diff --git a/readme.md b/readme.md index eca2a10..d9950ae 100644 --- a/readme.md +++ b/readme.md @@ -82,13 +82,17 @@ One `./rebuild.sh` run brings every installed component to its latest supported Before the switch: -- Homebrew formulae and casks, through `brew update` and `brew upgrade`. `configuration.nix` stays the declaration; `onActivation.upgrade` repeats the upgrade during the switch. -- npm globals through `/opt/homebrew/bin/npm`, never Nix's npm: `@steipete/bird`, `acpx`, `backpass`, `chrome-devtools-axi`, `defuddle`, `forgejo-axi`, `gh-axi`, `lavish-axi`, `quota-axi`, and `tasks-axi`. Each package is compared with the registry before an install. `tasks-axi` keeps its firstmate floor of 0.2.6 in `home.activation.axiTools`, which now installs only a missing or older copy, so the latest release survives the switch. +- Installed npm globals through `/opt/homebrew/bin/npm`, never Nix's npm: `@steipete/bird`, `chrome-devtools-axi`, `defuddle`, `forgejo-axi`, `gh-axi`, `lavish-axi`, `quota-axi`, and `tasks-axi`. The script skips absent packages and compares each installed package with the registry before an update. `tasks-axi` keeps its firstmate floor of 0.2.6 in `home.activation.axiTools`, which now installs only a missing or older copy, so the latest release survives the switch. - Retired npm packages are removed only while their evidence still holds: `@opencode-ai/cli`, `opencode-ai`, and the June `pi-cli`/`pi-coding-agent` placeholders. The global `pi-context` is removed only when Pi keeps its own copy under `~/.pi/agent/npm`. If `pi` resolves into npm's global tree, the script warns and leaves those packages in place. - `no-mistakes update`, using the binary at `~/.no-mistakes/bin/no-mistakes`. - `hermes update --yes`, which pulls the configured channel and restarts the services that run its new code. - `nix flake update`, so the switch builds from the newest locked inputs. Commit the resulting `flake.lock` change. +During the switch: + +- nix-darwin updates Homebrew formulae and casks through `configuration.nix`'s `onActivation.autoUpdate` and `onActivation.upgrade` settings. +- `home.activation.backpass` updates `acpx` and `backpass`. Other activation steps install their declared npm packages when absent. + After the switch: - The Skills CLI updates every skill tracked in `~/.agents/.skill-lock.json`. The pinned pstack skills are not in that lock, so they stay on the `home.nix` revision (see [pstack skills](#pstack-skills-pinned-on-every-rebuild)). `security-audit` is excluded on purpose, because `home.nix` freezes it so a rebuild never pulls a new skill mid-session; renew it by hand with the command in [security-audit skill](#security-audit-skill-agent-security-reviews). diff --git a/rebuild.sh b/rebuild.sh index 14a84a1..e9d5849 100755 --- a/rebuild.sh +++ b/rebuild.sh @@ -2,8 +2,8 @@ # Rebuild nix-darwin + home-manager from this checkout. # # Before the switch, update every installed component that is not declarative: -# Homebrew formulae and casks, npm globals (through Homebrew's node, never -# Nix's npm), no-mistakes, Hermes Agent, and the flake inputs. After the switch, +# npm globals (through Homebrew's node, never Nix's npm), no-mistakes, +# Hermes Agent, and the flake inputs. After the switch, # update the installed agent skills and Pi extensions against the upgraded # binaries. # @@ -16,18 +16,6 @@ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" ln -sfn "$DIR" ~/.dotfiles NPM=/opt/homebrew/bin/npm -# Homebrew: configuration.nix declares the formulae and casks, and the nix-darwin -# activation upgrades them too. This explicit pass reports what moved before the -# switch and keeps the same warning-not-fail behaviour when the network is down. -echo "==> Updating Homebrew formulae and casks..." -if ! command -v brew >/dev/null 2>&1; then - echo "==> WARNING: brew not found. Skipping Homebrew update." -elif brew update 2>&1 && brew upgrade 2>&1; then - echo "==> Homebrew update complete" -else - echo "==> WARNING: Homebrew update failed (network or package issue). Continuing with installed versions." -fi - # npm globals are installed outside Nix and Homebrew, so no other step moves # them. Use /opt/homebrew/bin/npm explicitly: the activation PATH can resolve # Nix's npm, which cannot write the Homebrew prefix, and these packages belong to @@ -52,6 +40,9 @@ process.stdin.on("end", () => { } catch {} }); ' "$pkg" || true)" + if [ -z "$installed" ]; then + return 0 + fi latest="$("$NPM" view "$pkg" version --fetch-timeout=15000 --fetch-retries=1 2>/dev/null \ | tr -d '[:space:]' || true)" if [ -z "$latest" ]; then @@ -62,9 +53,7 @@ process.stdin.on("end", () => { echo "==> $pkg already at $latest" return 0 fi - current="$installed" - [ -n "$current" ] || current=none - echo "==> $pkg $current -> $latest" + echo "==> $pkg $installed -> $latest" if "$NPM" install -g "$pkg@$latest" >/dev/null 2>&1; then echo "==> $pkg installed at $latest" else @@ -76,8 +65,6 @@ process.stdin.on("end", () => { # here so it reaches the latest release; the activation only fills a gap. npm_globals=( "@steipete/bird" - acpx - backpass chrome-devtools-axi defuddle forgejo-axi diff --git a/tests/rebuild-update-steps.py b/tests/rebuild-update-steps.py new file mode 100644 index 0000000..98926d9 --- /dev/null +++ b/tests/rebuild-update-steps.py @@ -0,0 +1,278 @@ +"""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_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)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/rebuild-update-steps.sh b/tests/rebuild-update-steps.sh index cef377b..676a4d4 100755 --- a/tests/rebuild-update-steps.sh +++ b/tests/rebuild-update-steps.sh @@ -1,64 +1,5 @@ #!/usr/bin/env bash -# Behavior check: rebuild.sh updates every installed component that is not -# declarative, and never relies on a bare `npm`. -# -# The check is static, so it runs without changing the machine: -# - the script parses as bash; -# - every npm global is updated through /opt/homebrew/bin/npm; -# - no bare npm invocation survives; -# - each component (Homebrew, npm globals, no-mistakes, Hermes, flake inputs, -# agent skills, Pi extensions) has a named step that warns instead of -# killing the rebuild; -# - the frozen security-audit skill is excluded from the skills update. set -euo pipefail ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P) -REBUILD="$ROOT/rebuild.sh" - -[ -f "$REBUILD" ] || { echo "FAIL: missing $REBUILD" >&2; exit 1; } - -fail() { - echo "FAIL: $1" >&2 - exit 1 -} - -bash -n "$REBUILD" || fail "rebuild.sh does not parse" -echo "PASS: rebuild.sh parses" - -grep -qF 'NPM=/opt/homebrew/bin/npm' "$REBUILD" \ - || fail "rebuild.sh does not set NPM to Homebrew's npm" -echo "PASS: npm globals use /opt/homebrew/bin/npm" - -# A bare `npm install|uninstall|view|ls|root` would resolve Nix's npm under the -# activation PATH. Every call must go through $NPM. -if grep -nE '(^|[^/[:alnum:]_-])npm[[:space:]]+(install|uninstall|view|ls|root)' "$REBUILD"; then - fail "rebuild.sh calls bare npm; use \$NPM instead" -fi -echo "PASS: no bare npm invocation" - -for pkg in '@steipete/bird' acpx backpass chrome-devtools-axi defuddle forgejo-axi \ - gh-axi lavish-axi quota-axi tasks-axi; do - grep -qF "$pkg" "$REBUILD" || fail "rebuild.sh does not update npm global $pkg" -done -echo "PASS: every npm global has an update entry" - -for step in 'Updating Homebrew formulae and casks' 'Updating npm global tools' \ - 'Updating no-mistakes' 'Updating Hermes Agent' 'Updating flake inputs' \ - 'Updating agent skills' 'Updating pi extensions'; do - grep -qF "==> $step..." "$REBUILD" || fail "rebuild.sh has no step: $step" -done -echo "PASS: every update step is present" - -# Each update step reports a warning and returns instead of aborting the whole -# rebuild when its tool or network is missing. -[ "$(grep -cF '==> WARNING:' "$REBUILD")" -ge 7 ] \ - || fail "rebuild.sh is missing warning fallbacks" -grep -qF 'hermes update --yes' "$REBUILD" \ - || fail "rebuild.sh does not use the supported hermes updater" -grep -qF 'skills@latest update -g -y' "$REBUILD" \ - || fail "rebuild.sh does not use the supported Skills CLI updater" -grep -qF 'name != "security-audit"' "$REBUILD" \ - || fail "rebuild.sh does not exclude the frozen security-audit skill" -echo "PASS: update steps warn and skip instead of failing" - -echo "PASS: rebuild update steps" +exec python3 "$ROOT/tests/rebuild-update-steps.py"