cartotree 0.2.0 → 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.
- package/.claude-plugin/marketplace.json +11 -11
- package/.claude-plugin/plugin.json +12 -12
- package/LICENSE +20 -20
- package/README.md +270 -246
- package/bin/cartotree.js +162 -162
- package/hooks/hooks.json +14 -14
- package/package.json +45 -45
- package/skills/cartotree/SKILL.md +32 -32
- package/src/ai.js +112 -112
- package/src/atlas/cache.js +46 -46
- package/src/atlas/files.js +56 -56
- package/src/atlas/git.js +65 -65
- package/src/atlas/init.js +114 -114
- package/src/atlas/links.js +87 -87
- package/src/atlas/locate.js +218 -218
- package/src/atlas/mcp.js +106 -106
- package/src/atlas/peek.js +24 -24
- package/src/atlas/symbols.js +41 -41
- package/src/clipboard.js +10 -10
- package/src/config.js +25 -25
- package/src/exports.js +73 -73
- package/src/ignore.js +30 -30
- package/src/sync.js +29 -29
- package/src/tree.js +96 -96
package/src/atlas/locate.js
CHANGED
|
@@ -1,218 +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 };
|
|
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
CHANGED
|
@@ -1,106 +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 };
|
|
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 };
|