# HITL known-limit corrections — 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:** Replace a departed operator only while the flow is waiting, make participant removal atomic, clear the waiting state in one write, and drop a replacement the flow no longer wants.

**Architecture:** `services/hitlParticipantListener.js` gets the "only while waiting" branch, a race-free `clearWaiting`, and a post-add ownership check. `services/requestService.js` `removeParticipantByRequestId` switches from load-modify-save to atomic updates while emitting the same events.

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

**Spec:** `docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §12.1, §12.2, §12.5 (and §11.4 for the listener it amends).

## Global Constraints

- Branch `feature/webhook-chatbot-hitl` (HEAD `97362be4` at plan time). Never commit to `master`, never push.
- Only conversations with `channel.name === 'webhook'` are affected by the listener; closed requests (`status 1000`) are never changed by it.
- Every query filters on `request_id` + `id_project`.
- `removeParticipantByRequestId(request_id, id_project, member, options)` keeps its signature, its resolve value (the populated request) and its reject behaviour, and emits exactly the same events with the same payload shapes: `request.update` (request), `request.update.comment` (`{ comment: 'PARTICIPANT_REMOVE', request }`), `request.updated` (`{ comment: 'PARTICIPANT_REMOVE', request, patch: { member } }`), `request.participants.leave` (`{ member, request, actor, source, trackLeave }`). A member that is not a participant resolves with the populated request and emits nothing (today's "already not found" branch).
- Status rule unchanged: never touch a closed request; otherwise `ASSIGNED` when participants remain, `UNASSIGNED` when none.
- No MongoDB aggregation-pipeline updates (production MongoDB version is not pinned); use plain operators and conditional filters.
- Tests: `./node_modules/.bin/mocha <files> --timeout 60000 --exit` from the repo root.
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>` after a blank line.

## Review Focus

1. The last invited human leaves while the flow is NOT waiting → no replacement, no fallback message, `hitl_fallback` gone, `workingStatus` unchanged.
2. Two different members removed at the same instant → both removed, status correct, both leave events emitted.
3. A removal racing with a HITL write (e.g. `$addToSet` into `attributes.hitl_left`) → the HITL write survives.
4. A human removed twice concurrently → exactly one leave event.
5. `clearWaiting` on a conversation that is `open` → no `request.workingStatus.update` event.

---

### Task 1: Atomic `removeParticipantByRequestId`

**Files:**
- Modify: `services/requestService.js` (`removeParticipantByRequestId`)
- Test: `test/requestServiceRemoveParticipant.js` (new; setup pattern from `test/inviteParticipantsRoute.js`: `userService.signup`, `projectService.create`, `faqService.create`, `requestService.create` with `participants`)

**Interfaces:**
- Produces: same signature/behaviour as Global Constraints. Implementation: (1) resolve `project_user` of a human member first (`Project_user.findOne({ id_user: member, id_project })`, errors logged and ignored as today); (2) one `Request.findOneAndUpdate({ request_id, id_project, participants: member }, update, { new: true })` where `update` = `$pull: { participants: member, participantsAgents: member }` for a human (plus `$set: { ['attributes.abandoned_by_project_users.' + pu._id]: Date.now() }` when `pu` exists), or `$pull: { participants: member, participantsBots: <id without bot_> }` + `$set: { hasBot: false }` for a `bot_` member; no document → the "already not found" branch (load + populate + resolve, no events); (3) unless `status === CLOSED`, `Request.updateOne({ request_id, id_project, status: { $ne: 1000 }, participants: { $size: 0 } }, { $set: { status: UNASSIGNED } })` or, when participants remain, the same with `'participants.0': { $exists: true }` → `ASSIGNED`; (4) reload + populate (same populate chain as today) and emit the four events.

- [ ] **Step 1: Write the failing tests**
  - `removes both members when two removals run at the same time` — request with bot + agents A and B; `Promise.all([remove(A), remove(B)])` → DB `participants` = `['bot_<id>']`, `participantsAgents` = `[]`, and two `request.participants.leave` events (one per member, captured with a temporary `requestEvent.on` listener removed in `finally`).
  - `keeps a concurrent HITL write` — start `remove(A)` and, without awaiting, `Request.updateOne({ request_id }, { $addToSet: { 'attributes.hitl_left': 'x' } })`; after both settle `attributes.hitl_left` contains `'x'` and `attributes.abandoned_by_project_users` has A's project_user id.
  - `emits one leave event when the same member is removed twice at once` → exactly one `request.participants.leave`.
  - `sets unassigned when the last participant leaves and never touches a closed request` — remove the only participant → `status === 100`; on a request set to `status 1000` first, remove a participant → still `1000`.
  - `resolves without events for a member that is not a participant`.
- [ ] **Step 2: Run to verify they fail** — `./node_modules/.bin/mocha test/requestServiceRemoveParticipant.js --timeout 60000 --exit`: the concurrency tests fail (one member left behind / `hitl_left` lost / two events).
- [ ] **Step 3: Implement** per Interfaces.
- [ ] **Step 4: Verify** — the new file passes; then `./node_modules/.bin/mocha test/requestService.js test/requestRoute.js test/removeParticipantsRoute.js test/hitlParticipantListener.js test/inviteParticipantsRoute.js --timeout 60000 --exit` — record counts; any failure must be shown to also fail on HEAD before this task (`git stash` the two files, run the same failing file, `git stash pop`), otherwise fix it.
- [ ] **Step 5: Commit** — `fix(requests): remove participants atomically` (+ trailer). Also mark the TODO entry "Concurrent participant removals can lose one removal" in `docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md` with "Done on feature/webhook-chatbot-hitl <sha>" in the same commit.

---

### Task 2: Listener — replace only while waiting; one-write clear; drop unwanted replacement

**Files:**
- Modify: `services/hitlParticipantListener.js` (`handleLeave`, `clearWaiting`)
- Test: `test/hitlParticipantListener.js`

**Interfaces:**
- Consumes: Task 1's atomic removal (unchanged API).
- `handleLeave(member, request, { pick })`: after step 1 (atomic pull/addToSet, unchanged), read `hitl_waiting` from the step-1 document (`updated.attributes.hitl_waiting === true`). Not waiting → if `hitl_invited` is now empty, `updateOne({ request_id, id_project, 'attributes.hitl_invited': { $size: 0 } }, { $unset: { 'attributes.hitl_fallback': '' } })`, emit `request.update` with the populated request, and return (no pick, no message, no status change). Waiting → current behaviour.
- `clearWaiting(request, extraFilter) → Promise<boolean>`: attempt A = `findOneAndUpdate(filter + { workingStatus: 'pending' }, { $unset: <3 fields>, $set: { workingStatus: 'open' } })`; if A matched → emit `request.workingStatus.update` and `request.update`, return true. Else attempt B = `findOneAndUpdate(filter, { $unset: <3 fields> })`; matched → emit only `request.update`, return true; else false. (`filter` = today's `HITL_EXISTS` + base filter + `extraFilter`.)
- After a successful `addParticipantByRequestId(replacement)`: `Request.exists({ request_id, id_project, 'attributes.hitl_invited': replacement })`; false → `requestService.removeParticipantByRequestId(request_id, id_project, replacement, {})`, log at verbose, return (no notify).

- [ ] **Step 1: Write the failing tests** (owner unavailable, departments created before the request, as in the existing file):
  - `releases instead of replacing when the flow is not waiting` — pooled A,B; invite with `fallback_intent`; clear `hitl_waiting` and set `workingStatus: 'open'` with `Request.updateOne` (simulates the human's answer); DELETE the invited one → after 1500 ms: no other agent added, no `Message` with `attributes.hitl_fallback`, `hitl_fallback` undefined, `hitl_left` = [leaver], `workingStatus === 'open'`.
  - `keeps replacing while the flow waits` — same setup without clearing `hitl_waiting` → the other agent is invited (regression of the §11 behaviour).
  - `emits no workingStatus event when clearing an open conversation` — only A, invite without fallback, then set `workingStatus: 'open'` keeping `hitl_waiting: true`; capture `request.workingStatus.update` events for this request; DELETE A → HITL fields cleared, zero captured events.
  - `removes a replacement the flow no longer wants` — pooled A,B; stub `requestService.addParticipantByRequestId` so that, for the replacement, it first runs `Request.updateOne({ request_id }, { $unset: { 'attributes.hitl_invited': '' } })` then calls the original (restore in `finally`); DELETE the invited one → after `waitFor`, the replacement is not a participant.
- [ ] **Step 2: Run to verify they fail** — `./node_modules/.bin/mocha test/hitlParticipantListener.js --timeout 60000 --exit` → the three new behaviours fail; the regression test passes.
- [ ] **Step 3: Implement** per Interfaces.
- [ ] **Step 4: Verify** — `./node_modules/.bin/mocha test/hitlParticipantListener.js test/removeParticipantsRoute.js test/inviteParticipantsRoute.js test/hitlWaitingReset.js test/webhookConversationRoute.js test/webhookConversationService.js test/botEventHitlFallback.js test/requestServiceRemoveParticipant.js --timeout 60000 --exit` → all pass.
- [ ] **Step 5: Commit** — `fix(requests): replace departed HITL humans only while the flow waits` (+ trailer).

---

### Task 3: Full-suite comparison

- [ ] **Step 1:** `npm test` on the branch head and on `origin/master` (temporary worktree under the session scratchpad with `node_modules` symlinked; run sequentially; remove the worktree and `git worktree prune` afterwards). Disk: the worktree without `node_modules` is ~130 MB — check `df -h` shows > 2 GB free first.
- [ ] **Step 2:** Compare failing test titles. Expected: none failing only on the branch; a branch-only title is re-run alone on both sides and reported if it is a real regression (no fix in this task).
