@teamscala/service-boot 0.23.345 → 0.23.347

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/package.json +1064 -1093
  2. package/src/fn-routers/index.ts +0 -2
  3. package/src/two-phase-boot.ts +2 -1
  4. package/src/agreement-gate.d.ts +0 -19
  5. package/src/asset-cache-key.d.ts +0 -11
  6. package/src/asset-optimize.d.ts +0 -17
  7. package/src/asset-proxy.d.ts +0 -11
  8. package/src/asset-social-card.d.ts +0 -17
  9. package/src/attach-agreement-magic.d.ts +0 -20
  10. package/src/attach-portal-members.d.ts +0 -23
  11. package/src/attach-proposal-accept.d.ts +0 -26
  12. package/src/attach-proposal-magic.d.ts +0 -18
  13. package/src/attach-transfers-upload.d.ts +0 -27
  14. package/src/auth-gate.d.ts +0 -29
  15. package/src/bind-page-handler.d.ts +0 -18
  16. package/src/build-client-assets/input-hashing.d.ts +0 -25
  17. package/src/build-client-assets/source-candidates.d.ts +0 -27
  18. package/src/build-client-assets.d.ts +0 -50
  19. package/src/compose-page-title.d.ts +0 -41
  20. package/src/content-gate/access.d.ts +0 -15
  21. package/src/content-gate/config-types.d.ts +0 -99
  22. package/src/content-gate/gate.d.ts +0 -13
  23. package/src/content-gate/parse-cookie.d.ts +0 -9
  24. package/src/content-gate/token.d.ts +0 -48
  25. package/src/content-page-floor.d.ts +0 -39
  26. package/src/discover-blocks.d.ts +0 -28
  27. package/src/expand-roster.d.ts +0 -34
  28. package/src/fn-routers/agreement-completion-email.d.ts +0 -14
  29. package/src/fn-routers/agreement-send-router.d.ts +0 -82
  30. package/src/fn-routers/ai-health-router.d.ts +0 -35
  31. package/src/fn-routers/auth-router.d.ts +0 -47
  32. package/src/fn-routers/cache-admin-router.d.ts +0 -57
  33. package/src/fn-routers/chat-session-router.d.ts +0 -219
  34. package/src/fn-routers/email-defaults.d.ts +0 -1
  35. package/src/fn-routers/email-link-ttl.d.ts +0 -1
  36. package/src/fn-routers/index.d.ts +0 -18
  37. package/src/fn-routers/orchestrator-registration-router.d.ts +0 -60
  38. package/src/fn-routers/orchestrator-registration-router.ts +0 -77
  39. package/src/fn-routers/orchestrator-registration.live.test.ts +0 -70
  40. package/src/fn-routers/orchestrator-registration.test.ts +0 -23
  41. package/src/fn-routers/panel-data-router.d.ts +0 -19
  42. package/src/fn-routers/persist-chat-messages.d.ts +0 -36
  43. package/src/fn-routers/plans-router.d.ts +0 -25
  44. package/src/fn-routers/proposal-send-router.d.ts +0 -58
  45. package/src/fn-routers/public-agreement-router.d.ts +0 -289
  46. package/src/fn-routers/public-assessment-router.d.ts +0 -68
  47. package/src/fn-routers/public-gpt-session-router.d.ts +0 -143
  48. package/src/fn-routers/sign-in-flow-router.d.ts +0 -107
  49. package/src/fn-routers/task-sync-assign.d.ts +0 -307
  50. package/src/fn-routers/task-sync-brief.d.ts +0 -98
  51. package/src/fn-routers/task-sync-close.d.ts +0 -41
  52. package/src/fn-routers/task-sync-dispatch.d.ts +0 -47
  53. package/src/fn-routers/task-sync-dispatch.ts +0 -81
  54. package/src/fn-routers/task-sync-lane.d.ts +0 -49
  55. package/src/fn-routers/task-sync-lane.ts +0 -114
  56. package/src/fn-routers/task-sync-projection.d.ts +0 -144
  57. package/src/fn-routers/task-sync-rename.d.ts +0 -91
  58. package/src/fn-routers/task-sync-router.d.ts +0 -455
  59. package/src/fn-routers/task-sync-router.test.ts +0 -361
  60. package/src/fn-routers/task-sync-router.ts +0 -1075
  61. package/src/fn-routers/tasks-router.d.ts +0 -25
  62. package/src/fn-routers/user-preferences-router.d.ts +0 -77
  63. package/src/fn-routers/work-items-router.d.ts +0 -102
  64. package/src/gate-ttls.d.ts +0 -6
  65. package/src/gpt-gate.d.ts +0 -25
  66. package/src/handlers/bun-stable-watch.d.ts +0 -1
  67. package/src/handlers/pane-outbox-drain.d.ts +0 -1
  68. package/src/handlers/projects-digest.d.ts +0 -26
  69. package/src/handlers/prune-stale-data.d.ts +0 -30
  70. package/src/handlers/registry-stale-inactive-sweep.d.ts +0 -1
  71. package/src/handlers/scala-tools-currency-watch.d.ts +0 -1
  72. package/src/handlers/singleton-tools-currency-watch.d.ts +0 -1
  73. package/src/handlers/sweep-event-log.d.ts +0 -1
  74. package/src/handlers/sweep-host-cache.d.ts +0 -24
  75. package/src/handlers/upstream-issue-sync.d.ts +0 -1
  76. package/src/handlers/whatsapp-liveness-logic.d.ts +0 -34
  77. package/src/handlers/whatsapp-liveness.d.ts +0 -4
  78. package/src/hono-error-handler.d.ts +0 -25
  79. package/src/install-harness.d.ts +0 -45
  80. package/src/install-logging.d.ts +0 -34
  81. package/src/load-service-install-row.d.ts +0 -24
  82. package/src/load-service-prisma-client.d.ts +0 -18
  83. package/src/mount-orpc-router.d.ts +0 -15
  84. package/src/mount-server-packages.d.ts +0 -29
  85. package/src/mount.d.ts +0 -9
  86. package/src/mutable-app-ref.d.ts +0 -44
  87. package/src/page-route-shell-types.d.ts +0 -12
  88. package/src/page-server-orpc/audit-revert-router.d.ts +0 -37
  89. package/src/page-server-orpc/hub-mcp-client.d.ts +0 -12
  90. package/src/page-server-orpc/portal-diagnostics-router.d.ts +0 -49
  91. package/src/page-server-orpc/puck-pages-router.d.ts +0 -58
  92. package/src/page-server-orpc/server-client.d.ts +0 -16
  93. package/src/page-server-orpc/templates-router.d.ts +0 -34
  94. package/src/page-server-orpc/user-preferences-router.d.ts +0 -79
  95. package/src/pg-boss-handler-registry.d.ts +0 -27
  96. package/src/pg-boss-mount.d.ts +0 -42
  97. package/src/proposal-authorized-emails.d.ts +0 -28
  98. package/src/proposal-chat-inject.d.ts +0 -17
  99. package/src/proposal-gate.d.ts +0 -18
  100. package/src/read-html-template.d.ts +0 -38
  101. package/src/read-viewport-from-request.d.ts +0 -18
  102. package/src/readiness-gate.d.ts +0 -16
  103. package/src/register-api-routes.d.ts +0 -18
  104. package/src/register-crash-handlers.d.ts +0 -15
  105. package/src/register-page-routes.d.ts +0 -27
  106. package/src/register-page-server-client.d.ts +0 -11
  107. package/src/register-registry-page-route/ai-chat-prefetch.d.ts +0 -13
  108. package/src/register-registry-page-route/graph-cache.d.ts +0 -30
  109. package/src/register-registry-page-route/meta-title.d.ts +0 -2
  110. package/src/register-registry-page-route/proposal-approval-email-token.d.ts +0 -14
  111. package/src/register-registry-page-route/proposal-brand-stamping.d.ts +0 -28
  112. package/src/register-registry-page-route/resolve-page-data.d.ts +0 -1
  113. package/src/register-registry-page-route.d.ts +0 -27
  114. package/src/register-static-assets.d.ts +0 -13
  115. package/src/register-ws-routes.d.ts +0 -28
  116. package/src/resolve-app-base-url.d.ts +0 -13
  117. package/src/resolve-brand-favicon.d.ts +0 -28
  118. package/src/resolve-from-loader-config.d.ts +0 -32
  119. package/src/resolve-service-context.d.ts +0 -17
  120. package/src/resolve-service-port.d.ts +0 -75
  121. package/src/resolve-theme-mode.d.ts +0 -42
  122. package/src/resolvers/fetch-org-brand.d.ts +0 -2
  123. package/src/resolvers/portal-route-paths.d.ts +0 -39
  124. package/src/resolvers/website-by-host-map.d.ts +0 -12
  125. package/src/resource-chat-inject.d.ts +0 -46
  126. package/src/resource-not-found.d.ts +0 -60
  127. package/src/run-boot-hook-list.d.ts +0 -19
  128. package/src/run-boot-hooks.d.ts +0 -31
  129. package/src/scala-tools-currency-watchdog.d.ts +0 -10
  130. package/src/security-headers.d.ts +0 -12
  131. package/src/serve/serve.d.ts +0 -46
  132. package/src/serve/stamp-transport-identity.d.ts +0 -39
  133. package/src/server-error-page.d.ts +0 -29
  134. package/src/start-scheduled-jobs.d.ts +0 -18
  135. package/src/two-phase-boot.d.ts +0 -176
  136. package/src/types.d.ts +0 -46
  137. package/src/ui-service.d.ts +0 -46
  138. package/src/ws-boot-self-test.d.ts +0 -19
@@ -1,1075 +0,0 @@
1
- /**
2
- * @system service-boot
3
- * @status handwritten
4
- * @edit edit directly
5
- * @indivisible-unit
6
- *
7
- * CLI-AGNOSTIC task-sync CORE — the bridge between a lane's native task list
8
- * (Claude Code TodoWrite, OpenCode todowrite, future CLIs) and the `work_items`
9
- * table, which is the single source of truth for "what work does this lane
10
- * have." Detailed contract + the per-CLI adapter split: apps/agent-fleet.md
11
- * (task-sync section).
12
- *
13
- * Design (operator requirement): work_items is the source; each CLI's task list
14
- * is a WRITE-THROUGH PROJECTION, never a peer. One source + write-through
15
- * projection cannot diverge by construction — no two-way sync, no conflict
16
- * resolution. The lane↔task binding is SYMMETRIC: a lane is a lane whether the
17
- * pane is an orchestrator or a supervised agent (both have tasks).
18
- *
19
- * Mapping: an operator request = a kind='task' work_item; the lane's todo items
20
- * = kind='subtask' rows under it via parent_id. The task carries the lane
21
- * identity in kind_data.lane = { pane, session, cli_kind, role } so any surface
22
- * (fleet UI, another lane) can resolve "who owns this work" and push changes
23
- * back. Binding is by pane identity (the stable $TMUX_PANE), not by fleet run —
24
- * so it works without any second runtime-assignment join; the canonical runtime
25
- * identity remains cli_sessions and the assignment remains work_items.
26
- *
27
- * These procedures are the ONLY CLI-agnostic surface an adapter calls:
28
- * bindLane — bind (create-or-confirm) a lane's task. SessionStart.
29
- * closeLane — reconcile a session-owned lane before its runtime releases it.
30
- * upsertFromTaskList — write a lane's current task list through to subtasks (AGENT→DB leg, OpenCode whole-list).
31
- * upsertFromTaskHook — apply a per-item Claude Code PostToolUse:TaskCreate/Update/Delete (AGENT→DB leg, Claude per-item).
32
- * readTaskList — read a lane's current subtasks as a normalized list (DB→AGENT backstop).
33
- * applyExternalChange — record an out-of-band subtask change + notify the owning lane (DB→AGENT realtime leg).
34
- * A CLI with no native task surface (Codex today — upstream_issue openai-codex-2966)
35
- * has NO adapter: it degrades to work_items-only. The work is still tracked and
36
- * visible in the projects UI; the lane simply has no live projection. That is a
37
- * legitimate end state, not a gap to paper over with a fake adapter.
38
- */
39
-
40
- import { getAppLogger } from "@teamscala/logger/app-loggers";
41
- import { recordEvent } from "@teamscala/event-log/record-event";
42
- import { getPlatformOrgId } from "@teamscala/db/registry/platform";
43
- import { createSafeFallback } from "@teamscala/safe-fallback/create-safe-fallback";
44
- import { authed, type Context } from "./auth-router.ts";
45
- import { notifyLaneOfTaskChange } from "./task-sync-dispatch.ts";
46
- import { resolveLaneTask, resolveLaneWorkName } from "./task-sync-lane.ts";
47
- import { readAssignedBriefHandler } from "./task-sync-brief.ts";
48
- import { renameLaneTaskHandler } from "./task-sync-rename.ts";
49
- import { closeLaneHandler } from "./task-sync-close.ts";
50
- import {
51
- adoptAssignmentTask,
52
- bindLaneInput,
53
- createBriefTaskHandler,
54
- resolveBindAction,
55
- } from "./task-sync-assign.ts";
56
- import * as v from "valibot";
57
- import {
58
- STATUS_TO_WORK_ITEM,
59
- deriveEvidenceProgress,
60
- normalizeStatus,
61
- resolveProjectedStatus,
62
- subtaskKey,
63
- resolveTaskUpdateTarget,
64
- planReconcile,
65
- type ProgressAcceptanceEvidence,
66
- type ReconcilePlan,
67
- } from "./task-sync-projection.ts";
68
-
69
- /** A lane's native task-list item, normalized. Every CLI adapter maps to this. */
70
- export interface TaskListItem {
71
- content: string;
72
- status: "pending" | "in_progress" | "completed";
73
- /** CLI-native stable id when the CLI provides one (TodoWrite has none; opencode todo row id). */
74
- mark?: string;
75
- }
76
-
77
- /**
78
- * Input contract for upsertFromTaskList. oRPC does NOT parse the JSON body into
79
- * `input` for a schema-less procedure (see the bindLane comment in this file) —
80
- * so without an explicit `.input()` schema, `input.lane_session` is ALWAYS
81
- * undefined and the procedure throws "requires lane_session" unconditionally.
82
- * Measured 2026-07-29: every pi/opencode whole-list `task_list` publish 400'd
83
- * for exactly this reason (the per-item upsertFromTaskHook path worked because
84
- * it unwraps `raw.json ?? raw`). Declaring the schema is the documented remedy
85
- * and the pattern every other `authed.input(...)` procedure in service-boot
86
- * already follows. The pi adapter (scala-hooks.ts syncTaskList) already sends
87
- * `{ lane_session, task_list, source }` — it was always valid; the server never
88
- * read it.
89
- */
90
- export const upsertFromTaskListInput = v.object({
91
- lane_session: v.string(),
92
- task_list: v.array(
93
- v.object({
94
- content: v.string(),
95
- status: v.picklist(["pending", "in_progress", "completed"]),
96
- mark: v.optional(v.string()),
97
- }),
98
- ),
99
- source: v.optional(v.string()),
100
- });
101
-
102
- /** Who a lane IS — symmetric across orchestrator/agent roles and across CLIs. */
103
- export interface LaneIdentity {
104
- /** "tmux:%42" — authoritative pane identity ($TMUX_PANE). */
105
- pane: string;
106
- session?: string;
107
- /** pane-inventory inferCliKind: claude-code | opencode | codex | unknown. */
108
- cli_kind?: string;
109
- /** agent | orchestrator — both have tasks; the model does not assume a supervised agent. */
110
- role?: string;
111
- /**
112
- * Optional. work_items.organisation_id is NOT NULL; when the caller omits it
113
- * (auto-bind at SessionStart — an adopted or channel-dispatched lane has no
114
- * client org), bindLane defaults to the platform org via resolveBindOrg.
115
- */
116
- organisation_id?: string;
117
- }
118
-
119
- export interface WorkItem {
120
- id: string;
121
- kind: string;
122
- parent_id: string | null;
123
- organisation_id: string;
124
- title: string;
125
- status: string | null;
126
- position: string | null;
127
- completed: boolean | null;
128
- kind_data: Record<string, unknown>;
129
- }
130
-
131
- export type Prisma = {
132
- work_items: {
133
- findFirst: (a: unknown) => Promise<WorkItem | null>;
134
- findMany: (a: unknown) => Promise<WorkItem[]>;
135
- create: (a: unknown) => Promise<WorkItem>;
136
- update: (a: unknown) => Promise<WorkItem>;
137
- deleteMany: (a: unknown) => Promise<{ count: number }>;
138
- };
139
- cli_sessions: {
140
- findFirst: (a: unknown) => Promise<{ id: string; label?: string | null } | null>;
141
- };
142
- // `comments` is a universal shared model (owned by @teamgbg/db), so every
143
- // service with the db client carries it. Declared here rather than
144
- // feature-detected only for clients generated before the shared comments model
145
- // was deployed; current consumers install the universal comments surface.
146
- comments?: {
147
- findFirst: (a: unknown) => Promise<CommentRow | null>;
148
- findMany: (a: unknown) => Promise<Array<ProgressAcceptanceEvidence>>;
149
- };
150
- };
151
-
152
- /** A `comments` row — only the fields readAssignedBrief touches. */
153
- export interface CommentRow {
154
- content: string;
155
- created_at: Date;
156
- }
157
-
158
- /**
159
- * Resolve the org a lane's task is created under. Explicit when the lane knows
160
- * its org (a dispatched fleet lane carries one); defaults to the platform org
161
- * otherwise — an adopted or channel-dispatched pane has no client org, and the
162
- * platform org is the home for fleet/internal lane tasks (where the operator's
163
- * PM view reads), so auto-bind at SessionStart seeds the task there.
164
- */
165
- export function resolveBindOrg(explicit?: string): string {
166
- return explicit ?? getPlatformOrgId();
167
- }
168
-
169
- const laneTaskCreateFallback = createSafeFallback<WorkItem | null>({
170
- name: "task-sync:lane-task-create-race",
171
- onFailure: "fail-open-noisy",
172
- degradedResult: null,
173
- });
174
-
175
- /**
176
- * Record a task-sync hook DISCARD to event_log so it is observable + queryable,
177
- * not silently swallowed by the hook command's `>/dev/null 2>&1 || true`. The
178
- * endpoint records it server-side regardless of what the hook does with stdout.
179
- * Fire-and-forget per event-log-is-the-only-durable-event-log. The headline
180
- * discard is "no-task-bound" (lane has no bound parent task — exactly the gap
181
- * that SessionStart auto-bind closes; once binding is automatic this becomes a
182
- * rare safety signal rather than the default outcome).
183
- */
184
- export function recordTaskSyncDiscard(
185
- reason: string,
186
- pane: string | null,
187
- extra: Record<string, unknown> = {},
188
- ): void {
189
- recordEvent({
190
- kind: "tasksync.hook.discarded",
191
- payload: { reason, pane: pane ?? null, ...extra },
192
- });
193
- }
194
-
195
- /**
196
- * Record a discard AND return the soft {applied:false} body in one step — every
197
- * no-op path in upsertFromTaskHook goes through here so none can silently drop
198
- * an event. The returned shape matches the prior `{applied:false, reason,...}`.
199
- */
200
- export function discardApplied(
201
- reason: string,
202
- pane: string | null,
203
- extra: Record<string, unknown> = {},
204
- ): { applied: false; reason: string } & Record<string, unknown> {
205
- recordTaskSyncDiscard(reason, pane, extra);
206
- return { applied: false as const, reason, ...extra };
207
- }
208
-
209
- /**
210
- * The lane's human work name is resolved by the assignment owner before binding.
211
- * This router never reads a retired fleet-run row to derive task identity.
212
- */
213
-
214
- /**
215
- * Resolve a lane's CLI-native session id from the canonical runtime row by pane.
216
- * Task-event payloads may lack session_id, so the active cli_sessions row's
217
- * host_route is the only valid recovery address.
218
- */
219
- async function resolveSessionFromPane(prisma: Prisma, pane: string): Promise<string | null> {
220
- try {
221
- const session = await prisma.cli_sessions.findFirst({
222
- where: {
223
- closed_at: null,
224
- lifecycle_state: { not: "closed" },
225
- host_route: { path: ["pane_id"], equals: pane },
226
- },
227
- select: { id: true },
228
- });
229
- return session?.id ?? null;
230
- } catch {
231
- return null;
232
- }
233
- }
234
-
235
- /** Resolve the task a lane owns, by SESSION IDENTITY (kind_data.lane.session).
236
- *
237
- * The CLI-native session id is the durable, unique-per-session key (Claude
238
- * Code's UUIDv7 = transcript filename; OpenCode's ses-prefixed id). A pane id
239
- * is NOT the key — it outlives the CLI session, so a fresh session in the same
240
- * pane would inherit the prior session's tasks (the exact bug this re-keys).
241
- * The pane stays on kind_data.lane.pane as a diagnostic field only. */
242
- /**
243
- * The lane's parent task, CREATING the binding when it does not exist yet.
244
- *
245
- * Every lane must be able to comply with `lane-labels-and-task-lists` — operator
246
- * ruling 2026-07-27: "ALL lanes can comply, there is no reason why a tab cant
247
- * comply." The task hooks previously resolved the parent and, finding none,
248
- * DISCARDED the lane's task ("no-task-bound"). A lane whose SessionStart bindLane
249
- * never ran, or ran while the endpoint was failing, therefore lost every task it
250
- * created, silently, forever — it was told to keep a task list and structurally
251
- * could not. Measured 2026-07-27: live active lanes with no binding at all, each
252
- * throwing away its own list.
253
- *
254
- * Binding on demand removes the failure mode instead of reporting it: the first
255
- * task a lane records creates the parent it needs. SessionStart binding still
256
- * runs and is still preferred (it names the task from the lane's work name); this
257
- * is the backstop that makes the discard impossible.
258
- *
259
- * The create races SessionStart and a sibling hook exactly as bindLane does, so
260
- * it loses the race the same way — re-read and carry on, never surface an error
261
- * for a row that now exists.
262
- */
263
- async function ensureLaneTask(
264
- prisma: Prisma,
265
- session: string,
266
- pane: string | null,
267
- ): Promise<WorkItem | null> {
268
- const existing = await resolveLaneTask(prisma, session);
269
- if (existing) return existing;
270
- // The lane's real work name — its fleet run's slot_name
271
- // (lanes-named-by-the-spawner). resolveLaneWorkName reads the most recent run
272
- // for the pane regardless of state, so a lane whose run closed still resolves.
273
- // A task with NO resolvable name is NOT created: writing the generic "Lane"
274
- // sentinel is exactly the unmakeable state this backstop must refuse (a row
275
- // titled "Lane" tells the operator nothing and reads as spawn debris).
276
- // Return null — reconcileTaskList throws, the TaskCreated hook discards
277
- // (observably), so the lane never silently produces a "Lane" row.
278
- const name = pane ? await resolveLaneWorkName(prisma, pane) : null;
279
- if (!name || name.trim().toLowerCase() === "lane") return null;
280
- const lane: LaneIdentity = { pane: pane ?? "", session, cli_kind: "claude-code", role: "agent" };
281
- const created = await laneTaskCreateFallback.call(() =>
282
- prisma.work_items.create({
283
- data: {
284
- kind: "task",
285
- parent_id: null,
286
- organisation_id: resolveBindOrg(),
287
- title: name,
288
- status: "active",
289
- // assignee_id on every bind path (see bindLane): without it a bound
290
- // task reads as unowned to an orchestrator steering by assignee_id.
291
- assignee_id: session,
292
- kind_data: { lane },
293
- },
294
- }),
295
- );
296
- return created ?? resolveLaneTask(prisma, session);
297
- }
298
-
299
-
300
- /** Match key for a subtask: stable mark when the CLI provides one, else content, else title. Uses || (not ??) so an empty-string content (passed for existing rows that key by title) falls through. */
301
- /**
302
- * Which lifecycle leg a Claude task-hook payload represents.
303
- *
304
- * The dedicated events `TaskCreated` and `TaskCompleted` BOTH carry
305
- * `task_subject`, so "has a subject" cannot distinguish them — a completion
306
- * classified as a creation mints a duplicate subtask instead of closing one,
307
- * which is precisely the "list only grows, nothing ever completes" symptom
308
- * (`task-projection-converges`). `hook_event_name` is a common field on every
309
- * hook event and is the only reliable discriminator, so the decision is made
310
- * here, once, rather than by branch ordering in the handler.
311
- */
312
- /**
313
- * Markers that can only appear in a task subject when the CLI's tool-call text
314
- * leaked into the field. `</subject>` is the closing tag of the parameter
315
- * itself, and `<parameter name=` is the START of the NEXT parameter — either
316
- * one means the extraction ran past the end of the value it was reading.
317
- */
318
- const SUBJECT_LEAK_MARKERS = ["</subject>", "<parameter name=", "</antml"];
319
-
320
- /**
321
- * Trim a task subject at the first tool-call marker.
322
- *
323
- * A subject arriving as `Cut judge false positives</subject>\n<parameter
324
- * name="description">Live gate blocks ~half...` is not a title with odd
325
- * punctuation — it is the raw tool call, and it renders on the dashboard as a
326
- * wall of XML where the operator expects a task name (observed live 2026-07-25,
327
- * 3 rows). The malformation happens upstream in the CLI's hook payload, which
328
- * this service does not control, so the defence belongs at the WRITE boundary:
329
- * `work_items` is the single source of truth for every surface, and once a
330
- * corrupted title lands there every reader shows it.
331
- *
332
- * Truncating rather than rejecting is deliberate: the text BEFORE the marker is
333
- * the real subject and is worth keeping. Dropping the row instead would lose a
334
- * task the lane genuinely created.
335
- */
336
- export function sanitizeTaskSubject(raw: string): string {
337
- let out = raw;
338
- for (const marker of SUBJECT_LEAK_MARKERS) {
339
- const i = out.indexOf(marker);
340
- if (i !== -1) out = out.slice(0, i);
341
- }
342
- return out.trim();
343
- }
344
-
345
- export function classifyTaskHookEvent(evt: {
346
- hook_event_name?: unknown;
347
- task_subject?: unknown;
348
- }): "completed" | "created" | "tool" {
349
- if (evt.hook_event_name === "TaskCompleted") return "completed";
350
- if (typeof evt.task_subject === "string") return "created";
351
- return "tool";
352
- }
353
-
354
-
355
- /**
356
- * Execute a reconcile against prisma for a lane's task — the shared write path
357
- * for upsertFromTaskList (normalized input) and upsertFromTodoWriteHook (raw
358
- * Claude hook event). Throws an Error ("No task bound to pane …") when the lane
359
- * has no task; callers map that to their preferred response (ORPC NOT_FOUND or a
360
- * soft {synced:0}). Does NOT dispatch a change notification — the lane that
361
- * authored the list already has it.
362
- */
363
- async function reconcileTaskList(
364
- prisma: Prisma,
365
- laneSession: string,
366
- list: TaskListItem[],
367
- source?: string,
368
- pane?: string | null,
369
- ): Promise<{ task_id: string; created: number; updated: number; deleted: number; total: number }> {
370
- // BIND ON DEMAND — this path used to `resolveLaneTask` and THROW, which is the
371
- // exact failure `ensureLaneTask` was written to make impossible (see its
372
- // comment above, and the operator ruling it cites: "ALL lanes can comply,
373
- // there is no reason why a tab cant comply"). The backstop existed and this
374
- // caller did not use it, so a lane whose SessionStart bindLane never ran — or
375
- // ran while the endpoint was failing — could never sync a task list again.
376
- // Not degraded: permanently, with a 404 on every attempt and no path to
377
- // self-recover.
378
- //
379
- // Measured 2026-07-30: a live lane reported ~9 consecutive failures over
380
- // hours and correctly diagnosed its own lane-compliance flag as a false
381
- // positive it was structurally unable to clear. The gate was telling it to
382
- // keep a task list while the only endpoint that records one refused it.
383
- //
384
- // A lane calling this HAS everything the bind needs — its session, its pane,
385
- // its list — so requiring a prior call is a sequencing demand with no
386
- // informational content. `friction-is-a-stop-condition`: the compliant path
387
- // must exist, or the rule is unenforceable against the lane it binds.
388
- const task = await ensureLaneTask(prisma, laneSession, pane ?? null);
389
- if (!task) {
390
- throw new Error(
391
- `Could not bind a task for session ${laneSession} — the create failed and no existing task was found.`,
392
- );
393
- }
394
- const existing = await prisma.work_items.findMany({
395
- where: { parent_id: task.id, kind: "subtask" },
396
- });
397
- const plan = planReconcile(existing, list, source);
398
- for (const c of plan.toCreate) {
399
- await prisma.work_items.create({
400
- data: {
401
- kind: "subtask",
402
- parent_id: task.id,
403
- organisation_id: task.organisation_id,
404
- title: c.content,
405
- status: c.status,
406
- completed: c.completed,
407
- position: c.position,
408
- kind_data: c.kind_data,
409
- },
410
- });
411
- }
412
- for (const u of plan.toUpdate) {
413
- await prisma.work_items.update({
414
- where: { id: u.id },
415
- data: { title: u.content, status: u.status, completed: u.completed, position: u.position, kind_data: u.kind_data },
416
- });
417
- }
418
- let deleted = 0;
419
- if (plan.toDelete.length > 0) {
420
- const res = await prisma.work_items.deleteMany({ where: { id: { in: plan.toDelete } } });
421
- deleted = res.count;
422
- }
423
- return { task_id: task.id, created: plan.toCreate.length, updated: plan.toUpdate.length, deleted, total: list.length };
424
- }
425
-
426
- export const taskSyncRouter = {
427
- /**
428
- * Bind (create-or-confirm) the task a lane owns. Called from a SessionStart
429
- * adapter so the lane has a durable task row before its first todo write.
430
- * Idempotent: re-binding updates the identity (role/cli_kind can change) but
431
- * never orphans existing subtasks. After binding, links the lane's
432
- * cli_sessions is the runtime identity and work_items is the assignment.
433
- */
434
- bindLane: authed.input(bindLaneInput).handler(async ({ input, context }) => {
435
- const ctx = context as Context;
436
- const prisma = ctx.prisma as Prisma;
437
- const log = getAppLogger();
438
- // The SessionStart hook sends the pane + the CLI's native session id.
439
- // SESSION is the match key (kind_data.lane.session) — it is unique per
440
- // CLI session and re-minted each session, so a fresh session cannot find
441
- // the prior session's tasks. PANE stays as a diagnostic field only
442
- // (kind_data.lane.pane) — it outlives the CLI session, so matching on it
443
- // is exactly the inheritance bug this re-keys. Without an .input()
444
- // valibot schema ORPC does not parse the JSON body into `input`, so the
445
- // headers (x-lane-session, x-lane-pane) are the reliable transport.
446
- const raw = (input ?? {}) as {
447
- lane?: Partial<LaneIdentity>;
448
- title?: string;
449
- parent_id?: string;
450
- };
451
- const headerPane = ctx.headers?.get("x-lane-pane") ?? null;
452
- const pane = raw.lane?.pane ?? headerPane;
453
- const headerSession = ctx.headers?.get("x-lane-session") ?? null;
454
- const session = raw.lane?.session ?? headerSession;
455
- // parent_id arrives EITHER as a body field (parsed now that bindLane has an
456
- // `.input()` schema — bindLaneInput) OR on the x-lane-work-item header. Both
457
- // are the assignment task id this lane ADOPTS (`adoptAssignmentTask`); the
458
- // header stays as the redundant transport a header-only caller (zerostack)
459
- // already sends. Before the schema, the body path silently never parsed, so a
460
- // body-only caller (pi) dropped parent_id, never adopted, and self-briefed to
461
- // nulls — the data-not-serving gap `bindLaneInput` exists to close.
462
- const headerWorkItem = ctx.headers?.get("x-lane-work-item") ?? null;
463
- // cli_kind via header is the fallback for callers that transport it there; a
464
- // caller that puts cli_kind in the body lane object (parsed by bindLaneInput)
465
- // is read from raw.lane.cli_kind first.
466
- const headerWorkKind = ctx.headers?.get("x-lane-cli-kind") ?? null;
467
- if (!session) {
468
- const { ORPCError } = await import("@orpc/server");
469
- throw new ORPCError("BAD_REQUEST", {
470
- message: "bindLane requires lane.session (the CLI's native session id)",
471
- });
472
- }
473
- const lanePane = pane ?? "";
474
- const lane: LaneIdentity = {
475
- pane: lanePane,
476
- session,
477
- cli_kind: (raw.lane?.cli_kind ?? headerWorkKind ?? "claude-code") as LaneIdentity["cli_kind"],
478
- role: raw.lane?.role ?? "agent",
479
- organisation_id: raw.lane?.organisation_id,
480
- };
481
- // organisation_id optional: defaults to the platform org (resolveBindOrg)
482
- // so auto-bind at SessionStart works with no client org on the lane.
483
- const organisation_id = resolveBindOrg(lane.organisation_id);
484
- const existing = await resolveLaneTask(prisma, session);
485
- // A human-readable title, resolved from the lane's OWN work name. NEVER a
486
- // pane id in user-facing text (agent-not-identity): `%9` is a machine
487
- // address, it renumbers, and it tells the operator nothing about what the
488
- // lane is doing. The run's slot_name IS the work name
489
- // (lanes-named-by-the-spawner); fall back to a bare "Lane" rather than
490
- // leak the pane id when no run resolves a name.
491
- // The lane's work name — NEVER the "Lane" sentinel (spawn debris an
492
- // orchestrator cannot attribute). null when no run resolves a slot_name;
493
- // the create path REFUSES rather than write "Lane" (lanes-named-by-the-
494
- // spawner).
495
- const laneTitle = raw.title ?? (await resolveLaneWorkName(prisma, lanePane)) ?? null;
496
- let taskId: string;
497
- let created: boolean;
498
- if (existing) {
499
- const kindData = { ...existing.kind_data, lane };
500
- const updated = await prisma.work_items.update({
501
- where: { id: existing.id },
502
- // A supplied parent is an INSTRUCTION, not a default: the spawn named
503
- // the project this lane is for, which is newer than whatever the row
504
- // carried. Set only on create until now, so a re-bind — the common
505
- // case, since this matches by session — silently dropped it.
506
- // Omitted leaves the existing parent alone, so a re-bind without a
507
- // project cannot orphan a lane that already has one.
508
- data: {
509
- kind_data: kindData,
510
- // assignee_id on EVERY bind path, not only adopt: a re-bind that
511
- // left assignee_id null read as "unowned" to an orchestrator
512
- // steering by it (measured 2026-08-01: "Dev-mcp bus claim" — a
513
- // live lane whose task had a session but null assignee_id).
514
- assignee_id: session,
515
- ...(raw.parent_id ? { parent_id: raw.parent_id } : {}),
516
- },
517
- });
518
- taskId = updated.id;
519
- created = false;
520
- log.info("[task-sync] bindLane: re-bound existing task", { taskId, session });
521
- } else {
522
- // DISPATCH-BY-ASSIGNMENT adopt, then a write-back that NEVER orphans.
523
- // The spawn may have carried a workItemId the lane should adopt; adopt
524
- // attempts it, then resolveBindAction decides from the outcome:
525
- // use — adopt succeeded.
526
- // create — exploratory lane (no workItemId) or the id is a PROJECT
527
- // the task is created under.
528
- // refuse — the spawn named a task that does NOT exist. This is the
529
- // `absent-input-reads-as-success` failure: silently creating
530
- // a new task here would abandon the spawn's referenced brief
531
- // and bind the lane to an empty task it was never meant to
532
- // own, leaving an orphan an orchestrator cannot tell from
533
- // real unowned work. Failing loudly surfaces the bad spawn.
534
- const workItemId = raw.parent_id ?? headerWorkItem;
535
- const adopted = await adoptAssignmentTask(prisma, workItemId, { ...lane, session });
536
- let referencedKind: string | null = null;
537
- if (!adopted && workItemId) {
538
- const ref = await prisma.work_items.findFirst({
539
- where: { id: workItemId },
540
- select: { kind: true },
541
- });
542
- referencedKind = ref?.kind ?? null;
543
- }
544
- const action = resolveBindAction({ adopted, workItemId, referencedKind });
545
- if (action.action === "refuse") {
546
- const { ORPCError } = await import("@orpc/server");
547
- throw new ORPCError("NOT_FOUND", {
548
- message:
549
- `bindLane: the spawn referenced work item ${action.workItemId} to adopt, but no task ` +
550
- "exists with that id — refusing rather than creating an orphan task and abandoning the spawn's brief.",
551
- });
552
- }
553
- if (action.action === "use") {
554
- taskId = adopted!.id;
555
- created = false;
556
- log.info("[task-sync] bindLane: adopted assigned task", {
557
- taskId: adopted!.id,
558
- session,
559
- });
560
- } else {
561
- // A task's title must carry the lane's REAL work name — never the
562
- // generic "Lane" sentinel (spawn debris an orchestrator cannot
563
- // attribute). No resolvable name = refuse, so a "Lane" row is
564
- // unmakeable on this path (lanes-named-by-the-spawner).
565
- if (!laneTitle || laneTitle.trim().toLowerCase() === "lane") {
566
- const { ORPCError } = await import("@orpc/server");
567
- throw new ORPCError("BAD_REQUEST", {
568
- message:
569
- "bindLane: no real work name resolved for this lane (its fleet run has no slot_name). " +
570
- "A task titled 'Lane' is spawn debris — name the lane at spawn (windowName) or ensure its fleet run resolves a slot_name.",
571
- });
572
- }
573
- // Read-then-create is a race: SessionStart and the lane's first
574
- // TaskCreate arrive seconds apart, both read nothing, and both create.
575
- // Measured 2026-07-25: 9 lanes with two active parents each, every twin
576
- // 2-3 seconds behind its sibling. Migration 109's partial unique index
577
- // makes the second write fail instead of succeed, and losing the race
578
- // is not an error — the winner's row is exactly what this call wanted,
579
- // so re-read it and carry on.
580
- let row: WorkItem;
581
- try {
582
- row = await prisma.work_items.create({
583
- data: {
584
- kind: "task",
585
- parent_id: raw.parent_id ?? null,
586
- organisation_id,
587
- title: laneTitle,
588
- status: "active",
589
- // assignee_id = the lane's session on EVERY bind path, not only
590
- // adopt. Without it a bound task reads as unowned (assignee_id
591
- // null) — the signal the fleet steers by. Measured 2026-08-01:
592
- // 207 task rows with kind_data.lane.session set but assignee_id
593
- // null, every one reading as unowned.
594
- assignee_id: session,
595
- kind_data: { lane },
596
- },
597
- });
598
- log.info("[task-sync] bindLane: created task", { taskId: row.id, session });
599
- } catch (err) {
600
- const winner = await resolveLaneTask(prisma, session);
601
- if (!winner) throw err;
602
- row = winner;
603
- log.info("[task-sync] bindLane: lost the create race, using existing task", {
604
- taskId: row.id,
605
- session,
606
- });
607
- }
608
- taskId = row.id;
609
- created = true;
610
- }
611
- }
612
- // Runtime identity is owned by cli_sessions; task binding must not mutate a retired run row.
613
- return { task_id: taskId, created };
614
- }),
615
-
616
- /**
617
- * AGENT→DB leg. Write a lane's CURRENT task list through to subtasks. The
618
- * list is authoritative for this lane (it's what the CLI just rendered), so
619
- * this is a full reconcile: create/update/delete to match. Matching is by
620
- * stable mark when the CLI provides one, else by content. Does NOT dispatch
621
- * a change notification — the lane that authored the list already has it.
622
- */
623
- upsertFromTaskList: authed.input(upsertFromTaskListInput).handler(async ({ input, context }) => {
624
- const body = input as { lane_session: string; task_list: TaskListItem[]; source?: string };
625
- const prisma = (context as Context).prisma as Prisma;
626
- const log = getAppLogger();
627
- const session = body?.lane_session;
628
- const list = Array.isArray(body?.task_list) ? body.task_list : [];
629
- if (!session) {
630
- const { ORPCError } = await import("@orpc/server");
631
- throw new ORPCError("BAD_REQUEST", { message: "upsertFromTaskList requires lane_session" });
632
- }
633
- // The pane rides in the header the callers already send (`x-lane-pane`)
634
- // for canonical cli_sessions routing. Absent, task binding still uses the
635
- // native lane session id.
636
- const headerPane = (context as Context).headers?.get("x-lane-pane") ?? null;
637
- try {
638
- const res = await reconcileTaskList(prisma, session, list, body.source, headerPane);
639
- log.info("[task-sync] upsertFromTaskList reconciled", { session, ...res });
640
- return res;
641
- } catch (err) {
642
- if (err instanceof Error && err.message.includes("No task bound")) {
643
- const { ORPCError } = await import("@orpc/server");
644
- throw new ORPCError("NOT_FOUND", { message: err.message });
645
- }
646
- // The 500 body is masked by oRPC (INTERNAL_SERVER_ERROR), so without
647
- // this the cause is invisible — measured 2026-07-30:
648
- // upsertFromTaskList 500ing consistently with no surfaced error,
649
- // blocking task-list projection + the watchdog for every lane. Log
650
- // the actual error before re-throwing (protective-layers-fail-
651
- // explicitly: a failure with no observability is the worst shape).
652
- log.error("[task-sync] upsertFromTaskList FAILED", { session, err: err instanceof Error ? `${err.name}: ${err.message}` : String(err) });
653
- throw err;
654
- }
655
- }),
656
- /**
657
- * Claude Code PostToolUse:TaskCreate/TaskUpdate hook entry. Claude Code's
658
- * todo tool is the per-item Task* family (TaskCreate/TaskUpdate) — TodoWrite
659
- * was REMOVED in recent Claude Code; the hook matcher keys on
660
- * TaskCreate/TaskUpdate, never TodoWrite. The hook command posts the RAW hook
661
- * event (stdin) + an x-lane-pane header (tmux:$TMUX_PANE). Fired as a
662
- * PostToolUse:TaskCreate/Update hook (NOT a "TaskCreated" event — that is
663
- * not a real Claude Code hook event + never fired); this procedure
664
- * applies the per-item change (TaskCreate → new subtask keyed by the harness
665
- * task id; TaskUpdate → status/title flip on the matching subtask). Server-
666
- * side extraction keeps the hook command a trivial jq|curl. Accepts the event
667
- * raw (input.tool_name) OR oRPC-enveloped (input.json.tool_name). Session-
668
- * less: fn.taskSync is page-gate-exempt; localhost pane shell authenticates
669
- * as super-admin via resolveUser. Soft-returns on any no-op (never throws).
670
- */
671
- upsertFromTaskHook: authed.handler(async ({ input, context }) =>
672
- upsertFromTaskHookHandler(input, context)),
673
-
674
- /**
675
- * DB→AGENT backstop read. Returns the lane's current subtasks in the
676
- * normalized shape every CLI adapter maps to its native list. Called by the
677
- * SessionStart/UserPromptSubmit adapters so a pane never opens or continues
678
- * on stale tasks, and by a lane after it receives a "your tasks changed"
679
- * channel notification.
680
- */
681
- readTaskList: authed.handler(async ({ input, context }) => {
682
- const ctx = context as Context;
683
- const prisma = ctx.prisma as Prisma;
684
- const body = (input ?? {}) as { lane_session?: string };
685
- // Same transport as bindLane/upsertFromTaskHook: the session id arrives
686
- // on the x-lane-session header (and body.lane_session as fallback).
687
- const session = body.lane_session ?? ctx.headers?.get("x-lane-session") ?? null;
688
- if (!session) {
689
- const { ORPCError } = await import("@orpc/server");
690
- throw new ORPCError("BAD_REQUEST", { message: "readTaskList requires lane_session" });
691
- }
692
- const task = await resolveLaneTask(prisma, session);
693
- if (!task) {
694
- return {
695
- task_id: null,
696
- task_title: null,
697
- subtasks: [],
698
- progress: { total: 0, accepted: 0, percentage: 0 },
699
- };
700
- }
701
- const rows = await prisma.work_items.findMany({
702
- where: { parent_id: task.id, kind: "subtask" },
703
- });
704
- rows.sort((a, b) => (a.position ?? "").localeCompare(b.position ?? "", undefined, { numeric: true }));
705
- const evidence = prisma.comments
706
- ? await prisma.comments.findMany({
707
- where: {
708
- work_item_id: { in: rows.map((row) => row.id) },
709
- sender_role: "orchestrator",
710
- },
711
- select: { work_item_id: true, sender_role: true, system_key: true },
712
- })
713
- : [];
714
- const subtasks: TaskListItem[] = rows.map((r) => ({
715
- content: r.title,
716
- status: normalizeStatus(r.status),
717
- mark: (r.kind_data?.task_sync as { mark?: string } | undefined)?.mark,
718
- }));
719
- return {
720
- task_id: task.id,
721
- task_title: task.title,
722
- subtasks,
723
- progress: deriveEvidenceProgress(rows, evidence),
724
- };
725
- }),
726
-
727
- /**
728
- * DB→AGENT self-brief leg. A spawned lane PULLS its own brief — nothing is
729
- * pasted, typed, passed as an argument or sent over a channel
730
- * (`action-emission-architecture.md` "The lane PULLS its brief"). The lane's
731
- * CLI extension reads its own session id on load, calls this procedure, and
732
- * reads the brief from the task's LATEST comment. The comment — not the
733
- * description, not a stale comment — is the brief for THIS run: every spawn
734
- * writes a NEW comment, so "what was this lane told" always has exactly one
735
- * answer (`assignment-as-dispatch`). Handler lives in task-sync-brief.ts
736
- * (router is at its line budget); mounted here so fn.taskSync surfaces it.
737
- */
738
- readAssignedBrief: readAssignedBriefHandler,
739
-
740
- /** SPAWNER→DB brief mint: `spawn_agent_tab` turns an initialPrompt into the task row (brief = first comment) the lane self-briefs from; returns the work_item_id that rides the spawn payload. Handler in task-sync-assign.ts. */
741
- createBriefTask: createBriefTaskHandler,
742
-
743
- /** RUNTIME→DB lifecycle close: mark lane.live=false and reconcile task status before the ACP owner releases the session. */
744
- closeLane: closeLaneHandler,
745
-
746
- /**
747
- * TAB→DB rename back-write: the session-picker `/rpc/rename` calls this after
748
- * renaming a tmux window to update the bound task's title BY SESSION (never
749
- * pane), so the tab bar and the project board never diverge
750
- * (`tab-rename-emits-back-to-task-title`). Handler in task-sync-rename.ts.
751
- */
752
- renameLaneTask: renameLaneTaskHandler,
753
-
754
- /**
755
- * DB→AGENT realtime leg (explicit dispatch path). Record an out-of-band
756
- * change to a subtask's status (operator toggles it in the projects UI,
757
- * another lane edits a shared task) and notify the OWNING lane's pane that
758
- * its projection is stale. The pane's adapter re-reads (readTaskList) and
759
- * updates its native list. Symmetric counterpart to upsertFromTaskList:
760
- * there the lane is the originator (no self-echo); here the lane is the
761
- * recipient.
762
- *
763
- * Every call writes the canonical task-change comment for the active
764
- * cli_sessions row; the database comment emission is the delivery trigger.
765
- * There is no pane transport or secondary channel publisher here.
766
- */
767
- applyExternalChange: authed.handler(async ({ input, context }) => {
768
- const body = input as { task_id: string; subtask_id?: string; status?: TaskListItem["status"] };
769
- const prisma = (context as Context).prisma as Prisma;
770
- const log = getAppLogger();
771
- const { task_id, subtask_id, status } = body ?? {};
772
- if (!task_id) {
773
- const { ORPCError } = await import("@orpc/server");
774
- throw new ORPCError("BAD_REQUEST", { message: "applyExternalChange requires task_id" });
775
- }
776
- if (subtask_id && status) {
777
- await prisma.work_items.update({
778
- where: { id: subtask_id },
779
- data: { status: STATUS_TO_WORK_ITEM[status], completed: status === "completed" },
780
- });
781
- }
782
- const task = await prisma.work_items.findFirst({ where: { id: task_id } });
783
- const dispatch = task
784
- ? await notifyLaneOfTaskChange(
785
- prisma as unknown as Parameters<typeof notifyLaneOfTaskChange>[0],
786
- task_id,
787
- `${subtask_id ?? "task"}:${status ?? "refresh"}`,
788
- )
789
- : { delivered: false, sessionId: null, commentId: null };
790
- log.info("[task-sync] applyExternalChange: durable comment emission", {
791
- taskId: task_id,
792
- sessionId: dispatch.sessionId,
793
- delivered: dispatch.delivered,
794
- });
795
- return { task_id, cli_session_id: dispatch.sessionId, comment_id: dispatch.commentId, notified: dispatch.delivered };
796
- }),
797
- };
798
-
799
- /**
800
- * The Claude Code per-item task lifecycle applied to a lane's work_items
801
- * subtasks — the AGENT→DB leg for the Task* tool family (TaskCreate /
802
- * TaskUpdate / TaskDelete) and the dedicated TaskCreated / TaskCompleted events.
803
- *
804
- * Extracted verbatim from the upsertFromTaskHook ORPC handler so the FULL
805
- * lifecycle — created, in_progress, completed, deleted — is unit-testable with a
806
- * mock prisma (same testability split as claim-orchestrator-session, and the
807
- * router-handlers-only-execute half of planReconcile). The ORPC handler is now a
808
- * thin `authed` wrapper that delegates here; this function takes the exact
809
- * `(input, context)` the handler would have bound, so behaviour is unchanged.
810
- *
811
- * `task-projection-converges`: every state a task reaches must write through, or
812
- * the projection is an append-only log and the operator cannot see what a lane is
813
- * doing. The matcher covering TaskCreate|TaskUpdate|TaskDelete is what makes all
814
- * four states reach this handler; this body is what applies them.
815
- */
816
- export async function upsertFromTaskHookHandler(input: unknown, context: Context) {
817
- const raw = (input ?? {}) as {
818
- tool_name?: string;
819
- tool_input?: Record<string, unknown>;
820
- tool_response?: Record<string, unknown>;
821
- json?: { tool_name?: string; tool_input?: Record<string, unknown>; tool_response?: Record<string, unknown> };
822
- };
823
- const evt = raw.tool_name ? raw : (raw.json ?? raw);
824
- const toolName = typeof evt.tool_name === "string" ? evt.tool_name : "";
825
- const toolInput = (evt.tool_input ?? {}) as Record<string, unknown>;
826
- const toolResponse = (evt.tool_response ?? {}) as Record<string, unknown>;
827
- const headerSession = (context as Context).headers?.get("x-lane-session") ?? null;
828
- const headerPane = (context as Context).headers?.get("x-lane-pane") ?? null;
829
- const prisma = (context as Context).prisma as Prisma;
830
- // TaskCreated/TaskCompleted event payloads do NOT carry session_id (only
831
- // SessionStart does), so the task hooks cannot populate x-lane-session —
832
- // the extraction in the hook command yields an empty string. Resolve the
833
- // session from the canonical cli_sessions row by pane instead: the bind (at
834
- // session_start) already stamped kind_data.lane.session. This keeps matching
835
- // session-keyed (resolveLaneTask still filters kind_data.lane.session)
836
- // without requiring every task-event payload to carry the session id.
837
- const session = headerSession || (headerPane ? await resolveSessionFromPane(prisma, headerPane) : null);
838
- if (!session) return discardApplied("no-session", null);
839
- const log = getAppLogger();
840
- // PostToolUse is what Claude Code fires for the Task* tools (verified live:
841
- // subtasks are created from PostToolUse:TaskCreate events). The dedicated
842
- // TaskCreated/TaskCompleted EVENT legs below are kept as a defensive path —
843
- // classifyTaskHookEvent discriminates them by hook_event_name — but the live
844
- // matcher is PostToolUse:TaskCreate|TaskUpdate|TaskDelete, which lands in the
845
- // `tool` leg. Handle the dedicated events first so a TaskCompleted cannot fall
846
- // through to create a duplicate (task-projection-converges).
847
- const createdEvt = evt as {
848
- task_subject?: unknown;
849
- task_id?: unknown;
850
- hook_event_name?: unknown;
851
- // Created-already-done must not project OPEN. Absent -> old behaviour.
852
- status?: unknown;
853
- };
854
- const leg = classifyTaskHookEvent(createdEvt);
855
- if (leg === "completed") {
856
- const task3 = await resolveLaneTask(prisma, session);
857
- if (!task3) return discardApplied("no-task-bound", session, { source: "TaskCompleted" });
858
- const completedId = String(createdEvt.task_id ?? "");
859
- const subject =
860
- typeof createdEvt.task_subject === "string"
861
- ? sanitizeTaskSubject(createdEvt.task_subject)
862
- : "";
863
- // Match on the mark stamped at creation; fall back to the title so a
864
- // subtask created before marks were recorded still closes.
865
- const siblings = await prisma.work_items.findMany({
866
- where: { parent_id: task3.id, kind: "subtask" },
867
- });
868
- const target =
869
- siblings.find(
870
- (s) =>
871
- completedId &&
872
- (s.kind_data as { task_sync?: { mark?: string } } | null)?.task_sync?.mark ===
873
- completedId,
874
- ) ?? siblings.find((s) => subject && s.title === subject);
875
- if (!target) {
876
- return discardApplied("no-matching-subtask", session, {
877
- source: "TaskCompleted",
878
- taskId: completedId,
879
- });
880
- }
881
- await prisma.work_items.update({
882
- where: { id: target.id },
883
- data: { status: "done", completed: true },
884
- });
885
- log.info("[task-sync] TaskCompleted: closed subtask", {
886
- session,
887
- taskId: completedId,
888
- subject,
889
- });
890
- return { applied: true, op: "complete", taskId: completedId };
891
- }
892
- if (leg === "created") {
893
- // Sanitized on BOTH legs: the completion leg matches by title, so a
894
- // raw subject here and a sanitized one at creation would never match.
895
- const subject = sanitizeTaskSubject(String(createdEvt.task_subject ?? ""));
896
- if (!subject) return discardApplied("no-subject", session, { source: "TaskCreated" });
897
- // Bind on demand rather than discard: a lane must always be able to
898
- // record the task it was just told to create.
899
- const task2 = await ensureLaneTask(prisma, session, headerPane);
900
- if (!task2) return discardApplied("no-task-bound", session, { source: "TaskCreated" });
901
- const createdId = String(createdEvt.task_id ?? "");
902
- const createdStatus =
903
- STATUS_TO_WORK_ITEM[createdEvt.status as TaskListItem["status"]] ?? "todo";
904
- const existing = await prisma.work_items.findMany({ where: { parent_id: task2.id, kind: "subtask" } });
905
- // IDEMPOTENT on the CLI's own task id. The hook curls with `--retry 2
906
- // --retry-connrefused`, so one TaskCreate can arrive twice (observed
907
- // 2026-07-25: four tasks each duplicated ~4s apart), and this path used
908
- // `existing` only to compute a position — never to check whether the
909
- // subtask was already written. A projection that duplicates on retry is
910
- // not a projection (task-projection-converges); the operator sees a list
911
- // that only grows. Match on the stored mark, falling back to title for
912
- // rows written before marks were recorded.
913
- const already = existing.find((e) => {
914
- const mark = (e.kind_data as { task_sync?: { mark?: string } } | null)?.task_sync?.mark;
915
- return createdId && mark ? mark === createdId : e.title === subject;
916
- });
917
- if (already) {
918
- return discardApplied("duplicate-create", session, {
919
- source: "TaskCreated",
920
- taskId: createdId,
921
- subtaskId: already.id,
922
- });
923
- }
924
- try {
925
- await prisma.work_items.create({
926
- data: {
927
- kind: "subtask",
928
- parent_id: task2.id,
929
- organisation_id: task2.organisation_id,
930
- title: subject,
931
- status: createdStatus,
932
- completed: createdStatus === "done",
933
- position: String(existing.length),
934
- kind_data: { task_sync: { mark: createdId || undefined, source: "claude-code" } },
935
- },
936
- });
937
- } catch (err) {
938
- // P2002 = unique violation on work_items_subtask_task_sync_mark_uniq.
939
- // The `already` check above is a READ-THEN-WRITE and therefore loses
940
- // a race by construction: two retries of one TaskCreate both read
941
- // `existing` before either writes, both see nothing, and both insert.
942
- // That is why cleaning duplicates by hand kept "fixing" a class that
943
- // came straight back (31 rows cleaned earlier on 2026-07-25, 13 more
944
- // by that evening). The index is what makes the second insert
945
- // impossible; this catch turns losing the race into the CORRECT
946
- // idempotent outcome instead of a 500 back to the hook.
947
- if ((err as { code?: string })?.code !== "P2002") throw err;
948
- return discardApplied("duplicate-create-race", session, {
949
- source: "TaskCreated",
950
- taskId: createdId,
951
- });
952
- }
953
- log.info("[task-sync] TaskCreated: created subtask", { session, taskId: createdId, subject });
954
- return { applied: true, op: "create", taskId: createdId };
955
- }
956
- if (toolName !== "TaskCreate" && toolName !== "TaskUpdate" && toolName !== "TaskDelete") {
957
- return discardApplied("unhandled-tool", session, { toolName });
958
- }
959
- const task = await ensureLaneTask(prisma, session, headerPane);
960
- if (!task) return discardApplied("no-task-bound", session, { toolName });
961
-
962
- if (toolName === "TaskCreate") {
963
- const subject = typeof toolInput.subject === "string" ? toolInput.subject.trim() : "";
964
- if (!subject) return discardApplied("no-subject", session, { toolName });
965
- const taskResp = toolResponse.task as Record<string, unknown> | undefined;
966
- const taskId = String(toolResponse.id ?? toolResponse.taskId ?? taskResp?.id ?? toolInput.taskId ?? "");
967
- const existing = await prisma.work_items.findMany({ where: { parent_id: task.id, kind: "subtask" } });
968
- // IDEMPOTENT on the CLI's own task id. The hook curls with --retry, so one
969
- // TaskCreate can arrive twice, and this (the LIVE PostToolUse path) used to
970
- // fetch `existing` only for position — never to check whether the subtask
971
- // was already written — so every retry minted a duplicate
972
- // (task-projection-converges: a projection that duplicates is not a
973
- // projection). Same mark-then-title match as the TaskCreated event leg.
974
- const already = existing.find((e) => {
975
- const mark = (e.kind_data as { task_sync?: { mark?: string } } | null)?.task_sync?.mark;
976
- return taskId && mark ? mark === taskId : e.title === subject;
977
- });
978
- if (already) {
979
- return discardApplied("duplicate-create", session, { toolName, taskId, subtaskId: already.id });
980
- }
981
- try {
982
- await prisma.work_items.create({
983
- data: {
984
- kind: "subtask",
985
- parent_id: task.id,
986
- organisation_id: task.organisation_id,
987
- title: subject,
988
- status: "todo",
989
- completed: false,
990
- position: String(existing.length),
991
- kind_data: { task_sync: { mark: taskId || undefined, source: "claude-code" } },
992
- },
993
- });
994
- } catch (err) {
995
- // P2002 = unique violation on work_items_subtask_task_sync_mark_uniq
996
- // (read-then-write race: two retries both read `existing` before either
997
- // writes). Losing the race is the correct idempotent outcome, not a 500.
998
- if ((err as { code?: string })?.code !== "P2002") throw err;
999
- return discardApplied("duplicate-create-race", session, { toolName, taskId });
1000
- }
1001
- log.info("[task-sync] upsertFromTaskHook: created subtask", { session, taskId, subject });
1002
- return { applied: true, op: "create", taskId };
1003
- }
1004
-
1005
- const taskId = String(toolInput.taskId ?? toolInput.id ?? "");
1006
- if (!taskId) return discardApplied("no-taskId", session, { toolName });
1007
- // The handler only EXECUTES; the matching rule lives in the pure
1008
- // resolveTaskUpdateTarget so it is unit-testable (same split as planReconcile).
1009
- const siblings = await prisma.work_items.findMany({
1010
- where: { parent_id: task.id, kind: "subtask" },
1011
- });
1012
- const subjectRaw = typeof toolInput.subject === "string" ? toolInput.subject : undefined;
1013
- const decision = resolveTaskUpdateTarget(siblings, { taskId, subject: subjectRaw });
1014
- if (decision.op === "heal" && toolName === "TaskUpdate") {
1015
- await prisma.work_items.create({
1016
- data: {
1017
- kind: "subtask",
1018
- parent_id: task.id,
1019
- organisation_id: task.organisation_id,
1020
- title: decision.title,
1021
- status: STATUS_TO_WORK_ITEM[toolInput.status as TaskListItem["status"]] ?? "todo",
1022
- completed: toolInput.status === "completed",
1023
- position: String(siblings.length),
1024
- kind_data: { task_sync: { mark: taskId || undefined, source: "claude-code" } },
1025
- },
1026
- });
1027
- log.warn("[task-sync] TaskUpdate healed a missing subtask", {
1028
- session,
1029
- taskId,
1030
- subject: decision.title,
1031
- });
1032
- return { applied: true, op: "create", taskId };
1033
- }
1034
- const subtask = decision.op === "update" ? siblings.find((s) => s.id === decision.id) : null;
1035
- if (!subtask) return discardApplied("no-matching-subtask", session, { taskId });
1036
- if (toolName === "TaskDelete") {
1037
- // Canonical Prisma form (the same as reconcileTaskList's deleteMany):
1038
- // `id: { in: [...] }`, NOT `id: [...]` — a bare array on the scalar id is a
1039
- // Prisma validation error that 500'd every TaskDelete, so deletion never
1040
- // projected even once the hook was wired.
1041
- await prisma.work_items.deleteMany({ where: { id: { in: [subtask.id] } } });
1042
- return { applied: true, op: "delete", taskId };
1043
- }
1044
- // TaskUpdate
1045
- const data: {
1046
- status?: string;
1047
- completed?: boolean;
1048
- title?: string;
1049
- kind_data?: Record<string, unknown>;
1050
- } = {};
1051
- const statusRaw = typeof toolInput.status === "string" ? toolInput.status : "";
1052
- if (statusRaw) {
1053
- data.status = STATUS_TO_WORK_ITEM[statusRaw as TaskListItem["status"]] ?? "todo";
1054
- data.completed = statusRaw === "completed";
1055
- }
1056
- if (typeof toolInput.subject === "string") data.title = toolInput.subject;
1057
- // STAMP THE MARK WHEN A ROW IS MATCHED BY TITLE. The first title-match a row
1058
- // ever gets makes it mark-addressable, so every later rename updates it in
1059
- // place (task-projection-converges — a row it can no longer address expresses
1060
- // nothing). The heal path stamps on create; this is the update half.
1061
- const alreadyMarked =
1062
- (subtask.kind_data as { task_sync?: { mark?: string } } | null)?.task_sync?.mark;
1063
- if (taskId && !alreadyMarked) {
1064
- const priorKindData = (subtask.kind_data ?? {}) as Record<string, unknown>;
1065
- const priorSync = (priorKindData.task_sync ?? {}) as Record<string, unknown>;
1066
- data.kind_data = {
1067
- ...priorKindData,
1068
- task_sync: { ...priorSync, mark: taskId, source: "claude-code" },
1069
- };
1070
- }
1071
- if (Object.keys(data).length === 0) return discardApplied("no-change", session, { taskId });
1072
- await prisma.work_items.update({ where: { id: subtask.id }, data });
1073
- log.info("[task-sync] upsertFromTaskHook: updated subtask", { session, taskId, ...data });
1074
- return { applied: true, op: "update", taskId };
1075
- }