@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,277 @@
1
+ /**
2
+ * TS / TSX / JS declaration extraction on masked text (spec 5.8 layer 2).
3
+ *
4
+ * WHAT THIS IS NOT: a TypeScript parser. It never builds a tree, never resolves
5
+ * types, and never guesses at a construct it cannot see. It walks the masked
6
+ * source line by line with a brace-depth counter and a small scope stack, which
7
+ * is enough to answer the three questions the index exists for: what is declared,
8
+ * where does it start and end, and what is it declared inside.
9
+ *
10
+ * THE HONESTY RULE (spec R1): anything uncertain downgrades instead of guessing.
11
+ * A duplicate qualified name becomes `name#2` and marks the file `partial`; an
12
+ * unterminated comment or template marks it `partial`; a line the pattern table
13
+ * cannot classify is simply not a symbol. `partial` is a signal the model sees,
14
+ * so a wrong guess would be worse than a gap.
15
+ *
16
+ * ALL STATE IS LOCAL TO ONE CALL. The parser runs in a concurrency pool, so a
17
+ * module-level scope stack would let two files corrupt each other's `el` ranges.
18
+ *
19
+ * ASCII ONLY: inside the glyph scanner's scope.
20
+ */
21
+ import { maskSource } from './mask.js';
22
+ /** Longest signature kept per symbol; the extra characters never earn their bytes. */
23
+ const SIGNATURE_MAX = 160;
24
+ /**
25
+ * Declarations, most specific first. `export`/`declare`/`abstract`/`async` are
26
+ * removed by `stripModifiers` before matching, so each pattern stays simple.
27
+ */
28
+ const DECLARATIONS = [
29
+ { regex: /^class\s+([A-Za-z_$][\w$]*)/, kind: 'class', opensScope: true },
30
+ { regex: /^interface\s+([A-Za-z_$][\w$]*)/, kind: 'interface', opensScope: true },
31
+ { regex: /^type\s+([A-Za-z_$][\w$]*)\s*[=<]/, kind: 'type', opensScope: false },
32
+ { regex: /^(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)/, kind: 'enum', opensScope: true },
33
+ { regex: /^function\s*\*?\s*([A-Za-z_$][\w$]*)\s*[(<]/, kind: 'function', opensScope: true },
34
+ { regex: /^namespace\s+([A-Za-z_$][\w$]*)/, kind: 'namespace', opensScope: true },
35
+ // A TS `module X {}` block IS a namespace: the web vocabulary has no `module` word, and a
36
+ // second word for the same construct is exactly the drift the vocabulary gate forbids.
37
+ { regex: /^module\s+([A-Za-z_$][\w$]*)/, kind: 'namespace', opensScope: true },
38
+ { regex: /^const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\(|function\b|<)/, kind: 'function', opensScope: true },
39
+ { regex: /^let\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\(|function\b)/, kind: 'function', opensScope: true },
40
+ { regex: /^const\s+([A-Za-z_$][\w$]*)\s*[:=]/, kind: 'constant', opensScope: false },
41
+ { regex: /^let\s+([A-Za-z_$][\w$]*)\s*[:=]/, kind: 'variable', opensScope: false },
42
+ { regex: /^var\s+([A-Za-z_$][\w$]*)\s*[:=]/, kind: 'variable', opensScope: false },
43
+ ];
44
+ /** Class-like bodies whose members we record. */
45
+ const MEMBER_OWNERS = new Set(['class', 'interface', 'enum', 'namespace']);
46
+ /** Class/interface members: accessor, method, property. Order matters. */
47
+ const MEMBERS = [
48
+ { regex: /^(?:static\s+)?(?:async\s+)?(?:get|set)\s+([A-Za-z_$#][\w$]*)\s*\(/, kind: 'property' },
49
+ { regex: /^(?:static\s+)?(?:async\s+)?#?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(/, kind: 'method' },
50
+ { regex: /^(?:static\s+)?(?:readonly\s+)?#?([A-Za-z_$][\w$]*)\s*[?!]?\s*[:=]/, kind: 'property' },
51
+ ];
52
+ /** Words that make a class-body-looking line a statement instead of a member. */
53
+ const NOT_A_MEMBER = new Set([
54
+ 'if', 'for', 'while', 'switch', 'catch', 'return', 'new', 'await', 'throw', 'typeof',
55
+ 'delete', 'function', 'const', 'let', 'var', 'else', 'do', 'try', 'case', 'super', 'this',
56
+ ]);
57
+ /** Strip leading modifiers so one pattern table covers `export default abstract class`. */
58
+ function stripModifiers(line) {
59
+ let text = line.trim();
60
+ for (let guard = 0; guard < 6; guard += 1) {
61
+ const before = text;
62
+ text = text.replace(/^(?:export|default|declare|abstract|async|public|protected|private|static|readonly)\s+/, '');
63
+ if (text === before)
64
+ break;
65
+ }
66
+ return text;
67
+ }
68
+ /** True when the raw line carries an `export` prefix (any form). */
69
+ function isExported(rawLine) {
70
+ return /^\s*export\b/.test(rawLine);
71
+ }
72
+ /** Visibility word, or undefined when the language default applies. */
73
+ function visibilityOf(rawLine) {
74
+ const match = /^\s*(?:export\s+)?(?:declare\s+)?(public|protected|private)\b/.exec(rawLine);
75
+ return match ? match[1] : undefined;
76
+ }
77
+ /** Net brace balance of a masked line. Masking already removed braces inside literals. */
78
+ function braceDelta(maskedLine) {
79
+ let delta = 0;
80
+ for (const ch of maskedLine) {
81
+ if (ch === '{')
82
+ delta += 1;
83
+ else if (ch === '}')
84
+ delta -= 1;
85
+ }
86
+ return delta;
87
+ }
88
+ /**
89
+ * Extract declarations and imports from one source file.
90
+ *
91
+ * `path` is written into every row so the artifact needs no second pass to
92
+ * attribute a row to a file.
93
+ */
94
+ export function extractTs(source, lang, path) {
95
+ const { masked, unterminated } = maskSource(source);
96
+ const maskedRows = masked.split('\n');
97
+ const rawRows = source.split('\n');
98
+ const symbols = [];
99
+ const imports = [];
100
+ const usedQualified = new Map();
101
+ const scopes = [];
102
+ let depth = 0;
103
+ let partial = unterminated;
104
+ for (let index = 0; index < maskedRows.length; index += 1) {
105
+ const maskedLine = maskedRows[index];
106
+ const rawLine = rawRows[index] ?? '';
107
+ const lineNo = index + 1;
108
+ // Close every scope we have stepped out of before classifying this line.
109
+ while (scopes.length > 0 && depth < scopes[scopes.length - 1].memberDepth) {
110
+ const closed = scopes.pop();
111
+ if (closed)
112
+ closeSymbol(symbols, closed, lineNo - 1);
113
+ }
114
+ if (maskedLine.trim() !== '') {
115
+ collectImport(maskedLine, rawLine, lineNo, path, imports);
116
+ const opened = tryDeclaration(maskedLine, rawLine, lineNo, depth, scopes, symbols, usedQualified, path);
117
+ if (!opened)
118
+ tryMember(maskedLine, rawLine, lineNo, depth, scopes, symbols, usedQualified, path);
119
+ }
120
+ depth += braceDelta(maskedLine);
121
+ if (depth < 0) {
122
+ partial = true;
123
+ depth = 0;
124
+ }
125
+ }
126
+ for (const open of scopes)
127
+ closeSymbol(symbols, open, maskedRows.length);
128
+ return { symbols, imports, lines: maskedRows.length, partial };
129
+ }
130
+ /** Append one symbol row, resolving a duplicate qualified name with a `#n` suffix. */
131
+ function pushSymbol(symbols, usedQualified, row) {
132
+ const seen = usedQualified.get(row.q) ?? 0;
133
+ usedQualified.set(row.q, seen + 1);
134
+ const qualified = seen === 0 ? row.q : `${row.q}#${seen + 1}`;
135
+ symbols.push({ ...row, q: qualified, el: row.ln, fl: 0, r: 0 });
136
+ return symbols.length - 1;
137
+ }
138
+ /** Fill `el` when a scope closes, so a class spans from its header to its last member. */
139
+ function closeSymbol(symbols, scope, endLine) {
140
+ const target = symbols[scope.symbolIndex];
141
+ if (!target || endLine <= target.el)
142
+ return;
143
+ symbols[scope.symbolIndex] = { ...target, el: endLine };
144
+ }
145
+ /**
146
+ * Try the declaration table on one line. Returns true when a declaration was
147
+ * recorded; the caller then does not look for a member on the same line.
148
+ */
149
+ function tryDeclaration(maskedLine, rawLine, lineNo, depth, scopes, symbols, usedQualified, path) {
150
+ const text = stripModifiers(maskedLine);
151
+ if (text === '')
152
+ return false;
153
+ const parent = scopes.length > 0 ? scopes[scopes.length - 1].qualified : undefined;
154
+ for (const pattern of DECLARATIONS) {
155
+ const match = pattern.regex.exec(text);
156
+ const name = match?.[1];
157
+ if (!name)
158
+ continue;
159
+ const qualified = parent ? `${parent}.${name}` : name;
160
+ const symbolIndex = pushSymbol(symbols, usedQualified, {
161
+ f: path,
162
+ n: name,
163
+ q: qualified,
164
+ k: pattern.kind,
165
+ ln: lineNo,
166
+ x: isExported(rawLine),
167
+ v: visibilityOf(rawLine),
168
+ sg: rawLine.trim().slice(0, SIGNATURE_MAX),
169
+ pa: parent,
170
+ });
171
+ if (pattern.opensScope) {
172
+ scopes.push({ qualified, kind: pattern.kind, memberDepth: depth + 1, symbolIndex });
173
+ }
174
+ return true;
175
+ }
176
+ return false;
177
+ }
178
+ /** Try the member table when the innermost scope is a class-like body and we sit directly in it. */
179
+ function tryMember(maskedLine, rawLine, lineNo, depth, scopes, symbols, usedQualified, path) {
180
+ const scope = scopes[scopes.length - 1];
181
+ if (!scope || !MEMBER_OWNERS.has(scope.kind) || depth !== scope.memberDepth)
182
+ return;
183
+ const text = stripMemberModifiers(maskedLine.trim());
184
+ if (text === '' || text.startsWith('}') || text.startsWith('*') || text.startsWith('//'))
185
+ return;
186
+ for (const member of MEMBERS) {
187
+ const name = member.regex.exec(text)?.[1];
188
+ if (!name)
189
+ continue;
190
+ if (NOT_A_MEMBER.has(name))
191
+ return;
192
+ pushSymbol(symbols, usedQualified, {
193
+ f: path,
194
+ n: name,
195
+ q: `${scope.qualified}.${name}`,
196
+ k: member.kind,
197
+ ln: lineNo,
198
+ x: false,
199
+ v: visibilityOf(rawLine),
200
+ sg: rawLine.trim().slice(0, SIGNATURE_MAX),
201
+ pa: scope.qualified,
202
+ });
203
+ return;
204
+ }
205
+ }
206
+ /**
207
+ * Strip the member modifiers that are NOT part of the name, BEFORE the pattern table runs.
208
+ *
209
+ * WHY THIS EXISTS: `private count = ORIGIN;` matched the property pattern with `private` as
210
+ * the captured name, so the real member `count` vanished and a symbol called `private`
211
+ * appeared instead. A single mis-parsed member is worse than a missing one, because the
212
+ * former is silently plausible (spec R1). `static` / `get` / `set` / `async` are NOT
213
+ * stripped here: the patterns classify them, and removing them would lose the accessor case.
214
+ */
215
+ function stripMemberModifiers(text) {
216
+ let out = text;
217
+ for (let guard = 0; guard < 4; guard += 1) {
218
+ const before = out;
219
+ out = out.replace(/^(?:public|protected|private|readonly|declare|override)\s+/, '');
220
+ if (out === before)
221
+ break;
222
+ }
223
+ return out;
224
+ }
225
+ /**
226
+ * Parse one import-ish line into an `ImportRow`. Covers the four shapes the
227
+ * scanner cares about: static `import ... from 'x'`, side-effect `import 'x'`,
228
+ * `require('x')` and dynamic `import('x')`.
229
+ *
230
+ * The module specifier is read from the RAW line (it is a string literal, hence
231
+ * blanked in the masked text) while `require`/`import(` are found in the masked
232
+ * text so a `require('x')` mentioned inside a comment or string is not counted.
233
+ */
234
+ function collectImport(maskedLine, rawLine, lineNo, path, out) {
235
+ const staticFrom = /^\s*import\s+([^'"]+?)\s+from\s+['"]([^'"]+)['"]/.exec(rawLine);
236
+ if (staticFrom) {
237
+ out.push({ f: path, ln: lineNo, sp: staticFrom[2], k: 'static', nm: parseImportedNames(staticFrom[1]) });
238
+ return;
239
+ }
240
+ const sideEffect = /^\s*import\s+['"]([^'"]+)['"]/.exec(rawLine);
241
+ if (sideEffect) {
242
+ out.push({ f: path, ln: lineNo, sp: sideEffect[1], k: 'static', nm: [] });
243
+ return;
244
+ }
245
+ const required = /\brequire\s*\(/.test(maskedLine) ? /require\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(rawLine) : null;
246
+ if (required) {
247
+ out.push({ f: path, ln: lineNo, sp: required[1], k: 'require', nm: [] });
248
+ return;
249
+ }
250
+ const dynamic = /\bimport\s*\(/.test(maskedLine) ? /import\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(rawLine) : null;
251
+ if (dynamic) {
252
+ out.push({ f: path, ln: lineNo, sp: dynamic[1], k: 'dynamic', nm: [] });
253
+ }
254
+ }
255
+ /** Parse `{ a, b as c }`, `* as ns`, `default as d` and a bare default binding. */
256
+ function parseImportedNames(clause) {
257
+ const names = [];
258
+ const braces = /\{([^}]*)\}/.exec(clause);
259
+ if (braces) {
260
+ for (const part of braces[1].split(',')) {
261
+ const trimmed = part.trim();
262
+ if (trimmed === '')
263
+ continue;
264
+ const alias = /^(\S+)\s+as\s+(\S+)$/.exec(trimmed);
265
+ names.push(alias ? { i: alias[1], l: alias[2] } : { i: trimmed, l: trimmed });
266
+ }
267
+ }
268
+ const star = /\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(clause);
269
+ if (star)
270
+ names.push({ i: '*', l: star[1] });
271
+ if (!braces && !star) {
272
+ const bare = /^([A-Za-z_$][\w$]*)/.exec(clause.trim());
273
+ if (bare)
274
+ names.push({ i: 'default', l: bare[1] });
275
+ }
276
+ return names;
277
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Generation storage: writing a new generation, reading the current one, moving
3
+ * the pointer (spec 5.5 / I-2).
4
+ *
5
+ * THE ONE RULE THAT MATTERS: `current` is replaced LAST, after every table of the
6
+ * new generation has been written and fsynced, and it is replaced by writing a
7
+ * temp file and renaming it. That single ordering is why a failed, cancelled or
8
+ * `SIGKILL`ed build leaves the previous generation complete: there is no window
9
+ * in which the pointer names a half-written directory. Readers never inspect
10
+ * `generations/` timestamps - they read `current` - so an in-progress build is
11
+ * invisible by construction rather than by a status flag.
12
+ *
13
+ * ASCII ONLY: inside the glyph scanner's scope.
14
+ */
15
+ import { type IndexPaths } from './paths.js';
16
+ import type { CurrentPointer, FileGraph, FileRow, GenerationPayload, ImportRow, IndexMeta, RefRow, SymbolRow } from './types.js';
17
+ /** File names inside one generation directory. */
18
+ export declare const GENERATION_FILES: {
19
+ readonly meta: "meta.json";
20
+ readonly files: "files.jsonl";
21
+ readonly symbols: "symbols.jsonl";
22
+ readonly refs: "refs.jsonl";
23
+ readonly imports: "imports.jsonl";
24
+ readonly graph: "graph.json";
25
+ };
26
+ /** Marker file that pins a generation against cleanup (spec 5.5). */
27
+ export declare const KEEP_MARKER = "KEEP";
28
+ /** Everything a reader needs from one generation. */
29
+ export interface LoadedGeneration {
30
+ /** Parsed `meta.json`. */
31
+ readonly meta: IndexMeta;
32
+ /** Files table. */
33
+ readonly files: readonly FileRow[];
34
+ /** Symbols table. */
35
+ readonly symbols: readonly SymbolRow[];
36
+ /** References table. */
37
+ readonly refs: readonly RefRow[];
38
+ /** Imports table. */
39
+ readonly imports: readonly ImportRow[];
40
+ /** File graph. */
41
+ readonly graph: FileGraph;
42
+ }
43
+ /** Parse one JSONL file into rows, skipping blank lines. */
44
+ export declare function readJsonl<T>(path: string): T[];
45
+ /** Serialize rows as JSONL with a trailing newline (a missing newline breaks `cat file | wc -l`). */
46
+ export declare function toJsonl(rows: readonly unknown[]): string;
47
+ /** Read the `current` pointer. Returns null when absent or unreadable (both mean "no index"). */
48
+ export declare function readCurrentPointer(paths: IndexPaths): CurrentPointer | null;
49
+ /**
50
+ * Load the generation the pointer names.
51
+ *
52
+ * An unknown `schemaVersion` is answered with `E_INDEX_SCHEMA` rather than a
53
+ * best-effort read: guessing at a format this engine does not know is how an
54
+ * index starts returning wrong symbols (spec 7.4, same discipline as an unknown
55
+ * credential version reading as signed-out).
56
+ */
57
+ export declare function loadCurrent(paths: IndexPaths): LoadedGeneration | null;
58
+ /** Read only `meta.json` for the current generation: what `/index status` needs, without the tables. */
59
+ export declare function readCurrentMeta(paths: IndexPaths): IndexMeta | null;
60
+ /**
61
+ * Write a whole generation. Throws `E_INDEX_COMMIT` on any failure and removes
62
+ * the partial directory, so a retry starts clean and the old generation is the
63
+ * only thing readers can see.
64
+ *
65
+ * WRITE ORDER is fixed: four tables, then the graph, then meta. `meta.json` is
66
+ * the "this generation is complete" signal for diagnostics (readers still go
67
+ * through `current`), so it must be last.
68
+ */
69
+ export declare function writeGeneration(paths: IndexPaths, payload: GenerationPayload): string;
70
+ /**
71
+ * Move the pointer. This is the last write of a build (I-2); if it fails the
72
+ * build reports failure and the previous generation is still the current one.
73
+ */
74
+ export declare function commitPointer(paths: IndexPaths, generation: number): void;
75
+ /** Generation numbers present on disk, newest first. Non-numeric entries are ignored. */
76
+ export declare function listGenerations(paths: IndexPaths): number[];
77
+ /** Next generation number: current + 1, or 1 for a first build. Gaps are never reused. */
78
+ export declare function nextGeneration(paths: IndexPaths): number;
79
+ /**
80
+ * Delete old generations, keeping `keep` of the newest plus anything with a
81
+ * `KEEP` marker. Runs AFTER the pointer moved, and every failure is swallowed:
82
+ * a sticky directory is a disk-space problem, never a correctness problem.
83
+ */
84
+ export declare function pruneGenerations(paths: IndexPaths, keep: number, currentGeneration: number): number[];
85
+ /** Delete every generation and the pointer. Used by `/index clean` only. */
86
+ export declare function removeAllGenerations(paths: IndexPaths): void;
87
+ /** Write the `KEEP` marker so `/index clean` and pruning leave this generation alone. */
88
+ export declare function markKeep(paths: IndexPaths, generation: number): void;
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Generation storage: writing a new generation, reading the current one, moving
3
+ * the pointer (spec 5.5 / I-2).
4
+ *
5
+ * THE ONE RULE THAT MATTERS: `current` is replaced LAST, after every table of the
6
+ * new generation has been written and fsynced, and it is replaced by writing a
7
+ * temp file and renaming it. That single ordering is why a failed, cancelled or
8
+ * `SIGKILL`ed build leaves the previous generation complete: there is no window
9
+ * in which the pointer names a half-written directory. Readers never inspect
10
+ * `generations/` timestamps - they read `current` - so an in-progress build is
11
+ * invisible by construction rather than by a status flag.
12
+ *
13
+ * ASCII ONLY: inside the glyph scanner's scope.
14
+ */
15
+ import { randomUUID } from 'node:crypto';
16
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import { commitError, schemaError } from './errors.js';
19
+ import { generationDir } from './paths.js';
20
+ import { INDEX_SCHEMA_VERSION } from './types.js';
21
+ /** File names inside one generation directory. */
22
+ export const GENERATION_FILES = {
23
+ meta: 'meta.json',
24
+ files: 'files.jsonl',
25
+ symbols: 'symbols.jsonl',
26
+ refs: 'refs.jsonl',
27
+ imports: 'imports.jsonl',
28
+ graph: 'graph.json',
29
+ };
30
+ /** Marker file that pins a generation against cleanup (spec 5.5). */
31
+ export const KEEP_MARKER = 'KEEP';
32
+ /** Parse one JSONL file into rows, skipping blank lines. */
33
+ export function readJsonl(path) {
34
+ if (!existsSync(path))
35
+ return [];
36
+ const text = readFileSync(path, 'utf8');
37
+ const rows = [];
38
+ for (const line of text.split('\n')) {
39
+ const trimmed = line.trim();
40
+ if (trimmed === '')
41
+ continue;
42
+ rows.push(JSON.parse(trimmed));
43
+ }
44
+ return rows;
45
+ }
46
+ /** Serialize rows as JSONL with a trailing newline (a missing newline breaks `cat file | wc -l`). */
47
+ export function toJsonl(rows) {
48
+ if (rows.length === 0)
49
+ return '';
50
+ return `${rows.map((row) => JSON.stringify(row)).join('\n')}\n`;
51
+ }
52
+ /** Read the `current` pointer. Returns null when absent or unreadable (both mean "no index"). */
53
+ export function readCurrentPointer(paths) {
54
+ if (!existsSync(paths.currentFile))
55
+ return null;
56
+ try {
57
+ const parsed = JSON.parse(readFileSync(paths.currentFile, 'utf8'));
58
+ if (typeof parsed.generation !== 'number' || !Number.isFinite(parsed.generation))
59
+ return null;
60
+ return {
61
+ generation: parsed.generation,
62
+ schemaVersion: typeof parsed.schemaVersion === 'number' ? parsed.schemaVersion : 0,
63
+ };
64
+ }
65
+ catch {
66
+ // A truncated or hand-edited pointer is treated as "no index" and rebuilt on
67
+ // the next run; throwing here would break `/index status` for a user who
68
+ // never asked it to write anything.
69
+ return null;
70
+ }
71
+ }
72
+ /**
73
+ * Load the generation the pointer names.
74
+ *
75
+ * An unknown `schemaVersion` is answered with `E_INDEX_SCHEMA` rather than a
76
+ * best-effort read: guessing at a format this engine does not know is how an
77
+ * index starts returning wrong symbols (spec 7.4, same discipline as an unknown
78
+ * credential version reading as signed-out).
79
+ */
80
+ export function loadCurrent(paths) {
81
+ const pointer = readCurrentPointer(paths);
82
+ if (!pointer)
83
+ return null;
84
+ if (pointer.schemaVersion !== INDEX_SCHEMA_VERSION) {
85
+ throw schemaError(pointer.schemaVersion, INDEX_SCHEMA_VERSION);
86
+ }
87
+ const dir = generationDir(paths.generationsDir, pointer.generation);
88
+ const metaPath = join(dir, GENERATION_FILES.meta);
89
+ if (!existsSync(metaPath))
90
+ return null;
91
+ // AN UNREADABLE meta.json IS "NO INDEX", NOT A CRASH. A truncated one used to throw a raw
92
+ // SyntaxError that `loadPrevious` did not recognise, so every rebuild answered
93
+ // `E_INDEX_INTERNAL` forever while `/index status` recommended exactly that rebuild.
94
+ // Rebuilding is the cure, so this read must degrade to "nothing to reuse".
95
+ let meta;
96
+ try {
97
+ meta = JSON.parse(readFileSync(metaPath, 'utf8'));
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ if (!meta || typeof meta !== 'object')
103
+ return null;
104
+ if (meta.schemaVersion !== INDEX_SCHEMA_VERSION) {
105
+ throw schemaError(meta.schemaVersion, INDEX_SCHEMA_VERSION);
106
+ }
107
+ return {
108
+ meta,
109
+ files: readJsonl(join(dir, GENERATION_FILES.files)),
110
+ symbols: readJsonl(join(dir, GENERATION_FILES.symbols)),
111
+ refs: readJsonl(join(dir, GENERATION_FILES.refs)),
112
+ imports: readJsonl(join(dir, GENERATION_FILES.imports)),
113
+ graph: readJsonFile(join(dir, GENERATION_FILES.graph), { nodes: [], edges: [] }),
114
+ };
115
+ }
116
+ /** Read a JSON file with a fallback; a corrupt side table must not hide the main tables. */
117
+ function readJsonFile(path, fallback) {
118
+ if (!existsSync(path))
119
+ return fallback;
120
+ try {
121
+ return JSON.parse(readFileSync(path, 'utf8'));
122
+ }
123
+ catch {
124
+ return fallback;
125
+ }
126
+ }
127
+ /** Read only `meta.json` for the current generation: what `/index status` needs, without the tables. */
128
+ export function readCurrentMeta(paths) {
129
+ const pointer = readCurrentPointer(paths);
130
+ if (!pointer)
131
+ return null;
132
+ if (pointer.schemaVersion !== INDEX_SCHEMA_VERSION) {
133
+ throw schemaError(pointer.schemaVersion, INDEX_SCHEMA_VERSION);
134
+ }
135
+ const metaPath = join(paths.generationsDir, String(pointer.generation), GENERATION_FILES.meta);
136
+ if (!existsSync(metaPath))
137
+ return null;
138
+ try {
139
+ return JSON.parse(readFileSync(metaPath, 'utf8'));
140
+ }
141
+ catch {
142
+ return null;
143
+ }
144
+ }
145
+ /** Flush a directory entry where the platform allows it; Windows refuses and that is fine. */
146
+ function fsyncDirBestEffort(dir) {
147
+ if (process.platform === 'win32')
148
+ return;
149
+ let handle;
150
+ try {
151
+ handle = openSync(dir, 'r');
152
+ fsyncSync(handle);
153
+ }
154
+ catch {
155
+ // Documented degradation (spec R3): NTFS rename is atomic on its own, and a
156
+ // platform that refuses a directory fsync cannot be given a stronger promise.
157
+ }
158
+ finally {
159
+ if (handle !== undefined)
160
+ closeSync(handle);
161
+ }
162
+ }
163
+ /**
164
+ * Write one file through a temp file and a rename, then fsync the directory.
165
+ * `rename` is atomic on every platform this ships to, which is what makes a
166
+ * partially written table impossible to observe.
167
+ */
168
+ function writeFileAtomic(dir, name, content) {
169
+ const target = join(dir, name);
170
+ // A UNIQUE temp name, never a fixed `<target>.tmp`: two writers sharing one temp path
171
+ // rename each other's bytes, which can leave one generation holding `files.jsonl` from
172
+ // one run beside `symbols.jsonl` from another - and the pointer move then blesses it.
173
+ const temp = `${target}.${process.pid}.${randomUUID()}.tmp`;
174
+ writeFileSync(temp, content, 'utf8');
175
+ try {
176
+ renameSync(temp, target);
177
+ }
178
+ catch (error) {
179
+ // Only OUR temp path is eligible: a failed rename must not leave scratch files behind.
180
+ try {
181
+ rmSync(temp, { force: true });
182
+ }
183
+ catch { /* best effort */ }
184
+ throw error;
185
+ }
186
+ }
187
+ /**
188
+ * Write a whole generation. Throws `E_INDEX_COMMIT` on any failure and removes
189
+ * the partial directory, so a retry starts clean and the old generation is the
190
+ * only thing readers can see.
191
+ *
192
+ * WRITE ORDER is fixed: four tables, then the graph, then meta. `meta.json` is
193
+ * the "this generation is complete" signal for diagnostics (readers still go
194
+ * through `current`), so it must be last.
195
+ */
196
+ export function writeGeneration(paths, payload) {
197
+ const dir = generationDir(paths.generationsDir, payload.meta.generation);
198
+ try {
199
+ rmSync(dir, { recursive: true, force: true });
200
+ mkdirRecursive(dir);
201
+ writeFileAtomic(dir, GENERATION_FILES.files, toJsonl(payload.files));
202
+ writeFileAtomic(dir, GENERATION_FILES.symbols, toJsonl(payload.symbols));
203
+ writeFileAtomic(dir, GENERATION_FILES.refs, toJsonl(payload.refs));
204
+ writeFileAtomic(dir, GENERATION_FILES.imports, toJsonl(payload.imports));
205
+ writeFileAtomic(dir, GENERATION_FILES.graph, JSON.stringify(payload.graph));
206
+ writeFileAtomic(dir, GENERATION_FILES.meta, JSON.stringify(payload.meta, null, 2));
207
+ fsyncDirBestEffort(dir);
208
+ return dir;
209
+ }
210
+ catch (error) {
211
+ const cause = error instanceof Error ? error.message : String(error);
212
+ try {
213
+ rmSync(dir, { recursive: true, force: true });
214
+ }
215
+ catch {
216
+ // The cleanup is best effort: the pointer was never moved, so readers are
217
+ // unaffected even if a stray directory survives.
218
+ }
219
+ throw commitError(cause);
220
+ }
221
+ }
222
+ /** `mkdirSync` wrapper kept separate so the write path reads as a sequence of steps. */
223
+ function mkdirRecursive(dir) {
224
+ mkdirSync(dir, { recursive: true });
225
+ }
226
+ /**
227
+ * Move the pointer. This is the last write of a build (I-2); if it fails the
228
+ * build reports failure and the previous generation is still the current one.
229
+ */
230
+ export function commitPointer(paths, generation) {
231
+ const content = JSON.stringify({ generation, schemaVersion: INDEX_SCHEMA_VERSION });
232
+ const temp = `${paths.currentFile}.${process.pid}.${randomUUID()}.tmp`;
233
+ try {
234
+ writeFileSync(temp, content, 'utf8');
235
+ renameSync(temp, paths.currentFile);
236
+ fsyncDirBestEffort(paths.astDir);
237
+ }
238
+ catch (error) {
239
+ const cause = error instanceof Error ? error.message : String(error);
240
+ throw commitError(cause);
241
+ }
242
+ }
243
+ /** Generation numbers present on disk, newest first. Non-numeric entries are ignored. */
244
+ export function listGenerations(paths) {
245
+ if (!existsSync(paths.generationsDir))
246
+ return [];
247
+ const entries = readdirSync(paths.generationsDir);
248
+ const numbers = [];
249
+ for (const entry of entries) {
250
+ const parsed = Number.parseInt(entry, 10);
251
+ if (!Number.isFinite(parsed) || String(parsed) !== entry)
252
+ continue;
253
+ numbers.push(parsed);
254
+ }
255
+ return numbers.sort((a, b) => b - a);
256
+ }
257
+ /** Next generation number: current + 1, or 1 for a first build. Gaps are never reused. */
258
+ export function nextGeneration(paths) {
259
+ const pointer = readCurrentPointer(paths);
260
+ const onDisk = listGenerations(paths);
261
+ const highest = onDisk.length > 0 ? Math.max(onDisk[0], pointer?.generation ?? 0) : (pointer?.generation ?? 0);
262
+ return highest + 1;
263
+ }
264
+ /**
265
+ * Delete old generations, keeping `keep` of the newest plus anything with a
266
+ * `KEEP` marker. Runs AFTER the pointer moved, and every failure is swallowed:
267
+ * a sticky directory is a disk-space problem, never a correctness problem.
268
+ */
269
+ export function pruneGenerations(paths, keep, currentGeneration) {
270
+ const removed = [];
271
+ const candidates = listGenerations(paths).filter((generation) => generation !== currentGeneration);
272
+ const protectedCount = Math.max(0, keep - 1);
273
+ for (let index = protectedCount; index < candidates.length; index += 1) {
274
+ const generation = candidates[index];
275
+ const dir = generationDir(paths.generationsDir, generation);
276
+ if (existsSync(join(dir, KEEP_MARKER)))
277
+ continue;
278
+ try {
279
+ rmSync(dir, { recursive: true, force: true });
280
+ removed.push(generation);
281
+ }
282
+ catch {
283
+ // Best effort: see the docstring.
284
+ }
285
+ }
286
+ return removed;
287
+ }
288
+ /** Delete every generation and the pointer. Used by `/index clean` only. */
289
+ export function removeAllGenerations(paths) {
290
+ try {
291
+ rmSync(paths.generationsDir, { recursive: true, force: true });
292
+ }
293
+ catch {
294
+ // Reported by the caller through `status()` reading `present === true` again.
295
+ }
296
+ try {
297
+ rmSync(paths.currentFile, { force: true });
298
+ }
299
+ catch {
300
+ // Same.
301
+ }
302
+ }
303
+ /** Write the `KEEP` marker so `/index clean` and pruning leave this generation alone. */
304
+ export function markKeep(paths, generation) {
305
+ const dir = generationDir(paths.generationsDir, generation);
306
+ if (!existsSync(dir))
307
+ return;
308
+ writeFileSync(join(dir, KEEP_MARKER), `pinned ${new Date().toISOString()}\n`, 'utf8');
309
+ }