neurastream 0.2.24 → 0.2.26

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
@@ -26,12 +26,12 @@ flowchart LR
26
26
  | Queue (`queue-check`, `queue-close`, `queue-cancel`) | Every open plan is a file in a main checkout, listed in the one main index (`paths.queue_index`, one absolute path per line — never repo directories) and follows a template; one plan = one worktree. A plan leaves the queue only when its branch is merged into remote main and its done check passes; a failing check reopens it. Closing removes the plan's worktree when it is clean and its branch landed — a plain `git worktree remove`; a dirty, unmerged or unremovable worktree and the repo's main checkout are kept with the reason. Branches leave only via `git branch -d`, so a branch whose merge git cannot see stays. |
27
27
  | Blockers | Each plan's phase 0 lists what helpers may not do: push, touch a path, run a command, or write a text. The guard judges the command that runs and the files it changes, not words inside commit messages, quoted text or heredoc bodies: `git commit -m "... push ..."` is allowed, `git push` is refused. |
28
28
  | Guards | Helpers may only edit their plan's `## Progress`; every new entry ends with a `Findings:` line (`Findings: none`, or one item per finding with `file:line` evidence) or the edit is refused and the file restored, and each item becomes an incident. Helpers get a warning at call 90 and are stopped at call 100; Main can set a different stop for one run with a `Call budget: <N>` line in the task brief (see "Main reads the code for its plans" below). Protected files need an owner unlock (a file the owner touches, valid 30 minutes). With `guards.chat_unlock` on (default off), the owner's whole chat message `unlock` / `unlock N` / `lock` — typed in the terminal or through a collab guest prompt from a write peer — moves that file instead; nothing a model, a subagent or a tool produces can. |
29
- | Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs 2. |
29
+ | Ledger (`agent-ledger`) | Tokens, cost, state and exit reason per agent; `--cap` refuses a spawn when a provider already runs `ledger.max_running_per_provider` (default 2), when a run is `OVER-BUDGET` (unless `--incident <id>`), or when a priority plan has no running agent (unless `--priority`). |
30
30
  | Scoring (`agent-score`) | Points only for work Main accepted by commit, times the phase difficulty. Ranked per dollar and per hour. |
31
31
  | Brief lint (`brief-lint`) | Refuses a helper brief that misses a required rule (acceptance, stop condition, no push, call budget). |
32
32
  | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
33
33
  | Unlanded work (`wip-check`, `wip-snapshot`, `wip-backup`) | Lists branches on no remote and dirty worktrees; snapshots them as hidden commits; can push them to a backup repo. |
34
- | Session rollover | When the main session file passes 5 MB, the next owner message starts a fresh session from a handoff note. |
34
+ | Session rollover | When the main session file passes 5 MB, or the installed neurastream version differs from the running plugin, Main writes a handoff note; under `neurastream main` a fresh session starts on its own, under plain omp the next owner message starts it. |
35
35
  | Owner page (`neurastream ui`) | One phone-sized page over Tailscale (`ui.*` config): the plans waiting on the owner with answer buttons, the guard unlock, running agents, the queue, recent merges/CI, open incidents, agent scores, machine health. Serves only a tailnet peer whose `tailscale whois` login equals `ui.owner_login`, only with a Host header naming the tailnet address or the MagicDNS name — DNS rebinding and every other visitor get a 403. Answers land in the owner inbox and reach Main once each; agents cannot start the page or write the inbox. |
36
36
 
37
37
  ## Requirements
@@ -109,6 +109,10 @@ A plan parked for the owner has one line: `WAITING on owner: <what>`. That line
109
109
 
110
110
  `INDEX.md` order is priority: the top line is rank 1. The queue summary lists plans in that order (`N. <file> [flags] <goal>`). Before a spawn, the guard checks every plan above each plan the brief names. A higher plan that is idle — open, no `WAITING on owner:`, not awaiting merge, still has an unticked phase, and not itself waiting on another open indexed plan via a `Waits on: <plan>` line — and not staffed by a running job blocks the spawn unless the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`, at least four words that appear in an owner message of the last 24 h (`<queue_state>/owner-messages.jsonl`, recorded from Main's prompts); any other skip line is refused. `Waits on:` lines are Main-only, like `WAITING on owner:`. Staffing is `<queue_state>/staffing.json` (each plan's newest spawn's task names) matched against omp's running job labels. The owner reorders the queue by dragging cards on the phone page.
111
111
 
112
+ ## Autonomy tiers
113
+
114
+ One setting decides how much Main does without asking: `autonomy.tier` in the config (default `opinionated`), moved any time by the owner's whole chat message `tier strict|opinionated|full` (when `guards.chat_unlock` is on) or the tier buttons on the phone page — the setting lives in `<queue_state>/autonomy-tier`, a guard-protected path no agent can write. `strict` caps Main's project-file changes at `autonomy.strict_edit_limit` per `guards.main_window_min` minutes and refuses `git push` / `glab mr merge` / `gh pr merge` until the owner types `go` (one landing, valid `autonomy.go_minutes` minutes); `opinionated` keeps today's limits (`guards.main_edit_limit`); `full` drops the cap and lets Main skip an idle higher plan with `Priority skip: <plan> — Main: "<reason>"` (reason ≥ 4 words). No tier loosens the owner-only moves: guard-file edits without the unlock, starting the phone page, reading notify secrets, local `npm publish` and the tier setting itself.
115
+
112
116
  ## Owner page (`neurastream ui`)
113
117
 
114
118
  `neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
@@ -201,7 +205,7 @@ notify: posted (rate-limit)
201
205
  RATE-LIMIT resume: new turn sent (waited until 08:12)
202
206
  ```
203
207
 
204
- 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: the 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.
208
+ 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.
205
209
 
206
210
  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.
207
211
 
@@ -209,6 +213,10 @@ omp retries a 429 itself while the provider's wait fits its `retry.maxDelayMs` (
209
213
 
210
214
  Before Main reads a message, reset timestamps matching `quota.reset_pattern` are annotated with their local time, for example `reset at 2026-10-25 18:56:22 (= 2026-10-25 11:56:22 CET local)`. Set `quota.reset_tz` to the provider's time zone; an explicit zone or UTC offset in the message takes precedence.
211
215
 
216
+ ## Suspicious actions (`neurastream traces actions`)
217
+
218
+ `neurastream traces actions <runId|--since 24h> [--json]` lists the suspicious tool actions a run's trace shows: reads of secret paths (`traces.actions.secret_globs`), network commands (`net_tools`) to unknown hosts, pipes into a shell (`shell_patterns`), and writes outside `write_roots` (empty = `paths.work_roots`; both empty = off) or on `deny_globs`. The high ones also open realtime suspicious-action incidents.
219
+
212
220
  ## Trace claims (`neurastream traces claims`)
213
221
 
214
222
  Agents' final reports assert results — "530 passed", "exit 0", commit SHAs, heavy-run labels, changed files. This command reads a run's trace (its session file, read-only) and checks each claim in the run's last assistant message against what the run's own tool activity shows: a count or exit code must appear in some tool output, a commit SHA must be printed by the output of a git command the run itself ran, a heavy-run label must appear in a quoted heavy-run call, and a changed path must be carried by an edit/write call or a shell write in the path's own command segment. A claim nothing shows becomes a `claim-unbacked` finding.
@@ -319,7 +327,7 @@ Live copies are never hand-edited. `neurastream doctor` names each hand-edited i
319
327
  - Managed: the text between the markers. Install replaces it. A second install changes nothing.
320
328
  - Yours: every line outside the markers. Install keeps it byte for byte. A file with no markers gets the block appended.
321
329
  - Drift: `neurastream doctor` reports `stale:` when the text between the markers differs from the package's block, and `missing:` when the markers are absent. Edits outside the markers are never reported.
322
- - Edit limit: the project-file changes Main gets per window come from `guards.main_edit_limit` and `guards.main_window_min`, not from the block text.
330
+ - Edit limit: the project-file changes Main gets per window come from the config, not from the block text: `guards.main_edit_limit` per `guards.main_window_min` in tier `opinionated`, `autonomy.strict_edit_limit` in tier `strict`, no cap in tier `full`.
323
331
 
324
332
  ## License
325
333
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.24",
3
+ "version": "0.2.26",
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",
@@ -19,6 +19,7 @@ import { execFileSync, spawn } from "node:child_process";
19
19
  import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
20
  import { basename, dirname, join } from "node:path";
21
21
  import type { Decision } from "../../core/adapter.ts";
22
+ import { chatGo, chatTier, type Tier } from "../../core/autonomy.ts";
22
23
  import { loadConfig, type Config } from "../../core/config.ts";
23
24
  import { nowSec, strftime } from "../../core/clock.ts";
24
25
  import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
@@ -462,10 +463,11 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
462
463
  // mid-work report, never a hand-back.
463
464
  let stopBlocked = false;
464
465
  // Rate-limit wait-it-out (plan 20261025_0640): consecutive turn ends on a provider rate limit
465
- // form one episode. The attempt doubles the wait, the owner chat is told once per episode, and
466
- // ONE timer gives Main a new turn when the wait is over; a new Main turn before expiry takes
467
- // over and cancels it. Inputs that do not start a turn leave it armed. Any turn that ends
468
- // without a limit resets the episode and disarms it.
466
+ // form one episode. Named provider retry-after values remain authoritative; otherwise the
467
+ // attempt doubles the default wait. The owner chat is told once per episode, and ONE timer
468
+ // gives Main a new turn when the wait is over; a new Main turn before expiry takes over and
469
+ // cancels it. Inputs that do not start a turn leave it armed. Any turn that ends without a
470
+ // limit resets the episode and disarms it.
469
471
  let rateAttempt = 0;
470
472
  let rateTimer: NodeJS.Timeout | null = null;
471
473
  const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
@@ -1092,8 +1094,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1092
1094
  return null;
1093
1095
  };
1094
1096
 
1095
- // Chat unlock (guards.chat_unlock): the owner's whole message "unlock"/"unlock N"/"lock" moves
1096
- // the guard unlock file (src/core/queue/lib.ts chatUnlock). Only prompts the owner really typed
1097
+ // Chat unlock + autonomy tiers (guards.chat_unlock): the owner's whole message "unlock"/
1098
+ // "unlock N"/"lock" moves the guard unlock file, "tier <name>" sets the autonomy tier and
1099
+ // "go" approves one strict landing (src/core/queue/lib.ts chatUnlock, src/core/autonomy.ts
1100
+ // chatTier/chatGo). Only prompts the owner really typed
1097
1101
  // count: the local terminal (input event, source "interactive") and collab guest prompts from
1098
1102
  // write peers. This handler is registered BEFORE the rollover input handler below, so the unlock
1099
1103
  // wins while a rollover is ready or in flight (emitInput short-circuits on { handled: true }).
@@ -1107,10 +1111,32 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1107
1111
  c.notify("guard locked again");
1108
1112
  }
1109
1113
  };
1114
+ // The tier switch and the one-shot `go` travel the same two owner paths and answer the same way.
1115
+ const notifyTier = (ctx: unknown, r: { tier?: Tier }): void => {
1116
+ const c = asRolloverCtx(ctx);
1117
+ if (!c || r.tier === undefined) return;
1118
+ c.notify(`tier now ${r.tier}`);
1119
+ };
1120
+ const notifyGo = (ctx: unknown, r: { minutes?: number }): void => {
1121
+ const c = asRolloverCtx(ctx);
1122
+ if (!c || r.minutes === undefined) return;
1123
+ c.notify(`go: one push/merge approved for ${r.minutes} min`);
1124
+ };
1110
1125
  pi.on("input", (event, ctx) => {
1111
1126
  if (!cfg.guards.chat_unlock || !isMain(ctx)) return undefined;
1112
1127
  const e = asRecord(event);
1113
1128
  if (asString(e.source) !== "interactive") return undefined;
1129
+ const text = asString(e.text);
1130
+ const t = chatTier(text, cfg, "interactive");
1131
+ if (t.applied) {
1132
+ notifyTier(ctx, t);
1133
+ return { handled: true };
1134
+ }
1135
+ const g = chatGo(text, cfg, "interactive");
1136
+ if (g.applied) {
1137
+ notifyGo(ctx, g);
1138
+ return { handled: true };
1139
+ }
1114
1140
  const r = q.chatUnlock(asString(e.text), cfg, "interactive");
1115
1141
  if (!r.applied) return undefined;
1116
1142
  notifyUnlock(ctx, r);
@@ -1146,7 +1172,17 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
1146
1172
  if (seenChatPrompts.has(key)) continue;
1147
1173
  seenChatPrompts.add(key);
1148
1174
  const r = q.chatUnlock(text, cfg, `collab:${from}`);
1149
- if (r.applied) notifyUnlock(ctx, r);
1175
+ if (r.applied) {
1176
+ notifyUnlock(ctx, r);
1177
+ continue;
1178
+ }
1179
+ const t = chatTier(text, cfg, `collab:${from}`);
1180
+ if (t.applied) {
1181
+ notifyTier(ctx, t);
1182
+ continue;
1183
+ }
1184
+ const g = chatGo(text, cfg, `collab:${from}`);
1185
+ if (g.applied) notifyGo(ctx, g);
1150
1186
  }
1151
1187
  }
1152
1188
  const rule = { pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz };
@@ -0,0 +1,97 @@
1
+ // Autonomy tiers (I-20261025-177): one owner setting — strict / opinionated / full — that the
2
+ // guards follow. The tier and a one-shot `go` are written only by the owner's own words (the same
3
+ // paths as chatUnlock: the terminal input event and collab write-peer messages) or the
4
+ // authenticated phone page; never by a tool call (the state dir is protected) and never from
5
+ // model text. Every tier keeps the owner-only moves owner-only; no tier loosens them.
6
+
7
+ import { appendFileSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import path from "node:path";
9
+ import type { Config } from "./config.ts";
10
+ import { stateDirPath } from "./queue/lib.ts";
11
+
12
+ export type Tier = "strict" | "opinionated" | "full";
13
+ const TIERS: readonly Tier[] = ["strict", "opinionated", "full"];
14
+
15
+ export function tierFile(): string {
16
+ return path.join(stateDirPath(), "autonomy-tier");
17
+ }
18
+
19
+ export function goFile(): string {
20
+ return path.join(stateDirPath(), "autonomy-go");
21
+ }
22
+
23
+ /** The tier the guards follow: `<state dir>/autonomy-tier` when it names one of the three (one word), else the config value. */
24
+ export function currentTier(cfg: Config): Tier {
25
+ try {
26
+ const word = readFileSync(tierFile(), "utf8").trim().toLowerCase();
27
+ if ((TIERS as readonly string[]).includes(word)) return word as Tier;
28
+ } catch {}
29
+ return cfg.autonomy.tier;
30
+ }
31
+
32
+ export interface ChatTierResult {
33
+ /** True when the text was a whole-message `tier <name>` command that took effect. */
34
+ applied: boolean;
35
+ /** The tier now in force. */
36
+ tier?: Tier;
37
+ }
38
+
39
+ const TIER_CMD = /^tier\s+(strict|opinionated|full)$/i;
40
+
41
+ /**
42
+ * Owner tier switch by chat (guards.chat_unlock, the same flag as chatUnlock): the whole trimmed
43
+ * message — "tier strict", "tier opinionated" or "tier full", case-insensitive — writes
44
+ * `<state dir>/autonomy-tier`. Only the adapter and the owner page call this, with text the owner
45
+ * really typed or tapped; a model, a tool result or a machine prompt must never reach it. Every
46
+ * applied switch is logged to the plan-guard log with `word` naming the entry point ("chat" or "ui").
47
+ */
48
+ export function chatTier(text: string, cfg: Config, source: string, word: "chat" | "ui" = "chat"): ChatTierResult {
49
+ if (!cfg.guards.chat_unlock) return { applied: false };
50
+ const m = TIER_CMD.exec(text.trim());
51
+ if (!m) return { applied: false };
52
+ const tier = (m[1] ?? "").toLowerCase() as Tier;
53
+ mkdirSync(stateDirPath(), { recursive: true });
54
+ writeFileSync(tierFile(), `${tier}\n`);
55
+ try {
56
+ appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} TIER ${tier} ${word} source=${source}\n`);
57
+ } catch {}
58
+ return { applied: true, tier };
59
+ }
60
+
61
+ export interface ChatGoResult {
62
+ /** True when the text was a whole-message `go` command that took effect. */
63
+ applied: boolean;
64
+ /** The minutes this `go` stays valid (autonomy.go_minutes), for the owner notice. */
65
+ minutes?: number;
66
+ }
67
+
68
+ /**
69
+ * The strict tier's one-shot landing approval by chat (guards.chat_unlock): the whole trimmed
70
+ * message "go" touches `<state dir>/autonomy-go`; the next strict push/merge consumes it
71
+ * (takeGo). Same trust rules as chatTier.
72
+ */
73
+ export function chatGo(text: string, cfg: Config, source: string, word: "chat" | "ui" = "chat"): ChatGoResult {
74
+ if (!cfg.guards.chat_unlock) return { applied: false };
75
+ if (text.trim().toLowerCase() !== "go") return { applied: false };
76
+ mkdirSync(stateDirPath(), { recursive: true });
77
+ writeFileSync(goFile(), "");
78
+ try {
79
+ appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} GO ${word} source=${source} minutes=${cfg.autonomy.go_minutes}\n`);
80
+ } catch {}
81
+ return { applied: true, minutes: cfg.autonomy.go_minutes };
82
+ }
83
+
84
+ /**
85
+ * Consume a standing `go`: true once — the file is deleted — when it is younger than
86
+ * autonomy.go_minutes; a stale or missing file is false (a stale one is removed).
87
+ */
88
+ export function takeGo(cfg: Config, now = Date.now()): boolean {
89
+ let mtimeMs: number;
90
+ try {
91
+ mtimeMs = statSync(goFile()).mtimeMs;
92
+ } catch {
93
+ return false;
94
+ }
95
+ rmSync(goFile(), { force: true });
96
+ return now - mtimeMs < cfg.autonomy.go_minutes * 60_000;
97
+ }
@@ -133,6 +133,16 @@ export interface Config {
133
133
  protected: string[];
134
134
  ledger_command: string;
135
135
  };
136
+ /** Autonomy tiers (I-20261025-177): how much Main may do without asking. The owner moves the
137
+ * tier (chat `tier <name>`, or the phone page); the guards follow it. */
138
+ autonomy: {
139
+ /** Tier in force when `<state dir>/autonomy-tier` does not name one (src/core/autonomy.ts). */
140
+ tier: "strict" | "opinionated" | "full";
141
+ /** Main's project-file changes per guards.main_window_min window in tier strict. */
142
+ strict_edit_limit: number;
143
+ /** Minutes one owner `go` approves exactly one push/merge in tier strict. */
144
+ go_minutes: number;
145
+ };
136
146
  /** The owner's phone page (`neurastream ui`): binds the tailnet address only. */
137
147
  ui: { enabled: boolean; port: number; owner_login: string };
138
148
  /** Static pages hosted over the tailnet. */
@@ -398,6 +408,12 @@ function check(cfg: Config): void {
398
408
  throw new ConfigError("guards.sub_max_calls_cap must be >= guards.sub_max_calls");
399
409
  }
400
410
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
411
+ if (cfg.autonomy.tier !== "strict" && cfg.autonomy.tier !== "opinionated" && cfg.autonomy.tier !== "full")
412
+ throw new ConfigError('autonomy.tier must be "strict", "opinionated" or "full"');
413
+ if (!Number.isInteger(cfg.autonomy.strict_edit_limit) || cfg.autonomy.strict_edit_limit < 1)
414
+ throw new ConfigError("autonomy.strict_edit_limit must be an integer >= 1");
415
+ if (!Number.isInteger(cfg.autonomy.go_minutes) || cfg.autonomy.go_minutes < 1)
416
+ throw new ConfigError("autonomy.go_minutes must be an integer >= 1");
401
417
  if (!Array.isArray(cfg.guards.rate_limit.patterns) || cfg.guards.rate_limit.patterns.some(p => typeof p !== "string" || p === "")) {
402
418
  throw new ConfigError("guards.rate_limit.patterns must be a list of non-empty strings");
403
419
  }
@@ -10,9 +10,13 @@
10
10
  // - protected guard files, unlockable by the owner for `guards.unlock_minutes`
11
11
  // - subs: no queue-close/queue-cancel, call budget 90/100, plan edits only inside "## Progress",
12
12
  // blocker execution, invalid plans refuse
13
- // - main: 5 project-file changes per `main_window_min` window (owner message resets), spawn
13
+ // - main: project-file changes per `main_window_min` window capped by the autonomy tier
14
+ // (strict: `autonomy.strict_edit_limit`, opinionated: 5, full: none), spawn
14
15
  // gate (allow-list, task-only, open plan, new Progress since last run), bypass launches go
15
- // through the same plan gate, cancel-pending blocks spawns and stops, keep-working stop rule
16
+ // through the same plan gate, cancel-pending blocks spawns and stops, keep-working stop rule;
17
+ // tier strict additionally refuses `git push` / `glab mr merge` / `gh pr merge` until the
18
+ // owner's one-shot `go`, and tier full lets a `Priority skip: <plan> — Main: "<reason>"` line
19
+ // past the priority gate
16
20
  // - incidents: while an incident is open (src/core/incidents.ts: no plan/dismiss/fixed record)
17
21
  // every Main prompt lists it, a spawn must be fix work (its plan cites `INCIDENT <id>`), and
18
22
  // the stop is refused; an incident with a plan no longer blocks
@@ -21,6 +25,7 @@ import { execFileSync } from "node:child_process";
21
25
  import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
22
26
  import path from "node:path";
23
27
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
28
+ import { currentTier, takeGo, type Tier } from "./autonomy.ts";
24
29
  import type { Config } from "./config.ts";
25
30
  import { addIncident, openIncidents, type IncidentView } from "./incidents.ts";
26
31
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
@@ -390,15 +395,18 @@ function priorityIdle(p: Plan, plans: Plan[]): boolean {
390
395
  * Proof is either the higher plan's own `Waits on: <plan>` line for a plan still open in the index
391
396
  * (then it is not idle at all) or a `Priority skip: <path> — owner: "<words>"` line whose quoted
392
397
  * words (≥ 4, normalised) appear in one of `messages` (the owner's recorded words of the last
393
- * 24 h; `now` is the current unix seconds). Any other skip line is refused.
398
+ * 24 h; `now` is the current unix seconds). In tier full (`cfg`) a `Priority skip: <path> —
399
+ * Main: "<reason>"` line with ≥ 4 words is proof too; without `cfg` the refusal behaviour is the
400
+ * pre-tier one. Any other skip line is refused.
394
401
  * `staffed === undefined` means the caller had no running-job info (CLI spawn without it): never
395
402
  * refuse. Plans already named by this call never block it.
396
403
  */
397
- export function priorityProblem(plans: Plan[], named: string[], staffed: string[] | undefined, brief: string, messages: OwnerMessage[] = [], now: number = nowSec()): PriorityOutcome | null {
404
+ export function priorityProblem(plans: Plan[], named: string[], staffed: string[] | undefined, brief: string, messages: OwnerMessage[] = [], now: number = nowSec(), cfg?: Config): PriorityOutcome | null {
398
405
  if (staffed === undefined) return { unknown: true };
399
406
  const namedRanks = named.map(f => plans.findIndex(p => p.file === f)).filter(n => n >= 0);
400
407
  if (!namedRanks.length) return null;
401
408
  const higher = plans.slice(0, Math.min(...namedRanks));
409
+ const tier = cfg ? currentTier(cfg) : "opinionated";
402
410
  const skipLines: Record<string, string> = {};
403
411
  for (const m of brief.matchAll(SKIP_LINE)) {
404
412
  const plan = (m[1] ?? "").trim();
@@ -410,6 +418,13 @@ export function priorityProblem(plans: Plan[], named: string[], staffed: string[
410
418
  const p = higher[i]!;
411
419
  if (!priorityIdle(p, plans) || staffed.includes(p.file)) continue;
412
420
  const why = skipLines[p.file];
421
+ // Tier full (20261025_1940 P2): Main's own >= 4-word reason is proof enough; every other
422
+ // tier refuses it exactly as before — only the owner's recorded words let a skip through.
423
+ const mainWhy = tier === "full" ? why?.match(/^Main:\s*"(.+)"\s*$/) : undefined;
424
+ if (why && mainWhy && mainWhy[1]!.trim().split(/\s+/).length >= 4) {
425
+ skips.push({ plan: p.file, why });
426
+ continue;
427
+ }
413
428
  const quote = why?.match(/^owner:\s*"(.+)"\s*$/);
414
429
  if (why && quote && ownerSaid(quote[1]!, messages, now)) {
415
430
  skips.push({ plan: p.file, why });
@@ -422,7 +437,7 @@ export function priorityProblem(plans: Plan[], named: string[], staffed: string[
422
437
 
423
438
  /** Load staffing and the owner's recorded words, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. */
424
439
  function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string): string | null {
425
- const outcome = priorityProblem(q.activePlans(), named, runningJobs === undefined ? undefined : staffedPlans(readStaffing(), runningJobs), brief, readOwnerMessages(), nowSec());
440
+ const outcome = priorityProblem(q.activePlans(), named, runningJobs === undefined ? undefined : staffedPlans(readStaffing(), runningJobs), brief, readOwnerMessages(), nowSec(), cfg);
426
441
  if (outcome?.unknown) log(cfg.paths.guard_log, "PRIORITY unknown jobs");
427
442
  for (const s of outcome?.skips ?? []) log(cfg.paths.guard_log, `PRIORITY skip ${s.plan}: ${s.why}`);
428
443
  return outcome?.problem ? `${label}: ${outcome.problem}` : null;
@@ -531,6 +546,23 @@ function startsOwnerUi(input: Record<string, unknown>): boolean {
531
546
  });
532
547
  }
533
548
 
549
+ // True when a command segment lands work on a remote (plan 20261025_1940 P2): `git push`,
550
+ // `glab mr merge`, `gh pr merge`. Segment splitting and launcher skipping match startsOwnerUi,
551
+ // so `sh -c "git push"`, `sudo git push` and chained pushes are seen too.
552
+ function landingCommand(input: Record<string, unknown>): boolean {
553
+ const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
554
+ return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
555
+ const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
556
+ let i = 0;
557
+ while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
558
+ const cmd = (words[i] ?? "").split("/").pop() ?? "";
559
+ if (cmd === "git" && words[i + 1] === "push") return true;
560
+ if (cmd === "glab" && words[i + 1] === "mr" && words[i + 2] === "merge") return true;
561
+ if (cmd === "gh" && words[i + 1] === "pr" && words[i + 2] === "merge") return true;
562
+ return false;
563
+ });
564
+ }
565
+
534
566
  // Subagent half of a tool call (the original plan-guard checkCall without the main return).
535
567
  // `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
536
568
  function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
@@ -565,33 +597,39 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
565
597
  return null;
566
598
  }
567
599
 
568
- // Main's edit limit: window starts at the first counted change, resets after main_window_min
569
- // minutes and at every owner message. State lives in the queue state dir so one-shot CLI
570
- // processes share the window (the original kept it in extension memory for one session).
600
+ // Main's edit limit (20261025_1940 P2): the cap follows the autonomy tier — autonomy.strict_edit_limit
601
+ // in strict, guards.main_edit_limit in opinionated, none in full. Window starts at the first counted
602
+ // change, resets after main_window_min minutes and at every owner message. State lives in the queue
603
+ // state dir so one-shot CLI processes share the window (the original kept it in extension memory for
604
+ // one session).
571
605
  function editWindow(e: ToolEvent, input: Record<string, unknown>, cfg: Config): Decision {
572
606
  const files = changedProjectFiles(e.tool, input, e.cwd, cfg);
573
607
  if (!files.length) return ALLOW;
608
+ const tier = currentTier(cfg);
609
+ if (tier === "full") return ALLOW; // no cap: Main works unattended
610
+ const limit = tier === "strict" ? cfg.autonomy.strict_edit_limit : cfg.guards.main_edit_limit;
611
+ const limitName = tier === "strict" ? "autonomy.strict_edit_limit" : "owner limit";
574
612
  const now = Date.now();
575
613
  const w = readWindow();
576
614
  if (w.used.length && now - w.windowStart >= cfg.guards.main_window_min * 60_000) w.used = [];
577
- if (w.used.length >= cfg.guards.main_edit_limit) {
615
+ if (w.used.length >= limit) {
578
616
  const mins = Math.ceil((w.windowStart + cfg.guards.main_window_min * 60_000 - now) / 60_000);
579
- log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${w.used.length} edits: ${files.join(",")}`);
617
+ log(cfg.paths.guard_log, `BLOCK tool=${e.tool} after ${w.used.length} edits (tier ${tier}): ${files.join(",")}`);
580
618
  return deny(
581
- `main-guard: Main already changed project files ${w.used.length} times in this ${cfg.guards.main_window_min}-minute window ` +
582
- `(owner limit ${cfg.guards.main_edit_limit}; resets in ${mins} min). Main writes plans, not code: put the work in a plan ` +
619
+ `main-guard: tier ${tier} — Main already changed project files ${w.used.length} times in this ${cfg.guards.main_window_min}-minute window ` +
620
+ `(${limitName} ${limit}; resets in ${mins} min). Main writes plans, not code: put the work in a plan ` +
583
621
  `(listed in ${q.INDEX}, phase-0 blockers first) and spawn an implementer. Changes so far: ${w.used.join(", ")}`,
584
622
  );
585
623
  }
586
624
  if (!w.used.length) w.windowStart = now;
587
625
  w.used.push(`${e.tool}:${files[0]!}`);
588
626
  writeWindow(w);
589
- const left = cfg.guards.main_edit_limit - w.used.length;
627
+ const left = limit - w.used.length;
590
628
  if (left <= 2)
591
629
  return {
592
630
  allow: true,
593
631
  reason: "",
594
- inject: `main-guard: ${left} project-file change(s) left in this ${cfg.guards.main_window_min}-minute window; then delegate.`,
632
+ inject: `main-guard: tier ${tier} — ${left} project-file change(s) left in this ${cfg.guards.main_window_min}-minute window; then delegate.`,
595
633
  };
596
634
  return ALLOW;
597
635
  }
@@ -662,6 +700,13 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
662
700
  return ALLOW;
663
701
  }
664
702
  if (cfg.guards.shell_tools.includes(e.tool)) {
703
+ // Strict landing gate (20261025_1940 P2): in tier strict every push/merge waits for the
704
+ // owner's one-shot `go` (autonomy.go_minutes); the landing that consumes it goes through.
705
+ // Opinionated and full keep today's allowance. Owner-only rules above are untouched.
706
+ if (landingCommand(input) && currentTier(cfg) === "strict" && !takeGo(cfg)) {
707
+ log(cfg.paths.guard_log, "BLOCK landing: tier strict, no go");
708
+ return deny('main-guard: tier strict — type "go" to approve one push/merge');
709
+ }
665
710
  const command = String(input?.command ?? input?.code ?? "");
666
711
  for (const entry of cfg.guards.bypass_spawn) {
667
712
  if (!bypassRegExp(entry).test(command)) continue;
@@ -888,7 +933,15 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
888
933
  const cancel = continuation ? "" : flagCancel(e.inject, cfg);
889
934
  const incidents = openIncidentList(cfg);
890
935
  const incidentText = incidents.length ? `\n${incidents.map(incidentLine).join("\n")}` : "";
891
- const editLimit = continuation ? "" : `\nmain-guard: Main may change project files at most ${cfg.guards.main_edit_limit} times per ${cfg.guards.main_window_min}-minute window; then delegate.`;
936
+ // 20261025_1940 P2: the injected line names the autonomy tier and what Main does without asking in it.
937
+ const tier = currentTier(cfg);
938
+ const tierNote =
939
+ tier === "strict"
940
+ ? `Main changes at most ${cfg.autonomy.strict_edit_limit} project files per ${cfg.guards.main_window_min} min, and every git push / glab mr merge / gh pr merge waits for your "go" (one landing, valid ${cfg.autonomy.go_minutes} min).`
941
+ : tier === "full"
942
+ ? `Main works unattended: no edit cap, its own "Priority skip: <plan> — Main: \\"<reason>\\"" skips pass, pushes and merges go through. Owner-only moves (guard files, the phone page, notify secrets, the unlock) stay locked.`
943
+ : `Main changes at most ${cfg.guards.main_edit_limit} project files per ${cfg.guards.main_window_min} min; pushes and merges go through.`;
944
+ const editLimit = continuation ? "" : `\nautonomy: ${tier} — ${tierNote}`;
892
945
  return {
893
946
  allow: true,
894
947
  reason: "",
@@ -12,6 +12,7 @@ import { randomUUID } from "node:crypto";
12
12
  import os from "node:os";
13
13
  import { basename, resolve } from "node:path";
14
14
  import type { RunSource } from "./adapter.ts";
15
+ import { chatTier, currentTier, type Tier } from "./autonomy.ts";
15
16
  import type { Config } from "./config.ts";
16
17
  import { nowSec, strftime } from "./clock.ts";
17
18
  import { cpuCount } from "./host.ts";
@@ -435,19 +436,21 @@ function tilesHtml(data: PageData): string {
435
436
  return [needsTile, spendTileHtml(data), runs, plans].join("\n");
436
437
  }
437
438
 
438
- /** The sticky mockup top bar: logo, pill tabs, and the lock pill that posts the unlock/lock forms. */
439
+ /** The sticky mockup top bar: logo, pill tabs, and the lock pill that posts the unlock/lock and tier forms. */
439
440
  function topBarHtml(tab: string, lockMinutesLeft: number | null, cfg: Config): string {
440
441
  const tabs: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"]];
441
442
  const pills = tabs.map(([id, label]) => `<a href="/?tab=${id}"${tab === id ? ` class="on"` : ""}>${label}</a>`).join("");
442
443
  const lockLabel = lockMinutesLeft === null ? "🔒 Off" : `🔓 ${lockMinutesLeft} min`;
443
444
  const unlockForm = (minutes: number) =>
444
445
  `<form method="post" action="/unlock"><input type="hidden" name="minutes" value="${minutes}"><button class="btn" type="submit">Unlock ${minutes} min</button></form>`;
446
+ const tierForm = (name: Tier, label: string) =>
447
+ `<form method="post" action="/tier"><input type="hidden" name="tier" value="${name}"><button class="btn${currentTier(cfg) === name ? " on" : ""}" type="submit">${label}</button></form>`;
445
448
  const off = cfg.guards.chat_unlock
446
449
  ? ""
447
450
  : `<p class="offnote">Unlocking from the page is switched off in the config. To turn it on, set:</p><code class="offcfg">guards: chat_unlock: true</code>`;
448
451
  return `<div class="top"><span class="logo">ns</span>
449
452
  <nav class="pills" aria-label="Sections">${pills}</nav>
450
- <details class="lock" id="lock-pill"><summary>${lockLabel}</summary><div class="lockmenu">${unlockForm(15)}${unlockForm(30)}<form method="post" action="/lock"><button class="btn" type="submit">Lock now</button></form>${off}</div></details>
453
+ <details class="lock" id="lock-pill"><summary>${lockLabel}</summary><div class="lockmenu">${unlockForm(15)}${unlockForm(30)}<form method="post" action="/lock"><button class="btn" type="submit">Lock now</button></form><hr>${tierForm("strict", "Tier: strict")}${tierForm("opinionated", "Tier: opinionated")}${tierForm("full", "Tier: full")}${off}</div></details>
451
454
  </div>`;
452
455
  }
453
456
 
@@ -836,6 +839,21 @@ function handleLock(cfg: Config, login: string): Response {
836
839
  return redirect("/?sent=lock");
837
840
  }
838
841
 
842
+ const TIERS: readonly Tier[] = ["strict", "opinionated", "full"];
843
+
844
+ // Autonomy tier from the phone page (plan 20261025_1940 P3): behind the same auth as every other
845
+ // route, written by the core chatTier with the owner's tapped name; a bad name is a 400 before
846
+ // the core is called, and the chat gate off redirects to the plain-words note like unlock/lock.
847
+ function handleTier(cfg: Config, fields: Record<string, string>, login: string): Response {
848
+ const name = (fields.tier ?? "").trim().toLowerCase();
849
+ if (!(TIERS as readonly string[]).includes(name)) return textRes("tier must be strict, opinionated or full", 400);
850
+ const result = chatTier(`tier ${name}`, cfg, `ui:${login}`, "ui");
851
+ if (!result.applied) return redirect("/?sent=unlock-off");
852
+ mkdirSync(stateDirPath(), { recursive: true });
853
+ appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "tier", tier: result.tier, login })}\n`);
854
+ return redirect(`/?sent=tier&tier=${result.tier}`);
855
+ }
856
+
839
857
  // ---- queue reorder (plan P4): the owner drags a card; INDEX.md is rewritten atomically ----
840
858
 
841
859
  /**
@@ -996,6 +1014,9 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
996
1014
  } else if (req.method === "POST" && url.pathname === "/lock") {
997
1015
  res = handleLock(cfg, login);
998
1016
  code = res.status;
1017
+ } else if (req.method === "POST" && url.pathname === "/tier") {
1018
+ res = handleTier(cfg, await fieldsOf(req), login);
1019
+ code = res.status;
999
1020
  } else if (req.method === "POST" && url.pathname === "/reorder") {
1000
1021
  res = handleReorder(cfg, await fieldsOf(req), login);
1001
1022
  code = res.status;
@@ -24,20 +24,19 @@ export interface RateLimitWait {
24
24
  const RETRY_AFTER_MS = /retry-after-ms[=:]\s*(\d+)/i;
25
25
  const RETRY_AFTER_S = /retry-after[=:]\s*(\d+)/i;
26
26
 
27
- function retryAfterMs(errorText: string, cfg: RateLimitConfig): number {
27
+ function retryAfterMs(errorText: string, cfg: RateLimitConfig): { ms: number; named: boolean } {
28
28
  const ms = RETRY_AFTER_MS.exec(errorText);
29
- if (ms) return Number(ms[1]);
29
+ if (ms) return { ms: Number(ms[1]), named: true };
30
30
  const s = RETRY_AFTER_S.exec(errorText);
31
- if (s) return Number(s[1]) * 1000;
32
- return cfg.default_wait_s * 1000;
31
+ if (s) return { ms: Number(s[1]) * 1000, named: true };
32
+ return { ms: cfg.default_wait_s * 1000, named: false };
33
33
  }
34
34
 
35
35
  /**
36
36
  * The wait for a turn that ended on a provider rate limit, or null when it did not: the stop
37
37
  * reason must be "error" and the error text must contain one of the configured patterns
38
- * (case-insensitive). The wait is the retry-after the text names (`retry-after-ms=<ms>` or
39
- * `retry-after: <seconds>`, else default_wait_s); attempt >= 2 doubles the previous wait of the
40
- * episode; every wait is clamped to max_wait_s, then slack_s is added.
38
+ * (case-insensitive). A named retry-after is used as-is; otherwise default_wait_s is doubled
39
+ * for each later attempt. The resulting wait is clamped to max_wait_s, then slack_s is added.
41
40
  */
42
41
  export function rateLimitWait(
43
42
  stopReason: string | null,
@@ -50,12 +49,15 @@ export function rateLimitWait(
50
49
  const text = errorText.toLowerCase();
51
50
  if (!cfg.patterns.some(p => text.includes(p.toLowerCase()))) return null;
52
51
  const capMs = cfg.max_wait_s * 1000;
53
- let baseMs = retryAfterMs(errorText, cfg);
54
- for (let i = 1; i < Math.max(1, attempt); i++) {
55
- baseMs *= 2;
56
- if (baseMs >= capMs) {
57
- baseMs = capMs;
58
- break;
52
+ const retryAfter = retryAfterMs(errorText, cfg);
53
+ let baseMs = retryAfter.ms;
54
+ if (!retryAfter.named) {
55
+ for (let i = 1; i < Math.max(1, attempt); i++) {
56
+ baseMs *= 2;
57
+ if (baseMs >= capMs) {
58
+ baseMs = capMs;
59
+ break;
60
+ }
59
61
  }
60
62
  }
61
63
  const waitMs = Math.min(baseMs, capMs) + cfg.slack_s * 1000;
@@ -27,3 +27,5 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
27
27
  |`machine-guard`, `heavy-run`|machine-guard at session start and before launches; every test run goes through heavy-run|
28
28
 
29
29
  Guard files are locked for every agent; the owner unlocks with `touch {{AGENT_DIR}}/.guard-unlock` (30 min), or — when `guards.chat_unlock` is on in the config — by typing `unlock 30` in chat (`lock` closes it again).
30
+
31
+ Autonomy tiers: the owner sets how much Main does unattended with one word — `tier strict` (edit cap `autonomy.strict_edit_limit`; every `git push`, `glab mr merge` or `gh pr merge` also waits until the owner types `go`, which approves exactly one landing for `autonomy.go_minutes` minutes), `tier opinionated` (the limits above), or `tier full` (no edit cap, and a `Priority skip: <plan> — Main: "<reason>"` line with a reason of at least four words may skip an idle higher plan). Pushes stay owner-ruled in strict and opinionated as above; whatever the tier, guard files, the phone page, notify secrets and the unlock stay owner-only.
@@ -125,6 +125,11 @@ guards:
125
125
  protected: []
126
126
  ledger_command: "agent-ledger --hours 12"
127
127
 
128
+ autonomy:
129
+ 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
130
+ strict_edit_limit: 2 # Main's project-file changes per main_window_min in tier strict
131
+ go_minutes: 10 # minutes one owner `go` approves exactly one push/merge in tier strict
132
+
128
133
  ui:
129
134
  enabled: false # the owner's phone page (neurastream ui); binds the tailnet address only
130
135
  port: 7787