-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclarify-intent.ts
More file actions
200 lines (173 loc) · 9.11 KB
/
clarify-intent.ts
File metadata and controls
200 lines (173 loc) · 9.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import { z } from "zod";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { run, shell, getBranch, getStatus, getRecentCommits, getDiffFiles, getStagedFiles } from "../lib/git.js";
import { findWorkspaceDocs, PROJECT_DIR } from "../lib/files.js";
import { searchSemantic } from "../lib/timeline-db.js";
import { getRelatedProjects } from "../lib/config.js";
import { existsSync, readFileSync } from "fs";
import { join, basename, resolve } from "path";
import { loadAllContracts, searchContracts, formatContracts } from "../lib/contracts.js";
/** Parse test failures from common report formats without fragile shell pipelines */
function getTestFailures(): string {
// Try playwright JSON report
const reportPath = join(PROJECT_DIR, "playwright-report", "results.json");
if (existsSync(reportPath)) {
try {
const data = JSON.parse(readFileSync(reportPath, "utf-8"));
const failures: string[] = [];
const walk = (suites: any[]) => {
for (const suite of suites || []) {
for (const spec of suite.specs || []) {
if (spec.ok === false) failures.push(spec.title);
}
walk(suite.suites);
}
};
walk(data.suites);
return failures.length ? failures.join("\n") : "all passing";
} catch {
return "report exists but could not parse";
}
}
// Try jest/vitest JSON output
for (const p of ["test-results.json", "jest-results.json"]) {
const fp = join(PROJECT_DIR, p);
if (existsSync(fp)) {
try {
const data = JSON.parse(readFileSync(fp, "utf-8"));
const failed = data.testResults
?.filter((t: any) => t.status === "failed")
?.map((t: any) => t.name) || [];
return failed.length ? failed.join("\n") : "all passing";
} catch { continue; }
}
}
return "no test report found";
}
/** Extract intent signals using weighted pattern matching */
function extractSignals(msg: string, context: { hasTypeErrors: boolean; hasTestFailures: boolean; hasDirtyFiles: boolean }): string[] {
const signals: string[] = [];
const lower = msg.toLowerCase();
const patterns: [RegExp, string, number][] = [
[/\b(fix|repair|broken|failing|error|bug|crash|issue)\b/, "FIX", 2],
[/\b(test|spec|suite|playwright|jest|vitest|e2e)\b/, "TESTS", 2],
[/\b(commit|push|pr|merge|rebase|cherry.?pick)\b/, "GIT", 2],
[/\b(add|create|new|build|implement|feature)\b/, "CREATE", 1],
[/\b(remove|delete|clean|strip|drop|deprecate)\b/, "REMOVE", 1],
[/\b(check|verify|confirm|status|review|audit)\b/, "VERIFY", 1],
[/\b(refactor|rename|move|reorganize|extract)\b/, "REFACTOR", 1],
[/\b(deploy|release|ship|publish)\b/, "DEPLOY", 1],
[/\b(everything|all|entire|whole)\b/, "⚠️ UNBOUNDED", 3],
];
const matched: { label: string; weight: number; hint: string }[] = [];
for (const [re, label, weight] of patterns) {
if (re.test(lower)) matched.push({ label, weight, hint: "" });
}
// Add contextual hints
if (matched.some(m => m.label === "FIX")) {
if (context.hasTypeErrors) signals.push("FIX: Type errors detected — likely the target.");
if (context.hasTestFailures) signals.push("FIX: Test failures detected — check test output.");
if (!context.hasTypeErrors && !context.hasTestFailures) signals.push("FIX: No obvious errors — ask what's broken.");
}
if (matched.some(m => m.label === "TESTS")) signals.push("TESTS: Check failing tests and test files below.");
if (matched.some(m => m.label === "GIT")) signals.push("GIT: Check dirty files and branch state.");
if (matched.some(m => m.label === "CREATE")) signals.push("CREATE: Check workspace priorities for planned work.");
if (matched.some(m => m.label === "REMOVE")) signals.push("REMOVE: Clarify what 'them/it' refers to before deleting.");
if (matched.some(m => m.label === "VERIFY")) signals.push("VERIFY: Use git/test state to answer.");
if (matched.some(m => m.label === "REFACTOR")) signals.push("REFACTOR: Identify scope boundaries before starting.");
if (matched.some(m => m.label === "DEPLOY")) signals.push("DEPLOY: Verify all checks pass first.");
if (matched.some(m => m.label === "⚠️ UNBOUNDED")) signals.push("⚠️ UNBOUNDED: Narrow down using workspace priorities.");
if (!signals.length) signals.push("UNCLEAR: Ask ONE clarifying question before proceeding.");
return signals;
}
/** Search for relevant cross-project context */
async function searchCrossProjectContext(userMessage: string): Promise<string[]> {
const relatedProjects = getRelatedProjects();
if (relatedProjects.length === 0) return [];
// Generate search queries for schemas, types, contracts, APIs
const queries = [
`${userMessage} type interface schema`,
`${userMessage} API endpoint contract`,
`${userMessage} enum constant definition`,
`${userMessage} class function method`,
];
const contextItems: string[] = [];
for (const query of queries) {
try {
const results = await searchSemantic(query, {
project_dirs: relatedProjects,
type: "commit", // Focus on code changes
limit: 3,
});
for (const result of results) {
const projectName = basename(result.project);
const content = result.content.slice(0, 200);
const sourceInfo = result.source_file ? ` at ${result.source_file}` : "";
contextItems.push(`**From ${projectName}:** ${content}${sourceInfo}`);
}
} catch {
// Skip if search fails
}
}
return contextItems.slice(0, 5); // Limit to top 5 context items
}
export function registerClarifyIntent(server: McpServer): void {
server.tool(
"clarify_intent",
`Clarify a vague user instruction by gathering project context. Call BEFORE executing when the user's prompt is missing specific files, actions, scope, or done conditions. Returns git state, test failures, recent changes, and workspace priorities.`,
{
user_message: z.string().describe("The user's raw message/instruction to clarify"),
suspected_area: z.string().optional().describe("Best guess area: 'tests', 'git', 'ui', 'api', 'schema'"),
},
async ({ user_message, suspected_area }) => {
const sections: string[] = [];
const branch = getBranch();
const status = getStatus();
const recentCommits = getRecentCommits(5);
const recentFiles = getDiffFiles("HEAD~3");
const staged = getStagedFiles();
const dirtyCount = status ? status.split("\n").filter(Boolean).length : 0;
sections.push(`## Git State\nBranch: ${branch}\nDirty files: ${dirtyCount}\n${status ? `\`\`\`\n${status}\n\`\`\`` : "Working tree clean"}\nStaged: ${staged || "nothing"}\n\nRecent commits:\n\`\`\`\n${recentCommits}\n\`\`\`\n\nRecently changed files:\n\`\`\`\n${recentFiles}\n\`\`\``);
// Gather test/type state when relevant
const area = (suspected_area || "").toLowerCase();
let hasTypeErrors = false;
let hasTestFailures = false;
if (!area || area.includes("test") || area.includes("fix") || area.includes("ui") || area.includes("api")) {
const typeErrors = shell("pnpm tsc --noEmit 2>&1 | grep -c 'error TS' || echo '0'");
hasTypeErrors = parseInt(typeErrors, 10) > 0;
const testFiles = shell("find tests -name '*.spec.ts' -maxdepth 4 2>/dev/null | head -20");
const failingTests = getTestFailures();
hasTestFailures = failingTests !== "all passing" && failingTests !== "no test report found";
sections.push(`## Test State\nType errors: ${typeErrors}\nFailing tests: ${failingTests}\nTest files:\n\`\`\`\n${testFiles || "none found"}\n\`\`\``);
}
// Workspace priorities
const workspaceDocs = findWorkspaceDocs();
const priorityDocs = Object.entries(workspaceDocs)
.filter(([n]) => /gap|roadmap|current|todo|changelog/i.test(n))
.slice(0, 3);
if (priorityDocs.length > 0) {
sections.push(`## Workspace Priorities\n${priorityDocs.map(([n, d]) => `### .claude/${n}\n\`\`\`\n${d.content}\n\`\`\``).join("\n\n")}`);
}
const signals = extractSignals(user_message, {
hasTypeErrors,
hasTestFailures,
hasDirtyFiles: dirtyCount > 0,
});
// Check contracts FIRST (fast, no vector search)
const contractDirs = [resolve(PROJECT_DIR), ...getRelatedProjects()];
const allContracts = loadAllContracts(contractDirs);
const matchedContracts = searchContracts(user_message, allContracts);
if (matchedContracts.length > 0) {
sections.push(`## Matching Contracts\n${formatContracts(matchedContracts, 8)}`);
}
// Search for cross-project context
const crossProjectContext = await searchCrossProjectContext(user_message);
if (crossProjectContext.length > 0) {
sections.push(`## Related Project Context\n${crossProjectContext.map(c => `- ${c}`).join("\n")}`);
}
sections.push(`## Intent Signals\n${signals.map(s => `- ${s}`).join("\n")}`);
sections.push(`## Recommendation\n1. **Proceed with specifics** — state what you'll do and why\n2. **Ask ONE question** — if context doesn't disambiguate`);
return { content: [{ type: "text" as const, text: sections.join("\n\n") }] };
}
);
}