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/neurarch.mjs CHANGED
@@ -22,7 +22,9 @@
22
22
  *
23
23
  * Zero dependencies; the engine is bundled. Set HF_TOKEN for gated repos.
24
24
  */
25
- import { inspectHFModel, keyFor, AGREE_TOLERANCE, priceHFModel, parseHumanSize, PREFLIGHT_GPUS, specFromFlags, renderLoraText, rightsize, renderMarkdown, headline, applyPrices, DEFAULT_CARDS, oomReport, renderOomText, readAttention, attentionPhrase, readSeqLen, DEFAULT_SEQ_LEN, inferHFModel, readInferencePrecision, INFERENCE_PRECISIONS, DEFAULT_GEN_TOKENS, DEFAULT_INFERENCE_BATCH, CHANGE_HEADROOM, storedTwiceSentence, dataFitHFModel, layoutHFModel, readLayout, readHistogram, renderLayoutText, resolveLayoutGpu, serveCheckHFModel, parseServeCommand, readSampler, renderServeText, SERVE_ENGINES } from '../engine.bundle.mjs';
25
+ import { checkParity, checkRevision, renderConformanceText, weightsDiff, renderWeightsDiffText, inspectHFModel, keyFor, AGREE_TOLERANCE, priceHFModel, parseHumanSize, PREFLIGHT_GPUS, specFromFlags, renderLoraText, rightsize, renderMarkdown, headline, applyPrices, DEFAULT_CARDS, oomReport, renderOomText, readAttention, attentionPhrase, readSeqLen, DEFAULT_SEQ_LEN, inferHFModel, readInferencePrecision, INFERENCE_PRECISIONS, DEFAULT_GEN_TOKENS, DEFAULT_INFERENCE_BATCH, CHANGE_HEADROOM, storedTwiceSentence, dataFitHFModel, layoutHFModel, readLayout, readHistogram, renderLayoutText, resolveLayoutGpu, serveCheckHFModel, resolveServeGpu, parseServeCommand, readSampler, renderServeText, SERVE_ENGINES, readReceiptInput, buildReceipt, renderReceiptText, predictionFromReport } from '../engine.bundle.mjs';
26
+ import { setup as policySetup, finish as policyFinish, policyCommand } from './policy.mjs';
27
+ import { setup as attestSetup, finish as attestFinish, finishPolicyApply } from './attest.mjs';
26
28
  /** The channel tag on every link this program prints. `docs/DISTRIBUTION.md`
27
29
  * has asked for one since the first release: without it a visit from a tool
28
30
  * and a visit from a search result are the same row, and "which channel brings
@@ -73,6 +75,22 @@ function gpuFromFlag(arg) {
73
75
  }
74
76
 
75
77
  const args = process.argv.slice(2);
78
+ // `--attest` / `--cyclonedx`: the run as an in-toto record and an ML-BOM fragment, see ./attest.mjs.
79
+ const att = attestSetup(args);
80
+ // `.neurarch.yml`, waivers, baselines, SARIF: see ./policy.mjs. Inert when the repo has none of them.
81
+ if (args[0] === 'policy') process.exit(await policyCommand(args.slice(1), att.active ? { onApply: (input, ev, st) => { att.argv = [...args]; return finishPolicyApply(att, st, input, ev); } } : undefined));
82
+ const pol = await policySetup(args);
83
+ att.argv = [...args];
84
+ /** Policy first (it may change the exit code), then the record of what the run concluded. */
85
+ const finish = async (run, code) => attestFinish(att, pol, run, await policyFinish(pol, run, code));
86
+ // pin-check: Hugging Face downloads not pinned to a commit (Bandit B615), see ./pinCheck.mjs.
87
+ // weights-diff: what differs between two local checkpoints, from the bytes, see ./weightsDiff.mjs.
88
+ if (args[0] === 'weights-diff') process.exit((await import('./weightsDiff.mjs')).weightsDiffCommand(args.slice(1), weightsDiff, renderWeightsDiffText));
89
+ if (args[0] === 'pin-check') process.exit(await (await import('./pinCheck.mjs')).pinCheckCommand(args.slice(1), pol, policyFinish));
90
+ // scan: a dependency scan for the models a repository pulls, see ./scan.mjs.
91
+ if (args[0] === 'scan') process.exit(await (await import('./scan.mjs')).scanCommand(args.slice(1), { checkRevision }));
92
+ // template-check: the prompt an engine sends against the reference, or across two revisions, see ./templateCheck.mjs.
93
+ if (args[0] === 'template-check') process.exit(await (await import('./templateCheck.mjs')).templateCheckCommand(args.slice(1), { checkParity, checkRevision, renderConformanceText }));
76
94
 
77
95
  // ── oom: why a job ran out of GPU memory, and the least invasive fix ─────────
78
96
  //
@@ -173,10 +191,11 @@ if (args[0] === 'layout') {
173
191
  Checks: world size and TP / EP / CP divisibility (block), per-stage balance
174
192
  with a rebalanced --layers, the pipeline bubble, per-stage memory on the card,
175
193
  and with --seq-hist (CSV of len,count) how much the slowest DP rank waits on
176
- uneven sequence lengths. Stage time is predicted, not timed: matmul FLOPs at
177
- 40% of the card's peak plus memory-bound bytes (norms, elementwise, the fp32
178
- loss) at 80% of its bandwidth; step time is m x slowest stage + the fill and
179
- drain, at your microbatch count. --fused-ce says the loss never holds fp32
194
+ uneven sequence lengths. Stage time is predicted, not timed: each matmul at up
195
+ to 40% of the card's peak, less when short (a curve fitted to measured kernels
196
+ on H100, L4, A100, V100, T4), plus memory-bound bytes (norms, elementwise, the
197
+ fp32 loss) at 80% of its bandwidth; step time simulates the 1F1B or
198
+ interleaved schedule at your microbatch count. --fused-ce says the loss never holds fp32
180
199
  logits (Liger, chunked CE). Exits 1 when a check blocks.
181
200
  `);
182
201
  process.exit(L.help ? 0 : 2);
@@ -224,7 +243,7 @@ logits (Liger, chunked CE). Exits 1 when a check blocks.
224
243
  .replace(/ NO$/gm, ` ${red('NO')}`);
225
244
  process.stdout.write(text);
226
245
  }
227
- process.exit(blocked ? 1 : 0);
246
+ process.exit(await finish({ command: 'layout', model: pos[0], layout: r.report, layoutSpec: layout, gpu: L.gpu, json: L.json }, blocked ? 1 : 0));
228
247
  }
229
248
 
230
249
  // ── serve-check: will this vLLM / SGLang / llama.cpp launch start ────────────
@@ -239,7 +258,7 @@ if (args[0] === 'serve-check') {
239
258
  const after = dd >= 0 ? args.slice(dd + 1) : null;
240
259
  const S = {};
241
260
  const pos = [];
242
- const VAL = ['engine', 'gpu', 'gpus', 'cmd', 'against', 'sampler'];
261
+ const VAL = ['engine', 'gpu', 'gpus', 'cmd', 'against', 'sampler', 'vllm-version', 'sglang-version', 'receipt', 'gpu-mem', 'gpu-mem-used'];
243
262
  for (let i = 0; i < rest.length; i++) {
244
263
  const a = rest[i];
245
264
  const eq = /^--([a-z-]+)=(.*)$/.exec(a);
@@ -254,7 +273,9 @@ if (args[0] === 'serve-check') {
254
273
  process.stdout.write(`neurarch serve-check: will this serving launch start, hold what it promises, and serve the model as published
255
274
 
256
275
  npx neurarch serve-check <hf-id | graph.json> [--engine vllm|sglang|llamacpp] --gpu h100 [--gpus 4]
257
- [--against <old-hf-id>] [--sampler temperature=0.7,top_p=0.8] [--json] -- <launch command>
276
+ [--vllm-version 0.19.1 | --sglang-version 0.5.22] [--against <old-hf-id>]
277
+ [--gpu-mem <GiB>] [--gpu-mem-used <GiB>]
278
+ [--sampler temperature=0.7,top_p=0.8] [--receipt <startup plan | dir | vLLM log>] [--json] -- <launch command>
258
279
  npx neurarch serve-check <hf-id> --gpu l4 --cmd "vllm serve Qwen/Qwen3-8B -tp 4 --max-model-len 32768"
259
280
 
260
281
  The launch command is the one you would run: vllm serve ..., python -m
@@ -264,13 +285,35 @@ llama.cpp give the original repo id, since a .gguf file carries no config.json.
264
285
 
265
286
  Checks: TP / PP / DP / EP legality against the heads, KV heads, FFN and expert
266
287
  widths and the GPU count; the served length against max_position_embeddings and
267
- rope_scaling; weights plus KV cache per GPU against the card and the engine's
268
- memory fraction, and how many full-length sequences fit; dtype and quant method
269
- against the card's compute capability; the chat template, tool and reasoning
270
- parsers, and sampler defaults against generation_config.json. --against diffs
271
- the config of the model being replaced. Everything is derived from files, not
272
- measured; template checks do not render a conversation. Exits 1 when a check
273
- blocks.
288
+ rope_scaling; memory per GPU with the engine's own arithmetic (vLLM's KV cache
289
+ blocks per attention type and the reserve it takes first, SGLang's
290
+ mem_fraction_static formula, llama.cpp's cells and the GGUF header), predicting
291
+ the "GPU KV cache size" and "Maximum concurrency" lines; the quant method
292
+ against each engine release's own minimum compute capability; the vLLM recipe
293
+ for the model (parsers, trust-remote-code, min version); the chat template and
294
+ sampler defaults against generation_config.json. Defaults that changed between
295
+ releases (gpu_memory_utilization 0.9 -> 0.92 and CUDA graphs counted, both in
296
+ vLLM 0.20.0) follow --vllm-version, or the newest release the tables were read
297
+ from, and the report says which. --against diffs the config of the model being
298
+ replaced. Everything is predicted from files, not measured; template checks do
299
+ not render a conversation. Exits 1 when a check blocks.
300
+
301
+ Cards: the app's table plus a40, gh200-96g, gh200-144g, rtx-pro-6000 and
302
+ ascend-910b (memory only; no CUDA checks). --gpu-mem <GiB> sets the card's total
303
+ as torch reports it (the figure vLLM multiplies by --gpu-memory-utilization),
304
+ on top of --gpu or alone for a card not in the table. --gpu-mem-used <GiB> is
305
+ memory other processes already hold on each GPU. vLLM's --kv-cache-memory-bytes
306
+ is read from the launch command. When the repo publishes
307
+ model.safetensors.index.json, the weights derived from config.json are compared
308
+ with its total_size; past 10% apart the published size is used and the report
309
+ says so.
310
+
311
+ --receipt prints what vLLM measured next to the prediction: a startup plan
312
+ (VLLM_ENABLE_STARTUP_PLAN=1 writes {VLLM_CACHE_ROOT}/startup_plan/startup_plan_<fp>.json,
313
+ vLLM >= 0.26; give a file or the directory, ranks are read together) or a startup
314
+ log. A plan vLLM itself would ignore (wrong schema, a fingerprint that does not
315
+ match its name, a non-positive size, a baseline above this card's memory) is
316
+ named and not quoted. A log's vLLM version is used when --vllm-version is not given.
274
317
  `);
275
318
  process.exit(S.help ? 0 : 2);
276
319
  }
@@ -288,8 +331,12 @@ blocks.
288
331
  process.stderr.write(`${red('no model')}: give the Hugging Face id (or graph.json) before the flags${parsed.engine === 'llamacpp' ? '; a .gguf file carries no config.json, so name the repo it was converted from' : ''}\n`);
289
332
  process.exit(2);
290
333
  }
291
- if (S.gpu != null && !resolveLayoutGpu(S.gpu)) {
292
- process.stderr.write(`${red('unknown --gpu')} ${S.gpu}: give a card id or an unambiguous prefix (h100, h200, b200, a100-80g, a100-40g, l40s, l4, a10g, t4, v100, ...)\n`);
334
+ const gpuMem = S['gpu-mem'] != null ? Number(S['gpu-mem']) : undefined;
335
+ const gpuMemUsed = S['gpu-mem-used'] != null ? Number(S['gpu-mem-used']) : undefined;
336
+ if (gpuMem != null && !(gpuMem > 0)) { process.stderr.write(`${red('--gpu-mem')} must be a positive number of GiB\n`); process.exit(2); }
337
+ if (gpuMemUsed != null && !(gpuMemUsed >= 0)) { process.stderr.write(`${red('--gpu-mem-used')} must be a number of GiB, 0 or more\n`); process.exit(2); }
338
+ if (S.gpu != null && !resolveServeGpu(S.gpu)) {
339
+ process.stderr.write(`${red('unknown --gpu')} ${S.gpu}: give a card id or an unambiguous prefix (h100, h200, b200, a100-80g, a100-40g, a40, gh200-96g, gh200-144g, rtx-pro-6000, ascend-910b, l40s, l4, ...), or --gpu-mem <GiB> for any other card\n`);
293
340
  process.exit(2);
294
341
  }
295
342
  const gpus = S.gpus != null ? Number(S.gpus) : undefined;
@@ -300,20 +347,42 @@ blocks.
300
347
  for (const part of String(S.sampler).split(',')) { const [k, v] = part.split('='); if (k && v != null) o[k.trim()] = v.trim(); }
301
348
  sampler = readSampler(o);
302
349
  }
303
- const r = await serveCheckHFModel(ref, { engine: parsed.engine, args: parsed.args, gpu: S.gpu, gpus, sampler, against: S.against });
350
+ let receiptInputs = null;
351
+ if (S.receipt) {
352
+ const fs = await import('node:fs');
353
+ const path = await import('node:path');
354
+ if (parsed.engine !== 'vllm') { process.stderr.write(`${red('--receipt')} reads vLLM startup plans and logs; this launch is ${parsed.engine}\n`); process.exit(2); }
355
+ let files;
356
+ try {
357
+ files = fs.statSync(S.receipt).isDirectory()
358
+ ? fs.readdirSync(S.receipt).filter((f) => /^startup_plan_.*\.json$/.test(f)).sort().map((f) => path.join(S.receipt, f))
359
+ : [S.receipt];
360
+ } catch (e) { process.stderr.write(`${red('cannot read --receipt')} ${S.receipt}: ${e.message}\n`); process.exit(2); }
361
+ if (!files.length) { process.stderr.write(`${red('--receipt')} ${S.receipt}: no startup_plan_*.json in the directory\n`); process.exit(2); }
362
+ receiptInputs = files.map((f) => readReceiptInput(fs.readFileSync(f, 'utf8'), f));
363
+ }
364
+ const logVersion = receiptInputs?.find((x) => x.kind === 'startup-log' && x.vllmVersion)?.vllmVersion;
365
+ const engineVersion = parsed.engine === 'vllm' ? (S['vllm-version'] ?? logVersion?.replace(/^(\d+\.\d+\.\d+).*$/, '$1')) : parsed.engine === 'sglang' ? S['sglang-version'] : undefined;
366
+ const r = await serveCheckHFModel(ref, { engine: parsed.engine, args: parsed.args, gpu: S.gpu, gpus, sampler, against: S.against, engineVersion, gpuMemGiB: gpuMem, gpuMemUsedGiB: gpuMemUsed });
304
367
  if (r.error) { process.stderr.write(`${red('cannot read')} ${ref}: ${r.error}\n`); process.exit(2); }
368
+ let receipt = null;
369
+ if (receiptInputs) {
370
+ const pred = predictionFromReport(r.report);
371
+ receipt = pred ? buildReceipt(receiptInputs, pred) : { source: S.receipt, rows: [], notes: ['no prediction to compare against: the memory check needs --gpu and a config with layer geometry'], compared: false };
372
+ }
305
373
  const blocked = r.report.findings.some((f) => f.severity === 'block');
306
374
  if (S.json) {
307
- process.stdout.write(JSON.stringify({ model: ref, command: Array.isArray(cmd) ? cmd.join(' ') : cmd, ignoredFlags: parsed.ignored, ...r.report }, null, 2) + '\n');
375
+ process.stdout.write(JSON.stringify({ model: ref, command: Array.isArray(cmd) ? cmd.join(' ') : cmd, ignoredFlags: parsed.ignored, ...r.report, ...(receipt ? { receipt } : {}) }, null, 2) + '\n');
308
376
  } else {
309
377
  let text = renderServeText(r.report, r.name)
310
378
  .replace(/^ {2}block (.*)$/gm, (_, t) => ` ${red('block')} ${bold(t)}`)
311
379
  .replace(/^ {2}warn {2}(.*)$/gm, (_, t) => ` ${yellow('warn ')} ${t}`)
312
380
  .replace(/^ {2}info {2}(.*)$/gm, (_, t) => ` ${dim('info ')} ${t}`);
313
381
  if (parsed.ignored.length) text += ` ${dim(`flags not read by this check: ${parsed.ignored.join(' ')}`)}\n\n`;
382
+ if (receipt) text += renderReceiptText(receipt);
314
383
  process.stdout.write(text);
315
384
  }
316
- process.exit(blocked ? 1 : 0);
385
+ process.exit(await finish({ command: 'serve-check', model: ref, serve: r.report, engine: parsed.engine, gpu: S.gpu, json: S.json }, blocked ? 1 : 0));
317
386
  }
318
387
 
319
388
  // ── rightsize: requested vs needed over a team's past jobs ──────────────────
@@ -404,6 +473,11 @@ if (flags.has('-h') || flags.has('--help') || positional.length === 0) {
404
473
  why a job ran out of GPU memory, and the least invasive fix
405
474
  npx neurarch serve-check <model-id> --gpu l4 --gpus 4 -- vllm serve <model-id> -tp 4 --max-model-len 32768
406
475
  will this vLLM / SGLang / llama.cpp launch start and hold what it promises (--help)
476
+ npx neurarch policy --help the repo's .neurarch.yml: severities, budget lines, waivers, baseline, --sarif
477
+ npx neurarch weights-diff <a> <b> Which tensors differ between two local checkpoints, and the shape of each edit
478
+ npx neurarch scan [paths] every model your code pulls: unpinned or changed remote code, pickle weights, upstream changes since your pin
479
+ npx neurarch pin-check [paths] Hugging Face downloads not pinned to a commit (Bandit B615), --sarif
480
+ npx neurarch template-check <id> the prompt vLLM or SGLang sends against the reference; --from <rev> for an upstream change
407
481
 
408
482
  npx neurarch <model-id> e.g. Qwen/Qwen3-8B, bert-base-uncased
409
483
  npx neurarch <model-id> --json machine-readable
@@ -420,6 +494,7 @@ if (flags.has('-h') || flags.has('--help') || positional.length === 0) {
420
494
  tokens, and which cards hold it (default batch ${DEFAULT_INFERENCE_BATCH}, ${DEFAULT_GEN_TOKENS} generated, bf16)
421
495
  npx neurarch <model-id> --lora r=16,targets=q_proj,v_proj --quant int8 --fit a100-40g
422
496
  the change record: what may move on this base, and whether the gate approves it
497
+ (memory sized at batch 32 and ${DEFAULT_SEQ_LEN} tokens unless --batch / --seq-len say otherwise)
423
498
  npx neurarch <model-id> --lora-targets every Linear a LoRA can target, and PEFT target_modules
424
499
  for the attention and all-linear presets with r=8 / r=16 totals
425
500
  npx neurarch <model-id> --seq-len 1024 --tokenizer-size 30524 --classes 5 [--image-size 384 --channels 1]
@@ -573,7 +648,8 @@ if (flags.has('--json')) {
573
648
  }
574
649
  : { ok: false, modelId, reason: result.reason };
575
650
  process.stdout.write(JSON.stringify(payload, null, 2) + '\n');
576
- process.exit(payload.ok && !(payload.dataFit?.findings ?? []).some((f) => f.severity === 'block') ? 0 : 1);
651
+ const code = payload.ok && !(payload.dataFit?.findings ?? []).some((f) => f.severity === 'block') ? 0 : 1;
652
+ process.exit(!payload.ok ? code : await finish({ command: 'check', model: modelId, json: true, lint: payload.findings, dataFit: payload.dataFit, cost: payload.cost, inference: payload.inference, change: payload.change, params: payload.derivedParams, gpu: opts.gpu, dataGiven: opts.data != null }, code));
577
653
  }
578
654
 
579
655
  if (!result.ok && !sizingOnly) {
@@ -585,6 +661,8 @@ const hub = result.hub;
585
661
  const facts = result.ok ? result.facts : result.sizing;
586
662
  /** Blocking findings; the exit code reads it. Empty when only sizing ran. */
587
663
  const blockers = result.ok ? facts.findings.filter((f) => f.severity === 'block') : [];
664
+ /** What the policy layer reads at exit; each block below adds its report. */
665
+ const policyRun = { command: 'check', model: modelId, gpu: opts.gpu, dataGiven: opts.data != null, lint: result.ok ? facts.findings : undefined, params: result.ok ? facts.derivedParams : undefined };
588
666
 
589
667
  process.stdout.write(`\n${bold(hub.modelId)} ${dim(`${hub.modelType}${hub.pipelineTag ? ` · ${hub.pipelineTag}` : ''}`)}\n\n`);
590
668
 
@@ -656,6 +734,7 @@ if (sizingOnly) {
656
734
  // does not get far enough for its peak to matter.
657
735
  if (dataAsked) {
658
736
  const fit = dataFitHFModel(facts, dataSpec);
737
+ policyRun.dataFit = fit;
659
738
  const blocks = fit.findings.filter((f) => f.severity === 'block');
660
739
  process.stdout.write(`\n ${bold('data fit')} ${dim(`checked: ${fit.checked.join(', ') || 'nothing'}`)}\n`);
661
740
  if (!fit.findings.length && fit.checked.length) process.stdout.write(` ${green('fits')} ${dim('every stated field is within what the config accepts')}\n`);
@@ -675,6 +754,7 @@ if (dataAsked) {
675
754
  // and the lines below say what that leaves out.
676
755
  if (inference) {
677
756
  const ip = inferHFModel(facts, inferOpts);
757
+ policyRun.inference = ip;
678
758
  if (!ip) {
679
759
  process.stderr.write(`\n ${red('cannot size')} inference for ${modelId}: no weights read from the config\n`);
680
760
  process.exit(1);
@@ -726,6 +806,7 @@ if (trainingSizing) {
726
806
  }
727
807
  const { plan } = priceHFModel(facts, samples != null ? { samples, source: String(opts.data) } : undefined, runFrom(run), undefined, attention, seqLen);
728
808
  const cost = plan.cost;
809
+ policyRun.cost = cost;
729
810
  if (samples != null) {
730
811
  const hrs = cost.estTrainSec != null ? cost.estTrainSec / 3600 : null;
731
812
  const money = cost.estCostUsd == null ? 'n/a'
@@ -791,6 +872,7 @@ if (spec) {
791
872
  const run = gpuFromFlag(opts.gpu);
792
873
  const { plan } = priceHFModel(facts, { samples: samples && samples > 0 ? samples : 50_000, source: opts.data != null ? String(opts.data) : 'assumed' }, runFrom(run), spec, attention, seqLen);
793
874
  const ch = plan.change;
875
+ policyRun.change = ch;
794
876
  if (ch) {
795
877
  const gateOk = ch.gate.ok;
796
878
  process.stdout.write(`\n ${bold('change record')} ${dim(`spec ${ch.specId} on ${ch.baseFingerprint}`)}\n`);
@@ -802,6 +884,11 @@ if (spec) {
802
884
  process.stdout.write(` ${dim('allowed to move')} ${desc.join(' · ')}\n`);
803
885
  const e = ch.estimates;
804
886
  if (e.trainMemGb != null) process.stdout.write(` ${dim('train memory ')} ${(e.trainMemGb * CHANGE_HEADROOM).toFixed(1)} GB ${dim(ch.spec.adapter ? `(peak ${e.trainMemGb.toFixed(1)} GB, ${humanParams(e.trainableParams)} trainable, ${CHANGE_HEADROOM}x headroom)` : `(peak ${e.trainMemGb.toFixed(1)} GB, full weights, ${CHANGE_HEADROOM}x headroom)`)}\n`);
887
+ // The peak is only true at a workload: say which, and that it was assumed when the caller gave none.
888
+ if (e.trainMemGb != null) {
889
+ const assumed = [batchSize == null ? '--batch' : null, seqLen == null && e.seqLen != null ? '--seq-len' : null].filter(Boolean);
890
+ process.stdout.write(` ${dim('sized at ')} batch ${e.batchSize}${e.seqLen != null ? `, ${e.seqLen} tokens per sample` : ''}${assumed.length ? dim(` (assumed; ${assumed.join(', ')} to change)`) : ''}\n`);
891
+ }
805
892
  if (e.weightBytes != null) process.stdout.write(` ${dim('weights ')} ${(e.weightBytes / 1e9).toFixed(2)} GB ${dim(`at ${ch.spec.quant ? ch.spec.quant.precision : 'fp16'}`)}\n`);
806
893
  if (e.servingFits != null) process.stdout.write(` ${dim('serving ')} ${e.servingFits ? green('fits') : red('does not fit')}\n`);
807
894
  process.stdout.write(` ${dim('gate ')} ${gateOk ? green('approved') : red(`refused (${ch.gate.blockers.length} blocker${ch.gate.blockers.length === 1 ? '' : 's'})`)}\n`);
@@ -841,4 +928,4 @@ process.stdout.write('\n');
841
928
  if (publishedPage) process.stdout.write(` ${dim(`page ${publishedPage}`)}\n`);
842
929
  process.stdout.write(` ${dim(`compare https://neurarch.com/compare?a=${encodeURIComponent(modelId)}&b=&utm_source=${SOURCE}`)}\n`);
843
930
  process.stdout.write(` ${dim('check POST https://www.neurarch.com/api/v1/check')}\n\n`);
844
- process.exit(blockers.length ? 1 : 0);
931
+ process.exit(await finish(policyRun, blockers.length ? 1 : 0));
@@ -0,0 +1,138 @@
1
+ /**
2
+ * `neurarch pin-check [paths...]`: Hugging Face downloads not pinned to a
3
+ * commit, in .py, .ipynb, YAML, shell scripts and Dockerfiles. Aligned with
4
+ * Bandit B615. The scanning is src/utils/policy/pinCheck.ts (through
5
+ * policy.bundle.mjs); this file walks the tree, optionally asks the Hub for
6
+ * the current commit (`--resolve`, off by default: no network unless asked),
7
+ * prints, and hands the findings to the policy layer for `.neurarch.yml`
8
+ * severities, waivers, the baseline and `--sarif`.
9
+ */
10
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
11
+ import { join, relative, resolve, sep } from 'node:path';
12
+
13
+ const SKIP_DIRS = new Set(['.git', '.hg', '.svn', 'node_modules', '.venv', 'venv', 'env', '__pycache__', '.tox', '.nox', '.mypy_cache', '.pytest_cache', '.ruff_cache', 'site-packages', '.ipynb_checkpoints']);
14
+ const MAX_BYTES = 5 * 1024 * 1024;
15
+
16
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
17
+ const c = (code, s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
18
+ const posix = (p) => p.split(sep).join('/');
19
+
20
+ function* walk(abs, kindOf) {
21
+ let st;
22
+ try { st = statSync(abs); } catch { return; }
23
+ if (st.isFile()) { if (kindOf(abs) && st.size <= MAX_BYTES) yield abs; return; }
24
+ if (!st.isDirectory()) return;
25
+ let entries;
26
+ try { entries = readdirSync(abs, { withFileTypes: true }); } catch { return; }
27
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
28
+ if (e.isDirectory() && SKIP_DIRS.has(e.name)) continue;
29
+ if (e.isSymbolicLink()) continue;
30
+ yield* walk(join(abs, e.name), kindOf);
31
+ }
32
+ }
33
+
34
+ /** The commit `main` points at now, or null. Only called with --resolve. */
35
+ async function headSha(repoType, id) {
36
+ const url = `https://huggingface.co/api/${repoType === 'dataset' ? 'datasets' : 'models'}/${id}/revision/main`;
37
+ const headers = process.env.HF_TOKEN ? { Authorization: `Bearer ${process.env.HF_TOKEN}` } : {};
38
+ try {
39
+ const r = await fetch(url, { headers, signal: AbortSignal.timeout(10_000) });
40
+ if (!r.ok) return null;
41
+ const j = await r.json();
42
+ return typeof j.sha === 'string' && /^[0-9a-f]{40}$/.test(j.sha) ? j.sha : null;
43
+ } catch { return null; }
44
+ }
45
+
46
+ const HELP = `neurarch pin-check: Hugging Face downloads that are not pinned to a commit
47
+
48
+ npx neurarch pin-check [paths...] [--resolve] [--json] [--sarif out.sarif] [--policy .neurarch.yml]
49
+
50
+ Reads .py, .ipynb, YAML, shell scripts and Dockerfiles (default: the current
51
+ directory) for from_pretrained / load_dataset / hf_hub_download /
52
+ snapshot_download / pipeline(model=...), vllm serve, the vLLM and SGLang server
53
+ modules, huggingface-cli / hf download, and YAML model keys (base_model,
54
+ model_name_or_path, ...) with no revision, or with a branch or tag as the
55
+ revision. Aligned with Bandit B615; # nosec and # nosec B615 are honoured.
56
+
57
+ pin/hf-unpinned NX-PIN-001 warn a repo id and no revision
58
+ pin/hf-floating-revision NX-PIN-002 warn revision is main, a tag or a PR ref
59
+ pin/hf-unpinned-dynamic NX-PIN-003 info the repo id is a variable and there is no revision
60
+
61
+ --resolve asks the Hub API for the commit main points at now and puts that sha
62
+ in the fix (network; HF_TOKEN is sent for gated repos). Off by default.
63
+
64
+ Severity per rule in .neurarch.yml, e.g. rules: { pin/hf-unpinned: block }
65
+ Once pinned, extend https://www.neurarch.com/changes-feeds/renovate/preset.json
66
+ in renovate.json and Renovate opens a PR when a tracked model moves.
67
+ `;
68
+
69
+ export async function pinCheckCommand(args, pol, policyFinish) {
70
+ const L = await import('../policy.bundle.mjs');
71
+ const o = { paths: [] };
72
+ for (const a of args) {
73
+ if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0; }
74
+ if (a === '--json') o.json = true;
75
+ else if (a === '--resolve') o.resolve = true;
76
+ else if (a.startsWith('-')) { process.stderr.write(`neurarch pin-check: unknown flag ${a} (--help)\n`); return 2; }
77
+ else o.paths.push(a);
78
+ }
79
+ if (!o.paths.length) o.paths.push('.');
80
+ const root = pol?.root ?? process.cwd();
81
+ const kindOf = (p) => L.pinFileKind(posix(p));
82
+
83
+ const hits = [];
84
+ const sources = [];
85
+ let files = 0;
86
+ for (const p of o.paths) {
87
+ const abs = resolve(p);
88
+ try { statSync(abs); } catch { process.stderr.write(`neurarch pin-check: ${p}: no such file or directory\n`); return 2; }
89
+ for (const f of walk(abs, kindOf)) {
90
+ let text;
91
+ try { text = readFileSync(f, 'utf8'); } catch { continue; }
92
+ files++;
93
+ const rel = posix(relative(root, f)) || posix(f);
94
+ const found = L.scanPins(rel, text);
95
+ hits.push(...found);
96
+ sources.push({ path: rel, text });
97
+ }
98
+ }
99
+
100
+ const shas = {};
101
+ let resolvedOn;
102
+ if (o.resolve) {
103
+ resolvedOn = new Date().toISOString().slice(0, 10);
104
+ const ids = [...new Set(hits.filter((h) => h.repo).map((h) => `${h.repoType}:${h.repo}`))];
105
+ await Promise.all(ids.map(async (k) => {
106
+ const [type, ...rest] = k.split(':');
107
+ const sha = await headSha(type, rest.join(':'));
108
+ if (sha) shas[k] = sha;
109
+ }));
110
+ }
111
+ const findings = L.fromPinCheck(hits, { shas, resolvedOn });
112
+ const code = findings.some((f) => f.severity === 'block') ? 1 : 0;
113
+
114
+ const out = o.json ? process.stderr : process.stdout;
115
+ if (o.json) {
116
+ process.stdout.write(JSON.stringify({ files, hits, findings, resolved: o.resolve ? shas : undefined }, null, 2) + '\n');
117
+ } else {
118
+ const counted = findings.filter((f) => f.severity !== 'info').length;
119
+ out.write(`\n ${c('1', 'pin-check')} ${files} file${files === 1 ? '' : 's'} read, ${counted} download${counted === 1 ? '' : 's'} not pinned to a commit${findings.length > counted ? `, ${findings.length - counted} with the repo id in a variable` : ''}\n\n`);
120
+ for (const f of findings) {
121
+ const lvl = f.severity === 'info' ? c('2', 'info') : c('33', 'warn');
122
+ out.write(` ${lvl} ${f.path}:${f.line} ${f.title} ${c('2', `[${f.rule}]`)}\n`);
123
+ out.write(` ${c('2', `fix: ${f.fix.split(' Then extend ')[0]}`)}\n`);
124
+ }
125
+ if (hits.some((h) => h.repoType === 'model' && h.rule !== 'pin/hf-unpinned-dynamic')) {
126
+ out.write(`\n Once pinned, extend ${L.RENOVATE_PRESET_URL} in renovate.json:\n Renovate opens one PR per model when a tracked model's main moves, linking what changed (${L.CHANGE_FEEDS_URL}).\n`);
127
+ }
128
+ if (!findings.length) out.write(` every Hugging Face download found is pinned to a commit (or none was found)\n`);
129
+ if (o.resolve) {
130
+ const want = new Set(hits.filter((h) => h.repo).map((h) => `${h.repoType}:${h.repo}`)).size;
131
+ out.write(`\n ${c('2', `--resolve: read ${Object.keys(shas).length} of ${want} current commits from the Hub on ${resolvedOn}`)}\n`);
132
+ }
133
+ out.write('\n');
134
+ }
135
+
136
+ const scopes = sources.map((s) => ({ checker: 'pin', path: s.path }));
137
+ return policyFinish(pol, { command: 'pin-check', json: o.json, findings, sources, scopes }, code);
138
+ }