gdp-wired 0.58.0 → 0.59.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -261,14 +261,15 @@ All of these are proven automatically, and each proof is also a Lean theorem:
261
261
  `check()` shows every state reached by a run (or proves it unreachable), no state stuck and no event ambiguous, and its
262
262
  laws prove like any rule's (`examples/charts.ts`). Not yet: parallel regions inside a state (XState's entry and exit
263
263
  actions, eventless and delayed transitions are read by `fromXState`, below).
264
- - **XState machines** (`gdp-wired/xstate`): `fromXState(machine, {guards, actions})` builds the chart an XState v5
265
- machine runs as, with each guard and action it names given again in gdp-wired's terms, and `conforms(chart, machine,
266
- createActor)` drives XState's own actor and the compiled rule with the same random events, comparing every state and
267
- context; what a chart can't run the same way, and any key it doesn't read, is refused when built, with the reason
268
- (`examples/xstate.ts`). A v4 machine's `cond` is read as its guard. An invoked actor's done and error and a timer
269
- firing are events from outside, taken only where they can come (each once a visit; one timer at a time), and
270
- eventless transitions and entry and exit actions that write the context are read into each transition as XState's
271
- macrostep.
264
+ - **With XState and `@xstate/graph`** (`gdp-wired/xstate`, [`docs/xstate.md`](docs/xstate.md)): prove a rule or chart
265
+ and present it as XState v5 `ActorLogic` with `toLogic(ruleOrChart, {params, maxValue})` (copied states via
266
+ `rule.interpreter()`, canonical `serializeState` over maps and logs, small-edge default `events`) so `@xstate/graph`'s
267
+ `TestModel` generates shortest paths against your real app, and `runToEvents(ruleOrChart, run)` turns prover
268
+ counterexamples into `getPathsFromEvents` regression paths (`examples/xstate-mbt.ts`). For an existing XState v5/v4
269
+ machine, `fromXState(machine, {guards, actions})` translates it into a provable chart (nesting, parallel roots, deep
270
+ history, `invoke`/`after`, `always` and `entry`/`exit` macrosteps; unsupported keys refused) and `conforms(chart,
271
+ machine, createActor)` checks it against XState's own actor (`examples/xstate.ts`). The proof covers the logic;
272
+ model-based tests cover the app around it.
272
273
  - **Rules read from the code** (`gdp-wired/extract`): `extract('./bucket.ts')` reads a reducer, `useReducer`'s, functions
273
274
  over one record, a class whose methods write its fields (with the classes it extends), or the object of functions a
274
275
  factory returns, and returns the rule that steps the same way, as a builder value and as source to keep
@@ -689,7 +690,7 @@ Proving and checking: a law over 64 steps proves in about 5 s, and Lean checks i
689
690
  | `kernel/` | The trusted kernel and the untrusted prover, with soundness fuzz (`kernel.test.ts`, `history.test.ts`) |
690
691
  | `lean-kernel/` | The kernel's Lean twin, its soundness proofs, and the exported trees |
691
692
  | `examples/` | The builders at work: `domains/` (187 rules across 21 domains, each with laws and broken variants), `harness.ts` (the triple check), `readme.ts`, `guide.ts` (the guide's code), `groups.ts` (two groups decided at every pair), `budget.ts`, `gdp.ts` (gdp-ts's example, its checks proven), `exists.ts` (laws with "there exists"), `datatypes.ts` (records and variants), `lemmas.ts` (recurrences and their lemmas), `invoices.ts` (lists a request carries), `folds.ts` (folds over trees), `trees.ts` (trees and lists of lists in the state), `composition.ts`, `sets.ts`, `quantifiers.ts`, `functions.ts`, `arith.ts` (division and remainder by a constant, integers in rules and datatypes), `lists.ts`, `sizes.ts`, `liveness.ts`, `steps.ts` (laws over up to 64 steps), and `jev-fabric/` (a Bend project's 59 proven laws, ported) |
692
- | `docs/` | [ARCHITECTURE.md](docs/ARCHITECTURE.md) (the trust boundaries and what guards each), [FRONTENDS.md](docs/FRONTENDS.md) (how a language's reader plugs in), [minimize.md](docs/minimize.md) (shrinking refuting runs with `minimizeRun`), [interchange.md](docs/interchange.md) (certificates as JSON, for checkers in other languages), the comparison with Bend and Lean |
693
+ | `docs/` | [ARCHITECTURE.md](docs/ARCHITECTURE.md) (the trust boundaries and what guards each), [FRONTENDS.md](docs/FRONTENDS.md) (how a language's reader plugs in), [xstate.md](docs/xstate.md) (XState machines and model-based testing with `@xstate/graph`), [minimize.md](docs/minimize.md) (shrinking refuting runs with `minimizeRun`), [interchange.md](docs/interchange.md) (certificates as JSON, for checkers in other languages), the comparison with Bend and Lean |
693
694
  | `compare/` | The same three rules in gdp-wired, Bend and plain Lean, checked and measured |
694
695
  | `research/` | Everything around the library ([`research/README.md`](research/README.md)): the GPU searches (`search/`, `hw/`, `modal-gpu/`), invariant and rank synthesis (`synth/`), relational laws and guard synthesis (`next/`), bit-vector laws (`sat/`), the enumeration and benchmarks (`enum/`, `gpu/`, `perf/`), the first Lean checker (`lean/`) and the first prototype, the audit path (`audit/`) |
695
696
  | `supercomputer/` | Everything above as jobs on instabox boxes through [supercomputer](https://github.com/monotykamary/supercomputer): `suite.json` is the regression suite, `setup.sh` the boxes' image |
@@ -703,7 +704,7 @@ The npm package is built from `core/`, `kernel/` and `lean-kernel/` alone; nothi
703
704
 
704
705
  The npm package is the library: the builders (`gdp-wired`), the runtimes (`gdp-wired/machine`), refutation run
705
706
  minimization (`gdp-wired/minimize`, also exported from `gdp-wired` and every frontend subpath), composition
706
- (`gdp-wired/compose`), XState machines as charts (`gdp-wired/xstate`), rules read from the code (`gdp-wired/extract`, with
707
+ (`gdp-wired/compose`), XState machines and `@xstate/graph` model-based testing (`gdp-wired/xstate`, [`docs/xstate.md`](docs/xstate.md)), rules read from the code (`gdp-wired/extract`, with
707
708
  `typescript` installed), Effect services (`gdp-wired/effect`, with `typescript` and `effect`), lemmas nobody stated (`gdp-wired/discover`), invariant
708
709
  inference (`gdp-wired/infer`), the
709
710
  Lean export (`gdp-wired/lean`), the kernel (`gdp-wired/kernel`), the prover (`gdp-wired/prove`), the derivation checker
@@ -72,6 +72,10 @@ export declare class Chart<P extends Obj = {}, I extends Obj = {}, X extends Obj
72
72
  private built?;
73
73
  private build;
74
74
  get rule(): Rule<Obj, Obj, Obj, Obj, Obj, Obj, Obj, Obj>;
75
+ regionFields(): {
76
+ name: string;
77
+ field: string;
78
+ }[];
75
79
  in(env: Obj, path: string): Cond;
76
80
  last(env: Obj, compound: string): Choice<string>;
77
81
  private wrap;
@@ -197,6 +197,8 @@ export class Chart {
197
197
  // The rule the chart compiles to: its state is each region's state (`state`, or the region's name), each compound's
198
198
  // last child where it keeps its history, and the context; its inputs the event and the payload.
199
199
  get rule() { return this.build().rule; }
200
+ // Each region's name and state variable in the compiled rule (a single-region chart has one, named 'state').
201
+ regionFields() { return this.build().regions.map(r => ({ name: r.name, field: r.field })); }
200
202
  // Whether a region is in a state (a compound: any state within it), for laws: chart.in(env, 'active').
201
203
  in(env, path) {
202
204
  const { regions } = this.build(), single = regions.length === 1 && regions[0].name === 'state';
@@ -2145,7 +2145,8 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
2145
2145
  }
2146
2146
  return broke;
2147
2147
  };
2148
- const houdiniUntil = opts.cubes || relStep ? 0 : Math.min(until, now() + Math.max(500, (until - now()) / 4));
2148
+ const hasRelations = !!Object.keys(m.relations ?? {}).length;
2149
+ const houdiniUntil = opts.cubes || relStep || hasRelations ? 0 : Math.min(until, now() + Math.max(500, (until - now()) / 4));
2149
2150
  for (let quiet = 0; samples.length && now() < houdiniUntil && !stop() && quiet < 3;) {
2150
2151
  const killed = new Set();
2151
2152
  for (let tries = 0; tries < 400 && now() < houdiniUntil && !stop(); tries++) {
@@ -2330,7 +2331,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
2330
2331
  if (joinOn && NS)
2331
2332
  try {
2332
2333
  // (a rule of relations: no round of the join, whose hulls and bounds state no law of a relation's tuples; the engine's)
2333
- const noJoin = opts.join === 0 || !!Object.keys(m.relations ?? {}).length;
2334
+ const noJoin = opts.join === 0 || hasRelations;
2334
2335
  const jT0 = countedSearchNow(), jUntil = Math.min(until, now() + (until - now()) * (noJoin ? 0 : opts.join ?? joinShare));
2335
2336
  // The control state: the choice (loc) and, where they are few, the yes/nos (a program counter in bits), each of its
2336
2337
  // values reached a part of its own.
@@ -2370,7 +2371,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
2370
2371
  // Where no key is composed but a caller's law is about several keys (two counted approvals by distinct reviewers, two
2371
2372
  // holders of one lock), the same space over two distinct keys x ≠ y: the cells at x and at y (`n` 0, no third place).
2372
2373
  const pairing = mapNames.length ? pairingOf(m) ?? ([...laws, ...stepLaws].some(l => l.keys?.length) ? { n: 0, c: 0, frame: not(same(x(KEY), x(KEY2))) } : undefined) : undefined;
2373
- const cellLevels = pairing ? levelsOf(cellAtoms.filter(i => !atoms[i].int), valsK) : [];
2374
+ const cellLevels = !noJoin && pairing ? levelsOf(cellAtoms.filter(i => !atoms[i].int), valsK) : [];
2374
2375
  // A view's atoms (each map at each place it is read at there) and rows: each assignment of its keys to keys a state
2375
2376
  // holds (by sort: the keys of the maps read at the key's place, the parts of composed keys there, and a fresh one;
2376
2377
  // per key at most `per`), the frame met, each map's cell at each of its places.
@@ -2498,7 +2499,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
2498
2499
  const sorts = mapNames.length ? keySorts(m, callerLaws, pairing) : undefined;
2499
2500
  // (the maps keyed by tuples are read at their tuples, in the engine's views alone)
2500
2501
  const flat = mapNames.filter(mp => !sorts?.tupled.has(mp));
2501
- if (pairing && flat.length) {
2502
+ if (!noJoin && pairing && flat.length) {
2502
2503
  const P = pairing, composed = plus(times(P.n, x(KEY)), x(KEY2)), places = P.n ? [x(KEY), x(KEY2), P.c ? plus(composed, n(P.c)) : composed] : [x(KEY), x(KEY2)];
2503
2504
  // (by sort, where the rule composes: a row's maps at x, a column's at y, the composed maps at the composed key)
2504
2505
  const sorted = P.n && sorts ? [sorts.plainMaps(sorts.find('hi')), sorts.plainMaps(sorts.find('lo')), sorts.composedMaps] : undefined;
@@ -2522,7 +2523,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
2522
2523
  // (keySorts: a sort is the places a key is read at, the rule's keys read alike as one), its places the composed keys
2523
2524
  // its reads name and each map read at a plain key of a key's sort, its frame its own guards on its keys and the keys
2524
2525
  // of one sort distinct.
2525
- if (sorts) {
2526
+ if (!noJoin && sorts) {
2526
2527
  const seen = new Set();
2527
2528
  for (const l of callerLaws) {
2528
2529
  const bound = l.forall ? [l.forall, ...(l.keys ?? [])] : [];
@@ -2835,7 +2836,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
2835
2836
  };
2836
2837
  return { cells, add, forms, refine, deepen, coords, control: () => `${ctl.map(c => nameOf(c.atom)).join(' ')} (${scored.join(' ')})`, groups };
2837
2838
  };
2838
- const spaces = [space('state'), ...(mapNames.length && cellAtoms.length ? [space('cells')] : []), ...views.flatMap((v, i) => (v.rows.length ? [space(i)] : []))];
2839
+ const spaces = noJoin ? [] : [space('state'), ...(mapNames.length && cellAtoms.length ? [space('cells')] : []), ...views.flatMap((v, i) => (v.rows.length ? [space(i)] : []))];
2839
2840
  const formsNow = () => {
2840
2841
  const out = [], seenT = new Set();
2841
2842
  const push = (f) => { const t = textOf(f); if (!seenT.has(t) && !names.has(t)) {
@@ -2979,17 +2980,17 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
2979
2980
  // (the rule's own comparisons first, then each value, then pairs: of two directions that leave out as many samples
2980
2981
  // the first is taken, so a bound the runs' depth sets, i0 <= 1 where they went 1 deep, gives way to the relation
2981
2982
  // that holds at every depth, i0 <= i1)
2982
- const lc = plain.filter(i => !atoms[i].param && !ctrl.includes(i)), D0 = directions(lc), own = 2 * lc.length + (lc.length <= joinPairs ? 2 * lc.length * (lc.length - 1) : 0);
2983
+ const lc = plain.filter(i => !atoms[i].param && !ctrl.includes(i)), D0 = noJoin ? [] : directions(lc), own = 2 * lc.length + (lc.length <= joinPairs ? 2 * lc.length * (lc.length - 1) : 0);
2983
2984
  const D = [...D0.slice(own), ...D0.slice(0, own)];
2984
2985
  const dot = (t, v) => { let s2 = 0; for (const [i, c] of t)
2985
2986
  s2 += c * v[i]; return s2; };
2986
2987
  const litHolds = (l, v) => ('at' in l ? v[l.at.atom] === l.at.value : dot(l.lin.coef, v) <= l.lin.d);
2987
2988
  const inCube = (c, v) => c.every(l => litHolds(l, v));
2988
2989
  const vecKey = (v) => v instanceof Float64Array ? v.join(',') : Array.from(v).join(',');
2989
- const S = rowsS.map(r => valuesOf(r)), sampled = new Set(S.map(vecKey));
2990
+ const S = noJoin ? [] : rowsS.map(r => valuesOf(r)), sampled = new Set(S.map(vecKey));
2990
2991
  let initVec;
2991
2992
  try {
2992
- if (!m.params.length)
2993
+ if (!noJoin && !m.params.length)
2993
2994
  initVec = valuesOf(pointOf({}, run.init({})).scalar);
2994
2995
  }
2995
2996
  catch {
@@ -3020,7 +3021,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
3020
3021
  // predecessors take it back to the samples; the comparisons are what a predecessor's guards say, as Spacer's
3021
3022
  // projections read them), then the direction that leaves out the most samples still in, its bound as weak as
3022
3023
  // leaves them out, until none is in (undefined: none leaves out the rest).
3023
- const ruleLits = joinAtoms ? comparisons(m, laws, atoms, lc).map(lin => ({ lin })) : [];
3024
+ const ruleLits = !noJoin && joinAtoms ? comparisons(m, laws, atoms, lc).map(lin => ({ lin })) : [];
3024
3025
  const cubeOf = (v) => {
3025
3026
  const lits = ctrl.map(i => ({ at: { atom: i, value: v[i] } }));
3026
3027
  for (const l of ruleLits)
@@ -3234,7 +3235,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts, observed) {
3234
3235
  // bounds that leave the samples' rows out), blocked as the state's cubes are (its negation proven relative to the
3235
3236
  // set, the literals it doesn't need taken out): a law at every tuple of the view's keys. The disjunctions a hull
3236
3237
  // can't say (two waiting threads' tickets differ) are such cubes.
3237
- const viewSpaces = views.map(v => {
3238
+ const viewSpaces = noJoin ? [] : views.map(v => {
3238
3239
  const R = v.rows.slice(0, 3000).map(valuesOf), seen = new Set(R.map(vecKey)), mapOf = (i) => atoms[i].parts[0][0].slice(2, atoms[i].parts[0][0].lastIndexOf(AT));
3239
3240
  const own = v.atoms.filter(i => !atoms[i].int), few = own.filter(i => new Set(R.map(r => r[i])).size <= 3);
3240
3241
  const eqs = own.flatMap((i, a2) => own.slice(a2 + 1).filter(j => mapOf(i) === mapOf(j) && !few.includes(i)).flatMap(j => [{ lin: { coef: [[i, 1], [j, -1]], d: 0 } }, { lin: { coef: [[j, 1], [i, -1]], d: 0 } }]));
@@ -1,5 +1,5 @@
1
- import { type Kind, Cond } from './dsl.js';
2
- import { type Chart } from './chart.js';
1
+ import { type Kind, type Raw, Cond, Rule } from './dsl.js';
2
+ import { Chart } from './chart.js';
3
3
  type Obj = Record<string, any>;
4
4
  type XAction = string | {
5
5
  type: string;
@@ -74,4 +74,78 @@ export declare function conforms(c: Chart<Obj, Obj, Obj>, machine: MachineLike,
74
74
  checked: number;
75
75
  failure?: string;
76
76
  };
77
+ export type RuleOrChart = Rule<any, any, any, any, any, any, any, any> | Chart<any, any, any>;
78
+ export type RuleEvent = {
79
+ readonly type: string;
80
+ readonly [k: string]: unknown;
81
+ };
82
+ export type RuleSnapshot<C extends Record<string, unknown> = Record<string, unknown>> = {
83
+ readonly status: 'active';
84
+ readonly output: undefined;
85
+ readonly error: undefined;
86
+ readonly context: C;
87
+ readonly value?: unknown;
88
+ readonly defaults?: Readonly<Record<string, number>>;
89
+ readonly history?: readonly Record<string, number>[];
90
+ readonly last?: number;
91
+ };
92
+ export type RulePersistedSnapshot = {
93
+ readonly status: 'active';
94
+ readonly output: undefined;
95
+ readonly error: undefined;
96
+ readonly context: Record<string, unknown>;
97
+ readonly value?: unknown;
98
+ readonly defaults?: Readonly<Record<string, number>>;
99
+ readonly history?: readonly Record<string, number>[];
100
+ readonly last?: number;
101
+ readonly state: {
102
+ readonly scalars: Record<string, number>;
103
+ readonly maps: Record<string, [number, number][]>;
104
+ readonly defaults?: Record<string, number>;
105
+ readonly history?: Record<string, number>[];
106
+ readonly last?: number;
107
+ };
108
+ readonly params: Record<string, number>;
109
+ };
110
+ export type ToLogicOptions<S extends RuleSnapshot = RuleSnapshot, E extends RuleEvent = RuleEvent> = {
111
+ params?: Record<string, Raw>;
112
+ events?: readonly E[] | ((snapshot: S) => readonly E[]);
113
+ maxValue?: number;
114
+ eventField?: string;
115
+ eventType?: string;
116
+ compileHelpers?: boolean;
117
+ };
118
+ export type RuleLogic<S extends RuleSnapshot = RuleSnapshot, E extends RuleEvent = RuleEvent> = {
119
+ readonly config: {
120
+ readonly name: string;
121
+ };
122
+ readonly getInitialSnapshot: (actorScope?: unknown, input?: unknown) => S;
123
+ readonly transition: (snapshot: S, event: E, actorScope?: unknown) => S;
124
+ readonly getPersistedSnapshot: (snapshot: S, options?: unknown) => RulePersistedSnapshot;
125
+ readonly restoreSnapshot: (persistedState: {
126
+ readonly status: string;
127
+ readonly output?: unknown;
128
+ readonly error?: unknown;
129
+ readonly [k: string]: unknown;
130
+ }, actorScope?: unknown) => S;
131
+ readonly events: (snapshot: S) => E[];
132
+ readonly serializeState: (snapshot: S) => string;
133
+ readonly stateMatcher: (snapshot: S, stateKey: string) => boolean;
134
+ readonly options: {
135
+ readonly events: (snapshot: S) => E[];
136
+ readonly serializeState: (snapshot: S) => string;
137
+ readonly stateMatcher: (snapshot: S, stateKey: string) => boolean;
138
+ };
139
+ };
140
+ export type RuleRun = {
141
+ readonly params?: Record<string, number>;
142
+ readonly trace: readonly Record<string, unknown>[];
143
+ };
144
+ export type RunToEventsOptions = {
145
+ eventField?: string;
146
+ eventType?: string;
147
+ };
148
+ export declare function serializeState(snapshot: unknown): string;
149
+ export declare function toLogic<S extends RuleSnapshot = RuleSnapshot, E extends RuleEvent = RuleEvent>(ruleOrChart: RuleOrChart, opts?: ToLogicOptions<S, E>): RuleLogic<S, E>;
150
+ export declare function runToEvents(ruleOrChart: RuleOrChart, run: RuleRun | readonly Record<string, unknown>[], opts?: RunToEventsOptions): RuleEvent[];
77
151
  export {};
@@ -33,9 +33,10 @@
33
33
  // An XState v4 machine reads the same, its `cond` the guard v5 calls `guard` (a name, or {type, ...params}); v4's
34
34
  // `in`, `strict`, `activities` and eventless `''` are refused with the rest. Each XState ignores the other's guard key,
35
35
  // so a v5 machine with `cond` or a v4 one with `guard` is refused (a plain config is read by the key it uses).
36
- import { Choice, Cond, Maybe, Str, Term, all, bool, int, lit, no, yes } from "./dsl.js";
37
- import { chart } from "./chart.js";
38
- import { seeded } from "./machine.js";
36
+ import { Bool, Choice, Cond, Decimal, FixedWord, Int, Maybe, Str, Term, Variant, all, bool, int, lit, no, yes } from "./dsl.js";
37
+ import { Chart, chart } from "./chart.js";
38
+ import { evalC, seeded } from "./machine.js";
39
+ import { allowed } from "./watch.js";
39
40
  // The keys read, and those that change nothing a run shows (descriptions, metadata, types, a final state's output, v4's
40
41
  // action-order flags, which order no write to the context: those a transition makes run in order either way; v5's
41
42
  // `reenter` and v4's `internal`, which change only which entry and exit actions run, and those write no context here).
@@ -555,3 +556,635 @@ export function conforms(c, machine, createActor, opts = {}) {
555
556
  }
556
557
  return { checked };
557
558
  }
559
+ const snapshotInternals = new WeakMap();
560
+ const sortKeys = (o) => Object.fromEntries(Object.keys(o).sort().map(k => [k, o[k]]));
561
+ const canonicalValue = (v) => {
562
+ if (v === null || typeof v !== 'object')
563
+ return JSON.stringify(v);
564
+ if (v instanceof Map) {
565
+ const entries = [...v.entries()].map(([k, val]) => [canonicalValue(k), canonicalValue(val)])
566
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
567
+ return `{"$map":[${entries.map(([k, val]) => `[${k},${val}]`).join(',')}]}`;
568
+ }
569
+ if (v instanceof Set) {
570
+ const items = [...v].map(canonicalValue).sort();
571
+ return `{"$set":[${items.join(',')}]}`;
572
+ }
573
+ if (Array.isArray(v))
574
+ return `[${v.map(canonicalValue).join(',')}]`;
575
+ const o = v;
576
+ const keys = Object.keys(o).filter(k => o[k] !== undefined).sort();
577
+ return `{${keys.map(k => `${JSON.stringify(k)}:${canonicalValue(o[k])}`).join(',')}}`;
578
+ };
579
+ // Canonical, key-order-independent serialization of a snapshot (scalars, maps with defaults, and logs included).
580
+ export function serializeState(snapshot) {
581
+ if (snapshot && typeof snapshot === 'object') {
582
+ const internal = snapshotInternals.get(snapshot);
583
+ if (internal) {
584
+ const { machine: m, state: st } = internal;
585
+ const scalars = sortKeys(st.scalars);
586
+ const maps = {};
587
+ for (const name of Object.keys(st.maps).sort()) {
588
+ const dflt = st.defaults && Object.hasOwn(st.defaults, name) ? st.defaults[name] : m.maps?.[name] ?? 0;
589
+ const entries = [...st.maps[name].entries()].filter(([, v]) => v !== dflt).sort((a, b) => a[0] - b[0]);
590
+ maps[name] = { default: dflt, entries };
591
+ }
592
+ const payload = { scalars, maps };
593
+ if (st.history !== undefined)
594
+ payload.history = st.history.map(rec => sortKeys(rec));
595
+ if (st.last !== undefined)
596
+ payload.last = st.last;
597
+ return canonicalValue(payload);
598
+ }
599
+ }
600
+ return canonicalValue(snapshot);
601
+ }
602
+ const isPlainObject = (x) => typeof x === 'object' && x !== null && Object.getPrototypeOf(x) === Object.prototype;
603
+ const isChoiceKind = (name, kind) => {
604
+ const val = kind.value(name);
605
+ return val instanceof Choice ? val : undefined;
606
+ };
607
+ function resolveEventField(r, isChart, explicit) {
608
+ const inputs = r.parts.inputs;
609
+ if (explicit !== undefined) {
610
+ const found = inputs.find(([n]) => n === explicit);
611
+ if (!found)
612
+ throw new Error(`${r.name}: eventField ${explicit} is not an input`);
613
+ const ch = isChoiceKind(found[0], found[1]);
614
+ if (!ch)
615
+ throw new Error(`${r.name}: eventField ${explicit} must be a oneOf input`);
616
+ return { field: explicit, choices: ch.values };
617
+ }
618
+ const prefer = isChart ? ['event'] : ['event', 'op'];
619
+ for (const cand of prefer) {
620
+ const found = inputs.find(([n]) => n === cand);
621
+ const ch = found ? isChoiceKind(found[0], found[1]) : undefined;
622
+ if (ch)
623
+ return { field: found[0], choices: ch.values };
624
+ }
625
+ for (const [n, k] of inputs) {
626
+ const ch = isChoiceKind(n, k);
627
+ if (ch)
628
+ return { field: n, choices: ch.values };
629
+ }
630
+ return {};
631
+ }
632
+ // Strip default-valued entries and copy every mutable container so states reached by different paths match canonically.
633
+ function normalizeState(m, st) {
634
+ const maps = {};
635
+ for (const name of Object.keys(st.maps)) {
636
+ const dflt = st.defaults && Object.hasOwn(st.defaults, name) ? st.defaults[name] : m.maps?.[name] ?? 0;
637
+ const clean = new Map();
638
+ for (const [k, v] of [...st.maps[name].entries()].sort((a, b) => a[0] - b[0])) {
639
+ if (v !== dflt)
640
+ clean.set(k, v);
641
+ }
642
+ maps[name] = clean;
643
+ }
644
+ const defaults = {};
645
+ for (const [name, d] of Object.entries(st.defaults ?? {})) {
646
+ if (d !== (m.maps?.[name] ?? 0))
647
+ defaults[name] = d;
648
+ }
649
+ return {
650
+ scalars: { ...st.scalars },
651
+ maps,
652
+ ...(Object.keys(defaults).length ? { defaults } : {}),
653
+ ...(st.history ? { history: st.history.map(rec => ({ ...rec })) } : {}),
654
+ ...(st.last !== undefined ? { last: st.last } : {}),
655
+ };
656
+ }
657
+ // Scalar variable names that encode finite/categorical/tagged kinds (not unbounded counters).
658
+ function boundedScalarNames(r) {
659
+ const out = new Set();
660
+ const walk = (name, val) => {
661
+ if (val instanceof Choice || val instanceof Bool) {
662
+ out.add(name);
663
+ return;
664
+ }
665
+ if (val instanceof Str) {
666
+ out.add(name);
667
+ out.add(`${name}$len`);
668
+ val.patterns.forEach((_, i) => out.add(`${name}$like${i}`));
669
+ return;
670
+ }
671
+ if (val instanceof Maybe) {
672
+ out.add(`${name}$some`);
673
+ walk(name, val.inner);
674
+ return;
675
+ }
676
+ if (val instanceof Variant) {
677
+ out.add(name);
678
+ for (const c of val.kind.names) {
679
+ const fields = val.cases[c];
680
+ for (const [f, fv] of Object.entries(fields))
681
+ walk(`${name}.${c}.${f}`, fv);
682
+ }
683
+ return;
684
+ }
685
+ if (val instanceof FixedWord) {
686
+ for (const limb of val.limbs)
687
+ if (limb.e.op === 'var')
688
+ out.add(limb.e.name);
689
+ return;
690
+ }
691
+ if (isPlainObject(val))
692
+ for (const [f, fv] of Object.entries(val))
693
+ walk(`${name}.${f}`, fv);
694
+ };
695
+ for (const [n, k] of r.kindsOfState())
696
+ walk(n, k.value(n));
697
+ return out;
698
+ }
699
+ // Upper bound declared on an upTo(k) kind, if any.
700
+ function upToBound(name, kind) {
701
+ for (const cond of kind.assume(name)) {
702
+ const c = cond.c;
703
+ if (c.op === '<=' && c.a.op === 'var' && c.a.name === name && c.b.op === 'const')
704
+ return c.b.value;
705
+ if (c.op === '<' && c.a.op === 'var' && c.a.name === name && c.b.op === 'const')
706
+ return c.b.value - 1;
707
+ }
708
+ return undefined;
709
+ }
710
+ function collectNumbers(v, out) {
711
+ if (typeof v === 'number' && Number.isSafeInteger(v)) {
712
+ out.push(v);
713
+ return;
714
+ }
715
+ if (Array.isArray(v)) {
716
+ for (const x of v)
717
+ collectNumbers(x, out);
718
+ return;
719
+ }
720
+ if (isPlainObject(v))
721
+ for (const x of Object.values(v))
722
+ collectNumbers(x, out);
723
+ }
724
+ function collectStrings(v, out) {
725
+ if (typeof v === 'string') {
726
+ out.add(v);
727
+ return;
728
+ }
729
+ if (Array.isArray(v)) {
730
+ for (const x of v)
731
+ collectStrings(x, out);
732
+ return;
733
+ }
734
+ if (isPlainObject(v))
735
+ for (const x of Object.values(v))
736
+ collectStrings(x, out);
737
+ }
738
+ function stateNumerics(st, bounded, plainMaps) {
739
+ const out = [];
740
+ for (const [k, v] of Object.entries(st.scalars))
741
+ if (!bounded.has(k))
742
+ out.push(v);
743
+ for (const name of plainMaps) {
744
+ const cells = st.maps[name];
745
+ if (!cells)
746
+ continue;
747
+ for (const [k, v] of cells) {
748
+ out.push(k);
749
+ out.push(v);
750
+ }
751
+ }
752
+ return out;
753
+ }
754
+ function decodedStateOf(r, m, st, chartRef) {
755
+ const decoded = r.decode(st);
756
+ const owned = new Set();
757
+ for (const [n, k] of r.kindsOfCells())
758
+ for (const part of k.vars(n))
759
+ owned.add(part);
760
+ for (const [n, val] of Object.entries(decoded)) {
761
+ if (!Array.isArray(val))
762
+ continue;
763
+ for (const mp of Object.keys(m.maps ?? {})) {
764
+ if (mp === n || mp.startsWith(`${n}.`) || mp.startsWith(`${n}^`) || mp.startsWith(`${n}$`))
765
+ owned.add(mp);
766
+ }
767
+ }
768
+ const plainMaps = new Set();
769
+ for (const name of Object.keys(m.maps ?? {}).sort()) {
770
+ if (owned.has(name))
771
+ continue;
772
+ plainMaps.add(name);
773
+ const entries = [...(st.maps[name]?.entries() ?? [])].sort((a, b) => a[0] - b[0]);
774
+ decoded[name] = Object.fromEntries(entries.map(([k, v]) => [String(k), v]));
775
+ }
776
+ let value;
777
+ if (chartRef) {
778
+ const regions = chartRef.regionFields();
779
+ const nest = (path) => path.split('.').reduceRight((acc, seg) => (acc === undefined ? seg : { [seg]: acc }), undefined);
780
+ if (regions.length === 1 && regions[0].name === 'state') {
781
+ const s = String(decoded[regions[0].field]);
782
+ value = s === STATELESS ? {} : nest(s);
783
+ }
784
+ else {
785
+ value = Object.fromEntries(regions.map(reg => [reg.name, nest(String(decoded[reg.field]))]));
786
+ }
787
+ }
788
+ return { context: sortKeys(decoded), value, plainMaps };
789
+ }
790
+ function emptyOfVal(val) {
791
+ if (val instanceof Choice)
792
+ return val.values[0];
793
+ if (val instanceof Bool)
794
+ return false;
795
+ if (val instanceof Maybe)
796
+ return null;
797
+ if (val instanceof Str)
798
+ return '';
799
+ if (val instanceof Variant) {
800
+ const k = val.kind.names[0], fields = val.cases[k];
801
+ return { [val.kind.tagKey]: k, ...Object.fromEntries(Object.entries(fields).map(([f, fv]) => [f, emptyOfVal(fv)])) };
802
+ }
803
+ if (isPlainObject(val))
804
+ return Object.fromEntries(Object.entries(val).map(([f, fv]) => [f, emptyOfVal(fv)]));
805
+ return 0;
806
+ }
807
+ function enumerateVal(name, val, kind, natEdges, intEdges, strings, maxValue, ceiling) {
808
+ if (val instanceof Choice)
809
+ return [...val.values];
810
+ if (val instanceof Bool)
811
+ return [false, true];
812
+ if (val instanceof Term) {
813
+ const cap = kind ? upToBound(name, kind) : undefined;
814
+ if (cap === undefined)
815
+ return natEdges;
816
+ const out = new Set();
817
+ for (const x of natEdges)
818
+ if (x <= cap)
819
+ out.add(x);
820
+ if (cap <= 4)
821
+ for (let i = 0; i <= cap; i++)
822
+ out.add(i);
823
+ else if (cap <= ceiling)
824
+ out.add(cap);
825
+ return [...out].sort((a, b) => a - b);
826
+ }
827
+ if (val instanceof Int)
828
+ return intEdges;
829
+ if (val instanceof Decimal) {
830
+ const unit = 1 / 10 ** val.places;
831
+ const out = new Set([0, unit, 1, maxValue].filter(x => x <= ceiling));
832
+ return [...out].sort((a, b) => a - b);
833
+ }
834
+ if (val instanceof Maybe)
835
+ return [null, ...enumerateVal(name, val.inner, undefined, natEdges, intEdges, strings, maxValue, ceiling)];
836
+ if (val instanceof Str) {
837
+ const pool = new Set(['', ...strings]);
838
+ for (const p of val.patterns) {
839
+ pool.add(p.replaceAll('*', ''));
840
+ pool.add(p.replaceAll('*', 'a'));
841
+ }
842
+ if (pool.size === 1)
843
+ pool.add('a');
844
+ return [...pool];
845
+ }
846
+ if (val instanceof Variant) {
847
+ const out = [];
848
+ for (const c of val.kind.names) {
849
+ const fields = Object.entries(val.cases[c]);
850
+ const combos = cartesian(fields.map(([f, fv]) => [f, enumerateVal(`${name}.${c}.${f}`, fv, undefined, natEdges, intEdges, strings, maxValue, ceiling)]));
851
+ for (const combo of combos)
852
+ out.push({ [val.kind.tagKey]: c, ...combo });
853
+ }
854
+ return out;
855
+ }
856
+ if (val instanceof FixedWord) {
857
+ const out = new Set([0, 1, maxValue]);
858
+ return [...out].sort((a, b) => a - b);
859
+ }
860
+ if (isPlainObject(val)) {
861
+ const fields = Object.entries(val);
862
+ return cartesian(fields.map(([f, fv]) => [f, enumerateVal(`${name}.${f}`, fv, undefined, natEdges, intEdges, strings, maxValue, ceiling)]));
863
+ }
864
+ return [emptyOfVal(val)];
865
+ }
866
+ function cartesian(fields) {
867
+ let acc = [{}];
868
+ for (const [k, vs] of fields) {
869
+ const next = [];
870
+ for (const row of acc)
871
+ for (const v of vs)
872
+ next.push({ ...row, [k]: v });
873
+ acc = next;
874
+ }
875
+ return acc;
876
+ }
877
+ // Present any proven gdp-wired rule or chart as XState v5 ActorLogic for @xstate/graph model-based testing.
878
+ // Steps through rule.interpreter() (never the in-place compiled runtime), so graph traversal branches safely.
879
+ export function toLogic(ruleOrChart, opts = {}) {
880
+ const isChart = ruleOrChart instanceof Chart;
881
+ const chartRef = isChart ? ruleOrChart : undefined;
882
+ const r = isChart ? chartRef.rule : ruleOrChart;
883
+ const m = r.machine;
884
+ const maxValue = opts.maxValue ?? 2;
885
+ if (!Number.isSafeInteger(maxValue) || maxValue < 0)
886
+ throw new RangeError(`${r.name}: maxValue must be a natural, not ${String(maxValue)}`);
887
+ const interp = r.interpreter({ compileHelpers: opts.compileHelpers });
888
+ const { field: eventField, choices: eventChoices } = resolveEventField(r, isChart, opts.eventField);
889
+ const eventType = opts.eventType ?? 'step';
890
+ const bounded = boundedScalarNames(r);
891
+ const listNames = new Set(r.parts.lists.map(([n]) => n));
892
+ const listLenNames = new Set([...listNames].map(n => `${n}_len`));
893
+ const listCarriedMaps = new Set(r.parts.lists.flatMap(([n, k, fs]) => [...k.vars(n), ...Object.keys(fs).map(f => `${n}$${f}`)]));
894
+ const plainCarriedMaps = (m.inputMaps ?? []).filter(mp => !listCarriedMaps.has(mp));
895
+ const userInputs = r.parts.inputs.filter(([n]) => !listLenNames.has(n));
896
+ const choicesSet = eventChoices ? new Set(eventChoices) : undefined;
897
+ const resolveParams = (given) => {
898
+ const rawParams = given ?? opts.params ?? (r.parts.params.length === 0 ? {} : undefined);
899
+ if (!rawParams)
900
+ throw new Error(`${r.name}: give params ({params: {...}}) for a rule with params`);
901
+ const ps = r.encodeParams(rawParams);
902
+ if (m.pre && !evalC(m.pre, ps, { scalars: {}, maps: {} }, m))
903
+ throw new RangeError(`${r.name}: params fail the rule's precondition`);
904
+ return { ps, rawParams };
905
+ };
906
+ const makeSnap = (st, ps, rawParams) => {
907
+ const clean = normalizeState(m, st);
908
+ const { context, value } = decodedStateOf(r, m, clean, chartRef);
909
+ const snap = {
910
+ status: 'active',
911
+ output: undefined,
912
+ error: undefined,
913
+ context,
914
+ ...(value !== undefined ? { value } : {}),
915
+ ...(clean.defaults && Object.keys(clean.defaults).length ? { defaults: sortKeys(clean.defaults) } : {}),
916
+ ...(clean.history !== undefined ? { history: clean.history.map(rec => sortKeys(rec)) } : {}),
917
+ ...(clean.last !== undefined ? { last: clean.last } : {}),
918
+ };
919
+ snapshotInternals.set(snap, { rule: r, machine: m, state: clean, params: ps, rawParams });
920
+ return snap;
921
+ };
922
+ const getInitialSnapshot = (_actorScope, input) => {
923
+ const override = isPlainObject(input) ? input : undefined;
924
+ const { ps, rawParams } = resolveParams(override);
925
+ return makeSnap(interp.init(ps), ps, rawParams);
926
+ };
927
+ const transition = (snapshot, event) => {
928
+ const internal = snapshotInternals.get(snapshot);
929
+ if (!internal)
930
+ throw new Error(`${r.name}: snapshot was not created by this logic (restore it with restoreSnapshot)`);
931
+ if (!event || typeof event !== 'object' || typeof event.type !== 'string' || event.type === 'xstate.init')
932
+ return snapshot;
933
+ if (eventField) {
934
+ if (!choicesSet.has(event.type))
935
+ return snapshot;
936
+ }
937
+ else if (event.type !== eventType) {
938
+ return snapshot;
939
+ }
940
+ const rawInput = {};
941
+ for (const [n, k] of userInputs) {
942
+ if (n === eventField) {
943
+ rawInput[n] = event.type;
944
+ continue;
945
+ }
946
+ rawInput[n] = event[n] !== undefined ? event[n] : k.empty();
947
+ }
948
+ for (const [n] of r.parts.lists)
949
+ rawInput[n] = event[n] !== undefined ? event[n] : [];
950
+ for (const mp of plainCarriedMaps) {
951
+ const v = event[mp];
952
+ if (v === undefined)
953
+ rawInput[mp] = new Map();
954
+ else if (v instanceof Map || v instanceof Set || Array.isArray(v))
955
+ rawInput[mp] = v;
956
+ else if (isPlainObject(v))
957
+ rawInput[mp] = new Map(Object.entries(v).map(([k, x]) => [Number(k), Number(x)]));
958
+ else
959
+ return snapshot;
960
+ }
961
+ let encoded;
962
+ try {
963
+ encoded = r.encodeInput(rawInput, r.parts.params.length ? internal.rawParams : undefined);
964
+ }
965
+ catch {
966
+ return snapshot;
967
+ }
968
+ try {
969
+ if (!allowed(m, interp, internal.params, internal.state, encoded))
970
+ return snapshot;
971
+ const next = interp.step(internal.params, internal.state, encoded);
972
+ return makeSnap(next, internal.params, internal.rawParams);
973
+ }
974
+ catch (e) {
975
+ if (e instanceof RangeError)
976
+ return snapshot;
977
+ throw e;
978
+ }
979
+ };
980
+ const getPersistedSnapshot = (snapshot) => {
981
+ const internal = snapshotInternals.get(snapshot);
982
+ if (!internal)
983
+ throw new Error(`${r.name}: snapshot was not created by this logic`);
984
+ const st = internal.state;
985
+ return {
986
+ status: 'active',
987
+ output: undefined,
988
+ error: undefined,
989
+ context: snapshot.context,
990
+ ...(snapshot.value !== undefined ? { value: snapshot.value } : {}),
991
+ ...(snapshot.defaults !== undefined ? { defaults: snapshot.defaults } : {}),
992
+ ...(snapshot.history !== undefined ? { history: snapshot.history } : {}),
993
+ ...(snapshot.last !== undefined ? { last: snapshot.last } : {}),
994
+ state: {
995
+ scalars: { ...st.scalars },
996
+ maps: Object.fromEntries(Object.entries(st.maps).map(([n, cells]) => [n, [...cells.entries()].sort((a, b) => a[0] - b[0])])),
997
+ ...(st.defaults && Object.keys(st.defaults).length ? { defaults: { ...st.defaults } } : {}),
998
+ ...(st.history !== undefined ? { history: st.history.map(rec => ({ ...rec })) } : {}),
999
+ ...(st.last !== undefined ? { last: st.last } : {}),
1000
+ },
1001
+ params: { ...internal.params },
1002
+ };
1003
+ };
1004
+ const restoreSnapshot = (persisted) => {
1005
+ const existing = snapshotInternals.get(persisted);
1006
+ if (existing)
1007
+ return makeSnap(existing.state, existing.params, existing.rawParams);
1008
+ const rawState = persisted.state;
1009
+ if (!rawState || typeof rawState !== 'object' || !rawState.scalars || !rawState.maps) {
1010
+ throw new Error(`${r.name}: persisted snapshot is missing raw state (produce it with getPersistedSnapshot)`);
1011
+ }
1012
+ const ps = (persisted.params ?? {});
1013
+ const rawParams = Object.fromEntries(r.parts.params.map(([n, k]) => [n, k.decode(n, ps)]));
1014
+ const st = {
1015
+ scalars: { ...rawState.scalars },
1016
+ maps: Object.fromEntries(Object.entries(rawState.maps).map(([n, entries]) => [n, new Map(entries)])),
1017
+ ...(rawState.defaults ? { defaults: { ...rawState.defaults } } : {}),
1018
+ ...(rawState.history ? { history: rawState.history.map(rec => ({ ...rec })) } : {}),
1019
+ ...(rawState.last !== undefined ? { last: rawState.last } : {}),
1020
+ };
1021
+ return makeSnap(st, { ...ps }, rawParams);
1022
+ };
1023
+ // Default event enumerator: all oneOf choices and booleans; for naturals, the small edge set (0, 1, state/param
1024
+ // values, maxValue). Stops expanding states whose unbounded numeric values or log length exceed the ceiling so
1025
+ // graph traversal on unbounded rules terminates cleanly.
1026
+ const defaultEvents = (snapshot) => {
1027
+ const internal = snapshotInternals.get(snapshot);
1028
+ if (!internal)
1029
+ return [];
1030
+ const { state: st, params: ps, rawParams } = internal;
1031
+ const { plainMaps } = decodedStateOf(r, m, st, chartRef);
1032
+ const initSt = normalizeState(m, interp.init(ps));
1033
+ const paramNums = [];
1034
+ collectNumbers(rawParams, paramNums);
1035
+ const initStateNums = stateNumerics(initSt, bounded, plainMaps);
1036
+ const stateCeiling = Math.max(maxValue, ...initStateNums.map(x => Math.abs(x)));
1037
+ const curNums = stateNumerics(st, bounded, plainMaps);
1038
+ if (curNums.some(x => Math.abs(x) > stateCeiling))
1039
+ return [];
1040
+ if (st.history !== undefined && st.history.length >= Math.max(1, maxValue))
1041
+ return [];
1042
+ const ceiling = Math.max(stateCeiling, ...paramNums.map(x => Math.abs(x)));
1043
+ const natSet = new Set([0]);
1044
+ if (maxValue >= 1)
1045
+ natSet.add(1);
1046
+ natSet.add(maxValue);
1047
+ const decodedNums = [...paramNums];
1048
+ collectNumbers(snapshot.context, decodedNums);
1049
+ for (const x of [...curNums, ...decodedNums])
1050
+ if (x >= 0 && x <= ceiling)
1051
+ natSet.add(x);
1052
+ const natEdges = [...natSet].sort((a, b) => a - b);
1053
+ const intSet = new Set([0, maxValue, -maxValue]);
1054
+ if (maxValue >= 1) {
1055
+ intSet.add(1);
1056
+ intSet.add(-1);
1057
+ }
1058
+ for (const x of decodedNums)
1059
+ if (Math.abs(x) <= ceiling)
1060
+ intSet.add(x);
1061
+ const intEdges = [...intSet].sort((a, b) => a - b);
1062
+ const strSet = new Set();
1063
+ collectStrings(rawParams, strSet);
1064
+ collectStrings(snapshot.context, strSet);
1065
+ const strings = [...strSet].sort();
1066
+ const fieldDomains = userInputs.map(([n, k]) => [
1067
+ n,
1068
+ enumerateVal(n, k.value(n), k, natEdges, intEdges, strings, maxValue, ceiling),
1069
+ ]);
1070
+ for (const [n, k] of r.parts.lists) {
1071
+ const sampleItem = enumerateVal(n, k.value(n), k, natEdges, intEdges, strings, maxValue, ceiling)[0] ?? k.empty();
1072
+ fieldDomains.push([n, [[], [sampleItem]]]);
1073
+ }
1074
+ for (const mp of plainCarriedMaps)
1075
+ fieldDomains.push([mp, [[], [0]]]);
1076
+ return cartesian(fieldDomains).map(combo => {
1077
+ if (eventField) {
1078
+ const { [eventField]: t, ...rest } = combo;
1079
+ return { type: typeof t === 'string' ? t : '', ...rest };
1080
+ }
1081
+ return { type: eventType, ...combo };
1082
+ });
1083
+ };
1084
+ const events = (snapshot) => {
1085
+ if (opts.events === undefined)
1086
+ return defaultEvents(snapshot);
1087
+ return typeof opts.events === 'function' ? [...opts.events(snapshot)] : [...opts.events];
1088
+ };
1089
+ const stateMatcher = (snapshot, stateKey) => {
1090
+ if (stateKey === '*')
1091
+ return true;
1092
+ if (!chartRef)
1093
+ return false;
1094
+ const regions = chartRef.regionFields();
1095
+ if (regions.length === 1 && regions[0].name === 'state') {
1096
+ const raw = snapshot.context[regions[0].field];
1097
+ const cur = typeof raw === 'string' ? raw : '';
1098
+ return cur === stateKey || cur.startsWith(`${stateKey}.`);
1099
+ }
1100
+ return regions.some(reg => {
1101
+ const raw = snapshot.context[reg.field];
1102
+ const cur = `${reg.name}.${typeof raw === 'string' ? raw : ''}`;
1103
+ return cur === stateKey || cur.startsWith(`${stateKey}.`);
1104
+ });
1105
+ };
1106
+ const options = { events, serializeState: (s) => serializeState(s), stateMatcher };
1107
+ return {
1108
+ config: { name: r.name },
1109
+ getInitialSnapshot,
1110
+ transition,
1111
+ getPersistedSnapshot,
1112
+ restoreSnapshot,
1113
+ events,
1114
+ serializeState: options.serializeState,
1115
+ stateMatcher,
1116
+ options,
1117
+ };
1118
+ }
1119
+ // Convert a verdict's or search()'s counterexample run into XState event objects ready for model.getPathsFromEvents(events).
1120
+ export function runToEvents(ruleOrChart, run, opts = {}) {
1121
+ const isChart = ruleOrChart instanceof Chart;
1122
+ const r = isChart ? ruleOrChart.rule : ruleOrChart;
1123
+ const m = r.machine;
1124
+ const trace = Array.isArray(run) ? run : run?.trace;
1125
+ if (!Array.isArray(trace))
1126
+ throw new Error(`${r.name}: runToEvents expects a verdict/search run ({trace: [...]}) or a trace array`);
1127
+ const { field: eventField } = resolveEventField(r, isChart, opts.eventField);
1128
+ const eventType = opts.eventType ?? 'step';
1129
+ const listNames = new Set(r.parts.lists.map(([n]) => n));
1130
+ const listLenNames = new Set([...listNames].map(n => `${n}_len`));
1131
+ const listCarriedMaps = new Set(r.parts.lists.flatMap(([n, k, fs]) => [...k.vars(n), ...Object.keys(fs).map(f => `${n}$${f}`)]));
1132
+ const plainCarriedMaps = (m.inputMaps ?? []).filter(mp => !listCarriedMaps.has(mp));
1133
+ const userInputs = r.parts.inputs.filter(([n]) => !listLenNames.has(n));
1134
+ const readCell = (rawMap, key) => {
1135
+ if (rawMap instanceof Map)
1136
+ return Number(rawMap.get(key) ?? 0);
1137
+ if (rawMap && typeof rawMap === 'object')
1138
+ return Number(rawMap[String(key)] ?? 0);
1139
+ return 0;
1140
+ };
1141
+ return trace.map(step => {
1142
+ const vars = {};
1143
+ for (const [k, v] of Object.entries(step))
1144
+ if (typeof v === 'number')
1145
+ vars[k] = v;
1146
+ const decoded = {};
1147
+ for (const [n, k] of userInputs) {
1148
+ const val = k.value(n);
1149
+ if (val instanceof Choice && typeof step[n] === 'string') {
1150
+ decoded[n] = step[n];
1151
+ continue;
1152
+ }
1153
+ if (val instanceof Str && typeof step[n] === 'string') {
1154
+ decoded[n] = step[n];
1155
+ continue;
1156
+ }
1157
+ for (const part of k.vars(n))
1158
+ if (vars[part] === undefined)
1159
+ vars[part] = 0;
1160
+ try {
1161
+ decoded[n] = k.decode(n, vars);
1162
+ }
1163
+ catch (e) {
1164
+ if (val instanceof Str)
1165
+ decoded[n] = `s${vars[n] ?? 0}`;
1166
+ else
1167
+ throw e;
1168
+ }
1169
+ }
1170
+ for (const [n, k] of r.parts.lists) {
1171
+ const len = Number(step[`${n}_len`] ?? 0);
1172
+ const parts = k.vars(n);
1173
+ decoded[n] = Array.from({ length: len }, (_, i) => k.decode(n, Object.fromEntries(parts.map(p => [p, readCell(step[p], i)]))));
1174
+ }
1175
+ for (const mp of plainCarriedMaps) {
1176
+ const rawMap = step[mp];
1177
+ if (rawMap instanceof Map) {
1178
+ decoded[mp] = Object.fromEntries([...rawMap.entries()].sort((a, b) => Number(a[0]) - Number(b[0])).map(([k, v]) => [String(k), Number(v)]));
1179
+ }
1180
+ else if (rawMap && typeof rawMap === 'object') {
1181
+ decoded[mp] = Object.fromEntries(Object.entries(rawMap).sort((a, b) => Number(a[0]) - Number(b[0])).map(([k, v]) => [k, Number(v)]));
1182
+ }
1183
+ }
1184
+ if (eventField) {
1185
+ const { [eventField]: t, ...rest } = decoded;
1186
+ return { type: String(t), ...rest };
1187
+ }
1188
+ return { type: eventType, ...decoded };
1189
+ });
1190
+ }
package/docs/xstate.md ADDED
@@ -0,0 +1,113 @@
1
+ # With XState and `@xstate/graph`
2
+
3
+ Formal verification proves the logic matches its specification; model-based testing checks that the real application
4
+ actually follows it in the world. `gdp-wired/xstate` connects both sides without adding `xstate` or `@xstate/graph` to
5
+ `gdp-wired`'s runtime dependencies.
6
+
7
+ ## 1. The default: write the rule or chart, prove it, and ship it
8
+
9
+ In TypeScript, write stateful logic directly with `rule()` or `chart()`, prove its laws (`proveRule`, `proveSteps`,
10
+ `chart.prove`, with `{from: 'any'}` wherever state is reloaded), keep each broken twin and assert it is refuted, and run
11
+ the proven rule itself (`rule.interpreter()` or `rule.compiled()`). That way the code making decisions cannot drift
12
+ from the model that was proven.
13
+
14
+ You do not need XState in your application to use `@xstate/graph` for model-based testing (section 3).
15
+
16
+ ## 2. An existing XState machine: `fromXState`, `conforms`, and extraction
17
+
18
+ When you already ship an XState v5 (or v4) machine, `fromXState(machine, {guards, actions})` translates it into a
19
+ `chart()` whose laws the kernel proves; `conforms(chart, machine, createActor)` runs XState's own actor beside the
20
+ compiled rule on random events so any mismatch in a guard or action shows up as a concrete run (`examples/xstate.ts`):
21
+
22
+ ```ts
23
+ import {createActor} from 'xstate'
24
+ import {conforms, fromXState} from 'gdp-wired/xstate'
25
+
26
+ const c = fromXState(orderMachine, {
27
+ guards: {canRetry: ({retries}) => retries.lt(2), unshipped: env => env.in('active.paid')},
28
+ actions: {count: ({retries}) => ({retries: retries.plus(1)}), notify: null},
29
+ })
30
+ c.check()
31
+ c.prove([c.law('the retries stay within 2', ({retries}) => retries.atMost(2))])
32
+ conforms(c, orderMachine, createActor, {runs: 300, depth: 16})
33
+ ```
34
+
35
+ - **Read:** nested states, parallel roots, deep history, final states, targetless (internal) transitions, named guards
36
+ and actions with params, `invoke` `onDone`/`onError` and single `after` timers (as external events, once per visit),
37
+ and `always` / context-writing `entry`/`exit` folded into XState's macrostep. What a chart cannot run the same way,
38
+ and any key `fromXState` does not read, is refused when built with the reason.
39
+ - **Extraction (only when asked):** `extractXState('./order.ts')` (`gdp-wired/extract`) reads guards and actions from
40
+ the machine's source and runs `conforms` against the project's own `xstate`.
41
+ - **CLI law comments on XState files:** as of 0.57, `npx gdp-wired-cli check order.ts` checks `// gdp: law` comments on
42
+ the extracted model only and reports them as `unknown` / `unchecked` (exit `2`), because XState extraction checks
43
+ conformance via `conforms` rather than native parameter-capture source-law replay. Prefer `fromXState` + `prove` +
44
+ `conforms`, or prove a native `chart()` / `rule()`.
45
+
46
+ ## 3. Model-based testing with `@xstate/graph`
47
+
48
+ `toLogic(ruleOrChart, {params?, events?, maxValue?})` wraps any proven `rule()` or `chart()` as XState v5 `ActorLogic`
49
+ (`getInitialSnapshot`, `transition`, `getPersistedSnapshot`, `restoreSnapshot`). Each step runs the proven rule via
50
+ `rule.interpreter()` (copied states — never the in-place `rule.compiled()` state), refused requests leave the snapshot
51
+ unchanged, `serializeState` serializes scalars, maps (key-order independent, default entries normalized) and logs
52
+ canonically, and the default `events(snapshot)` enumerates each input kind (`oneOf` choices, booleans, and for naturals
53
+ `0`, `1`, values read from the state/params, and `maxValue`).
54
+
55
+ Pass the logic and `logic.options` to `@xstate/graph`'s `TestModel` (in `@xstate/graph` 3.0.4, `new TestModel(logic,
56
+ options)` accepts any `ActorLogic`, while `createTestModel(machine, options)` is for `StateMachine`s) to generate paths
57
+ from the proven rule and drive the real application (`examples/xstate-mbt.ts`):
58
+
59
+ ```ts
60
+ import {TestModel} from '@xstate/graph'
61
+ import {proveRule} from 'gdp-wired'
62
+ import {runToEvents, toLogic} from 'gdp-wired/xstate'
63
+
64
+ proveRule(wallet, [walletCovered], {from: 'any'}) // proven, checked
65
+
66
+ const logic = toLogic(wallet, {maxValue: 2})
67
+ const model = new TestModel(logic, logic.options)
68
+ for (const path of model.getShortestPaths()) {
69
+ await model.testPath(path, {
70
+ states: {'*': snap => expectAppMatches(snap.context)}, // check UI / DB / service state
71
+ events: {
72
+ 'xstate.init': () => resetApp(),
73
+ topUp: ({event}) => app.topUp((event as {amount: number}).amount),
74
+ reserve: ({event}) => app.reserve((event as {id: number, amount: number}).id, (event as {amount: number}).amount),
75
+ release: ({event}) => app.release((event as {id: number}).id),
76
+ spend: ({event}) => app.spend((event as {id: number}).id),
77
+ },
78
+ })
79
+ }
80
+ ```
81
+
82
+ ### Counterexamples as regression paths (`runToEvents`)
83
+
84
+ `getShortestPaths()` covers every state reachable with the enumerated events (naturals bounded by `maxValue`, or the
85
+ `events` you pass) — not every reachable state of the rule; the proof covers the rest. To also exercise
86
+ rejected/ignored self-loops within that graph (such as an over-budget `reserve` that the proven rule leaves unchanged),
87
+ extend each shortest path with its outgoing transitions from `model.getAdjacencyMap()`, or turn a broken twin's
88
+ counterexample directly into a regression path with `runToEvents`.
89
+
90
+ `runToEvents(ruleOrChart, run)` turns a refuting run from `proveRule`, `proveSteps`, `chart.prove`, `minimizeRun`, or
91
+ `search` into the XState event objects `{type, ...payload}` ready for `getPathsFromEvents`:
92
+
93
+ ```ts
94
+ // From a broken rule twin -> regression path on the proven rule's model against the real app:
95
+ const broken = proveRule(uncheckedWallet, [uncheckedCovered])
96
+ const [regression] = model.getPathsFromEvents(runToEvents(uncheckedWallet, broken.run!))
97
+ await model.testPath(regression!, walletHarness) // fails the buggy app, passes the fixed app
98
+
99
+ // From a broken XState variant -> replay directly on the real XState machine:
100
+ const v = brokenOrderChart.prove(laws, stepLaws)
101
+ const events = runToEvents(brokenOrderChart, v.run!) // [{type: 'PAY'}, ..., {type: 'REFUND'}]
102
+ const [path] = createTestModel(buggyOrderMachine).getPathsFromEvents(events)
103
+ // path.state.value === 'refunded' after {active: 'shipped'}
104
+ ```
105
+
106
+ ## 4. The division of labour
107
+
108
+ - **The proof (`proveRule`, `proveSteps`, `chart.prove`) covers the logic:** every reachable (or arbitrary `{from: 'any'}`)
109
+ state, every unbounded natural, every map key, every interleaving within the rule — with a kernel-checked certificate
110
+ that Lean checks again.
111
+ - **Model-based testing (`toLogic`, `runToEvents`, `@xstate/graph`) covers the app around it:** the UI wiring, database
112
+ transactions, serialization, HTTP handlers, and integration boundaries that sit outside the rule, checked along shortest
113
+ paths and proven counterexample regressions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.58.0",
3
+ "version": "0.59.1",
4
4
  "description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
5
5
  "keywords": [
6
6
  "verification",
@@ -198,6 +198,7 @@
198
198
  "docs/agent-consult.md",
199
199
  "docs/lean-aggregate.md",
200
200
  "docs/minimize.md",
201
+ "docs/xstate.md",
201
202
  "docs/agent-consult-workspace-check.md",
202
203
  "examples/agent-consult.json"
203
204
  ],
@@ -233,6 +234,7 @@
233
234
  "@reduxjs/toolkit": "2.13.0",
234
235
  "@types/bun": "1.3.1",
235
236
  "@webgpu/types": "0.1.66",
237
+ "@xstate/graph": "3.0.4",
236
238
  "effect": "4.0.7",
237
239
  "effect3": "npm:effect@3.22.4",
238
240
  "oxlint": "1.88.0",