|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""authoring-audit.py -- maintainer-side, ADVISORY authoring audit. Never ships to projects. |
| 3 | +
|
| 4 | + dupes near-duplicate rules across skills/, agents/, CLAUDE.md and README "Baseline routing" |
| 5 | + (sparse TF-IDF cosine on 1-2-grams). Each hit is a rule stated twice: pick the canonical |
| 6 | + home and make the other a pointer, or allowlist it in dupes-allow.tsv with a reason. |
| 7 | + routing BM25 over the trigger text (column 3) of bin/lib/skill-routing.tsv, scored against the |
| 8 | + labelled phrasings in routing-phrasings.tsv -- CLAUDE.md "Adding new skills", rule 8. |
| 9 | +
|
| 10 | +Python 3 standard library only. Exit 0 always, except `routing --strict` (a must_hit phrasing missed |
| 11 | +its top 3). Calibration on master 484e7ff: dupes top 40 held 19 true duplicates (82.5% not false |
| 12 | +positives, 69 hand-judged pairs); routing top-3 46/55. |
| 13 | +
|
| 14 | +Usage: authoring-audit.py dupes [--root DIR] [--top N] |
| 15 | + authoring-audit.py routing [--root DIR] [--phrasings FILE] [--strict] |
| 16 | +""" |
| 17 | +import argparse, fnmatch, glob, math, os, re, sys, time |
| 18 | +from collections import Counter, defaultdict |
| 19 | + |
| 20 | +HERE = os.path.dirname(os.path.abspath(__file__)) |
| 21 | +# sklearn's English list is not available without sklearn; this covers the high-df function words. |
| 22 | +STOP = set("""a about above after again against all also am an and any are as at be because been |
| 23 | +before being below between both but by can could did do does doing down during each else few for |
| 24 | +from further had has have having he her here hers him his how i if in into is it its itself just |
| 25 | +me more most my no nor not now of off on once only or other our ours out over own same she should |
| 26 | +so some such than that the their them then there these they this those through to too under until |
| 27 | +up very was we were what when where which while who whom why will with would you your yours""".split()) |
| 28 | + |
| 29 | +# ---------------------------------------------------------------- chunking |
| 30 | +LIST_RE = re.compile(r'^\s*([-*+]|\d+[.)])\s+') |
| 31 | +def chunks_of(lines, lo=0, hi=None): |
| 32 | + """Rule-sized chunks: one per table row, one per bullet (with its indented continuation), and |
| 33 | + paragraphs capped at ~120 words. Code fences, headings and ROUTING:BEGIN/END blocks skipped.""" |
| 34 | + out, para, pstart = [], [], None |
| 35 | + hi = len(lines) if hi is None else hi |
| 36 | + i, incode, inroute = lo, False, False |
| 37 | + def flush(): |
| 38 | + nonlocal para, pstart |
| 39 | + if para: out.append((pstart, ' '.join(para))) |
| 40 | + para, pstart = [], None |
| 41 | + while i < hi: |
| 42 | + raw = lines[i].rstrip('\n'); s = raw.strip() |
| 43 | + if 'ROUTING:BEGIN' in s: inroute = True |
| 44 | + if 'ROUTING:END' in s: inroute = False; i += 1; continue |
| 45 | + if inroute: i += 1; continue |
| 46 | + if s.startswith('```'): flush(); incode = not incode; i += 1; continue |
| 47 | + if incode: i += 1; continue |
| 48 | + if not s or s.startswith('#'): flush(); i += 1; continue |
| 49 | + if s.startswith('|'): |
| 50 | + flush() |
| 51 | + if not re.fullmatch(r'\|[\s:\-|]+\|?', s): out.append((i + 1, s)) |
| 52 | + i += 1; continue |
| 53 | + if LIST_RE.match(raw): |
| 54 | + flush(); buf, start = [s], i + 1; i += 1 |
| 55 | + while (i < hi and lines[i].strip() and lines[i].startswith(' ') |
| 56 | + and not re.match(r'^\s*([-*+]|\d+[.)]|\||#|```)', lines[i])): |
| 57 | + buf.append(lines[i].strip()); i += 1 |
| 58 | + out.append((start, ' '.join(buf))); continue |
| 59 | + if pstart is None: pstart = i + 1 |
| 60 | + para.append(s.lstrip('> ').strip()); i += 1 |
| 61 | + if len(' '.join(para).split()) > 120: flush() |
| 62 | + flush() |
| 63 | + return out |
| 64 | + |
| 65 | +def corpus(root): |
| 66 | + files = sorted(glob.glob(os.path.join(root, 'skills', '**', '*.md'), recursive=True)) |
| 67 | + files += sorted(glob.glob(os.path.join(root, 'agents', '*.md'))) + [os.path.join(root, 'CLAUDE.md')] |
| 68 | + out = [] |
| 69 | + def add(rel, lines, lo=0, hi=None): |
| 70 | + for ln, t in chunks_of(lines, lo, hi): |
| 71 | + if len(re.findall(r'\w+', t)) >= 10: out.append((rel, ln, t)) |
| 72 | + for f in files: |
| 73 | + if os.path.isfile(f): |
| 74 | + with open(f, encoding='utf-8') as fh: add(os.path.relpath(f, root).replace(os.sep, '/'), fh.readlines()) |
| 75 | + with open(os.path.join(root, 'README.md'), encoding='utf-8') as fh: L = fh.readlines() |
| 76 | + st = next((i for i, l in enumerate(L) if l.startswith('#### Baseline routing')), None) |
| 77 | + if st is not None: |
| 78 | + en = next((i for i in range(st + 1, len(L)) if re.match(r'^#{2,4} ', L[i])), len(L)) |
| 79 | + add('README.md', L, st + 1, en) |
| 80 | + return out |
| 81 | + |
| 82 | +# ---------------------------------------------------------------- dupes |
| 83 | +def tfidf(texts): |
| 84 | + """Sparse, L2-normalised TF-IDF over 1-2-grams (sublinear tf, smoothed idf). Returns dicts.""" |
| 85 | + grams = [] |
| 86 | + for t in texts: |
| 87 | + w = [x for x in re.findall(r'\b\w\w+\b', re.sub(r'[`*_|>]', ' ', t).lower()) if x not in STOP] |
| 88 | + grams.append(Counter(w + [a + ' ' + b for a, b in zip(w, w[1:])])) |
| 89 | + df = Counter(g for c in grams for g in c) |
| 90 | + n = len(texts); vecs = [] |
| 91 | + for c in grams: |
| 92 | + v = {g: (1 + math.log(tf)) * (math.log((1 + n) / (1 + df[g])) + 1) for g, tf in c.items()} |
| 93 | + norm = math.sqrt(sum(x * x for x in v.values())) or 1.0 |
| 94 | + vecs.append({g: x / norm for g, x in v.items()}) |
| 95 | + return vecs |
| 96 | + |
| 97 | +def load_allow(path): |
| 98 | + rows = [] |
| 99 | + if os.path.isfile(path): |
| 100 | + for l in open(path, encoding='utf-8'): |
| 101 | + if l.strip() and not l.startswith('#'): |
| 102 | + p = l.rstrip('\n').split('\t') |
| 103 | + if len(p) >= 3: rows.append((p[0], p[1], p[2].lower())) |
| 104 | + return rows |
| 105 | + |
| 106 | +def allowed(allow, fa, fb, ta, tb): |
| 107 | + for ga, gb, m in allow: |
| 108 | + if ((fnmatch.fnmatch(fa, ga) and fnmatch.fnmatch(fb, gb)) or |
| 109 | + (fnmatch.fnmatch(fa, gb) and fnmatch.fnmatch(fb, ga))): |
| 110 | + if m == '*' or m in ta.lower() or m in tb.lower(): return True |
| 111 | + return False |
| 112 | + |
| 113 | +def cmd_dupes(a): |
| 114 | + t0 = time.time() |
| 115 | + C = corpus(a.root); V = tfidf([t for _, _, t in C]) |
| 116 | + isag = [f.startswith('agents/') for f, _, _ in C] |
| 117 | + post = defaultdict(list) # inverted index -> sparse dot products |
| 118 | + for i, v in enumerate(V): |
| 119 | + for g, x in v.items(): post[g].append((i, x)) |
| 120 | + cand = [] |
| 121 | + for i, v in enumerate(V): |
| 122 | + acc = defaultdict(float) |
| 123 | + for g, x in v.items(): |
| 124 | + for j, y in post[g]: |
| 125 | + if j > i: acc[j] += x * y |
| 126 | + best = sorted(((s, j) for j, s in acc.items() |
| 127 | + if C[j][0] != C[i][0] and not (isag[i] and isag[j])), reverse=True)[:5] |
| 128 | + cand += [(s, i, j) for s, j in best if s > 0] |
| 129 | + cand.sort(key=lambda c: (-c[0], c[1], c[2])) |
| 130 | + allow = load_allow(os.path.join(HERE, 'dupes-allow.tsv')) |
| 131 | + per, shown, skipped = Counter(), 0, 0 |
| 132 | + print(f'dupes: {len(C)} chunks from {len({f for f, _, _ in C})} files; top {a.top} cross-file pairs ' |
| 133 | + f'(max 3 per file pair), allowlist {len(allow)} rows') |
| 134 | + for s, i, j in cand: |
| 135 | + (fa, la, ta), (fb, lb, tb) = C[i], C[j] |
| 136 | + key = tuple(sorted((fa, fb))) |
| 137 | + if allowed(allow, fa, fb, ta, tb): skipped += 1; continue # before the cap: never spends it |
| 138 | + if per[key] >= 3: continue |
| 139 | + per[key] += 1 |
| 140 | + shown += 1 |
| 141 | + print(f'{shown:3d} {s:.3f} {fa}:{la} <> {fb}:{lb}\n A: {ta[:110]}\n B: {tb[:110]}') |
| 142 | + if shown >= a.top: break |
| 143 | + print(f'dupes: {shown} shown, {skipped} allowlisted, {time.time() - t0:.1f}s') |
| 144 | + return 0 |
| 145 | + |
| 146 | +# ---------------------------------------------------------------- routing |
| 147 | +def stem(w): |
| 148 | + for s in ('ing', 'ed', 'es', 's'): |
| 149 | + if len(w) > 4 and w.endswith(s): return w[:-len(s)] |
| 150 | + return w |
| 151 | +QSTOP = set('a an the of to and or in on for is it be at by as this that with i my me we our you ' |
| 152 | + 'your its are was can do if not no'.split()) |
| 153 | +def tok(t): return [stem(w) for w in re.findall(r'[a-z0-9]+', t.lower()) if w not in QSTOP] |
| 154 | + |
| 155 | +class BM25: # Okapi, k1=1.5 b=0.75, idf floor eps*mean |
| 156 | + def __init__(self, docs, k1=1.5, b=0.75, eps=0.25): |
| 157 | + self.tf = [Counter(d) for d in docs]; self.dl = [len(d) for d in docs] |
| 158 | + self.avg = sum(self.dl) / len(docs); self.k1, self.b = k1, b |
| 159 | + df = Counter(w for d in docs for w in set(d)); n = len(docs) |
| 160 | + self.idf = {w: math.log(n - c + 0.5) - math.log(c + 0.5) for w, c in df.items()} |
| 161 | + floor = eps * sum(self.idf.values()) / len(self.idf) |
| 162 | + self.idf = {w: (x if x >= 0 else floor) for w, x in self.idf.items()} |
| 163 | + def scores(self, q): |
| 164 | + out = [] |
| 165 | + for tf, dl in zip(self.tf, self.dl): |
| 166 | + s = 0.0 |
| 167 | + for w in q: |
| 168 | + f = tf.get(w, 0) |
| 169 | + if f: s += self.idf[w] * f * (self.k1 + 1) / (f + self.k1 * (1 - self.b + self.b * dl / self.avg)) |
| 170 | + out.append(s) |
| 171 | + return out |
| 172 | + |
| 173 | +def cmd_routing(a): |
| 174 | + t0 = time.time() |
| 175 | + rows = [l.rstrip('\n').split('\t') for l in open(os.path.join(a.root, 'bin/lib/skill-routing.tsv'), encoding='utf-8') |
| 176 | + if l.strip() and not l.startswith('#')] |
| 177 | + paths = [r[1] for r in rows]; bm = BM25([tok(r[2]) for r in rows]) |
| 178 | + qs = [l.rstrip('\n').split('\t') for l in open(a.phrasings, encoding='utf-8') if l.strip() and not l.startswith('#')] |
| 179 | + top1 = top3 = 0; misses = []; strict_fail = [] |
| 180 | + for q in qs: |
| 181 | + phr, exp = q[0], q[1] |
| 182 | + ok = {exp} | {x for x in (q[2] if len(q) > 2 else '').split(',') if x and x != '-'} |
| 183 | + s = bm.scores(tok(phr)) |
| 184 | + order = [paths[i] for i in sorted(range(len(s)), key=lambda i: (-s[i], i))[:3]] |
| 185 | + rank = min([order.index(p) + 1 for p in ok if p in order], default=99) |
| 186 | + top1 += rank == 1; top3 += rank <= 3 |
| 187 | + if rank > 3: |
| 188 | + must = len(q) > 3 and q[3].strip() == 'must_hit' |
| 189 | + misses.append((phr, exp, order, must)); strict_fail += [phr] if must else [] |
| 190 | + n = len(qs) |
| 191 | + print(f'routing: {len(rows)} rows, {n} phrasings: top-1 {top1}/{n} top-3 {top3}/{n} ({time.time() - t0:.1f}s)') |
| 192 | + for phr, exp, order, must in misses: |
| 193 | + print(f' MISS{" (must_hit)" if must else ""}: "{phr}"\n want {exp}; got {", ".join(order)}') |
| 194 | + return 1 if (a.strict and strict_fail) else 0 |
| 195 | + |
| 196 | +def main(): |
| 197 | + p = argparse.ArgumentParser(description='Advisory authoring audit (maintainer-side; never ships).') |
| 198 | + p.add_argument('--root', default=os.path.abspath(os.path.join(HERE, '..', '..'))) |
| 199 | + sp = p.add_subparsers(dest='cmd', required=True) |
| 200 | + d = sp.add_parser('dupes'); d.add_argument('--top', type=int, default=40) |
| 201 | + r = sp.add_parser('routing'); r.add_argument('--strict', action='store_true') |
| 202 | + r.add_argument('--phrasings', default=os.path.join(HERE, 'routing-phrasings.tsv')) |
| 203 | + a = p.parse_args() |
| 204 | + sys.exit(cmd_dupes(a) if a.cmd == 'dupes' else cmd_routing(a)) |
| 205 | + |
| 206 | +if __name__ == '__main__': |
| 207 | + main() |
0 commit comments