@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
@@ -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,7 @@ 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 } 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";
@@ -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,7 @@ 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 } 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";
@@ -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;