@ancientpantheon/khronoton-core 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@ 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.14.0 — 2026-11-20
8
+
9
+ **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.**
10
+
11
+ 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.
12
+
13
+ - **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.
14
+ - **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.
15
+ - **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`.
16
+ - 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.
17
+
18
+ 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/`.
19
+
20
+ **1317 specs pass.**
21
+
7
22
  ## 0.13.0 — 2026-11-20
8
23
 
9
24
  **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,8 @@ Khronoton is the "When do I act?" Constructor of the Pantheon architecture — t
6
6
 
7
7
  ## Status
8
8
 
9
+ **`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.**
10
+
9
11
  **`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
12
 
11
13
  **`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 +360,8 @@ npm install @ancientpantheon/khronoton-core
358
360
 
359
361
  ## Version history
360
362
 
363
+ **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.**
364
+
361
365
  **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
366
 
363
367
  **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.**
@@ -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,7 @@ 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");
311
360
  }
312
361
 
313
362
  // src/server/executor-signers.ts
@@ -1992,17 +2041,48 @@ function markRunTerminal(runId, status, dep) {
1992
2041
  throw new RunAlreadyTerminalError(runId);
1993
2042
  }
1994
2043
  }
2044
+ function upsertYield(input, dep) {
2045
+ const id = crypto2.randomUUID();
2046
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2047
+ const value = input.value === void 0 ? null : input.value;
2048
+ dep.db.prepare(
2049
+ `INSERT INTO codex_cronoton_run_yields (id, run_id, name, value_json, step_index, created_at)
2050
+ VALUES (?, ?, ?, ?, ?, ?)
2051
+ ON CONFLICT(run_id, name) DO UPDATE SET
2052
+ value_json = excluded.value_json,
2053
+ step_index = excluded.step_index,
2054
+ created_at = excluded.created_at`
2055
+ ).run(id, input.runId, input.name, JSON.stringify(value), input.stepIndex, now);
2056
+ }
2057
+ function getYieldPool(runId, dep) {
2058
+ const rows = dep.db.prepare(`SELECT name, value_json FROM codex_cronoton_run_yields WHERE run_id = ?`).all(runId);
2059
+ const pool = /* @__PURE__ */ Object.create(null);
2060
+ for (const row of rows) {
2061
+ pool[row.name] = JSON.parse(row.value_json);
2062
+ }
2063
+ return pool;
2064
+ }
1995
2065
 
1996
2066
  // src/server/planners/registry.ts
1997
- var STEP_PLANNERS = {};
2067
+ function normalizePlannerResult(result) {
2068
+ if (Array.isArray(result)) return { legs: result };
2069
+ return result;
2070
+ }
2071
+ var STEP_PLANNERS = /* @__PURE__ */ Object.create(null);
1998
2072
  function getStepPlanner(name) {
1999
2073
  return STEP_PLANNERS[name];
2000
2074
  }
2001
- function resolvePlannerFor(step, seams) {
2075
+ function resolvePlannerFor(step, seams, yieldPool = {}) {
2002
2076
  const planner = getStepPlanner(step.planner_name ?? "");
2003
2077
  if (!planner) return void 0;
2004
2078
  const plannerCtx = { runtime: seams.runtime, resolver: seams.resolver, config: seams.config };
2005
- return { planner, plannerCtx };
2079
+ const resolvedStep = {
2080
+ ...step,
2081
+ planner_params_json: JSON.stringify(
2082
+ resolveYieldRefs(JSON.parse(step.planner_params_json ?? "{}"), yieldPool)
2083
+ )
2084
+ };
2085
+ return { planner, plannerCtx, resolvedStep };
2006
2086
  }
2007
2087
 
2008
2088
  // src/server/runs-driver.ts
@@ -2088,7 +2168,7 @@ async function handleSubmitLeg(legIndex, run, stepLegs, now, ctx) {
2088
2168
  });
2089
2169
  return false;
2090
2170
  }
2091
- async function handlePoll(stepLegs, ctx) {
2171
+ async function handlePoll(stepLegs, step, ctx) {
2092
2172
  const submitted = stepLegs.filter(
2093
2173
  (l) => l.status === "submitted" && l.request_key != null && l.chain_id != null
2094
2174
  );
@@ -2108,6 +2188,17 @@ async function handlePoll(stepLegs, ctx) {
2108
2188
  if (!landed) continue;
2109
2189
  if (landed.result.status === "success") {
2110
2190
  markLegConfirmed(leg.id, { db: ctx.db });
2191
+ if (step.mode === "single" && step.yield_as) {
2192
+ upsertYield(
2193
+ {
2194
+ runId: leg.run_id,
2195
+ name: step.yield_as,
2196
+ value: landed.result.data,
2197
+ stepIndex: step.step_index
2198
+ },
2199
+ { db: ctx.db }
2200
+ );
2201
+ }
2111
2202
  } else {
2112
2203
  markLegFailed(
2113
2204
  leg.id,
@@ -2147,22 +2238,27 @@ async function handleReplanStep(run, step, allRunLegs, now, ctx) {
2147
2238
  }
2148
2239
  async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
2149
2240
  if (step.mode === "planner") {
2150
- const resolved = resolvePlannerFor(step, ctx);
2241
+ const pool2 = getYieldPool(run.id, { db: ctx.db });
2242
+ const resolved = resolvePlannerFor(step, ctx, pool2);
2151
2243
  if (!resolved) {
2152
2244
  throw new PlannerNotRegisteredError(step.planner_name ?? "(unnamed)");
2153
2245
  }
2154
- const legs = await resolved.planner(step, resolved.plannerCtx);
2246
+ const rawResult = await resolved.planner(resolved.resolvedStep, resolved.plannerCtx);
2247
+ const normalized = normalizePlannerResult(rawResult);
2248
+ const legs = normalized.legs;
2155
2249
  if (legs.length === 0) {
2250
+ if (normalized.yield !== void 0 && step.yield_as) {
2251
+ upsertYield(
2252
+ { runId: run.id, name: step.yield_as, value: normalized.yield, stepIndex: run.step_index },
2253
+ { db: ctx.db }
2254
+ );
2255
+ }
2156
2256
  return handleAdvanceStep(run, now, ctx);
2157
2257
  }
2158
2258
  const allStepLegs = allRunLegs.filter((l) => l.step_index === run.step_index);
2159
2259
  const isReplan = allStepLegs.length > 0;
2160
2260
  const newAttempt = isReplan ? run.attempt + 1 : run.attempt;
2161
2261
  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
2262
  legs.forEach((leg, i) => {
2167
2263
  insertRunLeg(
2168
2264
  {
@@ -2175,6 +2271,16 @@ async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
2175
2271
  { db: ctx.db }
2176
2272
  );
2177
2273
  });
2274
+ if (isReplan) {
2275
+ bumpRunAttempt(run.id, { db: ctx.db });
2276
+ touchRunDeadline(run.id, computeStepDeadline(now, ctx), { db: ctx.db });
2277
+ }
2278
+ if (normalized.yield !== void 0 && step.yield_as) {
2279
+ upsertYield(
2280
+ { runId: run.id, name: step.yield_as, value: normalized.yield, stepIndex: run.step_index },
2281
+ { db: ctx.db }
2282
+ );
2283
+ }
2178
2284
  if (!isReplan) {
2179
2285
  advanceRunStep(
2180
2286
  run.id,
@@ -2184,7 +2290,9 @@ async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
2184
2290
  }
2185
2291
  return true;
2186
2292
  }
2187
- const definition = stepRowToDefinition(step);
2293
+ const pool = getYieldPool(run.id, { db: ctx.db });
2294
+ const resolvedStep = resolveSingleStepPayload(step, pool);
2295
+ const definition = stepRowToDefinition(resolvedStep);
2188
2296
  insertRunLeg(
2189
2297
  { runId: run.id, stepIndex: run.step_index, legIndex: 0, definitionJson: JSON.stringify(definition) },
2190
2298
  { db: ctx.db }
@@ -2212,7 +2320,7 @@ async function executeAction(action, run, step, stepLegs, allRunLegs, now, ctx)
2212
2320
  case "submit-leg":
2213
2321
  return handleSubmitLeg(action.legIndex, run, stepLegs, now, ctx);
2214
2322
  case "poll":
2215
- return handlePoll(stepLegs, ctx);
2323
+ return handlePoll(stepLegs, step, ctx);
2216
2324
  case "advance-step":
2217
2325
  return handleAdvanceStep(run, now, ctx);
2218
2326
  case "replan-step":
@@ -2224,10 +2332,12 @@ async function executeAction(action, run, step, stepLegs, allRunLegs, now, ctx)
2224
2332
  }
2225
2333
  }
2226
2334
  async function driveRunOnce(runId, now, ctx) {
2335
+ const initialRun = getRun(runId, { db: ctx.db });
2336
+ if (!initialRun) return;
2337
+ const steps = listStepsForCronoton(initialRun.codex_cronoton_id, { db: ctx.db });
2227
2338
  for (; ; ) {
2228
2339
  const run = getRun(runId, { db: ctx.db });
2229
2340
  if (!run) return;
2230
- const steps = listStepsForCronoton(run.codex_cronoton_id, { db: ctx.db });
2231
2341
  const step = steps.find((s) => s.step_index === run.step_index);
2232
2342
  if (!step) {
2233
2343
  markRunTerminal(runId, "failed", { db: ctx.db });
@@ -1,4 +1,4 @@
1
- import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-IAK4UEAA.js';
1
+ import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-A5YODPKQ.js';
2
2
  import { useState, useRef, useEffect, useCallback } from 'react';
3
3
 
4
4
  function useCronotons(query) {
@@ -17,7 +17,9 @@
17
17
  */
18
18
  import { json, err } from "./http.js";
19
19
  import { withConfirm } from "./context.js";
20
- import { getCodexCronoton, listStepsForCronoton, resolvePlannerFor, stepRowToDefinition, executeCodexTransaction, } from "../server/index.js";
20
+ import { getCodexCronoton, getStepByIndex, resolvePlannerFor, stepRowToDefinition, executeCodexTransaction, } from "../server/index.js";
21
+ import { resolveSingleStepPayload, YieldNotFoundError } from "../server/pure/yields.js";
22
+ import { normalizePlannerResult } from "../server/planners/registry.js";
21
23
  /** Terminal statuses cannot be fired on demand — same set `execute.ts`'s
22
24
  * `executeNow`/`triggerCronoton` already enforce, duplicated locally per
23
25
  * this codebase's own per-module-small-constant convention (`parseJson`,
@@ -27,18 +29,53 @@ const TERMINAL_STATUSES = new Set(["completed", "error"]);
27
29
  /** Resolve the leg(s) a stored step currently produces, via the SAME shared
28
30
  * `resolvePlannerFor` helper `runs-driver.ts`'s `handleReplanStep` uses —
29
31
  * 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. */
32
+ * Returns a DISCRIMINATED failure reason rather than a bare `{ok:false}` —
33
+ * a real review finding caught that collapsing "planner not registered"
34
+ * and "unresolved $yield reference" into the same untagged shape made
35
+ * every caller report a misleading `planner 'null' is not registered`
36
+ * message for a `mode:'single'` step (whose `planner_name` is always
37
+ * `null`) that actually failed on a yield reference, not a planner lookup.
38
+ *
39
+ * A standalone fire/simulate has no run, so no yield pool to resolve a
40
+ * `{"$yield": "<name>"}` reference against — every resolution here runs
41
+ * against an explicit empty pool (`docs/work/khronoton-step-yield-carry/
42
+ * design.md`'s "Consuming a yield"). A step that references a yield (e.g.
43
+ * authored for chained-run use, then fired standalone to preview it) always
44
+ * fails `YieldNotFoundError`; caught here and reported as its own reason,
45
+ * rather than letting it escape uncaught to the handler's generic 500
46
+ * catch-all or being folded into the unrelated planner-not-registered case. */
33
47
  async function resolveStepLegs(step, ctx) {
34
- if (step.mode === "single") {
35
- return { ok: true, legs: [stepRowToDefinition(step)] };
48
+ try {
49
+ if (step.mode === "single") {
50
+ // Same shared helper `runs-driver.ts`'s single-mode branch uses — not
51
+ // a parallel reimplementation (a review finding caught the two call
52
+ // sites independently re-deriving the identical sequence).
53
+ const resolvedStep = resolveSingleStepPayload(step, {});
54
+ return { ok: true, legs: [stepRowToDefinition(resolvedStep)] };
55
+ }
56
+ const resolved = resolvePlannerFor(step, ctx, {});
57
+ if (!resolved)
58
+ return { ok: false, reason: "planner-not-registered" };
59
+ const result = await resolved.planner(resolved.resolvedStep, resolved.plannerCtx);
60
+ // The standalone route has no run to persist a yield into, so
61
+ // `normalized.yield`, if present, is deliberately discarded here.
62
+ const normalized = normalizePlannerResult(result);
63
+ return { ok: true, legs: normalized.legs };
64
+ }
65
+ catch (error) {
66
+ if (error instanceof YieldNotFoundError) {
67
+ return { ok: false, reason: "yield-not-found", message: error.message };
68
+ }
69
+ throw error;
70
+ }
71
+ }
72
+ /** Shared 404 body for either `resolveStepLegs` failure reason, so
73
+ * `simulateStep`/`fireStep` never independently decide how to phrase it. */
74
+ function resolveStepLegsErrorResponse(step, resolved) {
75
+ if (resolved.reason === "yield-not-found") {
76
+ return err(404, `cannot resolve this step: ${resolved.message}`);
36
77
  }
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 };
78
+ return err(404, `planner '${step.planner_name}' is not registered`);
42
79
  }
43
80
  /** Shared step lookup: 404 on missing cronoton or missing step-at-index.
44
81
  * Returns the parent cronoton row too (not just the step) so `fireStep`
@@ -48,7 +85,7 @@ function findStep(ctx, cronotonId, index) {
48
85
  const row = getCodexCronoton(cronotonId, { db: ctx.db });
49
86
  if (!row)
50
87
  return { ok: false, response: err(404, "not found") };
51
- const step = listStepsForCronoton(cronotonId, { db: ctx.db }).find((s) => s.step_index === index);
88
+ const step = getStepByIndex(cronotonId, index, { db: ctx.db });
52
89
  if (!step)
53
90
  return { ok: false, response: err(404, "step not found at that index") };
54
91
  return { ok: true, row, step };
@@ -63,7 +100,7 @@ export const simulateStep = (ctx, req) => withConfirm(ctx, req, async () => {
63
100
  return found.response;
64
101
  const resolved = await resolveStepLegs(found.step, ctx);
65
102
  if (!resolved.ok) {
66
- return err(404, `planner '${found.step.planner_name}' is not registered`);
103
+ return resolveStepLegsErrorResponse(found.step, resolved);
67
104
  }
68
105
  const legs = resolved.legs;
69
106
  const results = await Promise.all(legs.map((leg) => executeCodexTransaction(leg, "simulate", { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config })));
@@ -98,7 +135,7 @@ export const fireStep = (ctx, req) => withConfirm(ctx, req, async () => {
98
135
  return err(400, "cannot execute a terminal cronoton");
99
136
  const resolved = await resolveStepLegs(found.step, ctx);
100
137
  if (!resolved.ok) {
101
- return err(404, `planner '${found.step.planner_name}' is not registered`);
138
+ return resolveStepLegsErrorResponse(found.step, resolved);
102
139
  }
103
140
  const legs = resolved.legs;
104
141
  const results = await Promise.all(legs.map((leg) => executeCodexTransaction(leg, "fire", { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config })));
@@ -1,2 +1,2 @@
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
+ export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-WKI52IPY.js';
2
+ export { useKhronoton } from '../chunk-A5YODPKQ.js';
@@ -1,5 +1,5 @@
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';
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-A5YODPKQ.js';
2
+ export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-A5YODPKQ.js';
3
3
  import { useRef, useState, useEffect } from 'react';
4
4
  import { jsx } from 'react/jsx-runtime';
5
5
 
@@ -18,6 +18,7 @@ export { parseRuntimeArgKeys, validateRuntimeArgs, applyRuntimeArgs, runtimeArgK
18
18
  export type { RuntimeArgs, ValidateRuntimeArgsResult } from "./pure/runtime-args.js";
19
19
  export { advanceRun } from "./pure/run-advance.js";
20
20
  export type { StepMode, RunState, LegState, RunPolicy, RunAction } from "./pure/run-advance.js";
21
+ export { YieldNotFoundError } from "./pure/yields.js";
21
22
  export { installSchema } from "./schema.js";
22
23
  export type { ScheduleMode, ScheduleConfig } from "../schedule.js";
23
24
  export { executeCodexTransaction } from "./executor.js";
@@ -20,6 +20,15 @@ export { defaultOnAudit, defaultResolveFireMode, TICK_INTERVAL_MS, LISTEN_TIMEOU
20
20
  export { parseCapabilityLine, computeTerminalIntent } from "./pure/capability.js";
21
21
  export { parseRuntimeArgKeys, validateRuntimeArgs, applyRuntimeArgs, runtimeArgKeysCollide, hashRuntimeArgs, } from "./pure/runtime-args.js";
22
22
  export { advanceRun } from "./pure/run-advance.js";
23
+ // ── Step-to-step yield carry (docs/work/khronoton-step-yield-carry) ──────────
24
+ // Only the typed error is public — `resolveYieldRefs`/`resolveSingleStepPayload`
25
+ // are internal resolution mechanics (consulted transparently by
26
+ // `resolvePlannerFor`/`runs-driver.ts`/`handlers/steps.ts`, never something an
27
+ // external caller builds a step against directly), matching every OTHER
28
+ // typed error this package throws (`RunAlreadyInFlightError`,
29
+ // `PlannerNotRegisteredError`, etc.) being public so a host can `instanceof`-
30
+ // check it from its own error handling.
31
+ export { YieldNotFoundError } from "./pure/yields.js";
23
32
  // ── Consolidated schema installer (T1.6) ─────────────────────────────────────
24
33
  export { installSchema } from "./schema.js";
25
34
  // ── Headless executor (Phase 3: build/sign/simulate/fire behind the seams) ────
@@ -48,15 +48,40 @@ export interface PlannedLeg {
48
48
  * A step planner: given the step row + the injected seams, decides the legs
49
49
  * to build for the step's current pass. An empty array means "nothing to do
50
50
  * this pass" — `handleReplanStep` treats that like a cleared barrier.
51
+ *
52
+ * A planner may ALSO return `{ legs, yield? }` instead of a bare array, to
53
+ * additionally report a value for `runs-driver.ts` to store into the run's
54
+ * yield pool (`docs/work/khronoton-step-yield-carry/design.md`'s "Producing
55
+ * a yield") — see `normalizePlannerResult` below. The bare-array return
56
+ * stays valid forever; none of the 5 existing built-ins that don't produce a
57
+ * yield (`evict`/`inject`/`unstall`/`stoa-unwrap`) are forced to change.
58
+ * Deliberately a bare, unnamed `yield` value here — the NAME a yield is
59
+ * stored under always comes from the consuming step's own `step.yield_as`,
60
+ * decided by whoever wrote the step, never by the planner itself.
61
+ */
62
+ export type StepPlanner = (step: CodexCronotonStepRow, ctx: PlannerCtx) => Promise<PlannedLeg[] | {
63
+ legs: PlannedLeg[];
64
+ yield?: unknown;
65
+ }>;
66
+ /**
67
+ * Normalize a `StepPlanner`'s return value to the `{ legs, yield? }` shape
68
+ * regardless of which form the planner actually returned — the SINGLE
69
+ * shared normalizer `runs-driver.ts` and `handlers/steps.ts` both call, so
70
+ * neither hand-rolls its own array-vs-object check.
51
71
  */
52
- export type StepPlanner = (step: CodexCronotonStepRow, ctx: PlannerCtx) => Promise<PlannedLeg[]>;
72
+ export declare function normalizePlannerResult(result: Awaited<ReturnType<StepPlanner>>): {
73
+ legs: PlannedLeg[];
74
+ yield?: unknown;
75
+ };
53
76
  /**
54
77
  * Register (or replace) a named step planner. A module that owns a planner
55
78
  * calls this at module-eval time so the registry is populated by the time
56
79
  * `handleReplanStep` consults it.
57
80
  */
58
81
  export declare function registerStepPlanner(name: string, planner: StepPlanner): void;
59
- /** Read a registered step planner by name, or `undefined`. */
82
+ /** Read a registered step planner by name, or `undefined` — including for a
83
+ * name colliding with an `Object.prototype` member, since `STEP_PLANNERS` is
84
+ * prototype-less (see its own doc comment above). */
60
85
  export declare function getStepPlanner(name: string): StepPlanner | undefined;
61
86
  /**
62
87
  * Resolve a `mode:'planner'` step's registered planner AND build the
@@ -69,12 +94,25 @@ export declare function getStepPlanner(name: string): StepPlanner | undefined;
69
94
  * Returns `undefined` for an unregistered `planner_name` — callers decide
70
95
  * how to report that (a thrown `PlannerNotRegisteredError` for the real
71
96
  * driver, a 404 for the standalone-fire route).
97
+ *
98
+ * Also resolves any `{"$yield": "<name>"}` placeholder in the step's
99
+ * `planner_params_json` against `yieldPool` BEFORE a caller ever invokes the
100
+ * planner (`docs/work/khronoton-step-yield-carry/design.md`'s "Consuming a
101
+ * yield") — returned as a shallow-cloned `resolvedStep` with that field
102
+ * replaced by the resolved JSON string, so `ouronet.aqp-inject` and every
103
+ * other planner keep calling `parseJson(step.planner_params_json, {})`
104
+ * exactly as they do today and simply receive already-resolved values; zero
105
+ * planner-side changes needed. `yieldPool` defaults to `{}`, so every
106
+ * pre-Wave-3 call site (passing only `(step, seams)`) is unaffected — a step
107
+ * with no `$yield` references anywhere resolves byte-identical to before
108
+ * this parameter existed.
72
109
  */
73
110
  export declare function resolvePlannerFor(step: CodexCronotonStepRow, seams: {
74
111
  runtime: ChainRuntime;
75
112
  resolver: KeyResolver;
76
113
  config?: Partial<Config>;
77
- }): {
114
+ }, yieldPool?: Record<string, unknown>): {
78
115
  planner: StepPlanner;
79
116
  plannerCtx: PlannerCtx;
117
+ resolvedStep: CodexCronotonStepRow;
80
118
  } | undefined;