cartotree 0.1.0 → 0.2.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/.claude-plugin/marketplace.json +11 -0
- package/.claude-plugin/plugin.json +12 -0
- package/LICENSE +20 -20
- package/README.md +246 -200
- package/bin/cartotree.js +162 -55
- package/hooks/hooks.json +14 -0
- package/package.json +45 -15
- package/skills/cartotree/SKILL.md +32 -0
- package/src/ai.js +112 -112
- package/src/atlas/cache.js +46 -0
- package/src/atlas/files.js +56 -0
- package/src/atlas/git.js +65 -0
- package/src/atlas/init.js +114 -0
- package/src/atlas/links.js +87 -0
- package/src/atlas/locate.js +218 -0
- package/src/atlas/mcp.js +106 -0
- package/src/atlas/peek.js +24 -0
- package/src/atlas/symbols.js +41 -0
- package/src/clipboard.js +10 -10
- package/src/config.js +25 -25
- package/src/exports.js +74 -65
- package/src/ignore.js +30 -30
- package/src/sync.js +29 -29
- package/src/tree.js +96 -96
package/src/atlas/git.js
ADDED
|
@@ -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 };
|
package/src/atlas/mcp.js
ADDED
|
@@ -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/clipboard.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
const clipboardy = require('clipboardy');
|
|
2
|
-
const chalk = require('chalk');
|
|
3
|
-
|
|
4
|
-
function copyToClipboard(text) {
|
|
5
|
-
const plain = text.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, '');
|
|
6
|
-
clipboardy.writeSync(plain);
|
|
7
|
-
console.log(chalk.green('✔ Copied to clipboard!'));
|
|
8
|
-
console.log(chalk.gray('(Color codes stripped for clean paste)'));
|
|
9
|
-
}
|
|
10
|
-
|
|
1
|
+
const clipboardy = require('clipboardy');
|
|
2
|
+
const chalk = require('chalk');
|
|
3
|
+
|
|
4
|
+
function copyToClipboard(text) {
|
|
5
|
+
const plain = text.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, '');
|
|
6
|
+
clipboardy.writeSync(plain);
|
|
7
|
+
console.log(chalk.green('✔ Copied to clipboard!'));
|
|
8
|
+
console.log(chalk.gray('(Color codes stripped for clean paste)'));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
11
|
module.exports = { copyToClipboard };
|