@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,62 @@
1
+ /**
2
+ * Stable error codes for the index engine (spec 7.5).
3
+ *
4
+ * These codes are a PUBLIC contract: `/index`, the host bridge, the desktop app
5
+ * and the tests all branch on them, so renaming one is a breaking change and
6
+ * needs a changelog entry. The code carries the diagnosis; the message carries
7
+ * the sentence a human reads, and every message names where it happened and
8
+ * what the user can do next.
9
+ *
10
+ * ASCII ONLY: `indexer/**` is inside the glyph scanner's scope.
11
+ */
12
+ import type { IndexErrorCode } from '@aragon-agent/tui/model/index-build/types';
13
+ /** Re-exported so callers inside the engine need one import, not two. */
14
+ export type { IndexErrorCode };
15
+ /**
16
+ * One engine failure. Extends Error so an unexpected `throw` still behaves, but
17
+ * every intentional failure is constructed through the helpers below, which is
18
+ * what keeps the code set small and the messages consistent.
19
+ */
20
+ export declare class IndexError extends Error {
21
+ /** Stable code from spec 7.5. */
22
+ readonly code: IndexErrorCode;
23
+ /** Optional run id, so a log search can find the whole build. */
24
+ readonly runId?: string;
25
+ constructor(code: IndexErrorCode, message: string, runId?: string);
26
+ }
27
+ /** True when `value` is an `IndexError` (works across the ESM boundary). */
28
+ export declare function isIndexError(value: unknown): value is IndexError;
29
+ /**
30
+ * Narrow any thrown value into a code + message pair. Cancellation and index
31
+ * failures keep their identity; anything else becomes `E_INDEX_INTERNAL` with
32
+ * the `runId` attached, because "something broke" without an id is unsearchable.
33
+ */
34
+ export declare function toIndexFailure(error: unknown, runId?: string): {
35
+ code: IndexErrorCode;
36
+ message: string;
37
+ };
38
+ /** `index.enabled === false`: nothing is built, queried or injected. */
39
+ export declare function disabledError(): IndexError;
40
+ /**
41
+ * Another process holds the writer lock. This is NOT a refusal to show: the
42
+ * caller is expected to display the holder's live progress instead (spec 7.5).
43
+ */
44
+ export declare function busyError(holder: {
45
+ pid: number;
46
+ host: string;
47
+ generation?: number;
48
+ }): IndexError;
49
+ /** Both `git ls-files` and the filesystem walk failed: name the root. */
50
+ export declare function discoverError(root: string, cause: string): IndexError;
51
+ /** The workspace is larger than `index.maxFiles`: quote the limit and the way out. */
52
+ export declare function tooLargeError(found: number, limit: number): IndexError;
53
+ /** The artifact directory is not writable: name the directory, not the error code. */
54
+ export declare function unwritableError(dir: string, cause: string): IndexError;
55
+ /** The heartbeat failed repeatedly: assume another writer took over and stop writing. */
56
+ export declare function lockLostError(): IndexError;
57
+ /** Writing the new generation failed. The previous index is still the one on disk. */
58
+ export declare function commitError(cause: string): IndexError;
59
+ /** `schemaVersion` on disk is not one this engine understands: rebuild, do not guess. */
60
+ export declare function schemaError(found: unknown, expected: number): IndexError;
61
+ /** The user cancelled: the message states the invariant that matters. */
62
+ export declare function cancelledError(): IndexError;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Stable error codes for the index engine (spec 7.5).
3
+ *
4
+ * These codes are a PUBLIC contract: `/index`, the host bridge, the desktop app
5
+ * and the tests all branch on them, so renaming one is a breaking change and
6
+ * needs a changelog entry. The code carries the diagnosis; the message carries
7
+ * the sentence a human reads, and every message names where it happened and
8
+ * what the user can do next.
9
+ *
10
+ * ASCII ONLY: `indexer/**` is inside the glyph scanner's scope.
11
+ */
12
+ /**
13
+ * One engine failure. Extends Error so an unexpected `throw` still behaves, but
14
+ * every intentional failure is constructed through the helpers below, which is
15
+ * what keeps the code set small and the messages consistent.
16
+ */
17
+ export class IndexError extends Error {
18
+ /** Stable code from spec 7.5. */
19
+ code;
20
+ /** Optional run id, so a log search can find the whole build. */
21
+ runId;
22
+ constructor(code, message, runId) {
23
+ super(message);
24
+ this.name = 'IndexError';
25
+ this.code = code;
26
+ this.runId = runId;
27
+ }
28
+ }
29
+ /** True when `value` is an `IndexError` (works across the ESM boundary). */
30
+ export function isIndexError(value) {
31
+ return value instanceof IndexError || (typeof value === 'object' && value !== null && value.name === 'IndexError');
32
+ }
33
+ /**
34
+ * Narrow any thrown value into a code + message pair. Cancellation and index
35
+ * failures keep their identity; anything else becomes `E_INDEX_INTERNAL` with
36
+ * the `runId` attached, because "something broke" without an id is unsearchable.
37
+ */
38
+ export function toIndexFailure(error, runId) {
39
+ if (isIndexError(error))
40
+ return { code: error.code, message: error.message };
41
+ if (error instanceof Error) {
42
+ return { code: 'E_INDEX_INTERNAL', message: `${error.message}${runId ? ` (run ${runId})` : ''}` };
43
+ }
44
+ return { code: 'E_INDEX_INTERNAL', message: `Unexpected failure: ${String(error)}${runId ? ` (run ${runId})` : ''}` };
45
+ }
46
+ /** `index.enabled === false`: nothing is built, queried or injected. */
47
+ export function disabledError() {
48
+ return new IndexError('E_INDEX_DISABLED', 'The project index is off. Run /index on to enable it.');
49
+ }
50
+ /**
51
+ * Another process holds the writer lock. This is NOT a refusal to show: the
52
+ * caller is expected to display the holder's live progress instead (spec 7.5).
53
+ */
54
+ export function busyError(holder) {
55
+ const where = holder.host ? ` on ${holder.host}` : '';
56
+ const target = holder.generation !== undefined ? ` (writing generation ${holder.generation})` : '';
57
+ return new IndexError('E_INDEX_BUSY', `Another process is building the index (pid ${holder.pid}${where})${target}. Press Ctrl+I to watch it.`);
58
+ }
59
+ /** Both `git ls-files` and the filesystem walk failed: name the root. */
60
+ export function discoverError(root, cause) {
61
+ return new IndexError('E_INDEX_DISCOVER', `Could not list the files under ${root}: ${cause}. Check that the directory is readable.`);
62
+ }
63
+ /** The workspace is larger than `index.maxFiles`: quote the limit and the way out. */
64
+ export function tooLargeError(found, limit) {
65
+ return new IndexError('E_INDEX_TOO_LARGE', `This workspace has ${found} indexable files, above the limit of ${limit}. Narrow it with index.exclude or raise index.maxFiles.`);
66
+ }
67
+ /** The artifact directory is not writable: name the directory, not the error code. */
68
+ export function unwritableError(dir, cause) {
69
+ return new IndexError('E_INDEX_UNWRITABLE', `Cannot write the index under ${dir}: ${cause}. Fix the permissions or point the workspace elsewhere.`);
70
+ }
71
+ /** The heartbeat failed repeatedly: assume another writer took over and stop writing. */
72
+ export function lockLostError() {
73
+ return new IndexError('E_INDEX_LOCK_LOST', 'Lost the index build lock (another process took over). This build stopped without touching the previous index.');
74
+ }
75
+ /** Writing the new generation failed. The previous index is still the one on disk. */
76
+ export function commitError(cause) {
77
+ return new IndexError('E_INDEX_COMMIT', `Could not write the new index generation: ${cause}. The previous index was not modified.`);
78
+ }
79
+ /** `schemaVersion` on disk is not one this engine understands: rebuild, do not guess. */
80
+ export function schemaError(found, expected) {
81
+ return new IndexError('E_INDEX_SCHEMA', `The index on disk uses schema ${String(found)}, which this version does not read (expected ${expected}). Run /index rebuild.`);
82
+ }
83
+ /** The user cancelled: the message states the invariant that matters. */
84
+ export function cancelledError() {
85
+ return new IndexError('E_INDEX_CANCELLED', 'Index build cancelled. The index was not changed.');
86
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Stage 6 FINALIZE (spec 5.3): move the pointer, then clean up old generations.
3
+ *
4
+ * ORDER IS THE WHOLE POINT. `commitPointer` runs first and is the last write a
5
+ * build performs; pruning runs afterwards and may fail freely. A build that dies
6
+ * between the two leaves a correct index plus some extra directories - annoying,
7
+ * never wrong. A build that pruned first could delete the generation the pointer
8
+ * still names, which would be unrecoverable.
9
+ *
10
+ * ASCII ONLY: inside the glyph scanner's scope.
11
+ */
12
+ import type { IndexPaths } from './paths.js';
13
+ import type { IndexMeta } from './types.js';
14
+ /** What FINALIZE did, for the structured log and the result card. */
15
+ export interface FinalizeResult {
16
+ /** Generation the pointer now names. */
17
+ readonly generation: number;
18
+ /** Old generation numbers actually deleted. */
19
+ readonly removed: readonly number[];
20
+ /** True when the tables were byte-identical to the previous generation. */
21
+ readonly unchanged: boolean;
22
+ }
23
+ /** Move the pointer and prune. `keep` includes the generation just written. */
24
+ export declare function finalize(options: {
25
+ readonly paths: IndexPaths;
26
+ readonly generation: number;
27
+ readonly keepGenerations: number;
28
+ readonly unchanged: boolean;
29
+ readonly onPointerMoved?: (meta: IndexMeta | null) => void;
30
+ }): FinalizeResult;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Stage 6 FINALIZE (spec 5.3): move the pointer, then clean up old generations.
3
+ *
4
+ * ORDER IS THE WHOLE POINT. `commitPointer` runs first and is the last write a
5
+ * build performs; pruning runs afterwards and may fail freely. A build that dies
6
+ * between the two leaves a correct index plus some extra directories - annoying,
7
+ * never wrong. A build that pruned first could delete the generation the pointer
8
+ * still names, which would be unrecoverable.
9
+ *
10
+ * ASCII ONLY: inside the glyph scanner's scope.
11
+ */
12
+ import { commitPointer, pruneGenerations, readCurrentMeta } from './store.js';
13
+ /** Move the pointer and prune. `keep` includes the generation just written. */
14
+ export function finalize(options) {
15
+ commitPointer(options.paths, options.generation);
16
+ options.onPointerMoved?.(readCurrentMeta(options.paths));
17
+ const removed = pruneGenerations(options.paths, options.keepGenerations, options.generation);
18
+ return { generation: options.generation, removed, unchanged: options.unchanged };
19
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Hashing pass for the incremental decision (spec 5.3 PLAN / AC-9).
3
+ *
4
+ * WHY THIS EXISTS AS ITS OWN PASS: PLAN must decide "changed / reused" from CONTENT, not
5
+ * from a size hint. A same-length edit (flip one digit) is invisible to a size comparison,
6
+ * and a plan that trusts size degrades the incremental path into a permanent no-op - the
7
+ * exact interaction the design nails shut in §13.4: `gitHead` moves, the plan says
8
+ * "nothing to re-parse", the pointer never advances, and the stale hint never clears.
9
+ *
10
+ * Hashing is far cheaper than parsing (one `sha1` over the bytes vs. a full character
11
+ * scan), so reading every candidate once here and re-reading only the changed ones in
12
+ * PARSE is still a large saving over a cold build, and it makes the "only changed files
13
+ * are re-parsed" promise真 exactly - which is what AC-9 measures.
14
+ *
15
+ * ASCII ONLY: inside the glyph scanner's scope.
16
+ */
17
+ import type { DiscoveredFile } from './discover.js';
18
+ /** One file's identity, as PLAN needs it. */
19
+ export interface FileFingerprint {
20
+ /** Repo-relative path. */
21
+ readonly path: string;
22
+ /** Content hash, `sha1:<hex>`; empty when the file could not be read. */
23
+ readonly sha1: string;
24
+ /** Byte size observed while reading (authoritative over the earlier `stat`). */
25
+ readonly bytes: number;
26
+ /** True when the read failed, in which case PARSE will record an error row. */
27
+ readonly unreadable: boolean;
28
+ }
29
+ /** Hash one buffer as `sha1:<hex>`; the prefix makes the stored value self-describing. */
30
+ export declare function hashBytes(buffer: Buffer): string;
31
+ /**
32
+ * Fingerprint every candidate, in order, checking the abort signal between files.
33
+ *
34
+ * A read failure is NOT an exception here: it becomes `unreadable: true`, so PLAN always
35
+ * produces a complete decision and PARSE is the one place that records an error row (one
36
+ * failure path, not two).
37
+ */
38
+ export declare function fingerprintFiles(files: readonly DiscoveredFile[], options?: {
39
+ readonly signal?: AbortSignal;
40
+ readonly maxFileBytes?: number;
41
+ }): FileFingerprint[];
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Hashing pass for the incremental decision (spec 5.3 PLAN / AC-9).
3
+ *
4
+ * WHY THIS EXISTS AS ITS OWN PASS: PLAN must decide "changed / reused" from CONTENT, not
5
+ * from a size hint. A same-length edit (flip one digit) is invisible to a size comparison,
6
+ * and a plan that trusts size degrades the incremental path into a permanent no-op - the
7
+ * exact interaction the design nails shut in §13.4: `gitHead` moves, the plan says
8
+ * "nothing to re-parse", the pointer never advances, and the stale hint never clears.
9
+ *
10
+ * Hashing is far cheaper than parsing (one `sha1` over the bytes vs. a full character
11
+ * scan), so reading every candidate once here and re-reading only the changed ones in
12
+ * PARSE is still a large saving over a cold build, and it makes the "only changed files
13
+ * are re-parsed" promise真 exactly - which is what AC-9 measures.
14
+ *
15
+ * ASCII ONLY: inside the glyph scanner's scope.
16
+ */
17
+ import { createHash } from 'node:crypto';
18
+ import { readFileSync } from 'node:fs';
19
+ /** Hash one buffer as `sha1:<hex>`; the prefix makes the stored value self-describing. */
20
+ export function hashBytes(buffer) {
21
+ return `sha1:${createHash('sha1').update(buffer).digest('hex')}`;
22
+ }
23
+ /**
24
+ * Fingerprint every candidate, in order, checking the abort signal between files.
25
+ *
26
+ * A read failure is NOT an exception here: it becomes `unreadable: true`, so PLAN always
27
+ * produces a complete decision and PARSE is the one place that records an error row (one
28
+ * failure path, not two).
29
+ */
30
+ export function fingerprintFiles(files, options = {}) {
31
+ const out = [];
32
+ for (const file of files) {
33
+ if (options.signal?.aborted)
34
+ break;
35
+ if (options.maxFileBytes !== undefined && file.bytes > options.maxFileBytes) {
36
+ // Oversize files are never read; PARSE records them as `large`.
37
+ out.push({ path: file.path, sha1: '', bytes: file.bytes, unreadable: false });
38
+ continue;
39
+ }
40
+ try {
41
+ const buffer = readFileSync(file.absolute);
42
+ out.push({ path: file.path, sha1: hashBytes(buffer), bytes: buffer.byteLength, unreadable: false });
43
+ }
44
+ catch {
45
+ out.push({ path: file.path, sha1: '', bytes: file.bytes, unreadable: true });
46
+ }
47
+ }
48
+ return out;
49
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Exclusions for DISCOVER (spec 6.2 `ignore.ts`).
3
+ *
4
+ * Three sources, in precedence order, and the order is the whole design:
5
+ *
6
+ * 1. built-in defaults (dependency and build directories nobody wants indexed),
7
+ * 2. `.gitignore` from the repository root, when the file exists,
8
+ * 3. the user's `index.exclude` prefixes.
9
+ *
10
+ * Precedence is "first match wins", so a later source can never resurrect a path
11
+ * an earlier one excluded - which is what a user asking for `exclude` expects and
12
+ * what a `.gitignore` negation cannot promise with this simple matcher.
13
+ *
14
+ * Why not a full gitignore implementation: it needs a glob engine with `**`
15
+ * semantics and negation ordering, and getting it 95% right would silently index
16
+ * the wrong set. The documented limitation is that a negated pattern (`!keep`)
17
+ * is ignored, which is why the rules are reported to `/index status` instead.
18
+ *
19
+ * ASCII ONLY: inside the glyph scanner's scope.
20
+ */
21
+ /** One parsed exclusion rule. */
22
+ export interface IgnoreRule {
23
+ /** Normalized pattern, forward slashes, no trailing slash. */
24
+ readonly pattern: string;
25
+ /** Where the rule came from; used by `/index status` to explain an omission. */
26
+ readonly source: 'default' | 'gitignore' | 'config';
27
+ /** True when the pattern ends with `/` in its source (directory-only). */
28
+ readonly directoryOnly: boolean;
29
+ }
30
+ /** The resolved exclusion set for one build. */
31
+ export interface IgnoreMatcher {
32
+ /** Rules in precedence order. */
33
+ readonly rules: readonly IgnoreRule[];
34
+ /** True when a `.gitignore` was found and read. */
35
+ readonly gitignoreLoaded: boolean;
36
+ /** True when paths were tested (a floor, so "excluded everything" is visible in tests). */
37
+ matches(relativePath: string): boolean;
38
+ }
39
+ /** Read `.gitignore` from the root, skipping comments, blanks and negations. */
40
+ export declare function readGitignoreRules(root: string): IgnoreRule[];
41
+ /** Built-in rules, expanded from `DEFAULT_EXCLUDED_PREFIXES`. */
42
+ export declare function defaultIgnoreRules(): IgnoreRule[];
43
+ /** Rules from the user's `index.exclude` list. */
44
+ export declare function configIgnoreRules(prefixes: readonly string[]): IgnoreRule[];
45
+ /**
46
+ * Build the matcher for one build. Rules are ordered defaults -> gitignore ->
47
+ * config, and `matches` returns true on the FIRST rule that matches, so the
48
+ * precedence is visible in `rules` alone.
49
+ */
50
+ export declare function createIgnoreMatcher(options: {
51
+ readonly root: string;
52
+ readonly exclude?: readonly string[];
53
+ readonly extraRules?: readonly IgnoreRule[];
54
+ }): IgnoreMatcher;
55
+ /** Convenience wrapper for a single path, used by the tests and by PLAN's sanity checks. */
56
+ export declare function isExcluded(relativePath: string, options: {
57
+ root: string;
58
+ exclude?: readonly string[];
59
+ }): boolean;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Exclusions for DISCOVER (spec 6.2 `ignore.ts`).
3
+ *
4
+ * Three sources, in precedence order, and the order is the whole design:
5
+ *
6
+ * 1. built-in defaults (dependency and build directories nobody wants indexed),
7
+ * 2. `.gitignore` from the repository root, when the file exists,
8
+ * 3. the user's `index.exclude` prefixes.
9
+ *
10
+ * Precedence is "first match wins", so a later source can never resurrect a path
11
+ * an earlier one excluded - which is what a user asking for `exclude` expects and
12
+ * what a `.gitignore` negation cannot promise with this simple matcher.
13
+ *
14
+ * Why not a full gitignore implementation: it needs a glob engine with `**`
15
+ * semantics and negation ordering, and getting it 95% right would silently index
16
+ * the wrong set. The documented limitation is that a negated pattern (`!keep`)
17
+ * is ignored, which is why the rules are reported to `/index status` instead.
18
+ *
19
+ * ASCII ONLY: inside the glyph scanner's scope.
20
+ */
21
+ import { existsSync, readFileSync } from 'node:fs';
22
+ import { join } from 'node:path';
23
+ import { DEFAULT_EXCLUDED_PREFIXES } from './limits.js';
24
+ /** Normalize a pattern: forward slashes, strip a leading `./`, strip trailing slashes. */
25
+ function normalizePattern(raw) {
26
+ let text = raw.trim().replace(/\\/g, '/');
27
+ const directoryOnly = text.endsWith('/');
28
+ while (text.endsWith('/'))
29
+ text = text.slice(0, -1);
30
+ while (text.startsWith('./'))
31
+ text = text.slice(2);
32
+ if (text.startsWith('/'))
33
+ text = text.slice(1);
34
+ return { pattern: text, directoryOnly };
35
+ }
36
+ /**
37
+ * Translate one pattern into a prefix test. Supported forms:
38
+ * - `name` -> exclude a path segment named `name` in any directory
39
+ * - `dir/sub` -> exclude that path prefix
40
+ * - `*.ext` -> exclude by suffix
41
+ * - `prefix*` -> exclude by prefix
42
+ *
43
+ * A negated rule (`!x`) returns null: this matcher does not implement
44
+ * re-inclusion, and pretending to would silently index files the user excluded.
45
+ */
46
+ function matchPattern(pattern, relativePath, directoryOnly) {
47
+ if (pattern === '' || pattern.startsWith('!'))
48
+ return false;
49
+ if (pattern.includes('/')) {
50
+ if (relativePath === pattern || relativePath.startsWith(`${pattern}/`))
51
+ return true;
52
+ return relativePath.includes(`/${pattern}`) || relativePath.includes(`/${pattern}/`);
53
+ }
54
+ if (pattern.startsWith('*.'))
55
+ return relativePath.endsWith(pattern.slice(1));
56
+ if (pattern.endsWith('*'))
57
+ return relativePath.startsWith(pattern.slice(0, -1));
58
+ const segments = relativePath.split('/');
59
+ if (directoryOnly) {
60
+ // Directory-only: match any ancestor directory, never the file name itself.
61
+ return segments.slice(0, -1).some((segment) => segment === pattern);
62
+ }
63
+ return segments.some((segment) => segment === pattern);
64
+ }
65
+ /** Read `.gitignore` from the root, skipping comments, blanks and negations. */
66
+ export function readGitignoreRules(root) {
67
+ const path = join(root, '.gitignore');
68
+ if (!existsSync(path))
69
+ return [];
70
+ let text;
71
+ try {
72
+ text = readFileSync(path, 'utf8');
73
+ }
74
+ catch {
75
+ return [];
76
+ }
77
+ const rules = [];
78
+ for (const line of text.split('\n')) {
79
+ const trimmed = line.trim();
80
+ if (trimmed === '' || trimmed.startsWith('#'))
81
+ continue;
82
+ if (trimmed.startsWith('!'))
83
+ continue;
84
+ const { pattern, directoryOnly } = normalizePattern(trimmed);
85
+ if (pattern === '')
86
+ continue;
87
+ rules.push({ pattern, source: 'gitignore', directoryOnly });
88
+ }
89
+ return rules;
90
+ }
91
+ /** Built-in rules, expanded from `DEFAULT_EXCLUDED_PREFIXES`. */
92
+ export function defaultIgnoreRules() {
93
+ return DEFAULT_EXCLUDED_PREFIXES.map((prefix) => {
94
+ const { pattern } = normalizePattern(prefix);
95
+ // Defaults are all directory names: they must never exclude a FILE that
96
+ // happens to share the name (a `dist.ts` source file is legitimate code).
97
+ return { pattern, source: 'default', directoryOnly: true };
98
+ });
99
+ }
100
+ /** Rules from the user's `index.exclude` list. */
101
+ export function configIgnoreRules(prefixes) {
102
+ const rules = [];
103
+ for (const prefix of prefixes) {
104
+ const { pattern, directoryOnly } = normalizePattern(prefix);
105
+ if (pattern === '')
106
+ continue;
107
+ rules.push({ pattern, source: 'config', directoryOnly });
108
+ }
109
+ return rules;
110
+ }
111
+ /**
112
+ * Build the matcher for one build. Rules are ordered defaults -> gitignore ->
113
+ * config, and `matches` returns true on the FIRST rule that matches, so the
114
+ * precedence is visible in `rules` alone.
115
+ */
116
+ export function createIgnoreMatcher(options) {
117
+ const gitignore = readGitignoreRules(options.root);
118
+ const rules = [
119
+ ...defaultIgnoreRules(),
120
+ ...gitignore,
121
+ ...(options.extraRules ?? []),
122
+ ...configIgnoreRules(options.exclude ?? []),
123
+ ];
124
+ return {
125
+ rules,
126
+ gitignoreLoaded: gitignore.length > 0,
127
+ matches(relativePath) {
128
+ const normalized = relativePath.replace(/\\/g, '/');
129
+ for (const rule of rules) {
130
+ if (matchPattern(rule.pattern, normalized, rule.directoryOnly))
131
+ return true;
132
+ }
133
+ return false;
134
+ },
135
+ };
136
+ }
137
+ /** Convenience wrapper for a single path, used by the tests and by PLAN's sanity checks. */
138
+ export function isExcluded(relativePath, options) {
139
+ return createIgnoreMatcher(options).matches(relativePath);
140
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The indexer package surface (spec 6.2).
3
+ *
4
+ * NO FILE IMPORTS THIS BARREL, and that is worth saying rather than leaving implied: every
5
+ * consumer inside the CLI reaches the specific module it needs (`engine.js`,
6
+ * `read/query.js`, `wiring.js`), because a barrel would widen every import closure and the
7
+ * layering check (`check-layering.mjs` L9) walks closures. It exists for the tests and for
8
+ * an out-of-tree consumer that wants one import; it is NOT a guarantee that everything
9
+ * re-exported here is stable.
10
+ *
11
+ * ASCII ONLY: inside the glyph scanner's scope.
12
+ */
13
+ export { createIndexEngine, type IndexEngine, type IndexerDeps } from './engine.js';
14
+ export { createIndexer, type Indexer, type CreateIndexerOptions } from './wiring.js';
15
+ export { buildIndexBlock, estimateBlockTokens, INDEX_BLOCK_END, INDEX_BLOCK_START, renderL0, stripIndexBlock, type L0Input, } from './l0.js';
16
+ export { CODE_QUERY_DESCRIPTION, CODE_QUERY_OPS, CODE_QUERY_PARAMETERS, CODE_QUERY_TOOL, CODE_QUERY_TOOL_NAME, type CodeQueryToolSpec, } from './tools.js';
17
+ export { absoluteOf, areaOf, countCommitsBehind, discoverRoot, displayPath, extensionOf, hasCurrentPointer, indexPathsFor, readGitHead, relativeToRoot, toPosix, type IndexPaths, } from './paths.js';
18
+ export { IndexError, isIndexError, toIndexFailure, type IndexErrorCode } from './errors.js';
19
+ export { loadCached, invalidateCache } from './read/cache.js';
20
+ export { runQuery, NO_INDEX_SENTENCE } from './read/query.js';
21
+ export { INDEX_SCHEMA_VERSION, SYMBOL_KINDS, REF_KINDS } from './types.js';
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The indexer package surface (spec 6.2).
3
+ *
4
+ * NO FILE IMPORTS THIS BARREL, and that is worth saying rather than leaving implied: every
5
+ * consumer inside the CLI reaches the specific module it needs (`engine.js`,
6
+ * `read/query.js`, `wiring.js`), because a barrel would widen every import closure and the
7
+ * layering check (`check-layering.mjs` L9) walks closures. It exists for the tests and for
8
+ * an out-of-tree consumer that wants one import; it is NOT a guarantee that everything
9
+ * re-exported here is stable.
10
+ *
11
+ * ASCII ONLY: inside the glyph scanner's scope.
12
+ */
13
+ export { createIndexEngine } from './engine.js';
14
+ export { createIndexer } from './wiring.js';
15
+ export { buildIndexBlock, estimateBlockTokens, INDEX_BLOCK_END, INDEX_BLOCK_START, renderL0, stripIndexBlock, } from './l0.js';
16
+ export { CODE_QUERY_DESCRIPTION, CODE_QUERY_OPS, CODE_QUERY_PARAMETERS, CODE_QUERY_TOOL, CODE_QUERY_TOOL_NAME, } from './tools.js';
17
+ export { absoluteOf, areaOf, countCommitsBehind, discoverRoot, displayPath, extensionOf, hasCurrentPointer, indexPathsFor, readGitHead, relativeToRoot, toPosix, } from './paths.js';
18
+ export { IndexError, isIndexError, toIndexFailure } from './errors.js';
19
+ export { loadCached, invalidateCache } from './read/cache.js';
20
+ export { runQuery, NO_INDEX_SENTENCE } from './read/query.js';
21
+ export { INDEX_SCHEMA_VERSION, SYMBOL_KINDS, REF_KINDS } from './types.js';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The L0 prompt block: a compact, deterministic index summary for the model
3
+ * (spec 5.11a, invariant I-4).
4
+ *
5
+ * DETERMINISM IS THE CONTRACT. The block's bytes must depend only on
6
+ * `(generation, settings, normalized root, the gitHead FROZEN in meta.json)`.
7
+ * No relative time, no session content, no live HEAD, no randomness. That is what
8
+ * lets the provider's prompt cache hit: same generation, same bytes, every turn.
9
+ * A "built 2h ago" line would look friendlier and would silently invalidate the
10
+ * cache on every build, which is why it lives in the panel and `/index status`
11
+ * instead of here.
12
+ *
13
+ * The block is DATA about the code and says so, because a model must never treat
14
+ * a path or a symbol name as an instruction.
15
+ *
16
+ * ASCII ONLY: inside the glyph scanner's scope.
17
+ */
18
+ import type { LoadedGeneration } from './store.js';
19
+ /** Markers around the block. `buildIndexBlock` also strips a previous block by these. */
20
+ export declare const INDEX_BLOCK_START = "<!-- aragon-index:start -->";
21
+ export declare const INDEX_BLOCK_END = "<!-- aragon-index:end -->";
22
+ /** Input to one render. `budgetTokens` is the clamped `index.promptTokens`. */
23
+ export interface L0Input {
24
+ /** The loaded generation, or null when there is no index. */
25
+ readonly loaded: LoadedGeneration | null;
26
+ /** Token budget; the render never exceeds it. */
27
+ readonly budgetTokens: number;
28
+ }
29
+ /** Estimate tokens for the whole block. */
30
+ export declare function estimateBlockTokens(text: string): number;
31
+ /**
32
+ * Render the block. Returns `''` when there is no index, which is what makes the
33
+ * system prompt byte-identical to today's on an unbuilt workspace (AC-14).
34
+ *
35
+ * Budget policy: the header, the DATA disclaimer and the tool menu are never cut;
36
+ * areas are added in rank order until the budget is spent. Cutting the disclaimer
37
+ * would be the one cut that matters, so it is excluded from the budget loop.
38
+ */
39
+ export declare function renderL0(input: L0Input): string;
40
+ /**
41
+ * Normalise a rendered block for the system prompt, or return `''`.
42
+ *
43
+ * IDEMPOTENT IN THE SENSE THE DESIGN ASKS FOR (AC-13 "marker replacement is idempotent"):
44
+ * a value that ALREADY contains the marker pair is returned unchanged. An earlier draft
45
+ * stripped the block first and then returned the remainder, which meant feeding it its own
46
+ * output produced `''` - the opposite of idempotent, and a silent way to lose the block on
47
+ * the second rebuild of a session.
48
+ *
49
+ * Text that contains a block plus surrounding prose keeps the block and drops the rest:
50
+ * this function's job is to hand the prompt ONE block, and appending a second copy of the
51
+ * same facts is how the prompt grows on every rebuild.
52
+ */
53
+ export declare function buildIndexBlock(text: string): string;
54
+ /** Remove every previously injected block, keeping the rest of the text untouched. */
55
+ export declare function stripIndexBlock(text: string): string;