@fabersep/atlas 0.1.0 → 0.1.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,216 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { estimateTokens } from '../tokens.js';
4
+ import { flow, impact, renderFlow } from './flow.js';
5
+ import { isTestFile } from './map.js';
6
+ import { renderSearch, search } from './search.js';
7
+ const CALLABLE_KINDS = new Set(['function', 'method', 'constructor', 'getter', 'setter']);
8
+ const MAX_EXCERPT_LINES = 60;
9
+ function hasEdges(res) {
10
+ return res.roots.some((r) => r.children.length > 0);
11
+ }
12
+ function chainQueryForHit(hit) {
13
+ if (CALLABLE_KINDS.has(hit.kind))
14
+ return `${hit.file}#${hit.label}`;
15
+ if (hit.kind === 'class')
16
+ return hit.label;
17
+ return undefined;
18
+ }
19
+ function findRelatedTests(map, hits, maxTests = 6) {
20
+ const matchedFiles = new Set(hits.map((h) => h.file));
21
+ const stems = new Set();
22
+ for (const file of matchedFiles) {
23
+ const base = path.posix.basename(file).replace(/\.[^.]+$/, '').toLowerCase();
24
+ if (base.length >= 4 && base !== 'index')
25
+ stems.add(base);
26
+ }
27
+ const scored = [];
28
+ for (const record of map.files) {
29
+ if (!isTestFile(record.path))
30
+ continue;
31
+ let score = 0;
32
+ for (const imp of record.imports) {
33
+ if (imp.kind === 'file' && imp.target && matchedFiles.has(imp.target)) {
34
+ score += 3;
35
+ }
36
+ }
37
+ const lower = record.path.toLowerCase();
38
+ for (const stem of stems) {
39
+ if (lower.includes(stem))
40
+ score += 1;
41
+ }
42
+ if (score > 0)
43
+ scored.push({ path: record.path, score });
44
+ }
45
+ scored.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
46
+ return scored.slice(0, maxTests).map((s) => s.path);
47
+ }
48
+ function overlaps(ranges, start, end) {
49
+ return ranges.some(([s, e]) => start <= e && end >= s);
50
+ }
51
+ function readExcerpt(root, hit, maxLines, fileCache) {
52
+ let lines = fileCache.get(hit.file);
53
+ if (lines === undefined) {
54
+ const abs = path.join(root, hit.file);
55
+ try {
56
+ lines = fs.readFileSync(abs, 'utf8').split(/\r?\n/);
57
+ }
58
+ catch {
59
+ lines = null;
60
+ }
61
+ fileCache.set(hit.file, lines);
62
+ }
63
+ if (!lines || lines.length === 0)
64
+ return undefined;
65
+ const start = Math.max(1, hit.lineStart);
66
+ const rawEnd = hit.kind === 'file' ? Math.min(lines.length, start + 24) : Math.min(lines.length, Math.max(start, hit.lineEnd));
67
+ const totalLines = rawEnd - start + 1;
68
+ const end = totalLines > maxLines ? start + maxLines - 1 : rawEnd;
69
+ const truncated = end < rawEnd;
70
+ const formatted = [];
71
+ for (let ln = start; ln <= end; ln++) {
72
+ formatted.push(`${ln}: ${lines[ln - 1] ?? ''}`);
73
+ }
74
+ if (truncated) {
75
+ formatted.push(`... (${rawEnd - end} more lines)`);
76
+ }
77
+ return {
78
+ file: hit.file,
79
+ label: hit.label,
80
+ lineStart: start,
81
+ lineEnd: end,
82
+ truncated,
83
+ code: formatted.join('\n'),
84
+ };
85
+ }
86
+ export function investigate(map, root, query, options = {}) {
87
+ const budget = Math.max(400, Math.min(options.budget ?? 3000, 16000));
88
+ const limit = Math.max(1, Math.min(options.limit ?? 8, 20));
89
+ const depth = Math.max(1, Math.min(options.depth ?? 2, 5));
90
+ const includeTests = options.includeTests === true;
91
+ const searchResult = search(map, query, { folder: options.folder, limit, includeTests });
92
+ if (searchResult.hits.length === 0) {
93
+ const empty = {
94
+ query,
95
+ budget,
96
+ estimatedTokens: 0,
97
+ search: searchResult,
98
+ chains: [],
99
+ excerpts: [],
100
+ relatedTests: [],
101
+ };
102
+ empty.estimatedTokens = estimateTokens(renderInvestigate(empty));
103
+ return empty;
104
+ }
105
+ let usedTokens = estimateTokens(renderSearch(searchResult)) + 40;
106
+ const relatedTests = findRelatedTests(map, searchResult.hits);
107
+ if (relatedTests.length) {
108
+ usedTokens += estimateTokens(relatedTests.join('\n')) + 20;
109
+ }
110
+ // 1. Flow / impact chains for up to top 3 distinct callable symbols (within ~35% of budget)
111
+ const chains = [];
112
+ const chainBudget = Math.max(250, Math.floor(budget * 0.35));
113
+ let chainTokens = 0;
114
+ const seenChainKeys = new Set();
115
+ for (const hit of searchResult.hits) {
116
+ if (chains.length >= 3 || chainTokens >= chainBudget)
117
+ break;
118
+ const symQuery = chainQueryForHit(hit);
119
+ if (!symQuery || seenChainKeys.has(symQuery))
120
+ continue;
121
+ seenChainKeys.add(symQuery);
122
+ let flowText;
123
+ let impactText;
124
+ try {
125
+ const f = flow(map, symQuery, { depth, includeTests });
126
+ if (hasEdges(f))
127
+ flowText = renderFlow(f);
128
+ }
129
+ catch {
130
+ // Not in flow graph
131
+ }
132
+ try {
133
+ const imp = impact(map, symQuery, { depth, includeTests });
134
+ if (hasEdges(imp))
135
+ impactText = renderFlow(imp);
136
+ }
137
+ catch {
138
+ // Not in flow graph
139
+ }
140
+ if (!flowText && !impactText)
141
+ continue;
142
+ const cost = estimateTokens((flowText ?? '') + (impactText ?? '')) + 24;
143
+ if (chainTokens + cost > chainBudget && chains.length > 0)
144
+ break;
145
+ if (usedTokens + cost > budget)
146
+ break;
147
+ chains.push({ symbol: hit.label, ...(flowText ? { flowText } : {}), ...(impactText ? { impactText } : {}) });
148
+ chainTokens += cost;
149
+ usedTokens += cost;
150
+ }
151
+ // 2. Line-numbered source excerpts within remaining token budget
152
+ const excerpts = [];
153
+ const covered = new Map();
154
+ const fileCache = new Map();
155
+ for (const hit of searchResult.hits) {
156
+ const remaining = budget - usedTokens;
157
+ if (remaining < 80)
158
+ break;
159
+ const ranges = covered.get(hit.file) ?? [];
160
+ const hitEnd = hit.kind === 'file' ? hit.lineStart + 24 : Math.max(hit.lineStart, hit.lineEnd);
161
+ if (overlaps(ranges, hit.lineStart, hitEnd))
162
+ continue;
163
+ const maxLines = Math.min(MAX_EXCERPT_LINES, Math.max(8, Math.floor(remaining / 12)));
164
+ const excerpt = readExcerpt(root, hit, maxLines, fileCache);
165
+ if (!excerpt)
166
+ continue;
167
+ const cost = estimateTokens(excerpt.code) + 20;
168
+ if (usedTokens + cost > budget && excerpts.length > 0)
169
+ continue;
170
+ excerpts.push(excerpt);
171
+ ranges.push([excerpt.lineStart, excerpt.lineEnd]);
172
+ covered.set(hit.file, ranges);
173
+ usedTokens += cost;
174
+ }
175
+ const result = {
176
+ query,
177
+ budget,
178
+ estimatedTokens: 0,
179
+ search: searchResult,
180
+ chains,
181
+ excerpts,
182
+ relatedTests,
183
+ };
184
+ result.estimatedTokens = estimateTokens(renderInvestigate(result));
185
+ return result;
186
+ }
187
+ export function renderInvestigate(result) {
188
+ if (result.search.hits.length === 0) {
189
+ return `No structural matches for "${result.query}". Try broader keywords, map(zoom=0), or Grep/Read for literal text.`;
190
+ }
191
+ const sections = [
192
+ `## Matches\n${renderSearch(result.search)}`,
193
+ ];
194
+ if (result.chains.length > 0) {
195
+ const chainLines = ['## Chains'];
196
+ for (const c of result.chains) {
197
+ if (c.flowText)
198
+ chainLines.push(`### Flow: ${c.symbol}\n${c.flowText}`);
199
+ if (c.impactText)
200
+ chainLines.push(`### Impact: ${c.symbol}\n${c.impactText}`);
201
+ }
202
+ sections.push(chainLines.join('\n\n'));
203
+ }
204
+ if (result.excerpts.length > 0) {
205
+ const exLines = ['## Code Excerpts'];
206
+ for (const ex of result.excerpts) {
207
+ exLines.push(`### ${ex.label} (${ex.file}:${ex.lineStart}-${ex.lineEnd})\n\`\`\`\n${ex.code}\n\`\`\``);
208
+ }
209
+ sections.push(exLines.join('\n\n'));
210
+ }
211
+ if (result.relatedTests.length > 0) {
212
+ sections.push(`## Related Tests\n${result.relatedTests.map((t) => `- ${t}`).join('\n')}`);
213
+ }
214
+ const body = sections.join('\n\n');
215
+ return `${body}\n\n(investigate pack: ~${estimateTokens(body)}/${result.budget} tokens)`;
216
+ }
@@ -0,0 +1,37 @@
1
+ import type { CodeMap } from '../model.js';
2
+ /**
3
+ * Fast structural search across symbols, files, entrypoints, and call/event/job references.
4
+ * Gives an agent a 1-turn replacement for Grep when it does not know the exact symbol or file name yet.
5
+ */
6
+ export interface SearchOptions {
7
+ /** Maximum number of hits to return (default: 12). */
8
+ limit?: number;
9
+ /** Include test/spec files (default: false). */
10
+ includeTests?: boolean;
11
+ /** Restrict search to files under this folder prefix. */
12
+ folder?: string;
13
+ }
14
+ export interface SearchHit {
15
+ score: number;
16
+ kind: string;
17
+ label: string;
18
+ file: string;
19
+ lineStart: number;
20
+ lineEnd: number;
21
+ signature: string;
22
+ entrypoints?: string[];
23
+ roles?: string[];
24
+ emits?: string[];
25
+ queues?: string[];
26
+ sends?: string[];
27
+ calls?: string[];
28
+ }
29
+ export interface SearchResult {
30
+ query: string;
31
+ totalMatches: number;
32
+ hits: SearchHit[];
33
+ }
34
+ /** Splits camelCase, PascalCase, snake_case, kebab-case, and regex/punctuation into lowercase terms. */
35
+ export declare function tokenize(text: string): string[];
36
+ export declare function search(map: CodeMap, query: string, options?: SearchOptions): SearchResult;
37
+ export declare function renderSearch(result: SearchResult): string;
@@ -0,0 +1,279 @@
1
+ import { isTestFile } from './map.js';
2
+ /** Splits camelCase, PascalCase, snake_case, kebab-case, and regex/punctuation into lowercase terms. */
3
+ export function tokenize(text) {
4
+ const spaced = text
5
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
6
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
7
+ .toLowerCase();
8
+ const raw = spaced.split(/[^a-z0-9]+/).filter((t) => t.length >= 2);
9
+ return [...new Set(raw)];
10
+ }
11
+ /** Strips common regex metacharacters when a query comes from a Grep pattern. */
12
+ function cleanQuery(q) {
13
+ return q.replace(/[\\^$*+?()[\]{}|]/g, ' ').replace(/\s+/g, ' ').trim();
14
+ }
15
+ function summarizeCalls(sym) {
16
+ if (!sym.calls?.length)
17
+ return {};
18
+ const emits = new Set();
19
+ const queues = new Set();
20
+ const sends = new Set();
21
+ const calls = new Set();
22
+ for (const c of sym.calls) {
23
+ if (c.kind === 'emits' && c.targetKey)
24
+ emits.add(c.targetKey);
25
+ else if (c.kind === 'queues' && c.targetKey)
26
+ queues.add(c.targetKey);
27
+ else if (c.kind === 'sends' && c.targetKey)
28
+ sends.add(c.targetKey);
29
+ else if (c.callee)
30
+ calls.add(c.callee.replace(/^this\./, ''));
31
+ }
32
+ return {
33
+ emits: emits.size ? [...emits] : undefined,
34
+ queues: queues.size ? [...queues] : undefined,
35
+ sends: sends.size ? [...sends] : undefined,
36
+ calls: calls.size ? [...calls].slice(0, 6) : undefined,
37
+ };
38
+ }
39
+ /** Extracts code-identifier-like words (camelCase, snake_case, dot.names) from a cleaned query. */
40
+ function extractIdentifiers(cleaned) {
41
+ const words = cleaned.split(/\s+/).filter(Boolean);
42
+ const out = [];
43
+ for (const w of words) {
44
+ if (/[a-z][A-Z]|_|\./.test(w) && w.length >= 4) {
45
+ out.push(w.toLowerCase());
46
+ }
47
+ }
48
+ return [...new Set(out)];
49
+ }
50
+ function scoreEntry(rawLower, terms, identifiers, label, name, file, signature, entrypoints, calls) {
51
+ const labelLower = label.toLowerCase();
52
+ const nameLower = name.toLowerCase();
53
+ const fileLower = file.toLowerCase();
54
+ const sigLower = signature.toLowerCase();
55
+ const epLower = (entrypoints ?? []).join(' ').toLowerCase();
56
+ const targetKeysLower = (calls ?? [])
57
+ .map((c) => c.targetKey ?? '')
58
+ .filter(Boolean)
59
+ .join(' ')
60
+ .toLowerCase();
61
+ const callList = calls ?? [];
62
+ const callKeysLower = callList
63
+ .map((c) => `${c.callee} ${c.method}`)
64
+ .join(' ')
65
+ .toLowerCase();
66
+ let score = 0;
67
+ // Exact or substring matches on primary identifiers
68
+ if (rawLower.length >= 2) {
69
+ if (nameLower === rawLower || labelLower === rawLower)
70
+ score += 220;
71
+ else if (nameLower.includes(rawLower) || labelLower.includes(rawLower))
72
+ score += 110;
73
+ if (epLower.includes(rawLower))
74
+ score += 95;
75
+ if (targetKeysLower.includes(rawLower))
76
+ score += 85;
77
+ else if (callKeysLower.includes(rawLower))
78
+ score += callList.length > 20 ? 30 : 75;
79
+ if (fileLower.includes(rawLower))
80
+ score += 55;
81
+ if (sigLower.includes(rawLower))
82
+ score += 35;
83
+ }
84
+ // Exact identifier word matches inside multi-word queries (e.g. "what breaks if staticErrorWorkflowId changes")
85
+ if (identifiers.length > 0 && rawLower.includes(' ')) {
86
+ for (const id of identifiers) {
87
+ if (nameLower === id || labelLower === id)
88
+ score += 200;
89
+ else if (id.length >= 6 && (nameLower.includes(id) || labelLower.includes(id)))
90
+ score += 95;
91
+ if (epLower.includes(id))
92
+ score += 80;
93
+ }
94
+ }
95
+ // Token-level scoring across all structural fields
96
+ if (terms.length > 0) {
97
+ const nameTokens = new Set(tokenize(label));
98
+ const fileTokens = new Set(tokenize(file));
99
+ const epTokens = new Set(tokenize(epLower));
100
+ const targetTokens = new Set(tokenize(targetKeysLower));
101
+ const callTokens = new Set(tokenize(callKeysLower));
102
+ const sigTokens = new Set(tokenize(signature));
103
+ // Scale down generic call-list weight for very large "god functions" (100+ calls)
104
+ // so they do not match every multi-word query solely via their callee list.
105
+ const callWeight = callList.length <= 15 ? 26 : Math.max(6, Math.round((26 * 15) / callList.length));
106
+ let matched = 0;
107
+ let primaryMatched = 0;
108
+ for (const t of terms) {
109
+ let termBest = 0;
110
+ let hitPrimary = false;
111
+ if (nameTokens.has(t)) {
112
+ termBest = Math.max(termBest, 40);
113
+ hitPrimary = true;
114
+ }
115
+ else if (nameLower.includes(t)) {
116
+ termBest = Math.max(termBest, 28);
117
+ hitPrimary = true;
118
+ }
119
+ if (epTokens.has(t) || epLower.includes(t)) {
120
+ termBest = Math.max(termBest, 35);
121
+ hitPrimary = true;
122
+ }
123
+ if (targetTokens.has(t) || targetKeysLower.includes(t)) {
124
+ termBest = Math.max(termBest, 30);
125
+ hitPrimary = true;
126
+ }
127
+ if (callTokens.has(t) || callKeysLower.includes(t)) {
128
+ termBest = Math.max(termBest, callWeight);
129
+ }
130
+ if (fileTokens.has(t) || fileLower.includes(t)) {
131
+ termBest = Math.max(termBest, 22);
132
+ hitPrimary = true;
133
+ }
134
+ if (sigTokens.has(t) || sigLower.includes(t)) {
135
+ termBest = Math.max(termBest, 15);
136
+ }
137
+ if (termBest > 0) {
138
+ matched++;
139
+ if (hitPrimary)
140
+ primaryMatched++;
141
+ score += termBest;
142
+ }
143
+ }
144
+ if (matched === 0)
145
+ return 0;
146
+ // Strong bonus when every query term is represented (require at least one primary match on large functions)
147
+ if (matched === terms.length && terms.length > 1) {
148
+ if (callList.length <= 20 || primaryMatched > 0)
149
+ score += 50;
150
+ }
151
+ else if (terms.length > 1) {
152
+ score = Math.round(score * (matched / terms.length));
153
+ }
154
+ }
155
+ return score;
156
+ }
157
+ export function search(map, query, options = {}) {
158
+ const limit = Math.max(1, Math.min(options.limit ?? 12, 50));
159
+ const cleaned = cleanQuery(query);
160
+ const rawLower = cleaned.toLowerCase();
161
+ const terms = tokenize(cleaned);
162
+ const identifiers = extractIdentifiers(cleaned);
163
+ if (!rawLower && terms.length === 0) {
164
+ return { query, totalMatches: 0, hits: [] };
165
+ }
166
+ const folderPrefix = options.folder ? options.folder.replace(/^\/+|\/+$/g, '') : undefined;
167
+ const includeTests = options.includeTests === true || /\b(test|spec)\b/i.test(query);
168
+ const hits = [];
169
+ for (const record of map.files) {
170
+ const testFile = isTestFile(record.path);
171
+ if (testFile && !includeTests)
172
+ continue;
173
+ if (folderPrefix && record.path !== folderPrefix && !record.path.startsWith(`${folderPrefix}/`))
174
+ continue;
175
+ let fileBest = 0;
176
+ const visit = (sym, owner) => {
177
+ const label = owner ? `${owner}.${sym.name}` : sym.name;
178
+ const s = scoreEntry(rawLower, terms, identifiers, label, sym.name, record.path, sym.signature, sym.entrypoints, sym.calls);
179
+ if (s > 0) {
180
+ const penalty = testFile ? 0.7 : 1;
181
+ const kindBoost = sym.kind === 'method' || sym.kind === 'function' ? 1.08 : 1;
182
+ const finalScore = Math.round(s * penalty * kindBoost);
183
+ fileBest = Math.max(fileBest, finalScore);
184
+ hits.push({
185
+ score: finalScore,
186
+ kind: sym.kind,
187
+ label,
188
+ file: record.path,
189
+ lineStart: sym.lineStart,
190
+ lineEnd: sym.lineEnd,
191
+ signature: sym.signature,
192
+ entrypoints: sym.entrypoints,
193
+ roles: record.roles,
194
+ ...summarizeCalls(sym),
195
+ });
196
+ }
197
+ for (const m of sym.members ?? []) {
198
+ visit(m, owner ? `${owner}.${sym.name}` : sym.name);
199
+ }
200
+ };
201
+ for (const sym of record.symbols) {
202
+ visit(sym);
203
+ }
204
+ // If no symbol in this file scored well, check file path itself
205
+ if (fileBest < 40) {
206
+ const fsScore = scoreEntry(rawLower, terms, identifiers, pathBasename(record.path), pathBasename(record.path), record.path, '', undefined, undefined);
207
+ if (fsScore > 0) {
208
+ hits.push({
209
+ score: Math.round(fsScore * (testFile ? 0.6 : 0.85)),
210
+ kind: 'file',
211
+ label: record.path,
212
+ file: record.path,
213
+ lineStart: 1,
214
+ lineEnd: 1,
215
+ signature: record.roles?.length ? `[${record.roles.join(', ')}]` : '(file)',
216
+ roles: record.roles,
217
+ });
218
+ }
219
+ }
220
+ }
221
+ hits.sort((a, b) => b.score - a.score || a.file.localeCompare(b.file) || a.lineStart - b.lineStart);
222
+ return {
223
+ query,
224
+ totalMatches: hits.length,
225
+ hits: hits.slice(0, limit),
226
+ };
227
+ }
228
+ function pathBasename(p) {
229
+ const idx = p.lastIndexOf('/');
230
+ return idx >= 0 ? p.slice(idx + 1) : p;
231
+ }
232
+ function formatEntrypoints(entrypoints, query, maxShow = 5) {
233
+ if (!entrypoints?.length)
234
+ return '';
235
+ if (entrypoints.length <= maxShow)
236
+ return ` [${entrypoints.join(', ')}]`;
237
+ const qLower = cleanQuery(query).toLowerCase();
238
+ const qTerms = tokenize(qLower);
239
+ const scored = entrypoints.map((ep, idx) => {
240
+ const lower = ep.toLowerCase();
241
+ let s = 0;
242
+ if (qLower.length >= 2 && lower.includes(qLower))
243
+ s += 100;
244
+ for (const t of qTerms)
245
+ if (lower.includes(t))
246
+ s += 10;
247
+ return { ep, s, idx };
248
+ });
249
+ scored.sort((a, b) => b.s - a.s || a.idx - b.idx);
250
+ const shown = scored.slice(0, maxShow).map((x) => x.ep);
251
+ const rest = entrypoints.length - shown.length;
252
+ return ` [${shown.join(', ')}, +${rest} more]`;
253
+ }
254
+ export function renderSearch(result) {
255
+ if (result.hits.length === 0) {
256
+ return `No structural matches for "${result.query}". Try broader keywords, map(zoom=0), or Read/Grep for literal text.`;
257
+ }
258
+ const lines = [
259
+ `Atlas search "${result.query}" (${result.hits.length} of ${result.totalMatches} matches):`,
260
+ ];
261
+ for (const h of result.hits) {
262
+ const loc = h.kind === 'file' ? h.file : `${h.file}:${h.lineStart}-${h.lineEnd}`;
263
+ const ep = formatEntrypoints(h.entrypoints, result.query);
264
+ const sig = h.signature ? ` — ${h.signature}` : '';
265
+ lines.push(`- ${h.label} (${loc})${ep}${sig}`);
266
+ const meta = [];
267
+ if (h.emits?.length)
268
+ meta.push(`emits: ${h.emits.join(', ')}`);
269
+ if (h.queues?.length)
270
+ meta.push(`queues: ${h.queues.join(', ')}`);
271
+ if (h.sends?.length)
272
+ meta.push(`sends: ${h.sends.join(', ')}`);
273
+ if (h.calls?.length)
274
+ meta.push(`calls: ${h.calls.join(', ')}`);
275
+ if (meta.length)
276
+ lines.push(` ${meta.join(' | ')}`);
277
+ }
278
+ return lines.join('\n');
279
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabersep/atlas",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "private": false,
5
5
  "description": "Deterministic codebase map, execution flow/impact graph, and token-budgeted context MCP server for AI coding agents.",
6
6
  "license": "Apache-2.0",