@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,147 @@
1
+ /**
2
+ * Stage 1 DISCOVER (spec 5.3): enumerate candidate files under the root.
3
+ *
4
+ * TWO SOURCES, ONE SHAPE. `git ls-files` is the primary source because it already
5
+ * applies the repository's own ignore rules and is an order of magnitude faster
6
+ * on a large tree. When git is unavailable the scanner walks the filesystem and
7
+ * applies the same matcher itself - and that fallback is LABELLED, so the panel
8
+ * can say `DISCOVER (fs walk)` instead of implying git was used (spec I-5:
9
+ * degrade honestly, never silently).
10
+ *
11
+ * The output is sorted. Determinism is not cosmetic here: an unsorted list makes
12
+ * a diff of two generations meaningless and makes a flaky test out of any
13
+ * duplicate-name resolution.
14
+ *
15
+ * ASCII ONLY: inside the glyph scanner's scope.
16
+ */
17
+ import { execFileSync } from 'node:child_process';
18
+ import { readdirSync, statSync } from 'node:fs';
19
+ import { join } from 'node:path';
20
+ import { discoverError } from './errors.js';
21
+ import { INDEXABLE_EXTENSIONS, MAX_FILES_DEFAULT } from './limits.js';
22
+ import { extensionOf, toPosix } from './paths.js';
23
+ /** True when the extension is one the scanner can read. */
24
+ function isIndexable(path) {
25
+ return INDEXABLE_EXTENSIONS.includes(extensionOf(path));
26
+ }
27
+ /** Try `git ls-files -z`: NUL separated so a path with a newline cannot split a row. */
28
+ function listWithGit(root) {
29
+ try {
30
+ const out = execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
31
+ cwd: root,
32
+ encoding: 'utf8',
33
+ stdio: ['ignore', 'pipe', 'ignore'],
34
+ timeout: 60_000,
35
+ maxBuffer: 256 * 1024 * 1024,
36
+ });
37
+ return out.split('\u0000').filter((entry) => entry !== '');
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ /**
44
+ * Walk the filesystem. Depth-first with an explicit stack (no recursion) so a
45
+ * pathological tree cannot blow the call stack, and symlinked directories are
46
+ * skipped because following them risks an infinite loop.
47
+ */
48
+ function listWithFsWalk(root, matcher, maxFiles) {
49
+ const out = [];
50
+ const stack = [''];
51
+ while (stack.length > 0) {
52
+ const relative = stack.pop();
53
+ if (relative === undefined)
54
+ break;
55
+ const absolute = relative === '' ? root : join(root, relative);
56
+ let entries;
57
+ try {
58
+ entries = readdirSync(absolute);
59
+ }
60
+ catch {
61
+ // An unreadable directory is skipped, not fatal: the rest of the tree is
62
+ // still worth indexing, and `/index status` reports the file count it got.
63
+ continue;
64
+ }
65
+ for (const entry of entries) {
66
+ const childRelative = relative === '' ? entry : `${relative}/${entry}`;
67
+ if (matcher.matches(childRelative))
68
+ continue;
69
+ const childAbsolute = join(root, childRelative);
70
+ let stats;
71
+ try {
72
+ stats = statSync(childAbsolute);
73
+ }
74
+ catch {
75
+ continue;
76
+ }
77
+ if (stats.isDirectory()) {
78
+ stack.push(childRelative);
79
+ continue;
80
+ }
81
+ if (!stats.isFile() || !isIndexable(childRelative))
82
+ continue;
83
+ out.push(childRelative);
84
+ if (out.length > maxFiles)
85
+ return out;
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+ /**
91
+ * Discover every indexable file.
92
+ *
93
+ * `maxFiles` is enforced here rather than in PLAN so an enormous workspace stops
94
+ * before any `stat` storm; PLAN still validates the count, because the two
95
+ * checks protect different things (cost vs. correctness).
96
+ */
97
+ export function discover(options) {
98
+ const maxFiles = options.maxFiles ?? MAX_FILES_DEFAULT;
99
+ const preferGit = options.preferGit !== false;
100
+ const matcher = options.matcher;
101
+ let paths;
102
+ if (preferGit) {
103
+ const fromGit = listWithGit(options.root);
104
+ if (fromGit) {
105
+ paths = fromGit
106
+ .map((entry) => toPosix(entry))
107
+ .filter((entry) => isIndexable(entry) && !matcher.matches(entry));
108
+ }
109
+ }
110
+ const usedGit = paths !== undefined;
111
+ const walked = paths ?? listWithFsWalk(options.root, matcher, maxFiles);
112
+ const candidates = paths ?? walked;
113
+ const files = [];
114
+ let excluded = 0;
115
+ for (const relative of candidates) {
116
+ // STOP ONE PAST THE LIMIT, NEVER AT IT. Breaking at `>= maxFiles` capped the list at
117
+ // exactly the limit, so the caller's `files.length > maxFiles` check could never fire
118
+ // and `E_INDEX_TOO_LARGE` was dead code: an over-limit workspace became an index that
119
+ // silently omits files, which is the degradation I-5 forbids. One extra stat call is
120
+ // the price of being able to say "there are more than maxFiles".
121
+ if (files.length > maxFiles) {
122
+ // The caller turns the count into `E_INDEX_TOO_LARGE`; discovery itself
123
+ // never decides policy, it only stops paying for more stat calls.
124
+ break;
125
+ }
126
+ const absolute = toPosix(join(options.root, relative));
127
+ let bytes = 0;
128
+ try {
129
+ const stats = statSync(absolute);
130
+ if (!stats.isFile())
131
+ continue;
132
+ bytes = stats.size;
133
+ }
134
+ catch {
135
+ excluded += 1;
136
+ continue;
137
+ }
138
+ files.push({ path: relative, absolute, extension: extensionOf(relative), bytes });
139
+ }
140
+ if (files.length === 0 && !usedGit && candidates.length === 0) {
141
+ // Nothing at all came back from either source: this is the one case that is
142
+ // a real failure rather than an empty (or fully excluded) repository.
143
+ throw discoverError(options.root, 'no files were listed and the filesystem walk returned nothing');
144
+ }
145
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
146
+ return { files, usedGit, excluded };
147
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The engine facade: `build` / `status` / `query` / `clean` (spec 7.2).
3
+ *
4
+ * THERE IS NO `cancel()`, AND THAT IS A DECISION (spec P1-7). Cancellation travels
5
+ * as the `signal` on `build()`; a second entry point would create the half-cancelled
6
+ * state ("aborted the signal but did not call cancel") and that state can never be
7
+ * defined cleanly. One cancellation entry point is the whole rule.
8
+ *
9
+ * The six stages run in one function so the ordering is visible in one place. Each
10
+ * stage is imported, pure and separately tested; this file only sequences them,
11
+ * owns the lock, and turns failures into `IndexResult` values instead of throws.
12
+ *
13
+ * ASCII ONLY: inside the glyph scanner's scope.
14
+ */
15
+ import type { IndexBuildOptions, IndexQueryRequest, IndexQueryResult, IndexResult, IndexStatus } from '@aragon-agent/tui/model/index-build/types';
16
+ import type { IndexLimits } from './limits.js';
17
+ import { type IndexPaths } from './paths.js';
18
+ /** Everything the facade needs, injected so tests can forge roots, clocks and logs. */
19
+ export interface IndexerDeps {
20
+ /** Working directory the user invoked from; the root is discovered from it. */
21
+ readonly cwd: string;
22
+ /** Clamped byte/count budgets. */
23
+ readonly limits: IndexLimits;
24
+ /** Extra exclusion prefixes from `index.exclude`. */
25
+ readonly exclude: readonly string[];
26
+ /** Master switch; off short-circuits every entry point. */
27
+ readonly enabled: boolean;
28
+ /** Structured log sink. Never receives file contents (spec 5.13). */
29
+ readonly log?: (event: string, fields?: Record<string, unknown>) => void;
30
+ /** Clock override, for byte-stable generation tests. */
31
+ readonly now?: () => number;
32
+ /** Generation number override, for tests that must not race the pointer. */
33
+ readonly generationOverride?: number;
34
+ }
35
+ /** The port the TUI, `/index` and the host all consume. */
36
+ export interface IndexEngine {
37
+ /** Run one build. Resolves to a failure value rather than throwing. */
38
+ build(opts: IndexBuildOptions): Promise<IndexResult>;
39
+ /** Read the current index's facts without loading its tables. */
40
+ status(): Promise<IndexStatus>;
41
+ /** Answer one `code_query`. */
42
+ query(req: IndexQueryRequest): Promise<IndexQueryResult>;
43
+ /** Delete every generation; leaves the prose index alone. */
44
+ clean(): Promise<void>;
45
+ /** Root this engine resolved on construction. */
46
+ readonly root: string;
47
+ /** Artifact paths, for `/index status` and `/index open ast`. */
48
+ readonly paths: IndexPaths;
49
+ }
50
+ /** Build the engine for one workspace. The root is resolved once, here. */
51
+ export declare function createIndexEngine(deps: IndexerDeps): IndexEngine;
@@ -0,0 +1,477 @@
1
+ /**
2
+ * The engine facade: `build` / `status` / `query` / `clean` (spec 7.2).
3
+ *
4
+ * THERE IS NO `cancel()`, AND THAT IS A DECISION (spec P1-7). Cancellation travels
5
+ * as the `signal` on `build()`; a second entry point would create the half-cancelled
6
+ * state ("aborted the signal but did not call cancel") and that state can never be
7
+ * defined cleanly. One cancellation entry point is the whole rule.
8
+ *
9
+ * The six stages run in one function so the ordering is visible in one place. Each
10
+ * stage is imported, pure and separately tested; this file only sequences them,
11
+ * owns the lock, and turns failures into `IndexResult` values instead of throws.
12
+ *
13
+ * ASCII ONLY: inside the glyph scanner's scope.
14
+ */
15
+ import { assemblePayload, commitGeneration, fingerprintPayload, resolveImports } from './commit.js';
16
+ import { discover } from './discover.js';
17
+ import { fingerprintFiles } from './fingerprint.js';
18
+ import { cancelledError, isIndexError, toIndexFailure, tooLargeError, } from './errors.js';
19
+ import { finalize } from './finalize.js';
20
+ import { createIgnoreMatcher } from './ignore.js';
21
+ import { applyFanIn, linkReferences, resolutionHistogram, resolvedPercent } from './link.js';
22
+ import { acquireLock, assertLockOwned, startStageHeartbeat } from './lock.js';
23
+ import { parseFiles } from './parse.js';
24
+ import { plan } from './plan.js';
25
+ import { countCommitsBehind, discoverRoot, ensureArtifactDirs, indexPathsFor, readGitHead } from './paths.js';
26
+ import { buildGraph, rankMap, rankSymbols } from './rank.js';
27
+ import { loadCurrent, readCurrentMeta, removeAllGenerations } from './store.js';
28
+ /** Stage weights for the progress percentage (spec 13.2). */
29
+ const STAGE_MS_KEYS = ['discover', 'plan', 'parse', 'commit', 'link', 'finalize'];
30
+ /** Build the engine for one workspace. The root is resolved once, here. */
31
+ export function createIndexEngine(deps) {
32
+ const { root } = discoverRoot(deps.cwd);
33
+ const paths = indexPathsFor(root);
34
+ const log = deps.log ?? (() => undefined);
35
+ const now = deps.now ?? Date.now;
36
+ /** Compose the snapshot the overlay consumes. */
37
+ function snapshot(state, status) {
38
+ const stages = STAGE_MS_KEYS.map((stage) => {
39
+ const row = state.stages.get(stage) ?? { state: 'pending', done: 0, total: 0, ms: 0 };
40
+ return { stage, state: row.state, done: row.done, total: row.total, ms: Math.round(row.ms), detail: row.detail };
41
+ });
42
+ return {
43
+ runId: state.runId,
44
+ status,
45
+ stages,
46
+ currentFile: state.currentFile,
47
+ symbols: state.symbols,
48
+ files: state.files,
49
+ failures: state.failures,
50
+ elapsedMs: Math.round(now() - state.startedAt),
51
+ etaMs: state.etaMs,
52
+ generation: state.generation,
53
+ notice: state.notice,
54
+ };
55
+ }
56
+ /** Mark a stage active and remember its start time, so `ms` is measured not guessed. */
57
+ function beginStage(state, stage, total = 0, detail) {
58
+ state.stages.set(stage, { state: 'active', done: 0, total, ms: 0, detail });
59
+ }
60
+ /** Mark a stage done, accumulating its duration. */
61
+ function endStage(state, stage, elapsedMs, done) {
62
+ const row = state.stages.get(stage);
63
+ state.stages.set(stage, {
64
+ state: 'done',
65
+ done: done ?? row?.done ?? 0,
66
+ total: row?.total ?? 0,
67
+ ms: elapsedMs,
68
+ detail: row?.detail,
69
+ });
70
+ }
71
+ /** Load the previous generation's rows, mapping a schema failure to a rebuild. */
72
+ function loadPrevious() {
73
+ try {
74
+ const generation = loadCurrent(paths);
75
+ if (!generation)
76
+ return { facts: [], rows: [] };
77
+ // ONE GROUPING PASS, NOT A FILTER PER FILE. Filtering the whole table inside the
78
+ // per-file loop is quadratic, and it produces exactly the facts these maps do.
79
+ const symbolsByFile = groupBy(generation.symbols, (symbol) => symbol.f);
80
+ const refsByFile = groupBy(generation.refs, (ref) => ref.f);
81
+ const importsByFile = groupBy(generation.imports, (entry) => entry.f);
82
+ const byFile = new Map();
83
+ for (const row of generation.files) {
84
+ byFile.set(row.p, {
85
+ path: row.p,
86
+ lang: row.l,
87
+ bytes: row.b,
88
+ sha1: row.h,
89
+ lines: row.n,
90
+ status: row.s,
91
+ parseMs: row.ms,
92
+ symbols: symbolsByFile.get(row.p) ?? [],
93
+ refs: (refsByFile.get(row.p) ?? []).map((ref) => ({ f: ref.f, ln: ref.ln, fk: ref.fk, n: ref.n })),
94
+ imports: importsByFile.get(row.p) ?? [],
95
+ });
96
+ }
97
+ return { facts: [...byFile.values()], rows: generation.files };
98
+ }
99
+ catch (error) {
100
+ // An unreadable/unknown-schema index is not a reason to refuse a rebuild:
101
+ // it is the reason FOR one (spec 7.4).
102
+ if (isIndexError(error) && error.code === 'E_INDEX_SCHEMA') {
103
+ log('index.schema.unknown', { message: error.message });
104
+ return { facts: [], rows: [] };
105
+ }
106
+ throw error;
107
+ }
108
+ }
109
+ /** Build the answer for `status()`, including staleness reasons (spec 13.4). */
110
+ async function status() {
111
+ const proseIndex = (await import('node:fs')).existsSync(paths.proseIndexFile) ? 'present' : 'missing';
112
+ let meta;
113
+ try {
114
+ meta = readCurrentMeta(paths);
115
+ }
116
+ catch (error) {
117
+ if (isIndexError(error) && error.code === 'E_INDEX_SCHEMA') {
118
+ return { present: false, staleReasons: ['schema'], proseIndex, notice: error.message };
119
+ }
120
+ throw error;
121
+ }
122
+ if (!meta) {
123
+ return { present: false, staleReasons: ['missing'], proseIndex };
124
+ }
125
+ const behind = countCommitsBehind(root, meta.gitHead);
126
+ const staleReasons = [];
127
+ if (behind !== undefined && behind > 0)
128
+ staleReasons.push('git-head');
129
+ const resolvedTotal = Object.values(meta.resolved).reduce((sum, value) => sum + value, 0);
130
+ const resolvedOk = resolvedTotal - (meta.resolved.none ?? 0);
131
+ return {
132
+ present: true,
133
+ generation: meta.generation,
134
+ files: meta.counts.files,
135
+ symbols: meta.counts.symbols,
136
+ refs: meta.counts.refs,
137
+ resolvedPct: resolvedTotal === 0 ? 0 : Math.round((resolvedOk / resolvedTotal) * 1000) / 10,
138
+ behindCommits: behind,
139
+ builtHeadSha: meta.gitHead,
140
+ staleReasons,
141
+ proseIndex,
142
+ notice: behind === undefined ? 'behind-commits unknown (git unavailable)' : undefined,
143
+ };
144
+ }
145
+ /** Run the whole pipeline. */
146
+ async function build(opts) {
147
+ if (!deps.enabled) {
148
+ return { ok: false, code: 'E_INDEX_DISABLED', message: 'The project index is off. Run /index on to enable it.' };
149
+ }
150
+ const runId = `run-${now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
151
+ const state = {
152
+ runId,
153
+ stages: new Map(),
154
+ symbols: 0,
155
+ files: 0,
156
+ failures: 0,
157
+ startedAt: now(),
158
+ };
159
+ let lock;
160
+ let stopHeartbeat;
161
+ log('index.build.start', { root, reason: opts.reason, runId });
162
+ try {
163
+ ensureArtifactDirs(paths);
164
+ const acquired = acquireLock(paths, { runId });
165
+ if (!acquired.ok) {
166
+ const holder = acquired.holder;
167
+ log('index.build.busy', { pid: holder.pid, runId: holder.runId });
168
+ return {
169
+ ok: false,
170
+ code: 'E_INDEX_BUSY',
171
+ message: `Another process is building the index (pid ${holder.pid}). Press Ctrl+I to watch it.`,
172
+ };
173
+ }
174
+ lock = acquired.handle;
175
+ if (acquired.takeover !== 'none')
176
+ log('index.lock.takeover', { reason: acquired.takeover });
177
+ stopHeartbeat = startStageHeartbeat(lock);
178
+ const previous = loadPrevious();
179
+ const previousByPath = new Map(previous.rows.map((row) => [row.p, row]));
180
+ // ---- stage 1 DISCOVER
181
+ const discoverStart = now();
182
+ beginStage(state, 'discover');
183
+ opts.onProgress(snapshot(state, 'running'));
184
+ const matcher = createIgnoreMatcher({ root, exclude: deps.exclude });
185
+ const discovered = discover({ root, matcher, maxFiles: deps.limits.maxFiles });
186
+ endStage(state, 'discover', now() - discoverStart, discovered.files.length);
187
+ state.files = discovered.files.length;
188
+ if (!discovered.usedGit)
189
+ state.notice = 'DISCOVER (fs walk)';
190
+ opts.onProgress(snapshot(state, 'running'));
191
+ if (discovered.files.length > deps.limits.maxFiles)
192
+ throw tooLargeError(discovered.files.length, deps.limits.maxFiles);
193
+ if (discovered.files.length === 0) {
194
+ state.stages.set('discover', { state: 'done', done: 0, total: 0, ms: 0, detail: 'no indexable files' });
195
+ state.stages.set('plan', { state: 'skipped', done: 0, total: 0, ms: 0 });
196
+ state.stages.set('parse', { state: 'skipped', done: 0, total: 0, ms: 0 });
197
+ state.stages.set('commit', { state: 'skipped', done: 0, total: 0, ms: 0 });
198
+ state.stages.set('link', { state: 'skipped', done: 0, total: 0, ms: 0 });
199
+ state.stages.set('finalize', { state: 'skipped', done: 0, total: 0, ms: 0 });
200
+ state.notice = 'No indexable files found';
201
+ opts.onProgress(snapshot(state, 'ok'));
202
+ return { ok: false, code: 'E_INDEX_DISCOVER', message: `No indexable files found under ${root}.` };
203
+ }
204
+ // ---- stage 2 PLAN
205
+ const planStart = now();
206
+ beginStage(state, 'plan');
207
+ // Hash every candidate FIRST: the changed/reused split must be a CONTENT decision,
208
+ // not a size guess (spec 13.4 / AC-9). Oversize files are skipped without a read.
209
+ const fingerprints = fingerprintFiles(discovered.files, {
210
+ signal: opts.signal,
211
+ maxFileBytes: deps.limits.maxFileBytes,
212
+ });
213
+ if (opts.signal.aborted)
214
+ throw cancelledError();
215
+ const planned = plan({
216
+ files: discovered.files,
217
+ fingerprints,
218
+ previous: previous.rows,
219
+ maxFiles: deps.limits.maxFiles,
220
+ });
221
+ endStage(state, 'plan', now() - planStart, planned.toParse.length);
222
+ state.stages.set('plan', {
223
+ state: 'done',
224
+ done: planned.toParse.length,
225
+ total: discovered.files.length,
226
+ ms: now() - planStart,
227
+ detail: `${planned.toParse.length} changed - ${planned.toReuse.length} reused`,
228
+ });
229
+ opts.onProgress(snapshot(state, 'running'));
230
+ assertLockOwned(lock);
231
+ // ---- stage 3 PARSE
232
+ const parseStart = now();
233
+ beginStage(state, 'parse', planned.toParse.length);
234
+ const onFileTimes = [];
235
+ const parsed = await parseFiles({
236
+ files: planned.toParse,
237
+ maxFileBytes: deps.limits.maxFileBytes,
238
+ signal: opts.signal,
239
+ onFile: (facts) => {
240
+ onFileTimes.push(facts.parseMs);
241
+ if (onFileTimes.length > 64)
242
+ onFileTimes.shift();
243
+ },
244
+ onBatch: (report) => {
245
+ lock?.heartbeat();
246
+ state.symbols += 0;
247
+ state.files = report.done + planned.toReuse.length;
248
+ state.failures = report.failures;
249
+ state.currentFile = report.lastPath;
250
+ const row = state.stages.get('parse');
251
+ if (row) {
252
+ state.stages.set('parse', { ...row, done: report.done, total: report.total, ms: now() - parseStart });
253
+ }
254
+ state.etaMs = estimateEtaMs(report.done, report.total, onFileTimes);
255
+ opts.onProgress(snapshot(state, 'running'));
256
+ },
257
+ });
258
+ if (opts.signal.aborted)
259
+ throw cancelledError();
260
+ assertLockOwned(lock);
261
+ const reusedFacts = previous.facts.filter((facts) => planned.toReuse.includes(facts.path));
262
+ const allFacts = [...parsed, ...reusedFacts].sort((a, b) => (a.path < b.path ? -1 : 1));
263
+ state.symbols = allFacts.reduce((sum, facts) => sum + facts.symbols.length, 0);
264
+ state.failures = allFacts.filter((facts) => facts.status !== 'ok').length;
265
+ endStage(state, 'parse', now() - parseStart, planned.toParse.length);
266
+ opts.onProgress(snapshot(state, 'running'));
267
+ // ---- stage 5 LINK (before COMMIT: links need the whole generation in memory)
268
+ const linkStart = now();
269
+ beginStage(state, 'link');
270
+ opts.onProgress(snapshot(state, 'running'));
271
+ const linked = linkReferences(allFacts);
272
+ assertLockOwned(lock);
273
+ endStage(state, 'link', now() - linkStart, linked.refs.length);
274
+ // ---- RANK, then stage 4 COMMIT
275
+ const rankStart = now();
276
+ const fileRows = allFacts.map((facts) => ({
277
+ p: facts.path,
278
+ l: facts.lang,
279
+ b: facts.bytes,
280
+ h: facts.sha1,
281
+ n: facts.lines,
282
+ s: facts.status,
283
+ ms: Math.round(facts.parseMs),
284
+ sy: facts.symbols.length,
285
+ rf: facts.refs.length,
286
+ im: facts.imports.length,
287
+ }));
288
+ const imports = resolveImports(allFacts);
289
+ const graph = buildGraph(fileRows, imports);
290
+ const ranks = rankMap(graph);
291
+ const symbols = rankSymbols(applyFanIn(allFacts.flatMap((facts) => facts.symbols), linked.fanIn), ranks);
292
+ const refs = linked.refs;
293
+ void rankStart;
294
+ const git = readGitHead(root);
295
+ const previousMeta = readCurrentMeta(paths);
296
+ const buildStartWall = now();
297
+ const generation = deps.generationOverride ?? (previousMeta ? previousMeta.generation + 1 : 1);
298
+ const sameFileSet = planned.toParse.length === 0 && planned.removed.length === 0;
299
+ const sameHead = (previousMeta?.gitHead ?? null) === (git.head ?? null);
300
+ const unchanged = sameFileSet && sameHead && previousMeta !== undefined;
301
+ const payload = assemblePayload({
302
+ facts: allFacts,
303
+ refs,
304
+ symbols,
305
+ imports,
306
+ graph,
307
+ generation,
308
+ root,
309
+ gitHead: git.head,
310
+ gitHeadDirty: git.dirty,
311
+ durationMs: now() - buildStartWall,
312
+ reparsed: planned.toParse.length,
313
+ reused: planned.toReuse.length,
314
+ unchanged,
315
+ });
316
+ if (unchanged && previousMeta) {
317
+ // No-op (spec 13.4): nothing to re-parse AND the head did not move, so the
318
+ // generation on disk is still honest about HEAD. Writing another identical
319
+ // generation would advance a pointer that describes the same content.
320
+ state.generation = previousMeta.generation;
321
+ for (const stage of ['commit', 'finalize']) {
322
+ state.stages.set(stage, { state: 'skipped', done: 0, total: 0, ms: 0 });
323
+ }
324
+ opts.onProgress(snapshot(state, 'ok'));
325
+ log('index.build.end', { generation: previousMeta.generation, unchanged: true, runId });
326
+ return {
327
+ ok: true,
328
+ generation: previousMeta.generation,
329
+ files: payload.meta.counts.files,
330
+ symbols: payload.meta.counts.symbols,
331
+ refs: payload.meta.counts.refs,
332
+ durationMs: now() - state.startedAt,
333
+ failures: allFacts.filter((facts) => facts.status !== 'ok').length,
334
+ reparsed: 0,
335
+ unchanged: true,
336
+ };
337
+ }
338
+ const commitStart = now();
339
+ beginStage(state, 'commit');
340
+ state.generation = generation;
341
+ state.stages.set('commit', {
342
+ state: 'active',
343
+ done: 0,
344
+ total: payload.files.length,
345
+ ms: 0,
346
+ detail: `writes generation ${generation}`,
347
+ });
348
+ opts.onProgress(snapshot(state, 'running'));
349
+ const fingerprint = fingerprintPayload(payload);
350
+ commitGeneration(paths, payload);
351
+ assertLockOwned(lock);
352
+ endStage(state, 'commit', now() - commitStart, payload.files.length);
353
+ opts.onProgress(snapshot(state, 'running'));
354
+ // ---- stage 6 FINALIZE
355
+ const finalizeStart = now();
356
+ beginStage(state, 'finalize');
357
+ // THE GUARD IMMEDIATELY BEFORE THE ONE IRREVERSIBLE WRITE. `assertLockOwned` ran
358
+ // after COMMIT but not between COMMIT and the pointer rename: a takeover landing in
359
+ // that window let two processes both move `current` and both prune, and
360
+ // `pruneGenerations` deletes everything except ITS OWN generation - so the loser
361
+ // could leave `current` naming a directory the winner had already deleted.
362
+ assertLockOwned(lock);
363
+ const result = finalize({
364
+ paths,
365
+ generation,
366
+ keepGenerations: deps.limits.keepGenerations,
367
+ unchanged: false,
368
+ onPointerMoved: () => log('index.pointer.moved', { generation }),
369
+ });
370
+ endStage(state, 'finalize', now() - finalizeStart);
371
+ opts.onProgress(snapshot(state, 'ok'));
372
+ log('index.build.end', {
373
+ generation,
374
+ files: payload.meta.counts.files,
375
+ symbols: payload.meta.counts.symbols,
376
+ resolvedPct: resolvedPercent(refs),
377
+ durationMs: now() - state.startedAt,
378
+ status: 'ok',
379
+ fingerprint,
380
+ removed: result.removed,
381
+ resolved: resolutionHistogram(refs),
382
+ });
383
+ return {
384
+ ok: true,
385
+ generation,
386
+ files: payload.meta.counts.files,
387
+ symbols: payload.meta.counts.symbols,
388
+ refs: payload.meta.counts.refs,
389
+ durationMs: now() - state.startedAt,
390
+ failures: allFacts.filter((facts) => facts.status !== 'ok').length,
391
+ reparsed: planned.toParse.length,
392
+ unchanged: false,
393
+ };
394
+ }
395
+ catch (error) {
396
+ const failure = toIndexFailure(error, runId);
397
+ if (failure.code === 'E_INDEX_CANCELLED') {
398
+ log('index.build.abort', { runId, code: failure.code });
399
+ opts.onProgress(snapshot(state, 'cancelled'));
400
+ }
401
+ else {
402
+ log('index.build.end', { runId, status: 'failed', code: failure.code });
403
+ const row = state.stages.get('parse');
404
+ if (row)
405
+ state.stages.set('parse', { ...row, state: 'failed' });
406
+ opts.onProgress(snapshot(state, 'failed'));
407
+ }
408
+ return { ok: false, code: failure.code, message: failure.message };
409
+ }
410
+ finally {
411
+ stopHeartbeat?.();
412
+ lock?.release();
413
+ }
414
+ }
415
+ return {
416
+ build,
417
+ status,
418
+ query: async (req) => {
419
+ // A DISABLED INDEX ANSWERS WITH THE SWITCH, NOT WITH STALE FACTS (spec 7.5).
420
+ if (!deps.enabled) {
421
+ const text = 'The project index is off, so code_query has nothing to answer from. Run /index on to enable it.';
422
+ return { text, truncated: false, tokens: Math.ceil(text.length / 4) };
423
+ }
424
+ const { runQuery } = await import('./read/query.js');
425
+ return runQuery({ paths, root, request: req });
426
+ },
427
+ clean: async () => {
428
+ // A DISABLED INDEX REFUSES RATHER THAN DELETING (spec 7.5): the user switched the
429
+ // feature off, and `removeAllGenerations` cannot be undone by reading the artifact.
430
+ if (!deps.enabled) {
431
+ throw new Error('The project index is off. Run /index on before cleaning it.');
432
+ }
433
+ // Clean takes the lock first: deleting a generation another process is
434
+ // writing is the only operation here that can truly corrupt an index
435
+ // (spec P2-8).
436
+ const acquired = acquireLock(paths, { runId: `clean-${now().toString(36)}` });
437
+ if (!acquired.ok) {
438
+ throw new Error(`Another process is building the index (pid ${acquired.holder.pid}). Stop it before cleaning.`);
439
+ }
440
+ try {
441
+ removeAllGenerations(paths);
442
+ log('index.clean', { root });
443
+ }
444
+ finally {
445
+ acquired.handle.release();
446
+ }
447
+ },
448
+ root,
449
+ paths,
450
+ };
451
+ }
452
+ /** Group table rows by one key, in a single pass (see the note in `loadPrevious`). */
453
+ function groupBy(rows, key) {
454
+ const out = new Map();
455
+ for (const row of rows) {
456
+ const bucket = out.get(key(row));
457
+ if (bucket)
458
+ bucket.push(row);
459
+ else
460
+ out.set(key(row), [row]);
461
+ }
462
+ return out;
463
+ }
464
+ /** ETA from a recent per-file window; undefined when the sample is too noisy (HCI rule 2). */
465
+ function estimateEtaMs(done, total, window) {
466
+ if (total <= 0 || done >= total)
467
+ return undefined;
468
+ const recent = window.slice(-32).filter((ms) => Number.isFinite(ms) && ms > 0);
469
+ if (recent.length < 4)
470
+ return undefined;
471
+ const mean = recent.reduce((sum, ms) => sum + ms, 0) / recent.length;
472
+ const min = Math.min(...recent);
473
+ const max = Math.max(...recent);
474
+ if (mean <= 0 || (max - min) / mean > 0.4)
475
+ return undefined;
476
+ return Math.round(mean * (total - done));
477
+ }