gdp-wired 0.56.0 → 0.56.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { serveStdio } from "./session.js";
3
3
  // No tool/CLI flags accept roots or interpreters. Only trusted server startup environment configures roots.
4
+ process.exitCode = 2;
5
+ let settled = false, reported = false;
6
+ const onUnsettled = (ev) => { if (settled || reported)
7
+ return; reported = true; process.exitCode = 2; process.stderr.write(`gdp-wired: the check did not complete (${ev})\n`); };
8
+ process.on('beforeExit', () => onUnsettled('beforeExit'));
9
+ process.on('exit', () => onUnsettled('exit'));
4
10
  if (process.argv.length > 2) {
11
+ settled = true;
5
12
  process.stderr.write('Usage: gdp-wired-agent-consult (stdio MCP; accepts no arguments)\n');
6
13
  process.exitCode = 2;
7
14
  }
@@ -11,8 +18,12 @@ else {
11
18
  if (!Array.isArray(configured) || !configured.every(p => typeof p === 'string'))
12
19
  throw Error('GDP_AGENT_CONSULT_ROOTS must be a JSON array of trusted absolute directories');
13
20
  await serveStdio({ workspaceRoots: configured });
21
+ settled = true;
22
+ if (process.exitCode === 2)
23
+ process.exitCode = 0;
14
24
  }
15
25
  catch (e) {
26
+ settled = true;
16
27
  process.stderr.write(String(e) + '\n');
17
28
  process.exitCode = 1;
18
29
  }
@@ -1,5 +1,11 @@
1
1
  import { execute, failure } from "./service.js";
2
2
  import { wireJSON } from "./protocol.js";
3
+ process.exitCode = 2;
4
+ let settled = false, reported = false;
5
+ const onUnsettled = (ev) => { if (settled || reported)
6
+ return; reported = true; process.exitCode = 2; process.stderr.write(`gdp-wired: the check did not complete (${ev})\n`); };
7
+ process.on('beforeExit', () => onUnsettled('beforeExit'));
8
+ process.on('exit', () => onUnsettled('exit'));
3
9
  let data = '';
4
10
  try {
5
11
  for await (const chunk of process.stdin) {
@@ -10,8 +16,11 @@ try {
10
16
  const request = JSON.parse(data);
11
17
  const value = request.tool === 'check' ? await (await import("./source-service.js")).executeSource(request.args, request.roots ?? []) : execute(request.tool, request.args);
12
18
  process.stdout.write(wireJSON(value) + '\n');
19
+ settled = true;
20
+ process.exitCode = 0;
13
21
  }
14
22
  catch (e) {
23
+ settled = true;
15
24
  process.stdout.write(wireJSON(failure('worker', e)) + '\n');
16
25
  process.exitCode = 1;
17
26
  }
@@ -111,4 +111,8 @@ export declare function check(targets: string[], given?: Partial<Opts>, each?: (
111
111
  exit: number;
112
112
  }>;
113
113
  export declare function main(argv: string[]): Promise<number>;
114
+ export declare function runCli(argv?: string[], opts?: {
115
+ label?: string;
116
+ run?: (argv: string[]) => Promise<number>;
117
+ }): void;
114
118
  export {};
package/dist/core/cli.js CHANGED
@@ -28,6 +28,7 @@ import { contend, envOf, inEnv, shrinkRun } from "./system.js";
28
28
  const proc = globalThis.process;
29
29
  const fs = proc.getBuiltinModule('node:fs'), path = proc.getBuiltinModule('node:path');
30
30
  const out = (s = '') => proc.stdout.write(`${s}\n`);
31
+ const err = (s) => (proc.stderr ?? proc.stdout).write(`${s}\n`);
31
32
  // Color, plain ANSI: only on a terminal, never with --json, NO_COLOR (any value) or TERM=dumb; FORCE_COLOR turns it on.
32
33
  // Uncolored, the text is the same byte for byte.
33
34
  export const colors = (env, tty, json = false) => !json && (env.FORCE_COLOR !== undefined && !['0', 'false'].includes(env.FORCE_COLOR) ? true : env.NO_COLOR === undefined && env.TERM !== 'dumb' && tty);
@@ -1476,7 +1477,7 @@ export async function check(targets, given = {}, each) {
1476
1477
  const safetyLookalike = all.some(r => r.notes.some(n => SAFETY_LOOKALIKE_NOTE_RE.test(n)));
1477
1478
  const uncheckedSafety = safetyLookalike || all.some(r => r.safety && ('why' in r.safety || r.safety.status === 'unchecked' || r.safety.status === 'unproven'));
1478
1479
  const brokenSafety = all.some(r => r.safety && !('why' in r.safety) && r.safety.status === 'broken');
1479
- return { rules: all, exit: uncheckedSafety || stated.some(l => l.verdict === 'unknown' || l.translation === 'unchecked' || l.translation === 'error') ? 2 : brokenSafety || stated.some(l => l.verdict === 'broken') ? 1 : stated.some(l => l.verdict === 'not read') || o.security && all.some(r => !r.ok) ? 2 : 0 };
1480
+ return { rules: all, exit: uncheckedSafety || stated.some(l => l.verdict === 'unknown' || l.translation === 'unchecked' || l.translation === 'error') ? 2 : brokenSafety || stated.some(l => l.verdict === 'broken') ? 1 : stated.some(l => l.verdict === 'not read' || l.verdict !== 'proven') || o.security && all.some(r => !r.ok) ? 2 : 0 };
1480
1481
  }
1481
1482
  // --- draft: laws from a clause, for a person to review ----------------------------------------------------------------
1482
1483
  // gdp-wired draft <file> --clause <text> | --clause-file <f> --cite <ref> [--llm <command> | --answer <file>] [--by <who>]:
@@ -1559,8 +1560,18 @@ export async function main(argv) {
1559
1560
  }
1560
1561
  return code;
1561
1562
  }
1562
- if (import.meta.url === `file://${proc.argv[1]}` || /\/(cli\.(ts|js)|gdp-wired)$/.test(proc.argv[1] ?? '')) {
1563
- let sigExiting = false;
1563
+ export function runCli(argv = proc.argv.slice(2), opts = {}) {
1564
+ const label = opts.label ?? 'gdp-wired', run = opts.run ?? main;
1565
+ let settled = false, reported = false, sigExiting = false;
1566
+ // Fail-safe: never exit 0 unless main() resolves and authorizes the final code.
1567
+ proc.exitCode = 2;
1568
+ const onUnsettled = (why) => {
1569
+ if (settled || sigExiting || reported)
1570
+ return;
1571
+ reported = true;
1572
+ proc.exitCode = 2;
1573
+ err(`gdp-wired: the check did not complete (${why})`);
1574
+ };
1564
1575
  const onSignal = (code) => () => {
1565
1576
  if (sigExiting)
1566
1577
  return;
@@ -1570,6 +1581,27 @@ if (import.meta.url === `file://${proc.argv[1]}` || /\/(cli\.(ts|js)|gdp-wired)$
1570
1581
  };
1571
1582
  proc.on?.('SIGINT', onSignal(130));
1572
1583
  proc.on?.('SIGTERM', onSignal(143));
1573
- proc.on?.('exit', () => { cleanupCSafetySnapshots(); });
1574
- main(proc.argv.slice(2)).then(c => { proc.exitCode = c; }, e => { out(`gdp-wired: ${e.message}`); proc.exitCode = 2; });
1584
+ proc.on?.('beforeExit', () => { onUnsettled('main did not settle before process exit'); });
1585
+ proc.on?.('exit', () => { cleanupCSafetySnapshots(); onUnsettled('process exited before main settled'); });
1586
+ let pending;
1587
+ try {
1588
+ pending = run(argv);
1589
+ }
1590
+ catch (e) {
1591
+ settled = true;
1592
+ out(`${label}: ${e instanceof Error ? e.message : String(e)}`);
1593
+ proc.exitCode = 2;
1594
+ return;
1595
+ }
1596
+ pending.then(c => {
1597
+ settled = true;
1598
+ proc.exitCode = typeof c === 'number' && Number.isInteger(c) ? c : 2;
1599
+ }, e => {
1600
+ settled = true;
1601
+ out(`${label}: ${e instanceof Error ? e.message : String(e)}`);
1602
+ proc.exitCode = 2;
1603
+ });
1604
+ }
1605
+ if (import.meta.url === `file://${proc.argv[1]}` || /\/(cli\.(ts|js)|gdp-wired)$/.test(proc.argv[1] ?? '')) {
1606
+ runCli(proc.argv.slice(2));
1575
1607
  }
@@ -92,6 +92,67 @@ export function instrument(code, file, tail = '', extra = []) {
92
92
  const js = ts.transpileModule(out, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true, jsx: ts.JsxEmit.React }, fileName: file.replace(/\.js$/, '.ts').replace(/\.jsx$/, '.tsx') }).outputText;
93
93
  return { js, arms };
94
94
  }
95
+ // Cooperative deadline instrumentation for Bun, where node:vm's `timeout` option leaks a watchdog timer that can kill
96
+ // later host JavaScript on affected versions (e.g. Bun 1.3.14). Node keeps node:vm's native timeout unchanged.
97
+ const isBun = typeof globalThis.Bun !== 'undefined';
98
+ class SandboxTimeout extends Error {
99
+ code = 'ERR_SCRIPT_EXECUTION_TIMEOUT';
100
+ constructor(ms) { super(`Script execution timed out after ${ms}ms`); }
101
+ }
102
+ function instrumentTicks(js, file) {
103
+ const sf = ts.createSourceFile(file, js, ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
104
+ const edits = [];
105
+ const isLoop = (n) => ts.isForStatement(n) || ts.isForInStatement(n) || ts.isForOfStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n);
106
+ const isFn = (n) => ts.isFunctionDeclaration(n) || ts.isFunctionExpression(n) || ts.isMethodDeclaration(n) ||
107
+ ts.isGetAccessorDeclaration(n) || ts.isSetAccessorDeclaration(n) || ts.isConstructorDeclaration(n) || ts.isArrowFunction(n);
108
+ const blockInsert = (b) => {
109
+ const start = b.getStart(sf) + 1;
110
+ let pos = start;
111
+ for (const st of b.statements) {
112
+ if (ts.isExpressionStatement(st) && ts.isStringLiteral(st.expression))
113
+ pos = st.end;
114
+ else
115
+ break;
116
+ }
117
+ return [pos, pos > start ? ';__gdp_tick();' : '__gdp_tick();'];
118
+ };
119
+ const visit = (n) => {
120
+ if (isLoop(n)) {
121
+ const body = n.statement;
122
+ if (ts.isBlock(body)) {
123
+ edits.push([body.getStart(sf) + 1, '__gdp_tick();']);
124
+ ts.forEachChild(n, visit);
125
+ }
126
+ else {
127
+ edits.push([body.getStart(sf), '{__gdp_tick();']);
128
+ ts.forEachChild(n, visit);
129
+ edits.push([body.end, '}']);
130
+ }
131
+ return;
132
+ }
133
+ if (isFn(n) && n.body) {
134
+ if (ts.isBlock(n.body)) {
135
+ edits.push(blockInsert(n.body));
136
+ ts.forEachChild(n, visit);
137
+ }
138
+ else {
139
+ edits.push([n.body.getStart(sf), '(__gdp_tick(), (']);
140
+ ts.forEachChild(n, visit);
141
+ edits.push([n.body.end, '))']);
142
+ }
143
+ return;
144
+ }
145
+ ts.forEachChild(n, visit);
146
+ };
147
+ visit(sf);
148
+ if (!edits.length)
149
+ return js;
150
+ const order = edits.map((e, i) => [...e, i]).sort((a, b) => b[0] - a[0] || b[2] - a[2]);
151
+ let out = js;
152
+ for (const [pos, txt] of order)
153
+ out = out.slice(0, pos) + txt + out.slice(pos);
154
+ return out;
155
+ }
95
156
  export function sandbox(code, file, expose, modules = {}, init, files = {}, extra = [], nativeMethods = []) {
96
157
  const vm = vmOf();
97
158
  // A final arrow can end exactly where a factory appends fields. Its capture
@@ -100,6 +161,19 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
100
161
  const captured = new Map(), captureErrors = new Map();
101
162
  const counts = arms.map(() => 0);
102
163
  let now = 0, invocation = 0, observedClock, observing = false;
164
+ let ticks = 0, deadline = Infinity, limitMs = 0, timedOut = false;
165
+ const startBudget = (ms) => { ticks = 0; limitMs = ms; timedOut = false; deadline = performance.now() + ms; };
166
+ const stopBudget = () => { deadline = Infinity; timedOut = false; };
167
+ const tick = () => {
168
+ if (timedOut)
169
+ throw new SandboxTimeout(limitMs);
170
+ if (deadline === Infinity)
171
+ return;
172
+ if ((++ticks & 15) === 0 && performance.now() >= deadline) {
173
+ timedOut = true;
174
+ throw new SandboxTimeout(limitMs);
175
+ }
176
+ };
103
177
  const stub = (name) => new Proxy({}, {
104
178
  get: (_, k) => { if (k === '__esModule' || typeof k === 'symbol')
105
179
  return undefined; throw new Error(`the check loads no module ${name} (its ${String(k)} was read)`); },
@@ -125,6 +199,8 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
125
199
  require: (name) => (name in modules ? modules[name] : name.startsWith('.') && Object.keys(files).length ? load(ENTRY, name) : stub(name)),
126
200
  console: { log() { }, warn() { }, error() { }, info() { }, debug() { } },
127
201
  });
202
+ if (isBun)
203
+ Object.defineProperty(ctx, '__gdp_tick', { value: tick, writable: false, configurable: false, enumerable: false });
128
204
  // The files given, by their place beside the entry's; each loaded once.
129
205
  const ENTRY = `/v/${file.split('/').pop()}`, abs = Object.fromEntries(Object.entries(files).map(([p, c]) => [normalize(`/v/${p}`), c])), loaded = new Map();
130
206
  const load = (from, spec) => {
@@ -142,10 +218,13 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
142
218
  // A file that doesn't load here (it reads import.meta, a browser's globals): a stub that throws when read, so a step
143
219
  // that reads it fails the check rather than running without it.
144
220
  try {
145
- const f = vm.runInContext(`(function (module, exports, require) {${js}\n})`, ctx);
221
+ const body = isBun ? instrumentTicks(js, at) : js;
222
+ const f = vm.runInContext(`(function (module, exports, require) {${body}\n})`, ctx);
146
223
  f(m, m.exports, (s2) => (s2 in modules ? modules[s2] : s2.startsWith('.') ? load(at, s2) : stub(s2)));
147
224
  }
148
225
  catch (e) {
226
+ if (timedOut)
227
+ throw e;
149
228
  const st = stub(`${spec} (${e.message})`);
150
229
  loaded.set(at, st);
151
230
  return st;
@@ -155,8 +234,22 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
155
234
  };
156
235
  // The clock is the request's: Date.now() and new Date() read it.
157
236
  vm.runInContext('globalThis.Date = new Proxy(Date, {construct: (D, a) => (a.length ? new D(...a) : new D(__now())), get: (D, k) => (k === "now" ? () => __now() : D[k])}); Math.random = () => { throw new Error("Math.random in a step") }', ctx);
158
- vm.runInContext(`${js}\n;globalThis.__gdp = {${expose.map(n => { if (n === 'default')
159
- return 'default: module.exports.default'; const [h, ...rest] = n.split('.'); return `${JSON.stringify(n)}: (typeof ${h} !== 'undefined' ? ${h} : module.exports.${h})${rest.map(x => `.${x}`).join('')}`; }).join(', ')}};`, ctx, { timeout: 2000, filename: file });
237
+ const loadCode = `${isBun ? instrumentTicks(js, file) : js}\n;globalThis.__gdp = {${expose.map(n => { if (n === 'default')
238
+ return 'default: module.exports.default'; const [h, ...rest] = n.split('.'); return `${JSON.stringify(n)}: (typeof ${h} !== 'undefined' ? ${h} : module.exports.${h})${rest.map(x => `.${x}`).join('')}`; }).join(', ')}};`;
239
+ if (isBun) {
240
+ startBudget(2000);
241
+ try {
242
+ vm.runInContext(loadCode, ctx, { filename: file });
243
+ if (timedOut)
244
+ throw new SandboxTimeout(2000);
245
+ }
246
+ finally {
247
+ stopBudget();
248
+ }
249
+ }
250
+ else {
251
+ vm.runInContext(loadCode, ctx, { timeout: 2000, filename: file });
252
+ }
160
253
  const script = new vm.Script('globalThis.__r = (() => { try { return {ok: true, value: __gdp[__f].apply(__self, __args)} } catch (e) { return {ok: false, error: String(e && e.message || e)} } })()');
161
254
  const call = (f, self, args, housekeeping = false) => {
162
255
  // Reading/restoring a factory's closure is harness work, not a new request.
@@ -169,16 +262,35 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
169
262
  }
170
263
  observing = request;
171
264
  Object.assign(ctx, { __f: f, __self: self, __args: args });
172
- try {
173
- script.runInContext(ctx, { timeout: 1000 });
174
- }
175
- catch (e) {
176
- if (e.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT')
177
- throw new HarnessFailure(`a request ran past the check's 1000 ms (${e.message})`);
178
- throw e;
265
+ if (isBun) {
266
+ startBudget(1000);
267
+ try {
268
+ script.runInContext(ctx);
269
+ if (timedOut)
270
+ throw new SandboxTimeout(1000);
271
+ }
272
+ catch (e) {
273
+ if (timedOut || e.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT')
274
+ throw new HarnessFailure(`a request ran past the check's 1000 ms (${e.message})`);
275
+ throw e;
276
+ }
277
+ finally {
278
+ stopBudget();
279
+ observing = false;
280
+ }
179
281
  }
180
- finally {
181
- observing = false;
282
+ else {
283
+ try {
284
+ script.runInContext(ctx, { timeout: 1000 });
285
+ }
286
+ catch (e) {
287
+ if (e.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT')
288
+ throw new HarnessFailure(`a request ran past the check's 1000 ms (${e.message})`);
289
+ throw e;
290
+ }
291
+ finally {
292
+ observing = false;
293
+ }
182
294
  }
183
295
  return ctx.__r;
184
296
  };
@@ -13,10 +13,22 @@ import { checkDocument, decidedBy, goalsOf } from "./check.js";
13
13
  import { fromInterchange, toInterchange } from "./format.js";
14
14
  const proc = globalThis.process;
15
15
  const fs = proc.getBuiltinModule('node:fs');
16
+ proc.exitCode = 2;
17
+ let completed = false, reported = false;
18
+ const onUnsettled = (ev) => {
19
+ if (completed || reported)
20
+ return;
21
+ reported = true;
22
+ proc.exitCode = 2;
23
+ proc.stderr.write(`gdp-wired: the check did not complete (${ev})\n`);
24
+ };
25
+ proc.on?.('beforeExit', () => onUnsettled('beforeExit'));
26
+ proc.on?.('exit', () => onUnsettled('exit'));
16
27
  const args = proc.argv.slice(2), json = args.includes('--json'), gi = args.indexOf('--goals'), goalsOut = gi >= 0 ? args[gi + 1] : undefined;
17
28
  const files = args.filter((a, i) => !a.startsWith('--') && (gi < 0 || i !== gi + 1));
18
29
  if (!files.length || (gi >= 0 && !goalsOut)) {
19
30
  proc.stderr.write('usage: gdp-wired-check [--json] [--goals <out.json>] <file.json>... (- reads standard input)\n');
31
+ completed = true;
20
32
  proc.exit(2);
21
33
  }
22
34
  const read = (f) => JSON.parse(f === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(f, 'utf8'));
@@ -42,4 +54,5 @@ else
42
54
  for (const c of report.claims)
43
55
  say(` ${c.accepted ? 'accepted' : 'refused '} ${c.name}${c.why ? `: ${c.why}` : ''}`);
44
56
  }
57
+ completed = true;
45
58
  proc.exit(out.every(o => o.report.accepted) ? 0 : 1);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.56.0",
3
+ "version": "0.56.1",
4
4
  "description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
5
5
  "keywords": [
6
6
  "verification",