# Flow start points — 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:** Conversation webhooks carry `start_points`; a webhook call starts the flow at the webhook start box, with no change for widget starts and automation webhooks.

**Architecture:** `start_points` lives on the existing per-chatbot webhook record, managed by two new admin routes and a small service. The public conversation path looks up the `webhook` start point, resolves the department from the chatbot, and sends the system `/start` with `attributes.action = '#<block_id>'`. A `faq.delete` listener removes start points whose box is deleted.

**Tech Stack:** Node/Express, Mongoose, mocha + chai-http (test MongoDB + Redis).

**Spec:** `docs/superpowers/specs/2026-09-30-flow-start-points-design.md` (§4, §8, §9).

## Global Constraints

- Branch `feature/webhook-chatbot-hitl` (checked out). Never push, never commit to master. Commit messages end with a blank line + `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
- Start point types: enum exactly `['webhook']` in this plan (`'web'` is implicit, never stored). At most one entry per type, enforced by the service (400), not by an index.
- Start point shape: `{ type, block_id, enabled (default true), mapping: { source_name } }`.
- Webhook stays unique per chatbot; the automation path (no `mode`) is untouched: `block_id`, `webhookService.run`, `/block` sync/async.
- Remove `department_id` and `source_name` from the conversation webhook (model, validator, routes); no migration.
- Start text stays `/start`; the box is selected with `attributes.action = '#' + block_id`.
- Department of a webhook conversation: the project's default department if its `id_bot` is this chatbot; else the oldest department (by `createdAt`) whose `id_bot` is this chatbot; else the project default department.
- Error bodies `{ success: false, error: <message> }`; 422 message for a missing/disabled start point exactly `"Webhook start is not enabled"`.
- All new routes project-scoped under the existing `routes/webhooks.js` mount (admin role).
- Tests: `NODE_ENV=test` DB (`tiledesk-test`); run with `./node_modules/.bin/mocha <files> --timeout 60000 --exit`. If a local RabbitMQ that rejects guest is running on 5672 (container `td-e2e-rabbitmq`), stop it for the run and restart it after.

## Review Focus

1. A chatbot whose webhook has no `start_points` yet but `mode: 'conversation'` (created by the old toggle on this branch) → calls answer 422 "Webhook start is not enabled", never 500.
2. `PUT …/start_points/webhook` on a chatbot with an automation webhook (no mode) without `confirm` → 409, and the automation webhook still runs its block afterwards.
3. `block_id` of another chatbot, or a random string → 404, nothing saved.
4. Deleting the start box by `intentId…` and by `_id` (both DELETE forms in `routes/faq.js:492-535`) → start point removed.
5. Widget `/start` launch of the same chatbot → unchanged (no `attributes.action`, no `start_type`).

---

### Task 1: start_points model, service and admin API

**Files:**
- Modify: `models/webhook.js` (add `start_points` subdocument array; remove `department_id`, `source_name`)
- Create: `services/startPointService.js`
- Modify: `services/webhookSettingsValidator.js` (drop department_id/source_name handling)
- Modify: `routes/webhooks.js` (two routes; GET already returns the document)
- Test: `test/startPointsRoute.js`; update existing tests that use `department_id`/`source_name` (`test/webhookRoute.js`, `test/webhookConversationRoute.js`, `test/webhookConversationService.js`, `test/webhookConversationTestUtils.js`)

**Interfaces:**
- Produces `startPointService.TYPES = ['webhook']`.
- Produces `startPointService.upsert(id_project, chatbot, type, body) → Promise<webhook>`; body `{ block_id, enabled?, mapping?: { source_name? }, confirm? }`. Throws `StartPointError(status, message)` for 400/404/409.
- Produces `startPointService.remove(id_project, chatbot_id, type) → Promise<webhook>` (404 when absent).
- Produces `startPointService.find(webhook, type) → startPoint | undefined`.
- Routes: `PUT /:projectid/webhooks/:chatbot_id/start_points/:type`, `DELETE /:projectid/webhooks/:chatbot_id/start_points/:type`, both answer the updated webhook.

- [ ] **Step 1: Write the failing tests** in `test/startPointsRoute.js`:
  - PUT on a chatbot (subtype `chatbot`) without webhook → 200; webhook created with `mode: 'conversation'`, `start_points: [{type:'webhook', block_id:<start box intent_id>, enabled:true, mapping:{source_name:'Grafana'}}]`.
  - PUT again with `enabled:false` → same single entry updated (length 1).
  - PUT `type: 'scheduled'` → 400; chatbot subtype `webhook` → 400; `block_id` of another chatbot → 404; `block_id: 'nope'` → 404.
  - Existing webhook without mode: PUT → 409, webhook unchanged; PUT with `confirm: true` → 200, `mode: 'conversation'`, automation `block_id` kept.
  - DELETE → 200, `start_points` empty; DELETE again → 404.
  - Agent-role user → 403 (admin only); other project's chatbot → 404.
- [ ] **Step 2: Run to verify they fail** — `./node_modules/.bin/mocha test/startPointsRoute.js --timeout 60000 --exit` → 404s on the new routes.
- [ ] **Step 3: Implement** model field, `startPointService`, routes; remove `department_id`/`source_name` from model and validator, and adapt the existing tests that set them (drop those assertions; department cases move to Task 2).
- [ ] **Step 4: Run** `./node_modules/.bin/mocha test/startPointsRoute.js test/webhookRoute.js test/webhookConversationRoute.js test/webhookConversationService.js --timeout 60000 --exit` → all pass.
- [ ] **Step 5: Commit** — `feat(webhooks): start points on conversation webhooks`.

### Task 2: webhook call starts at the start box

**Files:**
- Modify: `routes/webhook.js` (`router.all('/:webhook_id')` ~311 and `/:webhook_id/dev` ~368: after `checkEnabledAndRateLimit`, conversation mode requires the enabled `webhook` start point)
- Modify: `services/webhookConversationService.js` (`start()`: department rule, lead name from mapping, `/start` with action)
- Test: `test/webhookConversationRoute.js`, `test/webhookConversationService.js`

**Interfaces:**
- Consumes Task 1 `startPointService.find(webhook, 'webhook')`.
- Produces `webhookConversationService.resolveChatbotDepartment(id_project, chatbot_id) → Promise<department>` (rule in Global Constraints).
- `start(webhook, chatbot, payload, options)` now reads `startPoint = find(webhook,'webhook')`; lead fullname `startPoint.mapping.source_name || webhook.name || 'Webhook'`; sends `messageService.send('system','Bot',request_id,'/start',id_project,null,{subtype:'info',updateconversation:false, action:'#'+startPoint.block_id})`.

- [ ] **Step 1: Write the failing tests:**
  - Conversation webhook with enabled start point → 202; the system message stored for the request has text `/start` and `attributes.action === '#<block_id>'`; request `attributes.start_type === 'webhook'`.
  - Lead fullname = `mapping.source_name`; empty mapping → webhook name.
  - Department: bot attached to a non-default department → that department; attached to the default department and another → default; not attached → project default.
  - `mode:'conversation'` with no start points → 422 `"Webhook start is not enabled"`; start point `enabled:false` → same 422; `/dev` preloaded run with disabled start point → 422.
  - Automation webhook (no mode) → still calls tybot `/block` (existing webhookRoute tests stay green).
- [ ] **Step 2: Run to verify they fail** (`test/webhookConversationRoute.js test/webhookConversationService.js`).
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** the two files plus `test/webhookRoute.js test/inviteParticipantsRoute.js test/hitlParticipantListener.js` → all pass.
- [ ] **Step 5: Commit** — `feat(webhook): conversation webhooks start at the webhook start box`.

### Task 3: box deletion cleanup and regression

**Files:**
- Create: `services/startPointCleanupListener.js` (listens to `faqBotEvent` `faq.delete`; `$pull` start points whose `block_id` equals the deleted faq's `intent_id` for that chatbot)
- Modify: `app.js` (wire the listener next to the HITL listener)
- Test: `test/startPointsCleanup.js`; `test/startPointsRegression.js`

**Interfaces:**
- Consumes the faq document emitted by `routes/faq.js` (`id_faq_kb`, `intent_id`, `id_project`).

- [ ] **Step 1: Write the failing tests:**
  - `startPointsCleanup`: DELETE the box via `/:projectid/faq/intentId<intent_id>?id_faq_kb=<bot>` → start point removed; via `/:projectid/faq/<_id>` → removed; deleting another block → start point kept.
  - `startPointsRegression`: automation webhook sync (`async:false`) answers the stubbed tybot response; async → 200; a chatbot published via `PUT /:projectid/faq_kb/:id/publish` keeps its start point `block_id` resolvable in the published copy (faq with same `intent_id` exists under the published bot); widget-like start (`rulesTrigger` bot launch) sends `/start` without `attributes.action`.
- [ ] **Step 2: Run to verify** the cleanup tests fail and the regression tests pass on the current code (they pin behaviour).
- [ ] **Step 3: Implement** the listener and wiring.
- [ ] **Step 4: Run** `./node_modules/.bin/mocha test/startPointsCleanup.js test/startPointsRegression.js test/startPointsRoute.js test/webhookConversationRoute.js test/webhookRoute.js --timeout 60000 --exit` → all pass.
- [ ] **Step 5: Commit** — `feat(webhooks): remove a start point when its box is deleted`.
