@ancientpantheon/khronoton-core 0.13.0 → 0.14.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.
@@ -15,8 +15,34 @@
15
15
  * at module-eval time, exactly as a server resolver self-registers into
16
16
  * `resolvers.ts`.
17
17
  */
18
- /** Registry of step planners keyed by `planner_name`. */
19
- const STEP_PLANNERS = {};
18
+ import { resolveYieldRefs } from "../pure/yields.js";
19
+ /**
20
+ * Normalize a `StepPlanner`'s return value to the `{ legs, yield? }` shape
21
+ * regardless of which form the planner actually returned — the SINGLE
22
+ * shared normalizer `runs-driver.ts` and `handlers/steps.ts` both call, so
23
+ * neither hand-rolls its own array-vs-object check.
24
+ */
25
+ export function normalizePlannerResult(result) {
26
+ if (Array.isArray(result))
27
+ return { legs: result };
28
+ return result;
29
+ }
30
+ /**
31
+ * Registry of step planners keyed by `planner_name`. Built via
32
+ * `Object.create(null)`, NOT a `{}` literal — `planner_name` is unconstrained
33
+ * free-form `TEXT` (schema.ts only enforces NOT NULL for a planner-mode
34
+ * step, no enum/whitelist), so a step row naming
35
+ * `"constructor"`/`"toString"`/`"hasOwnProperty"`/etc. would otherwise make a
36
+ * `{}`-based lookup return a truthy inherited `Object.prototype` member
37
+ * instead of `undefined`, bypassing every caller's "undefined means not
38
+ * registered" contract (`resolvePlannerFor` below, and
39
+ * `runs-driver.ts`'s/`handlers/steps.ts`'s "planner not registered" branches)
40
+ * and failing downstream with an unrelated `TypeError` instead of the
41
+ * intended clean `PlannerNotRegisteredError`/404. Mirrors the identical fix
42
+ * already applied to the sibling yield pool (`store/yields.ts`'s
43
+ * `getYieldPool`) for the same class of bug.
44
+ */
45
+ const STEP_PLANNERS = Object.create(null);
20
46
  /**
21
47
  * Register (or replace) a named step planner. A module that owns a planner
22
48
  * calls this at module-eval time so the registry is populated by the time
@@ -25,7 +51,9 @@ const STEP_PLANNERS = {};
25
51
  export function registerStepPlanner(name, planner) {
26
52
  STEP_PLANNERS[name] = planner;
27
53
  }
28
- /** Read a registered step planner by name, or `undefined`. */
54
+ /** Read a registered step planner by name, or `undefined` — including for a
55
+ * name colliding with an `Object.prototype` member, since `STEP_PLANNERS` is
56
+ * prototype-less (see its own doc comment above). */
29
57
  export function getStepPlanner(name) {
30
58
  return STEP_PLANNERS[name];
31
59
  }
@@ -40,11 +68,27 @@ export function getStepPlanner(name) {
40
68
  * Returns `undefined` for an unregistered `planner_name` — callers decide
41
69
  * how to report that (a thrown `PlannerNotRegisteredError` for the real
42
70
  * driver, a 404 for the standalone-fire route).
71
+ *
72
+ * Also resolves any `{"$yield": "<name>"}` placeholder in the step's
73
+ * `planner_params_json` against `yieldPool` BEFORE a caller ever invokes the
74
+ * planner (`docs/work/khronoton-step-yield-carry/design.md`'s "Consuming a
75
+ * yield") — returned as a shallow-cloned `resolvedStep` with that field
76
+ * replaced by the resolved JSON string, so `ouronet.aqp-inject` and every
77
+ * other planner keep calling `parseJson(step.planner_params_json, {})`
78
+ * exactly as they do today and simply receive already-resolved values; zero
79
+ * planner-side changes needed. `yieldPool` defaults to `{}`, so every
80
+ * pre-Wave-3 call site (passing only `(step, seams)`) is unaffected — a step
81
+ * with no `$yield` references anywhere resolves byte-identical to before
82
+ * this parameter existed.
43
83
  */
44
- export function resolvePlannerFor(step, seams) {
84
+ export function resolvePlannerFor(step, seams, yieldPool = {}) {
45
85
  const planner = getStepPlanner(step.planner_name ?? "");
46
86
  if (!planner)
47
87
  return undefined;
48
88
  const plannerCtx = { runtime: seams.runtime, resolver: seams.resolver, config: seams.config };
49
- return { planner, plannerCtx };
89
+ const resolvedStep = {
90
+ ...step,
91
+ planner_params_json: JSON.stringify(resolveYieldRefs(JSON.parse(step.planner_params_json ?? "{}"), yieldPool)),
92
+ };
93
+ return { planner, plannerCtx, resolvedStep };
50
94
  }
@@ -8,15 +8,19 @@ import { type StepPlanner } from "./registry.js";
8
8
  * `read-string`-equivalent safety net, so this value is guarded
9
9
  * regardless of source).
10
10
  * 2. Parse `signers`/`config`/`gasPayer`; derive `executor`.
11
- * 3. Read the patron's live STOA balance via `coin.get-balance` (a
12
- * `dirtyRead` simulate, never a signed tx) — a failed read is a genuine
13
- * error, never "balance is zero".
11
+ * 3. If `params.amountOverride` is set, shape-guard it against
12
+ * `/^\d+\.\d+$/` and use it directly as the amount — skipping steps 4-5
13
+ * below entirely (no live probe at all). Otherwise, read the patron's
14
+ * live STOA balance via `coin.get-balance` (a `dirtyRead` simulate,
15
+ * never a signed tx) — a failed read is a genuine error, never "balance
16
+ * is zero".
14
17
  * 4. Validate the read result is numeric; `0` -> `[]` (the step is
15
18
  * trivially satisfied — mirrors `unstallPlanner`'s own "zero stale
16
19
  * users -> `[]`" convention).
17
- * 5. Format the balance as a decimal literal and build the one
18
- * `LQD|C_WrapStoa` leg, attaching a scoped `coin.TRANSFER` capability
19
- * (appended to, never replacing, signer 0's original capabilities
20
- * string).
20
+ * 5. Format the balance as a decimal literal.
21
+ * 6. Build the one `LQD|C_WrapStoa` leg, attaching a scoped `coin.TRANSFER`
22
+ * capability (appended to, never replacing, signer 0's original
23
+ * capabilities string), and report the final amount used back out as
24
+ * `{ legs: [leg], yield: amount }`.
21
25
  */
22
26
  export declare const stoaWrapPlanner: StepPlanner;
@@ -6,12 +6,16 @@
6
6
  *
7
7
  * Shape: always exactly ONE leg (never fans out — this built-in exists for
8
8
  * the capability-construction risk alone, see design.md's problem statement,
9
- * not for leg-count complexity). The amount is a LIVE `coin.get-balance`
10
- * read of the patron's current STOA balance, not an inter-step-carried
11
- * value (Khronoton has no mechanism for that yet — see design.md §A,
12
- * "Out of scope") — a self-correcting choice: if a prior drain step landed
13
- * and wrap hasn't run yet (or failed and is re-planned), the patron's
14
- * balance at read-time already equals exactly what's eligible to wrap.
9
+ * not for leg-count complexity). By default the amount is a LIVE
10
+ * `coin.get-balance` read of the patron's current STOA balance — a
11
+ * self-correcting choice: if a prior drain step landed and wrap hasn't run
12
+ * yet (or failed and is re-planned), the patron's balance at read-time
13
+ * already equals exactly what's eligible to wrap. `params.amountOverride`
14
+ * (see `docs/work/khronoton-step-yield-carry/design.md`) lets a caller skip
15
+ * that live probe entirely and supply the exact amount to wrap instead —
16
+ * e.g. a prior step's carried yield, via `{"$yield": "..."}` resolution one
17
+ * layer up. Either way, the function always reports the final amount it
18
+ * actually used back out as `yield`, so a later step can carry it forward.
15
19
  *
16
20
  * `coin` is called WITHOUT a namespace prefix throughout this module —
17
21
  * unlike `ouronet-ns.AQP-EVCT`/`ouronet-ns.AQP-FVT`, `coin` is Kadena's
@@ -104,16 +108,20 @@ function formatPactDecimal(n) {
104
108
  * `read-string`-equivalent safety net, so this value is guarded
105
109
  * regardless of source).
106
110
  * 2. Parse `signers`/`config`/`gasPayer`; derive `executor`.
107
- * 3. Read the patron's live STOA balance via `coin.get-balance` (a
108
- * `dirtyRead` simulate, never a signed tx) — a failed read is a genuine
109
- * error, never "balance is zero".
111
+ * 3. If `params.amountOverride` is set, shape-guard it against
112
+ * `/^\d+\.\d+$/` and use it directly as the amount — skipping steps 4-5
113
+ * below entirely (no live probe at all). Otherwise, read the patron's
114
+ * live STOA balance via `coin.get-balance` (a `dirtyRead` simulate,
115
+ * never a signed tx) — a failed read is a genuine error, never "balance
116
+ * is zero".
110
117
  * 4. Validate the read result is numeric; `0` -> `[]` (the step is
111
118
  * trivially satisfied — mirrors `unstallPlanner`'s own "zero stale
112
119
  * users -> `[]`" convention).
113
- * 5. Format the balance as a decimal literal and build the one
114
- * `LQD|C_WrapStoa` leg, attaching a scoped `coin.TRANSFER` capability
115
- * (appended to, never replacing, signer 0's original capabilities
116
- * string).
120
+ * 5. Format the balance as a decimal literal.
121
+ * 6. Build the one `LQD|C_WrapStoa` leg, attaching a scoped `coin.TRANSFER`
122
+ * capability (appended to, never replacing, signer 0's original
123
+ * capabilities string), and report the final amount used back out as
124
+ * `{ legs: [leg], yield: amount }`.
117
125
  */
118
126
  export const stoaWrapPlanner = async (step, ctx) => {
119
127
  const params = parseJson(step.planner_params_json, {});
@@ -132,27 +140,47 @@ export const stoaWrapPlanner = async (step, ctx) => {
132
140
  const config = parseJson(step.config_json, {});
133
141
  const gasPayer = parseJson(step.gas_payer_json, { type: "gas-station" });
134
142
  const executorCtx = { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config };
135
- // Bare `coin.get-balance` — `coin` is Kadena's root/system module, never
136
- // namespaced under `ctx.runtime.namespace` (see module doc above).
137
- const probeDefinition = {
138
- pactCode: '(coin.get-balance (read-string "patron"))',
139
- config,
140
- payload: { patron: patronAccount },
141
- gasPayer,
142
- signers,
143
- };
144
- const result = await executeCodexTransaction(probeDefinition, "simulate", executorCtx);
145
- if (!result.ok) {
146
- throw new Error(result.error ?? "coin.get-balance read failed");
147
- }
148
- const data = result.rawResult?.data;
149
- if (typeof data !== "number") {
150
- throw new Error("ouronet.stoa-wrap: coin.get-balance returned a non-numeric result");
143
+ let amount;
144
+ if (params.amountOverride !== undefined) {
145
+ if (!/^\d+\.\d+$/.test(params.amountOverride)) {
146
+ throw new Error(`ouronet.stoa-wrap: amountOverride must be a non-negative decimal string (e.g. "5.0"), got ${JSON.stringify(params.amountOverride)}`);
147
+ }
148
+ // Mirror the live-probe branch's own `data === 0` short-circuit below:
149
+ // a zero amount means there is nothing to wrap this pass (e.g. a
150
+ // yield-carried drain amount of "0.0"), not a doomed zero-value
151
+ // transfer — real review finding: without this check, "0.0" passed
152
+ // the decimal-shape regex above and flowed straight into building a
153
+ // real signed leg and a `coin.TRANSFER ... 0.0` capability line,
154
+ // unlike the probed path which already refuses to build anything for
155
+ // a zero balance.
156
+ if (Number(params.amountOverride) === 0) {
157
+ return [];
158
+ }
159
+ amount = params.amountOverride;
151
160
  }
152
- if (data === 0) {
153
- return [];
161
+ else {
162
+ // Bare `coin.get-balance` — `coin` is Kadena's root/system module, never
163
+ // namespaced under `ctx.runtime.namespace` (see module doc above).
164
+ const probeDefinition = {
165
+ pactCode: '(coin.get-balance (read-string "patron"))',
166
+ config,
167
+ payload: { patron: patronAccount },
168
+ gasPayer,
169
+ signers,
170
+ };
171
+ const result = await executeCodexTransaction(probeDefinition, "simulate", executorCtx);
172
+ if (!result.ok) {
173
+ throw new Error(result.error ?? "coin.get-balance read failed");
174
+ }
175
+ const data = result.rawResult?.data;
176
+ if (typeof data !== "number") {
177
+ throw new Error("ouronet.stoa-wrap: coin.get-balance returned a non-numeric result");
178
+ }
179
+ if (data === 0) {
180
+ return [];
181
+ }
182
+ amount = formatPactDecimal(data);
154
183
  }
155
- const amount = formatPactDecimal(data);
156
184
  // `ouronet-ns.TS01-C2` — the module's REAL, deployed, namespaced path
157
185
  // (confirmed against `03_TS01-C2.pact:1838`/`12_LIQUID.pact:612`); built
158
186
  // from `ctx.runtime.namespace`, never hardcoded, so a consumer on a
@@ -196,6 +224,6 @@ export const stoaWrapPlanner = async (step, ctx) => {
196
224
  };
197
225
  }),
198
226
  };
199
- return [leg];
227
+ return { legs: [leg], yield: amount };
200
228
  };
201
229
  registerStepPlanner("ouronet.stoa-wrap", stoaWrapPlanner);
@@ -0,0 +1,57 @@
1
+ /**
2
+ * yields — the pure `$yield` placeholder resolver
3
+ * (`docs/work/khronoton-step-yield-carry/design.md`'s "Consuming a yield").
4
+ *
5
+ * A step references a value a prior step produced by writing a structured
6
+ * placeholder, `{"$yield": "<name>"}`, anywhere a literal value would
7
+ * normally go inside its stored `payload_json`/`planner_params_json`.
8
+ * `resolveYieldRefs` walks a parsed JSON value and substitutes every such
9
+ * placeholder against a run's yield pool (a flat `{name: value}` map — see
10
+ * `store/yields.ts`'s `getYieldPool`), leaving everything else untouched. No
11
+ * DB, no chain client, no I/O: pure and dependency-free, following
12
+ * `run-advance.ts`/`split-plan.ts`'s convention of keeping types local to the
13
+ * module that owns them.
14
+ *
15
+ * A yielded value is returned as-is, never recursed into further — it is
16
+ * already fully resolved (it was produced by a planner's return value or a
17
+ * confirmed leg's on-chain result, not itself written with placeholders).
18
+ */
19
+ /**
20
+ * Thrown by `resolveYieldRefs` when a `{"$yield": "<name>"}` placeholder
21
+ * names a yield that has not been produced yet in this run (typo, wrong
22
+ * step order, or referenced before it was ever produced) — mirroring
23
+ * `runs-driver.ts`'s `PlannerNotRegisteredError` precedent of living next
24
+ * to its own primary thrower rather than in `store/errors.ts`, and this
25
+ * package's existing "never silently guess" posture: a missing yield must
26
+ * never silently resolve to `null`/`undefined`.
27
+ */
28
+ export declare class YieldNotFoundError extends Error {
29
+ constructor(name: string);
30
+ }
31
+ /**
32
+ * Recursively walks `value`, substituting every `{"$yield": "<name>"}`
33
+ * placeholder against `pool`. Arrays map each element through
34
+ * `resolveYieldRefs`; a placeholder object resolves to `pool[name]` (not
35
+ * recursed into further); any other plain object has every one of its own
36
+ * entries individually resolved; anything else (string/number/boolean/
37
+ * null) returns as-is.
38
+ */
39
+ export declare function resolveYieldRefs(value: unknown, pool: Record<string, unknown>): unknown;
40
+ /**
41
+ * The `mode:'single'` analog of `planners/registry.ts`'s `resolvePlannerFor`:
42
+ * build a shallow clone of a step row with its `payload_json` field's
43
+ * `$yield` placeholders resolved against `pool`, ready to pass straight into
44
+ * `store/mappers.ts`'s `stepRowToDefinition`. Planner-mode steps get this
45
+ * exact pattern for free via `resolvePlannerFor`; a review finding caught
46
+ * that the single-mode case had quietly re-derived the identical
47
+ * JSON.parse/resolveYieldRefs/JSON.stringify/spread sequence independently
48
+ * in both `runs-driver.ts` and `handlers/steps.ts` instead of sharing one
49
+ * implementation — the exact drift risk `resolvePlannerFor` itself was
50
+ * extracted to close for the planner-mode case, left open for this sibling
51
+ * one. A generic constraint (not importing `CodexCronotonStepRow` by name)
52
+ * keeps this module import-free, matching its own "pure and dependency-free"
53
+ * doc claim above.
54
+ */
55
+ export declare function resolveSingleStepPayload<T extends {
56
+ payload_json: string | null;
57
+ }>(step: T, pool: Record<string, unknown>): T;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * yields — the pure `$yield` placeholder resolver
3
+ * (`docs/work/khronoton-step-yield-carry/design.md`'s "Consuming a yield").
4
+ *
5
+ * A step references a value a prior step produced by writing a structured
6
+ * placeholder, `{"$yield": "<name>"}`, anywhere a literal value would
7
+ * normally go inside its stored `payload_json`/`planner_params_json`.
8
+ * `resolveYieldRefs` walks a parsed JSON value and substitutes every such
9
+ * placeholder against a run's yield pool (a flat `{name: value}` map — see
10
+ * `store/yields.ts`'s `getYieldPool`), leaving everything else untouched. No
11
+ * DB, no chain client, no I/O: pure and dependency-free, following
12
+ * `run-advance.ts`/`split-plan.ts`'s convention of keeping types local to the
13
+ * module that owns them.
14
+ *
15
+ * A yielded value is returned as-is, never recursed into further — it is
16
+ * already fully resolved (it was produced by a planner's return value or a
17
+ * confirmed leg's on-chain result, not itself written with placeholders).
18
+ */
19
+ /**
20
+ * Thrown by `resolveYieldRefs` when a `{"$yield": "<name>"}` placeholder
21
+ * names a yield that has not been produced yet in this run (typo, wrong
22
+ * step order, or referenced before it was ever produced) — mirroring
23
+ * `runs-driver.ts`'s `PlannerNotRegisteredError` precedent of living next
24
+ * to its own primary thrower rather than in `store/errors.ts`, and this
25
+ * package's existing "never silently guess" posture: a missing yield must
26
+ * never silently resolve to `null`/`undefined`.
27
+ */
28
+ export class YieldNotFoundError extends Error {
29
+ constructor(name) {
30
+ super(`no yield named "${name}" has been produced yet in this run`);
31
+ this.name = "YieldNotFoundError";
32
+ }
33
+ }
34
+ /** True for a plain object whose OWN keys are exactly `["$yield"]` and whose
35
+ * `$yield` value is a string — the one shape `resolveYieldRefs` treats as a
36
+ * placeholder rather than an ordinary object to recurse into. */
37
+ function isYieldPlaceholder(value) {
38
+ if (value === null || typeof value !== "object" || Array.isArray(value))
39
+ return false;
40
+ const keys = Object.keys(value);
41
+ return (keys.length === 1 &&
42
+ keys[0] === "$yield" &&
43
+ typeof value.$yield === "string");
44
+ }
45
+ /**
46
+ * Recursively walks `value`, substituting every `{"$yield": "<name>"}`
47
+ * placeholder against `pool`. Arrays map each element through
48
+ * `resolveYieldRefs`; a placeholder object resolves to `pool[name]` (not
49
+ * recursed into further); any other plain object has every one of its own
50
+ * entries individually resolved; anything else (string/number/boolean/
51
+ * null) returns as-is.
52
+ */
53
+ export function resolveYieldRefs(value, pool) {
54
+ if (Array.isArray(value)) {
55
+ return value.map((item) => resolveYieldRefs(item, pool));
56
+ }
57
+ if (isYieldPlaceholder(value)) {
58
+ const name = value.$yield;
59
+ // `Object.prototype.hasOwnProperty.call`, NEVER the `in` operator —
60
+ // `in` walks the full prototype chain, so for a pool that is (or
61
+ // ever could be) a plain object literal, a never-produced name like
62
+ // "toString"/"constructor"/"valueOf"/"hasOwnProperty" would silently
63
+ // resolve to an inherited Object.prototype function instead of
64
+ // throwing YieldNotFoundError, exactly defeating this module's own
65
+ // "never silently guess" invariant (see the class doc above). This
66
+ // check is safe regardless of how `pool` was constructed — it does
67
+ // not rely on every caller remembering to build a prototype-less
68
+ // object (`store/yields.ts`'s `getYieldPool` does, via
69
+ // `Object.create(null)`, but `handlers/steps.ts`'s standalone-fire
70
+ // route passes a bare `{}` literal directly).
71
+ if (!Object.prototype.hasOwnProperty.call(pool, name)) {
72
+ throw new YieldNotFoundError(name);
73
+ }
74
+ return pool[name];
75
+ }
76
+ if (value !== null && typeof value === "object") {
77
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolveYieldRefs(v, pool)]));
78
+ }
79
+ return value;
80
+ }
81
+ /**
82
+ * The `mode:'single'` analog of `planners/registry.ts`'s `resolvePlannerFor`:
83
+ * build a shallow clone of a step row with its `payload_json` field's
84
+ * `$yield` placeholders resolved against `pool`, ready to pass straight into
85
+ * `store/mappers.ts`'s `stepRowToDefinition`. Planner-mode steps get this
86
+ * exact pattern for free via `resolvePlannerFor`; a review finding caught
87
+ * that the single-mode case had quietly re-derived the identical
88
+ * JSON.parse/resolveYieldRefs/JSON.stringify/spread sequence independently
89
+ * in both `runs-driver.ts` and `handlers/steps.ts` instead of sharing one
90
+ * implementation — the exact drift risk `resolvePlannerFor` itself was
91
+ * extracted to close for the planner-mode case, left open for this sibling
92
+ * one. A generic constraint (not importing `CodexCronotonStepRow` by name)
93
+ * keeps this module import-free, matching its own "pure and dependency-free"
94
+ * doc claim above.
95
+ */
96
+ export function resolveSingleStepPayload(step, pool) {
97
+ return {
98
+ ...step,
99
+ payload_json: JSON.stringify(resolveYieldRefs(JSON.parse(step.payload_json ?? "{}"), pool)),
100
+ };
101
+ }
@@ -38,8 +38,10 @@ import { advanceRunStep, bumpRunAttempt, getRun, insertRunLeg, listInFlightRuns,
38
38
  import { listStepsForCronoton } from "./store/steps.js";
39
39
  import { RunLegAlreadyExistsError } from "./store/errors.js";
40
40
  import { stepRowToDefinition } from "./store/mappers.js";
41
+ import { getYieldPool, upsertYield } from "./store/yields.js";
41
42
  import { executeCodexTransaction } from "./executor.js";
42
- import { resolvePlannerFor } from "./planners/registry.js";
43
+ import { resolvePlannerFor, normalizePlannerResult } from "./planners/registry.js";
44
+ import { resolveSingleStepPayload } from "./pure/yields.js";
43
45
  import { advanceRun } from "./pure/run-advance.js";
44
46
  /**
45
47
  * Thrown by `driveRunOnce` when a `mode: 'planner'` step names a
@@ -196,7 +198,7 @@ async function handleSubmitLeg(legIndex, run, stepLegs, now, ctx) {
196
198
  * tick" contract). Returns `true` iff at least one leg landed (confirmed or
197
199
  * failed) this pass.
198
200
  */
199
- async function handlePoll(stepLegs, ctx) {
201
+ async function handlePoll(stepLegs, step, ctx) {
200
202
  const submitted = stepLegs.filter((l) => l.status === "submitted" && l.request_key != null && l.chain_id != null);
201
203
  if (submitted.length === 0)
202
204
  return false;
@@ -216,6 +218,21 @@ async function handlePoll(stepLegs, ctx) {
216
218
  continue; // still pending — absent key means "not landed yet"
217
219
  if (landed.result.status === "success") {
218
220
  markLegConfirmed(leg.id, { db: ctx.db });
221
+ if (step.mode === "single" && step.yield_as) {
222
+ // The only way a plain hand-written Pact call (no JS-side planner
223
+ // runs for it) can contribute a yield: capture the real on-chain
224
+ // return value the moment this step's one leg CONFIRMS. `data` is
225
+ // not declared on `ListenResult.result`'s own narrow type (only
226
+ // `status`/`error` are), since most callers never need it — cast
227
+ // locally rather than widening that shared seam type for this one
228
+ // reader.
229
+ upsertYield({
230
+ runId: leg.run_id,
231
+ name: step.yield_as,
232
+ value: landed.result.data,
233
+ stepIndex: step.step_index,
234
+ }, { db: ctx.db });
235
+ }
219
236
  }
220
237
  else {
221
238
  markLegFailed(leg.id, { errorMessage: landed.result.error?.message ?? "transaction failed on-chain" }, { db: ctx.db });
@@ -325,16 +342,32 @@ async function handleReplanStep(run, step, allRunLegs, now, ctx) {
325
342
  }
326
343
  async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
327
344
  if (step.mode === "planner") {
328
- const resolved = resolvePlannerFor(step, ctx);
345
+ // Resolve any `{"$yield": "<name>"}` placeholder in this step's
346
+ // `planner_params_json` against the run's yield pool BEFORE the planner
347
+ // ever runs — a step with no `$yield` references anywhere resolves
348
+ // against this SAME pool (always `{}` for such a step) byte-identical
349
+ // to before this feature existed.
350
+ const pool = getYieldPool(run.id, { db: ctx.db });
351
+ const resolved = resolvePlannerFor(step, ctx, pool);
329
352
  if (!resolved) {
330
353
  throw new PlannerNotRegisteredError(step.planner_name ?? "(unnamed)");
331
354
  }
332
- const legs = await resolved.planner(step, resolved.plannerCtx);
355
+ const rawResult = await resolved.planner(resolved.resolvedStep, resolved.plannerCtx);
356
+ const normalized = normalizePlannerResult(rawResult);
357
+ const legs = normalized.legs;
333
358
  if (legs.length === 0) {
334
359
  // The planner decided this step needs no work this pass (e.g. nothing
335
360
  // owed) — treat exactly like a cleared barrier, matching
336
361
  // `handleAdvanceStep`'s own terminal-vs-advance branch verbatim rather
337
- // than duplicating it.
362
+ // than duplicating it. A review finding caught that an EARLIER version
363
+ // returned here before ever reaching the yield-write below, silently
364
+ // discarding a yield a planner reported alongside zero legs (e.g. "I
365
+ // confirmed there's nothing to do, and here's the value that proves
366
+ // it") — this step's barrier is cleared either way, so its yield (if
367
+ // any) is just as real and must still be persisted.
368
+ if (normalized.yield !== undefined && step.yield_as) {
369
+ upsertYield({ runId: run.id, name: step.yield_as, value: normalized.yield, stepIndex: run.step_index }, { db: ctx.db });
370
+ }
338
371
  return handleAdvanceStep(run, now, ctx);
339
372
  }
340
373
  // Every generation of this step's legs, NOT attempt-filtered — unlike
@@ -350,6 +383,31 @@ async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
350
383
  const isReplan = allStepLegs.length > 0;
351
384
  const newAttempt = isReplan ? run.attempt + 1 : run.attempt;
352
385
  const startLegIndex = isReplan ? Math.max(...allStepLegs.map((l) => l.leg_index)) + 1 : 0;
386
+ // Leg inserts run BEFORE the attempt bump / deadline touch / yield
387
+ // write, not after — a review finding caught that writing those first
388
+ // let a concurrent loser (two `driveRunOnce` callers racing this exact
389
+ // step generation, per this function's own doc comment above) commit
390
+ // its own `bumpRunAttempt`/`touchRunDeadline`/`upsertYield` calls even
391
+ // though `insertRunLeg` below then throws `RunLegAlreadyExistsError`
392
+ // for THAT caller specifically, meaning only the OTHER (winning)
393
+ // caller's legs actually get submitted. A SECOND review pass (after the
394
+ // yield-ordering fix alone had already landed) caught that
395
+ // `bumpRunAttempt`/`touchRunDeadline` had been left in their ORIGINAL,
396
+ // still-unguarded position — a losing racer was still silently burning
397
+ // through `maxReplanAttempts` roughly twice as fast as the configured
398
+ // budget, racing ahead of `insertRunLeg`'s own loss detection.
399
+ // Inserting legs FIRST means a losing caller never reaches ANY of the
400
+ // three writes below — each one is only ever persisted by whichever
401
+ // caller's legs genuinely won the race.
402
+ legs.forEach((leg, i) => {
403
+ insertRunLeg({
404
+ runId: run.id,
405
+ stepIndex: run.step_index,
406
+ legIndex: startLegIndex + i,
407
+ definitionJson: JSON.stringify(leg),
408
+ attempt: newAttempt,
409
+ }, { db: ctx.db });
410
+ });
353
411
  if (isReplan) {
354
412
  // `bumpRunAttempt` + `touchRunDeadline`, NEVER `advanceRunStep`, for a
355
413
  // genuine re-plan: `advanceRunStep` unconditionally resets `attempt`
@@ -360,15 +418,12 @@ async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
360
418
  bumpRunAttempt(run.id, { db: ctx.db });
361
419
  touchRunDeadline(run.id, computeStepDeadline(now, ctx), { db: ctx.db });
362
420
  }
363
- legs.forEach((leg, i) => {
364
- insertRunLeg({
365
- runId: run.id,
366
- stepIndex: run.step_index,
367
- legIndex: startLegIndex + i,
368
- definitionJson: JSON.stringify(leg),
369
- attempt: newAttempt,
370
- }, { db: ctx.db });
371
- });
421
+ if (normalized.yield !== undefined && step.yield_as) {
422
+ // A planner that yields on a step with no `yield_as` set simply has
423
+ // that value discarded here — the leg-building itself still
424
+ // succeeded, so this is not an error, just nothing to carry forward.
425
+ upsertYield({ runId: run.id, name: step.yield_as, value: normalized.yield, stepIndex: run.step_index }, { db: ctx.db });
426
+ }
372
427
  if (!isReplan) {
373
428
  // First entry (no legs existed yet) — byte-identical in final effect
374
429
  // to before: stamp this step's first deadline (and the no-op
@@ -378,7 +433,14 @@ async function handleReplanStepInner(run, step, allRunLegs, now, ctx) {
378
433
  }
379
434
  return true;
380
435
  }
381
- const definition = stepRowToDefinition(step);
436
+ // Same yield-reference resolution as the planner branch above, applied to
437
+ // the stored `payload_json` instead of `planner_params_json` — via the
438
+ // SAME shared `resolveSingleStepPayload` helper `handlers/steps.ts` uses,
439
+ // not a parallel reimplementation (a review finding caught the two call
440
+ // sites independently re-deriving the identical sequence).
441
+ const pool = getYieldPool(run.id, { db: ctx.db });
442
+ const resolvedStep = resolveSingleStepPayload(step, pool);
443
+ const definition = stepRowToDefinition(resolvedStep);
382
444
  insertRunLeg({ runId: run.id, stepIndex: run.step_index, legIndex: 0, definitionJson: JSON.stringify(definition) }, { db: ctx.db });
383
445
  advanceRunStep(run.id, { fromStepIndex: run.step_index, toStepIndex: run.step_index, deadlineAt: computeStepDeadline(now, ctx) }, { db: ctx.db });
384
446
  return true;
@@ -405,7 +467,7 @@ async function executeAction(action, run, step, stepLegs, allRunLegs, now, ctx)
405
467
  case "submit-leg":
406
468
  return handleSubmitLeg(action.legIndex, run, stepLegs, now, ctx);
407
469
  case "poll":
408
- return handlePoll(stepLegs, ctx);
470
+ return handlePoll(stepLegs, step, ctx);
409
471
  case "advance-step":
410
472
  return handleAdvanceStep(run, now, ctx);
411
473
  case "replan-step":
@@ -423,11 +485,20 @@ async function executeAction(action, run, step, stepLegs, allRunLegs, now, ctx)
423
485
  * defensive no-ops) or a pass makes no further progress.
424
486
  */
425
487
  export async function driveRunOnce(runId, now, ctx) {
488
+ const initialRun = getRun(runId, { db: ctx.db });
489
+ if (!initialRun)
490
+ return; // the run vanished between listInFlightRuns and this call
491
+ // Fetched ONCE for the whole call, not per inner-loop pass: a run's
492
+ // parent cronoton_id is immutable for the run's lifetime, so its static
493
+ // step definitions can never change mid-call either — a confirmed LOW
494
+ // performance finding (this file's own `allRunLegs` hoist two lines below
495
+ // already recognized and closed exactly this class of redundant re-query
496
+ // for legs; the same re-query was still happening here for steps).
497
+ const steps = listStepsForCronoton(initialRun.codex_cronoton_id, { db: ctx.db });
426
498
  for (;;) {
427
499
  const run = getRun(runId, { db: ctx.db });
428
500
  if (!run)
429
- return; // the run vanished between listInFlightRuns and this call
430
- const steps = listStepsForCronoton(run.codex_cronoton_id, { db: ctx.db });
501
+ return; // the run vanished since the last pass
431
502
  const step = steps.find((s) => s.step_index === run.step_index);
432
503
  if (!step) {
433
504
  // A run/step-definition mismatch (e.g. steps deleted out from under a
@@ -1,8 +1,9 @@
1
1
  /**
2
- * The consolidated DDL installer for the six codex-cronoton tables: the
2
+ * The consolidated DDL installer for the seven codex-cronoton tables: the
3
3
  * original three (`codex_cronotons`, `codex_cronoton_fires`,
4
4
  * `codex_cronoton_manual_batches`) plus the chained-runs tables
5
- * (`codex_cronoton_steps`, `codex_cronoton_runs`, `codex_cronoton_run_legs`).
5
+ * (`codex_cronoton_steps`, `codex_cronoton_runs`, `codex_cronoton_run_legs`)
6
+ * plus the step-to-step yield carry table (`codex_cronoton_run_yields`).
6
7
  *
7
8
  * This folds the Hub's incremental migration chain (base tables + a dozen later
8
9
  * ALTERs) into the FINAL column shapes, emitted in a single idempotent call.
@@ -24,7 +25,7 @@
24
25
  */
25
26
  import type { Database } from "./seams.js";
26
27
  /**
27
- * Installs the six codex-cronoton tables and their indexes on the injected DB
28
+ * Installs the seven codex-cronoton tables and their indexes on the injected DB
28
29
  * handle in a single idempotent call. Safe to re-run: every statement is guarded
29
30
  * with `IF NOT EXISTS`.
30
31
  *
@@ -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 six codex-cronoton tables and their indexes on the injected DB
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,9 @@ 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");
197
213
  }
@@ -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";