gunk-dev/the-valley

knowledge-lint.py

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