gdp-wired 0.50.1 → 0.50.3

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 (55) hide show
  1. package/README.md +4 -2
  2. package/dist/core/cli.d.ts +12 -1
  3. package/dist/core/cli.js +64 -26
  4. package/dist/core/discover.d.ts +6 -1
  5. package/dist/core/discover.js +54 -7
  6. package/dist/core/dsl-deadline.d.ts +3 -0
  7. package/dist/core/dsl-deadline.js +26 -2
  8. package/dist/core/dsl.d.ts +3 -1
  9. package/dist/core/dsl.js +97 -32
  10. package/dist/core/effect.d.ts +12 -0
  11. package/dist/core/effect.js +26 -9
  12. package/dist/core/ex/harness.exs +171 -5
  13. package/dist/core/extract-c.js +64 -7
  14. package/dist/core/extract-check.d.ts +5 -1
  15. package/dist/core/extract-check.js +28 -10
  16. package/dist/core/extract-go-check.js +130 -3
  17. package/dist/core/extract-go.js +8 -2
  18. package/dist/core/extract-jvm.js +2 -2
  19. package/dist/core/extract-rs.js +51 -5
  20. package/dist/core/extract-step.js +49 -6
  21. package/dist/core/extract-swift.js +47 -3
  22. package/dist/core/extract.d.ts +9 -0
  23. package/dist/core/infer.d.ts +8 -0
  24. package/dist/core/infer.js +133 -16
  25. package/dist/core/jvm/Harness.java +135 -3
  26. package/dist/core/jvm/Rt.java +66 -4
  27. package/dist/core/laws.d.ts +4 -0
  28. package/dist/core/laws.js +59 -10
  29. package/dist/core/native-law.d.ts +3 -1
  30. package/dist/core/native-law.js +126 -14
  31. package/dist/core/native-observations.d.ts +20 -0
  32. package/dist/core/native-observations.js +41 -0
  33. package/dist/core/native-wire.d.ts +2 -0
  34. package/dist/core/native-wire.js +99 -0
  35. package/dist/core/py/harness.py +53 -2
  36. package/dist/core/rb/harness.rb +178 -9
  37. package/dist/core/search-termination.d.ts +35 -0
  38. package/dist/core/search-termination.js +13 -0
  39. package/dist/core/search-watchdog.d.ts +8 -0
  40. package/dist/core/search-watchdog.js +34 -0
  41. package/dist/core/source-check.d.ts +5 -0
  42. package/dist/core/source-check.js +21 -0
  43. package/dist/core/swift/Harness.swift +65 -4
  44. package/dist/core/swift/Main.swift +27 -4
  45. package/dist/core/wall.d.ts +3 -1
  46. package/dist/core/wall.js +7 -4
  47. package/dist/core/work-refusal.d.ts +3 -0
  48. package/dist/core/work-refusal.js +8 -0
  49. package/dist/kernel/prove.d.ts +2 -0
  50. package/dist/kernel/prove.js +13 -5
  51. package/dist/kernel/reader.js +5 -1
  52. package/dist/lean-kernel/axiom-audit.js +5 -2
  53. package/dist/lean-kernel/emit.d.ts +1 -0
  54. package/dist/lean-kernel/emit.js +22 -4
  55. package/package.json +1 -1
@@ -1,6 +1,46 @@
1
1
  // gdp-wired's check harness for Swift, its fixed part (core/extract-swift.ts appends it, after the part generated for the
2
2
  // type read, to the type's file in the check's copy of the package): JSON, the requests, the stores, the answers.
3
3
  // Pure Swift, no Foundation (importing it into the code's file could change what its names resolve to).
4
+ // Raw source-language values only. Object equality is intentionally scalar-only.
5
+ func __gdpNativeUnsupported(_ reason: String) throws -> __GdpJ { throw __GdpBad(why: reason) }
6
+ func __gdpNativeInt<T: BinaryInteger>(_ x: T) throws -> __GdpJ {
7
+ guard let n = Int64(exactly: x), n >= -9007199254740991, n <= 9007199254740991 else { throw __GdpBad(why: "native integer outside safe range") }
8
+ return .n(String(n))
9
+ }
10
+ func __gdpNativeNode(_ kind: String, _ items: [__GdpJ]) throws -> __GdpJ {
11
+ guard __gdpS.nativeID < 9007199254740991, items.count <= 10000 else { throw __GdpBad(why: "native snapshot bound") }
12
+ let id = __gdpS.nativeID; __gdpS.nativeID += 1
13
+ return .o(["kind": .s(kind), "id": .s(String(id)), "items": .a(items)])
14
+ }
15
+ func __gdpNativeObject(_ items: [(String, __GdpJ)]) throws -> __GdpJ { try __gdpNativeNode("object", items.map { .a([.s($0.0), $0.1]) }) }
16
+ func __gdpNativeMap(_ items: [__GdpJ]) throws -> __GdpJ { try __gdpNativeNode("map", items) }
17
+ func __gdpNativeFrame(_ read: () throws -> __GdpJ) -> __GdpJ {
18
+ do { return .o(["snapshot": .o(["version": .n("1"), "root": try read()])]) } catch { return .o(["error": .s("\(error)")]) }
19
+ }
20
+ func __gdpNativeScalar(_ x: Any, _ depth: Int = 0) throws -> __GdpJ {
21
+ guard depth < 8 else { throw __GdpBad(why: "native optional bound") }
22
+ if let b = x as? Bool { return .b(b) }
23
+ if let s = x as? String { return .s(s) }
24
+ if let n = x as? any BinaryInteger { return try __gdpNativeInt(n) }
25
+ let mirror = Mirror(reflecting: x)
26
+ if mirror.displayStyle == .optional { return try mirror.children.first.map { try __gdpNativeScalar($0.value, depth + 1) } ?? .null }
27
+ throw __GdpBad(why: "unsupported native answer type")
28
+ }
29
+ final class __GdpCapture: @unchecked Sendable {
30
+ var invocation = 0; var calls: [String: __GdpJ] = [:]; var error: String?
31
+ }
32
+ let __gdpCapture = __GdpCapture()
33
+ func __gdpObservationFrame() -> __GdpJ {
34
+ if let error = __gdpCapture.error { return .o(["error": .s(error)]) }
35
+ return __gdpNativeFrame {
36
+ try __gdpNativeObject([("invocation", .n(String(__gdpCapture.invocation))), ("calls", try __gdpNativeObject(try __gdpCapture.calls.map { key, value in (key, try __gdpNativeObject([("kind", .s("returned")), ("value", value)])) }))])
37
+ }
38
+ }
39
+ func __gdpRecordNative(_ key: String, _ value: __GdpJ) {
40
+ var text = ""; value.write(&text)
41
+ if let previous = __gdpCapture.calls[key] { var old = ""; previous.write(&old); if old != text { __gdpCapture.error = "differing repeated native call \(key)" } }
42
+ else { __gdpCapture.calls[key] = value }
43
+ }
4
44
  struct __GdpBad: Error { let why: String }
5
45
  struct __GdpErr: Error { let why: String }
6
46
  indirect enum __GdpJ {
@@ -64,7 +104,13 @@ extension UInt8: __GdpAns { static func __gdpOf(_ j: __GdpJ?) throws -> UInt8 {
64
104
  extension Bool: __GdpAns { static func __gdpOf(_ j: __GdpJ?) throws -> Bool { try __gdpBool(j) }; static var __gdpZero: Bool { false } }
65
105
  extension String: __GdpAns { static func __gdpOf(_ j: __GdpJ?) throws -> String { try __gdpStr(j) }; static var __gdpZero: String { "" } }
66
106
  extension Optional: __GdpAns where Wrapped: __GdpAns { static func __gdpOf(_ j: __GdpJ?) throws -> Optional<Wrapped> { __gdpIsNone(j) ? nil : try Wrapped.__gdpOf(j) }; static var __gdpZero: Optional<Wrapped> { nil } }
67
- func __gdpAnswer<T: __GdpAns>(_ k: String) -> T { do { return try T.__gdpOf(__gdpS.answers[k]) } catch { fatalError("gdp: no answer for \(k)") } }
107
+ func __gdpAnswer<T: __GdpAns>(_ k: String) -> T {
108
+ do {
109
+ let value = try T.__gdpOf(__gdpS.answers[k])
110
+ do { __gdpRecordNative(k, try __gdpNativeScalar(value)) } catch { __gdpCapture.error = "unsupported actual answer: \(error)" }
111
+ return value
112
+ } catch { __gdpCapture.error = "actual answer conversion failed: \(error)"; fatalError("gdp: no answer for \(k)") }
113
+ }
68
114
  func __gdpZero<T: __GdpAns>() -> T { T.__gdpZero }
69
115
  final class __GdpStore: @unchecked Sendable { var data: [String: __GdpJ] = [:] }
70
116
  func __gdpStoreGet<T: __GdpAns>(_ s: __GdpStore, _ k: String) -> T { do { return try T.__gdpOf(s.data[k] ?? .null) } catch { fatalError("gdp: the store holds no \(T.self) at \(k)") } }
@@ -78,9 +124,17 @@ func __gdpTpl(_ t: String, _ k: String) -> String? {
78
124
  }
79
125
  func __gdpFill(_ t: String, _ h: String) -> String { guard let (pre, post) = __gdpSplit(t) else { return t }; return pre + h + post }
80
126
  func __gdpOut(_ m: [String: __GdpJ]) -> String { var o = ""; __GdpJ.o(m).write(&o); return o }
81
- public func __gdpOp(_ line: String) -> String { var p = __GdpParse(line); if case .s(let op)? = p.val()["op"] { return op }; return "" }
127
+ public func __gdpOp(_ line: String) -> String {
128
+ var p = __GdpParse(line); let req = p.val()
129
+ guard case .s(let op)? = req["op"] else { return "" }
130
+ if op == "call" {
131
+ __gdpCapture.invocation += 1
132
+ __gdpS.binding = .o(["error": .s("native arguments were not bound")])
133
+ }
134
+ return op
135
+ }
82
136
  public func __gdpCrash(_ op: String, _ how: String) -> String {
83
- op == "call" ? __gdpOut(["out": .null, "err": .s("a crash (\(how): a trap, a precondition, fatalError, nil force-unwrapped)")]) : op == "at" ? __gdpOut(["bad": .s("a crash setting the state (\(how))")]) : __gdpOut(["err": .s("a crash in init (\(how))")])
137
+ op == "call" ? __gdpOut(["out": .null, "err": .s("a crash (\(how): a trap, a precondition, fatalError, nil force-unwrapped)"), "nativeBindings": __gdpS.binding, "nativeObservations": .o(["error": .s("child native observation unavailable after crash")])]) : op == "at" ? __gdpOut(["bad": .s("a crash setting the state (\(how))")]) : __gdpOut(["err": .s("a crash in init (\(how))")])
84
138
  }
85
139
  func __gdpStoresOk() -> String? {
86
140
  for (n, st) in __gdpS.cur { for k in st.data.keys where !(__gdpTpls[n] ?? []).contains(where: { __gdpTpl($0, k) != nil }) { return "the store \(n) holds \(k), a key no template of the rule names" } }
@@ -91,7 +145,7 @@ public func __gdpHandle(_ line: String) -> String {
91
145
  let req = p.val()
92
146
  guard case .s(let op)? = req["op"] else { return __gdpOut(["error": .s("no op")]) }
93
147
  switch op {
94
- case "hello": __gdpS.discard = __gdpIsTrue(req["discard"]); return __gdpOut(["ok": .b(true)])
148
+ case "hello": __gdpS.discard = __gdpIsTrue(req["discard"]); return __gdpOut(["ok": .b(true), "nativeSnapshot": .n("1"), "nativeBindings": .n("1"), "nativeObservations": .n("1"), "nativeEquality": .s("scalar")])
95
149
  case "new", "at":
96
150
  __gdpS.cur = [:]
97
151
  do {
@@ -105,7 +159,12 @@ public func __gdpHandle(_ line: String) -> String {
105
159
  __gdpS.cur = __gdpS.stores[i - 1]
106
160
  if let bad = __gdpStoresOk() { return __gdpOut(["error": .s(bad)]) }
107
161
  return __gdpOut(["state": .o(__gdpGet(__gdpS.objs[i - 1]))])
162
+ case "native":
163
+ guard let i = req["id"]?.text.flatMap({ Int($0) }), i >= 1, i <= __gdpS.objs.count else { return __gdpOut(["error": .s("no object")]) }
164
+ __gdpS.cur = __gdpS.stores[i - 1]
165
+ var result = ""; __gdpNativeFrame { try __gdpNative(__gdpS.objs[i - 1]) }.write(&result); return result
108
166
  case "call":
167
+ __gdpCapture.calls = [:]; __gdpCapture.error = nil
109
168
  guard let i = req["id"]?.text.flatMap({ Int($0) }), i >= 1, i <= __gdpS.objs.count, case .s(let m)? = req["m"] else { return __gdpOut(["error": .s("no object")]) }
110
169
  __gdpS.cur = __gdpS.stores[i - 1]
111
170
  if case .o(let a)? = req["answers"] { __gdpS.answers = a } else { __gdpS.answers = [:] }
@@ -117,6 +176,8 @@ public func __gdpHandle(_ line: String) -> String {
117
176
  catch { res = ["out": .null, "err": .s("\(error)")] }
118
177
  let after = __gdpFrames(__gdpS.objs[i - 1])
119
178
  for (k, v) in before where after[k] != v { return __gdpOut(["frame": .s(k)]) }
179
+ res["nativeBindings"] = __gdpS.binding
180
+ res["nativeObservations"] = __gdpObservationFrame()
120
181
  return __gdpOut(res)
121
182
  case "coverage": return __gdpOut(["hit": .a([])])
122
183
  default: return __gdpOut(["error": .s("no op \(op)")])
@@ -11,21 +11,44 @@ func run() {
11
11
  let args = CommandLine.arguments
12
12
  guard args.count >= 3, let fin = fopen(args[args.count - 2], "r") else { return }
13
13
  let fout = open(args[args.count - 1], O_WRONLY)
14
+ guard fout >= 0 else { fclose(fin); return }
14
15
  typealias Fork = @convention(c) () -> Int32
15
16
  let fork = unsafeBitCast(dlsym(dlopen(nil, RTLD_NOW), "fork"), to: Fork.self)
16
17
  var line: UnsafeMutablePointer<CChar>? = nil
17
18
  var cap = 0
19
+ defer { if let line { free(line) }; fclose(fin); close(fout) }
18
20
  while getline(&line, &cap, fin) > 0 {
19
21
  let req = String(cString: line!)
20
22
  let op = __gdpOp(req)
21
23
  var res: String
22
24
  if op == "new" || op == "at" || op == "call" {
25
+ // A crashed child's journal is unavailable; never fabricate it from the request.
26
+ // The successful parent execution records its own actual calls.
23
27
  let pid = fork()
24
- if pid == 0 { if getenv("GDP_SWIFT_DEBUG") == nil { dup2(open("/dev/null", O_WRONLY), 2) }; _ = __gdpHandle(req); _exit(0) }
28
+ if pid == 0 {
29
+ if getenv("GDP_SWIFT_DEBUG") == nil {
30
+ let fd = open("/dev/null", O_WRONLY)
31
+ if fd >= 0 { _ = dup2(fd, 2); if fd != 2 { close(fd) } }
32
+ }
33
+ _ = __gdpHandle(req)
34
+ _exit(0)
35
+ }
25
36
  var st: Int32 = 0
26
- _ = waitpid(pid, &st, 0)
27
- let sig = st & 0x7f, code = (st >> 8) & 0xff
28
- if sig != 0 || code != 0 { res = __gdpCrash(op, sig != 0 ? "signal \(sig)" : "exit \(code)") } else { res = __gdpHandle(req) }
37
+ var waited: Int32 = -1
38
+ if pid > 0 {
39
+ repeat { waited = waitpid(pid, &st, 0) } while waited == -1 && errno == EINTR
40
+ if waited == -1 && errno != ECHILD {
41
+ // Only the still-owned child can be signalled; never a process group.
42
+ _ = kill(pid, SIGKILL)
43
+ var reaped: Int32
44
+ repeat { reaped = waitpid(pid, &st, 0) } while reaped == -1 && errno == EINTR
45
+ }
46
+ }
47
+ if pid <= 0 || waited != pid { res = "{\"error\":\"child execution unavailable\"}" }
48
+ else {
49
+ let sig = st & 0x7f, code = (st >> 8) & 0xff
50
+ if sig != 0 || code != 0 { res = __gdpCrash(op, sig != 0 ? "signal \(sig)" : "exit \(code)") } else { res = __gdpHandle(req) }
51
+ }
29
52
  } else { res = __gdpHandle(req) }
30
53
  res += "\n"
31
54
  _ = res.withCString { write(fout, $0, strlen($0)) }
@@ -1,4 +1,5 @@
1
1
  import { type WallDeadline } from '../kernel/prove.js';
2
+ import type { SearchTermination } from './search-termination.js';
2
3
  export { wallDeadline, withBudget, budgetEnd, inBudget, checkBudget, checkWorkEndpoint, BudgetExpired, searchNow } from '../kernel/prove.js';
3
4
  export { traceNow } from './trace-clock.js';
4
5
  export declare const searchDateNow: () => number;
@@ -6,6 +7,7 @@ export declare const searchWall: (ms: number) => WallDeadline;
6
7
  export declare const transportEnd: (until: number, cap?: number) => number;
7
8
  export declare class WallExpired extends Error {
8
9
  readonly phase: string;
9
- constructor(phase: string);
10
+ readonly termination?: SearchTermination | undefined;
11
+ constructor(phase: string, termination?: SearchTermination | undefined);
10
12
  }
11
13
  export declare function checkWall(phase: string): void;
package/dist/core/wall.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Cooperative cancellation of untrusted search. Legacy callers retain their
2
2
  // wall; an explicit work scope never consults it or grants completion headroom.
3
- import { pastWall, clock, searchNow, wallAt, inBudget, inWorkScope, checkBudget, checkWorkAdmission, remainingWork, wallDeadline } from "../kernel/prove.js";
3
+ import { wallTermination, clock, searchNow, wallAt, inBudget, inWorkScope, checkBudget, checkWorkAdmission, remainingWork, wallDeadline } from "../kernel/prove.js";
4
4
  import { runtimeWall } from "./runtime-wall.js";
5
5
  export { wallDeadline, withBudget, budgetEnd, inBudget, checkBudget, checkWorkEndpoint, BudgetExpired, searchNow } from "../kernel/prove.js";
6
6
  export { traceNow } from "./trace-clock.js";
@@ -17,9 +17,11 @@ export const transportEnd = (until, cap = Infinity) => inWorkScope()
17
17
  : Math.min(wallAt(), searchNow() + Math.min(cap, Math.max(0, until - clock()) * 10));
18
18
  export class WallExpired extends Error {
19
19
  phase;
20
- constructor(phase) {
20
+ termination;
21
+ constructor(phase, termination) {
21
22
  super(`time (${phase})`);
22
23
  this.phase = phase;
24
+ this.termination = termination;
23
25
  this.name = 'WallExpired';
24
26
  }
25
27
  }
@@ -28,8 +30,9 @@ export function checkWall(phase) {
28
30
  checkBudget(phase);
29
31
  return;
30
32
  }
31
- if (pastWall())
32
- throw new WallExpired(phase);
33
+ const termination = wallTermination(phase);
34
+ if (termination)
35
+ throw new WallExpired(phase, termination);
33
36
  }
34
37
  // The interpreter must not import the proof engine just to check cancellation.
35
38
  runtimeWall.check = checkWall;
@@ -1 +1,4 @@
1
+ import { type SearchContext } from './search-termination.js';
2
+ export declare function captureWorkContext(error: Error, context: SearchContext): void;
3
+ export declare const workContext: (error: Error) => SearchContext | undefined;
1
4
  export declare function workRefusalWhy(error: Error): string;
@@ -1,5 +1,13 @@
1
1
  // Diagnostic only: never changes refusal ownership, admission or counters.
2
2
  import { workLedger } from "./work-admission.js";
3
+ // Non-authoritative context captured before a search unwinds its SAT/model state.
4
+ // Keep the error identity and the ledger's authenticated refusal untouched.
5
+ const contexts = new WeakMap();
6
+ export function captureWorkContext(error, context) {
7
+ if (!contexts.has(error))
8
+ contexts.set(error, context);
9
+ }
10
+ export const workContext = (error) => contexts.get(error);
3
11
  export function workRefusalWhy(error) {
4
12
  const refusal = workLedger.capacityRefusal(error);
5
13
  return refusal ? `${error.message} [limits=${[...new Set(refusal.limiting.map(endpoint => endpoint.kind))].join(',')}]` : error.message;
@@ -1,3 +1,4 @@
1
+ import type { SearchTermination } from '../core/search-termination.js';
1
2
  import { type C, type E, type Law, type Machine } from '../core/machine.js';
2
3
  import { type Lin } from '../core/solver.js';
3
4
  import { type WorkAmount } from '../core/work-amount.js';
@@ -73,6 +74,7 @@ export type WallDeadline = Readonly<{
73
74
  end: number;
74
75
  }>;
75
76
  export declare const wallDeadline: (end: number, domain?: WallDeadline["domain"]) => WallDeadline;
77
+ export declare const wallTermination: (phase: string) => SearchTermination | undefined;
76
78
  export declare const pastWall: () => boolean;
77
79
  export declare function withWall<T>(limit: number | WallDeadline, f: () => T): T;
78
80
  export declare const wallAt: () => number;
@@ -1,4 +1,5 @@
1
1
  import { retainFamily, retainFrom } from "../core/proof-output.js";
2
+ import { checkWatchdog } from "../core/search-watchdog.js";
2
3
  // An untrusted prover for the kernel: grows a split tree until every leaf's constraints are refuted by solve(), splitting
3
4
  // on whatever atom the hypotheses leave open (an if's condition, a min's or ∸'s comparison, a disjunction's atoms, two
4
5
  // reads of one map at keys not yet known equal or apart). Its trees go to kernel.check; nothing it says is trusted.
@@ -390,6 +391,7 @@ export const budgetEnd = () => {
390
391
  };
391
392
  // Hard-stop checkpoints must not turn a local search deadline into a whole-run stop.
392
393
  export function checkWorkEndpoint(phase) {
394
+ checkWatchdog(phase);
393
395
  if (completeWorkProfile.enabled) {
394
396
  workLedger.check(phase);
395
397
  return;
@@ -521,14 +523,20 @@ export const wallDeadline = (end, domain) => ({ end, domain: domain ?? (inWorkSc
521
523
  // A legacy counted clock is not an opt-in work-only cancellation policy.
522
524
  // Preserve its inherited real wall; only explicit work scopes/profiles elide it.
523
525
  const workOnlyWall = () => inBudget() || stepWorkProfile.enabled;
524
- export const pastWall = () => {
526
+ // Preserve the predicate's original order, but capture the actual clock domain
527
+ // at the cancelling boundary. A WallExpired alone cannot identify real time:
528
+ // pastWall has always included counted stage endpoints as well.
529
+ export const wallTermination = (phase) => {
525
530
  checkWorkEndpoint('prover boundary');
526
531
  const proxy = proxySearchState();
527
- if (proxy)
528
- return clock() > withinDeadline(Infinity) || (!workOnlyWall() && proxy.wallEnd !== Infinity && performance.now() > proxy.wallEnd);
529
- return (inWorkScope() && clock() > withinDeadline(budgetEnd()))
530
- || (!workOnlyWall() && wallEnd !== Infinity && performance.now() > wallEnd);
532
+ if (proxy ? clock() > withinDeadline(Infinity) : inWorkScope() && clock() > withinDeadline(budgetEnd()))
533
+ return { kind: 'work-exhausted', phase, scope: 'stage' };
534
+ const end = proxy ? proxy.wallEnd : wallEnd;
535
+ if (!workOnlyWall() && end !== Infinity && performance.now() > end)
536
+ return { kind: 'wall-deadline', phase, scope: 'search' };
537
+ return undefined;
531
538
  };
539
+ export const pastWall = () => wallTermination('prover boundary') !== undefined;
532
540
  export function withWall(limit, f) {
533
541
  const proxy = proxySearchState();
534
542
  // Untagged legacy endpoints retain their old policy. Search producers tag
@@ -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.3",
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",