@tangle-network/agent-app 0.46.21 → 0.46.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-OCZEPFAZ.js → chunk-BDMDL4AB.js} +27 -1
- package/dist/chunk-BDMDL4AB.js.map +1 -0
- package/dist/{chunk-55E3K3Q6.js → chunk-BOQ4HVVH.js} +36 -3
- package/dist/chunk-BOQ4HVVH.js.map +1 -0
- package/dist/peer-floors/check.d.ts +5 -0
- package/dist/peer-floors/check.js +3 -1
- package/dist/peer-floors/cli.js +5 -5
- package/dist/peer-floors/cli.js.map +1 -1
- package/dist/signoff/cli.js +1 -1
- package/dist/signoff/index.js +1 -1
- package/dist/signoff/node-version.d.ts +2 -0
- package/package.json +9 -9
- package/dist/chunk-55E3K3Q6.js.map +0 -1
- package/dist/chunk-OCZEPFAZ.js.map +0 -1
|
@@ -256,6 +256,31 @@ function assertNodeVersion(requirement, running = process.version) {
|
|
|
256
256
|
`signoff: this repo pins Node ${requirement.declared} (${requirement.source}) and you are running ${running}. A sign-off that replaces CI has to verify the runtime the product ships, so this refuses rather than reporting a pass it did not earn. Switch with \`nvm use ${requirement.major}\`, or change the pin if the product really has moved.`
|
|
257
257
|
);
|
|
258
258
|
}
|
|
259
|
+
function assertNodeTypesVersion(repoRoot, requirement) {
|
|
260
|
+
if (!requirement) return;
|
|
261
|
+
const packagePath = join3(repoRoot, "package.json");
|
|
262
|
+
if (!existsSync3(packagePath)) return;
|
|
263
|
+
const manifest = JSON.parse(readFileSync3(packagePath, "utf8"));
|
|
264
|
+
const declared = manifest.devDependencies?.["@types/node"] ?? manifest.dependencies?.["@types/node"] ?? manifest.optionalDependencies?.["@types/node"];
|
|
265
|
+
if (!declared) return;
|
|
266
|
+
const declaredMajor = /^[~^]?v?(\d+)(?:\.|$)/.exec(declared.trim())?.[1];
|
|
267
|
+
if (declaredMajor !== void 0 && Number.parseInt(declaredMajor, 10) !== requirement.major) {
|
|
268
|
+
throw new Error(
|
|
269
|
+
`signoff: this repo pins Node ${requirement.declared} but declares @types/node ${declared}. Use the latest @types/node ${requirement.major}.x release.`
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
const installedPath = join3(repoRoot, "node_modules", "@types", "node", "package.json");
|
|
273
|
+
if (!existsSync3(installedPath)) {
|
|
274
|
+
throw new Error(`signoff: @types/node is declared but missing after install in ${repoRoot}.`);
|
|
275
|
+
}
|
|
276
|
+
const installed = JSON.parse(readFileSync3(installedPath, "utf8"));
|
|
277
|
+
const installedMajor = majorOf(installed.version ?? "");
|
|
278
|
+
if (installedMajor !== requirement.major) {
|
|
279
|
+
throw new Error(
|
|
280
|
+
`signoff: this repo pins Node ${requirement.declared} but installed @types/node@${installed.version ?? "unknown"}. Use the latest @types/node ${requirement.major}.x release.`
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
259
284
|
|
|
260
285
|
// src/signoff/exec.ts
|
|
261
286
|
import { spawn } from "child_process";
|
|
@@ -800,6 +825,7 @@ async function runSignoff(options = {}) {
|
|
|
800
825
|
options
|
|
801
826
|
});
|
|
802
827
|
}
|
|
828
|
+
assertNodeTypesVersion(tree.path, nodeRequirement);
|
|
803
829
|
const treeRoot = tree.path;
|
|
804
830
|
const outcomes = await runGraph({
|
|
805
831
|
nodes: config.steps,
|
|
@@ -1022,4 +1048,4 @@ export {
|
|
|
1022
1048
|
formatSignoffReport,
|
|
1023
1049
|
formatSignoffLine
|
|
1024
1050
|
};
|
|
1025
|
-
//# sourceMappingURL=chunk-
|
|
1051
|
+
//# sourceMappingURL=chunk-BDMDL4AB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/signoff/config.ts","../src/signoff/run.ts","../src/signoff/node-version.ts","../src/signoff/workflow-pin.ts","../src/signoff/exec.ts","../src/signoff/schedule.ts","../src/signoff/seeds.ts","../src/signoff/store.ts","../src/signoff/workspace.ts","../src/signoff/report.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { z } from 'zod'\nimport type { LoadedSignoffConfig, SignoffConfig, SignoffStepSpec } from './types'\n\n/**\n * Where the step list comes from.\n *\n * It is declared by the repo, never hardcoded here, because the three workflows\n * this has to reproduce do not share a shape: tax-agent filters its install to\n * one workspace package and runs a Python toolkit suite; legal-agent runs a\n * react-router typegen and a Worker startup check; agent-app runs a named\n * incident-class gate, a generated-project test and knip. A checker that\n * hardcodes any one of those is wrong for the other two.\n *\n * Three sources, in order:\n * 1. `signoff.config.mjs` (or `.js`) — the full surface, including per-step\n * `env`, `needs` and shuffle specs.\n * 2. a `signoff` key in `package.json` — the same shape, JSON-only.\n * 3. derived from the repo's own `scripts`, so a repo gets a real gate before\n * anyone writes a config. The derivation is documented below and its origin\n * is stamped into the proof, because a derived run is a weaker claim than a\n * declared one.\n */\n\nconst SIGNOFF_CONFIG_FILES: readonly string[] = ['signoff.config.mjs', 'signoff.config.js']\n\nconst shuffleSchema = z.object({\n runs: z.number().int().positive().optional(),\n seeds: z.array(z.number().int()).optional(),\n args: z.array(z.string()).optional(),\n})\n\nconst stepSchema = z.object({\n name: z.string().min(1),\n run: z.string().min(1),\n cwd: z.string().optional(),\n env: z.record(z.string(), z.string()).optional(),\n needs: z.array(z.string()).optional(),\n timeoutMs: z.number().int().positive().optional(),\n shuffle: z.union([z.boolean(), shuffleSchema]).optional(),\n})\n\nconst configSchema = z.object({\n install: z\n .object({\n run: z.string().min(1).optional(),\n storeDirFlag: z.string().nullable().optional(),\n storeEnv: z.string().nullable().optional(),\n cwd: z.string().optional(),\n timeoutMs: z.number().int().positive().optional(),\n env: z.record(z.string(), z.string()).optional(),\n })\n .optional(),\n steps: z.array(stepSchema).min(1),\n maxParallel: z.number().int().positive().optional(),\n env: z.record(z.string(), z.string()).optional(),\n nodeVersion: z.string().min(1).optional(),\n carryFiles: z.array(z.string()).optional(),\n cacheDir: z.string().optional(),\n storeGenerations: z.number().int().positive().optional(),\n})\n\nfunction describeIssues(error: z.ZodError, where: string): string {\n const lines = error.issues.map((issue) => ` ${issue.path.join('.') || '(root)'}: ${issue.message}`)\n return `signoff: ${where} is not a valid config:\\n${lines.join('\\n')}`\n}\n\nexport function parseSignoffConfig(value: unknown, where: string): SignoffConfig {\n const result = configSchema.safeParse(value)\n if (!result.success) throw new Error(describeIssues(result.error, where))\n return result.data as SignoffConfig\n}\n\n/**\n * The script → step derivation, and the dependency edges it asserts.\n *\n * The edges are the speed lever, so each one is a claim about the repo:\n * typecheck, the suite, the build and knip are ASSUMED to read source and not\n * each other's output, so they run concurrently. Only `test:generated`\n * genuinely consumes a build artifact, so only it declares a dependency.\n *\n * **That assumption is a guess, and it is wrong for at least one real repo.**\n * agent-app's own suite copies `dist/` into a generated project while `tsup`\n * (`clean: true`) is deleting it, which fails loudly as \"dist/ not built\" and\n * quietly as a half-copied package. A repo whose suite reads build output MUST\n * declare `needs: ['build']` on it in a `signoff.config.mjs`; the derivation\n * cannot see that from a script name, which is one more reason a derived run is\n * a weaker claim than a declared one.\n *\n * `build:check` supersedes `build` when both exist (legal-agent's `build:check`\n * is `pnpm build && …`, so running both builds twice for one verdict).\n */\nconst DERIVED_STEPS: readonly {\n readonly script: string\n readonly name: string\n readonly shuffle?: boolean\n readonly supersedes?: string\n readonly needsBuild?: boolean\n}[] = [\n { script: 'peer-check', name: 'peer floors' },\n { script: 'typecheck', name: 'typecheck' },\n { script: 'test:gates', name: 'incident-class gates' },\n { script: 'test', name: 'unit tests', shuffle: true },\n { script: 'build', name: 'build' },\n { script: 'build:check', name: 'build + worker checks', supersedes: 'build' },\n { script: 'test:generated', name: 'generated projects', needsBuild: true },\n { script: 'knip', name: 'dead-surface (knip)' },\n]\n\nexport function deriveSignoffConfig(scripts: Readonly<Record<string, string>>): {\n readonly config: SignoffConfig\n readonly used: readonly string[]\n} {\n const present = DERIVED_STEPS.filter((candidate) => scripts[candidate.script] !== undefined)\n const superseded = new Set(present.map((candidate) => candidate.supersedes).filter((name): name is string => !!name))\n const kept = present.filter((candidate) => !superseded.has(candidate.script))\n const buildStep = kept.find((candidate) => candidate.script === 'build' || candidate.script === 'build:check')\n\n const steps: SignoffStepSpec[] = kept.map((candidate) => ({\n name: candidate.name,\n run: `pnpm run ${candidate.script}`,\n ...(candidate.shuffle ? { shuffle: true as const } : {}),\n ...(candidate.needsBuild && buildStep ? { needs: [buildStep.name] } : {}),\n }))\n\n if (steps.length === 0) {\n throw new Error(\n 'signoff: no config and no recognizable scripts. Add a `signoff.config.mjs` naming the steps ' +\n `this repo's CI runs, or a package.json \"signoff\" key. Recognized script names: ` +\n `${DERIVED_STEPS.map((candidate) => candidate.script).join(', ')}.`,\n )\n }\n return { config: { steps }, used: kept.map((candidate) => candidate.script) }\n}\n\nexport interface LoadSignoffConfigOptions {\n readonly repoRoot: string\n /** Explicit config path. Missing file is an error, never a silent fallback. */\n readonly configPath?: string\n}\n\nexport async function loadSignoffConfig(options: LoadSignoffConfigOptions): Promise<LoadedSignoffConfig> {\n const { repoRoot, configPath } = options\n\n if (configPath !== undefined) {\n const abs = resolve(repoRoot, configPath)\n if (!existsSync(abs)) throw new Error(`signoff: no config at ${abs}`)\n return { config: await importConfig(abs), origin: { kind: 'file', path: abs } }\n }\n\n for (const candidate of SIGNOFF_CONFIG_FILES) {\n const abs = join(repoRoot, candidate)\n if (existsSync(abs)) return { config: await importConfig(abs), origin: { kind: 'file', path: abs } }\n }\n\n const pkgPath = join(repoRoot, 'package.json')\n if (!existsSync(pkgPath)) {\n throw new Error(`signoff: ${repoRoot} has no package.json, no signoff.config.mjs, and nothing to derive from.`)\n }\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as {\n signoff?: unknown\n scripts?: Record<string, string>\n }\n if (pkg.signoff !== undefined) {\n return { config: parseSignoffConfig(pkg.signoff, `${pkgPath} \"signoff\"`), origin: { kind: 'package-json', path: pkgPath } }\n }\n\n const derived = deriveSignoffConfig(pkg.scripts ?? {})\n return { config: derived.config, origin: { kind: 'derived', path: pkgPath, scripts: derived.used } }\n}\n\nasync function importConfig(abs: string): Promise<SignoffConfig> {\n const mod: unknown = await import(pathToFileURL(abs).href)\n const value = (mod as { default?: unknown }).default\n if (value === undefined) throw new Error(`signoff: ${abs} must have a default export`)\n return parseSignoffConfig(value, abs)\n}\n","import { spawnSync } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { availableParallelism, homedir } from 'node:os'\nimport { basename, join, resolve } from 'node:path'\nimport { loadSignoffConfig } from './config'\nimport {\n assertNodeTypesVersion,\n assertNodeVersion,\n resolveNodeRequirement,\n type NodeVersionRequirement,\n} from './node-version'\nimport { runCommand, type CommandResult } from './exec'\nimport { runGraph, validateGraph, type TaskOutcome } from './schedule'\nimport { assertShuffleArgsReachTheRunner, newSeedBase, planAttempts } from './seeds'\nimport { resolveStore } from './store'\nimport { materializeCleanTree, removeCleanTree, repoRootOf, type CleanTree } from './workspace'\nimport type {\n SignoffAttempt,\n SignoffEvent,\n SignoffHostFacts,\n SignoffInstallResult,\n SignoffReport,\n SignoffSource,\n SignoffStepResult,\n SignoffStepSpec,\n} from './types'\n\n/**\n * The sign-off run: reproduce a clean CI environment, then go further.\n *\n * Order matters and each stage exists for a failure this fleet actually paid\n * for:\n * 1. a pristine checkout (`workspace.ts`) — no warm `node_modules`, no Vite\n * cache, because that is the entire mechanical difference between \"green\n * locally\" and \"red in CI\";\n * 2. `--frozen-lockfile` into a store keyed on the lockfile (`store.ts`) — the\n * clean install CI does, without paying the download twice;\n * 3. the repo's declared steps (`config.ts`), run as a graph rather than a line\n * (`schedule.ts`), with the suite re-run under randomized file order and\n * recorded seeds (`seeds.ts`) — the part CI does not do at all.\n *\n * Nothing about a failure is inferred. Every step reports its command, exit\n * code, duration, seed and captured output.\n */\n\nexport interface RunSignoffOptions {\n /** Any directory inside the repo. Defaults to the process cwd. */\n readonly repoDir?: string\n readonly configPath?: string\n /** Default `working-tree` — verify what you are about to commit. */\n readonly source?: SignoffSource\n /** Run every step even after one fails. Default false. */\n readonly keepGoing?: boolean\n /** Base seed. Pass a previous run's to reproduce it exactly. */\n readonly seed?: number\n readonly maxParallel?: number\n readonly cacheDir?: string\n /** Override every shuffled step's run count. */\n readonly shuffleRuns?: number\n /** Keep the clean tree for inspection instead of removing it. */\n readonly keepWorkspace?: boolean\n readonly onEvent?: (event: SignoffEvent) => void\n}\n\nconst DEFAULT_CACHE_DIR = join(homedir(), '.cache', 'agent-app-signoff')\n\nfunction hostFacts(treePath: string, requirement: NodeVersionRequirement | null): SignoffHostFacts {\n const pm = spawnSync('pnpm', ['--version'], { cwd: treePath, encoding: 'utf8' })\n return {\n node: process.version,\n nodePinned: requirement?.declared ?? null,\n nodePinSource: requirement?.source ?? null,\n packageManager: pm.status === 0 ? `pnpm ${pm.stdout.trim()}` : 'pnpm (not resolvable)',\n platform: process.platform,\n arch: process.arch,\n cpus: availableParallelism(),\n }\n}\n\n/** Successful steps keep only a tail; a passing 3,000-test run is not evidence. */\nconst SUCCESS_OUTPUT_TAIL = 4_000\n\nfunction toAttempt(result: CommandResult, seed: number | null, ok: boolean): SignoffAttempt {\n return {\n command: result.command,\n seed,\n exitCode: result.exitCode,\n signal: result.signal,\n durationMs: result.durationMs,\n timedOut: result.timedOut,\n output: ok ? result.output.slice(-SUCCESS_OUTPUT_TAIL) : result.output,\n outputTruncated: result.truncated || (ok && result.output.length > SUCCESS_OUTPUT_TAIL),\n }\n}\n\nfunction buildEnv(\n base: Readonly<Record<string, string | undefined>>,\n layers: readonly (Readonly<Record<string, string>> | undefined)[],\n): Record<string, string | undefined> {\n const env: Record<string, string | undefined> = { ...base }\n for (const layer of layers) {\n if (layer) Object.assign(env, layer)\n }\n return env\n}\n\n/** Where the store flag goes: after the subcommand, so `pnpm install X --store-dir Y` stays valid. */\nfunction withStoreDir(command: string, flag: string | null | undefined, storeDir: string): string {\n if (flag === null) return command\n return `${command} ${flag ?? '--store-dir'} ${JSON.stringify(storeDir)}`\n}\n\nexport async function runSignoff(options: RunSignoffOptions = {}): Promise<SignoffReport> {\n const startedAt = new Date()\n const wallStart = Date.now()\n const repoDir = resolve(options.repoDir ?? process.cwd())\n const repoRoot = repoRootOf(repoDir)\n const { config, origin } = await loadSignoffConfig({ repoRoot, configPath: options.configPath })\n\n // Fail before materializing anything: a bad graph is a config error, and\n // paying for an install to learn that is a waste of the speed this exists for.\n validateGraph(config.steps.map((step) => ({ name: step.name, needs: step.needs })))\n assertShuffleArgsReachTheRunner(config.steps)\n const nodeRequirement = resolveNodeRequirement(repoRoot, config.nodeVersion)\n assertNodeVersion(nodeRequirement)\n\n const source = options.source ?? 'working-tree'\n const cacheDir = resolve(options.cacheDir ?? config.cacheDir ?? DEFAULT_CACHE_DIR)\n // The tree lives under the same root as the stores on purpose: pnpm hardlinks\n // from the store into `node_modules`, and a store on another filesystem\n // silently degrades to a full copy.\n const treePath = join(cacheDir, 'trees', `${basename(repoRoot)}-${process.pid}`)\n\n let tree: CleanTree | null = null\n try {\n tree = materializeCleanTree({ repoDir: repoRoot, dest: treePath, source, carryFiles: config.carryFiles })\n options.onEvent?.({ kind: 'tree', path: tree.path, head: tree.head, dirty: tree.dirty })\n\n const store = resolveStore({ treePath: tree.path, cacheDir, generations: config.storeGenerations })\n options.onEvent?.({ kind: 'store', storeDir: store.storeDir, cacheHit: store.hit, cacheKey: store.cacheKey })\n\n const installSpec = config.install ?? {}\n const installCwd = join(tree.path, installSpec.cwd ?? '.')\n const installCommand = withStoreDir(\n installSpec.run ?? 'pnpm install --frozen-lockfile',\n installSpec.storeDirFlag,\n store.storeDir,\n )\n const storeEnvName = installSpec.storeEnv === null ? null : installSpec.storeEnv ?? 'NPM_CONFIG_STORE_DIR'\n const sharedEnv = buildEnv(process.env, [\n // Parity with CI: a runner that behaves differently under `CI` (vitest's\n // reporter, wrangler's prompts) must behave that way here too.\n { CI: 'true' },\n config.env,\n storeEnvName === null ? undefined : { [storeEnvName]: store.storeDir },\n ])\n\n options.onEvent?.({ kind: 'install-start', command: installCommand })\n const installResult = await runCommand({\n command: installCommand,\n cwd: installCwd,\n env: buildEnv(sharedEnv, [installSpec.env]),\n timeoutMs: installSpec.timeoutMs,\n })\n options.onEvent?.({ kind: 'install-end', exitCode: installResult.exitCode, durationMs: installResult.durationMs })\n\n const install: SignoffInstallResult = {\n command: installCommand,\n storeDir: store.storeDir,\n cacheKey: store.cacheKey,\n cacheHit: store.hit,\n keyedOn: store.keyedOn,\n exitCode: installResult.exitCode,\n durationMs: installResult.durationMs,\n output: installResult.exitCode === 0 ? installResult.output.slice(-SUCCESS_OUTPUT_TAIL) : installResult.output,\n outputTruncated: installResult.truncated,\n }\n\n const host = hostFacts(tree.path, nodeRequirement)\n const seedBase = options.seed ?? newSeedBase()\n\n if (installResult.exitCode !== 0) {\n // Every step is unrunnable, and saying so is the honest report. A gate\n // that reports \"0 failures\" because it never ran anything is the failure\n // mode this whole module exists to prevent.\n return finish({\n ok: false,\n startedAt,\n wallStart,\n tree,\n origin,\n host,\n install,\n steps: config.steps.map(\n (step): SignoffStepResult => ({\n name: step.name,\n status: 'skipped',\n attempts: [],\n durationMs: 0,\n startedAtMs: null,\n finishedAtMs: null,\n }),\n ),\n seedBase,\n keepGoing: options.keepGoing ?? false,\n workspaceRetained: options.keepWorkspace ?? false,\n source,\n options,\n })\n }\n\n assertNodeTypesVersion(tree.path, nodeRequirement)\n\n const treeRoot = tree.path\n const outcomes = await runGraph<SignoffStepSpec, readonly SignoffAttempt[]>({\n nodes: config.steps,\n maxParallel: options.maxParallel ?? config.maxParallel ?? availableParallelism(),\n keepGoing: options.keepGoing ?? false,\n run: async (step, signal) => {\n const attempts: SignoffAttempt[] = []\n for (const plan of planAttempts(step, seedBase, options.shuffleRuns)) {\n options.onEvent?.({ kind: 'step-start', name: step.name, command: plan.command, seed: plan.seed })\n const result = await runCommand({\n command: plan.command,\n cwd: join(treeRoot, step.cwd ?? '.'),\n env: buildEnv(sharedEnv, [step.env]),\n timeoutMs: step.timeoutMs,\n signal,\n })\n const ok = result.exitCode === 0\n attempts.push(toAttempt(result, plan.seed, ok))\n // Stop at the first failing order: the remaining seeds would report\n // the same defect, and the seed that found it is already recorded.\n if (!ok) {\n emitStepEnd(options, step.name, 'failed', attempts)\n return { ok: false, value: attempts }\n }\n }\n emitStepEnd(options, step.name, 'passed', attempts)\n return { ok: true, value: attempts }\n },\n })\n\n const steps = outcomes.map(toStepResult)\n return finish({\n ok: steps.every((step) => step.status === 'passed'),\n startedAt,\n wallStart,\n tree,\n origin,\n host,\n install,\n steps,\n seedBase,\n keepGoing: options.keepGoing ?? false,\n workspaceRetained: options.keepWorkspace ?? false,\n source,\n options,\n })\n } finally {\n if (tree && !options.keepWorkspace && existsSync(tree.path)) removeCleanTree(tree)\n }\n}\n\n/** Emitted from inside the step, so a watching CLI sees a completion when it\n * happens rather than every completion at the end of the run. */\nfunction emitStepEnd(\n options: RunSignoffOptions,\n name: string,\n status: SignoffStepResult['status'],\n attempts: readonly SignoffAttempt[],\n): void {\n options.onEvent?.({\n kind: 'step-end',\n name,\n status,\n durationMs: attempts.reduce((total, attempt) => total + attempt.durationMs, 0),\n })\n}\n\nfunction toStepResult(outcome: TaskOutcome<readonly SignoffAttempt[]>): SignoffStepResult {\n const attempts = outcome.value ?? []\n const durationMs = attempts.reduce((total, attempt) => total + attempt.durationMs, 0)\n return {\n name: outcome.name,\n status: outcome.status,\n attempts,\n durationMs,\n startedAtMs: outcome.startedAtMs,\n finishedAtMs: outcome.finishedAtMs,\n }\n}\n\ninterface FinishInput {\n readonly ok: boolean\n readonly startedAt: Date\n readonly wallStart: number\n readonly tree: CleanTree\n readonly origin: SignoffReport['configOrigin']\n readonly host: SignoffHostFacts\n readonly install: SignoffInstallResult\n readonly steps: readonly SignoffStepResult[]\n readonly seedBase: number\n readonly keepGoing: boolean\n readonly workspaceRetained: boolean\n readonly source: SignoffSource\n readonly options: RunSignoffOptions\n}\n\nfunction finish(input: FinishInput): SignoffReport {\n const serialMs = input.install.durationMs + input.steps.reduce((total, step) => total + step.durationMs, 0)\n const flags = [\n `--source ${input.source}`,\n `--seed ${input.seedBase}`,\n ...(input.keepGoing ? ['--keep-going'] : []),\n ]\n return {\n ok: input.ok,\n startedAt: input.startedAt.toISOString(),\n repo: {\n root: input.tree.root,\n head: input.tree.head,\n branch: input.tree.branch,\n source: input.source,\n dirty: input.tree.dirty,\n diffSha256: input.tree.diffSha256,\n untrackedFiles: input.tree.untrackedFiles,\n carriedFiles: input.tree.carriedFiles,\n },\n configOrigin: input.origin,\n workspace: input.tree.path,\n workspaceRetained: input.workspaceRetained,\n host: input.host,\n install: input.install,\n steps: input.steps,\n seedBase: input.seedBase,\n wallClockMs: Date.now() - input.wallStart,\n serialMs,\n keepGoing: input.keepGoing,\n reproduce: `agent-app-signoff ${input.tree.root} ${flags.join(' ')}`,\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { resolveWorkflowNodePin } from './workflow-pin'\n\n/**\n * Refuse to sign off on a runtime the product does not ship.\n *\n * CI pins its Node version (`actions/setup-node` with `node-version: 22` in all\n * three fleet workflows). A developer's shell does not — this host runs 24. A\n * local gate that inherits whatever is on `PATH` therefore verifies a runtime\n * nobody deploys, and reports it as the runtime that ships. That is the same\n * failure shape as a number measured in a narrower context than it is\n * presented in, and it is not acceptable in the thing that replaces the merge\n * gate.\n *\n * So the pin is read from the repo and enforced, or it is absent and the report\n * says so. Three sources, in order:\n *\n * - `signoff.config.mjs`'s `nodeVersion` — the explicit declaration.\n * - `.nvmrc` — the pin a repo already keeps for humans.\n * - the `pull_request` workflows' `node-version` (`./workflow-pin`) — the pin\n * CI itself runs on.\n *\n * **The third source was added because the first two were empty on the entire\n * fleet, and that produced a false PASS.** legal-agent `4c0d688` failed CI on\n * `Cannot bundle Node.js built-in \"node:sqlite\"` and this gate signed it off.\n * Reproduced in one installed tree, same bytes: Node 22 fails both files, Node\n * 24 passes both, every time. No `.nvmrc` exists in tax-agent, legal-agent or\n * agent-app; all three pin `node-version: 22` in the workflow being replaced.\n * A gate that replaces a workflow has to read the runtime that workflow pins.\n *\n * A `.nvmrc` and a workflow that disagree is not resolved by preference — it is\n * a refusal, because it means the local gate and CI verify different runtimes,\n * which is the exact defect this module exists to prevent.\n *\n * **`engines.node` is deliberately NOT read.** It is a floor (`\">=18\"`), not a\n * pin, so treating it as one manufactures refusals on every version above the\n * floor — and an unsatisfiable gate does not stop bad work, it gets waived.\n */\n\nexport interface NodeVersionRequirement {\n /** The declared major, e.g. `22`. */\n readonly major: number\n readonly declared: string\n /** Where it came from, for the proof. */\n readonly source: string\n}\n\n/** Leading major from a pin like `22`, `v22.22.3`, `22.22`, `lts/iron` (none). */\nfunction majorOf(raw: string): number | null {\n const match = /^v?(\\d+)(?:\\.|$)/.exec(raw.trim())\n return match?.[1] === undefined ? null : Number.parseInt(match[1], 10)\n}\n\nexport function resolveNodeRequirement(\n repoRoot: string,\n configured?: string,\n): NodeVersionRequirement | null {\n if (configured !== undefined) {\n const major = majorOf(configured)\n if (major === null) {\n throw new Error(\n `signoff: nodeVersion \"${configured}\" does not start with a major version. ` +\n 'Declare a pin like \"22\" or \"22.22.3\".',\n )\n }\n return { major, declared: configured.trim(), source: 'signoff config `nodeVersion`' }\n }\n\n let fromNvmrc: NodeVersionRequirement | null = null\n const nvmrc = join(repoRoot, '.nvmrc')\n if (existsSync(nvmrc)) {\n const raw = readFileSync(nvmrc, 'utf8').trim()\n const major = majorOf(raw)\n // An alias (`lts/iron`) is a pin this module cannot resolve without a\n // network call, so it is reported as no requirement rather than guessed.\n if (major !== null) fromNvmrc = { major, declared: raw, source: '.nvmrc' }\n }\n\n const fromWorkflow = resolveWorkflowNodePin(repoRoot, majorOf)\n if (fromNvmrc && fromWorkflow && fromNvmrc.major !== fromWorkflow.major) {\n throw new Error(\n `signoff: .nvmrc pins Node ${fromNvmrc.declared} and ${fromWorkflow.source} pins ` +\n `${fromWorkflow.declared}. A sign-off that replaces CI cannot verify two runtimes, and picking ` +\n 'one silently would sign off a runtime the other half of the repo says is wrong. Make them agree, ' +\n 'or declare `nodeVersion` in the signoff config.',\n )\n }\n if (fromNvmrc) return fromNvmrc\n if (fromWorkflow) return { ...fromWorkflow, source: fromWorkflow.source }\n return null\n}\n\n/**\n * Throw when the running Node cannot stand in for the declared one.\n *\n * Major-only: a patch difference is not a different runtime, and demanding an\n * exact patch would refuse every host that has not just re-installed.\n */\nexport function assertNodeVersion(requirement: NodeVersionRequirement | null, running = process.version): void {\n if (!requirement) return\n const runningMajor = majorOf(running)\n if (runningMajor === requirement.major) return\n throw new Error(\n `signoff: this repo pins Node ${requirement.declared} (${requirement.source}) and you are running ${running}. ` +\n 'A sign-off that replaces CI has to verify the runtime the product ships, so this refuses rather than ' +\n `reporting a pass it did not earn. Switch with \\`nvm use ${requirement.major}\\`, or change the pin if the ` +\n 'product really has moved.',\n )\n}\n\n/** Refuse Node declaration files for a different runtime major. */\nexport function assertNodeTypesVersion(\n repoRoot: string,\n requirement: NodeVersionRequirement | null,\n): void {\n if (!requirement) return\n const packagePath = join(repoRoot, 'package.json')\n if (!existsSync(packagePath)) return\n const manifest = JSON.parse(readFileSync(packagePath, 'utf8')) as {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n optionalDependencies?: Record<string, string>\n }\n const declared = manifest.devDependencies?.['@types/node']\n ?? manifest.dependencies?.['@types/node']\n ?? manifest.optionalDependencies?.['@types/node']\n if (!declared) return\n\n const declaredMajor = /^[~^]?v?(\\d+)(?:\\.|$)/.exec(declared.trim())?.[1]\n if (declaredMajor !== undefined && Number.parseInt(declaredMajor, 10) !== requirement.major) {\n throw new Error(\n `signoff: this repo pins Node ${requirement.declared} but declares @types/node ${declared}. `\n + `Use the latest @types/node ${requirement.major}.x release.`,\n )\n }\n\n const installedPath = join(repoRoot, 'node_modules', '@types', 'node', 'package.json')\n if (!existsSync(installedPath)) {\n throw new Error(`signoff: @types/node is declared but missing after install in ${repoRoot}.`)\n }\n const installed = JSON.parse(readFileSync(installedPath, 'utf8')) as { version?: string }\n const installedMajor = majorOf(installed.version ?? '')\n if (installedMajor !== requirement.major) {\n throw new Error(\n `signoff: this repo pins Node ${requirement.declared} but installed @types/node@${installed.version ?? 'unknown'}. `\n + `Use the latest @types/node ${requirement.major}.x release.`,\n )\n }\n}\n","import { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\n/**\n * Read the Node pin out of the workflows that gate a merge.\n *\n * This exists because of a measured false PASS. legal-agent `4c0d688` was red\n * in CI on two test files — `Cannot bundle Node.js built-in \"node:sqlite\"` —\n * and the sign-off gate signed it off. Same bytes, same lockfile, same\n * hermetic tree: on Node 22 both files fail, on Node 24 both pass, 100% of the\n * time. The runtime was the whole difference, and the gate never saw it because\n * it looked for a pin in exactly two places the fleet does not keep one.\n *\n * At measurement time, none of tax-agent, legal-agent, or agent-app had an\n * `.nvmrc`.\n * All three pinned Node 22 in the merge workflow.\n * Agent App now also pins Node 22 in `.nvmrc`.\n *\n * The workflow fallback reads only `pull_request` checks because those checks\n * can block a merge.\n * Agent App uses `.nvmrc` instead of this fallback.\n * Its publish workflow uses Node 22 for source checks and Node 24 for npm.\n *\n * Nothing here guesses. An expression (`${{ matrix.node }}`) is not a version,\n * a `node-version-file` that does not exist is not a pin, and two merge-gate\n * workflows on different majors is a question this module cannot answer.\n * Each one refuses and names the config key that settles it.\n */\n\nexport interface WorkflowNodePin {\n /** Repo-relative workflow path, for the proof. */\n readonly file: string\n /** The version as written: `22`, `24.18.0`, `v20`. */\n readonly value: string\n /** `node-version`, or the `node-version-file` path it was read through. */\n readonly via: string\n}\n\nconst WORKFLOW_DIR = join('.github', 'workflows')\n\n/** Everything after an unquoted ` #`, plus surrounding quotes, is not the value. */\nfunction scalarValue(raw: string): string {\n const withoutComment = raw.replace(/\\s+#.*$/, '').trim()\n const quoted = /^(['\"])(.*)\\1$/.exec(withoutComment)\n return (quoted?.[2] ?? withoutComment).trim()\n}\n\nfunction indentOf(line: string): number {\n return line.length - line.trimStart().length\n}\n\nfunction isBlank(line: string): boolean {\n const trimmed = line.trim()\n return trimmed.length === 0 || trimmed.startsWith('#')\n}\n\n/**\n * Does this workflow run on `pull_request`?\n *\n * Both spellings the fleet uses are handled: the block form every workflow here\n * writes, and the inline form (`on: [push, pull_request]`). `on` is quoted in\n * some repos because YAML 1.1 reads a bare `on` as the boolean true, so the\n * quoted keys are matched too.\n */\nexport function triggersOnPullRequest(source: string): boolean {\n const lines = source.split('\\n')\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index] as string\n const header = /^(?:on|\"on\"|'on')\\s*:(.*)$/.exec(line)\n if (!header) continue\n\n const inline = scalarValue(header[1] ?? '')\n if (inline.length > 0) {\n return inline\n .replace(/^\\[|\\]$/g, '')\n .split(',')\n .map((token) => token.trim())\n .includes('pull_request')\n }\n\n // Block form: the trigger names sit at the first nesting level under `on:`.\n // Anything deeper belongs to a trigger's own options (`branches`, `paths`).\n let nesting: number | null = null\n for (let cursor = index + 1; cursor < lines.length; cursor += 1) {\n const body = lines[cursor] as string\n if (isBlank(body)) continue\n const bodyIndent = indentOf(body)\n if (bodyIndent === 0) break\n if (nesting === null) nesting = bodyIndent\n if (bodyIndent !== nesting) continue\n const key = /^\\s*(?:-\\s*)?([A-Za-z_][\\w-]*)\\s*:?\\s*$/.exec(body)\n if (key?.[1] === 'pull_request') return true\n }\n return false\n }\n return false\n}\n\n/** Every Node pin an `actions/setup-node` step declares in one workflow. */\nfunction pinsInWorkflow(repoRoot: string, file: string, source: string): WorkflowNodePin[] {\n const pins: WorkflowNodePin[] = []\n for (const line of source.split('\\n')) {\n const match = /^\\s*(node-version|node-version-file)\\s*:\\s*(\\S.*)$/.exec(line)\n if (!match) continue\n const key = match[1] as string\n const value = scalarValue(match[2] as string)\n // A matrix expression is several runtimes, not one. Refusing to guess is\n // the point; `resolveWorkflowNodePin` turns an all-expression repo into a\n // named refusal rather than a silent \"unpinned\".\n if (value.includes('${{')) continue\n\n if (key === 'node-version') {\n pins.push({ file, value, via: 'node-version' })\n continue\n }\n\n const target = join(repoRoot, value)\n if (!existsSync(target)) {\n throw new Error(\n `signoff: ${file} reads its Node pin from \"${value}\" (node-version-file) and that file does not exist. ` +\n 'The workflow this gate replaces cannot itself run, so there is nothing to verify against.',\n )\n }\n const declared = readFileSync(target, 'utf8')\n .split('\\n')\n .map((entry) => entry.trim())\n .find((entry) => entry.length > 0 && !entry.startsWith('#'))\n if (declared !== undefined) pins.push({ file, value: declared, via: `node-version-file ${value}` })\n }\n return pins\n}\n\n/** Node pins declared by every workflow that gates a merge, in filename order. */\nexport function scanMergeGateNodePins(repoRoot: string): WorkflowNodePin[] {\n const dir = join(repoRoot, WORKFLOW_DIR)\n if (!existsSync(dir)) return []\n\n const pins: WorkflowNodePin[] = []\n const files = readdirSync(dir)\n .filter((name) => name.endsWith('.yml') || name.endsWith('.yaml'))\n .sort()\n for (const name of files) {\n const source = readFileSync(join(dir, name), 'utf8')\n if (!triggersOnPullRequest(source)) continue\n pins.push(...pinsInWorkflow(repoRoot, `${WORKFLOW_DIR}/${name}`, source))\n }\n return pins\n}\n\nexport interface ResolvedWorkflowPin {\n readonly major: number\n readonly declared: string\n readonly source: string\n}\n\n/**\n * One Node major for the whole merge gate, or a refusal that names why not.\n *\n * `majorOf` is injected rather than imported to keep the direction of the\n * dependency one-way: `node-version.ts` owns what a version string means, this\n * module owns where the string lives.\n */\nexport function resolveWorkflowNodePin(\n repoRoot: string,\n majorOf: (raw: string) => number | null,\n): ResolvedWorkflowPin | null {\n const pins = scanMergeGateNodePins(repoRoot)\n if (pins.length === 0) return null\n\n const byMajor = new Map<number, WorkflowNodePin[]>()\n for (const pin of pins) {\n const major = majorOf(pin.value)\n // An alias (`lts/*`) is a pin this module cannot resolve without a network\n // call — the same treatment `.nvmrc` gives one.\n if (major === null) continue\n const bucket = byMajor.get(major)\n if (bucket) bucket.push(pin)\n else byMajor.set(major, [pin])\n }\n\n if (byMajor.size === 0) return null\n if (byMajor.size > 1) {\n const detail = [...byMajor.values()]\n .flat()\n .map((pin) => ` ${pin.file} (${pin.via}): ${pin.value}`)\n .join('\\n')\n throw new Error(\n 'signoff: the workflows that gate a merge here pin different Node majors, so there is no single ' +\n `runtime to verify:\\n${detail}\\n` +\n 'Declare `nodeVersion` in the signoff config to say which one a sign-off means.',\n )\n }\n\n const [entry] = [...byMajor.entries()]\n if (entry === undefined) return null\n const [major, matched] = entry\n const first = matched[0] as WorkflowNodePin\n const files = [...new Set(matched.map((pin: WorkflowNodePin) => pin.file))].join(', ')\n return { major, declared: first.value, source: `${files} (${first.via})` }\n}\n","import { spawn } from 'node:child_process'\n\n/**\n * The subprocess primitive every sign-off step runs through.\n *\n * Three properties the gate depends on, none of which `execSync` gives:\n *\n * 1. **Cancellable.** Under fail-fast, a build still running when typecheck\n * fails is killed rather than waited out — otherwise the \"faster than CI\"\n * claim is spent waiting for work whose verdict no longer matters.\n * 2. **Process-group kill.** Steps run through `sh -c`, so killing the shell\n * leaves `vitest`'s forks and `tsup`'s dts worker orphaned and holding CPU.\n * The child is spawned as a group leader and the whole group is signalled.\n * 3. **Bounded, non-silent capture.** Output is capped, and when the cap is hit\n * the elision is stated in the captured text. A gate that quietly drops the\n * middle of a failure log is a gate that hides the failure.\n */\n\nexport interface CommandResult {\n readonly command: string\n readonly cwd: string\n readonly exitCode: number\n readonly signal: string | null\n readonly durationMs: number\n readonly output: string\n readonly truncated: boolean\n readonly timedOut: boolean\n}\n\nexport interface RunCommandOptions {\n readonly command: string\n readonly cwd: string\n readonly env?: Readonly<Record<string, string | undefined>>\n readonly timeoutMs?: number\n readonly signal?: AbortSignal\n /** Retained bytes before elision. Default 2 MiB. */\n readonly maxOutputBytes?: number\n /** Grace between SIGTERM and SIGKILL. Default 5 s. */\n readonly killGraceMs?: number\n readonly onData?: (chunk: string) => void\n}\n\nconst DEFAULT_MAX_OUTPUT_BYTES = 2 * 1024 * 1024\nconst DEFAULT_KILL_GRACE_MS = 5_000\n/** Fraction of the budget kept from the head; the rest is the tail. The head\n * carries the command echo and the first error, the tail carries the summary. */\nconst HEAD_SHARE = 0.25\n\n/**\n * Ring-ish buffer that keeps a head window and a tail window, so both the first\n * error and the final summary survive a very long log.\n */\nclass BoundedOutput {\n private head = ''\n private tail = ''\n private total = 0\n private readonly headBudget: number\n private readonly tailBudget: number\n\n constructor(private readonly budget: number) {\n this.headBudget = Math.floor(budget * HEAD_SHARE)\n this.tailBudget = budget - this.headBudget\n }\n\n push(chunk: string): void {\n this.total += chunk.length\n if (this.head.length < this.headBudget) {\n const room = this.headBudget - this.head.length\n this.head += chunk.slice(0, room)\n chunk = chunk.slice(room)\n if (chunk.length === 0) return\n }\n this.tail = (this.tail + chunk).slice(-this.tailBudget)\n }\n\n get truncated(): boolean {\n return this.total > this.budget\n }\n\n text(): string {\n if (!this.truncated) return this.head + this.tail\n const elided = this.total - this.head.length - this.tail.length\n return `${this.head}\\n\\n[signoff] ${elided} bytes elided (output exceeded ${this.budget} bytes)\\n\\n${this.tail}`\n }\n}\n\n/** Signal a whole process group, tolerating the race where it already exited. */\nfunction killGroup(pid: number, signal: NodeJS.Signals): void {\n try {\n process.kill(-pid, signal)\n } catch (err) {\n // ESRCH means the group is already gone, which is the outcome we wanted.\n // Anything else is a real failure to signal and must not be swallowed.\n if ((err as NodeJS.ErrnoException).code !== 'ESRCH') throw err\n }\n}\n\n/**\n * Run one shell command to completion and report what happened.\n *\n * Never throws on a non-zero exit — a failing step is data, not an exception.\n * It throws only when the process could not be started at all.\n */\nexport function runCommand(options: RunCommandOptions): Promise<CommandResult> {\n const {\n command,\n cwd,\n env,\n timeoutMs,\n signal,\n maxOutputBytes = DEFAULT_MAX_OUTPUT_BYTES,\n killGraceMs = DEFAULT_KILL_GRACE_MS,\n onData,\n } = options\n\n return new Promise<CommandResult>((resolve, reject) => {\n const startedAt = Date.now()\n const buffer = new BoundedOutput(maxOutputBytes)\n let timedOut = false\n let killTimer: NodeJS.Timeout | undefined\n let graceTimer: NodeJS.Timeout | undefined\n\n const child = spawn(command, {\n cwd,\n env: env as NodeJS.ProcessEnv | undefined,\n shell: true,\n // Group leader: lets one signal reach `sh` and everything it spawned.\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n\n const pid = child.pid\n const terminate = (): void => {\n if (pid === undefined || child.exitCode !== null || child.signalCode !== null) return\n killGroup(pid, 'SIGTERM')\n graceTimer = setTimeout(() => {\n if (child.exitCode === null && child.signalCode === null) killGroup(pid, 'SIGKILL')\n }, killGraceMs)\n graceTimer.unref()\n }\n\n const onAbort = (): void => terminate()\n signal?.addEventListener('abort', onAbort, { once: true })\n\n if (timeoutMs !== undefined) {\n killTimer = setTimeout(() => {\n timedOut = true\n terminate()\n }, timeoutMs)\n killTimer.unref()\n }\n\n const collect = (chunk: Buffer): void => {\n const text = chunk.toString('utf8')\n buffer.push(text)\n onData?.(text)\n }\n child.stdout.on('data', collect)\n child.stderr.on('data', collect)\n\n const cleanup = (): void => {\n if (killTimer) clearTimeout(killTimer)\n if (graceTimer) clearTimeout(graceTimer)\n signal?.removeEventListener('abort', onAbort)\n }\n\n child.on('error', (err) => {\n cleanup()\n reject(new Error(`signoff: could not start \\`${command}\\` in ${cwd}: ${err.message}`))\n })\n\n child.on('close', (code, sig) => {\n cleanup()\n resolve({\n command,\n cwd,\n // A signalled process reports code `null`; 128+n is the shell's own\n // convention and keeps the field a number a caller can compare.\n exitCode: code ?? (sig === 'SIGKILL' ? 137 : 143),\n signal: sig,\n durationMs: Date.now() - startedAt,\n output: buffer.text(),\n truncated: buffer.truncated,\n timedOut,\n })\n })\n })\n}\n","/**\n * The dependency graph, and running it as wide as the graph allows.\n *\n * CI runs these steps in a line because a YAML `steps:` list is a line. Nothing\n * about the work requires that: typecheck, the suite, the build and knip all\n * read source and none reads another's output. On a 32-core host, running them\n * concurrently is free wall-clock, and it is the only reason a strictly larger\n * verification can still finish faster than the CI it replaces.\n *\n * The graph is declared per step (`needs`), validated here, and the schedule is\n * derived from it — so an omitted edge is a correctness bug the repo owns, and\n * a cycle is named rather than deadlocking.\n */\n\nexport interface GraphNode {\n readonly name: string\n readonly needs?: readonly string[]\n}\n\n/** Throws on a duplicate name, a dangling `needs`, or a cycle. */\nexport function validateGraph(nodes: readonly GraphNode[]): void {\n const seen = new Set<string>()\n for (const node of nodes) {\n if (seen.has(node.name)) throw new Error(`signoff: two steps are both named \"${node.name}\"; names must be unique`)\n seen.add(node.name)\n }\n for (const node of nodes) {\n for (const need of node.needs ?? []) {\n if (!seen.has(need)) {\n throw new Error(`signoff: step \"${node.name}\" needs \"${need}\", which is not a step in this config`)\n }\n }\n }\n\n const byName = new Map(nodes.map((node) => [node.name, node]))\n const state = new Map<string, 'visiting' | 'done'>()\n const walk = (name: string, path: readonly string[]): void => {\n const status = state.get(name)\n if (status === 'done') return\n if (status === 'visiting') {\n const cycle = [...path.slice(path.indexOf(name)), name].join(' -> ')\n throw new Error(`signoff: dependency cycle among steps: ${cycle}`)\n }\n state.set(name, 'visiting')\n for (const need of byName.get(name)?.needs ?? []) walk(need, [...path, name])\n state.set(name, 'done')\n }\n for (const node of nodes) walk(node.name, [])\n}\n\ntype TaskStatus = 'passed' | 'failed' | 'skipped' | 'cancelled' | 'blocked'\n\nexport interface TaskOutcome<T> {\n readonly name: string\n readonly status: TaskStatus\n /** Present for anything that actually ran, including a cancelled task. */\n readonly value: T | null\n readonly startedAtMs: number | null\n readonly finishedAtMs: number | null\n}\n\nexport interface RunGraphOptions<TNode extends GraphNode, TValue> {\n readonly nodes: readonly TNode[]\n readonly maxParallel: number\n /** `false` stops scheduling after the first failure and kills what is running. */\n readonly keepGoing: boolean\n /** Runs one node. Resolves `{ ok }` for pass/fail; must not throw for a\n * failing command — a non-zero exit is data. */\n readonly run: (node: TNode, signal: AbortSignal) => Promise<{ readonly ok: boolean; readonly value: TValue }>\n /** Wall-clock origin, so outcomes are comparable across the whole run. */\n readonly now?: () => number\n}\n\n/**\n * Run the graph, honouring dependencies and the parallelism cap.\n *\n * Failure semantics, stated because they are the difference between a gate you\n * trust and one you argue with:\n * - fail-fast (default): nothing new is scheduled, everything in flight is\n * aborted and reported as `cancelled`, everything unstarted as `skipped`.\n * - `keepGoing`: independent work continues, but a step whose dependency\n * failed is reported `blocked`. It is never reported as passed, and never\n * silently omitted.\n */\nexport async function runGraph<TNode extends GraphNode, TValue>(\n options: RunGraphOptions<TNode, TValue>,\n): Promise<TaskOutcome<TValue>[]> {\n const { nodes, maxParallel, keepGoing, run, now = () => Date.now() } = options\n validateGraph(nodes)\n\n const origin = now()\n const outcomes = new Map<string, TaskOutcome<TValue>>()\n const pending = new Map(nodes.map((node) => [node.name, node]))\n const running = new Map<string, { readonly promise: Promise<void>; readonly controller: AbortController }>()\n let aborted = false\n\n const failedNames = new Set<string>()\n const passedNames = new Set<string>()\n\n const blockedBy = (node: TNode): boolean => (node.needs ?? []).some((need) => failedNames.has(need))\n const ready = (node: TNode): boolean => (node.needs ?? []).every((need) => passedNames.has(need))\n\n const settle = (name: string, outcome: TaskOutcome<TValue>): void => {\n outcomes.set(name, outcome)\n if (outcome.status === 'passed') passedNames.add(name)\n else failedNames.add(name)\n }\n\n const start = (node: TNode): void => {\n pending.delete(node.name)\n const controller = new AbortController()\n const startedAtMs = now() - origin\n const promise = run(node, controller.signal).then((result) => {\n const finishedAtMs = now() - origin\n const cancelled = controller.signal.aborted && !result.ok\n settle(node.name, {\n name: node.name,\n status: cancelled ? 'cancelled' : result.ok ? 'passed' : 'failed',\n value: result.value,\n startedAtMs,\n finishedAtMs,\n })\n running.delete(node.name)\n })\n running.set(node.name, { promise, controller })\n }\n\n for (;;) {\n if (!aborted) {\n // Drain everything the graph currently permits, up to the cap.\n for (const node of [...pending.values()]) {\n if (running.size >= maxParallel) break\n if (blockedBy(node)) {\n pending.delete(node.name)\n settle(node.name, { name: node.name, status: 'blocked', value: null, startedAtMs: null, finishedAtMs: null })\n continue\n }\n if (ready(node)) start(node)\n }\n }\n\n if (running.size === 0) {\n // Nothing running: either everything settled, or the rest is unreachable.\n if (pending.size === 0) break\n if (aborted) break\n // A pending node whose dependency neither passed nor failed cannot happen\n // after validateGraph, so anything left here is blocked or ready-next.\n const progressed = [...pending.values()].some((node) => ready(node) || blockedBy(node))\n if (!progressed) break\n continue\n }\n\n await Promise.race([...running.values()].map((entry) => entry.promise))\n\n if (!keepGoing && failedNames.size > 0 && !aborted) {\n aborted = true\n for (const entry of running.values()) entry.controller.abort()\n }\n }\n\n for (const node of pending.values()) {\n settle(node.name, {\n name: node.name,\n status: blockedBy(node) ? 'blocked' : 'skipped',\n value: null,\n startedAtMs: null,\n finishedAtMs: null,\n })\n }\n\n return nodes.map((node) => {\n const outcome = outcomes.get(node.name)\n if (!outcome) throw new Error(`signoff: step \"${node.name}\" produced no outcome — scheduler bug`)\n return outcome\n })\n}\n","import { createHash, randomInt } from 'node:crypto'\nimport type { SignoffShuffleSpec, SignoffStepSpec } from './types'\n\n/**\n * Suite-order randomization — the half of this gate that CI does not have.\n *\n * CI runs one arbitrary file order, so a scheduling-dependent failure is a coin\n * flip it happens to win or lose. The `node:sqlite` bundling failure that\n * started this was exactly that shape: it reproduced under CI's clean install\n * and worker sharding and not under a warm local run, and a single fixed order\n * could have missed it in either direction.\n *\n * Two rules make randomization useful rather than merely noisy:\n *\n * 1. **Every seed is recorded.** A shuffled failure that cannot be replayed is\n * a rumour. The report carries the base seed and every derived seed, and the\n * derivation is a pure function of `(base, step, index)` — so `--seed <base>`\n * reproduces the whole run, and a single seed replays one step.\n * 2. **Files are shuffled; tests inside a file are not.** File order is what\n * module-graph and worker-scheduling failures depend on. Shuffling the tests\n * within a file mostly finds intentional ordering in a `describe` block,\n * which is a false alarm, and a gate that cries wolf gets waived.\n */\n\n/**\n * Vitest file-order shuffle. `{seed}` is substituted per attempt.\n *\n * **No `--` separator, and that is measured, not assumed.** The habit is to\n * write `pnpm run test -- --flag`, and it silently breaks this: pnpm forwards\n * script arguments verbatim without needing the separator, so the `--` reaches\n * vitest, whose CLI treats it as end-of-options and drops everything after it.\n * Measured on this repo, four test files, `--reporter=verbose`:\n *\n * | invocation | seed 1 order | seed 2 order |\n * |---|---|---|\n * | `vitest run -- --sequence.shuffle.files=true --sequence.seed=N` | schedule, store, seeds, config | schedule, store, seeds, config |\n * | `vitest run --sequence.shuffle.files=true --sequence.seed=N` | schedule, config, store, seeds | seeds, schedule, config, store |\n *\n * The first row is the failure this gate exists to prevent, applied to itself:\n * a run that reports \"2 orders, seeds recorded\" while running one fixed order\n * twice. If a runner ever does need a separator, its config declares its own\n * `shuffle.args`.\n */\nconst DEFAULT_SHUFFLE_ARGS: readonly string[] = [\n '--sequence.shuffle.files=true',\n '--sequence.seed={seed}',\n]\n\nexport const DEFAULT_SHUFFLE_RUNS = 2\n\n/** A fresh base seed. Random, then recorded — never a fixed constant, or the\n * \"randomized\" order is one more fixed order. */\nexport function newSeedBase(): number {\n return randomInt(0, 2 ** 31 - 1)\n}\n\n/**\n * Derive a step's Nth seed from the base.\n *\n * A hash rather than `base + n`: adjacent seeds produce correlated orders in\n * some runners, and the point is independent samples of the order space.\n */\nexport function deriveSeed(base: number, stepName: string, index: number): number {\n const digest = createHash('sha256').update(`${base}:${stepName}:${index}`).digest()\n return digest.readUInt32BE(0) % 2 ** 31\n}\n\n/**\n * Refuse a shuffled step whose command cannot receive the appended flags.\n *\n * pnpm only forwards extra arguments to a script through `run`, `exec` or\n * `dlx`. The shorthand form puts pnpm's own option parser in front of them, and\n * what happens next is a version lottery. Measured on this host, appending\n * `--sequence.shuffle.files=true --sequence.seed=7` to a script that prints its\n * `process.argv`:\n *\n * | command | pnpm 9.15.9 | pnpm 10.22.0 |\n * |---|---|---|\n * | `pnpm run t <flags>` | forwarded, exit 0 | forwarded, exit 0 |\n * | `pnpm exec node probe.mjs <flags>` | forwarded, exit 0 | forwarded, exit 0 |\n * | `pnpm t <flags>` | `Unknown options`, exit 1 | exit 254, script never ran |\n * | `pnpm --filter web t <flags>` | `Unknown options`, exit 1 | **exit 0, script never ran** |\n *\n * That last cell is the reason this is a refusal and not a note. tax-agent's CI\n * runs `pnpm --filter web test`, and a config that copied the line verbatim\n * would, on pnpm 10, report a green \"unit tests\" step that executed zero tests.\n * A gate reporting safety it did not provide is the exact failure this module\n * exists to prevent, and the shorthand makes it silent.\n *\n * This is a static approximation — it checks the invocation SHAPE, not what the\n * runner received — so it is deliberately narrow: it fires only on commands\n * that invoke pnpm, and only on steps that get arguments appended.\n */\nexport function assertShuffleArgsReachTheRunner(steps: readonly SignoffStepSpec[]): void {\n for (const step of steps) {\n if (!normalizeShuffle(step.shuffle)) continue\n const tokens = step.run.split(/\\s+/).filter((token) => token.length > 0)\n const pnpmAt = tokens.findIndex((token) => token === 'pnpm' || token.endsWith('/pnpm'))\n if (pnpmAt === -1) continue\n if (tokens.slice(pnpmAt + 1).some((token) => token === 'run' || token === 'exec' || token === 'dlx')) continue\n throw new Error(\n `signoff: step \"${step.name}\" runs \\`${step.run}\\` and is shuffled, but pnpm only forwards appended ` +\n 'arguments to a script through `run`, `exec` or `dlx`. In the shorthand form pnpm 9 errors and pnpm 10 ' +\n 'exits 0 having run nothing, which would report a passing suite that never executed. ' +\n `Write it as \\`${step.run.replace(/\\s(\\S+)$/, ' run $1')}\\`.`,\n )\n }\n}\n\nexport interface StepAttemptPlan {\n readonly command: string\n readonly seed: number | null\n}\n\nfunction normalizeShuffle(shuffle: boolean | SignoffShuffleSpec | undefined): SignoffShuffleSpec | null {\n if (shuffle === undefined || shuffle === false) return null\n return shuffle === true ? {} : shuffle\n}\n\n/**\n * Expand one step into the commands that will actually run.\n *\n * An unshuffled step is one attempt with no seed. A shuffled step is one\n * attempt per seed, each with the seed substituted into the appended arguments.\n */\nexport function planAttempts(\n step: SignoffStepSpec,\n seedBase: number,\n overrideRuns?: number,\n): StepAttemptPlan[] {\n const spec = normalizeShuffle(step.shuffle)\n if (!spec) return [{ command: step.run, seed: null }]\n\n const args = spec.args ?? DEFAULT_SHUFFLE_ARGS\n const seeds =\n spec.seeds && spec.seeds.length > 0\n ? [...spec.seeds]\n : Array.from({ length: overrideRuns ?? spec.runs ?? DEFAULT_SHUFFLE_RUNS }, (_unused, index) =>\n deriveSeed(seedBase, step.name, index),\n )\n\n return seeds.map((seed) => ({\n command: `${step.run} ${args.map((arg) => arg.replaceAll('{seed}', String(seed))).join(' ')}`,\n seed,\n }))\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'\nimport { join, relative, sep } from 'node:path'\n\n/**\n * The pristine package store, cached on the lockfile so speed is not paid for\n * with a stale module graph.\n *\n * The whole mechanical difference between \"green locally\" and \"red in CI\" is\n * that CI installs `--frozen-lockfile` into an isolated store with no\n * `node_modules` and no framework cache, and a local run reuses both. Only one\n * of those two is safe to keep:\n *\n * - `node_modules` and any build/framework cache are **never** reused. They are\n * what masked the failure this gate exists to catch, and they are recreated\n * for every run inside a fresh `git worktree`.\n * - The **store** is reused, keyed on the bytes that decide what gets installed.\n * A pnpm store is content-addressed: every entry is named by the hash of what\n * is in it, so a reused entry cannot be a different version of a package than\n * the lockfile asked for. Reusing it skips downloads, not resolution.\n *\n * The key covers every manifest in the tree — lockfile, workspace file, every\n * `package.json`, `.npmrc`. Change any of them and the key changes, so the next\n * run installs into an empty store and pays the honest cold cost. Generations\n * are kept (default 4) rather than one, so moving between a branch and `main`\n * finds both warm instead of thrashing.\n */\n\n/** Basenames whose bytes decide what an install resolves to. */\nconst MANIFEST_FILES: readonly string[] = [\n 'pnpm-lock.yaml',\n 'pnpm-workspace.yaml',\n 'package.json',\n '.npmrc',\n '.nvmrc',\n 'package-lock.json',\n 'npm-shrinkwrap.json',\n 'yarn.lock',\n]\n\n/** Never descended into when hunting manifests. */\nconst SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next', '.wrangler', '.react-router'])\n\nexport interface StoreResolution {\n readonly storeDir: string\n readonly cacheKey: string\n /** True when a store for this key already had content. */\n readonly hit: boolean\n /** Repo-relative manifest paths, sorted — the inputs to `cacheKey`. */\n readonly keyedOn: readonly string[]\n /** Store directories removed by the generation cap. */\n readonly pruned: readonly string[]\n}\n\nexport interface ResolveStoreOptions {\n /** The clean tree whose manifests are hashed. */\n readonly treePath: string\n readonly cacheDir: string\n /** Generations to keep. Default 4. */\n readonly generations?: number\n}\n\nfunction collectManifests(dir: string, root: string, out: string[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) continue\n collectManifests(join(dir, entry.name), root, out)\n } else if (MANIFEST_FILES.includes(entry.name)) {\n out.push(relative(root, join(dir, entry.name)).split(sep).join('/'))\n }\n }\n}\n\n/** Every manifest in the tree, repo-relative and sorted. */\nexport function manifestFiles(treePath: string): string[] {\n const found: string[] = []\n collectManifests(treePath, treePath, found)\n return found.sort()\n}\n\n/** sha256 over each manifest's path and content — order-independent by sorting. */\nexport function manifestCacheKey(treePath: string, files: readonly string[]): string {\n const hash = createHash('sha256')\n for (const rel of files) {\n hash.update(rel)\n hash.update('\\0')\n hash.update(createHash('sha256').update(readFileSync(join(treePath, rel))).digest('hex'))\n hash.update('\\n')\n }\n return hash.digest('hex')\n}\n\n/**\n * Prune all but the `keep` most recently used store generations.\n *\n * Recency is the directory's mtime, stamped on every use, so the store a run\n * just used is never the one evicted.\n */\nfunction pruneStores(storesRoot: string, keep: number): string[] {\n if (!existsSync(storesRoot)) return []\n const entries = readdirSync(storesRoot, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => {\n const full = join(storesRoot, entry.name)\n return { full, mtimeMs: statSync(full).mtimeMs }\n })\n .sort((a, b) => b.mtimeMs - a.mtimeMs)\n\n const pruned: string[] = []\n for (const stale of entries.slice(keep)) {\n rmSync(stale.full, { recursive: true, force: true })\n pruned.push(stale.full)\n }\n return pruned\n}\n\nexport function resolveStore(options: ResolveStoreOptions): StoreResolution {\n const { treePath, cacheDir, generations = 4 } = options\n const files = manifestFiles(treePath)\n if (files.length === 0) {\n throw new Error(\n `signoff: no package manifest under ${treePath}. A sign-off run installs from a lockfile; ` +\n 'there is nothing here to install.',\n )\n }\n\n const cacheKey = manifestCacheKey(treePath, files)\n const storesRoot = join(cacheDir, 'stores')\n const storeDir = join(storesRoot, cacheKey)\n // A store directory that exists but holds only the marker is a previous run\n // that died before installing; treat it as a miss so the report does not\n // claim a warm store it does not have.\n const marker = join(storeDir, '.signoff-store.json')\n const hit = existsSync(storeDir) && readdirSync(storeDir).some((entry) => entry !== '.signoff-store.json')\n\n mkdirSync(storeDir, { recursive: true })\n writeFileSync(marker, `${JSON.stringify({ cacheKey, keyedOn: files, usedAt: new Date().toISOString() }, null, 2)}\\n`)\n const now = new Date()\n utimesSync(storeDir, now, now)\n\n return { storeDir, cacheKey, hit, keyedOn: files, pruned: pruneStores(storesRoot, generations) }\n}\n","import { spawnSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { copyFileSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport type { SignoffRepoFacts, SignoffSource } from './types'\n\n/**\n * Materialize the pristine checkout every step runs against.\n *\n * **The decision, and the measurement behind it: a `git worktree` of HEAD, not\n * a filtered copy.** Both were timed on two real repos on this host:\n *\n * | repo | `git worktree add --detach` | `rsync -a --exclude node_modules --exclude .git` |\n * |---|---|---|\n * | agent-app (931 tracked files) | **0.04 s / 11 MB** | 0.12 s / 25 MB |\n * | legal-agent (753 tracked files) | **0.06 s / 24 MB** | **3.97 s / 2.7 GB** |\n *\n * The 2.7 GB is the argument. The copy carried `build/`, `.react-router/` and\n * `.wrangler/` — generated output and framework caches — because an exclude\n * list is a hand-maintained enumeration of things to leave behind, and it is\n * never complete. A warm Vite cache is precisely what made the `node:sqlite`\n * bundling failure invisible locally while CI saw it, so a materializer that\n * can leak one has defeated its own purpose. `git` already knows what is source\n * and what is generated, and `.gitignore` is that list, maintained by the repo.\n *\n * The overlay on top is what keeps the gate usable before you commit:\n * `source: 'working-tree'` applies `git diff HEAD` (staged and unstaged) as a\n * patch and copies untracked, non-ignored files in. `source: 'head'` verifies\n * exactly the commit that would merge.\n */\n\nexport interface MaterializeOptions {\n readonly repoDir: string\n readonly dest: string\n readonly source: SignoffSource\n /** Gitignored files the run genuinely needs. Missing ones abort. */\n readonly carryFiles?: readonly string[]\n}\n\nexport interface CleanTree extends SignoffRepoFacts {\n /** Absolute path of the materialized checkout. */\n readonly path: string\n}\n\nfunction git(args: readonly string[], cwd: string): string {\n const result = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })\n if (result.error) throw new Error(`signoff: git ${args.join(' ')} failed to start: ${result.error.message}`)\n if (result.status !== 0) {\n throw new Error(`signoff: git ${args.join(' ')} exited ${result.status}\\n${result.stderr.trim()}`)\n }\n return result.stdout\n}\n\n/** Split a `-z` separated git list into entries. */\nfunction zsplit(out: string): string[] {\n return out.split('\\0').filter((entry) => entry.length > 0)\n}\n\nexport function repoRootOf(dir: string): string {\n return git(['rev-parse', '--show-toplevel'], dir).trim()\n}\n\nexport function materializeCleanTree(options: MaterializeOptions): CleanTree {\n const { repoDir, dest, source, carryFiles = [] } = options\n const root = repoRootOf(repoDir)\n const head = git(['rev-parse', 'HEAD'], root).trim()\n const branch = git(['rev-parse', '--abbrev-ref', 'HEAD'], root).trim()\n\n // A crashed earlier run leaves a registered worktree whose directory is gone;\n // `add` then refuses on a name collision. Pruning first is what makes the gate\n // re-runnable after a kill.\n git(['worktree', 'prune'], root)\n mkdirSync(dirname(dest), { recursive: true })\n if (existsSync(dest)) rmSync(dest, { recursive: true, force: true })\n git(['worktree', 'add', '--detach', '--quiet', dest, head], root)\n\n let diffSha256: string | null = null\n let untrackedFiles: string[] = []\n\n if (source === 'working-tree') {\n // `git diff HEAD` covers staged and unstaged changes to tracked files in one\n // patch, including deletions and renames. `--binary` keeps a changed image\n // or lockfile-adjacent binary from silently dropping out of the patch.\n const patch = git(['diff', 'HEAD', '--binary', '--no-color', '--no-ext-diff'], root)\n if (patch.length > 0) {\n diffSha256 = createHash('sha256').update(patch).digest('hex')\n const patchFile = join(dirname(dest), `${dest.split('/').pop() ?? 'tree'}.patch`)\n writeFileSync(patchFile, patch)\n // Fail loud: a patch that does not apply means the tree we would verify is\n // not the tree the developer has, and verifying the wrong bytes is worse\n // than not verifying.\n git(['apply', '--binary', '--whitespace=nowarn', patchFile], dest)\n rmSync(patchFile, { force: true })\n }\n\n untrackedFiles = zsplit(git(['ls-files', '--others', '--exclude-standard', '-z'], root))\n for (const rel of untrackedFiles) {\n const target = join(dest, rel)\n mkdirSync(dirname(target), { recursive: true })\n copyFileSync(join(root, rel), target)\n }\n }\n\n const carried: string[] = []\n for (const rel of carryFiles) {\n if (isAbsolute(rel)) throw new Error(`signoff: carryFiles must be repo-relative; got \"${rel}\"`)\n const from = resolve(root, rel)\n if (!existsSync(from)) {\n throw new Error(\n `signoff: carryFiles names \"${rel}\", which does not exist at ${from}. ` +\n 'Remove it from the config or create the file — installing without it would resolve ' +\n 'against a different registry than the one you think you are verifying.',\n )\n }\n const target = join(dest, rel)\n mkdirSync(dirname(target), { recursive: true })\n copyFileSync(from, target)\n carried.push(rel)\n }\n\n return {\n path: dest,\n root,\n head,\n branch,\n source,\n dirty: diffSha256 !== null || untrackedFiles.length > 0,\n diffSha256,\n untrackedFiles,\n carriedFiles: carried,\n }\n}\n\n/** Unregister and delete a materialized tree. */\nexport function removeCleanTree(tree: CleanTree): void {\n git(['worktree', 'remove', '--force', tree.path], tree.root)\n}\n","import type { SignoffReport, SignoffStepResult } from './types'\n\n/**\n * The proof a human reads before merging.\n *\n * A sign-off gate is only worth the CI it replaces if its output answers the\n * question CI's green tick answers and the ones it does not: what bytes were\n * verified, in what environment, under which suite orders, and how to reproduce\n * it. So the report leads with the verdict, states the subject (commit + patch\n * digest) and the environment (clean tree, store cache state), lists every step\n * with its seeds, and ends with the exact command that runs it again.\n *\n * Failure output is printed in full, under the step's name. Naming the step is\n * the difference between \"CI is red\" and a fix.\n */\n\nconst BAR = '─'.repeat(72)\n\nfunction ms(value: number): string {\n return value >= 10_000 ? `${(value / 1000).toFixed(1)}s` : `${value}ms`\n}\n\nfunction statusMark(status: SignoffStepResult['status']): string {\n switch (status) {\n case 'passed': return 'ok '\n case 'failed': return 'FAIL'\n case 'cancelled': return 'kill'\n case 'blocked': return 'blkd'\n case 'skipped': return '-- '\n }\n}\n\nfunction seedList(step: SignoffStepResult): string {\n const seeds = step.attempts.map((attempt) => attempt.seed).filter((seed): seed is number => seed !== null)\n return seeds.length === 0 ? '' : ` seeds ${seeds.join(', ')}`\n}\n\n/** Concurrency actually achieved, measured from the step windows rather than\n * asserted from the config. A claimed speedup nobody measured is a wish. */\nexport function peakConcurrency(steps: readonly SignoffStepResult[]): number {\n const events: { at: number; delta: number }[] = []\n for (const step of steps) {\n if (step.startedAtMs === null || step.finishedAtMs === null) continue\n events.push({ at: step.startedAtMs, delta: 1 }, { at: step.finishedAtMs, delta: -1 })\n }\n events.sort((a, b) => a.at - b.at || a.delta - b.delta)\n let current = 0\n let peak = 0\n for (const event of events) {\n current += event.delta\n peak = Math.max(peak, current)\n }\n return peak\n}\n\nexport function formatSignoffReport(report: SignoffReport): string {\n const lines: string[] = []\n const verdict = report.ok ? 'SIGN-OFF PASSED' : 'SIGN-OFF FAILED'\n lines.push(BAR, `${verdict} — ${report.repo.branch} @ ${report.repo.head.slice(0, 12)}`, BAR, '')\n\n lines.push('subject')\n lines.push(` repo ${report.repo.root}`)\n lines.push(` source ${report.repo.source}${report.repo.dirty ? ' (working tree carries uncommitted work)' : ''}`)\n if (report.repo.diffSha256) lines.push(` patch sha256:${report.repo.diffSha256.slice(0, 16)}`)\n if (report.repo.untrackedFiles.length > 0) {\n lines.push(` untracked ${report.repo.untrackedFiles.length} file(s) copied in`)\n }\n if (report.repo.carriedFiles.length > 0) lines.push(` carried ${report.repo.carriedFiles.join(', ')}`)\n lines.push('')\n\n lines.push('environment')\n lines.push(` clean tree ${report.workspace}${report.workspaceRetained ? ' (retained)' : ' (removed)'}`)\n lines.push(` install ${report.install.command}`)\n lines.push(\n ` store ${report.install.cacheHit ? 'warm' : 'cold'} — ${report.install.cacheKey.slice(0, 16)} ` +\n `(keyed on ${report.install.keyedOn.length} manifest file(s))`,\n )\n lines.push(\n ` host ${report.host.node} · ${report.host.packageManager} · ${report.host.cpus} cpus` +\n (report.host.nodePinned === null\n ? ' · node UNPINNED by this repo'\n : ` · pinned ${report.host.nodePinned} (${report.host.nodePinSource})`),\n )\n lines.push(\n ` config ${report.configOrigin.kind === 'derived'\n ? `derived from scripts: ${report.configOrigin.scripts.join(', ')}`\n : report.configOrigin.path}`,\n )\n lines.push('')\n\n const width = Math.max(...report.steps.map((step) => step.name.length), 'install'.length)\n lines.push('steps')\n lines.push(\n ` ${report.install.exitCode === 0 ? 'ok ' : 'FAIL'} ${'install'.padEnd(width)} ${ms(report.install.durationMs).padStart(8)}`,\n )\n for (const step of report.steps) {\n const window =\n step.startedAtMs === null || step.finishedAtMs === null\n ? ''\n : ` [${ms(step.startedAtMs)} → ${ms(step.finishedAtMs)}]`\n lines.push(\n ` ${statusMark(step.status)} ${step.name.padEnd(width)} ${ms(step.durationMs).padStart(8)}` +\n ` ${step.attempts.length} run(s)${window}${seedList(step)}`,\n )\n }\n lines.push('')\n\n const peak = peakConcurrency(report.steps)\n const saved = report.serialMs - report.wallClockMs\n lines.push('timing')\n lines.push(` wall clock ${ms(report.wallClockMs)}`)\n lines.push(` serial sum ${ms(report.serialMs)} (install + every step, one after another)`)\n lines.push(\n ` parallel peak ${peak} step(s) at once — ` +\n (saved > 0 ? `${ms(saved)} saved, ${(report.serialMs / report.wallClockMs).toFixed(2)}x` : 'no overlap available'),\n )\n lines.push('')\n\n const failures = report.steps.filter((step) => step.status === 'failed' || step.status === 'cancelled')\n if (report.install.exitCode !== 0) {\n lines.push(BAR, 'install FAILED — no step could run', BAR, report.install.output.trimEnd(), '')\n }\n for (const step of failures) {\n const last = step.attempts[step.attempts.length - 1]\n lines.push(BAR)\n lines.push(`${step.status === 'cancelled' ? 'CANCELLED' : 'FAILED'}: ${step.name}`)\n if (last) {\n lines.push(` command ${last.command}`)\n lines.push(` exit ${last.exitCode}${last.signal ? ` (${last.signal})` : ''}${last.timedOut ? ' — TIMED OUT' : ''}`)\n if (last.seed !== null) {\n lines.push(` seed ${last.seed} — replay this order alone with the same seed`)\n }\n lines.push(BAR, last.output.trimEnd(), '')\n }\n }\n\n const blocked = report.steps.filter((step) => step.status === 'blocked' || step.status === 'skipped')\n if (blocked.length > 0) {\n lines.push(`not judged: ${blocked.map((step) => `${step.name} (${step.status})`).join(', ')}`)\n lines.push('')\n }\n\n lines.push(`reproduce: ${report.reproduce}`)\n return lines.join('\\n')\n}\n\n/** One line for a commit message, a PR comment, or a chat handoff. */\nexport function formatSignoffLine(report: SignoffReport): string {\n const passed = report.steps.filter((step) => step.status === 'passed').length\n return (\n `${report.ok ? 'signoff PASS' : 'signoff FAIL'} ${report.repo.head.slice(0, 12)} — ` +\n `${passed}/${report.steps.length} steps, ${ms(report.wallClockMs)} wall ` +\n `(${ms(report.serialMs)} serial), seed ${report.seedBase}, ` +\n `${report.install.cacheHit ? 'warm' : 'cold'} store, clean install`\n )\n}\n"],"mappings":";AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,MAAM,eAAe;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,SAAS;AAuBlB,IAAM,uBAA0C,CAAC,sBAAsB,mBAAmB;AAE1F,IAAM,gBAAgB,EAAE,OAAO;AAAA,EAC7B,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS;AAAA,EAC3C,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EAC1C,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AACrC,CAAC;AAED,IAAM,aAAa,EAAE,OAAO;AAAA,EAC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AAI,oDAA+C;AAAA,MACpF;AACA,YAAM,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,EAAE;AAAA,IAC3C;AAAA,EACF;AAEA,QAAM,UAAU,OAAO,MAAM,OAAO,CAAC,SAAS,KAAK,WAAW,aAAa,KAAK,WAAW,SAAS;AACpG,MAAI,QAAQ,SAAS,GAAG;AACtB,UAAM,KAAK,eAAe,QAAQ,IAAI,CAAC,SAAS,GAAG,KAAK,IAAI,KAAK,KAAK,MAAM,GAAG,EAAE,KAAK,IAAI,CAAC,EAAE;AAC7F,UAAM,KAAK,EAAE;AAAA,EACf;AAEA,QAAM,KAAK,cAAc,OAAO,SAAS,EAAE;AAC3C,SAAO,MAAM,KAAK,IAAI;AACxB;AAGO,SAAS,kBAAkB,QAA+B;AAC/D,QAAM,SAAS,OAAO,MAAM,OAAO,CAAC,SAAS,KAAK,WAAW,QAAQ,EAAE;AACvE,SACE,GAAG,OAAO,KAAK,iBAAiB,cAAc,IAAI,OAAO,KAAK,KAAK,MAAM,GAAG,EAAE,CAAC,WAC5E,MAAM,IAAI,OAAO,MAAM,MAAM,WAAW,GAAG,OAAO,WAAW,CAAC,UAC7D,GAAG,OAAO,QAAQ,CAAC,kBAAkB,OAAO,QAAQ,KACrD,OAAO,QAAQ,WAAW,SAAS,MAAM;AAEhD;","names":["spawnSync","existsSync","join","resolve","existsSync","readFileSync","join","existsSync","readFileSync","join","majorOf","major","join","existsSync","readFileSync","resolve","createHash","existsSync","readFileSync","readdirSync","join","createHash","existsSync","mkdirSync","rmSync","writeFileSync","join","resolve","join","spawnSync","resolve","existsSync"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/peer-floors/check.ts
|
|
2
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
2
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, readdirSync as readdirSync2 } from "fs";
|
|
3
3
|
import { dirname as dirname2, join as join2 } from "path";
|
|
4
4
|
|
|
5
5
|
// src/peer-floors/dependency-source.ts
|
|
@@ -475,6 +475,15 @@ function formatDependencySourceReport(report) {
|
|
|
475
475
|
}
|
|
476
476
|
|
|
477
477
|
// src/peer-floors/check.ts
|
|
478
|
+
function installedPackageNames(appDir, modulesDir, scope) {
|
|
479
|
+
const modulesRoot = join2(appDir, modulesDir);
|
|
480
|
+
if (!existsSync2(modulesRoot)) return [];
|
|
481
|
+
if (scope !== "") {
|
|
482
|
+
const scopeDir = join2(modulesRoot, scope.slice(0, -1));
|
|
483
|
+
return existsSync2(scopeDir) ? readdirSync2(scopeDir).sort().map((name) => `${scope}${name}`) : [];
|
|
484
|
+
}
|
|
485
|
+
return readdirSync2(modulesRoot).filter((name) => !name.startsWith(".")).flatMap((name) => name.startsWith("@") ? readdirSync2(join2(modulesRoot, name)).map((child) => `${name}/${child}`) : [name]).sort();
|
|
486
|
+
}
|
|
478
487
|
function readInstalledManifest(name, fromDir, modulesDir) {
|
|
479
488
|
let dir = fromDir;
|
|
480
489
|
for (; ; ) {
|
|
@@ -571,19 +580,42 @@ function checkPeerFloors(options) {
|
|
|
571
580
|
});
|
|
572
581
|
const violations = rows.filter((row) => row.verdict === "below-floor" || row.verdict === "absent-but-declared");
|
|
573
582
|
return {
|
|
583
|
+
shell,
|
|
574
584
|
shellVersion: shellManifest.version ?? "unknown",
|
|
575
585
|
rows,
|
|
576
586
|
violations,
|
|
577
587
|
ok: violations.length === 0
|
|
578
588
|
};
|
|
579
589
|
}
|
|
590
|
+
function checkAllPeerFloors(options) {
|
|
591
|
+
const {
|
|
592
|
+
appDir,
|
|
593
|
+
modulesDir = "node_modules",
|
|
594
|
+
scope = "@tangle-network/"
|
|
595
|
+
} = options;
|
|
596
|
+
const normalizedScope = scope === "" ? "" : scope.endsWith("/") ? scope : `${scope}/`;
|
|
597
|
+
const shells = installedPackageNames(appDir, modulesDir, normalizedScope).filter((name) => {
|
|
598
|
+
const manifest = readInstalledManifest(name, appDir, modulesDir);
|
|
599
|
+
return Object.keys(manifest?.peerDependencies ?? {}).some((peer) => peer.startsWith(normalizedScope));
|
|
600
|
+
});
|
|
601
|
+
if (shells.length === 0) {
|
|
602
|
+
const label = normalizedScope || "package";
|
|
603
|
+
throw new Error(`no installed ${label} package declares a ${label} peer under ${appDir}`);
|
|
604
|
+
}
|
|
605
|
+
return shells.map((shell) => checkPeerFloors({
|
|
606
|
+
appDir,
|
|
607
|
+
modulesDir,
|
|
608
|
+
scope: normalizedScope,
|
|
609
|
+
shell
|
|
610
|
+
}));
|
|
611
|
+
}
|
|
580
612
|
function describePeerFloorViolation(row, shellVersion, shell = "@tangle-network/agent-app") {
|
|
581
613
|
if (row.verdict === "below-floor") {
|
|
582
614
|
return `PEER FLOOR VIOLATED: ${shell}@${shellVersion} requires ${row.name}@${row.range}, but ${row.installed} is installed. A peer floor encodes a wire contract \u2014 bump the dependency, do not widen the floor. A caret on a 0.x version is minor-locked (^0.36.0 can never resolve to 0.38.0), so reinstalling alone will not fix this: change the pin, in EVERY place it appears including pnpm.overrides.`;
|
|
583
615
|
}
|
|
584
616
|
return `${row.name} is a declared dependency of this app, but no installed version could be read, so its peer floor ${row.range} went UNCHECKED. Failing loudly rather than reporting a pass this guard did not earn.`;
|
|
585
617
|
}
|
|
586
|
-
function formatPeerFloorReport(report, shell =
|
|
618
|
+
function formatPeerFloorReport(report, shell = report.shell) {
|
|
587
619
|
const width = Math.max(...report.rows.map((r) => r.name.length), 4);
|
|
588
620
|
const lines = [
|
|
589
621
|
`${shell}@${report.shellVersion} \u2014 peer floors`,
|
|
@@ -604,7 +636,8 @@ export {
|
|
|
604
636
|
formatDependencySourceReport,
|
|
605
637
|
satisfiesRange,
|
|
606
638
|
checkPeerFloors,
|
|
639
|
+
checkAllPeerFloors,
|
|
607
640
|
describePeerFloorViolation,
|
|
608
641
|
formatPeerFloorReport
|
|
609
642
|
};
|
|
610
|
-
//# sourceMappingURL=chunk-
|
|
643
|
+
//# sourceMappingURL=chunk-BOQ4HVVH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/peer-floors/check.ts","../src/peer-floors/dependency-source.ts"],"sourcesContent":["import { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/**\n * The second half of this gate lives in `./dependency-source` and ships on the\n * SAME subpath and the SAME `agent-app-peer-check` bin, because it answers the\n * question underneath this one: a floor comparison reads a version, and a\n * version is not an identity — a vendored `pnpm pack` of an unmerged branch\n * carries the same `0.45.33` a real release does.\n */\nexport * from './dependency-source'\n\n/**\n * Audit a consumer's installed tree against the peer floors this package\n * declares.\n *\n * A peer floor is not documentation — it encodes a WIRE CONTRACT, and breaking\n * one is invisible to every other gate. `pnpm` only WARNS on an unmet peer when\n * the package is also a direct dependency, and says nothing at all for an unmet\n * OPTIONAL peer, which is how most of the substrate is declared here. So a\n * product can sit below a floor with a clean install, a clean typecheck, a green\n * suite and a successful deploy, and fail only on a live wire call:\n *\n * `@tangle-network/sandbox` 0.15.0 → 0.15.1 changed the sidecar spawn body\n * from `{ command }` to `{ executable, args }`. Below the floor, every\n * `box.exec()` on a live sandbox returns 400 `Unrecognized key: \"command\"`.\n *\n * `@tangle-network/agent-interface` 0.38.0 changed MCP config values from\n * plain strings to tagged public/secret-ref objects. Below the floor, this\n * package fails at MODULE LOAD with \"does not provide an export named\n * defineAgentProfilePublicConfig\" — while `tsc` reports zero errors, because\n * the types resolve and only the runtime export is missing.\n *\n * That second shape is why this exists as its own gate: typecheck cannot see it,\n * and a suite only sees it as dozens of unrelated-looking import failures.\n */\n\n/** Installed, and inside the declared range. */\nexport type PeerFloorVerdict =\n | 'satisfied'\n /** Installed and BELOW the floor — the silent case this module exists for. */\n | 'below-floor'\n /** Not installed and never asked for. A legitimate answer for an optional peer. */\n | 'absent-unused'\n /** Declared by the app, yet no version could be read, so the floor went\n * UNCHECKED. Reported as a failure rather than a pass this did not earn. */\n | 'absent-but-declared'\n\nexport interface PeerFloorRow {\n readonly name: string\n readonly range: string\n readonly installed: string | null\n readonly verdict: PeerFloorVerdict\n}\n\nexport interface PeerFloorReport {\n readonly shell: string\n readonly shellVersion: string\n readonly rows: readonly PeerFloorRow[]\n readonly violations: readonly PeerFloorRow[]\n readonly ok: boolean\n}\n\nexport interface CheckPeerFloorsOptions {\n /** Directory of the app under audit — the one whose `package.json` and\n * installed tree are read. */\n appDir: string\n /** Package whose peer floors are the contract. Defaults to this shell. */\n shell?: string\n /** Only audit peers under this scope. Third-party peers (react, drizzle) are\n * the app's own business, not part of the Tangle wire contract. Pass `''` to\n * audit every peer. */\n scope?: string\n /** Floors to audit against, when the shell is not resolvable from `appDir` —\n * the package auditing ITSELF, which has no copy of itself in its own\n * `node_modules`. Without this a package cannot check that the contract it\n * publishes is one its own dev install satisfies. */\n shellManifest?: { version?: string; peerDependencies?: Record<string, string> }\n /** Directory name to walk for installed packages. Overridable so a test can\n * point at a committed fixture tree — `node_modules` is gitignored\n * everywhere, so a fixture using that name could not be committed, and a\n * calibration proof that is not committed is a proof that stops running. */\n modulesDir?: string\n}\n\nexport type CheckAllPeerFloorsOptions = Pick<\n CheckPeerFloorsOptions,\n 'appDir' | 'modulesDir' | 'scope'\n>\n\nfunction installedPackageNames(\n appDir: string,\n modulesDir: string,\n scope: string,\n): readonly string[] {\n const modulesRoot = join(appDir, modulesDir)\n if (!existsSync(modulesRoot)) return []\n if (scope !== '') {\n const scopeDir = join(modulesRoot, scope.slice(0, -1))\n return existsSync(scopeDir)\n ? readdirSync(scopeDir).sort().map((name) => `${scope}${name}`)\n : []\n }\n\n return readdirSync(modulesRoot)\n .filter((name) => !name.startsWith('.'))\n .flatMap((name) => name.startsWith('@')\n ? readdirSync(join(modulesRoot, name)).map((child) => `${name}/${child}`)\n : [name])\n .sort()\n}\n\n/**\n * Read a package's manifest off disk, walking `modulesDir` up from `fromDir`.\n *\n * Deliberately NOT `require.resolve('<name>/package.json')`: most of these\n * packages omit `./package.json` from their `exports` map, so that throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED — and a try/catch around it reports an INSTALLED\n * package as absent, turning the whole audit into a silent no-op. Walking the\n * tree is exports-map-independent and mirrors Node's own resolution order, so\n * the version reported is the version that would actually load.\n *\n * The walk STOPS at the repository root — a directory containing `.git` — and\n * never climbs past it. Node itself would keep going, but a `node_modules`\n * above a checkout belongs to something else entirely, and letting it answer\n * silently changes the verdict: a stray `/tmp/node_modules` shadowing one\n * package produced a confident FAIL for a repo that was above every floor. A\n * check that reports the wrong tree is worse than no check.\n *\n * Returns null only when no directory for the package exists inside the repo,\n * which is the genuine not-installed case.\n */\nfunction readInstalledManifest(\n name: string,\n fromDir: string,\n modulesDir: string,\n): { version?: string; peerDependencies?: Record<string, string> } | null {\n let dir = fromDir\n for (;;) {\n const manifest = join(dir, modulesDir, name, 'package.json')\n if (existsSync(manifest)) {\n return JSON.parse(readFileSync(manifest, 'utf8')) as {\n version?: string\n peerDependencies?: Record<string, string>\n }\n }\n // Repo boundary: stop here rather than inheriting an unrelated tree.\n if (existsSync(join(dir, '.git'))) return null\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Minimal range satisfaction for the ranges peer floors actually use:\n * `>=x <y`, `^x.y.z`, `~x.y.z`, `x.y.z`, and `*`/`x`.\n *\n * Hand-rolled rather than taking a `semver` dependency, because this package\n * ships zero runtime dependencies and a checker that forces one on every\n * consumer is a worse trade than 40 lines of comparison. Prerelease versions\n * compare by their release part — a floor is about the wire contract, and a\n * prerelease of a satisfying version speaks it.\n */\nfunction parseVersion(version: string): [number, number, number] {\n const [core] = version.split(/[-+]/)\n const parts = (core ?? '').split('.').map((p) => Number.parseInt(p, 10))\n return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0]\n}\n\nfunction compare(a: string, b: string): number {\n const va = parseVersion(a)\n const vb = parseVersion(b)\n for (let i = 0; i < 3; i += 1) {\n if (va[i]! !== vb[i]!) return va[i]! < vb[i]! ? -1 : 1\n }\n return 0\n}\n\nfunction satisfiesComparator(version: string, comparator: string): boolean {\n const trimmed = comparator.trim()\n if (!trimmed || trimmed === '*' || trimmed === 'x') return true\n const match = /^(>=|<=|>|<|=|\\^|~)?\\s*v?(.+)$/.exec(trimmed)\n if (!match) return false\n const [, op = '=', target = ''] = match\n const cmp = compare(version, target)\n switch (op) {\n case '>=': return cmp >= 0\n case '<=': return cmp <= 0\n case '>': return cmp > 0\n case '<': return cmp < 0\n case '=': return cmp === 0\n case '~': {\n // ~1.2.3 allows patch bumps; ~1.2 allows minor.\n const [major, minor] = parseVersion(target)\n const [vMajor, vMinor] = parseVersion(version)\n return cmp >= 0 && vMajor === major && vMinor === minor\n }\n case '^': {\n // A caret on a 0.x version is MINOR-locked: ^0.36.0 can never resolve to\n // 0.38.0. That is the single most common reason a floor cannot be met by\n // reinstalling, so it is modelled exactly rather than approximated.\n const [major, minor] = parseVersion(target)\n const [vMajor, vMinor] = parseVersion(version)\n if (cmp < 0) return false\n if (major > 0) return vMajor === major\n if (minor > 0) return vMajor === 0 && vMinor === minor\n return vMajor === 0 && vMinor === 0\n }\n default: return false\n }\n}\n\nexport function satisfiesRange(version: string, range: string): boolean {\n // `||` is alternation; whitespace inside an alternative is conjunction.\n return range.split('||').some((alternative) =>\n alternative.trim().split(/\\s+/).filter(Boolean).every((c) => satisfiesComparator(version, c)),\n )\n}\n\n/** Audit one app directory against the shell's declared peer floors. */\nexport function checkPeerFloors(options: CheckPeerFloorsOptions): PeerFloorReport {\n const {\n appDir,\n shell = '@tangle-network/agent-app',\n scope = '@tangle-network/',\n modulesDir = 'node_modules',\n } = options\n\n const shellManifest = options.shellManifest ?? readInstalledManifest(shell, appDir, modulesDir)\n if (!shellManifest) throw new Error(`${shell} is not installed under ${appDir}`)\n\n const appManifest = JSON.parse(readFileSync(join(appDir, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n optionalDependencies?: Record<string, string>\n }\n const declared = {\n ...appManifest.dependencies,\n ...appManifest.devDependencies,\n ...appManifest.optionalDependencies,\n }\n\n const floors = Object.entries(shellManifest.peerDependencies ?? {})\n .filter(([name]) => name.startsWith(scope))\n\n const rows = floors.map(([name, range]): PeerFloorRow => {\n const installed = readInstalledManifest(name, appDir, modulesDir)?.version ?? null\n if (installed === null) {\n return { name, range, installed, verdict: declared[name] ? 'absent-but-declared' : 'absent-unused' }\n }\n return {\n name,\n range,\n installed,\n verdict: satisfiesRange(installed, range) ? 'satisfied' : 'below-floor',\n }\n })\n\n const violations = rows.filter((row) => row.verdict === 'below-floor' || row.verdict === 'absent-but-declared')\n return {\n shell,\n shellVersion: shellManifest.version ?? 'unknown',\n rows,\n violations,\n ok: violations.length === 0,\n }\n}\n\n/** Audit every installed package in `scope` that constrains another package in\n * that scope. This is the complete stack check the CLI runs for consumers. */\nexport function checkAllPeerFloors(options: CheckAllPeerFloorsOptions): readonly PeerFloorReport[] {\n const {\n appDir,\n modulesDir = 'node_modules',\n scope = '@tangle-network/',\n } = options\n const normalizedScope = scope === '' ? '' : scope.endsWith('/') ? scope : `${scope}/`\n const shells = installedPackageNames(appDir, modulesDir, normalizedScope)\n .filter((name) => {\n const manifest = readInstalledManifest(name, appDir, modulesDir)\n return Object.keys(manifest?.peerDependencies ?? {})\n .some((peer) => peer.startsWith(normalizedScope))\n })\n\n if (shells.length === 0) {\n const label = normalizedScope || 'package'\n throw new Error(`no installed ${label} package declares a ${label} peer under ${appDir}`)\n }\n\n return shells.map((shell) => checkPeerFloors({\n appDir,\n modulesDir,\n scope: normalizedScope,\n shell,\n }))\n}\n\n/** The failure message for one violating row. Split out so a caller can raise\n * it from a test and a CLI can print it identically. */\nexport function describePeerFloorViolation(row: PeerFloorRow, shellVersion: string, shell = '@tangle-network/agent-app'): string {\n if (row.verdict === 'below-floor') {\n return `PEER FLOOR VIOLATED: ${shell}@${shellVersion} requires ${row.name}@${row.range}, `\n + `but ${row.installed} is installed. A peer floor encodes a wire contract — bump the `\n + `dependency, do not widen the floor. A caret on a 0.x version is minor-locked `\n + `(^0.36.0 can never resolve to 0.38.0), so reinstalling alone will not fix this: `\n + `change the pin, in EVERY place it appears including pnpm.overrides.`\n }\n return `${row.name} is a declared dependency of this app, but no installed version could be `\n + `read, so its peer floor ${row.range} went UNCHECKED. Failing loudly rather than `\n + `reporting a pass this guard did not earn.`\n}\n\nexport function formatPeerFloorReport(report: PeerFloorReport, shell = report.shell): string {\n const width = Math.max(...report.rows.map((r) => r.name.length), 4)\n const lines = [\n `${shell}@${report.shellVersion} — peer floors`,\n '',\n ...report.rows.map((row) =>\n ` ${row.verdict === 'satisfied' ? 'ok ' : row.verdict.startsWith('absent') ? '-- ' : 'FAIL'} `\n + `${row.name.padEnd(width)} installed ${(row.installed ?? '(none)').padEnd(10)} floor ${row.range}`),\n '',\n report.ok\n ? `all ${report.rows.length} floors satisfied`\n : report.violations.map((row) => describePeerFloorViolation(row, report.shellVersion, shell)).join('\\n\\n'),\n ]\n return lines.join('\\n')\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, lstatSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\n\n/**\n * Audit where a repository's dependencies COME FROM.\n *\n * `/peer-floors` already answers \"is the installed version inside the declared\n * range\". This answers the question underneath it — \"is the installed package\n * the one the registry publishes at all\" — because a version number is not an\n * identity. Two artifacts can carry `0.45.33` and ship different APIs, and every\n * gate that reads a version reads the same number for both.\n *\n * THE MEASURED DEFECT. insurance-agent's `pnpm-workspace.yaml` carried\n *\n * overrides:\n * '@tangle-network/agent-app': file:./vendor/agent-app/tangle-network-agent-app-0.45.33.tgz\n *\n * — a 2.6 MB `pnpm pack` of an UNMERGED pull request, committed into the\n * product repo (`insurance-agent` f7d0f51 removed it). It installed cleanly,\n * typechecked green and passed sign-off while the product ran code that existed\n * in no published release. Note where it was NOT: `package.json` still read\n * `\"@tangle-network/agent-app\": \"^0.45.33\"`, a perfectly ordinary registry\n * range. A check that reads only the root manifest's `dependencies` sees\n * nothing. The override lane is the one that shipped, so the override lane —\n * `pnpm-workspace.yaml`, `pnpm.overrides`, `resolutions` — is audited first.\n *\n * The second shape is worse because nothing declares it at all: a worktree was\n * found whose installed `agent-app@0.45.29` had `dist/spend/index.d.ts`\n * replaced with a newer version's content by hand. The manifest, the lockfile\n * and the version on disk all agreed; only the bytes disagreed, and the product\n * typechecked green against an API its declared dependency does not ship. See\n * `checkInstalledIntegrity` below for exactly how much of that class is\n * catchable cheaply and exactly how much is not.\n */\n\n/** How a specifier says a dependency should be obtained. */\nexport type DependencySourceProtocol =\n /** Resolvable from the registry by anyone: `^1.2.3`, `1.2.3`, `npm:x@1`. */\n | 'registry'\n /** `workspace:` — another package in this same repo. Reviewable in one diff. */\n | 'workspace'\n /** `catalog:` — indirection into `pnpm-workspace.yaml`, which is itself audited. */\n | 'catalog'\n /** A local path. Whether it is legitimate depends on WHERE it points. */\n | 'file'\n | 'link'\n | 'portal'\n /** A path or URL ending in a packed tarball. Opaque bytes; never legitimate. */\n | 'tarball'\n /** A git ref or a remote URL that is not the registry. */\n | 'git'\n | 'remote'\n\nconst TARBALL = /\\.(?:tgz|tar\\.gz)$/i\n\n/**\n * Classify one dependency specifier by the SOURCE it names.\n *\n * Pure and exported so a consumer can reuse the vocabulary, and so the rule can\n * be tested without a filesystem. Nothing here decides legitimacy — `file:` on\n * a directory inside the repo is correct and `file:` on a tarball never is, and\n * that distinction needs the disk (`resolveLocalPathSource`).\n */\nexport function classifyDependencySpecifier(specifier: string): DependencySourceProtocol {\n const spec = specifier.trim()\n if (spec.startsWith('workspace:')) return 'workspace'\n if (spec.startsWith('catalog:')) return 'catalog'\n for (const protocol of ['file:', 'link:', 'portal:'] as const) {\n if (spec.startsWith(protocol)) {\n const path = spec.slice(protocol.length)\n if (TARBALL.test(path)) return 'tarball'\n return protocol.slice(0, -1) as 'file' | 'link' | 'portal'\n }\n }\n if (/^(?:git|git\\+ssh|git\\+https?|git\\+file|ssh):/.test(spec)) return 'git'\n if (/^(?:github|gitlab|bitbucket):/.test(spec)) return 'git'\n if (/^https?:\\/\\//.test(spec)) return TARBALL.test(spec.split(/[?#]/)[0] ?? '') ? 'tarball' : 'remote'\n // `owner/repo` and `owner/repo#ref` are npm's GitHub shorthand. A scoped\n // package name (`@scope/name`) also contains a slash, hence the leading-@ guard.\n if (/^[\\w.-]+\\/[\\w.-]+(?:#.+)?$/.test(spec) && !spec.startsWith('@')) return 'git'\n return 'registry'\n}\n\n/** A protocol that resolves from the registry, or from this repo's own sources. */\nfunction isReproducible(protocol: DependencySourceProtocol): boolean {\n return protocol === 'registry' || protocol === 'workspace' || protocol === 'catalog'\n}\n\n/**\n * The legitimate-exception rule, stated once so it is not a path allowlist.\n *\n * agent-app's own `playground/package.json` declares\n * `\"@tangle-network/agent-app\": \"file:..\"` and that is CORRECT: the playground\n * depends on the package it lives inside. The property that makes it correct is\n * not its path — it is that the dependency is satisfied by SOURCE ALREADY IN\n * THIS REPOSITORY, under version control, changing only in a diff a reviewer\n * sees. So the rule is:\n *\n * A `file:` / `link:` / `portal:` specifier is exempt when it resolves to a\n * DIRECTORY inside this repository holding a `package.json` whose `name` is\n * the dependency being declared.\n *\n * Every clause is load-bearing. A DIRECTORY, because a `.tgz` is opaque bytes\n * that no diff shows — a packed tarball is never exempt, wherever it sits.\n * INSIDE THIS REPOSITORY, because `file:../../agent-app` is a path on one\n * machine: it resolves for its author and for nobody else, and a sign-off gate\n * that installs into a clean export dies at install. NAME MATCHES, because a\n * path pointing at some other package's source is a mis-wire, not a\n * self-reference.\n */\nexport type LocalPathSource =\n /** In-repo directory whose package.json names this dependency. Legitimate. */\n | 'in-repo-source'\n /** Points outside the repository — reproducible on one machine only. */\n | 'outside-repo'\n /** Nothing there, or not a directory (a packed tarball lands here too). */\n | 'not-a-directory'\n /** An in-repo directory, but it is a different package. */\n | 'name-mismatch'\n\nexport function resolveLocalPathSource(args: {\n /** Directory of the manifest that made the declaration. */\n fromDir: string\n /** Root of the repository the declaration must stay inside. */\n repoDir: string\n /** The path part of the specifier, protocol already stripped. */\n path: string\n /** The dependency name the path is claimed to satisfy. */\n name: string\n}): LocalPathSource {\n const root = resolve(args.repoDir)\n const target = isAbsolute(args.path) ? resolve(args.path) : resolve(args.fromDir, args.path)\n if (target !== root && !target.startsWith(root + sep)) return 'outside-repo'\n const manifest = join(target, 'package.json')\n if (!existsSync(manifest) || !statSync(target).isDirectory()) return 'not-a-directory'\n let declared: string | undefined\n try {\n declared = (JSON.parse(readFileSync(manifest, 'utf8')) as { name?: string }).name\n } catch {\n return 'not-a-directory'\n }\n return declared === args.name ? 'in-repo-source' : 'name-mismatch'\n}\n\n/** Which of the five scans produced a finding. Kept on the row because the fix\n * differs: a declaration is edited, an installed tree is reinstalled. */\nexport type DependencySourceCheck =\n /** A `dependencies`-family field in some `package.json`. */\n | 'declared'\n /** `pnpm.overrides` / `resolutions` / `pnpm-workspace.yaml` — the lane that shipped. */\n | 'override'\n /** `pnpm-lock.yaml` — what actually resolved, whatever the manifests now say. */\n | 'lockfile'\n /** A packed tarball sitting in the source tree. */\n | 'vendored-tarball'\n /** The installed tree on disk. */\n | 'installed'\n\nexport interface DependencySourceFinding {\n readonly check: DependencySourceCheck\n /** Dependency name, or `null` for a stray tarball that names no dependency. */\n readonly name: string | null\n readonly specifier: string | null\n readonly protocol: DependencySourceProtocol | null\n /** Repo-relative location, with the key or line that carries it. */\n readonly where: string\n /** Why this is a finding, and what to do about it. */\n readonly detail: string\n}\n\n/**\n * What the on-disk integrity pass was able to examine — reported on EVERY run,\n * clean or not, because \"checked nothing\" and \"checked everything and found\n * nothing\" render identically otherwise. This module's own doctrine: an\n * unchecked contract is never a pass it did not earn.\n */\nexport interface InstalledIntegrityCoverage {\n /** The only basis implemented. See `checkInstalledIntegrity`'s limits. */\n readonly basis: 'store-cas'\n /** False for npm, yarn, a pruned CI cache, or a store on another machine.\n * Nothing was verified, and the report says so rather than reading clean. */\n readonly storeLocated: boolean\n readonly packagesExamined: number\n readonly filesExamined: number\n /** Files settled by reading their bytes rather than by a shared inode. */\n readonly filesHashed: number\n}\n\nexport interface DependencySourceReport {\n readonly repoDir: string\n readonly manifestsScanned: number\n readonly lockfileScanned: boolean\n readonly integrity: InstalledIntegrityCoverage\n readonly findings: readonly DependencySourceFinding[]\n readonly ok: boolean\n}\n\nexport interface CheckDependencySourcesOptions {\n /** Repository root to audit. */\n repoDir: string\n /** Scope filter for the on-disk integrity pass. `''` examines every package. */\n scope?: string\n /** Directory name holding the installed tree. Overridable so a committed\n * fixture can use `fixture_modules` — `node_modules` is gitignored\n * everywhere, and a calibration proof that is not committed stops running. */\n modulesDir?: string\n /** Repo-relative path prefixes the source-tree walk skips. The escape hatch\n * for a repo that genuinely carries a tarball as test data — and for this\n * package's own calibration fixtures, whose purpose is to CONTAIN the\n * violation. */\n exclude?: readonly string[]\n}\n\n/** Directories a source-tree walk must never descend into: build output and\n * installed packages are not declarations, and walking them turns a\n * sub-second scan into a minute. */\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', 'out', 'coverage',\n '.wrangler', '.react-router', '.next', '.turbo', '.cache', '.worktrees', 'storybook-static',\n])\n\nfunction walkSourceTree(\n dir: string,\n repoDir: string,\n exclude: readonly string[],\n seen: { manifests: string[]; tarballs: string[] },\n): void {\n let entries: import('node:fs').Dirent[]\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return\n }\n for (const entry of entries) {\n const full = join(dir, entry.name)\n const rel = relative(repoDir, full).split(sep).join('/')\n if (exclude.some((prefix) => rel === prefix || rel.startsWith(`${prefix}/`))) continue\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) continue\n walkSourceTree(full, repoDir, exclude, seen)\n } else if (entry.isFile()) {\n if (entry.name === 'package.json') seen.manifests.push(full)\n else if (TARBALL.test(entry.name)) seen.tarballs.push(full)\n }\n }\n}\n\n/* ---------------------------------------------------------------------------\n * A line reader for the two YAML files that matter.\n *\n * Deliberately not a YAML dependency: this package ships zero runtime deps and\n * forcing one on every consumer to read four block mappings is the worse trade\n * — the same call `/peer-floors` made about `semver`. The shapes read here are\n * `pnpm-workspace.yaml`'s `overrides`/`catalog`/`catalogs` and\n * `pnpm-lock.yaml`'s `overrides`/`importers`/`packages`/`snapshots`, all of\n * which pnpm emits as plain two-space block mappings of scalars.\n * ------------------------------------------------------------------------ */\n\ninterface YamlLine {\n readonly indent: number\n readonly key: string\n readonly value: string\n /** Enclosing keys, outermost first, excluding this line's own key. */\n readonly path: readonly string[]\n readonly lineNumber: number\n}\n\nfunction unquote(text: string): string {\n const t = text.trim()\n if ((t.startsWith(\"'\") && t.endsWith(\"'\")) || (t.startsWith('\"') && t.endsWith('\"'))) {\n return t.slice(1, -1)\n }\n return t\n}\n\nfunction readYamlLines(text: string): YamlLine[] {\n const out: YamlLine[] = []\n // Innermost key seen at each indent level, so a `specifier:` line can name\n // the dependency it belongs to.\n const stack: string[] = []\n text.split('\\n').forEach((raw, index) => {\n if (!raw.trim() || raw.trimStart().startsWith('#')) return\n const indent = raw.length - raw.trimStart().length\n const match = /^\\s*(?:'((?:[^']|'')*)'|\"([^\"]*)\"|([^\\s:#][^:]*?))\\s*:(?:\\s+(.*))?$/.exec(raw)\n if (!match) return\n const key = (match[1] ?? match[2] ?? match[3] ?? '').replace(/''/g, \"'\")\n // A trailing ` # comment` is a comment only outside quotes; every value pnpm\n // writes here is unquoted or fully quoted, so splitting on ` #` is exact.\n const rawValue = (match[4] ?? '').split(' #')[0] ?? ''\n const depth = Math.floor(indent / 2)\n stack.length = depth\n const path = [...stack]\n stack[depth] = key\n out.push({ indent, key, value: unquote(rawValue), path, lineNumber: index + 1 })\n })\n return out\n}\n\n/** The top-level section a nested line sits under. */\nfunction sectionOf(line: YamlLine): string | undefined {\n return line.indent === 0 ? line.key : line.path[0]\n}\n\n/* ------------------------------------------------------------------------ */\n\nconst DEP_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'] as const\n\n/**\n * Judge one declaration and produce a finding, or `null` when it is fine.\n *\n * One function so the manifest lane, the override lane and the lockfile lane\n * cannot drift into three different opinions about the same specifier.\n */\nfunction judge(args: {\n check: DependencySourceCheck\n name: string\n specifier: string\n where: string\n fromDir: string\n repoDir: string\n}): DependencySourceFinding | null {\n const protocol = classifyDependencySpecifier(args.specifier)\n if (isReproducible(protocol)) return null\n\n const base = { check: args.check, name: args.name, specifier: args.specifier, protocol, where: args.where }\n\n if (protocol === 'tarball') {\n return {\n ...base,\n detail: 'resolves a PACKED TARBALL, not a published release. A .tgz is opaque bytes that no '\n + 'diff shows and no registry can reproduce: the version inside it can collide with a real '\n + 'release and ship a different API. Publish the change and pin the published range.',\n }\n }\n if (protocol === 'git' || protocol === 'remote') {\n return {\n ...base,\n detail: `resolves from ${protocol === 'git' ? 'a git ref' : 'a remote URL'} rather than the `\n + 'registry, so what installs depends on what that ref points at today. Publish the change '\n + 'and pin the published range.',\n }\n }\n\n const path = args.specifier.slice(args.specifier.indexOf(':') + 1)\n const source = resolveLocalPathSource({ fromDir: args.fromDir, repoDir: args.repoDir, path, name: args.name })\n if (source === 'in-repo-source') return null\n const why: Record<Exclude<LocalPathSource, 'in-repo-source'>, string> = {\n 'outside-repo': 'points OUTSIDE this repository, so it resolves on one machine and nowhere else — '\n + 'a clean checkout, a CI runner and a sign-off gate that installs into an exported tree all '\n + 'get a different answer or fail at install.',\n 'not-a-directory': 'does not resolve to a package directory in this repository. A local specifier '\n + 'is only legitimate when it points at in-repo SOURCE a reviewer sees in the diff.',\n 'name-mismatch': `resolves to an in-repo directory that declares a DIFFERENT package name, so the `\n + `dependency ${args.name} is being satisfied by something else entirely.`,\n }\n return { ...base, detail: `${why[source]} (${source})` }\n}\n\nfunction scanManifest(file: string, repoDir: string): DependencySourceFinding[] {\n let manifest: Record<string, unknown>\n try {\n manifest = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>\n } catch {\n return []\n }\n const fromDir = dirname(file)\n const where = relative(repoDir, file).split(sep).join('/') || 'package.json'\n const findings: DependencySourceFinding[] = []\n\n for (const field of DEP_FIELDS) {\n const block = manifest[field]\n if (!block || typeof block !== 'object') continue\n for (const [name, specifier] of Object.entries(block as Record<string, unknown>)) {\n if (typeof specifier !== 'string') continue\n const finding = judge({ check: 'declared', name, specifier, where: `${where} → ${field}`, fromDir, repoDir })\n if (finding) findings.push(finding)\n }\n }\n\n // The lane insurance's defect actually used. `resolutions` is yarn/npm's\n // spelling of the same authority; both silently outrank every range above.\n const overrideBlocks: Array<[string, unknown]> = [\n ['pnpm.overrides', (manifest.pnpm as { overrides?: unknown } | undefined)?.overrides],\n ['resolutions', manifest.resolutions],\n ]\n for (const [label, block] of overrideBlocks) {\n if (!block || typeof block !== 'object') continue\n for (const [name, specifier] of Object.entries(block as Record<string, unknown>)) {\n if (typeof specifier !== 'string') continue\n const finding = judge({\n check: 'override',\n // An override key can carry a range suffix (`foo@1 > bar`); the package\n // name is the leading segment.\n name: overrideKeyName(name),\n specifier,\n where: `${where} → ${label}['${name}']`,\n fromDir,\n repoDir,\n })\n if (finding) findings.push(finding)\n }\n }\n return findings\n}\n\n/** `@scope/pkg@^1 > dep` and `pkg@1` both name `pkg` / `@scope/pkg`. */\nfunction overrideKeyName(key: string): string {\n const head = (key.split('>').pop() ?? key).trim()\n const at = head.lastIndexOf('@')\n return at > 0 ? head.slice(0, at) : head\n}\n\nfunction scanWorkspaceYaml(file: string, repoDir: string): DependencySourceFinding[] {\n const findings: DependencySourceFinding[] = []\n const where = relative(repoDir, file).split(sep).join('/')\n for (const line of readYamlLines(readFileSync(file, 'utf8'))) {\n const section = sectionOf(line)\n if (section !== 'overrides' && section !== 'catalog' && section !== 'catalogs') continue\n if (line.indent === 0 || !line.value) continue\n const finding = judge({\n check: 'override',\n name: overrideKeyName(line.key),\n specifier: line.value,\n where: `${where}:${line.lineNumber} → ${[...line.path, line.key].join('.')}`,\n fromDir: dirname(file),\n repoDir,\n })\n if (finding) findings.push(finding)\n }\n return findings\n}\n\n/**\n * The lockfile is the only file that reports what ACTUALLY resolved. A manifest\n * can be cleaned up while `pnpm-lock.yaml` still resolves a tarball, and the\n * install follows the lockfile.\n *\n * Three shapes carry it, all present in the real insurance-agent lockfile:\n * overrides: '@tangle-network/agent-app': file:./vendor/…-0.45.33.tgz\n * importers: specifier: file:vendor/…-0.45.33.tgz\n * packages: '@tangle-network/agent-app@file:vendor/…-0.45.33.tgz':\n */\nfunction scanLockfile(file: string, repoDir: string): DependencySourceFinding[] {\n const findings: DependencySourceFinding[] = []\n const where = relative(repoDir, file).split(sep).join('/')\n const fromDir = dirname(file)\n const seen = new Set<string>()\n const push = (finding: DependencySourceFinding | null): void => {\n if (!finding) return\n const key = `${finding.name}|${finding.specifier}`\n if (seen.has(key)) return\n seen.add(key)\n findings.push(finding)\n }\n\n for (const line of readYamlLines(readFileSync(file, 'utf8'))) {\n const section = sectionOf(line)\n if (section === 'overrides' && line.indent > 0 && line.value) {\n push(judge({\n check: 'lockfile',\n name: overrideKeyName(line.key),\n specifier: line.value,\n where: `${where}:${line.lineNumber} → overrides`,\n fromDir,\n repoDir,\n }))\n continue\n }\n if (section === 'importers' && line.key === 'specifier' && line.value) {\n push(judge({\n check: 'lockfile',\n name: line.path[line.path.length - 1] ?? '(unknown)',\n specifier: line.value,\n where: `${where}:${line.lineNumber} → importers`,\n fromDir,\n repoDir,\n }))\n continue\n }\n if ((section === 'packages' || section === 'snapshots') && line.indent === 2 && !line.value) {\n const parsed = parsePackageKey(line.key)\n if (!parsed) continue\n push(judge({\n check: 'lockfile',\n name: parsed.name,\n specifier: parsed.reference,\n where: `${where}:${line.lineNumber} → ${section}`,\n fromDir,\n repoDir,\n }))\n }\n }\n return findings\n}\n\n/**\n * `'@scope/name@file:vendor/x.tgz'` → name + reference.\n *\n * The peer-suffix is stripped FIRST: a snapshot key looks like\n * `@radix-ui/react-dialog@1.1.23(@types/react@19.2.17)`, and the last `@` in\n * that string sits inside the suffix, not at the version boundary.\n */\nfunction parsePackageKey(key: string): { name: string; reference: string } | null {\n const withoutPeers = key.replace(/\\(.*\\)$/, '')\n const at = withoutPeers.lastIndexOf('@')\n if (at <= 0) return null\n return { name: withoutPeers.slice(0, at), reference: withoutPeers.slice(at + 1) }\n}\n\n/**\n * pnpm's virtual store encodes a dependency's SOURCE in the directory name:\n * a registry package is `@tangle-network+agent-app@0.45.33`, while the\n * vendored one installed as\n * `file+vendor+agent-app+tangle-network-agent-app-0.45.33.tgz`.\n *\n * This is install evidence that survives a tidied manifest and a regenerated\n * lockfile, which is why it is scanned separately rather than trusted to follow\n * from them.\n */\nfunction scanVirtualStore(\n repoDir: string,\n modulesDir: string,\n): DependencySourceFinding[] {\n const store = join(repoDir, modulesDir, '.pnpm')\n if (!existsSync(store)) return []\n const findings: DependencySourceFinding[] = []\n for (const entry of readdirSync(store, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name === modulesDir) continue\n const protocolMatch = /^(file|link|portal|git|https?)\\+/.exec(entry.name)\n if (!protocolMatch) continue\n const protocol = protocolMatch[1] as string\n // pnpm encodes `/` as `+` for the whole remainder of a path-protocol key.\n const encoded = entry.name.slice(protocol.length + 1)\n const name = installedPackageName(join(store, entry.name), modulesDir)\n const where = `${modulesDir}/.pnpm/${entry.name}`\n\n if (protocol === 'file' || protocol === 'link' || protocol === 'portal') {\n const path = encoded.split('+').join('/')\n const specifier = `${protocol}:${path}`\n const finding = judge({\n check: 'installed',\n name: name ?? path,\n specifier,\n where,\n // A virtual-store path is written relative to the install root.\n fromDir: repoDir,\n repoDir,\n })\n if (finding) findings.push(finding)\n continue\n }\n findings.push({\n check: 'installed',\n name,\n specifier: encoded.split('+++').join('://').split('+').join('/'),\n protocol: protocol === 'git' ? 'git' : 'remote',\n where,\n detail: 'is INSTALLED from a git ref or remote URL rather than the registry. The manifests may '\n + 'read clean — this is what the tree on disk actually holds. Reinstall from a published range.',\n })\n }\n return findings\n}\n\n/**\n * The package a virtual-store entry belongs to: the one REAL directory under\n * its nested module dir (its dependencies are all symlinks).\n *\n * The nested level takes `modulesDir` too, not a hardcoded `node_modules`.\n * In a real install both levels ARE `node_modules`, so nothing changes there —\n * but a COMMITTED fixture cannot carry a `node_modules` path segment at any\n * depth, because every repo gitignores that name. Hardcoding it here made this\n * module's own calibration tree un-committable, which is the failure the\n * `fixture_modules` convention exists to prevent, reintroduced one level down.\n */\nfunction installedPackageName(entryDir: string, modulesDir: string): string | null {\n const nested = join(entryDir, modulesDir)\n if (!existsSync(nested)) return null\n for (const child of readdirSync(nested, { withFileTypes: true })) {\n if (child.name === '.bin' || child.isSymbolicLink()) continue\n if (!child.isDirectory()) continue\n if (child.name.startsWith('@')) {\n const scopeDir = join(nested, child.name)\n for (const scoped of readdirSync(scopeDir, { withFileTypes: true })) {\n if (scoped.isSymbolicLink() || !scoped.isDirectory()) continue\n if (existsSync(join(scopeDir, scoped.name, 'package.json'))) return `${child.name}/${scoped.name}`\n }\n continue\n }\n if (existsSync(join(nested, child.name, 'package.json'))) return child.name\n }\n return null\n}\n\n/* ---------------------------------------------------------------------------\n * On-disk integrity — and an honest account of its ceiling.\n *\n * WHAT WAS CONSIDERED AND REJECTED. Full verification means comparing the\n * installed bytes against the PUBLISHED tarball. `pnpm-lock.yaml` records that\n * tarball's `integrity` (`sha512-…`) and nothing about its contents, and the\n * tarball is not on disk: pnpm unpacks into a content-addressed store and keeps\n * the per-file digests in an INDEX whose location and format change between\n * pnpm majors — pnpm 10 writes JSON under `store/v10/index/`, pnpm 11 writes one\n * SQLite database (measured: `~/.local/share/pnpm/store/v11/index.db`, 57 MB).\n * Reading it means a SQLite dependency plus a coupling to store internals, in a\n * package that ships zero runtime dependencies; re-fetching the tarball means\n * network access inside a gate that must run offline in seconds. So full\n * verification is NOT affordable and is not attempted.\n *\n * WHAT IS AFFORDABLE. The store is CONTENT-ADDRESSED: a file's bytes live at\n * `<store>/files/<first 2 hex>/<rest>` of their own sha512, a layout that has\n * survived v3 → v10 → v11 while the index format changed twice. So a file's\n * bytes can be asked one question with no dependency and no network — \"has this\n * store ever held these bytes?\" Bytes that came out of a package pnpm installed\n * are in there by construction. Bytes typed in afterwards are not.\n *\n * Two steps, because hashing 30,000 files per run would not be cheap:\n * 1. `nlink > 1` — the file shares an inode, so it IS a store blob. No hash.\n * This settles ~99% of files at the cost of one `lstat`.\n * 2. Everything else is hashed and looked up in the store CAS.\n *\n * THE HARD-LINK COUNT ALONE IS NOT THE SIGNAL, and believing it was is the\n * mistake this design corrects. An earlier cut reported any package holding\n * both linked and unlinked files as tampered. Measured across five real fleet\n * repos it fired once — on legal-agent's `@tangle-network/agent-interface@0.32.0`,\n * whose `dist/environment-provider.js` is `nlink == 1` — and that finding was\n * FALSE: `npm pack @tangle-network/agent-interface@0.32.0` yields the identical\n * 11-byte `export {};`. pnpm simply wrote that copy instead of linking it. A\n * 1-in-5-repos false alarm is a gate people switch off, and the CAS lookup is\n * what tells the two apart: those bytes ARE in the store.\n *\n * MEASURED after adding the lookup: 5 fleet repos, 0 findings, 0 false alarms.\n *\n * WHAT IT CANNOT CATCH, precisely — do not read a clean integrity line as more:\n * 1. A patch whose content came from ANOTHER package or version ALREADY in\n * this store. CAS membership proves \"this store has held these bytes\", not\n * \"these bytes belong to this package at this version\". The measured\n * defect — a `dist/spend/index.d.ts` overwritten with a NEWER version's\n * copy — is caught only when that newer version was never installed on the\n * machine. This is the real ceiling; closing it needs the per-file index.\n * 2. An edit that PRESERVES the inode (`> file`, `cp onto`). The link\n * survives and the STORE copy is corrupted with it, so both agree.\n * 3. A tampered store: everything resolves, everything agrees, all wrong.\n * 4. Anything at all when the store cannot be located — npm, yarn, a store on\n * another machine, a pruned CI cache. That is reported as NOT VERIFIED\n * rather than as a pass, and it is never a finding, because failing every\n * non-pnpm consumer forever is how a gate gets deleted.\n * ------------------------------------------------------------------------ */\n\n/**\n * Every content-addressed `files/` directory this install could have linked\n * from, read out of `node_modules/.modules.yaml` — pure `fs`, no `pnpm store\n * path` subprocess.\n *\n * More than one, because a long-lived machine has several store majors side by\n * side and an existing tree can be linked from an older one: measured on\n * legal-agent, `dist/index.js` resolves in `store/v10/files` while\n * `dist/environment-provider.js` resolves in `store/v10/v11/files`. Checking\n * only the configured one reports a linked file as unknown.\n */\nfunction locateStoreCas(repoDir: string, modulesDir: string): string[] {\n const modulesState = join(repoDir, modulesDir, '.modules.yaml')\n if (!existsSync(modulesState)) return []\n let configured: string | undefined\n try {\n const text = readFileSync(modulesState, 'utf8')\n // pnpm 11 writes JSON under the .yaml name; older versions write YAML.\n configured = (/\"storeDir\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/.exec(text)?.[1]\n ?? /^storeDir:\\s*(.+)$/m.exec(text)?.[1])?.trim()\n } catch {\n return []\n }\n if (!configured) return []\n const root = unquote(configured.replace(/\\\\\\\\/g, '\\\\'))\n const candidates = new Set<string>([root, dirname(root)])\n for (const base of [root, dirname(root)]) {\n try {\n for (const entry of readdirSync(base, { withFileTypes: true })) {\n if (entry.isDirectory() && /^v\\d+$/.test(entry.name)) candidates.add(join(base, entry.name))\n }\n } catch { /* an unreadable store is simply not a candidate */ }\n }\n return [...candidates].map((dir) => join(dir, 'files')).filter((dir) => existsSync(dir))\n}\n\nfunction collectFiles(dir: string, modulesDir: string, out: string[] = []): string[] {\n let entries: import('node:fs').Dirent[]\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return out\n }\n for (const entry of entries) {\n // A package's own nested `node_modules` holds pnpm-GENERATED `.bin` shims\n // and symlinks, never store content. Including it made 3 of this repo's 8\n // installed @tangle-network packages look partially replaced.\n if (entry.name === modulesDir) continue\n const full = join(dir, entry.name)\n if (entry.isSymbolicLink()) continue\n if (entry.isDirectory()) collectFiles(full, modulesDir, out)\n else if (entry.isFile()) out.push(full)\n }\n return out\n}\n\n/** Does any reachable store hold these exact bytes? `-exec` is pnpm's suffix\n * for the executable-mode copy of the same content. */\nfunction storeHolds(casDirs: readonly string[], bytes: Buffer): boolean {\n const hex = createHash('sha512').update(bytes).digest('hex')\n const tail = join(hex.slice(0, 2), hex.slice(2))\n return casDirs.some((dir) => existsSync(join(dir, tail)) || existsSync(join(dir, `${tail}-exec`)))\n}\n\n/**\n * Check each installed package under `scope` against the content-addressed\n * store it was installed from. Returns coverage alongside findings, because a\n * pass that verified nothing must not render like a pass that verified\n * everything.\n */\nexport function checkInstalledIntegrity(args: {\n repoDir: string\n modulesDir: string\n scope: string\n}): { coverage: InstalledIntegrityCoverage; findings: DependencySourceFinding[] } {\n const virtualStore = join(args.repoDir, args.modulesDir, '.pnpm')\n const casDirs = locateStoreCas(args.repoDir, args.modulesDir)\n const findings: DependencySourceFinding[] = []\n let packagesExamined = 0\n let filesExamined = 0\n let filesHashed = 0\n\n if (casDirs.length > 0 && existsSync(virtualStore)) {\n for (const entry of readdirSync(virtualStore, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name === args.modulesDir) continue\n const entryDir = join(virtualStore, entry.name)\n const name = installedPackageName(entryDir, args.modulesDir)\n if (!name || !name.startsWith(args.scope)) continue\n const packageDir = join(entryDir, args.modulesDir, name)\n if (!existsSync(packageDir)) continue\n\n const files = collectFiles(packageDir, args.modulesDir)\n if (files.length === 0) continue\n packagesExamined += 1\n filesExamined += files.length\n\n const foreign: string[] = []\n for (const file of files) {\n try {\n // A shared inode IS a store blob — settled without reading the file.\n if (lstatSync(file).nlink > 1) continue\n filesHashed += 1\n if (storeHolds(casDirs, readFileSync(file))) continue\n foreign.push(relative(packageDir, file).split(sep).join('/'))\n } catch { /* a file that vanished mid-walk is not evidence */ }\n }\n if (foreign.length === 0) continue\n\n const shown = foreign.slice(0, 5)\n findings.push({\n check: 'installed',\n name,\n specifier: null,\n protocol: null,\n where: `${args.modulesDir}/.pnpm/${entry.name} → ${shown.join(', ')}`\n + `${foreign.length > shown.length ? ` (+${foreign.length - shown.length} more)` : ''}`,\n detail: `holds ${foreign.length} file(s) whose bytes this pnpm store has never contained — the `\n + 'shape of a package HAND-PATCHED after install. The version on disk, the manifest and the '\n + 'lockfile all still agree; only the bytes do not, which is how a product typechecks green '\n + 'against an API its declared dependency does not ship. Delete the tree and reinstall '\n + `(\\`rm -rf ${args.modulesDir} && pnpm install --frozen-lockfile\\`), then publish whatever `\n + 'change made the patch look necessary.',\n })\n }\n }\n\n return {\n coverage: {\n basis: 'store-cas',\n storeLocated: casDirs.length > 0,\n packagesExamined,\n filesExamined,\n filesHashed,\n },\n findings,\n }\n}\n\n/** Audit one repository for dependencies whose source is not the registry. */\nexport function checkDependencySources(options: CheckDependencySourcesOptions): DependencySourceReport {\n const repoDir = resolve(options.repoDir)\n const { scope = '@tangle-network/', modulesDir = 'node_modules', exclude = [] } = options\n\n const seen = { manifests: [] as string[], tarballs: [] as string[] }\n walkSourceTree(repoDir, repoDir, exclude, seen)\n\n const findings: DependencySourceFinding[] = []\n for (const manifest of seen.manifests) findings.push(...scanManifest(manifest, repoDir))\n\n const workspaceYaml = join(repoDir, 'pnpm-workspace.yaml')\n if (existsSync(workspaceYaml)) findings.push(...scanWorkspaceYaml(workspaceYaml, repoDir))\n\n const lockfile = join(repoDir, 'pnpm-lock.yaml')\n const lockfileScanned = existsSync(lockfile)\n if (lockfileScanned) findings.push(...scanLockfile(lockfile, repoDir))\n\n for (const tarball of seen.tarballs) {\n findings.push({\n check: 'vendored-tarball',\n name: null,\n specifier: null,\n protocol: 'tarball',\n where: relative(repoDir, tarball).split(sep).join('/'),\n detail: 'is a PACKED TARBALL committed into the source tree. Even when nothing points at it today, '\n + 'it is a build nobody can reproduce from the registry sitting one `file:` line away from '\n + `shipping. Delete it; if ${basename(tarball)} is genuinely test data, move it under a path `\n + 'passed to `--exclude`.',\n })\n }\n\n findings.push(...scanVirtualStore(repoDir, modulesDir))\n const integrity = checkInstalledIntegrity({ repoDir, modulesDir, scope })\n findings.push(...integrity.findings)\n\n return {\n repoDir,\n manifestsScanned: seen.manifests.length,\n lockfileScanned,\n integrity: integrity.coverage,\n findings,\n ok: findings.length === 0,\n }\n}\n\nconst CHECK_LABEL: Record<DependencySourceCheck, string> = {\n declared: 'DECLARED',\n override: 'OVERRIDE',\n lockfile: 'LOCKFILE',\n 'vendored-tarball': 'TARBALL',\n installed: 'INSTALLED',\n}\n\n/** One finding rendered as the failure a reader has to act on. */\nexport function describeDependencySourceFinding(finding: DependencySourceFinding): string {\n const subject = finding.name\n ? `${finding.name}${finding.specifier ? ` (${finding.specifier})` : ''}`\n : finding.where\n return `DEPENDENCY SOURCE: ${subject} ${finding.detail}\\n at ${finding.where}`\n}\n\nexport function formatDependencySourceReport(report: DependencySourceReport): string {\n const { integrity } = report\n // Printed on EVERY report, clean or not: \"verified nothing\" and \"verified\n // everything and found nothing\" are otherwise the same green line, which is\n // this gate's own failure class turned on itself.\n const integrityLine = integrity.storeLocated\n ? ` integrity (${integrity.basis}): ${integrity.packagesExamined} package(s), `\n + `${integrity.filesExamined} file(s), ${integrity.filesHashed} hashed against the store`\n : ` integrity (${integrity.basis}): NOT VERIFIED — no pnpm content-addressed store is reachable `\n + 'from this tree, so no installed bytes were checked against anything'\n const lines = [\n 'dependency sources',\n '',\n ` scanned ${report.manifestsScanned} manifest(s), `\n + `${report.lockfileScanned ? 'pnpm-lock.yaml' : 'no lockfile'}`,\n integrityLine,\n '',\n ]\n if (report.ok) {\n lines.push(\n integrity.storeLocated && integrity.packagesExamined > 0\n ? ' ok every declared source is the registry, and every installed byte came from the store'\n : ' ok every declared source is the registry — installed bytes UNVERIFIED (see above)',\n )\n } else {\n for (const finding of report.findings) {\n lines.push(` FAIL [${CHECK_LABEL[finding.check]}] ${describeDependencySourceFinding(finding)}`, '')\n }\n }\n return lines.join('\\n')\n}\n"],"mappings":";AAAA,SAAS,cAAAA,aAAY,gBAAAC,eAAc,eAAAC,oBAAmB;AACtD,SAAS,WAAAC,UAAS,QAAAC,aAAY;;;ACD9B,SAAS,kBAAkB;AAC3B,SAAS,YAAY,WAAW,cAAc,aAAa,gBAAgB;AAC3E,SAAS,UAAU,SAAS,YAAY,MAAM,UAAU,SAAS,WAAW;AAoD5E,IAAM,UAAU;AAUT,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QAAyB,QAAQ,OAAO,OAAe;AAC3F,QAAM,QAAQ,KAAK,IAAI,GAAG,OAAO,KAAK,IAAI,CAAC,MAAM,EAAE,KAAK,MAAM,GAAG,CAAC;AAClE,QAAM,QAAQ;AAAA,IACZ,GAAG,KAAK,IAAI,OAAO,YAAY;AAAA,IAC/B;AAAA,IACA,GAAG,OAAO,KAAK,IAAI,CAAC,QAClB,KAAK,IAAI,YAAY,cAAc,SAAS,IAAI,QAAQ,WAAW,QAAQ,IAAI,SAAS,MAAM,IACzF,IAAI,KAAK,OAAO,KAAK,CAAC,gBAAgB,IAAI,aAAa,UAAU,OAAO,EAAE,CAAC,UAAU,IAAI,KAAK,EAAE;AAAA,IACvG;AAAA,IACA,OAAO,KACH,OAAO,OAAO,KAAK,MAAM,sBACzB,OAAO,WAAW,IAAI,CAAC,QAAQ,2BAA2B,KAAK,OAAO,cAAc,KAAK,CAAC,EAAE,KAAK,MAAM;AAAA,EAC7G;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":["existsSync","readFileSync","readdirSync","dirname","join","join","existsSync","readdirSync","readFileSync","dirname"]}
|
|
@@ -46,6 +46,7 @@ export interface PeerFloorRow {
|
|
|
46
46
|
readonly verdict: PeerFloorVerdict;
|
|
47
47
|
}
|
|
48
48
|
export interface PeerFloorReport {
|
|
49
|
+
readonly shell: string;
|
|
49
50
|
readonly shellVersion: string;
|
|
50
51
|
readonly rows: readonly PeerFloorRow[];
|
|
51
52
|
readonly violations: readonly PeerFloorRow[];
|
|
@@ -75,9 +76,13 @@ export interface CheckPeerFloorsOptions {
|
|
|
75
76
|
* calibration proof that is not committed is a proof that stops running. */
|
|
76
77
|
modulesDir?: string;
|
|
77
78
|
}
|
|
79
|
+
export type CheckAllPeerFloorsOptions = Pick<CheckPeerFloorsOptions, 'appDir' | 'modulesDir' | 'scope'>;
|
|
78
80
|
export declare function satisfiesRange(version: string, range: string): boolean;
|
|
79
81
|
/** Audit one app directory against the shell's declared peer floors. */
|
|
80
82
|
export declare function checkPeerFloors(options: CheckPeerFloorsOptions): PeerFloorReport;
|
|
83
|
+
/** Audit every installed package in `scope` that constrains another package in
|
|
84
|
+
* that scope. This is the complete stack check the CLI runs for consumers. */
|
|
85
|
+
export declare function checkAllPeerFloors(options: CheckAllPeerFloorsOptions): readonly PeerFloorReport[];
|
|
81
86
|
/** The failure message for one violating row. Split out so a caller can raise
|
|
82
87
|
* it from a test and a CLI can print it identically. */
|
|
83
88
|
export declare function describePeerFloorViolation(row: PeerFloorRow, shellVersion: string, shell?: string): string;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
|
+
checkAllPeerFloors,
|
|
2
3
|
checkDependencySources,
|
|
3
4
|
checkInstalledIntegrity,
|
|
4
5
|
checkPeerFloors,
|
|
@@ -9,8 +10,9 @@ import {
|
|
|
9
10
|
formatPeerFloorReport,
|
|
10
11
|
resolveLocalPathSource,
|
|
11
12
|
satisfiesRange
|
|
12
|
-
} from "../chunk-
|
|
13
|
+
} from "../chunk-BOQ4HVVH.js";
|
|
13
14
|
export {
|
|
15
|
+
checkAllPeerFloors,
|
|
14
16
|
checkDependencySources,
|
|
15
17
|
checkInstalledIntegrity,
|
|
16
18
|
checkPeerFloors,
|
package/dist/peer-floors/cli.js
CHANGED
|
@@ -3,11 +3,11 @@ import {
|
|
|
3
3
|
invokedAsScript
|
|
4
4
|
} from "../chunk-C3CAYGGQ.js";
|
|
5
5
|
import {
|
|
6
|
+
checkAllPeerFloors,
|
|
6
7
|
checkDependencySources,
|
|
7
|
-
checkPeerFloors,
|
|
8
8
|
formatDependencySourceReport,
|
|
9
9
|
formatPeerFloorReport
|
|
10
|
-
} from "../chunk-
|
|
10
|
+
} from "../chunk-BOQ4HVVH.js";
|
|
11
11
|
|
|
12
12
|
// src/peer-floors/cli.ts
|
|
13
13
|
function parsePeerCheckArgs(argv) {
|
|
@@ -42,10 +42,10 @@ function main() {
|
|
|
42
42
|
failed = true;
|
|
43
43
|
}
|
|
44
44
|
try {
|
|
45
|
-
const
|
|
46
|
-
process.stdout.write(`${formatPeerFloorReport(report)}
|
|
45
|
+
const reports = checkAllPeerFloors({ appDir });
|
|
46
|
+
process.stdout.write(`${reports.map((report) => formatPeerFloorReport(report)).join("\n\n")}
|
|
47
47
|
`);
|
|
48
|
-
if (!report.ok) failed = true;
|
|
48
|
+
if (reports.some((report) => !report.ok)) failed = true;
|
|
49
49
|
} catch (err) {
|
|
50
50
|
process.stderr.write(`agent-app-peer-check (peer floors) failed: ${err instanceof Error ? err.message : String(err)}
|
|
51
51
|
`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/peer-floors/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-peer-check` — fail a consumer's CI when its dependencies are wrong\n * in either of the two ways a version number cannot show.\n *\n * Runs in the CONSUMER's repo, over the consumer's own tree, because both\n * questions only mean anything against a real install. Add it next to\n * typecheck:\n *\n * \"scripts\": { \"peer-check\": \"agent-app-peer-check\" }\n *\n * Two gates, one report, one exit code:\n *\n * PEER FLOORS — is the installed version inside the range the shell\n * declares. `pnpm` only WARNS on an unmet peer that is\n * also a direct dependency and says nothing at all for an\n * unmet optional one.\n * DEPENDENCY SOURCE — is the installed package the one the registry\n * publishes at all. A `file:` tarball, a `link:` out of\n * the repo, or a hand-patched `node_modules` all report\n * the same version as the real release and ship different\n * bytes.\n *\n * The source gate runs FIRST and independently: it needs no installed shell, so\n * a repo whose install is broken still gets the answer that explains why.\n *\n * Usage: agent-app-peer-check [repoDir] [--exclude <path>]...\n * `--exclude` takes a repo-relative path prefix the source-tree walk skips —\n * the escape hatch for a repo that genuinely carries a tarball as test data.\n * Exits 1 on any violation, 0 otherwise.\n */\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/peer-floors/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-peer-check` — fail a consumer's CI when its dependencies are wrong\n * in either of the two ways a version number cannot show.\n *\n * Runs in the CONSUMER's repo, over the consumer's own tree, because both\n * questions only mean anything against a real install. Add it next to\n * typecheck:\n *\n * \"scripts\": { \"peer-check\": \"agent-app-peer-check\" }\n *\n * Two gates, one report, one exit code:\n *\n * PEER FLOORS — is the installed version inside the range the shell\n * declares. `pnpm` only WARNS on an unmet peer that is\n * also a direct dependency and says nothing at all for an\n * unmet optional one.\n * DEPENDENCY SOURCE — is the installed package the one the registry\n * publishes at all. A `file:` tarball, a `link:` out of\n * the repo, or a hand-patched `node_modules` all report\n * the same version as the real release and ship different\n * bytes.\n *\n * The source gate runs FIRST and independently: it needs no installed shell, so\n * a repo whose install is broken still gets the answer that explains why.\n *\n * Usage: agent-app-peer-check [repoDir] [--exclude <path>]...\n * `--exclude` takes a repo-relative path prefix the source-tree walk skips —\n * the escape hatch for a repo that genuinely carries a tarball as test data.\n * Exits 1 on any violation, 0 otherwise.\n */\nimport { checkAllPeerFloors, formatPeerFloorReport } from './check'\nimport { checkDependencySources, formatDependencySourceReport } from './dependency-source'\nimport { invokedAsScript } from '../signoff/invoked-as-script'\n\ninterface CliArgs {\n readonly appDir: string\n readonly exclude: readonly string[]\n}\n\nexport function parsePeerCheckArgs(argv: readonly string[]): CliArgs {\n const exclude: string[] = []\n let appDir: string | undefined\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i] as string\n if (arg === '--exclude') {\n const value = argv[i + 1]\n if (value) exclude.push(value)\n i += 1\n } else if (arg.startsWith('--exclude=')) {\n exclude.push(arg.slice('--exclude='.length))\n } else if (!arg.startsWith('-') && appDir === undefined) {\n appDir = arg\n }\n }\n return { appDir: appDir ?? process.cwd(), exclude }\n}\n\nfunction main(): void {\n const { appDir, exclude } = parsePeerCheckArgs(process.argv.slice(2))\n let failed = false\n\n try {\n const sources = checkDependencySources({ repoDir: appDir, exclude })\n process.stdout.write(`${formatDependencySourceReport(sources)}\\n\\n`)\n if (!sources.ok) failed = true\n } catch (err) {\n process.stderr.write(`agent-app-peer-check (dependency sources) failed: ${err instanceof Error ? err.message : String(err)}\\n`)\n failed = true\n }\n\n try {\n const reports = checkAllPeerFloors({ appDir })\n process.stdout.write(`${reports.map((report) => formatPeerFloorReport(report)).join('\\n\\n')}\\n`)\n if (reports.some((report) => !report.ok)) failed = true\n } catch (err) {\n process.stderr.write(`agent-app-peer-check (peer floors) failed: ${err instanceof Error ? err.message : String(err)}\\n`)\n failed = true\n }\n\n process.exit(failed ? 1 : 0)\n}\n\n/* c8 ignore start — process wiring, exercised by the bin itself */\nif (invokedAsScript(import.meta.url, process.argv[1])) main()\n/* c8 ignore stop */\n"],"mappings":";;;;;;;;;;;;AAwCO,SAAS,mBAAmB,MAAkC;AACnE,QAAM,UAAoB,CAAC;AAC3B,MAAI;AACJ,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;AACvC,UAAM,MAAM,KAAK,CAAC;AAClB,QAAI,QAAQ,aAAa;AACvB,YAAM,QAAQ,KAAK,IAAI,CAAC;AACxB,UAAI,MAAO,SAAQ,KAAK,KAAK;AAC7B,WAAK;AAAA,IACP,WAAW,IAAI,WAAW,YAAY,GAAG;AACvC,cAAQ,KAAK,IAAI,MAAM,aAAa,MAAM,CAAC;AAAA,IAC7C,WAAW,CAAC,IAAI,WAAW,GAAG,KAAK,WAAW,QAAW;AACvD,eAAS;AAAA,IACX;AAAA,EACF;AACA,SAAO,EAAE,QAAQ,UAAU,QAAQ,IAAI,GAAG,QAAQ;AACpD;AAEA,SAAS,OAAa;AACpB,QAAM,EAAE,QAAQ,QAAQ,IAAI,mBAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC;AACpE,MAAI,SAAS;AAEb,MAAI;AACF,UAAM,UAAU,uBAAuB,EAAE,SAAS,QAAQ,QAAQ,CAAC;AACnE,YAAQ,OAAO,MAAM,GAAG,6BAA6B,OAAO,CAAC;AAAA;AAAA,CAAM;AACnE,QAAI,CAAC,QAAQ,GAAI,UAAS;AAAA,EAC5B,SAAS,KAAK;AACZ,YAAQ,OAAO,MAAM,qDAAqD,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AAC9H,aAAS;AAAA,EACX;AAEA,MAAI;AACF,UAAM,UAAU,mBAAmB,EAAE,OAAO,CAAC;AAC7C,YAAQ,OAAO,MAAM,GAAG,QAAQ,IAAI,CAAC,WAAW,sBAAsB,MAAM,CAAC,EAAE,KAAK,MAAM,CAAC;AAAA,CAAI;AAC/F,QAAI,QAAQ,KAAK,CAAC,WAAW,CAAC,OAAO,EAAE,EAAG,UAAS;AAAA,EACrD,SAAS,KAAK;AACZ,YAAQ,OAAO,MAAM,8CAA8C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,CAAI;AACvH,aAAS;AAAA,EACX;AAEA,UAAQ,KAAK,SAAS,IAAI,CAAC;AAC7B;AAGA,IAAI,gBAAgB,YAAY,KAAK,QAAQ,KAAK,CAAC,CAAC,EAAG,MAAK;","names":[]}
|
package/dist/signoff/cli.js
CHANGED
package/dist/signoff/index.js
CHANGED
|
@@ -48,3 +48,5 @@ export declare function resolveNodeRequirement(repoRoot: string, configured?: st
|
|
|
48
48
|
* exact patch would refuse every host that has not just re-installed.
|
|
49
49
|
*/
|
|
50
50
|
export declare function assertNodeVersion(requirement: NodeVersionRequirement | null, running?: string): void;
|
|
51
|
+
/** Refuse Node declaration files for a different runtime major. */
|
|
52
|
+
export declare function assertNodeTypesVersion(repoRoot: string, requirement: NodeVersionRequirement | null): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "0.46.
|
|
3
|
+
"version": "0.46.22",
|
|
4
4
|
"packageManager": "pnpm@11.24.0",
|
|
5
5
|
"description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
|
|
6
6
|
"keywords": [
|
|
@@ -527,12 +527,12 @@
|
|
|
527
527
|
"@tangle-network/agent-docs": "0.2.1",
|
|
528
528
|
"@tangle-network/agent-eval": "0.170.0",
|
|
529
529
|
"@tangle-network/agent-integrations": "0.53.55",
|
|
530
|
-
"@tangle-network/agent-interface": "1.
|
|
530
|
+
"@tangle-network/agent-interface": "1.9.0",
|
|
531
531
|
"@tangle-network/agent-knowledge": "10.8.0",
|
|
532
532
|
"@tangle-network/agent-profile-materialize": "0.17.1",
|
|
533
|
-
"@tangle-network/agent-runtime": "0.
|
|
533
|
+
"@tangle-network/agent-runtime": "0.180.0",
|
|
534
534
|
"@tangle-network/brand": "1.5.0",
|
|
535
|
-
"@tangle-network/sandbox": "0.34.
|
|
535
|
+
"@tangle-network/sandbox": "0.34.3",
|
|
536
536
|
"@tangle-network/sandbox-ui": "0.111.0",
|
|
537
537
|
"@tangle-network/ui": "^11.6.0",
|
|
538
538
|
"@testing-library/dom": "^10.4.1",
|
|
@@ -560,7 +560,7 @@
|
|
|
560
560
|
"drizzle-orm": "^0.45.2",
|
|
561
561
|
"fast-check": "^4.9.0",
|
|
562
562
|
"jsdom": "^30.0.1",
|
|
563
|
-
"knip": "^6.
|
|
563
|
+
"knip": "^6.33.0",
|
|
564
564
|
"konva": "^10.3.2",
|
|
565
565
|
"lucide-react": "^1.35.0",
|
|
566
566
|
"npm": "12.0.2",
|
|
@@ -569,8 +569,8 @@
|
|
|
569
569
|
"react": "^19.2.8",
|
|
570
570
|
"react-dom": "^19.2.8",
|
|
571
571
|
"react-konva": "^19.2.5",
|
|
572
|
-
"react-router": "^8.3.
|
|
573
|
-
"resend": "^6.
|
|
572
|
+
"react-router": "^8.3.1",
|
|
573
|
+
"resend": "^6.25.0",
|
|
574
574
|
"semver": "^7.8.5",
|
|
575
575
|
"storybook": "^10.5.10",
|
|
576
576
|
"tailwindcss": "^4.3.3",
|
|
@@ -589,7 +589,7 @@
|
|
|
589
589
|
"@tangle-network/agent-interface": "^1.8.0",
|
|
590
590
|
"@tangle-network/agent-knowledge": "^10.8.0",
|
|
591
591
|
"@tangle-network/agent-profile-materialize": ">=0.17.1 <0.18.0",
|
|
592
|
-
"@tangle-network/agent-runtime": ">=0.178.0 <0.
|
|
592
|
+
"@tangle-network/agent-runtime": ">=0.178.0 <0.181.0",
|
|
593
593
|
"@tangle-network/brand": ">=1.5.0",
|
|
594
594
|
"@tangle-network/sandbox": ">=0.34.0 <0.35.0",
|
|
595
595
|
"@tangle-network/sandbox-ui": ">=0.111.0 <0.112.0",
|
|
@@ -693,6 +693,6 @@
|
|
|
693
693
|
}
|
|
694
694
|
},
|
|
695
695
|
"dependencies": {
|
|
696
|
-
"zod": "^4.
|
|
696
|
+
"zod": "^4.5.1"
|
|
697
697
|
}
|
|
698
698
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/peer-floors/check.ts","../src/peer-floors/dependency-source.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\n/**\n * The second half of this gate lives in `./dependency-source` and ships on the\n * SAME subpath and the SAME `agent-app-peer-check` bin, because it answers the\n * question underneath this one: a floor comparison reads a version, and a\n * version is not an identity — a vendored `pnpm pack` of an unmerged branch\n * carries the same `0.45.33` a real release does.\n */\nexport * from './dependency-source'\n\n/**\n * Audit a consumer's installed tree against the peer floors this package\n * declares.\n *\n * A peer floor is not documentation — it encodes a WIRE CONTRACT, and breaking\n * one is invisible to every other gate. `pnpm` only WARNS on an unmet peer when\n * the package is also a direct dependency, and says nothing at all for an unmet\n * OPTIONAL peer, which is how most of the substrate is declared here. So a\n * product can sit below a floor with a clean install, a clean typecheck, a green\n * suite and a successful deploy, and fail only on a live wire call:\n *\n * `@tangle-network/sandbox` 0.15.0 → 0.15.1 changed the sidecar spawn body\n * from `{ command }` to `{ executable, args }`. Below the floor, every\n * `box.exec()` on a live sandbox returns 400 `Unrecognized key: \"command\"`.\n *\n * `@tangle-network/agent-interface` 0.38.0 changed MCP config values from\n * plain strings to tagged public/secret-ref objects. Below the floor, this\n * package fails at MODULE LOAD with \"does not provide an export named\n * defineAgentProfilePublicConfig\" — while `tsc` reports zero errors, because\n * the types resolve and only the runtime export is missing.\n *\n * That second shape is why this exists as its own gate: typecheck cannot see it,\n * and a suite only sees it as dozens of unrelated-looking import failures.\n */\n\n/** Installed, and inside the declared range. */\nexport type PeerFloorVerdict =\n | 'satisfied'\n /** Installed and BELOW the floor — the silent case this module exists for. */\n | 'below-floor'\n /** Not installed and never asked for. A legitimate answer for an optional peer. */\n | 'absent-unused'\n /** Declared by the app, yet no version could be read, so the floor went\n * UNCHECKED. Reported as a failure rather than a pass this did not earn. */\n | 'absent-but-declared'\n\nexport interface PeerFloorRow {\n readonly name: string\n readonly range: string\n readonly installed: string | null\n readonly verdict: PeerFloorVerdict\n}\n\nexport interface PeerFloorReport {\n readonly shellVersion: string\n readonly rows: readonly PeerFloorRow[]\n readonly violations: readonly PeerFloorRow[]\n readonly ok: boolean\n}\n\nexport interface CheckPeerFloorsOptions {\n /** Directory of the app under audit — the one whose `package.json` and\n * installed tree are read. */\n appDir: string\n /** Package whose peer floors are the contract. Defaults to this shell. */\n shell?: string\n /** Only audit peers under this scope. Third-party peers (react, drizzle) are\n * the app's own business, not part of the Tangle wire contract. Pass `''` to\n * audit every peer. */\n scope?: string\n /** Floors to audit against, when the shell is not resolvable from `appDir` —\n * the package auditing ITSELF, which has no copy of itself in its own\n * `node_modules`. Without this a package cannot check that the contract it\n * publishes is one its own dev install satisfies. */\n shellManifest?: { version?: string; peerDependencies?: Record<string, string> }\n /** Directory name to walk for installed packages. Overridable so a test can\n * point at a committed fixture tree — `node_modules` is gitignored\n * everywhere, so a fixture using that name could not be committed, and a\n * calibration proof that is not committed is a proof that stops running. */\n modulesDir?: string\n}\n\n/**\n * Read a package's manifest off disk, walking `modulesDir` up from `fromDir`.\n *\n * Deliberately NOT `require.resolve('<name>/package.json')`: most of these\n * packages omit `./package.json` from their `exports` map, so that throws\n * ERR_PACKAGE_PATH_NOT_EXPORTED — and a try/catch around it reports an INSTALLED\n * package as absent, turning the whole audit into a silent no-op. Walking the\n * tree is exports-map-independent and mirrors Node's own resolution order, so\n * the version reported is the version that would actually load.\n *\n * The walk STOPS at the repository root — a directory containing `.git` — and\n * never climbs past it. Node itself would keep going, but a `node_modules`\n * above a checkout belongs to something else entirely, and letting it answer\n * silently changes the verdict: a stray `/tmp/node_modules` shadowing one\n * package produced a confident FAIL for a repo that was above every floor. A\n * check that reports the wrong tree is worse than no check.\n *\n * Returns null only when no directory for the package exists inside the repo,\n * which is the genuine not-installed case.\n */\nfunction readInstalledManifest(\n name: string,\n fromDir: string,\n modulesDir: string,\n): { version?: string; peerDependencies?: Record<string, string> } | null {\n let dir = fromDir\n for (;;) {\n const manifest = join(dir, modulesDir, name, 'package.json')\n if (existsSync(manifest)) {\n return JSON.parse(readFileSync(manifest, 'utf8')) as {\n version?: string\n peerDependencies?: Record<string, string>\n }\n }\n // Repo boundary: stop here rather than inheriting an unrelated tree.\n if (existsSync(join(dir, '.git'))) return null\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Minimal range satisfaction for the ranges peer floors actually use:\n * `>=x <y`, `^x.y.z`, `~x.y.z`, `x.y.z`, and `*`/`x`.\n *\n * Hand-rolled rather than taking a `semver` dependency, because this package\n * ships zero runtime dependencies and a checker that forces one on every\n * consumer is a worse trade than 40 lines of comparison. Prerelease versions\n * compare by their release part — a floor is about the wire contract, and a\n * prerelease of a satisfying version speaks it.\n */\nfunction parseVersion(version: string): [number, number, number] {\n const [core] = version.split(/[-+]/)\n const parts = (core ?? '').split('.').map((p) => Number.parseInt(p, 10))\n return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0]\n}\n\nfunction compare(a: string, b: string): number {\n const va = parseVersion(a)\n const vb = parseVersion(b)\n for (let i = 0; i < 3; i += 1) {\n if (va[i]! !== vb[i]!) return va[i]! < vb[i]! ? -1 : 1\n }\n return 0\n}\n\nfunction satisfiesComparator(version: string, comparator: string): boolean {\n const trimmed = comparator.trim()\n if (!trimmed || trimmed === '*' || trimmed === 'x') return true\n const match = /^(>=|<=|>|<|=|\\^|~)?\\s*v?(.+)$/.exec(trimmed)\n if (!match) return false\n const [, op = '=', target = ''] = match\n const cmp = compare(version, target)\n switch (op) {\n case '>=': return cmp >= 0\n case '<=': return cmp <= 0\n case '>': return cmp > 0\n case '<': return cmp < 0\n case '=': return cmp === 0\n case '~': {\n // ~1.2.3 allows patch bumps; ~1.2 allows minor.\n const [major, minor] = parseVersion(target)\n const [vMajor, vMinor] = parseVersion(version)\n return cmp >= 0 && vMajor === major && vMinor === minor\n }\n case '^': {\n // A caret on a 0.x version is MINOR-locked: ^0.36.0 can never resolve to\n // 0.38.0. That is the single most common reason a floor cannot be met by\n // reinstalling, so it is modelled exactly rather than approximated.\n const [major, minor] = parseVersion(target)\n const [vMajor, vMinor] = parseVersion(version)\n if (cmp < 0) return false\n if (major > 0) return vMajor === major\n if (minor > 0) return vMajor === 0 && vMinor === minor\n return vMajor === 0 && vMinor === 0\n }\n default: return false\n }\n}\n\nexport function satisfiesRange(version: string, range: string): boolean {\n // `||` is alternation; whitespace inside an alternative is conjunction.\n return range.split('||').some((alternative) =>\n alternative.trim().split(/\\s+/).filter(Boolean).every((c) => satisfiesComparator(version, c)),\n )\n}\n\n/** Audit one app directory against the shell's declared peer floors. */\nexport function checkPeerFloors(options: CheckPeerFloorsOptions): PeerFloorReport {\n const {\n appDir,\n shell = '@tangle-network/agent-app',\n scope = '@tangle-network/',\n modulesDir = 'node_modules',\n } = options\n\n const shellManifest = options.shellManifest ?? readInstalledManifest(shell, appDir, modulesDir)\n if (!shellManifest) throw new Error(`${shell} is not installed under ${appDir}`)\n\n const appManifest = JSON.parse(readFileSync(join(appDir, 'package.json'), 'utf8')) as {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n optionalDependencies?: Record<string, string>\n }\n const declared = {\n ...appManifest.dependencies,\n ...appManifest.devDependencies,\n ...appManifest.optionalDependencies,\n }\n\n const floors = Object.entries(shellManifest.peerDependencies ?? {})\n .filter(([name]) => name.startsWith(scope))\n\n const rows = floors.map(([name, range]): PeerFloorRow => {\n const installed = readInstalledManifest(name, appDir, modulesDir)?.version ?? null\n if (installed === null) {\n return { name, range, installed, verdict: declared[name] ? 'absent-but-declared' : 'absent-unused' }\n }\n return {\n name,\n range,\n installed,\n verdict: satisfiesRange(installed, range) ? 'satisfied' : 'below-floor',\n }\n })\n\n const violations = rows.filter((row) => row.verdict === 'below-floor' || row.verdict === 'absent-but-declared')\n return {\n shellVersion: shellManifest.version ?? 'unknown',\n rows,\n violations,\n ok: violations.length === 0,\n }\n}\n\n/** The failure message for one violating row. Split out so a caller can raise\n * it from a test and a CLI can print it identically. */\nexport function describePeerFloorViolation(row: PeerFloorRow, shellVersion: string, shell = '@tangle-network/agent-app'): string {\n if (row.verdict === 'below-floor') {\n return `PEER FLOOR VIOLATED: ${shell}@${shellVersion} requires ${row.name}@${row.range}, `\n + `but ${row.installed} is installed. A peer floor encodes a wire contract — bump the `\n + `dependency, do not widen the floor. A caret on a 0.x version is minor-locked `\n + `(^0.36.0 can never resolve to 0.38.0), so reinstalling alone will not fix this: `\n + `change the pin, in EVERY place it appears including pnpm.overrides.`\n }\n return `${row.name} is a declared dependency of this app, but no installed version could be `\n + `read, so its peer floor ${row.range} went UNCHECKED. Failing loudly rather than `\n + `reporting a pass this guard did not earn.`\n}\n\nexport function formatPeerFloorReport(report: PeerFloorReport, shell = '@tangle-network/agent-app'): string {\n const width = Math.max(...report.rows.map((r) => r.name.length), 4)\n const lines = [\n `${shell}@${report.shellVersion} — peer floors`,\n '',\n ...report.rows.map((row) =>\n ` ${row.verdict === 'satisfied' ? 'ok ' : row.verdict.startsWith('absent') ? '-- ' : 'FAIL'} `\n + `${row.name.padEnd(width)} installed ${(row.installed ?? '(none)').padEnd(10)} floor ${row.range}`),\n '',\n report.ok\n ? `all ${report.rows.length} floors satisfied`\n : report.violations.map((row) => describePeerFloorViolation(row, report.shellVersion, shell)).join('\\n\\n'),\n ]\n return lines.join('\\n')\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, lstatSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\n\n/**\n * Audit where a repository's dependencies COME FROM.\n *\n * `/peer-floors` already answers \"is the installed version inside the declared\n * range\". This answers the question underneath it — \"is the installed package\n * the one the registry publishes at all\" — because a version number is not an\n * identity. Two artifacts can carry `0.45.33` and ship different APIs, and every\n * gate that reads a version reads the same number for both.\n *\n * THE MEASURED DEFECT. insurance-agent's `pnpm-workspace.yaml` carried\n *\n * overrides:\n * '@tangle-network/agent-app': file:./vendor/agent-app/tangle-network-agent-app-0.45.33.tgz\n *\n * — a 2.6 MB `pnpm pack` of an UNMERGED pull request, committed into the\n * product repo (`insurance-agent` f7d0f51 removed it). It installed cleanly,\n * typechecked green and passed sign-off while the product ran code that existed\n * in no published release. Note where it was NOT: `package.json` still read\n * `\"@tangle-network/agent-app\": \"^0.45.33\"`, a perfectly ordinary registry\n * range. A check that reads only the root manifest's `dependencies` sees\n * nothing. The override lane is the one that shipped, so the override lane —\n * `pnpm-workspace.yaml`, `pnpm.overrides`, `resolutions` — is audited first.\n *\n * The second shape is worse because nothing declares it at all: a worktree was\n * found whose installed `agent-app@0.45.29` had `dist/spend/index.d.ts`\n * replaced with a newer version's content by hand. The manifest, the lockfile\n * and the version on disk all agreed; only the bytes disagreed, and the product\n * typechecked green against an API its declared dependency does not ship. See\n * `checkInstalledIntegrity` below for exactly how much of that class is\n * catchable cheaply and exactly how much is not.\n */\n\n/** How a specifier says a dependency should be obtained. */\nexport type DependencySourceProtocol =\n /** Resolvable from the registry by anyone: `^1.2.3`, `1.2.3`, `npm:x@1`. */\n | 'registry'\n /** `workspace:` — another package in this same repo. Reviewable in one diff. */\n | 'workspace'\n /** `catalog:` — indirection into `pnpm-workspace.yaml`, which is itself audited. */\n | 'catalog'\n /** A local path. Whether it is legitimate depends on WHERE it points. */\n | 'file'\n | 'link'\n | 'portal'\n /** A path or URL ending in a packed tarball. Opaque bytes; never legitimate. */\n | 'tarball'\n /** A git ref or a remote URL that is not the registry. */\n | 'git'\n | 'remote'\n\nconst TARBALL = /\\.(?:tgz|tar\\.gz)$/i\n\n/**\n * Classify one dependency specifier by the SOURCE it names.\n *\n * Pure and exported so a consumer can reuse the vocabulary, and so the rule can\n * be tested without a filesystem. Nothing here decides legitimacy — `file:` on\n * a directory inside the repo is correct and `file:` on a tarball never is, and\n * that distinction needs the disk (`resolveLocalPathSource`).\n */\nexport function classifyDependencySpecifier(specifier: string): DependencySourceProtocol {\n const spec = specifier.trim()\n if (spec.startsWith('workspace:')) return 'workspace'\n if (spec.startsWith('catalog:')) return 'catalog'\n for (const protocol of ['file:', 'link:', 'portal:'] as const) {\n if (spec.startsWith(protocol)) {\n const path = spec.slice(protocol.length)\n if (TARBALL.test(path)) return 'tarball'\n return protocol.slice(0, -1) as 'file' | 'link' | 'portal'\n }\n }\n if (/^(?:git|git\\+ssh|git\\+https?|git\\+file|ssh):/.test(spec)) return 'git'\n if (/^(?:github|gitlab|bitbucket):/.test(spec)) return 'git'\n if (/^https?:\\/\\//.test(spec)) return TARBALL.test(spec.split(/[?#]/)[0] ?? '') ? 'tarball' : 'remote'\n // `owner/repo` and `owner/repo#ref` are npm's GitHub shorthand. A scoped\n // package name (`@scope/name`) also contains a slash, hence the leading-@ guard.\n if (/^[\\w.-]+\\/[\\w.-]+(?:#.+)?$/.test(spec) && !spec.startsWith('@')) return 'git'\n return 'registry'\n}\n\n/** A protocol that resolves from the registry, or from this repo's own sources. */\nfunction isReproducible(protocol: DependencySourceProtocol): boolean {\n return protocol === 'registry' || protocol === 'workspace' || protocol === 'catalog'\n}\n\n/**\n * The legitimate-exception rule, stated once so it is not a path allowlist.\n *\n * agent-app's own `playground/package.json` declares\n * `\"@tangle-network/agent-app\": \"file:..\"` and that is CORRECT: the playground\n * depends on the package it lives inside. The property that makes it correct is\n * not its path — it is that the dependency is satisfied by SOURCE ALREADY IN\n * THIS REPOSITORY, under version control, changing only in a diff a reviewer\n * sees. So the rule is:\n *\n * A `file:` / `link:` / `portal:` specifier is exempt when it resolves to a\n * DIRECTORY inside this repository holding a `package.json` whose `name` is\n * the dependency being declared.\n *\n * Every clause is load-bearing. A DIRECTORY, because a `.tgz` is opaque bytes\n * that no diff shows — a packed tarball is never exempt, wherever it sits.\n * INSIDE THIS REPOSITORY, because `file:../../agent-app` is a path on one\n * machine: it resolves for its author and for nobody else, and a sign-off gate\n * that installs into a clean export dies at install. NAME MATCHES, because a\n * path pointing at some other package's source is a mis-wire, not a\n * self-reference.\n */\nexport type LocalPathSource =\n /** In-repo directory whose package.json names this dependency. Legitimate. */\n | 'in-repo-source'\n /** Points outside the repository — reproducible on one machine only. */\n | 'outside-repo'\n /** Nothing there, or not a directory (a packed tarball lands here too). */\n | 'not-a-directory'\n /** An in-repo directory, but it is a different package. */\n | 'name-mismatch'\n\nexport function resolveLocalPathSource(args: {\n /** Directory of the manifest that made the declaration. */\n fromDir: string\n /** Root of the repository the declaration must stay inside. */\n repoDir: string\n /** The path part of the specifier, protocol already stripped. */\n path: string\n /** The dependency name the path is claimed to satisfy. */\n name: string\n}): LocalPathSource {\n const root = resolve(args.repoDir)\n const target = isAbsolute(args.path) ? resolve(args.path) : resolve(args.fromDir, args.path)\n if (target !== root && !target.startsWith(root + sep)) return 'outside-repo'\n const manifest = join(target, 'package.json')\n if (!existsSync(manifest) || !statSync(target).isDirectory()) return 'not-a-directory'\n let declared: string | undefined\n try {\n declared = (JSON.parse(readFileSync(manifest, 'utf8')) as { name?: string }).name\n } catch {\n return 'not-a-directory'\n }\n return declared === args.name ? 'in-repo-source' : 'name-mismatch'\n}\n\n/** Which of the five scans produced a finding. Kept on the row because the fix\n * differs: a declaration is edited, an installed tree is reinstalled. */\nexport type DependencySourceCheck =\n /** A `dependencies`-family field in some `package.json`. */\n | 'declared'\n /** `pnpm.overrides` / `resolutions` / `pnpm-workspace.yaml` — the lane that shipped. */\n | 'override'\n /** `pnpm-lock.yaml` — what actually resolved, whatever the manifests now say. */\n | 'lockfile'\n /** A packed tarball sitting in the source tree. */\n | 'vendored-tarball'\n /** The installed tree on disk. */\n | 'installed'\n\nexport interface DependencySourceFinding {\n readonly check: DependencySourceCheck\n /** Dependency name, or `null` for a stray tarball that names no dependency. */\n readonly name: string | null\n readonly specifier: string | null\n readonly protocol: DependencySourceProtocol | null\n /** Repo-relative location, with the key or line that carries it. */\n readonly where: string\n /** Why this is a finding, and what to do about it. */\n readonly detail: string\n}\n\n/**\n * What the on-disk integrity pass was able to examine — reported on EVERY run,\n * clean or not, because \"checked nothing\" and \"checked everything and found\n * nothing\" render identically otherwise. This module's own doctrine: an\n * unchecked contract is never a pass it did not earn.\n */\nexport interface InstalledIntegrityCoverage {\n /** The only basis implemented. See `checkInstalledIntegrity`'s limits. */\n readonly basis: 'store-cas'\n /** False for npm, yarn, a pruned CI cache, or a store on another machine.\n * Nothing was verified, and the report says so rather than reading clean. */\n readonly storeLocated: boolean\n readonly packagesExamined: number\n readonly filesExamined: number\n /** Files settled by reading their bytes rather than by a shared inode. */\n readonly filesHashed: number\n}\n\nexport interface DependencySourceReport {\n readonly repoDir: string\n readonly manifestsScanned: number\n readonly lockfileScanned: boolean\n readonly integrity: InstalledIntegrityCoverage\n readonly findings: readonly DependencySourceFinding[]\n readonly ok: boolean\n}\n\nexport interface CheckDependencySourcesOptions {\n /** Repository root to audit. */\n repoDir: string\n /** Scope filter for the on-disk integrity pass. `''` examines every package. */\n scope?: string\n /** Directory name holding the installed tree. Overridable so a committed\n * fixture can use `fixture_modules` — `node_modules` is gitignored\n * everywhere, and a calibration proof that is not committed stops running. */\n modulesDir?: string\n /** Repo-relative path prefixes the source-tree walk skips. The escape hatch\n * for a repo that genuinely carries a tarball as test data — and for this\n * package's own calibration fixtures, whose purpose is to CONTAIN the\n * violation. */\n exclude?: readonly string[]\n}\n\n/** Directories a source-tree walk must never descend into: build output and\n * installed packages are not declarations, and walking them turns a\n * sub-second scan into a minute. */\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', 'out', 'coverage',\n '.wrangler', '.react-router', '.next', '.turbo', '.cache', '.worktrees', 'storybook-static',\n])\n\nfunction walkSourceTree(\n dir: string,\n repoDir: string,\n exclude: readonly string[],\n seen: { manifests: string[]; tarballs: string[] },\n): void {\n let entries: import('node:fs').Dirent[]\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return\n }\n for (const entry of entries) {\n const full = join(dir, entry.name)\n const rel = relative(repoDir, full).split(sep).join('/')\n if (exclude.some((prefix) => rel === prefix || rel.startsWith(`${prefix}/`))) continue\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) continue\n walkSourceTree(full, repoDir, exclude, seen)\n } else if (entry.isFile()) {\n if (entry.name === 'package.json') seen.manifests.push(full)\n else if (TARBALL.test(entry.name)) seen.tarballs.push(full)\n }\n }\n}\n\n/* ---------------------------------------------------------------------------\n * A line reader for the two YAML files that matter.\n *\n * Deliberately not a YAML dependency: this package ships zero runtime deps and\n * forcing one on every consumer to read four block mappings is the worse trade\n * — the same call `/peer-floors` made about `semver`. The shapes read here are\n * `pnpm-workspace.yaml`'s `overrides`/`catalog`/`catalogs` and\n * `pnpm-lock.yaml`'s `overrides`/`importers`/`packages`/`snapshots`, all of\n * which pnpm emits as plain two-space block mappings of scalars.\n * ------------------------------------------------------------------------ */\n\ninterface YamlLine {\n readonly indent: number\n readonly key: string\n readonly value: string\n /** Enclosing keys, outermost first, excluding this line's own key. */\n readonly path: readonly string[]\n readonly lineNumber: number\n}\n\nfunction unquote(text: string): string {\n const t = text.trim()\n if ((t.startsWith(\"'\") && t.endsWith(\"'\")) || (t.startsWith('\"') && t.endsWith('\"'))) {\n return t.slice(1, -1)\n }\n return t\n}\n\nfunction readYamlLines(text: string): YamlLine[] {\n const out: YamlLine[] = []\n // Innermost key seen at each indent level, so a `specifier:` line can name\n // the dependency it belongs to.\n const stack: string[] = []\n text.split('\\n').forEach((raw, index) => {\n if (!raw.trim() || raw.trimStart().startsWith('#')) return\n const indent = raw.length - raw.trimStart().length\n const match = /^\\s*(?:'((?:[^']|'')*)'|\"([^\"]*)\"|([^\\s:#][^:]*?))\\s*:(?:\\s+(.*))?$/.exec(raw)\n if (!match) return\n const key = (match[1] ?? match[2] ?? match[3] ?? '').replace(/''/g, \"'\")\n // A trailing ` # comment` is a comment only outside quotes; every value pnpm\n // writes here is unquoted or fully quoted, so splitting on ` #` is exact.\n const rawValue = (match[4] ?? '').split(' #')[0] ?? ''\n const depth = Math.floor(indent / 2)\n stack.length = depth\n const path = [...stack]\n stack[depth] = key\n out.push({ indent, key, value: unquote(rawValue), path, lineNumber: index + 1 })\n })\n return out\n}\n\n/** The top-level section a nested line sits under. */\nfunction sectionOf(line: YamlLine): string | undefined {\n return line.indent === 0 ? line.key : line.path[0]\n}\n\n/* ------------------------------------------------------------------------ */\n\nconst DEP_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'] as const\n\n/**\n * Judge one declaration and produce a finding, or `null` when it is fine.\n *\n * One function so the manifest lane, the override lane and the lockfile lane\n * cannot drift into three different opinions about the same specifier.\n */\nfunction judge(args: {\n check: DependencySourceCheck\n name: string\n specifier: string\n where: string\n fromDir: string\n repoDir: string\n}): DependencySourceFinding | null {\n const protocol = classifyDependencySpecifier(args.specifier)\n if (isReproducible(protocol)) return null\n\n const base = { check: args.check, name: args.name, specifier: args.specifier, protocol, where: args.where }\n\n if (protocol === 'tarball') {\n return {\n ...base,\n detail: 'resolves a PACKED TARBALL, not a published release. A .tgz is opaque bytes that no '\n + 'diff shows and no registry can reproduce: the version inside it can collide with a real '\n + 'release and ship a different API. Publish the change and pin the published range.',\n }\n }\n if (protocol === 'git' || protocol === 'remote') {\n return {\n ...base,\n detail: `resolves from ${protocol === 'git' ? 'a git ref' : 'a remote URL'} rather than the `\n + 'registry, so what installs depends on what that ref points at today. Publish the change '\n + 'and pin the published range.',\n }\n }\n\n const path = args.specifier.slice(args.specifier.indexOf(':') + 1)\n const source = resolveLocalPathSource({ fromDir: args.fromDir, repoDir: args.repoDir, path, name: args.name })\n if (source === 'in-repo-source') return null\n const why: Record<Exclude<LocalPathSource, 'in-repo-source'>, string> = {\n 'outside-repo': 'points OUTSIDE this repository, so it resolves on one machine and nowhere else — '\n + 'a clean checkout, a CI runner and a sign-off gate that installs into an exported tree all '\n + 'get a different answer or fail at install.',\n 'not-a-directory': 'does not resolve to a package directory in this repository. A local specifier '\n + 'is only legitimate when it points at in-repo SOURCE a reviewer sees in the diff.',\n 'name-mismatch': `resolves to an in-repo directory that declares a DIFFERENT package name, so the `\n + `dependency ${args.name} is being satisfied by something else entirely.`,\n }\n return { ...base, detail: `${why[source]} (${source})` }\n}\n\nfunction scanManifest(file: string, repoDir: string): DependencySourceFinding[] {\n let manifest: Record<string, unknown>\n try {\n manifest = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>\n } catch {\n return []\n }\n const fromDir = dirname(file)\n const where = relative(repoDir, file).split(sep).join('/') || 'package.json'\n const findings: DependencySourceFinding[] = []\n\n for (const field of DEP_FIELDS) {\n const block = manifest[field]\n if (!block || typeof block !== 'object') continue\n for (const [name, specifier] of Object.entries(block as Record<string, unknown>)) {\n if (typeof specifier !== 'string') continue\n const finding = judge({ check: 'declared', name, specifier, where: `${where} → ${field}`, fromDir, repoDir })\n if (finding) findings.push(finding)\n }\n }\n\n // The lane insurance's defect actually used. `resolutions` is yarn/npm's\n // spelling of the same authority; both silently outrank every range above.\n const overrideBlocks: Array<[string, unknown]> = [\n ['pnpm.overrides', (manifest.pnpm as { overrides?: unknown } | undefined)?.overrides],\n ['resolutions', manifest.resolutions],\n ]\n for (const [label, block] of overrideBlocks) {\n if (!block || typeof block !== 'object') continue\n for (const [name, specifier] of Object.entries(block as Record<string, unknown>)) {\n if (typeof specifier !== 'string') continue\n const finding = judge({\n check: 'override',\n // An override key can carry a range suffix (`foo@1 > bar`); the package\n // name is the leading segment.\n name: overrideKeyName(name),\n specifier,\n where: `${where} → ${label}['${name}']`,\n fromDir,\n repoDir,\n })\n if (finding) findings.push(finding)\n }\n }\n return findings\n}\n\n/** `@scope/pkg@^1 > dep` and `pkg@1` both name `pkg` / `@scope/pkg`. */\nfunction overrideKeyName(key: string): string {\n const head = (key.split('>').pop() ?? key).trim()\n const at = head.lastIndexOf('@')\n return at > 0 ? head.slice(0, at) : head\n}\n\nfunction scanWorkspaceYaml(file: string, repoDir: string): DependencySourceFinding[] {\n const findings: DependencySourceFinding[] = []\n const where = relative(repoDir, file).split(sep).join('/')\n for (const line of readYamlLines(readFileSync(file, 'utf8'))) {\n const section = sectionOf(line)\n if (section !== 'overrides' && section !== 'catalog' && section !== 'catalogs') continue\n if (line.indent === 0 || !line.value) continue\n const finding = judge({\n check: 'override',\n name: overrideKeyName(line.key),\n specifier: line.value,\n where: `${where}:${line.lineNumber} → ${[...line.path, line.key].join('.')}`,\n fromDir: dirname(file),\n repoDir,\n })\n if (finding) findings.push(finding)\n }\n return findings\n}\n\n/**\n * The lockfile is the only file that reports what ACTUALLY resolved. A manifest\n * can be cleaned up while `pnpm-lock.yaml` still resolves a tarball, and the\n * install follows the lockfile.\n *\n * Three shapes carry it, all present in the real insurance-agent lockfile:\n * overrides: '@tangle-network/agent-app': file:./vendor/…-0.45.33.tgz\n * importers: specifier: file:vendor/…-0.45.33.tgz\n * packages: '@tangle-network/agent-app@file:vendor/…-0.45.33.tgz':\n */\nfunction scanLockfile(file: string, repoDir: string): DependencySourceFinding[] {\n const findings: DependencySourceFinding[] = []\n const where = relative(repoDir, file).split(sep).join('/')\n const fromDir = dirname(file)\n const seen = new Set<string>()\n const push = (finding: DependencySourceFinding | null): void => {\n if (!finding) return\n const key = `${finding.name}|${finding.specifier}`\n if (seen.has(key)) return\n seen.add(key)\n findings.push(finding)\n }\n\n for (const line of readYamlLines(readFileSync(file, 'utf8'))) {\n const section = sectionOf(line)\n if (section === 'overrides' && line.indent > 0 && line.value) {\n push(judge({\n check: 'lockfile',\n name: overrideKeyName(line.key),\n specifier: line.value,\n where: `${where}:${line.lineNumber} → overrides`,\n fromDir,\n repoDir,\n }))\n continue\n }\n if (section === 'importers' && line.key === 'specifier' && line.value) {\n push(judge({\n check: 'lockfile',\n name: line.path[line.path.length - 1] ?? '(unknown)',\n specifier: line.value,\n where: `${where}:${line.lineNumber} → importers`,\n fromDir,\n repoDir,\n }))\n continue\n }\n if ((section === 'packages' || section === 'snapshots') && line.indent === 2 && !line.value) {\n const parsed = parsePackageKey(line.key)\n if (!parsed) continue\n push(judge({\n check: 'lockfile',\n name: parsed.name,\n specifier: parsed.reference,\n where: `${where}:${line.lineNumber} → ${section}`,\n fromDir,\n repoDir,\n }))\n }\n }\n return findings\n}\n\n/**\n * `'@scope/name@file:vendor/x.tgz'` → name + reference.\n *\n * The peer-suffix is stripped FIRST: a snapshot key looks like\n * `@radix-ui/react-dialog@1.1.23(@types/react@19.2.17)`, and the last `@` in\n * that string sits inside the suffix, not at the version boundary.\n */\nfunction parsePackageKey(key: string): { name: string; reference: string } | null {\n const withoutPeers = key.replace(/\\(.*\\)$/, '')\n const at = withoutPeers.lastIndexOf('@')\n if (at <= 0) return null\n return { name: withoutPeers.slice(0, at), reference: withoutPeers.slice(at + 1) }\n}\n\n/**\n * pnpm's virtual store encodes a dependency's SOURCE in the directory name:\n * a registry package is `@tangle-network+agent-app@0.45.33`, while the\n * vendored one installed as\n * `file+vendor+agent-app+tangle-network-agent-app-0.45.33.tgz`.\n *\n * This is install evidence that survives a tidied manifest and a regenerated\n * lockfile, which is why it is scanned separately rather than trusted to follow\n * from them.\n */\nfunction scanVirtualStore(\n repoDir: string,\n modulesDir: string,\n): DependencySourceFinding[] {\n const store = join(repoDir, modulesDir, '.pnpm')\n if (!existsSync(store)) return []\n const findings: DependencySourceFinding[] = []\n for (const entry of readdirSync(store, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name === modulesDir) continue\n const protocolMatch = /^(file|link|portal|git|https?)\\+/.exec(entry.name)\n if (!protocolMatch) continue\n const protocol = protocolMatch[1] as string\n // pnpm encodes `/` as `+` for the whole remainder of a path-protocol key.\n const encoded = entry.name.slice(protocol.length + 1)\n const name = installedPackageName(join(store, entry.name), modulesDir)\n const where = `${modulesDir}/.pnpm/${entry.name}`\n\n if (protocol === 'file' || protocol === 'link' || protocol === 'portal') {\n const path = encoded.split('+').join('/')\n const specifier = `${protocol}:${path}`\n const finding = judge({\n check: 'installed',\n name: name ?? path,\n specifier,\n where,\n // A virtual-store path is written relative to the install root.\n fromDir: repoDir,\n repoDir,\n })\n if (finding) findings.push(finding)\n continue\n }\n findings.push({\n check: 'installed',\n name,\n specifier: encoded.split('+++').join('://').split('+').join('/'),\n protocol: protocol === 'git' ? 'git' : 'remote',\n where,\n detail: 'is INSTALLED from a git ref or remote URL rather than the registry. The manifests may '\n + 'read clean — this is what the tree on disk actually holds. Reinstall from a published range.',\n })\n }\n return findings\n}\n\n/**\n * The package a virtual-store entry belongs to: the one REAL directory under\n * its nested module dir (its dependencies are all symlinks).\n *\n * The nested level takes `modulesDir` too, not a hardcoded `node_modules`.\n * In a real install both levels ARE `node_modules`, so nothing changes there —\n * but a COMMITTED fixture cannot carry a `node_modules` path segment at any\n * depth, because every repo gitignores that name. Hardcoding it here made this\n * module's own calibration tree un-committable, which is the failure the\n * `fixture_modules` convention exists to prevent, reintroduced one level down.\n */\nfunction installedPackageName(entryDir: string, modulesDir: string): string | null {\n const nested = join(entryDir, modulesDir)\n if (!existsSync(nested)) return null\n for (const child of readdirSync(nested, { withFileTypes: true })) {\n if (child.name === '.bin' || child.isSymbolicLink()) continue\n if (!child.isDirectory()) continue\n if (child.name.startsWith('@')) {\n const scopeDir = join(nested, child.name)\n for (const scoped of readdirSync(scopeDir, { withFileTypes: true })) {\n if (scoped.isSymbolicLink() || !scoped.isDirectory()) continue\n if (existsSync(join(scopeDir, scoped.name, 'package.json'))) return `${child.name}/${scoped.name}`\n }\n continue\n }\n if (existsSync(join(nested, child.name, 'package.json'))) return child.name\n }\n return null\n}\n\n/* ---------------------------------------------------------------------------\n * On-disk integrity — and an honest account of its ceiling.\n *\n * WHAT WAS CONSIDERED AND REJECTED. Full verification means comparing the\n * installed bytes against the PUBLISHED tarball. `pnpm-lock.yaml` records that\n * tarball's `integrity` (`sha512-…`) and nothing about its contents, and the\n * tarball is not on disk: pnpm unpacks into a content-addressed store and keeps\n * the per-file digests in an INDEX whose location and format change between\n * pnpm majors — pnpm 10 writes JSON under `store/v10/index/`, pnpm 11 writes one\n * SQLite database (measured: `~/.local/share/pnpm/store/v11/index.db`, 57 MB).\n * Reading it means a SQLite dependency plus a coupling to store internals, in a\n * package that ships zero runtime dependencies; re-fetching the tarball means\n * network access inside a gate that must run offline in seconds. So full\n * verification is NOT affordable and is not attempted.\n *\n * WHAT IS AFFORDABLE. The store is CONTENT-ADDRESSED: a file's bytes live at\n * `<store>/files/<first 2 hex>/<rest>` of their own sha512, a layout that has\n * survived v3 → v10 → v11 while the index format changed twice. So a file's\n * bytes can be asked one question with no dependency and no network — \"has this\n * store ever held these bytes?\" Bytes that came out of a package pnpm installed\n * are in there by construction. Bytes typed in afterwards are not.\n *\n * Two steps, because hashing 30,000 files per run would not be cheap:\n * 1. `nlink > 1` — the file shares an inode, so it IS a store blob. No hash.\n * This settles ~99% of files at the cost of one `lstat`.\n * 2. Everything else is hashed and looked up in the store CAS.\n *\n * THE HARD-LINK COUNT ALONE IS NOT THE SIGNAL, and believing it was is the\n * mistake this design corrects. An earlier cut reported any package holding\n * both linked and unlinked files as tampered. Measured across five real fleet\n * repos it fired once — on legal-agent's `@tangle-network/agent-interface@0.32.0`,\n * whose `dist/environment-provider.js` is `nlink == 1` — and that finding was\n * FALSE: `npm pack @tangle-network/agent-interface@0.32.0` yields the identical\n * 11-byte `export {};`. pnpm simply wrote that copy instead of linking it. A\n * 1-in-5-repos false alarm is a gate people switch off, and the CAS lookup is\n * what tells the two apart: those bytes ARE in the store.\n *\n * MEASURED after adding the lookup: 5 fleet repos, 0 findings, 0 false alarms.\n *\n * WHAT IT CANNOT CATCH, precisely — do not read a clean integrity line as more:\n * 1. A patch whose content came from ANOTHER package or version ALREADY in\n * this store. CAS membership proves \"this store has held these bytes\", not\n * \"these bytes belong to this package at this version\". The measured\n * defect — a `dist/spend/index.d.ts` overwritten with a NEWER version's\n * copy — is caught only when that newer version was never installed on the\n * machine. This is the real ceiling; closing it needs the per-file index.\n * 2. An edit that PRESERVES the inode (`> file`, `cp onto`). The link\n * survives and the STORE copy is corrupted with it, so both agree.\n * 3. A tampered store: everything resolves, everything agrees, all wrong.\n * 4. Anything at all when the store cannot be located — npm, yarn, a store on\n * another machine, a pruned CI cache. That is reported as NOT VERIFIED\n * rather than as a pass, and it is never a finding, because failing every\n * non-pnpm consumer forever is how a gate gets deleted.\n * ------------------------------------------------------------------------ */\n\n/**\n * Every content-addressed `files/` directory this install could have linked\n * from, read out of `node_modules/.modules.yaml` — pure `fs`, no `pnpm store\n * path` subprocess.\n *\n * More than one, because a long-lived machine has several store majors side by\n * side and an existing tree can be linked from an older one: measured on\n * legal-agent, `dist/index.js` resolves in `store/v10/files` while\n * `dist/environment-provider.js` resolves in `store/v10/v11/files`. Checking\n * only the configured one reports a linked file as unknown.\n */\nfunction locateStoreCas(repoDir: string, modulesDir: string): string[] {\n const modulesState = join(repoDir, modulesDir, '.modules.yaml')\n if (!existsSync(modulesState)) return []\n let configured: string | undefined\n try {\n const text = readFileSync(modulesState, 'utf8')\n // pnpm 11 writes JSON under the .yaml name; older versions write YAML.\n configured = (/\"storeDir\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/.exec(text)?.[1]\n ?? /^storeDir:\\s*(.+)$/m.exec(text)?.[1])?.trim()\n } catch {\n return []\n }\n if (!configured) return []\n const root = unquote(configured.replace(/\\\\\\\\/g, '\\\\'))\n const candidates = new Set<string>([root, dirname(root)])\n for (const base of [root, dirname(root)]) {\n try {\n for (const entry of readdirSync(base, { withFileTypes: true })) {\n if (entry.isDirectory() && /^v\\d+$/.test(entry.name)) candidates.add(join(base, entry.name))\n }\n } catch { /* an unreadable store is simply not a candidate */ }\n }\n return [...candidates].map((dir) => join(dir, 'files')).filter((dir) => existsSync(dir))\n}\n\nfunction collectFiles(dir: string, modulesDir: string, out: string[] = []): string[] {\n let entries: import('node:fs').Dirent[]\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return out\n }\n for (const entry of entries) {\n // A package's own nested `node_modules` holds pnpm-GENERATED `.bin` shims\n // and symlinks, never store content. Including it made 3 of this repo's 8\n // installed @tangle-network packages look partially replaced.\n if (entry.name === modulesDir) continue\n const full = join(dir, entry.name)\n if (entry.isSymbolicLink()) continue\n if (entry.isDirectory()) collectFiles(full, modulesDir, out)\n else if (entry.isFile()) out.push(full)\n }\n return out\n}\n\n/** Does any reachable store hold these exact bytes? `-exec` is pnpm's suffix\n * for the executable-mode copy of the same content. */\nfunction storeHolds(casDirs: readonly string[], bytes: Buffer): boolean {\n const hex = createHash('sha512').update(bytes).digest('hex')\n const tail = join(hex.slice(0, 2), hex.slice(2))\n return casDirs.some((dir) => existsSync(join(dir, tail)) || existsSync(join(dir, `${tail}-exec`)))\n}\n\n/**\n * Check each installed package under `scope` against the content-addressed\n * store it was installed from. Returns coverage alongside findings, because a\n * pass that verified nothing must not render like a pass that verified\n * everything.\n */\nexport function checkInstalledIntegrity(args: {\n repoDir: string\n modulesDir: string\n scope: string\n}): { coverage: InstalledIntegrityCoverage; findings: DependencySourceFinding[] } {\n const virtualStore = join(args.repoDir, args.modulesDir, '.pnpm')\n const casDirs = locateStoreCas(args.repoDir, args.modulesDir)\n const findings: DependencySourceFinding[] = []\n let packagesExamined = 0\n let filesExamined = 0\n let filesHashed = 0\n\n if (casDirs.length > 0 && existsSync(virtualStore)) {\n for (const entry of readdirSync(virtualStore, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name === args.modulesDir) continue\n const entryDir = join(virtualStore, entry.name)\n const name = installedPackageName(entryDir, args.modulesDir)\n if (!name || !name.startsWith(args.scope)) continue\n const packageDir = join(entryDir, args.modulesDir, name)\n if (!existsSync(packageDir)) continue\n\n const files = collectFiles(packageDir, args.modulesDir)\n if (files.length === 0) continue\n packagesExamined += 1\n filesExamined += files.length\n\n const foreign: string[] = []\n for (const file of files) {\n try {\n // A shared inode IS a store blob — settled without reading the file.\n if (lstatSync(file).nlink > 1) continue\n filesHashed += 1\n if (storeHolds(casDirs, readFileSync(file))) continue\n foreign.push(relative(packageDir, file).split(sep).join('/'))\n } catch { /* a file that vanished mid-walk is not evidence */ }\n }\n if (foreign.length === 0) continue\n\n const shown = foreign.slice(0, 5)\n findings.push({\n check: 'installed',\n name,\n specifier: null,\n protocol: null,\n where: `${args.modulesDir}/.pnpm/${entry.name} → ${shown.join(', ')}`\n + `${foreign.length > shown.length ? ` (+${foreign.length - shown.length} more)` : ''}`,\n detail: `holds ${foreign.length} file(s) whose bytes this pnpm store has never contained — the `\n + 'shape of a package HAND-PATCHED after install. The version on disk, the manifest and the '\n + 'lockfile all still agree; only the bytes do not, which is how a product typechecks green '\n + 'against an API its declared dependency does not ship. Delete the tree and reinstall '\n + `(\\`rm -rf ${args.modulesDir} && pnpm install --frozen-lockfile\\`), then publish whatever `\n + 'change made the patch look necessary.',\n })\n }\n }\n\n return {\n coverage: {\n basis: 'store-cas',\n storeLocated: casDirs.length > 0,\n packagesExamined,\n filesExamined,\n filesHashed,\n },\n findings,\n }\n}\n\n/** Audit one repository for dependencies whose source is not the registry. */\nexport function checkDependencySources(options: CheckDependencySourcesOptions): DependencySourceReport {\n const repoDir = resolve(options.repoDir)\n const { scope = '@tangle-network/', modulesDir = 'node_modules', exclude = [] } = options\n\n const seen = { manifests: [] as string[], tarballs: [] as string[] }\n walkSourceTree(repoDir, repoDir, exclude, seen)\n\n const findings: DependencySourceFinding[] = []\n for (const manifest of seen.manifests) findings.push(...scanManifest(manifest, repoDir))\n\n const workspaceYaml = join(repoDir, 'pnpm-workspace.yaml')\n if (existsSync(workspaceYaml)) findings.push(...scanWorkspaceYaml(workspaceYaml, repoDir))\n\n const lockfile = join(repoDir, 'pnpm-lock.yaml')\n const lockfileScanned = existsSync(lockfile)\n if (lockfileScanned) findings.push(...scanLockfile(lockfile, repoDir))\n\n for (const tarball of seen.tarballs) {\n findings.push({\n check: 'vendored-tarball',\n name: null,\n specifier: null,\n protocol: 'tarball',\n where: relative(repoDir, tarball).split(sep).join('/'),\n detail: 'is a PACKED TARBALL committed into the source tree. Even when nothing points at it today, '\n + 'it is a build nobody can reproduce from the registry sitting one `file:` line away from '\n + `shipping. Delete it; if ${basename(tarball)} is genuinely test data, move it under a path `\n + 'passed to `--exclude`.',\n })\n }\n\n findings.push(...scanVirtualStore(repoDir, modulesDir))\n const integrity = checkInstalledIntegrity({ repoDir, modulesDir, scope })\n findings.push(...integrity.findings)\n\n return {\n repoDir,\n manifestsScanned: seen.manifests.length,\n lockfileScanned,\n integrity: integrity.coverage,\n findings,\n ok: findings.length === 0,\n }\n}\n\nconst CHECK_LABEL: Record<DependencySourceCheck, string> = {\n declared: 'DECLARED',\n override: 'OVERRIDE',\n lockfile: 'LOCKFILE',\n 'vendored-tarball': 'TARBALL',\n installed: 'INSTALLED',\n}\n\n/** One finding rendered as the failure a reader has to act on. */\nexport function describeDependencySourceFinding(finding: DependencySourceFinding): string {\n const subject = finding.name\n ? `${finding.name}${finding.specifier ? ` (${finding.specifier})` : ''}`\n : finding.where\n return `DEPENDENCY SOURCE: ${subject} ${finding.detail}\\n at ${finding.where}`\n}\n\nexport function formatDependencySourceReport(report: DependencySourceReport): string {\n const { integrity } = report\n // Printed on EVERY report, clean or not: \"verified nothing\" and \"verified\n // everything and found nothing\" are otherwise the same green line, which is\n // this gate's own failure class turned on itself.\n const integrityLine = integrity.storeLocated\n ? ` integrity (${integrity.basis}): ${integrity.packagesExamined} package(s), `\n + `${integrity.filesExamined} file(s), ${integrity.filesHashed} hashed against the store`\n : ` integrity (${integrity.basis}): NOT VERIFIED — no pnpm content-addressed store is reachable `\n + 'from this tree, so no installed bytes were checked against anything'\n const lines = [\n 'dependency sources',\n '',\n ` scanned ${report.manifestsScanned} manifest(s), `\n + `${report.lockfileScanned ? 'pnpm-lock.yaml' : 'no lockfile'}`,\n integrityLine,\n '',\n ]\n if (report.ok) {\n lines.push(\n integrity.storeLocated && integrity.packagesExamined > 0\n ? ' ok every declared source is the registry, and every installed byte came from the store'\n : ' ok every declared source is the registry — installed bytes UNVERIFIED (see above)',\n )\n } else {\n for (const finding of report.findings) {\n lines.push(` FAIL [${CHECK_LABEL[finding.check]}] ${describeDependencySourceFinding(finding)}`, '')\n }\n }\n return lines.join('\\n')\n}\n"],"mappings":";AAAA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,WAAAC,UAAS,QAAAC,aAAY;;;ACD9B,SAAS,kBAAkB;AAC3B,SAAS,YAAY,WAAW,cAAc,aAAa,gBAAgB;AAC3E,SAAS,UAAU,SAAS,YAAY,MAAM,UAAU,SAAS,WAAW;AAoD5E,IAAM,UAAU;AAUT,SAAS,4BAA4B,WAA6C;AACvF,QAAM,OAAO,UAAU,KAAK;AAC5B,MAAI,KAAK,WAAW,YAAY,EAAG,QAAO;AAC1C,MAAI,KAAK,WAAW,UAAU,EAAG,QAAO;AACxC,aAAW,YAAY,CAAC,SAAS,SAAS,SAAS,GAAY;AAC7D,QAAI,KAAK,WAAW,QAAQ,GAAG;AAC7B,YAAM,OAAO,KAAK,MAAM,SAAS,MAAM;AACvC,UAAI,QAAQ,KAAK,IAAI,EAAG,QAAO;AAC/B,aAAO,SAAS,MAAM,GAAG,EAAE;AAAA,IAC7B;AAAA,EACF;AACA,MAAI,+CAA+C,KAAK,IAAI,EAAG,QAAO;AACtE,MAAI,gCAAgC,KAAK,IAAI,EAAG,QAAO;AACvD,MAAI,eAAe,KAAK,IAAI,EAAG,QAAO,QAAQ,KAAK,KAAK,MAAM,MAAM,EAAE,CAAC,KAAK,EAAE,IAAI,YAAY;AAG9F,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name","join","join","existsSync","readFileSync","dirname"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/signoff/config.ts","../src/signoff/run.ts","../src/signoff/node-version.ts","../src/signoff/workflow-pin.ts","../src/signoff/exec.ts","../src/signoff/schedule.ts","../src/signoff/seeds.ts","../src/signoff/store.ts","../src/signoff/workspace.ts","../src/signoff/report.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { z } from 'zod'\nimport type { LoadedSignoffConfig, SignoffConfig, SignoffStepSpec } from './types'\n\n/**\n * Where the step list comes from.\n *\n * It is declared by the repo, never hardcoded here, because the three workflows\n * this has to reproduce do not share a shape: tax-agent filters its install to\n * one workspace package and runs a Python toolkit suite; legal-agent runs a\n * react-router typegen and a Worker startup check; agent-app runs a named\n * incident-class gate, a generated-project test and knip. A checker that\n * hardcodes any one of those is wrong for the other two.\n *\n * Three sources, in order:\n * 1. `signoff.config.mjs` (or `.js`) — the full surface, including per-step\n * `env`, `needs` and shuffle specs.\n * 2. a `signoff` key in `package.json` — the same shape, JSON-only.\n * 3. derived from the repo's own `scripts`, so a repo gets a real gate before\n * anyone writes a config. The derivation is documented below and its origin\n * is stamped into the proof, because a derived run is a weaker claim than a\n * declared one.\n */\n\nconst SIGNOFF_CONFIG_FILES: readonly string[] = ['signoff.config.mjs', 'signoff.config.js']\n\nconst shuffleSchema = z.object({\n runs: z.number().int().positive().optional(),\n seeds: z.array(z.number().int()).optional(),\n args: z.array(z.string()).optional(),\n})\n\nconst stepSchema = z.object({\n name: z.string().min(1),\n run: z.string().min(1),\n cwd: z.string().optional(),\n env: z.record(z.string(), z.string()).optional(),\n needs: z.array(z.string()).optional(),\n timeoutMs: z.number().int().positive().optional(),\n shuffle: z.union([z.boolean(), shuffleSchema]).optional(),\n})\n\nconst configSchema = z.object({\n install: z\n .object({\n run: z.string().min(1).optional(),\n storeDirFlag: z.string().nullable().optional(),\n storeEnv: z.string().nullable().optional(),\n cwd: z.string().optional(),\n timeoutMs: z.number().int().positive().optional(),\n env: z.record(z.string(), z.string()).optional(),\n })\n .optional(),\n steps: z.array(stepSchema).min(1),\n maxParallel: z.number().int().positive().optional(),\n env: z.record(z.string(), z.string()).optional(),\n nodeVersion: z.string().min(1).optional(),\n carryFiles: z.array(z.string()).optional(),\n cacheDir: z.string().optional(),\n storeGenerations: z.number().int().positive().optional(),\n})\n\nfunction describeIssues(error: z.ZodError, where: string): string {\n const lines = error.issues.map((issue) => ` ${issue.path.join('.') || '(root)'}: ${issue.message}`)\n return `signoff: ${where} is not a valid config:\\n${lines.join('\\n')}`\n}\n\nexport function parseSignoffConfig(value: unknown, where: string): SignoffConfig {\n const result = configSchema.safeParse(value)\n if (!result.success) throw new Error(describeIssues(result.error, where))\n return result.data as SignoffConfig\n}\n\n/**\n * The script → step derivation, and the dependency edges it asserts.\n *\n * The edges are the speed lever, so each one is a claim about the repo:\n * typecheck, the suite, the build and knip are ASSUMED to read source and not\n * each other's output, so they run concurrently. Only `test:generated`\n * genuinely consumes a build artifact, so only it declares a dependency.\n *\n * **That assumption is a guess, and it is wrong for at least one real repo.**\n * agent-app's own suite copies `dist/` into a generated project while `tsup`\n * (`clean: true`) is deleting it, which fails loudly as \"dist/ not built\" and\n * quietly as a half-copied package. A repo whose suite reads build output MUST\n * declare `needs: ['build']` on it in a `signoff.config.mjs`; the derivation\n * cannot see that from a script name, which is one more reason a derived run is\n * a weaker claim than a declared one.\n *\n * `build:check` supersedes `build` when both exist (legal-agent's `build:check`\n * is `pnpm build && …`, so running both builds twice for one verdict).\n */\nconst DERIVED_STEPS: readonly {\n readonly script: string\n readonly name: string\n readonly shuffle?: boolean\n readonly supersedes?: string\n readonly needsBuild?: boolean\n}[] = [\n { script: 'peer-check', name: 'peer floors' },\n { script: 'typecheck', name: 'typecheck' },\n { script: 'test:gates', name: 'incident-class gates' },\n { script: 'test', name: 'unit tests', shuffle: true },\n { script: 'build', name: 'build' },\n { script: 'build:check', name: 'build + worker checks', supersedes: 'build' },\n { script: 'test:generated', name: 'generated projects', needsBuild: true },\n { script: 'knip', name: 'dead-surface (knip)' },\n]\n\nexport function deriveSignoffConfig(scripts: Readonly<Record<string, string>>): {\n readonly config: SignoffConfig\n readonly used: readonly string[]\n} {\n const present = DERIVED_STEPS.filter((candidate) => scripts[candidate.script] !== undefined)\n const superseded = new Set(present.map((candidate) => candidate.supersedes).filter((name): name is string => !!name))\n const kept = present.filter((candidate) => !superseded.has(candidate.script))\n const buildStep = kept.find((candidate) => candidate.script === 'build' || candidate.script === 'build:check')\n\n const steps: SignoffStepSpec[] = kept.map((candidate) => ({\n name: candidate.name,\n run: `pnpm run ${candidate.script}`,\n ...(candidate.shuffle ? { shuffle: true as const } : {}),\n ...(candidate.needsBuild && buildStep ? { needs: [buildStep.name] } : {}),\n }))\n\n if (steps.length === 0) {\n throw new Error(\n 'signoff: no config and no recognizable scripts. Add a `signoff.config.mjs` naming the steps ' +\n `this repo's CI runs, or a package.json \"signoff\" key. Recognized script names: ` +\n `${DERIVED_STEPS.map((candidate) => candidate.script).join(', ')}.`,\n )\n }\n return { config: { steps }, used: kept.map((candidate) => candidate.script) }\n}\n\nexport interface LoadSignoffConfigOptions {\n readonly repoRoot: string\n /** Explicit config path. Missing file is an error, never a silent fallback. */\n readonly configPath?: string\n}\n\nexport async function loadSignoffConfig(options: LoadSignoffConfigOptions): Promise<LoadedSignoffConfig> {\n const { repoRoot, configPath } = options\n\n if (configPath !== undefined) {\n const abs = resolve(repoRoot, configPath)\n if (!existsSync(abs)) throw new Error(`signoff: no config at ${abs}`)\n return { config: await importConfig(abs), origin: { kind: 'file', path: abs } }\n }\n\n for (const candidate of SIGNOFF_CONFIG_FILES) {\n const abs = join(repoRoot, candidate)\n if (existsSync(abs)) return { config: await importConfig(abs), origin: { kind: 'file', path: abs } }\n }\n\n const pkgPath = join(repoRoot, 'package.json')\n if (!existsSync(pkgPath)) {\n throw new Error(`signoff: ${repoRoot} has no package.json, no signoff.config.mjs, and nothing to derive from.`)\n }\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as {\n signoff?: unknown\n scripts?: Record<string, string>\n }\n if (pkg.signoff !== undefined) {\n return { config: parseSignoffConfig(pkg.signoff, `${pkgPath} \"signoff\"`), origin: { kind: 'package-json', path: pkgPath } }\n }\n\n const derived = deriveSignoffConfig(pkg.scripts ?? {})\n return { config: derived.config, origin: { kind: 'derived', path: pkgPath, scripts: derived.used } }\n}\n\nasync function importConfig(abs: string): Promise<SignoffConfig> {\n const mod: unknown = await import(pathToFileURL(abs).href)\n const value = (mod as { default?: unknown }).default\n if (value === undefined) throw new Error(`signoff: ${abs} must have a default export`)\n return parseSignoffConfig(value, abs)\n}\n","import { spawnSync } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { availableParallelism, homedir } from 'node:os'\nimport { basename, join, resolve } from 'node:path'\nimport { loadSignoffConfig } from './config'\nimport { assertNodeVersion, resolveNodeRequirement, type NodeVersionRequirement } from './node-version'\nimport { runCommand, type CommandResult } from './exec'\nimport { runGraph, validateGraph, type TaskOutcome } from './schedule'\nimport { assertShuffleArgsReachTheRunner, newSeedBase, planAttempts } from './seeds'\nimport { resolveStore } from './store'\nimport { materializeCleanTree, removeCleanTree, repoRootOf, type CleanTree } from './workspace'\nimport type {\n SignoffAttempt,\n SignoffEvent,\n SignoffHostFacts,\n SignoffInstallResult,\n SignoffReport,\n SignoffSource,\n SignoffStepResult,\n SignoffStepSpec,\n} from './types'\n\n/**\n * The sign-off run: reproduce a clean CI environment, then go further.\n *\n * Order matters and each stage exists for a failure this fleet actually paid\n * for:\n * 1. a pristine checkout (`workspace.ts`) — no warm `node_modules`, no Vite\n * cache, because that is the entire mechanical difference between \"green\n * locally\" and \"red in CI\";\n * 2. `--frozen-lockfile` into a store keyed on the lockfile (`store.ts`) — the\n * clean install CI does, without paying the download twice;\n * 3. the repo's declared steps (`config.ts`), run as a graph rather than a line\n * (`schedule.ts`), with the suite re-run under randomized file order and\n * recorded seeds (`seeds.ts`) — the part CI does not do at all.\n *\n * Nothing about a failure is inferred. Every step reports its command, exit\n * code, duration, seed and captured output.\n */\n\nexport interface RunSignoffOptions {\n /** Any directory inside the repo. Defaults to the process cwd. */\n readonly repoDir?: string\n readonly configPath?: string\n /** Default `working-tree` — verify what you are about to commit. */\n readonly source?: SignoffSource\n /** Run every step even after one fails. Default false. */\n readonly keepGoing?: boolean\n /** Base seed. Pass a previous run's to reproduce it exactly. */\n readonly seed?: number\n readonly maxParallel?: number\n readonly cacheDir?: string\n /** Override every shuffled step's run count. */\n readonly shuffleRuns?: number\n /** Keep the clean tree for inspection instead of removing it. */\n readonly keepWorkspace?: boolean\n readonly onEvent?: (event: SignoffEvent) => void\n}\n\nconst DEFAULT_CACHE_DIR = join(homedir(), '.cache', 'agent-app-signoff')\n\nfunction hostFacts(treePath: string, requirement: NodeVersionRequirement | null): SignoffHostFacts {\n const pm = spawnSync('pnpm', ['--version'], { cwd: treePath, encoding: 'utf8' })\n return {\n node: process.version,\n nodePinned: requirement?.declared ?? null,\n nodePinSource: requirement?.source ?? null,\n packageManager: pm.status === 0 ? `pnpm ${pm.stdout.trim()}` : 'pnpm (not resolvable)',\n platform: process.platform,\n arch: process.arch,\n cpus: availableParallelism(),\n }\n}\n\n/** Successful steps keep only a tail; a passing 3,000-test run is not evidence. */\nconst SUCCESS_OUTPUT_TAIL = 4_000\n\nfunction toAttempt(result: CommandResult, seed: number | null, ok: boolean): SignoffAttempt {\n return {\n command: result.command,\n seed,\n exitCode: result.exitCode,\n signal: result.signal,\n durationMs: result.durationMs,\n timedOut: result.timedOut,\n output: ok ? result.output.slice(-SUCCESS_OUTPUT_TAIL) : result.output,\n outputTruncated: result.truncated || (ok && result.output.length > SUCCESS_OUTPUT_TAIL),\n }\n}\n\nfunction buildEnv(\n base: Readonly<Record<string, string | undefined>>,\n layers: readonly (Readonly<Record<string, string>> | undefined)[],\n): Record<string, string | undefined> {\n const env: Record<string, string | undefined> = { ...base }\n for (const layer of layers) {\n if (layer) Object.assign(env, layer)\n }\n return env\n}\n\n/** Where the store flag goes: after the subcommand, so `pnpm install X --store-dir Y` stays valid. */\nfunction withStoreDir(command: string, flag: string | null | undefined, storeDir: string): string {\n if (flag === null) return command\n return `${command} ${flag ?? '--store-dir'} ${JSON.stringify(storeDir)}`\n}\n\nexport async function runSignoff(options: RunSignoffOptions = {}): Promise<SignoffReport> {\n const startedAt = new Date()\n const wallStart = Date.now()\n const repoDir = resolve(options.repoDir ?? process.cwd())\n const repoRoot = repoRootOf(repoDir)\n const { config, origin } = await loadSignoffConfig({ repoRoot, configPath: options.configPath })\n\n // Fail before materializing anything: a bad graph is a config error, and\n // paying for an install to learn that is a waste of the speed this exists for.\n validateGraph(config.steps.map((step) => ({ name: step.name, needs: step.needs })))\n assertShuffleArgsReachTheRunner(config.steps)\n const nodeRequirement = resolveNodeRequirement(repoRoot, config.nodeVersion)\n assertNodeVersion(nodeRequirement)\n\n const source = options.source ?? 'working-tree'\n const cacheDir = resolve(options.cacheDir ?? config.cacheDir ?? DEFAULT_CACHE_DIR)\n // The tree lives under the same root as the stores on purpose: pnpm hardlinks\n // from the store into `node_modules`, and a store on another filesystem\n // silently degrades to a full copy.\n const treePath = join(cacheDir, 'trees', `${basename(repoRoot)}-${process.pid}`)\n\n let tree: CleanTree | null = null\n try {\n tree = materializeCleanTree({ repoDir: repoRoot, dest: treePath, source, carryFiles: config.carryFiles })\n options.onEvent?.({ kind: 'tree', path: tree.path, head: tree.head, dirty: tree.dirty })\n\n const store = resolveStore({ treePath: tree.path, cacheDir, generations: config.storeGenerations })\n options.onEvent?.({ kind: 'store', storeDir: store.storeDir, cacheHit: store.hit, cacheKey: store.cacheKey })\n\n const installSpec = config.install ?? {}\n const installCwd = join(tree.path, installSpec.cwd ?? '.')\n const installCommand = withStoreDir(\n installSpec.run ?? 'pnpm install --frozen-lockfile',\n installSpec.storeDirFlag,\n store.storeDir,\n )\n const storeEnvName = installSpec.storeEnv === null ? null : installSpec.storeEnv ?? 'NPM_CONFIG_STORE_DIR'\n const sharedEnv = buildEnv(process.env, [\n // Parity with CI: a runner that behaves differently under `CI` (vitest's\n // reporter, wrangler's prompts) must behave that way here too.\n { CI: 'true' },\n config.env,\n storeEnvName === null ? undefined : { [storeEnvName]: store.storeDir },\n ])\n\n options.onEvent?.({ kind: 'install-start', command: installCommand })\n const installResult = await runCommand({\n command: installCommand,\n cwd: installCwd,\n env: buildEnv(sharedEnv, [installSpec.env]),\n timeoutMs: installSpec.timeoutMs,\n })\n options.onEvent?.({ kind: 'install-end', exitCode: installResult.exitCode, durationMs: installResult.durationMs })\n\n const install: SignoffInstallResult = {\n command: installCommand,\n storeDir: store.storeDir,\n cacheKey: store.cacheKey,\n cacheHit: store.hit,\n keyedOn: store.keyedOn,\n exitCode: installResult.exitCode,\n durationMs: installResult.durationMs,\n output: installResult.exitCode === 0 ? installResult.output.slice(-SUCCESS_OUTPUT_TAIL) : installResult.output,\n outputTruncated: installResult.truncated,\n }\n\n const host = hostFacts(tree.path, nodeRequirement)\n const seedBase = options.seed ?? newSeedBase()\n\n if (installResult.exitCode !== 0) {\n // Every step is unrunnable, and saying so is the honest report. A gate\n // that reports \"0 failures\" because it never ran anything is the failure\n // mode this whole module exists to prevent.\n return finish({\n ok: false,\n startedAt,\n wallStart,\n tree,\n origin,\n host,\n install,\n steps: config.steps.map(\n (step): SignoffStepResult => ({\n name: step.name,\n status: 'skipped',\n attempts: [],\n durationMs: 0,\n startedAtMs: null,\n finishedAtMs: null,\n }),\n ),\n seedBase,\n keepGoing: options.keepGoing ?? false,\n workspaceRetained: options.keepWorkspace ?? false,\n source,\n options,\n })\n }\n\n const treeRoot = tree.path\n const outcomes = await runGraph<SignoffStepSpec, readonly SignoffAttempt[]>({\n nodes: config.steps,\n maxParallel: options.maxParallel ?? config.maxParallel ?? availableParallelism(),\n keepGoing: options.keepGoing ?? false,\n run: async (step, signal) => {\n const attempts: SignoffAttempt[] = []\n for (const plan of planAttempts(step, seedBase, options.shuffleRuns)) {\n options.onEvent?.({ kind: 'step-start', name: step.name, command: plan.command, seed: plan.seed })\n const result = await runCommand({\n command: plan.command,\n cwd: join(treeRoot, step.cwd ?? '.'),\n env: buildEnv(sharedEnv, [step.env]),\n timeoutMs: step.timeoutMs,\n signal,\n })\n const ok = result.exitCode === 0\n attempts.push(toAttempt(result, plan.seed, ok))\n // Stop at the first failing order: the remaining seeds would report\n // the same defect, and the seed that found it is already recorded.\n if (!ok) {\n emitStepEnd(options, step.name, 'failed', attempts)\n return { ok: false, value: attempts }\n }\n }\n emitStepEnd(options, step.name, 'passed', attempts)\n return { ok: true, value: attempts }\n },\n })\n\n const steps = outcomes.map(toStepResult)\n return finish({\n ok: steps.every((step) => step.status === 'passed'),\n startedAt,\n wallStart,\n tree,\n origin,\n host,\n install,\n steps,\n seedBase,\n keepGoing: options.keepGoing ?? false,\n workspaceRetained: options.keepWorkspace ?? false,\n source,\n options,\n })\n } finally {\n if (tree && !options.keepWorkspace && existsSync(tree.path)) removeCleanTree(tree)\n }\n}\n\n/** Emitted from inside the step, so a watching CLI sees a completion when it\n * happens rather than every completion at the end of the run. */\nfunction emitStepEnd(\n options: RunSignoffOptions,\n name: string,\n status: SignoffStepResult['status'],\n attempts: readonly SignoffAttempt[],\n): void {\n options.onEvent?.({\n kind: 'step-end',\n name,\n status,\n durationMs: attempts.reduce((total, attempt) => total + attempt.durationMs, 0),\n })\n}\n\nfunction toStepResult(outcome: TaskOutcome<readonly SignoffAttempt[]>): SignoffStepResult {\n const attempts = outcome.value ?? []\n const durationMs = attempts.reduce((total, attempt) => total + attempt.durationMs, 0)\n return {\n name: outcome.name,\n status: outcome.status,\n attempts,\n durationMs,\n startedAtMs: outcome.startedAtMs,\n finishedAtMs: outcome.finishedAtMs,\n }\n}\n\ninterface FinishInput {\n readonly ok: boolean\n readonly startedAt: Date\n readonly wallStart: number\n readonly tree: CleanTree\n readonly origin: SignoffReport['configOrigin']\n readonly host: SignoffHostFacts\n readonly install: SignoffInstallResult\n readonly steps: readonly SignoffStepResult[]\n readonly seedBase: number\n readonly keepGoing: boolean\n readonly workspaceRetained: boolean\n readonly source: SignoffSource\n readonly options: RunSignoffOptions\n}\n\nfunction finish(input: FinishInput): SignoffReport {\n const serialMs = input.install.durationMs + input.steps.reduce((total, step) => total + step.durationMs, 0)\n const flags = [\n `--source ${input.source}`,\n `--seed ${input.seedBase}`,\n ...(input.keepGoing ? ['--keep-going'] : []),\n ]\n return {\n ok: input.ok,\n startedAt: input.startedAt.toISOString(),\n repo: {\n root: input.tree.root,\n head: input.tree.head,\n branch: input.tree.branch,\n source: input.source,\n dirty: input.tree.dirty,\n diffSha256: input.tree.diffSha256,\n untrackedFiles: input.tree.untrackedFiles,\n carriedFiles: input.tree.carriedFiles,\n },\n configOrigin: input.origin,\n workspace: input.tree.path,\n workspaceRetained: input.workspaceRetained,\n host: input.host,\n install: input.install,\n steps: input.steps,\n seedBase: input.seedBase,\n wallClockMs: Date.now() - input.wallStart,\n serialMs,\n keepGoing: input.keepGoing,\n reproduce: `agent-app-signoff ${input.tree.root} ${flags.join(' ')}`,\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { resolveWorkflowNodePin } from './workflow-pin'\n\n/**\n * Refuse to sign off on a runtime the product does not ship.\n *\n * CI pins its Node version (`actions/setup-node` with `node-version: 22` in all\n * three fleet workflows). A developer's shell does not — this host runs 24. A\n * local gate that inherits whatever is on `PATH` therefore verifies a runtime\n * nobody deploys, and reports it as the runtime that ships. That is the same\n * failure shape as a number measured in a narrower context than it is\n * presented in, and it is not acceptable in the thing that replaces the merge\n * gate.\n *\n * So the pin is read from the repo and enforced, or it is absent and the report\n * says so. Three sources, in order:\n *\n * - `signoff.config.mjs`'s `nodeVersion` — the explicit declaration.\n * - `.nvmrc` — the pin a repo already keeps for humans.\n * - the `pull_request` workflows' `node-version` (`./workflow-pin`) — the pin\n * CI itself runs on.\n *\n * **The third source was added because the first two were empty on the entire\n * fleet, and that produced a false PASS.** legal-agent `4c0d688` failed CI on\n * `Cannot bundle Node.js built-in \"node:sqlite\"` and this gate signed it off.\n * Reproduced in one installed tree, same bytes: Node 22 fails both files, Node\n * 24 passes both, every time. No `.nvmrc` exists in tax-agent, legal-agent or\n * agent-app; all three pin `node-version: 22` in the workflow being replaced.\n * A gate that replaces a workflow has to read the runtime that workflow pins.\n *\n * A `.nvmrc` and a workflow that disagree is not resolved by preference — it is\n * a refusal, because it means the local gate and CI verify different runtimes,\n * which is the exact defect this module exists to prevent.\n *\n * **`engines.node` is deliberately NOT read.** It is a floor (`\">=18\"`), not a\n * pin, so treating it as one manufactures refusals on every version above the\n * floor — and an unsatisfiable gate does not stop bad work, it gets waived.\n */\n\nexport interface NodeVersionRequirement {\n /** The declared major, e.g. `22`. */\n readonly major: number\n readonly declared: string\n /** Where it came from, for the proof. */\n readonly source: string\n}\n\n/** Leading major from a pin like `22`, `v22.22.3`, `22.22`, `lts/iron` (none). */\nfunction majorOf(raw: string): number | null {\n const match = /^v?(\\d+)(?:\\.|$)/.exec(raw.trim())\n return match?.[1] === undefined ? null : Number.parseInt(match[1], 10)\n}\n\nexport function resolveNodeRequirement(\n repoRoot: string,\n configured?: string,\n): NodeVersionRequirement | null {\n if (configured !== undefined) {\n const major = majorOf(configured)\n if (major === null) {\n throw new Error(\n `signoff: nodeVersion \"${configured}\" does not start with a major version. ` +\n 'Declare a pin like \"22\" or \"22.22.3\".',\n )\n }\n return { major, declared: configured.trim(), source: 'signoff config `nodeVersion`' }\n }\n\n let fromNvmrc: NodeVersionRequirement | null = null\n const nvmrc = join(repoRoot, '.nvmrc')\n if (existsSync(nvmrc)) {\n const raw = readFileSync(nvmrc, 'utf8').trim()\n const major = majorOf(raw)\n // An alias (`lts/iron`) is a pin this module cannot resolve without a\n // network call, so it is reported as no requirement rather than guessed.\n if (major !== null) fromNvmrc = { major, declared: raw, source: '.nvmrc' }\n }\n\n const fromWorkflow = resolveWorkflowNodePin(repoRoot, majorOf)\n if (fromNvmrc && fromWorkflow && fromNvmrc.major !== fromWorkflow.major) {\n throw new Error(\n `signoff: .nvmrc pins Node ${fromNvmrc.declared} and ${fromWorkflow.source} pins ` +\n `${fromWorkflow.declared}. A sign-off that replaces CI cannot verify two runtimes, and picking ` +\n 'one silently would sign off a runtime the other half of the repo says is wrong. Make them agree, ' +\n 'or declare `nodeVersion` in the signoff config.',\n )\n }\n if (fromNvmrc) return fromNvmrc\n if (fromWorkflow) return { ...fromWorkflow, source: fromWorkflow.source }\n return null\n}\n\n/**\n * Throw when the running Node cannot stand in for the declared one.\n *\n * Major-only: a patch difference is not a different runtime, and demanding an\n * exact patch would refuse every host that has not just re-installed.\n */\nexport function assertNodeVersion(requirement: NodeVersionRequirement | null, running = process.version): void {\n if (!requirement) return\n const runningMajor = majorOf(running)\n if (runningMajor === requirement.major) return\n throw new Error(\n `signoff: this repo pins Node ${requirement.declared} (${requirement.source}) and you are running ${running}. ` +\n 'A sign-off that replaces CI has to verify the runtime the product ships, so this refuses rather than ' +\n `reporting a pass it did not earn. Switch with \\`nvm use ${requirement.major}\\`, or change the pin if the ` +\n 'product really has moved.',\n )\n}\n","import { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\n/**\n * Read the Node pin out of the workflows that gate a merge.\n *\n * This exists because of a measured false PASS. legal-agent `4c0d688` was red\n * in CI on two test files — `Cannot bundle Node.js built-in \"node:sqlite\"` —\n * and the sign-off gate signed it off. Same bytes, same lockfile, same\n * hermetic tree: on Node 22 both files fail, on Node 24 both pass, 100% of the\n * time. The runtime was the whole difference, and the gate never saw it because\n * it looked for a pin in exactly two places the fleet does not keep one.\n *\n * At measurement time, none of tax-agent, legal-agent, or agent-app had an\n * `.nvmrc`.\n * All three pinned Node 22 in the merge workflow.\n * Agent App now also pins Node 22 in `.nvmrc`.\n *\n * The workflow fallback reads only `pull_request` checks because those checks\n * can block a merge.\n * Agent App uses `.nvmrc` instead of this fallback.\n * Its publish workflow uses Node 22 for source checks and Node 24 for npm.\n *\n * Nothing here guesses. An expression (`${{ matrix.node }}`) is not a version,\n * a `node-version-file` that does not exist is not a pin, and two merge-gate\n * workflows on different majors is a question this module cannot answer.\n * Each one refuses and names the config key that settles it.\n */\n\nexport interface WorkflowNodePin {\n /** Repo-relative workflow path, for the proof. */\n readonly file: string\n /** The version as written: `22`, `24.18.0`, `v20`. */\n readonly value: string\n /** `node-version`, or the `node-version-file` path it was read through. */\n readonly via: string\n}\n\nconst WORKFLOW_DIR = join('.github', 'workflows')\n\n/** Everything after an unquoted ` #`, plus surrounding quotes, is not the value. */\nfunction scalarValue(raw: string): string {\n const withoutComment = raw.replace(/\\s+#.*$/, '').trim()\n const quoted = /^(['\"])(.*)\\1$/.exec(withoutComment)\n return (quoted?.[2] ?? withoutComment).trim()\n}\n\nfunction indentOf(line: string): number {\n return line.length - line.trimStart().length\n}\n\nfunction isBlank(line: string): boolean {\n const trimmed = line.trim()\n return trimmed.length === 0 || trimmed.startsWith('#')\n}\n\n/**\n * Does this workflow run on `pull_request`?\n *\n * Both spellings the fleet uses are handled: the block form every workflow here\n * writes, and the inline form (`on: [push, pull_request]`). `on` is quoted in\n * some repos because YAML 1.1 reads a bare `on` as the boolean true, so the\n * quoted keys are matched too.\n */\nexport function triggersOnPullRequest(source: string): boolean {\n const lines = source.split('\\n')\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index] as string\n const header = /^(?:on|\"on\"|'on')\\s*:(.*)$/.exec(line)\n if (!header) continue\n\n const inline = scalarValue(header[1] ?? '')\n if (inline.length > 0) {\n return inline\n .replace(/^\\[|\\]$/g, '')\n .split(',')\n .map((token) => token.trim())\n .includes('pull_request')\n }\n\n // Block form: the trigger names sit at the first nesting level under `on:`.\n // Anything deeper belongs to a trigger's own options (`branches`, `paths`).\n let nesting: number | null = null\n for (let cursor = index + 1; cursor < lines.length; cursor += 1) {\n const body = lines[cursor] as string\n if (isBlank(body)) continue\n const bodyIndent = indentOf(body)\n if (bodyIndent === 0) break\n if (nesting === null) nesting = bodyIndent\n if (bodyIndent !== nesting) continue\n const key = /^\\s*(?:-\\s*)?([A-Za-z_][\\w-]*)\\s*:?\\s*$/.exec(body)\n if (key?.[1] === 'pull_request') return true\n }\n return false\n }\n return false\n}\n\n/** Every Node pin an `actions/setup-node` step declares in one workflow. */\nfunction pinsInWorkflow(repoRoot: string, file: string, source: string): WorkflowNodePin[] {\n const pins: WorkflowNodePin[] = []\n for (const line of source.split('\\n')) {\n const match = /^\\s*(node-version|node-version-file)\\s*:\\s*(\\S.*)$/.exec(line)\n if (!match) continue\n const key = match[1] as string\n const value = scalarValue(match[2] as string)\n // A matrix expression is several runtimes, not one. Refusing to guess is\n // the point; `resolveWorkflowNodePin` turns an all-expression repo into a\n // named refusal rather than a silent \"unpinned\".\n if (value.includes('${{')) continue\n\n if (key === 'node-version') {\n pins.push({ file, value, via: 'node-version' })\n continue\n }\n\n const target = join(repoRoot, value)\n if (!existsSync(target)) {\n throw new Error(\n `signoff: ${file} reads its Node pin from \"${value}\" (node-version-file) and that file does not exist. ` +\n 'The workflow this gate replaces cannot itself run, so there is nothing to verify against.',\n )\n }\n const declared = readFileSync(target, 'utf8')\n .split('\\n')\n .map((entry) => entry.trim())\n .find((entry) => entry.length > 0 && !entry.startsWith('#'))\n if (declared !== undefined) pins.push({ file, value: declared, via: `node-version-file ${value}` })\n }\n return pins\n}\n\n/** Node pins declared by every workflow that gates a merge, in filename order. */\nexport function scanMergeGateNodePins(repoRoot: string): WorkflowNodePin[] {\n const dir = join(repoRoot, WORKFLOW_DIR)\n if (!existsSync(dir)) return []\n\n const pins: WorkflowNodePin[] = []\n const files = readdirSync(dir)\n .filter((name) => name.endsWith('.yml') || name.endsWith('.yaml'))\n .sort()\n for (const name of files) {\n const source = readFileSync(join(dir, name), 'utf8')\n if (!triggersOnPullRequest(source)) continue\n pins.push(...pinsInWorkflow(repoRoot, `${WORKFLOW_DIR}/${name}`, source))\n }\n return pins\n}\n\nexport interface ResolvedWorkflowPin {\n readonly major: number\n readonly declared: string\n readonly source: string\n}\n\n/**\n * One Node major for the whole merge gate, or a refusal that names why not.\n *\n * `majorOf` is injected rather than imported to keep the direction of the\n * dependency one-way: `node-version.ts` owns what a version string means, this\n * module owns where the string lives.\n */\nexport function resolveWorkflowNodePin(\n repoRoot: string,\n majorOf: (raw: string) => number | null,\n): ResolvedWorkflowPin | null {\n const pins = scanMergeGateNodePins(repoRoot)\n if (pins.length === 0) return null\n\n const byMajor = new Map<number, WorkflowNodePin[]>()\n for (const pin of pins) {\n const major = majorOf(pin.value)\n // An alias (`lts/*`) is a pin this module cannot resolve without a network\n // call — the same treatment `.nvmrc` gives one.\n if (major === null) continue\n const bucket = byMajor.get(major)\n if (bucket) bucket.push(pin)\n else byMajor.set(major, [pin])\n }\n\n if (byMajor.size === 0) return null\n if (byMajor.size > 1) {\n const detail = [...byMajor.values()]\n .flat()\n .map((pin) => ` ${pin.file} (${pin.via}): ${pin.value}`)\n .join('\\n')\n throw new Error(\n 'signoff: the workflows that gate a merge here pin different Node majors, so there is no single ' +\n `runtime to verify:\\n${detail}\\n` +\n 'Declare `nodeVersion` in the signoff config to say which one a sign-off means.',\n )\n }\n\n const [entry] = [...byMajor.entries()]\n if (entry === undefined) return null\n const [major, matched] = entry\n const first = matched[0] as WorkflowNodePin\n const files = [...new Set(matched.map((pin: WorkflowNodePin) => pin.file))].join(', ')\n return { major, declared: first.value, source: `${files} (${first.via})` }\n}\n","import { spawn } from 'node:child_process'\n\n/**\n * The subprocess primitive every sign-off step runs through.\n *\n * Three properties the gate depends on, none of which `execSync` gives:\n *\n * 1. **Cancellable.** Under fail-fast, a build still running when typecheck\n * fails is killed rather than waited out — otherwise the \"faster than CI\"\n * claim is spent waiting for work whose verdict no longer matters.\n * 2. **Process-group kill.** Steps run through `sh -c`, so killing the shell\n * leaves `vitest`'s forks and `tsup`'s dts worker orphaned and holding CPU.\n * The child is spawned as a group leader and the whole group is signalled.\n * 3. **Bounded, non-silent capture.** Output is capped, and when the cap is hit\n * the elision is stated in the captured text. A gate that quietly drops the\n * middle of a failure log is a gate that hides the failure.\n */\n\nexport interface CommandResult {\n readonly command: string\n readonly cwd: string\n readonly exitCode: number\n readonly signal: string | null\n readonly durationMs: number\n readonly output: string\n readonly truncated: boolean\n readonly timedOut: boolean\n}\n\nexport interface RunCommandOptions {\n readonly command: string\n readonly cwd: string\n readonly env?: Readonly<Record<string, string | undefined>>\n readonly timeoutMs?: number\n readonly signal?: AbortSignal\n /** Retained bytes before elision. Default 2 MiB. */\n readonly maxOutputBytes?: number\n /** Grace between SIGTERM and SIGKILL. Default 5 s. */\n readonly killGraceMs?: number\n readonly onData?: (chunk: string) => void\n}\n\nconst DEFAULT_MAX_OUTPUT_BYTES = 2 * 1024 * 1024\nconst DEFAULT_KILL_GRACE_MS = 5_000\n/** Fraction of the budget kept from the head; the rest is the tail. The head\n * carries the command echo and the first error, the tail carries the summary. */\nconst HEAD_SHARE = 0.25\n\n/**\n * Ring-ish buffer that keeps a head window and a tail window, so both the first\n * error and the final summary survive a very long log.\n */\nclass BoundedOutput {\n private head = ''\n private tail = ''\n private total = 0\n private readonly headBudget: number\n private readonly tailBudget: number\n\n constructor(private readonly budget: number) {\n this.headBudget = Math.floor(budget * HEAD_SHARE)\n this.tailBudget = budget - this.headBudget\n }\n\n push(chunk: string): void {\n this.total += chunk.length\n if (this.head.length < this.headBudget) {\n const room = this.headBudget - this.head.length\n this.head += chunk.slice(0, room)\n chunk = chunk.slice(room)\n if (chunk.length === 0) return\n }\n this.tail = (this.tail + chunk).slice(-this.tailBudget)\n }\n\n get truncated(): boolean {\n return this.total > this.budget\n }\n\n text(): string {\n if (!this.truncated) return this.head + this.tail\n const elided = this.total - this.head.length - this.tail.length\n return `${this.head}\\n\\n[signoff] ${elided} bytes elided (output exceeded ${this.budget} bytes)\\n\\n${this.tail}`\n }\n}\n\n/** Signal a whole process group, tolerating the race where it already exited. */\nfunction killGroup(pid: number, signal: NodeJS.Signals): void {\n try {\n process.kill(-pid, signal)\n } catch (err) {\n // ESRCH means the group is already gone, which is the outcome we wanted.\n // Anything else is a real failure to signal and must not be swallowed.\n if ((err as NodeJS.ErrnoException).code !== 'ESRCH') throw err\n }\n}\n\n/**\n * Run one shell command to completion and report what happened.\n *\n * Never throws on a non-zero exit — a failing step is data, not an exception.\n * It throws only when the process could not be started at all.\n */\nexport function runCommand(options: RunCommandOptions): Promise<CommandResult> {\n const {\n command,\n cwd,\n env,\n timeoutMs,\n signal,\n maxOutputBytes = DEFAULT_MAX_OUTPUT_BYTES,\n killGraceMs = DEFAULT_KILL_GRACE_MS,\n onData,\n } = options\n\n return new Promise<CommandResult>((resolve, reject) => {\n const startedAt = Date.now()\n const buffer = new BoundedOutput(maxOutputBytes)\n let timedOut = false\n let killTimer: NodeJS.Timeout | undefined\n let graceTimer: NodeJS.Timeout | undefined\n\n const child = spawn(command, {\n cwd,\n env: env as NodeJS.ProcessEnv | undefined,\n shell: true,\n // Group leader: lets one signal reach `sh` and everything it spawned.\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n\n const pid = child.pid\n const terminate = (): void => {\n if (pid === undefined || child.exitCode !== null || child.signalCode !== null) return\n killGroup(pid, 'SIGTERM')\n graceTimer = setTimeout(() => {\n if (child.exitCode === null && child.signalCode === null) killGroup(pid, 'SIGKILL')\n }, killGraceMs)\n graceTimer.unref()\n }\n\n const onAbort = (): void => terminate()\n signal?.addEventListener('abort', onAbort, { once: true })\n\n if (timeoutMs !== undefined) {\n killTimer = setTimeout(() => {\n timedOut = true\n terminate()\n }, timeoutMs)\n killTimer.unref()\n }\n\n const collect = (chunk: Buffer): void => {\n const text = chunk.toString('utf8')\n buffer.push(text)\n onData?.(text)\n }\n child.stdout.on('data', collect)\n child.stderr.on('data', collect)\n\n const cleanup = (): void => {\n if (killTimer) clearTimeout(killTimer)\n if (graceTimer) clearTimeout(graceTimer)\n signal?.removeEventListener('abort', onAbort)\n }\n\n child.on('error', (err) => {\n cleanup()\n reject(new Error(`signoff: could not start \\`${command}\\` in ${cwd}: ${err.message}`))\n })\n\n child.on('close', (code, sig) => {\n cleanup()\n resolve({\n command,\n cwd,\n // A signalled process reports code `null`; 128+n is the shell's own\n // convention and keeps the field a number a caller can compare.\n exitCode: code ?? (sig === 'SIGKILL' ? 137 : 143),\n signal: sig,\n durationMs: Date.now() - startedAt,\n output: buffer.text(),\n truncated: buffer.truncated,\n timedOut,\n })\n })\n })\n}\n","/**\n * The dependency graph, and running it as wide as the graph allows.\n *\n * CI runs these steps in a line because a YAML `steps:` list is a line. Nothing\n * about the work requires that: typecheck, the suite, the build and knip all\n * read source and none reads another's output. On a 32-core host, running them\n * concurrently is free wall-clock, and it is the only reason a strictly larger\n * verification can still finish faster than the CI it replaces.\n *\n * The graph is declared per step (`needs`), validated here, and the schedule is\n * derived from it — so an omitted edge is a correctness bug the repo owns, and\n * a cycle is named rather than deadlocking.\n */\n\nexport interface GraphNode {\n readonly name: string\n readonly needs?: readonly string[]\n}\n\n/** Throws on a duplicate name, a dangling `needs`, or a cycle. */\nexport function validateGraph(nodes: readonly GraphNode[]): void {\n const seen = new Set<string>()\n for (const node of nodes) {\n if (seen.has(node.name)) throw new Error(`signoff: two steps are both named \"${node.name}\"; names must be unique`)\n seen.add(node.name)\n }\n for (const node of nodes) {\n for (const need of node.needs ?? []) {\n if (!seen.has(need)) {\n throw new Error(`signoff: step \"${node.name}\" needs \"${need}\", which is not a step in this config`)\n }\n }\n }\n\n const byName = new Map(nodes.map((node) => [node.name, node]))\n const state = new Map<string, 'visiting' | 'done'>()\n const walk = (name: string, path: readonly string[]): void => {\n const status = state.get(name)\n if (status === 'done') return\n if (status === 'visiting') {\n const cycle = [...path.slice(path.indexOf(name)), name].join(' -> ')\n throw new Error(`signoff: dependency cycle among steps: ${cycle}`)\n }\n state.set(name, 'visiting')\n for (const need of byName.get(name)?.needs ?? []) walk(need, [...path, name])\n state.set(name, 'done')\n }\n for (const node of nodes) walk(node.name, [])\n}\n\ntype TaskStatus = 'passed' | 'failed' | 'skipped' | 'cancelled' | 'blocked'\n\nexport interface TaskOutcome<T> {\n readonly name: string\n readonly status: TaskStatus\n /** Present for anything that actually ran, including a cancelled task. */\n readonly value: T | null\n readonly startedAtMs: number | null\n readonly finishedAtMs: number | null\n}\n\nexport interface RunGraphOptions<TNode extends GraphNode, TValue> {\n readonly nodes: readonly TNode[]\n readonly maxParallel: number\n /** `false` stops scheduling after the first failure and kills what is running. */\n readonly keepGoing: boolean\n /** Runs one node. Resolves `{ ok }` for pass/fail; must not throw for a\n * failing command — a non-zero exit is data. */\n readonly run: (node: TNode, signal: AbortSignal) => Promise<{ readonly ok: boolean; readonly value: TValue }>\n /** Wall-clock origin, so outcomes are comparable across the whole run. */\n readonly now?: () => number\n}\n\n/**\n * Run the graph, honouring dependencies and the parallelism cap.\n *\n * Failure semantics, stated because they are the difference between a gate you\n * trust and one you argue with:\n * - fail-fast (default): nothing new is scheduled, everything in flight is\n * aborted and reported as `cancelled`, everything unstarted as `skipped`.\n * - `keepGoing`: independent work continues, but a step whose dependency\n * failed is reported `blocked`. It is never reported as passed, and never\n * silently omitted.\n */\nexport async function runGraph<TNode extends GraphNode, TValue>(\n options: RunGraphOptions<TNode, TValue>,\n): Promise<TaskOutcome<TValue>[]> {\n const { nodes, maxParallel, keepGoing, run, now = () => Date.now() } = options\n validateGraph(nodes)\n\n const origin = now()\n const outcomes = new Map<string, TaskOutcome<TValue>>()\n const pending = new Map(nodes.map((node) => [node.name, node]))\n const running = new Map<string, { readonly promise: Promise<void>; readonly controller: AbortController }>()\n let aborted = false\n\n const failedNames = new Set<string>()\n const passedNames = new Set<string>()\n\n const blockedBy = (node: TNode): boolean => (node.needs ?? []).some((need) => failedNames.has(need))\n const ready = (node: TNode): boolean => (node.needs ?? []).every((need) => passedNames.has(need))\n\n const settle = (name: string, outcome: TaskOutcome<TValue>): void => {\n outcomes.set(name, outcome)\n if (outcome.status === 'passed') passedNames.add(name)\n else failedNames.add(name)\n }\n\n const start = (node: TNode): void => {\n pending.delete(node.name)\n const controller = new AbortController()\n const startedAtMs = now() - origin\n const promise = run(node, controller.signal).then((result) => {\n const finishedAtMs = now() - origin\n const cancelled = controller.signal.aborted && !result.ok\n settle(node.name, {\n name: node.name,\n status: cancelled ? 'cancelled' : result.ok ? 'passed' : 'failed',\n value: result.value,\n startedAtMs,\n finishedAtMs,\n })\n running.delete(node.name)\n })\n running.set(node.name, { promise, controller })\n }\n\n for (;;) {\n if (!aborted) {\n // Drain everything the graph currently permits, up to the cap.\n for (const node of [...pending.values()]) {\n if (running.size >= maxParallel) break\n if (blockedBy(node)) {\n pending.delete(node.name)\n settle(node.name, { name: node.name, status: 'blocked', value: null, startedAtMs: null, finishedAtMs: null })\n continue\n }\n if (ready(node)) start(node)\n }\n }\n\n if (running.size === 0) {\n // Nothing running: either everything settled, or the rest is unreachable.\n if (pending.size === 0) break\n if (aborted) break\n // A pending node whose dependency neither passed nor failed cannot happen\n // after validateGraph, so anything left here is blocked or ready-next.\n const progressed = [...pending.values()].some((node) => ready(node) || blockedBy(node))\n if (!progressed) break\n continue\n }\n\n await Promise.race([...running.values()].map((entry) => entry.promise))\n\n if (!keepGoing && failedNames.size > 0 && !aborted) {\n aborted = true\n for (const entry of running.values()) entry.controller.abort()\n }\n }\n\n for (const node of pending.values()) {\n settle(node.name, {\n name: node.name,\n status: blockedBy(node) ? 'blocked' : 'skipped',\n value: null,\n startedAtMs: null,\n finishedAtMs: null,\n })\n }\n\n return nodes.map((node) => {\n const outcome = outcomes.get(node.name)\n if (!outcome) throw new Error(`signoff: step \"${node.name}\" produced no outcome — scheduler bug`)\n return outcome\n })\n}\n","import { createHash, randomInt } from 'node:crypto'\nimport type { SignoffShuffleSpec, SignoffStepSpec } from './types'\n\n/**\n * Suite-order randomization — the half of this gate that CI does not have.\n *\n * CI runs one arbitrary file order, so a scheduling-dependent failure is a coin\n * flip it happens to win or lose. The `node:sqlite` bundling failure that\n * started this was exactly that shape: it reproduced under CI's clean install\n * and worker sharding and not under a warm local run, and a single fixed order\n * could have missed it in either direction.\n *\n * Two rules make randomization useful rather than merely noisy:\n *\n * 1. **Every seed is recorded.** A shuffled failure that cannot be replayed is\n * a rumour. The report carries the base seed and every derived seed, and the\n * derivation is a pure function of `(base, step, index)` — so `--seed <base>`\n * reproduces the whole run, and a single seed replays one step.\n * 2. **Files are shuffled; tests inside a file are not.** File order is what\n * module-graph and worker-scheduling failures depend on. Shuffling the tests\n * within a file mostly finds intentional ordering in a `describe` block,\n * which is a false alarm, and a gate that cries wolf gets waived.\n */\n\n/**\n * Vitest file-order shuffle. `{seed}` is substituted per attempt.\n *\n * **No `--` separator, and that is measured, not assumed.** The habit is to\n * write `pnpm run test -- --flag`, and it silently breaks this: pnpm forwards\n * script arguments verbatim without needing the separator, so the `--` reaches\n * vitest, whose CLI treats it as end-of-options and drops everything after it.\n * Measured on this repo, four test files, `--reporter=verbose`:\n *\n * | invocation | seed 1 order | seed 2 order |\n * |---|---|---|\n * | `vitest run -- --sequence.shuffle.files=true --sequence.seed=N` | schedule, store, seeds, config | schedule, store, seeds, config |\n * | `vitest run --sequence.shuffle.files=true --sequence.seed=N` | schedule, config, store, seeds | seeds, schedule, config, store |\n *\n * The first row is the failure this gate exists to prevent, applied to itself:\n * a run that reports \"2 orders, seeds recorded\" while running one fixed order\n * twice. If a runner ever does need a separator, its config declares its own\n * `shuffle.args`.\n */\nconst DEFAULT_SHUFFLE_ARGS: readonly string[] = [\n '--sequence.shuffle.files=true',\n '--sequence.seed={seed}',\n]\n\nexport const DEFAULT_SHUFFLE_RUNS = 2\n\n/** A fresh base seed. Random, then recorded — never a fixed constant, or the\n * \"randomized\" order is one more fixed order. */\nexport function newSeedBase(): number {\n return randomInt(0, 2 ** 31 - 1)\n}\n\n/**\n * Derive a step's Nth seed from the base.\n *\n * A hash rather than `base + n`: adjacent seeds produce correlated orders in\n * some runners, and the point is independent samples of the order space.\n */\nexport function deriveSeed(base: number, stepName: string, index: number): number {\n const digest = createHash('sha256').update(`${base}:${stepName}:${index}`).digest()\n return digest.readUInt32BE(0) % 2 ** 31\n}\n\n/**\n * Refuse a shuffled step whose command cannot receive the appended flags.\n *\n * pnpm only forwards extra arguments to a script through `run`, `exec` or\n * `dlx`. The shorthand form puts pnpm's own option parser in front of them, and\n * what happens next is a version lottery. Measured on this host, appending\n * `--sequence.shuffle.files=true --sequence.seed=7` to a script that prints its\n * `process.argv`:\n *\n * | command | pnpm 9.15.9 | pnpm 10.22.0 |\n * |---|---|---|\n * | `pnpm run t <flags>` | forwarded, exit 0 | forwarded, exit 0 |\n * | `pnpm exec node probe.mjs <flags>` | forwarded, exit 0 | forwarded, exit 0 |\n * | `pnpm t <flags>` | `Unknown options`, exit 1 | exit 254, script never ran |\n * | `pnpm --filter web t <flags>` | `Unknown options`, exit 1 | **exit 0, script never ran** |\n *\n * That last cell is the reason this is a refusal and not a note. tax-agent's CI\n * runs `pnpm --filter web test`, and a config that copied the line verbatim\n * would, on pnpm 10, report a green \"unit tests\" step that executed zero tests.\n * A gate reporting safety it did not provide is the exact failure this module\n * exists to prevent, and the shorthand makes it silent.\n *\n * This is a static approximation — it checks the invocation SHAPE, not what the\n * runner received — so it is deliberately narrow: it fires only on commands\n * that invoke pnpm, and only on steps that get arguments appended.\n */\nexport function assertShuffleArgsReachTheRunner(steps: readonly SignoffStepSpec[]): void {\n for (const step of steps) {\n if (!normalizeShuffle(step.shuffle)) continue\n const tokens = step.run.split(/\\s+/).filter((token) => token.length > 0)\n const pnpmAt = tokens.findIndex((token) => token === 'pnpm' || token.endsWith('/pnpm'))\n if (pnpmAt === -1) continue\n if (tokens.slice(pnpmAt + 1).some((token) => token === 'run' || token === 'exec' || token === 'dlx')) continue\n throw new Error(\n `signoff: step \"${step.name}\" runs \\`${step.run}\\` and is shuffled, but pnpm only forwards appended ` +\n 'arguments to a script through `run`, `exec` or `dlx`. In the shorthand form pnpm 9 errors and pnpm 10 ' +\n 'exits 0 having run nothing, which would report a passing suite that never executed. ' +\n `Write it as \\`${step.run.replace(/\\s(\\S+)$/, ' run $1')}\\`.`,\n )\n }\n}\n\nexport interface StepAttemptPlan {\n readonly command: string\n readonly seed: number | null\n}\n\nfunction normalizeShuffle(shuffle: boolean | SignoffShuffleSpec | undefined): SignoffShuffleSpec | null {\n if (shuffle === undefined || shuffle === false) return null\n return shuffle === true ? {} : shuffle\n}\n\n/**\n * Expand one step into the commands that will actually run.\n *\n * An unshuffled step is one attempt with no seed. A shuffled step is one\n * attempt per seed, each with the seed substituted into the appended arguments.\n */\nexport function planAttempts(\n step: SignoffStepSpec,\n seedBase: number,\n overrideRuns?: number,\n): StepAttemptPlan[] {\n const spec = normalizeShuffle(step.shuffle)\n if (!spec) return [{ command: step.run, seed: null }]\n\n const args = spec.args ?? DEFAULT_SHUFFLE_ARGS\n const seeds =\n spec.seeds && spec.seeds.length > 0\n ? [...spec.seeds]\n : Array.from({ length: overrideRuns ?? spec.runs ?? DEFAULT_SHUFFLE_RUNS }, (_unused, index) =>\n deriveSeed(seedBase, step.name, index),\n )\n\n return seeds.map((seed) => ({\n command: `${step.run} ${args.map((arg) => arg.replaceAll('{seed}', String(seed))).join(' ')}`,\n seed,\n }))\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'\nimport { join, relative, sep } from 'node:path'\n\n/**\n * The pristine package store, cached on the lockfile so speed is not paid for\n * with a stale module graph.\n *\n * The whole mechanical difference between \"green locally\" and \"red in CI\" is\n * that CI installs `--frozen-lockfile` into an isolated store with no\n * `node_modules` and no framework cache, and a local run reuses both. Only one\n * of those two is safe to keep:\n *\n * - `node_modules` and any build/framework cache are **never** reused. They are\n * what masked the failure this gate exists to catch, and they are recreated\n * for every run inside a fresh `git worktree`.\n * - The **store** is reused, keyed on the bytes that decide what gets installed.\n * A pnpm store is content-addressed: every entry is named by the hash of what\n * is in it, so a reused entry cannot be a different version of a package than\n * the lockfile asked for. Reusing it skips downloads, not resolution.\n *\n * The key covers every manifest in the tree — lockfile, workspace file, every\n * `package.json`, `.npmrc`. Change any of them and the key changes, so the next\n * run installs into an empty store and pays the honest cold cost. Generations\n * are kept (default 4) rather than one, so moving between a branch and `main`\n * finds both warm instead of thrashing.\n */\n\n/** Basenames whose bytes decide what an install resolves to. */\nconst MANIFEST_FILES: readonly string[] = [\n 'pnpm-lock.yaml',\n 'pnpm-workspace.yaml',\n 'package.json',\n '.npmrc',\n '.nvmrc',\n 'package-lock.json',\n 'npm-shrinkwrap.json',\n 'yarn.lock',\n]\n\n/** Never descended into when hunting manifests. */\nconst SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next', '.wrangler', '.react-router'])\n\nexport interface StoreResolution {\n readonly storeDir: string\n readonly cacheKey: string\n /** True when a store for this key already had content. */\n readonly hit: boolean\n /** Repo-relative manifest paths, sorted — the inputs to `cacheKey`. */\n readonly keyedOn: readonly string[]\n /** Store directories removed by the generation cap. */\n readonly pruned: readonly string[]\n}\n\nexport interface ResolveStoreOptions {\n /** The clean tree whose manifests are hashed. */\n readonly treePath: string\n readonly cacheDir: string\n /** Generations to keep. Default 4. */\n readonly generations?: number\n}\n\nfunction collectManifests(dir: string, root: string, out: string[]): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) continue\n collectManifests(join(dir, entry.name), root, out)\n } else if (MANIFEST_FILES.includes(entry.name)) {\n out.push(relative(root, join(dir, entry.name)).split(sep).join('/'))\n }\n }\n}\n\n/** Every manifest in the tree, repo-relative and sorted. */\nexport function manifestFiles(treePath: string): string[] {\n const found: string[] = []\n collectManifests(treePath, treePath, found)\n return found.sort()\n}\n\n/** sha256 over each manifest's path and content — order-independent by sorting. */\nexport function manifestCacheKey(treePath: string, files: readonly string[]): string {\n const hash = createHash('sha256')\n for (const rel of files) {\n hash.update(rel)\n hash.update('\\0')\n hash.update(createHash('sha256').update(readFileSync(join(treePath, rel))).digest('hex'))\n hash.update('\\n')\n }\n return hash.digest('hex')\n}\n\n/**\n * Prune all but the `keep` most recently used store generations.\n *\n * Recency is the directory's mtime, stamped on every use, so the store a run\n * just used is never the one evicted.\n */\nfunction pruneStores(storesRoot: string, keep: number): string[] {\n if (!existsSync(storesRoot)) return []\n const entries = readdirSync(storesRoot, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => {\n const full = join(storesRoot, entry.name)\n return { full, mtimeMs: statSync(full).mtimeMs }\n })\n .sort((a, b) => b.mtimeMs - a.mtimeMs)\n\n const pruned: string[] = []\n for (const stale of entries.slice(keep)) {\n rmSync(stale.full, { recursive: true, force: true })\n pruned.push(stale.full)\n }\n return pruned\n}\n\nexport function resolveStore(options: ResolveStoreOptions): StoreResolution {\n const { treePath, cacheDir, generations = 4 } = options\n const files = manifestFiles(treePath)\n if (files.length === 0) {\n throw new Error(\n `signoff: no package manifest under ${treePath}. A sign-off run installs from a lockfile; ` +\n 'there is nothing here to install.',\n )\n }\n\n const cacheKey = manifestCacheKey(treePath, files)\n const storesRoot = join(cacheDir, 'stores')\n const storeDir = join(storesRoot, cacheKey)\n // A store directory that exists but holds only the marker is a previous run\n // that died before installing; treat it as a miss so the report does not\n // claim a warm store it does not have.\n const marker = join(storeDir, '.signoff-store.json')\n const hit = existsSync(storeDir) && readdirSync(storeDir).some((entry) => entry !== '.signoff-store.json')\n\n mkdirSync(storeDir, { recursive: true })\n writeFileSync(marker, `${JSON.stringify({ cacheKey, keyedOn: files, usedAt: new Date().toISOString() }, null, 2)}\\n`)\n const now = new Date()\n utimesSync(storeDir, now, now)\n\n return { storeDir, cacheKey, hit, keyedOn: files, pruned: pruneStores(storesRoot, generations) }\n}\n","import { spawnSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { copyFileSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport type { SignoffRepoFacts, SignoffSource } from './types'\n\n/**\n * Materialize the pristine checkout every step runs against.\n *\n * **The decision, and the measurement behind it: a `git worktree` of HEAD, not\n * a filtered copy.** Both were timed on two real repos on this host:\n *\n * | repo | `git worktree add --detach` | `rsync -a --exclude node_modules --exclude .git` |\n * |---|---|---|\n * | agent-app (931 tracked files) | **0.04 s / 11 MB** | 0.12 s / 25 MB |\n * | legal-agent (753 tracked files) | **0.06 s / 24 MB** | **3.97 s / 2.7 GB** |\n *\n * The 2.7 GB is the argument. The copy carried `build/`, `.react-router/` and\n * `.wrangler/` — generated output and framework caches — because an exclude\n * list is a hand-maintained enumeration of things to leave behind, and it is\n * never complete. A warm Vite cache is precisely what made the `node:sqlite`\n * bundling failure invisible locally while CI saw it, so a materializer that\n * can leak one has defeated its own purpose. `git` already knows what is source\n * and what is generated, and `.gitignore` is that list, maintained by the repo.\n *\n * The overlay on top is what keeps the gate usable before you commit:\n * `source: 'working-tree'` applies `git diff HEAD` (staged and unstaged) as a\n * patch and copies untracked, non-ignored files in. `source: 'head'` verifies\n * exactly the commit that would merge.\n */\n\nexport interface MaterializeOptions {\n readonly repoDir: string\n readonly dest: string\n readonly source: SignoffSource\n /** Gitignored files the run genuinely needs. Missing ones abort. */\n readonly carryFiles?: readonly string[]\n}\n\nexport interface CleanTree extends SignoffRepoFacts {\n /** Absolute path of the materialized checkout. */\n readonly path: string\n}\n\nfunction git(args: readonly string[], cwd: string): string {\n const result = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })\n if (result.error) throw new Error(`signoff: git ${args.join(' ')} failed to start: ${result.error.message}`)\n if (result.status !== 0) {\n throw new Error(`signoff: git ${args.join(' ')} exited ${result.status}\\n${result.stderr.trim()}`)\n }\n return result.stdout\n}\n\n/** Split a `-z` separated git list into entries. */\nfunction zsplit(out: string): string[] {\n return out.split('\\0').filter((entry) => entry.length > 0)\n}\n\nexport function repoRootOf(dir: string): string {\n return git(['rev-parse', '--show-toplevel'], dir).trim()\n}\n\nexport function materializeCleanTree(options: MaterializeOptions): CleanTree {\n const { repoDir, dest, source, carryFiles = [] } = options\n const root = repoRootOf(repoDir)\n const head = git(['rev-parse', 'HEAD'], root).trim()\n const branch = git(['rev-parse', '--abbrev-ref', 'HEAD'], root).trim()\n\n // A crashed earlier run leaves a registered worktree whose directory is gone;\n // `add` then refuses on a name collision. Pruning first is what makes the gate\n // re-runnable after a kill.\n git(['worktree', 'prune'], root)\n mkdirSync(dirname(dest), { recursive: true })\n if (existsSync(dest)) rmSync(dest, { recursive: true, force: true })\n git(['worktree', 'add', '--detach', '--quiet', dest, head], root)\n\n let diffSha256: string | null = null\n let untrackedFiles: string[] = []\n\n if (source === 'working-tree') {\n // `git diff HEAD` covers staged and unstaged changes to tracked files in one\n // patch, including deletions and renames. `--binary` keeps a changed image\n // or lockfile-adjacent binary from silently dropping out of the patch.\n const patch = git(['diff', 'HEAD', '--binary', '--no-color', '--no-ext-diff'], root)\n if (patch.length > 0) {\n diffSha256 = createHash('sha256').update(patch).digest('hex')\n const patchFile = join(dirname(dest), `${dest.split('/').pop() ?? 'tree'}.patch`)\n writeFileSync(patchFile, patch)\n // Fail loud: a patch that does not apply means the tree we would verify is\n // not the tree the developer has, and verifying the wrong bytes is worse\n // than not verifying.\n git(['apply', '--binary', '--whitespace=nowarn', patchFile], dest)\n rmSync(patchFile, { force: true })\n }\n\n untrackedFiles = zsplit(git(['ls-files', '--others', '--exclude-standard', '-z'], root))\n for (const rel of untrackedFiles) {\n const target = join(dest, rel)\n mkdirSync(dirname(target), { recursive: true })\n copyFileSync(join(root, rel), target)\n }\n }\n\n const carried: string[] = []\n for (const rel of carryFiles) {\n if (isAbsolute(rel)) throw new Error(`signoff: carryFiles must be repo-relative; got \"${rel}\"`)\n const from = resolve(root, rel)\n if (!existsSync(from)) {\n throw new Error(\n `signoff: carryFiles names \"${rel}\", which does not exist at ${from}. ` +\n 'Remove it from the config or create the file — installing without it would resolve ' +\n 'against a different registry than the one you think you are verifying.',\n )\n }\n const target = join(dest, rel)\n mkdirSync(dirname(target), { recursive: true })\n copyFileSync(from, target)\n carried.push(rel)\n }\n\n return {\n path: dest,\n root,\n head,\n branch,\n source,\n dirty: diffSha256 !== null || untrackedFiles.length > 0,\n diffSha256,\n untrackedFiles,\n carriedFiles: carried,\n }\n}\n\n/** Unregister and delete a materialized tree. */\nexport function removeCleanTree(tree: CleanTree): void {\n git(['worktree', 'remove', '--force', tree.path], tree.root)\n}\n","import type { SignoffReport, SignoffStepResult } from './types'\n\n/**\n * The proof a human reads before merging.\n *\n * A sign-off gate is only worth the CI it replaces if its output answers the\n * question CI's green tick answers and the ones it does not: what bytes were\n * verified, in what environment, under which suite orders, and how to reproduce\n * it. So the report leads with the verdict, states the subject (commit + patch\n * digest) and the environment (clean tree, store cache state), lists every step\n * with its seeds, and ends with the exact command that runs it again.\n *\n * Failure output is printed in full, under the step's name. Naming the step is\n * the difference between \"CI is red\" and a fix.\n */\n\nconst BAR = '─'.repeat(72)\n\nfunction ms(value: number): string {\n return value >= 10_000 ? `${(value / 1000).toFixed(1)}s` : `${value}ms`\n}\n\nfunction statusMark(status: SignoffStepResult['status']): string {\n switch (status) {\n case 'passed': return 'ok '\n case 'failed': return 'FAIL'\n case 'cancelled': return 'kill'\n case 'blocked': return 'blkd'\n case 'skipped': return '-- '\n }\n}\n\nfunction seedList(step: SignoffStepResult): string {\n const seeds = step.attempts.map((attempt) => attempt.seed).filter((seed): seed is number => seed !== null)\n return seeds.length === 0 ? '' : ` seeds ${seeds.join(', ')}`\n}\n\n/** Concurrency actually achieved, measured from the step windows rather than\n * asserted from the config. A claimed speedup nobody measured is a wish. */\nexport function peakConcurrency(steps: readonly SignoffStepResult[]): number {\n const events: { at: number; delta: number }[] = []\n for (const step of steps) {\n if (step.startedAtMs === null || step.finishedAtMs === null) continue\n events.push({ at: step.startedAtMs, delta: 1 }, { at: step.finishedAtMs, delta: -1 })\n }\n events.sort((a, b) => a.at - b.at || a.delta - b.delta)\n let current = 0\n let peak = 0\n for (const event of events) {\n current += event.delta\n peak = Math.max(peak, current)\n }\n return peak\n}\n\nexport function formatSignoffReport(report: SignoffReport): string {\n const lines: string[] = []\n const verdict = report.ok ? 'SIGN-OFF PASSED' : 'SIGN-OFF FAILED'\n lines.push(BAR, `${verdict} — ${report.repo.branch} @ ${report.repo.head.slice(0, 12)}`, BAR, '')\n\n lines.push('subject')\n lines.push(` repo ${report.repo.root}`)\n lines.push(` source ${report.repo.source}${report.repo.dirty ? ' (working tree carries uncommitted work)' : ''}`)\n if (report.repo.diffSha256) lines.push(` patch sha256:${report.repo.diffSha256.slice(0, 16)}`)\n if (report.repo.untrackedFiles.length > 0) {\n lines.push(` untracked ${report.repo.untrackedFiles.length} file(s) copied in`)\n }\n if (report.repo.carriedFiles.length > 0) lines.push(` carried ${report.repo.carriedFiles.join(', ')}`)\n lines.push('')\n\n lines.push('environment')\n lines.push(` clean tree ${report.workspace}${report.workspaceRetained ? ' (retained)' : ' (removed)'}`)\n lines.push(` install ${report.install.command}`)\n lines.push(\n ` store ${report.install.cacheHit ? 'warm' : 'cold'} — ${report.install.cacheKey.slice(0, 16)} ` +\n `(keyed on ${report.install.keyedOn.length} manifest file(s))`,\n )\n lines.push(\n ` host ${report.host.node} · ${report.host.packageManager} · ${report.host.cpus} cpus` +\n (report.host.nodePinned === null\n ? ' · node UNPINNED by this repo'\n : ` · pinned ${report.host.nodePinned} (${report.host.nodePinSource})`),\n )\n lines.push(\n ` config ${report.configOrigin.kind === 'derived'\n ? `derived from scripts: ${report.configOrigin.scripts.join(', ')}`\n : report.configOrigin.path}`,\n )\n lines.push('')\n\n const width = Math.max(...report.steps.map((step) => step.name.length), 'install'.length)\n lines.push('steps')\n lines.push(\n ` ${report.install.exitCode === 0 ? 'ok ' : 'FAIL'} ${'install'.padEnd(width)} ${ms(report.install.durationMs).padStart(8)}`,\n )\n for (const step of report.steps) {\n const window =\n step.startedAtMs === null || step.finishedAtMs === null\n ? ''\n : ` [${ms(step.startedAtMs)} → ${ms(step.finishedAtMs)}]`\n lines.push(\n ` ${statusMark(step.status)} ${step.name.padEnd(width)} ${ms(step.durationMs).padStart(8)}` +\n ` ${step.attempts.length} run(s)${window}${seedList(step)}`,\n )\n }\n lines.push('')\n\n const peak = peakConcurrency(report.steps)\n const saved = report.serialMs - report.wallClockMs\n lines.push('timing')\n lines.push(` wall clock ${ms(report.wallClockMs)}`)\n lines.push(` serial sum ${ms(report.serialMs)} (install + every step, one after another)`)\n lines.push(\n ` parallel peak ${peak} step(s) at once — ` +\n (saved > 0 ? `${ms(saved)} saved, ${(report.serialMs / report.wallClockMs).toFixed(2)}x` : 'no overlap available'),\n )\n lines.push('')\n\n const failures = report.steps.filter((step) => step.status === 'failed' || step.status === 'cancelled')\n if (report.install.exitCode !== 0) {\n lines.push(BAR, 'install FAILED — no step could run', BAR, report.install.output.trimEnd(), '')\n }\n for (const step of failures) {\n const last = step.attempts[step.attempts.length - 1]\n lines.push(BAR)\n lines.push(`${step.status === 'cancelled' ? 'CANCELLED' : 'FAILED'}: ${step.name}`)\n if (last) {\n lines.push(` command ${last.command}`)\n lines.push(` exit ${last.exitCode}${last.signal ? ` (${last.signal})` : ''}${last.timedOut ? ' — TIMED OUT' : ''}`)\n if (last.seed !== null) {\n lines.push(` seed ${last.seed} — replay this order alone with the same seed`)\n }\n lines.push(BAR, last.output.trimEnd(), '')\n }\n }\n\n const blocked = report.steps.filter((step) => step.status === 'blocked' || step.status === 'skipped')\n if (blocked.length > 0) {\n lines.push(`not judged: ${blocked.map((step) => `${step.name} (${step.status})`).join(', ')}`)\n lines.push('')\n }\n\n lines.push(`reproduce: ${report.reproduce}`)\n return lines.join('\\n')\n}\n\n/** One line for a commit message, a PR comment, or a chat handoff. */\nexport function formatSignoffLine(report: SignoffReport): string {\n const passed = report.steps.filter((step) => step.status === 'passed').length\n return (\n `${report.ok ? 'signoff PASS' : 'signoff FAIL'} ${report.repo.head.slice(0, 12)} — ` +\n `${passed}/${report.steps.length} steps, ${ms(report.wallClockMs)} wall ` +\n `(${ms(report.serialMs)} serial), seed ${report.seedBase}, ` +\n `${report.install.cacheHit ? 'warm' : 'cold'} store, clean install`\n )\n}\n"],"mappings":";AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,MAAM,eAAe;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,SAAS;AAuBlB,IAAM,uBAA0C,CAAC,sBAAsB,mBAAmB;AAE1F,IAAM,gBAAgB,EAAE,OAAO;AAAA,EAC7B,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS;AAAA,EAC3C,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EAC1C,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AACrC,CAAC;AAED,IAAM,aAAa,EAAE,OAAO;AAAA,EAC1B,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACrB,KAAK,EAAE,OAAO,EAAE,SAAS;AAAA,EACzB,KAAK,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EAC/C,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACpC,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS;AAAA,EAChD,SAAS,EAAE,MAAM,CAAC,EAAE,QAAQ,GAAG,aAAa,CAAC,EAAE,SAAS;AAC1D,CAAC;AAED,IAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,SAAS,EACN,OAAO;AAAA,IACN,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,IAChC,cAAc,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,IAC7C,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,IACzC,KAAK,EAAE,OAAO,EAA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AAK,IAAI;AACxB;AAGO,SAAS,kBAAkB,QAA+B;AAC/D,QAAM,SAAS,OAAO,MAAM,OAAO,CAAC,SAAS,KAAK,WAAW,QAAQ,EAAE;AACvE,SACE,GAAG,OAAO,KAAK,iBAAiB,cAAc,IAAI,OAAO,KAAK,KAAK,MAAM,GAAG,EAAE,CAAC,WAC5E,MAAM,IAAI,OAAO,MAAM,MAAM,WAAW,GAAG,OAAO,WAAW,CAAC,UAC7D,GAAG,OAAO,QAAQ,CAAC,kBAAkB,OAAO,QAAQ,KACrD,OAAO,QAAQ,WAAW,SAAS,MAAM;AAEhD;","names":["spawnSync","existsSync","join","resolve","existsSync","readFileSync","join","existsSync","readFileSync","join","majorOf","major","join","existsSync","readFileSync","resolve","createHash","existsSync","readFileSync","readdirSync","join","createHash","existsSync","mkdirSync","rmSync","writeFileSync","join","resolve","join","spawnSync","resolve","existsSync"]}
|