neurastream 0.3.18 → 0.3.21

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.
Files changed (66) hide show
  1. package/README.md +88 -490
  2. package/package.json +1 -1
  3. package/src/adapters/index.ts +3 -2
  4. package/src/adapters/omp/adapter.ts +2 -1
  5. package/src/adapters/omp/auto-close.ts +64 -0
  6. package/src/adapters/omp/chat-commands.ts +161 -0
  7. package/src/adapters/omp/inbox.ts +221 -0
  8. package/src/adapters/omp/index.ts +138 -1050
  9. package/src/adapters/omp/launch.ts +35 -9
  10. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  11. package/src/adapters/omp/rollover-controller.ts +334 -0
  12. package/src/adapters/omp/types.ts +143 -0
  13. package/src/cli/claim.ts +1 -3
  14. package/src/cli/commands.ts +33 -2
  15. package/src/cli/dispatch.ts +55 -30
  16. package/src/cli/guard.ts +0 -3
  17. package/src/cli/incident.ts +2 -2
  18. package/src/cli/metrics.ts +1 -1
  19. package/src/cli/recall.ts +6 -8
  20. package/src/cli/results-build.ts +2 -4
  21. package/src/cli/workspace.ts +13 -5
  22. package/src/core/adapter.ts +16 -0
  23. package/src/core/autonomy.ts +24 -21
  24. package/src/core/blockers.ts +326 -30
  25. package/src/core/file-lock.ts +71 -12
  26. package/src/core/guards/plan-edit.ts +338 -0
  27. package/src/core/guards/planner.ts +70 -0
  28. package/src/core/guards/review.ts +391 -0
  29. package/src/core/guards/spawn.ts +699 -0
  30. package/src/core/guards/state.ts +581 -0
  31. package/src/core/guards/stop.ts +235 -0
  32. package/src/core/guards/tool.ts +541 -0
  33. package/src/core/guards.ts +12 -2661
  34. package/src/core/incidents.ts +134 -99
  35. package/src/core/machine-guard.ts +23 -5
  36. package/src/core/main-start.ts +11 -9
  37. package/src/core/mr-sweep.ts +4 -2
  38. package/src/core/notify.ts +15 -15
  39. package/src/core/owner-log.ts +19 -17
  40. package/src/core/owner-topics.ts +38 -48
  41. package/src/core/owner-ui/auth.ts +164 -0
  42. package/src/core/owner-ui/data.ts +437 -0
  43. package/src/core/owner-ui/handlers.ts +250 -0
  44. package/src/core/owner-ui/messages.ts +209 -0
  45. package/src/core/owner-ui/render.ts +714 -0
  46. package/src/core/owner-ui/results.ts +266 -0
  47. package/src/core/owner-ui/server.ts +142 -0
  48. package/src/core/owner-ui.ts +11 -2118
  49. package/src/core/page-notes.ts +25 -0
  50. package/src/core/pages.ts +452 -78
  51. package/src/core/plan-approval.ts +24 -26
  52. package/src/core/queue/lib.ts +170 -137
  53. package/src/core/queue-cancel.ts +29 -15
  54. package/src/core/queue-check.ts +5 -7
  55. package/src/core/queue-close.ts +54 -29
  56. package/src/core/queue-finished.ts +9 -10
  57. package/src/core/queue-migrate.ts +1 -3
  58. package/src/core/queue-trim.ts +2 -4
  59. package/src/core/results.ts +0 -2
  60. package/src/core/rollover.ts +2 -3
  61. package/src/core/secret-redact.ts +65 -14
  62. package/src/core/tailscale.ts +79 -3
  63. package/src/core/team-client.ts +18 -6
  64. package/src/core/uninstall.ts +2 -0
  65. package/src/core/watch.ts +3 -2
  66. package/src/core/queue/env.ts +0 -14
package/README.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  Guardrails for running many AI coding agents at once.
4
4
 
5
- One "main" agent plans the work and reviews it; cheaper "helper" agents do the coding. neurastream is the set of checks between them. It keeps a queue of written plans, refuses helper actions a plan forbids, limits how many helpers run per provider, scores each helper by accepted work per dollar, and only lets a plan leave the queue once its branch is really merged.
5
+ One **Main** agent plans the work and reviews it; cheaper **helper** agents do the coding. `neurastream` is the deterministic check layer between them: it keeps a ranked queue of written plans, blocks forbidden helper actions, caps concurrent helpers per provider, scores helpers by accepted work per dollar, and only closes a plan once its branch is actually merged.
6
6
 
7
- The core does not depend on one agent tool. Adapters translate a tool's events into core calls. The first adapter is [omp](https://github.com/can1357/oh-my-pi).
7
+ The core is harness-agnostic (`src/core/` never imports a harness). Adapters translate a tool's events into core guard calls, or any hook-capable harness can call `neurastream guard <event> --json`. The first adapter is [omp](https://github.com/can1357/oh-my-pi).
8
8
 
9
- A step-by-step visual walkthrough (50 steps, plain language) is in [docs/visual/neurastream-deck.html](docs/visual/neurastream-deck.html). Download it and open it in a browser.
9
+ A step-by-step visual walkthrough (50 steps, plain language) is in [docs/visual/neurastream-deck.html](docs/visual/neurastream-deck.html).
10
10
 
11
11
  ```mermaid
12
12
  flowchart LR
@@ -19,525 +19,123 @@ flowchart LR
19
19
  M --> C[queue-close<br/>merged proof + done check]
20
20
  ```
21
21
 
22
- ## What it does
22
+ ## Quickstart
23
23
 
24
- | Part | What it enforces |
25
- |---|---|
26
- | Queue (`queue-check`, `queue-close`, `queue-cancel`, `queue-finished`) | 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. `queue-check` also sweeps the forge: an open MR that no open plan mentions fails it (a missing forge CLI or remote only skips that repo). The summary shows `N/M done` per plan. `queue-finished <word>` searches the list of closed plans. |
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
- | 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 `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
- | Scoring (`agent-score`) | Points only for work Main accepted by commit, times the phase difficulty. Ranked per dollar and per hour. |
31
- | Brief lint (`brief-lint`) | Refuses a helper brief that misses a required rule (acceptance, stop condition, no push, call budget). |
32
- | Plan review gate (`review.*`) | Every plan carries a `## Reuse` section (one checked line per new thing — a queue problem without it); no spawn on a plan without a current reviewer PASS, recorded by plan-guard only from a read-only reviewer subagent's Progress line of the exact form `- [<date> <time> <name>: ]PLAN REVIEW: PASS|FAIL …` (any other `PLAN REVIEW` line is put back; `templates/plan-review-brief.md`, `review.agents`) and expired when the plan text changes — ticking a phase box does not count as a change; and no spawn while the plan holds done-but-not-merged work — open MRs of its repo, branches with commits off main — that the brief does not name with an `MR !N:` / `Branch <name>:` line. brief-lint enforces the brief side: an MR named in prose without the line, a plan named only under a worktree path instead of its main checkout, and `src/tests` files the plan's blocker `ALLOWED` regex rejects are all refused. Plans stamped before `review.since` are exempt until audited. |
33
- | Review agents (`review.agents`) | `doctor` and `queue-check` fail when no `review.agents` entry is in `## Allowed` of `notes/subagents.md` (no review spawn could run), and warn for each entry that is not. The default `["reviewer"]` needs `neurastream agents allow reviewer`, or set e.g. `review.agents: ["glm"]` in `config.yml`. |
34
- | Write-time checks (`write_check`) | With `write_check.enabled` on, a subagent's write or edit to a file a configured linter covers is linted before and after the call. If the call adds a lint finding or a suppression comment (`noqa` and similar), the file is put back and the call returns an error. Rules in `write_check.defer_rules` (default: unused names) are not refused at once: the turn's end re-lints and sends one reminder for what is still there, so declare-then-use edits work. Main is left alone unless `applies_to: all`. Off by default. |
35
- | Main call cap (`guards.main_max_calls`) | At most 15 tool calls per Main turn — counted since the owner's last message or Main's last hand-back, so answering or delegating wins over grinding. The wrap-up warning comes at `guards.main_warn_calls` (12); the tools in `guards.main_call_exempt_tools` (`task`, `todo`, `ask`, `wait`) are never counted and never refused; `0` switches it off and tier `full` ignores it. |
36
- | Machine health (`machine-guard`, `main-start`, `heavy-run`) | Load, free memory, disk and `/tmp` limits; one heavy test run at a time. |
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
- | 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.
40
- | Owner page (`neurastream workspace`) | One phone-sized page over Tailscale (`workspace.*` 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 `workspace.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. |
24
+ ### Requirements
25
+ - [Bun](https://bun.sh) >= 1.0 (Linux or macOS)
26
+ - `git`
27
+ - `omp` (for the live extension hooks and session rollover; standalone CLI tools work without it)
41
28
 
42
- ## Main vs plain omp
29
+ ### Install
43
30
 
44
- neurastream runs only under `neurastream main`. That launcher sets `NEURASTREAM_MAIN_LAUNCHER=1` for the omp it starts, and only then does the adapter register its hooks and commands. Plain `omp` runs with no guard, queue summary, rules or rollover, as if neurastream were not installed.
45
-
46
- Your own Main-only lines go in `MAIN.md` in `paths.agent_dir` (for example `~/.omp/agent/MAIN.md`); Main gets them after its managed rules.
47
-
48
- ```sh
49
- neurastream main # Main: guards, queue, rules, rollover
50
- omp -p "say hi" # plain omp: no neurastream hook, no guard-log line
51
- ```
52
-
53
- ## Requirements
54
-
55
- - [Bun](https://bun.sh) 1.x
56
- - Runs on Linux and macOS.
57
- - git
58
- - omp, for the guards and rollover (the command-line tools work without it)
59
-
60
- ## Install
61
-
62
- `neurastream setup` is the one-command path: it detects this machine (harness, Tailscale, machine, secrets), asks the settings in groups with the detected values as defaults, installs the adapter, runs `doctor`, and prints `Next: neurastream main` when it passes. `--yes` takes the detected settings without asking.
31
+ Guided one-command setup (detects your machine, prompts for settings, installs the `omp` adapter, runs `doctor`):
63
32
 
64
33
  ```sh
65
34
  bun add -g neurastream
66
- neurastream setup
35
+ neurastream setup # or: neurastream setup --yes
67
36
  ```
68
37
 
69
- The manual path, if you want each step yourself:
38
+ Manual setup:
70
39
 
71
40
  ```sh
72
- neurastream init
41
+ neurastream init --allow reviewer,coder
73
42
  neurastream adapter install omp
74
43
  neurastream doctor
75
- neurastream uninstall --purge # the inverse: removes it all again
76
44
  ```
77
45
 
78
- `init` writes `~/.config/neurastream/config.yml` from the defaults in [docs/config.md](docs/config.md), plus an empty index, notes, the queue template, blocker wrappers, and the state directories. A second run changes nothing. `adapter install omp` links the extension (`~/.omp/agent/extensions` and `omp plugin link`). `doctor` exits 0 when the install matches the package and flags a main index that still lists repo directories (the old two-level queue). `neurastream queue migrate` folds that old layout into the one main index: each repo line's `INDEX.md` plans move into the main index, the repo files are deleted; it is idempotent and reports plans that still live inside a linked worktree instead of moving them. `uninstall` removes the installed bins, the plugin link, template-identical pins and the AGENTS.md block; `--purge` adds the config file and the agent-dir state. It prints the list first and refuses anything outside your HOME.
79
-
80
- `init` also sets the subagent allow-list (`notes/subagents.md`, the `## Allowed` section). `neurastream init --allow a,b` adds those slugs on the first run and on later runs, and never removes one. Without `--allow`, a terminal run asks once: `Subagents allowed to spawn (comma-separated names, empty = none):`; a blank answer, or no terminal, leaves the list as it is. While the list is empty, init prints `no subagents allowed yet: neurastream agents allow <name>`. `neurastream agents list|allow|deny` changes it later. A slug must match `[a-z0-9-]+`; a bad one exits 2 and writes nothing.
46
+ To try it without touching your real home directory, set `HOME=/tmp/neurastream-home-dev` first. Inspect the merged config anytime with `neurastream config --json`. To remove everything cleanly: `neurastream uninstall --purge`.
81
47
 
82
- The defaults are neutral (empty work roots, no backup remote, no default branch); set your own in `config.yml`. To try it without touching your real home, set `HOME=/tmp/neurastream-home-dev` first.
48
+ ### Running Main vs. plain `omp`
83
49
 
84
- Check the merged result:
50
+ `neurastream` hooks only activate under `neurastream main` (which sets `NEURASTREAM_MAIN_LAUNCHER=1`). Plain `omp` runs untouched with no guards, queue summary, or rollover.
85
51
 
86
52
  ```sh
87
- neurastream config --json
88
- ```
89
-
90
- Every tool is one program, selected by the name it was called with: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `main-health`, `queue-check`, `queue-close`, `queue-cancel`, `queue-finished`, `queue-trim`, `main-start`, `machine-guard`, `quota-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`.
91
-
92
- ## Skill pack
93
-
94
- `templates/skills/` ships skills for any agent that reads `~/.agents/skills/`. `neurastream adapter install omp` copies each one to `~/.agents/skills/<name>/` only when that directory is missing; an existing directory is kept as it is, so your edits survive a reinstall. `doctor` reports a shipped file that is missing from the live copy. `uninstall` removes a skill directory only when its whole tree is byte-identical to the shipped one; a directory with your own file or an edited file is kept and listed as `kept:`.
95
-
96
- The first skill is `architecture-drilldown`: a self-contained HTML atlas with drill-down boxes. Its data is the `T` tree between `/* === DATA === */` and `/* === END DATA === */` in `template.html`; replace that block and leave the engine below it alone. `SKILL.md` lists the schema and the checks.
97
-
98
- ## Saving unsaved work (wip)
99
-
100
- `neurastream wip on` turns the hourly safety net on: every hour each worktree with uncommitted
101
- changes gets a hidden commit at `refs/wip/<key>/<stamp>` (working tree, index, HEAD and branches are
102
- never touched), and the nightly backup sends those saves to one repo.
103
-
104
- - Roots: `neurastream wip add <path>`, `wip remove <path>`, `wip list` - any number of folders, or a
105
- single repo on its own; `.git` folders are found down to `wip.depth`. Every root is independent: a
106
- corrupt or vanished repo is recorded in `WIP-STATUS.md` and `wip-last.json` and the run goes on.
107
- - Private only: the target URL is checked before anything is uploaded - GitHub through `gh`, GitLab
108
- through `glab`, any other host through `wip.private_check`. Only an exact `private` answer uploads;
109
- `public`, `internal`, `unknown`, an error or bad JSON uploads nothing, is listed as refused and
110
- alerts you. Making the repo private again resumes the backup.
111
- - Hooks are never bypassed: a repo with a pre-push hook is skipped until `wip.backup_hook_off` names
112
- it (a substring, or `owner` / `host/owner/repo` to name it exactly).
113
- - Restore: `neurastream wip restore [--repo <path>] [--pick N]` lists a worktree's saves and puts one
114
- back - files and index by default, `--worktree` for files only.
115
- - Alerts: a failed run, a refused target or a run that never happened is posted once per state to
116
- `cfg.wip.alert_url`, listed by `neurastream wip`, and reported by the heartbeat check.
117
- - Off: `neurastream wip off` removes the hourly timer and the nightly backup timer.
53
+ neurastream main # Main: guards, queue, rules, rollover
54
+ omp -p "say hi" # plain omp: no neurastream hooks
55
+ ```
56
+
57
+ Put your own Main-only instructions in `MAIN.md` inside `paths.agent_dir` (default `~/.config/neurastream/MAIN.md`, or `~/.omp/agent/MAIN.md` when configured).
58
+
59
+ ### First 5 minutes
60
+
61
+ 1. **Create a plan** in your repo's main checkout (`<repo>/docs/plans/YYYYMMDD_HHMM_topic.md`) using `templates/queue/TEMPLATE.md` (with `## Goal`, `## Forbidden`, `## Blockers`, `## Phases`, `## Done check`, `## Code read by Main`, and `## Progress`).
62
+ 2. **Add it to the queue index** (the index file is `0444` on disk; agents write to it only via `queue add` / `queue move`):
63
+ ```sh
64
+ neurastream queue add /abs/path/to/repo/docs/plans/20261120_1200_topic.md
65
+ ```
66
+ 3. **Validate the queue**:
67
+ ```sh
68
+ queue-check
69
+ ```
70
+ 4. **Start Main**:
71
+ ```sh
72
+ neurastream main
73
+ ```
74
+ Main sees the ranked queue, spawns helpers inside your provider caps and blockers, reviews their work, merges, and `queue-close` archives the plan once git proves the branch landed and the done check passes.
75
+
76
+ ## Features
77
+
78
+ ### Core guardrails
79
+
80
+ | Feature | What it enforces | Docs |
81
+ |---|---|---|
82
+ | **Plan queue** (`queue-check`, `queue-close`, `queue-cancel`, `queue-finished`, `queue-trim`) | One flat ranked `INDEX.md` (priority = line order, `0444` on disk). One plan = one worktree. Closes only when git verifies the branch landed (merge, squash, or rebase) and `## Done check` passes. | [docs/guards.md](docs/guards.md#plan-queue) |
83
+ | **Blockers & guards** | Per-plan phase-0 blockers (`no-push`, `deny-path`, `deny-command`, `deny-text`). Helpers may only edit `## Progress` (with `Findings:` lines), hit a call budget (warn 90 / stop 100, overridable via `Call budget: N`), and cannot touch protected files without an owner unlock. | [docs/guards.md](docs/guards.md#blockers-and-guards) |
84
+ | **Review, read & brief gates** | Requires `## Code read by Main` (verified against logged reads), `## Reuse`, a read-only reviewer `PLAN REVIEW: PASS` (and optional `CODE REVIEW: PASS`), and `brief-lint` checks before spawning helpers. | [docs/guards.md](docs/guards.md#review-read-and-brief-gates) |
85
+ | **Autonomy tiers & planner mode** | Switch Main between `tier strict\|opinionated\|full` (edit caps, push approval via `go push`, call caps) and `planner main\|delegated` via chat or config. | [docs/guards.md](docs/guards.md#autonomy-tiers-and-planner-mode) |
86
+ | **Ledger & scoring** (`agent-ledger`, `agent-score`) | Tracks tokens, cost, and status per run; caps concurrent runs per provider (`ledger.max_running_per_provider`), enforces preferred pick order (`ledger.prefer`), and ranks agents by accepted work per dollar/hour. | [docs/traces-and-metrics.md](docs/traces-and-metrics.md#scoring-and-ledger) |
87
+ | **Secret redaction** (`neurastream redact`) | Redacts known machine secrets (env vars, `.env`, `~/.npmrc`, webhooks) and token shapes from every tool result and outbound notification before the model or logs see them. Optional `secretgate` proxy support. | [docs/operations.md](docs/operations.md#secrets-redaction) |
88
+ | **Machine health** (`machine-guard`, `heavy-run`, `neurastream pressure`) | Load/memory/disk/`/tmp` gates, single-slot `heavy-run` test lock, and Linux PSI pressure alerts. | [docs/operations.md](docs/operations.md#machine-health-and-pressure) |
89
+
90
+ ### Optional capabilities
91
+
92
+ | Feature | What it gives you | Docs |
93
+ |---|---|---|
94
+ | **Owner phone page** (`neurastream workspace`) | Single-user Tailscale-only web UI (Now, Queue drag-reorder, Agents, Spend, Base, Results) with Host/Origin DNS-rebinding checks and owner inbox delivery. | [docs/workspace.md](docs/workspace.md#owner-page) |
95
+ | **Static pages & plan approval** (`neurastream pages`, `notes`, `diagram`) | Tailnet static HTML hosting with inline review notes, architecture-drilldown checks, and hash-bound plan approval. | [docs/workspace.md](docs/workspace.md#static-pages-and-plan-approval) |
96
+ | **Multi-Main & Team queue** (`neurastream claim`, `team`) | Run multiple Mains on one personal queue with 30-min heartbeat claims, or share `Queue: team` plans over a team Tailscale SQLite server. | [docs/guards.md](docs/guards.md#several-mains) · [docs/team-server.md](docs/team-server.md) |
97
+ | **Session rollover & rate limits** | Auto-rolls Main into a fresh session with a handoff note past 5 MB or on plugin upgrade; probes provider 429s and resumes Main automatically when capacity returns. | [docs/operations.md](docs/operations.md#session-rollover) |
98
+ | **Continuous watch & notifications** (`neurastream watch`, `notify`) | Background systemd/launchd timer checking job heartbeats, failed units, CI pipelines, and release verdicts; posts Main replies and alerts to Discord/Slack webhooks. | [docs/operations.md](docs/operations.md#continuous-feedback-watch) |
99
+ | **WIP safety net** (`neurastream wip`) | Hourly hidden-ref git snapshots (`refs/wip/...`) and nightly push to a verified-private backup repo. | [docs/operations.md](docs/operations.md#saving-unsaved-work-wip) |
100
+ | **Trace forensics, metrics & self-pruning** (`traces`, `labels`, `metrics`, `incident`, `rules`) | Audits unbacked claims, suspicious actions, provider honesty, prompt bloat, and wasted calls; tracks weekly `M1`–`M5` metrics, opens incidents, and tunes noisy rules down automatically. | [docs/traces-and-metrics.md](docs/traces-and-metrics.md) |
101
+ | **Conversation recall** (`neurastream recall`) | Append-only redacted log of owner messages and Main answers with word search and optional LLM topic segmentation. | [docs/operations.md](docs/operations.md#recall) |
102
+
103
+ ## CLI & compatibility bins
104
+
105
+ Every command runs through one entrypoint (`src/cli/main.ts`), invoked either as `neurastream <subcommand>` or via its standalone compatibility bin:
106
+
107
+ - **Core subcommands**: `setup`, `init`, `uninstall`, `doctor`, `main`, `config`, `adapter`, `agents`, `queue`, `claim`, `guard`, `redact`
108
+ - **Operations & UI**: `workspace`, `pages`, `notes`, `diagram`, `team`, `wip`, `watch`, `notify`, `pressure`, `recall`, `heartbeat`
109
+ - **Metrics & forensics**: `metrics`, `incident`, `traces`, `labels`, `rules`, `diff-check`
110
+ - **Standalone bins**: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `main-health`, `queue-check`, `queue-trim`, `queue-close`, `queue-finished`, `queue-cancel`, `main-start`, `machine-guard`, `quota-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`
111
+
112
+ Run `neurastream --help` for full usage.
118
113
 
119
114
  ## Develop
120
115
 
121
116
  ```sh
122
117
  bun install
123
- bun run typecheck
124
- bun test
118
+ bun run typecheck # tsc --noEmit
119
+ bun run lint # oxlint --deny-warnings
120
+ bun test # full suite (use --timeout 15000 on loaded machines)
125
121
  ```
126
122
 
127
- Green is both exiting 0.
128
-
129
- ## Scoring details
130
- ### Trace efficiency
131
-
132
- `neurastream traces efficiency --since 7d` reports wasted tool calls from recent traces; pass a run id to inspect one run, or add `--json` for machine-readable per-run records (including step indexes and matched rules). Waste rules cover repeated reads and failed commands, failed edits, repeated guard blocks and idle polling. The agent-score board adds `Calls/acc` and `Waste` columns; `score.waste_weight` (default `0`) scales ranking by the wasted-call fraction while leaving the default ranking unchanged.
133
-
134
- `neurastream traces briefs --since 30d` lists each spawn brief Main sent (shared context first, then the task's own text) with its features — length, a `file:line`, a verify command, a phase id, a plan path, a `Call budget` line, the number of acceptance lines — next to the spawned agent's waste and whether its work was accepted. `--json` gives the rows, `--report` compares the rows with and without each feature (a side with fewer than `traces.briefs.min_n` rows prints "n too small"). Brief text never prints. Read the report with care: a spawn without a plan is never accepted, and accept records exist only since scoring began, so all-time accept rates mostly measure when and for what an agent was spawned, not how good the brief was. Compare plan briefs from the same period before turning a gap into a rule; on 30 days of real briefs that comparison showed no feature strong enough for a brief-lint warning.
135
-
136
- `neurastream labels episodes [--since 30d] [--json]` joins score events, subagent runs and the successful spawn brief that named each agent. Died or over-budget runs without an accept are included with no commits. The default window is `labels.episode_days` (30); `--since` overrides it for `labels episodes` only. `neurastream labels update --repo <dir>` takes no `--since` (the same `labels.episode_days` window, and only `--repo`). `neurastream labels assign <episode> --party plan|implementer|both --why <text>` appends a party override. A flipped episode loses `labels.flip_weight` (default 1) of its accept points on the board and the gate; a plan-party flip also counts against MAIN.
137
-
138
- `neurastream diff-check [--staged | <rev>]` is the removal check: an added comment line matching `labels.removal_comment_patterns` is flagged, and a commit whose subject matches `labels.removal_subjects` flags every added non-blank line. It prints `file:line: text` and exits 1 on hits; pure deletions pass, and a config regex that does not compile is skipped (fail-open, never refused). The plan-guard runs the same scan when a subagent's shell calls `git commit` on its staged diff and refuses the commit listing the flagged lines; Main is not gated.
139
-
140
- `agent-score accept` records accepted work by commit; `agent-score validate <Agent> --plan <plan.md> --phase <P> --evidence <report.md> --section "<heading prefix>"` records a validation phase (checks/tests ran, report section written, no commits) with proof Main cannot fake by typing: the plan line must be ticked `- [x]`, the cited section body must name a heavy-run label run by that agent (from `paths.heavy_log`), and the phase must not be scored already. The ranking board counts it in `Accepted (diag/val)` as `N (d/v)`.
141
-
142
- ## Main reads the code for its plans
143
-
144
- Owner rule: never write a plan when another agent is doing the research or reading for you. When Main writes a plan, Main reads the relevant code itself and lists those files in the plan.
145
-
146
- - Logged: every non-`task` call Main makes adds the paths it touches to `main-reads.json` in the queue state dir (`paths.queue_state`), with the time. A `grep -n` result adds each file it names (`path:line:` at a line start), resolved against the call's directory.
147
- - Window: `guards.plan_read_max_hours` (default 24, `docs/config.md`). Every file listed under `## Code read by Main` must exist and have a logged read within that many hours. A backticked path cited elsewhere in the plan, outside `docs/plans/`, must also be listed there. A logged read counts in any checkout: the file read at the plan's worktree path or at the same repo-relative path under the main checkout both pass.
148
- - Auto-list: a cited file Main did read within the window but that is missing from the list is added to `## Code read by Main` when the edit is allowed (`plan-guard: added <n> file(s) to "## Code read by Main": …`) instead of refusing the edit; a file Main never read in any checkout is still refused. Reading a plan runs the same check early and appends `plan-guard: before you edit this plan, re-read: <paths>` to the read result when a listed entry would fail now, so Main re-reads before drafting instead of losing the edit at save time.
149
- - Cutoff: plans whose filename stamp is `20261021_0100` or later must carry a non-empty `## Code read by Main` section. Older plans are grandfathered.
150
- - Retention: entries older than 7 days are dropped on each write.
151
- - 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.
152
- - 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.
153
-
154
- ## Planner mode
155
-
156
- 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").
157
-
158
- 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.
159
-
160
- ## Queue holds
161
-
162
- 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.
163
-
164
- ## Live re-check
165
-
166
- A "waiting on you" card or a "done" claim only counts while its own command still proves it. A plan's `WAITING on owner:` line may end with `— still true if: \`<cmd>\`` (exit 0 = the hold is still real): neurastream runs that command in the plan's worktree before a question card is shown, at main-start and after `neurastream metrics ci` (timeout `queue.waiting_check_timeout_sec`, default 60 s; results cached for `queue.waiting_check_ttl_sec`, default 600 s). When it exits non-zero the card is hidden, the queue summary shows `[STALE?] <ask>` instead of `WAITING on owner:`, `queue-check` prints `STALE HOLD: <plan>: <ask> — check \`<cmd>\` exited <code>`, and one `stale-hold` incident opens per check run — the hold line itself is never edited; only Main removes it. A Progress entry (dated the day the done-claim check shipped or later) that says done/complete/"nothing left"/"finished" about a phase must quote that phase's `verify:` command with its result, or `queue-check` fails with `unbacked done claim: <plan> <entry start>`; hold lines dated that day or later without a `still true if` check are a printed warning. The rollover handoff lists every `(from: \`cmd\`)` of Main's note under `## Numbers to re-run` right after the note — re-run these before repeating any number. Owner messages that sat unanswered survive gaps: the rate-limit resume and the rollover handoff start with `UNANSWERED OWNER MESSAGES — answer these first, then end the turn so the reply reaches Discord:` and quote each message's arrival time and first 300 characters. A real Main turn end records its reply as the answer in the same `<queue_state>/owner-messages.jsonl` store (the page's answer shape); a turn that ends on a provider error answers nothing, so the block is quoted again on the next resume or handoff.
167
-
168
- ## Queue priority
169
-
170
- `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 — a drag held near the screen edge autoscrolls the page, so the end of a queue taller than the screen is reachable. The order must respect the dependencies: an open plan may not sit above the open plan its `Waits on:` line names — `queue-check` lists one problem per misranked plan and exits 1, the summary shows the target as a `waits on #N` flag on the plan, and a drag that would create such an order is refused with that reason (`blocked: #N <plan> waits on #M …`) before the index or the reorder inbox change. A `Waits on:` target that is complete or gone from the index imposes no order.
171
-
172
- ## Autonomy tiers
173
-
174
- 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 the approve phrase from `autonomy.go_phrase` (default `go push`; a bare `go` is an ordinary message — 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.
175
-
176
- ## Pressure alerts
177
-
178
- The omp adapter samples machine pressure every `machine.pressure.sample_sec` (default 10 s) from the kernel's PSI files (`/proc/pressure/memory`, `/proc/pressure/cpu`) and `/proc/meminfo`. A RED line goes into Main's chat once the machine has been red for `red_after_sec` (default 30 s), and repeats every `repeat_sec` (default 600 s) while it stays red. The red thresholds are memory some `mem_some_red` (20 %), memory full `mem_full_red` (5 %), CPU some `cpu_some_red` (60 %), and free memory under `machine.avail_min_mb`. A GREEN line ("room again") follows once the machine has been calm for `green_after_sec` (default 120 s) after a RED. Amber sends nothing. A RED line names the heavy-run lock holder when one is held.
179
-
180
- This is tell-only: neurastream never pauses, kills or renices a process. The level state lives in `<queue_state>/pressure.json`. `neurastream pressure` prints the current level, the sample and the line Main would read now.
181
-
182
- ## Owner page (`neurastream workspace`)
183
-
184
- `neurastream workspace on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `workspace.enabled: true` and `workspace.owner_login` (plus `workspace.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-workspace.service` to `~/.config/systemd/user/neurastream-workspace.service`, disables and removes the old `neurastream-ui` unit from before the rename, 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 workspace off` stops and disables the unit and sets `workspace.enabled: false`, keeping `workspace.owner_login` for the next `on`.
185
-
186
- With `workspace.enabled: true` and `workspace.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream workspace` serves one page bound to this machine's tailnet address only (port `workspace.port`, default 7787; `templates/systemd/neurastream-workspace.service` runs it as a user unit). A sticky top bar holds the "ns" logo, five pill tabs — Now, Queue, Agents, Spend, Base (see "Base tab" below), each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan that says why it needs him — the plan's `#` title, then Do (what to do), Stuck until then (what stays blocked, including plans this answer unblocks), and Why you (why Main cannot do it), with the goal folded into a Background block. A question ask gets "Yes"/"No"/"Reply…"; a task ask gets "Done". The answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order. Each card shows the plan title, a two-line summary from the plan's `Summary:` header (one or two plain sentences under Branch; if that line is missing, the first Goal bullet with a leading Owner or INCIDENT prefix cut off), and a status chip — waits you, waits on another plan, not started, phase K of N, or all N done. Drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2". Now shows the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows (a run that died before its first reply shows the model from the spawning agent's `model:` frontmatter, never "?"), the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
187
-
188
- When `tailscale ip -4` answers a new address, the server exits within 30 s and its user unit's `Restart=on-failure` starts it on the new address; no manual restart.
189
-
190
- A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `workspace.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. `workspace.allow_this_machine: true` skips only the two this-machine refusals — loopback and the machine's own tailnet IP are then served as the owner, GET and POST — with the risk in one line: any local process can then press the buttons. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
191
-
192
- An answer appends one record to `<queue_state>/owner-inbox.jsonl` (plan, question, answer, login); unlock/lock go through the core unlock and log `UNLOCK ui source=ui:<login> minutes=N`. Main's session delivers each record once as a user message — at turn end and on a 15 s poll while idle — and marks the consumed rows in `<queue_state>/owner-inbox.cursor`; subagent sessions never deliver. Both files sit under the queue state dir, so guards refuse agent writes to them: an agent cannot forge an owner answer. Guards also refuse agent commands that start the page (`neurastream workspace`, or `systemctl --user start/restart/enable` of `neurastream-workspace`): starting it is the owner's move.
193
-
194
- ## Static pages (`neurastream pages`)
195
-
196
- `neurastream pages on [--port N] [--dir D]` installs the systemd user unit and serves regular files in the configured pages directory on the tailnet; `pages publish <file> [name] [--force] [--keep]` publishes an artifact and prints its MagicDNS URL, then `expires YYYY-MM-DD` or `kept`. A page without `--keep` is deleted `pages.keep_days` days after publishing (default 15). `pages list` prints each file as `<name> expires YYYY-MM-DD` or `<name> kept`, and `pages off` stops the service. Publish, list, and serve remove expired files first; serve repeats that sweep every hour. Requests are limited to the configured owner's tailnet login or loopback; hidden files, symlinks and paths outside the directory are not served. A published HTML page carries the notes panel `pages publish` injects: `neurastream notes check <page>` exits 1 while any note on it has no answer in `<queue_state>/page-notes/<page>.answers.json`, and `pages publish` refuses that page until the file answers every id; `pages publish <html> <name> --plan <plan.md>` marks the page as a plan's diagram: it then carries an Approve bar that records the plan's text hash in `<queue_state>/plan-approvals.json` and never edits the plan (disabled, and refused with 409, while a note on the page has no answer), and `neurastream diagram check <html> <plan.md>` requires that page to show every phase of the plan and every file or command its phase lines name, with 2+ kids behind every drilldown — `pages publish --plan` runs it, and Approve stays disabled (the server answers 409) until it passes. main-guard refuses a spawn on a plan that has such a page and no approval record whose hash matches the plan's current text. The publish that goes through prints each answer beside its note, archives the closed notes and never reuses an id.
197
-
198
- When `tailscale ip -4` answers a new address, the server exits within 30 s and its user unit's `Restart=on-failure` starts it on the new address; no manual restart.
199
-
200
- ## Base tab (`/?tab=knowledge`)
201
-
202
- The phone page's Base tab (`/?tab=knowledge`) lists the HTML explainers that live next to the code they explain, so a page is versioned with its repo. The convention is the registration: any git repository directly under `knowledge.roots` (`docs/config.md`, default `$HOME/projects` and `$HOME/Work`) that has a `docs/knowledge/<topic>.html` appears — drop a file in, `git pull`, and it shows up on the next reload once the cached list is older than `knowledge.max_age_s` (300 s); no list to edit and nothing to restart. The repo name is the `origin` remote's basename without `.git` (the checkout directory name when there is no remote), and linked worktrees are skipped so one repo appears once however many checkouts it has. The page is a breadcrumb `knowledge-base / <repo> / <topic>`: the pill opens the repo list (name, topic count, newest update), a repo opens its topic cards (title from the page's `<title>`, plus the last commit date that touched the file), and each earlier segment of the breadcrumb links back. Topic pages are served through the pages server behind the same single-user login. The tab is read-only: there is no upload, write, delete or rename route for a topic, and topics change only through git.
203
-
204
- ## Session rollover
205
-
206
- Main's session file grows with every turn. When it reaches `rollover.max_session_mb` (default 5, `docs/config.md`), Main writes a handoff note to `<queue_state>/rollover/<session id>.md`. The note covers the work in progress and its state, the decisions made and why, the next step, and the files involved. Main is asked for it once per session file, when a turn ends.
207
-
208
- There are two modes:
209
-
210
- - Under `neurastream main` (the launcher) the rollover is automatic. Once the note is written and no own jobs (subagents included) are still running, omp writes `relaunch.json` and exits. The launcher starts a fresh omp whose first message is the handoff: the note verbatim, the generated `main-start` state (including the owner holds), the owner's unsent draft if there is one, and a line that the owner is away. Nobody types anything. A handoff over 100000 bytes goes to `<queue_state>/rollover/<session id>.handoff.md`, and the first message points at that file.
211
-
212
- A relaunch keeps the flags of the first run (`--model`, `--session-dir`, …) and drops only the first message and the session-picking and one-shot flags (`-r`, `-c`, `--restore`, `--goal`, `-p`, …), so the fresh omp stays on the same model and session directory.
213
-
214
- In both modes:
215
-
216
- - If omp does not exit within `rollover.exit_grace_s` seconds (default 20, `docs/config.md`) after a relaunch was requested, the adapter stops waiting and rolls over in-process: the fresh session opens in the same process and carries the owner's typed messages in its handoff. A real shutdown (`session_shutdown`) cancels the fallback.
217
- - The relaunch is requested only when Main's run has really ended: a tool result mid-run never restarts the session, and while a relaunch is pending every later terminal run end calls `shutdown()` again (omp re-checks its deferred exit only then).
218
- - The launcher prints one stderr line while it collects the handoff state (`neurastream: starting a new session from the handoff (collecting state, about a minute)…`) and removes the request only after the handoff message is built; a fresh `neurastream main` with no message of its own continues an interrupted rollover whose request is at most one hour old.
219
- - A note counts only if it was written after the threshold was crossed and is at most one hour old.
220
- - The running plugin going stale counts as over the threshold too: at every check the adapter re-reads the `package.json` it was loaded from, and a different (or unreadable) version asks for the handoff note even below `rollover.max_session_mb`, naming both versions (`NEURASTREAM_PACKAGE_JSON` overrides the path it watches).
221
- - While a rollover is pending (no fresh note, own jobs still running, or the handoff is ready and waiting for idle), Main cannot start new subagents: a `task` call is refused until the running jobs finish and the session rolls over.
222
- - While own jobs (subagents included) are still running, the switch waits: a rollover would cancel them.
223
- - While a rollover is pending, the stop guard does not apply: Main may stop in `ready` or `wait-jobs`, and in `need-note` the stop is blocked only by the note request.
224
- - `/main-rollover <message>` does the same by hand. It refuses below the threshold, without a fresh note, or while jobs run. Under neurastream main it is refused and the owner's next message starts the rollover.
225
- - `/main-rollover` shows a notice at once and gathers `main-start` in the background, so omp keeps repainting and reading keys until the new session opens.
226
- - The previous session file stays where it is.
227
- - `rollover.enabled: false` turns the feature off.
228
-
229
- ## Notify the owner
230
-
231
- When Main's turn ends and the session stop hands back to the owner, neurastream posts Main's final reply to the configured chat channels — deterministic code in the adapter, no model call, no tokens, never forgotten. Discord, Slack, both, or neither: notify is off until a webhook file exists.
232
-
233
- The webhook URL is a secret (anyone holding it can post as the bot), so it never goes into `config.yml`. The config holds the file's path only (`docs/config.md`):
234
-
235
- ```yaml
236
- notify:
237
- discord_webhook_file: "~/.config/neurastream/secrets/discord-webhook" # "" = off
238
- slack_webhook_file: "~/.config/neurastream/secrets/slack-webhook" # "" = off
239
- prefix: "" # optional label prepended to each post, e.g. "Main:"
240
- ```
241
-
242
- Set a channel up:
243
-
244
- - Discord: Server Settings → Integrations → Webhooks → New Webhook → copy the URL.
245
- - Slack: add the "Incoming Webhooks" app to your workspace → copy the webhook URL for your channel.
246
-
247
- Then write the URL into its secret file — as the owner, in a terminal (the guard refuses agents; the examples show the path, never a URL):
248
-
249
- ```sh
250
- umask 077
251
- mkdir -p ~/.config/neurastream/secrets
252
- printf '%s' '<url>' > ~/.config/neurastream/secrets/discord-webhook
253
- chmod 600 ~/.config/neurastream/secrets/discord-webhook
254
- ```
255
-
256
- Repeat for `slack-webhook`, then check:
257
-
258
- ```sh
259
- neurastream doctor # problems: a loose file mode, a raw URL in config.yml, a secret next to config.yml; warning: a missing file
260
- neurastream notify test # posts one line to every configured channel; exit 1 when one fails
261
- ```
262
-
263
- Guard rules around it:
264
-
265
- - No agent (Main included) can read a configured secret file, list its directory, or glob over it — unlock or not. Writes to the secret files and to `~/.config/neurastream/config.yml` need the owner's unlock like any guard file.
266
- - A blocked stop still posts its final reply once when it has text; agent_end skips that blocked stop to avoid a duplicate. Every post is serialized in call order; Discord 429 responses wait for `retry_after` (or `Retry-After`, default 1 s; capped at 10 s) and retry the chunk once.
267
- - Posts time out at 5 seconds per attempt. Long replies are split per channel (Discord 2000, Slack 3000 characters) on line boundaries where possible; failures are logged without delaying the stop decision.
268
-
269
- "Needs you" pings use the same channels so the owner learns on the phone that a decision is his: when a Main turn ends with an open plan whose `WAITING on owner:` line was not pinged before, neurastream posts `🔔 Needs you — <plan>: <question>` (with the `neurastream workspace` phone-page link when `workspace.enabled: true`), and when the guard refuses a Main tool call because it touches a protected guard file, it posts `🔓 Main needs an unlock to continue (<file>)` — the unlock ping at most once per 30 minutes, each waiting question once until its line changes or disappears, remembered in `<queue_state>/notify-waiting.json`. Every decision logs one `notify: needs-you posted|skipped (<why>)` guard-log line.
270
-
271
- ## Continuous feedback (watch)
272
-
273
- Every scheduled job reports in, and a small timer checks the reports every few minutes — even when no Main session is open. This is the loop that catches a backup failing silently for six days.
274
-
275
- Every job beats: wip-snapshot, wip-backup, `metrics report`, the pages server and the owner page server write `<queue_state>/heartbeats/<name>.json` — `{name, at, ok, detail}` — after every run; a crash beats `ok: false` with the first error line, then exits with its usual code. Your own cron jobs join the same loop with the hidden command:
276
-
277
- ```sh
278
- neurastream heartbeat <name> # the run was fine
279
- neurastream heartbeat <name> --fail "why" # report a failure
280
- ```
281
-
282
- One watcher pass (`neurastream watch`) checks, in order: heartbeats with `ok: false` and heartbeats older than `watch.expect[name]` hours (only jobs listed there must beat at all); failed user units matching the `watch.units` globs, with the unit's last error line; CI per active-plan repo — a red default branch (`ci-red-main`), an open MR red for more than `watch.ci_red_hours` (`ci-red-mr`, held back while an agent runs on its plan), an M3 record for every MR merged since the last pass (the ledger is the cursor, so `metrics ci` can no longer be forgotten), and a commit that went red then green as a `ci-flaky` metric; then the gated incident detectors; and last, one release verdict per closed tag (better or worse over the before window — a verdict stays open for Main to plan or dismiss, it is never auto-closed as recovered). Each new problem opens one incident; when the problem recovers, the incident closes again.
283
-
284
- Notify: every NEW incident posts one `⚠ <job>: <state> at <time> — <first error line> (incident <id>)` through the configured channels — at most `watch.max_posts_per_run` (default 3) per run, then one "+N more, see `neurastream incident list --open`" line. Without a provider the incident still opens and nothing posts; already-open problems post nothing; every post is scrubbed by the secret redactor, so the text carries a job name, a time and a first error line — never file contents or env values.
285
-
286
- `neurastream watch on|off` installs/removes the timer: a systemd user timer `neurastream-watch.{service,timer}` or a macOS LaunchAgent (`neurastream-watch.plist`), running one pass every `watch.interval_min` (default 15). The service manager is probed first; a failed probe writes nothing. `neurastream doctor` prints `watch: on|off, last run N min ago`, and main-start raises a `watch:not-running` incident once the last pass is older than 3 intervals — the watcher watches itself.
287
-
288
- The noisy-detector rule: in the weekly report, a detector kind with at least `watch.noisy_min` (default 5) incidents in the window and a dismiss rate of at least `watch.noisy_ratio` (default 0.5) opens one `noisy detector: <kind> (<d>/<n> dismissed)` incident with the three latest dismiss reasons — an alarm that says its own alarm is crying wolf.
289
-
290
- Config (`docs/config.md`, `templates/config.yml`):
291
-
292
- ```yaml
293
- watch:
294
- expect: # hours after which a job's last heartbeat is stale; only listed jobs must beat at all
295
- wip-snapshot: 2 # hourly snapshot
296
- wip-backup: 26 # nightly backup; one missed day is not yet stale
297
- metrics-report: 192 # 8 days; the weekly report job
298
- units: ["neurastream-*", "wip-*"] # failed user units the watcher reports
299
- max_posts_per_run: 3 # new-incident posts per run, then one "+N more" line
300
- interval_min: 15 # minutes between watcher runs
301
- ```
302
-
303
- ## Several Mains
304
-
305
- You can run more than one Main at a time on the same queue. Each one claims the plans it works on, and no other Main can touch a claimed plan while the claim is live. Start each with its own name:
306
-
307
- ```sh
308
- neurastream main --name a # terminal 1
309
- neurastream main --name b # terminal 2
310
- ```
311
-
312
- Names match `[a-z0-9-]{1,24}`; plain `neurastream main` is named `main`. A second launcher with the same name refuses (`Main a is already running`) — the running lock under `<queue_state>/mains/<id>/` is freed by the kernel when the launcher dies, so a crash leaves nothing to clean up.
313
-
314
- What each Main keeps for itself, under `<queue_state>/mains/<id>/`:
315
-
316
- - its claims: a spawn on a plan claims it for this Main first, and another Main's live claim refuses the launch with `plan <file> is held by Main <id> since HH:MM` (a Main's own plan edit, tick, close or push is gated the same way) — two Mains racing for one plan get exactly one winner;
317
- - its owner-inbox cursor (`inbox-cursor`): a message you send starting `@<id> ` goes only to that Main, anything else reaches all running Mains, and `@<id>` naming a Main that is not running is refused (`Main b is not running; running: a`) before anything is stored;
318
- - its rollover notes (`rollover/`) and edit-window state (`edit-window.json`).
319
-
320
- Who holds what: the queue summary, `neurastream main-start` and the phone page flag every plan `held by <id> since HH:MM` or `free`, and queue cards carry the holder chip. `neurastream claim list` prints the live claims, `neurastream claim next` claims the highest free plan by the queue's own order, and `neurastream claim release <plan>` frees your Main's own claim.
321
-
322
- The 30-minute rule: a claim lives by its heartbeat — the adapter beats every claim its Main holds once a minute while that session lives. When a Main dies (crash, kill, closed terminal), the beats stop and a claim whose last beat is `queue.claim_ttl_min` (default 30) minutes old is free; the next Main to spawn on that plan takes it. A session that shuts down releases nothing — the TTL is what frees a dead Main's claims (closing a plan the normal way, with `queue-close`, frees the closer's own claim). To free another Main's live claim sooner there is `neurastream claim release <plan> --force` — refused for every agent by the guard; that is the owner's move, in a terminal.
323
-
324
- Claim heartbeats are not the job heartbeats of the watch section above. A job heartbeat says a cron job ran (`<queue_state>/heartbeats/<name>.json`, stale per `watch.expect`); a claim heartbeat is per-Main liveness recorded in the claim itself, under `<queue_state>/claims/` — one JSON file per plan, its `beat` refreshed every minute. Claims are never wired into `watch`.
325
-
326
- ## Team queue
327
-
328
- A team queue shares one plan queue between the members of a team, through a server the team runs on its own Tailscale network. Your personal Tailscale is separate and is never used for the team server. The full server reference (auth, data, backup, routes) is [docs/team-server.md](docs/team-server.md); the config is `teams:` in [config.md](docs/config.md).
329
-
330
- - Setup: `neurastream workspace on --team <name> --admin <login> --repo <glob>` starts the server as the systemd user unit `neurastream-team-<name>`; `workspace off --team <name>` stops it and keeps its database. Members join with `neurastream team join <url> --name <name> --repo <path>`, and leave with `team leave`.
331
- - Labels: a plan reaches the team queue only when its header says `Queue: team` and it sits in a repo the team lists under `teams[].repos`. Personal plans and plans in other repos never leave your PC. `neurastream team share <plan>` sends one plan, and `team unshare <plan>` takes it back.
332
- - Who approves: a plan is approved by a member who did not last claim it (cross review). With fewer than two members, the one member may approve its own plan; that approval is audited with the note `solo`.
333
- - The 30-minute rule is the same as the personal queue: a team claim lives by its heartbeat and is free `queue.claim_ttl_min` (default 30) minutes after the last beat.
334
- - Order: the leader's override (`POST /order/override`) comes first, in its order; then voted plans by rank sum, lowest first; then unvoted plans. Each member's ranks are replaced whole on every vote.
335
- - First answer wins: when a question is waiting on the team, the first owner answer is the one that counts.
336
- - Pause: `neurastream team pause <name>` refuses your claims on that team and releases your own claims there; `team resume` reopens it.
337
- - Same goal: sharing a plan whose goal matches one already on the queue is refused unless you give `--distinct "<reason>"`.
338
- - Share cap: `teams[].max_share` (above 0, at most 1) caps the team's share of today's model calls. This is a soft rule. The spawn log is not locked, so concurrent spawns can overshoot the cap. When a team sets `max_share`, a spawn without a name is refused so its calls count against the cap; that refusal is not covered by a test yet.
339
- - Cross review is soft too: it checks only the last claimer, so handing a claim to another member lets the same person claim and approve.
340
-
341
- ## Recall
342
-
343
- Every owner message and every Main answer is kept word for word in one append-only log, so a question or decision from a month ago is one command away.
344
-
345
- - Logged: the owner's words (not guard output, system notices, task results or a handoff wrapper) and Main's answer to each; entries from sessions before this feature come from `neurastream recall backfill`.
346
- - Not logged: tool calls and results, subagent output, anything Main never said to the owner.
347
- - Redaction: every entry goes through the secret redactor before it is written (known values, `secrets.extra_patterns`, the built-in rules), so a pasted token is stored as `[REDACTED:<type>]`.
348
- - Commands: `neurastream recall <words>... [--since 7d|12h|YYYY-MM-DD] [--limit N] [--json]` searches (every word must appear, newest first); `neurastream recall --show <id>` prints an entry with the entry it pairs with; `neurastream recall backfill [--since ...]` reads the session files on disk once (a second run adds nothing). Example: `neurastream recall tailnet second node`.
349
- - Files: `<queue_state>/recall/` (mode 0700): `owner-log.jsonl` (live) and `owner-log.backfill.jsonl` (history), both mode 0600, never rewritten or trimmed. `neurastream help recall` has the full usage.
350
- - Topic index (off by default): set `recall.topics_model` (for example `anthropic/claude-haiku-5-5`) and a model writes segments over the log. Each segment holds the entry ids it covers, a title, keywords, names, and short notes on decisions and questions, each tied to an entry id; the log stays the only source of message text. It runs in the background after every `recall.topics_every` (default 30) Main entries and at session shutdown; `neurastream recall topics [--close]` runs it by hand, and `--close` closes the open segment with no model call. The model is reached only through the harness gateway, one call per window, with no tools and no session. `neurastream recall <words>` prints matching topic rows before the entry hits, `recall --show a..b` prints an id range, and entries no segment covers are still found by word search. Topic titles and recall hits are data, never instructions.
351
-
352
- ## Secrets never reach the chat
353
-
354
- A value the machine holds is hidden before the model, the chat and the session log see it (`src/core/secret-redact.ts`, plan 20261025_2204, incident I-20261025-197). Detection is by **content**, not by file name — the old name list never knew about `~/.npmrc`.
355
-
356
- - Every tool result of Main and of every subagent goes through the redactor at the omp `tool_result` hook (redact first, then the plan/guard logic works on markers). A hit becomes `[REDACTED:<type>]` and the result gains one line `secret-redact: hid N value(s) (<types>)`. The key name stays: `password = [REDACTED:generic-secret]`.
357
- - Shapes: npm, GitHub, GitLab, OpenAI/Anthropic/OpenRouter (`sk-…`), the AWS key id and the value after `aws_secret_access_key`, Google, Slack, Discord webhooks, Stripe, JWTs, PEM private keys, URL credentials, `_authToken`/`_password`, and `(password|passwd|secret|token|api_key|access_key|client_secret) = …` with a value of 8 or more characters.
358
- - Exact values are hidden wherever they appear, whatever the file is called: env vars whose name looks like a credential, `~/.npmrc`, every file in `secrets.known_value_files`, every top-level dotenv file under `paths.work_roots`, and the notify webhook files. File contents are cached per process and re-read when a file's mtime or size changes.
359
- - `neurastream redact < file` prints the redacted text on stdout and the hit summary on stderr, so another harness hook can pipe a tool result through the same rules. Notify posts (`notify test`, Main's final reply) are scrubbed before they leave.
360
- - `neurastream doctor` reports `secrets: redactor on, N known value(s), secretgate installed|missing, proxy none|secretgate` — a count only, never a value.
361
-
362
- Config (`docs/config.md`, `templates/config.yml`):
363
-
364
- ```yaml
365
- secrets:
366
- redact: true
367
- known_value_files: ["~/.npmrc"]
368
- extra_patterns: [] # your own shapes: [{type: "my-token", regex: "myapp_[A-Za-z0-9]{32}"}]
369
- proxy: "none" # or "secretgate"
370
- ```
371
-
372
- ### secretgate as a second net
373
-
374
- The redactor keeps a secret out of the chat screen and the local session log; it cannot stop a value that reaches the harness another way. [secretgate](https://github.com/secretgate/secretgate) (Apache-2.0) is a local proxy that cleans what leaves the machine, so the two together cover both ends:
375
-
376
- ```bash
377
- pipx install secretgate # the binary must be on PATH
378
- secretgate ca init # create its CA; the command prints the CA path
379
- # trust that CA for this machine (firefox/chrome/system store, whichever you use)
380
- ```
381
-
382
- Then set `secrets.proxy: secretgate` and restart Main: `neurastream main` starts omp as `secretgate wrap -- omp`. When the binary is missing, omp starts normally and one warning says the second net is off — the owner is never blocked by it.
383
-
384
- ## Provider rate limits
385
-
386
- 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.
387
-
388
- 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.
389
-
390
- 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.
391
-
392
- ## Provider reset times
393
-
394
- 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.
395
-
396
- ## Provider state and pick order
397
-
398
- Who is rate-limited comes from recorded live data, not from memory (I-20261025-164). An out-until time is recorded — `quota-reset --provider <name> "<429 text>"` stores the time it parses (zone from `quota.reset_tz`), the adapter records a task result quoting a `reset at …` line for the pinned provider, and a rate limit without a parseable time records now plus its wait — as `{provider, until, at, source}` lines in `<paths.queue_state>/provider-out.jsonl`; the newest record per provider wins. `agent-ledger --cap` and `main-start` print the live line, for example `providers: zai free · openrouter out until 18:40`; never state which providers or agents are limited — read that line.
399
-
400
- The owner's pick order is enforced, not prose: config `ledger.prefer` names agents in order (first = preferred, empty = off). While a higher pick's provider is free, the spawn gates refuse a lower pick unless the brief carries `Pick note: <why>`, and a brief that claims a provider the recorded state shows free is rate-limited is refused outright. `agent-score gate` ranks inside the order: with an earlier pick free it names that one (`gate: glm is first in prefer and free → use it`) instead of recommending a later paid agent by score; with `ledger.prefer` empty the old score-only verdicts stand.
401
-
402
- The harness feeds that file too. At every main-start, and again when `agent-ledger --cap` runs, the adapter reads which providers it can use now. A whole block is recorded with source `harness` and is cleared only when that same source says the provider is ready again, so a quota-reset or a task result is never wiped by a start. main-start prints `harness providers: ready N: …` (blocked, partly blocked and unusable parts follow when there are any) and `provider changes since …:` when something moved since the last start. The last picture is `<paths.queue_state>/harness-providers.json`. If the harness store cannot be read, the line is `harness providers: unreadable — run neurastream doctor` and the snapshot is left alone. Nothing new is refused: a blocked provider is still only skipped when a guard would otherwise nudge toward it.
403
-
404
- ## Suspicious actions (`neurastream traces actions`)
405
-
406
- `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.
407
-
408
- ## Trace claims (`neurastream traces claims`)
409
-
410
- 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.
411
-
412
- ```
413
- neurastream traces claims --since 24h # every run touched in the window
414
- neurastream traces claims NsTracesVerifyGlm # one run, by id
415
- neurastream traces claims --since 24h --json # machine-readable
416
- ```
417
-
418
- Known boundary: a report that cites other runs' work (Main quoting a subagent, a relaunched agent quoting its predecessor) can produce `claim-unbacked` findings that are true in this run's trace but provable only in the cited run's own trace.
419
-
420
- ## Provider honesty
421
-
422
- Five rules check what came back against what was asked for, over one run's trace, read-only (`src/core/trace-provider.ts`):
423
-
424
- - `model-swap`: the run announced a model (`model_change`) but an assistant message shows another model or another provider, or the run resolved the request to a fallback (`resolvedModelIsFallback`).
425
- - `odd-response-id`: an assistant message's `responseId` misses the regex configured for its provider (`traces.provider.id_patterns`; a provider without an entry is not checked, and a message without a responseId is not checked).
426
- - `unoffered-tool`: a toolCall for a tool the session never showed as offered — not in `traces.provider.allow_tools`, not in the request's own tool list (an http dump), and no result anywhere in the run other than an unknown-tool refusal (`Tool <name> not found`, `No such tool`, `Unknown tool`). An error result such as a guard refusal still proves the tool exists.
427
- - `phantom-output`: output tokens billed for an assistant message that wrote nothing. A message whose stream was aborted (owner interrupt) or errored is not judged: the harness drops its partial content but keeps the usage of what streamed.
428
- - `cost-mismatch`: the run's `model_usage` cost misses the `traces.provider.prices` table ($ per million tokens) by more than ±20%, in either direction; a model without a price row is not checked.
429
-
430
- `neurastream metrics report` ends with a weekly line — `Provider honesty over N runs: …` — counting the findings of every run touched in the window. Both config maps are open: an empty object in the template means "add your own keys" in your config. The id patterns below were sampled from real traces; paste them (or yours) into `~/.config/neurastream/config.yml`:
431
-
432
- ```yaml
433
- traces:
434
- provider:
435
- id_patterns:
436
- anthropic: '^msg_[A-Za-z0-9]+$'
437
- zai: '^[0-9]{14}[0-9a-f]+$'
438
- openai-codex: '^resp_[0-9a-f]+$'
439
- openrouter: '^gen-[0-9]+-[A-Za-z0-9]+$'
440
- prices: {} # e.g. glm-test: { input: 2, output: 6, cache_read: 0.2, cache_write: 0.5 }
441
- allow_tools: []
442
- ```
443
-
444
- Finding evidence is masked (long token-like runs never survive verbatim) and capped at 160 characters, so a response id or a tool call line cannot carry a secret into the findings.
445
-
446
- ## Prompt bloat (`neurastream traces bloat`)
447
-
448
- `neurastream traces bloat [--since 24h] [--json]` (or one run by id) lists, per run, every model call's prompt — `usage.input + usage.cacheRead + usage.cacheWrite`, one row per call — and flags `prompt-bloat` when
449
-
450
- - the run's FIRST call opens over `traces.bloat.first_call_max` (a run that starts huge stays huge), or
451
- - any call passes `traces.bloat.ratio_of_limit` × its model's `traces.bloat.context_limits` entry (an open map; a model without an entry is not limit-checked).
452
-
453
- A failed request dump under `~/.omp/logs/http-400-requests` (named `<epoch-ms>-<id>.json`) belongs to one run only: its trace window must cover the dump, its model must match, and among eligible runs the closest event timestamp at or before the dump wins. An exact tie—or no eligible run—leaves the dump unmatched; text and `--json` output list unmatched dumps once. For the owning run, the report shows what filled the prompt: system, messages and tool groups (tools grouped by the first capture of `traces.bloat.tool_group` on the tool name; no match = `builtin`) plus the five largest individual tools.
454
-
455
- A rejected call never wrote usage, so a run can carry a 1.17M-token prompt with no usage row and no finding of its own. When a run has no usage finding, the matched dump's error response is read: a stated prompt size ("prompt is too long: 1172629 tokens > 1000000 maximum") becomes the flag, with the dump named as the source. A dump whose error response states no count flags nothing, and no size is ever guessed from bytes.
456
-
457
- `neurastream metrics report` ends with a weekly line — `Prompt bloat over N runs: K flagged, largest first call X tokens (<run>)` — over every run touched in the window (largest first call = the run's usage, else the matched dump's stated prompt). The agent ledger shows a `tok/call` column: prompt tokens ÷ calls per run.
458
-
459
- Config (defaults):
460
-
461
- ```yaml
462
- labels:
463
- episode_days: 30
464
- flip_weight: 1.0
465
- repos: []
466
- removal_comment_patterns: ['\bremoved\b', '\bno longer\b', '\bpreviously\b', '\bused to\b', '\bwas deleted\b']
467
- removal_subjects: ['^(remove|drop|delete)\b', '^chore: remove']
468
- traces:
469
- bloat:
470
- first_call_max: 150000
471
- ratio_of_limit: 0.8
472
- context_limits: {} # e.g. claude-opus-5-5: 1000000
473
- tool_group: '^_?mcp__([A-Za-z0-9]+)_'
474
- ```
475
-
476
-
477
- ## Self-metrics
478
-
479
- `neurastream metrics report [--days N]` compares this window (the last `metrics.report_days`, default 7) with the one before it, writes `<paths.notes>/metrics.md`, and prints the same report. Worst change is marked `◀ worst`. The five numbers:
480
-
481
- - M1 cost per merge: cost of sub and main runs written in the window, divided by accepts in the window. Worker-only and Main-only dollars are shown too.
482
- - M2 idle calls: calls of finished or died sub runs in the window that never got an accept, diagnose or validate event. Top 3 shown.
483
- - M3 CI tries: mean `tries` of `ci` events in the window, and the MRs at 3 or more tries. Tries come from `metrics.ci_pipelines_cmd` (see `docs/config.md`).
484
- - M4 owner corrections: owner messages in main runs that match `metrics.correction_patterns`, and Main messages ending in `?`. The owner message count is shown but never ranked.
485
- - M5 guard blocks: BLOCK lines in the guard logs in the window, with false alarms and the top 3 reasons.
486
-
487
- Caveat: M4 is a whole-run measure. A main run counts entirely by its last write time, so a run that spans a window edge counts in the window it ends in.
488
-
489
- The report ends with a `Provider honesty over N runs: …` line — provider-honesty findings (see Provider honesty above) over every run touched in the window — and a `Prompt bloat over N runs: …` line (see Prompt bloat above) over the same runs.
490
-
491
- Weekly loop: run `neurastream metrics report`, then propose ONE rule change to the owner. When the owner decides, record it with `neurastream metrics rule "<text>" --approved|--rejected`; approved rules get a before/after check once a full window has passed. Record CI with `neurastream metrics ci <repo-dir> <mr-id>` and guard false alarms with `neurastream metrics false-alarm <log-ts> --why "<text>"`. main-start shows the report as due when it is missing or older than `metrics.report_days`.
492
-
493
- Feature results: `neurastream metrics features [--days N] [--json]` prints $ per finished feature — a feature is a plan plus every later plan whose Goal names its file stem, finished means every plan in the chain has a closing Progress status or is archived; each hour's Main cost splits evenly over the plan files that hour's messages name (nothing named → overhead), and a sub run's cost goes to the plan its first message names. `neurastream metrics releases [--days N] [--json]` prints, per release (a `v*` tag of this repo or another repo's `metrics ci` merge), the same numbers for the N days before vs after it — $/feature, features/day, main calls/feature, tokens/call, fix plans/feature — plus each configured product number (`metrics.product_cmds`, last value before vs first after). The owner page's Results tab draws the releases as a line chart: the y links pick the metric ($/feature, features/day, calls, tokens, fix rate, or one per product number), the x links switch between time (days on the axis, dashed release markers) and feature/release order; product numbers are neutral — the table marks their direction with ▲/▼ but never colors them better or worse.
494
-
495
- ## Self-improvement
496
-
497
- Bugs in neurastream itself are found by code, written to a persistent list, and pushed on Main until each one has a plan or a recorded dismissal — not remembered. The list is `<paths.queue_state>/incidents.jsonl`; `neurastream incident list [--open] [--json]` reads it.
498
-
499
- Five sources feed it:
500
-
501
- - Real time (at Main's prompt and after each Main bash result): a finished subagent the agent-ledger still shows RUNNING/WAITING past `incidents.contradiction_grace_min` (D1); a neurastream tool that crashed in a Main bash result (D2); the same guard block firing `incidents.block_repeat` times within one hour (D3); an owner message matching `metrics.correction_patterns` (D4). D2 and D4 run on every event; D1 and D3 read the session files and the guard logs at most once per `incidents.scan_interval_sec` (state: `incident-scan.json` in the queue state dir).
502
- - Daily: at the first main-start or Main prompt of a day, M1-M5 for the last 24 hours against the mean of the 7 days before; a metric worse by `incidents.daily_worse_pct` and above its `incidents.daily_floor` floor is an incident.
503
- - Weekly: when the metrics report is due, the code writes `<paths.notes>/metrics.md` itself and its worst ranked metric becomes an incident.
504
- - Main itself: `neurastream incident add "<summary>" --kind <k>`.
505
- - A plan's Findings lines, a subagent's or Main's own: every new `## Progress` entry in a plan ends with a `Findings:` line (`Findings: none`, or one item per finding — bug, workaround, improvement, any repo — with `file:line` evidence, items separated by `;`). The plan-guard refuses and restores an entry without the line, and each item of an allowed edit becomes an incident (source `findings`; a subagent's item is kind `agent-finding`, Main's own kind `main-finding`; evidence = plan path + agent); the same text again dedupes into the open incident. The plan the entry is written in does not count as planning its finding — planning is `neurastream incident plan`.
506
-
507
- While an incident is open (no plan, dismissal or fixed record), every Main prompt carries one `INCIDENT <id> [<source>/<kind>]: <summary>` line per open incident, Main's `task` spawns and bypass launches are refused unless the brief names a plan citing `INCIDENT <id>`, and Main cannot stop with an incident that has neither. A stop reply that only offers to plan is refused too: the reply Main stops with is matched against `guards.plan_offer` (case-insensitive; "want me to write a plan?", "should I plan") and a hit answers "don't offer it — write the plan and index it" — the two-idle-stops release does not lift that block. The loop closes three ways: `neurastream incident plan <id> <plan.md>` (the plan must exist, be listed in the main index, cite `INCIDENT <id>`, and carry a fail-before phase — its regression test has to fail on the old code), `neurastream incident dismiss <id> --why "<text>"` (a finding incident — `agent-finding` or `main-finding` — is dismissed only with the owner's own words: `--owner "<quote>"`, a substring of an owner message the inject hook saw in the last 24 h, so the agent that found the bug cannot also wave it away), and `fixed` — written by the queue itself when it closes a plan that cites the incident. `neurastream metrics report` shows M6: incidents opened / planned / dismissed / fixed and the median hours from open to fixed.
508
-
509
- A finding incident (`agent-finding`, `main-finding`) shows on the Agents tab with Main's latest reason and two buttons. Main writes the reason with `neurastream incident propose <id> --why "<file:line and reason>"`; the why must cite the proof as `file:line`, and the incident stays open. The owner taps **False alarm** (the incident closes; the reason is recorded as the dismissal with the owner's login) or **It's a bug — plan it** (the incident stays open and one message goes to Main's inbox). A finding with no reason yet says "Main has not said why yet".
510
-
511
- ## Changing a script
512
-
513
- Edit the script in this repo. Green is `bun run typecheck` and `bun test`, both exit 0. Main tags the release. The publish workflow puts that tag on npm. Then:
123
+ Green is all three exiting `0`. Live installs are never hand-edited; after tagging a release, GitHub Actions publishes to npm, then update locally with:
514
124
 
515
125
  ```sh
516
126
  bun add -g neurastream@latest
517
127
  neurastream adapter install omp
518
128
  ```
519
129
 
520
- Live copies are never hand-edited. `neurastream doctor` names each hand-edited installed file and each missing one (`missing:`), and a stale install (the installed version is not `npm view neurastream version`). If the registry cannot be reached, that check is a warning, not a failure.
521
-
522
- ## AGENTS.md block
523
-
524
- Main's rules are not written into `~/.omp/agent/AGENTS.md`. Under `neurastream main` they ride Main's system prompt on each turn, built from `templates/AGENTS.md` with the agent dir from your config. Install strips a block an older install left between the markers `<!-- neurastream:begin (managed by neurastream; edit the package, not this block) -->` and `<!-- neurastream:end -->`.
525
-
526
- - Yours: every line outside the markers. Install keeps it byte for byte; a file the strip leaves empty is removed.
527
- - Leftover: markers still in the file, malformed ones included. Install leaves them alone; `neurastream doctor` reports `stale: neurastream block still in <file>`.
528
- - 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`.
529
-
530
- ## Project rules
531
-
532
- The repo an agent works in has its own `AGENTS.md` — test lanes, no-push, conventions. neurastream hands it over the way it hands Main the queue summary, always the live file and never a copy, so a rule added to a repo reaches the next agent that works in it:
533
-
534
- - **A subagent** gets, on its first turn, `Repo rules (<path>):` plus the `AGENTS.md` text of the repo its plan's index path lives in, then the owner's burden rule from `templates/AGENTS.md`. One hand-over per session: the same text is not repeated on the next turn.
535
- - **Main** gets a repo's `AGENTS.md` the first time the session works in that repo — a task spawn on that repo's plan, a read, a write, or a shell `cd` — and again only when the file changes. Rules never ride on every prompt, and an index repo the session never touches is never injected.
536
- - **Size cap**: `rules.max_bytes` (default 24000). A longer file is cut and one line says `…cut, read <path>`.
537
- - A repo with no `AGENTS.md` gets nothing: no error, no empty block.
538
- - A plan whose `Worktree:` line names a linked worktree with a different `AGENTS.md` gets that worktree's rules.
130
+ ## Documentation
539
131
 
540
- The finder and the hash cache are host-neutral (`src/core/repo-rules.ts`); the cache is `<paths.queue_state>/repo-rules.json`. The adapter decides only when the text is injected (`docs/adapter.md`).
132
+ - [docs/config.md](docs/config.md) — full configuration schema and defaults (`templates/config.yml`)
133
+ - [docs/adapter.md](docs/adapter.md) — harness-neutral adapter contract (`src/core/adapter.ts`) and `neurastream guard <event> --json`
134
+ - [docs/guards.md](docs/guards.md) — queue, blockers, review/read gates, autonomy tiers, planner mode, multi-Main claims, project rules
135
+ - [docs/workspace.md](docs/workspace.md) — owner phone UI, static pages, plan approvals, knowledge base tab
136
+ - [docs/operations.md](docs/operations.md) — rollover, rate limits, notifications, watch, WIP backup, secrets, machine health, recall
137
+ - [docs/traces-and-metrics.md](docs/traces-and-metrics.md) — scoring, trace audits, provider honesty, prompt bloat, self-metrics, incidents, rule tuning
138
+ - [docs/team-server.md](docs/team-server.md) — team queue server setup, auth, and routes
541
139
 
542
140
  ## License
543
141