336 lines
14 KiB
Python
336 lines
14 KiB
Python
"""Execute rebuild.sh against isolated external command boundaries.
|
|
|
|
Oracles: installed-tool updates from the rebuild contract, activation ownership
|
|
from configuration.nix/home.nix, and the security-audit/pstack freeze policy.
|
|
Assertions reject dead update blocks, absent-package installs, duplicate owners,
|
|
failed-update aborts, and updates to frozen or untracked skills.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
GLOBALS = (
|
|
"@steipete/bird", "chrome-devtools-axi", "defuddle", "forgejo-axi",
|
|
"gh-axi", "lavish-axi", "quota-axi", "tasks-axi",
|
|
)
|
|
ACTIVATION_GLOBALS = ("acpx", "backpass")
|
|
|
|
BOUNDARIES = r'''
|
|
mock() { command "$TEST_PYTHON" "$TEST_DISPATCH" "$@"; }
|
|
function /opt/homebrew/bin/npm { mock npm "$@"; }
|
|
function /opt/homebrew/bin/node { command "$TEST_NODE" "$@"; }
|
|
function /opt/homebrew/bin/npx { mock npx "$@"; }
|
|
function /usr/bin/python3 { command "$TEST_PYTHON" "$@"; }
|
|
function [ {
|
|
if [[ $1 == '!' ]]; then
|
|
shift
|
|
! '[' "$@"
|
|
return
|
|
fi
|
|
if [[ $1 == -x && $2 == /opt/homebrew/bin/* ]]; then
|
|
case "$2" in
|
|
/opt/homebrew/bin/npm) builtin [ "$TEST_NPM" = 1 ]; return ;;
|
|
/opt/homebrew/bin/npx) builtin [ "$TEST_NPX" = 1 ]; return ;;
|
|
esac
|
|
fi
|
|
builtin [ "$@"
|
|
}
|
|
readlink() { return 1; }
|
|
npm() { mock bare-npm "$@"; }
|
|
brew() { mock brew "$@"; }
|
|
sudo() { mock sudo "$@"; }
|
|
nix() { mock nix "$@"; }
|
|
hermes() { mock hermes "$@"; }
|
|
pi() { mock pi "$@"; }
|
|
no-mistakes() { mock no-mistakes "$@"; }
|
|
if [[ $TEST_MISSING_TOOLS == 1 ]]; then
|
|
unset -f hermes pi no-mistakes
|
|
fi
|
|
'''
|
|
|
|
DISPATCH = r'''
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
|
|
kind, *args = sys.argv[1:]
|
|
root = Path(os.environ["TEST_ROOT"])
|
|
with (root / "calls.jsonl").open("a") as log:
|
|
log.write(json.dumps([kind, *args]) + "\n")
|
|
state_path = root / "state.json"
|
|
state = json.loads(state_path.read_text())
|
|
|
|
def save():
|
|
state_path.write_text(json.dumps(state))
|
|
|
|
if kind == "npm":
|
|
action = args[0]
|
|
if action == "ls":
|
|
if state.get("bad_inventory"):
|
|
print("invalid inventory")
|
|
sys.exit(1)
|
|
print(json.dumps({"dependencies": {
|
|
name: {"version": version}
|
|
for name, version in state["packages"].items()
|
|
}}))
|
|
elif action == "view":
|
|
if state.get("fail_lookup") == args[1]:
|
|
sys.exit(1)
|
|
print("2.0.0")
|
|
elif action == "install":
|
|
name, version = args[2].rsplit("@", 1)
|
|
if state.get("fail_install") == name:
|
|
sys.exit(1)
|
|
state["packages"][name] = version
|
|
save()
|
|
elif action == "root":
|
|
print(root / "global_modules")
|
|
else:
|
|
sys.exit("unexpected npm command: " + repr(args))
|
|
elif kind in ("no-mistakes", "hermes", "nix", "npx", "pi"):
|
|
if state.get("fail_updaters"):
|
|
sys.exit(1)
|
|
if kind == "npx":
|
|
for name in args[5:]:
|
|
state["skills"][name] = "new"
|
|
else:
|
|
state["components"][kind] = "new"
|
|
save()
|
|
elif kind == "sudo":
|
|
sys.exit(state.get("switch_status", 0))
|
|
else:
|
|
sys.exit("unexpected updater: " + kind)
|
|
'''
|
|
|
|
|
|
class RebuildUpdates(unittest.TestCase):
|
|
def setUp(self):
|
|
for tool in ("bash", "node"):
|
|
if shutil.which(tool) is None:
|
|
self.fail(f"Missing required test tool: {tool}")
|
|
self.scratch = tempfile.TemporaryDirectory(prefix=".rebuild-test-", dir=ROOT)
|
|
self.addCleanup(self.scratch.cleanup)
|
|
self.root = Path(self.scratch.name)
|
|
self.home = self.root / "home"
|
|
self.home.mkdir()
|
|
self.bin = self.root / "bin"
|
|
self.bin.mkdir()
|
|
for tool in ("dirname", "ln", "tr", "date", "mv"):
|
|
executable = shutil.which(tool)
|
|
self.assertIsNotNone(executable, f"Missing required test tool: {tool}")
|
|
(self.bin / tool).symlink_to(executable)
|
|
self.bash = shutil.which("bash")
|
|
self.env = {
|
|
"HOME": str(self.home),
|
|
"PATH": str(self.bin),
|
|
"BASH_ENV": str(self.root / "boundaries.bash"),
|
|
"TEST_ROOT": str(self.root),
|
|
"TEST_PYTHON": sys.executable,
|
|
"TEST_NODE": shutil.which("node"),
|
|
"TEST_DISPATCH": str(self.root / "dispatch.py"),
|
|
"TEST_NPM": "1",
|
|
"TEST_NPX": "1",
|
|
"TEST_MISSING_TOOLS": "0",
|
|
}
|
|
(self.root / "boundaries.bash").write_text(BOUNDARIES)
|
|
(self.root / "dispatch.py").write_text(DISPATCH)
|
|
direct = self.home / ".no-mistakes/bin/no-mistakes"
|
|
direct.parent.mkdir(parents=True)
|
|
direct.write_text(f'#!{self.bash}\nmock no-mistakes "$@"\n')
|
|
direct.chmod(0o755)
|
|
lock = self.home / ".agents/.skill-lock.json"
|
|
lock.parent.mkdir()
|
|
lock.write_text(json.dumps({"skills": {
|
|
"tdd": {}, "browser-harness": {}, "security-audit": {},
|
|
}}))
|
|
self.state = {
|
|
"packages": {name: "1.0.0" for name in GLOBALS + ACTIVATION_GLOBALS},
|
|
"skills": {name: "old" for name in (
|
|
"tdd", "browser-harness", "security-audit", "codebase-design",
|
|
)},
|
|
"components": {name: "old" for name in (
|
|
"no-mistakes", "hermes", "nix", "pi",
|
|
)},
|
|
}
|
|
|
|
def execute(self):
|
|
(self.root / "state.json").write_text(json.dumps(self.state))
|
|
(self.root / "calls.jsonl").write_text("")
|
|
result = subprocess.run(
|
|
[self.bash, str(ROOT / "rebuild.sh")], env=self.env,
|
|
cwd=ROOT, text=True, capture_output=True, timeout=30,
|
|
)
|
|
self.assertEqual(result.returncode, self.state.get("switch_status", 0),
|
|
result.stdout + result.stderr)
|
|
self.state = json.loads((self.root / "state.json").read_text())
|
|
self.calls = [json.loads(line) for line in
|
|
(self.root / "calls.jsonl").read_text().splitlines()]
|
|
self.assertFalse(any(call[0] in ("brew", "bare-npm") for call in self.calls))
|
|
self.assertFalse(any(call[:2] == ["npm", "view"] and
|
|
call[2] in ACTIVATION_GLOBALS for call in self.calls))
|
|
self.assertEqual(Path(os.readlink(self.home / ".dotfiles")), ROOT)
|
|
return result.stdout
|
|
|
|
def assert_update_order(self):
|
|
flake = ["nix", "flake", "update", "--flake", str(self.home / ".dotfiles")]
|
|
switch = ["sudo", "darwin-rebuild", "switch", "--flake",
|
|
str(self.home / ".dotfiles") + "#lt-mbp"]
|
|
skills = ["npx", "--yes", "skills@latest", "update", "-g", "-y",
|
|
"browser-harness", "tdd"]
|
|
pi = ["pi", "update", "--extensions", "--no-approve"]
|
|
self.assertIn(["no-mistakes", "update"], self.calls)
|
|
self.assertIn(["hermes", "update", "--yes"], self.calls)
|
|
self.assertLess(self.calls.index(flake), self.calls.index(switch))
|
|
self.assertLess(self.calls.index(switch), self.calls.index(skills))
|
|
self.assertLess(self.calls.index(skills), self.calls.index(pi))
|
|
|
|
def test_updates_installed_tools_and_preserves_frozen_skills(self):
|
|
self.execute()
|
|
self.assert_update_order()
|
|
for name in GLOBALS:
|
|
self.assertIn(["npm", "install", "-g", name + "@2.0.0"], self.calls)
|
|
self.assertEqual(self.state["packages"][name], "2.0.0")
|
|
for name in ACTIVATION_GLOBALS:
|
|
self.assertEqual(self.state["packages"][name], "1.0.0")
|
|
self.assertEqual(self.state["skills"], {
|
|
"browser-harness": "new", "tdd": "new",
|
|
"security-audit": "old", "codebase-design": "old",
|
|
})
|
|
self.assertTrue(all(version == "new" for version in
|
|
self.state["components"].values()))
|
|
self.execute()
|
|
self.assertFalse(any(call[:2] == ["npm", "install"] for call in self.calls))
|
|
|
|
def test_absent_packages_are_not_installed_or_queried(self):
|
|
self.state["packages"] = {}
|
|
self.execute()
|
|
self.assertEqual(self.state["packages"], {})
|
|
self.assertFalse(any(call[:2] in (["npm", "install"], ["npm", "view"])
|
|
for call in self.calls))
|
|
self.assert_update_order()
|
|
|
|
def test_registry_and_install_failures_preserve_versions_and_continue(self):
|
|
self.state["fail_lookup"] = "@steipete/bird"
|
|
self.state["fail_install"] = "defuddle"
|
|
output = self.execute()
|
|
self.assertIn("WARNING:", output)
|
|
self.assertEqual(self.state["packages"]["@steipete/bird"], "1.0.0")
|
|
self.assertEqual(self.state["packages"]["defuddle"], "1.0.0")
|
|
self.assertEqual(self.state["packages"]["tasks-axi"], "2.0.0")
|
|
self.assert_update_order()
|
|
|
|
def test_bad_inventory_never_installs_packages(self):
|
|
self.state["bad_inventory"] = True
|
|
self.execute()
|
|
self.assertFalse(any(call[:2] == ["npm", "install"] for call in self.calls))
|
|
self.assert_update_order()
|
|
|
|
def test_updater_failures_do_not_abort_switch_or_later_updates(self):
|
|
self.state["fail_updaters"] = True
|
|
output = self.execute()
|
|
self.assert_update_order()
|
|
self.assertGreaterEqual(output.count("WARNING:"), 5)
|
|
self.assertTrue(all(version == "old" for version in
|
|
self.state["components"].values()))
|
|
self.assertTrue(all(version == "old" for version in self.state["skills"].values()))
|
|
|
|
def test_missing_tools_warn_and_still_switch(self):
|
|
self.env.update(TEST_NPM="0", TEST_NPX="0", TEST_MISSING_TOOLS="1")
|
|
(self.home / ".no-mistakes/bin/no-mistakes").unlink()
|
|
output = self.execute()
|
|
self.assertGreaterEqual(output.count("WARNING:"), 5)
|
|
self.assertEqual([call[0] for call in self.calls], ["nix", "sudo"])
|
|
|
|
def test_no_mistakes_path_fallback(self):
|
|
(self.home / ".no-mistakes/bin/no-mistakes").unlink()
|
|
self.execute()
|
|
self.assertEqual(self.calls.count(["no-mistakes", "update"]), 1)
|
|
|
|
def test_missing_empty_or_frozen_only_lock_never_updates_skills(self):
|
|
lock = self.home / ".agents/.skill-lock.json"
|
|
for skills in (None, {}, {"security-audit": {}}):
|
|
with self.subTest(skills=skills):
|
|
if skills is None:
|
|
lock.unlink()
|
|
else:
|
|
lock.write_text(json.dumps({"skills": skills}))
|
|
self.execute()
|
|
self.assertFalse(any(call[0] == "npx" for call in self.calls))
|
|
self.assertEqual(self.state["skills"]["security-audit"], "old")
|
|
self.assertIn(["pi", "update", "--extensions", "--no-approve"], self.calls)
|
|
|
|
def test_pi_packages_are_not_retired(self):
|
|
packages = ("pi-cli", "pi-coding-agent", "pi-context")
|
|
for name in packages:
|
|
(self.root / "global_modules" / name).mkdir(parents=True)
|
|
self.state["packages"][name] = "1.0.0"
|
|
for private_copy in (False, True):
|
|
with self.subTest(private_copy=private_copy):
|
|
if private_copy:
|
|
(self.home / ".pi/agent/npm/node_modules/pi-context").mkdir(parents=True)
|
|
self.execute()
|
|
self.assertFalse(any(call[:2] == ["npm", "uninstall"] and
|
|
call[-1] in packages for call in self.calls))
|
|
for name in packages:
|
|
self.assertEqual(self.state["packages"][name], "1.0.0")
|
|
self.assertTrue((self.root / "global_modules" / name).is_dir())
|
|
self.assertIn(["pi", "update", "--extensions", "--no-approve"], self.calls)
|
|
|
|
def test_managed_lint_tool_backups_rotate(self):
|
|
for name in ("actionlint", "shellcheck"):
|
|
path = self.home / ".local/bin" / (name + ".backup")
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text("previous binary")
|
|
self.execute()
|
|
for name in ("actionlint", "shellcheck"):
|
|
path = self.home / ".local/bin" / (name + ".backup")
|
|
self.assertFalse(path.exists())
|
|
rotated = list(path.parent.glob(name + ".backup.*"))
|
|
self.assertEqual(len(rotated), 1)
|
|
self.assertEqual(rotated[0].read_text(), "previous binary")
|
|
|
|
def test_switch_failure_stops_post_switch_updates(self):
|
|
self.state["switch_status"] = 1
|
|
self.execute()
|
|
self.assertFalse(any(call[0] in ("npx", "pi") for call in self.calls))
|
|
|
|
|
|
class ManagedLintTools(unittest.TestCase):
|
|
def test_commands_follow_selected_nixpkgs_packages(self):
|
|
nix = shutil.which("nix")
|
|
self.assertIsNotNone(nix, "Missing required test tool: nix")
|
|
expression = '''
|
|
let
|
|
system = (builtins.getFlake (toString ./.)).darwinConfigurations."lt-mbp";
|
|
files = system.config.home-manager.users.laptran.home.file;
|
|
in builtins.map (name: {
|
|
inherit name;
|
|
source = toString files.${".local/bin/" + name}.source;
|
|
force = files.${".local/bin/" + name}.force;
|
|
package = toString system.pkgs.${name};
|
|
}) [ "actionlint" "shellcheck" ]
|
|
'''
|
|
result = subprocess.run(
|
|
[nix, "eval", "--json", "--impure", "--expr", expression],
|
|
cwd=ROOT, text=True, capture_output=True, timeout=120,
|
|
)
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
for command in json.loads(result.stdout):
|
|
with self.subTest(name=command["name"]):
|
|
self.assertEqual(command["source"],
|
|
command["package"] + "/bin/" + command["name"])
|
|
self.assertTrue(command["force"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|