@ancientpantheon/khronoton-core 0.13.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.
- package/CHANGELOG.md +31 -0
- package/README.md +8 -0
- package/dist/{chunk-IAK4UEAA.js → chunk-24THBKR7.js} +188 -28
- package/dist/{chunk-7H5TM3CS.js → chunk-VPVEIDNN.js} +1 -1
- package/dist/{context-P-rCtBbJ.d.ts → context-ec4m0UBZ.d.ts} +1 -1
- package/dist/handlers/execute.js +28 -41
- package/dist/handlers/steps.js +51 -14
- package/dist/hooks/index.d.ts +3 -3
- package/dist/hooks/index.js +2 -2
- package/dist/provider/index.d.ts +3 -3
- package/dist/provider/index.js +93 -45
- package/dist/server/fire-and-record.d.ts +47 -0
- package/dist/server/fire-and-record.js +85 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +9 -0
- package/dist/server/planners/registry.d.ts +41 -3
- package/dist/server/planners/registry.js +49 -5
- package/dist/server/planners/stoa-wrap.d.ts +11 -7
- package/dist/server/planners/stoa-wrap.js +61 -33
- package/dist/server/pure/yields.d.ts +57 -0
- package/dist/server/pure/yields.js +101 -0
- package/dist/server/resolvers.js +7 -1
- package/dist/server/runs-driver.js +89 -18
- package/dist/server/schema.d.ts +4 -3
- package/dist/server/schema.js +26 -1
- package/dist/server/single-tx.d.ts +44 -0
- package/dist/server/single-tx.js +143 -0
- package/dist/server/store/cronoton.d.ts +21 -0
- package/dist/server/store/cronoton.js +72 -5
- package/dist/server/store/index.d.ts +2 -1
- package/dist/server/store/index.js +3 -1
- package/dist/server/store/steps.d.ts +12 -0
- package/dist/server/store/steps.js +26 -3
- package/dist/server/store/yields.d.ts +46 -0
- package/dist/server/store/yields.js +73 -0
- package/dist/server/tick.js +38 -0
- package/dist/server/types.d.ts +31 -0
- package/dist/{types-uYSglFrJ.d.ts → types-DH7Ym8FQ.d.ts} +17 -0
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +2 -2
- package/package.json +1 -1
package/dist/server/schema.js
CHANGED
|
@@ -144,6 +144,17 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_slot
|
|
|
144
144
|
ON codex_cronoton_run_legs(run_id, step_index, leg_index);
|
|
145
145
|
CREATE INDEX IF NOT EXISTS idx_codex_cronoton_run_legs_barrier
|
|
146
146
|
ON codex_cronoton_run_legs(run_id, step_index, status);
|
|
147
|
+
|
|
148
|
+
CREATE TABLE IF NOT EXISTS codex_cronoton_run_yields (
|
|
149
|
+
id TEXT PRIMARY KEY,
|
|
150
|
+
run_id TEXT NOT NULL REFERENCES codex_cronoton_runs(id) ON DELETE CASCADE,
|
|
151
|
+
name TEXT NOT NULL,
|
|
152
|
+
value_json TEXT NOT NULL,
|
|
153
|
+
step_index INTEGER NOT NULL,
|
|
154
|
+
created_at TEXT NOT NULL
|
|
155
|
+
);
|
|
156
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_codex_cronoton_run_yields_name
|
|
157
|
+
ON codex_cronoton_run_yields(run_id, name);
|
|
147
158
|
`;
|
|
148
159
|
/**
|
|
149
160
|
* Idempotently ensures `column` exists on `table`, adding it via `ALTER TABLE
|
|
@@ -168,7 +179,7 @@ function ensureColumn(db, table, column, columnDefSql) {
|
|
|
168
179
|
}
|
|
169
180
|
}
|
|
170
181
|
/**
|
|
171
|
-
* Installs the
|
|
182
|
+
* Installs the seven codex-cronoton tables and their indexes on the injected DB
|
|
172
183
|
* handle in a single idempotent call. Safe to re-run: every statement is guarded
|
|
173
184
|
* with `IF NOT EXISTS`.
|
|
174
185
|
*
|
|
@@ -194,4 +205,18 @@ export function installSchema(db) {
|
|
|
194
205
|
// status enum value, so the existing CHECK constraint is untouched. See
|
|
195
206
|
// `store/runs.ts`'s `claimLegForSubmit`/`releaseLegClaim`.
|
|
196
207
|
ensureColumn(db, "codex_cronoton_run_legs", "claimed_at", "TEXT");
|
|
208
|
+
// Step-to-step yield carry: the NAME a step's confirmed on-chain return
|
|
209
|
+
// value (mode:'single') or planner-returned yield (mode:'planner') gets
|
|
210
|
+
// stored under in `codex_cronoton_run_yields`. Additive via `ensureColumn`,
|
|
211
|
+
// covering both a fresh install and an already-provisioned database.
|
|
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'))");
|
|
197
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,
|
|
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 = ?,
|
|
279
|
-
|
|
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 ──────────────────────────────────────────────────
|
|
@@ -26,7 +26,8 @@ export type { CreateManualBatchInput } from "./manual-batch.js";
|
|
|
26
26
|
export { computeDefinitionFingerprint } from "../pure/fingerprint.js";
|
|
27
27
|
export { getCodexCronotonByPublicToken, setPublicObservable, getCronotonFireCounts, deriveCronotonHealth, toPublicCronotonView, } from "./public.js";
|
|
28
28
|
export type { SetPublicObservableOpts, CronotonFireCounts, CronotonHealth, PublicCronotonView, PublicCronotonFireView, PublicCronotonFiresPage, } from "./public.js";
|
|
29
|
-
export { insertStep, listStepsForCronoton } from "./steps.js";
|
|
29
|
+
export { insertStep, listStepsForCronoton, getStepByIndex } from "./steps.js";
|
|
30
30
|
export type { InsertStepInput, CodexCronotonStepRow } from "./steps.js";
|
|
31
31
|
export { createRun, getRun, listRunLegs, listRunsForCronoton, insertRunLeg, claimLegForSubmit, releaseLegClaim, markLegSubmitted, markLegConfirmed, markLegFailed, listInFlightRuns, advanceRunStep, markRunTerminal, bumpRunAttempt, touchRunDeadline, } from "./runs.js";
|
|
32
32
|
export type { CreateRunInput, CodexCronotonRunRow, CodexCronotonRunLegRow } from "./runs.js";
|
|
33
|
+
export { upsertYield, getYieldPool } from "./yields.js";
|
|
@@ -34,6 +34,8 @@ export { computeDefinitionFingerprint } from "../pure/fingerprint.js";
|
|
|
34
34
|
// ── Public observability: token toggle, by-token read, counts, health, projector ──
|
|
35
35
|
export { getCodexCronotonByPublicToken, setPublicObservable, getCronotonFireCounts, deriveCronotonHealth, toPublicCronotonView, } from "./public.js";
|
|
36
36
|
// ── Chained-run step definitions: insert / list ──────────────────────────────
|
|
37
|
-
export { insertStep, listStepsForCronoton } from "./steps.js";
|
|
37
|
+
export { insertStep, listStepsForCronoton, getStepByIndex } from "./steps.js";
|
|
38
38
|
// ── Chained runs + legs: create / read / leg lifecycle ────────────────────────
|
|
39
39
|
export { createRun, getRun, listRunLegs, listRunsForCronoton, insertRunLeg, claimLegForSubmit, releaseLegClaim, markLegSubmitted, markLegConfirmed, markLegFailed, listInFlightRuns, advanceRunStep, markRunTerminal, bumpRunAttempt, touchRunDeadline, } from "./runs.js";
|
|
40
|
+
// ── Step-to-step yield carry: upsert / read the per-run named-yield pool ─────
|
|
41
|
+
export { upsertYield, getYieldPool } from "./yields.js";
|
|
@@ -11,6 +11,7 @@ export interface InsertStepInput {
|
|
|
11
11
|
plannerName?: string;
|
|
12
12
|
plannerParams?: unknown;
|
|
13
13
|
idempotent?: boolean;
|
|
14
|
+
yieldAs?: string;
|
|
14
15
|
}
|
|
15
16
|
export interface CodexCronotonStepRow {
|
|
16
17
|
id: string;
|
|
@@ -27,6 +28,7 @@ export interface CodexCronotonStepRow {
|
|
|
27
28
|
idempotent: number;
|
|
28
29
|
created_at: string;
|
|
29
30
|
modified_at: string;
|
|
31
|
+
yield_as: string | null;
|
|
30
32
|
}
|
|
31
33
|
/**
|
|
32
34
|
* Insert one step row. Returns the new row's id.
|
|
@@ -40,3 +42,13 @@ export interface CodexCronotonStepRow {
|
|
|
40
42
|
export declare function insertStep(input: InsertStepInput, dep: DbDep): string;
|
|
41
43
|
/** Full raw snake_case rows for a cronoton's steps, ordered by step_index ASC. */
|
|
42
44
|
export declare function listStepsForCronoton(codexCronotonId: string, dep: DbDep): CodexCronotonStepRow[];
|
|
45
|
+
/**
|
|
46
|
+
* One step row at a specific `(codexCronotonId, stepIndex)` slot, or `null`.
|
|
47
|
+
* A direct point lookup hitting `idx_codex_cronoton_steps_order` (the
|
|
48
|
+
* existing unique index on exactly this pair, `schema.ts`), instead of a
|
|
49
|
+
* caller fetching every step for the cronoton via {@link listStepsForCronoton}
|
|
50
|
+
* and filtering client-side for one row — a confirmed LOW performance
|
|
51
|
+
* finding from `handlers/steps.ts`'s standalone fire/simulate route, which
|
|
52
|
+
* only ever needs one step per request.
|
|
53
|
+
*/
|
|
54
|
+
export declare function getStepByIndex(codexCronotonId: string, stepIndex: number, dep: DbDep): CodexCronotonStepRow | null;
|
|
@@ -9,6 +9,13 @@
|
|
|
9
9
|
* validation of step sequencing, no planner-registry lookup, no "is this the
|
|
10
10
|
* right next step" decision logic — that's explicitly Phase 2's job
|
|
11
11
|
* (`pure/run-advance.ts`), not this layer's.
|
|
12
|
+
*
|
|
13
|
+
* `yieldAs`/`yield_as` (step-to-step yield carry, per
|
|
14
|
+
* `docs/work/khronoton-step-yield-carry/design.md`) applies uniformly to
|
|
15
|
+
* BOTH step modes: for `mode:'single'` it names what to store the confirmed
|
|
16
|
+
* leg's on-chain return value as; for `mode:'planner'` it names what to
|
|
17
|
+
* store the planner's returned yield value as. The step row itself owns the
|
|
18
|
+
* yield's NAME either way — never the planner, never hard-coded elsewhere.
|
|
12
19
|
*/
|
|
13
20
|
import crypto from "node:crypto";
|
|
14
21
|
import { isUniqueConstraintError, StepAlreadyExistsError } from "./errors.js";
|
|
@@ -29,9 +36,9 @@ export function insertStep(input, dep) {
|
|
|
29
36
|
.prepare(`INSERT INTO codex_cronoton_steps
|
|
30
37
|
(id, codex_cronoton_id, step_index, mode, pact_code, config_json,
|
|
31
38
|
payload_json, gas_payer_json, signers_json, planner_name,
|
|
32
|
-
planner_params_json, idempotent, created_at, modified_at)
|
|
33
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
34
|
-
.run(id, input.codexCronotonId, input.stepIndex, input.mode, input.pactCode ?? null, input.config !== undefined ? JSON.stringify(input.config) : null, input.payload !== undefined ? JSON.stringify(input.payload) : null, input.gasPayer !== undefined ? JSON.stringify(input.gasPayer) : null, input.signers !== undefined ? JSON.stringify(input.signers) : null, input.plannerName ?? null, input.plannerParams !== undefined ? JSON.stringify(input.plannerParams) : null, input.idempotent ? 1 : 0, now, now);
|
|
39
|
+
planner_params_json, idempotent, created_at, modified_at, yield_as)
|
|
40
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
41
|
+
.run(id, input.codexCronotonId, input.stepIndex, input.mode, input.pactCode ?? null, input.config !== undefined ? JSON.stringify(input.config) : null, input.payload !== undefined ? JSON.stringify(input.payload) : null, input.gasPayer !== undefined ? JSON.stringify(input.gasPayer) : null, input.signers !== undefined ? JSON.stringify(input.signers) : null, input.plannerName ?? null, input.plannerParams !== undefined ? JSON.stringify(input.plannerParams) : null, input.idempotent ? 1 : 0, now, now, input.yieldAs ?? null);
|
|
35
42
|
}
|
|
36
43
|
catch (error) {
|
|
37
44
|
if (isUniqueConstraintError(error)) {
|
|
@@ -49,3 +56,19 @@ export function listStepsForCronoton(codexCronotonId, dep) {
|
|
|
49
56
|
ORDER BY step_index ASC`)
|
|
50
57
|
.all(codexCronotonId);
|
|
51
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* One step row at a specific `(codexCronotonId, stepIndex)` slot, or `null`.
|
|
61
|
+
* A direct point lookup hitting `idx_codex_cronoton_steps_order` (the
|
|
62
|
+
* existing unique index on exactly this pair, `schema.ts`), instead of a
|
|
63
|
+
* caller fetching every step for the cronoton via {@link listStepsForCronoton}
|
|
64
|
+
* and filtering client-side for one row — a confirmed LOW performance
|
|
65
|
+
* finding from `handlers/steps.ts`'s standalone fire/simulate route, which
|
|
66
|
+
* only ever needs one step per request.
|
|
67
|
+
*/
|
|
68
|
+
export function getStepByIndex(codexCronotonId, stepIndex, dep) {
|
|
69
|
+
const row = dep.db
|
|
70
|
+
.prepare(`SELECT * FROM codex_cronoton_steps
|
|
71
|
+
WHERE codex_cronoton_id = ? AND step_index = ?`)
|
|
72
|
+
.get(codexCronotonId, stepIndex);
|
|
73
|
+
return row ?? null;
|
|
74
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { DbDep } from "../seams.js";
|
|
2
|
+
/**
|
|
3
|
+
* Insert-or-overwrite one named yield for a run. `ON CONFLICT(run_id, name)
|
|
4
|
+
* DO UPDATE` is the design's stated overwrite semantics (design.md's
|
|
5
|
+
* "Storage" section): a replanned step's freshest computed value always
|
|
6
|
+
* wins, with no separate invalidation step needed since nothing downstream
|
|
7
|
+
* of an unconfirmed step ever runs yet. `value` is JSON-stringified so any
|
|
8
|
+
* JSON-serializable on-chain return value (string, number, object) round-trips.
|
|
9
|
+
*
|
|
10
|
+
* `input.value` is normalized to `null` first when it is `undefined` —
|
|
11
|
+
* `JSON.stringify(undefined)` returns the JS value `undefined`, not a
|
|
12
|
+
* string, which `better-sqlite3`'s `.run()` refuses to bind (it only
|
|
13
|
+
* accepts numbers/bigints/strings/buffers/`null`) and throws. A caller can
|
|
14
|
+
* legitimately hit this: `runs-driver.ts`'s single-mode confirm path stores
|
|
15
|
+
* whatever on-chain return value a `ListenResult` carries, and that `data`
|
|
16
|
+
* field is optional on the wire — a real review finding caught this
|
|
17
|
+
* crashing AFTER the leg's `markLegConfirmed` write had already committed,
|
|
18
|
+
* permanently stranding an otherwise-successful run with no yield ever
|
|
19
|
+
* recorded. `null` round-trips through `value_json`/`getYieldPool` like any
|
|
20
|
+
* other JSON value, so a caller that legitimately yields `null` is
|
|
21
|
+
* unaffected — this only changes what an absent/`undefined` value becomes.
|
|
22
|
+
*/
|
|
23
|
+
export declare function upsertYield(input: {
|
|
24
|
+
runId: string;
|
|
25
|
+
name: string;
|
|
26
|
+
value: unknown;
|
|
27
|
+
stepIndex: number;
|
|
28
|
+
}, dep: DbDep): void;
|
|
29
|
+
/**
|
|
30
|
+
* The full `{name: value}` map for a run — `{}` for a run with zero yields.
|
|
31
|
+
* Every `value_json` is parsed back into its original JSON value, so a
|
|
32
|
+
* caller resolving a `{"$yield": "<name>"}` placeholder (`pure/yields.ts`)
|
|
33
|
+
* reads the same shape that was originally passed to {@link upsertYield}.
|
|
34
|
+
*
|
|
35
|
+
* Built via `Object.create(null)`, NOT a `{}` literal — a plain object
|
|
36
|
+
* literal inherits `Object.prototype`, so `pure/yields.ts`'s own
|
|
37
|
+
* `name in pool` membership check (which walks the prototype chain) would
|
|
38
|
+
* otherwise treat `"toString"`/`"constructor"`/`"hasOwnProperty"`/etc. as
|
|
39
|
+
* present even for an empty pool, silently resolving a `$yield` reference
|
|
40
|
+
* to a built-in function instead of throwing `YieldNotFoundError` — exactly
|
|
41
|
+
* the "never silently guess" invariant this feature is built around. A
|
|
42
|
+
* prototype-less object also makes a yield legitimately named `"__proto__"`
|
|
43
|
+
* store as an ordinary own property instead of reassigning the object's own
|
|
44
|
+
* prototype (which a `{}` literal's special `__proto__` setter would do).
|
|
45
|
+
*/
|
|
46
|
+
export declare function getYieldPool(runId: string, dep: DbDep): Record<string, unknown>;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* yields — the decision-free CRUD layer for `codex_cronoton_run_yields`, the
|
|
3
|
+
* flat named-yield pool a chained run's steps write to and read from (per
|
|
4
|
+
* `docs/work/khronoton-step-yield-carry/design.md`). Mirrors `./runs.ts`'s
|
|
5
|
+
* own style (`crypto.randomUUID()` ids, a `DbDep`-shaped second arg) rather
|
|
6
|
+
* than introducing a new idiom for this one table.
|
|
7
|
+
*
|
|
8
|
+
* No resolution/validation logic lives here — "does a referenced yield name
|
|
9
|
+
* exist" (`YieldNotFoundError`) is `pure/yields.ts`'s job (Wave 2's T2), not
|
|
10
|
+
* this layer's; this file only ever does the mechanical read/write.
|
|
11
|
+
*/
|
|
12
|
+
import crypto from "node:crypto";
|
|
13
|
+
/**
|
|
14
|
+
* Insert-or-overwrite one named yield for a run. `ON CONFLICT(run_id, name)
|
|
15
|
+
* DO UPDATE` is the design's stated overwrite semantics (design.md's
|
|
16
|
+
* "Storage" section): a replanned step's freshest computed value always
|
|
17
|
+
* wins, with no separate invalidation step needed since nothing downstream
|
|
18
|
+
* of an unconfirmed step ever runs yet. `value` is JSON-stringified so any
|
|
19
|
+
* JSON-serializable on-chain return value (string, number, object) round-trips.
|
|
20
|
+
*
|
|
21
|
+
* `input.value` is normalized to `null` first when it is `undefined` —
|
|
22
|
+
* `JSON.stringify(undefined)` returns the JS value `undefined`, not a
|
|
23
|
+
* string, which `better-sqlite3`'s `.run()` refuses to bind (it only
|
|
24
|
+
* accepts numbers/bigints/strings/buffers/`null`) and throws. A caller can
|
|
25
|
+
* legitimately hit this: `runs-driver.ts`'s single-mode confirm path stores
|
|
26
|
+
* whatever on-chain return value a `ListenResult` carries, and that `data`
|
|
27
|
+
* field is optional on the wire — a real review finding caught this
|
|
28
|
+
* crashing AFTER the leg's `markLegConfirmed` write had already committed,
|
|
29
|
+
* permanently stranding an otherwise-successful run with no yield ever
|
|
30
|
+
* recorded. `null` round-trips through `value_json`/`getYieldPool` like any
|
|
31
|
+
* other JSON value, so a caller that legitimately yields `null` is
|
|
32
|
+
* unaffected — this only changes what an absent/`undefined` value becomes.
|
|
33
|
+
*/
|
|
34
|
+
export function upsertYield(input, dep) {
|
|
35
|
+
const id = crypto.randomUUID();
|
|
36
|
+
const now = new Date().toISOString();
|
|
37
|
+
const value = input.value === undefined ? null : input.value;
|
|
38
|
+
dep.db
|
|
39
|
+
.prepare(`INSERT INTO codex_cronoton_run_yields (id, run_id, name, value_json, step_index, created_at)
|
|
40
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
41
|
+
ON CONFLICT(run_id, name) DO UPDATE SET
|
|
42
|
+
value_json = excluded.value_json,
|
|
43
|
+
step_index = excluded.step_index,
|
|
44
|
+
created_at = excluded.created_at`)
|
|
45
|
+
.run(id, input.runId, input.name, JSON.stringify(value), input.stepIndex, now);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The full `{name: value}` map for a run — `{}` for a run with zero yields.
|
|
49
|
+
* Every `value_json` is parsed back into its original JSON value, so a
|
|
50
|
+
* caller resolving a `{"$yield": "<name>"}` placeholder (`pure/yields.ts`)
|
|
51
|
+
* reads the same shape that was originally passed to {@link upsertYield}.
|
|
52
|
+
*
|
|
53
|
+
* Built via `Object.create(null)`, NOT a `{}` literal — a plain object
|
|
54
|
+
* literal inherits `Object.prototype`, so `pure/yields.ts`'s own
|
|
55
|
+
* `name in pool` membership check (which walks the prototype chain) would
|
|
56
|
+
* otherwise treat `"toString"`/`"constructor"`/`"hasOwnProperty"`/etc. as
|
|
57
|
+
* present even for an empty pool, silently resolving a `$yield` reference
|
|
58
|
+
* to a built-in function instead of throwing `YieldNotFoundError` — exactly
|
|
59
|
+
* the "never silently guess" invariant this feature is built around. A
|
|
60
|
+
* prototype-less object also makes a yield legitimately named `"__proto__"`
|
|
61
|
+
* store as an ordinary own property instead of reassigning the object's own
|
|
62
|
+
* prototype (which a `{}` literal's special `__proto__` setter would do).
|
|
63
|
+
*/
|
|
64
|
+
export function getYieldPool(runId, dep) {
|
|
65
|
+
const rows = dep.db
|
|
66
|
+
.prepare(`SELECT name, value_json FROM codex_cronoton_run_yields WHERE run_id = ?`)
|
|
67
|
+
.all(runId);
|
|
68
|
+
const pool = Object.create(null);
|
|
69
|
+
for (const row of rows) {
|
|
70
|
+
pool[row.name] = JSON.parse(row.value_json);
|
|
71
|
+
}
|
|
72
|
+
return pool;
|
|
73
|
+
}
|