workspace-cleanup
Scope
You may only ever consider paths inside your own workspace:
<workspace>/repos/<repo>/.claude/worktrees/* (registered linked worktrees) and
the literal node_modules/.venv caches inside them. Never touch another
agent's workspace, the primary checkout, workspace roots, output/, memory/,
artifact stores, configuration, databases, logs, canonical skills, or any
unknown path. Never use elevation.
Invocation
The one shared workspace-cleanup skill for every agent, including no-repo
agents. It is invoked two ways, and both use exactly this contract:
-
Manual dispatch. The task brief's first line is exactly:
HAPPYRANCH SYSTEM WORKSPACE CLEANUP RUN (manual-dispatch)
A manual request that does not carry that exact first line is
inventory-only: report candidates and skips, and take no action. Manual
runs never advance the scheduled occurrence count.
-
Daemon daily trigger. The daemon's daily marker is exactly:
HAPPYRANCH SYSTEM WORKSPACE CLEANUP RUN (daemon-triggered)
The daemon composes the brief that begins with that marker, so the same skill
and the same gates apply automatically.
Both markers identify the same skill. No other skill, task, or prompt grants
cleanup authority.
Prerequisites and ordered steps
Use the current task/session binding and an exact marker above. Keep complete
native inventory, owner/peer/trigger receipts and maintained history exclusions;
unknown history, ownership, process use, protection or remaining budget refuses
action. Installed scripts require external PATH python3, Git and the supported
HappyRanch readers. Source delivery, a witness or a merge grants no live cleanup,
deployment, restart or activation authority.
- Collect and prepare one repository at a
time, preserving native receipts and exact original history sources.
- Prepare the frozen manifest.
Complete empty/no-repository evidence produces no action request; incomplete
evidence stops without refilling candidates or repairing history.
- Render the supported observed job request only with authentic launch-deadline
evidence, then submit exactly once under the current ACTIVE owner binding.
- Observe the original job and retain its terminal receipt, enclosing sequence,
postchecks and acknowledged journal. Unknown transport or any anomaly stops
further mutation; successful submission or wrapper exit alone proves no removal.
- Report actual outcomes and missing evidence, then make the genuine
current-session completion callback the final action.
Gate refusals retain the candidate and their exact reason. Evidence/publication
failures, interruption and partial effects remain unknown and stop the batch;
never rebind, retry or replace an uncertain attempt.
The separate daemon nightly disk sweeper, its operator manual backlog entry and
measurement internals are owned by the maintained
nightly disk sweeper contract.
Its native writer/hold, ownership, age, mount/link and durable-output protections
remain its own. It does not replace this skill's marker, ordinal, host-job,
peer/history or preservation gates and grants no manual fallback or live authority.
Retained preparation and admission
Shared Pause, native identity, retry budgets and cleanup ownership remain
operative under the native ownership contract.
New execution requires a current executable owner; historical task attribution
is not current launch eligibility. Strict saved history and callback/uncertainty
settlement remain. Never rewrite live state, audit history, stored compatibility
rows, teams, callbacks or bindings as cleanup.
Thread retry initialization freezes even EMPTY budgets. Initial/fallback/nudge
initialization differs from a frozen zero budget; deferral/reentry cannot
replenish it. Missing legacy facts preserve their original interpretation but
refuse ambiguous retry/reentry with team_move_thread_retry_initialization_unknown;
never backfill that history.
The SAME INTEGER thread invocation/agent/SID preparation owner spans native
materialization, integrity, repository refresh and launch-spec/cache preparation,
including helper-internal omissions and caught failures. Such uncertainty appends
the existing sticky failed_cleanup fact BEFORE ordinary failure settlement;
backend preparation/cleanup and native workspace/cache failures retain ownership.
Later success/callback/terminal state cannot erase it. Serializer, audit COMMIT,
strict history reader, restart/reentry and census preserve that fact, independently
of frozen EMPTY/nonempty retries. Ordinary stale-claim/agent/breaker or missing
launch-seam refusals before effects retain their native no-effect disposition;
returned failure alone never proves compensation. No new schema/journal/backfill
or generic producer identity is introduced.
Ordinary tasks carry their SAME native TaskInvocation/task/agent/runtime SID
through materialization, integrity (including retries), package omissions,
repository refresh, attachment writes/cleanup, task scratch and builtin/custom
cache/workspace setup. Safe deferred ownership becomes durably prepared before
preparation resumes; this never clears existing uncertainty.
Preparation failure sets the existing local reservation cleanup flag BEFORE the
fallible strict Pause save/COMMIT, then retains execution_unknown/unknown in
the admitted journal. Terminal/callback/quiescent later attempts and safe unrelated
worktree cleanup cannot clear it. Settlement persists that fact before release;
failed saves retain local ownership and original plus persistence errors.
Restart treats unclosed task prepared entries as unknown, including terminal
rows and prepared recovery/retry owners; absence of first launch is no proof of
preparation cleanup. Unknown deferred entries cannot authorize a fresh launch.
Native pre-effect source/artifact validation, repo-scan and missing launch-seam refusals
retain their no-effect disposition. Existing retry/recovery IDs, frozen budgets,
INTEGER callbacks and authority-v2 are preserved. No new field/journal, history
backfill, compensation or clearance writer is introduced.
Native C3 preparation failure or ordinary process return never proves file,
package or process cleanup. Unknown ownership remains in retained audit census.
New retry budgets explicitly freeze even an empty schedule; missing legacy facts
cannot authorize replenishment/reentry. Schedule runtime SID is pinned through
real preparation/spec/execution and is distinct from provider resume identity.
Custom-skill authority validates before reservations; only explicit native
validation/rollback/temporary-cleanup evidence can settle a refused writer.
No history deletion, automatic recovery, apply or execution authority follows.
The native workspace-cleanup trigger no longer checks a team-move hold. Its existing cleanup authority, writer ownership and all preservation gates remain. Never delete another owner’s workspace, clear uncertainty or fabricate settlement. The separate nightly disk sweeper retains its move-hold and native uncertainty gates.
Guard setup best-effort adds the root-only /.worktree-guard.json rule to
that clone's shared common-dir info/exclude (THR-307 seq337 step 4). Existing
clones gain it only on their next guard setup; this skill does not bulk-edit Git
metadata.
Aliased or unsafe excludes warn and are skipped without changing target bytes:
a symlinked/non-directory info parent, a symlinked or multiply linked final
file, or any non-regular final file. Setup and guard enforcement continue.
Unwritable excludes leave guard enforcement active and, without another
ignore rule, the file dirty. Modified tracked/staged guards, .gitignore negation,
subdirectory guards and other untracked files stay dirty. This changes no cleanup
gate or non-force removal rule; guard-only dirt is not removal authority.
Report-only ordinal
The first two triggered cleanups for an agent are strictly report-only: no
deletion, no move, no modification. Only from the third triggered run, and only
when every gate below is re-derived at action time, may you act. Manual dispatch
contributes zero to that count; a manual run still requires the two prior
joined terminal daemon occurrences before it may act.
Authoritative joins (R5 / R6.5 / R7)
Authoritative recorded terminal status plus a fresh, complete, current scan of
folder use replaces separate live-session/task-to-process identity for terminal
candidates, terminal cleanup peers, and the two prior joined terminal scheduled
occurrences. Nonterminal peers block. Missing, conflicting, or incomplete
non-exempt evidence is a skip. Positive use blocks.
- R5 (target task). The owning task must be terminal and older than the
retention floor (24 hours for a cache, 7 days for a whole worktree). The
owning task and its terminal time come from the authoritative read-only
happyranch recall record; the shared OS UID and any directory mtime are
never used to establish the owner or the terminal age.
- R6.5 (cleanup peers). Union all same-owner cleanup peers across all
statuses from a complete keyset-paged assigned-task lookup — the manual
marker, the daemon marker, and trigger-history rows — and omit only your own
acting task. Any nonterminal peer is a skip. Recheck after claim and again
immediately before every action. Unrelated audit history, however large,
never makes this candidate-specific join incomplete.
- R7 (prior occurrences). Require at least two distinct prior joined terminal
scheduled occurrences, retaining the complete history rather than selecting a
subset. Duplicates collapse. The filtered trigger audit is
read through complete keyset pages; missing, malformed, changing, or failed
pages are a skip.
- Cooperative overlap. Perform the peer and listing recheck after claim and
immediately before each action. This is cooperative, not a lock. A new peer
appearing in the window makes the action a skip.
Ownership and protected paths
Only a registered, non-primary, clean whole worktree whose HEAD is durably
preserved, with no open or closed-unmerged PR for its branch, and no protection,
may be considered. Durable preservation is exactly one of: the existing
accepted durable ref (normally origin/main); a freshly verified owning-task
remote branch on origin whose head contains (is equal to or descends from)
the candidate HEAD; a confirmed merged PR for that same task branch whose
head contains the candidate HEAD; or a merged PR from any task whose head is
independently confirmed to contain the candidate HEAD. When the owning live
remote branch exists, it is authoritative: if its head does not contain the
candidate HEAD, or its containment evidence fails, refuse without consulting
owning-task or any-task merged-PR alternatives. The any-task proof
requires complete, non-truncated, double-read discovery; a stable closed PR
projection with MERGED, non-empty mergedAt, and base equal to the
double-read repository default branch; and a stable complete compare proving
the candidate is equal to or an ancestor of the PR head. Discovery alone never
counts. Another task's open or closed-unmerged PR never preserves; an owning
branch's open or closed-unmerged PR remains a refusal even if a different
merged PR contains the candidate. Missing, stale, unfetchable, truncated,
diverged, conflicting, changing, or malformed remote/PR evidence refuses. A
confirmed merged PR preserves the integrated content but may not preserve the
original commit topology. Refuse
cross-owner, protected, symlink/shared/unknown, dirty whole worktrees,
local-only or unreachable commits, and insufficient age. Never rewrite, move,
archive, bundle, tag, quarantine, or repair preserved work.
The sole dirty-tree exception is a literal immediate-child node_modules or
.venv cache. Its containing worktree may be dirty, but every other gate still
applies and the action may remove only that cache. The dirty whole-worktree is
never removed or cleaned. Source bytes and Git status must be identical before
and after the cache action.
Current-use observation
Before acting, run the bundled read-only helper only through a task-bound,
host-visible HappyRanch job. Never run it directly in the cleanup session and
never fall back to an in-session scan. A whole-worktree candidate is passed as
its own target. A literal node_modules/.venv cache candidate MUST
also resolve to its containing registered worktree so that use anywhere in that
worktree (for example a process whose cwd is a sibling src/) blocks even
though the cache directory itself is untouched:
The job carries the literal, shell-quoted command for the existing packaged
scripts/check_path_use.py, the active cleanup task/session binding, and a
unique receipt nonce. Submit it with the single-line happyranch jobs submit --from-file contract, wait with the same task/session binding, then consume
jobs show and jobs output. Authenticate the exact job id, task, agent,
session-bearing rationale, nonce/title, interpreter, workspace cwd, script,
fresh submission time, terminal status, exit code, complete stdout/stderr, and
scanner JSON. Only exact completed + exit 0 + empty stderr + matching target
clear_observation continues. Rejected, failed, timeout, output-cap, nonzero,
stale, mismatched, malformed, or missing output refuses without mutation.
For a whole-worktree candidate the containing worktree is the candidate itself,
so --containing-worktree may be omitted. For a cache candidate the helper
derives the deepest registered non-primary (linked) worktree containing the
target, excluding the primary checkout identified by Git's first porcelain
record (and never selecting an unregistered nested directory such as web/).
When supplied explicitly, it must match that canonical root. Missing,
tied-deepest, unregistered, or changed registration is unknown, never a
dirname fallback.
It returns exactly one of clear_observation, blocked, or unknown
(never safe), and exit 0 only for clear_observation.
- Complete same-user population (Linux). Every process running as your user must be
read, except confirmed-exited processes and the fixed login/session daemons
matched by an exact readable process name AND its exact bounded cgroup
role:
sshd-session in session-<N>.scope under your user slice;
systemd (the per-user manager) and (sd-pam) in
user@<UID>.service/init.scope;
ssh-agent in user@<UID>.service/app.slice/ssh-agent.service;
gpg-agent in user@<UID>.service/app.slice/gpg-agent.service;
gcr-ssh-agent or its ssh-agent child alias in
user@<UID>.service/app.slice/gcr-ssh-agent.service.
- Name alone, role alone, a unit/session lookalike, a generic
*.service/*agent wildcard, an arbitrary cgroup, or a different UID never
qualifies. A qualifying exception is deliberately not inspected:
unreadable exe/namespace does not veto it, and it is not proof the service
cannot use the path.
- Root-owned processes are outside the scan — never permission to run as root.
- Any other unreadable same-user process makes coverage
unknown ->
skip. A readable occupied non-exempt member is blocked. Positive use
blocks even when coverage is otherwise incomplete.
- An independently absent PID/TID
stat confirms that sampled process or
thread exited. If the corresponding stat remains readable, a missing,
unreadable, or incomplete status is an incomplete identity -> unknown,
not confirmed exit. An unparseable starttime, PID/TID reuse, or changed
real/effective/saved/fs credentials is also unknown.
- Per thread, the helper checks
cwd, root, exe, maps, and the private
FD table, and verifies cross-mount-namespace path identity. Every newly
admitted read/iteration — including each maps line and each FD entry — is
admitted against one shared deadline; an already admitted syscall is not
hard-preempted, and a scan that exhausts the deadline never claims success.