@ancientpantheon/khronoton-core 0.12.0 → 0.14.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/CHANGELOG.md +35 -0
- package/README.md +8 -0
- package/dist/blockchain/stoachain.d.ts +1 -1
- package/dist/blockchain/stoachain.js +16 -1
- package/dist/{chunk-GIGLXIMC.js → chunk-A5YODPKQ.js} +820 -23
- package/dist/{chunk-KQZYMPZS.js → chunk-WKI52IPY.js} +1 -1
- package/dist/{context-CApk-LP4.d.ts → context-P-rCtBbJ.d.ts} +1 -1
- package/dist/handlers/execute.d.ts +12 -4
- package/dist/handlers/execute.js +42 -5
- package/dist/handlers/index.d.ts +2 -1
- package/dist/handlers/index.js +4 -1
- package/dist/handlers/read.d.ts +11 -0
- package/dist/handlers/read.js +65 -1
- package/dist/handlers/steps.d.ts +3 -0
- package/dist/handlers/steps.js +152 -0
- package/dist/hooks/index.d.ts +3 -3
- package/dist/hooks/index.js +2 -2
- package/dist/provider/index.d.ts +3 -3
- package/dist/provider/index.js +33 -2
- package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
- package/dist/server/executor.d.ts +14 -1
- package/dist/server/executor.js +144 -26
- package/dist/server/index.d.ts +12 -2
- package/dist/server/index.js +38 -1
- package/dist/server/loop.d.ts +17 -13
- package/dist/server/loop.js +19 -12
- package/dist/server/planners/evict.d.ts +20 -0
- package/dist/server/planners/evict.js +143 -0
- package/dist/server/planners/inject.d.ts +22 -0
- package/dist/server/planners/inject.js +120 -0
- package/dist/server/planners/registry.d.ts +118 -0
- package/dist/server/planners/registry.js +94 -0
- package/dist/server/planners/stoa-unwrap.d.ts +23 -0
- package/dist/server/planners/stoa-unwrap.js +204 -0
- package/dist/server/planners/stoa-wrap.d.ts +26 -0
- package/dist/server/planners/stoa-wrap.js +229 -0
- package/dist/server/planners/unstall.d.ts +25 -0
- package/dist/server/planners/unstall.js +135 -0
- package/dist/server/pure/run-advance.d.ts +76 -0
- package/dist/server/pure/run-advance.js +94 -0
- package/dist/server/pure/split-plan.d.ts +144 -0
- package/dist/server/pure/split-plan.js +362 -0
- package/dist/server/pure/yields.d.ts +57 -0
- package/dist/server/pure/yields.js +101 -0
- package/dist/server/resolvers.js +48 -6
- package/dist/server/runs-driver.d.ts +92 -0
- package/dist/server/runs-driver.js +582 -0
- package/dist/server/schema.d.ts +6 -2
- package/dist/server/schema.js +89 -1
- package/dist/server/seams.d.ts +28 -0
- package/dist/server/seams.js +4 -0
- package/dist/server/store/errors.d.ts +38 -0
- package/dist/server/store/errors.js +61 -0
- package/dist/server/store/index.d.ts +7 -2
- package/dist/server/store/index.js +8 -2
- package/dist/server/store/mappers.d.ts +11 -0
- package/dist/server/store/mappers.js +20 -0
- package/dist/server/store/runs.d.ts +233 -0
- package/dist/server/store/runs.js +341 -0
- package/dist/server/store/steps.d.ts +54 -0
- package/dist/server/store/steps.js +74 -0
- package/dist/server/store/yields.d.ts +46 -0
- package/dist/server/store/yields.js +73 -0
- package/dist/server/tick.d.ts +7 -0
- package/dist/server/tick.js +50 -1
- package/dist/server/types.d.ts +42 -3
- package/dist/ui/index.js +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* runs — the decision-free CRUD layer for `codex_cronoton_runs` +
|
|
3
|
+
* `codex_cronoton_run_legs` (the RUNTIME state of a chained run, per
|
|
4
|
+
* `docs/work/khronoton-chained-runs/design.md`'s Phase 1). No "is the
|
|
5
|
+
* barrier met," "which legs are missing," or "has the deadline passed"
|
|
6
|
+
* logic lives here — that's Phase 2's pure `advanceRun`, explicitly out of
|
|
7
|
+
* scope for this layer.
|
|
8
|
+
*
|
|
9
|
+
* The self-blocking invariant (design §5.6) — a non-terminal run blocks a
|
|
10
|
+
* NEW run of the SAME cronoton, but never a different one — is enforced by
|
|
11
|
+
* `schema.ts`'s partial unique index
|
|
12
|
+
* (`idx_codex_cronoton_runs_self_block ON codex_cronoton_runs(codex_cronoton_id)
|
|
13
|
+
* WHERE status IN ('planning', 'awaiting', 'advancing')`), not by a
|
|
14
|
+
* check-then-insert here. {@link createRun} lets the INSERT hit that index
|
|
15
|
+
* directly — the racing-callers window is closed by the index itself, the
|
|
16
|
+
* same posture `claim.ts`'s conditional UPDATE establishes for fires — and
|
|
17
|
+
* catches the resulting UNIQUE-constraint `SqliteError` by code, re-throwing
|
|
18
|
+
* the typed {@link RunAlreadyInFlightError} so no raw driver error escapes
|
|
19
|
+
* the store layer.
|
|
20
|
+
*
|
|
21
|
+
* `markLegSubmitted`'s "never re-submit, only poll" invariant (design §5.3)
|
|
22
|
+
* is enforced by a single conditional UPDATE (`WHERE status = 'pending'`)
|
|
23
|
+
* that only a genuinely-pending leg can satisfy. A second attempt on an
|
|
24
|
+
* already-submitted (or otherwise non-pending) leg matches zero rows and
|
|
25
|
+
* throws {@link LegAlreadySubmittedError} instead of silently overwriting the
|
|
26
|
+
* existing `request_key`.
|
|
27
|
+
*
|
|
28
|
+
* {@link claimLegForSubmit}/{@link releaseLegClaim} (Phase 5): a true
|
|
29
|
+
* claim-BEFORE-submit step, now shared with `claim.ts`'s idiom — closing a
|
|
30
|
+
* gap `markLegSubmitted` alone could not: `markLegSubmitted`'s guard runs
|
|
31
|
+
* AFTER the real chain submission, so it only ever protected against a
|
|
32
|
+
* SEQUENTIAL re-submission of a leg that already has a request key; it
|
|
33
|
+
* could not stop two CONCURRENT callers from both reading the same
|
|
34
|
+
* `pending` leg and both submitting to chain before either wrote
|
|
35
|
+
* `markLegSubmitted`. `runs-driver.ts`'s `handleSubmitLeg` now calls
|
|
36
|
+
* `claimLegForSubmit` immediately before the real network submit — exactly
|
|
37
|
+
* one of any two concurrent callers racing the same leg can win that
|
|
38
|
+
* conditional UPDATE, so at most one ever reaches the network call. This
|
|
39
|
+
* was deferred during Phase 3 ("no such caller exists yet") until Phase 5's
|
|
40
|
+
* `executeNow` fix made a genuine concurrent caller (an HTTP-triggered
|
|
41
|
+
* `driveRunOnce` racing the background loop's own sweep) real.
|
|
42
|
+
*/
|
|
43
|
+
import { randomUUID } from "node:crypto";
|
|
44
|
+
import { isUniqueConstraintError, LegAlreadySubmittedError, LegNotSubmittedError, RunAlreadyInFlightError, RunAlreadyTerminalError, RunLegAlreadyExistsError, RunStepMismatchError, } from "./errors.js";
|
|
45
|
+
/**
|
|
46
|
+
* Insert a new run row. Lets the partial unique self-block index
|
|
47
|
+
* (`schema.ts`) be the actual enforcement: a racing/overlapping INSERT for a
|
|
48
|
+
* cronoton that already has a non-terminal run throws a UNIQUE-constraint
|
|
49
|
+
* `SqliteError`, caught here and re-thrown as the typed
|
|
50
|
+
* {@link RunAlreadyInFlightError} — never a raw driver error.
|
|
51
|
+
*/
|
|
52
|
+
export function createRun(input, dep) {
|
|
53
|
+
const id = randomUUID();
|
|
54
|
+
const now = new Date().toISOString();
|
|
55
|
+
try {
|
|
56
|
+
dep.db
|
|
57
|
+
.prepare(`INSERT INTO codex_cronoton_runs
|
|
58
|
+
(id, codex_cronoton_id, step_count, started_at, modified_at, deadline_at, context_json)
|
|
59
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`)
|
|
60
|
+
.run(id, input.codexCronotonId, input.stepCount, now, now, input.deadlineAt ?? null, input.contextJson !== undefined ? JSON.stringify(input.contextJson) : null);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (isUniqueConstraintError(error)) {
|
|
64
|
+
throw new RunAlreadyInFlightError(input.codexCronotonId);
|
|
65
|
+
}
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
return id;
|
|
69
|
+
}
|
|
70
|
+
/** Read back one run row by id, or null if it doesn't exist. */
|
|
71
|
+
export function getRun(runId, dep) {
|
|
72
|
+
const row = dep.db
|
|
73
|
+
.prepare(`SELECT * FROM codex_cronoton_runs WHERE id = ?`)
|
|
74
|
+
.get(runId);
|
|
75
|
+
return row ?? null;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Every non-terminal run (`planning`/`awaiting`/`advancing`), ordered by
|
|
79
|
+
* `modified_at` ascending — the read `advanceInFlightRunsOnce` polls every
|
|
80
|
+
* pass to find which runs need driving forward. Uses the existing
|
|
81
|
+
* `idx_codex_cronoton_runs_due` index (`schema.ts`), previously unused by
|
|
82
|
+
* any store function.
|
|
83
|
+
*/
|
|
84
|
+
export function listInFlightRuns(dep) {
|
|
85
|
+
return dep.db
|
|
86
|
+
.prepare(`SELECT * FROM codex_cronoton_runs
|
|
87
|
+
WHERE status IN ('planning', 'awaiting', 'advancing')
|
|
88
|
+
ORDER BY modified_at ASC`)
|
|
89
|
+
.all();
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Paginated run history for a cronoton, newest-first by `started_at` —
|
|
93
|
+
* mirrors `fires.ts`'s {@link listFires} exact pagination shape (`limit`
|
|
94
|
+
* clamped to `[1,100]`, default `20`; `offset` clamped to `>=0`, default
|
|
95
|
+
* `0`; a separate `COUNT(*)` query; `{rows, total}`-shaped return).
|
|
96
|
+
*/
|
|
97
|
+
export function listRunsForCronoton(codexCronotonId, params = {}, dep) {
|
|
98
|
+
const db = dep.db;
|
|
99
|
+
const limit = Math.min(Math.max(params.limit ?? 20, 1), 100);
|
|
100
|
+
const offset = Math.max(params.offset ?? 0, 0);
|
|
101
|
+
const runs = db
|
|
102
|
+
.prepare(`SELECT * FROM codex_cronoton_runs
|
|
103
|
+
WHERE codex_cronoton_id = ?
|
|
104
|
+
ORDER BY started_at DESC LIMIT ? OFFSET ?`)
|
|
105
|
+
.all(codexCronotonId, limit, offset);
|
|
106
|
+
const totalRow = db
|
|
107
|
+
.prepare("SELECT COUNT(*) AS c FROM codex_cronoton_runs WHERE codex_cronoton_id = ?")
|
|
108
|
+
.get(codexCronotonId);
|
|
109
|
+
return { runs, total: totalRow?.c ?? 0 };
|
|
110
|
+
}
|
|
111
|
+
/** Every leg for a run, ordered by (step_index, leg_index) ascending. */
|
|
112
|
+
export function listRunLegs(runId, dep) {
|
|
113
|
+
return dep.db
|
|
114
|
+
.prepare(`SELECT * FROM codex_cronoton_run_legs
|
|
115
|
+
WHERE run_id = ?
|
|
116
|
+
ORDER BY step_index ASC, leg_index ASC`)
|
|
117
|
+
.all(runId);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Write a leg row in `status='pending'` with no `request_key` — the
|
|
121
|
+
* write-before-submit discipline (design, mirroring `tick.ts`'s
|
|
122
|
+
* claim-before-fire one level down): a leg must exist before its
|
|
123
|
+
* transaction is ever submitted, never after.
|
|
124
|
+
*
|
|
125
|
+
* Lets the unique index on `(run_id, step_index, leg_index)` (`schema.ts`)
|
|
126
|
+
* be the actual enforcement, mirroring `createRun`/`insertStep`: a duplicate
|
|
127
|
+
* slot insert throws a UNIQUE-constraint `SqliteError`, caught here and
|
|
128
|
+
* re-thrown as the typed {@link RunLegAlreadyExistsError} — never a raw
|
|
129
|
+
* driver error escaping the store layer.
|
|
130
|
+
*/
|
|
131
|
+
export function insertRunLeg(input, dep) {
|
|
132
|
+
const id = randomUUID();
|
|
133
|
+
try {
|
|
134
|
+
dep.db
|
|
135
|
+
.prepare(`INSERT INTO codex_cronoton_run_legs (id, run_id, step_index, leg_index, definition_json, attempt)
|
|
136
|
+
VALUES (?, ?, ?, ?, ?, ?)`)
|
|
137
|
+
.run(id, input.runId, input.stepIndex, input.legIndex, input.definitionJson, input.attempt ?? 0);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (isUniqueConstraintError(error)) {
|
|
141
|
+
throw new RunLegAlreadyExistsError(input.runId, input.stepIndex, input.legIndex);
|
|
142
|
+
}
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
return id;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Claim a `pending` leg for submission, BEFORE the real chain call —
|
|
149
|
+
* closing the concurrency gap `runs-driver.ts`'s `handleSubmitLeg` used to
|
|
150
|
+
* defer (see its own doc comment history): the conditional `WHERE status =
|
|
151
|
+
* 'pending' AND claimed_at IS NULL` is a true claim-before-submit step,
|
|
152
|
+
* mirroring `claim.ts`'s `claimDueCodexCronoton` idiom one level down —
|
|
153
|
+
* two concurrent callers racing the same `pending` leg can never BOTH win
|
|
154
|
+
* this UPDATE, so at most one proceeds to the real network submit. Returns
|
|
155
|
+
* `true` iff THIS call won the claim.
|
|
156
|
+
*
|
|
157
|
+
* KNOWN, ACCEPTED LIMITATION (not the same shape as `claimDueCodexCronoton`'s
|
|
158
|
+
* one-shot claim — reviewed and deliberately left as a bounded tradeoff
|
|
159
|
+
* rather than built out further here): this claim is a TWO-PHASE lease —
|
|
160
|
+
* something must later call {@link markLegSubmitted} or
|
|
161
|
+
* {@link releaseLegClaim} to make the leg claimable again. If the process
|
|
162
|
+
* crashes (OOM-kill, hard restart) strictly between a won claim and either
|
|
163
|
+
* of those two calls, the leg is stuck `pending` with `claimed_at` set
|
|
164
|
+
* forever — `executeCodexTransaction`'s own documented "submit never
|
|
165
|
+
* throws" contract (`executor.ts`) means no in-process `try`/`finally`
|
|
166
|
+
* here could ever help (there is no exception to catch), and only a
|
|
167
|
+
* genuine process-level crash reaches this window at all. The run still
|
|
168
|
+
* recovers, just more slowly than before this fix: `advanceRun`'s
|
|
169
|
+
* deadline-exceeded branch (`pure/run-advance.ts`) eventually re-plans
|
|
170
|
+
* (bumping `attempt`, which excludes the orphaned leg from all future
|
|
171
|
+
* barrier checks) or fails the run outright — bounded by
|
|
172
|
+
* `RUN_STEP_DEADLINE_MS` (10 minutes by default) rather than "retry on the
|
|
173
|
+
* very next pass" as it was before. The orphaned leg row itself is
|
|
174
|
+
* permanently inert (never re-selected, never blocks anything else) —
|
|
175
|
+
* harmless DB clutter, not a stuck run. A reconciliation sweep that frees
|
|
176
|
+
* an expired claim before the full step deadline is a legitimate future
|
|
177
|
+
* improvement, but is new recovery machinery deserving its own scoped
|
|
178
|
+
* design, not a drive-by addition here (matching this file's own existing
|
|
179
|
+
* "no retry-cap mechanism... an operator noticing is the backstop today"
|
|
180
|
+
* posture for a different, pre-existing limitation).
|
|
181
|
+
*/
|
|
182
|
+
export function claimLegForSubmit(legId, claimedAt, dep) {
|
|
183
|
+
const result = dep.db
|
|
184
|
+
.prepare(`UPDATE codex_cronoton_run_legs
|
|
185
|
+
SET claimed_at = ?
|
|
186
|
+
WHERE id = ? AND status = 'pending' AND claimed_at IS NULL`)
|
|
187
|
+
.run(claimedAt, legId);
|
|
188
|
+
return result.changes === 1;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Release a claim taken by {@link claimLegForSubmit} after a submit attempt
|
|
192
|
+
* that did NOT land (so the leg stays `pending` for a later pass to retry —
|
|
193
|
+
* the existing "no retry-cap mechanism" posture, unchanged). Unconditional:
|
|
194
|
+
* the caller already knows it won the claim it's releasing, so there is no
|
|
195
|
+
* race to guard against here (only the claim ACQUISITION needs the
|
|
196
|
+
* conditional guard above). See {@link claimLegForSubmit}'s own doc for the
|
|
197
|
+
* one known gap this does NOT cover: a process crash between the claim and
|
|
198
|
+
* this call (or `markLegSubmitted`) leaves exactly one permanently-orphaned
|
|
199
|
+
* `pending`+`claimed_at`-set leg row per occurrence — harmless, never
|
|
200
|
+
* cleaned up by this function, by design (nothing calls this except the
|
|
201
|
+
* normal submit-failure path).
|
|
202
|
+
*/
|
|
203
|
+
export function releaseLegClaim(legId, dep) {
|
|
204
|
+
dep.db.prepare(`UPDATE codex_cronoton_run_legs SET claimed_at = NULL WHERE id = ?`).run(legId);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Flip a `pending` leg to `submitted`, stamping `request_key`/`chain_id`/
|
|
208
|
+
* `submitted_at`. The conditional `WHERE status = 'pending'` is the
|
|
209
|
+
* enforcement for "never re-submit, only poll": a leg that's already
|
|
210
|
+
* `submitted` (or further along) matches zero rows, so a second call throws
|
|
211
|
+
* {@link LegAlreadySubmittedError} instead of overwriting the existing key.
|
|
212
|
+
* Does NOT clear `claimed_at` — once `status` leaves `'pending'`,
|
|
213
|
+
* `claimLegForSubmit`'s own `WHERE status = 'pending'` guard already makes
|
|
214
|
+
* `claimed_at` irrelevant for this leg forever (a non-pending leg can never
|
|
215
|
+
* be claimed again), so there is nothing left to clean up.
|
|
216
|
+
*/
|
|
217
|
+
export function markLegSubmitted(legId, input, dep) {
|
|
218
|
+
const result = dep.db
|
|
219
|
+
.prepare(`UPDATE codex_cronoton_run_legs
|
|
220
|
+
SET status = 'submitted', request_key = ?, chain_id = ?, submitted_at = ?
|
|
221
|
+
WHERE id = ? AND status = 'pending'`)
|
|
222
|
+
.run(input.requestKey, input.chainId, new Date().toISOString(), legId);
|
|
223
|
+
if (result.changes !== 1) {
|
|
224
|
+
throw new LegAlreadySubmittedError(legId);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Flip a `submitted` leg to its `confirmed` terminal status, stamping
|
|
229
|
+
* `confirmed_at`. The conditional `WHERE status = 'submitted'` is the
|
|
230
|
+
* enforcement, mirroring `markLegSubmitted`'s own guard one level up: a leg
|
|
231
|
+
* that was never submitted (still `pending`) or is already terminal
|
|
232
|
+
* (`confirmed`/`failed`) cannot be silently flipped — a leg that never
|
|
233
|
+
* reached the chain must never be treated as "funds moved," and an
|
|
234
|
+
* already-terminal leg must never be overwritten.
|
|
235
|
+
*/
|
|
236
|
+
export function markLegConfirmed(legId, dep) {
|
|
237
|
+
const result = dep.db
|
|
238
|
+
.prepare(`UPDATE codex_cronoton_run_legs
|
|
239
|
+
SET status = 'confirmed', confirmed_at = ?
|
|
240
|
+
WHERE id = ? AND status = 'submitted'`)
|
|
241
|
+
.run(new Date().toISOString(), legId);
|
|
242
|
+
if (result.changes !== 1) {
|
|
243
|
+
throw new LegNotSubmittedError(legId);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Flip a `submitted` leg to its `failed` terminal status, stamping
|
|
248
|
+
* `error_message`. Same guard as {@link markLegConfirmed} — a leg that was
|
|
249
|
+
* never submitted or is already terminal cannot be silently flipped (in
|
|
250
|
+
* particular, an already-`confirmed` leg can never be overwritten back to
|
|
251
|
+
* `failed`, which would otherwise invite a caller to re-submit a leg whose
|
|
252
|
+
* first attempt already landed on-chain).
|
|
253
|
+
*/
|
|
254
|
+
export function markLegFailed(legId, input, dep) {
|
|
255
|
+
const result = dep.db
|
|
256
|
+
.prepare(`UPDATE codex_cronoton_run_legs
|
|
257
|
+
SET status = 'failed', error_message = ?
|
|
258
|
+
WHERE id = ? AND status = 'submitted'`)
|
|
259
|
+
.run(input.errorMessage, legId);
|
|
260
|
+
if (result.changes !== 1) {
|
|
261
|
+
throw new LegNotSubmittedError(legId);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Move a run from `fromStepIndex` to `toStepIndex`, resetting `attempt` to 0
|
|
266
|
+
* and stamping a new `deadline_at`/`modified_at`. The trailing `WHERE ... AND
|
|
267
|
+
* step_index = ?` is an optimistic-concurrency guard, mirroring
|
|
268
|
+
* `markLegSubmitted`'s conditional-UPDATE-as-the-guard idiom one level up: if
|
|
269
|
+
* another process already moved this run's step, this call's precondition is
|
|
270
|
+
* stale and must fail loudly rather than overwrite it.
|
|
271
|
+
*
|
|
272
|
+
* Doubles as both "really advance to the next step" (`toStepIndex ===
|
|
273
|
+
* fromStepIndex + 1`) and "stamp this step's first deadline without moving
|
|
274
|
+
* it" (`toStepIndex === fromStepIndex`, used when a step's leg is first
|
|
275
|
+
* planned) — one function, two callers, same guard.
|
|
276
|
+
*/
|
|
277
|
+
export function advanceRunStep(runId, input, dep) {
|
|
278
|
+
const result = dep.db
|
|
279
|
+
.prepare(`UPDATE codex_cronoton_runs
|
|
280
|
+
SET step_index = ?, attempt = 0, deadline_at = ?, modified_at = ?
|
|
281
|
+
WHERE id = ? AND step_index = ?`)
|
|
282
|
+
.run(input.toStepIndex, input.deadlineAt, new Date().toISOString(), runId, input.fromStepIndex);
|
|
283
|
+
if (result.changes !== 1) {
|
|
284
|
+
throw new RunStepMismatchError(runId, input.fromStepIndex);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Increment a run's `attempt` by one, stamping `modified_at`. Unconditional —
|
|
289
|
+
* no precondition — incrementing is commutative regardless of caller
|
|
290
|
+
* ordering, so there is no stale-view case to guard against the way
|
|
291
|
+
* {@link advanceRunStep}'s `WHERE step_index = ?` must. This is the Phase-3
|
|
292
|
+
* design anticipated (and correctly deferred, since nothing exercised it
|
|
293
|
+
* yet — see `docs/work/khronoton-chained-runs-phase-3/design.md`'s §G): a
|
|
294
|
+
* genuine re-plan (a `canReplan:true` step whose leg actually fails) bumps
|
|
295
|
+
* `attempt` here INSTEAD OF going through `advanceRunStep`, specifically to
|
|
296
|
+
* avoid `advanceRunStep`'s own unconditional `attempt = 0` reset undoing the
|
|
297
|
+
* bump on every single re-plan.
|
|
298
|
+
*/
|
|
299
|
+
export function bumpRunAttempt(runId, dep) {
|
|
300
|
+
dep.db
|
|
301
|
+
.prepare(`UPDATE codex_cronoton_runs SET attempt = attempt + 1, modified_at = ? WHERE id = ?`)
|
|
302
|
+
.run(new Date().toISOString(), runId);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Stamp a fresh `deadline_at`/`modified_at`, touching NOTHING else — in
|
|
306
|
+
* particular, never `attempt` or `step_index`. Narrower than
|
|
307
|
+
* {@link advanceRunStep} on purpose: `advanceRunStep` unconditionally resets
|
|
308
|
+
* `attempt` to `0` as part of its contract, which is correct for a real
|
|
309
|
+
* step-advance or a step's very first deadline stamp (`attempt` is already
|
|
310
|
+
* `0` in both those cases) but WRONG immediately after {@link bumpRunAttempt}
|
|
311
|
+
* has just incremented `attempt` for a genuine re-plan — calling
|
|
312
|
+
* `advanceRunStep` there would silently reset the bump back to `0` on every
|
|
313
|
+
* re-plan, making `replanOrFail`'s `attempt < maxReplanAttempts` check
|
|
314
|
+
* permanently true and turning `maxReplanAttempts` into dead config (an
|
|
315
|
+
* infinite retry loop with no error ever surfacing). No optimistic-
|
|
316
|
+
* concurrency guard is needed here (unlike `advanceRunStep`'s
|
|
317
|
+
* `WHERE step_index = ?`): this function never touches `step_index`, so
|
|
318
|
+
* there is no stale-precondition case to guard against.
|
|
319
|
+
*/
|
|
320
|
+
export function touchRunDeadline(runId, deadlineAt, dep) {
|
|
321
|
+
dep.db
|
|
322
|
+
.prepare(`UPDATE codex_cronoton_runs SET deadline_at = ?, modified_at = ? WHERE id = ?`)
|
|
323
|
+
.run(deadlineAt, new Date().toISOString(), runId);
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Flip a non-terminal run to one of its terminal statuses
|
|
327
|
+
* (`succeeded`/`failed`/`abandoned`), stamping `modified_at`. The conditional
|
|
328
|
+
* `WHERE status NOT IN (...)` is the enforcement, mirroring
|
|
329
|
+
* `markLegConfirmed`/`markLegFailed`'s own terminal guard one level down: a
|
|
330
|
+
* run that's already terminal cannot be silently overwritten.
|
|
331
|
+
*/
|
|
332
|
+
export function markRunTerminal(runId, status, dep) {
|
|
333
|
+
const result = dep.db
|
|
334
|
+
.prepare(`UPDATE codex_cronoton_runs
|
|
335
|
+
SET status = ?, modified_at = ?
|
|
336
|
+
WHERE id = ? AND status NOT IN ('succeeded', 'failed', 'abandoned')`)
|
|
337
|
+
.run(status, new Date().toISOString(), runId);
|
|
338
|
+
if (result.changes !== 1) {
|
|
339
|
+
throw new RunAlreadyTerminalError(runId);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { DbDep } from "../seams.js";
|
|
2
|
+
export interface InsertStepInput {
|
|
3
|
+
codexCronotonId: string;
|
|
4
|
+
stepIndex: number;
|
|
5
|
+
mode: "single" | "planner";
|
|
6
|
+
pactCode?: string;
|
|
7
|
+
config?: unknown;
|
|
8
|
+
payload?: unknown;
|
|
9
|
+
gasPayer?: unknown;
|
|
10
|
+
signers?: unknown;
|
|
11
|
+
plannerName?: string;
|
|
12
|
+
plannerParams?: unknown;
|
|
13
|
+
idempotent?: boolean;
|
|
14
|
+
yieldAs?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface CodexCronotonStepRow {
|
|
17
|
+
id: string;
|
|
18
|
+
codex_cronoton_id: string;
|
|
19
|
+
step_index: number;
|
|
20
|
+
mode: "single" | "planner";
|
|
21
|
+
pact_code: string | null;
|
|
22
|
+
config_json: string | null;
|
|
23
|
+
payload_json: string | null;
|
|
24
|
+
gas_payer_json: string | null;
|
|
25
|
+
signers_json: string | null;
|
|
26
|
+
planner_name: string | null;
|
|
27
|
+
planner_params_json: string | null;
|
|
28
|
+
idempotent: number;
|
|
29
|
+
created_at: string;
|
|
30
|
+
modified_at: string;
|
|
31
|
+
yield_as: string | null;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Insert one step row. Returns the new row's id.
|
|
35
|
+
*
|
|
36
|
+
* Lets the unique index on `(codex_cronoton_id, step_index)` (`schema.ts`)
|
|
37
|
+
* be the actual enforcement, mirroring `runs.ts`'s `createRun`: a duplicate
|
|
38
|
+
* step index for the same cronoton throws a UNIQUE-constraint `SqliteError`,
|
|
39
|
+
* caught here and re-thrown as the typed {@link StepAlreadyExistsError} —
|
|
40
|
+
* never a raw driver error escaping the store layer.
|
|
41
|
+
*/
|
|
42
|
+
export declare function insertStep(input: InsertStepInput, dep: DbDep): string;
|
|
43
|
+
/** Full raw snake_case rows for a cronoton's steps, ordered by step_index ASC. */
|
|
44
|
+
export declare function listStepsForCronoton(codexCronotonId: string, dep: DbDep): CodexCronotonStepRow[];
|
|
45
|
+
/**
|
|
46
|
+
* One step row at a specific `(codexCronotonId, stepIndex)` slot, or `null`.
|
|
47
|
+
* A direct point lookup hitting `idx_codex_cronoton_steps_order` (the
|
|
48
|
+
* existing unique index on exactly this pair, `schema.ts`), instead of a
|
|
49
|
+
* caller fetching every step for the cronoton via {@link listStepsForCronoton}
|
|
50
|
+
* and filtering client-side for one row — a confirmed LOW performance
|
|
51
|
+
* finding from `handlers/steps.ts`'s standalone fire/simulate route, which
|
|
52
|
+
* only ever needs one step per request.
|
|
53
|
+
*/
|
|
54
|
+
export declare function getStepByIndex(codexCronotonId: string, stepIndex: number, dep: DbDep): CodexCronotonStepRow | null;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* steps — the decision-free CRUD layer for `codex_cronoton_steps`, the STATIC
|
|
3
|
+
* step definitions of a chained cronoton (design.md's Phase 1): step 0 might be
|
|
4
|
+
* a plain pact-code transaction (`mode: 'single'`), step 1 a registered planner
|
|
5
|
+
* that builds N legs at run time (`mode: 'planner'`, the planner registry
|
|
6
|
+
* itself a LATER phase, out of scope here).
|
|
7
|
+
*
|
|
8
|
+
* Purely mechanical, mirroring `./fires.ts`'s own level of ambition: no
|
|
9
|
+
* validation of step sequencing, no planner-registry lookup, no "is this the
|
|
10
|
+
* right next step" decision logic — that's explicitly Phase 2's job
|
|
11
|
+
* (`pure/run-advance.ts`), not this layer's.
|
|
12
|
+
*
|
|
13
|
+
* `yieldAs`/`yield_as` (step-to-step yield carry, per
|
|
14
|
+
* `docs/work/khronoton-step-yield-carry/design.md`) applies uniformly to
|
|
15
|
+
* BOTH step modes: for `mode:'single'` it names what to store the confirmed
|
|
16
|
+
* leg's on-chain return value as; for `mode:'planner'` it names what to
|
|
17
|
+
* store the planner's returned yield value as. The step row itself owns the
|
|
18
|
+
* yield's NAME either way — never the planner, never hard-coded elsewhere.
|
|
19
|
+
*/
|
|
20
|
+
import crypto from "node:crypto";
|
|
21
|
+
import { isUniqueConstraintError, StepAlreadyExistsError } from "./errors.js";
|
|
22
|
+
/**
|
|
23
|
+
* Insert one step row. Returns the new row's id.
|
|
24
|
+
*
|
|
25
|
+
* Lets the unique index on `(codex_cronoton_id, step_index)` (`schema.ts`)
|
|
26
|
+
* be the actual enforcement, mirroring `runs.ts`'s `createRun`: a duplicate
|
|
27
|
+
* step index for the same cronoton throws a UNIQUE-constraint `SqliteError`,
|
|
28
|
+
* caught here and re-thrown as the typed {@link StepAlreadyExistsError} —
|
|
29
|
+
* never a raw driver error escaping the store layer.
|
|
30
|
+
*/
|
|
31
|
+
export function insertStep(input, dep) {
|
|
32
|
+
const id = crypto.randomUUID();
|
|
33
|
+
const now = new Date().toISOString();
|
|
34
|
+
try {
|
|
35
|
+
dep.db
|
|
36
|
+
.prepare(`INSERT INTO codex_cronoton_steps
|
|
37
|
+
(id, codex_cronoton_id, step_index, mode, pact_code, config_json,
|
|
38
|
+
payload_json, gas_payer_json, signers_json, planner_name,
|
|
39
|
+
planner_params_json, idempotent, created_at, modified_at, yield_as)
|
|
40
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
41
|
+
.run(id, input.codexCronotonId, input.stepIndex, input.mode, input.pactCode ?? null, input.config !== undefined ? JSON.stringify(input.config) : null, input.payload !== undefined ? JSON.stringify(input.payload) : null, input.gasPayer !== undefined ? JSON.stringify(input.gasPayer) : null, input.signers !== undefined ? JSON.stringify(input.signers) : null, input.plannerName ?? null, input.plannerParams !== undefined ? JSON.stringify(input.plannerParams) : null, input.idempotent ? 1 : 0, now, now, input.yieldAs ?? null);
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (isUniqueConstraintError(error)) {
|
|
45
|
+
throw new StepAlreadyExistsError(input.codexCronotonId, input.stepIndex);
|
|
46
|
+
}
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
return id;
|
|
50
|
+
}
|
|
51
|
+
/** Full raw snake_case rows for a cronoton's steps, ordered by step_index ASC. */
|
|
52
|
+
export function listStepsForCronoton(codexCronotonId, dep) {
|
|
53
|
+
return dep.db
|
|
54
|
+
.prepare(`SELECT * FROM codex_cronoton_steps
|
|
55
|
+
WHERE codex_cronoton_id = ?
|
|
56
|
+
ORDER BY step_index ASC`)
|
|
57
|
+
.all(codexCronotonId);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* One step row at a specific `(codexCronotonId, stepIndex)` slot, or `null`.
|
|
61
|
+
* A direct point lookup hitting `idx_codex_cronoton_steps_order` (the
|
|
62
|
+
* existing unique index on exactly this pair, `schema.ts`), instead of a
|
|
63
|
+
* caller fetching every step for the cronoton via {@link listStepsForCronoton}
|
|
64
|
+
* and filtering client-side for one row — a confirmed LOW performance
|
|
65
|
+
* finding from `handlers/steps.ts`'s standalone fire/simulate route, which
|
|
66
|
+
* only ever needs one step per request.
|
|
67
|
+
*/
|
|
68
|
+
export function getStepByIndex(codexCronotonId, stepIndex, dep) {
|
|
69
|
+
const row = dep.db
|
|
70
|
+
.prepare(`SELECT * FROM codex_cronoton_steps
|
|
71
|
+
WHERE codex_cronoton_id = ? AND step_index = ?`)
|
|
72
|
+
.get(codexCronotonId, stepIndex);
|
|
73
|
+
return row ?? null;
|
|
74
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { DbDep } from "../seams.js";
|
|
2
|
+
/**
|
|
3
|
+
* Insert-or-overwrite one named yield for a run. `ON CONFLICT(run_id, name)
|
|
4
|
+
* DO UPDATE` is the design's stated overwrite semantics (design.md's
|
|
5
|
+
* "Storage" section): a replanned step's freshest computed value always
|
|
6
|
+
* wins, with no separate invalidation step needed since nothing downstream
|
|
7
|
+
* of an unconfirmed step ever runs yet. `value` is JSON-stringified so any
|
|
8
|
+
* JSON-serializable on-chain return value (string, number, object) round-trips.
|
|
9
|
+
*
|
|
10
|
+
* `input.value` is normalized to `null` first when it is `undefined` —
|
|
11
|
+
* `JSON.stringify(undefined)` returns the JS value `undefined`, not a
|
|
12
|
+
* string, which `better-sqlite3`'s `.run()` refuses to bind (it only
|
|
13
|
+
* accepts numbers/bigints/strings/buffers/`null`) and throws. A caller can
|
|
14
|
+
* legitimately hit this: `runs-driver.ts`'s single-mode confirm path stores
|
|
15
|
+
* whatever on-chain return value a `ListenResult` carries, and that `data`
|
|
16
|
+
* field is optional on the wire — a real review finding caught this
|
|
17
|
+
* crashing AFTER the leg's `markLegConfirmed` write had already committed,
|
|
18
|
+
* permanently stranding an otherwise-successful run with no yield ever
|
|
19
|
+
* recorded. `null` round-trips through `value_json`/`getYieldPool` like any
|
|
20
|
+
* other JSON value, so a caller that legitimately yields `null` is
|
|
21
|
+
* unaffected — this only changes what an absent/`undefined` value becomes.
|
|
22
|
+
*/
|
|
23
|
+
export declare function upsertYield(input: {
|
|
24
|
+
runId: string;
|
|
25
|
+
name: string;
|
|
26
|
+
value: unknown;
|
|
27
|
+
stepIndex: number;
|
|
28
|
+
}, dep: DbDep): void;
|
|
29
|
+
/**
|
|
30
|
+
* The full `{name: value}` map for a run — `{}` for a run with zero yields.
|
|
31
|
+
* Every `value_json` is parsed back into its original JSON value, so a
|
|
32
|
+
* caller resolving a `{"$yield": "<name>"}` placeholder (`pure/yields.ts`)
|
|
33
|
+
* reads the same shape that was originally passed to {@link upsertYield}.
|
|
34
|
+
*
|
|
35
|
+
* Built via `Object.create(null)`, NOT a `{}` literal — a plain object
|
|
36
|
+
* literal inherits `Object.prototype`, so `pure/yields.ts`'s own
|
|
37
|
+
* `name in pool` membership check (which walks the prototype chain) would
|
|
38
|
+
* otherwise treat `"toString"`/`"constructor"`/`"hasOwnProperty"`/etc. as
|
|
39
|
+
* present even for an empty pool, silently resolving a `$yield` reference
|
|
40
|
+
* to a built-in function instead of throwing `YieldNotFoundError` — exactly
|
|
41
|
+
* the "never silently guess" invariant this feature is built around. A
|
|
42
|
+
* prototype-less object also makes a yield legitimately named `"__proto__"`
|
|
43
|
+
* store as an ordinary own property instead of reassigning the object's own
|
|
44
|
+
* prototype (which a `{}` literal's special `__proto__` setter would do).
|
|
45
|
+
*/
|
|
46
|
+
export declare function getYieldPool(runId: string, dep: DbDep): Record<string, unknown>;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* yields — the decision-free CRUD layer for `codex_cronoton_run_yields`, the
|
|
3
|
+
* flat named-yield pool a chained run's steps write to and read from (per
|
|
4
|
+
* `docs/work/khronoton-step-yield-carry/design.md`). Mirrors `./runs.ts`'s
|
|
5
|
+
* own style (`crypto.randomUUID()` ids, a `DbDep`-shaped second arg) rather
|
|
6
|
+
* than introducing a new idiom for this one table.
|
|
7
|
+
*
|
|
8
|
+
* No resolution/validation logic lives here — "does a referenced yield name
|
|
9
|
+
* exist" (`YieldNotFoundError`) is `pure/yields.ts`'s job (Wave 2's T2), not
|
|
10
|
+
* this layer's; this file only ever does the mechanical read/write.
|
|
11
|
+
*/
|
|
12
|
+
import crypto from "node:crypto";
|
|
13
|
+
/**
|
|
14
|
+
* Insert-or-overwrite one named yield for a run. `ON CONFLICT(run_id, name)
|
|
15
|
+
* DO UPDATE` is the design's stated overwrite semantics (design.md's
|
|
16
|
+
* "Storage" section): a replanned step's freshest computed value always
|
|
17
|
+
* wins, with no separate invalidation step needed since nothing downstream
|
|
18
|
+
* of an unconfirmed step ever runs yet. `value` is JSON-stringified so any
|
|
19
|
+
* JSON-serializable on-chain return value (string, number, object) round-trips.
|
|
20
|
+
*
|
|
21
|
+
* `input.value` is normalized to `null` first when it is `undefined` —
|
|
22
|
+
* `JSON.stringify(undefined)` returns the JS value `undefined`, not a
|
|
23
|
+
* string, which `better-sqlite3`'s `.run()` refuses to bind (it only
|
|
24
|
+
* accepts numbers/bigints/strings/buffers/`null`) and throws. A caller can
|
|
25
|
+
* legitimately hit this: `runs-driver.ts`'s single-mode confirm path stores
|
|
26
|
+
* whatever on-chain return value a `ListenResult` carries, and that `data`
|
|
27
|
+
* field is optional on the wire — a real review finding caught this
|
|
28
|
+
* crashing AFTER the leg's `markLegConfirmed` write had already committed,
|
|
29
|
+
* permanently stranding an otherwise-successful run with no yield ever
|
|
30
|
+
* recorded. `null` round-trips through `value_json`/`getYieldPool` like any
|
|
31
|
+
* other JSON value, so a caller that legitimately yields `null` is
|
|
32
|
+
* unaffected — this only changes what an absent/`undefined` value becomes.
|
|
33
|
+
*/
|
|
34
|
+
export function upsertYield(input, dep) {
|
|
35
|
+
const id = crypto.randomUUID();
|
|
36
|
+
const now = new Date().toISOString();
|
|
37
|
+
const value = input.value === undefined ? null : input.value;
|
|
38
|
+
dep.db
|
|
39
|
+
.prepare(`INSERT INTO codex_cronoton_run_yields (id, run_id, name, value_json, step_index, created_at)
|
|
40
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
41
|
+
ON CONFLICT(run_id, name) DO UPDATE SET
|
|
42
|
+
value_json = excluded.value_json,
|
|
43
|
+
step_index = excluded.step_index,
|
|
44
|
+
created_at = excluded.created_at`)
|
|
45
|
+
.run(id, input.runId, input.name, JSON.stringify(value), input.stepIndex, now);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The full `{name: value}` map for a run — `{}` for a run with zero yields.
|
|
49
|
+
* Every `value_json` is parsed back into its original JSON value, so a
|
|
50
|
+
* caller resolving a `{"$yield": "<name>"}` placeholder (`pure/yields.ts`)
|
|
51
|
+
* reads the same shape that was originally passed to {@link upsertYield}.
|
|
52
|
+
*
|
|
53
|
+
* Built via `Object.create(null)`, NOT a `{}` literal — a plain object
|
|
54
|
+
* literal inherits `Object.prototype`, so `pure/yields.ts`'s own
|
|
55
|
+
* `name in pool` membership check (which walks the prototype chain) would
|
|
56
|
+
* otherwise treat `"toString"`/`"constructor"`/`"hasOwnProperty"`/etc. as
|
|
57
|
+
* present even for an empty pool, silently resolving a `$yield` reference
|
|
58
|
+
* to a built-in function instead of throwing `YieldNotFoundError` — exactly
|
|
59
|
+
* the "never silently guess" invariant this feature is built around. A
|
|
60
|
+
* prototype-less object also makes a yield legitimately named `"__proto__"`
|
|
61
|
+
* store as an ordinary own property instead of reassigning the object's own
|
|
62
|
+
* prototype (which a `{}` literal's special `__proto__` setter would do).
|
|
63
|
+
*/
|
|
64
|
+
export function getYieldPool(runId, dep) {
|
|
65
|
+
const rows = dep.db
|
|
66
|
+
.prepare(`SELECT name, value_json FROM codex_cronoton_run_yields WHERE run_id = ?`)
|
|
67
|
+
.all(runId);
|
|
68
|
+
const pool = Object.create(null);
|
|
69
|
+
for (const row of rows) {
|
|
70
|
+
pool[row.name] = JSON.parse(row.value_json);
|
|
71
|
+
}
|
|
72
|
+
return pool;
|
|
73
|
+
}
|
package/dist/server/tick.d.ts
CHANGED
|
@@ -53,6 +53,13 @@ export interface CodexTickResult {
|
|
|
53
53
|
failedIds: string[];
|
|
54
54
|
/** Rows skipped without firing (lost claim, or an orchestration error). */
|
|
55
55
|
skippedIds: string[];
|
|
56
|
+
/**
|
|
57
|
+
* Chained-run ids created AND driven inline this pass (design.md §B).
|
|
58
|
+
* `loop.ts` passes this as `advanceInFlightRunsOnce`'s `excludeRunIds` so
|
|
59
|
+
* the sweep pass a moment later doesn't re-drive — and re-poll — a run
|
|
60
|
+
* this same tick pass already drove as far as it would synchronously go.
|
|
61
|
+
*/
|
|
62
|
+
drivenRunIds: string[];
|
|
56
63
|
}
|
|
57
64
|
/**
|
|
58
65
|
* Select → claim → fire → record → finalize → audit for every due codex
|