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,532 @@
1
+ // `gate <pkg>`: the done rule. Replays the recorded cases and fresh holdout inputs near real usage (R43), runs the
2
+ // anti-cheat checks on every replacement file, checks package.json against the baseline and runs the project's own
3
+ // typecheck and tests. Every check runs (so the agent sees every problem at once) except the slow typecheck/tests,
4
+ // which are skipped once anything failed.
5
+ import { createHash } from 'node:crypto';
6
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
7
+ import { createRequire } from 'node:module';
8
+ import { dirname, join, relative, resolve, sep } from 'node:path';
9
+ import { checkNoEmbeddedOutputs, checkNotCopied, checkSelfContained } from './anticheat.js';
10
+ import { readRecordedCases, runCheck, SANDBOX_UNAVAILABLE } from './check.js';
11
+ import { holdoutCheck } from './gate/holdout.js';
12
+ import { runProcess } from './gate/process.js';
13
+ import { resolveReplacementFiles } from './replacement.js';
14
+ import { replacementSandboxAvailable } from './runner.js';
15
+ import { exportName } from './runtime/protocol.js';
16
+ import { DepkillError } from './types.js';
17
+ import { pkgSafe, readJson, stateDir, writeJson } from './util/fs.js';
18
+ import { paint } from './util/term.js';
19
+ import { collectRelativeImports, listSourceFiles, scanUsage } from './usage.js';
20
+ export { runShell } from './gate/process.js';
21
+ const DEP_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
22
+ const SLOW_TIMEOUT_MS = 10 * 60 * 1000;
23
+ const SHOWN_IDS = 5;
24
+ /** R42: accepted generated mismatches may not exceed this share of the compared generated cases. */
25
+ const MAX_ACCEPTED_RATIO = 0.1;
26
+ const NAME_WIDTH = 19;
27
+ const RERECORD = 're-run depkill record';
28
+ const NPM_DEFAULT_TEST = 'Error: no test specified';
29
+ const pass = (name, detail) => ({ name, status: 'pass', detail });
30
+ const fail = (name, detail) => ({ name, status: 'fail', detail });
31
+ const skipped = (name, detail) => ({ name, status: 'skipped', detail });
32
+ function listIds(ids) {
33
+ const more = ids.length - SHOWN_IDS;
34
+ return `${ids.slice(0, SHOWN_IDS).join(', ')}${more > 0 ? ` (+${more} more)` : ''}`;
35
+ }
36
+ const compared = (c) => c.outcome.kind === 'return' || c.outcome.kind === 'throw';
37
+ const isReal = (c) => c.source !== 'generated';
38
+ const uncomparable = (c) => !compared(c);
39
+ /**
40
+ * C1: why each judged export (meta.json `exportIds` except `#*`; the case export ids when there is no list) lacks
41
+ * evidence. A function export needs at least one compared real (callsite/agent) case, and no more uncomparable real
42
+ * cases than compared ones; a plain-value export (`exportKinds`) needs one compared case from any source.
43
+ */
44
+ function unprovenExports(pkg, cases, evidence) {
45
+ const ids = (evidence.exportIds ?? [...new Set(cases.map((c) => c.exportId))]).filter((id) => exportName(id) !== '*');
46
+ return [...new Set(ids)].sort().flatMap((id) => {
47
+ const own = cases.filter((c) => c.exportId === id);
48
+ const real = own.filter(isReal);
49
+ const comparedReal = real.filter(compared).length;
50
+ const isValue = evidence.exportKinds?.[id] === 'value';
51
+ const comparedAny = isValue ? own.filter(compared).length : comparedReal;
52
+ const missing = real.filter(uncomparable).length;
53
+ if (comparedAny >= 1 && missing <= comparedAny)
54
+ return [];
55
+ return [`\`${id}\` cannot be proven (${comparedReal} of ${real.length} real cases comparable; `
56
+ + `add inputs to .depkill/${pkgSafe(pkg)}/inputs.mjs or pick another package)`];
57
+ });
58
+ }
59
+ /**
60
+ * `cases-real`: every compared callsite/agent case matches, and every used export has usable evidence (C1,
61
+ * unprovenExports). No compared real case at all is a failure (R27) unless every used export is a plain value
62
+ * proven by a compared case: generated inputs alone are no evidence of how the project calls the package.
63
+ */
64
+ export function casesRealCheck(pkg, cases, result, evidence = {}) {
65
+ const real = cases.filter((c) => isReal(c) && compared(c));
66
+ const unproven = unprovenExports(pkg, cases, evidence);
67
+ const judged = (evidence.exportIds ?? cases.map((c) => c.exportId)).filter((id) => exportName(id) !== '*');
68
+ if (real.length === 0 && (unproven.length > 0 || judged.length === 0)) {
69
+ const lines = [`no real-usage evidence: add inputs to .depkill/${pkgSafe(pkg)}/inputs.mjs and re-record`, ...unproven];
70
+ return { check: fail('cases-real', lines.join('\n')), compared: 0 };
71
+ }
72
+ const failed = result.failures.filter((f) => f.source !== 'generated').map((f) => f.caseId);
73
+ const summary = `${real.length - failed.length}/${real.length} real-usage cases match`;
74
+ const problems = [
75
+ ...(failed.length === 0 ? [] : [`${summary}; failing: ${listIds(failed)} (run depkill check ${pkg} for details)`]),
76
+ ...unproven,
77
+ ];
78
+ const check = problems.length === 0 ? pass('cases-real', summary) : fail('cases-real', problems.join('\n'));
79
+ return { check, compared: real.length };
80
+ }
81
+ function isEntry(value) {
82
+ if (value === null || typeof value !== 'object')
83
+ return false;
84
+ const entry = value;
85
+ return typeof entry.caseId === 'string' && typeof entry.reason === 'string';
86
+ }
87
+ /**
88
+ * `cases-generated`: every failing generated case is listed in `accepted.json` (`accepted`: its parsed content, or
89
+ * undefined when there is none) with a non-empty reason. A malformed file, an empty reason, an unknown case id
90
+ * (stale) or a non-generated case id is itself a failure.
91
+ */
92
+ export function casesGeneratedCheck(pkg, cases, result, accepted) {
93
+ const name = 'cases-generated';
94
+ const file = `.depkill/${pkgSafe(pkg)}/accepted.json`;
95
+ const generated = cases.filter((c) => !isReal(c) && compared(c));
96
+ const failed = result.failures.filter((f) => f.source === 'generated').map((f) => f.caseId);
97
+ if (accepted !== undefined && (!Array.isArray(accepted) || !accepted.every(isEntry))) {
98
+ return { check: fail(name, `${file} must be a JSON array of { "caseId": "<id>", "reason": "<why the difference is acceptable>" }`), compared: generated.length, accepted: 0 };
99
+ }
100
+ const entries = (accepted ?? []);
101
+ const byId = new Map(cases.map((c) => [c.id, c]));
102
+ const problems = [];
103
+ const valid = new Set();
104
+ for (const { caseId, reason } of entries) {
105
+ const recordedCase = byId.get(caseId);
106
+ if (recordedCase === undefined)
107
+ problems.push(`${file} lists "${caseId}", which is not a recorded case (stale entry: remove it)`);
108
+ else if (recordedCase.source !== 'generated')
109
+ problems.push(`${file} lists "${caseId}", a ${recordedCase.source} case: only generated cases can be accepted`);
110
+ else if (reason.trim() === '')
111
+ problems.push(`${file} entry "${caseId}" has no reason: say why the difference is acceptable`);
112
+ else
113
+ valid.add(caseId);
114
+ }
115
+ const unaccepted = failed.filter((id) => !valid.has(id));
116
+ const acceptedCount = failed.length - unaccepted.length;
117
+ if (acceptedCount > MAX_ACCEPTED_RATIO * generated.length) {
118
+ problems.push(`too many accepted mismatches (${acceptedCount} of ${generated.length}); fix the replacement instead of accepting`);
119
+ }
120
+ if (unaccepted.length > 0) {
121
+ problems.unshift(`${unaccepted.length} generated case${unaccepted.length === 1 ? '' : 's'} differ from the original: ${listIds(unaccepted)}. `
122
+ + `Fix the replacement, or add { "caseId": "<id>", "reason": "<why the difference is acceptable>" } to ${file} (run depkill check ${pkg} to see them)`);
123
+ }
124
+ if (problems.length > 0)
125
+ return { check: fail(name, problems.join('\n')), compared: generated.length, accepted: acceptedCount };
126
+ if (generated.length === 0)
127
+ return { check: pass(name, 'no generated cases'), compared: 0, accepted: 0 };
128
+ const summary = `${generated.length - failed.length}/${generated.length} generated cases match`;
129
+ return {
130
+ check: pass(name, acceptedCount === 0 ? summary : `${summary}; ${acceptedCount} accepted in ${file}`),
131
+ compared: generated.length, accepted: acceptedCount,
132
+ };
133
+ }
134
+ function depNames(pkg) {
135
+ return new Set(DEP_FIELDS.flatMap((field) => Object.keys(pkg[field] ?? {})));
136
+ }
137
+ /** `removed` and `no-new-deps`, against `.depkill/baseline/package.json` (`baseline`: null when missing). */
138
+ export function dependencyChecks(pkg, current, baseline) {
139
+ if (baseline === null) {
140
+ const detail = `no baseline (.depkill/baseline/package.json): ${RERECORD}`;
141
+ return [fail('removed', detail), fail('no-new-deps', detail)];
142
+ }
143
+ const fields = DEP_FIELDS.filter((field) => Object.hasOwn(current[field] ?? {}, pkg));
144
+ const removed = fields.length === 0 ? pass('removed', `${pkg} is not in package.json`)
145
+ : fail('removed', `${pkg} is still in ${fields.join(', ')} of package.json: remove it and reinstall`);
146
+ const before = depNames(baseline);
147
+ const added = [...depNames(current)].filter((name) => name !== 'depkill' && !before.has(name)).sort();
148
+ const noNew = added.length === 0 ? pass('no-new-deps', 'no dependencies added')
149
+ : fail('no-new-deps', `added since the baseline (.depkill/baseline/package.json): ${added.join(', ')}; a replacement must not add dependencies`);
150
+ return [removed, noNew];
151
+ }
152
+ function readBaseline(project) {
153
+ const file = join(stateDir(project.root), 'baseline', 'package.json');
154
+ if (!existsSync(file))
155
+ return null;
156
+ try {
157
+ return readJson(file);
158
+ }
159
+ catch (error) {
160
+ throw new DepkillError(`${error instanceof Error ? error.message : String(error)} (the baseline is written by the first depkill record)`);
161
+ }
162
+ }
163
+ function noImportsLeft(project, pkg) {
164
+ const sites = scanUsage(project, new Set([pkg]));
165
+ if (sites.length === 0)
166
+ return pass('no-imports-left', `no imports of ${pkg} left`);
167
+ const where = sites.map((s) => `${s.file}:${s.line}`).join(', ');
168
+ return fail('no-imports-left', `${pkg} is still imported at ${where}: import your replacement instead`);
169
+ }
170
+ const relPath = (root, file) => relative(root, file).split(sep).join('/');
171
+ const FOLD_CASE = process.platform === 'win32' || process.platform === 'darwin';
172
+ const foldCase = (value) => (FOLD_CASE ? value.toLowerCase() : value);
173
+ const RESOLVE_EXTS = ['.js', '.cjs', '.mjs', '.jsx', '.ts', '.cts', '.mts', '.tsx'];
174
+ function realpathSafe(file) {
175
+ try {
176
+ return realpathSync.native(file);
177
+ }
178
+ catch {
179
+ return file;
180
+ }
181
+ }
182
+ function isRegularFile(file) {
183
+ try {
184
+ return statSync(file).isFile();
185
+ }
186
+ catch {
187
+ return false;
188
+ }
189
+ }
190
+ function resolveRelativeTarget(fromFile, specifier, targetByReal) {
191
+ const clean = specifier.split(/[?#]/)[0];
192
+ const base = resolve(dirname(fromFile), clean);
193
+ const candidates = [base];
194
+ if (base.endsWith('.js'))
195
+ candidates.push(`${base.slice(0, -3)}.ts`, `${base.slice(0, -3)}.tsx`);
196
+ else if (base.endsWith('.mjs'))
197
+ candidates.push(`${base.slice(0, -4)}.mts`);
198
+ else if (base.endsWith('.cjs'))
199
+ candidates.push(`${base.slice(0, -4)}.cts`);
200
+ for (const ext of RESOLVE_EXTS)
201
+ candidates.push(`${base}${ext}`);
202
+ for (const ext of RESOLVE_EXTS)
203
+ candidates.push(join(base, `index${ext}`));
204
+ for (const candidate of candidates) {
205
+ if (!isRegularFile(candidate))
206
+ continue;
207
+ const hit = targetByReal.get(foldCase(realpathSafe(candidate)));
208
+ if (hit !== undefined)
209
+ return hit;
210
+ }
211
+ return null;
212
+ }
213
+ /** Root-relative `/` importers per replacement file (`files.root` and `files.subpaths`). */
214
+ export function findImporters(project, files) {
215
+ const targets = [...new Set([files.root, ...Object.values(files.subpaths)])];
216
+ const targetByReal = new Map();
217
+ const importers = new Map();
218
+ for (const file of targets) {
219
+ const rel = relPath(project.root, file);
220
+ targetByReal.set(foldCase(realpathSafe(file)), rel);
221
+ importers.set(rel, new Set());
222
+ }
223
+ for (const file of listSourceFiles(project.root)) {
224
+ if (targetByReal.has(foldCase(realpathSafe(file))))
225
+ continue;
226
+ const text = readFileSync(file, 'utf8');
227
+ if (!text.includes('./') && !text.includes('../'))
228
+ continue;
229
+ const fromRel = relPath(project.root, file);
230
+ for (const spec of collectRelativeImports(project, file, text)) {
231
+ const targetRel = resolveRelativeTarget(file, spec, targetByReal);
232
+ if (targetRel !== null)
233
+ importers.get(targetRel).add(fromRel);
234
+ }
235
+ }
236
+ return new Map([...importers].map(([target, set]) => [target, [...set].sort()]));
237
+ }
238
+ /** `wired`: every configured replacement file is actually imported/required by at least one project source file. */
239
+ export function wiredCheck(project, files, importers) {
240
+ const targets = [...new Set([files.root, ...Object.values(files.subpaths)])].map((f) => relPath(project.root, f));
241
+ const missing = targets.filter((rel) => (importers.get(rel) ?? []).length === 0);
242
+ if (missing.length > 0) {
243
+ return fail('wired', missing.map((rel) => `replacement ${rel} is not imported anywhere`).join('\n'));
244
+ }
245
+ return pass('wired', 'replacement is imported by project code');
246
+ }
247
+ function globToRegExp(pattern) {
248
+ let re = '^';
249
+ for (let i = 0; i < pattern.length; i += 1) {
250
+ const ch = pattern[i];
251
+ if (ch === '*') {
252
+ if (pattern[i + 1] === '*') {
253
+ if (pattern[i + 2] === '/') {
254
+ re += '(?:.+/)?';
255
+ i += 2;
256
+ }
257
+ else {
258
+ re += '.*';
259
+ i += 1;
260
+ }
261
+ }
262
+ else {
263
+ re += '[^/]*';
264
+ }
265
+ }
266
+ else if (ch === '?') {
267
+ re += '[^/]';
268
+ }
269
+ else if (/[.*+?^${}()|[\]\\]/.test(ch)) {
270
+ re += `\\${ch}`;
271
+ }
272
+ else {
273
+ re += ch;
274
+ }
275
+ }
276
+ return new RegExp(`${re}$`);
277
+ }
278
+ /** Whether `rel` (root-relative `/`) is included by an npm `package.json` `files` array. */
279
+ export function isCoveredByFiles(rel, files) {
280
+ const norm = rel.replace(/^\.?\//, '');
281
+ let included = false;
282
+ for (const entry of files) {
283
+ if (typeof entry !== 'string')
284
+ continue;
285
+ let pat = entry.trim();
286
+ if (pat === '')
287
+ continue;
288
+ const negate = pat.startsWith('!');
289
+ if (negate)
290
+ pat = pat.slice(1);
291
+ pat = pat.replace(/^\.?\//, '').replace(/\/+$/, '');
292
+ if (pat === '')
293
+ continue;
294
+ const matched = pat.includes('*') || pat.includes('?')
295
+ ? globToRegExp(pat).test(norm)
296
+ : norm === pat || norm.startsWith(`${pat}/`);
297
+ if (matched)
298
+ included = !negate;
299
+ }
300
+ return included;
301
+ }
302
+ /** `ships`: when `package.json` declares `files`, a replacement imported by a shipped file must also ship. */
303
+ export function shipsCheck(project, files, importers) {
304
+ if (!Array.isArray(project.pkg.files))
305
+ return skipped('ships', 'no files field in package.json');
306
+ const entries = project.pkg.files;
307
+ const targets = [...new Set([files.root, ...Object.values(files.subpaths)])].map((f) => relPath(project.root, f));
308
+ const unshipped = targets.filter((rel) => !isCoveredByFiles(rel, entries)
309
+ && (importers.get(rel) ?? []).some((imp) => isCoveredByFiles(imp, entries)));
310
+ if (unshipped.length > 0) {
311
+ return fail('ships', unshipped.map((rel) => `replacement ${rel} is not included in package.json files; it won't be published`).join('\n'));
312
+ }
313
+ return pass('ships', 'replacement files are covered by package.json files');
314
+ }
315
+ /** `self-contained`, `not-copied`, `no-embedded-outputs` over every replacement file (R4), one check per name. */
316
+ function antiCheatChecks(project, pkg, files, cases) {
317
+ const originalDir = join(stateDir(project.root, pkg), 'original');
318
+ const perFile = [...new Set([files.root, ...Object.values(files.subpaths)])].map((file) => {
319
+ const src = readFileSync(file, 'utf8');
320
+ const opts = { ts: project.ts, fileName: file };
321
+ return { rel: relPath(project.root, file), checks: [checkSelfContained(src, pkg, opts), checkNotCopied(src, originalDir, opts), checkNoEmbeddedOutputs(src, cases, opts)] };
322
+ });
323
+ return perFile[0].checks.map(({ name }, i) => {
324
+ const results = perFile.map((f) => ({ rel: f.rel, check: f.checks[i] }));
325
+ const failing = results.filter((r) => r.check.status === 'fail');
326
+ const shown = failing.length > 0 ? failing : results;
327
+ const detail = shown.flatMap((r) => r.check.detail.split('\n').map((line) => `${r.rel}: ${line}`)).join('\n');
328
+ return failing.length > 0 ? fail(name, detail) : pass(name, detail);
329
+ });
330
+ }
331
+ function tail(result) {
332
+ return result.output.trim() === '' ? '' : `\n${result.output.trimEnd()}`;
333
+ }
334
+ /** `typecheck`: the project's own `tsc --noEmit -p <root>` when it has a tsconfig.json and TypeScript. */
335
+ export async function typecheckCheck(project) {
336
+ const name = 'typecheck';
337
+ if (!project.hasTsconfig)
338
+ return skipped(name, 'no tsconfig.json');
339
+ if (project.ts === null)
340
+ return skipped(name, 'typescript is not installed');
341
+ let tsc;
342
+ try {
343
+ tsc = join(dirname(createRequire(join(project.root, 'package.json')).resolve('typescript/package.json')), 'bin', 'tsc');
344
+ }
345
+ catch {
346
+ return skipped(name, 'typescript is not resolvable from the project root');
347
+ }
348
+ const result = await runProcess(process.execPath, [tsc, '--noEmit', '-p', project.root], { cwd: project.root, timeoutMs: SLOW_TIMEOUT_MS });
349
+ if (result.timedOut)
350
+ return fail(name, `tsc --noEmit timed out after 10 minutes${tail(result)}`);
351
+ return result.code === 0 ? pass(name, 'tsc --noEmit passed') : fail(name, `tsc --noEmit failed (exit code ${result.code ?? 'none'}):${tail(result)}`);
352
+ }
353
+ function defaultTestCommand(project) {
354
+ const script = project.pkg.scripts?.test;
355
+ if (script === undefined || script.trim() === '' || script.includes(NPM_DEFAULT_TEST))
356
+ return null;
357
+ return project.pm === 'npm' ? 'npm test' : project.pm === 'pnpm' ? 'pnpm test' : 'yarn test';
358
+ }
359
+ async function testsCheck(project, opts) {
360
+ const name = 'tests';
361
+ if (opts.skipTests)
362
+ return skipped(name, '--skip-tests');
363
+ const cmd = opts.testCmd ?? defaultTestCommand(project);
364
+ if (cmd === null)
365
+ return skipped(name, 'no test script in package.json (pass --test-cmd "<command>" to run your tests)');
366
+ opts.progress?.(`Running ${cmd} …\n`);
367
+ const result = await runProcess(cmd, [], { cwd: project.root, timeoutMs: SLOW_TIMEOUT_MS, shell: true });
368
+ if (result.timedOut)
369
+ return fail(name, `${cmd} timed out after 10 minutes${tail(result)}`);
370
+ return result.code === 0 ? pass(name, `${cmd} passed`) : fail(name, `${cmd} failed (exit code ${result.code ?? 'none'}):${tail(result)}`);
371
+ }
372
+ function readAccepted(project, pkg) {
373
+ const file = join(stateDir(project.root, pkg), 'accepted.json');
374
+ if (!existsSync(file))
375
+ return { value: undefined };
376
+ try {
377
+ return { value: readJson(file) };
378
+ }
379
+ catch (error) {
380
+ return { error: error instanceof Error ? error.message : String(error) };
381
+ }
382
+ }
383
+ /**
384
+ * R37: sha256 of every file the gate verdict depends on — each replacement file, `.depkill/<pkg-safe>/cases.jsonl`
385
+ * and the root `package.json` — keyed by root-relative path with `/`. The card recomputes it to refuse a stale or
386
+ * hand-edited gate.json. DepkillError when no replacement is configured.
387
+ */
388
+ export function computeGateFingerprint(project, pkg) {
389
+ return fingerprintOf(project, pkg, false);
390
+ }
391
+ /**
392
+ * C3: the fingerprint the holdout seed is drawn from — computeGateFingerprint, except that replacement files are
393
+ * hashed with CRLF normalized to LF, so the same code checked out on Windows or Unix gets the same holdout inputs.
394
+ */
395
+ export function holdoutFingerprint(project, pkg) {
396
+ return fingerprintOf(project, pkg, true);
397
+ }
398
+ /** Bytes with every CRLF pair turned into LF (latin1 round trip: byte-exact for any encoding). */
399
+ function lfBytes(bytes) {
400
+ return Buffer.from(bytes.toString('latin1').replaceAll('\r\n', '\n'), 'latin1');
401
+ }
402
+ function fingerprintOf(project, pkg, normalizeReplacements) {
403
+ const files = resolveReplacementFiles(project, pkg);
404
+ const replacements = new Set([files.root, ...Object.values(files.subpaths)]);
405
+ const paths = [...replacements, join(stateDir(project.root, pkg), 'cases.jsonl'), join(project.root, 'package.json')];
406
+ const entries = [...new Set(paths)].map((file) => {
407
+ let digest = 'missing';
408
+ try {
409
+ const bytes = readFileSync(file);
410
+ digest = createHash('sha256').update(normalizeReplacements && replacements.has(file) ? lfBytes(bytes) : bytes).digest('hex');
411
+ }
412
+ catch {
413
+ // recorded as missing: the card cannot match it
414
+ }
415
+ return [relPath(project.root, file), digest];
416
+ });
417
+ return Object.fromEntries(entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
418
+ }
419
+ /**
420
+ * R46: the holdout seed, derived from the code under test so the same files always get the same verdict: the first
421
+ * 31 bits of sha256 over the fingerprint entries of the replacement files and cases.jsonl (sorted by path; the root
422
+ * package.json is left out). Any change to the replacement or the cases draws a new holdout set. runGate passes
423
+ * holdoutFingerprint (C3: line endings do not pick the holdout).
424
+ */
425
+ export function holdoutSeedFor(fingerprint) {
426
+ const entries = Object.entries(fingerprint).filter(([path]) => path !== 'package.json')
427
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
428
+ const digest = createHash('sha256').update(entries.map(([path, hash]) => `${path}\0${hash}\n`).join('')).digest();
429
+ return digest.readUInt32BE(0) >>> 1;
430
+ }
431
+ /** meta.json `exportIds` / `exportKinds` as written by record; empty when there is no meta.json (C1 then judges case ids). */
432
+ function readRecordedExports(project, pkg) {
433
+ const file = join(stateDir(project.root, pkg), 'meta.json');
434
+ if (!existsSync(file))
435
+ return {};
436
+ let meta;
437
+ try {
438
+ meta = readJson(file);
439
+ }
440
+ catch (error) {
441
+ throw new DepkillError(`${error instanceof Error ? error.message : String(error)} (${RERECORD})`);
442
+ }
443
+ const { exportIds, exportKinds } = (meta !== null && typeof meta === 'object' ? meta : {});
444
+ const ids = Array.isArray(exportIds) && exportIds.every((id) => typeof id === 'string') ? exportIds : undefined;
445
+ const kinds = exportKinds !== null && typeof exportKinds === 'object' && !Array.isArray(exportKinds)
446
+ ? Object.fromEntries(Object.entries(exportKinds).filter((entry) => typeof entry[1] === 'string')) : undefined;
447
+ return { ...(ids === undefined ? {} : { exportIds: ids }), ...(kinds === undefined ? {} : { exportKinds: kinds }) };
448
+ }
449
+ /** Checks 1–2: replays the cases (runCheck, quietly) and judges real and generated cases separately. */
450
+ async function caseChecks(project, pkg, cases) {
451
+ let result;
452
+ try {
453
+ result = await runCheck(project, pkg, { log: () => { } });
454
+ }
455
+ catch (error) {
456
+ if (!(error instanceof DepkillError))
457
+ throw error;
458
+ return {
459
+ checks: [fail('cases-real', `could not replay the recorded cases: ${error.message}`), fail('cases-generated', 'not compared (see cases-real)')],
460
+ real: 0, generated: 0, accepted: 0, sandboxed: false,
461
+ };
462
+ }
463
+ const judged = casesRealCheck(pkg, cases, result, readRecordedExports(project, pkg));
464
+ const real = replacementSandboxAvailable() ? judged
465
+ : { ...judged, check: { ...judged.check, detail: `${judged.check.detail} (${SANDBOX_UNAVAILABLE})` } };
466
+ const acceptedFile = readAccepted(project, pkg);
467
+ const generated = 'error' in acceptedFile
468
+ ? { check: fail('cases-generated', acceptedFile.error), compared: cases.filter((c) => !isReal(c) && compared(c)).length, accepted: 0 }
469
+ : casesGeneratedCheck(pkg, cases, result, acceptedFile.value);
470
+ return {
471
+ checks: [real.check, generated.check], real: real.compared, generated: generated.compared, accepted: generated.accepted,
472
+ sandboxed: replacementSandboxAvailable(),
473
+ };
474
+ }
475
+ /**
476
+ * Runs the gate for `pkg` and writes `.depkill/<pkg-safe>/gate.json`. `pass` = no check failed. DepkillError
477
+ * (exit 2) when nothing was recorded or no replacement is configured.
478
+ */
479
+ export async function runGate(project, pkg, opts) {
480
+ const cases = readRecordedCases(project, pkg);
481
+ const files = resolveReplacementFiles(project, pkg);
482
+ // Taken before anything runs: the verdict is about exactly these bytes.
483
+ const fingerprint = computeGateFingerprint(project, pkg);
484
+ const holdoutSeed = opts.holdoutSeed ?? holdoutSeedFor(holdoutFingerprint(project, pkg));
485
+ const replayed = await caseChecks(project, pkg, cases);
486
+ opts.progress?.('Running holdout cases …\n');
487
+ const holdout = await holdoutCheck(project, pkg, cases, files, holdoutSeed);
488
+ const importers = findImporters(project, files);
489
+ const checks = [
490
+ ...replayed.checks,
491
+ holdout.check,
492
+ ...dependencyChecks(pkg, project.pkg, readBaseline(project)),
493
+ noImportsLeft(project, pkg),
494
+ wiredCheck(project, files, importers),
495
+ shipsCheck(project, files, importers),
496
+ ...antiCheatChecks(project, pkg, files, cases),
497
+ ];
498
+ const blocked = () => checks.some((c) => c.status === 'fail');
499
+ const slowSkipped = (name) => skipped(name, 'fix the failing checks above first');
500
+ if (blocked())
501
+ checks.push(slowSkipped('typecheck'));
502
+ else {
503
+ if (project.hasTsconfig && project.ts !== null)
504
+ opts.progress?.('Running tsc --noEmit …\n');
505
+ checks.push(await typecheckCheck(project));
506
+ }
507
+ checks.push(blocked() ? slowSkipped('tests') : await testsCheck(project, opts));
508
+ const result = {
509
+ pkg, pass: !blocked(), realCases: replayed.real, generatedCases: replayed.generated, acceptedMismatches: replayed.accepted,
510
+ checks, at: new Date().toISOString(), sandboxed: replayed.sandboxed, fingerprint, holdoutCases: holdout.compared, holdoutSeed,
511
+ };
512
+ writeJson(join(stateDir(project.root, pkg), 'gate.json'), result);
513
+ return result;
514
+ }
515
+ /** One line per check (✓ pass, ✗ fail, – skipped; further detail lines indented), then the verdict. */
516
+ export function renderGate(result, opts) {
517
+ const { color } = opts;
518
+ const mark = (status) => (status === 'pass' ? paint('green', '✓', color)
519
+ : status === 'fail' ? paint('red', '✗', color) : paint('dim', '–', color));
520
+ const lines = result.checks.flatMap((c) => {
521
+ const [first = '', ...rest] = c.detail.split('\n');
522
+ return [`${mark(c.status)} ${c.name.padEnd(NAME_WIDTH)} ${first}`.trimEnd(), ...rest.map((line) => `${' '.repeat(NAME_WIDTH + 4)}${line}`.trimEnd())];
523
+ });
524
+ lines.push('', `holdout: ${result.holdoutCases} fresh cases`);
525
+ lines.push(result.sandboxed ? 'runtime sandbox: on' : 'runtime sandbox: off (needs Node 22.13+ or 23.5+ for stable --permission)');
526
+ if (result.acceptedMismatches > 0) {
527
+ lines.push('', `Accepted generated mismatches: ${result.acceptedMismatches} (see .depkill/${pkgSafe(result.pkg)}/accepted.json)`);
528
+ }
529
+ lines.push('', result.pass ? paint('green', 'Gate passed. Run depkill card.', color)
530
+ : `Gate failed: fix the ✗ checks above, then run depkill gate ${result.pkg} again.`);
531
+ return `${lines.join('\n')}\n`;
532
+ }