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