neurastream 0.2.84 → 0.2.86

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
@@ -173,6 +173,12 @@ A "waiting on you" card or a "done" claim only counts while its own command stil
173
173
 
174
174
  One setting decides how much Main does without asking: `autonomy.tier` in the config (default `opinionated`), moved any time by the owner's whole chat message `tier strict|opinionated|full` (when `guards.chat_unlock` is on) or the tier buttons on the phone page — the setting lives in `<queue_state>/autonomy-tier`, a guard-protected path no agent can write. `strict` caps Main's project-file changes at `autonomy.strict_edit_limit` per `guards.main_window_min` minutes and refuses `git push` / `glab mr merge` / `gh pr merge` until the owner types the approve phrase from `autonomy.go_phrase` (default `go push`; a bare `go` is an ordinary message — one landing, valid `autonomy.go_minutes` minutes); `opinionated` keeps today's limits (`guards.main_edit_limit`); `full` drops the cap and lets Main skip an idle higher plan with `Priority skip: <plan> — Main: "<reason>"` (reason ≥ 4 words). No tier loosens the owner-only moves: guard-file edits without the unlock, starting the phone page, reading notify secrets, local `npm publish` and the tier setting itself.
175
175
 
176
+ ## Pressure alerts
177
+
178
+ The omp adapter samples machine pressure every `machine.pressure.sample_sec` (default 10 s) from the kernel's PSI files (`/proc/pressure/memory`, `/proc/pressure/cpu`) and `/proc/meminfo`. A RED line goes into Main's chat once the machine has been red for `red_after_sec` (default 30 s), and repeats every `repeat_sec` (default 600 s) while it stays red. The red thresholds are memory some `mem_some_red` (20 %), memory full `mem_full_red` (5 %), CPU some `cpu_some_red` (60 %), and free memory under `machine.avail_min_mb`. A GREEN line ("room again") follows once the machine has been calm for `green_after_sec` (default 120 s) after a RED. Amber sends nothing. A RED line names the heavy-run lock holder when one is held.
179
+
180
+ This is tell-only: neurastream never pauses, kills or renices a process. The level state lives in `<queue_state>/pressure.json`. `neurastream pressure` prints the current level, the sample and the line Main would read now.
181
+
176
182
  ## Owner page (`neurastream ui`)
177
183
 
178
184
  `neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.84",
3
+ "version": "0.2.86",
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",
@@ -52,6 +52,7 @@ import * as q from "../../core/queue/lib.ts";
52
52
  import { pinModel, providerOfModel, recordOut, resetEpochFromText } from "../../core/provider-state.ts";
53
53
  import { annotateResetTimes } from "../../core/reset-time.ts";
54
54
  import { tryLock, type HeldLock } from "../../core/file-lock.ts";
55
+ import { currentHolder, pressureLevel, pressureMessage, pressureTransition, readPressure, type PressureSample, type PressureState } from "../../core/pressure.ts";
55
56
  // Registers the plugin-command matcher into core's writeTargets (side effect).
56
57
  import "./package-ops.ts";
57
58
 
@@ -632,6 +633,27 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
632
633
 
633
634
  /** The most recently registered createOmpAdapter cleanup, for the exported reset(). */
634
635
  let activeAdapterReset: (() => void) | null = null;
636
+ /** Pressure alert tick (plan 20261026_0100 P2): classifies one sample, runs the transition, and tells Main on a RED or GREEN fire. The state lives in <queue_state>/pressure.json and is rewritten only when it changes, so a reloaded session does not re-fire. */
637
+ export function pressureTick(pi: ExtensionHost, cfg: Config, sample: PressureSample, now: number): void {
638
+ const file = join(cfg.paths.queue_state, "pressure.json");
639
+ let prev: PressureState | null = null;
640
+ try {
641
+ prev = JSON.parse(readFileSync(file, "utf8")) as PressureState;
642
+ } catch {}
643
+ const level = pressureLevel(sample, cfg);
644
+ const r = pressureTransition(prev, level, now, cfg);
645
+ const next = JSON.stringify(r.state);
646
+ if (next !== JSON.stringify(prev)) {
647
+ try {
648
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
649
+ writeFileSync(file, next);
650
+ } catch {}
651
+ }
652
+ if (r.fire === "red") {
653
+ pi.sendUserMessage(pressureMessage("red", sample, currentHolder(cfg, now)));
654
+ } else if (r.fire === "green") pi.sendUserMessage(pressureMessage("green", sample, null));
655
+ }
656
+
635
657
  /** This process's held Main session lock (plan 20261103_1146 P2): the first main session_start
636
658
  * locks `<queue_state>/mains/<id>/session.lock` for the process lifetime — the kernel frees it
637
659
  * when the process dies. A factory re-run must not release it (P4): dropping it lets another
@@ -928,6 +950,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
928
950
  ? c.setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS)
929
951
  : setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS);
930
952
  if (it && typeof it === "object" && "unref" in it && typeof it.unref === "function") it.unref();
953
+ // Pressure alerts (P2): sample the machine every sample_sec; tell Main only on a RED or GREEN fire.
954
+ const sample = (): void => pressureTick(pi, cfg, readPressure(), nowSec());
955
+ const sampleMs = cfg.machine.pressure.sample_sec * 1000;
956
+ const pt: unknown = c.setInterval ? c.setInterval(sample, sampleMs) : setInterval(sample, sampleMs);
957
+ if (pt && typeof pt === "object" && "unref" in pt && typeof pt.unref === "function") pt.unref();
931
958
  // Multi-main P3: every held claim heartbeats once a minute while this Main session lives,
932
959
  // so a live Main never loses a plan to queue.claim_ttl_min. session_shutdown releases
933
960
  // nothing: the TTL frees a crashed or restarted Main's claims the same way.
@@ -18,6 +18,7 @@ import { runInit } from "./init.ts";
18
18
  import { realSetupDeps, runSetup } from "./setup.ts";
19
19
  import { PORTED, runMain, runPorted } from "./commands.ts";
20
20
  import { runMetrics } from "./metrics.ts";
21
+ import { runPressure } from "./pressure.ts";
21
22
  import { runIncident } from "./incident.ts";
22
23
  import { runTraces } from "./traces.ts";
23
24
  import { runUi } from "./ui.ts";
@@ -100,6 +101,7 @@ export function helpText(): string {
100
101
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
101
102
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
102
103
  " neurastream metrics <cmd> self-metrics: report, features, releases, ci, false-alarm, rule (see README)",
104
+ " neurastream pressure machine pressure now: level, the sample, the line Main would read",
103
105
  " neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
104
106
  " neurastream labels episodes [--since 30d] [--json]",
105
107
  " join scored work, agent runs and spawn briefs",
@@ -155,6 +157,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
155
157
  if (cmd === "main") return runMain(args);
156
158
  if (cmd === "init") return runInit(args);
157
159
  if (cmd === "metrics") return runMetrics(args);
160
+ if (cmd === "pressure") return runPressure(args);
158
161
  if (cmd === "incident") return runIncident(args);
159
162
  if (cmd === "traces") return runTraces(args);
160
163
  if (cmd === "labels") return runLabels(args);
@@ -0,0 +1,29 @@
1
+ // `neurastream pressure`: prints the machine-pressure level, the sample it came from, and the
2
+ // line Main would read for that level. Read only: it never acts on a process.
3
+
4
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
5
+ import { nowSec } from "../core/clock.ts";
6
+ import { currentHolder, pressureLevel, pressureMessage, readPressure, type PressureSample } from "../core/pressure.ts";
7
+
8
+ /** The three lines the command prints. Amber has nothing to say, so it names that instead of a message. */
9
+ export function pressureReport(cfg: Config, sample: PressureSample, now: number): string {
10
+ const level = pressureLevel(sample, cfg);
11
+ let last = "none (amber: nothing to say)";
12
+ if (level === "red") last = pressureMessage("red", sample, currentHolder(cfg, now));
13
+ if (level === "green") last = pressureMessage("green", sample, null);
14
+ return [`level: ${level}`, `sample: ${JSON.stringify(sample)}`, `last message: ${last}`].join("\n");
15
+ }
16
+
17
+ export function runPressure(args: string[]): number {
18
+ if (args.length > 0) {
19
+ console.error("usage: neurastream pressure");
20
+ return 2;
21
+ }
22
+ try {
23
+ console.log(pressureReport(loadConfig(), readPressure(), nowSec()));
24
+ } catch (err) {
25
+ console.error(err instanceof ConfigError ? err.message : String(err));
26
+ return 1;
27
+ }
28
+ return 0;
29
+ }
@@ -253,6 +253,16 @@ export interface Config {
253
253
  idle_min_ticks: number;
254
254
  watch_sec: number;
255
255
  watch_streak: number;
256
+ /** Pressure alerts (src/core/pressure.ts): tell Main when the machine chokes, and when it has room again. Never acts. */
257
+ pressure: {
258
+ sample_sec: number;
259
+ mem_some_red: number;
260
+ mem_full_red: number;
261
+ cpu_some_red: number;
262
+ red_after_sec: number;
263
+ green_after_sec: number;
264
+ repeat_sec: number;
265
+ };
256
266
  };
257
267
  quota: { reset_tz: string; reset_pattern: string; label: string };
258
268
  /** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
@@ -0,0 +1,121 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { Config } from "./config.ts";
4
+
5
+ // Pressure core: reads the kernel's pressure (PSI) and memory numbers, classifies them, and decides when
6
+ // Main should hear about it. Read and report only; this file never acts on a process.
7
+
8
+ export type PressureLevel = "red" | "green" | "amber";
9
+ export interface PressureSample {
10
+ memSome: number | null;
11
+ memFull: number | null;
12
+ cpuSome: number | null;
13
+ ioFull: number | null;
14
+ availMb: number | null;
15
+ swapFreeMb: number | null;
16
+ }
17
+ export interface PressureState {
18
+ level: PressureLevel;
19
+ since: number;
20
+ lastRed: number | null;
21
+ redSent: boolean;
22
+ }
23
+
24
+ function avg10(line: string | undefined): number | null {
25
+ const m = line?.match(/avg10=([\d.]+)/);
26
+ return m ? Number(m[1]) : null;
27
+ }
28
+
29
+ /** avg10 of the `some` and `full` lines of a /proc/pressure file; unrecognised text gives nulls. */
30
+ export function parsePsi(text: string): { someAvg10: number | null; fullAvg10: number | null } {
31
+ const lines = text.split("\n");
32
+ return {
33
+ someAvg10: avg10(lines.find((l) => l.startsWith("some "))),
34
+ fullAvg10: avg10(lines.find((l) => l.startsWith("full "))),
35
+ };
36
+ }
37
+
38
+ function readText(path: string): string | null {
39
+ try {
40
+ return readFileSync(path, "utf8");
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ /** Reads the PSI files and /proc/meminfo under root. A missing file is null, never a throw. */
47
+ export function readPressure(root = "/"): PressureSample {
48
+ const psi = (name: string) => parsePsi(readText(join(root, "proc/pressure", name)) ?? "");
49
+ const mem = psi("memory");
50
+ const meminfo = readText(join(root, "proc/meminfo")) ?? "";
51
+ const kbToMb = (key: string): number | null => {
52
+ const m = meminfo.match(new RegExp(`^${key}:\\s+(\\d+) kB`, "m"));
53
+ return m ? Number(m[1]) / 1024 : null;
54
+ };
55
+ return {
56
+ memSome: mem.someAvg10,
57
+ memFull: mem.fullAvg10,
58
+ cpuSome: psi("cpu").someAvg10,
59
+ ioFull: psi("io").fullAvg10,
60
+ availMb: kbToMb("MemAvailable"),
61
+ swapFreeMb: kbToMb("SwapFree"),
62
+ };
63
+ }
64
+
65
+ const over = (v: number | null, limit: number) => v !== null && v >= limit;
66
+ const under = (v: number | null, limit: number) => v !== null && v < limit;
67
+
68
+ /** Classifies one sample. Red on any stall or low-memory threshold; green only when every reading is well
69
+ * below its threshold; otherwise amber (including when nothing could be read). */
70
+ export function pressureLevel(s: PressureSample, cfg: Config): PressureLevel {
71
+ const p = cfg.machine.pressure;
72
+ const min = cfg.machine.avail_min_mb;
73
+ if (over(s.memSome, p.mem_some_red) || over(s.memFull, p.mem_full_red) || over(s.cpuSome, p.cpu_some_red) || under(s.availMb, min)) {
74
+ return "red";
75
+ }
76
+ const calm = under(s.memSome, p.mem_some_red / 2) && under(s.memFull, p.mem_full_red / 2) && under(s.cpuSome, p.cpu_some_red / 2) && over(s.availMb, min * 1.5);
77
+ return calm ? "green" : "amber";
78
+ }
79
+
80
+ /** Advances the level state machine. RED fires once the level has been red for red_after_sec, then at most
81
+ * every repeat_sec. GREEN fires once, after green_after_sec of green, and only after a RED. Amber never fires. */
82
+ export function pressureTransition(prev: PressureState | null, level: PressureLevel, nowSec: number, cfg: Config): { state: PressureState; fire: "red" | "green" | null } {
83
+ const p = cfg.machine.pressure;
84
+ const base: PressureState = prev ?? { level: "amber", since: nowSec, lastRed: null, redSent: false };
85
+ const state = base.level === level ? base : { ...base, level, since: nowSec };
86
+ const held = nowSec - state.since;
87
+ if (level === "red") {
88
+ const due = held >= p.red_after_sec && (state.lastRed === null || nowSec - state.lastRed >= p.repeat_sec);
89
+ return due ? { state: { ...state, lastRed: nowSec, redSent: true }, fire: "red" } : { state, fire: null };
90
+ }
91
+ if (level === "green" && state.redSent && held >= p.green_after_sec) {
92
+ return { state: { ...state, redSent: false }, fire: "green" };
93
+ }
94
+ return { state, fire: null };
95
+ }
96
+
97
+ /** The heavy-run holder right now, read from cfg.paths.heavy_owner; null when the file is missing or no lock is held. Shared by the tick and `neurastream pressure`. */
98
+ export function currentHolder(cfg: Config, nowSec: number): string | null {
99
+ const text = readText(cfg.paths.heavy_owner);
100
+ return text === null ? null : heavyHolder(text, nowSec);
101
+ }
102
+
103
+ /** The line Main reads. holder is the heavy-run lock holder from heavyHolder, or null. */
104
+ export function pressureMessage(level: "red" | "green", s: PressureSample, holder: string | null): string {
105
+ const mem = s.memSome === null ? "n/a" : `${Math.round(s.memSome)}%`;
106
+ const cpu = s.cpuSome === null ? "n/a" : `${Math.round(s.cpuSome)}%`;
107
+ const free = s.availMb === null ? "n/a" : `${(s.availMb / 1024).toFixed(1)} GB`;
108
+ const tail = level === "green" ? "; room again" : holder === null ? "" : `; heavy-run lock held by ${holder}`;
109
+ return `machine: ${level === "red" ? "RED" : "GREEN"} — memory stall ${mem}, cpu ${cpu}, ${free} free${tail}`;
110
+ }
111
+
112
+ /** Turns the heavy-run owner file ("<who> | <what> | since <stamp> | pid N") into "who (what) for N min".
113
+ * Null when the file is empty. nowSec is in seconds. */
114
+ export function heavyHolder(ownerText: string, nowSec: number): string | null {
115
+ const m = ownerText.match(/^(.*?) \| (.*?) \| since (\S+ \S+) \|/);
116
+ if (!m) return null;
117
+ const [, who = "", what = "", stamp = ""] = m;
118
+ const since = Date.parse(stamp.replace(" ", "T"));
119
+ if (Number.isNaN(since)) return `${who} (${what})`;
120
+ return `${who} (${what}) for ${Math.floor((nowSec * 1000 - since) / 60000)} min`;
121
+ }
@@ -1159,8 +1159,11 @@ export function openWaits(p: Plan, plans: Plan[], rank: Map<string, number>): nu
1159
1159
  // result, or queue-check fails the plan; entries without a date or dated before it are grandfathered.
1160
1160
  export const DONE_CLAIM_SINCE = "2026-11-01";
1161
1161
 
1162
- const DONE_WORD = /\b(?:done|completed?|nothing left|finished)\b/i;
1162
+ // "Done check" is a plan section name, not a claim.
1163
+ const DONE_WORD_SRC = String.raw`(?:done(?!\s+check)|completed?|nothing left|finished)`;
1163
1164
  const NOT_DONE = /\b(?:not|never)\s+(?:done|completed?|finished)\b/i;
1165
+ // A reviewer's PLAN/CODE REVIEW entry critiques a plan; it claims no phase done.
1166
+ const REVIEW_ENTRY = /\b(?:PLAN|CODE) REVIEW:/;
1164
1167
  const RESULT_MARK = /\bexit(?: code|ed)?\s*\d|\b\d+ pass|\b\d+ fail|\bpass(?:ed|ing)?\b|\bfail(?:ed|ing)?\b|\bresult\b/i;
1165
1168
 
1166
1169
  /** Progress entries: the "- " line plus the lines up to the next entry start (trimProgressBody's rule). */
@@ -1177,6 +1180,12 @@ function progressEntryBlocks(text: string): string[] {
1177
1180
  return blocks;
1178
1181
  }
1179
1182
 
1183
+ /** Phase ids the entry says are done: a done word within 40 characters of the id, in the same sentence. */
1184
+ function claimedPhases(entry: string): string[] {
1185
+ const ids = new Set([...entry.matchAll(/\b(P\d+[a-z]?)\b/g)].map(m => m[1]!));
1186
+ return [...ids].filter(id => new RegExp(String.raw`\b${id}\b[^.;\n]{0,40}\b${DONE_WORD_SRC}\b|\b${DONE_WORD_SRC}\b[^.;\n]{0,40}\b${id}\b`, "i").test(entry)).map(id => id.toUpperCase());
1187
+ }
1188
+
1180
1189
  /** A dated done claim about phase Pn must quote Pn's verify (or the Done check) with its result; else one problem per entry. */
1181
1190
  function doneClaimProblems(p: Plan): QueueProblem[] {
1182
1191
  const probs: QueueProblem[] = [];
@@ -1188,8 +1197,8 @@ function doneClaimProblems(p: Plan): QueueProblem[] {
1188
1197
  }
1189
1198
  for (const entry of progressEntryBlocks(p.text)) {
1190
1199
  const date = /^- (\d{4}-\d{2}-\d{2})/.exec(entry)?.[1];
1191
- if (!date || date < DONE_CLAIM_SINCE || !DONE_WORD.test(entry) || NOT_DONE.test(entry)) continue;
1192
- const ids = [...entry.matchAll(/\b(P\d+[a-z]?)\b/g)].map(m => m[1]!.toUpperCase());
1200
+ if (!date || date < DONE_CLAIM_SINCE || REVIEW_ENTRY.test(entry.split("\n")[0]!) || NOT_DONE.test(entry)) continue;
1201
+ const ids = claimedPhases(entry);
1193
1202
  if (!ids.length) continue;
1194
1203
  const backings = [...new Set(ids.flatMap(id => verifies.get(id) ?? []))];
1195
1204
  if (p.doneCheck) backings.push(p.doneCheck);
@@ -240,6 +240,14 @@ machine:
240
240
  idle_min_ticks: 300 # idle ticks before the flag
241
241
  watch_sec: 60 # seconds between machine watches
242
242
  watch_streak: 3 # consecutive watches before the flag
243
+ pressure: # pressure alerts (src/core/pressure.ts): tell Main when the machine chokes and when it has room; never acts
244
+ sample_sec: 10 # seconds between samples
245
+ mem_some_red: 20 # memory stall avg10 (%) that is red
246
+ mem_full_red: 5 # memory full-stall avg10 (%) that is red
247
+ cpu_some_red: 60 # cpu stall avg10 (%) that is red
248
+ red_after_sec: 30 # seconds red before the RED message
249
+ green_after_sec: 120 # seconds green after a RED before the GREEN message
250
+ repeat_sec: 600 # minimum seconds between two RED messages
243
251
 
244
252
  quota:
245
253
  reset_tz: "Asia/Shanghai" # timezone of the quota reset time