project-brain 0.41.2 → 0.43.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
@@ -353,6 +353,26 @@ project-brain setup --none
353
353
 
354
354
  Run `project-brain setup --with=nope` to print the list of valid ids.
355
355
 
356
+ #### Worktree lifecycle
357
+
358
+ ```bash
359
+ project-brain worktree create <name> [--base <ref>] # .claude/worktrees/<name>, branch worktree/<name>, own brain
360
+ project-brain worktree finish [<name|path>] [--yes] # dry run unless --yes
361
+ project-brain worktree sweep [--yes] [--branches] # finish every worktree that qualifies
362
+ ```
363
+
364
+ 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
+
366
+ `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.
367
+
368
+ #### Disk maintenance
369
+
370
+ LanceDB keeps every superseded version and soft-deleted row until something removes them, so a busy index can grow to several times its live size (one went from 1.16 GB to 0.16 GB when compacted). `setup` adds a default-on `SessionEnd` hook (`hooks:index-maintenance`) that runs `project-brain maintain --quiet --background`: it returns at once and a detached process does the work, so it never delays the host. That run drops dead worktree indexes (as `worktree prune` does), then compacts the largest idle indexes, and prints `project-brain: reclaimed X GB from N index(es)` only when it freed something. Untick it in `setup`, or use `--without=hooks:index-maintenance`, to opt out.
371
+
372
+ An index is compacted only when all of these hold: it is at least 256 MB, it was not compacted in the last 24 h, nothing was committed to it in the last 10 minutes, no process has a file open inside it (`lsof`; an unreadable check counts as in use), and it is not the current project's. A run compacts at most 2 indexes, largest first, and stops starting new ones after 60 s. Versions younger than 30 minutes survive. Tune with `BRAIN_AUTO_COMPACT_MIN_MB`, `BRAIN_AUTO_COMPACT_INTERVAL_HOURS`, `BRAIN_AUTO_COMPACT_QUIET_MINUTES`, `BRAIN_AUTO_COMPACT_MAX_TABLES`, `BRAIN_AUTO_COMPACT_BUDGET_SECONDS` and `BRAIN_AUTO_COMPACT_RETENTION_MINUTES`.
373
+
374
+ `project-brain compact [--project <id>]` still reclaims one index on demand. It now refuses, and exits 1, while another process has the index open or the check cannot be made; `--force` overrides that. `compact --help` prints usage and changes nothing.
375
+
356
376
  #### Worktrees start from the main checkout's index
357
377
 
358
378
  `init` inside a linked git worktree copies the main checkout's vectors, manifest and graph before indexing, then syncs only what differs. Every path those artefacts store is repository-relative, so one checkout's index describes another equally well, and sync re-hashes each file anyway — a stale or wrong-branch base costs a few extra embeddings, never a wrong index.
@@ -400,9 +420,9 @@ It ships **unchecked**: it changes what every commit and PR says in every repo o
400
420
 
401
421
  #### chrome-devtools autoConnect
402
422
 
403
- If a detected host runs the [chrome-devtools MCP server](https://github.com/ChromeDevTools/chrome-devtools-mcp) without `--autoConnect`, setup offers to add it (`config:chrome-autoconnect`). Without the flag those browser tools launch a throwaway, logged-out Chrome profile; with it they drive the Chrome you are already signed into, which is the only way to reach a flow behind a login.
423
+ The default is **not** your Chrome: the chrome-devtools tools drive a headless browser (see the shared server below). If a detected host runs the [chrome-devtools MCP server](https://github.com/ChromeDevTools/chrome-devtools-mcp) without `--autoConnect`, setup offers to add it (`config:chrome-autoconnect`) as an explicit opt-in. Without the flag those browser tools launch their own browser; with it they drive the Chrome you are already signed into. Chrome shows an authorization modal on every (re)connection of such a client, by design and with no way to remember the answer ([Chrome for Developers](https://developer.chrome.com/blog/chrome-devtools-mcp-debug-your-browser-session)), so expect to approve it each time the server reconnects. The two modes are exclusive: adding `--autoConnect` drops `--headless` and setup's own `--userDataDir` from the same command, and removing it puts them back.
404
424
 
405
- It is the one unit that ships **unchecked**, on purpose. Attaching to your own browser is full control of it, and Chrome says so on the toggle the flag depends on: it "allows external apps to request full control of this browser. This includes read access to your saved data, cookies and site data, and the ability to navigate to any URL."
425
+ It ships **unchecked**, on purpose. Attaching to your own browser is full control of it, and Chrome says so on the toggle the flag depends on: it "allows external apps to request full control of this browser. This includes read access to your saved data, cookies and site data, and the ability to navigate to any URL."
406
426
 
407
427
  The flag is only half of it — Chrome refuses the connection until you open `chrome://inspect/#remote-debugging` and turn on "Allow remote debugging for this browser instance" yourself. Setup never flips that toggle; it prints the step after writing the flag. Entries already wired another way (`--browserUrl`, `--wsEndpoint`) or explicitly opted out (`--no-auto-connect`) are left untouched.
408
428
 
@@ -418,11 +438,21 @@ It is **unchecked** by default, and it is the only unit that installs an OS serv
418
438
 
419
439
  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.
420
440
 
421
- The command moves across **verbatim**, so whatever flags you already answered for — `--autoConnect` included — carry over, and this unit decides none of them. Removing it restores each entry from a record written at install rather than reconstructing a command.
441
+ The command moves across **verbatim**, so whatever flags you already answered for — `--autoConnect` included — carry over. The one thing setup adds is the default: a command that chose no browser (no `--autoConnect`, `--browserUrl`, `--wsEndpoint`, `--isolated` or `--userDataDir`) is shared with `--headless --userDataDir=~/.project-brain/chrome-profile`, so every session drives one shared headless browser that the server launches itself on a dedicated, persistent profile: no CDP toggle, no approval modal, and logins that survive restarts. Setup creates that directory (mode 0700) and, while it holds no Chrome profile yet, points you to `project-brain browser login`. That command opens your real Chrome, headed, on the profile with no remote-debugging or automation flags (Google refuses sign-in in automated browsers), and waits until you close it. Chrome allows one process per profile, so if the shared server (or any Chrome) holds the profile it stops and tells you to stop that first; it never kills anything. Restart the shared server afterwards so it reuses the saved login. For a separate session on the same URL (own cookies and storage), the agent passes `isolatedContext` to `new_page` inside that browser instead of starting another one. Removing the unit restores each entry from a record written at install rather than reconstructing a command.
442
+
443
+ An existing install keeps its command until you change it; setup never rewrites it behind your back. If its service still runs `--autoConnect`, `project-brain setup` prints a one-line notice. To switch it to the headless default, untick "chrome-devtools autoConnect" (or `project-brain setup --without=config:chrome-autoconnect`): setup rewrites the service command and reloads the service itself. To restart it by hand, the command is the one setup prints at install (`launchctl kickstart -k gui/$(id -u)/dev.projectbrain.chrome-devtools-shared` on macOS, `systemctl --user restart dev.projectbrain.chrome-devtools-shared` on Linux). Only the service this unit installed is rewritten; a bridge you set up yourself is never touched.
444
+
445
+ The `hooks:browser-route` unit (on by default, Claude Code only, opt out by unticking it) adds a `PreToolUse` hook on the `mcp__chrome-devtools__*` tools. The first time a session calls one, it adds one line saying: share the headless browser on its dedicated profile (sign in once with `project-brain browser login`), use `isolatedContext` for a separate session on the same URL, and use your real Chrome only when you ask. It prints nothing otherwise and never blocks the call.
422
446
 
423
447
  If a host already points at a bridge you set up yourself, under any service name, setup reads that service's command instead. autoConnect then shows `current` when the flag is in that command (`foreign` when it isn't; edit it there), and this unit shows `foreign`: the service is yours, and setup never installs over it or removes it. A service counts only when some host entry's URL uses its `--port`.
424
448
 
425
- Two limits worth knowing. Sharing the server shares its state: one page list visible to every session, one profile, and process-level flags (`--headless`, `--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.
449
+ ##### `project-brain browser`
450
+
451
+ - `browser status [--json]` is read-only and exits 0 whatever it could not determine. It reports the running server's mode (`headless-profile`, `autoConnect`, or `foreign`, read from its live command line), the profile path and whether Chrome has initialised it (a sign-in itself cannot be proven from disk), the server's and its browser's memory, its age, the open page count through the bridge (`unavailable` when the bridge does not answer), and whether it is over budget.
452
+ - **Memory budget.** Past `BRAIN_CHROME_SERVER_MAX_MB` (default 1024) the server is reported as over budget, in `browser status` and in the one-time hook line, together with the restart command of the service this tool installed. Nothing is restarted automatically: every open session holds a persistent connection to the bridge and the bridge exposes no activity time, so there is no reliable idle signal, and a restart on a guess would cut a session's browser. Growth in the headless-profile mode has not been measured; the 1.42 GB figure is from an autoConnect server after about four days.
453
+ - `browser prune-pages --older-than <90s|30m|2h|1d> [--yes]` lists, and with `--yes` closes, pages the shared browser has held longer than that. `list_pages` reports no page age, owner or isolatedContext, so "age" is how long this tool has seen the page (recorded between runs; a lower bound), and the selected and newest pages are never listed. It is a dry run without `--yes`, and it refuses on a server that is not the headless-profile one, because there the pages can be your own tabs.
454
+
455
+ 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.
426
456
 
427
457
  #### Model routing for sub-agents
428
458
 
@@ -456,6 +486,18 @@ Override the table in `~/.project-brain/model-routing.json`:
456
486
 
457
487
  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.
458
488
 
489
+ #### Coding rules guard
490
+
491
+ 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.
492
+
493
+ ```bash
494
+ project-brain setup --with=hooks:style-guard # already on in a plain `setup`
495
+ ```
496
+
497
+ **Which skills apply.** A table maps file extensions to skills (code files to `brain-style`; prose, data and config files to nothing). Only a file the table cannot classify, and only when a TypeSafe token exists, goes to Jev, which sees the file path alone and answers per skill whether it applies; without a token the hook stays silent for those files. The rules text is read from `~/.claude/skills/<skill>/SKILL.md`, so editing the installed skill changes what is injected; if the skill is not installed the hook says nothing.
498
+
499
+ **Opt out.** Deselect `hooks:style-guard` in `setup`.
500
+
459
501
  #### Architecture guard
460
502
 
461
503
  A `PreToolUse` hook on `Edit`, `Write` and `MultiEdit` that checks an edit against your architecture boundaries. It is selected by default in `setup` because it is local and warn-only out of the box: the setup unit installs the hook and seeds a **global default** at `~/.project-brain/architecture.json` (hexagonal/clean preset, `"mode": "warn"`), so every project is covered with no per-project step.
@@ -498,7 +540,7 @@ A `PreToolUse` hook on `Bash` that acts only on `git commit` (including `git -C
498
540
  project-brain setup --with=hooks:commit-check
499
541
  ```
500
542
 
501
- `setup` ticks it by default only when a token is already configured, since the diff (first 16,000 characters) is sent to `api.typesafe.ai`. Without a token, with an empty diff, or on any error or timeout, it does nothing. The default is a warning delivered as `additionalContext`; to make the review escalation block (exit `2`, reason on stderr), write `~/.project-brain/commit-check.json`:
543
+ `setup` ticks it by default only when a token is already configured, since the diff (first 16,000 characters) is sent to `api.typesafe.ai`. Without a token, with an empty diff, or on any error or timeout, the Jev part does nothing. Independently of Jev, it names the source files whose staged diff adds comment lines (the `brain-style` rule is zero comments in new code); that check is local, needs no token, and only warns. The default is a warning delivered as `additionalContext`; to make the review escalation block (exit `2`, reason on stderr), write `~/.project-brain/commit-check.json`:
502
544
 
503
545
  ```json
504
546
  { "mode": "block" }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "project-brain",
3
- "version": "0.41.2",
3
+ "version": "0.43.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",
@@ -49,11 +49,11 @@
49
49
  "zod": "^4.4.3"
50
50
  },
51
51
  "optionalDependencies": {
52
- "project-brain-darwin-arm64": "0.41.2",
53
- "project-brain-linux-x64": "0.41.2",
54
- "project-brain-linux-arm64": "0.41.2",
55
- "project-brain-windows-x64": "0.41.2",
56
- "project-brain-windows-arm64": "0.41.2"
52
+ "project-brain-darwin-arm64": "0.43.0",
53
+ "project-brain-linux-x64": "0.43.0",
54
+ "project-brain-linux-arm64": "0.43.0",
55
+ "project-brain-windows-x64": "0.43.0",
56
+ "project-brain-windows-arm64": "0.43.0"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@types/bun": "latest",
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  name: brain-style
3
- description: "Trigger: writing or editing code, adding a comment, docblock or header, reviewing a diff for readability, escribe el código, refactor this, clean this up. Keeps generated code declarative — the code carries the meaning, and a comment appears only where it says something the code cannot."
3
+ description: "Trigger: writing or editing code, adding a comment, docblock or header, reviewing a diff for readability or architecture, escribe el código, refactor this, clean this up, delegating code to a sub-agent. Keeps generated code architecture-first and declarative — the code carries the meaning, and the why lives in the commit message or the knowledge bundle, never in a comment."
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: jcsoftdev
7
- version: "1.0"
7
+ version: "1.1"
8
8
  generator: project-brain
9
9
  ---
10
10
 
@@ -17,7 +17,7 @@ metadata:
17
17
 
18
18
  ## Activation Contract
19
19
 
20
- Apply whenever code is written or edited: a new file, a patch, a refactor, a snippet in an answer.
20
+ Apply whenever code is written or edited: a new file, a patch, a refactor, a snippet in an answer. Apply it to a sub-agent's diff before accepting it.
21
21
 
22
22
  Do not apply when: the user dictated the comment or the code verbatim, the file is generated or vendored, or the comment is published API documentation that a doc generator turns into a reference page.
23
23
 
@@ -27,13 +27,40 @@ This rule outranks inherited style guidance — a house style read off surroundi
27
27
 
28
28
  One thing outranks it: the user asking, in the moment, for something else. Their instruction is the answer, not a conflict to resolve.
29
29
 
30
- Existing comments are not the target. Do not strip a file's docblocks as a side effect of editing three lines in it — that is a rewrite nobody asked for, and it buries the actual change in the diff.
30
+ Existing comments are not the target. Do not strip a file's docblocks as a side effect of editing three lines in it — that is a rewrite nobody asked for, and it buries the actual change in the diff. Pre-existing comments on untouched lines stay.
31
31
 
32
- ## The rule
32
+ ## Architecture first
33
33
 
34
- **Default: no comment.** A comment is a claim that the code failed to say something, and most of the time the honest fix is the code.
34
+ Never write code "as it comes out".
35
35
 
36
- Before writing one, try these, in order:
36
+ - Before writing, find how the repo already solves the same problem and follow it.
37
+ - Use the repo's own formatter, never another one.
38
+ - Second copy of anything: extract it. Reach for the existing helper or kit component before writing a new one.
39
+
40
+ ### Contracts, not magic strings
41
+
42
+ A code or state that crosses a boundary (API to client, service to service) is a typed enum or schema in the shared contract.
43
+
44
+ - The producer builds with the contract type; the consumer parses with the schema.
45
+ - Copy per code lives in an exhaustive map, so a new code without copy fails to compile.
46
+ - Parse external data with its schema. `as` only when the type system cannot express the fact.
47
+
48
+ ### Layers
49
+
50
+ | Layer | Owns | Never owns |
51
+ |---|---|---|
52
+ | Domain | Business rules, pure and tested | I/O, framework types |
53
+ | Adapter | Persistence | Business rules |
54
+ | Controller | Validate, orchestrate, translate | Business rules |
55
+ | UI component | Rendering | Rules, thresholds, conditional copy |
56
+
57
+ - Container–presentational: a component receives what to show; it does not decide.
58
+ - Mappers, thresholds and conditional copy are pure functions with tests, outside the component.
59
+ - Translate errors in one place per module. The same `catch` repeated per handler is the defect.
60
+
61
+ ## Zero comments
62
+
63
+ A comment is a claim that the code failed to say something, and the honest fix is the code. Add none. Try these, in order:
37
64
 
38
65
  | Instead of a comment | Do this |
39
66
  |---|---|
@@ -43,26 +70,30 @@ Before writing one, try these, in order:
43
70
  | `// this branch handles the empty case` | Make the branch read as the empty case: guard clause, early return |
44
71
  | `// args: name, retries, timeout` | Take a named object, or a type the reader can open |
45
72
  | `// returns null when not found` | Say it in the signature: `T \| null`, `Option<T>`, a typed result |
73
+ | `// must stay sorted, bisect depends on it` | A type or a named function that enforces it |
46
74
 
47
75
  If one of those works, the comment was a naming problem wearing a disguise.
48
76
 
49
- ## What earns a comment
77
+ ### Where the why goes
78
+
79
+ A reason the code cannot hold — a rejected alternative, an external constraint, a vendor quirk, a workaround pinned to a bug or version — does not go in the file.
80
+
81
+ - The commit message carries the why of this change.
82
+ - The knowledge bundle carries the lasting why: a constraint that must keep holding, a trap that already cost a debugging session. Use the `brain-okf` skill.
83
+
84
+ Banners, commented-out code (delete it), changelog lines, attribution, dates and ownerless `TODO`s never belong in the file either.
50
85
 
51
- Three things, all of them the *why* — never the *what*:
86
+ ### Check before every commit
52
87
 
53
- - **A reason the code cannot hold.** A rejected alternative and why it lost, an external constraint, a spec or vendor quirk that makes correct code look wrong.
54
- - **An invariant that breaks non-locally.** "This must stay sorted, `bisect` downstream depends on it." The reader cannot see the downstream from here.
55
- - **A workaround pinned to something external.** Name the bug, version, or ticket, so the next person can tell whether it is still needed.
88
+ ```sh
89
+ git diff --cached | rg '^\+\s*(//|/\*|\*\s|\{/\*)'
90
+ ```
56
91
 
57
- Write those in full sentences. They are for a reader a year out with no memory of this week.
92
+ The output must be empty.
58
93
 
59
- ## What never earns one
94
+ ## Delegating code
60
95
 
61
- - Restating the line below it.
62
- - Section banners (`// ---- helpers ----`) — that is a file asking to be split.
63
- - Commented-out code. Delete it; that is what version control is for.
64
- - Changelog, attribution, or a date. The log holds those, and it stays accurate.
65
- - A `TODO` with no owner and no condition. Either it blocks and belongs in an issue, or it does not and belongs nowhere.
96
+ Restate this whole rule in every sub-agent prompt that writes code, and review its diff against it before accepting. A sub-agent that was not told produces code as it comes out.
66
97
 
67
98
  ## Reporting back
68
99
 
@@ -4,7 +4,7 @@ description: "Trigger: before starting an isolated task, run this in a worktree,
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: jcsoftdev
7
- version: "1.0"
7
+ version: "1.1"
8
8
  generator: project-brain
9
9
  ---
10
10
 
@@ -66,11 +66,15 @@ worktree nobody indexed. The two halves drift apart and nothing errors.
66
66
  2. Decide isolation. Needed when the task changes code and something else must keep
67
67
  running on the current branch, or when sibling agents work in parallel. Not needed for
68
68
  a read-only task. Ask before creating one unless the user already said to.
69
- 3. Create it with the harness's own tool (`EnterWorktree`, or the `using-git-worktrees`
70
- skill). Never `git worktree add` by hand when a native tool exists — the harness
71
- cannot see or clean up what it did not create.
72
- 4. In the worktree: `project-brain init` then `project-brain sync`. Only now does the
73
- agent have a graph that matches its branch.
69
+ 3. Create it with `project-brain worktree create <name> [--base <ref>]`. It puts the
70
+ worktree at `<repo>/.claude/worktrees/<name>` on branch `worktree/<name>` (`--branch`
71
+ to choose another), refuses an existing path or branch, runs the same `init` as step 4
72
+ and prints the path plus the `port_acquire` pair. Keep worktrees inside `.claude/`: one
73
+ place to look, one place the sweep cleans. A harness-native tool (`EnterWorktree`) is
74
+ fine when the harness must own the worktree; `finish` and `sweep` handle those too.
75
+ 4. `worktree create` already ran `init` there. For a worktree made some other way, run
76
+ `project-brain init` then `project-brain sync` in it. Only then does the agent have a
77
+ graph that matches its branch.
74
78
  5. `port_acquire(project, worktree, technology)` with the pair from step 1, once per
75
79
  service the task boots. The lease is sticky, so re-running returns the same port.
76
80
  6. Delegate. The sub-agent starts with an empty context and never reads CLAUDE.md, so
@@ -78,12 +82,36 @@ worktree nobody indexed. The two halves drift apart and nothing errors.
78
82
  and the model-routing table if it will spawn its own sub-agents. A sub-agent has the
79
83
  `Agent` tool and can nest; it does NOT have `Workflow`, so deterministic
80
84
  orchestration stays with you.
81
- 7. Tear down. `project-brain setup` installs hooks that do this for you: `WorktreeRemove`
82
- reclaims the worktree's index, and mcp-port-registry's own hook releases its ports.
83
- Run `project-brain worktree prune` and `port_release` by hand only when you removed a
84
- worktree outside the harness, or when a non-interactive run skipped hooks entirely.
85
- Both sides reconcile against `git worktree list` on the next session start anyway,
86
- which is why neither trusts the removal event alone.
85
+ 7. Tear down when the work is finished: `project-brain worktree finish [<name|path>]` (dry
86
+ run) then `--yes`. See "Finishing a worktree" below. Release the leased ports with
87
+ `port_release`; mcp-port-registry's own hook usually does it, and both sides reconcile
88
+ against `git worktree list` on the next session start anyway.
89
+
90
+ ## Finishing a worktree
91
+
92
+ A worktree is finished when ALL of these hold:
93
+
94
+ - it is not the main checkout, and not on the default branch;
95
+ - its branch is merged into the default branch (or has no commits of its own and is more
96
+ than an hour old);
97
+ - its tree is clean: no modified, staged or untracked file. The one exception is a lone
98
+ untracked `node_modules` symlink, the known leftover of isolation worktrees;
99
+ - no process has it as its working directory, and your shell is not standing in it.
100
+
101
+ `finish` is a dry run that prints what would go, or the exact reason it is not finished.
102
+ With `--yes` it removes the `node_modules` symlink (the link, never its target), runs
103
+ `git worktree remove` and `git branch -d` (never `--force`, never `-D`), and drops the
104
+ worktree's index. Unmerged or dirty work is never removed.
105
+
106
+ `worktree sweep` applies the same rule to every linked worktree, removes only worktrees under
107
+ `.claude/worktrees`. Ones outside it (siblings, other tools') are listed as `[outside .claude]`
108
+ and removed only with `--include-outside`, or by `finish <path> --yes`, never moved. It also
109
+ lists merged local branches that have no worktree. `sweep --yes --branches` deletes those
110
+ with `git branch -d`.
111
+
112
+ `project-brain setup` installs a default-on `SessionEnd` hook that runs
113
+ `worktree sweep --yes --quiet`: when a session ends, leftovers from earlier finished work are
114
+ removed, silently unless something was removed. Untick `hooks:worktree-sweep` to opt out.
87
115
 
88
116
  ## Browsers are per session, not per worktree
89
117
 
@@ -97,16 +125,17 @@ Fill the browser role in this order, and record which tool filled it:
97
125
 
98
126
  | Tool | Reach for it when |
99
127
  |---|---|
100
- | `chrome-devtools` | The default. Isolated profile, headless, performance trace, network with headers and timing. |
101
- | `claude-in-chrome` | The flow needs the user's own signed-in session and the user said so. Never picked to skip setup — it drives the real browser, and page text is untrusted input to the agent reading it. |
128
+ | `chrome-devtools` | The default. A shared headless browser on a dedicated persistent profile (no approval modal; the owner signs in once with `project-brain browser login`), performance trace, network with headers and timing. Reuse it, open your own page, close it when done. For a separate session on the same URL (own cookies and storage), pass `isolatedContext` to `new_page` — not a new browser. |
129
+ | `claude-in-chrome`, or `chrome-devtools` attached with `--autoConnect` | The flow needs the user's own signed-in session and the user said so; `--autoConnect` makes Chrome show an approval modal on every reconnect. Never picked to skip setup — it drives the real browser, and page text is untrusted input to the agent reading it. |
102
130
  | `playwright` | Last, and only for what the other two cannot do. `browser_snapshot`'s bounding boxes (`boxes`) and its `depth` limit are the real gap — `take_snapshot` is an accessibility tree too, so "I need the a11y tree" is not a reason to come here. |
103
131
 
104
132
  Sharing one browser across worktrees is not automatic, because each session runs its own
105
133
  MCP server process. Where it is worth arranging, point those servers at a single Chrome
106
- (`--browserUrl`, or `--autoConnect` — `project-brain setup` offers to add that flag, and
107
- prints the `chrome://inspect` toggle it depends on) and give each worktree its own `isolatedContext`
108
- name on `new_page`: pages in different contexts share no cookies or storage, and every
109
- page-scoped tool routes by `pageId`. A worktree then costs a context, not a browser.
134
+ (`--browserUrl`, or the explicit opt-in `--autoConnect` — `project-brain setup` offers to add
135
+ that flag, and prints the `chrome://inspect` toggle it depends on) and give each worktree its
136
+ own `isolatedContext` name on `new_page`: pages in different contexts share no cookies or
137
+ storage, and every page-scoped tool routes by `pageId`. A worktree then costs a context, not
138
+ a browser.
110
139
 
111
140
  That shares the browser, not the server. Each session still attaches to it separately, and
112
141
  an attachment holds its CDP connection for the session's whole life while buffering what
@@ -115,7 +144,8 @@ Six sessions is six of those.
115
144
 
116
145
  To share the SERVER too, `project-brain setup` offers `service:chrome-shared-server`: one
117
146
  `chrome-devtools-mcp` behind an HTTP bridge, held open by a login service, with every host
118
- entry pointed at the URL instead of spawning its own. Sessions then cost a connection each.
147
+ entry pointed at the URL instead of spawning its own, headless on the dedicated profile unless
148
+ the command already chose its own browser (`--autoConnect`, `--userDataDir`, ...). Sessions then cost a connection each.
119
149
  Nothing bounds how large that one server grows, so it still wants restarting between long
120
150
  stretches of browser work — setup prints the command for your platform.
121
151
 
@@ -129,6 +159,8 @@ A CDP port is a port like any other. Lease it with `port_acquire` instead of ass
129
159
  - Never write durable knowledge expecting it to live in the worktree. `add_knowledge`
130
160
  from a worktree is routed to the BASE project on purpose: a worktree index is
131
161
  disposable and `worktree prune` will drop it.
162
+ - Never pass `--force` to `git worktree remove`, or `-D` to `git branch`, to get a stubborn
163
+ worktree out of the way. `finish` refusing is the answer: merge or commit first.
132
164
  - Never run `worktree prune` to fix a confusing result. It reclaims by asking git which
133
165
  worktrees are live, with no grace window, because a worktree index is re-derivable by
134
166
  one `sync`. That is safe for worktrees and wrong for projects — whole projects belong