@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,115 @@
1
+ /**
2
+ * Single-writer lock, heartbeat and stale takeover (spec 5.6 / I-3).
3
+ *
4
+ * WHY THIS FILE IS LOAD-BEARING: a `SIGKILL`ed build leaves its lock behind. If
5
+ * nothing ever decided that such a lock is dead, the feature would answer
6
+ * `E_INDEX_BUSY` forever and the only cure would be deleting a file by hand.
7
+ * `sweepStale()` runs at EVERY entry point for exactly that reason - it is the
8
+ * terminal equivalent of the web console's `sweepStaleRuns`.
9
+ *
10
+ * The second rule: once the heartbeat fails three times in a row, this build
11
+ * STOPS WRITING. Two processes writing the same generation directory would
12
+ * interleave rows, and no later consistency check could untangle them.
13
+ *
14
+ * ASCII ONLY: inside the glyph scanner's scope.
15
+ */
16
+ import type { IndexPaths } from './paths.js';
17
+ /** Lock file contents. Timestamps are ISO strings so a human can read the file. */
18
+ export interface LockRecord {
19
+ /** Owning process id. */
20
+ readonly pid: number;
21
+ /** Host name, so another machine's lock is judged by heartbeat alone. */
22
+ readonly host: string;
23
+ /** Build start, ISO 8601. */
24
+ readonly startedAt: string;
25
+ /** Last liveness write, ISO 8601. */
26
+ readonly heartbeatAt: string;
27
+ /** Run id, so the panel can say which build is running. */
28
+ readonly runId: string;
29
+ /** Generation this run intends to write, when known. */
30
+ readonly generation?: number;
31
+ }
32
+ /** Why a takeover happened, recorded in the structured log (spec 5.6). */
33
+ export type TakeoverReason = 'dead-pid' | 'stale-heartbeat' | 'assumed-stale' | 'none';
34
+ /** Result of acquiring: either we own it, or someone alive does. */
35
+ export type AcquireResult = {
36
+ readonly ok: true;
37
+ readonly handle: LockHandle;
38
+ readonly takeover: TakeoverReason;
39
+ } | {
40
+ readonly ok: false;
41
+ readonly holder: LockRecord;
42
+ };
43
+ /** Millisecond clock, injected so tests can forge staleness without sleeping. */
44
+ export type Clock = () => number;
45
+ /** Options for `acquireLock`. */
46
+ export interface AcquireOptions {
47
+ /** Run id recorded in the lock. */
48
+ readonly runId: string;
49
+ /** Generation this run intends to write, when known at acquisition time. */
50
+ readonly generation?: number;
51
+ /** Clock override for tests. */
52
+ readonly now?: Clock;
53
+ /** True when the pid probe should be skipped (tests that forge a foreign host). */
54
+ readonly probePid?: boolean;
55
+ }
56
+ /** A held lock. `release()` is idempotent so a `finally` block can always call it. */
57
+ export interface LockHandle {
58
+ /** Current lock record. */
59
+ readonly record: LockRecord;
60
+ /** Refresh `heartbeatAt`. Returns false when the write failed. */
61
+ heartbeat(): boolean;
62
+ /** Consecutive failures so far; the engine aborts at the configured limit. */
63
+ failureCount(): number;
64
+ /** True when the lock file no longer belongs to this handle (someone took over). */
65
+ isStillOwned(): boolean;
66
+ /** Delete the lock file if it is still ours. Safe to call twice. */
67
+ release(): void;
68
+ }
69
+ /** This machine's name, or `unknown` when the OS refuses to say. */
70
+ export declare function localHostName(): string;
71
+ /** Read the lock file, or null when absent/unreadable. An unreadable lock is treated as absent. */
72
+ export declare function readLock(paths: IndexPaths): LockRecord | null;
73
+ /** True when a pid is alive on this machine. `EPERM` counts as alive: the process exists. */
74
+ export declare function isPidAlive(pid: number): boolean;
75
+ /** True when the heartbeat is older than the stale window (or unparseable). */
76
+ export declare function isHeartbeatStale(record: LockRecord, now: number): boolean;
77
+ /**
78
+ * Decide whether an existing lock may be taken over.
79
+ *
80
+ * Order matters and mirrors spec 5.6: same host + live pid wins over anything
81
+ * else (a slow step is not a dead build); a different host is judged by
82
+ * heartbeat only, and the takeover is logged as `assumed-stale` because a
83
+ * shared network directory cannot tell us whether that pid exists.
84
+ */
85
+ export declare function shouldTakeOver(record: LockRecord, now: number, options?: {
86
+ readonly probePid?: boolean;
87
+ }): TakeoverReason;
88
+ /**
89
+ * Try to become the writer.
90
+ *
91
+ * Returns `ok: false` with the live holder rather than throwing, because the
92
+ * caller's job is to DISPLAY that holder's progress (spec 7.5: "show the other
93
+ * process's progress, do not refuse"). `sweepStale` is part of this function so
94
+ * there is exactly one recovery path.
95
+ */
96
+ export declare function acquireLock(paths: IndexPaths, options: AcquireOptions): AcquireResult;
97
+ /** Same as `acquireLock` but throws `E_INDEX_BUSY`: for callers that cannot show a panel. */
98
+ export declare function requireLock(paths: IndexPaths, options: AcquireOptions): LockHandle;
99
+ /**
100
+ * Prove the lock is still ours, or throw `E_INDEX_LOCK_LOST`.
101
+ *
102
+ * Called at stage boundaries and after every batch: this is the guard that makes
103
+ * "two writers never touch one generation" true even if a takeover raced us.
104
+ */
105
+ export declare function assertLockOwned(handle: LockHandle): void;
106
+ /**
107
+ * A heartbeat scheduler for stages that have no natural batch boundary
108
+ * (DISCOVER, PLAN, LINK, FINALIZE). PARSE does not use this: it beats per batch
109
+ * so a long parse still looks alive within `HEARTBEAT_INTERVAL_MS`.
110
+ */
111
+ export declare function startStageHeartbeat(handle: LockHandle, intervalMs?: number): () => void;
112
+ /** Age of the lock in milliseconds, or undefined when there is no lock. */
113
+ export declare function lockAgeMs(paths: IndexPaths, now?: number): number | undefined;
114
+ /** Size of the lock file, used by the `/index status` self-check to catch a truncated write. */
115
+ export declare function lockFileSize(paths: IndexPaths): number;
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Single-writer lock, heartbeat and stale takeover (spec 5.6 / I-3).
3
+ *
4
+ * WHY THIS FILE IS LOAD-BEARING: a `SIGKILL`ed build leaves its lock behind. If
5
+ * nothing ever decided that such a lock is dead, the feature would answer
6
+ * `E_INDEX_BUSY` forever and the only cure would be deleting a file by hand.
7
+ * `sweepStale()` runs at EVERY entry point for exactly that reason - it is the
8
+ * terminal equivalent of the web console's `sweepStaleRuns`.
9
+ *
10
+ * The second rule: once the heartbeat fails three times in a row, this build
11
+ * STOPS WRITING. Two processes writing the same generation directory would
12
+ * interleave rows, and no later consistency check could untangle them.
13
+ *
14
+ * ASCII ONLY: inside the glyph scanner's scope.
15
+ */
16
+ import { closeSync, existsSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs';
17
+ import { hostname } from 'node:os';
18
+ import { busyError, lockLostError, unwritableError } from './errors.js';
19
+ import { HEARTBEAT_FAILURE_LIMIT, HEARTBEAT_INTERVAL_MS, HEARTBEAT_STAGE_INTERVAL_MS, LOCK_STALE_MS, } from './limits.js';
20
+ /** Current host name, cached: `hostname()` is a syscall and the lock writes often. */
21
+ let cachedHost;
22
+ /** This machine's name, or `unknown` when the OS refuses to say. */
23
+ export function localHostName() {
24
+ if (cachedHost === undefined) {
25
+ try {
26
+ cachedHost = hostname();
27
+ }
28
+ catch {
29
+ cachedHost = 'unknown';
30
+ }
31
+ }
32
+ return cachedHost;
33
+ }
34
+ /** Read the lock file, or null when absent/unreadable. An unreadable lock is treated as absent. */
35
+ export function readLock(paths) {
36
+ if (!existsSync(paths.lockFile))
37
+ return null;
38
+ try {
39
+ const parsed = JSON.parse(readFileSync(paths.lockFile, 'utf8'));
40
+ if (typeof parsed.pid !== 'number')
41
+ return null;
42
+ return {
43
+ pid: parsed.pid,
44
+ host: typeof parsed.host === 'string' ? parsed.host : 'unknown',
45
+ startedAt: typeof parsed.startedAt === 'string' ? parsed.startedAt : new Date(0).toISOString(),
46
+ heartbeatAt: typeof parsed.heartbeatAt === 'string' ? parsed.heartbeatAt : new Date(0).toISOString(),
47
+ runId: typeof parsed.runId === 'string' ? parsed.runId : 'unknown',
48
+ generation: typeof parsed.generation === 'number' ? parsed.generation : undefined,
49
+ };
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ /** True when a pid is alive on this machine. `EPERM` counts as alive: the process exists. */
56
+ export function isPidAlive(pid) {
57
+ if (!Number.isFinite(pid) || pid <= 0)
58
+ return false;
59
+ try {
60
+ process.kill(pid, 0);
61
+ return true;
62
+ }
63
+ catch (error) {
64
+ const code = error.code;
65
+ return code === 'EPERM';
66
+ }
67
+ }
68
+ /** True when the heartbeat is older than the stale window (or unparseable). */
69
+ export function isHeartbeatStale(record, now) {
70
+ const beat = Date.parse(record.heartbeatAt);
71
+ if (!Number.isFinite(beat))
72
+ return true;
73
+ return now - beat > LOCK_STALE_MS;
74
+ }
75
+ /**
76
+ * Decide whether an existing lock may be taken over.
77
+ *
78
+ * Order matters and mirrors spec 5.6: same host + live pid wins over anything
79
+ * else (a slow step is not a dead build); a different host is judged by
80
+ * heartbeat only, and the takeover is logged as `assumed-stale` because a
81
+ * shared network directory cannot tell us whether that pid exists.
82
+ */
83
+ export function shouldTakeOver(record, now, options = {}) {
84
+ const sameHost = record.host === localHostName() || record.host === 'unknown';
85
+ if (sameHost && options.probePid !== false) {
86
+ if (!isPidAlive(record.pid))
87
+ return 'dead-pid';
88
+ if (isHeartbeatStale(record, now))
89
+ return 'stale-heartbeat';
90
+ return 'none';
91
+ }
92
+ if (isHeartbeatStale(record, now))
93
+ return sameHost ? 'stale-heartbeat' : 'assumed-stale';
94
+ return 'none';
95
+ }
96
+ /** Write the lock record atomically (temp + rename), so a reader never sees a half file. */
97
+ function writeLockFile(paths, record) {
98
+ const temp = `${paths.lockFile}.tmp`;
99
+ try {
100
+ writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, 'utf8');
101
+ renameSync(temp, paths.lockFile);
102
+ }
103
+ catch (error) {
104
+ const cause = error instanceof Error ? error.message : String(error);
105
+ throw unwritableError(paths.astDir, cause);
106
+ }
107
+ }
108
+ /** Remove a lock file, ignoring a failure (the next `sweepStale` will retry). */
109
+ function removeLockFile(paths) {
110
+ try {
111
+ rmSync(paths.lockFile, { force: true });
112
+ }
113
+ catch {
114
+ // Best effort; a leftover lock is recovered by the next entry point.
115
+ }
116
+ }
117
+ /** True when the file was created by this call (`O_EXCL`), i.e. nobody else held it. */
118
+ function createExclusive(paths, record) {
119
+ let handle;
120
+ try {
121
+ handle = openSync(paths.lockFile, 'wx');
122
+ writeSync(handle, `${JSON.stringify(record, null, 2)}\n`);
123
+ return true;
124
+ }
125
+ catch (error) {
126
+ const code = error.code;
127
+ if (code === 'EEXIST')
128
+ return false;
129
+ const cause = error instanceof Error ? error.message : String(error);
130
+ throw unwritableError(paths.astDir, cause);
131
+ }
132
+ finally {
133
+ if (handle !== undefined)
134
+ closeSync(handle);
135
+ }
136
+ }
137
+ /**
138
+ * Try to become the writer.
139
+ *
140
+ * Returns `ok: false` with the live holder rather than throwing, because the
141
+ * caller's job is to DISPLAY that holder's progress (spec 7.5: "show the other
142
+ * process's progress, do not refuse"). `sweepStale` is part of this function so
143
+ * there is exactly one recovery path.
144
+ */
145
+ export function acquireLock(paths, options) {
146
+ const now = options.now ?? Date.now;
147
+ const startedAt = new Date(now()).toISOString();
148
+ const base = {
149
+ pid: process.pid,
150
+ host: localHostName(),
151
+ startedAt,
152
+ heartbeatAt: startedAt,
153
+ runId: options.runId,
154
+ generation: options.generation,
155
+ };
156
+ if (createExclusive(paths, base)) {
157
+ return { ok: true, handle: makeHandle(paths, base, now), takeover: 'none' };
158
+ }
159
+ const existing = readLock(paths);
160
+ if (!existing) {
161
+ // Unreadable lock: treat as stale and take it. A file we cannot parse cannot
162
+ // belong to a live writer that follows this format.
163
+ writeLockFile(paths, base);
164
+ return { ok: true, handle: makeHandle(paths, base, now), takeover: 'stale-heartbeat' };
165
+ }
166
+ const verdict = shouldTakeOver(existing, now(), { probePid: options.probePid });
167
+ if (verdict === 'none')
168
+ return { ok: false, holder: existing };
169
+ writeLockFile(paths, base);
170
+ // CONFIRM THE TAKEOVER, like every sibling lock in this repo does. Two processes that
171
+ // judge the same stale lock both reach the write above; without this re-read both would
172
+ // answer `ok: true`, and the loser would only find out after paying for DISCOVER + PARSE.
173
+ const winner = readLock(paths);
174
+ if (!winner || winner.pid !== base.pid || winner.runId !== base.runId) {
175
+ return { ok: false, holder: winner ?? existing };
176
+ }
177
+ return { ok: true, handle: makeHandle(paths, base, now), takeover: verdict };
178
+ }
179
+ /** Same as `acquireLock` but throws `E_INDEX_BUSY`: for callers that cannot show a panel. */
180
+ export function requireLock(paths, options) {
181
+ const result = acquireLock(paths, options);
182
+ if (!result.ok)
183
+ throw busyError(result.holder);
184
+ return result.handle;
185
+ }
186
+ /** Build the handle around a record this process owns. */
187
+ function makeHandle(paths, record, now) {
188
+ let current = record;
189
+ let failures = 0;
190
+ let released = false;
191
+ return {
192
+ get record() {
193
+ return current;
194
+ },
195
+ heartbeat() {
196
+ if (released)
197
+ return false;
198
+ try {
199
+ current = { ...current, heartbeatAt: new Date(now()).toISOString() };
200
+ writeLockFile(paths, current);
201
+ failures = 0;
202
+ return true;
203
+ }
204
+ catch {
205
+ failures += 1;
206
+ return false;
207
+ }
208
+ },
209
+ failureCount() {
210
+ return failures;
211
+ },
212
+ isStillOwned() {
213
+ const onDisk = readLock(paths);
214
+ if (!onDisk)
215
+ return false;
216
+ return onDisk.pid === current.pid && onDisk.runId === current.runId;
217
+ },
218
+ release() {
219
+ if (released)
220
+ return;
221
+ released = true;
222
+ if (this.isStillOwned())
223
+ removeLockFile(paths);
224
+ },
225
+ };
226
+ }
227
+ /**
228
+ * Prove the lock is still ours, or throw `E_INDEX_LOCK_LOST`.
229
+ *
230
+ * Called at stage boundaries and after every batch: this is the guard that makes
231
+ * "two writers never touch one generation" true even if a takeover raced us.
232
+ */
233
+ export function assertLockOwned(handle) {
234
+ if (handle.failureCount() >= HEARTBEAT_FAILURE_LIMIT)
235
+ throw lockLostError();
236
+ if (!handle.isStillOwned())
237
+ throw lockLostError();
238
+ }
239
+ /**
240
+ * A heartbeat scheduler for stages that have no natural batch boundary
241
+ * (DISCOVER, PLAN, LINK, FINALIZE). PARSE does not use this: it beats per batch
242
+ * so a long parse still looks alive within `HEARTBEAT_INTERVAL_MS`.
243
+ */
244
+ export function startStageHeartbeat(handle, intervalMs = HEARTBEAT_STAGE_INTERVAL_MS) {
245
+ const timer = setInterval(() => {
246
+ handle.heartbeat();
247
+ }, Math.max(HEARTBEAT_INTERVAL_MS, intervalMs));
248
+ if (typeof timer.unref === 'function')
249
+ timer.unref();
250
+ return () => clearInterval(timer);
251
+ }
252
+ /** Age of the lock in milliseconds, or undefined when there is no lock. */
253
+ export function lockAgeMs(paths, now = Date.now()) {
254
+ const record = readLock(paths);
255
+ if (!record)
256
+ return undefined;
257
+ const beat = Date.parse(record.heartbeatAt);
258
+ if (!Number.isFinite(beat))
259
+ return undefined;
260
+ return Math.max(0, now - beat);
261
+ }
262
+ /** Size of the lock file, used by the `/index status` self-check to catch a truncated write. */
263
+ export function lockFileSize(paths) {
264
+ try {
265
+ return statSync(paths.lockFile).size;
266
+ }
267
+ catch {
268
+ return 0;
269
+ }
270
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Stage 3 PARSE (spec 5.3): read, hash and scan files in a bounded pool.
3
+ *
4
+ * THREE PROPERTIES THIS STAGE OWNS:
5
+ *
6
+ * 1. A bad file never stops the build. Oversize, unreadable, timed out: each one
7
+ * becomes a row with a `status`, and the run continues (spec 5.3 failure
8
+ * semantics: "does not interrupt the whole build").
9
+ * 2. Workers never write. They return pure `FileFacts`; COMMIT is the only writer,
10
+ * which is what keeps four workers from interleaving rows in one directory.
11
+ * 3. The abort signal is checked at every batch boundary, and a heartbeat is sent
12
+ * per batch. That pairing is why `Esc` stops within one batch instead of
13
+ * finishing the whole workspace (spec 5.9 / R11).
14
+ *
15
+ * ASCII ONLY: inside the glyph scanner's scope.
16
+ */
17
+ import type { DiscoveredFile } from './discover.js';
18
+ import type { FileFacts } from './types.js';
19
+ /** Outcome of one parse batch, as the engine reports it to the panel. */
20
+ export interface ParseBatchReport {
21
+ /** Files parsed so far, across batches. */
22
+ readonly done: number;
23
+ /** Files this run must parse in total. */
24
+ readonly total: number;
25
+ /** Symbols found so far. */
26
+ readonly symbols: number;
27
+ /** Files that failed (timeout/large/error/partial). */
28
+ readonly failures: number;
29
+ /** Path most recently finished, for the panel's `current file` line. */
30
+ readonly lastPath: string;
31
+ }
32
+ /** Everything the pool needs from its caller. */
33
+ export interface ParseOptions {
34
+ /** Files to parse. */
35
+ readonly files: readonly DiscoveredFile[];
36
+ /** Per-file byte ceiling; above it the file is recorded as `large` and not read. */
37
+ readonly maxFileBytes: number;
38
+ /** Aborting stops at the next batch boundary. */
39
+ readonly signal: AbortSignal;
40
+ /** Called once per batch with a monotonic report. */
41
+ readonly onBatch?: (report: ParseBatchReport) => void;
42
+ /** Called per completed file, so a caller can feed the ETA window. */
43
+ readonly onFile?: (facts: FileFacts) => void;
44
+ /** Pool size override; defaults to `concurrencyFor(cpus)`. */
45
+ readonly concurrency?: number;
46
+ /** True when memory pressure was observed: halves the pool (spec 5.7). */
47
+ readonly degrade?: boolean;
48
+ }
49
+ /** Hash a buffer as `sha1:<hex>`; the prefix makes the format self-describing in the artifact. */
50
+ export declare function hashContent(buffer: Buffer): string;
51
+ /**
52
+ * Read and parse one file. Exported for the scanner tests, which assert exact
53
+ * line numbers on a fixture without spinning up a pool.
54
+ */
55
+ export declare function parseOne(file: DiscoveredFile, maxFileBytes: number): FileFacts;
56
+ /**
57
+ * Parse every file in `options.files`.
58
+ *
59
+ * The pool is a simple worker loop over a shared index: `count` workers pull the
60
+ * next file, so a slow file cannot block a whole chunk and the batch callback
61
+ * still fires in file order of completion. Files are independent, so no ordering
62
+ * guarantee is needed - the results are sorted by the caller before COMMIT.
63
+ */
64
+ export declare function parseFiles(options: ParseOptions): Promise<FileFacts[]>;
65
+ /** Aggregate the failure histogram COMMIT writes into `meta.json`. */
66
+ export declare function failureHistogram(facts: readonly FileFacts[]): Record<'timeout' | 'large' | 'error' | 'partial', number>;
67
+ /** Language histogram for `meta.json`. */
68
+ export declare function languageHistogram(facts: readonly FileFacts[]): Record<string, number>;
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Stage 3 PARSE (spec 5.3): read, hash and scan files in a bounded pool.
3
+ *
4
+ * THREE PROPERTIES THIS STAGE OWNS:
5
+ *
6
+ * 1. A bad file never stops the build. Oversize, unreadable, timed out: each one
7
+ * becomes a row with a `status`, and the run continues (spec 5.3 failure
8
+ * semantics: "does not interrupt the whole build").
9
+ * 2. Workers never write. They return pure `FileFacts`; COMMIT is the only writer,
10
+ * which is what keeps four workers from interleaving rows in one directory.
11
+ * 3. The abort signal is checked at every batch boundary, and a heartbeat is sent
12
+ * per batch. That pairing is why `Esc` stops within one batch instead of
13
+ * finishing the whole workspace (spec 5.9 / R11).
14
+ *
15
+ * ASCII ONLY: inside the glyph scanner's scope.
16
+ */
17
+ import { createHash } from 'node:crypto';
18
+ import { readFileSync } from 'node:fs';
19
+ import { cpus as cpusImpl } from 'node:os';
20
+ import { parseFile } from './scanner/extract.js';
21
+ import { HEARTBEAT_BATCH_FILES, FILE_TIMEOUT_MS, concurrencyFor } from './limits.js';
22
+ /** Hash a buffer as `sha1:<hex>`; the prefix makes the format self-describing in the artifact. */
23
+ export function hashContent(buffer) {
24
+ return `sha1:${createHash('sha1').update(buffer).digest('hex')}`;
25
+ }
26
+ /** Facts for a file that was never read, so the row still exists and says why. */
27
+ function unreadableFacts(file, status, reason) {
28
+ return {
29
+ path: file.path,
30
+ lang: 'other',
31
+ bytes: file.bytes,
32
+ sha1: '',
33
+ lines: 0,
34
+ status,
35
+ parseMs: 0,
36
+ symbols: [],
37
+ refs: [],
38
+ imports: [],
39
+ };
40
+ }
41
+ /**
42
+ * Read and parse one file. Exported for the scanner tests, which assert exact
43
+ * line numbers on a fixture without spinning up a pool.
44
+ */
45
+ export function parseOne(file, maxFileBytes) {
46
+ if (file.bytes > maxFileBytes) {
47
+ return unreadableFacts(file, 'large', `file is ${file.bytes} bytes, above the ${maxFileBytes} byte limit`);
48
+ }
49
+ let buffer;
50
+ try {
51
+ buffer = readFileSync(file.absolute);
52
+ }
53
+ catch (error) {
54
+ const cause = error instanceof Error ? error.message : String(error);
55
+ return unreadableFacts(file, 'error', cause);
56
+ }
57
+ try {
58
+ return parseFile({
59
+ path: file.path,
60
+ source: buffer.toString('utf8'),
61
+ bytes: file.bytes,
62
+ sha1: hashContent(buffer),
63
+ extension: file.extension,
64
+ });
65
+ }
66
+ catch (error) {
67
+ const cause = error instanceof Error ? error.message : String(error);
68
+ return { ...unreadableFacts(file, 'error', cause), sha1: hashContent(buffer) };
69
+ }
70
+ }
71
+ /**
72
+ * Parse every file in `options.files`.
73
+ *
74
+ * The pool is a simple worker loop over a shared index: `count` workers pull the
75
+ * next file, so a slow file cannot block a whole chunk and the batch callback
76
+ * still fires in file order of completion. Files are independent, so no ordering
77
+ * guarantee is needed - the results are sorted by the caller before COMMIT.
78
+ */
79
+ export async function parseFiles(options) {
80
+ const total = options.files.length;
81
+ const concurrency = Math.max(1, options.concurrency ?? concurrencyFor(cpus(), options.degrade === true));
82
+ const results = new Array(total);
83
+ let next = 0;
84
+ let done = 0;
85
+ let symbols = 0;
86
+ let failures = 0;
87
+ let lastPath = '';
88
+ let sinceBatch = 0;
89
+ const emit = () => {
90
+ sinceBatch = 0;
91
+ options.onBatch?.({ done, total, symbols, failures, lastPath });
92
+ };
93
+ const worker = async () => {
94
+ for (;;) {
95
+ const index = next;
96
+ next += 1;
97
+ if (index >= total)
98
+ return;
99
+ if (options.signal.aborted)
100
+ return;
101
+ const file = options.files[index];
102
+ const facts = await withTimeout(parseOne(file, options.maxFileBytes), FILE_TIMEOUT_MS, file);
103
+ results[index] = facts;
104
+ done += 1;
105
+ sinceBatch += 1;
106
+ symbols += facts.symbols.length;
107
+ if (facts.status !== 'ok')
108
+ failures += 1;
109
+ lastPath = facts.path;
110
+ options.onFile?.(facts);
111
+ if (sinceBatch >= HEARTBEAT_BATCH_FILES)
112
+ emit();
113
+ }
114
+ };
115
+ const workers = [];
116
+ for (let i = 0; i < Math.min(concurrency, Math.max(1, total)); i += 1)
117
+ workers.push(worker());
118
+ await Promise.all(workers);
119
+ emit();
120
+ // A cancelled run leaves holes in the result array; the engine discards the
121
+ // whole run, so holes are filtered rather than filled with fake rows.
122
+ return results.filter((facts) => facts !== undefined);
123
+ }
124
+ /** Race a parse against the per-file budget, resolving (never rejecting) with a timeout row. */
125
+ async function withTimeout(work, ms, file) {
126
+ // Parsing is synchronous, so the race is really a guard around scheduling:
127
+ // a file that already took longer than the budget is reported as `timeout`
128
+ // instead of being allowed to inflate the batch's wall-clock silently.
129
+ const started = Date.now();
130
+ const facts = work;
131
+ const elapsed = facts.parseMs > 0 ? facts.parseMs : Date.now() - started;
132
+ if (elapsed > ms && facts.status === 'ok') {
133
+ return { ...facts, status: 'timeout' };
134
+ }
135
+ return facts;
136
+ }
137
+ /** `os.cpus()` with a fallback: some sandboxes throw instead of returning a list. */
138
+ function cpus() {
139
+ try {
140
+ return cpusImpl().length;
141
+ }
142
+ catch {
143
+ return 2;
144
+ }
145
+ }
146
+ /** Aggregate the failure histogram COMMIT writes into `meta.json`. */
147
+ export function failureHistogram(facts) {
148
+ const histogram = { timeout: 0, large: 0, error: 0, partial: 0 };
149
+ for (const file of facts) {
150
+ if (file.status === 'ok')
151
+ continue;
152
+ histogram[file.status] += 1;
153
+ }
154
+ return histogram;
155
+ }
156
+ /** Language histogram for `meta.json`. */
157
+ export function languageHistogram(facts) {
158
+ const histogram = {};
159
+ for (const file of facts) {
160
+ histogram[file.lang] = (histogram[file.lang] ?? 0) + 1;
161
+ }
162
+ return histogram;
163
+ }