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.
- package/LICENSE +21 -0
- package/README.md +179 -3
- package/data/module-replacements.LICENSE +21 -0
- package/data/module-replacements.json +947 -0
- package/dist/src/anticheat/constants.js +105 -0
- package/dist/src/anticheat/imports.js +419 -0
- package/dist/src/anticheat/tokens.js +177 -0
- package/dist/src/anticheat.js +189 -0
- package/dist/src/card/format.js +113 -0
- package/dist/src/card/svg.js +137 -0
- package/dist/src/card.js +364 -0
- package/dist/src/check.js +139 -0
- package/dist/src/cli.js +333 -0
- package/dist/src/gate/holdout.js +78 -0
- package/dist/src/gate/process.js +78 -0
- package/dist/src/gate.js +532 -0
- package/dist/src/graph.js +148 -0
- package/dist/src/holdout/perturb.js +108 -0
- package/dist/src/holdout/snapshot.js +113 -0
- package/dist/src/init.js +76 -0
- package/dist/src/inputs/generate.js +282 -0
- package/dist/src/inputs.js +273 -0
- package/dist/src/measure.js +149 -0
- package/dist/src/project.js +72 -0
- package/dist/src/record.js +180 -0
- package/dist/src/registry.js +78 -0
- package/dist/src/replacement.js +146 -0
- package/dist/src/runner.js +227 -0
- package/dist/src/runtime/agent-inputs.js +36 -0
- package/dist/src/runtime/child.js +260 -0
- package/dist/src/runtime/esm-hooks.js +44 -0
- package/dist/src/runtime/fsguard.js +264 -0
- package/dist/src/runtime/inspect.js +115 -0
- package/dist/src/runtime/lockdown.js +157 -0
- package/dist/src/runtime/protocol.js +16 -0
- package/dist/src/scan.js +210 -0
- package/dist/src/serialize.js +399 -0
- package/dist/src/tooling.js +88 -0
- package/dist/src/types.js +9 -0
- package/dist/src/usage/common.js +36 -0
- package/dist/src/usage/fallback.js +227 -0
- package/dist/src/usage/ts.js +142 -0
- package/dist/src/usage.js +97 -0
- package/dist/src/util/exports.js +86 -0
- package/dist/src/util/fs.js +64 -0
- package/dist/src/util/term.js +61 -0
- package/package.json +54 -6
- package/skills/AGENTS.section.md +52 -0
- package/skills/depkill/SKILL.md +148 -0
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { runCard } from './card.js';
|
|
6
|
+
import { checkPassed, runCheck } from './check.js';
|
|
7
|
+
import { renderGate, runGate } from './gate.js';
|
|
8
|
+
import { INIT_AGENTS, runInit } from './init.js';
|
|
9
|
+
import { detectProject } from './project.js';
|
|
10
|
+
import { runRecord } from './record.js';
|
|
11
|
+
import { renderScan, runScan } from './scan.js';
|
|
12
|
+
import { DepkillError } from './types.js';
|
|
13
|
+
import { colorEnabled, terminalWidth } from './util/term.js';
|
|
14
|
+
export function writeOut(text) {
|
|
15
|
+
process.stdout.write(text);
|
|
16
|
+
}
|
|
17
|
+
export function writeErr(text) {
|
|
18
|
+
process.stderr.write(text);
|
|
19
|
+
}
|
|
20
|
+
/** Usage error (exit 2) for any argument a command does not take. */
|
|
21
|
+
export function expectNoArgs(command, args) {
|
|
22
|
+
if (args.length === 0)
|
|
23
|
+
return;
|
|
24
|
+
const [first] = args;
|
|
25
|
+
throw new DepkillError(first.startsWith('-') ? `Unknown option for ${command}: ${first}` : `${command} takes no arguments (got "${first}").`);
|
|
26
|
+
}
|
|
27
|
+
const scanCommand = {
|
|
28
|
+
name: 'scan',
|
|
29
|
+
usage: 'scan',
|
|
30
|
+
summary: 'Rank dependencies by how worthwhile and easy they are to remove',
|
|
31
|
+
async run(args, globals) {
|
|
32
|
+
expectNoArgs('scan', args);
|
|
33
|
+
const entries = await runScan(detectProject(globals.cwd), { offline: globals.offline });
|
|
34
|
+
writeOut(globals.json
|
|
35
|
+
? `${JSON.stringify(entries, null, 2)}\n`
|
|
36
|
+
: renderScan(entries, { color: colorEnabled(process.stdout), width: terminalWidth() }));
|
|
37
|
+
return 0;
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
const DEFAULT_MAX_GENERATED = 200;
|
|
41
|
+
const MAX_GENERATED_LIMIT = 100_000;
|
|
42
|
+
function parseMaxGenerated(value) {
|
|
43
|
+
if (value === undefined || !/^\d+$/.test(value) || Number(value) > MAX_GENERATED_LIMIT) {
|
|
44
|
+
throw new DepkillError(`--max-generated needs a whole number from 0 to ${MAX_GENERATED_LIMIT}.`);
|
|
45
|
+
}
|
|
46
|
+
return Number(value);
|
|
47
|
+
}
|
|
48
|
+
/** `record <pkg> [--max-generated N]`. */
|
|
49
|
+
function parseRecordArgs(args) {
|
|
50
|
+
const positional = [];
|
|
51
|
+
let maxGenerated = DEFAULT_MAX_GENERATED;
|
|
52
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
53
|
+
const arg = args[i];
|
|
54
|
+
if (arg === '--max-generated') {
|
|
55
|
+
maxGenerated = parseMaxGenerated(args[i + 1]);
|
|
56
|
+
i += 1;
|
|
57
|
+
}
|
|
58
|
+
else if (arg.startsWith('--max-generated='))
|
|
59
|
+
maxGenerated = parseMaxGenerated(arg.slice('--max-generated='.length));
|
|
60
|
+
else if (arg.startsWith('-'))
|
|
61
|
+
throw new DepkillError(`Unknown option for record: ${arg}`);
|
|
62
|
+
else
|
|
63
|
+
positional.push(arg);
|
|
64
|
+
}
|
|
65
|
+
if (positional.length !== 1)
|
|
66
|
+
throw new DepkillError('Usage: depkill record <pkg> [--max-generated N]');
|
|
67
|
+
return { pkg: positional[0], maxGenerated };
|
|
68
|
+
}
|
|
69
|
+
const recordCommand = {
|
|
70
|
+
name: 'record',
|
|
71
|
+
usage: 'record <pkg> [--max-generated N]',
|
|
72
|
+
summary: 'Record how a dependency behaves on real and generated inputs',
|
|
73
|
+
async run(args, globals) {
|
|
74
|
+
const { pkg, maxGenerated } = parseRecordArgs(args);
|
|
75
|
+
// With --json, stdout carries only the JSON summary; progress goes to stderr.
|
|
76
|
+
const result = await runRecord(detectProject(globals.cwd), pkg, { maxGenerated, log: globals.json ? writeErr : writeOut });
|
|
77
|
+
if (globals.json) {
|
|
78
|
+
const { summary, unsupported, cases } = result;
|
|
79
|
+
writeOut(`${JSON.stringify({ pkg, total: cases.length, summary, unsupported }, null, 2)}\n`);
|
|
80
|
+
}
|
|
81
|
+
return 0;
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
/** `check <pkg> [--replacement <path>]`; the path resolves from the --cwd directory. */
|
|
85
|
+
function parseCheckArgs(args, cwd) {
|
|
86
|
+
const positional = [];
|
|
87
|
+
let replacement;
|
|
88
|
+
const setReplacement = (value) => {
|
|
89
|
+
if (value === undefined || value === '' || value.startsWith('--'))
|
|
90
|
+
throw new DepkillError('--replacement needs a file path.');
|
|
91
|
+
replacement = resolve(cwd, value);
|
|
92
|
+
};
|
|
93
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
94
|
+
const arg = args[i];
|
|
95
|
+
if (arg === '--replacement') {
|
|
96
|
+
setReplacement(args[i + 1]);
|
|
97
|
+
i += 1;
|
|
98
|
+
}
|
|
99
|
+
else if (arg.startsWith('--replacement='))
|
|
100
|
+
setReplacement(arg.slice('--replacement='.length));
|
|
101
|
+
else if (arg.startsWith('-'))
|
|
102
|
+
throw new DepkillError(`Unknown option for check: ${arg}`);
|
|
103
|
+
else
|
|
104
|
+
positional.push(arg);
|
|
105
|
+
}
|
|
106
|
+
if (positional.length !== 1)
|
|
107
|
+
throw new DepkillError('Usage: depkill check <pkg> [--replacement <path>]');
|
|
108
|
+
return replacement === undefined ? { pkg: positional[0] } : { pkg: positional[0], replacement };
|
|
109
|
+
}
|
|
110
|
+
const checkCommand = {
|
|
111
|
+
name: 'check',
|
|
112
|
+
usage: 'check <pkg> [--replacement <path>]',
|
|
113
|
+
summary: 'Replay recorded cases against your replacement; exit 1 on any mismatch',
|
|
114
|
+
async run(args, globals) {
|
|
115
|
+
const { pkg, replacement } = parseCheckArgs(args, globals.cwd);
|
|
116
|
+
// With --json, stdout carries only the CheckResult.
|
|
117
|
+
const result = await runCheck(detectProject(globals.cwd), pkg, {
|
|
118
|
+
replacement, color: colorEnabled(process.stdout), log: globals.json ? () => { } : writeOut,
|
|
119
|
+
});
|
|
120
|
+
if (globals.json)
|
|
121
|
+
writeOut(`${JSON.stringify(result, null, 2)}\n`);
|
|
122
|
+
return checkPassed(result) ? 0 : 1;
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
/** `gate <pkg> [--test-cmd "<cmd>"] [--skip-tests]`. */
|
|
126
|
+
function parseGateArgs(args) {
|
|
127
|
+
const positional = [];
|
|
128
|
+
let testCmd;
|
|
129
|
+
let skipTests = false;
|
|
130
|
+
const setTestCmd = (value) => {
|
|
131
|
+
if (value === undefined || value.trim() === '' || value.startsWith('--'))
|
|
132
|
+
throw new DepkillError('--test-cmd needs a command, e.g. --test-cmd "npm run test:unit".');
|
|
133
|
+
testCmd = value;
|
|
134
|
+
};
|
|
135
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
136
|
+
const arg = args[i];
|
|
137
|
+
if (arg === '--test-cmd') {
|
|
138
|
+
setTestCmd(args[i + 1]);
|
|
139
|
+
i += 1;
|
|
140
|
+
}
|
|
141
|
+
else if (arg.startsWith('--test-cmd='))
|
|
142
|
+
setTestCmd(arg.slice('--test-cmd='.length));
|
|
143
|
+
else if (arg === '--skip-tests')
|
|
144
|
+
skipTests = true;
|
|
145
|
+
else if (arg.startsWith('-'))
|
|
146
|
+
throw new DepkillError(`Unknown option for gate: ${arg}`);
|
|
147
|
+
else
|
|
148
|
+
positional.push(arg);
|
|
149
|
+
}
|
|
150
|
+
if (positional.length !== 1)
|
|
151
|
+
throw new DepkillError('Usage: depkill gate <pkg> [--test-cmd "<cmd>"] [--skip-tests]');
|
|
152
|
+
if (testCmd !== undefined && skipTests)
|
|
153
|
+
throw new DepkillError('--test-cmd and --skip-tests cannot be combined.');
|
|
154
|
+
return testCmd === undefined ? { pkg: positional[0], skipTests } : { pkg: positional[0], testCmd, skipTests };
|
|
155
|
+
}
|
|
156
|
+
const gateCommand = {
|
|
157
|
+
name: 'gate',
|
|
158
|
+
usage: 'gate <pkg> [--test-cmd "<cmd>"] [--skip-tests]',
|
|
159
|
+
summary: 'Done rule: cases, anti-cheat, removal, typecheck and tests; exit 1 on fail',
|
|
160
|
+
async run(args, globals) {
|
|
161
|
+
const { pkg, testCmd, skipTests } = parseGateArgs(args);
|
|
162
|
+
// Progress goes to stderr; with --json, stdout carries only the GateResult.
|
|
163
|
+
const result = await runGate(detectProject(globals.cwd), pkg, { testCmd, skipTests, progress: writeErr });
|
|
164
|
+
writeOut(globals.json ? `${JSON.stringify(result, null, 2)}\n` : renderGate(result, { color: colorEnabled(process.stdout) }));
|
|
165
|
+
return result.pass ? 0 : 1;
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
const cardCommand = {
|
|
169
|
+
name: 'card',
|
|
170
|
+
usage: 'card',
|
|
171
|
+
summary: 'Measure before/after with clean installs; write the card, badge and report',
|
|
172
|
+
async run(args, globals) {
|
|
173
|
+
expectNoArgs('card', args);
|
|
174
|
+
// Progress and the summary go to stderr with --json; stdout then carries only the CardInput.
|
|
175
|
+
const input = await runCard(detectProject(globals.cwd), { offline: globals.offline, log: globals.json ? writeErr : writeOut });
|
|
176
|
+
if (globals.json)
|
|
177
|
+
writeOut(`${JSON.stringify(input, null, 2)}\n`);
|
|
178
|
+
return 0;
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
/** `init [--agent claude|agents|all]` (default all). */
|
|
182
|
+
function parseInitArgs(args) {
|
|
183
|
+
let agent = 'all';
|
|
184
|
+
const setAgent = (value) => {
|
|
185
|
+
if (value === undefined || !INIT_AGENTS.includes(value)) {
|
|
186
|
+
throw new DepkillError(`--agent needs one of ${INIT_AGENTS.join(', ')}.`);
|
|
187
|
+
}
|
|
188
|
+
agent = value;
|
|
189
|
+
};
|
|
190
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
191
|
+
const arg = args[i];
|
|
192
|
+
if (arg === '--agent') {
|
|
193
|
+
setAgent(args[i + 1]);
|
|
194
|
+
i += 1;
|
|
195
|
+
}
|
|
196
|
+
else if (arg.startsWith('--agent='))
|
|
197
|
+
setAgent(arg.slice('--agent='.length));
|
|
198
|
+
else if (arg.startsWith('-'))
|
|
199
|
+
throw new DepkillError(`Unknown option for init: ${arg}`);
|
|
200
|
+
else
|
|
201
|
+
throw new DepkillError(`init takes no arguments (got "${arg}"). Usage: depkill init [--agent claude|agents|all]`);
|
|
202
|
+
}
|
|
203
|
+
return agent;
|
|
204
|
+
}
|
|
205
|
+
const initCommand = {
|
|
206
|
+
name: 'init',
|
|
207
|
+
usage: 'init [--agent claude|agents|all]',
|
|
208
|
+
summary: 'Install the agent instructions (Claude Code skill, AGENTS.md section)',
|
|
209
|
+
async run(args, globals) {
|
|
210
|
+
const agent = parseInitArgs(args);
|
|
211
|
+
const project = detectProject(globals.cwd);
|
|
212
|
+
const written = runInit(project, { agent });
|
|
213
|
+
if (globals.json)
|
|
214
|
+
writeOut(`${JSON.stringify({ written }, null, 2)}\n`);
|
|
215
|
+
else {
|
|
216
|
+
writeOut([
|
|
217
|
+
...written.map((file) => `Wrote ${relative(project.root, file).split(sep).join('/')}`),
|
|
218
|
+
'Next: ask your coding agent to "use depkill to remove my smallest dependencies".',
|
|
219
|
+
'',
|
|
220
|
+
].join('\n'));
|
|
221
|
+
}
|
|
222
|
+
return 0;
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
/** Registered subcommands; later commands append here. */
|
|
226
|
+
export const commands = [initCommand, scanCommand, recordCommand, checkCommand, gateCommand, cardCommand];
|
|
227
|
+
function version() {
|
|
228
|
+
const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
229
|
+
return pkg.version;
|
|
230
|
+
}
|
|
231
|
+
function helpText() {
|
|
232
|
+
const width = Math.max(...commands.map((c) => c.usage.length));
|
|
233
|
+
return [
|
|
234
|
+
'Usage: depkill <command> [options]',
|
|
235
|
+
'',
|
|
236
|
+
'Prove an npm dependency can be deleted: record its behavior, replay it against a replacement, gate the removal.',
|
|
237
|
+
'',
|
|
238
|
+
'Commands:',
|
|
239
|
+
...commands.map((c) => ` ${c.usage.padEnd(width)} ${c.summary}`),
|
|
240
|
+
'',
|
|
241
|
+
'Global options:',
|
|
242
|
+
' --cwd <dir> Project directory (default: current directory)',
|
|
243
|
+
' --json Machine-readable output on stdout',
|
|
244
|
+
' --offline Never contact the npm registry',
|
|
245
|
+
' --help Show this help',
|
|
246
|
+
' --version Show the depkill version',
|
|
247
|
+
'',
|
|
248
|
+
].join('\n');
|
|
249
|
+
}
|
|
250
|
+
/** Pulls global flags out of `argv` wherever they appear; everything after `--` is passed through untouched. */
|
|
251
|
+
function parseArgv(argv) {
|
|
252
|
+
const parsed = { globals: { cwd: process.cwd(), json: false, offline: false }, help: false, version: false, rest: [] };
|
|
253
|
+
const setCwd = (value) => {
|
|
254
|
+
if (value === undefined || value === '' || value.startsWith('--'))
|
|
255
|
+
throw new DepkillError('--cwd needs a directory.');
|
|
256
|
+
parsed.globals.cwd = resolve(value);
|
|
257
|
+
};
|
|
258
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
259
|
+
const arg = argv[i];
|
|
260
|
+
if (arg === '--') {
|
|
261
|
+
parsed.rest.push(...argv.slice(i + 1));
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
if (arg === '--cwd') {
|
|
265
|
+
setCwd(argv[i + 1]);
|
|
266
|
+
i += 1;
|
|
267
|
+
}
|
|
268
|
+
else if (arg.startsWith('--cwd='))
|
|
269
|
+
setCwd(arg.slice('--cwd='.length));
|
|
270
|
+
else if (arg === '--json')
|
|
271
|
+
parsed.globals.json = true;
|
|
272
|
+
else if (arg === '--offline')
|
|
273
|
+
parsed.globals.offline = true;
|
|
274
|
+
else if (arg === '--help' || arg === '-h')
|
|
275
|
+
parsed.help = true;
|
|
276
|
+
else if (arg === '--version' || arg === '-v')
|
|
277
|
+
parsed.version = true;
|
|
278
|
+
else
|
|
279
|
+
parsed.rest.push(arg);
|
|
280
|
+
}
|
|
281
|
+
return parsed;
|
|
282
|
+
}
|
|
283
|
+
/** Runs the CLI and returns the exit code (0 ok, 1 check/gate failed, 2 usage/config error). Never exits the process. */
|
|
284
|
+
export async function main(argv) {
|
|
285
|
+
try {
|
|
286
|
+
const { globals, help, version: showVersion, rest } = parseArgv(argv);
|
|
287
|
+
if (help) {
|
|
288
|
+
writeOut(helpText());
|
|
289
|
+
return 0;
|
|
290
|
+
}
|
|
291
|
+
if (showVersion) {
|
|
292
|
+
writeOut(`${version()}\n`);
|
|
293
|
+
return 0;
|
|
294
|
+
}
|
|
295
|
+
const [name, ...args] = rest;
|
|
296
|
+
if (name === undefined) {
|
|
297
|
+
writeErr(helpText());
|
|
298
|
+
return 2;
|
|
299
|
+
}
|
|
300
|
+
const command = commands.find((c) => c.name === name);
|
|
301
|
+
if (command === undefined) {
|
|
302
|
+
writeErr(`Unknown command: ${name}\n\n${helpText()}`);
|
|
303
|
+
return 2;
|
|
304
|
+
}
|
|
305
|
+
return await command.run(args, globals);
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
if (error instanceof DepkillError) {
|
|
309
|
+
writeErr(`depkill: ${error.message}\n`);
|
|
310
|
+
return error.exitCode;
|
|
311
|
+
}
|
|
312
|
+
writeErr(`depkill: unexpected error: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
|
|
313
|
+
return 2;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/** True when this module is the process entry point (also through npm's bin shims and symlinks). */
|
|
317
|
+
function isEntryPoint() {
|
|
318
|
+
const entry = process.argv[1];
|
|
319
|
+
if (entry === undefined)
|
|
320
|
+
return false;
|
|
321
|
+
try {
|
|
322
|
+
return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
|
|
323
|
+
}
|
|
324
|
+
catch {
|
|
325
|
+
return false;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (isEntryPoint()) {
|
|
329
|
+
void main(process.argv.slice(2)).then((code) => {
|
|
330
|
+
// Exit once stdout has flushed: pipes are asynchronous on Windows and macOS.
|
|
331
|
+
process.stdout.write('', () => process.exit(code));
|
|
332
|
+
});
|
|
333
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// R43: the gate's `holdout` check. Static detection of embedded outputs is whack-a-mole (a lookup table can be built
|
|
2
|
+
// from char codes or joined pieces); fresh inputs near the project's real usage, answered by the ORIGINAL package
|
|
3
|
+
// (from record's runtime snapshot) and by the replacement, catch any table of recorded answers.
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { replayAgainstReplacement } from '../check.js';
|
|
7
|
+
import { generateHoldoutInputs, perturbable } from '../holdout/perturb.js';
|
|
8
|
+
import { runCases } from '../runner.js';
|
|
9
|
+
import { outcomesEqual } from '../serialize.js';
|
|
10
|
+
import { pkgSafe, readJson, stateDir } from '../util/fs.js';
|
|
11
|
+
import { truncate } from '../util/term.js';
|
|
12
|
+
const NAME = 'holdout';
|
|
13
|
+
const SHOWN_MISMATCHES = 5;
|
|
14
|
+
const SHOWN_CHARS = 120;
|
|
15
|
+
const RERECORD = 're-run depkill record';
|
|
16
|
+
const compared = (outcome) => outcome.kind === 'return' || outcome.kind === 'throw';
|
|
17
|
+
const shown = (value) => truncate(JSON.stringify(value), SHOWN_CHARS);
|
|
18
|
+
function readMeta(project, pkg) {
|
|
19
|
+
const file = join(stateDir(project.root, pkg), 'meta.json');
|
|
20
|
+
if (!existsSync(file))
|
|
21
|
+
return null;
|
|
22
|
+
try {
|
|
23
|
+
const meta = readJson(file);
|
|
24
|
+
return meta !== null && typeof meta === 'object' ? meta : null;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Runs min(60, 6 × real cases) perturbed real-usage inputs (seeded by `seed`) against the original package's runtime
|
|
32
|
+
* snapshot and against the replacement (sandboxed like check), and compares every pair whose original outcome is a
|
|
33
|
+
* return or throw. `skipped` when record could not snapshot the original (meta.json says why), no real case has a
|
|
34
|
+
* perturbable argument (R48) or every perturbation drawn is already recorded (C1); a failure on any mismatch, on a
|
|
35
|
+
* missing snapshot, or when the original gave no comparable outcome on any holdout input.
|
|
36
|
+
*/
|
|
37
|
+
export async function holdoutCheck(project, pkg, cases, files, seed, opts = {}) {
|
|
38
|
+
const done = (status, detail, count = 0) => ({ check: { name: NAME, status, detail }, compared: count });
|
|
39
|
+
const meta = readMeta(project, pkg);
|
|
40
|
+
if (meta?.holdoutAvailable === false) {
|
|
41
|
+
return done('skipped', `original not runnable after removal: ${typeof meta.holdoutReason === 'string' ? meta.holdoutReason : 'unknown reason'}`);
|
|
42
|
+
}
|
|
43
|
+
const runtime = join(stateDir(project.root, pkg), 'runtime');
|
|
44
|
+
if (meta?.holdoutAvailable !== true || !existsSync(join(runtime, 'package.json'))) {
|
|
45
|
+
return done('fail', `no runtime snapshot of the original in .depkill/${pkgSafe(pkg)}/runtime: ${RERECORD}`);
|
|
46
|
+
}
|
|
47
|
+
const real = cases.filter((c) => c.source !== 'generated' && compared(c.outcome));
|
|
48
|
+
// R48: nothing to vary is not evidence of cheating (e.g. only zero-argument calls): shown, not failed.
|
|
49
|
+
if (!real.some((c) => c.args.some(perturbable)))
|
|
50
|
+
return done('skipped', 'no perturbable arguments in real usage');
|
|
51
|
+
const inputs = generateHoldoutInputs(real, cases, seed);
|
|
52
|
+
// C1: real usage (plus generated cases) already covers every nearby input: nothing fresh to ask, not a cheat.
|
|
53
|
+
if (inputs.length === 0)
|
|
54
|
+
return done('skipped', 'all nearby inputs already recorded');
|
|
55
|
+
let original;
|
|
56
|
+
let actual;
|
|
57
|
+
try {
|
|
58
|
+
original = await runCases({ kind: 'package', name: pkg, resolveFrom: runtime }, inputs, { caseTimeoutMs: opts.caseTimeoutMs, cwd: project.root });
|
|
59
|
+
actual = await replayAgainstReplacement(project, files, inputs, opts);
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
return done('fail', `could not run the holdout cases: ${error instanceof Error ? error.message : String(error)}`);
|
|
63
|
+
}
|
|
64
|
+
const pairs = original.filter((c) => compared(c.outcome));
|
|
65
|
+
if (pairs.length === 0)
|
|
66
|
+
return done('fail', 'no holdout evidence: the original gave no comparable outcome on any holdout input');
|
|
67
|
+
const mismatches = pairs.filter((c) => !outcomesEqual(c.outcome, actual.get(c.id)));
|
|
68
|
+
if (mismatches.length === 0)
|
|
69
|
+
return done('pass', `${pairs.length}/${pairs.length} fresh cases near real usage match (seed ${seed})`, pairs.length);
|
|
70
|
+
const lines = mismatches.slice(0, SHOWN_MISMATCHES).map((c) => `${c.exportId} args ${shown(c.args)}: expected ${shown(c.outcome)}, actual ${shown(actual.get(c.id))}`);
|
|
71
|
+
const more = mismatches.length - SHOWN_MISMATCHES;
|
|
72
|
+
return done('fail', [
|
|
73
|
+
`${mismatches.length} of ${pairs.length} fresh cases differ from the original (seed ${seed}):`,
|
|
74
|
+
...lines,
|
|
75
|
+
...(more > 0 ? [`… and ${more} more`] : []),
|
|
76
|
+
'these inputs are near your real usage; make the replacement handle them',
|
|
77
|
+
].join('\n'), pairs.length);
|
|
78
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Runs the project's typecheck / test commands for `gate`: output captured (only the tail is kept), stdin ignored,
|
|
2
|
+
// and on timeout the whole process tree is killed (taskkill /T on Windows, the process group elsewhere).
|
|
3
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
4
|
+
const TAIL_LINES = 40;
|
|
5
|
+
/** Characters kept while running: far more than 40 lines usually take, without unbounded growth. */
|
|
6
|
+
const TAIL_CHARS = 64 * 1024;
|
|
7
|
+
/** How long to wait for stdio to close after the process exited (a background grandchild may hold the pipes). */
|
|
8
|
+
const DRAIN_MS = 2_000;
|
|
9
|
+
function lastLines(text) {
|
|
10
|
+
return text.replace(/\r\n/g, '\n').split('\n').slice(-TAIL_LINES).join('\n');
|
|
11
|
+
}
|
|
12
|
+
function killTree(child) {
|
|
13
|
+
if (child.pid === undefined)
|
|
14
|
+
return;
|
|
15
|
+
try {
|
|
16
|
+
if (process.platform === 'win32') {
|
|
17
|
+
spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
child.kill('SIGKILL');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function runProcess(command, args, opts) {
|
|
28
|
+
return new Promise((resolve) => {
|
|
29
|
+
let output = '';
|
|
30
|
+
let timedOut = false;
|
|
31
|
+
let settled = false;
|
|
32
|
+
let drain;
|
|
33
|
+
const child = spawn(command, args, {
|
|
34
|
+
cwd: opts.cwd,
|
|
35
|
+
shell: opts.shell === true,
|
|
36
|
+
env: opts.env === undefined ? process.env : { ...process.env, ...opts.env },
|
|
37
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
38
|
+
// Own process group on POSIX so a timeout can kill the shell and everything it started.
|
|
39
|
+
detached: process.platform !== 'win32',
|
|
40
|
+
windowsHide: true,
|
|
41
|
+
});
|
|
42
|
+
const finish = (code) => {
|
|
43
|
+
if (settled)
|
|
44
|
+
return;
|
|
45
|
+
settled = true;
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
clearTimeout(drain);
|
|
48
|
+
child.stdout?.destroy();
|
|
49
|
+
child.stderr?.destroy();
|
|
50
|
+
resolve({ code: timedOut ? null : code, timedOut, output: lastLines(output) });
|
|
51
|
+
};
|
|
52
|
+
const collect = (chunk) => {
|
|
53
|
+
output = (output + chunk).slice(-TAIL_CHARS);
|
|
54
|
+
};
|
|
55
|
+
for (const stream of [child.stdout, child.stderr]) {
|
|
56
|
+
stream?.setEncoding('utf8');
|
|
57
|
+
stream?.on('data', collect);
|
|
58
|
+
}
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
timedOut = true;
|
|
61
|
+
killTree(child);
|
|
62
|
+
drain = setTimeout(() => finish(null), DRAIN_MS);
|
|
63
|
+
}, opts.timeoutMs);
|
|
64
|
+
child.on('error', (error) => {
|
|
65
|
+
output += `\n${error.message}`;
|
|
66
|
+
finish(null);
|
|
67
|
+
});
|
|
68
|
+
child.on('exit', (code) => {
|
|
69
|
+
clearTimeout(drain);
|
|
70
|
+
drain = setTimeout(() => finish(code), DRAIN_MS);
|
|
71
|
+
});
|
|
72
|
+
child.on('close', (code) => finish(code));
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/** `command` through the shell in `cwd`; see runProcess. */
|
|
76
|
+
export function runShell(command, cwd, timeoutMs) {
|
|
77
|
+
return runProcess(command, [], { cwd, timeoutMs, shell: true });
|
|
78
|
+
}
|