@ancientpantheon/khronoton-core 0.14.0 → 0.15.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.
@@ -0,0 +1,47 @@
1
+ import type { ChainRuntime, Config, Database, KeyResolver, OnAudit, ResolveFireMode } from "./seams.js";
2
+ import type { CodexCronotonRow, CodexTxDefinition, FireResult } from "./types.js";
3
+ /**
4
+ * The injected context this function runs against — a structural subset
5
+ * `HandlerContext`/`RunsDriverCtx`/`SingleTxAttemptCtx` all already satisfy,
6
+ * so every existing caller passes its own `ctx` straight through with no
7
+ * adaptation.
8
+ */
9
+ export interface FireAndRecordCtx {
10
+ db: Database;
11
+ runtime: ChainRuntime;
12
+ resolver: KeyResolver;
13
+ config?: Partial<Config>;
14
+ resolveFireMode?: ResolveFireMode;
15
+ onAudit?: OnAudit;
16
+ }
17
+ export interface FireAndRecordExtras {
18
+ /** Audit action-name pair; defaults to the ordinary one-shot fire names
19
+ * (`codex_cronoton.fire`/`.fire_failed`) every pre-existing caller relies on. */
20
+ auditAction?: {
21
+ success: string;
22
+ failure: string;
23
+ };
24
+ /** Extra fields merged into the audit event's `detail` (e.g. `actor`). */
25
+ auditDetailExtra?: Record<string, unknown>;
26
+ }
27
+ /**
28
+ * Record exactly one fire row for an ALREADY-obtained `result`, apply the
29
+ * one-time terminal transition, and audit — the record+finalize+audit half
30
+ * of the sequence, shared by both {@link fireAndRecord} and any caller (like
31
+ * `single-tx.ts`) that needs to inspect `result` itself before reaching
32
+ * this point.
33
+ */
34
+ export declare function recordAndFinalizeFire(result: FireResult, ctx: FireAndRecordCtx, row: CodexCronotonRow, definition: CodexTxDefinition, extras?: FireAndRecordExtras): Promise<{
35
+ result: FireResult;
36
+ fireId: string;
37
+ }>;
38
+ /**
39
+ * Fire `definition` for `row` through the shared dispatcher, then record +
40
+ * finalize + audit via {@link recordAndFinalizeFire}. The convenience
41
+ * all-in-one entry point for every caller that doesn't need to inspect the
42
+ * `FireResult` before deciding whether to record it.
43
+ */
44
+ export declare function fireAndRecord(ctx: FireAndRecordCtx, row: CodexCronotonRow, definition: CodexTxDefinition, extras?: FireAndRecordExtras): Promise<{
45
+ result: FireResult;
46
+ fireId: string;
47
+ }>;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The shared fire -> record -> finalize -> audit sequence for firing a
3
+ * loaded cronoton row's own definition inline through the dispatcher — "fire
4
+ * one transaction, write exactly one fire row, apply the one-time terminal
5
+ * transition." `handlers/execute.ts`'s on-demand fire (`executeNow`/
6
+ * `triggerCronoton`) and `single-tx.ts`'s single-tx-first attempt both need
7
+ * this identically.
8
+ *
9
+ * A review finding caught the two independently re-deriving this exact
10
+ * sequence by hand (`single-tx.ts`'s own module doc used to admit as much).
11
+ * A third, pre-existing, MORE divergent inline copy already lived in
12
+ * `tick.ts` before this feature (it also collects `txKeys` for the
13
+ * scheduler's multi-tx dispatch path and carries a few extra audit-detail
14
+ * fields) — deliberately left alone here: unifying that one too is a larger,
15
+ * separate refactor the finding that prompted this extraction never asked
16
+ * for.
17
+ *
18
+ * Split into two layers rather than one all-in-one function: `single-tx.ts`
19
+ * needs to inspect the fire `FireResult` itself (specifically
20
+ * `result.postponed` — see that field's own doc comment) BEFORE deciding
21
+ * whether to record/finalize/audit anything at all, so it cannot call an
22
+ * all-in-one "fire-then-record" helper. {@link recordAndFinalizeFire} is the
23
+ * shared record+finalize+audit half, taking an ALREADY-obtained result;
24
+ * {@link fireAndRecord} is the full convenience (fire, then delegate to
25
+ * {@link recordAndFinalizeFire}) for the common case that needs no
26
+ * interception between the two.
27
+ */
28
+ import { fireByServerResolver } from "./resolvers.js";
29
+ import { recordFire } from "./store/fires.js";
30
+ import { applyTerminalIntent } from "./store/claim.js";
31
+ import { computeDefinitionFingerprint } from "./pure/fingerprint.js";
32
+ /**
33
+ * Record exactly one fire row for an ALREADY-obtained `result`, apply the
34
+ * one-time terminal transition, and audit — the record+finalize+audit half
35
+ * of the sequence, shared by both {@link fireAndRecord} and any caller (like
36
+ * `single-tx.ts`) that needs to inspect `result` itself before reaching
37
+ * this point.
38
+ */
39
+ export async function recordAndFinalizeFire(result, ctx, row, definition, extras = {}) {
40
+ const fingerprint = computeDefinitionFingerprint(row);
41
+ const fireId = recordFire({
42
+ codexCronotonId: row.id,
43
+ jobId: null,
44
+ firedAt: new Date().toISOString(),
45
+ status: result.ok ? "success" : "failure",
46
+ requestKey: result.requestKey,
47
+ chainId: result.chainId,
48
+ errorMessage: result.error,
49
+ chainResponse: result.rawResult,
50
+ definitionFingerprint: fingerprint,
51
+ }, { db: ctx.db, resolveFireMode: ctx.resolveFireMode });
52
+ if ((definition.scheduleKind ?? "recurring") === "one-time") {
53
+ applyTerminalIntent(row.id, result.terminalIntent, { db: ctx.db });
54
+ }
55
+ const { success, failure } = extras.auditAction ?? {
56
+ success: "codex_cronoton.fire",
57
+ failure: "codex_cronoton.fire_failed",
58
+ };
59
+ await ctx.onAudit?.({
60
+ action: result.ok ? success : failure,
61
+ result: result.ok ? "success" : "failure",
62
+ targetKind: "codex_cronoton",
63
+ targetId: row.id,
64
+ detail: {
65
+ codexCronotonId: row.id,
66
+ fireId,
67
+ requestKey: result.requestKey,
68
+ chainId: result.chainId,
69
+ definitionFingerprint: fingerprint,
70
+ errorMessage: result.error,
71
+ ...extras.auditDetailExtra,
72
+ },
73
+ });
74
+ return { result, fireId };
75
+ }
76
+ /**
77
+ * Fire `definition` for `row` through the shared dispatcher, then record +
78
+ * finalize + audit via {@link recordAndFinalizeFire}. The convenience
79
+ * all-in-one entry point for every caller that doesn't need to inspect the
80
+ * `FireResult` before deciding whether to record it.
81
+ */
82
+ export async function fireAndRecord(ctx, row, definition, extras = {}) {
83
+ const result = await fireByServerResolver(definition, row, ctx);
84
+ return recordAndFinalizeFire(result, ctx, row, definition, extras);
85
+ }
@@ -75,7 +75,13 @@ export async function dispatchMultiTxResolver(name, opts) {
75
75
  return r.run(opts);
76
76
  }
77
77
  function postponed(error) {
78
- return { ok: false, mode: "fire", error, terminalIntent: null };
78
+ // `postponed: true` is the ONLY reliable signal that this result was never
79
+ // submitted to chain at all — a review finding caught that a caller
80
+ // deciding whether to fall back to an alternate path (e.g. `single-tx.ts`'s
81
+ // `attemptSingleTxFirst`) could not otherwise distinguish this from a
82
+ // GENUINE on-chain fire failure, since both are `{ ok: false, terminalIntent:
83
+ // null }` for a recurring row. See `FireResult.postponed`'s own doc comment.
84
+ return { ok: false, mode: "fire", error, terminalIntent: null, postponed: true };
79
85
  }
80
86
  /**
81
87
  * Coerce a batch's `ok` field (typed `unknown` — the orchestrator's return
@@ -210,4 +210,13 @@ export function installSchema(db) {
210
210
  // stored under in `codex_cronoton_run_yields`. Additive via `ensureColumn`,
211
211
  // covering both a fresh install and an already-provisioned database.
212
212
  ensureColumn(db, "codex_cronoton_steps", "yield_as", "TEXT");
213
+ // Opt-in single-tx-first chain variant (docs/work/khronoton-single-tx-custom):
214
+ // `try_single_tx_first` gates the simulate-then-decide orchestration ahead of
215
+ // the chained-run machinery; `single_tx_mode` (meaningful only when the flag
216
+ // is on) selects how the single-tx Pact code was produced. The CHECK is
217
+ // vacuously satisfied by NULL (mirrors `codex_cronoton_steps.yield_as`'s own
218
+ // nullable-no-CHECK precedent, just with a value whitelist added), so a row
219
+ // can leave `single_tx_mode` unset without an explicit `OR ... IS NULL` clause.
220
+ ensureColumn(db, "codex_cronotons", "try_single_tx_first", "INTEGER NOT NULL DEFAULT 0");
221
+ ensureColumn(db, "codex_cronotons", "single_tx_mode", "TEXT CHECK (single_tx_mode IN ('custom', 'default'))");
213
222
  }
@@ -0,0 +1,44 @@
1
+ import { type FireAndRecordCtx, type FireAndRecordExtras } from "./fire-and-record.js";
2
+ import type { CodexCronotonRow, FireResult } from "./types.js";
3
+ /**
4
+ * The injected context `attemptSingleTxFirst` runs against. Reuses
5
+ * `fire-and-record.ts`'s own `FireAndRecordCtx` verbatim (same
6
+ * `db`/`runtime`/`resolver`/`config`/`resolveFireMode`/`onAudit` shape this
7
+ * function needs to pass straight through to `recordAndFinalizeFire`) rather
8
+ * than re-declaring an identical interface — a review finding caught the two
9
+ * independently drifting apart. A real `TickCtx` (or `executeNow`'s own ad
10
+ * hoc ctx) satisfies this alias already, with no adaptation needed at either
11
+ * call site.
12
+ */
13
+ export type SingleTxAttemptCtx = FireAndRecordCtx;
14
+ /** The outcome of one single-tx-first attempt. */
15
+ export interface SingleTxAttemptResult {
16
+ /**
17
+ * `false` means "did not fire" — the flag is off, the simulate was
18
+ * refused specifically for being too expensive, or a server-resolver
19
+ * postponed the fire without ever submitting it (see `FireResult.
20
+ * postponed`); in every case the caller falls through to its own
21
+ * existing chained/plain decision. `true` means the single-tx variant
22
+ * was actually fired (successfully or not) — the caller must NOT fall
23
+ * back to the chain.
24
+ */
25
+ fired: boolean;
26
+ result?: FireResult;
27
+ fireId?: string;
28
+ }
29
+ /**
30
+ * Decide — and, when it fits, fire — a row's single-tx-first variant. See the
31
+ * module doc above for the full decision shape.
32
+ *
33
+ * `extras.auditDetailExtra` (e.g. `{ actor: "scheduler" }`/`{ actor:
34
+ * "ancient" }`) is merged into the resulting `codex_cronoton.single_tx.fire`/
35
+ * `.fire_failed` audit event's detail, exactly like `fire-and-record.ts`'s
36
+ * own `fireAndRecord`/every other fire path's audit event already does. A
37
+ * review finding caught this function silently dropping that attribution —
38
+ * every OTHER fire path (`tick.ts`'s plain-fire/chained-run branches,
39
+ * `handlers/execute.ts`'s `fireAndRecord` wrapper) tags its audit event with
40
+ * `actor: "scheduler"` or `actor: "ancient"`, but a single-tx-first fire's
41
+ * audit event carried no such field at all, regardless of which trigger
42
+ * caused it.
43
+ */
44
+ export declare function attemptSingleTxFirst(row: CodexCronotonRow, ctx: SingleTxAttemptCtx, extras?: Pick<FireAndRecordExtras, "auditDetailExtra">): Promise<SingleTxAttemptResult>;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * The shared "try single-tx first" decision helper — see
3
+ * `docs/work/khronoton-single-tx-custom/design.md`.
4
+ *
5
+ * At the exact point a chained row's work would normally begin (`tick.ts`'s
6
+ * due-row branch, `handlers/execute.ts`'s `executeNow` manual-trigger
7
+ * branch), the caller consults {@link attemptSingleTxFirst} ahead of its own
8
+ * existing chained/plain decision. This module owns ONLY that decision —
9
+ * never the chained/plain branch itself, which stays each caller's own.
10
+ *
11
+ * Decision shape (mirrors `ouronet.aqp-evict`'s own established
12
+ * try-then-fan-out precedent — the identical "refuse unmineable" signal, one
13
+ * level down):
14
+ * - `try_single_tx_first` off -> `{ fired: false }` immediately, no
15
+ * simulate call at all (the ONLY branch allowed to skip simulating).
16
+ * - simulate fits under the gas ceiling -> fire via `fireByServerResolver`,
17
+ * then record+finalize+audit via the SAME shared `recordAndFinalizeFire`
18
+ * helper (`./fire-and-record.js`) `handlers/execute.ts`'s own fire path
19
+ * uses — not a parallel reimplementation (a prior version of this
20
+ * module hand-copied that exact sequence; a review finding closed that
21
+ * drift risk by extracting the shared helper).
22
+ * - simulate refused SPECIFICALLY for being too expensive (a numeric
23
+ * `gasUsed` on an `{ ok: false }` simulate result — the executor's own
24
+ * refuse-unmineable signal) -> `{ fired: false }` with NO fire record
25
+ * written at all; the caller alone decides what happens next (fall
26
+ * through to its own chained/plain path).
27
+ * - any OTHER simulate failure (a genuine, non-gas Pact error) -> throws,
28
+ * never silently treated as "doesn't fit."
29
+ * - `row.server_resolver` registered as a MULTI-TX orchestrator ->
30
+ * `{ fired: false }` BEFORE simulating or firing at all, never reaching
31
+ * `fireByServerResolver` — that dispatcher awaits a multi-tx
32
+ * orchestrator's entire run inline, which is exactly what
33
+ * `handlers/execute.ts`'s own plain-fire branch refuses to do for every
34
+ * other row (REQ-H06: queued 202, never fired inline). A review finding
35
+ * caught that this function had no equivalent guard.
36
+ * - otherwise, `row.server_resolver` routes the fire through
37
+ * `fireByServerResolver`'s single-tx path, which runs its OWN
38
+ * safety-guard simulate (a different, merged payload) and postpones
39
+ * (never submits) on failure or an over-budget gas guard -> `{ fired:
40
+ * false }` with NO fire record written, exactly like the gas-refusal
41
+ * case above. Detected via `FireResult.postponed` (see that field's own
42
+ * doc comment) — a review finding caught that this result is otherwise
43
+ * structurally indistinguishable from a genuine on-chain fire failure,
44
+ * and recording it as one would permanently orphan a one-time row.
45
+ * - the single-tx variant is actually fired and then genuinely fails for
46
+ * real (a true on-chain revert, not a gas issue) -> recorded as a failed
47
+ * fire, same as any plain one-shot cronoton's fire failure; `fired: true`
48
+ * still, so the caller never falls back to the chain at this point (Pact
49
+ * transactions are atomic — no partial state to recover from).
50
+ */
51
+ import { executeCodexTransaction } from "./executor.js";
52
+ import { fireByServerResolver, getServerResolver } from "./resolvers.js";
53
+ import { rowToDefinition } from "./store/mappers.js";
54
+ import { recordAndFinalizeFire } from "./fire-and-record.js";
55
+ /** Distinct from the ordinary one-shot fire path's own
56
+ * `codex_cronoton.fire`/`.fire_failed`, so an operator reading the audit
57
+ * log can tell a single-tx attempt apart from an ordinary one-shot fire or
58
+ * a chained run start. */
59
+ const SINGLE_TX_AUDIT_ACTION = {
60
+ success: "codex_cronoton.single_tx.fire",
61
+ failure: "codex_cronoton.single_tx.fire_failed",
62
+ };
63
+ /**
64
+ * Decide — and, when it fits, fire — a row's single-tx-first variant. See the
65
+ * module doc above for the full decision shape.
66
+ *
67
+ * `extras.auditDetailExtra` (e.g. `{ actor: "scheduler" }`/`{ actor:
68
+ * "ancient" }`) is merged into the resulting `codex_cronoton.single_tx.fire`/
69
+ * `.fire_failed` audit event's detail, exactly like `fire-and-record.ts`'s
70
+ * own `fireAndRecord`/every other fire path's audit event already does. A
71
+ * review finding caught this function silently dropping that attribution —
72
+ * every OTHER fire path (`tick.ts`'s plain-fire/chained-run branches,
73
+ * `handlers/execute.ts`'s `fireAndRecord` wrapper) tags its audit event with
74
+ * `actor: "scheduler"` or `actor: "ancient"`, but a single-tx-first fire's
75
+ * audit event carried no such field at all, regardless of which trigger
76
+ * caused it.
77
+ */
78
+ export async function attemptSingleTxFirst(row, ctx, extras = {}) {
79
+ if (!row.try_single_tx_first)
80
+ return { fired: false };
81
+ // A row's `server_resolver` can be registered as a multi-tx orchestrator
82
+ // (fanning out to many on-chain transactions, dispatched asynchronously).
83
+ // `fireByServerResolver` awaits that orchestrator's ENTIRE run inline —
84
+ // exactly what `handlers/execute.ts`'s own plain-fire branch explicitly
85
+ // refuses to do for every other row (REQ-H06: queued 202, never fired
86
+ // inline). A review finding caught that this function had no equivalent
87
+ // guard, so a `try_single_tx_first=1` row bound to a multi-tx resolver
88
+ // would synchronously await the orchestrator on both the scheduler tick
89
+ // and the manual-trigger endpoint, bypassing that invariant entirely and
90
+ // losing the multi-tx `txKeys` breakdown `recordAndFinalizeFire` never
91
+ // threads through. Treat this exactly like a gas-refusal: no fire record,
92
+ // caller falls through to its own existing chained/plain/queued decision.
93
+ if (row.server_resolver && getServerResolver(row.server_resolver)?.kind === "multi-tx") {
94
+ return { fired: false };
95
+ }
96
+ const definition = rowToDefinition(row);
97
+ const sim = await executeCodexTransaction(definition, "simulate", {
98
+ runtime: ctx.runtime,
99
+ resolver: ctx.resolver,
100
+ config: ctx.config,
101
+ });
102
+ if (!sim.ok) {
103
+ if (typeof sim.gasUsed === "number") {
104
+ // Refused specifically for being too expensive — the executor's own
105
+ // refuse-unmineable signal. No fire record written; the caller alone
106
+ // decides what happens next (fall through to the chained path).
107
+ return { fired: false };
108
+ }
109
+ // A genuine, non-gas simulate failure — propagate as a real error, never
110
+ // silently treated as "doesn't fit."
111
+ throw new Error(sim.error ?? "single-tx simulate failed");
112
+ }
113
+ // Fits — fire via the exact same plain one-shot dispatcher
114
+ // `fire-and-record.ts`'s own `fireAndRecord` uses (`ctx` already carries
115
+ // every field `fireByServerResolver`'s opts need structurally, so no
116
+ // separate translation object here either).
117
+ const result = await fireByServerResolver(definition, row, ctx);
118
+ if (result.postponed) {
119
+ // A review finding caught this: `row.server_resolver` can route a
120
+ // single-tx-first row through `fireWithServerResolver`'s OWN
121
+ // safety-guard simulate (a different, merged payload than the one this
122
+ // function already simulated above) or its single-tx gas guard — either
123
+ // can postpone (never submit to chain at all) with an `{ ok: false,
124
+ // terminalIntent: null }` result that is otherwise indistinguishable
125
+ // from a genuine on-chain fire failure. Recording that as a "failure"
126
+ // fire (as the code below does for a REAL failure) would permanently
127
+ // orphan a one-time row: the claim already cleared `next_fire_at`
128
+ // before this attempt ran, `applyTerminalIntent(row.id, null, ...)` is
129
+ // a documented no-op, and the row would never be reselected by the
130
+ // scheduler again. Treat it exactly like this function's OWN
131
+ // gas-refusal case instead — no fire record, caller falls through.
132
+ return { fired: false };
133
+ }
134
+ // Record + finalize + audit via the SAME shared helper
135
+ // `handlers/execute.ts`'s own fire path uses — not a parallel
136
+ // reimplementation (a review finding caught this module hand-copying that
137
+ // exact sequence).
138
+ const { fireId } = await recordAndFinalizeFire(result, ctx, row, definition, {
139
+ auditAction: SINGLE_TX_AUDIT_ACTION,
140
+ auditDetailExtra: extras.auditDetailExtra,
141
+ });
142
+ return { fired: true, result, fireId };
143
+ }
@@ -22,6 +22,20 @@ export interface CommitCodexCronotonInput {
22
22
  /** When true, the row is host-fired on an event (via executeNow) rather than on a
23
23
  * timer — a THIRD trigger-only reason: it commits scheduler-off (next_fire_at NULL). */
24
24
  eventDriven?: boolean;
25
+ /**
26
+ * Opt-in "try single-tx first" flag — ALWAYS rejected at commit time. A
27
+ * brand-new row never has `codex_cronoton_steps` rows yet (they're inserted
28
+ * via a separate, later `insertStep` call), so there is never a fallback
29
+ * chain to justify the flag this early. Enable it later via
30
+ * {@link editCodexCronoton} once ≥1 step row exists.
31
+ */
32
+ trySingleTxFirst?: boolean;
33
+ /**
34
+ * Single-tx Pact-code production mode. Only `'custom'` is supported today;
35
+ * `'default'` is reserved for the sibling (not-yet-shipped) topic and is
36
+ * ALWAYS rejected at commit time.
37
+ */
38
+ singleTxMode?: "custom" | "default";
25
39
  }
26
40
  interface CommitOpts extends DbDep {
27
41
  now?: Date;
@@ -60,6 +74,13 @@ export interface EditCodexCronotonPatch {
60
74
  * edit or a scheduled→event-driven conversion. There is no persisted column, so
61
75
  * the edit path relies on this patch signal (the persisted row can't reveal it). */
62
76
  eventDriven?: boolean;
77
+ /** Opt-in "try single-tx first" flag. Enabling it (explicitly `true`, or already
78
+ * on and not explicitly turned off) requires the row to already carry ≥1
79
+ * `codex_cronoton_steps` row — rejected otherwise, naming the missing chain. */
80
+ trySingleTxFirst?: boolean;
81
+ /** Single-tx Pact-code production mode. `'default'` is always rejected — reserved
82
+ * for the sibling (not-yet-shipped) topic. */
83
+ singleTxMode?: "custom" | "default";
63
84
  }
64
85
  /**
65
86
  * Apply-at-next-fire edit. Recomputes next_fire_at when the schedule changes,
@@ -21,6 +21,7 @@ import { runtimeArgKeysCollide } from "../pure/runtime-args.js";
21
21
  import { getServerResolver } from "../resolvers.js";
22
22
  import { CodexCronotonValidationError, TerminalCronotonError } from "./errors.js";
23
23
  import { assertAutoGasGate, assertGasPriceBufferAnu, rowExternalFireable, rowRuntimeArgKeys, } from "./mappers.js";
24
+ import { listStepsForCronoton } from "./steps.js";
24
25
  /** Compute the first next-fire, mapping engine errors to a typed reject. */
25
26
  function computeNextOrReject(mode, config, now) {
26
27
  let next;
@@ -59,6 +60,24 @@ export function commitCodexCronoton(input, opts) {
59
60
  throw new CodexCronotonValidationError("gasPayer.type must be a string");
60
61
  }
61
62
  assertAutoGasGate(input.config);
63
+ // Validated against the FULL allowed set, not just the one reserved
64
+ // literal — a review finding caught that `singleTxMode`'s TypeScript type
65
+ // is erased at runtime, so any out-of-enum string (a typo, a stale client)
66
+ // previously fell through this check uncaught and relied solely on
67
+ // schema.ts's raw SQL CHECK constraint, surfacing as a driver-level
68
+ // SqliteError instead of this function's own typed validation error. (The
69
+ // `'default'` single-tx mode specifically is reserved for the sibling
70
+ // not-yet-shipped Default-mode topic — accepting it would silently
71
+ // configure a mode that never actually composes anything.)
72
+ if (input.singleTxMode !== undefined && input.singleTxMode !== "custom") {
73
+ throw new CodexCronotonValidationError(`singleTxMode must be "custom" (got ${JSON.stringify(input.singleTxMode)}) — "default" is not yet supported`);
74
+ }
75
+ // A brand-new row never has codex_cronoton_steps rows yet (they're inserted
76
+ // via a separate, later insertStep call), so there is never a fallback chain
77
+ // to justify enabling the flag this early — enable it via an edit instead.
78
+ if (input.trySingleTxFirst) {
79
+ throw new CodexCronotonValidationError("trySingleTxFirst cannot be set at commit time — this cronoton has no steps yet; add steps first, then enable it via an edit");
80
+ }
62
81
  // Runtime-arg keys must be DISJOINT from the fixed payload — a trigger-supplied
63
82
  // arg must never be able to clobber a fixed key (e.g. a keyset).
64
83
  const runtimeArgKeys = input.runtimeArgKeys ?? [];
@@ -105,10 +124,11 @@ export function commitCodexCronoton(input, opts) {
105
124
  .prepare(`INSERT INTO codex_cronotons
106
125
  (id, name, description, pact_code, config_json, payload_json,
107
126
  gas_payer_json, signers_json, schedule_mode, schedule_config_json,
108
- server_resolver, external_fireable, runtime_arg_keys, status,
127
+ server_resolver, external_fireable, runtime_arg_keys,
128
+ try_single_tx_first, single_tx_mode, status,
109
129
  next_fire_at, last_fire_at, created_at, modified_at, created_by)
110
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NULL, ?, ?, ?)`)
111
- .run(id, input.name.trim(), input.description, input.pactCode, JSON.stringify(input.config), input.payload ? JSON.stringify(input.payload) : null, JSON.stringify(input.gasPayer), JSON.stringify(input.signers), input.scheduleMode, JSON.stringify(input.scheduleConfig), input.serverResolver ?? null, externalFireable ? 1 : 0, runtimeArgKeys.length > 0 ? JSON.stringify(runtimeArgKeys) : null, nextFireAt, nowIso, nowIso, input.createdBy);
130
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NULL, ?, ?, ?)`)
131
+ .run(id, input.name.trim(), input.description, input.pactCode, JSON.stringify(input.config), input.payload ? JSON.stringify(input.payload) : null, JSON.stringify(input.gasPayer), JSON.stringify(input.signers), input.scheduleMode, JSON.stringify(input.scheduleConfig), input.serverResolver ?? null, externalFireable ? 1 : 0, runtimeArgKeys.length > 0 ? JSON.stringify(runtimeArgKeys) : null, input.trySingleTxFirst ? 1 : 0, input.singleTxMode ?? null, nextFireAt, nowIso, nowIso, input.createdBy);
112
132
  return { id, nextFireAt };
113
133
  }
114
134
  export function getCodexCronoton(id, dep) {
@@ -177,6 +197,13 @@ export function editCodexCronoton(id, patch, opts) {
177
197
  let nextScheduleConfigJson = row.schedule_config_json;
178
198
  let nextServerResolver = row.server_resolver;
179
199
  let nextFireAt = row.next_fire_at;
200
+ // `?? 0`/`?? null`: the row type widens both columns as optional only for
201
+ // pre-existing hand-constructed fixtures elsewhere; a real row from
202
+ // `getCodexCronoton`'s `SELECT *` always carries a concrete value, but the
203
+ // fallback keeps these locals bindable (better-sqlite3 rejects `undefined`
204
+ // params) even against an unusual double that omits them.
205
+ let nextTrySingleTxFirst = row.try_single_tx_first ?? 0;
206
+ let nextSingleTxMode = row.single_tx_mode ?? null;
180
207
  if (typeof patch.name === "string" &&
181
208
  patch.name.trim() !== "" &&
182
209
  patch.name.trim() !== row.name) {
@@ -220,6 +247,45 @@ export function editCodexCronoton(id, patch, opts) {
220
247
  nextServerResolver = patch.serverResolver;
221
248
  changedFields.push("serverResolver");
222
249
  }
250
+ // Validated against the FULL allowed set — see commitCodexCronoton's
251
+ // identical guard's doc comment for why (a review finding: the TS type is
252
+ // erased at runtime, so an out-of-enum string must not fall through to the
253
+ // raw SQL CHECK constraint uncaught). Rejected at edit time regardless of
254
+ // step count, the same as at commit time.
255
+ if (patch.singleTxMode !== undefined && patch.singleTxMode !== "custom") {
256
+ throw new CodexCronotonValidationError(`singleTxMode must be "custom" (got ${JSON.stringify(patch.singleTxMode)}) — "default" is not yet supported`);
257
+ }
258
+ // Enabling the flag (explicitly, OR already on and not explicitly turned off)
259
+ // requires a real fallback chain to exist — otherwise there is nothing for the
260
+ // flag to ever fall back to.
261
+ const willBeTrySingleTxFirst = patch.trySingleTxFirst !== undefined ? patch.trySingleTxFirst : row.try_single_tx_first === 1;
262
+ if (willBeTrySingleTxFirst && listStepsForCronoton(id, { db }).length === 0) {
263
+ throw new CodexCronotonValidationError("trySingleTxFirst requires at least one codex_cronoton_steps row to fall back to — this cronoton has no steps");
264
+ }
265
+ // A review finding caught this: `attemptSingleTxFirst` never reads
266
+ // `single_tx_mode` at all today (it is pure provenance metadata), so
267
+ // nothing previously stopped an edit from turning `trySingleTxFirst` on
268
+ // while leaving `single_tx_mode` at `null` — a state `types.ts`'s own doc
269
+ // comment documents as meaningless ("Meaningful only when
270
+ // try_single_tx_first is 1"). Harmless today (only `'custom'`/`null` are
271
+ // reachable, and both behave identically), but left unresolved it would
272
+ // silently misrecord operator intent once a future `'default'` mode needs
273
+ // to branch on this field. Require the resulting mode to resolve to
274
+ // `'custom'` whenever the flag will be on, mirroring the steps-count guard
275
+ // immediately above.
276
+ const willBeSingleTxMode = patch.singleTxMode !== undefined ? patch.singleTxMode : row.single_tx_mode;
277
+ if (willBeTrySingleTxFirst && willBeSingleTxMode !== "custom") {
278
+ throw new CodexCronotonValidationError("trySingleTxFirst requires singleTxMode: \"custom\" to be set (single_tx_mode is otherwise left meaningless)");
279
+ }
280
+ if (patch.trySingleTxFirst !== undefined &&
281
+ (patch.trySingleTxFirst ? 1 : 0) !== row.try_single_tx_first) {
282
+ nextTrySingleTxFirst = patch.trySingleTxFirst ? 1 : 0;
283
+ changedFields.push("trySingleTxFirst");
284
+ }
285
+ if (patch.singleTxMode !== undefined && patch.singleTxMode !== row.single_tx_mode) {
286
+ nextSingleTxMode = patch.singleTxMode;
287
+ changedFields.push("singleTxMode");
288
+ }
223
289
  let scheduleChanged = false;
224
290
  if (patch.scheduleMode && patch.scheduleConfig) {
225
291
  nextScheduleMode = patch.scheduleMode;
@@ -275,8 +341,9 @@ export function editCodexCronoton(id, patch, opts) {
275
341
  SET name = ?, description = ?, pact_code = ?, config_json = ?,
276
342
  payload_json = ?, gas_payer_json = ?, signers_json = ?,
277
343
  schedule_mode = ?, schedule_config_json = ?, server_resolver = ?,
278
- external_fireable = ?, next_fire_at = ?, modified_at = ?
279
- WHERE id = ?`).run(nextName, nextDescription, nextPactCode, nextConfigJson, nextPayloadJson, nextGasPayerJson, nextSignersJson, nextScheduleMode, nextScheduleConfigJson, nextServerResolver, nextExternalFireable, nextFireAt, (opts.now ?? new Date()).toISOString(), id);
344
+ external_fireable = ?, try_single_tx_first = ?, single_tx_mode = ?,
345
+ next_fire_at = ?, modified_at = ?
346
+ WHERE id = ?`).run(nextName, nextDescription, nextPactCode, nextConfigJson, nextPayloadJson, nextGasPayerJson, nextSignersJson, nextScheduleMode, nextScheduleConfigJson, nextServerResolver, nextExternalFireable, nextTrySingleTxFirst, nextSingleTxMode, nextFireAt, (opts.now ?? new Date()).toISOString(), id);
280
347
  return { changedFields, nextFireAt };
281
348
  }
282
349
  // ── Pause / resume / delete ──────────────────────────────────────────────────
@@ -43,6 +43,7 @@ import { createRun } from "./store/runs.js";
43
43
  import { RunAlreadyInFlightError } from "./store/errors.js";
44
44
  import { listStepsForCronoton } from "./store/steps.js";
45
45
  import { driveRunOnce } from "./runs-driver.js";
46
+ import { attemptSingleTxFirst } from "./single-tx.js";
46
47
  /**
47
48
  * One multi-tx `onTx` collector + the `FireTxKey[]` it fills, threaded into
48
49
  * {@link fireByServerResolver} so an INLINE multi-tx fire records the per-tx
@@ -83,6 +84,21 @@ export async function codexCronotonTickOnce(now, ctx) {
83
84
  skippedIds.push(row.id);
84
85
  continue;
85
86
  }
87
+ // Try-single-tx-first decision — ahead of the chained/plain branch below,
88
+ // per docs/work/khronoton-single-tx-custom/design.md. `fired: false` means
89
+ // either the flag is off or the simulate was refused specifically for
90
+ // being too expensive; either way fall through to the existing
91
+ // chained/plain decision unchanged. `fired: true` means the single-tx
92
+ // variant was actually fired (successfully or not) — the chained/plain
93
+ // path below is never reached for this row.
94
+ const attempt = await attemptSingleTxFirst(row, ctx, { auditDetailExtra: { actor: "scheduler" } });
95
+ if (attempt.fired) {
96
+ if (attempt.result.ok)
97
+ firedIds.push(row.id);
98
+ else
99
+ failedIds.push(row.id);
100
+ continue;
101
+ }
86
102
  // Chained (≥1 codex_cronoton_steps row) vs plain — design.md §A/§B. A
87
103
  // chained row never reaches the one-shot fire path below: its lifecycle
88
104
  // lives in codex_cronoton_runs/..._run_legs, not codex_cronoton_fires.
@@ -218,6 +234,28 @@ export async function processDueManualBatchesOnce(now, ctx) {
218
234
  cancelledIds.push(batch.id);
219
235
  continue;
220
236
  }
237
+ if (cronoton.try_single_tx_first) {
238
+ // A review finding caught this: this loop fires the parent's raw
239
+ // top-level definition directly via `fireByServerResolver`, with NO
240
+ // `attemptSingleTxFirst` gas-ceiling simulate-then-decide guard — the
241
+ // exact guard `codexCronotonTickOnce`'s due-row branch and
242
+ // `executeNow`'s manual-trigger branch both now apply ahead of this
243
+ // same definition. A `try_single_tx_first=1` row's top-level fields
244
+ // are no longer inert placeholder data (docs/work/
245
+ // khronoton-single-tx-custom/design.md) — they are the operator's
246
+ // real single-tx Pact code, so firing them here on a repeating timer
247
+ // with no gas check is a genuinely new, unsafe bypass this topic's
248
+ // own change in field semantics introduces. Stop the batch rather
249
+ // than risk an unmineable (or unintended) repeated submission; the
250
+ // operator can re-trigger via `executeNow`, which DOES apply the
251
+ // guard. (Manual batches on an ORDINARY chained row — zero
252
+ // `try_single_tx_first` — already bypass the step machinery
253
+ // entirely; that is a separate, pre-existing gap this fix does not
254
+ // attempt to close.)
255
+ cancelManualBatch(batch.id, { db: ctx.db });
256
+ cancelledIds.push(batch.id);
257
+ continue;
258
+ }
221
259
  const claimed = claimManualBatchFire(batch, now, { db: ctx.db });
222
260
  if (!claimed) {
223
261
  skippedIds.push(batch.id);
@@ -126,6 +126,20 @@ export interface FireResult {
126
126
  readonly error?: string;
127
127
  /** Computed one-time terminal intent; `null` for recurring. */
128
128
  readonly terminalIntent: TerminalIntent | null;
129
+ /**
130
+ * `true` only for `resolvers.ts`'s own `postponed(...)` results — a
131
+ * server-resolver-routed fire that was NEVER submitted to chain at all
132
+ * (a dispatch error, an unknown/multi-tx-mismatched resolver name, a
133
+ * resolver-side safety-guard simulate failure, or its gas guard being
134
+ * tripped). Absent/`undefined` for every other `FireResult`, including a
135
+ * GENUINE on-chain fire failure — the two are otherwise structurally
136
+ * identical (`ok: false`, `terminalIntent: null` for a recurring row
137
+ * either way), which is exactly the ambiguity this field exists to
138
+ * resolve: a caller deciding whether "didn't fire" should fall back to
139
+ * an alternate path (as `single-tx.ts`'s `attemptSingleTxFirst` does)
140
+ * must be able to tell the two apart without parsing `error` text.
141
+ */
142
+ readonly postponed?: boolean;
129
143
  }
130
144
  /**
131
145
  * Result of a `submit` run. Builds, signs, pre-flights, and submits — never
@@ -203,6 +217,23 @@ export interface CodexCronotonRow {
203
217
  * `SELECT *` carry the column.
204
218
  */
205
219
  public_observable?: number;
220
+ /**
221
+ * When 1, a chained row attempts a single-transaction variant of its own
222
+ * work (via `pact_code`/`payload_json`/`config_json`/`gas_payer_json`/
223
+ * `signers_json`, reinterpreted) before falling through to the step-by-step
224
+ * chain. Optional so pre-existing hand-constructed row doubles (test
225
+ * fixtures across the package, predating this column) still typecheck;
226
+ * real rows from `SELECT *` carry the column (value is never actually
227
+ * undefined at runtime — `installSchema`'s `ensureColumn` backfills
228
+ * `NOT NULL DEFAULT 0` on every row).
229
+ */
230
+ try_single_tx_first?: number;
231
+ /**
232
+ * Meaningful only when `try_single_tx_first` is 1: how the single-tx Pact
233
+ * code was produced. `null`/absent when unset. Optional for the same
234
+ * pre-existing-fixture-compatibility reason as `try_single_tx_first`.
235
+ */
236
+ single_tx_mode?: "custom" | "default" | null;
206
237
  status: "active" | "paused" | "completed" | "error";
207
238
  next_fire_at: string | null;
208
239
  last_fire_at: string | null;
@@ -189,6 +189,23 @@ interface CodexCronotonRow {
189
189
  * `SELECT *` carry the column.
190
190
  */
191
191
  public_observable?: number;
192
+ /**
193
+ * When 1, a chained row attempts a single-transaction variant of its own
194
+ * work (via `pact_code`/`payload_json`/`config_json`/`gas_payer_json`/
195
+ * `signers_json`, reinterpreted) before falling through to the step-by-step
196
+ * chain. Optional so pre-existing hand-constructed row doubles (test
197
+ * fixtures across the package, predating this column) still typecheck;
198
+ * real rows from `SELECT *` carry the column (value is never actually
199
+ * undefined at runtime — `installSchema`'s `ensureColumn` backfills
200
+ * `NOT NULL DEFAULT 0` on every row).
201
+ */
202
+ try_single_tx_first?: number;
203
+ /**
204
+ * Meaningful only when `try_single_tx_first` is 1: how the single-tx Pact
205
+ * code was produced. `null`/absent when unset. Optional for the same
206
+ * pre-existing-fixture-compatibility reason as `try_single_tx_first`.
207
+ */
208
+ single_tx_mode?: "custom" | "default" | null;
192
209
  status: "active" | "paused" | "completed" | "error";
193
210
  next_fire_at: string | null;
194
211
  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-uYSglFrJ.js';
2
+ import { a as CodexCronotonFireRow, C as CodexCronotonRow, f as CodexFireMode } from '../types-DH7Ym8FQ.js';
3
3
 
4
4
  /**
5
5
  * The theming boundary. Every Khronoton UI surface renders inside a