How to Sandbox Human Worktrees and Prune Orphaned Workspaces
This guide explains how human engineers can spawn conflict-free git worktrees for task development, safely integrate finished work into main under merge locks, and prune abandoned or orphaned worktrees without risking dirty local state.
Overview
SpecOps enforces git worktree isolation to guarantee that concurrent workers and human developers never modify shared backlog files on feature branches (ADR-0005). The spec-ops worktree and spec-ops rescue prune commands provide developer ergonomics that abstract low-level git worktree commands, configure UV environment symlinks automatically, and safeguard active uncommitted changes.
Step 1: Spawn a Clean Development Worktree
To pick up an unassigned task from docs/project/backlog/refined/, spawn an isolated worktree:
spec-ops worktree start TASK-0042
This command automatically:
- Validates that the task is in
refined/status and unblocked. - Creates an isolated directory at
.worktrees/task-0042. - Creates and checks out a dedicated branch (
feat/task-0042ortask/task-0042). - Links the root
.venvor UV workspace configuration so tools (pytest,spec-ops) work immediately. - Records the developer claim in task frontmatter on
main.
Navigate into the newly provisioned worktree:
cd .worktrees/task-0042
Step 2: Implement and Verify Changes in Isolation
Develop your changes using test-driven development. Run local verification inside the worktree:
uv run pytest
uv run spec-ops health
Your work is completely isolated from other branches and workers running concurrently.
Step 3: Finish and Integrate Under Merge Lock
Once all tests pass and documentation invariants are met, finalize the task from within the worktree directory:
spec-ops worktree finish
Or execute it from the repository root by specifying the task ID:
spec-ops worktree finish --task-id TASK-0042
The finish workflow:
- Runs full preflight validation (
uv lock --check,pytest,spec-ops health). - Acquires
MERGE_LOCKto ensure zero merge races against autonomous agent workers. - Automatically rebases onto
mainand squash-merges with structured RFC-822 trailers (SpecOps-Task: TASK-0042). - Atomically transitions the task file from
refined/tocomplete/and syncsPRIORITY.md. - Removes
.worktrees/task-0042and deletes the feature branch cleanly.
Step 4: Preview and Prune Orphaned Worktrees
Interrupted autonomous agent cycles or abandoned tasks can leave stale directories in .worktrees/.
Preview reclaimable disk space and candidate worktrees without making any changes:
spec-ops rescue prune --dry-run
Execute garbage collection to remove merged worktrees and dangling agent branches:
spec-ops rescue prune
Safety Protections
spec-ops rescue prune enforces strict safety invariants:
- Dirty State Guard: Any worktree containing uncommitted modifications or untracked files is skipped with a protective warning.
- Human Claim Guard: Worktrees claimed by human developers (
claimed_by: humanor active developer handles) are never pruned automatically. - Git Prune Sync: Automatically invokes
git worktree pruneto keep git internal metadata clean.
Step 5: Triage and Takeover Preserved Agent Worktrees
When an autonomous worker session exhausts its self-healing retries, its isolated worktree is preserved under .worktrees/task- with an automated HANDOVER.md debug brief.
- Automated Handover Brief (
HANDOVER.md): Contains task header metadata, attempt timeline (chronological summary with exit codes), isolated failure traceback, governing PRD/story/ADR hyperlinks, reproduction command, and completion command. Ephemeral handover files (HANDOVER.md,.task-prompt.md) are automatically excluded from git staging and purged during rescue completion. - Terminal Quickstart Cheatsheet: Inspect the worktree metadata and view an instant copy-paste developer cheatsheet: ``
bash spec-ops rescue TASK-0014 # or spec-ops rescue inspect TASK-0014`Displays high-contrast reproducer commands and rescue next steps:``text 🚀 Rescue Quickstart: - Jump into worktree: cd .worktrees/task-0014
- Reproduce failure: uv run pytest tests/test_curator.py -k test_buffer_sync
- Inspect changes: git diff HEAD
- Complete & merge: spec-ops rescue TASK-0014 --complete
- Discard & reset: spec-ops rescue reset TASK-0014 ```
- Interactive Failure Triage: Inspect categorized root causes (file length invariants, test suite failures, lockfile drift, git status) and AST diffs: ``
bash spec-ops rescue triage TASK-0012`` - Diagnostic Human Takeover: Transfer task claim from autonomous worker to human developer and provision workspace: ``
bash spec-ops rescue takeover TASK-0012`` - Verify and Finalize: Implement fixes inside
.worktrees/task-0012, then verify preflight and squash-merge intomain: ``bash spec-ops rescue TASK-0012 --complete``
Step 6: Rapid Iteration with Fast Incremental Preflight Runner
When troubleshooting a rescued worktree, rerunning the entire multi-minute preflight suite for each small change introduces significant latency. Use the incremental test runner to isolate broken checks:
- Re-run Only Failed Steps: Rerun only the previously failed check (skipping cached passes like lockfile validation and invariant checks): ``
bash spec-ops rescue test --only-failed`` - Isolate a Specific Preflight Step: Target an individual gate or check for sub-second feedback during iterative fixes: ``
bash spec-ops rescue test --step lint`` - Mandatory Full Revalidation on Completion: When completing rescue with
spec-ops rescue, incremental caches are automatically bypassed to enforce an un-truncated, full preflight run before merging into--complete main.
Step 7: Reset Broken Worktrees with Anti-Loop Failure Memory
If an agent's approach was fundamentally flawed (e.g. attempting internal mock backdoors violating ADR-0003 or monkey-patching libraries), wipe the worktree while capturing the failure post-mortem directly into task frontmatter:
spec-ops rescue reset TASK-0024 --reason "Agent attempted internal mock backdoors violating ADR-0003 instead of public CLI testing"
This safely deletes .worktrees/task-0024 and its feature branch, while appending a failure_history entry to the task file in refined/. Subsequent autonomous worker sessions will have their .task-prompt.md hydrated with explicit negative constraints:
## Prior Attempt Failures & Anti-Patterns (DO NOT REPEAT)
- Previous failure: Agent attempted internal mock backdoors violating ADR-0003 instead of public CLI testing.
- Mandate: You must strictly use public frontdoor entrypoints with zero mock backdoors.
Demoting Ambiguous Specifications
If the failure was caused by contradictory acceptance criteria or missing requirements, add --demote to move the task from refined/ back to proposed/ and update PRIORITY.md:
spec-ops rescue reset TASK-0030 --demote --reason "Contradictory Gherkin criteria in Scenario 2"