@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,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
+ }
@@ -0,0 +1,17 @@
1
+ import type { FileRecord, GraphEdge, NodeType } from '../model.js';
2
+ /** Nodes and edges of the topology graph: files that import, their top-level declarations, and the links between them. */
3
+ export interface RawNode {
4
+ id: string;
5
+ label: string;
6
+ path: string;
7
+ type: NodeType;
8
+ language?: string;
9
+ line?: number;
10
+ tokenEstimate?: number;
11
+ }
12
+ export declare const fileId: (path: string) => string;
13
+ /** The graph of the files whose language has imports (`codeLanguages`); data files and unsupported files are not part of it. */
14
+ export declare function buildGraph(records: FileRecord[], codeLanguages: Set<string>): {
15
+ nodes: RawNode[];
16
+ edges: GraphEdge[];
17
+ };
@@ -0,0 +1,41 @@
1
+ const SYMBOL_NODE_KINDS = new Set(['class', 'interface', 'enum', 'mixin', 'extension', 'type', 'function']);
2
+ export const fileId = (path) => `file:${path}`;
3
+ const symbolId = (path, name) => `symbol:${path}#${name}`;
4
+ /** `State<HomeScreen>` names the type `State`; `http.Client` names `Client`. */
5
+ const typeName = (ref) => ref.replace(/<.*$/s, '').split('.').pop().trim();
6
+ function fileNode(r) {
7
+ return { id: fileId(r.path), label: r.path.split('/').pop(), path: r.path, type: 'file', language: r.language, tokenEstimate: r.rawTokens };
8
+ }
9
+ function symbolNodes(r) {
10
+ return r.symbols
11
+ .filter((s) => SYMBOL_NODE_KINDS.has(s.kind))
12
+ .map((s) => ({ id: symbolId(r.path, s.name), label: s.name, path: r.path, type: s.kind, line: s.lineStart }));
13
+ }
14
+ /** Import edges between project files, once per pair. */
15
+ function importEdges(r, files) {
16
+ const targets = new Set(r.imports.filter((i) => i.kind === 'file' && i.target && files.has(i.target) && i.target !== r.path).map((i) => i.target));
17
+ return [...targets].sort().map((t) => ({ source: fileId(r.path), target: fileId(t), type: 'imports' }));
18
+ }
19
+ /** extends, with and implements: to a declaration of the same file or of a file it imports, found by name. */
20
+ function heritageEdges(r, byFile) {
21
+ const visible = [r.path, ...r.imports.filter((i) => i.kind === 'file' && i.target).map((i) => i.target)];
22
+ const find = (name) => visible.find((p) => byFile.get(p)?.has(name));
23
+ const link = (s, refs, type) => (refs ?? []).map(typeName).flatMap((name) => {
24
+ const at = find(name);
25
+ return at ? [{ source: symbolId(r.path, s.name), target: symbolId(at, name), type }] : [];
26
+ });
27
+ return r.symbols.flatMap((s) => [...link(s, [...(s.extends ?? []), ...(s.mixins ?? [])], 'extends'), ...link(s, s.implements, 'implements')]);
28
+ }
29
+ /** The graph of the files whose language has imports (`codeLanguages`); data files and unsupported files are not part of it. */
30
+ export function buildGraph(records, codeLanguages) {
31
+ const code = records.filter((r) => codeLanguages.has(r.language));
32
+ const files = new Set(code.map((r) => r.path));
33
+ const declared = new Map(code.map((r) => [r.path, new Set(symbolNodes(r).map((n) => n.label))]));
34
+ const nodes = code.flatMap((r) => [fileNode(r), ...symbolNodes(r)]);
35
+ const edges = code.flatMap((r) => [
36
+ ...importEdges(r, files),
37
+ ...symbolNodes(r).map((n) => ({ source: fileId(r.path), target: n.id, type: 'defines' })),
38
+ ...heritageEdges(r, declared),
39
+ ]);
40
+ return { nodes, edges };
41
+ }
@@ -0,0 +1,12 @@
1
+ import type { GraphEdge } from '../model.js';
2
+ /** In- and out-degree per node, counting only the given edge types. */
3
+ export declare function degrees(edges: GraphEdge[], types: Set<string>): {
4
+ inDegree: Map<string, number>;
5
+ outDegree: Map<string, number>;
6
+ };
7
+ /** PageRank over directed edges among `ids` (a node that links nowhere shares its rank with every node), rounded to 6 places. */
8
+ export declare function pageRank(ids: string[], edges: GraphEdge[]): Map<string, number>;
9
+ /** Import cycles found by a depth-first search in path order, each starting at its smallest file, at most 20. */
10
+ export declare function cycles(ids: string[], edges: GraphEdge[]): string[][];
11
+ /** A file's cluster: its folder, at most two levels deep (`src/orders`, `lib/screens`); `.` for the root. */
12
+ export declare function clusterOf(path: string): string;
@@ -0,0 +1,75 @@
1
+ /** Graph measures: degrees, PageRank, cycles and clusters. Every result is deterministic for the same graph. */
2
+ const DAMPING = 0.85;
3
+ const ITERATIONS = 100;
4
+ const TOLERANCE = 1e-10;
5
+ const MAX_CYCLES = 20;
6
+ /** In- and out-degree per node, counting only the given edge types. */
7
+ export function degrees(edges, types) {
8
+ const inDegree = new Map();
9
+ const outDegree = new Map();
10
+ for (const e of edges.filter((e) => types.has(e.type))) {
11
+ outDegree.set(e.source, (outDegree.get(e.source) ?? 0) + 1);
12
+ inDegree.set(e.target, (inDegree.get(e.target) ?? 0) + 1);
13
+ }
14
+ return { inDegree, outDegree };
15
+ }
16
+ /** PageRank over directed edges among `ids` (a node that links nowhere shares its rank with every node), rounded to 6 places. */
17
+ export function pageRank(ids, edges) {
18
+ const n = ids.length;
19
+ const out = new Map(ids.map((id) => [id, []]));
20
+ for (const e of edges)
21
+ if (out.has(e.source) && out.has(e.target))
22
+ out.get(e.source).push(e.target);
23
+ let rank = new Map(ids.map((id) => [id, 1 / n]));
24
+ for (let i = 0; i < ITERATIONS; i++) {
25
+ const dangling = ids.filter((id) => out.get(id).length === 0).reduce((sum, id) => sum + rank.get(id), 0);
26
+ const next = new Map(ids.map((id) => [id, (1 - DAMPING) / n + (DAMPING * dangling) / n]));
27
+ for (const id of ids)
28
+ for (const t of out.get(id))
29
+ next.set(t, next.get(t) + (DAMPING * rank.get(id)) / out.get(id).length);
30
+ const change = ids.reduce((sum, id) => sum + Math.abs(next.get(id) - rank.get(id)), 0);
31
+ rank = next;
32
+ if (change < TOLERANCE)
33
+ break;
34
+ }
35
+ return new Map(ids.map((id) => [id, Number(rank.get(id).toFixed(6))]));
36
+ }
37
+ /** Import cycles found by a depth-first search in path order, each starting at its smallest file, at most 20. */
38
+ export function cycles(ids, edges) {
39
+ const adj = new Map(ids.map((id) => [id, []]));
40
+ for (const e of edges)
41
+ if (adj.has(e.source) && adj.has(e.target))
42
+ adj.get(e.source).push(e.target);
43
+ adj.forEach((targets) => targets.sort());
44
+ const found = new Map();
45
+ const state = new Map();
46
+ const stack = [];
47
+ const visit = (id) => {
48
+ state.set(id, 'open');
49
+ stack.push(id);
50
+ for (const t of adj.get(id)) {
51
+ if (state.get(t) === 'open')
52
+ record(found, stack.slice(stack.indexOf(t)));
53
+ else if (!state.has(t))
54
+ visit(t);
55
+ }
56
+ stack.pop();
57
+ state.set(id, 'done');
58
+ };
59
+ for (const id of [...ids].sort())
60
+ if (!state.has(id))
61
+ visit(id);
62
+ return [...found.values()].slice(0, MAX_CYCLES);
63
+ }
64
+ function record(found, loop) {
65
+ const start = loop.indexOf([...loop].sort()[0]);
66
+ const rotated = [...loop.slice(start), ...loop.slice(0, start)];
67
+ const key = rotated.join('>');
68
+ if (!found.has(key))
69
+ found.set(key, [...rotated, rotated[0]]);
70
+ }
71
+ /** A file's cluster: its folder, at most two levels deep (`src/orders`, `lib/screens`); `.` for the root. */
72
+ export function clusterOf(path) {
73
+ const parts = path.split('/').slice(0, -1);
74
+ return parts.length ? parts.slice(0, 2).join('/') : '.';
75
+ }
@@ -0,0 +1,5 @@
1
+ import type { FileRecord, GraphNode, Hub, Topology } from '../model.js';
2
+ import type { Generator } from '../model.js';
3
+ /** Files by centrality score, then PageRank, then path. */
4
+ export declare function rankHubs(nodes: GraphNode[], top: number): Hub[];
5
+ export declare function buildTopology(records: FileRecord[], codeLanguages: Set<string>, generator: Generator): Topology;
@@ -0,0 +1,54 @@
1
+ import { buildGraph } from './build.js';
2
+ import { clusterOf, cycles, degrees, pageRank } from './metrics.js';
3
+ /**
4
+ * The topology graph (topology.json). File degrees count import edges; a declaration's degrees count the
5
+ * extends and implements edges. `centralityScore` is twice the in-degree plus the out-degree; `pageRank` ranks files
6
+ * by the import graph.
7
+ */
8
+ const TOP_HUBS = 10;
9
+ const FILE_EDGES = new Set(['imports']);
10
+ const SYMBOL_EDGES = new Set(['extends', 'implements']);
11
+ const toHub = (n) => ({ id: n.id, path: n.path, inDegree: n.inDegree, outDegree: n.outDegree, centralityScore: n.centralityScore, pageRank: n.pageRank });
12
+ /** Files by centrality score, then PageRank, then path. */
13
+ export function rankHubs(nodes, top) {
14
+ return nodes
15
+ .filter((n) => n.type === 'file')
16
+ .sort((a, b) => b.centralityScore - a.centralityScore || b.pageRank - a.pageRank || (a.path < b.path ? -1 : 1))
17
+ .slice(0, top)
18
+ .map(toHub);
19
+ }
20
+ function clusters(nodes) {
21
+ const counts = new Map();
22
+ for (const n of nodes)
23
+ counts.set(n.cluster, (counts.get(n.cluster) ?? 0) + 1);
24
+ return [...counts].map(([name, nodeCount]) => ({ name, nodeCount })).sort((a, b) => b.nodeCount - a.nodeCount || (a.name < b.name ? -1 : 1));
25
+ }
26
+ export function buildTopology(records, codeLanguages, generator) {
27
+ const { nodes: raw, edges } = buildGraph(records, codeLanguages);
28
+ const fileIds = raw.filter((n) => n.type === 'file').map((n) => n.id);
29
+ const fileDegrees = degrees(edges, FILE_EDGES);
30
+ const symbolDegrees = degrees(edges, SYMBOL_EDGES);
31
+ const ranks = pageRank(fileIds, edges.filter((e) => e.type === 'imports'));
32
+ const nodes = raw.map((n) => {
33
+ const d = n.type === 'file' ? fileDegrees : symbolDegrees;
34
+ const inDegree = d.inDegree.get(n.id) ?? 0;
35
+ const outDegree = d.outDegree.get(n.id) ?? 0;
36
+ return { ...n, inDegree, outDegree, centralityScore: inDegree * 2 + outDegree, pageRank: ranks.get(n.id) ?? 0, cluster: clusterOf(n.path) };
37
+ });
38
+ const count = nodes.length;
39
+ return {
40
+ ...generator,
41
+ summary: {
42
+ totalFiles: fileIds.length,
43
+ totalSymbols: count - fileIds.length,
44
+ totalNodes: count,
45
+ totalEdges: edges.length,
46
+ density: count > 1 ? Number((edges.length / (count * (count - 1))).toFixed(5)) : 0,
47
+ circularDependencies: cycles(fileIds, edges.filter((e) => e.type === 'imports')).map((c) => ({ cycle: c.map((id) => id.replace(/^file:/, '')) })),
48
+ clusters: clusters(nodes),
49
+ topHubs: rankHubs(nodes, TOP_HUBS),
50
+ },
51
+ nodes,
52
+ edges,
53
+ };
54
+ }
@@ -0,0 +1,2 @@
1
+ import { type HealthComparison, type HealthReport } from './types.js';
2
+ export declare function compareHealth(before: HealthReport, after: HealthReport): HealthComparison;
@@ -0,0 +1,38 @@
1
+ import { LIMIT_NAMES, HealthLimitsError } from './types.js';
2
+ /**
3
+ * What a change did to code health (FR-07, CIN-18): of two reports of the same project made with the same limits, the
4
+ * files and functions that crossed a limit (length or nesting), the new duplicated blocks and import cycles, and the
5
+ * totals before and after.
6
+ */
7
+ const RANK = { soft: 1, hard: 2 };
8
+ const functionKey = (f) => `${f.path}\u0000${f.name}`;
9
+ /** A cycle in a stable form, so the same cycle found from another start file is the same cycle. */
10
+ function cycleKey(cycle) {
11
+ const nodes = cycle[0] === cycle[cycle.length - 1] ? cycle.slice(0, -1) : cycle;
12
+ const start = nodes.indexOf([...nodes].sort()[0]);
13
+ return [...nodes.slice(start), ...nodes.slice(0, start)].join('\u0000');
14
+ }
15
+ function sameLimits(before, after) {
16
+ const differ = LIMIT_NAMES.filter((name) => before.limits[name] !== after.limits[name]);
17
+ if (differ.length)
18
+ throw new HealthLimitsError(`The two reports were made with different limits (${differ.join(', ')}); make both with the same limits.`);
19
+ }
20
+ export function compareHealth(before, after) {
21
+ sameLimits(before, after);
22
+ const filesBefore = new Set(before.files.map((f) => f.path));
23
+ const functionsBefore = new Map(before.functions.map((f) => [functionKey(f), RANK[f.limit]]));
24
+ const deepBefore = new Set(before.nesting.map(functionKey));
25
+ const keysBefore = new Set(before.duplicates.flatMap((d) => d.keys));
26
+ const cyclesBefore = new Set(before.cycles.map(cycleKey));
27
+ const linesBefore = new Map(before.notMeasured.map((f) => [f.path, f.lines]));
28
+ return {
29
+ limits: after.limits,
30
+ files: after.files.filter((f) => !filesBefore.has(f.path)),
31
+ functions: after.functions.filter((f) => (functionsBefore.get(functionKey(f)) ?? 0) < RANK[f.limit]),
32
+ nesting: after.nesting.filter((f) => !deepBefore.has(functionKey(f))),
33
+ duplicates: after.duplicates.filter((d) => !d.keys.some((k) => keysBefore.has(k))),
34
+ cycles: after.cycles.filter((c) => !cyclesBefore.has(cycleKey(c))),
35
+ notMeasured: after.notMeasured.filter((f) => linesBefore.get(f.path) !== f.lines),
36
+ totals: { before: before.totals, after: after.totals },
37
+ };
38
+ }
@@ -0,0 +1,11 @@
1
+ import type { DuplicateBlock } from './types.js';
2
+ /**
3
+ * Duplicated blocks: the same normalized run of significant lines in two places. Blank lines and lines of brackets or
4
+ * separators only are not significant; whitespace inside a line is collapsed. Each window of `minLines` significant
5
+ * lines is hashed; consecutive duplicated windows of one file form a block, and blocks sharing a window are copies.
6
+ */
7
+ export interface SourceFile {
8
+ path: string;
9
+ content: string;
10
+ }
11
+ export declare function findDuplicates(files: SourceFile[], minLines: number): DuplicateBlock[];
@@ -0,0 +1,66 @@
1
+ import crypto from 'node:crypto';
2
+ const TRIVIAL = /^[\s{}()[\];,]*$/;
3
+ function significantLines(content) {
4
+ return content.split('\n').flatMap((raw, i) => {
5
+ const text = raw.trim().replace(/\s+/g, ' ');
6
+ return TRIVIAL.test(text) ? [] : [{ text, number: i + 1 }];
7
+ });
8
+ }
9
+ const hashOf = (lines) => crypto.createHash('sha1').update(lines.map((l) => l.text).join('\n')).digest('hex').slice(0, 12);
10
+ function windowsOf(file, minLines) {
11
+ const lines = significantLines(file.content);
12
+ return Array.from({ length: Math.max(0, lines.length - minLines + 1) }, (_, i) => hashOf(lines.slice(i, i + minLines)));
13
+ }
14
+ /** Where each window hash starts; a hash is duplicated when it starts in two files or twice without overlapping. */
15
+ function duplicatedHashes(windows, minLines) {
16
+ const starts = new Map();
17
+ for (const [path, hashes] of windows)
18
+ hashes.forEach((h, index) => starts.set(h, [...(starts.get(h) ?? []), { path, index }]));
19
+ const duplicated = new Set();
20
+ for (const [hash, at] of starts) {
21
+ const apart = at.some((a, i) => at.slice(i + 1).some((b) => b.path !== a.path || Math.abs(b.index - a.index) >= minLines));
22
+ if (apart)
23
+ duplicated.add(hash);
24
+ }
25
+ return duplicated;
26
+ }
27
+ /** Runs of consecutive duplicated windows in one file, as blocks with their line range. */
28
+ function blocksOf(file, hashes, duplicated, minLines) {
29
+ const lines = significantLines(file.content);
30
+ const blocks = [];
31
+ let open = null;
32
+ const close = (last) => {
33
+ if (open)
34
+ blocks.push({ path: file.path, lineStart: lines[open.first].number, lineEnd: lines[last + minLines - 1].number, keys: open.keys });
35
+ open = null;
36
+ };
37
+ hashes.forEach((h, i) => {
38
+ if (!duplicated.has(h))
39
+ return close(i - 1);
40
+ open = open ?? { first: i, keys: [] };
41
+ open.keys.push(h);
42
+ });
43
+ close(hashes.length - 1);
44
+ return blocks;
45
+ }
46
+ /** Blocks that share a window are copies of each other (union of the blocks by shared keys). */
47
+ function groupCopies(blocks) {
48
+ const groups = [];
49
+ for (const block of blocks) {
50
+ const keys = new Set(block.keys);
51
+ const joined = groups.filter((g) => g.some((b) => b.keys.some((k) => keys.has(k))));
52
+ const merged = [...joined.flat(), block];
53
+ groups.splice(0, groups.length, ...groups.filter((g) => !joined.includes(g)), merged);
54
+ }
55
+ return groups.filter((g) => g.length > 1).map((g) => ({
56
+ keys: [...new Set(g.flatMap((b) => b.keys))].sort(),
57
+ lines: Math.max(...g.map((b) => b.lineEnd - b.lineStart + 1)),
58
+ locations: g.map(({ path, lineStart, lineEnd }) => ({ path, lineStart, lineEnd })).sort((a, b) => a.path.localeCompare(b.path) || a.lineStart - b.lineStart),
59
+ }));
60
+ }
61
+ export function findDuplicates(files, minLines) {
62
+ const windows = new Map(files.map((f) => [f.path, windowsOf(f, minLines)]));
63
+ const duplicated = duplicatedHashes(windows, minLines);
64
+ const blocks = files.flatMap((f) => blocksOf(f, windows.get(f.path), duplicated, minLines));
65
+ return groupCopies(blocks).sort((a, b) => a.locations[0].path.localeCompare(b.locations[0].path) || a.locations[0].lineStart - b.locations[0].lineStart);
66
+ }
@@ -0,0 +1,12 @@
1
+ import type { CodeMap, Topology } from '../model.js';
2
+ import type { LanguagePack } from '../packs/pack.js';
3
+ import { type HealthLimits, type HealthReport } from './types.js';
4
+ /**
5
+ * The code health of a scanned folder (FR-07, CIN-18): files over the line limit, functions over the soft and hard
6
+ * limits and over the nesting limit, duplicated blocks and import cycles, from the scan's outputs and the files themselves. Only files a code pack
7
+ * declares are measured; data files (JSON, YAML) are left out, and files no pack reads are listed as not measured.
8
+ */
9
+ /** Checks that every limit was passed as a positive whole number; no limit is ever assumed. */
10
+ export declare function checkLimits(input: Partial<Record<keyof HealthLimits, unknown>>): HealthLimits;
11
+ /** The health report of `root`, whose scan outputs are `map` and `topology`. */
12
+ export declare function health(map: CodeMap, topology: Topology, root: string, limits: HealthLimits, packs: LanguagePack[]): HealthReport;