Skip to content

fix(cleanup): read ownership from creation stamps, not transcripts - #324

Merged
Ardnived merged 8 commits into
mainfrom
claude/cleanup-ownership-stamps
Nov 26, 2026
Merged

Ardnived merged 8 commits into
mainfrom
claude/cleanup-ownership-stamps

Conversation

@Ardnived

@Ardnived Ardnived commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Cleanup refused its own worktrees and branches as "named by a live session". Cleanup itself put those names there: each scan printed every worktree and branch into its own transcript.
  • A new hook records the creating session inside git. Cleanup reads only that record, and removes the worktree the session ran in.

Change outline

Flow — who owns a worktree or branch

The owner is now written when the thing is created, instead of inferred later from transcript text.

 Bash (git worktree|branch|switch|checkout, gh pr checkout) · EnterWorktree without `path`
+  PreToolUse   stamp-ownership.mjs          snapshot worktrees + branches of the cwd's repo and its siblings
+  PostToolUse / PostToolUseFailure          diff the snapshot, stamp everything new; the first stamp wins
+    stampWorktree   lib/stamps.mjs         .git/worktrees/<name>/claude-session   (git worktree remove deletes it)
+    stampBranch     lib/stamps.mjs         branch.<name>.claudeSession            (git branch -D deletes it)

 cleanup.mjs scan / remove / drop-branch
-  createdThisSession = registered after start && own transcript names it
-  refuse when any live session's transcript names it (naming / mentions)
+  owner = ownerOf(stamp)                    self | live (another running session) | orphan (dead or unstamped)
+    self    → removed
+    live    → never touched; scan only counts it
+    orphan  → removed only with --orphans (replaces --stale), worktrees only under .claude/worktrees
   then: dirty / unpushed / locked / process-in-it blockers, unchanged

Behaviour — the worktree the session runs in

remove refused this worktree because its own lsof, started inside it, listed itself as a holder. Every command now runs at /. A real process still running there, this session's included, keeps the worktree. The skill calls ExitWorktree keep first, so the session leaves the directory before removal.

 attempt(cmd, args, opts)                   skills/cleanup/cleanup.mjs
-  spawnSync(cmd, args, { …opts })          # inherited the caller's cwd
+  spawnSync(cmd, args, { cwd: '/', …opts })

Files

 workflow/
+├── hooks/stamp-ownership.mjs    # writes stamps around creating calls
+├── lib/stamps.mjs               # the stamp format, and the git helpers both readers share
 └── skills/cleanup/cleanup.mjs   # reads stamps; no other session's transcript is read

Test results

  • Lean gate: ✓ claude plugin validate ./workflow --strict and node --test workflow/lib/*.test.mjs, 194 passed
  • Targeted specs: cleanup.test.mjs 17, hooks.test.mjs 21, all passed
  • Build: N/A

Manual verification

  1. After merge, run /plugin → update, so the hook is installed. Work in a session that creates a worktree, then run /workflow:cleanup from inside it while another session is open. The worktree and branch are removed, with no "a live session names it".
  2. On the first cleanup after the update, the unstamped leftovers from older sessions go as orphans when they are clean and pushed. Anything holding unpushed work is kept and listed.

Notes for reviewer

  • The hook adds latency. It runs on every Bash call, but takes snapshots only around creating calls: about 0.6 s on those, and node startup (~0.1 s) on the rest. Hook if filters would remove that startup cost. They are not used, because the minimum Claude Code version that supports them is unverified.
  • Two risks are accepted, and both are recorded in docs/why.md#cleanup-touches-only-its-own-session:
    • A neighbour's branch created during this session's creating call can be stamped as this session's, if the neighbour's call ends last.
    • A live session's unstamped worktree that is clean and fully pushed can be pruned, and its dev
      database goes with it. Restricting teardown to self would instead strand a database on every
      orphan prune, and the removal is the one moment teardown can run.
  • Dismissed review findings:
    • Wrapper scripts are not stamped. A creating call with no git/gh text, such as a script, leaves its item unstamped, so it becomes an orphan. That is the safe direction: it is pruned only when nothing would be lost.
    • A resumed session loses ownership. --resume keeps the session id, and only --fork-session mints a new one. A fork's old stamps become orphans under the same safety rule.
    • Removing a worktree also deletes its unstamped branch. This is intended (gh pr checkout names no branch). The unsafe and live checks still apply.
Detail
  • The first draft stamped only what the call's text named. Review found that it missed ../x worktrees, gh pr checkout and a nameless EnterWorktree, and that git commit -m fix claimed a neighbour's fix. The final version stamps whatever is new, and the first stamp wins.
  • The first draft also exempted all of the session's own processes from holding a worktree. That masked the real holder, cleanup's own lsof, and let a still-running build lose its worktree. The exemption is gone.
  • macOS hides a platform binary's environment from ps -E (/bin/sleep shows none, node does). The tests therefore use a node child as the holding process.
  • Measured on a 6-repo workspace: scan on an 81 MB transcript went from 21.7 s to 3.0 s, because no other session's transcript is read now.
  • rule-delta: 94 → 94 directives, none removed.
  • Security review ran twice, because hooks, lib and skill paths match the trigger pattern. No findings either time.
  • The review's six findings are built, one commit each, and answered in their threads.

🤖 Written by the sydevs autonomous loop — see what this is

🤖 Generated with Claude Code

Ardnived and others added 2 commits November 25, 2026 16:44
Cleanup refused its own worktrees and branches as "named by a live
session", and the naming came from cleanup itself: every scan printed
every worktree and branch in the repo into that session's transcript,
so after one cleanup every open session named everything. A second scan
in the same session also marked unrelated branches as its own. And a
cleanup refused the worktree it ran in, because the session's own
processes had their cwd there.

A new stamp-ownership hook snapshots worktrees and branches either side
of each git/gh Bash call and EnterWorktree, and stamps what is new and
named by the call, inside git: a claude-session file in the worktree's
admin dir, and branch.<name>.claudeSession. Git deletes both with the
thing. cleanup.mjs now reads only those stamps: self is removed, another
live session's is counted and never touched or printed, and an orphan
(a dead session's, or unstamped) is pruned with --orphans when nothing
would be lost. --stale is gone. This session's own processes (its
session id in their env, or descended from CLAUDE_PID) no longer hold a
worktree, and the skill calls ExitWorktree keep before removing the
worktree the session is in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The hook stamps whatever a creating call makes, first stamp wins,
  instead of only what the call names: naming missed ../x worktrees,
  gh pr checkout and a nameless EnterWorktree, and let `git commit -m
  fix` claim a neighbour's `fix`. It snapshots only around calls that
  can create (worktree, branch, switch, checkout), not every git/gh call.
- Register it for PostToolUseFailure too: a creating chain that exits
  non-zero still created.
- The stamp format moves to workflow/lib/stamps.mjs, used by the hook,
  cleanup.mjs and both test suites.
- cleanup.mjs runs every command at `/`: its own lsof, started in the
  worktree, was what held the worktree a session ran in. The blanket
  own-process exemption goes with it, so a build still running there
  keeps its worktree again.
- namedIn loses its unreachable name half, scan counts a live session's
  worktree before crediting changes in it, and prose no longer says
  cleanup touches nothing a running session uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sydevs-dispatcher

sydevs-dispatcher Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

🤖 no session running

recent dispatches
  • 00:26Z address-review · attempt 1 · session · done
  • 00:26Z address-review · attempt 1 · session
  • 00:14Z review-pr · attempt 1 · session · done
  • 00:14Z review-pr · attempt 1 · session

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-dispatcher sydevs-dispatcher Bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 26, 2026
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 26, 2026

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 Adversarial review

Writing ownership into git at creation is the right shape: a git-native record beats the transcript grep it replaces, and the laptop state measured in docs/why.md#cleanup-touches-only-its-own-session justifies keeping a neighbour protection at all, rather than deleting the refusal and carrying the risk. The one-line cwd: '/' fix belongs here, and one hook plus one lib module is no larger than the question cleanup cannot answer alone.

Two things to settle. The feature rests on tool_use_id reaching a PreToolUse hook; nothing verifies that, and the failure is silent and total. The accepted-risk note also promises more than the code gives: an orphan prune can drop a neighbour's dev database.

Findings

  • should-fix stamp-ownership.mjs:92 — unverified tool_use_id on PreToolUse. Absent, nothing is stamped and nothing says so.
  • should-fix docs/why.md:1068 — "safe on GitHub" misses the dev database teardown drops.
  • should-fix Streamline ×4 — stamp-ownership.mjs:33 three utilities defined elsewhere, :73 branch data nothing reads, :101 an unmeasured temp sweep; stamps.mjs:29 hand-parsed gitdir:.

What was checked

Read whole on the branch: cleanup.mjs, stamps.mjs, stamp-ownership.mjs, hooks.json, cleanup/SKILL.md, the why.md and README hunks. The 37 new tests were listed, not run. The ladder covered the hooks.json entries and the skipped files: no dependency added. Streamliner: 35 pieces covered, 31 kept. rule-delta 94 → 94, none removed. version is bumped, README's hook count, the why.md anchor and every path the body names check out, and loop-config.json is untouched. No ## Preview link and no fixture in .claude/workflow.json, so no data check applies. Dismissed: ownerOf cannot read an unstamped branch as self, because loadSession exits without an id.
🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread workflow/hooks/stamp-ownership.mjs Resolved
Comment thread docs/why.md Resolved
Comment thread workflow/hooks/stamp-ownership.mjs Resolved
Comment thread workflow/hooks/stamp-ownership.mjs Resolved
Comment thread workflow/hooks/stamp-ownership.mjs Resolved
Comment thread workflow/lib/stamps.mjs Resolved
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 26, 2026
@sydevs-dispatcher sydevs-dispatcher Bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 26, 2026
`adminDir` parsed `gitdir:` out of the worktree's `.git` file. `git rev-parse
--path-format=absolute --git-dir --git-common-dir` answers the same question:
the two paths differ only in a linked worktree, so a main checkout still gives
null.

It also fixes a case the hand-parse got wrong. A `.git` file whose admin
directory git has already dropped still parsed, so `stampWorktree` wrote a
stamp into a directory nothing reads. rev-parse fails there, and the stamp is
skipped.

Addresses #324 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZHnNizRaus1DpCe19
The hook defined `git`, `lines` and `repoOf` itself, and all three already
existed: `git` in `lib/stamps.mjs`, `lines` and `repoOf` in
`skills/cleanup/cleanup.mjs`. Both files already import `stamps.mjs`, so the
three move there and the copies go.

`cleanup.mjs` keeps its own `git`, which routes through `attempt` so a failure
can be reported as a blocker. Its `repoOf` discards the error either way.

Addresses #324 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZHnNizRaus1DpCe19
`snapshot` recorded each worktree's checked-out branch, and nothing read it:
the post event compares worktree paths, and a new branch comes from
`branches`. The worktrees are an array of paths now, compared with `includes`.

Addresses #324 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZHnNizRaus1DpCe19
The hook returned unless the payload carried `tool_use_id`. Nothing verifies
that a PreToolUse event sends it, and absent it the whole feature failed
silently: no snapshot, no stamp, no output, in a repo whose change cannot be
tested by running it. `hooks.test.mjs` wrote the field into its own payloads,
so the suite could not catch it.

The key is `tool_use_id ?? session_id`. Two creating calls at once then share
a snapshot, which costs a stamp and never misplaces one, because the later
snapshot already holds what the earlier call made.

The Pre event now writes the file even when there is nothing to snapshot.
A session-keyed file is reused across calls, so an abandoned call must not
leave one for a later call's post event to read as its own.

A test drives a creating call whose payload has no `tool_use_id`.

Addresses #324 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZHnNizRaus1DpCe19
The Pre event swept the snapshot directory for files older than a day, at a
readdir plus a stat per file on every creating call. It defended against a few
hundred bytes of JSON per abandoned call in the OS temp directory, which the
OS sweeps itself.

A stale snapshot could never be read in any case: a `tool_use_id` key is
unique to one call, and a session key is overwritten by that call's own Pre
event, which now always writes.

Addresses #324 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZHnNizRaus1DpCe19
The accepted-risk note claimed the work is safe on GitHub. A dev database is
not: `remove` runs `dev-server.sh teardown` first, and `foreignDb` clears a
same-repo worktree's database because its name fits the main checkout's
template. So a pruned worktree's database goes with it.

The note now says so, and says why teardown is not restricted to `self`:
that would strand a database on every orphan prune, and the removal is the
one moment teardown can still run.

Addresses #324 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZHnNizRaus1DpCe19
@sydevs-bot

Copy link
Copy Markdown
Contributor

Six review threads, all adopted. Each reply has the detail.

Base already current with main. Gate green: 194 tests, rule-delta 94 → 94. Security review: nothing.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 26, 2026

@sydevs-dispatcher sydevs-dispatcher Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved for Ardnived, who wrote it: GitHub refuses an author's own approval. CI is green and the automated review has run. Enable auto-merge when you want it merged: the queue tests it against its base. 🤖 Written by the sydevs autonomous loop — see what this is

@sydevs-dispatcher sydevs-dispatcher Bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 26, 2026
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Pending to Awaiting in SYDevelopers Technical Roadmap Nov 26, 2026
@Ardnived
Ardnived added this pull request to the merge queue Nov 26, 2026
Merged via the queue into main with commit 0525fef Nov 26, 2026
97 of 106 checks passed
@Ardnived
Ardnived deleted the claude/cleanup-ownership-stamps branch November 26, 2026 16:12
@sydevs-dispatcher sydevs-dispatcher Bot moved this from Awaiting to Done in SYDevelopers Technical Roadmap Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

3 participants