# Scheduled start point — 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:** A `scheduled` start point whose draft is edited through the start point API, made live in DolphinScheduler at publish, and run through a token-protected endpoint that opens a conversation from the Scheduled box.

**Architecture:** Pure rules (`scheduledStartRules.js`: validation, Quartz cron, summary) feed `startPointService` for the draft; `dolphinSchedulerClient.js` + `scheduledStartService.js` own the DolphinScheduler workflow/schedule; a `faqbot.publish` listener syncs draft → live; `POST /webhook/scheduled-start` starts the conversation through a generalized `webhookConversationService.start`.

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

**Spec:** `docs/superpowers/specs/2026-10-01-scheduled-start-point-design.md`

## Global Constraints

- Branch `feature/scheduled-start-point` (checked out, created from `feature/webhook-chatbot-hitl`). Never push. Commits end with a blank line + `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
- Start point types become exactly `['webhook', 'scheduled']`; `'web'` stays implicit.
- Scheduled config is the **draft**; production changes only at publish (spec §7). Deleting the chatbot destroys the schedule immediately.
- **Ruling (storage of live):** the live snapshot is stored on the webhook record as top-level `scheduled_live` (not inside the start point entry), so removing the draft entry (DELETE route or the existing `faq.delete` cleanup `$pull`) keeps the live ids the next publish needs to destroy the schedule. Same fields as spec §4 `live`: `{ enabled, block_id, mapping, schedule, published_bot_id, published_at, workflow_code, schedule_id, error }`. Never accepted from clients.
- Feature enabled only when `SCHEDULER_BASEURL`, `SCHEDULER_TOKEN`, `SCHEDULER_PROJECT` and `SCHEDULED_START_TOKEN` are all set; otherwise every `scheduled` route answers 503 `"Scheduled starts are not available on this installation"`. No default token.
- Workflow name `auto-start-<chatbot_id>`; HTTP task `POST {API_URL}/webhook/scheduled-start`, body params `id_project`, `chatbot_id`, header `x-auth-token: ${token}` (workflow global params), timeouts 60000, no retries. Schedule: `timezoneId`, `startTime` now, `endTime` `2099-12-31 23:59:59`, `failureStrategy: CONTINUE`, `warningType: NONE`, `processInstancePriority: MEDIUM`. DolphinScheduler 3.2.2 REST, header `token`, same endpoints as `services/aiReindexService.js` / jobworker `ReindexScheduler.js`.
- Validation values (400): interval minutes ∈ {5,10,15,20,30}, hours 1..12; `time` `^([01]\d|2[0-3]):[0-5]\d$`; weekly ≥ 1 of `mon..sun`; monthly `day_of_month` 1..28 or `'last'`; IANA timezone; payload flat, keys `^[A-Za-z_][A-Za-z0-9_]*$`, values string|finite number|boolean, ≤ 50 keys, ≤ 8192 bytes serialized.
- Cron mapping (spec §6): minutes N `0 0/N * * * ? *`; hours N `0 0 0/N * * ? *`; daily `0 MM HH * * ? *`; weekly `0 MM HH ? * MON,WED,FRI *` (weekday order mon..sun); monthly `0 MM HH D * ? *`, last `0 MM HH L * ? *`.
- Run endpoint statuses: 401 bad/missing token, 503 not configured, 410 + workflow offline when chatbot missing or `trashed`, webhook/start point/`scheduled_live` missing or `scheduled_live.enabled` false; 429 rate limit; 202 `{ success: true, request_id }`.
- Scheduled conversation: lead id `scheduled_<chatbot_id>`, fullname `scheduled_live.mapping.source_name || chatbot.name || 'Scheduled'`; channel `webhook`; request attributes `{ start_type: 'scheduled', payload, scheduled_at }`; `/start` with `attributes.action = '#' + block_id`; not draft.
- Invite/Remove human 422 messages become `"Invite human requires a conversation started by a webhook or a schedule"` / `"Remove human requires a conversation started by a webhook or a schedule"`.
- Tests: `NODE_ENV=test ./node_modules/.bin/mocha <files> --timeout 60000 --exit` with test MongoDB/Redis up (docker `tiledesk-test-mongo`, `tiledesk-test-redis`); stop `td-e2e-rabbitmq` if running. nock all DolphinScheduler traffic; no real scheduler in tests.

## Review Focus

1. Publish of a chatbot without any scheduled start point → no DolphinScheduler call at all (spec §11), and publish answers 200 even when DolphinScheduler is unreachable for a chatbot that has one.
2. Box deleted from the draft (faq delete) and then publish → the live schedule is destroyed (needs `scheduled_live` to survive the `$pull`).
3. A run firing for a chatbot that was trashed or whose `scheduled_live.enabled` is false → 410 and the workflow taken offline, no conversation.
4. Changing only the timezone of a live schedule and publishing → `update` (offline → update → online), not a second workflow.
5. Two publishes in a row with no change → second sync is an `update` with the same cron, never `activate` again (no duplicate `auto-start-<id>` definitions).

---

### Task 1: scheduled draft — rules, model, API

**Files:**
- Create: `services/scheduledStartRules.js`
- Modify: `models/webhook.js` (start point enum, `mapping.payload`, `schedule`; webhook-level `scheduled_live`)
- Modify: `services/startPointService.js` (TYPES, scheduled validation and storage)
- Modify: `routes/webhooks.js` (503 gate for `scheduled`, `schedule_summary`/`live_summary` in PUT response, `scheduled_available` in GET)
- Test: `test/scheduledStartRules.js`, `test/scheduledStartRoute.js`

**Interfaces:**
- Produces `scheduledStartRules.validateSchedule(schedule) → string|null` (error message or null), `validatePayload(payload) → string|null`, `toQuartzCron(schedule) → string`, `summarize(schedule) → string` (e.g. `"Every weekday at 08:30 (Europe/Rome)"`, `"Every 15 minutes (UTC)"`, `"Daily at 09:00 (Europe/Rome)"`, `"Monthly on the last day at 07:00 (UTC)"`; weekday list `mon..fri` reads "Every weekday", otherwise "Every Mon, Wed, Fri"), `isConfigured() → boolean` (the four env vars).
- `startPointService.upsert(id_project, chatbot, 'scheduled', { block_id, enabled?, mapping?: { source_name?, payload? }, schedule?, confirm? })`: `schedule` required when creating; stored as given after validation; never touches `scheduled_live`.
- Webhook GET/PUT responses: `scheduled_available: Boolean`; PUT `scheduled` adds `schedule_summary` and, when `scheduled_live` exists, `live_summary`.

- [ ] **Step 1: Failing tests.** `scheduledStartRules`: every cron row of Global Constraints (`toQuartzCron({frequency:'weekly',time:'08:30',weekdays:['fri','mon','wed'],timezone:'UTC'}) === '0 30 8 ? * MON,WED,FRI *'`), each 400 case of Global Constraints returns a message naming the field (`every`, `time`, `weekdays`, `day_of_month`, `timezone`, payload key/value/size), `summarize` examples above. Route: PUT scheduled with valid schedule → 200, entry stored, `schedule_summary` set, no `scheduled_live`; PUT without `schedule` on create → 400; payload `{ 'a.b': 1 }` → 400; env unset (delete `process.env.SCHEDULED_START_TOKEN` in the test) → 503 for PUT/DELETE scheduled while PUT webhook still works; GET → `scheduled_available` false/true accordingly; DELETE scheduled → entry gone, `scheduled_live` untouched (seed one directly).
- [ ] **Step 2: Run** `NODE_ENV=test ./node_modules/.bin/mocha test/scheduledStartRules.js test/scheduledStartRoute.js --timeout 60000 --exit` → fail.
- [ ] **Step 3: Implement.** Timezone check with `moment.tz.zone(name)`; summary text built from the schedule only (no DolphinScheduler).
- [ ] **Step 4: Run** the two files plus `test/startPointsRoute.js test/startPointsCleanup.js test/webhookConversationRoute.js` → all pass.
- [ ] **Step 5: Commit** — `feat(scheduled-start): scheduled start point draft, rules and API`.

### Task 2: DolphinScheduler client and scheduled start lifecycle

**Files:**
- Create: `services/dolphinSchedulerClient.js`, `services/scheduledStartService.js`
- Test: `test/scheduledStartService.js`

**Interfaces:**
- Consumes `toQuartzCron`, `isConfigured` (Task 1).
- Produces `dolphinSchedulerClient`: `createWorkflow(name, httpTask) → { code }`, `releaseWorkflow(code, 'ONLINE'|'OFFLINE')`, `deleteWorkflow(code)`, `createSchedule(code, { crontab, timezoneId }) → { id }`, `updateSchedule(id, code, { crontab, timezoneId })`, `scheduleOnline(id)`, `scheduleOffline(id)`, `findWorkflowByName(name) → { code }|null`, `previewSchedule({ crontab, timezoneId }) → string[]`. Errors carry `.status` and the DolphinScheduler message; a response with `success: false` or `code !== 0` is an error.
- Produces `scheduledStartService`: `activate(chatbot_id, snapshot) → { workflow_code, schedule_id }`, `update(live, snapshot)`, `deactivate(live)`, `destroy(live)`, `nextRuns(live) → string[]` (3 items, `[]` on error). `snapshot = { schedule, ... }`; `live` = the stored `scheduled_live`.

- [ ] **Step 1: Failing tests (nock on `SCHEDULER_BASEURL`):** activate issues in order create definition (assert body: name `auto-start-<id>`, HTTP task URL `{API_URL}/webhook/scheduled-start`, global params `id_project`, `chatbot_id`, `token`) → release ONLINE → create schedule (assert `crontab`, `timezoneId`, `endTime` 2099) → schedule online, and returns ids; schedule-creation failure → definition released OFFLINE and deleted, error rethrown with status 502; update with known ids → offline, update, online; update whose schedule id is unknown (DolphinScheduler 404/`code!=0`) → falls back to activate (findWorkflowByName reuses an existing `auto-start-<id>` definition instead of creating a duplicate); deactivate → schedule offline only; destroy → schedule offline → definition offline → delete; destroy with unknown ids → resolves (nothing to remove).
- [ ] **Step 2: Run** `... test/scheduledStartService.js` → fail.
- [ ] **Step 3: Implement** (axios, header `token`, params as query like the jobworker; HTTP task JSON shape copied from tiledesk-training-jobworker `utils/shedulerUtils.js#getWorkflowObject`).
- [ ] **Step 4: Run** → pass; also `nock.isDone()` asserted per test.
- [ ] **Step 5: Commit** — `feat(scheduled-start): DolphinScheduler client and schedule lifecycle`.

### Task 3: publish sync, retry, chatbot delete

**Files:**
- Create: `services/scheduledStartPublishListener.js`
- Modify: `app.js` (listen next to `startPointCleanupListener`), `routes/webhooks.js` (`POST /:chatbot_id/start_points/scheduled/sync`; `DELETE /:chatbot_id` destroys first), GET adds `next_runs`
- Test: `test/scheduledStartPublish.js`

**Interfaces:**
- Consumes Task 2 `scheduledStartService`.
- Produces `scheduledStartPublishListener.sync(id_project, chatbot_id, published_bot_id) → scheduled_live|null` (used by the listener and the sync route), `listen()` on `botEvent` `faqbot.publish` (payload `{ chatbot, publishedBotId }`) and `faqbot.delete` (deleted faq_kb doc).

- [ ] **Step 1: Failing tests** (stub `scheduledStartService` methods by replacing them on the singleton, restore in afterEach): sync table of spec §7 — draft enabled + box in published copy (Faq with same `intent_id` under `published_bot_id`) → `activate` first time, `update` afterwards, `scheduled_live` = snapshot with `published_bot_id`/`published_at`; draft disabled → `deactivate`, `scheduled_live.enabled` false; box missing from published copy → `destroy`, `scheduled_live` unset; draft absent but `scheduled_live` present → `destroy`; no draft and no live → no service call (Review Focus 1); service throws → `scheduled_live.error` set, sync resolves; `PUT /:projectid/faq_kb/:id/publish` with the scheduler stubbed to throw → 200 (Review Focus 1); draft entry removed by `DELETE …/faq/<id>` then sync → destroy called with the old ids (Review Focus 2); two syncs unchanged → second is `update` (Review Focus 5); `faqbot.delete` → destroy; `DELETE /:projectid/webhooks/:chatbot_id` → destroy before delete; sync route returns `scheduled_live` and requires admin; GET returns `next_runs` from `nextRuns`.
- [ ] **Step 2: Run** `... test/scheduledStartPublish.js` → fail.
- [ ] **Step 3: Implement.** The listener catches everything (never throws into publish); `published_bot_id` for the sync route = the newest `faq_kb` with `root_id` = chatbot (`/:faq_kbid/published` query).
- [ ] **Step 4: Run** the file plus `test/startPointsRegression.js test/startPointsCleanup.js` → pass.
- [ ] **Step 5: Commit** — `feat(scheduled-start): go live at publish, retry and cleanup on chatbot delete`.

### Task 4: the scheduled run and the draft test run

**Files:**
- Modify: `services/webhookConversationService.js` (`start` takes the start point and start type), `routes/webhook.js` (`POST /scheduled-start`), `routes/webhooks.js` (`POST /:chatbot_id/start_points/scheduled/test`), `services/participantInviteService.js:46`, `services/participantRemoveService.js:28`
- Test: `test/scheduledStartRun.js`; adapt `test/webhookConversationService.js` only if the `start` signature change requires it

**Interfaces:**
- `webhookConversationService.start(webhook, chatbot, payload, options)` gains `options.startPoint` (default: the enabled `webhook` start point, current behaviour), `options.startType` (default `'webhook'`), `options.leadId`/`options.leadName` overrides and `options.extraAttributes` (merged into request attributes). Existing callers unchanged.
- `POST /webhook/scheduled-start` (mounted on the existing public `/webhook` router, defined **before** `/:webhook_id`).

- [ ] **Step 1: Failing tests:** no header → 401; wrong token → 401; token env unset → 503; trashed chatbot → 410 and `scheduleOffline` called (stub) (Review Focus 3); `scheduled_live.enabled` false → 410 + offline; valid → 202, request has `channel.name === 'webhook'`, `attributes.start_type === 'scheduled'`, `attributes.payload` equals `scheduled_live.mapping.payload` (not the draft), `attributes.scheduled_at` ISO string, lead `scheduled_<chatbot_id>` named from the live source name or the chatbot name, system message `/start` with `attributes.action === '#' + scheduled_live.block_id`, `sourcePage` without `td_draft`; test route (admin) → 202, uses the **draft** mapping and `sourcePage` containing `dev=true&td_draft=true`, works with no `scheduled_live`; Invite human on a scheduled conversation → 200 (channel check), on a widget conversation → 422 with the new message.
- [ ] **Step 2: Run** `... test/scheduledStartRun.js` → fail.
- [ ] **Step 3: Implement.** Rate limit: reuse the webhook rate limiter keyed on the webhook id.
- [ ] **Step 4: Run** the file plus `test/webhookConversationService.js test/webhookConversationRoute.js test/inviteParticipantsRoute.js test/startPointsRegression.js test/webhookRoute.js` → all pass.
- [ ] **Step 5: Commit** — `feat(scheduled-start): scheduled runs and draft test runs`.
