@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
@@ -68,6 +68,17 @@ export function registerExecCommand(program, toFlags, deps) {
68
68
  .option('--deny-tool <names>', 'Remove tools; wins over --allow-tool (repeatable; comma-separated accepted)', collect)
69
69
  // OPT-IN, NEVER DEFAULT (gene-bank D-40): an automation path has to be reproducible, so the
70
70
  // library and its learning are off unless asked for. `--gene-learn` implies `--gene`.
71
+ // --- launch-time model / kit selection (launch-model-and-kit-flags 3.7) ---
72
+ // DECLARED HERE for the reason the bridge budgets are: `aragon exec --help`
73
+ // has to be the complete list of what a caller can tune. These are what make
74
+ // `aragon exec --kit ci-fast` reproducible in CI instead of depending on the
75
+ // developer's own config.json. Read, not persisted.
76
+ .option('--kit <name|#id|id>', 'Run on that kit (dev pack); not saved')
77
+ .option('--no-kit', 'Ignore the saved default kit for this run')
78
+ .option('--profile <name|#id|id>', 'Main slot: use a saved connection')
79
+ .option('--fast-profile <name|#id|id>', 'Fast slot: use a saved connection')
80
+ .option('--subagent-model <main|fast|profile>', 'Subagent slot: how it picks a model')
81
+ .option('--subagent-profile <name|#id|id>', 'Subagent slot: connection for profile mode')
71
82
  .option('--gene', 'Enable the Gene Bank (read-only use) for this run')
72
83
  .option('--gene-learn', 'Enable the Gene Bank and let this run learn (implies --gene)')
73
84
  .option('--append-system-prompt <text>', 'Append text to the builtin system prompt')
@@ -80,7 +91,11 @@ export function registerExecCommand(program, toFlags, deps) {
80
91
  .addOption(new Option('--timeout <ms>', 'Alias of --max-duration').hideHelp());
81
92
  exec.action(async (prompt, opts) => {
82
93
  const rootOpts = program.opts();
83
- process.exitCode = await runExec(toFlags(program.opts()), {
94
+ process.exitCode = await runExec(
95
+ // THE SIX LAUNCH FLAGS ARE ON THIS SUBCOMMAND, NOT ON THE ROOT (3.7 / 3.8).
96
+ // `toFlags` reads a `RawOpts`, so they are merged in here; without it
97
+ // `aragon exec --kit ci-fast` would parse and change nothing.
98
+ toFlags(mergeLaunchSelectionFlags(program.opts(), opts)), {
84
99
  ...opts,
85
100
  // Hoisted from the root by commander, and read here because `exec` does
86
101
  // not redeclare them. `--print` is REFUSED rather than ignored (P2-5).
@@ -89,6 +104,38 @@ export function registerExecCommand(program, toFlags, deps) {
89
104
  }, prompt, { version: deps.version, makeController: deps.makeController });
90
105
  });
91
106
  }
107
+ /**
108
+ * Hand the launch-selection flags from `exec`'s own options to `toFlags` (3.7).
109
+ *
110
+ * `toFlags(program.opts())` reads the ROOT program, and these six are declared on
111
+ * the `exec` SUBCOMMAND - so without this merge all six parse and do nothing, the
112
+ * "inert flag, no compile error, no runtime error" trap this package has recorded
113
+ * a dozen times, and the one 3.8 exists to prevent.
114
+ *
115
+ * THESE SIX AND NOT `...opts`: `RawExecOptions` reuses root names for different
116
+ * meanings (`--resume` here is a session file, while `CliFlags.resumeSession` is
117
+ * the TUI's new-branch flag), so a blanket spread would silently re-point a flag
118
+ * that has nothing to do with launch selection.
119
+ *
120
+ * ONLY A SUBCOMMAND VALUE WINS, AND `undefined` IS NOT A VALUE.
121
+ * `packages/cli/README.md` promises the two positions are equivalent
122
+ * (`aragon --model m exec "..."` and `aragon exec --model m "..."` parse alike),
123
+ * and a blanket `{ ...rootOpts, kit: execOpts.kit }` would break that promise for
124
+ * these six: `aragon --kit cheap exec "..."` would have its root value overwritten
125
+ * with the subcommand's `undefined` and the kit would silently not apply - the
126
+ * same inert-flag trap, one layer up.
127
+ * `false` IS a value here, because `--no-kit` arrives folded as `kit: false`.
128
+ */
129
+ export function mergeLaunchSelectionFlags(rootOpts, execOpts) {
130
+ const merged = { ...rootOpts };
131
+ for (const key of ['kit', 'profile', 'fastProfile', 'subagentModel',
132
+ 'subagentProfile']) {
133
+ const value = execOpts[key];
134
+ if (value !== undefined)
135
+ merged[key] = value;
136
+ }
137
+ return merged;
138
+ }
92
139
  /** Repeatable option accumulator. Comma splitting happens in `options.ts`. */
93
140
  function collect(value, previous = []) {
94
141
  return [...previous, value];
@@ -66,6 +66,15 @@ export async function runExec(flags, raw, promptArg, ctx) {
66
66
  // below because this is the first consumer, and `options.ts` stays a pure
67
67
  // flag parser: it is told the fact, it does not go looking for it.
68
68
  const config = loadConfig(flags);
69
+ // A REFUSED LAUNCH SELECTION IS A USAGE ERROR, AND IT COMES FIRST (3.8 / 2.4).
70
+ // Before `resolveExecOptions`, because a bad `--kit` is not a question about
71
+ // exec's own flags; and on STDERR with an empty stdout, because `--output-format
72
+ // json` promises exactly one JSON object there - the same reason every other
73
+ // usage error in this module returns 2 rather than throwing.
74
+ if (config.launchFatal) {
75
+ err.write(`${config.launchFatal.message}\n`);
76
+ return 2;
77
+ }
69
78
  const resolved = resolveExecOptions(raw, { confirmTools: config.confirmTools });
70
79
  if (!resolved.ok) {
71
80
  err.write(`${resolved.message}\n`);
@@ -44,6 +44,18 @@ export interface RawExecOptions {
44
44
  maxDuration?: string;
45
45
  /** The hidden `--timeout` alias of `--max-duration` (P2-1 / D-16). */
46
46
  timeout?: string;
47
+ /**
48
+ * `--kit <ref>`, and `false` for `--no-kit`.
49
+ *
50
+ * COMMANDER'S SHAPE, for the reason the root `RawOpts.kit` records: `--no-kit`
51
+ * negates the `--kit` option, so it arrives as `kit: false` and no separate
52
+ * `noKit` key ever exists.
53
+ */
54
+ kit?: string | boolean;
55
+ profile?: string;
56
+ fastProfile?: string;
57
+ subagentModel?: string;
58
+ subagentProfile?: string;
47
59
  permissionMode?: string;
48
60
  /** `--decision-timeout <ms>`; bridge only. */
49
61
  decisionTimeout?: string;
@@ -1,11 +1,16 @@
1
1
  /**
2
2
  * "Build the project index" for a host without a keyboard: the desktop equivalent of Ctrl+I.
3
3
  *
4
- * Same words, same skill, same lifecycle as the terminal: the message is the bundled
5
- * `project-indexer` skill run through `prepareSkillInvocation`, and the sentence handed to it is
6
- * the one `indexBuildInvocationArgs` writes (which the invocation card recognises as machine
7
- * text, not as something the user typed). The terminal asks for confirmation in an overlay; the
8
- * desktop asks in its own dialog BEFORE sending this, so it is not repeated here.
4
+ * TWO STAGES, ONE ENTRY (tui-ctrl-i-ast-index 6.4 / 5.10):
5
+ *
6
+ * A. the DETERMINISTIC AST index - no model, no key, seconds - via `createIndexer`;
7
+ * B. the bundled `project-indexer` skill, run through `prepareSkillInvocation` exactly as
8
+ * before: same words, same lifecycle, same invocation card.
9
+ *
10
+ * `astOnly` skips stage B entirely, which is what makes "build an index with no API key" a
11
+ * capability the desktop gets for free. The default (`astOnly: false`) keeps the pre-feature
12
+ * behaviour byte for byte: stage B only, and the `busy` / `skills_disabled` / `skill_unavailable`
13
+ * / `rejected` codes unchanged.
9
14
  *
10
15
  * Refuses rather than queues when the agent is busy: a queued skill body would arrive as
11
16
  * steering in the middle of a run, which is not what "build the index" means.
@@ -15,9 +20,35 @@ import type { InteractionCoordinator } from './interaction.js';
15
20
  export type IndexBuildOutcome = {
16
21
  ok: true;
17
22
  rebuild: boolean;
23
+ generation?: number;
24
+ astOnly?: boolean;
18
25
  } | {
19
26
  ok: false;
20
- code: 'busy' | 'skills_disabled' | 'skill_unavailable' | 'rejected';
27
+ code: 'busy' | 'skills_disabled' | 'skill_unavailable' | 'rejected'
28
+ /** The AST stage could not write or could not discover (tui-ctrl-i-ast-index 6.4). */
29
+ | 'index_failed'
30
+ /** Another process holds the writer lock; its progress is what the caller should show. */
31
+ | 'index_busy';
21
32
  message: string;
22
33
  };
23
- export declare function startIndexBuild(controller: AgentController, interaction: InteractionCoordinator): IndexBuildOutcome;
34
+ /**
35
+ * Options for one host-initiated build.
36
+ *
37
+ * `astOnly` is optional and its DEFAULT keeps the old behaviour, which is what lets the existing
38
+ * `host/__tests__/index-build.test.ts` assertions stay green without an edit.
39
+ */
40
+ export interface StartIndexBuildOptions {
41
+ /** Skip the prose stage (the bundled skill). */
42
+ astOnly?: boolean;
43
+ }
44
+ /**
45
+ * Start a build.
46
+ *
47
+ * Synchronous in its decision, asynchronous in its work: the AST stage returns a promise, so a
48
+ * caller that asked for `astOnly` receives `ok: true` once the run has been STARTED - the same
49
+ * contract the skill path has always had (`interaction.submit` is also fire-and-forget from the
50
+ * caller's point of view). Failures that the AST stage can detect immediately (a busy lock, a
51
+ * disabled index) are reported synchronously, because a caller that gets `ok: true` and then
52
+ * silence is worse than one that gets a code.
53
+ */
54
+ export declare function startIndexBuild(controller: AgentController, interaction: InteractionCoordinator, opts?: StartIndexBuildOptions): IndexBuildOutcome;
@@ -1,35 +1,89 @@
1
1
  /**
2
2
  * "Build the project index" for a host without a keyboard: the desktop equivalent of Ctrl+I.
3
3
  *
4
- * Same words, same skill, same lifecycle as the terminal: the message is the bundled
5
- * `project-indexer` skill run through `prepareSkillInvocation`, and the sentence handed to it is
6
- * the one `indexBuildInvocationArgs` writes (which the invocation card recognises as machine
7
- * text, not as something the user typed). The terminal asks for confirmation in an overlay; the
8
- * desktop asks in its own dialog BEFORE sending this, so it is not repeated here.
4
+ * TWO STAGES, ONE ENTRY (tui-ctrl-i-ast-index 6.4 / 5.10):
5
+ *
6
+ * A. the DETERMINISTIC AST index - no model, no key, seconds - via `createIndexer`;
7
+ * B. the bundled `project-indexer` skill, run through `prepareSkillInvocation` exactly as
8
+ * before: same words, same lifecycle, same invocation card.
9
+ *
10
+ * `astOnly` skips stage B entirely, which is what makes "build an index with no API key" a
11
+ * capability the desktop gets for free. The default (`astOnly: false`) keeps the pre-feature
12
+ * behaviour byte for byte: stage B only, and the `busy` / `skills_disabled` / `skill_unavailable`
13
+ * / `rejected` codes unchanged.
9
14
  *
10
15
  * Refuses rather than queues when the agent is busy: a queued skill body would arrive as
11
16
  * steering in the middle of a run, which is not what "build the index" means.
12
17
  */
13
18
  import { hasProjectIndex, indexBuildInvocationArgs, INDEX_SKILL_NAME } from '../commands/index-build.js';
19
+ import { createIndexer } from '../indexer/wiring.js';
14
20
  import { prepareSkillInvocation } from '../skills/invoke.js';
15
- export function startIndexBuild(controller, interaction) {
21
+ /**
22
+ * Start a build.
23
+ *
24
+ * Synchronous in its decision, asynchronous in its work: the AST stage returns a promise, so a
25
+ * caller that asked for `astOnly` receives `ok: true` once the run has been STARTED - the same
26
+ * contract the skill path has always had (`interaction.submit` is also fire-and-forget from the
27
+ * caller's point of view). Failures that the AST stage can detect immediately (a busy lock, a
28
+ * disabled index) are reported synchronously, because a caller that gets `ok: true` and then
29
+ * silence is worse than one that gets a code.
30
+ */
31
+ export function startIndexBuild(controller, interaction, opts = {}) {
16
32
  if (controller.isRunning() || interaction.phase !== 'idle') {
17
33
  return { ok: false, code: 'busy', message: 'The agent is busy. Let it finish before building the index.' };
18
34
  }
19
- if (!controller.getConfig().skills.enabled) {
20
- return { ok: false, code: 'skills_disabled', message: 'Skills are disabled; the project index needs the bundled skill.' };
35
+ const rebuild = hasProjectIndex(controller.getCwd());
36
+ // ---- DEFAULT PATH: the pre-feature behaviour, unchanged -------------------------------
37
+ //
38
+ // `astOnly` absent means "build the prose index", which is exactly what this function did
39
+ // before the deterministic engine existed: same guards, same codes, same SYNCHRONOUS
40
+ // submit. Keeping it synchronous is not politeness - a caller that receives `ok: true`
41
+ // must already have the turn in flight, and the pre-existing host tests assert precisely
42
+ // that (spec 6.4: "old codes unchanged").
43
+ //
44
+ // THIS BRANCH TOUCHES NOTHING NEW, and that is the point: it does not call
45
+ // `getIndexConfig()` or construct an engine, so a host double built before this feature
46
+ // keeps working unchanged. The old tests are the proof rather than an obstacle.
47
+ if (opts.astOnly !== true) {
48
+ if (!controller.getConfig().skills.enabled) {
49
+ return { ok: false, code: 'skills_disabled', message: 'Skills are disabled; the project index needs the bundled skill.' };
50
+ }
51
+ const service = controller.getSkillService();
52
+ const record = service.get(INDEX_SKILL_NAME);
53
+ if (!record || record.disabled || record.invalid) {
54
+ return { ok: false, code: 'skill_unavailable', message: `Skill "${INDEX_SKILL_NAME}" is not available.` };
55
+ }
56
+ const prepared = prepareSkillInvocation(record, indexBuildInvocationArgs(rebuild), service, () => controller.listTools().map((tool) => tool.name));
57
+ if (!prepared.ok)
58
+ return { ok: false, code: 'rejected', message: prepared.error };
59
+ const outcome = interaction.submit(prepared.message, { invocation: prepared.card });
60
+ return outcome.accepted
61
+ // NO `astOnly: false` FIELD HERE. This return value is compared for deep equality by
62
+ // the pre-existing host tests, and spec 6.4 says the default path's outcome must be
63
+ // unchanged - an extra key is a change, even when it carries the default value. The
64
+ // AST-only path adds the field; the classic path stays exactly as it was.
65
+ ? { ok: true, rebuild }
66
+ : { ok: false, code: 'rejected', message: outcome.reason ?? 'The request was not accepted.' };
21
67
  }
22
- const service = controller.getSkillService();
23
- const record = service.get(INDEX_SKILL_NAME);
24
- if (!record || record.disabled || record.invalid) {
25
- return { ok: false, code: 'skill_unavailable', message: `Skill "${INDEX_SKILL_NAME}" is not available.` };
68
+ // ---- astOnly PATH: the deterministic engine, no model, no key ------------------------
69
+ //
70
+ // A host that asks for the AST stage only gets a build that needs no credential. The
71
+ // failure codes here are the two this feature adds; `index_busy` reports the lock holder
72
+ // so the caller can show who is building instead of refusing.
73
+ const indexConfig = controller.getIndexConfig();
74
+ if (!indexConfig.enabled) {
75
+ return {
76
+ ok: false,
77
+ code: 'index_failed',
78
+ message: 'The project index is off. Enable it with /index on before building.',
79
+ };
26
80
  }
27
- const rebuild = hasProjectIndex(controller.getCwd());
28
- const prepared = prepareSkillInvocation(record, indexBuildInvocationArgs(rebuild), service, () => controller.listTools().map((tool) => tool.name));
29
- if (!prepared.ok)
30
- return { ok: false, code: 'rejected', message: prepared.error };
31
- const outcome = interaction.submit(prepared.message, { invocation: prepared.card });
32
- return outcome.accepted
33
- ? { ok: true, rebuild }
34
- : { ok: false, code: 'rejected', message: outcome.reason ?? 'The request was not accepted.' };
81
+ const { engine } = createIndexer({ cwd: controller.getCwd(), config: indexConfig });
82
+ void engine
83
+ .build({ astOnly: true, reason: 'host', signal: new AbortController().signal, onProgress: () => undefined })
84
+ .then((result) => {
85
+ if (result.ok)
86
+ controller.refreshIndexPrompt();
87
+ });
88
+ return { ok: true, rebuild, astOnly: true };
35
89
  }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Stage 4 COMMIT (spec 5.3): assemble the generation payload in memory and write it.
3
+ *
4
+ * COMMIT is the ONLY stage that writes, and it writes only inside the new
5
+ * generation directory. It never touches `current` (FINALIZE owns that one
6
+ * rename), which is what makes "a failed build leaves the previous index intact"
7
+ * true rather than aspirational.
8
+ *
9
+ * The assembly step is separated from the write step so the row-shape tests can
10
+ * assert payloads without a filesystem, and so the no-op decision can be made
11
+ * BEFORE paying for the write (spec 13.4: no-op skips re-parsing, not the pointer).
12
+ *
13
+ * ASCII ONLY: inside the glyph scanner's scope.
14
+ */
15
+ import { applyFanIn } from './link.js';
16
+ import type { IndexPaths } from './paths.js';
17
+ import type { FileFacts, FileRow, GenerationPayload, ImportRow, RefRow, SymbolRow } from './types.js';
18
+ /** Everything COMMIT needs to assemble one generation. */
19
+ export interface CommitInput {
20
+ /** All parsed facts for this generation (re-parsed + reused, already merged). */
21
+ readonly facts: readonly FileFacts[];
22
+ /** Resolved references for this generation. */
23
+ readonly refs: readonly RefRow[];
24
+ /** Symbol rows with `fl`/`r` already applied. */
25
+ readonly symbols: readonly SymbolRow[];
26
+ /** Imports with `tp` resolved. */
27
+ readonly imports: readonly ImportRow[];
28
+ /** Graph built in RANK. */
29
+ readonly graph: GenerationPayload['graph'];
30
+ /** Generation number to write. */
31
+ readonly generation: number;
32
+ /** Workspace root, absolute. */
33
+ readonly root: string;
34
+ /** Frozen git head for this generation, or null. */
35
+ readonly gitHead: string | null;
36
+ /** True when the working tree had uncommitted changes at build time. */
37
+ readonly gitHeadDirty: boolean;
38
+ /** Total wall clock of the run. */
39
+ readonly durationMs: number;
40
+ /** Files re-parsed in this run. */
41
+ readonly reparsed: number;
42
+ /** Files reused from the previous generation. */
43
+ readonly reused: number;
44
+ /** True when neither the file set nor the git head changed (spec 13.4). */
45
+ readonly unchanged: boolean;
46
+ /** Override of the build clock, for byte-stable tests. */
47
+ readonly builtAt?: string;
48
+ }
49
+ /** One `files.jsonl` row from facts. */
50
+ export declare function fileRowOf(facts: FileFacts): FileRow;
51
+ /**
52
+ * Assemble the payload. Pure: no filesystem, no clock (the built-at value is
53
+ * passed in), so `commit.test.ts` can assert exact row shapes.
54
+ */
55
+ export declare function assemblePayload(input: CommitInput): GenerationPayload;
56
+ /**
57
+ * Write the payload. Any failure removes the partial directory and surfaces as
58
+ * `E_INDEX_COMMIT`; `current` is untouched either way (spec 5.3 stage 4).
59
+ */
60
+ export declare function commitGeneration(paths: IndexPaths, payload: GenerationPayload): string;
61
+ /**
62
+ * Content fingerprint of the four tables, used to decide whether a new generation
63
+ * is byte-identical to the previous one.
64
+ *
65
+ * WHY A HASH AND NOT A DEEP COMPARE: the tables can be tens of megabytes, and the
66
+ * only question is "did anything change". A hash of the serialized rows answers it
67
+ * in one pass and gives the log a short value to quote.
68
+ */
69
+ export declare function fingerprintPayload(payload: GenerationPayload): string;
70
+ /**
71
+ * Resolve import targets for a set of facts, returning rows with `tp` filled where
72
+ * the specifier points inside the repository. Kept here so COMMIT owns the whole
73
+ * "what does the artifact contain" decision.
74
+ */
75
+ export declare function resolveImports(facts: readonly FileFacts[]): ImportRow[];
76
+ /** Re-export so `engine.ts` needs one import for the symbol pass. */
77
+ export { applyFanIn };
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Stage 4 COMMIT (spec 5.3): assemble the generation payload in memory and write it.
3
+ *
4
+ * COMMIT is the ONLY stage that writes, and it writes only inside the new
5
+ * generation directory. It never touches `current` (FINALIZE owns that one
6
+ * rename), which is what makes "a failed build leaves the previous index intact"
7
+ * true rather than aspirational.
8
+ *
9
+ * The assembly step is separated from the write step so the row-shape tests can
10
+ * assert payloads without a filesystem, and so the no-op decision can be made
11
+ * BEFORE paying for the write (spec 13.4: no-op skips re-parsing, not the pointer).
12
+ *
13
+ * ASCII ONLY: inside the glyph scanner's scope.
14
+ */
15
+ import { createHash } from 'node:crypto';
16
+ import { resolveModuleSpecifier } from './link.js';
17
+ import { applyFanIn } from './link.js';
18
+ import { writeGeneration } from './store.js';
19
+ import { INDEX_ENGINE_ID, INDEX_SCHEMA_VERSION } from './types.js';
20
+ /** One `files.jsonl` row from facts. */
21
+ export function fileRowOf(facts) {
22
+ return {
23
+ p: facts.path,
24
+ l: facts.lang,
25
+ b: facts.bytes,
26
+ h: facts.sha1,
27
+ n: facts.lines,
28
+ sy: facts.symbols.length,
29
+ s: facts.status,
30
+ ms: Math.round(facts.parseMs),
31
+ rf: facts.refs.length,
32
+ im: facts.imports.length,
33
+ };
34
+ }
35
+ /** Failure histogram including `partial`, which is a degradation rather than a failure. */
36
+ function buildFailureHistogram(facts) {
37
+ const histogram = { timeout: 0, large: 0, error: 0, partial: 0 };
38
+ for (const file of facts) {
39
+ if (file.status === 'ok')
40
+ continue;
41
+ histogram[file.status] += 1;
42
+ }
43
+ return histogram;
44
+ }
45
+ /** Language histogram, keyed by bucket name. */
46
+ function buildLanguageHistogram(facts) {
47
+ const histogram = {};
48
+ for (const file of facts) {
49
+ histogram[file.lang] = (histogram[file.lang] ?? 0) + 1;
50
+ }
51
+ return histogram;
52
+ }
53
+ /** Resolution histogram; a ref with no resolution counts as `none`. */
54
+ function buildResolutionHistogram(refs) {
55
+ const counts = { local: 0, import: 0, this: 0, name: 0, none: 0 };
56
+ for (const ref of refs)
57
+ counts[ref.rs] += 1;
58
+ return counts;
59
+ }
60
+ /**
61
+ * Assemble the payload. Pure: no filesystem, no clock (the built-at value is
62
+ * passed in), so `commit.test.ts` can assert exact row shapes.
63
+ */
64
+ export function assemblePayload(input) {
65
+ const files = input.facts.map(fileRowOf);
66
+ const sortedFiles = [...files].sort((a, b) => (a.p < b.p ? -1 : a.p > b.p ? 1 : 0));
67
+ const sortedSymbols = [...input.symbols].sort((a, b) => a.f === b.f ? (a.ln === b.ln ? (a.q < b.q ? -1 : 1) : a.ln - b.ln) : a.f < b.f ? -1 : 1);
68
+ const sortedRefs = [...input.refs].sort((a, b) => a.f === b.f ? (a.ln === b.ln ? (a.n < b.n ? -1 : 1) : a.ln - b.ln) : a.f < b.f ? -1 : 1);
69
+ const sortedImports = [...input.imports].sort((a, b) => a.f === b.f ? a.ln - b.ln : a.f < b.f ? -1 : 1);
70
+ const meta = {
71
+ schemaVersion: INDEX_SCHEMA_VERSION,
72
+ generation: input.generation,
73
+ engine: INDEX_ENGINE_ID,
74
+ builtAt: input.builtAt ?? new Date().toISOString(),
75
+ root: input.root,
76
+ gitHead: input.gitHead,
77
+ gitHeadDirty: input.gitHeadDirty,
78
+ counts: {
79
+ files: sortedFiles.length,
80
+ symbols: sortedSymbols.length,
81
+ refs: sortedRefs.length,
82
+ imports: sortedImports.length,
83
+ },
84
+ languages: buildLanguageHistogram(input.facts),
85
+ resolved: buildResolutionHistogram(input.refs),
86
+ durationMs: Math.round(input.durationMs),
87
+ failures: buildFailureHistogram(input.facts),
88
+ unchanged: input.unchanged,
89
+ reparsed: input.reparsed,
90
+ reused: input.reused,
91
+ };
92
+ return {
93
+ files: sortedFiles,
94
+ symbols: sortedSymbols,
95
+ refs: sortedRefs,
96
+ imports: sortedImports,
97
+ graph: input.graph,
98
+ meta,
99
+ };
100
+ }
101
+ /**
102
+ * Write the payload. Any failure removes the partial directory and surfaces as
103
+ * `E_INDEX_COMMIT`; `current` is untouched either way (spec 5.3 stage 4).
104
+ */
105
+ export function commitGeneration(paths, payload) {
106
+ return writeGeneration(paths, payload);
107
+ }
108
+ /**
109
+ * Content fingerprint of the four tables, used to decide whether a new generation
110
+ * is byte-identical to the previous one.
111
+ *
112
+ * WHY A HASH AND NOT A DEEP COMPARE: the tables can be tens of megabytes, and the
113
+ * only question is "did anything change". A hash of the serialized rows answers it
114
+ * in one pass and gives the log a short value to quote.
115
+ */
116
+ export function fingerprintPayload(payload) {
117
+ const hash = createHash('sha1');
118
+ hash.update(`files:${payload.files.length}\n`);
119
+ hash.update(`symbols:${payload.symbols.length}\n`);
120
+ hash.update(`refs:${payload.refs.length}\n`);
121
+ hash.update(`imports:${payload.imports.length}\n`);
122
+ for (const row of payload.symbols)
123
+ hash.update(`${row.f}\u0000${row.q}\u0000${row.ln}\n`);
124
+ for (const row of payload.refs)
125
+ hash.update(`${row.f}\u0000${row.ln}\u0000${row.n}\u0000${row.rs}\n`);
126
+ return hash.digest('hex');
127
+ }
128
+ /**
129
+ * Resolve import targets for a set of facts, returning rows with `tp` filled where
130
+ * the specifier points inside the repository. Kept here so COMMIT owns the whole
131
+ * "what does the artifact contain" decision.
132
+ */
133
+ export function resolveImports(facts) {
134
+ const known = new Set(facts.map((file) => file.path));
135
+ const out = [];
136
+ for (const file of facts) {
137
+ for (const row of file.imports) {
138
+ const target = row.k === 'py' ? undefined : resolveModuleSpecifier(file.path, row.sp, known);
139
+ out.push(target === undefined ? row : { ...row, tp: target });
140
+ }
141
+ }
142
+ return out;
143
+ }
144
+ /** Re-export so `engine.ts` needs one import for the symbol pass. */
145
+ export { applyFanIn };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Stage 1 DISCOVER (spec 5.3): enumerate candidate files under the root.
3
+ *
4
+ * TWO SOURCES, ONE SHAPE. `git ls-files` is the primary source because it already
5
+ * applies the repository's own ignore rules and is an order of magnitude faster
6
+ * on a large tree. When git is unavailable the scanner walks the filesystem and
7
+ * applies the same matcher itself - and that fallback is LABELLED, so the panel
8
+ * can say `DISCOVER (fs walk)` instead of implying git was used (spec I-5:
9
+ * degrade honestly, never silently).
10
+ *
11
+ * The output is sorted. Determinism is not cosmetic here: an unsorted list makes
12
+ * a diff of two generations meaningless and makes a flaky test out of any
13
+ * duplicate-name resolution.
14
+ *
15
+ * ASCII ONLY: inside the glyph scanner's scope.
16
+ */
17
+ import type { IgnoreMatcher } from './ignore.js';
18
+ /** One discovered file, before any parsing. */
19
+ export interface DiscoveredFile {
20
+ /** Repo-relative path with forward slashes. */
21
+ readonly path: string;
22
+ /** Absolute path on disk. */
23
+ readonly absolute: string;
24
+ /** Lower-case extension including the dot. */
25
+ readonly extension: string;
26
+ /** Byte size from `stat`, so PLAN can refuse oversize files without reading them. */
27
+ readonly bytes: number;
28
+ }
29
+ /** Result of a discovery pass. */
30
+ export interface DiscoverResult {
31
+ /** Files sorted by path. */
32
+ readonly files: readonly DiscoveredFile[];
33
+ /** True when `git ls-files` produced the list. */
34
+ readonly usedGit: boolean;
35
+ /** Number of paths rejected by the exclusion matcher (reported, not hidden). */
36
+ readonly excluded: number;
37
+ }
38
+ /**
39
+ * Discover every indexable file.
40
+ *
41
+ * `maxFiles` is enforced here rather than in PLAN so an enormous workspace stops
42
+ * before any `stat` storm; PLAN still validates the count, because the two
43
+ * checks protect different things (cost vs. correctness).
44
+ */
45
+ export declare function discover(options: {
46
+ readonly root: string;
47
+ readonly matcher: IgnoreMatcher;
48
+ readonly maxFiles?: number;
49
+ readonly preferGit?: boolean;
50
+ }): DiscoverResult;