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
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { existsSync, readdirSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { basename, dirname, join, relative, sep } from 'node:path';
|
|
3
|
+
import { DepkillError } from './types.js';
|
|
4
|
+
import { dirSize, readJson } from './util/fs.js';
|
|
5
|
+
const INSTALL_SCRIPTS = ['preinstall', 'install', 'postinstall'];
|
|
6
|
+
/**
|
|
7
|
+
* Explicit lifecycle install scripts, or npm's implicit `node-gyp rebuild` install that it adds
|
|
8
|
+
* when binding.gyp exists, `gypfile` is not false and neither `install` nor `preinstall` is defined.
|
|
9
|
+
*/
|
|
10
|
+
function hasInstallScript(manifest, hasBindingGyp) {
|
|
11
|
+
const scripts = manifest.scripts ?? {};
|
|
12
|
+
const defined = (script) => typeof scripts[script] === 'string';
|
|
13
|
+
const implicitGyp = hasBindingGyp && manifest.gypfile !== false && !defined('install') && !defined('preinstall');
|
|
14
|
+
return INSTALL_SCRIPTS.some(defined) || implicitGyp;
|
|
15
|
+
}
|
|
16
|
+
/** An installed package's manifest; unreadable or malformed JSON is a DepkillError (exit 2) naming the file. */
|
|
17
|
+
function readManifest(dir) {
|
|
18
|
+
const file = join(dir, 'package.json');
|
|
19
|
+
try {
|
|
20
|
+
return readJson(file);
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
24
|
+
throw new DepkillError(`Cannot read ${file}: ${reason}. Reinstall dependencies (e.g. npm install).`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Node-style lookup: `<ancestor>/node_modules/<name>` for every ancestor of `fromDir`
|
|
29
|
+
* (skipping `node_modules` directories themselves). Returns the real directory, or null.
|
|
30
|
+
*/
|
|
31
|
+
function resolveDep(name, fromDir) {
|
|
32
|
+
for (let dir = fromDir;; dir = dirname(dir)) {
|
|
33
|
+
if (basename(dir) !== 'node_modules') {
|
|
34
|
+
const candidate = join(dir, 'node_modules', ...name.split('/'));
|
|
35
|
+
if (existsSync(join(candidate, 'package.json')))
|
|
36
|
+
return realpathSync(candidate);
|
|
37
|
+
}
|
|
38
|
+
if (dirname(dir) === dir)
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** `dependencies` + `optionalDependencies` (the latter wins, as in npm), deduplicated. */
|
|
43
|
+
function runtimeDeps(pkg) {
|
|
44
|
+
const optional = Object.keys(pkg.optionalDependencies ?? {});
|
|
45
|
+
const required = Object.keys(pkg.dependencies ?? {}).filter((name) => !optional.includes(name));
|
|
46
|
+
return [...required.map((name) => ({ name, optional: false })), ...optional.map((name) => ({ name, optional: true }))];
|
|
47
|
+
}
|
|
48
|
+
/** True when any `*.node` file exists under `dir`, ignoring nested node_modules and symlinks. */
|
|
49
|
+
function hasNodeFile(dir) {
|
|
50
|
+
return readdirSync(dir, { withFileTypes: true }).some((entry) => {
|
|
51
|
+
if (entry.name === 'node_modules')
|
|
52
|
+
return false;
|
|
53
|
+
if (entry.isDirectory())
|
|
54
|
+
return hasNodeFile(join(dir, entry.name));
|
|
55
|
+
return entry.isFile() && entry.name.endsWith('.node');
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
function describe(id, requestedName, dir, manifest, deps) {
|
|
59
|
+
const hasBindingGyp = existsSync(join(dir, 'binding.gyp'));
|
|
60
|
+
return {
|
|
61
|
+
id,
|
|
62
|
+
name: manifest.name ?? requestedName,
|
|
63
|
+
version: manifest.version ?? '0.0.0',
|
|
64
|
+
dir,
|
|
65
|
+
sizeBytes: dirSize(dir, (name) => name === 'node_modules'),
|
|
66
|
+
hasInstallScript: hasInstallScript(manifest, hasBindingGyp),
|
|
67
|
+
isNative: hasBindingGyp || manifest.gypfile === true || hasNodeFile(dir),
|
|
68
|
+
deps,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Installed dependency graph of the project at `root`, read from node_modules.
|
|
73
|
+
* Node ids are real directories relative to the real project root, with `/` separators
|
|
74
|
+
* (e.g. `node_modules/a/node_modules/b`). Dev dependencies of installed packages and
|
|
75
|
+
* peer dependencies are not followed; optional dependencies and root devDependencies that are not
|
|
76
|
+
* installed are skipped. Throws DepkillError (exit 2) when a prod or transitive required dependency
|
|
77
|
+
* cannot be resolved.
|
|
78
|
+
*/
|
|
79
|
+
export function buildGraph(root, pkg) {
|
|
80
|
+
const realRoot = realpathSync(root);
|
|
81
|
+
const nodes = new Map();
|
|
82
|
+
const seen = new Set();
|
|
83
|
+
const resolveRefs = (refs, fromDir, requiredBy) => refs.flatMap(({ name, optional }) => {
|
|
84
|
+
const dir = resolveDep(name, fromDir);
|
|
85
|
+
if (dir !== null)
|
|
86
|
+
return [[name, visit(name, dir)]];
|
|
87
|
+
if (optional)
|
|
88
|
+
return [];
|
|
89
|
+
throw new DepkillError(`Cannot find "${name}" (required by ${requiredBy}) in node_modules; run npm install (or your package manager's install).`);
|
|
90
|
+
});
|
|
91
|
+
function visit(requestedName, dir) {
|
|
92
|
+
const id = relative(realRoot, dir).split(sep).join('/');
|
|
93
|
+
if (seen.has(id))
|
|
94
|
+
return id;
|
|
95
|
+
seen.add(id);
|
|
96
|
+
const manifest = readManifest(dir);
|
|
97
|
+
const label = `${manifest.name ?? requestedName}@${manifest.version ?? '0.0.0'}`;
|
|
98
|
+
const deps = [...new Set(resolveRefs(runtimeDeps(manifest), dir, label).map(([, depId]) => depId))];
|
|
99
|
+
nodes.set(id, describe(id, requestedName, dir, manifest, deps));
|
|
100
|
+
return id;
|
|
101
|
+
}
|
|
102
|
+
const rootLabel = pkg.name ?? 'the project';
|
|
103
|
+
const prod = new Map(resolveRefs(runtimeDeps(pkg), realRoot, rootLabel));
|
|
104
|
+
const devRefs = Object.keys(pkg.devDependencies ?? {})
|
|
105
|
+
.filter((name) => !prod.has(name))
|
|
106
|
+
// Omitted dev installs (e.g. --omit=dev) are not an error: missing dev deps are just absent.
|
|
107
|
+
.map((name) => ({ name, optional: true }));
|
|
108
|
+
const dev = new Map(resolveRefs(devRefs, realRoot, rootLabel));
|
|
109
|
+
return { nodes, direct: { prod, dev } };
|
|
110
|
+
}
|
|
111
|
+
/** Ids reachable from `starts` (inclusive), in breadth-first order. */
|
|
112
|
+
function reachable(graph, starts) {
|
|
113
|
+
const order = [];
|
|
114
|
+
const seen = new Set();
|
|
115
|
+
const queue = [...starts];
|
|
116
|
+
while (queue.length > 0) {
|
|
117
|
+
const id = queue.shift();
|
|
118
|
+
if (seen.has(id))
|
|
119
|
+
continue;
|
|
120
|
+
seen.add(id);
|
|
121
|
+
order.push(id);
|
|
122
|
+
queue.push(...(graph.nodes.get(id)?.deps ?? []));
|
|
123
|
+
}
|
|
124
|
+
return order;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Packages that would leave node_modules if direct dependency `name` were removed:
|
|
128
|
+
* everything reachable from it (inclusive) that no other direct dependency (prod or dev) reaches.
|
|
129
|
+
*/
|
|
130
|
+
export function exclusiveClosure(graph, name) {
|
|
131
|
+
const target = graph.direct.prod.get(name) ?? graph.direct.dev.get(name);
|
|
132
|
+
if (target === undefined)
|
|
133
|
+
throw new DepkillError(`"${name}" is not a direct dependency of this project.`);
|
|
134
|
+
const otherStarts = [...graph.direct.prod, ...graph.direct.dev]
|
|
135
|
+
.filter(([other]) => other !== name)
|
|
136
|
+
.map(([, id]) => id);
|
|
137
|
+
const shared = new Set(reachable(graph, otherStarts));
|
|
138
|
+
return reachable(graph, [target])
|
|
139
|
+
.filter((id) => !shared.has(id))
|
|
140
|
+
.map((id) => graph.nodes.get(id));
|
|
141
|
+
}
|
|
142
|
+
/** R43: everything direct dependency `name` loads at runtime (inclusive), breadth-first, shared packages included. */
|
|
143
|
+
export function dependencyClosure(graph, name) {
|
|
144
|
+
const target = graph.direct.prod.get(name) ?? graph.direct.dev.get(name);
|
|
145
|
+
if (target === undefined)
|
|
146
|
+
throw new DepkillError(`"${name}" is not a direct dependency of this project.`);
|
|
147
|
+
return reachable(graph, [target]).map((id) => graph.nodes.get(id));
|
|
148
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** Cap on holdout cases, and how many per real case below the cap. */
|
|
2
|
+
export const MAX_HOLDOUT = 60;
|
|
3
|
+
export const HOLDOUT_PER_REAL = 6;
|
|
4
|
+
/** Draws per wanted case before giving up (duplicates and recorded tuples are skipped). */
|
|
5
|
+
const ATTEMPTS_PER_CASE = 25;
|
|
6
|
+
const ALPHABET = [...'abcdefghijklmnopqrstuvwxyz0123456789'];
|
|
7
|
+
/** mulberry32: a small deterministic PRNG over [0, 1). */
|
|
8
|
+
export function mulberry32(seed) {
|
|
9
|
+
let state = seed >>> 0;
|
|
10
|
+
return () => {
|
|
11
|
+
state = (state + 0x6d2b79f5) >>> 0;
|
|
12
|
+
let t = state;
|
|
13
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
14
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
15
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
const pick = (rng, items) => items[Math.floor(rng() * items.length)];
|
|
19
|
+
const intBetween = (rng, min, max) => min + Math.floor(rng() * (max - min + 1));
|
|
20
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
21
|
+
/** A plain object as encoded by serialize.ts: no `$`-tagged keys (tags mark undefined, Map, Date, functions…). */
|
|
22
|
+
const isPlain = (value) => Object.keys(value).every((key) => !key.startsWith('$'));
|
|
23
|
+
/** An escaped plain object (`{ $obj: {...}, $desc?: {...}, $nullproto?: 1 }`). */
|
|
24
|
+
const isEscapedPlain = (value) => Object.hasOwn(value, '$obj') && isObject(value.$obj)
|
|
25
|
+
&& Object.keys(value).every((key) => key === '$obj' || key === '$desc' || key === '$nullproto');
|
|
26
|
+
/** Whether `perturbValue` can change `value`. */
|
|
27
|
+
export function perturbable(value) {
|
|
28
|
+
if (typeof value === 'string')
|
|
29
|
+
return value !== '';
|
|
30
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
31
|
+
return true;
|
|
32
|
+
if (Array.isArray(value))
|
|
33
|
+
return value.some(perturbable);
|
|
34
|
+
if (!isObject(value))
|
|
35
|
+
return false;
|
|
36
|
+
if (isPlain(value))
|
|
37
|
+
return Object.values(value).some(perturbable);
|
|
38
|
+
return isEscapedPlain(value) && Object.values(value.$obj).some(perturbable);
|
|
39
|
+
}
|
|
40
|
+
function perturbNumber(rng, n) {
|
|
41
|
+
const delta = rng() < 0.5 ? 1 : intBetween(rng, 2, 10);
|
|
42
|
+
const next = rng() < 0.5 ? n - delta : n + delta;
|
|
43
|
+
return Object.is(next, -0) ? 0 : next;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* One edit of `s` over its own characters plus [a-z0-9]. R47: a string of at most one character is a "char"
|
|
47
|
+
* parameter (a fill, a separator): only replaced, never grown or emptied. The empty string is not perturbable.
|
|
48
|
+
*/
|
|
49
|
+
function perturbString(rng, s) {
|
|
50
|
+
const chars = [...s];
|
|
51
|
+
const alphabet = [...new Set([...chars, ...ALPHABET])];
|
|
52
|
+
const ops = chars.length <= 1 ? ['replace'] : ['replace', 'insert', 'delete'];
|
|
53
|
+
const op = pick(rng, ops);
|
|
54
|
+
if (op === 'insert') {
|
|
55
|
+
const at = intBetween(rng, 0, chars.length);
|
|
56
|
+
return [...chars.slice(0, at), pick(rng, alphabet), ...chars.slice(at)].join('');
|
|
57
|
+
}
|
|
58
|
+
const at = intBetween(rng, 0, chars.length - 1);
|
|
59
|
+
if (op === 'delete')
|
|
60
|
+
return [...chars.slice(0, at), ...chars.slice(at + 1)].join('');
|
|
61
|
+
const others = alphabet.filter((c) => c !== chars[at]);
|
|
62
|
+
return [...chars.slice(0, at), pick(rng, others), ...chars.slice(at + 1)].join('');
|
|
63
|
+
}
|
|
64
|
+
/** `value` with exactly one leaf changed; `value` must be perturbable. */
|
|
65
|
+
export function perturbValue(rng, value) {
|
|
66
|
+
if (typeof value === 'number')
|
|
67
|
+
return perturbNumber(rng, value);
|
|
68
|
+
if (typeof value === 'string')
|
|
69
|
+
return perturbString(rng, value);
|
|
70
|
+
if (typeof value === 'boolean')
|
|
71
|
+
return !value;
|
|
72
|
+
if (Array.isArray(value)) {
|
|
73
|
+
const at = pick(rng, value.flatMap((item, i) => (perturbable(item) ? [i] : [])));
|
|
74
|
+
return value.map((item, i) => (i === at ? perturbValue(rng, item) : item));
|
|
75
|
+
}
|
|
76
|
+
const obj = value;
|
|
77
|
+
// An escaped plain object (`{ $obj: {...}, $desc?, $nullproto? }`) is perturbed inside `$obj`, keeping metadata.
|
|
78
|
+
return isPlain(obj) ? perturbEntries(rng, obj) : { ...obj, $obj: perturbEntries(rng, obj.$obj) };
|
|
79
|
+
}
|
|
80
|
+
function perturbEntries(rng, obj) {
|
|
81
|
+
const key = pick(rng, Object.keys(obj).filter((k) => perturbable(obj[k])));
|
|
82
|
+
return { ...obj, [key]: perturbValue(rng, obj[key]) };
|
|
83
|
+
}
|
|
84
|
+
const argsKey = (args) => JSON.stringify(args);
|
|
85
|
+
/**
|
|
86
|
+
* Up to min(60, 6 × real cases) holdout inputs (ids `holdout-1…`): a real case drawn at random, one perturbable
|
|
87
|
+
* argument perturbed. Deduplicated by export id + encoded args; args equal to any recorded case's args are skipped.
|
|
88
|
+
* Deterministic for a given seed.
|
|
89
|
+
*/
|
|
90
|
+
export function generateHoldoutInputs(real, recorded, seed) {
|
|
91
|
+
const wanted = Math.min(MAX_HOLDOUT, HOLDOUT_PER_REAL * real.length);
|
|
92
|
+
const bases = real.filter((c) => c.args.some(perturbable));
|
|
93
|
+
const recordedArgs = new Set(recorded.map((c) => argsKey(c.args)));
|
|
94
|
+
const seen = new Set();
|
|
95
|
+
const out = [];
|
|
96
|
+
const rng = mulberry32(seed);
|
|
97
|
+
for (let attempt = 0; bases.length > 0 && out.length < wanted && attempt < wanted * ATTEMPTS_PER_CASE; attempt++) {
|
|
98
|
+
const base = pick(rng, bases);
|
|
99
|
+
const at = pick(rng, base.args.flatMap((arg, i) => (perturbable(arg) ? [i] : [])));
|
|
100
|
+
const args = base.args.map((arg, i) => (i === at ? perturbValue(rng, arg) : arg));
|
|
101
|
+
const key = argsKey(args);
|
|
102
|
+
if (recordedArgs.has(key) || seen.has(`${base.exportId}\0${key}`))
|
|
103
|
+
continue;
|
|
104
|
+
seen.add(`${base.exportId}\0${key}`);
|
|
105
|
+
out.push({ id: `holdout-${out.length + 1}`, exportId: base.exportId, source: 'generated', args });
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// R43: `record` keeps a runnable copy of the original package and its whole dependency closure under
|
|
2
|
+
// `.depkill/<pkg-safe>/runtime/`, so `gate` can run the ORIGINAL on fresh holdout inputs after the package was removed.
|
|
3
|
+
import { copyFileSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { buildGraph, dependencyClosure } from '../graph.js';
|
|
6
|
+
import { DepkillError } from '../types.js';
|
|
7
|
+
/** Cap on the bytes copied into the runtime snapshot (every placement counted). */
|
|
8
|
+
export const RUNTIME_LIMIT_BYTES = 50 * 1024 * 1024;
|
|
9
|
+
/** Placements beyond this mean a pathological layout (dependency cycles with conflicting versions). */
|
|
10
|
+
const MAX_PLACEMENTS = 5000;
|
|
11
|
+
const NODE_MODULES = 'node_modules';
|
|
12
|
+
/** The name a package is installed (and required) under: the folder after the last `node_modules/` of its id. */
|
|
13
|
+
export function installedName(node) {
|
|
14
|
+
const at = node.id.lastIndexOf(`${NODE_MODULES}/`);
|
|
15
|
+
return at === -1 ? node.name : node.id.slice(at + NODE_MODULES.length + 1);
|
|
16
|
+
}
|
|
17
|
+
const parentOf = (dir) => (dir === '' ? null : dir.includes('/') ? dir.slice(0, dir.lastIndexOf('/')) : '');
|
|
18
|
+
const lastSegment = (dir) => dir.slice(dir.lastIndexOf('/') + 1);
|
|
19
|
+
/**
|
|
20
|
+
* Where each closure package goes, relative to the runtime dir (`/` separators): flat `node_modules/<name>` by
|
|
21
|
+
* default; when a dependent would resolve a different version of a name, a copy is nested under that dependent's own
|
|
22
|
+
* `node_modules`. Simulates Node's lookup (`<dir>/node_modules/<name>` for every ancestor that is not itself a
|
|
23
|
+
* `node_modules` folder), so the layout loads the same versions. Returns [dir, node] pairs in placement order.
|
|
24
|
+
*/
|
|
25
|
+
export function planRuntimeLayout(graph, start) {
|
|
26
|
+
const placed = new Map();
|
|
27
|
+
const order = [];
|
|
28
|
+
const place = (dir, node) => {
|
|
29
|
+
if (placed.size >= MAX_PLACEMENTS)
|
|
30
|
+
throw new DepkillError(`more than ${MAX_PLACEMENTS} package copies needed`);
|
|
31
|
+
placed.set(dir, node);
|
|
32
|
+
order.push([dir, node]);
|
|
33
|
+
};
|
|
34
|
+
const lookup = (from, name) => {
|
|
35
|
+
for (let dir = from; dir !== null; dir = parentOf(dir)) {
|
|
36
|
+
if (lastSegment(dir) === NODE_MODULES)
|
|
37
|
+
continue;
|
|
38
|
+
const found = placed.get(dir === '' ? `${NODE_MODULES}/${name}` : `${dir}/${NODE_MODULES}/${name}`);
|
|
39
|
+
if (found !== undefined)
|
|
40
|
+
return found;
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
};
|
|
44
|
+
place(`${NODE_MODULES}/${installedName(start)}`, start);
|
|
45
|
+
for (let i = 0; i < order.length; i++) {
|
|
46
|
+
const [dir, node] = order[i];
|
|
47
|
+
for (const depId of node.deps) {
|
|
48
|
+
const dep = graph.nodes.get(depId);
|
|
49
|
+
if (dep === undefined)
|
|
50
|
+
continue;
|
|
51
|
+
const name = installedName(dep);
|
|
52
|
+
const found = lookup(dir, name);
|
|
53
|
+
if (found === dep)
|
|
54
|
+
continue;
|
|
55
|
+
place(found === undefined ? `${NODE_MODULES}/${name}` : `${dir}/${NODE_MODULES}/${name}`, dep);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return order;
|
|
59
|
+
}
|
|
60
|
+
/** Copies the regular files of `src` into `dest`, recursively, skipping `node_modules` folders and symlinks. */
|
|
61
|
+
function copyPackage(src, dest) {
|
|
62
|
+
mkdirSync(dest, { recursive: true });
|
|
63
|
+
for (const entry of readdirSync(src, { withFileTypes: true })) {
|
|
64
|
+
if (entry.isDirectory()) {
|
|
65
|
+
if (entry.name !== NODE_MODULES)
|
|
66
|
+
copyPackage(join(src, entry.name), join(dest, entry.name));
|
|
67
|
+
}
|
|
68
|
+
else if (entry.isFile()) {
|
|
69
|
+
copyFileSync(join(src, entry.name), join(dest, entry.name));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function unavailable(reason) {
|
|
74
|
+
return { available: false, reason };
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Writes `dest` (replacing it): `package.json` `{ "name": "depkill-holdout", "private": true }` plus `node_modules/`
|
|
78
|
+
* holding `pkg` and its full runtime closure. Not available (nothing written) when the closure cannot be read, holds
|
|
79
|
+
* a native addon, or exceeds 50 MB.
|
|
80
|
+
*/
|
|
81
|
+
export function snapshotRuntime(project, pkg, dest, limitBytes = RUNTIME_LIMIT_BYTES) {
|
|
82
|
+
rmSync(dest, { recursive: true, force: true });
|
|
83
|
+
let layout;
|
|
84
|
+
try {
|
|
85
|
+
const graph = buildGraph(project.root, project.pkg);
|
|
86
|
+
const closure = dependencyClosure(graph, pkg);
|
|
87
|
+
const native = closure.filter((node) => node.isNative).map((node) => `${node.name}@${node.version}`);
|
|
88
|
+
if (native.length > 0)
|
|
89
|
+
return unavailable(`native addon in the dependency closure (${native.join(', ')})`);
|
|
90
|
+
layout = planRuntimeLayout(graph, closure[0]);
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (!(error instanceof DepkillError))
|
|
94
|
+
throw error;
|
|
95
|
+
return unavailable(`cannot snapshot the dependency closure: ${error.message}`);
|
|
96
|
+
}
|
|
97
|
+
const bytes = layout.reduce((total, [, node]) => total + node.sizeBytes, 0);
|
|
98
|
+
if (bytes > limitBytes) {
|
|
99
|
+
const mb = (n) => (n / 1024 / 1024).toFixed(1);
|
|
100
|
+
return unavailable(`dependency closure is ${mb(bytes)} MB (limit ${mb(limitBytes)} MB)`);
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
mkdirSync(dest, { recursive: true });
|
|
104
|
+
writeFileSync(join(dest, 'package.json'), `${JSON.stringify({ name: 'depkill-holdout', private: true }, null, 2)}\n`);
|
|
105
|
+
for (const [dir, node] of layout)
|
|
106
|
+
copyPackage(node.dir, join(dest, ...dir.split('/')));
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
rmSync(dest, { recursive: true, force: true });
|
|
110
|
+
return unavailable(`cannot copy the dependency closure: ${error instanceof Error ? error.message : String(error)}`);
|
|
111
|
+
}
|
|
112
|
+
return { available: true };
|
|
113
|
+
}
|
package/dist/src/init.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// `init`: installs depkill's agent instructions into a project — the Claude Code skill
|
|
2
|
+
// (`.claude/skills/depkill/SKILL.md`) and/or a marked section in `AGENTS.md` (read by Codex, Cursor and other agents).
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { DepkillError } from './types.js';
|
|
7
|
+
export const INIT_AGENTS = ['claude', 'agents', 'all'];
|
|
8
|
+
export const AGENTS_START = '<!-- depkill:start -->';
|
|
9
|
+
export const AGENTS_END = '<!-- depkill:end -->';
|
|
10
|
+
// Shipped with the package (`files` includes `skills`); resolved from dist/src/init.js.
|
|
11
|
+
const SKILL_SOURCE = new URL('../../skills/depkill/SKILL.md', import.meta.url);
|
|
12
|
+
const SECTION_SOURCE = new URL('../../skills/AGENTS.section.md', import.meta.url);
|
|
13
|
+
const toLf = (text) => text.replace(/\r\n/g, '\n');
|
|
14
|
+
function bundled(url) {
|
|
15
|
+
try {
|
|
16
|
+
return toLf(readFileSync(fileURLToPath(url), 'utf8'));
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
throw new DepkillError(`depkill is missing its bundled ${fileURLToPath(url)} (${error instanceof Error ? error.message : String(error)}); reinstall depkill.`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function unterminated(file) {
|
|
23
|
+
return new DepkillError(`${file} has "${AGENTS_START}" without a matching "${AGENTS_END}"; fix or remove the depkill block, then run depkill init again.`);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* `text` (LF line endings) with the depkill block replaced by `block` — or appended when there is none. Later
|
|
27
|
+
* duplicate blocks (e.g. from a merge) are dropped so exactly one remains; everything else is kept as is.
|
|
28
|
+
* DepkillError when a start marker has no end marker.
|
|
29
|
+
*/
|
|
30
|
+
export function upsertBlock(text, block, file) {
|
|
31
|
+
let out = '';
|
|
32
|
+
let rest = text;
|
|
33
|
+
let placed = false;
|
|
34
|
+
for (let start = rest.indexOf(AGENTS_START); start !== -1; start = rest.indexOf(AGENTS_START)) {
|
|
35
|
+
const end = rest.indexOf(AGENTS_END, start);
|
|
36
|
+
if (end === -1)
|
|
37
|
+
throw unterminated(file);
|
|
38
|
+
out += placed ? rest.slice(0, start).trimEnd() : `${rest.slice(0, start)}${block}`;
|
|
39
|
+
placed = true;
|
|
40
|
+
rest = rest.slice(end + AGENTS_END.length);
|
|
41
|
+
}
|
|
42
|
+
if (placed)
|
|
43
|
+
return `${out}${rest}`;
|
|
44
|
+
const body = text.trimEnd();
|
|
45
|
+
return body === '' ? `${block}\n` : `${body}\n\n${block}\n`;
|
|
46
|
+
}
|
|
47
|
+
function skillWrite(root) {
|
|
48
|
+
return { file: join(root, '.claude', 'skills', 'depkill', 'SKILL.md'), content: bundled(SKILL_SOURCE) };
|
|
49
|
+
}
|
|
50
|
+
function agentsWrite(root) {
|
|
51
|
+
const file = join(root, 'AGENTS.md');
|
|
52
|
+
const block = `${AGENTS_START}\n${bundled(SECTION_SOURCE).trim()}\n${AGENTS_END}`;
|
|
53
|
+
const existing = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
54
|
+
const updated = upsertBlock(toLf(existing), block, file);
|
|
55
|
+
// An AGENTS.md written with CRLF keeps CRLF.
|
|
56
|
+
return { file, content: existing.includes('\r\n') ? updated.replace(/\n/g, '\r\n') : updated };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Installs the agent instructions into `project.root` and returns the written paths (absolute):
|
|
60
|
+
* `claude` copies the bundled skill to `.claude/skills/depkill/SKILL.md` (overwritten on every run); `agents` puts
|
|
61
|
+
* the bundled section between `<!-- depkill:start -->` / `<!-- depkill:end -->` in `AGENTS.md`, replacing an existing
|
|
62
|
+
* block and keeping everything else (idempotent); `all` does both. DepkillError (exit 2) on an unterminated block.
|
|
63
|
+
*/
|
|
64
|
+
export function runInit(project, opts) {
|
|
65
|
+
// Everything is prepared before anything is written: a malformed AGENTS.md leaves the project untouched.
|
|
66
|
+
const writes = [];
|
|
67
|
+
if (opts.agent === 'claude' || opts.agent === 'all')
|
|
68
|
+
writes.push(skillWrite(project.root));
|
|
69
|
+
if (opts.agent === 'agents' || opts.agent === 'all')
|
|
70
|
+
writes.push(agentsWrite(project.root));
|
|
71
|
+
for (const { file, content } of writes) {
|
|
72
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
73
|
+
writeFileSync(file, content);
|
|
74
|
+
}
|
|
75
|
+
return writes.map((w) => w.file);
|
|
76
|
+
}
|