@ancientpantheon/khronoton-core 0.12.0 → 0.13.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -0
  3. package/dist/blockchain/stoachain.d.ts +1 -1
  4. package/dist/blockchain/stoachain.js +16 -1
  5. package/dist/{chunk-KQZYMPZS.js → chunk-7H5TM3CS.js} +1 -1
  6. package/dist/{chunk-GIGLXIMC.js → chunk-IAK4UEAA.js} +710 -23
  7. package/dist/{context-CApk-LP4.d.ts → context-P-rCtBbJ.d.ts} +1 -1
  8. package/dist/handlers/execute.d.ts +12 -4
  9. package/dist/handlers/execute.js +42 -5
  10. package/dist/handlers/index.d.ts +2 -1
  11. package/dist/handlers/index.js +4 -1
  12. package/dist/handlers/read.d.ts +11 -0
  13. package/dist/handlers/read.js +65 -1
  14. package/dist/handlers/steps.d.ts +3 -0
  15. package/dist/handlers/steps.js +115 -0
  16. package/dist/hooks/index.d.ts +3 -3
  17. package/dist/hooks/index.js +2 -2
  18. package/dist/provider/index.d.ts +3 -3
  19. package/dist/provider/index.js +33 -2
  20. package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
  21. package/dist/server/executor.d.ts +14 -1
  22. package/dist/server/executor.js +144 -26
  23. package/dist/server/index.d.ts +11 -2
  24. package/dist/server/index.js +29 -1
  25. package/dist/server/loop.d.ts +17 -13
  26. package/dist/server/loop.js +19 -12
  27. package/dist/server/planners/evict.d.ts +20 -0
  28. package/dist/server/planners/evict.js +143 -0
  29. package/dist/server/planners/inject.d.ts +22 -0
  30. package/dist/server/planners/inject.js +120 -0
  31. package/dist/server/planners/registry.d.ts +80 -0
  32. package/dist/server/planners/registry.js +50 -0
  33. package/dist/server/planners/stoa-unwrap.d.ts +23 -0
  34. package/dist/server/planners/stoa-unwrap.js +204 -0
  35. package/dist/server/planners/stoa-wrap.d.ts +22 -0
  36. package/dist/server/planners/stoa-wrap.js +201 -0
  37. package/dist/server/planners/unstall.d.ts +25 -0
  38. package/dist/server/planners/unstall.js +135 -0
  39. package/dist/server/pure/run-advance.d.ts +76 -0
  40. package/dist/server/pure/run-advance.js +94 -0
  41. package/dist/server/pure/split-plan.d.ts +144 -0
  42. package/dist/server/pure/split-plan.js +362 -0
  43. package/dist/server/resolvers.js +48 -6
  44. package/dist/server/runs-driver.d.ts +92 -0
  45. package/dist/server/runs-driver.js +511 -0
  46. package/dist/server/schema.d.ts +5 -2
  47. package/dist/server/schema.js +73 -1
  48. package/dist/server/seams.d.ts +28 -0
  49. package/dist/server/seams.js +4 -0
  50. package/dist/server/store/errors.d.ts +38 -0
  51. package/dist/server/store/errors.js +61 -0
  52. package/dist/server/store/index.d.ts +6 -2
  53. package/dist/server/store/index.js +6 -2
  54. package/dist/server/store/mappers.d.ts +11 -0
  55. package/dist/server/store/mappers.js +20 -0
  56. package/dist/server/store/runs.d.ts +233 -0
  57. package/dist/server/store/runs.js +341 -0
  58. package/dist/server/store/steps.d.ts +42 -0
  59. package/dist/server/store/steps.js +51 -0
  60. package/dist/server/tick.d.ts +7 -0
  61. package/dist/server/tick.js +50 -1
  62. package/dist/server/types.d.ts +42 -3
  63. package/dist/ui/index.js +2 -2
  64. package/package.json +1 -1
@@ -0,0 +1,201 @@
1
+ /**
2
+ * `ouronet.stoa-wrap` — the "Wrap STOA" step planner, ported from OuronetUI's
3
+ * own `tokenOpSpecs.tsx` (`TF_WRAP_STOA`, a different workspace entirely:
4
+ * `OuroborosNetwork/daimons/OuronetUI`). See design.md's §A for the full port
5
+ * rationale.
6
+ *
7
+ * Shape: always exactly ONE leg (never fans out — this built-in exists for
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.
15
+ *
16
+ * `coin` is called WITHOUT a namespace prefix throughout this module —
17
+ * unlike `ouronet-ns.AQP-EVCT`/`ouronet-ns.AQP-FVT`, `coin` is Kadena's
18
+ * root/system module, confirmed against OuronetUI's own bare
19
+ * `coin.get-balance`/`coin.TRANSFER` calls (`tokenOpSpecs.tsx`).
20
+ */
21
+ import { executeCodexTransaction } from "../executor.js";
22
+ import { registerStepPlanner, } from "./registry.js";
23
+ /** Mirrors `store/mappers.ts`'s own one-line helper — duplicated locally per the plan rather than importing a private function from another module. */
24
+ function parseJson(json, fallback) {
25
+ if (json == null)
26
+ return fallback;
27
+ return JSON.parse(json);
28
+ }
29
+ /**
30
+ * Fixed, public, non-secret StoaChain system account OuronetUI's own
31
+ * `coin.TRANSFER` capability for `TF_WRAP_STOA` scopes its second arg to —
32
+ * confirmed against `ouronet-core/src/constants/ouronet.ts:44`. A module-local
33
+ * constant, not a dynamic value; duplicated in `stoa-unwrap.ts` too, per the
34
+ * same per-module-duplication convention `parseJson` above already uses, to
35
+ * keep the two planners independent.
36
+ */
37
+ const STOA_AUTONOMIC_LIQUIDPOT = "c:ZNfuj3iZI83n7MUSKGuoXoSxFg1cyMxCzB3szUHVvrI";
38
+ /** Shape guard for a Kadena `k:`/`c:` account string — see module doc + design.md §C. */
39
+ const ACCOUNT_SHAPE = /^[kc]:[A-Za-z0-9_-]+$/;
40
+ /**
41
+ * Expand a JS exponential-notation number string (e.g. `"1e-7"`,
42
+ * `"1.23e-12"`) into plain fixed-point decimal form (`"0.0000001"`,
43
+ * `"0.00000000000123"`). Pact decimal literals have no exponent syntax, so
44
+ * this is required whenever `Number.prototype.toString`'s own shortest-
45
+ * round-trip representation falls back to exponential form — which it does
46
+ * for any finite magnitude below `1e-6` (there is no upper-bound case to
47
+ * handle here: `formatPactDecimal` below already rejects `n >= 1e21`
48
+ * before this function is ever reached, and `toString` only switches to
49
+ * exponential notation outside the `[1e-6, 1e21)` range).
50
+ */
51
+ function expandExponentialNotation(s) {
52
+ const match = /^(-?)(\d+)(?:\.(\d+))?[eE]([+-]?\d+)$/.exec(s);
53
+ if (!match) {
54
+ throw new Error(`ouronet.stoa-wrap: cannot expand unexpected numeric string: ${s}`);
55
+ }
56
+ const [, sign, intPart, fracPart = "", expStr] = match;
57
+ const exponent = parseInt(expStr, 10);
58
+ const digits = intPart + fracPart;
59
+ const pointPos = intPart.length + exponent;
60
+ if (pointPos <= 0) {
61
+ return `${sign}0.${"0".repeat(-pointPos)}${digits}`;
62
+ }
63
+ if (pointPos >= digits.length) {
64
+ return `${sign}${digits}${"0".repeat(pointPos - digits.length)}.0`;
65
+ }
66
+ return `${sign}${digits.slice(0, pointPos)}.${digits.slice(pointPos)}`;
67
+ }
68
+ /**
69
+ * Format a non-negative finite number as a Pact decimal literal: always has
70
+ * a decimal point, never scientific notation. Throws on a negative/NaN/
71
+ * Infinite input, or one `>= 1e21` — `coin.get-balance` returning such a
72
+ * value is impossible in a correct chain state, so it is treated as a
73
+ * genuine error, not formatted away.
74
+ *
75
+ * Built on `n.toString()` (JS's own SHORTEST round-trip representation),
76
+ * not `n.toFixed(12)` — `toFixed` reintroduces binary-floating-point
77
+ * representation noise for almost any real-world balance (e.g.
78
+ * `(262613.4).toFixed(12) === "262613.400000000023"`, confirmed against the
79
+ * handoff's own measured dispenser balance during this planner's
80
+ * behavioral verification — `toString()` instead gives the clean
81
+ * `"262613.4"`). `toString()` only falls back to exponential notation
82
+ * outside `[1e-6, 1e21)`; `expandExponentialNotation` above handles the
83
+ * small-magnitude side of that (the large side is already rejected by the
84
+ * `n >= 1e21` guard before `toString` is ever called).
85
+ */
86
+ function formatPactDecimal(n) {
87
+ if (!Number.isFinite(n) || n < 0 || n >= 1e21) {
88
+ throw new Error(`ouronet.stoa-wrap: coin.get-balance returned an invalid amount: ${n}`);
89
+ }
90
+ if (n === 0)
91
+ return "0.0";
92
+ let s = n.toString();
93
+ if (s.includes("e") || s.includes("E")) {
94
+ s = expandExponentialNotation(s);
95
+ }
96
+ return s.includes(".") ? s : `${s}.0`;
97
+ }
98
+ /**
99
+ * Drives one `mode:'planner'` step registered under `ouronet.stoa-wrap`:
100
+ *
101
+ * 1. Parse `patronAccount` from `step.planner_params_json`; shape-guard it
102
+ * against `/^[kc]:[A-Za-z0-9_-]+$/` BEFORE it reaches either the payload
103
+ * or a signer's capability line (see design.md §C: capabilities have no
104
+ * `read-string`-equivalent safety net, so this value is guarded
105
+ * regardless of source).
106
+ * 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".
110
+ * 4. Validate the read result is numeric; `0` -> `[]` (the step is
111
+ * trivially satisfied — mirrors `unstallPlanner`'s own "zero stale
112
+ * 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).
117
+ */
118
+ export const stoaWrapPlanner = async (step, ctx) => {
119
+ const params = parseJson(step.planner_params_json, {});
120
+ if (typeof params.patronAccount !== "string") {
121
+ throw new Error("ouronet.stoa-wrap: step.planner_params_json must have a patronAccount string");
122
+ }
123
+ const { patronAccount } = params;
124
+ if (!ACCOUNT_SHAPE.test(patronAccount)) {
125
+ throw new Error(`ouronet.stoa-wrap: patronAccount is not a well-formed k:/c: account: ${JSON.stringify(patronAccount)}`);
126
+ }
127
+ const signers = parseJson(step.signers_json, []);
128
+ if (signers.length === 0) {
129
+ throw new Error("ouronet.stoa-wrap: step.signers_json must have at least one signer (used as the executor)");
130
+ }
131
+ const executor = `k:${signers[0].publicKey}`;
132
+ const config = parseJson(step.config_json, {});
133
+ const gasPayer = parseJson(step.gas_payer_json, { type: "gas-station" });
134
+ 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");
151
+ }
152
+ if (data === 0) {
153
+ return [];
154
+ }
155
+ const amount = formatPactDecimal(data);
156
+ // `ouronet-ns.TS01-C2` — the module's REAL, deployed, namespaced path
157
+ // (confirmed against `03_TS01-C2.pact:1838`/`12_LIQUID.pact:612`); built
158
+ // from `ctx.runtime.namespace`, never hardcoded, so a consumer on a
159
+ // different namespace isn't silently wrong.
160
+ const ts01c2 = `${ctx.runtime.namespace}.TS01-C2`;
161
+ // Every value below flows through `payload` (env-data) and is read back
162
+ // with `read-string`/`read-decimal` in `pactCode` — zero interpolated
163
+ // values in the EXECUTED code, matching `evict.ts`'s own discipline. The
164
+ // ONE deliberate exception is the signer's `capabilities` line below —
165
+ // Pact's signed `clist` has no env-data equivalent, so capabilities must
166
+ // be literal in the signed command (see design.md §C). It is made safe by
167
+ // `patronAccount` already being shape-guarded above and `amount` being a
168
+ // self-formatted decimal literal from a trusted live numeric chain read —
169
+ // never a raw pass-through of untrusted text.
170
+ const leg = {
171
+ pactCode: `(${ts01c2}.LQD|C_WrapStoa (read-string "patron") (read-string "executor") (read-decimal "amount"))`,
172
+ config,
173
+ payload: { patron: patronAccount, executor, amount },
174
+ gasPayer,
175
+ signers: signers.map((signer, index) => {
176
+ if (index !== 0)
177
+ return signer;
178
+ const capLine = `(coin.TRANSFER "${patronAccount}" "${STOA_AUTONOMIC_LIQUIDPOT}" ${amount})`;
179
+ // If signer 0's own key is ALSO the gas-station's signing key,
180
+ // `effectiveSigners` (executor-signers.ts) sees that pubkey "already
181
+ // present" among `signers` and skips synthesizing its own
182
+ // DALOS.GAS_PAYER-scoped entry for it (it only checks presence by
183
+ // pubkey, never capability content) — so narrowing this signer to
184
+ // `capabilityMode:'scoped'` with ONLY `coin.TRANSFER` would silently
185
+ // drop the gas-sponsorship grant that SAME key needs, surfacing as an
186
+ // opaque failure at submit time, not at plan time. Append the
187
+ // identical capability line `effectiveSigners` would otherwise have
188
+ // synthesized, so the narrowed signer still carries it.
189
+ const gasPayerCapLine = gasPayer.type === "gas-station" && gasPayer.gasStationSignerKey === signer.publicKey
190
+ ? `(${ctx.runtime.namespace}.DALOS.GAS_PAYER "" 0 0.0)`
191
+ : null;
192
+ return {
193
+ ...signer,
194
+ capabilityMode: "scoped",
195
+ capabilities: [signer.capabilities, capLine, gasPayerCapLine].filter(Boolean).join("\n"),
196
+ };
197
+ }),
198
+ };
199
+ return [leg];
200
+ };
201
+ registerStepPlanner("ouronet.stoa-wrap", stoaWrapPlanner);
@@ -0,0 +1,25 @@
1
+ import { type StepPlanner } from "./registry.js";
2
+ /**
3
+ * Drives one `mode:'planner'` step registered under `ouronet.aqp-unstall`:
4
+ *
5
+ * 1. Parse `fvtId`/`patronAccount`/`rewardDptfId` from
6
+ * `step.planner_params_json`. Derive `executor = k:<the step's own first
7
+ * signer's publicKey>` — identical validation shape to `evictPlanner`'s
8
+ * own (`executor` itself is unused by `CCp_FvtFixSlice`'s signature —
9
+ * `(patron, fvt-id, reward-dptf-id, users)`, no credited caller — but the
10
+ * signer-presence check stays, since a step with zero signers can never
11
+ * build or sign ANY leg this planner might produce).
12
+ * 2. Read `URH_FvtStalePresentUsers(fvtId)` via a `"simulate"` call (same
13
+ * pattern as `evictPlanner`'s own plan-read probe) — a LIVE CHAIN READ, so
14
+ * its result is validated at runtime (`Array.isArray` + every element a
15
+ * string) before being trusted as part of a signed transaction's payload.
16
+ * A failed read rethrows — never "needs splitting", since there is no
17
+ * list to split.
18
+ * 3. Zero stale users → `[]` (step trivially satisfied).
19
+ * 4. Else `splitPlan(staleUsers, probe, ceiling)` (`../pure/split-plan.js`),
20
+ * where `probe` builds a `CCp_FvtFixSlice` leg for the candidate batch and
21
+ * simulates it; a `SplitResult.ok:false` rethrows as a genuine error,
22
+ * never silently treated as "nothing to do".
23
+ * 5. Return one `PlannedLeg` per batch in the result.
24
+ */
25
+ export declare const unstallPlanner: StepPlanner;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * `ouronet.aqp-unstall` — the "Unstale FVT" step planner, ported from
3
+ * OuronetUI's `FvtUnstaleFlow.tsx`/`fvtOwnerSpecs.tsx` (`FVT_FIX_SLICE`) — a
4
+ * different workspace entirely: `OuroborosNetwork/daimons/OuronetUI`. See
5
+ * design.md's §C for the full port rationale.
6
+ *
7
+ * Shape: unlike `evictPlanner`, the plan READ here (`URH_FvtStalePresentUsers`)
8
+ * returns the raw item list to split, not a pre-built on-chain plan — the
9
+ * actual leg-count decision is this planner's own, delegated whole to the
10
+ * generic gas-probe-and-pack algorithm (`../pure/split-plan.js`, ported
11
+ * separately). `CCp_FvtFixSlice` is the parallel-safe, order-independent
12
+ * repair entrypoint `FVT_FIX_SLICE` names — disjoint slices of stale users can
13
+ * be sent together, which is exactly what `splitPlan`'s batches are.
14
+ */
15
+ import { executeCodexTransaction } from "../executor.js";
16
+ import { AUTO_GAS_CEILING } from "../seams.js";
17
+ import { splitPlan } from "../pure/split-plan.js";
18
+ import { registerStepPlanner, } from "./registry.js";
19
+ /** Mirrors `store/mappers.ts`'s own one-line helper — duplicated locally per the plan rather than importing a private function from another module. */
20
+ function parseJson(json, fallback) {
21
+ if (json == null)
22
+ return fallback;
23
+ return JSON.parse(json);
24
+ }
25
+ /**
26
+ * Drives one `mode:'planner'` step registered under `ouronet.aqp-unstall`:
27
+ *
28
+ * 1. Parse `fvtId`/`patronAccount`/`rewardDptfId` from
29
+ * `step.planner_params_json`. Derive `executor = k:<the step's own first
30
+ * signer's publicKey>` — identical validation shape to `evictPlanner`'s
31
+ * own (`executor` itself is unused by `CCp_FvtFixSlice`'s signature —
32
+ * `(patron, fvt-id, reward-dptf-id, users)`, no credited caller — but the
33
+ * signer-presence check stays, since a step with zero signers can never
34
+ * build or sign ANY leg this planner might produce).
35
+ * 2. Read `URH_FvtStalePresentUsers(fvtId)` via a `"simulate"` call (same
36
+ * pattern as `evictPlanner`'s own plan-read probe) — a LIVE CHAIN READ, so
37
+ * its result is validated at runtime (`Array.isArray` + every element a
38
+ * string) before being trusted as part of a signed transaction's payload.
39
+ * A failed read rethrows — never "needs splitting", since there is no
40
+ * list to split.
41
+ * 3. Zero stale users → `[]` (step trivially satisfied).
42
+ * 4. Else `splitPlan(staleUsers, probe, ceiling)` (`../pure/split-plan.js`),
43
+ * where `probe` builds a `CCp_FvtFixSlice` leg for the candidate batch and
44
+ * simulates it; a `SplitResult.ok:false` rethrows as a genuine error,
45
+ * never silently treated as "nothing to do".
46
+ * 5. Return one `PlannedLeg` per batch in the result.
47
+ */
48
+ export const unstallPlanner = async (step, ctx) => {
49
+ const params = parseJson(step.planner_params_json, {});
50
+ if (typeof params.fvtId !== "string" ||
51
+ typeof params.patronAccount !== "string" ||
52
+ typeof params.rewardDptfId !== "string") {
53
+ throw new Error("ouronet.aqp-unstall: step.planner_params_json must have fvtId, patronAccount, and rewardDptfId strings");
54
+ }
55
+ const { fvtId, patronAccount, rewardDptfId } = params;
56
+ const signers = parseJson(step.signers_json, []);
57
+ if (signers.length === 0) {
58
+ throw new Error("ouronet.aqp-unstall: step.signers_json must have at least one signer (needed to build/sign a leg, even though CCp_FvtFixSlice itself takes no executor arg)");
59
+ }
60
+ const config = parseJson(step.config_json, {});
61
+ const gasPayer = parseJson(step.gas_payer_json, { type: "gas-station" });
62
+ const executorCtx = { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config };
63
+ // `ouronet-ns.AQP-FVT` — the module's REAL, deployed, namespaced path
64
+ // (confirmed against the ported source's own `fvtOwnerSpecs.tsx`
65
+ // `FVT_FIX_SLICE`/`URH_FvtStalePresentUsers` entrypoint strings and
66
+ // `05_FVT.pact`'s own `(namespace "ouronet-ns")` declaration; a bare
67
+ // `AQP-FVT.*` reference is unresolvable by Pact's namespace mechanism).
68
+ // Built from `ctx.runtime.namespace`, never hardcoded, so a consumer on a
69
+ // different namespace isn't silently wrong. The SAME module `injectPlanner`
70
+ // targets — the two planners are a two-step sequence against one contract.
71
+ const fvt = `${ctx.runtime.namespace}.AQP-FVT`;
72
+ const staleReadDefinition = {
73
+ pactCode: `(${fvt}.URH_FvtStalePresentUsers (read-string "fvt-id"))`,
74
+ config,
75
+ payload: { "fvt-id": fvtId },
76
+ gasPayer,
77
+ signers,
78
+ };
79
+ const staleReadResult = await executeCodexTransaction(staleReadDefinition, "simulate", executorCtx);
80
+ if (!staleReadResult.ok) {
81
+ throw new Error(staleReadResult.error ?? "URH_FvtStalePresentUsers read failed");
82
+ }
83
+ const data = staleReadResult.rawResult?.data;
84
+ if (!Array.isArray(data) || !data.every((s) => typeof s === "string")) {
85
+ throw new Error("ouronet.aqp-unstall: URH_FvtStalePresentUsers returned a non-array-of-strings result");
86
+ }
87
+ const staleUsers = data;
88
+ if (staleUsers.length === 0) {
89
+ return [];
90
+ }
91
+ // Every value below flows through `payload` (env-data, `addData` per
92
+ // `executor.ts`'s `buildTransaction`) and is read back with
93
+ // `read-string`/`read-msg` in `pactCode` — NEVER string-concatenated into
94
+ // the Pact source itself, mirroring `evictPlanner`'s own "no code-injection
95
+ // surface" guarantee. `users` (a LIST, not a scalar) goes through
96
+ // `(read-msg "users")` — env-data's generic JSON-value reader, since
97
+ // `read-string`/`read-integer` are scalar-only; `addData` already
98
+ // serializes array values as-is per `executor.ts`'s `buildTransaction`.
99
+ const fixSlicePactCode = `(${fvt}.CCp_FvtFixSlice (read-string "patron") (read-string "fvt-id") (read-string "reward-dptf-id") (read-msg "users"))`;
100
+ const probe = async (batch) => {
101
+ const leg = {
102
+ pactCode: fixSlicePactCode,
103
+ config,
104
+ payload: { patron: patronAccount, "fvt-id": fvtId, "reward-dptf-id": rewardDptfId, users: [...batch] },
105
+ gasPayer,
106
+ signers,
107
+ };
108
+ const result = await executeCodexTransaction(leg, "simulate", executorCtx);
109
+ if (result.ok) {
110
+ return { ok: true, gas: result.gasUsed ?? 0 };
111
+ }
112
+ if (typeof result.gasUsed === "number") {
113
+ return { ok: false, floor: result.gasUsed };
114
+ }
115
+ // A genuine chain-level/Pact-execution failure — never swallowed into a
116
+ // `ProbeOutcome`. `splitPlan` never calls `probe` in a context where a
117
+ // genuine error should be treated as "infeasible," so letting it
118
+ // propagate out of this callback and up through `splitPlan` unchanged is
119
+ // correct.
120
+ throw new Error(result.error ?? "CCp_FvtFixSlice simulation failed");
121
+ };
122
+ const ceiling = ctx.config?.autoGasCeiling ?? AUTO_GAS_CEILING;
123
+ const result = await splitPlan(staleUsers, probe, ceiling);
124
+ if (!result.ok) {
125
+ throw new Error(result.reason);
126
+ }
127
+ return result.batches.map((batch) => ({
128
+ pactCode: fixSlicePactCode,
129
+ config,
130
+ payload: { patron: patronAccount, "fvt-id": fvtId, "reward-dptf-id": rewardDptfId, users: batch },
131
+ gasPayer,
132
+ signers,
133
+ }));
134
+ };
135
+ registerStepPlanner("ouronet.aqp-unstall", unstallPlanner);
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Phase 2's pure decision core for chained runs (handoff
3
+ * `HANDOFF-khronoton-chained-runs.md` §3/§5; full spec in
4
+ * `docs/work/khronoton-chained-runs-phase-2/design.md`'s "Decision algorithm").
5
+ *
6
+ * Given a run's current state and its current step's legs, `advanceRun`
7
+ * decides what happens next — "submit this leg," "keep polling," "the step
8
+ * is done, advance," "ask the planner again," or "give up." No DB, no chain
9
+ * client, no I/O: pure and dependency-free, following `runtime-args.ts` /
10
+ * `capability.ts`'s convention of keeping types local to the module that
11
+ * owns the function's input/output shape rather than in `server/types.ts`.
12
+ */
13
+ /** The two fan shapes a step's legs can be submitted in (handoff §3: "is this
14
+ * step serial (submit one, wait) or parallel (submit all)"). A `mode:
15
+ * 'single'` step from `codex_cronoton_steps` has exactly one leg and is
16
+ * represented to `advanceRun` as `stepMode: 'serial'` — with N=1, "submit
17
+ * one, wait" and "submit all" are the same thing, so a third enum value
18
+ * would be a pure alias. The caller (Phase 3's driver) makes this call, not
19
+ * this function — it already knows the step's `mode` column and, for a
20
+ * planner step, the registered planner's own fan declaration. */
21
+ export type StepMode = "serial" | "parallel";
22
+ export interface RunState {
23
+ readonly status: "planning" | "awaiting" | "advancing" | "succeeded" | "failed" | "abandoned";
24
+ readonly stepIndex: number;
25
+ readonly stepCount: number;
26
+ /** ISO timestamp, or `null` for "no deadline configured" (unbounded wait). */
27
+ readonly deadlineAt: string | null;
28
+ /** Re-plan attempts already spent on the CURRENT step (resets to 0 when the
29
+ * driver advances to a new step — Phase 3's job, not this function's). */
30
+ readonly attempt: number;
31
+ }
32
+ export interface LegState {
33
+ readonly legIndex: number;
34
+ readonly status: "pending" | "submitted" | "confirmed" | "failed";
35
+ }
36
+ export interface RunPolicy {
37
+ readonly stepMode: StepMode;
38
+ /** False for a `mode: 'single'` step: there is no registered planner to
39
+ * consult, so a failed leg has no "ask the chain who is still owed"
40
+ * escape hatch and the run must fail immediately (handoff §5.5 only
41
+ * describes re-planning in terms of a planner's `plan()` reading live
42
+ * state — a fixed single-tx step has no such thing). */
43
+ readonly canReplan: boolean;
44
+ /** Ignored when `canReplan` is false. Bounds §5.5's "small attempt count
45
+ * per step"; exhausting it fails the run per §5.1. */
46
+ readonly maxReplanAttempts: number;
47
+ }
48
+ export type RunAction = {
49
+ readonly kind: "submit-leg";
50
+ readonly legIndex: number;
51
+ } | {
52
+ readonly kind: "poll";
53
+ }
54
+ /** Barrier met for the current step. The driver (Phase 3), not this
55
+ * function, decides whether that means "move to stepIndex + 1" or "the
56
+ * run is done" — by comparing stepIndex + 1 to stepCount. advanceRun
57
+ * itself has no opinion on what happens after the barrier clears. */
58
+ | {
59
+ readonly kind: "advance-step";
60
+ }
61
+ /** Ask the registered planner (or, for a step's very first pass, build its
62
+ * one fixed leg) to (re)produce this step's legs. Mechanically the same
63
+ * operation whether it's step 0's first plan or a post-failure re-plan —
64
+ * the handoff's own framing treats "no legs yet" and "re-plan after a
65
+ * failure" as the same call into `plan()`, so one action kind covers
66
+ * both rather than inventing a seventh. */
67
+ | {
68
+ readonly kind: "replan-step";
69
+ readonly reason: string;
70
+ } | {
71
+ readonly kind: "fail-run";
72
+ readonly reason: string;
73
+ } | {
74
+ readonly kind: "wait";
75
+ };
76
+ export declare function advanceRun(run: RunState, legs: readonly LegState[], now: Date, policy: RunPolicy): RunAction[];
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Phase 2's pure decision core for chained runs (handoff
3
+ * `HANDOFF-khronoton-chained-runs.md` §3/§5; full spec in
4
+ * `docs/work/khronoton-chained-runs-phase-2/design.md`'s "Decision algorithm").
5
+ *
6
+ * Given a run's current state and its current step's legs, `advanceRun`
7
+ * decides what happens next — "submit this leg," "keep polling," "the step
8
+ * is done, advance," "ask the planner again," or "give up." No DB, no chain
9
+ * client, no I/O: pure and dependency-free, following `runtime-args.ts` /
10
+ * `capability.ts`'s convention of keeping types local to the module that
11
+ * owns the function's input/output shape rather than in `server/types.ts`.
12
+ */
13
+ /** Shared by decision steps 4 (deadline exceeded), 5 (serial failure), and 6
14
+ * (parallel failure, fully resolved): spend a re-plan attempt if the policy
15
+ * and budget allow it, otherwise fail the run outright. */
16
+ function replanOrFail(run, trigger, policy) {
17
+ if (policy.canReplan && run.attempt < policy.maxReplanAttempts) {
18
+ return [
19
+ {
20
+ kind: "replan-step",
21
+ reason: `step ${run.stepIndex}: ${trigger}; re-planning (attempt ${run.attempt + 1}/${policy.maxReplanAttempts})`,
22
+ },
23
+ ];
24
+ }
25
+ const why = policy.canReplan
26
+ ? `replan attempts exhausted (${run.attempt}/${policy.maxReplanAttempts})`
27
+ : "no re-plan available for a single-mode step";
28
+ return [{ kind: "fail-run", reason: `step ${run.stepIndex}: ${trigger}; ${why}` }];
29
+ }
30
+ export function advanceRun(run, legs, now, policy) {
31
+ // 1. Terminal run — pure no-op, defends against a driver that calls
32
+ // advanceRun on a run it should have already stopped touching.
33
+ if (run.status === "succeeded" || run.status === "failed" || run.status === "abandoned") {
34
+ return [{ kind: "wait" }];
35
+ }
36
+ // 2. No legs yet for the current step — building a step's legs for the
37
+ // first time and re-planning after a failure are the same call, so
38
+ // this reuses replan-step rather than inventing a plan-step kind.
39
+ if (legs.length === 0) {
40
+ return [{ kind: "replan-step", reason: `step ${run.stepIndex} has no legs yet` }];
41
+ }
42
+ // 3. Barrier met — checked BEFORE the deadline test: once every leg is
43
+ // confirmed, a deadline that already passed is moot.
44
+ if (legs.every((l) => l.status === "confirmed")) {
45
+ return [{ kind: "advance-step" }];
46
+ }
47
+ // 4. Deadline exceeded and the barrier is not met — the "poll once more,
48
+ // then decide" moment from handoff §5.7, regardless of step mode or how
49
+ // many legs are still pending/submitted.
50
+ const deadlinePassed = run.deadlineAt != null && now.getTime() > new Date(run.deadlineAt).getTime();
51
+ if (deadlinePassed) {
52
+ return replanOrFail(run, "barrier deadline exceeded", policy);
53
+ }
54
+ // 5. A failed leg exists and the step's legs are NOT independent of each
55
+ // other (serial, cursor-paged) — re-plan-or-fail immediately, even if
56
+ // later legs are still pending and never attempted.
57
+ if (policy.stepMode === "serial" && legs.some((l) => l.status === "failed")) {
58
+ return replanOrFail(run, "a leg failed", policy);
59
+ }
60
+ // 6. A failed leg exists but the step's legs ARE independent (parallel,
61
+ // fed-slices) — only once every leg has reached a terminal status
62
+ // (confirmed or failed) does the failure trigger re-plan-or-fail.
63
+ // Until then, fall through: a sibling failing is not a reason to stop
64
+ // submitting or polling the others.
65
+ if (policy.stepMode === "parallel" && legs.some((l) => l.status === "failed")) {
66
+ const allResolved = legs.every((l) => l.status === "confirmed" || l.status === "failed");
67
+ if (allResolved) {
68
+ return replanOrFail(run, "a leg failed", policy);
69
+ }
70
+ // fall through to step 7
71
+ }
72
+ // 7. Otherwise — normal submit/poll, branching on step mode.
73
+ if (policy.stepMode === "parallel") {
74
+ const pending = legs.filter((l) => l.status === "pending");
75
+ if (pending.length > 0) {
76
+ return pending.map((l) => ({ kind: "submit-leg", legIndex: l.legIndex }));
77
+ }
78
+ return [{ kind: "poll" }];
79
+ }
80
+ // serial
81
+ if (legs.some((l) => l.status === "submitted")) {
82
+ return [{ kind: "poll" }];
83
+ }
84
+ const pendingLegs = legs.filter((l) => l.status === "pending");
85
+ if (pendingLegs.length > 0) {
86
+ const lowest = pendingLegs.reduce((a, b) => (b.legIndex < a.legIndex ? b : a));
87
+ return [{ kind: "submit-leg", legIndex: lowest.legIndex }];
88
+ }
89
+ // Defensive fallback: should not arise given the CHECK-constrained leg
90
+ // statuses and the branches above (any failed leg is caught by step 5;
91
+ // all-confirmed is caught by step 3) — documented rather than silently
92
+ // falling through, and must not throw.
93
+ return [{ kind: "wait" }];
94
+ }