neurastream 0.2.67 → 0.2.68

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
@@ -36,6 +36,7 @@ flowchart LR
36
36
  | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
37
37
  | 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. |
38
38
  | 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`. |
39
+ A request written by an older version in the legacy dir is still picked up: when the new-path file is missing or stale, the launcher falls back to the legacy `rollover/relaunch.json` (main id only) and clears both copies once consumed.
39
40
  | 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 (a finding carries Main's reason and False alarm / It's a bug buttons), 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. |
40
41
 
41
42
  ## Main vs plain omp
@@ -125,6 +126,12 @@ Owner rule: never write a plan when another agent is doing the research or readi
125
126
  - Spawn briefs: a brief must name an unticked phase id of the plan (for example `P4`). A brief that asks for research for a plan to be written is refused, quoting the owner rule.
126
127
  - Call budget: a `Call budget: <N>` line in a task brief (the task's own text, or the shared `context` of the same `task` call; the task's own line wins) gives that run a hard stop at N calls, with the warning N − (`guards.sub_max_calls` − `guards.sub_warn_calls`) calls in, floored at 1. At the stop only plan Progress reads and edits pass, as at the global limit. N must be between 10 and `guards.sub_max_calls_cap` (default 200) and the task must carry a `name` — the budget is keyed by it in `<queue_state>/spawn-budgets.json` — or the spawn is refused with the allowed range. A task without the line keeps the global warn 90 / stop 100, and the ledger flags a still-running sub `OVER-BUDGET` past its own N.
127
128
 
129
+ ## Planner mode
130
+
131
+ One owner word decides who writes the plans: `autonomy.planner` (default `main`), moved any time by the owner's whole chat message `planner main|delegated` when `guards.chat_unlock` is on, or by a config write of the key at the owner's terminal (`neurastream config set autonomy.planner delegated`, `neurastream setup`). `main` is today's rule: Main researches the code, writes the plan and lists what it read in `## Code read by Main`. `delegated` hands the plan to a planner subagent: an approved spawn whose brief carries `Planner role for <plan path>` binds the agent to that one plan, the plan carries a `Planner: <agent>` header, and the research and the `## Code read by Main` list are the planner's; Main routes the owner's asks to it, dispatches implementers, checks the outcomes (verify commands, CI, the reviewer's PASS) and lands, and does not read repo code to plan. Two refusals hold the line: while delegated, Main's create of a new plan file or rewrite of a plan's body is refused ("planner is delegated — route the ask to the planner agent"); while main, a Planner-role brief is refused ("planner mode is main").
132
+
133
+ The mode facts are owner-only and anchored: the guard baseline `<config dir>/guard-baseline` records the mode file's existence and bytes, the config file's own `autonomy.planner` and `paths.queue_state`, and its full bytes; every omp adapter event and the guard process's first load restore a non-owner edit (the value through the config editor, the bytes as the fallback), and only the owner's stampers write it — the chat command, a terminal write of a mode key, a clean shutdown. With no baseline the mode is `main`, and a `planner-mode` file in a state dir the baseline does not pin is deleted.
134
+
128
135
  ## Queue holds
129
136
 
130
137
  A plan parked for the owner has one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it>` (`blocked` and `why you` may be omitted). That line is the only hold, and only Main writes it (plan-guard refuses subagents). The queue summary shows it as a flag on the plan, cut at 80 characters. Compaction and the rollover handoff read the same lines through `ownerHolds`: the compaction context lists each `<plan file>: WAITING on owner: <text>` line (or `none`) and says any other "needs the owner" or "paused" claim is unverified; the handoff's generated state carries the same lines. Main does not keep holds in a handoff note. A plan header may also carry `Summary: <one or two plain sentences>` under Branch (`templates/queue/TEMPLATE.md`); old plans without it still pass `queue-check`, and the phone page uses that line as the queue card's summary.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.67",
3
+ "version": "0.2.68",
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",
@@ -20,7 +20,7 @@ import { appendFileSync, existsSync, mkdirSync, openSync, readFileSync, renameSy
20
20
  import { basename, dirname, extname, join, resolve } from "node:path";
21
21
  import type { Decision, TraceEvent } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
23
- import { chatGo, chatTier, type Tier } from "../../core/autonomy.ts";
23
+ import { chatGo, chatPlanner, chatTier, currentPlanner, plannerPin, stampPlannerMode, verifyPlannerMode, type Tier } from "../../core/autonomy.ts";
24
24
  import { chatApprove } from "../../core/plan-approval.ts";
25
25
  import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
26
26
  import { configFile, loadConfig, reloadingConfig, type Config } from "../../core/config.ts";
@@ -29,7 +29,7 @@ import { nowSec, strftime } from "../../core/clock.ts";
29
29
  import { runDetectors, type DetectorInput } from "../../core/incident-detectors.ts";
30
30
  import { fileClaimStore } from "../../core/claims.ts";
31
31
  import { appendOwnerAnswer, readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
32
- import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
32
+ import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, plannerSpawnPlan, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
33
33
  import { rateLimited } from "../../core/rate-limit.ts";
34
34
  import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
35
35
  import { appendMetric } from "../../core/metrics.ts";
@@ -53,6 +53,25 @@ import { annotateResetTimes } from "../../core/reset-time.ts";
53
53
  // Registers the plugin-command matcher into core's writeTargets (side effect).
54
54
  import "./package-ops.ts";
55
55
 
56
+ /**
57
+ * Re-reads the config, then holds the planner mode facts to the owner's baseline (P2 d): a
58
+ * non-owner write of the state file or of a mode key is reverted and the reverted config is
59
+ * re-read, so no handler ever acts on the dirt.
60
+ */
61
+ export function freshPlannerConfig(freshConfig: () => Config): Config {
62
+ const next = freshConfig();
63
+ const held = verifyPlannerMode(plannerPin(next));
64
+ if (!held.reverted) return next;
65
+ adapterLog(next, `planner mode: reverted a non-owner change (${held.hint ?? "config dirt"})`);
66
+ return freshConfig();
67
+ }
68
+
69
+ /** A clean shutdown stamps the state the verify pass just confirmed (P2 d). */
70
+ export function stampPlannerState(freshConfig: () => Config): void {
71
+ const cfg = freshPlannerConfig(freshConfig);
72
+ stampPlannerMode(plannerPin(cfg));
73
+ }
74
+
56
75
  /** TraceEvents of the newest Main session file (D8's input); [] when there is none or it cannot be read. */
57
76
  function defaultMainEvents(cfg: Config): TraceEvent[] {
58
77
  try {
@@ -289,8 +308,9 @@ function writeCheckSnapshot(tool: string, input: Record<string, unknown>, cwd: s
289
308
 
290
309
  // Plan files a subagent write/edit may touch: snapshot before the call so tool_result can verify
291
310
  // and restore (the original snapshotted inside checkCall; core returns pure decisions now).
292
- function snapshotPlans(tool: string, input: Record<string, unknown>, cwd: string, snap: Map<string, string>, main: boolean): void {
311
+ function snapshotPlans(tool: string, input: Record<string, unknown>, cwd: string, snap: Map<string, string>, main: boolean, plannerPlan: string | null, cfg: Config): void {
293
312
  if (tool !== "write" && tool !== "edit") return;
313
+ const delegated = currentPlanner(cfg) === "delegated";
294
314
  const plans = q.activePlans();
295
315
  for (const p of q.writeTargets(tool, input, cwd)) {
296
316
  if (snap.has(p)) continue;
@@ -304,7 +324,12 @@ function snapshotPlans(tool: string, input: Record<string, unknown>, cwd: string
304
324
  }
305
325
  continue;
306
326
  }
307
- if (!q.isOrchestrationPath(p, plans) || !q.planAt(p, plans)) continue;
327
+ if (!q.isOrchestrationPath(p, plans) || !q.planAt(p, plans)) {
328
+ // planner mode P2 (b): the brief's named plan snapshots before its create/edit so
329
+ // checkPlanEdit judges it (Planner header, Main-only lines) — a new plan file is not
330
+ // an indexed path yet, and every other plan write is refused pre-tool while delegated.
331
+ if (!(delegated && p === plannerPlan)) continue;
332
+ }
308
333
  try {
309
334
  snap.set(p, readFileSync(p, "utf8"));
310
335
  } catch {}
@@ -620,6 +645,8 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
620
645
  let cfg = initial;
621
646
  // The queue library resolves its paths from env snapshots; point them at this config first.
622
647
  applyQueueEnv(cfg);
648
+ // P2 d: the first seam — a mode fact another writer left behind is reverted before any handler runs.
649
+ cfg = freshPlannerConfig(freshConfig);
623
650
  // P5: seed the per-Main inbox floor once — a Main that has never delivered starts past rows
624
651
  // that predate its registration; the pre-multi-main cursor file belongs to the default id's
625
652
  // first start. Later reads/writes own the file, so the floor is only a creation-time default.
@@ -917,7 +944,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
917
944
  };
918
945
 
919
946
  pi.on("before_agent_start", (event, ctx) => {
920
- cfg = freshConfig();
947
+ cfg = freshPlannerConfig(freshConfig);
921
948
  const c = asCtx(ctx);
922
949
  const prompt = asString(asRecord(event).prompt);
923
950
  if (c.kind !== "main") {
@@ -963,7 +990,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
963
990
  // The spawn event carries no brief, so the plan gate runs at the task tool call (original
964
991
  // behaviour); here only the allow-list and the task-only rule apply, with the original texts.
965
992
  pi.on("before_subagent_spawn", (event, _ctx) => {
966
- cfg = freshConfig();
993
+ cfg = freshPlannerConfig(freshConfig);
967
994
  const agent = asString(asRecord(event).agent);
968
995
  const kind = asString(asRecord(event).invocationKind);
969
996
  if (!q.allowedAgents().has(agent))
@@ -976,7 +1003,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
976
1003
  let lastMainRc: RolloverCtx | null = null;
977
1004
 
978
1005
  pi.on("tool_call", (event, ctx) => {
979
- cfg = freshConfig();
1006
+ cfg = freshPlannerConfig(freshConfig);
980
1007
  const c = asCtx(ctx);
981
1008
  const e = asRecord(event);
982
1009
  const tool = asString(e.toolName);
@@ -989,8 +1016,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
989
1016
  if (isSub) calls.set(id, n);
990
1017
  if (!isSub) callsSinceStop++;
991
1018
  const cwd = c.cwd ?? process.cwd();
1019
+ // planner mode P2 (plan 20261102_1515): the plan a sub's approved spawn bound to it (the
1020
+ // brief's `Planner role for <plan path>` line) — the gates check it against plan-path writes.
1021
+ const plannerPlan = isSub ? plannerSpawnPlan(id) : null;
992
1022
  const snap = new Map<string, string>();
993
- snapshotPlans(tool, input, cwd, snap, !isSub);
1023
+ snapshotPlans(tool, input, cwd, snap, !isSub, plannerPlan, cfg);
994
1024
  // Drain (src/core/rollover.ts): while a rollover is pending no new subagent starts; the
995
1025
  // running ones finish first. Subagents' own tool calls are unaffected. Main's task calls
996
1026
  // also carry the running job labels for the priority gate (20261025_0215 P2).
@@ -1050,7 +1080,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1050
1080
  };
1051
1081
 
1052
1082
  pi.on("tool_result", (event, ctx) => {
1053
- cfg = freshConfig();
1083
+ cfg = freshPlannerConfig(freshConfig);
1054
1084
  // P9: an owner message past notify.answer_within_min with no hand-back steers once per
1055
1085
  // message; sendUserMessage reaches Main mid-turn through the steer queue.
1056
1086
  if (isMain(ctx)) {
@@ -1170,7 +1200,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1170
1200
  });
1171
1201
 
1172
1202
  pi.on("session_stop", (e, ctx) => {
1173
- cfg = freshConfig();
1203
+ cfg = freshPlannerConfig(freshConfig);
1174
1204
  const c = asCtx(ctx);
1175
1205
  if (c.hasAgent && c.kind !== "main") return;
1176
1206
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
@@ -1551,8 +1581,12 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1551
1581
  if (note) pendingReviewNotes.push(note);
1552
1582
  });
1553
1583
 
1554
- // omp is really shutting down: the exit-grace fallback must not fire.
1555
- pi.on("session_shutdown", () => clearGrace?.());
1584
+ // omp is really shutting down: the exit-grace fallback must not fire. A clean shutdown is also
1585
+ // the owner's last stamp (P2 d): verify first, then record the state that pass confirmed.
1586
+ pi.on("session_shutdown", () => {
1587
+ clearGrace?.();
1588
+ stampPlannerState(freshConfig);
1589
+ });
1556
1590
 
1557
1591
  // Compaction keeps the owner's holds true: a summary may state a hold only as a plans' WAITING on owner line says it.
1558
1592
  pi.on("session.compacting", (_e, ctx) => {
@@ -1619,6 +1653,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1619
1653
  notifyTier(ctx, t);
1620
1654
  return { handled: true };
1621
1655
  }
1656
+ const p = chatPlanner(text, cfg, "interactive");
1657
+ if (p.applied) {
1658
+ asRolloverCtx(ctx)?.notify(`planner now ${p.planner}`);
1659
+ return { handled: true };
1660
+ }
1622
1661
  const g = chatGo(text, cfg, "interactive");
1623
1662
  if (g.applied) {
1624
1663
  notifyGo(ctx, g);
@@ -13,7 +13,7 @@ import { mainStartText } from "../../core/main-start.ts";
13
13
  import { appendMetric } from "../../core/metrics.ts";
14
14
  import { applyQueueEnv } from "../../core/queue/env.ts";
15
15
  import { tryLock } from "../../core/file-lock.ts";
16
- import { MAIN_ID_RE, mainStateDir } from "../../core/guards.ts";
16
+ import { MAIN_ID_RE, mainId, mainStateDir } from "../../core/guards.ts";
17
17
  import * as q from "../../core/queue/lib.ts";
18
18
  import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath, unansweredOwnerMessages } from "../../core/rollover.ts";
19
19
  import { PROXY_BIN, proxyOnPath } from "../../core/secret-redact.ts";
@@ -210,7 +210,7 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
210
210
  if (message === null) return 1;
211
211
  // The request is removed only once its message exists: a kill during main-start
212
212
  // (I-20261024-4) must leave it for the next launcher to continue.
213
- rmSync(relaunchPath(), { force: true });
213
+ clearRelaunchFiles(cfg);
214
214
  runArgs = [...carried, message];
215
215
  }
216
216
  } else if (!hasPositional(harnessArgs)) {
@@ -223,7 +223,7 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
223
223
  console.error(HANDOFF_PENDING_LINE);
224
224
  const message = await nextMessage(req, cfg, mainStart);
225
225
  if (message !== null) {
226
- rmSync(relaunchPath(), { force: true });
226
+ clearRelaunchFiles(cfg);
227
227
  runArgs = [...carried, message];
228
228
  }
229
229
  }
@@ -248,7 +248,7 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
248
248
  console.error(HANDOFF_PENDING_LINE);
249
249
  const message = await nextMessage(req, cfg, mainStart);
250
250
  if (message === null) return code;
251
- rmSync(relaunchPath(), { force: true });
251
+ clearRelaunchFiles(cfg);
252
252
  runArgs = [...carried, message];
253
253
  }
254
254
  } finally {
@@ -268,20 +268,18 @@ function runChild(cmd: string, args: string[], env: NodeJS.ProcessEnv): Promise<
268
268
  return promise;
269
269
  }
270
270
 
271
- /**
272
- * The request the last run left behind, only if it was written during that run (mtime at or after
273
- * `since`). Not consumed: the caller removes it once it has decided to use it. A request without the
274
- * required fields is removed and logged; an unreadable one is logged and left in place.
275
- */
276
- function readRequest(since: number, cfg: Config): RelaunchRequest | null {
277
- const path = relaunchPath();
278
- let mtimeMs: number;
279
- try {
280
- mtimeMs = statSync(path).mtimeMs;
281
- } catch {
282
- return null;
283
- }
284
- if (mtimeMs < since) return null;
271
+ /** Pre-multi-main relaunch request location; only read when mainId is `main`. */
272
+ function legacyRelaunchPath(cfg: Config): string {
273
+ return join(cfg.paths.queue_state, "rollover", "relaunch.json");
274
+ }
275
+
276
+ /** After a successful consume, drop the request on the new path and any legacy copy for id main. */
277
+ function clearRelaunchFiles(cfg: Config): void {
278
+ rmSync(relaunchPath(), { force: true });
279
+ if (mainId() === "main") rmSync(legacyRelaunchPath(cfg), { force: true });
280
+ }
281
+
282
+ function parseRelaunchFile(path: string, cfg: Config): RelaunchRequest | null {
285
283
  let raw: Partial<RelaunchRequest>;
286
284
  try {
287
285
  raw = JSON.parse(readFileSync(path, "utf8")) as Partial<RelaunchRequest>;
@@ -297,6 +295,35 @@ function readRequest(since: number, cfg: Config): RelaunchRequest | null {
297
295
  return { previousSessionFile: raw.previousSessionFile, notePath: raw.notePath, draft: raw.draft ?? "" };
298
296
  }
299
297
 
298
+ /**
299
+ * The request the last run left behind, only if it was written during that run (mtime at or after
300
+ * `since`). Not consumed: the caller removes it once it has decided to use it. A request without the
301
+ * required fields is removed and logged; an unreadable one is logged and left in place.
302
+ */
303
+ function readRequest(since: number, cfg: Config): RelaunchRequest | null {
304
+ const newPath = relaunchPath();
305
+ let newMtime: number | undefined;
306
+ try {
307
+ newMtime = statSync(newPath).mtimeMs;
308
+ } catch {
309
+ newMtime = undefined;
310
+ }
311
+ if (newMtime !== undefined && newMtime >= since) {
312
+ return parseRelaunchFile(newPath, cfg);
313
+ }
314
+ if (mainId() !== "main") return null;
315
+ const legacyPath = legacyRelaunchPath(cfg);
316
+ let legacyMtime: number;
317
+ try {
318
+ legacyMtime = statSync(legacyPath).mtimeMs;
319
+ } catch {
320
+ return null;
321
+ }
322
+ if (legacyMtime < since) return null;
323
+ adapterLog(cfg, `rollover: relaunch request read from legacy path ${legacyPath}`);
324
+ return parseRelaunchFile(legacyPath, cfg);
325
+ }
326
+
300
327
  /** Whether the handoff note can be read now: a launcher cannot relaunch without it. */
301
328
  function noteReadable(path: string): boolean {
302
329
  try {
@@ -6,12 +6,13 @@
6
6
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
7
  import { homedir } from "node:os";
8
8
  import { dirname } from "node:path";
9
+ import { isPlannerModeKey, stampPlannerMode, verifyPlannerMode } from "../core/autonomy.ts";
9
10
  import { checkEdited, leafKeys, setConfigKeys, valueAt, yamlValue } from "../core/config-edit.ts";
10
11
  import { TEMPLATE_PATH, configFile, loadConfig } from "../core/config.ts";
11
12
 
12
13
  const VALID_KEYS = leafKeys(Bun.YAML.parse(readFileSync(TEMPLATE_PATH, "utf8")));
13
14
 
14
- export function runConfigKeys(args: string[], home: string = homedir()): number {
15
+ export function runConfigKeys(args: string[], home: string = homedir(), tty: boolean = process.stdin.isTTY === true): number {
15
16
  const [verb, key, raw] = args;
16
17
  try {
17
18
  if (verb === "list") {
@@ -43,11 +44,16 @@ export function runConfigKeys(args: string[], home: string = homedir()): number
43
44
  // Lists in flow style on one line ([a, b]); scalars as JSON, which is valid YAML.
44
45
  const text = yamlValue(parsed);
45
46
  const file = configFile(home);
47
+ const pin = { file, home };
48
+ // A mode key is a planner mode fact and owner-only: revert non-owner dirt first (the
49
+ // reverted file is what the write starts from), and only a TTY write stamps it (P2 d).
50
+ if (tty && isPlannerModeKey(key)) verifyPlannerMode(pin);
46
51
  const original = existsSync(file) ? readFileSync(file, "utf8") : null;
47
52
  const edited = setConfigKeys(original, { [key]: text });
48
53
  if (!checkEdited(edited, home, (line) => console.error(line))) return 1;
49
54
  mkdirSync(dirname(file), { recursive: true });
50
55
  writeFileSync(file, edited);
56
+ if (tty && isPlannerModeKey(key)) stampPlannerMode(pin);
51
57
  return 0;
52
58
  } catch (err) {
53
59
  console.error(err instanceof Error ? err.message : String(err));
package/src/cli/guard.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // and 2 when refused (same code a blocker uses).
4
4
 
5
5
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "../core/adapter.ts";
6
+ import { plannerPin, verifyPlannerMode } from "../core/autonomy.ts";
6
7
  import { ConfigError, loadConfig } from "../core/config.ts";
7
8
  import { checkPlanEdit, checkSpawn, checkStop, checkTool, checkInject } from "../core/guards.ts";
8
9
  import { applyQueueEnv } from "../core/queue/env.ts";
@@ -105,6 +106,14 @@ export async function runGuard(event: string): Promise<number> {
105
106
  try {
106
107
  cfg = loadConfig();
107
108
  applyQueueEnv(cfg);
109
+ // P2 d: hold the mode facts to the owner's baseline before any decision reads them; a
110
+ // reverted config is re-read so this guard sees the restored values.
111
+ const held = verifyPlannerMode(plannerPin(cfg));
112
+ if (held.reverted) {
113
+ if (held.hint !== null) console.error(held.hint);
114
+ cfg = loadConfig();
115
+ applyQueueEnv(cfg);
116
+ }
108
117
  } catch (err) {
109
118
  console.error(err instanceof ConfigError ? err.message : String(err));
110
119
  return 1;
package/src/cli/setup.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  import { readFileSync, writeFileSync } from "node:fs";
9
9
  import { homedir } from "node:os";
10
10
  import { getAdapter, harnessBins } from "../adapters/index.ts";
11
+ import { isPlannerModeKey, stampPlannerMode, verifyPlannerMode } from "../core/autonomy.ts";
11
12
  import { TEMPLATE_PATH, configFile } from "../core/config.ts";
12
13
  import { checkEdited, leafKeys, setConfigKeys, valueAt, yamlValue } from "../core/config-edit.ts";
13
14
  import { pagesDoctor } from "../core/pages-doctor.ts";
@@ -16,6 +17,22 @@ import { invalidSlugs } from "../core/subagents.ts";
16
17
  import { TAILSCALE_MISSING, TAILSCALE_STOPPED } from "../core/ui-setup.ts";
17
18
  import { askLine, initHome } from "./init.ts";
18
19
 
20
+ /**
21
+ * The planner mode side of a setup write (P2 d): a mode key is owner-only, so when the owner's
22
+ * terminal is about to write one, dirt is reverted first and the re-read text is what the write
23
+ * starts from — a dirty sibling line can never be adopted by this stamp.
24
+ */
25
+ export function holdPlannerKeys(deps: SetupDeps, file: string, keys: string[], text: string): string {
26
+ if (!deps.terminal || !keys.some(isPlannerModeKey)) return text;
27
+ verifyPlannerMode({ file, home: deps.home });
28
+ return readFileSync(file, "utf8");
29
+ }
30
+
31
+ /** After the write: a mode key written at the owner's terminal is what stamps the mode facts. */
32
+ export function stampPlannerKeys(deps: SetupDeps, file: string, keys: string[]): void {
33
+ if (deps.terminal && keys.some(isPlannerModeKey)) stampPlannerMode({ file, home: deps.home });
34
+ }
35
+
19
36
  export interface SetupDeps {
20
37
  home: string;
21
38
  env: NodeJS.ProcessEnv;
@@ -72,12 +89,13 @@ const TEMPLATE = Bun.YAML.parse(TEMPLATE_TEXT);
72
89
  const COMMENTS = templateComments(TEMPLATE_TEXT);
73
90
  const VALID_KEYS = leafKeys(TEMPLATE);
74
91
  const TIERS = ["strict", "opinionated", "full"];
92
+ const PLANNERS = ["main", "delegated"];
75
93
 
76
94
  // The asked groups, in order. Keys outside them form the advanced walk.
77
95
  const GROUPS: { name: string; keys: string[] }[] = [
78
96
  { name: "Paths", keys: ["paths.work_roots"] },
79
97
  { name: "Harness", keys: ["harness"] },
80
- { name: "Autonomy", keys: ["autonomy.tier", "autonomy.strict_edit_limit", "autonomy.go_minutes", "autonomy.go_phrase"] },
98
+ { name: "Autonomy", keys: ["autonomy.tier", "autonomy.planner", "autonomy.strict_edit_limit", "autonomy.go_minutes", "autonomy.go_phrase"] },
81
99
  { name: "Phone page", keys: ["ui.enabled", "ui.owner_login"] },
82
100
  { name: "Static pages", keys: ["pages.enabled", "pages.port", "pages.dir"] },
83
101
  { name: "Notify", keys: ["notify.discord_webhook_file", "notify.slack_webhook_file"] },
@@ -204,10 +222,12 @@ function runGroup(ctx: Ctx, name: string, keys: string[]): number {
204
222
  ctx.changed.push({ key, old, next: picks[key] });
205
223
  }
206
224
  if (Object.keys(changes).length === 0) return 0;
207
- const edited = setConfigKeys(ctx.text, changes);
225
+ const changed = Object.keys(changes);
226
+ const edited = setConfigKeys(holdPlannerKeys(ctx.deps, ctx.file, changed, ctx.text), changes);
208
227
  if (!checkEdited(edited, ctx.deps.home, (line) => ctx.deps.say(line))) return 1;
209
228
  writeFileSync(ctx.file, edited);
210
229
  ctx.text = edited;
230
+ stampPlannerKeys(ctx.deps, ctx.file, changed);
211
231
  return 0;
212
232
  }
213
233
 
@@ -301,6 +321,7 @@ function validate(ctx: Ctx, key: string, value: unknown): string | null {
301
321
 
302
322
  function rule(ctx: Ctx, key: string, value: unknown): string | null {
303
323
  if (key === "autonomy.tier" && !TIERS.includes(String(value))) return `autonomy.tier must be ${TIERS.join(", ")}`;
324
+ if (key === "autonomy.planner" && !PLANNERS.includes(String(value))) return `autonomy.planner must be ${PLANNERS.join(", ")}`;
304
325
  if (key === "harness" && !ctx.deps.seams.harnesses.some((h) => h.name === value)) {
305
326
  return `harness must be one of: ${ctx.deps.seams.harnesses.map((h) => h.name).join(", ")}`;
306
327
  }
@@ -7,7 +7,8 @@
7
7
 
8
8
  import { appendFileSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
9
9
  import path from "node:path";
10
- import type { Config } from "./config.ts";
10
+ import { configFile, loadConfig, type Config } from "./config.ts";
11
+ import { checkEdited, setConfigKeys, yamlValue } from "./config-edit.ts";
11
12
  import { stateDirPath } from "./queue/lib.ts";
12
13
 
13
14
  export type Tier = "strict" | "opinionated" | "full";
@@ -101,3 +102,240 @@ export function takeGo(cfg: Config, now = Date.now()): boolean {
101
102
  rmSync(goFile(), { force: true });
102
103
  return now - mtimeMs < cfg.autonomy.go_minutes * 60_000;
103
104
  }
105
+
106
+ // Planner mode (plan 20261102_1515): who writes the plans. "main" is today's behaviour; in
107
+ // "delegated" the planner agent plans and Main routes. Same owner-switch family as the tier: a
108
+ // state file beside tierFile(), a whole-message chat command behind guards.chat_unlock, and the
109
+ // config value as the default when the file is absent or junk.
110
+
111
+ export type PlannerMode = "main" | "delegated";
112
+ const PLANNER_MODES: readonly PlannerMode[] = ["main", "delegated"];
113
+
114
+ export function plannerFile(): string {
115
+ return path.join(stateDirPath(), "planner-mode");
116
+ }
117
+
118
+ // The effective mode facts are owner-only (P2 d). A guard baseline beside the config file records
119
+ // the state file's existence and bytes, the config file's own autonomy.planner and full bytes,
120
+ // and its paths.queue_state as the file states it (before any env overlay, which would mask a
121
+ // dirty line). A write a subagent slips into either file is caught at the next verify seam and
122
+ // reverted; only the owner's stampers (the chat command, a TTY config write of a mode key, a
123
+ // clean shutdown) create or refresh it. The baseline sits next to configFile(), a fixed anchor no
124
+ // config write can relocate, and it is in the built-in protected set (src/core/queue/lib.ts), so
125
+ // no tool can plant or edit it. No baseline = mode main: before the first owner stamp any state
126
+ // file is deleted and the config value is forced back to main, so nothing a non-owner wrote can
127
+ // take effect.
128
+
129
+ /** Where the baseline's facts live: the config file and the home its paths expand from. */
130
+ export interface PlannerPin {
131
+ file: string;
132
+ home: string;
133
+ }
134
+
135
+ export function plannerPin(cfg: Config): PlannerPin {
136
+ return { file: cfg.file ?? configFile(cfg.paths.home), home: cfg.paths.home };
137
+ }
138
+
139
+ /** The baseline file: beside the config file it describes. */
140
+ export function plannerBaselineFile(pin: PlannerPin): string {
141
+ return path.join(path.dirname(pin.file), "guard-baseline");
142
+ }
143
+
144
+ /** The config keys that carry a mode fact: a TTY write of one is a stamp. */
145
+ export function isPlannerModeKey(key: string): boolean {
146
+ return key === "autonomy.planner" || key === "paths.queue_state";
147
+ }
148
+
149
+ interface PlannerState {
150
+ exists: boolean;
151
+ bytes: string | null;
152
+ }
153
+
154
+ interface PlannerBaseline {
155
+ version: 1;
156
+ /** The state dir the facts were recorded under: the mode file is always read there. */
157
+ state_dir: string;
158
+ planner: PlannerState;
159
+ config: { planner: string; queue_state: string; bytes: string };
160
+ }
161
+
162
+ export function readPlannerState(file: string): PlannerState {
163
+ try {
164
+ return { exists: true, bytes: readFileSync(file, "utf8") };
165
+ } catch {
166
+ return { exists: false, bytes: null };
167
+ }
168
+ }
169
+
170
+ function readPlannerBaseline(pin: PlannerPin): PlannerBaseline | null {
171
+ let raw: unknown;
172
+ try {
173
+ raw = JSON.parse(readFileSync(plannerBaselineFile(pin), "utf8"));
174
+ } catch {
175
+ return null;
176
+ }
177
+ const b = raw as Record<string, unknown>;
178
+ const planner = b.planner as Record<string, unknown> | undefined;
179
+ const config = b.config as Record<string, unknown> | undefined;
180
+ if (b.version !== 1 || typeof b.state_dir !== "string") return null;
181
+ if (typeof config?.planner !== "string" || typeof config.queue_state !== "string" || typeof config.bytes !== "string") return null;
182
+ return {
183
+ version: 1,
184
+ state_dir: b.state_dir,
185
+ planner: { exists: planner?.exists === true, bytes: typeof planner?.bytes === "string" ? planner.bytes : null },
186
+ config: { planner: config.planner, queue_state: config.queue_state, bytes: config.bytes },
187
+ };
188
+ }
189
+
190
+ /** The mode facts a config FILE states: its own values, before any env overlay (QUEUE_STATE would mask a dirty line). */
191
+ function fileFacts(pin: PlannerPin): { planner: PlannerMode; queue_state: string } {
192
+ const cfg = loadConfig({ file: pin.file, home: pin.home, env: {} });
193
+ return { planner: cfg.autonomy.planner, queue_state: cfg.paths.queue_state };
194
+ }
195
+
196
+ /** Writes an edited config only when it still loads; false leaves the file untouched. */
197
+ function writeConfig(pin: PlannerPin, text: string): boolean {
198
+ if (!checkEdited(text, pin.home, () => {})) return false;
199
+ mkdirSync(path.dirname(pin.file), { recursive: true });
200
+ writeFileSync(pin.file, text);
201
+ return true;
202
+ }
203
+
204
+ export interface PlannerVerifyResult {
205
+ /** True when a mode fact was dirty and has been restored. */
206
+ reverted: boolean;
207
+ /** The one line to show when something was reverted; null when clean. */
208
+ hint: string | null;
209
+ }
210
+
211
+ const REVERT_HINT = "planner mode changes need your terminal or the chat command `planner <mode>`";
212
+
213
+ /**
214
+ * Holds the mode facts to the baseline: a config value that differs is restored by value through
215
+ * the one config editor (the baseline's full bytes only when the file no longer loads), and the
216
+ * state file is restored to its recorded bytes or deleted. Runs at every seam — the adapter's
217
+ * events and the guard process's first load — so the guards only ever see baseline-clean facts.
218
+ */
219
+ export function verifyPlannerMode(pin: PlannerPin): PlannerVerifyResult {
220
+ try {
221
+ const base = readPlannerBaseline(pin);
222
+ let text: string | null = null;
223
+ try {
224
+ text = readFileSync(pin.file, "utf8");
225
+ } catch {
226
+ text = null;
227
+ }
228
+ let facts: { planner: PlannerMode; queue_state: string } | null = null;
229
+ try {
230
+ facts = fileFacts(pin);
231
+ } catch {
232
+ facts = null;
233
+ }
234
+ let reverted = false;
235
+ const values: Record<string, string> = {};
236
+ if (facts === null) {
237
+ // The file no longer parses: only the baseline's own bytes can restore it (a rare
238
+ // dirty case; losing post-stamp sibling keys is accepted over leaving dirt in place).
239
+ if (base !== null && text !== base.config.bytes) reverted = writeConfig(pin, base.config.bytes) || reverted;
240
+ } else {
241
+ const wantPlanner = base?.config.planner ?? "main";
242
+ if (facts.planner !== wantPlanner && (PLANNER_MODES as readonly string[]).includes(wantPlanner)) values["autonomy.planner"] = yamlValue(wantPlanner);
243
+ if (base !== null && facts.queue_state !== base.config.queue_state) values["paths.queue_state"] = yamlValue(base.config.queue_state);
244
+ }
245
+ if (Object.keys(values).length > 0) {
246
+ let edited: string | null = null;
247
+ try {
248
+ edited = setConfigKeys(text, values);
249
+ } catch {
250
+ edited = null;
251
+ }
252
+ if (edited !== null && writeConfig(pin, edited)) reverted = true;
253
+ else if (base !== null) reverted = writeConfig(pin, base.config.bytes) || reverted;
254
+ }
255
+ // The state file: pinned by the baseline; with no baseline it may not exist at all.
256
+ const pinnedDir = base?.state_dir ?? stateDirPath();
257
+ const pinnedFile = path.join(pinnedDir, "planner-mode");
258
+ const want = base?.planner ?? { exists: false, bytes: null };
259
+ const cur = readPlannerState(pinnedFile);
260
+ if (want.exists) {
261
+ if (cur.exists !== true || cur.bytes !== want.bytes) {
262
+ mkdirSync(pinnedDir, { recursive: true });
263
+ writeFileSync(pinnedFile, want.bytes ?? "");
264
+ reverted = true;
265
+ }
266
+ } else if (cur.exists) {
267
+ rmSync(pinnedFile, { force: true });
268
+ reverted = true;
269
+ }
270
+ // A mode file beside the freshly configured state dir is foreign: the baseline pins the dir.
271
+ const live = plannerFile();
272
+ if (live !== pinnedFile && readPlannerState(live).exists) {
273
+ rmSync(live, { force: true });
274
+ reverted = true;
275
+ }
276
+ return { reverted, hint: reverted ? REVERT_HINT : null };
277
+ } catch {
278
+ // A guard never fails open on a broken read, and never crashes a running session.
279
+ return { reverted: false, hint: null };
280
+ }
281
+ }
282
+
283
+ /** Records the current mode facts as the baseline. Only a stamper calls this, after a clean verify. */
284
+ export function stampPlannerMode(pin: PlannerPin): void {
285
+ try {
286
+ const text = readFileSync(pin.file, "utf8");
287
+ const facts = fileFacts(pin);
288
+ const dir = stateDirPath();
289
+ const base: PlannerBaseline = {
290
+ version: 1,
291
+ state_dir: dir,
292
+ planner: readPlannerState(path.join(dir, "planner-mode")),
293
+ config: { planner: facts.planner, queue_state: facts.queue_state, bytes: text },
294
+ };
295
+ mkdirSync(path.dirname(plannerBaselineFile(pin)), { recursive: true });
296
+ writeFileSync(plannerBaselineFile(pin), `${JSON.stringify(base, null, 2)}\n`);
297
+ } catch {}
298
+ }
299
+
300
+ /** The planner mode in force: the file twin of tierFile() when it names one of the two (one word), else the config value. */
301
+ export function currentPlanner(cfg: Config): PlannerMode {
302
+ try {
303
+ const word = readFileSync(plannerFile(), "utf8").trim().toLowerCase();
304
+ if ((PLANNER_MODES as readonly string[]).includes(word)) return word as PlannerMode;
305
+ } catch {}
306
+ return cfg.autonomy.planner;
307
+ }
308
+
309
+ export interface ChatPlannerResult {
310
+ /** True when the text was a whole-message `planner <mode>` command that took effect. */
311
+ applied: boolean;
312
+ /** The planner mode now in force. */
313
+ planner?: PlannerMode;
314
+ }
315
+
316
+ const PLANNER_CMD = /^planner\s+(main|delegated)$/i;
317
+
318
+ /**
319
+ * Owner planner switch by chat (guards.chat_unlock, the same flag as chatTier): the whole trimmed
320
+ * message — "planner main" or "planner delegated", case-insensitive — writes the file twin of
321
+ * tierFile(). Only the adapter and the owner page call this, with text the owner really typed or
322
+ * tapped; a model, a tool result or a machine prompt must never reach it. Every applied switch is
323
+ * logged to the plan-guard log with `word` naming the entry point ("chat" or "ui").
324
+ */
325
+ export function chatPlanner(text: string, cfg: Config, source: string, word: "chat" | "ui" = "chat"): ChatPlannerResult {
326
+ if (!cfg.guards.chat_unlock) return { applied: false };
327
+ const m = PLANNER_CMD.exec(text.trim());
328
+ if (!m) return { applied: false };
329
+ const planner = (m[1] ?? "").toLowerCase() as PlannerMode;
330
+ const pin = plannerPin(cfg);
331
+ // The owner's own switch: revert any dirt first, write, then record the new state. The mode
332
+ // file is written in-process, so no tool call sees it.
333
+ verifyPlannerMode(pin);
334
+ mkdirSync(stateDirPath(), { recursive: true });
335
+ writeFileSync(plannerFile(), `${planner}\n`);
336
+ stampPlannerMode(pin);
337
+ try {
338
+ appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} PLANNER ${planner} ${word} source=${source}\n`);
339
+ } catch {}
340
+ return { applied: true, planner };
341
+ }
@@ -166,6 +166,8 @@ export interface Config {
166
166
  autonomy: {
167
167
  /** Tier in force when `<state dir>/autonomy-tier` does not name one (src/core/autonomy.ts). */
168
168
  tier: "strict" | "opinionated" | "full";
169
+ /** Planner mode in force when the state file does not name one (plan 20261102_1515, src/core/autonomy.ts): "main" = Main writes the plans; "delegated" = the planner agent does and Main routes. */
170
+ planner: "main" | "delegated";
169
171
  /** Main's project-file changes per guards.main_window_min window in tier strict. */
170
172
  strict_edit_limit: number;
171
173
  /** Minutes the approve phrase approves exactly one push/merge in tier strict. */
@@ -328,6 +330,8 @@ export interface Config {
328
330
  adapter?: { name: string; sessions: string; pins: string; extensions: string };
329
331
  /** Notices about legacy keys in the user's config file; empty when there are none. */
330
332
  notices: string[];
333
+ /** The file these values were loaded from: the anchor the planner mode baseline sits beside. */
334
+ file?: string;
331
335
  }
332
336
 
333
337
  type EnvKind = "string" | "number" | "csv";
@@ -576,6 +580,8 @@ function check(cfg: Config): void {
576
580
  throw new ConfigError('approval.since must be "" or a plan stamp YYYYMMDD_HHMM (plans stamped at or after it need a page and an approval record)');
577
581
  if (cfg.autonomy.tier !== "strict" && cfg.autonomy.tier !== "opinionated" && cfg.autonomy.tier !== "full")
578
582
  throw new ConfigError('autonomy.tier must be "strict", "opinionated" or "full"');
583
+ if (cfg.autonomy.planner !== "main" && cfg.autonomy.planner !== "delegated")
584
+ throw new ConfigError('autonomy.planner must be "main" or "delegated"');
579
585
  if (!Number.isInteger(cfg.autonomy.strict_edit_limit) || cfg.autonomy.strict_edit_limit < 1)
580
586
  throw new ConfigError("autonomy.strict_edit_limit must be an integer >= 1");
581
587
  if (!Number.isInteger(cfg.autonomy.go_minutes) || cfg.autonomy.go_minutes < 1)
@@ -799,6 +805,7 @@ export function loadConfig(opts: LoadOptions = {}): Config {
799
805
  applyEnv(merged, opts.env ?? process.env);
800
806
  const expanded = expand(merged, home) as Config;
801
807
  expanded.notices = notices;
808
+ expanded.file = file;
802
809
  check(expanded);
803
810
  return expanded;
804
811
  }
@@ -26,7 +26,7 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSy
26
26
  import { homedir } from "node:os";
27
27
  import path from "node:path";
28
28
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
29
- import { currentTier, takeGo } from "./autonomy.ts";
29
+ import { currentPlanner, currentTier, takeGo } from "./autonomy.ts";
30
30
  import { approvalProblem, MAIN_ONLY_LINE, reviewHash } from "./plan-approval.ts";
31
31
  export { reviewHash };
32
32
  import type { Config } from "./config.ts";
@@ -362,6 +362,45 @@ function matchReviewSpawn(spawns: Record<string, ReviewSpawn>, agentId: string):
362
362
  return null;
363
363
  }
364
364
 
365
+ // --- planner mode (plan 20261102_1515 P2): the named planner spawns ---
366
+
367
+ /** The plan path a brief's `Planner role for <plan path>` line names, or null. */
368
+ function plannerRolePlan(text: string): string | null {
369
+ const p = (/^[ \t]*Planner role for[ \t]+(.+?)[ \t]*$/im.exec(text)?.[1] ?? "").trim();
370
+ return p || null;
371
+ }
372
+
373
+ /** P2(b): the named planner spawns, spawn name → the one plan path its brief may create and edit (planner-spawns.json in the state dir). Recorded only on an approved spawn: in main mode the spawn gate refused the brief, so a binding exists only for a delegated planner. */
374
+ function plannerSpawnsFile(): string {
375
+ return path.join(q.STATE_DIR, "planner-spawns.json");
376
+ }
377
+
378
+ function readPlannerSpawns(): Record<string, string> {
379
+ try {
380
+ const parsed: unknown = JSON.parse(readFileSync(plannerSpawnsFile(), "utf8"));
381
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, string>) : {};
382
+ } catch {
383
+ return {};
384
+ }
385
+ }
386
+
387
+ function recordPlannerSpawn(name: string, plan: string): void {
388
+ const spawns = readPlannerSpawns();
389
+ spawns[name] = plan;
390
+ mkdirSync(q.STATE_DIR, { recursive: true });
391
+ writeFileSync(plannerSpawnsFile(), `${JSON.stringify(spawns, null, 2)}\n`);
392
+ }
393
+
394
+ /** The plan path the agent's brief named in its `Planner role for` line: its spawn name, or the name without a -<digits> suffix (the P4f id rule); null when no planner role is bound. */
395
+ export function plannerSpawnPlan(agentId: string): string | null {
396
+ const spawns = readPlannerSpawns();
397
+ for (const name of [agentId, agentId.replace(/-\d+$/, "")]) {
398
+ const plan = Object.hasOwn(spawns, name) ? spawns[name] : undefined;
399
+ if (typeof plan === "string" && plan) return plan;
400
+ }
401
+ return null;
402
+ }
403
+
365
404
  /** P4f: the secret-read deny: credential dirs under a home, and env files. Shell text expands `~` to the process home (queue lib) while config points at the sandbox home in tests, so both roots are judged; they are the same directory in production. */
366
405
  function secretPath(p: string, cfg: Config, cwd: string): boolean {
367
406
  const abs = path.resolve(cwd, p.startsWith("~/") ? path.join(cfg.paths.home, p.slice(2)) : p);
@@ -977,6 +1016,7 @@ export function spawnProblem(
977
1016
  spawner: Spawner = "main",
978
1017
  ): string | null {
979
1018
  const roles: Record<string, string | null> = {};
1019
+ const plannerRoles: Record<string, string> = {};
980
1020
  const tasks = Array.isArray(input?.tasks) ? input.tasks : [];
981
1021
  const context = String(input?.context ?? "");
982
1022
  const allowed = q.allowedAgents();
@@ -987,6 +1027,29 @@ export function spawnProblem(
987
1027
  const agent = String(t?.agent ?? "task");
988
1028
  const label = String(t?.name ?? agent);
989
1029
  const text = `${context}\n${String(t?.task ?? "")}`;
1030
+ // The role line belongs to the task's own brief (the adapter keys the spawn's brief by it);
1031
+ // a mention in the shared context names no one's role.
1032
+ const plannerFor = plannerRolePlan(String(t?.task ?? ""));
1033
+ // planner mode P2 (c): a Planner-role brief is refused while the mode is main — the switch
1034
+ // is the owner's (`planner delegated`). While delegated the planner spawn skips the open-plan
1035
+ // gates below (the plan it names does not exist yet — writing it is the spawn's job), but the
1036
+ // ## Allowed deny still holds, and it needs a name to key its role.
1037
+ if (plannerFor && currentPlanner(cfg) === "main") {
1038
+ problems.push(`${label}: planner mode is main — a Planner-role spawn needs the owner's \`planner delegated\` switch.`);
1039
+ continue;
1040
+ }
1041
+ if (plannerFor && !t?.name) {
1042
+ problems.push(`${label}: a planner spawn needs a name (the task name keys its planner role).`);
1043
+ continue;
1044
+ }
1045
+ if (plannerFor) {
1046
+ if (!allowed.has(agent)) {
1047
+ problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
1048
+ continue;
1049
+ }
1050
+ plannerRoles[label] = plannerFor;
1051
+ continue;
1052
+ }
990
1053
  if (!allowed.has(agent)) {
991
1054
  problems.push(`${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
992
1055
  continue;
@@ -1056,6 +1119,7 @@ export function spawnProblem(
1056
1119
  );
1057
1120
  if (verdict) return verdict;
1058
1121
  for (const [name, plan] of Object.entries(roles)) recordReviewSpawn(name, plan);
1122
+ for (const [name, plan] of Object.entries(plannerRoles)) recordPlannerSpawn(name, plan);
1059
1123
  return null;
1060
1124
  }
1061
1125
 
@@ -1232,6 +1296,19 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
1232
1296
  if (!keeper)
1233
1297
  return "this is the read tool's redaction placeholder, not the real value; re-read the file raw or keep the original line";
1234
1298
  }
1299
+ // planner mode P2 (b): while delegated, every sub write to a plan path is refused except the
1300
+ // plan its brief named in the approved spawn's `Planner role for <plan path>` line (the
1301
+ // planner-spawns binding). A NEW plan file is invisible to the indexed-plan gate below
1302
+ // (isOrchestrationPath + planAt both false), so the refusal fires here — never by accident of
1303
+ // indexing — and covers shell redirects through writeTargets too.
1304
+ const delegatedPlanner = currentPlanner(cfg) === "delegated" ? plannerSpawnPlan(e.agentId) : null;
1305
+ if (currentPlanner(cfg) === "delegated") {
1306
+ for (const p of writes) {
1307
+ if (!MAIN_PLAN_FILE.test(p) || p === delegatedPlanner) continue;
1308
+ if (delegatedPlanner) return `planner is delegated — your Planner role names ${delegatedPlanner} only; ${p} is not yours to write.`;
1309
+ return `planner is delegated — plan files are the planner agent's; your brief carries no "Planner role for <plan path>" line, so ${p} is refused.`;
1310
+ }
1311
+ }
1235
1312
  const plans = q.activePlans();
1236
1313
  if (e.calls >= cap) {
1237
1314
  // Plan edit targets come from writeTargets (write and structured/hashline edit)
@@ -1246,7 +1323,12 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
1246
1323
  if (!plans.length || !paths.length) return null;
1247
1324
  for (const p of writes) {
1248
1325
  if (!q.isOrchestrationPath(p, plans)) continue;
1249
- if (!q.planAt(p, plans)) return `${p} belongs to Main (main index / blocker script); read it, never change it. Report instead.`;
1326
+ if (!q.planAt(p, plans)) {
1327
+ // planner mode P2 (b): the bound planner plan routes into checkPlanEdit (Planner header,
1328
+ // Main-only lines), it is not Main's — but only that path, and only while delegated.
1329
+ if (currentPlanner(cfg) === "delegated" && p === delegatedPlanner) continue;
1330
+ return `${p} belongs to Main (main index / blocker script); read it, never change it. Report instead.`;
1331
+ }
1250
1332
  if (e.tool !== "write" && e.tool !== "edit")
1251
1333
  return `${p} is a plan file: change its "## Progress" section only with the edit or write tool.`;
1252
1334
  }
@@ -1752,7 +1834,16 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1752
1834
  // P4 (plan 20261031_1207): every gate's refusal lands in one numbered verdict; nothing
1753
1835
  // short-circuits, so Main sees all the problems in one round trip.
1754
1836
  const problems: string[] = [];
1755
- const [why, named] = planGate(e.brief, e.agent, cfg);
1837
+ // planner mode P2 (c): a Planner-role brief is refused while the mode is main — the switch is
1838
+ // the owner's (`planner delegated`). While delegated the planner spawn skips the open-plan
1839
+ // gates (the plan it names does not exist yet — writing it is the spawn's job) and its role
1840
+ // binds to the spawn name at the tail; a planner spawn needs that name.
1841
+ const plannerFor = plannerRolePlan(e.brief);
1842
+ const delegatedPlanner = plannerFor !== null && currentPlanner(cfg) === "delegated";
1843
+ if (plannerFor && !delegatedPlanner)
1844
+ problems.push(`${e.agent}: planner mode is main — a Planner-role spawn needs the owner's \`planner delegated\` switch.`);
1845
+ else if (delegatedPlanner && !e.name) problems.push(`${e.agent}: a planner spawn needs a name (the task name keys its planner role).`);
1846
+ const [why, named] = delegatedPlanner ? [null, [] as string[]] : planGate(e.brief, e.agent, cfg);
1756
1847
  if (why) problems.push(why);
1757
1848
  const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent, e.agent, "main");
1758
1849
  if (gate) problems.push(gate);
@@ -1786,6 +1877,8 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1786
1877
  for (const f of named) staffing[f] = [e.agent];
1787
1878
  recordSpawns(named, staffing);
1788
1879
  if (e.name) recordReviewSpawn(e.name, role.plan);
1880
+ // planner mode P2 (b): the approved planner spawn binds its name to the plan its brief named.
1881
+ if (delegatedPlanner && e.name && plannerFor) recordPlannerSpawn(e.name, plannerFor);
1789
1882
  return ALLOW;
1790
1883
  }
1791
1884
 
@@ -1864,7 +1957,30 @@ function mainOnlyLines(text: string): string {
1864
1957
  */
1865
1958
  export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1866
1959
  if (e.agent === "main") return checkMainPlan(e, cfg);
1867
- if (q.outsideProgress(e.after) !== q.outsideProgress(e.before) || mainOnlyLines(e.after) !== mainOnlyLines(e.before)) {
1960
+ // planner mode P2 (b): the plan bound to this sub by its approved spawn (the `Planner role for`
1961
+ // line) is the planner agent's to write — body freedom, but never the Main-only lines, and the
1962
+ // header names its agent. Only while delegated: in main mode the spawn gate refused the
1963
+ // Planner-role brief, and the plain Progress-only rule holds.
1964
+ if (currentPlanner(cfg) === "delegated" && e.agentId !== undefined && plannerSpawnPlan(e.agentId) === e.path) {
1965
+ if (mainOnlyLines(e.after) !== mainOnlyLines(e.before)) {
1966
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (planner wrote a Main-only line)`);
1967
+ return {
1968
+ allow: false,
1969
+ reason: `plan-guard: the Main-only lines ("Status:", "WAITING on owner:", "Waits on:", "Cancelled by owner:", "False positive:") of ${e.path} are never a planner agent's. The file was restored.`,
1970
+ restore: { path: e.path, text: e.before || null },
1971
+ };
1972
+ }
1973
+ const name = e.agentId ?? "";
1974
+ const head = e.after.split(/^## /m)[0] ?? "";
1975
+ if (!head.split("\n").some((l) => l.trim() === `Planner: ${name}`)) {
1976
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (no Planner header)`);
1977
+ return {
1978
+ allow: false,
1979
+ reason: `plan-guard: ${e.path} carries no "Planner: ${name}" header — a planner agent's plan names its agent above the first section. The file was restored.`,
1980
+ restore: { path: e.path, text: e.before || null },
1981
+ };
1982
+ }
1983
+ } else if (q.outsideProgress(e.after) !== q.outsideProgress(e.before) || mainOnlyLines(e.after) !== mainOnlyLines(e.before)) {
1868
1984
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path}`);
1869
1985
  return {
1870
1986
  allow: false,
@@ -1948,9 +2064,30 @@ function codeReviewProblem(file: string, after: string, ids: string[]): string |
1948
2064
  return null;
1949
2065
  }
1950
2066
 
2067
+ /** The plan text a planner agent owns: everything outside "## Progress" and the Main-only lines (planner mode P2a, plan 20261102_1515). */
2068
+ function plannerBody(text: string): string {
2069
+ return q
2070
+ .outsideProgress(text)
2071
+ .split("\n")
2072
+ .filter((l) => !MAIN_ONLY_LINE.test(l))
2073
+ .join("\n");
2074
+ }
2075
+
1951
2076
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
1952
2077
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
1953
2078
  function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
2079
+ // planner mode P2 (a): while delegated, Main plans nothing — a new plan file or a rewrite of
2080
+ // the text outside "## Progress" is the planner agent's work. Main keeps its Progress entries,
2081
+ // the Main-only lines (Status / WAITING on owner / Waits on / Cancelled by owner / False
2082
+ // positive) and the index; running the queue stays Main's.
2083
+ if (currentPlanner(cfg) === "delegated" && e.path !== q.INDEX && plannerBody(e.after) !== plannerBody(e.before)) {
2084
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (planner delegated)`);
2085
+ return {
2086
+ allow: false,
2087
+ reason: `plan-guard: planner is delegated — route the ask to the planner agent. ${e.before ? "The file was restored." : "The new file was removed."}`,
2088
+ restore: { path: e.path, text: e.before || null },
2089
+ };
2090
+ }
1954
2091
  // P3 (plan 20261027_1300): another Main's live claim on this plan refuses the edit, restored
1955
2092
  // like any refused plan edit. No claim — or this Main's own — edits freely.
1956
2093
  const holder = claims(cfg).holder(e.path);
@@ -797,6 +797,10 @@ function protectedPaths(): string[] {
797
797
  // The user's neurastream config file, even when agent_dir points elsewhere: an agent that
798
798
  // could rewrite it could point notify at its own webhook.
799
799
  `${HOME}/.config/neurastream/config.yml`,
800
+ // The planner mode guard baseline beside that file (plan 20261102_1515 P2 d): the
801
+ // owner-only anchor of the mode facts. A write that could plant or edit it would make the
802
+ // writer's own dirt the truth, so no tool may touch it.
803
+ `${HOME}/.config/neurastream/guard-baseline`,
800
804
  `${agent}/notes/subagents.md`,
801
805
  `${agent}/.guard-unlock`,
802
806
  `${path.dirname(agent)}/git-no-verify-guard.mjs`,
@@ -9,7 +9,7 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
9
9
  - INDEX.md order is priority: free agents go to the top plans first. A lower plan goes first only when the higher one says `Waits on: <plan>`, is WAITING on owner, or the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`.
10
10
  - A hold is one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it>`. The phone page shows those three parts; a missing part is left out.
11
11
  - Entering a repo: read its AGENTS.md first.
12
- - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings.
12
+ - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings. In `planner delegated` mode the planner agent writes the plan instead (`Planner: <agent>` header; the research and the `## Code read by Main` list are the planner's): Main routes the owner's asks to it, dispatches implementers, checks the outcomes (verify commands, CI, the reviewer's PASS) and lands, and Main does not read repo code to plan. The owner's whole message `planner main` returns this rule; `autonomy.planner` (default `main`) is the same switch in the config.
13
13
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
14
14
  - Every plan has `## Reuse`; no spawn without a current reviewer PASS (`templates/plan-review-brief.md`, recorded only from the reviewer's own Progress edit); a brief names every open MR of its plan with an `MR !N:` line.
15
15
  - Plan order: plan → page built from the architecture-drilldown template (`neurastream pages publish <page.html> --plan <plan.md>` refuses anything else) → owner approves (Approve on the page, or types `approve <YYYYMMDD_HHMM>`) → reviewer PASS → implementer. Once `approval.since` is set, a plan stamped at or after it gets no spawn without a page and an approval record for its current text; a body edit voids the approval, a Progress-only edit keeps it.
@@ -149,6 +149,7 @@ guards:
149
149
 
150
150
  autonomy:
151
151
  tier: opinionated # strict | opinionated | full: how much Main does without asking; the owner moves it with `tier <name>` in chat or a button on the phone page
152
+ planner: main # main = Main writes the plans; delegated = the planner agent plans and Main routes only (plan 20261102_1515); the owner flips it with `planner <mode>` in chat or here
152
153
  strict_edit_limit: 2 # Main's project-file changes per main_window_min in tier strict
153
154
  go_minutes: 10 # minutes the approve phrase approves exactly one push/merge in tier strict
154
155
  go_phrase: "go push" # the whole chat message that approves one push/merge in tier strict (I-20261025-201); a bare `go` is an ordinary message
@@ -1,5 +1,7 @@
1
1
  # <short title>
2
2
  Worktree: <work root>/<repo>-<topic> (configure paths.work_roots, e.g. {{HOME}}/work)
3
+ <!-- Planner mode: in `planner delegated` the planner agent writes the plan, and the plan carries a
4
+ bare `Planner: <agent>` line above the first `##` (no trailing comment). Omit it while Main plans. -->
3
5
  Branch: <type>/<topic>
4
6
  Summary: <one or two plain sentences: what this plan gives the owner>
5
7
  PRIORITY-ID: <optional, e.g. PR01>