project-brain 0.43.0 → 0.45.1
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 +97 -11
- package/package.json +6 -6
- package/templates/claude-tui/activity-pane/.claude-plugin/plugin.json +7 -0
- package/templates/claude-tui/activity-pane/hooks/feat-agents.tsx +179 -0
- package/templates/claude-tui/activity-pane/hooks/feat-blocked.tsx +232 -0
- package/templates/claude-tui/activity-pane/hooks/feat-ci.tsx +400 -0
- package/templates/claude-tui/activity-pane/hooks/feat-context.tsx +283 -0
- package/templates/claude-tui/activity-pane/hooks/feat-notify.tsx +145 -0
- package/templates/claude-tui/activity-pane/hooks/feat-progress.tsx +413 -0
- package/templates/claude-tui/activity-pane/hooks/feat-running.tsx +528 -0
- package/templates/claude-tui/activity-pane/hooks/feat-savings.tsx +533 -0
- package/templates/claude-tui/activity-pane/hooks/hooks.json +1 -0
- package/templates/claude-tui/activity-pane/hooks/register.tsx +2141 -0
- package/templates/claude-tui/activity-pane/types/index.d.ts +201 -0
- package/templates/claude-tui/context-gate/.claude-plugin/plugin.json +7 -0
- package/templates/claude-tui/context-gate/hooks/hooks.json +1 -0
- package/templates/claude-tui/context-gate/hooks/register.tsx +355 -0
- package/templates/claude-tui/context-gate/types/index.d.ts +28 -0
- package/templates/claude-tui/skill-listing/.claude-plugin/plugin.json +7 -0
- package/templates/claude-tui/skill-listing/hooks/hooks.json +1 -0
- package/templates/claude-tui/skill-listing/hooks/register.tsx +300 -0
- package/templates/claude-tui/skill-listing/types/index.d.ts +22 -0
- package/templates/model-routing.md +10 -0
- package/templates/skills/brain-design-review/SKILL.md +65 -0
- package/templates/skills/brain-design-review/references/audit.md +56 -0
- package/templates/skills/brain-design-review/references/fix-loop.md +36 -0
- package/templates/skills/brain-design-review/references/probes.md +80 -0
- package/templates/skills/brain-qa-only/SKILL.md +59 -0
- package/templates/skills/brain-qa-only/references/report.md +63 -0
- package/templates/skills/brain-worktree/SKILL.md +18 -0
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
|
|
|
@@ -192,6 +194,8 @@ These five are thin wrappers over the CLI. **project-brain does not install them
|
|
|
192
194
|
|---|---|---|
|
|
193
195
|
| `/brain-audit` | *(none — host skill)* | Whole-project audit: dead code, orphan UI, broken flows, coverage gaps, plus findings by severity across security, performance and architecture |
|
|
194
196
|
| `/brain-okf` | *(none — host skill)* | Write an OKF concept: the reasoning behind code, anchored to a verified symbol and checkable by `okf audit` |
|
|
197
|
+
| `/brain-design-review` | *(none — host skill)* | Audit a rendered UI like a designer (ten categories, AI-slop check), score it, then fix findings one commit each and re-verify |
|
|
198
|
+
| `/brain-qa-only` | *(none — host skill)* | Explore a browser, API, CLI or worker surface and report reproducible bugs with evidence; never edits product code |
|
|
195
199
|
| `/brain-commit` | *(none — host skill)* | Write a commit message in the convention the repository's own log already shows |
|
|
196
200
|
| `/brain-record` | *(none — host skill)* | Record the flow a branch touches as video evidence for a PR or ticket |
|
|
197
201
|
| `/brain-worktree` | *(none — host skill)* | Give an isolated worktree its own index (seeded from the main checkout) and its own leased port |
|
|
@@ -280,9 +284,9 @@ With no token configured, nothing changes — zero network calls, identical resu
|
|
|
280
284
|
|
|
281
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`.
|
|
282
286
|
|
|
283
|
-
With a token configured, the hook asks Jev
|
|
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.
|
|
284
288
|
|
|
285
|
-
**The prompt text and the shortlisted skills' names and descriptions (at most
|
|
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`.
|
|
286
290
|
|
|
287
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`.
|
|
288
292
|
|
|
@@ -329,10 +333,14 @@ Every context-economy feature is its own unit in the `setup` checklist, ticked b
|
|
|
329
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 |
|
|
330
334
|
| `feature:search-gate` | per-prompt search skips non-code prompts, caps hits, floors reranker scores | nothing extra |
|
|
331
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 |
|
|
332
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 |
|
|
333
341
|
|
|
334
342
|
`setup` asks which parts to install — one checklist per group (Hosts, Guidance,
|
|
335
|
-
Skills, Other), asked in order, so each question is about one kind of thing — and
|
|
343
|
+
Skills, Claude TUI, Other), asked in order, so each question is about one kind of thing — and
|
|
336
344
|
remembers the answer in `~/.project-brain/setup-selection.json`. Re-running it
|
|
337
345
|
shows what is currently on disk beside what you are selecting, then a diff of
|
|
338
346
|
what will change before anything is written. A part you deselect is removed and
|
|
@@ -353,6 +361,50 @@ project-brain setup --none
|
|
|
353
361
|
|
|
354
362
|
Run `project-brain setup --with=nope` to print the list of valid ids.
|
|
355
363
|
|
|
364
|
+
#### Claude TUI
|
|
365
|
+
|
|
366
|
+
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.
|
|
367
|
+
|
|
368
|
+
| Unit | What it changes | Undo (untick) |
|
|
369
|
+
|---|---|---|
|
|
370
|
+
| `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 |
|
|
371
|
+
| `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 |
|
|
372
|
+
| `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 |
|
|
373
|
+
| `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 |
|
|
374
|
+
|
|
375
|
+
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.
|
|
376
|
+
|
|
377
|
+
**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:
|
|
378
|
+
|
|
379
|
+
- **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.
|
|
380
|
+
- **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.
|
|
381
|
+
|
|
382
|
+
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.
|
|
383
|
+
|
|
384
|
+
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:
|
|
385
|
+
|
|
386
|
+
```json
|
|
387
|
+
{
|
|
388
|
+
"general": ["brain-style", "superpowers:brainstorming"],
|
|
389
|
+
"picker": true,
|
|
390
|
+
"pickCeiling": 10,
|
|
391
|
+
"keepTop": 15,
|
|
392
|
+
"keepRecentDays": 7
|
|
393
|
+
}
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
`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.
|
|
397
|
+
|
|
398
|
+
**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.
|
|
399
|
+
|
|
400
|
+
**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.
|
|
401
|
+
|
|
402
|
+
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.
|
|
403
|
+
|
|
404
|
+
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`.
|
|
405
|
+
|
|
406
|
+
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.
|
|
407
|
+
|
|
356
408
|
#### Worktree lifecycle
|
|
357
409
|
|
|
358
410
|
```bash
|
|
@@ -361,6 +413,8 @@ project-brain worktree finish [<name|path>] [--yes] # dry run unless --yes
|
|
|
361
413
|
project-brain worktree sweep [--yes] [--branches] # finish every worktree that qualifies
|
|
362
414
|
```
|
|
363
415
|
|
|
416
|
+
`create` also clones the main checkout's `node_modules` into the worktree copy-on-write (`cp -c -R` on macOS/APFS, `cp --reflink=always` on Linux), so a worktree costs ~0 extra disk instead of a second install. In a monorepo it clones every workspace package's `node_modules` too (the packages listed in `package.json` `workspaces` or `pnpm-workspace.yaml`), each only where that package exists in the worktree and has no `node_modules` yet. When the lockfile content hash matches the main checkout's, the clone is all it does. When it differs, it clones anyway and then runs the package manager's install in the worktree (`bun install`, `pnpm install`, `npm install` or `yarn install`, picked from the lockfile); because the clone is copy-on-write, the install only writes the packages that changed. That install runs the package manager's lifecycle scripts (such as `postinstall`) from the worktree's `package.json`. It has a 10-minute timeout. If it fails, times out, or the tool is missing, every clone is removed, along with any `node_modules` the install created where there was none before, so the worktree has no `node_modules` again, and `create` prints one line saying why. The Node version and platform are not compared: a clone reproduces the main checkout's folder exactly, so it works in the worktree exactly as well as it works in the main checkout. The clone is independent, so changing a dependency in the worktree never touches the main checkout. On macOS it first checks that the main checkout and the worktree are on the same APFS volume, because `cp -c` silently falls back to a full copy elsewhere (HFS+, exFAT, or across volumes). If the filesystem cannot clone, nothing is copied and `create` prints one line saying why.
|
|
417
|
+
|
|
364
418
|
A worktree is finished when it is not the main checkout, its branch is merged into the default branch (or has no commits of its own and is over an hour old), its tree is clean (a lone untracked `node_modules` symlink is tolerated), and no process is using it. `--yes` removes the directory with `git worktree remove` and the branch with `git branch -d`; it never forces and never uses `-D`, so unmerged or dirty work is never removed. `sweep` removes only worktrees under `.claude/worktrees`; it lists ones outside it as `[outside .claude]` and removes them only with `--include-outside` (or `finish <path> --yes`, since naming a worktree is explicit consent). It also lists merged branches that have no worktree (`--branches` deletes those). `create` adds `.claude/worktrees/` and the files `init` generates (`.project-brain/`, `CLAUDE.md`, `docs/modules/`, `.claude/settings.json`) to the repository's local `info/exclude`, so a fresh worktree is not dirty.
|
|
365
419
|
|
|
366
420
|
`setup` adds a default-on `SessionEnd` hook (`hooks:worktree-sweep`) that runs `worktree sweep --yes --quiet` and prints a line only when it removed something. Untick it in `setup`, or use `--without=hooks:worktree-sweep`, to opt out.
|
|
@@ -404,7 +458,7 @@ project-brain mcp prune --apply # add them to that project's disabledMcpServe
|
|
|
404
458
|
project-brain mcp prune --revert # re-enable exactly what --apply disabled
|
|
405
459
|
```
|
|
406
460
|
|
|
407
|
-
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.
|
|
461
|
+
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.
|
|
408
462
|
|
|
409
463
|
#### Auto-compact window
|
|
410
464
|
|
|
@@ -434,7 +488,7 @@ If that multiplication is the problem rather than the flag itself, the next unit
|
|
|
434
488
|
|
|
435
489
|
`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.
|
|
436
490
|
|
|
437
|
-
It is **unchecked** by default, and it
|
|
491
|
+
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.
|
|
438
492
|
|
|
439
493
|
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.
|
|
440
494
|
|
|
@@ -454,6 +508,20 @@ If a host already points at a bridge you set up yourself, under any service name
|
|
|
454
508
|
|
|
455
509
|
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.
|
|
456
510
|
|
|
511
|
+
#### Ollama interactive lane
|
|
512
|
+
|
|
513
|
+
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.
|
|
514
|
+
|
|
515
|
+
`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.
|
|
516
|
+
|
|
517
|
+
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.
|
|
518
|
+
|
|
519
|
+
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`.
|
|
520
|
+
|
|
521
|
+
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.
|
|
522
|
+
|
|
523
|
+
`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.
|
|
524
|
+
|
|
457
525
|
#### Model routing for sub-agents
|
|
458
526
|
|
|
459
527
|
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*.
|
|
@@ -486,6 +554,8 @@ Override the table in `~/.project-brain/model-routing.json`:
|
|
|
486
554
|
|
|
487
555
|
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.
|
|
488
556
|
|
|
557
|
+
**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.
|
|
558
|
+
|
|
489
559
|
#### Coding rules guard
|
|
490
560
|
|
|
491
561
|
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.
|
|
@@ -590,6 +660,16 @@ project-brain health
|
|
|
590
660
|
|
|
591
661
|
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.
|
|
592
662
|
|
|
663
|
+
### `status`
|
|
664
|
+
|
|
665
|
+
Everything left pending across every registered project, in one read-only report. It never changes anything.
|
|
666
|
+
|
|
667
|
+
```bash
|
|
668
|
+
project-brain status [--json] [--project <id>]
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
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`. 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.
|
|
672
|
+
|
|
593
673
|
### `bench` — measure retrieval quality
|
|
594
674
|
|
|
595
675
|
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.
|
|
@@ -612,13 +692,16 @@ project-brain search "how does auth work"
|
|
|
612
692
|
echo "how does auth work" | project-brain search --stdin
|
|
613
693
|
```
|
|
614
694
|
|
|
615
|
-
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
|
|
695
|
+
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 plain CLI `search "<q>"` is not gated.
|
|
696
|
+
|
|
697
|
+
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.
|
|
616
698
|
|
|
617
699
|
| Variable | Default | Effect |
|
|
618
700
|
|---|---|---|
|
|
619
|
-
| `PROJECT_BRAIN_SEARCH_MIN_SCORE` | `0.
|
|
701
|
+
| `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 |
|
|
620
702
|
| `PROJECT_BRAIN_SEARCH_MAX_HITS` | `5` | Maximum snippets injected |
|
|
621
703
|
| `PROJECT_BRAIN_SEARCH_PROMPT_FILTER` | on | Set to `0` to search every prompt, including non-code ones |
|
|
704
|
+
| `PROJECT_BRAIN_CONTEXT_DEDUP` | on | Set to `0` to inject snippets and suggestions on every prompt, even when the session already has them |
|
|
622
705
|
|
|
623
706
|
### Structural & lexical commands (`find`, `callers`, `callees`, `impact`, `trace`, `map`, `code`)
|
|
624
707
|
|
|
@@ -730,8 +813,10 @@ BRAIN_HTTP_TOKEN=your-secret project-brain serve --http [--port 3000]
|
|
|
730
813
|
| `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) |
|
|
731
814
|
| `OLLAMA_HOST` | `http://127.0.0.1:11434` | Ollama server URL |
|
|
732
815
|
| `BRAIN_NO_UPDATE_CHECK` | — | Set to `1` to disable the update-available notice |
|
|
733
|
-
| `
|
|
734
|
-
| `
|
|
816
|
+
| `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. |
|
|
817
|
+
| `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. |
|
|
818
|
+
| `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`. |
|
|
819
|
+
| `BRAIN_SKILL_PICK_MAX` | `10` | Safety ceiling on skills suggested for one prompt or delegation; wins over `pickCeiling` in `~/.project-brain/skills.json`. |
|
|
735
820
|
| `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. |
|
|
736
821
|
|
|
737
822
|
## Tuning (environment variables)
|
|
@@ -742,7 +827,8 @@ BRAIN_HTTP_TOKEN=your-secret project-brain serve --http [--port 3000]
|
|
|
742
827
|
|---|---|---|---|
|
|
743
828
|
| `BRAIN_EMBED_BATCH_SIZE` | `64` | `1`–`512` | Texts per Ollama embed request. Lower it if Ollama times out under load. |
|
|
744
829
|
| `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. |
|
|
745
|
-
| `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:
|
|
830
|
+
| `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. |
|
|
831
|
+
| `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). |
|
|
746
832
|
| `BRAIN_EMBED_MODEL` | `qwen3-embedding:0.6b` | model name | Override the embedding model (see table above). |
|
|
747
833
|
| `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. |
|
|
748
834
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "project-brain",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local-first MCP server that gives AI tools semantic memory of your codebase.",
|
|
6
6
|
"author": "jcsoftdev",
|
|
@@ -49,11 +49,11 @@
|
|
|
49
49
|
"zod": "^4.4.3"
|
|
50
50
|
},
|
|
51
51
|
"optionalDependencies": {
|
|
52
|
-
"project-brain-darwin-arm64": "0.
|
|
53
|
-
"project-brain-linux-x64": "0.
|
|
54
|
-
"project-brain-linux-arm64": "0.
|
|
55
|
-
"project-brain-windows-x64": "0.
|
|
56
|
-
"project-brain-windows-arm64": "0.
|
|
52
|
+
"project-brain-darwin-arm64": "0.45.1",
|
|
53
|
+
"project-brain-linux-x64": "0.45.1",
|
|
54
|
+
"project-brain-linux-arm64": "0.45.1",
|
|
55
|
+
"project-brain-windows-x64": "0.45.1",
|
|
56
|
+
"project-brain-windows-arm64": "0.45.1"
|
|
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
|
+
}
|