cartotree 0.1.1 → 0.2.1

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.
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "cartotree",
3
+ "owner": { "name": "kingluminance" },
4
+ "plugins": [
5
+ {
6
+ "name": "cartotree",
7
+ "source": "./",
8
+ "description": "Find the right files with few tokens: locate / peek / links MCP tools + a navigation skill."
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "cartotree",
3
+ "version": "0.2.0",
4
+ "description": "Find the right files with few tokens: local index for locate / peek / links, as MCP tools + a skill.",
5
+ "author": { "name": "kingluminance" },
6
+ "repository": "https://github.com/kingluminance/cartotree",
7
+ "license": "MIT",
8
+ "keywords": ["navigation", "search", "tokens", "codebase", "mcp"],
9
+ "mcpServers": {
10
+ "cartotree": { "command": "npx", "args": ["-y", "cartotree@latest", "mcp"] }
11
+ }
12
+ }
package/README.md CHANGED
@@ -1,26 +1,97 @@
1
1
  # 🌲 cartotree
2
2
 
3
- > AI-friendly codebase mapping CLI — annotated directory trees that save tokens, not just space.
3
+ > Tell your coding agent which files to open first. Fewer grep calls, fewer tokens, same answers.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/cartotree)](https://www.npmjs.com/package/cartotree)
6
6
  [![license](https://img.shields.io/npm/l/cartotree)](./LICENSE)
7
7
 
8
+ Ask an agent "why does this bug happen?" and it usually runs grep dozens of times and reads whole files before it finds where to look. cartotree keeps a local index of your repo and answers that first question directly: a ranked list of files with the matching lines as evidence. Works with Claude Code, Cursor, Codex and anything that speaks MCP.
9
+
10
+ ```bash
11
+ npx cartotree init # installs a skill + MCP server for your agent (shows every change, --dry-run to preview)
12
+ ```
13
+
14
+ ---
15
+
16
+ ## What the agent gets
17
+
18
+ Three commands, each returning a few lines instead of a wall of grep output:
19
+
20
+ ```bash
21
+ npx cartotree locate "abort JSONL stream on httpBatchStreamLink unsubscribe" # which files to open first
22
+ npx cartotree peek packages/client/src/links/httpBatchStreamLink.ts abort unsubscribe # only the matching lines
23
+ npx cartotree links httpBatchStreamLink # where a symbol is defined and called
24
+ npx cartotree links src/foo.ts # imports, importers, files usually changed with it (git)
25
+ ```
26
+
27
+ ## Setup
28
+
29
+ ```bash
30
+ npx cartotree init # skill + MCP server + SessionStart reminder (shows every change)
31
+ npx cartotree init --dry-run # preview only
32
+ ```
33
+
34
+ Or as a Claude Code plugin:
35
+
36
+ ```bash
37
+ claude plugin marketplace add kingluminance/cartotree
38
+ claude plugin install cartotree@cartotree
39
+ ```
40
+
41
+ The MCP server (`npx cartotree mcp`) exposes `cartotree_locate`, `cartotree_peek` and `cartotree_links`.
42
+ After the first call the index stays in memory (~10 ms per lookup). An on-disk cache in `.cartotree/` is keyed by git HEAD and your uncommitted changes.
43
+
44
+ ## How locate ranks files
45
+
46
+ BM25F over four fields of every source file: path words, exported names, code identifiers (scored per function so one matching function is not diluted by a long file) and **past commit messages that touched the file**. Plus light stemming, an import-neighbor boost, 1–2 evidence lines per result, a warning when the top results are close, and "usually changes with" from git co-change history. No LLM, no network.
47
+
48
+ ---
49
+
50
+ ## Benchmark
51
+
52
+ [deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) (21,632 files). Questions are real commit messages ("which files were changed?"), answered by a Claude Haiku agent with cartotree vs. the same agent with only ls/find/grep. Each setup was run twice and averaged. Git history was cut off before the test commits so the tool cannot see the answers.
53
+
54
+ **Fast mode, 15 questions** (default)
55
+
56
+ | | grep only | cartotree |
57
+ |---|---|---|
58
+ | right file in top 3 | 13.5 / 15 | 14 / 15 |
59
+ | right file ranked 1st | 12 / 15 | 11 / 15 |
60
+ | tool-output tokens | ~37k | ~7.5k (**−80%**) |
61
+ | total agent tokens | ~153k | ~100k (**−35%**) |
62
+ | time | ~130 s | ~45 s (**−66%**) |
63
+
64
+ **Careful mode, 30 questions** (agent verifies with `peek` before answering)
65
+
66
+ | | grep only | cartotree |
67
+ |---|---|---|
68
+ | right file ranked 1st | 22 / 30 | 22.5 / 30 |
69
+ | right file in top 3 | 25.5 / 30 | 24.5 / 30 |
70
+ | tool-output tokens | baseline | **−63%** |
71
+ | time | baseline | **−17%** |
72
+
73
+ Accuracy is on par with grep (within ±1.5 questions); the gain is cost and speed. One thing we tried and reverted: telling the agent to "answer immediately when confident" made it list fewer candidates and lowered top-3 accuracy.
74
+
8
75
  ---
9
76
 
10
- ## The Problem
77
+ ## Annotated directory trees
78
+
79
+ The original cartotree command still works: a compact, annotated map of your codebase to paste into any AI chat.
80
+
81
+ ### The problem it started with
11
82
 
12
83
  When you paste your project structure into an AI assistant, two things happen:
13
84
 
14
85
  1. **Token waste** — Raw `tree` output burns hundreds of tokens on ASCII box characters with zero semantic value.
15
86
  2. **Hallucination** — AI has no idea what each folder *does*, so it guesses wrong.
16
87
 
17
- ## The Solution
88
+ ### The Solution
18
89
 
19
90
  cartotree generates a compact, annotated map of your codebase — folder descriptions, exported functions, and an AI-optimized serialization format that fits your architecture into a fraction of the tokens.
20
91
 
21
92
  ---
22
93
 
23
- ## Quick Start
94
+ ### Quick Start
24
95
 
25
96
  ```bash
26
97
  npx cartotree
@@ -30,7 +101,7 @@ No install required.
30
101
 
31
102
  ---
32
103
 
33
- ## Output Formats
104
+ ### Output Formats
34
105
 
35
106
  ### Default — Annotated ASCII Tree
36
107
  ```
@@ -69,7 +140,7 @@ my-app{Core application source}[src{Core application source}[components{Reusable
69
140
 
70
141
  ---
71
142
 
72
- ## Usage
143
+ ### Usage
73
144
 
74
145
  ```bash
75
146
  # Default annotated ASCII tree
@@ -105,7 +176,7 @@ npx cartotree --no-exports
105
176
 
106
177
  ---
107
178
 
108
- ## Options
179
+ ### Options
109
180
 
110
181
  | Option | Default | Description |
111
182
  |--------|---------|-------------|
@@ -120,7 +191,7 @@ npx cartotree --no-exports
120
191
 
121
192
  ---
122
193
 
123
- ## Configuration
194
+ ### Configuration
124
195
 
125
196
  Create `.cartotreerc` in your project root to set persistent defaults:
126
197
 
@@ -138,7 +209,7 @@ Now `npx cartotree` automatically runs with `--ai --no-exports`.
138
209
 
139
210
  ---
140
211
 
141
- ## Folder Annotations
212
+ ### Folder Annotations
142
213
 
143
214
  Add a `.folder.md` to any directory — the first line becomes the annotation:
144
215
 
@@ -151,7 +222,7 @@ cartotree also falls back to the first line of `README.md` if no `.folder.md` ex
151
222
 
152
223
  ---
153
224
 
154
- ## Ignoring Files
225
+ ### Ignoring Files
155
226
 
156
227
  Create `.cartotreeignore` in your project root:
157
228
 
@@ -167,7 +238,7 @@ coverage
167
238
 
168
239
  ---
169
240
 
170
- ## `--sync` Integration
241
+ ### `--sync` Integration
171
242
 
172
243
  Running `cartotree --sync` injects the tree between marker tags:
173
244
 
@@ -181,7 +252,7 @@ Works with `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, or any file.
181
252
 
182
253
  ---
183
254
 
184
- ## Export Parsing
255
+ ### Export Parsing
185
256
 
186
257
  cartotree reads your source files and surfaces exported symbols directly in the tree:
187
258
 
@@ -195,6 +266,5 @@ Supports `.js`, `.ts`, `.jsx`, `.tsx`, `.mjs`, `.cjs`.
195
266
  ---
196
267
 
197
268
  ## License
198
- MIT
199
269
 
200
- ---
270
+ MIT
package/bin/cartotree.js CHANGED
@@ -7,11 +7,12 @@ const { syncToFile } = require('../src/sync');
7
7
  const { copyToClipboard } = require('../src/clipboard');
8
8
  const { loadIgnorePatterns } = require('../src/ignore');
9
9
  const { loadConfig } = require('../src/config');
10
+ const { version } = require('../package.json');
10
11
 
11
12
  program
12
13
  .name('cartotree')
13
- .description('AI-friendly annotated directory tree')
14
- .version('0.1.0')
14
+ .description('AI-friendly annotated directory tree + code navigation for agents')
15
+ .version(version)
15
16
  .option('-d, --depth <number>', 'max depth')
16
17
  .option('-e, --exclude <patterns>', 'exclude patterns (comma-separated)')
17
18
  .option('--ai', 'AI-optimized compact format')
@@ -20,36 +21,142 @@ program
20
21
  .option('--copy', 'copy to clipboard')
21
22
  .option('--sync [file]', 'sync to CLAUDE.md or specified file')
22
23
  .option('--full', 'no depth limit')
23
- .parse(process.argv);
24
-
25
- const opts = program.opts();
26
- const config = loadConfig(process.cwd());
27
-
28
- const depth = opts.full ? Infinity : parseInt(opts.depth ?? config.depth);
29
- const useAI = opts.ai || config.ai;
30
- const useJSON = opts.json || config.json;
31
- const useCopy = opts.copy || config.copy;
32
- const useSync = opts.sync || config.sync;
33
- const showExports = opts.exports ?? config.exports;
34
-
35
- const ignorePatterns = loadIgnorePatterns(process.cwd());
36
- const manualExclude = opts.exclude ? opts.exclude.split(',').map(s => s.trim()) : [];
37
- const exclude = [...new Set([...ignorePatterns, ...manualExclude])];
38
- const target = typeof useSync === 'string' ? useSync : 'CLAUDE.md';
39
-
40
- let output;
41
- if (useAI) {
42
- output = generateAI(process.cwd(), { depth, exclude, showExports });
43
- } else if (useJSON) {
44
- output = generateJSON(process.cwd(), { depth, exclude, showExports });
45
- } else {
46
- output = generateTree(process.cwd(), { depth, exclude, showExports });
47
- }
48
-
49
- if (useCopy) {
50
- copyToClipboard(output);
51
- } else if (useSync) {
52
- syncToFile(output, target);
53
- } else {
54
- console.log(output);
55
- }
24
+ .action(opts => {
25
+ const config = loadConfig(process.cwd());
26
+ const depth = opts.full ? Infinity : parseInt(opts.depth ?? config.depth);
27
+ const useAI = opts.ai || config.ai;
28
+ const useJSON = opts.json || config.json;
29
+ const useCopy = opts.copy || config.copy;
30
+ const useSync = opts.sync || config.sync;
31
+ const showExports = opts.exports ?? config.exports;
32
+
33
+ const ignorePatterns = loadIgnorePatterns(process.cwd());
34
+ const manualExclude = opts.exclude ? opts.exclude.split(',').map(s => s.trim()) : [];
35
+ const exclude = [...new Set([...ignorePatterns, ...manualExclude])];
36
+ const target = typeof useSync === 'string' ? useSync : 'CLAUDE.md';
37
+
38
+ let output;
39
+ if (useAI) output = generateAI(process.cwd(), { depth, exclude, showExports });
40
+ else if (useJSON) output = generateJSON(process.cwd(), { depth, exclude, showExports });
41
+ else output = generateTree(process.cwd(), { depth, exclude, showExports });
42
+
43
+ if (useCopy) copyToClipboard(output);
44
+ else if (useSync) syncToFile(output, target);
45
+ else console.log(output);
46
+ });
47
+
48
+ // ---------- atlas: navigation commands for agents ----------
49
+
50
+ program
51
+ .command('locate <task...>')
52
+ .description('suggest which files to open first for a task (no LLM): BM25F over path/exports/code/past commit messages + import-graph boost')
53
+ .option('-k, --top <n>', 'number of results', '6')
54
+ .option('--no-history', 'ignore git commit history')
55
+ .option('--tests', 'include test files')
56
+ .option('--json', 'JSON output')
57
+ .action((task, o) => {
58
+ const { buildIndex, search } = require('../src/atlas/locate');
59
+ const { readHistory } = require('../src/atlas/git');
60
+ const root = process.cwd();
61
+ const { cached } = require('../src/atlas/cache');
62
+ const index = cached(root, 'locate', { tests: !!o.tests, history: o.history, v: 2 }, () =>
63
+ buildIndex(root, { includeTests: !!o.tests, graph: true, chunks: true, history: o.history ? readHistory(root) : null }));
64
+ const res = search(index, task.join(' '), { k: parseInt(o.top), chunkWeight: 0.5 });
65
+ if (o.history && res.length) {
66
+ // attach "usually changes with" for the top 2 results: helps find the second file of a change
67
+ const { coChanges } = require('../src/atlas/git');
68
+ const hist = readHistory(root);
69
+ const known = new Set(index.files);
70
+ for (const r of res.slice(0, 2)) {
71
+ const cc = coChanges(hist, r.file, 8);
72
+ if (cc.total >= 2) r.changesWith = cc.files.filter(c => known.has(c.file) && c.ratio >= 0.3).slice(0, 2);
73
+ }
74
+ }
75
+ if (o.json) return console.log(JSON.stringify({ ambiguous: !!res.ambiguous, results: res }, null, 2));
76
+ if (!res.length) return console.log('no match — try other words (function names, folder names)');
77
+ const lines = res.map((r, i) => {
78
+ const ev = (r.evidence || []).map(e => `\n L${e.line}: ${e.code}`).join('')
79
+ + (r.changesWith && r.changesWith.length ? `\n usually changes with: ${r.changesWith.map(c => `${c.file} (${Math.round(c.ratio * 100)}%)`).join(', ')}` : '');
80
+ return `${i + 1}. ${r.file} (score ${r.score}; ${r.matched.join(', ')})${ev}`;
81
+ });
82
+ if (res.ambiguous) lines.unshift('! top results are close — verify before choosing');
83
+ console.log(lines.join('\n'));
84
+ });
85
+
86
+ program
87
+ .command('links <target>')
88
+ .description('connection map for a file (imports, importers, co-changes, recent commits) or a symbol (definition + call sites)')
89
+ .option('--json', 'JSON output')
90
+ .action((target, o) => {
91
+ const fs = require('fs');
92
+ const { buildGraph, symbolLinks, fileLinks } = require('../src/atlas/links');
93
+ const root = process.cwd();
94
+ const { cached } = require('../src/atlas/cache');
95
+ const graph = cached(root, 'graph', {}, () => buildGraph(root));
96
+ const isFile = graph.set.has(target) || fs.existsSync(target);
97
+ const res = isFile ? fileLinks(graph, root, target) : symbolLinks(graph, target, { root });
98
+ if (o.json) return console.log(JSON.stringify(res, null, 2));
99
+ const out = [];
100
+ if (isFile) {
101
+ out.push(`# ${res.file}`);
102
+ if (res.exports.length) out.push(`exports: ${res.exports.slice(0, 12).join(', ')}`);
103
+ out.push(`imports (${res.imports.length}): ${res.imports.join(', ') || '-'}`);
104
+ out.push(`imported by (${res.importedByCount}): ${res.importedBy.join(', ') || '-'}`);
105
+ if (res.changedWith.total) {
106
+ out.push(`usually changes with (of ${res.changedWith.total} commits):`);
107
+ res.changedWith.files.forEach(c => out.push(` ${c.file} ${Math.round(c.ratio * 100)}%`));
108
+ }
109
+ if (res.recent.length) {
110
+ out.push('recent commits:');
111
+ res.recent.forEach(c => out.push(` ${c.date} ${c.hash} ${c.subject}`));
112
+ }
113
+ } else {
114
+ out.push(`# symbol ${res.symbol}`);
115
+ out.push('defined in: ' + (res.definedIn.map(d => `${d.file}:${d.line}${d.exported ? ' (exported)' : ''}`).join(', ') || '-'));
116
+ out.push('used in:');
117
+ res.usedIn.forEach(u => out.push(` ${u.file} (${u.count}x) ${u.first}`));
118
+ if (res.moreFiles) out.push(` ... +${res.moreFiles} more files`);
119
+ }
120
+ console.log(out.join('\n'));
121
+ });
122
+
123
+ program
124
+ .command('peek <file> <words...>')
125
+ .description('show only the lines of a file that contain the given words (compact grep for verifying a candidate)')
126
+ .option('-n, --max <n>', 'max lines', '10')
127
+ .option('--json', 'JSON output')
128
+ .action((file, words, o) => {
129
+ const { peek } = require('../src/atlas/peek');
130
+ const r = peek(process.cwd(), file, words, { max: parseInt(o.max) });
131
+ if (o.json) return console.log(JSON.stringify(r, null, 2));
132
+ if (r.error) return console.log(`${file}: ${r.error}`);
133
+ const out = [`# ${r.file} (${r.totalLines} lines, ${r.matchedLines} matching)`];
134
+ r.lines.forEach(l => out.push(`${l.line}: ${l.code}`));
135
+ if (r.matchedLines > r.lines.length) out.push(`... ${r.matchedLines - r.lines.length} more matching lines`);
136
+ console.log(out.join('\n'));
137
+ });
138
+
139
+ program
140
+ .command('mcp')
141
+ .description('run the cartotree MCP server over stdio (tools: cartotree_locate, cartotree_peek, cartotree_links)')
142
+ .action(async () => {
143
+ const { startMcpServer } = require('../src/atlas/mcp');
144
+ await startMcpServer(process.cwd());
145
+ });
146
+
147
+ program
148
+ .command('init')
149
+ .description('set up this project so AI agents use cartotree automatically (skill + MCP server + reminder hook)')
150
+ .option('--agent <names>', 'comma-separated: claude-code, cursor, codex, windsurf (default: detect)')
151
+ .option('--no-hook', 'do not add the SessionStart reminder hook')
152
+ .option('--dry-run', 'show what would change, write nothing')
153
+ .action(o => {
154
+ const { runInit } = require('../src/atlas/init');
155
+ const agents = o.agent ? o.agent.split(',').map(s => s.trim()) : null;
156
+ const { agents: list, report } = runInit(process.cwd(), { agents, hook: o.hook, dryRun: !!o.dryRun });
157
+ console.log(`cartotree init${o.dryRun ? ' (dry run)' : ''} — agents: ${list.join(', ')}`);
158
+ report.forEach(l => console.log(' ' + l));
159
+ if (!o.dryRun) console.log('\nRestart your agent session to load the MCP server and skill.');
160
+ });
161
+
162
+ program.parse(process.argv);
@@ -0,0 +1,14 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "echo 'cartotree is available: to find where code lives, call cartotree_locate first (then cartotree_peek to confirm) before grep or reading whole files.'"
9
+ }
10
+ ]
11
+ }
12
+ ]
13
+ }
14
+ }
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "cartotree",
3
- "version": "0.1.1",
4
- "description": "AI-friendly codebase mapping CLI — annotated directory trees that save tokens",
3
+ "version": "0.2.1",
4
+ "description": "Find the right files with few tokens — annotated trees plus locate/peek/links for AI agents (CLI + MCP server + skill)",
5
5
  "main": "src/tree.js",
6
+ "scripts": {
7
+ "test": "node --test"
8
+ },
6
9
  "bin": {
7
10
  "cartotree": "bin/cartotree.js"
8
11
  },
@@ -13,16 +16,30 @@
13
16
  "tree",
14
17
  "claude",
15
18
  "cursor",
16
- "tokens"
19
+ "tokens",
20
+ "mcp",
21
+ "claude-code",
22
+ "agents"
17
23
  ],
18
24
  "license": "MIT",
25
+ "files": [
26
+ "bin",
27
+ "src",
28
+ "skills",
29
+ "hooks",
30
+ ".claude-plugin",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
19
34
  "repository": {
20
35
  "type": "git",
21
36
  "url": "git+https://github.com/kingluminance/cartotree.git"
22
37
  },
23
38
  "dependencies": {
24
- "commander": "^11.0.0",
39
+ "@modelcontextprotocol/sdk": "^1.32.2",
25
40
  "chalk": "^4.0.0",
26
- "clipboardy": "^2.0.0"
41
+ "clipboardy": "^2.0.0",
42
+ "commander": "^11.0.0",
43
+ "zod": "^4.6.7"
27
44
  }
28
45
  }
@@ -0,0 +1,32 @@
1
+ ---
2
+ name: cartotree
3
+ description: Navigate a codebase cheaply with cartotree. Use when you need to find which files to change for a task, confirm a candidate file, or follow how files and symbols connect — especially in large or unfamiliar repositories — before falling back to grep or reading whole files.
4
+ ---
5
+
6
+ # cartotree — find the right files with few tokens
7
+
8
+ The `cartotree_*` MCP tools (or the `npx cartotree` CLI) answer "where is this?" from a local index — no file dumps.
9
+
10
+ ## Workflow (fast mode — the default)
11
+
12
+ 1. **Locate first.** `cartotree_locate` with the task in plain words (CLI: `npx cartotree locate <words>`).
13
+ You get ranked files, each with 1–2 evidence lines, and sometimes *usually changes with* (files often edited together, from git history).
14
+ 2. **Decide from the evidence.** If rank 1's evidence clearly implements the described behavior, go with it.
15
+ 3. **Verify only when unsure.** If you see `! top results are close`, or the evidence is weak, call
16
+ `cartotree_peek` on the top 1–2 candidates with the task's key words (CLI: `npx cartotree peek <file> <words...>`).
17
+ Prefer peek over grep or reading whole files.
18
+ 4. **Second file?** If the change likely spans two files (component + locales, implementation + its caller),
19
+ check *usually changes with* or `cartotree_links <file>`.
20
+ 5. **Follow a call chain** with `cartotree_links <SymbolName>`: where it is defined and called, one line each.
21
+
22
+ ## Tips
23
+
24
+ - If locate misses, run it again with words that would appear in the code (guessed function/file names, camelCase).
25
+ - Words that never appear in code (e.g. a feature's marketing name) won't match; search for the identifiers instead.
26
+ - Keep listing 2–3 candidate files when unsure rather than committing to one too early.
27
+ - Fall back to grep/read only after locate + peek did not find it.
28
+
29
+ ## Measured effect
30
+
31
+ On a 21k-file TypeScript monorepo with 30 real commits (Haiku agent): same accuracy as a grep-only agent,
32
+ 63–80% fewer tool-output tokens, 17–66% less time.
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Disk cache for atlas indexes so repeated agent calls are fast.
3
+ * Key = git HEAD + working-tree changes + options. Stored with v8.serialize (keeps Map objects).
4
+ */
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const v8 = require('v8');
8
+ const crypto = require('crypto');
9
+ const { execSync } = require('child_process');
10
+
11
+ function repoState(root) {
12
+ try {
13
+ const head = execSync('git rev-parse HEAD', { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
14
+ const dirty = execSync('git status --porcelain --untracked-files=normal', { cwd: root, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 1 << 26 }).toString();
15
+ return head + '\n' + dirty.split('\n').filter(l => !l.includes('.cartotree/')).join('\n');
16
+ } catch {
17
+ return null; // not a git repo -> no caching
18
+ }
19
+ }
20
+
21
+ function cached(root, name, opts, build) {
22
+ if (process.env.CARTOTREE_NO_CACHE) return build();
23
+ const state = repoState(root);
24
+ if (state === null) return build();
25
+ const key = crypto.createHash('sha1')
26
+ .update(name + '\n' + JSON.stringify(opts) + '\n' + (process.env.CARTOTREE_HISTORY_SKIP || '') + '\n' + state)
27
+ .digest('hex').slice(0, 16);
28
+ const dir = path.join(root, '.cartotree', 'cache');
29
+ const file = path.join(dir, `${name}-${key}.bin`);
30
+ if (fs.existsSync(file)) {
31
+ try {
32
+ return v8.deserialize(fs.readFileSync(file));
33
+ } catch { /* corrupted cache -> rebuild */ }
34
+ }
35
+ const value = build();
36
+ try {
37
+ fs.mkdirSync(dir, { recursive: true });
38
+ const gi = path.join(root, '.cartotree', '.gitignore');
39
+ if (!fs.existsSync(gi)) fs.writeFileSync(gi, 'cache/\n');
40
+ for (const old of fs.readdirSync(dir)) if (old.startsWith(name + '-') && old !== path.basename(file)) fs.unlinkSync(path.join(dir, old));
41
+ fs.writeFileSync(file, v8.serialize(value));
42
+ } catch { /* read-only repo: just skip caching */ }
43
+ return value;
44
+ }
45
+
46
+ module.exports = { cached };
@@ -0,0 +1,56 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { execSync } = require('child_process');
4
+
5
+ const SRC_RE = /\.(ts|tsx|js|jsx|mjs|cjs)$/;
6
+ const SKIP_RE = /(^|\/)(node_modules|dist|build|coverage|\.next|out)\//;
7
+ const TEST_RE = /(\.test\.|\.spec\.|__tests__\/|(^|\/)tests?\/|fixtures\/|\.d\.ts$)/;
8
+
9
+ function isGitRepo(root) {
10
+ try {
11
+ execSync('git rev-parse --is-inside-work-tree', { cwd: root, stdio: 'ignore' });
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ }
17
+
18
+ function walk(root, dir = '', out = []) {
19
+ let entries;
20
+ try {
21
+ entries = fs.readdirSync(path.join(root, dir), { withFileTypes: true });
22
+ } catch {
23
+ return out;
24
+ }
25
+ for (const e of entries) {
26
+ if (e.name.startsWith('.') && e.isDirectory()) continue;
27
+ const rel = dir ? `${dir}/${e.name}` : e.name;
28
+ if (e.isDirectory()) {
29
+ if (!SKIP_RE.test(rel + '/')) walk(root, rel, out);
30
+ } else {
31
+ out.push(rel);
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /** Source files (relative paths), tests excluded unless includeTests. */
38
+ function listSourceFiles(root, { includeTests = false } = {}) {
39
+ let files;
40
+ if (isGitRepo(root)) {
41
+ files = execSync('git ls-files', { cwd: root, maxBuffer: 1 << 28 }).toString().split('\n').filter(Boolean);
42
+ } else {
43
+ files = walk(root);
44
+ }
45
+ return files.filter(f => SRC_RE.test(f) && !SKIP_RE.test(f) && (includeTests || !TEST_RE.test(f)));
46
+ }
47
+
48
+ function readSafe(root, rel, max = 200000) {
49
+ try {
50
+ return fs.readFileSync(path.join(root, rel), 'utf-8').slice(0, max);
51
+ } catch {
52
+ return '';
53
+ }
54
+ }
55
+
56
+ module.exports = { listSourceFiles, readSafe, isGitRepo, SRC_RE, TEST_RE };
@@ -0,0 +1,65 @@
1
+ const { execSync } = require('child_process');
2
+ const { isGitRepo } = require('./files');
3
+
4
+ /**
5
+ * Read recent commit history once.
6
+ * @returns {{commits: {hash:string, date:string, subject:string, files:string[]}[]}}
7
+ */
8
+ function readHistoryRaw(root, { limit = 3000, skip = parseInt(process.env.CARTOTREE_HISTORY_SKIP || '0'), maxFilesPerCommit = 25 } = {}) {
9
+ if (!isGitRepo(root)) return { commits: [] };
10
+ let raw;
11
+ try {
12
+ raw = execSync(
13
+ `git log -n ${limit} --skip=${skip} --no-merges --name-only --date=short --pretty=format:@@%h%x09%ad%x09%s`,
14
+ { cwd: root, maxBuffer: 1 << 28 }
15
+ ).toString();
16
+ } catch {
17
+ return { commits: [] };
18
+ }
19
+ const commits = [];
20
+ for (const block of raw.split('@@').slice(1)) {
21
+ const lines = block.split('\n').filter(Boolean);
22
+ const [hash, date, ...subj] = lines[0].split('\t');
23
+ const files = lines.slice(1);
24
+ if (files.length && files.length <= maxFilesPerCommit) commits.push({ hash, date, subject: subj.join('\t'), files });
25
+ }
26
+ return { commits };
27
+ }
28
+
29
+ function readHistory(root, opts = {}) {
30
+ const { cached } = require('./cache');
31
+ return cached(root, 'history', opts, () => readHistoryRaw(root, opts));
32
+ }
33
+
34
+ /** How often each file changed (heat). */
35
+ function heatMap(history) {
36
+ const heat = new Map();
37
+ for (const c of history.commits) for (const f of c.files) heat.set(f, (heat.get(f) || 0) + 1);
38
+ return heat;
39
+ }
40
+
41
+ /** Files that usually change together with `file`. */
42
+ function coChanges(history, file, top = 5) {
43
+ const counts = new Map();
44
+ let total = 0;
45
+ for (const c of history.commits) {
46
+ if (!c.files.includes(file)) continue;
47
+ total++;
48
+ for (const f of c.files) if (f !== file) counts.set(f, (counts.get(f) || 0) + 1);
49
+ }
50
+ return {
51
+ total,
52
+ files: [...counts.entries()]
53
+ .sort((a, b) => b[1] - a[1])
54
+ .slice(0, top)
55
+ .map(([f, n]) => ({ file: f, together: n, ratio: +(n / total).toFixed(2) })),
56
+ };
57
+ }
58
+
59
+ /** Recent commits touching a file. */
60
+ function recentChanges(history, file, top = 3) {
61
+ return history.commits.filter(c => c.files.includes(file)).slice(0, top)
62
+ .map(({ hash, date, subject }) => ({ hash, date, subject }));
63
+ }
64
+
65
+ module.exports = { readHistory, heatMap, coChanges, recentChanges };
@@ -0,0 +1,114 @@
1
+ /**
2
+ * cartotree init — set up a project so AI agents use cartotree automatically.
3
+ * Only runs when the user calls it (never from npm postinstall). Shows every change; --dry-run writes nothing.
4
+ *
5
+ * Claude Code:
6
+ * .claude/skills/cartotree/SKILL.md how and when to use the tools
7
+ * .mcp.json registers the cartotree MCP server
8
+ * .claude/settings.json SessionStart hook with a one-line reminder (skip with --no-hook)
9
+ * .gitignore ignores .cartotree/ (index cache)
10
+ * Other agents (Cursor, Codex, ...): writes the skill under their skills folder when it exists.
11
+ */
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+
15
+ const SKILL_SRC = path.join(__dirname, '..', '..', 'skills', 'cartotree', 'SKILL.md');
16
+ const HOOK_CMD = "echo 'cartotree is available: to find where code lives, call cartotree_locate first (then cartotree_peek to confirm) before grep or reading whole files.'";
17
+ const MCP_ENTRY = { command: 'npx', args: ['-y', 'cartotree@latest', 'mcp'] };
18
+
19
+ const AGENT_SKILL_DIRS = {
20
+ 'claude-code': '.claude/skills',
21
+ cursor: '.cursor/skills',
22
+ codex: '.codex/skills',
23
+ windsurf: '.windsurf/skills',
24
+ };
25
+
26
+ function readJson(file, fallback) {
27
+ try {
28
+ return JSON.parse(fs.readFileSync(file, 'utf-8'));
29
+ } catch {
30
+ return fallback;
31
+ }
32
+ }
33
+
34
+ function detectAgents(root) {
35
+ const found = Object.keys(AGENT_SKILL_DIRS).filter(a => fs.existsSync(path.join(root, AGENT_SKILL_DIRS[a].split('/')[0])));
36
+ return found.length ? found : ['claude-code'];
37
+ }
38
+
39
+ function plan(root, { agents, hook = true } = {}) {
40
+ const steps = [];
41
+ const list = agents && agents.length ? agents : detectAgents(root);
42
+ const skill = fs.readFileSync(SKILL_SRC, 'utf-8');
43
+
44
+ for (const a of list) {
45
+ const dir = AGENT_SKILL_DIRS[a];
46
+ if (!dir) continue;
47
+ steps.push({ file: path.join(dir, 'cartotree', 'SKILL.md'), why: `skill for ${a}`, write: () => skill });
48
+ }
49
+
50
+ if (list.includes('claude-code')) {
51
+ steps.push({
52
+ file: '.mcp.json',
53
+ why: 'register cartotree MCP server',
54
+ write: prev => {
55
+ const j = prev ? JSON.parse(prev) : {};
56
+ j.mcpServers = { ...(j.mcpServers || {}), cartotree: MCP_ENTRY };
57
+ return JSON.stringify(j, null, 2) + '\n';
58
+ },
59
+ });
60
+ if (hook) {
61
+ steps.push({
62
+ file: '.claude/settings.json',
63
+ why: 'SessionStart reminder to use cartotree',
64
+ write: prev => {
65
+ const j = prev ? JSON.parse(prev) : {};
66
+ j.hooks = j.hooks || {};
67
+ const ss = (j.hooks.SessionStart = j.hooks.SessionStart || []);
68
+ const exists = ss.some(g => (g.hooks || []).some(h => h.command === HOOK_CMD));
69
+ if (!exists) ss.push({ hooks: [{ type: 'command', command: HOOK_CMD }] });
70
+ return JSON.stringify(j, null, 2) + '\n';
71
+ },
72
+ });
73
+ }
74
+ }
75
+
76
+ steps.push({
77
+ file: '.gitignore',
78
+ why: 'ignore index cache',
79
+ write: prev => {
80
+ const body = prev || '';
81
+ if (body.split('\n').some(l => l.trim() === '.cartotree/')) return body;
82
+ return body + (body && !body.endsWith('\n') ? '\n' : '') + '.cartotree/\n';
83
+ },
84
+ });
85
+ return { agents: list, steps };
86
+ }
87
+
88
+ function runInit(root, { agents, hook = true, dryRun = false } = {}) {
89
+ const { agents: list, steps } = plan(root, { agents, hook });
90
+ const report = [];
91
+ for (const s of steps) {
92
+ const abs = path.join(root, s.file);
93
+ const prev = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf-8') : null;
94
+ if (prev !== null && s.file.endsWith('.json')) {
95
+ if (readJson(abs, null) === null) {
96
+ report.push(`skip ${s.file} (not valid JSON — edit it by hand)`);
97
+ continue;
98
+ }
99
+ }
100
+ const next = s.write(prev);
101
+ if (prev === next) {
102
+ report.push(`ok ${s.file} (already set up)`);
103
+ continue;
104
+ }
105
+ report.push(`${prev === null ? 'create' : 'update'} ${s.file} — ${s.why}`);
106
+ if (!dryRun) {
107
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
108
+ fs.writeFileSync(abs, next);
109
+ }
110
+ }
111
+ return { agents: list, report };
112
+ }
113
+
114
+ module.exports = { runInit, plan, MCP_ENTRY };
@@ -0,0 +1,87 @@
1
+ /**
2
+ * atlas links — a compact "connection map" for a file or symbol, so an agent
3
+ * can follow a call chain without reading whole files.
4
+ */
5
+ const { listSourceFiles, readSafe } = require('./files');
6
+ const { parseExportsFromText, parseImports } = require('./symbols');
7
+ const { readHistory, coChanges, recentChanges } = require('./git');
8
+
9
+ function buildGraph(root) {
10
+ const files = listSourceFiles(root, { includeTests: true });
11
+ const set = new Set(files);
12
+ const imports = new Map();
13
+ const importers = new Map();
14
+ const exportsOf = new Map();
15
+ for (const f of files) {
16
+ const t = readSafe(root, f);
17
+ exportsOf.set(f, parseExportsFromText(t));
18
+ const im = parseImports(t, f, set);
19
+ imports.set(f, im);
20
+ for (const g of im) {
21
+ if (!importers.has(g)) importers.set(g, []);
22
+ importers.get(g).push(f);
23
+ }
24
+ }
25
+ return { files, set, imports, importers, exportsOf };
26
+ }
27
+
28
+ function lineOf(text, idx) {
29
+ return text.slice(0, idx).split('\n').length;
30
+ }
31
+
32
+ /** Where a symbol is defined and where it is called (file:line + trimmed code). */
33
+ function candidateFiles(root, graph, name) {
34
+ try {
35
+ const out = require('child_process').execSync(`git grep -l -w -- ${JSON.stringify(name)}`, { cwd: root, maxBuffer: 1 << 26, stdio: ['ignore', 'pipe', 'ignore'] }).toString();
36
+ return out.split('\n').filter(f => graph.set.has(f));
37
+ } catch (e) {
38
+ return e.status === 1 ? [] : graph.files; // 1 = no match; otherwise not git -> scan all
39
+ }
40
+ }
41
+
42
+ function symbolLinks(graph, name, { maxUses = 12, root = process.cwd() } = {}) {
43
+ const defs = [];
44
+ const uses = [];
45
+ const defRe = new RegExp(`(?:function\\*?|class|const|let|var|type|interface|enum)\\s+${name}\\b`);
46
+ const useRe = new RegExp(`\\b${name}\\s*[(<.]`, 'g');
47
+ for (const f of candidateFiles(root, graph, name)) {
48
+ const t = readSafe(root, f);
49
+ if (!t.includes(name)) continue;
50
+ const d = defRe.exec(t);
51
+ if (d) defs.push({ file: f, line: lineOf(t, d.index), exported: graph.exportsOf.get(f).includes(name) });
52
+ let m;
53
+ while ((m = useRe.exec(t)) && uses.length < maxUses * 4) {
54
+ if (d && m.index >= d.index && m.index <= d.index + d[0].length + 2) continue;
55
+ const ln = lineOf(t, m.index);
56
+ const code = t.split('\n')[ln - 1].trim().slice(0, 90);
57
+ uses.push({ file: f, line: ln, code });
58
+ }
59
+ }
60
+ const byFile = new Map();
61
+ for (const u of uses) {
62
+ if (!byFile.has(u.file)) byFile.set(u.file, []);
63
+ byFile.get(u.file).push(u);
64
+ }
65
+ return {
66
+ symbol: name,
67
+ definedIn: defs,
68
+ usedIn: [...byFile.entries()].slice(0, maxUses).map(([file, us]) => ({ file, count: us.length, first: `${us[0].line}: ${us[0].code}` })),
69
+ moreFiles: Math.max(0, byFile.size - maxUses),
70
+ };
71
+ }
72
+
73
+ /** What a file pulls in, who depends on it, and how it tends to change. */
74
+ function fileLinks(graph, root, file, { history = null } = {}) {
75
+ const hist = history || readHistory(root);
76
+ return {
77
+ file,
78
+ exports: graph.exportsOf.get(file) || [],
79
+ imports: graph.imports.get(file) || [],
80
+ importedBy: (graph.importers.get(file) || []).slice(0, 15),
81
+ importedByCount: (graph.importers.get(file) || []).length,
82
+ changedWith: coChanges(hist, file),
83
+ recent: recentChanges(hist, file),
84
+ };
85
+ }
86
+
87
+ module.exports = { buildGraph, symbolLinks, fileLinks };
@@ -0,0 +1,218 @@
1
+ /**
2
+ * atlas locate — find where a task should start, without calling an LLM.
3
+ *
4
+ * Scoring = BM25F over three fields of every source file:
5
+ * path — folder and file name words (strongest signal)
6
+ * exports — exported symbol names
7
+ * body — identifiers and words used in the code
8
+ * plus light stemming, an optional neighbor boost over the import graph,
9
+ * and an "ambiguous" flag when the top results are close.
10
+ */
11
+ const { listSourceFiles, readSafe } = require('./files');
12
+ const { parseExportsFromText, parseImports } = require('./symbols');
13
+
14
+ const STOP = new Set(['in', 'on', 'of', 'to', 'an', 'as', 'at', 'by', 'is', 'it', 'or', 'be', 'if', 'so', 'do', 'we', 'up', 'no', 'its', 'the', 'and', 'for', 'with', 'from', 'when', 'into', 'that', 'this', 'are', 'not', 'fix', 'feat',
15
+ 'refactor', 'perf', 'add', 'use', 'its', 'all', 'any', 'out', 'new', 'get', 'set', 'make', 'only', 'also', 'via',
16
+ 'should', 'can', 'will', 'was', 'has', 'have', 'been', 'but', 'than', 'then', 'them', 'they', 'their', 'there',
17
+ 'instead', 'before', 'after', 'during', 'keep', 'let', 'more', 'less', 'one', 'two', 'too', 'does', 'don', 'isn']);
18
+
19
+ /** very light English stemmer: enough to merge locale/locales/localize, clean/cleanup/cleaning */
20
+ function stem(w) {
21
+ if (w.length <= 4) return w;
22
+ for (const suf of ['izations', 'ization', 'ations', 'ation', 'ings', 'ing', 'izes', 'ized', 'ize', 'ies', 'ers', 'er', 'es', 'ed', 's']) {
23
+ if (w.endsWith(suf) && w.length - suf.length >= 4) {
24
+ const r = w.slice(0, -suf.length);
25
+ // setting -> sett -> set, running -> runn -> run
26
+ return /([bdgmnprt])\1$/.test(r) ? r.slice(0, -1) : r;
27
+ }
28
+ }
29
+ return w;
30
+ }
31
+
32
+ function splitWords(s) {
33
+ return s
34
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
35
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
36
+ .split(/[^A-Za-z0-9]+/)
37
+ .map(w => w.toLowerCase())
38
+ .filter(w => w.length > 1 && !STOP.has(w) && !/^\d+$/.test(w))
39
+ .map(stem);
40
+ }
41
+
42
+ function counts(words) {
43
+ const m = new Map();
44
+ for (const w of words) m.set(w, (m.get(w) || 0) + 1);
45
+ return m;
46
+ }
47
+
48
+ const FIELDS = ['path', 'exports', 'body', 'hist'];
49
+
50
+ function buildIndex(root, opts = {}) {
51
+ const files = listSourceFiles(root, opts);
52
+ const fileSet = new Set(files);
53
+ const docs = [];
54
+ const texts = [];
55
+ for (const f of files) {
56
+ const text = readSafe(root, f, 80000);
57
+ texts.push(text);
58
+ docs.push({
59
+ path: counts(splitWords(f)),
60
+ exports: counts(splitWords(parseExportsFromText(text).join(' '))),
61
+ body: counts(splitWords((text.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g) || []).slice(0, 6000).join(' '))),
62
+ });
63
+ }
64
+ // hist: words from past commit messages that touched the file ("what this file has been about")
65
+ const histWords = new Map();
66
+ if (opts.history) {
67
+ for (const c of opts.history.commits) {
68
+ const ws = splitWords(c.subject.replace(/^\w+(\([^)]*\))?!?:\s*/, m => m.replace(/[()!:]/g, ' ')));
69
+ for (const f of c.files) {
70
+ if (!fileSet.has(f)) continue;
71
+ if (!histWords.has(f)) histWords.set(f, []);
72
+ const arr = histWords.get(f);
73
+ if (arr.length < 3000) arr.push(...ws);
74
+ }
75
+ }
76
+ }
77
+ files.forEach((f, i) => { docs[i].hist = counts(histWords.get(f) || []); });
78
+ if (opts.chunks) {
79
+ // split code into top-level blocks (functions/classes/consts) so a match inside one function is not diluted by the whole file
80
+ files.forEach((f, i) => {
81
+ const lines = texts[i].split('\n');
82
+ const chunks = [];
83
+ let cur = [];
84
+ const flush = () => { if (cur.length) { chunks.push(counts(splitWords((cur.join(' ').match(/[A-Za-z_][A-Za-z0-9_]{2,}/g) || []).join(' ')))); cur = []; } };
85
+ for (const ln of lines) {
86
+ if ((/^(export\s|function\s|class\s|const\s|async\s|interface\s|type\s)/.test(ln) && cur.length > 5) || cur.length >= 80) flush();
87
+ cur.push(ln);
88
+ }
89
+ flush();
90
+ docs[i].chunks = chunks.map(c => { let len = 0; for (const v of c.values()) len += v; return { c, len }; });
91
+ });
92
+ }
93
+ const df = new Map();
94
+ const avgLen = {};
95
+ for (const fld of FIELDS) {
96
+ let total = 0;
97
+ for (const d of docs) {
98
+ let len = 0;
99
+ for (const v of d[fld].values()) len += v;
100
+ d[fld + 'Len'] = len;
101
+ total += len;
102
+ }
103
+ avgLen[fld] = total / Math.max(1, docs.length);
104
+ }
105
+ for (const d of docs) {
106
+ const seen = new Set([...d.path.keys(), ...d.exports.keys(), ...d.body.keys(), ...d.hist.keys()]);
107
+ for (const w of seen) df.set(w, (df.get(w) || 0) + 1);
108
+ }
109
+ let neighbors = null;
110
+ if (opts.graph) {
111
+ neighbors = files.map(() => []);
112
+ const pos = new Map(files.map((f, i) => [f, i]));
113
+ files.forEach((f, i) => {
114
+ for (const g of parseImports(texts[i], f, fileSet)) {
115
+ const j = pos.get(g);
116
+ if (j !== undefined) { neighbors[i].push(j); neighbors[j].push(i); }
117
+ }
118
+ });
119
+ }
120
+ return { root, files, docs, texts: opts.keepText ? texts : null, df, avgLen, N: docs.length, neighbors };
121
+ }
122
+
123
+ const DEFAULT_WEIGHTS = { path: 3.0, exports: 2.0, body: 1.0, hist: 1.5 };
124
+
125
+ function scoreAll(index, qWords, { weights = DEFAULT_WEIGHTS, k1 = 1.2, b = { path: 0.3, exports: 0.5, body: 0.75, hist: 0.5 } } = {}) {
126
+ const idf = new Map(qWords.map(w => {
127
+ const n = index.df.get(w) || 0;
128
+ return [w, n ? Math.log(1 + (index.N - n + 0.5) / (n + 0.5)) : 0];
129
+ }));
130
+ return index.docs.map(d => {
131
+ let s = 0;
132
+ const hit = [];
133
+ for (const w of qWords) {
134
+ if (!idf.get(w)) continue;
135
+ // BM25F: combine normalized term frequency across fields, then saturate once
136
+ let tf = 0;
137
+ for (const fld of FIELDS) {
138
+ if (!weights[fld]) continue;
139
+ const f = d[fld].get(w);
140
+ if (!f) continue;
141
+ tf += weights[fld] * f / (1 - b[fld] + b[fld] * d[fld + 'Len'] / (index.avgLen[fld] || 1));
142
+ }
143
+ if (!tf) continue;
144
+ const part = idf.get(w) * tf * (k1 + 1) / (tf + k1);
145
+ s += part;
146
+ hit.push([w, part]);
147
+ }
148
+ return { s, hit };
149
+ });
150
+ }
151
+
152
+ /** best single line of a file for the query words (evidence for the agent) */
153
+ function bestLines(text, qWords, n = 1) {
154
+ if (!text) return [];
155
+ const lines = text.split('\n');
156
+ const scored = [];
157
+ for (let i = 0; i < lines.length; i++) {
158
+ const ln = lines[i];
159
+ if (ln.length > 300) continue;
160
+ const ws = new Set(splitWords(ln));
161
+ let sc = 0;
162
+ for (const w of qWords) if (ws.has(w)) sc++;
163
+ if (sc) scored.push({ line: i + 1, sc, code: ln.trim().slice(0, 100) });
164
+ }
165
+ return scored.sort((a, b) => b.sc - a.sc || a.line - b.line).slice(0, n)
166
+ .sort((a, b) => a.line - b.line).map(({ line, code }) => ({ line, code }));
167
+ }
168
+
169
+ function search(index, query, opts = {}) {
170
+ const { k = 10, heat = null, heatWeight = 0.15, graphWeight = 0.3, snippet = true } = opts;
171
+ const qWords = [...new Set(splitWords(query))];
172
+ const base = scoreAll(index, qWords, opts);
173
+ if (opts.chunkWeight && index.docs[0] && index.docs[0].chunks) {
174
+ const idf = w => { const n = index.df.get(w) || 0; return n ? Math.log(1 + (index.N - n + 0.5) / (n + 0.5)) : 0; };
175
+ const qi = qWords.map(w => [w, idf(w)]).filter(x => x[1]);
176
+ const avg = 60;
177
+ base.forEach((x, i) => {
178
+ if (!x.s) return;
179
+ let best = 0;
180
+ for (const ch of index.docs[i].chunks) {
181
+ let sc = 0;
182
+ for (const [w, wi] of qi) {
183
+ const f = ch.c.get(w);
184
+ if (f) sc += wi * f * 2.2 / (f + 1.2 * (0.25 + 0.75 * ch.len / avg));
185
+ }
186
+ if (sc > best) best = sc;
187
+ }
188
+ x.s += opts.chunkWeight * best;
189
+ });
190
+ }
191
+ let scores = base.map(x => x.s);
192
+ if (index.neighbors && graphWeight) {
193
+ // a file whose neighbours also match is more likely the right place
194
+ scores = scores.map((s, i) => {
195
+ if (!s) return 0;
196
+ const nb = index.neighbors[i];
197
+ if (!nb.length) return s;
198
+ const top = nb.map(j => base[j].s).sort((a, c) => c - a).slice(0, 3);
199
+ return s + graphWeight * top.reduce((a, c) => a + c, 0) / 3;
200
+ });
201
+ }
202
+ if (heat) scores = scores.map((s, i) => s * (1 + heatWeight * Math.log1p(heat.get(index.files[i]) || 0)));
203
+ const order = scores.map((s, i) => [s, i]).filter(x => x[0] > 0).sort((a, c) => c[0] - a[0]).slice(0, k);
204
+ const { evidenceTop = 3, evidenceLines = 2 } = opts;
205
+ const out = order.map(([s, i], rank) => ({
206
+ file: index.files[i],
207
+ score: +s.toFixed(2),
208
+ matched: base[i].hit.sort((a, c) => c[1] - a[1]).slice(0, 4).map(([w]) => w),
209
+ ...(snippet ? { evidence: bestLines(index.texts ? index.texts[i] : readSafe(index.root, index.files[i], 200000), qWords, rank < evidenceTop ? evidenceLines : 1) } : {}),
210
+ }));
211
+ if (out.length > 1) {
212
+ const ratio = out[1].score / out[0].score;
213
+ out.ambiguous = ratio > 0.85;
214
+ }
215
+ return out;
216
+ }
217
+
218
+ module.exports = { buildIndex, search, splitWords, stem };
@@ -0,0 +1,106 @@
1
+ /**
2
+ * cartotree MCP server (stdio).
3
+ * Keeps the index in memory, so after the first call every lookup is a few milliseconds.
4
+ *
5
+ * Tools:
6
+ * cartotree_locate — which files to open first for a task
7
+ * cartotree_peek — only the lines of a file that contain some words
8
+ * cartotree_links — connection map of a file or symbol
9
+ */
10
+ const { McpServer } = require('@modelcontextprotocol/sdk/server/mcp.js');
11
+ const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
12
+ const { z } = require('zod');
13
+ const { version } = require('../../package.json');
14
+ const { buildIndex, search } = require('./locate');
15
+ const { readHistory, coChanges } = require('./git');
16
+ const { peek } = require('./peek');
17
+ const { buildGraph, symbolLinks, fileLinks } = require('./links');
18
+ const { cached } = require('./cache');
19
+
20
+ function text(s) {
21
+ return { content: [{ type: 'text', text: s }] };
22
+ }
23
+
24
+ function formatLocate(res) {
25
+ if (!res.length) return 'no match — try other words (function names, folder names)';
26
+ const lines = res.map((r, i) => {
27
+ const ev = (r.evidence || []).map(e => `\n L${e.line}: ${e.code}`).join('');
28
+ const cw = r.changesWith && r.changesWith.length
29
+ ? `\n usually changes with: ${r.changesWith.map(c => `${c.file} (${Math.round(c.ratio * 100)}%)`).join(', ')}` : '';
30
+ return `${i + 1}. ${r.file} (score ${r.score}; ${r.matched.join(', ')})${ev}${cw}`;
31
+ });
32
+ if (res.ambiguous) lines.unshift('! top results are close — verify before choosing');
33
+ return lines.join('\n');
34
+ }
35
+
36
+ async function startMcpServer(root = process.cwd()) {
37
+ let index = null;
38
+ let history = null;
39
+ let graph = null;
40
+ const getHistory = () => (history ||= readHistory(root));
41
+ const getIndex = () => (index ||= cached(root, 'locate', { tests: false, history: true, v: 2 },
42
+ () => buildIndex(root, { graph: true, chunks: true, history: getHistory() })));
43
+ const getGraph = () => (graph ||= cached(root, 'graph', {}, () => buildGraph(root)));
44
+
45
+ const server = new McpServer({ name: 'cartotree', version });
46
+
47
+ server.registerTool('cartotree_locate', {
48
+ title: 'Locate files for a task',
49
+ description: 'Rank the source files most likely to need changes for a task, without reading them. '
50
+ + 'Use FIRST when you do not know where code lives. Returns paths with evidence lines; '
51
+ + '"top results are close" means verify with cartotree_peek. Pass the task in plain words, or likely identifiers.',
52
+ inputSchema: { task: z.string().describe('task description or likely identifiers'), top: z.number().int().min(1).max(20).optional() },
53
+ }, async ({ task, top }) => {
54
+ const res = search(getIndex(), task, { k: top || 6, chunkWeight: 0.5 });
55
+ const known = new Set(getIndex().files);
56
+ for (const r of res.slice(0, 2)) {
57
+ const cc = coChanges(getHistory(), r.file, 8);
58
+ if (cc.total >= 2) r.changesWith = cc.files.filter(c => known.has(c.file) && c.ratio >= 0.3).slice(0, 2);
59
+ }
60
+ return text(formatLocate(res));
61
+ });
62
+
63
+ server.registerTool('cartotree_peek', {
64
+ title: 'Peek into a file',
65
+ description: 'Show only the lines of one file that contain the given words (max ~10 lines). '
66
+ + 'Cheaper than reading the whole file or a broad grep; use it to confirm a candidate from cartotree_locate.',
67
+ inputSchema: { file: z.string(), words: z.array(z.string()).min(1), max: z.number().int().min(1).max(40).optional() },
68
+ }, async ({ file, words, max }) => {
69
+ const r = peek(root, file, words, { max: max || 10 });
70
+ if (r.error) return text(`${file}: ${r.error}`);
71
+ const out = [`# ${r.file} (${r.totalLines} lines, ${r.matchedLines} matching)`, ...r.lines.map(l => `${l.line}: ${l.code}`)];
72
+ if (r.matchedLines > r.lines.length) out.push(`... ${r.matchedLines - r.lines.length} more matching lines`);
73
+ return text(out.join('\n'));
74
+ });
75
+
76
+ server.registerTool('cartotree_links', {
77
+ title: 'Connection map',
78
+ description: 'For a file path: its exports, imports, importers, files usually changed with it, recent commits. '
79
+ + 'For a symbol name: where it is defined and called. Use to follow a call chain or find the second file of a change.',
80
+ inputSchema: { target: z.string().describe('file path relative to the repo root, or a symbol name') },
81
+ }, async ({ target }) => {
82
+ const g = getGraph();
83
+ if (g.set.has(target)) {
84
+ const r = fileLinks(g, root, target, { history: getHistory() });
85
+ const out = [`# ${r.file}`];
86
+ if (r.exports.length) out.push(`exports: ${r.exports.slice(0, 12).join(', ')}`);
87
+ out.push(`imports (${r.imports.length}): ${r.imports.join(', ') || '-'}`);
88
+ out.push(`imported by (${r.importedByCount}): ${r.importedBy.join(', ') || '-'}`);
89
+ if (r.changedWith.total) {
90
+ out.push(`usually changes with (of ${r.changedWith.total} commits):`);
91
+ r.changedWith.files.forEach(c => out.push(` ${c.file} ${Math.round(c.ratio * 100)}%`));
92
+ }
93
+ r.recent.forEach(c => out.push(`recent: ${c.date} ${c.hash} ${c.subject}`));
94
+ return text(out.join('\n'));
95
+ }
96
+ const r = symbolLinks(g, target, { root });
97
+ const out = [`# symbol ${r.symbol}`, 'defined in: ' + (r.definedIn.map(d => `${d.file}:${d.line}`).join(', ') || '-'), 'used in:'];
98
+ r.usedIn.forEach(u => out.push(` ${u.file} (${u.count}x) ${u.first}`));
99
+ if (r.moreFiles) out.push(` ... +${r.moreFiles} more files`);
100
+ return text(out.join('\n'));
101
+ });
102
+
103
+ await server.connect(new StdioServerTransport());
104
+ }
105
+
106
+ module.exports = { startMcpServer, formatLocate };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * atlas peek — show only the lines of a file that matter for some words.
3
+ * A compressed replacement for `grep -n` when an agent verifies a candidate file.
4
+ */
5
+ const { readSafe } = require('./files');
6
+ const { splitWords } = require('./locate');
7
+
8
+ function peek(root, file, words, { max = 10 } = {}) {
9
+ const text = readSafe(root, file, 2_000_000);
10
+ if (!text) return { file, error: 'cannot read file' };
11
+ const q = [...new Set(splitWords(words.join(' ')))];
12
+ const lines = text.split('\n');
13
+ const hits = [];
14
+ lines.forEach((ln, i) => {
15
+ if (ln.length > 400) return;
16
+ const ws = new Set(splitWords(ln));
17
+ const m = q.filter(w => ws.has(w));
18
+ if (m.length) hits.push({ line: i + 1, score: m.length, code: ln.trim().slice(0, 120) });
19
+ });
20
+ const top = hits.sort((a, b) => b.score - a.score || a.line - b.line).slice(0, max).sort((a, b) => a.line - b.line);
21
+ return { file, totalLines: lines.length, matchedLines: hits.length, lines: top };
22
+ }
23
+
24
+ module.exports = { peek };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Lightweight, regex-based symbol facts (no TypeScript compiler):
3
+ * exports, relative imports, and call sites.
4
+ */
5
+ const path = require('path');
6
+ const { stripComments } = require('../exports');
7
+
8
+ const EXPORT_RE = /export\s+(?:default\s+)?(?:declare\s+)?(?:async\s+)?(?:function\*?|const|let|var|class|abstract\s+class|type|interface|enum)\s+(\w+)/g;
9
+ const EXPORT_LIST_RE = /export\s*\{([^}]+)\}/g;
10
+ const IMPORT_RE = /(?:import\s[^'"]*?from\s*|import\s*\(\s*|require\s*\(\s*|export\s[^'"]*?from\s*)['"]([^'"]+)['"]/g;
11
+
12
+ function parseExportsFromText(text) {
13
+ const src = stripComments(text);
14
+ const out = new Set();
15
+ let m;
16
+ while ((m = EXPORT_RE.exec(src))) out.add(m[1]);
17
+ while ((m = EXPORT_LIST_RE.exec(src))) {
18
+ m[1].split(',').map(s => s.trim().split(/\s+as\s+/).pop().trim()).filter(s => /^\w+$/.test(s)).forEach(n => out.add(n));
19
+ }
20
+ return [...out];
21
+ }
22
+
23
+ /** Relative imports resolved against the known file set. */
24
+ function parseImports(text, fromFile, fileSet) {
25
+ const out = new Set();
26
+ let m;
27
+ const src = stripComments(text);
28
+ while ((m = IMPORT_RE.exec(src))) {
29
+ const spec = m[1];
30
+ if (!spec.startsWith('.')) continue;
31
+ const base = path.posix.normalize(path.posix.join(path.posix.dirname(fromFile), spec));
32
+ const stem = base.replace(/\.(m|c)?js$/, '');
33
+ const cands = [base, ...['.ts', '.tsx', '.js', '.jsx', '.mjs'].map(e => stem + e),
34
+ ...['index.ts', 'index.tsx', 'index.js'].map(i => `${base}/${i}`)];
35
+ const hit = cands.find(c => fileSet.has(c));
36
+ if (hit && hit !== fromFile) out.add(hit);
37
+ }
38
+ return [...out];
39
+ }
40
+
41
+ module.exports = { parseExportsFromText, parseImports };
package/src/exports.js CHANGED
@@ -2,6 +2,12 @@ const fs = require('fs');
2
2
 
3
3
  const SUPPORTED_EXTENSIONS = ['.js', '.ts', '.jsx', '.tsx', '.mjs', '.cjs'];
4
4
 
5
+ function stripComments(src) {
6
+ return src
7
+ .replace(/\/\*[\s\S]*?\*\//g, '')
8
+ .replace(/(^|[^:'"`\\])\/\/.*$/gm, '$1');
9
+ }
10
+
5
11
  function parseExports(filePath) {
6
12
  const ext = SUPPORTED_EXTENSIONS.find(e => filePath.endsWith(e));
7
13
  if (!ext) return null;
@@ -13,10 +19,13 @@ function parseExports(filePath) {
13
19
  return null;
14
20
  }
15
21
 
22
+ // strip comments so examples like `// export { foo }` are not parsed
23
+ content = stripComments(content);
24
+
16
25
  const names = new Set();
17
26
 
18
27
  // export function foo / export async function foo / export class foo / export const foo
19
- const namedPattern = /export\s+(?:async\s+)?(?:function|const|let|var|class)\s+(\w+)/g;
28
+ const namedPattern = /export\s+(?:async\s+)?(?:function\*?|const|let|var|class|abstract\s+class|type|interface|enum)\s+(\w+)/g;
20
29
  let match;
21
30
  while ((match = namedPattern.exec(content)) !== null) {
22
31
  if (match[1] !== 'default') names.add(match[1]);
@@ -62,4 +71,4 @@ function formatExports(names, max = 4) {
62
71
  return `<${visible.join(', ')}${rest}>`;
63
72
  }
64
73
 
65
- module.exports = { parseExports, formatExports };
74
+ module.exports = { parseExports, formatExports, stripComments };