@maximalabs/dev-mcp-suite 0.0.0-stage → 3.6.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.
Files changed (68) hide show
  1. package/.env.example +69 -0
  2. package/CHANGELOG.md +271 -0
  3. package/CODEX_DEV_MCP_GUIDE.md +297 -0
  4. package/LICENSE +21 -0
  5. package/README.md +193 -2
  6. package/armada/package.json +14 -0
  7. package/armada/server.js +329 -0
  8. package/backfill-sessions-v2.mjs +288 -0
  9. package/bin/_meta.mjs +73 -0
  10. package/bin/armada-mcp.mjs +12 -0
  11. package/bin/checkpoint.mjs +9 -0
  12. package/bin/context-pack.mjs +9 -0
  13. package/bin/devjournal.mjs +9 -0
  14. package/bin/init.mjs +25 -0
  15. package/bin/project-memory.mjs +10 -0
  16. package/bin/provider-smoke.mjs +278 -0
  17. package/bin/prune.mjs +158 -0
  18. package/bin/stats.mjs +101 -0
  19. package/bin/ui.mjs +5 -0
  20. package/checkpoint/package.json +14 -0
  21. package/checkpoint/server.js +318 -0
  22. package/context-pack/package.json +14 -0
  23. package/context-pack/server.js +747 -0
  24. package/devjournal/compress.js +75 -0
  25. package/devjournal/env.js +3 -0
  26. package/devjournal/package.json +14 -0
  27. package/devjournal/provider-chain.js +109 -0
  28. package/devjournal/rerank.js +120 -0
  29. package/devjournal/server.js +415 -0
  30. package/docs/ROADMAP.md +77 -0
  31. package/docs/clients/antigravity.md +52 -0
  32. package/docs/clients/claude-code.md +46 -0
  33. package/docs/clients/codex.md +39 -0
  34. package/docs/clients/generic-mcp.md +45 -0
  35. package/docs/clients/hermes.md +48 -0
  36. package/docs/configuration.md +123 -0
  37. package/docs/privacy.md +39 -0
  38. package/docs/providers.md +13 -0
  39. package/docs/superpowers/plans/2026-06-15-hardening-v1-2-implementation.md +60 -0
  40. package/docs/superpowers/plans/2026-06-15-provider-chain-v1-1-implementation.md +65 -0
  41. package/docs/superpowers/plans/2026-06-15-provider-client-agnostic-config.md +41 -0
  42. package/docs/superpowers/plans/2026-06-15-trust-release-implementation.md +62 -0
  43. package/docs/superpowers/plans/2026-06-18-v1-5-0-knowledge-graph.md +792 -0
  44. package/docs/superpowers/specs/2026-06-15-provider-chain-v1-1-design.md +89 -0
  45. package/docs/superpowers/specs/2026-06-15-trust-release-design.md +164 -0
  46. package/docs/superpowers/specs/2026-06-18-dev-mcp-suite-v1-5-0-knowledge-graph-design.md +386 -0
  47. package/docs/superpowers/specs/2026-07-22-v2-0-0-peak-intelligence.md +50 -0
  48. package/docs/superpowers/specs/2026-07-22-v3-0-0-god-tier.md +32 -0
  49. package/lib/init-wizard.js +120 -0
  50. package/lib/provider-smoke.js +234 -0
  51. package/lib/prune.js +114 -0
  52. package/lib/stats.js +269 -0
  53. package/lib/ui-server.js +151 -0
  54. package/lib/update-check.js +125 -0
  55. package/package.json +71 -4
  56. package/project-memory/auto-indexer.js +152 -0
  57. package/project-memory/dedup.js +49 -0
  58. package/project-memory/embedding.js +174 -0
  59. package/project-memory/env.js +3 -0
  60. package/project-memory/global-index.js +46 -0
  61. package/project-memory/graph.js +93 -0
  62. package/project-memory/local-embed.js +92 -0
  63. package/project-memory/package.json +14 -0
  64. package/project-memory/provider-chain.js +109 -0
  65. package/project-memory/rerank.js +120 -0
  66. package/project-memory/server.js +931 -0
  67. package/project-memory/swarm.js +56 -0
  68. package/run-tests.mjs +54 -0
@@ -0,0 +1,747 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Context Pack MCP Server for Codex
5
+ *
6
+ * Builds a compact, token-budgeted "briefing" of a project so a fresh
7
+ * session can get oriented without re-pasting files or blowing the context
8
+ * window. Detects stack, shows a pruned tree, surfaces key files, and
9
+ * extracts top-level symbols (functions/classes/exports) heuristically.
10
+ *
11
+ * Tools: pack_overview, pack_tree, pack_outline, pack_search, pack_audit
12
+ */
13
+
14
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
15
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
16
+ import {
17
+ CallToolRequestSchema,
18
+ ListToolsRequestSchema,
19
+ } from "@modelcontextprotocol/sdk/types.js";
20
+ import fs from "fs/promises";
21
+ import path from "path";
22
+ import { execSync } from "child_process";
23
+
24
+ const IGNORE = new Set([
25
+ "node_modules", ".git", ".next", "dist", "build", "target", ".venv",
26
+ "venv", "__pycache__", ".cache", ".turbo", "coverage", ".DS_Store",
27
+ "vendor", ".idea", ".gradle", "out", ".parcel-cache", ".pytest_cache",
28
+ ]);
29
+ const KEY_FILES = [
30
+ "package.json", "pyproject.toml", "requirements.txt", "Cargo.toml",
31
+ "go.mod", "pom.xml", "build.gradle", "composer.json", "Gemfile",
32
+ "README.md", "readme.md", "Makefile", "Dockerfile", "docker-compose.yml",
33
+ "tsconfig.json", "next.config.js", "vite.config.ts", "vite.config.js",
34
+ ".env.example", "AGENTS.md", "CLAUDE.md", "RTK.md",
35
+ ];
36
+ const CODE_EXT = new Set([".js", ".mjs", ".ts", ".tsx", ".jsx", ".py", ".go", ".rs", ".java", ".rb", ".php", ".c", ".cpp", ".h", ".sh"]);
37
+ const MAX_FILE_BYTES = 1_500_000;
38
+ const AUDIT_SENSITIVE_PATTERNS = [
39
+ /^\.env/i, /\.pem$/i, /\.key$/i, /\.p12$/i, /\.pfx$/i,
40
+ /id_rsa/i, /id_ed25519/i, /id_ecdsa/i, /id_dsa/i,
41
+ /known_hosts/i, /authorized_keys/i,
42
+ /credentials/i, /password/i, /secret/i, /token/i,
43
+ /\.htpasswd/i, /\.netrc/i, /npmrc$/i,
44
+ /service[_-]?account.*\.json$/i,
45
+ ];
46
+ const AUDIT_SECRET_CONTENT_RE = [
47
+ /sk-[a-zA-Z0-9]{20,}/i,
48
+ /ghp_[a-zA-Z0-9]{36}/i,
49
+ /gho_[a-zA-Z0-9]{36}/i,
50
+ /glpat-[a-zA-Z0-9\-_]{20}/i,
51
+ /AKIA[0-9A-Z]{16}/i,
52
+ /AIza[0-9A-Za-z_-]{35}/i,
53
+ /bearer\s+[a-zA-Z0-9_\-\.]{20,}/i,
54
+ /api[_-]?key\s*[:=]\s*["']?[a-zA-Z0-9_\-]{16,}/i,
55
+ /password\s*[:=]\s*["']?[^\s"']{6,}/i,
56
+ ];
57
+ const AUDIT_LARGE_WARN = 100_000;
58
+ const AUDIT_LARGE_CRIT = 1_000_000;
59
+ const AUDIT_MAX_SCAN = 16_384;
60
+
61
+ function isSensitiveName(filename) {
62
+ return AUDIT_SENSITIVE_PATTERNS.some((pattern) => pattern.test(filename));
63
+ }
64
+
65
+ function resolveDir(dir) { return path.resolve(dir || process.cwd()); }
66
+
67
+ async function walk(base, rel = "", out = [], depth = 0, maxDepth = 8) {
68
+ if (depth > maxDepth) return out;
69
+ let entries;
70
+ try { entries = await fs.readdir(path.join(base, rel), { withFileTypes: true }); } catch { return out; }
71
+ entries.sort((a, b) => a.name.localeCompare(b.name));
72
+ for (const e of entries) {
73
+ if (IGNORE.has(e.name) || e.name.startsWith(".") && e.isDirectory() && e.name !== ".github") continue;
74
+ const childRel = path.join(rel, e.name);
75
+ if (e.isDirectory()) { out.push({ rel: childRel, dir: true, depth }); await walk(base, childRel, out, depth + 1, maxDepth); }
76
+ else if (e.isFile()) out.push({ rel: childRel, dir: false, depth });
77
+ }
78
+ return out;
79
+ }
80
+
81
+ async function detectStack(root, files) {
82
+ const names = new Set(files.filter((f) => !f.dir).map((f) => path.basename(f.rel)));
83
+ const stack = [];
84
+ if (names.has("package.json")) {
85
+ stack.push("Node/JS");
86
+ try {
87
+ const pkg = JSON.parse(await fs.readFile(path.join(root, "package.json"), "utf8"));
88
+ const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
89
+ for (const [d, label] of [["next", "Next.js"], ["react", "React"], ["vue", "Vue"], ["svelte", "Svelte"], ["express", "Express"], ["fastify", "Fastify"], ["typescript", "TypeScript"], ["tailwindcss", "Tailwind"], ["prisma", "Prisma"], ["vite", "Vite"]]) {
90
+ if (deps[d]) stack.push(label);
91
+ }
92
+ } catch { /* ignore */ }
93
+ }
94
+ if (names.has("pyproject.toml") || names.has("requirements.txt")) stack.push("Python");
95
+ if (names.has("Cargo.toml")) stack.push("Rust");
96
+ if (names.has("go.mod")) stack.push("Go");
97
+ if (names.has("pom.xml") || names.has("build.gradle")) stack.push("Java/JVM");
98
+ if (names.has("composer.json")) stack.push("PHP");
99
+ if (names.has("Gemfile")) stack.push("Ruby");
100
+ if (names.has("Dockerfile") || names.has("docker-compose.yml")) stack.push("Docker");
101
+ return [...new Set(stack)];
102
+ }
103
+
104
+ function extractSymbols(content, ext) {
105
+ const syms = [];
106
+ const lines = content.split("\n");
107
+ const patterns = [
108
+ /^\s*export\s+(?:default\s+)?(?:async\s+)?function\s+([A-Za-z0-9_]+)/,
109
+ /^\s*export\s+(?:const|let|var)\s+([A-Za-z0-9_]+)\s*=/,
110
+ /^\s*export\s+(?:abstract\s+)?class\s+([A-Za-z0-9_]+)/,
111
+ /^\s*(?:async\s+)?function\s+([A-Za-z0-9_]+)/,
112
+ /^\s*class\s+([A-Za-z0-9_]+)/,
113
+ /^\s*def\s+([A-Za-z0-9_]+)/,
114
+ /^\s*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z0-9_]+)/,
115
+ /^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z0-9_]+)/,
116
+ /^\s*(?:public|private|protected)\s+(?:static\s+)?[A-Za-z0-9_<>\[\]]+\s+([A-Za-z0-9_]+)\s*\(/,
117
+ ];
118
+ for (let i = 0; i < lines.length; i++) {
119
+ for (const re of patterns) {
120
+ const m = lines[i].match(re);
121
+ if (m) { syms.push({ name: m[1], line: i + 1 }); break; }
122
+ }
123
+ if (syms.length >= 80) break;
124
+ }
125
+ return syms;
126
+ }
127
+
128
+ class ContextPackServer {
129
+ constructor() {
130
+ this.server = new Server({ name: "context-pack", version: "1.0.0" }, { capabilities: { tools: {} } });
131
+ this.setup();
132
+ }
133
+
134
+ setup() {
135
+ this.server.setRequestHandler(ListToolsRequestSchema, () => ({
136
+ tools: [
137
+ {
138
+ name: "pack_find_todos",
139
+ description: "Scan the codebase for TODO, FIXME, HACK, and NOTE comments to surface technical debt.",
140
+ inputSchema: {
141
+ type: "object",
142
+ properties: {
143
+ dir: { type: "string", description: "Project directory (defaults to CWD)" }
144
+ }
145
+ }
146
+ },
147
+ {
148
+ name: "pack_overview",
149
+ description: "Build a compact project briefing: detected stack, key config files (with short excerpts), top-level dirs, and file counts. Call at session start to get oriented cheaply.",
150
+ inputSchema: {
151
+ type: "object",
152
+ properties: {
153
+ dir: { type: "string", description: "Project directory (defaults to CWD)" },
154
+ include_readme: { type: "boolean", description: "Include README excerpt", default: true },
155
+ },
156
+ },
157
+ },
158
+ {
159
+ name: "pack_tree",
160
+ description: "Print a pruned directory tree (ignores node_modules/.git/build dirs).",
161
+ inputSchema: {
162
+ type: "object",
163
+ properties: {
164
+ dir: { type: "string", description: "Project directory (defaults to CWD)" },
165
+ max_depth: { type: "number", description: "Max depth", default: 3 },
166
+ max_entries: { type: "number", description: "Max lines", default: 200 },
167
+ },
168
+ },
169
+ },
170
+ {
171
+ name: "pack_outline",
172
+ description: "Extract top-level symbols (functions/classes/exports) from a source file without dumping the whole file.",
173
+ inputSchema: {
174
+ type: "object",
175
+ properties: {
176
+ file: { type: "string", description: "Path to source file (absolute or relative to dir)" },
177
+ dir: { type: "string", description: "Base directory (defaults to CWD)" },
178
+ },
179
+ required: ["file"],
180
+ },
181
+ },
182
+ {
183
+ name: "pack_search",
184
+ description: "Find files whose name or path matches a substring (fast, ignores build dirs). Returns relative paths.",
185
+ inputSchema: {
186
+ type: "object",
187
+ properties: {
188
+ query: { type: "string", description: "Substring to match in path" },
189
+ dir: { type: "string", description: "Project directory (defaults to CWD)" },
190
+ limit: { type: "number", description: "Max results", default: 50 },
191
+ },
192
+ required: ["query"],
193
+ },
194
+ },
195
+ {
196
+ name: "pack_audit",
197
+ description: "Audit project for security risks, leaked secrets/credentials, missing .gitignore, uncommitted sensitive files, and overly large files.",
198
+ inputSchema: {
199
+ type: "object",
200
+ properties: {
201
+ dir: { type: "string", description: "Project directory (defaults to CWD)" },
202
+ strict: { type: "boolean", description: "Flag missing .gitignore as critical instead of warn", default: false },
203
+ },
204
+ },
205
+ },
206
+ {
207
+ name: "pack_impact",
208
+ description: "Analyze dependency blast-radius and callers for a specific file to prevent breaking downstream code.",
209
+ inputSchema: {
210
+ type: "object",
211
+ properties: {
212
+ targetFile: { type: "string", description: "Relative path to target file (e.g. 'lib/stats.js')" },
213
+ dir: { type: "string", description: "Project directory (defaults to CWD)" },
214
+ maxDepth: { type: "number", description: "Traversal depth", default: 3 },
215
+ },
216
+ required: ["targetFile"],
217
+ },
218
+ },
219
+ {
220
+ name: "pack_guard",
221
+ description: "Execute self-healing diagnostic pre-flight checks (typecheck, lint, test) and return structured findings.",
222
+ inputSchema: {
223
+ type: "object",
224
+ properties: {
225
+ dir: { type: "string", description: "Project directory (defaults to CWD)" },
226
+ checkType: { type: "string", description: "Check type: 'all' | 'typecheck' | 'test' | 'lint'", default: "all" },
227
+ },
228
+ },
229
+ },
230
+ {
231
+ name: "pack_telemetry",
232
+ description: "Read live dev server logs, runtime errors, and stack traces to diagnose issues without asking user to copy-paste logs.",
233
+ inputSchema: {
234
+ type: "object",
235
+ properties: {
236
+ dir: { type: "string", description: "Project directory (defaults to CWD)" },
237
+ logFile: { type: "string", description: "Path to specific log file (optional)" },
238
+ limit: { type: "number", description: "Max log entries", default: 50 },
239
+ },
240
+ },
241
+ },
242
+ {
243
+ name: "pack_dense_brief",
244
+ description: "Extract an ultra-dense, token-budgeted structural briefing of a file or directory (exports, function signatures, interfaces, routes, line counts) with ~85% token reduction.",
245
+ inputSchema: {
246
+ type: "object",
247
+ properties: {
248
+ target: { type: "string", description: "File path or directory relative to project root" },
249
+ dir: { type: "string", description: "Project directory (defaults to CWD)" },
250
+ maxLines: { type: "number", description: "Max lines in dense output", default: 150 },
251
+ },
252
+ required: ["target"],
253
+ },
254
+ },
255
+ {
256
+ name: "pack_predictive_diff",
257
+ description: "Simulate proposed file changes against caller files to predict breaking contract or API signature changes.",
258
+ inputSchema: {
259
+ type: "object",
260
+ properties: {
261
+ targetFile: { type: "string", description: "Target file path" },
262
+ proposedDiff: { type: "string", description: "Proposed code snippet or diff" },
263
+ dir: { type: "string", description: "Project directory (defaults to CWD)" },
264
+ },
265
+ required: ["targetFile", "proposedDiff"],
266
+ },
267
+ },
268
+ ],
269
+ }));
270
+
271
+ this.server.setRequestHandler(CallToolRequestSchema, async (req) => {
272
+ const { name, arguments: args } = req.params;
273
+ try {
274
+ switch (name) {
275
+ case "pack_overview": return await this.overview(args || {});
276
+ case "pack_tree": return await this.tree(args || {});
277
+ case "pack_outline": return await this.outline(args || {});
278
+ case "pack_search": return await this.search(args || {});
279
+ case "pack_find_todos": return await this.findTodos(args || {});
280
+ case "pack_audit": return await this.audit(args || {});
281
+ case "pack_impact": return await this.impact(args || {});
282
+ case "pack_guard": return await this.guard(args || {});
283
+ case "pack_telemetry": return await this.telemetry(args || {});
284
+ case "pack_predictive_diff": return await this.predictiveDiff(args || {});
285
+ default: throw new Error(`Unknown tool: ${name}`);
286
+ }
287
+ } catch (e) {
288
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
289
+ }
290
+ });
291
+ }
292
+
293
+ async overview({ dir, include_readme = true }) {
294
+ const root = resolveDir(dir);
295
+ const all = await walk(root, "", [], 0, 6);
296
+ const fileCount = all.filter((f) => !f.dir).length;
297
+ const dirCount = all.filter((f) => f.dir).length;
298
+ const stack = await detectStack(root, all);
299
+
300
+ const topDirs = all.filter((f) => f.dir && f.depth === 0).map((f) => f.rel);
301
+ const present = KEY_FILES.filter((k) => all.some((f) => !f.dir && f.rel === k || path.basename(f.rel) === k && f.depth === 0));
302
+
303
+ const sections = [];
304
+ sections.push(`# Project briefing: ${path.basename(root)}`);
305
+ sections.push(`Path: ${root}`);
306
+ sections.push(`Stack: ${stack.length ? stack.join(", ") : "unknown"}`);
307
+ sections.push(`Files: ${fileCount} | Dirs: ${dirCount}`);
308
+ sections.push(`Top-level dirs: ${topDirs.length ? topDirs.join(", ") : "(none)"}`);
309
+ sections.push(`Key files: ${present.length ? present.join(", ") : "(none)"}`);
310
+
311
+ // package.json scripts
312
+ if (present.includes("package.json")) {
313
+ try {
314
+ const pkg = JSON.parse(await fs.readFile(path.join(root, "package.json"), "utf8"));
315
+ if (pkg.scripts) sections.push(`\n## Scripts\n` + Object.entries(pkg.scripts).map(([k, v]) => `- ${k}: ${v}`).join("\n"));
316
+ } catch { /* ignore */ }
317
+ }
318
+
319
+ if (include_readme) {
320
+ const readme = present.find((k) => k.toLowerCase() === "readme.md");
321
+ if (readme) {
322
+ try {
323
+ const txt = await fs.readFile(path.join(root, readme), "utf8");
324
+ sections.push(`\n## README (excerpt)\n` + txt.trim().split("\n").slice(0, 25).join("\n"));
325
+ } catch { /* ignore */ }
326
+ }
327
+ }
328
+
329
+ return { content: [{ type: "text", text: sections.join("\n") }] };
330
+ }
331
+
332
+ async tree({ dir, max_depth = 3, max_entries = 200 }) {
333
+ const root = resolveDir(dir);
334
+ const all = await walk(root, "", [], 0, Math.max(1, Math.min(10, max_depth)));
335
+ const filtered = all.filter((f) => f.depth < max_depth).slice(0, Math.max(10, Math.min(1000, max_entries)));
336
+ const lines = filtered.map((f) => `${" ".repeat(f.depth)}${f.dir ? "📁 " : ""}${path.basename(f.rel)}${f.dir ? "/" : ""}`);
337
+ return { content: [{ type: "text", text: `Tree of ${root} (depth ${max_depth}):\n${lines.join("\n")}${all.length > filtered.length ? `\n... (${all.length - filtered.length} more entries truncated)` : ""}` }] };
338
+ }
339
+
340
+ async outline({ file, dir }) {
341
+ const root = resolveDir(dir);
342
+ const abs = path.isAbsolute(file) ? file : path.join(root, file);
343
+ const stat = await fs.stat(abs).catch(() => null);
344
+ if (!stat || !stat.isFile()) throw new Error(`File not found: ${abs}`);
345
+ if (stat.size > MAX_FILE_BYTES) throw new Error(`File too large (${stat.size} bytes)`);
346
+ const ext = path.extname(abs);
347
+ const content = await fs.readFile(abs, "utf8");
348
+ const totalLines = content.split("\n").length;
349
+ if (!CODE_EXT.has(ext)) {
350
+ return { content: [{ type: "text", text: `${abs}\n${totalLines} lines, ext ${ext || "(none)"} — no symbol extractor for this type. First 20 lines:\n` + content.split("\n").slice(0, 20).join("\n") }] };
351
+ }
352
+ const syms = extractSymbols(content, ext);
353
+ const list = syms.length ? syms.map((s) => ` L${s.line}: ${s.name}`).join("\n") : " (no top-level symbols detected)";
354
+ return { content: [{ type: "text", text: `Outline of ${abs}\n${totalLines} lines, ${syms.length} symbols:\n${list}` }] };
355
+ }
356
+
357
+ async search({ query, dir, limit = 50, include_content = false }) {
358
+ const root = resolveDir(dir);
359
+ const q = String(query).toLowerCase();
360
+ const all = await walk(root, "", [], 0, 10);
361
+ const max = Math.max(1, Math.min(500, limit));
362
+
363
+ if (!include_content) {
364
+ const hits = all.filter((f) => !f.dir && f.rel.toLowerCase().includes(q)).map((f) => f.rel).slice(0, max);
365
+ return { content: [{ type: "text", text: hits.length ? `Matches for "${query}" (${hits.length}):\n` + hits.map((h) => ` ${h}`).join("\n") : `No path matches for "${query}" in ${root}` }] };
366
+ } else {
367
+ const hits = [];
368
+ for (const f of all) {
369
+ if (f.dir) continue;
370
+ if (hits.length >= max) break;
371
+ try {
372
+ const stat = await fs.stat(path.join(root, f.rel));
373
+ if (stat.size > MAX_FILE_BYTES) continue;
374
+ const content = await fs.readFile(path.join(root, f.rel), "utf8");
375
+ if (content.toLowerCase().includes(q)) {
376
+ const lines = content.split('\n');
377
+ for (let i = 0; i < lines.length; i++) {
378
+ if (lines[i].toLowerCase().includes(q)) {
379
+ hits.push(`${f.rel}:${i+1} -> ${lines[i].trim().slice(0, 120)}`);
380
+ if (hits.length >= max) break;
381
+ }
382
+ }
383
+ }
384
+ } catch { /* ignore */ }
385
+ }
386
+ return { content: [{ type: "text", text: hits.length ? `Content matches for "${query}" (${hits.length}):\n` + hits.map((h) => ` ${h}`).join("\n") : `No content matches for "${query}" in ${root}` }] };
387
+ }
388
+ }
389
+
390
+ async findTodos({ dir }) {
391
+ const root = resolveDir(dir);
392
+ const all = await walk(root, "", [], 0, 10);
393
+ const files = all.filter(f => !f.dir && CODE_EXT.has(path.extname(f.rel)));
394
+ const findings = [];
395
+ const todoRe = /(TODO|FIXME|HACK|NOTE)[\s:]+(.*)/i;
396
+
397
+ for (const f of files) {
398
+ try {
399
+ const stat = await fs.stat(path.join(root, f.rel));
400
+ if (stat.size > MAX_FILE_BYTES) continue;
401
+ const content = await fs.readFile(path.join(root, f.rel), "utf8");
402
+ const lines = content.split("\n");
403
+ for (let i = 0; i < lines.length; i++) {
404
+ const m = lines[i].match(todoRe);
405
+ if (m) {
406
+ findings.push(`${f.rel}:${i+1} [${m[1].toUpperCase()}] ${m[2].trim()}`);
407
+ }
408
+ }
409
+ } catch { /* ignore */ }
410
+ }
411
+
412
+ if (findings.length === 0) return { content: [{ type: "text", text: `No TODO/FIXME/HACK found in ${root}` }] };
413
+ return { content: [{ type: "text", text: `Found ${findings.length} technical debt items:\n\n` + findings.slice(0, 500).join("\n") }] };
414
+ }
415
+
416
+
417
+
418
+ async audit({ dir, strict = false }) {
419
+ const root = resolveDir(dir);
420
+ const findings = [];
421
+
422
+ function add(sev, msg, fix) {
423
+ findings.push({ severity: sev, message: msg, fix });
424
+ }
425
+
426
+ // walk
427
+ let all = [];
428
+ try { all = await walk(root, "", [], 0, 6); } catch { /* ignore */ }
429
+ const files = all.filter((f) => !f.dir);
430
+
431
+ // git presence and status
432
+ let gitRoot = null;
433
+ try {
434
+ const g = execSync("git rev-parse --show-toplevel", { cwd: root, encoding: "utf8", timeout: 3000 }).trim();
435
+ gitRoot = g;
436
+ } catch { /* not a git repo */ }
437
+
438
+ let gitStatus = [];
439
+ if (gitRoot) {
440
+ try {
441
+ const out = execSync("git status --porcelain", { cwd: root, encoding: "utf8", timeout: 5000 });
442
+ gitStatus = out.trim().split("\n").filter(Boolean).map((line) => {
443
+ const code = line.slice(0, 2);
444
+ const file = line.slice(3);
445
+ return { code, file, untracked: code === "??" };
446
+ });
447
+ } catch { /* ignore */ }
448
+ }
449
+
450
+ const statusMap = new Map(gitStatus.map((s) => [s.file, s]));
451
+
452
+ // Helpers
453
+ const isGitTracked = (rel) => {
454
+ const s = statusMap.get(rel);
455
+ if (!s) return true; // assume tracked if no status (could be clean tracked)
456
+ return !s.untracked;
457
+ };
458
+ const isIgnored = (rel) => {
459
+ try {
460
+ execSync(`git check-ignore -q -- "${rel}"`, { cwd: root, timeout: 2000 });
461
+ return true;
462
+ } catch { return false; }
463
+ };
464
+
465
+ // --- Missing critical files ---
466
+ const hasGitignore = files.some((f) => f.rel === ".gitignore" || path.basename(f.rel) === ".gitignore");
467
+ const hasEnvExample = files.some((f) => f.rel === ".env.example" || f.rel === ".env.sample" || f.rel === ".env.template");
468
+ if (gitRoot && !hasGitignore) add(strict ? "critical" : "warn", "No .gitignore found in a git repository.", "Add a .gitignore to prevent accidental commits of build artifacts, secrets, and OS files.");
469
+ if (!hasEnvExample) add("info", "No .env.example / .env.sample found.", "Add .env.example with dummy values so contributors know which env vars are required.");
470
+
471
+ // --- File-by-file scan ---
472
+ for (const f of files) {
473
+ const basename = path.basename(f.rel);
474
+ const abs = path.join(root, f.rel);
475
+ let stat;
476
+ try { stat = await fs.stat(abs); } catch { continue; }
477
+ const size = stat.size;
478
+ const sensitiveName = isSensitiveName(basename);
479
+
480
+ // large files
481
+ if (size > AUDIT_LARGE_CRIT) {
482
+ add("critical", `Large file: ${f.rel} (${(size/1e6).toFixed(1)} MB)`, "Consider adding to .gitignore, using Git LFS, or splitting.");
483
+ } else if (size > AUDIT_LARGE_WARN) {
484
+ add("warn", `Large file: ${f.rel} (${(size/1e3).toFixed(0)} KB)`, "Consider adding to .gitignore, using Git LFS, or splitting.");
485
+ }
486
+
487
+ // exposed sensitive files
488
+ if (sensitiveName) {
489
+ if (gitRoot) {
490
+ const tracked = isGitTracked(f.rel);
491
+ const ignored = isIgnored(f.rel);
492
+ if (tracked && !ignored) {
493
+ add("critical", `Sensitive file committed to git: ${f.rel}`, "Remove from git history (e.g. git-filter-repo), add to .gitignore, rotate any exposed secrets.");
494
+ } else if (!tracked) {
495
+ add("warn", `Sensitive file untracked: ${f.rel}`, "Ensure it is listed in .gitignore and never committed.");
496
+ } else if (ignored) {
497
+ add("info", `Sensitive file present but gitignored: ${f.rel}`, "OK — ensure secrets are rotated if previously committed.");
498
+ }
499
+ } else {
500
+ add("warn", `Sensitive file found (not a git repo): ${f.rel}`, "Review permissions and consider encrypting or moving to a secret manager.");
501
+ }
502
+ }
503
+
504
+ // secret content scan (small text-ish files only)
505
+ if (!f.dir && (CODE_EXT.has(path.extname(basename)) || [".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".env", ".sh"].includes(path.extname(basename).toLowerCase()) || basename.startsWith(".env"))) {
506
+ if (size > 0 && size < AUDIT_MAX_SCAN * 4) {
507
+ let content = "";
508
+ try {
509
+ const fd = await fs.open(abs, "r");
510
+ const buf = Buffer.alloc(Math.min(size, AUDIT_MAX_SCAN));
511
+ await fd.read(buf, 0, buf.length, 0);
512
+ await fd.close();
513
+ content = buf.toString("utf8");
514
+ } catch { continue; }
515
+ for (const re of AUDIT_SECRET_CONTENT_RE) {
516
+ if (re.test(content)) {
517
+ add("critical", `Possible secret/hardcoded credential in ${f.rel}`, "Move to environment vars, secret manager, or encrypted vault. Rotate leaked value immediately.");
518
+ break;
519
+ }
520
+ }
521
+ }
522
+ }
523
+ }
524
+
525
+ // --- duplicate / inconsistent configs ---
526
+ const envFiles = files.filter((f) => path.basename(f.rel).startsWith(".env"));
527
+ if (envFiles.length > 2) {
528
+ add("info", `Multiple env files found (${envFiles.map((f) => f.rel).join(", ")})`, "Consolidate variants into .env, .env.local, .env.production. Ensure .gitignore covers all .env* except .env.example.");
529
+ }
530
+
531
+ // --- render ---
532
+ const icon = { critical: "🔴", warn: "🟡", info: "đŸŸĸ" };
533
+ const groups = { critical: [], warn: [], info: [] };
534
+ for (const f of findings) groups[f.severity].push(f);
535
+ const lines = [`# Audit: ${path.basename(root)}`, `Path: ${root}`, `Git repo: ${gitRoot ? gitRoot : "no"}`, ``];
536
+ for (const sev of ["critical", "warn", "info"]) {
537
+ if (!groups[sev].length) continue;
538
+ lines.push(`## ${icon[sev]} ${sev.toUpperCase()} (${groups[sev].length})`);
539
+ for (const f of groups[sev]) {
540
+ lines.push(`- ${f.message}`);
541
+ if (f.fix) lines.push(` → Fix: ${f.fix}`);
542
+ }
543
+ lines.push("");
544
+ }
545
+ if (!findings.length) lines.push("đŸŸĸ No issues detected.");
546
+ return { content: [{ type: "text", text: lines.join("\n") }] };
547
+ }
548
+
549
+ async impact({ targetFile, dir, maxDepth = 3 }) {
550
+ const root = resolveDir(dir);
551
+ if (!targetFile) throw new Error("targetFile is required");
552
+ const normTarget = targetFile.replace(/\\/g, "/").replace(/^\.\//, "");
553
+ const all = await walk(root, "", [], 0, 8);
554
+ const codeFiles = all.filter((f) => !f.dir && CODE_EXT.has(path.extname(f.rel)));
555
+
556
+ const importMap = new Map();
557
+ const reverseMap = new Map();
558
+
559
+ for (const f of codeFiles) {
560
+ const abs = path.join(root, f.rel);
561
+ try {
562
+ const content = await fs.readFile(abs, "utf8");
563
+ const imports = [];
564
+ const re = /(?:import|export)\s+.*?\s+from\s+["']([^"']+)["']|require\(["']([^"']+)["']\)|import\(["']([^"']+)["']\)/g;
565
+ let match;
566
+ while ((match = re.exec(content)) !== null) {
567
+ const spec = match[1] || match[2] || match[3];
568
+ if (spec && (spec.startsWith(".") || spec.startsWith("/"))) {
569
+ const dirName = path.dirname(f.rel);
570
+ const resolvedRel = path.normalize(path.join(dirName, spec)).replace(/\\/g, "/");
571
+ imports.push(resolvedRel);
572
+ }
573
+ }
574
+ importMap.set(f.rel.replace(/\\/g, "/"), imports);
575
+ } catch {}
576
+ }
577
+
578
+ for (const [importer, importedList] of importMap.entries()) {
579
+ for (const imp of importedList) {
580
+ for (const f of codeFiles) {
581
+ const fRel = f.rel.replace(/\\/g, "/");
582
+ const fRelNoExt = fRel.replace(/\.[^/.]+$/, "");
583
+ if (fRel === imp || fRelNoExt === imp || fRelNoExt === imp.replace(/\/index$/, "")) {
584
+ if (!reverseMap.has(fRel)) reverseMap.set(fRel, []);
585
+ reverseMap.get(fRel).push(importer);
586
+ }
587
+ }
588
+ }
589
+ }
590
+
591
+ const directImporters = reverseMap.get(normTarget) || [];
592
+ const directImports = importMap.get(normTarget) || [];
593
+
594
+ const lines = [
595
+ `# Impact Blast-Radius: ${normTarget}`,
596
+ `Project: ${root}`,
597
+ ``,
598
+ `## đŸŽ¯ Direct Importers / Callers (${directImporters.length})`,
599
+ ...(directImporters.length ? directImporters.map((f) => `- \`${f}\``) : ["- None (No other file directly imports this file)"]),
600
+ ``,
601
+ `## đŸ“Ļ Outbound Imports (${directImports.length})`,
602
+ ...(directImports.length ? directImports.map((f) => `- \`${f}\``) : ["- None"]),
603
+ ``,
604
+ `## âš ī¸ Calculated Blast-Radius Score: ${directImporters.length > 5 ? "HIGH 🔴" : directImporters.length > 2 ? "MEDIUM 🟡" : "LOW đŸŸĸ"}`
605
+ ];
606
+
607
+ return { content: [{ type: "text", text: lines.join("\n") }] };
608
+ }
609
+
610
+ async guard({ dir, checkType = "all" }) {
611
+ const root = resolveDir(dir);
612
+ const pkgPath = path.join(root, "package.json");
613
+ let hasPkg = false;
614
+ let pkg = {};
615
+ try {
616
+ pkg = JSON.parse(await fs.readFile(pkgPath, "utf8"));
617
+ hasPkg = true;
618
+ } catch {}
619
+
620
+ const runScript = (cmd, label) => {
621
+ try {
622
+ const out = execSync(cmd, { cwd: root, encoding: "utf8", timeout: 15000, stdio: ["pipe", "pipe", "pipe"] });
623
+ return { label, status: "PASS đŸŸĸ", output: out.slice(0, 500) };
624
+ } catch (e) {
625
+ const errOut = (e.stdout || "") + "\n" + (e.stderr || "");
626
+ return { label, status: "FAIL 🔴", output: errOut.slice(0, 1000) };
627
+ }
628
+ };
629
+
630
+ const results = [];
631
+ if (hasPkg && pkg.scripts) {
632
+ if ((checkType === "all" || checkType === "typecheck") && (pkg.scripts.typecheck || pkg.scripts["check-types"])) {
633
+ results.push(runScript("npm run " + (pkg.scripts.typecheck ? "typecheck" : "check-types"), "Typecheck"));
634
+ } else if (hasPkg && await fs.access(path.join(root, "tsconfig.json")).then(() => true).catch(() => false)) {
635
+ results.push(runScript("npx tsc --noEmit", "Typecheck (tsc)"));
636
+ }
637
+
638
+ if ((checkType === "all" || checkType === "lint") && pkg.scripts.lint) {
639
+ results.push(runScript("npm run lint", "Linter"));
640
+ }
641
+
642
+ if ((checkType === "all" || checkType === "test") && pkg.scripts.test) {
643
+ results.push(runScript("npm test", "Test Suite"));
644
+ }
645
+ }
646
+
647
+ const lines = [`# Guard Pre-flight Diagnostics: ${path.basename(root)}`, `Path: ${root}`, ``];
648
+ if (!results.length) {
649
+ lines.push("â„šī¸ No build/test/lint scripts detected in project toolchain.");
650
+ } else {
651
+ for (const r of results) {
652
+ lines.push(`## ${r.label}: ${r.status}`);
653
+ if (r.output) {
654
+ lines.push("```");
655
+ lines.push(r.output.trim());
656
+ lines.push("```");
657
+ }
658
+ lines.push("");
659
+ }
660
+ }
661
+
662
+ return { content: [{ type: "text", text: lines.join("\n") }] };
663
+ }
664
+
665
+ async telemetry({ dir, logFile, limit = 50 }) {
666
+ const root = resolveDir(dir);
667
+ const candidateFiles = [];
668
+ if (logFile) candidateFiles.push(path.resolve(root, logFile));
669
+ candidateFiles.push(
670
+ path.join(root, "error.log"),
671
+ path.join(root, "app.log"),
672
+ path.join(root, "dev.log"),
673
+ path.join(root, "server.log"),
674
+ path.join(root, ".next", "server.log"),
675
+ "/tmp/dev.log"
676
+ );
677
+
678
+ let foundPath = null;
679
+ let content = "";
680
+ for (const f of candidateFiles) {
681
+ try {
682
+ content = await fs.readFile(f, "utf8");
683
+ foundPath = f;
684
+ break;
685
+ } catch {}
686
+ }
687
+
688
+ const lines = [`# Live Runtime Telemetry Observer: ${path.basename(root)}`, `Observed Log File: ${foundPath ? foundPath : "None detected (create dev.log or error.log in project)"}`, ``];
689
+ if (foundPath && content) {
690
+ const rawLines = content.split("\n").filter((l) => l.trim().length > 0);
691
+ const recent = rawLines.slice(-limit);
692
+ const errors = recent.filter((l) => /error|exception|fail|crash|500|unhandled/i.test(l));
693
+ lines.push(`## 🔴 Surfaced Errors / Exceptions (${errors.length})`);
694
+ if (errors.length) {
695
+ lines.push("```");
696
+ lines.push(errors.join("\n"));
697
+ lines.push("```");
698
+ } else {
699
+ lines.push("đŸŸĸ No runtime errors detected in recent log lines.");
700
+ }
701
+
702
+ lines.push(``);
703
+ lines.push(`## 📜 Recent Log Feed (${recent.length} lines)`);
704
+ lines.push("```");
705
+ lines.push(recent.slice(-20).join("\n"));
706
+ lines.push("```");
707
+ } else {
708
+ lines.push("â„šī¸ No active dev server log file found. Pass logFile parameter or log output to `./error.log` or `/tmp/dev.log`.");
709
+ }
710
+
711
+ return { content: [{ type: "text", text: lines.join("\n") }] };
712
+ }
713
+
714
+ async predictiveDiff({ targetFile, proposedDiff, dir }) {
715
+ const root = resolveDir(dir);
716
+ const impactRes = await this.impact({ targetFile, dir, maxDepth: 3 });
717
+ const impactText = impactRes.content[0].text;
718
+
719
+ const warnings = [];
720
+ if (/delete|remove|drop|rename/i.test(proposedDiff)) {
721
+ warnings.push("âš ī¸ Proposed diff contains potential destructive operation (delete/drop/rename).");
722
+ }
723
+ if (/export\s+(const|function|class|interface|type)\s+/i.test(proposedDiff)) {
724
+ warnings.push("â„šī¸ Exported symbol signature changed. Verify caller arguments in dependent files.");
725
+ }
726
+
727
+ const lines = [
728
+ `# Predictive Contract & Diff Analysis: ${targetFile}`,
729
+ `Project: ${root}`,
730
+ ``,
731
+ `## 🔮 Predicted Impact Warnings (${warnings.length})`,
732
+ ...(warnings.length ? warnings.map((w) => `- ${w}`) : ["đŸŸĸ No high-risk signature breaks predicted."]),
733
+ ``,
734
+ impactText
735
+ ];
736
+
737
+ return { content: [{ type: "text", text: lines.join("\n") }] };
738
+ }
739
+
740
+ async run() {
741
+ const t = new StdioServerTransport();
742
+ await this.server.connect(t);
743
+ console.error("Context Pack MCP server running on stdio");
744
+ }
745
+ }
746
+
747
+ new ContextPackServer().run().catch(console.error);