@ancientpantheon/khronoton-core 0.11.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 (71) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +114 -0
  3. package/dist/blockchain/stoachain.d.ts +1 -1
  4. package/dist/blockchain/stoachain.js +16 -1
  5. package/dist/{chunk-LX6T2BDL.js → chunk-7H5TM3CS.js} +1 -1
  6. package/dist/{chunk-GNQ2IVXA.js → chunk-IAK4UEAA.js} +731 -24
  7. package/dist/{context-89YS4xT3.d.ts → context-P-rCtBbJ.d.ts} +2 -2
  8. package/dist/handlers/execute.d.ts +12 -4
  9. package/dist/handlers/execute.js +42 -5
  10. package/dist/handlers/index.d.ts +4 -2
  11. package/dist/handlers/index.js +7 -2
  12. package/dist/handlers/public.d.ts +41 -0
  13. package/dist/handlers/public.js +78 -0
  14. package/dist/handlers/read.d.ts +11 -0
  15. package/dist/handlers/read.js +65 -1
  16. package/dist/handlers/steps.d.ts +3 -0
  17. package/dist/handlers/steps.js +115 -0
  18. package/dist/hooks/index.d.ts +4 -4
  19. package/dist/hooks/index.js +2 -2
  20. package/dist/provider/index.d.ts +4 -4
  21. package/dist/provider/index.js +33 -2
  22. package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
  23. package/dist/server/executor.d.ts +14 -1
  24. package/dist/server/executor.js +144 -26
  25. package/dist/server/index.d.ts +11 -2
  26. package/dist/server/index.js +29 -1
  27. package/dist/server/loop.d.ts +17 -13
  28. package/dist/server/loop.js +19 -12
  29. package/dist/server/planners/evict.d.ts +20 -0
  30. package/dist/server/planners/evict.js +143 -0
  31. package/dist/server/planners/inject.d.ts +22 -0
  32. package/dist/server/planners/inject.js +120 -0
  33. package/dist/server/planners/registry.d.ts +80 -0
  34. package/dist/server/planners/registry.js +50 -0
  35. package/dist/server/planners/stoa-unwrap.d.ts +23 -0
  36. package/dist/server/planners/stoa-unwrap.js +204 -0
  37. package/dist/server/planners/stoa-wrap.d.ts +22 -0
  38. package/dist/server/planners/stoa-wrap.js +201 -0
  39. package/dist/server/planners/unstall.d.ts +25 -0
  40. package/dist/server/planners/unstall.js +135 -0
  41. package/dist/server/pure/run-advance.d.ts +76 -0
  42. package/dist/server/pure/run-advance.js +94 -0
  43. package/dist/server/pure/split-plan.d.ts +144 -0
  44. package/dist/server/pure/split-plan.js +362 -0
  45. package/dist/server/resolvers.js +48 -6
  46. package/dist/server/runs-driver.d.ts +92 -0
  47. package/dist/server/runs-driver.js +511 -0
  48. package/dist/server/schema.d.ts +12 -2
  49. package/dist/server/schema.js +105 -1
  50. package/dist/server/seams.d.ts +28 -0
  51. package/dist/server/seams.js +4 -0
  52. package/dist/server/store/errors.d.ts +38 -0
  53. package/dist/server/store/errors.js +61 -0
  54. package/dist/server/store/fires.js +27 -1
  55. package/dist/server/store/index.d.ts +8 -2
  56. package/dist/server/store/index.js +8 -2
  57. package/dist/server/store/mappers.d.ts +11 -0
  58. package/dist/server/store/mappers.js +20 -0
  59. package/dist/server/store/public.d.ts +104 -0
  60. package/dist/server/store/public.js +197 -0
  61. package/dist/server/store/runs.d.ts +233 -0
  62. package/dist/server/store/runs.js +341 -0
  63. package/dist/server/store/steps.d.ts +42 -0
  64. package/dist/server/store/steps.js +51 -0
  65. package/dist/server/tick.d.ts +7 -0
  66. package/dist/server/tick.js +50 -1
  67. package/dist/server/types.d.ts +55 -3
  68. package/dist/{types-DnFB1Yz-.d.ts → types-uYSglFrJ.d.ts} +13 -0
  69. package/dist/ui/index.d.ts +1 -1
  70. package/dist/ui/index.js +2 -2
  71. package/package.json +1 -1
@@ -0,0 +1,143 @@
1
+ /**
2
+ * `ouronet.aqp-evict` — the "Evict Rewards" step planner, ported from
3
+ * OuronetUI's `EvictSection.tsx`/`evictSpecs.tsx`/`fvtChain.ts` (a different
4
+ * workspace entirely: `OuroborosNetwork/daimons/OuronetUI`). See design.md's
5
+ * §D for the full port rationale.
6
+ *
7
+ * Shape: one Pact *read* (`URHC_BuildEvictPlans`) computes the plan ON-CHAIN,
8
+ * so this planner never decides leg count itself — it tries one transaction
9
+ * (`CC_FullEvictRewards`) first and only fans out to one leg per plan entry
10
+ * (`CC_EvictSingleReward`) when that one transaction genuinely cannot fit the
11
+ * block's gas ceiling (never on any OTHER simulate failure, which propagates
12
+ * as a real error instead — see step 9 below).
13
+ */
14
+ import { executeCodexTransaction } from "../executor.js";
15
+ import { registerStepPlanner, } from "./registry.js";
16
+ /** Mirrors `store/mappers.ts`'s own one-line helper — duplicated locally per the plan rather than importing a private function from another module. */
17
+ function parseJson(json, fallback) {
18
+ if (json == null)
19
+ return fallback;
20
+ return JSON.parse(json);
21
+ }
22
+ /**
23
+ * Validate one chain-read plan entry's shape before it is trusted enough to
24
+ * become part of a signed transaction's `payload` (env-data). This is a
25
+ * live chain-read response, not operator-configured `planner_params_json` —
26
+ * nothing in this codebase (or, per the ported source's own caveat, the
27
+ * `AQP-EVCT` contract) guarantees these fields are well-formed, so a bare
28
+ * type assertion over `unknown` is not enough here.
29
+ */
30
+ function isWellFormedEvictLeg(value) {
31
+ if (typeof value !== "object" || value === null)
32
+ return false;
33
+ const leg = value;
34
+ return (typeof leg.beneficiary === "string" &&
35
+ typeof leg.scoreEntityType === "number" &&
36
+ Number.isInteger(leg.scoreEntityType) &&
37
+ typeof leg.scoreEntityId === "string" &&
38
+ typeof leg.rewardDptfId === "string");
39
+ }
40
+ /**
41
+ * Drives one `mode:'planner'` step registered under `ouronet.aqp-evict`:
42
+ *
43
+ * 1. Parse `fvtId`/`patronAccount` from `step.planner_params_json`.
44
+ * 2. Derive `executor = k:<the step's own first signer's publicKey>`.
45
+ * 3-4. Read the plan (`URHC_BuildEvictPlans`) via a simulate; a failed READ
46
+ * is never "needs splitting" — there is no plan to split.
47
+ * 5-6. Zero plan entries → `[]` (handleReplanStep treats this as a cleared
48
+ * barrier — see design.md §C).
49
+ * 7-8. Probe `CC_FullEvictRewards` as one candidate leg; a successful
50
+ * simulate → exactly that one leg.
51
+ * 9. A failed probe is "needs splitting" ONLY when `runSimulate`'s own
52
+ * `gasUsed > ceiling` refuse-unmineable branch produced it (signaled by a
53
+ * numeric `gasUsed` on the `ok:false` result) — any OTHER failure
54
+ * rethrows as a genuine error, never silently treated as "needs
55
+ * splitting".
56
+ * 10. Fan out: one `CC_EvictSingleReward` leg per plan entry.
57
+ */
58
+ export const evictPlanner = async (step, ctx) => {
59
+ const params = parseJson(step.planner_params_json, {});
60
+ if (typeof params.fvtId !== "string" || typeof params.patronAccount !== "string") {
61
+ throw new Error("ouronet.aqp-evict: step.planner_params_json must have fvtId and patronAccount strings");
62
+ }
63
+ const { fvtId, patronAccount } = params;
64
+ const signers = parseJson(step.signers_json, []);
65
+ if (signers.length === 0) {
66
+ throw new Error("ouronet.aqp-evict: step.signers_json must have at least one signer (used as the executor)");
67
+ }
68
+ const executor = `k:${signers[0].publicKey}`;
69
+ const config = parseJson(step.config_json, {});
70
+ const gasPayer = parseJson(step.gas_payer_json, { type: "gas-station" });
71
+ const executorCtx = { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config };
72
+ // `ouronet-ns.AQP-EVCT` — the module's REAL, deployed, namespaced path
73
+ // (confirmed against the ported source's own `fvtChain.ts` NS/EVCT
74
+ // constants and its `(namespace "ouronet-ns")` on-chain declaration; a
75
+ // bare `AQP-EVCT.*` reference is unresolvable by Pact's namespace
76
+ // mechanism). Built from `ctx.runtime.namespace`, never hardcoded, so a
77
+ // consumer on a different namespace isn't silently wrong.
78
+ const evct = `${ctx.runtime.namespace}.AQP-EVCT`;
79
+ // Every value below flows through `payload` (env-data, `addData` per
80
+ // `executor.ts`'s `buildTransaction`) and is read back with
81
+ // `read-string`/`read-integer` in `pactCode` — NEVER string-concatenated
82
+ // into the Pact source itself, mirroring `pure/runtime-args.ts`'s own
83
+ // "no code-injection surface" guarantee. This matters most for
84
+ // `beneficiary`/`scoreEntityId`/`rewardDptfId`/`scoreEntityType` below,
85
+ // which come from a LIVE CHAIN READ (`URHC_BuildEvictPlans`'s response),
86
+ // not from operator-configured `planner_params_json` — nothing in this
87
+ // codebase or (per the ported source's own caveat) the `AQP-EVCT`
88
+ // contract guarantees those fields can't contain `"`/`(`/`)`.
89
+ const probeDefinition = {
90
+ pactCode: `(${evct}.URHC_BuildEvictPlans (read-string "fvt-id"))`,
91
+ config,
92
+ payload: { "fvt-id": fvtId },
93
+ gasPayer,
94
+ signers,
95
+ };
96
+ const result = await executeCodexTransaction(probeDefinition, "simulate", executorCtx);
97
+ if (!result.ok) {
98
+ throw new Error(result.error ?? "evict plan read failed");
99
+ }
100
+ const data = result.rawResult?.data;
101
+ if (!Array.isArray(data)) {
102
+ throw new Error("ouronet.aqp-evict: URHC_BuildEvictPlans returned a non-array result");
103
+ }
104
+ if (!data.every(isWellFormedEvictLeg)) {
105
+ throw new Error("ouronet.aqp-evict: URHC_BuildEvictPlans returned a malformed plan entry (expected string beneficiary/scoreEntityId/rewardDptfId and an integer scoreEntityType)");
106
+ }
107
+ const legs = data;
108
+ if (legs.length === 0) {
109
+ return [];
110
+ }
111
+ const fullLeg = {
112
+ pactCode: `(${evct}.CC_FullEvictRewards (read-string "patron") (read-string "executor") (read-string "fvt-id"))`,
113
+ config,
114
+ payload: { patron: patronAccount, executor, "fvt-id": fvtId },
115
+ gasPayer,
116
+ signers,
117
+ };
118
+ const fullResult = await executeCodexTransaction(fullLeg, "simulate", executorCtx);
119
+ if (fullResult.ok) {
120
+ return [fullLeg];
121
+ }
122
+ if (typeof fullResult.gasUsed !== "number") {
123
+ // A genuine chain-level/Pact-execution failure — never interpreted as
124
+ // "needs splitting" (see the module doc's step 9 above).
125
+ throw new Error(fullResult.error ?? "CC_FullEvictRewards simulation failed");
126
+ }
127
+ return legs.map((leg) => ({
128
+ pactCode: `(${evct}.CC_EvictSingleReward (read-string "patron") (read-string "executor") (read-string "fvt-id") (read-string "beneficiary") (read-integer "score-entity-type") (read-string "score-entity-id") (read-string "reward-dptf-id"))`,
129
+ config,
130
+ payload: {
131
+ patron: patronAccount,
132
+ executor,
133
+ "fvt-id": fvtId,
134
+ beneficiary: leg.beneficiary,
135
+ "score-entity-type": leg.scoreEntityType,
136
+ "score-entity-id": leg.scoreEntityId,
137
+ "reward-dptf-id": leg.rewardDptfId,
138
+ },
139
+ gasPayer,
140
+ signers,
141
+ }));
142
+ };
143
+ registerStepPlanner("ouronet.aqp-evict", evictPlanner);
@@ -0,0 +1,22 @@
1
+ import { type StepPlanner } from "./registry.js";
2
+ /**
3
+ * Drives one `mode:'planner'` step registered under `ouronet.aqp-inject`:
4
+ *
5
+ * 1. Parse `fvtId`/`patronAccount`/`rewardDptfId`/`amount` 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.
9
+ * 2. Probe `CC_InjectFinalize` as one candidate leg; a successful simulate
10
+ * → exactly that one leg.
11
+ * 3. Else probe `CC_Inject` (same five env-data fields); a successful
12
+ * simulate → exactly that one leg.
13
+ * 4. Else — never fans out, never silently succeeds — rethrow regardless
14
+ * of whether the second failure's `gasUsed` is a number (unlike
15
+ * `evictPlanner`, which fans out on a numeric `gasUsed`; `injectPlanner`
16
+ * has no fan-out leg shape to produce at all — a too-expensive
17
+ * `CC_Inject` here means staleness reappeared after the preceding
18
+ * `ouronet.aqp-unstall` step already ran, a narrow race this planner
19
+ * reports as a genuine failure rather than inventing recovery logic the
20
+ * real ported source itself never needed).
21
+ */
22
+ export declare const injectPlanner: StepPlanner;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * `ouronet.aqp-inject` — the "Inject Reward" step planner, ported from
3
+ * OuronetUI's `fvtOwnerSpecs.tsx` (`INJECT_FINALIZE`) and `aqpConsumerSpecs.tsx`
4
+ * (`INJECT_FVT`, the real `CC_Inject`/inline-repair entrypoint — it does NOT
5
+ * live in `fvtOwnerSpecs.tsx` despite the similar naming) — a different
6
+ * workspace entirely: `OuroborosNetwork/daimons/OuronetUI`. See design.md's
7
+ * §D for the full port rationale.
8
+ *
9
+ * Shape: unlike `evictPlanner`, this planner has no on-chain plan read and no
10
+ * fan-out leg shape at all — it tries the cheap `CC_InjectFinalize` path
11
+ * first (correct once a preceding `ouronet.aqp-unstall` step has already
12
+ * repaired every stale member in slices), falls back to the heavier
13
+ * inline-repair `CC_Inject` when that fails, and reports a genuine failure
14
+ * when BOTH fail rather than inventing any further recovery.
15
+ */
16
+ import { executeCodexTransaction } from "../executor.js";
17
+ import { registerStepPlanner, } from "./registry.js";
18
+ /** Mirrors `store/mappers.ts`'s own one-line helper — duplicated locally per the plan rather than importing a private function from another module. */
19
+ function parseJson(json, fallback) {
20
+ if (json == null)
21
+ return fallback;
22
+ return JSON.parse(json);
23
+ }
24
+ /**
25
+ * Drives one `mode:'planner'` step registered under `ouronet.aqp-inject`:
26
+ *
27
+ * 1. Parse `fvtId`/`patronAccount`/`rewardDptfId`/`amount` from
28
+ * `step.planner_params_json`. Derive `executor = k:<the step's own first
29
+ * signer's publicKey>` — identical validation shape to `evictPlanner`'s
30
+ * own.
31
+ * 2. Probe `CC_InjectFinalize` as one candidate leg; a successful simulate
32
+ * → exactly that one leg.
33
+ * 3. Else probe `CC_Inject` (same five env-data fields); a successful
34
+ * simulate → exactly that one leg.
35
+ * 4. Else — never fans out, never silently succeeds — rethrow regardless
36
+ * of whether the second failure's `gasUsed` is a number (unlike
37
+ * `evictPlanner`, which fans out on a numeric `gasUsed`; `injectPlanner`
38
+ * has no fan-out leg shape to produce at all — a too-expensive
39
+ * `CC_Inject` here means staleness reappeared after the preceding
40
+ * `ouronet.aqp-unstall` step already ran, a narrow race this planner
41
+ * reports as a genuine failure rather than inventing recovery logic the
42
+ * real ported source itself never needed).
43
+ */
44
+ export const injectPlanner = async (step, ctx) => {
45
+ const params = parseJson(step.planner_params_json, {});
46
+ if (typeof params.fvtId !== "string" ||
47
+ typeof params.patronAccount !== "string" ||
48
+ typeof params.rewardDptfId !== "string" ||
49
+ typeof params.amount !== "string") {
50
+ throw new Error("ouronet.aqp-inject: step.planner_params_json must have fvtId, patronAccount, rewardDptfId, and amount strings");
51
+ }
52
+ const { fvtId, patronAccount, rewardDptfId, amount } = params;
53
+ // Non-negative decimal format only — this rejects a malformed/negative
54
+ // amount BEFORE it reaches a signed transaction, as cheap defense-in-depth
55
+ // on top of the contract's own business-rule enforcement (which this
56
+ // planner still trusts for anything beyond shape, same as `evictPlanner`'s
57
+ // own "trust the contract" posture). Pact's `read-decimal` itself requires
58
+ // a decimal literal (at least one digit on each side of a mandatory `.`),
59
+ // so a bare integer string like "5" is intentionally also rejected here.
60
+ if (!/^\d+\.\d+$/.test(amount)) {
61
+ throw new Error(`ouronet.aqp-inject: amount must be a non-negative decimal string (e.g. "5.0"), got ${JSON.stringify(amount)}`);
62
+ }
63
+ const signers = parseJson(step.signers_json, []);
64
+ if (signers.length === 0) {
65
+ throw new Error("ouronet.aqp-inject: step.signers_json must have at least one signer (used as the executor)");
66
+ }
67
+ const executor = `k:${signers[0].publicKey}`;
68
+ const config = parseJson(step.config_json, {});
69
+ const gasPayer = parseJson(step.gas_payer_json, { type: "gas-station" });
70
+ const executorCtx = { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config };
71
+ // `ouronet-ns.AQP-FVT` — the module's REAL, deployed, namespaced path
72
+ // (confirmed against the ported source's own `fvtOwnerSpecs.tsx`/
73
+ // `aqpConsumerSpecs.tsx` entrypoint strings and `05_FVT.pact`'s own
74
+ // `(namespace "ouronet-ns")` declaration; a bare `AQP-FVT.*` reference is
75
+ // unresolvable by Pact's namespace mechanism). Built from
76
+ // `ctx.runtime.namespace`, never hardcoded, so a consumer on a different
77
+ // namespace isn't silently wrong. NOTE: this is a DIFFERENT module than
78
+ // `evictPlanner`'s own `AQP-EVCT`.
79
+ const fvt = `${ctx.runtime.namespace}.AQP-FVT`;
80
+ // Every value below flows through `payload` (env-data, `addData` per
81
+ // `executor.ts`'s `buildTransaction`) and is read back with
82
+ // `read-string`/`read-decimal` in `pactCode` — NEVER string-concatenated
83
+ // into the Pact source itself, mirroring `evictPlanner`'s own
84
+ // "no code-injection surface" guarantee (see that module's doc comment for
85
+ // the vulnerability this closes).
86
+ const payload = {
87
+ patron: patronAccount,
88
+ executor,
89
+ "fvt-id": fvtId,
90
+ "reward-dptf-id": rewardDptfId,
91
+ amount,
92
+ };
93
+ const finalizeLeg = {
94
+ pactCode: `(${fvt}.CC_InjectFinalize (read-string "patron") (read-string "executor") (read-string "fvt-id") (read-string "reward-dptf-id") (read-decimal "amount"))`,
95
+ config,
96
+ payload,
97
+ gasPayer,
98
+ signers,
99
+ };
100
+ const finalizeResult = await executeCodexTransaction(finalizeLeg, "simulate", executorCtx);
101
+ if (finalizeResult.ok) {
102
+ return [finalizeLeg];
103
+ }
104
+ const injectLeg = {
105
+ pactCode: `(${fvt}.CC_Inject (read-string "patron") (read-string "executor") (read-string "fvt-id") (read-string "reward-dptf-id") (read-decimal "amount"))`,
106
+ config,
107
+ payload,
108
+ gasPayer,
109
+ signers,
110
+ };
111
+ const injectResult = await executeCodexTransaction(injectLeg, "simulate", executorCtx);
112
+ if (injectResult.ok) {
113
+ return [injectLeg];
114
+ }
115
+ // Never fans out, never silently succeeds — rethrow regardless of
116
+ // whether `injectResult.gasUsed` happens to be a number (see the module
117
+ // doc's step 4 above).
118
+ throw new Error(injectResult.error ?? "CC_Inject simulation failed");
119
+ };
120
+ registerStepPlanner("ouronet.aqp-inject", injectPlanner);
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The `StepPlanner` registry — the `mode:'planner'` analog of `resolvers.ts`'s
3
+ * `SERVER_RESOLVERS` registry.
4
+ *
5
+ * A step planner is a named hook consulted when a chained run's current step
6
+ * is `mode:'planner'`: given the step row + a `PlannerCtx`, it decides at RUN
7
+ * TIME how many legs to build this pass (zero, one, or many) rather than the
8
+ * fixed single leg a `mode:'single'` step's own stored definition already
9
+ * fully specifies. `runs-driver.ts`'s `handleReplanStep` is the sole consumer,
10
+ * looking a planner up by `step.planner_name` and calling it to produce the
11
+ * `PlannedLeg[]` it then inserts.
12
+ *
13
+ * This module carries NO domain-planner coupling: the concrete planners
14
+ * (e.g. `ouronet.aqp-evict`) live in sibling modules and self-register here
15
+ * at module-eval time, exactly as a server resolver self-registers into
16
+ * `resolvers.ts`.
17
+ */
18
+ import type { CodexGasPayer, CodexSigner, CodexTxConfig } from "../types.js";
19
+ import type { ChainRuntime, Config, KeyResolver } from "../seams.js";
20
+ import type { CodexCronotonStepRow } from "../store/steps.js";
21
+ /**
22
+ * The seams a step planner runs against — the same three injectable
23
+ * dependencies `executor.ts`'s `ExecutorCtx` carries, declared as this
24
+ * module's OWN interface (matching `runs-driver.ts`'s `RunsDriverCtx`
25
+ * precedent) rather than importing another module's ctx type name.
26
+ */
27
+ export interface PlannerCtx {
28
+ runtime: ChainRuntime;
29
+ resolver: KeyResolver;
30
+ config?: Partial<Config>;
31
+ }
32
+ /**
33
+ * One leg a planner produces for the step's current pass. Deliberately the
34
+ * same field set as `CodexTxDefinition` minus `scheduleKind`/`serverResolver`
35
+ * — a leg never needs either — matching `store/mappers.ts`'s own
36
+ * `stepRowToDefinition` output shape exactly, so `JSON.stringify`-ing a
37
+ * `PlannedLeg` produces a string `handleSubmitLeg`'s existing
38
+ * `parseLegDefinition` already accepts without any change there.
39
+ */
40
+ export interface PlannedLeg {
41
+ pactCode: string;
42
+ config: CodexTxConfig;
43
+ payload: Record<string, unknown>;
44
+ gasPayer: CodexGasPayer;
45
+ signers: CodexSigner[];
46
+ }
47
+ /**
48
+ * A step planner: given the step row + the injected seams, decides the legs
49
+ * to build for the step's current pass. An empty array means "nothing to do
50
+ * this pass" — `handleReplanStep` treats that like a cleared barrier.
51
+ */
52
+ export type StepPlanner = (step: CodexCronotonStepRow, ctx: PlannerCtx) => Promise<PlannedLeg[]>;
53
+ /**
54
+ * Register (or replace) a named step planner. A module that owns a planner
55
+ * calls this at module-eval time so the registry is populated by the time
56
+ * `handleReplanStep` consults it.
57
+ */
58
+ export declare function registerStepPlanner(name: string, planner: StepPlanner): void;
59
+ /** Read a registered step planner by name, or `undefined`. */
60
+ export declare function getStepPlanner(name: string): StepPlanner | undefined;
61
+ /**
62
+ * Resolve a `mode:'planner'` step's registered planner AND build the
63
+ * `PlannerCtx` it needs, in one call — the single shared implementation of
64
+ * "which planner handles this step, with what ctx" that `runs-driver.ts`'s
65
+ * `handleReplanStep` and `handlers/steps.ts`'s standalone-fire route both
66
+ * consume, so the two call sites can never silently drift from each other
67
+ * (a prior version of this codebase had each hand-copy this exact lookup;
68
+ * Phase 5's review found that drift risk and this function closes it).
69
+ * Returns `undefined` for an unregistered `planner_name` — callers decide
70
+ * how to report that (a thrown `PlannerNotRegisteredError` for the real
71
+ * driver, a 404 for the standalone-fire route).
72
+ */
73
+ export declare function resolvePlannerFor(step: CodexCronotonStepRow, seams: {
74
+ runtime: ChainRuntime;
75
+ resolver: KeyResolver;
76
+ config?: Partial<Config>;
77
+ }): {
78
+ planner: StepPlanner;
79
+ plannerCtx: PlannerCtx;
80
+ } | undefined;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The `StepPlanner` registry — the `mode:'planner'` analog of `resolvers.ts`'s
3
+ * `SERVER_RESOLVERS` registry.
4
+ *
5
+ * A step planner is a named hook consulted when a chained run's current step
6
+ * is `mode:'planner'`: given the step row + a `PlannerCtx`, it decides at RUN
7
+ * TIME how many legs to build this pass (zero, one, or many) rather than the
8
+ * fixed single leg a `mode:'single'` step's own stored definition already
9
+ * fully specifies. `runs-driver.ts`'s `handleReplanStep` is the sole consumer,
10
+ * looking a planner up by `step.planner_name` and calling it to produce the
11
+ * `PlannedLeg[]` it then inserts.
12
+ *
13
+ * This module carries NO domain-planner coupling: the concrete planners
14
+ * (e.g. `ouronet.aqp-evict`) live in sibling modules and self-register here
15
+ * at module-eval time, exactly as a server resolver self-registers into
16
+ * `resolvers.ts`.
17
+ */
18
+ /** Registry of step planners keyed by `planner_name`. */
19
+ const STEP_PLANNERS = {};
20
+ /**
21
+ * Register (or replace) a named step planner. A module that owns a planner
22
+ * calls this at module-eval time so the registry is populated by the time
23
+ * `handleReplanStep` consults it.
24
+ */
25
+ export function registerStepPlanner(name, planner) {
26
+ STEP_PLANNERS[name] = planner;
27
+ }
28
+ /** Read a registered step planner by name, or `undefined`. */
29
+ export function getStepPlanner(name) {
30
+ return STEP_PLANNERS[name];
31
+ }
32
+ /**
33
+ * Resolve a `mode:'planner'` step's registered planner AND build the
34
+ * `PlannerCtx` it needs, in one call — the single shared implementation of
35
+ * "which planner handles this step, with what ctx" that `runs-driver.ts`'s
36
+ * `handleReplanStep` and `handlers/steps.ts`'s standalone-fire route both
37
+ * consume, so the two call sites can never silently drift from each other
38
+ * (a prior version of this codebase had each hand-copy this exact lookup;
39
+ * Phase 5's review found that drift risk and this function closes it).
40
+ * Returns `undefined` for an unregistered `planner_name` — callers decide
41
+ * how to report that (a thrown `PlannerNotRegisteredError` for the real
42
+ * driver, a 404 for the standalone-fire route).
43
+ */
44
+ export function resolvePlannerFor(step, seams) {
45
+ const planner = getStepPlanner(step.planner_name ?? "");
46
+ if (!planner)
47
+ return undefined;
48
+ const plannerCtx = { runtime: seams.runtime, resolver: seams.resolver, config: seams.config };
49
+ return { planner, plannerCtx };
50
+ }
@@ -0,0 +1,23 @@
1
+ import { type StepPlanner } from "./registry.js";
2
+ /**
3
+ * Drives one `mode:'planner'` step registered under `ouronet.stoa-unwrap`:
4
+ *
5
+ * 1. Parse + validate `patronAccount`/`amount` from `step.planner_params_json`.
6
+ * 2. Derive `executor = k:<the step's own first signer's publicKey>`.
7
+ * 3. Resolve the target StoaChain account via `DALOS.UR_AccountKadena` — a
8
+ * chain-read-sourced value, so it is shape-guarded (unlike `patronAccount`,
9
+ * which is operator-configured) before it is trusted anywhere downstream.
10
+ * 4. Probe whether the target already exists via `coin.get-balance` wrapped
11
+ * in `try false`.
12
+ * 5. If it doesn't exist, require a `k:`-prefixed target (account creation
13
+ * assumes a single-key account, matching OuronetUI's own unconditional
14
+ * key-stripping) and strip its prefix for the `read-keyset` payload.
15
+ * 6. Build the one leg: a single-form `pactCode` when the target already
16
+ * exists, or a two-form `coin.C_CreateAccount` + `LQD|C_UnwrapStoa`
17
+ * composite (in that order) when it doesn't — with a `coin.TRANSFER`
18
+ * capability from `STOA_AUTONOMIC_LIQUIDPOT` to the target attached to
19
+ * signer 0 (the REVERSE account order from `stoa-wrap.ts`'s own
20
+ * capability — a real asymmetry per design.md §B, not a copy-paste of
21
+ * wrap's capability with names swapped).
22
+ */
23
+ export declare const stoaUnwrapPlanner: StepPlanner;
@@ -0,0 +1,204 @@
1
+ /**
2
+ * `ouronet.stoa-unwrap` — the "Unwrap STOA" step planner, ported from
3
+ * OuronetUI's `ouroWrapFunctions.ts`/`ouroPriceFunctions.ts`/
4
+ * `tokenOpSpecs.tsx` (a different workspace entirely:
5
+ * `OuroborosNetwork/daimons/OuronetUI`). See design.md's §B for the full
6
+ * port rationale, and §C for the capability-line interpolation exception
7
+ * both this module and its sibling `stoa-wrap.ts` rely on.
8
+ *
9
+ * Shape: always exactly one leg. Unlike `stoa-wrap.ts` (whose `amount` is a
10
+ * LIVE balance read), this planner's `amount` is an explicit, validated
11
+ * `planner_params_json` param — no confirmed "unwrap the full balance"
12
+ * semantic exists yet (design.md §B). Two `dirtyRead`s resolve whether the
13
+ * target StoaChain account needs creating before the real
14
+ * `LQD|C_UnwrapStoa` call is built: `DALOS.UR_AccountKadena` resolves the
15
+ * target address, then `coin.get-balance` (wrapped in `try false`, bare
16
+ * `coin`, no namespace prefix — `coin` is Kadena's own root/system module,
17
+ * confirmed against OuronetUI's own bare `coin.get-balance`/`coin.TRANSFER`
18
+ * calls, unlike `ouronet-ns`-namespaced modules such as `TS01-C2`/`DALOS`)
19
+ * probes whether it already exists. When it doesn't, `coin.C_CreateAccount`
20
+ * is composed as a second top-level form ahead of the unwrap call in one
21
+ * `pactCode` string (two env-data-only forms joined by a newline — a real,
22
+ * independently-rendered-forms mechanism per OuronetUI's own registry, not
23
+ * string-splicing of untrusted text).
24
+ */
25
+ import { executeCodexTransaction } from "../executor.js";
26
+ import { stripPrefix } from "../executor-signers.js";
27
+ import { registerStepPlanner, } from "./registry.js";
28
+ /** Mirrors `store/mappers.ts`'s own one-line helper — duplicated locally per the plan rather than importing a private function from another module. */
29
+ function parseJson(json, fallback) {
30
+ if (json == null)
31
+ return fallback;
32
+ return JSON.parse(json);
33
+ }
34
+ /**
35
+ * The protocol's STOA-autonomic liquidity pot — a fixed, public, non-secret
36
+ * system account (confirmed against `ouronet-core/src/constants/
37
+ * ouronet.ts:44`). A module-local constant, duplicated from `stoa-wrap.ts`
38
+ * per that module's own per-module-duplication convention, to keep the two
39
+ * planners independent.
40
+ */
41
+ const STOA_AUTONOMIC_LIQUIDPOT = "c:ZNfuj3iZI83n7MUSKGuoXoSxFg1cyMxCzB3szUHVvrI";
42
+ /** Shape guard for a `k:`/`c:` Kadena account string — see the module doc comment's "chain reads are not trusted" note for why this matters for `targetAccount` specifically. */
43
+ const ACCOUNT_SHAPE = /^[kc]:[A-Za-z0-9_-]+$/;
44
+ /**
45
+ * Drives one `mode:'planner'` step registered under `ouronet.stoa-unwrap`:
46
+ *
47
+ * 1. Parse + validate `patronAccount`/`amount` from `step.planner_params_json`.
48
+ * 2. Derive `executor = k:<the step's own first signer's publicKey>`.
49
+ * 3. Resolve the target StoaChain account via `DALOS.UR_AccountKadena` — a
50
+ * chain-read-sourced value, so it is shape-guarded (unlike `patronAccount`,
51
+ * which is operator-configured) before it is trusted anywhere downstream.
52
+ * 4. Probe whether the target already exists via `coin.get-balance` wrapped
53
+ * in `try false`.
54
+ * 5. If it doesn't exist, require a `k:`-prefixed target (account creation
55
+ * assumes a single-key account, matching OuronetUI's own unconditional
56
+ * key-stripping) and strip its prefix for the `read-keyset` payload.
57
+ * 6. Build the one leg: a single-form `pactCode` when the target already
58
+ * exists, or a two-form `coin.C_CreateAccount` + `LQD|C_UnwrapStoa`
59
+ * composite (in that order) when it doesn't — with a `coin.TRANSFER`
60
+ * capability from `STOA_AUTONOMIC_LIQUIDPOT` to the target attached to
61
+ * signer 0 (the REVERSE account order from `stoa-wrap.ts`'s own
62
+ * capability — a real asymmetry per design.md §B, not a copy-paste of
63
+ * wrap's capability with names swapped).
64
+ */
65
+ export const stoaUnwrapPlanner = async (step, ctx) => {
66
+ const params = parseJson(step.planner_params_json, {});
67
+ if (typeof params.patronAccount !== "string" || typeof params.amount !== "string") {
68
+ throw new Error("ouronet.stoa-unwrap: step.planner_params_json must have patronAccount and amount strings");
69
+ }
70
+ const { patronAccount, amount } = params;
71
+ if (!ACCOUNT_SHAPE.test(patronAccount)) {
72
+ throw new Error(`ouronet.stoa-unwrap: patronAccount is not a well-formed k:/c: account: ${JSON.stringify(patronAccount)}`);
73
+ }
74
+ // Non-negative decimal format only — this rejects a malformed/negative
75
+ // amount BEFORE it reaches a signed transaction (or a capability line),
76
+ // the identical shape `inject.ts`'s own amount guard already establishes
77
+ // elsewhere in this codebase.
78
+ if (!/^\d+\.\d+$/.test(amount)) {
79
+ throw new Error(`ouronet.stoa-unwrap: amount must be a non-negative decimal string (e.g. "5.0"), got ${JSON.stringify(amount)}`);
80
+ }
81
+ const signers = parseJson(step.signers_json, []);
82
+ if (signers.length === 0) {
83
+ throw new Error("ouronet.stoa-unwrap: step.signers_json must have at least one signer (used as the executor)");
84
+ }
85
+ const executor = `k:${signers[0].publicKey}`;
86
+ const config = parseJson(step.config_json, {});
87
+ const gasPayer = parseJson(step.gas_payer_json, { type: "gas-station" });
88
+ const executorCtx = { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config };
89
+ // `ouronet-ns.DALOS` — the module's REAL, deployed, namespaced path, built
90
+ // from `ctx.runtime.namespace`, never hardcoded (same discipline as every
91
+ // other planner's own namespaced module reference).
92
+ const dalos = `${ctx.runtime.namespace}.DALOS`;
93
+ const resolveDefinition = {
94
+ pactCode: `(${dalos}.UR_AccountKadena (read-string "patron"))`,
95
+ config,
96
+ payload: { patron: patronAccount },
97
+ gasPayer,
98
+ signers,
99
+ };
100
+ const resolveResult = await executeCodexTransaction(resolveDefinition, "simulate", executorCtx);
101
+ if (!resolveResult.ok) {
102
+ throw new Error(resolveResult.error ?? "UR_AccountKadena read failed");
103
+ }
104
+ const targetData = resolveResult.rawResult?.data;
105
+ // This value IS chain-read-sourced, unlike `patronAccount` above — the
106
+ // same "chain reads are not trusted" posture as `evict.ts`'s own
107
+ // `isWellFormedEvictLeg` guard — so it is shape-guarded before it reaches
108
+ // either `payload` or a capability line.
109
+ if (typeof targetData !== "string" || !ACCOUNT_SHAPE.test(targetData)) {
110
+ throw new Error(`ouronet.stoa-unwrap: UR_AccountKadena returned a malformed target account: ${JSON.stringify(targetData)}`);
111
+ }
112
+ const targetAccount = targetData;
113
+ const existenceDefinition = {
114
+ pactCode: '(try false (coin.get-balance (read-string "target")))',
115
+ config,
116
+ payload: { target: targetAccount },
117
+ gasPayer,
118
+ signers,
119
+ };
120
+ const existenceResult = await executeCodexTransaction(existenceDefinition, "simulate", executorCtx);
121
+ if (!existenceResult.ok) {
122
+ throw new Error(existenceResult.error ?? "coin.get-balance existence probe failed");
123
+ }
124
+ const existenceData = existenceResult.rawResult?.data;
125
+ let needsCreate;
126
+ if (existenceData === false) {
127
+ needsCreate = true;
128
+ }
129
+ else if (typeof existenceData === "number") {
130
+ needsCreate = false;
131
+ }
132
+ else {
133
+ throw new Error(`ouronet.stoa-unwrap: coin.get-balance existence probe returned an unexpected shape: ${JSON.stringify(existenceData)}`);
134
+ }
135
+ let strippedPubkey;
136
+ if (needsCreate) {
137
+ // Account CREATION assumes a single-key `k:` account, matching
138
+ // OuronetUI's own unconditional `target.slice(2)` key-stripping — a
139
+ // `c:`-prefixed target here is a shape the real UI never handles
140
+ // either, so it is a genuine error rather than a guessed guard.
141
+ if (!/^k:[A-Za-z0-9_-]+$/.test(targetAccount)) {
142
+ throw new Error(`ouronet.stoa-unwrap: cannot auto-create a non-k: target account: ${targetAccount}`);
143
+ }
144
+ strippedPubkey = stripPrefix(targetAccount);
145
+ }
146
+ // Every value below flows through `payload` (env-data) and is read back
147
+ // with `read-string`/`read-decimal`/`read-keyset` in `pactCode` — NEVER
148
+ // string-concatenated into the Pact source itself, mirroring
149
+ // `evict.ts`'s/`inject.ts`'s own "no code-injection surface" guarantee.
150
+ const unwrapForm = `(${ctx.runtime.namespace}.TS01-C2.LQD|C_UnwrapStoa (read-string "patron") (read-string "executor") (read-decimal "amount"))`;
151
+ const pactCode = needsCreate
152
+ ? `(coin.C_CreateAccount (read-string "target") (read-keyset "ks"))\n${unwrapForm}`
153
+ : unwrapForm;
154
+ const payload = needsCreate
155
+ ? {
156
+ patron: patronAccount,
157
+ executor,
158
+ amount,
159
+ target: targetAccount,
160
+ ks: { keys: [strippedPubkey], pred: "keys-all" },
161
+ }
162
+ : { patron: patronAccount, executor, amount };
163
+ // The one deliberate exception to the "never interpolate into executed
164
+ // code" rule (design.md §C) — Pact's signed `clist` has no `read-string`
165
+ // equivalent, so capabilities must be literal in the signed command. Made
166
+ // safe here because `targetAccount` is shape-guarded above and `amount`
167
+ // is already regex-validated, never a raw pass-through of untrusted text.
168
+ // LIQUIDPOT -> target is the REVERSE account order from `stoa-wrap.ts`'s
169
+ // own patron -> LIQUIDPOT capability (confirmed asymmetric per
170
+ // design.md §B).
171
+ const capabilityLine = `(coin.TRANSFER "${STOA_AUTONOMIC_LIQUIDPOT}" "${targetAccount}" ${amount})`;
172
+ const newSigners = signers.map((signer, index) => {
173
+ if (index !== 0)
174
+ return signer;
175
+ // If signer 0's own key is ALSO the gas-station's signing key,
176
+ // `effectiveSigners` (executor-signers.ts) sees that pubkey "already
177
+ // present" among `signers` and skips synthesizing its own
178
+ // DALOS.GAS_PAYER-scoped entry for it (presence is checked by pubkey
179
+ // only, never capability content) — so narrowing this signer to
180
+ // `capabilityMode:'scoped'` with ONLY `coin.TRANSFER` would silently
181
+ // drop the gas-sponsorship grant that SAME key needs, surfacing as an
182
+ // opaque failure at submit time, not at plan time (identical risk to
183
+ // `stoa-wrap.ts`'s own fix for this). Append the identical capability
184
+ // line `effectiveSigners` would otherwise have synthesized.
185
+ const gasPayerCapLine = gasPayer.type === "gas-station" && gasPayer.gasStationSignerKey === signer.publicKey
186
+ ? `(${ctx.runtime.namespace}.DALOS.GAS_PAYER "" 0 0.0)`
187
+ : null;
188
+ return {
189
+ ...signer,
190
+ capabilityMode: "scoped",
191
+ capabilities: [signer.capabilities, capabilityLine, gasPayerCapLine].filter(Boolean).join("\n"),
192
+ };
193
+ });
194
+ return [
195
+ {
196
+ pactCode,
197
+ config,
198
+ payload,
199
+ gasPayer,
200
+ signers: newSigners,
201
+ },
202
+ ];
203
+ };
204
+ registerStepPlanner("ouronet.stoa-unwrap", stoaUnwrapPlanner);