Skip to content

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:

  1. 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.log and exits.
  2. Updates each configured repository: git fetch --prune origin, then git 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 against origin/<default> anyway.
  3. Prunes gone branches. It deletes with git branch -d every 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 own try/notes), an unmerged one (a pull request closed without merging), and one without an upstream.

  4. 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_branch repo (a config key), branch; optionally pr and head, together the branch matches branch_pattern, is not the default branch, is checked out in no worktree, is merged into origin/<default>; then git branch -d. With pr and head (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 is head, by git update-ref with head as the old value, and refused when its tip differs. An entry without them gets the merge check
    remove_folder folder (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 .git in 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 link
    vault_sync none: any field beyond the common ones is refused the token sync ran: systemctl --user start ops-vault-sync.service, the unit vault.sh timer installs; on Windows the scheduled task ops-vault-sync that vault.ps1 task registers

    Each entry gets results/<id>.json with done, refused or retry:

    • done: carried out. An already deleted branch or folder is done too.
    • refused: final; the entry leaves the queue.
    • retry (a folder Windows still holds open, a failed fetch, claude agents not answering): the entry stays queued for the next pass, up to retry_limit passes (24, two hours at the default cadence). Then it ends as refused: retry limit reached (<last reason>).

    The coordinator queues entries in coordinator cleanup --execute when this config names its base_dir and lists the repository. Otherwise, and for a folder not directly under base_dir, the steps stay in its owner_command. A step already queued is not queued again; one the janitor refused goes back to owner_command. coordinator status shows the repository's queue and last results under janitor.

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_branch is refused as an unknown kind; pull_main is internal; update_plugins stays with workflow:maintenance;
  • ask for, print or pass a token;
  • use sudo or 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. -Install puts the marker file .claude-janitor-base there; a pass refuses a base_dir without it.
  • repos: the key is what queue entries name. checkout must be the main checkout, whose origin points at github. branch_pattern null means 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, so PATH decides nothing. systemctl only on Linux. On Windows git is C:/Program Files/Git/cmd/git.exe and claude C:/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:

  1. validates the config;
  2. runs one git fetch --dry-run per repository, so a missing credential shows now, not at the first timed pass;
  3. copies the script to ~/.local/share/claude-janitor/janitor.ps1;
  4. 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 optional EnvironmentFile=-%h/.config/claude-dev-doctor/claude-remote.env, and two ExecStartPre= lines that check the hashes with sha256sum --check.
  • claude-janitor.timer: OnActiveSec=2min, OnUnitActiveSec=<cadence>min.

  • git fetch authenticates through gh as git credential helper with the user's stored gh login (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.deny entries for ~/.claude/settings.json: Bash janitor.ps1 -Once, -ConfigSha256, -ScriptSha256, -Install and -Uninstall, each by the shortest prefix PowerShell accepts (-Onc is -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 (-Json for 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 -Install runs again), entries stuck in retry, 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 that vault.sh timer installs for the hourly sync, with the systemctl of its config, and waits for it.
  • Windows: it starts the scheduled task ops-vault-sync that vault.ps1 task registers, 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_branch entry's head is taken on trust (#596). A squash-merged branch is not merged for git, and the janitor never asks GitHub, so the coordinator's pr and head replace the merge check: the janitor deletes the branch while its tip is head. 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 until git gc prunes 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 -Status shows 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-doctor reports 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 -Install prints for ~/.config/systemd/user/claude-janitor.* are what stands in the way. The owner chose that trade-off for a setup without sudo.
  • vault_sync runs whatever ops-vault-sync.service says. The janitor starts the unit by name and does not check its ExecStart; the unit lives in ~/.config/systemd/user, writable by the agents' user. A rewritten unit runs at the next hourly sync anyway; a vault_sync entry only brings that forward. The deny rules and dcg patterns -Install prints therefore cover ~/.config/systemd/user/ops-vault-sync.* too, as they cover the janitor's own units. On Windows the task ops-vault-sync runs vault.ps1 of 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