@ancientpantheon/khronoton-core 0.13.0 → 0.15.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.
- package/CHANGELOG.md +31 -0
- package/README.md +8 -0
- package/dist/{chunk-IAK4UEAA.js → chunk-24THBKR7.js} +188 -28
- package/dist/{chunk-7H5TM3CS.js → chunk-VPVEIDNN.js} +1 -1
- package/dist/{context-P-rCtBbJ.d.ts → context-ec4m0UBZ.d.ts} +1 -1
- package/dist/handlers/execute.js +28 -41
- package/dist/handlers/steps.js +51 -14
- package/dist/hooks/index.d.ts +3 -3
- package/dist/hooks/index.js +2 -2
- package/dist/provider/index.d.ts +3 -3
- package/dist/provider/index.js +93 -45
- package/dist/server/fire-and-record.d.ts +47 -0
- package/dist/server/fire-and-record.js +85 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +9 -0
- package/dist/server/planners/registry.d.ts +41 -3
- package/dist/server/planners/registry.js +49 -5
- package/dist/server/planners/stoa-wrap.d.ts +11 -7
- package/dist/server/planners/stoa-wrap.js +61 -33
- package/dist/server/pure/yields.d.ts +57 -0
- package/dist/server/pure/yields.js +101 -0
- package/dist/server/resolvers.js +7 -1
- package/dist/server/runs-driver.js +89 -18
- package/dist/server/schema.d.ts +4 -3
- package/dist/server/schema.js +26 -1
- package/dist/server/single-tx.d.ts +44 -0
- package/dist/server/single-tx.js +143 -0
- package/dist/server/store/cronoton.d.ts +21 -0
- package/dist/server/store/cronoton.js +72 -5
- package/dist/server/store/index.d.ts +2 -1
- package/dist/server/store/index.js +3 -1
- package/dist/server/store/steps.d.ts +12 -0
- package/dist/server/store/steps.js +26 -3
- package/dist/server/store/yields.d.ts +46 -0
- package/dist/server/store/yields.js +73 -0
- package/dist/server/tick.js +38 -0
- package/dist/server/types.d.ts +31 -0
- package/dist/{types-uYSglFrJ.d.ts → types-DH7Ym8FQ.d.ts} +17 -0
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,37 @@ All notable changes to `@ancientpantheon/khronoton-core`.
|
|
|
4
4
|
|
|
5
5
|
The engine's pre-extraction history lives in the AncientHoldings hub, whose inline scheduler ("Cronoton") this package extracts and generalises.
|
|
6
6
|
|
|
7
|
+
## 0.15.0 — 2026-11-21
|
|
8
|
+
|
|
9
|
+
**MINOR — a chained cronoton can now optionally try a single-transaction variant first, falling back to the proven step-by-step chain only when that one transaction is specifically too expensive to mine.**
|
|
10
|
+
|
|
11
|
+
Every chained cronoton (0.13.0) always drove its work as N separate transactions, one per step, even for a chain cheap enough to easily fit in a single transaction with room to spare. There was no way to attempt a cheaper, faster single-transaction execution and fall back to the step-by-step chain only when genuinely needed. This release adds that as a new, opt-in decision — never mandatory, off by default — ahead of the existing chained/plain branch, implementing the `'custom'` mode (the sibling Default-mode topic, auto-composing the single-tx Pact code from the chain's own steps, stays explicitly deferred).
|
|
12
|
+
|
|
13
|
+
- **Two new `codex_cronotons` columns.** `try_single_tx_first INTEGER NOT NULL DEFAULT 0` and `single_tx_mode TEXT CHECK (single_tx_mode IN ('custom', 'default'))`, validated against the full allowed set (not just the literal `'default'`) at both commit and edit time — a raw out-of-enum string must never reach the SQL `CHECK` uncaught. When on, the row's own existing top-level `pact_code`/`payload_json`/`config_json`/`gas_payer_json`/`signers_json` fields — already required, `NOT NULL`, and confirmed dead-weight placeholder data for any row that also has `codex_cronoton_steps` rows — are reinterpreted as the single-tx variant the operator hand-composes directly, exactly as for a plain one-shot cronoton. `editCodexCronoton` rejects enabling the flag on a zero-step row (nothing to fall back to) and now also requires `singleTxMode: 'custom'` to be set (or already persisted) whenever the flag is on, so the mode selector is never left meaningfully unset.
|
|
14
|
+
- **The decision, mirroring `ouronet.aqp-evict`'s own established try-then-fan-out precedent one level up.** At the exact point a chained row's work would normally begin (`tick.ts`'s due-row branch, `handlers/execute.ts`'s `executeNow` manual-trigger branch), a new shared `attemptSingleTxFirst` helper (`server/single-tx.ts`) simulates the row's own definition first: fits under the gas ceiling → fires it via the exact same plain one-shot path (`fireByServerResolver`/`recordFire`) a non-chained cronoton already uses, recorded as an ordinary fire row, the chained run/step machinery never touched; refused specifically for being too expensive (the executor's existing numeric-`gasUsed`-on-`{ok:false}` refuse-unmineable signal) → falls through to the existing chained-run path unchanged; any other simulate failure → propagates as a real error, never silently treated as "fall back to the chain"; fires but genuinely reverts for real → recorded as a failed fire, no chain retry in the same pass (Pact transactions are atomic — no partial state to recover from). A row bound to a registered **multi-tx** server resolver is refused by this decision before ever simulating or firing — inline-dispatching a multi-tx orchestrator would bypass `executeNow`'s own documented "never fire multi-tx inline" invariant (202-queued) on both the scheduler tick and the manual-trigger endpoint.
|
|
15
|
+
- **Shared fire-record-finalize-audit sequence, not a third hand-copy.** `handlers/execute.ts`'s own on-demand fire path and the new `attemptSingleTxFirst` both delegate to a new shared `server/fire-and-record.ts` (`recordAndFinalizeFire`/`fireAndRecord`) rather than each independently re-deriving the fire→record→finalize→audit sequence — split into two layers specifically because the single-tx path needs to inspect the `FireResult` (via the new `FireResult.postponed` field, set only by `resolvers.ts`'s own never-submitted-to-chain paths) before deciding whether to record anything at all, distinguishing a genuinely-never-submitted postpone from a real on-chain fire failure that would otherwise permanently orphan a one-time row. Both `tick.ts` and `handlers/execute.ts` thread an `actor` (`"scheduler"`/`"ancient"`) into the resulting `codex_cronoton.single_tx.fire`/`.fire_failed` audit event, matching every other fire path's own attribution.
|
|
16
|
+
- **The manual-batch "Execute Now ×N" rail now stops rather than bypasses the new guard.** `processDueManualBatchesOnce` fires a chained cronoton's raw top-level definition with no steps/single-tx awareness of its own; for a `try_single_tx_first=1` row this would have bypassed the gas-ceiling simulate-then-decide check entirely now that those fields are live operator code, not inert placeholder data. The batch is now auto-cancelled (mirroring the existing parent-inactive cancellation) rather than firing unchecked.
|
|
17
|
+
- Both existing gas-payer types (`type: "codex"` self-paid, `type: "gas-station"` sponsored) work for the single-tx attempt via the exact same executor/signer-planning path a plain one-shot cronoton already uses — no new gas-payer-specific code needed.
|
|
18
|
+
|
|
19
|
+
Reviewed via nectar across 6 rounds (correctness/conventions/security/tests lenses each round, adversarial validation throughout): **10 CONFIRMED findings fixed, 0 REFUTED, 1 left open as a harmless STYLISTIC nit** (an escaped-quote string literal instead of this file's usual backtick-template idiom). Standout findings: a **HIGH** in round 1 caught a server-resolver's "postponed, never submitted" fire result as structurally indistinguishable from a genuine on-chain failure, risking a permanently orphaned one-time row (fixed via the new `FireResult.postponed` field); a **HIGH** in round 2 caught `attemptSingleTxFirst` able to inline-dispatch a registered multi-tx orchestrator, bypassing `executeNow`'s own 202-queued invariant (fixed with an explicit kind guard); a **MEDIUM**-severity correctness finding in round 3 (initially flagged HIGH, narrowed on adversarial validation to the genuinely new risk only) caught the manual-batch rail's gas-ceiling bypass described above; a **MEDIUM** security finding in the same round caught single-tx fires carrying no `actor` attribution in their audit events, unlike every other fire path. Two findings were duplication/test-coverage gaps closed by extracting the shared `fire-and-record.ts` module and adding its own direct test file. Full history in `docs/work/khronoton-single-tx-custom/review.md`. Behavioral verification drove the real compiled `dist/` artifact through all three core decision-tree branches (off/fits/gas-refused) against a real in-memory DB and fake chain client, confirming each against design.md's acceptance criteria. Full design/plan/review in `docs/work/khronoton-single-tx-custom/` (Topic 1 of `docs/work/khronoton-single-tx-chain/design.md` — the sibling Default-mode topic stays deferred).
|
|
20
|
+
|
|
21
|
+
**1356 specs pass.**
|
|
22
|
+
|
|
23
|
+
## 0.14.0 — 2026-11-20
|
|
24
|
+
|
|
25
|
+
**MINOR — step-to-step yield carry: a chained run's steps can now hand a specific computed value forward to a later step, closing the one real gap 0.13.0's chained-runs feature shipped with.**
|
|
26
|
+
|
|
27
|
+
0.13.0 let each step either use a fixed baked-in value or re-probe live chain state at its own fire time — which works for a self-correcting planner like `ouronet.stoa-wrap` (it just wraps whatever balance currently sits in an account) but not for a drain → wrap → inject pipeline where wrap and inject both need the *exact* amount the previous step actually moved, since the intermediate/target accounts can independently hold their own pre-existing balance. This release adds a generic, flat, named-yield pool per run: any step can produce a value under a name it declares itself (`yield_as`), and any later step references it with a structured `{"$yield": "<name>"}` placeholder written directly into its own stored `payload_json`/`planner_params_json`, resolved transparently before that step ever executes.
|
|
28
|
+
|
|
29
|
+
- **Storage.** New `codex_cronoton_run_yields(run_id, name, value_json, step_index, created_at)` table, unique on `(run_id, name)`, upserted on every write — a replanned step's freshest computed value always wins. New nullable `codex_cronoton_steps.yield_as` column, applying uniformly to both step modes: the step row itself always owns the yield's name, never the planner.
|
|
30
|
+
- **Producing a yield.** A `mode:'planner'` step's `StepPlanner` can now optionally return `{ legs, yield }` instead of a bare leg array (the old bare-array return stays valid forever — none of the 5 existing built-ins were forced to change). A `mode:'single'` step with `yield_as` set captures the real on-chain return value the moment its leg confirms — that value already flowed through the confirm path, previously just discarded. `ouronet.stoa-wrap` is the one built-in planner that changed: it gained an `amountOverride` param (skipping its live balance probe when given, including a zero-amount short-circuit matching the probed path's own) and now always reports back the exact amount it used.
|
|
31
|
+
- **Consuming a yield.** A `{"$yield": "<name>"}` placeholder is resolved recursively against the run's pool right before a step executes — for planner-mode steps this means **zero code changes to any planner, built-in or custom**: `ouronet.aqp-inject` still just parses `planner_params_json` normally and sees an already-resolved decimal string. An unresolvable reference throws a named `YieldNotFoundError` (now a public export) rather than silently resolving to `null`.
|
|
32
|
+
- Standalone per-step fire/simulate (`handlers/steps.ts`) always resolves against an empty pool — there's no run to source a yield from there, so a `$yield` reference fails loudly instead of reaching the chain as a literal placeholder.
|
|
33
|
+
|
|
34
|
+
Reviewed via nectar across 4 rounds (correctness/conventions/security/tests/performance lenses each round, adversarial validation throughout): **12 CONFIRMED findings fixed, 0 REFUTED, 2 validator-adjusted severity downgrades.** Two HIGH findings in round 1: a confirmed single-mode leg with an `undefined` on-chain result crashed yield capture *after* the leg was already marked confirmed, permanently stranding an otherwise-successful run; and the yield pool's `name in pool` membership check walked the prototype chain, silently resolving a never-produced name like `"toString"`/`"constructor"` to an inherited `Object.prototype` member instead of throwing (plus a `"__proto__"`-named yield risking prototype reassignment) — both fixed (`undefined` → `null` normalization; `Object.create(null)` pools plus `hasOwnProperty`-based lookups). Round 2's terminal pass caught that the identical prototype-chain gap existed in the sibling `StepPlanner` registry, unfixed; round 3's pass then caught that two concurrent `driveRunOnce` callers racing a genuine re-plan could both bump the run's retry-attempt counter even though only one's legs ever land, silently burning through `maxReplanAttempts` roughly twice as fast as configured — both fixed following the same ordering principle (second-order writes only commit after the leg insert that proves this caller actually won the race). Round 4's terminal pass came back fully clean. Behavioral verification drove the real `ouronet.stoa-wrap` → `ouronet.aqp-inject` chain against the actual compiled `dist/` artifact (not source, not a fully mocked DB): the run reached `succeeded` with inject's amount exactly matching wrap's actual used amount, never re-probed or statically pre-set. Full history in `docs/work/khronoton-step-yield-carry/`.
|
|
35
|
+
|
|
36
|
+
**1317 specs pass.**
|
|
37
|
+
|
|
7
38
|
## 0.13.0 — 2026-11-20
|
|
8
39
|
|
|
9
40
|
**MINOR — chained multi-step cronoton runs: a cronoton can now express a sequential "drain→wrap→inject→evict"-shaped multi-action workflow as one unit, with a non-blocking driver, five registered built-in planners, and new per-run/per-step observability and standalone-fire routes.**
|
package/README.md
CHANGED
|
@@ -6,6 +6,10 @@ Khronoton is the "When do I act?" Constructor of the Pantheon architecture — t
|
|
|
6
6
|
|
|
7
7
|
## Status
|
|
8
8
|
|
|
9
|
+
**`0.15.0` on public npmjs** — **MINOR.** Released 2026-11-21. A chained cronoton can now optionally try a single-transaction variant first, falling back to the proven step-by-step chain only when that one transaction is specifically too expensive to mine — never mandatory, off by default. New `try_single_tx_first`/`single_tx_mode` columns on `codex_cronotons`; when on, the row's own existing top-level `pact_code`/payload/config/gas-payer/signers fields (already-required, previously-dead-weight placeholder data for any row with steps) are reinterpreted as the operator's own hand-composed single-tx Pact code. A new shared `attemptSingleTxFirst` decision (`server/single-tx.ts`), consulted ahead of the existing chained/plain branch in both the scheduler tick and `executeNow`, mirrors `ouronet.aqp-evict`'s own established try-then-fan-out precedent one level up: fits under the gas ceiling → fires via the exact same plain one-shot path; refused specifically for being too expensive → falls through to the existing chain unchanged; any other simulate failure → a real error, never a silent fallback; fires but genuinely reverts → recorded as a failed fire, no chain retry (Pact transactions are atomic). A new shared `fire-and-record.ts` closes a hand-copy-triplication gap between `executeNow` and the new path. Reviewed via nectar across 6 rounds: a **HIGH** caught a server-resolver "postponed" result risking a permanently orphaned one-time row; a second **HIGH** caught the new decision able to inline-dispatch a registered multi-tx orchestrator, bypassing `executeNow`'s own 202-queued invariant; a **MEDIUM** caught the manual-batch "Execute Now ×N" rail bypassing the new gas-ceiling guard entirely for a single-tx-first row (now auto-cancelled instead); a second **MEDIUM** caught single-tx fires missing the `actor` audit attribution every other fire path records. **10 CONFIRMED findings fixed, 0 REFUTED.** **1356 specs pass.**
|
|
10
|
+
|
|
11
|
+
**`0.14.0` on public npmjs** — **MINOR.** Released 2026-11-20. Chained runs (0.13.0) can now carry a specific computed value from one step to a later one — a generic, flat, named-yield pool per run. Any step declares the name it produces a value under (`yield_as`); a `mode:'planner'` step's planner optionally returns `{ legs, yield }` instead of a bare array (zero changes forced on any existing planner); a `mode:'single'` step captures its confirmed leg's real on-chain return value. A later step references a prior yield with `{"$yield": "<name>"}` written directly into its own stored payload/params, resolved transparently before it executes — for planner-mode steps this means **zero code changes to any planner, built-in or custom** to consume a carried value. `ouronet.stoa-wrap` gained an `amountOverride` param to actually produce a usable yield. Reviewed via nectar across 4 rounds: two HIGH findings in round 1 (a confirmed leg with no on-chain `data` crashed yield capture after already being marked confirmed; the yield pool's `name in pool` check silently resolved a never-produced name like `"constructor"` to an inherited `Object.prototype` member instead of throwing) were fixed, and the identical prototype-chain gap was then found and fixed in the sibling `StepPlanner` registry (round 2) and a concurrent-attempt-double-bump race was found and fixed in the core driver (round 3), before round 4 came back fully clean. Behavioral verification drove the real `ouronet.stoa-wrap` → `ouronet.aqp-inject` chain against the actual compiled artifact, confirming inject's amount exactly matched wrap's actual used amount. **1317 specs pass.**
|
|
12
|
+
|
|
9
13
|
**`0.13.0` on public npmjs** — **MINOR.** Released 2026-11-20. A cronoton can now express a chained, multi-step workflow ("drain→wrap→inject→evict"-shaped) as one schedulable unit instead of being limited to a single one-shot transaction. Three new tables (`codex_cronoton_steps`/`codex_cronoton_runs`/`codex_cronoton_run_legs`) back a non-blocking driver (`runs-driver.ts`'s `driveRunOnce`/`advanceInFlightRunsOnce`, a third pass in `startKhronotonLoop`) built on a new non-blocking `"submit"` executor mode and a pure decision core (`pure/run-advance.ts`'s `advanceRun`) that decides submit/poll/advance/re-plan/fail purely from a run's and its legs' current state. A new `StepPlanner` registry ships five built-in planners ported from OuronetUI's real transaction-construction logic — `ouronet.aqp-evict`, `ouronet.aqp-inject`, `ouronet.aqp-unstall` (backed by a newly-ported generic gas-probe-and-pack algorithm, `pure/split-plan.ts`), `ouronet.stoa-wrap`, and `ouronet.stoa-unwrap` — every one of which builds Pact code with zero interpolated values in the executed code itself. New `executeNow` chained-row support, a widened `adaptMultiTxSummary`, a standalone per-step `POST .../steps/:index/{simulate,fire}` route, and new `GET /[id]/runs`/`GET /[id]/runs/[runId]/legs` read routes round out the observability surface. A plain one-shot cronoton's behavior is completely unchanged. Reviewed via nectar across all seven phases of this feature plus one additional cross-phase round after they shipped (33 rounds total, 73 CONFIRMED findings): four **CRITICAL** findings surfaced across the arc — a missing Pact module-namespace prefix and a Pact-code-injection vulnerability (both caught before ever shipping, in round 1 of the `ouronet.aqp-evict` planner's own review), a run-gets-permanently-stuck bug found only in a follow-up cross-phase pass (a planner throw on a run's first drive left it stranded forever with no recovery path), and a regression in that very fix (an overly broad catch that turned a benign concurrency race into a false permanent failure), caught by re-reviewing the fix itself. Multiple **HIGH** findings were also found and fixed, including a standalone-fire route that could bypass the paused/terminal guard every other fire route enforces, a genuine concurrency race in the core driver (fixed with a new claim-before-submit mechanism), and a read-tier handler leaking real transaction amounts and account identifiers. **1265 specs pass.**
|
|
10
14
|
|
|
11
15
|
**`0.12.0` on public npmjs** — **MINOR.** Released 2026-11-11. Any codex-cronoton can now opt into a public, unauthenticated, token-gated observability view of its schedule, health, and fire history — the concrete driver being a UI that wants to embed a cronoton's next-fire time and recent executions on a public-facing page, without exposing the authenticated admin surface. New `public_token`/`public_observable` columns (added via a new `ensureColumn` upgrade helper — the first time `installSchema` has needed to add a column to an already-provisioned database, not just a fresh install); a new `server/store/public.ts` surface (`setPublicObservable`, `getCodexCronotonByPublicToken`, `getCronotonFireCounts`, `deriveCronotonHealth`, `toPublicCronotonView`); and a new `handlers/public.ts` `publicCronotonHandler` that deliberately never calls `ctx.auth` — gated purely on token validity plus the observable flag, with an unknown token and a known-but-non-observable token returning the identical 404. The sanitizing projector never includes `pact_code`, `payload_json`, `signers_json`, `gas_payer_json`, `server_resolver`, `created_by`, `config_json`, raw fire error text, or the internal row `id` — the public token is the only public identifier. **1027 specs pass.**
|
|
@@ -358,6 +362,10 @@ npm install @ancientpantheon/khronoton-core
|
|
|
358
362
|
|
|
359
363
|
## Version history
|
|
360
364
|
|
|
365
|
+
**v0.15.0** — Single-tx-first Custom mode for chained cronotons. Every chained cronoton (0.13.0) always drove its work as N separate transactions, one per step, even for a chain cheap enough to easily fit in a single transaction. This release adds an opt-in, off-by-default decision to try a single-transaction variant first, falling back to the proven step-by-step chain only when that one transaction is specifically refused for being too expensive to mine — implementing only the `'custom'` branch (the sibling Default-mode topic, auto-composing the single-tx Pact code from the chain's own steps, stays explicitly deferred, blocked on a confirmed `TS01-C1.DPTF|C_Transmute` signature and a clean gasless-patron account identifier). **Schema.** Two new `codex_cronotons` columns: `try_single_tx_first INTEGER NOT NULL DEFAULT 0` and `single_tx_mode TEXT CHECK (single_tx_mode IN ('custom', 'default'))`, validated against the FULL allowed set (not just the literal `'default'`) at both commit and edit time in `store/cronoton.ts` — a raw out-of-enum string, possible at runtime since TypeScript's enum type is erased, must never reach the SQL `CHECK` uncaught. `editCodexCronoton` rejects enabling the flag on a zero-step row (nothing for it to ever fall back to) and — after a review finding caught the gap — now also requires the resolved `single_tx_mode` to be `'custom'` whenever the flag will be on, whether freshly patched or inherited from a prior edit, so the mode selector is never left meaningfully unset while the flag is live. When on, the row's own existing top-level `pact_code`/`payload_json`/`config_json`/`gas_payer_json`/`signers_json` fields (already required, `NOT NULL`, confirmed dead-weight placeholder data for any row that also has `codex_cronoton_steps` rows, since `tick.ts`'s chained-vs-plain branch never touches them once ≥1 step exists) are reinterpreted as the single-tx variant: the operator writes their own composed Pact code there directly, exactly as for a plain one-shot cronoton. **The decision (`server/single-tx.ts`'s new `attemptSingleTxFirst`), mirroring `ouronet.aqp-evict`'s own established try-then-fan-out precedent one level up.** Consulted at the exact point a chained row's work would normally begin — `tick.ts`'s due-row branch and `handlers/execute.ts`'s `executeNow` manual-trigger branch, both of which already decide "chained vs plain" on `steps.length > 0` — ahead of that existing decision, only when `try_single_tx_first` is on: (1) simulate the row's own definition via the existing `executeCodexTransaction(..., "simulate", ...)` seam; (2) fits under the gas ceiling → fire it via the exact same plain one-shot path (`fireByServerResolver`/`recordFire`) a non-chained cronoton already uses — the chained run/step machinery is never touched, the fire is recorded as an ordinary `codex_cronoton_fires` row; (3) refused specifically for being too expensive (a numeric `gasUsed` on an `{ok:false}` simulate result — the executor's own existing refuse-unmineable signal, the same one `ouronet.aqp-evict` already reads to decide "fan out instead") → fall through to the existing chained-run path, completely unchanged; (4) any other simulate failure (a genuine Pact error, unrelated to gas) → propagate as a real error, never silently treated as "fall back to the chain," mirroring `evict`'s own established discipline for the identical decision shape one level down; (5) the single-tx variant fires and then genuinely fails for real (a true on-chain revert, not a gas issue) → recorded as a failed fire exactly as a plain one-shot cronoton's failure is today, no fallback to the chain at this point — Pact transactions are atomic, so there's no partial state to recover from, and the underlying failure is a business-logic one the chained path would very likely hit too. A row bound to a registered **multi-tx** server resolver is refused by this decision before ever simulating or firing at all — `fireByServerResolver` awaits a multi-tx orchestrator's entire run inline, which is exactly what `executeNow`'s own plain-fire branch already refuses to do for every other row (202-queued, never fired inline); without this guard a `try_single_tx_first=1` row bound to one would have bypassed that invariant on both the scheduler tick and the manual-trigger endpoint, and lost the multi-tx `txKeys` breakdown besides. Both existing gas-payer types (`type: "codex"` self-paid, `type: "gas-station"` sponsored) work for the single-tx attempt via the identical executor/signer-planning path a plain one-shot cronoton already uses — no new gas-payer-specific code needed; the operator's own hand-written Pact code is responsible for satisfying whatever the gas station's capability actually requires. **A shared fire-record-finalize-audit sequence, not a third hand-copy.** `handlers/execute.ts`'s own on-demand fire path and `attemptSingleTxFirst` both delegate to a new shared `server/fire-and-record.ts` (`recordAndFinalizeFire`/`fireAndRecord`) — split into two layers specifically because the single-tx path needs to inspect the resulting `FireResult` (via a new `FireResult.postponed` field, set only by `resolvers.ts`'s own `postponed(...)` helper on its never-submitted-to-chain paths) *before* deciding whether to record anything at all, distinguishing a genuinely-never-submitted server-resolver postpone from a real on-chain fire failure — conflating the two would have permanently orphaned a one-time row (its `next_fire_at` already cleared by the claim, with no code path left to ever reselect it). Both `tick.ts` and `handlers/execute.ts` thread an `actor` (`"scheduler"`/`"ancient"` respectively) through to the resulting `codex_cronoton.single_tx.fire`/`.fire_failed` audit event, matching every other fire path's own attribution — a gap a review finding caught the new path missing entirely. **The manual-batch "Execute Now ×N" rail (`tick.ts`'s `processDueManualBatchesOnce`) now stops rather than bypasses the new guard.** That rail fires a chained cronoton's raw top-level definition directly with no steps/single-tx awareness of its own; for a `try_single_tx_first=1` row this would have bypassed the gas-ceiling simulate-then-decide check entirely now that those top-level fields are live operator-authored code rather than inert placeholder data — a genuinely new risk this topic's own reinterpretation of those fields introduces (the broader, pre-existing "manual batch ignores `codex_cronoton_steps` entirely" gap for an ORDINARY chained row predates this topic and is tracked separately). Fixed by auto-cancelling the batch, mirroring the rail's existing parent-inactive cancellation, rather than firing unchecked. Reviewed via nectar across 6 rounds (correctness/conventions/security/tests lenses each round, adversarial validation throughout): **10 CONFIRMED findings fixed, 0 REFUTED, 1 left open as a harmless STYLISTIC nit** (an escaped-quote string literal in one new error message instead of this file's usual backtick-template idiom for an embedded quote — zero functional impact, left for a future pass). Round 1 found and fixed a HIGH (the server-resolver postpone misclassification above) plus two MEDIUMs (the `fireAndRecord` triplication; the `singleTxMode` enum-validation gap checking only the literal `'default'`). Round 2's terminal pass caught the second HIGH (the multi-tx inline-dispatch bypass above) plus a MEDIUM-downgraded-to-LOW `SingleTxAttemptCtx`/`FireAndRecordCtx` duplication and two LOWs (`fire-and-record.ts` missing its own test file; a duplicated fire-dispatch options object plus a stale code comment). Round 3's terminal pass caught the manual-batch gas-ceiling bypass (initially flagged HIGH, narrowed on adversarial validation to MEDIUM once scoped to only the genuinely-new risk) plus a LOW (a stale hand-rebuilt ctx object in `execute.ts` instead of passing `ctx` straight through) and a MEDIUM security finding (the missing `actor` audit attribution). Round 4's terminal pass caught a MEDIUM-downgraded-to-LOW data-hygiene gap (enabling `trySingleTxFirst` without requiring `single_tx_mode` to resolve to `'custom'`, harmless today since no other value is reachable, but a trap once the deferred Default-mode topic needs to branch on it). Round 5's terminal pass caught the STYLISTIC nit above plus a genuine MEDIUM test-coverage gap (the new mode-inheritance guard's *success* path — a later edit flipping the flag on alone, relying on a previously-persisted `'custom'` value — was only ever exercised via its rejection branch, never its success branch). Round 6's terminal pass came back fully clean across all four lenses. Behavioral verification drove the real compiled `dist/` artifact — `@ancientpantheon/khronoton-core/server` resolved through the published package's own exports map, not source — through all three core decision-tree branches (`try_single_tx_first` off: byte-identical, exactly one preflight simulate call; fits: plain one-shot fire, zero run rows; gas-refused: falls through to a real driven chain reaching a real run row) against a real in-memory DB and a fake chain client at the system boundary, confirming each against design.md's acceptance criteria. Full design/plan/review in `docs/work/khronoton-single-tx-custom/` (Topic 1 of `docs/work/khronoton-single-tx-chain/design.md`). **1356 specs pass.**
|
|
366
|
+
|
|
367
|
+
**v0.14.0** — Step-to-step yield carry. 0.13.0's chained runs let each step either use a fixed baked-in value or re-probe live chain state at its own fire time — self-correcting planners like `ouronet.stoa-wrap` worked fine with this (wrap whatever balance currently sits in an account), but a drain→wrap→inject pipeline needs wrap and inject to both use the *exact* amount the previous step actually moved, since intermediate/target accounts can independently hold their own pre-existing balance. This release adds a generic, flat, named-yield pool per run, closing that gap without requiring every planner to become yield-aware. **Storage.** New `codex_cronoton_run_yields(run_id, name, value_json, step_index, created_at)` table, `UNIQUE(run_id, name)`, upserted via `ON CONFLICT ... DO UPDATE` (`store/yields.ts`'s `upsertYield`/`getYieldPool`) — a replanned step's freshest value always wins, no separate invalidation needed since nothing downstream of an unconfirmed step runs yet. New nullable `codex_cronoton_steps.yield_as` column, applying uniformly to both step modes — the step row itself always owns the yield's name, never the planner (avoiding a name-collision risk if a chain ever ran two wrap-shaped steps). **Producing a yield.** `StepPlanner`'s return type widened to `PlannedLeg[] | { legs: PlannedLeg[]; yield?: unknown }` (`planners/registry.ts`) — the bare-array return stays valid forever, so none of `evict`/`inject`/`unstall`/`stoa-unwrap` needed source changes. A `mode:'single'` step with `yield_as` set captures the confirmed leg's real on-chain return value (`ListenResult.result.data`, already flowing through `runs-driver.ts`'s `handlePoll` confirm loop, previously just discarded) under that name. `ouronet.stoa-wrap` is the one built-in that changed: a new optional `amountOverride` param skips its live `coin.get-balance` probe entirely when given (with its own zero-amount short-circuit, mirroring the probed path's `data === 0` → `[]`), and the planner now always returns `{ legs, yield: amount }` — the exact amount it used, whichever path produced it — instead of a bare array. **Consuming a yield.** A new pure helper (`pure/yields.ts`'s `resolveYieldRefs`) recursively walks a step's parsed `payload_json`/`planner_params_json`, substituting every `{"$yield": "<name>"}` placeholder against the run's pool. For `mode:'planner'` steps this resolution happens inside the widened `resolvePlannerFor` (now `resolvePlannerFor(step, seams, yieldPool = {})`), producing a shallow-cloned, already-resolved step row before the planner ever runs — `ouronet.aqp-inject` still just does `parseJson(step.planner_params_json, {})` and sees a concrete decimal string, with **zero code changes needed**. For `mode:'single'` steps, a shared `resolveSingleStepPayload` helper (extracted after a review finding caught `runs-driver.ts` and `handlers/steps.ts` each independently re-deriving the identical resolution sequence) does the equivalent for `payload_json`. An unresolvable reference throws `YieldNotFoundError` (a new public export, matching every other typed error this package throws) rather than silently resolving to `null` — propagating through the same `handleReplanStep` catch path `PlannerNotRegisteredError` already uses, terminalizing the run. The standalone per-step fire/simulate route (`handlers/steps.ts`) always resolves against an explicit empty pool — there is no run to source a yield from there, so a `$yield` reference fails loudly (caught and folded into the route's existing discriminated `{ok:false, reason}` result shape) instead of reaching the chain as a literal placeholder object. Reviewed via nectar across 4 rounds (correctness/conventions/security/tests/performance lenses, adversarial validation throughout): **12 CONFIRMED findings, 0 REFUTED, 2 validator-adjusted severity downgrades**. Round 1 found two HIGH findings — `upsertYield` crashing on a confirmed leg's `undefined` on-chain result (`JSON.stringify(undefined)` is not a bindable SQL value), thrown *after* `markLegConfirmed` had already committed, permanently stranding an otherwise-successful run (fixed: normalize `undefined` → `null`); and the yield pool's `name in pool` membership check walking the prototype chain, so a never-produced name like `"toString"`/`"constructor"`/`"__proto__"` silently resolved to an inherited `Object.prototype` member instead of throwing, defeating the feature's own "never silently guess" invariant (fixed: `Object.create(null)` pools in `getYieldPool` plus `Object.prototype.hasOwnProperty.call` checks in `resolveYieldRefs`) — plus two MEDIUMs (a misleading "planner not registered" 404 for a yield-resolution failure on a `mode:'single'` step, whose `planner_name` is always `null`, fixed via a discriminated failure-reason shape; `stoa-wrap`'s `amountOverride` path missing the zero-amount short-circuit the probed path has, fixed) and three LOWs (stale "six tables" doc comments after a 7th table was added; the single-mode resolution duplication now fixed by `resolveSingleStepPayload`; a static step list re-fetched every `driveRunOnce` inner-loop pass, now hoisted once per call). Round 2's terminal pass caught that the identical prototype-chain gap existed, unfixed, in the sibling `StepPlanner` registry (`planners/registry.ts`'s `STEP_PLANNERS`) — fixed the same way — plus a planner returning `{legs: [], yield}` silently discarding that yield because the empty-legs early return in `handleReplanStepInner` happened before the yield-write check (fixed: write the yield in that branch too), and a yield write racing ahead of a concurrent loser's `insertRunLeg` collision (fixed: leg inserts now run before the yield write, so a losing caller never reaches it). Round 3's terminal pass caught the identical ordering bug class one layer up: `bumpRunAttempt`/`touchRunDeadline` also ran before the leg-insert loop, so two concurrent genuine-replan racers could both bump a run's retry-attempt counter even though only one's legs ever land — silently burning through `maxReplanAttempts` roughly twice as fast as configured (fixed: moved after the leg-insert loop, alongside the yield write, so all "second-order" writes for a replan generation only commit for whichever caller actually won the race). Round 4's terminal pass came back fully clean across all 5 lenses, with the correctness lens specifically re-verifying the final `insertRunLeg → bumpRunAttempt/touchRunDeadline → upsertYield` ordering end to end (having been rewritten twice across rounds) against the three dedicated regression tests that now pin it. One further gap was caught only by behavioral verification against the real compiled artifact (not the lens passes): `YieldNotFoundError` had not been added to the package's public `server/index.ts` barrel, breaking the established convention that every custom typed error is public — fixed. Behavioral verification then drove the real registered `ouronet.stoa-wrap` → `ouronet.aqp-inject` chain (with `amountOverride: "77.0"`, `yieldAs: "wrappedAmount"`, and `amount: {"$yield":"wrappedAmount"}` respectively) via `driveRunOnce` against a real in-memory DB with a fake chain client at the system boundary: the run reached `succeeded`, and inject's submitted leg's `payload.amount` was exactly `"77.0"` — the literal value wrap actually used, never independently re-probed or statically pre-set. Full history in `docs/work/khronoton-step-yield-carry/design.md`, `plan.md`, and `review.md`. Released 2026-11-20. **1317 specs pass.**
|
|
368
|
+
|
|
361
369
|
**v0.13.0** — Chained multi-step cronoton runs. A cronoton was always exactly one scheduled Pact transaction; a workflow needing several transactions in sequence — some fanning out into a variable number of legs decided only at fire time — had no way to express itself as a single schedulable unit. This release adds that capability end to end, fully additive, across what was built and reviewed as seven sequential phases plus a follow-up cross-phase review. **Non-blocking submit.** The scheduler's tick awaits a fire's confirmation inline inside a single `running`-boolean-guarded pass (`server/loop.ts`) — fine for one transaction, impossible for a multi-leg chained run (serially awaiting four legs could freeze the entire scheduler for up to twenty minutes). A third `executeCodexTransaction` mode, `"submit"`, builds/signs/preflights/submits and returns without ever calling `listenWithTimeout`; `runFire`'s build-through-submit internals were extracted into a shared `submitTransaction` helper with zero change to `fire`'s own external behavior (its existing test suite runs unmodified as the proof). A new optional `ChainClient.pollRequestKeys(keys, chainId)` seam (implemented in `blockchain/stoachain.ts` over Kadena's batch `/poll`) polls every outstanding request key on a chain in one HTTP call per tick, not one per leg. **Schema.** Three new tables: `codex_cronoton_steps` (a cronoton's static step definitions, `mode: 'single' | 'planner'`, a `CHECK` enforcing exactly one shape is filled), `codex_cronoton_runs` (`status: 'planning' | 'awaiting' | 'advancing' | 'succeeded' | 'failed' | 'abandoned'`, `step_index`/`step_count`, `deadline_at`, `attempt`, with a partial `UNIQUE` index self-blocking a second non-terminal run per cronoton at the DB layer — a second `createRun` attempt throws a typed `RunAlreadyInFlightError`, never a raw constraint leak), and `codex_cronoton_run_legs` (`status: 'pending' | 'submitted' | 'confirmed' | 'failed'`, `request_key`, `attempt` as a generation marker, and a `claimed_at` lease column added partway through the arc to close a concurrency race — see below). A leg row is always written `pending` before any submission, mirroring the existing claim-before-fire discipline one level down; store functions (`store/runs.ts`/`store/steps.ts`) are decision-free CRUD, with every typed-error gap (`StepAlreadyExistsError`, `RunLegAlreadyExistsError`, `LegNotSubmittedError`) caught and closed during review, and a shared `isUniqueConstraintError` helper (`store/errors.ts`) replacing what review caught as a verbatim-duplicated copy between the two store files. **Pure decision core (`pure/run-advance.ts`).** `advanceRun(run, legs, now, policy)` is a stateless function returning one or more of six actions (`submit-leg`, `poll`, `advance-step`, `replan-step`, `fail-run`, `wait`) from a fixed-order decision table: a met barrier is checked before a passed deadline (confirmed legs always win); a serial step's mid-sequence failure re-plans immediately (a cursor-paged sequence's later legs become suspect the moment one fails); a parallel step's failure waits for every sibling leg to reach a terminal status first (the "3 of 4 confirm, one fails" case re-plans only once that picture is complete, never on the first failure). A cross-cutting invariant test (`tests/chained-run-invariants.test.ts`) proves `advance-step` is never returned unless every current-step leg is confirmed. **The driver (`runs-driver.ts`).** `driveRunOnce`/`advanceInFlightRunsOnce` execute `advanceRun`'s actions against the store and chain client, wired into `startKhronotonLoop` as a third pass (`codexCronotonTickOnce`'s own claimed-due-row loop branches into a create-run-and-submit-step-0 path for any row with ≥1 step row, reusing `driveRunOnce` for both "just created" and "Nth pass" rather than a second decision path). The schedule's own `next_fire_at` keeps advancing on every due tick regardless of a long-lived run's self-block — two deliberately independent clocks, proven end to end against a real in-memory DB. A prerequisite fix (generation-scoped legs: the previously-unwritten `attempt` column used as a generation marker, plus a new `bumpRunAttempt` store write) makes a genuine re-plan after a failure actually work — without it, a step whose barrier check filters on `step_index` alone would be permanently defeated the instant any leg ever failed once; this retroactively corrected a latent gap in `ouronet.aqp-evict`'s own re-plan path, not just the planners added afterward. **Five built-in planners**, registered through a new `StepPlanner` registry (`registerStepPlanner`/`getStepPlanner`, a plain module-level map mirroring the existing server-resolver registry precedent), ported faithfully from OuronetUI's real transaction-construction logic across a workspace boundary: `ouronet.aqp-evict` reads an on-chain `URHC_BuildEvictPlans` plan, tries one simulated `CC_FullEvictRewards` leg first, and fans out to one `CC_EvictSingleReward` leg per beneficiary only on an actual gas-ceiling refusal; `ouronet.aqp-inject` tries `CC_InjectFinalize` then `CC_Inject` and — unlike the human-facing UI flow it replaces — never fans out and never refuses, propagating a genuine error if both attempts fail, since there's no human in the loop to hand a refusal to; `ouronet.aqp-unstall` fans stale-member-score repair into `CCp_FvtFixSlice` batches sized by a newly-ported generic gas-probe-and-pack algorithm (`pure/split-plan.ts`'s `measureSize`/`planFromSizing`/`splitPlan`, ported verbatim from OuronetUI's `measureSplit.ts` including its two-probe sizing, shrink-and-retry confirmation loop, and secant-refit growth loop); `ouronet.stoa-wrap` and `ouronet.stoa-unwrap` exist as built-ins because hand-authoring a Pact signer capability's scope correctly is the dangerous part, independent of leg count — `stoa-wrap` reads the patron account's live STOA balance via `coin.get-balance` immediately before building its one leg (rather than trusting any inter-step-carried value) and returns `[]` rather than a doomed zero-amount leg when the balance is 0; `stoa-unwrap` conditionally composes a `coin.C_CreateAccount` + `LQD|C_UnwrapStoa` two-form transaction only when its target account probe shows it doesn't exist yet. Every planner builds Pact code with zero interpolated values in the executed code itself — every dynamic value flows through transaction payload and a `read-string`/`read-integer`/`read-msg`/`read-decimal`/`read-keyset` placeholder; only a leg's signer `capabilities` string is a documented, narrowly-scoped exception, made safe by shape-guarding every account string before it reaches either payload or capability line. **Observability and standalone fire.** `executeNow` (`handlers/execute.ts`) now recognizes a chained row (≥1 `codex_cronoton_steps` row), starts a real run via `createRun`+`driveRunOnce`, and returns a real HTTP 409 when a non-terminal run is already in flight. `adaptMultiTxSummary` (`server/resolvers.ts`) widens its existing duck-typed extraction to read an optional per-batch `ok` field (via a dedicated `toReportedOk` helper, never a naive `Boolean()` coercion) and reports genuine multi-tx failure instead of hardcoding `ok: true` — strictly additive. A new `handlers/steps.ts` adds `POST /cronotons/:id/steps/:index/simulate` and `POST /cronotons/:id/steps/:index/fire`, resolving a stored step by index (byte-identical leg construction to a real run, sharing `stepRowToDefinition`/a new shared `resolvePlannerFor` helper rather than reimplementing either) and deliberately bypassing the run/leg-table lifecycle — a preview/testing mechanism, not an alternate production fire path — behind the same confirm gate `executeNow` uses, correctly rejecting a fire (but not a simulate) against a paused or terminal cronoton. New `GET /[id]/runs` (paginated, newest-first) and `GET /[id]/runs/[runId]/legs` (404 if the run belongs to a different cronoton) make a run's full lifecycle and every leg's fire/confirm history visible through this package's own surface for the first time, with per-leg `signers`/capability data redacted from the response. **A genuine concurrency race, found and fixed in already-shipped Phase 3 code.** `driveRunOnce` was only ever called from inside the scheduler loop's own single-process re-entrancy guard until `executeNow`'s new chained-row branch invoked it directly from an HTTP handler — making a previously-deferred, previously-documented gap in `runs-driver.ts`'s own doc comment concretely reachable: the background sweep could pick up the same newly-created run and both callers could read and submit the same `pending` leg before either write landed. Fixed with a real claim-before-submit step: a new nullable `claimed_at` column on `codex_cronoton_run_legs` plus `claimLegForSubmit`/`releaseLegClaim` (a conditional `UPDATE ... WHERE status='pending' AND claimed_at IS NULL`, mirroring the existing due-row claim idiom one level down), proven by an end-to-end test driving two concurrent `driveRunOnce` calls on the same run and asserting the real chain submit happens exactly once. **A follow-up cross-phase review**, run after all six phases shipped and everything was green, found three more significant bugs no single phase's own review could see: a **CRITICAL** stuck-run bug (a planner throw on a run's very first drive — every real planner's first action is a live chain read, so a bad params blob, a genuine Pact failure, or a transient chain outage all trigger it — left the run permanently non-terminal, since `deadline_at` is never stamped before that point and no code path ever marked the run terminal, blocking that cronoton's one-run-at-a-time slot forever with no recovery short of direct DB surgery); a **HIGH** leak of real transfer amounts, account identifiers, and Pact capability lines through the read-tier `runLegsHandler` (now redacted, mirroring `toPublicCronotonView`'s field-by-field convention); and a **HIGH** uncached live `getBlockGasLimit()` fetch repeated on every leg submit and planner probe within a single driver pass, serialized behind the loop's single re-entrancy guard and so delaying every other scheduled fire in the same tick (now cached per chain with a short TTL). A dedicated terminal re-review of the CRITICAL fix then caught a real regression in it — the new terminalize-on-throw catch was broader than intended, turning a benign concurrent-insert race into a permanent run failure and silently discarding the replan retry budget on a transient re-plan error — fixed by narrowing the catch to only the genuinely-unrecoverable first-entry case. Reviewed via nectar across all seven phases of this feature plus the cross-phase round — **33 rounds total**, correctness/conventions/tests on every phase plus a security lens from Phase 3 onward (a funds-moving automaton porting real transaction-construction and signer-capability logic across a workspace boundary), **73 CONFIRMED findings fixed** (or resolved via documentation where that was the proportionate response — e.g. a lease-expiry edge case on the new claim mechanism, accepted as a bounded, already-self-recovering limitation rather than rushed new reconciliation machinery), **4 REFUTED** on adversarial validation, **2 downgraded to STYLISTIC**. One further real bug — binary-floating-point noise leaking into a signed capability line and transaction payload for realistic token balances — was caught only by behavioral verification against the real built artifact using a real measured value from the source handoff; no lens pass or unit test (all of which used clean round numbers) found it. Full history in `docs/work/khronoton-chained-runs/review.md`, its six phase-numbered siblings, and `docs/work/khronoton-chained-runs-cross-phase-review/review.md`. Released 2026-11-20. **1265 specs pass.**
|
|
362
370
|
|
|
363
371
|
**v0.12.0** — Opt-in public cronoton observability. A cronoton's state (schedule, status, fire history, success/fail counts) was previously visible only through the authenticated admin surface (`listHandler`/`getHandler`/`firesHandler` behind `withRead` + the host's `AuthSeam`) — nothing let a host expose one cronoton's state to an unauthenticated, cross-origin caller (the concrete driver: embedding a mint's next-fire time + recent executions in a public-facing page), and this is framed as a general capability, not a one-off. **Schema.** Two new `codex_cronotons` columns: `public_token TEXT` (unique, nullable) and `public_observable INTEGER NOT NULL DEFAULT 0` (off by default). SQLite has no `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`, so `installSchema` (`server/schema.ts`) gains a small reusable `ensureColumn(db, table, column, columnDefSql)` helper (`PRAGMA table_info` → conditional `ALTER TABLE ADD COLUMN`), called once for each new column, immediately after `CREATE TABLE IF NOT EXISTS` — the FIRST time this package has needed to add a column to an already-provisioned database rather than just a fresh install, since the same call handles both a brand-new DB (the columns are absent from the `CREATE TABLE` literal) and an existing host's DB identically. A `CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronotons_public_token` follows — SQLite's unique index already permits multiple `NULL`s, so non-observable rows with no token never collide. **Store (`server/store/public.ts`).** `setPublicObservable(id, { observable, regenerate? }, dep)` toggles `public_observable` and mints `public_token` lazily: once, the first time a row is made observable (`crypto.randomBytes(20).toString("base64url")`), and never again on a plain disable→re-enable toggle — stable, so an embed URL built from the token never needs re-minting; `regenerate: true` is the only way to force a new one. A call against an unknown id throws the existing `CodexCronotonValidationError("not found")` — no new error type. `getCodexCronotonByPublicToken(token, dep)` resolves a row with one query (`WHERE public_token = ? AND public_observable = 1`), so an unknown token and a known-but-non-observable token are **indistinguishable** — both `null` — matching the "never 403, never leak which" rule one layer up in the handler. `getCronotonFireCounts(id, dep)` computes whole-history aggregates independently of any paginated fires window (a page of 20 out of 150 fires would under-report every aggregate): one query for `fired`/`succeeded`/`failed`/`lastSuccessAt`/`lastFailureAt`, plus a DESC-ordered scan (capped at 1000 rows) counting leading `'failure'` statuses for `currentFailStreak` — the scan stops at the first non-failure, so a success anywhere further back in the history never dilutes the trailing streak count. `deriveCronotonHealth({ currentFailStreak, isOverdue })` is a pure, standalone traffic-light rule: `"down"` at a streak ≥ 3, `"degraded"` at 1–2 or when overdue, `"healthy"` otherwise. `toPublicCronotonView(row, counts, firesPage, now?)` is the sanitizing projector and the ONLY place the privacy guarantee is enforced — it builds the DTO field-by-field from the row/fires, never spreading either, so `pact_code`, `payload_json`, `signers_json`, `gas_payer_json`, `server_resolver`, `created_by`, `config_json`, a fire's raw `errorMessage`/`chainResponse`, and the internal row `id` can never ride along by accident; the public token is the only public identifier the view carries. The view includes `schedule.humanText` (via `summariseSchedule`) and `schedule.cron` only for a `cron-expression` row, `triggerOnly` (reusing `rowExternalFireable`), `isOverdue` (true only for an `active` row whose `next_fire_at` has passed — overdue only makes sense for a row the scheduler is actually ticking), and a `fires` page whose `total`/`limit`/`offset` are passed through from `listFires` verbatim, not recomputed. **Handler (`handlers/public.ts`).** `publicCronotonHandler(ctx, request)`, added to the barrel, is a framework-agnostic `GET /<token>` route that is **unauthenticated by design** — it never calls `ctx.auth`/`withRead`/`withConfirm` at all, a deliberately different trust tier than the admin gates, authorizing purely on token validity plus the `public_observable` flag. Returns `{ status: 404, body: { error: "not found" } }` for both an unknown token and a known-but-non-observable one (byte-identical, never distinguishable), `200` with the sanitized view otherwise. `limit`/`offset` are parsed from `request.query` with a local, file-private copy of `read.ts`'s `firesHandler` clamp (1..100, default 50) — `read.ts`'s own `clampInt`/`firstScalar` are module-private, so this is a deliberate duplicate rather than a cross-handler import — over the cronoton's **complete** fire history, not a fixed "last 20": a cronoton with 150 fires is fully reachable across repeated calls with increasing `offset`, and `fires.total` always reports 150 regardless of the requested window. Cache-Control and CORS stay entirely host-side, unchanged package convention (`HandlerResponse` carries no headers field). Entirely additive — no existing export, column default, or admin-surface response shape changes for a cronoton that never opts in. Reviewed via nectar across 4 rounds (correctness/conventions/security/tests lenses each round, adversarial validation throughout, 16 CONFIRMED findings total, zero REFUTED, zero STYLISTIC): round 1 (7 findings) caught the two most significant — a `triggerOnly` gap that missed a plain-`eventDriven` cronoton (no persisted column distinguishes it; fixed by gating on `next_fire_at === null` excluding terminal one-time rows) and a clamp-default mismatch (the handler's own doc comment and CHANGELOG claimed parity with the admin `firesHandler`'s default of 50 while actually defaulting to 20) — plus an `ORDER BY` tiebreak gap, a `modified_at` omission, and two test-coverage gaps; round 2 re-verified round 1's fixes and caught that the `triggerOnly` fix's own comment asserted a false invariant (`claimDueCodexCronoton` also nulls `next_fire_at` on an ordinary row, not just the terminal-intent writer), plus two more test gaps; round 3 found the round-1 `ORDER BY` tiebreak itself was wrong — it sorted on the fire row's random `crypto.randomUUID()` id instead of a chronological key, fixed to SQLite's implicit `rowid` — plus two more test-coverage gaps; round 4 added a `mapStoreError` safety net this one unauthenticated handler had been missing (every sibling handler gets it for free from `withRead`/`withConfirm`) and closed the last two test gaps (`health`'s wiring inside the projector, and the fail-streak's 1000-row cap); round 5 found that round 4's own safety net had a real (if narrow) hole — a malformed `chain_response_json` row's `JSON.parse` failure was uncaught in `server/store/fires.ts`'s shared `listFires` (unlike its sibling `parseTxKeys`, which already tolerated bad input), and Node 20+'s V8 embeds a snippet of the actual malformed input text in that error's message — which `mapStoreError`'s generic passthrough would then have forwarded verbatim into the public route's 500 body, bypassing `toPublicCronotonView`'s sanitization entirely. Fixed at the root (`fires.ts` gains the same try/catch-degrade-to-null guard as `parseTxKeys`, benefiting every current and future caller of `listFires`, not just this one route) rather than only patched at this one call site. Full history in `docs/work/public-cronoton-observability/review.md`. Released 2026-11-11. **1027 specs pass.**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import crypto3, { randomUUID } from 'crypto';
|
|
2
2
|
import { createContext, useContext } from 'react';
|
|
3
3
|
|
|
4
4
|
// src/server/seams.ts
|
|
@@ -145,6 +145,43 @@ function advanceRun(run, legs, now, policy) {
|
|
|
145
145
|
return [{ kind: "wait" }];
|
|
146
146
|
}
|
|
147
147
|
|
|
148
|
+
// src/server/pure/yields.ts
|
|
149
|
+
var YieldNotFoundError = class extends Error {
|
|
150
|
+
constructor(name) {
|
|
151
|
+
super(`no yield named "${name}" has been produced yet in this run`);
|
|
152
|
+
this.name = "YieldNotFoundError";
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
function isYieldPlaceholder(value) {
|
|
156
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
157
|
+
const keys = Object.keys(value);
|
|
158
|
+
return keys.length === 1 && keys[0] === "$yield" && typeof value.$yield === "string";
|
|
159
|
+
}
|
|
160
|
+
function resolveYieldRefs(value, pool) {
|
|
161
|
+
if (Array.isArray(value)) {
|
|
162
|
+
return value.map((item) => resolveYieldRefs(item, pool));
|
|
163
|
+
}
|
|
164
|
+
if (isYieldPlaceholder(value)) {
|
|
165
|
+
const name = value.$yield;
|
|
166
|
+
if (!Object.prototype.hasOwnProperty.call(pool, name)) {
|
|
167
|
+
throw new YieldNotFoundError(name);
|
|
168
|
+
}
|
|
169
|
+
return pool[name];
|
|
170
|
+
}
|
|
171
|
+
if (value !== null && typeof value === "object") {
|
|
172
|
+
return Object.fromEntries(
|
|
173
|
+
Object.entries(value).map(([k, v]) => [k, resolveYieldRefs(v, pool)])
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
function resolveSingleStepPayload(step, pool) {
|
|
179
|
+
return {
|
|
180
|
+
...step,
|
|
181
|
+
payload_json: JSON.stringify(resolveYieldRefs(JSON.parse(step.payload_json ?? "{}"), pool))
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
148
185
|
// src/server/schema.ts
|
|
149
186
|
var SCHEMA_SQL = `
|
|
150
187
|
CREATE TABLE IF NOT EXISTS codex_cronotons (
|
|
@@ -292,6 +329,17 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_slot
|
|
|
292
329
|
ON codex_cronoton_run_legs(run_id, step_index, leg_index);
|
|
293
330
|
CREATE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_barrier
|
|
294
331
|
ON codex_cronoton_run_legs(run_id, step_index, status);
|
|
332
|
+
|
|
333
|
+
CREATE TABLE IF NOT EXISTS codex_cronoton_run_yields (
|
|
334
|
+
id TEXT PRIMARY KEY,
|
|
335
|
+
run_id TEXT NOT NULL REFERENCES codex_cronoton_runs(id) ON DELETE CASCADE,
|
|
336
|
+
name TEXT NOT NULL,
|
|
337
|
+
value_json TEXT NOT NULL,
|
|
338
|
+
step_index INTEGER NOT NULL,
|
|
339
|
+
created_at TEXT NOT NULL
|
|
340
|
+
);
|
|
341
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_run_yields_name
|
|
342
|
+
ON codex_cronoton_run_yields(run_id, name);
|
|
295
343
|
`;
|
|
296
344
|
function ensureColumn(db, table, column, columnDefSql) {
|
|
297
345
|
const existing = db.prepare(`PRAGMA table_info(${table})`).all();
|
|
@@ -308,6 +356,14 @@ function installSchema(db) {
|
|
|
308
356
|
`CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronotons_public_token ON codex_cronotons(public_token)`
|
|
309
357
|
);
|
|
310
358
|
ensureColumn(db, "codex_cronoton_run_legs", "claimed_at", "TEXT");
|
|
359
|
+
ensureColumn(db, "codex_cronoton_steps", "yield_as", "TEXT");
|
|
360
|
+
ensureColumn(db, "codex_cronotons", "try_single_tx_first", "INTEGER NOT NULL DEFAULT 0");
|
|
361
|
+
ensureColumn(
|
|
362
|
+
db,
|
|
363
|
+
"codex_cronotons",
|
|
364
|
+
"single_tx_mode",
|
|
365
|
+
"TEXT CHECK (single_tx_mode IN ('custom', 'default'))"
|
|
366
|
+
);
|
|
311
367
|
}
|
|
312
368
|
|
|
313
369
|
// src/server/executor-signers.ts
|
|
@@ -1382,7 +1438,7 @@ async function dispatchMultiTxResolver(name, opts) {
|
|
|
1382
1438
|
return r.run(opts);
|
|
1383
1439
|
}
|
|
1384
1440
|
function postponed(error) {
|
|
1385
|
-
return { ok: false, mode: "fire", error, terminalIntent: null };
|
|
1441
|
+
return { ok: false, mode: "fire", error, terminalIntent: null, postponed: true };
|
|
1386
1442
|
}
|
|
1387
1443
|
function toReportedOk(value) {
|
|
1388
1444
|
if (typeof value === "boolean") return value;
|
|
@@ -1488,6 +1544,13 @@ async function fireWithServerResolver(definition, _row, opts = {}) {
|
|
|
1488
1544
|
}
|
|
1489
1545
|
return result;
|
|
1490
1546
|
}
|
|
1547
|
+
function listStepsForCronoton(codexCronotonId, dep) {
|
|
1548
|
+
return dep.db.prepare(
|
|
1549
|
+
`SELECT * FROM codex_cronoton_steps
|
|
1550
|
+
WHERE codex_cronoton_id = ?
|
|
1551
|
+
ORDER BY step_index ASC`
|
|
1552
|
+
).all(codexCronotonId);
|
|
1553
|
+
}
|
|
1491
1554
|
|
|
1492
1555
|
// src/server/store/cronoton.ts
|
|
1493
1556
|
function computeNextOrReject(mode, config, now) {
|
|
@@ -1523,6 +1586,16 @@ function commitCodexCronoton(input, opts) {
|
|
|
1523
1586
|
throw new CodexCronotonValidationError("gasPayer.type must be a string");
|
|
1524
1587
|
}
|
|
1525
1588
|
assertAutoGasGate(input.config);
|
|
1589
|
+
if (input.singleTxMode !== void 0 && input.singleTxMode !== "custom") {
|
|
1590
|
+
throw new CodexCronotonValidationError(
|
|
1591
|
+
`singleTxMode must be "custom" (got ${JSON.stringify(input.singleTxMode)}) \u2014 "default" is not yet supported`
|
|
1592
|
+
);
|
|
1593
|
+
}
|
|
1594
|
+
if (input.trySingleTxFirst) {
|
|
1595
|
+
throw new CodexCronotonValidationError(
|
|
1596
|
+
"trySingleTxFirst cannot be set at commit time \u2014 this cronoton has no steps yet; add steps first, then enable it via an edit"
|
|
1597
|
+
);
|
|
1598
|
+
}
|
|
1526
1599
|
const runtimeArgKeys = input.runtimeArgKeys ?? [];
|
|
1527
1600
|
if (runtimeArgKeysCollide(input.payload ?? {}, runtimeArgKeys)) {
|
|
1528
1601
|
throw new CodexCronotonValidationError(
|
|
@@ -1549,15 +1622,16 @@ function commitCodexCronoton(input, opts) {
|
|
|
1549
1622
|
const externalFireable = input.externalFireable === true || evented;
|
|
1550
1623
|
const triggerOnly = externalFireable || runtimeArgKeys.length > 0 || input.eventDriven === true;
|
|
1551
1624
|
const nextFireAt = triggerOnly ? null : computeNextOrReject(input.scheduleMode, input.scheduleConfig, now).toISOString();
|
|
1552
|
-
const id =
|
|
1625
|
+
const id = crypto3.randomUUID();
|
|
1553
1626
|
const nowIso = now.toISOString();
|
|
1554
1627
|
opts.db.prepare(
|
|
1555
1628
|
`INSERT INTO codex_cronotons
|
|
1556
1629
|
(id, name, description, pact_code, config_json, payload_json,
|
|
1557
1630
|
gas_payer_json, signers_json, schedule_mode, schedule_config_json,
|
|
1558
|
-
server_resolver, external_fireable, runtime_arg_keys,
|
|
1631
|
+
server_resolver, external_fireable, runtime_arg_keys,
|
|
1632
|
+
try_single_tx_first, single_tx_mode, status,
|
|
1559
1633
|
next_fire_at, last_fire_at, created_at, modified_at, created_by)
|
|
1560
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NULL, ?, ?, ?)`
|
|
1634
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NULL, ?, ?, ?)`
|
|
1561
1635
|
).run(
|
|
1562
1636
|
id,
|
|
1563
1637
|
input.name.trim(),
|
|
@@ -1572,6 +1646,8 @@ function commitCodexCronoton(input, opts) {
|
|
|
1572
1646
|
input.serverResolver ?? null,
|
|
1573
1647
|
externalFireable ? 1 : 0,
|
|
1574
1648
|
runtimeArgKeys.length > 0 ? JSON.stringify(runtimeArgKeys) : null,
|
|
1649
|
+
input.trySingleTxFirst ? 1 : 0,
|
|
1650
|
+
input.singleTxMode ?? null,
|
|
1575
1651
|
nextFireAt,
|
|
1576
1652
|
nowIso,
|
|
1577
1653
|
nowIso,
|
|
@@ -1618,6 +1694,8 @@ function editCodexCronoton(id, patch, opts) {
|
|
|
1618
1694
|
let nextScheduleConfigJson = row.schedule_config_json;
|
|
1619
1695
|
let nextServerResolver = row.server_resolver;
|
|
1620
1696
|
let nextFireAt = row.next_fire_at;
|
|
1697
|
+
let nextTrySingleTxFirst = row.try_single_tx_first ?? 0;
|
|
1698
|
+
let nextSingleTxMode = row.single_tx_mode ?? null;
|
|
1621
1699
|
if (typeof patch.name === "string" && patch.name.trim() !== "" && patch.name.trim() !== row.name) {
|
|
1622
1700
|
nextName = patch.name.trim();
|
|
1623
1701
|
changedFields.push("name");
|
|
@@ -1657,6 +1735,31 @@ function editCodexCronoton(id, patch, opts) {
|
|
|
1657
1735
|
nextServerResolver = patch.serverResolver;
|
|
1658
1736
|
changedFields.push("serverResolver");
|
|
1659
1737
|
}
|
|
1738
|
+
if (patch.singleTxMode !== void 0 && patch.singleTxMode !== "custom") {
|
|
1739
|
+
throw new CodexCronotonValidationError(
|
|
1740
|
+
`singleTxMode must be "custom" (got ${JSON.stringify(patch.singleTxMode)}) \u2014 "default" is not yet supported`
|
|
1741
|
+
);
|
|
1742
|
+
}
|
|
1743
|
+
const willBeTrySingleTxFirst = patch.trySingleTxFirst !== void 0 ? patch.trySingleTxFirst : row.try_single_tx_first === 1;
|
|
1744
|
+
if (willBeTrySingleTxFirst && listStepsForCronoton(id, { db }).length === 0) {
|
|
1745
|
+
throw new CodexCronotonValidationError(
|
|
1746
|
+
"trySingleTxFirst requires at least one codex_cronoton_steps row to fall back to \u2014 this cronoton has no steps"
|
|
1747
|
+
);
|
|
1748
|
+
}
|
|
1749
|
+
const willBeSingleTxMode = patch.singleTxMode !== void 0 ? patch.singleTxMode : row.single_tx_mode;
|
|
1750
|
+
if (willBeTrySingleTxFirst && willBeSingleTxMode !== "custom") {
|
|
1751
|
+
throw new CodexCronotonValidationError(
|
|
1752
|
+
'trySingleTxFirst requires singleTxMode: "custom" to be set (single_tx_mode is otherwise left meaningless)'
|
|
1753
|
+
);
|
|
1754
|
+
}
|
|
1755
|
+
if (patch.trySingleTxFirst !== void 0 && (patch.trySingleTxFirst ? 1 : 0) !== row.try_single_tx_first) {
|
|
1756
|
+
nextTrySingleTxFirst = patch.trySingleTxFirst ? 1 : 0;
|
|
1757
|
+
changedFields.push("trySingleTxFirst");
|
|
1758
|
+
}
|
|
1759
|
+
if (patch.singleTxMode !== void 0 && patch.singleTxMode !== row.single_tx_mode) {
|
|
1760
|
+
nextSingleTxMode = patch.singleTxMode;
|
|
1761
|
+
changedFields.push("singleTxMode");
|
|
1762
|
+
}
|
|
1660
1763
|
let scheduleChanged = false;
|
|
1661
1764
|
if (patch.scheduleMode && patch.scheduleConfig) {
|
|
1662
1765
|
nextScheduleMode = patch.scheduleMode;
|
|
@@ -1693,7 +1796,8 @@ function editCodexCronoton(id, patch, opts) {
|
|
|
1693
1796
|
SET name = ?, description = ?, pact_code = ?, config_json = ?,
|
|
1694
1797
|
payload_json = ?, gas_payer_json = ?, signers_json = ?,
|
|
1695
1798
|
schedule_mode = ?, schedule_config_json = ?, server_resolver = ?,
|
|
1696
|
-
external_fireable = ?,
|
|
1799
|
+
external_fireable = ?, try_single_tx_first = ?, single_tx_mode = ?,
|
|
1800
|
+
next_fire_at = ?, modified_at = ?
|
|
1697
1801
|
WHERE id = ?`
|
|
1698
1802
|
).run(
|
|
1699
1803
|
nextName,
|
|
@@ -1707,6 +1811,8 @@ function editCodexCronoton(id, patch, opts) {
|
|
|
1707
1811
|
nextScheduleConfigJson,
|
|
1708
1812
|
nextServerResolver,
|
|
1709
1813
|
nextExternalFireable,
|
|
1814
|
+
nextTrySingleTxFirst,
|
|
1815
|
+
nextSingleTxMode,
|
|
1710
1816
|
nextFireAt,
|
|
1711
1817
|
(opts.now ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
1712
1818
|
id
|
|
@@ -1796,7 +1902,7 @@ function createManualBatch(input, opts) {
|
|
|
1796
1902
|
}
|
|
1797
1903
|
const now = opts.now ?? /* @__PURE__ */ new Date();
|
|
1798
1904
|
const nowIso = now.toISOString();
|
|
1799
|
-
const id =
|
|
1905
|
+
const id = crypto3.randomUUID();
|
|
1800
1906
|
db.prepare(
|
|
1801
1907
|
`INSERT INTO codex_cronoton_manual_batches
|
|
1802
1908
|
(id, codex_cronoton_id, total, completed, interval_seconds, status,
|
|
@@ -1848,14 +1954,7 @@ function computeDefinitionFingerprint(row) {
|
|
|
1848
1954
|
scheduleConfig: parseJson2(row.schedule_config_json, {})
|
|
1849
1955
|
};
|
|
1850
1956
|
const canonical = JSON.stringify(canonicalize(parts));
|
|
1851
|
-
return
|
|
1852
|
-
}
|
|
1853
|
-
function listStepsForCronoton(codexCronotonId, dep) {
|
|
1854
|
-
return dep.db.prepare(
|
|
1855
|
-
`SELECT * FROM codex_cronoton_steps
|
|
1856
|
-
WHERE codex_cronoton_id = ?
|
|
1857
|
-
ORDER BY step_index ASC`
|
|
1858
|
-
).all(codexCronotonId);
|
|
1957
|
+
return crypto3.createHash("sha256").update(canonical).digest("hex");
|
|
1859
1958
|
}
|
|
1860
1959
|
function createRun(input, dep) {
|
|
1861
1960
|
const id = randomUUID();
|
|
@@ -1992,17 +2091,48 @@ function markRunTerminal(runId, status, dep) {
|
|
|
1992
2091
|
throw new RunAlreadyTerminalError(runId);
|
|
1993
2092
|
}
|
|
1994
2093
|
}
|
|
2094
|
+
function upsertYield(input, dep) {
|
|
2095
|
+
const id = crypto3.randomUUID();
|
|
2096
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2097
|
+
const value = input.value === void 0 ? null : input.value;
|
|
2098
|
+
dep.db.prepare(
|
|
2099
|
+
`INSERT INTO codex_cronoton_run_yields (id, run_id, name, value_json, step_index, created_at)
|
|
2100
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
2101
|
+
ON CONFLICT(run_id, name) DO UPDATE SET
|
|
2102
|
+
value_json = excluded.value_json,
|
|
2103
|
+
step_index = excluded.step_index,
|
|
2104
|
+
created_at = excluded.created_at`
|
|
2105
|
+
).run(id, input.runId, input.name, JSON.stringify(value), input.stepIndex, now);
|
|
2106
|
+
}
|
|
2107
|
+
function getYieldPool(runId, dep) {
|
|
2108
|
+
const rows = dep.db.prepare(`SELECT name, value_json FROM codex_cronoton_run_yields WHERE run_id = ?`).all(runId);
|
|
2109
|
+
const pool = /* @__PURE__ */ Object.create(null);
|
|
2110
|
+
for (const row of rows) {
|
|
2111
|
+
pool[row.name] = JSON.parse(row.value_json);
|
|
2112
|
+
}
|
|
2113
|
+
return pool;
|
|
2114
|
+
}
|
|
1995
2115
|
|
|
1996
2116
|
// src/server/planners/registry.ts
|
|
1997
|
-
|
|
2117
|
+
function normalizePlannerResult(result) {
|
|
2118
|
+
if (Array.isArray(result)) return { legs: result };
|
|
2119
|
+
return result;
|
|
2120
|
+
}
|
|
2121
|
+
var STEP_PLANNERS = /* @__PURE__ */ Object.create(null);
|
|
1998
2122
|
function getStepPlanner(name) {
|
|
1999
2123
|
return STEP_PLANNERS[name];
|
|
2000
2124
|
}
|
|
2001
|
-
function resolvePlannerFor(step, seams) {
|
|
2125
|
+
function resolvePlannerFor(step, seams, yieldPool = {}) {
|
|
2002
2126
|
const planner = getStepPlanner(step.planner_name ?? "");
|
|
2003
2127
|
if (!planner) return void 0;
|
|
2004
2128
|
const plannerCtx = { runtime: seams.runtime, resolver: seams.resolver, config: seams.config };
|
|
2005
|
-
|
|
2129
|
+
const resolvedStep = {
|
|
2130
|
+
...step,
|
|
2131
|
+
planner_params_json: JSON.stringify(
|
|
2132
|
+
resolveYieldRefs(JSON.parse(step.planner_params_json ?? "{}"), yieldPool)
|
|
2133
|
+
)
|
|
2134
|
+
};
|
|
2135
|
+
return { planner, plannerCtx, resolvedStep };
|
|
2006
2136
|
}
|
|
2007
2137
|
|
|
2008
2138
|
// src/server/runs-driver.ts
|
|
@@ -2088,7 +2218,7 @@ async function handleSubmitLeg(legIndex, run, stepLegs, now, ctx) {
|
|
|
2088
2218
|
});
|
|
2089
2219
|
return false;
|
|
2090
2220
|
}
|
|
2091
|
-
async function handlePoll(stepLegs, ctx) {
|
|
2221
|
+
async function handlePoll(stepLegs, step, ctx) {
|
|
2092
2222
|
const submitted = stepLegs.filter(
|
|
2093
2223
|
(l) => l.status === "submitted" && l.request_key != null && l.chain_id != null
|
|
2094
2224
|
);
|
|
@@ -2108,6 +2238,17 @@ async function handlePoll(stepLegs, ctx) {
|
|
|
2108
2238
|
if (!landed) continue;
|
|
2109
2239
|
if (landed.result.status === "success") {
|
|
2110
2240
|
markLegConfirmed(leg.id, { db: ctx.db });
|
|
2241
|
+
if (step.mode === "single" && step.yield_as) {
|
|
2242
|
+
upsertYield(
|
|
2243
|
+
{
|
|
2244
|
+
runId: leg.run_id,
|
|
2245
|
+
name: step.yield_as,
|
|
2246
|
+
value: landed.result.data,
|
|
2247
|
+
stepIndex: step.step_index
|
|
2248
|
+
},
|
|
2249
|
+
{ db: ctx.db }
|
|
2250
|
+
);
|
|
2251
|
+
}
|
|
2111
2252
|
} else {
|
|
2112
2253
|
markLegFailed(
|
|
2113
2254
|
leg.id,
|
|
@@ -2147,22 +2288,27 @@ async function handleReplanStep(run, step, allRunLegs, now, ctx) {
|
|
|
2147
2288
|
}
|
|
2148
2289
|
async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
|
|
2149
2290
|
if (step.mode === "planner") {
|
|
2150
|
-
const
|
|
2291
|
+
const pool2 = getYieldPool(run.id, { db: ctx.db });
|
|
2292
|
+
const resolved = resolvePlannerFor(step, ctx, pool2);
|
|
2151
2293
|
if (!resolved) {
|
|
2152
2294
|
throw new PlannerNotRegisteredError(step.planner_name ?? "(unnamed)");
|
|
2153
2295
|
}
|
|
2154
|
-
const
|
|
2296
|
+
const rawResult = await resolved.planner(resolved.resolvedStep, resolved.plannerCtx);
|
|
2297
|
+
const normalized = normalizePlannerResult(rawResult);
|
|
2298
|
+
const legs = normalized.legs;
|
|
2155
2299
|
if (legs.length === 0) {
|
|
2300
|
+
if (normalized.yield !== void 0 && step.yield_as) {
|
|
2301
|
+
upsertYield(
|
|
2302
|
+
{ runId: run.id, name: step.yield_as, value: normalized.yield, stepIndex: run.step_index },
|
|
2303
|
+
{ db: ctx.db }
|
|
2304
|
+
);
|
|
2305
|
+
}
|
|
2156
2306
|
return handleAdvanceStep(run, now, ctx);
|
|
2157
2307
|
}
|
|
2158
2308
|
const allStepLegs = allRunLegs.filter((l) => l.step_index === run.step_index);
|
|
2159
2309
|
const isReplan = allStepLegs.length > 0;
|
|
2160
2310
|
const newAttempt = isReplan ? run.attempt + 1 : run.attempt;
|
|
2161
2311
|
const startLegIndex = isReplan ? Math.max(...allStepLegs.map((l) => l.leg_index)) + 1 : 0;
|
|
2162
|
-
if (isReplan) {
|
|
2163
|
-
bumpRunAttempt(run.id, { db: ctx.db });
|
|
2164
|
-
touchRunDeadline(run.id, computeStepDeadline(now, ctx), { db: ctx.db });
|
|
2165
|
-
}
|
|
2166
2312
|
legs.forEach((leg, i) => {
|
|
2167
2313
|
insertRunLeg(
|
|
2168
2314
|
{
|
|
@@ -2175,6 +2321,16 @@ async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
|
|
|
2175
2321
|
{ db: ctx.db }
|
|
2176
2322
|
);
|
|
2177
2323
|
});
|
|
2324
|
+
if (isReplan) {
|
|
2325
|
+
bumpRunAttempt(run.id, { db: ctx.db });
|
|
2326
|
+
touchRunDeadline(run.id, computeStepDeadline(now, ctx), { db: ctx.db });
|
|
2327
|
+
}
|
|
2328
|
+
if (normalized.yield !== void 0 && step.yield_as) {
|
|
2329
|
+
upsertYield(
|
|
2330
|
+
{ runId: run.id, name: step.yield_as, value: normalized.yield, stepIndex: run.step_index },
|
|
2331
|
+
{ db: ctx.db }
|
|
2332
|
+
);
|
|
2333
|
+
}
|
|
2178
2334
|
if (!isReplan) {
|
|
2179
2335
|
advanceRunStep(
|
|
2180
2336
|
run.id,
|
|
@@ -2184,7 +2340,9 @@ async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
|
|
|
2184
2340
|
}
|
|
2185
2341
|
return true;
|
|
2186
2342
|
}
|
|
2187
|
-
const
|
|
2343
|
+
const pool = getYieldPool(run.id, { db: ctx.db });
|
|
2344
|
+
const resolvedStep = resolveSingleStepPayload(step, pool);
|
|
2345
|
+
const definition = stepRowToDefinition(resolvedStep);
|
|
2188
2346
|
insertRunLeg(
|
|
2189
2347
|
{ runId: run.id, stepIndex: run.step_index, legIndex: 0, definitionJson: JSON.stringify(definition) },
|
|
2190
2348
|
{ db: ctx.db }
|
|
@@ -2212,7 +2370,7 @@ async function executeAction(action, run, step, stepLegs, allRunLegs, now, ctx)
|
|
|
2212
2370
|
case "submit-leg":
|
|
2213
2371
|
return handleSubmitLeg(action.legIndex, run, stepLegs, now, ctx);
|
|
2214
2372
|
case "poll":
|
|
2215
|
-
return handlePoll(stepLegs, ctx);
|
|
2373
|
+
return handlePoll(stepLegs, step, ctx);
|
|
2216
2374
|
case "advance-step":
|
|
2217
2375
|
return handleAdvanceStep(run, now, ctx);
|
|
2218
2376
|
case "replan-step":
|
|
@@ -2224,10 +2382,12 @@ async function executeAction(action, run, step, stepLegs, allRunLegs, now, ctx)
|
|
|
2224
2382
|
}
|
|
2225
2383
|
}
|
|
2226
2384
|
async function driveRunOnce(runId, now, ctx) {
|
|
2385
|
+
const initialRun = getRun(runId, { db: ctx.db });
|
|
2386
|
+
if (!initialRun) return;
|
|
2387
|
+
const steps = listStepsForCronoton(initialRun.codex_cronoton_id, { db: ctx.db });
|
|
2227
2388
|
for (; ; ) {
|
|
2228
2389
|
const run = getRun(runId, { db: ctx.db });
|
|
2229
2390
|
if (!run) return;
|
|
2230
|
-
const steps = listStepsForCronoton(run.codex_cronoton_id, { db: ctx.db });
|
|
2231
2391
|
const step = steps.find((s) => s.step_index === run.step_index);
|
|
2232
2392
|
if (!step) {
|
|
2233
2393
|
markRunTerminal(runId, "failed", { db: ctx.db });
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-
|
|
1
|
+
import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-24THBKR7.js';
|
|
2
2
|
import { useState, useRef, useEffect, useCallback } from 'react';
|
|
3
3
|
|
|
4
4
|
function useCronotons(query) {
|
|
@@ -1,5 +1,5 @@
|
|
|
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-
|
|
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-DH7Ym8FQ.js';
|
|
3
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`). */
|