# HITL participant removal and reassignment — tybot (tiledesk-chatbot) 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:** `invite_human` tells the server where to resume when nobody can replace a departed human, a new `remove_human` action releases humans, and replies to a waiting question are no longer swallowed by the block lock (TODO item 3).

**Architecture:** `DirInviteHuman` adds `fallback_intent` to its invite body. `DirRemoveHuman` mirrors `DirInviteHuman` (same HTTP, token and error-summary rules) against the server's project-scoped remove endpoint. The server's fallback jump reuses the engine's existing explicit-action path (no engine change). The lock fix backports two small parts of `main_pre`: internal jumps bypass the locked intent, and Capture User Reply stops the flow after locking.

**Tech Stack:** Node, mocha (from `tybotRoute/` with `../node_modules/.bin/mocha`), in-process tilebot on 10001 + mock Tiledesk API on 10002, Redis `tiledesk-test-redis` on 6379.

**Spec:** `tiledesk-server/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §11.5 (and §6 for the v1 `invite_human`); TODO item 3 in `tiledesk-server/docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md`.

## Global Constraints

- Repo `tiledesk-chatbot`, branch `feature/webhook-chatbot-hitl` (already checked out, `origin/main` 2.2.0 merged at `4bdccbb8`). Never commit to `main`, never push.
- Directive name exactly `remove_human` (`Directives.REMOVE_HUMAN`); action fields `scope` (`'invited' | 'all_humans'`, default `'invited'`), `trueIntent`, `falseIntent`, `trueIntentAttributes`, `falseIntentAttributes`.
- Variables exactly `removed_humans` (array of `{ id_user, fullname }`) and `removed_humans_count`.
- flowError texts exactly: `(Remove human) An error occurred: <message>` and `(Remove human) requires a conversation`; the server's fallback text `(Invite human) The invited human left and no replacement is available`.
- Endpoint: `POST ${API_ENDPOINT}/${projectId}/requests/${requestId}/participants/remove`, JSON body `{ scope }`, header `Authorization: JWT <bot token>` (via `DirInviteHuman.fixToken`), timeout `DirInviteHuman.INVITE_TIMEOUT_MS` (30000).
- Never log a raw HTTP error: log `JSON.stringify(DirInviteHuman.errorSummary(err))` only.
- Every jump ends with `callback(true)`; the callback runs exactly once (same guard as `DirInviteHuman.execute`).
- Run tests from `tybotRoute/` with `API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 ../node_modules/.bin/mocha <files> --timeout 60000 --exit`. Never `npx`, never `npm install`.
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.

## Review Focus

1. A paused Reply V2 must still accept a button click after the lock fix (existing replyv2 suites stay green).
2. The server's fallback message arrives from sender `system` with subtype `info`: it must jump to the fallback block, not be treated as an answer to the paused question.
3. `remove_human` in an automation run (request id not starting with `support-group-`) must not call the server.
4. `remove_human` with no branches configured must let the block continue (callback without `true`), not stop the flow silently.
5. The Capture User Reply change must not break blocks where it is the last action (`test/conversation-capture_test.js` stays green).

---

## File Structure

| File | Status | Responsibility |
|---|---|---|
| `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js` | Modify | send `fallback_intent` |
| `tybotRoute/tiledeskChatbotPlugs/directives/DirRemoveHuman.js` | Create | `remove_human` directive |
| `tybotRoute/tiledeskChatbotPlugs/directives/Directives.js`, `tybotRoute/tiledeskChatbotPlugs/DirectivesChatbotPlug.js` | Modify | register `remove_human` |
| `tybotRoute/engine/TiledeskChatbot.js` | Modify | internal jumps bypass the locked intent |
| `tybotRoute/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js` | Modify | stop after locking; guarded lock key |
| `tybotRoute/test/conversation-invite_human_test.js` | Modify | fallback body + fallback jump |
| `tybotRoute/test/remove_human_test.js`, `conversation-remove_human_bot.js`, `conversation-remove_human_test.js` | Create | remove tests |
| `tybotRoute/test/conversation-lock_internal_jump_bot.js`, `conversation-lock_internal_jump_test.js` | Create | lock fix tests |

---

### Task 1: `invite_human` sends its fallback block; the fallback jump lands there

**Files:**
- Modify: `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js:88` (the `invite({...})` call)
- Test: `tybotRoute/test/conversation-invite_human_test.js`

**Interfaces:**
- Produces: invite body `{ department_id, members, fallback_intent }` where `fallback_intent = action.falseIntent` when it is a non-empty string, omitted otherwise.

- [ ] **Step 1: Write the failing tests**
  - In the first test (`invites the resolved members and continues in the invited block`), add `assert.strictEqual(req.body.fallback_intent, '#noone-id');` next to the existing body assertions.
  - New test `jumps to the "no human available" block when the server sends the fallback action`: invite answers one invited human; when the `invited 1: restart?` message arrives, send
    `userMessage(REQUEST_ID, 'The invited human left and no replacement is available', { sender: 'system', senderFullname: 'System', attributes: { subtype: 'info', hitl_fallback: true, action: '#noone-id{"flowError":"(Invite human) The invited human left and no replacement is available"}' } })`
    (extend the file's `userMessage` helper to accept `attributes` if it does not already), and expect the next bot message to be `no human available|(Invite human) The invited human left and no replacement is available`.
- [ ] **Step 2: Run to verify** — `../node_modules/.bin/mocha test/conversation-invite_human_test.js …`: the first test FAILS (`undefined !== '#noone-id'`). The jump test is expected to PASS already (engine explicit-action path); if it FAILS, stop and report the output — the spec assumes no engine change.
- [ ] **Step 3: Implement** the body field.
- [ ] **Step 4: Run to verify they pass** — same file, all PASS; plus `test/invite_human_members_test.js` PASS.
- [ ] **Step 5: Commit** — `feat(invite_human): send the no-human block as the server fallback` (+ trailer).

---

### Task 2: `remove_human` directive

**Files:**
- Create: `tybotRoute/tiledeskChatbotPlugs/directives/DirRemoveHuman.js`
- Modify: `Directives.js` (`static REMOVE_HUMAN = "remove_human";` next to `INVITE_HUMAN`), `DirectivesChatbotPlug.js` (require + `[Directives.REMOVE_HUMAN]: DirRemoveHuman` next to `:315`)
- Test: `tybotRoute/test/remove_human_test.js` (unit), `conversation-remove_human_bot.js` + `conversation-remove_human_test.js` (copy the harness of `conversation-invite_human_test.js`: tilebot on 10001, mock API on 10002 with a `remove` handler on `POST /:projectId/requests/:requestId/participants/remove`)

**Interfaces:**
- Consumes: `DirInviteHuman.fixToken`, `DirInviteHuman.errorSummary`, `DirInviteHuman.INVITE_TIMEOUT_MS`; the same constructor context fields as `DirInviteHuman` (projectId, requestId, token, API_ENDPOINT, tdcache, chatbot, logger, intentDir).
- Produces: `class DirRemoveHuman { constructor(context); execute(directive, callback); go(action, callback); remove(body) → Promise<{ request_id, removed }> ; static normalizeScope(scope) → 'invited' | 'all_humans' }` — `normalizeScope` returns `'all_humans'` only for exactly that string, `'invited'` otherwise.
- Behaviour: automation request (`requestId` not starting with `support-group-`) → flowError `(Remove human) requires a conversation`, jump `falseIntent` (or `callback()` when absent). Success → set `removed_humans` and `removed_humans_count`, jump `trueIntent` (or `callback()` when absent). HTTP error → flowError `(Remove human) An error occurred: ` + `errorSummary(err).message`, jump `falseIntent` (or `callback()`).

- [ ] **Step 1: Write the failing tests**
  - `remove_human_test.js`: `normalizeScope(undefined) === 'invited'`, `normalizeScope('all_humans') === 'all_humans'`, `normalizeScope('ALL') === 'invited'`; a directive with `remove` stubbed to resolve `{ removed: [{ id_user: 'u1', fullname: 'A' }] }` sets `removed_humans_count` 1 and jumps once to `#removed…`; with `remove` rejecting `{ message: 'x', config: { headers: { Authorization: 'JWT SECRET' } }, response: { status: 422, data: { error: 'Remove human requires a conversation started by a webhook' } } }` the logged text never contains `SECRET` and `flowError === '(Remove human) An error occurred: Remove human requires a conversation started by a webhook'`; with no branches the callback is called once with `undefined`.
  - Fixture blocks: `remove` (action `remove_human`, `scope: 'all_humans'`, `trueIntent: '#removed-id'`, `falseIntent: '#rmerror-id'`), `removed` (reply `removed {{removed_humans_count}}`), `rmerror` (reply `remove error|{{flowError}}`).
  - Conversation tests: `removes the humans and continues in the removed block` (mock asserts `req.body.scope === 'all_humans'` and the `Authorization` header starts with `JWT `, answers two removed → `removed 2`); `goes to the error block with the server reason` (422 → `remove error|(Remove human) An error occurred: <server error>`); `does not call the server for automation runs` (request id `automation-request-…` → `remove error|(Remove human) requires a conversation`, mock `remove` handler never hit).
- [ ] **Step 2: Run to verify they fail** — module not found / no directive.
- [ ] **Step 3: Implement and register.**
- [ ] **Step 4: Run to verify they pass** — the three new files PASS; `test/conversation-invite_human_test.js` and `test/invite_human_members_test.js` PASS.
- [ ] **Step 5: Commit** — `feat(directives): add remove_human to release humans from the conversation` (+ trailer).

---

### Task 3: Replies are not swallowed by the block lock (TODO item 3)

**Files:**
- Modify: `tybotRoute/engine/TiledeskChatbot.js` (the `if (locked_intent) {` check after `currentLockedIntent`)
- Modify: `tybotRoute/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js`
- Test: `tybotRoute/test/conversation-lock_internal_jump_bot.js`, `conversation-lock_internal_jump_test.js` (capture-test harness)

**Interfaces:**
- Produces: `TiledeskChatbot` treats the locked intent only for messages whose `sender !== '_tdinternal'`.
- Produces: `DirCaptureUserReply` — after locking it calls `callback(true)` (stops the block); `execute` passes the stop flag through (`this.go(action, (stop) => callback(stop))`); the lock key comes from a private resolver trying, in order, `reply.attributes.intent_info.intent_id` (as `'#' + id`), `reply.attributes.intent_info.intent_name`, `reply.intent_id` (as `'#' + id`), `reply.intent_display_name`; no key → log an error and `callback()` without locking. Port these from `origin/main_pre:tybotRoute/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js` (only these parts; leave the rest of `main_pre` out).

- [ ] **Step 1: Write the failing tests** — fixture:
  - `ask` block: reply `question?`, then `capture_user_reply` (`goToIntent: '#answered-id'`, `assignResultTo: 'answer'`), then reply `must not run`.
  - `answered` block: reply `answer: {{answer}}`.
  - `locked_jump` block: reply `waiting`, `capture_user_reply` (`goToIntent: '#answered-id'`, `assignResultTo: 'answer'`), then an `intent` action to `#other-id`.
  - `other` block: reply `other ran`.
  Tests: `stops the block after Capture User Reply` — send `/ask`: messages seen are `question?` then, after sending `yes` as the user, `answer: yes`; `must not run` never arrives. `does not treat an internal jump as the reply` — send `/locked_jump`: `waiting` then no `other ran` before the user replies (Capture stops the block), and after the user sends `ok` → `answer: ok`. Add a direct engine test: with the conversation locked on `ask`, a `_tdinternal` message `/other` produces `other ran` and leaves the lock in place (the next user text `yes` → `answer: yes`).
- [ ] **Step 2: Run to verify they fail** — `must not run` arrives / `/other` is captured as the answer.
- [ ] **Step 3: Implement** both changes.
- [ ] **Step 4: Run to verify they pass** — new file PASS; regression: `test/conversation-capture_test.js test/conversation-locked-intent-test.js test/conversation-replyv2_button_match_test.js test/conversation-replyv2_noinput_test.js test/conversation-invite_human_test.js test/conversation-remove_human_test.js` all PASS.
- [ ] **Step 5: Commit** — `fix(engine): internal jumps skip the locked intent; Capture User Reply stops the block` (+ trailer); then update TODO item 3 in `tiledesk-server/docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md` with "Done on tiledesk-chatbot feature/webhook-chatbot-hitl <sha>" and commit it in tiledesk-server with `docs(todo): …` (+ trailer).

---

### Task 4: Suite comparison

- [ ] **Step 1:** Run the whole suite from `tybotRoute/` on the branch head and on `origin/main` (temporary worktree with `node_modules` symlinked, removed afterwards); compare failing test titles.
- [ ] **Step 2:** Expected: no title fails only on the branch, apart from tests failing on the known port-10002 `EADDRINUSE` cascade that pass when their file is run alone (verify each such file alone). Report the counts.
