From 0c4f0aee72dbb287d9f9af94294c44ce72493797 Mon Sep 17 00:00:00 2001 From: Milad Imen Date: Tue, 15 Sep 2026 13:34:22 -0700 Subject: [PATCH 1/2] Refresh each host's agent package from main on an hourly job Every machine pins its package independently, so a skill fix merged to main only reaches a host when someone re-runs bootstrap-agent there. A theme deleted on main stayed in use for a week that way. bin/refresh-agent compares the installed .release-revision against the tip of main and, when they differ, re-runs bootstrap-agent from the package being replaced, so the installer updates on the same tick. It reads url and tokenRef from the existing host config and never writes it. A matching pin prints one line and exits zero. A missing config, a missing package, a non-sha revision, and an unreachable GitHub each exit nonzero naming the failing step, because this runs unattended. --install --job-id writes the hourly LaunchAgent through the hub reporter and refuses to overwrite a plist it did not write. Co-Authored-By: Claude Opus 5 (1M context) --- DEPLOY.md | 12 +++ bin/refresh-agent | 194 +++++++++++++++++++++++++++++++++++++++++ deploy/test_refresh.py | 115 ++++++++++++++++++++++++ 3 files changed, 321 insertions(+) create mode 100755 bin/refresh-agent create mode 100644 deploy/test_refresh.py diff --git a/DEPLOY.md b/DEPLOY.md index be50426..21fdc2d 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -54,6 +54,18 @@ python3 bin/bootstrap-agent --revision \ The bootstrap fetches the GitHub archive directly into `~/.local/share/html-plan-host/packages/`. `bin/install-agent` links its CLI through `~/.local/bin/html-plan` and its skills through `~/.codex/skills` and `~/.agents/skills`. It rejects conflicting existing files instead of overwriting them. This installation does not edit Claude's settings or copy packages into the synced vault. In the personal fleet, the synced house `html-plan` entry is only an adapter that reads the installed package. Other Claude installations can use the repo's native marketplace plugin instead. +### Keeping installed packages current + +Each host pins its own package, so a skill fix merged to `main` does not reach a machine until that machine reinstalls. `bin/refresh-agent` closes that gap. It compares the installed `.release-revision` against the tip of `main` and, when they differ, re-runs `bin/bootstrap-agent` from the currently installed package, using the `url` and `tokenRef` already in `~/.config/html-plan-host/config.json`. Running the installer from the package being replaced lets the installer itself update on the same tick. A matching pin prints one line and exits zero. The tool never writes that config and never installs onto a host that was never bootstrapped; a missing config, a missing package, and an unreachable GitHub each exit nonzero naming the failing step. + +```sh +python3 bin/refresh-agent # check and update this host once +python3 bin/refresh-agent --self-check # prove the compare and failure logic, no network +python3 bin/refresh-agent --install --job-id .launchd.html-plan-agent-refresh +``` + +`--install` writes and bootstraps the `com.mimen.html-plan-host.agent-refresh` user LaunchAgent, which runs hourly through the hub reporter so an unattended failure surfaces as a failed run rather than silence. The hub job id differs per host, so it is an explicit argument. The command refuses to overwrite a plist at that label that it did not write. + A machine-local, nonsecret `~/.config/html-plan-host/config.json` selects the personal deployment: ```json diff --git a/bin/refresh-agent b/bin/refresh-agent new file mode 100755 index 0000000..c43578d --- /dev/null +++ b/bin/refresh-agent @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Keep this host's installed agent package on the tip of main. + +Every machine pins its own package, so a fixed skill can sit on main +indefinitely while local agents keep generating plans from the revision +installed months ago. This compares the installed pin against main and re-runs +the pinned installer when they differ. + +It runs unattended, so there is no recovery here and no default that papers +over a broken host. An unusable config, a missing package, or an unreachable +GitHub exits nonzero naming the step that failed. +""" + +import argparse +import json +import os +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import tempfile +import urllib.request + +HOME = Path.home() +DATA = HOME / '.local/share/html-plan-host' +CONFIG = HOME / '.config/html-plan-host/config.json' +CURRENT = DATA / 'agent-current' +LAUNCH_AGENTS = HOME / 'Library/LaunchAgents' +HUB_RUN = HOME / 'Programming/Repos/hub/bin/run' +LABEL = 'com.mimen.html-plan-host.agent-refresh' +TIP_URL = 'https://api.github.com/repos/mimen/html-plan-host/commits/main' +PYTHON = '/usr/bin/python3' +COMMIT = re.compile('[0-9a-f]{40}') +DOMAIN = 'gui/{}'.format(os.getuid()) + + +def run(step, command): + done = subprocess.run([str(part) for part in command]) + if done.returncode: + raise SystemExit('{}: {} exited {}'.format(step, command[0], done.returncode)) + + +def read_config(): + try: + settings = json.loads(CONFIG.read_text()) + url, token_ref = settings['url'], settings['tokenRef'] + except (OSError, ValueError, KeyError, TypeError) as failure: + raise SystemExit('config: cannot read url and tokenRef from {} ({}); bootstrap this host first'.format(CONFIG, failure)) + if not isinstance(url, str) or not isinstance(token_ref, str) or not url or not token_ref: + raise SystemExit('config: {} needs nonempty string url and tokenRef; bootstrap this host first'.format(CONFIG)) + return url, token_ref + + +def installed_revision(): + marker = CURRENT / '.release-revision' + try: + revision = marker.read_text().strip() + except OSError as failure: + raise SystemExit('installed: no package at {} ({}); bootstrap this host first'.format(CURRENT, failure)) + if not COMMIT.fullmatch(revision): + raise SystemExit('installed: {} does not hold a commit sha'.format(marker)) + return revision + + +def fetch_tip(): + request = urllib.request.Request(TIP_URL, headers={'User-Agent': 'html-plan-host-refresh', + 'Accept': 'application/vnd.github.sha'}) + return urllib.request.urlopen(request, timeout=30).read().decode('utf-8', 'replace').strip() + + +def resolve_tip(): + try: + body = fetch_tip() + except OSError as failure: + raise SystemExit('resolve: cannot reach {} ({})'.format(TIP_URL, failure)) + if not COMMIT.fullmatch(body): + raise SystemExit('resolve: main did not resolve to a commit sha: ' + body[:200]) + return body + + +def refresh(): + url, token_ref = read_config() + installed = installed_revision() + tip = resolve_tip() + if tip == installed: + return 'up to date at ' + installed + # Run the installer from the package being replaced, so bootstrap-agent and + # install-agent pick up their own fixes on the same tick as everything else. + installer = CURRENT / 'bin/bootstrap-agent' + if not installer.is_file(): + raise SystemExit('bootstrap: no installer at {}; bootstrap this host first'.format(installer)) + run('bootstrap', [PYTHON, installer, '--revision', tip, '--url', url, '--token-ref', token_ref]) + return 'updated {} -> {}'.format(installed, tip) + + +def install(job_id): + if not job_id or job_id.startswith('-'): + raise SystemExit('install: --job-id must be a hub job id such as mini.launchd.html-plan-agent-refresh') + # The scheduled command goes through the agent-current link rather than this + # file's resolved path, which moves to a new package directory on every + # upgrade and would leave the job pointing at a stale revision. + script = CURRENT / 'bin/refresh-agent' + if not script.is_file(): + raise SystemExit('install: no refresh tool at {}; bootstrap this host first'.format(script)) + if not HUB_RUN.is_file(): + raise SystemExit('install: no hub reporter at {}'.format(HUB_RUN)) + config = {'Label': LABEL, + 'ProgramArguments': ['/bin/zsh', str(HUB_RUN), job_id, '--', PYTHON, str(script)], + 'StartInterval': 3600, 'RunAtLoad': True, + 'StandardOutPath': str(DATA / (LABEL + '.log')), + 'StandardErrorPath': str(DATA / (LABEL + '.error.log'))} + target = LAUNCH_AGENTS / (LABEL + '.plist') + if target.exists(): + previous = plistlib.loads(target.read_bytes()) + if previous.get('ProgramArguments', [])[-1:] != [str(script)]: + raise SystemExit('install: {} belongs to another owner'.format(target)) + subprocess.run(['/bin/launchctl', 'bootout', DOMAIN, str(target)], capture_output=True) + target.parent.mkdir(parents=True, exist_ok=True) + DATA.mkdir(parents=True, exist_ok=True) + target.write_bytes(plistlib.dumps(config)) + run('install', ['/bin/launchctl', 'bootstrap', DOMAIN, target]) + return 'installed {} for hub job {}, every {} seconds'.format(LABEL, job_id, config['StartInterval']) + + +def demo(): + global CONFIG, CURRENT, fetch_tip, run + root = Path(tempfile.mkdtemp(prefix='refresh-agent-demo.')) + CONFIG, CURRENT = root / 'config.json', root / 'agent-current' + old, new = 'a' * 40, 'b' * 40 + url, token_ref = 'https://plans.example', 'op://Test/Plan/token' + tip = {'value': old} + invoked = [] + fetch_tip = lambda: tip['value'] + run = lambda step, command: invoked.append([str(part) for part in command]) + + def fails(step, fragment=''): + try: + refresh() + except SystemExit as failure: + assert str(failure).startswith(step + ':'), failure + assert fragment in str(failure), failure + return + raise AssertionError('expected ' + step + ' to fail') + + try: + fails('config', 'bootstrap this host first') + CONFIG.write_text('{ not json') + fails('config') + CONFIG.write_text(json.dumps({'url': url})) + fails('config') + CONFIG.write_text(json.dumps({'url': url, 'tokenRef': ''})) + fails('config') + + CONFIG.write_text(json.dumps({'url': url, 'tokenRef': token_ref})) + fails('installed', 'bootstrap this host first') + + (CURRENT / 'bin').mkdir(parents=True) + (CURRENT / 'bin/bootstrap-agent').write_text('#!/usr/bin/env python3\n') + (CURRENT / '.release-revision').write_text(old + '\n') + + tip['value'] = 'HEAD' + fails('resolve') + + tip['value'] = old + assert refresh() == 'up to date at ' + old + assert invoked == [], invoked + + tip['value'] = new + assert refresh() == 'updated {} -> {}'.format(old, new) + assert invoked == [[PYTHON, str(CURRENT / 'bin/bootstrap-agent'), '--revision', new, + '--url', url, '--token-ref', token_ref]], invoked + + (CURRENT / '.release-revision').write_text('not a revision\n') + fails('installed') + print('self-check passed') + finally: + shutil.rmtree(root, ignore_errors=True) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Update this host to the current tip of main.') + parser.add_argument('--install', action='store_true', help='schedule this tool as an hourly user LaunchAgent') + parser.add_argument('--job-id', help='hub job id the scheduled run reports under') + parser.add_argument('--self-check', action='store_true', help='prove the compare and failure logic against temp dirs') + args = parser.parse_args() + if args.self_check: + demo() + elif args.install: + print(install(args.job_id)) + elif args.job_id: + parser.error('--job-id only applies to --install') + else: + print(refresh()) diff --git a/deploy/test_refresh.py b/deploy/test_refresh.py new file mode 100644 index 0000000..8d3e690 --- /dev/null +++ b/deploy/test_refresh.py @@ -0,0 +1,115 @@ +import importlib.machinery +import importlib.util +import json +from pathlib import Path +import plistlib +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +TOOL = Path(__file__).resolve().parent.parent / 'bin/refresh-agent' +SPEC = importlib.util.spec_from_file_location( + 'refresh_agent', TOOL, loader=importlib.machinery.SourceFileLoader('refresh_agent', str(TOOL))) +REFRESH = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(REFRESH) + +OLD = 'a' * 40 +NEW = 'b' * 40 +URL = 'https://plans.example' +TOKEN_REF = 'op://Test/Plan/token' + + +class RefreshTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() + self.config = self.root / 'config.json' + self.current = self.root / 'agent-current' + self.commands = [] + for item in [patch.object(REFRESH, 'CONFIG', self.config), + patch.object(REFRESH, 'CURRENT', self.current), + patch.object(REFRESH, 'DATA', self.root / 'data'), + patch.object(REFRESH, 'LAUNCH_AGENTS', self.root / 'LaunchAgents')]: + item.start() + self.addCleanup(item.stop) + + def record(self, command, **kwargs): + self.commands.append([str(part) for part in command]) + return subprocess.CompletedProcess(command, 0) + + def write_config(self, settings=None): + self.config.write_text(json.dumps({'url': URL, 'tokenRef': TOKEN_REF} if settings is None else settings)) + + def install_package(self, revision): + (self.current / 'bin').mkdir(parents=True, exist_ok=True) + (self.current / '.release-revision').write_text(revision + '\n') + for tool in ['bootstrap-agent', 'refresh-agent']: + (self.current / 'bin' / tool).write_text('#!/usr/bin/env python3\n') + + def refresh(self, tip): + with patch.object(REFRESH, 'fetch_tip', return_value=tip), \ + patch.object(REFRESH.subprocess, 'run', self.record): + return REFRESH.refresh() + + def test_matching_pin_leaves_the_host_untouched(self): + self.write_config() + self.install_package(OLD) + self.assertEqual(self.refresh(OLD), 'up to date at ' + OLD) + self.assertEqual(self.commands, []) + self.assertEqual((self.current / '.release-revision').read_text(), OLD + '\n') + + def test_new_tip_installs_it_with_the_configured_url_and_token(self): + self.write_config() + self.install_package(OLD) + self.assertEqual(self.refresh(NEW), 'updated {} -> {}'.format(OLD, NEW)) + self.assertEqual(self.commands, [['/usr/bin/python3', str(self.current / 'bin/bootstrap-agent'), + '--revision', NEW, '--url', URL, '--token-ref', TOKEN_REF]]) + + def test_missing_config_reports_the_config_step(self): + self.install_package(OLD) + with self.assertRaises(SystemExit) as caught: + self.refresh(NEW) + self.assertTrue(str(caught.exception).startswith('config: '), caught.exception) + self.assertIn('bootstrap this host first', str(caught.exception)) + self.assertEqual(self.commands, []) + + def test_missing_package_reports_the_installed_step(self): + self.write_config() + with self.assertRaises(SystemExit) as caught: + self.refresh(NEW) + self.assertTrue(str(caught.exception).startswith('installed: '), caught.exception) + self.assertIn('bootstrap this host first', str(caught.exception)) + self.assertEqual(self.commands, []) + + def test_install_schedules_the_hub_wrapped_hourly_job(self): + self.install_package(OLD) + hub = self.root / 'run' + hub.write_text('#!/bin/zsh\n') + with patch.object(REFRESH, 'HUB_RUN', hub), patch.object(REFRESH.subprocess, 'run', self.record): + REFRESH.install('mini.launchd.html-plan-agent-refresh') + plist = plistlib.loads((self.root / 'LaunchAgents' / (REFRESH.LABEL + '.plist')).read_bytes()) + self.assertEqual(plist['ProgramArguments'], ['/bin/zsh', str(hub), 'mini.launchd.html-plan-agent-refresh', + '--', '/usr/bin/python3', str(self.current / 'bin/refresh-agent')]) + self.assertEqual(plist['StartInterval'], 3600) + self.assertEqual(plist['Label'], 'com.mimen.html-plan-host.agent-refresh') + + def test_install_refuses_a_plist_it_did_not_write(self): + self.install_package(OLD) + hub = self.root / 'run' + hub.write_text('#!/bin/zsh\n') + target = self.root / 'LaunchAgents' / (REFRESH.LABEL + '.plist') + target.parent.mkdir(parents=True) + foreign = {'Label': REFRESH.LABEL, 'ProgramArguments': ['/bin/echo', 'another-owner']} + target.write_bytes(plistlib.dumps(foreign)) + with patch.object(REFRESH, 'HUB_RUN', hub), patch.object(REFRESH.subprocess, 'run', self.record): + with self.assertRaises(SystemExit) as caught: + REFRESH.install('mini.launchd.html-plan-agent-refresh') + self.assertIn('belongs to another owner', str(caught.exception)) + self.assertEqual(plistlib.loads(target.read_bytes()), foreign) + self.assertEqual(self.commands, []) + + +if __name__ == '__main__': + unittest.main() From a09a09efde8268611a854b5f03cc9c520a9b427d Mon Sep 17 00:00:00 2001 From: Milad Imen Date: Tue, 15 Sep 2026 13:37:50 -0700 Subject: [PATCH 2/2] Lock the refresh against overlapping runs and fix its job id example Two hourly runs, or one racing a manual bootstrap-agent, would both clear install-agent's guards and then race the agent-current relink. mini-host.py takes the same non-blocking flock around activate; a second runner now exits naming the lock step instead of interleaving. The documented and suggested job ids also have to follow the registry's .launchd.