ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.
Python ai-agentsamdcomfyuidockerllama-cppllmlocal-ain8nnvidiaopen-webuiragself-hostedspeech-to-textstrix-halotext-to-speechworkflow-automation
fix(installer): refresh stale Hermes file mounts after publication (#8170)
Mike Bradley7f5c6c2232c8
diff --git a/ods/installers/phases/11-services.sh b/ods/installers/phases/11-services.shindex 1b6ee80aa..f0d2f744d 100755--- a/ods/installers/phases/11-services.sh+++ b/ods/installers/phases/11-services.sh@@ -96,6 +96,18 @@ _phase11_refresh_litellm() {fi}+_phase11_refresh_hermes_mounts() {+ [[ "${ENABLE_HERMES:-false}" == true ]] || return 0+ local python_cmd flag+ local -a args=()+ python_cmd="${ODS_PYTHON_CMD:-$(command -v python3 2>/dev/null || true)}"+ [[ -n "$python_cmd" ]] || return 1+ for flag in "${COMPOSE_FLAGS_ARR[@]}"; do args+=("--compose-arg=$flag"); done+ "$python_cmd" "$INSTALL_DIR/scripts/refresh-hermes-mounts.py" \+ --install-dir "$INSTALL_DIR" --docker-command "$DOCKER_CMD" \+ --compose-command "$DOCKER_COMPOSE_CMD" "${args[@]}" >>"$LOG_FILE" 2>&1+}+_phase11_build_local_images() {local -a build_services=("$@")local -a failed_build_services=()@@ -1636,6 +1648,15 @@ MODELS_INI_EOFif [[ -n "${_python_cmd:-}" ]] && [[ -f "$INSTALL_DIR/scripts/build-installation-context.py" ]]; then"$_python_cmd" "$INSTALL_DIR/scripts/build-installation-context.py" >>"$LOG_FILE" 2>&1 || \warn "Installation-context SOUL.md regen failed post-launch (non-fatal — earlier static SOUL.md is in place)"+ fi+ # Source publication replaces file inodes while an unchanged running+ # Hermes can retain old binds. Check after the final SOUL render, before+ # copying that mounted persona; preserve the existing live config.+ if ! _phase11_refresh_hermes_mounts; then+ ai_bad "Could not verify Hermes mounted files. See $LOG_FILE."+ exit 1+ fi+ if [[ -n "${_python_cmd:-}" ]] && [[ -f "$INSTALL_DIR/scripts/build-installation-context.py" ]]; thenif $DOCKER_CMD ps --format '{{.Names}}' 2>/dev/null | grep -qx 'ods-hermes'; then$DOCKER_CMD exec ods-hermes cp /opt/hermes/docker/SOUL.md /opt/data/SOUL.md \>>"$LOG_FILE" 2>&1 || \diff --git a/ods/scripts/refresh-hermes-mounts.py b/ods/scripts/refresh-hermes-mounts.pynew file mode 100644index 000000000..46c964172--- /dev/null+++ b/ods/scripts/refresh-hermes-mounts.py@@ -0,0 +1,195 @@+#!/usr/bin/env python3+"""Rebind only this installation's Hermes when its reviewed file mounts are stale."""+import argparse+import hashlib+import json+import os+from pathlib import Path+import re+import shlex+import stat+import subprocess+import time+++FILES = {+ "/opt/hermes/cli-config.yaml.example": "extensions/services/hermes/cli-config.yaml.template",+ "/opt/hermes/ods-auth-bootstrap.py": "extensions/services/dashboard-api/hermes_auth.py",+ "/opt/hermes/docker/SOUL.md": "data/persona/SOUL.md",+}+LIVE_CONFIG = "/opt/data/config.yaml"+MAX_BYTES = 1024 * 1024+DESKTOP_FILE_SOURCE = re.compile(+ r"/run/desktop/mnt/host/wsl/docker-desktop-bind-mounts/[A-Za-z0-9_.-]{1,128}/[a-f0-9]{64}"+)+# Hash inside the container: never return credential-bearing file contents.+CONTAINER_DIGESTS = """import hashlib,json,os,stat,sys+result={}+for path in sys.argv[1:]:+ try:+ fd=os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)+ except FileNotFoundError:+ if path == '/opt/data/config.yaml':+ result[path]=None+ continue+ raise+ with os.fdopen(fd,'rb') as source:+ info=os.fstat(source.fileno())+ if not stat.S_ISREG(info.st_mode) or info.st_size > 1048576:+ raise ValueError('unsupported file')+ raw=source.read(1048577)+ if len(raw)>1048576: raise ValueError('oversized file')+ result[path]=hashlib.sha256(raw).hexdigest()+print(json.dumps(result))+"""+++class Refused(RuntimeError):+ pass+++def execute(argv, cwd, timeout=30):+ try:+ result = subprocess.run(argv, cwd=cwd, capture_output=True, timeout=timeout, check=True)+ return result.stdout.decode("utf-8")+ except (OSError, UnicodeError, subprocess.SubprocessError) as exc:+ # Docker/config errors may contain secrets. Keep them out of installer logs.+ raise Refused("Hermes mount verification command failed") from exc+++def host_digests(root):+ result = {}+ for destination, relative in FILES.items():+ path = root+ for component in Path(relative).parts:+ path = path / component+ if path.is_symlink():+ raise Refused("Hermes mount source contains a symlink")+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)+ with os.fdopen(fd, "rb") as source:+ info = os.fstat(source.fileno())+ if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_BYTES:+ raise Refused("Hermes mount source is not a bounded regular file")+ raw = source.read(MAX_BYTES + 1)+ if len(raw) > MAX_BYTES:+ raise Refused("Hermes mount source is too large")+ result[destination] = hashlib.sha256(raw).hexdigest()+ return result+++def refresh(root, docker, compose, run=execute):+ root = Path(root).absolute()+ if root != root.resolve() or not root.is_dir():+ raise Refused("Hermes installation root is not a real directory")+ config = json.loads(run(compose + ["config", "--format", "json"], root))+ service = config["services"].get("hermes")+ if service is None:+ return "not-selected"+ project = config["name"]+ if not isinstance(project, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", project):+ raise Refused("Hermes Compose project is invalid")+ volumes = service.get("volumes", [])+ for destination, relative in {**FILES, "/opt/data": "data/hermes"}.items():+ matches = [item for item in volumes if item.get("target") == destination]+ if (len(matches) != 1 or matches[0].get("type") != "bind"+ or matches[0].get("source") != str(root / relative)+ or bool(matches[0].get("read_only")) != (destination != "/opt/data")):+ raise Refused("Hermes Compose mount is outside the installed contract")++ def container():+ ids = run(compose + ["ps", "--all", "--quiet", "hermes"], root).split()+ if len(ids) != 1 or not re.fullmatch(r"[a-f0-9]{64}", ids[0]):+ raise Refused("Hermes container identity is unavailable or ambiguous")+ inspected = json.loads(run(docker + ["inspect", ids[0]], root))+ if not isinstance(inspected, list) or len(inspected) != 1:+ raise Refused("Hermes container inspection is invalid")+ item = inspected[0]+ labels = item.get("Config", {}).get("Labels", {}) or {}+ if (item.get("Id") != ids[0] or item.get("State", {}).get("Running") is not True+ or labels.get("com.docker.compose.project") != project+ or labels.get("com.docker.compose.service") != "hermes"+ or labels.get("com.docker.compose.project.working_dir") != str(root)+ or labels.get("com.docker.compose.oneoff", "").lower() != "false"):+ raise Refused("Hermes running-container ownership could not be verified")+ if item["State"].get("Health", {}).get("Status") not in {"starting", "healthy", "unhealthy"}:+ raise Refused("Hermes container health observation is unavailable")+ for destination in [*FILES, "/opt/data"]:+ mounts = [mount for mount in item.get("Mounts", []) if mount.get("Destination") == destination]+ if (len(mounts) != 1 or mounts[0].get("Type") != "bind"+ or mounts[0].get("RW") is not (destination == "/opt/data")):+ raise Refused("Hermes running mount is outside the installed contract")+ relative = "data/hermes" if destination == "/opt/data" else FILES[destination]+ source = mounts[0].get("Source")+ # Desktop substitutes individual WSL file binds with a proxy inode.+ # Directory binds must still identify this installation's live data.+ if source != str(root / relative) and not (+ destination in FILES and isinstance(source, str) and DESKTOP_FILE_SOURCE.fullmatch(source)):+ raise Refused("Hermes running mount has an unexplained source")+ return item++ def observed(identity):+ values = json.loads(run(docker + ["exec", identity, "python3", "-c", CONTAINER_DIGESTS,+ *FILES, LIVE_CONFIG], root))+ if (not isinstance(values, dict) or set(values) != {*FILES, LIVE_CONFIG}+ or any(not (key == LIVE_CONFIG and value is None)+ and (not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{64}", value))+ for key, value in values.items())):+ raise Refused("Hermes file hashes could not be verified")+ return values++ expected = host_digests(root)+ identity = container()["Id"]+ before = observed(identity)+ if all(before[path] == value for path, value in expected.items()):+ return "current"+ # Recheck the installation and selected container immediately before the+ # only mutation. Never repair an unreadable file or a changed ownership claim.+ if (host_digests(root) != expected or container()["Id"] != identity+ or json.loads(run(compose + ["config", "--format", "json"], root)) != config):+ raise Refused("Hermes installation changed during mount verification")+ run(compose + ["up", "-d", "--no-deps", "--force-recreate", "--no-build", "--pull", "never", "hermes"],+ root, timeout=120)+ # The real entrypoint can seed/migrate live state during startup. Compare+ # config and file hashes only after its configured health probe succeeds.+ deadline = time.monotonic() + 180+ refreshed = container()+ new_identity = refreshed["Id"]+ if new_identity == identity:+ raise Refused("Hermes recreation did not replace the selected container")+ while refreshed["State"]["Health"]["Status"] != "healthy":+ if refreshed["State"]["Health"]["Status"] == "unhealthy" or time.monotonic() >= deadline:+ raise Refused("Hermes did not become healthy after one recreation")+ time.sleep(2)+ refreshed = container()+ if refreshed["Id"] != new_identity:+ raise Refused("Hermes container changed while awaiting startup")+ after = observed(new_identity)+ if host_digests(root) != expected or any(after[path] != value for path, value in expected.items()):+ raise Refused("Hermes mounted files still differ after one recreation")+ if before[LIVE_CONFIG] is not None and before[LIVE_CONFIG] != after[LIVE_CONFIG]:+ raise Refused("Hermes live configuration changed during recreation; review before continuing")+ return "refreshed"+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--install-dir", type=Path, required=True)+ parser.add_argument("--docker-command", default="docker")+ parser.add_argument("--compose-command", default="docker compose")+ parser.add_argument("--compose-arg", action="append", default=[])+ args = parser.parse_args()+ try:+ result = refresh(args.install_dir, shlex.split(args.docker_command),+ shlex.split(args.compose_command) + args.compose_arg)+ except Refused as exc:+ print(str(exc) + "; no further automatic recreation.")+ return 1+ except (OSError, ValueError, TypeError, KeyError, AttributeError):+ print("Hermes mounted-file verification failed; no further automatic recreation. Review the installation before retrying.")+ return 1+ print("Hermes mounted files: " + result)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/ods/tests/ci-suite.txt b/ods/tests/ci-suite.txtindex 41505c2e0..9c67fbe12 100644--- a/ods/tests/ci-suite.txt+++ b/ods/tests/ci-suite.txt@@ -194,6 +194,7 @@ tests/test-phase10-skip-templated-user-units.shtests/test-phase11-compose-recovery-status.shtests/test-phase11-download-linger.shtests/test-phase11-exited-service-recovery.sh+tests/test-phase11-hermes-mount-refresh.pytests/test-pixel-output-budget.shtests/test-port-ollama-detection.shtests/test-postflight-docker-context.shdiff --git a/ods/tests/test-phase11-hermes-mount-refresh.py b/ods/tests/test-phase11-hermes-mount-refresh.pynew file mode 100644index 000000000..5b2f58217--- /dev/null+++ b/ods/tests/test-phase11-hermes-mount-refresh.py@@ -0,0 +1,251 @@+#!/usr/bin/env python3+"""Retained running Hermes file binds must follow installed source publication."""+import hashlib+import importlib.util+import json+import os+from pathlib import Path+import tempfile+import unittest+from unittest.mock import patch++ROOT = Path(__file__).resolve().parents[1]+spec = importlib.util.spec_from_file_location("hermes_mounts", ROOT / "scripts/refresh-hermes-mounts.py")+mounts = importlib.util.module_from_spec(spec)+spec.loader.exec_module(mounts)+++class DockerFixture:+ def __init__(self, root):+ self.root = root+ self.calls = []+ self.identity = "a" * 64+ self.live = b"owner live config: preserve exactly\n"+ self.other_identity = "b" * 64+ self.keep_stale = False+ self.change_live = False+ self.read_error = False+ self.ids = None+ self.project = "ods"+ self.labels = {+ "com.docker.compose.project": self.project,+ "com.docker.compose.service": "hermes",+ "com.docker.compose.project.working_dir": str(root),+ "com.docker.compose.oneoff": "False",+ }+ self.running = True+ self.health = "healthy"+ self.startup_health = []+ self.volumes = []+ for destination, relative in {**mounts.FILES, "/opt/data": "data/hermes"}.items():+ source = root / relative+ source.parent.mkdir(parents=True, exist_ok=True)+ if destination == "/opt/data":+ source.mkdir()+ (source / "config.yaml").write_bytes(self.live)+ else:+ source.write_bytes(("original " + destination).encode())+ self.volumes.append(dict(type="bind", source=str(source), target=destination,+ read_only=destination != "/opt/data"))+ self.mounted = {destination: (root / relative).read_bytes() for destination, relative in mounts.FILES.items()}+ self.inspected_mounts = [dict(Type="bind", Source=v["source"], Destination=v["target"], RW=not v["read_only"])+ for v in self.volumes]+ self.selected = True++ def replace(self, destination):+ path = self.root / mounts.FILES[destination]+ temporary = path.with_name(path.name + ".new")+ temporary.write_bytes(b"reviewed replacement bytes")+ os.replace(temporary, path)++ def run(self, argv, cwd, timeout=30):+ assert cwd == self.root+ self.calls.append(argv)+ if argv[0] == "compose":+ args = argv[1:]+ if args == ["config", "--format", "json"]:+ return json.dumps(dict(name=self.project, services={"hermes": {"volumes": self.volumes}} if self.selected else {}))+ if args == ["ps", "--all", "--quiet", "hermes"]:+ return self.ids if self.ids is not None else self.identity + "\n"+ if args == ["up", "-d", "--no-deps", "--force-recreate", "--no-build", "--pull", "never", "hermes"]:+ assert timeout == 120+ self.identity = "c" * 64+ if not self.keep_stale:+ self.mounted = {p: (self.root / relative).read_bytes() for p, relative in mounts.FILES.items()}+ if self.change_live:+ self.live = b"unexpected upstream config change"+ return ""+ if argv[:2] == ["docker", "inspect"]:+ if self.identity == "c" * 64 and self.startup_health:+ self.health = self.startup_health.pop(0)+ return json.dumps([dict(Id=self.identity, Config={"Labels": self.labels},+ State={"Running": self.running, "Health": {"Status": self.health}},+ Mounts=self.inspected_mounts)])+ if argv[:2] == ["docker", "exec"]:+ if self.read_error:+ raise mounts.Refused("unreadable container file")+ assert argv[2] == self.identity and argv[3:6] == ["python3", "-c", mounts.CONTAINER_DIGESTS]+ return json.dumps({**{p: hashlib.sha256(raw).hexdigest() for p, raw in self.mounted.items()},+ mounts.LIVE_CONFIG: hashlib.sha256(self.live).hexdigest()})+ raise AssertionError("Unexpected Docker command: " + repr(argv[:4]))++ def refresh(self):+ return mounts.refresh(self.root, ["docker"], ["compose"], self.run)++ def mutations(self):+ return [call for call in self.calls if call[:2] == ["compose", "up"]]+++class HermesMountTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name).resolve()+ self.docker = DockerFixture(self.root)++ def test_each_reviewed_replaced_file_rebinds_once_without_touching_live_config_or_other_services(self):+ for destination in mounts.FILES:+ with self.subTest(destination=destination):+ self.docker.calls.clear()+ self.docker.identity = "a" * 64+ # Change each file again, retaining the old mounted bytes.+ path = self.root / mounts.FILES[destination]+ replacement = path.with_name(path.name + ".new")+ replacement.write_bytes(path.read_bytes() + b" updated")+ os.replace(replacement, path)+ live = (self.root / "data/hermes/config.yaml").read_bytes()+ self.assertEqual(self.docker.refresh(), "refreshed")+ self.assertEqual(len(self.docker.mutations()), 1)+ self.assertEqual(self.docker.mounted[destination], path.read_bytes())+ self.assertEqual((self.root / "data/hermes/config.yaml").read_bytes(), live)+ self.assertEqual(self.docker.live, live)+ self.assertEqual(self.docker.other_identity, "b" * 64)++ def test_current_mounts_and_unselected_hermes_do_not_restart(self):+ self.assertEqual(self.docker.refresh(), "current")+ self.docker.selected = False+ self.assertEqual(self.docker.refresh(), "not-selected")+ self.assertFalse(self.docker.mutations())++ def test_unknown_owner_or_mount_is_not_recreated(self):+ for key in self.docker.labels:+ with self.subTest(label=key):+ original = self.docker.labels[key]+ self.docker.labels[key] = "foreign"+ with self.assertRaises(mounts.Refused):+ self.docker.refresh()+ self.docker.labels[key] = original+ self.docker.volumes[0]["source"] = "/foreign/config"+ with self.assertRaises(mounts.Refused):+ self.docker.refresh()+ self.assertFalse(self.docker.mutations())++ def test_unreadable_mount_or_ambiguous_container_fails_without_recreation(self):+ self.docker.read_error = True+ with self.assertRaises(mounts.Refused):+ self.docker.refresh()+ self.docker.read_error = False+ for ids in ("", "short-id", "a" * 64 + "\n" + "b" * 64):+ self.docker.ids = ids+ with self.assertRaises(mounts.Refused):+ self.docker.refresh()+ self.assertFalse(self.docker.mutations())++ def test_foreign_live_data_and_unexplained_file_sources_never_recreate(self):+ self.docker.replace(next(iter(mounts.FILES)))+ for mounted in self.docker.inspected_mounts:+ with self.subTest(destination=mounted["Destination"]):+ original = mounted["Source"]+ mounted["Source"] = "/foreign/owner-data"+ with self.assertRaisesRegex(mounts.Refused, "unexplained source"):+ self.docker.refresh()+ mounted["Source"] = original+ self.assertFalse(self.docker.mutations())++ def test_desktop_file_proxy_is_allowed_only_for_readonly_files(self):+ proxy = "/run/desktop/mnt/host/wsl/docker-desktop-bind-mounts/Ubuntu-24.04/" + "d" * 64+ self.docker.inspected_mounts[0]["Source"] = proxy+ self.docker.replace(next(iter(mounts.FILES)))+ self.assertEqual(self.docker.refresh(), "refreshed")+ self.docker.inspected_mounts[-1]["Source"] = proxy+ with self.assertRaisesRegex(mounts.Refused, "unexplained source"):+ self.docker.refresh()+ self.assertEqual(len(self.docker.mutations()), 1)++ def test_postcheck_waits_for_healthy_startup_without_another_recreation(self):+ self.docker.replace(next(iter(mounts.FILES)))+ self.docker.startup_health = ["starting", "starting", "healthy"]+ with patch.object(mounts.time, "sleep") as sleep:+ self.assertEqual(self.docker.refresh(), "refreshed")+ self.assertEqual(sleep.call_count, 2)+ self.assertEqual(len(self.docker.mutations()), 1)++ def test_unhealthy_or_timed_out_startup_fails_without_retry(self):+ self.docker.replace(next(iter(mounts.FILES)))+ self.docker.startup_health = ["unhealthy"]+ with self.assertRaisesRegex(mounts.Refused, "did not become healthy"):+ self.docker.refresh()+ self.assertEqual(len(self.docker.mutations()), 1)+ self.docker.identity = "a" * 64+ self.docker.replace(next(iter(mounts.FILES)))+ self.docker.mounted[next(iter(mounts.FILES))] = b"stale again"+ self.docker.startup_health = ["starting"]+ with patch.object(mounts.time, "monotonic", side_effect=[0, 181]):+ with self.assertRaisesRegex(mounts.Refused, "did not become healthy"):+ self.docker.refresh()+ self.assertEqual(len(self.docker.mutations()), 2)++ def test_source_symlink_and_nonrunning_container_fail_without_recreation(self):+ self.docker.running = False+ with self.assertRaises(mounts.Refused):+ self.docker.refresh()+ self.docker.running = True+ path = self.root / next(iter(mounts.FILES.values()))+ path.unlink()+ path.symlink_to(self.root / "data/hermes/config.yaml")+ with self.assertRaises(mounts.Refused):+ self.docker.refresh()+ self.assertFalse(self.docker.mutations())++ def test_failed_postcheck_never_retries(self):+ self.docker.replace(next(iter(mounts.FILES)))+ self.docker.keep_stale = True+ with self.assertRaises(mounts.Refused):+ self.docker.refresh()+ self.assertEqual(len(self.docker.mutations()), 1)++ def test_live_configuration_change_is_reported(self):+ self.docker.replace(next(iter(mounts.FILES)))+ self.docker.change_live = True+ with self.assertRaisesRegex(mounts.Refused, "live configuration changed"):+ self.docker.refresh()+ self.assertEqual(len(self.docker.mutations()), 1)++ def test_source_change_during_check_prevents_recreation(self):+ self.docker.replace(next(iter(mounts.FILES)))+ original = self.docker.run+ def changing(argv, cwd, timeout=30):+ result = original(argv, cwd, timeout)+ if argv[:2] == ["docker", "exec"]:+ (self.root / next(iter(mounts.FILES.values()))).write_bytes(b"concurrent edit")+ return result+ self.docker.run = changing+ with self.assertRaisesRegex(mounts.Refused, "installation changed"):+ self.docker.refresh()+ self.assertFalse(self.docker.mutations())++ def test_installer_orders_check_after_final_render_before_persona_copy(self):+ phase = (ROOT / "installers/phases/11-services.sh").read_text()+ complete = phase.index("if ! ods_pixel_install_default_agent; then")+ patch = phase.index('_phase11_apply_hermes_template "${_phase11_hermes_template_route[@]}"', complete)+ render = phase.index('"$_python_cmd" "$INSTALL_DIR/scripts/build-installation-context.py"', patch)+ check = phase.index("if ! _phase11_refresh_hermes_mounts; then", render)+ copy_persona = phase.index("$DOCKER_CMD exec ods-hermes cp", render)+ self.assertLess(complete, patch)+ self.assertLess(render, check)+ self.assertLess(check, copy_persona)+ self.assertIn('exit 1', phase[check:copy_persona])+++if __name__ == "__main__":+ unittest.main()