gdp-wired 0.50.2 → 0.50.4

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 (69) hide show
  1. package/README.md +8 -2
  2. package/dist/core/agent-consult/cli.d.ts +2 -0
  3. package/dist/core/agent-consult/cli.js +19 -0
  4. package/dist/core/agent-consult/protocol.d.ts +93 -0
  5. package/dist/core/agent-consult/protocol.js +154 -0
  6. package/dist/core/agent-consult/service.d.ts +435 -0
  7. package/dist/core/agent-consult/service.js +84 -0
  8. package/dist/core/agent-consult/session.d.ts +13 -0
  9. package/dist/core/agent-consult/session.js +163 -0
  10. package/dist/core/agent-consult/source-service.d.ts +83 -0
  11. package/dist/core/agent-consult/source-service.js +51 -0
  12. package/dist/core/agent-consult/tsconfig.json +5 -0
  13. package/dist/core/agent-consult/worker.d.ts +1 -0
  14. package/dist/core/agent-consult/worker.js +17 -0
  15. package/dist/core/agent-consult/workspace.d.ts +27 -0
  16. package/dist/core/agent-consult/workspace.js +66 -0
  17. package/dist/core/agent-consult.d.ts +8 -0
  18. package/dist/core/agent-consult.js +6 -0
  19. package/dist/core/cli.d.ts +17 -1
  20. package/dist/core/cli.js +174 -68
  21. package/dist/core/discover.d.ts +6 -1
  22. package/dist/core/discover.js +54 -7
  23. package/dist/core/dsl-deadline.d.ts +3 -0
  24. package/dist/core/dsl-deadline.js +26 -2
  25. package/dist/core/dsl.d.ts +3 -1
  26. package/dist/core/dsl.js +93 -30
  27. package/dist/core/effect.d.ts +12 -0
  28. package/dist/core/effect.js +26 -9
  29. package/dist/core/ex/harness.exs +171 -5
  30. package/dist/core/extract-c.js +63 -6
  31. package/dist/core/extract-check.d.ts +5 -1
  32. package/dist/core/extract-check.js +28 -10
  33. package/dist/core/extract-go-check.js +127 -1
  34. package/dist/core/extract-go.js +8 -2
  35. package/dist/core/extract-jvm.js +2 -2
  36. package/dist/core/extract-rs.js +51 -5
  37. package/dist/core/extract-step.js +40 -6
  38. package/dist/core/extract-swift.js +47 -3
  39. package/dist/core/extract.d.ts +8 -0
  40. package/dist/core/infer.d.ts +8 -0
  41. package/dist/core/infer.js +133 -16
  42. package/dist/core/jvm/Harness.java +135 -3
  43. package/dist/core/jvm/Rt.java +66 -4
  44. package/dist/core/laws.js +51 -10
  45. package/dist/core/native-law.d.ts +3 -1
  46. package/dist/core/native-law.js +126 -14
  47. package/dist/core/native-observations.d.ts +20 -0
  48. package/dist/core/native-observations.js +41 -0
  49. package/dist/core/native-wire.d.ts +1 -0
  50. package/dist/core/native-wire.js +16 -2
  51. package/dist/core/py/harness.py +21 -4
  52. package/dist/core/rb/harness.rb +178 -9
  53. package/dist/core/search-termination.d.ts +35 -0
  54. package/dist/core/search-termination.js +13 -0
  55. package/dist/core/search-watchdog.d.ts +8 -0
  56. package/dist/core/search-watchdog.js +34 -0
  57. package/dist/core/source-check.d.ts +3 -0
  58. package/dist/core/swift/Harness.swift +65 -4
  59. package/dist/core/swift/Main.swift +27 -4
  60. package/dist/core/wall.d.ts +3 -1
  61. package/dist/core/wall.js +7 -4
  62. package/dist/core/work-refusal.d.ts +3 -0
  63. package/dist/core/work-refusal.js +8 -0
  64. package/dist/kernel/prove.d.ts +2 -0
  65. package/dist/kernel/prove.js +13 -5
  66. package/docs/agent-consult-workspace-check.md +118 -0
  67. package/docs/agent-consult.md +151 -0
  68. package/examples/agent-consult.json +22 -0
  69. package/package.json +11 -3
@@ -0,0 +1,13 @@
1
+ export const searchContext = (v) => v.context ?? ({
2
+ ...(v.goal === undefined ? {} : { goal: v.goal }), ...(v.stuck === undefined ? {} : { stuck: v.stuck }),
3
+ ...(v.why === undefined ? {} : { why: v.why }), ...(v.witness === undefined ? {} : { witness: v.witness }),
4
+ });
5
+ export const terminationWhy = (t) => `${t.kind === 'wall-deadline' ? 'wall deadline reached' : 'counted work exhausted'} (${t.phase}${t.scope === 'stage' ? '; stage allowance' : ''})`;
6
+ // Terminal evidence of source refusal, never permission to publish a proof.
7
+ // In particular, neither a generic unknown nor interrupted source checking is
8
+ // completed merely because its mathematical part once succeeded.
9
+ export const completedSourceRefusal = (v) => !!v && v.proven === false && v.checked === false && v.kernelProven === true &&
10
+ (v.translation === 'unchecked' || v.translation === 'error') &&
11
+ v.stopped === undefined && v.termination === undefined && !v.stats?.stopped && v.stats?.termination === undefined;
12
+ export const completedSearch = (v) => !!v && (v.proven && v.checked || v.run !== undefined || completedSourceRefusal(v));
13
+ export const stoppedSearch = (v, termination) => ({ ...v, stopped: true, termination, context: searchContext(v), why: terminationWhy(termination) });
@@ -0,0 +1,8 @@
1
+ import type { SearchTermination } from './search-termination.js';
2
+ export declare class WatchdogExpired extends Error {
3
+ readonly termination: SearchTermination;
4
+ constructor(phase: string);
5
+ }
6
+ export declare function withSearchWatchdog<T>(ms: number | undefined, run: () => T): T;
7
+ export declare function checkWatchdog(phase: string): void;
8
+ export declare function validateWatchdog(ms: number | undefined): void;
@@ -0,0 +1,34 @@
1
+ let watchdogEnd = Infinity;
2
+ export class WatchdogExpired extends Error {
3
+ termination;
4
+ constructor(phase) {
5
+ super(`wall deadline reached (${phase}; explicit watchdog)`);
6
+ this.name = 'WatchdogExpired';
7
+ this.termination = { kind: 'wall-deadline', phase, scope: 'search' };
8
+ }
9
+ }
10
+ export function withSearchWatchdog(ms, run) {
11
+ validateWatchdog(ms);
12
+ const outer = watchdogEnd;
13
+ if (ms !== undefined)
14
+ watchdogEnd = Math.min(outer, performance.now() + ms);
15
+ try {
16
+ checkWatchdog('search preflight');
17
+ const out = run();
18
+ if (out !== null && (typeof out === 'object' || typeof out === 'function') && typeof out.then === 'function')
19
+ throw new TypeError('search watchdog scope requires a synchronous callback');
20
+ checkWatchdog('search result');
21
+ return out;
22
+ }
23
+ finally {
24
+ watchdogEnd = outer;
25
+ }
26
+ }
27
+ export function checkWatchdog(phase) {
28
+ if (watchdogEnd !== Infinity && performance.now() >= watchdogEnd)
29
+ throw new WatchdogExpired(phase);
30
+ }
31
+ export function validateWatchdog(ms) {
32
+ if (ms !== undefined && (!Number.isFinite(ms) || ms < 0))
33
+ throw new RangeError('watchdogMs must be finite and nonnegative');
34
+ }
@@ -1,3 +1,4 @@
1
+ import type { NativeExecutionObservation } from './native-observations.js';
1
2
  export type Translation = 'exhaustive' | 'sampled' | 'unchecked' | 'error';
2
3
  export type NativeObservation = {
3
4
  where: string;
@@ -11,6 +12,8 @@ export type NativeObservation = {
11
12
  result: unknown;
12
13
  failed: boolean;
13
14
  legacyResult?: boolean;
15
+ observed?: NativeExecutionObservation;
16
+ nativeEquality?: 'scalar';
14
17
  };
15
18
  export type NativeJournal = {
16
19
  enabled: boolean;
@@ -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
@@ -0,0 +1,118 @@
1
+ # Workspace `check`
2
+
3
+ Use `check` to read laws from a trusted Python or plain TypeScript/JavaScript
4
+ workspace through the same engine as the CLI. The default remains data-only;
5
+ filesystem access requires explicit server configuration.
6
+
7
+ The native edit/check fixture exercises both Python and TypeScript through the
8
+ built Node MCP server: a bounded implementation is proven, a conservative edit
9
+ remains proven, and a bad edit is broken with a real run. These results retain
10
+ `translation: sampled`; they are not exhaustive native equivalence certificates.
11
+
12
+ ## Server-owned authority; data-only default
13
+
14
+ `createConsultation()` and the stdio executable with no root configuration keep
15
+ the old data-only default. All six tools are listed; `check` returns the typed
16
+ `workspace-unconfigured` refusal until the server explicitly opts in:
17
+
18
+ ```ts
19
+ import {createConsultation} from 'gdp-wired/agent-consult'
20
+
21
+ const session = createConsultation({workspaceRoots: ['/absolute/trusted/project']})
22
+ const receipt = await session.call('check', {
23
+ file: '/absolute/trusted/project/counter.py',
24
+ budget: {work: 5000000, apiCalls: 64, candidates: 2}
25
+ })
26
+ ```
27
+
28
+ For the stdio server, the operator sets `GDP_AGENT_CONSULT_ROOTS` to a JSON array
29
+ of absolute directories in its startup environment. CLI arguments still cannot
30
+ choose roots, source modules, flags or interpreters. Root configuration is never
31
+ accepted in tool arguments, including nested `options`, `root`, `roots`, `python`
32
+ or `workspaceRoots`. The existing five tools remain data-only.
33
+
34
+ The server canonicalizes/freezes at most16 roots once. Requests must name absolute
35
+ local regular files (no URLs, directories, devices, relative paths or `..`).
36
+ Containment uses `path.relative`, not a string prefix. Both root and file symlinks
37
+ are realpathed; out-of-root results and sibling-prefix paths are refused. Source
38
+ reads used by the guard use a no-follow/nonblocking read-only FD and fstat; each
39
+ file is capped at128KiB. Root dev/inode and file identity/content are rechecked
40
+ before/after the pipeline; source and relative TS dependency hashes bind the
41
+ returned revision. Replacements or edits observed during a check refuse rather
42
+ than silently bind another revision.
43
+
44
+ **Not an OS sandbox:** the configured root is a trust grant to execute the existing
45
+ extractor/runtime/project code. Python may import dependencies; TypeScript native
46
+ replay may execute code. Those runtimes can read dependencies and access resources
47
+ outside the root with the worker's OS permissions. No claim of transitive import
48
+ confinement, hostile-code containment, or atomic filesystem snapshots is made.
49
+ An adversarial process can race mutable files between rechecks. Use a stable,
50
+ trusted checkout and externally enforced OS isolation for untrusted code. Cancellation
51
+ joins the direct worker; this is not a descendant-process sandbox/reaper guarantee.
52
+ No arbitrary shell launcher is added; only the installed fixed-path worker runs.
53
+
54
+ ## Shared engine, explicit initial scope
55
+
56
+ `packages/cli/bin.js` delegates to `core/cli.ts`. The latter now has one generator
57
+ pipeline for entry enumeration, initializer expansion, laws, proof/replay and
58
+ proposals. Ordinary CLI calls drive it asynchronously; workspace check preloads
59
+ Python/plainTS extractor modules as initialization and then drives that **same**
60
+ pipeline synchronously inside the counted root. No copied extraction/proof engine
61
+ and no `withBudget(Promise)`.
62
+
63
+ Supported initially: Python and plain TypeScript/JavaScript (`.py`, `.ts`, `.mts`,
64
+ `.tsx`, `.js`, `.mjs`). Effect/XState, async lemma expansion and other CLI language
65
+ frontends are explicitly refused. The initial workspace profile does **not** read
66
+ project GDP configuration: no ancestor search, no config-specified interpreters,
67
+ root overrides, certificate writes or CLI switches. Ordinary CLI defaults/config
68
+ behavior remain unchanged. Rules needing config receive the extractor's refusal
69
+ or unknown rather than substituted modeling choices.
70
+
71
+ The returned `result.rules` is the existing structured CLI `RuleOut[]`: stated
72
+ laws, refusal reasons, replayed runs where available, and proposals with paste-ready
73
+ language comments in `where`. `proven` requires a nonempty stated law set all
74
+ reported proven by that engine; `broken` requires a stated broken law with a real
75
+ run; otherwise the aggregate is `unknown` with a reason. Each rule/law retains its
76
+ own detailed verdict. `check` does not populate the scalar-model `status` registry.
77
+
78
+ **Evidence boundary:** a model-only result with `translation: unchecked` remains
79
+ unknown even when `kernelProven: true`. When the existing engine supplies a native
80
+ law journal, its `sampled` or `exhaustive` profile and observation count are retained.
81
+ The current Python/TypeScript demo uses sampled journals. A checked symbolic proof
82
+ plus sampled native observations does not establish universal source equivalence.
83
+ This adapter neither upgrades unchecked results nor invents counterexample runs.
84
+
85
+ ## Budget coverage
86
+
87
+ One `withBudget` root and sticky capacity-refusal boundary surround synchronous
88
+ extraction, law parsing, proofs, replay, proposals, source receipt construction and
89
+ serialization validation. Each extraction and top-level proof/step/liveness/two-run
90
+ API call is admitted against `apiCalls`. API exhaustion is also sticky, so existing
91
+ CLI catch-and-return-unknown handlers cannot turn exhaustion into a successful
92
+ partial proof receipt. Proposal candidates are finite and capped by the request
93
+ hint (at most40); CLI wall-clock stops/telemetry are disabled only for this counted
94
+ synchronous path. Ordinary CLI wall behavior is unchanged.
95
+
96
+ Exact work/counter deltas and profile identity are retained. Counted work means
97
+ **existing engine sinks**, not CPU instructions: module initialization, filesystem
98
+ bytes/identity/hash operations, unmetered frontend parsing, external interpreter
99
+ runtime and project execution are not charged to the work vector. Source-byte and
100
+ API caps are separate controls. These exclusions are explicit in every source
101
+ budget receipt; external runtime is not misrepresented as counted work.
102
+
103
+ ## Development checks
104
+
105
+ After normal dependency preparation, run these checks in the project's test environment:
106
+
107
+ 1. `bunx tsc -p core/agent-consult/tsconfig.json --noEmit`
108
+ 2. `GDP_WORK_FULL=1 bun test core/agent-consult/workspace.test.ts core/agent-consult.test.ts research/agent-tools/protocol.test.ts research/agent-tools/service.test.ts`
109
+ 3. The existing CLI, budget ownership, watchdog and package regression suites.
110
+ 4. `bun scripts/build.ts`
111
+ 5. `node scripts/agent-consult-workspace-demo.mjs > "$SUPERCOMPUTER_OUTPUT_DIR/workspace-check-transcript.jsonl"`
112
+
113
+ The last command creates temporary Python and TS files, initializes/lists the
114
+ built Node MCP server, edits each through good/good-edit/bad versions, and logs
115
+ actual edit/request/response/observation JSONL. It requires successful extraction,
116
+ changing source revisions, sampled native-law observations for the good edits,
117
+ and real runs for the bad edits. The server must close cleanly after stdin EOF.
118
+ The workspace suite is also registered in the default CI test roster.
@@ -0,0 +1,151 @@
1
+ # Agent consultation: MCP and library
2
+
3
+ The supported adapter asks the **existing** gdp-wired engines whether a scalar-natural
4
+ model law has a checked proof, a reachable counterexample, or a missing inductive
5
+ invariant. It adds no inference/proof algorithm. This is a package integration, not
6
+ a new proof capability or a native/source-conformance certification. The counted
7
+ work profile is still provisional research machinery. Do not use `ok: true` alone
8
+ as a proof: require each relevant `proven === true && checked === true`.
9
+
10
+ ## Start and configure
11
+
12
+ After installing a version of `gdp-wired` containing this surface (this change does
13
+ not publish one), run `gdp-wired-agent-consult`. Node >=20 is sufficient; no Bun,
14
+ MCP SDK, credentials, network service or model provider is needed for the data-only tools.
15
+ Opt-in workspace extraction additionally needs TypeScript beside the package and the
16
+ source language runtime (Python for `.py`), exactly as the CLI does. In a source checkout the equivalent is
17
+ `bun core/agent-consult/cli.ts`; build with the repository's normal build before
18
+ running `node dist/core/agent-consult/cli.js`.
19
+
20
+ Generic MCP client configuration (configure your client explicitly; nothing is
21
+ registered automatically):
22
+
23
+ ```json
24
+ {
25
+ "mcpServers": {
26
+ "gdp-wired": {
27
+ "command": "/absolute/path/to/node",
28
+ "args": ["/absolute/path/to/node_modules/gdp-wired/dist/core/agent-consult/cli.js"]
29
+ }
30
+ }
31
+ }
32
+ ```
33
+
34
+ Use an explicitly installed/pinned package; avoid an unpinned runtime download.
35
+ The CLI accepts **no arguments**, roots, modules, file paths or source code. It
36
+ reads newline-delimited JSON-RPC 2.0 MCP (protocol `2024-11-05`) on stdin; stdout is
37
+ protocol JSON only. `initialize`, `ping`, `tools/list`, `tools/call` are supported.
38
+ Results include both `structuredContent` and equivalent JSON text for older clients.
39
+ No HTTP transport, resources, prompts, dynamic roots or persistent database is provided.
40
+ The server name is now `gdp-wired-agent-consult` (formerly the research prototype's
41
+ `gdp-wired-agent-tools-prototype`). The original five tools and their v1 schemas
42
+ are preserved; the additional `check` tool has an explicit workspace trust boundary.
43
+
44
+ Workspace checking is a separate server-authorized opt-in: see
45
+ [workspace check trust/budget contract and native demo](agent-consult-workspace-check.md).
46
+ With no configured roots, `check` refuses and the original data-only default remains.
47
+
48
+ ## Agent reasoning loop
49
+
50
+ 1. Translate the rule and law faithfully to **data**, never a module to execute.
51
+ [examples/agent-consult.json](../examples/agent-consult.json) is a complete
52
+ `tools/call` request for a capped budget. Read `tools/list` for recursive schemas.
53
+ 2. `prove {subject,laws,budget?}` returns per-law checked inductive verdicts.
54
+ A failed induction step can be an unreachable state: it is not a real bug yet.
55
+ 3. `why_not {subject,laws,budget?}` asks existing finite search for a reachable,
56
+ interpreter-checked trace. Original parameter/input/state names are preserved.
57
+ No trace **does not** establish a law. Trace minimality is length-first only
58
+ inside the reported finite domain, not global minimality.
59
+ 4. If no real trace explains the failed proof, use
60
+ `suggest {subject,laws,nearMisses?,budget?}`. Existing `inferLaws` proposes helper
61
+ invariants; only jointly checked support sets are returned as `discovered`.
62
+ Keep `supportSource` with the goal; do not paste a helper while dropping the
63
+ laws that support it. A missing invariant is not inferred from silence alone.
64
+ `nearMisses` are caller-supplied candidates, not generated language-model laws;
65
+ a returned near miss includes a real trace. `unresolvedNearMisses` are unknown.
66
+ 5. `check_change {before,after,laws,budget?}` rechecks the same laws on revisions
67
+ with identical unit, parameter, input and state names. `newlyBroken` requires
68
+ an old checked proof plus a new reachable trace. `lostProof` is separate.
69
+ Behaviour comparison is **directional refinement under the after rule's
70
+ precondition**, using existing compose and both invariant/admissibility checks;
71
+ it is not bidirectional/source equivalence.
72
+ 6. `status {unit,revision}` uses the digest returned by a computational request.
73
+ It never accepts labels supplied by a caller, substitutes another revision,
74
+ or invents native evidence. Only `prove`/`check_change` populate its registry.
75
+ `nativeLabel` is null. Unknown/evicted revisions return `missing-evidence`.
76
+
77
+ A `subject` is `{unit,rule}`. Rule data includes `name`, `params`, `inputs`,
78
+ initial `state`, `step.state`, optional `pre` and `assume`; laws are `{name,holds}`.
79
+ Terms: `var`, `const`, `add`, **truncated natural `sub`**, `min`, `max`, constant
80
+ `mul`, `if`. Conditions: `<`, `<=`, `=`, `and`, `or`, `not`. Signed values, maps,
81
+ functions, quantification, callbacks, source, modules, paths and URLs are refused by
82
+ the five data-only tools, not approximated. `check` alone accepts a local file path. Outputs include `assumptions`: exact initial/pre/request data
83
+ and laws bound into the revision. Retain those alongside proofs and suggestions.
84
+ A model proof does not assert the shipping program matches that model.
85
+
86
+ ## Library
87
+
88
+ ```ts
89
+ import {createConsultation} from 'gdp-wired/agent-consult'
90
+ const session = createConsultation()
91
+ try {
92
+ const receipt = await session.call('prove', {subject, laws, budget: {work: 500000}})
93
+ // Inspect receipt; only checked proof pairs establish model laws.
94
+ const explained = await session.call('why_not', {subject, laws})
95
+ } finally {
96
+ await session.close()
97
+ }
98
+ ```
99
+
100
+ `call(tool,args,{signal?})` returns the structured data envelope.
101
+ `handle(jsonRpcRequest,{signal?})` returns a JSON-RPC response (or null for a
102
+ notification). Both serialize work per session. No engine is imported into the
103
+ host: each computational request uses a fresh installed worker with a fixed path
104
+ and sanitized environment. Status is session-local, bounded to256 revisions
105
+ (oldest entries evicted); a new session has no evidence. Importing the subpath
106
+ starts no server, worker, signal handler or stdin listener.
107
+
108
+ `AbortSignal` cancels library requests; `close()` cancels the active worker and
109
+ refuses queued tool calls; await its returned promise to join the exact child exit. On stdio, SIGINT/SIGTERM or closed stdin shuts down the
110
+ server and its own worker. MCP cancellation notifications are currently ignored;
111
+ use process termination to cancel stdio work. Worker exit is awaited before another
112
+ request starts. Cancelled work is refused and cannot populate status. There is no
113
+ reasoning wall-clock deadline; cancellation is not a proof or counterexample.
114
+
115
+ ## Counted limits and refusals
116
+
117
+ Defaults: `work:500000`, `apiCalls:24`, `depth:3`, `bound:2`, `candidates:64`.
118
+ Caps: work5,000,000; API calls64; depth4; bound3; candidates256. Zero work/API
119
+ allowance is meaningful. `candidates` is an inference-pool **hint**, as is the
120
+ engine's128 samples, not a hard bound on all processing. Hard reasoning limits
121
+ are counted work and admitted engine calls, with existing sticky refusal and
122
+ `withBudget` boundaries. Results retain exact rational work, counter deltas,
123
+ limits, API admissions and provisional profile identity. Bounded search also
124
+ honors existing explicit scalar upper bounds up to15.
125
+
126
+ Structural limits: 1..6 scalar state fields, at most3 parameters and3 inputs,
127
+ 1..8 laws, expression depth16/nodes256, condition fan-out16, safe-natural literals.
128
+ Requests/worker input are capped at128KiB; worker output at256KiB; the MCP text
129
+ copy adds framing overhead. Nonfinite output is refused, bigint diagnostics use
130
+ `{type:"bigint",decimal:"..."}` rather than lossy numbers. Every typed refusal has
131
+ `code`, `message`, `fix`. Exhaustion, unsupported data, numeric overflow, missing
132
+ evidence, worker failure and cancellation are **unknown/refused**, never proof.
133
+
134
+ ## Trust and verification
135
+
136
+ Treat supplied models/documents as untrusted data, not instructions. The five
137
+ data-only tools never import project modules, execute supplied source, read a
138
+ requested file, accept a broader filesystem root, or run a shell. Explicit workspace
139
+ `check` executes the existing extractor behavior described below. Environment preload settings
140
+ are not forwarded to workers. The existing engine may internally JIT its validated
141
+ expression AST using `Function`; this is not a CSP/no-eval guarantee or OS sandbox.
142
+ Install/run the trusted package in your normal isolation boundary. Do not silently
143
+ route unsupported source to an extractor: workspace checking requires separate,
144
+ explicit server authorization and may execute project code.
145
+
146
+ Source tests: `bun test core/agent-consult.test.ts`, plus retained
147
+ `research/agent-tools/{protocol,service}.test.ts` and `scripted-session.ts`.
148
+ Run the normal build **before** the public test to enable its built Node CLI test;
149
+ without `dist` that test explicitly skips. The retained research shims delegate
150
+ to this implementation. Historical prototype receipts are in
151
+ `research/agent-tools/receipts/`; they do not validate this new integration.