@aragon-agent/cli 0.6.78 → 0.6.79

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.
Files changed (93) hide show
  1. package/README.md +89 -21
  2. package/dist/agent/controller.d.ts +36 -0
  3. package/dist/agent/controller.js +108 -0
  4. package/dist/agent/system-prompt.d.ts +10 -0
  5. package/dist/agent/system-prompt.js +6 -0
  6. package/dist/app/App.js +108 -27
  7. package/dist/app/index-console.d.ts +59 -0
  8. package/dist/app/index-console.js +99 -0
  9. package/dist/cli.js +80 -4
  10. package/dist/commands/builtins.js +4 -2
  11. package/dist/commands/catalog.js +7 -1
  12. package/dist/commands/index-build.js +10 -1
  13. package/dist/commands/index-command.d.ts +43 -0
  14. package/dist/commands/index-command.js +244 -0
  15. package/dist/commands/index-copy.d.ts +50 -0
  16. package/dist/commands/index-copy.js +82 -0
  17. package/dist/commands/kit-command.d.ts +10 -0
  18. package/dist/commands/kit-command.js +8 -2
  19. package/dist/commands/kits-command.d.ts +35 -0
  20. package/dist/commands/kits-command.js +137 -0
  21. package/dist/commands/registry.d.ts +10 -0
  22. package/dist/compaction/memory-agent.js +61 -0
  23. package/dist/config/env.d.ts +30 -0
  24. package/dist/config/env.js +47 -0
  25. package/dist/config/launch-notice.d.ts +61 -0
  26. package/dist/config/launch-notice.js +138 -0
  27. package/dist/config/load.d.ts +20 -0
  28. package/dist/config/load.js +72 -2
  29. package/dist/diagnostics/info.d.ts +28 -0
  30. package/dist/diagnostics/info.js +41 -0
  31. package/dist/exec/cli-commands.d.ts +24 -0
  32. package/dist/exec/cli-commands.js +48 -1
  33. package/dist/exec/index.js +9 -0
  34. package/dist/exec/options.d.ts +12 -0
  35. package/dist/host/index-build.d.ts +38 -7
  36. package/dist/host/index-build.js +74 -20
  37. package/dist/indexer/commit.d.ts +77 -0
  38. package/dist/indexer/commit.js +145 -0
  39. package/dist/indexer/discover.d.ts +50 -0
  40. package/dist/indexer/discover.js +147 -0
  41. package/dist/indexer/engine.d.ts +51 -0
  42. package/dist/indexer/engine.js +477 -0
  43. package/dist/indexer/errors.d.ts +62 -0
  44. package/dist/indexer/errors.js +86 -0
  45. package/dist/indexer/finalize.d.ts +30 -0
  46. package/dist/indexer/finalize.js +19 -0
  47. package/dist/indexer/fingerprint.d.ts +41 -0
  48. package/dist/indexer/fingerprint.js +49 -0
  49. package/dist/indexer/ignore.d.ts +59 -0
  50. package/dist/indexer/ignore.js +140 -0
  51. package/dist/indexer/index.d.ts +21 -0
  52. package/dist/indexer/index.js +21 -0
  53. package/dist/indexer/l0.d.ts +55 -0
  54. package/dist/indexer/l0.js +168 -0
  55. package/dist/indexer/limits.d.ts +75 -0
  56. package/dist/indexer/limits.js +106 -0
  57. package/dist/indexer/link.d.ts +68 -0
  58. package/dist/indexer/link.js +220 -0
  59. package/dist/indexer/lock.d.ts +115 -0
  60. package/dist/indexer/lock.js +270 -0
  61. package/dist/indexer/parse.d.ts +68 -0
  62. package/dist/indexer/parse.js +163 -0
  63. package/dist/indexer/paths.d.ts +99 -0
  64. package/dist/indexer/paths.js +198 -0
  65. package/dist/indexer/plan.d.ts +48 -0
  66. package/dist/indexer/plan.js +80 -0
  67. package/dist/indexer/rank.d.ts +42 -0
  68. package/dist/indexer/rank.js +125 -0
  69. package/dist/indexer/read/cache.d.ts +28 -0
  70. package/dist/indexer/read/cache.js +54 -0
  71. package/dist/indexer/read/query.d.ts +48 -0
  72. package/dist/indexer/read/query.js +361 -0
  73. package/dist/indexer/scanner/extract.d.ts +36 -0
  74. package/dist/indexer/scanner/extract.js +134 -0
  75. package/dist/indexer/scanner/mask.d.ts +44 -0
  76. package/dist/indexer/scanner/mask.js +198 -0
  77. package/dist/indexer/scanner/py-extract.d.ts +29 -0
  78. package/dist/indexer/scanner/py-extract.js +164 -0
  79. package/dist/indexer/scanner/refs.d.ts +31 -0
  80. package/dist/indexer/scanner/refs.js +116 -0
  81. package/dist/indexer/scanner/ts-extract.d.ts +39 -0
  82. package/dist/indexer/scanner/ts-extract.js +277 -0
  83. package/dist/indexer/store.d.ts +88 -0
  84. package/dist/indexer/store.js +309 -0
  85. package/dist/indexer/tools.d.ts +120 -0
  86. package/dist/indexer/tools.js +132 -0
  87. package/dist/indexer/types.d.ts +225 -0
  88. package/dist/indexer/types.js +44 -0
  89. package/dist/indexer/wiring.d.ts +45 -0
  90. package/dist/indexer/wiring.js +42 -0
  91. package/dist/tools/index.d.ts +16 -2
  92. package/dist/tools/index.js +23 -0
  93. package/package.json +3 -3
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The six query operations behind `code_query` (spec 6.2 `read/query.ts`, 7.3).
3
+ *
4
+ * EVERY ANSWER STARTS WITH A FRESHNESS LINE. That is not decoration: the index can
5
+ * lag the user's edits, and a model that cannot tell a fresh answer from a stale
6
+ * one will confidently describe code that no longer exists. `formatFreshness`
7
+ * carries the generation and the commit distance, and it is byte-identical to what
8
+ * `/index status` shows a human.
9
+ *
10
+ * Answers are budgeted, never unbounded. When a result is cut, the reply says HOW
11
+ * to narrow it and returns a cursor, because a silent truncation reads like "this
12
+ * is all there is" - the worst possible failure for a structure tool.
13
+ *
14
+ * ASCII ONLY: inside the glyph scanner's scope.
15
+ */
16
+ import type { IndexQueryRequest, IndexQueryResult } from '@aragon-agent/tui/model/index-build/types';
17
+ import type { IndexPaths } from '../paths.js';
18
+ import type { LoadedGeneration } from '../store.js';
19
+ import type { SymbolRow } from '../types.js';
20
+ /** Input to one query. */
21
+ export interface QueryInput {
22
+ /** Artifact paths for the workspace. */
23
+ readonly paths: IndexPaths;
24
+ /** Workspace root (unused by the math, kept for future path display). */
25
+ readonly root: string;
26
+ /** The request as the tool received it. */
27
+ readonly request: IndexQueryRequest;
28
+ /** Token budget override, clamped by the caller. */
29
+ readonly budget?: number;
30
+ }
31
+ /** Estimate tokens for a string, rounded up so the budget is never overshot. */
32
+ export declare function estimateTokens(text: string): number;
33
+ /** Clamp the page size into the allowed range. */
34
+ export declare function clampLimit(limit: number | undefined): number;
35
+ /** Clamp the graph depth into the allowed range. */
36
+ export declare function clampDepth(depth: number | undefined): number;
37
+ /** Decode an opaque cursor (`<offset>`); an invalid one starts from the beginning. */
38
+ export declare function decodeCursor(cursor: string | undefined): number;
39
+ /** Find a symbol by exact qualified name, then by simple name (first match by path). */
40
+ export declare function findSymbol(loaded: LoadedGeneration, wanted: string): SymbolRow | undefined;
41
+ /** Sentence for the unbuilt-index case: actionable, never an empty result (AC-18). */
42
+ export declare const NO_INDEX_SENTENCE = "Index not built. Press Ctrl+I (or run /index) to build it. Answers come from the deterministic AST index, not from the model.";
43
+ /**
44
+ * Run one query. Returns a value in every case - an unbuilt index, an illegal
45
+ * `op` and an empty match are all answers with actionable text, because a tool
46
+ * that returns nothing teaches the model to guess.
47
+ */
48
+ export declare function runQuery(input: QueryInput): IndexQueryResult;
@@ -0,0 +1,361 @@
1
+ /**
2
+ * The six query operations behind `code_query` (spec 6.2 `read/query.ts`, 7.3).
3
+ *
4
+ * EVERY ANSWER STARTS WITH A FRESHNESS LINE. That is not decoration: the index can
5
+ * lag the user's edits, and a model that cannot tell a fresh answer from a stale
6
+ * one will confidently describe code that no longer exists. `formatFreshness`
7
+ * carries the generation and the commit distance, and it is byte-identical to what
8
+ * `/index status` shows a human.
9
+ *
10
+ * Answers are budgeted, never unbounded. When a result is cut, the reply says HOW
11
+ * to narrow it and returns a cursor, because a silent truncation reads like "this
12
+ * is all there is" - the worst possible failure for a structure tool.
13
+ *
14
+ * ASCII ONLY: inside the glyph scanner's scope.
15
+ */
16
+ import { formatCount, formatFreshness, shortPath } from '@aragon-agent/tui/model/index-build/format';
17
+ import { QUERY_DEPTH_DEFAULT, QUERY_DEPTH_MAX, QUERY_DEPTH_MIN, QUERY_LIMIT_DEFAULT, QUERY_LIMIT_MAX, QUERY_LIMIT_MIN, QUERY_TOKEN_BUDGET } from '../limits.js';
18
+ import { areaOf, countCommitsBehind, dirOf } from '../paths.js';
19
+ import { loadCached } from './cache.js';
20
+ /** Rough tokens-per-character for the estimator; English code averages ~4. */
21
+ const CHARS_PER_TOKEN = 4;
22
+ /** Estimate tokens for a string, rounded up so the budget is never overshot. */
23
+ export function estimateTokens(text) {
24
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
25
+ }
26
+ /** Clamp the page size into the allowed range. */
27
+ export function clampLimit(limit) {
28
+ if (limit === undefined || !Number.isFinite(limit))
29
+ return QUERY_LIMIT_DEFAULT;
30
+ const rounded = Math.trunc(limit);
31
+ if (rounded < QUERY_LIMIT_MIN)
32
+ return QUERY_LIMIT_MIN;
33
+ if (rounded > QUERY_LIMIT_MAX)
34
+ return QUERY_LIMIT_MAX;
35
+ return rounded;
36
+ }
37
+ /** Clamp the graph depth into the allowed range. */
38
+ export function clampDepth(depth) {
39
+ if (depth === undefined || !Number.isFinite(depth))
40
+ return QUERY_DEPTH_DEFAULT;
41
+ const rounded = Math.trunc(depth);
42
+ if (rounded < QUERY_DEPTH_MIN)
43
+ return QUERY_DEPTH_MIN;
44
+ if (rounded > QUERY_DEPTH_MAX)
45
+ return QUERY_DEPTH_MAX;
46
+ return rounded;
47
+ }
48
+ /** Decode an opaque cursor (`<offset>`); an invalid one starts from the beginning. */
49
+ export function decodeCursor(cursor) {
50
+ if (!cursor)
51
+ return 0;
52
+ const parsed = Number.parseInt(cursor, 10);
53
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
54
+ }
55
+ /**
56
+ * Fit lines into the token budget. Whole lines are kept in order; the first line
57
+ * that does not fit stops the page, so the caller never gets half a table row.
58
+ */
59
+ function fitLines(header, body, budget) {
60
+ const out = [...header];
61
+ let used = estimateTokens(header.join('\n'));
62
+ let index = 0;
63
+ for (; index < body.length; index += 1) {
64
+ const cost = estimateTokens(body[index]) + 1;
65
+ if (used + cost > budget)
66
+ break;
67
+ out.push(body[index]);
68
+ used += cost;
69
+ }
70
+ const truncated = index < body.length;
71
+ return { lines: out, truncated, nextCursor: truncated ? String(index) : undefined };
72
+ }
73
+ /** Build the freshness header from the loaded generation and the commit distance. */
74
+ function freshnessOf(loaded, behind) {
75
+ return formatFreshness(loaded.meta.generation, behind);
76
+ }
77
+ /**
78
+ * Compose the final result. The hint is included WHENEVER the answer is not the whole
79
+ * truth: either the token budget cut it, or a page boundary did. A refusal that names no
80
+ * next step is the "empty result" failure AC-18 forbids, so `hintIsBody` lets a caller put
81
+ * the sentence in the body for a zero-row answer.
82
+ *
83
+ * `forceCursor` exists because two different things truncate an answer: the token budget
84
+ * (`fitLines`) and the page size (`limit`). Only the first sets `page.nextCursor`, and a
85
+ * page cut reported as complete tells the model "these are all the matches".
86
+ */
87
+ function toResult(page, hint, options = {}) {
88
+ const truncated = page.truncated || options.forceCursor !== undefined;
89
+ const nextCursor = page.nextCursor ?? options.forceCursor;
90
+ const lines = [...page.lines];
91
+ if (truncated) {
92
+ lines.push(`... truncated. ${hint}`);
93
+ if (nextCursor)
94
+ lines.push(`Next page: pass cursor "${nextCursor}".`);
95
+ }
96
+ else if (options.hintIsBody === true && hint !== '') {
97
+ // Nothing to show: the next step IS the answer.
98
+ lines.push(hint);
99
+ }
100
+ const text = lines.join('\n');
101
+ return { text, truncated, nextCursor, tokens: estimateTokens(text) };
102
+ }
103
+ /** `map`: areas -> directories, with file counts and the top exported symbols of each. */
104
+ function runMap(loaded, request, budget) {
105
+ const depth = clampDepth(request.depth);
106
+ const scope = (request.path ?? '').replace(/\\/g, '/').replace(/\/$/, '');
107
+ const scoped = scope === '' ? loaded.files : loaded.files.filter((file) => file.p.startsWith(scope));
108
+ const groups = new Map();
109
+ for (const file of scoped) {
110
+ const key = depth <= 1 ? areaOf(file.p) : dirOf(file.p) || '.';
111
+ const list = groups.get(key) ?? [];
112
+ list.push(file);
113
+ groups.set(key, list);
114
+ }
115
+ const exportsByFile = new Map();
116
+ for (const symbol of loaded.symbols) {
117
+ if (!symbol.x)
118
+ continue;
119
+ const list = exportsByFile.get(symbol.f) ?? [];
120
+ if (list.length < 6)
121
+ list.push(symbol.n);
122
+ exportsByFile.set(symbol.f, list);
123
+ }
124
+ const sorted = [...groups.entries()].sort((a, b) => b[1].length - a[1].length);
125
+ const body = sorted.map(([key, files]) => {
126
+ const top = new Set();
127
+ for (const file of files) {
128
+ for (const name of exportsByFile.get(file.p) ?? []) {
129
+ if (top.size >= 4)
130
+ break;
131
+ top.add(name);
132
+ }
133
+ }
134
+ const names = top.size > 0 ? ` - ${[...top].join(', ')}` : '';
135
+ return `- ${key} - ${formatCount(files.length)} files${names}`;
136
+ });
137
+ const header = [`${formatCount(scoped.length)} files in ${formatCount(groups.size)} areas`];
138
+ return toResult(fitLines(header, body, budget), 'Narrow it with path or raise depth.');
139
+ }
140
+ /** `outline`: signatures of one file, or of every file under a directory. */
141
+ function runOutline(loaded, request, budget) {
142
+ const target = (request.path ?? '').replace(/\\/g, '/');
143
+ if (target === '') {
144
+ return toResult({ lines: ['outline needs a path (a file or a directory).'], truncated: false }, '');
145
+ }
146
+ const isFile = loaded.files.some((file) => file.p === target);
147
+ const scope = isFile ? [target] : loaded.files.filter((file) => file.p.startsWith(target)).map((file) => file.p);
148
+ if (scope.length === 0) {
149
+ return toResult({ lines: [`No indexed file matches "${target}".`], truncated: false }, 'Try code_query { op: "find", query } to locate it.', { hintIsBody: true });
150
+ }
151
+ const limit = clampLimit(request.limit);
152
+ const lines = [];
153
+ let shown = 0;
154
+ for (const file of scope.slice(0, limit)) {
155
+ const symbols = loaded.symbols.filter((symbol) => symbol.f === file);
156
+ lines.push(`${shortPath(file, 72)} (${symbols.length} symbols)`);
157
+ for (const symbol of symbols.slice(0, 40)) {
158
+ lines.push(` ${symbol.ln}-${symbol.el} ${symbol.k} ${symbol.q}${symbol.sg ? ` ${symbol.sg}` : ''}`);
159
+ }
160
+ shown += 1;
161
+ if (lines.length > 400)
162
+ break;
163
+ }
164
+ const header = [`outline of ${formatCount(shown)} of ${formatCount(scope.length)} files`];
165
+ return toResult(fitLines(header, lines, budget), 'Narrow with a file path, or page with cursor.');
166
+ }
167
+ /** `find`: symbol search by name or qualified name, ranked by file PageRank. */
168
+ function runFind(loaded, request, budget) {
169
+ const needle = (request.query ?? '').toLowerCase();
170
+ if (needle === '') {
171
+ return toResult({ lines: ['find needs a query string.'], truncated: false }, '');
172
+ }
173
+ const kindFilter = request.kind?.toLowerCase();
174
+ const matches = loaded.symbols.filter((symbol) => {
175
+ if (kindFilter && symbol.k !== kindFilter)
176
+ return false;
177
+ return symbol.n.toLowerCase().includes(needle) || symbol.q.toLowerCase().includes(needle);
178
+ });
179
+ const ranks = new Map(loaded.graph.nodes.map((node) => [node.id, node.rank]));
180
+ matches.sort((a, b) => {
181
+ const rankDelta = (ranks.get(b.f) ?? 0) - (ranks.get(a.f) ?? 0);
182
+ return rankDelta !== 0 ? rankDelta : a.q < b.q ? -1 : 1;
183
+ });
184
+ const limit = clampLimit(request.limit);
185
+ const offset = decodeCursor(request.cursor);
186
+ const page = matches.slice(offset, offset + limit);
187
+ const more = offset + page.length < matches.length;
188
+ const body = page.map((symbol) => `- ${symbol.q} (${symbol.k}) ${symbol.f}:${symbol.ln}`);
189
+ const header = [`${formatCount(matches.length)} symbols match "${request.query}"`];
190
+ return toResult(fitLines(header, body, budget), 'Add kind, or raise limit.', {
191
+ // A PAGE boundary cuts the answer just as surely as a token budget does. Reporting it
192
+ // as complete would tell the model "these are all the matches", which is the silent
193
+ // truncation this layer exists to avoid.
194
+ forceCursor: more ? String(offset + page.length) : undefined,
195
+ });
196
+ }
197
+ /** `symbol`: one symbol's location, signature and callers. */
198
+ function runSymbol(loaded, request, budget) {
199
+ const wanted = request.symbol ?? '';
200
+ if (wanted === '')
201
+ return toResult({ lines: ['symbol needs a name.'], truncated: false }, '');
202
+ const found = findSymbol(loaded, wanted);
203
+ if (!found) {
204
+ return toResult({ lines: [`No symbol named "${wanted}".`], truncated: false }, 'Try code_query { op: "find", query } for a partial match.');
205
+ }
206
+ const callers = loaded.refs.filter((ref) => ref.t === `${found.f}#${found.q}` || ref.t.endsWith(`#${found.n}`));
207
+ const lines = [
208
+ `${found.q} (${found.k})${found.x ? ' exported' : ''}`,
209
+ ` at ${found.f}:${found.ln}-${found.el}`,
210
+ ...(found.sg ? [` ${found.sg}`] : []),
211
+ ` ${formatCount(callers.length)} references in ${formatCount(new Set(callers.map((ref) => ref.f)).size)} files`,
212
+ ...callers.slice(0, 20).map((ref) => ` - ${ref.f}:${ref.ln} (${ref.fk}, ${ref.rs})`),
213
+ ];
214
+ return toResult(fitLines([], lines, budget), 'Use op "refs" for the full list.');
215
+ }
216
+ /** `refs`: every reference to a name, grouped by resolution kind. */
217
+ function runRefs(loaded, request, budget) {
218
+ const wanted = request.symbol ?? '';
219
+ if (wanted === '')
220
+ return toResult({ lines: ['refs needs a symbol name.'], truncated: false }, '');
221
+ const matches = loaded.refs.filter((ref) => ref.n === wanted || ref.t.endsWith(`#${wanted}`));
222
+ const limit = clampLimit(request.limit);
223
+ const offset = decodeCursor(request.cursor);
224
+ const page = matches.slice(offset, offset + limit);
225
+ const byKind = new Map();
226
+ for (const ref of matches)
227
+ byKind.set(ref.rs, (byKind.get(ref.rs) ?? 0) + 1);
228
+ const summary = [...byKind.entries()].map(([kind, count]) => `${kind} ${count}`).join(', ');
229
+ const body = page.map((ref) => `- ${ref.f}:${ref.ln} ${ref.fk}${ref.t ? ` -> ${ref.t}` : ' (unresolved)'}`);
230
+ const header = [`${formatCount(matches.length)} references to "${wanted}"${summary ? ` (${summary})` : ''}`];
231
+ return toResult(fitLines(header, body, budget), 'Page with cursor, or narrow to a path.');
232
+ }
233
+ /** `impact`: what a change to a file or symbol touches, walked over the import graph. */
234
+ function runImpact(loaded, request, budget) {
235
+ const target = (request.target ?? request.path ?? request.symbol ?? '').replace(/\\/g, '/');
236
+ if (target === '')
237
+ return toResult({ lines: ['impact needs a target (path or symbol).'], truncated: false }, '');
238
+ const depth = clampDepth(request.depth);
239
+ const startFiles = new Set();
240
+ if (loaded.files.some((file) => file.p === target))
241
+ startFiles.add(target);
242
+ for (const symbol of loaded.symbols) {
243
+ if (symbol.q === target || symbol.n === target)
244
+ startFiles.add(symbol.f);
245
+ }
246
+ if (startFiles.size === 0) {
247
+ const prefix = loaded.files.filter((file) => file.p.startsWith(target));
248
+ for (const file of prefix)
249
+ startFiles.add(file.p);
250
+ }
251
+ if (startFiles.size === 0) {
252
+ return toResult({ lines: [`Nothing indexed matches "${target}".`], truncated: false }, 'Try code_query { op: "find", query }.');
253
+ }
254
+ const inbound = new Map();
255
+ for (const edge of loaded.graph.edges) {
256
+ const set = inbound.get(edge.to) ?? new Set();
257
+ set.add(edge.from);
258
+ inbound.set(edge.to, set);
259
+ }
260
+ const reached = new Set(startFiles);
261
+ let frontier = [...startFiles];
262
+ for (let level = 0; level < depth; level += 1) {
263
+ const next = [];
264
+ for (const file of frontier) {
265
+ for (const importer of inbound.get(file) ?? []) {
266
+ if (reached.has(importer))
267
+ continue;
268
+ reached.add(importer);
269
+ next.push(importer);
270
+ }
271
+ }
272
+ frontier = next;
273
+ if (frontier.length === 0)
274
+ break;
275
+ }
276
+ const affected = [...reached].filter((file) => !startFiles.has(file)).sort();
277
+ const refs = loaded.refs.filter((ref) => startFiles.has(ref.f) && ref.t !== '');
278
+ const lines = [
279
+ `${formatCount(startFiles.size)} starting files, ${formatCount(affected.length)} importers within depth ${depth}`,
280
+ ...affected.slice(0, 60).map((file) => `- ${file}`),
281
+ ` ${formatCount(refs.length)} outgoing references from the starting files`,
282
+ ];
283
+ return toResult(fitLines([], lines, budget), 'Reduce depth or narrow the target.');
284
+ }
285
+ /** Find a symbol by exact qualified name, then by simple name (first match by path). */
286
+ export function findSymbol(loaded, wanted) {
287
+ const exact = loaded.symbols.find((symbol) => symbol.q === wanted);
288
+ if (exact)
289
+ return exact;
290
+ const simple = loaded.symbols.filter((symbol) => symbol.n === wanted);
291
+ if (simple.length === 0)
292
+ return undefined;
293
+ const ranks = new Map(loaded.graph.nodes.map((node) => [node.id, node.rank]));
294
+ simple.sort((a, b) => (ranks.get(b.f) ?? 0) - (ranks.get(a.f) ?? 0));
295
+ return simple[0];
296
+ }
297
+ /** Sentence for the unbuilt-index case: actionable, never an empty result (AC-18). */
298
+ export const NO_INDEX_SENTENCE = 'Index not built. Press Ctrl+I (or run /index) to build it. Answers come from the deterministic AST index, not from the model.';
299
+ /** The operation names, quoted in the "illegal op" message so the caller can correct it. */
300
+ const LEGAL_OPS = 'map, outline, find, symbol, refs, impact';
301
+ /**
302
+ * Run one query. Returns a value in every case - an unbuilt index, an illegal
303
+ * `op` and an empty match are all answers with actionable text, because a tool
304
+ * that returns nothing teaches the model to guess.
305
+ */
306
+ export function runQuery(input) {
307
+ const budget = input.budget ?? QUERY_TOKEN_BUDGET;
308
+ const loaded = loadCached(input.paths);
309
+ if (!loaded) {
310
+ return { text: NO_INDEX_SENTENCE, truncated: false, tokens: estimateTokens(NO_INDEX_SENTENCE) };
311
+ }
312
+ const behind = behindCommits(loaded);
313
+ const header = freshnessOf(loaded, behind);
314
+ const body = dispatch(loaded, input.request, budget, header);
315
+ return body;
316
+ }
317
+ /** Route to the operation, keeping each one a separate function with its own tests. */
318
+ function dispatch(loaded, request, budget, header) {
319
+ // The freshness line is prepended after the operation renders, so every
320
+ // operation's own truncation math stays independent of it.
321
+ const inner = (() => {
322
+ switch (request.op) {
323
+ case 'map':
324
+ return runMap(loaded, request, budget);
325
+ case 'outline':
326
+ return runOutline(loaded, request, budget);
327
+ case 'find':
328
+ return runFind(loaded, request, budget);
329
+ case 'symbol':
330
+ return runSymbol(loaded, request, budget);
331
+ case 'refs':
332
+ return runRefs(loaded, request, budget);
333
+ case 'impact':
334
+ return runImpact(loaded, request, budget);
335
+ default:
336
+ return {
337
+ text: `Unknown op "${String(request.op)}". Legal ops: ${LEGAL_OPS}.`,
338
+ truncated: false,
339
+ tokens: 0,
340
+ };
341
+ }
342
+ })();
343
+ const text = `${header}\n${inner.text}`;
344
+ return { ...inner, text, tokens: estimateTokens(text) };
345
+ }
346
+ /**
347
+ * Commit distance for the freshness line. The engine owns `git`; this module only
348
+ * needs the number, and a failed probe must not turn a query into an error, so the
349
+ * value is left undefined (the line then omits the distance rather than lying).
350
+ */
351
+ function behindCommits(loaded) {
352
+ const meta = loaded.meta;
353
+ if (!meta.gitHead)
354
+ return undefined;
355
+ try {
356
+ return countCommitsBehind(meta.root, meta.gitHead);
357
+ }
358
+ catch {
359
+ return undefined;
360
+ }
361
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Extension dispatch for the tier-1 scanner (spec 5.8 / 6.2 `scanner/extract.ts`).
3
+ *
4
+ * This is the only entry point the parser stage calls. Keeping the dispatch in
5
+ * one place is what makes "which languages are supported" a single answer: a
6
+ * caller that switched on an extension itself would be a second list, and a
7
+ * second list drifts.
8
+ *
9
+ * ASCII ONLY: inside the glyph scanner's scope.
10
+ */
11
+ import type { FileFacts, IndexLang } from '../types.js';
12
+ /** Map an extension (with dot, lower case) to a language bucket. */
13
+ export declare function languageFor(extension: string): IndexLang;
14
+ /** True when the scanner can read this language. */
15
+ export declare function isSupportedLanguage(lang: IndexLang): boolean;
16
+ /** Input to one parse: everything the scanner needs, and nothing else. */
17
+ export interface ParseInput {
18
+ /** Repo-relative path, written into every row. */
19
+ readonly path: string;
20
+ /** File contents, already read and already size-checked. */
21
+ readonly source: string;
22
+ /** Byte size on disk. */
23
+ readonly bytes: number;
24
+ /** Content hash, `sha1:<hex>`. */
25
+ readonly sha1: string;
26
+ /** Extension with dot, lower case. */
27
+ readonly extension: string;
28
+ }
29
+ /**
30
+ * Parse one file into `FileFacts`.
31
+ *
32
+ * A language the scanner cannot read still produces facts (line count, hash,
33
+ * status `partial`) rather than nothing: a `files.jsonl` row that exists but has
34
+ * no symbols is honest, while a missing row makes the file invisible to `map`.
35
+ */
36
+ export declare function parseFile(input: ParseInput): FileFacts;
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Extension dispatch for the tier-1 scanner (spec 5.8 / 6.2 `scanner/extract.ts`).
3
+ *
4
+ * This is the only entry point the parser stage calls. Keeping the dispatch in
5
+ * one place is what makes "which languages are supported" a single answer: a
6
+ * caller that switched on an extension itself would be a second list, and a
7
+ * second list drifts.
8
+ *
9
+ * ASCII ONLY: inside the glyph scanner's scope.
10
+ */
11
+ import { extractRefs } from './refs.js';
12
+ import { extractPy } from './py-extract.js';
13
+ import { extractTs } from './ts-extract.js';
14
+ import { maskSource } from './mask.js';
15
+ /** Map an extension (with dot, lower case) to a language bucket. */
16
+ export function languageFor(extension) {
17
+ switch (extension) {
18
+ case '.ts':
19
+ return 'ts';
20
+ case '.tsx':
21
+ return 'tsx';
22
+ case '.js':
23
+ return 'js';
24
+ case '.jsx':
25
+ return 'jsx';
26
+ case '.mjs':
27
+ return 'mjs';
28
+ case '.cjs':
29
+ return 'cjs';
30
+ case '.py':
31
+ return 'py';
32
+ default:
33
+ return 'other';
34
+ }
35
+ }
36
+ /** True when the scanner can read this language. */
37
+ export function isSupportedLanguage(lang) {
38
+ return lang !== 'other';
39
+ }
40
+ /**
41
+ * Parse one file into `FileFacts`.
42
+ *
43
+ * A language the scanner cannot read still produces facts (line count, hash,
44
+ * status `partial`) rather than nothing: a `files.jsonl` row that exists but has
45
+ * no symbols is honest, while a missing row makes the file invisible to `map`.
46
+ */
47
+ export function parseFile(input) {
48
+ const lang = languageFor(input.extension);
49
+ const started = process.hrtime.bigint();
50
+ const result = lang === 'py' ? extractPy(input.source, lang, input.path) : parseTsLike(input, lang);
51
+ const refs = extractRefsFor(input.source, lang);
52
+ const parseMs = Number(process.hrtime.bigint() - started) / 1e6;
53
+ return {
54
+ path: input.path,
55
+ lang,
56
+ bytes: input.bytes,
57
+ sha1: input.sha1,
58
+ lines: result.lines,
59
+ status: result.partial ? 'partial' : 'ok',
60
+ parseMs,
61
+ symbols: result.symbols,
62
+ refs,
63
+ imports: result.imports,
64
+ };
65
+ }
66
+ /** TS/JS branch; `other` still gets a line count so the row is not empty. */
67
+ function parseTsLike(input, lang) {
68
+ if (lang === 'other') {
69
+ const masked = maskSource(input.source);
70
+ return { symbols: [], imports: [], lines: masked.lineStarts.length, partial: true };
71
+ }
72
+ return extractTs(input.source, lang, input.path);
73
+ }
74
+ /** References for the file, with `t`/`rs` left for LINK to fill. */
75
+ function extractRefsFor(source, lang) {
76
+ if (lang === 'py')
77
+ return extractPyRefs(source);
78
+ return extractRefs(source).map((ref) => ({ f: '', ln: ref.ln, fk: ref.fk, n: ref.n }));
79
+ }
80
+ /**
81
+ * Python references: a call is `name(` minus the definition keywords, and a base
82
+ * class is recorded as `extends`. Kept local because Python has no `new`, no
83
+ * decorators-as-symbols rule and no JSX.
84
+ */
85
+ function extractPyRefs(source) {
86
+ const { masked, lineStarts } = maskSource(source);
87
+ const out = [];
88
+ const seen = new Set();
89
+ const keyword = new Set(['if', 'for', 'while', 'def', 'class', 'return', 'print', 'len', 'range', 'super', 'isinstance', 'str', 'int', 'float', 'list', 'dict', 'set', 'tuple', 'open', 'enumerate', 'zip', 'sorted', 'sum', 'min', 'max', 'abs', 'any', 'all']);
90
+ const callPattern = /\b([A-Za-z_]\w*)\s*\(/g;
91
+ let match = callPattern.exec(masked);
92
+ while (match !== null) {
93
+ const name = match[1];
94
+ if (!keyword.has(name)) {
95
+ const line = lineOf(lineStarts, match.index);
96
+ const key = `${line}:call:${name}`;
97
+ if (!seen.has(key)) {
98
+ seen.add(key);
99
+ out.push({ f: '', ln: line, fk: 'call', n: name });
100
+ }
101
+ }
102
+ match = callPattern.exec(masked);
103
+ }
104
+ const classPattern = /^\s*class\s+[A-Za-z_]\w*\s*\(([^)]*)\)/gm;
105
+ let base = classPattern.exec(masked);
106
+ while (base !== null) {
107
+ for (const entry of base[1].split(',')) {
108
+ const name = entry.trim().split('.')[0];
109
+ if (name === '' || name === 'object')
110
+ continue;
111
+ const line = lineOf(lineStarts, base.index);
112
+ const key = `${line}:extends:${name}`;
113
+ if (!seen.has(key)) {
114
+ seen.add(key);
115
+ out.push({ f: '', ln: line, fk: 'extends', n: name });
116
+ }
117
+ }
118
+ base = classPattern.exec(masked);
119
+ }
120
+ return out;
121
+ }
122
+ /** 1-based line of an offset. */
123
+ function lineOf(lineStarts, offset) {
124
+ let low = 0;
125
+ let high = lineStarts.length - 1;
126
+ while (low < high) {
127
+ const mid = Math.ceil((low + high) / 2);
128
+ if (lineStarts[mid] <= offset)
129
+ low = mid;
130
+ else
131
+ high = mid - 1;
132
+ }
133
+ return low + 1;
134
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Character-level masking for the tier-1 scanner (spec 5.8 layer 1).
3
+ *
4
+ * WHY MASK INSTEAD OF PARSING: the alternative is `tree-sitter`, which needs a
5
+ * native build or wasm assets and would break "install and run" (spec NG1). The
6
+ * masking pass is what makes a character scanner safe enough to promise: it
7
+ * blanks strings, templates, regex literals and comments with SPACES of the same
8
+ * length, so a `class` inside a string can never be mistaken for a declaration
9
+ * and every byte offset (and therefore every line number) is preserved.
10
+ *
11
+ * Known and accepted limit (spec P2-7 / R8): a template literal is masked
12
+ * wholesale, including its `${...}` interpolations, so a call written only
13
+ * inside an interpolation is not reported. That is a syntax-level scanner, and
14
+ * `status: 'partial'` is how the artifact stays honest about it.
15
+ *
16
+ * ASCII ONLY: inside the glyph scanner's scope.
17
+ */
18
+ /** Result of one masking pass. */
19
+ export interface MaskedSource {
20
+ /** Source with strings/comments/regex replaced by spaces; newlines are preserved. */
21
+ readonly masked: string;
22
+ /** Byte offset of the first character of each line, index 0 being line 1. */
23
+ readonly lineStarts: readonly number[];
24
+ /** True when an unterminated string/comment/template was found (file is `partial`). */
25
+ readonly unterminated: boolean;
26
+ }
27
+ /**
28
+ * Mask one source file. Linear in the input size, one pass, no recursion.
29
+ *
30
+ * Returns the same text with the same length: every masked character becomes a
31
+ * space except line breaks, which survive so line numbers stay valid.
32
+ */
33
+ export declare function maskSource(source: string): MaskedSource;
34
+ /** 1-based line number for a byte offset, via binary search over `lineStarts`. */
35
+ export declare function lineAt(lineStarts: readonly number[], offset: number): number;
36
+ /** Same text as `source` but with the given 1-based line replaced by spaces (keeps offsets). */
37
+ export declare function blankLine(source: string, lineStarts: readonly number[], line: number): string;
38
+ /** Split masked text into lines, paired with their 1-based number. */
39
+ export declare function maskedLines(masked: string): readonly {
40
+ readonly line: number;
41
+ readonly text: string;
42
+ }[];
43
+ /** True when `ch` at `index` sits inside a word (used to reject partial identifier matches). */
44
+ export declare function isIdentifierBoundary(source: string, index: number): boolean;