neurastream 0.2.66 → 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/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;
@@ -0,0 +1,11 @@
1
+ // One tick of the main-agent limit probe (plan 20261027_1500, P3). The adapter spawns this detached
2
+ // every probe_interval_s while an episode is open; it runs at most one probe and exits. A give-up
3
+ // posts the ⚠ to the owner chat (P4), so the serial notify queue is drained before exit.
4
+
5
+ import { loadConfig } from "../core/config.ts";
6
+ import { probeStep } from "../core/limit-probe.ts";
7
+ import { notifyIdle } from "../core/notify.ts";
8
+
9
+ const cfg = loadConfig();
10
+ probeStep(cfg, Date.now());
11
+ await notifyIdle();
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
+ }
@@ -134,16 +134,20 @@ export interface Config {
134
134
  idle_stops: number;
135
135
  /** A Main stop reply matching this regex (case-insensitive) offers to plan instead of planning; the stop is refused (20261028_0900 P2). */
136
136
  plan_offer: string;
137
- /** Provider rate limits (src/core/rate-limit.ts): a turn that ends on one waits it out instead of
138
- * asking again straight into the limit. The words and the waits come from here. */
137
+ /** Provider rate limits (src/core/rate-limit.ts, src/core/limit-probe.ts): a turn that ends on one waits for the
138
+ * named reset, or probes the provider until it answers. The words and the timings come from here. */
139
139
  rate_limit: {
140
140
  /** Case-insensitive substrings in the error text that mark a rate limit. */
141
141
  patterns: string[];
142
- /** Wait when the error text names no retry-after. */
143
- default_wait_s: number;
144
- /** Cap for the parsed (or doubled) wait, before slack. */
145
- max_wait_s: number;
146
- /** Added on top of every wait. */
142
+ /** Probe the provider this often (s) while it names no reset. */
143
+ probe_interval_s: number;
144
+ /** Probes before the episode gives up. */
145
+ max_probes: number;
146
+ /** Kill a probe that runs longer than this (s). */
147
+ probe_timeout_s: number;
148
+ /** Shell command that probes the provider; {model} is replaced by the shell-quoted model. Exit 0 means it answered. */
149
+ probe_cmd: string;
150
+ /** Added on top of every wait (s). */
147
151
  slack_s: number;
148
152
  };
149
153
  blocker_timeout_ms: number;
@@ -162,6 +166,8 @@ export interface Config {
162
166
  autonomy: {
163
167
  /** Tier in force when `<state dir>/autonomy-tier` does not name one (src/core/autonomy.ts). */
164
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";
165
171
  /** Main's project-file changes per guards.main_window_min window in tier strict. */
166
172
  strict_edit_limit: number;
167
173
  /** Minutes the approve phrase approves exactly one push/merge in tier strict. */
@@ -324,6 +330,8 @@ export interface Config {
324
330
  adapter?: { name: string; sessions: string; pins: string; extensions: string };
325
331
  /** Notices about legacy keys in the user's config file; empty when there are none. */
326
332
  notices: string[];
333
+ /** The file these values were loaded from: the anchor the planner mode baseline sits beside. */
334
+ file?: string;
327
335
  }
328
336
 
329
337
  type EnvKind = "string" | "number" | "csv";
@@ -572,6 +580,8 @@ function check(cfg: Config): void {
572
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)');
573
581
  if (cfg.autonomy.tier !== "strict" && cfg.autonomy.tier !== "opinionated" && cfg.autonomy.tier !== "full")
574
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"');
575
585
  if (!Number.isInteger(cfg.autonomy.strict_edit_limit) || cfg.autonomy.strict_edit_limit < 1)
576
586
  throw new ConfigError("autonomy.strict_edit_limit must be an integer >= 1");
577
587
  if (!Number.isInteger(cfg.autonomy.go_minutes) || cfg.autonomy.go_minutes < 1)
@@ -581,8 +591,12 @@ function check(cfg: Config): void {
581
591
  if (!Array.isArray(cfg.guards.rate_limit.patterns) || cfg.guards.rate_limit.patterns.some(p => typeof p !== "string" || p === "")) {
582
592
  throw new ConfigError("guards.rate_limit.patterns must be a list of non-empty strings");
583
593
  }
584
- if (!(cfg.guards.rate_limit.default_wait_s >= 1)) throw new ConfigError("guards.rate_limit.default_wait_s must be >= 1");
585
- if (!(cfg.guards.rate_limit.max_wait_s >= 1)) throw new ConfigError("guards.rate_limit.max_wait_s must be >= 1");
594
+ if (!(cfg.guards.rate_limit.probe_interval_s >= 1)) throw new ConfigError("guards.rate_limit.probe_interval_s must be >= 1");
595
+ if (!(cfg.guards.rate_limit.max_probes >= 1)) throw new ConfigError("guards.rate_limit.max_probes must be >= 1");
596
+ if (!(cfg.guards.rate_limit.probe_timeout_s >= 1)) throw new ConfigError("guards.rate_limit.probe_timeout_s must be >= 1");
597
+ if (typeof cfg.guards.rate_limit.probe_cmd !== "string" || !cfg.guards.rate_limit.probe_cmd.includes("{model}")) {
598
+ throw new ConfigError("guards.rate_limit.probe_cmd must be a string containing {model}");
599
+ }
586
600
  if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
587
601
  if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
588
602
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
@@ -791,6 +805,7 @@ export function loadConfig(opts: LoadOptions = {}): Config {
791
805
  applyEnv(merged, opts.env ?? process.env);
792
806
  const expanded = expand(merged, home) as Config;
793
807
  expanded.notices = notices;
808
+ expanded.file = file;
794
809
  check(expanded);
795
810
  return expanded;
796
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);