@fabersep/atlas 0.0.0-stage → 0.1.1

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 (155) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/LICENSE +202 -0
  3. package/README.md +175 -2
  4. package/dist/packs/csharp/calls.d.ts +4 -0
  5. package/dist/packs/csharp/calls.js +167 -0
  6. package/dist/packs/csharp/declarations.d.ts +4 -0
  7. package/dist/packs/csharp/declarations.js +142 -0
  8. package/dist/packs/csharp/pack.d.ts +2 -0
  9. package/dist/packs/csharp/pack.js +39 -0
  10. package/dist/packs/csharp/resolve.d.ts +2 -0
  11. package/dist/packs/csharp/resolve.js +35 -0
  12. package/dist/packs/csharp/signals.d.ts +7 -0
  13. package/dist/packs/csharp/signals.js +143 -0
  14. package/dist/packs/dart/calls.d.ts +4 -0
  15. package/dist/packs/dart/calls.js +130 -0
  16. package/dist/packs/dart/declarations.d.ts +11 -0
  17. package/dist/packs/dart/declarations.js +79 -0
  18. package/dist/packs/dart/members.d.ts +4 -0
  19. package/dist/packs/dart/members.js +62 -0
  20. package/dist/packs/dart/pack.d.ts +2 -0
  21. package/dist/packs/dart/pack.js +37 -0
  22. package/dist/packs/dart/resolve.d.ts +2 -0
  23. package/dist/packs/dart/resolve.js +32 -0
  24. package/dist/packs/index.d.ts +3 -0
  25. package/dist/packs/index.js +8 -0
  26. package/dist/packs/json/pack.d.ts +2 -0
  27. package/dist/packs/json/pack.js +27 -0
  28. package/dist/packs/msbuild/pack.d.ts +2 -0
  29. package/dist/packs/msbuild/pack.js +75 -0
  30. package/dist/packs/msbuild/xml.d.ts +16 -0
  31. package/dist/packs/msbuild/xml.js +123 -0
  32. package/dist/packs/typescript/calls.d.ts +4 -0
  33. package/dist/packs/typescript/calls.js +208 -0
  34. package/dist/packs/typescript/declarations.d.ts +9 -0
  35. package/dist/packs/typescript/declarations.js +74 -0
  36. package/dist/packs/typescript/members.d.ts +4 -0
  37. package/dist/packs/typescript/members.js +92 -0
  38. package/dist/packs/typescript/pack.d.ts +2 -0
  39. package/dist/packs/typescript/pack.js +53 -0
  40. package/dist/packs/typescript/resolve.d.ts +2 -0
  41. package/dist/packs/typescript/resolve.js +68 -0
  42. package/dist/packs/typescript/signals.d.ts +7 -0
  43. package/dist/packs/typescript/signals.js +310 -0
  44. package/dist/packs/yaml/pack.d.ts +2 -0
  45. package/dist/packs/yaml/pack.js +35 -0
  46. package/dist/src/cli.d.ts +2 -0
  47. package/dist/src/cli.js +477 -0
  48. package/dist/src/context/pre-grep.d.ts +15 -0
  49. package/dist/src/context/pre-grep.js +79 -0
  50. package/dist/src/context/pre-invoke.d.ts +20 -0
  51. package/dist/src/context/pre-invoke.js +127 -0
  52. package/dist/src/context/pre-prompt.d.ts +16 -0
  53. package/dist/src/context/pre-prompt.js +66 -0
  54. package/dist/src/context/session.d.ts +17 -0
  55. package/dist/src/context/session.js +57 -0
  56. package/dist/src/graph/build.d.ts +17 -0
  57. package/dist/src/graph/build.js +41 -0
  58. package/dist/src/graph/metrics.d.ts +12 -0
  59. package/dist/src/graph/metrics.js +75 -0
  60. package/dist/src/graph/topology.d.ts +5 -0
  61. package/dist/src/graph/topology.js +54 -0
  62. package/dist/src/health/compare.d.ts +2 -0
  63. package/dist/src/health/compare.js +38 -0
  64. package/dist/src/health/duplicates.d.ts +11 -0
  65. package/dist/src/health/duplicates.js +66 -0
  66. package/dist/src/health/health.d.ts +12 -0
  67. package/dist/src/health/health.js +94 -0
  68. package/dist/src/health/types.d.ts +101 -0
  69. package/dist/src/health/types.js +5 -0
  70. package/dist/src/index.d.ts +25 -0
  71. package/dist/src/index.js +22 -0
  72. package/dist/src/init/init.d.ts +104 -0
  73. package/dist/src/init/init.js +499 -0
  74. package/dist/src/init/scout.d.ts +45 -0
  75. package/dist/src/init/scout.js +217 -0
  76. package/dist/src/jsonc.d.ts +5 -0
  77. package/dist/src/jsonc.js +34 -0
  78. package/dist/src/mcp/server.d.ts +398 -0
  79. package/dist/src/mcp/server.js +543 -0
  80. package/dist/src/metrics/doctor.d.ts +15 -0
  81. package/dist/src/metrics/doctor.js +125 -0
  82. package/dist/src/metrics/log.d.ts +43 -0
  83. package/dist/src/metrics/log.js +101 -0
  84. package/dist/src/metrics/stats.d.ts +43 -0
  85. package/dist/src/metrics/stats.js +172 -0
  86. package/dist/src/model.d.ts +178 -0
  87. package/dist/src/model.js +2 -0
  88. package/dist/src/outputs.d.ts +16 -0
  89. package/dist/src/outputs.js +48 -0
  90. package/dist/src/packs/calls.d.ts +9 -0
  91. package/dist/src/packs/calls.js +119 -0
  92. package/dist/src/packs/dataShape.d.ts +6 -0
  93. package/dist/src/packs/dataShape.js +54 -0
  94. package/dist/src/packs/pack.d.ts +51 -0
  95. package/dist/src/packs/pack.js +3 -0
  96. package/dist/src/packs/packFiles.d.ts +5 -0
  97. package/dist/src/packs/packFiles.js +12 -0
  98. package/dist/src/packs/symbols.d.ts +39 -0
  99. package/dist/src/packs/symbols.js +98 -0
  100. package/dist/src/packs/treeSitter.d.ts +8 -0
  101. package/dist/src/packs/treeSitter.js +107 -0
  102. package/dist/src/queries/flow.d.ts +42 -0
  103. package/dist/src/queries/flow.js +398 -0
  104. package/dist/src/queries/investigate.d.ts +43 -0
  105. package/dist/src/queries/investigate.js +216 -0
  106. package/dist/src/queries/map.d.ts +28 -0
  107. package/dist/src/queries/map.js +102 -0
  108. package/dist/src/queries/neighborhood.d.ts +35 -0
  109. package/dist/src/queries/neighborhood.js +60 -0
  110. package/dist/src/queries/search.d.ts +37 -0
  111. package/dist/src/queries/search.js +279 -0
  112. package/dist/src/scan/audit.d.ts +2 -0
  113. package/dist/src/scan/audit.js +41 -0
  114. package/dist/src/scan/records.d.ts +12 -0
  115. package/dist/src/scan/records.js +42 -0
  116. package/dist/src/scan/resolveImports.d.ts +3 -0
  117. package/dist/src/scan/resolveImports.js +47 -0
  118. package/dist/src/scan/roles.d.ts +5 -0
  119. package/dist/src/scan/roles.js +87 -0
  120. package/dist/src/scan/scan.d.ts +24 -0
  121. package/dist/src/scan/scan.js +72 -0
  122. package/dist/src/text/briefs.d.ts +13 -0
  123. package/dist/src/text/briefs.js +43 -0
  124. package/dist/src/text/collapse.d.ts +10 -0
  125. package/dist/src/text/collapse.js +58 -0
  126. package/dist/src/text/declarations.d.ts +12 -0
  127. package/dist/src/text/declarations.js +120 -0
  128. package/dist/src/text/structure.d.ts +2 -0
  129. package/dist/src/text/structure.js +15 -0
  130. package/dist/src/text/tree.d.ts +20 -0
  131. package/dist/src/text/tree.js +49 -0
  132. package/dist/src/tokens.d.ts +4 -0
  133. package/dist/src/tokens.js +9 -0
  134. package/dist/src/version.d.ts +10 -0
  135. package/dist/src/version.js +11 -0
  136. package/dist/src/walk/ignoreRules.d.ts +17 -0
  137. package/dist/src/walk/ignoreRules.js +72 -0
  138. package/dist/src/walk/walk.d.ts +11 -0
  139. package/dist/src/walk/walk.js +29 -0
  140. package/grammars/LICENSE-tree-sitter-dart +20 -0
  141. package/grammars/README.md +11 -0
  142. package/grammars/tree-sitter-dart.wasm +0 -0
  143. package/package.json +68 -4
  144. package/packs/csharp/README.md +9 -0
  145. package/packs/csharp/imports.scm +3 -0
  146. package/packs/csharp/symbols.scm +17 -0
  147. package/packs/dart/imports.scm +5 -0
  148. package/packs/dart/symbols.scm +13 -0
  149. package/packs/msbuild/README.md +11 -0
  150. package/packs/typescript/exports.scm +16 -0
  151. package/packs/typescript/imports.scm +9 -0
  152. package/packs/typescript/symbols.scm +19 -0
  153. package/schema/ast_code_map.schema.json +144 -0
  154. package/schema/schema-lock.json +7 -0
  155. package/schema/topology.schema.json +87 -0
@@ -0,0 +1,477 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { PACKS } from '../packs/index.js';
5
+ import { rankHubs } from './graph/topology.js';
6
+ import { compareHealth } from './health/compare.js';
7
+ import { checkLimits, health } from './health/health.js';
8
+ import { HealthLimitsError } from './health/types.js';
9
+ import { formatInitPlan, planOrApplyInit } from './init/init.js';
10
+ import { defaultUserHome, discoverLiveAgyModels, formatScoutStatus, readCurrentScoutConfigs, runInteractiveScout, setScoutConfig, } from './init/scout.js';
11
+ import { preGrepEnrich } from './context/pre-grep.js';
12
+ import { preInvokeEnrich } from './context/pre-invoke.js';
13
+ import { prePromptEnrich } from './context/pre-prompt.js';
14
+ import { ensureFreshIndex, projectRootFrom, serveMcp } from './mcp/server.js';
15
+ import { formatDoctor, runDoctor } from './metrics/doctor.js';
16
+ import { computeStats, formatShareCard, formatStats } from './metrics/stats.js';
17
+ import { readCodeMap, readTopology } from './outputs.js';
18
+ import { flow, impact, renderFlow, UnknownSymbolError } from './queries/flow.js';
19
+ import { investigate, renderInvestigate } from './queries/investigate.js';
20
+ import { renderMap } from './queries/map.js';
21
+ import { neighborhood } from './queries/neighborhood.js';
22
+ import { renderSearch, search } from './queries/search.js';
23
+ import { scan } from './scan/scan.js';
24
+ import { briefsText, neighborhoodList, neighborhoodText } from './text/briefs.js';
25
+ import { GENERATOR_VERSION } from './version.js';
26
+ const USAGE = `Usage: faber-atlas <command> [options] (faber-atlas --version prints the version)
27
+
28
+ scan <folder> [--out <dir>] [--exclude <path>]... [--full] [--json]
29
+ Scan a folder and write ast_code_map.json, topology.json, TopologyFULL.txt and
30
+ project_structure.md to --out (default <folder>/.faber-atlas). Unchanged files are not parsed
31
+ again unless --full is given.
32
+ map [<subfolder or file>] [--out <dir>] [--zoom 0|1|2] [--include-tests] [--fields] [--full] [--depth <n>] [--folders]
33
+ Print the repo map of the scanned folder, a subfolder, or one file's declarations.
34
+ --zoom 0: folders with file counts and roles. --zoom 1: files + top-level symbols (tests
35
+ excluded unless --include-tests). --zoom 2: method-level compact map (default).
36
+ neighborhood <file>... [--budget <tokens>] [--contents [--root <folder>]] [--list] [--out <dir>] [--json]
37
+ The files around the given ones with their briefs (declarations without bodies, data shapes).
38
+ Without --budget: every file they import and every file importing them. With --budget: also
39
+ the next ring, most central first, while they fit. --contents prints whole files instead,
40
+ read from --root (default: the folder that holds --out). --list prints only the paths.
41
+ brief <file>... [--out <dir>]
42
+ The briefs of the given files.
43
+ flow <symbol> [--depth <n>] [--include-tests] [--out <dir>] [--json]
44
+ Linearized downstream call, event, job, and implementation flow tree from <symbol> (default depth 4).
45
+ impact <symbol> [--depth <n>] [--include-tests] [--out <dir>] [--json]
46
+ Upstream callers and entrypoints that reach <symbol> (default depth 4).
47
+ hubs [--top <n>] [--out <dir>] [--json]
48
+ The most connected files.
49
+ health <folder> --max-file-lines <n> --max-function-lines <n> --hard-function-lines <n>
50
+ --max-nesting-depth <n> --min-duplicate-lines <n> [--out <dir>] [--json]
51
+ Files and functions over the limits (length and nesting depth), duplicated blocks and import cycles of the scanned folder
52
+ (--out defaults to <folder>/.faber-atlas). Every limit is required; none is assumed.
53
+ health-compare <before.json> <after.json> [--json]
54
+ What changed between two health reports made with the same limits: limits crossed, new
55
+ duplicates, new cycles, and the totals before and after.
56
+ investigate <query> [--budget <tokens>] [--folder <dir>] [--limit <n>] [--depth <n>] [--include-tests] [--out <dir>] [--root <folder>] [--fresh] [--json]
57
+ One-call context pack: structural search hits, flow/impact chains, budgeted source excerpts, and related tests.
58
+ search <query> [--folder <dir>] [--limit <n>] [--include-tests] [--out <dir>] [--fresh] [--json]
59
+ Fast structural search across symbols, files, HTTP routes, events, and jobs.
60
+ pre-grep
61
+ Claude Code PreToolUse hook for Grep: reads hook JSON on stdin and enriches Grep with Atlas matches.
62
+ pre-prompt
63
+ Claude Code UserPromptSubmit hook: reads hook JSON on stdin and injects Atlas matches for each user prompt.
64
+ pre-invoke
65
+ Antigravity PreInvocation hook: reads hook JSON on stdin and injects Atlas matches for each new prompt.
66
+ mcp [--root <folder>] [--out <dir>] [--no-fresh]
67
+ Start a stdio MCP server exposing investigate, search, map, brief, neighborhood, flow, impact, hubs, and health.
68
+ Without --root it maps the project the AI tool has open (its workspace root, else the git
69
+ root above the folder it starts in), never the whole home folder. Runs an incremental scan
70
+ before each query unless --no-fresh is given.
71
+ init [--engine <name>]... [--scout-model <m>] [--scout-effort <low|medium|high>] [--no-scout] [--no-rules] [--no-allow] [--no-hooks] [--agents-md] [--root <folder>] [--preview | --undo] [--json]
72
+ One-time setup for every project: the MCP server and a read-only Scout for Claude Code,
73
+ Antigravity and Cursor (Claude Desktop with --engine claude-desktop, mapping --root).
74
+ Applies directly (with .faber-atlas.bak backups); --preview shows the changes without writing,
75
+ --undo removes them. --agents-md also adds a navigation block to this project's AGENTS.md.
76
+ For Claude Code it also adds a short Atlas block to ~/.claude/CLAUDE.md (--no-rules skips it),
77
+ allows Atlas's read-only tools (--no-allow skips it), and installs a PreToolUse Grep enrich hook
78
+ in ~/.claude/settings.json (--no-hooks skips it).
79
+ scout [--engine <claude-code|antigravity>] [--model <name>] [--effort <low|medium|high>] [--discover] [--json]
80
+ Inspect or configure the read-only Scout model and reasoning effort per environment.
81
+ Run interactively without flags to pick from supported tiers, or pass --model/--effort directly.
82
+ stats [--out <dir>] [--days <n>] [--share] [--json]
83
+ Show local, zero-telemetry token compression, zoom sizes, scan latency, and MCP usage.
84
+ Pass --share for a strictly anonymized Markdown benchmark card.
85
+ doctor [--root <folder>] [--out <dir>] [--json]
86
+ Read-only health check of Node runtime, index schema/freshness, parse health, and .gitignore.
87
+
88
+ Queries read the outputs in --out (default ./.faber-atlas) and never parse again unless --fresh is given
89
+ (with --root <folder>, defaulting to the parent of --out).
90
+ `;
91
+ const LIMIT_FLAGS = {
92
+ maxFileLines: 'max-file-lines', maxFunctionLines: 'max-function-lines', hardFunctionLines: 'hard-function-lines',
93
+ maxNestingDepth: 'max-nesting-depth', minDuplicateLines: 'min-duplicate-lines',
94
+ };
95
+ const VALUE_FLAGS = new Set([
96
+ 'out', 'exclude', 'depth', 'budget', 'top', 'root', 'zoom', 'engine', 'days',
97
+ 'model', 'effort', 'scout-model', 'scout-effort', 'limit', 'folder',
98
+ ...Object.values(LIMIT_FLAGS),
99
+ ]);
100
+ function parseArgs(argv) {
101
+ const args = { positional: [], values: new Map(), flags: new Set() };
102
+ for (let i = 0; i < argv.length; i++) {
103
+ const name = argv[i].startsWith('--') ? argv[i].slice(2) : undefined;
104
+ if (!name)
105
+ args.positional.push(argv[i]);
106
+ else if (VALUE_FLAGS.has(name))
107
+ args.values.set(name, [...(args.values.get(name) ?? []), argv[++i]]);
108
+ else
109
+ args.flags.add(name);
110
+ }
111
+ return args;
112
+ }
113
+ const value = (args, name) => args.values.get(name)?.[0];
114
+ const numberValue = (args, name) => (value(args, name) === undefined ? undefined : Number(value(args, name)));
115
+ const outDir = (args) => path.resolve(value(args, 'out') ?? '.faber-atlas');
116
+ const rootDir = (args) => path.resolve(value(args, 'root') ?? path.dirname(outDir(args)));
117
+ async function loadMap(args) {
118
+ const out = outDir(args);
119
+ if (args.flags.has('fresh'))
120
+ return (await ensureFreshIndex(rootDir(args), out)).map;
121
+ return readCodeMap(out);
122
+ }
123
+ async function loadIndex(args) {
124
+ const out = outDir(args);
125
+ if (args.flags.has('fresh'))
126
+ return ensureFreshIndex(rootDir(args), out);
127
+ return { map: readCodeMap(out), topology: readTopology(out) };
128
+ }
129
+ function printSummary(s) {
130
+ console.log(`Scanned ${s.files} files (${s.parsed} parsed, ${s.reused} unchanged) in ${s.durationMs} ms; ${s.symbols} declarations.`);
131
+ for (const f of s.failed)
132
+ console.log(` failed ${f.path}: ${f.error}`);
133
+ const unsupported = Object.entries(s.unsupported).map(([ext, n]) => `${ext} (${n})`);
134
+ if (unsupported.length)
135
+ console.log(` unsupported (listed without declarations): ${unsupported.join(', ')}`);
136
+ }
137
+ async function runScan(args) {
138
+ const folder = args.positional[1];
139
+ if (!folder) {
140
+ console.error('scan needs a folder.');
141
+ return 2;
142
+ }
143
+ const out = value(args, 'out');
144
+ const result = await scan({ root: folder, out: out && path.resolve(out), exclude: args.values.get('exclude'), full: args.flags.has('full'), packs: PACKS });
145
+ if (args.flags.has('json'))
146
+ console.log(JSON.stringify({ out: result.out, generatorVersion: result.map.generatorVersion, schemaVersion: result.map.schemaVersion, summary: result.map.summary }, null, 2));
147
+ else
148
+ printSummary(result.map.summary);
149
+ return 0;
150
+ }
151
+ async function runNeighborhood(args) {
152
+ const budget = numberValue(args, 'budget');
153
+ const files = args.positional.slice(1);
154
+ if (!files.length || Number.isNaN(budget)) {
155
+ console.error('neighborhood needs files, and --budget <tokens> must be a number.');
156
+ return 2;
157
+ }
158
+ const contents = args.flags.has('contents');
159
+ const { map, topology } = await loadIndex(args);
160
+ const result = neighborhood(map, topology, files, { budget, contents });
161
+ if (args.flags.has('json'))
162
+ console.log(JSON.stringify(result, null, 2));
163
+ else if (args.flags.has('list'))
164
+ console.log(neighborhoodList(result));
165
+ else
166
+ console.log(neighborhoodText(result, contents ? { root: rootDir(args) } : undefined));
167
+ return 0;
168
+ }
169
+ async function runBrief(args) {
170
+ const files = args.positional.slice(1);
171
+ if (!files.length) {
172
+ console.error('brief needs files.');
173
+ return 2;
174
+ }
175
+ console.log(briefsText(await loadMap(args), files));
176
+ return 0;
177
+ }
178
+ async function runFlow(args, direction) {
179
+ const symbol = args.positional[1];
180
+ const depth = numberValue(args, 'depth');
181
+ if (!symbol || Number.isNaN(depth)) {
182
+ console.error(`${direction === 'downstream' ? 'flow' : 'impact'} needs a symbol, and --depth must be a number.`);
183
+ return 2;
184
+ }
185
+ const map = await loadMap(args);
186
+ const opts = { depth, includeTests: args.flags.has('include-tests') };
187
+ const result = direction === 'downstream' ? flow(map, symbol, opts) : impact(map, symbol, opts);
188
+ if (args.flags.has('json'))
189
+ console.log(JSON.stringify(result, null, 2));
190
+ else
191
+ console.log(renderFlow(result));
192
+ return 0;
193
+ }
194
+ async function runHubs(args) {
195
+ const { topology } = await loadIndex(args);
196
+ const hubs = rankHubs(topology.nodes, numberValue(args, 'top') ?? 10);
197
+ if (args.flags.has('json'))
198
+ console.log(JSON.stringify(hubs, null, 2));
199
+ else
200
+ hubs.forEach((h, i) => console.log(`#${i + 1} ${h.path} score ${h.centralityScore} in ${h.inDegree} out ${h.outDegree} pagerank ${h.pageRank}`));
201
+ return 0;
202
+ }
203
+ function runHealth(args) {
204
+ const folder = args.positional[1];
205
+ if (!folder) {
206
+ console.error('health needs a folder.');
207
+ return 2;
208
+ }
209
+ const limits = checkLimits(Object.fromEntries(Object.entries(LIMIT_FLAGS).map(([name, flag]) => [name, numberValue(args, flag)])));
210
+ const out = path.resolve(value(args, 'out') ?? path.join(folder, '.faber-atlas'));
211
+ const report = health(readCodeMap(out), readTopology(out), path.resolve(folder), limits, PACKS);
212
+ if (args.flags.has('json')) {
213
+ console.log(JSON.stringify(report, null, 2));
214
+ return 0;
215
+ }
216
+ const t = report.totals;
217
+ console.log(`${t.files} files, ${t.lines} lines; ${t.filesOverLimit} files over ${limits.maxFileLines} lines; ${t.functionsOverSoft} functions over ${limits.maxFunctionLines} and ${t.functionsOverHard} over ${limits.hardFunctionLines} lines; ${t.functionsOverNesting} functions nested deeper than ${limits.maxNestingDepth}; ${t.duplicateBlocks} duplicated blocks; ${t.cycles} import cycles; ${t.notMeasured} files not measured.`);
218
+ return 0;
219
+ }
220
+ function runHealthCompare(args) {
221
+ const [before, after] = args.positional.slice(1);
222
+ if (!before || !after) {
223
+ console.error('health-compare needs two health reports.');
224
+ return 2;
225
+ }
226
+ const readReport = (file) => JSON.parse(fs.readFileSync(file, 'utf8'));
227
+ const result = compareHealth(readReport(before), readReport(after));
228
+ if (args.flags.has('json')) {
229
+ console.log(JSON.stringify(result, null, 2));
230
+ return 0;
231
+ }
232
+ console.log(`${result.files.length} files and ${result.functions.length} functions crossed a length limit; ${result.nesting.length} functions crossed the nesting limit; ${result.duplicates.length} new duplicated blocks; ${result.cycles.length} new import cycles; ${result.notMeasured.length} changed files not measured.`);
233
+ return 0;
234
+ }
235
+ async function main(argv) {
236
+ if (argv[0] === '--version' || argv[0] === '-v' || argv[0] === 'version') {
237
+ console.log(GENERATOR_VERSION);
238
+ return 0;
239
+ }
240
+ const args = parseArgs(argv);
241
+ switch (args.positional[0]) {
242
+ case 'scan': return runScan(args);
243
+ case 'map': {
244
+ const zoomRaw = numberValue(args, 'zoom');
245
+ if (zoomRaw !== undefined && zoomRaw !== 0 && zoomRaw !== 1 && zoomRaw !== 2) {
246
+ console.error('map --zoom must be 0, 1, or 2.');
247
+ return 2;
248
+ }
249
+ console.log(renderMap(await loadMap(args), {
250
+ folder: args.positional[1],
251
+ fields: args.flags.has('fields'),
252
+ full: args.flags.has('full'),
253
+ depth: numberValue(args, 'depth'),
254
+ foldersOnly: args.flags.has('folders'),
255
+ zoom: zoomRaw,
256
+ includeTests: args.flags.has('include-tests'),
257
+ }));
258
+ return 0;
259
+ }
260
+ case 'neighborhood': return runNeighborhood(args);
261
+ case 'brief': return runBrief(args);
262
+ case 'flow': return runFlow(args, 'downstream');
263
+ case 'impact': return runFlow(args, 'upstream');
264
+ case 'hubs': return runHubs(args);
265
+ case 'health': return runHealth(args);
266
+ case 'health-compare': return runHealthCompare(args);
267
+ case 'investigate': {
268
+ const q = args.positional.slice(1).join(' ');
269
+ if (!q.trim()) {
270
+ console.error('investigate needs a query.');
271
+ return 2;
272
+ }
273
+ const map = await loadMap(args);
274
+ const result = investigate(map, rootDir(args), q, {
275
+ budget: numberValue(args, 'budget'),
276
+ folder: value(args, 'folder'),
277
+ limit: numberValue(args, 'limit'),
278
+ depth: numberValue(args, 'depth'),
279
+ includeTests: args.flags.has('include-tests'),
280
+ });
281
+ if (args.flags.has('json'))
282
+ console.log(JSON.stringify(result, null, 2));
283
+ else
284
+ console.log(renderInvestigate(result));
285
+ return 0;
286
+ }
287
+ case 'search': {
288
+ const q = args.positional.slice(1).join(' ');
289
+ if (!q.trim()) {
290
+ console.error('search needs a query.');
291
+ return 2;
292
+ }
293
+ const result = search(await loadMap(args), q, {
294
+ folder: value(args, 'folder'),
295
+ limit: numberValue(args, 'limit'),
296
+ includeTests: args.flags.has('include-tests'),
297
+ });
298
+ if (args.flags.has('json'))
299
+ console.log(JSON.stringify(result, null, 2));
300
+ else
301
+ console.log(renderSearch(result));
302
+ return 0;
303
+ }
304
+ case 'pre-grep': {
305
+ let input = {};
306
+ if (!process.stdin.isTTY) {
307
+ try {
308
+ const raw = fs.readFileSync(0, 'utf8');
309
+ input = raw.trim() ? JSON.parse(raw) : {};
310
+ }
311
+ catch {
312
+ input = {};
313
+ }
314
+ }
315
+ if (input.cwd === undefined)
316
+ input = { ...input, cwd: process.cwd() };
317
+ console.log(await preGrepEnrich(input));
318
+ return 0;
319
+ }
320
+ case 'pre-prompt': {
321
+ let input = {};
322
+ if (!process.stdin.isTTY) {
323
+ try {
324
+ const raw = fs.readFileSync(0, 'utf8');
325
+ input = raw.trim() ? JSON.parse(raw) : {};
326
+ }
327
+ catch {
328
+ input = {};
329
+ }
330
+ }
331
+ if (input.cwd === undefined)
332
+ input = { ...input, cwd: process.cwd() };
333
+ console.log(await prePromptEnrich(input));
334
+ return 0;
335
+ }
336
+ case 'pre-invoke': {
337
+ let input = {};
338
+ if (!process.stdin.isTTY) {
339
+ try {
340
+ const raw = fs.readFileSync(0, 'utf8');
341
+ input = raw.trim() ? JSON.parse(raw) : {};
342
+ }
343
+ catch {
344
+ input = {};
345
+ }
346
+ }
347
+ if (input.cwd === undefined && !Array.isArray(input.workspacePaths))
348
+ input = { ...input, cwd: process.cwd() };
349
+ console.log(await preInvokeEnrich(input));
350
+ return 0;
351
+ }
352
+ case 'mcp':
353
+ await serveMcp({
354
+ root: value(args, 'root'),
355
+ out: value(args, 'out'),
356
+ fresh: !args.flags.has('no-fresh'),
357
+ });
358
+ return 0;
359
+ case 'init': {
360
+ const engines = args.values.get('engine');
361
+ const preview = args.flags.has('preview') || args.flags.has('dry-run');
362
+ const undo = args.flags.has('undo');
363
+ const scoutEffort = value(args, 'scout-effort');
364
+ if (scoutEffort && scoutEffort !== 'low' && scoutEffort !== 'medium' && scoutEffort !== 'high') {
365
+ console.error('init --scout-effort must be low, medium, or high.');
366
+ return 2;
367
+ }
368
+ const result = planOrApplyInit({
369
+ root: value(args, 'root') ?? args.positional[1],
370
+ engines,
371
+ agentsMd: args.flags.has('agents-md'),
372
+ rules: !args.flags.has('no-rules'),
373
+ allow: !args.flags.has('no-allow'),
374
+ hooks: !args.flags.has('no-hooks'),
375
+ scout: !args.flags.has('no-scout'),
376
+ scoutModel: value(args, 'scout-model'),
377
+ scoutEffort,
378
+ preview,
379
+ undo,
380
+ });
381
+ if (args.flags.has('json'))
382
+ console.log(JSON.stringify(result, null, 2));
383
+ else
384
+ console.log(formatInitPlan(result));
385
+ return 0;
386
+ }
387
+ case 'scout': {
388
+ const userHome = defaultUserHome();
389
+ const engine = value(args, 'engine');
390
+ if (engine && engine !== 'claude-code' && engine !== 'antigravity') {
391
+ console.error('scout --engine must be claude-code or antigravity.');
392
+ return 2;
393
+ }
394
+ const model = value(args, 'model');
395
+ const effort = value(args, 'effort');
396
+ if (effort && effort !== 'low' && effort !== 'medium' && effort !== 'high') {
397
+ console.error('scout --effort must be low, medium, or high.');
398
+ return 2;
399
+ }
400
+ if (args.flags.has('discover')) {
401
+ const live = discoverLiveAgyModels();
402
+ if (args.flags.has('json')) {
403
+ console.log(JSON.stringify(live, null, 2));
404
+ }
405
+ else if (live.ok) {
406
+ console.log('Live Antigravity models (agy models):\n' + live.lines.join('\n'));
407
+ }
408
+ else {
409
+ console.log(live.note ?? 'Live discovery unavailable.');
410
+ }
411
+ return 0;
412
+ }
413
+ if (model || effort) {
414
+ const targetEngine = engine ?? 'claude-code';
415
+ const saved = setScoutConfig({
416
+ userHome,
417
+ engine: targetEngine,
418
+ model: model ?? (targetEngine === 'claude-code' ? 'haiku' : 'flash'),
419
+ effort,
420
+ });
421
+ if (args.flags.has('json'))
422
+ console.log(JSON.stringify(saved, null, 2));
423
+ else
424
+ console.log(`Updated ${saved.engine} Scout -> model: ${saved.model}${saved.effort ? `, effort: ${saved.effort}` : ''} (${saved.filePath})`);
425
+ return 0;
426
+ }
427
+ if (process.stdin.isTTY && !args.flags.has('json') && !args.flags.has('status')) {
428
+ await runInteractiveScout(userHome, engine);
429
+ return 0;
430
+ }
431
+ const configs = readCurrentScoutConfigs(userHome);
432
+ if (args.flags.has('json'))
433
+ console.log(JSON.stringify(configs, null, 2));
434
+ else
435
+ console.log(formatScoutStatus(configs));
436
+ return 0;
437
+ }
438
+ case 'stats': {
439
+ const days = numberValue(args, 'days');
440
+ if (days !== undefined && (Number.isNaN(days) || days <= 0)) {
441
+ console.error('stats --days must be a positive number.');
442
+ return 2;
443
+ }
444
+ const out = value(args, 'out')
445
+ ? path.resolve(value(args, 'out'))
446
+ : path.resolve(value(args, 'root') ?? projectRootFrom('.'), '.faber-atlas');
447
+ const stats = computeStats(out, { days });
448
+ if (args.flags.has('share')) {
449
+ if (args.flags.has('json'))
450
+ console.log(JSON.stringify(stats, null, 2));
451
+ else
452
+ console.log(formatShareCard(stats));
453
+ }
454
+ else if (args.flags.has('json')) {
455
+ console.log(JSON.stringify(stats, null, 2));
456
+ }
457
+ else {
458
+ console.log(formatStats(stats));
459
+ }
460
+ return 0;
461
+ }
462
+ case 'doctor': {
463
+ const root = value(args, 'root') ?? args.positional[1] ?? projectRootFrom('.');
464
+ const out = value(args, 'out');
465
+ const report = runDoctor(root, out);
466
+ if (args.flags.has('json'))
467
+ console.log(JSON.stringify(report, null, 2));
468
+ else
469
+ console.log(formatDoctor(report));
470
+ return report.ok ? 0 : 1;
471
+ }
472
+ default:
473
+ console.log(USAGE);
474
+ return args.positional[0] ? 2 : 0;
475
+ }
476
+ }
477
+ main(process.argv.slice(2)).then((code) => { process.exitCode = code; }, (err) => { console.error(`faber-atlas: ${err.message}`); process.exitCode = err instanceof HealthLimitsError || err instanceof UnknownSymbolError ? 2 : 1; });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Claude Code PreToolUse hook for Grep (02/AC-24).
3
+ * Never blocks Grep: runs a fast structural Atlas search for the same pattern and attaches matching
4
+ * symbols, signatures, entrypoints, and call/event/job links as `additionalContext`.
5
+ */
6
+ export interface PreToolUseInput {
7
+ session_id?: string;
8
+ cwd?: string;
9
+ tool_name?: string;
10
+ tool_input?: Record<string, unknown>;
11
+ }
12
+ /** Resolves the project git root for the hook's cwd, or undefined outside any project (home folder or `/`). */
13
+ export declare function hookProjectRoot(cwd: unknown, userHome?: string): string | undefined;
14
+ /** Enriches a Claude Code Grep call with Atlas structural matches; never throws or blocks. */
15
+ export declare function preGrepEnrich(input: PreToolUseInput, userHome?: string): Promise<string>;
@@ -0,0 +1,79 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { PACKS } from '../../packs/index.js';
5
+ import { projectRootFrom } from '../mcp/server.js';
6
+ import { readCodeMap } from '../outputs.js';
7
+ import { renderSearch, search } from '../queries/search.js';
8
+ import { scan } from '../scan/scan.js';
9
+ const NON_CODE_EXTS = /\.(md|markdown|json|yaml|yml|toml|ini|env|txt|csv|tsv|sql|html|css|scss|svg|xml|lock|sh|bash|zsh)$/i;
10
+ function isNonCodeTarget(toolInput) {
11
+ const targetPath = typeof toolInput.path === 'string' ? toolInput.path : '';
12
+ const glob = typeof toolInput.glob === 'string' ? toolInput.glob : '';
13
+ if (targetPath && NON_CODE_EXTS.test(targetPath))
14
+ return true;
15
+ if (glob && NON_CODE_EXTS.test(glob))
16
+ return true;
17
+ return false;
18
+ }
19
+ /** Resolves the project git root for the hook's cwd, or undefined outside any project (home folder or `/`). */
20
+ export function hookProjectRoot(cwd, userHome = os.homedir()) {
21
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd) || !fs.existsSync(cwd))
22
+ return undefined;
23
+ const root = projectRootFrom(cwd);
24
+ const real = (p) => (fs.existsSync(p) ? fs.realpathSync(p) : p);
25
+ if (real(root) === real(userHome) || path.dirname(root) === root)
26
+ return undefined;
27
+ return root;
28
+ }
29
+ async function loadFastMap(root) {
30
+ const out = path.join(root, '.faber-atlas');
31
+ try {
32
+ return readCodeMap(out);
33
+ }
34
+ catch {
35
+ return (await scan({ root, out, packs: PACKS })).map;
36
+ }
37
+ }
38
+ /** Broad multi-branch regexes or very long patterns are literal scans, not symbol lookups. */
39
+ function isBroadRegexPattern(pattern) {
40
+ if (pattern.length > 60)
41
+ return true;
42
+ const pipes = (pattern.match(/\|/g) ?? []).length;
43
+ return pipes >= 2;
44
+ }
45
+ /** Enriches a Claude Code Grep call with Atlas structural matches; never throws or blocks. */
46
+ export async function preGrepEnrich(input, userHome = os.homedir()) {
47
+ try {
48
+ if (input.tool_name !== 'Grep')
49
+ return '{}';
50
+ const toolInput = input.tool_input ?? {};
51
+ const pattern = typeof toolInput.pattern === 'string' ? toolInput.pattern.trim() : '';
52
+ if (!pattern || isNonCodeTarget(toolInput) || isBroadRegexPattern(pattern))
53
+ return '{}';
54
+ const root = hookProjectRoot(input.cwd, userHome);
55
+ if (!root)
56
+ return '{}';
57
+ const map = await loadFastMap(root);
58
+ const result = search(map, pattern, { limit: 4 });
59
+ if (result.hits.length === 0)
60
+ return '{}';
61
+ // Skip noisy low-signal keyword matches on huge repos (e.g. generic tokens matching thousands of symbols)
62
+ if (result.totalMatches > 200 && result.hits[0].score < 150)
63
+ return '{}';
64
+ const additionalContext = [
65
+ renderSearch(result),
66
+ 'Tip: use mcp__faber-atlas__flow(symbol) or mcp__faber-atlas__impact(symbol) to trace call/event/job chains instead of extra Grep or Read calls.',
67
+ ].join('\n');
68
+ return JSON.stringify({
69
+ hookSpecificOutput: {
70
+ hookEventName: 'PreToolUse',
71
+ permissionDecision: 'allow',
72
+ additionalContext,
73
+ },
74
+ });
75
+ }
76
+ catch {
77
+ return '{}';
78
+ }
79
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Antigravity PreInvocation hook (02/AC-25).
3
+ * Runs once per new user prompt (deduplicated per conversationId + prompt hash), searches the project's
4
+ * Atlas index for structural matches, and injects them as a systemMessage via `injectSteps` before the
5
+ * model makes its first tool call. Never throws.
6
+ */
7
+ export interface PreInvocationInput {
8
+ conversationId?: unknown;
9
+ workspacePaths?: unknown;
10
+ cwd?: unknown;
11
+ lastUserInput?: unknown;
12
+ invocationNum?: unknown;
13
+ }
14
+ /** Extracts high-signal search keywords from a natural-language user prompt. */
15
+ export declare function extractPromptKeywords(prompt: string, maxTerms?: number): string;
16
+ /** Enriches a new Antigravity user turn with Atlas structural matches; never throws. */
17
+ export declare function preInvokeEnrich(input: PreInvocationInput, options?: {
18
+ userHome?: string;
19
+ stateDir?: string;
20
+ }): Promise<string>;