# HITL known-limit corrections — 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:** Stop tybot from logging the bot token on HTTP errors, make a block lock count only for the action that set it, and make Capture User Reply stop when it cannot lock.

**Architecture:** `tybotRoute/utils/HttpUtils.js` logs a safe error summary. `DirCaptureUserReply` and `DirReplyV2.lockUnlock` compare the locked action id with their own `_tdActionId` before taking the "reply" path.

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

**Spec:** `tiledesk-server/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` §12.3, §12.5.

## Global Constraints

- Repo `tiledesk-chatbot`, branch `feature/webhook-chatbot-hitl` (HEAD `7d3e1a67` at plan time). Never commit to `main`, never push.
- HttpUtils error log shape exactly: `{ message, code, status, url, data }` where `url` has no query string; never log `error`, `error.response`, `error.config` or `error.request`; the callback still receives the original error object.
- Lock ownership: "reply path" only when `currentLockedAction(requestId) === action._tdActionId`; a different locked action id → first pass (ask, then `lockIntent` + `lockAction` with this action's values, overwriting the old lock).
- Capture User Reply without a lock key: log an error and call `callback(true)`.
- Tests from `tybotRoute/`: `API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 ../node_modules/.bin/mocha <files> --timeout 60000 --exit`, one conversation file per mocha process when checking regressions (shared ports).
- Commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>` after a blank line.

## Review Focus

1. A Reply V2 with buttons answered by a button click (same action, lock held) still takes the reply path.
2. A Reply V2 no-input timeout still fires and unlocks.
3. An HTTP error whose response body itself contains the token (echoing server) — the body is logged as-is; acceptable, but the request headers must never be.
4. A non-axios error (e.g. thrown before the request) passed to the catch → summary still logged without crashing.
5. Two Captures in the same block (unusual) → the first stops the block; the second never runs until the reply.

---

### Task 1: HttpUtils logs a safe summary

**Files:**
- Modify: `tybotRoute/utils/HttpUtils.js` (`.catch` in `request`)
- Test: `tybotRoute/test/http_utils_test.js` (new)

**Interfaces:**
- Produces: `static errorSummary(error, url) → { message, code, status, url, data }` on `HttpUtils` (exported class unchanged otherwise); `url` stripped at `?`.

- [ ] **Step 1: Write the failing tests** — capture `winston` output by temporarily wrapping `require('../utils/winston').error` (restore in `afterEach`):
  - `does not log the Authorization header on a connection error` — `new HttpUtils().request({ url: 'http://127.0.0.1:1/x?token=q', method: 'GET', headers: { Authorization: 'JWT SECRET' }, json: null }, cb)` → cb gets an error; captured log text contains neither `SECRET` nor `token=q`.
  - `does not log the Authorization header on a timeout` — local `http` server that never answers, `timeout: 200` → same assertions; close the server in `finally`.
  - `logs the server response body on an HTTP error` — local server answering 422 `{"error":"nope"}` → captured text contains `nope` and `422`, not `SECRET`.
  - `errorSummary handles a non-axios error` — `HttpUtils.errorSummary(new Error('boom'), 'http://a/b?c=1')` → `{ message: 'boom', code: undefined, status: undefined, url: 'http://a/b', data: undefined }`.
- [ ] **Step 2: Run to verify they fail** — the two header tests fail (`SECRET` found), `errorSummary` is not a function.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Verify** — new file passes; regression, each alone: `test/conversation-invite_human_test.js`, `test/conversation-remove_human_test.js`, `test/conversation-web_requestv2_test.js`, `test/invite_human_members_test.js`, `test/remove_human_test.js`.
- [ ] **Step 5: Commit** — `fix(http): never log request headers on HTTP errors` (+ trailer); mark TODO item 6 in `tiledesk-server/docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md` "Done on tiledesk-chatbot feature/webhook-chatbot-hitl <sha>" and commit it in tiledesk-server (`docs(todo): …`, + trailer; only that file there).

---

### Task 2: A lock belongs to the action that set it; Capture without lock key stops

**Files:**
- Modify: `tybotRoute/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js` (`go`: the `if (!lockedAction)` branch and the missing-key path)
- Modify: `tybotRoute/tiledeskChatbotPlugs/directives/DirReplyV2.js` (`lockUnlock`)
- Test: `tybotRoute/test/conversation-lock_ownership_bot.js` + `conversation-lock_ownership_test.js` (new; harness copied from `test/conversation-lock_internal_jump_test.js`); unit test in `tybotRoute/test/capture_user_reply_test.js` (new) for the missing-key path.

**Interfaces:**
- Both directives: `const locked = await this.chatbot.currentLockedAction(this.requestId); const own = locked && locked === action._tdActionId;` → `own` = reply path (today's `else` branch); otherwise first pass.

- [ ] **Step 1: Write the failing tests**
  - Fixture: block `a` = reply `question A?` + `capture_user_reply` (`goToIntent: '#a_done-id'`, `assignResultTo: 'ans_a'`); block `a_done` = reply `A: {{ans_a}}`; block `b` = reply `question B?` + `capture_user_reply` (`goToIntent: '#b_done-id'`, `assignResultTo: 'ans_b'`); block `b_done` = reply `B: {{ans_b}}`; block `rv` = replyv2 `choose` with one action button `Go` → `#rv_done-id`; block `rv_done` = reply `rv done`.
  - `an internal jump to another question does not consume the waiting one` — send `/a` → `question A?`; send a `_tdinternal` `/b` → `question B?`; send user text `yes` → `B: yes`; no `A: …` message within 1500 ms.
  - `the same for a Reply V2 reached by an internal jump` — send `/a` → `question A?`; `_tdinternal` `/rv` → `choose`; user clicks `Go` (message with `attributes.action: '#rv_done-id'`) → `rv done`; no `A: …` message within 1500 ms.
  - `capture_user_reply_test.js`: a `DirCaptureUserReply` whose reply has no intent info (`reply: {}`) and no lock → callback called once with `true`, lock not set (stub `chatbot.lockIntent`/`lockAction` to fail the test if called).
- [ ] **Step 2: Run to verify they fail** — the internal-jump test prints `A: yes` (reply path taken by B), the unit test gets `undefined`.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Verify** — new files pass; regression, each file alone: `conversation-lock_internal_jump_test.js`, `conversation-capture_test.js`, `conversation-replyv2_button_match_test.js`, `conversation-replyv2_noinput_test.js`, `conversation-invite_human_test.js`, `conversation-remove_human_test.js` (Review Focus 1 and 2 are covered by the replyv2 suites).
- [ ] **Step 5: Commit** — `fix(directives): a block lock only counts for the action that set it` (+ trailer).

---

### Task 3: Suite comparison
- [ ] Full suite from `tybotRoute/` on the branch and on `origin/main` (temporary worktree under the session scratchpad, repo-root `node_modules` symlinked, removed afterwards; check `df -h` > 2 GB free first). Expected: no failing title only on the branch other than port-10002 cascades whose files pass alone.
