@teamscala/service-boot 0.23.319 → 0.23.321

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