gunk-dev/the-valley

knowledge-lint.py

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