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