neurarch 0.2.0 → 0.4.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/bin/policy.mjs ADDED
@@ -0,0 +1,320 @@
1
+ /**
2
+ * The repo's policy around every pre-check: `.neurarch.yml`, waivers,
3
+ * baselines and SARIF. This file is the CLI's glue (files, git, network,
4
+ * clock); every decision is in src/utils/policy/ through policy.bundle.mjs.
5
+ *
6
+ * Nothing here runs unless it has something to do: with no policy file in the
7
+ * repo, no baseline, and no --sarif / --policy / baseline flag, `finish`
8
+ * returns the checker's own exit code and prints nothing, so the CLI behaves
9
+ * exactly as it did before this file existed.
10
+ *
11
+ * neurarch layout <id> ... [--policy .neurarch.yml] [--no-policy] [--sarif out.sarif]
12
+ * [--source launch.sh] [--changed-lines changes.diff | "path:3-5,9"] [--cluster prod]
13
+ * [--baseline .neurarch/baseline.json] [--all]
14
+ * neurarch baseline layout <id> ... write what this run finds as the baseline
15
+ * neurarch policy show | validate | schema | apply
16
+ */
17
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
18
+ import { dirname, join, relative, resolve, sep } from 'node:path';
19
+ import { execFileSync } from 'node:child_process';
20
+ import { fileURLToPath } from 'node:url';
21
+
22
+ const HERE = dirname(fileURLToPath(import.meta.url));
23
+ const POLICY_NAMES = ['.neurarch.yml', '.neurarch.yaml'];
24
+ const VALUED = ['--policy', '--sarif', '--source', '--changed-lines', '--cluster', '--baseline'];
25
+ const BARE = ['--no-policy', '--all'];
26
+
27
+ let bundle;
28
+ const lib = async () => (bundle ??= await import('../policy.bundle.mjs'));
29
+ const toolVersion = () => { try { return JSON.parse(readFileSync(join(HERE, '..', 'package.json'), 'utf8')).version; } catch { return '0.0.0'; } };
30
+
31
+ const posix = (p) => p.split(sep).join('/');
32
+
33
+ function repoRoot(from) {
34
+ let d = resolve(from);
35
+ for (;;) {
36
+ if (existsSync(join(d, '.git'))) return d;
37
+ const up = dirname(d);
38
+ if (up === d) return null;
39
+ d = up;
40
+ }
41
+ }
42
+
43
+ /** The nearest `.neurarch.yml` from `from` up to the repo root (or the filesystem root). */
44
+ export function discoverPolicy(from = process.cwd()) {
45
+ const stop = repoRoot(from);
46
+ let d = resolve(from);
47
+ for (;;) {
48
+ for (const n of POLICY_NAMES) if (existsSync(join(d, n))) return join(d, n);
49
+ if (d === stop) return null;
50
+ const up = dirname(d);
51
+ if (up === d) return null;
52
+ d = up;
53
+ }
54
+ }
55
+
56
+ /** Pull the policy flags out of argv (in place) and say what this run will do. */
57
+ function takeFlags(args) {
58
+ const o = {};
59
+ for (let i = 0; i < args.length; i++) {
60
+ const a = args[i];
61
+ if (a === '--') break; // serve-check: everything after is the launch command
62
+ const eq = /^(--[a-z-]+)=(.*)$/.exec(a);
63
+ if (eq && VALUED.includes(eq[1])) { o[eq[1].slice(2)] = eq[2]; args.splice(i--, 1); continue; }
64
+ if (VALUED.includes(a)) { o[a.slice(2)] = args[i + 1]; args.splice(i--, 2); continue; }
65
+ if (BARE.includes(a)) { o[a.slice(2)] = true; args.splice(i--, 1); }
66
+ }
67
+ return o;
68
+ }
69
+
70
+ function gitBlameDate(root, file, line) {
71
+ if (!root || !file || !line) return null;
72
+ try {
73
+ const out = execFileSync('git', ['blame', '--porcelain', '-L', `${line},${line}`, '--', file], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
74
+ if (/^0{40}\b/.test(out)) return null; // not committed yet
75
+ const t = /^author-time (\d+)$/m.exec(out);
76
+ return t ? new Date(Number(t[1]) * 1000).toISOString().slice(0, 10) : null;
77
+ } catch { return null; }
78
+ }
79
+
80
+ function presetSource(root) {
81
+ return {
82
+ async readLocal(p) { return readFileSync(resolve(root, p), 'utf8'); },
83
+ async fetchGithub({ org, repo, path, tag }) {
84
+ const url = `https://raw.githubusercontent.com/${org}/${repo}/${tag ?? 'HEAD'}/${path}`;
85
+ const headers = process.env.GITHUB_TOKEN ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` } : {};
86
+ const r = await fetch(url, { headers, signal: AbortSignal.timeout(10_000) });
87
+ if (!r.ok) throw new Error(`${url} answered ${r.status}`);
88
+ return r.text();
89
+ },
90
+ };
91
+ }
92
+
93
+ function waiverDeps(root, now = () => new Date()) {
94
+ const storePath = root ? join(root, '.neurarch', 'waivers-seen.json') : null;
95
+ let store = {};
96
+ try { if (storePath && existsSync(storePath)) store = JSON.parse(readFileSync(storePath, 'utf8')); } catch { store = {}; }
97
+ return {
98
+ now,
99
+ createdFromBlame: (w) => (w.origin.kind === 'preset' && !w.origin.file ? null : gitBlameDate(root, w.origin.file, w.origin.line)),
100
+ firstSeen: (k) => store[k] ?? null,
101
+ recordFirstSeen: (k, d) => {
102
+ if (!storePath) return;
103
+ store[k] = d;
104
+ try { mkdirSync(dirname(storePath), { recursive: true }); writeFileSync(storePath, JSON.stringify(store, null, 2) + '\n'); } catch { /* read-only checkout: the date is still today, and the finding says so */ }
105
+ },
106
+ };
107
+ }
108
+
109
+ /** Read and resolve a policy file. Exits 2 when it cannot be read: a half-read policy is one nobody wrote. */
110
+ async function loadAt(path, root) {
111
+ const L = await lib();
112
+ const rel = posix(relative(root, path));
113
+ const r = await L.loadPolicy(readFileSync(path, 'utf8'), rel, presetSource(root));
114
+ if (r.errors.length) {
115
+ process.stderr.write(`neurarch: cannot use ${rel}:\n${r.errors.map((e) => ` ${e}`).join('\n')}\n`);
116
+ process.exit(2);
117
+ }
118
+ return r;
119
+ }
120
+
121
+ const say = (s) => process.stderr.write((process.stderr.isTTY && !process.env.NO_COLOR ? `\x1b[2m${s}\x1b[0m` : s) + '\n');
122
+
123
+ /**
124
+ * Called first thing by the CLI with its argv. Removes the policy flags,
125
+ * handles the `baseline` prefix, fills command flags from `defaults:` that the
126
+ * command did not give, and returns the state `finish` needs.
127
+ */
128
+ export async function setup(args) {
129
+ const st = { baselineMode: false };
130
+ if (args[0] === 'baseline') { args.shift(); st.baselineMode = true; }
131
+ Object.assign(st, takeFlags(args));
132
+ st.root = repoRoot(process.cwd()) ?? process.cwd();
133
+ st.policyPath = st['no-policy'] ? null : st.policy ? resolve(st.policy) : process.env.NEURARCH_POLICY ? resolve(process.env.NEURARCH_POLICY) : discoverPolicy();
134
+ if (st.policy && !existsSync(st.policyPath)) { process.stderr.write(`neurarch: --policy ${st.policy}: no such file\n`); process.exit(2); }
135
+ st.baselinePath = st.baseline ? resolve(st.baseline) : join(st.root, '.neurarch', 'baseline.json');
136
+ st.active = !!(st.policyPath || st.sarif || st.baselineMode || existsSync(st.baselinePath));
137
+ if (!st.active) return st;
138
+
139
+ if (st.policyPath) {
140
+ st.loaded = await loadAt(st.policyPath, st.root);
141
+ const d = st.loaded.policy.defaults;
142
+ const cmd = args[0];
143
+ const has = (f) => args.some((a, i) => (a === f || a.startsWith(`${f}=`)) && (args.indexOf('--') < 0 || i < args.indexOf('--')));
144
+ const inject = (flag, value) => {
145
+ const dd = args.indexOf('--');
146
+ if (dd >= 0) args.splice(dd, 0, flag, String(value)); else args.push(flag, String(value));
147
+ say(` policy default: ${flag} ${value} (from ${posix(relative(st.root, st.policyPath))})`);
148
+ };
149
+ const sized = has('--batch') || has('--data') || has('--inference');
150
+ if (d.gpu && !has('--gpu') && !['oom', 'rightsize', 'policy', 'pin-check'].includes(cmd)) inject('--gpu', d.gpu);
151
+ if (d.seq_len && !has('--seq-len') && (cmd === 'layout' || (!['serve-check', 'oom', 'rightsize', 'policy', 'pin-check'].includes(cmd) && sized))) inject('--seq-len', d.seq_len);
152
+ }
153
+ if (st.source) {
154
+ st.sourceAbs = resolve(st.source);
155
+ try { st.sourceText = readFileSync(st.sourceAbs, 'utf8'); } catch (e) { process.stderr.write(`neurarch: --source ${st.source}: ${e.message}\n`); process.exit(2); }
156
+ st.sourceRel = posix(relative(st.root, st.sourceAbs));
157
+ }
158
+ st.cluster = st.cluster ?? process.env.NEURARCH_CLUSTER ?? process.env.SLURM_CLUSTER_NAME;
159
+ return st;
160
+ }
161
+
162
+ /** Checker output -> findings + budget facts, through the bundle's thin adapters. */
163
+ export async function collect(run, st) {
164
+ const L = await lib();
165
+ const ctx = { model: run.model, path: st.sourceRel };
166
+ const findings = [];
167
+ const facts = { model: run.model };
168
+ if (run.layout) findings.push(...L.fromLayout(run.layout, ctx));
169
+ if (run.serve) { findings.push(...L.fromServe(run.serve, ctx)); if (run.engine) facts.engine = run.engine; }
170
+ if (run.lint) findings.push(...L.fromLint(run.lint, ctx));
171
+ if (run.dataFit) findings.push(...L.fromDataFit(run.dataFit, ctx));
172
+ if (run.change) findings.push(...L.fromChangeGate(run.change.gate, ctx));
173
+ if (run.findings) findings.push(...run.findings); // pin-check: already findings, each with its own file and line
174
+ const policy = st.loaded?.policy;
175
+ if (run.cost || run.inference) {
176
+ const { PREFLIGHT_GPUS } = await import('../engine.bundle.mjs');
177
+ const cards = PREFLIGHT_GPUS.map((g) => ({ name: g.name, gb: g.gb, id: g.hwId }));
178
+ const mopts = { gpu: run.gpu, fleet: policy?.defaults.cards, headroom: policy?.defaults.headroom, cards };
179
+ if (run.cost) findings.push(...L.memoryFindings({ kind: 'training', peakGb: run.cost.peakGb, upperGb: run.cost.peakGbUpper }, mopts, ctx));
180
+ if (run.inference) findings.push(...L.memoryFindings({ kind: 'inference', peakGb: run.inference.peakGb }, mopts, ctx));
181
+ if (run.cost?.estCostUsd != null && run.dataGiven) facts.estCostUsd = run.cost.estCostUsd;
182
+ }
183
+ if (run.params != null) facts.params = run.params;
184
+ if (run.gpu) facts.cards = [run.gpu];
185
+ return { findings, facts: [facts] };
186
+ }
187
+
188
+ /**
189
+ * Called by the CLI where it would exit. `code` is the checker's own exit
190
+ * code; the return value is the one to exit with.
191
+ */
192
+ export async function finish(st, run, code) {
193
+ if (!st?.active) return code;
194
+ const L = await lib();
195
+ const { findings, facts } = await collect(run, st);
196
+ const policy = st.loaded?.policy;
197
+ const ctx = { model: run.model, path: st.sourceRel, cluster: st.cluster };
198
+
199
+ const policyFindings = [...(st.loaded?.findings ?? [])];
200
+ let inline = [];
201
+ const inlineFrom = [...(st.sourceText != null ? [{ path: st.sourceRel, text: st.sourceText }] : []), ...(run.sources ?? [])];
202
+ for (const src of inlineFrom) {
203
+ const p = L.parseInlineWaivers(src.text, src.path);
204
+ inline.push(...p.waivers);
205
+ for (const pr of p.problems) policyFindings.push({ checker: 'policy', rule: 'policy/inline-waiver-unreadable', severity: 'warn', title: pr.message, path: src.path, line: pr.line });
206
+ }
207
+
208
+ let baseline;
209
+ if (!st.baselineMode && existsSync(st.baselinePath)) {
210
+ const b = L.readBaseline(readFileSync(st.baselinePath, 'utf8'));
211
+ if (b.error) { process.stderr.write(`neurarch: ${posix(relative(st.root, st.baselinePath))}: ${b.error}\n`); return 2; }
212
+ baseline = b.baseline;
213
+ }
214
+
215
+ const ev = L.evaluate({ policy, findings, facts, inline, policyFindings, baseline, ctx }, waiverDeps(st.root));
216
+ st.judged = ev.judged; // --attest records what the policy concluded, not only what the checkers said
217
+ const out = run.json ? process.stderr : process.stdout;
218
+ const policyRel = st.policyPath ? posix(relative(st.root, st.policyPath)) : undefined;
219
+ const baselineRel = posix(relative(st.root, st.baselinePath));
220
+
221
+ if (st.baselineMode) {
222
+ const prev = existsSync(st.baselinePath) ? L.readBaseline(readFileSync(st.baselinePath, 'utf8')).baseline : undefined;
223
+ const checkerFindings = ev.judged.filter((j) => j.checker !== 'policy');
224
+ const scopes = run.scopes ?? [...new Set(['layout', 'serve', 'lint', 'data-fit', 'change', 'memory', 'budget'])].map((checker) => ({ checker, model: run.model, path: st.sourceRel }));
225
+ const next = L.mergeBaseline(prev, checkerFindings, scopes, L.today(new Date()));
226
+ mkdirSync(dirname(st.baselinePath), { recursive: true });
227
+ writeFileSync(st.baselinePath, JSON.stringify(next, null, 2) + '\n');
228
+ out.write(`\n baseline ${checkerFindings.length} finding${checkerFindings.length === 1 ? '' : 's'} from this run written to ${baselineRel} (${next.findings.length} in the file). Later runs fail only on new ones; --all shows every one.\n\n`);
229
+ return 0;
230
+ }
231
+
232
+ if (st.sarif) {
233
+ const sarif = L.buildSarif({
234
+ command: run.command, model: run.model, source: st.sourceRel, policyFile: policyRel, judged: ev.judged,
235
+ changed: st['changed-lines'] ? L.parseChangedLines(existsSync(st['changed-lines']) && statSync(st['changed-lines']).isFile() ? readFileSync(st['changed-lines'], 'utf8') : st['changed-lines']) : undefined,
236
+ includeExisting: !!st.all, toolVersion: toolVersion(),
237
+ readText: (p) => { try { return readFileSync(resolve(st.root, p), 'utf8'); } catch { return undefined; } },
238
+ });
239
+ writeFileSync(st.sarif, JSON.stringify(sarif, null, 2) + '\n');
240
+ }
241
+ out.write('\n' + L.renderPolicyText(ev, { policyFile: policyRel, presets: policy?.presets, baselineFile: baseline ? baselineRel : undefined, showAll: !!st.all }));
242
+ if (st.sarif) out.write(` sarif ${st.sarif} (${((n) => `${n} result${n === 1 ? '' : 's'}`)(ev.judged.filter((j) => j.effective !== 'off' && (st.all || j.baseline !== 'existing')).length)})\n`);
243
+ out.write('\n');
244
+ return ev.exitCode;
245
+ }
246
+
247
+ /** `neurarch policy <show | validate | schema | apply>`. */
248
+ export async function policyCommand(args, hooks = {}) {
249
+ const sub = args[0];
250
+ const L = await lib();
251
+ const json = args.includes('--json');
252
+ const st = { root: repoRoot(process.cwd()) ?? process.cwd() };
253
+ const pIdx = args.indexOf('--policy');
254
+ const explicit = pIdx >= 0 ? args[pIdx + 1] : args.find((a, i) => i > 0 && !a.startsWith('--') && args[i - 1] !== '--policy' && args[i - 1] !== '--cluster');
255
+ const path = explicit ? resolve(explicit) : process.env.NEURARCH_POLICY ? resolve(process.env.NEURARCH_POLICY) : discoverPolicy();
256
+
257
+ if (sub === 'schema') { process.stdout.write(JSON.stringify(L.POLICY_SCHEMA, null, 2) + '\n'); return 0; }
258
+ if (!sub || sub === '-h' || sub === '--help') {
259
+ process.stdout.write(`neurarch policy: the repo's .neurarch.yml
260
+
261
+ npx neurarch policy show [--policy .neurarch.yml] [--json] the effective policy after presets, and every waiver's dates
262
+ npx neurarch policy validate [file] exit 0 when the file can be used, 2 with the reasons when not
263
+ npx neurarch policy schema the JSON Schema (also at https://neurarch.com/schema/neurarch-policy-v1.json)
264
+ npx neurarch policy apply --json [--policy p] [--cluster c] < findings.json
265
+ judge findings from another tool (the SkyPilot and SLURM helpers use this)
266
+
267
+ Every check also takes: --policy <file> | --no-policy, --sarif <out.sarif>, --source <launch file>,
268
+ --changed-lines <diff | path:lines>, --cluster <name>, --baseline <file>, --all.
269
+ \`npx neurarch baseline <check ...>\` writes what that check finds to .neurarch/baseline.json.
270
+ `);
271
+ return 0;
272
+ }
273
+ if (sub === 'apply') {
274
+ let input;
275
+ try { input = JSON.parse(await new Promise((res, rej) => { let s = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', (d) => { s += d; }); process.stdin.on('end', () => res(s)); process.stdin.on('error', rej); })); } catch (e) {
276
+ process.stdout.write(JSON.stringify({ error: `stdin is not JSON: ${e.message}` }) + '\n'); return 2;
277
+ }
278
+ if (!path || !existsSync(path)) { process.stdout.write(JSON.stringify({ policy: null, findings: [], exitCode: 0 }) + '\n'); return (await hooks.onApply?.(input, null, { root: st.root })) ?? 0; }
279
+ const rel = posix(relative(st.root, path));
280
+ const r = await L.loadPolicy(readFileSync(path, 'utf8'), rel, presetSource(st.root));
281
+ if (r.errors.length) { process.stdout.write(JSON.stringify({ policy: rel, error: r.errors.join('; ') }) + '\n'); return 2; }
282
+ const cIdx = args.indexOf('--cluster');
283
+ const ctx = { model: input.model, path: input.path, cluster: cIdx >= 0 ? args[cIdx + 1] : input.cluster };
284
+ const ev = L.evaluate({ policy: r.policy, findings: input.findings ?? [], facts: input.facts ?? [], policyFindings: r.findings, ctx }, waiverDeps(st.root));
285
+ process.stdout.write(JSON.stringify({ policy: rel, presets: r.policy.presets, budget: r.policy.budget, findings: ev.judged, counts: ev.counts, exitCode: ev.exitCode }) + '\n');
286
+ return (await hooks.onApply?.(input, ev, { root: st.root, policyPath: path })) ?? 0;
287
+ }
288
+ if (!path || !existsSync(path)) { process.stderr.write(`neurarch policy ${sub}: no .neurarch.yml here or above (give --policy <file>)\n`); return 2; }
289
+ const rel = posix(relative(st.root, path));
290
+ const r = await L.loadPolicy(readFileSync(path, 'utf8'), rel, presetSource(st.root));
291
+ if (r.errors.length) {
292
+ if (json) process.stdout.write(JSON.stringify({ policy: rel, ok: false, errors: r.errors }, null, 2) + '\n');
293
+ else process.stderr.write(`${rel}: cannot be used\n${r.errors.map((e) => ` ${e}`).join('\n')}\n`);
294
+ return 2;
295
+ }
296
+ if (sub === 'validate') {
297
+ if (json) process.stdout.write(JSON.stringify({ policy: rel, ok: true, presets: r.policy.presets, findings: r.findings }, null, 2) + '\n');
298
+ else process.stdout.write(`${rel}: ok${r.policy.presets.length ? ` (extends ${r.policy.presets.join(', ')})` : ''}, ${Object.keys(r.policy.rules).length} rule override(s), ${r.policy.waivers.length} waiver(s)\n${r.findings.map((f) => ` ${f.severity} ${f.rule}: ${f.title}\n`).join('')}`);
299
+ return 0;
300
+ }
301
+ if (sub === 'show') {
302
+ const { waivers, findings } = L.resolveWaivers(r.policy.waivers, waiverDeps(st.root));
303
+ if (json) { process.stdout.write(JSON.stringify({ policy: r.policy, waivers, findings: [...r.findings, ...findings] }, null, 2) + '\n'); return 0; }
304
+ const p = r.policy;
305
+ const lines = [`${rel}${p.presets.length ? ` extends ${p.presets.join(', ')}` : ''}`];
306
+ if (Object.keys(p.defaults).length) lines.push(` defaults ${Object.entries(p.defaults).map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(',') : v}`).join(' ')}`);
307
+ if (Object.keys(p.budget).length) lines.push(` budget ${Object.entries(p.budget).map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(',') : v}`).join(' ')}`);
308
+ if (p.engines.length) lines.push(` engines ${p.engines.join(', ')}`);
309
+ for (const [k, v] of Object.entries(p.rules)) lines.push(` rule ${k}: ${v}`);
310
+ for (const w of waivers) {
311
+ const state = w.invalid ? `does not apply (${w.invalid})` : w.expired ? `EXPIRED ${w.expires}` : `in force until ${w.expires}${w.expiresSource === 'defaulted' ? ' (defaulted: created + 30 days)' : ''}`;
312
+ lines.push(` waiver ${w.rule}${w.model ? ` model=${w.model}` : ''}${w.path ? ` path=${w.path}` : ''}${w.cluster ? ` cluster=${w.cluster}` : ''} owner=${w.owner ?? '-'} created ${w.created} (${w.createdSource}) ${state}`);
313
+ }
314
+ for (const f of [...r.findings, ...findings]) lines.push(` ${f.severity.padEnd(5)} ${f.rule}: ${f.title}`);
315
+ process.stdout.write(lines.join('\n') + '\n');
316
+ return 0;
317
+ }
318
+ process.stderr.write(`neurarch policy: unknown subcommand ${sub} (show, validate, schema, apply)\n`);
319
+ return 2;
320
+ }
package/bin/scan.mjs ADDED
@@ -0,0 +1,255 @@
1
+ /**
2
+ * `neurarch scan [paths...]`: a dependency scan for the models a repository
3
+ * pulls. Finds every Hugging Face download with a literal repo id (pinned or
4
+ * not; the same reader as pin-check), then for each model reads the Hub API at
5
+ * the pinned commit and at main, the recorded history at
6
+ * neurarch.com/changes/index.json, and (pinned, moved) renders the chat
7
+ * template at both commits. Grading is src/utils/policy/modelScan.ts.
8
+ *
9
+ * Network: huggingface.co and www.neurarch.com only. Nothing from the scanned
10
+ * repository is sent anywhere; only public model ids are requested.
11
+ */
12
+ import { readFileSync, writeFileSync } from 'node:fs';
13
+ import { randomUUID } from 'node:crypto';
14
+ import { relative, resolve, sep, join } from 'node:path';
15
+ import { readdirSync, statSync } from 'node:fs';
16
+
17
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
18
+ const c = (code, s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
19
+ const posix = (p) => p.split(sep).join('/');
20
+ const SKIP_DIRS = new Set(['.git', '.hg', '.svn', 'node_modules', '.venv', 'venv', 'env', '__pycache__', '.tox', '.nox', 'site-packages', '.ipynb_checkpoints']);
21
+ const FEED = process.env.NEURARCH_CHANGES_URL || 'https://www.neurarch.com/changes/index.json';
22
+ const TRACKED = process.env.NEURARCH_TRACKED_URL || 'https://www.neurarch.com/changes-feeds/advisories/index.json';
23
+
24
+ const HELP = `neurarch scan: a dependency scan for the models your code pulls
25
+
26
+ npx neurarch scan [paths...] [--json] [--no-template] [--fix] [--cyclonedx out.cdx.json]
27
+
28
+ Finds every Hugging Face model your .py, .ipynb, YAML, shell scripts and
29
+ Dockerfiles download (from_pretrained, vllm serve, hf download, base_model:,
30
+ ...), pinned or not. For each one it reports, in three lanes:
31
+
32
+ security Python the loader runs from the repo (auto_map) that is unpinned,
33
+ changed since your pin, or lives in another repository that
34
+ revision= does not pin; weights only in pickle formats.
35
+ behavior recorded upstream changes since your pin (template, tokenizer,
36
+ EOS, generation defaults) from neurarch.com/changes, and whether
37
+ the chat template now renders a different prompt.
38
+ hygiene downloads not pinned to a commit.
39
+
40
+ It also reads repo ids and commits held in module constants (MODEL_ID = ...),
41
+ metadata records (MTEB's ModelMeta(name=..., revision=...)) and serving env
42
+ vars in manifests, compose files and Dockerfiles (MODEL_ID, REVISION).
43
+
44
+ --fix hold the code you run today: add code_revision= (pinned to the
45
+ code repository's current commit) where a model imports code from
46
+ another repository, and revision= where a remote-code load is not
47
+ pinned. Edits .py files and shell launch lines in place; review with
48
+ git diff. Calls it cannot edit safely are listed, not guessed.
49
+ --cyclonedx F (alias --bom) write a CycloneDX 1.6 BOM: one component per model (purl at the
50
+ commit), cross-repository code as a dependency, each finding as a
51
+ vulnerability entry mapped to NIST SP 800-218A / AI 600-1.
52
+
53
+ Exit 1 when any finding is high. Reads huggingface.co and www.neurarch.com;
54
+ set HF_TOKEN for gated repos. Only public model ids leave your machine.
55
+ `;
56
+
57
+ function* walk(abs, kindOf) {
58
+ let st;
59
+ try { st = statSync(abs); } catch { return; }
60
+ if (st.isFile()) { if (kindOf(abs) && st.size <= 5 * 1024 * 1024) yield abs; return; }
61
+ if (!st.isDirectory()) return;
62
+ let entries;
63
+ try { entries = readdirSync(abs, { withFileTypes: true }); } catch { return; }
64
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
65
+ if (e.isDirectory() && SKIP_DIRS.has(e.name)) continue;
66
+ if (e.isSymbolicLink()) continue;
67
+ yield* walk(join(abs, e.name), kindOf);
68
+ }
69
+ }
70
+
71
+ const headers = () => (process.env.HF_TOKEN ? { Authorization: `Bearer ${process.env.HF_TOKEN}` } : {});
72
+ async function getJson(url, h = {}) {
73
+ try {
74
+ const r = await fetch(url, { headers: h, signal: AbortSignal.timeout(20_000) });
75
+ return r.ok ? await r.json() : null;
76
+ } catch { return null; }
77
+ }
78
+ const hubInfo = (id, rev) => getJson(`https://huggingface.co/api/models/${id}/revision/${encodeURIComponent(rev)}?blobs=true`, headers());
79
+
80
+ async function rawConfig(id, rev) {
81
+ try {
82
+ const r = await fetch(`https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/config.json`, { headers: headers(), signal: AbortSignal.timeout(20_000) });
83
+ return r.ok ? await r.json() : null;
84
+ } catch { return null; }
85
+ }
86
+
87
+ async function templateAt(id, rev) {
88
+ const get = async (f) => {
89
+ try {
90
+ const r = await fetch(`https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/${f}`, { headers: headers(), signal: AbortSignal.timeout(20_000) });
91
+ return r.ok ? r.text() : null;
92
+ } catch { return null; }
93
+ };
94
+ const [jinja, tokRaw] = await Promise.all([get('chat_template.jinja'), get('tokenizer_config.json')]);
95
+ let tok = null;
96
+ try { tok = tokRaw ? JSON.parse(tokRaw) : null; } catch { tok = null; }
97
+ const t = tok?.chat_template;
98
+ const text = jinja ?? (typeof t === 'string' ? t : Array.isArray(t) ? (t.find((x) => x?.name === 'default') ?? t[0])?.template : null);
99
+ const tx = (v) => (v && typeof v === 'object' ? v.content : typeof v === 'string' ? v : null);
100
+ return text ? { text, specials: { bos_token: tx(tok?.bos_token), eos_token: tx(tok?.eos_token) } } : null;
101
+ }
102
+
103
+ const SEV = { high: '31', medium: '33', low: '2' };
104
+
105
+ export async function scanCommand(args, engine) {
106
+ const L = await import('../policy.bundle.mjs');
107
+ const o = { paths: [], template: true };
108
+ const skip = new Set();
109
+ for (const [i, a] of args.entries()) {
110
+ if (skip.has(i)) continue;
111
+ if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0; }
112
+ if (a === '--json') o.json = true;
113
+ else if (a === '--no-template') o.template = false;
114
+ else if (a === '--fix') o.fix = true;
115
+ else if (a === '--cyclonedx' || a === '--bom') { o.bom = args[args.indexOf(a) + 1]; if (!o.bom || o.bom.startsWith('-')) { process.stderr.write(`neurarch scan: ${a} needs a file path\n`); return 2; } skip.add(args.indexOf(a) + 1); }
116
+ else if (a.startsWith('-')) { process.stderr.write(`neurarch scan: unknown flag ${a} (--help)\n`); return 2; }
117
+ else o.paths.push(a);
118
+ }
119
+ if (!o.paths.length) o.paths.push('.');
120
+ const root = process.cwd();
121
+ const refs = [];
122
+ let files = 0;
123
+ for (const p of o.paths) {
124
+ const abs = resolve(p);
125
+ try { statSync(abs); } catch { process.stderr.write(`neurarch scan: ${p}: no such file or directory\n`); return 2; }
126
+ for (const f of walk(abs, (x) => L.pinFileKind(posix(x)))) {
127
+ let text;
128
+ try { text = readFileSync(f, 'utf8'); } catch { continue; }
129
+ files++;
130
+ const rel = posix(relative(root, f)) || posix(f);
131
+ for (const h of L.scanModelRefs(rel, text)) if (h.repoType === 'model') refs.push(h);
132
+ }
133
+ }
134
+
135
+ // One assessment per (model, pin); call sites listed under it.
136
+ const groups = new Map();
137
+ const codeHeads = new Map();
138
+ for (const h of refs) {
139
+ const pin = h.pinned ? h.revision : undefined;
140
+ const k = `${h.repo}@${pin ?? ''}`;
141
+ if (!groups.has(k)) groups.set(k, { id: h.repo, pinned: pin, sites: [], hits: [], codeRevision: true });
142
+ const g = groups.get(k);
143
+ g.sites.push(`${h.path}:${h.line}`);
144
+ g.hits.push(h);
145
+ if (!h.codeRevision) g.codeRevision = false;
146
+ if (h.via !== 'env' || h.trustRemoteCode) g.remoteCodeRuns = undefined;
147
+ else if (g.hits.length === 1) g.remoteCodeRuns = false;
148
+ }
149
+
150
+ const [feed, advisories] = await Promise.all([getJson(FEED), getJson(TRACKED)]);
151
+ const recorded = feed?.changes ?? null;
152
+ const securityRecorded = (feed?.lanes ?? []).filter((l) => l.lane === 'security');
153
+ const tracked = new Set((advisories?.advisories ?? []).map((a) => a.model));
154
+ for (const ch of recorded ?? []) tracked.add(ch.id);
155
+
156
+ const results = [];
157
+ for (const g of groups.values()) {
158
+ const [atMain, atPin] = await Promise.all([hubInfo(g.id, 'main'), g.pinned ? hubInfo(g.id, g.pinned) : null]);
159
+ let templateVerdict = null;
160
+ const moved = g.pinned && atMain?.sha && !atMain.sha.startsWith(g.pinned);
161
+ if (o.template && moved && engine?.checkRevision) {
162
+ const [a, b] = await Promise.all([templateAt(g.id, g.pinned), templateAt(g.id, atMain.sha)]);
163
+ if (a && b) {
164
+ try { templateVerdict = engine.checkRevision(a.text, b.text, 'vllm', a.specials, b.specials).verdict; } catch { templateVerdict = null; }
165
+ }
166
+ }
167
+ const [rawConfigMain, rawConfigPin] = await Promise.all([atMain?.sha ? rawConfig(g.id, atMain.sha) : null, g.pinned ? rawConfig(g.id, g.pinned) : null]);
168
+ const code = g.remoteCodeRuns === false ? { declared: false, crossRepo: [] } : L.remoteCodeOf(atMain ?? atPin, g.id);
169
+ const codeRepos = [];
170
+ for (const repo of code.crossRepo) {
171
+ if (!codeHeads.has(repo)) codeHeads.set(repo, hubInfo(repo, 'main').then((x) => x?.sha ?? null));
172
+ codeRepos.push({ id: repo, sha: await codeHeads.get(repo), held: g.codeRevision });
173
+ }
174
+ const findings = atMain || atPin
175
+ ? L.assessRef({ id: g.id, pinned: g.pinned, codeRevision: g.codeRevision, atMain, atPin, recorded, tracked: tracked.has(g.id), templateVerdict, rawConfigMain, rawConfigPin, remoteCodeRuns: g.remoteCodeRuns, securityRecorded: g.remoteCodeRuns === false ? [] : securityRecorded })
176
+ : [{ lane: 'hygiene', severity: 'low', kind: 'unreadable', message: 'The Hub did not answer for this id (private, gated without HF_TOKEN, renamed or deleted). A deleted author name can be re-registered by someone else; check who owns it now.' }];
177
+ results.push({ ...g, mainSha: atMain?.sha ?? null, tracked: tracked.has(g.id), remoteCode: code.declared, codeRepos, findings });
178
+ }
179
+ const fixes = o.fix ? applyFixes(results, root, L) : null;
180
+ if (o.bom) {
181
+ let version = '0';
182
+ try { version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version; } catch { /* keep 0 */ }
183
+ const bom = L.scanBom(results.map((r) => ({ id: r.id, pinned: r.pinned, mainSha: r.mainSha, sites: r.sites, codeRepos: r.codeRepos, findings: r.findings })), { tool: 'neurarch', version, timestamp: new Date().toISOString(), serial: `urn:uuid:${randomUUID()}` });
184
+ writeFileSync(o.bom, JSON.stringify(bom, null, 2) + '\n');
185
+ }
186
+ const code = L.scanExitCode(results.map((r) => r.findings));
187
+
188
+ if (o.json) {
189
+ process.stdout.write(JSON.stringify({ files, feed: recorded ? FEED : null, models: results.map(({ hits, ...r }) => r), ...(fixes ? { fixes } : {}), ...(o.bom ? { bom: o.bom } : {}) }, null, 2) + '\n');
190
+ return code;
191
+ }
192
+ const out = process.stdout;
193
+ const count = (sev) => results.reduce((n, r) => n + r.findings.filter((f) => f.severity === sev && f.kind !== 'pin-current').length, 0);
194
+ out.write(`\n ${c('1', 'neurarch scan')} ${files} file${files === 1 ? '' : 's'} read, ${results.length} model reference${results.length === 1 ? '' : 's'}, ${c(SEV.high, `${count('high')} high`)}, ${c(SEV.medium, `${count('medium')} medium`)}\n`);
195
+ if (!recorded) out.write(` ${c('33', 'recorded history unavailable')} (${FEED}); upstream changes since your pin are not listed\n`);
196
+ for (const r of results) {
197
+ out.write(`\n ${c('1', r.id)}${r.pinned ? ` @ ${r.pinned.slice(0, 12)}` : c('33', ' (not pinned)')}${r.tracked ? '' : c('2', ' no recorded upstream changes at neurarch.com/changes')}\n`);
198
+ out.write(` ${c('2', r.sites.slice(0, 4).join(', ') + (r.sites.length > 4 ? ` +${r.sites.length - 4}` : ''))}\n`);
199
+ for (const f of r.findings) {
200
+ out.write(` ${c(SEV[f.severity], f.severity.padEnd(6))} ${f.lane.padEnd(8)} ${f.message}\n`);
201
+ if (f.fix) out.write(` ${' '.repeat(16)}${c('2', 'fix: ' + f.fix)}\n`);
202
+ if (f.url) out.write(` ${' '.repeat(16)}${c('2', f.url)}\n`);
203
+ }
204
+ }
205
+ if (fixes) {
206
+ out.write(`\n ${c('1', '--fix')} ${fixes.edited.length} call site${fixes.edited.length === 1 ? '' : 's'} edited in ${new Set(fixes.edited.map((e) => e.path)).size} file(s)${fixes.skipped.length ? `, ${fixes.skipped.length} left for you` : ''}\n`);
207
+ for (const e of fixes.edited) out.write(` ${c('32', 'edited')} ${e.path}:${e.line} ${e.what}\n`);
208
+ for (const e of fixes.skipped) out.write(` ${c('33', 'skipped')} ${e.path}:${e.line} ${e.why}\n`);
209
+ if (fixes.edited.length) out.write(` ${c('2', 'Review with git diff. The commits are what each repository has on main today, so nothing you run changes now; it just stops changing underneath you.')}\n`);
210
+ }
211
+ if (o.bom) out.write(`\n ${c('1', '--cyclonedx')} wrote ${o.bom} (CycloneDX 1.6, ${results.length} model${results.length === 1 ? '' : 's'})\n`);
212
+ out.write(`\n ${c('2', 'security = code that runs on load or weights that can execute; behavior = what the model receives changed, not a vulnerability.')}\n\n`);
213
+ return code;
214
+ }
215
+
216
+ /**
217
+ * --fix: for each model that runs remote code, add what holds it to the
218
+ * commits upstream has today. Python call sites and shell launch lines only;
219
+ * records (ModelMeta) and env vars are listed for a person, because which
220
+ * call consumes them is not in the file.
221
+ */
222
+ function applyFixes(results, root, L) {
223
+ const edited = [];
224
+ const skipped = [];
225
+ const byFile = new Map();
226
+ for (const r of results) {
227
+ if (!r.remoteCode) continue;
228
+ const crossHeld = r.codeRepos.length ? r.codeRepos[0] : null;
229
+ const set = {};
230
+ if (!r.pinned && r.mainSha) set.revision = r.mainSha;
231
+ if (crossHeld && !r.codeRevision && crossHeld.sha) set.codeRevision = crossHeld.sha;
232
+ if (r.codeRepos.length > 1) { for (const h of r.hits) skipped.push({ path: h.path, line: h.line, why: `imports code from ${r.codeRepos.length} repositories; code_revision takes one` }); continue; }
233
+ if (!set.revision && !set.codeRevision) continue;
234
+ for (const h of r.hits) {
235
+ if (h.via === 'record' || h.via === 'env') { skipped.push({ path: h.path, line: h.line, why: `${h.via === 'env' ? 'an env var' : 'a metadata record'}: pass ${set.codeRevision ? `code_revision="${set.codeRevision}"` : `revision="${set.revision}"`} where it is loaded` }); continue; }
236
+ if (!byFile.has(h.path)) byFile.set(h.path, []);
237
+ byFile.get(h.path).push({ h, set });
238
+ }
239
+ }
240
+ for (const [path, items] of byFile) {
241
+ const abs = resolve(root, path);
242
+ if (/\.ipynb$/i.test(path)) { for (const { h } of items) skipped.push({ path, line: h.line, why: 'a notebook; edit the cell by hand' }); continue; }
243
+ let src;
244
+ try { src = readFileSync(abs, 'utf8'); } catch { continue; }
245
+ // bottom-up so earlier line numbers stay valid
246
+ for (const { h, set } of items.sort((a, b) => b.h.line - a.h.line)) {
247
+ const r = h.syntax === 'python' ? L.fixPythonCall(src, h.line, h.api, set) : h.syntax === 'shell' ? L.fixShellLine(src, h.line, set) : { skipped: 'YAML: add the revision keys by hand' };
248
+ if ('src' in r) { src = r.src; edited.push({ path, line: h.line, what: [set.revision && 'revision=', set.codeRevision && 'code_revision='].filter(Boolean).join(' and ') }); }
249
+ else if (r.skipped !== 'already holds both') skipped.push({ path, line: h.line, why: r.skipped });
250
+ }
251
+ writeFileSync(abs, src);
252
+ }
253
+ edited.sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line);
254
+ return { edited, skipped };
255
+ }