Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(agents): bring the subagents back in line with the repo and reclaim finished subagent worktrees
nirholase67935efe241
diff --git a/.claude/agents/completionist.md b/.claude/agents/completionist.mdindex 5584eabbe..a64e594bf 100644--- a/.claude/agents/completionist.md+++ b/.claude/agents/completionist.md@@ -23,7 +23,9 @@ Audit every changed file for:Verification you can run cheaply, and should. Run these before reading anything by hand; they turn categories 1, 2, 7, and 8 into a mechanical answer:- `npm run check:rules -- --paths <changed files>` catches em-dashes, TODOs, not-implemented throws, commented-out code, and sample-data arrays in the added lines. Always scope with `--paths`: concurrent agents share this worktree, so an unscoped run reports their in-flight work as if it were this change.-- `npm run check:claude` confirms CLAUDE.md and the agent definitions have not drifted from the repo.+- `npm run check:claude` confirms CLAUDE.md and the agent definitions have not drifted from the repo. Run it whenever the change touched CLAUDE.md, `.claude/agents/`, `package.json` scripts, or a path either of them names.+- `npm run audit:docs` when the change added, moved, or deleted a doc, page, script, or package: it catches dead links, routes that match nothing, and commands naming a script that no longer exists.+- `npx vitest run <test files covering the changed modules>` for a fast signal on the code you are judging; a full `npm test` is the implementer's job, not yours.- `git diff` on the changed paths, for everything a regex cannot judge.If the change touched a page, note whether `npm run check:pages` would still pass.diff --git a/.claude/agents/deploy-preflight.md b/.claude/agents/deploy-preflight.mdindex 88f7639f0..78e707794 100644--- a/.claude/agents/deploy-preflight.md+++ b/.claude/agents/deploy-preflight.md@@ -1,23 +1,29 @@---name: deploy-preflight-description: Verifies a three.ws production deploy is safe to run BEFORE gcloud builds submit. Checks the load-bearing build order, worktree artifacts, service-account pins, and changelog wiring. Use before any deploy or when a deploy failed mid-build.+description: Verifies a three.ws production deploy is safe to run BEFORE gcloud builds submit. Checks disk, the deploy worktree and its artifacts, the load-bearing build order, the submit gates, service-account pins, and changelog wiring. Use before any deploy or when a deploy failed mid-build.tools: Bash, Read, Grep, Glob---You are the deploy preflight for three.ws (Cloud Run, project aerial-vehicle-466722-p5, region us-central1). You do NOT deploy; deploys are owner-gated. You verify everything so the ship is one command, and you output a pass/fail checklist.+The "Deploy runbook" section of CLAUDE.md is the procedure. You check that it is being followed, and you never restate a chain from memory: read it from `package.json` (`node -e 'console.log(require("./package.json").scripts["build:gcp"])'`), because the chains change and a remembered order is how deploys broke before.+Check, in order:-1. **Build order encoded, not hand-run.** The deploy must use `npm run build:gcp` (frontend vite build first, then UMD lib, `publish:lib`, `build:info`, `check:dist`, `check:pages`). Flag any plan that runs `build:vercel` as the frontend build: it skips the static HTML pages and `check:dist` will fail.+1. **Disk.** Run `df -h .` and `npm run clean:worktrees` (plan only). A disk near full fails `git worktree add` mid-checkout with an error that looks like a different bug. If the plan lists reclaimable trees and free space is under 20 GB, flag it and give the `--apply` command. Never pass `--apply` yourself.++2. **Deploy worktree staged by the script, not by hand.** The worktree must come from `npm run prep:worktree -- --apply` (add `--path <dir>` when another agent owns the default). Verify in the worktree that every build-critical artifact in the `ARTIFACTS` list of `scripts/prepare-deploy-worktree.mjs` exists (read the list; do not assume it), and that BOTH `.env` and `.env.local` are present. A missing `.env.local` means `db:check` cannot read `DATABASE_URL` and the submit refuses. Confirm the worktree HEAD is the commit the owner intends to ship (`git -C <path> log -1 --oneline`).++3. **Build order encoded, not hand-run.** The deploy must run `npm run build:gcp` exactly. Flag any plan that hand-runs its steps, reorders them, or uses `build:vercel` as the frontend build (it skips the static HTML pages, so `check:dist` fails). If `package.json` has `version` set to something absent from `data/agent-3d-releases.json`, `publish:lib` will fail: report that `npm run release:lib` is needed first.-2. **Clean worktree with all three hardlinked artifacts.** A deploy worktree needs `node_modules`, `chat/node_modules`, AND `character-studio/build` hardlinked (`cp -al`, same filesystem) plus `.env` copied. Missing `chat/node_modules` fails with `Cannot find package '@sveltejs/vite-plugin-svelte'`; missing `character-studio/build` OOMs (exit 144) on the avatar-studio rebuild. Verify all three exist in the worktree before passing.+4. **Submit gates.** The submit must be `npm run deploy:gcp:submit`, never a bare `gcloud builds submit`. Run its cheap gates yourself from the worktree and report each: `npm run db:check` (exit 4 means pending migrations; report `npm run db:status` output, never run `db:migrate`), `npm run check:gcloudignore`, `npm run audit:deploy`, `npm run check:api-imports`.-3. **Service accounts pinned.** Every cloudbuild config involved must pin `serviceAccount: .../three-ws-build@...` (the default compute SA was deleted). Grep the relevant `cloudbuild.yaml` files. Manual submits with `$SHORT_SHA` image tags need `--substitutions=SHORT_SHA=manual$(date +%s)`.+5. **Service accounts pinned.** Every cloudbuild config involved must pin `serviceAccount: .../three-ws-build@...` (the default compute SA was deleted). Grep `server/cloudbuild.yaml` and any worker `cloudbuild.yaml` in scope. Manual submits with `$SHORT_SHA` image tags need `--substitutions=SHORT_SHA=manual$(date +%s)`.-4. **Changelog entry present** if the diff is user-visible: `data/changelog.json` has an entry and `npm run build:pages` passes (it validates entries). Internal-only chores are exempt.+6. **Changelog entry present** if the shipped range is user-visible: `data/changelog.json` has an entry and `npm run build:pages` passes (it validates entries). Internal-only chores are exempt.-5. **Tests green.** Run `npm test` directly, never piped through `tail` (masks exit codes). A vitest failure gates the Playwright stage.+7. **Tests green at the shipped commit.** Run `npm test` inside the worktree, never piped through `tail` (masks exit codes). A vitest failure gates the Playwright stage. Report failures with their output; say whether each is in code the shipped range touched.-6. **Post-deploy verification plan stated.** Confirm the report ends with the two verification commands: `curl -s https://three.ws/api/version` (live SHA + revision) and `npm run smoke:prod`. The CDN purge must stay synchronous; flag any `--async` reintroduction.+8. **Post-deploy plan stated.** The plan must end with `npm run deploy:gcp:sync-crons`, `npm run deploy:gcp:purge-cdn` (synchronous; flag any `--async`), `curl -s https://three.ws/api/version` (live SHA + revision), `npm run smoke:prod`, and removing the worktree (`git worktree remove --force <path>`).-Output: a numbered pass/fail list with evidence per item, then a single verdict line: SAFE TO SHIP or BLOCKED (with the one thing blocking). No em-dashes anywhere.+Output: a numbered pass/fail list with evidence per item, then a single verdict line: SAFE TO SHIP or BLOCKED (with the one thing blocking and the command that clears it). No em-dashes anywhere.diff --git a/.claude/agents/x402-economy-triage.md b/.claude/agents/x402-economy-triage.mdindex 0ccd5fcae..db269d9e2 100644--- a/.claude/agents/x402-economy-triage.md+++ b/.claude/agents/x402-economy-triage.md@@ -18,18 +18,19 @@ You triage the three.ws x402 agent economy. Do not guess; run the checks in this2. **Capital dispersion (one-way drift into agent wallets).** Run `node scripts/audit-wallet-flows.mjs` to get the dispersion picture. The funding master IS the x402 payer (shared alias); SOL parked in per-agent wallets is stranded capital, not a leak. `scripts/gpu-capacity.mjs` is unrelated; do not touch it.-3. **Genuinely dry.** Never quote a remembered burn rate; measure it, because the figure has been wrong by 10x. Derive lamports-per-settle and the settle count from `x402_self_facilitator_log` over the window you care about, then multiply. If the payer balance is below a day of measured burn, report the exact balance, the derived rate, the resulting runway in hours, and that the owner must fund or throttle (env levers are documented in the memory file `x402-ring-scale-config`). Never top up per-agent wallets; that strands SOL and kills the rail.+3. **Genuinely dry.** Never quote a remembered burn rate; measure it, because the figure has been wrong by 10x. Derive lamports-per-settle and the settle count from `x402_self_facilitator_log` over the window you care about, then multiply. If the payer balance is below a day of measured burn, report the exact balance, the derived rate, the resulting runway in hours, and that the owner must fund or throttle (the env levers, governors and their defaults are in `docs/x402-ring-economy.md`; the payer-float row and its floor var are in the env table of `docs/ops/gcp-production.md`). Never top up per-agent wallets; that strands SOL and kills the rail.Also check affordability against the ring's own prices before calling it dry. A `settle_unaffordable` stall means `X402_PRICE_RING_SETTLE` exceeds the ring payer's float, which is a config fix (lower the price with `--update-env-vars`), not a funding problem.4. **gcloud auth dead.** If gcloud commands fail with `invalid_rapt`, that is the sperax.io Workspace reauth policy, not token expiry. There is no on-machine fallback: gather everything that does not need gcloud, then report that the owner must run `gcloud auth login` once.-5. **Solana RPC lane exhaustion (upstream of classes 1 and 3).** Probe every lane with a METERED method; `getHealth` is unmetered and answers ok on an exhausted endpoint. One `getBalance` POST per endpoint tells you whether the paid tier is dark. If it is, expect blocked reclaims, `broadcast_failed` settles and floor drift. Two tells that a `broadcast_failed` cluster is RPC-shaped rather than insufficient funds: it is amount-independent (group failures by payment amount, and a rail fault fails the smallest bucket as readily as the largest), and it comes with `Blockhash not found` or malformed-response parse errors. Details and the per-provider exhaustion signatures are in the memory file `solana-rpc-lane-exhaustion`.+5. **Solana RPC lane exhaustion (upstream of classes 1 and 3).** Probe every lane with a METERED method; `getHealth` is unmetered and answers ok on an exhausted endpoint. One `getBalance` POST per endpoint tells you whether the paid tier is dark. If it is, expect blocked reclaims, `broadcast_failed` settles and floor drift. Two tells that a `broadcast_failed` cluster is RPC-shaped rather than insufficient funds: it is amount-independent (group failures by payment amount, and a rail fault fails the smallest bucket as readily as the largest), and it comes with `Blockhash not found` or malformed-response parse errors. The one-sweep lane diagnosis, the per-provider capability table, and the repoint-a-lane recovery are in `docs/ops/solana-rpc-lanes.md`; follow its "Diagnose the whole tier in one sweep" section rather than hand-probing.## Ground truth sources-- `forge_creations` table (Neon, `DATABASE_URL` in `.env`) for per-generation status/errors.-- Cloud Run env is authoritative: `gcloud run services describe three-ws-api --region us-central1 --project aerial-vehicle-466722-p5 --format=yaml`. Never trust `vercel env pull`.+- `x402_self_facilitator_log` (Neon, `DATABASE_URL` in `.env.local`, never `.env`, which holds only the QA login) for per-settle outcomes, amounts and error strings. It is the ground truth for classes 1, 3 and 5.+- Cloud Run env is authoritative. Every credential there is a Secret Manager reference, so `describe` shows `valueFrom` instead of a value: read one with `node scripts/read-service-env.mjs '^NAME$' --raw`. Never trust `vercel env pull`.+- `docs/ops/production-log-triage.md` maps known log signatures to causes; check it before inventing a new failure class.## Report formatdiff --git a/CLAUDE.md b/CLAUDE.mdindex f59e0a4fb..0f6bdacfb 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -181,7 +181,7 @@ Fix every issue found. Then report complete.## Workflow-- Use TodoWrite for any task with 3+ steps. Mark items complete in real time.+- Track any task with 3+ steps in the harness's task list (TodoWrite or its equivalent; the tool name differs between harnesses). Mark items complete in real time.- Communication: short. State what you did, what's next. No trailing recaps.## Specialized agents in this repo@@ -192,14 +192,18 @@ Three subagents live in `.claude/agents/` and encode checklists you would otherw- **`deploy-preflight`** verifies a production deploy is safe BEFORE `gcloud builds submit`: build order, worktree artifacts, service-account pins, changelog wiring. Run it before any deploy, or when a deploy died mid-build. It does not deploy; deploys stay owner-gated.- **`x402-economy-triage`** diagnoses x402 outages against the known failure map. Run it before concluding "the wallets are dry", which is usually wrong: settle-floor starvation and capital dispersion look identical from the outside and have completely different fixes.-`.claude/workflows/docs-drift.js` is a workflow script for sweeping documentation drift across the repo.+**Autopilot** (`npm run autopilot:start`, `scripts/autopilot.mjs`, runbook `docs/ops/autopilot.md`) runs headless Claude Code sessions around the clock in its own worktree (`../.autopilot-wt`, branch `autopilot`): it works the `prompts/finish/` queue, writes new scouted orders into the `400` band, and sweeps production, then fast-forwards finished commits into local `main`. Its sessions are denied every owner-gated action. If you are hand-running an order, autopilot leaves it alone for 6 hours after you last touched it; `npm run autopilot:pause` frees the subscription for interactive work.++`.claude/workflows/` holds two workflow scripts: `docs-drift.js` sweeps documentation drift across the repo, and `docs-freshness.js` re-verifies the docs the freshness report marks stale.++**Maintaining these agents.** An agent definition is executed verbatim, exactly like this file, so it is held to the same standard and `npm run check:claude` enforces it: every `npm run` script and repo path it names must exist, it must never send the agent to a per-machine memory file (auto-memory under `~/.claude` is invisible to a fresh clone or a cloud session; put the knowledge in `docs/` and link it), and it must read changeable facts (build chains, artifact lists, env-var locations) from their source of truth instead of restating them. When the same multi-step diagnosis has been rebuilt from scratch twice, that is the signal to add an agent for it. Subagents launched with `isolation: "worktree"` leave a tree under `.claude/worktrees/`; `npm run clean:worktrees` reclaims each one once its branch is merged and it holds no uncommitted work.## Keeping this file trueThis file is the operating brain for every agent here, and agents execute what it says verbatim. A stale line in it does not read as stale, it reads as an instruction, and the cost is a wasted session per drift. Treat it as load-bearing code:- **`npm run check:rules` enforces the hard rules on the lines you changed** (`scripts/check-rules.mjs`). It reads added lines only, so your change is held to the rules while the legacy around it is left alone: em-dashes, TODO/FIXME comments, not-implemented throws, commented-out code, and `sampleFoo = [...]` fallback arrays all fail it. Because concurrent agents share this worktree, scope it to your own work: `npm run check:rules -- --paths <files you touched>`. It also reads brand-new untracked files, which a bare `git diff` cannot see. Generated output is excluded, including the compiled Marketplace Action under `satellites/glb-quality-gate/dist/`; its authored source remains scanned. It is also enforced mechanically at push time: the pre-push hook (installed into `.git/hooks` by `scripts/setup-git-hooks.mjs`, which `postinstall` runs on every `npm install`) runs it with `--base <remote sha> --head <local sha>` per pushed ref, so it judges exactly the commits leaving the machine and never the shared working tree. In that push-scoped mode it also lints every pushed commit's subject line against the "Commit messages" rules in the Git section, so a `chore: sync working tree` never lands again. Emergency bypass: `SKIP_PUSH_CHECKS=1 git push`. The hook deliberately runs ONLY this diff-scoped check and its sibling secrets scan (`scripts/check-secrets.mjs`, same push-scoped mode, so no credential material leaves the machine), never `npm run gate` or other worktree-state audits, because those would block a requested push on other agents' in-flight work.-- **`npm run check:claude` guards it** (`scripts/check-claude-md.mjs`, wired into `npm run gate`). It re-derives the checkable claims from their source of truth on every run: every npm script and repo path named here must exist, the cron count must match `vercel.json`, the deploy runbook must list the real `build:gcp` chain in the real order, the `db:migrate` warning must match what the script actually does, the README-coverage standard must hold, the remotes documented below must be the ones actually configured (a `git push <remote> main` instruction that does not resolve fails exactly when the owner asked to ship), and the em-dash ban must be honored by this file itself. Run it after editing this file.+- **`npm run check:claude` guards it** (`scripts/check-claude-md.mjs`, wired into `npm run gate`). It re-derives the checkable claims from their source of truth on every run: every npm script and repo path named here or in `.claude/agents/` must exist, the cron count must match `vercel.json`, the deploy runbook must list the real `build:gcp` chain in the real order, the `db:migrate` warning must match what the script actually does, the README-coverage standard must hold, the remotes documented below must be the ones actually configured (a `git push <remote> main` instruction that does not resolve fails exactly when the owner asked to ship), and the em-dash ban must be honored by this file itself. Run it after editing this file.- **If you change a load-bearing script, update this file in the same change.** Renaming a script, reordering `build:gcp`, adding a cron, or flipping a default is a documentation change too. The guard will catch most of it; do not make it do your job.- **Never add a claim here you have not verified.** Numbers, dates, and "X is automatic" statements are the ones that rot. If a claim cannot be checked mechanically, prefer wording that stays true (name the source of truth instead of quoting a number from it).@@ -291,7 +295,7 @@ The root `vercel.json` filename is legacy but the file is still load-bearing: thRemember stop-and-ask gate 2: production deploys need owner approval unless the owner's current instruction is itself the approval. Full runbook incl. LB/DNS/TLS/env/rollback/recovery: `docs/ops/gcp-production.md`. GPU workers deploy from their own `workers/<name>/cloudbuild.yaml`.-0. **Reclaim disk first: `npm run clean:worktrees` (add `--apply` to act).** Deploy worktrees are created by every deploy and removed by nobody. On 2026-08-04 ten had accumulated and filled the 126 GB disk to 100%, which fails in a way that reads like a different bug entirely: `git worktree add` dies mid-checkout with `No space left on device` and leaves a half-written tree behind. The script only reclaims a linked worktree that is detached, clean, and idle past `--min-age-hours` (default 2, so a concurrent agent's live build is never deleted); anything with uncommitted work is reported and kept.+0. **Reclaim disk first: `npm run clean:worktrees` (add `--apply` to act).** Deploy worktrees are created by every deploy and removed by nobody. On 2026-08-04 ten had accumulated and filled the 126 GB disk to 100%, which fails in a way that reads like a different bug entirely: `git worktree add` dies mid-checkout with `No space left on device` and leaves a half-written tree behind. The script only reclaims a linked worktree that is detached, clean, and idle past `--min-age-hours` (default 2, so a concurrent agent's live build is never deleted); anything with uncommitted work is reported and kept. It applies the same rules to the subagent worktrees under `.claude/worktrees/`, which additionally must have their `worktree-agent-*` branch already merged into HEAD; the merged branch is deleted with `git branch -d` (on 2026-10-08 nine of those held 31 GB).1. **Prepare a CLEAN worktree: `npm run prep:worktree -- --apply`.** That is the whole step; it encodes everything below, and running it beats staging by hand. Plan first with a bare `npm run prep:worktree` (writes nothing), `--path <dir>` to stage your own tree instead of colliding with a concurrent agent on the default `/workspaces/.deploy-wt`, `--force` to replace an existing tree (refused if it holds uncommitted work). What it does: `git worktree add --detach <path> HEAD`, then hardlinks every artifact in the `ARTIFACTS` list of `scripts/prepare-deploy-worktree.mjs` with `cp -al` on the same filesystem (not just the first). Three of them are build-critical, `node_modules`, `chat/node_modules` and `character-studio/build`; the optional ones (`walk-sdk/dist`, `multiplayer/node_modules`, `animation-sources`) are what let the worktree also run the repo's own test suite, so a pre-ship `npm test` can be taken at the exact commit being shipped instead of in the shared tree. It then copies BOTH `.env` and `.env.local`. Omitting either nested one kills the build minutes in: an OOM exit 144 on the avatar-studio rebuild, or `Cannot find package '@sveltejs/vite-plugin-svelte'` on the chat build. A nested artifact that is missing from the source tree is BUILT first (`deps:chat`, `build:avatar-studio`) rather than skipped, which is the failure a hand-run `cp -al` produces on a machine that has never deployed. `.env.local` is the one that carries `DATABASE_URL`, and without it step 3's migration gate cannot read the schema state and refuses to submit. **Remove it when the deploy lands** (`git worktree remove --force <path>`); that is what step 0 exists to clean up after. See `docs/ops/gcp-production.md`.2. **Build: `npm run build:gcp`.** ORDER IS LOAD-BEARING and `build:gcp` already encodes it. Never hand-run the steps in a different order. The full chain, in order:diff --git a/scripts/check-claude-md.mjs b/scripts/check-claude-md.mjsindex 2537dcf95..9eedca0e8 100644--- a/scripts/check-claude-md.mjs+++ b/scripts/check-claude-md.mjs@@ -66,17 +66,23 @@ const artifactPaths = new Set([// pointing at the main checkout, so this never resolves there.'.git/hooks',]);-const candidates = new Set();-for (const m of md.matchAll(/`([^`\n]+)`/g)) candidates.add(m[1]);-for (const m of md.matchAll(/\]\(([^)\s]+)\)/g)) candidates.add(m[1]);-for (const raw of [...candidates].sort()) {- if (!raw.includes('/')) continue;- if (!/^[A-Za-z0-9_./-]+$/.test(raw)) continue; // placeholders, globs, braces, spaces, @scopes- if (raw.startsWith('/') || raw.startsWith('-') || raw.includes('://')) continue; // routes, flags, URLs- if (raw.startsWith('three.ws/') || raw.startsWith('pump.fun/')) continue; // domains in prose- if (artifactPaths.has(raw)) continue;- if (!existsSync(path.join(root, raw))) failures.push(`path \`${raw}\` is referenced but does not exist`);+/** Repo paths a markdown body names that do not exist on disk. */+function missingPaths(body) {+ const candidates = new Set();+ for (const m of body.matchAll(/`([^`\n]+)`/g)) candidates.add(m[1]);+ for (const m of body.matchAll(/\]\(([^)\s]+)\)/g)) candidates.add(m[1]);+ const missing = [];+ for (const raw of [...candidates].sort()) {+ if (!raw.includes('/')) continue;+ if (!/^[A-Za-z0-9_./-]+$/.test(raw)) continue; // placeholders, globs, braces, spaces, @scopes+ if (raw.startsWith('/') || raw.startsWith('-') || raw.includes('://')) continue; // routes, flags, URLs+ if (raw.startsWith('three.ws/') || raw.startsWith('pump.fun/')) continue; // domains in prose+ if (artifactPaths.has(raw)) continue;+ if (!existsSync(path.join(root, raw))) missing.push(raw);+ }+ return missing;}+for (const raw of missingPaths(md)) failures.push(`path \`${raw}\` is referenced but does not exist`);// 3. Typography: the ban applies to the file that declares it. Only the lines// that name the banned characters may contain them.@@ -258,7 +264,8 @@ if (existsSync(cronHandler)) {// 5. The subagent definitions in .claude/agents/ are operating rules too: an// agent executes them verbatim the same way it executes this file. Hold them-// to the same two mechanical standards (real scripts, banned typography).+// to the same mechanical standards: real scripts, real paths, banned+// typography, and no dependence on state that lives on one machine only.const agentsDir = path.join(root, '.claude/agents');if (existsSync(agentsDir)) {const { readdirSync: readAgents } = await import('node:fs');@@ -270,6 +277,20 @@ if (existsSync(agentsDir)) {for (const m of body.matchAll(/npm run ([a-z0-9:._-]+)/g)) {if (!scripts[m[1]]) failures.push(`.claude/agents/${file} tells the agent to run \`npm run ${m[1]}\`, which does not exist`);}+ for (const raw of missingPaths(body)) {+ failures.push(`.claude/agents/${file} points the agent at \`${raw}\`, which does not exist`);+ }+ // Auto-memory lives under ~/.claude on one machine and is invisible to a+ // fresh clone, a cloud session, or another developer. An agent told to+ // read "the memory file X" finds nothing and guesses (2026-10-08: the+ // x402 triage agent cited two that existed nowhere). Point at docs/.+ if (/memory file `/.test(body)) {+ failures.push(`.claude/agents/${file} cites a per-machine memory file; move that knowledge into docs/ and link it`);+ }+ // DATABASE_URL lives in .env.local; .env holds only the QA login.+ if (/`DATABASE_URL` in `\.env`/.test(body)) {+ failures.push(`.claude/agents/${file} says DATABASE_URL is in .env; it is in .env.local`);+ }}}diff --git a/scripts/clean-deploy-worktrees.mjs b/scripts/clean-deploy-worktrees.mjsindex 97c48def0..7cabcc59b 100644--- a/scripts/clean-deploy-worktrees.mjs+++ b/scripts/clean-deploy-worktrees.mjs@@ -27,6 +27,16 @@// Everything it removes is regenerable in one command, which is what makes this// safe to run unattended. Anything it cannot prove safe, it reports and skips.//+// Subagent worktrees are the second source of the same leak. Every Agent call+// made with `isolation: "worktree"` leaves `.claude/worktrees/agent-<id>` on a+// `worktree-agent-<id>` branch, and nothing removes those either: on 2026-10-08+// twenty-one of them held 32 GB. They sit on a branch, so condition 2 alone+// would keep them forever. A worktree on a `worktree-agent-*` branch is+// reclaimed under conditions 1, 3 and the age floor, plus one more that stands+// in for 2: the branch tip must already be an ancestor of the main worktree's+// HEAD, so every commit the subagent made is in history. The branch is then+// deleted with `git branch -d`, which git itself refuses for unmerged work.+//// node scripts/clean-deploy-worktrees.mjs plan only, writes nothing// node scripts/clean-deploy-worktrees.mjs --apply remove the reclaimable ones// node scripts/clean-deploy-worktrees.mjs --apply --min-age-hours 6@@ -84,6 +94,16 @@ export function parseWorktrees(porcelain) {return out;}+/**+ * True for the branch the harness creates for an isolated subagent worktree.+ * Anything else on a branch is somebody's feature work and is never touched.+ *+ * @param {string|null} branch full ref from `git worktree list --porcelain`+ */+export function isAgentWorktreeBranch(branch) {+ return typeof branch === 'string' && /^refs\/heads\/worktree-agent-[A-Za-z0-9]+$/.test(branch);+}+/*** Tracked files the build rewrites in place. `npm run build:pages`* (scripts/build-page-index.mjs) regenerates these index/feed JSONs and injects@@ -162,6 +182,17 @@ function ageHours(dir) {}}+/** Whether every commit at `head` is already reachable from the main worktree's HEAD. */+function isMerged(head, main) {+ if (!head) return false;+ try {+ git(['merge-base', '--is-ancestor', head, 'HEAD'], main);+ return true;+ } catch {+ return false;+ }+}+function diskFree() {try {const out = execFileSync('df', ['-h', ROOT], { encoding: 'utf8', timeout: 30_000 });@@ -189,8 +220,13 @@ for (const wt of worktrees) {reclaimable.push({ ...wt, reason: 'registered but missing on disk', bytes: 0, stale: true });continue;}- if (!wt.detached) {- kept.push({ ...wt, why: `on branch ${wt.branch || '(unknown)'}, not a deploy scratch tree` });+ const agentTree = !wt.detached && isAgentWorktreeBranch(wt.branch);+ if (!wt.detached && !agentTree) {+ kept.push({ ...wt, why: `on branch ${wt.branch || '(unknown)'}, not a deploy or subagent scratch tree` });+ continue;+ }+ if (agentTree && !isMerged(wt.head, main)) {+ kept.push({ ...wt, why: `subagent branch ${wt.branch.replace('refs/heads/', '')} holds commits not yet in HEAD` });continue;}const hours = ageHours(wt.path);@@ -209,7 +245,8 @@ for (const wt of worktrees) {kept.push({ ...wt, why: `${dirty} uncommitted file(s), which cannot be regenerated` });continue;}- reclaimable.push({ ...wt, reason: `detached at ${(wt.head || '').slice(0, 9)}, clean, idle ${hours.toFixed(0)}h`, bytes: sizeBytes(wt.path) });+ const where = agentTree ? `subagent branch merged at ${(wt.head || '').slice(0, 9)}` : `detached at ${(wt.head || '').slice(0, 9)}`;+ reclaimable.push({ ...wt, agentTree, reason: `${where}, clean, idle ${hours.toFixed(0)}h`, bytes: sizeBytes(wt.path) });}const before = diskFree();@@ -246,6 +283,16 @@ for (const r of reclaimable) {git(['worktree', 'remove', '--force', r.path], ROOT, 600_000);removed++;console.log(`removed ${r.path}`);+ if (r.agentTree) {+ // -d, never -D: git re-checks the merge and refuses if anything is unmerged.+ const name = r.branch.replace('refs/heads/', '');+ try {+ git(['branch', '-d', name]);+ console.log(`deleted merged branch ${name}`);+ } catch (err) {+ console.error(`kept branch ${name}: ${String(err.message).slice(0, 120)}`);+ }+ }} catch (err) {console.error(`FAILED to remove ${r.path}: ${String(err.message).slice(0, 120)}`);}diff --git a/tests/clean-deploy-worktrees.test.js b/tests/clean-deploy-worktrees.test.jsindex 08a2030d5..dda901ec4 100644--- a/tests/clean-deploy-worktrees.test.js+++ b/tests/clean-deploy-worktrees.test.js@@ -8,7 +8,7 @@// worktree that cannot be regenerated.import { describe, it, expect } from 'vitest';-import { parseWorktrees, dirtyCount } from '../scripts/clean-deploy-worktrees.mjs';+import { parseWorktrees, dirtyCount, isAgentWorktreeBranch } from '../scripts/clean-deploy-worktrees.mjs';describe('parseWorktrees', () => {it('separates the main worktree from detached deploy scratch trees', () => {@@ -115,3 +115,17 @@ describe('dirtyCount', () => {expect(dirtyCount('')).toBe(0);});});++describe('isAgentWorktreeBranch', () => {+ it('recognizes the branch an isolated subagent worktree is created on', () => {+ expect(isAgentWorktreeBranch('refs/heads/worktree-agent-a06be27a4734bc811')).toBe(true);+ });++ it('never treats feature work as a subagent scratch tree', () => {+ expect(isAgentWorktreeBranch('refs/heads/main')).toBe(false);+ expect(isAgentWorktreeBranch('refs/heads/pr-landing')).toBe(false);+ expect(isAgentWorktreeBranch('refs/heads/codex/i18n-lint')).toBe(false);+ expect(isAgentWorktreeBranch('refs/heads/worktree-agent-x/nested')).toBe(false);+ expect(isAgentWorktreeBranch(null)).toBe(false);+ });+});