| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404 |
- """Exercise the installed Hermes runtime in a network-isolated local Docker container.
- Run through scripts/verify-container-runtime.mjs; /evidence contains read-only source
- copies from the server template, never environment files or production state.
- """
- from __future__ import annotations
- import hashlib
- import contextlib
- import importlib.util
- import io
- import json
- import os
- from pathlib import Path
- import shutil
- import sqlite3
- import subprocess
- import sys
- import tempfile
- import threading
- import time
- import unittest
- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
- from unittest.mock import patch
- import urllib.request
- ROOT = Path(__file__).resolve().parents[2]
- SKILL = ROOT / "cloud/skills/container-provision-job"
- EVIDENCE = Path(os.environ.get("FMODE_RUNTIME_EVIDENCE", "/evidence"))
- def load_file(name, path):
- spec = importlib.util.spec_from_file_location(name, path)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
- def old_file(path, content, old):
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(content, encoding="utf-8")
- os.utime(path, (old, old))
- return path
- def runtime_directories_case(home):
- fixture = Path(os.environ['FMODE_PROVISIONED_FIXTURE'])
- assert os.getuid() == 10000, 'Permission checks must run as the real Hermes user'
- for relative in ('cache', 'sessions', 'work'):
- parent = fixture / relative
- assert os.access(parent, os.W_OK), f'Provisioned runtime parent is not writable: {parent}'
- with tempfile.TemporaryDirectory(prefix='.runtime-write-', dir=parent) as temp:
- target = Path(temp) / 'state.json'
- target.write_text('{"checked":true}', encoding='utf-8')
- target.replace(Path(temp) / 'committed.json')
- return {'runtimeUid': os.getuid(), 'writableParents': ['cache', 'sessions', 'work']}
- def scheduler_case(home):
- contract = load_file("gc_contract", ROOT / "cloud/scripts/test_fmode_safe_gc_scheduler.py")
- scripts = home / "scripts"
- scripts.mkdir()
- for name in ("fmode-safe-gc.py", "fmode-safe-gc-run.py"):
- shutil.copy2(SKILL / name, scripts / name)
- cron = home / "cron"
- cron.mkdir()
- (cron / "jobs.json").write_text(json.dumps({"jobs": [
- {"id": "other-job", "name": "preserve-me", "enabled": False,
- "script": "never-run.py", "no_agent": True, "state": "paused"},
- {"id": "old-media-gc", "name": "media-gc-delayed-cleanup", "enabled": True,
- "script": "fmode-media-gc-wrapper.sh", "no_agent": True, "state": "scheduled"},
- ]}), encoding="utf-8")
- installed = contract.run_installer(home)
- assert installed.returncode == 0, installed.stderr
- again = contract.run_installer(home)
- assert again.returncode == 0, again.stderr
- now, old = time.time(), time.time() - 7200
- uploaded = old_file(home / "work/uploads/ack.txt", "verified upload", old)
- pending = old_file(home / "work/uploads/pending.txt", "unregistered upload", old)
- active = old_file(home / "work/tasks/active/output.txt", "still used", old)
- (active.parent / ".fmode-task.json").write_text(json.dumps({
- "status": "running", "activeSessionIds": ["active-session"],
- "lastActivityAt": int(old * 1000), "files": [],
- }), encoding="utf-8")
- cache = old_file(home / "cache/regenerable/index.tmp", "regenerable", old)
- state = home / "cache/deliverable-hook/session.json"
- state.parent.mkdir(parents=True, exist_ok=True)
- record = lambda p: {"path": str(p), "url": "https://s3.fmode.cn/fixture.txt",
- "uploadedAt": int(old * 1000), "cloudAck": True,
- "hubRegistered": True, "sha256": hashlib.sha256(p.read_bytes()).hexdigest()}
- state.write_text(json.dumps({"pushed": [record(uploaded), record(active)]}), encoding="utf-8")
- protected = old_file(home / "skills/custom/keep.txt", "protected skill", old)
- from cron import jobs, scheduler
- due = jobs.get_due_jobs()
- target = [j for j in due if j.get("name") == "fmode-safe-gc"]
- assert len(target) == 1, due
- job_id = target[0]["id"]
- assert scheduler.tick(verbose=False) == 1
- deadline = time.monotonic() + 45
- job = jobs.get_job(job_id)
- while time.monotonic() < deadline and not job.get("last_run_at"):
- time.sleep(0.1)
- job = jobs.get_job(job_id)
- assert job.get("last_status") == "ok", job
- assert not uploaded.exists(), "actual scheduler subprocess did not run the cleaner"
- assert not cache.exists()
- assert pending.exists() and active.exists() and protected.exists()
- assert state.exists() and json.loads(state.read_text())["pushed"][0]["gc"] is True
- assert job["repeat"]["completed"] == 1, job
- assert job["state"] == "scheduled" and not job.get("last_error"), job
- from datetime import datetime
- next_at = datetime.fromisoformat(job["next_run_at"]).timestamp()
- assert 1700 < next_at - now < 1900, job
- assert jobs.get_job("old-media-gc")["enabled"] is False
- assert jobs.get_job("other-job")["script"] == "never-run.py"
- assert scheduler.tick(verbose=False) == 0, "an immediate second tick must not run it twice"
- return {"actualTick": True, "lastStatus": job["last_status"], "runs": 1,
- "legacyCleanerPaused": True, "protectedFilesRetained": True}
- def skills_case(home):
- names = []
- for category in ("platform", "custom"):
- name = "baseline-" + category + "-check"
- path = home / "skills" / category / name / "SKILL.md"
- path.parent.mkdir(parents=True)
- path.write_text(f"---\nname: {name}\ndescription: Local runtime acceptance fixture.\n---\n\n"
- f"# {name}\n\nRead acceptance instructions for {category}.\n", encoding="utf-8")
- names.append(name)
- from tools.skills_tool import skills_list, skill_view
- listed = json.loads(skills_list())
- assert listed["success"], listed
- found = {skill["name"] for skill in listed["skills"]}
- assert set(names).issubset(found), listed
- for name in names:
- viewed = json.loads(skill_view(name, preprocess=False))
- assert viewed["success"] and "Read acceptance instructions" in json.dumps(viewed), viewed
- cli = subprocess.run(["/opt/hermes/.venv/bin/hermes", "skills", "list", "--source", "local",
- "--enabled-only"], text=True, capture_output=True, timeout=45)
- assert cli.returncode == 0, cli.stderr
- assert all(name in cli.stdout for name in names), cli.stdout
- return {"cliDiscoversBoth": True, "agentCanReadBoth": True, "skills": names}
- def patch_case(home):
- checks = {}
- # A shared image tag is insufficient: compare the installed runtime files
- # with copies read from the running server container.
- matched = []
- for relative in ("cron/scheduler.py", "cron/scheduler_script.py", "cron/scheduler_tick.py",
- "cron/jobs.py", "tools/skills_tool.py", "agent/skill_utils.py"):
- installed = Path("/opt/hermes") / relative
- expected = EVIDENCE / relative
- # Windows evidence copies can use CRLF; compare the exact Python source
- # after the same universal-newline decoding used by Python's loader.
- assert hashlib.sha256(installed.read_text(encoding="utf-8").encode()).digest() == hashlib.sha256(
- expected.read_text(encoding="utf-8").encode()).digest(), relative
- matched.append(relative)
- checks["serverRuntimeSourceMatch"] = matched
- for patcher, relative in [
- ("patch_app_reporter", "template/plugins/plugin-active-reporter/__init__.py"),
- ("patch_process_notice", "template/scripts/fmode-process-notice.py"),
- ("patch_deliverable_ack", "data/scripts/fmode-deliverable-hook.py"),
- ]:
- module = load_file(patcher, SKILL / (patcher + ".py"))
- original = (EVIDENCE / relative).read_text(encoding="utf-8")
- updated = module.patch_text(original)
- assert module.patch_text(updated) == updated
- compile(updated, relative, "exec")
- checks[patcher] = {"sourceSha256": hashlib.sha256(original.encode()).hexdigest(),
- "patchValidAndIdempotent": True}
- if patcher == "patch_app_reporter":
- scope = {"__name__": "runtime_acceptance"}
- exec(compile(updated, relative, "exec"), scope)
- (home / "gateway_state.json").write_text(json.dumps({
- "platforms": {"matrix": {"state": "connected"}},
- }), encoding="utf-8")
- sent = []
- scope["_balance_value"] = lambda: ("", None)
- scope["_push_with_sessions"] = lambda fields: sent.append(fields) or True
- assert scope["_heartbeat_once"](0)
- assert set(sent[0]) == {"heartbeatAt", "channels"}, sent
- assert json.loads(sent[0]["channels"])["matrix"] is True
- scope["_session_mark_running"]("session-a", "acceptance task")
- scope["_session_key_for"] = lambda sid: "$" + sid
- scope["_user_id_of"] = lambda sid: "@fixture:local"
- rows = scope["_sessions_snapshot"]()
- assert rows[0]["task"] == "acceptance task" and rows[0]["status"] == "running"
- scope["_session_mark_idle"]("session-a")
- assert scope["_sessions_snapshot"]()[0]["status"] == "idle"
- checks[patcher]["realHeartbeatAndSessionTransitions"] = True
- return checks
- def notice_case(home):
- requests = []
- class Handler(BaseHTTPRequestHandler):
- def log_message(self, *_):
- pass
- def respond(self):
- data = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
- requests.append((self.command, self.path, data))
- answer = {"access_token": "local-test-token"} if self.path.endswith("/login") else {
- "event_id": "$local-" + str(len(requests))}
- body = json.dumps(answer).encode()
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.send_header("Content-Length", str(len(body)))
- self.end_headers()
- self.wfile.write(body)
- do_POST = respond
- do_PUT = respond
- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
- threading.Thread(target=server.serve_forever, daemon=True).start()
- try:
- db = sqlite3.connect(home / "state.db")
- db.execute("CREATE TABLE sessions (id TEXT, chat_id TEXT, thread_id TEXT)")
- db.execute("INSERT INTO sessions VALUES (?, ?, ?)", ("session-a", "!room:local", "$root:local"))
- db.commit()
- db.close()
- patcher = load_file("notice_patcher", SKILL / "patch_process_notice.py")
- updated = patcher.patch_text((EVIDENCE / "template/scripts/fmode-process-notice.py").read_text())
- scope = {"__name__": "runtime_acceptance"}
- exec(compile(updated, "fmode-process-notice.py", "exec"), scope)
- scope.update({"HOME": home, "STATE_DB": home / "state.db", "ENV_FILE": home / ".env",
- "LOG": home / "notice.log", "THROTTLE_DIR": home / "cache/process-notice",
- "AUTH_CACHE_ROOT": home / "auth-cache"})
- (home / ".env").write_text(
- f"MATRIX_HOMESERVER=http://127.0.0.1:{server.server_port}\n"
- "MATRIX_USER_ID=@fixture:local\nMATRIX_PASSWORD=local-test-password\n"
- f"HERMES_HOME={home}\n", encoding="utf-8")
- before = sys.stdin
- try:
- for number in range(3):
- sys.stdin = io.StringIO(json.dumps({"session_id": "session-a", "tool_name": "terminal",
- "tool_input": {"command": f"echo step-{number}; TOKEN=never-expose-this"}}))
- assert scope["main"](["notice.py"]) == 0
- finally:
- sys.stdin = before
- logins = [r for r in requests if r[0] == "POST"]
- events = [r[2] for r in requests if r[0] == "PUT"]
- assert len(logins) == 1 and len(events) == 3, requests
- for event in events:
- assert event["fmode.kind"] == "process"
- assert event["m.relates_to"]["event_id"] == "$root:local"
- assert "never-expose-this" not in event["body"]
- return {"realLoopbackHttp": True, "logins": 1, "events": 3, "threadBound": True}
- finally:
- server.shutdown()
- server.server_close()
- def upload_case(home):
- """Real hook + real local HTTP PUT/readback; only cloud API routing is substituted."""
- storage, controls, uploaded_bytes = {}, {"mismatch": False, "hub_ok": True}, []
- class StorageHandler(BaseHTTPRequestHandler):
- def log_message(self, *_):
- pass
- def do_PUT(self):
- data = self.rfile.read(int(self.headers["Content-Length"]))
- storage[self.path] = data
- uploaded_bytes.append(data)
- self.send_response(200)
- self.send_header("Content-Length", "0")
- self.end_headers()
- def do_GET(self):
- data = b"incorrect remote copy" if controls["mismatch"] else storage[self.path]
- self.send_response(200)
- self.send_header("Content-Length", str(len(data)))
- self.end_headers()
- self.wfile.write(data)
- class LocalPlatform:
- def __init__(self):
- self.pending = []
- def call(self, params):
- action = params["action"]
- if action == "list":
- return {"deliverables": []}
- if action == "report":
- return {"code": 200, "id": "local-deliverable"}
- if action == "enqueueArtifact":
- url = "https://s3.fmode.cn/local/" + params["filename"]
- self.pending.append({"id": "local-job", "deliverableId": params["deliverableId"],
- "source": params["source"], "filename": params["filename"],
- "uploadUrl": url, "publicUrl": url})
- return {"code": 200}
- if action == "pendingArtifacts":
- return {"jobs": self.pending}
- if action == "ackArtifact":
- return {"code": 200}
- raise AssertionError(action)
- def hub_call(params):
- if params["action"] == "listByUrl":
- return {"code": 200, "count": 0, "files": []}
- assert params["action"] == "registerFile", params
- return {"code": 200 if controls["hub_ok"] else 500, "id": "local-file"}
- server = ThreadingHTTPServer(("127.0.0.1", 0), StorageHandler)
- threading.Thread(target=server.serve_forever, daemon=True).start()
- original_open = urllib.request.urlopen
- def local_open(request, *args, **kwargs):
- if isinstance(request, str):
- url, data, headers, method = request, None, {}, "GET"
- else:
- url, data, headers, method = request.full_url, request.data, dict(request.headers), request.method
- assert url.startswith("https://s3.fmode.cn/"), url
- url = url.replace("https://s3.fmode.cn", f"http://127.0.0.1:{server.server_port}", 1)
- return original_open(urllib.request.Request(url, data=data, headers=headers, method=method), *args, **kwargs)
- try:
- patcher = load_file("ack_patcher", SKILL / "patch_deliverable_ack.py")
- source = patcher.patch_text((EVIDENCE / "data/scripts/fmode-deliverable-hook.py").read_text())
- scope = {"__name__": "runtime_acceptance"}
- exec(compile(source, "fmode-deliverable-hook.py", "exec"), scope)
- scope.update({"HOME": home, "CACHE_DIR": home / "cache/deliverable-hook",
- "LOG": home / "upload.log", "LEDGER": home / "upload-ledger.jsonl",
- "_resolve_agent_id": lambda: "agent-local-acceptance",
- "_thread_root": lambda *args: "$local-thread", "_hub_call": hub_call})
- scope["load_round"] = lambda sid: {"turn_id": sid}
- os.environ["HERMES_SESSION_CHAT_ID"] = "!local-room:local"
- cleaner = load_file("safe_cleaner", SKILL / "fmode-safe-gc.py")
- outcomes = {}
- for mode in ("success", "registration-failed", "readback-mismatch"):
- controls.update(mismatch=mode == "readback-mismatch", hub_ok=mode != "registration-failed")
- platform = LocalPlatform()
- scope["_load_pusher"] = lambda: platform
- os.environ["HERMES_SESSION_ID"] = mode
- path = home / "work/uploads" / (mode + ".txt")
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text("original upload bytes for " + mode, encoding="utf-8")
- scope["save_state"](mode, {"queued": [{"path": str(path)}], "pushed": []})
- with patch.object(urllib.request, "urlopen", local_open), contextlib.redirect_stdout(io.StringIO()):
- assert scope["handle_transform_llm_output"]({"session_id": mode, "response_text": "done"}) == 0
- state = scope["load_state"](mode)
- if mode == "readback-mismatch":
- assert not state["pushed"], state
- else:
- ack = state["pushed"][0]
- assert ack["sha256"] == hashlib.sha256(uploaded_bytes[-1]).hexdigest()
- assert ack["cloudAck"] is True
- assert ack["hubRegistered"] is (mode == "success"), ack
- assert path.exists(), "upload must keep source during its grace period"
- cleaner.cleanup(home, apply=True, now=time.time() + 7200, disk_percent=99)
- assert path.exists() is (mode != "success"), mode
- outcomes[mode] = "source-deleted-after-grace" if mode == "success" else "source-retained"
- return {"realHookUploadAndReadback": True, "localPlatformOnly": True, "outcomes": outcomes}
- finally:
- server.shutdown()
- server.server_close()
- CASES = {"directories": runtime_directories_case, "scheduler": scheduler_case, "skills": skills_case, "patches": patch_case,
- "notice": notice_case, "upload": upload_case}
- class InstalledHermesRuntimeTests(unittest.TestCase):
- def exercise(self, case):
- result = subprocess.run([sys.executable, "-B", __file__, "--case", case], cwd=ROOT,
- capture_output=True, text=True, timeout=100)
- self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
- print(result.stdout.strip(), flush=True)
- def test_actual_scheduler_tick_runs_safe_gc_once(self):
- self.exercise("scheduler")
- def test_provisioned_runtime_parents_allow_hook_state_and_session_mirrors(self):
- self.exercise("directories")
- def test_actual_skills_cli_and_agent_discover_both_categories(self):
- self.exercise("skills")
- def test_all_patches_accept_actual_server_template_sources(self):
- self.exercise("patches")
- def test_actual_notice_hook_uses_http_and_session_database(self):
- self.exercise("notice")
- def test_actual_upload_hook_acknowledgments_control_cleanup(self):
- self.exercise("upload")
- if __name__ == "__main__":
- if len(sys.argv) == 3 and sys.argv[1] == "--case":
- with tempfile.TemporaryDirectory(prefix="fmode-runtime-", dir="/opt/data") as temp:
- home = Path(temp)
- os.environ["HERMES_HOME"] = str(home)
- os.environ["HOME"] = str(home)
- print(json.dumps({"case": sys.argv[2], "result": CASES[sys.argv[2]](home)}), flush=True)
- else:
- unittest.main()
|