ckb/tests/unit/test_silent_reads.py
Michał Kopeć 51aaeadcdb Phase 1: honest failure, folded names, safer exports
- OKF export: a bare [[X]] becomes a bundle-root link when it resolves
  (path, file name or title; `&`, spaces and brackets percent-encoded)
  instead of degrading to plain text.
- N2 "degraded, not empty": retrieve reports DEGRADED for unread pages,
  graph or exact search ("no candidates among what could be read");
  lint reports Crux quotes and secret scans it could not do, and no
  longer skips an unreadable file as binary in the secrets scan.
  AGENTS.md rule; test_silent_reads guards new swallowed reads
  (`# ok-silent: <reason>` for the deliberate ones).
- N17: case- and accent-insensitive fold in retrieve's tldr and scope
  matching; lint check 20 flags page names that collide after folding.
- N7: one publish filter in both exporters drops HTML comments outside
  code (unclosed to the end of the page), `--drop-section NAME` leaves out
  sections, and a page whose frontmatter never closes is refused (exit 1).
- Test that an interrupted routine stays due until --mark.
- Docs: lint, retrieve and exporter skills, both manuals; goldens updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:52:39 +01:00

76 lines
3.5 KiB
Python

"""N2 "degraded, not empty": a script that could not read something must say
so. An `except` that swallows a read error and then passes, continues or
returns an empty value turns "could not check" into "nothing found".
Every such handler in a shipped script either reports the failure or carries
an `# ok-silent: <reason>` marker on its `except` line explaining who reports
it instead. A marker with no reason does not count (gbrain's guard does the
same).
"""
import re
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SWALLOW = re.compile(
r"^[ \t]*except\b(?P<exc>[^:\n]*):(?P<tail>[^\n]*)\n[ \t]*"
r"(?:pass|continue|return(?:[ \t]+(?:\[\]|\{\}|set\(\)|None|\"\"|''|0|False))?)[ \t]*(?:#[^\n]*)?$",
re.M)
READ_ERRORS = re.compile(r"OSError|IOError|Exception|JSONDecodeError|DatabaseError|"
r"SubprocessError|TimeoutExpired|URLError|^\s*$")
MARKER = re.compile(r"#\s*ok-silent:\s*\S.{5,}")
def offenders():
found = []
for f in sorted((ROOT / ".agents").rglob("*.py")):
text = f.read_text(encoding="utf-8")
for m in SWALLOW.finditer(text):
if not READ_ERRORS.search(m.group("exc")):
continue
if MARKER.search(m.group("tail")):
continue
line = text.count("\n", 0, m.start()) + 1
found.append(f"{f.relative_to(ROOT).as_posix()}:{line}")
return found
class SilentReads(unittest.TestCase):
def test_no_unexplained_swallowed_reads(self):
self.assertEqual(offenders(), [], "report the failure (DEGRADED/finding) or add "
"`# ok-silent: <who reports it instead>` on the except line")
def test_the_guard_catches_a_bare_swallow(self):
sample = "try:\n x = p.read_text()\nexcept OSError:\n continue\n"
self.assertTrue(SWALLOW.search(sample))
marked = "try:\n x = p.read_text()\nexcept OSError: # ok-silent:\n continue\n"
m = SWALLOW.search(marked)
self.assertFalse(MARKER.search(m.group("tail")), "an empty reason must not count")
class RetrieveSaysDegraded(unittest.TestCase):
def test_unreadable_graph_is_reported_not_empty(self):
import json, shutil, subprocess, sys, tempfile
fix = ROOT / "tests/fixtures/minimal-kb"
script = ROOT / ".agents/skills/ckb-retrieve/scripts/retrieve_candidates.py"
with tempfile.TemporaryDirectory() as tmp:
kb = Path(tmp) / "kb"
shutil.copytree(str(fix), str(kb))
(kb / "wiki/graph").mkdir(parents=True, exist_ok=True)
(kb / "wiki/graph/edges.json").write_text("{ not json", encoding="utf-8")
r = subprocess.run([sys.executable, str(script), "atlas retry policy", "--root", str(kb),
"--json", "--no-bm25", "--today", "2026-11-23"],
capture_output=True, text=True, encoding="utf-8")
self.assertEqual(r.returncode, 0, r.stderr)
out = json.loads(r.stdout)
self.assertTrue(any("graph not read" in d for d in out["degraded"]), out["degraded"])
text = subprocess.run([sys.executable, str(script), "zzzz qqqq", "--root", str(kb),
"--no-bm25", "--today", "2026-11-23"],
capture_output=True, text=True, encoding="utf-8").stdout
self.assertIn("DEGRADED: graph not read", text)
self.assertIn("not the same as no match", text)
if __name__ == "__main__":
unittest.main()