The janitor: scheduled branch and folder cleanup¶
Contents: What it does · What it never does · Config · Install · Uninstall · Day to day · Threat model · Files
After a worker's pull request merges, its local branch and sometimes its worktree folder stay
behind. Agents may not delete them: the destructive-command guard blocks that, rightly. And
Windows keeps a worktree folder locked for minutes after claude stop (#94). The janitor does
this cleanup on a schedule, with no agent in the loop. It is
plugins/dev-env/janitor/janitor.ps1 (plugins/dev-env/janitor/janitor.ps1), one pwsh 7
script for both machines. The design and its decisions are in #153, the build in #350.
Remote branches are GitHub's job. The repository has "Automatically delete head branches" on, so GitHub deletes a pull request's branch when it merges. Branches merged before the setting was turned on take a one-off owner command. The janitor never pushes and never deletes a remote branch.
What it does¶
A pass runs every cadence_minutes (5 by default), under a lock: a second pass at the same time
exits 0 and does nothing. Each pass:
- Checks the pins. The SHA-256 hashes of the config and of the installed copy are in the
scheduler definition. On a mismatch the pass refuses, logs it in
pass.logand exits. - Updates each configured repository:
git fetch --prune origin, thengit merge --ff-only origin/<default>when the default branch is checked out, the tree is clean and no merge or rebase is in progress. A refused fast-forward is logged and the pass goes on: every deletion is checked againstorigin/<default>anyway. -
Prunes gone branches. It deletes with
git branch -devery local branch that:- has a gone upstream;
- is merged into
origin/<default>; - matches the repository's
branch_pattern; - is checked out in no worktree.
Everything else is kept and listed by
-Status: a merged gone branch outside the pattern (the owner's owntry/notes), an unmerged one (a pull request closed without merging), and one without an upstream. -
Carries out the queue. A coordinator writes one file per step,
queue/<id>.json(schema (plugins/dev-env/janitor/queue-entry.schema.json), #351). Three kinds:Kind Fields Done when delete_branchrepo(a config key),branch; optionallyprandhead, togetherthe branch matches branch_pattern, is not the default branch, is checked out in no worktree, is merged intoorigin/<default>; thengit branch -d. Withprandhead(the merged pull request and its head commit, which the coordinator read from GitHub, #596) the merge check is replaced by that proof, which holds for a squash merge too: the branch is deleted while its tip ishead, bygit update-refwithheadas the old value, and refused when its tip differs. An entry without them gets the merge checkremove_folderfolder(a leaf name)base_dir/<folder>exists, is a folder and not a link, its name starts with<repo key>-of a configured repository, it is no registered worktree and holds no checkout of a configured repository, any.gitin it is the leftover pointer of a worktree of that repository that git no longer knows (never a clone, never another repository's worktree), and no active session (claude agents --json) works in it or below it; then it is deleted, a link inside removed as a linkvault_syncnone: any field beyond the common ones is refusedthe token sync ran: systemctl --user start ops-vault-sync.service, the unitvault.sh timerinstalls; on Windows the scheduled taskops-vault-syncthatvault.ps1 taskregistersEach entry gets
results/<id>.jsonwithdone,refusedorretry:done: carried out. An already deleted branch or folder isdonetoo.refused: final; the entry leaves the queue.retry(a folder Windows still holds open, a failed fetch,claude agentsnot answering): the entry stays queued for the next pass, up toretry_limitpasses (24, two hours at the default cadence). Then it ends asrefused: retry limit reached (<last reason>).
The coordinator queues entries in
coordinator cleanup --executewhen this config names itsbase_dirand lists the repository. Otherwise, and for a folder not directly underbase_dir, the steps stay in itsowner_command. A step already queued is not queued again; one the janitor refused goes back toowner_command.coordinator statusshows the repository's queue and last results underjanitor.
What it never does¶
git push,git branch -D,reset,clean,stash;- delete anything outside
base_dir; - follow a symlink or a junction;
- run an executable that is not in the config;
- run any entry kind but the three above. An old coordinator's
delete_remote_branchisrefusedas an unknown kind;pull_mainis internal;update_pluginsstays withworkflow:maintenance; - ask for, print or pass a token;
- use
sudoor an elevated task; - write a file outside the user's home.
Config¶
~/.config/claude-janitor/config.json, written by the owner. The schema is closed: an unknown
field refuses the pass.
{
"version": 1,
"base_dir": "/srv/worktrees",
"repos": {
"claude": { "github": "<owner>/claude", "checkout": "/srv/projects/claude", "branch_pattern": null }
},
"executables": { "git": "/usr/bin/git", "claude": "<home>/.local/bin/claude", "systemctl": "/usr/bin/systemctl" },
"cadence_minutes": 5,
"retry_limit": 24
}
base_dir: the shared worktree directory, the one the coordinator uses. Not a drive root, not the home folder or a parent of it, not a link.-Installputs the marker file.claude-janitor-basethere; a pass refuses abase_dirwithout it.repos: the key is what queue entries name.checkoutmust be the main checkout, whoseoriginpoints atgithub.branch_patternnullmeans the worker branches,^(feat|fix|docs|chore|refactor|test)/[0-9]+(-[0-9]+)?-[a-z0-9-]+$; another pattern must be anchored with^and$.executables: absolute paths, soPATHdecides nothing.systemctlonly on Linux. On WindowsgitisC:/Program Files/Git/cmd/git.exeandclaudeC:/Users/<user>/.local/bin/claude.exe.
Install¶
Run it from the marketplace copy of the plugin, as the user the agents run as:
pwsh -NoProfile -File "<plugin dir>/janitor/janitor.ps1" -Install
<plugin dir> is dev-env's installPath in ~/.claude/plugins/installed_plugins.json;
dev-env:dev-doctor prints the full line. -Install:
- validates the config;
- runs one
git fetch --dry-runper repository, so a missing credential shows now, not at the first timed pass; - copies the script to
~/.local/share/claude-janitor/janitor.ps1; - pins both hashes and starts the schedule.
Running it again replaces the pins. Do that after every change to the config and after a
dev-env update; dev-doctor reports when the installed copy is older than the plugin's.
Windows. A Task Scheduler task \claude-janitor\claude-janitor for the current user,
-LogonType Interactive (it runs while the owner is logged on and needs no elevation and no stored
password), with a logon trigger and one that repeats every cadence_minutes, and
-StartWhenAvailable, so a pass missed during sleep runs on wake. The action is conhost.exe
--headless pwsh … -EncodedCommand …: no window flashes, and the encoded command checks both hashes
before the script runs at all.
Linux. Two systemd user units of the agents' user, then systemctl --user daemon-reload and
systemctl --user enable --now claude-janitor.timer. No sudo, no file outside the home folder.
~/.config/systemd/user/claude-janitor.service:Type=oneshot, the optionalEnvironmentFile=-%h/.config/claude-dev-doctor/claude-remote.env, and twoExecStartPre=lines that check the hashes withsha256sum --check.-
claude-janitor.timer:OnActiveSec=2min,OnUnitActiveSec=<cadence>min. -
git fetchauthenticates throughghas git credential helper with the user's storedghlogin (gh auth setup-git, as on the host already). No token from the env file reaches git: the janitor removes the env file's names, and every name that looks like a secret, from the environment of each program it starts. - Until lingering is on for the user (
loginctl enable-linger, #319) the timer fires only while the user has a login session.
Deny rules. -Install prints, and never writes, two sets of rules. Add them: they are what
keeps an agent to queueing.
permissions.denyentries for~/.claude/settings.json: Bashjanitor.ps1 -Once,-ConfigSha256,-ScriptSha256,-Installand-Uninstall, each by the shortest prefix PowerShell accepts (-Oncis-Once); Edit and Write on the config, the installed copy and, on Linux, the units.- Matching
[[overrides.block]]patterns for~/.config/dcg/config.toml.
Both are needed. Claude Code's rules compare case-sensitively, while PowerShell takes -once for
-Once, and an en or em dash for the -. The dcg pattern ignores case and takes those dashes
too.
Read-only folders. On Linux a folder without write permission (r-x) cannot be emptied, and
the janitor does not change permissions: such a remove_folder stays in retry and ends as
refused at retry_limit, for the owner to look at.
Uninstall¶
pwsh -NoProfile -File "<plugin dir>/janitor/janitor.ps1" -Uninstall
Removes the task (Windows) or disables and removes both units (Linux), and the installed copy. The config, the queue and the results stay. Running it twice is harmless.
Day to day¶
janitor.ps1 -Status(-Jsonfor scripts): installed or not, pins intact, the last pass, the queue with its retries, the last 20 results, the branches pruning keeps. Open to agents.janitor.ps1 -DryRun: what the next pass would do with each entry and branch, and why it would refuse. Fetches nothing, changes nothing. Open to agents.janitor.ps1 -Once: one pass now, for the owner.dev-env:dev-doctor, group Worktrees, row Janitor: not installed (OK), pin broken (FAIL: every pass refuses until-Installruns again), entries stuck inretry, a last pass older than three cadences, an installed copy older than the plugin.
Vault sync¶
A vault_sync entry refreshes this machine's token cache at the next pass (#479):
- Linux: the janitor starts
ops-vault-sync.service, the oneshot unit thatvault.sh timerinstalls for the hourly sync, with thesystemctlof its config, and waits for it. - Windows: it starts the scheduled task
ops-vault-syncthatvault.ps1 taskregisters, and waits for its run, up to the task's 10-minute limit and one more.
That is vault.sh refresh (vault.ps1 refresh) without the check that follows; run check to
see the result. The entry names no repository. It runs once per pass, outside the per-repository
loop, however many are queued and whether or not a fetch failed. Where no janitor is installed
(the Raspberry Pi, the owner user on the Linux host), vault.sh refresh does the same by hand.
| Outcome | When |
|---|---|
done |
the sync ran |
retry |
the sync failed (Bitwarden unreachable, say) or did not finish in time, or the Task Scheduler failed: the next pass and the hourly timer try again; a Bitwarden that cannot be read leaves the cache (the user environment on Windows) as it was |
refused |
no ops-vault-sync.service in ~/.config/systemd/user (vault.sh timer installs it); on Windows no task ops-vault-sync, or a disabled one (vault.ps1 task registers it again) |
Queue one by hand, under a temporary name and then renamed, as the janitor expects:
q=~/.local/state/claude-janitor/queue; id=$(cat /proc/sys/kernel/random/uuid)
printf '{"version":1,"id":"%s","kind":"vault_sync","queued_at":"%s","queued_by":"owner"}\n' \
"$id" "$(date -Iseconds)" >"$q/$id.json.tmp" && mv "$q/$id.json.tmp" "$q/$id.json"
Threat model¶
The janitor runs as the same user as the agents, and a process of that user can do anything the user can: no file permission keeps an agent out of the janitor's files. What the design guards against is a confused or prompt-injected agent using the janitor as a way around the destructive-command guard. It does not guard against malware running as the owner.
- The queue cannot widen the config. An entry names a repository by its config key and gives a
leaf name; it never carries a path, an executable or a URL. The schema is closed (unknown kind,
unknown or missing field, wrong type, duplicate key:
refused). Every check runs against live state—git, the file system,claude agents—never against what the entry claims, with one exception below. - A
delete_branchentry'sheadis taken on trust (#596). A squash-merged branch is not merged for git, and the janitor never asks GitHub, so the coordinator'sprandheadreplace the merge check: the janitor deletes the branch while its tip ishead. Any agent can read a branch's tip, so an agent that queues an entry with it can have an unmerged local branch deleted, which the destructive-command guard would have blocked. The ref goes, and its reflog with it; the commits stay in the object store untilgit gcprunes them (two weeks by default), and a pushed branch is still on the remote. The entry and its result stay in the queue's folders, so-Statusshows which branch went and on whose claim. - The config and the script cannot be swapped quietly. Both hashes are in the scheduler
definition, checked before the script starts. An agent that edits either file disables the
janitor instead of widening it, and
dev-doctorreports it as FAIL. - The pin on Linux is weaker than a root-owned one. A system unit would keep the pins in a
root-owned file (the first design, j2). The user unit (#319) is writable by the agents' user,
so an agent could rewrite the unit with new pins. The deny rules and dcg patterns that
-Installprints for~/.config/systemd/user/claude-janitor.*are what stands in the way. The owner chose that trade-off for a setup withoutsudo. vault_syncruns whateverops-vault-sync.servicesays. The janitor starts the unit by name and does not check itsExecStart; the unit lives in~/.config/systemd/user, writable by the agents' user. A rewritten unit runs at the next hourly sync anyway; avault_syncentry only brings that forward. The deny rules and dcg patterns-Installprints therefore cover~/.config/systemd/user/ops-vault-sync.*too, as they cover the janitor's own units. On Windows the taskops-vault-syncrunsvault.ps1of the plugin copy it was registered from; the user can re-register it without elevation, and a changed task runs at its next hourly run anyway, so the janitor starting it brings that forward and adds nothing beyond it.- Arguments are arrays. Every program runs from its absolute path in the config with an
argument list, never a command string; a branch name goes after
--, so a name can never become an option.-d, never-D.
Files¶
| Path | What |
|---|---|
~/.config/claude-janitor/config.json |
the config, owner-written |
~/.local/share/claude-janitor/janitor.ps1 |
the installed copy, pinned |
~/.local/state/claude-janitor/queue/<id>.json |
queued entries, written by a coordinator (temporary name, then rename) |
~/.local/state/claude-janitor/results/<id>.json |
one result per entry: outcome, reason, attempts, times, the entry |
~/.local/state/claude-janitor/pass.log |
one line per pass plus each refusal; 30 days kept |
~/.local/state/claude-janitor/last-pass.json, janitor.lock |
the last pass's counts; the lock |
~/.config/systemd/user/claude-janitor.{service,timer} |
Linux only, written by -Install |