@dzhechkov/harness-core 0.3.111 → 0.3.113
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/project-skills.d.ts +111 -0
- package/dist/project-skills.d.ts.map +1 -0
- package/dist/project-skills.js +259 -0
- package/dist/project-skills.js.map +1 -0
- package/dist/rake-analyzer.d.ts +82 -0
- package/dist/rake-analyzer.d.ts.map +1 -0
- package/dist/rake-analyzer.js +249 -0
- package/dist/rake-analyzer.js.map +1 -0
- package/package.json +3 -3
- package/src/index.ts +2 -0
- package/src/project-skills.ts +281 -0
- package/src/rake-analyzer.ts +265 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MR rake analyzer (feature mr-rake-analyzer, ADR-001).
|
|
3
|
+
*
|
|
4
|
+
* Mines a project's review corpus for RECURRING mistakes ("rakes") and closes them into self-learning.
|
|
5
|
+
* The parse/normalize/detect/render functions are PURE + deterministic (sorted, no clock/random) so the
|
|
6
|
+
* same corpus yields a byte-identical report; the load/scan helpers do disk I/O with TOP-LEVEL node:fs
|
|
7
|
+
* imports (harness-core is ESM — a lazy require() is undefined at runtime; the R1 footgun).
|
|
8
|
+
*
|
|
9
|
+
* Signature is DETERMINISTIC (ADR-001 §1): a rule table of known rake classes, with an unmatched finding
|
|
10
|
+
* falling to a normalized-text bucket so novel recurrences still cluster. LLM classification is an optional
|
|
11
|
+
* amplifier, never in this core.
|
|
12
|
+
*
|
|
13
|
+
* SAFETY PROPERTY (ADR-001 §3, load-bearing): a finding whose signature appears in fewer than
|
|
14
|
+
* `thresholds.candidate` DISTINCT sources is a one-off — it is NEVER a rake and never reaches teach/critic.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { existsSync, readFileSync, readdirSync, statSync, realpathSync } from 'node:fs';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
|
|
20
|
+
export type Severity = 'blocker' | 'high' | 'medium' | 'low' | 'unknown';
|
|
21
|
+
const SEVERITY_RANK: Record<Severity, number> = { blocker: 4, high: 3, medium: 2, low: 1, unknown: 0 };
|
|
22
|
+
|
|
23
|
+
export interface Finding {
|
|
24
|
+
readonly source: string; // artifact id (e.g. features/<slug>/08_qe_report.md)
|
|
25
|
+
readonly severity: Severity;
|
|
26
|
+
readonly text: string;
|
|
27
|
+
readonly site?: string; // file:line if present
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface Rake {
|
|
31
|
+
readonly signature: string;
|
|
32
|
+
readonly label: string;
|
|
33
|
+
readonly sources: readonly string[]; // DISTINCT sources (sorted)
|
|
34
|
+
readonly count: number; // = sources.length
|
|
35
|
+
readonly severity: Severity; // max across the group
|
|
36
|
+
readonly examples: readonly Finding[]; // up to 3, sorted
|
|
37
|
+
readonly status: 'candidate' | 'confirmed';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface RakeThresholds { readonly candidate: number; readonly confirmed: number }
|
|
41
|
+
export const DEFAULT_RAKE_THRESHOLDS: RakeThresholds = { candidate: 2, confirmed: 3 };
|
|
42
|
+
|
|
43
|
+
export interface RakeReport {
|
|
44
|
+
readonly rakes: readonly Rake[];
|
|
45
|
+
readonly totalFindings: number;
|
|
46
|
+
readonly oneOffs: number; // signatures below the candidate threshold (dropped)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface RakeSignature { readonly id: string; readonly label: string; readonly patterns: readonly RegExp[] }
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Known rake classes (extensible, data-only). Seeded from the classes that actually recur in this repo's
|
|
53
|
+
* QE reports — that IS the dogfood. First match in order wins; unmatched → normalized-text bucket.
|
|
54
|
+
*/
|
|
55
|
+
export const RAKE_SIGNATURES: readonly RakeSignature[] = [
|
|
56
|
+
{ id: 'esm-require-footgun', label: 'ESM lazy require() undefined at runtime', patterns: [/require\(['"]node:/, /\besm\b.*require/i, /lazy require/i] },
|
|
57
|
+
{ id: 'untested-adr-property', label: 'ADR-named safety property left untested', patterns: [/load-bearing.*(untested|not\s+tested|no\s+test)/i, /adr.*names.*(property|test)/i, /safety property.*test/i] },
|
|
58
|
+
{ id: 'claim-check-fp', label: 'claim-check false positive / untagged count', patterns: [/claim-check.*(false positive|\bfp\b)/i, /untagged.*(count|claim)/i, /metric term/i] },
|
|
59
|
+
// "traversal" alone over-matches (AST/tree traversal); require a filesystem-scope token to CO-OCCUR
|
|
60
|
+
// (or a literal `../`) — cross-model QE caught the over-match.
|
|
61
|
+
{ id: 'path-traversal', label: 'path not constrained to the repo (traversal)', patterns: [/\.\.\//, /(?=.*travers)(?=.*(repo|root|\bpath\b|director|\/etc\/))/i, /escapes.{0,12}repo/i] },
|
|
62
|
+
{ id: 'silent-drop-or-inject', label: 'silent drop / silent injection (no report)', patterns: [/silent(ly)?\s+(drop|inject|discard|dropped)/i, /no silent (injection|caps|drop)/i] },
|
|
63
|
+
{ id: 'swallow-generic-exception', label: 'generic except/catch swallows real bugs', patterns: [/except\s+Exception/i, /catch.*swallow/i, /generic (exception|catch)/i] },
|
|
64
|
+
{ id: 'determinism-hole', label: 'non-deterministic output (unsorted/clock/random)', patterns: [/non-determinis/i, /determinism hole/i, /unsorted|not sorted/i] },
|
|
65
|
+
{ id: 'cross-model-self-qe', label: 'coder self-QE instead of cross-model', patterns: [/self-qe/i, /coder.*(review|qe).*(itself|self)/i, /cross-model/i] },
|
|
66
|
+
{ id: 'malformed-input-bypass', label: 'malformed input bypasses validation', patterns: [/array.*(pass|bypass)/i, /malformed.*(bypass|pass|manifest)/i, /typeof.*object/i] },
|
|
67
|
+
];
|
|
68
|
+
// Deep-freeze so an external caller can't inject a `/g`-flag regex whose `.test()` mutates lastIndex and
|
|
69
|
+
// makes signatureOf non-deterministic (cross-model QE). None of the patterns above use `g`/`y`.
|
|
70
|
+
for (const s of RAKE_SIGNATURES) { Object.freeze(s.patterns); Object.freeze(s); }
|
|
71
|
+
Object.freeze(RAKE_SIGNATURES);
|
|
72
|
+
|
|
73
|
+
const byStr = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
|
|
74
|
+
const uniqSorted = (xs: readonly string[]): string[] => [...new Set(xs)].sort(byStr);
|
|
75
|
+
const maxSeverity = (a: Severity, b: Severity): Severity => (SEVERITY_RANK[a] >= SEVERITY_RANK[b] ? a : b);
|
|
76
|
+
|
|
77
|
+
const STOPWORDS = new Set(['the', 'a', 'an', 'and', 'or', 'to', 'of', 'in', 'on', 'is', 'it', 'that', 'this', 'for', 'with', 'as', 'at', 'by', 'be', 'not', 'no', 'its', 'when', 'if', 'was', 'are', 'но', 'и', 'в', 'на', 'что', 'это', 'не', 'из', 'за', 'для']);
|
|
78
|
+
|
|
79
|
+
/** Normalize a finding's text to a stable clustering key: lowercase, strip sites/numbers/punct, top significant words. */
|
|
80
|
+
export function normalizeText(text: string): string {
|
|
81
|
+
const cleaned = text
|
|
82
|
+
.toLowerCase()
|
|
83
|
+
.replace(/[\w./-]+:\d+/g, ' ') // drop file:line
|
|
84
|
+
.replace(/`[^`]*`/g, ' ') // drop code literals
|
|
85
|
+
.replace(/[^a-zа-я\s]/gi, ' '); // drop digits/punct
|
|
86
|
+
const words = cleaned.split(/\s+/).filter((w) => w.length >= 4 && !STOPWORDS.has(w));
|
|
87
|
+
return uniqSorted(words).slice(0, 6).join(' ');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const SEV_MAP: Record<string, Severity> = {
|
|
91
|
+
blocker: 'blocker', critical: 'blocker', crit: 'blocker',
|
|
92
|
+
high: 'high', hi: 'high',
|
|
93
|
+
medium: 'medium', med: 'medium',
|
|
94
|
+
low: 'low', nit: 'low',
|
|
95
|
+
};
|
|
96
|
+
const toSeverity = (raw: string): Severity => SEV_MAP[raw.trim().toLowerCase()] ?? 'unknown';
|
|
97
|
+
const SITE_RE = /([\w./-]+\.(?:ts|js|tsx|jsx|py|go|md|json|yml|yaml):\d+)/;
|
|
98
|
+
|
|
99
|
+
/** The signature of a finding: first matching rule, else the normalized-text bucket. */
|
|
100
|
+
export function signatureOf(finding: Finding): { id: string; label: string } {
|
|
101
|
+
for (const s of RAKE_SIGNATURES) {
|
|
102
|
+
if (s.patterns.some((p) => p.test(finding.text))) return { id: s.id, label: s.label };
|
|
103
|
+
}
|
|
104
|
+
const key = normalizeText(finding.text);
|
|
105
|
+
if (key !== '') return { id: `text:${key}`, label: key };
|
|
106
|
+
// No significant words (code-only / very short). Key on the LITERAL text so two DIFFERENT such findings
|
|
107
|
+
// never merge into a false "unclassified ×N" rake (cross-model QE) — but two IDENTICAL ones still cluster.
|
|
108
|
+
const literal = finding.text.toLowerCase().replace(/\s+/g, ' ').trim().slice(0, 80);
|
|
109
|
+
return { id: `literal:${literal}`, label: literal === '' ? 'unclassified finding' : literal };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Parse one markdown artifact into findings. Handles (a) severity table rows `| … | High | <text> | … |`,
|
|
114
|
+
* (b) inline markers `[High]` / `**High —**` / `Sev — <text>`. Deterministic; unknown formats yield nothing.
|
|
115
|
+
*/
|
|
116
|
+
export function extractFindings(markdown: string, source: string): Finding[] {
|
|
117
|
+
const out: Finding[] = [];
|
|
118
|
+
const push = (severity: Severity, text: string): void => {
|
|
119
|
+
const t = text.replace(/\s+/g, ' ').trim();
|
|
120
|
+
if (t.length < 8) return; // too short to be a finding
|
|
121
|
+
const site = SITE_RE.exec(t)?.[1];
|
|
122
|
+
out.push(site ? { source, severity, text: t, site } : { source, severity, text: t });
|
|
123
|
+
};
|
|
124
|
+
for (const line of markdown.split('\n')) {
|
|
125
|
+
// (a) table row: | ... | <sev> | <finding> | ...
|
|
126
|
+
const cells = line.includes('|') ? line.split('|').map((c) => c.trim()) : null;
|
|
127
|
+
if (cells && cells.length >= 4) {
|
|
128
|
+
const sevCell = cells.find((c) => SEV_MAP[c.toLowerCase()] !== undefined);
|
|
129
|
+
if (sevCell) {
|
|
130
|
+
const sevIdx = cells.indexOf(sevCell);
|
|
131
|
+
const finding = cells.slice(sevIdx + 1).find((c) => c.length >= 8 && !/^-+$/.test(c));
|
|
132
|
+
if (finding) { push(toSeverity(sevCell), finding); continue; }
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
// (b) inline `[High] text` / `**High —** text` / `- High: text`. The bracketed form `[High] text`
|
|
136
|
+
// needs no separator (the brackets delimit); the bare form `High: text` requires one so prose like
|
|
137
|
+
// "high latency" doesn't register (cross-model QE: a missing separator silently dropped findings).
|
|
138
|
+
const bracketed = /^[\s\-*>]*\**\[(blocker|critical|high|medium|med|low)\]\**\s*[—:\-]?\s*(.+)$/i.exec(line);
|
|
139
|
+
const bare = /^[\s\-*>]*\**(blocker|critical|high|medium|med|low)\**\s*[—:]\s*(.+)$/i.exec(line);
|
|
140
|
+
const m = bracketed ?? bare;
|
|
141
|
+
if (m && m[1] && m[2]) push(toSeverity(m[1]), m[2]);
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Detect rakes: group findings by signature, count DISTINCT sources, keep only groups at/above the candidate
|
|
148
|
+
* threshold (a below-threshold group is a one-off, NEVER a rake — the load-bearing anti-noise property).
|
|
149
|
+
* PURE + deterministic (ADR-001 §1): rakes sorted by (count desc, severity desc, signature asc).
|
|
150
|
+
*/
|
|
151
|
+
export function detectRakes(findings: readonly Finding[], thresholds: RakeThresholds = DEFAULT_RAKE_THRESHOLDS): RakeReport {
|
|
152
|
+
const groups = new Map<string, { label: string; findings: Finding[] }>();
|
|
153
|
+
for (const f of findings) {
|
|
154
|
+
const sig = signatureOf(f);
|
|
155
|
+
const g = groups.get(sig.id);
|
|
156
|
+
if (g) g.findings.push(f);
|
|
157
|
+
else groups.set(sig.id, { label: sig.label, findings: [f] });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const rakes: Rake[] = [];
|
|
161
|
+
let oneOffs = 0;
|
|
162
|
+
for (const [signature, g] of groups) {
|
|
163
|
+
const sources = uniqSorted(g.findings.map((f) => f.source));
|
|
164
|
+
const count = sources.length;
|
|
165
|
+
if (count < thresholds.candidate) { oneOffs++; continue; }
|
|
166
|
+
const severity = g.findings.reduce<Severity>((m, f) => maxSeverity(m, f.severity), 'unknown');
|
|
167
|
+
const examples = [...g.findings]
|
|
168
|
+
.sort((a, b) => SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] || byStr(a.source, b.source))
|
|
169
|
+
.slice(0, 3);
|
|
170
|
+
rakes.push({ signature, label: g.label, sources, count, severity, examples, status: count >= thresholds.confirmed ? 'confirmed' : 'candidate' });
|
|
171
|
+
}
|
|
172
|
+
rakes.sort((a, b) => b.count - a.count || SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] || byStr(a.signature, b.signature));
|
|
173
|
+
return { rakes, totalFindings: findings.length, oneOffs };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Human render of the rake report. Deterministic. */
|
|
177
|
+
export function renderRakeReport(report: RakeReport): string {
|
|
178
|
+
if (report.rakes.length === 0) {
|
|
179
|
+
return `mr-rakes: no recurring rakes (${report.totalFindings} finding(s), ${report.oneOffs} one-off signature(s) below threshold).`;
|
|
180
|
+
}
|
|
181
|
+
const lines = [`mr-rakes: ${report.rakes.length} rake(s) from ${report.totalFindings} finding(s) (${report.oneOffs} one-off(s) dropped):`, ''];
|
|
182
|
+
for (const r of report.rakes) {
|
|
183
|
+
lines.push(` [${r.status}] ${r.severity.toUpperCase()} ×${r.count} — ${r.label} (${r.signature})`);
|
|
184
|
+
lines.push(` sources: ${r.sources.join(', ')}`);
|
|
185
|
+
}
|
|
186
|
+
return lines.join('\n');
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** The teachable rule text for a rake (fed to `dz teach`). Deterministic. */
|
|
190
|
+
export function rakeAsLesson(rake: Rake): string {
|
|
191
|
+
return `Project rake (recurred in ${rake.count} reviews): ${rake.label}. First seen: ${rake.examples[0]?.site ?? rake.sources[0]}. Watch for this class before it ships again.`;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Severity → teach reward. Higher-severity rakes are higher-signal lessons. */
|
|
195
|
+
export function rakeReward(rake: Rake): number {
|
|
196
|
+
return ({ blocker: 0.95, high: 0.9, medium: 0.8, low: 0.7, unknown: 0.7 } as const)[rake.severity];
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Render the CONFIRMED rakes as a project-critic SKILL.md section (sink B). Deterministic; confirmed only. */
|
|
200
|
+
export function renderCriticSection(report: RakeReport): string {
|
|
201
|
+
const confirmed = report.rakes.filter((r) => r.status === 'confirmed');
|
|
202
|
+
const lines = [
|
|
203
|
+
'## Recurring mistakes (auto-mined by `dz mr-rakes`)',
|
|
204
|
+
'',
|
|
205
|
+
confirmed.length === 0
|
|
206
|
+
? '_No confirmed recurring rakes yet._'
|
|
207
|
+
: 'These classes of mistake have recurred across this project\'s reviews. Flag them before they ship again:',
|
|
208
|
+
'',
|
|
209
|
+
];
|
|
210
|
+
for (const r of confirmed) {
|
|
211
|
+
lines.push(`- **${r.label}** (${r.severity}, ×${r.count}) — e.g. ${r.examples[0]?.site ?? r.sources[0]}.`);
|
|
212
|
+
}
|
|
213
|
+
return lines.join('\n');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ── Thin I/O (top-level fs; never throws) ────────────────────────────────────────────────────────────
|
|
217
|
+
|
|
218
|
+
/** Find review artifacts: each `features/<slug>/08_qe_report.md` plus any `REVIEW`-named markdown. Sorted. */
|
|
219
|
+
export function findReviewArtifacts(repoRoot: string): string[] {
|
|
220
|
+
if (typeof repoRoot !== 'string' || repoRoot === '') return []; // fail-open on bad runtime input (cross-model QE)
|
|
221
|
+
const candidates: string[] = [];
|
|
222
|
+
const featuresDir = join(repoRoot, 'features');
|
|
223
|
+
try {
|
|
224
|
+
if (existsSync(featuresDir)) {
|
|
225
|
+
for (const slug of readdirSync(featuresDir)) {
|
|
226
|
+
const qe = join(featuresDir, slug, '08_qe_report.md');
|
|
227
|
+
if (existsSync(qe)) candidates.push(`features/${slug}/08_qe_report.md`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} catch { /* ignore */ }
|
|
231
|
+
// Shallow scan of the repo root for REVIEW-named markdown (mr-review outputs land there).
|
|
232
|
+
try {
|
|
233
|
+
for (const entry of readdirSync(repoRoot)) {
|
|
234
|
+
if (/REVIEW.*\.md$/i.test(entry)) {
|
|
235
|
+
try { if (statSync(join(repoRoot, entry)).isFile()) candidates.push(entry); } catch { /* ignore */ }
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
} catch { /* ignore */ }
|
|
239
|
+
|
|
240
|
+
// Dedupe by PHYSICAL identity (realpath), not path string — two paths (e.g. a symlinked feature dir)
|
|
241
|
+
// pointing at ONE file must count as ONE source, else a single review fakes a rake (cross-model QE:
|
|
242
|
+
// the real load-bearing breach). Keep the first (sorted) relative path per physical file.
|
|
243
|
+
const seenReal = new Set<string>();
|
|
244
|
+
const out: string[] = [];
|
|
245
|
+
for (const rel of uniqSorted(candidates)) {
|
|
246
|
+
let real: string;
|
|
247
|
+
try { real = realpathSync(join(repoRoot, rel)); } catch { real = join(repoRoot, rel); }
|
|
248
|
+
if (seenReal.has(real)) continue;
|
|
249
|
+
seenReal.add(real);
|
|
250
|
+
out.push(rel);
|
|
251
|
+
}
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Analyze the whole repo corpus. Impure wrapper: find artifacts → extract → detect. Never throws. */
|
|
256
|
+
export function analyzeCorpus(repoRoot: string, thresholds: RakeThresholds = DEFAULT_RAKE_THRESHOLDS): RakeReport {
|
|
257
|
+
const findings: Finding[] = [];
|
|
258
|
+
for (const rel of findReviewArtifacts(repoRoot)) {
|
|
259
|
+
try {
|
|
260
|
+
const md = readFileSync(join(repoRoot, rel), 'utf8');
|
|
261
|
+
findings.push(...extractFindings(md, rel));
|
|
262
|
+
} catch { /* skip unreadable artifact */ }
|
|
263
|
+
}
|
|
264
|
+
return detectRakes(findings, thresholds);
|
|
265
|
+
}
|