"""The guard after a repair (okfwiki.kguard): order 35 A2b, the operator 22.10.2026 ("Lag vakten som egen kommando (Anbefalt)", PLAN.md ยง Rammer point 10). It asks the model again for the pages without a home and the sources without a main page that the frozen auditor reports, with the frozen guard of kpack and klink, and applies the answer as kpack.apply_guard does, logged in its own folder instead of packs.json. Synthetic fixtures only (the repair gate's bee sources); no text from any documentation. """ from __future__ import annotations import io import json import sys import tempfile import unittest from contextlib import redirect_stderr, redirect_stdout from pathlib import Path from typing import Any from unittest import mock ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "gates")) import repair_gate as gate # noqa: E402 from okfwiki import kassemble, kguard, kpack, krepair # noqa: E402 MANIFEST = ROOT / "gates" / "repair.manifest.json" CASES = ROOT / "gates" / "repair" AT = "2026-01-02T00:00:00Z" ANSWER = {"homes": [{"page": "frames", "home": "hive"}], "main_pages": [{"source": "kilde/docs-en-honey.md", "page": "honey-harvest"}]} def run(argv: list[str]) -> tuple[int, str]: out = io.StringIO() with redirect_stdout(out), redirect_stderr(out): code = kguard.main(argv) return code, out.getvalue() class Base(unittest.TestCase): """The repair gate's base, built once; every test works in fresh copies of it.""" base: gate.Base _class_tmp: tempfile.TemporaryDirectory[str] @classmethod def setUpClass(cls) -> None: cls._class_tmp = tempfile.TemporaryDirectory(prefix="kguard-test-") manifest = gate.load_manifest(MANIFEST) gate.verify_fixtures(manifest, CASES) cls.base = gate.build_base(manifest, CASES, Path(cls._class_tmp.name)) @classmethod def tearDownClass(cls) -> None: cls._class_tmp.cleanup() def setUp(self) -> None: self._tmp = tempfile.TemporaryDirectory(prefix="kguard-case-") self.tmp = Path(self._tmp.name) def tearDown(self) -> None: self._tmp.cleanup() def copy(self, name: str, homeless: bool = True) -> gate.Copy: """A fresh copy; with `homeless`, frames has lost its home and docs-en-honey.md its main page, and the collection is built again, so the auditor reports two pages without a home and one source without a main page.""" c = gate.fresh_copy(self.base, self.tmp, name) if homeless: path = c.path("work") / "K-work" / "accepted.json" acc = json.loads(path.read_text(encoding="utf-8")) acc["homes"] = [h for h in acc["homes"] if h["concept_id"] != "frames"] acc["main_pages"] = [m for m in acc["main_pages"] if m["concept_id"] != "honey-harvest"] path.write_text(kpack.dump(acc), encoding="utf-8") code, said = gate.quiet(kassemble.main, ["build", "--work", c.places["work"], "--sources", c.places["sources"], "--out", c.places["wiki"], "--links", c.places["links"], "--replace", "--at", AT]) self.assertEqual(0, code, said) return c def ask(self, c: gate.Copy, out: Path | None = None) -> tuple[int, str]: return run(["ask", "--work", c.places["work"], "--bundle", c.places["wiki"], "--sources", c.places["sources"], "--out", str(out or c.path("out") / "guard")]) def apply(self, c: gate.Copy, answer: dict[str, Any], out: Path | None = None) -> tuple[int, str]: folder = out or c.path("out") / "guard" folder.mkdir(parents=True, exist_ok=True) path = folder / "answer.json" path.write_text(json.dumps(answer), encoding="utf-8") return run(["apply", "--work", c.places["work"], "--asked", str(folder / "asked.json"), "--answer", str(path), "--bundle", c.places["wiki"]]) def asked(self, c: gate.Copy) -> dict[str, Any]: doc: dict[str, Any] = json.loads((c.path("out") / "guard" / "asked.json").read_text(encoding="utf-8")) return doc def accepted(self, c: gate.Copy) -> dict[str, Any]: doc: dict[str, Any] = json.loads((c.path("work") / "K-work" / "accepted.json").read_text(encoding="utf-8")) return doc class AskTest(Base): def test_no_task_when_the_auditor_reports_nothing(self) -> None: c = self.copy("plain", homeless=False) code, said = self.ask(c) self.assertEqual(0, code, said) self.assertFalse((c.path("out") / "guard").exists()) self.assertIn("no task", said) def test_the_task_asks_for_the_pages_and_sources_the_auditor_reports(self) -> None: c = self.copy("homeless") before = c.trees("work", "wiki") code, said = self.ask(c) self.assertEqual(kguard.EXIT_GUARD, code, said) self.assertEqual(before, c.trees("work", "wiki")) # ask writes only in --out asked = self.asked(c) self.assertEqual("okf-wiki/guard-asked/1", asked["schema"]) self.assertEqual(["frames.md", "honey-harvest.md"], asked["pages"]) self.assertEqual(["kilde/docs-en-honey.md"], asked["sources"]) self.assertEqual(["hive", "swarming"], sorted(asked["catalogue"])) self.assertEqual(2, asked["pack"]) # the last pack of packs.json self.assertEqual(krepair.tree_sha256(c.path("wiki")), asked["bundle_sha256"]) parts = [Path(p) for p in asked["parts"]] self.assertTrue(parts and all(p.is_file() for p in parts)) text = "".join(p.read_text(encoding="utf-8") for p in parts) self.assertIn("frames", text) self.assertIn("kilde/docs-en-honey.md", text) self.assertFalse(Path(asked["answer"]).exists()) def test_ask_never_writes_over_what_exists(self) -> None: c = self.copy("homeless") out = c.path("out") / "guard" out.mkdir() (out / "asked.json").write_text("{}", encoding="utf-8") code, said = self.ask(c) self.assertEqual(2, code, said) self.assertEqual("{}", (out / "asked.json").read_text(encoding="utf-8")) self.assertEqual(["asked.json"], sorted(p.name for p in out.iterdir())) def test_a_finding_the_guard_cannot_mend_stops_and_writes_nothing(self) -> None: c = self.copy("homeless") found = {"findings": [{"check": "citations", "file": "frames.md", "message": "a planted finding"}]} with mock.patch.object(kpack, "run_audit", return_value=found): code, said = self.ask(c) self.assertEqual(kguard.EXIT_BREACH, code, said) self.assertIn("citations", said) self.assertFalse((c.path("out") / "guard").exists()) def test_a_page_the_operator_approved_without_a_home_is_not_asked(self) -> None: c = self.copy("homeless") (c.path("work") / kpack.HOMELESS_APPROVED).write_text(json.dumps({ "schema": kpack.HOMELESS_SCHEMA, "pages": [{"page": "frames.md", "pack": 1, "date": "2026-01-02", "operator": "a planted approval"}]}), encoding="utf-8") code, said = self.ask(c) self.assertEqual(kguard.EXIT_GUARD, code, said) self.assertEqual(["honey-harvest.md"], self.asked(c)["pages"]) def test_a_source_the_operator_approved_without_a_main_page_is_not_asked(self) -> None: c = self.copy("homeless") (c.path("work") / kpack.HOMELESS_APPROVED).write_text(json.dumps({ "schema": kpack.HOMELESS_SCHEMA, "sources": [{"source": "kilde/docs-en-honey.md", "pack": 1, "date": "2026-01-02", "operator": "a planted approval"}]}), encoding="utf-8") code, said = self.ask(c) self.assertEqual(kguard.EXIT_GUARD, code, said) self.assertEqual([], self.asked(c)["sources"]) self.assertEqual(["frames.md", "honey-harvest.md"], self.asked(c)["pages"]) def test_with_every_finding_on_the_operator_s_list_there_is_no_task(self) -> None: c = self.copy("homeless") entry = {"pack": 1, "date": "2026-01-02", "operator": "a planted approval"} (c.path("work") / kpack.HOMELESS_APPROVED).write_text(json.dumps({ "schema": kpack.HOMELESS_SCHEMA, "pages": [{**entry, "page": p} for p in ("frames.md", "honey-harvest.md")], "sources": [{**entry, "source": "/kilde/docs-en-honey.md"}]}), encoding="utf-8") code, said = self.ask(c) self.assertEqual(0, code, said) self.assertFalse((c.path("out") / "guard").exists()) class ApplyTest(Base): def test_apply_gives_the_accepted_json_kpack_apply_guard_gives(self) -> None: mine, theirs = self.copy("mine"), self.copy("theirs") code, said = self.ask(mine) self.assertEqual(kguard.EXIT_GUARD, code, said) packs_before = (mine.path("work") / "K-work" / "packs.json").read_bytes() code, said = self.apply(mine, ANSWER) self.assertEqual(0, code, said) asked = self.asked(mine) work = theirs.path("work") log = kpack.pack_log(work) guard = {"asked": {k: asked[k] for k in ("pages", "sources", "catalogue")}, "parts": len(asked["parts"])} kpack.record(log, asked["pack"])["guard"] = guard answer = work / "K-guard" / f"p{asked['pack']}" / "answer.json" answer.parent.mkdir(parents=True) answer.write_text(json.dumps(ANSWER), encoding="utf-8") with redirect_stdout(io.StringIO()): kpack.apply_guard(work, theirs.path("wiki"), asked["pack"], guard, log) self.assertEqual(self.accepted(theirs), self.accepted(mine)) self.assertIn({"source": "docs-en-hive.md", "concept_id": "frames", "home": "hive", "pack": 2, "by": "guard"}, self.accepted(mine)["homes"]) self.assertEqual(packs_before, (mine.path("work") / "K-work" / "packs.json").read_bytes()) logged = json.loads((mine.path("work") / "K-guard" / "r35-1" / "guard.json").read_text(encoding="utf-8")) self.assertEqual({"homes": 1, "main_pages": 1, "none": [], "unanswered": [], "rejected": {}}, logged["answered"]) def test_a_home_outside_the_catalogue_is_rejected_as_read_guard_rejects_it(self) -> None: c = self.copy("outside") self.ask(c) homes_before = self.accepted(c)["homes"] code, said = self.apply(c, {"homes": [{"page": "frames", "home": "brood"}]}) self.assertEqual(0, code, said) self.assertEqual(homes_before, self.accepted(c)["homes"]) logged = json.loads((c.path("work") / "K-guard" / "r35-1" / "guard.json").read_text(encoding="utf-8")) self.assertEqual({"home-not-in-catalogue": 1}, logged["answered"]["rejected"]) self.assertEqual(["frames", "honey-harvest"], sorted(logged["answered"]["unanswered"])) self.assertIn("rejected 1", said) def test_a_task_applied_once_is_refused_the_second_time(self) -> None: c = self.copy("twice") self.ask(c) self.assertEqual(0, self.apply(c, ANSWER)[0]) before = c.trees("work") code, said = self.apply(c, ANSWER) self.assertEqual(1, code, said) self.assertRegex(said, r"(?m)^refused: applied ") self.assertEqual(before, c.trees("work")) def test_an_answer_against_another_collection_than_the_one_asked_is_refused(self) -> None: c = self.copy("stale") self.ask(c) page = c.path("wiki") / "smoker.md" page.write_text(page.read_text(encoding="utf-8") + "\n", encoding="utf-8") before = c.trees("work") code, said = self.apply(c, ANSWER) self.assertEqual(1, code, said) self.assertRegex(said, r"(?m)^refused: stale-bundle ") self.assertEqual(before, c.trees("work")) def test_an_answer_after_accepted_json_changed_since_ask_is_refused(self) -> None: c = self.copy("moved") self.assertEqual(kguard.EXIT_GUARD, self.ask(c)[0]) self.assertEqual(krepair.file_sha256(c.path("work") / "K-work" / "accepted.json"), self.asked(c)["accepted_sha256"]) path = c.path("work") / "K-work" / "accepted.json" # a repair between ask and apply, the bundle not rebuilt acc = json.loads(path.read_text(encoding="utf-8")) acc["fragments"] = [r for r in acc["fragments"] if r["concept_id"] != "frames"] path.write_text(kpack.dump(acc), encoding="utf-8") before = c.trees("work") code, said = self.apply(c, ANSWER) self.assertEqual(1, code, said) self.assertRegex(said, r"(?m)^refused: stale-accepted ") self.assertEqual(before, c.trees("work")) if __name__ == "__main__": unittest.main()