@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.
Files changed (68) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +8 -0
  3. package/dist/blockchain/stoachain.d.ts +1 -1
  4. package/dist/blockchain/stoachain.js +16 -1
  5. package/dist/{chunk-GIGLXIMC.js → chunk-A5YODPKQ.js} +820 -23
  6. package/dist/{chunk-KQZYMPZS.js → chunk-WKI52IPY.js} +1 -1
  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 +152 -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 +12 -2
  24. package/dist/server/index.js +38 -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 +118 -0
  32. package/dist/server/planners/registry.js +94 -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 +26 -0
  36. package/dist/server/planners/stoa-wrap.js +229 -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/pure/yields.d.ts +57 -0
  44. package/dist/server/pure/yields.js +101 -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 +582 -0
  48. package/dist/server/schema.d.ts +6 -2
  49. package/dist/server/schema.js +89 -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/index.d.ts +7 -2
  55. package/dist/server/store/index.js +8 -2
  56. package/dist/server/store/mappers.d.ts +11 -0
  57. package/dist/server/store/mappers.js +20 -0
  58. package/dist/server/store/runs.d.ts +233 -0
  59. package/dist/server/store/runs.js +341 -0
  60. package/dist/server/store/steps.d.ts +54 -0
  61. package/dist/server/store/steps.js +74 -0
  62. package/dist/server/store/yields.d.ts +46 -0
  63. package/dist/server/store/yields.js +73 -0
  64. package/dist/server/tick.d.ts +7 -0
  65. package/dist/server/tick.js +50 -1
  66. package/dist/server/types.d.ts +42 -3
  67. package/dist/ui/index.js +2 -2
  68. package/package.json +1 -1
@@ -79,6 +79,82 @@ CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_due
79
79
 
80
80
  CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_cronoton
81
81
  ON codex_cronoton_manual_batches(codex_cronoton_id);
82
+
83
+ CREATE TABLE IF NOT EXISTS codex_cronoton_steps (
84
+ id TEXT PRIMARY KEY,
85
+ codex_cronoton_id TEXT NOT NULL REFERENCES codex_cronotons(id) ON DELETE CASCADE,
86
+ step_index INTEGER NOT NULL,
87
+ mode TEXT NOT NULL CHECK (mode IN ('single', 'planner')),
88
+ pact_code TEXT,
89
+ config_json TEXT,
90
+ payload_json TEXT,
91
+ gas_payer_json TEXT,
92
+ signers_json TEXT,
93
+ planner_name TEXT,
94
+ planner_params_json TEXT,
95
+ idempotent INTEGER NOT NULL DEFAULT 0,
96
+ created_at TEXT NOT NULL,
97
+ modified_at TEXT NOT NULL,
98
+ CHECK (
99
+ (mode = 'single' AND pact_code IS NOT NULL) OR
100
+ (mode = 'planner' AND planner_name IS NOT NULL)
101
+ )
102
+ );
103
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_steps_order
104
+ ON codex_cronoton_steps(codex_cronoton_id, step_index);
105
+
106
+ CREATE TABLE IF NOT EXISTS codex_cronoton_runs (
107
+ id TEXT PRIMARY KEY,
108
+ codex_cronoton_id TEXT NOT NULL REFERENCES codex_cronotons(id) ON DELETE CASCADE,
109
+ fire_id TEXT REFERENCES codex_cronoton_fires(id),
110
+ status TEXT NOT NULL DEFAULT 'planning' CHECK (status IN (
111
+ 'planning', 'awaiting', 'advancing', 'succeeded', 'failed', 'abandoned'
112
+ )),
113
+ step_index INTEGER NOT NULL DEFAULT 0,
114
+ step_count INTEGER NOT NULL,
115
+ started_at TEXT NOT NULL,
116
+ modified_at TEXT NOT NULL,
117
+ deadline_at TEXT,
118
+ attempt INTEGER NOT NULL DEFAULT 0,
119
+ context_json TEXT
120
+ );
121
+ CREATE INDEX IF NOT EXISTS idx_codex_cronoton_runs_due
122
+ ON codex_cronoton_runs(status, modified_at);
123
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_runs_self_block
124
+ ON codex_cronoton_runs(codex_cronoton_id)
125
+ WHERE status IN ('planning', 'awaiting', 'advancing');
126
+
127
+ CREATE TABLE IF NOT EXISTS codex_cronoton_run_legs (
128
+ id TEXT PRIMARY KEY,
129
+ run_id TEXT NOT NULL REFERENCES codex_cronoton_runs(id) ON DELETE CASCADE,
130
+ step_index INTEGER NOT NULL,
131
+ leg_index INTEGER NOT NULL,
132
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN (
133
+ 'pending', 'submitted', 'confirmed', 'failed'
134
+ )),
135
+ request_key TEXT,
136
+ chain_id TEXT,
137
+ definition_json TEXT NOT NULL,
138
+ error_message TEXT,
139
+ submitted_at TEXT,
140
+ confirmed_at TEXT,
141
+ attempt INTEGER NOT NULL DEFAULT 0
142
+ );
143
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_slot
144
+ ON codex_cronoton_run_legs(run_id, step_index, leg_index);
145
+ CREATE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_barrier
146
+ ON codex_cronoton_run_legs(run_id, step_index, status);
147
+
148
+ CREATE TABLE IF NOT EXISTS codex_cronoton_run_yields (
149
+ id TEXT PRIMARY KEY,
150
+ run_id TEXT NOT NULL REFERENCES codex_cronoton_runs(id) ON DELETE CASCADE,
151
+ name TEXT NOT NULL,
152
+ value_json TEXT NOT NULL,
153
+ step_index INTEGER NOT NULL,
154
+ created_at TEXT NOT NULL
155
+ );
156
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_run_yields_name
157
+ ON codex_cronoton_run_yields(run_id, name);
82
158
  `;
83
159
  /**
84
160
  * Idempotently ensures `column` exists on `table`, adding it via `ALTER TABLE
@@ -103,7 +179,7 @@ function ensureColumn(db, table, column, columnDefSql) {
103
179
  }
104
180
  }
105
181
  /**
106
- * Installs the three codex-cronoton tables and their indexes on the injected DB
182
+ * Installs the seven codex-cronoton tables and their indexes on the injected DB
107
183
  * handle in a single idempotent call. Safe to re-run: every statement is guarded
108
184
  * with `IF NOT EXISTS`.
109
185
  *
@@ -122,4 +198,16 @@ export function installSchema(db) {
122
198
  ensureColumn(db, "codex_cronotons", "public_token", "TEXT");
123
199
  ensureColumn(db, "codex_cronotons", "public_observable", "INTEGER NOT NULL DEFAULT 0");
124
200
  db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronotons_public_token ON codex_cronotons(public_token)`);
201
+ // Phase 5 fix: a real claim-before-submit marker for `codex_cronoton_run_legs`,
202
+ // closing the concurrency gap `runs-driver.ts`'s `handleSubmitLeg` doc
203
+ // previously deferred ("adding one changes the leg status enum, which is
204
+ // schema scope beyond this phase") — additive via `ensureColumn`, NOT a new
205
+ // status enum value, so the existing CHECK constraint is untouched. See
206
+ // `store/runs.ts`'s `claimLegForSubmit`/`releaseLegClaim`.
207
+ ensureColumn(db, "codex_cronoton_run_legs", "claimed_at", "TEXT");
208
+ // Step-to-step yield carry: the NAME a step's confirmed on-chain return
209
+ // value (mode:'single') or planner-returned yield (mode:'planner') gets
210
+ // stored under in `codex_cronoton_run_yields`. Additive via `ensureColumn`,
211
+ // covering both a fresh install and an already-provisioned database.
212
+ ensureColumn(db, "codex_cronoton_steps", "yield_as", "TEXT");
125
213
  }
@@ -117,6 +117,28 @@ export interface ChainClient {
117
117
  * on any failure or absence, matching OuronetUI's own documented choice here.
118
118
  */
119
119
  getBlockGasLimit?(): Promise<number>;
120
+ /**
121
+ * Poll many request keys on ONE chain in a single call. Returns a map keyed
122
+ * by requestKey; a key ABSENT from the map means "still pending" (Kadena's
123
+ * /poll endpoint only returns landed transactions), a key PRESENT means a
124
+ * definite {@link ListenResult}. Declared optional for Phase 0's own
125
+ * single-fire executor, which never calls it. What matters there is that a
126
+ * multi-leg step costs one request per chain per tick, not one request per
127
+ * leg — see `blockchain/stoachain.ts` for the implementation, which always
128
+ * provides it.
129
+ *
130
+ * CAVEAT (Phase 3): `runs-driver.ts`'s `handlePoll` is this method's only
131
+ * consumer, and it does NOT fall back to polling one key at a time via
132
+ * `listen` when this is absent — a `ChainClient` that omits it will never
133
+ * observe a chained run's submitted legs land, stalling every step until
134
+ * its deadline fails the run outright (even one that actually succeeded
135
+ * on-chain). In practice this is a theoretical gap, not a live bug: the
136
+ * only shipped adapter (`blockchain/stoachain.ts`) always implements this
137
+ * method. Treat it as effectively REQUIRED for a `ChainClient` meant to
138
+ * back chained runs, not merely a performance optimization, despite the
139
+ * `?` in its signature.
140
+ */
141
+ pollRequestKeys?(keys: string[], chainId: string): Promise<Record<string, ListenResult>>;
120
142
  submit(tx: unknown): Promise<{
121
143
  requestKey: string;
122
144
  }>;
@@ -275,6 +297,8 @@ export interface Config {
275
297
  max: number;
276
298
  intervalSeconds: number;
277
299
  };
300
+ runStepDeadlineMs?: number;
301
+ maxReplanAttempts?: number;
278
302
  }
279
303
  /** Default tick cadence (30s) — {@link Config.tickIntervalMs}. */
280
304
  export declare const TICK_INTERVAL_MS = 30000;
@@ -292,3 +316,7 @@ export declare const MANUAL_BATCH_MIN = 2;
292
316
  export declare const MANUAL_BATCH_MAX = 60;
293
317
  /** Default manual-batch inter-fire interval (seconds) — {@link Config.manualBatch}.intervalSeconds. */
294
318
  export declare const MANUAL_BATCH_INTERVAL_SECONDS = 60;
319
+ /** Default per-step barrier deadline (10 minutes) — {@link Config.runStepDeadlineMs}. */
320
+ export declare const RUN_STEP_DEADLINE_MS = 600000;
321
+ /** Default max replan attempts — {@link Config.maxReplanAttempts}. */
322
+ export declare const DEFAULT_MAX_REPLAN_ATTEMPTS = 3;
@@ -32,3 +32,7 @@ export const MANUAL_BATCH_MIN = 2;
32
32
  export const MANUAL_BATCH_MAX = 60;
33
33
  /** Default manual-batch inter-fire interval (seconds) — {@link Config.manualBatch}.intervalSeconds. */
34
34
  export const MANUAL_BATCH_INTERVAL_SECONDS = 60;
35
+ /** Default per-step barrier deadline (10 minutes) — {@link Config.runStepDeadlineMs}. */
36
+ export const RUN_STEP_DEADLINE_MS = 600000;
37
+ /** Default max replan attempts — {@link Config.maxReplanAttempts}. */
38
+ export const DEFAULT_MAX_REPLAN_ATTEMPTS = 3;
@@ -1,3 +1,13 @@
1
+ /**
2
+ * True for the better-sqlite3 `SqliteError` a UNIQUE index violation raises.
3
+ * The single shared home for this driver-error-classification check — a
4
+ * cross-phase review found `store/runs.ts` and `store/steps.ts` each
5
+ * carrying a byte-identical, independently-declared copy (one file's own
6
+ * doc comment admitted it "mirrors" the other's), which is exactly the kind
7
+ * of drift risk `planners/registry.ts`'s `resolvePlannerFor` was extracted
8
+ * to close for a different pair of duplicated call sites.
9
+ */
10
+ export declare function isUniqueConstraintError(error: unknown): boolean;
1
11
  /** Generic validation/schedule reject — the route maps it to 400 + the reason. */
2
12
  export declare class CodexCronotonValidationError extends Error {
3
13
  constructor(message: string);
@@ -14,6 +24,34 @@ export declare class TerminalCronotonError extends Error {
14
24
  export declare class ManualBatchActiveError extends Error {
15
25
  constructor();
16
26
  }
27
+ /** A non-terminal run already exists for this cronoton — self-blocking only (a DIFFERENT cronoton must never be blocked by this). */
28
+ export declare class RunAlreadyInFlightError extends Error {
29
+ constructor(codexCronotonId: string);
30
+ }
31
+ /** A run leg already has (or is past) a request key — re-submission is refused; the leg must only be polled, never re-submitted. */
32
+ export declare class LegAlreadySubmittedError extends Error {
33
+ constructor(legId: string);
34
+ }
35
+ /** markLegConfirmed/markLegFailed require the leg to currently be 'submitted' — a leg that never reached the chain cannot be confirmed, and an already-terminal leg cannot be silently overwritten. */
36
+ export declare class LegNotSubmittedError extends Error {
37
+ constructor(legId: string);
38
+ }
39
+ /** A step already exists at this (codexCronotonId, stepIndex) — step indexes are immutable once written, mirroring RunAlreadyInFlightError's "no raw driver error escapes the store layer" posture. */
40
+ export declare class StepAlreadyExistsError extends Error {
41
+ constructor(codexCronotonId: string, stepIndex: number);
42
+ }
43
+ /** A leg already exists at this (runId, stepIndex, legIndex) slot — the same "no raw driver error escapes the store layer" posture as StepAlreadyExistsError/RunAlreadyInFlightError. */
44
+ export declare class RunLegAlreadyExistsError extends Error {
45
+ constructor(runId: string, stepIndex: number, legIndex: number);
46
+ }
47
+ /** advanceRunStep's fromStepIndex no longer matches the run's live step_index — a stale caller must fail loudly rather than overwrite a step another process already moved past. */
48
+ export declare class RunStepMismatchError extends Error {
49
+ constructor(runId: string, expectedStepIndex: number);
50
+ }
51
+ /** markRunTerminal requires the run to currently be non-terminal — an already-terminal run (succeeded/failed/abandoned) cannot be silently overwritten. */
52
+ export declare class RunAlreadyTerminalError extends Error {
53
+ constructor(runId: string);
54
+ }
17
55
  /**
18
56
  * Batch count bounds + fixed cadence. These back the injectable Config seam as
19
57
  * its DEFAULTS: consumer sites read `config?.manualBatch?.<field> ?? <CONSTANT>`
@@ -1,3 +1,15 @@
1
+ /**
2
+ * True for the better-sqlite3 `SqliteError` a UNIQUE index violation raises.
3
+ * The single shared home for this driver-error-classification check — a
4
+ * cross-phase review found `store/runs.ts` and `store/steps.ts` each
5
+ * carrying a byte-identical, independently-declared copy (one file's own
6
+ * doc comment admitted it "mirrors" the other's), which is exactly the kind
7
+ * of drift risk `planners/registry.ts`'s `resolvePlannerFor` was extracted
8
+ * to close for a different pair of duplicated call sites.
9
+ */
10
+ export function isUniqueConstraintError(error) {
11
+ return error instanceof Error && error.code === "SQLITE_CONSTRAINT_UNIQUE";
12
+ }
1
13
  // ── Typed errors ─────────────────────────────────────────────────────────────
2
14
  /** Generic validation/schedule reject — the route maps it to 400 + the reason. */
3
15
  export class CodexCronotonValidationError extends Error {
@@ -27,6 +39,55 @@ export class ManualBatchActiveError extends Error {
27
39
  this.name = 'ManualBatchActiveError';
28
40
  }
29
41
  }
42
+ /** A non-terminal run already exists for this cronoton — self-blocking only (a DIFFERENT cronoton must never be blocked by this). */
43
+ export class RunAlreadyInFlightError extends Error {
44
+ constructor(codexCronotonId) {
45
+ super(`codex cronoton ${codexCronotonId} already has a non-terminal run in flight — a new run cannot start until it settles`);
46
+ this.name = 'RunAlreadyInFlightError';
47
+ }
48
+ }
49
+ /** A run leg already has (or is past) a request key — re-submission is refused; the leg must only be polled, never re-submitted. */
50
+ export class LegAlreadySubmittedError extends Error {
51
+ constructor(legId) {
52
+ super(`run leg ${legId} is already submitted (or past submission) — re-submission is refused, only polling for its outcome is allowed`);
53
+ this.name = 'LegAlreadySubmittedError';
54
+ }
55
+ }
56
+ /** markLegConfirmed/markLegFailed require the leg to currently be 'submitted' — a leg that never reached the chain cannot be confirmed, and an already-terminal leg cannot be silently overwritten. */
57
+ export class LegNotSubmittedError extends Error {
58
+ constructor(legId) {
59
+ super(`run leg ${legId} is not in 'submitted' status — it has either never been submitted or is already in a terminal status (confirmed/failed)`);
60
+ this.name = 'LegNotSubmittedError';
61
+ }
62
+ }
63
+ /** A step already exists at this (codexCronotonId, stepIndex) — step indexes are immutable once written, mirroring RunAlreadyInFlightError's "no raw driver error escapes the store layer" posture. */
64
+ export class StepAlreadyExistsError extends Error {
65
+ constructor(codexCronotonId, stepIndex) {
66
+ super(`codex cronoton ${codexCronotonId} already has a step at index ${stepIndex} — step indexes are immutable once written`);
67
+ this.name = 'StepAlreadyExistsError';
68
+ }
69
+ }
70
+ /** A leg already exists at this (runId, stepIndex, legIndex) slot — the same "no raw driver error escapes the store layer" posture as StepAlreadyExistsError/RunAlreadyInFlightError. */
71
+ export class RunLegAlreadyExistsError extends Error {
72
+ constructor(runId, stepIndex, legIndex) {
73
+ super(`run ${runId} already has a leg at step ${stepIndex}, leg ${legIndex} — that slot cannot be inserted twice`);
74
+ this.name = 'RunLegAlreadyExistsError';
75
+ }
76
+ }
77
+ /** advanceRunStep's fromStepIndex no longer matches the run's live step_index — a stale caller must fail loudly rather than overwrite a step another process already moved past. */
78
+ export class RunStepMismatchError extends Error {
79
+ constructor(runId, expectedStepIndex) {
80
+ super(`run ${runId} is not at step ${expectedStepIndex} — its step_index has already moved on, so this advance is stale`);
81
+ this.name = 'RunStepMismatchError';
82
+ }
83
+ }
84
+ /** markRunTerminal requires the run to currently be non-terminal — an already-terminal run (succeeded/failed/abandoned) cannot be silently overwritten. */
85
+ export class RunAlreadyTerminalError extends Error {
86
+ constructor(runId) {
87
+ super(`run ${runId} is already in a terminal status (succeeded/failed/abandoned)`);
88
+ this.name = 'RunAlreadyTerminalError';
89
+ }
90
+ }
30
91
  // ── Constants ────────────────────────────────────────────────────────────────
31
92
  /**
32
93
  * Batch count bounds + fixed cadence. These back the injectable Config seam as
@@ -14,8 +14,8 @@
14
14
  * collide with the seams.ts source at the server barrel. seams.ts is the single
15
15
  * public source for those constants.
16
16
  */
17
- export { CodexCronotonValidationError, AutoGasGateError, TerminalCronotonError, ManualBatchActiveError, } from "./errors.js";
18
- export { rowToDefinition, rowExternalFireable, rowRuntimeArgKeys, assertAutoGasGate, assertGasPriceBufferAnu, manualBatchView, } from "./mappers.js";
17
+ export { CodexCronotonValidationError, AutoGasGateError, TerminalCronotonError, ManualBatchActiveError, RunAlreadyInFlightError, LegAlreadySubmittedError, LegNotSubmittedError, StepAlreadyExistsError, RunLegAlreadyExistsError, RunStepMismatchError, RunAlreadyTerminalError, } from "./errors.js";
18
+ export { rowToDefinition, stepRowToDefinition, rowExternalFireable, rowRuntimeArgKeys, assertAutoGasGate, assertGasPriceBufferAnu, manualBatchView, } from "./mappers.js";
19
19
  export { fetchDueCodexCronotons, claimDueCodexCronoton, applyTerminalIntent, advanceRecurring, } from "./claim.js";
20
20
  export { recordFire, createRunningFire, setFireJobId, appendFireTxKeys, finalizeFire, listFires, recoverFire, } from "./fires.js";
21
21
  export type { RecordFireInput, FireDep } from "./fires.js";
@@ -26,3 +26,8 @@ export type { CreateManualBatchInput } from "./manual-batch.js";
26
26
  export { computeDefinitionFingerprint } from "../pure/fingerprint.js";
27
27
  export { getCodexCronotonByPublicToken, setPublicObservable, getCronotonFireCounts, deriveCronotonHealth, toPublicCronotonView, } from "./public.js";
28
28
  export type { SetPublicObservableOpts, CronotonFireCounts, CronotonHealth, PublicCronotonView, PublicCronotonFireView, PublicCronotonFiresPage, } from "./public.js";
29
+ export { insertStep, listStepsForCronoton, getStepByIndex } from "./steps.js";
30
+ export type { InsertStepInput, CodexCronotonStepRow } from "./steps.js";
31
+ export { createRun, getRun, listRunLegs, listRunsForCronoton, insertRunLeg, claimLegForSubmit, releaseLegClaim, markLegSubmitted, markLegConfirmed, markLegFailed, listInFlightRuns, advanceRunStep, markRunTerminal, bumpRunAttempt, touchRunDeadline, } from "./runs.js";
32
+ export type { CreateRunInput, CodexCronotonRunRow, CodexCronotonRunLegRow } from "./runs.js";
33
+ export { upsertYield, getYieldPool } from "./yields.js";
@@ -15,9 +15,9 @@
15
15
  * public source for those constants.
16
16
  */
17
17
  // ── Typed errors (classes — values, not types) ───────────────────────────────
18
- export { CodexCronotonValidationError, AutoGasGateError, TerminalCronotonError, ManualBatchActiveError, } from "./errors.js";
18
+ export { CodexCronotonValidationError, AutoGasGateError, TerminalCronotonError, ManualBatchActiveError, RunAlreadyInFlightError, LegAlreadySubmittedError, LegNotSubmittedError, StepAlreadyExistsError, RunLegAlreadyExistsError, RunStepMismatchError, RunAlreadyTerminalError, } from "./errors.js";
19
19
  // ── Pure mappers / gates ─────────────────────────────────────────────────────
20
- export { rowToDefinition, rowExternalFireable, rowRuntimeArgKeys, assertAutoGasGate, assertGasPriceBufferAnu, manualBatchView, } from "./mappers.js";
20
+ export { rowToDefinition, stepRowToDefinition, rowExternalFireable, rowRuntimeArgKeys, assertAutoGasGate, assertGasPriceBufferAnu, manualBatchView, } from "./mappers.js";
21
21
  // ── Atomic claim + due selection + terminal/advance writes ───────────────────
22
22
  export { fetchDueCodexCronotons, claimDueCodexCronoton, applyTerminalIntent, advanceRecurring, } from "./claim.js";
23
23
  // ── Fires: record / running / append / finalize / list / recover ─────────────
@@ -33,3 +33,9 @@ export { getManualBatch, getActiveManualBatchForCronoton, createManualBatch, fet
33
33
  export { computeDefinitionFingerprint } from "../pure/fingerprint.js";
34
34
  // ── Public observability: token toggle, by-token read, counts, health, projector ──
35
35
  export { getCodexCronotonByPublicToken, setPublicObservable, getCronotonFireCounts, deriveCronotonHealth, toPublicCronotonView, } from "./public.js";
36
+ // ── Chained-run step definitions: insert / list ──────────────────────────────
37
+ export { insertStep, listStepsForCronoton, getStepByIndex } from "./steps.js";
38
+ // ── Chained runs + legs: create / read / leg lifecycle ────────────────────────
39
+ export { createRun, getRun, listRunLegs, listRunsForCronoton, insertRunLeg, claimLegForSubmit, releaseLegClaim, markLegSubmitted, markLegConfirmed, markLegFailed, listInFlightRuns, advanceRunStep, markRunTerminal, bumpRunAttempt, touchRunDeadline, } from "./runs.js";
40
+ // ── Step-to-step yield carry: upsert / read the per-run named-yield pool ─────
41
+ export { upsertYield, getYieldPool } from "./yields.js";
@@ -1,10 +1,21 @@
1
1
  import type { CodexCronotonRow, CodexManualBatchRow, CodexTxConfig, CodexTxDefinition, ManualBatchView } from '../types.js';
2
+ import type { CodexCronotonStepRow } from './steps.js';
2
3
  /**
3
4
  * The single mapper from a `codex_cronotons` row to the `CodexTxDefinition`
4
5
  * consumed by the executor. `scheduleKind` is `'one-time'` ONLY for the
5
6
  * one-time mode; all other six modes map to `'recurring'`.
6
7
  */
7
8
  export declare function rowToDefinition(row: CodexCronotonRow): CodexTxDefinition;
9
+ /**
10
+ * Mirrors {@link rowToDefinition} for a `codex_cronoton_steps` row — the
11
+ * STATIC per-step definition a `mode: 'single'` step carries. Omits
12
+ * `scheduleKind`/`serverResolver` entirely, since a step row has neither
13
+ * column (those two fields belong to the cronoton's own schedule, not a
14
+ * step inside a chained run). `pact_code` falls back to `""` when `null`
15
+ * — only ever non-null for a `mode: 'single'` step, the only mode any
16
+ * current caller passes to this function.
17
+ */
18
+ export declare function stepRowToDefinition(step: CodexCronotonStepRow): CodexTxDefinition;
8
19
  /** True when the row is opted into external (HMAC-endpoint) firing. */
9
20
  export declare function rowExternalFireable(row: CodexCronotonRow): boolean;
10
21
  /** The declared runtime-arg keys for the row; empty for ordinary rows. */
@@ -23,6 +23,26 @@ export function rowToDefinition(row) {
23
23
  serverResolver: row.server_resolver ?? undefined,
24
24
  };
25
25
  }
26
+ /**
27
+ * Mirrors {@link rowToDefinition} for a `codex_cronoton_steps` row — the
28
+ * STATIC per-step definition a `mode: 'single'` step carries. Omits
29
+ * `scheduleKind`/`serverResolver` entirely, since a step row has neither
30
+ * column (those two fields belong to the cronoton's own schedule, not a
31
+ * step inside a chained run). `pact_code` falls back to `""` when `null`
32
+ * — only ever non-null for a `mode: 'single'` step, the only mode any
33
+ * current caller passes to this function.
34
+ */
35
+ export function stepRowToDefinition(step) {
36
+ return {
37
+ pactCode: step.pact_code ?? '',
38
+ config: parseJson(step.config_json, {}),
39
+ payload: parseJson(step.payload_json, {}),
40
+ gasPayer: parseJson(step.gas_payer_json, {
41
+ type: 'gas-station',
42
+ }),
43
+ signers: parseJson(step.signers_json, []),
44
+ };
45
+ }
26
46
  /** True when the row is opted into external (HMAC-endpoint) firing. */
27
47
  export function rowExternalFireable(row) {
28
48
  return row.external_fireable === 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;