@ancientpantheon/khronoton-core 0.10.0 → 0.12.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,34 @@ 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.12.0 — 2026-11-11
8
+
9
+ **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.**
10
+
11
+ Today a cronoton's state is only visible through the authenticated admin surface (`listHandler`/`getHandler`/`firesHandler` behind `withRead` + the host's own `AuthSeam`). Nothing lets a host expose one cronoton's state to an unauthenticated, cross-origin caller — the concrete driver is embedding a mint's next-fire time and recent executions in a public-facing page — but the capability is general: every cronoton can opt in, not just one.
12
+
13
+ - **Schema.** Two new `codex_cronotons` columns: `public_token TEXT` (unique, nullable) and `public_observable INTEGER NOT NULL DEFAULT 0` (off by default). This is the first time `installSchema` has needed to add a column to an **already-provisioned** database, not just a fresh install — SQLite has no `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`, so `installSchema` gains a small reusable `ensureColumn(db, table, column, columnDefSql)` helper (`PRAGMA table_info` → conditional `ALTER TABLE ADD COLUMN`) called once per column, plus a `CREATE UNIQUE INDEX IF NOT EXISTS` on `public_token` (SQLite's unique index already permits multiple `NULL`s, so non-observable rows never collide). Both a fresh install and an existing host's DB go through the identical call.
14
+ - **New `server/store/public.ts` surface.** `setPublicObservable(id, { observable, regenerate? }, dep)` toggles the flag and mints a token lazily — once, the first time a row is made observable; stable across an observable → non-observable → observable toggle (no silent rotation), with an explicit `regenerate: true` the only way to mint a new one. `getCodexCronotonByPublicToken(token, dep)` resolves a row by token, returning `null` for both an unknown token and a known-but-non-observable one — the two cases are never distinguishable, by design. `getCronotonFireCounts(id, dep)` reports whole-history aggregates (`fired`/`succeeded`/`failed`, `lastSuccessAt`/`lastFailureAt`, and a `currentFailStreak` counting only the consecutive failures immediately preceding the most recent fire). `deriveCronotonHealth({ currentFailStreak, isOverdue })` is a pure `"healthy" | "degraded" | "down"` traffic-light rule. `toPublicCronotonView(row, counts, firesPage, now?)` is the sanitizing projector — it builds the public DTO field-by-field and never spreads the row or a fire, 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 leak through it; the public token is the only public identifier.
15
+ - **New `handlers/public.ts` → `publicCronotonHandler`.** A framework-agnostic `GET /<token>` handler, added to the barrel, that is **unauthenticated by design**: it never calls the host's `ctx.auth`/`AuthSeam` at all — a different trust tier than the admin read/confirm gates, gated purely on token validity plus the `public_observable` flag. Returns 404 for an unknown or non-observable token (identical shape, never distinguishable), 200 with the sanitized view otherwise. Paginates over the cronoton's **complete** fire history (not a fixed "last 20") via `limit`/`offset`, clamped with the same 1..100/default-50 bounds the admin `firesHandler` already uses.
16
+
17
+ New public surface is entirely additive; no existing export, column default, or response shape changes for a non-opted-in cronoton.
18
+
19
+ 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`.
20
+
21
+ **1027 specs pass.**
22
+
23
+ ## 0.11.0 — 2026-09-17
24
+
25
+ **MINOR — a discoverable edit-mode Save affordance, and auto self-calibrating gas as the default for every new cronoton.**
26
+
27
+ Two independent handoffs, built and shipped together. **(1) Editor Save.** Editing an existing cronoton had no discoverable Save — the only save action was the "Commit Codex Cronoton" button on the last (Execute) tab, silently disabled under AUTO gas until a Simulate ran, with no explanation visible from any other tab. Adds an always-visible edit-mode **`SaveBar`** — Simulate, Save changes, and a live status line — rendered above the Pact editor/tabs on every tab, gated on the edited row having actually loaded (`editReady`) so it can never fire a Simulate against a blank default state during the load window. The Execute tab's own Commit button is now edit-aware ("Save changes" / "Saving…"); create mode is unaffected. A new shared `useCommitGate(state, sim)` hook (called once in `Builder.tsx`, threaded as props) keeps `SaveBar` and `ExecuteTab` reading the identical commit body and gate — no risk of two independent `builderToCommit`/`canCommit` call sites drifting apart, and no duplicate computation on every keystroke. `SaveBar`'s Save AND Simulate buttons are both `canMutate(access)`-gated in their click handlers, not just their `disabled` attribute.
28
+
29
+ **(2) 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()` now defaults `autoGasLimit` to `true`. `ChainClient` gains two new optional methods: `preflightRead` (the SDK's `local` with `{preflight:true, signatureVerification:false}` — accurate gas including the transaction-size charge that plain `dirtyRead` omits) and `getBlockGasLimit` (a live `/config` fetch, best-effort with the existing static fallback). AUTO-gas fires now calibrate from `preflightRead` instead of `dirtyRead`; a runtime missing it hard-throws on an AUTO-gas fire (mirroring the 0.9.0 `gasMeta` precedent) while a MANUAL-gas fire on the same runtime is completely unaffected. A new refuse-unmineable check returns a structured failure — never a silent cap or submit — when measured gas exceeds the resolved ceiling, for both AUTO and MANUAL fires. The ceiling itself is validated (`Number.isFinite && > 0`) before use, so a buggy adapter returning `NaN`/`0`/negative can never silently defeat the refuse check.
30
+
31
+ Reviewed via nectar (2 rounds, 5 lenses then a targeted 2-lens re-pass, adversarial validation throughout): 9 CONFIRMED findings fixed — two initially-HIGH findings (SaveBar's pre-load readiness gap; its unguarded Simulate click) were validated down to MEDIUM once the actual blast radius was traced (Save itself stayed correctly disabled; the server has its own independent auth gate); the rest were MEDIUM/LOW test-coverage, duplication, and stale-doc gaps. Zero REFUTED, zero STYLISTIC. Full history in `docs/work/khronoton-editor-save-and-auto-gas/review.md`.
32
+
33
+ **980 specs pass.**
34
+
7
35
  ## 0.10.0 — 2026-09-08
8
36
 
9
37
  **MINOR — the Builder's absolute "Gas Price (ANU)" field is gone; a cronoton now always pays the live network floor plus an optional priority buffer.**
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.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
+
11
+ **`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.**
12
+
9
13
  **`0.10.0` on public npmjs** — **MINOR.** Released 2026-09-08. The Builder's absolute "Gas Price (ANU)" field is gone: the UI now shows a read-only, live-refreshing "Live Network Floor" plus an editable "Priority Buffer (ANU above floor)" (default 0), and every fire prices as `liveFloor(creationTime) + buffer`. New optional `CodexTxConfig.gasPriceBufferAnu` (absent/pre-migration rows default to 0, self-healing with no DB migration); `gasPrice` stays, `@deprecated`, for reading historical rows. `ChainRuntime.gasMeta` gains an optional 2nd `bufferAnu` param (non-breaking) — the adapter sums floor+buffer **in ANU** before the one conversion, not two summed STOA floats. A negative/non-finite buffer can never underprice a fire — enforced at three layers: client `validateConfig`, the store's `commitCodexCronoton`/`editCodexCronoton` (reject before any write), and the seam's own defensive clamp. New `useLiveGasFloor()` hook polls every 30s plus visibilitychange/focus. `BuilderConfig.gasPriceAnu` and `CommitGateOptions.minGasPriceAnu` are **removed** (not deprecated-in-place) — both lost all meaning once there's no absolute price to floor-check. **938 specs pass** (+5 real-runtime integration specs).
10
14
 
11
15
  **`0.9.0` on public npmjs** — **MINOR.** Released 2026-09-07. Scheduled transactions are now priced against the chain's **live** gas floor at fire time instead of a static value stored at creation time. A cronoton's `gasPrice` was persisted once at creation and read back verbatim on every tick, so as chainweb's post-fork Yin Engine floor rises, a long-lived cronoton silently drifts below it and its fire is rejected — with nobody watching a 3am tick. (Live, not theoretical: at release the floor was **11,569 ANU** against a stored default of **10,000**.) Adds an **optional** `ChainRuntime.gasMeta(floorAnu)` seam returning `{ creationTime, gasPrice }` from one clock read; the stored price becomes a **floor an operator can raise, never a cap**, so existing rows **self-heal with no migration**. `creationTime` is now stamped explicitly from the same call that produced the price (it was previously auto-stamped by the Pact builder from a second, independent clock read), and the AUTO-gas rebuild re-derives both fresh. Transaction meta uses the precision-safe `anuToStoaNumber` rather than float division. A StoaChain fire on a runtime lacking `gasMeta` **fails loudly** rather than silently reusing the stale price. Requires a coordinated bump of `@stoachain/stoa-core@^4.4.0`, `@stoachain/kadena-stoic-legacy@^4.4.0`, `@ouronet/ouronet-core@^4.6.0`. **907 specs pass** (+5 real-runtime integration specs).
@@ -238,6 +242,112 @@ This bump ships the engine only. Framework-agnostic HTTP handlers (create/edit/l
238
242
 
239
243
  The `/server` subpath's CJS `require` condition relies on Node's `require(esm)` support (Node **≥ 20.19 / ≥ 22.12**), the same mechanism as the root's 0.1.1 `require` condition — so the effective Node floor for CommonJS consumers is ≥ 20.19. The package `engines` field stays `>=20` (unchanged), matching the root.
240
244
 
245
+ ## Public observability (`public_token` / `publicCronotonHandler`) — since 0.12.0
246
+
247
+ Every cronoton can opt into a **public, unauthenticated, read-only** view of
248
+ its own state — schedule, status, health, and complete fire history — for a
249
+ host that wants to embed "next mint at…" + recent executions on a
250
+ public-facing page without exposing its authenticated admin surface at all.
251
+ **Off by default.** Nothing is public until an admin explicitly flips it on
252
+ for that one cronoton.
253
+
254
+ **1. Opt a cronoton in** (admin-side, through your own authenticated route —
255
+ this call has no auth of its own, same as every other `/server` store
256
+ function):
257
+
258
+ ```ts
259
+ import { setPublicObservable } from '@ancientpantheon/khronoton-core/server';
260
+
261
+ const { publicToken } = setPublicObservable(cronotonId, { observable: true }, { db });
262
+ // publicToken is minted ONCE, the first time a row goes observable, and is
263
+ // STABLE across later observable:false -> observable:true toggles (so an
264
+ // embed URL built from it never has to be re-minted). Pass
265
+ // { observable: true, regenerate: true } to force a fresh token instead
266
+ // (e.g. if the old one leaked). { observable: false } hides the cronoton
267
+ // again WITHOUT clearing the stored token, so re-enabling reuses it.
268
+ ```
269
+
270
+ Build your public embed URL from `publicToken` — it's an opaque,
271
+ 160-bit (`crypto.randomBytes(20)`, base64url) string, not the cronoton's
272
+ internal `id`. The internal `id` never appears anywhere in the public
273
+ surface.
274
+
275
+ **2. Mount the route** (host-side, any router — this one handler is the
276
+ entire public surface):
277
+
278
+ ```ts
279
+ import { publicCronotonHandler } from '@ancientpantheon/khronoton-core/handlers';
280
+
281
+ // e.g. a Next.js API route: pages/api/public/cronoton/[token].ts
282
+ export default async function handler(req, res) {
283
+ const result = await publicCronotonHandler(
284
+ { db, runtime, resolver, auth: yourAuthSeam }, // auth is REQUIRED by the
285
+ // HandlerContext type but
286
+ // is NEVER actually called
287
+ // by this one handler —
288
+ // any AuthSeam satisfies it
289
+ { params: { token: req.query.token }, query: req.query },
290
+ );
291
+ // YOUR responsibility, not this package's: Cache-Control + CORS.
292
+ res.setHeader('Cache-Control', 'public, max-age=30');
293
+ res.setHeader('Access-Control-Allow-Origin', '*'); // or your embed's origin
294
+ res.status(result.status).json(result.body);
295
+ }
296
+ ```
297
+
298
+ Unlike every other handler in `/handlers`, `publicCronotonHandler`
299
+ **deliberately never calls `ctx.auth`** — that's not an oversight, it's the
300
+ whole point: this route's trust boundary is "does this token resolve to an
301
+ observable row," entirely independent of whatever your admin `AuthSeam`
302
+ would otherwise require. An unknown token and a known-but-currently-disabled
303
+ token return the **identical** `404 { error: "not found" }` — the two cases
304
+ are indistinguishable on purpose, so a probing request can never learn
305
+ whether a given token ever existed.
306
+
307
+ **3. The response**, for a known, currently-observable token:
308
+
309
+ ```jsonc
310
+ {
311
+ "ok": true,
312
+ "name": "DailyStoicismMint",
313
+ "description": "Mints the daily Stoicism allotment",
314
+ "status": "active", // active | paused | completed | error
315
+ "schedule": { "mode": "daily-at-utc", "humanText": "Daily at 18:00 UTC" },
316
+ "triggerOnly": false, // true = fires on demand (event/HMAC/runtime-arg), no timer
317
+ "nextFireAt": "2026-11-11T18:00:00.000Z",
318
+ "lastFireAt": "2026-11-10T18:00:00.000Z",
319
+ "isOverdue": false, // active + scheduled + nextFireAt already passed
320
+ "since": "2026-01-01T00:00:00.000Z", // row's created_at
321
+ "counts": {
322
+ "fired": 42, "succeeded": 41, "failed": 1,
323
+ "lastSuccessAt": "...", "lastFailureAt": "...",
324
+ "currentFailStreak": 0, // consecutive failures ending at the most recent fire
325
+ "successRatePercent": 98
326
+ },
327
+ "health": "healthy", // healthy | degraded | down — derived traffic light
328
+ "fires": {
329
+ "page": [
330
+ { "firedAt": "...", "status": "success", "chainId": "0", "requestKey": "...", "txKeys": [], "recoveredAt": null, "mode": "live" }
331
+ ],
332
+ "total": 42, "limit": 50, "offset": 0 // ?limit=&offset= page the COMPLETE history, not just "last 20"
333
+ }
334
+ }
335
+ ```
336
+
337
+ **Never present, under any circumstances:** `pact_code`, `payload_json`,
338
+ `signers_json`, `gas_payer_json`, `server_resolver`, `created_by`,
339
+ `config_json`, a fire's raw `errorMessage`/`chainResponse`, or the internal
340
+ row `id`. A fire's `status` already says `"failure"` when relevant — no raw
341
+ error text ever ships alongside it. See
342
+ `src/server/store/public.ts`'s `toPublicCronotonView` for the one place this
343
+ guarantee is enforced (it builds the response field-by-field and never
344
+ spreads the underlying row/fire objects).
345
+
346
+ `health` is a simple derived traffic light, not a new source of truth:
347
+ `"down"` once `currentFailStreak` hits 3, `"degraded"` at 1–2 or whenever
348
+ `isOverdue` is true, `"healthy"` otherwise — call `deriveCronotonHealth`
349
+ yourself if you need the same rule outside this response shape.
350
+
241
351
  ## Install
242
352
 
243
353
  ```bash
@@ -246,6 +356,10 @@ npm install @ancientpantheon/khronoton-core
246
356
 
247
357
  ## Version history
248
358
 
359
+ **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
+
361
+ **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.**
362
+
249
363
  **v0.10.0** — Locked live-floor gas + priority buffer. 0.9.0 made the executor floor a *stored* absolute price against the live Yin Engine floor so a fire could no longer underprice, but the Builder UI still framed gas price as something an operator *sets* — the wrong model for a recurring transaction, since any absolute number typed today is guaranteed to go stale as the live floor keeps rising every ~3h. This finishes the redesign: the UI shows a read-only, live-refreshing "Live Network Floor" display plus an editable "Priority Buffer (ANU above floor)" (default 0), and every fire prices as `liveFloor(creationTime) + buffer`, derived fresh at build time — never a cached/stored absolute value. **Schema.** `CodexTxConfig` gains optional `gasPriceBufferAnu`; `gasPrice` stays, `@deprecated`, read-only, so historical `config_json` still parses — absence (every pre-migration row) defaults to 0, self-healing with no DB migration. **Seam.** `ChainRuntime.gasMeta(floorAnu, bufferAnu?)` — the buffer is a new optional 2nd parameter (non-breaking: TypeScript accepts a shorter existing implementation as satisfying the widened optional signature). The adapter (`blockchain/stoachain.ts`) sums `floorAnu + bufferAnu` **in ANU**, inside the adapter, before the **one** `anuToStoaNumber` conversion at the end — summing two independently-converted STOA floats instead produces a different serialized value in roughly 1 in 5 floor/buffer pairs, reintroducing the exact precision bug 0.9.0 fixed. `buildTransaction` always calls `gasMeta(0, config.gasPriceBufferAnu ?? 0)` now — there is no more stored absolute value to raise to a floor, so the seam's first argument is always 0. **Defense in depth.** A negative or non-finite buffer can never underprice a fire, enforced at three independent layers: `ui/builder-state.ts`'s `validateConfig` blocks commit client-side; `server/store/cronoton.ts`'s `commitCodexCronoton`/`editCodexCronoton` reject a present-and-invalid `gasPriceBufferAnu` before any write, so a caller reaching the store directly (bypassing the Builder UI) can't persist a row that silently underprices every future fire; and `blockchain/stoachain.ts`'s `gasMeta` clamps a bad buffer to 0 as a third line of defense for any `CodexTxDefinition` built outside the store entirely. **Live display.** New `useLiveGasFloor()` hook (`ui/builder/live-gas-floor.ts`) polls the live floor every 30s plus a `visibilitychange`/`focus` refresh — browsers throttle `setInterval` in backgrounded tabs, and this Builder screen is routinely left open for hours — called once in `Builder.tsx`, threaded to `ConfigTab` and `ExecuteTab`. **Precision fix applied a second place.** `ui/tx-size.ts`'s size estimator now uses the same floor+buffer-summed-in-ANU-then-converted-once formula the executor uses, instead of the deprecated absolute `gasPrice`. **Breaking at the UI-type layer.** `BuilderConfig.gasPriceAnu` and `CommitGateOptions.minGasPriceAnu` are **removed**, not deprecated-in-place — both lose all meaning once there is no absolute price to floor-check against, and keeping them would be actively misleading; `CodexTxConfig` itself stays additive. Reviewed via nectar across 3 rounds (5 lenses each, adversarial validation): round 1 found and fixed a HIGH gap (server-side validation of the buffer was entirely absent) plus 5 lower-severity test-coverage/UI gaps; round 2 re-verified those fixes and caught 3 more small issues (a misleading UI label, duplicated validation logic, a test-loop robustness nit); round 3 caught one last barrel-export asymmetry — all fixed, full history in `docs/work/gas-price-buffer/review.md`. Released 2026-09-08. **938 specs pass** (+5 real-runtime integration specs).
250
364
 
251
365
  **v0.9.0** — Live gas floor at fire time. `buildTransaction` priced every fire off `definition.config.gasPrice`, a plain ANU number persisted in `codex_cronotons` at creation time and read back verbatim on every tick (`server/tick.ts`, `server/store/mappers.ts`) — never re-derived. Post-fork, chainweb-node validates a signed transaction's price against the rising Yin Engine floor **as of that transaction's own `creationTime`**, so a cronoton created at the builder's 10,000 ANU default is already underpriced and drifts further as it ages; because this is unattended automation, the rejection surfaces at 3am with nobody watching. **The seam.** `ChainRuntime` gains an **optional** `gasMeta(floorAnu): { creationTime, gasPrice }`. Optional keeps the package chain-POLYGLOT and `@stoachain/*` an optional peer dependency — a chain without a rising floor omits it — but the executor **hard throws** when a StoaChain fire finds it missing, because a silent fallback to the stored value would ship the original bug to anyone who did not notice they must upgrade their adapter. In `fire` mode that throw is caught by the existing F-002 wrapper and returned as a structured `{ ok: false, error }`, so a one-time entry still records its spent attempt instead of re-firing forever. **Floor, not cap.** The implementation returns `max(storedAnu, minGasPriceAnu(creationTime))`, so an operator may still price above the minimum and existing stored rows self-heal with **no database migration**. **One clock read.** `setMeta` previously omitted `creationTime` entirely, letting the Pact builder auto-stamp its own at `createTransaction()` — an independent second read the price no longer corresponded to. Both fields now come from a single `stoaGasMeta()`-derived call, and the AUTO-gas calibrated rebuild+re-sign re-enters the seam rather than reusing the pre-flight values, so the two builds cannot straddle a 3-hour tick boundary and underprice the transaction that actually ships (pinned by a regression spec that fails if the call is hoisted out of `buildTransaction`). **Precision.** Transaction meta now converts via `anuToStoaNumber` (exact padded-decimal) instead of `anuToStoa` (float division), which upstream documents as unsafe for a value chainweb hashes and validates exactly; the same fix lands in `ui/tx-size.ts`'s fee meter, whose purpose is predicting the real signed transaction's byte size. **Builder gate.** `validateConfig` accepts `CommitGateOptions.minGasPriceAnu` in place of a hardcoded `>= 10000` check that accepted already-underpriced values, and names the applied floor in its message; omitting it falls back to the genesis floor, under-rejecting rather than over-rejecting since the executor raises the price at fire time regardless. **Boundary.** `blockchain/stoachain.ts` is the only module that knows the Yin Engine exists, wrapping `@stoachain/stoa-core/gas` rather than reimplementing a formula already independently reimplemented four times across the ecosystem; `/server` stays free of any `@stoachain/*` import. Requires a coordinated dependency bump — stoa-core 4.4.0 peer-pins kadena-stoic-legacy 4.4.0 exactly, and only ouronet-core 4.6.0 accepts stoa-core 4.4.0, so the three move together. All new surface (`StoaGasMeta`, `ChainRuntime.gasMeta`, `CommitGateOptions.minGasPriceAnu`) is additive. Released 2026-09-07. **907 specs pass** (+5 real-runtime integration specs).
@@ -1,26 +1,5 @@
1
- import { C as ChainRuntime } from '../seams-BL_ntGK_.js';
1
+ import { C as ChainRuntime } from '../seams-DUtxDw_U.js';
2
2
 
3
- /**
4
- * `@ancientpantheon/khronoton-core/blockchain/stoachain` — the StoaChain edge.
5
- *
6
- * khronoton is chain-POLYGLOT, not chain-agnostic: the root `.` schedule engine
7
- * and the `/server` tick/store engine orchestrate, and each `/blockchain/<chain>`
8
- * subpath teaches them to speak one chain's language. This one wraps the
9
- * `@stoachain/*` runtime into the core {@link ChainRuntime} seam so a StoaChain
10
- * automaton injects one object instead of reaching for `@stoachain/*` directly.
11
- *
12
- * The `@stoachain/*` packages are OPTIONAL PEER DEPENDENCIES: importing this
13
- * subpath costs nothing (the SDK imports are lazy, inside the factory), so a
14
- * consumer who never talks StoaChain never installs them. Only calling
15
- * `createStoachainRuntime()` pulls the SDK — and a StoaChain automaton has it.
16
- *
17
- * This adapter is also the ONLY place khronoton knows StoaChain's rising gas
18
- * floor (the Yin Engine) exists. The `/server` executor asks for gas meta
19
- * through the {@link ChainRuntime.gasMeta} seam and never imports the formula;
20
- * `@stoachain/stoa-core/gas` owns the single canonical implementation, which is
21
- * why this wraps it rather than reimplementing the arithmetic locally — that
22
- * reimplementation has already happened four times across the ecosystem.
23
- */
24
3
  /**
25
4
  * Consumer-facing knobs for {@link createStoachainRuntime}. Every field is
26
5
  * optional; an omitted field falls back to the corresponding `@stoachain/*`
@@ -1,4 +1,18 @@
1
1
  // src/blockchain/stoachain.ts
2
+ var AUTO_GAS_CEILING_FALLBACK = 2e6;
3
+ function findBlockGasLimit(obj, depth = 0) {
4
+ if (depth > 8 || obj == null || typeof obj !== "object") return null;
5
+ for (const [k, v] of Object.entries(obj)) {
6
+ if (typeof v === "number" && /block.?gas.?limit|gas.?limit.?of.?block/i.test(k) && v >= 5e4 && v <= 5e7) {
7
+ return Math.floor(v);
8
+ }
9
+ if (v && typeof v === "object") {
10
+ const found = findBlockGasLimit(v, depth + 1);
11
+ if (found) return found;
12
+ }
13
+ }
14
+ return null;
15
+ }
2
16
  async function createStoachainRuntime(config) {
3
17
  const client = await import('@stoachain/kadena-stoic-legacy/client');
4
18
  const signing = await import('@stoachain/stoa-core/signing');
@@ -12,7 +26,33 @@ async function createStoachainRuntime(config) {
12
26
  const getPactUrl = nodeBaseUrl ? (chainId) => `${nodeBaseUrl}/chainweb/0.0/${networkId}/chain/${chainId}/pact` : constants.getPactUrl;
13
27
  return {
14
28
  Pact: client.Pact,
15
- createClient: client.createClient,
29
+ // The SDK client is no longer returned by identity: it's wrapped so the
30
+ // two new optional ChainClient capabilities (preflightRead,
31
+ // getBlockGasLimit) ride alongside the real dirtyRead/submit/listen,
32
+ // which stay byte-identical pass-throughs.
33
+ createClient: ((url) => {
34
+ const real = client.createClient(url);
35
+ return {
36
+ ...real,
37
+ preflightRead: (tx) => real.local(tx, {
38
+ preflight: true,
39
+ signatureVerification: false
40
+ }),
41
+ getBlockGasLimit: async () => {
42
+ try {
43
+ const origin = url.replace(/\/chainweb\/.*$/, "");
44
+ const res = await fetch(`${origin}/config`, {
45
+ headers: { accept: "application/json" }
46
+ });
47
+ if (!res.ok) return AUTO_GAS_CEILING_FALLBACK;
48
+ const found = findBlockGasLimit(await res.json());
49
+ return found ?? AUTO_GAS_CEILING_FALLBACK;
50
+ } catch {
51
+ return AUTO_GAS_CEILING_FALLBACK;
52
+ }
53
+ }
54
+ };
55
+ }),
16
56
  isSignedTransaction: client.isSignedTransaction,
17
57
  universalSignTransaction: signing.universalSignTransaction,
18
58
  calculateAutoGasLimit: gas.calculateAutoGasLimit,
@@ -170,8 +170,20 @@ CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_due
170
170
  CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_cronoton
171
171
  ON codex_cronoton_manual_batches(codex_cronoton_id);
172
172
  `;
173
+ function ensureColumn(db, table, column, columnDefSql) {
174
+ const existing = db.prepare(`PRAGMA table_info(${table})`).all();
175
+ const hasColumn = existing.some((c) => c.name === column);
176
+ if (!hasColumn) {
177
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${columnDefSql}`);
178
+ }
179
+ }
173
180
  function installSchema(db) {
174
181
  db.exec(SCHEMA_SQL);
182
+ ensureColumn(db, "codex_cronotons", "public_token", "TEXT");
183
+ ensureColumn(db, "codex_cronotons", "public_observable", "INTEGER NOT NULL DEFAULT 0");
184
+ db.exec(
185
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronotons_public_token ON codex_cronotons(public_token)`
186
+ );
175
187
  }
176
188
 
177
189
  // src/server/executor-signers.ts
@@ -213,6 +225,14 @@ function effectiveSigners(definition, kadenaNamespace) {
213
225
  }
214
226
 
215
227
  // src/server/executor.ts
228
+ function isSaneCeiling(v) {
229
+ return typeof v === "number" && Number.isFinite(v) && v > 0;
230
+ }
231
+ async function resolveCeiling(ctx, client) {
232
+ if (isSaneCeiling(ctx.config?.autoGasCeiling)) return ctx.config.autoGasCeiling;
233
+ const live = await client.getBlockGasLimit?.();
234
+ return isSaneCeiling(live) ? live : AUTO_GAS_CEILING;
235
+ }
216
236
  function buildTransaction(runtime, definition, signers, gasLimitOverride) {
217
237
  if (signers.length === 0) {
218
238
  throw new Error(
@@ -313,8 +333,9 @@ async function listenWithTimeout(listen, descriptor, timeoutMs) {
313
333
  }
314
334
  async function runSimulate(ctx, definition, signers) {
315
335
  const { runtime, resolver } = ctx;
316
- const ceiling = ctx.config?.autoGasCeiling ?? AUTO_GAS_CEILING;
317
336
  const { autoGasLimit } = definition.config;
337
+ const client = runtime.createClient(runtime.getPactUrl(definition.config.chainId));
338
+ const ceiling = await resolveCeiling(ctx, client);
318
339
  const tx = buildTransaction(
319
340
  runtime,
320
341
  definition,
@@ -322,10 +343,12 @@ async function runSimulate(ctx, definition, signers) {
322
343
  autoGasLimit ? ceiling : void 0
323
344
  );
324
345
  const signed = await signTransaction(runtime, resolver, signers, tx);
325
- const { dirtyRead } = runtime.createClient(
326
- runtime.getPactUrl(definition.config.chainId)
327
- );
328
- const simulation = await dirtyRead(signed);
346
+ if (autoGasLimit && !client.preflightRead) {
347
+ throw new Error(
348
+ "ChainRuntime.preflightRead is required to auto-size gas for an AUTO-gas transaction: without it the calibration would use dirtyRead's execution-only gas figure, which omits the transaction-size charge and reproduces the exact over-reservation bug this capability exists to fix. Upgrade the injected runtime adapter (see blockchain/stoachain.ts), or switch this cronoton to manual gas."
349
+ );
350
+ }
351
+ const simulation = autoGasLimit ? await client.preflightRead(signed) : await client.dirtyRead(signed);
329
352
  if (simulation.result.status === "failure") {
330
353
  return {
331
354
  ok: false,
@@ -336,6 +359,16 @@ async function runSimulate(ctx, definition, signers) {
336
359
  };
337
360
  }
338
361
  const gasUsed = simulation.gas || 0;
362
+ if (gasUsed > ceiling) {
363
+ return {
364
+ ok: false,
365
+ mode: "simulate",
366
+ gasUsed,
367
+ error: `Transaction needs ${gasUsed} gas, over the block limit of ${ceiling} \u2014 no gas setting can mine it. Reduce the transaction's size or complexity.`,
368
+ rawResult: simulation.result,
369
+ terminalIntent: null
370
+ };
371
+ }
339
372
  const calibratedGasLimit = autoGasLimit && gasUsed > 0 ? runtime.calculateAutoGasLimit(gasUsed) : void 0;
340
373
  return {
341
374
  ok: true,
@@ -348,10 +381,10 @@ async function runSimulate(ctx, definition, signers) {
348
381
  }
349
382
  async function runFire(ctx, definition, signers) {
350
383
  const { runtime, resolver } = ctx;
351
- const ceiling = ctx.config?.autoGasCeiling ?? AUTO_GAS_CEILING;
352
384
  const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
353
385
  const { chainId, autoGasLimit } = definition.config;
354
386
  const client = runtime.createClient(runtime.getPactUrl(chainId));
387
+ const ceiling = await resolveCeiling(ctx, client);
355
388
  let tx = buildTransaction(
356
389
  runtime,
357
390
  definition,
@@ -359,7 +392,12 @@ async function runFire(ctx, definition, signers) {
359
392
  autoGasLimit ? ceiling : void 0
360
393
  );
361
394
  let signed = await signTransaction(runtime, resolver, signers, tx);
362
- const preflight = await client.dirtyRead(signed);
395
+ if (autoGasLimit && !client.preflightRead) {
396
+ throw new Error(
397
+ "ChainRuntime.preflightRead is required to auto-size gas for an AUTO-gas transaction: without it the calibration would use dirtyRead's execution-only gas figure, which omits the transaction-size charge and reproduces the exact over-reservation bug this capability exists to fix. Upgrade the injected runtime adapter (see blockchain/stoachain.ts), or switch this cronoton to manual gas."
398
+ );
399
+ }
400
+ const preflight = autoGasLimit ? await client.preflightRead(signed) : await client.dirtyRead(signed);
363
401
  if (preflight.result.status === "failure") {
364
402
  return {
365
403
  ok: false,
@@ -370,8 +408,19 @@ async function runFire(ctx, definition, signers) {
370
408
  terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
371
409
  };
372
410
  }
373
- if (autoGasLimit && (preflight.gas || 0) > 0) {
374
- const calibrated = runtime.calculateAutoGasLimit(preflight.gas || 0);
411
+ const gasUsed = preflight.gas || 0;
412
+ if (gasUsed > ceiling) {
413
+ return {
414
+ ok: false,
415
+ mode: "fire",
416
+ chainId,
417
+ error: `Transaction needs ${gasUsed} gas, over the block limit of ${ceiling} \u2014 no gas setting can mine it. Reduce the transaction's size or complexity.`,
418
+ rawResult: preflight.result,
419
+ terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false)
420
+ };
421
+ }
422
+ if (autoGasLimit && gasUsed > 0) {
423
+ const calibrated = runtime.calculateAutoGasLimit(gasUsed);
375
424
  tx = buildTransaction(runtime, definition, signers, calibrated);
376
425
  signed = await signTransaction(runtime, resolver, signers, tx);
377
426
  }
@@ -1005,6 +1054,14 @@ function parseTxKeys(json2) {
1005
1054
  return [];
1006
1055
  }
1007
1056
  }
1057
+ function parseChainResponse(json2) {
1058
+ if (!json2) return null;
1059
+ try {
1060
+ return JSON.parse(json2);
1061
+ } catch {
1062
+ return null;
1063
+ }
1064
+ }
1008
1065
  function listFires(id, params = {}, dep) {
1009
1066
  const db = dep.db;
1010
1067
  const limit = Math.min(Math.max(params.limit ?? 20, 1), 100);
@@ -1025,7 +1082,7 @@ function listFires(id, params = {}, dep) {
1025
1082
  requestKey: r.request_key,
1026
1083
  chainId: r.chain_id,
1027
1084
  errorMessage: r.error_message,
1028
- chainResponse: r.chain_response_json ? JSON.parse(r.chain_response_json) : null,
1085
+ chainResponse: parseChainResponse(r.chain_response_json),
1029
1086
  definitionFingerprint: r.definition_fingerprint,
1030
1087
  mode: r.mode === "live" ? "live" : "test",
1031
1088
  recoveredAt: r.recovered_at,
@@ -1,4 +1,4 @@
1
- import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-KDCNWWWQ.js';
1
+ import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-GIGLXIMC.js';
2
2
  import { useState, useRef, useEffect, useCallback } from 'react';
3
3
 
4
4
  function useCronotons(query) {
@@ -1,6 +1,6 @@
1
1
  import { ReactNode } from 'react';
2
- import { b as CodexTxConfig, c as CodexGasPayer, d as CodexSigner, S as ScheduleMode, e as ScheduleConfig, C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from './types-DnFB1Yz-.js';
3
- import { b as DbDep, D as Database } from './seams-BL_ntGK_.js';
2
+ import { b as CodexTxConfig, c as CodexGasPayer, d as CodexSigner, S as ScheduleMode, e as ScheduleConfig, C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from './types-uYSglFrJ.js';
3
+ import { b as DbDep, D as Database } from './seams-DUtxDw_U.js';
4
4
 
5
5
  /** A validated bag of runtime args — every value is a string (Pact `read-string`). */
6
6
  type RuntimeArgs = Record<string, string>;
@@ -3,7 +3,7 @@
3
3
  * framework-agnostic route surface over the `/server` store + executor. A
4
4
  * consumer adapts its framework's request/response into {@link HandlerRequest} /
5
5
  * {@link HandlerResponse}, injects a {@link HandlerContext} (db + runtime +
6
- * resolver + an {@link AuthSeam}), and calls the seventeen handlers below.
6
+ * resolver + an {@link AuthSeam}), and calls the eighteen handlers below.
7
7
  *
8
8
  * The read handlers keep their contract names here (aliasing their module's
9
9
  * `*Handler` implementations), so the barrel exposes the exact route contract
@@ -18,6 +18,7 @@ export { commitCodexCronoton, editCodexCronoton, pauseCodexCronoton, resumeCodex
18
18
  export type { CommitBody, CommitEnvelope, CommitSchedule } from "./cronoton.js";
19
19
  export { simulateCodexTx, executeNow, triggerCronoton, recoverFire } from "./execute.js";
20
20
  export { startExecuteBatch, getExecuteBatch, cancelExecuteBatch } from "./batch.js";
21
+ export { publicCronotonHandler } from "./public.js";
21
22
  export { json, err, errorBody, mapStoreError } from "./http.js";
22
23
  export type { HandlerRequest, HandlerResponse } from "./http.js";
23
24
  export { defaultSignerSource, descriptorSourceToDisplay } from "./http.js";
@@ -3,7 +3,7 @@
3
3
  * framework-agnostic route surface over the `/server` store + executor. A
4
4
  * consumer adapts its framework's request/response into {@link HandlerRequest} /
5
5
  * {@link HandlerResponse}, injects a {@link HandlerContext} (db + runtime +
6
- * resolver + an {@link AuthSeam}), and calls the seventeen handlers below.
6
+ * resolver + an {@link AuthSeam}), and calls the eighteen handlers below.
7
7
  *
8
8
  * The read handlers keep their contract names here (aliasing their module's
9
9
  * `*Handler` implementations), so the barrel exposes the exact route contract
@@ -21,6 +21,8 @@ export { commitCodexCronoton, editCodexCronoton, pauseCodexCronoton, resumeCodex
21
21
  export { simulateCodexTx, executeNow, triggerCronoton, recoverFire } from "./execute.js";
22
22
  // ── Manual-batch handlers (TC.5) ──────────────────────────────────────────────
23
23
  export { startExecuteBatch, getExecuteBatch, cancelExecuteBatch } from "./batch.js";
24
+ // ── Public observability (unauthenticated-by-design; bypasses ctx.auth) ──────
25
+ export { publicCronotonHandler } from "./public.js";
24
26
  // ── Kernel contract (TC.1): normalized request/response + helpers ─────────────
25
27
  // The request/response shapes plus the response helpers a consumer needs to
26
28
  // build its own auth seam, signer source, or error mapping.
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The public (unauthenticated-by-design) observability route: `GET
3
+ * /public/[token]`. A DIFFERENT trust tier than the admin `AuthSeam` governs —
4
+ * gating is purely "does this token resolve to an observable row," independent
5
+ * of whatever the host's admin auth would otherwise require — so this handler
6
+ * deliberately never calls `withRead`/`withConfirm`/`ctx.auth` at all. An
7
+ * unknown token and a known token whose row has `public_observable = 0` are
8
+ * made INDISTINGUISHABLE (identical 404), matching
9
+ * `getCodexCronotonByPublicToken`'s own "never 403, never leak which" contract
10
+ * one layer down.
11
+ *
12
+ * `limit`/`offset` get the SAME defensive clamp `read.ts`'s `firesHandler`
13
+ * applies (1..100, default 50 — REQ-G08/REQ-H07's override of the store's own
14
+ * default of 20) — duplicated here as a local, file-private copy rather than
15
+ * imported across handler files, since `read.ts`'s `clampInt`/`firstScalar`
16
+ * are module-private by design.
17
+ *
18
+ * The host is responsible for transport concerns this package's `{status,
19
+ * body}` contract doesn't carry: set `Cache-Control: public, max-age=30` and
20
+ * whatever CORS policy fits the deployment (mirroring the hub's own
21
+ * `pythia-odometer.ts` precedent).
22
+ */
23
+ import { type HandlerResponse } from "./http.js";
24
+ import type { HandlerContext } from "./context.js";
25
+ import type { HandlerRequest } from "./http.js";
26
+ /**
27
+ * `GET /public/[token]` — the sanitized public view for one codex-cronoton, or
28
+ * a 404 for an unknown/non-observable token (the two are indistinguishable by
29
+ * design). Never runs `ctx.auth` — this route's trust tier is the token
30
+ * itself, not the host's admin `AuthSeam`.
31
+ *
32
+ * Wrapped in try/catch -> `mapStoreError`, matching the error-translation
33
+ * idiom every other handler gets for free from `withRead`/`withConfirm`'s
34
+ * shared `runGated` wrapper — this route can't use that wrapper (it would
35
+ * reintroduce the `ctx.auth` call this handler exists to bypass), but it
36
+ * still owes the same "{status, body:{error}}` for any failure" guarantee
37
+ * (e.g. `listFires`'s `JSON.parse(chain_response_json)` throwing on a
38
+ * malformed/legacy row). The explicit 404 `return` below is unaffected by
39
+ * the wrapping `try` — it exits before the `catch` could ever see it.
40
+ */
41
+ export declare function publicCronotonHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The public (unauthenticated-by-design) observability route: `GET
3
+ * /public/[token]`. A DIFFERENT trust tier than the admin `AuthSeam` governs —
4
+ * gating is purely "does this token resolve to an observable row," independent
5
+ * of whatever the host's admin auth would otherwise require — so this handler
6
+ * deliberately never calls `withRead`/`withConfirm`/`ctx.auth` at all. An
7
+ * unknown token and a known token whose row has `public_observable = 0` are
8
+ * made INDISTINGUISHABLE (identical 404), matching
9
+ * `getCodexCronotonByPublicToken`'s own "never 403, never leak which" contract
10
+ * one layer down.
11
+ *
12
+ * `limit`/`offset` get the SAME defensive clamp `read.ts`'s `firesHandler`
13
+ * applies (1..100, default 50 — REQ-G08/REQ-H07's override of the store's own
14
+ * default of 20) — duplicated here as a local, file-private copy rather than
15
+ * imported across handler files, since `read.ts`'s `clampInt`/`firstScalar`
16
+ * are module-private by design.
17
+ *
18
+ * The host is responsible for transport concerns this package's `{status,
19
+ * body}` contract doesn't carry: set `Cache-Control: public, max-age=30` and
20
+ * whatever CORS policy fits the deployment (mirroring the hub's own
21
+ * `pythia-odometer.ts` precedent).
22
+ */
23
+ import { json, err, mapStoreError } from "./http.js";
24
+ import { getCodexCronotonByPublicToken, getCronotonFireCounts, listFires, toPublicCronotonView, } from "../server/index.js";
25
+ /** First scalar of a query value (a repeated key arrives as an array); `undefined` if empty. */
26
+ function firstScalar(raw) {
27
+ const value = Array.isArray(raw) ? raw[0] : raw;
28
+ return value === undefined || value === null || value === "" ? undefined : value;
29
+ }
30
+ /**
31
+ * Parse a query int, falling back to `def` for absent/NaN input, then clamp into
32
+ * `[min, max]`. Clamping in the handler (not only in the store) keeps the echoed
33
+ * `limit`/`offset` equal to the window actually queried.
34
+ */
35
+ function clampInt(raw, { def, min, max }) {
36
+ const scalar = firstScalar(raw);
37
+ const parsed = scalar === undefined ? Number.NaN : Number.parseInt(scalar, 10);
38
+ const base = Number.isNaN(parsed) ? def : parsed;
39
+ const lowerBounded = Math.max(base, min);
40
+ return max === undefined ? lowerBounded : Math.min(lowerBounded, max);
41
+ }
42
+ // ── Handler ───────────────────────────────────────────────────────────────────
43
+ /**
44
+ * `GET /public/[token]` — the sanitized public view for one codex-cronoton, or
45
+ * a 404 for an unknown/non-observable token (the two are indistinguishable by
46
+ * design). Never runs `ctx.auth` — this route's trust tier is the token
47
+ * itself, not the host's admin `AuthSeam`.
48
+ *
49
+ * Wrapped in try/catch -> `mapStoreError`, matching the error-translation
50
+ * idiom every other handler gets for free from `withRead`/`withConfirm`'s
51
+ * shared `runGated` wrapper — this route can't use that wrapper (it would
52
+ * reintroduce the `ctx.auth` call this handler exists to bypass), but it
53
+ * still owes the same "{status, body:{error}}` for any failure" guarantee
54
+ * (e.g. `listFires`'s `JSON.parse(chain_response_json)` throwing on a
55
+ * malformed/legacy row). The explicit 404 `return` below is unaffected by
56
+ * the wrapping `try` — it exits before the `catch` could ever see it.
57
+ */
58
+ export async function publicCronotonHandler(ctx, request) {
59
+ try {
60
+ const token = request.params?.token ?? "";
61
+ const row = getCodexCronotonByPublicToken(token, { db: ctx.db });
62
+ if (!row) {
63
+ return err(404, "not found");
64
+ }
65
+ const query = request.query ?? {};
66
+ const limit = clampInt(query.limit, { def: 50, min: 1, max: 100 });
67
+ const offset = clampInt(query.offset, { def: 0, min: 0 });
68
+ const counts = getCronotonFireCounts(row.id, { db: ctx.db });
69
+ const { fires, total } = listFires(row.id, { limit, offset }, { db: ctx.db });
70
+ return json(200, {
71
+ ok: true,
72
+ ...toPublicCronotonView(row, counts, { fires, total, limit, offset }, new Date()),
73
+ });
74
+ }
75
+ catch (error) {
76
+ return mapStoreError(error);
77
+ }
78
+ }