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.

tests/test_integration_cleanup.py

View on GitHub
"""Read-only cleanup inventory and refusal boundaries."""
from contextlib import redirect_stdout
import importlib.util
import io
import json
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch

ROOT = Path(__file__).resolve().parents[3]
HELPER = ROOT / "skills/beads/scripts/integration_cleanup.py"
BLOCK = "<!-- BEGIN BEADS INTEGRATION v:1 profile:minimal hash:fixture -->\ngenerated\n<!-- END BEADS INTEGRATION -->\n"
CODEX = "<!-- BEGIN BEADS CODEX SETUP: generated by bd setup codex -->\ngenerated\n<!-- END BEADS CODEX SETUP -->\n"
HOOK = "# --- BEGIN BEADS INTEGRATION v1.2.2 ---\nbd hooks run pre-commit\n# --- END BEADS INTEGRATION v1.2.2 ---\n"


class InventoryTests(unittest.TestCase):
    def setUp(self):
        self.assertTrue(HELPER.is_file(), "read-only integration cleanup helper is not implemented")
        spec = importlib.util.spec_from_file_location("integration_cleanup", HELPER)
        self.helper = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(self.helper)
        (ROOT / ".artifacts").mkdir(exist_ok=True)
        self.temp = tempfile.TemporaryDirectory(dir=ROOT / ".artifacts", prefix="cleanup-test-")
        self.addCleanup(self.temp.cleanup)
        self.base = Path(self.temp.name)
        self.repo = self.base / "repo"
        self.repo.mkdir()
        self.env = patch.dict(os.environ, {"GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_COUNT": "0"})
        self.env.start()
        self.addCleanup(self.env.stop)
        subprocess.run(["git", "init", "-q", "-b", "main", str(self.repo)], check=True)
        self.probe = patch.object(self.helper, "bd_probe", return_value={
            "version": "1.2.2", "supported": True, "executable": "/trusted/bd", "sha256": "a" * 64,
        })
        self.probe.start()
        self.addCleanup(self.probe.stop)
        self.generated = patch.object(self.helper, "generated_codex", return_value={"files": {}, "block": None})
        self.generated.start()
        self.addCleanup(self.generated.stop)

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

    def inspect(self):
        return self.helper.inspect_repository(str(self.repo))

    def action(self, report, name):
        return next(item for item in report["actions"] if item["id"] == name)

    def snapshot(self):
        return {str(p.relative_to(self.repo)): (p.lstat().st_mode, p.read_bytes())
                for p in self.repo.rglob("*") if p.is_file() and not p.is_symlink()}

    def test_clean_inspection_is_a_read_only_noop(self):
        self.put("AGENTS.md", "authored policy\n")
        before = self.snapshot()
        first = self.inspect()
        self.assertEqual({a["status"] for a in first["actions"]}, {"clean"})
        self.assertEqual(self.inspect()["fingerprint"], first["fingerprint"])
        self.assertEqual(before, self.snapshot())

    def test_claude_mixed_hooks_and_authored_text_have_exact_scoped_proposal(self):
        self.put("CLAUDE.md", "before\n" + BLOCK + "after\n")
        self.put("AGENTS.md", "authored\n" + BLOCK)
        self.put(".claude/settings.json", json.dumps({"private": "DO_NOT_PRINT_ME", "hooks": {
            "SessionStart": [{"hooks": [{"type": "command", "command": "bd prime --hook-json"},
                                         {"type": "command", "command": "project-check"}]}]}}))
        before = self.snapshot()
        report = self.inspect()
        action = self.action(report, "claude")
        self.assertEqual(action["status"], "ready")
        self.assertIn("--global=false", action["argv"])
        self.assertIn(str(self.repo), action["argv"])
        self.assertEqual(action["argv"][1], "--chdir=" + str(self.repo))
        self.assertEqual({e["path"] for e in action["effects"]}, {"CLAUDE.md", ".claude/settings.json"})
        self.assertEqual(self.action(report, "agents-blocks")["status"], "ready")
        self.assertNotIn("DO_NOT_PRINT_ME", json.dumps(report))
        self.assertEqual(before, self.snapshot())

    def test_aliases_are_inventoried_once_but_native_mutation_is_refused(self):
        self.put("AGENTS.md", BLOCK)
        (self.repo / "CLAUDE.md").symlink_to("AGENTS.md")
        report = self.inspect()
        groups = [f for f in report["files"] if "AGENTS.md" in f["aliases"]]
        self.assertEqual(len(groups), 1)
        self.assertEqual(set(groups[0]["aliases"]), {"AGENTS.md", "CLAUDE.md"})
        self.assertEqual(self.action(report, "claude")["status"], "blocked")
        self.assertTrue((self.repo / "CLAUDE.md").is_symlink())

    def test_outside_links_and_symlinked_parent_are_not_read_or_proposed(self):
        outside = self.base / "private"
        outside.mkdir()
        (outside / "settings.json").write_text("DO_NOT_PRINT_ME")
        (self.repo / ".claude").symlink_to(outside)
        self.put("CLAUDE.md", BLOCK)
        report = self.inspect()
        self.assertEqual(self.action(report, "claude")["status"], "blocked")
        self.assertNotIn("DO_NOT_PRINT_ME", json.dumps(report))

    def test_hardlinks_and_malformed_or_oversized_inputs_fail_closed(self):
        for mode in ("hardlink", "markers", "json", "oversized", "duplicate-json"):
            with self.subTest(mode=mode):
                a = self.put("CLAUDE.md", BLOCK)
                settings = self.repo / ".claude/settings.json"
                if settings.exists():
                    settings.unlink()
                if mode == "hardlink":
                    os.link(a, self.repo / "alias")
                elif mode == "markers":
                    a.write_text(BLOCK + BLOCK)
                elif mode == "json":
                    self.put(".claude/settings.json", "{")
                elif mode == "duplicate-json":
                    self.put(".claude/settings.json", '{"hooks":{},"hooks":{}}')
                else:
                    a.write_text("x" * (self.helper.MAX_BYTES + 1))
                self.assertEqual(self.action(self.inspect(), "claude")["status"], "blocked")
                if mode == "hardlink":
                    (self.repo / "alias").unlink()

    def test_codex_refuses_shared_flags_and_mixed_command_entries(self):
        self.put("AGENTS.md", CODEX)
        self.put(".codex/config.toml", "[features]\nhooks=true\n")
        self.assertEqual(self.action(self.inspect(), "codex-native")["status"], "blocked")
        (self.repo / ".codex/config.toml").unlink()
        self.put(".codex/hooks.json", json.dumps({"hooks": {"SessionStart": [{"hooks": [
            {"type": "command", "command": "bd codex-hook SessionStart"},
            {"type": "command", "command": "project-check"},
        ]}]}}))
        self.assertEqual(self.action(self.inspect(), "codex-native")["status"], "blocked")

    def test_exact_generated_codex_tree_is_ready_for_bounded_deletion(self):
        files = {
            ".codex/config.toml": b"generated config",
            ".codex/hooks.json": b"generated hooks",
            ".agents/skills/beads/SKILL.md": b"generated skill",
            ".agents/skills/beads/agents/openai.yaml": b"generated metadata",
        }
        self.put("AGENTS.md", "authored\n")
        for path, content in files.items():
            target = self.repo / path
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_bytes(content)
        hashes = {path: self.helper.digest(content) for path, content in files.items()}
        with patch.object(self.helper, "generated_codex", return_value={"files": hashes, "block": None}):
            report = self.inspect()
            action = self.action(report, "codex-generated")
            self.assertEqual(action["status"], "ready")
            self.assertEqual({effect["path"] for effect in action["effects"]}, set(files))
            self.put(".codex/authored.toml", "keep")
            self.assertEqual(self.action(self.inspect(), "codex-generated")["status"], "blocked")

    def test_agent_blocks_are_ready_for_exact_marker_bounded_edit(self):
        self.put("AGENTS.md", "before\n\n" + BLOCK + "\n" + CODEX + "after\n")
        action = self.action(self.inspect(), "agents-blocks")
        self.assertEqual(action["status"], "ready")
        self.assertEqual([effect["operation"] for effect in action["effects"]], [
            "remove exact general managed block", "remove exact Codex managed block",
        ])
        lines = action["effects"][0]["lines"][0]
        self.assertEqual(lines["cleanupStartLine"], lines["startLine"] - 1)

    def test_interactions_requires_ignore_edit_and_index_only_removal(self):
        self.put(".gitignore", "# project\n")
        interactions = self.put(".beads/interactions.jsonl", "")
        subprocess.run(["git", "-C", str(self.repo), "add", ".gitignore", ".beads/interactions.jsonl"], check=True)
        action = self.action(self.inspect(), "interactions-ignore")
        self.assertEqual(action["status"], "ready")
        self.assertEqual(action["ignoreRule"], "/.beads/interactions.jsonl")
        self.assertTrue(interactions.exists())
        tracked = subprocess.run(["git", "-C", str(self.repo), "ls-files", ".beads/interactions.jsonl"], capture_output=True, text=True, check=True).stdout.strip()
        self.assertEqual(tracked, ".beads/interactions.jsonl")

    def test_interactions_already_untracked_and_ignored_is_clean(self):
        self.put(".gitignore", "/.beads/interactions.jsonl\n")
        self.put(".beads/interactions.jsonl", "local\n")
        self.assertEqual(self.action(self.inspect(), "interactions-ignore")["status"], "clean")

    def test_codex_ready_only_without_shared_config_or_unproven_skill_ownership(self):
        self.put("AGENTS.md", "authored\n" + CODEX)
        self.assertEqual(self.action(self.inspect(), "codex-native")["status"], "ready")
        self.put(".agents/skills/beads/SKILL.md", "authored skill")
        self.assertEqual(self.action(self.inspect(), "codex-native")["status"], "blocked")

    def test_hooks_preserve_default_path_logic_but_refuse_shared_path_checks(self):
        self.put(".git/hooks/pre-commit", "#!/bin/sh\n" + HOOK + "\nproject-check\n")
        self.assertEqual(self.action(self.inspect(), "hooks")["status"], "ready")
        self.put(".beads/hooks/pre-commit", "#!/bin/sh\n" + HOOK + "\nproject-check\n")
        subprocess.run(["git", "-C", str(self.repo), "config", "core.hooksPath", ".beads/hooks"], check=True)
        self.assertEqual(self.action(self.inspect(), "hooks")["status"], "blocked")

    def test_noncanonical_beads_hookspath_cannot_claim_native_reset(self):
        self.put(".beads/hooks/pre-commit", "#!/bin/sh\n" + HOOK)
        subprocess.run(["git", "-C", str(self.repo), "config", "core.hooksPath", ".beads/./hooks"], check=True)
        self.assertEqual(self.action(self.inspect(), "hooks")["status"], "blocked")

    def test_hooks_refuse_chain_backups_and_global_fallback(self):
        self.put(".git/hooks/pre-commit", "#!/bin/sh\n" + HOOK)
        self.put(".git/hooks/pre-commit.old", "project-check")
        self.assertEqual(self.action(self.inspect(), "hooks")["status"], "blocked")
        (self.repo / ".git/hooks/pre-commit.old").unlink()
        global_config = self.base / "global.gitconfig"
        global_config.write_text("[core]\n hooksPath = /outside/hooks\n")
        with patch.dict(os.environ, {"GIT_CONFIG_GLOBAL": str(global_config)}):
            self.assertEqual(self.action(self.inspect(), "hooks")["status"], "blocked")

    def test_hook_markers_from_any_bd_version_are_recognized(self):
        for version in ("1.2.2", "1.3.0", "2.0.0-rc1"):
            text = "#!/bin/sh\n" + HOOK.replace("v1.2.2", "v" + version)
            spans, error = self.helper.block_ranges(text, "hook")
            self.assertIsNone(error)
            self.assertEqual(len(spans), 1)

    def test_native_action_selection_runs_self_test_and_blocks_on_failure(self):
        self.put("CLAUDE.md", BLOCK)
        argv = [str(HELPER), "--repo", str(self.repo), "--action", "claude"]
        with patch.object(self.helper, "self_test", return_value=["CLAUDE.md authored text not preserved exactly"]) as tested, \
                patch("sys.argv", argv), redirect_stdout(io.StringIO()) as out:
            self.assertEqual(self.helper.main(), 2)
        tested.assert_called_once()
        self.assertIn("self-test", out.getvalue())
        with patch.object(self.helper, "self_test", return_value=[]), patch("sys.argv", argv), redirect_stdout(io.StringIO()) as out:
            self.assertEqual(self.helper.main(), 0)
        self.assertTrue(self.action(json.loads(out.getvalue()), "claude")["selfTest"]["passed"])

    def test_stale_fingerprint_detects_content_and_topology_changes(self):
        self.put("CLAUDE.md", BLOCK)
        initial = self.inspect()["fingerprint"]
        self.put("CLAUDE.md", "authored\n" + BLOCK)
        self.assertNotEqual(initial, self.inspect()["fingerprint"])
        initial = self.inspect()["fingerprint"]
        (self.repo / "CLAUDE.md").chmod(0o600)
        self.assertNotEqual(initial, self.inspect()["fingerprint"])

    def test_unknown_bd_version_and_local_config_includes_are_inventory_only(self):
        self.put("CLAUDE.md", BLOCK)
        with patch.object(self.helper, "bd_probe", return_value={"version": "future", "supported": False}):
            self.assertEqual(self.action(self.inspect(), "claude")["status"], "blocked")
        subprocess.run(["git", "-C", str(self.repo), "config", "include.path", "/unknown/config"], check=True)
        self.assertEqual(self.action(self.inspect(), "claude")["status"], "blocked")

    def test_shared_config_and_redirected_beads_are_never_proposed(self):
        self.put("CLAUDE.md", BLOCK)
        config = self.repo / ".git/config"
        saved = config.read_text()
        config.unlink()
        outside = self.base / "external-config"
        outside.write_text(saved)
        config.symlink_to(outside)
        self.assertEqual(self.action(self.inspect(), "claude")["status"], "blocked")
        config.unlink()
        config.write_text(saved)
        self.put(".beads/redirect", "/another/store\n")
        self.assertEqual(self.action(self.inspect(), "claude")["status"], "blocked")

    def test_cli_rejects_stale_or_ineligible_selection_without_writes(self):
        self.put("CLAUDE.md", BLOCK)
        before = self.snapshot()
        with patch("sys.argv", [str(HELPER), "--repo", str(self.repo), "--expect", "stale"]), redirect_stdout(io.StringIO()) as out:
            self.assertEqual(self.helper.main(), 2)
        self.assertIn("stale", out.getvalue())
        with patch("sys.argv", [str(HELPER), "--repo", str(self.repo), "--action", "codex-native"]), redirect_stdout(io.StringIO()):
            self.assertEqual(self.helper.main(), 2)
        self.assertEqual(before, self.snapshot())

    def test_ambient_config_allows_only_noninteractive_credential_suppression(self):
        with patch.dict(os.environ, {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "credential.interactive", "GIT_CONFIG_VALUE_0": "false"}):
            self.assertTrue(self.inspect()["readOnly"])
        with patch.dict(os.environ, {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.hooksPath", "GIT_CONFIG_VALUE_0": "/outside"}):
            with self.assertRaises(ValueError):
                self.inspect()

    def test_subdirectories_and_shared_worktree_administration_are_refused(self):
        child = self.repo / "child"
        child.mkdir()
        with self.assertRaises(ValueError):
            self.helper.inspect_repository(str(child))
        self.put("CLAUDE.md", BLOCK)
        (self.repo / ".git/worktrees/peer").mkdir(parents=True)
        self.assertEqual(self.action(self.inspect(), "claude")["status"], "blocked")



class GlobalInventoryTests(unittest.TestCase):
    def setUp(self):
        spec = importlib.util.spec_from_file_location("integration_cleanup", HELPER)
        self.helper = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(self.helper)
        (ROOT / ".artifacts").mkdir(exist_ok=True)
        self.temp = tempfile.TemporaryDirectory(dir=ROOT / ".artifacts", prefix="cleanup-global-test-")
        self.addCleanup(self.temp.cleanup)
        self.home = Path(self.temp.name) / "home"
        self.backup = Path(self.temp.name) / "backup"
        (self.home / ".claude").mkdir(parents=True)
        self.backup.mkdir(mode=0o700)
        env = patch.dict(os.environ, {"HOME": str(self.home), "CODEX_HOME": ""})
        env.start()
        self.addCleanup(env.stop)
        self.settings = self.home / ".claude/settings.json"
        self.authored = {"type": "command", "command": "run-user-check"}

    def write(self, hooks, **extra):
        self.settings.write_text(json.dumps({**extra, "hooks": hooks}, indent=2) + "\n")

    def action(self):
        return self.helper.inspect_global()["actions"][0]

    def apply(self, *extra):
        fingerprint = self.helper.inspect_global()["fingerprint"]
        argv = [str(HELPER), "--global", "--expect", fingerprint, "--apply", "claude-global", "--backup-dir", str(self.backup), *extra]
        with patch("sys.argv", argv), redirect_stdout(io.StringIO()) as out:
            return self.helper.main(), out.getvalue()

    def test_exact_prime_hooks_are_ready_without_bd_and_inspection_writes_nothing(self):
        self.write({"SessionStart": [{"matcher": "", "hooks": [self.authored, {"type": "command", "command": "bd prime"}]}]})
        before = self.settings.read_bytes()
        with patch.object(self.helper, "bd_probe", side_effect=AssertionError("bd must not be probed")):
            action = self.action()
        self.assertEqual(action["status"], "ready")
        self.assertEqual(action["effects"][0]["removedCommands"], 1)
        self.assertEqual(before, self.settings.read_bytes())

    def test_absent_or_authored_only_hooks_are_clean(self):
        self.assertEqual(self.action()["status"], "clean")
        self.write({"SessionStart": [{"matcher": "", "hooks": [self.authored]}]})
        self.assertEqual(self.action()["status"], "clean")

    def test_apply_removes_only_prime_hooks_preserving_order_mode_and_siblings(self):
        self.write({"PreToolUse": [{"hooks": [{"type": "command", "command": "bd prime"}]}],
                    "SessionStart": [{"matcher": "", "hooks": [self.authored, {"type": "command", "command": "bd prime"}]}],
                    "PreCompact": [{"matcher": "", "hooks": [{"type": "command", "command": "bd prime --hook-json"}]}]},
                   zeta={"kept": True}, alpha=["kept"])
        self.settings.chmod(0o640)
        original = self.settings.read_bytes()
        code, output = self.apply()
        self.assertEqual(code, 0, output)
        result = json.loads(output)
        self.assertEqual((result["removedCommands"], result["status"]), (2, "clean"))
        data = json.loads(self.settings.read_text())
        self.assertEqual(list(data), ["zeta", "alpha", "hooks"])
        self.assertEqual(data["hooks"], {"PreToolUse": [{"hooks": [{"type": "command", "command": "bd prime"}]}],
                                         "SessionStart": [{"matcher": "", "hooks": [self.authored]}]})
        self.assertEqual(self.settings.stat().st_mode & 0o777, 0o640)
        self.assertEqual(Path(result["backup"]).read_bytes(), original)
        self.assertEqual(Path(result["backup"]).stat().st_mode & 0o777, 0o600)

    def test_apply_refuses_stale_unready_public_backup_or_linked_settings(self):
        self.write({"SessionStart": [{"hooks": [{"type": "command", "command": "bd prime"}]}]})
        argv = [str(HELPER), "--global", "--expect", "stale", "--apply", "claude-global", "--backup-dir", str(self.backup)]
        with patch("sys.argv", argv), redirect_stdout(io.StringIO()):
            self.assertEqual(self.helper.main(), 2)
        with patch("sys.argv", [str(HELPER), "--global", "--apply", "claude-global"]), redirect_stdout(io.StringIO()):
            self.assertEqual(self.helper.main(), 2)
        self.backup.chmod(0o755)
        self.assertEqual(self.apply()[0], 2)
        self.backup.chmod(0o700)
        target = self.home / "dotfiles-settings.json"
        self.settings.rename(target)
        self.settings.symlink_to(target)
        self.assertEqual(self.action()["status"], "blocked")
        self.assertEqual(self.apply()[0], 2)
        self.assertIn("bd prime", target.read_text())
        self.assertEqual(list(self.backup.iterdir()), [])

    def test_other_global_clients_are_residuals_only(self):
        codex = self.home / ".codex/hooks.json"
        codex.parent.mkdir()
        codex.write_text(json.dumps({"hooks": {"SessionStart": [{"hooks": [{"type": "command", "command": "bd codex-hook prime"}]}]}}))
        report = self.helper.inspect_global()
        self.assertEqual([a["id"] for a in report["actions"]], ["claude-global"])
        self.assertEqual(len(report["residuals"]), 1)
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