@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.
@@ -1,8 +1,8 @@
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-CMk8bLsF.js';
2
- export { U as UseKhronotonResult, u as useKhronoton } from '../context-CMk8bLsF.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
- import '../seams-BL_ntGK_.js';
5
+ import '../seams-DUtxDw_U.js';
6
6
 
7
7
  /** The `useCronotons()` return shape — the list, its load state, and a refetch. */
8
8
  interface UseCronotonsView {
@@ -1,2 +1,2 @@
1
- export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-UP3SYP2U.js';
2
- export { useKhronoton } from '../chunk-KDCNWWWQ.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-CMk8bLsF.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-CMk8bLsF.js';
4
- import { D as Database, C as ChainRuntime, K as KeyResolver, R as ResolveFireMode, O as OnAudit, a as Config } from '../seams-BL_ntGK_.js';
5
- export { a as CodexCronotonFireRow, C as CodexCronotonRow, M as ManualBatchView } from '../types-DnFB1Yz-.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
+ 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-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-KDCNWWWQ.js';
2
- export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-KDCNWWWQ.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
 
@@ -97,6 +97,26 @@ interface ListenResult {
97
97
  /** A network client bound to a single Pact endpoint URL. */
98
98
  interface ChainClient {
99
99
  dirtyRead(tx: unknown): Promise<DirtyReadResult>;
100
+ /**
101
+ * `local` with `{ preflight: true, signatureVerification: false }` — measures
102
+ * the TRUE gas a transaction will consume, including the transaction-size
103
+ * charge that a plain `dirtyRead` (execution gas only) omits. Optional so the
104
+ * package stays non-breaking for any custom `ChainClient`; the executor HARD
105
+ * THROWS when it's absent on an AUTO-gas fire — a silent fallback to the
106
+ * inaccurate `dirtyRead` measurement would ship the exact over-reservation bug
107
+ * this capability exists to fix (mirrors `ChainRuntime.gasMeta`'s precedent).
108
+ * A MANUAL-gas fire never needs this and is unaffected by its absence.
109
+ */
110
+ preflightRead?(tx: unknown): Promise<DirtyReadResult>;
111
+ /**
112
+ * The live block gas limit, read from the node. Optional and BEST-EFFORT —
113
+ * unlike `preflightRead`, a stale/failed read here only degrades the
114
+ * simulate-at-ceiling sizing and the refuse-unmineable threshold, since the
115
+ * real chainweb node is still the authoritative validator of what actually
116
+ * fits; the executor falls back to `Config.autoGasCeiling`/`AUTO_GAS_CEILING`
117
+ * on any failure or absence, matching OuronetUI's own documented choice here.
118
+ */
119
+ getBlockGasLimit?(): Promise<number>;
100
120
  submit(tx: unknown): Promise<{
101
121
  requestKey: string;
102
122
  }>;
@@ -13,10 +13,26 @@
13
13
  * - fire NEVER throws (F-002) — every failure returns a structured result;
14
14
  * - the dirty-read pre-flight gate (F-001) — a failing pre-flight never submits;
15
15
  * - AUTO-gas calibrate — build at the ceiling, rebuild + re-sign at the
16
- * dirty-read-derived limit;
16
+ * preflight-derived limit;
17
17
  * - the 504/derived-request-key recovery (REQ-23) — the request key is derived
18
18
  * from the signed command hash UP FRONT so a lost submit response or a listen
19
19
  * timeout never discards a tx that may already be on-chain.
20
+ *
21
+ * Auto self-calibrating gas (khronoton-auto-gas) adds three more:
22
+ * - AUTO-gas calibration sources its measurement from `ChainClient.preflightRead`
23
+ * (the TRUE gas, including the transaction-size charge) instead of the plain
24
+ * `dirtyRead` (execution gas only) — the executor HARD THROWS when
25
+ * `autoGasLimit` is true and `preflightRead` is absent from the injected
26
+ * runtime, mirroring the `gasMeta` hard-throw precedent above. A MANUAL-gas
27
+ * fire never needs this and stays on `dirtyRead`, unaffected by its absence;
28
+ * - the simulate/fire ceiling is resolved live via `resolveCeiling`: an
29
+ * explicit `config.autoGasCeiling` override wins outright, else a
30
+ * best-effort `client.getBlockGasLimit()` read, else the static
31
+ * `AUTO_GAS_CEILING` fallback;
32
+ * - refuse-unmineable — a transaction whose measured gas exceeds the resolved
33
+ * ceiling is refused with a structured `{ ok: false, error }` (never a
34
+ * throw, matching F-002) BEFORE any calibration/rebuild or submit, for both
35
+ * AUTO and MANUAL fires.
20
36
  */
21
37
  import type { ChainRuntime, KeyResolver, Config } from "./seams.js";
22
38
  import type { CodexTxDefinition, FireResult, SimulateResult } from "./types.js";
@@ -35,19 +51,23 @@ export interface ExecutorCtx {
35
51
  config?: Partial<Config>;
36
52
  }
37
53
  /**
38
- * Execute a codex transaction in `simulate` (sign + dirty-read, NO submit) or
39
- * `fire` (pre-flight dirty-read → submit → listen) mode against the injected
40
- * {@link ExecutorCtx}.
54
+ * Execute a codex transaction in `simulate` (sign + pre-submit read, NO
55
+ * submit) or `fire` (pre-flight read → submit → listen) mode against the
56
+ * injected {@link ExecutorCtx}. That pre-submit/pre-flight read is
57
+ * `ChainClient.preflightRead` for an AUTO-gas transaction (accurate gas,
58
+ * including the transaction-size charge) and plain `ChainClient.dirtyRead`
59
+ * for a MANUAL-gas one (see the module doc above for why) — both modes
60
+ * inherit whichever the definition's `autoGasLimit` selects.
41
61
  *
42
62
  * `fire` mode NEVER throws on chain/sign/decrypt failure (F-002): every failure
43
- * mode — dirty-read failure, sign-incompletion, submit error, listen timeout,
44
- * and resolver/decrypt rejection — returns a structured
63
+ * mode — pre-flight-read failure, sign-incompletion, submit error, listen
64
+ * timeout, and resolver/decrypt rejection — returns a structured
45
65
  * `{ ok: false, error, terminalIntent }`. A one-time entry whose fire threw
46
66
  * would otherwise get no terminalIntent and re-fire on the next tick.
47
67
  *
48
68
  * `simulate` mode surfaces build errors (zero signers, gas-station with no
49
- * signing key) as throws to the caller, but converts chain-side dirty-read
50
- * failures into structured results.
69
+ * signing key) as throws to the caller, but converts chain-side pre-submit-
70
+ * read failures into structured results.
51
71
  */
52
72
  export declare function executeCodexTransaction(definition: CodexTxDefinition, mode: "simulate", ctx: ExecutorCtx): Promise<SimulateResult>;
53
73
  export declare function executeCodexTransaction(definition: CodexTxDefinition, mode: "fire", ctx: ExecutorCtx): Promise<FireResult>;
@@ -13,16 +13,57 @@
13
13
  * - fire NEVER throws (F-002) — every failure returns a structured result;
14
14
  * - the dirty-read pre-flight gate (F-001) — a failing pre-flight never submits;
15
15
  * - AUTO-gas calibrate — build at the ceiling, rebuild + re-sign at the
16
- * dirty-read-derived limit;
16
+ * preflight-derived limit;
17
17
  * - the 504/derived-request-key recovery (REQ-23) — the request key is derived
18
18
  * from the signed command hash UP FRONT so a lost submit response or a listen
19
19
  * timeout never discards a tx that may already be on-chain.
20
+ *
21
+ * Auto self-calibrating gas (khronoton-auto-gas) adds three more:
22
+ * - AUTO-gas calibration sources its measurement from `ChainClient.preflightRead`
23
+ * (the TRUE gas, including the transaction-size charge) instead of the plain
24
+ * `dirtyRead` (execution gas only) — the executor HARD THROWS when
25
+ * `autoGasLimit` is true and `preflightRead` is absent from the injected
26
+ * runtime, mirroring the `gasMeta` hard-throw precedent above. A MANUAL-gas
27
+ * fire never needs this and stays on `dirtyRead`, unaffected by its absence;
28
+ * - the simulate/fire ceiling is resolved live via `resolveCeiling`: an
29
+ * explicit `config.autoGasCeiling` override wins outright, else a
30
+ * best-effort `client.getBlockGasLimit()` read, else the static
31
+ * `AUTO_GAS_CEILING` fallback;
32
+ * - refuse-unmineable — a transaction whose measured gas exceeds the resolved
33
+ * ceiling is refused with a structured `{ ok: false, error }` (never a
34
+ * throw, matching F-002) BEFORE any calibration/rebuild or submit, for both
35
+ * AUTO and MANUAL fires.
20
36
  */
21
37
  import { LISTEN_TIMEOUT_MS, AUTO_GAS_CEILING } from "./seams.js";
22
38
  import { parseCapabilityLine, computeTerminalIntent } from "./pure/capability.js";
23
39
  import { effectiveSigners, deriveSenderAccount } from "./executor-signers.js";
24
40
  /** Listen (confirmation) timeout default: 5 minutes. Overridable via `ctx.config.listenTimeoutMs`. */
25
41
  export { LISTEN_TIMEOUT_MS } from "./seams.js";
42
+ /** A ceiling value is only trusted if it's a genuine positive number — `NaN`
43
+ * passes `typeof === "number"` but every `gasUsed > ceiling` comparison
44
+ * against it is `false`, which would silently defeat the refuse-unmineable
45
+ * check below rather than falling back as documented. Applied uniformly to
46
+ * BOTH the config override and the live-fetched value: `ChainClient` is an
47
+ * injectable, chain-polyglot seam (per `seams.ts`'s own "BEST-EFFORT" doc on
48
+ * `getBlockGasLimit`), so the executor must not trust an adapter — any
49
+ * adapter, not just the one shipped in `blockchain/stoachain.ts` — to hand
50
+ * back a sane number unchecked. */
51
+ function isSaneCeiling(v) {
52
+ return typeof v === "number" && Number.isFinite(v) && v > 0;
53
+ }
54
+ /** Resolves the effective simulate/fire ceiling: an explicit config override
55
+ * wins outright (no network call); else a best-effort live fetch off the
56
+ * ALREADY-CONSTRUCTED client for this fire's own chain; else the static
57
+ * fallback. Never throws — `getBlockGasLimit` failures are absorbed by the
58
+ * adapter itself (see `blockchain/stoachain.ts`), and an out-of-range value
59
+ * from EITHER source falls back to `AUTO_GAS_CEILING` rather than being
60
+ * trusted verbatim. */
61
+ async function resolveCeiling(ctx, client) {
62
+ if (isSaneCeiling(ctx.config?.autoGasCeiling))
63
+ return ctx.config.autoGasCeiling;
64
+ const live = await client.getBlockGasLimit?.();
65
+ return isSaneCeiling(live) ? live : AUTO_GAS_CEILING;
66
+ }
26
67
  /**
27
68
  * Build a Pact transaction from the definition:
28
69
  * `Pact.builder.execution().setMeta().setNetworkId()` + an `addData` loop over
@@ -140,12 +181,22 @@ async function listenWithTimeout(listen, descriptor, timeoutMs) {
140
181
  }
141
182
  async function runSimulate(ctx, definition, signers) {
142
183
  const { runtime, resolver } = ctx;
143
- const ceiling = ctx.config?.autoGasCeiling ?? AUTO_GAS_CEILING;
144
184
  const { autoGasLimit } = definition.config;
185
+ const client = runtime.createClient(runtime.getPactUrl(definition.config.chainId));
186
+ const ceiling = await resolveCeiling(ctx, client);
145
187
  const tx = buildTransaction(runtime, definition, signers, autoGasLimit ? ceiling : undefined);
146
188
  const signed = await signTransaction(runtime, resolver, signers, tx);
147
- const { dirtyRead } = runtime.createClient(runtime.getPactUrl(definition.config.chainId));
148
- const simulation = await dirtyRead(signed);
189
+ if (autoGasLimit && !client.preflightRead) {
190
+ throw new Error("ChainRuntime.preflightRead is required to auto-size gas for an AUTO-gas " +
191
+ "transaction: without it the calibration would use dirtyRead's execution-" +
192
+ "only gas figure, which omits the transaction-size charge and reproduces " +
193
+ "the exact over-reservation bug this capability exists to fix. Upgrade the " +
194
+ "injected runtime adapter (see blockchain/stoachain.ts), or switch this " +
195
+ "cronoton to manual gas.");
196
+ }
197
+ const simulation = autoGasLimit
198
+ ? await client.preflightRead(signed)
199
+ : await client.dirtyRead(signed);
149
200
  if (simulation.result.status === "failure") {
150
201
  return {
151
202
  ok: false,
@@ -156,9 +207,17 @@ async function runSimulate(ctx, definition, signers) {
156
207
  };
157
208
  }
158
209
  const gasUsed = simulation.gas || 0;
159
- const calibratedGasLimit = autoGasLimit && gasUsed > 0
160
- ? runtime.calculateAutoGasLimit(gasUsed)
161
- : undefined;
210
+ if (gasUsed > ceiling) {
211
+ return {
212
+ ok: false,
213
+ mode: "simulate",
214
+ gasUsed,
215
+ error: `Transaction needs ${gasUsed} gas, over the block limit of ${ceiling} — no gas setting can mine it. Reduce the transaction's size or complexity.`,
216
+ rawResult: simulation.result,
217
+ terminalIntent: null,
218
+ };
219
+ }
220
+ const calibratedGasLimit = autoGasLimit && gasUsed > 0 ? runtime.calculateAutoGasLimit(gasUsed) : undefined;
162
221
  return {
163
222
  ok: true,
164
223
  mode: "simulate",
@@ -170,16 +229,27 @@ async function runSimulate(ctx, definition, signers) {
170
229
  }
171
230
  async function runFire(ctx, definition, signers) {
172
231
  const { runtime, resolver } = ctx;
173
- const ceiling = ctx.config?.autoGasCeiling ?? AUTO_GAS_CEILING;
174
232
  const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
175
233
  const { chainId, autoGasLimit } = definition.config;
176
234
  const client = runtime.createClient(runtime.getPactUrl(chainId));
177
- // Build + sign for the pre-flight dirty-read.
235
+ const ceiling = await resolveCeiling(ctx, client);
236
+ // Build + sign for the pre-flight read.
178
237
  let tx = buildTransaction(runtime, definition, signers, autoGasLimit ? ceiling : undefined);
179
238
  let signed = await signTransaction(runtime, resolver, signers, tx);
180
- // (F-001) Pre-submit dirty-read pre-flight — never submit a tx a pre-flight
181
- // would catch (saves a one-time terminal fire + gas).
182
- const preflight = await client.dirtyRead(signed);
239
+ if (autoGasLimit && !client.preflightRead) {
240
+ throw new Error("ChainRuntime.preflightRead is required to auto-size gas for an AUTO-gas " +
241
+ "transaction: without it the calibration would use dirtyRead's execution-" +
242
+ "only gas figure, which omits the transaction-size charge and reproduces " +
243
+ "the exact over-reservation bug this capability exists to fix. Upgrade the " +
244
+ "injected runtime adapter (see blockchain/stoachain.ts), or switch this " +
245
+ "cronoton to manual gas.");
246
+ }
247
+ // (F-001) Pre-submit pre-flight — never submit a tx a pre-flight would
248
+ // catch (saves a one-time terminal fire + gas). AUTO-gas fires source this
249
+ // from the accurate `preflightRead`; MANUAL-gas fires stay on `dirtyRead`.
250
+ const preflight = autoGasLimit
251
+ ? await client.preflightRead(signed)
252
+ : await client.dirtyRead(signed);
183
253
  if (preflight.result.status === "failure") {
184
254
  return {
185
255
  ok: false,
@@ -190,9 +260,23 @@ async function runFire(ctx, definition, signers) {
190
260
  terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
191
261
  };
192
262
  }
193
- // Auto-gas: rebuild + re-sign with the calibrated limit from the dirty-read.
194
- if (autoGasLimit && (preflight.gas || 0) > 0) {
195
- const calibrated = runtime.calculateAutoGasLimit(preflight.gas || 0);
263
+ // Refuse the unmineable case BEFORE any rebuild/resubmit — a transaction
264
+ // whose measured gas exceeds the resolved block ceiling can never mine, for
265
+ // either an AUTO-gas or a manually-set-limit fire.
266
+ const gasUsed = preflight.gas || 0;
267
+ if (gasUsed > ceiling) {
268
+ return {
269
+ ok: false,
270
+ mode: "fire",
271
+ chainId,
272
+ error: `Transaction needs ${gasUsed} gas, over the block limit of ${ceiling} — no gas setting can mine it. Reduce the transaction's size or complexity.`,
273
+ rawResult: preflight.result,
274
+ terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
275
+ };
276
+ }
277
+ // Auto-gas: rebuild + re-sign with the calibrated limit from the pre-flight read.
278
+ if (autoGasLimit && gasUsed > 0) {
279
+ const calibrated = runtime.calculateAutoGasLimit(gasUsed);
196
280
  tx = buildTransaction(runtime, definition, signers, calibrated);
197
281
  signed = await signTransaction(runtime, resolver, signers, tx);
198
282
  }
@@ -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
  }
@@ -97,6 +97,26 @@ export interface ListenResult {
97
97
  /** A network client bound to a single Pact endpoint URL. */
98
98
  export interface ChainClient {
99
99
  dirtyRead(tx: unknown): Promise<DirtyReadResult>;
100
+ /**
101
+ * `local` with `{ preflight: true, signatureVerification: false }` — measures
102
+ * the TRUE gas a transaction will consume, including the transaction-size
103
+ * charge that a plain `dirtyRead` (execution gas only) omits. Optional so the
104
+ * package stays non-breaking for any custom `ChainClient`; the executor HARD
105
+ * THROWS when it's absent on an AUTO-gas fire — a silent fallback to the
106
+ * inaccurate `dirtyRead` measurement would ship the exact over-reservation bug
107
+ * this capability exists to fix (mirrors `ChainRuntime.gasMeta`'s precedent).
108
+ * A MANUAL-gas fire never needs this and is unaffected by its absence.
109
+ */
110
+ preflightRead?(tx: unknown): Promise<DirtyReadResult>;
111
+ /**
112
+ * The live block gas limit, read from the node. Optional and BEST-EFFORT —
113
+ * unlike `preflightRead`, a stale/failed read here only degrades the
114
+ * simulate-at-ceiling sizing and the refuse-unmineable threshold, since the
115
+ * real chainweb node is still the authoritative validator of what actually
116
+ * fits; the executor falls back to `Config.autoGasCeiling`/`AUTO_GAS_CEILING`
117
+ * on any failure or absence, matching OuronetUI's own documented choice here.
118
+ */
119
+ getBlockGasLimit?(): Promise<number>;
100
120
  submit(tx: unknown): Promise<{
101
121
  requestKey: string;
102
122
  }>;
@@ -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;