Skip to content

flurdy/agent-skills / skills/beads

Shared Beads workflow baseline. Use whenever an agent uses `bd`, manages durable tasks, blockers, or handoffs, resolves work ownership, or decides between an ephemeral checklist and durable tracking. Covers store authority and remote Dolt safety.

scripts/integration_cleanup.py

View on GitHub
#!/usr/bin/env python3
"""Fail-closed preview of bd integration removal, gated by a sandbox self-test of the installed bd."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
import sys
import tempfile

MAX_BYTES = 262144
MAX_HOOK_FILES = 128
HOOK_NAMES = ("pre-commit", "post-merge", "pre-push", "post-checkout", "prepare-commit-msg")
CLAUDE_COMMANDS = {"bd prime", "bd prime --stealth", "bd prime --hook-json", "bd prime --stealth --hook-json"}
CODEX_EVENTS = ("SessionStart", "PreCompact", "PostCompact", "UserPromptSubmit")
GENERATED_CODEX_FILES = (".codex/config.toml", ".codex/hooks.json", ".agents/skills/beads/SKILL.md", ".agents/skills/beads/agents/openai.yaml")
TEMPLATE_FILES = tuple(path for path in GENERATED_CODEX_FILES if path.startswith(".agents/"))
NATIVE_ACTIONS = ("claude", "codex-native", "hooks")
IGNORE_INTERACTIONS = "/.beads/interactions.jsonl"
MARKERS = {
    "general": (r"<!-- BEGIN BEADS INTEGRATION(?: v:[^\r\n]*?)? -->", re.escape("<!-- END BEADS INTEGRATION -->")),
    "codex": (re.escape("<!-- BEGIN BEADS CODEX SETUP: generated by bd setup codex -->"), re.escape("<!-- END BEADS CODEX SETUP -->")),
    "hook": (r"# --- BEGIN BEADS INTEGRATION v[0-9][^\r\n]*? ---", r"# --- END BEADS INTEGRATION v[0-9][^\r\n]*? ---"),
}


def digest(data):
    return hashlib.sha256(data).hexdigest()


def execute(argv, cwd=None, allowed=(0,)):
    env = dict(os.environ, GIT_OPTIONAL_LOCKS="0", BD_DISABLE_METRICS="1", BD_DISABLE_EVENT_FLUSH="1")
    result = subprocess.run(argv, cwd=cwd, env=env, capture_output=True, timeout=10, check=False)
    if result.returncode not in allowed or len(result.stdout) > MAX_BYTES or len(result.stderr) > MAX_BYTES:
        raise ValueError("read-only command failed or exceeded its output bound: " + Path(argv[0]).name)
    return result.stdout.decode("utf-8", errors="strict").strip()


def git(root, *args, allowed=(0,)):
    return execute(["git", "-c", "core.fsmonitor=false", "-C", str(root), *args], allowed=allowed)


def bd_probe():
    binary = shutil.which("bd")
    if not binary:
        return {"supported": False, "reason": "bd unavailable"}
    binary = str(Path(binary).resolve(strict=True))
    try:
        version = execute([binary, "--version"])
        version_match = re.match(r"^bd version (\S+)", version)
        supported = bool(version_match)
        for command, tokens in [
            (["init", "--help"], ["--skip-agents", "--skip-hooks"]),
            (["setup", "--help"], ["--remove", "--global"]),
            (["hooks", "uninstall", "--help"], ["Remove bd git hooks", "uninstall"]),
        ]:
            help_text = execute([binary, *command])
            supported = supported and all(token in help_text for token in tokens)
        env_binary = shutil.which("env")
        if not env_binary or "--chdir" not in execute([env_binary, "--help"]):
            supported = False
        with open(binary, "rb") as stream:
            hasher = hashlib.sha256()
            for chunk in iter(lambda: stream.read(65536), b""):
                hasher.update(chunk)
        return {"executable": binary, "version": version_match[1] if version_match else "unknown",
                "sha256": hasher.hexdigest(), "envExecutable": str(Path(env_binary).resolve()) if env_binary else None,
                "supported": supported}
    except (OSError, ValueError, subprocess.SubprocessError):
        return {"executable": binary, "supported": False, "reason": "bd version/help probe unavailable"}


class Sandbox:
    """Disposable repository and HOME for characterizing the installed bd; never touches real state."""

    def __init__(self, tool):
        self.tool = tool
        self.temp = tempfile.TemporaryDirectory(prefix="beads-cleanup-selftest-")
        base = Path(self.temp.name)
        self.repo, self.home = base / "repo", base / "home"
        self.repo.mkdir()
        self.home.mkdir()
        self.env = {"PATH": os.environ.get("PATH", ""), "HOME": str(self.home), "XDG_CONFIG_HOME": str(self.home / ".config"),
                    "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_TERMINAL_PROMPT": "0",
                    "BD_DISABLE_METRICS": "1", "BD_DISABLE_EVENT_FLUSH": "1", "BD_BACKUP_ENABLED": "false",
                    "BD_EXPORT_AUTO": "false", "BD_NO_PUSH": "true", "BD_NO_GIT_OPS": "true",
                    "BEADS_DIR": str(self.repo / ".beads")}
        self.run(["git", "init", "-q", "-b", "main"])
        (self.repo / ".beads").mkdir(mode=0o700)
        self.put(".beads/config.yaml", "metrics:\n  disabled: true\nbackup:\n  enabled: false\n")

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.temp.cleanup()

    def put(self, name, content):
        path = self.repo / name
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(content)
        return path

    def text(self, name):
        path = self.repo / name
        return path.read_text() if path.is_file() else None

    def run(self, argv):
        return subprocess.run(argv, cwd=self.repo, env=self.env, capture_output=True, text=True, timeout=20, check=False)

    def bd(self, *args):
        return self.run([self.tool["executable"], "-C", str(self.repo), "--sandbox", *args])

    def native(self, action_id):
        return self.run(native_argv(self.tool, self.repo, action_id))


def native_argv(tool, root, action_id):
    env_binary = tool.get("envExecutable") or shutil.which("env") or "env"
    argv = [str(Path(env_binary).resolve()), "--chdir=" + str(root), "BD_DISABLE_METRICS=1", "BD_DISABLE_EVENT_FLUSH=1",
            tool.get("executable", "bd"), "-C", str(root), "--sandbox"]
    recipe = action_id.removesuffix("-native")
    return argv + (["hooks", "uninstall"] if recipe == "hooks" else ["setup", recipe, "--remove", "--global=false"])


_GENERATED = {}


def generated_codex(tool):
    """Hashes of what the installed bd generates for `setup codex`, so ownership proof follows the binary."""
    key = tool.get("sha256")
    if key not in _GENERATED:
        with Sandbox(tool) as box:
            result = box.bd("setup", "codex")
            if result.returncode != 0:
                raise ValueError("sandbox bd setup codex failed")
            files = {name: digest((box.repo / name).read_bytes()) for name in GENERATED_CODEX_FILES if (box.repo / name).is_file()}
            spans, _ = block_ranges(box.text("AGENTS.md") or "", "codex")
            block = digest(box.text("AGENTS.md")[spans[0]["start"]:spans[0]["end"]].encode()) if spans else None
        _GENERATED[key] = {"files": files, "block": block}
    return _GENERATED[key]


def self_test(tool, action_id):
    """Run the selected native remover against a sandbox fixture and return every broken assumption."""
    failures = []
    block = "<!-- BEGIN BEADS INTEGRATION -->\nfixture\n<!-- END BEADS INTEGRATION -->\n"
    with Sandbox(tool) as box:
        if action_id == "claude":
            authored = {"type": "command", "command": "run-project-check"}
            settings = {"permissions": {"deny": ["x"]}, "hooks": {"SessionStart": [{"matcher": "", "hooks": [
                authored, {"type": "command", "command": "bd prime --hook-json"}]}]}}
            box.put("CLAUDE.md", "before\n" + block + "after\n")
            for name in (".claude/settings.json", ".claude/settings.local.json"):
                box.put(name, json.dumps(settings))
            sentinel = box.home / ".claude/settings.json"
            sentinel.parent.mkdir()
            sentinel.write_text("global sentinel")
            result = box.native("claude")
            if result.returncode != 0 or "Warning" in result.stderr:
                failures.append("remover exited non-zero or warned")
            if box.text("CLAUDE.md") != "before\nafter\n":
                failures.append("CLAUDE.md authored text not preserved exactly")
            for name in (".claude/settings.json", ".claude/settings.local.json"):
                data = json.loads(box.text(name) or "{}")
                if data.get("permissions") != settings["permissions"] or data.get("hooks", {}).get("SessionStart", [{}])[0].get("hooks") != [authored]:
                    failures.append(name + ": sibling hooks or unrelated properties not preserved")
            if sentinel.read_text() != "global sentinel":
                failures.append("project removal touched global settings")
        elif action_id == "codex-native":
            box.put("AGENTS.md", "authored\n")
            if box.bd("setup", "codex").returncode != 0:
                failures.append("sandbox bd setup codex failed")
            result = box.native("codex-native")
            if result.returncode != 0:
                failures.append("remover exited non-zero")
            if (box.text("AGENTS.md") or "").strip() != "authored":
                failures.append("AGENTS.md authored text not preserved")
            for name in (".codex/hooks.json", *TEMPLATE_FILES):
                if (box.repo / name).exists():
                    failures.append(name + ": generated file survived removal")
        elif action_id == "hooks":
            if box.bd("hooks", "install", "--beads").returncode != 0:
                failures.append("sandbox bd hooks install failed")
            hook = box.repo / ".beads/hooks/pre-commit"
            text = hook.read_text() if hook.is_file() else ""
            if not block_ranges(text, "hook")[0]:
                failures.append("installed hook markers are not recognized")
            hook.write_text(text + "\nrun-project-check\n")
            if box.native("hooks").returncode != 0:
                failures.append("remover exited non-zero")
            remaining = hook.read_text() if hook.is_file() else ""
            if "run-project-check" not in remaining or "BEADS INTEGRATION" in remaining:
                failures.append("managed hook block not removed or authored hook content lost")
            if box.run(["git", "config", "--get", "core.hooksPath"]).returncode != 1:
                failures.append("core.hooksPath not unset")
    return failures


def block_ranges(text, kind):
    begin, end = MARKERS[kind]
    begins = list(re.finditer("^" + begin + r"\r?$", text, re.MULTILINE))
    ends = list(re.finditer("^" + end + r"\r?$", text, re.MULTILINE))
    prefix = {"general": "<!-- BEGIN BEADS INTEGRATION", "codex": "<!-- BEGIN BEADS CODEX", "hook": "# --- BEGIN BEADS INTEGRATION"}[kind]
    if not begins and not ends and prefix not in text:
        return [], None
    if len(begins) != 1 or len(ends) != 1 or text.count(prefix) != 1 or begins[0].end() >= ends[0].start():
        return [], "malformed, duplicate or unsupported " + kind + " markers"
    start, finish = begins[0].start(), ends[0].end()
    cleanup_start = start
    if start > 0 and text[start - 1] == "\n":
        previous_line_start = text.rfind("\n", 0, start - 1) + 1
        if not text[previous_line_start:start - 1].strip():
            cleanup_start = previous_line_start
    return [{"startLine": text.count("\n", 0, start) + 1,
             "cleanupStartLine": text.count("\n", 0, cleanup_start) + 1,
             "endLine": text.count("\n", 0, finish) + 1,
             "start": start, "cleanupStart": cleanup_start, "end": finish}], None


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate JSON key")
        result[key] = value
    return result


def hook_config(text, codex=False):
    data = json.loads(text, object_pairs_hook=unique_object)
    if not isinstance(data, dict) or not isinstance(data.get("hooks", {}), dict):
        raise ValueError("malformed hooks object")
    count, mixed, unknown = 0, False, False
    events = CODEX_EVENTS if codex else ("SessionStart", "PreCompact")
    for event, entries in data.get("hooks", {}).items():
        if not isinstance(entries, list):
            raise ValueError("malformed hook event")
        for entry in entries:
            if not isinstance(entry, dict) or not isinstance(entry.get("hooks"), list) or not entry["hooks"]:
                raise ValueError("malformed or empty hook entry")
            managed = 0
            for command in entry["hooks"]:
                if not isinstance(command, dict) or not isinstance(command.get("command"), str):
                    raise ValueError("malformed hook command")
                value = command["command"]
                match = value.startswith("bd codex-hook ") if codex else value in CLAUDE_COMMANDS
                if match and event in events:
                    if command.get("type") != "command":
                        raise ValueError("ambiguous hook command type")
                    managed += 1
                elif "bd " in value:
                    unknown = True
            count += managed
            mixed = mixed or (0 < managed < len(entry["hooks"]))
    return count, mixed, unknown, "hooks" in data


def bounded_tree(root, relative):
    base = root / relative
    if not base.exists():
        return set(), []
    problems, entries = [], set()
    if base.is_symlink() or not base.is_dir():
        return entries, [relative + ": expected an ordinary directory"]
    for directory, names, files in os.walk(base, followlinks=False):
        if len(entries) + len(names) + len(files) > MAX_HOOK_FILES:
            problems.append(relative + ": generated tree exceeds entry bound")
            break
        current = Path(directory)
        for name in names + files:
            path = current / name
            item = path.relative_to(root).as_posix()
            entries.add(item)
            if path.is_symlink():
                problems.append(item + ": linked generated-tree entry")
    return entries, problems


class Inventory:
    def __init__(self, root):
        self.root = root
        self.rows = {}
        self.text = {}

    def read(self, name):
        if name in self.rows:
            return self.rows[name]
        path = self.root / name
        row = {"path": name, "kind": "missing", "sha256": None}
        self.rows[name] = row
        try:
            canonical = path.resolve(strict=False)
            if not canonical.is_relative_to(self.root):
                raise ValueError("out-of-repository target")
            row["canonical"] = str(canonical)
            linked = any(p.is_symlink() for p in (path, *path.parents) if p != self.root and p.is_relative_to(self.root))
            if linked:
                row["problem"] = "symlink mutation footprint is unsupported"
            if not path.exists():
                if path.is_symlink():
                    raise ValueError("dangling symlink")
                return row
            info = path.stat()
            row.update(kind="file", mode=stat.S_IMODE(info.st_mode), links=info.st_nlink)
            if not stat.S_ISREG(info.st_mode):
                raise ValueError("non-regular file")
            if info.st_nlink != 1:
                row["problem"] = "hardlinked mutation footprint is unsupported"
            if info.st_size > MAX_BYTES:
                raise ValueError("file exceeds byte bound")
            raw = path.read_bytes()
            if len(raw) > MAX_BYTES:
                raise ValueError("file exceeds byte bound")
            row.update(sha256=digest(raw), bytes=len(raw))
            self.text[name] = raw.decode("utf-8", errors="strict")
        except (OSError, RuntimeError, ValueError) as error:
            row["problem"] = str(error) if isinstance(error, ValueError) else "unavailable file identity/content"
        return row

    def files(self):
        groups = {}
        for name, row in self.rows.items():
            key = row.get("canonical", name)
            if key not in groups:
                groups[key] = {**row, "aliases": []}
            groups[key]["aliases"].append(name)
            if row.get("problem"):
                groups[key]["problem"] = row["problem"]
        return sorted(groups.values(), key=lambda item: item["path"])


def inspect_repository(repository):
    if any(os.environ.get(key) for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_CONFIG_PARAMETERS", "BEADS_DIR")):
        raise ValueError("ambient Git/Beads location overrides are unsupported")
    count = int(os.environ.get("GIT_CONFIG_COUNT", "0"))
    if not 0 <= count <= 32 or any(
        os.environ.get(f"GIT_CONFIG_KEY_{i}", "").lower() not in ("credential.interactive", "credential.guiprompt")
        or os.environ.get(f"GIT_CONFIG_VALUE_{i}", "").lower() not in ("false", "never", "0")
        for i in range(count)
    ):
        raise ValueError("ambient Git config override is unsupported")
    root = Path(repository).expanduser().resolve(strict=True)
    if root != Path(git(root, "rev-parse", "--show-toplevel")).resolve():
        raise ValueError("select the exact repository root, not a subdirectory")
    inventory = Inventory(root)
    issues = []
    config = git(root, "config", "--local", "--no-includes", "--name-only", "--get-regexp", r"^(include.*\.path|extensions\.worktreeconfig)$", allowed=(0, 1))
    if config:
        issues.append("local Git includes/worktree config are unsupported")
    git_dir = Path(git(root, "rev-parse", "--absolute-git-dir"))
    if (root / ".git").is_symlink() or not (root / ".git").is_dir() or git_dir.resolve() != root / ".git" or (git_dir / "worktrees").exists():
        issues.append("shared, redirected or linked Git administration is unsupported")
    config_row = inventory.read(".git/config")
    if config_row.get("problem"):
        issues.append(".git/config: " + config_row["problem"])
    if (root / ".beads").is_symlink() or os.path.lexists(root / ".beads/redirect"):
        issues.append("linked or redirected Beads storage: no integration removal proposed")
    tool = bd_probe()
    if not tool.get("supported"):
        issues.append("bd unavailable or missing the removal commands/help this helper relies on")
    residuals, actions = [], []

    def action(name, paths, needed, effects, reasons):
        for filename in paths:
            row = inventory.read(filename)
            if row.get("problem"):
                reasons.append(filename + ": " + row["problem"])
        reasons = list(dict.fromkeys([*issues, *reasons]))
        if not (tool.get("envExecutable") or shutil.which("env")):
            reasons.append("env executable with --chdir support is unavailable")
        status = "blocked" if reasons else "ready" if needed else "clean"
        argv = native_argv(tool, root, name)
        actions.append({"id": name, "mechanism": "bd-native", "status": status, "argv": argv if status == "ready" else None,
                        "effects": effects, "reasons": reasons, "requires": ["passing sandbox self-test (--action)", "source scope", "backup/recovery evidence", "fresh per-command confirmation", "post-command verification"]})

    ranges = {}
    for filename in ("AGENTS.md", "CLAUDE.md"):
        row = inventory.read(filename)
        for kind in ("general", "codex"):
            spans, error = block_ranges(inventory.text.get(filename, ""), kind)
            ranges[filename, kind] = spans
            if error:
                row["problem"] = error
            if spans:
                row[kind + "Blocks"] = [{k: v for k, v in span.items() if k.endswith("Line")} for span in spans]

    agents_effects, agents_reasons = [], [*issues]
    for kind, operation in (("general", "remove exact general managed block"), ("codex", "remove exact Codex managed block")):
        if ranges["AGENTS.md", kind]:
            agents_effects.append({"path": "AGENTS.md", "operation": operation,
                                   "lines": inventory.rows["AGENTS.md"].get(kind + "Blocks")})
    if inventory.rows["AGENTS.md"].get("problem"):
        agents_reasons.append("AGENTS.md: " + inventory.rows["AGENTS.md"]["problem"])
    agents_status = "blocked" if agents_reasons else "ready" if agents_effects else "clean"
    actions.append({"id": "agents-blocks", "mechanism": "confirmed-native-edit", "status": agents_status,
                    "argv": None, "effects": agents_effects, "reasons": list(dict.fromkeys(agents_reasons)),
                    "requires": ["shared replacement guidance confirmed", "source scope", "backup/recovery evidence", "fresh confirmation", "exact old/new preview", "post-edit verification"]})

    claude_paths = ["CLAUDE.md", ".claude/settings.json", ".claude/settings.local.json"]
    effects, reasons = [], []
    needed = bool(ranges["CLAUDE.md", "general"])
    if needed:
        effects.append({"path": "CLAUDE.md", "operation": "remove general managed block", "lines": inventory.rows["CLAUDE.md"].get("generalBlocks")})
    for filename in claude_paths[1:]:
        row = inventory.read(filename)
        if filename in inventory.text:
            try:
                count, _, unknown, has_hooks = hook_config(inventory.text[filename])
                row["managedCommands"] = count
                needed = needed or count > 0
                if has_hooks:
                    effects.append({"path": filename, "operation": "rewrite hook JSON; remove exact bd prime commands, preserve siblings", "removedCommands": count})
                if unknown:
                    residuals.append({"path": filename, "reason": "nonstandard bd hook commands remain"})
            except ValueError:
                reasons.append(filename + ": malformed or ambiguous hook JSON")
    action("claude", claude_paths, needed, effects, reasons)

    codex_paths = ["AGENTS.md", ".codex/config.toml", ".codex/hooks.json", *TEMPLATE_FILES]
    codex_present = any((root / name).exists() for name in GENERATED_CODEX_FILES) or bool(ranges["AGENTS.md", "codex"])
    generated, generation_problems = {"files": {}, "block": None}, []
    if codex_present and tool.get("supported"):
        try:
            generated = generated_codex(tool)
        except (OSError, ValueError, subprocess.SubprocessError):
            generation_problems.append("sandbox generation of Codex templates failed: ownership unprovable")
    effects, reasons = [], [*generation_problems]
    needed = bool(ranges["AGENTS.md", "codex"])
    if needed:
        effects.append({"path": "AGENTS.md", "operation": "remove Codex managed block only", "lines": inventory.rows["AGENTS.md"].get("codexBlocks")})
    if inventory.read(".codex/config.toml")["kind"] != "missing":
        reasons.append(".codex/config.toml exists: native removal may disable shared hook feature flags; no safe scoped remover")
    for filename in TEMPLATE_FILES:
        row = inventory.read(filename)
        if row["kind"] != "missing":
            needed = True
            if row.get("sha256") != generated["files"].get(filename):
                reasons.append(filename + ": generated template ownership is unproven")
            effects.append({"path": filename, "operation": "delete file matching installed bd output; prune empty skill ancestors"})
    row = inventory.read(".codex/hooks.json")
    if ".codex/hooks.json" in inventory.text:
        try:
            count, mixed, unknown, _ = hook_config(inventory.text[".codex/hooks.json"], codex=True)
            needed = needed or count > 0
            if mixed:
                reasons.append(".codex/hooks.json: native removal would delete sibling non-Beads commands")
            if unknown:
                reasons.append(".codex/hooks.json: nonstandard bd commands need separate review")
            effects.append({"path": ".codex/hooks.json", "operation": "remove managed entries; delete file if empty, otherwise rewrite JSON", "removedCommands": count})
        except ValueError:
            reasons.append(".codex/hooks.json: malformed or ambiguous hook JSON")
    action("codex-native", codex_paths, needed, effects, reasons)

    generated_effects, generated_reasons = [], [*issues, *generation_problems]
    codex_entries, codex_tree_problems = bounded_tree(root, ".codex")
    skill_entries, skill_tree_problems = bounded_tree(root, ".agents/skills/beads")
    generated_reasons.extend(codex_tree_problems + skill_tree_problems)
    expected_codex_entries = {".codex/config.toml", ".codex/hooks.json"}
    expected_skill_entries = {".agents/skills/beads/SKILL.md", ".agents/skills/beads/agents", ".agents/skills/beads/agents/openai.yaml"}
    if codex_entries - expected_codex_entries:
        generated_reasons.append(".codex contains non-generated or unexpected entries")
    if skill_entries - expected_skill_entries:
        generated_reasons.append(".agents/skills/beads contains non-generated or unexpected entries")
    for filename in GENERATED_CODEX_FILES:
        row = inventory.read(filename)
        if row["kind"] != "missing":
            generated_effects.append({"path": filename, "operation": "delete file matching installed bd output"})
            if row.get("sha256") != generated["files"].get(filename):
                generated_reasons.append(filename + ": generated ownership hash mismatch")
    if ranges["AGENTS.md", "codex"]:
        span = ranges["AGENTS.md", "codex"][0]
        block = inventory.text["AGENTS.md"][span["start"]:span["end"]]
        if digest(block.encode()) != generated["block"]:
            generated_reasons.append("AGENTS.md: Codex managed block does not match checked bd output")
    local_skill = root / ".agents/skills/beads"
    global_skill = Path.home() / ".agents/skills/beads"
    if local_skill.exists() and global_skill.exists():
        local_info, global_info = local_skill.stat(), global_skill.stat()
        if local_skill.resolve() == global_skill.resolve() or (local_info.st_dev, local_info.st_ino) == (global_info.st_dev, global_info.st_ino):
            generated_reasons.append("project generated skill aliases the global skill installation")
    generated_status = "blocked" if generated_reasons else "ready" if generated_effects else "clean"
    actions.append({"id": "codex-generated", "mechanism": "confirmed-exact-delete", "status": generated_status,
                    "argv": None, "effects": generated_effects, "reasons": list(dict.fromkeys(generated_reasons)),
                    "pruneEmptyDirectories": [".codex", ".agents/skills/beads/agents", ".agents/skills/beads", ".agents/skills", ".agents"],
                    "requires": ["agents-blocks selected or Codex block already absent", "source scope", "verified private backup hashes", "fresh confirmation", "one visible exact-file deletion command", "post-delete verification"]})

    effects, reasons, paths, needed = [], [], [], False
    hooks_config = git(root, "config", "--show-scope", "--show-origin", "--get-all", "core.hooksPath", allowed=(0, 1))
    hook_dir = Path(git(root, "rev-parse", "--git-path", "hooks"))
    if not hook_dir.is_absolute():
        hook_dir = root / hook_dir
    if any(not line.startswith("local\t") for line in hooks_config.splitlines()) or len(hooks_config.splitlines()) > 1:
        reasons.append("inherited or multiple hooksPath values: fallback integration cannot be proven safe")
    if not hook_dir.resolve().is_relative_to(root):
        reasons.append("hook directory is outside the selected repository")
    else:
        relative = hook_dir.relative_to(root).as_posix()
        if relative not in (".git/hooks", ".beads/hooks", ".beads-hooks"):
            reasons.append("custom hooksPath has no verified removal contract")
        resets = relative in (".beads/hooks", ".beads-hooks")
        literal_hook_path = hooks_config.split("\t")[-1] if hooks_config else ""
        if resets and literal_hook_path not in (relative, str(root / relative)):
            reasons.append("noncanonical hooksPath spelling: native reset is not verified")
        dirs = list(dict.fromkeys([relative, ".git/hooks"]))
        for directory in dirs:
            directory_path = root / directory
            if any(p.is_symlink() for p in (directory_path, *directory_path.parents) if p != root and p.is_relative_to(root)):
                reasons.append(directory + ": linked hooks directory")
                continue
            if directory_path.exists() and not directory_path.is_dir():
                reasons.append(directory + ": invalid hook directory")
                continue
            entries = sorted(directory_path.iterdir()) if directory_path.is_dir() else []
            if len(entries) > MAX_HOOK_FILES:
                reasons.append(directory + ": hook inventory exceeds bound")
                continue
            for entry in entries:
                filename = entry.relative_to(root).as_posix()
                paths.append(filename)
                row = inventory.read(filename)
                text = inventory.text.get(filename, "")
                if entry.name.endswith((".old", ".backup")):
                    reasons.append(filename + ": chain/backup may become unreachable")
                if directory != relative:
                    if resets and not entry.name.endswith(".sample"):
                        reasons.append(filename + ": unsetting hooksPath would activate an existing fallback hook")
                    continue
                spans, error = block_ranges(text, "hook")
                if error or (not spans and any(marker in text for marker in ("# bd-shim ", "# bd-hooks-version:", "# bd (beads)"))):
                    reasons.append(filename + ": malformed/legacy hook removal is unsupported")
                if spans and entry.name in HOOK_NAMES:
                    needed = True
                    remaining = text[:spans[0]["start"]] + text[spans[0]["end"]:]
                    pure = remaining.strip() in ("", "#!/bin/sh", "#!/usr/bin/env sh")
                    effects.append({"path": filename, "operation": "delete pure Beads hook" if pure else "strip managed block; preserve project hook"})
                    if resets and not pure:
                        reasons.append(filename + ": unsetting hooksPath would disable preserved project checks")
                elif resets:
                    reasons.append(filename + ": unsetting hooksPath would strand non-managed content")
                elif spans:
                    residuals.append({"path": filename, "reason": "hook is outside the owning tool removal set"})
        if resets:
            needed = True
            effects.append({"path": ".git/config", "operation": "unset local core.hooksPath; reactivate default .git/hooks"})
    action("hooks", paths, needed, effects, reasons)

    ignore_paths = [".gitignore", ".beads/.gitignore", ".beads/interactions.jsonl"]
    ignore_reasons = [*issues]
    for filename in ignore_paths:
        row = inventory.read(filename)
        if row.get("problem"):
            ignore_reasons.append(filename + ": " + row["problem"])
    root_ignore = inventory.text.get(".gitignore", "")
    beads_ignore = inventory.text.get(".beads/.gitignore", "")
    rule_present = any(line.strip() == IGNORE_INTERACTIONS for line in root_ignore.splitlines())
    if any(line.lstrip().startswith("!") for line in beads_ignore.splitlines()):
        ignore_reasons.append(".beads/.gitignore contains negation rules; ignore precedence needs manual review")
    tracked = bool(git(root, "ls-files", "--", ".beads/interactions.jsonl", allowed=(0, 1)))
    if tracked and inventory.rows[".beads/interactions.jsonl"]["kind"] == "missing":
        ignore_reasons.append("tracked interactions file is absent; local retention cannot be proven")
    ignore_effects = []
    interactions_present = inventory.rows[".beads/interactions.jsonl"]["kind"] != "missing"
    if not rule_present and (tracked or interactions_present):
        ignore_effects.append({"path": ".gitignore", "operation": "add anchored ignore rule", "rule": IGNORE_INTERACTIONS})
    if tracked:
        ignore_effects.append({"path": ".beads/interactions.jsonl", "operation": "remove from Git index only; retain local file"})
    ignore_status = "blocked" if ignore_reasons else "ready" if ignore_effects else "clean"
    actions.append({"id": "interactions-ignore", "mechanism": "confirmed-native-edit-and-git-index", "status": ignore_status,
                    "argv": None, "indexArgv": ["git", "-C", str(root), "rm", "--cached", "--", ".beads/interactions.jsonl"] if tracked else None,
                    "ignoreRule": IGNORE_INTERACTIONS, "effects": ignore_effects, "reasons": list(dict.fromkeys(ignore_reasons)),
                    "requires": ["source scope", "backup/recovery evidence", "fresh confirmation before index mutation", "git check-ignore --no-index cites root rule", "local file retained", "post-change status verification"]})

    for name in (".beads/recipes.toml", ".gemini/settings.json", ".cursor/rules/beads.mdc", ".github/copilot-instructions.md", ".aider.conf.yml"):
        row = inventory.read(name)
        if row["kind"] != "missing" or row.get("problem"):
            residuals.append({"path": name, "reason": "other/custom client integration: inspection only, no verified removal action"})
    report = {"schemaVersion": "beads-integration-cleanup/v1", "repository": str(root), "bd": tool,
              "files": inventory.files(), "actions": actions, "residuals": residuals,
              "hooksConfig": hooks_config, "readOnly": True, "inspectorSha256": digest(Path(__file__).read_bytes())}
    report["fingerprint"] = digest(json.dumps(report, sort_keys=True).encode())
    return report


def strip_prime_hooks(data):
    """Remove the exact `bd prime` commands from SessionStart/PreCompact; drop entries/events left empty."""
    removed = 0
    hooks = data.get("hooks", {})
    for event in ("SessionStart", "PreCompact"):
        kept_entries = []
        for entry in hooks.get(event, []):
            kept = [c for c in entry["hooks"] if not (c.get("type") == "command" and c.get("command") in CLAUDE_COMMANDS)]
            removed += len(entry["hooks"]) - len(kept)
            if kept:
                kept_entries.append({**entry, "hooks": kept})
        if event in hooks:
            if kept_entries:
                hooks[event] = kept_entries
            else:
                del hooks[event]
    return removed


def inspect_global():
    home = Path.home().resolve(strict=True)
    inventory = Inventory(home)
    residuals, effects, reasons = [], [], []
    settings = ".claude/settings.json"
    row = inventory.read(settings)
    if row.get("problem"):
        reasons.append(settings + ": " + row["problem"])
    needed = False
    if settings in inventory.text:
        try:
            count, _, unknown, _ = hook_config(inventory.text[settings])
            row["managedCommands"] = count
            needed = count > 0
            if needed:
                effects.append({"path": "~/" + settings, "operation": "remove exact bd prime commands; drop emptied entries/events; preserve everything else", "removedCommands": count})
            if unknown:
                residuals.append({"path": "~/" + settings, "reason": "nonstandard bd hook commands remain"})
        except ValueError:
            reasons.append(settings + ": malformed or ambiguous hook JSON")
    codex_home = Path(os.environ.get("CODEX_HOME") or home / ".codex")
    for path, marker in ((codex_home / "hooks.json", "bd codex-hook "), (home / ".gemini/settings.json", "bd prime"), (home / ".cursor/hooks.json", "bd prime")):
        try:
            if not path.is_file() or path.stat().st_size > MAX_BYTES:
                continue
            text = path.read_text(encoding="utf-8")
        except (OSError, UnicodeDecodeError):
            residuals.append({"path": str(path), "reason": "unreadable global client settings"})
            continue
        if marker in text:
            residuals.append({"path": str(path), "reason": "global Beads hooks for another client: inspection only, no verified removal action"})
    status = "blocked" if reasons else "ready" if needed else "clean"
    actions = [{"id": "claude-global", "mechanism": "helper-json-filter", "status": status,
                "apply": [sys.executable, str(Path(__file__).resolve()), "--global", "--expect", "FINGERPRINT",
                          "--apply", "claude-global", "--backup-dir", "PRIVATE_DIR"] if status == "ready" else None,
                "effects": effects, "reasons": reasons,
                "requires": ["fresh confirmation", "private backup directory", "post-apply verification"]}]
    report = {"schemaVersion": "beads-integration-cleanup/v1", "scope": "global", "home": str(home),
              "files": inventory.files(), "actions": actions, "residuals": residuals,
              "readOnly": True, "inspectorSha256": digest(Path(__file__).read_bytes())}
    report["fingerprint"] = digest(json.dumps(report, sort_keys=True).encode())
    return report


def apply_global_claude(report, backup_dir):
    """The helper's only write: back up, then atomically rewrite ~/.claude/settings.json without bd prime hooks."""
    if report["actions"][0]["status"] != "ready":
        raise ValueError("claude-global is not ready; nothing written")
    backup = Path(backup_dir).expanduser().resolve(strict=True)
    if not backup.is_dir() or stat.S_IMODE(backup.stat().st_mode) & 0o077:
        raise ValueError("--backup-dir must be an existing directory private to the user (mode 0700)")
    path = Path(report["home"]) / ".claude/settings.json"
    raw = path.read_bytes()
    mode = stat.S_IMODE(path.stat().st_mode)
    saved = backup / ("claude-settings." + digest(raw)[:16] + ".json")
    fd = os.open(saved, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "wb") as stream:
        stream.write(raw)
    data = json.loads(raw, object_pairs_hook=unique_object)
    removed = strip_prime_hooks(data)
    fd, temporary = tempfile.mkstemp(prefix=".settings.", dir=path.parent)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as stream:
            stream.write(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
        os.chmod(temporary, mode)
        os.replace(temporary, path)
    except BaseException:
        os.unlink(temporary)
        raise
    after = inspect_global()
    return {"applied": "claude-global", "removedCommands": removed, "backup": str(saved),
            "status": after["actions"][0]["status"], "readOnly": False}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    scope = parser.add_mutually_exclusive_group(required=True)
    scope.add_argument("--repo", help="exact repository root (never recursive)")
    scope.add_argument("--global", dest="global_scope", action="store_true", help="inspect user-level client settings")
    parser.add_argument("--expect", help="require unchanged prior fingerprint; not an approval token")
    parser.add_argument("--action", choices=("agents-blocks", "claude", "claude-global", "codex-native", "codex-generated", "hooks", "interactions-ignore"),
                        help="require this proposal to be ready and, for native removers, pass a sandbox self-test; never execute it")
    parser.add_argument("--apply", choices=("claude-global",), help="perform the global Claude hook removal (requires --global, --expect, --backup-dir)")
    parser.add_argument("--backup-dir", help="existing private directory for the pre-apply backup")
    args = parser.parse_args()
    try:
        if args.apply and not (args.global_scope and args.expect and args.backup_dir):
            raise ValueError("--apply requires --global, --expect and --backup-dir")
        report = inspect_global() if args.global_scope else inspect_repository(args.repo)
        if args.expect and args.expect != report["fingerprint"]:
            raise ValueError("stale preview: inventory changed; inspect and confirm again")
        selected = args.action or args.apply
        action = next((a for a in report["actions"] if a["id"] == selected), None) if selected else None
        if selected and (action is None or action["status"] != "ready"):
            raise ValueError("selected action is not ready; no command authorized")
        if args.apply:
            print(json.dumps(apply_global_claude(report, args.backup_dir), indent=2, ensure_ascii=True))
            return 0
        if action and action["id"] in NATIVE_ACTIONS:
            failures = self_test(report["bd"], action["id"])
            action["selfTest"] = {"bd": report["bd"].get("version"), "passed": not failures, "failures": failures}
            if failures:
                print(json.dumps({"error": "installed bd failed the sandbox self-test; no command authorized",
                                  "selfTest": action["selfTest"], "readOnly": True}, indent=2))
                return 2
        print(json.dumps(report, indent=2, ensure_ascii=True))
        return 0
    except ValueError as error:
        print(json.dumps({"error": str(error), "readOnly": True}))
        return 2
    except (OSError, RuntimeError, subprocess.SubprocessError):
        print(json.dumps({"error": "inspection unavailable; no action may run", "readOnly": True}))
        return 2


if __name__ == "__main__":
    sys.exit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall