@dimassetoid/septum-mcp 0.3.0 → 0.5.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.
- package/README.md +38 -55
- package/package.json +7 -5
- package/src/cli/commands/check.ts +14 -10
- package/src/cli/commands/hook.ts +41 -6
- package/src/cli/commands/init.ts +10 -1
- package/src/cli/commands/stats.ts +33 -0
- package/src/cli/commands/sync-progress.ts +71 -0
- package/src/cli/commands/sync.ts +32 -4
- package/src/cli/index.ts +7 -0
- package/src/cli/templates/hooks.ts +3 -14
- package/src/cli/templates/skill.ts +17 -10
- package/src/core/boundary/audit.ts +383 -0
- package/src/core/boundary/evaluator.ts +251 -114
- package/src/core/boundary/staged-auditor.ts +147 -55
- package/src/core/config/domain-ownership.ts +6 -4
- package/src/core/config/domain-registration.ts +141 -0
- package/src/core/config/loader.ts +1 -25
- package/src/core/config/schema.ts +24 -36
- package/src/core/database/client.ts +2 -0
- package/src/core/database/repositories/dependency.repository.ts +334 -572
- package/src/core/database/repositories/domain.repository.ts +2 -1
- package/src/core/database/repositories/file.repository.ts +10 -0
- package/src/core/database/repositories/symbol.repository.ts +97 -398
- package/src/core/database/repository.ts +68 -9
- package/src/core/database/schema.ts +26 -0
- package/src/core/discovery/declarative-routes.ts +69 -0
- package/src/core/discovery/framework-detector.ts +149 -0
- package/src/core/discovery/navigation.ts +222 -58
- package/src/core/discovery/topology-detector.ts +93 -168
- package/src/core/errors.ts +19 -0
- package/src/core/ingestion/pipeline.ts +287 -88
- package/src/core/parser/extractors/base.ts +11 -3
- package/src/core/parser/extractors/csharp.ts +2 -2
- package/src/core/parser/extractors/django-routing.ts +163 -0
- package/src/core/parser/extractors/django-semantic.ts +397 -481
- package/src/core/parser/extractors/elysia-semantic.ts +172 -475
- package/src/core/parser/extractors/express-semantic.ts +195 -383
- package/src/core/parser/extractors/fastapi-semantic.ts +178 -361
- package/src/core/parser/extractors/fastify-semantic.ts +216 -717
- package/src/core/parser/extractors/flask-semantic.ts +89 -352
- package/src/core/parser/extractors/go-routing.ts +344 -0
- package/src/core/parser/extractors/go-semantic.ts +205 -562
- package/src/core/parser/extractors/go.ts +6 -3
- package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
- package/src/core/parser/extractors/hono-semantic.ts +132 -509
- package/src/core/parser/extractors/java.ts +2 -2
- package/src/core/parser/extractors/laravel-routing.ts +263 -0
- package/src/core/parser/extractors/laravel-semantic.ts +143 -335
- package/src/core/parser/extractors/manifest-helpers.ts +64 -0
- package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
- package/src/core/parser/extractors/mcp-cli-semantic.ts +82 -333
- package/src/core/parser/extractors/nestjs-semantic.ts +238 -494
- package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
- package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
- package/src/core/parser/extractors/php.ts +1 -1
- package/src/core/parser/extractors/python-route-ast.ts +249 -0
- package/src/core/parser/extractors/python.ts +5 -9
- package/src/core/parser/extractors/registry.ts +2 -0
- package/src/core/parser/extractors/route-prefixes.ts +43 -0
- package/src/core/parser/extractors/ruby.ts +2 -2
- package/src/core/parser/extractors/rust.ts +4 -4
- package/src/core/parser/extractors/symfony-routing.ts +114 -0
- package/src/core/parser/extractors/symfony-semantic.ts +72 -226
- package/src/core/parser/extractors/typescript-bindings.ts +333 -0
- package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
- package/src/core/parser/extractors/typescript-fallback.ts +207 -0
- package/src/core/parser/extractors/typescript-route-context.ts +58 -0
- package/src/core/parser/extractors/typescript.ts +23 -216
- package/src/core/parser/language-capabilities.ts +1 -1
- package/src/core/parser/schema/providers/laravel-migration-provider.ts +4 -1
- package/src/core/parser/wasm-loader.ts +6 -2
- package/src/core/resolver/ast-method-tracer.ts +230 -0
- package/src/core/resolver/call-graph-helpers.ts +72 -0
- package/src/core/resolver/call-graph-tracer.ts +169 -414
- package/src/core/resolver/dependency-analysis.ts +593 -0
- package/src/core/resolver/import-candidates.ts +120 -0
- package/src/core/resolver/import-evidence.ts +88 -0
- package/src/core/resolver/import-resolver.ts +60 -7
- package/src/core/resolver/interpretation-inputs.ts +60 -2
- package/src/core/resolver/languages/python.ts +31 -13
- package/src/core/resolver/languages/shared.ts +4 -1
- package/src/core/resolver/module-resolver.ts +10 -3
- package/src/core/resolver/path-resolver.ts +6 -3
- package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
- package/src/core/resolver/slice-catalog.ts +21 -6
- package/src/core/resolver/slice-format.ts +13 -0
- package/src/core/resolver/slice-selection.ts +237 -0
- package/src/core/resolver/symbol-impact.ts +104 -8
- package/src/core/resolver/symbol-locator.ts +82 -15
- package/src/core/resolver/vertical-slice-tracer.ts +31 -230
- package/src/core/resources/ignore.ts +0 -1
- package/src/core/resources/limits.ts +2 -1
- package/src/core/resources/work-queue.ts +167 -4
- package/src/core/retrieval/context-page.ts +11 -4
- package/src/core/retrieval/context.ts +363 -226
- package/src/{mcp/tools/get-symbol.ts → core/retrieval/source-context.ts} +145 -96
- package/src/core/retrieval/symbol-details.ts +453 -0
- package/src/core/retrieval/symbol-evidence.ts +3 -3
- package/src/core/retrieval/typescript-references.ts +38 -7
- package/src/core/retrieval/universal-context.ts +182 -0
- package/src/core/telemetry/summary.ts +114 -0
- package/src/core/telemetry/telemetry.ts +192 -49
- package/src/mcp/formatters/compact-text.ts +439 -0
- package/src/mcp/resources-and-prompts.ts +255 -0
- package/src/mcp/schemas/boundary.ts +145 -0
- package/src/mcp/schemas/map.ts +250 -0
- package/src/mcp/schemas/shared.ts +52 -0
- package/src/mcp/schemas/slice.ts +60 -0
- package/src/mcp/schemas/symbol.ts +268 -0
- package/src/mcp/schemas.ts +5 -746
- package/src/mcp/server.ts +269 -429
- package/src/mcp/tool-catalog.ts +331 -0
- package/src/mcp/tools/boundary.ts +68 -3
- package/src/mcp/tools/map.ts +104 -4
- package/src/mcp/tools/slice.ts +101 -3
- package/src/mcp/tools/symbol.ts +469 -17
- package/src/mcp/ui/app-client.ts +899 -0
- package/src/mcp/ui/app.html +478 -0
- package/src/mcp/workflow-playbooks.ts +181 -0
- package/src/mcp/workspace-boundary.ts +50 -0
- package/src/mcp/workspace-manager.ts +88 -15
- package/src/mcp/workspace-watcher.ts +30 -11
- package/src/types/index.ts +12 -0
- package/src/mcp/tools/check-boundary.ts +0 -382
- package/src/mcp/tools/get-domain-catalog.ts +0 -39
- package/src/mcp/tools/get-symbol-impact.ts +0 -104
- package/src/mcp/tools/locate-symbol.ts +0 -236
- package/src/mcp/tools/register-domain.ts +0 -113
- package/src/mcp/tools/trace-vertical-slice.ts +0 -106
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { pageContext, response, budgetedResponse, type ContextItem, type SourceItem } from "./context-page.ts";
|
|
2
|
+
import { retrieveUniversalContext } from "./universal-context.ts";
|
|
2
3
|
import ts from "typescript";
|
|
3
4
|
import { bindContextFile, type ContextValue } from "./typescript-references.ts";
|
|
4
5
|
import { resolve } from "node:path";
|
|
@@ -15,6 +16,8 @@ import { symbolTargetId } from "./symbol-evidence.ts";
|
|
|
15
16
|
export const CONTEXT_POLICY = "referenced-typescript-declarations/v4";
|
|
16
17
|
export const MIN_CONTEXT_BUDGET = 2048;
|
|
17
18
|
export const MAX_CONTEXT_BUDGET = 2 * 1024 * 1024;
|
|
19
|
+
export const DEFAULT_CONTEXT_DEPTH = 2;
|
|
20
|
+
export const MAX_CONTEXT_DEPTH = 4;
|
|
18
21
|
const MAX_ITEMS = 256;
|
|
19
22
|
const MAX_SOURCE_BYTES = 8 * 1024 * 1024;
|
|
20
23
|
|
|
@@ -25,6 +28,7 @@ export interface ContextQuery {
|
|
|
25
28
|
file_path?: string;
|
|
26
29
|
domain?: string;
|
|
27
30
|
budget_bytes?: number;
|
|
31
|
+
max_depth?: number;
|
|
28
32
|
continuation?: string;
|
|
29
33
|
}
|
|
30
34
|
function canonical(value: unknown): unknown {
|
|
@@ -35,6 +39,290 @@ function canonical(value: unknown): unknown {
|
|
|
35
39
|
}
|
|
36
40
|
function digest(value: unknown) { return computeContentHash(JSON.stringify(canonical(value))); }
|
|
37
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
|
+
|
|
38
326
|
|
|
39
327
|
/** Read-only context for a bounded import policy; no complete call graph claim. */
|
|
40
328
|
export async function retrieveContext(repo: SeptumRepository, config: ValidatedSeptumConfig, query: ContextQuery, workspaceRoot: string, signal?: AbortSignal) {
|
|
@@ -43,6 +331,10 @@ export async function retrieveContext(repo: SeptumRepository, config: ValidatedS
|
|
|
43
331
|
if (!Number.isInteger(budget) || budget < MIN_CONTEXT_BUDGET || budget > MAX_CONTEXT_BUDGET) {
|
|
44
332
|
return response({ status: "invalid_budget", minimum_budget_bytes: MIN_CONTEXT_BUDGET, maximum_budget_bytes: MAX_CONTEXT_BUDGET });
|
|
45
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
|
+
}
|
|
46
338
|
const root = resolve(workspaceRoot);
|
|
47
339
|
const name = (query.symbol_ref?.name || query.symbol || query.query || "").trim();
|
|
48
340
|
if (!name) return response({ status: "invalid_query", message: "Choose a target with query, symbol or symbol_ref." });
|
|
@@ -57,11 +349,11 @@ export async function retrieveContext(repo: SeptumRepository, config: ValidatedS
|
|
|
57
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);
|
|
58
350
|
}
|
|
59
351
|
const target = candidates[0]!;
|
|
60
|
-
if (!/\.(?:ts|mts|cts)$/.test(target.file_path)) {
|
|
61
|
-
return
|
|
352
|
+
if (!/\.(?:ts|mts|cts|tsx)$/.test(target.file_path)) {
|
|
353
|
+
return retrieveUniversalContext(repo, config, query, target, root, signal);
|
|
62
354
|
}
|
|
63
355
|
const queryId = digest({ root, target: target.symbol_ref, policy: CONTEXT_POLICY, domain: query.domain ?? null,
|
|
64
|
-
budget, parser: PARSER_FINGERPRINT, resolver: RESOLVER_REVISION, reads: SOURCE_READ_REVISION, config });
|
|
356
|
+
budget, max_depth: maxDepth, parser: PARSER_FINGERPRINT, resolver: RESOLVER_REVISION, reads: SOURCE_READ_REVISION, config });
|
|
65
357
|
let cursor: { query: string; snapshot: string; offset: number; source_offset?: number } | undefined;
|
|
66
358
|
if (query.continuation) {
|
|
67
359
|
try {
|
|
@@ -71,230 +363,75 @@ export async function retrieveContext(repo: SeptumRepository, config: ValidatedS
|
|
|
71
363
|
cursor.source_offset !== undefined && (!Number.isSafeInteger(cursor.source_offset) || cursor.source_offset < 0)) throw new Error("invalid");
|
|
72
364
|
} catch { return response({ status: "invalid_continuation", message: "Continuation must match the target, workspace, policy and budget; restart retrieval." }); }
|
|
73
365
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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
|
+
};
|
|
79
388
|
const collected = await collectSourceSkips(root, async () => {
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
const
|
|
86
|
-
incomplete = true; add({ kind: "diagnostic", reason, file_path, detail });
|
|
87
|
-
};
|
|
88
|
-
const readIndexed = (path: string): string | undefined => {
|
|
89
|
-
signal?.throwIfAborted();
|
|
90
|
-
try {
|
|
91
|
-
assertPathContained(path, root, "Context source");
|
|
92
|
-
const source = readSourceFile(resolve(root, path));
|
|
93
|
-
sourceBytes += Buffer.byteLength(source, "utf8");
|
|
94
|
-
if (sourceBytes > MAX_SOURCE_BYTES) { addDiagnostic("analysis_source_byte_limit", path); return; }
|
|
95
|
-
if (computeContentHash(source) !== repo.getFileByPath(path)?.content_hash) {
|
|
96
|
-
freshness = "stale"; addDiagnostic("source_differs_from_index", path); return;
|
|
97
|
-
}
|
|
98
|
-
return source;
|
|
99
|
-
} catch {
|
|
100
|
-
if (freshness !== "stale") freshness = "unavailable";
|
|
101
|
-
addDiagnostic("source_unavailable_or_out_of_scope", path);
|
|
102
|
-
}
|
|
103
|
-
};
|
|
104
|
-
const addSource = (path: string, source: string, symbol: { name: string; line_start: number; line_end: number }, reason: SourceItem["reason"]) => {
|
|
105
|
-
const starts = [0]; const ends: number[] = [];
|
|
106
|
-
for (const match of source.matchAll(/\r\n|\n|\r/g)) { ends.push(match.index!); starts.push(match.index! + match[0].length); }
|
|
107
|
-
ends.push(source.length);
|
|
108
|
-
if (symbol.line_start < 1 || symbol.line_end < symbol.line_start || symbol.line_end > starts.length) {
|
|
109
|
-
addDiagnostic("invalid_indexed_span", path); return;
|
|
110
|
-
}
|
|
111
|
-
add({ kind: "source", name: symbol.name, reason, source: { file_path: path,
|
|
112
|
-
indexed_content_hash: repo.getFileByPath(path)!.content_hash, start_line: symbol.line_start, end_line: symbol.line_end,
|
|
113
|
-
text: source.slice(starts[symbol.line_start - 1], ends[symbol.line_end - 1]) } });
|
|
114
|
-
};
|
|
115
|
-
if (incomplete) addDiagnostic("index_not_complete");
|
|
116
|
-
const source = readIndexed(target.file_path);
|
|
117
|
-
if (source === undefined) return items;
|
|
118
|
-
addSource(target.file_path, source, target, "target_implementation");
|
|
119
|
-
const relationships = repo.getImportRelationships(root);
|
|
120
|
-
const referencedEdges = new Set<ImportRelationship>();
|
|
121
|
-
const visited = new Set<string>();
|
|
122
|
-
const emitted = new Set<string>();
|
|
123
|
-
const variants = new Map<string, Set<string>>();
|
|
124
|
-
const files = new Map<string, { text: string; bound: ReturnType<typeof bindContextFile> }>();
|
|
125
|
-
const load = (path: string) => {
|
|
126
|
-
if (files.has(path)) return files.get(path);
|
|
127
|
-
if (sourceBytes >= MAX_SOURCE_BYTES || files.size >= 64) {
|
|
128
|
-
unexpandedFiles++; addDiagnostic("analysis_file_limit", path); return;
|
|
129
|
-
}
|
|
130
|
-
if (!repo.getFileByPath(path) || !/\.(?:ts|mts|cts)$/.test(path)) {
|
|
131
|
-
addDiagnostic("dependency_not_indexed_or_unsupported", path); return;
|
|
132
|
-
}
|
|
133
|
-
const text = path === target.file_path ? source : readIndexed(path);
|
|
134
|
-
if (text === undefined) return;
|
|
135
|
-
const bound = bindContextFile(path, text);
|
|
136
|
-
const value = { text, bound }; files.set(path, value);
|
|
137
|
-
if (bound.hasErrors) addDiagnostic("typescript_syntax_errors", path);
|
|
138
|
-
// Initializers and decorators can execute independently of references.
|
|
139
|
-
// Retain relationships and explicitly decline module-execution closure.
|
|
140
|
-
if (bound.source.statements.some(node => ts.isImportDeclaration(node) && !node.importClause))
|
|
141
|
-
addDiagnostic("side_effect_import_not_expanded", path);
|
|
142
|
-
const hasExecution = (node: ts.Node): boolean => {
|
|
143
|
-
if (ts.isFunctionLike(node)) return false;
|
|
144
|
-
if (ts.isCallExpression(node) || ts.isNewExpression(node) || ts.isAwaitExpression(node)) return true;
|
|
145
|
-
return ts.forEachChild(node, child => hasExecution(child) || undefined) ?? false;
|
|
146
|
-
};
|
|
147
|
-
if (bound.source.statements.some(node => ts.isExpressionStatement(node) || ts.isExportDeclaration(node) || ts.isClassDeclaration(node) ||
|
|
148
|
-
(ts.isVariableStatement(node) && hasExecution(node))))
|
|
149
|
-
addDiagnostic("module_execution_or_reexport_not_expanded", path);
|
|
150
|
-
return value;
|
|
151
|
-
};
|
|
152
|
-
const isTypeOnlyImportBinding = (declaration: ts.ImportDeclaration, exportedName: string): boolean => {
|
|
153
|
-
if (declaration.importClause?.isTypeOnly) return true;
|
|
154
|
-
const bindings = declaration.importClause?.namedBindings;
|
|
155
|
-
if (bindings && ts.isNamedImports(bindings)) {
|
|
156
|
-
const matching = bindings.elements.filter(el => (el.propertyName ?? el.name).text === exportedName);
|
|
157
|
-
if (matching.length > 0 && matching.every(el => el.isTypeOnly)) return true;
|
|
158
|
-
}
|
|
159
|
-
return false;
|
|
160
|
-
};
|
|
161
|
-
type QueuedNode = { path: string; node: ts.Node; depth: number; reason: SourceItem["reason"]; typeOnlyClass: boolean; arguments?: ContextValue[] };
|
|
162
|
-
const expansionQueue: QueuedNode[] = [];
|
|
163
|
-
const enqueueNode = (path: string, node: ts.Node, depth: number, reason: SourceItem["reason"], typeOnlyClass = false, argumentFacts?: ContextValue[]) => {
|
|
164
|
-
const declarationKey = `${path}:${node.pos}:${node.end}:${typeOnlyClass}`;
|
|
165
|
-
const seen = variants.get(declarationKey) ?? new Set<string>();
|
|
166
|
-
if (seen.size >= 4) argumentFacts = undefined;
|
|
167
|
-
const variant = JSON.stringify(argumentFacts ?? null);
|
|
168
|
-
seen.add(variant); variants.set(declarationKey, seen);
|
|
169
|
-
const key = `${declarationKey}:${variant}`;
|
|
170
|
-
if (visited.has(key)) return;
|
|
171
|
-
visited.add(key);
|
|
172
|
-
if (items.length >= MAX_ITEMS) { capacityOmissions++; incomplete = true; return; }
|
|
173
|
-
const file = load(path);
|
|
174
|
-
if (!file) return;
|
|
175
|
-
if (reason === "target_implementation") emitted.add(declarationKey);
|
|
176
|
-
if (reason !== "target_implementation" && !emitted.has(declarationKey)) {
|
|
177
|
-
emitted.add(declarationKey);
|
|
178
|
-
const start = file.bound.source.getLineAndCharacterOfPosition(node.getStart()).line + 1;
|
|
179
|
-
const end = file.bound.source.getLineAndCharacterOfPosition(node.end).line + 1;
|
|
180
|
-
const indexed = repo.getSymbolsByFileId(repo.getFileByPath(path)!.id).find(s => s.line_start >= start && s.line_end <= end);
|
|
181
|
-
const name = indexed?.name ?? ("name" in node ? (node as ts.NamedDeclaration).name?.getText(file.bound.source) : undefined) ?? "local_declaration";
|
|
182
|
-
if (typeOnlyClass && ts.isClassDeclaration(node)) {
|
|
183
|
-
const contract = file.bound.contract(node);
|
|
184
|
-
add({ kind: "type_contract", name, file_path: path, indexed_content_hash: repo.getFileByPath(path)!.content_hash,
|
|
185
|
-
start_line: start, end_line: end, projection: "public_instance_signatures", text: contract.text,
|
|
186
|
-
inferred_types: contract.inferred ? "unknown" : "explicit" });
|
|
187
|
-
addDiagnostic("type_only_class_bodies_omitted", path, "Instance signature projection; constructors, private/static members, bodies and initializers omitted. Inferred types use unknown.");
|
|
188
|
-
} else {
|
|
189
|
-
const before = items.length;
|
|
190
|
-
addSource(path, file.text, { name, line_start: start, line_end: end }, reason);
|
|
191
|
-
const item = items[before];
|
|
192
|
-
if (item?.kind === "source") item.selection_role = ts.isTypeAliasDeclaration(node) || ts.isInterfaceDeclaration(node) ? "contract" : "implementation";
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
expansionQueue.push({ path, node, depth, reason, typeOnlyClass, arguments: argumentFacts });
|
|
196
|
-
};
|
|
197
|
-
const expandReferences = async (entry: QueuedNode) => {
|
|
198
|
-
signal?.throwIfAborted();
|
|
199
|
-
const file = load(entry.path);
|
|
200
|
-
if (!file) return;
|
|
201
|
-
const startLine = file.bound.source.getLineAndCharacterOfPosition(entry.node.getStart()).line + 1;
|
|
202
|
-
const endLine = file.bound.source.getLineAndCharacterOfPosition(entry.node.end).line + 1;
|
|
203
|
-
for (const edge of relationships.filter(edge => !entry.typeOnlyClass && edge.source.file === entry.path &&
|
|
204
|
-
edge.source.line >= startLine && edge.source.line <= endLine)) {
|
|
205
|
-
if (entry.path === target.file_path) referencedEdges.add(edge);
|
|
206
|
-
if (edge.freshness !== "current" || (edge.resolution.status !== "resolved" && edge.resolution.status !== "external") || edge.resolution.coverage === "conditional")
|
|
207
|
-
addDiagnostic("import_not_fully_resolved", entry.path, `${edge.resolution.source.target}: ${edge.resolution.reason}`);
|
|
208
|
-
}
|
|
209
|
-
const signatureNodes = entry.typeOnlyClass && ts.isClassDeclaration(entry.node) ? file.bound.contract(entry.node).signatures : undefined;
|
|
210
|
-
const refs = file.bound.references(entry.node, entry.arguments, signatureNodes);
|
|
211
|
-
if (refs.prunedBranches && entry.arguments) add({ kind: "selection", reason: "known_call_arguments", file_path: entry.path,
|
|
212
|
-
start_line: startLine, arguments: entry.arguments, pruned_branches: refs.prunedBranches });
|
|
213
|
-
for (const local of refs.locals) {
|
|
214
|
-
const calls = refs.escapes.has(local) ? [] : refs.calls.filter(call => call.target === local);
|
|
215
|
-
if (entry.depth === 0) {
|
|
216
|
-
// For the target file (depth 0), emit and expand local helpers immediately before cross-file imports
|
|
217
|
-
const prevLen = expansionQueue.length;
|
|
218
|
-
if (calls.length) for (const call of calls) enqueueNode(entry.path, local, 0, "local_dependency", false, call.arguments);
|
|
219
|
-
else enqueueNode(entry.path, local, 0, "local_dependency", entry.typeOnlyClass);
|
|
220
|
-
while (expansionQueue.length > prevLen) {
|
|
221
|
-
const localEntry = expansionQueue.pop()!;
|
|
222
|
-
await expandReferences(localEntry);
|
|
223
|
-
}
|
|
224
|
-
} else {
|
|
225
|
-
if (calls.length) for (const call of calls) enqueueNode(entry.path, local, entry.depth, "local_dependency", false, call.arguments);
|
|
226
|
-
else enqueueNode(entry.path, local, entry.depth, "local_dependency", entry.typeOnlyClass);
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
const deferredTypeOnlyClassImports: Array<{ dependencyPath: string; effectiveNames: string[]; depth: number }> = [];
|
|
230
|
-
for (const [declaration, names] of refs.imports) {
|
|
231
|
-
const sortedNames = [...names].sort();
|
|
232
|
-
const typeOnlyByName = new Map<string, boolean>();
|
|
233
|
-
for (const n of sortedNames) typeOnlyByName.set(n, entry.typeOnlyClass || isTypeOnlyImportBinding(declaration, n));
|
|
234
|
-
const effectiveNames = sortedNames;
|
|
235
|
-
const line = file.bound.source.getLineAndCharacterOfPosition(declaration.getStart()).line + 1;
|
|
236
|
-
const moduleName = ts.isStringLiteral(declaration.moduleSpecifier) ? declaration.moduleSpecifier.text : undefined;
|
|
237
|
-
const edge = relationships.find(e => e.source.file === entry.path && e.source.line === line &&
|
|
238
|
-
e.resolution.source.target === moduleName);
|
|
239
|
-
if (edge && entry.path === target.file_path) referencedEdges.add(edge);
|
|
240
|
-
if (!edge || edge.freshness !== "current" || edge.resolution.status !== "resolved" || edge.resolution.coverage === "conditional") {
|
|
241
|
-
addDiagnostic("referenced_import_not_expanded", entry.path,
|
|
242
|
-
`${declaration.getText()}: ${edge?.resolution.reason ?? "relationship_not_found"}`); continue;
|
|
243
|
-
}
|
|
244
|
-
const paths = [...new Set(edge.resolution.targets.flatMap(t => t.files))];
|
|
245
|
-
if (entry.depth >= 3 || paths.length !== 1 || names.has("*")) {
|
|
246
|
-
unexpandedFiles++; addDiagnostic("dependency_depth_or_binding_limit", entry.path, declaration.getText()); continue;
|
|
247
|
-
}
|
|
248
|
-
const dependencyPath = paths[0]!;
|
|
249
|
-
const depFileRecord = repo.getFileByPath(dependencyPath);
|
|
250
|
-
const depSymbols = depFileRecord ? repo.getSymbolsByFileId(depFileRecord.id) : [];
|
|
251
|
-
const isAllTypeOnlyClass = effectiveNames.length > 0 && effectiveNames.every(
|
|
252
|
-
n => Boolean(typeOnlyByName.get(n)) && depSymbols.some(s => s.name === n && s.kind === "class")
|
|
253
|
-
);
|
|
254
|
-
if (isAllTypeOnlyClass) {
|
|
255
|
-
deferredTypeOnlyClassImports.push({ dependencyPath, effectiveNames, depth: entry.depth + 1 });
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
const dependency = load(dependencyPath);
|
|
259
|
-
if (!dependency) continue;
|
|
260
|
-
for (const name of effectiveNames) {
|
|
261
|
-
const selected = dependency.bound.exported(name);
|
|
262
|
-
if (!selected) { addDiagnostic("export_binding_not_resolved", dependencyPath, name); continue; }
|
|
263
|
-
const nextTypeOnlyClass = Boolean(typeOnlyByName.get(name)) && ts.isClassDeclaration(selected);
|
|
264
|
-
const calls = refs.escapes.has(declaration) ? [] : refs.calls.filter(call => call.target === declaration && call.name === name);
|
|
265
|
-
if (calls.length && !nextTypeOnlyClass) for (const call of calls)
|
|
266
|
-
enqueueNode(dependencyPath, selected, entry.depth + 1, "direct_import_declaration", false, call.arguments);
|
|
267
|
-
else enqueueNode(dependencyPath, selected, entry.depth + 1, "direct_import_declaration", nextTypeOnlyClass);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
for (const deferred of deferredTypeOnlyClassImports) {
|
|
271
|
-
const dependency = load(deferred.dependencyPath);
|
|
272
|
-
if (!dependency) continue;
|
|
273
|
-
for (const name of deferred.effectiveNames) {
|
|
274
|
-
const selected = dependency.bound.exported(name);
|
|
275
|
-
if (!selected) { addDiagnostic("export_binding_not_resolved", deferred.dependencyPath, name); continue; }
|
|
276
|
-
enqueueNode(deferred.dependencyPath, selected, deferred.depth, "direct_import_declaration", ts.isClassDeclaration(selected));
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
if (visited.size % 8 === 0) await new Promise<void>(done => setTimeout(done, 0));
|
|
280
|
-
};
|
|
281
|
-
const targetFile = load(target.file_path);
|
|
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);
|
|
282
395
|
const declaration = targetFile?.bound.declaration(target.line_start, target.line_end);
|
|
283
396
|
if (declaration) {
|
|
284
397
|
if (targetFile!.bound.source.getLineAndCharacterOfPosition(declaration.getStart()).line + 1 !== target.line_start ||
|
|
285
|
-
targetFile!.bound.source.getLineAndCharacterOfPosition(declaration.end).line + 1 !== target.line_end)
|
|
286
|
-
|
|
287
|
-
enqueueNode(target.file_path, declaration, 0, "target_implementation");
|
|
288
|
-
while (expansionQueue.length > 0) {
|
|
289
|
-
await expandReferences(expansionQueue.shift()!);
|
|
398
|
+
targetFile!.bound.source.getLineAndCharacterOfPosition(declaration.end).line + 1 !== target.line_end) {
|
|
399
|
+
addContextDiagnostic(state, "enclosing_declaration_reference_scope", target.file_path);
|
|
290
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);
|
|
291
407
|
}
|
|
292
|
-
|
|
293
|
-
//
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
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;
|
|
298
435
|
});
|
|
299
436
|
signal?.throwIfAborted();
|
|
300
437
|
if (repo.getIndexIdentity() !== initialIndex) return response({ status: "index_changed", message: "Index changed during context analysis; retry retrieval." });
|
|
@@ -306,15 +443,15 @@ export async function retrieveContext(repo: SeptumRepository, config: ValidatedS
|
|
|
306
443
|
}
|
|
307
444
|
return pageContext({
|
|
308
445
|
items: collected.value, start: cursor?.offset ?? 0, sourceOffset: cursor?.source_offset ?? 0,
|
|
309
|
-
budget, incomplete,
|
|
310
|
-
accounting: { omitted_by_capacity: capacityOmissions, unexpanded_dependency_files: unexpandedFiles },
|
|
446
|
+
budget, incomplete: state.incomplete,
|
|
447
|
+
accounting: { omitted_by_capacity: state.capacityOmissions, unexpanded_dependency_files: state.unexpandedFiles },
|
|
311
448
|
base: {
|
|
312
449
|
policy: CONTEXT_POLICY, context_mode: "deep", workspace: root, target: target.symbol_ref,
|
|
313
|
-
target_id: symbolTargetId(root, target.symbol_ref), query_id: queryId, snapshot_id: snapshot, freshness,
|
|
450
|
+
target_id: symbolTargetId(root, target.symbol_ref), query_id: queryId, snapshot_id: snapshot, freshness: state.freshness,
|
|
314
451
|
freshness_scope: "returned source hashes checked against index during response preparation",
|
|
315
|
-
completeness_scope:
|
|
452
|
+
completeness_scope: `target and bound local/referenced declarations in directly imported TypeScript files up to ${maxDepth} import edge(s)`,
|
|
316
453
|
capability_limits: "static references, not calls", task_sufficiency: "unknown",
|
|
317
|
-
input_count: collected.inputs.length, selected_source_bytes_read: sourceBytes, dependency_depth:
|
|
454
|
+
input_count: collected.inputs.length, selected_source_bytes_read: state.sourceBytes, dependency_depth: maxDepth,
|
|
318
455
|
},
|
|
319
456
|
});
|
|
320
457
|
}
|