| 1 | #!/usr/bin/env python3 |
| 2 | """The knowledge lint: check a tree's .the-valley graph against the convention. |
| 3 | |
| 4 | Three classes of finding, all reported in one run (ida-1ec03b1): |
| 5 | |
| 6 | frontmatter every node's YAML frontmatter vets against #Node in |
| 7 | schema/node.cue, in one `cue vet` pass over the whole graph |
| 8 | filename coherence a node lives at <type directory>/<id>-<slug>.md, its filename |
| 9 | id is the id its frontmatter declares, no id repeats, and — |
| 10 | for nodes the derivation rule covers — the id's hash is |
| 11 | derived from the slug |
| 12 | reference integrity [[wiki-links]], `blocked_by`, `parent`, `supersedes` and |
| 13 | `graduated_into` ids, and relative markdown links all resolve, a |
| 14 | parent is an outcome, a graduated idea went to an outcome, a |
| 15 | question or a document, and a superseded node says so in its own |
| 16 | status. A `blocked_by` entry written <project>:<id> names a node |
| 17 | in another project's graph, which only a reader of both resolves |
| 18 | |
| 19 | The lint reads only the tree it is given. It never runs git, so it holds for a |
| 20 | worktree, a store path, or an unpacked archive alike. |
| 21 | """ |
| 22 | |
| 23 | import argparse |
| 24 | import hashlib |
| 25 | import json |
| 26 | import os |
| 27 | import re |
| 28 | import subprocess |
| 29 | import sys |
| 30 | |
| 31 | # A markdown link target: ](target) or ](target "title"). |
| 32 | LINK = re.compile(r"\]\(\s*([^)\s]+)(?:\s+\"[^\"]*\")?\s*\)") |
| 33 | WIKI_LINK = re.compile(r"\[\[([^\]|]+)\]\]") |
| 34 | INLINE_CODE = re.compile(r"`[^`\n]*`") |
| 35 | FENCE = re.compile(r"^\s*(```|~~~)") |
| 36 | NODE_FILENAME = re.compile(r"^([a-z]+-[0-9a-f]+)-([a-z0-9-]+)\.md$") |
| 37 | HEADING = re.compile(r"^#{1,6}\s+(.*?)\s*$") |
| 38 | NOT_IN_SLUG = re.compile(r"[^\w\s-]") |
| 39 | # A link target the tree cannot answer for: another host, or a mail client. |
| 40 | EXTERNAL = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:") |
| 41 | # A graduated_into target that is a node id rather than a document path. |
| 42 | NODE_ID = re.compile(r"^[a-z]+-[0-9a-f]{7}$") |
| 43 | # The types a graduated idea may go to: an outcome, when it is taken on as |
| 44 | # work, or a question, when it needs settling. |
| 45 | GRADUATION_TYPES = ("outcome", "question") |
| 46 | |
| 47 | # The id-derivation rule (archive/.the-valley/README.md): a node's id hash is the |
| 48 | # first 7 hex characters of the SHA-256 of its slug. The rule covers every |
| 49 | # node created after this date; nodes created on or before it keep their |
| 50 | # ids, checked for shape and uniqueness only. |
| 51 | ID_RULE_CUTOFF = "2026-08-05" |
| 52 | |
| 53 | # When a blocker stops blocking: the statuses, per type, at which a node no |
| 54 | # longer holds up an outcome that names it in `blocked_by` (dcr-593d3d1). An |
| 55 | # idea clears by graduating, being superseded, or being discarded; a question |
| 56 | # by being answered or dropped; a bug by being closed; an outcome by being |
| 57 | # done or abandoned. Nothing here computes an outcome's frontier; whatever |
| 58 | # does applies this predicate. |
| 59 | BLOCKER_CLEARS_AT = { |
| 60 | "idea": {"graduated", "superseded", "discarded"}, |
| 61 | "question": {"answered", "dropped"}, |
| 62 | "bug": {"closed"}, |
| 63 | "outcome": {"done", "abandoned"}, |
| 64 | } |
| 65 | |
| 66 | |
| 67 | def blocker_cleared(node): |
| 68 | """Whether a node named in an outcome's blocked_by has stopped blocking it.""" |
| 69 | return node.get("status") in BLOCKER_CLEARS_AT.get(node.get("type"), ()) |
| 70 | |
| 71 | |
| 72 | class Findings: |
| 73 | """Every finding the run produces, in the order the files were read.""" |
| 74 | |
| 75 | def __init__(self): |
| 76 | self.items = [] |
| 77 | |
| 78 | def add(self, path, message, line=None): |
| 79 | where = f"{path}:{line}" if line else path |
| 80 | self.items.append(f"{where}: {message}") |
| 81 | |
| 82 | def raw(self, line): |
| 83 | """One line of cue's own error output, which already says where it is. |
| 84 | |
| 85 | cue states a message and then indents the source locations behind it, so an |
| 86 | indented line continues the finding above rather than counting as another. |
| 87 | """ |
| 88 | if self.items and line[:1].isspace(): |
| 89 | self.items[-1] += "\n" + line |
| 90 | else: |
| 91 | self.items.append(line) |
| 92 | |
| 93 | def __len__(self): |
| 94 | return len(self.items) |
| 95 | |
| 96 | |
| 97 | def read_directories(schema): |
| 98 | """The type -> directory table, read from the schema rather than restated.""" |
| 99 | out = subprocess.run( |
| 100 | ["cue", "export", "-e", "#Directories", schema, "--out", "json"], |
| 101 | capture_output=True, |
| 102 | text=True, |
| 103 | ) |
| 104 | if out.returncode != 0: |
| 105 | sys.exit(f"knowledge-lint: cannot read #Directories from {schema}:\n{out.stderr}") |
| 106 | return json.loads(out.stdout) |
| 107 | |
| 108 | |
| 109 | def outside_fences(lines): |
| 110 | """Yield (line number, line) for every line that is not inside a fenced code block.""" |
| 111 | fenced = False |
| 112 | for number, line in enumerate(lines, start=1): |
| 113 | if FENCE.match(line): |
| 114 | fenced = not fenced |
| 115 | elif not fenced: |
| 116 | yield number, line |
| 117 | |
| 118 | |
| 119 | def strip_code(lines): |
| 120 | """Yield (line number, prose) with fenced blocks and inline code spans removed. |
| 121 | |
| 122 | A link inside code formatting is a link being talked about, not a link — the |
| 123 | convention's own documentation writes `[[wiki-links]]` that way. |
| 124 | """ |
| 125 | for number, line in outside_fences(lines): |
| 126 | yield number, INLINE_CODE.sub(" ", line) |
| 127 | |
| 128 | |
| 129 | def anchors(path, cache): |
| 130 | """The anchors a markdown file offers: one per heading, slugged as forges slug them. |
| 131 | |
| 132 | Lowercase, drop everything that is neither word character, whitespace nor hyphen, |
| 133 | then turn each remaining space into a hyphen. A heading that repeats an earlier |
| 134 | slug gets a numeric suffix, in the order the headings appear. |
| 135 | """ |
| 136 | if path in cache: |
| 137 | return cache[path] |
| 138 | found, counts = set(), {} |
| 139 | with open(path, encoding="utf-8") as handle: |
| 140 | for _, line in outside_fences(handle.read().splitlines()): |
| 141 | heading = HEADING.match(line) |
| 142 | if not heading: |
| 143 | continue |
| 144 | title = heading.group(1).replace("`", "").lower() |
| 145 | slug = NOT_IN_SLUG.sub("", title).strip().replace(" ", "-") |
| 146 | counts[slug] = counts.get(slug, 0) + 1 |
| 147 | found.add(slug if counts[slug] == 1 else f"{slug}-{counts[slug] - 1}") |
| 148 | cache[path] = found |
| 149 | return found |
| 150 | |
| 151 | |
| 152 | def read_frontmatter(text): |
| 153 | """Return the file's frontmatter lines, or None if it opens with no --- block.""" |
| 154 | lines = text.splitlines() |
| 155 | if not lines or lines[0].rstrip() != "---": |
| 156 | return None |
| 157 | for index in range(1, len(lines)): |
| 158 | if lines[index].rstrip() == "---": |
| 159 | return lines[1:index] |
| 160 | return None |
| 161 | |
| 162 | |
| 163 | def collect_documents(tree, root, directories, findings): |
| 164 | """Find every markdown file in the graph, and say which of them are nodes. |
| 165 | |
| 166 | A file directly under the graph root is a graph document (the README), not a |
| 167 | node. A file in a type directory is a node. Anything else is markdown filed |
| 168 | somewhere the convention has no reading for, which is itself a finding. |
| 169 | """ |
| 170 | nodes, documents = [], [] |
| 171 | node_directories = set(directories.values()) |
| 172 | for current, subdirectories, filenames in os.walk(os.path.join(tree, root)): |
| 173 | subdirectories.sort() |
| 174 | for filename in sorted(filenames): |
| 175 | if not filename.endswith(".md"): |
| 176 | continue |
| 177 | path = os.path.relpath(os.path.join(current, filename), tree) |
| 178 | documents.append(path) |
| 179 | parent = os.path.dirname(path) |
| 180 | if parent == root: |
| 181 | continue |
| 182 | if os.path.relpath(parent, root) in node_directories: |
| 183 | nodes.append(path) |
| 184 | else: |
| 185 | findings.add(path, f"markdown outside {root}'s type directories") |
| 186 | return nodes, documents |
| 187 | |
| 188 | |
| 189 | def build_graph_document(tree, nodes, findings): |
| 190 | """Fold every node's frontmatter into one YAML document keyed by file path. |
| 191 | |
| 192 | One document means one `cue vet`, which means one run reports every node's |
| 193 | schema errors and names the file each belongs to. |
| 194 | """ |
| 195 | chunks = [] |
| 196 | for path in nodes: |
| 197 | with open(os.path.join(tree, path), encoding="utf-8") as handle: |
| 198 | frontmatter = read_frontmatter(handle.read()) |
| 199 | if frontmatter is None: |
| 200 | findings.add(path, "no YAML frontmatter: the file must open with a --- block") |
| 201 | continue |
| 202 | chunks.append(json.dumps(path) + ":\n") |
| 203 | chunks.extend(" " + line + "\n" if line.strip() else "\n" for line in frontmatter) |
| 204 | return "".join(chunks) |
| 205 | |
| 206 | |
| 207 | def vet_frontmatter(schema, graph_yaml, work, findings): |
| 208 | """Vet the whole graph against #Node, and return it parsed for the later checks.""" |
| 209 | if not graph_yaml.strip(): |
| 210 | # Every node failed to yield frontmatter, or there are no nodes. Either |
| 211 | # way there is nothing to vet and nothing to hand the later checks. |
| 212 | return {} |
| 213 | |
| 214 | document = os.path.join(work, "graph.yaml") |
| 215 | with open(document, "w", encoding="utf-8") as handle: |
| 216 | handle.write(graph_yaml) |
| 217 | |
| 218 | vet = subprocess.run( |
| 219 | ["cue", "vet", "-c", "-d", "#Graph", schema, document], |
| 220 | capture_output=True, |
| 221 | text=True, |
| 222 | ) |
| 223 | if vet.returncode != 0: |
| 224 | for line in vet.stderr.rstrip().splitlines(): |
| 225 | findings.raw(line) |
| 226 | |
| 227 | export = subprocess.run( |
| 228 | ["cue", "export", document, "--out", "json"], capture_output=True, text=True |
| 229 | ) |
| 230 | if export.returncode != 0: |
| 231 | # Frontmatter that is not YAML at all: vet has already said so, and |
| 232 | # there is nothing to hand the reference checks. |
| 233 | return {} |
| 234 | return json.loads(export.stdout) or {} |
| 235 | |
| 236 | |
| 237 | def check_filenames(nodes, frontmatter, directories, root, findings): |
| 238 | """A node's path must agree with its frontmatter, and its id must be its own.""" |
| 239 | seen = {} |
| 240 | for path in nodes: |
| 241 | match = NODE_FILENAME.match(os.path.basename(path)) |
| 242 | if not match: |
| 243 | findings.add(path, "filename is not <id>-<slug>.md with a lowercase slug") |
| 244 | continue |
| 245 | filename_id = match.group(1) |
| 246 | |
| 247 | declared = frontmatter.get(path, {}) |
| 248 | node_id = declared.get("id") |
| 249 | if node_id and node_id != filename_id: |
| 250 | findings.add(path, f"filename says id {filename_id}, frontmatter says {node_id}") |
| 251 | |
| 252 | if str(declared.get("created", "")) > ID_RULE_CUTOFF: |
| 253 | prefix, _, id_hash = filename_id.partition("-") |
| 254 | derived = hashlib.sha256(match.group(2).encode()).hexdigest()[:7] |
| 255 | if id_hash != derived: |
| 256 | findings.add( |
| 257 | path, |
| 258 | f"id {filename_id} is not derived from the slug: " |
| 259 | f"sha256 of the slug gives {prefix}-{derived}", |
| 260 | ) |
| 261 | |
| 262 | node_type = declared.get("type") |
| 263 | if node_type in directories: |
| 264 | expected = os.path.join(root, directories[node_type]) |
| 265 | if os.path.dirname(path) != expected: |
| 266 | findings.add(path, f"a {node_type} node belongs in {expected}/") |
| 267 | |
| 268 | if filename_id in seen: |
| 269 | findings.add(path, f"id {filename_id} is already used by {seen[filename_id]}") |
| 270 | else: |
| 271 | seen[filename_id] = path |
| 272 | |
| 273 | |
| 274 | def check_references(tree, documents, frontmatter, findings): |
| 275 | """Every [[id]], typed-edge id, and relative link must resolve inside the tree.""" |
| 276 | status = {node.get("id"): node.get("status") for node in frontmatter.values()} |
| 277 | kind = {node.get("id"): node.get("type") for node in frontmatter.values()} |
| 278 | ids = set(status) |
| 279 | ids.discard(None) |
| 280 | headings = {} |
| 281 | |
| 282 | for path, node in sorted(frontmatter.items()): |
| 283 | for blocked_by in node.get("blocked_by", []): |
| 284 | if ":" in blocked_by: |
| 285 | # Another project's node: the schema has checked its shape, |
| 286 | # and this tree cannot answer for the rest. |
| 287 | continue |
| 288 | if blocked_by not in ids: |
| 289 | findings.add(path, f"blocked_by names {blocked_by}, which is not a node") |
| 290 | # The node this one belongs to, which is always an outcome in the |
| 291 | # same graph. The schema checks the id's shape; whether it is there, |
| 292 | # and is an outcome, only the whole graph can say. |
| 293 | parent = node.get("parent") |
| 294 | if parent is not None: |
| 295 | if parent not in ids: |
| 296 | findings.add(path, f"parent names {parent}, which is not a node") |
| 297 | elif kind[parent] != "outcome": |
| 298 | findings.add(path, f"parent names {parent}, a {kind[parent]}, not an outcome") |
| 299 | # The edge and the replaced node's status state one fact twice, so |
| 300 | # they are checked together: a superseded node still reading `adopted` |
| 301 | # is exactly the contradiction the convention's resolution rule |
| 302 | # exists to settle, and it is settled here rather than by a reader. |
| 303 | for supersedes in node.get("supersedes", []): |
| 304 | if supersedes not in ids: |
| 305 | findings.add(path, f"supersedes names {supersedes}, which is not a node") |
| 306 | elif status[supersedes] != "superseded": |
| 307 | findings.add( |
| 308 | path, |
| 309 | f"supersedes names {supersedes}, whose status is " |
| 310 | f"{status[supersedes]}, not superseded", |
| 311 | ) |
| 312 | # A graduated idea's destination: an outcome or a question that must |
| 313 | # exist, or a repo-root-relative document that must be in the tree. |
| 314 | graduated_into = node.get("graduated_into") |
| 315 | if graduated_into is not None: |
| 316 | if NODE_ID.match(graduated_into): |
| 317 | if graduated_into not in ids: |
| 318 | findings.add( |
| 319 | path, f"graduated_into names {graduated_into}, which is not a node" |
| 320 | ) |
| 321 | elif kind[graduated_into] not in GRADUATION_TYPES: |
| 322 | found = kind[graduated_into] |
| 323 | article = "an" if found[:1] in "aeiou" else "a" |
| 324 | findings.add( |
| 325 | path, |
| 326 | f"graduated_into names {graduated_into}, {article} {found}, " |
| 327 | "not an outcome or a question", |
| 328 | ) |
| 329 | elif not os.path.exists(os.path.join(tree, graduated_into)): |
| 330 | findings.add( |
| 331 | path, f"graduated_into names {graduated_into}, which does not exist" |
| 332 | ) |
| 333 | |
| 334 | for path in documents: |
| 335 | with open(os.path.join(tree, path), encoding="utf-8") as handle: |
| 336 | lines = handle.read().splitlines() |
| 337 | for number, prose in strip_code(lines): |
| 338 | for target in WIKI_LINK.findall(prose): |
| 339 | if target not in ids: |
| 340 | findings.add(path, f"[[{target}]] is not a node id", line=number) |
| 341 | for target in LINK.findall(prose): |
| 342 | check_link(tree, path, target, number, headings, findings) |
| 343 | |
| 344 | |
| 345 | def check_link(tree, path, target, number, headings, findings): |
| 346 | """One markdown link: the file it names must exist, and its anchor must be there.""" |
| 347 | if EXTERNAL.match(target): |
| 348 | return |
| 349 | relative, _, anchor = target.partition("#") |
| 350 | if not relative: |
| 351 | # A link within the same file; its anchor is checked against this file. |
| 352 | resolved = path |
| 353 | else: |
| 354 | resolved = os.path.normpath(os.path.join(os.path.dirname(path), relative)) |
| 355 | if resolved.startswith(".."): |
| 356 | findings.add(path, f"{target} points outside the tree", line=number) |
| 357 | return |
| 358 | if not os.path.exists(os.path.join(tree, resolved)): |
| 359 | findings.add(path, f"{target} does not exist", line=number) |
| 360 | return |
| 361 | if anchor and resolved.endswith(".md"): |
| 362 | if anchor not in anchors(os.path.join(tree, resolved), headings): |
| 363 | findings.add(path, f"{target} names no heading in {resolved}", line=number) |
| 364 | |
| 365 | |
| 366 | def main(): |
| 367 | parser = argparse.ArgumentParser(description="Lint a tree's knowledge graph.") |
| 368 | parser.add_argument("--tree", required=True, help="the project tree to lint") |
| 369 | parser.add_argument("--root", default=".the-valley", help="the graph root inside the tree") |
| 370 | parser.add_argument("--schema", required=True, help="path to schema/node.cue") |
| 371 | parser.add_argument("--work", required=True, help="a writable directory for intermediates") |
| 372 | arguments = parser.parse_args() |
| 373 | |
| 374 | graph_root = os.path.join(arguments.tree, arguments.root) |
| 375 | if not os.path.isdir(graph_root): |
| 376 | print(f"knowledge-lint: no graph at {arguments.root}/ — nothing to check") |
| 377 | return 0 |
| 378 | |
| 379 | findings = Findings() |
| 380 | directories = read_directories(arguments.schema) |
| 381 | nodes, documents = collect_documents(arguments.tree, arguments.root, directories, findings) |
| 382 | graph_yaml = build_graph_document(arguments.tree, nodes, findings) |
| 383 | frontmatter = vet_frontmatter(arguments.schema, graph_yaml, arguments.work, findings) |
| 384 | check_filenames(nodes, frontmatter, directories, arguments.root, findings) |
| 385 | check_references(arguments.tree, documents, frontmatter, findings) |
| 386 | |
| 387 | if findings: |
| 388 | print(f"knowledge-lint: {len(findings)} findings in {arguments.root}/", file=sys.stderr) |
| 389 | for item in findings.items: |
| 390 | print(item, file=sys.stderr) |
| 391 | return 1 |
| 392 | print(f"knowledge-lint: {len(nodes)} nodes in {arguments.root}/, no findings") |
| 393 | return 0 |
| 394 | |
| 395 | |
| 396 | if __name__ == "__main__": |
| 397 | sys.exit(main()) |