minicode-ai 0.27.0 → 0.30.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 (145) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +184 -57
  3. package/cli/bootstrap/presentation-bridge.ts +383 -0
  4. package/cli/commands/acp.ts +45 -29
  5. package/cli/commands/auth.ts +17 -17
  6. package/cli/commands/config.ts +65 -66
  7. package/cli/commands/daemon.ts +44 -16
  8. package/cli/commands/doctor.ts +18 -15
  9. package/cli/commands/exec.ts +41 -89
  10. package/cli/commands/mcp.ts +25 -8
  11. package/cli/commands/memory.ts +16 -24
  12. package/cli/commands/openwork.ts +6 -2
  13. package/cli/commands/pricing.ts +14 -12
  14. package/cli/commands/providers.ts +36 -57
  15. package/cli/commands/sessions.ts +24 -18
  16. package/cli/commands/skills.ts +33 -18
  17. package/cli/commands/stats.ts +15 -30
  18. package/cli/commands.ts +73 -44
  19. package/cli/context-command-run.ts +30 -18
  20. package/cli/index.ts +51 -100
  21. package/cli/model-manager.ts +7 -2
  22. package/cli/provider-manager.ts +33 -18
  23. package/cli/router.ts +41 -12
  24. package/cli/setup.ts +241 -485
  25. package/cli/tui.ts +303 -100
  26. package/docs/TERMINAL_CONTRACT.md +258 -73
  27. package/docs/UI_RENDER_PIPELINE.md +9 -1
  28. package/docs/agents.md +2 -2
  29. package/docs/architecture.md +17 -32
  30. package/docs/choosing-mode.md +7 -9
  31. package/docs/cli.md +3 -5
  32. package/docs/environment.md +1 -2
  33. package/docs/policy-sandbox.md +3 -3
  34. package/docs/repl.md +2 -2
  35. package/docs/tools.md +1 -1
  36. package/package.json +1 -1
  37. package/src/app/mentions.ts +60 -13
  38. package/src/app/rag-layer.ts +17 -20
  39. package/src/app/session.ts +144 -68
  40. package/src/app/tool-layer.ts +38 -16
  41. package/src/config.ts +64 -104
  42. package/src/constants.ts +4 -6
  43. package/src/daemon/capability.ts +8 -1
  44. package/src/daemon/control.ts +3 -2
  45. package/src/daemon/server.ts +57 -0
  46. package/src/hooks/run.ts +73 -41
  47. package/src/lib/atomic-write.ts +31 -59
  48. package/src/lib/db-path.ts +47 -0
  49. package/src/lib/process-tree.ts +62 -0
  50. package/src/lib/public-http.ts +88 -23
  51. package/src/lib/trusted-exec.ts +48 -1
  52. package/src/lsp/client.ts +62 -17
  53. package/src/mcp/client.ts +85 -38
  54. package/src/mcp/http-transport.ts +28 -16
  55. package/src/mcp/transport.ts +42 -6
  56. package/src/memory/files.ts +164 -134
  57. package/src/memory/vector.ts +371 -420
  58. package/src/policy/approval-binding.ts +122 -45
  59. package/src/policy/bash-guard.ts +18 -7
  60. package/src/policy/compaction.ts +51 -18
  61. package/src/policy/context-window.ts +31 -8
  62. package/src/policy/context.ts +62 -36
  63. package/src/policy/executor.ts +17 -7
  64. package/src/policy/jail.ts +6 -8
  65. package/src/policy/microcompact.ts +4 -3
  66. package/src/policy/no-progress.ts +103 -22
  67. package/src/policy/permission.ts +36 -12
  68. package/src/policy/tool-contract.ts +74 -416
  69. package/src/policy/usage.ts +24 -2
  70. package/src/policy/verifier.ts +50 -2
  71. package/src/policy/work-mode.ts +28 -54
  72. package/src/presentation/adapter.ts +24 -16
  73. package/src/providers/anthropic.ts +16 -5
  74. package/src/providers/provision.ts +6 -56
  75. package/src/providers/responses.ts +38 -7
  76. package/src/providers/sse-bounds.ts +6 -4
  77. package/src/runtime/execution-journal.ts +4 -29
  78. package/src/sandbox/docker.ts +58 -34
  79. package/src/sandbox/mask.ts +157 -0
  80. package/src/sandbox/os.ts +107 -73
  81. package/src/session/authority.ts +29 -10
  82. package/src/session/context-projection.ts +6 -5
  83. package/src/session/db/runs.ts +397 -0
  84. package/src/session/db/schema.ts +358 -0
  85. package/src/session/open-work.ts +26 -3
  86. package/src/session/persistence.ts +74 -998
  87. package/src/session/verification.ts +170 -20
  88. package/src/skills/loader.ts +31 -16
  89. package/src/task/db/schema.ts +325 -0
  90. package/src/task/db/types.ts +269 -0
  91. package/src/task/production-scheduler.ts +13 -1
  92. package/src/task/store.ts +92 -1021
  93. package/src/telemetry/trace.ts +27 -0
  94. package/src/tools/ask_user.ts +1 -13
  95. package/src/tools/bash.ts +27 -92
  96. package/src/tools/code_run.ts +1 -1
  97. package/src/tools/context.ts +133 -0
  98. package/src/tools/delete_file.ts +3 -2
  99. package/src/tools/edit.ts +37 -72
  100. package/src/tools/git.ts +86 -9
  101. package/src/tools/glob.ts +26 -51
  102. package/src/tools/grep.ts +67 -57
  103. package/src/tools/hashline.ts +4 -0
  104. package/src/tools/lsp.ts +11 -8
  105. package/src/tools/mcp_call.ts +9 -6
  106. package/src/tools/memory.ts +56 -33
  107. package/src/tools/move_file.ts +36 -10
  108. package/src/tools/patch.ts +13 -21
  109. package/src/tools/read_file.ts +18 -25
  110. package/src/tools/read_image.ts +35 -33
  111. package/src/tools/submit_result.ts +29 -8
  112. package/src/tools/task.ts +74 -17
  113. package/src/tools/todo.ts +181 -74
  114. package/src/tools/web_fetch.ts +42 -2
  115. package/src/tools/web_search.ts +47 -8
  116. package/src/ui/approval/prompt.ts +206 -47
  117. package/src/ui/assistant/turn-status.ts +14 -5
  118. package/src/ui/footer.ts +4 -4
  119. package/src/ui/i18n/en.ts +47 -23
  120. package/src/ui/i18n/id.ts +76 -51
  121. package/src/ui/input/input.ts +4 -3
  122. package/src/ui/input/prompt-engine.ts +35 -5
  123. package/src/ui/render/activity-panel.ts +4 -2
  124. package/src/ui/render/hint.ts +7 -4
  125. package/src/ui/render/list.ts +32 -0
  126. package/src/ui/render/markdown.ts +6 -3
  127. package/src/ui/render/notice.ts +19 -0
  128. package/src/ui/render/table-grid.ts +7 -8
  129. package/src/ui/render/theme.ts +113 -39
  130. package/src/ui/runtime/screen.ts +74 -10
  131. package/src/ui/runtime/spinner.ts +19 -6
  132. package/src/ui/screens/dialog.ts +19 -1
  133. package/src/ui/screens/form.ts +80 -35
  134. package/src/ui/screens/model-manager.ts +82 -61
  135. package/src/ui/screens/output-window.ts +263 -0
  136. package/src/ui/screens/picker.ts +94 -81
  137. package/src/ui/screens/provider-manager.ts +100 -69
  138. package/src/ui/screens/wizard.ts +117 -28
  139. package/src/ui/tui/app.ts +196 -33
  140. package/src/ui/tui/transcript.ts +158 -25
  141. package/vendor/minicore/src/core/executor.ts +2 -0
  142. package/vendor/minicore/src/core/loop.ts +17 -6
  143. package/vendor/minicore/src/core/session.ts +3 -0
  144. package/vendor/minicore/src/core/tool.ts +1 -0
  145. package/vendor/minicore/src/providers/openai-compat.ts +35 -19
package/src/task/store.ts CHANGED
@@ -25,12 +25,55 @@
25
25
  //
26
26
  // All SQL lives here. Other subsystems may only use the domain API.
27
27
 
28
- import { Database } from "bun:sqlite"
29
28
  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"
29
+ import {
30
+ closeTaskStoreHandle,
31
+ dbFile,
32
+ handle,
33
+ j,
34
+ legacyDigest,
35
+ parseStringArrayStrict,
36
+ resetTaskStoreHandles,
37
+ rowToTask,
38
+ txDepth,
39
+ } from "./db/schema.ts"
40
+ import {
41
+ ADOPTABLE_STATUS_SET,
42
+ ADOPTABLE_STATUSES,
43
+ type AttemptRecordOutcome,
44
+ buildVerificationTaskEvidence,
45
+ CLAIMABLE_STATUSES,
46
+ type ExecutionLineage,
47
+ type ExecutionOwner,
48
+ type ExecutionOwnership,
49
+ emitTaskTransition,
50
+ type LineageReconcileOutcome,
51
+ MAX_DEPENDS_ON,
52
+ MAX_EVIDENCE,
53
+ type NewTaskInput,
54
+ nowIso,
55
+ type PatchOptions,
56
+ setTaskTransitionSink,
57
+ sqlList,
58
+ TASK_DATA_VERSION,
59
+ type TaskAuthorityMode,
60
+ type TaskDuplicateOutcome,
61
+ type TaskDuplicateRequest,
62
+ type TaskDuplicateResult,
63
+ type TaskMerge,
64
+ type TaskPatch,
65
+ type TaskRow,
66
+ type TaskStoreOptions,
67
+ type TaskTransfer,
68
+ type TaskTransferOutcome,
69
+ type TaskTransferRequest,
70
+ type TaskTransferResult,
71
+ type TaskTransition,
72
+ type TaskTransitionKind,
73
+ type UnfinishedWorkItem,
74
+ type UpsertOptions,
75
+ type VerificationGateOutcome,
76
+ } from "./db/types.ts"
34
77
  import {
35
78
  type ClaimOutcome,
36
79
  IllegalTaskTransitionError,
@@ -40,11 +83,8 @@ import {
40
83
  isTerminalTaskStatus,
41
84
  type ReconcileOutcome,
42
85
  type Task,
43
- type TaskAcceptance,
44
86
  TaskAuthorityLostError,
45
87
  TaskError,
46
- type TaskEvidence,
47
- type TaskProvenance,
48
88
  type TaskSnapshot,
49
89
  type TaskStatus,
50
90
  type TaskVerification,
@@ -52,980 +92,35 @@ import {
52
92
  } from "./model.ts"
53
93
  import type { SessionAuthority } from "./session-authority.ts"
54
94
 
55
- const TASK_DB_FILENAME = "tasks.db"
56
-
57
- /**
58
- * P2.3 (Session 4): satu sink transisi process-wide. `src/task` tidak boleh
59
- * mengimpor presentation; composition root memasang sink untuk memproyeksikan
60
- * transisi AUTHORITATIVE (setelah commit DB) menjadi event `task.status`.
61
- * Satu sesi agent per proses (lihat guard single-session), jadi sink tunggal
62
- * cukup dan tidak membocorkan lintas sesi.
63
- */
64
- export type TaskTransitionKind = "created" | "updated" | "claimed"
65
- export interface TaskTransition {
66
- kind: TaskTransitionKind
67
- task: Task
68
- previousStatus: TaskStatus | null
69
- }
70
-
71
- let taskTransitionSink: ((transition: TaskTransition) => void) | null = null
72
-
73
- export function setTaskTransitionSink(sink: ((transition: TaskTransition) => void) | null): void {
74
- taskTransitionSink = sink
75
- }
76
-
77
- /** Emit SETELAH commit; kegagalan observer tak boleh menggagalkan transisi. */
78
- function emitTaskTransition(
79
- kind: TaskTransitionKind,
80
- task: Task,
81
- previousStatus: TaskStatus | null,
82
- ): void {
83
- try {
84
- taskTransitionSink?.({ kind, task, previousStatus })
85
- } catch {}
95
+ export type {
96
+ AttemptRecordOutcome,
97
+ ExecutionLineage,
98
+ ExecutionOwner,
99
+ ExecutionOwnership,
100
+ LineageReconcileOutcome,
101
+ NewTaskInput,
102
+ PatchOptions,
103
+ TaskAuthorityMode,
104
+ TaskDuplicateOutcome,
105
+ TaskDuplicateRequest,
106
+ TaskDuplicateResult,
107
+ TaskMerge,
108
+ TaskPatch,
109
+ TaskStoreOptions,
110
+ TaskTransfer,
111
+ TaskTransferOutcome,
112
+ TaskTransferRequest,
113
+ TaskTransferResult,
114
+ TaskTransition,
115
+ TaskTransitionKind,
116
+ UnfinishedWorkItem,
117
+ UpsertOptions,
118
+ VerificationGateOutcome,
86
119
  }
120
+ export { buildVerificationTaskEvidence, legacyDigest, resetTaskStoreHandles, setTaskTransitionSink }
87
121
 
88
- /** Bounds so the JSON columns cannot grow without limit. */
89
- const MAX_DEPENDS_ON = 32
90
- const MAX_EVIDENCE = 32
91
-
92
- /** Shape of the data, not of the table: this rises when column SEMANTICS
93
- * change, not merely when a column is added. */
94
- // [PHASE 6K] Deliberately NOT bumped. `TASK_DATA_VERSION` is an existing
95
- // contract (taskstore.test.ts "H" asserts `ensureDataVersion() === 1`, and that
96
- // a newer writer is refused rather than downgraded), and bumping it would be a
97
- // semantic change outside the scope of D3/D4/D5.
98
- //
99
- // It is also unnecessary. The lineage migration decides from
100
- // `PRAGMA table_info`, not from this stamp, precisely because a stamp can lie
101
- // and the schema cannot. The stamp is written as bookkeeping; the migration's
102
- // correctness does not depend on it. If a future change makes the SCHEMA itself
103
- // version-dependent, that change should bump this constant deliberately.
104
- const TASK_DATA_VERSION = 1
105
-
106
- /** Bounded schema-DDL retry. Matches the Phase 0C contract: at most `attempts`
107
- * tries, only transient SQLite contention is retried, every other error
108
- * (corruption, constraint, …) propagates immediately, and exhaustion yields
109
- * `null` so the caller raises its own domain error.
110
- *
111
- * [Phase 12.2] Dibanding Phase 0C, predikat kontensi diperluas dari hanya
112
- * SQLITE_BUSY/"database is locked" → mencakup kontensi WAL lintas-proses Windows
113
- * (SQLITE_IOERR_TRUNCATE / SHMOPEN / LOCK / PROTOCOL / LOCKED), yang transien dan
114
- * aman di-retry. Bun menaruh kode simbolik di `error.code`, teks di `error.message`. */
115
- const SCHEMA_ATTEMPTS = 8
116
- const SCHEMA_BACKOFF_MS = 25
117
-
118
- const SQLITE_CONTENTION_RE =
119
- /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
120
-
121
- function isSqliteContention(e: unknown): boolean {
122
- const code = (e as { code?: unknown } | null)?.code
123
- if (typeof code === "string" && SQLITE_CONTENTION_RE.test(code)) return true
124
- const msg = e instanceof Error ? String(e.message ?? e) : String(e)
125
- return SQLITE_CONTENTION_RE.test(msg)
126
- }
127
-
128
- function withBusyRetrySync<T>(fn: () => T, attempts = SCHEMA_ATTEMPTS): T | null {
129
- for (let i = 1; i <= attempts; i++) {
130
- try {
131
- return fn()
132
- } catch (e) {
133
- if (!isSqliteContention(e)) throw e
134
- if (i === attempts) return null
135
- sleepSync(SCHEMA_BACKOFF_MS * 2 ** (i - 1))
136
- }
137
- }
138
- return null
139
- }
140
-
141
- function sleepSync(ms: number): void {
142
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
143
- }
144
-
145
- interface TaskRow {
146
- session_id: string
147
- task_id: string
148
- title: string
149
- status: string
150
- task_order: number
151
- parent_id: string | null
152
- depends_on_json: string | null
153
- blocked_reason: string | null
154
- verification_json: string | null
155
- evidence_json: string | null
156
- acceptance_json: string | null
157
- provenance_json: string | null
158
- created_at: string
159
- updated_at: string
160
- revision: number
161
- exec_generation: number
162
- attempt_generation: number | null
163
- /** [PHASE 6P] Kolom terpisah dari status/lineage; lihat `ExecutionOwner`. */
164
- execution_owner: string | null
165
- }
166
-
167
- /**
168
- * [PHASE 6I] Execution lineage for one task, read through a dedicated accessor so
169
- * it never becomes part of the public `Task` shape.
170
- *
171
- * `execGeneration` is the CURRENT execution generation. It advances ONLY when
172
- * `claimTask` accepts a claim - never on a title, order, dependency, parent,
173
- * blockedReason, evidence, verification or status write. That invariance is the
174
- * whole point: it makes the lineage decision immune to arbitrary task mutation,
175
- * which is what 6G D1 proved revision could not be.
176
- *
177
- * `attemptGeneration` is the generation whose execution attempt reached its end,
178
- * or `null` when no attempt of the current generation has completed. It records
179
- * that an ATTEMPT ENDED - never that the task is correct or complete.
180
- *
181
- * It is NOT a task status, NOT a lock, NOT a lease, NOT a counter of attempts
182
- * and NOT a history: exactly one generation is retained, and evidence lives on
183
- * the task row so it cannot outlive the task.
184
- */
185
- export interface ExecutionLineage {
186
- readonly execGeneration: number
187
- readonly attemptGeneration: number | null
188
- }
189
-
190
- /**
191
- * [PHASE 6P] Who owns the CURRENT in-flight state of a task.
192
- *
193
- * This is a FOURTH, separate fact. It is deliberately NOT folded into
194
- * `TaskStatus`, `ExecutionLineage`, or `Task`:
195
- *
196
- * status WHAT the task is (pending, in-flight, done, …)
197
- * execution_owner WHOSE in-flight state it is
198
- * exec_generation WHICH execution generation is current
199
- * attempt_generation whether that generation's attempt reached its end
200
- *
201
- * WHY IT EXISTS (6N F1, proved in 6O §5.2). `IN_PROGRESS` is overloaded: it is
202
- * written both by `claimTask` (a Scheduler-owned execution) and by the
203
- * model-facing path (`todo_write` → `synchronizeCanonicalTasks` → `patchTask`,
204
- * where it is the agent's plan cursor — see `src/tools/todo.ts:15-19`).
205
- * Reconciliation used to read *every* `IN_PROGRESS`/`VERIFYING` without a
206
- * completion marker as stranded Scheduler work, so it reverted the user's cursor.
207
- *
208
- * The information needed to tell those apart DID NOT EXIST in the other columns.
209
- * Two histories are byte-identical under `(status, exec_generation,
210
- * attempt_generation)` and demand opposite actions:
211
- *
212
- * H2 claim → crash → IN_PROGRESS/1/NULL → REVERT
213
- * H5 claim → crash → reconcile → user
214
- * marks IN_PROGRESS → IN_PROGRESS/1/NULL → LEAVE
215
- *
216
- * `exec_generation > 0` does not separate them (both are 1, and reconcile never
217
- * resets the counter), and `attempt_generation` is NULL in both. This column is
218
- * the missing fact: it records whether a reconcile already ended that claim.
219
- *
220
- * STATE MODEL — the only two values:
221
- * 'scheduler' the current in-flight status was established by `claimTask` and
222
- * has NOT been reconciled away. The Scheduler may recover it.
223
- * null no Scheduler execution owns this task. Either never claimed, or
224
- * ownership was released (by a reconcile, or by any status write
225
- * that leaves the Scheduler-owned in-flight states). The Scheduler
226
- * must NOT touch it.
227
- *
228
- * TRANSITIONS (and only these):
229
- * set 'scheduler' by `claimTask`, in the SAME statement that advances
230
- * `exec_generation` and writes IN_PROGRESS — so ownership and
231
- * generation can never disagree.
232
- * clear null by `reconcileStranded` / `reconcileIfNoCompletedAttempt`
233
- * (reverting releases it), and by ANY other writer that
234
- * moves the task OUT of RECONCILABLE_STATUSES.
235
- * keep unchanged by a status write that STAYS inside
236
- * RECONCILABLE_STATUSES, and by every non-status write
237
- * (title, order, dependency, evidence, …). A title edit does
238
- * not end a claim.
239
- *
240
- * WHY A WRITE THAT STAYS `IN_PROGRESS` KEEPS OWNERSHIP. A user writing
241
- * `IN_PROGRESS` onto a task whose claim is stranded does not end the stranded
242
- * execution; it only re-states the agent's plan cursor on top of it. The
243
- * Scheduler's generation is still dead, so the row is still recoverable (6O
244
- * history H3/H6). Releasing ownership there would strand the generation forever.
245
- * Ownership is released when the task LEAVES the in-flight states — which is
246
- * also exactly what a reconcile does.
247
- *
248
- * IT IS NOT: a lock, a lease, a heartbeat, a priority, a completion claim, a
249
- * verification, or evidence of anything. It grants no authority over the task
250
- * beyond "the Scheduler may revert this in-flight state", and it is never
251
- * consulted for readiness, identity, or dependency semantics.
252
- */
253
- export type ExecutionOwner = "scheduler"
254
-
255
- /** Result shape for `getExecutionOwnership`. `null` = no such task. */
256
- export interface ExecutionOwnership {
257
- readonly executionOwner: ExecutionOwner | null
258
- }
259
-
260
- /** `task_meta` key holding the current incarnation of a session id. */
261
122
  const incarnationKey = (sessionId: string): string => `session_incarnation:${sessionId}`
262
123
 
263
- /**
264
- * [PHASE 6Q] Outcome of `recordAttemptReturned`.
265
- *
266
- * [DESIGN DECISION] This used to be `void` and it THREW whenever the guarded
267
- * UPDATE matched no row. That is what made 6N F2 a wedge rather than an error: the
268
- * throw escaped `cycle()`, so the Scheduler never reached the line that clears its
269
- * own claim, and it kept both the claim and the session ownership forever.
270
- *
271
- * "The row I claimed is gone" and "the generation moved" are NOT persistence
272
- * failures - they are the ordinary outcomes of a session being deleted under a
273
- * running execution, or of a later generation superseding an earlier one. The
274
- * protection 6I wanted is preserved exactly (NOTHING IS WRITTEN when the guard
275
- * does not match); what changes is that the caller is TOLD, instead of being
276
- * destroyed by it. Genuine SQL errors still throw.
277
- */
278
- export type AttemptRecordOutcome =
279
- /** The completion marker for this generation was written. */
280
- | "RECORDED"
281
- /** The task row no longer exists - the session was deleted under this execution. */
282
- | "TASK_GONE"
283
- /** The row exists but this generation is no longer current. Nothing was written. */
284
- | "SUPERSEDED"
285
- /**
286
- * The session was deleted (or deleted and recreated) since this execution was
287
- * claimed, so the row that exists - if any - belongs to a DIFFERENT incarnation.
288
- * This is the cross-generation guard; nothing was written.
289
- */
290
- | "SESSION_SUPERSEDED"
291
-
292
- /**
293
- * [PHASE 6I] Outcome of `reconcileIfNoCompletedAttempt`.
294
- *
295
- * Distinct from the 6B `ReconcileOutcome` because the decision now also carries
296
- * lineage meaning: `RECONCILED` means "this execution generation has no recorded
297
- * completion, so it is stranded", whereas `NOT_STRANDED` means the current
298
- * generation DID record completion (or the row is not reconcilable at all).
299
- * `REFUSED_NO_OWNERSHIP` keeps 6B's fail-closed contract.
300
- */
301
- export type LineageReconcileOutcome =
302
- | "RECONCILED"
303
- | "NOT_STRANDED"
304
- | "REJECTED_STALE"
305
- | "NOT_FOUND"
306
- | "REFUSED_NO_OWNERSHIP"
307
-
308
- /**
309
- * [P14] Status yang boleh DIPINDAHKAN ke sesi lain.
310
- *
311
- * Kenapa bukan "semua status": memindahkan pekerjaan yang sudah COMPLETED atau
312
- * CANCELLED akan menghidupkan kembali pekerjaan yang sudah ditutup — persis
313
- * larangan P14. Status di luar daftar ini = terminal/UNKNOWN dan harus
314
- * ditangani operator, bukan diadopsi diam-diam.
315
- */
316
- const ADOPTABLE_STATUSES: readonly TaskStatus[] = [
317
- "PENDING",
318
- "IN_PROGRESS",
319
- "VERIFYING",
320
- "BLOCKED",
321
- "FAILED",
322
- "RETRYING",
323
- ]
324
-
325
- const ADOPTABLE_STATUS_SET: ReadonlySet<TaskStatus> = new Set(ADOPTABLE_STATUSES)
326
-
327
- /**
328
- * [P14] Satu baris ledger transfer. TIDAK mengandung token otoritas: token
329
- * adalah kredensial proses, bukan bukti yang boleh menetap di database.
330
- *
331
- * Ledger ini adalah BUKTI ASAL, bukan otoritas kedua. Status task tetap
332
- * dibaca dari tabel `tasks`; ledger hanya menjawab "task id ini pernah
333
- * berpindah dari sesi mana ke sesi mana, pada revisi/generasi apa".
334
- */
335
- export interface TaskTransfer {
336
- readonly transferId: string
337
- readonly taskId: string
338
- readonly fromSessionId: string
339
- readonly fromIncarnation: number
340
- readonly toSessionId: string
341
- readonly toIncarnation: number
342
- readonly expectedRevision: number
343
- readonly newRevision: number
344
- readonly status: string
345
- readonly execGeneration: number
346
- readonly attemptGeneration: number | null
347
- readonly executionOwner: ExecutionOwner | null
348
- readonly transferredAt: string
349
- }
350
-
351
- export interface TaskTransferRequest {
352
- readonly taskId: string
353
- readonly fromSessionId: string
354
- readonly fromIncarnation: number
355
- readonly toSessionId: string
356
- readonly toIncarnation: number
357
- readonly expectedRevision: number
358
- /** Token yang HARUS masih memegang lease sesi sumber. */
359
- readonly sourceOwnerToken: string
360
- /** Token yang HARUS masih memegang lease sesi tujuan. */
361
- readonly targetOwnerToken: string
362
- /** Satu jam logis untuk seluruh pemeriksaan + mutasi. */
363
- readonly now?: number
364
- }
365
-
366
- export type TaskTransferOutcome =
367
- | "TRANSFERRED"
368
- | "NOT_FOUND"
369
- | "REFUSED_SELF_TRANSFER"
370
- | "REJECTED_STALE_SOURCE_INCARNATION"
371
- | "REJECTED_STALE_TARGET_INCARNATION"
372
- | "REJECTED_STALE_REVISION"
373
- | "REFUSED_NO_SOURCE_AUTHORITY"
374
- | "REFUSED_NO_TARGET_AUTHORITY"
375
- | "REFUSED_STATUS"
376
- | "REFUSED_TARGET_ID_CONFLICT"
377
- | "REFUSED_UNRESOLVED_RELATION"
378
- | "REFUSED_CORRUPT_STATE"
379
-
380
- export interface TaskTransferResult {
381
- readonly outcome: TaskTransferOutcome
382
- readonly task: Task | null
383
- readonly transfer: TaskTransfer | null
384
- readonly detail: string
385
- /**
386
- * Id relasi (parent/dependency) yang tidak bisa dibuktikan berasal dari sesi
387
- * sumber yang sama. Kosong kecuali outcome `REFUSED_UNRESOLVED_RELATION`.
388
- */
389
- readonly unresolvedRelations: readonly string[]
390
- }
391
-
392
- /**
393
- * [P14] Satu item inventaris open-work lintas sesi.
394
- *
395
- * `Task` sengaja tetap bentuk kanoniknya; fakta eksekusi dan provenance
396
- * transfer berada DI SAMPINGNYA, bukan dicampur ke dalam `Task`. Discovery
397
- * tidak pernah memberi otoritas: tidak ada lease yang diakuisisi dan tidak
398
- * ada baris yang ditulis.
399
- */
400
- export interface UnfinishedWorkItem {
401
- readonly sessionId: string
402
- readonly sessionIncarnation: number
403
- readonly task: Task
404
- readonly execGeneration: number
405
- readonly attemptGeneration: number | null
406
- readonly executionOwner: ExecutionOwner | null
407
- readonly transferredFromSessionId: string | null
408
- readonly transferredAt: string | null
409
- }
410
-
411
- /**
412
- * [P14.3] Satu baris ledger dedup. Append-only.
413
- *
414
- * `duplicateId` adalah task yang DINYATAKAN operator sebagai unit kerja yang
415
- * sama dengan `survivorId`, lalu ditutup sebagai CANCELLED (BUKAN COMPLETED —
416
- * menyelesaikan duplikat adalah inferensi yang dilarang). `evidence` adalah
417
- * teks operator yang direkam utuh: kemiripan judul tidak pernah cukup, dan
418
- * ledger inilah bukti bahwa keputusan itu eksplisit, bukan otomatis.
419
- */
420
- export interface TaskMerge {
421
- readonly mergeId: string
422
- readonly sessionId: string
423
- readonly survivorId: string
424
- readonly duplicateId: string
425
- readonly evidence: string
426
- readonly survivorStatus: string
427
- readonly duplicateStatus: string
428
- readonly duplicateRevision: number
429
- readonly mergedAt: string
430
- }
431
-
432
- export interface TaskDuplicateRequest {
433
- readonly sessionId: string
434
- readonly survivorId: string
435
- readonly duplicateId: string
436
- /** WAJIB non-kosong: alasan operator bahwa ini unit kerja yang sama. */
437
- readonly evidence: string
438
- /** Revisi duplikat yang dilihat operator (read-then-write, bukan CAS). */
439
- readonly expectedRevision?: number
440
- }
441
-
442
- export type TaskDuplicateOutcome =
443
- | "DECLARED"
444
- | "NOT_FOUND"
445
- | "REFUSED_SELF_MERGE"
446
- | "REFUSED_NO_EVIDENCE"
447
- | "REFUSED_TERMINAL_DUPLICATE"
448
- | "REJECTED_STALE_REVISION"
449
-
450
- export interface TaskDuplicateResult {
451
- readonly outcome: TaskDuplicateOutcome
452
- /** Duplikat setelah ditutup (CANCELLED, revisi +1), atau null saat ditolak. */
453
- readonly duplicate: Task | null
454
- readonly survivor: Task | null
455
- readonly merge: TaskMerge | null
456
- readonly detail: string
457
- }
458
-
459
- const DDL = `
460
- CREATE TABLE IF NOT EXISTS tasks (
461
- session_id TEXT NOT NULL,
462
- task_id TEXT NOT NULL,
463
- title TEXT NOT NULL,
464
- status TEXT NOT NULL,
465
- task_order INTEGER NOT NULL,
466
- parent_id TEXT,
467
- depends_on_json TEXT,
468
- blocked_reason TEXT,
469
- verification_json TEXT,
470
- evidence_json TEXT,
471
- acceptance_json TEXT,
472
- provenance_json TEXT,
473
- created_at TEXT NOT NULL,
474
- updated_at TEXT NOT NULL,
475
- revision INTEGER NOT NULL,
476
- exec_generation INTEGER NOT NULL DEFAULT 0,
477
- attempt_generation INTEGER,
478
- execution_owner TEXT,
479
- PRIMARY KEY (session_id, task_id)
480
- );
481
- CREATE INDEX IF NOT EXISTS idx_tasks_session_order ON tasks(session_id, task_order);
482
- CREATE TABLE IF NOT EXISTS task_meta (
483
- key TEXT PRIMARY KEY,
484
- value TEXT NOT NULL
485
- );
486
-
487
- CREATE TABLE IF NOT EXISTS session_authority (
488
- -- [PHASE 6X] One row per (session, incarnation): a bounded, self-expiring
489
- -- claim on the RIGHT TO SCHEDULE, never proof of liveness.
490
- session_id TEXT NOT NULL,
491
- incarnation INTEGER NOT NULL,
492
- owner_token TEXT NOT NULL,
493
- owner_pid INTEGER NOT NULL,
494
- acquired_at INTEGER NOT NULL,
495
- lease_expires_at INTEGER NOT NULL,
496
- -- Keyed by incarnation as well as session, so a session deleted and recreated
497
- -- (6Q bumps the incarnation) can never inherit its predecessor's lease.
498
- PRIMARY KEY (session_id, incarnation)
499
- );
500
-
501
- CREATE TABLE IF NOT EXISTS task_transfers (
502
- -- [P14] Ledger transfer lintas sesi. APPEND-ONLY: tidak ada UPDATE/DELETE di
503
- -- jalur produksi. Token otoritas sengaja TIDAK disimpan — yang dicatat adalah
504
- -- fakta yang tidak berubah (identitas, revisi, generasi, status) supaya
505
- -- operator bisa mengaudit asal task tanpa memegang kredensial proses.
506
- transfer_id TEXT PRIMARY KEY,
507
- task_id TEXT NOT NULL,
508
- from_session_id TEXT NOT NULL,
509
- from_incarnation INTEGER NOT NULL,
510
- to_session_id TEXT NOT NULL,
511
- to_incarnation INTEGER NOT NULL,
512
- expected_revision INTEGER NOT NULL,
513
- new_revision INTEGER NOT NULL,
514
- status TEXT NOT NULL,
515
- exec_generation INTEGER NOT NULL,
516
- attempt_generation INTEGER,
517
- execution_owner TEXT,
518
- transferred_at TEXT NOT NULL
519
- );
520
- CREATE INDEX IF NOT EXISTS idx_task_transfers_from ON task_transfers(from_session_id, task_id);
521
- CREATE INDEX IF NOT EXISTS idx_task_transfers_to ON task_transfers(to_session_id, task_id);
522
- CREATE TABLE IF NOT EXISTS task_merges (
523
- -- [P14.3] Ledger dedup EKSPLISIT operator. Append-only. Satu-satunya penulis
524
- -- adalah declareTaskDuplicate, di transaksi yang sama dengan status CANCELLED
525
- -- duplikat. Kolom evidence WAJIB: kemiripan judul bukan bukti, operator
526
- -- yang menyatakan alasannya dan teks itu disimpan utuh untuk audit
527
- -- (tanpa token otoritas — sama seperti task_transfers).
528
- merge_id TEXT PRIMARY KEY,
529
- session_id TEXT NOT NULL,
530
- survivor_id TEXT NOT NULL,
531
- duplicate_id TEXT NOT NULL,
532
- evidence TEXT NOT NULL,
533
- survivor_status TEXT NOT NULL,
534
- duplicate_status TEXT NOT NULL,
535
- duplicate_revision INTEGER NOT NULL,
536
- merged_at TEXT NOT NULL
537
- );
538
- CREATE INDEX IF NOT EXISTS idx_task_merges_session ON task_merges(session_id, duplicate_id);
539
- `
540
-
541
- /**
542
- * The DDL as INDIVIDUAL statements.
543
- *
544
- * [PHASE 1 FIX] The artifact passed the whole script to a single `db.exec()`.
545
- * Measured under a held write lock, that does not fail the way the code
546
- * assumed: bun runs the script past the blocked `CREATE TABLE` and the next
547
- * statement (`CREATE INDEX ... ON tasks`) then fails with
548
- * `no such table: main.tasks` — a NON-busy error. A retry keyed on
549
- * SQLITE_BUSY therefore never engaged, and the caller saw a misleading error
550
- * after the full 3s busy_timeout. Running one statement at a time means a lock
551
- * conflict surfaces as SQLITE_BUSY on the statement that actually needs the
552
- * lock, which is exactly what the retry can act on.
553
- */
554
- const DDL_STATEMENTS: readonly string[] = DDL.split(";")
555
- .map((s) => s.trim())
556
- .filter((s) => s.length > 0)
557
-
558
- /** Handle cache per path, as with `sessions.db`, so `initialize()` does not run
559
- * the DDL on every operation. */
560
- const handles = new Map<string, Database>()
561
- const initialized = new Set<string>()
562
-
563
- /** Depth of in-flight `withTransaction` calls, per db path.
564
- *
565
- * Exists for two reasons:
566
- * 1. `close`/`resetTaskStoreHandles` must not yank the connection out from
567
- * under an open transaction - that would leave a half-applied unit of work
568
- * with no rollback path.
569
- * 2. It makes the transaction boundary observable, so a caller cannot open a
570
- * transaction and then escape it by reaching for a different connection. */
571
- const txDepth = new Map<string, number>()
572
-
573
- function openTxPaths(): string[] {
574
- return [...txDepth.entries()].filter(([, d]) => d > 0).map(([p]) => p)
575
- }
576
-
577
- /** Throw if `p` currently has an open transaction. */
578
- function assertNoOpenTx(p: string, what: string): void {
579
- if ((txDepth.get(p) ?? 0) > 0) {
580
- throw new TaskError(
581
- "TASK_TX_ACTIVE",
582
- `cannot ${what} while a TaskStore transaction is open for this database`,
583
- )
584
- }
585
- }
586
-
587
- function dbFile(cwd?: string): string {
588
- return resolveLocalDbPath(TASK_DB_FILENAME, cwd)
589
- }
590
-
591
- /**
592
- * [PHASE 6K] Bring an existing `tasks` table up to the current lineage schema.
593
- *
594
- * WHY THIS EXISTS (Phase 6J D3, HIGH): `CREATE TABLE IF NOT EXISTS tasks (...)`
595
- * is a NO-OP when the table already exists. SQLite does not add columns. So a
596
- * database created before Phase 6I never received `exec_generation` /
597
- * `attempt_generation`, and because `createTask` names them, task creation
598
- * failed outright on any pre-6I installation - on the LEGACY path, with the
599
- * Scheduler still disabled.
600
- *
601
- * WHY SCHEMA INTROSPECTION rather than only a version stamp: a version stamp
602
- * can lie (a 6F database may carry a stale or absent `data_version`), whereas
603
- * `PRAGMA table_info` reports what is actually there. The stamp is still
604
- * written so `dataVersion()` reflects reality, but the DECISION is made from
605
- * the schema.
606
- *
607
- * PROPERTIES, each load-bearing:
608
- * - IDEMPOTENT: a column is added only when absent, so running twice is a
609
- * no-op, and a partially migrated database converges.
610
- * - NON-DESTRUCTIVE: no row is deleted, updated, or reordered. `ADD COLUMN`
611
- * only appends.
612
- * - COMPATIBLE WITH EXISTING ROWS: the defaults are exactly the 6H
613
- * semantics for a row that predates lineage - `exec_generation = 0`
614
- * ("never claimed") and `attempt_generation = NULL` ("never attempted").
615
- * `revision`, `status`, `task_id` and every relationship are untouched.
616
- * - NO INFERENCE: a pre-lineage row is NOT given a generation derived from
617
- * its revision. 6H explicitly declined that, and it is what caused D1.
618
- * - TRANSACTIONAL: both ALTERs run in one transaction, so an interruption
619
- * leaves the table in its previous state rather than half-migrated.
620
- */
621
- function migrateExecutionLineageSchema(db: Database): void {
622
- const present = new Set(
623
- (db.prepare("PRAGMA table_info(tasks)").all() as { name: string }[]).map((r) => r.name),
624
- )
625
- // No `tasks` table at all: the DDL above just created it with the columns.
626
- if (present.size === 0) return
627
-
628
- const needsExec = !present.has("exec_generation")
629
- const needsAttempt = !present.has("attempt_generation")
630
- if (!needsExec && !needsAttempt) return
631
-
632
- const run = db.transaction(() => {
633
- if (needsExec) {
634
- // NOT NULL with a non-null default is required by SQLite for ADD COLUMN,
635
- // and it backfills every existing row with 0 = "never claimed".
636
- db.exec("ALTER TABLE tasks ADD COLUMN exec_generation INTEGER NOT NULL DEFAULT 0")
637
- }
638
- if (needsAttempt) {
639
- // Deliberately nullable with NO default: existing rows read as NULL,
640
- // which is exactly 6H's "no attempt of the current generation".
641
- db.exec("ALTER TABLE tasks ADD COLUMN attempt_generation INTEGER")
642
- }
643
- })
644
- try {
645
- withBusyRetrySync(() => {
646
- run()
647
- return true
648
- })
649
- } catch (e) {
650
- throw new TaskError(
651
- "TASK_MIGRATION_FAILURE",
652
- `lineage migration failed: ${(e as Error).message}`,
653
- )
654
- }
655
- // Record the schema version so `dataVersion()` is no longer fiction.
656
- try {
657
- const cur = db.prepare("SELECT value FROM task_meta WHERE key = ?").get("data_version") as
658
- | { value: string }
659
- | null
660
- | undefined
661
- const n = cur ? Number(cur.value) : 0
662
- if (!Number.isFinite(n) || n < TASK_DATA_VERSION) {
663
- db.prepare(
664
- "INSERT INTO task_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
665
- ).run("data_version", String(TASK_DATA_VERSION))
666
- }
667
- } catch {
668
- // The version stamp is bookkeeping, not correctness. A failure to record it
669
- // must never prevent the store from opening.
670
- }
671
- }
672
-
673
- /**
674
- * [PHASE 6P] Add `execution_owner` to a database that predates it.
675
- *
676
- * Same decision procedure as `migrateExecutionLineageSchema` — decide from
677
- * `PRAGMA table_info`, never from a version stamp, because a stamp can lie and
678
- * the schema cannot. Kept as a SEPARATE function so the 6P change is
679
- * independently reviewable and independently idempotent, and so the older
680
- * function's documented properties are not silently redefined.
681
- *
682
- * PROPERTIES, each load-bearing:
683
- * - IDEMPOTENT: added only when absent, so repeated opens are a no-op and a
684
- * partially migrated database converges.
685
- * - ADDITIVE / NON-DESTRUCTIVE: `ADD COLUMN` only. No row is updated, deleted,
686
- * reordered or rewritten. Same guarantee as the 6I migration.
687
- * - COMPATIBLE WITH EXISTING ROWS: nullable with no default, so every existing
688
- * row reads back as `NULL` = "no Scheduler execution owns this task".
689
- * - TRANSACTIONAL: the ALTER runs in one transaction, so an interruption leaves
690
- * the table as it was rather than half-migrated.
691
- *
692
- * NO BACKFILL — DELIBERATE, and it is the important decision here.
693
- *
694
- * It is tempting to backfill `'scheduler'` onto every pre-6P row that looks like a
695
- * stranded claim (`status IN (IN_PROGRESS, VERIFYING) AND exec_generation > 0`).
696
- * That would be a GUESS, and it is provably wrong in one direction and
697
- * un-recoverable in the other:
698
- *
699
- * - A pre-6P row can ALSO be history H5: claim → crash → 6B `reconcileStranded`
700
- * (status → PENDING) → a user turn marks IN_PROGRESS. That is the same
701
- * `(IN_PROGRESS, exec>0, att NULL)` shape, and backfilling would mark
702
- * interactive work as Scheduler-owned and revert it — reintroducing 6N F1
703
- * on upgraded databases.
704
- * - Not backfilling leaves a pre-6P genuinely stranded claim unrecovered. Its
705
- * row stays IN_PROGRESS, which is not-eligible, so its dependents stay
706
- * unready. This is an availability cost, and it is a MANUAL/OPERATOR cost,
707
- * not a correctness one: no execution is corrupted, nothing is lost.
708
- *
709
- * The ambiguity in legacy rows is IRREDUCIBLE — the fact was never recorded, and
710
- * 6I's "NO INFERENCE" rule (a pre-lineage row is not given a generation derived
711
- * from its revision) forbids manufacturing it. Inventing ownership would be the
712
- * same error one column over. So: additive only, no inference, and the
713
- * behaviour change is stated rather than hidden.
714
- */
715
- function migrateExecutionOwnershipSchema(db: Database): void {
716
- const present = new Set(
717
- (db.prepare("PRAGMA table_info(tasks)").all() as { name: string }[]).map((r) => r.name),
718
- )
719
- // No `tasks` table at all: the DDL above just created it with the column.
720
- if (present.size === 0) return
721
- if (present.has("execution_owner")) return
722
-
723
- try {
724
- withBusyRetrySync(() => {
725
- // Nullable with NO default: existing rows read as NULL, which is exactly
726
- // "no Scheduler execution owns this task" - the safe direction, because it
727
- // forbids reconciliation rather than permitting it.
728
- db.exec("ALTER TABLE tasks ADD COLUMN execution_owner TEXT")
729
- return true
730
- })
731
- } catch (e) {
732
- throw new TaskError(
733
- "TASK_MIGRATION_FAILURE",
734
- `execution-ownership migration failed: ${(e as Error).message}`,
735
- )
736
- }
737
- }
738
-
739
- function handle(cwd?: string): Database {
740
- const p = dbFile(cwd)
741
- const existing = handles.get(p)
742
- if (existing) return existing
743
- // [Phase 7 / Live #1] Sama dengan persistence.ts: buka koneksi + PRAGMA
744
- // setup dalam retry. `new Database(p)` dan `PRAGMA journal_mode=WAL`
745
- // bisa gagal SQLITE_BUSY saat beberapa proses membuka tasks.db bersamaan.
746
- // busy_timeout diatur SEBELUM journal_mode (peralihan WAL butuh exclusive
747
- // lock sesaat yang langsung gagal tanpa busy_timeout).
748
- let db: Database
749
- const opened = withBusyRetrySync(() => {
750
- const d = new Database(p)
751
- try {
752
- d.exec(`PRAGMA busy_timeout=${LIMITS.SQLITE_BUSY_TIMEOUT_MS}`)
753
- } catch {}
754
- return d
755
- })
756
- if (!opened) {
757
- throw new TaskError(
758
- "TASK_DB_INIT_FAILURE",
759
- `cannot open ${p} after ${SCHEMA_ATTEMPTS} busy-retry attempts`,
760
- )
761
- }
762
- db = opened
763
- // [Audit #3 RL-3] WAL + DDL/migrasi dibungkus SATU guard pasca-konstruksi agar
764
- // kegagalan IOERR/CORRUPT menutup handle (bukan bocor) — WAL sebelumnya di luar guard.
765
- try {
766
- if (!initialized.has(p)) {
767
- // Sama dengan persistence.ts: PRAGMA WAL dibungkus retry (peralihan WAL
768
- // butuh exclusive lock sesaat).
769
- const walOk = withBusyRetrySync(() => {
770
- db.exec(
771
- `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};`,
772
- )
773
- return true
774
- })
775
- if (walOk === null) {
776
- process.stderr.write(`[warn] taskstore: wal setup deferred, retry next open: ${p}\n`)
777
- }
778
- try {
779
- const { chmodSync } = require("node:fs") as typeof import("node:fs")
780
- chmodSync(p, 0o600)
781
- } catch {}
782
- }
783
- // D2: the artifact ran this bare and could therefore throw SQLITE_BUSY before
784
- // any retry. Bounded retry now. On failure the handle is closed and dropped
785
- // from the cache, exactly as the artifact did, so the next call retries from a
786
- // clean state instead of handing out a half-built connection.
787
- for (const stmt of DDL_STATEMENTS) {
788
- const ok = withBusyRetrySync(() => {
789
- db.exec(stmt)
790
- return true
791
- })
792
- if (ok === null) throw new Error(`schema init did not complete: ${stmt.slice(0, 40)}`)
793
- }
794
- // [PHASE 6K] `CREATE TABLE IF NOT EXISTS` cannot add a column to an
795
- // existing table, so a database created before 6I never receives the
796
- // execution-lineage columns and every statement naming them fails. The
797
- // migration runs here, on the same open path, immediately after the DDL.
798
- migrateExecutionLineageSchema(db)
799
- // [PHASE 6P] Same open path, immediately after, so a database that already
800
- // has the lineage columns but predates 6P still receives `execution_owner`.
801
- migrateExecutionOwnershipSchema(db)
802
- initialized.add(p)
803
- } catch (e) {
804
- try {
805
- db.close()
806
- } catch {}
807
- handles.delete(p)
808
- throw new TaskError("TASK_DB_INIT_FAILURE", `schema init failed: ${(e as Error).message}`)
809
- }
810
- handles.set(p, db)
811
- return db
812
- }
813
-
814
- function parseJson<T>(raw: string | null, fallback: T): T {
815
- if (!raw) return fallback
816
- try {
817
- const v = JSON.parse(raw) as T
818
- return v ?? fallback
819
- } catch {
820
- // A corrupt column must NOT drop the whole task. Fall back to a neutral
821
- // shape and the task still reads as present.
822
- return fallback
823
- }
824
- }
825
-
826
- /**
827
- * [P14] Parse relasi secara KETAT — berbeda dari `parseJson` yang sengaja
828
- * memaafkan kolom rusak untuk pembacaan biasa.
829
- *
830
- * Transfer lintas sesi memindahkan baris yang relasinya akan ditafsirkan ulang
831
- * di namespace sesi lain. Menebak `[]` dari JSON rusak berarti memindahkan task
832
- * tanpa dependency yang sebenarnya ada — persis "deduplication menyatukan tugas
833
- * yang berbeda" yang dilarang P14. `null` = tidak bisa dibuktikan, jadi tolak.
834
- */
835
- function parseStringArrayStrict(raw: string | null): string[] | null {
836
- if (raw === null || raw.trim() === "") return []
837
- try {
838
- const v: unknown = JSON.parse(raw)
839
- if (!Array.isArray(v)) return null
840
- if (v.some((x) => typeof x !== "string")) return null
841
- return v as string[]
842
- } catch {
843
- return null
844
- }
845
- }
846
-
847
- function rowToTask(r: TaskRow): Task {
848
- return {
849
- id: r.task_id,
850
- sessionId: r.session_id,
851
- title: r.title,
852
- status: (isTaskStatus(r.status) ? r.status : "PENDING") as TaskStatus,
853
- order: r.task_order,
854
- parentId: r.parent_id,
855
- dependsOn: parseJson<string[]>(r.depends_on_json, []),
856
- blockedReason: r.blocked_reason,
857
- verification: parseJson<TaskVerification | null>(r.verification_json, null),
858
- evidence: parseJson<TaskEvidence[]>(r.evidence_json, []),
859
- acceptance: parseJson<TaskAcceptance | null>(r.acceptance_json, null),
860
- provenance: parseJson<TaskProvenance>(r.provenance_json, {
861
- origin: "runtime",
862
- source: "unknown",
863
- }),
864
- createdAt: r.created_at,
865
- updatedAt: r.updated_at,
866
- revision: r.revision,
867
- }
868
- }
869
-
870
- function nowIso(): string {
871
- return new Date().toISOString()
872
- }
873
-
874
- function j(value: unknown): string | null {
875
- return value === null || value === undefined ? null : JSON.stringify(value)
876
- }
877
-
878
- /** Shape that may arrive from the model/caller. Task ids are already validated
879
- * by the allocator; this struct is never stored as-is. */
880
- export interface NewTaskInput {
881
- title: string
882
- status: TaskStatus
883
- order: number
884
- parentId?: string | null
885
- dependsOn?: string[]
886
- blockedReason?: string | null
887
- verification?: TaskVerification | null
888
- evidence?: TaskEvidence[]
889
- acceptance?: TaskAcceptance | null
890
- provenance: TaskProvenance
891
- }
892
-
893
- export interface TaskPatch {
894
- title?: string
895
- status?: TaskStatus
896
- /** Display position. Unlike `id`, `order` may change at any time and `id`
897
- * never does. */
898
- order?: number
899
- parentId?: string | null
900
- dependsOn?: string[]
901
- blockedReason?: string | null
902
- verification?: TaskVerification | null
903
- evidence?: TaskEvidence[]
904
- acceptance?: TaskAcceptance | null
905
- }
906
-
907
- export interface UpsertOptions {
908
- /** Evidence used by the completion gate. Default `unverified` so a TaskStore
909
- * called without DI cannot silently refuse `completed`.
910
- * [PHASE 1] inert: the only reader was the deferred `synchronizeTasks`. */
911
- evidence?: CompletionEvidence
912
- /** Revision that MUST match (optimistic). `undefined` = no check.
913
- *
914
- * [Fase 1 / LOOP-INV-01] The check now runs INSIDE the write transaction and
915
- * the UPDATE carries `AND revision = ?`, so it is a real compare-and-swap
916
- * (one writer wins, the loser gets `TASK_STALE_REVISION` and changes
917
- * nothing). Previously it was a read-then-write outside the transaction and
918
- * two concurrent writers could both pass it. */
919
- expectedRevision?: number
920
- }
921
-
922
- /**
923
- * [Fase 1] Opsi khusus `patchTask` untuk dua jaminan baru.
924
- */
925
- export interface PatchOptions extends UpsertOptions {
926
- /**
927
- * [LOOP-INV-02] Permit EKSPLISIT untuk keluar dari status terminal
928
- * (`COMPLETED`/`CANCELLED`). Tanpa ini, transisi tersebut ditolak dengan
929
- * `IllegalTaskTransitionError`.
930
- *
931
- * Ini bukan pelonggaran diam-diam: reopen tetap mungkin (operator yang salah
932
- * merge harus bisa membatalkannya), tetapi setiap pemanggil yang
933
- * melakukannya menyatakannya di kode dan bisa diaudit lewat grep, bukan
934
- * tersembunyi sebagai efek samping "tulis status apa saja".
935
- */
936
- allowReopen?: boolean
937
- /**
938
- * [LOOP-INV-13] Token lease milik pemanggil. Bila diberikan, `patchTask`
939
- * memverifikasi token itu masih memegang `session_authority` untuk sesi ini.
940
- * Token basi/tersingkir = `TaskAuthorityLostError`, tanpa menulis apa pun.
941
- *
942
- * `undefined` = pemanggil tanpa identitas lease (CLI interaktif / operator).
943
- * Mode itu sengaja tetap diizinkan supaya sesi tunggal tanpa kontensi tidak
944
- * berubah perilakunya.
945
- */
946
- authorityToken?: string
947
- }
948
-
949
- /**
950
- * [Fase 3 / LOOP-INV-12, LOOP-G21] Hasil verifikasi terstruktur untuk mengunci
951
- * transisi dari `VERIFYING` ke `COMPLETED` (lulus) atau `BLOCKED` (gagal).
952
- */
953
- export interface VerificationGateOutcome {
954
- readonly ok: boolean
955
- readonly verdict: "passed" | "failed" | "stale"
956
- readonly exitCode?: number | null
957
- readonly command?: string
958
- readonly summary?: string
959
- readonly integrityOk?: boolean
960
- readonly timestamp?: string
961
- }
962
-
963
- /** Format satu rekaman `TaskEvidence` berjenis `"verify"` secara deterministik. */
964
- export function buildVerificationTaskEvidence(outcome: VerificationGateOutcome): TaskEvidence {
965
- const at = outcome.timestamp ?? nowIso()
966
- const payload = {
967
- verdict: outcome.verdict,
968
- ok: outcome.ok,
969
- exitCode: outcome.exitCode ?? (outcome.ok ? 0 : 1),
970
- ...(outcome.command ? { command: scrubSecrets(outcome.command).slice(0, 200) } : {}),
971
- summary: scrubSecrets(
972
- outcome.summary ?? (outcome.ok ? "verification passed" : "verification failed"),
973
- ).slice(0, 500),
974
- ...(typeof outcome.integrityOk === "boolean" ? { integrityOk: outcome.integrityOk } : {}),
975
- timestamp: at,
976
- }
977
- return {
978
- kind: "verify",
979
- detail: JSON.stringify(payload),
980
- at,
981
- }
982
- }
983
-
984
- /**
985
- * PHASE 6B: authority mode.
986
- *
987
- * `LEGACY` (the default, and the only mode in production today) preserves the
988
- * historical behaviour where any writer may author `IN_PROGRESS`.
989
- *
990
- * `SCHEDULER` closes that door: `IN_PROGRESS` may then be authored ONLY by
991
- * `claimTask`. Model-facing `todo_write` therefore fails closed with
992
- * `TASK_AUTHORITY_VIOLATION` instead of creating a claim.
993
- *
994
- * Activation is explicit and per-instance. There is no environment variable, no
995
- * module-level flag, and no automatic activation on `initialize()`.
996
- */
997
- export type TaskAuthorityMode = "LEGACY" | "SCHEDULER"
998
-
999
- export interface TaskStoreOptions {
1000
- /**
1001
- * PHASE 6B. Defaults to `"LEGACY"`. Must be opted into by a composition root.
1002
- * Tests must assert that no production path sets this.
1003
- */
1004
- authority?: TaskAuthorityMode
1005
- }
1006
-
1007
- /**
1008
- * Render a status allow-list as a SQL literal list.
1009
- *
1010
- * The values are module-private compile-time constants (`TaskStatus` members),
1011
- * never caller input, so this needs no escaping. It exists so the claim and
1012
- * reconcile predicates read as one auditable statement each, instead of string
1013
- * concatenation repeated per call site.
1014
- */
1015
- function sqlList(statuses: readonly TaskStatus[]): string {
1016
- return statuses.map((s) => `'${s}'`).join(", ")
1017
- }
1018
-
1019
- /**
1020
- * PHASE 6B: the only status a claim may transition from.
1021
- *
1022
- * `COMPLETED`, `CANCELLED` and `FAILED` are irreversible and are therefore not
1023
- * claimable — which is what stops a claim from resurrecting finished or
1024
- * abandoned work. `IN_PROGRESS` and `VERIFYING` are excluded because a second
1025
- * claim of in-flight work is exactly the double-claim the primitive prevents.
1026
- */
1027
- const CLAIMABLE_STATUSES: readonly TaskStatus[] = ["PENDING"]
1028
-
1029
124
  /**
1030
125
  * PHASE 6B: the only statuses reconciliation may revert.
1031
126
  *
@@ -1396,6 +491,16 @@ export class TaskStore {
1396
491
  }
1397
492
  const ev = buildVerificationTaskEvidence(outcome)
1398
493
  const mergedEvidence = [...(base.evidence ?? []).slice(-(MAX_EVIDENCE - 1)), ev]
494
+ const verification: TaskVerification = {
495
+ verdict:
496
+ outcome.verdict === "passed"
497
+ ? "passed"
498
+ : outcome.verdict === "failed" || outcome.verdict === "stale"
499
+ ? "failed"
500
+ : "unverified",
501
+ ...(ev.detail ? { detail: ev.detail } : {}),
502
+ checkedAt: ev.at,
503
+ }
1399
504
  if (outcome.ok) {
1400
505
  return this.patchTask(
1401
506
  sessionId,
@@ -1403,6 +508,7 @@ export class TaskStore {
1403
508
  {
1404
509
  status: "COMPLETED",
1405
510
  blockedReason: null,
511
+ verification,
1406
512
  evidence: mergedEvidence,
1407
513
  },
1408
514
  nextOpts,
@@ -1417,6 +523,7 @@ export class TaskStore {
1417
523
  {
1418
524
  status: "BLOCKED",
1419
525
  blockedReason: reason,
526
+ verification,
1420
527
  evidence: mergedEvidence,
1421
528
  },
1422
529
  nextOpts,
@@ -2693,18 +1800,7 @@ export class TaskStore {
2693
1800
 
2694
1801
  /** Close the handle. For tests and explicit shutdown only. */
2695
1802
  static close(cwd?: string): void {
2696
- const p = dbFile(cwd)
2697
- // Closing the connection under an open transaction would abandon a
2698
- // half-applied unit of work with no way to roll it back.
2699
- assertNoOpenTx(p, "close the store")
2700
- const db = handles.get(p)
2701
- if (db) {
2702
- try {
2703
- db.close()
2704
- } catch {}
2705
- handles.delete(p)
2706
- initialized.delete(p)
2707
- }
1803
+ closeTaskStoreHandle(cwd)
2708
1804
  }
2709
1805
 
2710
1806
  // ── transaction boundary (Phase 4A.2) ─────────────────────────────────────
@@ -2736,12 +1832,15 @@ export class TaskStore {
2736
1832
  *
2737
1833
  * Errors from `fn` propagate unchanged after rollback.
2738
1834
  */
2739
- withTransaction<T>(fn: (tx: TaskStore) => T): T {
1835
+ withTransaction<T>(fn: (tx: TaskStore) => T, immediate = false): T {
2740
1836
  const p = dbFile(this.cwd)
2741
1837
  const db = handle(this.cwd)
2742
- txDepth.set(p, (txDepth.get(p) ?? 0) + 1)
1838
+ const depth = txDepth.get(p) ?? 0
1839
+ txDepth.set(p, depth + 1)
2743
1840
  try {
2744
- return db.transaction(() => fn(this))()
1841
+ const txn = db.transaction(() => fn(this))
1842
+ // IMMEDIATE mengambil lock tulis sejak awal agar pola baca-lalu-tulis lintas koneksi tidak terkena deadlock upgrade SQLite.
1843
+ return immediate && depth === 0 ? txn.immediate() : txn()
2745
1844
  } finally {
2746
1845
  const d = (txDepth.get(p) ?? 1) - 1
2747
1846
  if (d <= 0) txDepth.delete(p)
@@ -2893,31 +1992,3 @@ export class TaskStore {
2893
1992
  return a !== null && a.ownerToken === ownerToken && a.leaseExpiresAt > now
2894
1993
  }
2895
1994
  }
2896
-
2897
- /** Discard the handle cache. For hermetic tests only. */
2898
- export function resetTaskStoreHandles(): void {
2899
- // Refuse while any transaction is open, for the same reason `close` does.
2900
- const open = openTxPaths()
2901
- if (open.length > 0) {
2902
- throw new TaskError(
2903
- "TASK_TX_ACTIVE",
2904
- `cannot reset task store handles while ${open.length} transaction(s) are open`,
2905
- )
2906
- }
2907
- for (const db of handles.values()) {
2908
- try {
2909
- db.close()
2910
- } catch {}
2911
- }
2912
- handles.clear()
2913
- initialized.clear()
2914
- }
2915
-
2916
- /** Legacy-source fingerprint, used by migration so a re-import of identical
2917
- * content changes nothing. */
2918
- export function legacyDigest(raw: string): string {
2919
- // `scrubSecrets` is used so a secret accidentally present in the legacy file
2920
- // is neither hashed nor leaked through the marker.
2921
- const { createHash } = require("node:crypto") as typeof import("node:crypto")
2922
- return createHash("sha256").update(scrubSecrets(raw)).digest("hex").slice(0, 32)
2923
- }