@ancientpantheon/khronoton-core 0.12.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.
Files changed (68) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +8 -0
  3. package/dist/blockchain/stoachain.d.ts +1 -1
  4. package/dist/blockchain/stoachain.js +16 -1
  5. package/dist/{chunk-GIGLXIMC.js → chunk-A5YODPKQ.js} +820 -23
  6. package/dist/{chunk-KQZYMPZS.js → chunk-WKI52IPY.js} +1 -1
  7. package/dist/{context-CApk-LP4.d.ts → context-P-rCtBbJ.d.ts} +1 -1
  8. package/dist/handlers/execute.d.ts +12 -4
  9. package/dist/handlers/execute.js +42 -5
  10. package/dist/handlers/index.d.ts +2 -1
  11. package/dist/handlers/index.js +4 -1
  12. package/dist/handlers/read.d.ts +11 -0
  13. package/dist/handlers/read.js +65 -1
  14. package/dist/handlers/steps.d.ts +3 -0
  15. package/dist/handlers/steps.js +152 -0
  16. package/dist/hooks/index.d.ts +3 -3
  17. package/dist/hooks/index.js +2 -2
  18. package/dist/provider/index.d.ts +3 -3
  19. package/dist/provider/index.js +33 -2
  20. package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
  21. package/dist/server/executor.d.ts +14 -1
  22. package/dist/server/executor.js +144 -26
  23. package/dist/server/index.d.ts +12 -2
  24. package/dist/server/index.js +38 -1
  25. package/dist/server/loop.d.ts +17 -13
  26. package/dist/server/loop.js +19 -12
  27. package/dist/server/planners/evict.d.ts +20 -0
  28. package/dist/server/planners/evict.js +143 -0
  29. package/dist/server/planners/inject.d.ts +22 -0
  30. package/dist/server/planners/inject.js +120 -0
  31. package/dist/server/planners/registry.d.ts +118 -0
  32. package/dist/server/planners/registry.js +94 -0
  33. package/dist/server/planners/stoa-unwrap.d.ts +23 -0
  34. package/dist/server/planners/stoa-unwrap.js +204 -0
  35. package/dist/server/planners/stoa-wrap.d.ts +26 -0
  36. package/dist/server/planners/stoa-wrap.js +229 -0
  37. package/dist/server/planners/unstall.d.ts +25 -0
  38. package/dist/server/planners/unstall.js +135 -0
  39. package/dist/server/pure/run-advance.d.ts +76 -0
  40. package/dist/server/pure/run-advance.js +94 -0
  41. package/dist/server/pure/split-plan.d.ts +144 -0
  42. package/dist/server/pure/split-plan.js +362 -0
  43. package/dist/server/pure/yields.d.ts +57 -0
  44. package/dist/server/pure/yields.js +101 -0
  45. package/dist/server/resolvers.js +48 -6
  46. package/dist/server/runs-driver.d.ts +92 -0
  47. package/dist/server/runs-driver.js +582 -0
  48. package/dist/server/schema.d.ts +6 -2
  49. package/dist/server/schema.js +89 -1
  50. package/dist/server/seams.d.ts +28 -0
  51. package/dist/server/seams.js +4 -0
  52. package/dist/server/store/errors.d.ts +38 -0
  53. package/dist/server/store/errors.js +61 -0
  54. package/dist/server/store/index.d.ts +7 -2
  55. package/dist/server/store/index.js +8 -2
  56. package/dist/server/store/mappers.d.ts +11 -0
  57. package/dist/server/store/mappers.js +20 -0
  58. package/dist/server/store/runs.d.ts +233 -0
  59. package/dist/server/store/runs.js +341 -0
  60. package/dist/server/store/steps.d.ts +54 -0
  61. package/dist/server/store/steps.js +74 -0
  62. package/dist/server/store/yields.d.ts +46 -0
  63. package/dist/server/store/yields.js +73 -0
  64. package/dist/server/tick.d.ts +7 -0
  65. package/dist/server/tick.js +50 -1
  66. package/dist/server/types.d.ts +42 -3
  67. package/dist/ui/index.js +2 -2
  68. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,41 @@ 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
+
22
+ ## 0.13.0 — 2026-11-20
23
+
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.**
25
+
26
+ A cronoton has always been one scheduled Pact transaction. A workflow that genuinely needs several transactions in sequence — some of which fan out into N legs decided only at fire time (how many reward lanes need paying, how many stale member scores need repair) — had no way to express itself as a single schedulable unit. This release adds that as a new, fully additive capability alongside the existing one-shot cronoton; nothing about a plain cronoton's behavior changes.
27
+
28
+ - **Non-blocking submit, the keystone.** The scheduler's tick awaits a fire's confirmation inline inside a single `running`-boolean-guarded pass — fine for one transaction, impossible for a chained run (four evict legs awaited serially would freeze the *entire* scheduler, every cronoton, for up to twenty minutes). A new `"submit"` executor mode builds/signs/preflights/submits and returns immediately, never calling `listenWithTimeout`; a new optional `ChainClient.pollRequestKeys(keys, chainId)` seam polls many request keys per chain in one call (one request per chain per tick, not one per leg). `runFire`'s internals were extracted into a shared `submitTransaction` helper with zero change to `fire`'s own external behavior.
29
+ - **Schema: three new tables.** `codex_cronoton_steps` (a cronoton's static step definitions — `mode: 'single' | 'planner'`), `codex_cronoton_runs` (one run's lifecycle: `status`, `step_index`/`step_count`, `deadline_at`, `attempt`), and `codex_cronoton_run_legs` (one step's individual transactions: `status: 'pending' | 'submitted' | 'confirmed' | 'failed'`, plus a `claimed_at` lease column — see the concurrency fix below). A partial unique index self-blocks a second concurrent run per cronoton at the DB layer (`RunAlreadyInFlightError`, not a raw constraint leak); a leg row is written `pending` before it is ever submitted, mirroring the existing claim-before-fire discipline one level down.
30
+ - **Pure decision core.** `pure/run-advance.ts`'s `advanceRun(run, legs, now, policy)` is a stateless function deciding, from a run's and its legs' current state alone, one of six actions (`submit-leg`, `poll`, `advance-step`, `replan-step`, `fail-run`, `wait`) — barrier-met-before-deadline ordering, serial-vs-parallel fan handling, and the "3 of 4 legs confirm, one fails" re-plan-only-once-fully-resolved rule are all independently unit-tested branches, plus a cross-cutting invariant test proving a run can never advance past an unconfirmed leg.
31
+ - **The driver.** `runs-driver.ts`'s `driveRunOnce`/`advanceInFlightRunsOnce` execute `advanceRun`'s actions against the store and chain, wired into `startKhronotonLoop` as a third pass alongside the existing tick and manual-batch passes. A newly-due chained cronoton gets its run created and step 0 submitted within the same tick pass that created it, not merely at the next loop interval; the schedule's own `next_fire_at` keeps advancing independently of a long-lived run's self-block, by design — two independent clocks, not one gated by the other.
32
+ - **The `StepPlanner` registry + five built-in planners.** `registerStepPlanner`/`getStepPlanner` (a plain module-level map, mirroring the existing server-resolver registry) let a `mode: 'planner'` step fan out into N legs decided fresh at fire time, ported faithfully from OuronetUI's real transaction-construction logic: `ouronet.aqp-evict` (reads an on-chain evict plan, tries one `CC_FullEvictRewards` leg, fans out to one `CC_EvictSingleReward` leg per beneficiary only on a genuine gas-ceiling refusal), `ouronet.aqp-inject` (tries `CC_InjectFinalize` then `CC_Inject`, and — unlike the human-facing UI it's ported from — never refuses, propagating a genuine error instead since there's no human to hand a refusal to), `ouronet.aqp-unstall` (fans stale-member-score repair into `CCp_FvtFixSlice` batches via a newly-ported generic gas-probe-and-pack algorithm, `pure/split-plan.ts`), and `ouronet.stoa-wrap`/`ouronet.stoa-unwrap` (built as capability-construction built-ins, not fan-out built-ins — getting a Pact signer capability's scope right by hand is the dangerous part, independent of leg count; `stoa-wrap` reads the patron's live balance rather than trusting any inter-step-carried value). 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` placeholder; only a signer's capability line (which Pact's own signing mechanism has no env-data equivalent for) is the one documented, shape-guarded exception.
33
+ - **A run can now genuinely re-plan after a failure**, not just on its first entry — a prerequisite fix (generation-scoped legs, using the previously-unwritten `codex_cronoton_run_legs.attempt` column as a generation marker plus a new `bumpRunAttempt` store write) was needed because every planner driven before this fix would otherwise permanently defeat the barrier check the instant any single leg ever failed once — a step could never advance again, for any future attempt. This retroactively corrected a latent gap in the already-shipped `ouronet.aqp-evict` re-plan path too, not just the newly-added planners.
34
+ - **New per-run/per-step observability and standalone-fire routes.** `executeNow` now recognizes a chained row (≥1 `codex_cronoton_steps` row), starts a real run, and reports HTTP 409 (not a crash) when one is already in flight — an explicit on-demand request deserves to know it didn't happen, unlike the scheduler's own silent tick-skip. `adaptMultiTxSummary` now reads an optional per-batch `ok` field (recognizing real booleans and common stringified/numeric truthy forms, never a naive `Boolean()` coercion) to report genuine multi-tx failure instead of hardcoding success — strictly additive, falling back to today's behavior when no batch supplies the field. A new standalone `POST /cronotons/:id/steps/:index/{simulate,fire}` lets an operator preview or fire one step of a chained cronoton by index, in isolation from the run/leg lifecycle (deliberately never writing a run/leg row), behind the same confirm gate `executeNow` uses. New `GET /[id]/runs` (paginated) 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 history visible through this package's own surface for the first time.
35
+ - **A genuine concurrency race was found and fixed in already-shipped Phase 3 code.** Before this release's final phase, `driveRunOnce` was only ever invoked from inside the scheduler loop's single-process re-entrancy guard; wiring `executeNow` to call it directly from an HTTP handler made a previously-deferred, previously-documented gap real: the background loop's sweep could pick up the same newly-created run and both callers could submit the same leg before either write landed. Fixed with a genuine claim-before-submit step — a new nullable `claimed_at` column 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 a dedicated end-to-end test driving two concurrent `driveRunOnce` calls on the same run and asserting the chain submit happens exactly once.
36
+ - **A follow-up cross-phase review, run after all six phases shipped, found and fixed one more CRITICAL and several more real bugs.** A planner throw on a run's very first pass (every real planner's first action is a live chain read, so a bad `planner_params_json`, a genuine Pact failure, or a transient chain outage all trigger this) left the run stuck non-terminal forever: `deadline_at` is never stamped before that point, so the deadline-based recovery path could never engage, and no code path ever marked the run terminal — permanently occupying that cronoton's one-run-at-a-time slot with no recovery short of direct DB surgery. Fixed by terminalizing the run on an unrecoverable first-entry throw, while carefully preserving the existing `maxReplanAttempts` retry budget for a transient failure during a genuine later re-plan (a first attempt at this fix was itself too broad — see below). The same round also found `runLegsHandler` leaking real transfer amounts, account identifiers, and Pact capability lines through the read-tier `GET /[id]/runs/[runId]/legs` route (now redacted, mirroring `toPublicCronotonView`'s field-by-field convention) and an uncached live `getBlockGasLimit()` fetch repeated on every leg submit and planner probe within one driver pass (now cached per chain with a short TTL) — both HIGH. 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 any transient re-plan error — both fixed by narrowing the catch to only the genuinely-unrecoverable first-entry case.
37
+
38
+ Reviewed via nectar across all seven phases (base/Phase 0+1, Phase 2, Phase 3, Phase 4, Phase 4.1, Phase 4b, Phase 5) plus one additional cross-phase round after all six shipped — **33 review rounds total, 73 CONFIRMED findings fixed (or resolved via documentation where that was the proportionate response), 4 REFUTED on adversarial validation, 2 downgraded to STYLISTIC.** Standout findings: two **CRITICAL** findings (a missing Pact module-namespace prefix; a Pact-code-injection vulnerability via unescaped, unvalidated chain-read fields spliced directly into signed Pact source) were caught in round 1 of the `ouronet.aqp-evict` planner's own review, before ever shipping; a **HIGH** finding in Phase 5 caught `fireStep` firing real Pact code against a paused or terminal cronoton, bypassing the guard every other fire-capable route already enforces; a second **HIGH** in that phase is the `driveRunOnce` concurrency race described above. The follow-up cross-phase round then found a third **CRITICAL** (the stuck-run bug above) plus a **HIGH** transaction-detail leak through `runLegsHandler` — and, reviewing its own CRITICAL fix a second time, a fourth **CRITICAL** regression in that very fix (the overly-broad catch). One further real bug (floating-point noise leaking into a signed capability line and payload for realistic token balances) was caught only by behavioral verification against the real built artifact using a real measured value — no lens 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 (`-phase-2`, `-phase-3`, `-phase-4`, `-phase-4.1`, `-phase-4b`, `-phase-5`), and `docs/work/khronoton-chained-runs-cross-phase-review/review.md`.
39
+
40
+ **1265 specs pass.**
41
+
7
42
  ## 0.12.0 — 2026-11-11
8
43
 
9
44
  **MINOR — an opt-in public observability surface: any codex-cronoton can now expose a sanitized, token-gated, unauthenticated read-only view of its schedule, health, and fire history.**
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.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
+
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.**
12
+
9
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.**
10
14
 
11
15
  **`0.11.0` on public npmjs** — **MINOR.** Released 2026-09-17. Two independent handoffs, shipped together. **Editor Save:** an always-visible edit-mode `SaveBar` (Simulate + Save changes + live status) now renders on every tab, gated on the edited row having actually loaded so it can never fire a Simulate against a blank default state; the Execute tab's own Commit button is edit-aware ("Save changes"); a new shared `useCommitGate(state, sim)` hook keeps both surfaces reading the identical commit body and gate, computed once. **Auto self-calibrating gas:** `autoGasLimit` now defaults to `true` for new cronotons; `ChainClient` gains optional `preflightRead` (accurate gas via the SDK's preflight mode, replacing `dirtyRead`'s execution-only measurement for AUTO fires) and `getBlockGasLimit` (a live block-ceiling fetch with a static fallback); a transaction whose measured gas exceeds the resolved ceiling is now refused with a structured error — never silently capped or submitted — for both AUTO and MANUAL fires, with the ceiling itself validated against `NaN`/non-finite/non-positive values before use. **980 specs pass.**
@@ -356,6 +360,10 @@ npm install @ancientpantheon/khronoton-core
356
360
 
357
361
  ## Version history
358
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
+
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.**
366
+
359
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.**
360
368
 
361
369
  **v0.11.0** — Discoverable edit-mode Save + auto self-calibrating gas. Two independent handoffs built and shipped together. **Editor Save.** Editing an existing cronoton had no discoverable Save — the only action was the "Commit Codex Cronoton" button on the last (Execute) tab, silently disabled under AUTO gas until a Simulate ran, with the reason invisible from any other tab. Adds an always-visible edit-mode `SaveBar` (`ui/builder/SaveBar.tsx`) — Simulate, Save changes, and a live status line — rendered above the Pact editor/tabs on every tab, gated on `Builder.tsx`'s `editReady` (the edited row having actually finished loading) so it can never fire a Simulate against the blank default `makeEmptyBuilderState()` during the load window. The Execute tab's own Commit button is now edit-aware ("Save changes" / "Saving…"); create mode is byte-identical to before. A new shared `useCommitGate(state, sim)` hook (`ui/builder/use-commit-gate.ts`), extracted from `ExecuteTab.tsx`'s own prior inline logic, is called ONCE in `Builder.tsx` and threaded as `commit`/`gate` props to both `SaveBar` and `ExecuteTab` — no risk of two independent `builderToCommit`/`canCommit` call sites drifting apart, and no duplicate computation on every keystroke when both are mounted. Both of `SaveBar`'s buttons are `canMutate(access)`-gated in their CLICK HANDLERS, not just their `disabled` attribute (a directly-dispatched click event still reaches a React handler regardless of the DOM disabled state). **Auto self-calibrating gas.** Khronoton transactions defaulted to a fixed, manually-set gas limit, so fires over-reserved gas wildly — a real pool-payout fire measured 594 gas used against a 600,000 limit. `makeEmptyBuilderState()`'s `config.autoGasLimit` now defaults to `true`. `ChainClient` (`server/seams.ts`) gains two new optional methods: `preflightRead` — implemented in `blockchain/stoachain.ts` via the SDK's raw `local(tx, {preflight:true, signatureVerification:false})`, NOT its `.preflight` convenience alias (which also forces `signatureVerification:true`) — measures the TRUE gas including the transaction-size charge that plain `dirtyRead` omits; `getBlockGasLimit` does a best-effort `/config` fetch (mirroring OuronetUI's `gas-limits.ts`, ported without its browser-oriented module-level mutable-singleton cache — this package fetches fresh per fire instead, since a Node server core handling concurrent fires can't safely share that kind of global state) falling back to the existing static `AUTO_GAS_CEILING` on any failure. `executor.ts`'s `runSimulate`/`runFire` were reordered so the `ChainClient` is constructed BEFORE ceiling resolution (ceiling resolution needs it) — a real sequencing fix, not just an addition. AUTO-gas fires now calibrate from `preflightRead`; a runtime missing it hard-throws on an AUTO-gas fire only (mirroring the 0.9.0 `gasMeta` precedent — silent fallback would ship the exact over-reservation bug this exists to fix), while a MANUAL-gas fire on the same un-upgraded runtime is completely unaffected. A new refuse-unmineable check returns a structured `{ok:false, error}` — never a silent cap, never a submit — when measured gas exceeds the resolved ceiling, for BOTH AUTO and MANUAL fires. The ceiling itself (from either the live fetch or an explicit `Config.autoGasCeiling` override) is validated via a new `isSaneCeiling` check (`Number.isFinite && > 0`) before use — `NaN` in particular would otherwise silently defeat the refuse check entirely, since every `gasUsed > NaN` comparison is `false` in JS. Reviewed via nectar (2 rounds, 5 lenses then a targeted 2-lens re-pass, adversarial validation throughout): 9 CONFIRMED findings fixed, including two initially-HIGH findings (the `SaveBar` pre-load readiness gap; its originally-unguarded Simulate click) validated down to MEDIUM once the actual blast radius was traced against the code (Save itself stayed correctly disabled during the load window; the server independently re-authorizes via its own `withConfirm`/`auth.requireConfirm` gate regardless of what the UI allows). Full history in `docs/work/khronoton-editor-save-and-auto-gas/review.md`. Released 2026-09-17. **980 specs pass.**
@@ -1,4 +1,4 @@
1
- import { C as ChainRuntime } from '../seams-DUtxDw_U.js';
1
+ import { C as ChainRuntime } from '../seams-Co8Tq4ka.js';
2
2
 
3
3
  /**
4
4
  * Consumer-facing knobs for {@link createStoachainRuntime}. Every field is
@@ -23,7 +23,7 @@ async function createStoachainRuntime(config) {
23
23
  const namespace = config?.namespace ?? ouronetConstants.KADENA_NAMESPACE;
24
24
  const gasStationAccount = config?.gasStationAccount ?? ouronetConstants.STOA_AUTONOMIC_OURONETGASSTATION;
25
25
  const nodeBaseUrl = config?.nodeBaseUrl;
26
- const getPactUrl = nodeBaseUrl ? (chainId) => `${nodeBaseUrl}/chainweb/0.0/${networkId}/chain/${chainId}/pact` : constants.getPactUrl;
26
+ const getPactUrl = nodeBaseUrl ? (chainId) => `${nodeBaseUrl}/chainweb/0.0/${networkId}/chain/${encodeURIComponent(chainId)}/pact` : constants.getPactUrl;
27
27
  return {
28
28
  Pact: client.Pact,
29
29
  // The SDK client is no longer returned by identity: it's wrapped so the
@@ -50,6 +50,21 @@ async function createStoachainRuntime(config) {
50
50
  } catch {
51
51
  return AUTO_GAS_CEILING_FALLBACK;
52
52
  }
53
+ },
54
+ pollRequestKeys: async (keys, chainId) => {
55
+ try {
56
+ if (!real.getStatus || keys.length === 0) return {};
57
+ const raw = await real.getStatus(
58
+ keys.map((requestKey) => ({ requestKey, chainId, networkId }))
59
+ );
60
+ const out = {};
61
+ for (const [key, entry] of Object.entries(raw ?? {})) {
62
+ out[key] = { result: entry.result, reqKey: entry.reqKey };
63
+ }
64
+ return out;
65
+ } catch {
66
+ return {};
67
+ }
53
68
  }
54
69
  };
55
70
  }),