Repository navigation
feat(cleanup): add an end-of-session cleanup skill - #316
Conversation
`info` prints a worktree's slug, state directory and isolated database as JSON, so another script can ask instead of re-deriving the cksum slug and the database template, which would drift. The `<slug>.pid` file only hands `$!` out of the start subshell, but nothing removed it: every server ever started left one behind, sixteen on one laptop, several for worktrees long gone. It now goes right after the state file is written. Co-Authored-By: Claude Opus 5.5 <[email protected]>
/workflow:cleanup is run when a maintainer believes a local session is done. It stops the dev and Ladle servers the session started, removes its worktrees with their local branches and isolated databases once nothing would be lost, prunes what older sessions left behind, and reports what is still outstanding: uncommitted or unpushed work, PRs that need attention, follow-up tickets discussed but never filed, and cross-repo steps still owed. The failure it prevents is twofold. Sessions end with servers holding ports, and worktrees, branches and databases pile up (ten worktrees, two orphaned databases and ninety-odd local branches on one laptop), while work is quietly left unpushed. And a naive sweep would kill a concurrent session's work, since many sessions run at once. So cleanup.mjs owns every stop and delete, and re-proves safety as it acts: - a server is this session's by CLAUDE_CODE_SESSION_ID in its env; - a worktree is this session's when the transcript names it, as a whole path token, and git registered it after the session began; - anything a live session (~/.claude/sessions/<pid>.json) names or sits in is never touched, and nor is any worktree a process runs in; `--stale` removal of older worktrees is limited to .claude/worktrees; - a commit is safe when a remote branch or a PR head holds it. The skill fetches PR heads into refs/cleanup/pull/*, which is what lets a squash-merged branch be recognised as done. Only local branches are deleted; GitHub deletes merged ones itself. Slugs and database names come from `dev-server.sh info`. The script never talks to GitHub; the skill gathers PR state with gh. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A worktree's .claude/workflow.json is the branch's to set. A template of
`{slug}` there, with no literal prefix, would make every database on the
machine read as an orphan for drop-db. Narrow `gh api` in allowed-tools
to graphql, so the skill cannot delete a remote branch unprompted.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff is the size of its title: one script owning every stop and delete, one skill gathering GitHub state, and dev-server.sh info so the naming has one owner. The piece count is high, and no cheaper approach survives: the live-session veto needs other sessions' transcripts, and git branch -d and worktree remove refuse strictly less, neither counting a PR head that outlives a squash merge. No contract surface is touched. Ownership rests on four undocumented harness internals, and fails the right way — loadSession calls fail(). But allowed-tools grants a set that cannot run two of this skill's own steps — the opposite of an over-broad line, and still a failure.
Findings
- should-fix
cleanup.mjs:355— a full transcript copy per checkout;RangeErrorpast ~512 MB. - should-fix
SKILL.md:121—gh api repos/…is outsideallowed-tools. - should-fix
SKILL.md:42—git -C <repo> fetchis outsideallowed-tools. - should-fix
cleanup.mjs:467—branches[]carries no owner; steps 5 and 9 cannot be split. - consider
cleanup.mjs:544— a removal failing afterteardownhides the dropped database. - should-fix 5 × Streamline —
cleanup.mjs:93,:197,:392,:423,:551.
What was checked
Read whole on the branch: cleanup.mjs (616), cleanup/SKILL.md, dev-server.sh, cleanup.test.mjs, plus the README, why.md and manifest lines. Ladder walked for the added dependency (lib/config.mjs, already shared) and the pieces new-pieces.mjs skipped. Streamliner: 53 covered, 47 kept, 12 sketches, 5 held. Held: .pid has no reader left but staleStateFiles' legacy branch; infos[0] is the main checkout at all three call sites; namedIn's latin1 and boundary handling match its tests. version bumped; manifest still valid. No question threads.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
`inspectCheckout` joined every transcript of the session into one string, once per checkout, to look for the `[<branch> <sha>]` line `git commit` prints. Live transcripts run to hundreds of megabytes, so past about 512 MB `join` throws an uncaught `RangeError: Invalid string length` and `scan` dies with no report at all. The regex is built once per commit and tested against each text instead. A commit line never straddles two files, so the answer is the same. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
`scan` emitted `branches` with no owner, so the skill could not make the split it asks for: step 5 drops this session's branches, step 9 the rest. Without the field, *Cleaned up* and *Found, not touched* could not be filled apart. The transcript answers it, in one `namedIn` pass per repo. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
`teardown` needs the worktree, so it runs before `git worktree remove`. When the removal then failed — a file appeared, a lock was taken — the report said `KEPT — <err>` and said nothing about the database already dropped, leaving the user to find a worktree whose server cannot start. The error now carries `(database <name> was already dropped)`, and only when `teardown` actually succeeded. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
`staleStateFiles` also read a pid from `<slug>.pid`, which this PR makes `dev-server.sh` delete once the state file is written. A surviving `.pid` is a crashed start's or the old script's leftover, and its number may by now belong to any process, so `pids.some(alive)` could keep dead state files on disk forever. The json has held the pid since before this change, so dropping the `.pid` read loses nothing: a live server's state is still kept. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
`processEnv` had one caller, and `sessionOf` was only a `.find().slice()` over it, with the environment variable's name spelled twice. One function and one named constant now hold both. The macOS `ps -E` fallback and the try/catch are unchanged. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
The function required `infos[0]` to be the main checkout's info, a rule only its own comment held, and both callers built the same `listWorktrees(repo).map(devServerInfo)` to satisfy it. It now takes the repo and asks `dev-server.sh` itself: the template from the main checkout, the owned names from the worktrees it lists. Both call sites become `orphanDatabases(r)`, and the ordering invariant is gone. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
`remove`'s branch block and `dropBranch` were near-copies of one rule: find the branch, `branchBlocker`, the live-session veto, `git branch -D`, `settle`. `deleteBranch` now holds it, taking the already-listed branches and the naming set so neither caller pays an extra git call. Two visible changes, both the shared version's: a branch deleted after a worktree removal reports `(was <sha12>)`, and a branch that no longer exists says `no such branch` instead of printing git's error. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
A lookbehind now rejects a candidate position whose preceding character continues a token, replacing the hand-rolled `BEFORE` test. One constant and one check go, and the result is unchanged on 200,000 random needle/text pairs. The closing boundary stays per needle, and the scan stays zero-width. An alternation would report only its longest match at a position, so a needle set holding `/r/wt` and `/r/wt/src` would lose `/r/wt` — in the live-session veto, the direction that deletes something. A test now asserts both are found. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
`Bash(git fetch:*)` matches `git fetch …`, not `git -C <repo> fetch …`, so step 2's parallel PR-head fetch prompted for every repo but the rooted one. AGENTS.md asks for the narrowest set that works, and that set did not. `block-wrong-bash` already refuses `git -C` at the session's own root, so the grant reaches no further than the sibling checkouts step 2 fetches. Prefix matching cannot express `git -C <any> fetch`, so this is the narrowest grant available. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
`gh api repos/…/contents/loop-config.json` fell outside `Bash(gh api graphql:*)`, so step 8 prompted on every run. The workspace already holds the file, so the step reads it there and needs no network call at all; `Bash(jq:*)` is the only grant added, and a far narrower one than the `Bash(gh api:*)` that would have made the old command work. A workspace without the claude-workflow checkout now reports the check as skipped rather than failing step 8. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
The branch-level `/security-review` scored `allowed-tools` as its highest finding: `Bash(node:*)` also matches `node -e '<any JS>'`, and the skill pulls untrusted text into context from PR comments, search results and other sessions' transcripts. Every `node` call here runs `skills/cleanup/cleanup.mjs`, and the one `jq` call reads `.contractSync`, so both grants now name the command — the idiom `settle-roadmap` already uses. A prompt still covers anything else. `git -C` and `gh api graphql` cannot be narrowed the same way, and the body says why: a `*` before a subcommand does not restrict the subcommand, so `Bash(git -C * fetch *)` would still match `git -C /x push origin fetch`, and a trailing `*` after `query=` would still match a `mutation` appended to it. Deny rules and a PreToolUse hook are the only real enforcement, and `.claude/settings.json` is a protected path this run cannot write. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
`remove --stale` runs `dev-server.sh teardown`, which does `dropdb --if-exists "$DB_NAME"`, in worktrees this session did not create. `DB_NAME` comes from `databaseNameTemplate` in that worktree's own `.claude/workflow.json` — the branch's to set, and not a protected path against `git checkout`. So an abandoned worktree on a branch that edited that file could name any database on the cluster, and step 9 runs `remove --stale` unattended. 57f8235 closed this route for `orphanDatabases` and left it open here. `isOwnDatabase` now holds that one rule, both callers use it, and a worktree whose database the main checkout's template does not shape is kept with its name in the reason. Found by the branch-level `/security-review`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
The live-session veto asks `namedIn`, which requires a whole token. A database name reaches a transcript inside the `DATABASE_URL` `dev-server.sh start` passes — `…:5432/<name>` — where the preceding `/` makes the token test fail. Measured: `sahajcloud_dev_wt_123` in that URL is not named. A branch is usually also printed bare, so it survives the test; a database may never be. Dropping a database cannot be undone, and the veto is the only guard between it and another live session's running server, so `drop-db` and `remove`'s teardown now refuse on any mention, not a token. Everything else keeps the strict test: there a false positive deletes. Found by the branch-level `/security-review`. The remaining half — whether `drop-branch` needs the same, and whether a database's owner should be proved from the dev-server state records instead of inferred — is an open question thread. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjV5Uq51ZfRXFYMV52z
sydevs-bot
left a comment
There was a problem hiding this comment.
1 question for the reviewer, one per thread.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
|
Ten threads: nine adopted, one half. Replies carry the SHAs.
A second 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
There was a problem hiding this comment.
Approved for Ardnived, who wrote it: GitHub refuses an author's own approval. CI is green and the automated review has run. 🤖 Written by the sydevs autonomous loop — see what this is
|
Approved, but this thread still waits on you, and the ruleset will not merge until it is resolved: #316 (comment). Reply there, or resolve it. 🤖 sydevs dispatcher |
Nothing proves which checkout made a database whose worktree is gone. A second clone's worktrees are invisible to this one, so its live database read as an orphan, and `dev-server.sh stop` deletes the state file that would record the owner. The only guard left was a loose mention check on other sessions' transcripts, and a dropped database cannot be recovered. A database now goes only with its worktree, through `dev-server.sh teardown` in `remove`. `scan` loses `orphanDatabases` and `drop-db` goes; a stray database costs disk space and is dropped by hand. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
/workflow:cleanup, run when a local session is done. It stops this session's servers, removes its worktrees, local branches and dev databases, prunes older sessions' leftovers, and lists what is still outstanding.dev-server.shgainsinfo, and its leftover.pidhandoff file is now deleted.allowed-toolsnames thenodeandjqcommands the skill runs, andteardownrefuses a database the main checkout's template does not shape.Change outline
Flow —
/workflow:cleanup(workflow/skills/cleanup/SKILL.md)The skill drives one script,
cleanup.mjs. The script owns every stop and every delete. The skill gathers PR and ticket state withghand writes the report.Behaviour — what the script will touch (
workflow/skills/cleanup/cleanup.mjs)Ownership is proved, and a live session can veto any change. Each mutating command re-checks these rules when it acts.
Contract —
dev-server.sh infocleanup.mjsasksdev-server.shfor the slug and database name, so the naming rules live only indev-server.sh.Test results
claude plugin validate --strictpasses, andnode --test workflow/lib/*.test.mjspasses 184 tests.cleanup.test.mjshas 13 tests, all passing. They cover token-boundary matching, two needles starting at one index, which loose branches the session named, the database-name rule, refusals (dirty, unpushed, not ours, outside.claude/worktrees, claimed by a live session), local-only branch deletion, and PR heads counting as safe.Manual verification
pnpm ladle) and created a worktree, run/workflow:cleanupafter the PR merges and/pluginhas updated. Check that both are gone and that the report lists anything unpushed.Notes for reviewer
refs/pull/*/headbecause squash merges leave branches whose commits exist only in a PR head. The script itself never contacts GitHub (why.md#a-script-here-never-fetches)./simplify(4 lenses) and/code-review high; the toolkit is not installed./security-reviewtriggered onworkflow/skills/**.mdandworkflow/lib/. All its findings scored below 8. The two that came closest were applied anyway:gh apiis narrowed to graphql, and the database template now comes from the main checkout only.Bash(git -C:*)andBash(gh api graphql:*)grant more than the steps use, and nothing narrower holds. A*may sit mid-pattern, but one placed before a subcommand does not restrict it:Bash(git -C * fetch *)still matchesgit -C /x push origin fetch, as the docs' ownBash(git * main)example shows. Pinning the path is the only safe spelling, and the repo paths vary per laptop. Likewise a trailing*afterquery=still matches amutationappended to the same string. A deny rule plus aPreToolUsehook is the only real enforcement;.claude/settings.jsonis a protected path, so neither is in this PR. 57f8235's property — no remote branch deleted unprompted — therefore rests on this skill's prose. Dropping step 2's cross-repo fetch is the alternative, and that call is yours./security-review, on the critic's fixes. Three findings. Two applied: thenodeandjqgrants now name their commands (Bash(node *skills/cleanup/cleanup.mjs*)issettle-roadmap's idiom), andremove --staleno longer letsteardowndrop a database named by the stale worktree's own.claude/workflow.json— 57f8235 closed that route fororphanDatabasesand left it open here. Its two recommended grant spellings were rejected, for the reason in the bullet above. The third is half built — any mention of a database now vetoes dropping it, because the name reaches a transcript only inside aDATABASE_URL, where the token test misses it — and half asked, in the open question thread oncleanup.mjs:193.merge-gate.mjs. Step 4 only reports PR state and never gates anything, andmerge-verdictreports only the first blocker it finds.node_modulesdeletion, at the cost of async process handling.namedIn's closing boundary in the regex as well. A consuming alternation reports only its longest match at a position, so the needle set['/r/wt', '/r/wt/src']overcd /r/wt/src/x.tsloses/r/wt. In the live-session veto that is the direction that deletes. The opening boundary moved to a lookbehind, and a test now pins both needles.comment-lint.mjsadds no banned comment. It runs from the checkout; from a worktree it cannot resolve typescript.Detail
DATABASE_URL: there a miss is unrecoverable, and a false positive only leaves a database behind. Concurrent sessions are normal here: fifteen were running while this PR was written.scantakes about 5 s with 15 live sessions (≈720 MB of transcripts are read only by the mutating commands, in one regex pass per file), ~10 worktrees, ~100 branches..pidfix moved. It first lived instop. A server killed by any other route would still have leaked the file, so it now runs right afterstate_write.🤖 Generated with Claude Code