Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/tools/audit-workspace.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { run } from "../lib/git.js";
import { readIfExists, findWorkspaceDocs } from "../lib/files.js";
import { readIfExists, findWorkspaceDocs, PROJECT_DIR } from "../lib/files.js";
import { readdirSync } from "fs";
import { join } from "path";

/** Extract top-level work areas from file paths generically */
function detectWorkAreas(files: string[]): Set<string> {
Expand Down Expand Up @@ -36,7 +38,8 @@ export function registerAuditWorkspace(server: McpServer): void {
{},
async () => {
const docs = findWorkspaceDocs();
const recentFiles = run("git diff --name-only HEAD~10 2>/dev/null || echo ''").split("\n").filter(Boolean);
const diffResult = run(["diff", "--name-only", "HEAD~10"]);
const recentFiles = diffResult.startsWith("[") ? [] : diffResult.split("\n").filter(Boolean);
const sections: string[] = [];

// Doc freshness
Expand Down Expand Up @@ -75,7 +78,21 @@ export function registerAuditWorkspace(server: McpServer): void {
// Check for gap trackers or similar tracking docs
const trackingDocs = Object.entries(docs).filter(([n]) => /gap|track|progress/i.test(n));
if (trackingDocs.length > 0) {
const testFilesCount = parseInt(run("find tests -name '*.spec.ts' -o -name '*.test.ts' 2>/dev/null | wc -l").trim()) || 0;
// Count test files using Node.js fs
let testFilesCount = 0;
const countTestFiles = (dir: string, depth = 0): void => {
if (depth > 4) return;
try {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
countTestFiles(join(dir, entry.name), depth + 1);
} else if (entry.isFile() && /\.(spec|test)\.(ts|tsx|js|jsx)$/.test(entry.name)) {
testFilesCount++;
}
}
} catch { /* dir may not exist */ }
};
countTestFiles(join(PROJECT_DIR, "tests"));
sections.push(`## Tracking Docs\n${trackingDocs.map(([n]) => {
const age = docStatus.find(d => d.name === n)?.ageHours ?? "?";
return `- .claude/${n} — last updated ${age}h ago`;
Expand Down
35 changes: 15 additions & 20 deletions src/tools/checkpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,32 +63,27 @@ ${dirty || "clean"}
const shortSummary = summary.split("\n")[0].slice(0, 72);
const commitMsg = `checkpoint: ${shortSummary}`;

let addCmd: string;
switch (mode) {
case "staged": {
const staged = getStagedFiles();
if (!staged) {
commitResult = "nothing staged — skipped commit (use 'tracked' or 'all' mode, or stage files first)";
}
addCmd = "true"; // noop, already staged
break;
if (mode === "staged") {
const staged = getStagedFiles();
if (!staged) {
commitResult = "nothing staged — skipped commit (use 'tracked' or 'all' mode, or stage files first)";
}
case "all":
addCmd = "git add -A";
break;
case "tracked":
default:
addCmd = "git add -u";
break;
}

if (commitResult === "no uncommitted changes") {
// Stage the checkpoint file too
run(`git add "${checkpointFile}"`);
const result = run(`${addCmd} && git commit -m "${commitMsg.replace(/"/g, '\\"')}" 2>&1`);
if (result.includes("commit failed") || result.includes("nothing to commit")) {
run(["add", checkpointFile]);
// Stage based on mode
if (mode === "all") {
run(["add", "-A"]);
} else if (mode === "tracked") {
run(["add", "-u"]);
}
// mode === "staged": already staged, nothing extra to do
const result = run(["commit", "-m", commitMsg]);
if (result.includes("commit failed") || result.includes("nothing to commit") || result.startsWith("[command failed")) {
// Rollback: unstage if commit failed
run("git reset HEAD 2>/dev/null");
run(["reset", "HEAD"]);
commitResult = `commit failed: ${result}`;
} else {
commitResult = result;
Expand Down
43 changes: 39 additions & 4 deletions src/tools/clarify-intent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,31 @@ import { run, getBranch, getStatus, getRecentCommits, getDiffFiles, getStagedFil
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 { existsSync, readFileSync, readdirSync, statSync } from "fs";
import { execFileSync } from "child_process";
import { join, basename, resolve } from "path";
import { loadAllContracts, searchContracts, formatContracts } from "../lib/contracts.js";

/** Recursively find test files using Node.js fs */
function findTestFiles(dir: string, maxDepth: number, limit: number, depth = 0): string[] {
const results: string[] = [];
if (depth > maxDepth || results.length >= limit) return results;
try {
const entries = readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (results.length >= limit) break;
const fullPath = join(dir, entry.name);
if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
results.push(...findTestFiles(fullPath, maxDepth, limit - results.length, depth + 1));
} else if (entry.isFile() && /\.spec\.ts$/.test(entry.name)) {
// Return relative to PROJECT_DIR
results.push(fullPath.replace(PROJECT_DIR + "/", ""));
}
}
} catch { /* directory may not exist */ }
return results;
}

/** Parse test failures from common report formats without fragile shell pipelines */
function getTestFailures(): string {
// Try playwright JSON report
Expand Down Expand Up @@ -152,10 +173,24 @@ export function registerClarifyIntent(server: McpServer): void {
let hasTestFailures = false;

if (!area || area.includes("test") || area.includes("fix") || area.includes("ui") || area.includes("api")) {
const typeErrors = run("pnpm tsc --noEmit 2>&1 | grep -c 'error TS' || echo '0'");
hasTypeErrors = parseInt(typeErrors, 10) > 0;
let typeErrorCount = 0;
try {
execFileSync("pnpm", ["tsc", "--noEmit"], {
cwd: PROJECT_DIR,
encoding: "utf-8",
timeout: 30000,
stdio: ["pipe", "pipe", "pipe"],
});
} catch (e: any) {
const output = (e.stdout || "") + (e.stderr || "");
const matches = output.match(/error TS/g);
typeErrorCount = matches ? matches.length : 0;
}
const typeErrors = String(typeErrorCount);
hasTypeErrors = typeErrorCount > 0;

const testFiles = run("find tests -name '*.spec.ts' -maxdepth 4 2>/dev/null | head -20");
// Find test files using Node.js fs instead of shell find
const testFiles = findTestFiles(join(PROJECT_DIR, "tests"), 4, 20).join("\n");
const failingTests = getTestFailures();
hasTestFailures = failingTests !== "all passing" && failingTests !== "no test report found";

Expand Down
49 changes: 33 additions & 16 deletions src/tools/enrich-agent-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@ import { execFileSync } from "child_process";
import { join, basename } from "path";
import { createHash } from "crypto";

/** Sanitize user input for safe use in shell commands */
function shellEscape(s: string): string {
return s.replace(/[^a-zA-Z0-9_\-./]/g, "");
}

/** Detect package manager from lockfiles */
function detectPackageManager(): string {
if (existsSync(join(PROJECT_DIR, "pnpm-lock.yaml"))) return "pnpm";
Expand All @@ -25,35 +20,57 @@ function detectPackageManager(): string {
function findAreaFiles(area: string): string {
if (!area) return getDiffFiles("HEAD~3");

const safeArea = shellEscape(area);
// Get all tracked files and filter in JS
const allFiles = run(["ls-files"]);
if (allFiles.startsWith("[")) return getDiffFiles("HEAD~3");

const fileList = allFiles.split("\n").filter(Boolean);
const areaLower = area.toLowerCase();

// If area looks like a path, search directly
let matches: string[];
if (area.includes("/")) {
return run(`git ls-files -- '${safeArea}*' 2>/dev/null | head -20`);
// If area looks like a path, match prefix
matches = fileList.filter(f => f.startsWith(area));
} else {
// Search for area keyword in file paths
matches = fileList.filter(f => f.toLowerCase().includes(areaLower));
}

// Search for area keyword in git-tracked file paths
const files = run(`git ls-files 2>/dev/null | grep -i '${safeArea}' | head -20`);
if (files && !files.startsWith("[command failed")) return files;
if (matches.length > 0) return matches.slice(0, 20).join("\n");

// Fallback to recently changed files
return getDiffFiles("HEAD~3");
}

/** Find related test files for an area */
function findRelatedTests(area: string): string {
if (!area) return run("git ls-files 2>/dev/null | grep -E '\\.(spec|test)\\.(ts|tsx|js|jsx)$' | head -10");
const allFiles = run(["ls-files"]);
if (allFiles.startsWith("[")) return "";

const testPattern = /\.(spec|test)\.(ts|tsx|js|jsx)$/;
const testFiles = allFiles.split("\n").filter(f => testPattern.test(f));

if (!area) return testFiles.slice(0, 10).join("\n");

const safeArea = shellEscape(area.split(/\s+/)[0]);
const tests = run(`git ls-files 2>/dev/null | grep -E '\\.(spec|test)\\.(ts|tsx|js|jsx)$' | grep -i '${safeArea}' | head -10`);
return tests || run("git ls-files 2>/dev/null | grep -E '\\.(spec|test)\\.(ts|tsx|js|jsx)$' | head -10");
const areaKeyword = area.split(/\s+/)[0].toLowerCase();
const areaTests = testFiles.filter(f => f.toLowerCase().includes(areaKeyword));
if (areaTests.length > 0) return areaTests.slice(0, 10).join("\n");

return testFiles.slice(0, 10).join("\n");
}

/** Get an example pattern from the first matching file */
function getExamplePattern(files: string): string {
const firstFile = files.split("\n").filter(Boolean)[0];
if (!firstFile) return "no pattern available";
return run(`head -30 '${shellEscape(firstFile)}' 2>/dev/null || echo 'could not read file'`);
try {
const fullPath = join(PROJECT_DIR, firstFile);
const content = readFileSync(fullPath, "utf-8");
const lines = content.split("\n").slice(0, 30);
return lines.join("\n");
} catch {
return "could not read file";
}
}

// ---------------------------------------------------------------------------
Expand Down
3 changes: 2 additions & 1 deletion src/tools/sequence-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ export function registerSequenceTasks(server: McpServer): void {
// For locality: infer directories from path-like tokens in task text
if (strategy === "locality") {
// Use git ls-files with a depth limit instead of find for performance
const gitFiles = run("git ls-files 2>/dev/null | head -1000");
const gitFilesRaw = run(["ls-files"]);
const gitFiles = gitFilesRaw.startsWith("[") ? "" : gitFilesRaw.split("\n").slice(0, 1000).join("\n");
const knownDirs = new Set<string>();
for (const f of gitFiles.split("\n").filter(Boolean)) {
const parts = f.split("/");
Expand Down
18 changes: 15 additions & 3 deletions src/tools/session-handoff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ import { z } from "zod";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { existsSync, readFileSync } from "fs";
import { join } from "path";
import { execFileSync } from "child_process";
import { run, getBranch, getRecentCommits, getStatus } from "../lib/git.js";
import { readIfExists, findWorkspaceDocs } from "../lib/files.js";
import { STATE_DIR, now } from "../lib/state.js";

/** Check if a CLI tool is available */
function hasCommand(cmd: string): boolean {
const result = run(`command -v ${cmd} 2>/dev/null`);
return !!result && !result.startsWith("[command failed");
try {
execFileSync("which", [cmd], { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
return true;
} catch {
return false;
}
}

export function registerSessionHandoff(server: McpServer): void {
Expand Down Expand Up @@ -44,7 +49,14 @@ export function registerSessionHandoff(server: McpServer): void {

// Only try gh if it exists
if (hasCommand("gh")) {
const openPRs = run("gh pr list --state open --json number,title,headRefName 2>/dev/null || echo '[]'");
let openPRs = "[]";
try {
openPRs = execFileSync("gh", ["pr", "list", "--state", "open", "--json", "number,title,headRefName"], {
encoding: "utf-8",
timeout: 10000,
stdio: ["pipe", "pipe", "pipe"],
}).trim();
} catch { /* gh not available or failed */ }
if (openPRs && openPRs !== "[]") {
sections.push(`## Open PRs\n\`\`\`json\n${openPRs}\n\`\`\``);
}
Expand Down
16 changes: 8 additions & 8 deletions src/tools/sharpen-followup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ function parsePortelainFiles(output: string): string[] {
/** Get recently changed files, safe for first commit / shallow clones */
function getRecentChangedFiles(): string[] {
// Try HEAD~1..HEAD, fall back to just staged, then unstaged
const commands = [
"git diff --name-only HEAD~1 HEAD 2>/dev/null",
"git diff --name-only --cached 2>/dev/null",
"git diff --name-only 2>/dev/null",
const commands: string[][] = [
["diff", "--name-only", "HEAD~1", "HEAD"],
["diff", "--name-only", "--cached"],
["diff", "--name-only"],
];
const results = new Set<string>();
for (const cmd of commands) {
const out = run(cmd);
if (out) out.split("\n").filter(Boolean).forEach((f) => results.add(f));
for (const args of commands) {
const out = run(args);
if (out && !out.startsWith("[")) out.split("\n").filter(Boolean).forEach((f) => results.add(f));
if (results.size > 0) break; // first successful source is enough
}
return [...results];
Expand Down Expand Up @@ -87,7 +87,7 @@ export function registerSharpenFollowup(server: McpServer): void {
// Gather context to resolve ambiguity
const contextFiles: string[] = [...(previous_files ?? [])];
const recentChanged = getRecentChangedFiles();
const porcelainOutput = run("git status --porcelain 2>/dev/null");
const porcelainOutput = run(["status", "--porcelain"]);
const untrackedOrModified = parsePortelainFiles(porcelainOutput);

const allKnownFiles = [...new Set([...contextFiles, ...recentChanged, ...untrackedOrModified])].filter(Boolean);
Expand Down
Loading
Loading