gdp-wired 0.56.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  }
@@ -94,9 +94,24 @@ export type RuleOut = {
94
94
  type SafetyReport = {
95
95
  why: string;
96
96
  } | CSafetyResult;
97
+ type LawOwner = {
98
+ file: string;
99
+ start: number;
100
+ end: number;
101
+ kind: 'class' | 'anon-class' | 'function' | 'var' | 'member' | 'file';
102
+ name?: string;
103
+ };
97
104
  type Scoped = LawText & {
98
105
  cls?: string;
99
106
  fn?: string;
107
+ owner?: LawOwner;
108
+ memberOwner?: {
109
+ file: string;
110
+ start: number;
111
+ end: number;
112
+ };
113
+ inBody?: boolean;
114
+ why?: string;
100
115
  };
101
116
  export declare function scoped(file: string): Scoped[];
102
117
  export declare function checkTarget(t: Target, o: Opts): Promise<RuleOut[]>;
@@ -111,4 +126,8 @@ export declare function check(targets: string[], given?: Partial<Opts>, each?: (
111
126
  exit: number;
112
127
  }>;
113
128
  export declare function main(argv: string[]): Promise<number>;
129
+ export declare function runCli(argv?: string[], opts?: {
130
+ label?: string;
131
+ run?: (argv: string[]) => Promise<number>;
132
+ }): void;
114
133
  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);
@@ -453,7 +454,18 @@ function* rulesOf(t, o, laws) {
453
454
  // (a function that is a request of a rule read, a C file's globals', is read with it)
454
455
  const evs = (x) => { const s = x.model?.inputs?.find(v => v.name === (x.names ?? []).find(n => n.role === 'method')?.rule)?.sort; return s?.k === 'choice' ? s.values ?? [] : []; };
455
456
  const have = new Set(got.flatMap(r => [r.entry, r.x.model?.name, r.x.initializers?.name, ...(r.x.ok ? [...(r.x.names ?? []).map(n => n.method), ...evs(r.x)] : [])].filter((n) => !!n)));
456
- const more = [...new Set(laws.map(l => l.cls ?? l.fn).filter((n) => !!n && !have.has(n)))];
457
+ const triedEntries = new Set(got.map(r => r.entry ?? r.x.model?.name).filter((n) => !!n));
458
+ const more = [...new Set(laws.flatMap(l => {
459
+ if (l.owner) {
460
+ if (got.some(r => ownsLaw(l, r)))
461
+ return [];
462
+ if (l.owner.kind === 'anon-class' || l.owner.kind === 'file' || !l.owner.name)
463
+ return [];
464
+ return triedEntries.has(l.owner.name) ? [] : [l.owner.name];
465
+ }
466
+ const n = l.cls ?? l.fn;
467
+ return n && !have.has(n) ? [n] : [];
468
+ }))];
457
469
  if (!more.length)
458
470
  return yield* expandInitializers(t, o, laws, got);
459
471
  const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, from: _fr, env: _e, ...flags } = o;
@@ -513,11 +525,13 @@ function* rulesOf0(t, o, laws) {
513
525
  if (given)
514
526
  return [yield* one(given)];
515
527
  if (t.lang === 'ts' || t.lang === 'cpp') {
516
- const code = t.files.map(f => fs.readFileSync(f, 'utf8')).join('\n');
517
- const re = t.lang === 'cpp' ? /^\s*(?:class|struct)\s+(\w+)\s*(?::[^{]*)?\{/gm : /export\s+(?:default\s+)?(?:abstract\s+)?class\s+(\w+)|export\s+(?:const|function)\s+(\w+)/g;
518
- // (C++: a class its source file defines methods of, `Alarm::detected(...) {`, declared in its header)
519
- const defs = t.lang === 'cpp' ? [...code.matchAll(/^[\w:<>*&\s]*?\b(\w+)::~?\w+\s*\([^;]*?\)\s*(?:const\s*)?(?::[^{;]*)?\{/gm)].map(m => m[1]) : [];
520
- const cands = [...new Set([...[...code.matchAll(re)].map(m => m[1] ?? m[2]), ...defs])];
528
+ const cands = t.lang === 'ts' ? tsExports(t.files) : (() => {
529
+ const code = t.files.map(f => fs.readFileSync(f, 'utf8')).join('\n');
530
+ const re = /^\s*(?:class|struct)\s+(\w+)\s*(?::[^{]*)?\{/gm;
531
+ // (C++: a class its source file defines methods of, `Alarm::detected(...) {`, declared in its header)
532
+ const defs = [...code.matchAll(/^[\w:<>*&\s]*?\b(\w+)::~?\w+\s*\([^;]*?\)\s*(?:const\s*)?(?::[^{;]*)?\{/gm)].map(m => m[1]);
533
+ return [...new Set([...[...code.matchAll(re)].map(m => m[1]), ...defs])];
534
+ })();
521
535
  const all = yield* manyOf(cands);
522
536
  const good = all.filter(r => r.x.ok);
523
537
  return good.length ? good : all.length ? all : [{ x: { ok: false, refusals: [{ where: t.at, what: 'no class or exported function to read: name the entry (--entry)' }], notes: [] } }];
@@ -542,6 +556,18 @@ function* rulesOf0(t, o, laws) {
542
556
  const fns = [...new Set(laws.filter(l => !l.cls && l.fn).map(l => l.fn))];
543
557
  return several.length || fns.length ? yield* manyOf([...several, ...fns]) : [first];
544
558
  }
559
+ const sameSpan = (a, b) => a.start >= 0 && path.resolve(a.file) === path.resolve(b.file) && a.start === b.start && a.end === b.end;
560
+ const ownsLaw = (l, r) => {
561
+ if (!l.owner)
562
+ return false;
563
+ const spans = r.x.declSpans;
564
+ if (spans?.length)
565
+ return spans.some(sp => sameSpan(l.owner, sp) || (!!l.memberOwner && sameSpan(l.memberOwner, sp)));
566
+ if (!r.x.ok && l.owner.kind !== 'anon-class' && l.owner.kind !== 'file' && l.owner.name) {
567
+ return (r.entry ?? r.x.model?.name) === l.owner.name;
568
+ }
569
+ return false;
570
+ };
545
571
  // (a class statement's name: its keyword at the start of a line, after modifiers; never a word in a comment)
546
572
  const classAt = (line) => {
547
573
  const m = /^\s*(?:(?:export|default|public|private|protected|internal|abstract|final|sealed|open|data|static|partial|pub(?:\([^)]*\))?|unsafe)\s+)*(?:class|struct|actor|defmodule|module|object|impl(?:<[^>]*>)?|record|interface|contract)\s+([\w.:]+)|^\s*type\s+(\w+)\s+struct\b/.exec(line.replace(/(#|\/\/).*$/, ''));
@@ -561,9 +587,273 @@ const declares = (code, open) => {
561
587
  const m = /^\s*(?:[A-Za-z_$][\w$]*\s+)*([A-Za-z_$][\w$]*)\s*(?:;|=(?![=>]))/.exec(code.slice(i + 1));
562
588
  return !!m && !/^(const|override|final|noexcept|volatile|default|delete)$/.test(m[1]);
563
589
  };
590
+ let cachedTS;
591
+ function loadTS() {
592
+ if (cachedTS)
593
+ return cachedTS;
594
+ const { createRequire } = proc.getBuiltinModule('node:module');
595
+ cachedTS = createRequire(import.meta.url)('typescript');
596
+ return cachedTS;
597
+ }
598
+ function tsExports(files) {
599
+ const ts = loadTS(), out = [];
600
+ const hasExport = (st) => !!(ts.canHaveModifiers(st) && ts.getModifiers(st)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword));
601
+ for (const f of files) {
602
+ const text = fs.readFileSync(f, 'utf8'), ext = path.extname(f).toLowerCase();
603
+ const kind = ext === '.tsx' ? ts.ScriptKind.TSX : ext === '.jsx' ? ts.ScriptKind.JSX : ext === '.js' || ext === '.mjs' || ext === '.cjs' ? ts.ScriptKind.JS : ts.ScriptKind.TS;
604
+ const sf = ts.createSourceFile(f, text, ts.ScriptTarget.ES2022, true, kind);
605
+ for (const st of sf.statements) {
606
+ if (!hasExport(st))
607
+ continue;
608
+ if ((ts.isClassDeclaration(st) || ts.isFunctionDeclaration(st)) && st.name)
609
+ out.push(st.name.text);
610
+ else if (ts.isVariableStatement(st))
611
+ for (const d of st.declarationList.declarations)
612
+ if (ts.isIdentifier(d.name))
613
+ out.push(d.name.text);
614
+ }
615
+ }
616
+ return [...new Set(out)];
617
+ }
618
+ function scopedTS(file, text, laws) {
619
+ if (!laws.length)
620
+ return [];
621
+ const ts = loadTS(), ext = path.extname(file).toLowerCase();
622
+ const kind = ext === '.tsx' ? ts.ScriptKind.TSX : ext === '.jsx' ? ts.ScriptKind.JSX : ext === '.js' || ext === '.mjs' || ext === '.cjs' ? ts.ScriptKind.JS : ts.ScriptKind.TS;
623
+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.ES2022, true, kind), lines = text.split('\n');
624
+ const propName = (n) => n && (ts.isIdentifier(n) || ts.isStringLiteral(n) || ts.isNumericLiteral(n)) ? n.text : undefined;
625
+ const unwrap = (n) => {
626
+ while (ts.isParenthesizedExpression(n) || ts.isAsExpression(n) || ts.isSatisfiesExpression(n))
627
+ n = n.expression;
628
+ return n;
629
+ };
630
+ const isCallableInit = (init) => {
631
+ if (!init)
632
+ return false;
633
+ const e = unwrap(init);
634
+ if (ts.isArrowFunction(e) || ts.isFunctionExpression(e))
635
+ return true;
636
+ if (ts.isCallExpression(e) && e.arguments.length >= 1) {
637
+ const first = unwrap(e.arguments[0]);
638
+ if (ts.isFunctionExpression(first) && first.asteriskToken) {
639
+ const callee = unwrap(e.expression), head = ts.isCallExpression(callee) ? unwrap(callee.expression) : callee;
640
+ if (ts.isPropertyAccessExpression(head) && (head.name.text === 'fn' || head.name.text === 'fnUntraced'))
641
+ return true;
642
+ }
643
+ }
644
+ return false;
645
+ };
646
+ const spanOf = (n) => ({ file, start: n.getStart(sf), end: n.end });
647
+ const declNameOf = (st) => {
648
+ if (ts.isClassDeclaration(st) || ts.isFunctionDeclaration(st))
649
+ return st.name?.text;
650
+ if (ts.isVariableDeclaration(st))
651
+ return ts.isIdentifier(st.name) ? st.name.text : undefined;
652
+ if (ts.isExportAssignment(st))
653
+ return 'default';
654
+ return undefined;
655
+ };
656
+ const varDeclOwner = (d) => {
657
+ const vName = ts.isIdentifier(d.name) ? d.name.text : undefined;
658
+ const isCls = !!(d.initializer && ts.isClassExpression(unwrap(d.initializer)));
659
+ const owner = { ...spanOf(d), kind: isCls ? 'class' : 'var', ...(vName ? { name: vName } : {}) };
660
+ return { ...(isCls && vName ? { cls: vName } : vName ? { fn: vName } : {}), owner };
661
+ };
662
+ const listOf = (n) => {
663
+ if (ts.isSourceFile(n) || ts.isBlock(n) || ts.isModuleBlock(n) || ts.isCaseClause(n) || ts.isDefaultClause(n))
664
+ return n.statements;
665
+ if (ts.isClassDeclaration(n) || ts.isClassExpression(n))
666
+ return n.members;
667
+ if (ts.isObjectLiteralExpression(n))
668
+ return n.properties;
669
+ return undefined;
670
+ };
671
+ return laws.map(l => {
672
+ const lineIdx = Math.max(0, (l.line ?? 1) - 1), rawLine = lines[lineIdx] ?? '';
673
+ const indent = /^\s*/.exec(rawLine)[0].length;
674
+ const standalone = /^\s*(?:(?:\/\/+|\/\*+|\*)\s*gdp:\s*law\b|@(?:GdpLaw|gdp\.law|gdp_law)\b)/i.test(rawLine)
675
+ && !/^\s*\/\*.*\*\/\s*\S/.test(rawLine);
676
+ if (!standalone) {
677
+ return {
678
+ ...l,
679
+ owner: { file, start: -1, end: -1, kind: 'file' },
680
+ inBody: false,
681
+ why: 'write the law on its own line above the declaration it is about',
682
+ };
683
+ }
684
+ const lineStart = sf.getPositionOfLineAndCharacter(lineIdx, 0);
685
+ const lineEnd = lineIdx + 1 < lines.length ? sf.getPositionOfLineAndCharacter(lineIdx + 1, 0) : text.length;
686
+ const pos = Math.min(text.length, lineStart + indent);
687
+ // Collect the exact chain of AST nodes whose real token span [getStart(sf), end) covers `pos`.
688
+ const chain = [sf];
689
+ const descend = (n) => {
690
+ ts.forEachChild(n, c => {
691
+ const s = c.getStart(sf);
692
+ if (s <= pos && pos < c.end) {
693
+ chain.push(c);
694
+ descend(c);
695
+ }
696
+ });
697
+ };
698
+ descend(sf);
699
+ // Innermost enclosing class (named OR anonymous `export default class` / `wrap(class {...})`).
700
+ let clsNode;
701
+ for (let i = chain.length - 1; i >= 0; i--) {
702
+ const n = chain[i];
703
+ if (ts.isClassDeclaration(n) || ts.isClassExpression(n)) {
704
+ clsNode = n;
705
+ break;
706
+ }
707
+ }
708
+ const memberTarget = (stopAt) => {
709
+ let container = stopAt;
710
+ for (let i = chain.length - 1; i >= 0; i--) {
711
+ const n = chain[i];
712
+ if (listOf(n)) {
713
+ if ((ts.isClassDeclaration(n) || ts.isClassExpression(n)) && n.members.pos > pos)
714
+ continue;
715
+ container = n;
716
+ break;
717
+ }
718
+ if (n === stopAt)
719
+ break;
720
+ }
721
+ const items = listOf(container) ?? [];
722
+ const next = items.find(it => { const s = it.getStart(sf); return s >= lineStart && s < lineEnd; })
723
+ ?? items.find(it => it.getStart(sf) >= pos);
724
+ if (next) {
725
+ if (ts.isMethodDeclaration(next) || ts.isGetAccessorDeclaration(next) || ts.isSetAccessorDeclaration(next))
726
+ return propName(next.name);
727
+ if (ts.isFunctionDeclaration(next) && next.name)
728
+ return next.name.text;
729
+ if (ts.isPropertyDeclaration(next) && isCallableInit(next.initializer))
730
+ return propName(next.name);
731
+ if (ts.isPropertyAssignment(next) || ts.isShorthandPropertyAssignment(next))
732
+ return propName(next.name);
733
+ if (ts.isVariableStatement(next)) {
734
+ const d = next.declarationList.declarations[0];
735
+ if (d && ts.isIdentifier(d.name) && isCallableInit(d.initializer))
736
+ return d.name.text;
737
+ }
738
+ }
739
+ for (let i = chain.length - 1; i >= 0; i--) {
740
+ const n = chain[i];
741
+ if (n === stopAt)
742
+ break;
743
+ if (ts.isMethodDeclaration(n) || ts.isGetAccessorDeclaration(n) || ts.isSetAccessorDeclaration(n))
744
+ return propName(n.name);
745
+ if (ts.isFunctionDeclaration(n) && n.name)
746
+ return n.name.text;
747
+ }
748
+ return undefined;
749
+ };
750
+ if (clsNode) {
751
+ let cls;
752
+ let owner;
753
+ if (ts.isClassDeclaration(clsNode) && clsNode.name) {
754
+ cls = clsNode.name.text;
755
+ owner = { ...spanOf(clsNode), kind: 'class', name: cls };
756
+ }
757
+ else {
758
+ let p = clsNode.parent;
759
+ while (p && (ts.isParenthesizedExpression(p) || ts.isAsExpression(p) || ts.isSatisfiesExpression(p)))
760
+ p = p.parent;
761
+ if (ts.isClassExpression(clsNode) && p && ts.isVariableDeclaration(p) && ts.isIdentifier(p.name) && p.parent.parent?.parent === sf) {
762
+ cls = p.name.text;
763
+ owner = { ...spanOf(p), kind: 'class', name: cls };
764
+ }
765
+ else {
766
+ owner = { ...spanOf(clsNode), kind: 'anon-class', name: clsNode.name?.text ?? (ts.isClassDeclaration(clsNode) ? 'default class' : 'anonymous class') };
767
+ }
768
+ }
769
+ const inDecorator = chain.some(n => ts.isDecorator(n));
770
+ if (inDecorator) {
771
+ if (chain.some(n => ts.isDecorator(n) && n.parent === clsNode))
772
+ return { ...l, ...(cls ? { cls } : {}), owner, inBody: false };
773
+ for (let i = chain.length - 1; i >= 0; i--) {
774
+ const n = chain[i];
775
+ if (n === clsNode)
776
+ break;
777
+ if (ts.isMethodDeclaration(n) || ts.isGetAccessorDeclaration(n) || ts.isSetAccessorDeclaration(n)) {
778
+ const fn = propName(n.name);
779
+ return { ...l, ...(cls ? { cls } : {}), ...(fn ? { fn } : {}), owner, inBody: true };
780
+ }
781
+ }
782
+ }
783
+ const clsIdx = chain.indexOf(clsNode);
784
+ const enclosingMember = clsNode.members.find(m => clsIdx >= 0 && chain[clsIdx + 1] === m);
785
+ const targetMember = enclosingMember ?? (clsNode.members.pos <= pos ? clsNode.members.find(m => m.getStart(sf) >= pos) : undefined);
786
+ const isStaticMember = !!(targetMember && ts.canHaveModifiers(targetMember) && ts.getModifiers(targetMember)?.some(m => m.kind === ts.SyntaxKind.StaticKeyword));
787
+ if (targetMember && isStaticMember) {
788
+ const mName = 'name' in targetMember ? propName(targetMember.name) : undefined;
789
+ const fullName = cls && mName ? `${cls}.${mName}` : mName;
790
+ const mOwner = { ...spanOf(targetMember), kind: 'member', ...(fullName ? { name: fullName } : {}) };
791
+ const memberFn = enclosingMember ? memberTarget(enclosingMember) : undefined;
792
+ return { ...l, ...(memberFn ? { fn: memberFn, inBody: true } : { inBody: false }), owner: mOwner };
793
+ }
794
+ const memberOwner = targetMember ? spanOf(targetMember) : undefined;
795
+ const fn = memberTarget(clsNode);
796
+ return { ...l, ...(cls ? { cls } : {}), ...(fn ? { fn } : {}), owner, ...(memberOwner ? { memberOwner } : {}), inBody: true };
797
+ }
798
+ // Inside a top-level VariableStatement: bind to the specific VariableDeclaration covering `pos`,
799
+ // or (between comma-separated declarators) to the next VariableDeclaration in that list.
800
+ if (chain.length >= 2 && ts.isVariableStatement(chain[1])) {
801
+ const topStmt = chain[1];
802
+ const varDecl = chain.find((n) => ts.isVariableDeclaration(n) && n.parent.parent === topStmt);
803
+ if (varDecl) {
804
+ const { owner } = varDeclOwner(varDecl), vName = declNameOf(varDecl);
805
+ const memberFn = memberTarget(varDecl);
806
+ return { ...l, ...(memberFn ? { fn: memberFn, inBody: true } : vName ? { fn: vName, inBody: false } : { inBody: false }), owner };
807
+ }
808
+ const decls = topStmt.declarationList.declarations;
809
+ const nextDecl = decls.find(d => { const s = d.getStart(sf); return s >= pos && s < lineEnd; })
810
+ ?? decls.find(d => d.getStart(sf) >= pos);
811
+ if (!nextDecl)
812
+ return { ...l, owner: { file, start: -1, end: -1, kind: 'file' }, inBody: false };
813
+ return { ...l, ...varDeclOwner(nextDecl), inBody: false };
814
+ }
815
+ // Inside another top-level non-class statement (e.g. a FunctionDeclaration or ExportAssignment).
816
+ if (chain.length >= 2) {
817
+ const topStmt = chain[1];
818
+ const tName = declNameOf(topStmt);
819
+ const owner = { ...spanOf(topStmt), kind: ts.isFunctionDeclaration(topStmt) ? 'function' : ts.isExportAssignment(topStmt) ? 'var' : 'file', ...(tName ? { name: tName } : {}) };
820
+ const memberFn = memberTarget(topStmt);
821
+ return { ...l, ...(memberFn ? { fn: memberFn, inBody: true } : tName ? { fn: tName, inBody: false } : { inBody: false }), owner };
822
+ }
823
+ // At top level of SourceFile: bind strictly to the next top-level declaration node.
824
+ const items = sf.statements.filter(st => !ts.isEmptyStatement(st));
825
+ const next = items.find(it => { const s = it.getStart(sf); return s >= lineStart && s < lineEnd; })
826
+ ?? items.find(it => it.getStart(sf) >= pos);
827
+ if (!next)
828
+ return { ...l, owner: { file, start: -1, end: -1, kind: 'file' }, inBody: false };
829
+ if (ts.isClassDeclaration(next)) {
830
+ const cls = next.name?.text;
831
+ const owner = { ...spanOf(next), kind: cls ? 'class' : 'anon-class', name: cls ?? 'default class' };
832
+ return { ...l, ...(cls ? { cls } : {}), owner, inBody: false };
833
+ }
834
+ if (ts.isFunctionDeclaration(next)) {
835
+ const fn = next.name?.text;
836
+ const owner = { ...spanOf(next), kind: 'function', name: fn ?? 'default function' };
837
+ return { ...l, ...(fn ? { fn } : {}), owner, inBody: false };
838
+ }
839
+ if (ts.isVariableStatement(next)) {
840
+ const d = next.declarationList.declarations[0];
841
+ if (!d)
842
+ return { ...l, owner: { file, start: -1, end: -1, kind: 'file' }, inBody: false };
843
+ return { ...l, ...varDeclOwner(d), inBody: false };
844
+ }
845
+ if (ts.isExportAssignment(next)) {
846
+ return { ...l, fn: 'default', owner: { ...spanOf(next), kind: 'var', name: 'default' }, inBody: false };
847
+ }
848
+ return { ...l, owner: { ...spanOf(next), kind: 'file' }, inBody: false };
849
+ });
850
+ }
564
851
  export function scoped(file) {
565
- const text = fs.readFileSync(file, 'utf8'), lines = text.split('\n');
566
- return lawsIn(text, path.basename(file)).map(l => {
852
+ const text = fs.readFileSync(file, 'utf8'), laws = lawsIn(text, path.basename(file));
853
+ if (/\.[cm]?[jt]sx?$/.test(file))
854
+ return scopedTS(file, text, laws);
855
+ const lines = text.split('\n');
856
+ return laws.map(l => {
567
857
  let cls, fn;
568
858
  // (the nearest enclosing class statement: its keyword at the start of a line, after modifiers, never a word in a
569
859
  // docstring's or a comment's prose; in Python, at an indentation that encloses the law's)
@@ -729,7 +1019,10 @@ function* checkPipeline(t, o) {
729
1019
  // (a law on a function outside any class is that function's, where the file has a rule of its name, never a method
730
1020
  // of another rule that shares the name)
731
1021
  const fnRules = new Set(rules.map(r => r.entry ?? r.x.model?.name).filter(Boolean));
732
- const mine = rules.length === 1 ? laws.filter(l => !name || (l.cls ? l.cls === name : !l.fn || l.fn === name || ms0.has(l.fn))) : laws.filter(l => (!l.cls && !l.fn) || (l.cls ? l.cls === name : l.fn === name || (ms0.has(l.fn) && !fnRules.has(l.fn))));
1022
+ const mine = laws.filter(l => l.owner
1023
+ ? ownsLaw(l, { entry, ctor, x: x0 })
1024
+ : rules.length === 1 ? (!name || (l.cls ? l.cls === name : !l.fn || l.fn === name || ms0.has(l.fn)))
1025
+ : ((!l.cls && !l.fn) || (l.cls ? l.cls === name : l.fn === name || (ms0.has(l.fn) && !fnRules.has(l.fn)))));
733
1026
  if (!x.ok || !x.rule) {
734
1027
  r.laws = mine.map(l => ({ name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: 'the rule was refused', ms: 0 }));
735
1028
  continue;
@@ -743,7 +1036,7 @@ function* checkPipeline(t, o) {
743
1036
  // (the rule's methods: the choice of method where it has several, else the one each name says)
744
1037
  const evSort = x.model?.inputs.find(v => v.name === x.model?.event)?.sort;
745
1038
  const methods = new Set([...(x.names ?? []).filter(n => n.method).map(n => n.method), ...(evSort?.k === 'choice' ? evSort.values : [])]);
746
- const stated = mine.map(l => ({ ...l, ...(l.fn && methods.has(l.fn) ? { method: l.fn } : {}) }));
1039
+ const stated = mine.map(l => ({ ...l, ...(l.fn && methods.has(l.fn) && (!l.owner || l.inBody) ? { method: l.fn } : {}) }));
747
1040
  const proven = [];
748
1041
  // (the environment the code runs in: --env, gdp.toml's env for the rule or every rule, or a `gdp: env` comment in
749
1042
  // its class: every call at once at its isolation level, keys that expire, retries; its laws lifted to it)
@@ -827,10 +1120,15 @@ function* checkPipeline(t, o) {
827
1120
  // (every law stated is accounted for: one that no rule took is reported not read, with why, never dropped)
828
1121
  const told = new Set(outs.flatMap(r => r.laws.map(l => l.where)));
829
1122
  const lost = laws.filter(l => !told.has(l.where));
830
- if (lost.length)
831
- outs.push({ file: path.relative(proc.cwd(), t.at) || '.', lang: LANG_NAME[t.lang], entry: [...new Set(lost.map(l => l.cls ?? l.fn ?? '(the file)'))].join(', '), ok: false,
1123
+ if (lost.length) {
1124
+ const lostEntry = (l) => l.owner?.kind === 'member' && l.owner.name ? l.owner.name
1125
+ : l.cls ?? (l.owner?.kind === 'anon-class' ? `(${l.owner.name ?? 'anonymous class'})` : l.owner?.name ?? l.fn ?? '(the file)');
1126
+ const lostTarget = (l) => l.owner?.kind === 'member' && l.owner.name ? `member ${l.owner.name}`
1127
+ : l.cls ? `class ${l.cls}` : l.owner?.kind === 'anon-class' ? `anonymous ${l.owner.name ?? 'class'}` : l.owner?.kind === 'function' && l.owner.name ? `function ${l.owner.name}` : l.fn ? `function ${l.fn}` : 'the file';
1128
+ outs.push({ file: path.relative(proc.cwd(), t.at) || '.', lang: LANG_NAME[t.lang], entry: [...new Set(lost.map(lostEntry))].join(', '), ok: false,
832
1129
  refusals: [{ where: t.at, what: 'laws no rule read' }], notes: [], names: [], proposed: [],
833
- laws: lost.map(l => ({ name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `no rule read for it (${l.cls ? `class ${l.cls}` : l.fn ? `function ${l.fn}` : 'the file'}): name its entry (--entry, or [rules.<entry>] in gdp.toml)`, ms: 0 })) });
1130
+ laws: lost.map(l => ({ name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: l.why ?? `no rule read for it (${lostTarget(l)}): name its entry (--entry, or [rules.<entry>] in gdp.toml)`, ms: 0 })) });
1131
+ }
834
1132
  // (a citation of no law stated in the target: refused, as a law not read is)
835
1133
  const named = new Set(laws.map(l => l.name));
836
1134
  for (const c of cites.filter(c => !named.has(c.law)))
@@ -1476,7 +1774,7 @@ export async function check(targets, given = {}, each) {
1476
1774
  const safetyLookalike = all.some(r => r.notes.some(n => SAFETY_LOOKALIKE_NOTE_RE.test(n)));
1477
1775
  const uncheckedSafety = safetyLookalike || all.some(r => r.safety && ('why' in r.safety || r.safety.status === 'unchecked' || r.safety.status === 'unproven'));
1478
1776
  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 };
1777
+ 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
1778
  }
1481
1779
  // --- draft: laws from a clause, for a person to review ----------------------------------------------------------------
1482
1780
  // gdp-wired draft <file> --clause <text> | --clause-file <f> --cite <ref> [--llm <command> | --answer <file>] [--by <who>]:
@@ -1559,8 +1857,18 @@ export async function main(argv) {
1559
1857
  }
1560
1858
  return code;
1561
1859
  }
1562
- if (import.meta.url === `file://${proc.argv[1]}` || /\/(cli\.(ts|js)|gdp-wired)$/.test(proc.argv[1] ?? '')) {
1563
- let sigExiting = false;
1860
+ export function runCli(argv = proc.argv.slice(2), opts = {}) {
1861
+ const label = opts.label ?? 'gdp-wired', run = opts.run ?? main;
1862
+ let settled = false, reported = false, sigExiting = false;
1863
+ // Fail-safe: never exit 0 unless main() resolves and authorizes the final code.
1864
+ proc.exitCode = 2;
1865
+ const onUnsettled = (why) => {
1866
+ if (settled || sigExiting || reported)
1867
+ return;
1868
+ reported = true;
1869
+ proc.exitCode = 2;
1870
+ err(`gdp-wired: the check did not complete (${why})`);
1871
+ };
1564
1872
  const onSignal = (code) => () => {
1565
1873
  if (sigExiting)
1566
1874
  return;
@@ -1570,6 +1878,27 @@ if (import.meta.url === `file://${proc.argv[1]}` || /\/(cli\.(ts|js)|gdp-wired)$
1570
1878
  };
1571
1879
  proc.on?.('SIGINT', onSignal(130));
1572
1880
  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; });
1881
+ proc.on?.('beforeExit', () => { onUnsettled('main did not settle before process exit'); });
1882
+ proc.on?.('exit', () => { cleanupCSafetySnapshots(); onUnsettled('process exited before main settled'); });
1883
+ let pending;
1884
+ try {
1885
+ pending = run(argv);
1886
+ }
1887
+ catch (e) {
1888
+ settled = true;
1889
+ out(`${label}: ${e instanceof Error ? e.message : String(e)}`);
1890
+ proc.exitCode = 2;
1891
+ return;
1892
+ }
1893
+ pending.then(c => {
1894
+ settled = true;
1895
+ proc.exitCode = typeof c === 'number' && Number.isInteger(c) ? c : 2;
1896
+ }, e => {
1897
+ settled = true;
1898
+ out(`${label}: ${e instanceof Error ? e.message : String(e)}`);
1899
+ proc.exitCode = 2;
1900
+ });
1901
+ }
1902
+ if (import.meta.url === `file://${proc.argv[1]}` || /\/(cli\.(ts|js)|gdp-wired)$/.test(proc.argv[1] ?? '')) {
1903
+ runCli(proc.argv.slice(2));
1575
1904
  }
@@ -24,8 +24,8 @@ export type MethodSchedule = {
24
24
  rule: ScheduleRule;
25
25
  };
26
26
  export type Runner = {
27
- run: (eff: unknown, now?: number) => unknown;
28
- exit: (eff: unknown, now: number) => {
27
+ run: (eff: unknown, now?: number, observeClock?: (t: number) => void) => unknown;
28
+ exit: (eff: unknown, now: number, observeClock?: (t: number) => void) => {
29
29
  ok: true;
30
30
  value: unknown;
31
31
  } | {