@fabersep/atlas 0.1.0 → 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.
@@ -0,0 +1,127 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { PACKS } from '../../packs/index.js';
6
+ import { antigravityRulesPath, defaultScoutModel, SCOUT_BLOCK_START } from '../init/scout.js';
7
+ import { readCodeMap } from '../outputs.js';
8
+ import { renderSearch, search } from '../queries/search.js';
9
+ import { scan } from '../scan/scan.js';
10
+ import { hookProjectRoot } from './pre-grep.js';
11
+ const STOP_WORDS = new Set([
12
+ 'the', 'and', 'for', 'with', 'from', 'that', 'this', 'what', 'when', 'where', 'which', 'how', 'does',
13
+ 'into', 'are', 'all', 'want', 'need', 'add', 'new', 'list', 'give', 'exact', 'file', 'line', 'files',
14
+ 'lines', 'pointers', 'trace', 'happens', 'user', 'users', 'app', 'server', 'across', 'every', 'before',
15
+ 'after', 'must', 'stay', 'affected', 'minimal', 'edit', 'plan', 'propose', 'whenever', 'fails', 'should',
16
+ 'edited', 'numbers', 'about', 'their', 'during', 'poll', 'start', 'change', 'signature', 'instead',
17
+ 'including', 'side', 'effects', 'like', 'full', 'report', 'says', 'sometimes', 'skip', 'please', 'can',
18
+ 'you', 'check', 'show', 'find', 'explain', 'tell', 'make', 'fix', 'update', 'code', 'project', 'repo',
19
+ // Common Turkish filler words
20
+ 'bir', 'ile', 'icin', 'gibi', 'nasil', 'nerede', 'hangi', 'kadar', 'sonra', 'once', 'bakalim', 'bakar',
21
+ 'misin', 'yapar', 'yapalim', 'olsun', 'olan', 'olarak', 'daha', 'cok', 'ama', 'veya', 'bunu', 'buna',
22
+ ]);
23
+ /** Extracts high-signal search keywords from a natural-language user prompt. */
24
+ export function extractPromptKeywords(prompt, maxTerms = 8) {
25
+ const words = prompt
26
+ .replace(/[^a-zA-Z0-9._/-]+/g, ' ')
27
+ .split(/\s+/)
28
+ .map((w) => w.replace(/^[._/-]+|[._/-]+$/g, ''))
29
+ .filter((w) => w.length >= 3 && !STOP_WORDS.has(w.toLowerCase()));
30
+ const unique = [];
31
+ const seen = new Set();
32
+ for (const w of words) {
33
+ const key = w.toLowerCase();
34
+ if (seen.has(key))
35
+ continue;
36
+ seen.add(key);
37
+ unique.push(w);
38
+ if (unique.length >= maxTerms)
39
+ break;
40
+ }
41
+ return unique.join(' ');
42
+ }
43
+ function alreadyInjected(conversationId, prompt, stateDir) {
44
+ const convHash = crypto.createHash('sha1').update(conversationId).digest('hex').slice(0, 12);
45
+ const promptHash = crypto.createHash('sha1').update(prompt).digest('hex').slice(0, 16);
46
+ const file = path.join(stateDir, `faber-atlas-preinvoke-${convHash}.txt`);
47
+ try {
48
+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf8').trim() === promptHash) {
49
+ return true;
50
+ }
51
+ fs.writeFileSync(file, promptHash, 'utf8');
52
+ }
53
+ catch {
54
+ // Best-effort deduplication.
55
+ }
56
+ return false;
57
+ }
58
+ async function loadFastMap(root) {
59
+ const out = path.join(root, '.faber-atlas');
60
+ try {
61
+ return readCodeMap(out);
62
+ }
63
+ catch {
64
+ return (await scan({ root, out, packs: PACKS })).map;
65
+ }
66
+ }
67
+ /** Enriches a new Antigravity user turn with Atlas structural matches; never throws. */
68
+ export async function preInvokeEnrich(input, options = {}) {
69
+ try {
70
+ const userHome = options.userHome ?? os.homedir();
71
+ const stateDir = options.stateDir ?? os.tmpdir();
72
+ const prompt = typeof input.lastUserInput === 'string' ? input.lastUserInput.trim() : '';
73
+ if (!prompt)
74
+ return '{}';
75
+ const workspace = Array.isArray(input.workspacePaths)
76
+ ? input.workspacePaths.find((p) => typeof p === 'string')
77
+ : undefined;
78
+ const root = hookProjectRoot(workspace ?? input.cwd, userHome);
79
+ if (!root)
80
+ return '{}';
81
+ const convId = typeof input.conversationId === 'string' && input.conversationId.trim()
82
+ ? input.conversationId.trim()
83
+ : undefined;
84
+ if (convId) {
85
+ if (alreadyInjected(convId, prompt, stateDir))
86
+ return '{}';
87
+ }
88
+ else if (typeof input.invocationNum === 'number' && input.invocationNum > 1) {
89
+ return '{}';
90
+ }
91
+ // With the Scout installed in GEMINI.md, keep the hook to a single compact routing line without dumping
92
+ // raw search hits: raw file:line matches caused the main model to skip the Scout and call read_file directly.
93
+ const rulesFile = antigravityRulesPath(userHome);
94
+ if (fs.existsSync(rulesFile)) {
95
+ const rulesText = fs.readFileSync(rulesFile, 'utf8');
96
+ if (rulesText.includes(SCOUT_BLOCK_START)) {
97
+ const model = rulesText.match(/Model:\s*"([^"]+)"/)?.[1]?.trim() ?? defaultScoutModel('antigravity');
98
+ const routingMsg = `FaberSEP Atlas (project root: ${root}): for multi-file trace/flow, "what happens when", or vague bug questions, ` +
99
+ `define a read-only "atlas-scout" subagent with EnableMCPTools=true (built-in research has no MCP tools) and invoke it via invoke_subagent(TypeName="atlas-scout", Model="${model}"), passing the user's question and root="${root}". ` +
100
+ `For "what breaks if I change <symbol>", call faber-atlas impact first (call_mcp_tool ServerName="faber-atlas", ToolName="impact", root="${root}") before any grep or run_command. ` +
101
+ `For a named file, single symbol, literal text, or local edit, do it yourself.`;
102
+ return JSON.stringify({
103
+ injectSteps: [{ systemMessage: { systemMessage: routingMsg } }],
104
+ });
105
+ }
106
+ }
107
+ const query = extractPromptKeywords(prompt);
108
+ if (!query)
109
+ return '{}';
110
+ const map = await loadFastMap(root);
111
+ const result = search(map, query, { limit: 8 });
112
+ if (result.hits.length === 0)
113
+ return '{}';
114
+ const message = [
115
+ renderSearch(result),
116
+ '',
117
+ `FaberSEP Atlas structural matches for this request (project root: ${root}). ` +
118
+ `Inspect exact lines with read_file, or call faber-atlas flow/impact (pass root="${root}") instead of broad grep searches.`,
119
+ ].join('\n');
120
+ return JSON.stringify({
121
+ injectSteps: [{ systemMessage: { systemMessage: message } }],
122
+ });
123
+ }
124
+ catch {
125
+ return '{}';
126
+ }
127
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Claude Code UserPromptSubmit hook (03/AC-08).
3
+ * Runs once per user prompt, extracts high-signal keywords, searches the project's
4
+ * Atlas index, and attaches matching symbols/routes/events/jobs as `additionalContext`.
5
+ * Never throws or blocks.
6
+ */
7
+ export interface PrePromptInput {
8
+ session_id?: unknown;
9
+ cwd?: unknown;
10
+ prompt?: unknown;
11
+ hook_event_name?: unknown;
12
+ }
13
+ /** Enriches a Claude Code user prompt with Atlas structural matches; never throws or blocks. */
14
+ export declare function prePromptEnrich(input: PrePromptInput, options?: {
15
+ userHome?: string;
16
+ }): Promise<string>;
@@ -0,0 +1,66 @@
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 { claudeScoutFilePath } from '../init/scout.js';
6
+ import { readCodeMap } from '../outputs.js';
7
+ import { renderSearch, search } from '../queries/search.js';
8
+ import { scan } from '../scan/scan.js';
9
+ import { hookProjectRoot } from './pre-grep.js';
10
+ import { extractPromptKeywords } from './pre-invoke.js';
11
+ async function loadFastMap(root) {
12
+ const out = path.join(root, '.faber-atlas');
13
+ try {
14
+ return readCodeMap(out);
15
+ }
16
+ catch {
17
+ return (await scan({ root, out, packs: PACKS })).map;
18
+ }
19
+ }
20
+ /** Internal Claude Code system notifications that also fire UserPromptSubmit; never enrich them. */
21
+ const SYSTEM_PROMPT_PREFIX = /^<(?:task-notification|system-reminder|command-message|local-command)\b/i;
22
+ /** Enriches a Claude Code user prompt with Atlas structural matches; never throws or blocks. */
23
+ export async function prePromptEnrich(input, options = {}) {
24
+ try {
25
+ const userHome = options.userHome ?? os.homedir();
26
+ const prompt = typeof input.prompt === 'string' ? input.prompt.trim() : '';
27
+ if (!prompt || SYSTEM_PROMPT_PREFIX.test(prompt))
28
+ return '{}';
29
+ const root = hookProjectRoot(input.cwd, userHome);
30
+ if (!root)
31
+ return '{}';
32
+ // With the Scout installed, keep the hook to a single compact routing line (~55 tokens) without dumping raw
33
+ // search hits: raw file:line matches caused the main model to skip the Scout and added 1-5k wasted tokens
34
+ // per turn (suite 1.0, n8n, 2026-11-29).
35
+ const scout = fs.existsSync(claudeScoutFilePath(userHome));
36
+ if (scout) {
37
+ return JSON.stringify({
38
+ hookSpecificOutput: {
39
+ hookEventName: 'UserPromptSubmit',
40
+ additionalContext: 'FaberSEP Atlas: for multi-file trace/flow, "what happens when", or vague bug questions, delegate to the atlas-scout agent first (passing the user\'s question). For "what breaks if I change <symbol>", call mcp__faber-atlas__impact first (load via ToolSearch "faber-atlas" if needed). For a named file, single symbol, literal text, or local edit, do it yourself.',
41
+ },
42
+ });
43
+ }
44
+ const query = extractPromptKeywords(prompt);
45
+ if (!query)
46
+ return '{}';
47
+ const map = await loadFastMap(root);
48
+ const result = search(map, query, { limit: 6 });
49
+ if (result.hits.length === 0)
50
+ return '{}';
51
+ const additionalContext = [
52
+ renderSearch(result),
53
+ '',
54
+ 'FaberSEP Atlas structural matches for this prompt. Use mcp__faber-atlas__investigate / flow / impact for full chains.',
55
+ ].join('\n');
56
+ return JSON.stringify({
57
+ hookSpecificOutput: {
58
+ hookEventName: 'UserPromptSubmit',
59
+ additionalContext,
60
+ },
61
+ });
62
+ }
63
+ catch {
64
+ return '{}';
65
+ }
66
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The text a session-start hook puts in front of the model (02/AC-24): the project's zoom 0 map and how to dig
3
+ * deeper. Aider-style: the model sees the map without having to pick a tool first.
4
+ */
5
+ export type HookEngine = 'claude-code' | 'antigravity';
6
+ /** What the AI tool sends the hook on stdin: Claude Code `cwd`; Antigravity `workspacePaths` and `cwd`. */
7
+ export interface HookInput {
8
+ cwd?: unknown;
9
+ workspacePaths?: unknown;
10
+ }
11
+ /** The project a session runs in, or undefined outside any project (the home folder, `/`). */
12
+ export declare function sessionRoot(input: HookInput, userHome?: string): string | undefined;
13
+ export declare function sessionText(root: string, map: string, engine: HookEngine): string;
14
+ /** The hook's stdout for each tool's session-start contract. */
15
+ export declare function hookOutput(engine: HookEngine, text: string | undefined): string;
16
+ /** Builds (or refreshes) the index and returns the hook output; never throws, since a hook must not break a session. */
17
+ export declare function sessionContext(engine: HookEngine, input: HookInput, userHome?: string): Promise<string>;
@@ -0,0 +1,57 @@
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 { renderMap } from '../queries/map.js';
7
+ import { scan } from '../scan/scan.js';
8
+ /** The project a session runs in, or undefined outside any project (the home folder, `/`). */
9
+ export function sessionRoot(input, userHome = os.homedir()) {
10
+ const workspace = Array.isArray(input.workspacePaths) ? input.workspacePaths.find((p) => typeof p === 'string') : undefined;
11
+ const start = workspace ?? (typeof input.cwd === 'string' ? input.cwd : undefined);
12
+ if (!start || !path.isAbsolute(start) || !fs.existsSync(start))
13
+ return undefined;
14
+ const root = projectRootFrom(start);
15
+ const real = (p) => (fs.existsSync(p) ? fs.realpathSync(p) : p);
16
+ if (real(root) === real(userHome) || path.dirname(root) === root)
17
+ return undefined;
18
+ return root;
19
+ }
20
+ export function sessionText(root, map, engine) {
21
+ const load = engine === 'claude-code' ? ' (load them with ToolSearch, query "faber-atlas", if they are not loaded yet)' : '';
22
+ const rootArg = engine === 'antigravity' ? ` Pass root="${root}" on every faber-atlas call.` : '';
23
+ return [
24
+ `FaberSEP Atlas map of this project (${root}), zoom 0: folders, file counts and roles.`,
25
+ '',
26
+ map,
27
+ '',
28
+ `To look further, use the faber-atlas MCP tools before Grep, Glob or reading files${load}: ` +
29
+ 'map(folder, zoom=1) for files and symbols, flow(symbol) for what a function calls, ' +
30
+ 'impact(symbol) for its callers and what a change breaks, brief(files) for signatures.' +
31
+ rootArg,
32
+ ].join('\n');
33
+ }
34
+ /** The hook's stdout for each tool's session-start contract. */
35
+ export function hookOutput(engine, text) {
36
+ if (!text)
37
+ return '{}';
38
+ if (engine === 'claude-code') {
39
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: text } });
40
+ }
41
+ return JSON.stringify({ injectSteps: [{ systemMessage: { systemMessage: text } }] });
42
+ }
43
+ /** Builds (or refreshes) the index and returns the hook output; never throws, since a hook must not break a session. */
44
+ export async function sessionContext(engine, input, userHome = os.homedir()) {
45
+ try {
46
+ const root = sessionRoot(input, userHome);
47
+ if (!root)
48
+ return hookOutput(engine, undefined);
49
+ const result = await scan({ root, packs: PACKS });
50
+ if (result.map.files.length === 0)
51
+ return hookOutput(engine, undefined);
52
+ return hookOutput(engine, sessionText(root, renderMap(result.map, { zoom: 0 }), engine));
53
+ }
54
+ catch {
55
+ return hookOutput(engine, undefined);
56
+ }
57
+ }
@@ -2,6 +2,8 @@
2
2
  export { scan, type ScanOptions, type ScanResult } from './scan/scan.js';
3
3
  export { renderMap, isTestFile, type MapOptions, type ZoomLevel } from './queries/map.js';
4
4
  export { flow, impact, renderFlow, UnknownSymbolError, type FlowEdgeKind, type FlowNode, type FlowOptions, type FlowResult } from './queries/flow.js';
5
+ export { search, renderSearch, type SearchHit, type SearchOptions, type SearchResult } from './queries/search.js';
6
+ export { investigate, renderInvestigate, type InvestigateChain, type InvestigateExcerpt, type InvestigateOptions, type InvestigateResult } from './queries/investigate.js';
5
7
  export { inferFileRoles, ROLE_TAGS } from './scan/roles.js';
6
8
  export { neighborhood, UnknownFileError, type Neighborhood, type NeighborhoodEntry, type NeighborhoodOptions } from './queries/neighborhood.js';
7
9
  export { rankHubs as hubs } from './graph/topology.js';
package/dist/src/index.js CHANGED
@@ -2,6 +2,8 @@
2
2
  export { scan } from './scan/scan.js';
3
3
  export { renderMap, isTestFile } from './queries/map.js';
4
4
  export { flow, impact, renderFlow, UnknownSymbolError } from './queries/flow.js';
5
+ export { search, renderSearch } from './queries/search.js';
6
+ export { investigate, renderInvestigate } from './queries/investigate.js';
5
7
  export { inferFileRoles, ROLE_TAGS } from './scan/roles.js';
6
8
  export { neighborhood, UnknownFileError } from './queries/neighborhood.js';
7
9
  export { rankHubs as hubs } from './graph/topology.js';
@@ -1,6 +1,11 @@
1
1
  import { type EffortLevel } from './scout.js';
2
2
  export declare const BLOCK_START = "<!-- faber-atlas:start -->";
3
3
  export declare const BLOCK_END = "<!-- faber-atlas:end -->";
4
+ /** Claude Code's global instructions (`~/.claude/CLAUDE.md`) get their own block (02/AC-21). */
5
+ export declare const RULES_BLOCK_START = "<!-- faber-atlas-rules:start -->";
6
+ export declare const RULES_BLOCK_END = "<!-- faber-atlas-rules:end -->";
7
+ /** The Claude Code permission rule that lets every Atlas tool run without a prompt (02/AC-22). */
8
+ export declare const CLAUDE_ALLOW_RULE = "mcp__faber-atlas";
4
9
  export type EngineName = 'claude-code' | 'claude-desktop' | 'antigravity' | 'cursor' | 'codex';
5
10
  export interface EngineSpec {
6
11
  name: EngineName;
@@ -15,7 +20,7 @@ export interface EngineSpec {
15
20
  }
16
21
  export interface FilePlan {
17
22
  filePath: string;
18
- kind: 'mcp-config' | 'agents-md' | 'scout-agent' | 'scout-rules';
23
+ kind: 'mcp-config' | 'agents-md' | 'scout-agent' | 'scout-rules' | 'rules' | 'permissions' | 'hooks';
19
24
  engine: EngineName | 'project';
20
25
  before: string | null;
21
26
  after: string;
@@ -41,6 +46,12 @@ export interface InitOptions {
41
46
  /** Override default Scout effort for engines that support it (default: low). */
42
47
  scoutEffort?: EffortLevel;
43
48
  userHome?: string;
49
+ /** Add the Atlas instruction block to Claude Code's global CLAUDE.md (default: true; `--no-rules`). */
50
+ rules?: boolean;
51
+ /** Let Atlas's read-only tools run without a prompt in Claude Code (default: true; `--no-allow`). */
52
+ allow?: boolean;
53
+ /** Install the Claude Code PreToolUse Grep enrich hook (default: true; `--no-hooks`). */
54
+ hooks?: boolean;
44
55
  }
45
56
  export interface InitResult {
46
57
  root: string;
@@ -53,6 +64,26 @@ export interface InitResult {
53
64
  }
54
65
  export declare function getEngineSpecs(): Record<EngineName, EngineSpec>;
55
66
  export declare function detectTargetEngines(userHome: string, requested?: EngineName[]): EngineName[];
67
+ /**
68
+ * Claude Code shows MCP tools by name only until the model loads them, so without this block it used Atlas in 0 of 4
69
+ * measured questions (2026-11-28). The block says when to reach for Atlas and how to load its tools. Without the Scout
70
+ * (`--no-scout`) it leaves out the sentence that delegates to it (`04/FR-09`).
71
+ */
72
+ export declare function renderClaudeRulesBlock(options?: {
73
+ scout?: boolean;
74
+ }): string;
75
+ export declare function claudeRulesPath(userHome: string): string;
76
+ export declare function claudeSettingsPath(userHome: string): string;
77
+ /** A managed block between two markers: replaced in place, added at the end, or removed. */
78
+ export declare function upsertBlock(existing: string, block: string, start: string, end: string): string;
79
+ export declare function removeBlock(existing: string, start: string, end: string): string;
80
+ export declare const PRE_GREP_HOOK_MARK = "@fabersep/atlas pre-grep";
81
+ export declare const PRE_GREP_HOOK_COMMAND = "npx -y @fabersep/atlas pre-grep";
82
+ export declare const PRE_PROMPT_HOOK_MARK = "@fabersep/atlas pre-prompt";
83
+ export declare const PRE_PROMPT_HOOK_COMMAND = "npx -y @fabersep/atlas pre-prompt";
84
+ export declare const PRE_INVOKE_HOOK_MARK = "@fabersep/atlas pre-invoke";
85
+ export declare const PRE_INVOKE_HOOK_COMMAND = "npx -y @fabersep/atlas pre-invoke";
86
+ export declare function antigravityHooksPath(userHome: string): string;
56
87
  export declare function renderAgentsBlock(): string;
57
88
  export declare function upsertManagedBlock(existing: string, block: string): string;
58
89
  export declare function removeManagedBlock(existing: string): string;
@@ -4,6 +4,11 @@ import path from 'node:path';
4
4
  import { antigravityRulesPath, claudeScoutFilePath, defaultScoutEffort, defaultScoutModel, removeScoutBlock, renderAntigravityScoutBlock, renderClaudeScoutAgent, upsertScoutBlock, } from './scout.js';
5
5
  export const BLOCK_START = '<!-- faber-atlas:start -->';
6
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';
7
12
  export function getEngineSpecs() {
8
13
  return {
9
14
  'claude-code': {
@@ -49,6 +54,148 @@ export function detectTargetEngines(userHome, requested) {
49
54
  detected.push('claude-code');
50
55
  return detected;
51
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
+ }
52
199
  export function renderAgentsBlock() {
53
200
  return [
54
201
  BLOCK_START,
@@ -231,6 +378,53 @@ export function planOrApplyInit(options = {}) {
231
378
  ...(undo && sBefore !== null ? { deleted: true } : {}),
232
379
  });
233
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
+ }
234
428
  if (includeScout && engineName === 'antigravity') {
235
429
  const block = renderAntigravityScoutBlock(options.scoutModel ?? defaultScoutModel('antigravity'));
236
430
  plans.push(blockPlan(antigravityRulesPath(userHome), 'scout-rules', 'antigravity', undo, (text) => undo ? removeScoutBlock(text) : upsertScoutBlock(text, block)));
@@ -38,20 +38,26 @@ export function renderClaudeScoutAgent(model = 'haiku', effort = 'low') {
38
38
  return [
39
39
  '---',
40
40
  'name: atlas-scout',
41
- 'description: Fast, read-only codebase explorer powered by FaberSEP Atlas MCP. Delegate code discovery, call-chain tracing, and impact analysis here before editing.',
41
+ 'description: Fast, read-only codebase explorer powered by FaberSEP Atlas MCP. Delegate open-ended, multi-file, cross-layer exploration with unknown entry points here before editing.',
42
42
  `model: ${model}`,
43
43
  `effort: ${effort}`,
44
- 'tools: mcp__faber-atlas__map, mcp__faber-atlas__brief, mcp__faber-atlas__neighborhood, mcp__faber-atlas__flow, mcp__faber-atlas__impact, mcp__faber-atlas__hubs, mcp__faber-atlas__health, Read',
44
+ 'tools: mcp__faber-atlas__investigate, mcp__faber-atlas__search, mcp__faber-atlas__map, mcp__faber-atlas__brief, mcp__faber-atlas__neighborhood, mcp__faber-atlas__flow, mcp__faber-atlas__impact, mcp__faber-atlas__hubs, mcp__faber-atlas__health, Read, Grep, Glob',
45
45
  '---',
46
46
  '',
47
- 'You are **Atlas Scout**, a read-only codebase explorer. Your job is to locate exact `file:line` targets, call chains, and affected callers for the primary model using minimal tokens.',
47
+ 'You are **Atlas Scout**, a read-only codebase explorer. Your job is to locate exact `file:line` targets, call/event chains, and affected tests for the primary model using minimal turns and tokens.',
48
48
  '',
49
49
  '## Protocol',
50
- '1. Start with `map(zoom=0)` to identify relevant modules (~200 tokens).',
51
- '2. Narrow down with `map(folder="<dir>", zoom=1)` to find exact files and top-level symbols.',
52
- '3. Trace execution with `flow(symbol)` (downstream) or `impact(symbol)` (upstream callers & entrypoints).',
53
- '4. Fetch signatures via `brief(files)` or `neighborhood(files, budget=...)` before reading raw files.',
54
- '5. Return a concise structured summary: verified `file:line` pointers, relevant flow/impact chains, and any test files that must be updated. Never edit files.',
50
+ '1. Start with `investigate(query)` for open-ended questions (returns search hits, flow/impact chains, budgeted code excerpts, and related tests in one call), or `search(query)` / `map(zoom=0)` when you need a layout overview.',
51
+ '2. Trace remaining gaps with `flow(symbol)` (downstream) or `impact(symbol)` (upstream callers & entrypoints).',
52
+ '3. Fetch signatures via `brief(files)` or `neighborhood(files, budget=...)` before reading raw files; `Read` only the lines you must verify.',
53
+ '4. If a tool answers that the folder is not a project, call it again with `root` set to the absolute path of the project.',
54
+ '5. Never edit files.',
55
+ '',
56
+ '## Execution & Budget',
57
+ '- Batch independent tool calls in parallel in the same turn (e.g., multiple `flow`, `impact`, or `Read` calls at once).',
58
+ '- Target at most 4 tool-calling turns (hard stop at 5). Never spiral into single-file sequential reads.',
59
+ '- Use `Grep`/`Glob` as a fallback for literal strings, config keys, or dynamic event/registry wiring that Atlas does not index.',
60
+ '- Keep the final report <= 400 words: verified `file:line` pointers, call/event chains, affected tests, and a 1-line **Coverage** note listing what you searched and any dynamic links you could not statically verify.',
55
61
  '',
56
62
  ].join('\n');
57
63
  }
@@ -60,10 +66,13 @@ export function renderAntigravityScoutBlock(model = 'flash') {
60
66
  SCOUT_BLOCK_START,
61
67
  '## Atlas Scout (Code Discovery)',
62
68
  '',
63
- `For codebase exploration, call tracing, or impact analysis, delegate a read-only subagent with \`Model: "${model}"\` using the \`faber-atlas\` MCP tools:`,
64
- '1. Start with `map(zoom=0)` -> `map(folder=..., zoom=1)` to locate target files and symbols.',
65
- '2. Use `flow(symbol)` / `impact(symbol)` to trace calls, implementations, and async events/jobs, and `brief` / `neighborhood` for signatures.',
66
- '3. Return only verified `file:line` pointers, flow summaries, and affected tests to the primary session.',
69
+ `**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 with unknown entry points, use a read-only \`atlas-scout\` subagent with MCP access (built-in \`research\` has no MCP tools): call \`define_subagent\` once with \`Name: "atlas-scout"\`, \`EnableMCPTools: true\`, \`EnableWriteTools: false\`, then call \`invoke_subagent\` with \`TypeName: "atlas-scout"\` and \`Model: "${model}"\` (passing the user's question and workspace \`root\`), and 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 — skip the Scout for a named file or single symbol, literal text, a localized edit, or context already loaded. When the user names a symbol and asks what changing it breaks, call \`faber-atlas\` \`impact\` yourself first (\`call_mcp_tool\` with \`ServerName: "faber-atlas"\`, \`ToolName: "impact"\`, and \`root\`) before any grep or \`run_command\`.`,
70
+ '',
71
+ 'SystemPrompt / instructions for `atlas-scout`:',
72
+ '1. Start with `call_mcp_tool(ServerName: "faber-atlas", ToolName: "investigate", Arguments: {query, root})` (or `search` / `map` zoom=0) and batch independent `flow`/`impact`/`read_file` calls in parallel — target at most 4 turns (hard stop at 5).',
73
+ '2. Use `Grep`/`Glob` only as a fallback for literal strings, config keys, or dynamic event/registry wiring that Atlas does not index.',
74
+ '3. Return a report <= 400 words with verified `file:line` pointers, call/event chains, affected tests, and a 1-line **Coverage** note.',
75
+ '4. Antigravity starts the `faber-atlas` server outside the workspace, so pass `root` (the absolute path of the workspace you are working in) on every `faber-atlas` call.',
67
76
  SCOUT_BLOCK_END,
68
77
  ].join('\n');
69
78
  }