From 51aaeadcdbb3c24ee1e8a229bb20eb06fd7de70f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Kope=C4=87?= Date: Mon, 23 Nov 2026 23:52:39 +0100 Subject: [PATCH] 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: ` 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 --- .../skills/ckb-capture/scripts/capture_url.py | 2 +- .../skills/ckb-convert/scripts/convert.py | 2 +- .../share/skills/ckb-share/scripts/share.py | 2 +- .../scripts/save_conversation.py | 2 +- .agents/skills/ckb-export-okf/SKILL.md | 21 ++- .../ckb-export-okf/scripts/export_okf.py | 134 ++++++++++++++++-- .agents/skills/ckb-export-starlight/SKILL.md | 11 ++ .../scripts/export_starlight.py | 72 +++++++++- .../skills/ckb-ingest/scripts/dedup_inbox.py | 6 +- .agents/skills/ckb-lint/SKILL.md | 8 ++ .../skills/ckb-lint/scripts/lint_report.py | 39 ++++- .../skills/ckb-lint/scripts/session_start.py | 4 +- .agents/skills/ckb-retrieve/SKILL.md | 8 +- .../scripts/retrieve_candidates.py | 48 +++++-- AGENTS.md | 5 + docs/MANUAL.md | 4 + docs/MANUAL.pl.md | 4 + tests/expected/lint.json | 1 + tests/expected/retrieve.json | 3 +- tests/unit/test_exporters.py | 87 ++++++++++++ tests/unit/test_fold.py | 68 +++++++++ tests/unit/test_routines.py | 14 ++ tests/unit/test_silent_reads.py | 76 ++++++++++ 23 files changed, 572 insertions(+), 49 deletions(-) create mode 100644 tests/unit/test_fold.py create mode 100644 tests/unit/test_silent_reads.py diff --git a/.agents/modules/capture/skills/ckb-capture/scripts/capture_url.py b/.agents/modules/capture/skills/ckb-capture/scripts/capture_url.py index 7283470..8c4ef84 100644 --- a/.agents/modules/capture/skills/ckb-capture/scripts/capture_url.py +++ b/.agents/modules/capture/skills/ckb-capture/scripts/capture_url.py @@ -184,7 +184,7 @@ def wayback(url): # archive.org rate-limits this API (HTTP 429) after a burst; fetch() waits and retries once. data, _, _ = fetch(WAYBACK_API + urllib.parse.quote(url, safe=":/")) snap = json.loads(data).get("archived_snapshots", {}).get("closest", {}) - except (OSError, ValueError, urllib.error.URLError): + except (OSError, ValueError, urllib.error.URLError): # ok-silent: the Wayback snapshot is an optional fallback; None means none offered return None if not snap.get("available") or not snap.get("url"): return None diff --git a/.agents/modules/convert/skills/ckb-convert/scripts/convert.py b/.agents/modules/convert/skills/ckb-convert/scripts/convert.py index 02dc2ef..cca5b1c 100644 --- a/.agents/modules/convert/skills/ckb-convert/scripts/convert.py +++ b/.agents/modules/convert/skills/ckb-convert/scripts/convert.py @@ -92,7 +92,7 @@ def pandoc_version(): try: out = subprocess.run([exe, "--version"], capture_output=True, timeout=30, encoding="utf-8", errors="replace").stdout - except (OSError, subprocess.SubprocessError): + except (OSError, subprocess.SubprocessError): # ok-silent: callers report pandoc as unavailable return None m = re.search(r"pandoc(?:\.exe)?\s+(\d+(?:\.\d+)*)", out) return tuple(int(x) for x in m.group(1).split(".")) if m else (0,) diff --git a/.agents/modules/share/skills/ckb-share/scripts/share.py b/.agents/modules/share/skills/ckb-share/scripts/share.py index ba45a20..451b0a9 100644 --- a/.agents/modules/share/skills/ckb-share/scripts/share.py +++ b/.agents/modules/share/skills/ckb-share/scripts/share.py @@ -665,7 +665,7 @@ def local_received(root): try: with f.open(encoding="utf-8-sig", errors="replace") as fh: head = fh.read(4096) - except OSError: + except OSError: # ok-silent: a share listing; dedup_inbox reads every inbox file and fails loudly continue if "type: share" not in head: continue diff --git a/.agents/skills/ckb-add-conversation/scripts/save_conversation.py b/.agents/skills/ckb-add-conversation/scripts/save_conversation.py index cf2016a..9ac3fc5 100644 --- a/.agents/skills/ckb-add-conversation/scripts/save_conversation.py +++ b/.agents/skills/ckb-add-conversation/scripts/save_conversation.py @@ -163,7 +163,7 @@ def read_entries(path: Path): continue try: entries.append(redact(json.loads(line))) - except json.JSONDecodeError: + except json.JSONDecodeError: # ok-silent: the verbatim .jsonl is saved too; only the rendering skips a bad line continue return entries diff --git a/.agents/skills/ckb-export-okf/SKILL.md b/.agents/skills/ckb-export-okf/SKILL.md index 68b88d6..303ba88 100644 --- a/.agents/skills/ckb-export-okf/SKILL.md +++ b/.agents/skills/ckb-export-okf/SKILL.md @@ -35,6 +35,10 @@ If no interpreter is found, stop, say so, and point to "Prerequisites" in - `--out DIR` — write somewhere other than `outputs/okf` (rarely needed). It must be a folder inside `outputs/`, because it is deleted and rebuilt on every export; anything else is refused with exit code 2. +- `--drop-section NAME` — leave out every `## NAME` section, up to the next + `#`/`##` heading (repeatable; e.g. `Crux`, `Notes`). Offer it when the + bundle goes outside the team: Crux quotes and personal notes are evidence + for the KB's own readers. The script deletes and rebuilds the output directory on every run, so the bundle can never accumulate stale files from pages that were since renamed @@ -42,7 +46,7 @@ or removed. It touches nothing outside the output directory and runs no `git` commands. The exit code is `0` when the generated bundle conforms and `1` when it does -not — the report always prints either way, so read it rather than relying on +not or a page was refused — the report always prints either way, so read it rather than relying on the exit code alone. ### Step 2 — Relay the script's report @@ -58,6 +62,8 @@ The script prints, and you should summarize back to the user: the export — most commonly a page with no `type`, which the bundle exports as `type: unknown`. Surface them; the fix belongs in the source wiki (run `ckb-lint`), not in the export. +- Any `REFUSED:` lines: pages left out because their frontmatter never + closes. Say which, and that the bundle is incomplete until they are fixed. - Any `NONCONFORMANT:` lines. These are bugs in the export — an intra-bundle link that doesn't resolve, an index with the wrong frontmatter shape, a malformed log header. Do not report the run as @@ -87,8 +93,10 @@ The script prints, and you should summarize back to the user: | *(none)* | `tags` | omitted — no source field to derive it from | **Links:** the `[[Wikilink]]` half of every dual-link is dropped, keeping the -markdown half (a bare wikilink with no markdown twin degrades to its plain -label). Root-absolute `/wiki/entities/foo.md` becomes `/entities/foo.md`, +markdown half. A bare wikilink with no markdown twin becomes a bundle-root +link when its target matches a page's path, file name or title (`[[X|label]]` +and `[[X#anchor]]` included; `&`, spaces and brackets percent-encoded), and +degrades to its plain label only when nothing matches. Root-absolute `/wiki/entities/foo.md` becomes `/entities/foo.md`, since the bundle root is `outputs/okf/`, not the repo root. Relative links need no change — the export mirrors `wiki/`'s tree exactly. `linked//...` and `libs//...` references are left untouched and @@ -117,6 +125,13 @@ every non-reserved page has a non-empty `type`; the root index has only matches `## YYYY-MM-DD`; and every intra-bundle link resolves to a file that exists (cross-cascade `linked/`/`libs/` references are exempt by design). +**What never leaves the KB.** Both exporters run the same publish filter on +every page: `` spans go (in code too), HTML comments go (outside +fenced code), and an unclosed one of either takes the rest of the page with +it. A page whose frontmatter opens but never closes is refused, not exported, +because its raw keys would land in the body; the report prints a `REFUSED:` +line and the exit code is `1`. Fix the page and export again. + ## Edge cases Unusual situations — an empty target, a partial run, a conflicting state, diff --git a/.agents/skills/ckb-export-okf/scripts/export_okf.py b/.agents/skills/ckb-export-okf/scripts/export_okf.py index 2ea81a8..160ebf9 100644 --- a/.agents/skills/ckb-export-okf/scripts/export_okf.py +++ b/.agents/skills/ckb-export-okf/scripts/export_okf.py @@ -66,14 +66,66 @@ VERB_MAP = { # -------------------------------------------------------------------------- -# `` spans should never be in wiki/ (lint check 15 flags them), but an -# export publishes: drop any that slipped through, an unclosed tag to the end. -PRIVATE_RE = re.compile(r".*?(?:|\Z)", re.S | re.I) - - FM_CLOSE_RE = re.compile(r"^---[ \t]*$", re.M) # the closing line; may end the file +# --- publish filter: keep identical in both exporters (test_exporters) --- +# An export publishes, so it fails closed. `` spans should never be in +# wiki/ (lint check 15 flags them) and go wherever they are, code included; an +# HTML comment goes outside fenced code; an unclosed one of either takes the +# rest of the page with it. `--drop-section NAME` removes whole `## NAME` +# sections (e.g. Crux, Notes) up to the next `#`/`##` heading. +PRIVATE_RE = re.compile(r".*?(?:|\Z)", re.S | re.I) +COMMENT_RE = re.compile(r"|\Z)", re.S) +FENCE_LINE_RE = re.compile(r"^\s*(```|~~~)") + + +def unclosed_frontmatter(text): + """True when a page opens a frontmatter block that never closes: its raw + keys would be published as body text, so the page is refused.""" + return text.startswith("---\n") and FM_CLOSE_RE.search(text, 4) is None + + +def strip_for_publish(body, drop_sections=()): + body = PRIVATE_RE.sub("", body) + drop = {d.strip().lower() for d in drop_sections} + out, prose, fence, dropping = [], [], None, False + + def flush(): + text = "\n".join(prose) + prose.clear() + cut = text.find("" not in text[cut:] + + for line in body.split("\n"): + m = FENCE_LINE_RE.match(line) + if fence is None and not m and re.match(r"^#{1,2} ", line): + dropping = line.startswith("## ") and line[3:].strip().lower() in drop + if dropping: + continue + if fence is None and m: + if flush(): + return "\n".join(out) + fence = m.group(1) + out.append(line) + continue + if fence is not None: + out.append(line) + if m and m.group(1) == fence: + fence = None + continue + prose.append(line) + flush() + return "\n".join(out) +# --- end publish filter --- + + +DROP_SECTIONS = [] # set from --drop-section + + def parse_frontmatter(text): """Return (dict, body). Flat `key: value` YAML only — that is all the schema uses. Unparseable or absent frontmatter yields ({}, text).""" @@ -147,8 +199,32 @@ def slug_title(filename): return " ".join(w.capitalize() for w in re.split(r"[-_]+", stem) if w) -def strip_wikilinks(body, counters): - """Drop the [[...]] half of every dual-link, keeping the markdown half.""" +def build_link_index(pages): + """Wikilink target -> bundle-root href (`/entities/foo.md`), for resolving + bare [[Wikilinks]]. Keys: the path without `.md`, the file stem, and the + page title, each also lower-cased; the first page (in sorted order) wins a + shared key, so the result is deterministic.""" + index = {} + for rel in sorted(pages): + href = "/" + quote_href(rel.as_posix()) + keys = [rel.with_suffix("").as_posix(), rel.stem, pages[rel].title] + for key in keys: + if key: + index.setdefault(key, href) + index.setdefault(key.lower(), href) + return index + + +def quote_href(path): + """Percent-encode what would break or split a Markdown link target.""" + return (path.replace("%", "%25").replace("&", "%26").replace(" ", "%20") + .replace("(", "%28").replace(")", "%29")) + + +def strip_wikilinks(body, counters, link_index=None): + """Drop the [[...]] half of every dual-link, keeping the markdown half. + A bare [[X]] becomes a link when `link_index` resolves X (`[[X|label]]` + and `[[X#anchor]]` included), else its plain label.""" def drop_pair(m): counters["wikilinks"] += 1 @@ -162,11 +238,23 @@ def strip_wikilinks(body, counters): r"(?P\[[^\]]*\]\([^)]*\))\s*/\s*\[\[[^\]]*\]\]", drop_pair, body ) - # Any remaining bare wikilink degrades to its plain label. + # A remaining bare wikilink becomes a bundle link when it resolves, + # else degrades to its plain label. def bare(m): counters["wikilinks"] += 1 - label = m.group(1) - return label.split("|", 1)[-1].strip() + target, _, label = m.group(1).partition("|") + target, anchor = target.strip(), "" + if "#" in target: + target, anchor = target.split("#", 1) + target, anchor = target.strip(), "#" + anchor.strip() + text = (label or m.group(1).partition("|")[0]).strip() + lookup = target[5:] if target.startswith("wiki/") else target + lookup = lookup[:-3] if lookup.endswith(".md") else lookup + href = (link_index or {}).get(lookup) or (link_index or {}).get(lookup.lower()) + if href: + counters["wikilinks_linked"] = counters.get("wikilinks_linked", 0) + 1 + return f"[{text}]({href}{quote_href(anchor)})" + return text return re.sub(r"\[\[([^\]]*)\]\]", bare, body) @@ -191,8 +279,13 @@ def rewrite_links(body, counters): return re.sub(r"\[([^\]]*)\]\(([^)]*)\)", repl, body) +LINK_INDEX = {} # set by build(); bare [[X]] targets resolved against it + + def transform_body(body, counters): - return rewrite_links(strip_wikilinks(body, counters), counters) + # Links made from bare wikilinks are already bundle-root; rewrite_links + # leaves them alone (no /wiki/ prefix, not linked//libs/). + return rewrite_links(strip_wikilinks(body, counters, LINK_INDEX), counters) # -------------------------------------------------------------------------- @@ -203,8 +296,9 @@ def transform_body(body, counters): class Page: def __init__(self, relpath, text): self.relpath = relpath # PosixPath relative to wiki/ + self.refused = unclosed_frontmatter(text) self.fm, self.body = parse_frontmatter(text) - self.body = PRIVATE_RE.sub("", self.body) + self.body = strip_for_publish(self.body, DROP_SECTIONS) self.title = first_h1(self.body) or slug_title(relpath.name) self.description = self.fm.get("tldr", "") @@ -407,7 +501,11 @@ def emit_log(text, counters): def build(out_dir): pages, logs, indexes, assets = read_tree(WIKI) - counters = {"wikilinks": 0, "cascade_refs": 0, "rewritten": 0} + refused = sorted(rel.as_posix() for rel, page in pages.items() if page.refused) + pages = {rel: page for rel, page in pages.items() if not page.refused} + LINK_INDEX.clear() + LINK_INDEX.update(build_link_index(pages)) + counters = {"wikilinks": 0, "wikilinks_linked": 0, "cascade_refs": 0, "rewritten": 0} issues = [] if out_dir.exists(): @@ -450,6 +548,7 @@ def build(out_dir): "assets": len(assets), "counters": counters, "issues": issues, + "refused": refused, } return report @@ -500,7 +599,10 @@ def main(): parser = argparse.ArgumentParser(description="Export wiki/ as an OKF v0.1 bundle.") parser.add_argument("--check", action="store_true", help="validate only; write nothing") parser.add_argument("--out", default="outputs/okf", help="output directory (default: outputs/okf)") + parser.add_argument("--drop-section", action="append", default=[], metavar="NAME", + help="leave out every `## NAME` section, e.g. Crux or Notes (repeatable)") args = parser.parse_args() + DROP_SECTIONS[:] = args.drop_section if not WIKI.is_dir(): print(f"error: no wiki/ directory under {REPO_ROOT} — run from the repository root", file=sys.stderr) @@ -532,7 +634,7 @@ def main(): problems = validate(out_dir) print_report(report, problems, out_dir, checked_only=False) - return 1 if problems else 0 + return 1 if problems or report.get("refused") else 0 def print_report(report, problems, out_dir, checked_only): @@ -544,10 +646,14 @@ def print_report(report, problems, out_dir, checked_only): if report["assets"]: print(f"non-markdown files copied: {report['assets']}") print(f"wikilinks stripped: {counters['wikilinks']}") + if counters.get("wikilinks_linked"): + print(f"bare wikilinks turned into bundle links: {counters['wikilinks_linked']}") print(f"/wiki/ links rewritten to bundle-root: {counters['rewritten']}") print(f"linked//libs/ cross-cascade refs left unconverted: {counters['cascade_refs']}") for issue in report["issues"]: print(f"SOURCE ISSUE: {issue}") + for rel in report.get("refused", []): + print(f"REFUSED: {rel} — its frontmatter never closes, so its raw keys would be published; fix the page") if problems: print(f"NONCONFORMANT: {len(problems)} problem(s) in the generated bundle:") for p in problems: diff --git a/.agents/skills/ckb-export-starlight/SKILL.md b/.agents/skills/ckb-export-starlight/SKILL.md index b3f59a4..bdc1cfb 100644 --- a/.agents/skills/ckb-export-starlight/SKILL.md +++ b/.agents/skills/ckb-export-starlight/SKILL.md @@ -58,6 +58,8 @@ otherwise comes from `wiki/overview.md`'s H1 — a serviceable but generic default like "Knowledge Base Overview"). Consider offering this to the user rather than always silently accepting the default, since it's the one piece of branding a reader sees first. +`--drop-section NAME` (repeatable, e.g. `Crux`, `Notes`) leaves out every +`## NAME` section; offer it for a site readers outside the team will see. ### Step 3 — Relay the script's report @@ -65,6 +67,8 @@ The script prints, and you should summarize back to the user: - Mode used and page count exported. - Assets (images) copied. - Which meta pages were skipped (if `--include-meta` was omitted). +- Any `REFUSED:` lines: pages left out because their frontmatter never + closes (exit code `1`). The site is incomplete until they are fixed. - Any unresolved `[[wikilinks]]` (bare wikilinks with no matching page title — these get silently degraded to plain text in the output; a small number is normal wiki-content noise, but flag the list so the user @@ -115,6 +119,13 @@ The script prints, and you should summarize back to the user: sidebar config), plus explicit entries for the handful of root-level pages (Overview, the routing table, and the two optional meta pages). +**What never leaves the KB.** Both exporters run the same publish filter on +every page: `` spans go (in code too), HTML comments go (outside +fenced code), and an unclosed one of either takes the rest of the page with +it. A page whose frontmatter opens but never closes is refused, not exported, +because its raw keys would land in the body; the report prints a `REFUSED:` +line and the exit code is `1`. Fix the page and export again. + ## Edge cases Unusual situations — an empty target, a partial run, a conflicting state, diff --git a/.agents/skills/ckb-export-starlight/scripts/export_starlight.py b/.agents/skills/ckb-export-starlight/scripts/export_starlight.py index 8eeaf16..edd2692 100644 --- a/.agents/skills/ckb-export-starlight/scripts/export_starlight.py +++ b/.agents/skills/ckb-export-starlight/scripts/export_starlight.py @@ -53,9 +53,61 @@ RESERVED_ROOT_ROUTES = { # A root page named like a reserved route (wiki/routing-table.md, changelog.md) # would overwrite it: it is exported as -page instead. TAKEN_ROOT_NAMES = {v + ".md" for v in RESERVED_ROOT_ROUTES.values()} - set(RESERVED_ROOT_ROUTES) -# `` spans should never be in wiki/ (lint check 15 flags them), but an -# export publishes: drop any that slipped through, an unclosed tag to the end. +# --- publish filter: keep identical in both exporters (test_exporters) --- +# An export publishes, so it fails closed. `` spans should never be in +# wiki/ (lint check 15 flags them) and go wherever they are, code included; an +# HTML comment goes outside fenced code; an unclosed one of either takes the +# rest of the page with it. `--drop-section NAME` removes whole `## NAME` +# sections (e.g. Crux, Notes) up to the next `#`/`##` heading. PRIVATE_RE = re.compile(r".*?(?:|\Z)", re.S | re.I) +COMMENT_RE = re.compile(r"|\Z)", re.S) +FENCE_LINE_RE = re.compile(r"^\s*(```|~~~)") + + +def unclosed_frontmatter(text): + """True when a page opens a frontmatter block that never closes: its raw + keys would be published as body text, so the page is refused.""" + return text.startswith("---\n") and FM_CLOSE_RE.search(text, 4) is None + + +def strip_for_publish(body, drop_sections=()): + body = PRIVATE_RE.sub("", body) + drop = {d.strip().lower() for d in drop_sections} + out, prose, fence, dropping = [], [], None, False + + def flush(): + text = "\n".join(prose) + prose.clear() + cut = text.find("" not in text[cut:] + + for line in body.split("\n"): + m = FENCE_LINE_RE.match(line) + if fence is None and not m and re.match(r"^#{1,2} ", line): + dropping = line.startswith("## ") and line[3:].strip().lower() in drop + if dropping: + continue + if fence is None and m: + if flush(): + return "\n".join(out) + fence = m.group(1) + out.append(line) + continue + if fence is not None: + out.append(line) + if m and m.group(1) == fence: + fence = None + continue + prose.append(line) + flush() + return "\n".join(out) +# --- end publish filter --- + + +DROP_SECTIONS = [] # set from --drop-section def yaml_quote(s): @@ -310,7 +362,7 @@ def compute_badge(fm, today): def render_page(relpath, path, title_index, today, report): text = path.read_text(encoding="utf-8-sig") fm, body = parse_frontmatter(text) - body = PRIVATE_RE.sub("", body) + body = strip_for_publish(body, DROP_SECTIONS) h1_title, body = extract_h1(body) title = h1_title or Path(relpath).stem.replace("-", " ").title() @@ -508,11 +560,14 @@ def main(): parser.add_argument("--mode", choices=["full", "content-only"], required=True) parser.add_argument("--include-meta", action="store_true") parser.add_argument("--today", default=None) + parser.add_argument("--drop-section", action="append", default=[], metavar="NAME", + help="leave out every `## NAME` section, e.g. Crux or Notes (repeatable)") parser.add_argument( "--site-title", default=None, help="Override the site title (default: derived from wiki/overview.md's H1)", ) args = parser.parse_args() + DROP_SECTIONS[:] = args.drop_section if not WIKI.is_dir(): sys.exit(f"No wiki/ directory found under {REPO_ROOT} - run this from the repo root.") @@ -534,7 +589,7 @@ def main(): shutil.rmtree(assets_dir) docs_dir.mkdir(parents=True, exist_ok=True) - report = {"copied_assets": [], "unresolved_wikilinks": [], "pages": 0, "skipped_meta": []} + report = {"copied_assets": [], "unresolved_wikilinks": [], "pages": 0, "skipped_meta": [], "refused": []} top_dirs = set() edges_path = WIKI / "graph" / "edges.json" @@ -544,6 +599,9 @@ def main(): if relpath in ("log.md", "error-book.md") and not args.include_meta: report["skipped_meta"].append(relpath) continue + if unclosed_frontmatter(path.read_text(encoding="utf-8-sig")): + report["refused"].append(relpath) + continue rendered = render_page(relpath, path, title_index, today, report) @@ -605,6 +663,8 @@ def main(): for relpath, _ in pages: if relpath in ("log.md", "error-book.md") and not args.include_meta: continue + if relpath in report["refused"]: + continue dest = docs_dir / out_path_for(relpath) text = dest.read_text(encoding="utf-8-sig") for m in re.finditer(r"\]\((/[a-zA-Z0-9_\-./]+/)\)", text): @@ -619,6 +679,8 @@ def main(): print(f"mode: {args.mode}") print(f"pages exported: {report['pages']}") print(f"assets copied: {len(report['copied_assets'])}") + for rel in report["refused"]: + print(f"REFUSED: {rel} — its frontmatter never closes, so its raw keys would be published; fix the page") if report["skipped_meta"]: print(f"meta pages skipped (--include-meta not set): {', '.join(report['skipped_meta'])}") if report["unresolved_wikilinks"]: @@ -630,6 +692,8 @@ def main(): for b in broken: print(f" - {b}") print(f"output: {OUT}") + if report["refused"]: + sys.exit(1) if __name__ == "__main__": diff --git a/.agents/skills/ckb-ingest/scripts/dedup_inbox.py b/.agents/skills/ckb-ingest/scripts/dedup_inbox.py index be70f58..52f968a 100644 --- a/.agents/skills/ckb-ingest/scripts/dedup_inbox.py +++ b/.agents/skills/ckb-ingest/scripts/dedup_inbox.py @@ -47,7 +47,7 @@ def text_digest(path): return None try: text = path.read_text(encoding="utf-8-sig", errors="replace") - except OSError: + except OSError: # ok-silent: sha256() reads the same file first and fails loudly return None return hashlib.sha256(" ".join(text.split()).encode("utf-8")).hexdigest() @@ -69,7 +69,7 @@ def link_url(path): """The URL a link file points at, or None.""" try: text = path.read_text(encoding="utf-8-sig", errors="replace") - except OSError: + except OSError: # ok-silent: sha256() reads the same file first and fails loudly return None suffix = path.suffix.lower() captured = frontmatter_value(text, "source_url") if suffix == ".md" else "" @@ -115,7 +115,7 @@ def share_key(path): return None try: text = path.read_text(encoding="utf-8-sig", errors="replace") - except OSError: + except OSError: # ok-silent: sha256() reads the same file first and fails loudly return None if frontmatter_value(text, "type") != "share" or not frontmatter_value(text, "share_channel"): return None diff --git a/.agents/skills/ckb-lint/SKILL.md b/.agents/skills/ckb-lint/SKILL.md index c413869..8131e4c 100644 --- a/.agents/skills/ckb-lint/SKILL.md +++ b/.agents/skills/ckb-lint/SKILL.md @@ -398,6 +398,14 @@ auto-fixed: either the vocabulary gains a row (the user's call) or the page drops the tag. A connector-backed lib is checked against its own `tags.md` when it has one. +### 20 — Name collisions + +Two pages whose paths differ only by case or accents (`entities/Kopeć.md` and +`entities/kopec.md`, or the same `ć` composed in one name and decomposed in +the other) look like one page to a reader, to `ckb-retrieve`'s name matching +and to a case-insensitive file system (Windows, macOS). Each group is +reported once. Never auto-fixed: merge the two or rename one, and log it. + ### Context budget `--quick` and the full report flag an always-loaded layer — `AGENTS.md` plus diff --git a/.agents/skills/ckb-lint/scripts/lint_report.py b/.agents/skills/ckb-lint/scripts/lint_report.py index 7c61dfe..3e7dd2d 100644 --- a/.agents/skills/ckb-lint/scripts/lint_report.py +++ b/.agents/skills/ckb-lint/scripts/lint_report.py @@ -41,6 +41,7 @@ import hashlib import json import re import sys +import unicodedata from datetime import date, datetime from pathlib import Path @@ -392,6 +393,30 @@ def check_decisions(docs, root, today): return findings +# Letters NFKD does not split into base + accent; the same map as +# session_start.py's SLUG_MAP, so `Michał`, `Michal` and a decomposed `Michał` +# all fold to `michal` (N17). Keep the three copies identical (test_fold). +FOLD_MAP = str.maketrans({"ł": "l", "Ł": "L", "ø": "o", "Ø": "O", "đ": "d", "Đ": "D", + "ß": "ss", "æ": "ae", "Æ": "AE", "œ": "oe", "Œ": "OE"}) + + +def fold(s): + """Case- and accent-insensitive key: NFKD, combining marks dropped, lower-cased.""" + s = unicodedata.normalize("NFKD", s.translate(FOLD_MAP)) + return "".join(c for c in s if not unicodedata.combining(c)).lower() + + +def check_names(docs): + """Two pages whose paths differ only by case or accents (`Kopeć.md` and + `kopec.md`, or a composed and a decomposed `ć`) are one name to a reader + and to a case-insensitive file system: report each group once (check 20).""" + groups = {} + for doc in docs: + groups.setdefault(fold(doc.rel.with_suffix("").as_posix()), []).append(doc.rel.as_posix()) + return [f"{', '.join(sorted(paths))}: names differ only by case or accents — merge or rename one" + for key, paths in sorted(groups.items()) if len(paths) > 1] + + def check_orphans(docs): inbound = set() titles = {} @@ -604,7 +629,7 @@ def digest(path): """First 8 hex chars of the file's sha256, or None if unreadable.""" try: return hashlib.sha256(path.read_bytes()).hexdigest()[:8] - except OSError: + except OSError: # ok-silent: None is reported by the caller as `could not be read` return None @@ -620,7 +645,7 @@ def fingerprint_matches(recorded, path): """True/False whether `recorded` (a hex prefix) fingerprints `path`; None if unreadable.""" try: data = path.read_bytes() - except OSError: + except OSError: # ok-silent: None is reported by the caller as `could not be read` return None recorded = recorded.lower() return any(d.startswith(recorded) for d in line_ending_digests(data)) @@ -753,6 +778,7 @@ def check_crux(docs, root): try: haystack = " ".join(target.read_text(encoding="utf-8-sig", errors="replace").split()) except OSError: + findings.append(f"{doc.rel.as_posix()}: crux quote not checked — source `{ref}` could not be read") continue if len(needle) < 24: continue # too short to match meaningfully @@ -957,7 +983,7 @@ def secret_candidate(path): with path.open("rb") as fh: return b"\0" not in fh.read(8192) except OSError: - return False + return True # unreadable: let check_secrets try it and report "not scanned" def check_secrets(): @@ -984,6 +1010,7 @@ def check_secrets(): continue text = path.read_text(encoding="utf-8-sig", errors="replace") except OSError: + findings.append(f"{rel}: not scanned for secrets — could not be read; check it by hand") continue # One pass per pattern over the whole file, line numbers only for # the rare match: per-line scanning is too slow for session start. @@ -1076,7 +1103,7 @@ def print_budget(budget): out = subprocess.run([sys.executable, "-I", str(start), "--no-git", "--root", str(REPO_ROOT)], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120).stdout print(f" plus the session-start brief: ~{-(-len(out) // 4)} tokens this time (varies per session; not counted)") - except (OSError, subprocess.SubprocessError): + except (OSError, subprocess.SubprocessError): # ok-silent: an extra estimate line; the budget itself is still reported pass @@ -1132,6 +1159,7 @@ CHECKS = [ ("17 review", "review"), ("18 contradictions", "contradictions"), ("19 tags", "tags"), + ("20 name collisions", "names"), ] # The subset worth running at session start (Rule E): cheap, and each finding @@ -1161,6 +1189,7 @@ def run_tree(root, today, label): "review": check_review(docs), "contradictions": check_contradictions(docs), "tags": check_tags(root, docs), + "names": check_names(docs), "review_queue": review_queue(docs), "hubs": in_degree(root, docs), } @@ -1178,7 +1207,7 @@ def in_degree(root, docs): return [] try: data = json.loads(edges_path.read_text(encoding="utf-8-sig")) - except json.JSONDecodeError: + except json.JSONDecodeError: # ok-silent: check_graph reports invalid edges.json as a finding return [] edges = data.get("edges", data) if isinstance(data, dict) else data if not isinstance(edges, list): diff --git a/.agents/skills/ckb-lint/scripts/session_start.py b/.agents/skills/ckb-lint/scripts/session_start.py index 09652e1..08a32fb 100644 --- a/.agents/skills/ckb-lint/scripts/session_start.py +++ b/.agents/skills/ckb-lint/scripts/session_start.py @@ -113,7 +113,7 @@ def stored_title(root, session_id=None): sys.path.insert(0, str(SAVE.parent)) try: import save_conversation as sc # noqa: E402 - except Exception: + except Exception: # ok-silent: no stored title prints `title: none` and the agent stores one return None finally: sys.path.pop(0) @@ -125,7 +125,7 @@ def stored_title(root, session_id=None): if not sessions: return None return sc.stored_title(root, sessions[0]["id"]) - except Exception: + except Exception: # ok-silent: no stored title prints `title: none` and the agent stores one return None diff --git a/.agents/skills/ckb-retrieve/SKILL.md b/.agents/skills/ckb-retrieve/SKILL.md index bf5aec1..f427af9 100644 --- a/.agents/skills/ckb-retrieve/SKILL.md +++ b/.agents/skills/ckb-retrieve/SKILL.md @@ -95,7 +95,13 @@ came from and at what rank, its `tldr`, `STALE`/`INBOX`/`SUPERSEDED`/`DRAFT`/ any `raw/archive/` or `outputs/` file it cites that the script folded in as corroboration rather than counting as a second source. -Two lines of the header matter on their own: +Three lines of the header matter on their own: + +- **`DEGRADED: …`** (`degraded` in `--json`) — a page, the graph or the + exact-match search could not be read, so the list is incomplete. Name what + was missed in the answer. With no candidates, the script says "no + candidates among what could be read": that is not "the KB has nothing on + this", so don't write a `query-gaps.md` entry until the read is fixed. - **`raw/inbox/ hits`** — un-ingested material already holds something relevant. It can answer the question, and it is the clearest signal an diff --git a/.agents/skills/ckb-retrieve/scripts/retrieve_candidates.py b/.agents/skills/ckb-retrieve/scripts/retrieve_candidates.py index f3f1fe7..32b3a98 100755 --- a/.agents/skills/ckb-retrieve/scripts/retrieve_candidates.py +++ b/.agents/skills/ckb-retrieve/scripts/retrieve_candidates.py @@ -41,6 +41,7 @@ import shutil import sqlite3 import subprocess import sys +import unicodedata from collections import Counter, defaultdict from datetime import date, datetime from pathlib import Path @@ -50,6 +51,10 @@ was we what when where which who why with do does did our your their about into """.split()) MD_EXCLUDE = {"index.md", "log.md"} +# What could not be read this run. A signal that failed must say so: an empty +# list from a failed read is indistinguishable from "nothing matches" (N2). +DEGRADED = [] + # ---------------------------------------------------------------- parsing --- FM_CLOSE_RE = re.compile(r"^---[ \t]*$", re.M) # the closing line; may end the file @@ -75,6 +80,19 @@ def title_of(body, fallback): return m.group(1).strip() if m else fallback +# Letters NFKD does not split into base + accent; the same map as +# session_start.py's SLUG_MAP, so `Michał`, `Michal` and a decomposed `Michał` +# all fold to `michal` (N17). Keep the three copies identical (test_fold). +FOLD_MAP = str.maketrans({"ł": "l", "Ł": "L", "ø": "o", "Ø": "O", "đ": "d", "Đ": "D", + "ß": "ss", "æ": "ae", "Æ": "AE", "œ": "oe", "Œ": "OE"}) + + +def fold(s): + """Case- and accent-insensitive key: NFKD, combining marks dropped, lower-cased.""" + s = unicodedata.normalize("NFKD", s.translate(FOLD_MAP)) + return "".join(c for c in s if not unicodedata.combining(c)).lower() + + def tokens(s): # Unicode letters and digits, so "właścicielem" is one token, not "cicielem". return [t for t in re.findall(r"[^\W_][\w./:-]{1,}", s.lower()) if t not in STOP and len(t) > 1] @@ -123,7 +141,8 @@ def load_pages(root): continue try: text = p.read_text(encoding="utf-8-sig", errors="replace") - except OSError: + except OSError as e: + DEGRADED.append(f"page not read: {p.relative_to(root).as_posix()} ({e.strerror or e})") continue fm, body = parse_frontmatter(text) if not fm.get("type") and base.name == "wiki": @@ -143,8 +162,8 @@ def load_edges(root): if f.exists(): try: edges += json.loads(f.read_text(encoding="utf-8-sig")).get("edges", []) - except (OSError, ValueError): - pass + except (OSError, ValueError) as e: + DEGRADED.append(f"graph not read: {f.relative_to(root).as_posix()} ({e}) — graph signals incomplete") return edges @@ -172,7 +191,8 @@ def signal_exact(root, toks, lits): cmd = ["grep", "-r", "-c", "-i", "-F", "--exclude=*.json", "--exclude-dir=.git", "--", n, *targets] try: out = subprocess.run(cmd, cwd=root, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30).stdout - except (OSError, subprocess.TimeoutExpired): + except (OSError, subprocess.TimeoutExpired) as e: + DEGRADED.append(f"exact-match search failed for {n!r} ({type(e).__name__}) — exact signal incomplete") continue for line in out.splitlines(): path, _, cnt = line.rpartition(":") @@ -187,10 +207,10 @@ def signal_exact(root, toks, lits): def signal_tldr(pages, toks): - qs = set(toks) + qs = {fold(t) for t in toks} scored = [] for rel, pg in pages.items(): - hay = set(tokens(pg["title"] + " " + pg["fm"].get("tldr", ""))) + hay = {fold(t) for t in tokens(pg["title"] + " " + pg["fm"].get("tldr", ""))} hit = len(qs & hay) if hit: scored.append((-(hit / max(len(qs), 1)), -hit, rel)) @@ -201,7 +221,7 @@ def signal_scope(root, pages, toks, forced): proj = root / "wiki/projects" if not proj.is_dir(): return [], None - qs = set(toks) + qs = {fold(t) for t in toks} best, best_hit = None, 0 for p in proj.glob("*.md"): if p.name == "index.md": @@ -210,7 +230,7 @@ def signal_scope(root, pages, toks, forced): best = p break pg = pages.get(p.relative_to(root).as_posix()) - hit = len(qs & set(tokens((pg["title"] if pg else "") + " " + (pg["fm"].get("tldr", "") if pg else "") + " " + p.stem))) + hit = len(qs & {fold(t) for t in tokens((pg["title"] if pg else "") + " " + (pg["fm"].get("tldr", "") if pg else "") + " " + p.stem)}) if hit > best_hit: best, best_hit = p, hit if not best: @@ -334,7 +354,7 @@ def refresh_index(db, root, pages): f = root / rel try: mtime = f.stat().st_mtime - except OSError: + except OSError: # ok-silent: a page gone since load_pages; load_pages reports unreadable pages continue old = known.pop(rel, None) if old and old[0] == mtime: @@ -397,7 +417,7 @@ def log_opened(root, paths, today): def est_tokens(root, rel): try: return -(-(root / rel).stat().st_size // 4) - except OSError: + except OSError: # ok-silent: only the token estimate is left out return None @@ -483,7 +503,7 @@ def main(): out = { "query": a.query, "k": a.k, "literal_tokens": lits, "scope_page": scope_page, "tags": a.tag, "inbox_hits": sorted(inbox_hits), "empty_graph": not edges, "bm25": bm25_status, - "candidates": [], + "candidates": [], "degraded": list(DEGRADED), } for item, sc in results: pg = pages.get(item) @@ -517,6 +537,8 @@ def main(): print(f"bm25: {bm25_status} — section search skipped") if inbox_hits: print(f"raw/inbox/ hits ({len(inbox_hits)}): un-ingested material — an ingest is overdue") + for d in DEGRADED: + print(f"DEGRADED: {d}") print() for i, c in enumerate(out["candidates"], 1): flags = [f for f, on in [("STALE", c["stale"]), ("INBOX", c["from_inbox"]), ("SUPERSEDED", c["superseded_by"]), @@ -530,7 +552,9 @@ def main(): print(" sections: " + ", ".join(f"#{s['anchor']} ({s['heading']})" for s in c["sections"])) if c["corroborated_by"]: print(f" corroborated by: {', '.join(c['corroborated_by'])}") - if not out["candidates"]: + if not out["candidates"] and DEGRADED: + print("no candidates among what could be read — not the same as no match; fix the DEGRADED lines and re-run") + elif not out["candidates"]: print("no candidates — nothing in the cascade matches; consider a wiki/query-gaps.md entry") diff --git a/AGENTS.md b/AGENTS.md index 73fa026..323f792 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -280,6 +280,11 @@ Never retry a failed interpreter on every call, and never install anything without asking. Every script the template and its modules ship is Python; a module may need other tools, never another script language. +A failed read is never an empty result. When a script prints `DEGRADED:` +or a finding says something "could not be read" or "not checked", report +that part as unchecked: say "could not check X", never "none found" or +"nothing matches". + --- ## 4. NON-NEGOTIABLE RULES diff --git a/docs/MANUAL.md b/docs/MANUAL.md index f67a384..3c52ea8 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -907,6 +907,10 @@ Produces an Astro + Starlight-ready site at `outputs/starlight/` - real pages, real navigation, something you could host and hand to someone who's never seen the wiki. `.agents/skills/ckb-export-starlight/SKILL.md`. +Both exports leave out `` spans and HTML comments, and refuse a page +whose frontmatter never closes. For an export that leaves the team, say +"without the Crux and Notes sections" and those go too. + **A document you write often, from a template** - say: > "Prepare a new document using template status-report." / "New status diff --git a/docs/MANUAL.pl.md b/docs/MANUAL.pl.md index bd36939..604195e 100644 --- a/docs/MANUAL.pl.md +++ b/docs/MANUAL.pl.md @@ -948,6 +948,10 @@ Tworzy gotową do uruchomienia stronę Astro + Starlight w możesz hostować i dać komuś, kto nigdy nie widział wiki. `.agents/skills/ckb-export-starlight/SKILL.md`. +Oba eksporty pomijają fragmenty `` i komentarze HTML, a stronę, +której frontmatter się nie zamyka, odrzucają. Dla eksportu, który wychodzi +poza zespół, powiedz „bez sekcji Crux i Notes” i te też zostaną pominięte. + **Dokument, który piszesz regularnie, z szablonu** — powiedz: > „Prepare a new document using template status-report.” / „New status diff --git a/tests/expected/lint.json b/tests/expected/lint.json index 2cdb312..92e892d 100644 --- a/tests/expected/lint.json +++ b/tests/expected/lint.json @@ -17,6 +17,7 @@ "review": [], "contradictions": [], "tags": [], + "names": [], "review_queue": [], "hubs": [ [ diff --git a/tests/expected/retrieve.json b/tests/expected/retrieve.json index 1b0f254..0ada3e3 100644 --- a/tests/expected/retrieve.json +++ b/tests/expected/retrieve.json @@ -292,5 +292,6 @@ "sections": [], "tokens": 15 } - ] + ], + "degraded": [] } diff --git a/tests/unit/test_exporters.py b/tests/unit/test_exporters.py index e6d57f1..c3467bb 100644 --- a/tests/unit/test_exporters.py +++ b/tests/unit/test_exporters.py @@ -113,6 +113,93 @@ class OkfScalars(unittest.TestCase): self.assertEqual(self.okf.first_h1(body), "Real title") self.assertIsNone(self.okf.first_h1("```\n# only in code\n```\n")) + def test_bare_wikilinks_become_bundle_links(self): + # A bare [[X]] used to degrade to plain text, losing the link. + Path_ = self.okf.Path + + class P: + def __init__(self, title): + self.title = title + + pages = {Path_("entities/maria-nowak.md"): P("Maria Nowak"), + Path_("topics/r&d plan.md"): P("R&D plan")} + index = self.okf.build_link_index(pages) + c = {"wikilinks": 0} + out = self.okf.strip_wikilinks( + "See [[entities/maria-nowak]], [[Maria Nowak|Maria]], [[maria-nowak#Role]], " + "[[wiki/entities/maria-nowak.md]], [[R&D plan]] and [[nowhere]].", c, index) + self.assertEqual(out, + "See [entities/maria-nowak](/entities/maria-nowak.md), [Maria](/entities/maria-nowak.md), " + "[maria-nowak#Role](/entities/maria-nowak.md#Role), " + "[wiki/entities/maria-nowak.md](/entities/maria-nowak.md), " + "[R&D plan](/topics/r%26d%20plan.md) and nowhere.") + self.assertEqual(c["wikilinks"], 6) + self.assertEqual(c["wikilinks_linked"], 5) + # a dual link still keeps only its Markdown half + self.assertEqual(self.okf.strip_wikilinks( + "[[entities/maria-nowak]] / [Maria](/wiki/entities/maria-nowak.md)", {"wikilinks": 0}, index), + "[Maria](/wiki/entities/maria-nowak.md)") + + +def publish_filter(path): + text = path.read_text(encoding="utf-8") + start = text.index("# --- publish filter") + return text[start:text.index("# --- end publish filter ---", start)] + + +class PublishFilter(unittest.TestCase): + """N7: an export publishes, so it fails closed. One planted leak of each + kind must not reach either exporter's output.""" + + LEAKY = ("---\ntype: concept\ntldr: leak test\n---\n\n# Leaky\n\nVisible intro.\n" + "\n" + "Inline SECRET-PRIVATE text.\n\n" + "```html\n\n```\n\n" + "## Crux\n\n> SECRET-CRUX quote\n\n" + "## Notes\n\nSECRET-NOTE\n\n" + "## After\n\nStill here.\n", "Still here."): + self.assertIn(kept, text) + + def test_okf(self): + r = run(self.kb, OKF, "--drop-section", "Crux", "--drop-section", "notes") + self.assertIn(r.returncode, (0, 1), r.stdout + r.stderr) + self.check(self.kb / "outputs/okf/entities/leaky.md") + + def test_starlight(self): + r = run(self.kb, STARLIGHT, "--mode", "content-only", "--today", "2026-11-23", + "--drop-section", "Crux", "--drop-section", "Notes") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.check(next((self.kb / "outputs/starlight").rglob("leaky.md"))) + + def test_unclosed_frontmatter_is_refused(self): + (self.kb / "wiki/entities/broken.md").write_text( + "---\ntype: concept\nowner_email: SECRET-FM\n\n# Broken\n", encoding="utf-8") + for script, args in ((OKF, ()), (STARLIGHT, ("--mode", "content-only", "--today", "2026-11-23"))): + r = run(self.kb, script, *args) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("REFUSED: entities/broken.md", r.stdout) + for f in (self.kb / "outputs").rglob("*.md"): + self.assertNotIn("SECRET-FM", f.read_text(encoding="utf-8"), f) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/test_fold.py b/tests/unit/test_fold.py new file mode 100644 index 0000000..0d66167 --- /dev/null +++ b/tests/unit/test_fold.py @@ -0,0 +1,68 @@ +"""N17: one case- and accent-insensitive fold, kept identical where it is +copied (each skill's scripts stand alone), and lint check 20 built on it.""" +import importlib.util +import shutil +import subprocess +import sys +import tempfile +import unicodedata +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +LINT = ROOT / ".agents/skills/ckb-lint/scripts/lint_report.py" +RETRIEVE = ROOT / ".agents/skills/ckb-retrieve/scripts/retrieve_candidates.py" +START = ROOT / ".agents/skills/ckb-lint/scripts/session_start.py" + + +def load(path): + spec = importlib.util.spec_from_file_location(path.stem, str(path)) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +class Fold(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.lint, cls.retrieve, cls.start = load(LINT), load(RETRIEVE), load(START) + + def test_maps_are_identical(self): + self.assertEqual(self.lint.FOLD_MAP, self.retrieve.FOLD_MAP) + self.assertEqual(self.lint.FOLD_MAP, self.start.SLUG_MAP) + + def test_fold_equates_case_accents_and_composition(self): + decomposed = unicodedata.normalize("NFD", "Michał Kopeć") + for fold in (self.lint.fold, self.retrieve.fold): + self.assertEqual(fold("Michał Kopeć"), "michal kopec") + self.assertEqual(fold(decomposed), "michal kopec") + self.assertEqual(fold("ŁÓDŹ"), "lodz") + + def test_lint_reports_names_that_collide_after_folding(self): + with tempfile.TemporaryDirectory() as tmp: + kb = Path(tmp) / "kb" + shutil.copytree(str(ROOT / "tests/fixtures/minimal-kb"), str(kb)) + page = "---\ntype: person\n---\n\n# X\n" + (kb / "wiki/entities/Kopeć.md").write_text(page, encoding="utf-8") + (kb / "wiki/entities/kopec.md").write_text(page, encoding="utf-8") + out = subprocess.run([sys.executable, str(LINT), "--today", "2026-11-23"], cwd=str(kb), + capture_output=True, text=True, encoding="utf-8").stdout + self.assertIn("names differ only by case or accents", out) + + def test_retrieve_matches_a_title_without_its_accents(self): + with tempfile.TemporaryDirectory() as tmp: + kb = Path(tmp) / "kb" + shutil.copytree(str(ROOT / "tests/fixtures/minimal-kb"), str(kb)) + (kb / "wiki/entities/branch-a.md").write_text( + "---\ntype: place\ntldr: Łódź office opening hours\n---\n\n# Łódź office\n", encoding="utf-8") + out = subprocess.run([sys.executable, str(RETRIEVE), "lodz", "--root", str(kb), + "--no-bm25", "--today", "2026-11-23"], + capture_output=True, text=True, encoding="utf-8").stdout + # Only the folded tldr signal can find it: the query has no accent, + # the page text has no "lodz" for grep, and the file name doesn't either. + self.assertIn("wiki/entities/branch-a.md", out) + self.assertIn("tldr:", out.split("wiki/entities/branch-a.md", 1)[1].split("\n", 1)[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_routines.py b/tests/unit/test_routines.py index 7cb2ca0..0a677ae 100644 --- a/tests/unit/test_routines.py +++ b/tests/unit/test_routines.py @@ -57,6 +57,20 @@ class Mark(unittest.TestCase): due = run(self.root, "--due") self.assertNotIn("unreadable", due.stdout + due.stderr) + def test_interrupted_run_stays_due(self): + # Only --mark advances last_run. Reading what is due (session start does + # this) must never write, so a run that dies before --mark is due again + # next session instead of silently skipped (ai-memory b4fbe3c4). + before = "routines:\n - name: wl\n do: Lint\n every: 7d\n last_run: 2026-01-01\n" + self.write(before) + for args in (("--due",), ("--list",), ("--due",)): + r = run(self.root, *args) + self.assertIn(r.returncode, (0, 1), r.stdout + r.stderr) # --due: 1 = something due + self.assertEqual(self.read(), before, f"{args} wrote ckb.yaml") + self.assertIn("wl", run(self.root, "--due").stdout) + run(self.root, "--mark", "wl") + self.assertNotIn("wl", run(self.root, "--due").stdout) + def test_mark_replaces_existing_date_only(self): self.write("routines:\n - name: wl\n do: Lint\n every: 7d\n last_run: 2026-01-01 # weekly\n") run(self.root, "--mark", "wl") diff --git a/tests/unit/test_silent_reads.py b/tests/unit/test_silent_reads.py new file mode 100644 index 0000000..67cbee3 --- /dev/null +++ b/tests/unit/test_silent_reads.py @@ -0,0 +1,76 @@ +"""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: ` 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[^:\n]*):(?P[^\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: ` 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()