@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,499 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { antigravityRulesPath, claudeScoutFilePath, defaultScoutEffort, defaultScoutModel, removeScoutBlock, renderAntigravityScoutBlock, renderClaudeScoutAgent, upsertScoutBlock, } from './scout.js';
5
+ export const BLOCK_START = '<!-- faber-atlas:start -->';
6
+ export const BLOCK_END = '<!-- faber-atlas:end -->';
7
+ /** Claude Code's global instructions (`~/.claude/CLAUDE.md`) get their own block (02/AC-21). */
8
+ export const RULES_BLOCK_START = '<!-- faber-atlas-rules:start -->';
9
+ export const RULES_BLOCK_END = '<!-- faber-atlas-rules:end -->';
10
+ /** The Claude Code permission rule that lets every Atlas tool run without a prompt (02/AC-22). */
11
+ export const CLAUDE_ALLOW_RULE = 'mcp__faber-atlas';
12
+ export function getEngineSpecs() {
13
+ return {
14
+ 'claude-code': {
15
+ name: 'claude-code',
16
+ gap: false,
17
+ mcpConfigFile: (home) => path.join(home, '.claude.json'),
18
+ },
19
+ 'claude-desktop': {
20
+ name: 'claude-desktop',
21
+ gap: false,
22
+ needsRoot: true,
23
+ mcpConfigFile: (home) => process.platform === 'darwin'
24
+ ? path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
25
+ : path.join(home, '.config', 'Claude', 'claude_desktop_config.json'),
26
+ },
27
+ antigravity: {
28
+ name: 'antigravity',
29
+ gap: false,
30
+ mcpConfigFile: (home) => path.join(home, '.gemini', 'config', 'mcp_config.json'),
31
+ },
32
+ cursor: {
33
+ name: 'cursor',
34
+ gap: false,
35
+ mcpConfigFile: (home) => path.join(home, '.cursor', 'mcp.json'),
36
+ },
37
+ codex: {
38
+ name: 'codex',
39
+ gap: true,
40
+ },
41
+ };
42
+ }
43
+ export function detectTargetEngines(userHome, requested) {
44
+ if (requested && requested.length > 0)
45
+ return requested;
46
+ const detected = [];
47
+ if (fs.existsSync(path.join(userHome, '.claude')))
48
+ detected.push('claude-code');
49
+ if (fs.existsSync(path.join(userHome, '.gemini')))
50
+ detected.push('antigravity');
51
+ if (fs.existsSync(path.join(userHome, '.cursor')))
52
+ detected.push('cursor');
53
+ if (detected.length === 0)
54
+ detected.push('claude-code');
55
+ return detected;
56
+ }
57
+ /**
58
+ * Claude Code shows MCP tools by name only until the model loads them, so without this block it used Atlas in 0 of 4
59
+ * measured questions (2026-11-28). The block says when to reach for Atlas and how to load its tools. Without the Scout
60
+ * (`--no-scout`) it leaves out the sentence that delegates to it (`04/FR-09`).
61
+ */
62
+ export function renderClaudeRulesBlock(options = {}) {
63
+ // Suite 1.0 on n8n (2026-11-29): with this sentence placed after the tool list, the main model delegated in 0 of 6
64
+ // runs that expected it; placing routing first and trusting Scout's verified pointers avoids both misses and re-greps.
65
+ const scoutParagraph = [
66
+ '**Route first, before any tool call of your own.** For multi-file trace/flow questions (how X works across layers, what happens when Y, a vague bug report) or open-ended, multi-file, cross-layer exploration, delegate to the `atlas-scout` agent first, passing the user\'s question, then answer directly from its report (its `file:line` pointers are already verified; only Read files if you are editing or the Scout flagged an unverified gap). Do it yourself instead, and skip it for a named file or single symbol, literal text, or a local edit. When the user names a symbol and asks what changing it breaks, call `impact` on that symbol yourself before any Grep (load it with ToolSearch, query "faber-atlas").',
67
+ '',
68
+ ];
69
+ return [
70
+ RULES_BLOCK_START,
71
+ '## Code Navigation (FaberSEP Atlas)',
72
+ '',
73
+ ...(options.scout === false ? [] : scoutParagraph),
74
+ 'To find code in a project, ask the `faber-atlas` MCP tools before Grep, Glob or reading files (load them with ToolSearch, query "faber-atlas", if they are not loaded yet): `investigate(query)` for a one-call context pack (search hits + flow/impact chains + budgeted code excerpts + related tests), `search(query)` to locate symbols, files, routes, events and jobs in one step, `map` (zoom 0, then zoom 1 on a folder) for folder overviews, `flow` to see what a function calls, `impact` to see what calls it and what a change breaks, `brief` for signatures. Use Grep and Read for exact literal text, or when Atlas has no answer.',
75
+ RULES_BLOCK_END,
76
+ ].join('\n');
77
+ }
78
+ export function claudeRulesPath(userHome) {
79
+ return path.join(userHome, '.claude', 'CLAUDE.md');
80
+ }
81
+ export function claudeSettingsPath(userHome) {
82
+ return path.join(userHome, '.claude', 'settings.json');
83
+ }
84
+ /** A managed block between two markers: replaced in place, added at the end, or removed. */
85
+ export function upsertBlock(existing, block, start, end) {
86
+ const regex = new RegExp(`${escapeRegex(start)}[\\s\\S]*?${escapeRegex(end)}`, 'g');
87
+ if (regex.test(existing)) {
88
+ let first = true;
89
+ const replaced = existing.replace(regex, () => (first ? ((first = false), block) : ''));
90
+ return `${replaced.replace(/\n{3,}/g, '\n\n').trimEnd()}\n`;
91
+ }
92
+ const trimmed = existing.trimEnd();
93
+ return trimmed ? `${trimmed}\n\n${block}\n` : `${block}\n`;
94
+ }
95
+ export function removeBlock(existing, start, end) {
96
+ const regex = new RegExp(`\\n?${escapeRegex(start)}[\\s\\S]*?${escapeRegex(end)}\\n?`, 'g');
97
+ if (!regex.test(existing))
98
+ return existing;
99
+ const next = existing.replace(regex, '\n').replace(/\n{3,}/g, '\n\n').trim();
100
+ return next ? `${next}\n` : '';
101
+ }
102
+ export const PRE_GREP_HOOK_MARK = '@fabersep/atlas pre-grep';
103
+ export const PRE_GREP_HOOK_COMMAND = `npx -y ${PRE_GREP_HOOK_MARK}`;
104
+ export const PRE_PROMPT_HOOK_MARK = '@fabersep/atlas pre-prompt';
105
+ export const PRE_PROMPT_HOOK_COMMAND = `npx -y ${PRE_PROMPT_HOOK_MARK}`;
106
+ export const PRE_INVOKE_HOOK_MARK = '@fabersep/atlas pre-invoke';
107
+ export const PRE_INVOKE_HOOK_COMMAND = `npx -y ${PRE_INVOKE_HOOK_MARK}`;
108
+ export function antigravityHooksPath(userHome) {
109
+ return path.join(userHome, '.gemini', 'config', 'hooks.json');
110
+ }
111
+ /** Antigravity's global hooks.json: one named "faber-atlas" hook with a PreInvocation handler (02/AC-25). */
112
+ function editAntigravityHooks(before, obj, undo) {
113
+ if (undo) {
114
+ if (!('faber-atlas' in obj) || before === null)
115
+ return before ?? '';
116
+ delete obj['faber-atlas'];
117
+ return `${JSON.stringify(obj, null, 2)}\n`;
118
+ }
119
+ const want = { PreInvocation: [{ type: 'command', command: PRE_INVOKE_HOOK_COMMAND, timeout: 15 }] };
120
+ if (before !== null && JSON.stringify(obj['faber-atlas']) === JSON.stringify(want))
121
+ return before;
122
+ obj['faber-atlas'] = want;
123
+ return `${JSON.stringify(obj, null, 2)}\n`;
124
+ }
125
+ const isAtlasHookGroup = (g, mark) => isObject(g) &&
126
+ Array.isArray(g.hooks) &&
127
+ g.hooks.some((h) => isObject(h) && typeof h.command === 'string' && h.command.includes(mark));
128
+ const isAtlasPreGrepGroup = (g) => isAtlasHookGroup(g, PRE_GREP_HOOK_MARK);
129
+ const isAtlasPrePromptGroup = (g) => isAtlasHookGroup(g, PRE_PROMPT_HOOK_MARK);
130
+ /**
131
+ * Claude Code's settings: Atlas's allow rule (02/AC-22), its PreToolUse Grep enrich hook (02/AC-24),
132
+ * and its UserPromptSubmit enrich hook (03/AC-09), added or removed together in one edit of the file;
133
+ * `before` itself when nothing changes.
134
+ */
135
+ function editClaudeSettings(before, obj, opts) {
136
+ let changed = false;
137
+ const perms = isObject(obj.permissions) ? obj.permissions : undefined;
138
+ const allow = perms && Array.isArray(perms.allow) ? perms.allow : undefined;
139
+ const hasRule = !!allow?.includes(CLAUDE_ALLOW_RULE);
140
+ if (opts.allow) {
141
+ if (opts.undo && hasRule) {
142
+ perms.allow = allow.filter((r) => r !== CLAUDE_ALLOW_RULE);
143
+ changed = true;
144
+ }
145
+ else if (!opts.undo && !hasRule) {
146
+ const nextPerms = perms ?? {};
147
+ nextPerms.allow = [...(allow ?? []), CLAUDE_ALLOW_RULE];
148
+ obj.permissions = nextPerms;
149
+ changed = true;
150
+ }
151
+ }
152
+ if (opts.hook) {
153
+ const hooks = isObject(obj.hooks) ? obj.hooks : undefined;
154
+ const preToolGroups = hooks && Array.isArray(hooks.PreToolUse) ? hooks.PreToolUse : undefined;
155
+ const hasPreGrep = !!preToolGroups?.some(isAtlasPreGrepGroup);
156
+ if (opts.undo && hasPreGrep) {
157
+ const rest = preToolGroups.filter((g) => !isAtlasPreGrepGroup(g));
158
+ if (rest.length)
159
+ hooks.PreToolUse = rest;
160
+ else
161
+ delete hooks.PreToolUse;
162
+ changed = true;
163
+ }
164
+ else if (!opts.undo && !hasPreGrep) {
165
+ const nextHooks = (isObject(obj.hooks) ? obj.hooks : undefined) ?? {};
166
+ nextHooks.PreToolUse = [
167
+ ...(preToolGroups ?? []),
168
+ { matcher: 'Grep', hooks: [{ type: 'command', command: PRE_GREP_HOOK_COMMAND, timeout: 15 }] },
169
+ ];
170
+ obj.hooks = nextHooks;
171
+ changed = true;
172
+ }
173
+ const curHooks = isObject(obj.hooks) ? obj.hooks : undefined;
174
+ const promptGroups = curHooks && Array.isArray(curHooks.UserPromptSubmit) ? curHooks.UserPromptSubmit : undefined;
175
+ const hasPrePrompt = !!promptGroups?.some(isAtlasPrePromptGroup);
176
+ if (opts.undo && hasPrePrompt) {
177
+ const rest = promptGroups.filter((g) => !isAtlasPrePromptGroup(g));
178
+ if (rest.length)
179
+ curHooks.UserPromptSubmit = rest;
180
+ else
181
+ delete curHooks.UserPromptSubmit;
182
+ changed = true;
183
+ }
184
+ else if (!opts.undo && !hasPrePrompt) {
185
+ const nextHooks = curHooks ?? {};
186
+ nextHooks.UserPromptSubmit = [
187
+ ...(promptGroups ?? []),
188
+ { hooks: [{ type: 'command', command: PRE_PROMPT_HOOK_COMMAND, timeout: 15 }] },
189
+ ];
190
+ obj.hooks = nextHooks;
191
+ changed = true;
192
+ }
193
+ if (opts.undo && isObject(obj.hooks) && Object.keys(obj.hooks).length === 0) {
194
+ delete obj.hooks;
195
+ }
196
+ }
197
+ return changed || before === null ? `${JSON.stringify(obj, null, 2)}\n` : before;
198
+ }
199
+ export function renderAgentsBlock() {
200
+ return [
201
+ BLOCK_START,
202
+ '## Code Navigation (FaberSEP Atlas)',
203
+ '',
204
+ 'When exploring this repository, prefer the `faber-atlas` MCP tools before broad grep/file reads:',
205
+ '- Start with `map(zoom=0)` to locate modules, then `map(folder=..., zoom=1)` for files and top-level symbols.',
206
+ '- Use `flow(symbol)` / `impact(symbol)` to trace call chains, implementations, and events, and `brief` / `neighborhood` for token-budgeted signatures.',
207
+ BLOCK_END,
208
+ ].join('\n');
209
+ }
210
+ function escapeRegex(s) {
211
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
212
+ }
213
+ export function upsertManagedBlock(existing, block) {
214
+ const regex = new RegExp(`${escapeRegex(BLOCK_START)}[\\s\\S]*?${escapeRegex(BLOCK_END)}`, 'g');
215
+ if (regex.test(existing)) {
216
+ let first = true;
217
+ const replaced = existing.replace(regex, () => {
218
+ if (first) {
219
+ first = false;
220
+ return block;
221
+ }
222
+ return '';
223
+ });
224
+ return `${replaced.replace(/\n{3,}/g, '\n\n').trimEnd()}\n`;
225
+ }
226
+ const trimmed = existing.trimEnd();
227
+ return trimmed ? `${trimmed}\n\n${block}\n` : `${block}\n`;
228
+ }
229
+ export function removeManagedBlock(existing) {
230
+ const regex = new RegExp(`\\n?${escapeRegex(BLOCK_START)}[\\s\\S]*?${escapeRegex(BLOCK_END)}\\n?`, 'g');
231
+ const next = existing.replace(regex, '\n').replace(/\n{3,}/g, '\n\n').trim();
232
+ return next ? `${next}\n` : '';
233
+ }
234
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
235
+ /** Parses a config file; `null` when it is not a JSON object (comments, a half-written file), so it is never rewritten. */
236
+ export function parseConfig(raw) {
237
+ if (raw === null || !raw.trim())
238
+ return {};
239
+ try {
240
+ const obj = JSON.parse(raw);
241
+ return isObject(obj) ? obj : null;
242
+ }
243
+ catch {
244
+ return null;
245
+ }
246
+ }
247
+ function serverTable(holder, create) {
248
+ if (!isObject(holder.mcpServers)) {
249
+ if (!create)
250
+ return undefined;
251
+ holder.mcpServers = {};
252
+ }
253
+ return holder.mcpServers;
254
+ }
255
+ /** The project root an existing `faber-atlas` entry is pinned to, if any. */
256
+ export function entryRoot(entry) {
257
+ if (!isObject(entry) || !Array.isArray(entry.args))
258
+ return undefined;
259
+ const i = entry.args.indexOf('--root');
260
+ return i >= 0 && typeof entry.args[i + 1] === 'string' ? entry.args[i + 1] : undefined;
261
+ }
262
+ /**
263
+ * Per-project `faber-atlas` entries an earlier build wrote into `~/.claude.json` (`projects[<root>].mcpServers`).
264
+ * One global entry now serves every project, so these are removed. Returns whether any was found.
265
+ */
266
+ function removeProjectEntries(obj) {
267
+ if (!isObject(obj.projects))
268
+ return false;
269
+ let found = false;
270
+ for (const project of Object.values(obj.projects)) {
271
+ if (isObject(project) && isObject(project.mcpServers) && 'faber-atlas' in project.mcpServers) {
272
+ delete project.mcpServers['faber-atlas'];
273
+ found = true;
274
+ }
275
+ }
276
+ return found;
277
+ }
278
+ export function atlasEntry(engine, root) {
279
+ return {
280
+ ...(engine.name === 'claude-code' ? { type: 'stdio' } : {}),
281
+ command: 'npx',
282
+ args: ['-y', '@fabersep/atlas', 'mcp', ...(engine.needsRoot ? ['--root', root] : [])],
283
+ };
284
+ }
285
+ function upsertMcpJson(obj, entry) {
286
+ removeProjectEntries(obj);
287
+ serverTable(obj, true)['faber-atlas'] = entry;
288
+ return `${JSON.stringify(obj, null, 2)}\n`;
289
+ }
290
+ /** The file without Atlas's entries; `before` itself when there is none, so an untouched file is never reformatted. */
291
+ function removeMcpJson(before, obj) {
292
+ const servers = serverTable(obj, false);
293
+ const top = !!servers && 'faber-atlas' in servers;
294
+ if (top)
295
+ delete servers['faber-atlas'];
296
+ const projects = removeProjectEntries(obj);
297
+ return top || projects ? `${JSON.stringify(obj, null, 2)}\n` : before;
298
+ }
299
+ /** Backups get Atlas's own suffix, so they never collide with another tool's `.bak`, and keep the original's permissions. */
300
+ export const BACKUP_SUFFIX = '.faber-atlas.bak';
301
+ function writeBackup(filePath, content) {
302
+ const bakPath = `${filePath}${BACKUP_SUFFIX}`;
303
+ if (fs.existsSync(bakPath))
304
+ return undefined;
305
+ const mode = fs.statSync(filePath).mode & 0o777;
306
+ fs.writeFileSync(bakPath, content, { encoding: 'utf8', mode });
307
+ fs.chmodSync(bakPath, mode);
308
+ return bakPath;
309
+ }
310
+ function readOrNull(file) {
311
+ return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
312
+ }
313
+ /** A managed Markdown block added to or removed from a file (Antigravity's global rules, a project's AGENTS.md). */
314
+ function blockPlan(filePath, kind, engine, undo, edit) {
315
+ const before = readOrNull(filePath);
316
+ const after = undo && before === null ? '' : edit(before ?? '');
317
+ return { filePath, kind, engine, before, after, changed: (before ?? '') !== after && !(undo && before === null) };
318
+ }
319
+ /**
320
+ * One-time setup (FR-01): every tool gets one global entry, the Scout goes to the user's own folders, and nothing is
321
+ * written into a project unless `--agents-md` asks for it. Running it again in any folder changes nothing.
322
+ */
323
+ export function planOrApplyInit(options = {}) {
324
+ // Only Claude Desktop's entry and --agents-md use a project folder.
325
+ const root = path.resolve(options.root ?? process.cwd());
326
+ const userHome = options.userHome ?? process.env.FABER_USER_HOME ?? os.homedir();
327
+ const preview = options.preview === true;
328
+ const undo = options.undo === true;
329
+ const shouldWrite = !preview;
330
+ const includeScout = options.scout !== false;
331
+ const specs = getEngineSpecs();
332
+ const engines = detectTargetEngines(userHome, options.engines);
333
+ const plans = [];
334
+ const backups = [];
335
+ const notes = [];
336
+ for (const engineName of engines) {
337
+ const spec = specs[engineName];
338
+ if (!spec) {
339
+ notes.push(`Unknown engine "${engineName}" skipped.`);
340
+ continue;
341
+ }
342
+ if (spec.gap || !spec.mcpConfigFile) {
343
+ notes.push(`Engine "${engineName}" requires manual MCP wiring (GAP-02). Run: npx -y @fabersep/atlas mcp`);
344
+ continue;
345
+ }
346
+ const filePath = spec.mcpConfigFile(userHome);
347
+ const entry = atlasEntry(spec, root);
348
+ const before = readOrNull(filePath);
349
+ const parsed = parseConfig(before);
350
+ if (parsed === null) {
351
+ notes.push(`${filePath} is not plain JSON (comments or a half-written file?), so it was left unchanged. ` +
352
+ `Add the server by hand: "faber-atlas": ${JSON.stringify(entry)}`);
353
+ }
354
+ else {
355
+ if (spec.needsRoot && !undo) {
356
+ const previous = entryRoot(serverTable(parsed, false)?.['faber-atlas']);
357
+ notes.push(previous && previous !== root
358
+ ? `${engineName} has no project folder: Atlas now maps ${root} (it mapped ${previous}).`
359
+ : `${engineName} has no project folder: Atlas maps ${root}. Run "init --engine ${engineName} --root <folder>" to change it.`);
360
+ }
361
+ const after = undo ? (before !== null ? removeMcpJson(before, parsed) : '') : upsertMcpJson(parsed, entry);
362
+ const changed = (before ?? '') !== after && !(undo && before === null);
363
+ plans.push({ filePath, kind: 'mcp-config', engine: engineName, before, after, changed });
364
+ }
365
+ if (includeScout && engineName === 'claude-code') {
366
+ const scoutFile = claudeScoutFilePath(userHome);
367
+ const sBefore = readOrNull(scoutFile);
368
+ const sAfter = undo
369
+ ? ''
370
+ : renderClaudeScoutAgent(options.scoutModel ?? defaultScoutModel('claude-code'), options.scoutEffort ?? defaultScoutEffort('claude-code') ?? 'low');
371
+ plans.push({
372
+ filePath: scoutFile,
373
+ kind: 'scout-agent',
374
+ engine: 'claude-code',
375
+ before: sBefore,
376
+ after: sAfter,
377
+ changed: undo ? sBefore !== null : (sBefore ?? '') !== sAfter,
378
+ ...(undo && sBefore !== null ? { deleted: true } : {}),
379
+ });
380
+ }
381
+ if (engineName === 'claude-code' && options.rules !== false) {
382
+ const block = renderClaudeRulesBlock({ scout: includeScout });
383
+ plans.push(blockPlan(claudeRulesPath(userHome), 'rules', 'claude-code', undo, (text) => undo ? removeBlock(text, RULES_BLOCK_START, RULES_BLOCK_END) : upsertBlock(text, block, RULES_BLOCK_START, RULES_BLOCK_END)));
384
+ }
385
+ const withHook = options.hooks !== false;
386
+ if (engineName === 'claude-code' && (options.allow !== false || withHook)) {
387
+ const settingsFile = claudeSettingsPath(userHome);
388
+ const sBefore = readOrNull(settingsFile);
389
+ const sParsed = parseConfig(sBefore);
390
+ if (sParsed === null) {
391
+ notes.push(`${settingsFile} is not plain JSON, so it was left unchanged. To skip Atlas's permission prompts, add "${CLAUDE_ALLOW_RULE}" to permissions.allow; ` +
392
+ `to enrich Grep with Atlas matches, add a PreToolUse hook for "Grep" running "${PRE_GREP_HOOK_COMMAND}".`);
393
+ }
394
+ else {
395
+ const sAfter = editClaudeSettings(sBefore, sParsed, { undo, allow: options.allow !== false, hook: withHook });
396
+ plans.push({
397
+ filePath: settingsFile,
398
+ kind: 'permissions',
399
+ engine: 'claude-code',
400
+ before: sBefore,
401
+ after: sAfter,
402
+ changed: (sBefore ?? '') !== sAfter && !(undo && sBefore === null),
403
+ });
404
+ }
405
+ }
406
+ if (engineName === 'antigravity' && withHook) {
407
+ const hooksFile = antigravityHooksPath(userHome);
408
+ const hBefore = readOrNull(hooksFile);
409
+ const hParsed = parseConfig(hBefore);
410
+ if (hParsed === null) {
411
+ notes.push(`${hooksFile} is not plain JSON, so it was left unchanged. To enrich prompts with Atlas matches, add a "faber-atlas" PreInvocation hook running "${PRE_INVOKE_HOOK_COMMAND}".`);
412
+ }
413
+ else {
414
+ const hAfter = editAntigravityHooks(hBefore, hParsed, undo);
415
+ plans.push({
416
+ filePath: hooksFile,
417
+ kind: 'hooks',
418
+ engine: 'antigravity',
419
+ before: hBefore,
420
+ after: hAfter,
421
+ changed: (hBefore ?? '') !== hAfter && !(undo && hBefore === null),
422
+ });
423
+ }
424
+ }
425
+ if (engineName === 'antigravity' && !undo) {
426
+ notes.push('Antigravity asks before the first Atlas call in a conversation; choose "Always allow" so it stops asking.');
427
+ }
428
+ if (includeScout && engineName === 'antigravity') {
429
+ const block = renderAntigravityScoutBlock(options.scoutModel ?? defaultScoutModel('antigravity'));
430
+ plans.push(blockPlan(antigravityRulesPath(userHome), 'scout-rules', 'antigravity', undo, (text) => undo ? removeScoutBlock(text) : upsertScoutBlock(text, block)));
431
+ }
432
+ }
433
+ // Opt-in, per project: a short navigation block in the project's AGENTS.md.
434
+ if (options.agentsMd) {
435
+ plans.push(blockPlan(path.join(root, 'AGENTS.md'), 'agents-md', 'project', undo, (text) => undo ? removeManagedBlock(text) : upsertManagedBlock(text, renderAgentsBlock())));
436
+ }
437
+ if (shouldWrite) {
438
+ for (const p of plans) {
439
+ if (!p.changed)
440
+ continue;
441
+ if (undo && p.before === null)
442
+ continue;
443
+ if (undo && p.deleted) {
444
+ if (fs.existsSync(p.filePath))
445
+ fs.unlinkSync(p.filePath);
446
+ continue;
447
+ }
448
+ fs.mkdirSync(path.dirname(p.filePath), { recursive: true });
449
+ if (!undo && p.before !== null) {
450
+ const bakPath = writeBackup(p.filePath, p.before);
451
+ if (bakPath) {
452
+ p.backupPath = bakPath;
453
+ backups.push(bakPath);
454
+ }
455
+ }
456
+ fs.writeFileSync(p.filePath, p.after, 'utf8');
457
+ }
458
+ }
459
+ return { root, applied: shouldWrite && !undo, preview, undo, plans, backups, notes };
460
+ }
461
+ export function formatInitPlan(result) {
462
+ const mode = result.undo
463
+ ? 'UNDO COMPLETE'
464
+ : result.preview
465
+ ? 'PREVIEW (no files modified)'
466
+ : 'READY (applied)';
467
+ const lines = [`FaberSEP Atlas init — ${mode}`, `Project root: ${result.root}`, ''];
468
+ for (const plan of result.plans) {
469
+ lines.push(`[${plan.engine}] ${plan.kind} — ${plan.filePath}`);
470
+ if (!plan.changed) {
471
+ lines.push(' (already up to date)');
472
+ }
473
+ else if (plan.deleted) {
474
+ lines.push(' - (removed file)');
475
+ }
476
+ else {
477
+ const beforeLines = (plan.before ?? '').split('\n');
478
+ const afterLines = plan.after.split('\n');
479
+ const removed = beforeLines.filter((l) => l && !afterLines.includes(l));
480
+ const added = afterLines.filter((l) => l && !beforeLines.includes(l));
481
+ for (const l of removed)
482
+ lines.push(` - ${l}`);
483
+ for (const l of added)
484
+ lines.push(` + ${l}`);
485
+ if (plan.backupPath)
486
+ lines.push(` backup: ${plan.backupPath}`);
487
+ }
488
+ lines.push('');
489
+ }
490
+ for (const note of result.notes)
491
+ lines.push(`Note: ${note}`);
492
+ if (result.preview) {
493
+ lines.push('Run "faber-atlas init" (without --preview) to apply these changes.');
494
+ }
495
+ else if (!result.undo) {
496
+ lines.push('Next: change Scout model/effort anytime with "faber-atlas scout", or revert with "faber-atlas init --undo".');
497
+ }
498
+ return lines.join('\n').trimEnd();
499
+ }
@@ -0,0 +1,45 @@
1
+ export declare const SCOUT_BLOCK_START = "<!-- faber-atlas-scout:start -->";
2
+ export declare const SCOUT_BLOCK_END = "<!-- faber-atlas-scout:end -->";
3
+ export type ScoutEngine = 'claude-code' | 'antigravity';
4
+ export type EffortLevel = 'low' | 'medium' | 'high';
5
+ export interface ScoutTierOption {
6
+ id: string;
7
+ label: string;
8
+ recommended?: boolean;
9
+ }
10
+ export declare const CLAUDE_SCOUT_TIERS: readonly ScoutTierOption[];
11
+ export declare const ANTIGRAVITY_SCOUT_TIERS: readonly ScoutTierOption[];
12
+ export declare const EFFORT_OPTIONS: readonly EffortLevel[];
13
+ export interface ScoutConfig {
14
+ engine: ScoutEngine;
15
+ model: string;
16
+ effort?: EffortLevel;
17
+ filePath: string;
18
+ installed: boolean;
19
+ }
20
+ export declare function defaultScoutModel(engine: ScoutEngine): string;
21
+ export declare function defaultScoutEffort(engine: ScoutEngine): EffortLevel | undefined;
22
+ /** The Scout lives in the user's own folders, so one setup serves every project. */
23
+ export declare function claudeScoutFilePath(userHome: string): string;
24
+ /** Antigravity's global rules file, read in every workspace. */
25
+ export declare function antigravityRulesPath(userHome: string): string;
26
+ export declare const defaultUserHome: () => string;
27
+ export declare function renderClaudeScoutAgent(model?: string, effort?: EffortLevel): string;
28
+ export declare function renderAntigravityScoutBlock(model?: string): string;
29
+ export declare function upsertScoutBlock(existing: string, block: string): string;
30
+ export declare function removeScoutBlock(existing: string): string;
31
+ export declare function readCurrentScoutConfigs(userHome?: string): ScoutConfig[];
32
+ export declare function setScoutConfig(options: {
33
+ userHome?: string;
34
+ engine: ScoutEngine;
35
+ model: string;
36
+ effort?: EffortLevel;
37
+ }): ScoutConfig;
38
+ /** Optional live model discovery for Antigravity (`agy models`), with safe offline fallback. */
39
+ export declare function discoverLiveAgyModels(timeoutMs?: number): {
40
+ ok: boolean;
41
+ lines: string[];
42
+ note?: string;
43
+ };
44
+ export declare function formatScoutStatus(configs: ScoutConfig[]): string;
45
+ export declare function runInteractiveScout(userHome: string, preferredEngine?: ScoutEngine): Promise<ScoutConfig>;