minicode-ai 0.11.1 → 0.13.0

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 (221) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -71
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +2 -2
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +52 -19
  184. package/src/ui/i18n/en.ts +58 -6
  185. package/src/ui/i18n/id.ts +58 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +507 -169
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -169
  221. package/docs/USAGE.md +0 -11
@@ -0,0 +1,2887 @@
1
+ // TaskStore — durable authority for task state (Phase 1).
2
+ //
3
+ // RECOVERY NOTE. This file is reconstructed from
4
+ // `store.orig.ts`, an actual recovered snapshot of the pre-wipe uncommitted
5
+ // tree. It is NOT a redesign. Deviations from the artifact, and only these:
6
+ //
7
+ // D1. `synchronizeTasks()` / `upsertTasks()` / `UpsertResult` are NOT here.
8
+ // DEFERRED to Phase 3. They read `item.taskId` off the output of
9
+ // `normalizeTodos()`, and no surviving module has a `TodoItem.taskId`
10
+ // (see `todo.orig.ts` and baseline `src/tools/todo.ts` — neither has
11
+ // one). Recovering them would require inventing Phase 3 addressing.
12
+ // Every other artifact member is preserved verbatim.
13
+ // D2. `CREATE TABLE` is wrapped in a bounded busy-retry (artifact line 137 ran
14
+ // a bare `db.exec(DDL)`). The artifact therefore still carries the exact
15
+ // SQLITE_BUSY gap that Phase 0C closed in `persistence.ts`. Reintroducing
16
+ // it is forbidden, so it is fixed here. The retry is reimplemented locally
17
+ // rather than imported, leaving Phase 0C code untouched.
18
+ //
19
+ // Database: a SEPARATE `tasks.db` at `<cwd>/.minicode/tasks.db`, reached through
20
+ // `resolveLocalDbPath` (Phase 0B, N1). NOT `sessions.db`, because that resolves
21
+ // via `resolveDbPath` which may fall back to the shared `~/.minicode/` — which
22
+ // violates D2 ("MUST NOT silently fall back to a global/shared database path").
23
+ // A separate file also keeps this table clear of `sessions.db`, which already
24
+ // carries 11 additive migrations and its own concurrency tests.
25
+ //
26
+ // All SQL lives here. Other subsystems may only use the domain API.
27
+
28
+ import { Database } from "bun:sqlite"
29
+ import { randomUUID } from "node:crypto"
30
+ import { LIMITS } from "../constants.ts"
31
+ import { resolveLocalDbPath } from "../lib/db-path.ts"
32
+ import { scrubSecrets } from "../policy/scrub.ts"
33
+ import type { CompletionEvidence } from "../tools/todo.ts"
34
+ import {
35
+ type ClaimOutcome,
36
+ IllegalTaskTransitionError,
37
+ isLegalTaskTransition,
38
+ isTaskId,
39
+ isTaskStatus,
40
+ isTerminalTaskStatus,
41
+ type ReconcileOutcome,
42
+ type Task,
43
+ type TaskAcceptance,
44
+ TaskAuthorityLostError,
45
+ TaskError,
46
+ type TaskEvidence,
47
+ type TaskProvenance,
48
+ type TaskSnapshot,
49
+ type TaskStatus,
50
+ type TaskVerification,
51
+ taskIdFromIndex,
52
+ } from "./model.ts"
53
+ import type { SessionAuthority } from "./session-authority.ts"
54
+
55
+ const TASK_DB_FILENAME = "tasks.db"
56
+
57
+ /** Bounds so the JSON columns cannot grow without limit. */
58
+ const MAX_DEPENDS_ON = 32
59
+ const MAX_EVIDENCE = 32
60
+ const MAX_ACCEPTANCE = 32
61
+ const MAX_PARENT = 64
62
+
63
+ /** Shape of the data, not of the table: this rises when column SEMANTICS
64
+ * change, not merely when a column is added. */
65
+ // [PHASE 6K] Deliberately NOT bumped. `TASK_DATA_VERSION` is an existing
66
+ // contract (taskstore.test.ts "H" asserts `ensureDataVersion() === 1`, and that
67
+ // a newer writer is refused rather than downgraded), and bumping it would be a
68
+ // semantic change outside the scope of D3/D4/D5.
69
+ //
70
+ // It is also unnecessary. The lineage migration decides from
71
+ // `PRAGMA table_info`, not from this stamp, precisely because a stamp can lie
72
+ // and the schema cannot. The stamp is written as bookkeeping; the migration's
73
+ // correctness does not depend on it. If a future change makes the SCHEMA itself
74
+ // version-dependent, that change should bump this constant deliberately.
75
+ const TASK_DATA_VERSION = 1
76
+
77
+ /** Bounded schema-DDL retry. Matches the Phase 0C contract: at most `attempts`
78
+ * tries, only transient SQLite contention is retried, every other error
79
+ * (corruption, constraint, …) propagates immediately, and exhaustion yields
80
+ * `null` so the caller raises its own domain error.
81
+ *
82
+ * [Phase 12.2] Dibanding Phase 0C, predikat kontensi diperluas dari hanya
83
+ * SQLITE_BUSY/"database is locked" → mencakup kontensi WAL lintas-proses Windows
84
+ * (SQLITE_IOERR_TRUNCATE / SHMOPEN / LOCK / PROTOCOL / LOCKED), yang transien dan
85
+ * aman di-retry. Bun menaruh kode simbolik di `error.code`, teks di `error.message`. */
86
+ const SCHEMA_ATTEMPTS = 8
87
+ const SCHEMA_BACKOFF_MS = 25
88
+
89
+ const SQLITE_CONTENTION_RE =
90
+ /SQLITE_BUSY|database is locked|database table is locked|SQLITE_LOCKED|SQLITE_PROTOCOL|SQLITE_IOERR_TRUNCATE|SQLITE_IOERR_SHMOPEN|SQLITE_IOERR_LOCK|disk I\/O error/i
91
+
92
+ function isSqliteContention(e: unknown): boolean {
93
+ const code = (e as { code?: unknown } | null)?.code
94
+ if (typeof code === "string" && SQLITE_CONTENTION_RE.test(code)) return true
95
+ const msg = e instanceof Error ? String(e.message ?? e) : String(e)
96
+ return SQLITE_CONTENTION_RE.test(msg)
97
+ }
98
+
99
+ function withBusyRetrySync<T>(fn: () => T, attempts = SCHEMA_ATTEMPTS): T | null {
100
+ for (let i = 1; i <= attempts; i++) {
101
+ try {
102
+ return fn()
103
+ } catch (e) {
104
+ if (!isSqliteContention(e)) throw e
105
+ if (i === attempts) return null
106
+ sleepSync(SCHEMA_BACKOFF_MS * 2 ** (i - 1))
107
+ }
108
+ }
109
+ return null
110
+ }
111
+
112
+ function sleepSync(ms: number): void {
113
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
114
+ }
115
+
116
+ interface TaskRow {
117
+ session_id: string
118
+ task_id: string
119
+ title: string
120
+ status: string
121
+ task_order: number
122
+ parent_id: string | null
123
+ depends_on_json: string | null
124
+ blocked_reason: string | null
125
+ verification_json: string | null
126
+ evidence_json: string | null
127
+ acceptance_json: string | null
128
+ provenance_json: string | null
129
+ created_at: string
130
+ updated_at: string
131
+ revision: number
132
+ exec_generation: number
133
+ attempt_generation: number | null
134
+ /** [PHASE 6P] Kolom terpisah dari status/lineage; lihat `ExecutionOwner`. */
135
+ execution_owner: string | null
136
+ }
137
+
138
+ /**
139
+ * [PHASE 6I] Execution lineage for one task, read through a dedicated accessor so
140
+ * it never becomes part of the public `Task` shape.
141
+ *
142
+ * `execGeneration` is the CURRENT execution generation. It advances ONLY when
143
+ * `claimTask` accepts a claim - never on a title, order, dependency, parent,
144
+ * blockedReason, evidence, verification or status write. That invariance is the
145
+ * whole point: it makes the lineage decision immune to arbitrary task mutation,
146
+ * which is what 6G D1 proved revision could not be.
147
+ *
148
+ * `attemptGeneration` is the generation whose execution attempt reached its end,
149
+ * or `null` when no attempt of the current generation has completed. It records
150
+ * that an ATTEMPT ENDED - never that the task is correct or complete.
151
+ *
152
+ * It is NOT a task status, NOT a lock, NOT a lease, NOT a counter of attempts
153
+ * and NOT a history: exactly one generation is retained, and evidence lives on
154
+ * the task row so it cannot outlive the task.
155
+ */
156
+ export interface ExecutionLineage {
157
+ readonly execGeneration: number
158
+ readonly attemptGeneration: number | null
159
+ }
160
+
161
+ /**
162
+ * [PHASE 6P] Who owns the CURRENT in-flight state of a task.
163
+ *
164
+ * This is a FOURTH, separate fact. It is deliberately NOT folded into
165
+ * `TaskStatus`, `ExecutionLineage`, or `Task`:
166
+ *
167
+ * status WHAT the task is (pending, in-flight, done, …)
168
+ * execution_owner WHOSE in-flight state it is
169
+ * exec_generation WHICH execution generation is current
170
+ * attempt_generation whether that generation's attempt reached its end
171
+ *
172
+ * WHY IT EXISTS (6N F1, proved in 6O §5.2). `IN_PROGRESS` is overloaded: it is
173
+ * written both by `claimTask` (a Scheduler-owned execution) and by the
174
+ * model-facing path (`todo_write` → `synchronizeCanonicalTasks` → `patchTask`,
175
+ * where it is the agent's plan cursor — see `src/tools/todo.ts:15-19`).
176
+ * Reconciliation used to read *every* `IN_PROGRESS`/`VERIFYING` without a
177
+ * completion marker as stranded Scheduler work, so it reverted the user's cursor.
178
+ *
179
+ * The information needed to tell those apart DID NOT EXIST in the other columns.
180
+ * Two histories are byte-identical under `(status, exec_generation,
181
+ * attempt_generation)` and demand opposite actions:
182
+ *
183
+ * H2 claim → crash → IN_PROGRESS/1/NULL → REVERT
184
+ * H5 claim → crash → reconcile → user
185
+ * marks IN_PROGRESS → IN_PROGRESS/1/NULL → LEAVE
186
+ *
187
+ * `exec_generation > 0` does not separate them (both are 1, and reconcile never
188
+ * resets the counter), and `attempt_generation` is NULL in both. This column is
189
+ * the missing fact: it records whether a reconcile already ended that claim.
190
+ *
191
+ * STATE MODEL — the only two values:
192
+ * 'scheduler' the current in-flight status was established by `claimTask` and
193
+ * has NOT been reconciled away. The Scheduler may recover it.
194
+ * null no Scheduler execution owns this task. Either never claimed, or
195
+ * ownership was released (by a reconcile, or by any status write
196
+ * that leaves the Scheduler-owned in-flight states). The Scheduler
197
+ * must NOT touch it.
198
+ *
199
+ * TRANSITIONS (and only these):
200
+ * set 'scheduler' by `claimTask`, in the SAME statement that advances
201
+ * `exec_generation` and writes IN_PROGRESS — so ownership and
202
+ * generation can never disagree.
203
+ * clear null by `reconcileStranded` / `reconcileIfNoCompletedAttempt`
204
+ * (reverting releases it), and by ANY other writer that
205
+ * moves the task OUT of RECONCILABLE_STATUSES.
206
+ * keep unchanged by a status write that STAYS inside
207
+ * RECONCILABLE_STATUSES, and by every non-status write
208
+ * (title, order, dependency, evidence, …). A title edit does
209
+ * not end a claim.
210
+ *
211
+ * WHY A WRITE THAT STAYS `IN_PROGRESS` KEEPS OWNERSHIP. A user writing
212
+ * `IN_PROGRESS` onto a task whose claim is stranded does not end the stranded
213
+ * execution; it only re-states the agent's plan cursor on top of it. The
214
+ * Scheduler's generation is still dead, so the row is still recoverable (6O
215
+ * history H3/H6). Releasing ownership there would strand the generation forever.
216
+ * Ownership is released when the task LEAVES the in-flight states — which is
217
+ * also exactly what a reconcile does.
218
+ *
219
+ * IT IS NOT: a lock, a lease, a heartbeat, a priority, a completion claim, a
220
+ * verification, or evidence of anything. It grants no authority over the task
221
+ * beyond "the Scheduler may revert this in-flight state", and it is never
222
+ * consulted for readiness, identity, or dependency semantics.
223
+ */
224
+ export type ExecutionOwner = "scheduler"
225
+
226
+ /** Result shape for `getExecutionOwnership`. `null` = no such task. */
227
+ export interface ExecutionOwnership {
228
+ readonly executionOwner: ExecutionOwner | null
229
+ }
230
+
231
+ /** `task_meta` key holding the current incarnation of a session id. */
232
+ const incarnationKey = (sessionId: string): string => `session_incarnation:${sessionId}`
233
+
234
+ /**
235
+ * [PHASE 6Q] Outcome of `recordAttemptReturned`.
236
+ *
237
+ * [DESIGN DECISION] This used to be `void` and it THREW whenever the guarded
238
+ * UPDATE matched no row. That is what made 6N F2 a wedge rather than an error: the
239
+ * throw escaped `cycle()`, so the Scheduler never reached the line that clears its
240
+ * own claim, and it kept both the claim and the session ownership forever.
241
+ *
242
+ * "The row I claimed is gone" and "the generation moved" are NOT persistence
243
+ * failures - they are the ordinary outcomes of a session being deleted under a
244
+ * running execution, or of a later generation superseding an earlier one. The
245
+ * protection 6I wanted is preserved exactly (NOTHING IS WRITTEN when the guard
246
+ * does not match); what changes is that the caller is TOLD, instead of being
247
+ * destroyed by it. Genuine SQL errors still throw.
248
+ */
249
+ export type AttemptRecordOutcome =
250
+ /** The completion marker for this generation was written. */
251
+ | "RECORDED"
252
+ /** The task row no longer exists - the session was deleted under this execution. */
253
+ | "TASK_GONE"
254
+ /** The row exists but this generation is no longer current. Nothing was written. */
255
+ | "SUPERSEDED"
256
+ /**
257
+ * The session was deleted (or deleted and recreated) since this execution was
258
+ * claimed, so the row that exists - if any - belongs to a DIFFERENT incarnation.
259
+ * This is the cross-generation guard; nothing was written.
260
+ */
261
+ | "SESSION_SUPERSEDED"
262
+
263
+ /**
264
+ * [PHASE 6I] Outcome of `reconcileIfNoCompletedAttempt`.
265
+ *
266
+ * Distinct from the 6B `ReconcileOutcome` because the decision now also carries
267
+ * lineage meaning: `RECONCILED` means "this execution generation has no recorded
268
+ * completion, so it is stranded", whereas `NOT_STRANDED` means the current
269
+ * generation DID record completion (or the row is not reconcilable at all).
270
+ * `REFUSED_NO_OWNERSHIP` keeps 6B's fail-closed contract.
271
+ */
272
+ export type LineageReconcileOutcome =
273
+ | "RECONCILED"
274
+ | "NOT_STRANDED"
275
+ | "REJECTED_STALE"
276
+ | "NOT_FOUND"
277
+ | "REFUSED_NO_OWNERSHIP"
278
+
279
+ /**
280
+ * [P14] Status yang boleh DIPINDAHKAN ke sesi lain.
281
+ *
282
+ * Kenapa bukan "semua status": memindahkan pekerjaan yang sudah COMPLETED atau
283
+ * CANCELLED akan menghidupkan kembali pekerjaan yang sudah ditutup — persis
284
+ * larangan P14. Status di luar daftar ini = terminal/UNKNOWN dan harus
285
+ * ditangani operator, bukan diadopsi diam-diam.
286
+ */
287
+ const ADOPTABLE_STATUSES: readonly TaskStatus[] = [
288
+ "PENDING",
289
+ "IN_PROGRESS",
290
+ "VERIFYING",
291
+ "BLOCKED",
292
+ "FAILED",
293
+ "RETRYING",
294
+ ]
295
+
296
+ const ADOPTABLE_STATUS_SET: ReadonlySet<TaskStatus> = new Set(ADOPTABLE_STATUSES)
297
+
298
+ /**
299
+ * [P14] Satu baris ledger transfer. TIDAK mengandung token otoritas: token
300
+ * adalah kredensial proses, bukan bukti yang boleh menetap di database.
301
+ *
302
+ * Ledger ini adalah BUKTI ASAL, bukan otoritas kedua. Status task tetap
303
+ * dibaca dari tabel `tasks`; ledger hanya menjawab "task id ini pernah
304
+ * berpindah dari sesi mana ke sesi mana, pada revisi/generasi apa".
305
+ */
306
+ export interface TaskTransfer {
307
+ readonly transferId: string
308
+ readonly taskId: string
309
+ readonly fromSessionId: string
310
+ readonly fromIncarnation: number
311
+ readonly toSessionId: string
312
+ readonly toIncarnation: number
313
+ readonly expectedRevision: number
314
+ readonly newRevision: number
315
+ readonly status: string
316
+ readonly execGeneration: number
317
+ readonly attemptGeneration: number | null
318
+ readonly executionOwner: ExecutionOwner | null
319
+ readonly transferredAt: string
320
+ }
321
+
322
+ export interface TaskTransferRequest {
323
+ readonly taskId: string
324
+ readonly fromSessionId: string
325
+ readonly fromIncarnation: number
326
+ readonly toSessionId: string
327
+ readonly toIncarnation: number
328
+ readonly expectedRevision: number
329
+ /** Token yang HARUS masih memegang lease sesi sumber. */
330
+ readonly sourceOwnerToken: string
331
+ /** Token yang HARUS masih memegang lease sesi tujuan. */
332
+ readonly targetOwnerToken: string
333
+ /** Satu jam logis untuk seluruh pemeriksaan + mutasi. */
334
+ readonly now?: number
335
+ }
336
+
337
+ export type TaskTransferOutcome =
338
+ | "TRANSFERRED"
339
+ | "NOT_FOUND"
340
+ | "REFUSED_SELF_TRANSFER"
341
+ | "REJECTED_STALE_SOURCE_INCARNATION"
342
+ | "REJECTED_STALE_TARGET_INCARNATION"
343
+ | "REJECTED_STALE_REVISION"
344
+ | "REFUSED_NO_SOURCE_AUTHORITY"
345
+ | "REFUSED_NO_TARGET_AUTHORITY"
346
+ | "REFUSED_STATUS"
347
+ | "REFUSED_TARGET_ID_CONFLICT"
348
+ | "REFUSED_UNRESOLVED_RELATION"
349
+ | "REFUSED_CORRUPT_STATE"
350
+
351
+ export interface TaskTransferResult {
352
+ readonly outcome: TaskTransferOutcome
353
+ readonly task: Task | null
354
+ readonly transfer: TaskTransfer | null
355
+ readonly detail: string
356
+ /**
357
+ * Id relasi (parent/dependency) yang tidak bisa dibuktikan berasal dari sesi
358
+ * sumber yang sama. Kosong kecuali outcome `REFUSED_UNRESOLVED_RELATION`.
359
+ */
360
+ readonly unresolvedRelations: readonly string[]
361
+ }
362
+
363
+ /**
364
+ * [P14] Satu item inventaris open-work lintas sesi.
365
+ *
366
+ * `Task` sengaja tetap bentuk kanoniknya; fakta eksekusi dan provenance
367
+ * transfer berada DI SAMPINGNYA, bukan dicampur ke dalam `Task`. Discovery
368
+ * tidak pernah memberi otoritas: tidak ada lease yang diakuisisi dan tidak
369
+ * ada baris yang ditulis.
370
+ */
371
+ export interface UnfinishedWorkItem {
372
+ readonly sessionId: string
373
+ readonly sessionIncarnation: number
374
+ readonly task: Task
375
+ readonly execGeneration: number
376
+ readonly attemptGeneration: number | null
377
+ readonly executionOwner: ExecutionOwner | null
378
+ readonly transferredFromSessionId: string | null
379
+ readonly transferredAt: string | null
380
+ }
381
+
382
+ /**
383
+ * [P14.3] Satu baris ledger dedup. Append-only.
384
+ *
385
+ * `duplicateId` adalah task yang DINYATAKAN operator sebagai unit kerja yang
386
+ * sama dengan `survivorId`, lalu ditutup sebagai CANCELLED (BUKAN COMPLETED —
387
+ * menyelesaikan duplikat adalah inferensi yang dilarang). `evidence` adalah
388
+ * teks operator yang direkam utuh: kemiripan judul tidak pernah cukup, dan
389
+ * ledger inilah bukti bahwa keputusan itu eksplisit, bukan otomatis.
390
+ */
391
+ export interface TaskMerge {
392
+ readonly mergeId: string
393
+ readonly sessionId: string
394
+ readonly survivorId: string
395
+ readonly duplicateId: string
396
+ readonly evidence: string
397
+ readonly survivorStatus: string
398
+ readonly duplicateStatus: string
399
+ readonly duplicateRevision: number
400
+ readonly mergedAt: string
401
+ }
402
+
403
+ export interface TaskDuplicateRequest {
404
+ readonly sessionId: string
405
+ readonly survivorId: string
406
+ readonly duplicateId: string
407
+ /** WAJIB non-kosong: alasan operator bahwa ini unit kerja yang sama. */
408
+ readonly evidence: string
409
+ /** Revisi duplikat yang dilihat operator (read-then-write, bukan CAS). */
410
+ readonly expectedRevision?: number
411
+ }
412
+
413
+ export type TaskDuplicateOutcome =
414
+ | "DECLARED"
415
+ | "NOT_FOUND"
416
+ | "REFUSED_SELF_MERGE"
417
+ | "REFUSED_NO_EVIDENCE"
418
+ | "REFUSED_TERMINAL_DUPLICATE"
419
+ | "REJECTED_STALE_REVISION"
420
+
421
+ export interface TaskDuplicateResult {
422
+ readonly outcome: TaskDuplicateOutcome
423
+ /** Duplikat setelah ditutup (CANCELLED, revisi +1), atau null saat ditolak. */
424
+ readonly duplicate: Task | null
425
+ readonly survivor: Task | null
426
+ readonly merge: TaskMerge | null
427
+ readonly detail: string
428
+ }
429
+
430
+ const DDL = `
431
+ CREATE TABLE IF NOT EXISTS tasks (
432
+ session_id TEXT NOT NULL,
433
+ task_id TEXT NOT NULL,
434
+ title TEXT NOT NULL,
435
+ status TEXT NOT NULL,
436
+ task_order INTEGER NOT NULL,
437
+ parent_id TEXT,
438
+ depends_on_json TEXT,
439
+ blocked_reason TEXT,
440
+ verification_json TEXT,
441
+ evidence_json TEXT,
442
+ acceptance_json TEXT,
443
+ provenance_json TEXT,
444
+ created_at TEXT NOT NULL,
445
+ updated_at TEXT NOT NULL,
446
+ revision INTEGER NOT NULL,
447
+ exec_generation INTEGER NOT NULL DEFAULT 0,
448
+ attempt_generation INTEGER,
449
+ execution_owner TEXT,
450
+ PRIMARY KEY (session_id, task_id)
451
+ );
452
+ CREATE INDEX IF NOT EXISTS idx_tasks_session_order ON tasks(session_id, task_order);
453
+ CREATE TABLE IF NOT EXISTS task_meta (
454
+ key TEXT PRIMARY KEY,
455
+ value TEXT NOT NULL
456
+ );
457
+
458
+ CREATE TABLE IF NOT EXISTS session_authority (
459
+ -- [PHASE 6X] One row per (session, incarnation): a bounded, self-expiring
460
+ -- claim on the RIGHT TO SCHEDULE, never proof of liveness.
461
+ session_id TEXT NOT NULL,
462
+ incarnation INTEGER NOT NULL,
463
+ owner_token TEXT NOT NULL,
464
+ owner_pid INTEGER NOT NULL,
465
+ acquired_at INTEGER NOT NULL,
466
+ lease_expires_at INTEGER NOT NULL,
467
+ -- Keyed by incarnation as well as session, so a session deleted and recreated
468
+ -- (6Q bumps the incarnation) can never inherit its predecessor's lease.
469
+ PRIMARY KEY (session_id, incarnation)
470
+ );
471
+
472
+ CREATE TABLE IF NOT EXISTS task_transfers (
473
+ -- [P14] Ledger transfer lintas sesi. APPEND-ONLY: tidak ada UPDATE/DELETE di
474
+ -- jalur produksi. Token otoritas sengaja TIDAK disimpan — yang dicatat adalah
475
+ -- fakta yang tidak berubah (identitas, revisi, generasi, status) supaya
476
+ -- operator bisa mengaudit asal task tanpa memegang kredensial proses.
477
+ transfer_id TEXT PRIMARY KEY,
478
+ task_id TEXT NOT NULL,
479
+ from_session_id TEXT NOT NULL,
480
+ from_incarnation INTEGER NOT NULL,
481
+ to_session_id TEXT NOT NULL,
482
+ to_incarnation INTEGER NOT NULL,
483
+ expected_revision INTEGER NOT NULL,
484
+ new_revision INTEGER NOT NULL,
485
+ status TEXT NOT NULL,
486
+ exec_generation INTEGER NOT NULL,
487
+ attempt_generation INTEGER,
488
+ execution_owner TEXT,
489
+ transferred_at TEXT NOT NULL
490
+ );
491
+ CREATE INDEX IF NOT EXISTS idx_task_transfers_from ON task_transfers(from_session_id, task_id);
492
+ CREATE INDEX IF NOT EXISTS idx_task_transfers_to ON task_transfers(to_session_id, task_id);
493
+ CREATE TABLE IF NOT EXISTS task_merges (
494
+ -- [P14.3] Ledger dedup EKSPLISIT operator. Append-only. Satu-satunya penulis
495
+ -- adalah declareTaskDuplicate, di transaksi yang sama dengan status CANCELLED
496
+ -- duplikat. Kolom evidence WAJIB: kemiripan judul bukan bukti, operator
497
+ -- yang menyatakan alasannya dan teks itu disimpan utuh untuk audit
498
+ -- (tanpa token otoritas — sama seperti task_transfers).
499
+ merge_id TEXT PRIMARY KEY,
500
+ session_id TEXT NOT NULL,
501
+ survivor_id TEXT NOT NULL,
502
+ duplicate_id TEXT NOT NULL,
503
+ evidence TEXT NOT NULL,
504
+ survivor_status TEXT NOT NULL,
505
+ duplicate_status TEXT NOT NULL,
506
+ duplicate_revision INTEGER NOT NULL,
507
+ merged_at TEXT NOT NULL
508
+ );
509
+ CREATE INDEX IF NOT EXISTS idx_task_merges_session ON task_merges(session_id, duplicate_id);
510
+ `
511
+
512
+ /**
513
+ * The DDL as INDIVIDUAL statements.
514
+ *
515
+ * [PHASE 1 FIX] The artifact passed the whole script to a single `db.exec()`.
516
+ * Measured under a held write lock, that does not fail the way the code
517
+ * assumed: bun runs the script past the blocked `CREATE TABLE` and the next
518
+ * statement (`CREATE INDEX ... ON tasks`) then fails with
519
+ * `no such table: main.tasks` — a NON-busy error. A retry keyed on
520
+ * SQLITE_BUSY therefore never engaged, and the caller saw a misleading error
521
+ * after the full 3s busy_timeout. Running one statement at a time means a lock
522
+ * conflict surfaces as SQLITE_BUSY on the statement that actually needs the
523
+ * lock, which is exactly what the retry can act on.
524
+ */
525
+ const DDL_STATEMENTS: readonly string[] = DDL.split(";")
526
+ .map((s) => s.trim())
527
+ .filter((s) => s.length > 0)
528
+
529
+ /** Handle cache per path, as with `sessions.db`, so `initialize()` does not run
530
+ * the DDL on every operation. */
531
+ const handles = new Map<string, Database>()
532
+ const initialized = new Set<string>()
533
+
534
+ /** Depth of in-flight `withTransaction` calls, per db path.
535
+ *
536
+ * Exists for two reasons:
537
+ * 1. `close`/`resetTaskStoreHandles` must not yank the connection out from
538
+ * under an open transaction - that would leave a half-applied unit of work
539
+ * with no rollback path.
540
+ * 2. It makes the transaction boundary observable, so a caller cannot open a
541
+ * transaction and then escape it by reaching for a different connection. */
542
+ const txDepth = new Map<string, number>()
543
+
544
+ function openTxPaths(): string[] {
545
+ return [...txDepth.entries()].filter(([, d]) => d > 0).map(([p]) => p)
546
+ }
547
+
548
+ /** Throw if `p` currently has an open transaction. */
549
+ function assertNoOpenTx(p: string, what: string): void {
550
+ if ((txDepth.get(p) ?? 0) > 0) {
551
+ throw new TaskError(
552
+ "TASK_TX_ACTIVE",
553
+ `cannot ${what} while a TaskStore transaction is open for this database`,
554
+ )
555
+ }
556
+ }
557
+
558
+ function dbFile(cwd?: string): string {
559
+ return resolveLocalDbPath(TASK_DB_FILENAME, cwd)
560
+ }
561
+
562
+ /**
563
+ * [PHASE 6K] Bring an existing `tasks` table up to the current lineage schema.
564
+ *
565
+ * WHY THIS EXISTS (Phase 6J D3, HIGH): `CREATE TABLE IF NOT EXISTS tasks (...)`
566
+ * is a NO-OP when the table already exists. SQLite does not add columns. So a
567
+ * database created before Phase 6I never received `exec_generation` /
568
+ * `attempt_generation`, and because `createTask` names them, task creation
569
+ * failed outright on any pre-6I installation - on the LEGACY path, with the
570
+ * Scheduler still disabled.
571
+ *
572
+ * WHY SCHEMA INTROSPECTION rather than only a version stamp: a version stamp
573
+ * can lie (a 6F database may carry a stale or absent `data_version`), whereas
574
+ * `PRAGMA table_info` reports what is actually there. The stamp is still
575
+ * written so `dataVersion()` reflects reality, but the DECISION is made from
576
+ * the schema.
577
+ *
578
+ * PROPERTIES, each load-bearing:
579
+ * - IDEMPOTENT: a column is added only when absent, so running twice is a
580
+ * no-op, and a partially migrated database converges.
581
+ * - NON-DESTRUCTIVE: no row is deleted, updated, or reordered. `ADD COLUMN`
582
+ * only appends.
583
+ * - COMPATIBLE WITH EXISTING ROWS: the defaults are exactly the 6H
584
+ * semantics for a row that predates lineage - `exec_generation = 0`
585
+ * ("never claimed") and `attempt_generation = NULL` ("never attempted").
586
+ * `revision`, `status`, `task_id` and every relationship are untouched.
587
+ * - NO INFERENCE: a pre-lineage row is NOT given a generation derived from
588
+ * its revision. 6H explicitly declined that, and it is what caused D1.
589
+ * - TRANSACTIONAL: both ALTERs run in one transaction, so an interruption
590
+ * leaves the table in its previous state rather than half-migrated.
591
+ */
592
+ function migrateExecutionLineageSchema(db: Database): void {
593
+ const present = new Set(
594
+ (db.prepare("PRAGMA table_info(tasks)").all() as { name: string }[]).map((r) => r.name),
595
+ )
596
+ // No `tasks` table at all: the DDL above just created it with the columns.
597
+ if (present.size === 0) return
598
+
599
+ const needsExec = !present.has("exec_generation")
600
+ const needsAttempt = !present.has("attempt_generation")
601
+ if (!needsExec && !needsAttempt) return
602
+
603
+ const run = db.transaction(() => {
604
+ if (needsExec) {
605
+ // NOT NULL with a non-null default is required by SQLite for ADD COLUMN,
606
+ // and it backfills every existing row with 0 = "never claimed".
607
+ db.exec("ALTER TABLE tasks ADD COLUMN exec_generation INTEGER NOT NULL DEFAULT 0")
608
+ }
609
+ if (needsAttempt) {
610
+ // Deliberately nullable with NO default: existing rows read as NULL,
611
+ // which is exactly 6H's "no attempt of the current generation".
612
+ db.exec("ALTER TABLE tasks ADD COLUMN attempt_generation INTEGER")
613
+ }
614
+ })
615
+ try {
616
+ withBusyRetrySync(() => {
617
+ run()
618
+ return true
619
+ })
620
+ } catch (e) {
621
+ throw new TaskError(
622
+ "TASK_MIGRATION_FAILURE",
623
+ `lineage migration failed: ${(e as Error).message}`,
624
+ )
625
+ }
626
+ // Record the schema version so `dataVersion()` is no longer fiction.
627
+ try {
628
+ const cur = db.prepare("SELECT value FROM task_meta WHERE key = ?").get("data_version") as
629
+ | { value: string }
630
+ | null
631
+ | undefined
632
+ const n = cur ? Number(cur.value) : 0
633
+ if (!Number.isFinite(n) || n < TASK_DATA_VERSION) {
634
+ db.prepare(
635
+ "INSERT INTO task_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
636
+ ).run("data_version", String(TASK_DATA_VERSION))
637
+ }
638
+ } catch {
639
+ // The version stamp is bookkeeping, not correctness. A failure to record it
640
+ // must never prevent the store from opening.
641
+ }
642
+ }
643
+
644
+ /**
645
+ * [PHASE 6P] Add `execution_owner` to a database that predates it.
646
+ *
647
+ * Same decision procedure as `migrateExecutionLineageSchema` — decide from
648
+ * `PRAGMA table_info`, never from a version stamp, because a stamp can lie and
649
+ * the schema cannot. Kept as a SEPARATE function so the 6P change is
650
+ * independently reviewable and independently idempotent, and so the older
651
+ * function's documented properties are not silently redefined.
652
+ *
653
+ * PROPERTIES, each load-bearing:
654
+ * - IDEMPOTENT: added only when absent, so repeated opens are a no-op and a
655
+ * partially migrated database converges.
656
+ * - ADDITIVE / NON-DESTRUCTIVE: `ADD COLUMN` only. No row is updated, deleted,
657
+ * reordered or rewritten. Same guarantee as the 6I migration.
658
+ * - COMPATIBLE WITH EXISTING ROWS: nullable with no default, so every existing
659
+ * row reads back as `NULL` = "no Scheduler execution owns this task".
660
+ * - TRANSACTIONAL: the ALTER runs in one transaction, so an interruption leaves
661
+ * the table as it was rather than half-migrated.
662
+ *
663
+ * NO BACKFILL — DELIBERATE, and it is the important decision here.
664
+ *
665
+ * It is tempting to backfill `'scheduler'` onto every pre-6P row that looks like a
666
+ * stranded claim (`status IN (IN_PROGRESS, VERIFYING) AND exec_generation > 0`).
667
+ * That would be a GUESS, and it is provably wrong in one direction and
668
+ * un-recoverable in the other:
669
+ *
670
+ * - A pre-6P row can ALSO be history H5: claim → crash → 6B `reconcileStranded`
671
+ * (status → PENDING) → a user turn marks IN_PROGRESS. That is the same
672
+ * `(IN_PROGRESS, exec>0, att NULL)` shape, and backfilling would mark
673
+ * interactive work as Scheduler-owned and revert it — reintroducing 6N F1
674
+ * on upgraded databases.
675
+ * - Not backfilling leaves a pre-6P genuinely stranded claim unrecovered. Its
676
+ * row stays IN_PROGRESS, which is not-eligible, so its dependents stay
677
+ * unready. This is an availability cost, and it is a MANUAL/OPERATOR cost,
678
+ * not a correctness one: no execution is corrupted, nothing is lost.
679
+ *
680
+ * The ambiguity in legacy rows is IRREDUCIBLE — the fact was never recorded, and
681
+ * 6I's "NO INFERENCE" rule (a pre-lineage row is not given a generation derived
682
+ * from its revision) forbids manufacturing it. Inventing ownership would be the
683
+ * same error one column over. So: additive only, no inference, and the
684
+ * behaviour change is stated rather than hidden.
685
+ */
686
+ function migrateExecutionOwnershipSchema(db: Database): void {
687
+ const present = new Set(
688
+ (db.prepare("PRAGMA table_info(tasks)").all() as { name: string }[]).map((r) => r.name),
689
+ )
690
+ // No `tasks` table at all: the DDL above just created it with the column.
691
+ if (present.size === 0) return
692
+ if (present.has("execution_owner")) return
693
+
694
+ try {
695
+ withBusyRetrySync(() => {
696
+ // Nullable with NO default: existing rows read as NULL, which is exactly
697
+ // "no Scheduler execution owns this task" - the safe direction, because it
698
+ // forbids reconciliation rather than permitting it.
699
+ db.exec("ALTER TABLE tasks ADD COLUMN execution_owner TEXT")
700
+ return true
701
+ })
702
+ } catch (e) {
703
+ throw new TaskError(
704
+ "TASK_MIGRATION_FAILURE",
705
+ `execution-ownership migration failed: ${(e as Error).message}`,
706
+ )
707
+ }
708
+ }
709
+
710
+ function handle(cwd?: string): Database {
711
+ const p = dbFile(cwd)
712
+ const existing = handles.get(p)
713
+ if (existing) return existing
714
+ // [Phase 7 / Live #1] Sama dengan persistence.ts: buka koneksi + PRAGMA
715
+ // setup dalam retry. `new Database(p)` dan `PRAGMA journal_mode=WAL`
716
+ // bisa gagal SQLITE_BUSY saat beberapa proses membuka tasks.db bersamaan.
717
+ // busy_timeout diatur SEBELUM journal_mode (peralihan WAL butuh exclusive
718
+ // lock sesaat yang langsung gagal tanpa busy_timeout).
719
+ let db: Database
720
+ const opened = withBusyRetrySync(() => {
721
+ const d = new Database(p)
722
+ try {
723
+ d.exec(`PRAGMA busy_timeout=${LIMITS.SQLITE_BUSY_TIMEOUT_MS}`)
724
+ } catch {}
725
+ return d
726
+ })
727
+ if (!opened) {
728
+ throw new TaskError(
729
+ "TASK_DB_INIT_FAILURE",
730
+ `cannot open ${p} after ${SCHEMA_ATTEMPTS} busy-retry attempts`,
731
+ )
732
+ }
733
+ db = opened
734
+ // [Audit #3 RL-3] WAL + DDL/migrasi dibungkus SATU guard pasca-konstruksi agar
735
+ // kegagalan IOERR/CORRUPT menutup handle (bukan bocor) — WAL sebelumnya di luar guard.
736
+ try {
737
+ if (!initialized.has(p)) {
738
+ // Sama dengan persistence.ts: PRAGMA WAL dibungkus retry (peralihan WAL
739
+ // butuh exclusive lock sesaat).
740
+ const walOk = withBusyRetrySync(() => {
741
+ db.exec(
742
+ `PRAGMA journal_mode=WAL; PRAGMA busy_timeout=${LIMITS.SQLITE_BUSY_TIMEOUT_MS}; PRAGMA synchronous=NORMAL; PRAGMA journal_size_limit=${LIMITS.SQLITE_WAL_SIZE_LIMIT_BYTES}; PRAGMA wal_autocheckpoint=${LIMITS.SQLITE_WAL_AUTOCHECKPOINT_PAGES};`,
743
+ )
744
+ return true
745
+ })
746
+ if (walOk === null) {
747
+ process.stderr.write(`[warn] taskstore: wal setup deferred, retry next open: ${p}\n`)
748
+ }
749
+ try {
750
+ const { chmodSync } = require("node:fs") as typeof import("node:fs")
751
+ chmodSync(p, 0o600)
752
+ } catch {}
753
+ }
754
+ // D2: the artifact ran this bare and could therefore throw SQLITE_BUSY before
755
+ // any retry. Bounded retry now. On failure the handle is closed and dropped
756
+ // from the cache, exactly as the artifact did, so the next call retries from a
757
+ // clean state instead of handing out a half-built connection.
758
+ for (const stmt of DDL_STATEMENTS) {
759
+ const ok = withBusyRetrySync(() => {
760
+ db.exec(stmt)
761
+ return true
762
+ })
763
+ if (ok === null) throw new Error(`schema init did not complete: ${stmt.slice(0, 40)}`)
764
+ }
765
+ // [PHASE 6K] `CREATE TABLE IF NOT EXISTS` cannot add a column to an
766
+ // existing table, so a database created before 6I never receives the
767
+ // execution-lineage columns and every statement naming them fails. The
768
+ // migration runs here, on the same open path, immediately after the DDL.
769
+ migrateExecutionLineageSchema(db)
770
+ // [PHASE 6P] Same open path, immediately after, so a database that already
771
+ // has the lineage columns but predates 6P still receives `execution_owner`.
772
+ migrateExecutionOwnershipSchema(db)
773
+ initialized.add(p)
774
+ } catch (e) {
775
+ try {
776
+ db.close()
777
+ } catch {}
778
+ handles.delete(p)
779
+ throw new TaskError("TASK_DB_INIT_FAILURE", `schema init failed: ${(e as Error).message}`)
780
+ }
781
+ handles.set(p, db)
782
+ return db
783
+ }
784
+
785
+ function parseJson<T>(raw: string | null, fallback: T): T {
786
+ if (!raw) return fallback
787
+ try {
788
+ const v = JSON.parse(raw) as T
789
+ return v ?? fallback
790
+ } catch {
791
+ // A corrupt column must NOT drop the whole task. Fall back to a neutral
792
+ // shape and the task still reads as present.
793
+ return fallback
794
+ }
795
+ }
796
+
797
+ /**
798
+ * [P14] Parse relasi secara KETAT — berbeda dari `parseJson` yang sengaja
799
+ * memaafkan kolom rusak untuk pembacaan biasa.
800
+ *
801
+ * Transfer lintas sesi memindahkan baris yang relasinya akan ditafsirkan ulang
802
+ * di namespace sesi lain. Menebak `[]` dari JSON rusak berarti memindahkan task
803
+ * tanpa dependency yang sebenarnya ada — persis "deduplication menyatukan tugas
804
+ * yang berbeda" yang dilarang P14. `null` = tidak bisa dibuktikan, jadi tolak.
805
+ */
806
+ function parseStringArrayStrict(raw: string | null): string[] | null {
807
+ if (raw === null || raw.trim() === "") return []
808
+ try {
809
+ const v: unknown = JSON.parse(raw)
810
+ if (!Array.isArray(v)) return null
811
+ if (v.some((x) => typeof x !== "string")) return null
812
+ return v as string[]
813
+ } catch {
814
+ return null
815
+ }
816
+ }
817
+
818
+ function rowToTask(r: TaskRow): Task {
819
+ return {
820
+ id: r.task_id,
821
+ sessionId: r.session_id,
822
+ title: r.title,
823
+ status: (isTaskStatus(r.status) ? r.status : "PENDING") as TaskStatus,
824
+ order: r.task_order,
825
+ parentId: r.parent_id,
826
+ dependsOn: parseJson<string[]>(r.depends_on_json, []),
827
+ blockedReason: r.blocked_reason,
828
+ verification: parseJson<TaskVerification | null>(r.verification_json, null),
829
+ evidence: parseJson<TaskEvidence[]>(r.evidence_json, []),
830
+ acceptance: parseJson<TaskAcceptance | null>(r.acceptance_json, null),
831
+ provenance: parseJson<TaskProvenance>(r.provenance_json, {
832
+ origin: "runtime",
833
+ source: "unknown",
834
+ }),
835
+ createdAt: r.created_at,
836
+ updatedAt: r.updated_at,
837
+ revision: r.revision,
838
+ }
839
+ }
840
+
841
+ function nowIso(): string {
842
+ return new Date().toISOString()
843
+ }
844
+
845
+ function j(value: unknown): string | null {
846
+ return value === null || value === undefined ? null : JSON.stringify(value)
847
+ }
848
+
849
+ /** Shape that may arrive from the model/caller. Task ids are already validated
850
+ * by the allocator; this struct is never stored as-is. */
851
+ export interface NewTaskInput {
852
+ title: string
853
+ status: TaskStatus
854
+ order: number
855
+ parentId?: string | null
856
+ dependsOn?: string[]
857
+ blockedReason?: string | null
858
+ verification?: TaskVerification | null
859
+ evidence?: TaskEvidence[]
860
+ acceptance?: TaskAcceptance | null
861
+ provenance: TaskProvenance
862
+ }
863
+
864
+ export interface TaskPatch {
865
+ title?: string
866
+ status?: TaskStatus
867
+ /** Display position. Unlike `id`, `order` may change at any time and `id`
868
+ * never does. */
869
+ order?: number
870
+ parentId?: string | null
871
+ dependsOn?: string[]
872
+ blockedReason?: string | null
873
+ verification?: TaskVerification | null
874
+ evidence?: TaskEvidence[]
875
+ acceptance?: TaskAcceptance | null
876
+ }
877
+
878
+ export interface UpsertOptions {
879
+ /** Evidence used by the completion gate. Default `unverified` so a TaskStore
880
+ * called without DI cannot silently refuse `completed`.
881
+ * [PHASE 1] inert: the only reader was the deferred `synchronizeTasks`. */
882
+ evidence?: CompletionEvidence
883
+ /** Revision that MUST match (optimistic). `undefined` = no check.
884
+ *
885
+ * [Fase 1 / LOOP-INV-01] The check now runs INSIDE the write transaction and
886
+ * the UPDATE carries `AND revision = ?`, so it is a real compare-and-swap
887
+ * (one writer wins, the loser gets `TASK_STALE_REVISION` and changes
888
+ * nothing). Previously it was a read-then-write outside the transaction and
889
+ * two concurrent writers could both pass it. */
890
+ expectedRevision?: number
891
+ }
892
+
893
+ /**
894
+ * [Fase 1] Opsi khusus `patchTask` untuk dua jaminan baru.
895
+ */
896
+ export interface PatchOptions extends UpsertOptions {
897
+ /**
898
+ * [LOOP-INV-02] Permit EKSPLISIT untuk keluar dari status terminal
899
+ * (`COMPLETED`/`CANCELLED`). Tanpa ini, transisi tersebut ditolak dengan
900
+ * `IllegalTaskTransitionError`.
901
+ *
902
+ * Ini bukan pelonggaran diam-diam: reopen tetap mungkin (operator yang salah
903
+ * merge harus bisa membatalkannya), tetapi setiap pemanggil yang
904
+ * melakukannya menyatakannya di kode dan bisa diaudit lewat grep, bukan
905
+ * tersembunyi sebagai efek samping "tulis status apa saja".
906
+ */
907
+ allowReopen?: boolean
908
+ /**
909
+ * [LOOP-INV-13] Token lease milik pemanggil. Bila diberikan, `patchTask`
910
+ * memverifikasi token itu masih memegang `session_authority` untuk sesi ini.
911
+ * Token basi/tersingkir = `TaskAuthorityLostError`, tanpa menulis apa pun.
912
+ *
913
+ * `undefined` = pemanggil tanpa identitas lease (CLI interaktif / operator).
914
+ * Mode itu sengaja tetap diizinkan supaya sesi tunggal tanpa kontensi tidak
915
+ * berubah perilakunya.
916
+ */
917
+ authorityToken?: string
918
+ }
919
+
920
+ /**
921
+ * [Fase 3 / LOOP-INV-12, LOOP-G21] Hasil verifikasi terstruktur untuk mengunci
922
+ * transisi dari `VERIFYING` ke `COMPLETED` (lulus) atau `BLOCKED` (gagal).
923
+ */
924
+ export interface VerificationGateOutcome {
925
+ readonly ok: boolean
926
+ readonly verdict: "passed" | "failed" | "stale"
927
+ readonly exitCode?: number | null
928
+ readonly command?: string
929
+ readonly summary?: string
930
+ readonly integrityOk?: boolean
931
+ readonly timestamp?: string
932
+ }
933
+
934
+ /** Format satu rekaman `TaskEvidence` berjenis `"verify"` secara deterministik. */
935
+ export function buildVerificationTaskEvidence(outcome: VerificationGateOutcome): TaskEvidence {
936
+ const at = outcome.timestamp ?? nowIso()
937
+ const payload = {
938
+ verdict: outcome.verdict,
939
+ ok: outcome.ok,
940
+ exitCode: outcome.exitCode ?? (outcome.ok ? 0 : 1),
941
+ ...(outcome.command ? { command: scrubSecrets(outcome.command).slice(0, 200) } : {}),
942
+ summary: scrubSecrets(
943
+ outcome.summary ?? (outcome.ok ? "verification passed" : "verification failed"),
944
+ ).slice(0, 500),
945
+ ...(typeof outcome.integrityOk === "boolean" ? { integrityOk: outcome.integrityOk } : {}),
946
+ timestamp: at,
947
+ }
948
+ return {
949
+ kind: "verify",
950
+ detail: JSON.stringify(payload),
951
+ at,
952
+ }
953
+ }
954
+
955
+ /**
956
+ * PHASE 6B: authority mode.
957
+ *
958
+ * `LEGACY` (the default, and the only mode in production today) preserves the
959
+ * historical behaviour where any writer may author `IN_PROGRESS`.
960
+ *
961
+ * `SCHEDULER` closes that door: `IN_PROGRESS` may then be authored ONLY by
962
+ * `claimTask`. Model-facing `todo_write` therefore fails closed with
963
+ * `TASK_AUTHORITY_VIOLATION` instead of creating a claim.
964
+ *
965
+ * Activation is explicit and per-instance. There is no environment variable, no
966
+ * module-level flag, and no automatic activation on `initialize()`.
967
+ */
968
+ export type TaskAuthorityMode = "LEGACY" | "SCHEDULER"
969
+
970
+ export interface TaskStoreOptions {
971
+ /**
972
+ * PHASE 6B. Defaults to `"LEGACY"`. Must be opted into by a composition root.
973
+ * Tests must assert that no production path sets this.
974
+ */
975
+ authority?: TaskAuthorityMode
976
+ }
977
+
978
+ /**
979
+ * Render a status allow-list as a SQL literal list.
980
+ *
981
+ * The values are module-private compile-time constants (`TaskStatus` members),
982
+ * never caller input, so this needs no escaping. It exists so the claim and
983
+ * reconcile predicates read as one auditable statement each, instead of string
984
+ * concatenation repeated per call site.
985
+ */
986
+ function sqlList(statuses: readonly TaskStatus[]): string {
987
+ return statuses.map((s) => `'${s}'`).join(", ")
988
+ }
989
+
990
+ /**
991
+ * PHASE 6B: the only status a claim may transition from.
992
+ *
993
+ * `COMPLETED`, `CANCELLED` and `FAILED` are irreversible and are therefore not
994
+ * claimable — which is what stops a claim from resurrecting finished or
995
+ * abandoned work. `IN_PROGRESS` and `VERIFYING` are excluded because a second
996
+ * claim of in-flight work is exactly the double-claim the primitive prevents.
997
+ */
998
+ const CLAIMABLE_STATUSES: readonly TaskStatus[] = ["PENDING"]
999
+
1000
+ /**
1001
+ * PHASE 6B: the only statuses reconciliation may revert.
1002
+ *
1003
+ * `IN_PROGRESS` and `VERIFYING` assert in-flight activity with no durable proof
1004
+ * of liveness. `COMPLETED` / `CANCELLED` / `FAILED` are irreversible facts and
1005
+ * are never targets. `PAUSED` does not exist in `TaskStatus` and is never
1006
+ * introduced here.
1007
+ */
1008
+ const RECONCILABLE_STATUSES: readonly TaskStatus[] = ["IN_PROGRESS", "VERIFYING"]
1009
+
1010
+ export class TaskStore {
1011
+ readonly cwd: string
1012
+
1013
+ /**
1014
+ * PHASE 6B. Defaults to `"LEGACY"`, so every existing construction site keeps
1015
+ * its exact current behaviour. Per-instance, never a module singleton.
1016
+ */
1017
+ readonly authorityMode: TaskAuthorityMode
1018
+
1019
+ constructor(cwd?: string, opts: TaskStoreOptions = {}) {
1020
+ this.cwd = cwd ?? process.cwd()
1021
+ this.authorityMode = opts.authority ?? "LEGACY"
1022
+ }
1023
+
1024
+ /** Prepare the schema. Idempotent; safe to call repeatedly. */
1025
+ initialize(): void {
1026
+ handle(this.cwd)
1027
+ }
1028
+
1029
+ // ── read ──────────────────────────────────────────────────────────────────
1030
+
1031
+ getTask(sessionId: string, taskId: string): Task | null {
1032
+ if (!isTaskId(taskId)) throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${taskId}`)
1033
+ const db = handle(this.cwd)
1034
+ const row = db
1035
+ .prepare("SELECT * FROM tasks WHERE session_id = ? AND task_id = ?")
1036
+ .get(sessionId, taskId) as TaskRow | null
1037
+ return row ? rowToTask(row) : null
1038
+ }
1039
+
1040
+ listTasks(sessionId: string): Task[] {
1041
+ const db = handle(this.cwd)
1042
+ const rows = db
1043
+ .prepare("SELECT * FROM tasks WHERE session_id = ? ORDER BY task_order, task_id")
1044
+ .all(sessionId) as TaskRow[]
1045
+ return rows.map(rowToTask)
1046
+ }
1047
+
1048
+ getSnapshot(sessionId: string): TaskSnapshot {
1049
+ return { sessionId, tasks: this.listTasks(sessionId) }
1050
+ }
1051
+
1052
+ /** The next id that is DEFINITELY unused. Uses `max`, not `count`, so that
1053
+ * `t1,t2,t5` yields `t6` — not a `t3` that would collide. */
1054
+ nextId(sessionId: string): string {
1055
+ const tasks = this.listTasks(sessionId)
1056
+ let max = 0
1057
+ for (const t of tasks) {
1058
+ const n = Number(t.id.slice(1))
1059
+ if (Number.isFinite(n) && n > max) max = n
1060
+ }
1061
+ return taskIdFromIndex(max)
1062
+ }
1063
+
1064
+ // ── validation ────────────────────────────────────────────────────────────
1065
+
1066
+ /**
1067
+ * Validate blocker/verification/dependency BEFORE persisting.
1068
+ *
1069
+ * Rules enforced:
1070
+ * - `BLOCKED` requires a `blockedReason` (PF-04, second rail — the first is
1071
+ * already in `normalizeTodos`).
1072
+ * - `dependsOn` may only contain canonical ids that EXIST in this session, may
1073
+ * not point at itself, and may not duplicate.
1074
+ * - `COMPLETED` is never rejected here. The "completed needs evidence" gate
1075
+ * runs in `normalizeTodos` (red evidence -> BLOCKED), and duplicating that
1076
+ * logic in a second place is precisely what the brief forbids.
1077
+ */
1078
+ private validate(sessionId: string, input: NewTaskInput, selfId: string): void {
1079
+ if (input.status === "BLOCKED" && !input.blockedReason?.trim()) {
1080
+ throw new TaskError("TASK_INVALID_TRANSITION", "BLOCKED requires blockedReason")
1081
+ }
1082
+ const deps = input.dependsOn ?? []
1083
+ if (deps.length > MAX_DEPENDS_ON) {
1084
+ throw new TaskError("TASK_INVALID_DEPENDENCY", `dependsOn exceeds ${MAX_DEPENDS_ON}`)
1085
+ }
1086
+ const seen = new Set<string>()
1087
+ for (const d of deps) {
1088
+ if (!isTaskId(d)) throw new TaskError("TASK_INVALID_DEPENDENCY", `bad id: ${d}`)
1089
+ if (d === selfId) {
1090
+ throw new TaskError("TASK_INVALID_DEPENDENCY", "task cannot depend on itself")
1091
+ }
1092
+ if (seen.has(d)) throw new TaskError("TASK_INVALID_DEPENDENCY", `duplicate dependency: ${d}`)
1093
+ seen.add(d)
1094
+ const exists = this.getTask(sessionId, d)
1095
+ if (!exists) {
1096
+ throw new TaskError("TASK_INVALID_DEPENDENCY", `unknown dependency: ${d}`)
1097
+ }
1098
+ }
1099
+ if (input.parentId != null) {
1100
+ if (!isTaskId(input.parentId)) {
1101
+ throw new TaskError("TASK_INVALID_DEPENDENCY", `bad parentId: ${input.parentId}`)
1102
+ }
1103
+ if (input.parentId === selfId) {
1104
+ throw new TaskError("TASK_INVALID_DEPENDENCY", "task cannot be its own parent")
1105
+ }
1106
+ }
1107
+ }
1108
+
1109
+ // ── write ─────────────────────────────────────────────────────────────────
1110
+
1111
+ createTask(sessionId: string, input: NewTaskInput): Task {
1112
+ // PHASE 6B authority guard. Creating a task directly in `IN_PROGRESS` is an
1113
+ // authoritative claim just as much as patching one into that status, so the
1114
+ // guard must cover creation as well. LEGACY is untouched.
1115
+ if (this.authorityMode === "SCHEDULER" && input.status === "IN_PROGRESS") {
1116
+ throw new TaskError(
1117
+ "TASK_AUTHORITY_VIOLATION",
1118
+ `IN_PROGRESS may only be authored by claimTask while Scheduler authority is active (${sessionId})`,
1119
+ )
1120
+ }
1121
+ const db = handle(this.cwd)
1122
+ const id = this.nextId(sessionId)
1123
+ return db.transaction(() => {
1124
+ // `nextId` is recomputed INSIDE the transaction so two concurrent writers
1125
+ // cannot be handed the same id.
1126
+ const chosen = db
1127
+ .prepare("SELECT 1 FROM tasks WHERE session_id = ? AND task_id = ?")
1128
+ .get(sessionId, id)
1129
+ ? (() => {
1130
+ let max = 0
1131
+ for (const t of this.listTasks(sessionId)) {
1132
+ const n = Number(t.id.slice(1))
1133
+ if (Number.isFinite(n) && n > max) max = n
1134
+ }
1135
+ return taskIdFromIndex(max)
1136
+ })()
1137
+ : id
1138
+ this.validate(sessionId, input, chosen)
1139
+ const ts = nowIso()
1140
+ try {
1141
+ db.prepare(
1142
+ `INSERT INTO tasks (session_id, task_id, title, status, task_order, parent_id, depends_on_json, blocked_reason, verification_json, evidence_json, acceptance_json, provenance_json, created_at, updated_at, revision, exec_generation, attempt_generation)
1143
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, NULL)`,
1144
+ ).run(
1145
+ sessionId,
1146
+ chosen,
1147
+ input.title,
1148
+ input.status,
1149
+ input.order,
1150
+ input.parentId ?? null,
1151
+ j(input.dependsOn ?? []),
1152
+ input.blockedReason ?? null,
1153
+ j(input.verification ?? null),
1154
+ j((input.evidence ?? []).slice(0, MAX_EVIDENCE)),
1155
+ j(input.acceptance ?? null),
1156
+ j(input.provenance),
1157
+ ts,
1158
+ ts,
1159
+ )
1160
+ } catch (e) {
1161
+ throw new TaskError("TASK_PERSISTENCE_FAILURE", (e as Error).message)
1162
+ }
1163
+ return this.getTask(sessionId, chosen)!
1164
+ })()
1165
+ }
1166
+
1167
+ /**
1168
+ * Apply a patch to one task. Optimistic: if `expectedRevision` is supplied and
1169
+ * does not match, the mutation is REFUSED and the revision does not advance.
1170
+ *
1171
+ * [Fase 1 / LOOP-INV-01] `expectedRevision` is now a REAL compare-and-swap:
1172
+ * the read, the validation and the write share one transaction, and the
1173
+ * UPDATE carries `AND revision = ?`. Two concurrent writers can no longer
1174
+ * both pass it — the loser gets TASK_STALE_REVISION and writes nothing.
1175
+ * (The previous PHASE 6B note above described the old read-then-write shape;
1176
+ * that shape no longer exists.)
1177
+ *
1178
+ * [Fase 1 / LOOP-INV-02] From-state gate: `TASK_EDGES` rejects illegal
1179
+ * transitions, and terminal states (COMPLETED/CANCELLED) can only be left
1180
+ * with the explicit permit `allowReopen`.
1181
+ *
1182
+ * [Fase 1 / LOOP-INV-13] Lease fencing: when `authorityToken` is supplied and
1183
+ * no longer holds `session_authority`, the write is refused without touching
1184
+ * the row. Callers without a token (interactive operator) behave as before.
1185
+ *
1186
+ * PHASE 6B authority guard: when `authorityMode === "SCHEDULER"`, a patch may
1187
+ * not author `IN_PROGRESS` — only `claimTask` may. This is the fail-closed
1188
+ * door that stops model-facing `todo_write` from creating a claim.
1189
+ */
1190
+ patchTask(sessionId: string, taskId: string, patch: TaskPatch, opts: PatchOptions = {}): Task {
1191
+ if (this.authorityMode === "SCHEDULER" && patch.status === "IN_PROGRESS") {
1192
+ throw new TaskError(
1193
+ "TASK_AUTHORITY_VIOLATION",
1194
+ `IN_PROGRESS may only be authored by claimTask while Scheduler authority is active (${sessionId}/${taskId})`,
1195
+ )
1196
+ }
1197
+ if (!isTaskId(taskId)) throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${taskId}`)
1198
+ const db = handle(this.cwd)
1199
+ // [Fase 1 / LOOP-INV-01] READ -> VALIDATE -> WRITE is ONE transaction, and
1200
+ // the UPDATE carries `AND revision = ?`. That makes it a true CAS: a caller
1201
+ // passing `expectedRevision` that loses the race gets TASK_STALE_REVISION
1202
+ // and writes nothing, and even a caller that passes no revision cannot
1203
+ // silently overwrite a row whose revision moved underneath the read.
1204
+ return db.transaction(() => {
1205
+ const current = this.getTask(sessionId, taskId)
1206
+ if (!current) throw new TaskError("TASK_NOT_FOUND", `no task ${taskId} in ${sessionId}`)
1207
+ if (opts.expectedRevision !== undefined && opts.expectedRevision !== current.revision) {
1208
+ throw new TaskError(
1209
+ "TASK_STALE_REVISION",
1210
+ `${taskId} is at revision ${current.revision}, got ${opts.expectedRevision}`,
1211
+ )
1212
+ }
1213
+ // [Fase 1 / LOOP-INV-13] Lease fencing for callers that present an
1214
+ // identity. No token = interactive/operator path (unchanged behaviour);
1215
+ // a token that is no longer current = fail-closed, because a displaced
1216
+ // worker must not write after losing authority.
1217
+ if (
1218
+ opts.authorityToken !== undefined &&
1219
+ !this.holdsSessionAuthority(sessionId, opts.authorityToken)
1220
+ ) {
1221
+ throw new TaskAuthorityLostError(sessionId)
1222
+ }
1223
+ const nextStatus: TaskStatus = patch.status ?? current.status
1224
+ // [Fase 1 / LOOP-INV-02] From-state gate. A self-write (title/order edit)
1225
+ // keeps the same status and therefore always passes. Leaving a terminal
1226
+ // state requires the explicit permit `allowReopen`.
1227
+ if (
1228
+ nextStatus !== current.status &&
1229
+ !isLegalTaskTransition(current.status, nextStatus) &&
1230
+ !(opts.allowReopen === true && isTerminalTaskStatus(current.status))
1231
+ ) {
1232
+ throw new IllegalTaskTransitionError(current.status, nextStatus)
1233
+ }
1234
+ const next: NewTaskInput = {
1235
+ title: patch.title ?? current.title,
1236
+ status: nextStatus,
1237
+ order: patch.order ?? current.order,
1238
+ parentId: patch.parentId === undefined ? current.parentId : patch.parentId,
1239
+ dependsOn: patch.dependsOn ?? current.dependsOn,
1240
+ blockedReason:
1241
+ patch.blockedReason === undefined ? current.blockedReason : patch.blockedReason,
1242
+ verification: patch.verification === undefined ? current.verification : patch.verification,
1243
+ evidence: patch.evidence ?? current.evidence,
1244
+ acceptance: patch.acceptance === undefined ? current.acceptance : patch.acceptance,
1245
+ provenance: current.provenance,
1246
+ }
1247
+ // [PHASE 6P] EXECUTION OWNERSHIP IS RELEASED ONLY WHEN THE TASK LEAVES THE
1248
+ // SCHEDULER-OWNED IN-FLIGHT STATES.
1249
+ //
1250
+ // `patchTask` is every non-claim status writer: the model-facing
1251
+ // `synchronizeCanonicalTasks` path and any operator edit. Two rules, and the
1252
+ // difference between them is the whole point of the 6O history table:
1253
+ //
1254
+ // status STAYS inside RECONCILABLE_STATUSES -> ownership is KEPT.
1255
+ // A user writing IN_PROGRESS is the agent's plan cursor (todo.ts:15-19)
1256
+ // laid on top of a live claim. It does not end the stranded execution
1257
+ // (6O H3/H6), and only a legitimate authority may end a Scheduler
1258
+ // execution. Releasing here would strand the generation forever.
1259
+ //
1260
+ // status LEAVES RECONCILABLE_STATUSES -> ownership is CLEARED.
1261
+ // The row is no longer a Scheduler execution in flight, so leaving
1262
+ // `scheduler` on it would be STALE ownership that a later reconcile
1263
+ // could still match. This is what stops an interactive completion,
1264
+ // failure, cancellation, block or requeue from being reverted later.
1265
+ //
1266
+ // Non-status writes (title, order, dependsOn, evidence, …) never touch the
1267
+ // column: editing a title must not end an execution claim.
1268
+ //
1269
+ // The release is computed in SQL (a CASE over the RESULTING status), so it
1270
+ // needs no extra read and stays inside the same transaction as the write.
1271
+ // [Fase 1] The whole read-validate-write now lives inside that transaction
1272
+ // and the UPDATE is revision-guarded (CAS), so the ownership CASE, the
1273
+ // status gate and the mutation observe one consistent snapshot.
1274
+ this.validate(sessionId, next, taskId)
1275
+ let changes = 0
1276
+ try {
1277
+ changes = db
1278
+ .prepare(
1279
+ `UPDATE tasks SET title = ?, status = ?, task_order = ?, parent_id = ?, depends_on_json = ?, blocked_reason = ?,
1280
+ verification_json = ?, evidence_json = ?, acceptance_json = ?, updated_at = ?, revision = revision + 1,
1281
+ execution_owner = CASE WHEN ? IN (${sqlList(RECONCILABLE_STATUSES)}) THEN execution_owner ELSE NULL END
1282
+ WHERE session_id = ? AND task_id = ? AND revision = ?`,
1283
+ )
1284
+ .run(
1285
+ next.title,
1286
+ next.status,
1287
+ next.order,
1288
+ next.parentId ?? null,
1289
+ j(next.dependsOn ?? []),
1290
+ next.blockedReason ?? null,
1291
+ j(next.verification ?? null),
1292
+ j((next.evidence ?? []).slice(0, MAX_EVIDENCE)),
1293
+ j(next.acceptance ?? null),
1294
+ nowIso(),
1295
+ next.status,
1296
+ sessionId,
1297
+ taskId,
1298
+ current.revision,
1299
+ ).changes
1300
+ } catch (e) {
1301
+ throw new TaskError("TASK_PERSISTENCE_FAILURE", (e as Error).message)
1302
+ }
1303
+ if (changes !== 1) {
1304
+ // The predicate matched a revision read in this same transaction, so a
1305
+ // zero here means the row vanished under us (session deleted). Never a
1306
+ // silent success, and never a second write attempt.
1307
+ throw new TaskError(
1308
+ "TASK_STALE_REVISION",
1309
+ `${taskId} changed while the patch was being applied (expected revision ${current.revision})`,
1310
+ )
1311
+ }
1312
+ return this.getTask(sessionId, taskId)!
1313
+ })()
1314
+ }
1315
+ /** Readable alias for the layer above. */
1316
+ updateTask(sessionId: string, taskId: string, patch: TaskPatch, opts: PatchOptions = {}): Task {
1317
+ return this.patchTask(sessionId, taskId, patch, opts)
1318
+ }
1319
+
1320
+ // ── [Fase 3 / LOOP-INV-12, LOOP-G20, LOOP-G21] siklus VERIFYING ────────────
1321
+ //
1322
+ // Transisi eksplisit menuju `VERIFYING` dan penyelesaiannya ke `COMPLETED`
1323
+ // (bila bukti terverifikasi) atau `BLOCKED` (bila verifikasi / Tier 1 gagal),
1324
+ // sambil merekam bukti terstruktur pada `evidence_json`.
1325
+
1326
+ /**
1327
+ * Masuk ke status `VERIFYING` sebelum/selama verifikasi berjalan.
1328
+ * Mematuhi `TASK_EDGES`, CAS `expectedRevision`, dan lease `authorityToken`.
1329
+ */
1330
+ beginTaskVerification(sessionId: string, taskId: string, opts: PatchOptions = {}): Task {
1331
+ return this.patchTask(sessionId, taskId, { status: "VERIFYING", blockedReason: null }, opts)
1332
+ }
1333
+
1334
+ /**
1335
+ * Selesaikan verifikasi sebuah task dalam satu transaksi atomik:
1336
+ * - Jika task belum di `VERIFYING` (mis. `IN_PROGRESS`/`PENDING`) dan belum
1337
+ * terminal, transisikan dulu ke `VERIFYING` agar jalur siklus tetap utuh.
1338
+ * - Jika `outcome.ok === true`: `VERIFYING -> COMPLETED` + bukti `"verify"`.
1339
+ * - Jika `outcome.ok === false`: `VERIFYING -> BLOCKED` + alasan + bukti.
1340
+ */
1341
+ completeTaskVerification(
1342
+ sessionId: string,
1343
+ taskId: string,
1344
+ outcome: VerificationGateOutcome,
1345
+ opts: PatchOptions = {},
1346
+ ): Task {
1347
+ return this.withTransaction(() => {
1348
+ const current = this.getTask(sessionId, taskId)
1349
+ if (!current) throw new TaskError("TASK_NOT_FOUND", `no task ${taskId} in ${sessionId}`)
1350
+ let base = current
1351
+ let nextOpts = opts
1352
+ if (base.status !== "VERIFYING" && !isTerminalTaskStatus(base.status)) {
1353
+ base = this.patchTask(sessionId, taskId, { status: "VERIFYING", blockedReason: null }, opts)
1354
+ // Setelah langkah masuk VERIFYING menggunakan expectedRevision pemanggil,
1355
+ // langkah kedua mengunci revisi baru yang baru saja ditulis dalam txn ini.
1356
+ nextOpts = {
1357
+ ...opts,
1358
+ expectedRevision: base.revision,
1359
+ }
1360
+ }
1361
+ const ev = buildVerificationTaskEvidence(outcome)
1362
+ const mergedEvidence = [...(base.evidence ?? []).slice(-(MAX_EVIDENCE - 1)), ev]
1363
+ if (outcome.ok) {
1364
+ return this.patchTask(
1365
+ sessionId,
1366
+ taskId,
1367
+ {
1368
+ status: "COMPLETED",
1369
+ blockedReason: null,
1370
+ evidence: mergedEvidence,
1371
+ },
1372
+ nextOpts,
1373
+ )
1374
+ }
1375
+ const reason =
1376
+ outcome.summary?.trim().slice(0, 300) ||
1377
+ (outcome.verdict === "stale" ? "verification stale" : "verification failed")
1378
+ return this.patchTask(
1379
+ sessionId,
1380
+ taskId,
1381
+ {
1382
+ status: "BLOCKED",
1383
+ blockedReason: reason,
1384
+ evidence: mergedEvidence,
1385
+ },
1386
+ nextOpts,
1387
+ )
1388
+ })
1389
+ }
1390
+
1391
+ // ── PHASE 6B: scheduler substrate ──────────────────────────────────────────
1392
+ //
1393
+ // P1 (claim) and P3 (reconciliation) live here, inside the TaskStore
1394
+ // persistence boundary, for one reason: both need the revision predicate to be
1395
+ // part of the SQL mutation itself. Emulating either with
1396
+ // read -> compare in application code -> write without the predicate is
1397
+ // explicitly NOT a compare-and-swap and is not done.
1398
+ //
1399
+ // Neither primitive accepts a `TaskGraph`, a plan revision, a presentation
1400
+ // revision, or a timestamp as currency. The only currency is the per-task
1401
+ // `revision` column.
1402
+
1403
+ /**
1404
+ * P1: atomically claim one task for execution.
1405
+ *
1406
+ * The revision predicate and the claimable-status predicate are INSIDE the
1407
+ * single UPDATE statement, so SQLite decides the winner. This is the property
1408
+ * `patchTask`'s `expectedRevision` lacks.
1409
+ *
1410
+ * Claim contract (6A S4/S7): durable, revision-advancing, atomic, TaskStore
1411
+ * adjudicated, valid only from `CLAIMABLE_STATUSES`, never silently retried,
1412
+ * and never based on `TaskGraph.sourceMaxRevision`.
1413
+ *
1414
+ * A zero-rows-affected result is disambiguated with a follow-up READ so the
1415
+ * caller learns *which* precondition failed. That read is classification only
1416
+ * — it cannot turn a lost race into a win, because the mutation already
1417
+ * happened and already failed.
1418
+ */
1419
+ claimTask(
1420
+ sessionId: string,
1421
+ taskId: string,
1422
+ expectedRevision: number,
1423
+ /**
1424
+ * [PHASE 6T] `exclusive` adds the CAPACITY PREDICATE to the same statement
1425
+ * that performs the claim.
1426
+ *
1427
+ * [DESIGN DECISION] 6O selected this shape and it was never built: contention
1428
+ * was detected AFTER the claim, so a turn that never ran still consumed an
1429
+ * execution generation and left the task `IN_PROGRESS` and stranded. The fix
1430
+ * has to be atomic for the reason 6O gave — `exec_generation` is the unit that
1431
+ * must not be spent on a non-attempt, and a read-then-write check outside the
1432
+ * UPDATE would reopen exactly the window the revision predicate closes.
1433
+ *
1434
+ * The predicate is "no OTHER task in this session holds a LIVE Scheduler
1435
+ * execution", which is the Scheduler's own serial guarantee expressed durably,
1436
+ * so it holds across processes and not merely within one.
1437
+ *
1438
+ * [PHASE 6T][DESIGN DECISION] "LIVE" is not the same as "IN_PROGRESS", and
1439
+ * conflating them is a bug this predicate was written and then caught with.
1440
+ * After every completed turn the task deliberately REMAINS `IN_PROGRESS`
1441
+ * awaiting a verifier that does not exist yet (6N's "no verifier" limit), so
1442
+ * a naive `IN_PROGRESS` test finds a live execution forever and the Scheduler
1443
+ * can never run a second task. Live means the current generation's attempt has
1444
+ * not ended:
1445
+ *
1446
+ * attempt_generation IS NULL OR attempt_generation < exec_generation
1447
+ *
1448
+ * which is exactly the condition reconciliation already uses to tell a
1449
+ * crashed execution (REVERT) from finished work (LEAVE). Capacity and
1450
+ * recovery therefore read one fact, and cannot disagree.
1451
+ *
1452
+ * A crashed execution still occupies capacity until a cycle reconciles it —
1453
+ * which is correct: an execution of unknown liveness is not free capacity,
1454
+ * and `runCycle` reconciles before it selects.
1455
+ *
1456
+ * Off by default: every existing caller keeps its exact behaviour, and only a
1457
+ * caller that means to be exclusive asks for it.
1458
+ */
1459
+ opts: { readonly exclusive?: boolean } = {},
1460
+ ): {
1461
+ outcome: ClaimOutcome
1462
+ task: Task | null
1463
+ execGeneration: number
1464
+ /** [PHASE 6Q] Incarnation the claim was made under. 1 for an undeleted session. */
1465
+ sessionIncarnation: number
1466
+ } {
1467
+ if (!isTaskId(taskId)) throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${taskId}`)
1468
+ const db = handle(this.cwd)
1469
+ const statuses = sqlList(CLAIMABLE_STATUSES)
1470
+
1471
+ // THE revision predicate lives here, in SQL. One statement = one atomic
1472
+ // decision; there is no read-then-write window.
1473
+ //
1474
+ // [PHASE 6I] The execution generation is created by the SAME statement that
1475
+ // accepts the claim, so the two can never disagree and a rejected claim
1476
+ // cannot advance it. It is the only place in the entire store that
1477
+ // increments `exec_generation` - see the invariant at the column DDL.
1478
+ //
1479
+ // [PHASE 6P] `execution_owner = 'scheduler'` is set by that same statement,
1480
+ // for the same reason. The three facts that define a Scheduler execution -
1481
+ // accepted revision, new generation, durable ownership - are therefore
1482
+ // ATOMIC. There is no interleaving in which the row says "generation N
1483
+ // exists" while ownership still says "interactive/unknown", or vice versa,
1484
+ // and a rejected claim writes none of the three.
1485
+ const result = db
1486
+ .prepare(
1487
+ `UPDATE tasks
1488
+ SET status = 'IN_PROGRESS', updated_at = ?, revision = revision + 1,
1489
+ exec_generation = exec_generation + 1,
1490
+ execution_owner = 'scheduler'
1491
+ WHERE session_id = ? AND task_id = ? AND revision = ? AND status IN (${statuses})${
1492
+ opts.exclusive === true
1493
+ ? `
1494
+ AND NOT EXISTS (
1495
+ SELECT 1 FROM tasks AS busy
1496
+ WHERE busy.session_id = tasks.session_id
1497
+ AND busy.execution_owner = 'scheduler'
1498
+ AND busy.status = 'IN_PROGRESS'
1499
+ AND busy.exec_generation > 0
1500
+ AND (busy.attempt_generation IS NULL
1501
+ OR busy.attempt_generation < busy.exec_generation)
1502
+ AND busy.task_id <> tasks.task_id
1503
+ )`
1504
+ : ""
1505
+ }`,
1506
+ )
1507
+ .run(nowIso(), sessionId, taskId, expectedRevision)
1508
+
1509
+ if (result.changes === 1) {
1510
+ const lineage = this.getExecutionLineage(sessionId, taskId)
1511
+ return {
1512
+ outcome: "CLAIM_ACCEPTED",
1513
+ task: this.getTask(sessionId, taskId),
1514
+ execGeneration: lineage?.execGeneration ?? 0,
1515
+ // [PHASE 6Q] Read inside the same call so the Scheduler can present this
1516
+ // incarnation back at lineage-write time. A deletion between claim and
1517
+ // write moves it, and the write is then refused.
1518
+ sessionIncarnation: this.getSessionIncarnation(sessionId),
1519
+ }
1520
+ }
1521
+
1522
+ // Lost the race, or never was claimable. Classify for the caller. A rejected
1523
+ // claim creates NO generation: execGeneration reports the unchanged current
1524
+ // value so a caller can never mistake a rejection for a claim.
1525
+ const current = this.getTask(sessionId, taskId)
1526
+ const sessionIncarnation = this.getSessionIncarnation(sessionId)
1527
+ if (current === null) {
1528
+ return { outcome: "NOT_FOUND", task: null, execGeneration: 0, sessionIncarnation }
1529
+ }
1530
+ const lineage = this.getExecutionLineage(sessionId, taskId)
1531
+ const execGeneration = lineage?.execGeneration ?? 0
1532
+ if (current.revision !== expectedRevision) {
1533
+ return { outcome: "CLAIM_REJECTED_STALE", task: current, execGeneration, sessionIncarnation }
1534
+ }
1535
+ // [PHASE 6T] The row is claimable and the revision matched, so the ONLY
1536
+ // reason the UPDATE did not land is the capacity predicate. Classify it as
1537
+ // contention rather than lumping it in with WRONG_STATE: the caller must be
1538
+ // able to tell "someone else is running" (skip, no state spent) from
1539
+ // "this task is not claimable" (a different question entirely).
1540
+ if (opts.exclusive === true && this.hasLiveSchedulerClaim(sessionId, taskId)) {
1541
+ return { outcome: "CLAIM_REJECTED_BUSY", task: current, execGeneration, sessionIncarnation }
1542
+ }
1543
+ return { outcome: "WRONG_STATE", task: current, execGeneration, sessionIncarnation }
1544
+ }
1545
+
1546
+ /**
1547
+ * [PHASE 6T] Does another task in this session hold a LIVE Scheduler execution?
1548
+ *
1549
+ * "Live" means the current generation's attempt has not ended — see the note on
1550
+ * the capacity predicate. A task still `IN_PROGRESS` after a completed attempt
1551
+ * is awaiting verification, not occupying capacity.
1552
+ *
1553
+ * The read side of that predicate. It classifies a REJECTION; it is never used
1554
+ * to decide whether to attempt a claim, because only the atomic statement can
1555
+ * make that decision safely.
1556
+ */
1557
+ private hasLiveSchedulerClaim(sessionId: string, excludeTaskId: string): boolean {
1558
+ const row = handle(this.cwd)
1559
+ .prepare(
1560
+ `SELECT 1 FROM tasks
1561
+ WHERE session_id = ? AND execution_owner = 'scheduler'
1562
+ AND status = 'IN_PROGRESS' AND exec_generation > 0
1563
+ AND (attempt_generation IS NULL OR attempt_generation < exec_generation)
1564
+ AND task_id <> ?
1565
+ LIMIT 1`,
1566
+ )
1567
+ .get(sessionId, excludeTaskId)
1568
+ return row !== undefined && row !== null
1569
+ }
1570
+
1571
+ /**
1572
+ * P3: revert ONE stranded in-flight task, revision-safely.
1573
+ *
1574
+ * Deliberately single-task rather than bulk: a bulk revert cannot be made
1575
+ * atomic across rows, so a per-row revision predicate is the only way to
1576
+ * guarantee a newer writer is never clobbered (6B S-race case A/C).
1577
+ *
1578
+ * The caller MUST hold session ownership (see `task/session-ownership.ts`).
1579
+ * When `ownsSession` is false this returns `REFUSED_NO_OWNERSHIP` and mutates
1580
+ * nothing — reconciliation fails closed rather than guessing.
1581
+ *
1582
+ * Never deletes. Never touches `parentId` / `dependsOn` / `order`. Never
1583
+ * manufactures `verification` or `evidence`. Never reads a graph. Never
1584
+ * inspects message history or presentation events.
1585
+ */
1586
+ reconcileStranded(
1587
+ sessionId: string,
1588
+ taskId: string,
1589
+ expectedRevision: number,
1590
+ opts: { ownsSession: boolean },
1591
+ ): { outcome: ReconcileOutcome; task: Task | null } {
1592
+ if (!isTaskId(taskId)) throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${taskId}`)
1593
+ if (!opts.ownsSession) {
1594
+ // Fail closed. Uncertainty about ownership is not permission to act.
1595
+ return { outcome: "REFUSED_NO_OWNERSHIP", task: null }
1596
+ }
1597
+ const db = handle(this.cwd)
1598
+ const statuses = sqlList(RECONCILABLE_STATUSES)
1599
+
1600
+ // Sets status AND clears blockedReason is deliberately NOT done: a stranded
1601
+ // task's blockedReason is not the property being reconciled, and rewriting
1602
+ // it would destroy information the operator may need.
1603
+ // [PHASE 6P] Same contract as `reconcileIfNoCompletedAttempt` for ownership:
1604
+ // only durably Scheduler-owned in-flight state may be reverted, and
1605
+ // reverting releases ownership. This is the path `Scheduler.releaseClaim`
1606
+ // uses for a claim whose dispatch never established, so requiring ownership
1607
+ // here also stops this method from reverting a task whose claim has already
1608
+ // been released or was never ours.
1609
+ const result = db
1610
+ .prepare(
1611
+ `UPDATE tasks
1612
+ SET status = 'PENDING', updated_at = ?, revision = revision + 1,
1613
+ execution_owner = NULL
1614
+ WHERE session_id = ? AND task_id = ? AND revision = ? AND status IN (${statuses})
1615
+ AND execution_owner = 'scheduler' AND exec_generation > 0`,
1616
+ )
1617
+ .run(nowIso(), sessionId, taskId, expectedRevision)
1618
+
1619
+ if (result.changes === 1) {
1620
+ return { outcome: "RECONCILED", task: this.getTask(sessionId, taskId) }
1621
+ }
1622
+
1623
+ const current = this.getTask(sessionId, taskId)
1624
+ if (current === null) return { outcome: "NOT_FOUND", task: null }
1625
+ if (current.revision !== expectedRevision) {
1626
+ // Someone else moved it. Do not overwrite newer state.
1627
+ return { outcome: "REJECTED_STALE", task: current }
1628
+ }
1629
+ return { outcome: "NOT_STRANDED", task: current }
1630
+ }
1631
+
1632
+ /**
1633
+ * [PHASE 6I] Read the execution lineage of one task.
1634
+ *
1635
+ * Deliberately NOT part of the public `Task` shape: execution provenance is
1636
+ * not task state, and exposing it on `Task` would let it leak into TaskGraph,
1637
+ * readiness and presentation. It is reachable only through these accessors.
1638
+ *
1639
+ * Returns `null` for a task that does not exist. `attemptGeneration === null`
1640
+ * means "no attempt of the current generation has completed" - a meaningful
1641
+ * value, not an error.
1642
+ */
1643
+ getExecutionLineage(sessionId: string, taskId: string): ExecutionLineage | null {
1644
+ if (!isTaskId(taskId)) throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${taskId}`)
1645
+ const db = handle(this.cwd)
1646
+ const row = db
1647
+ .prepare(
1648
+ `SELECT exec_generation, attempt_generation FROM tasks WHERE session_id = ? AND task_id = ?`,
1649
+ )
1650
+ .get(sessionId, taskId) as
1651
+ | { exec_generation: number; attempt_generation: number | null }
1652
+ | null
1653
+ | undefined
1654
+ if (row === null || row === undefined) return null
1655
+ return { execGeneration: row.exec_generation, attemptGeneration: row.attempt_generation }
1656
+ }
1657
+
1658
+ /**
1659
+ * [PHASE 6P] Read EXECUTION OWNERSHIP for one task.
1660
+ *
1661
+ * Deliberately a SEPARATE accessor from `getExecutionLineage`, so the four
1662
+ * facts stay four facts: task state, execution ownership, execution generation,
1663
+ * attempt generation. Folding ownership into the lineage object would invite
1664
+ * exactly the collapse 6O rejected.
1665
+ *
1666
+ * Returns `null` for a task that does not exist (same convention as
1667
+ * `getExecutionLineage`). `executionOwner === null` on an existing task is a
1668
+ * MEANINGFUL value - "no Scheduler execution owns this task" - not an error.
1669
+ *
1670
+ * Reachable only here: ownership is execution state and must not leak into
1671
+ * `Task`, TaskGraph, readiness or presentation.
1672
+ */
1673
+ getExecutionOwnership(sessionId: string, taskId: string): ExecutionOwnership | null {
1674
+ if (!isTaskId(taskId)) throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${taskId}`)
1675
+ const db = handle(this.cwd)
1676
+ const row = db
1677
+ .prepare(`SELECT execution_owner FROM tasks WHERE session_id = ? AND task_id = ?`)
1678
+ .get(sessionId, taskId) as { execution_owner: ExecutionOwner | null } | null | undefined
1679
+ if (row === null || row === undefined) return null
1680
+ return { executionOwner: row.execution_owner }
1681
+ }
1682
+
1683
+ // ── [PHASE 6Q] SESSION INCARNATION ──────────────────────────────────────────
1684
+
1685
+ /**
1686
+ * [PHASE 6Q] A durable, monotonically increasing counter identifying WHICH
1687
+ * INCARNATION of a session id is current.
1688
+ *
1689
+ * WHY IT EXISTS (6N F2). `taskId` is allocated PER SESSION and restarts at `t1`,
1690
+ * so deleting a session and recreating it with the same id produces a session
1691
+ * whose task rows are *indistinguishable by id* from the deleted ones. An
1692
+ * execution that was still running against the DELETED incarnation therefore
1693
+ * holds a `(taskId, execGeneration)` pair that a FRESH claim in the RECREATED
1694
+ * session can legitimately match:
1695
+ *
1696
+ * delete session A -> recreate A -> new Scheduler claims new t1 (exec=1)
1697
+ * -> the OLD execution returns with (t1, execGeneration=1)
1698
+ * -> `WHERE exec_generation = 1` MATCHES THE NEW ROW
1699
+ *
1700
+ * Without a discriminator the old execution would stamp `attempt_generation` on
1701
+ * the new row, and that new claim would be treated as "already completed" and
1702
+ * never recovered. That is exactly the cross-generation effect 6Q must forbid.
1703
+ *
1704
+ * THE MINIMUM GUARD. The Scheduler reads the incarnation at CLAIM time and
1705
+ * passes it back at lineage-write time; the write is refused if the current
1706
+ * incarnation has moved. Deletion bumps the counter, which invalidates every
1707
+ * in-flight execution of that session id at once, in one durable write, with no
1708
+ * coordination and no cross-process signalling.
1709
+ *
1710
+ * Stored in `task_meta` in THIS database, so the counter and the task rows it
1711
+ * protects share a persistence domain and can be read and written under one
1712
+ * handle. It is NOT session state: it deliberately SURVIVES the session's own
1713
+ * deletion, because its entire job is to remember that a deletion happened.
1714
+ *
1715
+ * It is NOT a lease, lock, heartbeat, priority or completion claim. It grants no
1716
+ * authority; it only lets a late writer recognise that it is late.
1717
+ */
1718
+ getSessionIncarnation(sessionId: string): number {
1719
+ const db = handle(this.cwd)
1720
+ const row = db
1721
+ .prepare(`SELECT value FROM task_meta WHERE key = ?`)
1722
+ .get(incarnationKey(sessionId)) as { value: string } | null | undefined
1723
+ if (row === null || row === undefined) return 1
1724
+ const n = Number(row.value)
1725
+ return Number.isSafeInteger(n) && n > 0 ? n : 1
1726
+ }
1727
+
1728
+ /**
1729
+ * [PHASE 6Q] Invalidate every in-flight execution of this session id.
1730
+ *
1731
+ * Called by the canonical deletion operation BEFORE any row is removed, so that
1732
+ * an execution which returns after this point is refused rather than allowed to
1733
+ * write into a session that no longer exists - or into a later recreation of it.
1734
+ *
1735
+ * Idempotent-safe: bumping an already-bumped counter is harmless, and a session
1736
+ * that was never deleted keeps incarnation 1.
1737
+ */
1738
+ bumpSessionIncarnation(sessionId: string): number {
1739
+ const db = handle(this.cwd)
1740
+ const next = this.getSessionIncarnation(sessionId) + 1
1741
+ db.prepare(
1742
+ `INSERT INTO task_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
1743
+ ).run(incarnationKey(sessionId), String(next))
1744
+ return next
1745
+ }
1746
+
1747
+ /**
1748
+ * [PHASE 6I] Record that the execution attempt for one generation ended.
1749
+ *
1750
+ * This is the ONE durable fact the lineage design adds. It answers exactly one
1751
+ * question: "did the attempt for generation `execGeneration` reach its end?" It
1752
+ * is deliberately NOT:
1753
+ *
1754
+ * - a task status. `IN_PROGRESS` stays `IN_PROGRESS`; a returned turn is not
1755
+ * a verdict. EXECUTION != VERIFICATION != COMPLETION.
1756
+ * - a completion claim, a lock, a lease, a heartbeat, a retry counter, or an
1757
+ * attempt history. One generation is retained per task and nothing here
1758
+ * expires on a clock.
1759
+ * - a revision. `execGeneration` comes from the claim that ran, never from
1760
+ * the task's current revision - that conflation is 6G defect D1.
1761
+ *
1762
+ * The write is GUARDED on `exec_generation = ?`. If the generation moved while
1763
+ * the attempt was in flight the record would be misleading, so it is refused
1764
+ * rather than written.
1765
+ *
1766
+ * The task's durable status is NOT touched, and no other column is written.
1767
+ */
1768
+ recordAttemptReturned(
1769
+ sessionId: string,
1770
+ taskId: string,
1771
+ execGeneration: number,
1772
+ /**
1773
+ * [PHASE 6Q] The incarnation the caller claimed under. Omitted = "assume the
1774
+ * current one", which preserves the pre-6Q behaviour for any caller that does
1775
+ * not track incarnations; the Scheduler always supplies it.
1776
+ */
1777
+ sessionIncarnation?: number,
1778
+ ): AttemptRecordOutcome {
1779
+ if (!isTaskId(taskId)) throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${taskId}`)
1780
+ if (!Number.isSafeInteger(execGeneration) || execGeneration < 1) {
1781
+ throw new TaskError(
1782
+ "TASK_INVALID_ID",
1783
+ `execution generation must be a positive integer: ${execGeneration}`,
1784
+ )
1785
+ }
1786
+ const db = handle(this.cwd)
1787
+
1788
+ // [PHASE 6Q] THE INCARNATION GUARD MUST PRECEDE THE WRITE.
1789
+ //
1790
+ // Checking it afterwards is not a weaker check, it is a wrong one: the guarded
1791
+ // UPDATE can MATCH A ROW THAT BELONGS TO A DIFFERENT SESSION LIFETIME, because
1792
+ // `taskId` restarts at `t1` for every incarnation and a fresh claim also
1793
+ // starts at `exec_generation = 1`. Observed during 6Q: with the check after
1794
+ // the write, a delete + recreate + re-claim sequence returned RECORDED and
1795
+ // stamped `attempt_generation` onto the RECREATED row.
1796
+ //
1797
+ // The check and the write share one transaction, so no other process can bump
1798
+ // the incarnation between them.
1799
+ return db.transaction((): AttemptRecordOutcome => {
1800
+ if (sessionIncarnation !== undefined) {
1801
+ if (this.getSessionIncarnation(sessionId) !== sessionIncarnation) {
1802
+ return "SESSION_SUPERSEDED"
1803
+ }
1804
+ }
1805
+ let changes = 0
1806
+ try {
1807
+ changes = db
1808
+ .prepare(
1809
+ `UPDATE tasks
1810
+ SET attempt_generation = ?
1811
+ WHERE session_id = ? AND task_id = ? AND exec_generation = ?`,
1812
+ )
1813
+ .run(execGeneration, sessionId, taskId, execGeneration).changes
1814
+ } catch (e) {
1815
+ // Evidence that cannot be persisted is NOT a returned attempt. Never
1816
+ // swallow: converting this into "execution succeeded" would turn the crash
1817
+ // window into a silent permanent strand.
1818
+ throw new TaskError("TASK_PERSISTENCE_FAILURE", (e as Error).message)
1819
+ }
1820
+ if (changes === 1) return "RECORDED"
1821
+ // The guard did not match. Nothing was written, so 6I's protection holds:
1822
+ // an outcome is never attributed to a generation that is not current. These
1823
+ // are results, not throws, because a throw is what wedged the Scheduler
1824
+ // (6N F2).
1825
+ const current = this.getTask(sessionId, taskId)
1826
+ if (current === null) return "TASK_GONE"
1827
+ return "SUPERSEDED"
1828
+ })()
1829
+ }
1830
+
1831
+ /**
1832
+ * [PHASE 6I] Revert a stranded in-flight task, deciding strandedness by
1833
+ * EXECUTION LINEAGE rather than by revision.
1834
+ *
1835
+ * This replaces the 6F `reconcileStranded`-after-marker-read sequence. The
1836
+ * lineage predicate and the revert are ONE statement, so there is no
1837
+ * read-then-write window: a concurrent completion record cannot slip between
1838
+ * the decision and the mutation. That property was 6B's and 6G re-confirmed it
1839
+ * must not be regressed.
1840
+ *
1841
+ * The rule, exactly as 6H specified it:
1842
+ *
1843
+ * attempt_generation IS NULL -> STRANDED (never completed)
1844
+ * attempt_generation < exec_generation -> STRANDED (a later generation
1845
+ * superseded an earlier one; the
1846
+ * current one has no record)
1847
+ * attempt_generation = exec_generation -> not stranded
1848
+ * attempt_generation > exec_generation -> impossible -> THROW
1849
+ *
1850
+ * The `IS NULL` disjunct is explicit rather than a comparison because
1851
+ * `NULL < 0` is NULL, not true: a LEGACY-created `IN_PROGRESS` row that was
1852
+ * never claimed (`exec_generation = 0`, no attempt) must be reconciled.
1853
+ *
1854
+ * The relation is STRICTLY `<`, and that strictness is load-bearing twice over.
1855
+ * `<>` would wrongly match the impossible `attempt > exec` and silently revert
1856
+ * a row on corrupt data; `<` excludes it, so the row is left alone, `changes`
1857
+ * is 0, and the classification below raises instead of guessing. `<=` would be
1858
+ * worse still: it would match `attempt = exec`, i.e. a COMPLETED generation,
1859
+ * and reintroduce the 6D livelock in lineage form.
1860
+ *
1861
+ * Because `exec_generation` advances ONLY on an accepted claim, NO ordinary
1862
+ * mutation - title, order, dependency, parent, blockedReason, evidence,
1863
+ * verification, or status - can change the outcome of this rule. That is the
1864
+ * structural end of 6G D1.
1865
+ *
1866
+ * The caller MUST hold session ownership; without it this refuses and mutates
1867
+ * nothing (6B, unchanged). Never deletes. Never writes lineage. Never
1868
+ * manufactures verification or evidence. Never reads a graph.
1869
+ */
1870
+ reconcileIfNoCompletedAttempt(
1871
+ sessionId: string,
1872
+ taskId: string,
1873
+ expectedRevision: number,
1874
+ opts: { ownsSession: boolean },
1875
+ ): { outcome: LineageReconcileOutcome; task: Task | null } {
1876
+ if (!isTaskId(taskId)) throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${taskId}`)
1877
+ if (!opts.ownsSession) {
1878
+ // Fail closed. Uncertainty about ownership is not permission to act.
1879
+ return { outcome: "REFUSED_NO_OWNERSHIP", task: null }
1880
+ }
1881
+ const db = handle(this.cwd)
1882
+ const statuses = sqlList(RECONCILABLE_STATUSES)
1883
+
1884
+ // [PHASE 6P] `execution_owner = 'scheduler'` is a REQUIRED condition, and
1885
+ // `exec_generation > 0` is retained beside it as a co-condition.
1886
+ //
1887
+ // The owner condition is what makes 6N F1 impossible: a task the model marked
1888
+ // IN_PROGRESS without a claim is not Scheduler execution state, so it is
1889
+ // never reverted (6O H1). The exec condition is redundant while the column
1890
+ // exists - only `claimTask` sets ownership, and it always advances the
1891
+ // generation in the same statement - and is kept deliberately as a cheap
1892
+ // invariant: if a future writer ever sets ownership without a generation, this
1893
+ // still refuses rather than reverting.
1894
+ //
1895
+ // Reverting RELEASES ownership in the same statement, which is what makes
1896
+ // 6O H5 work: after this runs, the row is interactive state, and a later
1897
+ // user IN_PROGRESS write must survive the next reconcile.
1898
+ const result = db
1899
+ .prepare(
1900
+ `UPDATE tasks
1901
+ SET status = 'PENDING', updated_at = ?, revision = revision + 1,
1902
+ execution_owner = NULL
1903
+ WHERE session_id = ? AND task_id = ? AND revision = ? AND status IN (${statuses})
1904
+ AND execution_owner = 'scheduler' AND exec_generation > 0
1905
+ AND (attempt_generation IS NULL OR attempt_generation < exec_generation)`,
1906
+ )
1907
+ .run(nowIso(), sessionId, taskId, expectedRevision)
1908
+
1909
+ if (result.changes === 1) {
1910
+ return { outcome: "RECONCILED", task: this.getTask(sessionId, taskId) }
1911
+ }
1912
+
1913
+ // Zero changes: the lineage predicate said "not stranded", or the row moved
1914
+ // under us, or it is gone. One read classifies, exactly as 6B did.
1915
+ const current = this.getTask(sessionId, taskId)
1916
+ if (current === null) return { outcome: "NOT_FOUND", task: null }
1917
+ if (current.revision !== expectedRevision) {
1918
+ // Someone else moved it. Do not overwrite newer state.
1919
+ return { outcome: "REJECTED_STALE", task: current }
1920
+ }
1921
+ const lineage = this.getExecutionLineage(sessionId, taskId)
1922
+ if (lineage !== null && lineage.attemptGeneration !== null) {
1923
+ if (lineage.attemptGeneration > lineage.execGeneration) {
1924
+ // The recorded attempt names a generation NEWER than the current one.
1925
+ // No legitimate sequence produces this. Do not guess which side is wrong:
1926
+ // guessing either strands live work or re-runs finished work.
1927
+ throw new TaskError(
1928
+ "TASK_PERSISTENCE_FAILURE",
1929
+ `attempt generation ${lineage.attemptGeneration} exceeds execution generation ${lineage.execGeneration} for ${sessionId}/${taskId}`,
1930
+ )
1931
+ }
1932
+ return { outcome: "NOT_STRANDED", task: current }
1933
+ }
1934
+ // In flight with no completion record, yet the update matched nothing: the
1935
+ // row is not in a reconcilable status. Leave it alone.
1936
+ return { outcome: "NOT_STRANDED", task: current }
1937
+ }
1938
+
1939
+ /**
1940
+ * Delete one task. Used ONLY by compatibility: `deleteSession`.
1941
+ *
1942
+ * The model has no way to delete in Phase 1 (D7: explicit deletion is
1943
+ * deferred; cancellation happens through the `CANCELLED` status instead).
1944
+ */
1945
+ deleteTask(sessionId: string, taskId: string): boolean {
1946
+ if (!isTaskId(taskId)) throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${taskId}`)
1947
+ const db = handle(this.cwd)
1948
+ try {
1949
+ const r = db
1950
+ .prepare("DELETE FROM tasks WHERE session_id = ? AND task_id = ?")
1951
+ .run(sessionId, taskId)
1952
+ return r.changes > 0
1953
+ } catch (e) {
1954
+ throw new TaskError("TASK_PERSISTENCE_FAILURE", (e as Error).message)
1955
+ }
1956
+ }
1957
+
1958
+ /** Drop every task in one session. For `deleteSession`. */
1959
+ deleteSessionTasks(sessionId: string): number {
1960
+ const db = handle(this.cwd)
1961
+ try {
1962
+ return db.prepare("DELETE FROM tasks WHERE session_id = ?").run(sessionId).changes
1963
+ } catch (e) {
1964
+ throw new TaskError("TASK_PERSISTENCE_FAILURE", (e as Error).message)
1965
+ }
1966
+ }
1967
+
1968
+ // ── [P14] CROSS-SESSION UNFINISHED WORK ─────────────────────────────────────
1969
+ //
1970
+ // Dua operasi, satu batas: discovery READ-ONLY, dan transfer yang menuntut
1971
+ // otoritas eksplisit di KEDUA sesi. Keduanya hidup di TaskStore karena
1972
+ // TaskStore adalah satu-satunya otoritas status task; modul orkestrasi di
1973
+ // atasnya hanya mengakuisisi lease dan menerjemahkan hasil.
1974
+
1975
+ /**
1976
+ * [P14] Inventaris pekerjaan belum selesai di seluruh sesi WORKSPACE INI.
1977
+ *
1978
+ * Batas cakupan bukan pilihan bebas: `tasks.db` memang per-workspace
1979
+ * (`resolveLocalDbPath`), jadi query ini tidak bisa melihat sesi proyek lain.
1980
+ * Itu juga yang membuatnya aman dijalankan tanpa aturan merge lintas proyek.
1981
+ *
1982
+ * Operasi ini TIDAK PERNAH:
1983
+ * - mengakuisisi lease/otoritas,
1984
+ * - menulis baris, revisi, generasi, atau status,
1985
+ * - menyimpulkan bahwa item "boleh dilanjutkan" (itu keputusan scheduler
1986
+ * dengan continuity gate, bukan discovery).
1987
+ *
1988
+ * `transferredFromSessionId` diambil dari ledger agar operator bisa melihat
1989
+ * asal item yang sudah berpindah, tanpa menjadikan ledger sebagai otoritas
1990
+ * status kedua.
1991
+ */
1992
+ listUnfinishedWork(sessionId?: string): UnfinishedWorkItem[] {
1993
+ const db = handle(this.cwd)
1994
+ const statuses = sqlList(ADOPTABLE_STATUSES)
1995
+ const filter = sessionId === undefined ? "" : " AND t.session_id = ?"
1996
+ type OpenRow = TaskRow & {
1997
+ transferred_from_session_id: string | null
1998
+ transferred_at: string | null
1999
+ }
2000
+ const rows = db
2001
+ .prepare(
2002
+ `SELECT t.*,
2003
+ (SELECT tr.from_session_id
2004
+ FROM task_transfers tr
2005
+ WHERE tr.to_session_id = t.session_id AND tr.task_id = t.task_id
2006
+ ORDER BY tr.transferred_at DESC, tr.rowid DESC
2007
+ LIMIT 1) AS transferred_from_session_id,
2008
+ (SELECT tr.transferred_at
2009
+ FROM task_transfers tr
2010
+ WHERE tr.to_session_id = t.session_id AND tr.task_id = t.task_id
2011
+ ORDER BY tr.transferred_at DESC, tr.rowid DESC
2012
+ LIMIT 1) AS transferred_at
2013
+ FROM tasks t
2014
+ WHERE t.status IN (${statuses})${filter}
2015
+ ORDER BY t.session_id, t.task_order, t.task_id`,
2016
+ )
2017
+ .all(...(sessionId === undefined ? [] : [sessionId])) as OpenRow[]
2018
+
2019
+ const incarnations = new Map<string, number>()
2020
+ return rows.map((r) => {
2021
+ let incarnation = incarnations.get(r.session_id)
2022
+ if (incarnation === undefined) {
2023
+ incarnation = this.getSessionIncarnation(r.session_id)
2024
+ incarnations.set(r.session_id, incarnation)
2025
+ }
2026
+ return {
2027
+ sessionId: r.session_id,
2028
+ sessionIncarnation: incarnation,
2029
+ task: rowToTask(r),
2030
+ execGeneration: r.exec_generation,
2031
+ attemptGeneration: r.attempt_generation,
2032
+ // Nilai asing TIDAK dipromosikan menjadi "scheduler": discovery harus
2033
+ // gagal-jujur, bukan menciptakan pemilik yang tidak ada.
2034
+ executionOwner: r.execution_owner === "scheduler" ? "scheduler" : null,
2035
+ transferredFromSessionId: r.transferred_from_session_id ?? null,
2036
+ transferredAt: r.transferred_at ?? null,
2037
+ }
2038
+ })
2039
+ }
2040
+
2041
+ /**
2042
+ * [P14.0] Seluruh baris task lintas sesi — READ-ONLY, untuk inventaris.
2043
+ *
2044
+ * Tidak dipakai untuk keputusan status: TaskStore tetap satu-satunya
2045
+ * otoritas; inventaris hanya MENGHITUNG. Hasilnya tidak pernah menjadi
2046
+ * input jalur tulis, dan tidak menimpa semantik `listUnfinishedWork`
2047
+ * (yang tetap satu-satunya definisi "open").
2048
+ */
2049
+ listAllTasks(): { sessionId: string; task: Task }[] {
2050
+ const db = handle(this.cwd)
2051
+ const rows = db
2052
+ .prepare("SELECT * FROM tasks ORDER BY session_id, task_order, task_id")
2053
+ .all() as TaskRow[]
2054
+ return rows.map((r) => ({ sessionId: r.session_id, task: rowToTask(r) }))
2055
+ }
2056
+
2057
+ /**
2058
+ * [P14] Baca ledger transfer. Append-only dan read-only; dipakai audit/CLI.
2059
+ *
2060
+ * Tidak ada `DELETE`/`UPDATE` ledger di API publik: satu-satunya penulis
2061
+ * adalah `transferTaskAuthority`, di dalam transaksi yang sama dengan
2062
+ * perpindahan baris.
2063
+ */
2064
+ listTaskTransfers(
2065
+ filter: { fromSessionId?: string; toSessionId?: string; taskId?: string } = {},
2066
+ ): TaskTransfer[] {
2067
+ const db = handle(this.cwd)
2068
+ const clauses: string[] = []
2069
+ const params: string[] = []
2070
+ if (filter.fromSessionId !== undefined) {
2071
+ clauses.push("from_session_id = ?")
2072
+ params.push(filter.fromSessionId)
2073
+ }
2074
+ if (filter.toSessionId !== undefined) {
2075
+ clauses.push("to_session_id = ?")
2076
+ params.push(filter.toSessionId)
2077
+ }
2078
+ if (filter.taskId !== undefined) {
2079
+ clauses.push("task_id = ?")
2080
+ params.push(filter.taskId)
2081
+ }
2082
+ const where = clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : ""
2083
+ const rows = db
2084
+ .prepare(
2085
+ `SELECT transfer_id AS transferId,
2086
+ task_id AS taskId,
2087
+ from_session_id AS fromSessionId,
2088
+ from_incarnation AS fromIncarnation,
2089
+ to_session_id AS toSessionId,
2090
+ to_incarnation AS toIncarnation,
2091
+ expected_revision AS expectedRevision,
2092
+ new_revision AS newRevision,
2093
+ status AS status,
2094
+ exec_generation AS execGeneration,
2095
+ attempt_generation AS attemptGeneration,
2096
+ execution_owner AS executionOwner,
2097
+ transferred_at AS transferredAt
2098
+ FROM task_transfers${where}
2099
+ ORDER BY transferred_at, rowid`,
2100
+ )
2101
+ .all(...params) as Array<{
2102
+ transferId: string
2103
+ taskId: string
2104
+ fromSessionId: string
2105
+ fromIncarnation: number
2106
+ toSessionId: string
2107
+ toIncarnation: number
2108
+ expectedRevision: number
2109
+ newRevision: number
2110
+ status: string
2111
+ execGeneration: number
2112
+ attemptGeneration: number | null
2113
+ executionOwner: string | null
2114
+ transferredAt: string
2115
+ }>
2116
+ return rows.map((r) => ({
2117
+ ...r,
2118
+ executionOwner: r.executionOwner === "scheduler" ? "scheduler" : null,
2119
+ }))
2120
+ }
2121
+
2122
+ /**
2123
+ * [P14] Pindahkan SATU task unfinished ke sesi lain, dengan bukti otoritatif.
2124
+ *
2125
+ * Kontrak yang membuat operasi ini aman:
2126
+ *
2127
+ * 1. SATU transaksi. Pemeriksaan revisi/inkarnasi/status/relasi, UPDATE
2128
+ * baris, dan INSERT ledger berbagi transaksi yang sama. Kegagalan
2129
+ * ledger tidak boleh meninggalkan task sudah berpindah tanpa bukti.
2130
+ * 2. KEDUA lease harus dipegang token yang diberikan, diperiksa DI DALAM
2131
+ * transaksi. Lease sumber yang sudah diambil alih proses lain membuat
2132
+ * transfer gagal, bukan menebak bahwa pemilik lama sudah mati.
2133
+ * 3. Revisi + inkarnasi + generasi diperiksa ulang. Revisi TIDAK dipakai
2134
+ * sebagai pengganti lineage; `exec_generation`/`attempt_generation`
2135
+ * dipindahkan APA ADANYA sehingga target mewarisi bukti yang jujur.
2136
+ * 4. Task terminal/UNKNOWN tidak pernah diadopsi.
2137
+ * 5. Relasi hanya boleh menunjuk task yang SUDAH lebih dulu diadopsi dari
2138
+ * sesi sumber yang sama (dibuktikan ledger). Menunjuk id yang kebetulan
2139
+ * ada di target akan menyatukan dua tugas berbeda — dilarang.
2140
+ * 6. Task id TIDAK PERNAH diganti. Tabrakan id di target = tolak eksplisit,
2141
+ * bukan renumber diam-diam.
2142
+ *
2143
+ * Yang TIDAK dilakukan: tidak membuat generasi baru, tidak menandai selesai,
2144
+ * tidak menghapus attempt marker, tidak menyentuh jurnal runtime/child run.
2145
+ * Eksekusi baru hanya lahir dari claim baru di sesi tujuan, setelah
2146
+ * continuity gate memutuskan apakah retry aman.
2147
+ */
2148
+ transferTaskAuthority(req: TaskTransferRequest): TaskTransferResult {
2149
+ if (!isTaskId(req.taskId)) {
2150
+ throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${req.taskId}`)
2151
+ }
2152
+ const refuse = (
2153
+ outcome: TaskTransferOutcome,
2154
+ detail: string,
2155
+ task: Task | null = null,
2156
+ unresolvedRelations: readonly string[] = [],
2157
+ ): TaskTransferResult => ({ outcome, task, transfer: null, detail, unresolvedRelations })
2158
+
2159
+ if (req.fromSessionId.length === 0 || req.toSessionId.length === 0) {
2160
+ return refuse("NOT_FOUND", "source and target session ids must be non-empty")
2161
+ }
2162
+ if (req.fromSessionId === req.toSessionId) {
2163
+ return refuse("REFUSED_SELF_TRANSFER", "source and target sessions are identical")
2164
+ }
2165
+
2166
+ const db = handle(this.cwd)
2167
+ const now = req.now ?? Date.now()
2168
+ return db.transaction((): TaskTransferResult => {
2169
+ const sourceIncarnation = this.getSessionIncarnation(req.fromSessionId)
2170
+ if (sourceIncarnation !== req.fromIncarnation) {
2171
+ return refuse(
2172
+ "REJECTED_STALE_SOURCE_INCARNATION",
2173
+ `source incarnation moved: expected ${req.fromIncarnation}, found ${sourceIncarnation}`,
2174
+ )
2175
+ }
2176
+ const targetIncarnation = this.getSessionIncarnation(req.toSessionId)
2177
+ if (targetIncarnation !== req.toIncarnation) {
2178
+ return refuse(
2179
+ "REJECTED_STALE_TARGET_INCARNATION",
2180
+ `target incarnation moved: expected ${req.toIncarnation}, found ${targetIncarnation}`,
2181
+ )
2182
+ }
2183
+
2184
+ const raw = db
2185
+ .prepare("SELECT * FROM tasks WHERE session_id = ? AND task_id = ?")
2186
+ .get(req.fromSessionId, req.taskId) as TaskRow | null
2187
+ if (raw === null) {
2188
+ return refuse("NOT_FOUND", `no task ${req.taskId} in ${req.fromSessionId}`)
2189
+ }
2190
+ if (raw.revision !== req.expectedRevision) {
2191
+ return refuse(
2192
+ "REJECTED_STALE_REVISION",
2193
+ `${req.taskId} is at revision ${raw.revision}, expected ${req.expectedRevision}`,
2194
+ rowToTask(raw),
2195
+ )
2196
+ }
2197
+
2198
+ // Urutan sengaja: revisi dulu (murah, menentukan), lalu otoritas. Token
2199
+ // yang tidak memegang lease tidak boleh belajar status task lewat pesan
2200
+ // yang lebih spesifik.
2201
+ if (!this.holdsSessionAuthority(req.fromSessionId, req.sourceOwnerToken, now)) {
2202
+ return refuse(
2203
+ "REFUSED_NO_SOURCE_AUTHORITY",
2204
+ `source lease for ${req.fromSessionId} is not held by the presented token`,
2205
+ )
2206
+ }
2207
+ if (!this.holdsSessionAuthority(req.toSessionId, req.targetOwnerToken, now)) {
2208
+ return refuse(
2209
+ "REFUSED_NO_TARGET_AUTHORITY",
2210
+ `target lease for ${req.toSessionId} is not held by the presented token`,
2211
+ )
2212
+ }
2213
+
2214
+ if (!isTaskStatus(raw.status)) {
2215
+ return refuse("REFUSED_CORRUPT_STATE", `unknown task status: ${raw.status}`, rowToTask(raw))
2216
+ }
2217
+ if (!ADOPTABLE_STATUS_SET.has(raw.status)) {
2218
+ return refuse(
2219
+ "REFUSED_STATUS",
2220
+ `status ${raw.status} is terminal and cannot be adopted`,
2221
+ rowToTask(raw),
2222
+ )
2223
+ }
2224
+
2225
+ // Lineage yang tidak mungkin = HOLD, bukan tebakan. Sama seperti
2226
+ // reconcile: attempt > exec tidak punya penafsiran yang aman.
2227
+ if (!Number.isSafeInteger(raw.exec_generation) || raw.exec_generation < 0) {
2228
+ return refuse("REFUSED_CORRUPT_STATE", "exec_generation is not a non-negative integer")
2229
+ }
2230
+ if (
2231
+ raw.attempt_generation !== null &&
2232
+ (!Number.isSafeInteger(raw.attempt_generation) || raw.attempt_generation < 0)
2233
+ ) {
2234
+ return refuse("REFUSED_CORRUPT_STATE", "attempt_generation is not a non-negative integer")
2235
+ }
2236
+ if (raw.attempt_generation !== null && raw.attempt_generation > raw.exec_generation) {
2237
+ return refuse(
2238
+ "REFUSED_CORRUPT_STATE",
2239
+ `attempt_generation ${raw.attempt_generation} exceeds exec_generation ${raw.exec_generation}`,
2240
+ )
2241
+ }
2242
+ if (raw.attempt_generation !== null && raw.exec_generation === 0) {
2243
+ return refuse(
2244
+ "REFUSED_CORRUPT_STATE",
2245
+ "attempt marker exists without an execution generation",
2246
+ )
2247
+ }
2248
+ if (raw.execution_owner !== null && raw.execution_owner !== "scheduler") {
2249
+ return refuse("REFUSED_CORRUPT_STATE", `unknown execution_owner: ${raw.execution_owner}`)
2250
+ }
2251
+ if (raw.execution_owner === "scheduler") {
2252
+ if (raw.status !== "IN_PROGRESS" && raw.status !== "VERIFYING") {
2253
+ return refuse(
2254
+ "REFUSED_CORRUPT_STATE",
2255
+ `scheduler ownership is inconsistent with status ${raw.status}`,
2256
+ )
2257
+ }
2258
+ if (raw.exec_generation < 1) {
2259
+ return refuse("REFUSED_CORRUPT_STATE", "scheduler ownership without a claim generation")
2260
+ }
2261
+ }
2262
+
2263
+ // Relasi harus menunjuk task yang SUDAH berpindah dari sumber yang sama.
2264
+ // Keberadaan id semata tidak cukup: id task berulang per sesi, jadi id
2265
+ // yang sama di target bisa merupakan tugas yang sama sekali berbeda.
2266
+ const deps = parseStringArrayStrict(raw.depends_on_json)
2267
+ if (deps === null) {
2268
+ return refuse("REFUSED_CORRUPT_STATE", "depends_on_json is not a string array")
2269
+ }
2270
+ const relations = new Set<string>()
2271
+ if (raw.parent_id !== null) relations.add(raw.parent_id)
2272
+ for (const d of deps) relations.add(d)
2273
+ const unresolved: string[] = []
2274
+ const relationExistsInTarget = db.prepare(
2275
+ "SELECT 1 FROM tasks WHERE session_id = ? AND task_id = ?",
2276
+ )
2277
+ const relationWasAdopted = db.prepare(
2278
+ `SELECT 1 FROM task_transfers
2279
+ WHERE from_session_id = ? AND to_session_id = ? AND task_id = ?
2280
+ LIMIT 1`,
2281
+ )
2282
+ for (const relation of relations) {
2283
+ if (!isTaskId(relation) || relation === req.taskId) {
2284
+ return refuse("REFUSED_CORRUPT_STATE", `invalid or self relation: ${relation}`)
2285
+ }
2286
+ const exists = relationExistsInTarget.get(req.toSessionId, relation)
2287
+ if (exists === undefined || exists === null) {
2288
+ unresolved.push(relation)
2289
+ continue
2290
+ }
2291
+ const adopted = relationWasAdopted.get(req.fromSessionId, req.toSessionId, relation)
2292
+ if (adopted === undefined || adopted === null) unresolved.push(relation)
2293
+ }
2294
+ if (unresolved.length > 0) {
2295
+ return refuse(
2296
+ "REFUSED_UNRESOLVED_RELATION",
2297
+ `relations must be adopted first from ${req.fromSessionId}: ${unresolved.join(", ")}`,
2298
+ rowToTask(raw),
2299
+ unresolved,
2300
+ )
2301
+ }
2302
+
2303
+ // Tabrakan id adalah penolakan eksplisit. Renumber akan mengubah identitas
2304
+ // yang dipegang evidence/dependency dan menyembunyikan konflik.
2305
+ const collision = db
2306
+ .prepare("SELECT 1 FROM tasks WHERE session_id = ? AND task_id = ?")
2307
+ .get(req.toSessionId, req.taskId)
2308
+ if (collision !== undefined && collision !== null) {
2309
+ return refuse(
2310
+ "REFUSED_TARGET_ID_CONFLICT",
2311
+ `${req.taskId} already exists in ${req.toSessionId}; ids are never renumbered`,
2312
+ rowToTask(raw),
2313
+ )
2314
+ }
2315
+
2316
+ // Posisi tampilan di target: append. Urutan bukan identitas dan bukan
2317
+ // dependency; menyalin urutan sumber bisa membuat dua baris berbagi
2318
+ // nomor yang sama tanpa alasan.
2319
+ const maxRow = db
2320
+ .prepare("SELECT MAX(task_order) AS m FROM tasks WHERE session_id = ?")
2321
+ .get(req.toSessionId) as { m: number | null } | null
2322
+ const nextOrder = (maxRow?.m ?? 0) + 1
2323
+ const transferredAt = nowIso()
2324
+
2325
+ // SATU UPDATE: seluruh kolom dipertahankan; hanya namespace, posisi
2326
+ // tampilan, revisi (mutasi nyata), dan timestamp yang berubah. Lineage
2327
+ // dan status TIDAK disentuh.
2328
+ const moved = db
2329
+ .prepare(
2330
+ `UPDATE tasks
2331
+ SET session_id = ?, task_order = ?, revision = revision + 1, updated_at = ?
2332
+ WHERE session_id = ? AND task_id = ? AND revision = ?`,
2333
+ )
2334
+ .run(
2335
+ req.toSessionId,
2336
+ nextOrder,
2337
+ transferredAt,
2338
+ req.fromSessionId,
2339
+ req.taskId,
2340
+ req.expectedRevision,
2341
+ )
2342
+ if (moved.changes !== 1) {
2343
+ // Normalnya mustahil di dalam transaksi; tetap ditangani sebagai
2344
+ // klasifikasi, bukan dianggap sukses.
2345
+ return refuse("REJECTED_STALE_REVISION", "task moved while transfer was being prepared")
2346
+ }
2347
+
2348
+ const transfer: TaskTransfer = {
2349
+ transferId: randomUUID(),
2350
+ taskId: req.taskId,
2351
+ fromSessionId: req.fromSessionId,
2352
+ fromIncarnation: req.fromIncarnation,
2353
+ toSessionId: req.toSessionId,
2354
+ toIncarnation: req.toIncarnation,
2355
+ expectedRevision: req.expectedRevision,
2356
+ newRevision: req.expectedRevision + 1,
2357
+ status: raw.status,
2358
+ execGeneration: raw.exec_generation,
2359
+ attemptGeneration: raw.attempt_generation,
2360
+ executionOwner: raw.execution_owner === "scheduler" ? "scheduler" : null,
2361
+ transferredAt,
2362
+ }
2363
+ try {
2364
+ db.prepare(
2365
+ `INSERT INTO task_transfers
2366
+ (transfer_id, task_id, from_session_id, from_incarnation, to_session_id,
2367
+ to_incarnation, expected_revision, new_revision, status, exec_generation,
2368
+ attempt_generation, execution_owner, transferred_at)
2369
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2370
+ ).run(
2371
+ transfer.transferId,
2372
+ transfer.taskId,
2373
+ transfer.fromSessionId,
2374
+ transfer.fromIncarnation,
2375
+ transfer.toSessionId,
2376
+ transfer.toIncarnation,
2377
+ transfer.expectedRevision,
2378
+ transfer.newRevision,
2379
+ transfer.status,
2380
+ transfer.execGeneration,
2381
+ transfer.attemptGeneration,
2382
+ transfer.executionOwner,
2383
+ transfer.transferredAt,
2384
+ )
2385
+ } catch (e) {
2386
+ // Jangan telan: transaksi akan rollback, dan pesan ini adalah bukti
2387
+ // bahwa transfer TIDAK berlaku.
2388
+ throw new TaskError(
2389
+ "TASK_PERSISTENCE_FAILURE",
2390
+ `transfer ledger write failed: ${(e as Error).message}`,
2391
+ )
2392
+ }
2393
+
2394
+ return {
2395
+ outcome: "TRANSFERRED",
2396
+ task: this.getTask(req.toSessionId, req.taskId),
2397
+ transfer,
2398
+ detail: `moved ${req.taskId} from ${req.fromSessionId} to ${req.toSessionId}`,
2399
+ unresolvedRelations: [],
2400
+ }
2401
+ })()
2402
+ }
2403
+
2404
+ /**
2405
+ * [P14.3] Baca ledger dedup. Append-only dan read-only; dipakai audit/CLI.
2406
+ */
2407
+ listTaskMerges(
2408
+ filter: { sessionId?: string; survivorId?: string; duplicateId?: string } = {},
2409
+ ): TaskMerge[] {
2410
+ const db = handle(this.cwd)
2411
+ const clauses: string[] = []
2412
+ const params: string[] = []
2413
+ if (filter.sessionId !== undefined) {
2414
+ clauses.push("session_id = ?")
2415
+ params.push(filter.sessionId)
2416
+ }
2417
+ if (filter.survivorId !== undefined) {
2418
+ clauses.push("survivor_id = ?")
2419
+ params.push(filter.survivorId)
2420
+ }
2421
+ if (filter.duplicateId !== undefined) {
2422
+ clauses.push("duplicate_id = ?")
2423
+ params.push(filter.duplicateId)
2424
+ }
2425
+ const where = clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : ""
2426
+ const rows = db
2427
+ .prepare(
2428
+ `SELECT merge_id AS mergeId,
2429
+ session_id AS sessionId,
2430
+ survivor_id AS survivorId,
2431
+ duplicate_id AS duplicateId,
2432
+ evidence AS evidence,
2433
+ survivor_status AS survivorStatus,
2434
+ duplicate_status AS duplicateStatus,
2435
+ duplicate_revision AS duplicateRevision,
2436
+ merged_at AS mergedAt
2437
+ FROM task_merges${where}
2438
+ ORDER BY merged_at, rowid`,
2439
+ )
2440
+ .all(...params) as TaskMerge[]
2441
+ return rows
2442
+ }
2443
+
2444
+ /**
2445
+ * [P14.3] Deklarasikan EKSPLISIT bahwa satu task adalah duplikat unit kerja
2446
+ * dari task lain di SESI YANG SAMA, lalu tutup duplikat sebagai CANCELLED.
2447
+ *
2448
+ * Kontrak yang membuat operasi ini aman:
2449
+ *
2450
+ * 1. EVIDENCE WAJIB. Kemiripan judul bukan bukti — operator menulis
2451
+ * alasannya dan teks itu masuk ledger utuh. Tidak ada jalur otomatis
2452
+ * ke fungsi ini (proyeksi hanya MENANDAI kandidat serupa sebagai
2453
+ * UNPROVEN; ia tidak pernah menyatukan).
2454
+ * 2. Duplikat ditutup CANCELLED, BUKAN COMPLETED. "Sudah dikerjakan di
2455
+ * task lain" adalah keputusan operator; menulis COMPLETED akan menjadi
2456
+ * inferisi penyelesaian yang dilarang P14. CANCELLED = unit ini
2457
+ * ditarik sebagai kerja terpisah, status kanonik tetap jujur.
2458
+ * 3. Penulisan status lewat `patchTask` — penulis lifecycle yang SAMA
2459
+ * dengan jalur model/operator (revisi maju, ownership dilepas saat
2460
+ * keluar dari status in-flight). Tidak ada jalur tulis kedua.
2461
+ * 4. SATU transaksi (`withTransaction`): patch + INSERT ledger berjalan
2462
+ * bersama. Kegagalan ledger = status duplikat ikut rollback.
2463
+ * 5. Duplikat terminal ditolak: pekerjaan yang sudah ditutup tidak
2464
+ * dibuka ulang hanya untuk ditutup lagi. Survivor BOLEH terminal —
2465
+ * kasus klasik dedup adalah "task pending ini ternyata sudah
2466
+ * dikerjakan task yang selesai".
2467
+ * 6. Antar-sesi ditolak: pindahkan otoritasnya dulu lewat
2468
+ * `transferTaskAuthority` (adopsi), baru merge di satu namespace.
2469
+ *
2470
+ * Pembalikan kesalahan tetap jujur: ledger append-only (deklarasi tetap
2471
+ * tercatat selamanya), dan status kini-duplikat boleh dibuka kembali
2472
+ * operator lewat penulisan lifecycle biasa — status saat itulah kebenaran,
2473
+ * ledger hanyalah sejarah keputusan.
2474
+ */
2475
+ declareTaskDuplicate(req: TaskDuplicateRequest): TaskDuplicateResult {
2476
+ const refuse = (
2477
+ outcome: TaskDuplicateOutcome,
2478
+ detail: string,
2479
+ survivor: Task | null = null,
2480
+ ): TaskDuplicateResult => ({
2481
+ outcome,
2482
+ detail,
2483
+ duplicate: null,
2484
+ survivor,
2485
+ merge: null,
2486
+ })
2487
+
2488
+ if (!isTaskId(req.survivorId) || !isTaskId(req.duplicateId)) {
2489
+ throw new TaskError(
2490
+ "TASK_INVALID_ID",
2491
+ `not canonical ids: ${req.survivorId}/${req.duplicateId}`,
2492
+ )
2493
+ }
2494
+ if (req.survivorId === req.duplicateId) {
2495
+ return refuse("REFUSED_SELF_MERGE", "a task cannot be a duplicate of itself")
2496
+ }
2497
+ const evidence = req.evidence.trim()
2498
+ if (evidence.length === 0) {
2499
+ return refuse(
2500
+ "REFUSED_NO_EVIDENCE",
2501
+ "dedup requires operator evidence — similar wording is not proof",
2502
+ )
2503
+ }
2504
+ const survivor = this.getTask(req.sessionId, req.survivorId)
2505
+ if (survivor === null) {
2506
+ return refuse("NOT_FOUND", `no task ${req.survivorId} in ${req.sessionId}`)
2507
+ }
2508
+ const duplicate = this.getTask(req.sessionId, req.duplicateId)
2509
+ if (duplicate === null) {
2510
+ return refuse("NOT_FOUND", `no task ${req.duplicateId} in ${req.sessionId}`, survivor)
2511
+ }
2512
+ if (duplicate.status === "COMPLETED" || duplicate.status === "CANCELLED") {
2513
+ return refuse(
2514
+ "REFUSED_TERMINAL_DUPLICATE",
2515
+ `${req.duplicateId} is already ${duplicate.status} — closed work is never reopened to be closed again`,
2516
+ survivor,
2517
+ )
2518
+ }
2519
+ if (req.expectedRevision !== undefined && req.expectedRevision !== duplicate.revision) {
2520
+ return refuse(
2521
+ "REJECTED_STALE_REVISION",
2522
+ `${req.duplicateId} is at revision ${duplicate.revision}, expected ${req.expectedRevision}`,
2523
+ survivor,
2524
+ )
2525
+ }
2526
+
2527
+ // SATU transaksi: patchTask (penulis lifecycle yang sudah ada) + ledger
2528
+ // digabung oleh boundary Phase 4A.2 — nested db.transaction di bun adalah
2529
+ // savepoint yang bergabung, bukan transaksi terpisah.
2530
+ return this.withTransaction((): TaskDuplicateResult => {
2531
+ // Baca ulang DI DALAM transaksi: dunia boleh bergerak antara
2532
+ // pemeriksaan di atas dan titik tulis.
2533
+ const current = this.getTask(req.sessionId, req.duplicateId)
2534
+ if (current === null) {
2535
+ return refuse("NOT_FOUND", `${req.duplicateId} vanished while merge was prepared`)
2536
+ }
2537
+ if (current.status === "COMPLETED" || current.status === "CANCELLED") {
2538
+ return refuse(
2539
+ "REFUSED_TERMINAL_DUPLICATE",
2540
+ `${req.duplicateId} became ${current.status} while merge was prepared`,
2541
+ )
2542
+ }
2543
+ const survivorNow = this.getTask(req.sessionId, req.survivorId)
2544
+ if (survivorNow === null) {
2545
+ return refuse("NOT_FOUND", `${req.survivorId} vanished while merge was prepared`)
2546
+ }
2547
+ let patched: Task
2548
+ try {
2549
+ patched = this.patchTask(
2550
+ req.sessionId,
2551
+ req.duplicateId,
2552
+ { status: "CANCELLED" },
2553
+ req.expectedRevision !== undefined ? { expectedRevision: req.expectedRevision } : {},
2554
+ )
2555
+ } catch (e) {
2556
+ // Stale di jendela race = klasifikasi, bukan crash. Error TaskStore
2557
+ // lain (persistence, dependency) tetap dilempar — jangan ditelan.
2558
+ if (e instanceof TaskError && e.code === "TASK_STALE_REVISION") {
2559
+ return refuse(
2560
+ "REJECTED_STALE_REVISION",
2561
+ `${req.duplicateId} moved while merge was being prepared`,
2562
+ survivorNow,
2563
+ )
2564
+ }
2565
+ throw e
2566
+ }
2567
+
2568
+ const merge: TaskMerge = {
2569
+ mergeId: randomUUID(),
2570
+ sessionId: req.sessionId,
2571
+ survivorId: req.survivorId,
2572
+ duplicateId: req.duplicateId,
2573
+ evidence,
2574
+ survivorStatus: survivorNow.status,
2575
+ duplicateStatus: patched.status,
2576
+ duplicateRevision: patched.revision,
2577
+ mergedAt: patched.updatedAt,
2578
+ }
2579
+ const db = handle(this.cwd)
2580
+ try {
2581
+ db.prepare(
2582
+ `INSERT INTO task_merges
2583
+ (merge_id, session_id, survivor_id, duplicate_id, evidence,
2584
+ survivor_status, duplicate_status, duplicate_revision, merged_at)
2585
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2586
+ ).run(
2587
+ merge.mergeId,
2588
+ merge.sessionId,
2589
+ merge.survivorId,
2590
+ merge.duplicateId,
2591
+ merge.evidence,
2592
+ merge.survivorStatus,
2593
+ merge.duplicateStatus,
2594
+ merge.duplicateRevision,
2595
+ merge.mergedAt,
2596
+ )
2597
+ } catch (e) {
2598
+ throw new TaskError(
2599
+ "TASK_PERSISTENCE_FAILURE",
2600
+ `merge ledger write failed: ${(e as Error).message}`,
2601
+ )
2602
+ }
2603
+ return {
2604
+ outcome: "DECLARED",
2605
+ duplicate: patched,
2606
+ survivor: this.getTask(req.sessionId, req.survivorId),
2607
+ merge,
2608
+ detail: `closed ${req.duplicateId} as duplicate of ${req.survivorId} (CANCELLED, not COMPLETED)`,
2609
+ }
2610
+ })
2611
+ }
2612
+
2613
+ // ── meta / migration ──────────────────────────────────────────────────────
2614
+
2615
+ getMeta(key: string): string | null {
2616
+ const db = handle(this.cwd)
2617
+ const row = db.prepare("SELECT value FROM task_meta WHERE key = ?").get(key) as {
2618
+ value: string
2619
+ } | null
2620
+ return row?.value ?? null
2621
+ }
2622
+
2623
+ setMeta(key: string, value: string): void {
2624
+ const db = handle(this.cwd)
2625
+ db.prepare("INSERT OR REPLACE INTO task_meta (key, value) VALUES (?, ?)").run(key, value)
2626
+ }
2627
+
2628
+ /** Sessions whose data has already been imported from a legacy file,
2629
+ * together with the source fingerprint used. Used by migration idempotency. */
2630
+ migrationStamp(sessionId: string): string | null {
2631
+ return this.getMeta(`migrated:${sessionId}`)
2632
+ }
2633
+
2634
+ markMigrated(sessionId: string, digest: string): void {
2635
+ this.setMeta(`migrated:${sessionId}`, digest)
2636
+ }
2637
+
2638
+ dataVersion(): number {
2639
+ const raw = this.getMeta("data_version")
2640
+ const n = raw ? Number(raw) : NaN
2641
+ return Number.isFinite(n) ? n : 0
2642
+ }
2643
+
2644
+ ensureDataVersion(): number {
2645
+ const v = this.dataVersion()
2646
+ if (v === 0) this.setMeta("data_version", String(TASK_DATA_VERSION))
2647
+ if (v > TASK_DATA_VERSION) {
2648
+ throw new TaskError(
2649
+ "TASK_MIGRATION_FAILURE",
2650
+ `data written by newer version (${v} > ${TASK_DATA_VERSION}); refusing to downgrade`,
2651
+ )
2652
+ }
2653
+ return TASK_DATA_VERSION
2654
+ }
2655
+
2656
+ /** Close the handle. For tests and explicit shutdown only. */
2657
+ static close(cwd?: string): void {
2658
+ const p = dbFile(cwd)
2659
+ // Closing the connection under an open transaction would abandon a
2660
+ // half-applied unit of work with no way to roll it back.
2661
+ assertNoOpenTx(p, "close the store")
2662
+ const db = handles.get(p)
2663
+ if (db) {
2664
+ try {
2665
+ db.close()
2666
+ } catch {}
2667
+ handles.delete(p)
2668
+ initialized.delete(p)
2669
+ }
2670
+ }
2671
+
2672
+ // ── transaction boundary (Phase 4A.2) ─────────────────────────────────────
2673
+
2674
+ /**
2675
+ * Run `fn` inside a single SQLite transaction owned by THIS TaskStore.
2676
+ *
2677
+ * WHY THIS EXISTS. A caller could previously open its own `db.transaction()`
2678
+ * and call TaskStore methods inside it, and get atomicity that was silently
2679
+ * false: TaskStore holds its own cached `Database` handle, so the caller's
2680
+ * transaction and TaskStore's writes were two different connections and
2681
+ * committed independently. Measured: a forced throw rolled back nothing.
2682
+ *
2683
+ * WHY THE CALLBACK RECEIVES `this`. The transaction is opened on the very same
2684
+ * cached handle that every TaskStore method obtains from `handle(cwd)`, so
2685
+ * there is exactly ONE authoritative connection per path. Every method called
2686
+ * on `tx` therefore participates in this transaction by construction - there
2687
+ * is no "escaped" path, and no second allocator or duplicated SQL.
2688
+ *
2689
+ * NESTING. `bun:sqlite` implements a nested `db.transaction` as a savepoint
2690
+ * that joins the enclosing transaction rather than committing independently
2691
+ * (measured). So `createTask`/`patchTask`, which each open their own
2692
+ * transaction, compose correctly inside this one with no extra machinery.
2693
+ *
2694
+ * BUSY HANDLING. Deliberately unchanged: this adds no new retry. Contention
2695
+ * is handled by the connection's existing `busy_timeout` pragma, and the
2696
+ * bounded per-statement retry remains scoped to schema DDL exactly as in
2697
+ * Phase 1. No unbounded retry is introduced here.
2698
+ *
2699
+ * Errors from `fn` propagate unchanged after rollback.
2700
+ */
2701
+ withTransaction<T>(fn: (tx: TaskStore) => T): T {
2702
+ const p = dbFile(this.cwd)
2703
+ const db = handle(this.cwd)
2704
+ txDepth.set(p, (txDepth.get(p) ?? 0) + 1)
2705
+ try {
2706
+ return db.transaction(() => fn(this))()
2707
+ } finally {
2708
+ const d = (txDepth.get(p) ?? 1) - 1
2709
+ if (d <= 0) txDepth.delete(p)
2710
+ else txDepth.set(p, d)
2711
+ }
2712
+ }
2713
+
2714
+ /** True when a `withTransaction` is currently in flight for this store's
2715
+ * database. Diagnostics only; the guard above is what enforces safety. */
2716
+ inTransaction(): boolean {
2717
+ return (txDepth.get(dbFile(this.cwd)) ?? 0) > 0
2718
+ }
2719
+ // ── [PHASE 6X] session-level autonomous authority (6W ADR-20/21) ─────────────
2720
+ //
2721
+ // [DESIGN DECISION] The lease is a SESSION fact, kept deliberately separate from
2722
+ // the tasks table and from 6Q's per-task lineage. The two layers never read each
2723
+ // other, so authority can never be half-updated alongside a task row.
2724
+ //
2725
+ // Its existence is NOT evidence of liveness - it is a bounded claim on the right
2726
+ // to schedule. That distinction is the whole fix for 6V FINDING-02, which needed
2727
+ // two reconcilers to coexist on one session so one could revert the other's live
2728
+ // execution. Exactly one of them can hold this row at a time.
2729
+
2730
+ /**
2731
+ * Read the authority record for a session's current incarnation, or null.
2732
+ *
2733
+ * [DESIGN DECISION] Fail-closed on an undecodable row: it reads as "no authority
2734
+ * exists", the safe direction for a caller deciding whether it may schedule. It is
2735
+ * NOT treated as free for a *renewal*, which additionally requires our own token.
2736
+ */
2737
+ getSessionAuthority(sessionId: string, incarnation?: number): SessionAuthority | null {
2738
+ const inc = incarnation ?? this.getSessionIncarnation(sessionId)
2739
+ const row = handle(this.cwd)
2740
+ .prepare(
2741
+ `SELECT owner_token AS ownerToken,
2742
+ owner_pid AS ownerPid,
2743
+ acquired_at AS acquiredAt,
2744
+ lease_expires_at AS leaseExpiresAt,
2745
+ incarnation
2746
+ FROM session_authority
2747
+ WHERE session_id = ? AND incarnation = ?`,
2748
+ )
2749
+ .get(sessionId, inc) as Record<string, unknown> | undefined | null
2750
+ if (row === undefined || row === null) return null
2751
+ return {
2752
+ sessionId,
2753
+ incarnation: Number(row.incarnation),
2754
+ ownerToken: String(row.ownerToken),
2755
+ ownerPid: Number(row.ownerPid),
2756
+ acquiredAt: Number(row.acquiredAt),
2757
+ leaseExpiresAt: Number(row.leaseExpiresAt),
2758
+ }
2759
+ }
2760
+
2761
+ /**
2762
+ * Take the lease, or renew it, in ONE atomic statement.
2763
+ *
2764
+ * [DESIGN DECISION] This is the mutual-exclusion primitive, so it must be one SQL
2765
+ * statement. Split into a read-then-write it would reintroduce precisely the race
2766
+ * F02 needed, and a concurrent pair of acquirers would then have two winners.
2767
+ *
2768
+ * The `ON CONFLICT ... WHERE` clause is the whole trick: the upsert lands only when
2769
+ * no row exists, or when the existing row is still OURS. A live lease belonging to
2770
+ * somebody else fails the WHERE, is left untouched, and `changes` reports 0.
2771
+ */
2772
+ acquireSessionAuthority(
2773
+ sessionId: string,
2774
+ ownerToken: string,
2775
+ leaseMs: number,
2776
+ now = Date.now(),
2777
+ ): "ACQUIRED" | "REFUSED_LEASE_HELD" {
2778
+ const inc = this.getSessionIncarnation(sessionId)
2779
+ const result = handle(this.cwd)
2780
+ .prepare(
2781
+ `INSERT INTO session_authority
2782
+ (session_id, incarnation, owner_token, owner_pid, acquired_at, lease_expires_at)
2783
+ VALUES (?, ?, ?, ?, ?, ?)
2784
+ ON CONFLICT (session_id, incarnation) DO UPDATE SET
2785
+ -- [PHASE 6X] owner_token MUST be updated here, not just the deadline.
2786
+ -- On a takeover the new owner has to become the recorded owner, or the
2787
+ -- row would keep naming the previous owner while its lease was extended -
2788
+ -- so the old token would still pass holdsSessionAuthority and both
2789
+ -- parties would believe they were authoritative.
2790
+ owner_token = excluded.owner_token,
2791
+ owner_pid = excluded.owner_pid,
2792
+ acquired_at = excluded.acquired_at,
2793
+ lease_expires_at = excluded.lease_expires_at
2794
+ WHERE session_authority.owner_token = excluded.owner_token
2795
+ OR session_authority.lease_expires_at <= ?`,
2796
+ )
2797
+ .run(sessionId, inc, ownerToken, process.pid, now, now + leaseMs, now)
2798
+ return result.changes === 1 ? "ACQUIRED" : "REFUSED_LEASE_HELD"
2799
+ }
2800
+
2801
+ /**
2802
+ * Extend OUR lease. Refused when the token is not the current owner's, which is
2803
+ * what stops a paused or partitioned process from reclaiming a session whose lease
2804
+ * has already been taken over.
2805
+ */
2806
+ renewSessionAuthority(
2807
+ sessionId: string,
2808
+ ownerToken: string,
2809
+ leaseMs: number,
2810
+ now = Date.now(),
2811
+ ): "AUTHORITY_HELD" | "AUTHORITY_LOST" {
2812
+ const inc = this.getSessionIncarnation(sessionId)
2813
+ const result = handle(this.cwd)
2814
+ .prepare(
2815
+ `UPDATE session_authority
2816
+ SET lease_expires_at = ?
2817
+ WHERE session_id = ? AND incarnation = ? AND owner_token = ?`,
2818
+ )
2819
+ .run(now + leaseMs, sessionId, inc, ownerToken)
2820
+ return result.changes === 1 ? "AUTHORITY_HELD" : "AUTHORITY_LOST"
2821
+ }
2822
+
2823
+ /**
2824
+ * Give the lease back.
2825
+ *
2826
+ * [DESIGN DECISION] A clean stop is an unambiguous handover, so the row is DELETED
2827
+ * rather than left to expire. Keeping it would leave a released session with an
2828
+ * "authority record" a later reader could mistake for a live owner. The EXPIRY
2829
+ * path is the one that preserves the row, so a crashed owner's takeover history
2830
+ * stays inspectable.
2831
+ *
2832
+ * Token-guarded, so a stale instance can only ever fail to release - never evict
2833
+ * the successor that holds the session now.
2834
+ */
2835
+ releaseSessionAuthority(sessionId: string, ownerToken: string): boolean {
2836
+ const inc = this.getSessionIncarnation(sessionId)
2837
+ const result = handle(this.cwd)
2838
+ .prepare(
2839
+ `DELETE FROM session_authority
2840
+ WHERE session_id = ? AND incarnation = ? AND owner_token = ?`,
2841
+ )
2842
+ .run(sessionId, inc, ownerToken)
2843
+ return result.changes === 1
2844
+ }
2845
+
2846
+ /**
2847
+ * Is OUR authority still valid right now?
2848
+ *
2849
+ * The single predicate every scheduling boundary consults. A lease is ACTIVE while
2850
+ * `lease_expires_at > now`; the strict inequality means an expired row is already
2851
+ * free, so expiry and takeover can never both succeed at the same instant.
2852
+ */
2853
+ holdsSessionAuthority(sessionId: string, ownerToken: string, now = Date.now()): boolean {
2854
+ const a = this.getSessionAuthority(sessionId)
2855
+ return a !== null && a.ownerToken === ownerToken && a.leaseExpiresAt > now
2856
+ }
2857
+ }
2858
+
2859
+ /** Discard the handle cache. For hermetic tests only. */
2860
+ export function resetTaskStoreHandles(): void {
2861
+ // Refuse while any transaction is open, for the same reason `close` does.
2862
+ const open = openTxPaths()
2863
+ if (open.length > 0) {
2864
+ throw new TaskError(
2865
+ "TASK_TX_ACTIVE",
2866
+ `cannot reset task store handles while ${open.length} transaction(s) are open`,
2867
+ )
2868
+ }
2869
+ for (const db of handles.values()) {
2870
+ try {
2871
+ db.close()
2872
+ } catch {}
2873
+ }
2874
+ handles.clear()
2875
+ initialized.clear()
2876
+ }
2877
+
2878
+ /** Legacy-source fingerprint, used by migration so a re-import of identical
2879
+ * content changes nothing. */
2880
+ export function legacyDigest(raw: string): string {
2881
+ // `scrubSecrets` is used so a secret accidentally present in the legacy file
2882
+ // is neither hashed nor leaked through the marker.
2883
+ const { createHash } = require("node:crypto") as typeof import("node:crypto")
2884
+ return createHash("sha256").update(scrubSecrets(raw)).digest("hex").slice(0, 32)
2885
+ }
2886
+
2887
+ export const __testing = { MAX_DEPENDS_ON, MAX_EVIDENCE, MAX_ACCEPTANCE, MAX_PARENT }