neurastream 0.2.40 → 0.2.42

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
@@ -31,9 +31,18 @@ flowchart LR
31
31
  | Brief lint (`brief-lint`) | Refuses a helper brief that misses a required rule (acceptance, stop condition, no push, call budget). |
32
32
  | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
33
33
  | 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
- | 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; under `neurastream main` a fresh session starts on its own, under plain omp the next owner message starts it. |
34
+ | 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`. |
35
35
  | Owner page (`neurastream ui`) | One phone-sized page over Tailscale (`ui.*` config): the plans waiting on the owner with answer buttons, the guard unlock, running agents, the queue, recent merges/CI, open incidents, agent scores, machine health. Serves only a tailnet peer whose `tailscale whois` login equals `ui.owner_login`, only with a Host header naming the tailnet address or the MagicDNS name — DNS rebinding and every other visitor get a 403. Answers land in the owner inbox and reach Main once each; agents cannot start the page or write the inbox. |
36
36
 
37
+ ## Main vs plain omp
38
+
39
+ neurastream runs only under `neurastream main`. That launcher sets `NEURASTREAM_MAIN_LAUNCHER=1` for the omp it starts, and only then does the adapter register its hooks and commands. Plain `omp` runs with no guard, queue summary, rules or rollover, as if neurastream were not installed.
40
+
41
+ ```sh
42
+ neurastream main # Main: guards, queue, rules, rollover
43
+ omp -p "say hi" # plain omp: no neurastream hook, no guard-log line
44
+ ```
45
+
37
46
  ## Requirements
38
47
 
39
48
  - [Bun](https://bun.sh) 1.x
@@ -139,7 +148,6 @@ Main's session file grows with every turn. When it reaches `rollover.max_session
139
148
  There are two modes:
140
149
 
141
150
  - Under `neurastream main` (the launcher) the rollover is automatic. Once the note is written and no own jobs (subagents included) are still running, omp writes `relaunch.json` and exits. The launcher starts a fresh omp whose first message is the handoff: the note verbatim, the generated `main-start` state (including the owner holds), the owner's unsent draft if there is one, and a line that the owner is away. Nobody types anything. A handoff over 100000 bytes goes to `<queue_state>/rollover/<session id>.handoff.md`, and the first message points at that file.
142
- - Under plain `omp` the switch is never automatic. The owner's next plain message closes the session and starts a fresh one; the fresh session opens with the note verbatim, the generated state, and then the owner's message.
143
151
 
144
152
  A relaunch keeps the flags of the first run (`--model`, `--session-dir`, …) and drops only the first message and the session-picking and one-shot flags (`-r`, `-c`, `--restore`, `--goal`, `-p`, …), so the fresh omp stays on the same model and session directory.
145
153
 
@@ -153,7 +161,7 @@ In both modes:
153
161
  - While a rollover is pending (no fresh note, own jobs still running, or the handoff is ready and waiting for idle), Main cannot start new subagents: a `task` call is refused until the running jobs finish and the session rolls over.
154
162
  - While own jobs (subagents included) are still running, the switch waits: a rollover would cancel them.
155
163
  - While a rollover is pending, the stop guard does not apply: Main may stop in `ready` or `wait-jobs`, and in `need-note` the stop is blocked only by the note request.
156
- - `/main-rollover <message>` does the same by hand. It refuses below the threshold, without a fresh note, or while jobs run. Under neurastream main it is refused and the owner's next message starts the rollover; in plain omp a second call while one waits adds its text to the same handoff.
164
+ - `/main-rollover <message>` does the same by hand. It refuses below the threshold, without a fresh note, or while jobs run. Under neurastream main it is refused and the owner's next message starts the rollover.
157
165
  - `/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.
158
166
  - The previous session file stays where it is.
159
167
  - `rollover.enabled: false` turns the feature off.
@@ -348,9 +356,9 @@ Five sources feed it:
348
356
  - Daily: at the first main-start or Main prompt of a day, M1-M5 for the last 24 hours against the mean of the 7 days before; a metric worse by `incidents.daily_worse_pct` and above its `incidents.daily_floor` floor is an incident.
349
357
  - Weekly: when the metrics report is due, the code writes `<paths.notes>/metrics.md` itself and its worst ranked metric becomes an incident.
350
358
  - Main itself: `neurastream incident add "<summary>" --kind <k>`.
351
- - A subagent's plan work: every new `## Progress` entry in a plan ends with a `Findings:` line (`Findings: none`, or one item per finding — bug, workaround, improvement, any repo — with `file:line` evidence, items separated by `;`). The plan-guard refuses and restores an entry without the line, and each item of an allowed edit becomes an incident (source `findings`, evidence = plan path + agent); the same text again dedupes into the open incident.
359
+ - A plan's Findings lines, a subagent's or Main's own: every new `## Progress` entry in a plan ends with a `Findings:` line (`Findings: none`, or one item per finding — bug, workaround, improvement, any repo — with `file:line` evidence, items separated by `;`). The plan-guard refuses and restores an entry without the line, and each item of an allowed edit becomes an incident (source `findings`; a subagent's item is kind `agent-finding`, Main's own kind `main-finding`; evidence = plan path + agent); the same text again dedupes into the open incident. The plan the entry is written in does not count as planning its finding — planning is `neurastream incident plan`.
352
360
 
353
- While an incident is open (no plan, dismissal or fixed record), every Main prompt carries one `INCIDENT <id> [<source>/<kind>]: <summary>` line per open incident, Main's `task` spawns and bypass launches are refused unless the brief names a plan citing `INCIDENT <id>`, and Main cannot stop with an incident that has neither. The loop closes three ways: `neurastream incident plan <id> <plan.md>` (the plan must exist, be listed in the main index, cite `INCIDENT <id>`, and carry a fail-before phase — its regression test has to fail on the old code), `neurastream incident dismiss <id> --why "<text>"`, and `fixed` — written by the queue itself when it closes a plan that cites the incident. `neurastream metrics report` shows M6: incidents opened / planned / dismissed / fixed and the median hours from open to fixed.
361
+ While an incident is open (no plan, dismissal or fixed record), every Main prompt carries one `INCIDENT <id> [<source>/<kind>]: <summary>` line per open incident, Main's `task` spawns and bypass launches are refused unless the brief names a plan citing `INCIDENT <id>`, and Main cannot stop with an incident that has neither. A stop reply that only offers to plan is refused too: the reply Main stops with is matched against `guards.plan_offer` (case-insensitive; "want me to write a plan?", "should I plan") and a hit answers "don't offer it — write the plan and index it" — the two-idle-stops release does not lift that block. The loop closes three ways: `neurastream incident plan <id> <plan.md>` (the plan must exist, be listed in the main index, cite `INCIDENT <id>`, and carry a fail-before phase — its regression test has to fail on the old code), `neurastream incident dismiss <id> --why "<text>"` (a finding incident — `agent-finding` or `main-finding` — is dismissed only with the owner's own words: `--owner "<quote>"`, a substring of an owner message the inject hook saw in the last 24 h, so the agent that found the bug cannot also wave it away), and `fixed` — written by the queue itself when it closes a plan that cites the incident. `neurastream metrics report` shows M6: incidents opened / planned / dismissed / fixed and the median hours from open to fixed.
354
362
 
355
363
  ## Changing a script
356
364
 
@@ -365,11 +373,10 @@ Live copies are never hand-edited. `neurastream doctor` names each hand-edited i
365
373
 
366
374
  ## AGENTS.md block
367
375
 
368
- `adapter install omp` writes the neurastream orchestrator rules into `~/.omp/agent/AGENTS.md`, between the markers `<!-- neurastream:begin (managed by neurastream; edit the package, not this block) -->` and `<!-- neurastream:end -->`. The rules come from `templates/AGENTS.md`; the agent dir comes from your config.
376
+ Main's rules are not written into `~/.omp/agent/AGENTS.md`. Under `neurastream main` they ride Main's system prompt on each turn, built from `templates/AGENTS.md` with the agent dir from your config. Install strips a block an older install left between the markers `<!-- neurastream:begin (managed by neurastream; edit the package, not this block) -->` and `<!-- neurastream:end -->`.
369
377
 
370
- - Managed: the text between the markers. Install replaces it. A second install changes nothing.
371
- - Yours: every line outside the markers. Install keeps it byte for byte. A file with no markers gets the block appended.
372
- - Drift: `neurastream doctor` reports `stale:` when the text between the markers differs from the package's block, and `missing:` when the markers are absent. Edits outside the markers are never reported.
378
+ - Yours: every line outside the markers. Install keeps it byte for byte; a file the strip leaves empty is removed.
379
+ - Leftover: markers still in the file, malformed ones included. Install leaves them alone; `neurastream doctor` reports `stale: neurastream block still in <file>`.
373
380
  - Edit limit: the project-file changes Main gets per window come from the config, not from the block text: `guards.main_edit_limit` per `guards.main_window_min` in tier `opinionated`, `autonomy.strict_edit_limit` in tier `strict`, no cap in tier `full`.
374
381
 
375
382
  ## Project rules
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.40",
3
+ "version": "0.2.42",
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",
@@ -9,7 +9,7 @@ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSyn
9
9
  import { homedir } from "node:os";
10
10
  import { dirname, join, relative, resolve } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
- import { blockState, renderBlock } from "../../core/agents-md.ts";
12
+ import { stripBlock } from "../../core/agents-md.ts";
13
13
  import { loadConfig } from "../../core/config.ts";
14
14
  import { notifyFindings } from "../../core/notify.ts";
15
15
  import { loadKnownSecrets, proxyOnPath } from "../../core/secret-redact.ts";
@@ -211,9 +211,9 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
211
211
  : [];
212
212
  if (repoDirs.length)
213
213
  problems.push(`${idx} still lists ${repoDirs.length} repo director${repoDirs.length === 1 ? "y" : "ies"} (${repoDirs.join(", ")}); run neurastream queue migrate`);
214
- const state = blockState(text, renderBlock(cfg));
215
- if (state === "ok") ok.push(`${agents} neurastream block`);
216
- else problems.push(`${state}: ${agents} neurastream block`);
214
+ // The block is no longer written here: markers left in the owner's file are stale.
215
+ if (stripBlock(text).state === "missing") ok.push(`${agents} no neurastream block`);
216
+ else problems.push(`stale: neurastream block still in ${agents}`);
217
217
  const warnings: string[] = [];
218
218
  const notify = notifyFindings(cfg);
219
219
  problems.push(...notify.problems);
@@ -19,7 +19,7 @@ import { execFileSync, spawn } from "node:child_process";
19
19
  import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
20
  import { basename, dirname, join, resolve } from "node:path";
21
21
  import type { Decision } from "../../core/adapter.ts";
22
- import { AGENTS_TEMPLATE } from "../../core/agents-md.ts";
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";
@@ -37,7 +37,7 @@ import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
37
37
  import { readBlocks } from "../../core/metrics.ts";
38
38
  import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
39
39
  import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
40
- import { adapterLog } from "./launch.ts";
40
+ import { adapterLog, MAIN_ENV } from "./launch.ts";
41
41
  import { parseTraceFile } from "./traces.ts";
42
42
  import { packageJsonPath, packageVersion } from "./package-root.ts";
43
43
  import * as q from "../../core/queue/lib.ts";
@@ -552,6 +552,8 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
552
552
  export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
553
553
  // The queue library resolves its paths from env snapshots; point them at this config first.
554
554
  applyQueueEnv(cfg);
555
+ // Main's rules ride its system prompt each turn; they are never written into the owner's AGENTS.md.
556
+ const mainRules = renderBlock(cfg);
555
557
 
556
558
  let callsSinceStop = 0;
557
559
  let idleStops = 0;
@@ -795,7 +797,9 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
795
797
  if (r && rulesChanged(cfg, asString(c.id) || "main", r.path, r.text)) rules.push(`Repo rules (${r.path}):\n${r.text}`);
796
798
  }
797
799
  pendingRules.clear();
800
+ const hostPrompt = asRecord(event).systemPrompt;
798
801
  return {
802
+ systemPrompt: [...(Array.isArray(hostPrompt) ? hostPrompt : []), mainRules],
799
803
  message: {
800
804
  customType: "main-guard.queue",
801
805
  content: [d.inject, notice, ...rules].filter(Boolean).join("\n\n"),
@@ -992,15 +996,14 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
992
996
  }
993
997
  if (snap.state === "ready" || snap.state === "wait-jobs") {
994
998
  adapterLog(cfg, `ALLOW stop: rollover ${snap.state}`);
995
- // Under the launcher a ready rollover starts now (not a hand-back to the owner);
996
- // plain omp waits for the owner's next message.
997
- const handsToOwner = !(snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && requestRelaunch(rc, notePath(rc.sessionId)));
999
+ // Under the launcher a ready rollover starts now (not a hand-back to the owner).
1000
+ const handsToOwner = !(snap.state === "ready" && requestRelaunch(rc, notePath(rc.sessionId)));
998
1001
  if (handsToOwner) notifyHandback(reply, "allowed session_stop");
999
1002
  else adapterLog(cfg, "notify: skipped (relaunch requested)");
1000
1003
  return undefined;
1001
1004
  }
1002
1005
  }
1003
- const d = checkStop({ agent: "main", callsSinceStop, idleStops, ledgerText: ledgerText(cfg) }, cfg);
1006
+ const d = checkStop({ agent: "main", callsSinceStop, idleStops, ledgerText: ledgerText(cfg), reply: reply?.text ?? undefined }, cfg);
1004
1007
  callsSinceStop = d.state?.callsSinceStop ?? 0;
1005
1008
  idleStops = d.state?.idleStops ?? idleStops;
1006
1009
  if (d.allow) {
@@ -1058,7 +1061,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1058
1061
  // The note request for a state. A stale install names both versions in place of the size line.
1059
1062
  const noteRequestFor = (c: RolloverCtx, snap: { stale: boolean; liveVersion: string | null }): string => {
1060
1063
  const reason = snap.stale ? `neurastream on disk is ${snap.liveVersion ?? "unknown"}, this session runs ${loadedVersion ?? "unknown"}` : undefined;
1061
- return noteRequest(notePath(c.sessionId), process.env.NEURASTREAM_MAIN_LAUNCHER === "1", reason);
1064
+ return noteRequest(notePath(c.sessionId), reason);
1062
1065
  };
1063
1066
 
1064
1067
  let relaunched = false;
@@ -1081,12 +1084,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1081
1084
  };
1082
1085
  };
1083
1086
 
1084
- // One /main-rollover at a time: while one waits for idle, a second call adds its text to the owner message.
1087
+ // One in-process rollover at a time: while it waits for idle, the size check must not start
1088
+ // a relaunch over it.
1085
1089
  let flight: string[] | null = null;
1086
1090
 
1087
- // The one in-process rollover, shared by /main-rollover and the exit-grace fallback: gather the
1088
- // generated state, wait for idle, then start a fresh session whose first message is the handoff.
1089
- // A state change during the wait sends the owner's text to this session as an ordinary message.
1091
+ // The one in-process rollover, the exit-grace fallback: gather the generated state, wait for
1092
+ // idle, then start a fresh session whose first message is the handoff. A state change during
1093
+ // the wait sends the owner's text to this session as an ordinary message.
1090
1094
  const rolloverInProcess = async (c: RolloverCtx, owner: string[], notice: string): Promise<void> => {
1091
1095
  const previous = c.sessionFile;
1092
1096
  const path = notePath(c.sessionId);
@@ -1186,8 +1190,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1186
1190
  { customType: "main-guard.rollover", content: noteRequestFor(c, snap), display: false },
1187
1191
  { triggerTurn: true, deliverAs: "nextTurn" },
1188
1192
  );
1189
- } else if (terminal && snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && !relaunched && flight === null) {
1190
- // flight !== null: an in-process rollover (fallback or /main-rollover) owns this session's end.
1193
+ } else if (terminal && snap.state === "ready" && !relaunched && flight === null) {
1194
+ // flight !== null: an in-process rollover (the fallback) owns this session's end.
1191
1195
  requestRelaunch(c, notePath(c.sessionId));
1192
1196
  } else if (terminal && relaunched) {
1193
1197
  // A tool result mid-run never restarts the session (I-20261024-4), and omp's interactive
@@ -1401,67 +1405,43 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1401
1405
  return changed ? { messages: mapped } : undefined;
1402
1406
  });
1403
1407
 
1404
- // Under the launcher the relaunch is the only rollover path: a plain interactive message in the ready
1405
- // state requests it, and every such message joins the pending request's draft, in order. Plain omp keeps
1406
- // `/main-rollover <text>`: the message becomes the owner's first message of the new session.
1408
+ // The relaunch is the only rollover path: a plain interactive message in the ready state
1409
+ // requests it, and every such message joins the pending request's draft, in order.
1407
1410
  pi.on("input", (event, ctx) => {
1408
1411
  const e = asRecord(event);
1409
1412
  const c = asRolloverCtx(ctx);
1410
1413
  const text = asString(e.text);
1411
1414
  if (!cfg.rollover.enabled || !c || !isMain(ctx)) return undefined;
1412
1415
  if (asString(e.source) !== "interactive" || text === "" || text.startsWith("/")) return undefined;
1413
- if (process.env.NEURASTREAM_MAIN_LAUNCHER === "1") {
1414
- if (!relaunched) {
1415
- if (rolloverSnapshot(c).state !== "ready") return undefined;
1416
- // The message is the request's first owner text, so the editor draft is not carried.
1417
- if (!requestRelaunch(c, notePath(c.sessionId), "")) return undefined;
1418
- }
1419
- if (appendToRelaunch(text)) c.notify("rollover in progress: your message goes to the new session");
1420
- else c.notify("rollover in progress: your message could not be saved and was not sent; send it again after the rollover");
1421
- // omp re-checks its deferred exit only when shutdown() is called again: re-arm per message.
1422
- c.shutdown();
1423
- return { handled: true };
1416
+ if (!relaunched) {
1417
+ if (rolloverSnapshot(c).state !== "ready") return undefined;
1418
+ // The message is the request's first owner text, so the editor draft is not carried.
1419
+ if (!requestRelaunch(c, notePath(c.sessionId), "")) return undefined;
1424
1420
  }
1425
- if (rolloverSnapshot(c).state !== "ready") return undefined;
1426
- return { text: `/main-rollover ${text}` };
1421
+ if (appendToRelaunch(text)) c.notify("rollover in progress: your message goes to the new session");
1422
+ else c.notify("rollover in progress: your message could not be saved and was not sent; send it again after the rollover");
1423
+ // omp re-checks its deferred exit only when shutdown() is called again: re-arm per message.
1424
+ c.shutdown();
1425
+ return { handled: true };
1427
1426
  });
1428
1427
 
1429
- // One /main-rollover at a time: while one waits for idle, a second call adds its text to the owner message.
1428
+ // The rollover starts on its own (size + idle), and the owner's next message joins the
1429
+ // pending relaunch; the command only says so.
1430
1430
  pi.registerCommand("main-rollover", {
1431
1431
  description: "Start a fresh session from Main's handoff note; the rest of the message is the owner's first message",
1432
- handler: async (args: unknown, ctx: unknown) => {
1432
+ handler: async (_args: unknown, ctx: unknown) => {
1433
1433
  const c = asRolloverCtx(ctx);
1434
1434
  if (!c) return;
1435
- const text = asString(args);
1436
- if (process.env.NEURASTREAM_MAIN_LAUNCHER === "1") {
1437
- c.notify("main-rollover: under neurastream main the rollover starts from your next message, not from this command.");
1438
- return;
1439
- }
1440
- if (flight) {
1441
- flight.push(text);
1442
- c.notify("main-rollover: a rollover is already in progress; your message is added to its handoff.");
1443
- return;
1444
- }
1445
- const path = notePath(c.sessionId);
1446
- const state = rolloverSnapshot(c).state;
1447
- if (state === "below") {
1448
- c.notify("main-rollover: this session is below rollover.max_session_mb; nothing to roll over.");
1449
- return;
1450
- }
1451
- if (state === "need-note") {
1452
- c.notify(`main-rollover: no fresh handoff note at ${path}; Main must write it first.`);
1453
- return;
1454
- }
1455
- if (state === "wait-jobs") {
1456
- c.notify(`main-rollover: own jobs are still running (${c.runningJobs().join(", ")}); a rollover would cancel them.`);
1457
- return;
1458
- }
1459
- await rolloverInProcess(c, [text], "main-rollover: collecting main-start state for the handoff (this can take a minute)…");
1435
+ c.notify("main-rollover: under neurastream main the rollover starts from your next message, not from this command.");
1460
1436
  },
1461
1437
  });
1462
1438
  }
1463
1439
 
1464
1440
  /** package.json omp.extensions entry. */
1465
1441
  export default function ompExtension(pi: ExtensionHost): void {
1442
+ // The one switch (MAIN_ENV): plain `omp` runs nothing of neurastream — no hook, no command,
1443
+ // no config read. `neurastream main` sets it for its child (launch.ts), so anything the Main
1444
+ // session spawns inherits it and stays guarded.
1445
+ if (process.env[MAIN_ENV] !== "1") return;
1466
1446
  createOmpAdapter(pi, loadConfig());
1467
1447
  }
@@ -7,8 +7,8 @@ import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, re
7
7
  import { homedir } from "node:os";
8
8
  import { dirname, join, resolve } from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
- import { renderBlock, upsertBlock } from "../../core/agents-md.ts";
11
- import { configFile, loadConfig } from "../../core/config.ts";
10
+ import { stripBlock } from "../../core/agents-md.ts";
11
+ import { configFile } from "../../core/config.ts";
12
12
 
13
13
  import { adapterLiveFiles, liveAgentsMd } from "./doctor.ts";
14
14
  // Registers the plugin-command matcher into core's writeTargets (side effect).
@@ -39,7 +39,7 @@ export interface InstallResult {
39
39
  /** Left alone: not interactive, or answered no. */
40
40
  skillsSkipped: string[];
41
41
  overlay: "written" | "unchanged";
42
- agentsMd: "written" | "unchanged";
42
+ agentsMd: "removed" | "unchanged";
43
43
  }
44
44
 
45
45
  function ensureLink(link: string, target: string): void {
@@ -280,15 +280,17 @@ export function writeOverlay(file: string): "written" | "unchanged" {
280
280
  return "written";
281
281
  }
282
282
 
283
- // Writes the managed block into the owner's AGENTS.md: the rest of the file is never touched.
284
- function writeAgentsMd(home: string): "written" | "unchanged" {
283
+ // Strips the managed block an older install wrote into the owner's AGENTS.md: Main gets the rules
284
+ // in its system prompt now. Bytes outside the markers stay; a file the strip leaves empty is removed.
285
+ // A malformed block is left alone; doctor reports it.
286
+ function removeAgentsMd(home: string): "removed" | "unchanged" {
285
287
  const file = liveAgentsMd(home);
286
- const current = existsSync(file) ? readFileSync(file, "utf8") : "";
287
- const next = upsertBlock(current, renderBlock(loadConfig({ home })));
288
- if (next === current) return "unchanged";
289
- mkdirSync(dirname(file), { recursive: true });
290
- writeFileSync(file, next);
291
- return "written";
288
+ if (!existsSync(file)) return "unchanged";
289
+ const { text, state } = stripBlock(readFileSync(file, "utf8"));
290
+ if (state !== "ok") return "unchanged";
291
+ if (text === "") unlinkSync(file);
292
+ else writeFileSync(file, text);
293
+ return "removed";
292
294
  }
293
295
 
294
296
  function linkPlugin(home: string): string {
@@ -331,7 +333,7 @@ export function installOmp(home: string, ask: ((question: string) => string) | n
331
333
  linkInstalled(home);
332
334
  const plugin = linkPlugin(home);
333
335
  const overlay = writeOverlay(file);
334
- const agentsMd = writeAgentsMd(home);
336
+ const agentsMd = removeAgentsMd(home);
335
337
  const skills = syncSkills(home, ask);
336
338
  return {
337
339
  plugin,
@@ -26,6 +26,13 @@ export function adapterLog(cfg: Config, line: string): void {
26
26
  /** The harness the launcher runs. Tests pass another path through LaunchOptions. */
27
27
  export const OMP_BIN = "omp";
28
28
 
29
+ /**
30
+ * The one main-only switch, and why an env var and not a flag or config key: children inherit
31
+ * the environment, so a tool starting `omp` from inside a Main session stays guarded — a flag
32
+ * would not travel. The adapter is dead without it (ompExtension in ./index.ts).
33
+ */
34
+ export const MAIN_ENV = "NEURASTREAM_MAIN_LAUNCHER";
35
+
29
36
  export interface ProxyPlan {
30
37
  /** The command to spawn. */
31
38
  cmd: string;
@@ -171,7 +178,8 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
171
178
  }
172
179
  for (;;) {
173
180
  const started = Date.now();
174
- const code = await runChild(proxy.cmd, [...proxy.prefix, ...runArgs], { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" });
181
+ // The env, not a flag: the child inherits it, so an omp started from inside Main stays guarded.
182
+ const code = await runChild(proxy.cmd, [...proxy.prefix, ...runArgs], { ...process.env, [MAIN_ENV]: "1" });
175
183
  const req = readRequest(started, cfg);
176
184
  if (req === null) return code;
177
185
  const installed = packageVersion(packageJsonPath());
package/src/cli/guard.ts CHANGED
@@ -78,6 +78,9 @@ function decide(event: string, p: Record<string, unknown>, cfg: Config): Decisio
78
78
  callsSinceStop: asNumber(p.callsSinceStop),
79
79
  idleStops: asNumber(p.idleStops),
80
80
  ledgerText: asString(p.ledgerText),
81
+ // P5 (20261028_0900, I-20261028-67): non-omp harnesses reach the plan-offer block
82
+ // through this CLI, so the reply text travels like the omp adapter's does.
83
+ ...(p.reply === undefined ? {} : { reply: asString(p.reply) }),
81
84
  };
82
85
  return checkStop(e, cfg);
83
86
  }
@@ -17,7 +17,7 @@ export const INCIDENT_USAGE = [
17
17
  "usage: neurastream incident list [--open] [--json]",
18
18
  ' neurastream incident add "<summary>" --kind <k> [--evidence <text>]',
19
19
  " neurastream incident plan <id> <plan.md>",
20
- ' neurastream incident dismiss <id> --why "<text>"',
20
+ ' neurastream incident dismiss <id> --why "<text>" [--owner "<quote>"]',
21
21
  ].join("\n");
22
22
 
23
23
  function flagValue(args: string[], name: string): string | undefined {
@@ -77,12 +77,12 @@ export function planIncidentCmd(cfg: Config, id: string, planPath: string): numb
77
77
  return 0;
78
78
  }
79
79
 
80
- export function dismissIncidentCmd(cfg: Config, id: string, why: string | undefined): number {
80
+ export function dismissIncidentCmd(cfg: Config, id: string, why: string | undefined, owner: string | undefined): number {
81
81
  if (!id || why === undefined) {
82
82
  console.error(INCIDENT_USAGE);
83
83
  return 2;
84
84
  }
85
- const problem = dismissIncident(cfg, id, why);
85
+ const problem = dismissIncident(cfg, id, why, owner);
86
86
  if (problem) {
87
87
  console.error(problem);
88
88
  return 1;
@@ -103,7 +103,7 @@ export async function runIncident(args: string[]): Promise<number> {
103
103
  if (sub === "list") return listIncidents(cfg, rest);
104
104
  if (sub === "add") return addIncidentCmd(cfg, rest);
105
105
  if (sub === "plan") return planIncidentCmd(cfg, rest[0] ?? "", rest[1] ?? "");
106
- if (sub === "dismiss") return dismissIncidentCmd(cfg, rest[0] ?? "", flagValue(rest, "--why"));
106
+ if (sub === "dismiss") return dismissIncidentCmd(cfg, rest[0] ?? "", flagValue(rest, "--why"), flagValue(rest, "--owner"));
107
107
  console.error(INCIDENT_USAGE);
108
108
  return 2;
109
109
  }
@@ -135,6 +135,8 @@ export interface StopEvent {
135
135
  callsSinceStop: number;
136
136
  idleStops: number;
137
137
  ledgerText: string;
138
+ /** The reply text Main is stopping with, when the harness has it (20261028_0900 P2: a reply that offers to plan instead of planning refuses the stop). */
139
+ reply?: string;
138
140
  }
139
141
 
140
142
  export const GUARD_EVENTS = ["pre-tool", "inject", "spawn", "plan-edit", "stop"] as const;
@@ -1,6 +1,6 @@
1
- // The managed block in the owner's AGENTS.md. The rules come from templates/AGENTS.md with the
2
- // config's agent dir filled in; they sit between two markers, and only what is between them is
3
- // ever written or checked against the package's block. Everything outside the markers stays the owner's.
1
+ // The managed block: the rules from templates/AGENTS.md with the config's agent dir filled in,
2
+ // between two markers. Main puts them in its system prompt; install only strips an old copy from
3
+ // the owner's AGENTS.md, and everything outside the markers stays the owner's.
4
4
 
5
5
  import { readFileSync } from "node:fs";
6
6
  import { dirname, join } from "node:path";
@@ -37,29 +37,8 @@ function span(text: string): { start: number; end: number } | null {
37
37
  return { start: begin, end: end + END_MARK.length };
38
38
  }
39
39
 
40
- // Replace the marked block, or append one when the file has none. Bytes outside the markers are kept.
41
- export function upsertBlock(fileText: string, block: string): string {
42
- const at = span(fileText);
43
- if (at) return fileText.slice(0, at.start) + block + fileText.slice(at.end);
44
- if (fileText === "") return `${block}\n`;
45
- return `${fileText}\n${block}\n`;
46
- }
47
-
48
- // "missing": no block in the file. "stale": the block differs, or its markers are malformed.
49
- export function blockState(fileText: string, block: string): "ok" | "stale" | "missing" {
50
- let at: { start: number; end: number } | null;
51
- try {
52
- at = span(fileText);
53
- } catch {
54
- return "stale";
55
- }
56
- if (!at) return "missing";
57
- return fileText.slice(at.start, at.end) === block ? "ok" : "stale";
58
- }
59
-
60
- // Remove the marked block, keeping every byte outside the markers (uninstall's inverse of
61
- // upsertBlock). "missing": there was no block. "stale": the markers are malformed — the text
62
- // comes back untouched.
40
+ // Remove the marked block, keeping every byte outside the markers. "missing": there was no block.
41
+ // "stale": the markers are malformed, and the text comes back untouched.
63
42
  export function stripBlock(fileText: string): { text: string; state: "ok" | "stale" | "missing" } {
64
43
  let at: { start: number; end: number } | null;
65
44
  try {
@@ -119,6 +119,8 @@ export interface Config {
119
119
  chat_unlock: boolean;
120
120
  plan_read_max_hours: number;
121
121
  idle_stops: number;
122
+ /** A Main stop reply matching this regex (case-insensitive) offers to plan instead of planning; the stop is refused (20261028_0900 P2). */
123
+ plan_offer: string;
122
124
  /** Provider rate limits (src/core/rate-limit.ts): a turn that ends on one waits it out instead of
123
125
  * asking again straight into the limit. The words and the waits come from here. */
124
126
  rate_limit: {
@@ -435,6 +437,14 @@ function check(cfg: Config): void {
435
437
  if (cfg.guards.sub_max_calls_cap < cfg.guards.sub_max_calls) {
436
438
  throw new ConfigError("guards.sub_max_calls_cap must be >= guards.sub_max_calls");
437
439
  }
440
+ if (typeof cfg.guards.plan_offer !== "string" || cfg.guards.plan_offer === "") {
441
+ throw new ConfigError("guards.plan_offer must be a non-empty regex string");
442
+ }
443
+ try {
444
+ new RegExp(cfg.guards.plan_offer, "i");
445
+ } catch {
446
+ throw new ConfigError(`guards.plan_offer: not a valid regex: ${cfg.guards.plan_offer}`);
447
+ }
438
448
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
439
449
  if (cfg.autonomy.tier !== "strict" && cfg.autonomy.tier !== "opinionated" && cfg.autonomy.tier !== "full")
440
450
  throw new ConfigError('autonomy.tier must be "strict", "opinionated" or "full"');
@@ -28,7 +28,7 @@ import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolE
28
28
  import { currentTier, takeGo, type Tier } from "./autonomy.ts";
29
29
  import { approvalProblem } from "./plan-approval.ts";
30
30
  import type { Config } from "./config.ts";
31
- import { addIncident, openIncidents, type IncidentView } from "./incidents.ts";
31
+ import { addIncident, openIncidents, ownerMessagesFile, ownerSaid, readOwnerMessages, type IncidentView, type OwnerMessage } from "./incidents.ts";
32
32
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
33
33
  import * as q from "./queue/lib.ts";
34
34
  import type { Plan } from "./queue/lib.ts";
@@ -103,29 +103,8 @@ function staffingFile(): string {
103
103
  return path.join(q.STATE_DIR, "staffing.json");
104
104
  }
105
105
 
106
- export interface OwnerMessage {
107
- at: number;
108
- text: string;
109
- }
110
-
111
- function ownerMessagesFile(): string {
112
- return path.join(q.STATE_DIR, "owner-messages.jsonl");
113
- }
114
-
115
- function readOwnerMessages(): OwnerMessage[] {
116
- try {
117
- return readFileSync(ownerMessagesFile(), "utf8").split("\n").filter(Boolean)
118
- .map(line => JSON.parse(line) as OwnerMessage);
119
- } catch {
120
- return [];
121
- }
122
- }
123
-
124
- export function ownerSaid(words: string, messages: OwnerMessage[], now: number): boolean {
125
- const quote = words.toLowerCase().replace(/\s+/g, " ").trim();
126
- if (quote.split(" ").length < 4) return false;
127
- return messages.some(m => now - m.at >= 0 && now - m.at <= 86400 && m.text.toLowerCase().replace(/\s+/g, " ").includes(quote));
128
- }
106
+ // The owner-message store (owner-messages.jsonl) and its matcher live in src/core/incidents.ts
107
+ // (20261028_0900 P3): dismissIncident needs them too, and guards already imports incidents.
129
108
 
130
109
  function recordOwnerMessage(text: string, cfg: Config): void {
131
110
  if (text.trimStart().startsWith("main-guard:") || text.trimStart().startsWith("<system-notice>") || text.includes("<task-result")) return;
@@ -1126,18 +1105,20 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1126
1105
  }
1127
1106
 
1128
1107
  /**
1129
- * Each finding item of an allowed subagent edit becomes an incident (source "findings", kind
1130
- * "agent-finding", evidence = plan path + agent; the default fingerprint dedupes the same item
1131
- * text). A store failure is logged and swallowed: it must not break the verified edit.
1108
+ * Each finding item of an allowed plan edit becomes an incident (source "findings", evidence =
1109
+ * plan path + agent; the default fingerprint dedupes the same item text). A subagent's items are
1110
+ * kind "agent-finding"; Main's own are kind "main-finding" (20261028_0900 P1: a bug Main writes
1111
+ * down must block the stop like a subagent's). A store failure is logged and swallowed: it must
1112
+ * not break the verified edit.
1132
1113
  */
1133
- function recordFindings(e: PlanEditEvent, cfg: Config): void {
1114
+ function recordFindings(e: PlanEditEvent, cfg: Config, kind: "agent-finding" | "main-finding" = "agent-finding"): void {
1134
1115
  try {
1135
1116
  const evidence = `${e.path} (${e.agent})`;
1136
1117
  for (const block of newProgressEntries(e.before, e.after)) {
1137
1118
  const value = findingsValue(block);
1138
1119
  if (!value || /^none\.?$/i.test(value)) continue;
1139
1120
  for (const item of value.split(";")) {
1140
- if (item.trim()) addIncident(cfg, { source: "findings", kind: "agent-finding", summary: item.trim(), evidence });
1121
+ if (item.trim()) addIncident(cfg, { source: "findings", kind, summary: item.trim(), evidence });
1141
1122
  }
1142
1123
  }
1143
1124
  } catch (err) {
@@ -1181,7 +1162,10 @@ export function findingsValue(block: string): string | null {
1181
1162
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
1182
1163
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
1183
1164
  function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1184
- if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) return ALLOW;
1165
+ if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) {
1166
+ recordFindings(e, cfg, "main-finding");
1167
+ return ALLOW;
1168
+ }
1185
1169
  // A cited file Main did read lands in the list instead of the refusal (I-20261025-208): fix the
1186
1170
  // text first, then judge the fixed text like any other edit.
1187
1171
  const fix = autoListReads(e.after, e.path, cfg);
@@ -1191,6 +1175,7 @@ function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1191
1175
  const known = new Set(e.before ? planReadProblems(e.before, e.path, cfg) : []);
1192
1176
  const problems = planReadProblems(fixed, e.path, cfg).filter(p => p === NO_SECTION || !known.has(p));
1193
1177
  if (!problems.length) {
1178
+ recordFindings(e, cfg, "main-finding");
1194
1179
  if (!fix) return ALLOW;
1195
1180
  const list = fix.paths.join(", ");
1196
1181
  log(cfg.paths.plan_guard_log, `AUTO-LIST ${e.path}: ${list}`);
@@ -1373,6 +1358,12 @@ export function liveSubagents(ledgerOut: string): string[] {
1373
1358
  export function checkStop(e: StopEvent, cfg: Config): Decision {
1374
1359
  if (e.agent !== "main") return ALLOW;
1375
1360
  const state = { callsSinceStop: e.callsSinceStop, idleStops: e.idleStops };
1361
+ // 20261028_0900 P2: a reply that offers to plan instead of planning is refused for the offer
1362
+ // itself; the two-empty-stops valves below never release this block.
1363
+ if (e.reply && new RegExp(cfg.guards.plan_offer, "i").test(e.reply)) {
1364
+ log(cfg.paths.guard_log, "BLOCK stop: reply offers to plan instead of planning it");
1365
+ return { allow: false, reason: "main-guard: don't offer it — write the plan and index it", state };
1366
+ }
1376
1367
  let open: string[];
1377
1368
  try {
1378
1369
  open = openQueue();
@@ -195,14 +195,55 @@ export function planIncident(cfg: Config, id: string, planPath: string): string
195
195
  return null;
196
196
  }
197
197
 
198
- /** Records why an incident is not a bug (or not worth fixing); an empty why is refused. */
199
- export function dismissIncident(cfg: Config, id: string, why: string): string | null {
198
+ // The owner's own words, as the inject hook saw them (<queue_state>/owner-messages.jsonl, last
199
+ // 50 messages). Guards match quotes against them (priority skip, autonomy go); incidents dismiss
200
+ // a finding only with them (20261028_0900 P3).
201
+
202
+ /** The kinds plan-guard's recordFindings writes; only the owner's own words dismiss them. */
203
+ const FINDING_KINDS: Record<string, true> = { "agent-finding": true, "main-finding": true };
204
+
205
+ export interface OwnerMessage {
206
+ at: number;
207
+ text: string;
208
+ }
209
+
210
+ export function ownerMessagesFile(): string {
211
+ return join(q.STATE_DIR, "owner-messages.jsonl");
212
+ }
213
+
214
+ export function readOwnerMessages(): OwnerMessage[] {
215
+ try {
216
+ return readFileSync(ownerMessagesFile(), "utf8").split("\n").filter(Boolean)
217
+ .map(line => JSON.parse(line) as OwnerMessage);
218
+ } catch {
219
+ return [];
220
+ }
221
+ }
222
+
223
+ export function ownerSaid(words: string, messages: OwnerMessage[], now: number): boolean {
224
+ const quote = words.toLowerCase().replace(/\s+/g, " ").trim();
225
+ if (quote.split(" ").length < 4) return false;
226
+ return messages.some(m => now - m.at >= 0 && now - m.at <= 86400 && m.text.toLowerCase().replace(/\s+/g, " ").includes(quote));
227
+ }
228
+
229
+ /** Records why an incident is not a bug (or not worth fixing); an empty why is refused. A finding
230
+ * incident (kind "agent-finding"/"main-finding") is dismissed only with `owner` — a quote
231
+ * `ownerSaid` matches against the owner's own messages of the last 24 h (20261028_0900 P3: the
232
+ * agent that found the bug cannot also wave it away). */
233
+ export function dismissIncident(cfg: Config, id: string, why: string, owner?: string): string | null {
200
234
  const file = incidentsFile(cfg);
201
235
  const store = readStore(file);
202
- if (!store.incidents.some(i => i.id === id)) return `unknown incident ${id}`;
236
+ const rec = store.incidents.find(i => i.id === id);
237
+ if (!rec) return `unknown incident ${id}`;
203
238
  const res = store.resolutions.filter(r => r.id === id).at(-1);
204
239
  if (res) return `incident ${id} already has a ${res.type} record`;
205
240
  if (!why.trim()) return "refused: an empty --why would hide the incident without a recorded reason";
241
+ if (FINDING_KINDS[rec.kind]) {
242
+ if (owner === undefined)
243
+ return `refused: a ${rec.kind} is dismissed only with the owner's words: --owner "<quote>" (part of an owner message of the last 24 h)`;
244
+ if (!ownerSaid(owner, readOwnerMessages(), nowSec()))
245
+ return "refused: the --owner quote is not part of an owner message of the last 24 h";
246
+ }
206
247
  mkdirSync(dirname(file), { recursive: true });
207
248
  appendFileSync(file, `${JSON.stringify({ type: "dismiss", id, why })}\n`);
208
249
  return null;
@@ -112,7 +112,7 @@ export const OWNER_AWAY =
112
112
  "Owner away (automatic rollover). Continue the work in the note and the queue; the owner reads results later.";
113
113
 
114
114
  /** The one-time note instruction for Main's next turn. `reason` (a stale install) names both versions and replaces the size line. */
115
- export function noteRequest(path: string, auto = false, reason = ""): string {
115
+ export function noteRequest(path: string, reason = ""): string {
116
116
  return [
117
117
  reason
118
118
  ? `${NOTE_REQUEST_PREFIX} a new neurastream version is installed (${reason}).`
@@ -120,9 +120,7 @@ export function noteRequest(path: string, auto = false, reason = ""): string {
120
120
  `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.`,
121
121
  "Do not list holds or owner blockers in the note; they come from the plans' WAITING on owner lines.",
122
122
  "Do not state which agents or providers are rate-limited or free; that comes from agent-ledger --cap.",
123
- auto
124
- ? "As soon as this note is written and no own jobs run, this session restarts into a fresh one that starts from this note verbatim plus the generated main-start state."
125
- : "When the owner's next message arrives, this session closes and a fresh one starts from that note verbatim plus the generated main-start state.",
123
+ "As soon as this note is written and none of its own jobs are running, this session restarts into a fresh one that starts from this note verbatim plus the generated main-start state.",
126
124
  ].join("\n");
127
125
  }
128
126
 
@@ -122,6 +122,7 @@ guards:
122
122
  chat_unlock: false # the owner's whole chat message "unlock"/"unlock N"/"lock" moves the guard unlock file
123
123
  plan_read_max_hours: 24
124
124
  idle_stops: 3
125
+ plan_offer: 'want me to (write|make) a plan|should i plan|shall i plan|if you want, i(''ll)? plan|plan it or' # a Main stop reply matching this (case-insensitive) is refused: don't offer it — write the plan and index it
125
126
  rate_limit:
126
127
  patterns: ["429", "rate_limit", "rate limit", "overloaded", "529"] # error-text substrings (case-insensitive) that mark a provider rate limit
127
128
  default_wait_s: 300 # wait when the error text names no retry-after