project-context-map-mcp 0.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/src/indexer.js ADDED
@@ -0,0 +1,780 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { getLastChangedReasonMap, getRecentGitChanges } from "./git.js";
4
+ import {
5
+ MAP_JSON_FILE,
6
+ MAP_MD_FILE,
7
+ PROJECT_MD_FILE,
8
+ firstNonEmptyLine,
9
+ isPathInsideProject,
10
+ isTextLikeFile,
11
+ pathExists,
12
+ readTextIfExists,
13
+ readJsonIfExists,
14
+ relativeProjectPath,
15
+ resolveProjectRoot,
16
+ walkProjectFiles,
17
+ writeJson,
18
+ writeText
19
+ } from "./utils.js";
20
+
21
+ function detectTechStack(projectRoot) {
22
+ const checks = [
23
+ { file: "package.json", tag: "nodejs" },
24
+ { file: "next.config.js", tag: "nextjs" },
25
+ { file: "next.config.mjs", tag: "nextjs" },
26
+ { file: "next.config.ts", tag: "nextjs" },
27
+ { file: "pom.xml", tag: "springboot" },
28
+ { file: "build.gradle", tag: "gradle" },
29
+ { file: "build.gradle.kts", tag: "gradle" },
30
+ { file: "requirements.txt", tag: "python" },
31
+ { file: "pyproject.toml", tag: "python" },
32
+ { file: "manage.py", tag: "django" },
33
+ { file: "Cargo.toml", tag: "rust" }
34
+ ];
35
+
36
+ return checks
37
+ .filter((item) => pathExists(path.join(projectRoot, item.file)))
38
+ .map((item) => item.tag)
39
+ .filter((value, index, array) => array.indexOf(value) === index);
40
+ }
41
+
42
+ function inferProjectType(techStack) {
43
+ const hasFrontend = techStack.some((item) => ["nextjs", "react", "nodejs"].includes(item));
44
+ const hasBackend = techStack.some((item) => ["springboot", "python", "django"].includes(item));
45
+
46
+ if (hasFrontend && hasBackend) {
47
+ return "fullstack";
48
+ }
49
+
50
+ if (hasBackend) {
51
+ return "backend";
52
+ }
53
+
54
+ if (hasFrontend) {
55
+ return "frontend";
56
+ }
57
+
58
+ return "application";
59
+ }
60
+
61
+ function inferRole(relativePath) {
62
+ const value = relativePath.toLowerCase();
63
+ const ext = path.extname(relativePath).toLowerCase();
64
+
65
+ if (value.startsWith("scripts/hooks/")) {
66
+ return "Git automation hook";
67
+ }
68
+
69
+ if (value.includes("/test") || value.includes(".test.") || value.includes(".spec.")) {
70
+ return "Test coverage for a feature or module";
71
+ }
72
+
73
+ if (value.includes("controller")) {
74
+ return "Request or route controller";
75
+ }
76
+
77
+ if (value.includes("service")) {
78
+ return "Business logic service";
79
+ }
80
+
81
+ if (value.includes("repository")) {
82
+ return "Data access or persistence layer";
83
+ }
84
+
85
+ if (value.includes("component") || ext === ".jsx" || ext === ".tsx") {
86
+ return "UI component";
87
+ }
88
+
89
+ if (value.includes("hook")) {
90
+ return "Reusable UI or state hook";
91
+ }
92
+
93
+ if (value.includes("api") || value.includes("client")) {
94
+ return "API integration or boundary";
95
+ }
96
+
97
+ if (value.endsWith("package.json")) {
98
+ return "Package metadata and scripts";
99
+ }
100
+
101
+ if (value.endsWith("pom.xml") || value.endsWith("build.gradle")) {
102
+ return "Build and dependency configuration";
103
+ }
104
+
105
+ if (ext === ".md") {
106
+ return "Project documentation";
107
+ }
108
+
109
+ if (ext === ".json" || ext === ".yaml" || ext === ".yml" || ext === ".properties") {
110
+ return "Configuration file";
111
+ }
112
+
113
+ if (ext === ".java") {
114
+ return "Java source file";
115
+ }
116
+
117
+ if (ext === ".py") {
118
+ return "Python source file";
119
+ }
120
+
121
+ if (ext === ".js" || ext === ".mjs" || ext === ".cjs" || ext === ".ts") {
122
+ return "Application or tooling source file";
123
+ }
124
+
125
+ return "Project file";
126
+ }
127
+
128
+ function inferModule(relativePath) {
129
+ const segments = relativePath.split("/");
130
+ const [first, second, third] = segments;
131
+
132
+ if (segments.length === 1) {
133
+ return "root";
134
+ }
135
+
136
+ if (segments.length === 2) {
137
+ return first;
138
+ }
139
+
140
+ if (first === "src" || first === "app" || first === "backend" || first === "frontend") {
141
+ return third ? second : first;
142
+ }
143
+
144
+ if (first === ".claude" && second === "skills") {
145
+ return second;
146
+ }
147
+
148
+ return first;
149
+ }
150
+
151
+ function inferTags(relativePath) {
152
+ const value = relativePath.toLowerCase();
153
+ const tags = new Set();
154
+
155
+ if (value.includes("auth")) tags.add("auth");
156
+ if (value.includes("login")) tags.add("login");
157
+ if (value.includes("user")) tags.add("user");
158
+ if (value.includes("payment")) tags.add("payment");
159
+ if (value.includes("api")) tags.add("api");
160
+ if (value.includes("config")) tags.add("config");
161
+ if (value.includes("test") || value.includes("spec")) tags.add("test");
162
+ if (value.includes("component")) tags.add("ui");
163
+ if (value.includes("hook")) tags.add("hook");
164
+ if (value.endsWith(".tsx") || value.endsWith(".jsx")) tags.add("react");
165
+ if (value.includes("/app/") || value.includes("next.config")) tags.add("nextjs");
166
+ if (value.endsWith(".java") || value.includes("spring")) tags.add("java");
167
+ if (value.endsWith(".py")) tags.add("python");
168
+
169
+ return [...tags];
170
+ }
171
+
172
+ function buildFileRecord(projectRoot, absolutePath) {
173
+ const relativePath = relativeProjectPath(projectRoot, absolutePath);
174
+ const firstLine = firstNonEmptyLine(absolutePath);
175
+
176
+ return {
177
+ path: relativePath,
178
+ module: inferModule(relativePath),
179
+ role: inferRole(relativePath),
180
+ tags: inferTags(relativePath),
181
+ summary: firstLine.slice(0, 160)
182
+ };
183
+ }
184
+
185
+ function tryResolveImport(fromFile, specifier) {
186
+ const baseDir = path.dirname(fromFile);
187
+ const candidates = [];
188
+
189
+ if (specifier.startsWith("/")) {
190
+ return null;
191
+ }
192
+
193
+ if (path.extname(specifier)) {
194
+ candidates.push(path.resolve(baseDir, specifier));
195
+ } else {
196
+ candidates.push(
197
+ path.resolve(baseDir, specifier),
198
+ path.resolve(baseDir, `${specifier}.js`),
199
+ path.resolve(baseDir, `${specifier}.mjs`),
200
+ path.resolve(baseDir, `${specifier}.cjs`),
201
+ path.resolve(baseDir, `${specifier}.ts`),
202
+ path.resolve(baseDir, `${specifier}.tsx`),
203
+ path.resolve(baseDir, `${specifier}.jsx`),
204
+ path.resolve(baseDir, specifier, "index.js"),
205
+ path.resolve(baseDir, specifier, "index.ts"),
206
+ path.resolve(baseDir, specifier, "index.tsx"),
207
+ path.resolve(baseDir, specifier, "__init__.py"),
208
+ path.resolve(baseDir, `${specifier}.py`)
209
+ );
210
+ }
211
+
212
+ return candidates.find((candidate) => pathExists(candidate)) || null;
213
+ }
214
+
215
+ function extractImportSpecifiers(relativePath, content) {
216
+ const ext = path.extname(relativePath).toLowerCase();
217
+ const specs = new Set();
218
+
219
+ if ([".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"].includes(ext)) {
220
+ const importPatterns = [
221
+ /import\s+[^"'`]*?from\s+["'`]([^"'`]+)["'`]/g,
222
+ /import\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,
223
+ /require\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,
224
+ /export\s+[^"'`]*?from\s+["'`]([^"'`]+)["'`]/g
225
+ ];
226
+
227
+ for (const pattern of importPatterns) {
228
+ for (const match of content.matchAll(pattern)) {
229
+ if (match[1]) {
230
+ specs.add(match[1]);
231
+ }
232
+ }
233
+ }
234
+ }
235
+
236
+ if (ext === ".py") {
237
+ for (const match of content.matchAll(/(?:from\s+([a-zA-Z0-9_./]+)\s+import|import\s+([a-zA-Z0-9_.,\s]+))/g)) {
238
+ const specifier = match[1] || match[2]?.split(",")[0]?.trim();
239
+ if (specifier) {
240
+ specs.add(specifier.replace(/\./g, "/"));
241
+ }
242
+ }
243
+ }
244
+
245
+ return [...specs];
246
+ }
247
+
248
+ function buildTopology(projectRoot, files) {
249
+ const fileSet = new Set(files.map((file) => file.path));
250
+ const adjacency = new Map(files.map((file) => [file.path, new Set()]));
251
+ const reverse = new Map(files.map((file) => [file.path, new Set()]));
252
+ const externalDependencies = new Map();
253
+
254
+ for (const file of files) {
255
+ const absolutePath = path.join(projectRoot, file.path);
256
+ if (!isTextLikeFile(absolutePath)) {
257
+ continue;
258
+ }
259
+
260
+ let content = "";
261
+ try {
262
+ content = fs.readFileSync(absolutePath, "utf8");
263
+ } catch {
264
+ continue;
265
+ }
266
+
267
+ const specifiers = extractImportSpecifiers(file.path, content);
268
+
269
+ for (const specifier of specifiers) {
270
+ if (specifier.startsWith(".") || specifier.startsWith("..")) {
271
+ const resolved = tryResolveImport(absolutePath, specifier);
272
+ if (!resolved) {
273
+ continue;
274
+ }
275
+
276
+ const targetPath = relativeProjectPath(projectRoot, resolved);
277
+ if (!fileSet.has(targetPath)) {
278
+ continue;
279
+ }
280
+
281
+ adjacency.get(file.path).add(targetPath);
282
+ reverse.get(targetPath).add(file.path);
283
+ continue;
284
+ }
285
+
286
+ externalDependencies.set(specifier, (externalDependencies.get(specifier) || 0) + 1);
287
+ }
288
+ }
289
+
290
+ for (const file of files) {
291
+ file.dependencies = [...(adjacency.get(file.path) || [])].sort();
292
+ file.used_by = [...(reverse.get(file.path) || [])].sort();
293
+ }
294
+
295
+ return {
296
+ edges: files.flatMap((file) =>
297
+ [...(adjacency.get(file.path) || [])].map((target) => ({
298
+ from: file.path,
299
+ to: target,
300
+ type: "import"
301
+ }))
302
+ ),
303
+ importsByFile: Object.fromEntries(files.map((file) => [file.path, file.dependencies || []])),
304
+ usedByFile: Object.fromEntries(files.map((file) => [file.path, file.used_by || []])),
305
+ externalDependencies: [...externalDependencies.entries()]
306
+ .map(([name, count]) => ({ name, count }))
307
+ .sort((left, right) => right.count - left.count || left.name.localeCompare(right.name))
308
+ };
309
+ }
310
+
311
+ function buildModuleSummary(files) {
312
+ const modules = new Map();
313
+
314
+ for (const file of files) {
315
+ if (!modules.has(file.module)) {
316
+ modules.set(file.module, {
317
+ name: file.module,
318
+ fileCount: 0,
319
+ tags: new Set(),
320
+ sampleFiles: []
321
+ });
322
+ }
323
+
324
+ const module = modules.get(file.module);
325
+ module.fileCount += 1;
326
+ for (const tag of file.tags) {
327
+ module.tags.add(tag);
328
+ }
329
+ if (module.sampleFiles.length < 5) {
330
+ module.sampleFiles.push(file.path);
331
+ }
332
+ }
333
+
334
+ return [...modules.values()]
335
+ .map((module) => ({
336
+ name: module.name,
337
+ description: `Contains files related to the ${module.name} area of the project.`,
338
+ fileCount: module.fileCount,
339
+ paths: module.sampleFiles.map((item) => item.split("/").slice(0, 2).join("/")),
340
+ tags: [...module.tags].sort(),
341
+ sampleFiles: module.sampleFiles,
342
+ depends_on: []
343
+ }))
344
+ .sort((left, right) => right.fileCount - left.fileCount || left.name.localeCompare(right.name));
345
+ }
346
+
347
+ function dedupe(values) {
348
+ return [...new Set(values.filter(Boolean))];
349
+ }
350
+
351
+ function buildEntrypoints(projectRoot) {
352
+ const candidates = [
353
+ "package.json",
354
+ "src/index.js",
355
+ "src/main.js",
356
+ "src/server.js",
357
+ "app/page.tsx",
358
+ "app/layout.tsx",
359
+ "src/main/java",
360
+ "manage.py"
361
+ ];
362
+
363
+ return candidates
364
+ .filter((relativePath) => pathExists(path.join(projectRoot, relativePath)))
365
+ .map((relativePath) => ({
366
+ path: relativePath,
367
+ reason: "Detected by framework convention or common entrypoint path"
368
+ }));
369
+ }
370
+
371
+ function buildDependencies(projectRoot, techStack) {
372
+ const dependencies = [];
373
+ const packageJsonPath = path.join(projectRoot, "package.json");
374
+
375
+ if (pathExists(packageJsonPath)) {
376
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
377
+ const names = dedupe([
378
+ ...Object.keys(packageJson.dependencies || {}),
379
+ ...Object.keys(packageJson.devDependencies || {})
380
+ ]).slice(0, 50);
381
+
382
+ dependencies.push(
383
+ ...names.map((name) => ({
384
+ ecosystem: "npm",
385
+ name
386
+ }))
387
+ );
388
+ }
389
+
390
+ if (techStack.includes("springboot")) {
391
+ dependencies.push({
392
+ ecosystem: "maven",
393
+ name: "pom.xml",
394
+ note: "Java dependencies managed through Maven build file"
395
+ });
396
+ }
397
+
398
+ if (techStack.includes("python")) {
399
+ if (pathExists(path.join(projectRoot, "requirements.txt"))) {
400
+ dependencies.push({
401
+ ecosystem: "pip",
402
+ name: "requirements.txt"
403
+ });
404
+ }
405
+
406
+ if (pathExists(path.join(projectRoot, "pyproject.toml"))) {
407
+ dependencies.push({
408
+ ecosystem: "python",
409
+ name: "pyproject.toml"
410
+ });
411
+ }
412
+ }
413
+
414
+ return dependencies;
415
+ }
416
+
417
+ function enrichFileRelations(files, recentChanges) {
418
+ const byModule = new Map();
419
+ const byPath = new Map(files.map((file) => [file.path, file]));
420
+ const lastChangedReasonMap = getLastChangedReasonMap(recentChanges);
421
+
422
+ for (const file of files) {
423
+ if (!byModule.has(file.module)) {
424
+ byModule.set(file.module, []);
425
+ }
426
+ byModule.get(file.module).push(file.path);
427
+ }
428
+
429
+ for (const file of files) {
430
+ const siblings = (byModule.get(file.module) || []).filter((item) => item !== file.path).slice(0, 5);
431
+ const coChanged = [];
432
+
433
+ for (const commit of recentChanges.commits || []) {
434
+ if ((commit.files || []).includes(file.path)) {
435
+ for (const relatedPath of commit.files || []) {
436
+ if (relatedPath !== file.path && byPath.has(relatedPath)) {
437
+ coChanged.push(relatedPath);
438
+ }
439
+ }
440
+ }
441
+ }
442
+
443
+ file.related_to = dedupe([...siblings, ...coChanged]).slice(0, 8);
444
+ file.last_changed_reason = lastChangedReasonMap.get(file.path) || "";
445
+ }
446
+ }
447
+
448
+ function buildMarkdown(projectMap) {
449
+ const lines = [
450
+ "# Project Context Map",
451
+ "",
452
+ `Generated: ${projectMap.generatedAt}`,
453
+ "",
454
+ "## Summary",
455
+ "",
456
+ `- Project root: \`${projectMap.projectRoot}\``,
457
+ `- Project name: ${projectMap.project_summary.name}`,
458
+ `- Project type: ${projectMap.project_summary.type}`,
459
+ `- Total files indexed: ${projectMap.stats.totalFiles}`,
460
+ `- Tech stack: ${projectMap.tech_stack.length > 0 ? projectMap.tech_stack.join(", ") : "unknown"}`,
461
+ `- Git repo detected: ${projectMap.git.isGitRepo ? "yes" : "no"}`,
462
+ "",
463
+ "## Modules",
464
+ ""
465
+ ];
466
+
467
+ for (const module of projectMap.modules.slice(0, 12)) {
468
+ lines.push(
469
+ `- \`${module.name}\`: ${module.fileCount} files${module.tags.length ? `, tags: ${module.tags.join(", ")}` : ""}`
470
+ );
471
+ }
472
+
473
+ lines.push("", "## Entrypoints", "");
474
+
475
+ for (const entrypoint of projectMap.entrypoints) {
476
+ lines.push(`- \`${entrypoint.path}\`: ${entrypoint.reason}`);
477
+ }
478
+
479
+ lines.push("", "## Recent Git Changes", "");
480
+
481
+ if (!projectMap.git.isGitRepo) {
482
+ lines.push("- No git repository detected.");
483
+ } else if (projectMap.recent_changes.length === 0) {
484
+ lines.push(`- No commits found in the last ${projectMap.git.days} days.`);
485
+ } else {
486
+ for (const commit of projectMap.recent_changes.slice(0, 10)) {
487
+ lines.push(`- ${commit.date} \`${commit.hash.slice(0, 7)}\` ${commit.summary}`);
488
+ }
489
+ }
490
+
491
+ lines.push("", "## Hotspots", "");
492
+
493
+ if ((projectMap.hotspots || []).length === 0) {
494
+ lines.push("- No hotspots detected.");
495
+ } else {
496
+ for (const hotspot of projectMap.hotspots.slice(0, 10)) {
497
+ lines.push(`- \`${hotspot.path}\` touched ${hotspot.count} time(s)`);
498
+ }
499
+ }
500
+
501
+ lines.push("", "## Important Files", "");
502
+
503
+ for (const file of projectMap.files.slice(0, 50)) {
504
+ const summary = file.summary ? ` - ${file.summary}` : "";
505
+ lines.push(`- \`${file.path}\` (${file.role})${summary}`);
506
+ }
507
+
508
+ return lines.join("\n");
509
+ }
510
+
511
+ function extractChangeLogSection(existingContent = "") {
512
+ const marker = "## Change Log";
513
+ const index = existingContent.indexOf(marker);
514
+ return index >= 0 ? existingContent.slice(index).trim() : `${marker}\n\n- No logged changes yet.`;
515
+ }
516
+
517
+ function buildProjectContextMarkdown(projectMap, existingContent = "") {
518
+ const mermaidEdges = (projectMap.topology?.edges || []).slice(0, 40);
519
+ const lines = [
520
+ "# Project Context",
521
+ "",
522
+ `Generated: ${projectMap.generatedAt}`,
523
+ "",
524
+ "## Summary",
525
+ "",
526
+ `- Project root: \`${projectMap.projectRoot}\``,
527
+ `- Project name: ${projectMap.project_summary.name}`,
528
+ `- Project type: ${projectMap.project_summary.type}`,
529
+ `- Total files indexed: ${projectMap.stats.totalFiles}`,
530
+ `- Topology edges: ${(projectMap.topology?.edges || []).length}`,
531
+ "",
532
+ "## Key Modules",
533
+ "",
534
+ ...projectMap.modules.slice(0, 10).map((module) => `- \`${module.name}\`: ${module.fileCount} files`),
535
+ "",
536
+ "## Query Index",
537
+ "",
538
+ ...projectMap.files
539
+ .slice(0, 50)
540
+ .map((file) => `- \`${file.path}\`: ${[file.module, file.role, ...(file.tags || [])].filter(Boolean).join(" | ")}`),
541
+ "",
542
+ "## Topology Highlights",
543
+ "",
544
+ ...(projectMap.topology?.edges || []).length > 0
545
+ ? projectMap.topology.edges.slice(0, 30).map((edge) => `- \`${edge.from}\` -> \`${edge.to}\``)
546
+ : ["- No internal import/dependency edges detected."],
547
+ "",
548
+ "## Topology Graph",
549
+ "",
550
+ "```mermaid",
551
+ "graph TD",
552
+ ...(mermaidEdges.length > 0
553
+ ? mermaidEdges.map((edge) => ` ${edge.from.replace(/[^a-zA-Z0-9_]/g, "_")}["${edge.from}"] --> ${edge.to.replace(/[^a-zA-Z0-9_]/g, "_")}["${edge.to}"]`)
554
+ : [" no_topology_edges[\"No internal topology edges detected\"]"]),
555
+ "```",
556
+ "",
557
+ extractChangeLogSection(existingContent)
558
+ ];
559
+
560
+ return lines.join("\n");
561
+ }
562
+
563
+ export function buildProjectMap(projectRootInput) {
564
+ const projectRoot = resolveProjectRoot(projectRootInput);
565
+ const absoluteFiles = walkProjectFiles(projectRoot);
566
+ const files = absoluteFiles.map((filePath) => buildFileRecord(projectRoot, filePath));
567
+ const git = getRecentGitChanges(projectRoot, 5);
568
+ enrichFileRelations(files, git);
569
+ const modules = buildModuleSummary(files);
570
+ const techStack = detectTechStack(projectRoot);
571
+ const projectName = path.basename(projectRoot);
572
+ const topology = buildTopology(projectRoot, files);
573
+
574
+ return {
575
+ schemaVersion: 2,
576
+ generatedAt: new Date().toISOString(),
577
+ projectRoot,
578
+ project_summary: {
579
+ name: projectName,
580
+ type: inferProjectType(techStack),
581
+ frameworks: techStack,
582
+ last_updated: new Date().toISOString()
583
+ },
584
+ tech_stack: techStack,
585
+ stats: {
586
+ totalFiles: files.length
587
+ },
588
+ entrypoints: buildEntrypoints(projectRoot),
589
+ dependencies: buildDependencies(projectRoot, techStack),
590
+ topology,
591
+ modules,
592
+ files,
593
+ recent_changes: git.commits,
594
+ hotspots: git.hotspots,
595
+ ownership: {
596
+ manual_overrides_path: ".project-map.overrides.json"
597
+ },
598
+ git
599
+ };
600
+ }
601
+
602
+ export function refreshProjectMap(projectRootInput) {
603
+ const projectRoot = resolveProjectRoot(projectRootInput);
604
+ const projectMap = buildProjectMap(projectRoot);
605
+ const jsonPath = path.join(projectRoot, MAP_JSON_FILE);
606
+ const mdPath = path.join(projectRoot, MAP_MD_FILE);
607
+ const projectMdPath = path.join(projectRoot, PROJECT_MD_FILE);
608
+ const existingProjectMd = readTextIfExists(projectMdPath) || "";
609
+
610
+ writeJson(jsonPath, projectMap);
611
+ writeText(mdPath, buildMarkdown(projectMap));
612
+ writeText(projectMdPath, buildProjectContextMarkdown(projectMap, existingProjectMd));
613
+
614
+ return {
615
+ jsonPath,
616
+ markdownPath: mdPath,
617
+ projectMarkdownPath: projectMdPath,
618
+ projectMap
619
+ };
620
+ }
621
+
622
+ export function loadProjectMap(projectRootInput) {
623
+ const projectRoot = resolveProjectRoot(projectRootInput);
624
+ const jsonPath = path.join(projectRoot, MAP_JSON_FILE);
625
+ const current = readJsonIfExists(jsonPath);
626
+
627
+ if (current) {
628
+ return current;
629
+ }
630
+
631
+ return refreshProjectMap(projectRoot).projectMap;
632
+ }
633
+
634
+ export function explainFile(projectRootInput, relativePath) {
635
+ const projectRoot = resolveProjectRoot(projectRootInput);
636
+ const projectMap = loadProjectMap(projectRoot);
637
+ const file = projectMap.files.find((item) => item.path === relativePath);
638
+
639
+ if (!file) {
640
+ return null;
641
+ }
642
+
643
+ const recentCommits = (projectMap.git.commits || [])
644
+ .filter((commit) => (commit.files || []).includes(relativePath))
645
+ .slice(0, 5)
646
+ .map((commit) => ({
647
+ hash: commit.hash,
648
+ date: commit.date,
649
+ summary: commit.summary
650
+ }));
651
+
652
+ return {
653
+ ...file,
654
+ recentCommits
655
+ };
656
+ }
657
+
658
+ export function getModuleContext(projectRootInput, moduleName) {
659
+ const projectRoot = resolveProjectRoot(projectRootInput);
660
+ const projectMap = loadProjectMap(projectRoot);
661
+ const module = (projectMap.modules || []).find(
662
+ (item) => item.name.toLowerCase() === String(moduleName || "").toLowerCase()
663
+ );
664
+
665
+ if (!module) {
666
+ return null;
667
+ }
668
+
669
+ const files = (projectMap.files || []).filter((file) => file.module === module.name);
670
+ const fileSet = new Set(files.map((file) => file.path));
671
+ const recentCommits = (projectMap.recent_changes || [])
672
+ .filter((commit) => (commit.files || []).some((file) => fileSet.has(file)))
673
+ .slice(0, 10);
674
+
675
+ return {
676
+ module,
677
+ files: files.slice(0, 25),
678
+ recentCommits,
679
+ likelyImpactArea: files.slice(0, 8).map((file) => file.path)
680
+ };
681
+ }
682
+
683
+ export function readProjectContext(projectRootInput) {
684
+ const projectRoot = resolveProjectRoot(projectRootInput);
685
+ const projectMdPath = path.join(projectRoot, PROJECT_MD_FILE);
686
+
687
+ if (!pathExists(projectMdPath)) {
688
+ refreshProjectMap(projectRoot);
689
+ }
690
+
691
+ return {
692
+ path: projectMdPath,
693
+ content: readTextIfExists(projectMdPath) || ""
694
+ };
695
+ }
696
+
697
+ export function readFilesSparse(projectRootInput, filePaths = []) {
698
+ const projectRoot = resolveProjectRoot(projectRootInput);
699
+ const projectMap = loadProjectMap(projectRoot);
700
+ const indexed = new Set((projectMap.files || []).map((file) => file.path));
701
+
702
+ const files = filePaths.map((filePath) => {
703
+ const normalizedPath = relativeProjectPath(projectRoot, path.resolve(projectRoot, filePath));
704
+ const absolutePath = path.resolve(projectRoot, filePath);
705
+
706
+ if (!isPathInsideProject(projectRoot, absolutePath)) {
707
+ return {
708
+ path: filePath,
709
+ error: "Path is outside the project root."
710
+ };
711
+ }
712
+
713
+ if (!indexed.has(normalizedPath)) {
714
+ return {
715
+ path: normalizedPath,
716
+ error: "Path is not indexed in the project topology."
717
+ };
718
+ }
719
+
720
+ return {
721
+ path: normalizedPath,
722
+ content: readTextIfExists(absolutePath) || ""
723
+ };
724
+ });
725
+
726
+ return { files };
727
+ }
728
+
729
+ export function appendChangeLog(projectRootInput, entry) {
730
+ const projectRoot = resolveProjectRoot(projectRootInput);
731
+ const projectMdPath = path.join(projectRoot, PROJECT_MD_FILE);
732
+
733
+ if (!pathExists(projectMdPath)) {
734
+ refreshProjectMap(projectRoot);
735
+ }
736
+
737
+ const current = readTextIfExists(projectMdPath) || "# Project Context\n\n## Change Log\n";
738
+ const marker = "## Change Log";
739
+ const timestamp = new Date().toISOString();
740
+ const nextEntry = `- ${timestamp} ${entry}`.trim();
741
+
742
+ let updated = current;
743
+ if (!current.includes(marker)) {
744
+ updated = `${current.trim()}\n\n${marker}\n\n${nextEntry}\n`;
745
+ } else if (current.includes("- No logged changes yet.")) {
746
+ updated = current.replace("- No logged changes yet.", nextEntry);
747
+ if (!updated.endsWith("\n")) {
748
+ updated = `${updated}\n`;
749
+ }
750
+ } else {
751
+ updated = `${current.trimEnd()}\n${nextEntry}\n`;
752
+ }
753
+
754
+ writeText(projectMdPath, updated.trimEnd());
755
+ return {
756
+ path: projectMdPath,
757
+ entry: nextEntry
758
+ };
759
+ }
760
+
761
+ export function writeAndLog(projectRootInput, targetPath, content, changeSummary = "") {
762
+ const projectRoot = resolveProjectRoot(projectRootInput);
763
+ const absolutePath = path.resolve(projectRoot, targetPath);
764
+
765
+ if (!isPathInsideProject(projectRoot, absolutePath)) {
766
+ throw new Error("Refusing to write outside the project root.");
767
+ }
768
+
769
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
770
+ writeText(absolutePath, String(content || "").replace(/\n$/u, ""));
771
+
772
+ const normalizedPath = relativeProjectPath(projectRoot, absolutePath);
773
+ const logResult = appendChangeLog(projectRoot, `${normalizedPath}${changeSummary ? ` - ${changeSummary}` : ""}`);
774
+
775
+ return {
776
+ path: normalizedPath,
777
+ bytesWritten: Buffer.byteLength(String(content || ""), "utf8"),
778
+ log: logResult
779
+ };
780
+ }