@ancientpantheon/khronoton-core 0.12.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 (64) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -0
  3. package/dist/blockchain/stoachain.d.ts +1 -1
  4. package/dist/blockchain/stoachain.js +16 -1
  5. package/dist/{chunk-KQZYMPZS.js → chunk-7H5TM3CS.js} +1 -1
  6. package/dist/{chunk-GIGLXIMC.js → chunk-IAK4UEAA.js} +710 -23
  7. package/dist/{context-CApk-LP4.d.ts → context-P-rCtBbJ.d.ts} +1 -1
  8. package/dist/handlers/execute.d.ts +12 -4
  9. package/dist/handlers/execute.js +42 -5
  10. package/dist/handlers/index.d.ts +2 -1
  11. package/dist/handlers/index.js +4 -1
  12. package/dist/handlers/read.d.ts +11 -0
  13. package/dist/handlers/read.js +65 -1
  14. package/dist/handlers/steps.d.ts +3 -0
  15. package/dist/handlers/steps.js +115 -0
  16. package/dist/hooks/index.d.ts +3 -3
  17. package/dist/hooks/index.js +2 -2
  18. package/dist/provider/index.d.ts +3 -3
  19. package/dist/provider/index.js +33 -2
  20. package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
  21. package/dist/server/executor.d.ts +14 -1
  22. package/dist/server/executor.js +144 -26
  23. package/dist/server/index.d.ts +11 -2
  24. package/dist/server/index.js +29 -1
  25. package/dist/server/loop.d.ts +17 -13
  26. package/dist/server/loop.js +19 -12
  27. package/dist/server/planners/evict.d.ts +20 -0
  28. package/dist/server/planners/evict.js +143 -0
  29. package/dist/server/planners/inject.d.ts +22 -0
  30. package/dist/server/planners/inject.js +120 -0
  31. package/dist/server/planners/registry.d.ts +80 -0
  32. package/dist/server/planners/registry.js +50 -0
  33. package/dist/server/planners/stoa-unwrap.d.ts +23 -0
  34. package/dist/server/planners/stoa-unwrap.js +204 -0
  35. package/dist/server/planners/stoa-wrap.d.ts +22 -0
  36. package/dist/server/planners/stoa-wrap.js +201 -0
  37. package/dist/server/planners/unstall.d.ts +25 -0
  38. package/dist/server/planners/unstall.js +135 -0
  39. package/dist/server/pure/run-advance.d.ts +76 -0
  40. package/dist/server/pure/run-advance.js +94 -0
  41. package/dist/server/pure/split-plan.d.ts +144 -0
  42. package/dist/server/pure/split-plan.js +362 -0
  43. package/dist/server/resolvers.js +48 -6
  44. package/dist/server/runs-driver.d.ts +92 -0
  45. package/dist/server/runs-driver.js +511 -0
  46. package/dist/server/schema.d.ts +5 -2
  47. package/dist/server/schema.js +73 -1
  48. package/dist/server/seams.d.ts +28 -0
  49. package/dist/server/seams.js +4 -0
  50. package/dist/server/store/errors.d.ts +38 -0
  51. package/dist/server/store/errors.js +61 -0
  52. package/dist/server/store/index.d.ts +6 -2
  53. package/dist/server/store/index.js +6 -2
  54. package/dist/server/store/mappers.d.ts +11 -0
  55. package/dist/server/store/mappers.js +20 -0
  56. package/dist/server/store/runs.d.ts +233 -0
  57. package/dist/server/store/runs.js +341 -0
  58. package/dist/server/store/steps.d.ts +42 -0
  59. package/dist/server/store/steps.js +51 -0
  60. package/dist/server/tick.d.ts +7 -0
  61. package/dist/server/tick.js +50 -1
  62. package/dist/server/types.d.ts +42 -3
  63. package/dist/ui/index.js +2 -2
  64. 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,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
+ }
@@ -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
@@ -39,6 +39,10 @@ import { fetchDueManualBatches, claimManualBatchFire, cancelManualBatch, } from
39
39
  import { getCodexCronoton } from "./store/cronoton.js";
40
40
  import { fireByServerResolver } from "./resolvers.js";
41
41
  import { TICK_BATCH_LIMIT } from "./seams.js";
42
+ import { createRun } from "./store/runs.js";
43
+ import { RunAlreadyInFlightError } from "./store/errors.js";
44
+ import { listStepsForCronoton } from "./store/steps.js";
45
+ import { driveRunOnce } from "./runs-driver.js";
42
46
  /**
43
47
  * One multi-tx `onTx` collector + the `FireTxKey[]` it fills, threaded into
44
48
  * {@link fireByServerResolver} so an INLINE multi-tx fire records the per-tx
@@ -68,6 +72,7 @@ export async function codexCronotonTickOnce(now, ctx) {
68
72
  const firedIds = [];
69
73
  const failedIds = [];
70
74
  const skippedIds = [];
75
+ const drivenRunIds = [];
71
76
  const due = fetchDueCodexCronotons(now, ctx.config?.tickBatchLimit ?? TICK_BATCH_LIMIT, {
72
77
  db: ctx.db,
73
78
  });
@@ -78,6 +83,50 @@ export async function codexCronotonTickOnce(now, ctx) {
78
83
  skippedIds.push(row.id);
79
84
  continue;
80
85
  }
86
+ // Chained (≥1 codex_cronoton_steps row) vs plain — design.md §A/§B. A
87
+ // chained row never reaches the one-shot fire path below: its lifecycle
88
+ // lives in codex_cronoton_runs/..._run_legs, not codex_cronoton_fires.
89
+ const steps = listStepsForCronoton(row.id, { db: ctx.db });
90
+ if (steps.length > 0) {
91
+ try {
92
+ const runId = createRun({ codexCronotonId: row.id, stepCount: steps.length }, { db: ctx.db });
93
+ // Drive the freshly created run forward synchronously in this SAME
94
+ // tick pass, so step 0's leg is built AND submitted without waiting
95
+ // a full tickIntervalMs for the next advanceInFlightRunsOnce pass.
96
+ await driveRunOnce(runId, now, ctx);
97
+ // onAudit before the firedIds/drivenRunIds pushes, mirroring the
98
+ // plain-fire path below: onAudit "may be sync or async" (seams.ts)
99
+ // and isn't guaranteed non-throwing — a throw here is caught by
100
+ // the outer per-row catch and lands row.id in skippedIds, so it
101
+ // must never ALSO already be in firedIds by that point.
102
+ await ctx.onAudit({
103
+ action: "codex_cronoton.run_started",
104
+ result: "success",
105
+ targetKind: "codex_cronoton",
106
+ targetId: row.id,
107
+ detail: {
108
+ codexCronotonId: row.id,
109
+ runId,
110
+ stepCount: steps.length,
111
+ actor: "scheduler",
112
+ },
113
+ });
114
+ firedIds.push(row.id);
115
+ drivenRunIds.push(runId);
116
+ }
117
+ catch (err) {
118
+ if (err instanceof RunAlreadyInFlightError) {
119
+ // Self-blocked: an existing non-terminal run for this cronoton is
120
+ // already being driven by advanceInFlightRunsOnce every pass —
121
+ // the claim already advanced next_fire_at regardless (§C).
122
+ skippedIds.push(row.id);
123
+ }
124
+ else {
125
+ throw err;
126
+ }
127
+ }
128
+ continue;
129
+ }
81
130
  const scheduleKind = row.schedule_mode === "one-time" ? "one-time" : "recurring";
82
131
  const definition = rowToDefinition(row);
83
132
  const { txKeys, deps: collectDeps } = makeTxKeyCollector();
@@ -140,7 +189,7 @@ export async function codexCronotonTickOnce(now, ctx) {
140
189
  skippedIds.push(row.id);
141
190
  }
142
191
  }
143
- return { firedIds, failedIds, skippedIds };
192
+ return { firedIds, failedIds, skippedIds, drivenRunIds };
144
193
  }
145
194
  /**
146
195
  * Process due manual-execution batches — the "Execute Now ×N" rail. For each
@@ -17,8 +17,14 @@ import type { ScheduleMode } from "../schedule.js";
17
17
  * chain dependency (the source Hub imported a concrete `ChainId`).
18
18
  */
19
19
  export type ChainId = string;
20
- /** Run mode: `simulate` signs + dirty-reads but never submits; `fire` submits. */
21
- export type ExecutorMode = "simulate" | "fire";
20
+ /**
21
+ * Run mode: `simulate` signs + dirty-reads but never submits; `fire` submits
22
+ * AND awaits confirmation (listen); `submit` submits but does NOT await
23
+ * confirmation — the caller polls it separately (see {@link SubmitResult}
24
+ * and `ChainClient.pollRequestKeys`), which is what lets a chained,
25
+ * multi-leg run avoid blocking the scheduler on a 5-minute listen per leg.
26
+ */
27
+ export type ExecutorMode = "simulate" | "fire" | "submit";
22
28
  /** One-time entries terminate after a single fire; recurring re-fire on schedule. */
23
29
  export type ScheduleKind = "one-time" | "recurring";
24
30
  /** Capability scoping for a signer: `pure` (unrestricted) or `scoped` (capped). */
@@ -121,7 +127,40 @@ export interface FireResult {
121
127
  /** Computed one-time terminal intent; `null` for recurring. */
122
128
  readonly terminalIntent: TerminalIntent | null;
123
129
  }
124
- export type ExecutorResult = SimulateResult | FireResult;
130
+ /**
131
+ * Result of a `submit` run. Builds, signs, pre-flights, and submits — never
132
+ * calls `listenWithTimeout`. `ok: true` with a `requestKey` means "submitted,"
133
+ * not "confirmed"; confirmation is a separate poll (Phase 3), not this result.
134
+ * No `terminalIntent`: submit never resolves a one-time row's terminal state.
135
+ *
136
+ * A SHARPER caveat than "not confirmed yet": `ok: true` is not even proof the
137
+ * transaction reached the chain. The shared build-through-submit helper
138
+ * (`executor.ts`'s `submitTransaction`) treats ANY throw from the chain
139
+ * client's submit call as the ambiguous "lost the HTTP response, but the node
140
+ * may have already accepted it" case (REQ-23) whenever a request key can be
141
+ * derived from the signed command — which is unconditional, since that key is
142
+ * just the signed command's own hash, computed before the network call ever
143
+ * happens. For `fire` mode this is safe because the subsequent `listen` call
144
+ * eventually distinguishes a genuine rejection from a real confirmation; for
145
+ * `submit` mode there is no such follow-up inside this call. A caller polling
146
+ * a `requestKey` this result returns must be prepared for it to never
147
+ * confirm — that is an expected outcome requiring a bounded deadline + re-plan
148
+ * or fail-the-run response (see the chained-runs design's §5.5/§5.7), not a
149
+ * bug to work around by re-submitting (re-submitting a leg that already has a
150
+ * request key is exactly the unsafe case the "never re-submit, only poll"
151
+ * invariant exists to forbid).
152
+ */
153
+ export interface SubmitResult {
154
+ readonly ok: boolean;
155
+ readonly mode: "submit";
156
+ readonly requestKey?: string;
157
+ readonly chainId?: string;
158
+ readonly networkId?: string;
159
+ /** The preflight read, present on a pre-submit failure. */
160
+ readonly rawResult?: unknown;
161
+ readonly error?: string;
162
+ }
163
+ export type ExecutorResult = SimulateResult | FireResult | SubmitResult;
125
164
  /** The raw `codex_cronotons` row shape (JSON columns are still strings here). */
126
165
  export interface CodexCronotonRow {
127
166
  id: string;
package/dist/ui/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { useCronotons, useCronoton, useCronotonActions, useExecuteNow, useSimulate, useServerResolvers, useManualBatch, useStartBatch, useCancelBatch, useTrigger, useCronotonFires, useRecoverFire } from '../chunk-KQZYMPZS.js';
2
- import { useKhronotonAdapter, useKhronotonConfig, parseRuntimeArgKeys, summariseSchedule, KhronotonStaticContext, useKhronoton, computeNextFire, InvalidScheduleConfigError } from '../chunk-GIGLXIMC.js';
1
+ import { useCronotons, useCronoton, useCronotonActions, useExecuteNow, useSimulate, useServerResolvers, useManualBatch, useStartBatch, useCancelBatch, useTrigger, useCronotonFires, useRecoverFire } from '../chunk-7H5TM3CS.js';
2
+ import { useKhronotonAdapter, useKhronotonConfig, parseRuntimeArgKeys, summariseSchedule, KhronotonStaticContext, useKhronoton, computeNextFire, InvalidScheduleConfigError } from '../chunk-IAK4UEAA.js';
3
3
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
4
4
  import { lazy, forwardRef, createElement, useState, useEffect, useCallback, useMemo, Suspense, useContext } from 'react';
5
5
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ancientpantheon/khronoton-core",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Headless framework-agnostic scheduler engine: pure schedule math plus an injectable tick engine. No database, no job queue, no framework — hosts inject storage and firing via hooks.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",