@dimassetoid/septum-mcp 0.2.1 → 0.5.0

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 (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -0,0 +1,457 @@
1
+ import { pageContext, response, budgetedResponse, type ContextItem, type SourceItem } from "./context-page.ts";
2
+ import { retrieveUniversalContext } from "./universal-context.ts";
3
+ import ts from "typescript";
4
+ import { bindContextFile, type ContextValue } from "./typescript-references.ts";
5
+ import { resolve } from "node:path";
6
+ import type { SeptumRepository } from "../database/repository.ts";
7
+ import type { ValidatedSeptumConfig } from "../config/schema.ts";
8
+ import type { ImportRelationship, SymbolReference } from "../../types/index.ts";
9
+ import { computeContentHash } from "../ingestion/hasher.ts";
10
+ import { PARSER_FINGERPRINT } from "../parser/language-capabilities.ts";
11
+ import { RESOLVER_REVISION } from "../resolver/import-resolver.ts";
12
+ import { assertPathContained } from "../resolver/path-resolver.ts";
13
+ import { collectSourceSkips, readSourceFile, SOURCE_READ_REVISION } from "../resources/source-files.ts";
14
+ import { symbolTargetId } from "./symbol-evidence.ts";
15
+
16
+ export const CONTEXT_POLICY = "referenced-typescript-declarations/v4";
17
+ export const MIN_CONTEXT_BUDGET = 2048;
18
+ export const MAX_CONTEXT_BUDGET = 2 * 1024 * 1024;
19
+ export const DEFAULT_CONTEXT_DEPTH = 2;
20
+ export const MAX_CONTEXT_DEPTH = 4;
21
+ const MAX_ITEMS = 256;
22
+ const MAX_SOURCE_BYTES = 8 * 1024 * 1024;
23
+
24
+ export interface ContextQuery {
25
+ query?: string;
26
+ symbol?: string;
27
+ symbol_ref?: SymbolReference;
28
+ file_path?: string;
29
+ domain?: string;
30
+ budget_bytes?: number;
31
+ max_depth?: number;
32
+ continuation?: string;
33
+ }
34
+ function canonical(value: unknown): unknown {
35
+ if (Array.isArray(value)) return value.map(canonical);
36
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value)
37
+ .sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, canonical(entry)]));
38
+ return value;
39
+ }
40
+ function digest(value: unknown) { return computeContentHash(JSON.stringify(canonical(value))); }
41
+
42
+ type QueuedNode = { path: string; node: ts.Node; depth: number; hopDepth: number; reason: SourceItem["reason"]; typeOnlyClass: boolean; arguments?: ContextValue[] };
43
+ type BoundEntry = { text: string; bound: ReturnType<typeof bindContextFile> };
44
+
45
+ interface ContextWalkState {
46
+ repo: SeptumRepository;
47
+ root: string;
48
+ maxDepth: number;
49
+ signal?: AbortSignal;
50
+ targetFilePath: string;
51
+ targetSource: string;
52
+ relationshipsByFile: Map<string, ImportRelationship[]>;
53
+ referencedEdges: Set<ImportRelationship>;
54
+ visited: Set<string>;
55
+ emitted: Set<string>;
56
+ directCallItems: WeakSet<ContextItem>;
57
+ variants: Map<string, Set<string>>;
58
+ files: Map<string, BoundEntry>;
59
+ expansionQueue: QueuedNode[];
60
+ items: ContextItem[];
61
+ freshness: "current" | "stale" | "unavailable";
62
+ incomplete: boolean;
63
+ capacityOmissions: number;
64
+ unexpandedFiles: number;
65
+ sourceBytes: number;
66
+ }
67
+
68
+ function getFileRelationships(state: ContextWalkState, filePath: string): ImportRelationship[] {
69
+ let rels = state.relationshipsByFile.get(filePath);
70
+ if (!rels) {
71
+ rels = state.repo.getImportRelationships(state.root, filePath);
72
+ state.relationshipsByFile.set(filePath, rels);
73
+ }
74
+ return rels;
75
+ }
76
+
77
+ function addContextItem(state: ContextWalkState, item: ContextItem) {
78
+ if (state.items.length < MAX_ITEMS) state.items.push(item);
79
+ else { state.incomplete = true; state.capacityOmissions++; }
80
+ }
81
+
82
+ function addContextDiagnostic(state: ContextWalkState, reason: string, file_path?: string, detail?: string) {
83
+ state.incomplete = true;
84
+ addContextItem(state, { kind: "diagnostic", reason, file_path, detail });
85
+ }
86
+
87
+ function readIndexedSource(state: ContextWalkState, path: string): string | undefined {
88
+ state.signal?.throwIfAborted();
89
+ try {
90
+ assertPathContained(path, state.root, "Context source");
91
+ const source = readSourceFile(resolve(state.root, path));
92
+ state.sourceBytes += Buffer.byteLength(source, "utf8");
93
+ if (state.sourceBytes > MAX_SOURCE_BYTES) { addContextDiagnostic(state, "analysis_source_byte_limit", path); return; }
94
+ if (computeContentHash(source) !== state.repo.getFileByPath(path)?.content_hash) {
95
+ state.freshness = "stale";
96
+ addContextDiagnostic(state, "source_differs_from_index", path);
97
+ return;
98
+ }
99
+ return source;
100
+ } catch {
101
+ if (state.freshness !== "stale") state.freshness = "unavailable";
102
+ addContextDiagnostic(state, "source_unavailable_or_out_of_scope", path);
103
+ }
104
+ }
105
+
106
+ function addSymbolSourceItem(
107
+ state: ContextWalkState,
108
+ path: string,
109
+ source: string,
110
+ symbol: { name: string; line_start: number; line_end: number },
111
+ reason: SourceItem["reason"],
112
+ depth = 0
113
+ ) {
114
+ const starts = [0];
115
+ const ends: number[] = [];
116
+ for (const match of source.matchAll(/\r\n|\n|\r/g)) { ends.push(match.index!); starts.push(match.index! + match[0].length); }
117
+ ends.push(source.length);
118
+ if (symbol.line_start < 1 || symbol.line_end < symbol.line_start || symbol.line_end > starts.length) {
119
+ addContextDiagnostic(state, "invalid_indexed_span", path);
120
+ return;
121
+ }
122
+ addContextItem(state, {
123
+ kind: "source",
124
+ depth,
125
+ name: symbol.name,
126
+ reason,
127
+ source: {
128
+ file_path: path,
129
+ indexed_content_hash: state.repo.getFileByPath(path)!.content_hash,
130
+ start_line: symbol.line_start,
131
+ end_line: symbol.line_end,
132
+ text: source.slice(starts[symbol.line_start - 1], ends[symbol.line_end - 1]),
133
+ },
134
+ });
135
+ }
136
+
137
+ function hasModuleExecution(node: ts.Node): boolean {
138
+ if (ts.isFunctionLike(node)) return false;
139
+ if (ts.isCallExpression(node) || ts.isNewExpression(node) || ts.isAwaitExpression(node)) return true;
140
+ return ts.forEachChild(node, child => hasModuleExecution(child) || undefined) ?? false;
141
+ }
142
+
143
+ function loadBoundTsFile(state: ContextWalkState, path: string): BoundEntry | undefined {
144
+ if (state.files.has(path)) return state.files.get(path);
145
+ if (state.sourceBytes >= MAX_SOURCE_BYTES || state.files.size >= 64) {
146
+ state.unexpandedFiles++;
147
+ addContextDiagnostic(state, "analysis_file_limit", path);
148
+ return;
149
+ }
150
+ if (!state.repo.getFileByPath(path) || !/\.(?:ts|mts|cts|tsx)$/.test(path)) {
151
+ addContextDiagnostic(state, "dependency_not_indexed_or_unsupported", path);
152
+ return;
153
+ }
154
+ const text = path === state.targetFilePath ? state.targetSource : readIndexedSource(state, path);
155
+ if (text === undefined) return;
156
+ const bound = bindContextFile(path, text);
157
+ const value = { text, bound };
158
+ state.files.set(path, value);
159
+ if (bound.hasErrors) addContextDiagnostic(state, "typescript_syntax_errors", path);
160
+ // Initializers and decorators can execute independently of references; retain relationships and decline module-execution closure.
161
+ if (bound.source.statements.some(node => ts.isImportDeclaration(node) && !node.importClause)) {
162
+ addContextDiagnostic(state, "side_effect_import_not_expanded", path);
163
+ }
164
+ if (bound.source.statements.some(node => ts.isExpressionStatement(node) || ts.isExportDeclaration(node) || ts.isClassDeclaration(node) ||
165
+ (ts.isVariableStatement(node) && hasModuleExecution(node)))) {
166
+ addContextDiagnostic(state, "module_execution_or_reexport_not_expanded", path);
167
+ }
168
+ return value;
169
+ }
170
+
171
+ function isTypeOnlyImportBinding(declaration: ts.ImportDeclaration, exportedName: string): boolean {
172
+ if (declaration.importClause?.isTypeOnly) return true;
173
+ const bindings = declaration.importClause?.namedBindings;
174
+ if (bindings && ts.isNamedImports(bindings)) {
175
+ const matching = bindings.elements.filter(el => (el.propertyName ?? el.name).text === exportedName);
176
+ if (matching.length > 0 && matching.every(el => el.isTypeOnly)) return true;
177
+ }
178
+ return false;
179
+ }
180
+
181
+ function enqueueSymbolNode(
182
+ state: ContextWalkState,
183
+ path: string,
184
+ node: ts.Node,
185
+ depth: number,
186
+ reason: SourceItem["reason"],
187
+ typeOnlyClass = false,
188
+ argumentFacts?: ContextValue[],
189
+ isCall = false,
190
+ hopDepth = depth
191
+ ) {
192
+ const declarationKey = `${path}:${node.pos}:${node.end}:${typeOnlyClass}`;
193
+ const seen = state.variants.get(declarationKey) ?? new Set<string>();
194
+ if (seen.size >= 4) argumentFacts = undefined;
195
+ const variant = JSON.stringify(argumentFacts ?? null);
196
+ seen.add(variant);
197
+ state.variants.set(declarationKey, seen);
198
+ const key = `${declarationKey}:${variant}`;
199
+ if (state.visited.has(key)) return;
200
+ state.visited.add(key);
201
+ if (state.items.length >= MAX_ITEMS) { state.capacityOmissions++; state.incomplete = true; return; }
202
+ const file = loadBoundTsFile(state, path);
203
+ if (!file) return;
204
+ if (reason === "target_implementation") state.emitted.add(declarationKey);
205
+
206
+ if (reason !== "target_implementation" && !state.emitted.has(declarationKey)) {
207
+ state.emitted.add(declarationKey);
208
+ const start = file.bound.source.getLineAndCharacterOfPosition(node.getStart()).line + 1;
209
+ const end = file.bound.source.getLineAndCharacterOfPosition(node.end).line + 1;
210
+ const indexed = state.repo.getSymbolsByFileId(state.repo.getFileByPath(path)!.id).find(s => s.line_start >= start && s.line_end <= end);
211
+ const name = indexed?.name ?? ("name" in node ? (node as ts.NamedDeclaration).name?.getText(file.bound.source) : undefined) ?? "local_declaration";
212
+ if (typeOnlyClass && ts.isClassDeclaration(node)) {
213
+ const contract = file.bound.contract(node);
214
+ addContextItem(state, {
215
+ kind: "type_contract", depth: hopDepth, name, file_path: path, indexed_content_hash: state.repo.getFileByPath(path)!.content_hash,
216
+ start_line: start, end_line: end, projection: "public_instance_signatures", text: contract.text,
217
+ inferred_types: contract.inferred ? "unknown" : "explicit",
218
+ });
219
+ addContextDiagnostic(state, "type_only_class_bodies_omitted", path, "Instance signature projection; constructors, private/static members, bodies and initializers omitted. Inferred types use unknown.");
220
+ } else {
221
+ const before = state.items.length;
222
+ addSymbolSourceItem(state, path, file.text, { name, line_start: start, line_end: end }, reason, hopDepth);
223
+ const item = state.items[before];
224
+ if (item?.kind === "source") {
225
+ item.selection_role = ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node) ? "contract" : "implementation";
226
+ if (isCall) state.directCallItems.add(item);
227
+ }
228
+ }
229
+ }
230
+ state.expansionQueue.push({ path, node, depth, hopDepth, reason, typeOnlyClass, arguments: argumentFacts });
231
+ }
232
+
233
+ async function expandSymbolReferences(state: ContextWalkState, entry: QueuedNode) {
234
+ state.signal?.throwIfAborted();
235
+ const file = loadBoundTsFile(state, entry.path);
236
+ if (!file) return;
237
+ const startLine = file.bound.source.getLineAndCharacterOfPosition(entry.node.getStart()).line + 1;
238
+ const endLine = file.bound.source.getLineAndCharacterOfPosition(entry.node.end).line + 1;
239
+ const fileRels = getFileRelationships(state, entry.path);
240
+ for (const edge of fileRels.filter(e => !entry.typeOnlyClass && e.source.file === entry.path &&
241
+ e.source.line >= startLine && e.source.line <= endLine)) {
242
+ if (entry.path === state.targetFilePath) state.referencedEdges.add(edge);
243
+ if (edge.freshness !== "current" || (edge.resolution.status !== "resolved" && edge.resolution.status !== "external") || edge.resolution.coverage === "conditional") {
244
+ addContextDiagnostic(state, "import_not_fully_resolved", entry.path, `${edge.resolution.source.target}: ${edge.resolution.reason}`);
245
+ }
246
+ }
247
+ const signatureNodes = entry.typeOnlyClass && ts.isClassDeclaration(entry.node) ? file.bound.contract(entry.node).signatures : undefined;
248
+ const refs = file.bound.references(entry.node, entry.arguments, signatureNodes);
249
+ if (refs.prunedBranches && entry.arguments) {
250
+ addContextItem(state, { kind: "selection", reason: "known_call_arguments", file_path: entry.path, start_line: startLine, arguments: entry.arguments, pruned_branches: refs.prunedBranches });
251
+ }
252
+ for (const local of refs.locals) {
253
+ const calls = refs.escapes.has(local) ? [] : refs.calls.filter(call => call.target === local);
254
+ const prevLen = state.expansionQueue.length;
255
+ if (calls.length) for (const call of calls) enqueueSymbolNode(state, entry.path, local, entry.depth, "local_dependency", false, call.arguments, true, entry.hopDepth + 1);
256
+ else enqueueSymbolNode(state, entry.path, local, entry.depth, "local_dependency", entry.typeOnlyClass, undefined, false, entry.hopDepth + 1);
257
+ if (entry.depth === 0) {
258
+ while (state.expansionQueue.length > prevLen) {
259
+ await expandSymbolReferences(state, state.expansionQueue.pop()!);
260
+ }
261
+ }
262
+ }
263
+ const deferredTypeOnlyClassImports: Array<{ dependencyPath: string; effectiveNames: string[]; depth: number; hopDepth: number }> = [];
264
+ for (const [declaration, names] of refs.imports) {
265
+ const sortedNames = [...names].sort();
266
+ const typeOnlyByName = new Map<string, boolean>();
267
+ for (const n of sortedNames) typeOnlyByName.set(n, entry.typeOnlyClass || isTypeOnlyImportBinding(declaration, n));
268
+ const line = file.bound.source.getLineAndCharacterOfPosition(declaration.getStart()).line + 1;
269
+ const moduleName = ts.isStringLiteral(declaration.moduleSpecifier) ? declaration.moduleSpecifier.text : undefined;
270
+ const edge = fileRels.find(e => e.source.file === entry.path && e.source.line === line && e.resolution.source.target === moduleName);
271
+ if (edge && entry.path === state.targetFilePath) state.referencedEdges.add(edge);
272
+ if (!edge || edge.freshness !== "current" || edge.resolution.status !== "resolved" || edge.resolution.coverage === "conditional") {
273
+ addContextDiagnostic(state, "referenced_import_not_expanded", entry.path, `${declaration.getText()}: ${edge?.resolution.reason ?? "relationship_not_found"}`);
274
+ continue;
275
+ }
276
+ const paths = [...new Set(edge.resolution.targets.flatMap(t => t.files))];
277
+ if (paths.length !== 1 || names.has("*")) {
278
+ state.unexpandedFiles++;
279
+ addContextDiagnostic(state, "dependency_depth_or_binding_limit", entry.path, declaration.getText());
280
+ continue;
281
+ }
282
+ const dependencyPath = paths[0]!;
283
+ if (entry.depth >= state.maxDepth) {
284
+ const loaded = state.files.get(dependencyPath);
285
+ const alreadyEmitted = Boolean(loaded) && sortedNames.length > 0 && sortedNames.every((n) => {
286
+ const selected = loaded!.bound.exported(n);
287
+ if (!selected) return false;
288
+ const nextTypeOnlyClass = Boolean(typeOnlyByName.get(n)) && ts.isClassDeclaration(selected);
289
+ return state.emitted.has(`${dependencyPath}:${selected.pos}:${selected.end}:${nextTypeOnlyClass}`);
290
+ });
291
+ if (!alreadyEmitted) {
292
+ state.unexpandedFiles++;
293
+ addContextDiagnostic(state, "dependency_depth_or_binding_limit", entry.path, declaration.getText());
294
+ }
295
+ continue;
296
+ }
297
+ const depFileRecord = state.repo.getFileByPath(dependencyPath);
298
+ const depSymbols = depFileRecord ? state.repo.getSymbolsByFileId(depFileRecord.id) : [];
299
+ if (sortedNames.length > 0 && sortedNames.every(n => Boolean(typeOnlyByName.get(n)) && depSymbols.some(s => s.name === n && s.kind === "class"))) {
300
+ deferredTypeOnlyClassImports.push({ dependencyPath, effectiveNames: sortedNames, depth: entry.depth + 1, hopDepth: entry.hopDepth + 1 });
301
+ continue;
302
+ }
303
+ const dependency = loadBoundTsFile(state, dependencyPath);
304
+ if (!dependency) continue;
305
+ for (const name of sortedNames) {
306
+ const selected = dependency.bound.exported(name);
307
+ if (!selected) { addContextDiagnostic(state, "export_binding_not_resolved", dependencyPath, name); continue; }
308
+ const nextTypeOnlyClass = Boolean(typeOnlyByName.get(name)) && ts.isClassDeclaration(selected);
309
+ const calls = refs.escapes.has(declaration) ? [] : refs.calls.filter(call => call.target === declaration && call.name === name);
310
+ if (calls.length && !nextTypeOnlyClass) for (const call of calls) enqueueSymbolNode(state, dependencyPath, selected, entry.depth + 1, "direct_import_declaration", false, call.arguments, true, entry.hopDepth + 1);
311
+ else enqueueSymbolNode(state, dependencyPath, selected, entry.depth + 1, "direct_import_declaration", nextTypeOnlyClass, undefined, false, entry.hopDepth + 1);
312
+ }
313
+ }
314
+ for (const deferred of deferredTypeOnlyClassImports) {
315
+ const dependency = loadBoundTsFile(state, deferred.dependencyPath);
316
+ if (!dependency) continue;
317
+ for (const name of deferred.effectiveNames) {
318
+ const selected = dependency.bound.exported(name);
319
+ if (!selected) { addContextDiagnostic(state, "export_binding_not_resolved", deferred.dependencyPath, name); continue; }
320
+ enqueueSymbolNode(state, deferred.dependencyPath, selected, deferred.depth, "direct_import_declaration", ts.isClassDeclaration(selected), undefined, false, deferred.hopDepth);
321
+ }
322
+ }
323
+ if (state.visited.size % 8 === 0) await new Promise<void>(done => setTimeout(done, 0));
324
+ }
325
+
326
+
327
+ /** Read-only context for a bounded import policy; no complete call graph claim. */
328
+ export async function retrieveContext(repo: SeptumRepository, config: ValidatedSeptumConfig, query: ContextQuery, workspaceRoot: string, signal?: AbortSignal) {
329
+ signal?.throwIfAborted();
330
+ const budget = query.budget_bytes ?? 16 * 1024;
331
+ if (!Number.isInteger(budget) || budget < MIN_CONTEXT_BUDGET || budget > MAX_CONTEXT_BUDGET) {
332
+ return response({ status: "invalid_budget", minimum_budget_bytes: MIN_CONTEXT_BUDGET, maximum_budget_bytes: MAX_CONTEXT_BUDGET });
333
+ }
334
+ const maxDepth = query.max_depth ?? DEFAULT_CONTEXT_DEPTH;
335
+ if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > MAX_CONTEXT_DEPTH) {
336
+ return response({ status: "invalid_max_depth", minimum_max_depth: 1, maximum_max_depth: MAX_CONTEXT_DEPTH });
337
+ }
338
+ const root = resolve(workspaceRoot);
339
+ const name = (query.symbol_ref?.name || query.symbol || query.query || "").trim();
340
+ if (!name) return response({ status: "invalid_query", message: "Choose a target with query, symbol or symbol_ref." });
341
+ const initialIndex = repo.getIndexIdentity();
342
+ if (query.symbol_ref && repo.getFileByPath(query.symbol_ref.file_path)?.content_hash !== query.symbol_ref.indexed_content_hash) {
343
+ return response({ status: "stale_reference", message: "Locate the target again before retrieving context." });
344
+ }
345
+ const candidates = repo.findSymbolsByName(name, { filePath: query.file_path, reference: query.symbol_ref, domain: query.domain });
346
+ if (candidates.length !== 1) {
347
+ return budgetedResponse({ status: candidates.length ? "ambiguous" : "not_found", policy: CONTEXT_POLICY,
348
+ candidate_count: candidates.length, candidates: candidates.slice(0, 5).map(candidate => candidate.symbol_ref),
349
+ candidates_omitted: Math.max(0, candidates.length - 5), message: "Select one declaration with file_path or symbol_ref; narrow the query if candidates are omitted." }, budget);
350
+ }
351
+ const target = candidates[0]!;
352
+ if (!/\.(?:ts|mts|cts|tsx)$/.test(target.file_path)) {
353
+ return retrieveUniversalContext(repo, config, query, target, root, signal);
354
+ }
355
+ const queryId = digest({ root, target: target.symbol_ref, policy: CONTEXT_POLICY, domain: query.domain ?? null,
356
+ budget, max_depth: maxDepth, parser: PARSER_FINGERPRINT, resolver: RESOLVER_REVISION, reads: SOURCE_READ_REVISION, config });
357
+ let cursor: { query: string; snapshot: string; offset: number; source_offset?: number } | undefined;
358
+ if (query.continuation) {
359
+ try {
360
+ cursor = JSON.parse(Buffer.from(query.continuation, "base64url").toString("utf8"));
361
+ if (!cursor || cursor.query !== queryId || typeof cursor.snapshot !== "string" ||
362
+ !Number.isSafeInteger(cursor.offset) || cursor.offset < 0 ||
363
+ cursor.source_offset !== undefined && (!Number.isSafeInteger(cursor.source_offset) || cursor.source_offset < 0)) throw new Error("invalid");
364
+ } catch { return response({ status: "invalid_continuation", message: "Continuation must match the target, workspace, policy and budget; restart retrieval." }); }
365
+ }
366
+ const state: ContextWalkState = {
367
+ repo,
368
+ root,
369
+ maxDepth,
370
+ signal,
371
+ targetFilePath: target.file_path,
372
+ targetSource: "",
373
+ relationshipsByFile: new Map<string, ImportRelationship[]>(),
374
+ referencedEdges: new Set<ImportRelationship>(),
375
+ visited: new Set<string>(),
376
+ emitted: new Set<string>(),
377
+ directCallItems: new WeakSet<ContextItem>(),
378
+ variants: new Map<string, Set<string>>(),
379
+ files: new Map<string, BoundEntry>(),
380
+ expansionQueue: [],
381
+ items: [],
382
+ freshness: "current",
383
+ incomplete: repo.getMeta("sync_state") !== "complete",
384
+ capacityOmissions: 0,
385
+ unexpandedFiles: 0,
386
+ sourceBytes: 0,
387
+ };
388
+ const collected = await collectSourceSkips(root, async () => {
389
+ if (state.incomplete) addContextDiagnostic(state, "index_not_complete");
390
+ const source = readIndexedSource(state, target.file_path);
391
+ if (source === undefined) return state.items;
392
+ state.targetSource = source;
393
+ addSymbolSourceItem(state, target.file_path, source, target, "target_implementation", 0);
394
+ const targetFile = loadBoundTsFile(state, target.file_path);
395
+ const declaration = targetFile?.bound.declaration(target.line_start, target.line_end);
396
+ if (declaration) {
397
+ if (targetFile!.bound.source.getLineAndCharacterOfPosition(declaration.getStart()).line + 1 !== target.line_start ||
398
+ targetFile!.bound.source.getLineAndCharacterOfPosition(declaration.end).line + 1 !== target.line_end) {
399
+ addContextDiagnostic(state, "enclosing_declaration_reference_scope", target.file_path);
400
+ }
401
+ enqueueSymbolNode(state, target.file_path, declaration, 0, "target_implementation");
402
+ while (state.expansionQueue.length > 0) {
403
+ await expandSymbolReferences(state, state.expansionQueue.shift()!);
404
+ }
405
+ } else {
406
+ addContextDiagnostic(state, "target_ast_declaration_not_found", target.file_path);
407
+ }
408
+ // Signal-first, hop-aware ordering:
409
+ // 0: target implementation, 1: source & contracts sorted strictly by depth (0 -> 1 -> 2...),
410
+ // within each depth: direct calls -> contracts -> local helpers -> other imports, then smaller span.
411
+ // 2: selection notes, 3: diagnostics & relationships.
412
+ const itemGroup = (item: ContextItem) =>
413
+ item.kind === "source" && item.reason === "target_implementation" ? 0
414
+ : item.kind === "source" || item.kind === "type_contract" ? 1
415
+ : item.kind === "selection" ? 2 : 3;
416
+ const itemDepth = (item: ContextItem) =>
417
+ item.kind === "source" || item.kind === "type_contract" ? (item.depth ?? 1) : 99;
418
+ const roleRank = (item: ContextItem) => {
419
+ if (item.kind === "source" && state.directCallItems.has(item)) return 0;
420
+ if (item.kind === "type_contract" || (item.kind === "source" && item.selection_role === "contract")) return 1;
421
+ if (item.kind === "source" && item.reason === "local_dependency") return 2;
422
+ return 3;
423
+ };
424
+ const spanLines = (item: ContextItem) =>
425
+ item.kind === "source" ? item.source.end_line - item.source.start_line
426
+ : item.kind === "type_contract" ? item.end_line - item.start_line : 0;
427
+ state.items.sort((a, b) =>
428
+ itemGroup(a) - itemGroup(b) ||
429
+ (itemGroup(a) === 1
430
+ ? itemDepth(a) - itemDepth(b) || roleRank(a) - roleRank(b) || spanLines(a) - spanLines(b)
431
+ : 0)
432
+ );
433
+ for (const edge of state.referencedEdges) addContextItem(state, { kind: "relationship", reason: "target_file_import", relationship: edge });
434
+ return state.items;
435
+ });
436
+ signal?.throwIfAborted();
437
+ if (repo.getIndexIdentity() !== initialIndex) return response({ status: "index_changed", message: "Index changed during context analysis; retry retrieval." });
438
+ // Negative resolution can change when an unindexed file appears. Observed file
439
+ // reads alone cannot capture that; bind the resolved selection and diagnostics too.
440
+ const snapshot = digest({ index: initialIndex, inputs: collected.inputs.map(({ path, hash }) => ({ path, hash })), observations: collected.observations, selection: collected.value });
441
+ if (cursor && (cursor.snapshot !== snapshot || cursor.offset >= collected.value.length)) {
442
+ return response({ status: "stale_continuation", message: "Input/index identity changed or the page is invalid; restart retrieval." });
443
+ }
444
+ return pageContext({
445
+ items: collected.value, start: cursor?.offset ?? 0, sourceOffset: cursor?.source_offset ?? 0,
446
+ budget, incomplete: state.incomplete,
447
+ accounting: { omitted_by_capacity: state.capacityOmissions, unexpanded_dependency_files: state.unexpandedFiles },
448
+ base: {
449
+ policy: CONTEXT_POLICY, context_mode: "deep", workspace: root, target: target.symbol_ref,
450
+ target_id: symbolTargetId(root, target.symbol_ref), query_id: queryId, snapshot_id: snapshot, freshness: state.freshness,
451
+ freshness_scope: "returned source hashes checked against index during response preparation",
452
+ completeness_scope: `target and bound local/referenced declarations in directly imported TypeScript files up to ${maxDepth} import edge(s)`,
453
+ capability_limits: "static references, not calls", task_sufficiency: "unknown",
454
+ input_count: collected.inputs.length, selected_source_bytes_read: state.sourceBytes, dependency_depth: maxDepth,
455
+ },
456
+ });
457
+ }
@@ -0,0 +1,21 @@
1
+ import type { ImportRelationship } from "../../types/index.ts";
2
+
3
+ /** Only resolved, current, fully indexed unrelated targets can leave the target warnings. */
4
+ export function partitionResolutionWarnings(relationships: ImportRelationship[], targetFiles: string[]) {
5
+ const targets = new Set(targetFiles);
6
+ const warnings = relationships.filter(edge => !["resolved", "external"].includes(edge.resolution.status) || edge.resolution.coverage === "conditional");
7
+ const relevant = [];
8
+ const workspace = [];
9
+ for (const edge of warnings) {
10
+ const directlyRelated = targets.has(edge.source.file) || edge.resolution.targets.some(target => target.files.some(file => targets.has(file)));
11
+ const unrelatedProven = !directlyRelated && targets.size > 0 && edge.freshness === "current" && edge.index_coverage === "complete" &&
12
+ edge.resolution.status === "resolved" && edge.resolution.targets.length > 0 &&
13
+ edge.resolution.targets.every(target => target.files.length > 0);
14
+ if (unrelatedProven) workspace.push(edge);
15
+ else relevant.push({ ...edge,
16
+ warning_scope: directlyRelated ? "target" as const : "possible_target" as const,
17
+ relevance_reason: directlyRelated ? "source_or_resolved_target_is_selected" : "target_relevance_cannot_be_excluded",
18
+ });
19
+ }
20
+ return { relevant, workspace };
21
+ }