"""Small compiler guard examples. Run with Python 3.10+; no vault access required."""
from pathlib import Path


def verify_evidence(evidence, source):
    # The production caller validates the proposal's JSON schema first.
    if not evidence or any(
        not item["quote"].strip() or item["quote"] not in source
        for item in evidence
    ):
        raise ValueError("Missing or non-verbatim source evidence")


def safe_path(base, relative):
    rel = Path(relative)
    if rel.is_absolute() or not rel.parts or any(
        part in ("..", ".") or part.startswith(".") for part in rel.parts
    ):
        raise ValueError(f"Unsafe path: {relative}")
    base = base.resolve()
    target = base / rel
    if target.resolve() != target or not target.resolve().is_relative_to(base):
        raise ValueError(f"Symlink or escaping path: {relative}")
    return target


def recovery_action(current, before, after):
    """Decision extracted from journal replay; this function writes nothing."""
    if current == after:
        return "skip"
    if current != before:
        raise RuntimeError("Concurrent edit; preserve the recovery journal")
    return "write"


if __name__ == "__main__":
    import tempfile
    import unittest

    class GuardTests(unittest.TestCase):
        def test_verbatim_evidence_required(self):
            source = "user: Keep deployment in the owning pipeline."
            verify_evidence([{"quote": "Keep deployment in the owning pipeline."}], source)
            for evidence in ([], [{"quote": ""}], [{"quote": "Deploy from the agent."}]):
                with self.assertRaises(ValueError):
                    verify_evidence(evidence, source)

        def test_paths_cannot_escape_or_follow_symlinks(self):
            with tempfile.TemporaryDirectory() as directory:
                base = Path(directory)
                self.assertEqual(safe_path(base, "concepts/gitops.md"), base.resolve() / "concepts/gitops.md")
                for path in ("/etc/passwd", "../outside.md", ".obsidian/settings.json"):
                    with self.assertRaises(ValueError):
                        safe_path(base, path)
                (base / "alias").symlink_to(base, target_is_directory=True)
                with self.assertRaises(ValueError):
                    safe_path(base, "alias/note.md")

        def test_replay_preserves_concurrent_edit(self):
            self.assertEqual(recovery_action("old", "old", "new"), "write")
            self.assertEqual(recovery_action("new", "old", "new"), "skip")
            with self.assertRaises(RuntimeError):
                recovery_action("human edit", "old", "new")

    unittest.main()
