neurarch 0.1.2 → 0.3.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
+ }