File size: 9,046 Bytes
c3a45c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# SPDX-License-Identifier: CC-BY-4.0
# Copyright (c) 2026 Martin Schröder <info@swedishembedded.com>
"""Maintenance tool of the knowledge base: lint, export a mountable copy, leakage self-audit.

  kb.py lint                                   structure, headers, links and token budgets
  kb.py export --out DIR [--max-tier N] [--mount-path /knowledge]
                                               the pages an agent sees: no README, tools or .git;
                                               sections above tier N removed
  kb.py audit SOURCE_DIR...                    compares every page with practice-instance text
                                               (requests and workspace files a student sees)

Token counts are approximated as whitespace-separated words x 1.3.
"""
import argparse
import pathlib
import re
import sys

ROOT = pathlib.Path(__file__).resolve().parent.parent
INDEX_MAX, PAGE_MIN, PAGE_MAX = 1200, 600, 1000
SECTIONS = [("## Rule", 1), ("## Procedure", 2), ("## Worked example", 3), ("## Common mistakes", 2)]
SPDX = "# SPDX-License-Identifier: CC-BY-4.0"
COPYRIGHT = "# Copyright (c) 2026 Martin Schröder <info@swedishembedded.com>"
LINK = re.compile(r"`/knowledge/([a-z0-9/-]+\.md)`")


def pages():
    """Every knowledge page: one directory level below the root; a folder's index.md is not a page."""
    return sorted(p for p in ROOT.glob("*/*.md") if p.parent.name not in ("tools", ".git") and p.name != "index.md")


def indexes():
    """The root index and one index per folder."""
    return [ROOT / "index.md"] + sorted(ROOT.glob("*/index.md"))


def tokens(text):
    return round(len(text.split()) * 1.3)


def split_sections(text):
    """Returns (head, [(tier, section text)]): head is front matter, title and introduction."""
    marks = [(m.start(), int(m.group(1))) for m in re.finditer(r"^<!-- tier: (\d) -->\n", text, re.M)]
    if not marks:
        return text, []
    out = []
    for i, (pos, tier) in enumerate(marks):
        end = marks[i + 1][0] if i + 1 < len(marks) else len(text)
        out.append((tier, text[pos:end]))
    return text[: marks[0][0]], out


def lint(_args):
    bad = []
    index = (ROOT / "index.md").read_text()
    for p in indexes():
        n = tokens(p.read_text())
        rel = p.relative_to(ROOT).as_posix()
        print(f"{n:5d} tokens  {rel} (max {INDEX_MAX})")
        if n > INDEX_MAX:
            bad.append(f"{rel}: {n} tokens > {INDEX_MAX}")
    for d in sorted({p.parent for p in pages()}):
        folder_index = d / "index.md"
        if not folder_index.exists():
            bad.append(f"{d.name}: no index.md")
            continue
        listed = set(LINK.findall(folder_index.read_text()))
        for p in pages():
            if p.parent == d and p.relative_to(ROOT).as_posix() not in listed:
                bad.append(f"{d.name}/index.md: does not list {p.name}")
    linked = set(LINK.findall(index))
    for p in indexes() + pages():
        rel = p.relative_to(ROOT).as_posix()
        text = p.read_text()
        lines = text.split("\n")
        if lines[0] != "---" or lines[1] != SPDX or lines[2] != COPYRIGHT:
            bad.append(f"{rel}: front matter must start with the SPDX and copyright lines")
        if rel != rel.lower():
            bad.append(f"{rel}: file names are lowercase")
        if not text.replace("Schröder", "Schroder").isascii():
            bad.append(f"{rel}: non-ASCII character outside the copyright name")
        for target in LINK.findall(text):
            if not (ROOT / target).exists():
                bad.append(f"{rel}: links to missing /knowledge/{target}")
        if p.name == "index.md":
            continue
        n = tokens(text)
        print(f"{n:5d} tokens  {rel}")
        if not PAGE_MIN <= n <= PAGE_MAX:
            bad.append(f"{rel}: {n} tokens outside {PAGE_MIN}-{PAGE_MAX}")
        if rel not in linked:
            bad.append(f"{rel}: not linked from index.md")
        _, sections = split_sections(text)
        got = [(s.split("\n")[1].strip(), t) for t, s in sections]
        if got != SECTIONS:
            bad.append(f"{rel}: sections must be {SECTIONS}, each after its tier marker; found {got}")
        if re.search(r"\b(cite|quote|mention|name) (the |this |a |its )?(file|path|page)\b", text, re.I):
            bad.append(f"{rel}: a page must not tell the reader to cite files or paths")
    for b in bad:
        print("LINT:", b)
    print("lint:", "FAIL" if bad else "ok", f"({len(pages())} pages)")
    return 1 if bad else 0


def export(args):
    out = pathlib.Path(args.out)
    if out.exists() and any(out.iterdir()):
        sys.exit(f"{out} is not empty")
    for p in indexes() + pages():
        head, sections = split_sections(p.read_text())
        text = head + "".join(s for t, s in sections if t <= args.max_tier)
        text = text.replace("`/knowledge/", f"`{args.mount_path.rstrip('/')}/")
        dest = out / p.relative_to(ROOT)
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_text(text)
    print(f"exported {len(pages()) + len(indexes())} files to {out} (tiers <= {args.max_tier})")
    return 0


NUMBER = re.compile(r"(?<![\w.-])\d[\d,]*(?:\.\d+)?(?![\w-])")
IDENT = re.compile(r"\b[A-Z]{1,4}-?\d{2,}\b|\b[a-z]+(?:-[a-z0-9]+){2,}-\d+\b")
DATE = re.compile(r"\b\d{4}-\d{2}-\d{2}\b")
NAME = re.compile(r"\b[A-Z][a-z]{3,}\b")
# A name inside a sentence or a data field, so the first word of a sentence is not taken for one.
MID_NAME = re.compile(r"(?<=[a-z,;] )[A-Z][a-z]{3,}\b|(?<=,)[A-Z][a-z]{3,}\b")


# Month and weekday names, and the copyright holder's nationality adjective, are not instance names.
CALENDAR = set(
    "January February March April June July August September October November December "
    "Monday Tuesday Wednesday Thursday Friday Saturday Sunday Swedish".split()
)
YEAR = re.compile(r"^(19|20)\d\d$")


def features(text):
    """What must not travel from an instance into a page: long numbers, ids, dates, sentences."""
    numbers = set()
    for m in NUMBER.findall(DATE.sub(" ", text)):
        whole = m.replace(",", "").split(".")[0]
        # A bare year is not an amount; full dates are compared separately.
        if len(whole) > 3 and not YEAR.match(m):
            numbers.add(m.replace(",", ""))
    words = re.findall(r"[A-Za-z0-9.%-]+", text.lower())
    grams = {" ".join(words[i : i + 8]) for i in range(len(words) - 7)}
    return numbers, set(IDENT.findall(text)), set(DATE.findall(text)), grams


def audit(args):
    src_text = []
    for d in args.sources:
        for p in sorted(pathlib.Path(d).rglob("*")):
            keep = p.suffix in (".md", ".csv", ".txt") or p.name == "support"
            if p.is_file() and ".git" not in p.parts and keep:
                src_text.append(p.read_text(errors="replace"))
    src = "\n".join(src_text)
    s_num, s_id, s_date, s_gram = features(src)
    # An instance name is a capitalised word the instances never write in lower case, so "Buyer",
    # "Supplier" or "Rule" are not names, while a company or counterparty name is.
    s_lower = set(re.findall(r"\b[a-z]{4,}\b", src))
    s_names = {w for w in MID_NAME.findall(src) if w.lower() not in s_lower}
    print(
        f"sources: {len(src_text)} files, {len(s_num)} long numbers, {len(s_id)} ids, {len(s_date)} dates, "
        f"{len(s_names)} names, {len(s_gram)} 8-word sequences"
    )
    hits = 0
    for p in indexes() + [ROOT / "README.md"] + pages():
        # The licence and copyright lines are not content.
        text = "\n".join(l for l in p.read_text().split("\n") if "SPDX-License" not in l and "Copyright (c)" not in l)
        rel = p.relative_to(ROOT).as_posix()
        k_num, k_id, k_date, k_gram = features(text)
        k_lower = set(re.findall(r"\b[a-z]{4,}\b", text))
        found = {
            "number": k_num & s_num,
            "id": k_id & s_id,
            "date": k_date & s_date,
            "name": {w for w in set(NAME.findall(text)) & s_names if w.lower() not in k_lower} - CALENDAR,
            "8-word sequence": k_gram & s_gram,
        }
        for kind, items in found.items():
            for item in sorted(items):
                hits += 1
                print(f"AUDIT: {rel}: {kind} shared with a practice instance: {item!r}")
    print("audit:", f"{hits} hit(s)" if hits else "clean")
    return 1 if hits else 0


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    sub.add_parser("lint").set_defaults(fn=lint)
    e = sub.add_parser("export")
    e.add_argument("--out", required=True)
    e.add_argument("--max-tier", type=int, default=3, choices=[1, 2, 3])
    e.add_argument("--mount-path", default="/knowledge")
    e.set_defaults(fn=export)
    a = sub.add_parser("audit")
    a.add_argument("sources", nargs="+")
    a.set_defaults(fn=audit)
    args = ap.parse_args()
    sys.exit(args.fn(args))


if __name__ == "__main__":
    main()