Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions DEPLOY.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ python3 bin/bootstrap-agent --revision <full-commit-sha> \

The bootstrap fetches the GitHub archive directly into `~/.local/share/html-plan-host/packages/<sha>`. `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 <host>.launchd.com.mimen.html-plan-host.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
Expand Down
203 changes: 203 additions & 0 deletions bin/refresh-agent
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
#!/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.' + LABEL)
# 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:
# Two hourly runs, or one racing a manual bootstrap-agent, would both clear
# install-agent's guards and then race the agent-current relink.
import fcntl
DATA.mkdir(parents=True, exist_ok=True)
with (DATA / 'refresh.lock').open('a') as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
raise SystemExit('lock: another refresh is already running')
print(refresh())
115 changes: 115 additions & 0 deletions deploy/test_refresh.py
Original file line number Diff line number Diff line change
@@ -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()
Loading