@dzhechkov/harness-core 0.3.112 → 0.3.114

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.
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Per-session retro & co-learning loop (feature session-retro-colearn, ADR-001).
3
+ *
4
+ * At session end, `dz retro` mines the CURRENT session transcript for recurring PROCESS rakes, drills the
5
+ * user (socratic + checklist), and teaches/reinforces the agent — from the same mistake ("учиться вместе").
6
+ * The recurrence ledger IS the `dz teach` store (domain `retro`), so agent-recall and user-recurrence read
7
+ * ONE store (Step-0 recall: a feedback loop needs collect + rank + apply, not two write-only logs).
8
+ *
9
+ * parse/detect/render are PURE + deterministic (sorted, no clock/random); the stream/find helpers do disk
10
+ * I/O with TOP-LEVEL node:fs (harness-core is ESM — a lazy require() is undefined at runtime; the R1 footgun)
11
+ * and NEVER slurp a whole transcript (they reach ~95 MB — read + split lines, parse line-by-line).
12
+ *
13
+ * SAFETY PROPERTY (ADR-001 §3, load-bearing): a rake seen for the FIRST time (effective count < threshold)
14
+ * is taught silently but NOT drilled — no nagging on a one-off. Drills are for recurrent patterns only.
15
+ */
16
+
17
+ import { existsSync, readFileSync, readdirSync, statSync, openSync, readSync, closeSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+ import { homedir } from 'node:os';
20
+
21
+ export interface SessionEvent {
22
+ readonly kind: 'user' | 'assistant' | 'tool';
23
+ readonly text: string;
24
+ readonly tool?: string; // tool_use name (Read/Edit/Write/Bash) for a call
25
+ readonly file?: string; // file path arg for a Read/Edit/Write
26
+ readonly ok?: boolean; // for a tool RESULT: false ⇒ error/failure
27
+ }
28
+
29
+ export interface ProcessSignature {
30
+ readonly id: string;
31
+ readonly label: string;
32
+ readonly socratic: string; // the "predict first" prompt
33
+ readonly checklist: string; // the reveal
34
+ readonly skill?: string; // a shipped skill that addresses it
35
+ }
36
+
37
+ export interface ProcessHit {
38
+ readonly signature: string;
39
+ readonly label: string;
40
+ readonly withinSession: number; // occurrences in THIS session
41
+ readonly evidence: readonly string[];
42
+ }
43
+
44
+ export interface RetroItem {
45
+ readonly hit: ProcessHit;
46
+ readonly ledgerCount: number; // prior-session occurrences from the store
47
+ readonly effective: number; // ledgerCount + withinSession
48
+ readonly status: 'drill' | 'accrue';
49
+ readonly drill?: string;
50
+ }
51
+
52
+ export interface Retro {
53
+ readonly items: readonly RetroItem[];
54
+ readonly drilled: number;
55
+ readonly accrued: number;
56
+ readonly totalEvents: number;
57
+ }
58
+
59
+ export const RETRO_DOMAIN = 'retro';
60
+ export const DEFAULT_DRILL_THRESHOLD = 2;
61
+
62
+ export const PROCESS_SIGNATURES: readonly ProcessSignature[] = [
63
+ {
64
+ id: 'claimed-done-without-verify',
65
+ label: 'claimed done/fixed without running a verification',
66
+ socratic: 'Before you typed "done" — what exact command would have PROVEN it? Predict it, then check whether you actually ran it.',
67
+ checklist: 'Run the verification (test / build / repro) and READ its output BEFORE claiming done. No completion claim without fresh evidence.',
68
+ skill: 'validate',
69
+ },
70
+ {
71
+ id: 'n-fix-cycles',
72
+ label: 'multiple fix→break→fix cycles on one file (no root cause)',
73
+ socratic: 'After the 2nd failed fix — did you find the ROOT cause, or keep patching symptoms? Predict the real cause before the next change.',
74
+ checklist: 'Stop after 2 failed attempts. Revert, find the root cause (trace the bad value to its source), then ONE fix.',
75
+ skill: 'systematic-debugging',
76
+ },
77
+ {
78
+ id: 'ignored-user-correction',
79
+ label: 'the user had to correct the same point repeatedly',
80
+ socratic: 'When the user said "нет/wrong" the 2nd time — what did you keep assuming? Predict the misread before re-reading their message.',
81
+ checklist: 'On the 2nd correction, STOP and re-read the user\'s messages literally. Restate the ask back before acting.',
82
+ },
83
+ ];
84
+ for (const s of PROCESS_SIGNATURES) Object.freeze(s);
85
+ Object.freeze(PROCESS_SIGNATURES);
86
+
87
+ const byStr = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
88
+
89
+ // NB: `\b` is an ASCII word boundary — it does NOT anchor Cyrillic (the R2 cross-model-QE lesson), so the
90
+ // Russian alternatives use a leading letter-class lookbehind only (no TRAILING lookahead — it would reject
91
+ // inflected stems like "прошли/проходят/исправила"; cross-model QE caught the truncated-stem miss).
92
+ const DONE_RE = /(?<![a-zа-яё])(done|fixed|works now|passes|passing|готово|исправил\w*|работает|прошл\w*|проход\w*)/i;
93
+ const VERIFY_RE = /\b(test|tests|vitest|pytest|jest|npm test|pnpm test|npm run|tsc|typecheck|noEmit|cargo test|go test|build|repro|coverage|lint)\b/i;
94
+ // Negation immediately before a done-claim ("not done", "isn't fixed", "не готово") — suppress the accusation.
95
+ const NEG_RE = /\b(not|isn'?t|aren'?t|wasn'?t|won'?t|can'?t|couldn'?t|didn'?t|no longer)\b|(?<![a-zа-яё])(не|нет|ещё не|еще не)(?![a-zа-яё])/i;
96
+ // Explicit corrections only — dropped bare "again/wrong" (matched "thanks again" / "don't get me wrong").
97
+ const CORRECTION_RE = /(?<![a-zа-яё])(нет,|не так|неверно|не то|переделай)(?![a-zа-яё])|\b(that'?s not right|not right|that'?s wrong|incorrect|redo this|you misread)\b/i;
98
+ const WINDOW = 8;
99
+
100
+ /**
101
+ * Detect PROCESS rakes over the event stream. PURE + deterministic. Conservative (high-precision): prefer a
102
+ * miss to a false accusation (a wrong "you claimed done without testing" erodes trust worse than a miss).
103
+ * Returns ONE aggregated hit per signature that fired, `withinSession` = occurrence count.
104
+ */
105
+ export function detectProcessRakes(events: readonly SessionEvent[]): ProcessHit[] {
106
+ const counts = new Map<string, { n: number; evidence: string[] }>();
107
+ const bump = (sig: string, ev: string): void => {
108
+ const c = counts.get(sig) ?? { n: 0, evidence: [] };
109
+ c.n += 1;
110
+ if (c.evidence.length < 3) c.evidence.push(ev.replace(/\s+/g, ' ').trim().slice(0, 120));
111
+ counts.set(sig, c);
112
+ };
113
+
114
+ // NB: no `didnt-read-before-edit` signature — the harness ENFORCES read-before-edit (an Edit fails
115
+ // without a prior Read), so a genuine violation is near-impossible; that signal was pure artifact
116
+ // (cross-session / bounded-window reads, 88 false hits on the dogfood) and was dropped after cross-model QE.
117
+ const editsPerFile = new Map<string, number>();
118
+ const failedAfterEdit = new Set<string>(); // files that had a TEST failure after being edited
119
+ let lastEditedFile: string | undefined;
120
+ const TESTFAIL_RE = /\b(fail(ed|ing|s)?|assertion|assert|expected|not ok|panic|traceback|error ts\d|\d+ failed)\b/i;
121
+
122
+ for (let i = 0; i < events.length; i++) {
123
+ const e = events[i]!;
124
+
125
+ if (e.kind === 'tool' && e.tool === 'Edit' && e.file) {
126
+ editsPerFile.set(e.file, (editsPerFile.get(e.file) ?? 0) + 1);
127
+ lastEditedFile = e.file;
128
+ const edits = editsPerFile.get(e.file)!;
129
+ if (edits >= 3 && failedAfterEdit.has(e.file)) { bump('n-fix-cycles', `${edits} edits to ${e.file} with a failing test between`); failedAfterEdit.delete(e.file); }
130
+ }
131
+
132
+ // Only a TEST/BUILD failure (not a generic Read error) arms the most-recently-edited file, so an
133
+ // UNRELATED failure no longer globally triggers a fix-cycle (cross-model QE High).
134
+ if (e.kind === 'tool' && e.ok === false && lastEditedFile !== undefined && TESTFAIL_RE.test(e.text)) failedAfterEdit.add(lastEditedFile);
135
+
136
+ // claimed-done-without-verify: a done-claim that (a) FOLLOWS a code change in the window AND (b) has NO
137
+ // verification tool in the window. The change-in-window gate cuts prose "done"/"tests pass" that made
138
+ // no edit (measured over-firing on the dogfood — NFR-2 conservative).
139
+ if (e.kind === 'assistant') {
140
+ const m = DONE_RE.exec(e.text);
141
+ if (m) {
142
+ const before = e.text.slice(Math.max(0, m.index - 30), m.index);
143
+ const negated = NEG_RE.test(before) || NEG_RE.test(e.text.slice(m.index, m.index + 6));
144
+ if (!negated) {
145
+ let verified = false, changed = false;
146
+ for (let j = Math.max(0, i - WINDOW); j < i; j++) {
147
+ const p = events[j]!;
148
+ if (p.kind !== 'tool') continue;
149
+ if (VERIFY_RE.test(`${p.tool ?? ''} ${p.text}`)) verified = true;
150
+ if (p.tool === 'Edit' || p.tool === 'Write') changed = true;
151
+ }
152
+ if (changed && !verified) bump('claimed-done-without-verify', e.text.slice(0, 120));
153
+ }
154
+ }
155
+ }
156
+
157
+ // ignored-user-correction: 2nd+ correction within a short window of user turns.
158
+ if (e.kind === 'user' && CORRECTION_RE.test(e.text)) {
159
+ let priorCorrections = 0;
160
+ for (let j = Math.max(0, i - WINDOW * 2); j < i; j++) {
161
+ const p = events[j]!;
162
+ if (p.kind === 'user' && CORRECTION_RE.test(p.text)) priorCorrections++;
163
+ }
164
+ if (priorCorrections >= 1) bump('ignored-user-correction', e.text);
165
+ }
166
+ }
167
+
168
+ const hits: ProcessHit[] = [];
169
+ for (const sig of PROCESS_SIGNATURES) {
170
+ const c = counts.get(sig.id);
171
+ if (c) hits.push({ signature: sig.id, label: sig.label, withinSession: c.n, evidence: c.evidence });
172
+ }
173
+ return hits.sort((a, b) => b.withinSession - a.withinSession || byStr(a.signature, b.signature));
174
+ }
175
+
176
+ const sigById = (id: string): ProcessSignature | undefined => PROCESS_SIGNATURES.find((s) => s.id === id);
177
+
178
+ /** The stable store-key lesson for a signature (so teach/reinforce dedups on it and the ledger counts it). */
179
+ export function retroLessonText(sig: string): string {
180
+ const s = sigById(sig);
181
+ return `Process rake [${sig}]: ${s ? s.label : sig}. ${s?.checklist ?? ''}`.trim();
182
+ }
183
+
184
+ /** Render the mix drill: a socratic predict-then-reveal prompt, a marker, then the concrete checklist. */
185
+ export function renderDrill(sig: ProcessSignature, effective: number): string {
186
+ const skill = sig.skill ? ` (see the \`${sig.skill}\` skill)` : '';
187
+ return [
188
+ ` 🔁 ${sig.label} — ${effective}× (recurring)`,
189
+ ` ${sig.socratic}`,
190
+ ` --- reveal (cover this, predict first) ---`,
191
+ ` ✅ ${sig.checklist}${skill}`,
192
+ ].join('\n');
193
+ }
194
+
195
+ /**
196
+ * Build the retro. PURE. A hit is DRILLED only when `ledgerCount + withinSession >= threshold` (recurrent);
197
+ * otherwise it ACCRUES (taught silently, no drill) — the load-bearing anti-noise property (ADR-001 §3).
198
+ */
199
+ export function buildRetro(
200
+ hits: readonly ProcessHit[],
201
+ ledger: ReadonlyMap<string, number>,
202
+ totalEvents: number,
203
+ drillThreshold: number = DEFAULT_DRILL_THRESHOLD,
204
+ ): Retro {
205
+ const items: RetroItem[] = hits.map((hit) => {
206
+ const ledgerCount = ledger.get(hit.signature) ?? 0;
207
+ const effective = ledgerCount + hit.withinSession;
208
+ if (effective >= drillThreshold) {
209
+ const sig = sigById(hit.signature);
210
+ const drill = sig ? renderDrill(sig, effective) : undefined;
211
+ return drill !== undefined
212
+ ? { hit, ledgerCount, effective, status: 'drill' as const, drill }
213
+ : { hit, ledgerCount, effective, status: 'drill' as const };
214
+ }
215
+ return { hit, ledgerCount, effective, status: 'accrue' as const };
216
+ });
217
+ return {
218
+ items,
219
+ drilled: items.filter((i) => i.status === 'drill').length,
220
+ accrued: items.filter((i) => i.status === 'accrue').length,
221
+ totalEvents,
222
+ };
223
+ }
224
+
225
+ /** Human render of the retro. Deterministic. */
226
+ export function renderRetro(retro: Retro): string {
227
+ if (retro.items.length === 0) return `retro: no process rakes detected in ${retro.totalEvents} event(s). Clean session.`;
228
+ const lines = [`retro: ${retro.drilled} recurring rake(s) to drill, ${retro.accrued} accruing (from ${retro.totalEvents} events):`, ''];
229
+ for (const it of retro.items) {
230
+ if (it.status === 'drill' && it.drill) { lines.push(it.drill); lines.push(''); }
231
+ }
232
+ const accruing = retro.items.filter((i) => i.status === 'accrue');
233
+ if (accruing.length > 0) {
234
+ lines.push(' accruing (first time — taught, not drilled yet):');
235
+ for (const it of accruing) lines.push(` · ${it.hit.label} (×${it.hit.withinSession} this session)`);
236
+ }
237
+ return lines.join('\n');
238
+ }
239
+
240
+ // ── Streaming I/O (top-level fs; never throws; NEVER slurps into structured memory beyond the line split) ──
241
+
242
+ interface RawContentBlock { type?: string; text?: string; name?: string; input?: { file_path?: string; path?: string; command?: string }; content?: unknown; is_error?: boolean }
243
+ interface RawLine { type?: string; message?: { role?: string; content?: RawContentBlock[] | string } }
244
+
245
+ /** Cap the read at the last N bytes for very large transcripts (a retro is about the RECENT session), so
246
+ * memory stays bounded rather than slurping a multi-hundred-MB file whole (cross-model QE). */
247
+ const MAX_READ_BYTES = 48 * 1024 * 1024;
248
+
249
+ function readBounded(path: string): string {
250
+ let size = 0;
251
+ try { size = statSync(path).size; } catch { return ''; }
252
+ if (size <= MAX_READ_BYTES) {
253
+ try { return readFileSync(path, 'utf8'); } catch { return ''; }
254
+ }
255
+ // Read only the tail; drop the first (partial) line.
256
+ const fd = openSync(path, 'r');
257
+ try {
258
+ const buf = Buffer.allocUnsafe(MAX_READ_BYTES);
259
+ const bytes = readSync(fd, buf, 0, MAX_READ_BYTES, size - MAX_READ_BYTES);
260
+ const tail = buf.toString('utf8', 0, bytes);
261
+ const nl = tail.indexOf('\n');
262
+ return nl >= 0 ? tail.slice(nl + 1) : tail;
263
+ } catch { return ''; } finally { closeSync(fd); }
264
+ }
265
+
266
+ const isObj = (x: unknown): x is Record<string, unknown> => x !== null && typeof x === 'object';
267
+
268
+ /**
269
+ * Parse a Claude Code JSONL transcript into a normalized event stream. Bad/`null`/malformed lines are
270
+ * skipped (never throws — cross-model QE caught a crash on a `null` line and a `[null]` content block).
271
+ * Text blocks WITHIN one message are merged into a SINGLE assistant/user event, so a multi-block turn
272
+ * ("Done." + "Fixed.") counts as ONE claim, not two (else the anti-noise guarantee is defeated).
273
+ */
274
+ export function streamSessionEvents(path: string): SessionEvent[] {
275
+ const out: SessionEvent[] = [];
276
+ const raw = readBounded(path);
277
+ if (raw === '') return out;
278
+ for (const line of raw.split('\n')) {
279
+ const t = line.trim();
280
+ if (t === '') continue;
281
+ let obj: unknown;
282
+ try { obj = JSON.parse(t); } catch { continue; }
283
+ if (!isObj(obj)) continue;
284
+ const msg = (obj as RawLine).message;
285
+ if (!isObj(msg)) continue;
286
+ const role = typeof msg.role === 'string' ? msg.role : '';
287
+ const content = (msg as { content?: RawContentBlock[] | string }).content;
288
+ if (typeof content === 'string') {
289
+ if (content.trim() !== '') out.push({ kind: role === 'assistant' ? 'assistant' : 'user', text: content });
290
+ continue;
291
+ }
292
+ if (!Array.isArray(content)) continue;
293
+ const textParts: string[] = [];
294
+ for (const b of content) {
295
+ if (!isObj(b)) continue; // guard a `[null]` block (cross-model QE)
296
+ if (b.type === 'text' && typeof b.text === 'string') {
297
+ textParts.push(b.text);
298
+ } else if (b.type === 'tool_use') {
299
+ const input = isObj(b.input) ? (b.input as { file_path?: string; path?: string; command?: string }) : undefined;
300
+ const file = input?.file_path ?? input?.path;
301
+ const name = typeof b.name === 'string' ? b.name : undefined;
302
+ // Capture the Bash COMMAND as the event text so a real verification (`pnpm tsc`, `npm test`) is
303
+ // visible — dropping it made the "done without verify" check blind (cross-model QE).
304
+ const text = (name === 'Bash' && typeof input?.command === 'string') ? input.command : (name ?? '');
305
+ out.push({ kind: 'tool', text, ...(name ? { tool: name } : {}), ...(file ? { file } : {}) });
306
+ } else if (b.type === 'tool_result') {
307
+ const c = b.content;
308
+ const text = typeof c === 'string' ? c : JSON.stringify(c ?? '');
309
+ out.push({ kind: 'tool', text: text.slice(0, 2000), ok: b.is_error !== true });
310
+ }
311
+ }
312
+ if (textParts.length > 0) out.push({ kind: role === 'assistant' ? 'assistant' : 'user', text: textParts.join('\n') });
313
+ }
314
+ return out;
315
+ }
316
+
317
+ /** Find the most recently modified session transcript (roam state, then ~/.claude/projects). Null if none. */
318
+ export function findLatestTranscript(repoRoot: string): string | null {
319
+ let best: { path: string; mtime: number } | null = null;
320
+ const consider = (p: string): void => {
321
+ try {
322
+ const st = statSync(p);
323
+ // tie-break on path so equal mtimes are deterministic (cross-model QE).
324
+ if (st.isFile() && (best === null || st.mtimeMs > best.mtime || (st.mtimeMs === best.mtime && p < best.path))) best = { path: p, mtime: st.mtimeMs };
325
+ } catch { /* skip */ }
326
+ };
327
+ const scanDir = (dir: string): void => {
328
+ try { if (existsSync(dir)) for (const e of readdirSync(dir)) if (e.endsWith('.jsonl')) consider(join(dir, e)); } catch { /* ignore */ }
329
+ };
330
+ scanDir(join(repoRoot, 'roam', 'claude-state'));
331
+ // ~/.claude/projects/<encoded-repoRoot>/<uuid>.jsonl (the contract's second source).
332
+ try {
333
+ const enc = repoRoot.replace(/\//g, '-');
334
+ scanDir(join(homedir(), '.claude', 'projects', enc));
335
+ } catch { /* ignore */ }
336
+ return best === null ? null : (best as { path: string }).path;
337
+ }