gunk-dev/the-valley

knowledge-lint.py

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