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
#!/usr/bin/env node
// clean-deploy-worktrees.mjs: reclaim the disk that abandoned deploy worktrees eat.
//
// The deploy runbook tells every agent to stage a clean worktree
// (`git worktree add --detach /workspaces/.deploy-wt HEAD`) and hardlink
// node_modules into it. Nothing ever told anyone to remove one. On 2026-08-04
// ten of them had accumulated from three days of deploys and filled a 126 GB
// disk to 100%, which does NOT fail loudly: the next `git worktree add` dies
// mid-checkout with "cannot create directory: No space left on device", leaving
// a half-written worktree, and the build that follows fails somewhere else
// entirely. Freeing the nine stale ones returned 18 GB.
//
// What counts as reclaimable, and why each condition is required:
//
// 1. It is a linked worktree, never the main one. The main worktree is where
// the work lives.
// 2. Its HEAD is detached. Deploy scratch worktrees are created with
// --detach; a worktree on a branch is somebody's feature work.
// 3. `git status --porcelain` is clean, ignoring untracked node_modules that
// the runbook hardlinks in. Uncommitted work is the one thing here that
// cannot be regenerated, so a single dirty file disqualifies a worktree
// no matter how old it is.
// 4. Its HEAD commit is an ancestor of the current branch, or unreachable
// from it. Either way nothing is lost: the commit is already in history,
// or it was never going to be pushed from a detached scratch tree.
//
// 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
//
// --min-age-hours (default 2) protects a worktree another agent is building in
// right now: a concurrent deploy stages its tree and starts a build that runs
// for ten minutes, and a sweep that ignored age would delete it mid-build.
import { execFileSync } from 'node:child_process';
import { statSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const APPLY = process.argv.includes('--apply');
const MIN_AGE_HOURS = (() => {
const i = process.argv.indexOf('--min-age-hours');
if (i === -1) return 2;
const n = Number(process.argv[i + 1]);
return Number.isFinite(n) && n >= 0 ? n : 2;
})();
function git(args, cwd = ROOT, timeoutMs = 120_000) {
return execFileSync('git', args, { cwd, encoding: 'utf8', timeout: timeoutMs, stdio: ['ignore', 'pipe', 'pipe'] });
}
/**
* Parse `git worktree list --porcelain` into one record per worktree.
* Pure given its input so the classifier below can be tested with fixtures.
*
* @param {string} porcelain
* @returns {{path:string, head:string|null, branch:string|null, detached:boolean, bare:boolean}[]}
*/
export function parseWorktrees(porcelain) {
const out = [];
let cur = null;
for (const line of porcelain.split('\n')) {
if (line.startsWith('worktree ')) {
if (cur) out.push(cur);
cur = { path: line.slice('worktree '.length), head: null, branch: null, detached: false, bare: false };
} else if (!cur) {
continue;
} else if (line.startsWith('HEAD ')) {
cur.head = line.slice('HEAD '.length);
} else if (line.startsWith('branch ')) {
cur.branch = line.slice('branch '.length);
} else if (line === 'detached') {
cur.detached = true;
} else if (line === 'bare') {
cur.bare = true;
}
}
if (cur) out.push(cur);
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
* the og:image and twitter:image meta into every pages/*.html on every run, and
* the sibling generators (build-examples-index, mirror-examples-index,
* build-atlas-index, build-mcp-catalog) rewrite the rest. A deploy worktree
* therefore comes out of a build permanently modified, which used to make every
* one of them unreclaimable forever: on 2026-09-09 three had accumulated
* holding 11.3 GB, dirty with nothing but this generated output, while the disk
* sat at 99%. Regenerating any of it costs one command, so it is not work.
*/
const REGENERATED_TRACKED = [
/^CHANGELOG\.md$/,
/^data\/examples\.json$/,
/^pages\/[^/]+\.html$/,
/^public\/atlas-index\.json$/,
/^public\/changelog(-recent)?\.(json|xml)$/,
/^public\/examples\.json$/,
/^public\/features\.json$/,
/^public\/locales\/localized-pages\.json$/,
/^public\/mcp-catalog\.json$/,
];
/**
* Untracked node_modules and build output are hardlinked or generated by the
* runbook itself, so they are not "work". Everything else counts as dirty.
*
* A tracked file counts as regenerable only when the build rewrites it in place
* (status ` M`, both index and worktree modifications). A deletion, rename or
* brand-new tracked file is never generator output, so those still disqualify
* the worktree no matter which path they touch.
*
* @param {string} porcelain output of `git status --porcelain`
* @returns {number} count of lines that represent real uncommitted work
*/
export function dirtyCount(porcelain) {
return porcelain
.split('\n')
.filter(Boolean)
.filter((l) => {
const status = l.slice(0, 2);
const file = l.slice(3);
if (status === '??') return !/(^|\/)(node_modules|dist|build)(\/|$)/.test(file);
if (!/^[ M]M$/.test(status)) return true;
return !REGENERATED_TRACKED.some((re) => re.test(file));
}).length;
}
/** Bytes on disk, best effort. A directory we cannot size is still reclaimable. */
function sizeBytes(dir) {
try {
const out = execFileSync('du', ['-sb', dir], { encoding: 'utf8', timeout: 90_000 });
return Number(out.split('\t')[0]) || 0;
} catch {
return 0;
}
}
function humanBytes(n) {
if (!n) return 'unknown size';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
let v = n;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
return `${v.toFixed(1)} ${units[i]}`;
}
function ageHours(dir) {
try {
return (Date.now() - statSync(dir).mtimeMs) / 3_600_000;
} catch {
return Infinity;
}
}
/** 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 });
const line = out.trim().split('\n').pop() || '';
const cols = line.split(/\s+/);
return { used: cols[2], avail: cols[3], pct: cols[4] };
} catch {
return null;
}
}
function run() {
const main = git(['rev-parse', '--show-toplevel']).trim();
const worktrees = parseWorktrees(git(['worktree', 'list', '--porcelain']));
const reclaimable = [];
const kept = [];
for (const wt of worktrees) {
const isMain = path.resolve(wt.path) === path.resolve(main);
if (isMain) continue;
if (!existsSync(wt.path)) {
// Registered but gone: prune reclaims the registry entry, no disk to free.
reclaimable.push({ ...wt, reason: 'registered but missing on disk', bytes: 0, stale: true });
continue;
}
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);
if (hours < MIN_AGE_HOURS) {
kept.push({ ...wt, why: `modified ${hours.toFixed(1)}h ago, under the ${MIN_AGE_HOURS}h floor (a build may be running)` });
continue;
}
let dirty = 0;
try {
dirty = dirtyCount(git(['status', '--porcelain'], wt.path, 180_000));
} catch (err) {
kept.push({ ...wt, why: `status unreadable (${String(err.message).slice(0, 60)}), refusing to guess` });
continue;
}
if (dirty > 0) {
kept.push({ ...wt, why: `${dirty} uncommitted file(s), which cannot be regenerated` });
continue;
}
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();
console.log(`git worktrees: ${worktrees.length} total, ${reclaimable.length} reclaimable, ${kept.length} kept`);
if (before) console.log(`disk: ${before.used} used, ${before.avail} available (${before.pct})`);
console.log('');
for (const k of kept) console.log(` KEEP ${k.path}\n ${k.why}`);
if (kept.length) console.log('');
let totalBytes = 0;
for (const r of reclaimable) {
totalBytes += r.bytes;
console.log(` RECLAIM ${r.path} (${humanBytes(r.bytes)})\n ${r.reason}`);
}
if (!reclaimable.length) {
console.log('Nothing to reclaim.');
process.exit(0);
}
console.log(`\nReclaimable: ${humanBytes(totalBytes)} across ${reclaimable.length} worktree(s).`);
if (!APPLY) {
console.log('Plan only. Re-run with --apply to remove them.');
process.exit(0);
}
let removed = 0;
for (const r of reclaimable) {
try {
// --force because a hardlinked node_modules makes git consider the tree
// "not clean enough" to remove even when every tracked file matches.
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)}`);
}
}
try {
git(['worktree', 'prune']);
} catch {
// A prune failure leaves stale registry entries only; the disk is already back.
}
const after = diskFree();
console.log(`\nRemoved ${removed}/${reclaimable.length} worktree(s).`);
if (after) console.log(`disk now: ${after.used} used, ${after.avail} available (${after.pct})`);
}
// Importing this file must not delete anything: the tests import parseWorktrees
// and dirtyCount, and a top-level sweep would run against the real disk on
// import. Only a direct invocation sweeps.
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
run();
}