depkill 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -3
  3. package/data/module-replacements.LICENSE +21 -0
  4. package/data/module-replacements.json +947 -0
  5. package/dist/src/anticheat/constants.js +105 -0
  6. package/dist/src/anticheat/imports.js +419 -0
  7. package/dist/src/anticheat/tokens.js +177 -0
  8. package/dist/src/anticheat.js +189 -0
  9. package/dist/src/card/format.js +113 -0
  10. package/dist/src/card/svg.js +137 -0
  11. package/dist/src/card.js +364 -0
  12. package/dist/src/check.js +139 -0
  13. package/dist/src/cli.js +333 -0
  14. package/dist/src/gate/holdout.js +78 -0
  15. package/dist/src/gate/process.js +78 -0
  16. package/dist/src/gate.js +532 -0
  17. package/dist/src/graph.js +148 -0
  18. package/dist/src/holdout/perturb.js +108 -0
  19. package/dist/src/holdout/snapshot.js +113 -0
  20. package/dist/src/init.js +76 -0
  21. package/dist/src/inputs/generate.js +282 -0
  22. package/dist/src/inputs.js +273 -0
  23. package/dist/src/measure.js +149 -0
  24. package/dist/src/project.js +72 -0
  25. package/dist/src/record.js +180 -0
  26. package/dist/src/registry.js +78 -0
  27. package/dist/src/replacement.js +146 -0
  28. package/dist/src/runner.js +227 -0
  29. package/dist/src/runtime/agent-inputs.js +36 -0
  30. package/dist/src/runtime/child.js +260 -0
  31. package/dist/src/runtime/esm-hooks.js +44 -0
  32. package/dist/src/runtime/fsguard.js +264 -0
  33. package/dist/src/runtime/inspect.js +115 -0
  34. package/dist/src/runtime/lockdown.js +157 -0
  35. package/dist/src/runtime/protocol.js +16 -0
  36. package/dist/src/scan.js +210 -0
  37. package/dist/src/serialize.js +399 -0
  38. package/dist/src/tooling.js +88 -0
  39. package/dist/src/types.js +9 -0
  40. package/dist/src/usage/common.js +36 -0
  41. package/dist/src/usage/fallback.js +227 -0
  42. package/dist/src/usage/ts.js +142 -0
  43. package/dist/src/usage.js +97 -0
  44. package/dist/src/util/exports.js +86 -0
  45. package/dist/src/util/fs.js +64 -0
  46. package/dist/src/util/term.js +61 -0
  47. package/package.json +54 -6
  48. package/skills/AGENTS.section.md +52 -0
  49. package/skills/depkill/SKILL.md +148 -0
@@ -0,0 +1,364 @@
1
+ // `card`: after `gate` passed, measure the project before (the baseline record kept) and after (now) with clean temp
2
+ // installs, and render the shareable card, the README badge and a markdown report. Only gate results that still
3
+ // match the files they judged are counted (R37), and the evidence line names every caveat (R36).
4
+ import { existsSync, readdirSync, writeFileSync } from 'node:fs';
5
+ import { basename, join } from 'node:path';
6
+ import { badgeValue, driftCaveat, evidenceLine, headline, maintainersMeasured, prodRows, statRows, ungatedCaveat } from './card/format.js';
7
+ import { renderBadge, renderCard } from './card/svg.js';
8
+ import { readRecordedCases } from './check.js';
9
+ import { computeGateFingerprint } from './gate.js';
10
+ import { dependencyClosure } from './graph.js';
11
+ import { measureProject } from './measure.js';
12
+ import { DepkillError } from './types.js';
13
+ import { pkgSafe, readJson, stateDir } from './util/fs.js';
14
+ import { scanUsage } from './usage.js';
15
+ export { evidenceLine, formatCardBytes } from './card/format.js';
16
+ export { escapeXml, renderBadge, renderCard } from './card/svg.js';
17
+ const FILES = { card: 'card.svg', badge: 'badge.svg', report: 'report.md' };
18
+ const DEP_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
19
+ /** Fingerprint key of the root package.json (root-relative path). */
20
+ const ROOT_MANIFEST = 'package.json';
21
+ const NOT_MEASURED = 'maintainers not measured (offline, or an npm registry request failed)';
22
+ const stale = (pkg) => `gate result is stale or edited — re-run depkill gate ${pkg}`;
23
+ const notPassed = (pkg) => `gate has not passed — re-run depkill gate ${pkg}`;
24
+ /**
25
+ * I2: the first direct dependency whose closure still contains `name` (prod checked before dev).
26
+ * Dev-only hits are labelled `(dev)`; differing found versions are shown (e.g. `dep (dev, 1.0.6)`).
27
+ */
28
+ export function stillInstalledVia(graph, name, removedVersion) {
29
+ for (const dep of graph.direct.prod.keys()) {
30
+ const hit = dependencyClosure(graph, dep).find((node) => node.name === name);
31
+ if (hit !== undefined)
32
+ return removedVersion !== undefined && hit.version !== removedVersion ? `${dep} (${hit.version})` : dep;
33
+ }
34
+ for (const dep of graph.direct.dev.keys()) {
35
+ const hit = dependencyClosure(graph, dep).find((node) => node.name === name);
36
+ if (hit !== undefined)
37
+ return removedVersion !== undefined && hit.version !== removedVersion ? `${dep} (dev, ${hit.version})` : `${dep} (dev)`;
38
+ }
39
+ return null;
40
+ }
41
+ /**
42
+ * I1: package versions added, removed or changed between `before` and `after` outside the closures of
43
+ * `removedDirect` (gated + un-gated removals). Sorted human-readable entries.
44
+ */
45
+ export function detectDrift(before, after, removedDirect) {
46
+ const removedClosure = new Set();
47
+ for (const name of removedDirect) {
48
+ if (!before.direct.prod.has(name) && !before.direct.dev.has(name))
49
+ continue;
50
+ for (const node of dependencyClosure(before, name))
51
+ removedClosure.add(`${node.name}@${node.version}`);
52
+ }
53
+ const versionsOf = (graph) => {
54
+ const map = new Map();
55
+ for (const node of graph.nodes.values()) {
56
+ const set = map.get(node.name) ?? new Set();
57
+ set.add(node.version);
58
+ map.set(node.name, set);
59
+ }
60
+ return map;
61
+ };
62
+ const bMap = versionsOf(before);
63
+ const aMap = versionsOf(after);
64
+ const names = [...new Set([...bMap.keys(), ...aMap.keys()])].sort();
65
+ const out = [];
66
+ for (const name of names) {
67
+ const bSet = bMap.get(name) ?? new Set();
68
+ const aSet = aMap.get(name) ?? new Set();
69
+ const added = [...aSet].filter((v) => !bSet.has(v)).sort();
70
+ const removed = [...bSet].filter((v) => !aSet.has(v) && !removedClosure.has(`${name}@${v}`)).sort();
71
+ if (removed.length === 1 && added.length === 1) {
72
+ out.push(`${name}: ${removed[0]} → ${added[0]}`);
73
+ }
74
+ else {
75
+ for (const v of added)
76
+ out.push(`+${name}@${v}`);
77
+ for (const v of removed)
78
+ out.push(`-${name}@${v}`);
79
+ }
80
+ }
81
+ return out.sort();
82
+ }
83
+ const count = (n) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0;
84
+ function isGateResult(value) {
85
+ if (value === null || typeof value !== 'object')
86
+ return false;
87
+ const g = value;
88
+ const fingerprint = g.fingerprint;
89
+ return typeof g.pkg === 'string' && typeof g.pass === 'boolean' && typeof g.sandboxed === 'boolean'
90
+ && count(g.realCases) && count(g.generatedCases) && count(g.holdoutCases) && count(g.acceptedMismatches)
91
+ && fingerprint !== null && typeof fingerprint === 'object' && Object.values(fingerprint).every((v) => typeof v === 'string')
92
+ && Array.isArray(g.checks) && g.checks.every((c) => c !== null && typeof c === 'object'
93
+ && typeof c.name === 'string' && typeof c.status === 'string');
94
+ }
95
+ /** R51: did `gate` skip its check named `name`? */
96
+ const skippedCheck = (gate, name) => gate.checks.some((c) => c.name === name && c.status === 'skipped');
97
+ /**
98
+ * R49: the replacement files and cases.jsonl must match; the root package.json entry is ignored, because removing the
99
+ * next package changes it (the removal itself is re-verified by stillRemoved).
100
+ */
101
+ function sameFingerprint(a, b) {
102
+ const entries = (f) => JSON.stringify(Object.entries(f)
103
+ .filter(([path]) => path !== ROOT_MANIFEST)
104
+ .sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0)));
105
+ return entries(a) === entries(b);
106
+ }
107
+ /** R49: the gate's `removed` and `no-imports-left` checks, re-run now. Returns why the package is back, or null. */
108
+ function stillRemoved(project, pkg) {
109
+ const fields = DEP_FIELDS.filter((field) => Object.hasOwn(project.pkg[field] ?? {}, pkg));
110
+ if (fields.length > 0)
111
+ return `${pkg} is in ${fields.join(', ')} of package.json again — re-run depkill gate ${pkg}`;
112
+ const sites = scanUsage(project, new Set([pkg]));
113
+ if (sites.length > 0)
114
+ return `${pkg} is imported again at ${sites.map((s) => `${s.file}:${s.line}`).join(', ')} — re-run depkill gate ${pkg}`;
115
+ return null;
116
+ }
117
+ const compared = (c) => c.outcome.kind === 'return' || c.outcome.kind === 'throw';
118
+ /**
119
+ * R37/R49: a gate result counts only when it passed, its fingerprint (replacement files and cases.jsonl) matches
120
+ * the files now, its real/generated counts match the fingerprinted cases.jsonl, and the package is still absent
121
+ * from package.json and from every import. Returns the reason when it does not count.
122
+ */
123
+ function judge(project, dirName, file) {
124
+ const label = dirName.replace('__', '/');
125
+ let gate;
126
+ try {
127
+ gate = readJson(file);
128
+ }
129
+ catch {
130
+ return { reason: stale(label) };
131
+ }
132
+ if (!isGateResult(gate))
133
+ return { reason: stale(label) };
134
+ try {
135
+ if (pkgSafe(gate.pkg) !== dirName)
136
+ return { reason: stale(label) };
137
+ }
138
+ catch {
139
+ return { reason: stale(label) };
140
+ }
141
+ if (!gate.pass)
142
+ return { reason: notPassed(gate.pkg) };
143
+ try {
144
+ if (!sameFingerprint(gate.fingerprint, computeGateFingerprint(project, gate.pkg)))
145
+ return { reason: stale(gate.pkg) };
146
+ const cases = readRecordedCases(project, gate.pkg).filter(compared);
147
+ const real = cases.filter((c) => c.source !== 'generated').length;
148
+ if (real !== gate.realCases || cases.length - real !== gate.generatedCases)
149
+ return { reason: stale(gate.pkg) };
150
+ }
151
+ catch (error) {
152
+ if (!(error instanceof DepkillError))
153
+ throw error;
154
+ return { reason: stale(gate.pkg) };
155
+ }
156
+ const back = stillRemoved(project, gate.pkg);
157
+ return back === null ? { gate } : { reason: back };
158
+ }
159
+ /** Every `.depkill/<pkg-safe>/gate.json`, judged; counted results sorted by package name. */
160
+ export function gatedPackages(project) {
161
+ const dir = stateDir(project.root);
162
+ const counted = [];
163
+ const excluded = [];
164
+ if (!existsSync(dir))
165
+ return { counted, excluded };
166
+ const names = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
167
+ for (const name of names) {
168
+ const file = join(dir, name, 'gate.json');
169
+ if (!existsSync(file))
170
+ continue;
171
+ const verdict = judge(project, name, file);
172
+ if ('gate' in verdict)
173
+ counted.push(verdict.gate);
174
+ else
175
+ excluded.push({ pkg: name.replace('__', '/'), reason: verdict.reason });
176
+ }
177
+ counted.sort((a, b) => (a.pkg < b.pkg ? -1 : a.pkg > b.pkg ? 1 : 0));
178
+ return { counted, excluded };
179
+ }
180
+ /** Markdown inline text (never at a line start): backslash-escapes emphasis, code, link and table syntax; entity-escapes HTML. */
181
+ function md(text) {
182
+ return text.replace(/[\\`*_[\]|]/g, (ch) => `\\${ch}`).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
183
+ }
184
+ /** Inline code span; a package name never holds a backtick, but an installed manifest's name is not ours to trust. */
185
+ function code(name) {
186
+ return `\`${name.replace(/[`\r\n]/g, '')}\``;
187
+ }
188
+ /** Markdown report: removed packages, a before/after table, the evidence line, notes and the badge snippet. */
189
+ export function renderReport(input) {
190
+ const [packages, nodeModules, ...rest] = statRows(input);
191
+ const [prodPackages, prodNodeModules] = prodRows(input);
192
+ const rows = [packages, prodPackages, nodeModules, prodNodeModules, ...rest];
193
+ const notes = [...(input.notes ?? []), ...(maintainersMeasured(input) ? [] : [NOT_MEASURED])];
194
+ return [
195
+ `# depkill report: ${md(input.projectName)}`,
196
+ '',
197
+ `${headline(input)}:`,
198
+ '',
199
+ ...input.removed.map((r) => `- ${code(r.name)}${r.stillInstalledVia === null ? '' : ` (still via ${code(r.stillInstalledVia)})`}`),
200
+ '',
201
+ '| | before | after | change |',
202
+ '| --- | ---: | ---: | ---: |',
203
+ ...rows.map((row) => `| ${row.label} | ${row.before} | ${row.after} | ${row.delta} |`),
204
+ '',
205
+ ...ungatedSection(input),
206
+ ...driftSection(input),
207
+ evidenceLine(input),
208
+ '',
209
+ 'Measured with clean temp installs (install scripts off) of `.depkill/baseline/` (before) and the current package.json and lockfile (after).',
210
+ ...(notes.length > 0 ? ['', 'Notes:', '', ...notes.map((note) => `- ${note}`)] : []),
211
+ '',
212
+ // This file lives in .depkill/: the card is linked relative to it, the README snippet relative to the root.
213
+ `![depkill card](${FILES.card})`,
214
+ '',
215
+ '## Badge',
216
+ '',
217
+ 'Add to your README:',
218
+ '',
219
+ '```markdown',
220
+ `![depkill: ${badgeValue(input.removed.length)}](.depkill/${FILES.badge})`,
221
+ '```',
222
+ '',
223
+ ].join('\n');
224
+ }
225
+ /** R50: the caveat and every un-gated removal, or nothing. */
226
+ function ungatedSection(input) {
227
+ const caveat = ungatedCaveat(input);
228
+ if (caveat === null)
229
+ return [];
230
+ return [caveat, '', 'Removed without a depkill gate (included in the totals):', '', ...input.ungatedRemovals.map((name) => `- ${code(name)}`), ''];
231
+ }
232
+ /** I1: the drift caveat and every non-depkill dependency change, or nothing. */
233
+ function driftSection(input) {
234
+ const caveat = driftCaveat(input);
235
+ if (caveat === null)
236
+ return [];
237
+ return [caveat, '', 'Dependency changes not made by depkill (included in the totals):', '', ...(input.drift ?? []).map((item) => `- ${code(item)}`), ''];
238
+ }
239
+ function summary(input, written) {
240
+ const rows = statRows(input);
241
+ const width = Math.max(...rows.map((row) => row.label.length));
242
+ const removed = input.removed.map((r) => (r.stillInstalledVia === null ? r.name : `${r.name} (still via ${r.stillInstalledVia})`));
243
+ return [
244
+ '',
245
+ `${headline(input)}: ${removed.join(', ')}`,
246
+ '',
247
+ ...rows.map((row) => ` ${row.label.padEnd(width)} ${row.value} (${row.delta})`),
248
+ ...(maintainersMeasured(input) ? [] : [` ${NOT_MEASURED}`]),
249
+ ...[ungatedCaveat(input), driftCaveat(input)].filter((line) => line !== null).map((line) => ` ${line}`),
250
+ '',
251
+ evidenceLine(input),
252
+ ...(input.notes ?? []).map((note) => `Note: ${note}`),
253
+ '',
254
+ ...written.map((file) => `Wrote ${file}`),
255
+ `README badge: ![depkill: ${badgeValue(input.removed.length)}](.depkill/${FILES.badge})`,
256
+ '',
257
+ ].join('\n');
258
+ }
259
+ /** Root `dependencies`, `devDependencies` and `optionalDependencies` names (R50). */
260
+ function directNames(pkg) {
261
+ return new Set([pkg.dependencies, pkg.devDependencies, pkg.optionalDependencies].flatMap((deps) => Object.keys(deps ?? {})));
262
+ }
263
+ /** R50: direct dependencies of the baseline that are gone now and have no counted gate, sorted. */
264
+ export function ungatedRemovals(baseline, current, gated) {
265
+ const now = directNames(current);
266
+ return [...directNames(baseline)].filter((name) => !now.has(name) && !gated.has(name)).sort();
267
+ }
268
+ function readBaseline(file) {
269
+ try {
270
+ return readJson(file);
271
+ }
272
+ catch (error) {
273
+ throw new DepkillError(`${error instanceof Error ? error.message : String(error)} (the baseline is written by the first depkill record)`);
274
+ }
275
+ }
276
+ function readMetaVersion(project, pkg) {
277
+ const file = join(stateDir(project.root, pkg), 'meta.json');
278
+ if (!existsSync(file))
279
+ return undefined;
280
+ try {
281
+ const meta = readJson(file);
282
+ return typeof meta?.version === 'string' ? meta.version : undefined;
283
+ }
284
+ catch {
285
+ return undefined;
286
+ }
287
+ }
288
+ function realSourceCounts(project, counted) {
289
+ let callsite = 0;
290
+ let agent = 0;
291
+ for (const gate of counted) {
292
+ for (const c of readRecordedCases(project, gate.pkg).filter(compared)) {
293
+ if (c.source === 'callsite')
294
+ callsite += 1;
295
+ else if (c.source === 'agent')
296
+ agent += 1;
297
+ }
298
+ }
299
+ return { callsite, agent };
300
+ }
301
+ const sum = (gates, key) => gates.reduce((total, gate) => total + gate[key], 0);
302
+ /**
303
+ * Counts the packages whose gate passed and still matches (gatedPackages; others are logged with the reason),
304
+ * measures `.depkill/baseline/` (before) and the project (after) with clean installs, and writes
305
+ * `.depkill/card.svg`, `.depkill/badge.svg` and `.depkill/report.md`. Removals since the baseline without a counted
306
+ * gate are disclosed (R50). DepkillError (exit 2) when no package counts or the baseline is missing or malformed.
307
+ */
308
+ export async function runCard(project, opts) {
309
+ const log = opts.log ?? (() => { });
310
+ const { counted, excluded } = gatedPackages(project);
311
+ for (const { pkg, reason } of excluded)
312
+ log(`Skipped ${pkg}: ${reason}\n`);
313
+ if (counted.length === 0)
314
+ throw new DepkillError('no gated packages yet: run depkill gate <pkg> until it passes, then depkill card.');
315
+ const state = stateDir(project.root);
316
+ const baseline = join(state, 'baseline');
317
+ if (!existsSync(join(baseline, 'package.json'))) {
318
+ throw new DepkillError('no baseline (.depkill/baseline/package.json) to measure "before" from: re-run depkill record.');
319
+ }
320
+ const ungated = ungatedRemovals(readBaseline(join(baseline, 'package.json')), project.pkg, new Set(counted.map((gate) => gate.pkg)));
321
+ const measure = opts.measure ?? measureProject;
322
+ const measureOpts = { offline: opts.offline, configDir: project.root };
323
+ log('Measuring before: clean install of .depkill/baseline/ …\n');
324
+ const before = await measure(baseline, project.pm, measureOpts);
325
+ log('Measuring after: clean install of the current package.json …\n');
326
+ const after = await measure(project.root, project.pm, measureOpts);
327
+ const removed = counted.map((gate) => ({
328
+ name: gate.pkg,
329
+ stillInstalledVia: stillInstalledVia(after.graph, gate.pkg, readMetaVersion(project, gate.pkg)),
330
+ }));
331
+ const realCounts = realSourceCounts(project, counted);
332
+ const drift = detectDrift(before.graph, after.graph, new Set([...counted.map((g) => g.pkg), ...ungated]));
333
+ const input = {
334
+ before: before.measurement,
335
+ after: after.measurement,
336
+ removed,
337
+ realCases: sum(counted, 'realCases'),
338
+ callsiteCases: realCounts.callsite,
339
+ agentCases: realCounts.agent,
340
+ generatedCases: sum(counted, 'generatedCases'),
341
+ holdoutCases: sum(counted, 'holdoutCases'),
342
+ acceptedMismatches: sum(counted, 'acceptedMismatches'),
343
+ sandboxed: counted.every((gate) => gate.sandboxed),
344
+ testsSkipped: counted.some((gate) => skippedCheck(gate, 'tests')),
345
+ holdoutSkipped: counted.some((gate) => skippedCheck(gate, 'holdout')),
346
+ typecheckSkipped: counted.some((gate) => skippedCheck(gate, 'typecheck')),
347
+ projectName: project.pkg.name ?? basename(project.root),
348
+ ungatedRemovals: ungated,
349
+ drift,
350
+ notes: [
351
+ ...(before.withoutLockfile ? ['before: measured without lockfile'] : []),
352
+ ...(after.withoutLockfile ? ['after: measured without lockfile'] : []),
353
+ ],
354
+ };
355
+ const outputs = [
356
+ [FILES.card, renderCard(input)],
357
+ [FILES.badge, renderBadge(removed.length)],
358
+ [FILES.report, renderReport(input)],
359
+ ];
360
+ for (const [name, content] of outputs)
361
+ writeFileSync(join(state, name), content);
362
+ log(summary(input, outputs.map(([name]) => join('.depkill', name))));
363
+ return input;
364
+ }
@@ -0,0 +1,139 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ import { loadableReplacement, resolveReplacementFiles } from './replacement.js';
4
+ import { exportSubpath } from './runtime/protocol.js';
5
+ import { replacementSandboxAvailable, runCases } from './runner.js';
6
+ import { outcomesEqual } from './serialize.js';
7
+ import { DepkillError } from './types.js';
8
+ import { stateDir, writeJson } from './util/fs.js';
9
+ import { paint, truncate } from './util/term.js';
10
+ const SHOWN_FAILURES = 10;
11
+ const SHOWN_CHARS = 200;
12
+ /** R31: shown once per check when replacement replays cannot be confined to their own files. */
13
+ export const SANDBOX_UNAVAILABLE = 'runtime sandbox unavailable on this Node version';
14
+ const SOURCES = new Set(['callsite', 'agent', 'generated']);
15
+ const OUTCOME_KINDS = new Set(['return', 'throw', 'unsupported', 'nondeterministic']);
16
+ function isCase(value) {
17
+ if (value === null || typeof value !== 'object')
18
+ return false;
19
+ const c = value;
20
+ return typeof c.id === 'string' && typeof c.exportId === 'string' && typeof c.source === 'string' && SOURCES.has(c.source)
21
+ && Array.isArray(c.args) && c.outcome !== null && typeof c.outcome === 'object' && OUTCOME_KINDS.has(c.outcome.kind);
22
+ }
23
+ /** Cases recorded by `depkill record`; DepkillError when there are none or the file is corrupt. */
24
+ export function readRecordedCases(project, pkg) {
25
+ const file = join(stateDir(project.root, pkg), 'cases.jsonl');
26
+ if (!existsSync(file))
27
+ throw new DepkillError(`No recorded cases for ${pkg}; run depkill record ${pkg} first.`);
28
+ const cases = [];
29
+ const ids = new Set();
30
+ readFileSync(file, 'utf8').split('\n').forEach((line, index) => {
31
+ if (line.trim() === '')
32
+ return;
33
+ let parsed;
34
+ try {
35
+ parsed = JSON.parse(line);
36
+ }
37
+ catch {
38
+ parsed = null;
39
+ }
40
+ if (!isCase(parsed) || ids.has(parsed.id)) {
41
+ throw new DepkillError(`${file}:${index + 1} is not a valid recorded case; run depkill record ${pkg} again.`);
42
+ }
43
+ ids.add(parsed.id);
44
+ cases.push(parsed);
45
+ });
46
+ if (cases.length === 0)
47
+ throw new DepkillError(`No recorded cases for ${pkg}; run depkill record ${pkg} first.`);
48
+ return cases;
49
+ }
50
+ function toInput({ id, exportId, source, args }) {
51
+ return { id, exportId, source, args };
52
+ }
53
+ /** Replays `group` (all of one subpath) against its replacement file, or fails it when none is configured. */
54
+ async function replay(project, subpath, file, group, opts) {
55
+ if (file === undefined) {
56
+ const missing = { kind: 'unsupported', reason: `no replacement for ${subpath}` };
57
+ return new Map(group.map((c) => [c.id, missing]));
58
+ }
59
+ const path = loadableReplacement(project, file);
60
+ // Same runtime as record: same child, same double run, same async/unsupported rules, same cwd.
61
+ const replayed = await runCases({ kind: 'file', path }, group.map(toInput), { caseTimeoutMs: opts.caseTimeoutMs, cwd: project.root });
62
+ return new Map(replayed.map((c) => [c.id, c.outcome]));
63
+ }
64
+ /**
65
+ * Runs `inputs` against the replacement files (root file for `#…` ids, configured subpath files for `/sub#…` ids),
66
+ * sandboxed exactly as `check` replays recorded cases; a subpath without a replacement file is `unsupported`.
67
+ * Used by check and by the gate's holdout (R43).
68
+ */
69
+ export async function replayAgainstReplacement(project, files, inputs, opts = {}) {
70
+ const groups = new Map();
71
+ for (const c of inputs) {
72
+ const subpath = exportSubpath(c.exportId);
73
+ groups.set(subpath, [...(groups.get(subpath) ?? []), c]);
74
+ }
75
+ const actual = new Map();
76
+ for (const [subpath, group] of groups) {
77
+ const file = subpath === '' ? files.root : Object.hasOwn(files.subpaths, subpath) ? files.subpaths[subpath] : undefined;
78
+ for (const [id, outcome] of await replay(project, subpath, file, group, opts))
79
+ actual.set(id, outcome);
80
+ }
81
+ return actual;
82
+ }
83
+ /**
84
+ * Replays every recorded case of `pkg` whose original outcome is `return` or `throw` against the replacement
85
+ * (root file for `#…` ids, configured subpath files for `/sub#…` ids) and compares outcomes with outcomesEqual.
86
+ * Cases recorded as unsupported/nondeterministic are `skipped`; any other replacement outcome that differs —
87
+ * including unsupported ones such as 'export not found' or nondeterminism — is a failure. Writes
88
+ * `.depkill/<pkg-safe>/check.json` and prints a summary.
89
+ */
90
+ export async function runCheck(project, pkg, opts = {}) {
91
+ const log = opts.log ?? ((text) => { process.stdout.write(text); });
92
+ const cases = readRecordedCases(project, pkg);
93
+ const files = resolveReplacementFiles(project, pkg, opts.replacement);
94
+ const replayable = cases.filter((c) => c.outcome.kind === 'return' || c.outcome.kind === 'throw');
95
+ const actual = await replayAgainstReplacement(project, files, replayable, opts);
96
+ const failures = replayable
97
+ .filter((c) => !outcomesEqual(c.outcome, actual.get(c.id)))
98
+ .map((c) => ({ caseId: c.id, exportId: c.exportId, source: c.source, expected: c.outcome, actual: actual.get(c.id) }));
99
+ const result = {
100
+ pkg, total: replayable.length, passed: replayable.length - failures.length, skipped: cases.length - replayable.length, failures,
101
+ };
102
+ writeJson(join(stateDir(project.root, pkg), 'check.json'), result);
103
+ log(renderCheck(result, { color: opts.color ?? false, cases, checkJson: relative(project.root, join(stateDir(project.root, pkg), 'check.json')) }));
104
+ if (!replacementSandboxAvailable())
105
+ log(`Note: ${SANDBOX_UNAVAILABLE}
106
+ `);
107
+ return result;
108
+ }
109
+ /** A check passes only when at least one case was compared and none failed: 0/0 proves nothing (R30). */
110
+ export function checkPassed(result) {
111
+ return result.total > 0 && result.failures.length === 0;
112
+ }
113
+ function shown(value) {
114
+ return truncate(JSON.stringify(value), SHOWN_CHARS);
115
+ }
116
+ /**
117
+ * `✓ 212/214 cases match` (✗ when any case fails), the skipped count, then up to 10 failures with export id,
118
+ * source, args, expected and actual outcome (encoded JSON, each truncated to 200 characters). With no comparable
119
+ * case (R30) the first line is `✗ No comparable cases — nothing was proven`.
120
+ */
121
+ export function renderCheck(result, opts) {
122
+ const { color } = opts;
123
+ const lines = result.total === 0
124
+ ? [`${paint('red', '✗', color)} No comparable cases — nothing was proven`]
125
+ : [`${checkPassed(result) ? paint('green', '✓', color) : paint('red', '✗', color)} ${result.passed}/${result.total} cases match`];
126
+ if (result.skipped > 0)
127
+ lines.push(` ${result.skipped} skipped (unsupported or nondeterministic when recorded)`);
128
+ const args = new Map((opts.cases ?? []).map((c) => [c.id, c.args]));
129
+ for (const failure of result.failures.slice(0, SHOWN_FAILURES)) {
130
+ lines.push('', ` ${paint('bold', `${failure.exportId} (${failure.source})`, color)} case ${failure.caseId}`);
131
+ if (args.has(failure.caseId))
132
+ lines.push(` args: ${shown(args.get(failure.caseId))}`);
133
+ lines.push(` expected: ${shown(failure.expected)}`, ` actual: ${paint('red', shown(failure.actual), color)}`);
134
+ }
135
+ const more = result.failures.length - SHOWN_FAILURES;
136
+ if (more > 0)
137
+ lines.push('', ` … and ${more} more failures${opts.checkJson === undefined ? '' : ` (see ${opts.checkJson})`}`);
138
+ return `${lines.join('\n')}\n`;
139
+ }