# HITL participant removal and reassignment — tiledesk-server Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Let a flow remove the humans it invited, reassign automatically when an invited human leaves, and send the flow to its "No human available" block when nobody can replace them.

**Architecture:** The invite records the HITL context on the conversation (`attributes.hitl_*`). A new project-scoped remove endpoint releases humans on the flow's request. One new listener on the existing participant leave/update events handles every other removal path: it reassigns with the invite service's picker or clears the state and posts a system info message whose `action` jumps the bot to the fallback block; `botEvent` forwards that one message type to the bot.

**Tech Stack:** Node/Express, Mongoose 5.13, mocha + chai-http, local MongoDB (`tiledesk-test-mongo`, 27017) and Redis (`tiledesk-test-redis`, 6379).

**Spec:** `docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §11 (read §5.3–§5.5 for the v1 code this extends).

## Global Constraints

- Branch `feature/webhook-chatbot-hitl` (already checked out, default branch merged at `6ff4ac52`). Never commit to `master`, never push.
- All new REST APIs are project scoped: under `/:projectid/requests/...` in `routes/request.js` (mounted `app.js:621` with `hasRoleOrTypes('agent', ['bot','subscription'])`); every query filters on `id_project`; a conversation id of another project answers 404.
- Only conversations with `request.channel.name === ChannelConstants.WEBHOOK` are affected; closed conversations (`status === RequestConstants.CLOSED`, 1000) are never touched by the listener.
- Attribute names exactly: `start_type`, `hitl_waiting`, `hitl_invited`, `hitl_department_id`, `hitl_fallback` (`{ intent: '#<blockId>' }`), `hitl_left`.
- Remove scopes exactly `'invited' | 'all_humans'`, default `'invited'`.
- Fallback message text: `The invited human left and no replacement is available`; its `attributes.action` exactly `'#<blockId>{"flowError":"(Invite human) The invited human left and no replacement is available"}'` (no `'` inside the flowError text).
- The bot (`bot_*` participants) is never removed by the new endpoint; removing it through the generic DELETE stays allowed.
- Tests: `NODE_ENV=test`, run with `./node_modules/.bin/mocha <files> --timeout 60000 --exit` from the repo root; new test files use `mongoose.set('autoIndex', false)` only if they reproduce the known `phone` E11000 (TODO item 5).
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.

## Review Focus

1. A human who was never invited by the flow (e.g. an admin who joined) leaves → nothing happens (no pick, no fallback).
2. The flow's own `remove` call must never trigger a reassignment or fallback for the humans it removes.
3. The replacement must never be someone in `hitl_left` or already in the conversation, even when routing's selected operator is such a user (the v1 picker falls back to already-participants — the replacement picker must not).
4. Two invited humans removed back-to-back → at most one reassignment/fallback.
5. A request id of another project passed on this project's URL → 404, never a removal.

---

## File Structure

| File | Status | Responsibility |
|---|---|---|
| `services/webhookConversationService.js` | Modify | set `attributes.start_type = 'webhook'` at start |
| `services/participantInviteService.js` | Modify | record HITL context on invite; `pickReplacement` |
| `services/participantRemoveService.js` | Create | flow-requested removal (`remove`) |
| `services/hitlParticipantListener.js` | Create | leave/update listener: reassign or fallback |
| `routes/request.js` | Modify | `fallback_intent` validation; `POST /:requestid/participants/remove` |
| `event/botEvent.js` | Modify | forward the HITL fallback system message |
| `app.js` | Modify | `hitlParticipantListener.listen()` |
| `test/inviteParticipantsRoute.js`, `test/webhookConversationService.js` | Modify | invite context, start_type |
| `test/removeParticipantsRoute.js`, `test/hitlParticipantListener.js`, `test/botEventHitlFallback.js` | Create | new behaviour |

---

### Task 1: Record the HITL context on invite and the start type

**Files:**
- Modify: `services/webhookConversationService.js:92` (the `attributes` object)
- Modify: `services/participantInviteService.js` (`invite`, `markWaiting`)
- Modify: `routes/request.js:426-461` (invite route)
- Test: `test/inviteParticipantsRoute.js`, `test/webhookConversationService.js`

**Interfaces:**
- Produces: `participantInviteService.invite(id_project, request_id, { department_id, members, fallback_intent })` — same response shape as v1.
- Produces: `participantInviteService.markWaiting(request_id, id_project, { invitedIds, department_id, fallback_intent })` → populated request. It sets `workingStatus: 'pending'`, `attributes.hitl_waiting: true`, `attributes.hitl_department_id` (when non-null), `attributes.hitl_fallback: { intent: fallback_intent }` (only when `fallback_intent` is given), and `$addToSet: { 'attributes.hitl_invited': { $each: invitedIds } }`, in one `findOneAndUpdate` filtered by `request_id` + `id_project`.
- Produces: stored `attributes.hitl_department_id` is always the resolved department: explicit `department_id`, else `request.department`, else the project default. On the members path (no department pick) resolve it best-effort with `resolveDepartment` and store `null` on error — the members path must keep answering exactly as v1 (no new 422).

- [ ] **Step 1: Write the failing tests**

In `test/inviteParticipantsRoute.js` (reuse `setup`, `addAgent`, `invite`):

```js
it('records the invited humans, the department and the fallback block', async () => {
  const ctx = await setup({ ownerAvailable: false, beforeRequest: async (project, owner) => {
    const department = await departmentService.create('SRE pooled', project._id, 'pooled', owner._id);
    return { department, agents: [await addAgent(project, owner)] };
  }});
  const res = await invite(ctx, { department_id: ctx.department._id.toString(), fallback_intent: '#noone-id' });
  expect(res).to.have.status(200);
  const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
  expect(request.attributes.hitl_invited).to.deep.equal([res.body.invited[0].id_user]);
  expect(request.attributes.hitl_department_id).to.equal(ctx.department._id.toString());
  expect(request.attributes.hitl_fallback).to.deep.equal({ intent: '#noone-id' });
});

it('does not record HITL context when nobody is invited', async () => {
  const ctx = await setup({ ownerAvailable: false });
  const res = await invite(ctx, { fallback_intent: '#noone-id' });
  expect(res.body.invited).to.have.length(0);
  const request = await Request.findOne({ request_id: ctx.request.request_id }).lean().exec();
  expect(request.attributes && request.attributes.hitl_fallback).to.equal(undefined);
  expect(request.attributes && request.attributes.hitl_invited).to.equal(undefined);
});

it('stores the default department when members are invited by email', async () => {
  // owner invited by email: hitl_department_id = the project's default department id
});

it('rejects a non-string fallback_intent with 422', async () => {
  const ctx = await setup();
  const res = await invite(ctx, { fallback_intent: 42 });
  expect(res).to.have.status(422);
  expect(res.body.error).to.equal('fallback_intent must be a string');
});
```

The third test: invite `{ members: [ctx.ownerEmail] }` and assert `hitl_department_id` equals `(await Department.findOne({ id_project: ctx.project._id, default: true })).id` and `hitl_invited` contains the owner id.

In `test/webhookConversationService.js` add `it('marks the conversation start type as webhook')`: after a start, `request.attributes.start_type === 'webhook'`.

- [ ] **Step 2: Run to verify they fail**

Run: `./node_modules/.bin/mocha test/inviteParticipantsRoute.js test/webhookConversationService.js --timeout 60000 --exit`
Expected: the 5 new tests FAIL (undefined attributes, 200 instead of 422); existing tests pass.

- [ ] **Step 3: Implement**

`start_type: 'webhook'` in the starter's `attributes`; route validation `fallback_intent` (undefined/null allowed, otherwise must be a string → 422 `fallback_intent must be a string`) and pass it to `invite`; `invite` computes `invitedIds` (every returned invitee, including `already_participant`) and the resolved department id, then calls the new `markWaiting` signature.

- [ ] **Step 4: Run to verify they pass**

Same command. Expected: all tests in both files PASS.

- [ ] **Step 5: Commit**

```bash
git add services/webhookConversationService.js services/participantInviteService.js routes/request.js test/inviteParticipantsRoute.js test/webhookConversationService.js
git commit -m "feat(requests): record the HITL invite context and the conversation start type" -m "Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
```

---

### Task 2: Flow-requested removal endpoint

**Files:**
- Create: `services/participantRemoveService.js`
- Modify: `routes/request.js` (new route right after the invite route)
- Test: `test/removeParticipantsRoute.js` (copy the `addAgent` / `setup` helpers' approach from `test/inviteParticipantsRoute.js`; add a `remove(ctx, body, auth)` helper posting to `/:projectid/requests/:id/participants/remove`)

**Interfaces:**
- Consumes: Task 1 attributes; `participantInviteService.InviteError` (status + message), `participantInviteService.fullnameOf(id_user)`.
- Produces: `participantRemoveService.remove(id_project, request_id, { scope }) → Promise<{ request_id, removed: [{ id_user, fullname }] }>`; throws `InviteError` 404 `Request not found with id <id>`, 409 `Request <id> is closed`, 422 `Remove human requires a conversation started by a webhook`.
- Produces: route `POST /:requestid/participants/remove` — `scope` absent → `'invited'`; any other value than the two scopes → 422 `scope must be "invited" or "all_humans"`; errors answer `{ success: false, error }` with the service status, 500 `Error removing participants` otherwise.
- Behaviour order (spec §11.3.2): load and check the request; atomically `$unset` `attributes.hitl_waiting`, `attributes.hitl_invited`, `attributes.hitl_fallback` with `{ new: false }` to read the pre-clear `hitl_invited`; if the old `workingStatus` was `'pending'` set it to `'open'` and emit `request.workingStatus.update` + `request.update` with the populated request (same populate chain as `markWaiting`); then call `requestService.removeParticipantByRequestId(request_id, id_project, id_user, {})` for each target, sequentially. Targets: `invited` = pre-clear `hitl_invited` ∩ current participants; `all_humans` = current participants not starting with `bot_`.

- [ ] **Step 1: Write the failing tests** — `describe('RemoveParticipantsRoute')` with:
  - `removes only the humans invited by the flow and keeps the bot` — invite agent A (department with A), add agent B directly with `requestService.addParticipantByRequestId`; `remove({ scope: 'invited' })` → 200, `removed` = `[{ id_user: A, fullname: 'Agent Smith' }]`; participants = `['bot_<id>', B]`.
  - `removes every human with all_humans and keeps the bot` → participants = `['bot_<id>']`.
  - `clears the HITL context and reopens a pending conversation` → `hitl_waiting`, `hitl_invited`, `hitl_fallback` undefined, `workingStatus === 'open'`.
  - `answers 200 with an empty list when nobody is left to remove`.
  - `does not reassign the removed humans` — department has A and B, invite picks one with a fallback, remove it; `waitFor` 1500 ms then participants contain no agent and `hitl_left` is undefined (Task 3 must not act on it).
  - `rejects an unknown scope with 422` (`{ scope: 'everyone' }`).
  - `returns 404 for unknown and other-project requests, 409 for closed, 422 for non-webhook` — other project: owner of project A posts to `/A/requests/<request of B>/participants/remove` → 404.
- [ ] **Step 2: Run to verify they fail** — `./node_modules/.bin/mocha test/removeParticipantsRoute.js --timeout 60000 --exit` → 404 route not found for every test.
- [ ] **Step 3: Implement** the service and route per the Interfaces block.
- [ ] **Step 4: Run to verify they pass** — same command, all PASS; then `./node_modules/.bin/mocha test/inviteParticipantsRoute.js test/hitlWaitingReset.js --timeout 60000 --exit` still PASS.
- [ ] **Step 5: Commit** — `feat(requests): let the flow remove the humans it invited` (+ trailer), adding the service, route and test files.

---

### Task 3: Removal listener — reassignment and fallback

**Files:**
- Modify: `services/participantInviteService.js` (add `pickReplacement`)
- Create: `services/hitlParticipantListener.js`
- Modify: `event/botEvent.js:50-56` (system-message filter)
- Modify: `app.js` (after `BanUserNotifier.listen();` at `:229`)
- Test: `test/hitlParticipantListener.js`, `test/botEventHitlFallback.js`

**Interfaces:**
- Consumes: Task 1 attributes and `markWaiting`-populated requests; `participantInviteService.resolveDepartment`, `notifyInvited`, `fullnameOf`; `requestService.addParticipantByRequestId`; `messageService.send(sender, senderFullname, recipient, text, id_project, createdBy, attributes)`.
- Produces: `participantInviteService.pickReplacement(id_project, department, request, excluded: string[]) → Promise<string|null>` — first routing operator (`departmentService.getOperators(dept, project, true, undefined, { request })`) not in `excluded`, else one random `available_agents` entry not in `excluded` (`getRandomAvailableOperator`), else `null`. Never returns an excluded id (Review Focus 3).
- Produces: `hitlParticipantListener.listen()` — subscribes to `request.participants.leave` and `request.participants.update` (use the `.queue` variants when `requestEvent.queueEnabled`, as `pubmodules/routing-queue/listenerQueued.js:252-258` does).
- Produces: `hitlParticipantListener.onLeave({ member, request })` and `onUpdate({ request, removedParticipants, addedParticipants })`, both returning a Promise (exported for tests; handlers call them and log errors).
- Produces: exported `botEvent.shouldForwardSystemMessage(message) → boolean`, true for `/start` or `\start` text (v1) and for `message.attributes.hitl_fallback === true && message.attributes.action`; the `message.create` handler uses it.
- Algorithm (spec §11.4), ids compared as strings:
  - leave of a `bot_*` member → one `findOneAndUpdate` filtered by `request_id` + `id_project` unsetting `hitl_waiting`, `hitl_invited`, `hitl_fallback`, and setting `workingStatus: 'open'` when it was `'pending'`; emit the two events; no message.
  - leave of a human → step 1 is the atomic `findOneAndUpdate({ request_id, id_project, status: { $ne: 1000 }, 'channel.name': 'webhook', 'attributes.hitl_invited': member }, { $pull: { 'attributes.hitl_invited': member }, $addToSet: { 'attributes.hitl_left': member } }, { new: true })`; no document → return. Remaining `hitl_invited` non-empty or no `hitl_fallback` → return. Otherwise `pickReplacement(project, department(hitl_department_id), request, [...hitl_left, ...participants])`.
  - replacement found → `addParticipantByRequestId`, `$addToSet` it into `hitl_invited`, `notifyInvited`; do not touch `hitl_waiting` / `workingStatus`.
  - no replacement (or `hitl_department_id` null / department gone) → clear exactly as for the bot case, emit events, then `messageService.send('system', 'System', request_id, 'The invited human left and no replacement is available', id_project, 'system', { subtype: 'info', hitl_fallback: true, updateconversation: false, action: <Global Constraints action> })` built from `hitl_fallback.intent`; a send error is logged with `winston.error` and swallowed.
  - update event → for each added human `$addToSet` into `hitl_invited`; for each removed human run the leave algorithm but stop before the pick when the same update added any human.

- [ ] **Step 1: Write the failing tests**

`test/botEventHitlFallback.js` (pure, no server):
```js
const botEvent = require('../event/botEvent');
it('forwards /start and the HITL fallback system message only', () => {
  expect(botEvent.shouldForwardSystemMessage({ sender: 'system', text: '/start' })).to.equal(true);
  expect(botEvent.shouldForwardSystemMessage({ sender: 'system', text: 'x', attributes: { hitl_fallback: true, action: '#noone-id' } })).to.equal(true);
  expect(botEvent.shouldForwardSystemMessage({ sender: 'system', text: 'x', attributes: { action: '#noone-id' } })).to.equal(false);
  expect(botEvent.shouldForwardSystemMessage({ sender: 'system', text: 'x', attributes: { hitl_fallback: true } })).to.equal(false);
});
```

`test/hitlParticipantListener.js` (server + chai-http; setup like `test/inviteParticipantsRoute.js`, department created in `beforeRequest`; each scenario invites through the route with `fallback_intent: '#noone-id'`, then removes a participant with `DELETE /:projectid/requests/:id/participants/:userId` as the owner, then `waitFor` the DB state):
  - `invites another department agent when the invited human leaves` — pooled department with A and B (owner unavailable); invited X ∈ {A,B}; after DELETE X: participants contain the other agent, `hitl_invited` = [other], `hitl_left` = [X], `workingStatus === 'pending'`.
  - `never re-picks a human who already left` — A and B; invite picks X, delete X → Y invited; delete Y → no human participant, fallback message sent (see next).
  - `sends the fallback action when nobody can replace the human` — department with only A: after DELETE A, a `Message` with `recipient: request_id`, `sender: 'system'` and `attributes.action === '#noone-id{"flowError":"(Invite human) The invited human left and no replacement is available"}'` exists; `hitl_invited`/`hitl_fallback`/`hitl_waiting` undefined; `workingStatus === 'open'`.
  - `does nothing when a human the flow did not invite leaves` — owner added with `addParticipantByRequestId` directly, then deleted: no new participant, no message, `hitl_left` undefined.
  - `does nothing while another invited human remains` — invite `{ members: [A, B] }`, delete A: participants still B only (plus bot), no message.
  - `does not pick or fall back when an admin replaces the invited human` — `PUT /:projectid/requests/:id/participants` with `['bot_<id>', C]` after inviting A: participants = bot + C, `hitl_invited` includes C, no message.
  - `clears the HITL state when the bot is removed` — delete `bot_<id>`: `hitl_*` cleared, `workingStatus === 'open'`, no message.
  - `acts once when two invited humans are removed back to back` — invite `{ members: [A, B] }` with only A,B in the department, delete A and B without awaiting between them: exactly one fallback `Message` (count by `attributes.hitl_fallback`).
  - `ignores other channels` — a non-webhook request with `attributes.hitl_invited` seeded by `Request.updateOne`; delete that member: `hitl_left` undefined.

- [ ] **Step 2: Run to verify they fail** — `./node_modules/.bin/mocha test/botEventHitlFallback.js test/hitlParticipantListener.js --timeout 60000 --exit` → `shouldForwardSystemMessage is not a function` and `waitFor timeout` failures.
- [ ] **Step 3: Implement** `pickReplacement`, `shouldForwardSystemMessage` (keep the existing `/start` behaviour byte-for-byte), the listener module, and `hitlParticipantListener.listen();` in `app.js` right after `BanUserNotifier.listen();`.
- [ ] **Step 4: Run to verify they pass** — same command, all PASS; then the regression set `./node_modules/.bin/mocha test/webhookRoute.js test/webhookConversationRoute.js test/webhookConversationService.js test/inviteParticipantsRoute.js test/removeParticipantsRoute.js test/hitlWaitingReset.js --timeout 60000 --exit` all PASS.
- [ ] **Step 5: Commit** — `feat(requests): reassign or fall back when an invited human leaves a webhook conversation` (+ trailer).

---

### Task 4: Full-suite check and spec status

**Files:**
- Modify: `docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md` (only if new pre-existing problems are found)

- [ ] **Step 1:** Run `npm test > /tmp/server-full.log 2>&1`; record passing/failing counts.
- [ ] **Step 2:** On a temporary worktree of `origin/master` (`git worktree add /tmp/ts-master origin/master`, symlink `node_modules`), run the same and diff the failing test titles. Expected: no test fails only on the branch. Remove the worktree afterwards (`git worktree remove /tmp/ts-master`).
- [ ] **Step 3:** If a branch-only failure appears, stop and report it (it belongs to Tasks 1–3). Otherwise commit any TODO addition with `docs(todo): …` (+ trailer).

---

### Task 5: End-to-end acceptance (after the tybot, chat21-ionic and design-studio plans)

Run spec §11.8 "End-to-end" steps 1–5 on a local stack (this branch's server with the test MongoDB/Redis, tybot branch, chat21-ionic and design-studio branches), with a department containing agents A and B. Record each step's result in the SDD ledger; any failure goes back to the plan that owns the code. No commit unless a fix is needed.
