@teamscala/service-boot 0.23.329 → 0.23.331

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