gdp-wired 0.47.0 → 0.48.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 (170) hide show
  1. package/README.md +15 -4
  2. package/dist/core/carry.d.ts +15 -0
  3. package/dist/core/carry.js +651 -0
  4. package/dist/core/cli.d.ts +3 -1
  5. package/dist/core/cli.js +28 -8
  6. package/dist/core/count-cases.d.ts +24 -0
  7. package/dist/core/count-cases.js +320 -0
  8. package/dist/core/count-cert-grow.d.ts +4 -0
  9. package/dist/core/count-cert-grow.js +37 -0
  10. package/dist/core/count-cert-transport.d.ts +3 -0
  11. package/dist/core/count-cert-transport.js +58 -0
  12. package/dist/core/count-completion.d.ts +9 -0
  13. package/dist/core/count-completion.js +27 -0
  14. package/dist/core/count-cubes.d.ts +8 -0
  15. package/dist/core/count-cubes.js +69 -0
  16. package/dist/core/count-demand.d.ts +37 -0
  17. package/dist/core/count-demand.js +361 -0
  18. package/dist/core/count-facts.d.ts +52 -0
  19. package/dist/core/count-facts.js +247 -0
  20. package/dist/core/count-focus-proof.d.ts +8 -0
  21. package/dist/core/count-focus-proof.js +140 -0
  22. package/dist/core/count-focused.d.ts +22 -0
  23. package/dist/core/count-focused.js +676 -0
  24. package/dist/core/count-ranges.d.ts +5 -0
  25. package/dist/core/count-ranges.js +65 -0
  26. package/dist/core/count-recovery/action-guard.d.ts +5 -0
  27. package/dist/core/count-recovery/action-guard.js +51 -0
  28. package/dist/core/count-recovery/boolean-core.d.ts +16 -0
  29. package/dist/core/count-recovery/boolean-core.js +258 -0
  30. package/dist/core/count-recovery/carried-case.d.ts +2 -0
  31. package/dist/core/count-recovery/carried-case.js +24 -0
  32. package/dist/core/count-recovery/conditional-check-cache.d.ts +23 -0
  33. package/dist/core/count-recovery/conditional-check-cache.js +130 -0
  34. package/dist/core/count-recovery/conditional-cuts.d.ts +6 -0
  35. package/dist/core/count-recovery/conditional-cuts.js +318 -0
  36. package/dist/core/count-recovery/conditional-proof.d.ts +19 -0
  37. package/dist/core/count-recovery/conditional-proof.js +306 -0
  38. package/dist/core/count-recovery/derivability-closure.d.ts +14 -0
  39. package/dist/core/count-recovery/derivability-closure.js +533 -0
  40. package/dist/core/count-recovery/empty-count-source.d.ts +2 -0
  41. package/dist/core/count-recovery/empty-count-source.js +40 -0
  42. package/dist/core/count-recovery/field-bound-lemmas.d.ts +23 -0
  43. package/dist/core/count-recovery/field-bound-lemmas.js +640 -0
  44. package/dist/core/count-recovery/field-case.d.ts +5 -0
  45. package/dist/core/count-recovery/field-case.js +89 -0
  46. package/dist/core/count-recovery/field-demand.d.ts +46 -0
  47. package/dist/core/count-recovery/field-demand.js +47 -0
  48. package/dist/core/count-recovery/field-only.d.ts +3 -0
  49. package/dist/core/count-recovery/field-only.js +18 -0
  50. package/dist/core/count-recovery/fold-path.d.ts +6 -0
  51. package/dist/core/count-recovery/fold-path.js +35 -0
  52. package/dist/core/count-recovery/frame-lemmas.d.ts +9 -0
  53. package/dist/core/count-recovery/frame-lemmas.js +120 -0
  54. package/dist/core/count-recovery/guard-cases.d.ts +12 -0
  55. package/dist/core/count-recovery/guard-cases.js +138 -0
  56. package/dist/core/count-recovery/key-closure.d.ts +14 -0
  57. package/dist/core/count-recovery/key-closure.js +62 -0
  58. package/dist/core/count-recovery/leaf-allowance.d.ts +4 -0
  59. package/dist/core/count-recovery/leaf-allowance.js +7 -0
  60. package/dist/core/count-recovery/lift-count-proxies.d.ts +6 -0
  61. package/dist/core/count-recovery/lift-count-proxies.js +175 -0
  62. package/dist/core/count-recovery/live-dependencies.d.ts +6 -0
  63. package/dist/core/count-recovery/live-dependencies.js +76 -0
  64. package/dist/core/count-recovery/member-inclusions.d.ts +11 -0
  65. package/dist/core/count-recovery/member-inclusions.js +168 -0
  66. package/dist/core/count-recovery/member-premises.d.ts +29 -0
  67. package/dist/core/count-recovery/member-premises.js +114 -0
  68. package/dist/core/count-recovery/natural-cases.d.ts +6 -0
  69. package/dist/core/count-recovery/natural-cases.js +59 -0
  70. package/dist/core/count-recovery/ops.d.ts +6 -0
  71. package/dist/core/count-recovery/ops.js +8 -0
  72. package/dist/core/count-recovery/pre-state-source.d.ts +8 -0
  73. package/dist/core/count-recovery/pre-state-source.js +18 -0
  74. package/dist/core/count-recovery/rebase-path.d.ts +9 -0
  75. package/dist/core/count-recovery/rebase-path.js +70 -0
  76. package/dist/core/count-recovery/rename-proof.d.ts +2 -0
  77. package/dist/core/count-recovery/rename-proof.js +102 -0
  78. package/dist/core/count-recovery/row-cases.d.ts +16 -0
  79. package/dist/core/count-recovery/row-cases.js +291 -0
  80. package/dist/core/count-recovery/scalar-guards.d.ts +7 -0
  81. package/dist/core/count-recovery/scalar-guards.js +291 -0
  82. package/dist/core/count-recovery/source-memo.d.ts +12 -0
  83. package/dist/core/count-recovery/source-memo.js +67 -0
  84. package/dist/core/count-select.d.ts +16 -0
  85. package/dist/core/count-select.js +24 -0
  86. package/dist/core/count-support.d.ts +598 -0
  87. package/dist/core/count-support.js +2080 -0
  88. package/dist/core/count-unions.d.ts +2 -0
  89. package/dist/core/count-unions.js +139 -0
  90. package/dist/core/count-witness-flags.d.ts +9 -0
  91. package/dist/core/count-witness-flags.js +37 -0
  92. package/dist/core/count-write-frames.d.ts +12 -0
  93. package/dist/core/count-write-frames.js +206 -0
  94. package/dist/core/counts.d.ts +20 -2
  95. package/dist/core/counts.js +807 -156
  96. package/dist/core/dsl.d.ts +50 -6
  97. package/dist/core/dsl.js +307 -65
  98. package/dist/core/effect.js +8 -1
  99. package/dist/core/exists.d.ts +1 -1
  100. package/dist/core/exists.js +80 -15
  101. package/dist/core/extract-check.d.ts +7 -1
  102. package/dist/core/extract-check.js +130 -13
  103. package/dist/core/extract-read.d.ts +22 -8
  104. package/dist/core/extract-read.js +29 -11
  105. package/dist/core/extract-shapes.js +122 -41
  106. package/dist/core/extract-standalone.js +53 -9
  107. package/dist/core/extract.js +9 -3
  108. package/dist/core/field-laws.d.ts +2 -0
  109. package/dist/core/field-laws.js +100 -0
  110. package/dist/core/finite-frontiers.d.ts +5 -0
  111. package/dist/core/finite-frontiers.js +116 -0
  112. package/dist/core/finite-houdini.d.ts +52 -0
  113. package/dist/core/finite-houdini.js +460 -0
  114. package/dist/core/finite-model.d.ts +13 -0
  115. package/dist/core/finite-model.js +68 -0
  116. package/dist/core/finite-tiny.d.ts +72 -0
  117. package/dist/core/finite-tiny.js +1052 -0
  118. package/dist/core/infer.d.ts +1 -1
  119. package/dist/core/infer.js +32 -9
  120. package/dist/core/laws.d.ts +2 -1
  121. package/dist/core/laws.js +47 -14
  122. package/dist/core/lemma-cuts.d.ts +38 -0
  123. package/dist/core/lemma-cuts.js +365 -0
  124. package/dist/core/machine.d.ts +39 -2
  125. package/dist/core/machine.js +240 -35
  126. package/dist/core/mutate.d.ts +55 -0
  127. package/dist/core/mutate.js +210 -0
  128. package/dist/core/native-domain.d.ts +6 -0
  129. package/dist/core/native-domain.js +114 -0
  130. package/dist/core/native-law.d.ts +3 -0
  131. package/dist/core/native-law.js +174 -0
  132. package/dist/core/quorum-laws.d.ts +5 -0
  133. package/dist/core/quorum-laws.js +239 -0
  134. package/dist/core/relational.js +10 -2
  135. package/dist/core/relevance.d.ts +4 -0
  136. package/dist/core/relevance.js +79 -0
  137. package/dist/core/runtime-wall.d.ts +3 -0
  138. package/dist/core/runtime-wall.js +4 -0
  139. package/dist/core/sample-step.d.ts +16 -0
  140. package/dist/core/sample-step.js +28 -0
  141. package/dist/core/source-check.d.ts +44 -0
  142. package/dist/core/source-check.js +126 -0
  143. package/dist/core/source-diagnostic.d.ts +1 -0
  144. package/dist/core/source-diagnostic.js +34 -0
  145. package/dist/core/support-budget.d.ts +2 -0
  146. package/dist/core/support-budget.js +6 -0
  147. package/dist/core/system.js +2 -0
  148. package/dist/core/wall.d.ts +6 -0
  149. package/dist/core/wall.js +23 -0
  150. package/dist/core/watch.js +4 -0
  151. package/dist/kernel/cdcl.d.ts +4 -0
  152. package/dist/kernel/cdcl.js +20 -5
  153. package/dist/kernel/kernel.d.ts +10 -0
  154. package/dist/kernel/kernel.js +56 -3
  155. package/dist/kernel/model-sequence.d.ts +2 -2
  156. package/dist/kernel/model-sequence.js +4 -3
  157. package/dist/kernel/model-values.d.ts +2 -0
  158. package/dist/kernel/model-values.js +60 -0
  159. package/dist/kernel/prove.d.ts +10 -0
  160. package/dist/kernel/prove.js +56 -8
  161. package/dist/kernel/prover-rows.d.ts +29 -0
  162. package/dist/kernel/prover-rows.js +114 -0
  163. package/dist/lean-kernel/emit.d.ts +39 -2
  164. package/dist/lean-kernel/emit.js +136 -24
  165. package/dist/lean-kernel/lean-terms.d.ts +1 -0
  166. package/dist/lean-kernel/lean-terms.js +13 -5
  167. package/dist/lean-kernel/library.js +4 -0
  168. package/dist/lean-kernel/qalpha.d.ts +7 -0
  169. package/dist/lean-kernel/qalpha.js +40 -0
  170. package/package.json +5 -1
@@ -0,0 +1,239 @@
1
+ // Untrusted quorum candidates read from a stored row, a majority assumption, and
2
+ // an action's quantified guard. No protocol vocabulary or facts live here.
3
+ import { all, any, atMost, get, ite, less, n, not, plus, same, times, walk, x } from "./machine.js";
4
+ import { substC, substE } from "../kernel/kernel.js";
5
+ const text = (t) => JSON.stringify(t);
6
+ const eq = (a, b) => text(a) === text(b);
7
+ const conjs = (c) => c.op === 'and' ? c.xs.flatMap(conjs) : [c];
8
+ const atoms = (c) => c.op === 'and' || c.op === 'or' ? c.xs.flatMap(atoms) : c.op === 'not' ? atoms(c.x) : [c];
9
+ const vars = (t) => { const out = new Set(); walk(t, o => { if (o.op === 'var')
10
+ out.add(o.name); }); return out; };
11
+ const flagsIn = (t) => { const out = new Set(); walk(t, o => { if (o.op === 'flag')
12
+ out.add(o.name); }); return out; };
13
+ const sub = (names) => ({ vars: names, maps: {}, flags: {} });
14
+ const indicator = (c) => ite(c, n(1), n(0));
15
+ const bodyOf = (d) => d.body.op === 'if' && eq(d.body.then, n(1)) && eq(d.body.else, n(0)) ? d.body.c : undefined;
16
+ const packed = (base, a, b) => plus(times(base, a), b);
17
+ const contains = (t, part) => { let found = false; walk(t, o => { if (eq(o, part))
18
+ found = true; }); return found; };
19
+ // Replace the value an action stores BEFORE renaming the request's row. The
20
+ // fresh target key denotes any stored occurrence of that value, not the writer.
21
+ const replace = (t, values) => {
22
+ for (const [from, to] of values)
23
+ if (eq(t, from))
24
+ return to;
25
+ if (Array.isArray(t))
26
+ return t.map(v => replace(v, values));
27
+ if (t && typeof t === 'object')
28
+ return Object.fromEntries(Object.entries(t).map(([k, v]) => [k, replace(v, values)]));
29
+ return t;
30
+ };
31
+ // A positive row cell at base*request + member, in a 0/1 count.
32
+ function rowOf(m, name) {
33
+ const d = m.counts?.[name], body = d && bodyOf(d);
34
+ if (!d || !body || (body.op !== '=' && body.op !== '<='))
35
+ return undefined;
36
+ const cell = body.op === '=' && eq(body.b, n(1)) ? body.a : body.op === '<=' && eq(body.a, n(1)) ? body.b : undefined;
37
+ if (cell?.op !== 'get' || !(cell.map in (m.maps ?? {})))
38
+ return undefined;
39
+ const k = cell.key;
40
+ if (k.op !== 'add' || k.a.op !== 'mul' || k.a.k <= 1 || k.a.a.op !== 'var' || k.b.op !== 'var' || k.b.name !== d.key || !m.inputs.includes(k.a.a.name))
41
+ return undefined;
42
+ if ([d.j, ...m.inputs].some(v => vars(d.below).has(v)))
43
+ return undefined;
44
+ return { name, map: cell.map, input: k.a.a.name, base: k.a.k, below: d.below, key: d.key, body };
45
+ }
46
+ export function quorumLaws(m) {
47
+ const counts = {}, laws = [];
48
+ if (!m.assume || !m.counts || !m.inputMaps?.length)
49
+ return { counts, laws };
50
+ const names = new Set([...vars(m), ...Object.keys(m.counts), ...Object.keys(m.maps ?? {}), ...m.inputs, ...m.params, ...Object.keys(m.state)]);
51
+ const fresh = (stem) => { let name = stem; while (names.has(name))
52
+ name += '$'; names.add(name); return name; };
53
+ const a = fresh('a$quorum'), b = fresh('b$quorum'), u = fresh('u$quorum'), w = fresh('w$quorum');
54
+ const j = fresh('row$quorum'), lo = fresh('other$quorum'), key = fresh('member$quorum');
55
+ const fs = m.step.flags ?? {}, assumptions = atoms(m.assume);
56
+ const rows = new Map();
57
+ for (const g of assumptions) {
58
+ if (g.op !== '<' || g.a.op !== 'get' || g.b.op !== 'mul' || g.b.k !== 2 || g.b.a.op !== 'get')
59
+ continue;
60
+ const row = rowOf(m, g.a.map), d = m.counts[g.b.a.map], body = d && bodyOf(d);
61
+ if (!row || !d || !body || !eq(d.below, row.below) || vars([d.body, d.below]).has(d.j))
62
+ continue;
63
+ const used = new Set();
64
+ walk(body, o => { if (o.op === 'get')
65
+ used.add(o.map); });
66
+ if (used.size !== 1 || !m.inputMaps.includes([...used][0]))
67
+ continue;
68
+ let entry = rows.get(row.name);
69
+ if (!entry)
70
+ rows.set(row.name, (entry = { row, sets: new Set() }));
71
+ entry.sets.add(g.b.a.map);
72
+ }
73
+ // Fast no-op on machines with parameter majorities rather than stored rows.
74
+ for (const { row, sets } of rows.values()) {
75
+ const rowBody = substC(row.body, sub({ [row.input]: x(j), [row.key]: x(key) }));
76
+ const domain = (v) => less(x(v), row.below);
77
+ const registry = new Map();
78
+ const normal = (c) => c.op === 'and' ? text(['and', conjs(c).map(normal).sort()]) : text(c);
79
+ const count = (body, pair, label) => {
80
+ const id = normal(body), old = registry.get(id);
81
+ if (old)
82
+ return (a, b) => get(old.name, old.pair ? packed(row.base, x(old.swap ? b : a), x(old.swap ? a : b)) : x(a));
83
+ const name = fresh(`${row.name}$${label}`);
84
+ counts[name] = { j, key, below: row.below, body: indicator(body), ...(pair ? { lo, base: row.base } : {}) };
85
+ registry.set(id, { name, pair, swap: false });
86
+ if (pair) {
87
+ const swapped = normal(substC(body, sub({ [j]: x(lo), [lo]: x(j) })));
88
+ if (!registry.has(swapped))
89
+ registry.set(swapped, { name, pair, swap: true });
90
+ }
91
+ return (a, b) => get(name, pair ? packed(row.base, x(a), x(b)) : x(a));
92
+ };
93
+ let size;
94
+ const rowSize = (a) => (size ??= count(rowBody, false, 'row'))(a);
95
+ const noQuorums = [];
96
+ let flagCount = 0;
97
+ for (const [flag, q] of Object.entries(fs)) {
98
+ if (flagCount >= 2 || q.op !== 'all' || q.keys?.length || q.c.op !== 'or' || q.c.xs.length !== 2)
99
+ continue;
100
+ const neg = q.c.xs.find(c => c.op === 'not'), rest = q.c.xs.find(c => c !== neg);
101
+ if (neg?.op !== 'not' || !rest)
102
+ continue;
103
+ const set = [...sets].find(name => {
104
+ const d = m.counts[name], body = bodyOf(d);
105
+ return eq(substC(body, sub({ [d.key]: x(q.key) })), neg.x);
106
+ });
107
+ const parts = conjs(rest);
108
+ if (!set || !parts.length || parts.length > 3)
109
+ continue;
110
+ const actions = Object.entries(fs).filter(([, c]) => c.op !== 'all' && flagsIn(c).has(flag));
111
+ if (!actions.length)
112
+ continue;
113
+ flagCount++;
114
+ const values = [];
115
+ for (const [action] of actions)
116
+ for (const [map, update] of Object.entries(m.step.maps ?? {})) {
117
+ const visit = (value) => {
118
+ if (value.op !== 'if')
119
+ return;
120
+ const atRow = 'each' in update ? conjs(value.c).some(c => eq(c, same(x(update.each), x(row.input))) || eq(c, same(x(row.input), x(update.each)))) : eq(update.key, x(row.input));
121
+ if (atRow && flagsIn(value.c).has(action) && value.then.op !== 'const' && value.then.op !== 'var' && value.then.op !== 'if' && !values.some(([from]) => eq(from, value.then)))
122
+ values.push([value.then, get(map, x(lo))]);
123
+ visit(value.then);
124
+ visit(value.else);
125
+ };
126
+ visit(update.value);
127
+ }
128
+ for (let bits = 1; bits < 1 << parts.length && laws.length < 32; bits++) {
129
+ const selected = parts.filter((_, i) => bits >> i & 1);
130
+ const lifted = substC(replace(all(...selected), values), sub({ [row.input]: x(j), [q.key]: x(key) }));
131
+ if (m.inputs.some(i => vars(lifted).has(i)) || [...flagsIn(lifted)].length)
132
+ continue;
133
+ const pair = vars(lifted).has(lo), c = count(all(rowBody, ...conjs(lifted)), pair, `${flag}$${bits}`);
134
+ const atom = (a, b) => atMost(times(2, c(a, b)), rowSize(a));
135
+ laws.push({ name: `${row.name}: no quorum ${flag}/${bits}`, forall: a, ...(pair ? { keys: [b] } : {}), holds: any(not(all(domain(a), ...(pair ? [domain(b)] : []))), atom(a, b)) });
136
+ if (!pair)
137
+ noQuorums.push(a => atom(a));
138
+ }
139
+ }
140
+ // A carried set stored into this row licenses replacing that set by row b
141
+ // in its action guard, and the request row by a. Half witnesses retain the
142
+ // assumption atoms that constrain them; no arithmetic identity is trusted.
143
+ for (const [action, guard] of Object.entries(fs)) {
144
+ if (guard.op === 'all')
145
+ continue;
146
+ const update = m.step.maps?.[row.map];
147
+ if (!update || !('each' in update))
148
+ continue;
149
+ for (const [set, d] of Object.entries(m.counts)) {
150
+ const setBody = bodyOf(d);
151
+ if (!setBody || !eq(d.below, row.below))
152
+ continue;
153
+ const used = new Set();
154
+ walk(setBody, o => { if (o.op === 'get' && m.inputMaps.includes(o.map))
155
+ used.add(o.map); });
156
+ if (used.size !== 1)
157
+ continue;
158
+ const carried = [...used][0], shifted = substE(d.body, sub({ [d.key]: { op: 'sub', a: x(update.each), b: times(row.base, x(row.input)) } }));
159
+ let stores = false;
160
+ walk(update.value, o => {
161
+ if (o.op === 'if' && flagsIn(o.c).has(action) && eq(o.then, shifted))
162
+ stores = true;
163
+ // Boolean maps lower an if-tree to disjunctive membership clauses.
164
+ if (o.op === 'and' && shifted.op === 'if') {
165
+ const parts = conjs(o);
166
+ if (parts.some(c => c.op === 'flag' && c.name === action) && parts.some(c => eq(c, shifted.c)))
167
+ stores = true;
168
+ }
169
+ });
170
+ if (!stores)
171
+ continue;
172
+ const mapped = new Map();
173
+ // Lift every matching set-vs-row count the action reads. 0/1 membership
174
+ // substitutions are simplified so the reversed difference shares a count.
175
+ const simplify = (c) => {
176
+ if (c.op === 'and' || c.op === 'or')
177
+ return { ...c, xs: c.xs.map(simplify) };
178
+ if (c.op === 'not')
179
+ return not(simplify(c.x));
180
+ if (c.op === '=' && c.a.op === 'if' && eq(c.a.then, n(1)) && eq(c.a.else, n(0)) && eq(c.b, n(1)))
181
+ return simplify(c.a.c);
182
+ if (c.op === '<=' && eq(c.a, n(1)) && c.b.op === 'if' && eq(c.b.then, n(1)) && eq(c.b.else, n(0)))
183
+ return simplify(c.b.c);
184
+ return c;
185
+ };
186
+ for (const [name, decl] of Object.entries(m.counts)) {
187
+ const body = bodyOf(decl);
188
+ if (!body || !eq(decl.below, row.below) || vars(decl.body).has(decl.j))
189
+ continue;
190
+ const lifted = simplify(substC(body, { vars: { [row.input]: x(j), [decl.key]: x(key) }, maps: { [carried]: at => indicator(substC(row.body, sub({ [row.input]: x(lo), [row.key]: at }))) }, flags: {} }));
191
+ if (m.inputs.some(i => vars(lifted).has(i)) || contains(lifted, { op: 'get', map: carried }) || flagsIn(lifted).size)
192
+ continue;
193
+ let request = false;
194
+ walk(lifted, o => { if (o.op === 'get' && m.inputMaps.includes(o.map))
195
+ request = true; });
196
+ if (request)
197
+ continue;
198
+ if (eq(normal(lifted), normal(rowBody)))
199
+ mapped.set(name, aa => rowSize(aa));
200
+ else if (eq(normal(lifted), normal(substC(rowBody, sub({ [j]: x(lo) })))))
201
+ mapped.set(name, (_aa, bb) => rowSize(bb));
202
+ else if (vars(lifted).has(j) && vars(lifted).has(lo))
203
+ mapped.set(name, count(lifted, true, `rows$${name}`));
204
+ }
205
+ const comparisons = conjs(guard).filter(c => ['<', '<='].includes(c.op) && [...mapped.keys()].some(name => contains(c, { op: 'get', map: name, key: n(0) })));
206
+ for (const comparison of comparisons) {
207
+ const free = [...vars(comparison)].filter(v => m.inputs.includes(v) && v !== row.input);
208
+ if (free.length > 2)
209
+ continue;
210
+ const varsSub = Object.fromEntries(free.map((v, i) => [v, x(i ? w : u)]));
211
+ const mapSub = Object.fromEntries([...mapped].map(([name, read]) => [name, () => read(a, b)]));
212
+ const translate = (c) => substC(c, { vars: varsSub, maps: mapSub, flags: {} });
213
+ const hyps = assumptions.filter(c => free.some(v => vars(c).has(v)) && [...vars(c)].every(v => free.includes(v) || m.params.includes(v)));
214
+ const lifted = translate(comparison), constraints = hyps.map(translate);
215
+ if ([lifted, ...constraints].some(c => m.inputs.some(i => vars(c).has(i))))
216
+ continue;
217
+ let leaks = false;
218
+ walk([lifted, constraints], o => { if (o.op === 'get' && (m.inputMaps.includes(o.map) || o.map in m.counts))
219
+ leaks = true; });
220
+ if (leaks)
221
+ continue;
222
+ const base = [not(all(domain(a), domain(b), ...constraints)), lifted];
223
+ const add = (suffix, extra) => { if (laws.length < 32)
224
+ laws.push({ name: `${row.name}: stored guard ${action}/${set}${suffix}`, forall: a, keys: [b, ...free.map((_, i) => i ? w : u)], holds: any(...base, ...extra) }); };
225
+ add('', []);
226
+ for (const [i, atom] of noQuorums.entries())
227
+ add(` or disabled/${i}`, [atom(a), atom(b)]);
228
+ }
229
+ }
230
+ }
231
+ }
232
+ const used = new Set();
233
+ walk(laws, o => { if (o.op === 'get')
234
+ used.add(o.map); });
235
+ for (const name of Object.keys(counts))
236
+ if (!used.has(name))
237
+ delete counts[name];
238
+ return { counts, laws };
239
+ }
@@ -26,6 +26,7 @@ import { Rule, Term, all, any, forall, nat, no, not, proveSteps, same, when, yes
26
26
  import { proveLaws, proveStepLaws } from "../kernel/prove.js";
27
27
  import { fromInterchange, toInterchange } from "../interchange/format.js";
28
28
  import { checkCertificate } from "../interchange/check.js";
29
+ import { inheritSource, translationVerdict } from "./source-check.js";
29
30
  const specOf = (r) => r.spec;
30
31
  const v = (name) => new Term({ op: 'var', name });
31
32
  // The names a side declares that are its own in the rule built (renamed): state and its parts, maps, lists, cells,
@@ -152,7 +153,10 @@ export function twoRuns(a, b = a, opts = {}) {
152
153
  return out;
153
154
  },
154
155
  };
155
- return new Rule(spec);
156
+ const out = new Rule(spec);
157
+ inheritSource(a, out);
158
+ inheritSource(b, out);
159
+ return out;
156
160
  }
157
161
  // A run's write kept only where it takes the request (else the value before it).
158
162
  function guarded(sd, key, w, go) {
@@ -231,6 +235,7 @@ export function isolation(r, o) {
231
235
  if ([...s.params, ...s.inputs].some(([n]) => n === tenant))
232
236
  throw new Error(`isolation: ${tenant} is a name of ${s.name} already (name the tenant's param: tenant)`);
233
237
  const base = new Rule({ ...s, params: [...s.params, [tenant, nat]] });
238
+ inheritSource(r, base);
234
239
  const all2 = [...s.params, ...s.inputs].map(([n]) => n);
235
240
  const p = twoRuns(base, base, { name: `${s.name}: isolation of ${typeof o.owner === 'string' ? o.owner : 'the owner'}`, shared: [...all2, tenant], stays: env => not(mine(env)), refusals: o.refusals });
236
241
  const maps = new Set(vw.maps), name = o.name ?? `what ${typeof o.owner === 'string' ? o.owner : 'a tenant'} B sees is the same whatever the others do`;
@@ -300,7 +305,7 @@ export function proveTwoRuns(l, opts = {}) {
300
305
  let helpers = [...l.helpers];
301
306
  for (let round = 0; helpers.length && round <= l.helpers.length; round++) {
302
307
  const v = proveSteps(l.rule, [...lifted, ...helpers, ...l.laws], l.stepLaws, { search: false });
303
- if (v.proven && v.checked)
308
+ if ((v.proven && v.checked) || v.kernelProven === true)
304
309
  return { ...v, found: { ...v.found, laws: [...v.found?.laws ?? [], ...helpers.map(h => ({ law: h, text: h.name }))] }, given: lifted };
305
310
  const drop = helpers.find(h => v.goal?.startsWith(h.name));
306
311
  if (!drop)
@@ -335,6 +340,9 @@ export function certify(r, laws, stepLaws = [], meta = {}) {
335
340
  return undefined;
336
341
  c = { kind: 'laws', machine: p.machine ?? m, laws: p.laws ?? given, proof: { instances: p.proof.instances, trees: p.proof.trees } };
337
342
  }
343
+ const validation = translationVerdict(r, [...laws, ...stepLaws], { proven: true, checked: true });
344
+ if (!validation.proven || !validation.checked)
345
+ return undefined;
338
346
  const doc = toInterchange(c, meta);
339
347
  return checkCertificate(fromInterchange(JSON.parse(JSON.stringify(doc)))).every(x => x.accepted) ? doc : undefined;
340
348
  }
@@ -0,0 +1,4 @@
1
+ import { type Law, type Machine } from './machine.js';
2
+ import { type Goal } from '../kernel/kernel.js';
3
+ export declare function relevantLaws(m: Machine, laws: Law[], target: Law, structural?: ReadonlySet<Law>): Law[][];
4
+ export declare function relevantGoals(goal: Goal): Goal[];
@@ -0,0 +1,79 @@
1
+ // Untrusted search ordering only: a smaller context cannot authorize a result.
2
+ // Trees found here are lifted to the original goal before the kernel sees them.
3
+ import { walkOnce } from "./machine.js";
4
+ import { canon, linOfE } from "./solver.js";
5
+ function footprint(value) {
6
+ const out = { vars: new Set(), maps: new Set(), cells: new Set() };
7
+ walkOnce(value, node => {
8
+ const o = node;
9
+ if (o.op === 'var')
10
+ out.vars.add(String(o.name));
11
+ if (o.op === 'get') {
12
+ out.maps.add(String(o.map));
13
+ const key = linOfE(o.key);
14
+ out.cells.add(JSON.stringify([o.map, key ? canon(key) : o.key]));
15
+ }
16
+ });
17
+ return out;
18
+ }
19
+ const overlap = (a, b) => [...a].filter(x => b.has(x)).length;
20
+ // Count definitions participate through their actual read maps. Binder names
21
+ // never create relevance merely because two independent laws spell them alike.
22
+ export function relevantLaws(m, laws, target, structural = new Set()) {
23
+ if (laws.length <= 12)
24
+ return [];
25
+ const ofLaw = (law) => {
26
+ const f = footprint(law.holds), bound = new Set([law.forall, ...(law.keys ?? []), ...(law.some ?? [])]);
27
+ for (const v of f.vars)
28
+ if (bound.has(v) || !Object.hasOwn(m.state, v))
29
+ f.vars.delete(v);
30
+ for (const mp of f.maps) {
31
+ const d = m.counts?.[mp];
32
+ if (d)
33
+ for (const read of footprint(d.body).maps)
34
+ f.maps.add(read);
35
+ }
36
+ return f;
37
+ };
38
+ const own = ofLaw(target);
39
+ const ranked = laws.map((law, i) => {
40
+ const f = ofLaw(law), shared = overlap(f.maps, own.maps), fresh = f.maps.size - shared;
41
+ const states = overlap(f.vars, own.vars);
42
+ const scalar = !f.maps.size && (states > 0 || !f.vars.size);
43
+ const simple = shared > 0 && !fresh && !law.keys?.length && !law.some?.length;
44
+ const score = law === target ? -10000 : (simple ? -200 : scalar ? -150 : structural.has(law) && (shared || states) ? -100 : shared ? -20 : 100) + fresh * 20 + (f.vars.size - states) * 2 + (law.keys?.length ?? 0);
45
+ return { law, i, score };
46
+ }).sort((a, b) => a.score - b.score || a.i - b.i);
47
+ return [12, 24].filter(cap => cap < laws.length).map(cap => {
48
+ const chosen = new Set(ranked.slice(0, cap).map(r => r.law));
49
+ chosen.add(target);
50
+ return laws.filter(l => chosen.has(l));
51
+ });
52
+ }
53
+ // Keep exact source hypotheses, in their original order, and the conclusion last.
54
+ // Scalar premises for any newly introduced witness accompany its selected cells.
55
+ export function relevantGoals(goal) {
56
+ if (goal.hyps.length < 24)
57
+ return [];
58
+ const fs = goal.hyps.map(footprint), root = fs.at(-1);
59
+ const ranked = fs.slice(0, -1).map((f, i) => {
60
+ const cells = overlap(f.cells, root.cells), maps = overlap(f.maps, root.maps), vars = overlap(f.vars, root.vars);
61
+ const fresh = f.vars.size - vars;
62
+ const score = i < 2 ? -10000 : cells ? -1000 - 10 * cells + fresh : maps ? -100 - maps + 4 * fresh : f.maps.size ? 100 + fresh : fresh ? 200 + fresh : -500;
63
+ return { i, score };
64
+ }).sort((a, b) => a.score - b.score || a.i - b.i);
65
+ const out = [], seen = new Set();
66
+ for (const cap of [16, 32, 64]) {
67
+ const selected = new Set(ranked.slice(0, cap).map(r => r.i));
68
+ const vars = new Set([...root.vars, ...[...selected].flatMap(i => [...fs[i].vars])]);
69
+ fs.slice(0, -1).forEach((f, i) => { if (!f.maps.size && [...f.vars].every(v => vars.has(v)))
70
+ selected.add(i); });
71
+ selected.add(goal.hyps.length - 1);
72
+ const ids = [...selected].sort((a, b) => a - b), key = ids.join(',');
73
+ if (ids.length >= goal.hyps.length || seen.has(key))
74
+ continue;
75
+ seen.add(key);
76
+ out.push({ name: goal.name, hyps: ids.map(i => goal.hyps[i]) });
77
+ }
78
+ return out;
79
+ }
@@ -0,0 +1,3 @@
1
+ export declare const runtimeWall: {
2
+ check?: (phase: string) => void;
3
+ };
@@ -0,0 +1,4 @@
1
+ // Dependency-free bridge for cooperative runtime cancellation. The wall module
2
+ // installs its checker; the interpreter stays usable without importing the
3
+ // proof engine (which itself imports the machine constructors).
4
+ export const runtimeWall = {};
@@ -0,0 +1,16 @@
1
+ import { type Machine, type Request, type State } from './machine.js';
2
+ type Env = Record<string, number>;
3
+ export declare function sampleStep(m: Machine, run?: {
4
+ init: (params: {
5
+ [x: string]: number;
6
+ }) => State;
7
+ queries: (params: {
8
+ [x: string]: number;
9
+ }, st: State, input: Request) => {
10
+ [x: string]: number;
11
+ };
12
+ step: (params: {
13
+ [x: string]: number;
14
+ }, given: State, input: Request) => State;
15
+ }): (params: Env, st: State, input: Request) => State | undefined;
16
+ export {};
@@ -0,0 +1,28 @@
1
+ // Hot random walks reuse the existing persistent compiled step. No request,
2
+ // random draw, sample order or work counter is skipped. Cold/unsupported machines
3
+ // keep the interpreter. A refused request returns undefined; other errors retain
4
+ // the interpreter's exception behavior (the sampler ends that trial).
5
+ import { carriedView, compileC, fastStep, interpret, numbersOf } from "./machine.js";
6
+ import { allowed } from "./watch.js";
7
+ export function sampleStep(m, run = interpret(m)) {
8
+ let calls = 0, step = run.step;
9
+ let accepts = (params, st, input) => allowed(m, run, params, st, input);
10
+ return (params, st, input) => {
11
+ if (++calls === 1000) {
12
+ const fast = fastStep(m);
13
+ if (fast) {
14
+ step = fast;
15
+ const flags = Object.entries(m.step.flags ?? {}).map(([name, c]) => [name, compileC(c, m)]);
16
+ const assume = m.assume && compileC(m.assume, m);
17
+ accepts = !assume ? () => true : (params, st, input) => {
18
+ const env = { ...params, ...numbersOf(input), ...run.queries(params, st, input) };
19
+ const view = carriedView(m, st, input, undefined, params);
20
+ for (const [name, f] of flags)
21
+ env[`?${name}`] = f(env, view) ? 1 : 0;
22
+ return assume(env, view);
23
+ };
24
+ }
25
+ }
26
+ return accepts(params, st, input) ? step(params, st, input) : undefined;
27
+ };
28
+ }
@@ -0,0 +1,44 @@
1
+ export type Translation = 'exhaustive' | 'sampled' | 'unchecked' | 'error';
2
+ export type NativeObservation = {
3
+ where: string;
4
+ method?: string;
5
+ before: unknown;
6
+ after: unknown;
7
+ params: Record<string, unknown>;
8
+ inputs: Record<string, unknown>;
9
+ bindings: Record<string, unknown>;
10
+ args: unknown[];
11
+ result: unknown;
12
+ failed: boolean;
13
+ legacyResult?: boolean;
14
+ };
15
+ export type NativeJournal = {
16
+ enabled: boolean;
17
+ complete: boolean;
18
+ scope: 'exhaustive' | 'sampled';
19
+ reason?: string;
20
+ observations: NativeObservation[];
21
+ };
22
+ export type TranslationFields = {
23
+ translation?: Translation;
24
+ translationChecks?: number;
25
+ translationWitness?: NativeObservation;
26
+ kernelProven?: boolean;
27
+ };
28
+ export declare function inheritSource(from: object, to: object, transparent?: boolean): void;
29
+ export declare function rememberNative(e: object, journal: NativeJournal): void;
30
+ export declare function attachSource(rule: object, e: object, generated: object[]): void;
31
+ export declare function attachNativeLaw(rule: object, law: object, name: string, method: string | undefined, evaluate: (observation: NativeObservation) => boolean): void;
32
+ type TranslatedVerdict<V> = Omit<V, 'proven' | 'checked'> & {
33
+ proven: boolean;
34
+ checked: boolean;
35
+ } & TranslationFields;
36
+ export declare function translationVerdict<V extends {
37
+ proven: boolean;
38
+ checked: boolean;
39
+ why?: string;
40
+ stuck?: string;
41
+ }>(rule: object, laws: object[], verdict: V): TranslatedVerdict<V>;
42
+ export declare const nativeSame: (a: unknown, b: unknown) => boolean;
43
+ export declare function nativeSnapshot(value: unknown, seen?: Map<object, unknown>): unknown;
44
+ export {};
@@ -0,0 +1,126 @@
1
+ // A non-enumerable, versioned marker survives independent module copies. Losing
2
+ // the private observations must downgrade a source proof, not turn it into a DSL proof.
3
+ const sourceMarker = Symbol.for('gdp-wired.source-proof.v1');
4
+ const marked = (value) => Object.prototype.hasOwnProperty.call(value, sourceMarker);
5
+ const mark = (value, enumerable = false) => { if (!marked(value))
6
+ Object.defineProperty(value, sourceMarker, { value: true, enumerable }); };
7
+ const markRule = (value) => {
8
+ mark(value);
9
+ // A Rule's immutable specification is spread by constructor-based transforms.
10
+ // Carry only the fail-closed marker, never a native journal, across such copies.
11
+ const spec = Object.getOwnPropertyDescriptor(value, 'spec')?.value;
12
+ if (spec && typeof spec === 'object')
13
+ mark(spec, true);
14
+ };
15
+ export function inheritSource(from, to, transparent = false) {
16
+ if (marked(from))
17
+ markRule(to);
18
+ const source = sources.get(from);
19
+ if (transparent && source)
20
+ sources.set(to, source);
21
+ }
22
+ const evidence = new WeakMap();
23
+ const sources = new WeakMap();
24
+ const nativeLaws = new WeakMap();
25
+ export function rememberNative(e, journal) { evidence.set(e, journal); }
26
+ export function attachSource(rule, e, generated) {
27
+ markRule(rule);
28
+ sources.set(rule, { root: rule, journal: evidence.get(e), generated: new Set(generated) });
29
+ }
30
+ export function attachNativeLaw(rule, law, name, method, evaluate) {
31
+ mark(law);
32
+ nativeLaws.set(law, { rule: sources.get(rule)?.root ?? rule, name, method, evaluate });
33
+ }
34
+ export function translationVerdict(rule, laws, verdict) {
35
+ const source = sources.get(rule), bound = laws.map(l => nativeLaws.get(l)).filter(x => x !== undefined);
36
+ if (!source && !bound.length && !marked(rule) && !laws.some(marked))
37
+ return verdict;
38
+ const journal = source?.journal;
39
+ const unchecked = (why) => ({ ...verdict, proven: false, checked: false, kernelProven: verdict.proven && verdict.checked, translation: 'unchecked', why: `source translation unchecked: ${why}` });
40
+ if (!journal?.enabled || !journal.complete)
41
+ return unchecked(journal?.reason ?? 'native source replay is unavailable or disabled');
42
+ if (bound.some(b => b.rule !== source?.root))
43
+ return unchecked('the source law belongs to a different rule');
44
+ if (laws.some(l => !nativeLaws.has(l) && !source.generated.has(l)))
45
+ return unchecked('a source proof contains a law with no native interpretation');
46
+ if (!verdict.proven || !verdict.checked)
47
+ return { ...verdict, translation: journal.scope };
48
+ let checks = 0;
49
+ for (const law of bound) {
50
+ let observed = 0;
51
+ for (const observation of journal.observations) {
52
+ if (law.method && observation.method !== law.method)
53
+ continue;
54
+ observed++;
55
+ checks++;
56
+ let holds;
57
+ try {
58
+ holds = law.evaluate(observation);
59
+ }
60
+ catch (e) {
61
+ return unchecked(`native interpretation of ${law.name}: ${e instanceof Error ? e.message : String(e)}`);
62
+ }
63
+ if (!holds)
64
+ return { ...verdict, proven: false, checked: false, kernelProven: true, translation: 'error', translationChecks: checks,
65
+ translationWitness: observation, stuck: 'translation-error', why: `translation error: ${law.name} is false in the native code (${observation.where})` };
66
+ }
67
+ if (!observed)
68
+ return unchecked(`no native observation of ${law.method ?? law.name}`);
69
+ }
70
+ return { ...verdict, translation: journal.scope, translationChecks: checks };
71
+ }
72
+ const sourceIdentity = new WeakMap(), cloneIdentity = new WeakMap();
73
+ let nextIdentity = 0;
74
+ const identify = (original, clone) => {
75
+ let id = sourceIdentity.get(original);
76
+ if (id === undefined) {
77
+ id = ++nextIdentity;
78
+ sourceIdentity.set(original, id);
79
+ }
80
+ cloneIdentity.set(clone, id);
81
+ };
82
+ export const nativeSame = (a, b) => a === b || (a !== null && b !== null && typeof a === 'object' && typeof b === 'object' && cloneIdentity.has(a) && cloneIdentity.get(a) === cloneIdentity.get(b));
83
+ // Snapshot real JS values, preserving undefined, NaN, keys, aliasing and class prototypes.
84
+ // Functions are not invoked; laws cannot introduce arbitrary calls. An unsupported snapshot
85
+ // must make source proof finalization unchecked, never silently lose an observation.
86
+ export function nativeSnapshot(value, seen = new Map()) {
87
+ if (value === null || typeof value !== 'object')
88
+ return value;
89
+ if (seen.has(value))
90
+ return seen.get(value);
91
+ if (seen.size >= 10000)
92
+ throw new Error('native state exceeds the snapshot bound');
93
+ const tag = Object.prototype.toString.call(value);
94
+ if (tag === '[object Date]') {
95
+ const out = new Date(Number(value));
96
+ identify(value, out);
97
+ return out;
98
+ }
99
+ if (tag === '[object Map]') {
100
+ const out = new Map();
101
+ seen.set(value, out);
102
+ identify(value, out);
103
+ for (const [k, v] of value.entries())
104
+ out.set(nativeSnapshot(k, seen), nativeSnapshot(v, seen));
105
+ return out;
106
+ }
107
+ if (tag === '[object Set]') {
108
+ const out = new Set();
109
+ seen.set(value, out);
110
+ identify(value, out);
111
+ for (const v of value.values())
112
+ out.add(nativeSnapshot(v, seen));
113
+ return out;
114
+ }
115
+ const out = (Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value)));
116
+ seen.set(value, out);
117
+ identify(value, out);
118
+ for (const key of Reflect.ownKeys(value)) {
119
+ const d = Object.getOwnPropertyDescriptor(value, key);
120
+ if ('value' in d)
121
+ Object.defineProperty(out, key, { ...d, value: nativeSnapshot(d.value, seen) });
122
+ else
123
+ Object.defineProperty(out, key, d);
124
+ }
125
+ return out;
126
+ }
@@ -0,0 +1 @@
1
+ export declare function sourceDiagnostic(value: unknown, active?: Set<object>, depth?: number): unknown;
@@ -0,0 +1,34 @@
1
+ // JSON-safe native witnesses. Keep absence and non-finite numbers explicit; never
2
+ // invoke a getter while printing an error. This is diagnostic data, not a replay format.
3
+ export function sourceDiagnostic(value, active = new Set(), depth = 0) {
4
+ if (value === undefined)
5
+ return { $undefined: true };
6
+ if (typeof value === 'number' && !Number.isFinite(value))
7
+ return { $number: String(value) };
8
+ if (typeof value === 'bigint')
9
+ return { $bigint: String(value) };
10
+ if (typeof value === 'function' || typeof value === 'symbol')
11
+ return { $unsupported: typeof value };
12
+ if (value === null || typeof value !== 'object')
13
+ return value;
14
+ if (active.has(value))
15
+ return { $circular: true };
16
+ if (depth >= 32)
17
+ return { $truncated: true };
18
+ active.add(value);
19
+ const visit = (v) => sourceDiagnostic(v, active, depth + 1);
20
+ try {
21
+ if (value instanceof Date)
22
+ return { $date: Number.isNaN(Number(value)) ? 'Invalid Date' : value.toISOString() };
23
+ if (value instanceof Map)
24
+ return { $map: [...value].map(([k, v]) => [visit(k), visit(v)]) };
25
+ if (value instanceof Set)
26
+ return { $set: [...value].map(visit) };
27
+ if (Array.isArray(value))
28
+ return value.map(visit);
29
+ return Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(value)).map(([k, d]) => [k, 'value' in d ? visit(d.value) : { $accessor: true }]));
30
+ }
31
+ finally {
32
+ active.delete(value);
33
+ }
34
+ }
@@ -0,0 +1,2 @@
1
+ export declare const attemptShare: (remaining: number, pending: ReadonlySet<string>) => number;
2
+ export declare function supportBudget(remaining: number, share: number, priority: boolean, structural?: boolean): number;
@@ -0,0 +1,6 @@
1
+ // Shared untrusted allowance rule; existing law-level behavior is unchanged.
2
+ // Pending excludes already-tried, kept and carried laws of this round.
3
+ export const attemptShare = (remaining, pending) => Math.max(0, remaining) / Math.max(1, pending.size);
4
+ export function supportBudget(remaining, share, priority, structural = false) {
5
+ return Math.max(0, Math.min(remaining, structural ? 5_000 : priority ? Math.max(share, remaining / 3) : share));
6
+ }