@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
@@ -1,6 +1,6 @@
1
1
  import { ReactNode } from 'react';
2
- import { b as CodexTxConfig, c as CodexGasPayer, d as CodexSigner, S as ScheduleMode, e as ScheduleConfig, C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from './types-DnFB1Yz-.js';
3
- import { b as DbDep, D as Database } from './seams-DUtxDw_U.js';
2
+ import { b as CodexTxConfig, c as CodexGasPayer, d as CodexSigner, S as ScheduleMode, e as ScheduleConfig, C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from './types-uYSglFrJ.js';
3
+ import { b as DbDep, D as Database } from './seams-Co8Tq4ka.js';
4
4
 
5
5
  /** A validated bag of runtime args — every value is a string (Pact `read-string`). */
6
6
  type RuntimeArgs = Record<string, string>;
@@ -8,10 +8,18 @@ import type { Handler } from "./context.js";
8
8
  */
9
9
  export declare const simulateCodexTx: Handler;
10
10
  /**
11
- * Fire a committed cronoton on demand, outside its schedule. A multi-tx
12
- * server-resolved row is queued (202) rather than fired inline (REQ-H06); every
13
- * other row fires + records exactly one fire row and returns HTTP 200 with the
14
- * fire outcome in the body (`ok:false` still 200 — REQ-H04).
11
+ * Fire a committed cronoton on demand, outside its schedule. A CHAINED row
12
+ * (>=1 `codex_cronoton_steps` row) starts a real run instead — mirroring
13
+ * `tick.ts`'s own branch (design.md §A) rather than reinventing it: it never
14
+ * reaches the flat-definition/multi-tx paths below, since a chained row
15
+ * doesn't carry a meaningful `server_resolver`. Unlike the scheduler's tick
16
+ * (which silently skips a self-blocked cronoton to retry next pass), this is
17
+ * an explicit on-demand request — a non-terminal run already in flight for
18
+ * the SAME cronoton surfaces as a real 409, not a silent no-op. A multi-tx
19
+ * server-resolved PLAIN row is queued (202) rather than fired inline
20
+ * (REQ-H06); every other plain row fires + records exactly one fire row and
21
+ * returns HTTP 200 with the fire outcome in the body (`ok:false` still
22
+ * 200 — REQ-H04).
15
23
  */
16
24
  export declare const executeNow: Handler;
17
25
  /**
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { json, err } from "./http.js";
25
25
  import { withConfirm } from "./context.js";
26
- import { executeCodexTransaction, fireByServerResolver, getServerResolver, resolveServerVars, getCodexCronoton, recordFire, recoverFire as recoverFireInStore, applyTerminalIntent, rowToDefinition, rowRuntimeArgKeys, computeDefinitionFingerprint, validateRuntimeArgs, applyRuntimeArgs, } from "../server/index.js";
26
+ import { executeCodexTransaction, fireByServerResolver, getServerResolver, resolveServerVars, getCodexCronoton, recordFire, recoverFire as recoverFireInStore, applyTerminalIntent, rowToDefinition, rowRuntimeArgKeys, computeDefinitionFingerprint, validateRuntimeArgs, applyRuntimeArgs, listStepsForCronoton, createRun, getRun, driveRunOnce, defaultOnAudit, RunAlreadyInFlightError, } from "../server/index.js";
27
27
  /** A landed on-chain request key: 40–48 URL-safe base64 chars. */
28
28
  const REQUEST_KEY_RE = /^[A-Za-z0-9_-]{40,48}$/;
29
29
  /** Terminal statuses cannot be fired on demand (their single/spent attempt is done). */
@@ -139,10 +139,18 @@ export const simulateCodexTx = (ctx, req) => withConfirm(ctx, req, async () => {
139
139
  });
140
140
  });
141
141
  /**
142
- * Fire a committed cronoton on demand, outside its schedule. A multi-tx
143
- * server-resolved row is queued (202) rather than fired inline (REQ-H06); every
144
- * other row fires + records exactly one fire row and returns HTTP 200 with the
145
- * fire outcome in the body (`ok:false` still 200 — REQ-H04).
142
+ * Fire a committed cronoton on demand, outside its schedule. A CHAINED row
143
+ * (>=1 `codex_cronoton_steps` row) starts a real run instead — mirroring
144
+ * `tick.ts`'s own branch (design.md §A) rather than reinventing it: it never
145
+ * reaches the flat-definition/multi-tx paths below, since a chained row
146
+ * doesn't carry a meaningful `server_resolver`. Unlike the scheduler's tick
147
+ * (which silently skips a self-blocked cronoton to retry next pass), this is
148
+ * an explicit on-demand request — a non-terminal run already in flight for
149
+ * the SAME cronoton surfaces as a real 409, not a silent no-op. A multi-tx
150
+ * server-resolved PLAIN row is queued (202) rather than fired inline
151
+ * (REQ-H06); every other plain row fires + records exactly one fire row and
152
+ * returns HTTP 200 with the fire outcome in the body (`ok:false` still
153
+ * 200 — REQ-H04).
146
154
  */
147
155
  export const executeNow = (ctx, req) => withConfirm(ctx, req, async () => {
148
156
  const id = req.params?.id;
@@ -156,6 +164,35 @@ export const executeNow = (ctx, req) => withConfirm(ctx, req, async () => {
156
164
  if (TERMINAL_STATUSES.has(row.status)) {
157
165
  return err(400, "cannot execute a terminal cronoton");
158
166
  }
167
+ const steps = listStepsForCronoton(row.id, { db: ctx.db });
168
+ if (steps.length > 0) {
169
+ try {
170
+ const runId = createRun({ codexCronotonId: row.id, stepCount: steps.length }, { db: ctx.db });
171
+ const driverCtx = {
172
+ db: ctx.db,
173
+ runtime: ctx.runtime,
174
+ resolver: ctx.resolver,
175
+ config: ctx.config,
176
+ onAudit: ctx.onAudit ?? defaultOnAudit,
177
+ };
178
+ await driveRunOnce(runId, new Date(), driverCtx);
179
+ await ctx.onAudit?.({
180
+ action: "codex_cronoton.run_started",
181
+ result: "success",
182
+ targetKind: "codex_cronoton",
183
+ targetId: row.id,
184
+ detail: { codexCronotonId: row.id, runId, stepCount: steps.length, actor: "ancient" },
185
+ });
186
+ const run = getRun(runId, { db: ctx.db });
187
+ return json(200, { ok: true, runId, status: run?.status ?? null });
188
+ }
189
+ catch (e) {
190
+ if (e instanceof RunAlreadyInFlightError) {
191
+ return err(409, "a run is already in flight for this cronoton");
192
+ }
193
+ throw e;
194
+ }
195
+ }
159
196
  const resolverName = row.server_resolver ?? undefined;
160
197
  if (resolverName && getServerResolver(resolverName)?.kind === "multi-tx") {
161
198
  return json(202, { ok: true, queued: true });
@@ -3,7 +3,7 @@
3
3
  * framework-agnostic route surface over the `/server` store + executor. A
4
4
  * consumer adapts its framework's request/response into {@link HandlerRequest} /
5
5
  * {@link HandlerResponse}, injects a {@link HandlerContext} (db + runtime +
6
- * resolver + an {@link AuthSeam}), and calls the seventeen handlers below.
6
+ * resolver + an {@link AuthSeam}), and calls the eighteen handlers below.
7
7
  *
8
8
  * The read handlers keep their contract names here (aliasing their module's
9
9
  * `*Handler` implementations), so the barrel exposes the exact route contract
@@ -13,11 +13,13 @@
13
13
  * Every re-export is `export type` where the symbol is a type, so the emitted
14
14
  * `.d.ts` stays fully erasable. Explicit `.js` extensions throughout.
15
15
  */
16
- export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, resolversHandler as listResolvers, } from "./read.js";
16
+ export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, resolversHandler as listResolvers, runsHandler as fetchRuns, runLegsHandler as fetchRunLegs, } from "./read.js";
17
17
  export { commitCodexCronoton, editCodexCronoton, pauseCodexCronoton, resumeCodexCronoton, deleteCodexCronoton, } from "./cronoton.js";
18
18
  export type { CommitBody, CommitEnvelope, CommitSchedule } from "./cronoton.js";
19
19
  export { simulateCodexTx, executeNow, triggerCronoton, recoverFire } from "./execute.js";
20
+ export { simulateStep, fireStep } from "./steps.js";
20
21
  export { startExecuteBatch, getExecuteBatch, cancelExecuteBatch } from "./batch.js";
22
+ export { publicCronotonHandler } from "./public.js";
21
23
  export { json, err, errorBody, mapStoreError } from "./http.js";
22
24
  export type { HandlerRequest, HandlerResponse } from "./http.js";
23
25
  export { defaultSignerSource, descriptorSourceToDisplay } from "./http.js";
@@ -3,7 +3,7 @@
3
3
  * framework-agnostic route surface over the `/server` store + executor. A
4
4
  * consumer adapts its framework's request/response into {@link HandlerRequest} /
5
5
  * {@link HandlerResponse}, injects a {@link HandlerContext} (db + runtime +
6
- * resolver + an {@link AuthSeam}), and calls the seventeen handlers below.
6
+ * resolver + an {@link AuthSeam}), and calls the eighteen handlers below.
7
7
  *
8
8
  * The read handlers keep their contract names here (aliasing their module's
9
9
  * `*Handler` implementations), so the barrel exposes the exact route contract
@@ -14,13 +14,18 @@
14
14
  * `.d.ts` stays fully erasable. Explicit `.js` extensions throughout.
15
15
  */
16
16
  // ── Read handlers (TC.2) — aliased to their contract names ────────────────────
17
- export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, resolversHandler as listResolvers, } from "./read.js";
17
+ export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, resolversHandler as listResolvers, runsHandler as fetchRuns, runLegsHandler as fetchRunLegs, } from "./read.js";
18
18
  // ── Cronoton-lifecycle handlers (TC.3) ────────────────────────────────────────
19
19
  export { commitCodexCronoton, editCodexCronoton, pauseCodexCronoton, resumeCodexCronoton, deleteCodexCronoton, } from "./cronoton.js";
20
20
  // ── Execution handlers (TC.4) ─────────────────────────────────────────────────
21
21
  export { simulateCodexTx, executeNow, triggerCronoton, recoverFire } from "./execute.js";
22
+ // ── Per-step standalone fire (Phase 5) — same execution tier as TC.4, scoped
23
+ // to one stored step by index rather than a whole committed row ─────────────
24
+ export { simulateStep, fireStep } from "./steps.js";
22
25
  // ── Manual-batch handlers (TC.5) ──────────────────────────────────────────────
23
26
  export { startExecuteBatch, getExecuteBatch, cancelExecuteBatch } from "./batch.js";
27
+ // ── Public observability (unauthenticated-by-design; bypasses ctx.auth) ──────
28
+ export { publicCronotonHandler } from "./public.js";
24
29
  // ── Kernel contract (TC.1): normalized request/response + helpers ─────────────
25
30
  // The request/response shapes plus the response helpers a consumer needs to
26
31
  // build its own auth seam, signer source, or error mapping.
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The public (unauthenticated-by-design) observability route: `GET
3
+ * /public/[token]`. A DIFFERENT trust tier than the admin `AuthSeam` governs —
4
+ * gating is purely "does this token resolve to an observable row," independent
5
+ * of whatever the host's admin auth would otherwise require — so this handler
6
+ * deliberately never calls `withRead`/`withConfirm`/`ctx.auth` at all. An
7
+ * unknown token and a known token whose row has `public_observable = 0` are
8
+ * made INDISTINGUISHABLE (identical 404), matching
9
+ * `getCodexCronotonByPublicToken`'s own "never 403, never leak which" contract
10
+ * one layer down.
11
+ *
12
+ * `limit`/`offset` get the SAME defensive clamp `read.ts`'s `firesHandler`
13
+ * applies (1..100, default 50 — REQ-G08/REQ-H07's override of the store's own
14
+ * default of 20) — duplicated here as a local, file-private copy rather than
15
+ * imported across handler files, since `read.ts`'s `clampInt`/`firstScalar`
16
+ * are module-private by design.
17
+ *
18
+ * The host is responsible for transport concerns this package's `{status,
19
+ * body}` contract doesn't carry: set `Cache-Control: public, max-age=30` and
20
+ * whatever CORS policy fits the deployment (mirroring the hub's own
21
+ * `pythia-odometer.ts` precedent).
22
+ */
23
+ import { type HandlerResponse } from "./http.js";
24
+ import type { HandlerContext } from "./context.js";
25
+ import type { HandlerRequest } from "./http.js";
26
+ /**
27
+ * `GET /public/[token]` — the sanitized public view for one codex-cronoton, or
28
+ * a 404 for an unknown/non-observable token (the two are indistinguishable by
29
+ * design). Never runs `ctx.auth` — this route's trust tier is the token
30
+ * itself, not the host's admin `AuthSeam`.
31
+ *
32
+ * Wrapped in try/catch -> `mapStoreError`, matching the error-translation
33
+ * idiom every other handler gets for free from `withRead`/`withConfirm`'s
34
+ * shared `runGated` wrapper — this route can't use that wrapper (it would
35
+ * reintroduce the `ctx.auth` call this handler exists to bypass), but it
36
+ * still owes the same "{status, body:{error}}` for any failure" guarantee
37
+ * (e.g. `listFires`'s `JSON.parse(chain_response_json)` throwing on a
38
+ * malformed/legacy row). The explicit 404 `return` below is unaffected by
39
+ * the wrapping `try` — it exits before the `catch` could ever see it.
40
+ */
41
+ export declare function publicCronotonHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The public (unauthenticated-by-design) observability route: `GET
3
+ * /public/[token]`. A DIFFERENT trust tier than the admin `AuthSeam` governs —
4
+ * gating is purely "does this token resolve to an observable row," independent
5
+ * of whatever the host's admin auth would otherwise require — so this handler
6
+ * deliberately never calls `withRead`/`withConfirm`/`ctx.auth` at all. An
7
+ * unknown token and a known token whose row has `public_observable = 0` are
8
+ * made INDISTINGUISHABLE (identical 404), matching
9
+ * `getCodexCronotonByPublicToken`'s own "never 403, never leak which" contract
10
+ * one layer down.
11
+ *
12
+ * `limit`/`offset` get the SAME defensive clamp `read.ts`'s `firesHandler`
13
+ * applies (1..100, default 50 — REQ-G08/REQ-H07's override of the store's own
14
+ * default of 20) — duplicated here as a local, file-private copy rather than
15
+ * imported across handler files, since `read.ts`'s `clampInt`/`firstScalar`
16
+ * are module-private by design.
17
+ *
18
+ * The host is responsible for transport concerns this package's `{status,
19
+ * body}` contract doesn't carry: set `Cache-Control: public, max-age=30` and
20
+ * whatever CORS policy fits the deployment (mirroring the hub's own
21
+ * `pythia-odometer.ts` precedent).
22
+ */
23
+ import { json, err, mapStoreError } from "./http.js";
24
+ import { getCodexCronotonByPublicToken, getCronotonFireCounts, listFires, toPublicCronotonView, } from "../server/index.js";
25
+ /** First scalar of a query value (a repeated key arrives as an array); `undefined` if empty. */
26
+ function firstScalar(raw) {
27
+ const value = Array.isArray(raw) ? raw[0] : raw;
28
+ return value === undefined || value === null || value === "" ? undefined : value;
29
+ }
30
+ /**
31
+ * Parse a query int, falling back to `def` for absent/NaN input, then clamp into
32
+ * `[min, max]`. Clamping in the handler (not only in the store) keeps the echoed
33
+ * `limit`/`offset` equal to the window actually queried.
34
+ */
35
+ function clampInt(raw, { def, min, max }) {
36
+ const scalar = firstScalar(raw);
37
+ const parsed = scalar === undefined ? Number.NaN : Number.parseInt(scalar, 10);
38
+ const base = Number.isNaN(parsed) ? def : parsed;
39
+ const lowerBounded = Math.max(base, min);
40
+ return max === undefined ? lowerBounded : Math.min(lowerBounded, max);
41
+ }
42
+ // ── Handler ───────────────────────────────────────────────────────────────────
43
+ /**
44
+ * `GET /public/[token]` — the sanitized public view for one codex-cronoton, or
45
+ * a 404 for an unknown/non-observable token (the two are indistinguishable by
46
+ * design). Never runs `ctx.auth` — this route's trust tier is the token
47
+ * itself, not the host's admin `AuthSeam`.
48
+ *
49
+ * Wrapped in try/catch -> `mapStoreError`, matching the error-translation
50
+ * idiom every other handler gets for free from `withRead`/`withConfirm`'s
51
+ * shared `runGated` wrapper — this route can't use that wrapper (it would
52
+ * reintroduce the `ctx.auth` call this handler exists to bypass), but it
53
+ * still owes the same "{status, body:{error}}` for any failure" guarantee
54
+ * (e.g. `listFires`'s `JSON.parse(chain_response_json)` throwing on a
55
+ * malformed/legacy row). The explicit 404 `return` below is unaffected by
56
+ * the wrapping `try` — it exits before the `catch` could ever see it.
57
+ */
58
+ export async function publicCronotonHandler(ctx, request) {
59
+ try {
60
+ const token = request.params?.token ?? "";
61
+ const row = getCodexCronotonByPublicToken(token, { db: ctx.db });
62
+ if (!row) {
63
+ return err(404, "not found");
64
+ }
65
+ const query = request.query ?? {};
66
+ const limit = clampInt(query.limit, { def: 50, min: 1, max: 100 });
67
+ const offset = clampInt(query.offset, { def: 0, min: 0 });
68
+ const counts = getCronotonFireCounts(row.id, { db: ctx.db });
69
+ const { fires, total } = listFires(row.id, { limit, offset }, { db: ctx.db });
70
+ return json(200, {
71
+ ok: true,
72
+ ...toPublicCronotonView(row, counts, { fires, total, limit, offset }, new Date()),
73
+ });
74
+ }
75
+ catch (error) {
76
+ return mapStoreError(error);
77
+ }
78
+ }
@@ -33,3 +33,14 @@ export declare function resolversHandler(ctx: HandlerContext, request: HandlerRe
33
33
  * values reflect the window actually queried.
34
34
  */
35
35
  export declare function firesHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
36
+ /** `GET /[id]/runs?limit&offset` — paginated chained-run history for
37
+ * one cronoton. Page size defaults to 20 (matching listRunsForCronoton's
38
+ * own default), distinct from fires' 50-default (REQ-G08 is fires-specific). */
39
+ export declare function runsHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
40
+ /** `GET /[id]/runs/[runId]/legs` — every leg of one specific run,
41
+ * scoped so a runId belonging to a DIFFERENT cronoton 404s rather
42
+ * than leaking that cronoton's leg history. Unpaginated — a single
43
+ * run's legs are bounded by the gas-ceiling-pack algorithm, never
44
+ * realistically more than a few dozen. Each leg's `definition_json` is
45
+ * redacted via {@link redactLegRow} before it leaves this handler. */
46
+ export declare function runLegsHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
@@ -14,7 +14,7 @@
14
14
  */
15
15
  import { json, err, defaultSignerSource, } from "./http.js";
16
16
  import { withRead } from "./context.js";
17
- import { listCodexCronotons, getCodexCronoton, listFires, listServerResolvers, } from "../server/index.js";
17
+ import { listCodexCronotons, getCodexCronoton, listFires, listServerResolvers, listRunsForCronoton, listRunLegs, getRun, } from "../server/index.js";
18
18
  /** First scalar of a query value (a repeated key arrives as an array); `undefined` if empty. */
19
19
  function firstScalar(raw) {
20
20
  const value = Array.isArray(raw) ? raw[0] : raw;
@@ -100,3 +100,67 @@ export async function firesHandler(ctx, request) {
100
100
  return json(200, { ok: true, fires, total, limit, offset });
101
101
  });
102
102
  }
103
+ /** `GET /[id]/runs?limit&offset` — paginated chained-run history for
104
+ * one cronoton. Page size defaults to 20 (matching listRunsForCronoton's
105
+ * own default), distinct from fires' 50-default (REQ-G08 is fires-specific). */
106
+ export async function runsHandler(ctx, request) {
107
+ return withRead(ctx, request, async () => {
108
+ const id = request.params?.id ?? "";
109
+ const query = request.query ?? {};
110
+ const limit = clampInt(query.limit, { def: 20, min: 1, max: 100 });
111
+ const offset = clampInt(query.offset, { def: 0, min: 0 });
112
+ const { runs, total } = listRunsForCronoton(id, { limit, offset }, { db: ctx.db });
113
+ return json(200, { ok: true, runs, total, limit, offset });
114
+ });
115
+ }
116
+ /**
117
+ * Strip `signers` from a leg's stored `definition_json` before it's exposed
118
+ * through the READ tier (not CONFIRM) — a leg's `signers` array can carry a
119
+ * literal Pact CAPABILITY line baked with a real account identifier and a
120
+ * live-balance-derived amount (`stoa-wrap.ts`/`stoa-unwrap.ts`'s own
121
+ * `coin.TRANSFER` capability construction), which is exactly the category of
122
+ * data this codebase otherwise consistently withholds from a weaker-than-
123
+ * confirm gate: `handlers/steps.ts`'s own CONFIRM-gated standalone-fire
124
+ * preview already omits `signers` from its response; `store/fires.ts`'s
125
+ * `listFires` column-allowlists its SELECT and never returns a definition/
126
+ * signer field at all; `store/public.ts`'s `toPublicCronotonView` explicitly
127
+ * documents that `signers_json`/`gas_payer_json` "can never leak through
128
+ * it." `pactCode`/`payload`/`config`/`gasPayer` stay visible — this route's
129
+ * purpose is genuine operational visibility into a stuck or failed run
130
+ * (what a leg DOES), not the literal capability grant backing it.
131
+ *
132
+ * Fails closed, not open: a `definition_json` that doesn't even parse as
133
+ * JSON (never produced by this codebase's own `JSON.stringify` writers, but
134
+ * defensive regardless) returns `"{}"` rather than the raw, unredacted
135
+ * string — suppressing on a redaction failure, never leaking on one.
136
+ */
137
+ function redactLegRow(leg) {
138
+ let definitionJson = "{}";
139
+ try {
140
+ const parsed = JSON.parse(leg.definition_json);
141
+ const { signers, ...rest } = parsed;
142
+ definitionJson = JSON.stringify(rest);
143
+ }
144
+ catch {
145
+ // Malformed definition_json — fail closed (see doc comment above).
146
+ }
147
+ return { ...leg, definition_json: definitionJson };
148
+ }
149
+ /** `GET /[id]/runs/[runId]/legs` — every leg of one specific run,
150
+ * scoped so a runId belonging to a DIFFERENT cronoton 404s rather
151
+ * than leaking that cronoton's leg history. Unpaginated — a single
152
+ * run's legs are bounded by the gas-ceiling-pack algorithm, never
153
+ * realistically more than a few dozen. Each leg's `definition_json` is
154
+ * redacted via {@link redactLegRow} before it leaves this handler. */
155
+ export async function runLegsHandler(ctx, request) {
156
+ return withRead(ctx, request, async () => {
157
+ const id = request.params?.id ?? "";
158
+ const runId = request.params?.runId ?? "";
159
+ const run = getRun(runId, { db: ctx.db });
160
+ if (!run || run.codex_cronoton_id !== id) {
161
+ return err(404, "not found");
162
+ }
163
+ const legs = listRunLegs(runId, { db: ctx.db }).map(redactLegRow);
164
+ return json(200, { ok: true, legs });
165
+ });
166
+ }
@@ -0,0 +1,3 @@
1
+ import { type Handler } from "./context.js";
2
+ export declare const simulateStep: Handler;
3
+ export declare const fireStep: Handler;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Per-step standalone fire/simulate route: `simulateStep`/`fireStep` address a
3
+ * STORED cronoton's step by index — `POST /cronotons/:id/steps/:index/simulate`
4
+ * and `POST /cronotons/:id/steps/:index/fire` — rather than an arbitrary
5
+ * envelope (`simulateCodexTx`'s own job, `execute.ts`). Both mirror
6
+ * `simulateCodexTx`'s shape: behind {@link withConfirm} (firing standalone Pact
7
+ * code is exactly as sensitive as firing a committed row), HTTP 200 even when
8
+ * the resulting `ok` is false (a chain/build failure rides in the body).
9
+ *
10
+ * **Deliberately bypasses the run/leg-table lifecycle entirely** (design.md
11
+ * §C): no `codex_cronoton_runs` row, no `codex_cronoton_run_legs` rows are
12
+ * ever written here. This is a standalone preview/fire mechanism for testing
13
+ * a step in isolation, not an alternate way to advance a real run — mixing
14
+ * the two would let an ad-hoc standalone fire corrupt a real run's
15
+ * barrier/attempt bookkeeping. A `mode:'planner'` step that fans out to N
16
+ * legs gets ALL N legs simulated/fired here (never just the first).
17
+ */
18
+ import { json, err } from "./http.js";
19
+ import { withConfirm } from "./context.js";
20
+ import { getCodexCronoton, listStepsForCronoton, resolvePlannerFor, stepRowToDefinition, executeCodexTransaction, } from "../server/index.js";
21
+ /** Terminal statuses cannot be fired on demand — same set `execute.ts`'s
22
+ * `executeNow`/`triggerCronoton` already enforce, duplicated locally per
23
+ * this codebase's own per-module-small-constant convention (`parseJson`,
24
+ * `STOA_AUTONOMIC_LIQUIDPOT`, etc.) rather than importing a sibling
25
+ * handler module's private constant. */
26
+ const TERMINAL_STATUSES = new Set(["completed", "error"]);
27
+ /** Resolve the leg(s) a stored step currently produces, via the SAME shared
28
+ * `resolvePlannerFor` helper `runs-driver.ts`'s `handleReplanStep` uses —
29
+ * not a parallel reimplementation, so the two call sites can never drift.
30
+ * Returns `{ok:false}` for a planner-mode step whose `planner_name` has no
31
+ * registered `StepPlanner`, matching `findStep`'s own `{ok,...}` result
32
+ * convention rather than a one-off sentinel. */
33
+ async function resolveStepLegs(step, ctx) {
34
+ if (step.mode === "single") {
35
+ return { ok: true, legs: [stepRowToDefinition(step)] };
36
+ }
37
+ const resolved = resolvePlannerFor(step, ctx);
38
+ if (!resolved)
39
+ return { ok: false };
40
+ const legs = await resolved.planner(step, resolved.plannerCtx);
41
+ return { ok: true, legs };
42
+ }
43
+ /** Shared step lookup: 404 on missing cronoton or missing step-at-index.
44
+ * Returns the parent cronoton row too (not just the step) so `fireStep`
45
+ * can enforce the SAME paused/terminal guard `executeNow`/`triggerCronoton`
46
+ * already enforce before it submits anything real to chain. */
47
+ function findStep(ctx, cronotonId, index) {
48
+ const row = getCodexCronoton(cronotonId, { db: ctx.db });
49
+ if (!row)
50
+ return { ok: false, response: err(404, "not found") };
51
+ const step = listStepsForCronoton(cronotonId, { db: ctx.db }).find((s) => s.step_index === index);
52
+ if (!step)
53
+ return { ok: false, response: err(404, "step not found at that index") };
54
+ return { ok: true, row, step };
55
+ }
56
+ export const simulateStep = (ctx, req) => withConfirm(ctx, req, async () => {
57
+ const id = req.params?.id;
58
+ const index = Number.parseInt(req.params?.index ?? "", 10);
59
+ if (!id || !Number.isInteger(index))
60
+ return err(400, "cronoton id and an integer step index are required");
61
+ const found = findStep(ctx, id, index);
62
+ if (!found.ok)
63
+ return found.response;
64
+ const resolved = await resolveStepLegs(found.step, ctx);
65
+ if (!resolved.ok) {
66
+ return err(404, `planner '${found.step.planner_name}' is not registered`);
67
+ }
68
+ const legs = resolved.legs;
69
+ const results = await Promise.all(legs.map((leg) => executeCodexTransaction(leg, "simulate", { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config })));
70
+ return json(200, {
71
+ ok: results.every((r) => r.ok),
72
+ legs: results.map((r, i) => ({
73
+ ok: r.ok,
74
+ pactCode: legs[i].pactCode,
75
+ payload: legs[i].payload,
76
+ gasUsed: r.gasUsed,
77
+ error: r.error,
78
+ rawResult: r.rawResult,
79
+ })),
80
+ });
81
+ });
82
+ export const fireStep = (ctx, req) => withConfirm(ctx, req, async () => {
83
+ const id = req.params?.id;
84
+ const index = Number.parseInt(req.params?.index ?? "", 10);
85
+ if (!id || !Number.isInteger(index))
86
+ return err(400, "cronoton id and an integer step index are required");
87
+ const found = findStep(ctx, id, index);
88
+ if (!found.ok)
89
+ return found.response;
90
+ // Same guard `executeNow`/`triggerCronoton` enforce before firing
91
+ // anything real — a paused or terminal cronoton must stay un-fireable
92
+ // through EVERY route that can submit its Pact code to chain, not just
93
+ // the ones that go through the run/fire lifecycle. `simulateStep` needs
94
+ // no equivalent guard: it never submits.
95
+ if (found.row.status === "paused")
96
+ return err(400, "cannot execute a paused cronoton");
97
+ if (TERMINAL_STATUSES.has(found.row.status))
98
+ return err(400, "cannot execute a terminal cronoton");
99
+ const resolved = await resolveStepLegs(found.step, ctx);
100
+ if (!resolved.ok) {
101
+ return err(404, `planner '${found.step.planner_name}' is not registered`);
102
+ }
103
+ const legs = resolved.legs;
104
+ const results = await Promise.all(legs.map((leg) => executeCodexTransaction(leg, "fire", { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config })));
105
+ return json(200, {
106
+ ok: results.every((r) => r.ok),
107
+ legs: results.map((r, i) => ({
108
+ ok: r.ok,
109
+ pactCode: legs[i].pactCode,
110
+ requestKey: r.requestKey,
111
+ error: r.error,
112
+ rawResult: r.rawResult,
113
+ })),
114
+ });
115
+ });
@@ -1,8 +1,8 @@
1
- import { L as ListCronotonsQuery, R as ResolversView, C as CommitBody, a as CommitView, E as EditPatch, b as EditView, T as ToggleView, D as DeleteView, c as CancelBatchView, d as ExecuteView, e as RecoverView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, h as RuntimeArgs } from '../context-89YS4xT3.js';
2
- export { U as UseKhronotonResult, u as useKhronoton } from '../context-89YS4xT3.js';
3
- import { C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from '../types-DnFB1Yz-.js';
1
+ import { L as ListCronotonsQuery, R as ResolversView, C as CommitBody, a as CommitView, E as EditPatch, b as EditView, T as ToggleView, D as DeleteView, c as CancelBatchView, d as ExecuteView, e as RecoverView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, h as RuntimeArgs } from '../context-P-rCtBbJ.js';
2
+ export { U as UseKhronotonResult, u as useKhronoton } from '../context-P-rCtBbJ.js';
3
+ import { C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from '../types-uYSglFrJ.js';
4
4
  import 'react';
5
- import '../seams-DUtxDw_U.js';
5
+ import '../seams-Co8Tq4ka.js';
6
6
 
7
7
  /** The `useCronotons()` return shape — the list, its load state, and a refetch. */
8
8
  interface UseCronotonsView {
@@ -1,2 +1,2 @@
1
- export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-LX6T2BDL.js';
2
- export { useKhronoton } from '../chunk-GNQ2IVXA.js';
1
+ export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-7H5TM3CS.js';
2
+ export { useKhronoton } from '../chunk-IAK4UEAA.js';
@@ -1,8 +1,8 @@
1
1
  import { ReactNode } from 'react';
2
- import { H as HandlerRequest, i as HandlerResponse, K as KhronotonProviderProps, j as KhronotonAdapter, k as SignerSource } from '../context-89YS4xT3.js';
3
- export { c as CancelBatchView, l as CodexSignerDescriptor, C as CommitBody, a as CommitView, m as ConfirmGate, n as ConfirmOpts, o as DEFAULT_EXPLORER_BASE, p as DEFAULT_PAGE_SIZE, q as DEFAULT_POLL_CADENCE_MS, D as DeleteView, E as EditPatch, b as EditView, d as ExecuteView, F as FiresQuery, r as FiresView, G as GetBatchView, s as GetCronotonView, t as KhronotonConfig, v as KhronotonSnapshot, L as ListCronotonsQuery, w as ListCronotonsView, e as RecoverView, x as RenderMultiTx, h as RuntimeArgs, y as ServerResolverOption, z as SignersView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, T as ToggleView, U as UseKhronotonResult, A as assertAdapter, B as emptySnapshot, u as useKhronoton } from '../context-89YS4xT3.js';
4
- import { D as Database, C as ChainRuntime, K as KeyResolver, R as ResolveFireMode, O as OnAudit, a as Config } from '../seams-DUtxDw_U.js';
5
- export { a as CodexCronotonFireRow, C as CodexCronotonRow, M as ManualBatchView } from '../types-DnFB1Yz-.js';
2
+ import { H as HandlerRequest, i as HandlerResponse, K as KhronotonProviderProps, j as KhronotonAdapter, k as SignerSource } from '../context-P-rCtBbJ.js';
3
+ export { c as CancelBatchView, l as CodexSignerDescriptor, C as CommitBody, a as CommitView, m as ConfirmGate, n as ConfirmOpts, o as DEFAULT_EXPLORER_BASE, p as DEFAULT_PAGE_SIZE, q as DEFAULT_POLL_CADENCE_MS, D as DeleteView, E as EditPatch, b as EditView, d as ExecuteView, F as FiresQuery, r as FiresView, G as GetBatchView, s as GetCronotonView, t as KhronotonConfig, v as KhronotonSnapshot, L as ListCronotonsQuery, w as ListCronotonsView, e as RecoverView, x as RenderMultiTx, h as RuntimeArgs, y as ServerResolverOption, z as SignersView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, T as ToggleView, U as UseKhronotonResult, A as assertAdapter, B as emptySnapshot, u as useKhronoton } from '../context-P-rCtBbJ.js';
4
+ import { D as Database, C as ChainRuntime, K as KeyResolver, R as ResolveFireMode, O as OnAudit, a as Config } from '../seams-Co8Tq4ka.js';
5
+ export { a as CodexCronotonFireRow, C as CodexCronotonRow, M as ManualBatchView } from '../types-uYSglFrJ.js';
6
6
 
7
7
  /**
8
8
  * The per-request handler context + the injectable auth/confirm seam + the two
@@ -1,5 +1,5 @@
1
- import { assertAdapter, resolveConfig, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, installSchema, defaultOpenAuth, withConfirm, err, recoverFire, json, createManualBatch, manualBatchView, getCodexCronoton, validateRuntimeArgs, rowRuntimeArgKeys, applyRuntimeArgs, rowToDefinition, getServerResolver, resolveServerVars, executeCodexTransaction, CodexCronotonValidationError, deleteCodexCronoton, resumeCodexCronoton, pauseCodexCronoton, editCodexCronoton, commitCodexCronoton, withRead, listFires, listCodexCronotons, getActiveManualBatchForCronoton, cancelManualBatch, listServerResolvers, defaultSignerSource, fireByServerResolver, computeDefinitionFingerprint, recordFire, applyTerminalIntent } from '../chunk-GNQ2IVXA.js';
2
- export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-GNQ2IVXA.js';
1
+ import { assertAdapter, resolveConfig, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, installSchema, defaultOpenAuth, withConfirm, err, recoverFire, json, createManualBatch, manualBatchView, getCodexCronoton, validateRuntimeArgs, rowRuntimeArgKeys, applyRuntimeArgs, rowToDefinition, listStepsForCronoton, createRun, defaultOnAudit, driveRunOnce, getRun, RunAlreadyInFlightError, getServerResolver, resolveServerVars, executeCodexTransaction, CodexCronotonValidationError, deleteCodexCronoton, resumeCodexCronoton, pauseCodexCronoton, editCodexCronoton, commitCodexCronoton, withRead, listFires, listCodexCronotons, getActiveManualBatchForCronoton, cancelManualBatch, listServerResolvers, defaultSignerSource, fireByServerResolver, computeDefinitionFingerprint, recordFire, applyTerminalIntent } from '../chunk-IAK4UEAA.js';
2
+ export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-IAK4UEAA.js';
3
3
  import { useRef, useState, useEffect } from 'react';
4
4
  import { jsx } from 'react/jsx-runtime';
5
5
 
@@ -467,6 +467,37 @@ var executeNow = (ctx, req) => withConfirm(ctx, req, async () => {
467
467
  if (TERMINAL_STATUSES.has(row.status)) {
468
468
  return err(400, "cannot execute a terminal cronoton");
469
469
  }
470
+ const steps = listStepsForCronoton(row.id, { db: ctx.db });
471
+ if (steps.length > 0) {
472
+ try {
473
+ const runId = createRun(
474
+ { codexCronotonId: row.id, stepCount: steps.length },
475
+ { db: ctx.db }
476
+ );
477
+ const driverCtx = {
478
+ db: ctx.db,
479
+ runtime: ctx.runtime,
480
+ resolver: ctx.resolver,
481
+ config: ctx.config,
482
+ onAudit: ctx.onAudit ?? defaultOnAudit
483
+ };
484
+ await driveRunOnce(runId, /* @__PURE__ */ new Date(), driverCtx);
485
+ await ctx.onAudit?.({
486
+ action: "codex_cronoton.run_started",
487
+ result: "success",
488
+ targetKind: "codex_cronoton",
489
+ targetId: row.id,
490
+ detail: { codexCronotonId: row.id, runId, stepCount: steps.length, actor: "ancient" }
491
+ });
492
+ const run = getRun(runId, { db: ctx.db });
493
+ return json(200, { ok: true, runId, status: run?.status ?? null });
494
+ } catch (e) {
495
+ if (e instanceof RunAlreadyInFlightError) {
496
+ return err(409, "a run is already in flight for this cronoton");
497
+ }
498
+ throw e;
499
+ }
500
+ }
470
501
  const resolverName = row.server_resolver ?? void 0;
471
502
  if (resolverName && getServerResolver(resolverName)?.kind === "multi-tx") {
472
503
  return json(202, { ok: true, queued: true });
@@ -117,6 +117,28 @@ 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
  }>;
@@ -271,6 +293,8 @@ interface Config {
271
293
  max: number;
272
294
  intervalSeconds: number;
273
295
  };
296
+ runStepDeadlineMs?: number;
297
+ maxReplanAttempts?: number;
274
298
  }
275
299
 
276
300
  export type { ChainRuntime as C, Database as D, KeyResolver as K, OnAudit as O, ResolveFireMode as R, Config as a, DbDep as b };