Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

agent-cli-worktree-safety

БесплатноБез исполняемых скриптовНе проверен

Data-loss invariants for a CLI that runs an agent SDK in a git worktree then force-removes it. Use when building or reviewing such a CLI, or when an agent run…

laurigatesот laurigates★ 61 звезда на GitHub

Об этом скилле

Agent-CLI Worktree Safety

Data-loss prevention for CLIs that create a git worktree, run an LLM orchestrator (claude-agent-sdk or similar) that writes files there, and then clean up with git worktree remove --force.

When to Use This Skill

Use this skill when... Use something else when...
Building or reviewing a CLI that runs an agent SDK in a worktree it later removes Isolating a Claude Code subagent with isolation: "worktree" → .claude/rules/agent-runtime.md § Worktree Isolation
An agent run wrote files but reported "No changes were made" Pruning other sessions' worktrees → .claude/rules/agent-coworker-detection.md § Cleanup
Wiring the SDK's two-phase or create_worktree flow → REFERENCE.md Coordinating parallel agents → agent-patterns-plugin:agent-teams

The core failure mode

Three independent mistakes compound into silent data loss:

  1. Driver phases write but never commit — "the outer orchestrator handles git state".
  2. The outer orchestrator ends without committing — it stalls on an interactive tool call that cannot render (see Interactive tools in SDK subprocess mode below), or simply finishes.
  3. The "has changes" check only counts commits (git log base..HEAD), so it reports nothing to preserve — and cleanup force-removes the worktree.

Net result: many files are written, the user is told "No changes were made", and the work is destroyed. No error, no traceback. That user-visible message is the diagnostic tell — if a run wrote files and reported no changes, check invariant 1 before anything else.

Required invariants

1. "Has changes" means commits OR a dirty tree

Any function deciding whether a worktree is worth preserving must return true when the working tree is dirty, even with no commits beyond base:

def worktree_has_changes(worktree_path, base_branch):
    commits = subprocess.run(
        ["git", "log", "--oneline", f"{base_branch}..HEAD"],
        cwd=worktree_path, capture_output=True, text=True,
    )
    if commits.stdout.strip():
        return True
    dirty = subprocess.run(
        ["git", "status", "--porcelain"],
        cwd=worktree_path, capture_output=True, text=True,
    )
    return bool(dirty.stdout.strip())

A commits-only check is a data-loss bug. --porcelain (not git diff) is load-bearing: a brand-new file the agent created is untracked, and git diff cannot see it.

If uncommitted files matter for the next operation — push, PR, cleanup — they matter for this check.

2. Safety-net commit before any destructive cleanup

If the agent phase was supposed to commit and didn't, capture the work anyway:

def auto_commit_if_dirty(worktree_path, message):
    status = subprocess.run(
        ["git", "status", "--porcelain"],
        cwd=worktree_path, capture_output=True, text=True, check=True,
    )
    if not status.stdout.strip():
        return False
    subprocess.run(["git", "add", "-A"], cwd=worktree_path, check=True)
    subprocess.run(
        ["git", "commit", "-m", message],
        cwd=worktree_path, check=True, capture_output=True, text=True,
    )
    return True

Call it from every post-run path — interactive and non-interactive — with a message naming the workflow, and print a warning so the user learns the safety net fired. A silent safety net hides the bug it is compensating for.

3. Pre-validate before git touches the path

Typer's exists=True, dir_okay=True is not enough. Call explicit guards at the top of every command that will later run git rev-parse, git worktree add, or a domain operation:

def _ensure_git_repo(path):
    inside = subprocess.run(
        ["git", "rev-parse", "--is-inside-work-tree"],
        cwd=path, capture_output=True, text=True,
    )
    if inside.returncode != 0 or inside.stdout.strip() != "true":
        raise typer.Exit(code=EXIT_CONFIG_ERROR)
    head = subprocess.run(
        ["git", "rev-parse", "--verify", "HEAD"],
        cwd=path, capture_output=True, text=True,
    )
    if head.returncode != 0:  # unborn HEAD — no commits yet
        raise typer.Exit(code=EXIT_CONFIG_ERROR)

Unborn HEAD is its own failure class. A fresh git init with no commits passes --is-inside-work-tree but fails every downstream rev-parse HEAD and worktree add -b <br> <path> HEAD. Check both, always.

Add a domain check beside it — an Obsidian vault wants .obsidian/ or any *.md; a code repo wants a language marker — so "pointed at the wrong directory" is a friendly config error, not a CalledProcessError traceback.

4. Branch-name collisions are not free

Timestamp branch names (%Y-%m-%dT%H-%M) collide when two runs start in the same minute. If create_worktree force-removes a pre-existing worktree at the target path, the second run destroys the first run's uncommitted agent output.

Either use second granularity plus a sh

Полный SKILL.md на GitHub

Установить agent-cli-worktree-safety в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Glob
Grep
Read
Edit
Write

Вложенные файлы

REFERENCE.md

FAQ

Что делает скилл agent-cli-worktree-safety?

Data-loss invariants for a CLI that runs an agent SDK in a git worktree then force-removes it. Use when building or reviewing such a CLI, or when an agent run reports "no changes" after writing files.

Как установить скилл agent-cli-worktree-safety?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл agent-cli-worktree-safety запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить agent-cli-worktree-safety с