neurastream 0.2.44 → 0.2.45

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/README.md CHANGED
@@ -29,6 +29,7 @@ flowchart LR
29
29
  | Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs `ledger.max_running_per_provider` (default 2), when a run is `OVER-BUDGET` (unless `--incident <id>`), or when a priority plan has no running agent (unless `--priority`). |
30
30
  | Scoring (`agent-score`) | Points only for work Main accepted by commit, times the phase difficulty. Ranked per dollar and per hour. |
31
31
  | Brief lint (`brief-lint`) | Refuses a helper brief that misses a required rule (acceptance, stop condition, no push, call budget). |
32
+ | Write-time checks (`write_check`) | With `write_check.enabled` on, a subagent's write or edit to a file a configured linter covers is linted before and after the call. If the call adds a lint finding or a suppression comment (`noqa` and similar), the file is put back and the call returns an error. Main is left alone unless `applies_to: all`. Off by default. |
32
33
  | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
33
34
  | Unlanded work (`wip-check`, `wip-snapshot`, `wip-backup`) | Lists branches on no remote and dirty worktrees; snapshots them as hidden commits; can push them to a backup repo. |
34
35
  | Session rollover | When the main session file passes 5 MB, or the installed neurastream version differs from the running plugin, Main writes a handoff note; a fresh session then starts on its own under `neurastream main`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.44",
3
+ "version": "0.2.45",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -17,12 +17,13 @@
17
17
 
18
18
  import { execFileSync, spawn } from "node:child_process";
19
19
  import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
- import { basename, dirname, join, resolve } from "node:path";
20
+ import { basename, dirname, extname, join, resolve } from "node:path";
21
21
  import type { Decision } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
23
23
  import { chatGo, chatTier, type Tier } from "../../core/autonomy.ts";
24
24
  import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
25
25
  import { loadConfig, type Config } from "../../core/config.ts";
26
+ import { checkWrite, type WriteCheckConfig } from "../../core/write-check.ts";
26
27
  import { nowSec, strftime } from "../../core/clock.ts";
27
28
  import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
28
29
  import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, revertMainEdit, rekeySpawnFile } from "../../core/guards.ts";
@@ -249,6 +250,22 @@ function ledgerText(cfg: Config): string {
249
250
  }
250
251
  }
251
252
 
253
+ // Write-time checks (plan 20261028_1228): the text of each file a call names that a configured linter
254
+ // covers, read before the call runs; null when the file does not exist yet.
255
+ function writeCheckSnapshot(tool: string, input: Record<string, unknown>, cwd: string, wc: WriteCheckConfig): Map<string, string | null> {
256
+ const exts = wc.linters.flatMap((l) => l.ext);
257
+ const snap = new Map<string, string | null>();
258
+ for (const file of q.writeTargets(tool, input, cwd)) {
259
+ if (!exts.includes(extname(file))) continue;
260
+ try {
261
+ snap.set(file, readFileSync(file, "utf8"));
262
+ } catch (err) {
263
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") snap.set(file, null);
264
+ }
265
+ }
266
+ return snap;
267
+ }
268
+
252
269
  // Plan files a subagent write/edit may touch: snapshot before the call so tool_result can verify
253
270
  // and restore (the original snapshotted inside checkCall; core returns pure decisions now).
254
271
  function snapshotPlans(tool: string, input: Record<string, unknown>, cwd: string, snap: Map<string, string>, main: boolean): void {
@@ -561,6 +578,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
561
578
  let inboxTimer: unknown;
562
579
  const calls = new Map<string, number>(); // subagent call budget, by agent id
563
580
  const pending = new Map<string, Map<string, string>>(); // toolCallId -> plan snapshots
581
+ const pendingWrite = new Map<string, Map<string, string | null>>(); // toolCallId -> write-check snapshots; null: the file did not exist
564
582
  const pendingRules = new Set<string>(); // repos Main worked in, rules to hand over at the next prompt
565
583
  // Chat notify (plans 20261024_2155, 20261025_0130): the text a hand-back already posted
566
584
  // (attempted) — one post per distinct text, never a retry loop. The reply itself comes from
@@ -862,6 +880,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
862
880
  return { block: true, reason: d.reason };
863
881
  }
864
882
  if (snap.size) pending.set(asString(e.toolCallId), snap);
883
+ const wc = cfg.write_check;
884
+ if (wc.enabled && (wc.applies_to === "all" || isSub)) {
885
+ const ws = writeCheckSnapshot(tool, input, cwd, wc);
886
+ if (ws.size) pendingWrite.set(asString(e.toolCallId), ws);
887
+ }
865
888
  // An allowed Main call inside a repo queues that repo's rules for the next prompt (P3).
866
889
  if (!isSub) for (const repo of touchedRepos(tool, input, cwd)) pendingRules.add(repo);
867
890
  // The originals return nothing on a clean call; only warn injects carry an object.
@@ -883,6 +906,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
883
906
  const c = asCtx(ctx);
884
907
  const id = asString(e.toolCallId);
885
908
  const snap = pending.get(id);
909
+ const wsnap = pendingWrite.get(id);
910
+ pendingWrite.delete(id);
886
911
  // Redact first: everything below (plan checks, detectors, the returned content, the model,
887
912
  // the chat and the session log) then works on text that holds markers, never values.
888
913
  const redacted = redactToolResult(Array.isArray(e.content) ? e.content : [], cfg);
@@ -927,6 +952,28 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
927
952
  if (d.allow && c.kind === "sub") subActionDetectors(cfg, ctx, file, before, after);
928
953
  }
929
954
  }
955
+ // Write-time checks (plan 20261028_1228): a lint finding the call added is undone here, file by file.
956
+ if (wsnap && !e.isError) {
957
+ const refusals: string[] = [];
958
+ for (const [file, before] of wsnap) {
959
+ let after: string | null = null;
960
+ try {
961
+ after = readFileSync(file, "utf8");
962
+ } catch {}
963
+ const r = checkWrite(file, before, after, cfg.write_check);
964
+ if (r.allow) {
965
+ if (r.note) adapterLog(cfg, r.note);
966
+ continue;
967
+ }
968
+ try {
969
+ if (before === null) rmSync(file, { force: true });
970
+ else writeFileSync(file, before);
971
+ } catch {}
972
+ adapterLog(cfg, `WRITE-CHECK refused ${file}`);
973
+ refusals.push(r.reason);
974
+ }
975
+ if (refusals.length > 0) return { isError: true, content: [{ type: "text", text: refusals.join("\n\n") }] };
976
+ }
930
977
  if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash" && !e.isError) {
931
978
  if (PUSH_MERGE.test(asString(asRecord(e.input).command))) autoClose(cfg);
932
979
  }
@@ -5,6 +5,7 @@ import { existsSync, readFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
+ import type { WriteCheckConfig } from "./write-check.ts";
8
9
 
9
10
  const HERE = dirname(fileURLToPath(import.meta.url));
10
11
  export const TEMPLATE_PATH = join(HERE, "../../templates/config.yml");
@@ -205,6 +206,8 @@ export interface Config {
205
206
  /** A second net on the wire: wrap the harness in `secretgate wrap --` at launch. */
206
207
  proxy: "none" | "secretgate";
207
208
  };
209
+ /** Write-time lint checks (src/core/write-check.ts, plan 20261028_1228): an edit that adds a lint finding or a suppression comment is refused. */
210
+ write_check: WriteCheckConfig;
208
211
  priority: { sleep_sec: number };
209
212
  alerts: { temp_c: number; mem_psi: number; io_psi: number; cooldown_sec: number };
210
213
  snapshot: { tmp_dest: string; git_repo: string; git_backup: string; excludes: string[] };
@@ -440,6 +443,29 @@ function check(cfg: Config): void {
440
443
  if (typeof cfg.guards.plan_offer !== "string" || cfg.guards.plan_offer === "") {
441
444
  throw new ConfigError("guards.plan_offer must be a non-empty regex string");
442
445
  }
446
+ const wc = cfg.write_check;
447
+ if (wc.applies_to !== "sub" && wc.applies_to !== "all") throw new ConfigError('write_check.applies_to must be "sub" or "all"');
448
+ if (!(wc.timeout_ms > 0)) throw new ConfigError("write_check.timeout_ms must be > 0");
449
+ if (!Array.isArray(wc.linters)) throw new ConfigError("write_check.linters must be a list");
450
+ const regexes: [string, unknown][] = [["write_check.suppress", wc.suppress]];
451
+ for (const [i, l] of wc.linters.entries()) {
452
+ const at = `write_check.linters[${i}]`;
453
+ if (!Array.isArray(l.ext) || l.ext.some((e) => typeof e !== "string" || !e.startsWith(".")))
454
+ throw new ConfigError(`${at}.ext must be a list of extensions starting with "."`);
455
+ if (!Array.isArray(l.argv) || l.argv.length === 0 || !l.argv.every((a) => typeof a === "string") || !l.argv.includes("{file}"))
456
+ throw new ConfigError(`${at}.argv must be a non-empty list of strings containing "{file}"`);
457
+ if (typeof l.pattern !== "string" || !l.pattern.includes("(?<rule>"))
458
+ throw new ConfigError(`${at}.pattern must be a regex with a named group rule`);
459
+ regexes.push([`${at}.pattern`, l.pattern]);
460
+ }
461
+ for (const [key, src] of regexes) {
462
+ if (typeof src !== "string" || src === "") throw new ConfigError(`${key} must be a non-empty regex`);
463
+ try {
464
+ new RegExp(src);
465
+ } catch {
466
+ throw new ConfigError(`${key} must be a valid regex`);
467
+ }
468
+ }
443
469
  try {
444
470
  new RegExp(cfg.guards.plan_offer, "i");
445
471
  } catch {
@@ -0,0 +1,112 @@
1
+ // Write-time lint checks: an edit that adds a lint finding or a suppression comment to a file is
2
+ // refused, and the caller puts the file back. Linters run as argv arrays, never through a shell.
3
+ // `after` is what is on disk now; `before` is what the file held before the edit (null: new file).
4
+
5
+ import { spawnSync } from "node:child_process";
6
+ import { randomBytes } from "node:crypto";
7
+ import { rmSync, writeFileSync } from "node:fs";
8
+ import { basename, dirname, extname, join } from "node:path";
9
+
10
+ export interface WriteCheckLinter {
11
+ ext: string[];
12
+ argv: string[];
13
+ pattern: string;
14
+ }
15
+
16
+ export interface WriteCheckConfig {
17
+ enabled: boolean;
18
+ applies_to: "sub" | "all";
19
+ timeout_ms: number;
20
+ suppress: string;
21
+ linters: WriteCheckLinter[];
22
+ }
23
+
24
+ export type WriteCheckResult = { allow: true; note?: string } | { allow: false; reason: string };
25
+
26
+ // Counts per rule key; suppression comments count under SUPPRESSION.
27
+ interface Findings {
28
+ counts: Map<string, number>;
29
+ samples: Map<string, string>;
30
+ }
31
+
32
+ const SUPPRESSION = "suppression";
33
+ const REASON_MAX = 2000;
34
+ const SAMPLE_MAX = 300;
35
+ const TAIL = "The file was restored to its state before this edit; fix it and edit again — do not add suppression comments.";
36
+
37
+ function add(f: Findings, key: string, sample: string): void {
38
+ f.counts.set(key, (f.counts.get(key) ?? 0) + 1);
39
+ if (!f.samples.has(key)) f.samples.set(key, sample.trim().slice(0, SAMPLE_MAX));
40
+ }
41
+
42
+ // Runs each linter on `path` and counts its findings. Throws when a linter did not finish
43
+ // (missing binary, timeout, signal); the caller turns that into an allowed edit with a note.
44
+ function lint(path: string, linters: WriteCheckLinter[], wc: WriteCheckConfig, f: Findings): void {
45
+ for (const l of linters) {
46
+ const argv = l.argv.map((a) => (a === "{file}" ? path : a));
47
+ const [cmd = "", ...args] = argv;
48
+ const r = spawnSync(cmd, args, {
49
+ cwd: dirname(path),
50
+ encoding: "utf8",
51
+ timeout: wc.timeout_ms,
52
+ maxBuffer: 16 * 1024 * 1024,
53
+ });
54
+ if (r.error || r.signal) throw new Error(`${cmd} did not finish (${r.error?.message ?? r.signal})`);
55
+ const re = new RegExp(l.pattern);
56
+ for (const line of r.stdout.split("\n")) {
57
+ const rule = re.exec(line)?.groups?.rule;
58
+ if (rule) add(f, rule, line);
59
+ }
60
+ }
61
+ }
62
+
63
+ // Lints `text` as if it were `file`: written to a scratch file beside it (same extension, so the
64
+ // repo's own lint config applies) and removed afterwards.
65
+ function lintText(file: string, text: string, linters: WriteCheckLinter[], wc: WriteCheckConfig, f: Findings): void {
66
+ const ext = extname(file);
67
+ const scratch = join(dirname(file), `.${basename(file, ext)}.wc-${randomBytes(4).toString("hex")}${ext}`);
68
+ writeFileSync(scratch, text);
69
+ try {
70
+ lint(scratch, linters, wc, f);
71
+ } finally {
72
+ rmSync(scratch, { force: true });
73
+ }
74
+ }
75
+
76
+ function suppressions(text: string, re: RegExp, f: Findings): void {
77
+ for (const line of text.split("\n")) if (re.test(line)) add(f, SUPPRESSION, line);
78
+ }
79
+
80
+ function refusal(file: string, now: Findings, old: Findings): string {
81
+ const head = `write-check: this edit adds lint problems to ${file}:`;
82
+ const rows = [...now.counts].flatMap(([key, n]) => {
83
+ const delta = n - (old.counts.get(key) ?? 0);
84
+ return delta > 0 ? [`- ${key} (+${delta}): ${now.samples.get(key)}`] : [];
85
+ });
86
+ const room = REASON_MAX - head.length - TAIL.length - 2;
87
+ let body = rows.join("\n");
88
+ if (body.length > room) body = `${body.slice(0, room - 4)}\n...`;
89
+ return `${head}\n${body}\n${TAIL}`;
90
+ }
91
+
92
+ export function checkWrite(file: string, before: string | null, after: string | null, wc: WriteCheckConfig): WriteCheckResult {
93
+ if (after === null || before === after) return { allow: true };
94
+ const linters = wc.linters.filter((l) => l.ext.includes(extname(file)));
95
+ if (linters.length === 0) return { allow: true };
96
+ const old: Findings = { counts: new Map(), samples: new Map() };
97
+ const now: Findings = { counts: new Map(), samples: new Map() };
98
+ try {
99
+ const re = new RegExp(wc.suppress);
100
+ if (before !== null) {
101
+ suppressions(before, re, old);
102
+ lintText(file, before, linters, wc, old);
103
+ }
104
+ suppressions(after, re, now);
105
+ lint(file, linters, wc, now);
106
+ } catch (err) {
107
+ return { allow: true, note: `write-check: ${file} not checked (${(err as Error).message}); the edit was allowed` };
108
+ }
109
+ const grew = [...now.counts].some(([key, n]) => n > (old.counts.get(key) ?? 0));
110
+ if (!grew) return { allow: true };
111
+ return { allow: false, reason: refusal(file, now, old) };
112
+ }
@@ -210,6 +210,19 @@ secrets: # content redaction (src/core/secret-redact.ts); a
210
210
  extra_patterns: [] # your own shapes, e.g. [{type: "my-token", regex: "myapp_[A-Za-z0-9]{32}"}]
211
211
  proxy: "none" # "none" | "secretgate": launch the harness as `secretgate wrap -- omp` (README: Secrets)
212
212
 
213
+ write_check: # write-time lint checks (src/core/write-check.ts): an edit that adds a lint finding or suppression comment is undone and the agent is told why
214
+ enabled: false # on = check every edit; off in the shipped template
215
+ applies_to: sub # "sub" = subagents only; "all" = Main too
216
+ timeout_ms: 5000 # per linter run; a timeout, crash or missing linter allows the edit and logs a note
217
+ suppress: 'noqa|type:\s*ignore|oxlint-disable|eslint-disable|biome-ignore|@ts-ignore|@ts-expect-error|@ts-nocheck' # a new match counts as a new problem
218
+ linters:
219
+ - ext: [".py"]
220
+ argv: ["ruff", "check", "--no-cache", "--output-format=concise", "--select", "E,F,B,S,C90,PERF,SIM", "{file}"]
221
+ pattern: '^.+?:\d+:\d+: (?<rule>\S+) '
222
+ - ext: [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]
223
+ argv: ["oxlint", "-f", "unix", "-D", "correctness", "-D", "suspicious", "-D", "perf", "{file}"]
224
+ pattern: '^.+?:\d+:\d+: .*\[(?:Error|Warning)/(?<rule>[^\]]+)\]'
225
+
213
226
  priority:
214
227
  sleep_sec: 120
215
228