project-brain 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Local-first MCP server that gives AI tools semantic memory of your codebase.
4
4
 
5
+ The whole Claude Code flow on one page (every piece, how to turn it off, what leaves the machine, troubleshooting): [docs/flow-map.md](docs/flow-map.md).
6
+
5
7
  project-brain indexes your project files into a local LanceDB vector store using Ollama embeddings, and builds a SQLite **structural graph** (symbols + call edges) with a WASM tree-sitter parser. Once indexed, AI assistants connected via MCP can search your codebase **semantically** (by meaning) AND **structurally** (exact symbols, callers/callees, change blast-radius), track module documentation, and maintain knowledge that persists across sessions.
6
8
 
7
9
  ## Quick Start
@@ -162,7 +164,7 @@ bun build ./src/cli.ts ./src/parser/worker.ts --compile --outfile project-brain
162
164
 
163
165
  ### Keeping the host skills current
164
166
 
165
- Skills live in your assistant's global skills directory, not in the package, so upgrading the binary does not move them. project-brain compares the installed skill content against what the running binary carries and refreshes any directory it originally created — whichever way you upgraded. It never creates one (that is `setup`'s job) and never touches a directory it cannot prove it wrote. Opt out with `BRAIN_NO_SKILL_REFRESH=1`.
167
+ Skills live in your assistant's global skills directory, not in the package, so upgrading the binary does not move them. project-brain compares the installed skill content against what the running binary carries and refreshes any directory it originally created — whichever way you upgraded. It never creates one (that is `setup`'s job) and never touches a directory it cannot prove it wrote. Opt out with `BRAIN_NO_SKILL_REFRESH=1`. A checkout run from source (`bun src/cli.ts`, in a worktree or not) never refreshes skills, repairs host configs or adds hooks, so a branch cannot push unreleased content into your sessions; set `BRAIN_FORCE_SKILL_REFRESH=1` to allow those writes anyway.
166
168
 
167
169
  ## Usage modes
168
170
 
@@ -282,9 +284,9 @@ With no token configured, nothing changes — zero network calls, identical resu
282
284
 
283
285
  Suggestions come from their own **global** `UserPromptSubmit` hook, `project-brain suggest --stdin`, separate from the per-project retrieval hook. `setup` installs it by default (unit `hooks:suggest`), and an existing install gets it added **once** the next time its routing `SessionStart` hook runs, without rerunning `setup`. It works in every project, including ones never initialized with project-brain: no index is opened, and the prompt vector comes from the project's indexed embedding model when there is one, otherwise from the default model (keyword matching when Ollama does not answer). Without a token it stays silent. To opt out, deselect "Skill/tool suggestions" in `setup` (or remove the hook by hand) and it is never re-added, or set `BRAIN_SKILL_PICKER=0` / `BRAIN_TOOL_PICKER=0`.
284
286
 
285
- With a token configured, the hook asks Jev which installed skill best fits your prompt and adds one line to the context: `Suggested skill: <name> — <why>`. It only appears when Jev is at least 70% confident; otherwise nothing is added. Skills are read from `~/.claude/skills`, `<project>/.claude/skills`, `~/.agents/skills` and installed plugins (`plugin:skill`), cached on disk (rebuilt when any SKILL.md changes, or after ten minutes). The shortlist is chosen by embedding similarity using the project's embedding model, so prompts in any language the model supports match English skill descriptions; skill vectors are cached next to the skill list, and without embeddings it falls back to keyword overlap.
287
+ With a token configured, the hook asks Jev, for each shortlisted skill, whether the work your prompt asks for needs it: process skills (planning, brainstorming, debugging, review) and domain skills (the framework or tool the work touches) can both apply to one prompt, so every skill Jev judges at least 70% likely is suggested, best first, one line each: `Suggested skill: <name> — <its full description>`. The description is the skill's own, whole, because with the [compact skill listing](#claude-tui) the model may only have the name. Below 70% nothing is added. A ceiling of 10 picks per prompt (`pickCeiling` in `~/.project-brain/skills.json`, or `BRAIN_SKILL_PICK_MAX`) guards against a runaway response; when more skills clear the floor, the top ones are kept and a line on stderr says how many were cut. General-use skills (see the [compact skill listing](#claude-tui)) are never asked about or suggested. A suggestion still visible in the live conversation is not repeated. Skills are read from `~/.claude/skills`, `<project>/.claude/skills`, `~/.agents/skills` and installed plugins (`plugin:skill`), cached on disk (rebuilt when any SKILL.md changes, or after ten minutes), plus the built-in and connector skills Claude Code lists without a SKILL.md, whose descriptions the [compact skill listing](#claude-tui) mod records in `~/.project-brain/skill-listing.json`. The shortlist is the 12 skills nearest the prompt by embedding similarity (the project's embedding model, so prompts in any language match English descriptions; keyword overlap without embeddings, or when nothing ranks), plus up to 16 process skills, those whose description opens with "Use when", "Use before" or "You MUST use": a task prompt names the work, not the process, so embeddings rank those far down ("construye una feature nueva de login" put superpowers:brainstorming 58th of 135). There is no similarity floor for skills; Jev's 70% judgment is the filter. When Jev keeps failing (three requests in a row), the hook records it in `~/.project-brain/skill-pick-health.json` and the listing mod keeps descriptions until a request succeeds again.
286
288
 
287
- **The prompt text and the shortlisted skills' names and descriptions (at most 12) are sent to `api.typesafe.ai`** — the same disclosure as the reranker. Trivial prompts send nothing, and on the keyword fallback so do prompts with no overlap with any skill. The whole hook gives up after 5s (Jev itself after 1s) and fails silently. Opt out with `BRAIN_SKILL_PICKER=0`.
289
+ **The prompt text and the shortlisted skills' names and descriptions (at most 28) are sent to `api.typesafe.ai`** — the same disclosure as the reranker. Trivial prompts send nothing. The whole hook gives up after 5s (Jev itself after 1s) and fails silently. Opt out with `BRAIN_SKILL_PICKER=0`.
288
290
 
289
291
  **Tool suggestions.** The same request can also carry a second question about your MCP tools, and the hook then adds `Suggested tool: mcp__<server>__<tool> — <why>` (again only at 70% confidence). Claude Code defers most MCP tools, so the assistant often never reaches for the right one; the hint names it. project-brain keeps its own catalog in `~/.project-brain/`: `tool-catalog.json` for user-scope servers (`~/.claude.json` top level, `~/.claude/mcp-servers.json`) and a per-project file for local-scope servers plus the project's `.mcp.json` ones, which are used only if you approved them in Claude Code (so a freshly cloned repo can never make project-brain start its servers): each stdio server, or unauthenticated HTTP server, is started briefly and asked for `tools/list` (10s per server, four at a time; a failure or a 401 skips that server, and project-brain itself is left out). Servers that cannot be listed this way, such as claude.ai connectors, are filled in by name only from the `deferred_tools_delta` entries in your recent Claude Code transcripts (claude.ai connectors and plugin servers only). The suggest hook never builds the catalog: it only reads it, and when it is missing, older than 24 hours or its servers changed, it spawns `project-brain tool-catalog refresh` in the background (at most once every ten minutes). Run that command yourself to rebuild on demand; it prints how many tools it found, and it also embeds the tools in the background so the hook only ever reads cached vectors. Both questions share the one Jev request, so tool suggestions add no round trip, and the same disclosure applies to the shortlisted tools' names and descriptions (at most 12). Opt out with `BRAIN_TOOL_PICKER=0`, independently of `BRAIN_SKILL_PICKER`.
290
292
 
@@ -331,7 +333,11 @@ Every context-economy feature is its own unit in the `setup` checklist, ticked b
331
333
  | `feature:task-switch` | one-line `/clear` or `/compact` notice at 30% context | your last few prompts, to api.typesafe.ai, with a TypeSafe token and a picker on |
332
334
  | `feature:search-gate` | per-prompt search skips non-code prompts, caps hits, floors reranker scores | nothing extra |
333
335
  | `config:mcp-prune` | disables MCP servers a project never uses | nothing |
336
+ | `config:mcp-prune-jev` | opt-in: lets prune ask Jev about registered projects with little history | each unused server's name and tool names, the project's stack and unscoped dependency names, to api.typesafe.ai, with a TypeSafe token |
334
337
  | `config:context-slim` | moves large user sections of CLAUDE.md into skills | nothing |
338
+ | `tui:context-gate` | leaves out hook-injected context the prompt does not need | your prompt and the injected text it judges (head and tail of each piece), to api.typesafe.ai, with a TypeSafe token |
339
+ | git post-commit hook (written by `init`, not a setup unit) | runs `sync --changed-only && conceptualize` in the background after every commit | the commit message, each touched module's full diff (up to 5 modules per commit) and that module's current concept doc, to the backend `config:concept-provider` chose: **anthropic** (default) sends them to the Anthropic API, only when Anthropic credentials resolve (`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` or `ant auth login`); **claude-code** sends them to Anthropic through your Claude Code login (`claude -p`, haiku, your subscription quota, no API key); **ollama** sends nothing — `qwen3.5:4b` on the local Ollama writes the doc. A missing backend skips the commit's modules with one line in `.project-brain/sync.log`. Turn it off with the `feature:conceptualize` setup unit, or `PROJECT_BRAIN_CONCEPTUALIZE=0` |
340
+ | `config:concept-provider` | which backend writes the module docs, saved in `~/.project-brain/concept.json`; asked once, changed with `setup --concept-provider anthropic\|ollama\|claude-code` | see the post-commit row: anthropic and claude-code reach Anthropic, ollama stays local |
335
341
 
336
342
  `setup` asks which parts to install — one checklist per group (Hosts, Guidance,
337
343
  Skills, Claude TUI, Other), asked in order, so each question is about one kind of thing — and
@@ -355,17 +361,52 @@ project-brain setup --none
355
361
 
356
362
  Run `project-brain setup --with=nope` to print the list of valid ids.
357
363
 
364
+ After an upgrade, a prompt in a Claude Code session lists the units that shipped since you last chose (in neither list of `setup-selection.json`) and are not on disk: up to five by name, then a count. The list is computed between sessions, by `update` and by the SessionEnd maintenance job, so a prompt never waits on it; it is shown by one session only, each unit is named at most once per machine, a unit you declined is never named, and `PROJECT_BRAIN_WHATS_NEW=0` turns it off. `project-brain setup --new` opens the checklist with only those units and leaves every other answer as it is. Without a prompt, `--new --with=<ids>` enables what it names and `--new --without=<ids>` declines what it names, leaving the rest undecided; `--new --yes` enables only the units that are on by default unconditionally, so neither an opt-in unit nor one that turns on when a TypeSafe token exists is enabled that way. `--all`, `--none` and the `--no-*` flags are refused with `--new`. `project-brain status` keeps listing every unit that is available but not enabled.
365
+
358
366
  #### Claude TUI
359
367
 
360
- The "Claude TUI" checklist sets up Claude Code's terminal. Both units change files under `~/.claude`, so an upgrade never installs them on its own: they show up marked `NEW` and unchecked. Untick a unit to undo exactly what it wrote.
368
+ The "Claude TUI" checklist sets up Claude Code's terminal. Every unit changes files under `~/.claude`, so an upgrade never installs them on its own: they show up marked `NEW` and unchecked. Untick a unit to undo exactly what it wrote.
361
369
 
362
370
  | Unit | What it changes | Undo (untick) |
363
371
  |---|---|---|
364
372
  | `tui:activity-pane` | Writes the `project-brain-activity` mod into a local marketplace at `~/.project-brain/claude-plugins/`, registers it in `~/.claude/settings.json` (`extraKnownMarketplaces["project-brain"]`, `enabledPlugins["project-brain-activity@project-brain"]`) and, on first install, sets `tui` to `"fullscreen"`, remembering the value it replaced; a renderer you pick later is kept on updates | Deletes both entries and the files it wrote, and puts your previous `tui` value back unless you changed it since |
365
373
  | `tui:readable-replies` | Adds a marked block to `~/.claude/CLAUDE.md`: result first, full sentences, evidence at the end, no narration between tool calls | Deletes the block; the rest of the file stays as it was |
374
+ | `tui:skill-listing` | Writes the `project-brain-skill-listing` mod into the same local marketplace and registers it (`enabledPlugins["project-brain-skill-listing@project-brain"]`); asks for your general-use skills and saves them to `~/.project-brain/skills.json`; writes `~/.project-brain/skill-usage.json`. Unchecked even on a first run: it trades skill descriptions for tokens, which is yours to decide | Deletes its plugin entry, its files and `skill-usage.json`; the marketplace entry goes only with the last mod in it. `skills.json` stays, since the suggest hook reads it too |
375
+ | `tui:context-gate` | Writes the `project-brain-context-gate` mod into the same local marketplace and registers it (`enabledPlugins["project-brain-context-gate@project-brain"]`). Unchecked even on a first run: it leaves context out of what the model reads, which is yours to decide | Deletes its plugin entry and its files; the marketplace entry goes only with the last mod in it |
366
376
 
367
377
  The activity pane is a side pane named "Actividad" with tabs for todos, commands and uncommitted changes; each changed file expands to its diff against HEAD, with line numbers, and Enter on a file name opens it in one reused nvim split (Supacode, tmux, or a Terminal window) with its diff. When subagents run, a selector shows each one with its own summary, commands and diff; the header and footer stay fixed while the body scrolls. It docks on the right only in the fullscreen renderer (`/tui fullscreen`), which is why the unit switches it on. `/activity` reopens the pane after you close it, and ctrl+o still expands tool rows in the chat. The cost it shows is Claude Code's own estimate for the session, not a bill. If another marketplace is already registered under the name `project-brain`, setup reports the unit as foreign and leaves it alone; other plugins' settings are never touched. Mods need Claude Code 2.1.287 or later, and do not load when `disableAllHooks` is set.
368
378
 
379
+ **Compact skill listing.** Claude Code sends the model a listing of every installed skill, one line with its description each, at the start of every session and every subagent: about 7,500 tokens for 136 skills. The `project-brain-skill-listing` mod rewrites that listing so every name stays but most descriptions go, in one of two modes:
380
+
381
+ - **With the Jev picker** (a well-formed TypeSafe token, the picker on, the suggest hook installed and hooks not disabled, and fewer than three Jev failures in a row): every skill is listed by name only, except your general-use skills. The suggest hook then brings in, per prompt, the full description of each skill the work needs (see [Skill suggestions](#skill-suggestions)). Delegations get the same treatment: whenever a subagent, teammate or workflow agent is spawned, the mod runs `project-brain suggest --agent --stdin` on the task's description and prompt (one Jev request, same floor and ceiling) and puts the picked skills, with their full descriptions, before the subagent's prompt. With no token, a Jev failure or past the 5 s budget, the prompt goes out unchanged. A subagent's listing is names-only only when its spawn carried such a block; any other subagent gets the usage mode below.
382
+ - **Without it**: your general-use skills, the `brain-*` skills, the 15 you invoked most in the last 30 days and any you used in the last 7 keep their description; the rest are names. With fewer than 10 recorded invocations, the listing is left as it is.
383
+
384
+ Usage numbers come from `project-brain skill-usage --write`, which counts Skill tool calls and slash commands in `~/.claude/projects/**/*.jsonl` (under `CLAUDE_CONFIG_DIR` when set) from the last 30 days (newest first, at most 8 GiB read, a call copied into a resumed session counted once) and writes `~/.project-brain/skill-usage.json`. Setup runs it on install; the mod reruns it at session start when the file is a day old. `project-brain skill-usage` alone prints the counts and writes nothing. The mod only rewrites the listing Claude Code itself wrote, and on any failure passes the text through unchanged.
385
+
386
+ General-use skills keep their full line in every mode and are never suggested by Jev, so nothing is said twice. Setup asks for them each time it installs or updates the unit, as a multiselect of your installed skills with the most used marked as suggestions (never pre-ticked); the default is none. You can also edit the file by hand; every key is optional:
387
+
388
+ ```json
389
+ {
390
+ "general": ["brain-style", "superpowers:brainstorming"],
391
+ "picker": true,
392
+ "pickCeiling": 10,
393
+ "keepTop": 15,
394
+ "keepRecentDays": 7
395
+ }
396
+ ```
397
+
398
+ `picker: false` (or `BRAIN_SKILL_PICKER=0`) turns off the per-prompt and per-delegation skill picks, and the listing falls back to the usage mode. `keepTop` and `keepRecentDays` only matter in that mode.
399
+
400
+ **Context gate.** Other hooks and plugins inject context into every session: a SessionStart hook's handbook, a UserPromptSubmit hook's notes, a PostToolUse hook's policy. The `project-brain-context-gate` mod asks Jev, before that text reaches the model, whether the prompt at hand needs it, and leaves out what it does not.
401
+
402
+ **Your prompt and the injected text the gate judges are sent to `api.typesafe.ai`.** Each piece is sent as its first 800 and last 400 characters.
403
+
404
+ Only additional context and plain hook output from SessionStart, UserPromptSubmit and PostToolUse hooks, or a plugin's context, is judged. A blocking error, a stopped continuation, a permission decision, a system message and anything from a PreToolUse guard always reach the model as they are. Several hooks' outputs arrive joined line by line in one attachment, so the mod judges each run of lines between allowlisted ones. project-brain's own hooks wrap their text in `<!-- project-brain:begin -->` and `<!-- project-brain:end -->`, and everything between them is kept whole. Engram, project-brain and any signature you add under `contextAllow` in `~/.project-brain/skills.json` are never filtered, and pieces under 300 characters are not worth a request. One `project-brain suggest --context --stdin` call per attachment asks about every piece at once, and a piece Jev scores at 0.5 or above stays.
405
+
406
+ With no token, `"contextGate": false`, `BRAIN_CONTEXT_GATE=0`, a timeout or any error, the text goes out unchanged. After three Jev failures in a row (`~/.project-brain/context-gate-health.json`) the gate stops asking, and tries again once 10 minutes have passed since the last failure. Each piece left out is listed in `~/.project-brain/context-gate-log.json`.
407
+
408
+ The gate keeps the prompt cache. Claude Code asks for an attachment once per process, and again on resume, so every answer is stored per session and replayed byte for byte. A resumed session never asks Jev about its history, and sends any history it holds no answer for unchanged until a turn it started itself completes. Answers survive compactions: a row a compaction preserved replays the answer it was given before. The trade-off is that a verdict is pinned to its text for the whole session: a hook that injects the same text every turn is judged once, against the first prompt that saw it, and only text the gate has not seen before is judged after a compaction. Turning the gate off or uninstalling it mid-session costs one cache rewrite on the next resume, because the history goes back to the text the gate had left out. In a measured six-turn session with a resume, every request read the previous one's prefix from cache, and the gate cut the prompt from 104k to 75k tokens.
409
+
369
410
  #### Worktree lifecycle
370
411
 
371
412
  ```bash
@@ -419,7 +460,7 @@ project-brain mcp prune --apply # add them to that project's disabledMcpServe
419
460
  project-brain mcp prune --revert # re-enable exactly what --apply disabled
420
461
  ```
421
462
 
422
- It is per project: usage in one project never disables a server in another, and nothing touches the user-wide list. Git worktrees of a repo pool their usage and history, so a fresh worktree inherits the repo's. A project needs 10 sessions, or 14 days of history with at least 3 sessions inside the window, and its directory must still exist; new projects are handled by a later setup or update once they have history. project-brain, servers you list in `PROJECT_BRAIN_MCP_PRUNE_KEEP` (comma separated) and servers you switched back on after we disabled them are never touched: re-enabling a pruned server through `/mcp` is respected for good, even if it goes unused afterwards. Only MCP tool calls count as usage, so a server you use through resources or prompts alone belongs on the keep list. Setup (`config:mcp-prune`, checked by default) and `update` run `--apply` for all projects; opt out with `PROJECT_BRAIN_MCP_PRUNE=0`, change the window with `PROJECT_BRAIN_MCP_PRUNE_DAYS`. `~/.claude.json` is backed up under `~/.project-brain/mcp-prune/`, written atomically, and only the disabled lists change. Changes apply from the next session.
463
+ It is per project: usage in one project never disables a server in another, and nothing touches the user-wide list. Git worktrees of a repo pool their usage and history, so a fresh worktree inherits the repo's. A project needs 10 sessions, or 14 days of history with at least 3 sessions inside the window, and its directory must still exist; new projects are handled by a later setup or update once they have history. Jev assist is opt-in (the `config:mcp-prune-jev` unit, unticked by default and never turned on by an upgrade, or `PROJECT_BRAIN_MCP_PRUNE_JEV=1`; `=0` forces it off) and needs a TypeSafe token. With it on, a project registered with project-brain that has less history, but was used in the window, is not just skipped: on `--apply` (and setup or update), Jev is asked once per repo which of its unused servers it will need, and only those it rates under 20% are disabled. Answers are cached for 30 days per project and server, the whole run stops asking after 15 seconds, and anything unanswered is kept; a dry run and `status` read the cache only. The request carries each unused server's name and tool names, and the project's detected languages, frameworks, package manager and dependency names without scoped `@org/...` ones; never server instructions, the package name, README text, file names, or a server's command, URL or environment. With it on, the prune also runs between sessions without setup: `project-brain init` prunes its own project directory right after registering it, and the SessionEnd maintenance job prunes every registered project. Both leave alone any project where a Claude Code process is running (its working directory is the project or inside it, found with `ps` and `lsof` on macOS or `/proc` on Linux), or whose transcript changed in the last 10 minutes, since a live session there could rewrite `~/.claude.json` and undo the change; when that cannot be told (detection fails, times out after 2s, the platform is unsupported, or the transcript folder cannot be read) the project is skipped too. A later run picks it up. A session already running keeps the servers it started with, and the next one starts without the pruned ones. One prune runs at a time per machine: an automatic one skips when another holds the lock, while `--revert` waits up to 30 seconds and otherwise asks you to retry. The `~/.claude.json` from before the first prune stays in `~/.project-brain/mcp-prune/baseline-claude.json.bak` beside the five newest backups. What can still leak: an unscoped private dependency name, and the names you gave your MCP servers. A server that announced no tools is kept, never judged by its name. project-brain, servers you list in `PROJECT_BRAIN_MCP_PRUNE_KEEP` (comma separated) and servers you switched back on after we disabled them are never touched: re-enabling a pruned server through `/mcp` is respected for good, even if it goes unused afterwards. Only MCP tool calls count as usage, so a server you use through resources or prompts alone belongs on the keep list. Setup (`config:mcp-prune`, checked by default) and `update` run `--apply` for all projects; opt out with `PROJECT_BRAIN_MCP_PRUNE=0`, change the window with `PROJECT_BRAIN_MCP_PRUNE_DAYS`. `~/.claude.json` is backed up under `~/.project-brain/mcp-prune/`, written atomically, and only the disabled lists change. Changes apply from the next session.
423
464
 
424
465
  #### Auto-compact window
425
466
 
@@ -449,7 +490,7 @@ If that multiplication is the problem rather than the flag itself, the next unit
449
490
 
450
491
  `service:chrome-shared-server` replaces one server per session with one server for every session. It takes the command a detected host already runs, puts it behind an HTTP bridge held open by a login service, and rewrites each host entry to point at `http://127.0.0.1:39100/mcp`. Sessions then cost a client connection each; the machine carries one process and one CDP attachment.
451
492
 
452
- It is **unchecked** by default, and it is the only unit that installs an OS service (launchd on macOS, a systemd user unit on Linux; elsewhere it does not appear) and a Python tool. Both are answers to give on purpose.
493
+ It is **unchecked** by default, and it installs an OS service (launchd on macOS, a systemd user unit on Linux; elsewhere it does not appear) and a Python tool. Both are answers to give on purpose.
453
494
 
454
495
  The bridge is [`mcp-proxy`](https://github.com/sparfenyuk/mcp-proxy), installed with `uv` if it is missing. It calls `stdio_client` once at startup and reuses that session for every client, so all clients genuinely share one child, and its JSON-RPC ids cannot collide because it proxies at the MCP semantic layer rather than relaying bytes. Setup pins its SDK below 2: installed without that constraint, the tool resolves an SDK where `request_ctx` no longer exists and every invocation dies at import.
455
496
 
@@ -469,6 +510,20 @@ If a host already points at a bridge you set up yourself, under any service name
469
510
 
470
511
  Two limits worth knowing. Sharing the server shares its state: one page list visible to every session, one profile, and process-level flags (`--headless`, `--autoConnect`, `--viewport`, `--blockedUrlPattern`) that can no longer differ per session; `--pageIdRouting`, on by default, is what stops sessions from acting on each other's tabs. And collapsing N attachments to one does not bound how large that one grows — a single attached server was the 1.6 GB measurement — so setup prints the restart command for your platform when it finishes.
471
512
 
513
+ #### Ollama interactive lane
514
+
515
+ One Ollama answers embeds one at a time, so while `sync` sends its 64-chunk batches (about 5.5 s each on an M3 Max), the prompt hook's one-line query waits behind them: measured at 5.4 s p50 against the hook's 800 ms budget. `OLLAMA_NUM_PARALLEL` does not help. A second Ollama that only ever sees queries answers the same query in about 50 ms under that load.
516
+
517
+ `service:ollama-interactive` runs that second instance as a login service (launchd on macOS, a systemd user unit on Linux; not offered on Windows): `ollama serve` on `127.0.0.1:11435`, with `OLLAMA_KEEP_ALIVE=-1` so the embedding model stays warm, `OLLAMA_MAX_LOADED_MODELS=2` so two projects on different models do not evict each other on every prompt, and `OLLAMA_MODELS` pointing at the default models directory, so nothing is downloaded twice. It also copies the settings that change the numbers a runner produces (`OLLAMA_FLASH_ATTENTION`, `OLLAMA_KV_CACHE_TYPE`, `OLLAMA_LLM_LIBRARY`, `OLLAMA_MODELS`) from the default instance's service definition — Homebrew's plist, or the systemd unit together with its `*.service.d/*.conf` drop-ins, with `/usr/share/ollama/.ollama/models` assumed for the official system install — and from setup's own environment when there is no service file (Ollama.app, a hand-started `ollama serve`). Homebrew's Ollama runs with flash attention and a q8_0 KV cache, and an instance without them returns vectors that differ in the third decimal. Setup refuses to install when something else already listens on 11435, and fails (removing what it wrote) when `launchctl bootstrap` or `systemctl --user enable` does not succeed; `inspect` reports the unit stale when the service is written but not loaded. It is **unchecked** by default: it installs an OS service and keeps embedding models resident in memory for good.
518
+
519
+ The lane is on only where setup installed it (it records `{"interactiveHost": "http://127.0.0.1:11435"}` in `~/.project-brain/ollama.json` and removes it on uninstall) or `BRAIN_OLLAMA_INTERACTIVE_HOST` names a host. Prompt-time single-query embeds — the `suggest` and `search --stdin` hooks (skill, tool and context picks) and the MCP `search_context` query — then go to it. Every multi-text embed, including the 16-skill batches the hook fills its cache with, stays on the default instance, as does indexing (`sync`, `init`, `reindex`, the watcher, `sync_project`) and the skill and tool vector caches: a batch on the lane would take longer than the lane's 400 ms budget and switch it off for everyone.
520
+
521
+ The lane is not trusted until it is verified. A detached `project-brain lane-verify` compares the two instances' Ollama version, the model's digest, and one probe embedding, which must match exactly; it also loads the model, since a cold load takes longer than a query waits and Ollama abandons a load whose client hung up. Until a verdict exists, and for 15 minutes after a mismatch, queries use the default instance. A verified lane is re-verified every 15 minutes, which catches a `brew upgrade ollama` that restarted only one instance, a model pulled again, or a foreign process on the port. When a verified lane does not answer within 400 ms, the query is retried once on the default instance and the lane is skipped for 60 s. Verdicts live in `~/.project-brain/lane/`, keyed by host and model. `project-brain health` and `check_health` run the same verification and report the lane as `up`, `down`, `mismatch` (with the reason) or `off`.
522
+
523
+ 11435 stays the port because it is the one the setup unit was approved with; the `BRAIN_OLLAMA_HOSTS` example below uses 11436 so a pool built from it does not collide with the lane. A pool member that does sit on 11435 still passes verification only if it is genuinely the same Ollama, model and settings.
524
+
525
+ `BRAIN_OLLAMA_INTERACTIVE_HOST` overrides the host (`off` disables the lane); `~/.project-brain/ollama.json` with `{ "interactiveHost": "<url>|off" }` does the same when the env var is unset.
526
+
472
527
  #### Model routing for sub-agents
473
528
 
474
529
  Setup also writes model-routing guidance into each detected host's rules file: which **tier** — `fast`, `balanced`, or `deep` — a delegated sub-agent should run at for a given kind of task, and how to set that tier *on that host*.
@@ -501,6 +556,8 @@ Override the table in `~/.project-brain/model-routing.json`:
501
556
 
502
557
  Add `--routing-hook-strict` for enforcement: a `PreToolUse` hook that blocks a spawn naming no model and tells the model to re-issue it with one. Off by default — inheriting the session model is sometimes the right call, and the guard fails open on any payload it cannot parse. `--no-routing-hook` skips both.
503
558
 
559
+ **Report contract.** The skill and the `SessionStart` reminder both ask every delegation to close with a fixed hand-back: verdict (PASS / BLOCKERS / PARTIAL / DONE), changes, test counts, risks and open decisions, in about 400 words, with the full detail written to a file whose path the report gives. A long hand-back stays in the parent's context until it compacts, so the detail belongs on disk. `project-brain setup --with=hooks:report-contract` adds a `PreToolUse` hook that appends the contract to each delegation prompt through `updatedInput`. It never appends twice and leaves alone any prompt that sets its own output shape (JSON, YAML, a schema, an output format, a word cap). It is off by default because it rewrites a prompt the session wrote.
560
+
504
561
  #### Coding rules guard
505
562
 
506
563
  A `PreToolUse` hook on `Edit`, `Write` and `MultiEdit` that hands an agent the installed `brain-style` skill the first time it edits a code file, so the rules arrive when code is written rather than when a prompt is typed. It reaches sub-agents too: Claude Code fires `PreToolUse` inside them, and the hook keys its once-only memory by session and agent. It is selected by default in `setup` because it is local and warn-only: it exits 0 and adds the rules as `additionalContext`, and fails open on anything it cannot read.
@@ -605,6 +662,28 @@ project-brain health
605
662
 
606
663
  Also reports the outcome of the last background sync (`.project-brain/sync-status.json`) as a `Last sync:` line — `ok`, `aborted` (the watchdog gave up on a wedged job), `failed`, or `crashed` (the process died mid-run without ever writing a terminal outcome). Anything short of a clean `ok` points at `.project-brain/sync.log`, where the post-commit hook's `sync`/`conceptualize` output actually lands (overwritten on each run, so it always reflects the last one). The `check_health` MCP tool surfaces the same data as a `lastSync` field.
607
664
 
665
+ ### `status`
666
+
667
+ Everything left pending across every registered project, in one read-only report. It never changes anything.
668
+
669
+ ```bash
670
+ project-brain status [--json] [--project <id>]
671
+ ```
672
+
673
+ For each project it lists commits not yet pushed (a branch ahead of its upstream, or a local branch with no upstream that has commits not on the default branch), uncommitted changes in the main checkout, and linked worktrees that `worktree finish` would accept (merged, clean, idle). Globally it lists setup units that are available but not enabled (ones you declined are left out), and compares the installed version with npm's `latest` and `next` dist-tags, flagging when `latest` lags `next`, and lists your live MCP servers that run an older version than the installed one. Each pending item comes with the command that resolves it. A clean project prints nothing; when nothing at all is pending it prints one `All clear` line. Repositories with no remote are not checked for unpushed commits, and the npm lookup gives up after 3 s.
674
+
675
+ ### `stats`
676
+
677
+ What project-brain put into your Claude Code sessions, per session and per project, read only from local files: nothing is sent anywhere and nothing is written.
678
+
679
+ ```bash
680
+ project-brain stats [--days N] [--all] [--json]
681
+ ```
682
+
683
+ For each session in the window (default the last 7 days, `--days N` or `--days=N`; only injections and gate drops stamped inside it count) it reports the prompt-context hook's injected blocks (prompts, hits, tokens), the context the Jev context gate dropped (`~/.project-brain/context-gate-log.json`), the tool names and server instructions the session's MCP set holds in context at its largest between compactions (subagents counted apart), and the MCP servers `mcp prune` had disabled for that directory before the session began. The scope is the current project: the initialized project root, else the git repository root, else exactly the current directory, and the header says which; `--all` covers every project. Unknown flags exit with status 2. Every token figure is an estimate, characters divided by 4. `--json` carries counts, sources and scores only, never prompt text.
684
+
685
+ Per project it also prints a usage signal: of the distinct hits injected, how many the model later read, edited, named in a shell command, or got back from a project-brain tool in the same transcript, and that share at each floor. It is a report, not a calibration. Measured on real transcripts (5,345 injected hits), only 2% were later read, edited or returned by a project-brain tool; counting shell commands, the signal agreed with hand labels only moderately (17 of 36 relevant hits used, 8 of 127 irrelevant). And since only hits above the floor in force are ever injected, it cannot show what a lower floor would add.
686
+
608
687
  ### `bench` — measure retrieval quality
609
688
 
610
689
  Published embedding leaderboards score a different corpus and a different task. A percent-or-two delta on someone else's benchmark says nothing about whether YOUR queries still surface the right file after changing model, dimension or chunking — so `bench` measures against ground truth from *this* repository instead.
@@ -627,13 +706,13 @@ project-brain search "how does auth work"
627
706
  echo "how does auth work" | project-brain search --stdin
628
707
  ```
629
708
 
630
- The hook only injects when it is likely to help. Before any embedding work it skips prompts that carry no code question: very short prompts (under 3 words or 15 characters, unless they name a code identifier), acknowledgements and continuations in English and Spanish ("ok", "sí", "continúa", "commit y push"), slash-command echoes, and pasted harness or agent reports. Hits scoring below 0.5 are dropped and at most 5 are kept; if nothing survives, nothing is printed. The plain CLI `search "<q>"` is not gated.
709
+ The hook only injects when it is likely to help. Before any embedding work it skips prompts that carry no code question: very short prompts (under 3 words or 15 characters, unless they name a code identifier), acknowledgements and continuations in English and Spanish ("ok", "sí", "continúa", "commit y push"), slash-command echoes, and pasted harness or agent reports. Hits Jev scores below 0.65 are dropped and at most 5 are kept; if nothing survives, nothing is printed. The floor comes from `scripts/calibrate-hook-floor.ts`, which replays your own prompts read-only through the hook's retrieval and Jev (at most 30 requests), writes every hit to a file outside the repository for labelling, and prints precision and recall per floor. The floor is one value for every project and is not adjusted automatically; `project-brain stats` shows it next to how often injected hits were used. The plain CLI `search "<q>"` is not gated.
631
710
 
632
711
  Hook output stays in the conversation, so a snippet is injected only while it is not already there: the hook reads the newest 8 MB of the session transcript (`transcript_path`), follows the live message chain back from the newest entry, and skips any snippet whose printed text, score aside, an earlier UserPromptSubmit hook output on that chain already holds. When every relevant hit is already there, nothing is printed. The skill/tool suggestion hook does the same per suggested name. Because it reads the live chain, a compaction, `/clear`, `/rewind` or an edited earlier message brings the dropped snippets back on the next prompt, and an unreadable transcript dedups nothing. No state is stored.
633
712
 
634
713
  | Variable | Default | Effect |
635
714
  |---|---|---|
636
- | `PROJECT_BRAIN_SEARCH_MIN_SCORE` | `0.5` | Minimum reranker score (0-1) a hit needs to be injected; ignored without a reranker token, where only `PROJECT_BRAIN_SEARCH_MAX_HITS` applies |
715
+ | `PROJECT_BRAIN_SEARCH_MIN_SCORE` | `0.65` | Minimum reranker score (0-1) a hit needs to be injected; ignored without a reranker token, where only `PROJECT_BRAIN_SEARCH_MAX_HITS` applies |
637
716
  | `PROJECT_BRAIN_SEARCH_MAX_HITS` | `5` | Maximum snippets injected |
638
717
  | `PROJECT_BRAIN_SEARCH_PROMPT_FILTER` | on | Set to `0` to search every prompt, including non-code ones |
639
718
  | `PROJECT_BRAIN_CONTEXT_DEDUP` | on | Set to `0` to inject snippets and suggestions on every prompt, even when the session already has them |
@@ -714,13 +793,15 @@ What reaches Claude Code sessions that are already open:
714
793
 
715
794
  - **Hooks and skills** are live at once: Claude Code reloads `settings.json` and skill directories, and hooks re-run the binary on every event.
716
795
  - **CLAUDE.md** is only read at launch, so the first prompt after an update shows a one-time notice (`project-brain updated X → Y`) with the current model-routing guidance.
717
- - **The MCP server** is not reloaded by Claude Code. By default the same notice tells you to run `/mcp reconnect all` (or `/mcp`) to load the new tools.
796
+ - **The MCP server** is not reloaded by Claude Code, so stdio `serve` moves itself to the new binary (the hot swap below). With the hot swap turned off, the same notice tells you to run `/mcp reconnect all` (or `/mcp`) to load the new tools.
797
+
798
+ Whenever a server is still on old code, the `check_health` tool says so in its `versionDrift` field (`MCP server runs 0.42.0, installed 0.45.1: run /mcp reconnect ...`, or, when a hot swap to that version failed, the reason it failed), and `project-brain status` lists every live MCP server of yours that runs an older version than the installed one, by pid, with the same fix. Each server records its version under `~/.project-brain/servers/` while it runs, and a record counts only while its pid is still that server; a server too old to have recorded itself is found in the process table and reported when it started before the installed binary was put in place. Without `ps` (Windows) status leaves servers out.
718
799
 
719
- #### Optional: automatic MCP hot swap
800
+ #### Automatic MCP hot swap
720
801
 
721
- Set `BRAIN_MCP_HOT_SWAP=1` in the MCP server's environment and stdio `serve` runs a small supervisor that relays to a worker process. When the binary on disk is newer, it starts a new worker, waits until no request is in flight, switches over, sends `tools/list_changed`, then lets the old worker drain and exit. A failure at any point leaves the old worker serving, and the notice then says to run `/mcp reconnect all`; after two failed attempts at a version the supervisor stops trying for that session. It is off by default because the supervisor is a second process per session, about 76 MB of memory each. Servers started before the first release with this feature have no supervisor, so that first update still needs one `/mcp reconnect all`.
802
+ Stdio `serve` runs a small supervisor that relays to a worker process. When the binary on disk is newer, it starts a new worker, waits until no request is in flight, switches over, sends `tools/list_changed`, then lets the old worker drain and exit. A failure at any point leaves the old worker serving and is reported by `check_health`: when the new binary does not start, it says so and tells you to reinstall or upgrade again rather than reconnect, since a reconnect would start the same binary. After two failed attempts at a version the supervisor stops trying for that session. A new worker that speaks another MCP protocol version than the session negotiated is refused. If the old worker dies while the new one is ready, the new one takes over instead of the session ending. A retiring worker that is finishing a sync is never killed for it: it marks itself as draining and gets up to 10 minutes; the new worker cannot start indexing meanwhile, because the old one holds the project's `watch.lock` until its sync has finished. Only `serve` gets a supervisor: never `serve --http`, one-shot commands or hooks. The supervisor costs about 16 MB of physical memory per session (measured on macOS, against about 50 MB for the worker), because the release binary is compiled with `--splitting` and the supervisor loads only its own code. Set `BRAIN_MCP_HOT_SWAP=0` in the MCP server's environment to run the server in-process instead; `BRAIN_MCP_HOT_SWAP=1` from before this was the default keeps working. Servers started before the release that made this the default have no supervisor, so that first update still needs one `/mcp reconnect all`.
722
803
 
723
- Limits to know about: a new worker is launched through the same command your tool used (for a brew or npm link, the link, so a retargeted link is picked up), never through the old versioned directory; and when running from source with `bun run`, only the entry script is watched, so a change that touches `package.json` alone is not noticed.
804
+ Limits to know about: a new worker is launched through the same command your tool used (for a brew or npm link, the link, so a retargeted link is picked up), never through the old versioned directory; when running from source with `bun run`, only the entry script is watched, so a change that touches `package.json` alone is not noticed; and a pnpm global install runs project-brain from a versioned `.pnpm/project-brain@<version>` directory that an upgrade leaves in place, so pnpm users still need one `/mcp reconnect` per upgrade.
724
805
 
725
806
  ### `serve`
726
807
 
@@ -748,8 +829,10 @@ BRAIN_HTTP_TOKEN=your-secret project-brain serve --http [--port 3000]
748
829
  | `BRAIN_EMBED_MODEL` | `qwen3-embedding:0.6b` | Ollama embedding model (registry keys: `qwen3-embedding`, `nomic-text`; or any raw Ollama model name; `none` disables embeddings — lexical/keyword search only, no Ollama needed) |
749
830
  | `OLLAMA_HOST` | `http://127.0.0.1:11434` | Ollama server URL |
750
831
  | `BRAIN_NO_UPDATE_CHECK` | — | Set to `1` to disable the update-available notice |
751
- | `BRAIN_CONCEPT_MODEL` | `claude-haiku-5-5` | Anthropic model id `conceptualize` uses to write module concepts. Read on each call. Same credentials as `--judge` (`ANTHROPIC_API_KEY` or `ant auth login`). |
752
- | `BRAIN_SKILL_PICKER` | on | Set to `0` to turn off the Jev skill suggestion the global suggest hook prints — see [Skill suggestions](#skill-suggestions). |
832
+ | `BRAIN_CONCEPT_PROVIDER` | `concept.json`, else `anthropic` | Backend `conceptualize` writes module concepts with: `anthropic` (Anthropic API, same credentials as `--judge`), `claude-code` (`claude -p` on your Claude Code login, run with `--safe-mode`, no hooks, plugins, MCP or tools; the diffs still go to Anthropic) or `ollama` (local; waits at most 30s in total for a running `sync` to finish embedding, then skips). An unknown value, or a corrupt `concept.json`, sends nothing rather than falling back to anthropic. Outranks `~/.project-brain/concept.json`, which `setup --concept-provider` writes. |
833
+ | `BRAIN_CONCEPT_MODEL` | per backend: `claude-haiku-5-5`, `haiku`, `qwen3.5:4b` | Model `conceptualize` uses, for whichever backend is chosen. Read on each call. Outranks the `model` in `concept.json`, which only applies while the file's provider is the one in use. |
834
+ | `BRAIN_SKILL_PICKER` | on | Set to `0` to turn off the Jev skill suggestions the global suggest hook prints, and the per-delegation picks — see [Skill suggestions](#skill-suggestions). Wins over `picker` in `~/.project-brain/skills.json`. |
835
+ | `BRAIN_SKILL_PICK_MAX` | `10` | Safety ceiling on skills suggested for one prompt or delegation; wins over `pickCeiling` in `~/.project-brain/skills.json`. |
753
836
  | `TYPESAFE_API_KEY` | — | Opt-in Jev reranker token — see [Reranking (optional)](#reranking-optional). Checked before `~/.project-brain/reranker.json`; a SessionStart hook exports the stored token under this name to Claude Code sessions. |
754
837
 
755
838
  ## Tuning (environment variables)
@@ -760,7 +843,8 @@ BRAIN_HTTP_TOKEN=your-secret project-brain serve --http [--port 3000]
760
843
  |---|---|---|---|
761
844
  | `BRAIN_EMBED_BATCH_SIZE` | `64` | `1`–`512` | Texts per Ollama embed request. Lower it if Ollama times out under load. |
762
845
  | `BRAIN_EMBED_CONCURRENCY` | `1` | `1`–`16` | Concurrent embed requests. Defaults to `1` — a single local Ollama instance is GPU-compute-bound, so concurrency>1 adds no throughput, only false-timeout risk. Raise it only against a genuine multi-host pool (`BRAIN_OLLAMA_HOSTS`) or remote inference API where separate hardware actually runs requests in parallel. |
763
- | `BRAIN_OLLAMA_HOSTS` | — | comma-separated URLs | Pool of Ollama hosts for round-robin embedding (e.g. `http://127.0.0.1:11434,http://127.0.0.1:11435`). Falls through to the next host on failure; only `null`s when every host fails. |
846
+ | `BRAIN_OLLAMA_HOSTS` | — | comma-separated URLs | Pool of Ollama hosts for round-robin embedding (e.g. `http://127.0.0.1:11434,http://127.0.0.1:11436`). Falls through to the next host on failure; only `null`s when every host fails. |
847
+ | `BRAIN_OLLAMA_INTERACTIVE_HOST` | off, or `http://127.0.0.1:11435` once `service:ollama-interactive` is installed | URL or `off` | Ollama host for prompt-time single-query embeds (hooks, `search_context`). Used only after it verifies identical to the default host; falls back to the default host when it does not answer. See [Ollama interactive lane](#ollama-interactive-lane). |
764
848
  | `BRAIN_EMBED_MODEL` | `qwen3-embedding:0.6b` | model name | Override the embedding model (see table above). |
765
849
  | `BRAIN_SYNC_WINDOW_FILES` | `200` | `1`+ | Files held in memory at once during a sync. Their content, chunks and vectors are live together and released when the window is stored, so peak memory tracks this number rather than repository size. Lower it on a memory-constrained host; raising it buys nothing once a window already fills an embed batch. |
766
850
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "project-brain",
3
- "version": "0.44.0",
3
+ "version": "0.46.0",
4
4
  "type": "module",
5
5
  "description": "Local-first MCP server that gives AI tools semantic memory of your codebase.",
6
6
  "author": "jcsoftdev",
@@ -33,7 +33,7 @@
33
33
  "typecheck": "tsc --noEmit",
34
34
  "setup": "bun run src/cli.ts setup",
35
35
  "init": "bun run src/cli.ts init",
36
- "build": "bun build ./src/cli.ts ./src/parser/worker.ts --compile --outfile dist/project-brain"
36
+ "build": "bun build ./src/cli.ts ./src/parser/worker.ts --compile --splitting --outfile dist/project-brain"
37
37
  },
38
38
  "dependencies": {
39
39
  "@anthropic-ai/sdk": "^0.111.0",
@@ -49,11 +49,11 @@
49
49
  "zod": "^4.4.3"
50
50
  },
51
51
  "optionalDependencies": {
52
- "project-brain-darwin-arm64": "0.44.0",
53
- "project-brain-linux-x64": "0.44.0",
54
- "project-brain-linux-arm64": "0.44.0",
55
- "project-brain-windows-x64": "0.44.0",
56
- "project-brain-windows-arm64": "0.44.0"
52
+ "project-brain-darwin-arm64": "0.46.0",
53
+ "project-brain-linux-x64": "0.46.0",
54
+ "project-brain-linux-arm64": "0.46.0",
55
+ "project-brain-windows-x64": "0.46.0",
56
+ "project-brain-windows-arm64": "0.46.0"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@types/bun": "latest",
@@ -0,0 +1,179 @@
1
+ import type { Hook } from 'claude-code'
2
+ import { atom, read, update } from 'claude-code'
3
+ import type { Register } from 'claude-code'
4
+
5
+ import type { AgentRecord } from '../types'
6
+ import type { Action, Api, Cell, Look, Row, Span, Tone } from './register'
7
+ import { AGENT_LOOK, ICONS, MAIN, clean, fit, shortName, span } from './register'
8
+
9
+ // Values from './register' are used only inside functions: the import is circular.
10
+
11
+ const REPORT_CHARS = 4096
12
+ const REPORTS_KEPT = 30
13
+ const PREVIEW_LINES = 6
14
+ const MARKER_ROOM = 2 * 5
15
+
16
+ const expandedAtom = atom({ plugin: 'project-brain-activity', key: 'agentsExpanded' } as const, false, { shape: 'agentsExpanded-1' })
17
+ const reportsAtom = atom({ plugin: 'project-brain-activity', key: 'agentsReports' } as const, {} as Record<string, string>, { shape: 'agentsReports-1' })
18
+
19
+ /** The toggle that shows or hides the ended agents' chips. */
20
+ export type AgentsAction = { kind: 'agents'; op: 'toggle' }
21
+
22
+ /** A header cell whose action may be this feature's own, until `Action` carries `AgentsAction`. */
23
+ export type AgentsCell = Omit<Cell, 'action'> & { action?: Action | AgentsAction }
24
+
25
+ export type AgentsPart = { expanded: boolean; reports: Record<string, string> }
26
+
27
+ export type GroupedInput = { records: AgentRecord[]; scope: string; expanded: boolean; width: number }
28
+
29
+ export type Verdict = { token: string; tone: Tone }
30
+
31
+ const isEnded = (record: AgentRecord): boolean => record.state !== 'running'
32
+
33
+ const newestFirst = (a: AgentRecord, b: AgentRecord): number => b.startedAt - a.startedAt
34
+
35
+ const widthOf = (cell: AgentsCell): number => cell.spans.reduce((sum, one) => sum + [...one.text].length, 0)
36
+
37
+ const chipOf = (key: string, label: string, isOn: boolean, action: Action, look?: Look): AgentsCell => ({
38
+ key,
39
+ label,
40
+ action,
41
+ spans: [
42
+ span(` ${label} `, { inverse: isOn, bold: isOn }),
43
+ ...(look ? [span(`${look.icon} `, { color: look.color, inverse: isOn })] : []),
44
+ span(' '),
45
+ ],
46
+ })
47
+
48
+ const toggleOf = (ended: AgentRecord[], expanded: boolean): AgentsCell => {
49
+ const done = ended.filter(one => one.state === 'done').length
50
+ const failed = ended.length - done
51
+ const parts: Span[] = []
52
+ if (done > 0) parts.push(span(`${ICONS.ok} ${done}`, { color: 'success', bold: expanded }))
53
+ if (done > 0 && failed > 0) parts.push(span(' · ', { dim: true }))
54
+ if (failed > 0) parts.push(span(`${ICONS.error} ${failed}`, { color: 'error', bold: expanded }))
55
+ return {
56
+ key: 'agents-toggle',
57
+ label: expanded ? 'Ocultar terminados' : 'Mostrar terminados',
58
+ action: { kind: 'agents', op: 'toggle' },
59
+ spans: [span(expanded ? ' ▾ ' : ' ▸ ', { color: 'suggestion' }), ...parts, span(' ')],
60
+ }
61
+ }
62
+
63
+ /**
64
+ * The cells that fit one row: the pinned cells stay, the chips scroll as a window that always holds
65
+ * the selected one. Hidden chips collapse into "‹ N" / "N ›" markers that select the nearest hidden agent.
66
+ * The same windowing as `agentStrip`, for more than one pinned cell.
67
+ */
68
+ const windowed = (pinned: AgentsCell[], chips: AgentsCell[], selected: number, ids: string[], width: number): AgentsCell[] => {
69
+ const pinnedWidth = pinned.reduce((sum, one) => sum + widthOf(one), 0)
70
+ const total = pinnedWidth + chips.reduce((sum, one) => sum + widthOf(one), 0)
71
+ if (total <= width) return [...pinned, ...chips]
72
+ const room = width - pinnedWidth - MARKER_ROOM
73
+ if (room <= 0 || chips.length === 0) return pinned
74
+ const marker = (text: string, id: string, key: string): AgentsCell => ({
75
+ key,
76
+ label: text.trim(),
77
+ action: { kind: 'agent', id },
78
+ spans: [span(text, { color: 'suggestion', bold: true })],
79
+ })
80
+ let start = Math.max(0, selected)
81
+ let end = start
82
+ let used = 0
83
+ const fits = (index: number) => used + widthOf(chips[index] as AgentsCell) <= room
84
+ while (end < chips.length && (end === start || fits(end))) used += widthOf(chips[end++] as AgentsCell)
85
+ while (start > 0 && fits(start - 1)) used += widthOf(chips[--start] as AgentsCell)
86
+ return [
87
+ ...pinned,
88
+ ...(start > 0 ? [marker(`‹ ${start} `, ids[start - 1] ?? MAIN, 'agents-left')] : []),
89
+ ...chips.slice(start, end),
90
+ ...(end < chips.length ? [marker(` ${chips.length - end} ›`, ids[end] ?? MAIN, 'agents-right')] : []),
91
+ ]
92
+ }
93
+
94
+ /**
95
+ * The agent chips grouped: "Principal" and the ended agents' toggle stay pinned; running agents follow,
96
+ * newest first; ended agents show after them only when expanded. The selected agent is always shown.
97
+ */
98
+ export const agentChipsGrouped = ({ records, scope, expanded, width }: GroupedInput): AgentsCell[] => {
99
+ const live = records.filter(one => !isEnded(one)).sort(newestFirst)
100
+ const ended = records.filter(isEnded).sort(newestFirst)
101
+ const shownEnded = expanded ? ended : ended.filter(one => one.id === scope)
102
+ const visible = [...live, ...shownEnded]
103
+ const principal = chipOf(`agents-chip-${MAIN}`, 'Principal', scope === MAIN, { kind: 'agent', id: MAIN })
104
+ const pinned = ended.length > 0 ? [principal, toggleOf(ended, expanded)] : [principal]
105
+ const chips = visible.map(one => chipOf(`agents-chip-${one.id}`, shortName(one), scope === one.id, { kind: 'agent', id: one.id }, AGENT_LOOK[one.state]))
106
+ return windowed(pinned, chips, visible.findIndex(one => one.id === scope), visible.map(one => one.id), Math.max(1, width))
107
+ }
108
+
109
+ const VERDICT_LINE = /^[\s#>*_`-]*(?:\d+[.)]\s*)?[*_`]*(?:(?:final|overall)\s+)?(?:verdict|veredicto)(?:\s+final)?[*_`]*\s*[::]\s*[*_`]*\s*([A-Za-z][A-Za-z_-]*)/im
110
+
111
+ const VERDICT_TONES: Record<string, Tone> = {
112
+ PASS: 'success', PASSED: 'success', OK: 'success', APPROVED: 'success', APPROVE: 'success', SUCCESS: 'success', DONE: 'success',
113
+ FAIL: 'error', FAILED: 'error', REJECTED: 'error', REJECT: 'error', ERROR: 'error', BLOCKERS: 'error', BLOCKER: 'error',
114
+ PARTIAL: 'warning', BLOCKED: 'warning', WARN: 'warning', WARNING: 'warning', INCONCLUSIVE: 'warning',
115
+ }
116
+
117
+ /** The token of a "Verdict:" line, wherever the report puts it; markdown emphasis around it is ignored. */
118
+ export const verdictIn = (text: string): Verdict | undefined => {
119
+ const found = VERDICT_LINE.exec(text)?.[1]
120
+ if (found === undefined) return undefined
121
+ const token = found.toUpperCase().replace(/-/g, '_').slice(0, 16)
122
+ return { token, tone: VERDICT_TONES[token] ?? 'subtle' }
123
+ }
124
+
125
+ /** The report kept for an agent: cleaned, cut to its first 4 KB of characters. */
126
+ export const boundReport = (raw: string): string => {
127
+ const cleaned = clean(raw).trim()
128
+ const chars = [...cleaned]
129
+ return chars.length <= REPORT_CHARS ? cleaned : chars.slice(0, REPORT_CHARS).join('')
130
+ }
131
+
132
+ /** The first lines of an ended agent's report and its verdict; nothing for a running agent or one with no report. */
133
+ export const rowsAgentReport = (record: AgentRecord | undefined, report: string | undefined, width: number): Row[] => {
134
+ if (record === undefined || !isEnded(record) || report === undefined || report.trim() === '') return []
135
+ const verdict = verdictIn(report)
136
+ const lines = report.split('\n').map(one => one.trimEnd()).filter(one => one.trim() !== '' && !VERDICT_LINE.test(one))
137
+ const shown = lines.slice(0, PREVIEW_LINES)
138
+ const room = Math.max(1, width - 2)
139
+ const head: Row = {
140
+ key: 'agents-report-head',
141
+ cells: [{ spans: [span(`${ICONS.log} Informe`, { bold: true })] }],
142
+ ...(verdict ? { right: [span(` ${verdict.token} `, { color: verdict.tone, bold: true })] } : {}),
143
+ }
144
+ const body: Row[] = shown.map((one, index) => ({ key: `agents-report-${index}`, cells: [{ spans: [span(` ${fit(clean(one), room)}`, { dim: true })] }] }))
145
+ const more = lines.length - shown.length
146
+ return [
147
+ head,
148
+ ...body,
149
+ ...(more > 0 ? [{ key: 'agents-report-more', cells: [{ spans: [span(` … ${more} ${more === 1 ? 'línea más' : 'líneas más'}`, { color: 'subtle' })] }] }] : []),
150
+ ]
151
+ }
152
+
153
+ export async function readAgents($: Api): Promise<AgentsPart> {
154
+ const [expanded, reports] = await Promise.all([read($, expandedAtom), read($, reportsAtom)])
155
+ return { expanded, reports }
156
+ }
157
+
158
+ export async function actAgents($: Api, action: AgentsAction): Promise<void> {
159
+ if (action.op === 'toggle') await update($, expandedAtom, isOn => !isOn)
160
+ }
161
+
162
+ /** Keeps the latest report of each agent, the newest `REPORTS_KEPT` agents only. */
163
+ export const keepReport = (all: Record<string, string>, agentId: string, report: string): Record<string, string> =>
164
+ Object.fromEntries([...Object.entries(all).filter(([id]) => id !== agentId), [agentId, report]].slice(-REPORTS_KEPT))
165
+
166
+ export const registerAgents = (on: Parameters<Register>[0]): void => {
167
+ }
168
+
169
+ export async function agentsTurnComplete($: Api, e: Parameters<Hook<'turn.complete'>>[1], next: Parameters<Hook<'turn.complete'>>[2]): Promise<Awaited<ReturnType<Hook<'turn.complete'>>>> {
170
+ const done = await next(e)
171
+ try {
172
+ const agentId = e.agentId
173
+ const report = agentId === undefined ? '' : boundReport(e.answer)
174
+ if (agentId !== undefined && report !== '') await update($, reportsAtom, all => keepReport(all, agentId, report))
175
+ } catch {
176
+ // A lost preview never costs the turn its result.
177
+ }
178
+ return done
179
+ }