@nemus-cli/nemus 0.3.1 → 0.3.3

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,126 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { normalizeErrorSignature, analyzeCorpus, buildAnalysisPrompt } from './reflect-analyze';
3
+ import { ReflectionCorpus, isCorrectionPrompt } from './reflect';
4
+
5
+ describe('normalizeErrorSignature', () => {
6
+ it('collapses paths, numbers, and hashes so variants cluster', () => {
7
+ const a = normalizeErrorSignature('fatal: not a git repository (or any parent up to /Users/alice/work/repo)');
8
+ const b = normalizeErrorSignature('fatal: not a git repository (or any parent up to /home/bob/src/thing)');
9
+ expect(a).toBe(b);
10
+ expect(a).toContain('<path>');
11
+
12
+ expect(normalizeErrorSignature('exit code 137 after 4200ms')).toBe(
13
+ normalizeErrorSignature('exit code 2 after 9ms'),
14
+ );
15
+ expect(normalizeErrorSignature('object abc1234def not found')).toBe(
16
+ normalizeErrorSignature('object 0f9e8d7c6b not found'),
17
+ );
18
+ });
19
+
20
+ it('is bounded and safe on empty input', () => {
21
+ expect(normalizeErrorSignature('')).toBe('');
22
+ expect(normalizeErrorSignature('x'.repeat(500)).length).toBeLessThanOrEqual(100);
23
+ });
24
+ });
25
+
26
+ describe('isCorrectionPrompt', () => {
27
+ it('flags corrections, not normal instructions', () => {
28
+ expect(isCorrectionPrompt('no, that is wrong — revert it')).toBe(true);
29
+ expect(isCorrectionPrompt('actually use the other repo instead')).toBe(true);
30
+ expect(isCorrectionPrompt('you forgot to run the tests')).toBe(true);
31
+ expect(isCorrectionPrompt('add a health check to the api')).toBe(false);
32
+ expect(isCorrectionPrompt('create a workspace for payments')).toBe(false);
33
+ });
34
+ });
35
+
36
+ const corpus: ReflectionCorpus = {
37
+ generatedAt: 'now',
38
+ availableSkills: ['redash'],
39
+ workspaces: [
40
+ {
41
+ name: 'pay-app',
42
+ repoCount: 1,
43
+ repos: ['api'],
44
+ contextFiles: ['AGENTS.md'],
45
+ contextQuality: 'substantive',
46
+ session: {
47
+ sessionId: 's1',
48
+ agentType: 'pi',
49
+ turns: 40,
50
+ userPrompts: ['fix the sync bug', 'no that is wrong, revert'],
51
+ reSteerSamples: ['no that is wrong, revert'],
52
+ errors: [
53
+ 'fatal: not a git repository (at /Users/a/pay-app/api)',
54
+ 'fatal: not a git repository (at /Users/a/pay-app/web)',
55
+ 'gh: Not Found (HTTP 404)',
56
+ ],
57
+ tools: ['bash', 'edit'],
58
+ },
59
+ },
60
+ {
61
+ name: 'ledger',
62
+ repoCount: 0,
63
+ repos: [],
64
+ contextFiles: [], // missing context
65
+ contextQuality: 'missing',
66
+ session: {
67
+ sessionId: 's2',
68
+ agentType: 'pi',
69
+ turns: 12,
70
+ userPrompts: ['add tests'],
71
+ reSteerSamples: [],
72
+ errors: ['fatal: not a git repository (at /home/b/ledger)'],
73
+ tools: ['bash'],
74
+ },
75
+ },
76
+ { name: 'idle-ws', repoCount: 0, repos: [], contextFiles: ['CLAUDE.md'], contextQuality: 'boilerplate', session: null },
77
+ ],
78
+ };
79
+
80
+ describe('analyzeCorpus', () => {
81
+ const a = analyzeCorpus(corpus);
82
+
83
+ it('aggregates totals and correction signals', () => {
84
+ expect(a.totalWorkspaces).toBe(3);
85
+ expect(a.sessionsAnalyzed).toBe(2); // idle-ws has no session
86
+ expect(a.totalTurns).toBe(52);
87
+ expect(a.correctionSignals).toBe(1); // "no that is wrong, revert"
88
+ });
89
+
90
+ it('clusters the recurring failure across workspaces, most frequent first', () => {
91
+ const top = a.topErrors[0];
92
+ expect(top.signature).toContain('not a git repository');
93
+ expect(top.count).toBe(3); // 2 in pay-app + 1 in ledger
94
+ expect(top.workspaces.sort()).toEqual(['ledger', 'pay-app']);
95
+ expect(top.example).toContain('fatal: not a git repository');
96
+ });
97
+
98
+ it('reports tools, context quality, re-steers, and per-workspace facts', () => {
99
+ expect(a.topTools[0]).toEqual({ tool: 'bash', sessions: 2 });
100
+ expect(a.workspacesMissingContext).toEqual(['ledger']);
101
+ expect(a.workspacesBoilerplateContext).toEqual(['idle-ws']);
102
+ expect(a.reSteerSamples).toEqual(['no that is wrong, revert']);
103
+ const pay = a.workspaces.find((w) => w.name === 'pay-app')!;
104
+ expect(pay).toMatchObject({ turns: 40, failures: 3, contextQuality: 'substantive' });
105
+ expect(pay.topFailure).toContain('not a git repository');
106
+ expect(a.workspaces.find((w) => w.name === 'idle-ws')).toMatchObject({ turns: 0, failures: 0, contextQuality: 'boilerplate' });
107
+ });
108
+ });
109
+
110
+ describe('buildAnalysisPrompt', () => {
111
+ it('is compact and fact-based (no raw transcripts)', () => {
112
+ const p = buildAnalysisPrompt(analyzeCorpus(corpus));
113
+ expect(p).toContain('A script has already analyzed');
114
+ expect(p).toContain('Sessions analyzed: 2 across 3 workspaces (52 total turns).');
115
+ expect(p).toContain('Top recurring failures');
116
+ expect(p).toMatch(/\[3\u00d7 in 2 ws\]/); // the clustered failure
117
+ expect(p).toContain('NO context file (AGENTS.md/CLAUDE.md): ledger');
118
+ expect(p).toContain('boilerplate/template: idle-ws');
119
+ expect(p).toContain('Verbatim user corrections');
120
+ expect(p).toContain('no that is wrong, revert');
121
+ expect(p).toContain('bash(2)');
122
+ expect(p).toMatch(/ONLY a JSON object/);
123
+ // Compact: even this corpus stays well under a few KB.
124
+ expect(p.length).toBeLessThan(3000);
125
+ });
126
+ });
@@ -0,0 +1,246 @@
1
+ import { ReflectionCorpus, ContextQuality, isCorrectionPrompt } from './reflect';
2
+
3
+ /**
4
+ * Deterministic analysis layer for `reflect`.
5
+ *
6
+ * The LLM used to read raw transcripts (every prompt + every error) for every
7
+ * workspace, which made the judge prompt large and slow (timeouts on local
8
+ * models). Instead, a *script* does the heavy lifting here — clustering repeated
9
+ * failures, counting tools, spotting correction/retry loops — and the LLM only
10
+ * ever sees a small, pre-computed set of FACTS. That keeps the judge call fast
11
+ * and bounded no matter how many workspaces are analyzed, and grounds every
12
+ * recommendation in real counts rather than a wall of text.
13
+ *
14
+ * Everything here is pure (corpus in → report out) so it's exhaustively
15
+ * unit-tested without spawning an agent.
16
+ */
17
+
18
+ // ------------------------------------------------------------------ types
19
+
20
+ export interface ErrorCluster {
21
+ /** Normalized signature (paths/numbers/hashes stripped) used to group. */
22
+ signature: string;
23
+ /** Total occurrences across all analyzed sessions. */
24
+ count: number;
25
+ /** Distinct workspaces the signature appeared in (recurrence = strong signal). */
26
+ workspaces: string[];
27
+ /** One representative raw example (bounded). */
28
+ example: string;
29
+ }
30
+
31
+ export interface ToolStat {
32
+ tool: string;
33
+ /** Number of sessions that used the tool (not raw invocation count — the
34
+ * digest only records distinct tools per session). */
35
+ sessions: number;
36
+ }
37
+
38
+ export interface WorkspaceFact {
39
+ name: string;
40
+ turns: number;
41
+ failures: number;
42
+ /** Whether the primary context file is missing / boilerplate / substantive. */
43
+ contextQuality: ContextQuality;
44
+ /** The workspace's single most frequent failure signature, if any. */
45
+ topFailure?: string;
46
+ }
47
+
48
+ export interface AnalysisReport {
49
+ totalWorkspaces: number;
50
+ sessionsAnalyzed: number;
51
+ totalTurns: number;
52
+ /** Recurring failures, most frequent first. */
53
+ topErrors: ErrorCluster[];
54
+ /** Most-used tools, most sessions first. */
55
+ topTools: ToolStat[];
56
+ /** How many user prompts looked like corrections/retries (a friction signal). */
57
+ correctionSignals: number;
58
+ /** Verbatim user re-steer messages across sessions (the sharpest coaching
59
+ * signal), most-recent-workspace first, bounded. */
60
+ reSteerSamples: string[];
61
+ /** Workspaces with NO context file at all. */
62
+ workspacesMissingContext: string[];
63
+ /** Workspaces whose context file exists but is just boilerplate/template. */
64
+ workspacesBoilerplateContext: string[];
65
+ /** Skills already installed (so the judge suggests genuine gaps). */
66
+ availableSkills: string[];
67
+ /** One compact line of facts per workspace, for grounding. */
68
+ workspaces: WorkspaceFact[];
69
+ }
70
+
71
+ // --------------------------------------------------------------- normalizing
72
+
73
+ /**
74
+ * Reduce a raw error string to a stable signature so near-identical failures
75
+ * cluster together: lowercase, drop quotes, replace filesystem paths, hashes,
76
+ * hex ids and bare numbers with placeholders, collapse whitespace, and cap the
77
+ * length. `"fatal: not a git repository (or any of the parent up to /Users/x)"`
78
+ * and the same from another path collapse to one signature.
79
+ */
80
+ export function normalizeErrorSignature(raw: string): string {
81
+ let s = (raw ?? '').toLowerCase();
82
+ s = s.replace(/[`'"]/g, ' ');
83
+ // Windows paths first (contain ':' and '\'), then unix paths.
84
+ s = s.replace(/[a-z]:\\[^\s]+/g, '<path>');
85
+ s = s.replace(/\/[^\s:)'"]+/g, '<path>');
86
+ // Long hex / uuids / sha-like tokens before bare numbers.
87
+ s = s.replace(/\b[0-9a-f]{7,}\b/g, '<hash>');
88
+ // No trailing \b, so a number glued to a unit ('4200ms', '9ms') still clusters.
89
+ s = s.replace(/\b\d[\d.,:]*/g, '<n>');
90
+ s = s.replace(/\s+/g, ' ').trim();
91
+ return s.slice(0, 100);
92
+ }
93
+
94
+ // ------------------------------------------------------------------ analyze
95
+
96
+ export interface AnalyzeOptions {
97
+ /** Max error clusters to surface (default 8). */
98
+ topErrors?: number;
99
+ /** Max tools to surface (default 10). */
100
+ topTools?: number;
101
+ /** Max chars of a raw error kept as the example (default 160). */
102
+ exampleChars?: number;
103
+ /** Max verbatim re-steer samples to surface to the judge (default 8). */
104
+ maxReSteer?: number;
105
+ }
106
+
107
+ /**
108
+ * Turn a distilled corpus into aggregated facts. This is the "script processes
109
+ * the data" step — the LLM never sees the raw corpus, only the returned report.
110
+ */
111
+ export function analyzeCorpus(corpus: ReflectionCorpus, opts: AnalyzeOptions = {}): AnalysisReport {
112
+ const topErrorsK = opts.topErrors ?? 8;
113
+ const topToolsK = opts.topTools ?? 10;
114
+ const exampleChars = opts.exampleChars ?? 160;
115
+ const maxReSteer = opts.maxReSteer ?? 8;
116
+
117
+ const errorMap = new Map<string, { count: number; ws: Set<string>; example: string }>();
118
+ const toolMap = new Map<string, number>();
119
+ const workspacesMissingContext: string[] = [];
120
+ const workspacesBoilerplateContext: string[] = [];
121
+ const reSteerSamples: string[] = [];
122
+ const workspaces: WorkspaceFact[] = [];
123
+ let sessionsAnalyzed = 0;
124
+ let totalTurns = 0;
125
+ let correctionSignals = 0;
126
+
127
+ for (const ws of corpus.workspaces) {
128
+ if (ws.contextQuality === 'missing') workspacesMissingContext.push(ws.name);
129
+ else if (ws.contextQuality === 'boilerplate') workspacesBoilerplateContext.push(ws.name);
130
+
131
+ const s = ws.session;
132
+ if (!s) {
133
+ workspaces.push({ name: ws.name, turns: 0, failures: 0, contextQuality: ws.contextQuality });
134
+ continue;
135
+ }
136
+
137
+ sessionsAnalyzed++;
138
+ totalTurns += s.turns;
139
+ for (const t of s.tools) toolMap.set(t, (toolMap.get(t) ?? 0) + 1);
140
+ correctionSignals += s.userPrompts.filter(isCorrectionPrompt).length;
141
+ for (const q of s.reSteerSamples) {
142
+ if (reSteerSamples.length < maxReSteer) reSteerSamples.push(q);
143
+ }
144
+
145
+ // Per-workspace signature tally (drives the global map + this ws's topFailure).
146
+ const localSig = new Map<string, number>();
147
+ for (const e of s.errors) {
148
+ const sig = normalizeErrorSignature(e);
149
+ if (!sig) continue;
150
+ localSig.set(sig, (localSig.get(sig) ?? 0) + 1);
151
+ let entry = errorMap.get(sig);
152
+ if (!entry) {
153
+ entry = { count: 0, ws: new Set(), example: e.slice(0, exampleChars) };
154
+ errorMap.set(sig, entry);
155
+ }
156
+ entry.count++;
157
+ entry.ws.add(ws.name);
158
+ }
159
+ const topFailure = [...localSig.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
160
+
161
+ workspaces.push({ name: ws.name, turns: s.turns, failures: s.errors.length, contextQuality: ws.contextQuality, topFailure });
162
+ }
163
+
164
+ const topErrors: ErrorCluster[] = [...errorMap.entries()]
165
+ .map(([signature, v]) => ({ signature, count: v.count, workspaces: [...v.ws], example: v.example }))
166
+ // Most frequent first; break ties by cross-workspace spread (recurrence).
167
+ .sort((a, b) => b.count - a.count || b.workspaces.length - a.workspaces.length)
168
+ .slice(0, topErrorsK);
169
+
170
+ const topTools: ToolStat[] = [...toolMap.entries()]
171
+ .map(([tool, sessions]) => ({ tool, sessions }))
172
+ .sort((a, b) => b.sessions - a.sessions || a.tool.localeCompare(b.tool))
173
+ .slice(0, topToolsK);
174
+
175
+ return {
176
+ totalWorkspaces: corpus.workspaces.length,
177
+ sessionsAnalyzed,
178
+ totalTurns,
179
+ topErrors,
180
+ topTools,
181
+ correctionSignals,
182
+ reSteerSamples,
183
+ workspacesMissingContext,
184
+ workspacesBoilerplateContext,
185
+ availableSkills: corpus.availableSkills,
186
+ workspaces,
187
+ };
188
+ }
189
+
190
+ // --------------------------------------------------------------- judge prompt
191
+
192
+ /**
193
+ * Build the judge prompt from the pre-computed facts. Compact by construction
194
+ * (a handful of clusters + counts), so the LLM call stays small and fast no
195
+ * matter how many workspaces were analyzed. Output contract is unchanged
196
+ * (REFLECT_SCHEMA), so parsing/rendering are shared with the old path.
197
+ */
198
+ export function buildAnalysisPrompt(a: AnalysisReport): string {
199
+ const L: string[] = [];
200
+ L.push(
201
+ 'You are an expert reviewer ("LLM as a judge"). A script has already analyzed an engineer\'s',
202
+ 'recent AI coding-agent sessions and distilled them into the FACTS below. Do not ask for the',
203
+ 'raw transcripts — reason only from these facts.',
204
+ '',
205
+ 'Goal: recommend concrete improvements to their SETUP so the agent works better next time —',
206
+ 'which skills to add and WHERE, which AGENTS.md/context rules are missing, missing connectivity/',
207
+ 'smoke tests, and prompt/workflow habits. Ground every recommendation in a fact below',
208
+ '(a recurring failure, a correction loop, a missing context file). Prefer a few high-signal',
209
+ 'items over many generic ones. Include a concrete `example` snippet for skills/context rules.',
210
+ '',
211
+ `Sessions analyzed: ${a.sessionsAnalyzed} across ${a.totalWorkspaces} workspaces (${a.totalTurns} total turns).`,
212
+ `Installed skills (don't re-suggest; find genuine gaps): ${a.availableSkills.join(', ') || '(none)'}`,
213
+ `User correction/retry signals: ${a.correctionSignals} prompt(s) looked like corrections.`,
214
+ `Workspaces with NO context file (AGENTS.md/CLAUDE.md): ${a.workspacesMissingContext.join(', ') || '(none)'}`,
215
+ `Workspaces whose context file is just boilerplate/template: ${a.workspacesBoilerplateContext.join(', ') || '(none)'}`,
216
+ );
217
+
218
+ if (a.reSteerSamples.length) {
219
+ L.push('', 'Verbatim user corrections/re-steers (the sharpest signal — quote/act on these):');
220
+ for (const q of a.reSteerSamples) L.push(` - “${q.replace(/\n/g, ' ')}”`);
221
+ }
222
+
223
+ L.push('', 'Top recurring failures (count × workspaces — example):');
224
+ if (a.topErrors.length === 0) L.push(' (none captured)');
225
+ for (const e of a.topErrors) {
226
+ L.push(` - [${e.count}× in ${e.workspaces.length} ws] ${e.signature}`);
227
+ L.push(` e.g. ${e.example.replace(/\n/g, ' ')}`);
228
+ }
229
+
230
+ L.push('', `Most-used tools: ${a.topTools.map((t) => `${t.tool}(${t.sessions})`).join(', ') || '(none)'}`);
231
+
232
+ L.push('', 'Per-workspace:');
233
+ for (const w of a.workspaces) {
234
+ const top = w.topFailure ? ` · top failure: ${w.topFailure}` : '';
235
+ L.push(` - ${w.name}: ${w.turns} turns, ${w.failures} failures, context:${w.contextQuality}${top}`);
236
+ }
237
+
238
+ L.push(
239
+ '',
240
+ 'Respond with ONLY a JSON object of this shape (no prose, no markdown fence):',
241
+ '{"summary": string, "recommendations": [{"kind":"skill|context|test|prompt|connectivity|workflow|other",',
242
+ '"title": string, "detail": string, "target": string(optional workspace/repo/path),',
243
+ '"priority":"high|medium|low", "example": string(optional snippet)}]}',
244
+ );
245
+ return L.join('\n');
246
+ }
@@ -1,5 +1,7 @@
1
1
  import { describe, it, expect } from 'vitest';
2
- import { distillTranscript, buildJudgePrompt, parseReflectionReport, ReflectionCorpus } from './reflect';
2
+ import { distillTranscript, parseReflectionReport, classifyAgentsMd, isCorrectionPrompt, saveReflectionReport } from './reflect';
3
+ import * as fs from 'fs/promises';
4
+ import * as path from 'path';
3
5
 
4
6
  const J = (o: unknown) => JSON.stringify(o);
5
7
 
@@ -15,6 +17,8 @@ describe('distillTranscript', () => {
15
17
  J({ type: 'message', message: { role: 'toolResult', toolName: 'bash', isError: true, content: [{ type: 'text', text: 'command failed: boom' }] } }),
16
18
  // claude: user prompt as plain string
17
19
  J({ type: 'user', message: { role: 'user', content: 'claude style prompt' } }),
20
+ // a correction/re-steer → captured verbatim in reSteerSamples
21
+ J({ type: 'user', message: { role: 'user', content: 'no, that is wrong — revert that change' } }),
18
22
  // claude: assistant tool_use
19
23
  J({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'tool_use', name: 'Edit' }] } }),
20
24
  // claude: tool_result-only user message → an error, NOT a prompt
@@ -31,13 +35,14 @@ describe('distillTranscript', () => {
31
35
 
32
36
  const d = distillTranscript(lines, { sessionId: 's1', agentType: 'pi' });
33
37
  expect(d.turns).toBe(2);
34
- expect(d.userPrompts).toEqual(['do the thing', 'claude style prompt']);
38
+ expect(d.userPrompts).toEqual(['do the thing', 'claude style prompt', 'no, that is wrong — revert that change']);
35
39
  expect(d.tools.sort()).toEqual(['Edit', 'bash', 'git', 'grep']);
36
40
  expect(d.errors).toContain('command failed: boom'); // explicit isError:true
37
41
  expect(d.errors).toContain('file not found'); // explicit is_error:true
38
42
  expect(d.errors).toContain('fatal: not a git repository'); // unflagged + strong signal
39
43
  expect(d.errors).not.toContain('0 results for error'); // unflagged benign 'error' mention
40
44
  expect(d.errors.some((e) => e.includes('flagged success'))).toBe(false); // isError:false trusted
45
+ expect(d.reSteerSamples).toEqual(['no, that is wrong — revert that change']); // captured verbatim
41
46
  });
42
47
 
43
48
  it('is bounded and tolerant of empty input', () => {
@@ -50,32 +55,50 @@ describe('distillTranscript', () => {
50
55
  });
51
56
  });
52
57
 
53
- const corpus: ReflectionCorpus = {
54
- generatedAt: '2026-01-01T00:00:00Z',
55
- availableSkills: ['redash', 'datadog'],
56
- workspaces: [
57
- {
58
- name: 'pay-app',
59
- repoCount: 1,
60
- repos: ['api'],
61
- contextFiles: ['AGENTS.md'],
62
- session: { sessionId: 's', agentType: 'pi', turns: 12, userPrompts: ['fix the sync bug'], errors: ['gh_pr_create: not a git repository'], tools: ['bash', 'edit'] },
63
- },
64
- { name: 'empty-ws', repoCount: 0, repos: [], contextFiles: [], session: null },
65
- ],
66
- };
58
+ describe('saveReflectionReport', () => {
59
+ it('writes a timestamped JSON report (sanitized scope) and returns its path', async () => {
60
+ const file = await saveReflectionReport(
61
+ { summary: 'ok', recommendations: [{ kind: 'skill', title: 't', detail: 'd', priority: 'high' }] },
62
+ { analyzed: 2, workspaces: 3, workspace: 'pay/app' },
63
+ );
64
+ try {
65
+ expect(file).toMatch(/\.json$/);
66
+ expect(path.basename(file)).toContain('pay_app'); // scope suffix, path-sanitized
67
+ const written = JSON.parse(await fs.readFile(file, 'utf-8'));
68
+ expect(written).toMatchObject({ analyzed: 2, workspaces: 3, workspace: 'pay/app', summary: 'ok' });
69
+ expect(written.generatedAt).toBeTruthy();
70
+ } finally {
71
+ await fs.rm(file, { force: true });
72
+ }
73
+ });
74
+ });
75
+
76
+ describe('classifyAgentsMd', () => {
77
+ it('distinguishes missing / boilerplate / substantive', () => {
78
+ expect(classifyAgentsMd('')).toBe('missing');
79
+ expect(classifyAgentsMd(null)).toBe('missing');
80
+ // Generated template: headings + markers, little real guidance.
81
+ expect(classifyAgentsMd('# Workspace\n\nThis workspace was created with Workspace Manager.\n<!-- ws-rules:v2 -->\n## Notes\n- \n')).toBe('boilerplate');
82
+ // Real, rule-heavy content.
83
+ const real = Array.from({ length: 12 }, (_, i) => `- Always run the ${i} integration suite before opening a pull request here`).join('\n');
84
+ expect(classifyAgentsMd(`# Rules\n${real}`)).toBe('substantive');
85
+ });
86
+
87
+ it('is newline-independent: a whitespace-collapsed substantive file still classifies substantive', () => {
88
+ // Regression for the collapse bug: same content, newlines squashed to spaces.
89
+ const real = Array.from({ length: 12 }, (_, i) => `- Always run the ${i} integration suite before opening a pull request here`).join('\n');
90
+ const multiline = `# Rules\n${real}`;
91
+ const collapsed = multiline.replace(/\s+/g, ' ');
92
+ expect(classifyAgentsMd(collapsed)).toBe(classifyAgentsMd(multiline));
93
+ expect(classifyAgentsMd(collapsed)).toBe('substantive');
94
+ });
95
+ });
67
96
 
68
- describe('buildJudgePrompt', () => {
69
- const p = buildJudgePrompt(corpus);
70
- it('frames the judge task and includes the evidence + guardrails', () => {
71
- expect(p).toContain('LLM as a judge');
72
- expect(p).toContain('redash, datadog'); // available skills (do not re-suggest)
73
- expect(p).toContain('## pay-app');
74
- expect(p).toContain('fix the sync bug');
75
- expect(p).toContain('gh_pr_create: not a git repository');
76
- expect(p).toContain('no recent agent session found'); // empty-ws
77
- expect(p).toContain('context files: NONE'); // empty-ws has none
78
- expect(p).toMatch(/ONLY a JSON object/);
97
+ describe('isCorrectionPrompt', () => {
98
+ it('flags corrections, not normal instructions', () => {
99
+ expect(isCorrectionPrompt('no, revert that')).toBe(true);
100
+ expect(isCorrectionPrompt('actually use the other repo instead')).toBe(true);
101
+ expect(isCorrectionPrompt('add a health check to the api')).toBe(false);
79
102
  });
80
103
  });
81
104