@ancientpantheon/khronoton-core 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +114 -0
  3. package/dist/blockchain/stoachain.d.ts +1 -1
  4. package/dist/blockchain/stoachain.js +16 -1
  5. package/dist/{chunk-LX6T2BDL.js → chunk-7H5TM3CS.js} +1 -1
  6. package/dist/{chunk-GNQ2IVXA.js → chunk-IAK4UEAA.js} +731 -24
  7. package/dist/{context-89YS4xT3.d.ts → context-P-rCtBbJ.d.ts} +2 -2
  8. package/dist/handlers/execute.d.ts +12 -4
  9. package/dist/handlers/execute.js +42 -5
  10. package/dist/handlers/index.d.ts +4 -2
  11. package/dist/handlers/index.js +7 -2
  12. package/dist/handlers/public.d.ts +41 -0
  13. package/dist/handlers/public.js +78 -0
  14. package/dist/handlers/read.d.ts +11 -0
  15. package/dist/handlers/read.js +65 -1
  16. package/dist/handlers/steps.d.ts +3 -0
  17. package/dist/handlers/steps.js +115 -0
  18. package/dist/hooks/index.d.ts +4 -4
  19. package/dist/hooks/index.js +2 -2
  20. package/dist/provider/index.d.ts +4 -4
  21. package/dist/provider/index.js +33 -2
  22. package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
  23. package/dist/server/executor.d.ts +14 -1
  24. package/dist/server/executor.js +144 -26
  25. package/dist/server/index.d.ts +11 -2
  26. package/dist/server/index.js +29 -1
  27. package/dist/server/loop.d.ts +17 -13
  28. package/dist/server/loop.js +19 -12
  29. package/dist/server/planners/evict.d.ts +20 -0
  30. package/dist/server/planners/evict.js +143 -0
  31. package/dist/server/planners/inject.d.ts +22 -0
  32. package/dist/server/planners/inject.js +120 -0
  33. package/dist/server/planners/registry.d.ts +80 -0
  34. package/dist/server/planners/registry.js +50 -0
  35. package/dist/server/planners/stoa-unwrap.d.ts +23 -0
  36. package/dist/server/planners/stoa-unwrap.js +204 -0
  37. package/dist/server/planners/stoa-wrap.d.ts +22 -0
  38. package/dist/server/planners/stoa-wrap.js +201 -0
  39. package/dist/server/planners/unstall.d.ts +25 -0
  40. package/dist/server/planners/unstall.js +135 -0
  41. package/dist/server/pure/run-advance.d.ts +76 -0
  42. package/dist/server/pure/run-advance.js +94 -0
  43. package/dist/server/pure/split-plan.d.ts +144 -0
  44. package/dist/server/pure/split-plan.js +362 -0
  45. package/dist/server/resolvers.js +48 -6
  46. package/dist/server/runs-driver.d.ts +92 -0
  47. package/dist/server/runs-driver.js +511 -0
  48. package/dist/server/schema.d.ts +12 -2
  49. package/dist/server/schema.js +105 -1
  50. package/dist/server/seams.d.ts +28 -0
  51. package/dist/server/seams.js +4 -0
  52. package/dist/server/store/errors.d.ts +38 -0
  53. package/dist/server/store/errors.js +61 -0
  54. package/dist/server/store/fires.js +27 -1
  55. package/dist/server/store/index.d.ts +8 -2
  56. package/dist/server/store/index.js +8 -2
  57. package/dist/server/store/mappers.d.ts +11 -0
  58. package/dist/server/store/mappers.js +20 -0
  59. package/dist/server/store/public.d.ts +104 -0
  60. package/dist/server/store/public.js +197 -0
  61. package/dist/server/store/runs.d.ts +233 -0
  62. package/dist/server/store/runs.js +341 -0
  63. package/dist/server/store/steps.d.ts +42 -0
  64. package/dist/server/store/steps.js +51 -0
  65. package/dist/server/tick.d.ts +7 -0
  66. package/dist/server/tick.js +50 -1
  67. package/dist/server/types.d.ts +55 -3
  68. package/dist/{types-DnFB1Yz-.d.ts → types-uYSglFrJ.d.ts} +13 -0
  69. package/dist/ui/index.d.ts +1 -1
  70. package/dist/ui/index.js +2 -2
  71. package/package.json +1 -1
@@ -0,0 +1,233 @@
1
+ import type { DbDep } from "../seams.js";
2
+ export interface CreateRunInput {
3
+ codexCronotonId: string;
4
+ stepCount: number;
5
+ deadlineAt?: string;
6
+ contextJson?: unknown;
7
+ }
8
+ export interface CodexCronotonRunRow {
9
+ id: string;
10
+ codex_cronoton_id: string;
11
+ fire_id: string | null;
12
+ status: "planning" | "awaiting" | "advancing" | "succeeded" | "failed" | "abandoned";
13
+ step_index: number;
14
+ step_count: number;
15
+ started_at: string;
16
+ modified_at: string;
17
+ deadline_at: string | null;
18
+ attempt: number;
19
+ context_json: string | null;
20
+ }
21
+ export interface CodexCronotonRunLegRow {
22
+ id: string;
23
+ run_id: string;
24
+ step_index: number;
25
+ leg_index: number;
26
+ status: "pending" | "submitted" | "confirmed" | "failed";
27
+ request_key: string | null;
28
+ chain_id: string | null;
29
+ definition_json: string;
30
+ error_message: string | null;
31
+ submitted_at: string | null;
32
+ confirmed_at: string | null;
33
+ attempt: number;
34
+ /** Set by {@link claimLegForSubmit} while a submit attempt is in flight;
35
+ * cleared by {@link releaseLegClaim} on a failed submit so a later pass
36
+ * can retry. `null` whenever no submit is currently in flight for this
37
+ * leg (the common case). */
38
+ claimed_at: string | null;
39
+ }
40
+ /**
41
+ * Insert a new run row. Lets the partial unique self-block index
42
+ * (`schema.ts`) be the actual enforcement: a racing/overlapping INSERT for a
43
+ * cronoton that already has a non-terminal run throws a UNIQUE-constraint
44
+ * `SqliteError`, caught here and re-thrown as the typed
45
+ * {@link RunAlreadyInFlightError} — never a raw driver error.
46
+ */
47
+ export declare function createRun(input: CreateRunInput, dep: DbDep): string;
48
+ /** Read back one run row by id, or null if it doesn't exist. */
49
+ export declare function getRun(runId: string, dep: DbDep): CodexCronotonRunRow | null;
50
+ /**
51
+ * Every non-terminal run (`planning`/`awaiting`/`advancing`), ordered by
52
+ * `modified_at` ascending — the read `advanceInFlightRunsOnce` polls every
53
+ * pass to find which runs need driving forward. Uses the existing
54
+ * `idx_codex_cronoton_runs_due` index (`schema.ts`), previously unused by
55
+ * any store function.
56
+ */
57
+ export declare function listInFlightRuns(dep: DbDep): CodexCronotonRunRow[];
58
+ /**
59
+ * Paginated run history for a cronoton, newest-first by `started_at` —
60
+ * mirrors `fires.ts`'s {@link listFires} exact pagination shape (`limit`
61
+ * clamped to `[1,100]`, default `20`; `offset` clamped to `>=0`, default
62
+ * `0`; a separate `COUNT(*)` query; `{rows, total}`-shaped return).
63
+ */
64
+ export declare function listRunsForCronoton(codexCronotonId: string, params: {
65
+ limit?: number;
66
+ offset?: number;
67
+ } | undefined, dep: DbDep): {
68
+ runs: CodexCronotonRunRow[];
69
+ total: number;
70
+ };
71
+ /** Every leg for a run, ordered by (step_index, leg_index) ascending. */
72
+ export declare function listRunLegs(runId: string, dep: DbDep): CodexCronotonRunLegRow[];
73
+ /**
74
+ * Write a leg row in `status='pending'` with no `request_key` — the
75
+ * write-before-submit discipline (design, mirroring `tick.ts`'s
76
+ * claim-before-fire one level down): a leg must exist before its
77
+ * transaction is ever submitted, never after.
78
+ *
79
+ * Lets the unique index on `(run_id, step_index, leg_index)` (`schema.ts`)
80
+ * be the actual enforcement, mirroring `createRun`/`insertStep`: a duplicate
81
+ * slot insert throws a UNIQUE-constraint `SqliteError`, caught here and
82
+ * re-thrown as the typed {@link RunLegAlreadyExistsError} — never a raw
83
+ * driver error escaping the store layer.
84
+ */
85
+ export declare function insertRunLeg(input: {
86
+ runId: string;
87
+ stepIndex: number;
88
+ legIndex: number;
89
+ definitionJson: string;
90
+ attempt?: number;
91
+ }, dep: DbDep): string;
92
+ /**
93
+ * Claim a `pending` leg for submission, BEFORE the real chain call —
94
+ * closing the concurrency gap `runs-driver.ts`'s `handleSubmitLeg` used to
95
+ * defer (see its own doc comment history): the conditional `WHERE status =
96
+ * 'pending' AND claimed_at IS NULL` is a true claim-before-submit step,
97
+ * mirroring `claim.ts`'s `claimDueCodexCronoton` idiom one level down —
98
+ * two concurrent callers racing the same `pending` leg can never BOTH win
99
+ * this UPDATE, so at most one proceeds to the real network submit. Returns
100
+ * `true` iff THIS call won the claim.
101
+ *
102
+ * KNOWN, ACCEPTED LIMITATION (not the same shape as `claimDueCodexCronoton`'s
103
+ * one-shot claim — reviewed and deliberately left as a bounded tradeoff
104
+ * rather than built out further here): this claim is a TWO-PHASE lease —
105
+ * something must later call {@link markLegSubmitted} or
106
+ * {@link releaseLegClaim} to make the leg claimable again. If the process
107
+ * crashes (OOM-kill, hard restart) strictly between a won claim and either
108
+ * of those two calls, the leg is stuck `pending` with `claimed_at` set
109
+ * forever — `executeCodexTransaction`'s own documented "submit never
110
+ * throws" contract (`executor.ts`) means no in-process `try`/`finally`
111
+ * here could ever help (there is no exception to catch), and only a
112
+ * genuine process-level crash reaches this window at all. The run still
113
+ * recovers, just more slowly than before this fix: `advanceRun`'s
114
+ * deadline-exceeded branch (`pure/run-advance.ts`) eventually re-plans
115
+ * (bumping `attempt`, which excludes the orphaned leg from all future
116
+ * barrier checks) or fails the run outright — bounded by
117
+ * `RUN_STEP_DEADLINE_MS` (10 minutes by default) rather than "retry on the
118
+ * very next pass" as it was before. The orphaned leg row itself is
119
+ * permanently inert (never re-selected, never blocks anything else) —
120
+ * harmless DB clutter, not a stuck run. A reconciliation sweep that frees
121
+ * an expired claim before the full step deadline is a legitimate future
122
+ * improvement, but is new recovery machinery deserving its own scoped
123
+ * design, not a drive-by addition here (matching this file's own existing
124
+ * "no retry-cap mechanism... an operator noticing is the backstop today"
125
+ * posture for a different, pre-existing limitation).
126
+ */
127
+ export declare function claimLegForSubmit(legId: string, claimedAt: string, dep: DbDep): boolean;
128
+ /**
129
+ * Release a claim taken by {@link claimLegForSubmit} after a submit attempt
130
+ * that did NOT land (so the leg stays `pending` for a later pass to retry —
131
+ * the existing "no retry-cap mechanism" posture, unchanged). Unconditional:
132
+ * the caller already knows it won the claim it's releasing, so there is no
133
+ * race to guard against here (only the claim ACQUISITION needs the
134
+ * conditional guard above). See {@link claimLegForSubmit}'s own doc for the
135
+ * one known gap this does NOT cover: a process crash between the claim and
136
+ * this call (or `markLegSubmitted`) leaves exactly one permanently-orphaned
137
+ * `pending`+`claimed_at`-set leg row per occurrence — harmless, never
138
+ * cleaned up by this function, by design (nothing calls this except the
139
+ * normal submit-failure path).
140
+ */
141
+ export declare function releaseLegClaim(legId: string, dep: DbDep): void;
142
+ /**
143
+ * Flip a `pending` leg to `submitted`, stamping `request_key`/`chain_id`/
144
+ * `submitted_at`. The conditional `WHERE status = 'pending'` is the
145
+ * enforcement for "never re-submit, only poll": a leg that's already
146
+ * `submitted` (or further along) matches zero rows, so a second call throws
147
+ * {@link LegAlreadySubmittedError} instead of overwriting the existing key.
148
+ * Does NOT clear `claimed_at` — once `status` leaves `'pending'`,
149
+ * `claimLegForSubmit`'s own `WHERE status = 'pending'` guard already makes
150
+ * `claimed_at` irrelevant for this leg forever (a non-pending leg can never
151
+ * be claimed again), so there is nothing left to clean up.
152
+ */
153
+ export declare function markLegSubmitted(legId: string, input: {
154
+ requestKey: string;
155
+ chainId: string;
156
+ }, dep: DbDep): void;
157
+ /**
158
+ * Flip a `submitted` leg to its `confirmed` terminal status, stamping
159
+ * `confirmed_at`. The conditional `WHERE status = 'submitted'` is the
160
+ * enforcement, mirroring `markLegSubmitted`'s own guard one level up: a leg
161
+ * that was never submitted (still `pending`) or is already terminal
162
+ * (`confirmed`/`failed`) cannot be silently flipped — a leg that never
163
+ * reached the chain must never be treated as "funds moved," and an
164
+ * already-terminal leg must never be overwritten.
165
+ */
166
+ export declare function markLegConfirmed(legId: string, dep: DbDep): void;
167
+ /**
168
+ * Flip a `submitted` leg to its `failed` terminal status, stamping
169
+ * `error_message`. Same guard as {@link markLegConfirmed} — a leg that was
170
+ * never submitted or is already terminal cannot be silently flipped (in
171
+ * particular, an already-`confirmed` leg can never be overwritten back to
172
+ * `failed`, which would otherwise invite a caller to re-submit a leg whose
173
+ * first attempt already landed on-chain).
174
+ */
175
+ export declare function markLegFailed(legId: string, input: {
176
+ errorMessage: string;
177
+ }, dep: DbDep): void;
178
+ /**
179
+ * Move a run from `fromStepIndex` to `toStepIndex`, resetting `attempt` to 0
180
+ * and stamping a new `deadline_at`/`modified_at`. The trailing `WHERE ... AND
181
+ * step_index = ?` is an optimistic-concurrency guard, mirroring
182
+ * `markLegSubmitted`'s conditional-UPDATE-as-the-guard idiom one level up: if
183
+ * another process already moved this run's step, this call's precondition is
184
+ * stale and must fail loudly rather than overwrite it.
185
+ *
186
+ * Doubles as both "really advance to the next step" (`toStepIndex ===
187
+ * fromStepIndex + 1`) and "stamp this step's first deadline without moving
188
+ * it" (`toStepIndex === fromStepIndex`, used when a step's leg is first
189
+ * planned) — one function, two callers, same guard.
190
+ */
191
+ export declare function advanceRunStep(runId: string, input: {
192
+ fromStepIndex: number;
193
+ toStepIndex: number;
194
+ deadlineAt: string | null;
195
+ }, dep: DbDep): void;
196
+ /**
197
+ * Increment a run's `attempt` by one, stamping `modified_at`. Unconditional —
198
+ * no precondition — incrementing is commutative regardless of caller
199
+ * ordering, so there is no stale-view case to guard against the way
200
+ * {@link advanceRunStep}'s `WHERE step_index = ?` must. This is the Phase-3
201
+ * design anticipated (and correctly deferred, since nothing exercised it
202
+ * yet — see `docs/work/khronoton-chained-runs-phase-3/design.md`'s §G): a
203
+ * genuine re-plan (a `canReplan:true` step whose leg actually fails) bumps
204
+ * `attempt` here INSTEAD OF going through `advanceRunStep`, specifically to
205
+ * avoid `advanceRunStep`'s own unconditional `attempt = 0` reset undoing the
206
+ * bump on every single re-plan.
207
+ */
208
+ export declare function bumpRunAttempt(runId: string, dep: DbDep): void;
209
+ /**
210
+ * Stamp a fresh `deadline_at`/`modified_at`, touching NOTHING else — in
211
+ * particular, never `attempt` or `step_index`. Narrower than
212
+ * {@link advanceRunStep} on purpose: `advanceRunStep` unconditionally resets
213
+ * `attempt` to `0` as part of its contract, which is correct for a real
214
+ * step-advance or a step's very first deadline stamp (`attempt` is already
215
+ * `0` in both those cases) but WRONG immediately after {@link bumpRunAttempt}
216
+ * has just incremented `attempt` for a genuine re-plan — calling
217
+ * `advanceRunStep` there would silently reset the bump back to `0` on every
218
+ * re-plan, making `replanOrFail`'s `attempt < maxReplanAttempts` check
219
+ * permanently true and turning `maxReplanAttempts` into dead config (an
220
+ * infinite retry loop with no error ever surfacing). No optimistic-
221
+ * concurrency guard is needed here (unlike `advanceRunStep`'s
222
+ * `WHERE step_index = ?`): this function never touches `step_index`, so
223
+ * there is no stale-precondition case to guard against.
224
+ */
225
+ export declare function touchRunDeadline(runId: string, deadlineAt: string | null, dep: DbDep): void;
226
+ /**
227
+ * Flip a non-terminal run to one of its terminal statuses
228
+ * (`succeeded`/`failed`/`abandoned`), stamping `modified_at`. The conditional
229
+ * `WHERE status NOT IN (...)` is the enforcement, mirroring
230
+ * `markLegConfirmed`/`markLegFailed`'s own terminal guard one level down: a
231
+ * run that's already terminal cannot be silently overwritten.
232
+ */
233
+ export declare function markRunTerminal(runId: string, status: "succeeded" | "failed" | "abandoned", dep: DbDep): void;
@@ -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,42 @@
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
+ }
15
+ export interface CodexCronotonStepRow {
16
+ id: string;
17
+ codex_cronoton_id: string;
18
+ step_index: number;
19
+ mode: "single" | "planner";
20
+ pact_code: string | null;
21
+ config_json: string | null;
22
+ payload_json: string | null;
23
+ gas_payer_json: string | null;
24
+ signers_json: string | null;
25
+ planner_name: string | null;
26
+ planner_params_json: string | null;
27
+ idempotent: number;
28
+ created_at: string;
29
+ modified_at: string;
30
+ }
31
+ /**
32
+ * Insert one step row. Returns the new row's id.
33
+ *
34
+ * Lets the unique index on `(codex_cronoton_id, step_index)` (`schema.ts`)
35
+ * be the actual enforcement, mirroring `runs.ts`'s `createRun`: a duplicate
36
+ * step index for the same cronoton throws a UNIQUE-constraint `SqliteError`,
37
+ * caught here and re-thrown as the typed {@link StepAlreadyExistsError} —
38
+ * never a raw driver error escaping the store layer.
39
+ */
40
+ export declare function insertStep(input: InsertStepInput, dep: DbDep): string;
41
+ /** Full raw snake_case rows for a cronoton's steps, ordered by step_index ASC. */
42
+ export declare function listStepsForCronoton(codexCronotonId: string, dep: DbDep): CodexCronotonStepRow[];
@@ -0,0 +1,51 @@
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
+ import crypto from "node:crypto";
14
+ import { isUniqueConstraintError, StepAlreadyExistsError } from "./errors.js";
15
+ /**
16
+ * Insert one step row. Returns the new row's id.
17
+ *
18
+ * Lets the unique index on `(codex_cronoton_id, step_index)` (`schema.ts`)
19
+ * be the actual enforcement, mirroring `runs.ts`'s `createRun`: a duplicate
20
+ * step index for the same cronoton throws a UNIQUE-constraint `SqliteError`,
21
+ * caught here and re-thrown as the typed {@link StepAlreadyExistsError} —
22
+ * never a raw driver error escaping the store layer.
23
+ */
24
+ export function insertStep(input, dep) {
25
+ const id = crypto.randomUUID();
26
+ const now = new Date().toISOString();
27
+ try {
28
+ dep.db
29
+ .prepare(`INSERT INTO codex_cronoton_steps
30
+ (id, codex_cronoton_id, step_index, mode, pact_code, config_json,
31
+ payload_json, gas_payer_json, signers_json, planner_name,
32
+ planner_params_json, idempotent, created_at, modified_at)
33
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
34
+ .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);
35
+ }
36
+ catch (error) {
37
+ if (isUniqueConstraintError(error)) {
38
+ throw new StepAlreadyExistsError(input.codexCronotonId, input.stepIndex);
39
+ }
40
+ throw error;
41
+ }
42
+ return id;
43
+ }
44
+ /** Full raw snake_case rows for a cronoton's steps, ordered by step_index ASC. */
45
+ export function listStepsForCronoton(codexCronotonId, dep) {
46
+ return dep.db
47
+ .prepare(`SELECT * FROM codex_cronoton_steps
48
+ WHERE codex_cronoton_id = ?
49
+ ORDER BY step_index ASC`)
50
+ .all(codexCronotonId);
51
+ }