@antelopejs/tooling-configs 0.2.12 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/sync.mjs CHANGED
@@ -7,7 +7,7 @@ import { t as measureBaseline } from "../ratchet-DRdIYwmv.mjs";
7
7
  import { n as SUPPRESSIONS_FILE, r as adoptedBudget } from "../suppression-budget-Yyf5_J5l.mjs";
8
8
  import { a as ciWorkflow, c as ciNodeCallers, i as MUTATION_PATH, l as hasChecksWorkflow, o as mutationCaller, r as CI_PATH, s as MISSING_CHECKS_WORKFLOW } from "../ci-workflow-BDy6hQJ6.mjs";
9
9
  import { a as skillFolder, i as isVerifyKind, n as claudeLink, r as claudeLinkTarget, t as VERIFY_KINDS } from "../kinds-Bzyyi9yk.mjs";
10
- import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
10
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
11
11
  import { dirname, join, resolve } from "node:path";
12
12
  import { execFileSync } from "node:child_process";
13
13
  import { parseArgs } from "node:util";
@@ -453,7 +453,7 @@ ${BIN} clean <run>
453
453
  - \`verify.config.ts\` default-exports a \`VerifyConfig\` from \`@antelopejs/tooling-configs/verify\`:
454
454
  - \`doors\`: one entry per door kind (\`data\`, \`format\`, \`contract\`, \`outbound\`, \`exposure\`, \`publish\`), each \`null\` when it cannot apply or \`{ globs, funnels, containments, why }\`. \`containments\` names the \`feature/journey\` that contains a Data or Format door.
455
455
  - \`journeys\`: the repository's journeys by id, each \`{ title, entryPoint, run(context) }\`, using the check helpers the same import exports.
456
- - \`env\`, \`setup\` (commands replacing the build), \`userFacing\` (globs replacing the kind's default) and \`formal\` (formal checks with the files they cover).
456
+ - \`env\`, \`setup\` (commands replacing the build), \`userFacing\` (globs replacing the kind's default) and \`formal\` (formal checks: \`name\`, \`covers\`, \`command\`, \`violation\`, and optionally \`behaviour\` and \`baseCommand\`).
457
457
  ${text.layer}
458
458
  - \`features/<feature>.md\`: frontmatter lists \`covers:\` (source globs), \`docs:\` (pages a verdict judges) and \`journeys:\`, then the sections Sub-features, How to get to it (user POV), Driving it with antelopejs-verify, and Gotchas. \`features/smoke.md\` covers nothing and runs on every verdict; here it runs ${text.smoke}.
459
459
  - \`seeded-breaks/<feature>.patch\`: one minimal product bug per feature that its journeys must catch.
@@ -471,7 +471,12 @@ ${BIN} map
471
471
  2. **An unmapped surface fails the verdict.** A changed user-facing file no feature covers needs a feature entry, its journeys and its seeded break in the same PR.
472
472
  3. **Every registered journey of a feature in \`run\` must have run and passed.** Run whole features. A journey that could not reach the product is not verified, and so is the verdict, never PASS.
473
473
  4. **Docs.** Judge every \`docs:\` page of a touched feature against what the journeys showed. A stale page fails the verdict.
474
- 5. **Formal checks.** \`${BIN} formal <run>\` runs every formal check of \`verify.config.ts\` that covers the diff. One that did not run, violates a rule or errors fails the verdict.
474
+ 5. **Formal checks.** \`${BIN} formal <run>\` runs every formal check of \`verify.config.ts\` that covers the diff and records it under \`evidence/formal/<name>/\`. For each one it decides, without judgement, whether the diff changed what the covered code does. \`emit\` (the default) compares the structure of the covered files' JavaScript on the base and on HEAD: node kinds, names and literal values, leaving out types, comments, formatting, parentheses and \`export\` keywords. Each use of an imported binding stands for its origin (the resolved module and the imported name), so an import retargeted to another module or alias counts as changed; side-effect imports are compared by resolved module, and re-exports of uncovered modules by origin and exported name. Each file must keep its top-level statements in order; function declarations, which are hoisted, may move between covered files with their imports. So a type-only edit, a reformat or a moved function declaration counts as unchanged, while reordering statements or moving any other statement counts as changed. \`emit\` judges behaviour, not the public surface: exports are the api-diff's job. \`probe\` runs the check's \`behaviour.command\` with a worktree of each commit and compares what it prints. Then:
475
+ - a covered check that did not run, or exits non-zero (a tool error, or a check that no longer matches its record), fails the verdict;
476
+ - recorded findings fail the verdict only when the covered behaviour changed; when it did not, the verdict reports them as known findings;
477
+ - when the covered behaviour changed, or the diff changed the check's own \`files\`, \`formal\` also runs the check on the base (\`baseCommand\` when set). A rule the base broke counts as fixed only when HEAD reports it passing (\`passing\`); a rule the base broke that HEAD does not report at all fails the verdict. A change that leaves no violated rule passes.
478
+
479
+ The decision never reads the check's output, so a model whose rule names stay the same still fails on a changed behaviour. It is conservative: a local rename or an extracted helper counts as changed, and code outside \`covers\` is invisible to it. \`--all\` also runs the checks that do not cover the diff, without gating.
475
480
  6. **One-way doors.** The section comes right after the result line and is mandatory. \`${BIN} doors\` prints the \`One-way-door:\` line of the diff. Every file the path rules flag needs a door row or a false positive with its reason. A Data or Format row names a \`containments\` journey that passed in this run.
476
481
  7. **Result.** FAIL if any rule fails. NOT VERIFIED when a journey could not reach the product. PASS+NOTES when something is not verified or needs the owner's attention. PASS otherwise.
477
482
 
@@ -642,8 +647,7 @@ function planStaleKinds(root, keep) {
642
647
  });
643
648
  if (actions.length === before) continue;
644
649
  const folder = skillFolder(kind);
645
- const kept = existsSync(join(root, folder)) && readdirSync(join(root, folder)).some((name) => !syncedFiles(kind).some(({ path }) => path === `${folder}/${name}`));
646
- notes.push(`Removed the synced files of verify-${kind}.${kept ? ` Kept its repo-owned files in ${folder}.` : ""}`);
650
+ if (existsSync(join(root, folder)) && readdirSync(join(root, folder)).some((name) => !syncedFiles(kind).some(({ path }) => path === `${folder}/${name}`))) notes.push(`Removed the synced files of verify-${kind} and kept its repo-owned files in ${folder}.`);
647
651
  }
648
652
  return {
649
653
  actions,
@@ -676,6 +680,7 @@ function applyVerifyActions(root, actions) {
676
680
  const path = join(root, action.path);
677
681
  if (action.kind === "remove") {
678
682
  unlinkSync(path);
683
+ if (readdirSync(dirname(path)).length === 0) rmdirSync(dirname(path));
679
684
  continue;
680
685
  }
681
686
  mkdirSync(dirname(path), { recursive: true });
@@ -933,9 +938,10 @@ function syncRepository(root, options = {}) {
933
938
  return {
934
939
  artifacts: plan,
935
940
  paths: errors.length ? [] : [...writes, ...verify.actions].map(({ path }) => path),
941
+ removed: verify.actions.filter((action) => action.kind === "remove").map(({ path }) => path),
936
942
  errors,
937
943
  notes,
938
- verifyNotes: verify.notes,
944
+ verifyNotes: options.check || errors.length ? [] : verify.notes,
939
945
  advisories: entryOnly.advisories,
940
946
  dependenciesAdded
941
947
  };
@@ -963,7 +969,7 @@ runCli(() => {
963
969
  for (const advisory of result.advisories) process.stdout.write(`${advisory}\n`);
964
970
  for (const error of result.errors) process.stderr.write(`${error}\n`);
965
971
  if (result.errors.length) return 1;
966
- for (const path of result.paths) process.stdout.write(`${values.check ? "Drift" : "Updated"}: ${path}${values.check ? "; run antelopejs-sync" : ""}\n`);
972
+ for (const path of result.paths) process.stdout.write(values.check ? `Drift: ${path}; run antelopejs-sync\n` : `${result.removed.includes(path) ? "Removed" : "Updated"}: ${path}\n`);
967
973
  if (!result.paths.length) process.stdout.write("Guardrails are in sync.\n");
968
974
  if (!values.check && result.dependenciesAdded) process.stdout.write("Added devDependencies. Run install with your package manager before using the hooks or checks.\n");
969
975
  return values.check && result.paths.length ? 1 : 0;
@@ -5,13 +5,13 @@ import { n as runCliAsync } from "../cli-4Tv71vYk.mjs";
5
5
  import { o as repositoryRoot } from "../files-2FikHZ9F.mjs";
6
6
  import { a as skillFolder, i as isVerifyKind, t as VERIFY_KINDS } from "../kinds-Bzyyi9yk.mjs";
7
7
  import { appendFileSync, closeSync, copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
8
- import { basename, dirname, join, matchesGlob, relative, resolve, sep } from "node:path";
8
+ import { basename, dirname, extname, join, matchesGlob, posix, relative, resolve, sep } from "node:path";
9
9
  import { execFileSync, spawn, spawnSync } from "node:child_process";
10
10
  import { parseArgs } from "node:util";
11
11
  import { pathToFileURL } from "node:url";
12
12
  import { homedir, tmpdir } from "node:os";
13
- import { randomBytes } from "node:crypto";
14
13
  import ts from "typescript";
14
+ import { randomBytes } from "node:crypto";
15
15
  import { createServer } from "node:net";
16
16
  //#region src/verify/doors.ts
17
17
  const RELEASE_FILES = [
@@ -20,6 +20,7 @@ const RELEASE_FILES = [
20
20
  "changelogen.config.json",
21
21
  ".github/workflows/release.yml"
22
22
  ];
23
+ /** The pack's default path rules per repository kind; a repo's `doors` block adds to them. */
23
24
  const DEFAULT_DOOR_GLOBS = {
24
25
  interface: {
25
26
  contract: ["src/**", "package.json"],
@@ -68,122 +69,182 @@ function doorLine(doors) {
68
69
  return doors.length > 0 ? `One-way-door: ${doors.map((door) => door.kind).join(", ")}` : "";
69
70
  }
70
71
  //#endregion
71
- //#region src/verify/formal.ts
72
- /** The formal checks of verify.config.ts whose covered files the change touches. */
73
- function touchedFormalChecks(workspace, changed) {
74
- return (workspace.config.formal ?? []).filter((check) => changed.some((file) => check.covers.includes(file)));
75
- }
76
- function violatedRules(check, exitCode, output) {
77
- if (check.violation) return [...new Set([...output.matchAll(check.violation)].map((match) => match[1]))];
78
- return exitCode === 0 ? [] : ["property"];
79
- }
80
- /** Runs one formal check from the repository root and records it under evidence/formal/<name>/. */
81
- function runFormalCheck(workspace, state, check) {
82
- const folder = join(state.evidence, "formal", check.name);
83
- mkdirSync(folder, { recursive: true });
84
- const [program, ...args] = check.command;
85
- const run = spawnSync(program, args, {
86
- cwd: workspace.root,
87
- encoding: "utf8"
72
+ //#region src/verify/emit.ts
73
+ const CODE_EXTENSIONS = /* @__PURE__ */ new Set([
74
+ ".ts",
75
+ ".mts",
76
+ ".cts",
77
+ ".tsx",
78
+ ".js",
79
+ ".mjs",
80
+ ".cjs",
81
+ ".jsx"
82
+ ]);
83
+ const OUTPUT_LIMIT$2 = 67108864;
84
+ const TEXT_LENGTH = 160;
85
+ function fileAt(repo, sha, path) {
86
+ const shown = spawnSync("git", ["show", `${sha}:${path}`], {
87
+ cwd: repo,
88
+ encoding: "utf8",
89
+ maxBuffer: OUTPUT_LIMIT$2
88
90
  });
89
- writeFileSync(join(folder, "command.txt"), `${check.command.join(" ")}\n`);
90
- writeFileSync(join(folder, "stdout.txt"), run.stdout ?? "");
91
- writeFileSync(join(folder, "stderr.txt"), `${run.stderr ?? ""}${run.error ? `\n${run.error.message}\n` : ""}`);
92
- writeFileSync(join(folder, "exit-code.txt"), `${run.status}\n`);
93
- const result = {
94
- name: check.name,
95
- exitCode: run.status,
96
- violated: violatedRules(check, run.status, run.stdout ?? ""),
97
- folder: relative(state.evidence, folder)
98
- };
99
- writeFileSync(join(folder, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
100
- return result;
101
- }
102
- /** The recorded result of a formal check in a run, if it ran. */
103
- function readFormalResult(state, name) {
104
- const file = join(state.evidence, "formal", name, "result.json");
105
- if (!existsSync(file)) return void 0;
106
- return JSON.parse(readFileSync(file, "utf8"));
107
- }
108
- //#endregion
109
- //#region src/verify/judgement.ts
110
- const DOOR_KINDS = [
111
- "data",
112
- "format",
113
- "contract",
114
- "outbound",
115
- "exposure",
116
- "publish"
117
- ];
118
- function isDoorKind(value) {
119
- return DOOR_KINDS.some((kind) => kind === value);
91
+ return shown.status === 0 ? shown.stdout : null;
92
+ }
93
+ const MODULE_EXTENSION = /\.(?:[cm]?[jt]s|[jt]sx)$/;
94
+ function moduleKey(path, specifier) {
95
+ if (!specifier.startsWith(".")) return specifier;
96
+ return posix.join(dirname(path), specifier).replace(MODULE_EXTENSION, "");
97
+ }
98
+ function isPropertyName(node) {
99
+ const parent = node.parent;
100
+ return (ts.isPropertyAccessExpression(parent) || ts.isPropertyAssignment(parent) || ts.isMethodDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isGetAccessor(parent) || ts.isSetAccessor(parent) || ts.isEnumMember(parent)) && parent.name === node;
101
+ }
102
+ function bindingOrigin(covered, module, name) {
103
+ return covered.has(module) && name !== "default" && name !== "*" ? name : `${module}#${name}`;
104
+ }
105
+ function importedBindings(clause, module, covered) {
106
+ const named = clause.namedBindings;
107
+ const bindings = [];
108
+ if (clause.name) bindings.push([clause.name.text, bindingOrigin(covered, module, "default")]);
109
+ if (named && ts.isNamespaceImport(named)) bindings.push([named.name.text, bindingOrigin(covered, module, "*")]);
110
+ if (named && ts.isNamedImports(named)) for (const element of named.elements) bindings.push([element.name.text, bindingOrigin(covered, module, (element.propertyName ?? element.name).text)]);
111
+ return bindings;
112
+ }
113
+ function reexportTexts(statement, module) {
114
+ const exported = statement.exportClause;
115
+ if (exported === void 0) return [`export * from ${module}`];
116
+ if (ts.isNamespaceExport(exported)) return [`export * as ${exported.name.text} from ${module}`];
117
+ return exported.elements.map((element) => `export ${module}#${(element.propertyName ?? element.name).text} as ${element.name.text}`);
120
118
  }
121
- function text(source, key) {
122
- const value = source[key];
123
- return value !== void 0 && isString(value) ? value.trim() : "";
124
- }
125
- function texts(source, key) {
126
- const value = source[key];
127
- return Array.isArray(value) ? value.filter(isString) : [];
119
+ /**
120
+ * Where each value-imported binding of a file comes from: the resolved
121
+ * module and the imported name, so an alias or a swapped specifier changes
122
+ * what a use refers to. A binding from a covered module is its imported
123
+ * name alone, the same as a local declaration of it, so moving a
124
+ * declaration between covered files keeps every use the same. Side-effect
125
+ * imports and re-exports of uncovered modules become entries of their own.
126
+ */
127
+ function originsOf(path, covered, file) {
128
+ const bindings = /* @__PURE__ */ new Map();
129
+ const texts = [];
130
+ for (const statement of file.statements) {
131
+ if (!(ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement))) continue;
132
+ const specifier = statement.moduleSpecifier;
133
+ if (specifier === void 0 || !ts.isStringLiteral(specifier)) continue;
134
+ const module = moduleKey(path, specifier.text);
135
+ if (ts.isImportDeclaration(statement)) {
136
+ if (statement.importClause === void 0) {
137
+ texts.push(`import ${module}`);
138
+ continue;
139
+ }
140
+ for (const [name, origin] of importedBindings(statement.importClause, module, covered)) bindings.set(name, origin);
141
+ } else if (!covered.has(module)) texts.push(...reexportTexts(statement, module));
142
+ }
143
+ return {
144
+ bindings,
145
+ entries: texts.map((text) => ({
146
+ structure: text,
147
+ text,
148
+ hoisted: true
149
+ }))
150
+ };
128
151
  }
129
- function objects(value) {
130
- return Array.isArray(value) ? value.filter(isObject) : [];
152
+ function leafOf(node, bindings) {
153
+ if (ts.isIdentifier(node)) return isPropertyName(node) ? node.text : bindings.get(node.text) ?? node.text;
154
+ if (ts.isPrivateIdentifier(node)) return node.text;
155
+ if (ts.isNumericLiteral(node)) return String(Number(node.text));
156
+ if (ts.isStringLiteralLike(node) || ts.isTemplateLiteralToken(node)) return JSON.stringify(node.text);
157
+ if (ts.isBigIntLiteral(node) || ts.isRegularExpressionLiteral(node)) return node.text;
158
+ if (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) return ts.SyntaxKind[node.operator];
159
+ if (ts.isVariableDeclarationList(node)) return String(node.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const));
160
+ if (ts.isMetaProperty(node)) return ts.SyntaxKind[node.keywordToken];
161
+ return "";
131
162
  }
132
- function doorKind(value, label) {
133
- if (!isDoorKind(value)) throw new Error(`judgement.json: ${label} is "${value}", not one of ${DOOR_KINDS.join(", ")}`);
134
- return value;
163
+ function dropped(node) {
164
+ return node.kind === ts.SyntaxKind.ExportKeyword || node.kind === ts.SyntaxKind.DefaultKeyword;
135
165
  }
136
- function parseRows(doors) {
137
- return objects(doors.rows).map((row, index) => {
138
- const parsed = {
139
- location: text(row, "location"),
140
- irreversible: text(row, "irreversible"),
141
- containment: text(row, "containment")
142
- };
143
- if (!parsed.location || !parsed.irreversible || !parsed.containment) throw new Error(`judgement.json: doors.rows[${index}] needs kind, location, irreversible and containment`);
144
- return {
145
- ...parsed,
146
- kind: doorKind(text(row, "kind"), `doors.rows[${index}].kind`),
147
- containmentJourney: text(row, "containmentJourney")
148
- };
166
+ /**
167
+ * The structure of a node: its kind, its identifier name or literal value,
168
+ * and its children's structure, with parentheses, positions, trivia, quote
169
+ * style and line breaks left out, so formatting never changes it. An
170
+ * imported binding stands for its origin.
171
+ */
172
+ function structureOf(node, bindings) {
173
+ if (ts.isParenthesizedExpression(node)) return structureOf(node.expression, bindings);
174
+ const children = [];
175
+ ts.forEachChild(node, (child) => {
176
+ if (!dropped(child)) children.push(structureOf(child, bindings));
149
177
  });
150
- }
151
- function parseFalsePositives(doors) {
152
- return objects(doors.falsePositives).map((entry, index) => {
153
- const location = text(entry, "location");
154
- const reason = text(entry, "reason");
155
- if (!location || !reason) throw new Error(`judgement.json: doors.falsePositives[${index}] needs location and reason`);
156
- return {
157
- kind: doorKind(text(entry, "kind"), `doors.falsePositives[${index}].kind`),
158
- location,
159
- reason
160
- };
178
+ return `${ts.SyntaxKind[node.kind]}(${leafOf(node, bindings)}|${children.join(",")})`;
179
+ }
180
+ function readable(text) {
181
+ const flat = text.replace(/\s+/g, " ").trim();
182
+ return flat.length > TEXT_LENGTH ? `${flat.slice(0, TEXT_LENGTH)}…` : flat;
183
+ }
184
+ function scriptItems(path, source, covered) {
185
+ const { outputText } = ts.transpileModule(source, {
186
+ fileName: path,
187
+ compilerOptions: {
188
+ target: ts.ScriptTarget.ES2022,
189
+ module: ts.ModuleKind.ESNext,
190
+ removeComments: true,
191
+ experimentalDecorators: true
192
+ }
161
193
  });
194
+ const file = ts.createSourceFile("emit.js", outputText, ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
195
+ const { bindings, entries } = originsOf(path, covered, file);
196
+ const statements = file.statements.filter((statement) => !ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement)).map((statement) => ({
197
+ structure: structureOf(statement, bindings),
198
+ text: readable(statement.getText(file)),
199
+ hoisted: ts.isFunctionDeclaration(statement) && Boolean(statement.body)
200
+ }));
201
+ return [...entries, ...statements];
202
+ }
203
+ function vueItems(path, source, covered) {
204
+ const scripts = [...source.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/g)];
205
+ const template = /<template\b[^>]*>([\s\S]*)<\/template>/.exec(source);
206
+ const markup = template ? template[1].replace(/\s+/g, " ").trim() : null;
207
+ return [...scripts.flatMap(([, body]) => scriptItems(`${path}.ts`, body, covered)), ...markup === null ? [] : [{
208
+ structure: `template(${markup})`,
209
+ text: readable(`<template> ${markup}`),
210
+ hoisted: false
211
+ }]];
212
+ }
213
+ function itemsOf(path, source, covered) {
214
+ if (path.endsWith(".vue")) return vueItems(path, source, covered);
215
+ if (CODE_EXTENSIONS.has(extname(path))) return scriptItems(path, source, covered);
216
+ const flat = source.replace(/\s+/g, " ").trim();
217
+ return [{
218
+ structure: `file(${flat})`,
219
+ text: readable(flat),
220
+ hoisted: false
221
+ }];
162
222
  }
163
- /** Parses evidence/judgement.json. A verdict without a One-way doors section is void, so a missing one throws. */
164
- function readJudgement(file) {
165
- if (!existsSync(file)) throw new Error(`${file} is missing: write the verifier's judgement before rendering the verdict`);
166
- const raw = parseJson(readFileSync(file, "utf8"));
167
- if (!isObject(raw)) throw new Error(`${file} must hold a JSON object`);
168
- const doors = raw.doors !== void 0 && isObject(raw.doors) ? raw.doors : {};
169
- const rows = parseRows(doors);
170
- const none = text(doors, "none") || null;
171
- if (!none && rows.length === 0) throw new Error("judgement.json: doors needs `none` with a reason or at least one row; a verdict without it is void");
172
- const verifier = text(raw, "verifier");
173
- if (!verifier) throw new Error("judgement.json: verifier must say who judged this run, for example the verifier thread's URL");
174
- return {
175
- notVerified: texts(raw, "notVerified"),
176
- attention: texts(raw, "attention"),
177
- docs: objects(raw.docs).map((entry) => ({
178
- page: text(entry, "page"),
179
- matches: entry.matches === true,
180
- note: text(entry, "note")
181
- })),
182
- doorsNone: none,
183
- doors: rows,
184
- falsePositives: parseFalsePositives(doors),
185
- verifier
223
+ /**
224
+ * What the covered code does at a commit, as structure rather than text:
225
+ * each covered file's top-level statements in order, and, apart, the
226
+ * function declarations, side-effect imports and re-exports of every covered
227
+ * file, which hoisting lets move freely. Each use of an imported binding
228
+ * stands for its origin (resolved module and imported name), so retargeting
229
+ * an import or an alias changes the fingerprint. Types, comments, formatting
230
+ * and export keywords are left out, so a type-only edit, a reformat, or
231
+ * moving a function declaration to another covered file keeps the same
232
+ * fingerprint, while reordering or moving any other statement changes it.
233
+ */
234
+ function emitFingerprint(repo, sha, files) {
235
+ const fingerprint = {
236
+ functions: [],
237
+ files: {}
186
238
  };
239
+ const covered = new Set(files.map((path) => path.replace(MODULE_EXTENSION, "")));
240
+ for (const path of files) {
241
+ const source = fileAt(repo, sha, path);
242
+ if (source === null) continue;
243
+ const items = itemsOf(path, source, covered);
244
+ fingerprint.functions.push(...items.filter((item) => item.hoisted));
245
+ fingerprint.files[path] = items.filter((item) => !item.hoisted);
246
+ }
247
+ return fingerprint;
187
248
  }
188
249
  //#endregion
189
250
  //#region src/verify/workspace.ts
@@ -296,6 +357,337 @@ function isolatedEnv(workspace, home, extra = {}) {
296
357
  };
297
358
  }
298
359
  //#endregion
360
+ //#region src/verify/behaviour.ts
361
+ const DETAIL_LIMIT = 5;
362
+ const DETAIL_LENGTH = 160;
363
+ const OUTPUT_LIMIT$1 = 67108864;
364
+ /** Runs `action` in a throwaway worktree of `sha` whose `node_modules` links the checkout's, then removes it. */
365
+ function inWorktree(repo, sha, action) {
366
+ const dir = mkdtempSync(join(tmpdir(), "antelopejs-verify-behaviour-"));
367
+ git(repo, [
368
+ "worktree",
369
+ "add",
370
+ "--quiet",
371
+ "--detach",
372
+ "--force",
373
+ dir,
374
+ sha
375
+ ]);
376
+ try {
377
+ symlinkSync(join(repo, "node_modules"), join(dir, "node_modules"), "dir");
378
+ return action(dir);
379
+ } finally {
380
+ git(repo, [
381
+ "worktree",
382
+ "remove",
383
+ "--force",
384
+ dir
385
+ ]);
386
+ rmSync(dir, {
387
+ recursive: true,
388
+ force: true
389
+ });
390
+ }
391
+ }
392
+ function probeFingerprint(repo, command, sha) {
393
+ const [program, ...args] = command;
394
+ return inWorktree(repo, sha, (dir) => {
395
+ const run = spawnSync(program, [...args, dir], {
396
+ cwd: repo,
397
+ encoding: "utf8",
398
+ maxBuffer: OUTPUT_LIMIT$1
399
+ });
400
+ if (run.status !== 0) throw new Error(`behaviour probe ${command.join(" ")} failed on ${sha}:\n${run.stderr}`);
401
+ return run.stdout.split("\n").filter(Boolean);
402
+ });
403
+ }
404
+ function difference(left, right, key) {
405
+ const counts = /* @__PURE__ */ new Map();
406
+ for (const item of right) counts.set(key(item), (counts.get(key(item)) ?? 0) + 1);
407
+ return left.filter((item) => {
408
+ const count = counts.get(key(item)) ?? 0;
409
+ if (count === 0) return true;
410
+ counts.set(key(item), count - 1);
411
+ return false;
412
+ });
413
+ }
414
+ function sample(lines) {
415
+ return lines.slice(0, DETAIL_LIMIT).map((line) => line.length > DETAIL_LENGTH ? `${line.slice(0, DETAIL_LENGTH)}…` : line);
416
+ }
417
+ function sequenceChanges(path, base, head) {
418
+ const length = Math.max(base.length, head.length);
419
+ for (let index = 0; index < length; index += 1) if (base[index]?.structure !== head[index]?.structure) return {
420
+ removed: [`${path} statement ${index + 1}: ${base[index]?.text ?? "(none)"}`],
421
+ added: [`${path} statement ${index + 1}: ${head[index]?.text ?? "(none)"}`]
422
+ };
423
+ return {
424
+ removed: [],
425
+ added: []
426
+ };
427
+ }
428
+ function compareEmit(base, head) {
429
+ const structure = (item) => item.structure;
430
+ const removed = difference(base.functions, head.functions, structure).map((item) => `hoisted ${item.text}`);
431
+ const added = difference(head.functions, base.functions, structure).map((item) => `hoisted ${item.text}`);
432
+ for (const path of /* @__PURE__ */ new Set([...Object.keys(base.files), ...Object.keys(head.files)])) {
433
+ const change = sequenceChanges(path, base.files[path] ?? [], head.files[path] ?? []);
434
+ removed.push(...change.removed);
435
+ added.push(...change.added);
436
+ }
437
+ return {
438
+ removed,
439
+ added
440
+ };
441
+ }
442
+ function compareProbe(base, head) {
443
+ if (JSON.stringify(base) === JSON.stringify(head)) return {
444
+ removed: [],
445
+ added: []
446
+ };
447
+ const line = (item) => item;
448
+ const removed = difference(base, head, line);
449
+ const added = difference(head, base, line);
450
+ return removed.length + added.length > 0 ? {
451
+ removed,
452
+ added
453
+ } : {
454
+ removed: ["(order)"],
455
+ added: ["(order)"]
456
+ };
457
+ }
458
+ /**
459
+ * Whether a diff changed the behaviour of the code a formal check covers,
460
+ * decided without judgement. For `emit` (the default), each covered file
461
+ * keeps its top-level statements, in order, with the same structure, and the
462
+ * covered function declarations stay the same wherever they live; for
463
+ * `probe`, the check's probe prints the same lines on a checkout of the base
464
+ * and of HEAD. The check's own output never enters the decision, so a model
465
+ * that cannot see the code still gates it.
466
+ */
467
+ function behaviourChange(repo, check, commits) {
468
+ const probe = check.behaviour?.kind === "probe" ? check.behaviour.command : void 0;
469
+ const change = probe === void 0 ? compareEmit(emitFingerprint(repo, commits.baseSha, check.covers), emitFingerprint(repo, commits.headSha, check.covers)) : compareProbe(probeFingerprint(repo, probe, commits.baseSha), probeFingerprint(repo, probe, commits.headSha));
470
+ return {
471
+ method: probe === void 0 ? "emit" : `probe ${probe.join(" ")}`,
472
+ changed: change.removed.length + change.added.length > 0,
473
+ removed: sample(change.removed),
474
+ added: sample(change.added)
475
+ };
476
+ }
477
+ //#endregion
478
+ //#region src/verify/formal.ts
479
+ const OUTPUT_LIMIT = 67108864;
480
+ /** The formal checks of verify.config.ts whose covered files the change touches. */
481
+ function touchedFormalChecks(workspace, changed) {
482
+ return (workspace.config.formal ?? []).filter((check) => changed.some((file) => check.covers.includes(file)));
483
+ }
484
+ function violatedRules(check, exitCode, output) {
485
+ if (check.violation) return [...new Set([...output.matchAll(check.violation)].map((match) => match[1]))];
486
+ return exitCode === 0 ? [] : ["property"];
487
+ }
488
+ function passingRules(check, exitCode, output) {
489
+ if (check.passing) return [...new Set([...output.matchAll(check.passing)].map((match) => match[1]))];
490
+ return !check.violation && exitCode === 0 ? ["property"] : [];
491
+ }
492
+ function rulesOf(check, run) {
493
+ return {
494
+ exitCode: run.status,
495
+ violated: violatedRules(check, run.status, run.stdout ?? ""),
496
+ passing: passingRules(check, run.status, run.stdout ?? "")
497
+ };
498
+ }
499
+ function runCommand(command, cwd) {
500
+ const [program, ...args] = command;
501
+ return spawnSync(program, args, {
502
+ cwd,
503
+ encoding: "utf8",
504
+ maxBuffer: OUTPUT_LIMIT
505
+ });
506
+ }
507
+ function writeRun(folder, prefix, command, run) {
508
+ writeFileSync(join(folder, `${prefix}command.txt`), `${command.join(" ")}\n`);
509
+ writeFileSync(join(folder, `${prefix}stdout.txt`), run.stdout ?? "");
510
+ writeFileSync(join(folder, `${prefix}stderr.txt`), `${run.stderr ?? ""}${run.error ? `\n${run.error.message}\n` : ""}`);
511
+ writeFileSync(join(folder, `${prefix}exit-code.txt`), `${run.status}\n`);
512
+ }
513
+ function baseRun(workspace, check, baseSha, folder) {
514
+ const command = check.baseCommand ?? check.command;
515
+ const run = inWorktree(workspace.root, baseSha, (dir) => runCommand(command, dir));
516
+ writeRun(folder, "base-", command, run);
517
+ return rulesOf(check, run);
518
+ }
519
+ function gateFields(workspace, check, diff, folder, head) {
520
+ const behaviour = behaviourChange(workspace.root, check, diff);
521
+ const checkChanged = diff.changed.some((file) => (check.files ?? []).some((glob) => matchesGlob(file, glob)));
522
+ if (!behaviour.changed && !checkChanged) return {
523
+ behaviour,
524
+ checkChanged,
525
+ base: null,
526
+ fixed: [],
527
+ missing: []
528
+ };
529
+ const base = baseRun(workspace, check, diff.baseSha, folder);
530
+ const atHead = /* @__PURE__ */ new Set([...head.violated, ...head.passing]);
531
+ return {
532
+ behaviour,
533
+ checkChanged,
534
+ base,
535
+ fixed: base.violated.filter((rule) => head.passing.includes(rule) && !head.violated.includes(rule)),
536
+ missing: base.violated.filter((rule) => !atHead.has(rule))
537
+ };
538
+ }
539
+ /**
540
+ * Runs one formal check from the repository root and writes its command,
541
+ * output, exit code and violated rules under `evidence/formal/<name>/`.
542
+ * When the check covers the diff (`diff` given), it also records whether the
543
+ * diff changed the covered code's behaviour. When it did, or when the diff
544
+ * changed the check's own `files`, it runs the check on the base: `fixed`
545
+ * lists the rules the base broke that HEAD reports passing, and `missing`
546
+ * the rules the base broke that HEAD reports neither failing nor passing.
547
+ */
548
+ function runFormalCheck(workspace, state, check, diff) {
549
+ const folder = join(state.evidence, "formal", check.name);
550
+ mkdirSync(folder, { recursive: true });
551
+ const run = runCommand(check.command, workspace.root);
552
+ writeRun(folder, "", check.command, run);
553
+ const head = rulesOf(check, run);
554
+ const result = {
555
+ name: check.name,
556
+ exitCode: run.status,
557
+ violated: head.violated,
558
+ passing: head.passing,
559
+ folder: relative(state.evidence, folder)
560
+ };
561
+ if (diff !== null) Object.assign(result, { commits: {
562
+ baseSha: diff.baseSha,
563
+ headSha: diff.headSha
564
+ } }, gateFields(workspace, check, diff, folder, head));
565
+ writeFileSync(join(folder, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
566
+ return result;
567
+ }
568
+ /**
569
+ * How a formal check's result weighs on a verdict whose diff it covers. A
570
+ * non-zero exit (a tool error, or a check that no longer matches its record)
571
+ * fails. Recorded findings fail only when the diff changed the covered code's
572
+ * behaviour; otherwise they are reported as known. A rule the base broke and
573
+ * HEAD reports passing is reported as fixed; one HEAD does not report at all
574
+ * fails.
575
+ */
576
+ function formalGate(result) {
577
+ if (result.exitCode !== 0) return {
578
+ fails: true,
579
+ outcome: `${result.violated.length > 0 ? `the check no longer matches its record: ${result.violated.join(", ")}` : "tool error"}, exit ${result.exitCode}`
580
+ };
581
+ if ((result.missing ?? []).length > 0) return {
582
+ fails: true,
583
+ outcome: `rules the base broke are absent at HEAD: ${(result.missing ?? []).join(", ")}`
584
+ };
585
+ if (result.behaviour === void 0) return {
586
+ fails: result.violated.length > 0,
587
+ outcome: `violated ${result.violated.join(", ") || "nothing"}`
588
+ };
589
+ const how = result.behaviour.method;
590
+ if (!result.behaviour.changed) return {
591
+ fails: false,
592
+ outcome: `covered behaviour unchanged (${how}): ${result.violated.length > 0 ? `known findings ${result.violated.join(", ")}` : "no violated rule"}`
593
+ };
594
+ const fixed = (result.fixed ?? []).length > 0 ? `; fixed: ${(result.fixed ?? []).join(", ")}` : "";
595
+ if (result.violated.length === 0) return {
596
+ fails: false,
597
+ outcome: `covered behaviour changed (${how}), no violated rule${fixed}`
598
+ };
599
+ return {
600
+ fails: true,
601
+ outcome: `covered behaviour changed (${how}), violated ${result.violated.join(", ")}${fixed}`
602
+ };
603
+ }
604
+ /** The recorded result of a formal check in a run, if it ran. */
605
+ function readFormalResult(state, name) {
606
+ const file = join(state.evidence, "formal", name, "result.json");
607
+ if (!existsSync(file)) return void 0;
608
+ return JSON.parse(readFileSync(file, "utf8"));
609
+ }
610
+ //#endregion
611
+ //#region src/verify/judgement.ts
612
+ const DOOR_KINDS = [
613
+ "data",
614
+ "format",
615
+ "contract",
616
+ "outbound",
617
+ "exposure",
618
+ "publish"
619
+ ];
620
+ function isDoorKind(value) {
621
+ return DOOR_KINDS.some((kind) => kind === value);
622
+ }
623
+ function text(source, key) {
624
+ const value = source[key];
625
+ return value !== void 0 && isString(value) ? value.trim() : "";
626
+ }
627
+ function texts(source, key) {
628
+ const value = source[key];
629
+ return Array.isArray(value) ? value.filter(isString) : [];
630
+ }
631
+ function objects(value) {
632
+ return Array.isArray(value) ? value.filter(isObject) : [];
633
+ }
634
+ function doorKind(value, label) {
635
+ if (!isDoorKind(value)) throw new Error(`judgement.json: ${label} is "${value}", not one of ${DOOR_KINDS.join(", ")}`);
636
+ return value;
637
+ }
638
+ function parseRows(doors) {
639
+ return objects(doors.rows).map((row, index) => {
640
+ const parsed = {
641
+ location: text(row, "location"),
642
+ irreversible: text(row, "irreversible"),
643
+ containment: text(row, "containment")
644
+ };
645
+ if (!parsed.location || !parsed.irreversible || !parsed.containment) throw new Error(`judgement.json: doors.rows[${index}] needs kind, location, irreversible and containment`);
646
+ return {
647
+ ...parsed,
648
+ kind: doorKind(text(row, "kind"), `doors.rows[${index}].kind`),
649
+ containmentJourney: text(row, "containmentJourney")
650
+ };
651
+ });
652
+ }
653
+ function parseFalsePositives(doors) {
654
+ return objects(doors.falsePositives).map((entry, index) => {
655
+ const location = text(entry, "location");
656
+ const reason = text(entry, "reason");
657
+ if (!location || !reason) throw new Error(`judgement.json: doors.falsePositives[${index}] needs location and reason`);
658
+ return {
659
+ kind: doorKind(text(entry, "kind"), `doors.falsePositives[${index}].kind`),
660
+ location,
661
+ reason
662
+ };
663
+ });
664
+ }
665
+ /** Parses evidence/judgement.json. A verdict without a One-way doors section is void, so a missing one throws. */
666
+ function readJudgement(file) {
667
+ if (!existsSync(file)) throw new Error(`${file} is missing: write the verifier's judgement before rendering the verdict`);
668
+ const raw = parseJson(readFileSync(file, "utf8"));
669
+ if (!isObject(raw)) throw new Error(`${file} must hold a JSON object`);
670
+ const doors = raw.doors !== void 0 && isObject(raw.doors) ? raw.doors : {};
671
+ const rows = parseRows(doors);
672
+ const none = text(doors, "none") || null;
673
+ if (!none && rows.length === 0) throw new Error("judgement.json: doors needs `none` with a reason or at least one row; a verdict without it is void");
674
+ const verifier = text(raw, "verifier");
675
+ if (!verifier) throw new Error("judgement.json: verifier must say who judged this run, for example the verifier thread's URL");
676
+ return {
677
+ notVerified: texts(raw, "notVerified"),
678
+ attention: texts(raw, "attention"),
679
+ docs: objects(raw.docs).map((entry) => ({
680
+ page: text(entry, "page"),
681
+ matches: entry.matches === true,
682
+ note: text(entry, "note")
683
+ })),
684
+ doorsNone: none,
685
+ doors: rows,
686
+ falsePositives: parseFalsePositives(doors),
687
+ verifier
688
+ };
689
+ }
690
+ //#endregion
299
691
  //#region src/verify/docker.ts
300
692
  const READY_TIMEOUT_MS$1 = 9e4;
301
693
  function docker(args) {
@@ -717,6 +1109,75 @@ function ajsEntry(root) {
717
1109
  return join(folder, bin);
718
1110
  }
719
1111
  //#endregion
1112
+ //#region src/verify/surface-types.ts
1113
+ const NAMED = ts.SymbolFlags.Interface | ts.SymbolFlags.Class | ts.SymbolFlags.Enum | ts.SymbolFlags.TypeAlias;
1114
+ function isObjectType$1(type) {
1115
+ return (type.flags & ts.TypeFlags.Object) !== 0;
1116
+ }
1117
+ function isReference(type) {
1118
+ return (type.objectFlags & ts.ObjectFlags.Reference) !== 0;
1119
+ }
1120
+ function isPublicMember(member) {
1121
+ const hidden = ts.ModifierFlags.Private | ts.ModifierFlags.Protected;
1122
+ return (ts.getCombinedModifierFlags(member) & hidden) === 0 && !(member.name !== void 0 && ts.isPrivateIdentifier(member.name));
1123
+ }
1124
+ /** A class declaration reduced to the members a consumer can reach; any other declaration as it is. */
1125
+ function publicPart(declaration) {
1126
+ if (!ts.isClassDeclaration(declaration)) return declaration;
1127
+ return ts.factory.updateClassDeclaration(declaration, declaration.modifiers, declaration.name, declaration.typeParameters, declaration.heritageClauses, declaration.members.filter(isPublicMember));
1128
+ }
1129
+ /** Walks the types a set of signatures reaches and prints every declaration of the package among them. */
1130
+ var DeclarationWalk = class {
1131
+ found = /* @__PURE__ */ new Map();
1132
+ seen = /* @__PURE__ */ new Set();
1133
+ printer = ts.createPrinter({ removeComments: true });
1134
+ checker;
1135
+ isLocal;
1136
+ constructor(checker, isLocal) {
1137
+ this.checker = checker;
1138
+ this.isLocal = isLocal;
1139
+ }
1140
+ signature(signature) {
1141
+ for (const parameter of signature.getParameters()) this.type(this.checker.getTypeOfSymbol(parameter));
1142
+ this.type(signature.getReturnType());
1143
+ }
1144
+ record(symbol) {
1145
+ if (this.found.has(symbol.name) || (symbol.flags & NAMED) === 0 || !this.isLocal(symbol)) return;
1146
+ const texts = (symbol.declarations ?? []).map((declaration) => this.printer.printNode(ts.EmitHint.Unspecified, publicPart(declaration), declaration.getSourceFile()).replace(/\s+/g, " ").replace(/^(?:export )?(?:declare )?/, ""));
1147
+ this.found.set(symbol.name, texts.join(" "));
1148
+ }
1149
+ members(type) {
1150
+ for (const property of this.checker.getPropertiesOfType(type)) this.type(this.checker.getTypeOfSymbol(property));
1151
+ for (const signature of [...type.getCallSignatures(), ...type.getConstructSignatures()]) this.signature(signature);
1152
+ }
1153
+ type(type) {
1154
+ if (this.seen.has(type)) return;
1155
+ this.seen.add(type);
1156
+ if (type.isUnionOrIntersection()) {
1157
+ for (const part of type.types) this.type(part);
1158
+ return;
1159
+ }
1160
+ if (type.aliasSymbol) this.record(type.aliasSymbol);
1161
+ for (const argument of type.aliasTypeArguments ?? []) this.type(argument);
1162
+ if (isObjectType$1(type) && isReference(type)) for (const argument of this.checker.getTypeArguments(type)) this.type(argument);
1163
+ const symbol = type.getSymbol();
1164
+ if (symbol === void 0 || !this.isLocal(symbol)) return;
1165
+ this.record(symbol);
1166
+ this.members(type);
1167
+ }
1168
+ };
1169
+ /**
1170
+ * The declarations of the package that the signatures reach through their
1171
+ * parameter and answer types, transitively, each printed without comments.
1172
+ * A change inside one, such as a member's type, changes the functions that
1173
+ * reach it.
1174
+ */
1175
+ function referencedDeclarations(checker, isLocal, signatures) {
1176
+ const walk = new DeclarationWalk(checker, isLocal);
1177
+ for (const signature of signatures) walk.signature(signature);
1178
+ return [...walk.found].sort(([left], [right]) => left.localeCompare(right)).map(([, text]) => text);
1179
+ }
1180
+ //#endregion
720
1181
  //#region src/verify/surface.ts
721
1182
  const MAX_DEPTH = 4;
722
1183
  const SIGNATURE_FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.WriteArrowStyleSignature;
@@ -760,8 +1221,12 @@ function signatureTexts(walk, signatures, kind) {
760
1221
  }
761
1222
  function callableText(walk, type) {
762
1223
  const callable = walk.checker.getNonNullableType(type);
763
- const texts = [...signatureTexts(walk, callable.getCallSignatures(), ts.SignatureKind.Call), ...signatureTexts(walk, callable.getConstructSignatures(), ts.SignatureKind.Construct)];
764
- return texts.length === 0 ? void 0 : texts.join(" | ");
1224
+ const calls = callable.getCallSignatures();
1225
+ const constructs = callable.getConstructSignatures();
1226
+ const texts = [...signatureTexts(walk, calls, ts.SignatureKind.Call), ...signatureTexts(walk, constructs, ts.SignatureKind.Construct)];
1227
+ if (texts.length === 0) return void 0;
1228
+ const reached = referencedDeclarations(walk.checker, (symbol) => declaredHere(walk, symbol), [...calls, ...constructs]);
1229
+ return reached.length === 0 ? texts.join(" | ") : `${texts.join(" | ")} where ${reached.join(" ")}`;
765
1230
  }
766
1231
  function typeOf(walk, symbol) {
767
1232
  return walk.checker.getTypeOfSymbol(symbol);
@@ -816,6 +1281,15 @@ function unresolvedImports(walk, program) {
816
1281
  }
817
1282
  return missing;
818
1283
  }
1284
+ /** The nearest `node_modules/@types` holding `@types/node`, so declarations importing `node:` built-ins resolve. */
1285
+ function nodeTypeRoot(folder) {
1286
+ let current = folder;
1287
+ while (!existsSync(join(current, "node_modules", "@types", "node", "package.json"))) {
1288
+ if (dirname(current) === current) return void 0;
1289
+ current = dirname(current);
1290
+ }
1291
+ return join(current, "node_modules", "@types");
1292
+ }
819
1293
  function readManifest(folder) {
820
1294
  const manifest = parseJson(readFileSync(join(folder, "package.json"), "utf8"));
821
1295
  if (!isObject(manifest)) throw new Error(`${folder}: package.json is not an object`);
@@ -835,6 +1309,7 @@ function declaredSurface(packageFolder) {
835
1309
  if (!existsSync(file)) throw new Error(`${subpath}: ${declaration} is missing`);
836
1310
  files.set(subpath, file);
837
1311
  }
1312
+ const nodeTypes = nodeTypeRoot(folder);
838
1313
  const program = ts.createProgram([...files.values()], {
839
1314
  noEmit: true,
840
1315
  skipLibCheck: true,
@@ -842,7 +1317,10 @@ function declaredSurface(packageFolder) {
842
1317
  target: ts.ScriptTarget.ESNext,
843
1318
  module: ts.ModuleKind.ESNext,
844
1319
  moduleResolution: ts.ModuleResolutionKind.Bundler,
845
- types: []
1320
+ ...nodeTypes === void 0 ? { types: [] } : {
1321
+ typeRoots: [nodeTypes],
1322
+ types: ["node"]
1323
+ }
846
1324
  });
847
1325
  const walk = {
848
1326
  checker: program.getTypeChecker(),
@@ -850,7 +1328,7 @@ function declaredSurface(packageFolder) {
850
1328
  surface: /* @__PURE__ */ new Map()
851
1329
  };
852
1330
  const missing = unresolvedImports(walk, program);
853
- if (missing.length > 0) throw new Error(`unresolved imports in declarations: ${missing.join(", ")}`);
1331
+ if (missing.length > 0) throw new Error(`unresolved imports in declarations: ${missing.join(", ")}${nodeTypes === void 0 && missing.some((entry) => entry.includes("-> node:")) ? "; install @types/node so node: built-ins resolve" : ""}`);
854
1332
  for (const [subpath, file] of files) {
855
1333
  const source = program.getSourceFile(file);
856
1334
  const module = source && walk.checker.getSymbolAtLocation(source);
@@ -2515,20 +2993,18 @@ async function runFeature(workspace, state, feature, ids) {
2515
2993
  }
2516
2994
  //#endregion
2517
2995
  //#region src/verify/seeded.ts
2996
+ /** Runs a command in a scratch worktree; a failure carries the command's own output, which pnpm writes to stdout. */
2518
2997
  function inTree(worktree, program, args) {
2519
- return execFileSync(program, args, {
2998
+ const run = spawnSync(program, args, {
2520
2999
  cwd: worktree,
2521
3000
  encoding: "utf8",
2522
3001
  env: {
2523
3002
  ...process.env,
2524
3003
  CI: "1"
2525
- },
2526
- stdio: [
2527
- "ignore",
2528
- "pipe",
2529
- "pipe"
2530
- ]
2531
- }).trim();
3004
+ }
3005
+ });
3006
+ if (run.status !== 0) throw new Error(`${[program, ...args].join(" ")} exited ${run.status ?? run.signal} in ${worktree}\n${`${run.stdout ?? ""}${run.stderr ?? ""}${run.error?.message ?? ""}`.trim().slice(-2e3)}`);
3007
+ return run.stdout.trim();
2532
3008
  }
2533
3009
  function prepareWorktree(workspace, label, feature) {
2534
3010
  const worktree = mkdtempSync(join(tmpdir(), `antelopejs-verify-seeded-${label}-`));
@@ -2751,8 +3227,10 @@ function formalSection(workspace, state, plan, link) {
2751
3227
  if (gate) reasons.push(`formal check ${check.name} covers the diff but was not run`);
2752
3228
  continue;
2753
3229
  }
2754
- if (gate && (result.violated.length > 0 || result.exitCode !== 0)) reasons.push(`formal check ${check.name}: ${result.violated.length > 0 ? `violated ${result.violated.join(", ")}` : `exit ${result.exitCode}`}`);
2755
- const summary = result.violated.length > 0 ? `violated: ${result.violated.join(", ")}` : `exit ${result.exitCode}, no violated rule`;
3230
+ if (gate && result.behaviour === void 0 && result.exitCode === 0) reasons.push(`formal check ${check.name} covers the diff but its run did not compare the covered behaviour with the base`);
3231
+ const weight = formalGate(result);
3232
+ if (gate && weight.fails) reasons.push(`formal check ${check.name}: ${weight.outcome}`);
3233
+ const summary = gate ? weight.outcome : result.violated.length > 0 ? `violated: ${result.violated.join(", ")}` : `exit ${result.exitCode}, no violated rule`;
2756
3234
  lines.push(`\`${check.name}\` (${gate ? "covers the diff, gates the verdict" : "does not cover the diff, informational"}): ${summary}. [evidence](${link(result.folder)})`);
2757
3235
  }
2758
3236
  return {
@@ -2866,7 +3344,7 @@ const USAGE = `Usage: antelopejs-verify <command>
2866
3344
  new [--base <ref>] [--title <t>] build, prepare an isolated run, print its folder
2867
3345
  doctor <run> check the run is worth driving
2868
3346
  journey <run> <feature> [ids...] run a feature's journeys and record evidence
2869
- formal <run> [--all] run the formal checks that cover the diff, or every one
3347
+ formal <run> [--all] run the formal checks that cover the diff and gate them on changed behaviour
2870
3348
  doors [patch] [--base <ref>] print the One-way-door line for a patch, or for the diff
2871
3349
  seeded <feature...> [--base <ref>] run each feature unpatched and with its seeded break
2872
3350
  seeded-doors check every seeded door is flagged with its kind
@@ -2903,13 +3381,22 @@ async function runJourneys(workspace, dir, feature, ids) {
2903
3381
  }
2904
3382
  function runFormal(workspace, dir, all) {
2905
3383
  const state = loadRun(dir);
2906
- const checks = all ? workspace.config.formal ?? [] : touchedFormalChecks(workspace, planFor(workspace, state.baseRef).changed);
3384
+ const plan = planFor(workspace, state.baseRef);
3385
+ const touched = touchedFormalChecks(workspace, plan.changed);
3386
+ const checks = all ? workspace.config.formal ?? [] : touched;
3387
+ let fails = false;
2907
3388
  for (const check of checks) {
2908
- const result = runFormalCheck(workspace, state, check);
2909
- print(`${result.violated.length > 0 ? "VIOLATED" : result.exitCode === 0 ? "HOLDS" : "ERROR"} ${check.name}${result.violated.length > 0 ? `: ${result.violated.join(", ")}` : ""} (exit ${result.exitCode})`);
3389
+ const gates = touched.includes(check);
3390
+ const weight = formalGate(runFormalCheck(workspace, state, check, gates ? {
3391
+ baseSha: plan.baseSha,
3392
+ headSha: plan.headSha,
3393
+ changed: plan.changed
3394
+ } : null));
3395
+ fails ||= gates && weight.fails;
3396
+ print(`${gates ? weight.fails ? "FAIL" : "PASS" : "INFO"} ${check.name}: ${weight.outcome}`);
2910
3397
  }
2911
3398
  if (checks.length === 0) print("no formal check covers the diff");
2912
- return checks.every((check) => readFormalResult(state, check.name)?.exitCode === 0) ? 0 : 1;
3399
+ return fails ? 1 : 0;
2913
3400
  }
2914
3401
  function printDoors(workspace, files) {
2915
3402
  const doors = flaggedDoors(workspace, files);
@@ -20,12 +20,34 @@ interface DoorRule {
20
20
  }
21
21
  /** Every door kind with its rule, or `null` when the kind cannot apply to the repository. */
22
22
  type DoorRules = { [Kind in DoorKind]: DoorRule | null; };
23
- /** A formal check, the source files it covers, the command that runs it and how its output names a violated rule. */
23
+ /**
24
+ * How `formal` decides whether a diff changed what the covered code does:
25
+ * `emit` compares the structure of the covered files' JavaScript on the
26
+ * base and on HEAD (top-level statements in order per file, function
27
+ * declarations apart); `probe` runs `command` with a worktree of each commit as its last
28
+ * argument and compares what it prints.
29
+ */
30
+ type BehaviourMethod = {
31
+ kind: "emit";
32
+ } | {
33
+ kind: "probe";
34
+ command: string[];
35
+ };
36
+ /** A formal check, the source files it covers, its own files, the command that runs it and how its output names a violated and a passing rule. */
24
37
  interface FormalCheck {
25
38
  name: string;
26
39
  covers: string[];
40
+ /** Globs of the check's own files (its model, its tests): a diff that changes one also runs the check on the base. */
41
+ files?: string[];
42
+ /** Runs from the repository root; exits 0 while every finding breaks as recorded. */
27
43
  command: string[];
28
44
  violation: RegExp | null;
45
+ /** The first capture group names a rule the output reports as holding; a base finding counts as fixed only when HEAD reports it so. Without `passing` and `violation`, a zero exit is the one rule `property` holding. */
46
+ passing?: RegExp | null;
47
+ /** How a diff is judged to change the covered behaviour; `emit` by default. */
48
+ behaviour?: BehaviourMethod;
49
+ /** The command run on a worktree of the base when the covered behaviour or the check's own files changed, to tell which findings HEAD fixed; `command` by default. */
50
+ baseCommand?: string[];
29
51
  }
30
52
  /** A backing service the harness runs in Docker for every run, published on a free loopback port. */
31
53
  interface ServiceDefinition {
@@ -259,4 +281,4 @@ declare function answers(result: HttpResult, key: string, expected: JsonValue):
259
281
  /** Nothing answered the request. */
260
282
  declare function refused(result: HttpResult): Check;
261
283
  //#endregion
262
- export { type App, type CallRequest, type CallResult, type Check, type CommandResult, type DevOptions, type DoorKind, type DoorRule, type DoorRules, type DriveOptions, type FormalCheck, type HttpResult, type InterfaceCall, type InterfaceHooks, type Journey, type JourneyContext, type ServiceDefinition, type ServiceEndpoint, type StopResult, type TemplateProbe, type VerifyConfig, answered, answers, equal, exists, exitIs, fileHas, has, interrupted, lacks, refused };
284
+ export { type App, type BehaviourMethod, type CallRequest, type CallResult, type Check, type CommandResult, type DevOptions, type DoorKind, type DoorRule, type DoorRules, type DriveOptions, type FormalCheck, type HttpResult, type InterfaceCall, type InterfaceHooks, type Journey, type JourneyContext, type ServiceDefinition, type ServiceEndpoint, type StopResult, type TemplateProbe, type VerifyConfig, answered, answers, equal, exists, exitIs, fileHas, has, interrupted, lacks, refused };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/tooling-configs",
3
- "version": "0.2.12",
3
+ "version": "0.2.13",
4
4
  "description": "Shared tooling presets for AntelopeJS repositories: oxlint (with the vendored anti-slop rules), oxfmt, ESLint for Nuxt layers, Knip, and an interface range check",
5
5
  "keywords": [
6
6
  "antelopejs",