File size: 14,884 Bytes
9542666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Mechanical structural-integrity checks for the vault.

The judgment-heavy work (idea merges, author-spelling merges, extraction
spot-audits) stays in the vault-audit skill; this script is the deterministic
pass it — and end_of_wave.py — run first, so nobody re-derives these checks by
hand each time. Four groups: edges (papers/ + influences/), ideas, metadata
and controlled vocabulary (every enumerated frontmatter value and
scenario/benchmark token must be in _vocab.md, the single home of those
values), and meta (the process layer — PROJECT.md, skills, agents, templates
— must match the repo: no absolute paths, no references to missing scripts or
reference files, every skill listed in PROJECT.md and linked into .claude/).

    python3 _scripts/check_integrity.py            # full report
    python3 _scripts/check_integrity.py --strict   # exit 1 if any ERROR found

Read-only. Errors are real bugs; warnings are smells to eyeball. Info lines
(to-read danglers, deliberate origin-less ideas) are counts, not problems.
"""
import glob
import os
import re
import sys

VAULT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STANCE = ("first-mention", "argues-for", "argues-against", "nuances", "tests")
COND_EDGES = ("argues-for", "argues-against", "nuances")  # must carry a (condition)
LINEAGE = ("variant-of", "refines", "combines")
PAPER_SHAPED = re.compile(r"^[a-z][a-z-]*\d{4}")  # author+year slug, e.g. rebuffi2017-icarl


def read(p):
    return open(p, encoding="utf-8").read()


def slugset(d):
    return {os.path.basename(f)[:-3] for f in glob.glob(os.path.join(VAULT, d, "*.md"))}


def strip_code(t):
    """Drop fenced blocks, inline-code spans, and HTML comments — links there are
    examples or batch-mode edges held back for the consolidator, not live edges."""
    t = re.sub(r"<!--.*?-->", "", t, flags=re.S)
    t = re.sub(r"```.*?```", "", t, flags=re.S)
    return re.sub(r"`[^`]*`", "", t)


def frontmatter(t):
    m = re.match(r"^---\n(.*?)\n---", t, re.S)
    return m.group(1) if m else ""


def fm_list(fmt, field):
    m = re.search(rf"^{field}:\s*\[(.*?)\]", fmt, re.M)
    return [x.strip().strip("\"'") for x in m.group(1).split(",") if x.strip()] if m else []


def load_vocab():
    """Parse _vocab.md: scenario table, benchmark token list, constrained-fields table."""
    v = read(os.path.join(VAULT, "_vocab.md"))

    def section(title):
        m = re.search(rf"^## {re.escape(title)}\n(.*?)(?=^## |\Z)", v, re.S | re.M)
        return m.group(1) if m else ""

    scen = set(re.findall(r"^\| `([^`]+)` \|", section("`scenario` tokens"), re.M))
    bench = {t.strip() for ln in section("`benchmarks` tokens").splitlines() if "·" in ln
             for t in ln.split("·") if t.strip()}
    fields = {}
    for kind, field, vals in re.findall(r"^\| (paper|idea|method) \| `([^`]+)` \| (.*?) \|$",
                                        section("Other constrained fields"), re.M):
        fields.setdefault(kind, {})[field] = set(re.findall(r"`([^`]+)`", vals))
    return {"scenario": scen, "benchmarks": bench, "fields": fields}


def meta_checks():
    """The process layer (PROJECT.md, skills, agents, templates) must match the repo:
    no absolute paths, every referenced script/reference file exists, every skill is
    listed in PROJECT.md and linked into .claude/. These drift silently otherwise."""
    errs = []
    skill_dirs = sorted(os.path.basename(d.rstrip("/")) for d in glob.glob(os.path.join(VAULT, "skills", "*/")))
    agent_files = sorted(os.path.basename(a) for a in glob.glob(os.path.join(VAULT, "agents", "*.md")))
    process_docs = (glob.glob(os.path.join(VAULT, "skills", "**", "*.md"), recursive=True)
                    + [os.path.join(VAULT, "agents", a) for a in agent_files])
    docs = process_docs + [os.path.join(VAULT, "PROJECT.md"), os.path.join(VAULT, "_vocab.md")] \
        + glob.glob(os.path.join(VAULT, "_templates", "*.md"))
    script_dirs = {"_scripts": os.path.join(VAULT, "_scripts"),
                   "_blog/scripts": os.path.join(VAULT, "_blog", "scripts")}
    ref_re = re.compile(r"(?:(_blog/scripts|_scripts)/)?\b((?:make|check|fetch|suggest|end)_[a-z_]+\.py|link_skills\.sh)\b")
    for f in docs:
        rel, t = os.path.relpath(f, VAULT), read(f)
        if f in process_docs:
            for m in re.finditer(r"(?<![\w.~])/(?:Users|home)/[^\s`'\")]+", t):
                errs.append(f"[meta-abs-path] {rel}: absolute path `{m.group(0)}` — use vault-relative paths")
            for m in re.finditer(r"\breferences/[\w.-]+\.md\b", t):
                if not os.path.exists(os.path.join(os.path.dirname(f), m.group(0))) and \
                        not glob.glob(os.path.join(VAULT, "skills", "*", m.group(0))):
                    errs.append(f"[meta-missing-ref] {rel}: `{m.group(0)}` does not exist")
        for m in ref_re.finditer(t):
            where = [script_dirs[m.group(1)]] if m.group(1) else list(script_dirs.values())
            if not any(os.path.exists(os.path.join(d, m.group(2))) for d in where):
                errs.append(f"[meta-missing-script] {rel}: `{m.group(0)}` does not exist")
    proj = read(os.path.join(VAULT, "PROJECT.md"))
    listed = set(re.findall(r"^- `/([a-z0-9-]+)`", proj, re.M))
    for s in skill_dirs:
        if s not in listed:
            errs.append(f"[meta-skill-unlisted] skills/{s} is not listed in PROJECT.md ## Skills")
        link = os.path.join(VAULT, ".claude", "skills", s)
        if os.path.realpath(link) != os.path.realpath(os.path.join(VAULT, "skills", s)):
            errs.append(f"[meta-skill-unlinked] .claude/skills/{s} missing or wrong — run bash _scripts/link_skills.sh")
    for s in sorted(listed - set(skill_dirs)):
        errs.append(f"[meta-skill-missing] PROJECT.md lists /{s} but skills/{s} does not exist")
    for a in agent_files:
        link = os.path.join(VAULT, ".claude", "agents", a)
        if os.path.realpath(link) != os.path.realpath(os.path.join(VAULT, "agents", a)):
            errs.append(f"[meta-agent-unlinked] .claude/agents/{a} missing or wrong — run bash _scripts/link_skills.sh")
    return errs


def main():
    strict = "--strict" in sys.argv
    ideas = slugset("ideas")
    papers = slugset("papers")
    methods = slugset("methods")
    infl = slugset("influences")
    concepts = slugset("concepts")
    authors = slugset("authors")
    notes = ideas | papers | methods | infl | concepts | authors
    paper_files = glob.glob(os.path.join(VAULT, "papers", "*.md")) + \
        glob.glob(os.path.join(VAULT, "influences", "*.md"))

    errors, warns, infos = [], [], []

    # ---- edge-level checks over papers/ + influences/ -----------------------
    fm_holders = {}  # idea -> set(papers holding first-mention)
    incoming = set()  # ideas that any stance edge points at
    for f in paper_files:
        s = os.path.basename(f)[:-3]
        body = strip_code(read(f))
        edge_lines = [ln for ln in body.splitlines()
                      if re.match(rf"^\s*({'|'.join(STANCE + ('builds-on',) + LINEAGE)})::", ln)]
        n_edges = 0
        for ln in edge_lines:
            kind = ln.strip().split("::", 1)[0]
            tgt = re.search(r"\[\[([^\]]+)\]\]", ln)
            if not tgt:
                errors.append(f"[malformed-edge] {s}: `{ln.strip()[:70]}` has no [[link]]")
                continue
            n_edges += 1
            t = tgt.group(1)
            if kind in STANCE:
                if t not in notes:
                    errors.append(f"[dangling-stance] {s}: {kind}:: [[{t}]] — no such note")
                elif t not in ideas:
                    errors.append(f"[stance-not-idea] {s}: {kind}:: [[{t}]] targets a "
                                  f"{'method' if t in methods else 'concept' if t in concepts else 'paper/author'}, not an idea")
                else:
                    if kind == "first-mention":
                        fm_holders.setdefault(t, set()).add(s)
                    incoming.add(t)
                if kind in COND_EDGES and "(" not in ln.split("]]", 1)[1]:
                    warns.append(f"[edge-no-condition] {s}: {kind}:: [[{t}]] — no (condition)")
            elif kind == "builds-on":
                if t not in notes:
                    infos.append(f"[to-read] {s} builds-on [[{t}]]")
            elif kind in LINEAGE:  # in methods/, but tolerate here
                if t not in notes and PAPER_SHAPED.match(t):
                    errors.append(f"[lineage-paper-shaped] {s}: {kind}:: [[{t}]] — paper-shaped, inflates to-read")

        if s in papers and n_edges == 0:
            warns.append(f"[zero-edge-paper] {s}: no stance/first-mention/builds-on edge "
                         f"— scope smell (influence candidate?)")

        # metadata gaps (papers only; influences are exempt from scenario/venue)
        if s in papers:
            fmt = frontmatter(read(f))
            ptype = (re.search(r"^type:\s*(.*)$", fmt, re.M) or [None, ""])
            ptype = ptype.group(1).strip().strip('"') if hasattr(ptype, "group") else ""
            # scenario is only expected of papers tied to a concrete setting;
            # surveys/position/theory/book/dataset legitimately have none.
            no_scenario_ok = ptype in ("survey", "position", "theory", "book", "dataset")
            for field in ("venue", "status", "year", "citekey", "scenario"):
                if field == "scenario" and no_scenario_ok:
                    continue
                m = re.search(rf"^{field}:\s*(.*)$", fmt, re.M)
                val = (m.group(1).strip() if m else "").strip('"[] ')
                if not val:
                    warns.append(f"[metadata-gap] {s}: empty `{field}`" + (f" (type: {ptype})" if ptype else ""))
            pdf = re.search(r"^pdf:\s*(.*)$", fmt, re.M)
            if pdf:
                rel = pdf.group(1).strip().strip('"')
                if rel and not os.path.exists(os.path.join(VAULT, rel)):
                    errors.append(f"[pdf-missing] {s}: pdf: {rel} does not exist")

    # ---- method lineage checks ---------------------------------------------
    for f in glob.glob(os.path.join(VAULT, "methods", "*.md")):
        s = os.path.basename(f)[:-3]
        body = strip_code(read(f))
        for kind in LINEAGE:
            for mm in re.finditer(rf"(?<![a-z]){kind}::\s*\[\[([^\]]+)\]\]", body):
                t = mm.group(1)
                if t not in notes and PAPER_SHAPED.match(t):
                    errors.append(f"[lineage-paper-shaped] {s}: {kind}:: [[{t}]] — paper-shaped slug")

    # ---- idea-level checks --------------------------------------------------
    for f in glob.glob(os.path.join(VAULT, "ideas", "*.md")):
        s = os.path.basename(f)[:-3]
        t = read(f)
        holders = fm_holders.get(s, set())
        if not holders:
            infos.append(f"[no-first-mention] {s}")
        elif len(holders) >= 2:
            warns.append(f"[multi-first-mention] {s}: {sorted(holders)} — legitimate only if "
                         f"the First-mention section records a concurrent/adjudicated split")
        if s not in incoming and not holders:
            warns.append(f"[orphan-idea] {s}: no paper edge points to it")
        # stale first-mention prose: names a paper that is not a current holder
        m = re.search(r"## First mention\n(.*?)(\n## |\Z)", t, re.S)
        if m and holders:
            for mm in re.finditer(r"[Ff]irst[- ]ment\w*\s+(?:in|by)\s+\[\[([^\]]+)\]\]",
                                  strip_code(m.group(1))):
                if mm.group(1) not in holders:
                    warns.append(f"[stale-fm-prose] {s}: prose credits [[{mm.group(1)}]] but "
                                 f"first-mention edge is held by {sorted(holders)}")
        # parent resolution + self-cycle
        pm = re.search(r"^parent:\s*\"?\[\[([^\]]+)\]\]", frontmatter(t), re.M)
        if pm:
            if pm.group(1) not in ideas:
                errors.append(f"[bad-parent] {s}: parent [[{pm.group(1)}]] is not an idea note")
            elif pm.group(1) == s:
                errors.append(f"[parent-cycle] {s}: is its own parent")

    # ---- orphan PDFs --------------------------------------------------------
    referenced_pdfs = set()
    for f in paper_files:
        m = re.search(r"^pdf:\s*(.*)$", frontmatter(read(f)), re.M)
        if m:
            referenced_pdfs.add(os.path.basename(m.group(1).strip().strip('"')))
    for p in glob.glob(os.path.join(VAULT, "pdf", "*.pdf")):
        if os.path.basename(p) not in referenced_pdfs:
            warns.append(f"[orphan-pdf] pdf/{os.path.basename(p)}: no paper note points to it")

    # ---- controlled vocabulary (_vocab.md is the single home of every enum) ---
    vocab = load_vocab()
    note_dirs = {"paper": ["papers", "influences"], "idea": ["ideas"], "method": ["methods"]}
    for kind, dirs in note_dirs.items():
        for d in dirs:
            for f in glob.glob(os.path.join(VAULT, d, "*.md")):
                s, fmt = os.path.basename(f)[:-3], frontmatter(read(f))
                for field, allowed in vocab["fields"].get(kind, {}).items():
                    m = re.search(rf"^{re.escape(field)}:[ \t]*([^#\n]*)", fmt, re.M)
                    val = m.group(1).strip().strip("\"'") if m else ""
                    if val and val not in allowed:
                        warns.append(f"[vocab] {s}: {field}: `{val}` not in _vocab.md")
                if kind == "paper":
                    for field in ("scenario", "benchmarks"):
                        for tok in fm_list(fmt, field):
                            if tok not in vocab[field]:
                                warns.append(f"[vocab] {s}: {field} token `{tok}` not in _vocab.md")

    # ---- meta: do the docs/skills match the repository? ---------------------
    errors.extend(meta_checks())

    # ---- report -------------------------------------------------------------
    def block(title, items, cap=None):
        print(f"\n=== {title} ({len(items)}) ===")
        for x in (items[:cap] if cap else items):
            print(f"  {x}")
        if cap and len(items) > cap:
            print(f"  ... +{len(items) - cap} more")

    print(f"integrity: {len(ideas)} ideas, {len(papers)} papers, {len(methods)} methods, "
          f"{len(infl)} influences")
    block("ERRORS — real bugs", errors)
    block("WARNINGS — smells to eyeball", warns, cap=60)
    # infos: summarize, don't spam
    from collections import Counter
    kinds = Counter(re.match(r"\[([^\]]+)\]", i).group(1) for i in infos)
    print(f"\n=== INFO (counts only) ===")
    for k, c in kinds.most_common():
        print(f"  {c}  {k}")
    print(f"\nsummary: {len(errors)} errors, {len(warns)} warnings")
    if strict and errors:
        sys.exit(1)


if __name__ == "__main__":
    main()