@ancientpantheon/khronoton-core 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +114 -0
  3. package/dist/blockchain/stoachain.d.ts +1 -1
  4. package/dist/blockchain/stoachain.js +16 -1
  5. package/dist/{chunk-LX6T2BDL.js → chunk-7H5TM3CS.js} +1 -1
  6. package/dist/{chunk-GNQ2IVXA.js → chunk-IAK4UEAA.js} +731 -24
  7. package/dist/{context-89YS4xT3.d.ts → context-P-rCtBbJ.d.ts} +2 -2
  8. package/dist/handlers/execute.d.ts +12 -4
  9. package/dist/handlers/execute.js +42 -5
  10. package/dist/handlers/index.d.ts +4 -2
  11. package/dist/handlers/index.js +7 -2
  12. package/dist/handlers/public.d.ts +41 -0
  13. package/dist/handlers/public.js +78 -0
  14. package/dist/handlers/read.d.ts +11 -0
  15. package/dist/handlers/read.js +65 -1
  16. package/dist/handlers/steps.d.ts +3 -0
  17. package/dist/handlers/steps.js +115 -0
  18. package/dist/hooks/index.d.ts +4 -4
  19. package/dist/hooks/index.js +2 -2
  20. package/dist/provider/index.d.ts +4 -4
  21. package/dist/provider/index.js +33 -2
  22. package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
  23. package/dist/server/executor.d.ts +14 -1
  24. package/dist/server/executor.js +144 -26
  25. package/dist/server/index.d.ts +11 -2
  26. package/dist/server/index.js +29 -1
  27. package/dist/server/loop.d.ts +17 -13
  28. package/dist/server/loop.js +19 -12
  29. package/dist/server/planners/evict.d.ts +20 -0
  30. package/dist/server/planners/evict.js +143 -0
  31. package/dist/server/planners/inject.d.ts +22 -0
  32. package/dist/server/planners/inject.js +120 -0
  33. package/dist/server/planners/registry.d.ts +80 -0
  34. package/dist/server/planners/registry.js +50 -0
  35. package/dist/server/planners/stoa-unwrap.d.ts +23 -0
  36. package/dist/server/planners/stoa-unwrap.js +204 -0
  37. package/dist/server/planners/stoa-wrap.d.ts +22 -0
  38. package/dist/server/planners/stoa-wrap.js +201 -0
  39. package/dist/server/planners/unstall.d.ts +25 -0
  40. package/dist/server/planners/unstall.js +135 -0
  41. package/dist/server/pure/run-advance.d.ts +76 -0
  42. package/dist/server/pure/run-advance.js +94 -0
  43. package/dist/server/pure/split-plan.d.ts +144 -0
  44. package/dist/server/pure/split-plan.js +362 -0
  45. package/dist/server/resolvers.js +48 -6
  46. package/dist/server/runs-driver.d.ts +92 -0
  47. package/dist/server/runs-driver.js +511 -0
  48. package/dist/server/schema.d.ts +12 -2
  49. package/dist/server/schema.js +105 -1
  50. package/dist/server/seams.d.ts +28 -0
  51. package/dist/server/seams.js +4 -0
  52. package/dist/server/store/errors.d.ts +38 -0
  53. package/dist/server/store/errors.js +61 -0
  54. package/dist/server/store/fires.js +27 -1
  55. package/dist/server/store/index.d.ts +8 -2
  56. package/dist/server/store/index.js +8 -2
  57. package/dist/server/store/mappers.d.ts +11 -0
  58. package/dist/server/store/mappers.js +20 -0
  59. package/dist/server/store/public.d.ts +104 -0
  60. package/dist/server/store/public.js +197 -0
  61. package/dist/server/store/runs.d.ts +233 -0
  62. package/dist/server/store/runs.js +341 -0
  63. package/dist/server/store/steps.d.ts +42 -0
  64. package/dist/server/store/steps.js +51 -0
  65. package/dist/server/tick.d.ts +7 -0
  66. package/dist/server/tick.js +50 -1
  67. package/dist/server/types.d.ts +55 -3
  68. package/dist/{types-DnFB1Yz-.d.ts → types-uYSglFrJ.d.ts} +13 -0
  69. package/dist/ui/index.d.ts +1 -1
  70. package/dist/ui/index.js +2 -2
  71. package/package.json +1 -1
@@ -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
@@ -117,6 +117,32 @@ function parseTxKeys(json) {
117
117
  return [];
118
118
  }
119
119
  }
120
+ /**
121
+ * Parse the stored chain_response_json; tolerate null/malformed data by
122
+ * degrading to `null` rather than throwing. `chain_response_json` is only
123
+ * ever WRITTEN via `JSON.stringify` (recordFire/finalizeFire above), so a
124
+ * parse failure here can only come from pre-existing corrupted/legacy data —
125
+ * but letting that throw propagate is a real hazard for ANY caller: Node
126
+ * 20+'s V8 embeds a snippet of the actual malformed input text in a
127
+ * `JSON.parse` `SyntaxError`'s message (e.g. `Unexpected token 'x',
128
+ * "<snippet>"... is not valid JSON`), and this column can carry on-chain
129
+ * response data a caller may be obligated to keep confidential (the
130
+ * unauthenticated `handlers/public.ts` route is the sharpest edge of that —
131
+ * an uncaught throw here used to ride straight through `mapStoreError`'s
132
+ * generic `error.message` passthrough into a public 500 body, bypassing
133
+ * `toPublicCronotonView`'s sanitization entirely since the throw happened
134
+ * before the projector ever ran).
135
+ */
136
+ function parseChainResponse(json) {
137
+ if (!json)
138
+ return null;
139
+ try {
140
+ return JSON.parse(json);
141
+ }
142
+ catch {
143
+ return null;
144
+ }
145
+ }
120
146
  /** Paginated fire history for a cronoton, newest-first (limit clamped 1..100, default 20). */
121
147
  export function listFires(id, params = {}, dep) {
122
148
  const db = dep.db;
@@ -140,7 +166,7 @@ export function listFires(id, params = {}, dep) {
140
166
  requestKey: r.request_key,
141
167
  chainId: r.chain_id,
142
168
  errorMessage: r.error_message,
143
- chainResponse: r.chain_response_json ? JSON.parse(r.chain_response_json) : null,
169
+ chainResponse: parseChainResponse(r.chain_response_json),
144
170
  definitionFingerprint: r.definition_fingerprint,
145
171
  mode: r.mode === "live" ? "live" : "test",
146
172
  recoveredAt: r.recovered_at,
@@ -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";
@@ -24,3 +24,9 @@ export type { CommitCodexCronotonInput, EditCodexCronotonPatch } from "./cronoto
24
24
  export { getManualBatch, getActiveManualBatchForCronoton, createManualBatch, fetchDueManualBatches, claimManualBatchFire, cancelManualBatch, } from "./manual-batch.js";
25
25
  export type { CreateManualBatchInput } from "./manual-batch.js";
26
26
  export { computeDefinitionFingerprint } from "../pure/fingerprint.js";
27
+ export { getCodexCronotonByPublicToken, setPublicObservable, getCronotonFireCounts, deriveCronotonHealth, toPublicCronotonView, } from "./public.js";
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 ─────────────
@@ -31,3 +31,9 @@ export { getManualBatch, getActiveManualBatchForCronoton, createManualBatch, fet
31
31
  // store barrel is the single export site here (the Phase-1 server barrel drops
32
32
  // its own direct fingerprint export in favor of this one to avoid a duplicate).
33
33
  export { computeDefinitionFingerprint } from "../pure/fingerprint.js";
34
+ // ── Public observability: token toggle, by-token read, counts, health, projector ──
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,104 @@
1
+ import type { DbDep } from "../seams.js";
2
+ import type { CodexCronotonFireRow, CodexCronotonRow } from "../types.js";
3
+ export interface SetPublicObservableOpts {
4
+ observable: boolean;
5
+ /** Force a fresh token even if one already exists. Ignored when `observable` is false. */
6
+ regenerate?: boolean;
7
+ }
8
+ /**
9
+ * Flip a cronoton's public-observability flag. Minting is lazy and stable:
10
+ * a token is generated ONLY the first time a row is made observable (or when
11
+ * `regenerate: true` is explicitly passed) — disabling then re-enabling
12
+ * reuses the same token, so an embed URL built from it never has to be
13
+ * re-minted. Disabling never touches `public_token`.
14
+ */
15
+ export declare function setPublicObservable(id: string, opts: SetPublicObservableOpts, dep: DbDep): {
16
+ publicToken: string | null;
17
+ publicObservable: boolean;
18
+ };
19
+ /**
20
+ * Resolve a cronoton by its public token. Returns `null` for an unknown
21
+ * token AND for a known token whose row is currently non-observable — the
22
+ * single query makes the two cases indistinguishable on purpose (the public
23
+ * handler can't leak which one it is).
24
+ */
25
+ export declare function getCodexCronotonByPublicToken(token: string, dep: DbDep): CodexCronotonRow | null;
26
+ export interface CronotonFireCounts {
27
+ fired: number;
28
+ succeeded: number;
29
+ failed: number;
30
+ lastSuccessAt: string | null;
31
+ lastFailureAt: string | null;
32
+ /** Consecutive failures immediately preceding the most recent fire; capped at 1000. */
33
+ currentFailStreak: number;
34
+ }
35
+ /**
36
+ * Whole-history fire counts for a cronoton. Deliberately independent of any
37
+ * paginated fires window (a page of 20 out of 150 fires would under-report
38
+ * every aggregate): one aggregate query for the totals/last-timestamps, plus
39
+ * a second DESC-ordered scan (capped at 1000 rows) counting leading
40
+ * `'failure'` statuses for `currentFailStreak` — the scan stops at the first
41
+ * non-failure (or the cap), so a success anywhere further back never dilutes
42
+ * the trailing streak.
43
+ */
44
+ export declare function getCronotonFireCounts(id: string, dep: DbDep): CronotonFireCounts;
45
+ export type CronotonHealth = "healthy" | "degraded" | "down";
46
+ /**
47
+ * The pure traffic-light health rule: `"down"` once the trailing streak hits
48
+ * 3, `"degraded"` for a 1-2 streak OR an overdue schedule, `"healthy"`
49
+ * otherwise. Exported standalone so a consumer can reason about it without a
50
+ * DB row.
51
+ */
52
+ export declare function deriveCronotonHealth(input: {
53
+ currentFailStreak: number;
54
+ isOverdue: boolean;
55
+ }): CronotonHealth;
56
+ export interface PublicCronotonFireView {
57
+ firedAt: string;
58
+ status: CodexCronotonFireRow["status"];
59
+ chainId: string | null;
60
+ requestKey: string | null;
61
+ txKeys: CodexCronotonFireRow["txKeys"];
62
+ recoveredAt: string | null;
63
+ mode: CodexCronotonFireRow["mode"];
64
+ }
65
+ export interface PublicCronotonFiresPage {
66
+ fires: CodexCronotonFireRow[];
67
+ total: number;
68
+ limit: number;
69
+ offset: number;
70
+ }
71
+ export interface PublicCronotonView {
72
+ name: string;
73
+ description: string | null;
74
+ status: CodexCronotonRow["status"];
75
+ schedule: {
76
+ mode: CodexCronotonRow["schedule_mode"];
77
+ humanText: string;
78
+ cron?: string;
79
+ };
80
+ triggerOnly: boolean;
81
+ nextFireAt: string | null;
82
+ lastFireAt: string | null;
83
+ isOverdue: boolean;
84
+ since: string;
85
+ counts: CronotonFireCounts & {
86
+ successRatePercent: number | null;
87
+ };
88
+ health: CronotonHealth;
89
+ fires: {
90
+ page: PublicCronotonFireView[];
91
+ total: number;
92
+ limit: number;
93
+ offset: number;
94
+ };
95
+ }
96
+ /**
97
+ * Pure projector (no DB access of its own) from a `CodexCronotonRow` +
98
+ * its `getCronotonFireCounts` result + a `listFires` page onto the sanitized
99
+ * public DTO. Builds the result field-by-field — never spreads the row or a
100
+ * fire — so `pact_code`/`payload_json`/`signers_json`/`gas_payer_json`/
101
+ * `server_resolver`/`created_by`/`config_json`, the internal `id`, and a
102
+ * fire's raw `errorMessage`/`chainResponse` can never leak through it.
103
+ */
104
+ export declare function toPublicCronotonView(row: CodexCronotonRow, counts: CronotonFireCounts, firesPage: PublicCronotonFiresPage, now?: Date): PublicCronotonView;
@@ -0,0 +1,197 @@
1
+ /**
2
+ * public — the public (unauthenticated-by-design) observability surface for a
3
+ * single codex-cronoton: a lazily-minted, stable lookup token, a by-token
4
+ * read gated on `public_observable`, whole-history fire counts, a pure
5
+ * traffic-light health rule, and the sanitizing projector that assembles the
6
+ * client-facing DTO.
7
+ *
8
+ * `toPublicCronotonView` is the ONLY place the privacy guarantee is enforced:
9
+ * it builds a brand-new object field-by-field from the (far more sensitive)
10
+ * `CodexCronotonRow`/`CodexCronotonFireRow` inputs, never spreading either —
11
+ * a raw `pact_code`, JSON config blob, `created_by`, or fire `errorMessage`/
12
+ * `chainResponse` must never ride along by accident.
13
+ */
14
+ import crypto from "node:crypto";
15
+ import { summariseSchedule } from "../../schedule.js";
16
+ import { getCodexCronoton } from "./cronoton.js";
17
+ import { CodexCronotonValidationError } from "./errors.js";
18
+ import { rowExternalFireable, rowRuntimeArgKeys } from "./mappers.js";
19
+ /**
20
+ * Flip a cronoton's public-observability flag. Minting is lazy and stable:
21
+ * a token is generated ONLY the first time a row is made observable (or when
22
+ * `regenerate: true` is explicitly passed) — disabling then re-enabling
23
+ * reuses the same token, so an embed URL built from it never has to be
24
+ * re-minted. Disabling never touches `public_token`.
25
+ */
26
+ export function setPublicObservable(id, opts, dep) {
27
+ const db = dep.db;
28
+ const row = getCodexCronoton(id, { db });
29
+ if (!row)
30
+ throw new CodexCronotonValidationError("not found");
31
+ let nextToken = row.public_token ?? null;
32
+ if (opts.observable && (!nextToken || opts.regenerate === true)) {
33
+ nextToken = crypto.randomBytes(20).toString("base64url");
34
+ }
35
+ db.prepare(`UPDATE codex_cronotons SET public_token = ?, public_observable = ?, modified_at = ? WHERE id = ?`).run(nextToken, opts.observable ? 1 : 0, new Date().toISOString(), id);
36
+ return { publicToken: nextToken, publicObservable: opts.observable };
37
+ }
38
+ /**
39
+ * Resolve a cronoton by its public token. Returns `null` for an unknown
40
+ * token AND for a known token whose row is currently non-observable — the
41
+ * single query makes the two cases indistinguishable on purpose (the public
42
+ * handler can't leak which one it is).
43
+ */
44
+ export function getCodexCronotonByPublicToken(token, dep) {
45
+ const row = dep.db
46
+ .prepare(`SELECT * FROM codex_cronotons WHERE public_token = ? AND public_observable = 1`)
47
+ .get(token);
48
+ return row ?? null;
49
+ }
50
+ /**
51
+ * Whole-history fire counts for a cronoton. Deliberately independent of any
52
+ * paginated fires window (a page of 20 out of 150 fires would under-report
53
+ * every aggregate): one aggregate query for the totals/last-timestamps, plus
54
+ * a second DESC-ordered scan (capped at 1000 rows) counting leading
55
+ * `'failure'` statuses for `currentFailStreak` — the scan stops at the first
56
+ * non-failure (or the cap), so a success anywhere further back never dilutes
57
+ * the trailing streak.
58
+ */
59
+ export function getCronotonFireCounts(id, dep) {
60
+ const db = dep.db;
61
+ const agg = db
62
+ .prepare(`SELECT
63
+ COUNT(*) AS fired,
64
+ SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) AS succeeded,
65
+ SUM(CASE WHEN status = 'failure' THEN 1 ELSE 0 END) AS failed,
66
+ MAX(CASE WHEN status = 'success' THEN fired_at ELSE NULL END) AS lastSuccessAt,
67
+ MAX(CASE WHEN status = 'failure' THEN fired_at ELSE NULL END) AS lastFailureAt
68
+ FROM codex_cronoton_fires
69
+ WHERE codex_cronoton_id = ?`)
70
+ .get(id);
71
+ const recent = db
72
+ .prepare(
73
+ // Tiebreak on SQLite's implicit `rowid`, NOT the `id` column — `id` is a
74
+ // `crypto.randomUUID()` (fires.ts's recordFire/createRunningFire), with
75
+ // zero correlation to insertion order, so an `id`-based tiebreak would
76
+ // pick "most recent" essentially at random on a genuine fired_at tie.
77
+ // `rowid` is safe here: this table has no `INTEGER PRIMARY KEY`/`WITHOUT
78
+ // ROWID` override, and rows are never deleted standalone (only
79
+ // cascade-deleted with their parent cronoton), so rowid reuse never
80
+ // becomes a factor for a still-alive cronoton's fire history.
81
+ `SELECT status FROM codex_cronoton_fires
82
+ WHERE codex_cronoton_id = ?
83
+ ORDER BY fired_at DESC, rowid DESC LIMIT 1000`)
84
+ .all(id);
85
+ let currentFailStreak = 0;
86
+ for (const r of recent) {
87
+ if (r.status !== "failure")
88
+ break;
89
+ currentFailStreak += 1;
90
+ }
91
+ return {
92
+ fired: agg.fired,
93
+ succeeded: agg.succeeded ?? 0,
94
+ failed: agg.failed ?? 0,
95
+ lastSuccessAt: agg.lastSuccessAt ?? null,
96
+ lastFailureAt: agg.lastFailureAt ?? null,
97
+ currentFailStreak,
98
+ };
99
+ }
100
+ /**
101
+ * The pure traffic-light health rule: `"down"` once the trailing streak hits
102
+ * 3, `"degraded"` for a 1-2 streak OR an overdue schedule, `"healthy"`
103
+ * otherwise. Exported standalone so a consumer can reason about it without a
104
+ * DB row.
105
+ */
106
+ export function deriveCronotonHealth(input) {
107
+ if (input.currentFailStreak >= 3)
108
+ return "down";
109
+ if (input.currentFailStreak >= 1 || input.isOverdue)
110
+ return "degraded";
111
+ return "healthy";
112
+ }
113
+ /** Best-effort parse of `schedule_config_json`; `null` on malformed/legacy data. */
114
+ function parseScheduleConfig(json) {
115
+ try {
116
+ return JSON.parse(json);
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ }
122
+ /**
123
+ * Pure projector (no DB access of its own) from a `CodexCronotonRow` +
124
+ * its `getCronotonFireCounts` result + a `listFires` page onto the sanitized
125
+ * public DTO. Builds the result field-by-field — never spreads the row or a
126
+ * fire — so `pact_code`/`payload_json`/`signers_json`/`gas_payer_json`/
127
+ * `server_resolver`/`created_by`/`config_json`, the internal `id`, and a
128
+ * fire's raw `errorMessage`/`chainResponse` can never leak through it.
129
+ */
130
+ export function toPublicCronotonView(row, counts, firesPage, now = new Date()) {
131
+ const parsedConfig = parseScheduleConfig(row.schedule_config_json);
132
+ const humanText = parsedConfig
133
+ ? summariseSchedule(row.schedule_mode, parsedConfig)
134
+ : row.schedule_mode;
135
+ const schedule = {
136
+ mode: row.schedule_mode,
137
+ humanText,
138
+ };
139
+ if (parsedConfig && parsedConfig.mode === "cron-expression") {
140
+ schedule.cron = parsedConfig.expression;
141
+ }
142
+ // A row committed/edited with ONLY `eventDriven: true` (no `externalFireable`,
143
+ // no `evented` server resolver) persists `external_fireable = 0` and
144
+ // `runtime_arg_keys = null` — `next_fire_at === null` is the ONLY signal
145
+ // store/cronoton.ts leaves for it (see editCodexCronoton's own
146
+ // "reliable, column-free marker" comment). But a null `next_fire_at` is ALSO
147
+ // how a spent terminal one-time row looks (applyTerminalIntent clears it on
148
+ // completion/error) despite never being trigger-only — so the null check is
149
+ // gated on the row NOT being terminal.
150
+ //
151
+ // KNOWN LIMITATION (not fully disambiguable without a dedicated persisted
152
+ // column — judged disproportionate for a read-only view's display label):
153
+ // `claimDueCodexCronoton` (./claim.js) ALSO nulls `next_fire_at` on an
154
+ // ORDINARY, non-trigger-only row while leaving `status = 'active'` — (a)
155
+ // transiently, for every one-time row, during the brief window between
156
+ // claim and the eventual terminal-intent write; (b) PERMANENTLY, for a
157
+ // recurring row whose `schedule_config_json` is corrupt (claim.ts's own
158
+ // "F-003" case — the row is stuck `active` with a null `next_fire_at`
159
+ // forever, since the due-query requires `next_fire_at IS NOT NULL`). Both
160
+ // cases read as `triggerOnly: true` here. Accepted: the corrupt-config row
161
+ // is already broken regardless of this label, and the one-time window is
162
+ // bounded and transient.
163
+ const triggerOnly = rowExternalFireable(row) ||
164
+ rowRuntimeArgKeys(row).length > 0 ||
165
+ (row.next_fire_at === null && row.status !== "completed" && row.status !== "error");
166
+ const isOverdue = row.status === "active" &&
167
+ row.next_fire_at !== null &&
168
+ new Date(row.next_fire_at) < now;
169
+ const successRatePercent = counts.fired > 0 ? Math.round((counts.succeeded / counts.fired) * 100) : null;
170
+ return {
171
+ name: row.name,
172
+ description: row.description,
173
+ status: row.status,
174
+ schedule,
175
+ triggerOnly,
176
+ nextFireAt: row.next_fire_at,
177
+ lastFireAt: row.last_fire_at,
178
+ isOverdue,
179
+ since: row.created_at,
180
+ counts: { ...counts, successRatePercent },
181
+ health: deriveCronotonHealth({ currentFailStreak: counts.currentFailStreak, isOverdue }),
182
+ fires: {
183
+ page: firesPage.fires.map((fire) => ({
184
+ firedAt: fire.firedAt,
185
+ status: fire.status,
186
+ chainId: fire.chainId,
187
+ requestKey: fire.requestKey,
188
+ txKeys: fire.txKeys,
189
+ recoveredAt: fire.recoveredAt,
190
+ mode: fire.mode,
191
+ })),
192
+ total: firesPage.total,
193
+ limit: firesPage.limit,
194
+ offset: firesPage.offset,
195
+ },
196
+ };
197
+ }