gdp-wired 0.50.1 → 0.50.2

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/dist/core/cli.js CHANGED
@@ -1128,7 +1128,8 @@ export async function check(targets, given = {}, each) {
1128
1128
  rs.forEach(each);
1129
1129
  }
1130
1130
  const stated = all.flatMap(r => r.laws);
1131
- return { rules: all, exit: stated.some(l => l.translation === 'unchecked' || l.translation === 'error') ? 2 : stated.some(l => l.verdict === 'broken') ? 1 : stated.some(l => l.verdict === 'not read') || o.security && all.some(r => !r.ok) ? 2 : 0 };
1131
+ // A sampled source translation cannot turn an unknown proof into a successful check.
1132
+ return { rules: all, exit: stated.some(l => l.verdict === 'unknown' || l.translation === 'unchecked' || l.translation === 'error') ? 2 : stated.some(l => l.verdict === 'broken') ? 1 : stated.some(l => l.verdict === 'not read') || o.security && all.some(r => !r.ok) ? 2 : 0 };
1132
1133
  }
1133
1134
  // --- draft: laws from a clause, for a person to review ----------------------------------------------------------------
1134
1135
  // gdp-wired draft <file> --clause <text> | --clause-file <f> --cite <ref> [--llm <command> | --answer <file>] [--by <who>]:
package/dist/core/dsl.js CHANGED
@@ -21,7 +21,7 @@ import { binder, copyVariable, encodeBinders, generatedVariable, guardReserved,
21
21
  import { candidates, cone, searchCounted } from "./counts.js";
22
22
  import { proveCandidateSeeds } from "./candidate-seeds.js";
23
23
  import { proveCountedCandidateSeeds } from "./counted-candidate-seeds.js";
24
- import { inheritSource, translationVerdict } from "./source-check.js";
24
+ import { bindSourceMachine, inheritSource, translationVerdict } from "./source-check.js";
25
25
  import { env as knobs } from "./solver.js";
26
26
  import { argsKey, bindDirect, directOf, machineTerms, part, tuple, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, fnCall, hasFinite, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, sourceFreeFn, withArithmetic } from "./machine.js";
27
27
  import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
@@ -2550,7 +2550,9 @@ export class Rule {
2550
2550
  const sums = sumsIn(machineTerms(m), s.sumsRead ?? []);
2551
2551
  const out = withArithmetic(sums ? { ...m, state: { ...m.state, ...Object.fromEntries(Object.keys(sums).map(n => [n, { op: 'const', value: 0 }])) }, sums } : m, [], s.arith ?? []);
2552
2552
  const encoded = encodeBinders(out, this.names().map(([n]) => n));
2553
- return s.ghost ? s.ghost(encoded) : encoded;
2553
+ const machine = s.ghost ? s.ghost(encoded) : encoded;
2554
+ bindSourceMachine(this, machine);
2555
+ return machine;
2554
2556
  }
2555
2557
  // The same rule with ghosts its machine gains (the search's, over a law with "there exists" made plain: skolemOf).
2556
2558
  withGhosts(ghost) { return this.with({ ghost }); }
@@ -569,7 +569,7 @@ export function checkC(file, flags, c, read, r, sorts, opts, cpp) {
569
569
  return { ...empty, mismatch: `the check's harness doesn't start: ${why(x).split('\n').filter(Boolean).slice(0, 3).join(' | ')}` };
570
570
  }
571
571
  const buildMs = Math.round(performance.now() - b0), none = () => ({ arms: 0, hit: 0, missed: [] });
572
- return { ...speak(work, `${work}/harness`, globalThis.process?.env, c.pkg, read, r, sorts, opts.check ?? {}, none), buildMs };
572
+ return Object.assign(speak(work, `${work}/harness`, globalThis.process?.env, c.pkg, read, r, sorts, opts.check ?? {}, none), { buildMs });
573
573
  }
574
574
  finally {
575
575
  try {
@@ -386,7 +386,7 @@ export function checkGo(dir, pkg, read, r, sorts, gopts) {
386
386
  return { arms: 0, hit: 0, missed: [] };
387
387
  }
388
388
  };
389
- return { ...speak(work, `${work}/harness`, { ...goEnv(), GOCOVERDIR: `${work}/cov` }, pkg, read, r, sorts, opts, count), buildMs };
389
+ return Object.assign(speak(work, `${work}/harness`, { ...goEnv(), GOCOVERDIR: `${work}/cov` }, pkg, read, r, sorts, opts, count), { buildMs });
390
390
  }
391
391
  finally {
392
392
  try {
@@ -581,7 +581,8 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
581
581
  ev = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: 0, hit: 0, missed: [] }, ms: 0,
582
582
  mismatch: `the check's harness: ${e.message}` };
583
583
  }
584
- return { ...ev, runMs: Math.round(performance.now() - r0) };
584
+ // The native journal is keyed by this exact evidence object.
585
+ return Object.assign(ev, { runMs: Math.round(performance.now() - r0) });
585
586
  }
586
587
  finally {
587
588
  if (wi >= 0)
@@ -27,6 +27,7 @@
27
27
  import * as I from "./extract-ir.js";
28
28
  import { Refusal, mergeOps, mergeWrites } from "./extract-read.js";
29
29
  import { fromModel } from "./extract.js";
30
+ import { nativeWireDecoder } from "./native-wire.js";
30
31
  import { nonneg } from "./extract-print.js";
31
32
  import { HarnessFailure, Outside, constantsOf, draw, drive, evalTerm, noEvidence, retried, tiesIn } from "./extract-check.js";
32
33
  // Bitwise and, or and xor of two naturals below 2^53 (JavaScript's operators stop at 32 bits).
@@ -6632,6 +6633,7 @@ function checkStepOnce(h, read, r, sorts, opts) {
6632
6633
  const hi = ask({ op: 'hello', ...h.hello, naiveUtc: read.naiveUtc, leaves: read.leaves, ctor: read.ctor, answers: read.answers, kept: read.kept, cls: read.cls ?? null, stores: read.stores, arms: read.arms, discard: opts.onError === 'discard', ...(read.inject ? { inject: read.inject } : {}), ...(read.globals ? { globals: read.globals } : {}), ...(read.inert ? { inert: read.inert } : {}), ...(opts.fields ? { fields: opts.fields } : {}) });
6633
6634
  if (hi.error)
6634
6635
  return { ...empty, mismatch: `the code doesn't load with the check's harness: ${JSON.stringify(hi.error)}` };
6636
+ const native = hi.nativeSnapshot === 1 && read.leaves.some(l => l.ordered) ? nativeWireDecoder() : undefined;
6635
6637
  const num = (x, at) => { const n = Number(x); if (typeof x === 'string' && Number.isSafeInteger(n) && String(n) === x)
6636
6638
  return n; throw new Outside(`${at} is ${String(x)}`); };
6637
6639
  const toSnap = (s) => {
@@ -6712,6 +6714,12 @@ function checkStepOnce(h, read, r, sorts, opts) {
6712
6714
  }
6713
6715
  return { ok: true, value: o };
6714
6716
  },
6717
+ ...(native ? { nativeState: (self) => {
6718
+ const result = ask({ op: 'native', id: self });
6719
+ if (result.error)
6720
+ throw new Error(`native snapshot: ${JSON.stringify(result.error)}`);
6721
+ return native(result.snapshot);
6722
+ } } : {}),
6715
6723
  args: (inputs, e) => { inputsNow = inputs; return (read.args[e.call] ?? []).map(([n, a]) => [n, build(a, inputs)]); },
6716
6724
  setNow: n => { now = n; },
6717
6725
  coverage: () => (coverage ??= closeAndCount()),
@@ -6775,7 +6783,8 @@ function checkStepOnce(h, read, r, sorts, opts) {
6775
6783
  return { arms: arms.length, hit: arms.filter(a => hit.has(a)).length, missed: arms.filter(a => !hit.has(a)).map(a => `the arm at ${a}`) };
6776
6784
  }
6777
6785
  const ev = drive(m, r, sorts, side, o);
6778
- return { ...ev, runMs: Math.round(performance.now() - r0) };
6786
+ // The native journal is keyed by this exact evidence object.
6787
+ return Object.assign(ev, { runMs: Math.round(performance.now() - r0) });
6779
6788
  }
6780
6789
  catch (x) {
6781
6790
  if (x instanceof HarnessFailure)
@@ -6874,7 +6883,7 @@ export function stepNames(read) {
6874
6883
  for (const l of read.leaves) {
6875
6884
  const code = l.path.join('.');
6876
6885
  if (l.kind === 'map')
6877
- out.push({ code: l.orm ? l.name : l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.orm ? { store: l.orm.rec, tpl: '{}' } : l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}), ...(l.ordered ? { ordered: true } : {}) } });
6886
+ out.push({ code: l.orm ? l.name : l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.orm ? { store: l.orm.rec, tpl: '{}' } : l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}), ...(l.ordered ? { ordered: true, scalar: m.maps.find(d => d.name === l.name)?.scalar === true } : {}) } });
6878
6887
  else if (l.kind === 'none') {
6879
6888
  const n = at(code);
6880
6889
  if (n)
@@ -66,6 +66,7 @@ export type Name = {
66
66
  store?: string;
67
67
  tpl?: string;
68
68
  ordered?: boolean;
69
+ scalar?: boolean;
69
70
  };
70
71
  };
71
72
  export declare function namesOf(m: Model): Name[];
@@ -16,6 +16,10 @@ export type Built = {
16
16
  };
17
17
  export declare class LawError extends Error {
18
18
  }
19
+ export declare class ScalarListQuantifierError extends LawError {
20
+ readonly shape = "scalar-ordered-list-quantification";
21
+ constructor();
22
+ }
19
23
  export declare function lawsIn(text: string, where?: string): LawText[];
20
24
  type Seg = {
21
25
  f: string;
package/dist/core/laws.js CHANGED
@@ -36,6 +36,10 @@ import { CalendarError, businessDays } from "./calendar.js";
36
36
  export { businessDays } from "./calendar.js";
37
37
  export class LawError extends Error {
38
38
  }
39
+ export class ScalarListQuantifierError extends LawError {
40
+ shape = 'scalar-ordered-list-quantification';
41
+ constructor() { super('forall over a scalar ordered list is not supported: list values and membership must not be replaced by position keys'); }
42
+ }
39
43
  // --- reading the code's text -------------------------------------------------------------------------------------------
40
44
  // Every law stated in a file's text, with its line.
41
45
  const FORMS = [
@@ -350,6 +354,10 @@ function read(e, c, names, dry) {
350
354
  const over = val(f.over, c, names, dry);
351
355
  if (over.t !== 'map')
352
356
  throw new LawError(`forall ${f.v} in ...: over a map (a dict, a Map, a hash) or a list`);
357
+ // Record identity is represented by its stable key. A scalar value is not:
358
+ // neither its comparisons nor membership may silently use that position.
359
+ if (over.n.map?.ordered && over.n.map.scalar !== false)
360
+ throw new ScalarListQuantifierError();
353
361
  return { over, env: f.over.k === 'old' || !c.step ? c.b : c.a };
354
362
  });
355
363
  if (dry) {
@@ -0,0 +1 @@
1
+ export declare function nativeWireDecoder(maxObjects?: number, maxNodes?: number): (wire: unknown) => unknown;
@@ -0,0 +1,85 @@
1
+ // Decode identity-bearing snapshots returned by the real native harness. This
2
+ // is observation transport only: no model values or proof results are supplied.
3
+ export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
4
+ if (!Number.isSafeInteger(maxObjects) || maxObjects < 1 || !Number.isSafeInteger(maxNodes) || maxNodes < 1)
5
+ throw Error('invalid native snapshot bounds');
6
+ const objects = new Map();
7
+ return wire => {
8
+ let nodes = 0;
9
+ const seen = new Set();
10
+ const record = (value) => {
11
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
12
+ throw Error('invalid native snapshot node');
13
+ return value;
14
+ };
15
+ const decode = (value) => {
16
+ if (++nodes > maxNodes)
17
+ throw Error('native snapshot exceeds node bound');
18
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
19
+ return value;
20
+ if (typeof value === 'number') {
21
+ if (!Number.isSafeInteger(value))
22
+ throw Error('unsafe native snapshot number');
23
+ return value;
24
+ }
25
+ const node = record(value), id = node.id, kind = node.kind;
26
+ if (typeof id !== 'string' || !/^[1-9][0-9]*$/.test(id))
27
+ throw Error('invalid native snapshot identity');
28
+ if (kind === 'ref') {
29
+ if (!seen.has(id))
30
+ throw Error('unbound native snapshot reference');
31
+ return objects.get(id).value;
32
+ }
33
+ if (kind !== 'object' && kind !== 'array' && kind !== 'map')
34
+ throw Error('unsupported native snapshot kind');
35
+ if (seen.has(id))
36
+ throw Error('duplicate native snapshot identity');
37
+ seen.add(id);
38
+ let kept = objects.get(id);
39
+ if (kept && kept.kind !== kind)
40
+ throw Error('native snapshot identity changed kind');
41
+ if (!kept) {
42
+ if (objects.size >= maxObjects)
43
+ throw Error('native snapshot exceeds identity bound');
44
+ const fresh = kind === 'array' ? [] : kind === 'map' ? new Map() : Object.create(null);
45
+ kept = { kind, value: fresh };
46
+ objects.set(id, kept);
47
+ }
48
+ if (!Array.isArray(node.items))
49
+ throw Error('invalid native snapshot entries');
50
+ if (kind === 'array') {
51
+ const target = kept.value;
52
+ target.length = 0;
53
+ for (const item of node.items)
54
+ target.push(decode(item));
55
+ }
56
+ else if (kind === 'map') {
57
+ const target = kept.value;
58
+ target.clear();
59
+ for (const item of node.items) {
60
+ if (!Array.isArray(item) || item.length !== 2 || (typeof item[0] !== 'string' && typeof item[0] !== 'number'))
61
+ throw Error('invalid native snapshot map entry');
62
+ const key = decode(item[0]);
63
+ if (target.has(key))
64
+ throw Error('duplicate native snapshot map key');
65
+ target.set(key, decode(item[1]));
66
+ }
67
+ }
68
+ else {
69
+ const target = kept.value;
70
+ for (const key of Object.keys(target))
71
+ delete target[key];
72
+ for (const item of node.items) {
73
+ if (!Array.isArray(item) || item.length !== 2 || typeof item[0] !== 'string' || Object.hasOwn(target, item[0]))
74
+ throw Error('invalid native snapshot object entry');
75
+ Object.defineProperty(target, item[0], { value: decode(item[1]), writable: true, enumerable: true, configurable: true });
76
+ }
77
+ }
78
+ return kept.value;
79
+ };
80
+ const envelope = record(wire);
81
+ if (envelope.version !== 1)
82
+ throw Error('unsupported native snapshot version');
83
+ return decode(envelope.root);
84
+ };
85
+ }
@@ -12,6 +12,7 @@ CUR = {}
12
12
  EFF = {}
13
13
  HIT = set()
14
14
  S = {}
15
+ NATIVE_OBJECTS = {}
15
16
 
16
17
  def datetime_in(v, unit):
17
18
  epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc if unit == 'datetime-utc' else None)
@@ -591,7 +592,7 @@ def hello(req):
591
592
  S['cls'] = getattr(mod, req['cls'].rpartition('.')[2]) if req.get('cls') else None
592
593
  S['loop'] = asyncio.new_event_loop()
593
594
  asyncio.set_event_loop(S['loop'])
594
- return {'ok': True}
595
+ return {'ok': True, 'nativeSnapshot': 1}
595
596
 
596
597
  def make(args):
597
598
  global OBJ_STORES
@@ -659,6 +660,38 @@ def call(req):
659
660
  if after.get(k) != before[k]: return {'frame': k}
660
661
  return {'out': tag(out), **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
661
662
 
663
+ # Native observation transport for ordered containers. Retain real references
664
+ # so Python cannot recycle an address and manufacture cross-snapshot identity.
665
+ def native_state(obj):
666
+ seen = set()
667
+ count = [0]
668
+ def encode(value, names=None):
669
+ count[0] += 1
670
+ if count[0] > 10000: raise ValueError('native snapshot exceeds node bound')
671
+ if value is None or isinstance(value, (str, bool)): return value
672
+ if isinstance(value, (int, float)):
673
+ if not (-9007199254740991 <= value <= 9007199254740991) or int(value) != value:
674
+ raise ValueError('native snapshot number is outside exact integer range')
675
+ return int(value)
676
+ address = id(value)
677
+ if address not in NATIVE_OBJECTS:
678
+ if len(NATIVE_OBJECTS) >= 100000: raise ValueError('native snapshot exceeds identity bound')
679
+ NATIVE_OBJECTS[address] = (value, str(len(NATIVE_OBJECTS) + 1))
680
+ ident = NATIVE_OBJECTS[address][1]
681
+ if ident in seen: return {'kind': 'ref', 'id': ident}
682
+ seen.add(ident)
683
+ if isinstance(value, list):
684
+ return {'kind': 'array', 'id': ident, 'items': [encode(x) for x in value]}
685
+ if isinstance(value, dict):
686
+ if any(not isinstance(k, (str, int, float)) or isinstance(k, bool) for k in value):
687
+ raise ValueError('unsupported native snapshot map key')
688
+ return {'kind': 'map', 'id': ident, 'items': [[encode(k), encode(v)] for k, v in value.items()]}
689
+ fields = vars(value)
690
+ if names is not None: fields = {name: fields[name] for name in names}
691
+ return {'kind': 'object', 'id': ident, 'items': [[k, encode(v)] for k, v in fields.items()]}
692
+ roots = sorted({l['path'][0] for l in S['leaves'] if l.get('path') and l['kind'] != 'frame'})
693
+ return {'version': 1, 'root': encode(obj, roots)}
694
+
662
695
  def main():
663
696
  fin = open(sys.argv[1], 'r'); fout = open(sys.argv[2], 'w')
664
697
  for line in fin:
@@ -683,6 +716,7 @@ def main():
683
716
  elif op == 'get':
684
717
  obj, stores = OBJS[req['id']]
685
718
  res = {'state': state_of(obj, stores)}
719
+ elif op == 'native': res = {'snapshot': native_state(OBJS[req['id']][0])}
686
720
  elif op == 'call': res = call(req)
687
721
  elif op == 'coverage': res = {'hit': sorted(HIT)}
688
722
  else: res = {'error': f"no op {op}"}
@@ -26,6 +26,7 @@ export type TranslationFields = {
26
26
  kernelProven?: boolean;
27
27
  };
28
28
  export declare function inheritSource(from: object, to: object, transparent?: boolean): void;
29
+ export declare function bindSourceMachine(rule: object, machine: object): void;
29
30
  export declare function rememberNative(e: object, journal: NativeJournal): void;
30
31
  export declare function attachSource(rule: object, e: object, generated: object[]): void;
31
32
  export declare function attachNativeLaw(rule: object, law: object, name: string, method: string | undefined, evaluate: (observation: NativeObservation) => boolean): void;
@@ -39,6 +40,7 @@ export declare function translationVerdict<V extends {
39
40
  why?: string;
40
41
  stuck?: string;
41
42
  }>(rule: object, laws: object[], verdict: V): TranslatedVerdict<V>;
43
+ export declare function requireSourceTranslation(rule: object, laws: object[]): void;
42
44
  export declare const nativeSame: (a: unknown, b: unknown) => boolean;
43
45
  export declare function nativeSnapshot(value: unknown, seen?: Map<object, unknown>): unknown;
44
46
  export {};
@@ -19,6 +19,19 @@ export function inheritSource(from, to, transparent = false) {
19
19
  if (transparent && source)
20
20
  sources.set(to, source);
21
21
  }
22
+ // Rule.machine makes a fresh structural model. Carry source provenance onto that
23
+ // exact model so public consumers that receive only a Machine still fail closed.
24
+ // The marker is enumerable here: spread/reconstruction keeps the warning, but
25
+ // never the private WeakMap journal (a copied machine is therefore rejected).
26
+ export function bindSourceMachine(rule, machine) {
27
+ const source = sources.get(rule);
28
+ if (source) {
29
+ mark(machine, true);
30
+ sources.set(machine, source);
31
+ }
32
+ else if (marked(rule))
33
+ mark(machine, true);
34
+ }
22
35
  const evidence = new WeakMap();
23
36
  const sources = new WeakMap();
24
37
  const nativeLaws = new WeakMap();
@@ -69,6 +82,14 @@ export function translationVerdict(rule, laws, verdict) {
69
82
  }
70
83
  return { ...verdict, translation: journal.scope, translationChecks: checks };
71
84
  }
85
+ // Lean export is a public proof boundary. It must repeat source admission from
86
+ // the bound machine and laws instead of trusting caller-supplied fields or an
87
+ // old verdict: the journal and native-law identities live only in these maps.
88
+ export function requireSourceTranslation(rule, laws) {
89
+ const verdict = translationVerdict(rule, laws, { proven: true, checked: true });
90
+ if (!verdict.proven || !verdict.checked)
91
+ throw new Error(verdict.why ?? 'source translation was not checked');
92
+ }
72
93
  const sourceIdentity = new WeakMap(), cloneIdentity = new WeakMap();
73
94
  let nextIdentity = 0;
74
95
  const identify = (original, clone) => {
@@ -228,7 +228,7 @@ export class Reader {
228
228
  break;
229
229
  case 'mul': {
230
230
  const a = this.linear(e.a);
231
- lin = a.lin && same(0, e, a.lin, 0, 0, () => scale(a.lin, e.k));
231
+ lin = a.lin && Number.isSafeInteger(e.k) ? same(0, e, a.lin, 0, 0, () => scale(a.lin, e.k)) : undefined;
232
232
  r = a;
233
233
  break;
234
234
  }
@@ -312,6 +312,10 @@ export class Reader {
312
312
  break;
313
313
  }
314
314
  }
315
+ // Match kernel.ts's linearOf: an unsafe intermediate form is no form,
316
+ // even if later arithmetic would cancel it back into the safe range.
317
+ if (lin && !everyLinearCell(lin, (_key, coefficient) => Number.isSafeInteger(coefficient), 'reader linear safety'))
318
+ lin = undefined;
315
319
  // (an open value's reason is what its decided parts need: only the column's own value is open)
316
320
  const out = { lin, w: r.w, fin: r.fin, pos: r.pos, stamp: r.pos < 0 ? 0 : this.trail.stamp(r.pos), node: this.node };
317
321
  this.ls.set(e, out);
@@ -7,8 +7,11 @@ export function asked(source) {
7
7
  return [...code.matchAll(/^#print axioms\s+(\S+)/gm)].map(m => m[1]);
8
8
  }
9
9
  export function answers(out) {
10
- const deps = [...out.matchAll(/^'([^\r\n]+)' depends on axioms: \[([^\]]*)\]\r?$/gm)].map(m => ({ name: m[1], axioms: m[2].split(',').map(a => a.trim()).filter(Boolean) }));
11
- const none = [...out.matchAll(/^'([^\r\n]+)' does not depend on any axioms\r?$/gm)].map(m => ({ name: m[1], axioms: [] }));
10
+ // Lake prefixes native informational output with its source location. Strip
11
+ // only that exact envelope; arbitrary diagnostic text is not an axiom answer.
12
+ const plain = out.replace(/^info: [^\r\n]+\.lean:\d+:\d+: /gm, '');
13
+ const deps = [...plain.matchAll(/^'([^\r\n]+)' depends on axioms: \[([^\]]*)\]\r?$/gm)].map(m => ({ name: m[1], axioms: m[2].split(',').map(a => a.trim()).filter(Boolean) }));
14
+ const none = [...plain.matchAll(/^'([^\r\n]+)' does not depend on any axioms\r?$/gm)].map(m => ({ name: m[1], axioms: [] }));
12
15
  return [...deps, ...none];
13
16
  }
14
17
  export function gate(out, sources, native = false) {
@@ -116,6 +116,7 @@ export declare function readable(id: string, laws: Law[], vars: string[], maps:
116
116
  eLit?: (e: E) => string;
117
117
  ghosts?: boolean;
118
118
  explicitExistentials?: ReadonlySet<string>;
119
+ lawDef?: (j: number) => string;
119
120
  }): string;
120
121
  export type ProgressCase = {
121
122
  id: string;
@@ -12,6 +12,7 @@ import { legacyFamilyOrder } from "./legacy-family-order.js";
12
12
  import { proveKInduction } from "../core/kind.js";
13
13
  import { quantifiedRenames } from "./qalpha.js";
14
14
  import { countsForReads } from "../core/count-facts.js";
15
+ import { requireSourceTranslation } from "../core/source-check.js";
15
16
  export { leanLibrary };
16
17
  // --- to Lean ------------------------------------------------------------------------------------------------------------
17
18
  const varsOf = (c) => [...JSON.stringify(c).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
@@ -1002,6 +1003,7 @@ theorem ${id}_laws : ∀ maps ρ, evalC ρ maps ${id}_fold.pre = true → ∀ t,
1002
1003
  // abbreviation for its column), proven from the machine's theorem by unfolding the law's own definition. The statement
1003
1004
  // is what a Lean development cites; the column numbers stay inside the namespace.
1004
1005
  // `have`: the line that gives each law as a hypothesis hl (an SEntry's Holds by default; a cyclic proof's, holdsOver).
1006
+ // `lawDef`: the separate condition definition wrapped by a cyclic MLaw; other exporters inline the condition.
1005
1007
  // A law with "there exists" (core/exists.ts, `ex` on the law the kernel proved) is stated as the existential it is:
1006
1008
  // `<id>_someN`, ∃ w1 .. wn, P with the bound naturals set to them (updAll, Ghost.lean), from the law proven with its
1007
1009
  // witness terms in place (some_of_subst) or over the machine's ghosts at every reachable state of the machine without
@@ -1216,7 +1218,7 @@ ${laws.map((law, j) => {
1216
1218
  return `-- ${law.name}: its terms read an if, so no plain statement here (${id}_laws holds it)`;
1217
1219
  const hyps = arithBinders(law), names = arithIn(law).map(hypName);
1218
1220
  // Proof terms retain neutral Boolean children; surface statements omit them.
1219
- const surfaceProof = `by simpa [${id}_l${j}, holdsC, evalE, upd] using hl'`;
1221
+ const surfaceProof = `by simpa [${id}_l${j}${reach.lawDef ? `, ${reach.lawDef(j)}` : ''}, holdsC, evalE, upd] using hl'`;
1220
1222
  const rw = names.length ? `have hμ : ${statement(law, false)} := ${surfaceProof}\n rw [${names.join(', ')}] at hμ\n exact hμ` : `exact ${surfaceProof}`;
1221
1223
  const own = law.keys?.length ? `${reach.have ? reach.have(j) : `have hl : ${id}_e${j}.Holds ρ μ := ${reach.call} ${id}_e${j} (by simp [${id}_proof])`}
1222
1224
  have hl' := fun k ${law.keys.map((_, i) => `k${i + 2}`).join(' ')} => (evalC_iff (upd (${law.keys.reduce((acc, key, i) => `upd (${acc}) ${vars.indexOf(key)} k${i + 2}`, 'ρ')}) ${vars.indexOf(law.forall)} k) μ ${id}_l${j}.holds).mp (hl ${law.keys.map((_, i) => `k${i + 2}`).join(' ')} k)
@@ -2117,7 +2119,7 @@ theorem ${id}_laws : ∀ ρ M, SReach ${id}_machine ρ M → ∀ e ∈ ${id}_mla
2117
2119
  theorem ${id}_hcheck : checkHMachine ${id}_hist [] ${id}_records = true := by ${checkBy}
2118
2120
  theorem ${id}_hlaws : ∀ ρ M hist, HReach ${id}_hist ρ M hist → ∀ e ∈ ${id}_mlaws, holdsOver e.1 M e.2 ρ :=
2119
2121
  fun ρ M hist h => ${id}_laws ρ M (hreach_plain ${id}_hist ${id}_records ${id}_hcheck ρ M hist h)
2120
- ${readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat) (hist : List (Nat → Nat))', hyp: `HReach ${id}_hist ρ μ hist`, call: '',
2122
+ ${readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat) (hist : List (Nat → Nat))', hyp: `HReach ${id}_hist ρ μ hist`, call: '', lawDef: j => `${id}_law${j}`,
2121
2123
  have: j => `have hl : holdsOver ${id}_l${j} μ ${keys2(laws[j])} ρ := cyc_machine_holds (${id}_law${j}_holds ρ μ ${reach('h')})` })}`;
2122
2124
  };
2123
2125
  // The machine's own step laws, one step or k (BridgeRules.lean's cyc_kstep_sound): the SKStep as the usual export
@@ -2208,7 +2210,7 @@ ${cycProofText(id, p, [], vars, maps)}
2208
2210
  ${okLemmas}
2209
2211
  ${lawBlocks}
2210
2212
  ${lawsThm}
2211
- ${hm ? histBlock() : readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '', lit: c, eLit: e, ghosts: !rf && gv.length > 0,
2213
+ ${hm ? histBlock() : readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '', lit: c, eLit: e, ghosts: !rf && gv.length > 0, lawDef: j => `${id}_law${j}`,
2212
2214
  have: j => `have hl : holdsOver ${id}_l${j} μ ${keys2(laws[j])} ρ := cyc_machine_holds (${id}_law${j}_holds ρ μ h)` })}${opts.noFacts ? '' : factsProof(id, m, maps, vars, opts.simp)}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix)}` : ''}` };
2213
2215
  }
2214
2216
  // A fold from its cyclic proof (Bridge.lean's cyc_fold_sound): the fold numbered as foldToLean numbers it, each law's
@@ -2500,6 +2502,22 @@ export function hmachineToLean(id, m, laws, tampers = [], corollary) {
2500
2502
  // `cyclic`: each machine, loop and fold the cyclic route covers from cyclic certificates (see cycMachineToLean); defaults
2501
2503
  // to GDP_CERT=cyclic. `certReport` then says which items went which way.
2502
2504
  export function toLean(items, opts = {}) {
2505
+ // Admit source-derived models before changing exporter state or emitting any text.
2506
+ // Ordinary typed DSL machines have no provenance entry and pass unchanged.
2507
+ for (const item of items) {
2508
+ if ('machine' in item)
2509
+ requireSourceTranslation(item.machine, [...item.laws, ...(item.stepLaws ?? []), ...(item.liveness ?? [])]);
2510
+ else if ('kInduction' in item)
2511
+ requireSourceTranslation(item.kInduction.machine, [...item.kInduction.laws, item.kInduction.law]);
2512
+ else if ('countedMachine' in item)
2513
+ requireSourceTranslation(item.countedMachine, item.laws);
2514
+ else if ('refinement' in item) {
2515
+ requireSourceTranslation(item.refinement.impl, item.refinement.relation);
2516
+ requireSourceTranslation(item.refinement.spec, item.refinement.relation);
2517
+ }
2518
+ else if ('cyclic' in item && item.bridge)
2519
+ requireSourceTranslation(item.bridge.machine, item.bridge.laws);
2520
+ }
2503
2521
  const outer = checkBy, outerCerts = certsOn;
2504
2522
  const env = globalThis.process?.env;
2505
2523
  checkBy = (opts.native ?? env?.GDP_LEAN_NATIVE === '1') ? 'native_decide' : 'decide +kernel';
@@ -2930,6 +2948,6 @@ theorem ${id}_law${j}_holds : ∀ ρ M, SReach ${id}_machine ρ M → ∀ ρ' :
2930
2948
  ${(b.tampered ?? []).map((tm, j) => `-- TAMPERED: ${tm.what}. Lean computes the check against the proof to false.
2931
2949
  def ${id}_tamperedm${j} : SMachine := ${machineLit(tm.machine, t, ix, mx)}
2932
2950
  example : cycMOk ${id}_tamperedm${j} ${id}_enc ${id}_facts ${id}_law0 ${keysL(b.laws[0])} ${id}_node0 = false := by ${checkBy}`).join('\n')}
2933
- ${readable(id, b.laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '',
2951
+ ${readable(id, b.laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '', lawDef: j => `${id}_law${j}`,
2934
2952
  have: j => `have hl : holdsOver ${id}_l${j} μ ${list((b.laws[j].keys ?? []).map(k2 => String(ix(k2))))} ρ := cyc_machine_holds (${id}_law${j}_holds ρ μ h)` })}`;
2935
2953
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.50.1",
3
+ "version": "0.50.2",
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",