@ancientpantheon/khronoton-core 0.11.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,22 @@ 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
+
7
23
  ## 0.11.0 — 2026-09-17
8
24
 
9
25
  **MINOR — a discoverable edit-mode Save affordance, and auto self-calibrating gas as the default for every new cronoton.**
package/README.md CHANGED
@@ -6,6 +6,8 @@ Khronoton is the "When do I act?" Constructor of the Pantheon architecture — t
6
6
 
7
7
  ## Status
8
8
 
9
+ **`0.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
+
9
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.**
10
12
 
11
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).
@@ -240,6 +242,112 @@ This bump ships the engine only. Framework-agnostic HTTP handlers (create/edit/l
240
242
 
241
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.
242
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
+
243
351
  ## Install
244
352
 
245
353
  ```bash
@@ -248,6 +356,8 @@ npm install @ancientpantheon/khronoton-core
248
356
 
249
357
  ## Version history
250
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
+
251
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.**
252
362
 
253
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).
@@ -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
@@ -1042,6 +1054,14 @@ function parseTxKeys(json2) {
1042
1054
  return [];
1043
1055
  }
1044
1056
  }
1057
+ function parseChainResponse(json2) {
1058
+ if (!json2) return null;
1059
+ try {
1060
+ return JSON.parse(json2);
1061
+ } catch {
1062
+ return null;
1063
+ }
1064
+ }
1045
1065
  function listFires(id, params = {}, dep) {
1046
1066
  const db = dep.db;
1047
1067
  const limit = Math.min(Math.max(params.limit ?? 20, 1), 100);
@@ -1062,7 +1082,7 @@ function listFires(id, params = {}, dep) {
1062
1082
  requestKey: r.request_key,
1063
1083
  chainId: r.chain_id,
1064
1084
  errorMessage: r.error_message,
1065
- chainResponse: r.chain_response_json ? JSON.parse(r.chain_response_json) : null,
1085
+ chainResponse: parseChainResponse(r.chain_response_json),
1066
1086
  definitionFingerprint: r.definition_fingerprint,
1067
1087
  mode: r.mode === "live" ? "live" : "test",
1068
1088
  recoveredAt: r.recovered_at,
@@ -1,4 +1,4 @@
1
- import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-GNQ2IVXA.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,5 +1,5 @@
1
1
  import { ReactNode } from 'react';
2
- import { b as CodexTxConfig, c as CodexGasPayer, d as CodexSigner, S as ScheduleMode, e as ScheduleConfig, C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from './types-DnFB1Yz-.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
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`). */
@@ -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
+ }
@@ -1,6 +1,6 @@
1
- import { L as ListCronotonsQuery, R as ResolversView, C as CommitBody, a as CommitView, E as EditPatch, b as EditView, T as ToggleView, D as DeleteView, c as CancelBatchView, d as ExecuteView, e as RecoverView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, h as RuntimeArgs } from '../context-89YS4xT3.js';
2
- export { U as UseKhronotonResult, u as useKhronoton } from '../context-89YS4xT3.js';
3
- import { C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from '../types-DnFB1Yz-.js';
1
+ import { L as ListCronotonsQuery, R as ResolversView, C as CommitBody, a as CommitView, E as EditPatch, b as EditView, T as ToggleView, D as DeleteView, c as CancelBatchView, d as ExecuteView, e as RecoverView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, h as RuntimeArgs } from '../context-CApk-LP4.js';
2
+ export { U as UseKhronotonResult, u as useKhronoton } from '../context-CApk-LP4.js';
3
+ import { C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from '../types-uYSglFrJ.js';
4
4
  import 'react';
5
5
  import '../seams-DUtxDw_U.js';
6
6
 
@@ -1,2 +1,2 @@
1
- export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-LX6T2BDL.js';
2
- export { useKhronoton } from '../chunk-GNQ2IVXA.js';
1
+ export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-KQZYMPZS.js';
2
+ export { useKhronoton } from '../chunk-GIGLXIMC.js';
@@ -1,8 +1,8 @@
1
1
  import { ReactNode } from 'react';
2
- import { H as HandlerRequest, i as HandlerResponse, K as KhronotonProviderProps, j as KhronotonAdapter, k as SignerSource } from '../context-89YS4xT3.js';
3
- export { c as CancelBatchView, l as CodexSignerDescriptor, C as CommitBody, a as CommitView, m as ConfirmGate, n as ConfirmOpts, o as DEFAULT_EXPLORER_BASE, p as DEFAULT_PAGE_SIZE, q as DEFAULT_POLL_CADENCE_MS, D as DeleteView, E as EditPatch, b as EditView, d as ExecuteView, F as FiresQuery, r as FiresView, G as GetBatchView, s as GetCronotonView, t as KhronotonConfig, v as KhronotonSnapshot, L as ListCronotonsQuery, w as ListCronotonsView, e as RecoverView, x as RenderMultiTx, h as RuntimeArgs, y as ServerResolverOption, z as SignersView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, T as ToggleView, U as UseKhronotonResult, A as assertAdapter, B as emptySnapshot, u as useKhronoton } from '../context-89YS4xT3.js';
2
+ import { H as HandlerRequest, i as HandlerResponse, K as KhronotonProviderProps, j as KhronotonAdapter, k as SignerSource } from '../context-CApk-LP4.js';
3
+ export { c as CancelBatchView, l as CodexSignerDescriptor, C as CommitBody, a as CommitView, m as ConfirmGate, n as ConfirmOpts, o as DEFAULT_EXPLORER_BASE, p as DEFAULT_PAGE_SIZE, q as DEFAULT_POLL_CADENCE_MS, D as DeleteView, E as EditPatch, b as EditView, d as ExecuteView, F as FiresQuery, r as FiresView, G as GetBatchView, s as GetCronotonView, t as KhronotonConfig, v as KhronotonSnapshot, L as ListCronotonsQuery, w as ListCronotonsView, e as RecoverView, x as RenderMultiTx, h as RuntimeArgs, y as ServerResolverOption, z as SignersView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, T as ToggleView, U as UseKhronotonResult, A as assertAdapter, B as emptySnapshot, u as useKhronoton } from '../context-CApk-LP4.js';
4
4
  import { D as Database, C as ChainRuntime, K as KeyResolver, R as ResolveFireMode, O as OnAudit, a as Config } from '../seams-DUtxDw_U.js';
5
- export { a as CodexCronotonFireRow, C as CodexCronotonRow, M as ManualBatchView } from '../types-DnFB1Yz-.js';
5
+ export { a as CodexCronotonFireRow, C as CodexCronotonRow, M as ManualBatchView } from '../types-uYSglFrJ.js';
6
6
 
7
7
  /**
8
8
  * The per-request handler context + the injectable auth/confirm seam + the two
@@ -1,5 +1,5 @@
1
- import { assertAdapter, resolveConfig, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, installSchema, defaultOpenAuth, withConfirm, err, recoverFire, json, createManualBatch, manualBatchView, getCodexCronoton, validateRuntimeArgs, rowRuntimeArgKeys, applyRuntimeArgs, rowToDefinition, getServerResolver, resolveServerVars, executeCodexTransaction, CodexCronotonValidationError, deleteCodexCronoton, resumeCodexCronoton, pauseCodexCronoton, editCodexCronoton, commitCodexCronoton, withRead, listFires, listCodexCronotons, getActiveManualBatchForCronoton, cancelManualBatch, listServerResolvers, defaultSignerSource, fireByServerResolver, computeDefinitionFingerprint, recordFire, applyTerminalIntent } from '../chunk-GNQ2IVXA.js';
2
- export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-GNQ2IVXA.js';
1
+ import { assertAdapter, resolveConfig, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, installSchema, defaultOpenAuth, withConfirm, err, recoverFire, json, createManualBatch, manualBatchView, getCodexCronoton, validateRuntimeArgs, rowRuntimeArgKeys, applyRuntimeArgs, rowToDefinition, getServerResolver, resolveServerVars, executeCodexTransaction, CodexCronotonValidationError, deleteCodexCronoton, resumeCodexCronoton, pauseCodexCronoton, editCodexCronoton, commitCodexCronoton, withRead, listFires, listCodexCronotons, getActiveManualBatchForCronoton, cancelManualBatch, listServerResolvers, defaultSignerSource, fireByServerResolver, computeDefinitionFingerprint, recordFire, applyTerminalIntent } from '../chunk-GIGLXIMC.js';
2
+ export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-GIGLXIMC.js';
3
3
  import { useRef, useState, useEffect } from 'react';
4
4
  import { jsx } from 'react/jsx-runtime';
5
5
 
@@ -25,6 +25,13 @@ import type { Database } from "./seams.js";
25
25
  * handle in a single idempotent call. Safe to re-run: every statement is guarded
26
26
  * with `IF NOT EXISTS`.
27
27
  *
28
+ * After the base DDL, ensures the `public_token`/`public_observable` columns
29
+ * on `codex_cronotons` via {@link ensureColumn} — this covers both a fresh
30
+ * install (absent from the `CREATE TABLE` literal) and an existing database
31
+ * that predates these columns, through the one code path. `public_token`
32
+ * then gets a unique index; SQLite's unique index already permits multiple
33
+ * `NULL`s, so non-observable rows with no token never collide.
34
+ *
28
35
  * @param db - Any handle satisfying the {@link Database} seam (a real
29
36
  * `better-sqlite3` instance qualifies). Only `db.exec` is used.
30
37
  */
@@ -80,14 +80,46 @@ CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_due
80
80
  CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_cronoton
81
81
  ON codex_cronoton_manual_batches(codex_cronoton_id);
82
82
  `;
83
+ /**
84
+ * Idempotently ensures `column` exists on `table`, adding it via `ALTER TABLE
85
+ * ... ADD COLUMN` when absent. SQLite (3.53.2, bundled via better-sqlite3)
86
+ * does not support `ALTER TABLE ... ADD COLUMN IF NOT EXISTS` (syntax error),
87
+ * so the check-then-add via `PRAGMA table_info` is the idiomatic idempotent
88
+ * pattern — this is the single mechanism both a fresh install (the column is
89
+ * absent from the `CREATE TABLE` literal, so this always adds it) and an
90
+ * already-provisioned database (a second call is a no-op) go through.
91
+ *
92
+ * @param db - Any handle satisfying the {@link Database} seam.
93
+ * @param table - The table to inspect/alter.
94
+ * @param column - The column name to ensure exists.
95
+ * @param columnDefSql - The column's type/constraint SQL (e.g. `"TEXT"`),
96
+ * appended verbatim after the column name in the `ADD COLUMN` clause.
97
+ */
98
+ function ensureColumn(db, table, column, columnDefSql) {
99
+ const existing = db.prepare(`PRAGMA table_info(${table})`).all();
100
+ const hasColumn = existing.some((c) => c.name === column);
101
+ if (!hasColumn) {
102
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${columnDefSql}`);
103
+ }
104
+ }
83
105
  /**
84
106
  * Installs the three codex-cronoton tables and their indexes on the injected DB
85
107
  * handle in a single idempotent call. Safe to re-run: every statement is guarded
86
108
  * with `IF NOT EXISTS`.
87
109
  *
110
+ * After the base DDL, ensures the `public_token`/`public_observable` columns
111
+ * on `codex_cronotons` via {@link ensureColumn} — this covers both a fresh
112
+ * install (absent from the `CREATE TABLE` literal) and an existing database
113
+ * that predates these columns, through the one code path. `public_token`
114
+ * then gets a unique index; SQLite's unique index already permits multiple
115
+ * `NULL`s, so non-observable rows with no token never collide.
116
+ *
88
117
  * @param db - Any handle satisfying the {@link Database} seam (a real
89
118
  * `better-sqlite3` instance qualifies). Only `db.exec` is used.
90
119
  */
91
120
  export function installSchema(db) {
92
121
  db.exec(SCHEMA_SQL);
122
+ ensureColumn(db, "codex_cronotons", "public_token", "TEXT");
123
+ ensureColumn(db, "codex_cronotons", "public_observable", "INTEGER NOT NULL DEFAULT 0");
124
+ db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronotons_public_token ON codex_cronotons(public_token)`);
93
125
  }
@@ -117,6 +117,32 @@ function parseTxKeys(json) {
117
117
  return [];
118
118
  }
119
119
  }
120
+ /**
121
+ * Parse the stored chain_response_json; tolerate null/malformed data by
122
+ * degrading to `null` rather than throwing. `chain_response_json` is only
123
+ * ever WRITTEN via `JSON.stringify` (recordFire/finalizeFire above), so a
124
+ * parse failure here can only come from pre-existing corrupted/legacy data —
125
+ * but letting that throw propagate is a real hazard for ANY caller: Node
126
+ * 20+'s V8 embeds a snippet of the actual malformed input text in a
127
+ * `JSON.parse` `SyntaxError`'s message (e.g. `Unexpected token 'x',
128
+ * "<snippet>"... is not valid JSON`), and this column can carry on-chain
129
+ * response data a caller may be obligated to keep confidential (the
130
+ * unauthenticated `handlers/public.ts` route is the sharpest edge of that —
131
+ * an uncaught throw here used to ride straight through `mapStoreError`'s
132
+ * generic `error.message` passthrough into a public 500 body, bypassing
133
+ * `toPublicCronotonView`'s sanitization entirely since the throw happened
134
+ * before the projector ever ran).
135
+ */
136
+ function parseChainResponse(json) {
137
+ if (!json)
138
+ return null;
139
+ try {
140
+ return JSON.parse(json);
141
+ }
142
+ catch {
143
+ return null;
144
+ }
145
+ }
120
146
  /** Paginated fire history for a cronoton, newest-first (limit clamped 1..100, default 20). */
121
147
  export function listFires(id, params = {}, dep) {
122
148
  const db = dep.db;
@@ -140,7 +166,7 @@ export function listFires(id, params = {}, dep) {
140
166
  requestKey: r.request_key,
141
167
  chainId: r.chain_id,
142
168
  errorMessage: r.error_message,
143
- chainResponse: r.chain_response_json ? JSON.parse(r.chain_response_json) : null,
169
+ chainResponse: parseChainResponse(r.chain_response_json),
144
170
  definitionFingerprint: r.definition_fingerprint,
145
171
  mode: r.mode === "live" ? "live" : "test",
146
172
  recoveredAt: r.recovered_at,
@@ -24,3 +24,5 @@ export type { CommitCodexCronotonInput, EditCodexCronotonPatch } from "./cronoto
24
24
  export { getManualBatch, getActiveManualBatchForCronoton, createManualBatch, fetchDueManualBatches, claimManualBatchFire, cancelManualBatch, } from "./manual-batch.js";
25
25
  export type { CreateManualBatchInput } from "./manual-batch.js";
26
26
  export { computeDefinitionFingerprint } from "../pure/fingerprint.js";
27
+ export { getCodexCronotonByPublicToken, setPublicObservable, getCronotonFireCounts, deriveCronotonHealth, toPublicCronotonView, } from "./public.js";
28
+ export type { SetPublicObservableOpts, CronotonFireCounts, CronotonHealth, PublicCronotonView, PublicCronotonFireView, PublicCronotonFiresPage, } from "./public.js";
@@ -31,3 +31,5 @@ export { getManualBatch, getActiveManualBatchForCronoton, createManualBatch, fet
31
31
  // store barrel is the single export site here (the Phase-1 server barrel drops
32
32
  // its own direct fingerprint export in favor of this one to avoid a duplicate).
33
33
  export { computeDefinitionFingerprint } from "../pure/fingerprint.js";
34
+ // ── Public observability: token toggle, by-token read, counts, health, projector ──
35
+ export { getCodexCronotonByPublicToken, setPublicObservable, getCronotonFireCounts, deriveCronotonHealth, toPublicCronotonView, } from "./public.js";
@@ -0,0 +1,104 @@
1
+ import type { DbDep } from "../seams.js";
2
+ import type { CodexCronotonFireRow, CodexCronotonRow } from "../types.js";
3
+ export interface SetPublicObservableOpts {
4
+ observable: boolean;
5
+ /** Force a fresh token even if one already exists. Ignored when `observable` is false. */
6
+ regenerate?: boolean;
7
+ }
8
+ /**
9
+ * Flip a cronoton's public-observability flag. Minting is lazy and stable:
10
+ * a token is generated ONLY the first time a row is made observable (or when
11
+ * `regenerate: true` is explicitly passed) — disabling then re-enabling
12
+ * reuses the same token, so an embed URL built from it never has to be
13
+ * re-minted. Disabling never touches `public_token`.
14
+ */
15
+ export declare function setPublicObservable(id: string, opts: SetPublicObservableOpts, dep: DbDep): {
16
+ publicToken: string | null;
17
+ publicObservable: boolean;
18
+ };
19
+ /**
20
+ * Resolve a cronoton by its public token. Returns `null` for an unknown
21
+ * token AND for a known token whose row is currently non-observable — the
22
+ * single query makes the two cases indistinguishable on purpose (the public
23
+ * handler can't leak which one it is).
24
+ */
25
+ export declare function getCodexCronotonByPublicToken(token: string, dep: DbDep): CodexCronotonRow | null;
26
+ export interface CronotonFireCounts {
27
+ fired: number;
28
+ succeeded: number;
29
+ failed: number;
30
+ lastSuccessAt: string | null;
31
+ lastFailureAt: string | null;
32
+ /** Consecutive failures immediately preceding the most recent fire; capped at 1000. */
33
+ currentFailStreak: number;
34
+ }
35
+ /**
36
+ * Whole-history fire counts for a cronoton. Deliberately independent of any
37
+ * paginated fires window (a page of 20 out of 150 fires would under-report
38
+ * every aggregate): one aggregate query for the totals/last-timestamps, plus
39
+ * a second DESC-ordered scan (capped at 1000 rows) counting leading
40
+ * `'failure'` statuses for `currentFailStreak` — the scan stops at the first
41
+ * non-failure (or the cap), so a success anywhere further back never dilutes
42
+ * the trailing streak.
43
+ */
44
+ export declare function getCronotonFireCounts(id: string, dep: DbDep): CronotonFireCounts;
45
+ export type CronotonHealth = "healthy" | "degraded" | "down";
46
+ /**
47
+ * The pure traffic-light health rule: `"down"` once the trailing streak hits
48
+ * 3, `"degraded"` for a 1-2 streak OR an overdue schedule, `"healthy"`
49
+ * otherwise. Exported standalone so a consumer can reason about it without a
50
+ * DB row.
51
+ */
52
+ export declare function deriveCronotonHealth(input: {
53
+ currentFailStreak: number;
54
+ isOverdue: boolean;
55
+ }): CronotonHealth;
56
+ export interface PublicCronotonFireView {
57
+ firedAt: string;
58
+ status: CodexCronotonFireRow["status"];
59
+ chainId: string | null;
60
+ requestKey: string | null;
61
+ txKeys: CodexCronotonFireRow["txKeys"];
62
+ recoveredAt: string | null;
63
+ mode: CodexCronotonFireRow["mode"];
64
+ }
65
+ export interface PublicCronotonFiresPage {
66
+ fires: CodexCronotonFireRow[];
67
+ total: number;
68
+ limit: number;
69
+ offset: number;
70
+ }
71
+ export interface PublicCronotonView {
72
+ name: string;
73
+ description: string | null;
74
+ status: CodexCronotonRow["status"];
75
+ schedule: {
76
+ mode: CodexCronotonRow["schedule_mode"];
77
+ humanText: string;
78
+ cron?: string;
79
+ };
80
+ triggerOnly: boolean;
81
+ nextFireAt: string | null;
82
+ lastFireAt: string | null;
83
+ isOverdue: boolean;
84
+ since: string;
85
+ counts: CronotonFireCounts & {
86
+ successRatePercent: number | null;
87
+ };
88
+ health: CronotonHealth;
89
+ fires: {
90
+ page: PublicCronotonFireView[];
91
+ total: number;
92
+ limit: number;
93
+ offset: number;
94
+ };
95
+ }
96
+ /**
97
+ * Pure projector (no DB access of its own) from a `CodexCronotonRow` +
98
+ * its `getCronotonFireCounts` result + a `listFires` page onto the sanitized
99
+ * public DTO. Builds the result field-by-field — never spreads the row or a
100
+ * fire — so `pact_code`/`payload_json`/`signers_json`/`gas_payer_json`/
101
+ * `server_resolver`/`created_by`/`config_json`, the internal `id`, and a
102
+ * fire's raw `errorMessage`/`chainResponse` can never leak through it.
103
+ */
104
+ export declare function toPublicCronotonView(row: CodexCronotonRow, counts: CronotonFireCounts, firesPage: PublicCronotonFiresPage, now?: Date): PublicCronotonView;
@@ -0,0 +1,197 @@
1
+ /**
2
+ * public — the public (unauthenticated-by-design) observability surface for a
3
+ * single codex-cronoton: a lazily-minted, stable lookup token, a by-token
4
+ * read gated on `public_observable`, whole-history fire counts, a pure
5
+ * traffic-light health rule, and the sanitizing projector that assembles the
6
+ * client-facing DTO.
7
+ *
8
+ * `toPublicCronotonView` is the ONLY place the privacy guarantee is enforced:
9
+ * it builds a brand-new object field-by-field from the (far more sensitive)
10
+ * `CodexCronotonRow`/`CodexCronotonFireRow` inputs, never spreading either —
11
+ * a raw `pact_code`, JSON config blob, `created_by`, or fire `errorMessage`/
12
+ * `chainResponse` must never ride along by accident.
13
+ */
14
+ import crypto from "node:crypto";
15
+ import { summariseSchedule } from "../../schedule.js";
16
+ import { getCodexCronoton } from "./cronoton.js";
17
+ import { CodexCronotonValidationError } from "./errors.js";
18
+ import { rowExternalFireable, rowRuntimeArgKeys } from "./mappers.js";
19
+ /**
20
+ * Flip a cronoton's public-observability flag. Minting is lazy and stable:
21
+ * a token is generated ONLY the first time a row is made observable (or when
22
+ * `regenerate: true` is explicitly passed) — disabling then re-enabling
23
+ * reuses the same token, so an embed URL built from it never has to be
24
+ * re-minted. Disabling never touches `public_token`.
25
+ */
26
+ export function setPublicObservable(id, opts, dep) {
27
+ const db = dep.db;
28
+ const row = getCodexCronoton(id, { db });
29
+ if (!row)
30
+ throw new CodexCronotonValidationError("not found");
31
+ let nextToken = row.public_token ?? null;
32
+ if (opts.observable && (!nextToken || opts.regenerate === true)) {
33
+ nextToken = crypto.randomBytes(20).toString("base64url");
34
+ }
35
+ db.prepare(`UPDATE codex_cronotons SET public_token = ?, public_observable = ?, modified_at = ? WHERE id = ?`).run(nextToken, opts.observable ? 1 : 0, new Date().toISOString(), id);
36
+ return { publicToken: nextToken, publicObservable: opts.observable };
37
+ }
38
+ /**
39
+ * Resolve a cronoton by its public token. Returns `null` for an unknown
40
+ * token AND for a known token whose row is currently non-observable — the
41
+ * single query makes the two cases indistinguishable on purpose (the public
42
+ * handler can't leak which one it is).
43
+ */
44
+ export function getCodexCronotonByPublicToken(token, dep) {
45
+ const row = dep.db
46
+ .prepare(`SELECT * FROM codex_cronotons WHERE public_token = ? AND public_observable = 1`)
47
+ .get(token);
48
+ return row ?? null;
49
+ }
50
+ /**
51
+ * Whole-history fire counts for a cronoton. Deliberately independent of any
52
+ * paginated fires window (a page of 20 out of 150 fires would under-report
53
+ * every aggregate): one aggregate query for the totals/last-timestamps, plus
54
+ * a second DESC-ordered scan (capped at 1000 rows) counting leading
55
+ * `'failure'` statuses for `currentFailStreak` — the scan stops at the first
56
+ * non-failure (or the cap), so a success anywhere further back never dilutes
57
+ * the trailing streak.
58
+ */
59
+ export function getCronotonFireCounts(id, dep) {
60
+ const db = dep.db;
61
+ const agg = db
62
+ .prepare(`SELECT
63
+ COUNT(*) AS fired,
64
+ SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) AS succeeded,
65
+ SUM(CASE WHEN status = 'failure' THEN 1 ELSE 0 END) AS failed,
66
+ MAX(CASE WHEN status = 'success' THEN fired_at ELSE NULL END) AS lastSuccessAt,
67
+ MAX(CASE WHEN status = 'failure' THEN fired_at ELSE NULL END) AS lastFailureAt
68
+ FROM codex_cronoton_fires
69
+ WHERE codex_cronoton_id = ?`)
70
+ .get(id);
71
+ const recent = db
72
+ .prepare(
73
+ // Tiebreak on SQLite's implicit `rowid`, NOT the `id` column — `id` is a
74
+ // `crypto.randomUUID()` (fires.ts's recordFire/createRunningFire), with
75
+ // zero correlation to insertion order, so an `id`-based tiebreak would
76
+ // pick "most recent" essentially at random on a genuine fired_at tie.
77
+ // `rowid` is safe here: this table has no `INTEGER PRIMARY KEY`/`WITHOUT
78
+ // ROWID` override, and rows are never deleted standalone (only
79
+ // cascade-deleted with their parent cronoton), so rowid reuse never
80
+ // becomes a factor for a still-alive cronoton's fire history.
81
+ `SELECT status FROM codex_cronoton_fires
82
+ WHERE codex_cronoton_id = ?
83
+ ORDER BY fired_at DESC, rowid DESC LIMIT 1000`)
84
+ .all(id);
85
+ let currentFailStreak = 0;
86
+ for (const r of recent) {
87
+ if (r.status !== "failure")
88
+ break;
89
+ currentFailStreak += 1;
90
+ }
91
+ return {
92
+ fired: agg.fired,
93
+ succeeded: agg.succeeded ?? 0,
94
+ failed: agg.failed ?? 0,
95
+ lastSuccessAt: agg.lastSuccessAt ?? null,
96
+ lastFailureAt: agg.lastFailureAt ?? null,
97
+ currentFailStreak,
98
+ };
99
+ }
100
+ /**
101
+ * The pure traffic-light health rule: `"down"` once the trailing streak hits
102
+ * 3, `"degraded"` for a 1-2 streak OR an overdue schedule, `"healthy"`
103
+ * otherwise. Exported standalone so a consumer can reason about it without a
104
+ * DB row.
105
+ */
106
+ export function deriveCronotonHealth(input) {
107
+ if (input.currentFailStreak >= 3)
108
+ return "down";
109
+ if (input.currentFailStreak >= 1 || input.isOverdue)
110
+ return "degraded";
111
+ return "healthy";
112
+ }
113
+ /** Best-effort parse of `schedule_config_json`; `null` on malformed/legacy data. */
114
+ function parseScheduleConfig(json) {
115
+ try {
116
+ return JSON.parse(json);
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ }
122
+ /**
123
+ * Pure projector (no DB access of its own) from a `CodexCronotonRow` +
124
+ * its `getCronotonFireCounts` result + a `listFires` page onto the sanitized
125
+ * public DTO. Builds the result field-by-field — never spreads the row or a
126
+ * fire — so `pact_code`/`payload_json`/`signers_json`/`gas_payer_json`/
127
+ * `server_resolver`/`created_by`/`config_json`, the internal `id`, and a
128
+ * fire's raw `errorMessage`/`chainResponse` can never leak through it.
129
+ */
130
+ export function toPublicCronotonView(row, counts, firesPage, now = new Date()) {
131
+ const parsedConfig = parseScheduleConfig(row.schedule_config_json);
132
+ const humanText = parsedConfig
133
+ ? summariseSchedule(row.schedule_mode, parsedConfig)
134
+ : row.schedule_mode;
135
+ const schedule = {
136
+ mode: row.schedule_mode,
137
+ humanText,
138
+ };
139
+ if (parsedConfig && parsedConfig.mode === "cron-expression") {
140
+ schedule.cron = parsedConfig.expression;
141
+ }
142
+ // A row committed/edited with ONLY `eventDriven: true` (no `externalFireable`,
143
+ // no `evented` server resolver) persists `external_fireable = 0` and
144
+ // `runtime_arg_keys = null` — `next_fire_at === null` is the ONLY signal
145
+ // store/cronoton.ts leaves for it (see editCodexCronoton's own
146
+ // "reliable, column-free marker" comment). But a null `next_fire_at` is ALSO
147
+ // how a spent terminal one-time row looks (applyTerminalIntent clears it on
148
+ // completion/error) despite never being trigger-only — so the null check is
149
+ // gated on the row NOT being terminal.
150
+ //
151
+ // KNOWN LIMITATION (not fully disambiguable without a dedicated persisted
152
+ // column — judged disproportionate for a read-only view's display label):
153
+ // `claimDueCodexCronoton` (./claim.js) ALSO nulls `next_fire_at` on an
154
+ // ORDINARY, non-trigger-only row while leaving `status = 'active'` — (a)
155
+ // transiently, for every one-time row, during the brief window between
156
+ // claim and the eventual terminal-intent write; (b) PERMANENTLY, for a
157
+ // recurring row whose `schedule_config_json` is corrupt (claim.ts's own
158
+ // "F-003" case — the row is stuck `active` with a null `next_fire_at`
159
+ // forever, since the due-query requires `next_fire_at IS NOT NULL`). Both
160
+ // cases read as `triggerOnly: true` here. Accepted: the corrupt-config row
161
+ // is already broken regardless of this label, and the one-time window is
162
+ // bounded and transient.
163
+ const triggerOnly = rowExternalFireable(row) ||
164
+ rowRuntimeArgKeys(row).length > 0 ||
165
+ (row.next_fire_at === null && row.status !== "completed" && row.status !== "error");
166
+ const isOverdue = row.status === "active" &&
167
+ row.next_fire_at !== null &&
168
+ new Date(row.next_fire_at) < now;
169
+ const successRatePercent = counts.fired > 0 ? Math.round((counts.succeeded / counts.fired) * 100) : null;
170
+ return {
171
+ name: row.name,
172
+ description: row.description,
173
+ status: row.status,
174
+ schedule,
175
+ triggerOnly,
176
+ nextFireAt: row.next_fire_at,
177
+ lastFireAt: row.last_fire_at,
178
+ isOverdue,
179
+ since: row.created_at,
180
+ counts: { ...counts, successRatePercent },
181
+ health: deriveCronotonHealth({ currentFailStreak: counts.currentFailStreak, isOverdue }),
182
+ fires: {
183
+ page: firesPage.fires.map((fire) => ({
184
+ firedAt: fire.firedAt,
185
+ status: fire.status,
186
+ chainId: fire.chainId,
187
+ requestKey: fire.requestKey,
188
+ txKeys: fire.txKeys,
189
+ recoveredAt: fire.recoveredAt,
190
+ mode: fire.mode,
191
+ })),
192
+ total: firesPage.total,
193
+ limit: firesPage.limit,
194
+ offset: firesPage.offset,
195
+ },
196
+ };
197
+ }
@@ -151,6 +151,19 @@ export interface CodexCronotonRow {
151
151
  * doubles (test fixtures) typecheck.
152
152
  */
153
153
  runtime_arg_keys?: string | null;
154
+ /**
155
+ * Stable, URL-safe public lookup token; null/absent until the row is first
156
+ * made observable. Optional so pre-migration row doubles (test fixtures)
157
+ * typecheck; real rows from `SELECT *` carry the column (value may be null).
158
+ */
159
+ public_token?: string | null;
160
+ /**
161
+ * When 1, this cronoton's sanitized state is readable via the public
162
+ * by-token endpoint, bypassing admin auth entirely. Optional so
163
+ * pre-migration row doubles (test fixtures) typecheck; real rows from
164
+ * `SELECT *` carry the column.
165
+ */
166
+ public_observable?: number;
154
167
  status: "active" | "paused" | "completed" | "error";
155
168
  next_fire_at: string | null;
156
169
  last_fire_at: string | null;
@@ -176,6 +176,19 @@ interface CodexCronotonRow {
176
176
  * doubles (test fixtures) typecheck.
177
177
  */
178
178
  runtime_arg_keys?: string | null;
179
+ /**
180
+ * Stable, URL-safe public lookup token; null/absent until the row is first
181
+ * made observable. Optional so pre-migration row doubles (test fixtures)
182
+ * typecheck; real rows from `SELECT *` carry the column (value may be null).
183
+ */
184
+ public_token?: string | null;
185
+ /**
186
+ * When 1, this cronoton's sanitized state is readable via the public
187
+ * by-token endpoint, bypassing admin auth entirely. Optional so
188
+ * pre-migration row doubles (test fixtures) typecheck; real rows from
189
+ * `SELECT *` carry the column.
190
+ */
191
+ public_observable?: number;
179
192
  status: "active" | "paused" | "completed" | "error";
180
193
  next_fire_at: string | null;
181
194
  last_fire_at: string | null;
@@ -1,5 +1,5 @@
1
1
  import { ReactNode } from 'react';
2
- import { a as CodexCronotonFireRow, C as CodexCronotonRow, f as CodexFireMode } from '../types-DnFB1Yz-.js';
2
+ import { a as CodexCronotonFireRow, C as CodexCronotonRow, f as CodexFireMode } from '../types-uYSglFrJ.js';
3
3
 
4
4
  /**
5
5
  * The theming boundary. Every Khronoton UI surface renders inside a
package/dist/ui/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { useCronotons, useCronoton, useCronotonActions, useExecuteNow, useSimulate, useServerResolvers, useManualBatch, useStartBatch, useCancelBatch, useTrigger, useCronotonFires, useRecoverFire } from '../chunk-LX6T2BDL.js';
2
- import { useKhronotonAdapter, useKhronotonConfig, parseRuntimeArgKeys, summariseSchedule, KhronotonStaticContext, useKhronoton, computeNextFire, InvalidScheduleConfigError } from '../chunk-GNQ2IVXA.js';
1
+ import { useCronotons, useCronoton, useCronotonActions, useExecuteNow, useSimulate, useServerResolvers, useManualBatch, useStartBatch, useCancelBatch, useTrigger, useCronotonFires, useRecoverFire } from '../chunk-KQZYMPZS.js';
2
+ import { useKhronotonAdapter, useKhronotonConfig, parseRuntimeArgKeys, summariseSchedule, KhronotonStaticContext, useKhronoton, computeNextFire, InvalidScheduleConfigError } from '../chunk-GIGLXIMC.js';
3
3
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
4
4
  import { lazy, forwardRef, createElement, useState, useEffect, useCallback, useMemo, Suspense, useContext } from 'react';
5
5
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ancientpantheon/khronoton-core",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Headless framework-agnostic scheduler engine: pure schedule math plus an injectable tick engine. No database, no job queue, no framework — hosts inject storage and firing via hooks.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",