neurastream 0.1.12 → 0.1.14

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
@@ -102,12 +102,28 @@ A relaunch keeps the flags of the first run (`--model`, `--session-dir`, …) an
102
102
  In both modes:
103
103
 
104
104
  - A note counts only if it was written after the threshold was crossed and is at most one hour old.
105
+ - The running plugin going stale counts as over the threshold too: at every check the adapter re-reads the `package.json` it was loaded from, and a different (or unreadable) version asks for the handoff note even below `rollover.max_session_mb`, naming both versions (`NEURASTREAM_PACKAGE_JSON` overrides the path it watches).
106
+ - While a rollover is pending (no fresh note, or own jobs still running), Main cannot start new subagents: a `task` call is refused until the running jobs finish and the session rolls over.
105
107
  - While own jobs (subagents included) are still running, the switch waits: a rollover would cancel them.
106
108
  - `/main-rollover <message>` does the same by hand. It refuses below the threshold, without a fresh note, or while jobs run.
107
109
  - `/main-rollover` shows a notice at once and gathers `main-start` in the background, so omp keeps repainting and reading keys until the new session opens.
108
110
  - The previous session file stays where it is.
109
111
  - `rollover.enabled: false` turns the feature off.
110
112
 
113
+ ## Self-metrics
114
+
115
+ `neurastream metrics report [--days N]` compares this window (the last `metrics.report_days`, default 7) with the one before it, writes `<paths.notes>/metrics.md`, and prints the same report. Worst change is marked `◀ worst`. The five numbers:
116
+
117
+ - M1 cost per merge: cost of sub and main runs written in the window, divided by accepts in the window. Worker-only and Main-only dollars are shown too.
118
+ - M2 idle calls: calls of finished or died sub runs in the window that never got an accept, diagnose or validate event. Top 3 shown.
119
+ - M3 CI tries: mean `tries` of `ci` events in the window, and the MRs at 3 or more tries. Tries come from `metrics.ci_pipelines_cmd` (see `docs/config.md`).
120
+ - M4 owner corrections: owner messages in main runs that match `metrics.correction_patterns`, and Main messages ending in `?`. The owner message count is shown but never ranked.
121
+ - M5 guard blocks: BLOCK lines in the guard logs in the window, with false alarms and the top 3 reasons.
122
+
123
+ Caveat: M4 is a whole-run measure. A main run counts entirely by its last write time, so a run that spans a window edge counts in the window it ends in.
124
+
125
+ Weekly loop: run `neurastream metrics report`, then propose ONE rule change to the owner. When the owner decides, record it with `neurastream metrics rule "<text>" --approved|--rejected`; approved rules get a before/after check once a full window has passed. Record CI with `neurastream metrics ci <repo-dir> <mr-id>` and guard false alarms with `neurastream metrics false-alarm <log-ts> --why "<text>"`. main-start shows the report as due when it is missing or older than `metrics.report_days`.
126
+
111
127
  ## Changing a script
112
128
 
113
129
  Edit the script in this repo. Green is `bun run typecheck` and `bun test`, both exit 0. Main tags the release. The publish workflow puts that tag on npm. Then:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
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": ["ai-agents", "coding-agents", "orchestration", "guardrails", "omp", "bun", "cli"],
6
6
  "homepage": "https://github.com/umiddey/neurastream#readme",
@@ -17,13 +17,14 @@
17
17
 
18
18
  import { execFileSync, spawn } from "node:child_process";
19
19
  import { appendFileSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
20
- import { dirname, join } from "node:path";
20
+ import { dirname, join, resolve } from "node:path";
21
+ import { fileURLToPath } from "node:url";
21
22
  import type { Decision } from "../../core/adapter.ts";
22
23
  import { loadConfig, type Config } from "../../core/config.ts";
23
24
  import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult } from "../../core/guards.ts";
24
25
  import { applyQueueEnv } from "../../core/queue/env.ts";
25
26
  import { mainStartText } from "../../core/main-start.ts";
26
- import { buildHandoff, holdsBlock, notePath, noteRequest, relaunchPath, type RolloverState, rolloverState } from "../../core/rollover.ts";
27
+ import { buildHandoff, holdsBlock, notePath, noteRequest, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
27
28
  import * as q from "../../core/queue/lib.ts";
28
29
  // Registers the plugin-command matcher into core's writeTargets (side effect).
29
30
  import "./package-ops.ts";
@@ -80,6 +81,22 @@ export function toExtensionResult(d: Decision): Record<string, unknown> {
80
81
  // A push or merge by Main may have landed a completed plan: try closing right away.
81
82
  const PUSH_MERGE = /\bgit\b[^\n;|&]*\bpush\b|\b(glab\s+mr|gh\s+pr)\s+merge\b/;
82
83
 
84
+ // The installed copy this plugin comes from (computed as in doctor.ts) and the package.json whose
85
+ // version decides staleness. omp never reloads a plugin, so the version is read once at adapter
86
+ // start (the code actually running) and re-read at every rollover check; a different or unreadable
87
+ // version means the running plugin is stale. NEURASTREAM_PACKAGE_JSON overrides the path (tests
88
+ // and the sandbox smoke point it at a copy whose version changes mid-run), like QUEUE_CLOSE_BIN.
89
+ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
90
+
91
+ function packageVersion(packageJson: string): string | null {
92
+ try {
93
+ const version = asRecord(JSON.parse(readFileSync(packageJson, "utf8"))).version;
94
+ return typeof version === "string" ? version : null;
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+
83
100
  export function adapterLog(cfg: Config, line: string): void {
84
101
  try {
85
102
  appendFileSync(cfg.paths.guard_log, `${new Date().toISOString()} ${line}\n`);
@@ -298,6 +315,19 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
298
315
  const cwd = c.cwd ?? process.cwd();
299
316
  const snap = new Map<string, string>();
300
317
  snapshotPlans(tool, input, cwd, snap, !isSub);
318
+ // Drain (src/core/rollover.ts): while a rollover is pending no new subagent starts; the
319
+ // running ones finish first. Subagents' own tool calls are unaffected.
320
+ if (!isSub && tool === "task" && cfg.rollover.enabled) {
321
+ const rc = asRolloverCtx(ctx);
322
+ if (rc) {
323
+ const why = spawnRefusal(rolloverSnapshot(rc).state, rc.runningJobs());
324
+ if (why) {
325
+ const tasks = Array.isArray(input.tasks) ? input.tasks : [];
326
+ adapterLog(cfg, `BLOCK spawn ${String(asRecord(tasks[0]).agent ?? "task")}: rollover pending`);
327
+ return { block: true, reason: why };
328
+ }
329
+ }
330
+ }
301
331
  const d = checkTool(
302
332
  { tool, input, cwd, agent, agentId: id, calls: n - 1, paths: [], writes: [], command: asString(input.command) },
303
333
  cfg,
@@ -355,25 +385,44 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
355
385
  // Session rollover (src/core/rollover.ts). Main's session size decides when a handoff note is
356
386
  // asked for at turn end (a sendMessage that triggers Main's next turn). The owner's next message
357
387
  // then starts a fresh session from that note; under `neurastream main` the launcher starts it at
358
- // once. The size is re-read at every turn end and tool result; the note request goes out once per session file.
388
+ // once. The size and the installed version are re-read at every turn end and tool result; the
389
+ // note request goes out once per session file and note state.
390
+ // The version this process loaded at start: the plugin code that is actually running.
391
+ const loadedVersion = packageVersion(process.env.NEURASTREAM_PACKAGE_JSON ?? join(PACKAGE_ROOT, "package.json"));
359
392
  let crossed: { file: string; atMs: number } | null = null;
393
+ // The note request already sent, keyed by session file + note mtime at send time ("none" when
394
+ // no note exists): a note that expires while jobs run falls back to need-note with a key no
395
+ // request was sent for, so it gets exactly one new request and never a loop.
360
396
  let asked: string | null = null;
361
397
  let waitNoticeMs = 0;
362
398
 
363
- const stateOf = (c: RolloverCtx): RolloverState => {
399
+ const rolloverSnapshot = (c: RolloverCtx): { state: RolloverState; noteMtimeMs: number | null; stale: boolean; liveVersion: string | null } => {
364
400
  const nowMs = Date.now();
365
401
  const bytes = sizeOf(c.sessionFile);
366
402
  const maxMb = cfg.rollover.max_session_mb;
367
- if (bytes < maxMb * 1024 * 1024) crossed = null;
403
+ const noteMtimeMs = mtimeOf(notePath(c.sessionId));
404
+ const liveVersion = packageVersion(process.env.NEURASTREAM_PACKAGE_JSON ?? join(PACKAGE_ROOT, "package.json"));
405
+ const stale = liveVersion === null || loadedVersion === null || liveVersion !== loadedVersion;
406
+ if (stale) {
407
+ // Note freshness is measured against the crossing: a stale session counts as crossed
408
+ // from the first check that saw it, whatever its size.
409
+ if (crossed?.file !== c.sessionFile) crossed = { file: c.sessionFile, atMs: nowMs };
410
+ } else if (bytes < maxMb * 1024 * 1024) crossed = null;
368
411
  else if (crossed?.file !== c.sessionFile) crossed = { file: c.sessionFile, atMs: nowMs };
369
- return rolloverState({
370
- sessionBytes: bytes,
371
- maxMb,
372
- runningJobs: c.runningJobs(),
373
- crossedAtMs: crossed?.atMs ?? null,
374
- noteMtimeMs: mtimeOf(notePath(c.sessionId)),
375
- nowMs,
376
- });
412
+ return {
413
+ state: rolloverState({
414
+ sessionBytes: bytes,
415
+ maxMb,
416
+ runningJobs: c.runningJobs(),
417
+ crossedAtMs: crossed?.atMs ?? null,
418
+ noteMtimeMs,
419
+ nowMs,
420
+ stale,
421
+ }),
422
+ noteMtimeMs,
423
+ stale,
424
+ liveVersion,
425
+ };
377
426
  };
378
427
 
379
428
  let relaunched = false;
@@ -398,14 +447,19 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
398
447
  const onSizeCheck = (_e: unknown, ctx: unknown): void => {
399
448
  const c = asRolloverCtx(ctx);
400
449
  if (!cfg.rollover.enabled || !c || !isMain(ctx)) return;
401
- const state = stateOf(c);
402
- if (state === "need-note" && asked !== c.sessionFile) {
403
- asked = c.sessionFile;
450
+ const snap = rolloverSnapshot(c);
451
+ const key = `${c.sessionFile}:${snap.noteMtimeMs ?? "none"}`;
452
+ if (snap.state === "need-note" && asked !== key) {
453
+ asked = key;
454
+ // A stale install says so: the request names the version on disk and the one running.
455
+ const reason = snap.stale
456
+ ? `neurastream on disk is ${snap.liveVersion ?? "unknown"}, this session runs ${loadedVersion ?? "unknown"}`
457
+ : undefined;
404
458
  pi.sendMessage(
405
- { customType: "main-guard.rollover", content: noteRequest(notePath(c.sessionId), process.env.NEURASTREAM_MAIN_LAUNCHER === "1"), display: false },
459
+ { customType: "main-guard.rollover", content: noteRequest(notePath(c.sessionId), process.env.NEURASTREAM_MAIN_LAUNCHER === "1", reason), display: false },
406
460
  { triggerTurn: true, deliverAs: "nextTurn" },
407
461
  );
408
- } else if (state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && !relaunched) {
462
+ } else if (snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && !relaunched) {
409
463
  requestRelaunch(c, notePath(c.sessionId));
410
464
  }
411
465
  };
@@ -428,7 +482,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
428
482
  const rolloverNotice = (ctx: unknown): string | null => {
429
483
  const c = asRolloverCtx(ctx);
430
484
  if (!cfg.rollover.enabled || !c) return null;
431
- const state = stateOf(c);
485
+ const state = rolloverSnapshot(c).state;
432
486
  if (state === "wait-jobs" && Date.now() - waitNoticeMs >= WAIT_NOTICE_MS) {
433
487
  waitNoticeMs = Date.now();
434
488
  const jobs = c.runningJobs().join(", ");
@@ -444,7 +498,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
444
498
  const text = asString(e.text);
445
499
  if (!cfg.rollover.enabled || !c || !isMain(ctx)) return undefined;
446
500
  if (asString(e.source) !== "interactive" || text === "" || text.startsWith("/")) return undefined;
447
- if (stateOf(c) !== "ready") return undefined;
501
+ if (rolloverSnapshot(c).state !== "ready") return undefined;
448
502
  return { text: `/main-rollover ${text}` };
449
503
  });
450
504
 
@@ -454,7 +508,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
454
508
  const c = asRolloverCtx(ctx);
455
509
  if (!c) return;
456
510
  const path = notePath(c.sessionId);
457
- const state = stateOf(c);
511
+ const state = rolloverSnapshot(c).state;
458
512
  if (state === "below") {
459
513
  c.notify("main-rollover: this session is below rollover.max_session_mb; nothing to roll over.");
460
514
  return;
@@ -5,6 +5,7 @@ import { runDoctor } from "../adapters/omp/doctor.ts";
5
5
  import { GUARD_USAGE, runGuard } from "./guard.ts";
6
6
  import { runInit } from "./init.ts";
7
7
  import { PORTED, runMain, runPorted } from "./commands.ts";
8
+ import { runMetrics } from "./metrics.ts";
8
9
 
9
10
  const BINS = [
10
11
  "agent-score",
@@ -44,6 +45,7 @@ export function helpText(): string {
44
45
  " neurastream guard <event> --json",
45
46
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
46
47
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
48
+ " neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
47
49
  "",
48
50
  "Compatibility bins (same names as today; ports land in later phases):",
49
51
  ...BINS.map(b => ` ${b}`),
@@ -60,6 +62,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
60
62
  }
61
63
  if (cmd === "main") return runMain(args);
62
64
  if (cmd === "init") return runInit(args);
65
+ if (cmd === "metrics") return runMetrics(args);
63
66
  if (cmd === "adapter") return runAdapterInstall(args);
64
67
  if (cmd === "config") {
65
68
  try {
@@ -0,0 +1,131 @@
1
+ // `neurastream metrics …`: records facts the owner and the CI command decide into
2
+ // metrics.jsonl (see src/core/metrics.ts). Each record* function takes the config and the
3
+ // clock as arguments so tests run against a temp home.
4
+
5
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
8
+ import { appendMetric } from "../core/metrics.ts";
9
+ import { nowSec } from "../core/clock.ts";
10
+ import type { RunSource } from "../core/adapter.ts";
11
+ import { buildReport } from "../core/report.ts";
12
+ import { defaultRunSource } from "../adapters/omp/sessions.ts";
13
+
14
+ export const METRICS_USAGE = [
15
+ "usage: neurastream metrics ci <repo-dir> <mr-id>",
16
+ ' neurastream metrics false-alarm <log-ts> --why "<text>"',
17
+ ' neurastream metrics rule "<text>" --approved|--rejected',
18
+ " neurastream metrics report [--days N]",
19
+ ].join("\n");
20
+
21
+ function flagValue(args: string[], name: string): string | undefined {
22
+ const i = args.indexOf(name);
23
+ return i >= 0 ? args[i + 1] : undefined;
24
+ }
25
+
26
+ /** Single-quotes a value for `sh -c`, so an MR id cannot inject shell syntax. */
27
+ function shellQuote(v: string): string {
28
+ return `'${v.replaceAll("'", "'\\''")}'`;
29
+ }
30
+
31
+ /** Runs the configured CI command in the repo and records how many pipelines the MR needed. */
32
+ export function recordCi(cfg: Config, repoDir: string, mr: string, now: number): number {
33
+ if (!repoDir || !mr) {
34
+ console.error(METRICS_USAGE);
35
+ return 2;
36
+ }
37
+ const template = cfg.metrics.ci_pipelines_cmd;
38
+ if (!template) {
39
+ console.error("metrics.ci_pipelines_cmd not set");
40
+ return 2;
41
+ }
42
+ if (!existsSync(repoDir)) {
43
+ console.error(`repo-dir not found: ${repoDir}`);
44
+ return 2;
45
+ }
46
+ const proc = Bun.spawnSync(["sh", "-c", template.replaceAll("{mr}", shellQuote(mr))], {
47
+ cwd: repoDir,
48
+ stdout: "pipe",
49
+ stderr: "pipe",
50
+ });
51
+ if (proc.exitCode !== 0) {
52
+ console.error(`ci command exited ${proc.exitCode}: ${proc.stderr.toString().trim()}`);
53
+ return 1;
54
+ }
55
+ let pipelines: unknown;
56
+ try {
57
+ pipelines = JSON.parse(proc.stdout.toString());
58
+ } catch {
59
+ pipelines = undefined;
60
+ }
61
+ if (!Array.isArray(pipelines)) {
62
+ console.error("ci command must print a JSON array on stdout");
63
+ return 1;
64
+ }
65
+ appendMetric(cfg, { type: "ci", mr, repo: repoDir, tries: pipelines.length, ts: now });
66
+ console.log(`ci: ${mr} needed ${pipelines.length} pipeline(s)`);
67
+ return 0;
68
+ }
69
+
70
+ /** Marks one guard BLOCK line (by its ISO timestamp) as a false alarm. */
71
+ export function recordFalseAlarm(cfg: Config, logTs: string, why: string, now: number): number {
72
+ if (!logTs || !why) {
73
+ console.error(METRICS_USAGE);
74
+ return 2;
75
+ }
76
+ appendMetric(cfg, { type: "false-alarm", log_ts: logTs, why, ts: now });
77
+ console.log(`false-alarm recorded for ${logTs}`);
78
+ return 0;
79
+ }
80
+
81
+ /** Records the owner's decision on one proposed rule change. */
82
+ export function recordRule(cfg: Config, text: string, decision: "approved" | "rejected", now: number): number {
83
+ if (!text) {
84
+ console.error(METRICS_USAGE);
85
+ return 2;
86
+ }
87
+ appendMetric(cfg, { type: "rule", text, decision, ts: now });
88
+ console.log(`rule ${decision}: ${text}`);
89
+ return 0;
90
+ }
91
+
92
+ /** Writes notes/metrics.md and prints the same report: this window against the previous one. */
93
+ export function reportCmd(cfg: Config, source: RunSource, args: string[], now: number): number {
94
+ const raw = flagValue(args, "--days");
95
+ const days = raw === undefined ? cfg.metrics.report_days : Number(raw);
96
+ if (!Number.isInteger(days) || days < 1) {
97
+ console.error(METRICS_USAGE);
98
+ return 2;
99
+ }
100
+ const { md, text } = buildReport(cfg, source, days, now);
101
+ mkdirSync(cfg.paths.notes, { recursive: true });
102
+ writeFileSync(join(cfg.paths.notes, "metrics.md"), md);
103
+ console.log(text);
104
+ return 0;
105
+ }
106
+
107
+ export async function runMetrics(args: string[]): Promise<number> {
108
+ let cfg: Config;
109
+ try {
110
+ cfg = loadConfig();
111
+ } catch (err) {
112
+ console.error(err instanceof ConfigError ? err.message : String(err));
113
+ return 1;
114
+ }
115
+ const [sub = "", ...rest] = args;
116
+ const now = nowSec();
117
+ if (sub === "ci") return recordCi(cfg, rest[0] ?? "", rest[1] ?? "", now);
118
+ if (sub === "report") return reportCmd(cfg, defaultRunSource(cfg), rest, now);
119
+ if (sub === "false-alarm") return recordFalseAlarm(cfg, rest[0] ?? "", flagValue(rest, "--why") ?? "", now);
120
+ if (sub === "rule") {
121
+ const approved = rest.includes("--approved");
122
+ const rejected = rest.includes("--rejected");
123
+ if (approved === rejected) {
124
+ console.error(METRICS_USAGE);
125
+ return 2;
126
+ }
127
+ return recordRule(cfg, rest[0] ?? "", approved ? "approved" : "rejected", now);
128
+ }
129
+ console.error(METRICS_USAGE);
130
+ return 2;
131
+ }
@@ -28,7 +28,7 @@ function eventsPath(cfg: Config): string {
28
28
  return join(cfg.paths.score_state, "events.jsonl");
29
29
  }
30
30
 
31
- function readEvents(cfg: Config): Record<string, unknown>[] {
31
+ export function readEvents(cfg: Config): Record<string, unknown>[] {
32
32
  const path = eventsPath(cfg);
33
33
  if (!existsSync(path)) return [];
34
34
  return readFileSync(path, "utf8")
@@ -112,6 +112,7 @@ export interface Config {
112
112
  ledger_command: string;
113
113
  };
114
114
  rollover: { enabled: boolean; max_session_mb: number };
115
+ metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
115
116
  machine: {
116
117
  load_over_cores: number;
117
118
  load_max: number;
@@ -260,6 +261,14 @@ function check(cfg: Config): void {
260
261
  throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
261
262
  }
262
263
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
264
+ if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
265
+ for (const p of cfg.metrics.correction_patterns) {
266
+ try {
267
+ new RegExp(p, "i");
268
+ } catch {
269
+ throw new ConfigError(`metrics.correction_patterns: not a valid regex: ${p}`);
270
+ }
271
+ }
263
272
  for (const [key, value] of Object.entries(cfg.paths)) {
264
273
  if (key === "work_roots") {
265
274
  if (!Array.isArray(value) || value.some(v => typeof v !== "string")) {
@@ -1,4 +1,4 @@
1
- import { readFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
2
  import { spawn } from "node:child_process";
3
3
  import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
@@ -59,6 +59,9 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
59
59
  const h = args[0] ?? String(cfg.health.default_hours);
60
60
  const childStdin = opts.inheritStdin ? "inherit" : "ignore";
61
61
  const childStderr = opts.inheritStdin ? "inherit" : "pipe";
62
+ // Weekly self-metrics: nudge the owner's report when notes/metrics.md is missing or older than the window.
63
+ const due = metricsDueLine(cfg, Date.now());
64
+ if (due) say(due);
62
65
  say("=== machine");
63
66
  const mg = await run(bin("machine-guard", cfg), [], { stderr: "ignore" });
64
67
  const mgLines = mg.stdout.trim().split("\n");
@@ -107,3 +110,12 @@ export async function mainStart(args: string[], cfg: Config): Promise<number> {
107
110
  process.stdout.write(await mainStartText(args, cfg, { inheritStdin: true }));
108
111
  return 0;
109
112
  }
113
+
114
+ // Due line for the weekly self-metrics report; null when notes/metrics.md is fresh.
115
+ export function metricsDueLine(cfg: Config, nowMs: number): string | null {
116
+ const reportFile = join(cfg.paths.notes, "metrics.md");
117
+ const stamp = existsSync(reportFile) ? statSync(reportFile).mtime : null;
118
+ if (stamp && nowMs - stamp.getTime() <= cfg.metrics.report_days * 86400 * 1000) return null;
119
+ const last = stamp ? stamp.toISOString().slice(0, 10) : "never";
120
+ return `metrics: report due (last: ${last}) — run neurastream metrics report, then propose ONE rule change to the owner`;
121
+ }
@@ -0,0 +1,269 @@
1
+ // Self-metrics: numbers about Neurastream's own work, per time window. Pure functions over
2
+ // runs (via RunSource), the score ledger (events.jsonl) and metrics.jsonl (ci, false-alarm,
3
+ // rule). No harness names, no literals beyond the event types; every knob comes from the
4
+ // `metrics:` config section.
5
+
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import type { Config } from "./config.ts";
9
+ import type { Run, RunSource } from "./adapter.ts";
10
+ import { readEvents } from "./agent-score.ts";
11
+
12
+ export type Ev = Record<string, unknown>;
13
+
14
+ /** Half-open window [from, to) in unix seconds. */
15
+ export interface Window {
16
+ from: number;
17
+ to: number;
18
+ }
19
+
20
+ export interface Inputs {
21
+ runs: Run[];
22
+ events: Ev[];
23
+ }
24
+
25
+ const DAY = 86400;
26
+
27
+ /** Current window [now-N, now) and the one before it [now-2N, now-N). */
28
+ export function windows(now: number, days: number): { cur: Window; prev: Window } {
29
+ const span = days * DAY;
30
+ return {
31
+ cur: { from: now - span, to: now },
32
+ prev: { from: now - 2 * span, to: now - span },
33
+ };
34
+ }
35
+
36
+ export function inWindow(t: number, w: Window): boolean {
37
+ return t >= w.from && t < w.to;
38
+ }
39
+
40
+ /** Loads every run touched in the last two windows plus the full event ledger. */
41
+ export function loadInputs(cfg: Config, source: RunSource, now: number, days: number): Inputs {
42
+ return {
43
+ runs: source.listRuns(now - 2 * days * DAY),
44
+ events: readEvents(cfg),
45
+ };
46
+ }
47
+
48
+ // ---- metrics.jsonl: the facts the owner and the CI command record ----
49
+
50
+ export function metricsPath(cfg: Config): string {
51
+ return join(cfg.paths.score_state, "metrics.jsonl");
52
+ }
53
+
54
+ /** Appends one JSON line; the state directory is created on first use. */
55
+ export function appendMetric(cfg: Config, rec: Ev): void {
56
+ mkdirSync(cfg.paths.score_state, { recursive: true });
57
+ appendFileSync(metricsPath(cfg), `${JSON.stringify(rec)}\n`);
58
+ }
59
+
60
+ export function readMetricEvents(cfg: Config): Ev[] {
61
+ const path = metricsPath(cfg);
62
+ if (!existsSync(path)) return [];
63
+ const out: Ev[] = [];
64
+ for (const line of readFileSync(path, "utf8").split("\n")) {
65
+ if (!line.trim()) continue;
66
+ try {
67
+ out.push(JSON.parse(line) as Ev);
68
+ } catch {
69
+ // A torn line from an interrupted append is skipped, not fatal.
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+
75
+ // ---- M1, M2: cost and idle calls per merge ----
76
+
77
+ export interface M1 {
78
+ accepts: number;
79
+ worker: number;
80
+ main: number;
81
+ /** null when nothing was merged in the window. */
82
+ perMerge: number | null;
83
+ }
84
+
85
+ /** M1: cost of sub and main runs written in the window, per accepted merge in the window. */
86
+ export function m1(inp: Inputs, w: Window): M1 {
87
+ let worker = 0;
88
+ let main = 0;
89
+ for (const r of inp.runs) {
90
+ if (!inWindow(r.lastWriteAt, w)) continue;
91
+ if (r.kind === "sub") worker += r.cost;
92
+ else if (r.kind === "main") main += r.cost;
93
+ }
94
+ const accepts = inp.events.filter((e) => e.type === "accept" && inWindow(Number(e.ts), w)).length;
95
+ return {
96
+ accepts,
97
+ worker,
98
+ main,
99
+ perMerge: accepts > 0 ? (worker + main) / accepts : null,
100
+ };
101
+ }
102
+
103
+ /** Event types that mean a worker's output was judged at some point. */
104
+ const JUDGED: Record<string, true> = { accept: true, diagnose: true, validate: true };
105
+
106
+ export interface M2 {
107
+ calls: number;
108
+ top: { id: string; calls: number }[];
109
+ }
110
+
111
+ /**
112
+ * M2: calls spent by finished-or-died sub runs written in the window that never got an
113
+ * accept, diagnose or validate event (checked over the whole ledger, not just the window).
114
+ */
115
+ export function m2(inp: Inputs, w: Window): M2 {
116
+ const judged = new Set(inp.events.filter((e) => JUDGED[String(e.type)] === true).map((e) => String(e.agent)));
117
+ const idle = inp.runs.filter(
118
+ (r) =>
119
+ r.kind === "sub" &&
120
+ inWindow(r.lastWriteAt, w) &&
121
+ (r.status === "done" || r.status === "died") &&
122
+ !judged.has(r.id),
123
+ );
124
+ const top = idle
125
+ .map((r) => ({ id: r.id, calls: r.calls }))
126
+ .sort((a, b) => b.calls - a.calls || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
127
+ .slice(0, 3);
128
+ return { calls: idle.reduce((s, r) => s + r.calls, 0), top };
129
+ }
130
+
131
+ // ---- M3: CI tries ----
132
+
133
+ export interface M3 {
134
+ n: number;
135
+ /** null when no ci events fall in the window. */
136
+ mean: number | null;
137
+ /** MRs that needed 3 or more pipelines. */
138
+ big: string[];
139
+ }
140
+
141
+ /** M3: mean `tries` of `ci` events in the window, and the MRs that needed 3 or more. */
142
+ export function m3(events: Ev[], w: Window): M3 {
143
+ const ci = events.filter((e) => e.type === "ci" && inWindow(Number(e.ts), w));
144
+ const sum = ci.reduce((s, e) => s + Number(e.tries), 0);
145
+ return {
146
+ n: ci.length,
147
+ mean: ci.length > 0 ? sum / ci.length : null,
148
+ big: ci.filter((e) => Number(e.tries) >= 3).map((e) => String(e.mr)),
149
+ };
150
+ }
151
+
152
+ // ---- M4: owner corrections and Main's questions ----
153
+
154
+ interface Block {
155
+ type: string;
156
+ text: string;
157
+ }
158
+
159
+ /**
160
+ * Content blocks from RunMessage.text, which is a JSON dump of the message content. A plain
161
+ * string content counts as one text block; a dump that is not JSON is taken as plain text.
162
+ */
163
+ function blocks(raw: string): Block[] {
164
+ let v: unknown;
165
+ try {
166
+ v = JSON.parse(raw);
167
+ } catch {
168
+ return [{ type: "text", text: raw }];
169
+ }
170
+ if (typeof v === "string") return [{ type: "text", text: v }];
171
+ if (!Array.isArray(v)) return [];
172
+ const out: Block[] = [];
173
+ for (const b of v) {
174
+ if (typeof b !== "object" || b === null) continue;
175
+ const o = b as Record<string, unknown>;
176
+ if (typeof o.text === "string") out.push({ type: String(o.type ?? ""), text: o.text });
177
+ }
178
+ return out;
179
+ }
180
+
181
+ export interface M4 {
182
+ users: number;
183
+ corrections: number;
184
+ questions: number;
185
+ }
186
+
187
+ /**
188
+ * M4: user messages in main runs written in the window, how many match a correction pattern,
189
+ * and assistant messages whose last text block ends in "?". RunMessage has no timestamp, so
190
+ * a main run counts whole by its lastWriteAt.
191
+ */
192
+ export function m4(runs: Run[], w: Window, patterns: RegExp[]): M4 {
193
+ const out: M4 = { users: 0, corrections: 0, questions: 0 };
194
+ for (const r of runs) {
195
+ if (r.kind !== "main" || !inWindow(r.lastWriteAt, w)) continue;
196
+ for (const m of r.messages) {
197
+ if (m.role === "user") {
198
+ out.users++;
199
+ const text = blocks(m.text)
200
+ .map((b) => b.text)
201
+ .join("\n");
202
+ if (patterns.some((p) => p.test(text))) out.corrections++;
203
+ } else if (m.role === "assistant") {
204
+ const last = blocks(m.text)
205
+ .filter((b) => b.type === "text")
206
+ .at(-1);
207
+ if (last?.text.trimEnd().endsWith("?")) out.questions++;
208
+ }
209
+ }
210
+ }
211
+ return out;
212
+ }
213
+
214
+ // ---- M5: guard BLOCK lines and false alarms ----
215
+
216
+ export interface GuardBlock {
217
+ ts: number;
218
+ reason: string;
219
+ }
220
+
221
+ /** Groups reasons by shape: paths cut to 40 chars, digit runs collapsed to N, and every
222
+ * `open: <plan list>` tail collapsed to one key: the lists differ per plan set, the reason is one. */
223
+ function reasonKey(text: string): string {
224
+ const shaped = text.replace(/\S*\/\S*/g, (p) => (p.length > 40 ? `${p.slice(0, 40)}…` : p)).replace(/\d+/g, "N");
225
+ const at = shaped.indexOf("open: ");
226
+ return at === -1 ? shaped : `${shaped.slice(0, at)}open: <list>`;
227
+ }
228
+
229
+ /** BLOCK lines of one guard log, each `<ISO UTC> BLOCK <reason>`. Other lines are ignored. */
230
+ export function parseBlocks(text: string): GuardBlock[] {
231
+ const out: GuardBlock[] = [];
232
+ for (const line of text.split("\n")) {
233
+ const m = /^(\S+) BLOCK (.*)$/.exec(line);
234
+ if (!m) continue;
235
+ const ts = Date.parse(m[1] ?? "") / 1000;
236
+ if (Number.isNaN(ts)) continue;
237
+ out.push({ ts, reason: reasonKey(m[2] ?? "") });
238
+ }
239
+ return out;
240
+ }
241
+
242
+ /** BLOCK lines from both guard logs named in config. A missing log counts as none. */
243
+ export function readBlocks(cfg: Config): GuardBlock[] {
244
+ return [cfg.paths.guard_log, cfg.paths.plan_guard_log].flatMap((p) =>
245
+ existsSync(p) ? parseBlocks(readFileSync(p, "utf8")) : [],
246
+ );
247
+ }
248
+
249
+ export interface M5 {
250
+ blocks: number;
251
+ falseAlarms: number;
252
+ top: { reason: string; count: number }[];
253
+ }
254
+
255
+ /** M5: BLOCK lines in the window, false-alarm events in the window, and the 3 most common reasons. */
256
+ export function m5(blocks: GuardBlock[], events: Ev[], w: Window): M5 {
257
+ const inBlocks = blocks.filter((b) => inWindow(b.ts, w));
258
+ const counts = new Map<string, number>();
259
+ for (const b of inBlocks) counts.set(b.reason, (counts.get(b.reason) ?? 0) + 1);
260
+ const top = [...counts]
261
+ .map(([reason, count]) => ({ reason, count }))
262
+ .sort((a, b) => b.count - a.count || (a.reason < b.reason ? -1 : a.reason > b.reason ? 1 : 0))
263
+ .slice(0, 3);
264
+ return {
265
+ blocks: inBlocks.length,
266
+ falseAlarms: events.filter((e) => e.type === "false-alarm" && inWindow(Number(e.ts), w)).length,
267
+ top,
268
+ };
269
+ }
@@ -0,0 +1,179 @@
1
+ // The self-metrics report: this window against the previous one, the worst change, and a
2
+ // before/after check for each approved rule. Pure over RunSource, the ledger, metrics.jsonl
3
+ // and the guard logs; the caller decides where the text goes.
4
+
5
+ import type { Config } from "./config.ts";
6
+ import type { RunSource } from "./adapter.ts";
7
+ import {
8
+ m1,
9
+ m2,
10
+ m3,
11
+ m4,
12
+ m5,
13
+ readBlocks,
14
+ readMetricEvents,
15
+ windows,
16
+ loadInputs,
17
+ type Ev,
18
+ type GuardBlock,
19
+ type M1,
20
+ type M2,
21
+ type M3,
22
+ type M4,
23
+ type M5,
24
+ type Window,
25
+ } from "./metrics.ts";
26
+
27
+ const DAY = 86400;
28
+
29
+ const CAVEAT =
30
+ "M4 is a whole-run measure: a main run counts entirely by its last write time, so a run that spans a window edge counts in the window it ends in.";
31
+
32
+ interface Snap {
33
+ m1: M1;
34
+ m2: M2;
35
+ m3: M3;
36
+ m4: M4;
37
+ m5: M5;
38
+ }
39
+
40
+ function day(t: number): string {
41
+ return new Date(t * 1000).toISOString().slice(0, 10);
42
+ }
43
+
44
+ function snap(cfg: Config, source: RunSource, events: Ev[], blocks: GuardBlock[], w: Window): Snap {
45
+ const runs = source.listRuns(w.from);
46
+ const patterns = cfg.metrics.correction_patterns.map((p) => new RegExp(p, "i"));
47
+ return {
48
+ m1: m1({ runs, events }, w),
49
+ m2: m2({ runs, events }, w),
50
+ m3: m3(events, w),
51
+ m4: m4(runs, w, patterns),
52
+ m5: m5(blocks, events, w),
53
+ };
54
+ }
55
+
56
+ interface Row {
57
+ name: string;
58
+ cur: number | null;
59
+ prev: number | null;
60
+ fmt: (v: number | null) => string;
61
+ /** M4 owner-message count is shown but never ranked: it measures volume, not quality. */
62
+ rank: boolean;
63
+ }
64
+
65
+ function rowsOf(c: Snap, p: Snap): Row[] {
66
+ const usd = (v: number | null) => (v === null ? "n/a (0 merged)" : `$${v.toFixed(2)}`);
67
+ const num = (v: number | null) => (v === null ? "n/a" : String(v));
68
+ const mean = (v: number | null) => (v === null ? "n/a" : v.toFixed(2));
69
+ return [
70
+ { name: "M1 cost per merge", cur: c.m1.perMerge, prev: p.m1.perMerge, fmt: usd, rank: true },
71
+ { name: "M2 idle calls", cur: c.m2.calls, prev: p.m2.calls, fmt: num, rank: true },
72
+ { name: "M3 mean CI tries", cur: c.m3.mean, prev: p.m3.mean, fmt: mean, rank: true },
73
+ { name: "M4 owner corrections", cur: c.m4.corrections, prev: p.m4.corrections, fmt: num, rank: true },
74
+ { name: "M4 Main questions", cur: c.m4.questions, prev: p.m4.questions, fmt: num, rank: true },
75
+ { name: "M4 owner messages", cur: c.m4.users, prev: p.m4.users, fmt: num, rank: false },
76
+ { name: "M5 guard blocks", cur: c.m5.blocks, prev: p.m5.blocks, fmt: num, rank: true },
77
+ ];
78
+ }
79
+
80
+ /** Percent change of this window against the previous one; null when either is missing or the base is 0. */
81
+ function change(r: Row): number | null {
82
+ if (r.cur === null || r.prev === null || r.prev === 0) return null;
83
+ return ((r.cur - r.prev) / r.prev) * 100;
84
+ }
85
+
86
+ function signed(d: number | null): string {
87
+ if (d === null) return "n/a";
88
+ return `${d >= 0 ? "+" : ""}${d.toFixed(1)}%`;
89
+ }
90
+
91
+ function detail(c: Snap): string[] {
92
+ const top2 = c.m2.top.map((t) => `${t.id} ${t.calls}`).join(", ") || "none";
93
+ const reasons = c.m5.top.map((t) => `${t.count}× ${t.reason}`).join("; ") || "none";
94
+ return [
95
+ `M1 worker $${c.m1.worker.toFixed(2)}, main $${c.m1.main.toFixed(2)}, accepts ${c.m1.accepts}`,
96
+ `M2 top idle runs: ${top2}`,
97
+ `M3 CI runs ${c.m3.n}; MRs at 3+ tries: ${c.m3.big.join(", ") || "none"}`,
98
+ `M4 owner messages ${c.m4.users}, corrections ${c.m4.corrections}, Main questions ${c.m4.questions}`,
99
+ `M5 guard blocks ${c.m5.blocks}, false alarms ${c.m5.falseAlarms}; top reasons: ${reasons}`,
100
+ ];
101
+ }
102
+
103
+ /** Before/after per approved rule. A rule younger than one window reads "measuring". */
104
+ function ruleLines(cfg: Config, source: RunSource, events: Ev[], blocks: GuardBlock[], days: number, now: number): string[] {
105
+ const out: string[] = [];
106
+ for (const e of events) {
107
+ if (e.type !== "rule" || e.decision !== "approved") continue;
108
+ const ts = Number(e.ts);
109
+ const head = `- ${String(e.text)} (approved ${day(ts)})`;
110
+ if (now - ts < days * DAY) {
111
+ out.push(`${head}: measuring`);
112
+ continue;
113
+ }
114
+ const before = snap(cfg, source, events, blocks, { from: ts - days * DAY, to: ts });
115
+ const after = snap(cfg, source, events, blocks, { from: ts, to: ts + days * DAY });
116
+ const perMerge = (s: Snap) => (s.m1.perMerge === null ? "n/a" : `$${s.m1.perMerge.toFixed(2)}`);
117
+ const tries = (s: Snap) => (s.m3.mean === null ? "n/a" : s.m3.mean.toFixed(2));
118
+ out.push(
119
+ `${head}: M1 ${perMerge(before)} → ${perMerge(after)}; M2 idle calls ${before.m2.calls} → ${after.m2.calls}; ` +
120
+ `M3 tries ${tries(before)} → ${tries(after)}; M5 blocks ${before.m5.blocks} → ${after.m5.blocks}`,
121
+ );
122
+ }
123
+ return out.length ? out : ["(none approved yet)"];
124
+ }
125
+
126
+ export interface Report {
127
+ /** The full markdown written to notes/metrics.md. */
128
+ md: string;
129
+ /** The same content without the generated header, for stdout. */
130
+ text: string;
131
+ }
132
+
133
+ export function buildReport(cfg: Config, source: RunSource, days: number, now: number): Report {
134
+ const inp = loadInputs(cfg, source, now, days);
135
+ const events = [...inp.events, ...readMetricEvents(cfg)];
136
+ const blocks = readBlocks(cfg);
137
+ const { cur, prev } = windows(now, days);
138
+ const c = snap(cfg, source, events, blocks, cur);
139
+ const p = snap(cfg, source, events, blocks, prev);
140
+
141
+ const rows = rowsOf(c, p);
142
+ let worst: Row | null = null;
143
+ let worstPct = 0;
144
+ for (const r of rows) {
145
+ const d = change(r);
146
+ if (r.rank && d !== null && d > worstPct) {
147
+ worst = r;
148
+ worstPct = d;
149
+ }
150
+ }
151
+ const table = [
152
+ "| metric | this window | previous | change |",
153
+ "|---|---|---|---|",
154
+ ...rows.map((r) => {
155
+ const mark = r === worst ? " ◀ worst" : "";
156
+ return `| ${r.name} | ${r.fmt(r.cur)} | ${r.fmt(r.prev)} | ${signed(change(r))}${mark} |`;
157
+ }),
158
+ ];
159
+ const body = [
160
+ `Self-metrics: last ${days} days [${day(cur.from)} to ${day(cur.to)}) vs previous ${days} days.`,
161
+ "",
162
+ ...table,
163
+ "",
164
+ ...detail(c),
165
+ "",
166
+ "Approved rules, before vs after:",
167
+ ...ruleLines(cfg, source, events, blocks, days, now),
168
+ ].join("\n");
169
+
170
+ const md = [
171
+ "# Self-metrics (GENERATED by `neurastream metrics report`; do not hand-edit)",
172
+ "",
173
+ CAVEAT,
174
+ "",
175
+ body,
176
+ "",
177
+ ].join("\n");
178
+ return { md, text: body };
179
+ }
@@ -17,20 +17,24 @@ export interface RolloverInput {
17
17
  maxMb: number;
18
18
  /** Labels of the own async jobs (subagents included) that are still running. */
19
19
  runningJobs: readonly string[];
20
- /** When the session file was first seen at or over the threshold; null if never. */
20
+ /** When the session file was first seen at or over the threshold (or stale); null if never. */
21
21
  crossedAtMs: number | null;
22
22
  /** Mtime of the handoff note; null when the note does not exist. */
23
23
  noteMtimeMs: number | null;
24
+ /** The running plugin differs from the installed package (or its version is unreadable). */
25
+ stale: boolean;
24
26
  nowMs: number;
25
27
  }
26
28
 
27
29
  /**
28
- * below: under the threshold. need-note: over it and no fresh note (written after the crossing,
29
- * at most MAX_NOTE_AGE_MS old). wait-jobs: note is fresh but own jobs still run (rolling over
30
- * would cancel them). ready: the next owner message may roll over.
30
+ * below: under the threshold and not stale. need-note: over the threshold (or stale) with no fresh
31
+ * note (written after the crossing, at most MAX_NOTE_AGE_MS old). wait-jobs: note is fresh but own
32
+ * jobs still run (rolling over would cancel them). ready: the next owner message may roll over.
33
+ * A stale session counts like a crossed size threshold: even a small session rolls over, because
34
+ * the running plugin is not the code the owner installed.
31
35
  */
32
36
  export function rolloverState(p: RolloverInput): RolloverState {
33
- if (p.sessionBytes < p.maxMb * 1024 * 1024) return "below";
37
+ if (p.sessionBytes < p.maxMb * 1024 * 1024 && !p.stale) return "below";
34
38
  const noteFresh =
35
39
  p.noteMtimeMs !== null &&
36
40
  p.crossedAtMs !== null &&
@@ -40,6 +44,16 @@ export function rolloverState(p: RolloverInput): RolloverState {
40
44
  return p.runningJobs.length > 0 ? "wait-jobs" : "ready";
41
45
  }
42
46
 
47
+ /**
48
+ * Drain: while a rollover is pending (need-note or wait-jobs) Main must not start new subagents —
49
+ * a rollover would cancel them, or they would outlive the handoff. Returns the refusal text, or
50
+ * null when the spawn may proceed (below, ready).
51
+ */
52
+ export function spawnRefusal(state: RolloverState, runningJobs: readonly string[]): string | null {
53
+ if (state !== "need-note" && state !== "wait-jobs") return null;
54
+ return `main-guard: rollover pending (${state}); no new subagents until the session rolls over. Running: ${runningJobs.join(", ")}.`;
55
+ }
56
+
43
57
  export interface HandoffInput {
44
58
  /** Output of main-start (the generated state). */
45
59
  generated: string;
@@ -71,10 +85,11 @@ export function holdsBlock(holds: readonly string[]): string {
71
85
  return ["=== owner holds (plans' WAITING on owner lines)", ...(holds.length > 0 ? holds : ["none"]), ""].join("\n");
72
86
  }
73
87
 
74
- /** The one-time note instruction for Main's next turn. */
75
- export function noteRequest(path: string, auto = false): string {
88
+ /** The one-time note instruction for Main's next turn. `reason` (a stale install) names both versions. */
89
+ export function noteRequest(path: string, auto = false, reason = ""): string {
76
90
  return [
77
91
  "Session rollover: this session has grown past rollover.max_session_mb.",
92
+ ...(reason ? [reason] : []),
78
93
  `Write a handoff note to ${path} (overwrite it). Cover the work in progress and its state, the decisions made and why, the next step, and the files involved.`,
79
94
  "Do not list holds or owner blockers in the note; they come from the plans' WAITING on owner lines.",
80
95
  auto
@@ -118,6 +118,11 @@ rollover:
118
118
  enabled: true
119
119
  max_session_mb: 5
120
120
 
121
+ metrics:
122
+ report_days: 7
123
+ correction_patterns: ['\bno\b', 'wrong', 'why did', 'properly', 'not what', 'stop', 'bullshit', 'fuck']
124
+ ci_pipelines_cmd: "" # command run in the repo dir with {mr} replaced; stdout must be a JSON array; "" = not set
125
+
121
126
  machine:
122
127
  load_over_cores: 4
123
128
  load_max: 0