preflight-dev 3.1.0
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/LICENSE +21 -0
- package/README.md +172 -0
- package/bin/cli.js +11 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +154 -0
- package/dist/cli/init.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +122 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/config.d.ts +34 -0
- package/dist/lib/config.js +118 -0
- package/dist/lib/config.js.map +1 -0
- package/dist/lib/embeddings.d.ts +11 -0
- package/dist/lib/embeddings.js +88 -0
- package/dist/lib/embeddings.js.map +1 -0
- package/dist/lib/files.d.ts +15 -0
- package/dist/lib/files.js +60 -0
- package/dist/lib/files.js.map +1 -0
- package/dist/lib/git-extractor.d.ts +9 -0
- package/dist/lib/git-extractor.js +116 -0
- package/dist/lib/git-extractor.js.map +1 -0
- package/dist/lib/git.d.ts +29 -0
- package/dist/lib/git.js +86 -0
- package/dist/lib/git.js.map +1 -0
- package/dist/lib/session-parser.d.ts +45 -0
- package/dist/lib/session-parser.js +267 -0
- package/dist/lib/session-parser.js.map +1 -0
- package/dist/lib/state.d.ts +21 -0
- package/dist/lib/state.js +86 -0
- package/dist/lib/state.js.map +1 -0
- package/dist/lib/timeline-db.d.ts +67 -0
- package/dist/lib/timeline-db.js +380 -0
- package/dist/lib/timeline-db.js.map +1 -0
- package/dist/lib/triage.d.ts +29 -0
- package/dist/lib/triage.js +193 -0
- package/dist/lib/triage.js.map +1 -0
- package/dist/profiles.d.ts +3 -0
- package/dist/profiles.js +65 -0
- package/dist/profiles.js.map +1 -0
- package/dist/tools/audit-workspace.d.ts +2 -0
- package/dist/tools/audit-workspace.js +86 -0
- package/dist/tools/audit-workspace.js.map +1 -0
- package/dist/tools/checkpoint.d.ts +2 -0
- package/dist/tools/checkpoint.js +108 -0
- package/dist/tools/checkpoint.js.map +1 -0
- package/dist/tools/clarify-intent.d.ts +2 -0
- package/dist/tools/clarify-intent.js +180 -0
- package/dist/tools/clarify-intent.js.map +1 -0
- package/dist/tools/enrich-agent-task.d.ts +2 -0
- package/dist/tools/enrich-agent-task.js +97 -0
- package/dist/tools/enrich-agent-task.js.map +1 -0
- package/dist/tools/generate-scorecard.d.ts +2 -0
- package/dist/tools/generate-scorecard.js +617 -0
- package/dist/tools/generate-scorecard.js.map +1 -0
- package/dist/tools/log-correction.d.ts +2 -0
- package/dist/tools/log-correction.js +76 -0
- package/dist/tools/log-correction.js.map +1 -0
- package/dist/tools/onboard-project.d.ts +2 -0
- package/dist/tools/onboard-project.js +179 -0
- package/dist/tools/onboard-project.js.map +1 -0
- package/dist/tools/preflight-check.d.ts +2 -0
- package/dist/tools/preflight-check.js +229 -0
- package/dist/tools/preflight-check.js.map +1 -0
- package/dist/tools/prompt-score.d.ts +2 -0
- package/dist/tools/prompt-score.js +132 -0
- package/dist/tools/prompt-score.js.map +1 -0
- package/dist/tools/scan-sessions.d.ts +2 -0
- package/dist/tools/scan-sessions.js +182 -0
- package/dist/tools/scan-sessions.js.map +1 -0
- package/dist/tools/scope-work.d.ts +2 -0
- package/dist/tools/scope-work.js +214 -0
- package/dist/tools/scope-work.js.map +1 -0
- package/dist/tools/search-history.d.ts +2 -0
- package/dist/tools/search-history.js +130 -0
- package/dist/tools/search-history.js.map +1 -0
- package/dist/tools/sequence-tasks.d.ts +2 -0
- package/dist/tools/sequence-tasks.js +165 -0
- package/dist/tools/sequence-tasks.js.map +1 -0
- package/dist/tools/session-handoff.d.ts +2 -0
- package/dist/tools/session-handoff.js +113 -0
- package/dist/tools/session-handoff.js.map +1 -0
- package/dist/tools/session-health.d.ts +2 -0
- package/dist/tools/session-health.js +111 -0
- package/dist/tools/session-health.js.map +1 -0
- package/dist/tools/session-stats.d.ts +2 -0
- package/dist/tools/session-stats.js +112 -0
- package/dist/tools/session-stats.js.map +1 -0
- package/dist/tools/sharpen-followup.d.ts +2 -0
- package/dist/tools/sharpen-followup.js +192 -0
- package/dist/tools/sharpen-followup.js.map +1 -0
- package/dist/tools/timeline-view.d.ts +2 -0
- package/dist/tools/timeline-view.js +165 -0
- package/dist/tools/timeline-view.js.map +1 -0
- package/dist/tools/token-audit.d.ts +2 -0
- package/dist/tools/token-audit.js +227 -0
- package/dist/tools/token-audit.js.map +1 -0
- package/dist/tools/verify-completion.d.ts +2 -0
- package/dist/tools/verify-completion.js +154 -0
- package/dist/tools/verify-completion.js.map +1 -0
- package/dist/tools/what-changed.d.ts +2 -0
- package/dist/tools/what-changed.js +40 -0
- package/dist/tools/what-changed.js.map +1 -0
- package/dist/types.d.ts +78 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +52 -0
- package/src/cli/init.ts +133 -0
- package/src/index.ts +135 -0
- package/src/lib/config.ts +157 -0
- package/src/lib/embeddings.ts +118 -0
- package/src/lib/files.ts +59 -0
- package/src/lib/git-extractor.ts +137 -0
- package/src/lib/git.ts +89 -0
- package/src/lib/session-parser.ts +325 -0
- package/src/lib/state.ts +86 -0
- package/src/lib/timeline-db.ts +490 -0
- package/src/lib/triage.ts +255 -0
- package/src/profiles.ts +70 -0
- package/src/templates/config.yml +23 -0
- package/src/templates/triage.yml +27 -0
- package/src/tools/audit-workspace.ts +97 -0
- package/src/tools/checkpoint.ts +119 -0
- package/src/tools/clarify-intent.ts +191 -0
- package/src/tools/enrich-agent-task.ts +108 -0
- package/src/tools/generate-scorecard.ts +673 -0
- package/src/tools/log-correction.ts +89 -0
- package/src/tools/onboard-project.ts +214 -0
- package/src/tools/preflight-check.ts +263 -0
- package/src/tools/prompt-score.ts +150 -0
- package/src/tools/scan-sessions.ts +209 -0
- package/src/tools/scope-work.ts +238 -0
- package/src/tools/search-history.ts +145 -0
- package/src/tools/sequence-tasks.ts +182 -0
- package/src/tools/session-handoff.ts +125 -0
- package/src/tools/session-health.ts +107 -0
- package/src/tools/session-stats.ts +134 -0
- package/src/tools/sharpen-followup.ts +200 -0
- package/src/tools/timeline-view.ts +181 -0
- package/src/tools/token-audit.ts +259 -0
- package/src/tools/verify-completion.ts +159 -0
- package/src/tools/what-changed.ts +48 -0
- package/src/types.ts +87 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// =============================================================================
|
|
2
|
+
// prompt_score — Gamified prompt quality scoring
|
|
3
|
+
// =============================================================================
|
|
4
|
+
|
|
5
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
|
|
11
|
+
interface ScoreHistory {
|
|
12
|
+
scores: number[];
|
|
13
|
+
sessionStart: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const STATE_DIR = join(homedir(), ".preflight");
|
|
17
|
+
const STATE_FILE = join(STATE_DIR, "score-history.json");
|
|
18
|
+
|
|
19
|
+
async function loadHistory(): Promise<ScoreHistory> {
|
|
20
|
+
try {
|
|
21
|
+
const data = await readFile(STATE_FILE, "utf-8");
|
|
22
|
+
return JSON.parse(data);
|
|
23
|
+
} catch {
|
|
24
|
+
return { scores: [], sessionStart: new Date().toISOString() };
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function saveHistory(history: ScoreHistory): Promise<void> {
|
|
29
|
+
await mkdir(STATE_DIR, { recursive: true });
|
|
30
|
+
await writeFile(STATE_FILE, JSON.stringify(history, null, 2));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface ScoreResult {
|
|
34
|
+
specificity: number;
|
|
35
|
+
scope: number;
|
|
36
|
+
actionability: number;
|
|
37
|
+
doneCondition: number;
|
|
38
|
+
total: number;
|
|
39
|
+
grade: string;
|
|
40
|
+
feedback: string[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function scorePrompt(text: string): ScoreResult {
|
|
44
|
+
const feedback: string[] = [];
|
|
45
|
+
let specificity = 0;
|
|
46
|
+
let scope = 0;
|
|
47
|
+
let actionability = 0;
|
|
48
|
+
let doneCondition = 0;
|
|
49
|
+
|
|
50
|
+
// Specificity: file paths, function names, specific identifiers
|
|
51
|
+
if (/[\/\\][\w.-]+\.\w+/.test(text) || /`[^`]+`/.test(text)) {
|
|
52
|
+
specificity = 25;
|
|
53
|
+
} else if (/\b(file|component|function|class|module|test|route)\b/i.test(text)) {
|
|
54
|
+
specificity = 15;
|
|
55
|
+
feedback.push("📁 Name the specific file/function for +10 points");
|
|
56
|
+
} else {
|
|
57
|
+
specificity = 5;
|
|
58
|
+
feedback.push("📁 No specific targets mentioned — which file? which function?");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Scope: bounded task
|
|
62
|
+
if (/\b(only|just|single|one|specific|this)\b/i.test(text) || text.length > 100) {
|
|
63
|
+
scope = 25;
|
|
64
|
+
} else if (/\b(all|every|entire|whole)\b/i.test(text)) {
|
|
65
|
+
scope = 10;
|
|
66
|
+
feedback.push("🎯 'All/every' is broad — can you narrow the scope?");
|
|
67
|
+
} else {
|
|
68
|
+
scope = 10;
|
|
69
|
+
feedback.push("🎯 Scope unclear — how much should change?");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Actionability: clear verb
|
|
73
|
+
const actionVerbs = /\b(add|remove|rename|refactor|fix|create|delete|update|change|replace|move|extract|implement|write|test|migrate)\b/i;
|
|
74
|
+
if (actionVerbs.test(text)) {
|
|
75
|
+
actionability = 25;
|
|
76
|
+
} else if (/\b(make|do|handle|work|improve|clean)\b/i.test(text)) {
|
|
77
|
+
actionability = 15;
|
|
78
|
+
feedback.push("⚡ Vague verb — 'fix' beats 'make work', 'extract' beats 'clean up'");
|
|
79
|
+
} else {
|
|
80
|
+
actionability = 5;
|
|
81
|
+
feedback.push("⚡ What's the action? Use a specific verb (add, remove, rename, etc.)");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Done condition: verifiable outcome
|
|
85
|
+
if (/\b(should|must|expect|assert|return|output|pass|fail|error|log|print|display)\b/i.test(text)) {
|
|
86
|
+
doneCondition = 25;
|
|
87
|
+
} else if (/\?$/.test(text.trim())) {
|
|
88
|
+
doneCondition = 20; // questions are inherently verifiable
|
|
89
|
+
} else {
|
|
90
|
+
doneCondition = 5;
|
|
91
|
+
feedback.push("✅ No done condition — how will you know it worked?");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const total = specificity + scope + actionability + doneCondition;
|
|
95
|
+
|
|
96
|
+
let grade: string;
|
|
97
|
+
if (total >= 90) grade = "A+";
|
|
98
|
+
else if (total >= 85) grade = "A";
|
|
99
|
+
else if (total >= 80) grade = "A-";
|
|
100
|
+
else if (total >= 75) grade = "B+";
|
|
101
|
+
else if (total >= 70) grade = "B";
|
|
102
|
+
else if (total >= 65) grade = "B-";
|
|
103
|
+
else if (total >= 60) grade = "C+";
|
|
104
|
+
else if (total >= 55) grade = "C";
|
|
105
|
+
else if (total >= 45) grade = "D";
|
|
106
|
+
else grade = "F";
|
|
107
|
+
|
|
108
|
+
if (feedback.length === 0) {
|
|
109
|
+
feedback.push("🏆 Excellent prompt! Clear target, scope, action, and done condition.");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return { specificity, scope, actionability, doneCondition, total, grade, feedback };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function registerPromptScore(server: McpServer): void {
|
|
116
|
+
server.tool(
|
|
117
|
+
"prompt_score",
|
|
118
|
+
"Score a prompt on specificity, scope, actionability, and done-condition. Returns a letter grade with specific improvement tips.",
|
|
119
|
+
{
|
|
120
|
+
prompt: z.string().describe("The prompt text to score"),
|
|
121
|
+
},
|
|
122
|
+
async ({ prompt }) => {
|
|
123
|
+
const result = scorePrompt(prompt);
|
|
124
|
+
const history = await loadHistory();
|
|
125
|
+
history.scores.push(result.total);
|
|
126
|
+
await saveHistory(history);
|
|
127
|
+
|
|
128
|
+
const avg = history.scores.length > 0
|
|
129
|
+
? (history.scores.reduce((a, b) => a + b, 0) / history.scores.length).toFixed(0)
|
|
130
|
+
: result.total.toString();
|
|
131
|
+
|
|
132
|
+
const report = [
|
|
133
|
+
`🎯 Prompt Score: ${result.grade} (${result.total}/100)`,
|
|
134
|
+
`────────────────────────`,
|
|
135
|
+
`Specificity: ${result.specificity}/25 ${result.specificity >= 20 ? "✓" : "✗"}`,
|
|
136
|
+
`Scope: ${result.scope}/25 ${result.scope >= 20 ? "✓" : "✗"}`,
|
|
137
|
+
`Actionability: ${result.actionability}/25 ${result.actionability >= 20 ? "✓" : "✗"}`,
|
|
138
|
+
`Done condition: ${result.doneCondition}/25 ${result.doneCondition >= 20 ? "✓" : "✗"}`,
|
|
139
|
+
``,
|
|
140
|
+
...result.feedback,
|
|
141
|
+
``,
|
|
142
|
+
`Session average: ${avg}/100 (${history.scores.length} prompts scored)`,
|
|
143
|
+
].join("\n");
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
content: [{ type: "text" as const, text: report }],
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
);
|
|
150
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import * as fs from "fs";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
import { findSessionDirs, findSessionFiles } from "../lib/session-parser.js";
|
|
6
|
+
|
|
7
|
+
interface SessionInfo {
|
|
8
|
+
project: string;
|
|
9
|
+
projectName: string;
|
|
10
|
+
sessionId: string;
|
|
11
|
+
path: string;
|
|
12
|
+
mtime: Date;
|
|
13
|
+
size: number;
|
|
14
|
+
branch?: string;
|
|
15
|
+
lastMessage?: string;
|
|
16
|
+
messageCount?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function formatAge(ms: number): string {
|
|
20
|
+
const mins = Math.floor(ms / 60000);
|
|
21
|
+
if (mins < 1) return "just now";
|
|
22
|
+
if (mins < 60) return `${mins}min ago`;
|
|
23
|
+
const hours = Math.floor(mins / 60);
|
|
24
|
+
if (hours < 24) return `${hours}h ago`;
|
|
25
|
+
const days = Math.floor(hours / 24);
|
|
26
|
+
return `${days}d ago`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function formatSize(bytes: number): string {
|
|
30
|
+
if (bytes < 1024) return `${bytes}B`;
|
|
31
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)}KB`;
|
|
32
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function readLastLines(filePath: string, n: number): string[] {
|
|
36
|
+
try {
|
|
37
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
38
|
+
const lines = content.trim().split("\n");
|
|
39
|
+
return lines.slice(-n);
|
|
40
|
+
} catch {
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function readFirstLine(filePath: string): string | null {
|
|
46
|
+
try {
|
|
47
|
+
const fd = fs.openSync(filePath, "r");
|
|
48
|
+
const buf = Buffer.alloc(4096);
|
|
49
|
+
const bytesRead = fs.readSync(fd, buf, 0, 4096, 0);
|
|
50
|
+
fs.closeSync(fd);
|
|
51
|
+
const text = buf.toString("utf-8", 0, bytesRead);
|
|
52
|
+
const nl = text.indexOf("\n");
|
|
53
|
+
return nl >= 0 ? text.slice(0, nl) : text;
|
|
54
|
+
} catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function extractBranchFromSession(firstLine: string | null): string | undefined {
|
|
60
|
+
if (!firstLine) return undefined;
|
|
61
|
+
try {
|
|
62
|
+
const obj = JSON.parse(firstLine);
|
|
63
|
+
return obj.branch || obj.metadata?.branch;
|
|
64
|
+
} catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function extractMessageContent(line: string): string | undefined {
|
|
70
|
+
try {
|
|
71
|
+
const obj = JSON.parse(line);
|
|
72
|
+
if (obj.type === "human" || obj.type === "prompt") return obj.content?.slice(0, 120);
|
|
73
|
+
if (obj.type === "assistant") return obj.content?.slice(0, 120);
|
|
74
|
+
if (obj.message?.content) return obj.message.content.slice(0, 120);
|
|
75
|
+
if (typeof obj.content === "string") return obj.content.slice(0, 120);
|
|
76
|
+
} catch {
|
|
77
|
+
// not JSON
|
|
78
|
+
}
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function registerScanSessions(server: McpServer) {
|
|
83
|
+
server.tool(
|
|
84
|
+
"scan_sessions",
|
|
85
|
+
"Live scan of Claude Code sessions on disk. Shows active and recent sessions, file sizes, and optionally last messages. Detects parallel sessions on the same branch.",
|
|
86
|
+
{
|
|
87
|
+
project: z.string().optional().describe("Project name or path. If omitted, scans all projects."),
|
|
88
|
+
active_only: z.boolean().default(false).describe("Only show sessions modified in last hour"),
|
|
89
|
+
include_messages: z.number().default(0).describe("Include last N messages from each session"),
|
|
90
|
+
sort: z.enum(["recent", "size", "messages"]).default("recent"),
|
|
91
|
+
},
|
|
92
|
+
async (params) => {
|
|
93
|
+
const allDirs = findSessionDirs();
|
|
94
|
+
const filtered = params.project
|
|
95
|
+
? allDirs.filter(
|
|
96
|
+
(d) =>
|
|
97
|
+
d.projectName === params.project ||
|
|
98
|
+
d.project === params.project ||
|
|
99
|
+
d.projectName.toLowerCase().includes(params.project!.toLowerCase())
|
|
100
|
+
)
|
|
101
|
+
: allDirs;
|
|
102
|
+
|
|
103
|
+
if (filtered.length === 0) {
|
|
104
|
+
return { content: [{ type: "text", text: "## Sessions\n_No session directories found._" }] };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Gather all sessions
|
|
108
|
+
const sessions: SessionInfo[] = [];
|
|
109
|
+
for (const dir of filtered) {
|
|
110
|
+
const files = findSessionFiles(dir.sessionDir);
|
|
111
|
+
for (const f of files) {
|
|
112
|
+
let size = 0;
|
|
113
|
+
try {
|
|
114
|
+
size = fs.statSync(f.path).size;
|
|
115
|
+
} catch {}
|
|
116
|
+
|
|
117
|
+
const firstLine = readFirstLine(f.path);
|
|
118
|
+
const branch = extractBranchFromSession(firstLine);
|
|
119
|
+
|
|
120
|
+
const info: SessionInfo = {
|
|
121
|
+
project: dir.project,
|
|
122
|
+
projectName: dir.projectName,
|
|
123
|
+
sessionId: f.sessionId,
|
|
124
|
+
path: f.path,
|
|
125
|
+
mtime: f.mtime,
|
|
126
|
+
size,
|
|
127
|
+
branch,
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
if (params.include_messages > 0) {
|
|
131
|
+
const lastLines = readLastLines(f.path, params.include_messages);
|
|
132
|
+
const messages = lastLines.map(extractMessageContent).filter(Boolean) as string[];
|
|
133
|
+
info.lastMessage = messages[messages.length - 1];
|
|
134
|
+
info.messageCount = messages.length;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
sessions.push(info);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const now = Date.now();
|
|
142
|
+
const ONE_HOUR = 3600000;
|
|
143
|
+
|
|
144
|
+
// Filter active only
|
|
145
|
+
const visible = params.active_only
|
|
146
|
+
? sessions.filter((s) => now - s.mtime.getTime() < ONE_HOUR)
|
|
147
|
+
: sessions;
|
|
148
|
+
|
|
149
|
+
if (visible.length === 0) {
|
|
150
|
+
return { content: [{ type: "text", text: "## Sessions\n_No active sessions found._" }] };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Sort
|
|
154
|
+
if (params.sort === "recent") visible.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
155
|
+
else if (params.sort === "size") visible.sort((a, b) => b.size - a.size);
|
|
156
|
+
else visible.sort((a, b) => (b.messageCount || 0) - (a.messageCount || 0));
|
|
157
|
+
|
|
158
|
+
// Group by project
|
|
159
|
+
const byProject = new Map<string, SessionInfo[]>();
|
|
160
|
+
for (const s of visible) {
|
|
161
|
+
if (!byProject.has(s.projectName)) byProject.set(s.projectName, []);
|
|
162
|
+
byProject.get(s.projectName)!.push(s);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const lines: string[] = ["## Active Sessions", ""];
|
|
166
|
+
const warnings: string[] = [];
|
|
167
|
+
|
|
168
|
+
for (const [projName, projSessions] of byProject) {
|
|
169
|
+
const activeCount = projSessions.filter((s) => now - s.mtime.getTime() < ONE_HOUR).length;
|
|
170
|
+
lines.push(`### ${projName} (${projSessions.length} session${projSessions.length !== 1 ? "s" : ""}${activeCount > 0 ? `, ${activeCount} active` : ""})`);
|
|
171
|
+
|
|
172
|
+
for (const s of projSessions) {
|
|
173
|
+
const isActive = now - s.mtime.getTime() < ONE_HOUR;
|
|
174
|
+
const prefix = isActive ? "⚡" : " ";
|
|
175
|
+
const branch = s.branch || "unknown";
|
|
176
|
+
const age = formatAge(now - s.mtime.getTime());
|
|
177
|
+
const size = formatSize(s.size);
|
|
178
|
+
|
|
179
|
+
lines.push(`${prefix} **${s.sessionId.slice(0, 8)}** — ${branch} — Last active: ${age} — ${size}`);
|
|
180
|
+
|
|
181
|
+
if (s.lastMessage) {
|
|
182
|
+
lines.push(` Last: "${s.lastMessage}"`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Detect parallel sessions (same branch, both active in last hour)
|
|
187
|
+
const branchGroups = new Map<string, SessionInfo[]>();
|
|
188
|
+
for (const s of projSessions) {
|
|
189
|
+
if (!s.branch || now - s.mtime.getTime() >= ONE_HOUR) continue;
|
|
190
|
+
if (!branchGroups.has(s.branch)) branchGroups.set(s.branch, []);
|
|
191
|
+
branchGroups.get(s.branch)!.push(s);
|
|
192
|
+
}
|
|
193
|
+
for (const [branch, group] of branchGroups) {
|
|
194
|
+
if (group.length > 1) {
|
|
195
|
+
warnings.push(`⚠️ Parallel session warning: ${projName} has ${group.length} sessions on \`${branch}\` branch`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
lines.push("");
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (warnings.length > 0) {
|
|
203
|
+
lines.push(...warnings);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
207
|
+
}
|
|
208
|
+
);
|
|
209
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// CATEGORY 1: scope_work — Plans
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { run, getBranch, getRecentCommits, getStatus } from "../lib/git.js";
|
|
5
|
+
import { readIfExists, findWorkspaceDocs, PROJECT_DIR } from "../lib/files.js";
|
|
6
|
+
import { searchSemantic } from "../lib/timeline-db.js";
|
|
7
|
+
import { getRelatedProjects } from "../lib/config.js";
|
|
8
|
+
import { now } from "../lib/state.js";
|
|
9
|
+
import { existsSync } from "fs";
|
|
10
|
+
import { join, normalize, resolve, basename } from "path";
|
|
11
|
+
|
|
12
|
+
const STOP_WORDS = new Set([
|
|
13
|
+
"the", "and", "for", "with", "from", "that", "this", "should", "would", "could",
|
|
14
|
+
"into", "have", "been", "will", "just", "also", "when", "then", "than", "what",
|
|
15
|
+
"where", "which", "there", "their", "about", "after", "before", "does", "make",
|
|
16
|
+
"like", "some", "each", "only", "need", "want", "please", "update", "change",
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
/** Shell-escape a string for use inside single quotes */
|
|
20
|
+
function shellEscape(s: string): string {
|
|
21
|
+
return s.replace(/'/g, "'\\''");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Safely parse git porcelain status lines */
|
|
25
|
+
function parsePortelainFiles(porcelain: string): string[] {
|
|
26
|
+
if (!porcelain.trim()) return [];
|
|
27
|
+
return porcelain.split("\n").filter(Boolean).flatMap((line) => {
|
|
28
|
+
// Porcelain format: XY filename or XY orig -> renamed
|
|
29
|
+
if (line.length < 4) return [];
|
|
30
|
+
const status = line.slice(0, 2);
|
|
31
|
+
const rest = line.slice(3);
|
|
32
|
+
// Handle renames/copies: "R old -> new"
|
|
33
|
+
if (status.startsWith("R") || status.startsWith("C")) {
|
|
34
|
+
const parts = rest.split(" -> ");
|
|
35
|
+
return parts.map((p) => p.trim()).filter(Boolean);
|
|
36
|
+
}
|
|
37
|
+
return [rest.trim()];
|
|
38
|
+
}).filter(Boolean);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Validate a dir path is within PROJECT_DIR (no traversal) */
|
|
42
|
+
function isSafePath(dir: string): boolean {
|
|
43
|
+
const resolved = resolve(PROJECT_DIR, dir);
|
|
44
|
+
return resolved.startsWith(resolve(PROJECT_DIR));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Search for relevant cross-project context for scoping */
|
|
48
|
+
async function searchRelatedProjectContext(task: string): Promise<string[]> {
|
|
49
|
+
const relatedProjects = getRelatedProjects();
|
|
50
|
+
if (relatedProjects.length === 0) return [];
|
|
51
|
+
|
|
52
|
+
// Generate targeted search queries for scoping
|
|
53
|
+
const queries = [
|
|
54
|
+
`${task} interface type definition`,
|
|
55
|
+
`${task} API endpoint service`,
|
|
56
|
+
`${task} component hook pattern`,
|
|
57
|
+
`${task} database schema model`,
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
const contextItems: string[] = [];
|
|
61
|
+
|
|
62
|
+
for (const query of queries) {
|
|
63
|
+
try {
|
|
64
|
+
const results = await searchSemantic(query, {
|
|
65
|
+
project_dirs: relatedProjects,
|
|
66
|
+
limit: 2,
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
for (const result of results) {
|
|
70
|
+
const projectName = basename(result.project);
|
|
71
|
+
const content = result.content.slice(0, 150);
|
|
72
|
+
const fileInfo = result.source_file ? ` (${result.source_file})` : "";
|
|
73
|
+
contextItems.push(`- **${projectName}:** ${content}${fileInfo}`);
|
|
74
|
+
}
|
|
75
|
+
} catch {
|
|
76
|
+
// Skip if search fails
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return contextItems.slice(0, 4); // Limit to top 4 context items
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function registerScopeWork(server: McpServer): void {
|
|
84
|
+
server.tool(
|
|
85
|
+
"scope_work",
|
|
86
|
+
`Break down a task into a structured execution plan BEFORE writing any code. Call this tool whenever you receive a new task, feature request, or bug report. It analyzes the current project state (git, files, workspace docs) and returns an ordered plan with scope boundaries, complexity estimate, and done conditions. Use this to avoid scope creep and ensure you touch only what's needed.`,
|
|
87
|
+
{
|
|
88
|
+
task: z.string().describe("The raw user task or request to plan"),
|
|
89
|
+
branch: z.string().optional().describe("Git branch to scope against (defaults to current branch)"),
|
|
90
|
+
},
|
|
91
|
+
async ({ task, branch }) => {
|
|
92
|
+
const timestamp = now();
|
|
93
|
+
const currentBranch = branch ?? getBranch();
|
|
94
|
+
const recentCommits = getRecentCommits(10);
|
|
95
|
+
const porcelain = run("git status --porcelain");
|
|
96
|
+
const dirtyFiles = parsePortelainFiles(porcelain);
|
|
97
|
+
const diffStat = dirtyFiles.length > 0 ? run("git diff --stat") : "(clean working tree)";
|
|
98
|
+
|
|
99
|
+
// Scan for relevant files based on task keywords
|
|
100
|
+
const keywords = task.toLowerCase().split(/\s+/);
|
|
101
|
+
const scanDirs = [
|
|
102
|
+
{ pattern: "test", dirs: ["tests/", "test/", "__tests__/", "spec/"] },
|
|
103
|
+
{ pattern: "api", dirs: ["api/", "src/api/", "app/api/", "routes/"] },
|
|
104
|
+
{ pattern: "app", dirs: ["app/", "src/app/", "src/pages/"] },
|
|
105
|
+
{ pattern: "database", dirs: ["prisma/", "migrations/", "db/"] },
|
|
106
|
+
{ pattern: "prisma", dirs: ["prisma/"] },
|
|
107
|
+
{ pattern: "schema", dirs: ["prisma/", "schema/", "schemas/"] },
|
|
108
|
+
{ pattern: "component", dirs: ["components/", "src/components/"] },
|
|
109
|
+
{ pattern: "hook", dirs: ["hooks/", "src/hooks/"] },
|
|
110
|
+
{ pattern: "style", dirs: ["styles/", "src/styles/"] },
|
|
111
|
+
{ pattern: "config", dirs: ["config/", ".config/"] },
|
|
112
|
+
];
|
|
113
|
+
|
|
114
|
+
const relevantDirs = new Set<string>();
|
|
115
|
+
for (const { pattern, dirs } of scanDirs) {
|
|
116
|
+
if (keywords.some((k) => k.includes(pattern))) {
|
|
117
|
+
dirs.forEach((d) => relevantDirs.add(d));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Grep for files matching task keywords — sanitize for shell safety
|
|
122
|
+
let matchedFiles = "";
|
|
123
|
+
const grepTerms = keywords
|
|
124
|
+
.filter((k) => k.length > 3 && !STOP_WORDS.has(k))
|
|
125
|
+
.map((k) => k.replace(/[^a-z0-9_-]/g, "")) // strip non-alphanumeric to prevent injection
|
|
126
|
+
.filter((k) => k.length > 2)
|
|
127
|
+
.slice(0, 5);
|
|
128
|
+
if (grepTerms.length > 0) {
|
|
129
|
+
const pattern = shellEscape(grepTerms.join("|"));
|
|
130
|
+
matchedFiles = run(`git ls-files | head -500 | grep -iE '${pattern}' | head -30`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Check which relevant dirs actually exist (with path traversal protection)
|
|
134
|
+
const existingDirs: string[] = [];
|
|
135
|
+
for (const dir of relevantDirs) {
|
|
136
|
+
if (isSafePath(dir) && existsSync(join(PROJECT_DIR, dir))) {
|
|
137
|
+
existingDirs.push(dir);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Workspace docs
|
|
142
|
+
const workspaceDocs = findWorkspaceDocs();
|
|
143
|
+
const docEntries = Object.entries(workspaceDocs);
|
|
144
|
+
|
|
145
|
+
// Project instructions
|
|
146
|
+
const claudeMd = readIfExists("CLAUDE.md", 50);
|
|
147
|
+
const agentsMd = readIfExists(".claude/AGENTS.md", 50);
|
|
148
|
+
|
|
149
|
+
// Complexity estimate — count unique files from matched + dirty
|
|
150
|
+
const allTouchedFiles = [
|
|
151
|
+
...matchedFiles.split("\n").filter(Boolean),
|
|
152
|
+
...dirtyFiles,
|
|
153
|
+
];
|
|
154
|
+
const uniqueFiles = [...new Set(allTouchedFiles)];
|
|
155
|
+
const fileCount = uniqueFiles.length;
|
|
156
|
+
const complexity = fileCount <= 3 ? "SMALL" : fileCount <= 10 ? "MEDIUM" : "LARGE";
|
|
157
|
+
|
|
158
|
+
const dirLine = existingDirs.length > 0
|
|
159
|
+
? `**Relevant directories:** ${existingDirs.map((d) => `\`${d}\``).join(", ")}`
|
|
160
|
+
: "";
|
|
161
|
+
|
|
162
|
+
const docLines = docEntries.length > 0
|
|
163
|
+
? docEntries.map(([name]) => `- \`${name}\``).join("\n")
|
|
164
|
+
: "- (none found)";
|
|
165
|
+
|
|
166
|
+
// Get cross-project context
|
|
167
|
+
const relatedContext = await searchRelatedProjectContext(task);
|
|
168
|
+
|
|
169
|
+
const plan = `# 📋 Scope Work Plan
|
|
170
|
+
**Generated:** ${timestamp}
|
|
171
|
+
**Task:** ${task}
|
|
172
|
+
**Branch:** ${currentBranch}
|
|
173
|
+
**Complexity:** ${complexity} (${fileCount} files in scope)
|
|
174
|
+
|
|
175
|
+
---
|
|
176
|
+
|
|
177
|
+
## 🔍 Current State
|
|
178
|
+
**Recent commits:**
|
|
179
|
+
\`\`\`
|
|
180
|
+
${recentCommits || "(no commits)"}
|
|
181
|
+
\`\`\`
|
|
182
|
+
|
|
183
|
+
**Working tree:**
|
|
184
|
+
\`\`\`
|
|
185
|
+
${porcelain || "(clean)"}
|
|
186
|
+
\`\`\`
|
|
187
|
+
|
|
188
|
+
${diffStat !== "(clean working tree)" ? `**Uncommitted changes:**\n\`\`\`\n${diffStat}\n\`\`\`` : ""}
|
|
189
|
+
|
|
190
|
+
## 📁 Relevant Files
|
|
191
|
+
${matchedFiles ? matchedFiles.split("\n").filter(Boolean).map((f) => `- \`${f}\``).join("\n") : "- (no direct file matches — explore manually)"}
|
|
192
|
+
|
|
193
|
+
${dirLine}
|
|
194
|
+
|
|
195
|
+
## 📚 Workspace Docs
|
|
196
|
+
${docLines}
|
|
197
|
+
${claudeMd ? "- `CLAUDE.md` exists (project instructions)" : ""}
|
|
198
|
+
${agentsMd ? "- `.claude/AGENTS.md` exists" : ""}
|
|
199
|
+
|
|
200
|
+
${relatedContext.length > 0 ? `## 🔗 Related Project Context\n${relatedContext.join("\n")}\n` : ""}
|
|
201
|
+
---
|
|
202
|
+
|
|
203
|
+
## 📝 Execution Plan
|
|
204
|
+
|
|
205
|
+
### Steps:
|
|
206
|
+
1. **Understand** — Read the relevant files listed above
|
|
207
|
+
2. **Plan tests** — Identify or write failing tests first
|
|
208
|
+
3. **Implement** — Make the minimal changes needed
|
|
209
|
+
4. **Verify** — Run tests, check types, lint
|
|
210
|
+
5. **Clean up** — Remove debug code, check diff is tight
|
|
211
|
+
|
|
212
|
+
### Files to touch:
|
|
213
|
+
${uniqueFiles.length > 0 ? uniqueFiles.slice(0, 20).map((f) => `- [ ] \`${f}\``).join("\n") : "- [ ] (determine after reading codebase)"}
|
|
214
|
+
|
|
215
|
+
### Tests to run:
|
|
216
|
+
- [ ] Identify test files related to changed code
|
|
217
|
+
- [ ] Run full test suite before AND after changes
|
|
218
|
+
|
|
219
|
+
### 🚫 Scope Boundaries:
|
|
220
|
+
- Do NOT refactor unrelated code
|
|
221
|
+
- Do NOT update dependencies unless required by the task
|
|
222
|
+
- Do NOT change config files without explicit instruction
|
|
223
|
+
${dirtyFiles.length > 0 ? "- ⚠️ Working tree is dirty — do NOT commit unrelated changes" : ""}
|
|
224
|
+
|
|
225
|
+
### ✅ Done Conditions:
|
|
226
|
+
- [ ] All planned steps completed
|
|
227
|
+
- [ ] Tests pass
|
|
228
|
+
- [ ] Types check
|
|
229
|
+
- [ ] Diff reviewed — only expected changes present
|
|
230
|
+
- [ ] No TODOs or debug code left behind
|
|
231
|
+
|
|
232
|
+
---
|
|
233
|
+
*Use this plan as your checklist. Deviate only with explicit user approval.*`;
|
|
234
|
+
|
|
235
|
+
return { content: [{ type: "text" as const, text: plan }] };
|
|
236
|
+
}
|
|
237
|
+
);
|
|
238
|
+
}
|