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/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.
@@ -315,17 +322,11 @@ Then set `secrets.proxy: secretgate` and restart Main: `neurastream main` starts
315
322
 
316
323
  ## Provider rate limits
317
324
 
318
- When a Main turn ends on a provider rate limit, neurastream waits it out instead of asking again straight into the limit. The stop guard sees the turn's error text, matches it against `guards.rate_limit.patterns` (default `["429", "rate_limit", "rate limit", "overloaded", "529"]`, case-insensitive) and, on a hit, allows the stop without consulting the normal stop rules or touching the idle-stop counters. The chat channels get one post per episode — `⏳ Main is rate limited by its provider until HH:MM (local); it resumes on its own.` — and exactly one resume timer is armed (replacing any earlier one). When the wait is over, the plugin gives Main a new turn: `main-guard: the provider rate limit is over (waited until HH:MM). Continue the queue where you stopped.`, and the guard log carries the whole story:
319
-
320
- ```
321
- RATE-LIMIT stop: resume at 08:12 (35s, attempt 1)
322
- notify: posted (rate-limit)
323
- RATE-LIMIT resume: new turn sent (waited until 08:12)
324
- ```
325
+ When a Main turn ends on a provider rate limit, the stop guard matches the turn's error text against `guards.rate_limit.patterns` (default `["429", "rate_limit", "rate limit", "overloaded", "529"]`, case-insensitive), allows the stop without consulting the normal stop rules, and one episode opens. The chat channels get the first of exactly two posts: `⏳ Main hit its limit at HH:MM; resets at HH:MM` when the error text names a reset — a `retry-after-ms=<ms>` or `retry-after: <seconds>` the provider appended, or a timestamp it printed — or `⏳ Main hit its limit at HH:MM; checking every 5 min` when it names none.
325
326
 
326
- The wait is the `retry-after-ms=<ms>` or `retry-after: <seconds>` the error text names (omp appends the provider's header to the error message), else `default_wait_s` (300). A turn the resume started that ends on a limit again is the same episode at attempt 2: named retry-after values remain unchanged; only the default wait doubles, no second post. Any turn that ends without a limit ends the episode and disarms the timer. Every wait is clamped to `max_wait_s` (3600) before `slack_s` (15) is added on top. Your own message takes over and cancels the resume (`RATE-LIMIT resume cancelled: owner message`) when it starts a turn; a slash command or a handled input such as a chat unlock leaves the resume armed. A rate-limited deferred hand-back (an `agent_end` while an async job is pending) arms the same timer instead of logging "no reply text". The words and the waits live in `config.yml` (`guards.rate_limit`, `docs/config.md`); turns that did not end on a rate limit are unaffected.
327
+ A named reset is waited out (`slack_s`, default 15, added on top). An unnamed one is probed: a detached child runs `guards.rate_limit.probe_cmd` (default `omp -p --no-extensions --no-session --model {model} 'reply ok'`; `{model}` is replaced by the shell-quoted model, exit 0 = the provider answered) every `probe_interval_s` (default 300), killing any probe that runs longer than `probe_timeout_s` (default 90) — a killed or failing probe counts as still limited — up to `max_probes` (default 288 = 24 h at one probe per 5 min). When the named reset passes or a probe gets through, the plugin gives Main a new turn — `main-guard: the provider limit is over (back at HH:MM). Continue the queue where you stopped.` — and posts `✅ Main is back at HH:MM (limited N min, M checks)`; when `max_probes` is spent without an answer it posts `⚠ Main still limited after 24 h` once and closes the episode. Each finished episode appends one `{type: "limit", since, back_at, minutes, probes, reset_named}` metric, and the weekly report shows it as "Main limited: N h over K episodes". Posts, metric and report carry times and counts only, never the provider's error text.
327
328
 
328
- omp retries a 429 itself while the provider's wait fits its `retry.maxDelayMs` (300000 ms by default); only a longer wait ends the turn (`Retry failed after 1 attempts: Provider requested 731000ms wait, exceeds retry.maxDelayMs`), and that turn end is what neurastream waits out.
329
+ Your own message takes over and cancels the wait (`RATE-LIMIT tick cancelled: owner message (probe count kept)`) when it starts a turn; a slash command or a handled input such as a chat unlock leaves it armed. A rate-limited deferred hand-back does not open a second episode. omp itself retries a 429 while the provider's wait fits its `retry.maxDelayMs` (300000 ms by default); only a longer wait ends the turn (`Retry failed after 1 attempts: Provider requested 731000ms wait, exceeds retry.maxDelayMs`), and that turn end is what opens the episode.
329
330
 
330
331
  ## Provider reset times
331
332
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.66",
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,8 +29,10 @@ 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";
33
- import { rateLimitWait } from "../../core/rate-limit.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
+ import { rateLimited } from "../../core/rate-limit.ts";
34
+ import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
35
+ import { appendMetric } from "../../core/metrics.ts";
34
36
  import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
35
37
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
36
38
  import { inboxPath } from "../../core/owner-ui.ts";
@@ -40,7 +42,7 @@ import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from
40
42
  import { applyQueueEnv } from "../../core/queue/env.ts";
41
43
  import { mainDetectors, mainStartText } from "../../core/main-start.ts";
42
44
 
43
- import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, withUnanswered, type RolloverState } from "../../core/rollover.ts";
45
+ import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, type RolloverState } from "../../core/rollover.ts";
44
46
  import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
45
47
  import { adapterLog, MAIN_ENV } from "./launch.ts";
46
48
  import { parseTraceFile } from "./traces.ts";
@@ -51,6 +53,25 @@ import { annotateResetTimes } from "../../core/reset-time.ts";
51
53
  // Registers the plugin-command matcher into core's writeTargets (side effect).
52
54
  import "./package-ops.ts";
53
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
+
54
75
  /** TraceEvents of the newest Main session file (D8's input); [] when there is none or it cannot be read. */
55
76
  function defaultMainEvents(cfg: Config): TraceEvent[] {
56
77
  try {
@@ -76,6 +97,7 @@ interface HostCtx {
76
97
  id?: string;
77
98
  cwd?: string;
78
99
  setInterval?: (cb: () => void, ms: number) => unknown;
100
+ spawnLimitProbe?: () => void;
79
101
  }
80
102
 
81
103
  function asRecord(v: unknown): Record<string, unknown> {
@@ -139,6 +161,9 @@ function asCtx(v: unknown): HostCtx {
139
161
  // Harness-injected timer with the original main-guard signature (ctx.setInterval).
140
162
  const interval = r.setInterval as ((cb: () => void, ms: number) => unknown) | undefined;
141
163
  if (typeof interval === "function") out.setInterval = interval;
164
+ // Harness-injected probe spawner (tests); the default starts the niced probe child.
165
+ const probe = r.spawnLimitProbe as (() => void) | undefined;
166
+ if (typeof probe === "function") out.spawnLimitProbe = probe;
142
167
  return out;
143
168
  }
144
169
 
@@ -283,8 +308,9 @@ function writeCheckSnapshot(tool: string, input: Record<string, unknown>, cwd: s
283
308
 
284
309
  // Plan files a subagent write/edit may touch: snapshot before the call so tool_result can verify
285
310
  // and restore (the original snapshotted inside checkCall; core returns pure decisions now).
286
- 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 {
287
312
  if (tool !== "write" && tool !== "edit") return;
313
+ const delegated = currentPlanner(cfg) === "delegated";
288
314
  const plans = q.activePlans();
289
315
  for (const p of q.writeTargets(tool, input, cwd)) {
290
316
  if (snap.has(p)) continue;
@@ -298,7 +324,12 @@ function snapshotPlans(tool: string, input: Record<string, unknown>, cwd: string
298
324
  }
299
325
  continue;
300
326
  }
301
- 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
+ }
302
333
  try {
303
334
  snap.set(p, readFileSync(p, "utf8"));
304
335
  } catch {}
@@ -353,14 +384,18 @@ function recordProviderOutFromTask(e: Record<string, unknown>, content: unknown[
353
384
  adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (task result)`);
354
385
  }
355
386
 
356
- /** Rate-limited turn end: record the reset time the error text names, else the armed wait. */
357
- function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): void {
358
- const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
359
- if (!provider) return;
387
+ /** Rate-limited turn end: record the reset time the error text names, else the armed wait. Returns the
388
+ * named reset in epoch ms (null when the text names none): the one parse of that text, which the call
389
+ * site passes on to the rate-limit episode (plan 20261027_1500 P2/P3). */
390
+ export function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): number | null {
360
391
  const named = reply ? resetEpochFromText(reply.errorMessage ?? "", resetRule(cfg)) : null;
361
- const epoch = named ?? Math.floor(untilMs / 1000);
362
- recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
363
- adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (${named !== null ? "reset time in error text" : "rate limit, no reset time"})`);
392
+ const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
393
+ if (provider) {
394
+ const epoch = named ?? Math.floor(untilMs / 1000);
395
+ recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
396
+ adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (${named !== null ? "reset time in error text" : "rate limit, no reset time"})`);
397
+ }
398
+ return named === null ? null : named * 1000;
364
399
  }
365
400
 
366
401
  // Session rollover helpers: the harness context read through runtime checks, and the file size and
@@ -595,12 +630,23 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
595
630
 
596
631
  /** The most recently registered createOmpAdapter cleanup, for the exported reset(). */
597
632
  let activeAdapterReset: (() => void) | null = null;
633
+ /** The limit tick: one check of the open episode every 30 s (plan 20261027_1500 P3). */
634
+ const LIMIT_TICK_MS = 30_000;
635
+ /** One limit probe as a niced child (cli/limit-probe.ts). It writes the episode state itself;
636
+ * a failed start is logged and the next tick tries again. */
637
+ function spawnLimitProbeChild(cfg: Config): void {
638
+ const child = spawn("nice", ["-n", "19", process.execPath, join(import.meta.dir, "../../cli/limit-probe.ts")], { detached: true, stdio: "ignore", env: process.env });
639
+ child.on("error", err => adapterLog(cfg, `RATE-LIMIT probe: could not start: ${err.message}`));
640
+ child.unref();
641
+ }
598
642
  /** Register the guard handlers on one extension host. `initial` is injectable for tests; `freshConfig` re-reads the config per guarded call. */
599
643
  export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial): void {
600
644
  // Guarded handlers take `cfg = freshConfig()` first, so an edited config.yml reaches the next call (P4e).
601
645
  let cfg = initial;
602
646
  // The queue library resolves its paths from env snapshots; point them at this config first.
603
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);
604
650
  // P5: seed the per-Main inbox floor once — a Main that has never delivered starts past rows
605
651
  // that predate its registration; the pre-multi-main cursor file belongs to the default id's
606
652
  // first start. Later reads/writes own the file, so the floor is only a creation-time default.
@@ -643,24 +689,25 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
643
689
  // emits (sessionStopWillContinue) consumes it and posts nothing — a blocked stop's reply is a
644
690
  // mid-work report, never a hand-back.
645
691
  let stopBlocked = false;
646
- // Rate-limit wait-it-out (plan 20261025_0640): consecutive turn ends on a provider rate limit
647
- // form one episode. Named provider retry-after values remain authoritative; otherwise the
648
- // attempt doubles the default wait. The owner chat is told once per episode, and ONE timer
649
- // gives Main a new turn when the wait is over; a new Main turn before expiry takes over and
650
- // cancels it. Inputs that do not start a turn leave it armed. Any turn that ends without a
651
- // limit resets the episode and disarms it.
652
- let rateAttempt = 0;
653
- let rateTimer: NodeJS.Timeout | null = null;
692
+ // Rate-limit probe loop (plan 20261027_1500 P3). A limited turn end opens one episode in
693
+ // main-limit.json: a named reset is waited for; otherwise a niced probe child runs every
694
+ // probe_interval_s until one gets through or max_probes is spent. ONE tick (LIMIT_TICK_MS)
695
+ // reads the episode: it spawns a due probe, or, once the provider is back, sends Main ONE new
696
+ // turn. A new Main turn cancels the tick and keeps the episode (probe count kept); a turn that
697
+ // ends without a limit clears it.
698
+ let limitTickArmed = false;
699
+ let limitTick: NodeJS.Timeout | null = null;
654
700
  const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
655
- const clearRateTimer = (): void => {
656
- if (rateTimer !== null) {
657
- clearTimeout(rateTimer);
658
- rateTimer = null;
701
+ const stopLimitTick = (): void => {
702
+ limitTickArmed = false;
703
+ if (limitTick !== null) {
704
+ clearInterval(limitTick);
705
+ limitTick = null;
659
706
  }
660
707
  };
661
708
  const disarmRateEpisode = (): void => {
662
- clearRateTimer();
663
- rateAttempt = 0;
709
+ stopLimitTick();
710
+ clearLimitState(cfg);
664
711
  };
665
712
  // P5b: a real turn end answers every owner message it followed — the answer (the turn's own
666
713
  // reply, the page's lastAnswerFor shape) rides the same owner-message store. Rate-limited,
@@ -673,32 +720,69 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
673
720
  adapterLog(cfg, `OWNER-ANSWER record failed: ${err instanceof Error ? err.message : String(err)}`);
674
721
  }
675
722
  };
676
- // The one resume: replacing any armed timer, exactly one new user message when the wait is over.
677
- const armRateResume = (untilMs: number): void => {
678
- clearRateTimer();
679
- rateTimer = setTimeout(() => {
680
- rateTimer = null;
681
- // P5b: whichever resume text exists, it quotes owner messages no turn has answered.
682
- pi.sendUserMessage(withUnanswered(`main-guard: the provider rate limit is over (waited until ${rateClock(untilMs)}). Continue the queue where you stopped.`, readOwnerMessages(), readOwnerAnswers()));
683
- adapterLog(cfg, `RATE-LIMIT resume: new turn sent (waited until ${rateClock(untilMs)})`);
684
- }, untilMs - Date.now());
723
+ const limitTickFire = (c: HostCtx): void => {
724
+ if (!limitTickArmed) return;
725
+ const state = readLimitState(cfg);
726
+ if (state === null) {
727
+ stopLimitTick();
728
+ adapterLog(cfg, "RATE-LIMIT give up: episode state gone (max_probes spent or unreadable)");
729
+ return;
730
+ }
731
+ const now = Date.now();
732
+ if (state.back_at !== null) {
733
+ if (now < state.back_at) return;
734
+ stopLimitTick();
735
+ clearLimitState(cfg);
736
+ // P4: the finished episode is recorded once and the owner hears one back post; both are
737
+ // times and counts only — the episode's last_error never reaches chat or ledger.
738
+ appendMetric(cfg, limitMetric(state, now));
739
+ adapterLog(cfg, `RATE-LIMIT back: provider limit over (back at ${rateClock(state.back_at)}); new turn sent`);
740
+ void postReply(backPost(state), cfg).then(results => {
741
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
742
+ });
743
+ pi.sendUserMessage(`main-guard: the provider limit is over (back at ${rateClock(state.back_at)}). Continue the queue where you stopped.`);
744
+ return;
745
+ }
746
+ if (now < state.next_probe_at) return;
747
+ (c.spawnLimitProbe ?? (() => spawnLimitProbeChild(cfg)))();
685
748
  };
686
- // A turn that ended on a rate limit: log, tell the owner once per episode, arm the resume.
687
- const onRateLimitedStop = (untilMs: number, waitMs: number): void => {
688
- rateAttempt++;
689
- const at = rateClock(untilMs);
690
- adapterLog(cfg, `RATE-LIMIT stop: resume at ${at} (${Math.round(waitMs / 1000)}s, attempt ${rateAttempt})`);
691
- if (rateAttempt === 1) {
749
+ const armLimitTick = (c: HostCtx): void => {
750
+ stopLimitTick();
751
+ limitTickArmed = true;
752
+ const t: unknown = c.setInterval ? c.setInterval(() => limitTickFire(c), LIMIT_TICK_MS) : setInterval(() => limitTickFire(c), LIMIT_TICK_MS);
753
+ if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
754
+ limitTick = t as NodeJS.Timeout;
755
+ };
756
+ // A turn that ended on a provider rate limit: the episode opens (or continues with its probe
757
+ // count), the owner chat hears once per episode, and the tick takes over.
758
+ const onRateLimitedStop = (c: HostCtx, namedResetMs: number | null, errorText: string, model: string): void => {
759
+ const prev = readLimitState(cfg);
760
+ const timing = timingOf(cfg);
761
+ const state = onLimited(prev, namedResetMs, errorText, Date.now(), model, timing);
762
+ try {
763
+ writeLimitState(cfg, state);
764
+ } catch (err) {
765
+ adapterLog(cfg, `RATE-LIMIT state write failed: ${err instanceof Error ? err.message : String(err)}`);
766
+ return;
767
+ }
768
+ adapterLog(cfg, `RATE-LIMIT stop: ${state.reset_named ? "named reset" : "probe"} at ${rateClock(state.next_probe_at)} (probes ${state.probes} of ${timing.max_probes})`);
769
+ if (prev === null) {
692
770
  adapterLog(cfg, "notify: posted (rate-limit)");
693
- void postReply(`⏳ Main is rate limited by its provider until ${at} (local); it resumes on its own.`, cfg).then(results => {
771
+ void postReply(limitedPost(state, timing.probe_interval_s), cfg).then(results => {
694
772
  for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
695
773
  });
696
774
  }
697
- armRateResume(untilMs);
775
+ armLimitTick(c);
776
+ };
777
+ // The rate-limit decision for one turn end, from the event's own last assistant message. The
778
+ // untilMs is the fallback wait recorded with PROVIDER-OUT when the error text names no reset.
779
+ const rateLimitOf = (reply: EventReply | null): { untilMs: number } | null => {
780
+ const rl = cfg.guards.rate_limit;
781
+ const hit = rateLimited(reply?.stopReason ?? null, reply?.errorMessage ?? null, rl);
782
+ if (!hit) return null;
783
+ const waitMs = (hit.retryAfterMs ?? rl.probe_interval_s * 1000) + rl.slack_s * 1000;
784
+ return { untilMs: Date.now() + waitMs };
698
785
  };
699
- // The rate-limit decision for one turn end, from the event's own last assistant message.
700
- const rateLimitOf = (reply: EventReply | null): { untilMs: number; waitMs: number } | null =>
701
- rateLimitWait(reply?.stopReason ?? null, reply?.errorMessage ?? null, Date.now(), cfg.guards.rate_limit, rateAttempt + 1);
702
786
  // One guard-log line per notify decision: `notify: posted|skipped (<why>)`. Fire-and-forget:
703
787
  // the decision never awaits the post; a failed or slow post logs one line and never blocks
704
788
  // or retries.
@@ -860,7 +944,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
860
944
  };
861
945
 
862
946
  pi.on("before_agent_start", (event, ctx) => {
863
- cfg = freshConfig();
947
+ cfg = freshPlannerConfig(freshConfig);
864
948
  const c = asCtx(ctx);
865
949
  const prompt = asString(asRecord(event).prompt);
866
950
  if (c.kind !== "main") {
@@ -871,9 +955,9 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
871
955
  const content = unhanded(asString(c.id) || "sub", plans.find(file => prompt.includes(file)) ?? null);
872
956
  return content ? { message: { customType: "main-guard.rules", content, display: false } } : undefined;
873
957
  }
874
- if (rateTimer !== null) {
875
- clearRateTimer();
876
- adapterLog(cfg, "RATE-LIMIT resume cancelled: owner message");
958
+ if (limitTickArmed) {
959
+ stopLimitTick();
960
+ adapterLog(cfg, "RATE-LIMIT tick cancelled: owner message (probe count kept)");
877
961
  }
878
962
  const d = checkInject({ inject: prompt, agent: "main" }, cfg);
879
963
  callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
@@ -906,7 +990,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
906
990
  // The spawn event carries no brief, so the plan gate runs at the task tool call (original
907
991
  // behaviour); here only the allow-list and the task-only rule apply, with the original texts.
908
992
  pi.on("before_subagent_spawn", (event, _ctx) => {
909
- cfg = freshConfig();
993
+ cfg = freshPlannerConfig(freshConfig);
910
994
  const agent = asString(asRecord(event).agent);
911
995
  const kind = asString(asRecord(event).invocationKind);
912
996
  if (!q.allowedAgents().has(agent))
@@ -919,7 +1003,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
919
1003
  let lastMainRc: RolloverCtx | null = null;
920
1004
 
921
1005
  pi.on("tool_call", (event, ctx) => {
922
- cfg = freshConfig();
1006
+ cfg = freshPlannerConfig(freshConfig);
923
1007
  const c = asCtx(ctx);
924
1008
  const e = asRecord(event);
925
1009
  const tool = asString(e.toolName);
@@ -932,8 +1016,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
932
1016
  if (isSub) calls.set(id, n);
933
1017
  if (!isSub) callsSinceStop++;
934
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;
935
1022
  const snap = new Map<string, string>();
936
- snapshotPlans(tool, input, cwd, snap, !isSub);
1023
+ snapshotPlans(tool, input, cwd, snap, !isSub, plannerPlan, cfg);
937
1024
  // Drain (src/core/rollover.ts): while a rollover is pending no new subagent starts; the
938
1025
  // running ones finish first. Subagents' own tool calls are unaffected. Main's task calls
939
1026
  // also carry the running job labels for the priority gate (20261025_0215 P2).
@@ -993,7 +1080,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
993
1080
  };
994
1081
 
995
1082
  pi.on("tool_result", (event, ctx) => {
996
- cfg = freshConfig();
1083
+ cfg = freshPlannerConfig(freshConfig);
997
1084
  // P9: an owner message past notify.answer_within_min with no hand-back steers once per
998
1085
  // message; sendUserMessage reaches Main mid-turn through the steer queue.
999
1086
  if (isMain(ctx)) {
@@ -1113,7 +1200,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1113
1200
  });
1114
1201
 
1115
1202
  pi.on("session_stop", (e, ctx) => {
1116
- cfg = freshConfig();
1203
+ cfg = freshPlannerConfig(freshConfig);
1117
1204
  const c = asCtx(ctx);
1118
1205
  if (c.hasAgent && c.kind !== "main") return;
1119
1206
  // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
@@ -1133,13 +1220,14 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1133
1220
  const rl = rateLimitOf(reply);
1134
1221
  if (rl) {
1135
1222
  // Who is rate-limited is live data (plan 20261025_1700 P1): the error text's own reset
1136
- // time, else the armed wait. Best effort — a failed write never changes the stop.
1223
+ // time, else the fallback wait. Best effort — a failed write never changes the stop.
1224
+ let named: number | null = null;
1137
1225
  try {
1138
- recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
1226
+ named = recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
1139
1227
  } catch (err) {
1140
1228
  adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1141
1229
  }
1142
- onRateLimitedStop(rl.untilMs, rl.waitMs);
1230
+ onRateLimitedStop(c, named, reply?.errorMessage ?? "", reply?.model ?? "");
1143
1231
  return undefined;
1144
1232
  }
1145
1233
  // Any turn that ends without a rate limit ends the episode and disarms its resume timer.
@@ -1302,7 +1390,10 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1302
1390
  };
1303
1391
  // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
1304
1392
  activeAdapterReset?.();
1305
- activeAdapterReset = clearRolloverState;
1393
+ activeAdapterReset = (): void => {
1394
+ clearRolloverState();
1395
+ stopLimitTick();
1396
+ };
1306
1397
  // The launcher restarts omp: the request file carries the note and the editor draft, and omp
1307
1398
  // shuts down only after the file is written. A failed write keeps the session running.
1308
1399
  // Returns whether the request was written.
@@ -1395,12 +1486,20 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1395
1486
  }
1396
1487
  const reply = lastAssistantIn(asRecord(e).messages);
1397
1488
  // The same rate-limit check as session_stop (plan 20261025_0640): a rate-limited deferred
1398
- // hand-back arms the resume timer instead of logging "no reply text" — its reply carries an
1489
+ // hand-back opens the episode instead of logging "no reply text" — its reply carries an
1399
1490
  // error, no text. A mid-run continuation (tool calls, auto-retry) is not a turn end: the
1400
1491
  // episode state stays as it is.
1401
1492
  const rl = rateLimitOf(reply);
1402
1493
  if (rl) {
1403
- onRateLimitedStop(rl.untilMs, rl.waitMs);
1494
+ // The same one parse as session_stop (plan 20261027_1500 P1/P3): the error text's own
1495
+ // reset time, else the fallback wait. Best effort — a failed write never changes the stop.
1496
+ let named: number | null = null;
1497
+ try {
1498
+ named = recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
1499
+ } catch (err) {
1500
+ adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1501
+ }
1502
+ onRateLimitedStop(asCtx(ctx), named, reply?.errorMessage ?? "", reply?.model ?? "");
1404
1503
  return;
1405
1504
  }
1406
1505
  const jobCount = asRolloverCtx(ctx)?.runningJobs().length ?? 0;
@@ -1482,8 +1581,12 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1482
1581
  if (note) pendingReviewNotes.push(note);
1483
1582
  });
1484
1583
 
1485
- // omp is really shutting down: the exit-grace fallback must not fire.
1486
- 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
+ });
1487
1590
 
1488
1591
  // Compaction keeps the owner's holds true: a summary may state a hold only as a plans' WAITING on owner line says it.
1489
1592
  pi.on("session.compacting", (_e, ctx) => {
@@ -1550,6 +1653,11 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1550
1653
  notifyTier(ctx, t);
1551
1654
  return { handled: true };
1552
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
+ }
1553
1661
  const g = chatGo(text, cfg, "interactive");
1554
1662
  if (g.applied) {
1555
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));