@antelopejs/tooling-configs 0.2.11 → 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.
@@ -0,0 +1,3487 @@
1
+ #!/usr/bin/env node
2
+ import { a as isString, f as parseJson, i as isObject, u as optStr } from "../json-BqvuCkqr.mjs";
3
+ import { a as exitIs, c as interrupted, i as exists, r as equal, u as refused } from "../checks-BlWDFYio.mjs";
4
+ import { n as runCliAsync } from "../cli-4Tv71vYk.mjs";
5
+ import { o as repositoryRoot } from "../files-2FikHZ9F.mjs";
6
+ import { a as skillFolder, i as isVerifyKind, t as VERIFY_KINDS } from "../kinds-Bzyyi9yk.mjs";
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, extname, join, matchesGlob, posix, relative, resolve, sep } from "node:path";
9
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
10
+ import { parseArgs } from "node:util";
11
+ import { pathToFileURL } from "node:url";
12
+ import { homedir, tmpdir } from "node:os";
13
+ import ts from "typescript";
14
+ import { randomBytes } from "node:crypto";
15
+ import { createServer } from "node:net";
16
+ //#region src/verify/doors.ts
17
+ const RELEASE_FILES = [
18
+ "package.json",
19
+ ".release-it.json",
20
+ "changelogen.config.json",
21
+ ".github/workflows/release.yml"
22
+ ];
23
+ /** The pack's default path rules per repository kind; a repo's `doors` block adds to them. */
24
+ const DEFAULT_DOOR_GLOBS = {
25
+ interface: {
26
+ contract: ["src/**", "package.json"],
27
+ publish: RELEASE_FILES
28
+ },
29
+ module: {
30
+ contract: ["package.json"],
31
+ publish: RELEASE_FILES
32
+ },
33
+ template: {}
34
+ };
35
+ /** Every path rule of a door kind: the kind's defaults, the repo's globs and its declared funnels. */
36
+ function doorGlobs(workspace, kind) {
37
+ const rule = workspace.config.doors[kind];
38
+ if (!rule) return [];
39
+ return [.../* @__PURE__ */ new Set([
40
+ ...DEFAULT_DOOR_GLOBS[workspace.kind][kind] ?? [],
41
+ ...rule.globs,
42
+ ...rule.funnels
43
+ ])];
44
+ }
45
+ /** The door kinds whose path rules `files` hit. */
46
+ function flaggedDoors(workspace, files) {
47
+ return [
48
+ "data",
49
+ "format",
50
+ "contract",
51
+ "outbound",
52
+ "exposure",
53
+ "publish"
54
+ ].flatMap((kind) => {
55
+ const globs = doorGlobs(workspace, kind);
56
+ const hits = files.filter((file) => globs.some((glob) => matchesGlob(file, glob)));
57
+ return hits.length > 0 ? [{
58
+ kind,
59
+ files: hits
60
+ }] : [];
61
+ });
62
+ }
63
+ /** The files a unified diff changes, read from its `+++ b/` headers. */
64
+ function patchFiles(patch) {
65
+ return [...readFileSync(patch, "utf8").matchAll(/^\+\+\+ b\/(.+)$/gm)].map((match) => match[1]);
66
+ }
67
+ /** The `One-way-door:` line for flagged kinds, or nothing when none is flagged. */
68
+ function doorLine(doors) {
69
+ return doors.length > 0 ? `One-way-door: ${doors.map((door) => door.kind).join(", ")}` : "";
70
+ }
71
+ //#endregion
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
90
+ });
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}`);
118
+ }
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
+ };
151
+ }
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 "";
162
+ }
163
+ function dropped(node) {
164
+ return node.kind === ts.SyntaxKind.ExportKeyword || node.kind === ts.SyntaxKind.DefaultKeyword;
165
+ }
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));
177
+ });
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
+ }
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
+ }];
222
+ }
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: {}
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;
248
+ }
249
+ //#endregion
250
+ //#region src/verify/workspace.ts
251
+ /**
252
+ * Caches shared by every run: the warm pnpm store, the npm cache and the
253
+ * published packages. Nothing a journey asserts on lives here.
254
+ */
255
+ const CACHE_DIR = join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "antelopejs-verify");
256
+ /** Runs git in `cwd` and returns its trimmed output. */
257
+ function git(cwd, args) {
258
+ return execFileSync("git", args, {
259
+ cwd,
260
+ encoding: "utf8",
261
+ stdio: [
262
+ "ignore",
263
+ "pipe",
264
+ "pipe"
265
+ ]
266
+ }).trim();
267
+ }
268
+ function readManifest$1(root) {
269
+ const file = join(root, "package.json");
270
+ const value = existsSync(file) ? parseJson(readFileSync(file, "utf8")) : {};
271
+ return isObject(value) ? value : {};
272
+ }
273
+ /** Opens the repository at `root` for `kind`, loading the repo-owned verify.config.ts. */
274
+ async function openWorkspace(root, kind) {
275
+ const skill = join(root, skillFolder(kind));
276
+ const file = join(skill, "verify.config.ts");
277
+ if (!existsSync(file)) throw new Error(`${file} is missing. Write the repo-owned layer (verify.config.ts and features/) described in ${skillFolder(kind)}/SKILL.md.`);
278
+ const config = (await import(pathToFileURL(file).href)).default;
279
+ if (config?.doors === void 0) throw new Error(`${file} must export default a VerifyConfig with a doors block.`);
280
+ const manifest = readManifest$1(root);
281
+ return {
282
+ root,
283
+ kind,
284
+ skill,
285
+ config,
286
+ manifest,
287
+ name: String(manifest.name ?? basename(root)).replace(/^@[^/]+\//, "").replace(/[^a-z0-9-]+/gi, "-")
288
+ };
289
+ }
290
+ function stateFile(dir) {
291
+ return join(dir, "run.json");
292
+ }
293
+ /** Reads a run created by `new`, failing with the reason when it is missing. */
294
+ function loadRun(dir) {
295
+ const file = stateFile(resolve(dir));
296
+ if (!existsSync(file)) throw new Error(`No run at ${dir}: run.json is missing. Create one with \`new\`.`);
297
+ return JSON.parse(readFileSync(file, "utf8"));
298
+ }
299
+ /** Persists the run state. */
300
+ function saveRun(state) {
301
+ writeFileSync(stateFile(state.dir), `${JSON.stringify(state, null, 2)}\n`);
302
+ }
303
+ /** Allocates the folders of a new run under the system temp folder. */
304
+ function allocateRun(workspace, baseRef, title) {
305
+ const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").slice(0, 15)}-${randomBytes(3).toString("hex")}`;
306
+ const dir = join(tmpdir(), "antelopejs-verify", workspace.name, id);
307
+ const evidence = join(dir, "evidence");
308
+ mkdirSync(evidence, { recursive: true });
309
+ return {
310
+ id,
311
+ kind: workspace.kind,
312
+ repo: workspace.root,
313
+ dir,
314
+ evidence,
315
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
316
+ headSha: git(workspace.root, ["rev-parse", "HEAD"]),
317
+ baseRef,
318
+ title,
319
+ processes: [],
320
+ containers: [],
321
+ pack: "",
322
+ manifestUrl: "",
323
+ templateName: "",
324
+ missingKeys: (workspace.config.saas?.env ?? []).filter((key) => !process.env[key])
325
+ };
326
+ }
327
+ const INHERITED_PREFIXES = [
328
+ "ANTELOPEJS_",
329
+ "npm_",
330
+ "PNPM_",
331
+ "XDG_"
332
+ ];
333
+ /**
334
+ * The environment every driven command gets: the journey's HOME, CI=1, no
335
+ * update check, no colors and the shared caches. Variables that could leak
336
+ * the operator's own settings into the run are dropped.
337
+ */
338
+ function isolatedEnv(workspace, home, extra = {}) {
339
+ const kept = Object.entries(process.env).filter(([key]) => !INHERITED_PREFIXES.some((prefix) => key.startsWith(prefix)));
340
+ return {
341
+ ...Object.fromEntries(kept),
342
+ HOME: home,
343
+ USERPROFILE: home,
344
+ CI: "1",
345
+ AJS_NO_UPDATE_CHECK: "1",
346
+ NO_COLOR: "1",
347
+ COREPACK_HOME: process.env.COREPACK_HOME ?? join(homedir(), ".cache", "node", "corepack"),
348
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: "0",
349
+ XDG_DATA_HOME: join(CACHE_DIR, "xdg-data"),
350
+ XDG_CACHE_HOME: join(home, ".cache"),
351
+ XDG_CONFIG_HOME: join(home, ".config"),
352
+ npm_config_cache: join(CACHE_DIR, "npm"),
353
+ npm_config_prefer_offline: "true",
354
+ GIT_CONFIG_NOSYSTEM: "1",
355
+ ...workspace.config.env,
356
+ ...extra
357
+ };
358
+ }
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
691
+ //#region src/verify/docker.ts
692
+ const READY_TIMEOUT_MS$1 = 9e4;
693
+ function docker(args) {
694
+ const run = spawnSync("docker", args, { encoding: "utf8" });
695
+ return {
696
+ status: run.status,
697
+ stdout: run.stdout ?? "",
698
+ stderr: `${run.stderr ?? ""}${run.error ? `${run.error.message}\n` : ""}`
699
+ };
700
+ }
701
+ function record(folder, args, result) {
702
+ mkdirSync(folder, { recursive: true });
703
+ writeFileSync(join(folder, "command.txt"), `docker ${args.join(" ")}\n`);
704
+ writeFileSync(join(folder, "stdout.txt"), result.stdout);
705
+ writeFileSync(join(folder, "stderr.txt"), result.stderr);
706
+ writeFileSync(join(folder, "exit-code.txt"), `${result.status}\n`);
707
+ }
708
+ function publishedPort(container, port) {
709
+ const mapping = docker([
710
+ "port",
711
+ container,
712
+ `${port}/tcp`
713
+ ]).stdout;
714
+ const match = /127\.0\.0\.1:(\d+)/.exec(mapping);
715
+ if (!match) throw new Error(`${container} does not publish ${port}: ${mapping}`);
716
+ return Number(match[1]);
717
+ }
718
+ function waitReady(container, ready, folder) {
719
+ const deadline = Date.now() + READY_TIMEOUT_MS$1;
720
+ let last = docker([
721
+ "exec",
722
+ container,
723
+ ...ready
724
+ ]);
725
+ while (last.status !== 0 && Date.now() < deadline) {
726
+ spawnSync("sleep", ["0.5"]);
727
+ last = docker([
728
+ "exec",
729
+ container,
730
+ ...ready
731
+ ]);
732
+ }
733
+ record(folder, [
734
+ "exec",
735
+ container,
736
+ ...ready
737
+ ], last);
738
+ if (last.status !== 0) throw new Error(`${container} was not ready within ${READY_TIMEOUT_MS$1} ms: ${last.stderr}`);
739
+ }
740
+ /**
741
+ * Starts every service of verify.config.ts in its own container, named
742
+ * `<prefix>-<repo>-<service>-<run id>`, publishes its port on a free
743
+ * loopback port chosen by Docker, and waits for its readiness command. Each
744
+ * container is recorded before it is probed, so `clean` removes it even when
745
+ * it never became ready.
746
+ */
747
+ function startServices(workspace, state, prefix) {
748
+ for (const [service, definition] of Object.entries(workspace.config.services ?? {})) {
749
+ const name = `${prefix}-${workspace.name}-${service}-${state.id}`.toLowerCase();
750
+ const env = Object.entries(definition.env ?? {}).flatMap(([key, value]) => ["-e", `${key}=${value}`]);
751
+ const args = [
752
+ "run",
753
+ "-d",
754
+ "--name",
755
+ name,
756
+ "-p",
757
+ `127.0.0.1::${definition.port}`,
758
+ ...env,
759
+ definition.image
760
+ ];
761
+ const folder = join(state.evidence, "services", service);
762
+ const started = docker(args);
763
+ record(join(folder, "01-run"), args, started);
764
+ if (started.status !== 0) throw new Error(`docker ${args.join(" ")} failed: ${started.stderr}`);
765
+ const container = {
766
+ service,
767
+ name,
768
+ host: "127.0.0.1",
769
+ port: 0
770
+ };
771
+ state.containers.push(container);
772
+ saveRun(state);
773
+ container.port = publishedPort(name, definition.port);
774
+ saveRun(state);
775
+ waitReady(name, definition.ready, join(folder, "02-ready"));
776
+ }
777
+ }
778
+ /** Whether a recorded container is running. */
779
+ function containerRunning(name) {
780
+ return docker([
781
+ "inspect",
782
+ "-f",
783
+ "{{.State.Running}}",
784
+ name
785
+ ]).stdout.trim() === "true";
786
+ }
787
+ /** Removes a container this run started, by its recorded name. */
788
+ function removeContainer(name) {
789
+ return docker([
790
+ "rm",
791
+ "-f",
792
+ "-v",
793
+ name
794
+ ]).status === 0;
795
+ }
796
+ //#endregion
797
+ //#region src/verify/fixture-modules.ts
798
+ const WALK = String.raw`
799
+ const fs = require("node:fs");
800
+ const { pathToFileURL } = require("node:url");
801
+
802
+ const entries = JSON.parse(process.env.VERIFY_ENTRIES || "{}");
803
+
804
+ function load(name, entry) {
805
+ return require(entry === "." ? name : name + "/" + entry.replace(/^\.\//, ""));
806
+ }
807
+
808
+ function isClass(value) {
809
+ return /^class[\s{]/.test(Function.prototype.toString.call(value));
810
+ }
811
+
812
+ function kindOf(value) {
813
+ if (typeof value === "function") {
814
+ if (value.proxy && typeof value.proxy.onCall === "function") return "async";
815
+ return isClass(value) ? "class" : "function";
816
+ }
817
+ if (!value || typeof value !== "object") return "value";
818
+ if (typeof value.onCall === "function" && typeof value.call === "function") return "async";
819
+ if (typeof value.onHandlers === "function" || typeof value.onRegister === "function") return "registering";
820
+ if (typeof value.emit === "function" && typeof value.register === "function") return "event";
821
+ const prototype = Object.getPrototypeOf(value);
822
+ return prototype === Object.prototype || prototype === null ? "namespace" : "value";
823
+ }
824
+
825
+ function walk(value, keys, visit) {
826
+ for (const key of Object.keys(value)) {
827
+ if (key === "__esModule") continue;
828
+ const member = value[key];
829
+ const kind = kindOf(member);
830
+ if (kind === "namespace") {
831
+ if (keys.length < 4) walk(member, [...keys, key], visit);
832
+ continue;
833
+ }
834
+ visit([...keys, key], kind, member);
835
+ }
836
+ }
837
+
838
+ async function loadHooks() {
839
+ if (!process.env.VERIFY_CONFIG) return {};
840
+ const config = (await import(pathToFileURL(process.env.VERIFY_CONFIG).href)).default;
841
+ return (config && config.interface) || {};
842
+ }
843
+ `;
844
+ /** The driver module: the consumer every fixture project loads, answering HTTP calls by calling interfaces through core. */
845
+ const DRIVER_SOURCE = String.raw`"use strict";
846
+ const http = require("node:http");
847
+ ${WALK}
848
+ const TIMEOUT_MS = 15000;
849
+ const interfaces = Object.keys(entries);
850
+ let server;
851
+ let hooks = {};
852
+
853
+ function settle(value) {
854
+ return Promise.race([
855
+ Promise.resolve(value),
856
+ new Promise((_, reject) => setTimeout(() => reject(Object.assign(new Error("did not settle within " + TIMEOUT_MS + " ms"), { name: "Timeout" })), TIMEOUT_MS).unref()),
857
+ ]);
858
+ }
859
+
860
+ function serializable(value) {
861
+ try {
862
+ return JSON.parse(JSON.stringify(value === undefined ? null : value));
863
+ } catch {
864
+ return { unserializable: String(value) };
865
+ }
866
+ }
867
+
868
+ function target(body) {
869
+ const name = body.interface || interfaces[0];
870
+ let owner;
871
+ let value = load(name, body.entry || ".");
872
+ for (const key of body.path) {
873
+ owner = value;
874
+ value = value[key];
875
+ }
876
+ return { owner, value };
877
+ }
878
+
879
+ function surface() {
880
+ const found = [];
881
+ for (const name of interfaces) {
882
+ for (const entry of entries[name]) {
883
+ walk(load(name, entry), [], (keys, kind) => found.push({ interface: name, entry, path: entry + ":" + keys.join("."), kind }));
884
+ }
885
+ }
886
+ return found;
887
+ }
888
+
889
+ async function call(body) {
890
+ const { owner, value: member } = target(body);
891
+ const args = body.args || [];
892
+ let value = await settle(kindOf(member) === "async" && typeof member !== "function" ? member.call(...args) : member.apply(owner, args));
893
+ for (const [method, ...rest] of body.chain || []) value = await settle(value[method](...rest));
894
+ return value;
895
+ }
896
+
897
+ async function registering(body) {
898
+ const { value: proxy } = target(body);
899
+ await settle(proxy.register("verify-registration", () => "verify-handler"));
900
+ await settle(proxy.unregister("verify-registration"));
901
+ return "registered and unregistered";
902
+ }
903
+
904
+ async function event(body) {
905
+ const { value: proxy } = target(body);
906
+ let received = null;
907
+ const handler = (...args) => {
908
+ received = args;
909
+ };
910
+ proxy.register(handler);
911
+ proxy.emit(...(body.args || []));
912
+ proxy.unregister(handler);
913
+ return received;
914
+ }
915
+
916
+ async function hook(body) {
917
+ const entry = body.path.slice(0, body.path.indexOf(":"));
918
+ const found = (hooks.calls || {})[body.path];
919
+ if (!found) throw new Error("verify.config.ts has no interface.calls hook for " + body.path);
920
+ return found.call(load(body.interface || interfaces[0], entry));
921
+ }
922
+
923
+ const ROUTES = { "/surface": async () => surface(), "/call": call, "/registering": registering, "/event": event, "/hook": hook };
924
+
925
+ async function answer(request) {
926
+ if (request.url === "/health") return { ok: true };
927
+ const route = ROUTES[request.url];
928
+ if (!route) return { ok: false, error: { name: "NotFound", message: request.url } };
929
+ let text = "";
930
+ for await (const chunk of request) text += chunk;
931
+ try {
932
+ return { ok: true, value: serializable(await route(text ? JSON.parse(text) : {})) };
933
+ } catch (error) {
934
+ return { ok: false, error: { name: (error && error.name) || "Error", message: String((error && error.message) || error) } };
935
+ }
936
+ }
937
+
938
+ exports.construct = function construct() {};
939
+ exports.start = async function start() {
940
+ hooks = await loadHooks();
941
+ server = http.createServer((request, response) => {
942
+ answer(request).then((result) => {
943
+ response.setHeader("content-type", "application/json");
944
+ response.end(JSON.stringify(result));
945
+ });
946
+ });
947
+ await new Promise((resolve) => server.listen(Number(process.env.VERIFY_DRIVER_PORT), "127.0.0.1", resolve));
948
+ };
949
+ exports.stop = function stop() {
950
+ if (server) server.close();
951
+ };
952
+ exports.destroy = function destroy() {};
953
+ `;
954
+ /** The stub provider module of the interface kind: implements every proxy of the interface through ImplementInterface and logs each call. */
955
+ const STUB_SOURCE = String.raw`"use strict";
956
+ const { ImplementInterface } = require("@antelopejs/interface-core");
957
+ ${WALK}
958
+ function note(path, args) {
959
+ fs.appendFileSync(process.env.VERIFY_CALL_LOG, JSON.stringify({ path, args }) + "\n");
960
+ }
961
+
962
+ function place(tree, keys, leaf) {
963
+ let node = tree;
964
+ for (const key of keys.slice(0, -1)) node = node[key] = node[key] || {};
965
+ node[keys[keys.length - 1]] = leaf;
966
+ }
967
+
968
+ function stubs(entry, api) {
969
+ const tree = {};
970
+ walk(api, [], (keys, kind) => {
971
+ const path = entry + ":" + keys.join(".");
972
+ if (kind === "async") place(tree, keys, (...args) => (note(path, args), { stub: path, args }));
973
+ if (kind === "registering")
974
+ place(tree, keys, { register: (id) => note(path + ".register", [id]), unregister: (id) => note(path + ".unregister", [id]) });
975
+ });
976
+ return tree;
977
+ }
978
+
979
+ exports.construct = async function construct() {
980
+ for (const [name, list] of Object.entries(entries)) {
981
+ for (const entry of list) {
982
+ const api = load(name, entry);
983
+ ImplementInterface(api, stubs(entry, api));
984
+ }
985
+ }
986
+ const hooks = await loadHooks();
987
+ if (hooks.provide) await hooks.provide(load(Object.keys(entries)[0], "."));
988
+ };
989
+ exports.start = function start() {};
990
+ exports.stop = function stop() {};
991
+ exports.destroy = function destroy() {};
992
+ `;
993
+ //#endregion
994
+ //#region src/verify/fixture.ts
995
+ function readPackage(folder) {
996
+ const value = parseJson(readFileSync(join(folder, "package.json"), "utf8"));
997
+ return isObject(value) ? value : {};
998
+ }
999
+ /** The runtime export subpaths of a package: every `exports` key but `./package.json` and patterns, or `.` alone. */
1000
+ function runtimeEntries(manifest) {
1001
+ const exported = manifest.exports;
1002
+ if (exported === void 0 || exported === null || isString(exported) || !isObject(exported)) return ["."];
1003
+ const keys = Object.keys(exported).filter((key) => key.startsWith("."));
1004
+ if (keys.length === 0) return ["."];
1005
+ return keys.filter((key) => key !== "./package.json" && !key.includes("*"));
1006
+ }
1007
+ /** The interfaces a module declares in `antelopeJs.implements`. */
1008
+ function implementedInterfaces(manifest) {
1009
+ const antelope = manifest.antelopeJs;
1010
+ if (antelope === void 0 || !isObject(antelope)) return [];
1011
+ const list = antelope.implements;
1012
+ return Array.isArray(list) ? list.filter(isString) : [];
1013
+ }
1014
+ /** The real folder of a dependency installed in the repository, or a clear error naming what to install. */
1015
+ function installedPackage(root, name) {
1016
+ const folder = join(root, "node_modules", name);
1017
+ if (!existsSync(folder)) throw new Error(`${name} is not installed in ${root}. Run the package manager's install first.`);
1018
+ return realpathSync(folder);
1019
+ }
1020
+ function link(target, path) {
1021
+ mkdirSync(dirname(path), { recursive: true });
1022
+ symlinkSync(target, path, "dir");
1023
+ }
1024
+ function writeModule(folder, manifest, source, links) {
1025
+ mkdirSync(folder, { recursive: true });
1026
+ writeFileSync(join(folder, "package.json"), `${JSON.stringify(manifest, null, 2)}\n`);
1027
+ writeFileSync(join(folder, "index.js"), source);
1028
+ for (const [name, target] of links) link(target, join(folder, "node_modules", name));
1029
+ }
1030
+ function interfaceLinks(workspace, state) {
1031
+ const core = installedPackage(workspace.root, "@antelopejs/interface-core");
1032
+ if (workspace.kind === "interface") {
1033
+ const name = String(workspace.manifest.name);
1034
+ return {
1035
+ links: /* @__PURE__ */ new Map([[name, state.pack], ["@antelopejs/interface-core", core]]),
1036
+ entries: { [name]: runtimeEntries(readPackage(state.pack)) }
1037
+ };
1038
+ }
1039
+ const links = /* @__PURE__ */ new Map([["@antelopejs/interface-core", core]]);
1040
+ const entries = {};
1041
+ for (const name of implementedInterfaces(workspace.manifest)) {
1042
+ const folder = installedPackage(workspace.root, name);
1043
+ links.set(name, folder);
1044
+ entries[name] = runtimeEntries(readPackage(folder));
1045
+ }
1046
+ return {
1047
+ links,
1048
+ entries
1049
+ };
1050
+ }
1051
+ /**
1052
+ * Writes the fixture project of a journey: an `antelope.config.ts` loading
1053
+ * the driver module and, for the interface kind, the stub provider, or, for
1054
+ * the module kind, the module under verification as a `local` source. Every
1055
+ * interface the driver calls is linked to the copy the repository resolves,
1056
+ * so the project shares one copy per interface as core requires.
1057
+ */
1058
+ function writeFixture(workspace, state, folder, moduleConfig) {
1059
+ const project = join(folder, "project");
1060
+ const { links, entries } = interfaceLinks(workspace, state);
1061
+ const modules = {};
1062
+ if (workspace.kind === "interface") {
1063
+ writeModule(join(project, "stub"), {
1064
+ name: "verify-stub",
1065
+ version: "1.0.0",
1066
+ main: "index.js",
1067
+ antelopeJs: { implements: Object.keys(entries) }
1068
+ }, STUB_SOURCE, links);
1069
+ modules["verify-stub"] = { source: {
1070
+ type: "local",
1071
+ path: "./stub"
1072
+ } };
1073
+ } else modules[workspace.name] = {
1074
+ source: {
1075
+ type: "local",
1076
+ path: workspace.root
1077
+ },
1078
+ config: moduleConfig
1079
+ };
1080
+ writeModule(join(project, "driver"), {
1081
+ name: "verify-driver",
1082
+ version: "1.0.0",
1083
+ main: "index.js"
1084
+ }, DRIVER_SOURCE, links);
1085
+ modules["verify-driver"] = { source: {
1086
+ type: "local",
1087
+ path: "./driver"
1088
+ } };
1089
+ writeFileSync(join(project, "antelope.config.ts"), `export default ${JSON.stringify({
1090
+ name: `verify-${workspace.name}`,
1091
+ modules
1092
+ }, null, 2)};\n`);
1093
+ const config = join(workspace.skill, "verify.config.ts");
1094
+ return {
1095
+ project,
1096
+ env: {
1097
+ VERIFY_ENTRIES: JSON.stringify(entries),
1098
+ VERIFY_CALL_LOG: join(folder, "calls.jsonl"),
1099
+ VERIFY_CONFIG: config
1100
+ }
1101
+ };
1102
+ }
1103
+ /** The `ajs` entry of the `@antelopejs/core` the repository installs. */
1104
+ function ajsEntry(root) {
1105
+ const folder = installedPackage(root, "@antelopejs/core");
1106
+ const manifest = parseJson(readFileSync(join(folder, "package.json"), "utf8"));
1107
+ const bin = isObject(manifest) && manifest.bin !== void 0 && isObject(manifest.bin) ? manifest.bin.ajs : void 0;
1108
+ if (bin === void 0 || !isString(bin)) throw new Error(`${folder} has no ajs bin`);
1109
+ return join(folder, bin);
1110
+ }
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
1181
+ //#region src/verify/surface.ts
1182
+ const MAX_DEPTH = 4;
1183
+ const SIGNATURE_FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.WriteArrowStyleSignature;
1184
+ const DECLARATION_FILE = /\.d\.[cm]?ts$/;
1185
+ function exportedDeclaration(value) {
1186
+ if (Array.isArray(value)) return value.map(exportedDeclaration).find((found) => found !== void 0);
1187
+ if (isString(value)) return DECLARATION_FILE.test(value) ? value : void 0;
1188
+ if (!isObject(value)) return void 0;
1189
+ const types = optStr(value, "types");
1190
+ if (types !== void 0) return types;
1191
+ return Object.values(value).map(exportedDeclaration).find((found) => found !== void 0);
1192
+ }
1193
+ function declarationEntries(manifest) {
1194
+ const entries = /* @__PURE__ */ new Map();
1195
+ const exported = manifest.exports;
1196
+ if (exported === void 0) {
1197
+ const types = optStr(manifest, "types") ?? optStr(manifest, "typings");
1198
+ if (types !== void 0) entries.set(".", types);
1199
+ return entries;
1200
+ }
1201
+ const subpaths = isObject(exported) && Object.keys(exported).some((key) => key[0] === ".") ? Object.entries(exported) : [[".", exported]];
1202
+ for (const [subpath, target] of subpaths) {
1203
+ if (subpath === "./package.json" || subpath.includes("*")) continue;
1204
+ const declaration = exportedDeclaration(target);
1205
+ if (declaration !== void 0) entries.set(subpath, declaration);
1206
+ }
1207
+ return entries;
1208
+ }
1209
+ function inPackage(walk, file) {
1210
+ const path = relative(walk.folder, file);
1211
+ return path !== "" && !path.startsWith("..") && !path.split(sep).includes("node_modules");
1212
+ }
1213
+ function declaredHere(walk, symbol) {
1214
+ return (symbol.declarations ?? []).some((declaration) => inPackage(walk, declaration.getSourceFile().fileName));
1215
+ }
1216
+ function resolveAlias(walk, symbol) {
1217
+ return symbol.flags & ts.SymbolFlags.Alias ? walk.checker.getAliasedSymbol(symbol) : symbol;
1218
+ }
1219
+ function signatureTexts(walk, signatures, kind) {
1220
+ return signatures.map((signature) => walk.checker.signatureToString(signature, void 0, SIGNATURE_FLAGS, kind).replace(/\s+/g, " "));
1221
+ }
1222
+ function callableText(walk, type) {
1223
+ const callable = walk.checker.getNonNullableType(type);
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(" ")}`;
1230
+ }
1231
+ function typeOf(walk, symbol) {
1232
+ return walk.checker.getTypeOfSymbol(symbol);
1233
+ }
1234
+ function isPublic(property) {
1235
+ const hidden = ts.ModifierFlags.Private | ts.ModifierFlags.Protected;
1236
+ return (property.declarations ?? []).every((declaration) => (ts.getCombinedModifierFlags(declaration) & hidden) === 0);
1237
+ }
1238
+ function recordMembers(walk, type, prefix, skip) {
1239
+ for (const property of walk.checker.getPropertiesOfType(type)) {
1240
+ if (property.name === skip || !isPublic(property)) continue;
1241
+ if (!declaredHere(walk, property)) continue;
1242
+ const text = callableText(walk, typeOf(walk, property));
1243
+ if (text !== void 0) walk.surface.set(`${prefix}${property.name}`, text);
1244
+ }
1245
+ }
1246
+ function recordClass(walk, symbol, path) {
1247
+ recordMembers(walk, typeOf(walk, symbol), `${path}.`, "prototype");
1248
+ recordMembers(walk, walk.checker.getDeclaredTypeOfSymbol(symbol), `${path}.prototype.`, "");
1249
+ }
1250
+ function isObjectType(type) {
1251
+ return (type.flags & ts.TypeFlags.Object) !== 0;
1252
+ }
1253
+ function isObjectLiteralType(walk, type) {
1254
+ const owner = type.symbol;
1255
+ return isObjectType(type) && (type.objectFlags & ts.ObjectFlags.Anonymous) !== 0 && owner !== void 0 && (owner.flags & ts.SymbolFlags.TypeLiteral) !== 0 && declaredHere(walk, owner);
1256
+ }
1257
+ function visit(walk, exported, path, trail) {
1258
+ const symbol = resolveAlias(walk, exported);
1259
+ if (trail.includes(symbol)) return;
1260
+ const depth = path.split(":")[1]?.split(".").length ?? MAX_DEPTH;
1261
+ const type = symbol.flags & ts.SymbolFlags.Value ? typeOf(walk, symbol) : void 0;
1262
+ const text = type && callableText(walk, type);
1263
+ if (text !== void 0) walk.surface.set(path, text);
1264
+ if (symbol.flags & ts.SymbolFlags.Class && declaredHere(walk, symbol)) {
1265
+ recordClass(walk, symbol, path);
1266
+ return;
1267
+ }
1268
+ if (depth >= MAX_DEPTH || !declaredHere(walk, symbol)) return;
1269
+ const next = [...trail, symbol];
1270
+ if (symbol.flags & ts.SymbolFlags.Module) for (const member of walk.checker.getExportsOfModule(symbol)) visit(walk, member, `${path}.${member.name}`, next);
1271
+ else if (type && text === void 0 && isObjectLiteralType(walk, type)) for (const member of walk.checker.getPropertiesOfType(type)) visit(walk, member, `${path}.${member.name}`, next);
1272
+ }
1273
+ function unresolvedImports(walk, program) {
1274
+ const missing = [];
1275
+ for (const file of program.getSourceFiles()) {
1276
+ if (!inPackage(walk, file.fileName)) continue;
1277
+ for (const statement of file.statements) {
1278
+ const specifier = (ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) && statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier : void 0;
1279
+ if (specifier && !walk.checker.getSymbolAtLocation(specifier)) missing.push(`${relative(walk.folder, file.fileName)} -> ${specifier.text}`);
1280
+ }
1281
+ }
1282
+ return missing;
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
+ }
1293
+ function readManifest(folder) {
1294
+ const manifest = parseJson(readFileSync(join(folder, "package.json"), "utf8"));
1295
+ if (!isObject(manifest)) throw new Error(`${folder}: package.json is not an object`);
1296
+ return manifest;
1297
+ }
1298
+ /**
1299
+ * The function surface an extracted npm package declares, read from its `.d.ts` files.
1300
+ * Throws when an export's declaration file is missing or an import in the package's
1301
+ * own declarations cannot be resolved, because the surface would silently be partial.
1302
+ */
1303
+ function declaredSurface(packageFolder) {
1304
+ const folder = realpathSync(resolve(packageFolder));
1305
+ const entries = declarationEntries(readManifest(folder));
1306
+ const files = /* @__PURE__ */ new Map();
1307
+ for (const [subpath, declaration] of entries) {
1308
+ const file = resolve(folder, declaration);
1309
+ if (!existsSync(file)) throw new Error(`${subpath}: ${declaration} is missing`);
1310
+ files.set(subpath, file);
1311
+ }
1312
+ const nodeTypes = nodeTypeRoot(folder);
1313
+ const program = ts.createProgram([...files.values()], {
1314
+ noEmit: true,
1315
+ skipLibCheck: true,
1316
+ strict: true,
1317
+ target: ts.ScriptTarget.ESNext,
1318
+ module: ts.ModuleKind.ESNext,
1319
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
1320
+ ...nodeTypes === void 0 ? { types: [] } : {
1321
+ typeRoots: [nodeTypes],
1322
+ types: ["node"]
1323
+ }
1324
+ });
1325
+ const walk = {
1326
+ checker: program.getTypeChecker(),
1327
+ folder,
1328
+ surface: /* @__PURE__ */ new Map()
1329
+ };
1330
+ const missing = unresolvedImports(walk, program);
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" : ""}`);
1332
+ for (const [subpath, file] of files) {
1333
+ const source = program.getSourceFile(file);
1334
+ const module = source && walk.checker.getSymbolAtLocation(source);
1335
+ if (!module) continue;
1336
+ for (const member of walk.checker.getExportsOfModule(module)) visit(walk, member, `${subpath}:${member.name}`, []);
1337
+ }
1338
+ return walk.surface;
1339
+ }
1340
+ /** The paths added, removed and changed from `published` to `head`, each sorted. */
1341
+ function diffSurface(published, head) {
1342
+ const added = [...head.keys()].filter((path) => !published.has(path));
1343
+ const removed = [...published.keys()].filter((path) => !head.has(path));
1344
+ const changed = [...head].flatMap(([path, after]) => {
1345
+ const before = published.get(path);
1346
+ return before !== void 0 && before !== after ? [{
1347
+ path,
1348
+ before,
1349
+ after
1350
+ }] : [];
1351
+ });
1352
+ return {
1353
+ added: added.sort(),
1354
+ removed: removed.sort(),
1355
+ changed: changed.sort((a, b) => a.path.localeCompare(b.path))
1356
+ };
1357
+ }
1358
+ function parseVersion(text) {
1359
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(text.trim());
1360
+ if (!match) throw new Error(`not a semver version: ${text}`);
1361
+ return {
1362
+ core: [
1363
+ Number(match[1]),
1364
+ Number(match[2]),
1365
+ Number(match[3])
1366
+ ],
1367
+ pre: match[4] ? match[4].split(".") : []
1368
+ };
1369
+ }
1370
+ function comparePre(a, b) {
1371
+ if (a.length === 0 || b.length === 0) return b.length - a.length;
1372
+ const numeric = /^\d+$/;
1373
+ for (let index = 0; index < Math.min(a.length, b.length); index += 1) {
1374
+ const [left, right] = [a[index] ?? "", b[index] ?? ""];
1375
+ const order = numeric.test(left) && numeric.test(right) ? Number(left) - Number(right) : numeric.test(left) === numeric.test(right) ? left.localeCompare(right) : numeric.test(left) ? -1 : 1;
1376
+ if (order !== 0) return order;
1377
+ }
1378
+ return a.length - b.length;
1379
+ }
1380
+ function compareVersions(a, b) {
1381
+ return a.core[0] - b.core[0] || a.core[1] - b.core[1] || a.core[2] - b.core[2] || comparePre(a.pre, b.pre);
1382
+ }
1383
+ function increment(version, bump) {
1384
+ const [major, minor, patch] = version.core;
1385
+ if (bump === "major") return {
1386
+ core: [
1387
+ major + 1,
1388
+ 0,
1389
+ 0
1390
+ ],
1391
+ pre: []
1392
+ };
1393
+ if (bump === "minor") return {
1394
+ core: [
1395
+ major,
1396
+ minor + 1,
1397
+ 0
1398
+ ],
1399
+ pre: []
1400
+ };
1401
+ return {
1402
+ core: version.pre.length > 0 ? [
1403
+ major,
1404
+ minor,
1405
+ patch
1406
+ ] : [
1407
+ major,
1408
+ minor,
1409
+ patch + 1
1410
+ ],
1411
+ pre: []
1412
+ };
1413
+ }
1414
+ function format(version) {
1415
+ const core = version.core.join(".");
1416
+ return version.pre.length > 0 ? `${core}-${version.pre.join(".")}` : core;
1417
+ }
1418
+ function titleBump(title) {
1419
+ const match = /^(\w+)(?:\([^)]*\))?(!)?:/.exec(title.trim());
1420
+ if (match?.[2] === "!" || title.includes("BREAKING CHANGE")) return "major";
1421
+ return match?.[1] === "feat" ? "minor" : "patch";
1422
+ }
1423
+ /**
1424
+ * The bump changelogen 0.5.7 applies to `currentVersion` for these commit titles:
1425
+ * `!` or a `BREAKING CHANGE` footer is major, `feat` minor, anything else patch,
1426
+ * and on a `0.x` version major becomes minor and minor becomes patch.
1427
+ */
1428
+ function releaseType(currentVersion, titles) {
1429
+ const order = [
1430
+ "patch",
1431
+ "minor",
1432
+ "major"
1433
+ ];
1434
+ const highest = titles.map(titleBump).reduce((top, bump) => order.indexOf(bump) > order.indexOf(top) ? bump : top, "patch");
1435
+ if (!currentVersion.startsWith("0.")) return highest;
1436
+ return highest === "major" ? "minor" : "patch";
1437
+ }
1438
+ function listPaths(diff) {
1439
+ return [
1440
+ diff.added.length > 0 ? `added ${diff.added.join(", ")}` : "",
1441
+ diff.changed.length > 0 ? `changed ${diff.changed.map((entry) => entry.path).join(", ")}` : "",
1442
+ diff.removed.length > 0 ? `removed ${diff.removed.join(", ")}` : ""
1443
+ ].filter((part) => part !== "").join("; ");
1444
+ }
1445
+ /**
1446
+ * Judges the interface minor-bump rule: an added, changed or removed function needs a
1447
+ * release of at least the next minor of the published version.
1448
+ */
1449
+ function minorRule(input) {
1450
+ const { published, headVersion, titles, diff } = input;
1451
+ if (published === null) return {
1452
+ required: "none",
1453
+ releases: headVersion,
1454
+ ok: true,
1455
+ reason: "never published: the first release has no surface to compare against"
1456
+ };
1457
+ const base = parseVersion(published);
1458
+ const releases = compareVersions(parseVersion(headVersion), base) > 0 ? headVersion : format(increment(base, releaseType(published, titles)));
1459
+ const required = diff.added.length + diff.changed.length + diff.removed.length > 0 ? "minor" : "none";
1460
+ if (required === "none") return {
1461
+ required,
1462
+ releases,
1463
+ ok: true,
1464
+ reason: `no function added, changed or removed against ${published}: no minor required`
1465
+ };
1466
+ const floor = format(increment(base, "minor"));
1467
+ const ok = compareVersions(parseVersion(releases), parseVersion(floor)) >= 0;
1468
+ const facts = `${listPaths(diff)}: needs at least ${floor} against ${published}, this change releases as ${releases}`;
1469
+ const title = base.core[0] === 0 ? "a `feat!:` commit title (changelogen turns a breaking change into a minor on 0.x)" : "a `feat:` commit title";
1470
+ return {
1471
+ required,
1472
+ releases,
1473
+ ok,
1474
+ reason: ok ? facts : `${facts}. Fix: use ${title}, or run the release workflow with release-version ${floor}`
1475
+ };
1476
+ }
1477
+ //#endregion
1478
+ //#region src/verify/interface.ts
1479
+ const CALL_ARGS = ["verify-argument", 7];
1480
+ function runtimeMembers(value) {
1481
+ if (!Array.isArray(value)) return [];
1482
+ return value.filter(isObject).map((member) => ({
1483
+ path: String(member.path),
1484
+ kind: String(member.kind)
1485
+ }));
1486
+ }
1487
+ function splitPath(path) {
1488
+ const colon = path.indexOf(":");
1489
+ return {
1490
+ entry: path.slice(0, colon),
1491
+ keys: path.slice(colon + 1).split(".")
1492
+ };
1493
+ }
1494
+ function writeJson(folder, file, value) {
1495
+ writeFileSync(join(folder, file), `${JSON.stringify(value, null, 2)}\n`);
1496
+ }
1497
+ /** Links the repository's node_modules under an extracted package, so its declarations resolve their imports. */
1498
+ function linkDependencies(packageFolder, repo) {
1499
+ symlinkSync(join(repo, "node_modules"), join(packageFolder, "node_modules"), "dir");
1500
+ }
1501
+ function readSurface(context, folder, label) {
1502
+ const step = context.step(`${label} declared surface`);
1503
+ try {
1504
+ const surface = declaredSurface(folder);
1505
+ writeJson(step, "surface.json", Object.fromEntries(surface));
1506
+ context.expect(step, [{
1507
+ name: `${label} declarations read`,
1508
+ pass: true,
1509
+ detail: `${surface.size} functions`
1510
+ }]);
1511
+ return surface;
1512
+ } catch (error) {
1513
+ const detail = error instanceof Error ? error.message : String(error);
1514
+ context.expect(step, [{
1515
+ name: `${label} declarations read`,
1516
+ pass: false,
1517
+ detail
1518
+ }], { critical: true });
1519
+ return;
1520
+ }
1521
+ }
1522
+ function logged(context, project, path, args) {
1523
+ const calls = context.stubCalls(project);
1524
+ const seen = calls.some((call) => call.path === path && JSON.stringify(call.args) === JSON.stringify(args));
1525
+ return {
1526
+ name: `the stub provider received ${path}(${JSON.stringify(args).slice(1, -1)})`,
1527
+ pass: seen,
1528
+ detail: JSON.stringify(calls.filter((call) => call.path.startsWith(path)))
1529
+ };
1530
+ }
1531
+ async function callProxy(context, app, path) {
1532
+ const { entry, keys } = splitPath(path);
1533
+ const result = await context.call(`call ${path}`, app, {
1534
+ entry,
1535
+ path: keys,
1536
+ args: CALL_ARGS
1537
+ });
1538
+ context.expect(result.folder, [
1539
+ {
1540
+ name: `${path} resolved through core`,
1541
+ pass: result.ok,
1542
+ detail: JSON.stringify(result.value ?? result.error)
1543
+ },
1544
+ equal(`${path} returned the stub provider's answer`, result.value, {
1545
+ stub: path,
1546
+ args: CALL_ARGS
1547
+ }),
1548
+ logged(context, app.project, path, CALL_ARGS)
1549
+ ]);
1550
+ }
1551
+ async function callRegistering(context, app, path) {
1552
+ const { entry, keys } = splitPath(path);
1553
+ const result = await context.driver(`register ${path}`, app, "/registering", {
1554
+ entry,
1555
+ path: keys
1556
+ });
1557
+ context.expect(result.folder, [
1558
+ {
1559
+ name: `${path} register and unregister resolved through core`,
1560
+ pass: result.ok,
1561
+ detail: JSON.stringify(result.value ?? result.error)
1562
+ },
1563
+ logged(context, app.project, `${path}.register`, ["verify-registration"]),
1564
+ logged(context, app.project, `${path}.unregister`, ["verify-registration"])
1565
+ ]);
1566
+ }
1567
+ async function callEvent(context, app, path) {
1568
+ const { entry, keys } = splitPath(path);
1569
+ const result = await context.driver(`emit ${path}`, app, "/event", {
1570
+ entry,
1571
+ path: keys,
1572
+ args: CALL_ARGS
1573
+ });
1574
+ context.expect(result.folder, [equal(`a handler registered on ${path} received the emitted arguments`, result.value, CALL_ARGS)]);
1575
+ }
1576
+ async function callHook(context, app, path, expected) {
1577
+ const result = await context.driver(`call ${path}`, app, "/hook", { path });
1578
+ context.expect(result.folder, [{
1579
+ name: `${path} resolved through core`,
1580
+ pass: result.ok,
1581
+ detail: JSON.stringify(result.value ?? result.error)
1582
+ }, equal(`${path} returned the value verify.config.ts expects`, result.value, expected)]);
1583
+ }
1584
+ function unreachable(context, path, detail) {
1585
+ context.expect(context.step(`no call for ${path}`), [{
1586
+ name: `${path} is called through core`,
1587
+ pass: false,
1588
+ detail
1589
+ }]);
1590
+ }
1591
+ async function callMember(context, app, path, members) {
1592
+ const hooks = context.workspace.config.interface ?? {};
1593
+ const providerSide = hooks.providerSide?.[path];
1594
+ const hook = hooks.calls?.[path];
1595
+ const kind = members.find((member) => member.path === path)?.kind;
1596
+ if (providerSide !== void 0) {
1597
+ const step = context.step(`provider side ${path}`);
1598
+ context.expect(step, [{
1599
+ name: `${path} is called by providers only`,
1600
+ pass: providerSide.trim() !== "",
1601
+ detail: providerSide
1602
+ }]);
1603
+ } else if (hook !== void 0) await callHook(context, app, path, hook.expect);
1604
+ else if (kind === void 0) unreachable(context, path, "declared in the .d.ts files but the loaded package does not export it");
1605
+ else if (kind === "async") await callProxy(context, app, path);
1606
+ else if (kind === "registering") await callRegistering(context, app, path);
1607
+ else if (kind === "event") await callEvent(context, app, path);
1608
+ else unreachable(context, path, `a plain ${kind}: add interface.calls["${path}"] to verify.config.ts, or interface.providerSide["${path}"] with why consumers never call it`);
1609
+ }
1610
+ /** Loads the packed interface with a stub provider and a consumer, and calls every declared function through core. */
1611
+ const everyFunction = {
1612
+ title: "every declared function answers through core from a stub provider",
1613
+ entryPoint: "a consumer module calling the packed interface in `ajs project dev`",
1614
+ async run(context) {
1615
+ const declared = readSurface(context, context.state.pack, "head");
1616
+ const project = context.fixture();
1617
+ const app = await context.dev("ajs project dev", project);
1618
+ const surface = await context.driver("runtime surface", app, "/surface", {});
1619
+ const members = runtimeMembers(surface.value);
1620
+ context.expect(surface.folder, [{
1621
+ name: "the consumer walked the loaded interface",
1622
+ pass: surface.ok && members.length > 0,
1623
+ detail: `${members.length} members`
1624
+ }]);
1625
+ for (const path of declared?.keys() ?? []) await callMember(context, app, path, members);
1626
+ const stopped = await context.stop("SIGINT", app);
1627
+ context.expect(stopped.folder, [interrupted(stopped)]);
1628
+ }
1629
+ };
1630
+ function publishedVersion(output) {
1631
+ const text = output.trim();
1632
+ return text === "" ? null : text.replace(/^"|"$/g, "");
1633
+ }
1634
+ async function fetchPublished(context, name, version) {
1635
+ const folder = join(CACHE_DIR, "published", name.replace("/", "+"), version);
1636
+ mkdirSync(folder, { recursive: true });
1637
+ const packed = await context.command(`npm pack ${name}@${version}`, "npm", [
1638
+ "pack",
1639
+ `${name}@${version}`,
1640
+ "--pack-destination",
1641
+ folder
1642
+ ], { env: {
1643
+ npm_config_offline: "false",
1644
+ npm_config_prefer_offline: "false"
1645
+ } });
1646
+ const tarball = readdirSync(folder).find((file) => file.endsWith(".tgz"));
1647
+ if (packed.exitCode !== 0 || tarball === void 0) {
1648
+ context.expect(packed.folder, [exitIs(packed, 0)], { critical: true });
1649
+ return;
1650
+ }
1651
+ const extracted = join(context.work, "published");
1652
+ mkdirSync(extracted, { recursive: true });
1653
+ const untar = await context.command("extract published", "tar", [
1654
+ "-xzf",
1655
+ join(folder, tarball),
1656
+ "-C",
1657
+ extracted
1658
+ ]);
1659
+ context.expect(untar.folder, [exitIs(untar, 0)], { critical: true });
1660
+ const root = join(extracted, "package");
1661
+ linkDependencies(root, context.repo);
1662
+ return root;
1663
+ }
1664
+ function changeTitles(context) {
1665
+ if (context.state.title !== "") return [context.state.title];
1666
+ const base = git(context.repo, [
1667
+ "merge-base",
1668
+ context.state.baseRef,
1669
+ "HEAD"
1670
+ ]);
1671
+ return git(context.repo, [
1672
+ "log",
1673
+ "--format=%s",
1674
+ `${base}..HEAD`
1675
+ ]).split("\n").filter(Boolean);
1676
+ }
1677
+ /** The journeys the interface kind ships, by id. */
1678
+ const INTERFACE_JOURNEYS = {
1679
+ "every-function": everyFunction,
1680
+ "minor-bump": {
1681
+ title: "an added, changed or removed function releases as a new minor",
1682
+ entryPoint: "the published package against the packed head, as a module author upgrading sees it",
1683
+ async run(context) {
1684
+ const name = String(context.workspace.manifest.name);
1685
+ const headVersion = String(context.workspace.manifest.version);
1686
+ const view = await context.command(`npm view ${name}`, "npm", [
1687
+ "view",
1688
+ name,
1689
+ "version",
1690
+ "--json"
1691
+ ], { env: {
1692
+ npm_config_offline: "false",
1693
+ npm_config_prefer_offline: "false"
1694
+ } });
1695
+ const missing = view.exitCode !== 0 && /E404/.test(view.stderr);
1696
+ if (view.exitCode !== 0 && !missing) context.notVerified(`npm view ${name} failed: ${view.stderr.trim().slice(-200)}`);
1697
+ const published = missing ? null : publishedVersion(view.stdout);
1698
+ const head = readSurface(context, context.state.pack, "head");
1699
+ const root = published === null ? void 0 : await fetchPublished(context, name, published);
1700
+ const diff = diffSurface((root === void 0 ? void 0 : readSurface(context, root, `published ${published}`)) ?? /* @__PURE__ */ new Map(), head ?? /* @__PURE__ */ new Map());
1701
+ const titles = changeTitles(context);
1702
+ const verdict = minorRule({
1703
+ published,
1704
+ headVersion,
1705
+ titles,
1706
+ diff
1707
+ });
1708
+ const step = context.step("minor rule");
1709
+ writeJson(step, "minor-rule.json", {
1710
+ published,
1711
+ headVersion,
1712
+ titles,
1713
+ ...diff,
1714
+ ...verdict
1715
+ });
1716
+ context.expect(step, [{
1717
+ name: verdict.required === "minor" ? `releases at least the next minor of ${published}` : "no function changed against the published version",
1718
+ pass: verdict.ok,
1719
+ detail: verdict.reason
1720
+ }]);
1721
+ }
1722
+ }
1723
+ };
1724
+ //#endregion
1725
+ //#region src/verify/record.ts
1726
+ const DEFAULT_TIMEOUT_MS = 6e5;
1727
+ /** Quotes an argument the way a shell user would type it. */
1728
+ function shellQuote(value) {
1729
+ return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
1730
+ }
1731
+ function describe(spec) {
1732
+ return [spec.program, ...spec.args].map(shellQuote).join(" ");
1733
+ }
1734
+ function writeCommand(folder, spec) {
1735
+ mkdirSync(folder, { recursive: true });
1736
+ writeFileSync(join(folder, "command.txt"), `cd ${shellQuote(spec.cwd)}\n${describe(spec)}\n`);
1737
+ }
1738
+ /** Runs a command to completion and writes command.txt, stdout.txt, stderr.txt and exit-code.txt into `folder`. */
1739
+ function runRecorded(folder, spec) {
1740
+ writeCommand(folder, spec);
1741
+ return new Promise((resolve) => {
1742
+ const child = spawn(spec.program, spec.args, {
1743
+ cwd: spec.cwd,
1744
+ env: spec.env,
1745
+ stdio: [
1746
+ "ignore",
1747
+ "pipe",
1748
+ "pipe"
1749
+ ]
1750
+ });
1751
+ const out = [];
1752
+ const err = [];
1753
+ child.stdout.on("data", (chunk) => out.push(chunk));
1754
+ child.stderr.on("data", (chunk) => err.push(chunk));
1755
+ const timer = setTimeout(() => child.kill("SIGKILL"), spec.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1756
+ const finish = (code, signal, failure = "") => {
1757
+ clearTimeout(timer);
1758
+ const result = {
1759
+ folder,
1760
+ command: describe(spec),
1761
+ exitCode: code,
1762
+ signal,
1763
+ stdout: Buffer.concat(out).toString("utf8"),
1764
+ stderr: `${Buffer.concat(err).toString("utf8")}${failure}`
1765
+ };
1766
+ writeFileSync(join(folder, "stdout.txt"), result.stdout);
1767
+ writeFileSync(join(folder, "stderr.txt"), result.stderr);
1768
+ writeFileSync(join(folder, "exit-code.txt"), `${code ?? `signal ${signal}`}\n`);
1769
+ resolve(result);
1770
+ };
1771
+ child.on("error", (error) => finish(null, null, `${error.message}\n`));
1772
+ child.on("close", (code, signal) => finish(code, signal));
1773
+ });
1774
+ }
1775
+ /** Starts a long-running command in its own process group, writing stdout and stderr straight to files. */
1776
+ function startRecorded(folder, spec) {
1777
+ writeCommand(folder, spec);
1778
+ const stdout = openSync(join(folder, "stdout.txt"), "w");
1779
+ const stderr = openSync(join(folder, "stderr.txt"), "w");
1780
+ const child = spawn(spec.program, spec.args, {
1781
+ cwd: spec.cwd,
1782
+ env: spec.env,
1783
+ detached: true,
1784
+ stdio: [
1785
+ "ignore",
1786
+ stdout,
1787
+ stderr
1788
+ ]
1789
+ });
1790
+ closeSync(stdout);
1791
+ closeSync(stderr);
1792
+ const exited = new Promise((resolve) => {
1793
+ child.on("exit", (exitCode, signal) => {
1794
+ writeFileSync(join(folder, "exit-code.txt"), `${exitCode ?? `signal ${signal}`}\n`);
1795
+ resolve({
1796
+ exitCode,
1797
+ signal
1798
+ });
1799
+ });
1800
+ });
1801
+ if (child.pid === void 0) throw new Error(`Could not start ${describe(spec)}`);
1802
+ writeFileSync(join(folder, "pid.txt"), `${child.pid}\n`);
1803
+ return {
1804
+ folder,
1805
+ child,
1806
+ pid: child.pid,
1807
+ exited
1808
+ };
1809
+ }
1810
+ /** Kills the process group of `pid`, or `pid` alone, ignoring a process already gone. */
1811
+ function killGroup(pid) {
1812
+ try {
1813
+ process.kill(-pid, "SIGKILL");
1814
+ } catch {
1815
+ try {
1816
+ process.kill(pid, "SIGKILL");
1817
+ } catch {
1818
+ return;
1819
+ }
1820
+ }
1821
+ }
1822
+ /** Reads what a background command has written so far. */
1823
+ function readOutput(folder) {
1824
+ return {
1825
+ stdout: readFileSync(join(folder, "stdout.txt"), "utf8"),
1826
+ stderr: readFileSync(join(folder, "stderr.txt"), "utf8")
1827
+ };
1828
+ }
1829
+ /** Asks the kernel for a free TCP port on the loopback interface. */
1830
+ function freePort() {
1831
+ return new Promise((resolve, reject) => {
1832
+ const server = createServer();
1833
+ server.once("error", reject);
1834
+ server.listen(0, "127.0.0.1", () => {
1835
+ const address = server.address();
1836
+ const port = address !== null && address instanceof Object ? address.port : 0;
1837
+ server.close(() => resolve(port));
1838
+ });
1839
+ });
1840
+ }
1841
+ function reason(error) {
1842
+ return error.cause instanceof Error ? error.cause.message : error.message;
1843
+ }
1844
+ /** Sends one request and writes http.json with the status and body. */
1845
+ async function httpRecorded(folder, url, init = {}) {
1846
+ mkdirSync(folder, { recursive: true });
1847
+ let result;
1848
+ try {
1849
+ const response = await fetch(url, {
1850
+ method: init.method ?? "GET",
1851
+ body: init.body,
1852
+ headers: init.body ? { "content-type": "application/json" } : void 0,
1853
+ signal: AbortSignal.timeout(init.timeoutMs ?? 5e3)
1854
+ });
1855
+ const body = await response.text();
1856
+ let json;
1857
+ try {
1858
+ json = parseJson(body);
1859
+ } catch {
1860
+ json = void 0;
1861
+ }
1862
+ result = {
1863
+ folder,
1864
+ url,
1865
+ status: response.status,
1866
+ body,
1867
+ json,
1868
+ error: null
1869
+ };
1870
+ } catch (error) {
1871
+ result = {
1872
+ folder,
1873
+ url,
1874
+ status: null,
1875
+ body: "",
1876
+ json: void 0,
1877
+ error: error instanceof Error ? reason(error) : String(error)
1878
+ };
1879
+ }
1880
+ writeFileSync(join(folder, "http.json"), `${JSON.stringify({
1881
+ request: {
1882
+ url,
1883
+ ...init
1884
+ },
1885
+ response: result
1886
+ }, null, 2)}\n`);
1887
+ return result;
1888
+ }
1889
+ const TREE_SKIP = /* @__PURE__ */ new Set([
1890
+ "node_modules",
1891
+ ".git",
1892
+ ".pnpm-store"
1893
+ ]);
1894
+ function listTree(root, folder = root) {
1895
+ return readdirSync(folder, { withFileTypes: true }).filter((entry) => !TREE_SKIP.has(entry.name)).sort((left, right) => left.name.localeCompare(right.name)).flatMap((entry) => {
1896
+ const path = join(folder, entry.name);
1897
+ const name = relative(root, path);
1898
+ if (entry.isDirectory()) return [`${name}/`, ...listTree(root, path)];
1899
+ return [`${name} ${statSync(path).size}`];
1900
+ });
1901
+ }
1902
+ /** Writes `tree.txt`: every path under `root` with its size, node_modules and .git left out. */
1903
+ function recordTree(folder, root) {
1904
+ mkdirSync(folder, { recursive: true });
1905
+ let lines;
1906
+ try {
1907
+ lines = listTree(root);
1908
+ } catch {
1909
+ lines = [];
1910
+ }
1911
+ writeFileSync(join(folder, "tree.txt"), `${root}\n${lines.join("\n")}\n`);
1912
+ return lines;
1913
+ }
1914
+ //#endregion
1915
+ //#region src/verify/sources.ts
1916
+ const IDENTITY = [
1917
+ "-c",
1918
+ "user.name=antelopejs-verify",
1919
+ "-c",
1920
+ "user.email=verify@antelopejs.invalid",
1921
+ "-c",
1922
+ "init.defaultBranch=main",
1923
+ "-c",
1924
+ "commit.gpgsign=false"
1925
+ ];
1926
+ function commitFolder(folder) {
1927
+ for (const args of [
1928
+ ["init", "-q"],
1929
+ [
1930
+ "add",
1931
+ "-A",
1932
+ "--force"
1933
+ ],
1934
+ [
1935
+ "commit",
1936
+ "-q",
1937
+ "-m",
1938
+ "verify source"
1939
+ ]
1940
+ ]) execFileSync("git", [...IDENTITY, ...args], {
1941
+ cwd: folder,
1942
+ stdio: "ignore"
1943
+ });
1944
+ }
1945
+ function bare(source, target) {
1946
+ execFileSync("git", [
1947
+ "clone",
1948
+ "-q",
1949
+ "--bare",
1950
+ source,
1951
+ target
1952
+ ], { stdio: "ignore" });
1953
+ return pathToFileURL(target).href;
1954
+ }
1955
+ function copyWorkingTree(root, target) {
1956
+ const files = git(root, [
1957
+ "ls-files",
1958
+ "-z",
1959
+ "--cached",
1960
+ "--others",
1961
+ "--exclude-standard"
1962
+ ]).split("\0").filter(Boolean);
1963
+ for (const file of new Set(files)) {
1964
+ const source = join(root, file);
1965
+ const stat = lstatSync(source, { throwIfNoEntry: false });
1966
+ if (stat === void 0 || existsSync(join(target, file))) continue;
1967
+ mkdirSync(dirname(join(target, file)), { recursive: true });
1968
+ if (stat.isSymbolicLink()) symlinkSync(readlinkSync(source), join(target, file));
1969
+ else copyFileSync(source, join(target, file));
1970
+ }
1971
+ }
1972
+ /** The template name the offline manifest lists, the repository's own unless verify.config.ts names one. */
1973
+ function templateName(workspace) {
1974
+ return workspace.config.template?.name ?? `Verify ${workspace.name}`;
1975
+ }
1976
+ /**
1977
+ * Builds the offline template source of a run: the template's working tree,
1978
+ * uncommitted changes included, as a local git repository, and an interfaces
1979
+ * repository whose manifest.json lists it through a `file://` URL. Returns
1980
+ * the manifest repository URL `ajs config set git` points at.
1981
+ */
1982
+ function seedSources(workspace, state) {
1983
+ const sources = join(state.dir, "sources");
1984
+ const template = join(sources, "template");
1985
+ mkdirSync(template, { recursive: true });
1986
+ copyWorkingTree(workspace.root, template);
1987
+ commitFolder(template);
1988
+ const templateUrl = bare(template, join(sources, "template.git"));
1989
+ const manifest = join(sources, "interfaces");
1990
+ mkdirSync(manifest, { recursive: true });
1991
+ const listing = workspace.config.template?.project ? "projectTemplates" : "templates";
1992
+ const entry = {
1993
+ name: templateName(workspace),
1994
+ repository: templateUrl,
1995
+ branch: "main",
1996
+ packageManager: "pnpm"
1997
+ };
1998
+ const content = {
1999
+ interfaces: {},
2000
+ starredInterfaces: [],
2001
+ templates: [],
2002
+ projectTemplates: [],
2003
+ [listing]: [entry]
2004
+ };
2005
+ writeFileSync(join(manifest, "manifest.json"), `${JSON.stringify(content, null, 2)}\n`);
2006
+ commitFolder(manifest);
2007
+ return bare(manifest, join(sources, "interfaces.git"));
2008
+ }
2009
+ //#endregion
2010
+ //#region src/verify/lifecycle.ts
2011
+ /** The prefix of every container a run starts; `VERIFY_CONTAINER_PREFIX` overrides it. */
2012
+ function containerPrefix() {
2013
+ return process.env.VERIFY_CONTAINER_PREFIX ?? "verify";
2014
+ }
2015
+ function setupCommands(workspace) {
2016
+ if (workspace.config.setup) return workspace.config.setup;
2017
+ const scripts = workspace.manifest.scripts;
2018
+ return scripts !== void 0 && isObject(scripts) && scripts.build !== void 0 && workspace.kind !== "template" ? [[
2019
+ "pnpm",
2020
+ "run",
2021
+ "build"
2022
+ ]] : [];
2023
+ }
2024
+ async function runSetup(workspace, state) {
2025
+ const commands = setupCommands(workspace);
2026
+ for (const [index, [program, ...args]] of commands.entries()) {
2027
+ const folder = join(state.evidence, "setup", `${String(index + 1).padStart(2, "0")}-${program}`);
2028
+ const result = await runRecorded(folder, {
2029
+ program,
2030
+ args,
2031
+ cwd: workspace.root,
2032
+ env: {
2033
+ ...process.env,
2034
+ ...workspace.config.env
2035
+ }
2036
+ });
2037
+ if (result.exitCode !== 0) throw new Error(`setup \`${result.command}\` exited ${result.exitCode}; see ${folder}`);
2038
+ }
2039
+ }
2040
+ async function packInterface(workspace, state) {
2041
+ const folder = join(state.dir, "pack");
2042
+ mkdirSync(folder, { recursive: true });
2043
+ const env = isolatedEnv(workspace, join(state.dir, "home"));
2044
+ const packed = await runRecorded(join(state.evidence, "setup", "pack"), {
2045
+ program: "pnpm",
2046
+ args: [
2047
+ "pack",
2048
+ "--pack-destination",
2049
+ folder
2050
+ ],
2051
+ cwd: workspace.root,
2052
+ env
2053
+ });
2054
+ const tarball = readdirSync(folder).find((file) => file.endsWith(".tgz"));
2055
+ if (packed.exitCode !== 0 || tarball === void 0) throw new Error(`pnpm pack failed: ${packed.stderr.slice(-300)}`);
2056
+ const extract = await runRecorded(join(state.evidence, "setup", "extract"), {
2057
+ program: "tar",
2058
+ args: [
2059
+ "-xzf",
2060
+ join(folder, tarball),
2061
+ "-C",
2062
+ folder
2063
+ ],
2064
+ cwd: folder,
2065
+ env
2066
+ });
2067
+ if (extract.exitCode !== 0) throw new Error(`tar failed: ${extract.stderr.slice(-300)}`);
2068
+ const root = join(folder, "package");
2069
+ linkDependencies(root, workspace.root);
2070
+ return root;
2071
+ }
2072
+ /**
2073
+ * Creates an isolated run: runs the setup (the build by default), then
2074
+ * prepares what the kind drives. An interface is packed as npm would publish
2075
+ * it, a module's backing services start in Docker on free ports, and a
2076
+ * template is served from an offline manifest repository.
2077
+ */
2078
+ async function createRun(workspace, baseRef, title) {
2079
+ const state = allocateRun(workspace, baseRef, title);
2080
+ saveRun(state);
2081
+ await runSetup(workspace, state);
2082
+ if (workspace.kind === "interface") state.pack = await packInterface(workspace, state);
2083
+ if (workspace.kind === "module") startServices(workspace, state, containerPrefix());
2084
+ if (workspace.kind === "template") {
2085
+ state.manifestUrl = seedSources(workspace, state);
2086
+ state.templateName = templateName(workspace);
2087
+ }
2088
+ saveRun(state);
2089
+ return state;
2090
+ }
2091
+ function alive(pid) {
2092
+ try {
2093
+ process.kill(pid, 0);
2094
+ return true;
2095
+ } catch {
2096
+ return false;
2097
+ }
2098
+ }
2099
+ function newestUnder(folder) {
2100
+ if (!existsSync(folder)) return 0;
2101
+ return readdirSync(folder, {
2102
+ recursive: true,
2103
+ withFileTypes: true
2104
+ }).filter((entry) => entry.isFile()).reduce((newest, entry) => Math.max(newest, statSync(join(entry.parentPath, entry.name)).mtimeMs), 0);
2105
+ }
2106
+ function buildLine(workspace) {
2107
+ const built = newestUnder(join(workspace.root, "dist"));
2108
+ const source = newestUnder(join(workspace.root, "src"));
2109
+ if (workspace.kind === "template" || source === 0) return {
2110
+ check: "build",
2111
+ ok: true,
2112
+ detail: "nothing to build"
2113
+ };
2114
+ return {
2115
+ check: "build is newer than src",
2116
+ ok: built >= source,
2117
+ detail: built >= source ? "dist is current" : "src changed after the build; create a new run"
2118
+ };
2119
+ }
2120
+ function kindLines(workspace, state) {
2121
+ if (workspace.kind === "interface") return [{
2122
+ check: "packed interface",
2123
+ ok: existsSync(join(state.pack, "package.json")),
2124
+ detail: state.pack
2125
+ }];
2126
+ if (workspace.kind === "template") return [{
2127
+ check: "offline manifest",
2128
+ ok: existsSync(join(state.dir, "sources", "interfaces.git")),
2129
+ detail: `${state.templateName} at ${state.manifestUrl}`
2130
+ }];
2131
+ return [{
2132
+ check: "provider sandbox keys",
2133
+ ok: state.missingKeys.length === 0,
2134
+ detail: state.missingKeys.length === 0 ? "present or not needed" : `missing ${state.missingKeys.join(", ")}: every journey is not verified`
2135
+ }, ...state.containers.map((container) => ({
2136
+ check: `service ${container.service}`,
2137
+ ok: containerRunning(container.name),
2138
+ detail: `${container.name} on ${container.host}:${container.port}`
2139
+ }))];
2140
+ }
2141
+ /** Read-only checks that answer whether a run is worth driving. */
2142
+ function doctor(workspace, state) {
2143
+ const head = git(workspace.root, ["rev-parse", "HEAD"]);
2144
+ let core = "";
2145
+ try {
2146
+ core = relative(workspace.root, installedPackage(workspace.root, "@antelopejs/core"));
2147
+ } catch (error) {
2148
+ core = error instanceof Error ? error.message : String(error);
2149
+ }
2150
+ return [
2151
+ {
2152
+ check: "HEAD unchanged since new",
2153
+ ok: head === state.headSha,
2154
+ detail: head === state.headSha ? head.slice(0, 7) : `new at ${state.headSha.slice(0, 7)}, HEAD is ${head.slice(0, 7)}`
2155
+ },
2156
+ {
2157
+ check: "ajs from the repository's @antelopejs/core",
2158
+ ok: !core.includes(" "),
2159
+ detail: core
2160
+ },
2161
+ buildLine(workspace),
2162
+ ...kindLines(workspace, state),
2163
+ ...state.processes.map((record) => ({
2164
+ check: `no leftover process ${record.name}`,
2165
+ ok: !alive(record.pid),
2166
+ detail: `pid ${record.pid}`
2167
+ }))
2168
+ ];
2169
+ }
2170
+ /** Stops what the run started, by recorded PID and container name, and removes everything but the evidence and run.json. Returns what it could not remove. */
2171
+ function clean(state) {
2172
+ const lines = [];
2173
+ for (const record of state.processes) killGroup(record.pid);
2174
+ for (const container of state.containers) if (!removeContainer(container.name)) lines.push(`could not remove container ${container.name}`);
2175
+ state.processes = [];
2176
+ state.containers = [];
2177
+ saveRun(state);
2178
+ for (const entry of readdirSync(state.dir)) {
2179
+ if (entry === "evidence" || entry === "run.json") continue;
2180
+ rmSync(join(state.dir, entry), {
2181
+ recursive: true,
2182
+ force: true
2183
+ });
2184
+ }
2185
+ return lines;
2186
+ }
2187
+ //#endregion
2188
+ //#region src/verify/map.ts
2189
+ /** The feature that always runs, whatever the diff touches. */
2190
+ const SMOKE_FEATURE = "smoke";
2191
+ const DEFAULT_USER_FACING = {
2192
+ interface: ["src/**"],
2193
+ module: ["src/**"],
2194
+ template: ["**"]
2195
+ };
2196
+ const VERIFICATION_LAYER = [
2197
+ ".agents/**",
2198
+ ".claude/**",
2199
+ ".github/**"
2200
+ ];
2201
+ /** Tests are user-facing in a template, whose whole tree is what `ajs` copies. */
2202
+ const NOT_USER_FACING = {
2203
+ interface: [
2204
+ "**/*.test.ts",
2205
+ "**/test/**",
2206
+ "**/tests/**",
2207
+ ...VERIFICATION_LAYER
2208
+ ],
2209
+ module: [
2210
+ "**/*.test.ts",
2211
+ "**/test/**",
2212
+ "**/tests/**",
2213
+ ...VERIFICATION_LAYER
2214
+ ],
2215
+ template: VERIFICATION_LAYER
2216
+ };
2217
+ function frontmatterLists(text) {
2218
+ const lists = /* @__PURE__ */ new Map();
2219
+ const match = /^---\n([\s\S]*?)\n---\n/.exec(text);
2220
+ let current;
2221
+ for (const line of (match?.[1] ?? "").split("\n")) {
2222
+ const key = /^(\w+):\s*$/.exec(line);
2223
+ const item = /^\s+-\s+(.+)$/.exec(line);
2224
+ if (key) {
2225
+ current = [];
2226
+ lists.set(key[1], current);
2227
+ } else if (item && current) current.push(item[1].replace(/^"|"$/g, ""));
2228
+ }
2229
+ return lists;
2230
+ }
2231
+ /** Reads every feature file under features/, README.md excluded. */
2232
+ function readFeatures(workspace) {
2233
+ const folder = join(workspace.skill, "features");
2234
+ if (!existsSync(folder)) return [];
2235
+ return readdirSync(folder).filter((file) => file.endsWith(".md") && file !== "README.md").sort().map((file) => {
2236
+ const body = readFileSync(join(folder, file), "utf8");
2237
+ const lists = frontmatterLists(body);
2238
+ return {
2239
+ name: file.replace(/\.md$/, ""),
2240
+ file: relative(workspace.root, join(folder, file)),
2241
+ covers: lists.get("covers") ?? [],
2242
+ docs: lists.get("docs") ?? [],
2243
+ journeys: lists.get("journeys") ?? [],
2244
+ body
2245
+ };
2246
+ });
2247
+ }
2248
+ function matches(file, globs) {
2249
+ return globs.some((glob) => matchesGlob(file, glob));
2250
+ }
2251
+ /** Whether a user can observe a change to `file`. */
2252
+ function userFacing(workspace, file) {
2253
+ return matches(file, workspace.config.userFacing ?? DEFAULT_USER_FACING[workspace.kind]) && !matches(file, NOT_USER_FACING[workspace.kind]);
2254
+ }
2255
+ function trackedFiles(workspace) {
2256
+ return git(workspace.root, ["ls-files"]).split("\n").filter(Boolean);
2257
+ }
2258
+ /** The features whose globs cover `file`. */
2259
+ function featuresOf(file, features) {
2260
+ return features.filter((feature) => matches(file, feature.covers)).map((feature) => feature.name);
2261
+ }
2262
+ function featureProblems(workspace, feature, known, tracked) {
2263
+ const problems = [];
2264
+ if (feature.journeys.length === 0) problems.push(`${feature.file}: lists no journeys`);
2265
+ for (const journey of feature.journeys) {
2266
+ if (!known.has(journey)) problems.push(`${feature.file}: journey ${journey} is neither built in nor in verify.config.ts journeys`);
2267
+ if (!feature.body.includes(`\`${journey}\``)) problems.push(`${feature.file}: journey \`${journey}\` is not described`);
2268
+ }
2269
+ if (feature.name !== "smoke" && feature.covers.length === 0) problems.push(`${feature.file}: lists no covers globs`);
2270
+ for (const glob of feature.covers) if (!tracked.some((file) => matchesGlob(file, glob))) problems.push(`${feature.file}: glob ${glob} matches no tracked file`);
2271
+ if (feature.docs.length === 0) problems.push(`${feature.file}: lists no docs pages`);
2272
+ for (const doc of feature.docs) if (!existsSync(join(workspace.root, doc))) problems.push(`${feature.file}: docs path ${doc} does not exist`);
2273
+ if (!existsSync(join(workspace.skill, "seeded-breaks", `${feature.name}.patch`))) problems.push(`${feature.file}: seeded-breaks/${feature.name}.patch is missing`);
2274
+ return problems;
2275
+ }
2276
+ /**
2277
+ * Checks the repo-owned layer against the repository: a smoke feature
2278
+ * exists, every user-facing file is covered, every feature names known
2279
+ * journeys, docs pages that exist and a seeded break, every config journey is
2280
+ * used, and every applicable door kind has a seeded door. One line per problem.
2281
+ */
2282
+ function checkMap(workspace, builtins) {
2283
+ const features = readFeatures(workspace);
2284
+ const tracked = trackedFiles(workspace);
2285
+ const configJourneys = Object.keys(workspace.config.journeys ?? {});
2286
+ const known = /* @__PURE__ */ new Set([...builtins, ...configJourneys]);
2287
+ const problems = [];
2288
+ if (!features.some((feature) => feature.name === "smoke")) problems.push(`${skillFolder(workspace.kind)}/features/${SMOKE_FEATURE}.md is missing: every verdict runs the smoke feature`);
2289
+ for (const file of tracked.filter((path) => userFacing(workspace, path))) if (featuresOf(file, features).length === 0) problems.push(`unmapped: ${file} matches no feature glob`);
2290
+ for (const feature of features) problems.push(...featureProblems(workspace, feature, known, tracked));
2291
+ for (const journey of configJourneys) if (!features.some((feature) => feature.journeys.includes(journey))) problems.push(`verify.config.ts journey ${journey} is in no feature file`);
2292
+ for (const [kind, rule] of Object.entries(workspace.config.doors)) if (rule && !existsSync(join(workspace.skill, "seeded-doors", `${kind}.patch`))) problems.push(`seeded-doors/${kind}.patch is missing: the ${kind} door applies to this repository`);
2293
+ problems.push(...containmentProblems(workspace, features));
2294
+ return problems;
2295
+ }
2296
+ /** A Data or Format door is contained only by a journey, so each rule names at least one, as a registered `feature/journey`. */
2297
+ function containmentProblems(workspace, features) {
2298
+ const problems = [];
2299
+ for (const kind of ["data", "format"]) {
2300
+ const rule = workspace.config.doors[kind];
2301
+ if (!rule) continue;
2302
+ if (rule.containments.length === 0) problems.push(`doors.${kind} names no containments journey: a ${kind} door row could never pass`);
2303
+ for (const containment of rule.containments) {
2304
+ const [name, journey] = containment.split("/");
2305
+ if (!features.some((entry) => entry.name === name && entry.journeys.includes(journey))) problems.push(`doors.${kind} containment ${containment} is not a journey a feature registers`);
2306
+ }
2307
+ }
2308
+ return problems;
2309
+ }
2310
+ /** The files a change touches: committed since the merge base, staged, unstaged and untracked. */
2311
+ function changedFiles(workspace, baseSha) {
2312
+ const committed = git(workspace.root, [
2313
+ "diff",
2314
+ "--name-only",
2315
+ baseSha
2316
+ ]).split("\n");
2317
+ const untracked = git(workspace.root, [
2318
+ "ls-files",
2319
+ "--others",
2320
+ "--exclude-standard"
2321
+ ]).split("\n");
2322
+ return [...new Set([...committed, ...untracked].filter(Boolean))].sort();
2323
+ }
2324
+ /**
2325
+ * Maps the change from the merge base of `baseRef` onto features: every
2326
+ * touched feature plus the smoke feature runs, and a user-facing file outside
2327
+ * every glob is an unmapped surface.
2328
+ */
2329
+ function planFor(workspace, baseRef) {
2330
+ const features = readFeatures(workspace);
2331
+ const baseSha = git(workspace.root, [
2332
+ "merge-base",
2333
+ baseRef,
2334
+ "HEAD"
2335
+ ]);
2336
+ const changed = changedFiles(workspace, baseSha);
2337
+ const touched = features.map((feature) => ({
2338
+ feature: feature.name,
2339
+ files: changed.filter((file) => matches(file, feature.covers))
2340
+ })).filter((entry) => entry.files.length > 0);
2341
+ const unmapped = changed.filter((file) => userFacing(workspace, file) && featuresOf(file, features).length === 0);
2342
+ const touchedNames = new Set(touched.map((entry) => entry.feature));
2343
+ const docs = [...new Set(features.filter((feature) => touchedNames.has(feature.name)).flatMap((feature) => feature.docs))];
2344
+ const run = [SMOKE_FEATURE, ...[...touchedNames].filter((name) => name !== SMOKE_FEATURE)];
2345
+ const dirty = git(workspace.root, [
2346
+ "status",
2347
+ "--porcelain",
2348
+ "--untracked-files=no"
2349
+ ]).split("\n").filter(Boolean);
2350
+ return {
2351
+ baseRef,
2352
+ baseSha,
2353
+ headSha: git(workspace.root, ["rev-parse", "HEAD"]),
2354
+ changed,
2355
+ touched,
2356
+ unmapped,
2357
+ docs,
2358
+ run,
2359
+ dirty
2360
+ };
2361
+ }
2362
+ //#endregion
2363
+ //#region src/verify/publish.ts
2364
+ const EVIDENCE_BRANCH = "verify-evidence";
2365
+ const SCRATCH_BRANCH = "verify-evidence-scratch";
2366
+ const STATUS = {
2367
+ PASS: "success",
2368
+ "PASS+NOTES": "success",
2369
+ "NOT VERIFIED": "error",
2370
+ FAIL: "failure"
2371
+ };
2372
+ /**
2373
+ * Commits the run's evidence under pr-<n>/<sha>/ of the orphan evidence
2374
+ * branch and pushes it. Works in a temporary worktree so the checkout under
2375
+ * review is never touched. Returns the pushed evidence commit.
2376
+ */
2377
+ function pushEvidence(root, state, verdict) {
2378
+ const worktree = mkdtempSync(join(tmpdir(), "verify-evidence-"));
2379
+ try {
2380
+ if (git(root, [
2381
+ "ls-remote",
2382
+ "--heads",
2383
+ "origin",
2384
+ EVIDENCE_BRANCH
2385
+ ]) !== "") {
2386
+ git(root, [
2387
+ "fetch",
2388
+ "--quiet",
2389
+ "origin",
2390
+ `${EVIDENCE_BRANCH}:refs/remotes/origin/${EVIDENCE_BRANCH}`
2391
+ ]);
2392
+ git(root, [
2393
+ "worktree",
2394
+ "add",
2395
+ "--quiet",
2396
+ "--detach",
2397
+ worktree,
2398
+ `origin/${EVIDENCE_BRANCH}`
2399
+ ]);
2400
+ } else git(root, [
2401
+ "worktree",
2402
+ "add",
2403
+ "--quiet",
2404
+ "--orphan",
2405
+ "-B",
2406
+ SCRATCH_BRANCH,
2407
+ worktree
2408
+ ]);
2409
+ const target = join(worktree, `pr-${verdict.pr}`, verdict.headSha);
2410
+ rmSync(target, {
2411
+ recursive: true,
2412
+ force: true
2413
+ });
2414
+ mkdirSync(target, { recursive: true });
2415
+ cpSync(state.evidence, target, { recursive: true });
2416
+ git(worktree, [
2417
+ "add",
2418
+ "--all",
2419
+ "."
2420
+ ]);
2421
+ git(worktree, [
2422
+ "-c",
2423
+ "commit.gpgsign=false",
2424
+ "commit",
2425
+ "--quiet",
2426
+ "--allow-empty",
2427
+ "-m",
2428
+ `verify: evidence for #${verdict.pr} at ${verdict.headSha.slice(0, 7)} (${verdict.result})`
2429
+ ]);
2430
+ git(worktree, [
2431
+ "push",
2432
+ "--quiet",
2433
+ "origin",
2434
+ `HEAD:refs/heads/${EVIDENCE_BRANCH}`
2435
+ ]);
2436
+ return git(worktree, ["rev-parse", "HEAD"]);
2437
+ } finally {
2438
+ git(root, [
2439
+ "worktree",
2440
+ "remove",
2441
+ "--force",
2442
+ worktree
2443
+ ]);
2444
+ if (git(root, [
2445
+ "branch",
2446
+ "--list",
2447
+ SCRATCH_BRANCH
2448
+ ]) !== "") git(root, [
2449
+ "branch",
2450
+ "--quiet",
2451
+ "-D",
2452
+ SCRATCH_BRANCH
2453
+ ]);
2454
+ }
2455
+ }
2456
+ /** Posts the verdict as a PR comment and returns the comment URL printed by gh. */
2457
+ function postComment(root, verdict) {
2458
+ return execFileSync("gh", [
2459
+ "pr",
2460
+ "comment",
2461
+ String(verdict.pr),
2462
+ "--repo",
2463
+ verdict.repository,
2464
+ "--body",
2465
+ verdict.markdown
2466
+ ], {
2467
+ cwd: root,
2468
+ encoding: "utf8"
2469
+ }).trim();
2470
+ }
2471
+ /**
2472
+ * Sets the `verify` commit status on the head SHA the verdict judged and
2473
+ * reads it back from GitHub. Returns what GitHub holds, or the error GitHub
2474
+ * answered, so a token without `statuses: write` is reported, never hidden.
2475
+ */
2476
+ function setStatus(root, verdict, targetUrl) {
2477
+ const write = spawnSync("gh", [
2478
+ "api",
2479
+ "--silent",
2480
+ `repos/${verdict.repository}/statuses/${verdict.headSha}`,
2481
+ "-f",
2482
+ `state=${STATUS[verdict.result]}`,
2483
+ "-f",
2484
+ "context=verify",
2485
+ "-f",
2486
+ `description=verify: ${verdict.result}`,
2487
+ "-f",
2488
+ `target_url=${targetUrl}`
2489
+ ], {
2490
+ cwd: root,
2491
+ encoding: "utf8"
2492
+ });
2493
+ if (write.status !== 0) return {
2494
+ ok: false,
2495
+ detail: `setting status verify failed: ${(write.stderr || write.stdout).trim()}`
2496
+ };
2497
+ const state = spawnSync("gh", [
2498
+ "api",
2499
+ `repos/${verdict.repository}/commits/${verdict.headSha}/statuses`,
2500
+ "--jq",
2501
+ "[.[] | select(.context == \"verify\")][0].state"
2502
+ ], {
2503
+ cwd: root,
2504
+ encoding: "utf8"
2505
+ }).stdout.trim();
2506
+ return {
2507
+ ok: state === STATUS[verdict.result],
2508
+ detail: `status verify on ${verdict.headSha}: ${state || "absent"}`
2509
+ };
2510
+ }
2511
+ //#endregion
2512
+ //#region src/verify/builtins.ts
2513
+ /** Loads the module from its local source next to its backing services, then stops it. */
2514
+ const moduleDev = {
2515
+ title: "the module loads from its local source against its backing services and stops on Ctrl+C",
2516
+ entryPoint: "`ajs project dev` on a project that installs the module as `local`",
2517
+ async run(context) {
2518
+ const project = context.fixture();
2519
+ const app = await context.dev("ajs project dev", project);
2520
+ const surface = await context.driver("implemented interfaces", app, "/surface", {});
2521
+ context.expect(surface.folder, [{
2522
+ name: "the consumer loaded every implemented interface",
2523
+ pass: surface.ok,
2524
+ detail: JSON.stringify(surface.value).slice(0, 300)
2525
+ }]);
2526
+ const stopped = await context.stop("SIGINT", app);
2527
+ context.expect(stopped.folder, [interrupted(stopped)]);
2528
+ const after = await context.http("port after stop", `http://127.0.0.1:${app.port}/health`);
2529
+ context.expect(after.folder, [refused(after)]);
2530
+ }
2531
+ };
2532
+ /** Scaffolds a project from the template with `ajs project init` and installs it; returns its folder. */
2533
+ async function scaffoldProject(context) {
2534
+ const project = join(context.work, "app");
2535
+ const init = await context.scaffold("ajs project init", project);
2536
+ context.expect(init.folder, [exitIs(init, 0), exists(join(project, "antelope.config.ts"))], { critical: true });
2537
+ context.tree("scaffolded tree", project);
2538
+ const install = await context.command("pnpm install", "pnpm", [
2539
+ "install",
2540
+ "--frozen-lockfile",
2541
+ "--prefer-offline"
2542
+ ], { cwd: project });
2543
+ context.expect(install.folder, [exitIs(install, 0)], { critical: true });
2544
+ return project;
2545
+ }
2546
+ /** The journeys each kind ships, by id; a feature file names them next to its repo-owned journeys. */
2547
+ const BUILTIN_JOURNEYS = {
2548
+ interface: INTERFACE_JOURNEYS,
2549
+ module: { "module-dev": moduleDev },
2550
+ template: {
2551
+ "scaffold-dev": {
2552
+ title: "a project scaffolded from the template installs, starts and answers",
2553
+ entryPoint: "`ajs project init --template` from the interfaces manifest, then `ajs project dev --watch`, as the template's `pnpm dev` runs it",
2554
+ async run(context) {
2555
+ const app = await context.dev("ajs project dev --watch", await scaffoldProject(context), { args: ["--watch"] });
2556
+ const stopped = await context.stop("SIGINT", app);
2557
+ context.expect(stopped.folder, [interrupted(stopped)]);
2558
+ }
2559
+ },
2560
+ "scaffold-checks": {
2561
+ title: "a project scaffolded from the template passes its own checks",
2562
+ entryPoint: "`ajs project init --template` from the interfaces manifest, then `pnpm run checks`",
2563
+ async run(context) {
2564
+ const project = await scaffoldProject(context);
2565
+ const checks = await context.command("pnpm run checks", "pnpm", ["run", "checks"], { cwd: project });
2566
+ context.expect(checks.folder, [exitIs(checks, 0)]);
2567
+ }
2568
+ }
2569
+ }
2570
+ };
2571
+ //#endregion
2572
+ //#region src/verify/context.ts
2573
+ var JourneyAbort = class extends Error {};
2574
+ var NotVerified = class extends Error {};
2575
+ const READY_TIMEOUT_MS = 12e4;
2576
+ const STOP_TIMEOUT_MS = 3e4;
2577
+ const POLL_MS = 250;
2578
+ const SETTLE_MS = 3e3;
2579
+ function slug(text) {
2580
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
2581
+ }
2582
+ function sleep(ms) {
2583
+ return new Promise((resolve) => setTimeout(resolve, ms));
2584
+ }
2585
+ /** The harness side of a journey: every driving call writes its evidence into a new numbered step folder. */
2586
+ var VerifyContext = class {
2587
+ repo;
2588
+ folder;
2589
+ work;
2590
+ home;
2591
+ steps = [];
2592
+ running = [];
2593
+ fixtures = /* @__PURE__ */ new Map();
2594
+ index = 0;
2595
+ workspace;
2596
+ state;
2597
+ constructor(workspace, state, feature, journey) {
2598
+ this.workspace = workspace;
2599
+ this.state = state;
2600
+ this.repo = workspace.root;
2601
+ this.folder = join(state.evidence, feature, journey);
2602
+ this.work = join(state.dir, "work", feature, journey);
2603
+ this.home = join(state.dir, "homes", feature, journey);
2604
+ for (const folder of [
2605
+ this.folder,
2606
+ this.work,
2607
+ this.home
2608
+ ]) {
2609
+ rmSync(folder, {
2610
+ recursive: true,
2611
+ force: true
2612
+ });
2613
+ mkdirSync(folder, { recursive: true });
2614
+ }
2615
+ }
2616
+ /** A fresh numbered step folder. */
2617
+ step(name) {
2618
+ this.index += 1;
2619
+ const folder = join(this.folder, `${String(this.index).padStart(2, "0")}-${slug(name)}`);
2620
+ mkdirSync(folder, { recursive: true });
2621
+ return folder;
2622
+ }
2623
+ env(extra = {}) {
2624
+ return isolatedEnv(this.workspace, this.home, extra);
2625
+ }
2626
+ command(name, program, args, options = {}) {
2627
+ return runRecorded(this.step(name), {
2628
+ program,
2629
+ args,
2630
+ cwd: options.cwd ?? this.work,
2631
+ env: this.env(options.env),
2632
+ timeoutMs: options.timeoutMs
2633
+ });
2634
+ }
2635
+ /** Runs `ajs <args>` of the repository's `@antelopejs/core`. */
2636
+ ajs(name, args, options = {}) {
2637
+ return this.command(name, process.execPath, [ajsEntry(this.repo), ...args], options);
2638
+ }
2639
+ edit(name, file, content) {
2640
+ const folder = this.step(name);
2641
+ mkdirSync(join(file, ".."), { recursive: true });
2642
+ writeFileSync(file, content);
2643
+ writeFileSync(join(folder, "edit.txt"), `${file}\n---\n${content}`);
2644
+ return folder;
2645
+ }
2646
+ tree(name, root) {
2647
+ const folder = this.step(name);
2648
+ return {
2649
+ folder,
2650
+ lines: recordTree(folder, root)
2651
+ };
2652
+ }
2653
+ http(name, url, init = {}) {
2654
+ return httpRecorded(this.step(name), url, init);
2655
+ }
2656
+ expect(folder, checks, options = {}) {
2657
+ const name = relative(this.folder, folder) || "journey";
2658
+ this.steps.push({
2659
+ name,
2660
+ folder: relative(this.state.evidence, folder),
2661
+ checks
2662
+ });
2663
+ appendFileSync(join(folder, "checks.json"), `${JSON.stringify(checks, null, 2)}\n`);
2664
+ const passed = checks.every((check) => check.pass);
2665
+ if (!passed && options.critical) throw new JourneyAbort(`critical step ${name} failed`);
2666
+ return passed;
2667
+ }
2668
+ notVerified(reason) {
2669
+ throw new NotVerified(reason);
2670
+ }
2671
+ service(name) {
2672
+ const found = this.state.containers.find((container) => container.service === name);
2673
+ if (!found) throw new Error(`No service ${name} in this run; declare it under services in verify.config.ts.`);
2674
+ return {
2675
+ name,
2676
+ container: found.name,
2677
+ host: found.host,
2678
+ port: found.port
2679
+ };
2680
+ }
2681
+ services() {
2682
+ return this.state.containers.map((container) => this.service(container.service));
2683
+ }
2684
+ native(name, service, args) {
2685
+ return this.command(name, "docker", [
2686
+ "exec",
2687
+ this.service(service).container,
2688
+ ...args
2689
+ ]);
2690
+ }
2691
+ fixture(options = {}) {
2692
+ const config = options.moduleConfig ?? this.workspace.config.moduleConfig?.(this.services()) ?? {};
2693
+ const fixture = writeFixture(this.workspace, this.state, this.work, config);
2694
+ this.fixtures.set(fixture.project, fixture);
2695
+ this.tree("fixture project", fixture.project);
2696
+ return fixture.project;
2697
+ }
2698
+ /** The log the stub provider wrote, one call per line: the provider's view of what core delivered. */
2699
+ stubCalls(project) {
2700
+ const file = this.fixtures.get(project)?.env.VERIFY_CALL_LOG;
2701
+ if (!file) return [];
2702
+ let text = "";
2703
+ try {
2704
+ text = readFileSync(file, "utf8");
2705
+ } catch {
2706
+ return [];
2707
+ }
2708
+ return text.split("\n").filter(Boolean).map((line) => parseJson(line)).filter(isObject).map((entry) => ({
2709
+ path: String(entry.path),
2710
+ args: entry.args ?? null
2711
+ }));
2712
+ }
2713
+ async dev(name, project, options = {}) {
2714
+ const port = await freePort();
2715
+ const fixture = this.fixtures.get(project);
2716
+ const env = {
2717
+ ...fixture?.env,
2718
+ VERIFY_DRIVER_PORT: String(port),
2719
+ PORT: String(port),
2720
+ ...options.env
2721
+ };
2722
+ const folder = this.step(name);
2723
+ const handle = startRecorded(folder, {
2724
+ program: process.execPath,
2725
+ args: [
2726
+ ajsEntry(this.repo),
2727
+ "project",
2728
+ "dev",
2729
+ ...options.args ?? []
2730
+ ],
2731
+ cwd: project,
2732
+ env: this.env(env)
2733
+ });
2734
+ writeFileSync(join(folder, "port.txt"), `${port}\n`);
2735
+ const app = {
2736
+ name,
2737
+ pid: handle.pid,
2738
+ folder,
2739
+ project,
2740
+ port
2741
+ };
2742
+ this.running.push({
2743
+ app,
2744
+ handle
2745
+ });
2746
+ this.state.processes.push({
2747
+ name: `${name} (${project})`,
2748
+ pid: handle.pid
2749
+ });
2750
+ saveRun(this.state);
2751
+ await this.waitReady(app, handle, fixture !== void 0);
2752
+ return app;
2753
+ }
2754
+ async probe(app, fixture, folder) {
2755
+ const probe = this.workspace.config.template?.probe;
2756
+ if (!fixture && probe?.log) {
2757
+ const output = readOutput(app.folder);
2758
+ return {
2759
+ name: `dev output matches ${probe.log}`,
2760
+ pass: probe.log.test(`${output.stdout}${output.stderr}`),
2761
+ detail: output.stderr.slice(-300)
2762
+ };
2763
+ }
2764
+ const path = fixture ? "/health" : probe?.path ?? "/";
2765
+ const answer = await httpRecorded(folder, `http://127.0.0.1:${app.port}${path}`);
2766
+ const status = fixture ? 200 : probe?.status ?? 200;
2767
+ const body = !fixture && probe?.body ? probe.body : /./s;
2768
+ return {
2769
+ name: `GET ${path} answers ${status} with ${body}`,
2770
+ pass: answer.status === status && body.test(answer.body),
2771
+ detail: answer.error ?? `status ${answer.status}, body ${answer.body.slice(0, 300)}`
2772
+ };
2773
+ }
2774
+ async waitReady(app, handle, fixture) {
2775
+ const folder = this.step("ready");
2776
+ const deadline = Date.now() + READY_TIMEOUT_MS;
2777
+ let exited = false;
2778
+ handle.exited.then(() => {
2779
+ exited = true;
2780
+ });
2781
+ let check = await this.probe(app, fixture, folder);
2782
+ while (!check.pass && !exited && Date.now() < deadline) {
2783
+ await sleep(POLL_MS);
2784
+ check = await this.probe(app, fixture, folder);
2785
+ }
2786
+ const settle = this.workspace.config.template?.probe.log ? this.workspace.config.template.probe.settleMs ?? SETTLE_MS : 0;
2787
+ if (check.pass && settle > 0) await sleep(settle);
2788
+ const alive = {
2789
+ name: "still running after readiness",
2790
+ pass: !exited,
2791
+ detail: `waited ${settle} ms`
2792
+ };
2793
+ writeFileSync(join(folder, "ready.txt"), `${check.pass && !exited ? "ready" : exited ? "exited before ready" : "timed out"}\n`);
2794
+ this.expect(folder, check.pass ? [check, alive] : [check], { critical: true });
2795
+ this.expect(folder, [check], { critical: true });
2796
+ }
2797
+ /** Posts a JSON body to a route of the driver module. */
2798
+ async driver(name, app, route, body) {
2799
+ const result = await httpRecorded(this.step(name), `http://127.0.0.1:${app.port}${route}`, {
2800
+ method: "POST",
2801
+ body: JSON.stringify(body),
2802
+ timeoutMs: 3e4
2803
+ });
2804
+ const json = result.json !== void 0 && isObject(result.json) ? result.json : {};
2805
+ return {
2806
+ ...result,
2807
+ ok: json.ok === true,
2808
+ value: json.ok === true ? json.value : json.error
2809
+ };
2810
+ }
2811
+ call(name, app, request) {
2812
+ const body = {
2813
+ path: request.path,
2814
+ args: request.args ?? [],
2815
+ chain: request.chain ?? [],
2816
+ entry: request.entry ?? "."
2817
+ };
2818
+ if (request.interface) body.interface = request.interface;
2819
+ return this.driver(name, app, "/call", body);
2820
+ }
2821
+ async stop(name, app) {
2822
+ const folder = this.step(name);
2823
+ writeFileSync(join(folder, "command.txt"), `kill -INT ${app.pid}\n`);
2824
+ const running = this.running.find((entry) => entry.app.pid === app.pid);
2825
+ try {
2826
+ process.kill(app.pid, "SIGINT");
2827
+ } catch {
2828
+ writeFileSync(join(folder, "note.txt"), "process was already gone\n");
2829
+ }
2830
+ let timer;
2831
+ const timeout = new Promise((resolve) => {
2832
+ timer = setTimeout(() => resolve(void 0), STOP_TIMEOUT_MS);
2833
+ });
2834
+ const outcome = running ? await Promise.race([running.handle.exited, timeout]) : {
2835
+ exitCode: null,
2836
+ signal: null
2837
+ };
2838
+ clearTimeout(timer);
2839
+ if (!outcome) {
2840
+ killGroup(app.pid);
2841
+ writeFileSync(join(folder, "note.txt"), `no exit within ${STOP_TIMEOUT_MS} ms of SIGINT; killed the process group\n`);
2842
+ }
2843
+ const exit = outcome ?? {
2844
+ exitCode: null,
2845
+ signal: "SIGKILL"
2846
+ };
2847
+ writeFileSync(join(folder, "exit-code.txt"), `${exit.exitCode ?? `signal ${exit.signal}`}\n`);
2848
+ this.untrack(app.pid);
2849
+ return {
2850
+ ...exit,
2851
+ ...readOutput(app.folder),
2852
+ folder
2853
+ };
2854
+ }
2855
+ untrack(pid) {
2856
+ const index = this.running.findIndex((entry) => entry.app.pid === pid);
2857
+ if (index !== -1) this.running.splice(index, 1);
2858
+ this.state.processes = this.state.processes.filter((record) => record.pid !== pid);
2859
+ saveRun(this.state);
2860
+ }
2861
+ async scaffold(name, project, flags = [
2862
+ "--pm",
2863
+ "pnpm",
2864
+ "--git-init"
2865
+ ]) {
2866
+ const set = await this.ajs("config set git", [
2867
+ "config",
2868
+ "set",
2869
+ "git",
2870
+ this.state.manifestUrl
2871
+ ]);
2872
+ this.expect(set.folder, [{
2873
+ name: "git setting points at the offline manifest",
2874
+ pass: set.exitCode === 0,
2875
+ detail: set.stderr.slice(-300)
2876
+ }], { critical: true });
2877
+ return this.ajs(name, [
2878
+ "project",
2879
+ "init",
2880
+ relative(this.work, project),
2881
+ "--template",
2882
+ this.state.templateName,
2883
+ ...flags
2884
+ ]);
2885
+ }
2886
+ /** Stops every app the journey left running. */
2887
+ async cleanup() {
2888
+ for (const entry of this.running.slice()) await this.stop(`cleanup ${entry.app.name}`, entry.app);
2889
+ }
2890
+ /** Records why the journey ended without a verdict on the product. */
2891
+ static reasonOf(failure) {
2892
+ if (failure instanceof NotVerified) return {
2893
+ error: null,
2894
+ notVerified: failure.message
2895
+ };
2896
+ if (failure instanceof JourneyAbort) return {
2897
+ error: failure.message,
2898
+ notVerified: null
2899
+ };
2900
+ return {
2901
+ error: failure.stack ?? failure.message,
2902
+ notVerified: null
2903
+ };
2904
+ }
2905
+ };
2906
+ //#endregion
2907
+ //#region src/verify/runner.ts
2908
+ /** Every journey id a feature file may name: the kind's built-in journeys and the repo's own. */
2909
+ function knownJourneys(workspace) {
2910
+ return new Map([...Object.entries(BUILTIN_JOURNEYS[workspace.kind]), ...Object.entries(workspace.config.journeys ?? {})]);
2911
+ }
2912
+ /** The journeys a feature file registers, in order. */
2913
+ function featureJourneys(workspace, feature) {
2914
+ return readFeatures(workspace).find((entry) => entry.name === feature)?.journeys;
2915
+ }
2916
+ function resetServices(context) {
2917
+ for (const [name, service] of Object.entries(context.workspace.config.services ?? {})) {
2918
+ if (!service.reset) continue;
2919
+ const container = context.service(name).container;
2920
+ const run = spawnSync("docker", [
2921
+ "exec",
2922
+ container,
2923
+ ...service.reset
2924
+ ], { encoding: "utf8" });
2925
+ const folder = context.step(`reset ${name}`);
2926
+ writeFileSync(join(folder, "command.txt"), `docker exec ${container} ${service.reset.join(" ")}\n`);
2927
+ writeFileSync(join(folder, "stdout.txt"), run.stdout ?? "");
2928
+ writeFileSync(join(folder, "stderr.txt"), run.stderr ?? "");
2929
+ context.expect(folder, [{
2930
+ name: `${name} reset to a clean state`,
2931
+ pass: run.status === 0,
2932
+ detail: `exit ${run.status}`
2933
+ }], { critical: true });
2934
+ }
2935
+ }
2936
+ function statusOf(context, failure) {
2937
+ if (failure.notVerified !== null) return "NOT VERIFIED";
2938
+ return failure.error !== null || context.steps.some((step) => step.checks.some((check) => !check.pass)) || context.steps.length === 0 ? "FAIL" : "PASS";
2939
+ }
2940
+ async function runOne(workspace, state, feature, id, journey) {
2941
+ const context = new VerifyContext(workspace, state, feature, id);
2942
+ let failure = {
2943
+ error: null,
2944
+ notVerified: null
2945
+ };
2946
+ try {
2947
+ if (state.missingKeys.length > 0) context.notVerified(`provider sandbox keys missing from the environment: ${state.missingKeys.join(", ")}`);
2948
+ resetServices(context);
2949
+ await journey.run(context);
2950
+ } catch (error) {
2951
+ failure = VerifyContext.reasonOf(error instanceof Error ? error : new Error(String(error)));
2952
+ }
2953
+ await context.cleanup();
2954
+ const result = {
2955
+ feature,
2956
+ journey: id,
2957
+ title: journey.title,
2958
+ entryPoint: journey.entryPoint,
2959
+ status: statusOf(context, failure),
2960
+ steps: context.steps,
2961
+ ...failure,
2962
+ folder: relative(state.evidence, context.folder)
2963
+ };
2964
+ writeFileSync(join(context.folder, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
2965
+ return result;
2966
+ }
2967
+ /** Reads the merged results of a feature in a run, if any journey of it ran. */
2968
+ function readResults(state, feature) {
2969
+ const file = join(state.evidence, feature, "feature.json");
2970
+ if (!existsSync(file)) return void 0;
2971
+ return JSON.parse(readFileSync(file, "utf8"));
2972
+ }
2973
+ /**
2974
+ * Runs the named journeys of a feature, or all of them, and merges their
2975
+ * results into feature.json so partial runs add up instead of overwriting.
2976
+ */
2977
+ async function runFeature(workspace, state, feature, ids) {
2978
+ const registered = featureJourneys(workspace, feature);
2979
+ if (registered === void 0) throw new Error(`Unknown feature ${feature}: no features/${feature}.md`);
2980
+ const unknown = ids.filter((id) => !registered.includes(id));
2981
+ if (unknown.length > 0) throw new Error(`${feature} registers no journey ${unknown.join(", ")}; it registers ${registered.join(", ")}`);
2982
+ const known = knownJourneys(workspace);
2983
+ const results = [];
2984
+ for (const id of ids.length > 0 ? ids : registered) {
2985
+ const journey = known.get(id);
2986
+ if (journey === void 0) throw new Error(`${feature} names journey ${id}, which is neither built in nor in verify.config.ts journeys`);
2987
+ results.push(await runOne(workspace, state, feature, id, journey));
2988
+ }
2989
+ const earlier = readResults(state, feature) ?? [];
2990
+ const merged = registered.flatMap((id) => results.filter((result) => result.journey === id).concat(results.some((result) => result.journey === id) ? [] : earlier.filter((result) => result.journey === id)));
2991
+ writeFileSync(join(state.evidence, feature, "feature.json"), `${JSON.stringify(merged, null, 2)}\n`);
2992
+ return results;
2993
+ }
2994
+ //#endregion
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. */
2997
+ function inTree(worktree, program, args) {
2998
+ const run = spawnSync(program, args, {
2999
+ cwd: worktree,
3000
+ encoding: "utf8",
3001
+ env: {
3002
+ ...process.env,
3003
+ CI: "1"
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();
3008
+ }
3009
+ function prepareWorktree(workspace, label, feature) {
3010
+ const worktree = mkdtempSync(join(tmpdir(), `antelopejs-verify-seeded-${label}-`));
3011
+ execFileSync("git", [
3012
+ "worktree",
3013
+ "add",
3014
+ "--detach",
3015
+ "--force",
3016
+ worktree,
3017
+ "HEAD"
3018
+ ], {
3019
+ cwd: workspace.root,
3020
+ stdio: "ignore"
3021
+ });
3022
+ try {
3023
+ const skill = join(worktree, relative(workspace.root, workspace.skill));
3024
+ rmSync(skill, {
3025
+ recursive: true,
3026
+ force: true
3027
+ });
3028
+ cpSync(workspace.skill, skill, {
3029
+ recursive: true,
3030
+ verbatimSymlinks: true
3031
+ });
3032
+ if (feature !== null) inTree(worktree, "git", ["apply", join(skill, "seeded-breaks", `${feature}.patch`)]);
3033
+ inTree(worktree, "pnpm", [
3034
+ "install",
3035
+ "--frozen-lockfile",
3036
+ "--prefer-offline",
3037
+ "--ignore-scripts"
3038
+ ]);
3039
+ } catch (error) {
3040
+ removeWorktree(workspace, worktree);
3041
+ throw error;
3042
+ }
3043
+ return worktree;
3044
+ }
3045
+ function removeWorktree(workspace, worktree) {
3046
+ execFileSync("git", [
3047
+ "worktree",
3048
+ "remove",
3049
+ "--force",
3050
+ worktree
3051
+ ], {
3052
+ cwd: workspace.root,
3053
+ stdio: "ignore"
3054
+ });
3055
+ }
3056
+ function runFeatureIn(bin, worktree, feature, baseRef) {
3057
+ const created = spawnSync(process.execPath, [
3058
+ bin,
3059
+ "new",
3060
+ "--base",
3061
+ baseRef
3062
+ ], {
3063
+ cwd: worktree,
3064
+ encoding: "utf8"
3065
+ });
3066
+ const run = created.stdout.trim().split("\n").at(-1) ?? "";
3067
+ if (created.status !== 0 || !existsSync(join(run, "run.json"))) return {
3068
+ run,
3069
+ results: [],
3070
+ output: `${created.stdout}${created.stderr}`
3071
+ };
3072
+ const journeys = spawnSync(process.execPath, [
3073
+ bin,
3074
+ "journey",
3075
+ run,
3076
+ feature
3077
+ ], {
3078
+ cwd: worktree,
3079
+ encoding: "utf8"
3080
+ });
3081
+ const cleaned = spawnSync(process.execPath, [
3082
+ bin,
3083
+ "clean",
3084
+ run
3085
+ ], {
3086
+ cwd: worktree,
3087
+ encoding: "utf8"
3088
+ });
3089
+ return {
3090
+ run,
3091
+ results: readResults(loadRun(run), feature) ?? [],
3092
+ output: `${journeys.stdout}${journeys.stderr}${cleaned.stderr}`
3093
+ };
3094
+ }
3095
+ function failsACheck(result) {
3096
+ return result.steps.some((step) => step.checks.some((check) => !check.pass));
3097
+ }
3098
+ /** A break is caught only by a journey that passes in the control and fails one of its checks with the patch. */
3099
+ function judgeSeeded(feature, control, seeded) {
3100
+ const passedInControl = new Set(control.results.filter((result) => result.status === "PASS").map((result) => result.journey));
3101
+ const failed = seeded.results.filter((result) => result.status === "FAIL");
3102
+ return {
3103
+ feature,
3104
+ caught: failed.some((result) => passedInControl.has(result.journey) && failsACheck(result)),
3105
+ run: seeded.run,
3106
+ controlRun: control.run,
3107
+ caughtBy: failed.filter((result) => passedInControl.has(result.journey) && failsACheck(result)).map((result) => result.journey),
3108
+ failingInControl: control.results.filter((result) => result.status !== "PASS").map((result) => result.journey),
3109
+ harnessErrors: failed.filter((result) => !failsACheck(result)).map((result) => result.journey),
3110
+ output: seeded.output
3111
+ };
3112
+ }
3113
+ /**
3114
+ * Runs each feature's journeys twice from scratch worktrees of HEAD, with the
3115
+ * skill folder as it is in the checkout: once unpatched as the control, once
3116
+ * with seeded-breaks/<feature>.patch applied. Each run is cleaned afterwards;
3117
+ * both runs' evidence stays.
3118
+ */
3119
+ function runSeededBreaks(workspace, bin, features, baseRef) {
3120
+ const controlTree = prepareWorktree(workspace, "control", null);
3121
+ try {
3122
+ return features.map((feature) => {
3123
+ const control = runFeatureIn(bin, controlTree, feature, baseRef);
3124
+ const seededTree = prepareWorktree(workspace, feature, feature);
3125
+ try {
3126
+ return judgeSeeded(feature, control, runFeatureIn(bin, seededTree, feature, baseRef));
3127
+ } finally {
3128
+ removeWorktree(workspace, seededTree);
3129
+ }
3130
+ });
3131
+ } finally {
3132
+ removeWorktree(workspace, controlTree);
3133
+ }
3134
+ }
3135
+ /** Checks every seeded-doors/<kind>.patch: the path rules must flag its own kind. */
3136
+ function checkSeededDoors(workspace) {
3137
+ const folder = join(workspace.skill, "seeded-doors");
3138
+ if (!existsSync(folder)) return [];
3139
+ return readdirSync(folder).filter((file) => file.endsWith(".patch")).sort().map((file) => {
3140
+ const kind = file.replace(/\.patch$/, "");
3141
+ const kinds = flaggedDoors(workspace, patchFiles(join(folder, file))).map((door) => door.kind);
3142
+ return {
3143
+ kind,
3144
+ flagged: kinds.some((found) => found === kind),
3145
+ kinds
3146
+ };
3147
+ });
3148
+ }
3149
+ //#endregion
3150
+ //#region src/verify/verdict.ts
3151
+ const CONTAINED_KINDS = /* @__PURE__ */ new Set(["data", "format"]);
3152
+ /** The GitHub `owner/repo` of the origin remote. */
3153
+ function originRepository(root) {
3154
+ const url = git(root, [
3155
+ "remote",
3156
+ "get-url",
3157
+ "origin"
3158
+ ]);
3159
+ const match = /github\.com[:/](.+?)(?:\.git)?$/.exec(url);
3160
+ if (!match) throw new Error(`origin ${url} is not a GitHub repository`);
3161
+ return match[1];
3162
+ }
3163
+ function short(sha) {
3164
+ return sha.slice(0, 7);
3165
+ }
3166
+ function bullets(entries, empty) {
3167
+ return (entries.length > 0 ? entries : [empty]).map((entry) => `- ${entry}`);
3168
+ }
3169
+ function journeyRows(workspace, state, plan, link) {
3170
+ const rows = [];
3171
+ const reasons = [];
3172
+ const notVerified = [];
3173
+ const byJourney = /* @__PURE__ */ new Map();
3174
+ for (const feature of plan.run) {
3175
+ const results = readResults(state, feature) ?? [];
3176
+ const registered = featureJourneys(workspace, feature) ?? [];
3177
+ for (const id of registered.filter((journey) => !results.some((result) => result.journey === journey))) reasons.push(`${feature}/${id} was not run`);
3178
+ for (const result of results) {
3179
+ if (!registered.includes(result.journey)) reasons.push(`${feature}/${result.journey} is not a registered journey`);
3180
+ byJourney.set(`${feature}/${result.journey}`, result);
3181
+ if (result.status === "FAIL") reasons.push(`${feature}/${result.journey} failed`);
3182
+ if (result.status === "NOT VERIFIED") notVerified.push(`${feature}/${result.journey}: ${result.notVerified}`);
3183
+ const outcome = result.status === "PASS" ? "pass" : result.status === "FAIL" ? "**fail**" : "**not verified**";
3184
+ rows.push(`| ${feature} | \`${result.journey}\`: ${result.entryPoint} | ${outcome}: ${result.title} | [${result.folder}](${link(result.folder)}) |`);
3185
+ }
3186
+ }
3187
+ return {
3188
+ rows,
3189
+ reasons,
3190
+ notVerified,
3191
+ byJourney
3192
+ };
3193
+ }
3194
+ function doorReasons(workspace, judgement, results, plan) {
3195
+ const reasons = [];
3196
+ for (const row of judgement.doors.filter((door) => CONTAINED_KINDS.has(door.kind))) {
3197
+ const allowed = workspace.config.doors[row.kind]?.containments ?? [];
3198
+ const journey = results.get(row.containmentJourney);
3199
+ if (!allowed.includes(row.containmentJourney)) reasons.push(`${row.kind} door at ${row.location} names ${row.containmentJourney || "no journey"}; its containment must be one of ${allowed.join(", ") || "the kind's containments in verify.config.ts, which lists none"}`);
3200
+ else if (journey?.status !== "PASS") reasons.push(`${row.kind} door at ${row.location}: containment journey ${row.containmentJourney} did not pass in this run`);
3201
+ }
3202
+ for (const door of flaggedDoors(workspace, plan.changed)) for (const file of door.files) {
3203
+ const listed = judgement.doors.some((row) => row.kind === door.kind && row.location.includes(file));
3204
+ const dismissed = judgement.falsePositives.some((entry) => entry.kind === door.kind && entry.location === file);
3205
+ if (!listed && !dismissed) reasons.push(`path rules flag a ${door.kind} door at ${file} that the One-way doors section neither lists nor dismisses`);
3206
+ }
3207
+ return reasons;
3208
+ }
3209
+ function doorsSection(judgement) {
3210
+ const dismissed = judgement.falsePositives.map((entry) => `- Not a door: \`${entry.location}\` matches the ${entry.kind} path rules. ${entry.reason}`);
3211
+ if (judgement.doors.length === 0) return [`None: ${judgement.doorsNone}`, ...dismissed];
3212
+ return [
3213
+ ...dismissed,
3214
+ "| Kind | Location | What cannot be undone | Containment |",
3215
+ "|---|---|---|---|",
3216
+ ...judgement.doors.map((door) => `| ${door.kind} | \`${door.location}\` | ${door.irreversible} | ${door.containment}${door.containmentJourney ? ` (journey \`${door.containmentJourney}\`)` : ""} |`)
3217
+ ];
3218
+ }
3219
+ function formalSection(workspace, state, plan, link) {
3220
+ const reasons = [];
3221
+ const lines = [];
3222
+ const touched = touchedFormalChecks(workspace, plan.changed).map((check) => check.name);
3223
+ for (const check of workspace.config.formal ?? []) {
3224
+ const result = readFormalResult(state, check.name);
3225
+ const gate = touched.includes(check.name);
3226
+ if (!result) {
3227
+ if (gate) reasons.push(`formal check ${check.name} covers the diff but was not run`);
3228
+ continue;
3229
+ }
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`;
3234
+ lines.push(`\`${check.name}\` (${gate ? "covers the diff, gates the verdict" : "does not cover the diff, informational"}): ${summary}. [evidence](${link(result.folder)})`);
3235
+ }
3236
+ return {
3237
+ reasons,
3238
+ lines
3239
+ };
3240
+ }
3241
+ function docsReasons(judgement, plan) {
3242
+ return plan.docs.flatMap((page) => {
3243
+ const docs = judgement.docs.find((entry) => entry.page === page);
3244
+ if (!docs) return [`docs page ${page} of a touched feature has no judgement`];
3245
+ return docs.matches ? [] : [`${page} no longer matches the behaviour`];
3246
+ });
3247
+ }
3248
+ function resultOf(reasons, notVerified, notes) {
3249
+ if (reasons.length > 0) return "FAIL";
3250
+ if (notVerified.length > 0) return "NOT VERIFIED";
3251
+ return notes > 0 ? "PASS+NOTES" : "PASS";
3252
+ }
3253
+ /**
3254
+ * Computes the verdict of a run from its journey results, the diff plan and
3255
+ * the verifier's judgement, and writes verdict.md, verdict.json and plan.json
3256
+ * into the evidence folder.
3257
+ */
3258
+ function renderVerdict(workspace, state, pr, judgement) {
3259
+ const plan = planFor(workspace, state.baseRef);
3260
+ const repository = originRepository(workspace.root);
3261
+ const skillSha = git(workspace.root, [
3262
+ "log",
3263
+ "-1",
3264
+ "--format=%H",
3265
+ "--",
3266
+ relative(workspace.root, workspace.skill)
3267
+ ]) || plan.headSha;
3268
+ const link = (path) => `https://github.com/${repository}/tree/verify-evidence/pr-${pr}/${plan.headSha}/${path}`;
3269
+ const reasons = [];
3270
+ if (plan.headSha !== state.headSha) reasons.push(`the run was created at ${short(state.headSha)} but HEAD is ${short(plan.headSha)}`);
3271
+ const journeys = journeyRows(workspace, state, plan, link);
3272
+ const formal = formalSection(workspace, state, plan, link);
3273
+ reasons.push(...journeys.reasons, ...plan.unmapped.map((file) => `unmapped surface ${file}`), ...docsReasons(judgement, plan), ...doorReasons(workspace, judgement, journeys.byJourney, plan), ...formal.reasons);
3274
+ const notVerified = [...journeys.notVerified, ...judgement.notVerified];
3275
+ const result = resultOf(reasons, journeys.notVerified, notVerified.length + judgement.attention.length);
3276
+ const touched = plan.touched.map((entry) => `\`${entry.feature}\` (diff: ${entry.files.map((file) => `\`${file}\``).join(", ")})`);
3277
+ const markdown = [
3278
+ `## Verify: ${result}`,
3279
+ "",
3280
+ "### One-way doors",
3281
+ ...doorsSection(judgement),
3282
+ "",
3283
+ `**Head** \`${short(plan.headSha)}\` · **Skill** \`verify-${workspace.kind}\` @ \`${short(skillSha)}\` (not trusted yet) · **Verifier** ${judgement.verifier}`,
3284
+ "",
3285
+ "### Touched features",
3286
+ ...bullets(touched, "none"),
3287
+ `- ${SMOKE_FEATURE}: runs on every verdict`,
3288
+ "",
3289
+ ...plan.unmapped.length > 0 ? [
3290
+ "### Unmapped surfaces",
3291
+ ...plan.unmapped.map((file) => `- \`${file}\` matches no feature glob; add it to a feature file.`),
3292
+ ""
3293
+ ] : [],
3294
+ ...reasons.length > 0 ? [
3295
+ "### Why it fails",
3296
+ ...reasons.map((reason) => `- ${reason}`),
3297
+ ""
3298
+ ] : [],
3299
+ "### Journeys",
3300
+ "| Feature | Entry point | Result | Evidence |",
3301
+ "|---|---|---|---|",
3302
+ ...journeys.rows,
3303
+ "",
3304
+ "### Formal checks",
3305
+ ...bullets(formal.lines, "None configured."),
3306
+ "",
3307
+ "### Docs",
3308
+ ...bullets(judgement.docs.map((docs) => `\`${docs.page}\`: ${docs.matches ? "matches" : "**stale**"}${docs.note ? `. ${docs.note}` : ""}`), "No touched feature links a page."),
3309
+ "",
3310
+ "### Not verified",
3311
+ ...bullets(notVerified, "Nothing."),
3312
+ "",
3313
+ "### Attention",
3314
+ ...bullets(judgement.attention, "Nothing."),
3315
+ "",
3316
+ `Evidence: \`verify-evidence\` branch, [\`pr-${pr}/${plan.headSha}/\`](${link("")})`,
3317
+ ""
3318
+ ].join("\n");
3319
+ writeFileSync(join(state.evidence, "verdict.md"), markdown);
3320
+ writeFileSync(join(state.evidence, "plan.json"), `${JSON.stringify(plan, null, 2)}\n`);
3321
+ writeFileSync(join(state.evidence, "verdict.json"), `${JSON.stringify({
3322
+ result,
3323
+ headSha: plan.headSha,
3324
+ skillSha,
3325
+ pr,
3326
+ reasons
3327
+ }, null, 2)}\n`);
3328
+ return {
3329
+ result,
3330
+ headSha: plan.headSha,
3331
+ skillSha,
3332
+ pr,
3333
+ repository,
3334
+ markdown,
3335
+ reasons
3336
+ };
3337
+ }
3338
+ //#endregion
3339
+ //#region src/bin/verify.ts
3340
+ const USAGE = `Usage: antelopejs-verify <command>
3341
+
3342
+ map check every user-facing file is covered and every feature is complete
3343
+ plan [--base <ref>] map the diff to features; list unmapped surfaces
3344
+ new [--base <ref>] [--title <t>] build, prepare an isolated run, print its folder
3345
+ doctor <run> check the run is worth driving
3346
+ journey <run> <feature> [ids...] run a feature's journeys and record evidence
3347
+ formal <run> [--all] run the formal checks that cover the diff and gate them on changed behaviour
3348
+ doors [patch] [--base <ref>] print the One-way-door line for a patch, or for the diff
3349
+ seeded <feature...> [--base <ref>] run each feature unpatched and with its seeded break
3350
+ seeded-doors check every seeded door is flagged with its kind
3351
+ clean <run> stop what the run started, keep only the evidence
3352
+ verdict <run> --pr <n> render evidence/verdict.md from the results and evidence/judgement.json
3353
+ publish <run> --pr <n> push the evidence to verify-evidence, comment the verdict, set status verify
3354
+ `;
3355
+ function print(text) {
3356
+ process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
3357
+ }
3358
+ function detectKind(root, flag) {
3359
+ if (flag !== void 0) {
3360
+ if (!isVerifyKind(flag)) throw new Error(`--kind must be one of ${VERIFY_KINDS.join(", ")}`);
3361
+ return flag;
3362
+ }
3363
+ const found = VERIFY_KINDS.filter((kind) => existsSync(join(root, skillFolder(kind), "SKILL.md")));
3364
+ if (found.length !== 1) throw new Error(found.length === 0 ? "No shared verification skill in this repository: run antelopejs-sync --verify <kind>." : `Several shared verification skills: ${found.join(", ")}. Pass --kind.`);
3365
+ return found[0];
3366
+ }
3367
+ function printMap(workspace) {
3368
+ const problems = checkMap(workspace, [...knownJourneys(workspace).keys()]);
3369
+ for (const problem of problems) print(problem);
3370
+ return problems.length === 0 ? 0 : 1;
3371
+ }
3372
+ async function runJourneys(workspace, dir, feature, ids) {
3373
+ const results = await runFeature(workspace, loadRun(dir), feature, ids);
3374
+ for (const result of results) {
3375
+ print(`${result.status} ${feature}/${result.journey}`);
3376
+ for (const step of result.steps) for (const check of step.checks.filter((entry) => !entry.pass)) print(` ${step.name}: ${check.name} (${check.detail})`);
3377
+ if (result.error) print(` ${result.error.split("\n")[0]}`);
3378
+ if (result.notVerified) print(` ${result.notVerified}`);
3379
+ }
3380
+ return results.every((result) => result.status === "PASS") ? 0 : 1;
3381
+ }
3382
+ function runFormal(workspace, dir, all) {
3383
+ const state = loadRun(dir);
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;
3388
+ for (const check of checks) {
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}`);
3397
+ }
3398
+ if (checks.length === 0) print("no formal check covers the diff");
3399
+ return fails ? 1 : 0;
3400
+ }
3401
+ function printDoors(workspace, files) {
3402
+ const doors = flaggedDoors(workspace, files);
3403
+ print(doorLine(doors) || "One-way-door: none flagged by path rules");
3404
+ for (const door of doors) print(` ${door.kind}: ${door.files.join(", ")}`);
3405
+ return 0;
3406
+ }
3407
+ function runSeeded(workspace, features, baseRef) {
3408
+ const results = runSeededBreaks(workspace, process.argv[1], features, baseRef);
3409
+ for (const result of results) {
3410
+ print(`${result.caught ? "CAUGHT" : "MISSED"} ${result.feature} by ${result.caughtBy.join(", ") || "no journey"} (evidence ${result.run}/evidence/${result.feature}, control ${result.controlRun}/evidence/${result.feature})`);
3411
+ if (result.failingInControl.length > 0) print(` not passing without the patch, not counted: ${result.failingInControl.join(", ")}`);
3412
+ if (result.harnessErrors.length > 0) print(` failed without a failing check (harness error), not counted: ${result.harnessErrors.join(", ")}`);
3413
+ print(result.output.replace(/^/gm, " "));
3414
+ }
3415
+ return results.every((result) => result.caught) ? 0 : 1;
3416
+ }
3417
+ function runSeededDoors(workspace) {
3418
+ const doors = checkSeededDoors(workspace);
3419
+ for (const door of doors) print(`${door.flagged ? "FLAGGED" : "MISSED"} ${door.kind} (path rules flag: ${door.kinds.join(", ") || "nothing"})`);
3420
+ return doors.every((door) => door.flagged) ? 0 : 1;
3421
+ }
3422
+ function judge(workspace, command, dir, pr) {
3423
+ if (!Number.isInteger(pr) || pr <= 0) throw new Error(`${command} needs --pr <number>`);
3424
+ const state = loadRun(dir);
3425
+ const verdict = renderVerdict(workspace, state, pr, readJudgement(join(state.evidence, "judgement.json")));
3426
+ print(verdict.markdown);
3427
+ if (command === "publish") {
3428
+ print(`evidence commit ${pushEvidence(workspace.root, state, verdict)}`);
3429
+ const comment = postComment(workspace.root, verdict);
3430
+ print(`comment ${comment}`);
3431
+ const status = setStatus(workspace.root, verdict, comment);
3432
+ print(status.detail);
3433
+ if (!status.ok) return 1;
3434
+ }
3435
+ return verdict.result === "PASS" || verdict.result === "PASS+NOTES" ? 0 : 1;
3436
+ }
3437
+ async function main(argv) {
3438
+ const { positionals, values } = parseArgs({
3439
+ args: argv,
3440
+ allowPositionals: true,
3441
+ options: {
3442
+ base: {
3443
+ type: "string",
3444
+ default: "origin/main"
3445
+ },
3446
+ title: {
3447
+ type: "string",
3448
+ default: ""
3449
+ },
3450
+ pr: { type: "string" },
3451
+ all: { type: "boolean" },
3452
+ kind: { type: "string" }
3453
+ }
3454
+ });
3455
+ const [command, ...rest] = positionals;
3456
+ if (command === void 0) {
3457
+ print(USAGE);
3458
+ return 0;
3459
+ }
3460
+ const root = repositoryRoot();
3461
+ const workspace = await openWorkspace(root, detectKind(root, values.kind));
3462
+ if (command === "new") print((await createRun(workspace, values.base, values.title)).dir);
3463
+ else if (command === "map") return printMap(workspace);
3464
+ else if (command === "plan") {
3465
+ const plan = planFor(workspace, values.base);
3466
+ print(JSON.stringify(plan, null, 2));
3467
+ return plan.unmapped.length === 0 ? 0 : 1;
3468
+ } else if (command === "doctor") {
3469
+ const lines = doctor(workspace, loadRun(rest[0]));
3470
+ for (const line of lines) print(`${line.ok ? "ok " : "FAIL"} ${line.check}: ${line.detail}`);
3471
+ return lines.every((line) => line.ok) ? 0 : 1;
3472
+ } else if (command === "journey") return runJourneys(workspace, rest[0], rest[1], rest.slice(2));
3473
+ else if (command === "formal") return runFormal(workspace, rest[0], values.all === true);
3474
+ else if (command === "doors") return printDoors(workspace, rest[0] ? patchFiles(rest[0]) : planFor(workspace, values.base).changed);
3475
+ else if (command === "seeded") return runSeeded(workspace, rest, values.base);
3476
+ else if (command === "seeded-doors") return runSeededDoors(workspace);
3477
+ else if (command === "clean") for (const line of clean(loadRun(rest[0]))) print(line);
3478
+ else if (command === "verdict" || command === "publish") return judge(workspace, command, rest[0], Number(values.pr));
3479
+ else {
3480
+ print(USAGE);
3481
+ return 2;
3482
+ }
3483
+ return 0;
3484
+ }
3485
+ runCliAsync(() => main(process.argv.slice(2)));
3486
+ //#endregion
3487
+ export {};