Repository navigation
Expand file tree
/
Copy pathcheck_glossary.py
More file actions
457 lines (419 loc) · 15.5 KB
/
Copy pathcheck_glossary.py
File metadata and controls
457 lines (419 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#!/usr/bin/env python3
"""Validate declared concept cards and their generated index without engine imports.
The glossary is the source; this checker validates structure, declared dependency
edges and local evidence references. It neither proves a claim nor promotes its
scientific status. Normal checks are read-only; index replacement is explicit.
"""
import importlib.util
import re
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from urllib.parse import unquote, urlsplit
CARDS_START = "<!-- BEGIN CONCEPT CARDS -->"
CARDS_END = "<!-- END CONCEPT CARDS -->"
INDEX_START = "<!-- BEGIN GENERATED CONCEPT INDEX -->"
INDEX_END = "<!-- END GENERATED CONCEPT INDEX -->"
FIELD_NAMES = (
"Status",
"Basis",
"Emergence",
"Definition",
"Domain",
"Premises",
"Dependencies",
"Owner",
"Evidence",
"Implementation",
"Tests",
"Limits",
)
_SINGLE_LINE = frozenset(("Status", "Basis", "Emergence", "Dependencies"))
_ENUMS = {
"Status": {"maintained", "candidate"},
"Basis": {
"primitive",
"identity",
"constitutive",
"derived",
"diagnostic",
"policy",
"auxiliary",
"hypothesis",
},
"Emergence": {"not-claimed", "conditional"},
}
_ID = r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*"
_ANCHOR = re.compile(r'<a id="(' + _ID + r')"></a>')
_FIELD = re.compile(r"^(?:- )?\*\*([^*]+):\*\*[ \t]*(.*)$")
_PLACEHOLDER = re.compile(r"\b(?:TODO|TBD|FIXME|TBC)\b", re.I)
def _require(condition: bool, message: str) -> None:
if not condition:
raise RuntimeError(message)
@dataclass(frozen=True)
class ConceptCard:
"""One immutable parsed declaration, without a scientific validity seal."""
identifier: str
title: str
group: str
fields: tuple[tuple[str, str], ...]
def field(self, name: str) -> str:
"""Return a named field from the single retained declaration."""
return dict(self.fields)[name]
@property
def dependencies(self) -> tuple[str, ...]:
"""Read declared foundational edges, not related-reading links."""
value = self.field("Dependencies")
return (
() if value == "none" else tuple(part.strip() for part in value.split(","))
)
@lru_cache(maxsize=1)
def _references():
path = Path(__file__).with_name("verify_internal_references.py")
spec = importlib.util.spec_from_file_location("glossary_reference_syntax", path)
_require(
spec is not None and spec.loader is not None, "reference checker is unavailable"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _region(document: str, start_marker: str, end_marker: str) -> tuple[int, int]:
starts, ends = [], []
offset = 0
for line, prose in _references()._markdown_lines(document):
content = line.rstrip("\r\n")
if prose and content == start_marker:
starts.append(offset + len(content))
if prose and content == end_marker:
ends.append(offset)
offset += len(line)
_require(
len(starts) == len(ends) == 1,
f"glossary requires exactly one {start_marker} region",
)
start, end = starts[0], ends[0]
_require(start < end, "glossary region markers are reversed")
return start, end
def _parse_cards(document: str) -> tuple[ConceptCard, ...]:
start, end = _region(document, CARDS_START, CARDS_END)
index_start, index_end = _region(document, INDEX_START, INDEX_END)
_require(
end <= index_start or index_end <= start,
"concept card and generated index regions must be disjoint",
)
cards = []
group = identifier = title = None
blank_after_anchor = False
pairs = []
def finish():
nonlocal identifier, title, pairs
if identifier is None:
return
_require(
title is not None,
f"concept {identifier}: anchor requires a following H3 title",
)
names = tuple(name for name, _ in pairs)
_require(
names == FIELD_NAMES,
f"concept {identifier}: fields must occur exactly once in order {FIELD_NAMES}; got {names}",
)
cards.append(
ConceptCard(
identifier,
title,
group,
tuple((name, "\n".join(lines).strip()) for name, lines in pairs),
)
)
identifier, title, pairs = None, None, []
for raw, prose in _references()._markdown_lines(document[start:end]):
line = raw.rstrip("\r\n")
if not line.strip():
if identifier is not None and title is None:
blank_after_anchor = True
if pairs:
pairs[-1][1].append("")
continue
heading = (
re.fullmatch(r"##[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*", line) if prose else None
)
anchor = _ANCHOR.fullmatch(line) if prose else None
if heading:
finish()
group = heading.group(1)
continue
if anchor:
finish()
_require(group is not None, "concept cards require an H2 group")
identifier = anchor.group(1)
blank_after_anchor = False
continue
heading = (
re.fullmatch(r"###[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*", line) if prose else None
)
if heading:
_require(
identifier is not None and title is None and blank_after_anchor,
"each concept requires an explicit ID anchor, a blank line and one H3 title",
)
title = heading.group(1)
continue
_require(
identifier is not None and title is not None,
"unexpected text outside a concept card or missing ID/title",
)
field = _FIELD.fullmatch(line) if prose else None
if field:
name, value = field.groups()
if name in _SINGLE_LINE:
_require(
bool(value.strip()),
f"concept {identifier}: {name} must have a single-line value",
)
pairs.append((name, [value]))
else:
_require(
bool(pairs),
f"concept {identifier}: content must belong to a named field",
)
pairs[-1][1].append(line.strip())
finish()
_require(bool(cards), "glossary must contain at least one concept card")
return tuple(cards)
def _meaningful(value: str, label: str) -> None:
normalized = " ".join(value.split()).strip("` .").lower()
_require(bool(normalized), f"{label}: value must be nonempty")
_require(
not _PLACEHOLDER.search(value)
and re.fullmatch(
r"(?:<[^>]*(?:reason|description|placeholder|value|text|id)[^>]*>|\[insert\b.*\])",
normalized,
)
is None
and normalized
not in {
"none",
"n/a",
"na",
"null",
"unknown",
"placeholder",
"to be determined",
"coming soon",
"…",
},
f"{label}: placeholder is not evidence or an explanation",
)
def _local_links(value: str, source: Path, root: Path, label: str):
references = _references()
prose = "".join(
text if rendered else ""
for text, rendered in references._markdown_segments(value)
)
links = []
for _, raw in references.LINK_PATTERN.findall(prose):
target = references._target(raw)
repository_target = references._repository_url(target)
if repository_target is not None:
target, base = repository_target, root
else:
_require(
not references._is_external(target),
f"{label}: requires local evidence links",
)
base = source.parent
parsed = urlsplit(target)
path = (
(base / unquote(parsed.path).replace("\\", "/")).resolve()
if parsed.path
else source
)
_require(
path.is_relative_to(root), f"{label}: link leaves the repository: {target}"
)
_require(path.is_file(), f"{label}: missing local file: {target}")
fragment = unquote(parsed.fragment)
if fragment and path.suffix.lower() == ".md":
_require(
fragment in references._anchors(path),
f"{label}: missing fragment: {target}",
)
links.append((path, fragment))
return tuple(links)
def _archived(path: Path, root: Path) -> bool:
return bool(
{"archive", "archives"}
& {part.lower() for part in path.relative_to(root).parts}
)
def _under(path: Path, root: Path, directory: str) -> bool:
return path.is_relative_to(root / directory)
def _validate_card(card: ConceptCard, source: Path, root: Path) -> None:
for name, value in card.fields:
label = f"concept {card.identifier} {name}"
_require(bool(value.strip()), f"{label}: value must be nonempty")
if name in _SINGLE_LINE:
_require("\n" not in value, f"{label}: requires a single-line value")
if name != "Dependencies":
_meaningful(value, label)
if name in _ENUMS:
_require(value in _ENUMS[name], f"{label}: unknown value {value!r}")
basis, emergence, status = (
card.field(name) for name in ("Basis", "Emergence", "Status")
)
_require(
emergence != "conditional" or basis == "derived",
f"concept {card.identifier}: conditional emergence requires derived basis",
)
_require(
basis != "hypothesis" or status == "candidate",
f"concept {card.identifier}: hypothesis requires candidate status",
)
dependencies = card.field("Dependencies")
_require(
dependencies == "none"
or re.fullmatch(_ID + r"(?:[ \t]*,[ \t]*" + _ID + r")*", dependencies)
is not None,
f"concept {card.identifier}: Dependencies must be comma-separated IDs or none",
)
_require(
len(card.dependencies) == len(set(card.dependencies)),
f"concept {card.identifier}: duplicate dependencies",
)
_require(
basis != "derived" or bool(card.dependencies),
f"concept {card.identifier}: derived concepts require at least one dependency",
)
owners = _local_links(
card.field("Owner"), source, root, f"concept {card.identifier} Owner"
)
_require(
any(
path != source.resolve()
and path.suffix.lower() == ".md"
and not _archived(path, root)
and (_under(path, root, "theory") or _under(path, root, "docs"))
for path, _ in owners
),
f"concept {card.identifier}: Owner needs a maintained theory/docs Markdown link",
)
evidence = _local_links(
card.field("Evidence"), source, root, f"concept {card.identifier} Evidence"
)
_require(
any(not _archived(path, root) for path, _ in evidence),
f"concept {card.identifier}: Evidence needs a non-archive local link",
)
if basis == "derived":
_require(
any(
fragment
and path != source.resolve()
and path.suffix.lower() == ".md"
and _under(path, root, "theory")
and not _archived(path, root)
for path, fragment in evidence
),
f"concept {card.identifier}: derived evidence requires a maintained theory derivation anchor",
)
linked = {}
for name, directory in (("Implementation", "src"), ("Tests", "tests")):
value = card.field(name)
label = f"concept {card.identifier} {name}"
if value.startswith("none:"):
_meaningful(value[len("none:") :], label + " reason")
linked[name] = False
continue
links = _local_links(value, source, root, label)
linked[name] = any(
_under(path, root, directory)
and (
(
path.suffix == ".py"
and (
path.name.startswith("test_") or path.name.endswith("_test.py")
)
)
if name == "Tests"
else path.suffix.lower() in {".py", ".pyi"}
)
for path, _ in links
)
_require(
linked[name],
f"{label}: needs a {directory}/ {'test Python' if name == 'Tests' else 'code'} file link or none: <reason>",
)
_require(
status != "maintained" or not linked["Implementation"] or linked["Tests"],
f"concept {card.identifier}: maintained implemented concepts require a test link",
)
def load_cards(root: Path) -> tuple[ConceptCard, ...]:
"""Validate card structure, status boundaries, references and dependency DAG."""
root = Path(root).resolve()
source = root / "theory" / "GLOSSARY.md"
cards = _parse_cards(source.read_text(encoding="utf-8"))
identifiers = {card.identifier for card in cards}
_require(len(identifiers) == len(cards), "glossary contains duplicate concept IDs")
_require(
len({" ".join(card.title.split()).casefold() for card in cards}) == len(cards),
"glossary contains duplicate concept titles",
)
for card in cards:
_validate_card(card, source, root)
unknown = set(card.dependencies) - identifiers
_require(
not unknown,
f"concept {card.identifier}: unknown dependencies {sorted(unknown)}",
)
pending = {card.identifier: set(card.dependencies) for card in cards}
completed = set()
while pending:
ready = {
identifier
for identifier, dependencies in pending.items()
if dependencies <= completed
}
_require(bool(ready), "concept dependency cycle: " + ", ".join(sorted(pending)))
completed.update(ready)
for identifier in ready:
del pending[identifier]
return cards
def render_concept_index(cards: tuple[ConceptCard, ...]) -> str:
"""Render the compact index in source order without changing card status."""
rows = ["| Concept | Basis | Emergence | Status |", "| --- | --- | --- | --- |"]
for card in cards:
title = (
card.title.replace("|", "|")
.replace("[", "[")
.replace("]", "]")
)
rows.append(
f"| [{title}](#{card.identifier}) | {card.field('Basis')} | {card.field('Emergence')} | {card.field('Status')} |"
)
return "\n".join(rows)
def check_glossary(root: Path) -> None:
"""Check declarations and exact generated-index text without writing files."""
root = Path(root).resolve()
cards = load_cards(root)
document = (root / "theory" / "GLOSSARY.md").read_text(encoding="utf-8")
start, end = _region(document, INDEX_START, INDEX_END)
expected = "\n\n" + render_concept_index(cards) + "\n\n"
_require(
document[start:end] == expected,
"concept index drifted; run scripts/check_documentation.py --write-generated",
)
def update_concept_index(root: Path) -> None:
"""Replace only the generated index after validating the source cards."""
root = Path(root).resolve()
cards = load_cards(root)
path = root / "theory" / "GLOSSARY.md"
document = path.read_text(encoding="utf-8")
start, end = _region(document, INDEX_START, INDEX_END)
path.write_text(
document[:start]
+ "\n\n"
+ render_concept_index(cards)
+ "\n\n"
+ document[end:],
encoding="utf-8",
)