test_container_baseline_runtime.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. """Exercise the installed Hermes runtime in a network-isolated local Docker container.
  2. Run through scripts/verify-container-runtime.mjs; /evidence contains read-only source
  3. copies from the server template, never environment files or production state.
  4. """
  5. from __future__ import annotations
  6. import hashlib
  7. import contextlib
  8. import importlib.util
  9. import io
  10. import json
  11. import os
  12. from pathlib import Path
  13. import shutil
  14. import sqlite3
  15. import subprocess
  16. import sys
  17. import tempfile
  18. import threading
  19. import time
  20. import unittest
  21. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  22. from unittest.mock import patch
  23. import urllib.request
  24. ROOT = Path(__file__).resolve().parents[2]
  25. SKILL = ROOT / "cloud/skills/container-provision-job"
  26. EVIDENCE = Path(os.environ.get("FMODE_RUNTIME_EVIDENCE", "/evidence"))
  27. def load_file(name, path):
  28. spec = importlib.util.spec_from_file_location(name, path)
  29. module = importlib.util.module_from_spec(spec)
  30. spec.loader.exec_module(module)
  31. return module
  32. def old_file(path, content, old):
  33. path.parent.mkdir(parents=True, exist_ok=True)
  34. path.write_text(content, encoding="utf-8")
  35. os.utime(path, (old, old))
  36. return path
  37. def runtime_directories_case(home):
  38. fixture = Path(os.environ['FMODE_PROVISIONED_FIXTURE'])
  39. assert os.getuid() == 10000, 'Permission checks must run as the real Hermes user'
  40. for relative in ('cache', 'sessions', 'work'):
  41. parent = fixture / relative
  42. assert os.access(parent, os.W_OK), f'Provisioned runtime parent is not writable: {parent}'
  43. with tempfile.TemporaryDirectory(prefix='.runtime-write-', dir=parent) as temp:
  44. target = Path(temp) / 'state.json'
  45. target.write_text('{"checked":true}', encoding='utf-8')
  46. target.replace(Path(temp) / 'committed.json')
  47. return {'runtimeUid': os.getuid(), 'writableParents': ['cache', 'sessions', 'work']}
  48. def scheduler_case(home):
  49. contract = load_file("gc_contract", ROOT / "cloud/scripts/test_fmode_safe_gc_scheduler.py")
  50. scripts = home / "scripts"
  51. scripts.mkdir()
  52. for name in ("fmode-safe-gc.py", "fmode-safe-gc-run.py"):
  53. shutil.copy2(SKILL / name, scripts / name)
  54. cron = home / "cron"
  55. cron.mkdir()
  56. (cron / "jobs.json").write_text(json.dumps({"jobs": [
  57. {"id": "other-job", "name": "preserve-me", "enabled": False,
  58. "script": "never-run.py", "no_agent": True, "state": "paused"},
  59. {"id": "old-media-gc", "name": "media-gc-delayed-cleanup", "enabled": True,
  60. "script": "fmode-media-gc-wrapper.sh", "no_agent": True, "state": "scheduled"},
  61. ]}), encoding="utf-8")
  62. installed = contract.run_installer(home)
  63. assert installed.returncode == 0, installed.stderr
  64. again = contract.run_installer(home)
  65. assert again.returncode == 0, again.stderr
  66. now, old = time.time(), time.time() - 7200
  67. uploaded = old_file(home / "work/uploads/ack.txt", "verified upload", old)
  68. pending = old_file(home / "work/uploads/pending.txt", "unregistered upload", old)
  69. active = old_file(home / "work/tasks/active/output.txt", "still used", old)
  70. (active.parent / ".fmode-task.json").write_text(json.dumps({
  71. "status": "running", "activeSessionIds": ["active-session"],
  72. "lastActivityAt": int(old * 1000), "files": [],
  73. }), encoding="utf-8")
  74. cache = old_file(home / "cache/regenerable/index.tmp", "regenerable", old)
  75. state = home / "cache/deliverable-hook/session.json"
  76. state.parent.mkdir(parents=True, exist_ok=True)
  77. record = lambda p: {"path": str(p), "url": "https://s3.fmode.cn/fixture.txt",
  78. "uploadedAt": int(old * 1000), "cloudAck": True,
  79. "hubRegistered": True, "sha256": hashlib.sha256(p.read_bytes()).hexdigest()}
  80. state.write_text(json.dumps({"pushed": [record(uploaded), record(active)]}), encoding="utf-8")
  81. protected = old_file(home / "skills/custom/keep.txt", "protected skill", old)
  82. from cron import jobs, scheduler
  83. due = jobs.get_due_jobs()
  84. target = [j for j in due if j.get("name") == "fmode-safe-gc"]
  85. assert len(target) == 1, due
  86. job_id = target[0]["id"]
  87. assert scheduler.tick(verbose=False) == 1
  88. deadline = time.monotonic() + 45
  89. job = jobs.get_job(job_id)
  90. while time.monotonic() < deadline and not job.get("last_run_at"):
  91. time.sleep(0.1)
  92. job = jobs.get_job(job_id)
  93. assert job.get("last_status") == "ok", job
  94. assert not uploaded.exists(), "actual scheduler subprocess did not run the cleaner"
  95. assert not cache.exists()
  96. assert pending.exists() and active.exists() and protected.exists()
  97. assert state.exists() and json.loads(state.read_text())["pushed"][0]["gc"] is True
  98. assert job["repeat"]["completed"] == 1, job
  99. assert job["state"] == "scheduled" and not job.get("last_error"), job
  100. from datetime import datetime
  101. next_at = datetime.fromisoformat(job["next_run_at"]).timestamp()
  102. assert 1700 < next_at - now < 1900, job
  103. assert jobs.get_job("old-media-gc")["enabled"] is False
  104. assert jobs.get_job("other-job")["script"] == "never-run.py"
  105. assert scheduler.tick(verbose=False) == 0, "an immediate second tick must not run it twice"
  106. return {"actualTick": True, "lastStatus": job["last_status"], "runs": 1,
  107. "legacyCleanerPaused": True, "protectedFilesRetained": True}
  108. def skills_case(home):
  109. names = []
  110. for category in ("platform", "custom"):
  111. name = "baseline-" + category + "-check"
  112. path = home / "skills" / category / name / "SKILL.md"
  113. path.parent.mkdir(parents=True)
  114. path.write_text(f"---\nname: {name}\ndescription: Local runtime acceptance fixture.\n---\n\n"
  115. f"# {name}\n\nRead acceptance instructions for {category}.\n", encoding="utf-8")
  116. names.append(name)
  117. from tools.skills_tool import skills_list, skill_view
  118. listed = json.loads(skills_list())
  119. assert listed["success"], listed
  120. found = {skill["name"] for skill in listed["skills"]}
  121. assert set(names).issubset(found), listed
  122. for name in names:
  123. viewed = json.loads(skill_view(name, preprocess=False))
  124. assert viewed["success"] and "Read acceptance instructions" in json.dumps(viewed), viewed
  125. cli = subprocess.run(["/opt/hermes/.venv/bin/hermes", "skills", "list", "--source", "local",
  126. "--enabled-only"], text=True, capture_output=True, timeout=45)
  127. assert cli.returncode == 0, cli.stderr
  128. assert all(name in cli.stdout for name in names), cli.stdout
  129. return {"cliDiscoversBoth": True, "agentCanReadBoth": True, "skills": names}
  130. def patch_case(home):
  131. checks = {}
  132. # A shared image tag is insufficient: compare the installed runtime files
  133. # with copies read from the running server container.
  134. matched = []
  135. for relative in ("cron/scheduler.py", "cron/scheduler_script.py", "cron/scheduler_tick.py",
  136. "cron/jobs.py", "tools/skills_tool.py", "agent/skill_utils.py"):
  137. installed = Path("/opt/hermes") / relative
  138. expected = EVIDENCE / relative
  139. # Windows evidence copies can use CRLF; compare the exact Python source
  140. # after the same universal-newline decoding used by Python's loader.
  141. assert hashlib.sha256(installed.read_text(encoding="utf-8").encode()).digest() == hashlib.sha256(
  142. expected.read_text(encoding="utf-8").encode()).digest(), relative
  143. matched.append(relative)
  144. checks["serverRuntimeSourceMatch"] = matched
  145. for patcher, relative in [
  146. ("patch_app_reporter", "template/plugins/plugin-active-reporter/__init__.py"),
  147. ("patch_process_notice", "template/scripts/fmode-process-notice.py"),
  148. ("patch_deliverable_ack", "data/scripts/fmode-deliverable-hook.py"),
  149. ]:
  150. module = load_file(patcher, SKILL / (patcher + ".py"))
  151. original = (EVIDENCE / relative).read_text(encoding="utf-8")
  152. updated = module.patch_text(original)
  153. assert module.patch_text(updated) == updated
  154. compile(updated, relative, "exec")
  155. checks[patcher] = {"sourceSha256": hashlib.sha256(original.encode()).hexdigest(),
  156. "patchValidAndIdempotent": True}
  157. if patcher == "patch_app_reporter":
  158. scope = {"__name__": "runtime_acceptance"}
  159. exec(compile(updated, relative, "exec"), scope)
  160. (home / "gateway_state.json").write_text(json.dumps({
  161. "platforms": {"matrix": {"state": "connected"}},
  162. }), encoding="utf-8")
  163. sent = []
  164. scope["_balance_value"] = lambda: ("", None)
  165. scope["_push_with_sessions"] = lambda fields: sent.append(fields) or True
  166. assert scope["_heartbeat_once"](0)
  167. assert set(sent[0]) == {"heartbeatAt", "channels"}, sent
  168. assert json.loads(sent[0]["channels"])["matrix"] is True
  169. scope["_session_mark_running"]("session-a", "acceptance task")
  170. scope["_session_key_for"] = lambda sid: "$" + sid
  171. scope["_user_id_of"] = lambda sid: "@fixture:local"
  172. rows = scope["_sessions_snapshot"]()
  173. assert rows[0]["task"] == "acceptance task" and rows[0]["status"] == "running"
  174. scope["_session_mark_idle"]("session-a")
  175. assert scope["_sessions_snapshot"]()[0]["status"] == "idle"
  176. checks[patcher]["realHeartbeatAndSessionTransitions"] = True
  177. return checks
  178. def notice_case(home):
  179. requests = []
  180. class Handler(BaseHTTPRequestHandler):
  181. def log_message(self, *_):
  182. pass
  183. def respond(self):
  184. data = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
  185. requests.append((self.command, self.path, data))
  186. answer = {"access_token": "local-test-token"} if self.path.endswith("/login") else {
  187. "event_id": "$local-" + str(len(requests))}
  188. body = json.dumps(answer).encode()
  189. self.send_response(200)
  190. self.send_header("Content-Type", "application/json")
  191. self.send_header("Content-Length", str(len(body)))
  192. self.end_headers()
  193. self.wfile.write(body)
  194. do_POST = respond
  195. do_PUT = respond
  196. server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
  197. threading.Thread(target=server.serve_forever, daemon=True).start()
  198. try:
  199. db = sqlite3.connect(home / "state.db")
  200. db.execute("CREATE TABLE sessions (id TEXT, chat_id TEXT, thread_id TEXT)")
  201. db.execute("INSERT INTO sessions VALUES (?, ?, ?)", ("session-a", "!room:local", "$root:local"))
  202. db.commit()
  203. db.close()
  204. patcher = load_file("notice_patcher", SKILL / "patch_process_notice.py")
  205. updated = patcher.patch_text((EVIDENCE / "template/scripts/fmode-process-notice.py").read_text())
  206. scope = {"__name__": "runtime_acceptance"}
  207. exec(compile(updated, "fmode-process-notice.py", "exec"), scope)
  208. scope.update({"HOME": home, "STATE_DB": home / "state.db", "ENV_FILE": home / ".env",
  209. "LOG": home / "notice.log", "THROTTLE_DIR": home / "cache/process-notice",
  210. "AUTH_CACHE_ROOT": home / "auth-cache"})
  211. (home / ".env").write_text(
  212. f"MATRIX_HOMESERVER=http://127.0.0.1:{server.server_port}\n"
  213. "MATRIX_USER_ID=@fixture:local\nMATRIX_PASSWORD=local-test-password\n"
  214. f"HERMES_HOME={home}\n", encoding="utf-8")
  215. before = sys.stdin
  216. try:
  217. for number in range(3):
  218. sys.stdin = io.StringIO(json.dumps({"session_id": "session-a", "tool_name": "terminal",
  219. "tool_input": {"command": f"echo step-{number}; TOKEN=never-expose-this"}}))
  220. assert scope["main"](["notice.py"]) == 0
  221. finally:
  222. sys.stdin = before
  223. logins = [r for r in requests if r[0] == "POST"]
  224. events = [r[2] for r in requests if r[0] == "PUT"]
  225. assert len(logins) == 1 and len(events) == 3, requests
  226. for event in events:
  227. assert event["fmode.kind"] == "process"
  228. assert event["m.relates_to"]["event_id"] == "$root:local"
  229. assert "never-expose-this" not in event["body"]
  230. return {"realLoopbackHttp": True, "logins": 1, "events": 3, "threadBound": True}
  231. finally:
  232. server.shutdown()
  233. server.server_close()
  234. def upload_case(home):
  235. """Real hook + real local HTTP PUT/readback; only cloud API routing is substituted."""
  236. storage, controls, uploaded_bytes = {}, {"mismatch": False, "hub_ok": True}, []
  237. class StorageHandler(BaseHTTPRequestHandler):
  238. def log_message(self, *_):
  239. pass
  240. def do_PUT(self):
  241. data = self.rfile.read(int(self.headers["Content-Length"]))
  242. storage[self.path] = data
  243. uploaded_bytes.append(data)
  244. self.send_response(200)
  245. self.send_header("Content-Length", "0")
  246. self.end_headers()
  247. def do_GET(self):
  248. data = b"incorrect remote copy" if controls["mismatch"] else storage[self.path]
  249. self.send_response(200)
  250. self.send_header("Content-Length", str(len(data)))
  251. self.end_headers()
  252. self.wfile.write(data)
  253. class LocalPlatform:
  254. def __init__(self):
  255. self.pending = []
  256. def call(self, params):
  257. action = params["action"]
  258. if action == "list":
  259. return {"deliverables": []}
  260. if action == "report":
  261. return {"code": 200, "id": "local-deliverable"}
  262. if action == "enqueueArtifact":
  263. url = "https://s3.fmode.cn/local/" + params["filename"]
  264. self.pending.append({"id": "local-job", "deliverableId": params["deliverableId"],
  265. "source": params["source"], "filename": params["filename"],
  266. "uploadUrl": url, "publicUrl": url})
  267. return {"code": 200}
  268. if action == "pendingArtifacts":
  269. return {"jobs": self.pending}
  270. if action == "ackArtifact":
  271. return {"code": 200}
  272. raise AssertionError(action)
  273. def hub_call(params):
  274. if params["action"] == "listByUrl":
  275. return {"code": 200, "count": 0, "files": []}
  276. assert params["action"] == "registerFile", params
  277. return {"code": 200 if controls["hub_ok"] else 500, "id": "local-file"}
  278. server = ThreadingHTTPServer(("127.0.0.1", 0), StorageHandler)
  279. threading.Thread(target=server.serve_forever, daemon=True).start()
  280. original_open = urllib.request.urlopen
  281. def local_open(request, *args, **kwargs):
  282. if isinstance(request, str):
  283. url, data, headers, method = request, None, {}, "GET"
  284. else:
  285. url, data, headers, method = request.full_url, request.data, dict(request.headers), request.method
  286. assert url.startswith("https://s3.fmode.cn/"), url
  287. url = url.replace("https://s3.fmode.cn", f"http://127.0.0.1:{server.server_port}", 1)
  288. return original_open(urllib.request.Request(url, data=data, headers=headers, method=method), *args, **kwargs)
  289. try:
  290. patcher = load_file("ack_patcher", SKILL / "patch_deliverable_ack.py")
  291. source = patcher.patch_text((EVIDENCE / "data/scripts/fmode-deliverable-hook.py").read_text())
  292. scope = {"__name__": "runtime_acceptance"}
  293. exec(compile(source, "fmode-deliverable-hook.py", "exec"), scope)
  294. scope.update({"HOME": home, "CACHE_DIR": home / "cache/deliverable-hook",
  295. "LOG": home / "upload.log", "LEDGER": home / "upload-ledger.jsonl",
  296. "_resolve_agent_id": lambda: "agent-local-acceptance",
  297. "_thread_root": lambda *args: "$local-thread", "_hub_call": hub_call})
  298. scope["load_round"] = lambda sid: {"turn_id": sid}
  299. os.environ["HERMES_SESSION_CHAT_ID"] = "!local-room:local"
  300. cleaner = load_file("safe_cleaner", SKILL / "fmode-safe-gc.py")
  301. outcomes = {}
  302. for mode in ("success", "registration-failed", "readback-mismatch"):
  303. controls.update(mismatch=mode == "readback-mismatch", hub_ok=mode != "registration-failed")
  304. platform = LocalPlatform()
  305. scope["_load_pusher"] = lambda: platform
  306. os.environ["HERMES_SESSION_ID"] = mode
  307. path = home / "work/uploads" / (mode + ".txt")
  308. path.parent.mkdir(parents=True, exist_ok=True)
  309. path.write_text("original upload bytes for " + mode, encoding="utf-8")
  310. scope["save_state"](mode, {"queued": [{"path": str(path)}], "pushed": []})
  311. with patch.object(urllib.request, "urlopen", local_open), contextlib.redirect_stdout(io.StringIO()):
  312. assert scope["handle_transform_llm_output"]({"session_id": mode, "response_text": "done"}) == 0
  313. state = scope["load_state"](mode)
  314. if mode == "readback-mismatch":
  315. assert not state["pushed"], state
  316. else:
  317. ack = state["pushed"][0]
  318. assert ack["sha256"] == hashlib.sha256(uploaded_bytes[-1]).hexdigest()
  319. assert ack["cloudAck"] is True
  320. assert ack["hubRegistered"] is (mode == "success"), ack
  321. assert path.exists(), "upload must keep source during its grace period"
  322. cleaner.cleanup(home, apply=True, now=time.time() + 7200, disk_percent=99)
  323. assert path.exists() is (mode != "success"), mode
  324. outcomes[mode] = "source-deleted-after-grace" if mode == "success" else "source-retained"
  325. return {"realHookUploadAndReadback": True, "localPlatformOnly": True, "outcomes": outcomes}
  326. finally:
  327. server.shutdown()
  328. server.server_close()
  329. CASES = {"directories": runtime_directories_case, "scheduler": scheduler_case, "skills": skills_case, "patches": patch_case,
  330. "notice": notice_case, "upload": upload_case}
  331. class InstalledHermesRuntimeTests(unittest.TestCase):
  332. def exercise(self, case):
  333. result = subprocess.run([sys.executable, "-B", __file__, "--case", case], cwd=ROOT,
  334. capture_output=True, text=True, timeout=100)
  335. self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
  336. print(result.stdout.strip(), flush=True)
  337. def test_actual_scheduler_tick_runs_safe_gc_once(self):
  338. self.exercise("scheduler")
  339. def test_provisioned_runtime_parents_allow_hook_state_and_session_mirrors(self):
  340. self.exercise("directories")
  341. def test_actual_skills_cli_and_agent_discover_both_categories(self):
  342. self.exercise("skills")
  343. def test_all_patches_accept_actual_server_template_sources(self):
  344. self.exercise("patches")
  345. def test_actual_notice_hook_uses_http_and_session_database(self):
  346. self.exercise("notice")
  347. def test_actual_upload_hook_acknowledgments_control_cleanup(self):
  348. self.exercise("upload")
  349. if __name__ == "__main__":
  350. if len(sys.argv) == 3 and sys.argv[1] == "--case":
  351. with tempfile.TemporaryDirectory(prefix="fmode-runtime-", dir="/opt/data") as temp:
  352. home = Path(temp)
  353. os.environ["HERMES_HOME"] = str(home)
  354. os.environ["HOME"] = str(home)
  355. print(json.dumps({"case": sys.argv[2], "result": CASES[sys.argv[2]](home)}), flush=True)
  356. else:
  357. unittest.main()