Skip to content

Commit 1512b09

Browse files
MendixMauclaude
andauthored
tests(advisory): maintainer-side authoring audit — duplicate rules and routing misses (#394)
tests/advisory/authoring-audit.py (Python stdlib): `dupes` ranks cross-file near-duplicate rules by TF-IDF cosine with an allowlist; `routing` scores labelled phrasings against skill-routing.tsv trigger text by BM25 and lists misses. Advisory CI job (continue-on-error, never a gate); never ships to projects. Fixture tests/wave2/test-authoring-audit.sh; run-all.sh resolves .py subjects via the shared candidate list. Review: independent review MERGE (CI cannot turn red; nothing under bin/ or project-bin/; routing 36/55 top-1, 46/55 top-3 reproduced; dupes ~15 s; allowlist survives line drift) — fixes in 4156bec: allowlist check before the per-pair cap, specific allowlist phrases, synthetic-miss fixture probe, forward-slash paths, Context row with measured numbers. Field evidence: 2026-10-15 audit run found 14 true duplicate rules (fixed in #392/#393) and 5 never-firing triggers (#391). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VJgWP5vEoAsNsJYqCDMGNw
1 parent 78bc759 commit 1512b09

8 files changed

Lines changed: 343 additions & 2 deletions

File tree

‎.github/workflows/checks.yml‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,18 @@ jobs:
100100
run: bash tests/lint-rules/test-batch3-rules.sh
101101
- name: Lint-rule unit suite, batch 4 (tests/lint-rules/test-batch4-rules.sh)
102102
run: bash tests/lint-rules/test-batch4-rules.sh
103+
104+
# ADVISORY, never a gate (added with tests/advisory/authoring-audit.py): prints near-duplicate
105+
# rules across skills/agents/CLAUDE.md and routing top-3 hits for the labelled phrasings
106+
# (CLAUDE.md rule 8). Its own job, so it reports even when a gate above is red, and it cannot
107+
# turn the PR red: continue-on-error on job and step, `|| true` on both runs. Stdlib Python, ~15 s.
108+
authoring-audit:
109+
runs-on: ubuntu-latest
110+
continue-on-error: true
111+
steps:
112+
- uses: actions/checkout@v4
113+
- name: Authoring audit, advisory (routing, dupes)
114+
continue-on-error: true
115+
run: |
116+
python3 tests/advisory/authoring-audit.py routing || true
117+
python3 tests/advisory/authoring-audit.py dupes --top 40 || true

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Sections dated before 2026-09-19 predate the cycle and stay as they are. Named m
1919

2020
## Unreleased
2121

22+
- process(tests/advisory): **maintainer-side, advisory authoring audit: `tests/advisory/authoring-audit.py` reports near-duplicate rules and routing misses; it never ships and never gates.** `dupes` chunks `skills/`, `agents/`, `CLAUDE.md` and README "Baseline routing" into rule-sized pieces and ranks cross-file pairs by sparse TF-IDF cosine on 1–2-grams (ROUTING blocks, same-file and agent-to-agent pairs skipped, max 3 per file pair, `dupes-allow.tsv` seeded with the declared architect-agent ↔ workflow-structure-rules mirror and the pointer/tombstone/boilerplate pairs). `routing` scores BM25 over each `skill-routing.tsv` trigger against 55 labelled phrasings (`routing-phrasings.tsv`) and lists every top-3 miss; `--strict` exits 1 only for a `must_hit` row, and none is marked yet. Python 3 stdlib only. New non-blocking CI job `authoring-audit`; fixture `tests/wave2/test-authoring-audit.sh` (5 checks, floor top-3 ≥ 44/55); `run-all.sh` resolves `.py` subjects and `tests/advisory/`; CLAUDE.md rule 8 points at it. Field evidence, master 484e7ff: TF-IDF put 19 true duplicates in its top 40 (82.5% not false positives over 69 hand-judged pairs; 5-shingle Jaccard was worse); BM25 on trigger text hit top-3 46/55 (top-1 36/55), matching or beating an LSA stand-in; `dupes` 16 s over 7,031 chunks, `routing` < 0.1 s. — authoring audit, maintainer request
2223
- new(tests/behaviour): **a standing behaviour suite for agent-read text: arms M (base ref), T (candidate ref, or the base minus one skill for an ablation) and N (no pack), two drafting tasks with planted STOP-row requests and five retrieval probes, scored mechanically.** `tests/behaviour/build-packs.sh` builds a pack from any ref in a temporary worktree; `score.sh` adds `read_all` (the agent quoted the pack's `PACK-END` line back), `tool_calls` and `tokens`, and treats `mxcli check` as optional (NA without a binary). `RUNBOOK.md` has the triggers (every PR that changes baseline-routed text or an agent stub; N and ablations at each release cut), 5 reps x 2 tasks plus 5 probes x 3 reps, the rule (T no worse than M on every scored metric, probes T >= M - 1), and partial reads counted and re-run, never dropped. `docs/RELEASE-PROCESS.md` §4a names it as the way to run the Behaviour A/B. Field runs committed under `tests/behaviour/results/`: the 2026-10-15 stub-diet A/B (#369/#378/#380, 42 reps, 3 partial reads on the 4,822-line pack) and the first no-pack run (page trap refused 0/5 without a pack against 5/5 with either; mf passes check 1/5 against 5/5; every arm, N included, also inherited the host session's project CLAUDE.md (a generic mxcli/MDL guide), so N measures 'no toolkit rules', not 'no guidance'). Golden input: four real agent outputs, `tests/wave2/test-behaviour-score.sh`. — maintainer request (MendixMau)
2324
- process(pr-template, release-process): **every Direct-lane PR and every review fills a five-row Impact block: Process, Dependencies, Context cost, Behaviour, Runtime.** "none" or "NOT RUN: <reason>" is legal, a blank row is not. Context cost is pasted from `bin/render-routing.sh --check` on base and head, never estimated; a missing or estimated row is a review finding. The Behaviour A/B (`process/preflight-skill-baseline-2026-08-31.md`) is required for baseline-routed text and agent stubs, recommended for situational skills, NOT RUN with a reason for process docs review agents read, n/a for scripts only; Context cost may be "none" when no routed or always-loaded file is touched. `docs/RELEASE-PROCESS.md` §4a holds the rule and a bad/good example; `CONTRIBUTING.md`'s reviewer list points there. No CI check: `bin/check-pr-discipline.sh` reads the git diff, not the PR body. Field evidence: three PRs reviewed on 2026-10-15 with no process cost stated (#375 added a human step per re-baseline, #384 adds 1–11 s per exec), both found by chance. — maintainer request, MendixMau
2425
- chore(skills, agent stubs): **seven more duplicated rules become pointers to their single source** (CLAUDE.md: "single source of the rule; every other mention defers here"). `existing-app-assurance.md` (main.scss compiles last) and `design-artifacts.md` (tokens in `design-system.html`) point at `learned-stylegallery.md`; `testing-shape.md` §4's dormant-design-system row points at `design-artifacts.md` (which gains "it reads identically either way"); `tool-output-is-not-ground-truth.md`'s git-hash antidote points at `mpr-corruption-and-sp-load-errors.md` RULE 3; `full-harness-audit.md` §3's rung table and `harness-architecture.md` §6's rung 6/7 paragraph point at `journey-proof.md` (which gains "do not merge them into one 1–7 table"); the test-agent stub's two Trace rules point at `testing-shape.md` §4, whose Trace row gains the stub's stronger wording (handler swallowed a real failure; a page renders fine over a dead integration). The architect-agent stub's declared mirror of `workflow-structure-rules.md` §12 gets its dropped `(§N)` references back (+9 words, the only growth). Baseline 73,522 → 73,475 words (−47); test-agent stub −87 words (the no-op caveat stays inline). — authoring audit, maintainer request

‎CLAUDE.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,8 @@ Create `skills/{topic}.md` with `# Title`, `**Applies to:** migration | any mxcl
285285
produce (rule 1 makes the row a trigger condition; this rule is the check that the trigger
286286
works). The coverage audit in `render-routing.sh --check` catches the unrouted case
287287
mechanically; wrong-trigger routing it cannot see.
288+
`tests/advisory/authoring-audit.py routing` is that check (BM25 over trigger text vs the
289+
labelled `routing-phrasings.tsv`); its `dupes` lists rules stated twice. Advisory, never a gate.
288290

289291
(Rules 6–8 adapted 2026-08-31 from public skill-authoring guidance in obra/superpowers
290292
`writing-skills` and Matt Pocock's `writing-for-agents` — patterns only. Their fourth

‎tests/advisory/authoring-audit.py‎

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
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()

‎tests/advisory/dupes-allow.tsv‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# dupes-allow.tsv -- pairs `authoring-audit.py dupes` must not report.
2+
# TAB-separated: file_a glob, file_b glob (either order), match, reason.
3+
# match: case-insensitive substring of either chunk, or * for the whole file pair.
4+
# Seeded from the P (pointer/tombstone/boilerplate) labels of the 69 hand-judged pairs, master 484e7ff.
5+
agents/architect-agent.md skills/workflow-structure-rules.md * declared mirror: the stub carries the §12 checklist verbatim
6+
skills/module-completion-loop.md skills/ui-review-loop.md * tombstones: both forward to module-review.md
7+
* * generated from render-routing.sh marker comment
8+
skills/* skills/* **requires:** bash and python 3 standard skill header boilerplate
9+
skills/field-run.md skills/improvement-register.md do not group into a count pointer: field-run cites improvement-register
10+
skills/modularize-domain.md skills/module-folder-convention.md co-location is the point pointer: cites modularize-domain
11+
skills/degrade-to-judgement.md skills/finding-disposition.md harness updates itself both cite skills-over-scripts
12+
skills/degrade-to-judgement.md CLAUDE.md governing rule on where judgement lives both cite skills-over-scripts
13+
skills/brd-to-build-plan.md agents/architect-agent.md n constructs in the diagram, n rows in the plan both cite workflow-structure-rules §12 row 10
14+
skills/journey-examples.md skills/journey-proof.md after actions and landing guard, before text/trace/data both cite testing-shape §4a rule 7 as canonical

0 commit comments

Comments
 (0)