@dimassetoid/septum-mcp 0.2.1 → 0.3.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.
- package/README.md +46 -28
- package/package.json +4 -4
- package/src/cli/commands/check.ts +27 -16
- package/src/cli/commands/hook.ts +38 -101
- package/src/cli/commands/init.ts +26 -9
- package/src/cli/commands/sync.ts +4 -6
- package/src/cli/hook-payload.ts +43 -0
- package/src/cli/index.ts +9 -52
- package/src/cli/scaffold/harness-config.ts +48 -8
- package/src/cli/templates/hooks.ts +49 -14
- package/src/cli/templates/rules.ts +34 -49
- package/src/cli/templates/skill.ts +39 -35
- package/src/core/boundary/evaluator.ts +67 -83
- package/src/core/boundary/staged-auditor.ts +102 -40
- package/src/core/config/domain-ownership.ts +45 -0
- package/src/core/config/loader.ts +81 -29
- package/src/core/config/schema.ts +0 -10
- package/src/core/database/repositories/dependency.repository.ts +169 -148
- package/src/core/database/repositories/domain.repository.ts +46 -3
- package/src/core/database/repositories/symbol.repository.ts +226 -87
- package/src/core/database/repository.ts +73 -18
- package/src/core/database/schema.ts +2 -33
- package/src/core/discovery/navigation.ts +105 -0
- package/src/core/discovery/topology-detector.ts +60 -2
- package/src/core/ingestion/pipeline.ts +96 -129
- package/src/core/parser/behavioral-analyzer.ts +26 -22
- package/src/core/parser/boundary-tracker.ts +15 -0
- package/src/core/parser/extractors/base.ts +7 -3
- package/src/core/parser/extractors/csharp.ts +7 -3
- package/src/core/parser/extractors/django-semantic.ts +4 -36
- package/src/core/parser/extractors/elysia-semantic.ts +3 -24
- package/src/core/parser/extractors/express-semantic.ts +3 -18
- package/src/core/parser/extractors/fastapi-semantic.ts +19 -53
- package/src/core/parser/extractors/fastify-semantic.ts +3 -18
- package/src/core/parser/extractors/flask-semantic.ts +22 -55
- package/src/core/parser/extractors/go-semantic.ts +92 -33
- package/src/core/parser/extractors/hono-semantic.ts +3 -24
- package/src/core/parser/extractors/java.ts +5 -3
- package/src/core/parser/extractors/laravel-semantic.ts +44 -16
- package/src/core/parser/extractors/mcp-cli-semantic.ts +6 -7
- package/src/core/parser/extractors/nestjs-semantic.ts +3 -19
- package/src/core/parser/extractors/php.ts +16 -0
- package/src/core/parser/extractors/python.ts +9 -4
- package/src/core/parser/extractors/registry.ts +26 -5
- package/src/core/parser/extractors/ruby.ts +8 -5
- package/src/core/parser/extractors/rust.ts +31 -13
- package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
- package/src/core/parser/extractors/symfony-semantic.ts +4 -37
- package/src/core/parser/extractors/typescript.ts +14 -1
- package/src/core/parser/implementation-fingerprint.ts +97 -0
- package/src/core/parser/language-capabilities.ts +23 -7
- package/src/core/parser/schema/providers/laravel-migration-provider.ts +73 -50
- package/src/core/parser/schema/schema-provider-registry.ts +1 -3
- package/src/core/parser/schema/schema-provider.interface.ts +2 -1
- package/src/core/parser/semantic-revision.ts +3 -0
- package/src/core/parser/static-string.ts +51 -0
- package/src/core/resolver/call-graph-tracer.ts +337 -28
- package/src/core/resolver/import-resolver.ts +107 -179
- package/src/core/resolver/interpretation-inputs.ts +7 -0
- package/src/core/resolver/languages/go.ts +103 -0
- package/src/core/resolver/languages/managed.ts +200 -0
- package/src/core/resolver/languages/python.ts +115 -0
- package/src/core/resolver/languages/ruby.ts +40 -0
- package/src/core/resolver/languages/rust.ts +127 -0
- package/src/core/resolver/languages/shared.ts +71 -0
- package/src/core/resolver/module-resolver.ts +8 -4
- package/src/core/resolver/slice-catalog.ts +79 -0
- package/src/core/resolver/slice-format.ts +9 -0
- package/src/core/resolver/symbol-impact.ts +381 -0
- package/src/core/resolver/vertical-slice-tracer.ts +93 -115
- package/src/core/resources/ignore.ts +22 -1
- package/src/core/resources/source-files.ts +143 -20
- package/src/core/resources/source-inventory.ts +55 -0
- package/src/core/retrieval/context-page.ts +109 -0
- package/src/core/retrieval/context.ts +320 -0
- package/src/core/retrieval/resolution-warnings.ts +21 -0
- package/src/core/retrieval/symbol-evidence.ts +97 -0
- package/src/core/retrieval/typescript-references.ts +262 -0
- package/src/core/telemetry/telemetry.ts +54 -9
- package/src/index.ts +0 -3
- package/src/mcp/schemas.ts +61 -420
- package/src/mcp/server.ts +116 -290
- package/src/mcp/tools/boundary.ts +2 -2
- package/src/mcp/tools/check-boundary.ts +55 -60
- package/src/mcp/tools/get-domain-catalog.ts +32 -219
- package/src/mcp/tools/get-symbol-impact.ts +45 -5
- package/src/mcp/tools/get-symbol.ts +227 -3
- package/src/mcp/tools/locate-symbol.ts +54 -14
- package/src/mcp/tools/{domain.ts → map.ts} +4 -18
- package/src/mcp/tools/register-domain.ts +41 -3
- package/src/mcp/tools/symbol.ts +23 -21
- package/src/mcp/tools/trace-vertical-slice.ts +36 -10
- package/src/mcp/workspace-manager.ts +15 -4
- package/src/mcp/workspace-watcher.ts +8 -8
- package/src/types/index.ts +35 -53
- package/src/cli/commands/topology.ts +0 -161
- package/src/core/database/repositories/environment.repository.ts +0 -207
- package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
- package/src/core/session/session-manager.ts +0 -107
- package/src/core/topology/environment-detector.ts +0 -973
- package/src/core/topology/types.ts +0 -83
- package/src/mcp/tools/feature.ts +0 -67
- package/src/mcp/tools/get-environment-topology.ts +0 -138
- package/src/mcp/tools/get-feature-context.ts +0 -224
- package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
- package/src/mcp/tools/register-feature.ts +0 -110
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { lstatSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, relative, resolve } from "node:path";
|
|
3
|
+
import { getLanguageCapability } from "../parser/language-capabilities.ts";
|
|
4
|
+
import { shouldIgnoreSourcePath } from "./ignore.ts";
|
|
5
|
+
import { readSourceDirectory } from "./source-files.ts";
|
|
6
|
+
|
|
7
|
+
export interface SourceInventory { root: string; files: readonly string[] }
|
|
8
|
+
export interface ScanOptions {
|
|
9
|
+
directory?: string;
|
|
10
|
+
ignorePatterns?: string[];
|
|
11
|
+
excludeRoots?: string[];
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}
|
|
14
|
+
function contained(file: string, root: string): boolean {
|
|
15
|
+
const rel = relative(root, file).replace(/\\/g, "/");
|
|
16
|
+
return !isAbsolute(rel) && rel !== ".." && !rel.startsWith("../");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Shared source membership. Read failures propagate instead of certifying an empty scan. */
|
|
20
|
+
export function scanSourceFiles(root: string, options: ScanOptions = {}): SourceInventory {
|
|
21
|
+
root = resolve(root);
|
|
22
|
+
const directory = resolve(options.directory ?? root);
|
|
23
|
+
if (!contained(directory, root)) throw new Error(`Source directory escapes workspace: ${directory}`);
|
|
24
|
+
const files: string[] = [];
|
|
25
|
+
const walk = (dir: string) => {
|
|
26
|
+
options.signal?.throwIfAborted();
|
|
27
|
+
let entries;
|
|
28
|
+
try { entries = readSourceDirectory(dir); }
|
|
29
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return; throw error; }
|
|
30
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
31
|
+
options.signal?.throwIfAborted();
|
|
32
|
+
const file = resolve(dir, entry.name);
|
|
33
|
+
const rel = relative(root, file).replace(/\\/g, "/");
|
|
34
|
+
if (shouldIgnoreSourcePath(rel, options.ignorePatterns) || options.excludeRoots?.some(child => rel === child || rel.startsWith(child + "/"))) continue;
|
|
35
|
+
if (entry.isDirectory()) walk(file);
|
|
36
|
+
else if (entry.isSymbolicLink()) {
|
|
37
|
+
try {
|
|
38
|
+
const target = realpathSync(file);
|
|
39
|
+
if (contained(target, realpathSync(root)) && statSync(target).isFile() && getLanguageCapability(target)) files.push(file);
|
|
40
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
41
|
+
} else if (entry.isFile() && getLanguageCapability(file)) files.push(file);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
try {
|
|
45
|
+
if (!contained(realpathSync(directory), realpathSync(root))) throw new Error(`Source directory escapes workspace: ${directory}`);
|
|
46
|
+
if (!lstatSync(directory).isDirectory()) return { root, files };
|
|
47
|
+
walk(directory);
|
|
48
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
49
|
+
return { root, files };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function listSourceFiles(directory: string, pattern: RegExp, inventory?: SourceInventory): string[] {
|
|
53
|
+
const source = inventory ?? scanSourceFiles(directory);
|
|
54
|
+
return source.files.filter(file => contained(file, resolve(directory)) && pattern.test(file));
|
|
55
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { ImportRelationship } from "../../types/index.ts";
|
|
2
|
+
import type { ContextValue } from "./typescript-references.ts";
|
|
3
|
+
|
|
4
|
+
export type SourceItem = {
|
|
5
|
+
selection_role?: "implementation" | "contract";
|
|
6
|
+
kind: "source";
|
|
7
|
+
name: string;
|
|
8
|
+
reason: "target_implementation" | "direct_import_declaration" | "local_dependency";
|
|
9
|
+
source: { file_path: string; indexed_content_hash: string; start_line: number; end_line: number; text: string };
|
|
10
|
+
fragment?: { start_utf16: number; end_utf16: number; total_utf16: number; declaration_start_line: number; declaration_end_line: number };
|
|
11
|
+
};
|
|
12
|
+
type DiagnosticItem = { kind: "diagnostic"; reason: string; file_path?: string; detail?: string };
|
|
13
|
+
export type ContextItem = SourceItem | DiagnosticItem | { kind: "relationship"; reason: "target_file_import"; relationship: ImportRelationship } |
|
|
14
|
+
{ kind: "type_contract"; name: string; file_path: string; indexed_content_hash: string; start_line: number; end_line: number;
|
|
15
|
+
projection: "public_instance_signatures"; text: string; inferred_types: "unknown" | "explicit"; fragment?: SourceItem["fragment"] } |
|
|
16
|
+
{ kind: "selection"; reason: "known_call_arguments"; file_path: string; start_line: number; arguments: ContextValue[]; pruned_branches: number };
|
|
17
|
+
|
|
18
|
+
export function response(payload: object) {
|
|
19
|
+
return { content: [{ type: "text" as const, text: JSON.stringify(payload) }] };
|
|
20
|
+
}
|
|
21
|
+
export function budgetedResponse(payload: Record<string, unknown>, budget: number) {
|
|
22
|
+
let bytes = 0;
|
|
23
|
+
for (;;) {
|
|
24
|
+
const result = response({ ...payload, output_bytes: bytes });
|
|
25
|
+
const measured = Buffer.byteLength(JSON.stringify(result), "utf8");
|
|
26
|
+
if (bytes === measured) {
|
|
27
|
+
if (measured > budget) return response({ status: "budget_too_small", minimum_budget_bytes: measured,
|
|
28
|
+
message: "Required response metadata exceeds this budget; retry with a larger budget." });
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
bytes = measured;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
interface PageOptions {
|
|
35
|
+
items: ContextItem[];
|
|
36
|
+
start: number;
|
|
37
|
+
sourceOffset: number;
|
|
38
|
+
budget: number;
|
|
39
|
+
incomplete: boolean;
|
|
40
|
+
base: Record<string, unknown> & { query_id: string; snapshot_id: string };
|
|
41
|
+
accounting: { omitted_by_capacity: number; unexpanded_dependency_files: number };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function pageContext(options: PageOptions) {
|
|
45
|
+
const { items: all, start, sourceOffset, budget, incomplete, base, accounting } = options;
|
|
46
|
+
const current = all[start];
|
|
47
|
+
const currentText = current?.kind === "source" ? current.source.text : current?.kind === "type_contract" ? current.text : undefined;
|
|
48
|
+
if (sourceOffset && (currentText === undefined || sourceOffset >= currentText.length ||
|
|
49
|
+
currentText.charCodeAt(sourceOffset - 1) >= 0xd800 && currentText.charCodeAt(sourceOffset - 1) <= 0xdbff ||
|
|
50
|
+
currentText[sourceOffset - 1] === "\r" && currentText[sourceOffset] === "\n"))
|
|
51
|
+
return response({ status: "invalid_continuation", message: "Source fragment offset is outside the selected declaration." });
|
|
52
|
+
const envelope = (items: ContextItem[], end: number, nextSourceOffset = 0) => ({
|
|
53
|
+
...base,
|
|
54
|
+
status: incomplete || end < all.length || start > 0 || sourceOffset > 0 ? "partial" : "success",
|
|
55
|
+
completeness: incomplete || end < all.length || start > 0 || sourceOffset > 0 ? "partial" : "complete",
|
|
56
|
+
items,
|
|
57
|
+
accounting: { total: all.length, returned: items.length, offset: start, omitted_before: start,
|
|
58
|
+
omitted_after: all.length - end, source_offset: sourceOffset, next_source_offset: nextSourceOffset,
|
|
59
|
+
...accounting },
|
|
60
|
+
...(end < all.length && (end > start || nextSourceOffset > sourceOffset) ? { continuation: Buffer.from(JSON.stringify({ query: base.query_id, snapshot: base.snapshot_id, offset: end,
|
|
61
|
+
...(nextSourceOffset ? { source_offset: nextSourceOffset } : {}) })).toString("base64url") } : {}),
|
|
62
|
+
budget_bytes: budget,
|
|
63
|
+
});
|
|
64
|
+
let end = start;
|
|
65
|
+
const page: ContextItem[] = [];
|
|
66
|
+
let result = budgetedResponse(envelope([], start), budget);
|
|
67
|
+
for (; end < all.length; end++) {
|
|
68
|
+
const item = all[end]!;
|
|
69
|
+
const offset = end === start ? sourceOffset : 0;
|
|
70
|
+
const text = item.kind === "source" ? item.source.text : item.kind === "type_contract" ? item.text : undefined;
|
|
71
|
+
const fragment = (stop: number): ContextItem => {
|
|
72
|
+
if (text === undefined || (item.kind !== "source" && item.kind !== "type_contract")) return item;
|
|
73
|
+
const location = item.kind === "source" ? item.source : item;
|
|
74
|
+
const portion = text.slice(offset, stop);
|
|
75
|
+
const identity = { start_utf16: offset, end_utf16: stop, total_utf16: text.length,
|
|
76
|
+
declaration_start_line: location.start_line, declaration_end_line: location.end_line };
|
|
77
|
+
if (item.kind === "type_contract") return { ...item, text: portion, fragment: identity };
|
|
78
|
+
const line = item.source.start_line + (text.slice(0, offset).match(/\r\n|\r|\n/g)?.length ?? 0);
|
|
79
|
+
const lastLine = line + (portion.match(/\r\n|\r|\n/g)?.length ?? 0) - (/\r\n$|[\r\n]$/.test(portion) ? 1 : 0);
|
|
80
|
+
return { ...item, source: { ...item.source, text: portion, start_line: line, end_line: Math.max(line, lastLine) }, fragment: identity };
|
|
81
|
+
};
|
|
82
|
+
const whole = offset ? fragment(text!.length) : item;
|
|
83
|
+
const next = budgetedResponse(envelope([...page, whole], end + 1), budget);
|
|
84
|
+
if (JSON.parse(next.content[0]!.text).status === "budget_too_small") {
|
|
85
|
+
if (text !== undefined) {
|
|
86
|
+
let low = offset + 1, high = text.length - 1;
|
|
87
|
+
while (low <= high) {
|
|
88
|
+
const middle = Math.floor((low + high) / 2);
|
|
89
|
+
let stop = middle;
|
|
90
|
+
// Keep UTF-16 surrogate pairs and CRLF boundaries intact.
|
|
91
|
+
if (stop > offset && ((text.charCodeAt(stop - 1) >= 0xd800 && text.charCodeAt(stop - 1) <= 0xdbff) || text[stop - 1] === "\r" && text[stop] === "\n")) stop--;
|
|
92
|
+
if (stop === offset && offset + 2 < text.length) stop = offset + 2;
|
|
93
|
+
const partial = stop > offset ? budgetedResponse(envelope([...page, fragment(stop)], end, stop), budget) : undefined;
|
|
94
|
+
if (partial && JSON.parse(partial.content[0]!.text).status !== "budget_too_small") {
|
|
95
|
+
result = partial; low = middle + 1;
|
|
96
|
+
} else high = middle - 1;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
page.push(whole);
|
|
102
|
+
result = next;
|
|
103
|
+
}
|
|
104
|
+
if (end === start && all.length > start && !JSON.parse(result.content[0]!.text).continuation) {
|
|
105
|
+
return budgetedResponse({ ...envelope([], start), status: "budget_too_small", completeness: "partial",
|
|
106
|
+
message: "Response metadata and the next item fragment do not fit. Increase budget_bytes; no source was silently omitted." }, budget);
|
|
107
|
+
}
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { pageContext, response, budgetedResponse, type ContextItem, type SourceItem } from "./context-page.ts";
|
|
2
|
+
import ts from "typescript";
|
|
3
|
+
import { bindContextFile, type ContextValue } from "./typescript-references.ts";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import type { SeptumRepository } from "../database/repository.ts";
|
|
6
|
+
import type { ValidatedSeptumConfig } from "../config/schema.ts";
|
|
7
|
+
import type { ImportRelationship, SymbolReference } from "../../types/index.ts";
|
|
8
|
+
import { computeContentHash } from "../ingestion/hasher.ts";
|
|
9
|
+
import { PARSER_FINGERPRINT } from "../parser/language-capabilities.ts";
|
|
10
|
+
import { RESOLVER_REVISION } from "../resolver/import-resolver.ts";
|
|
11
|
+
import { assertPathContained } from "../resolver/path-resolver.ts";
|
|
12
|
+
import { collectSourceSkips, readSourceFile, SOURCE_READ_REVISION } from "../resources/source-files.ts";
|
|
13
|
+
import { symbolTargetId } from "./symbol-evidence.ts";
|
|
14
|
+
|
|
15
|
+
export const CONTEXT_POLICY = "referenced-typescript-declarations/v4";
|
|
16
|
+
export const MIN_CONTEXT_BUDGET = 2048;
|
|
17
|
+
export const MAX_CONTEXT_BUDGET = 2 * 1024 * 1024;
|
|
18
|
+
const MAX_ITEMS = 256;
|
|
19
|
+
const MAX_SOURCE_BYTES = 8 * 1024 * 1024;
|
|
20
|
+
|
|
21
|
+
export interface ContextQuery {
|
|
22
|
+
query?: string;
|
|
23
|
+
symbol?: string;
|
|
24
|
+
symbol_ref?: SymbolReference;
|
|
25
|
+
file_path?: string;
|
|
26
|
+
domain?: string;
|
|
27
|
+
budget_bytes?: number;
|
|
28
|
+
continuation?: string;
|
|
29
|
+
}
|
|
30
|
+
function canonical(value: unknown): unknown {
|
|
31
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
32
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value)
|
|
33
|
+
.sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, canonical(entry)]));
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
function digest(value: unknown) { return computeContentHash(JSON.stringify(canonical(value))); }
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
/** Read-only context for a bounded import policy; no complete call graph claim. */
|
|
40
|
+
export async function retrieveContext(repo: SeptumRepository, config: ValidatedSeptumConfig, query: ContextQuery, workspaceRoot: string, signal?: AbortSignal) {
|
|
41
|
+
signal?.throwIfAborted();
|
|
42
|
+
const budget = query.budget_bytes ?? 16 * 1024;
|
|
43
|
+
if (!Number.isInteger(budget) || budget < MIN_CONTEXT_BUDGET || budget > MAX_CONTEXT_BUDGET) {
|
|
44
|
+
return response({ status: "invalid_budget", minimum_budget_bytes: MIN_CONTEXT_BUDGET, maximum_budget_bytes: MAX_CONTEXT_BUDGET });
|
|
45
|
+
}
|
|
46
|
+
const root = resolve(workspaceRoot);
|
|
47
|
+
const name = (query.symbol_ref?.name || query.symbol || query.query || "").trim();
|
|
48
|
+
if (!name) return response({ status: "invalid_query", message: "Choose a target with query, symbol or symbol_ref." });
|
|
49
|
+
const initialIndex = repo.getIndexIdentity();
|
|
50
|
+
if (query.symbol_ref && repo.getFileByPath(query.symbol_ref.file_path)?.content_hash !== query.symbol_ref.indexed_content_hash) {
|
|
51
|
+
return response({ status: "stale_reference", message: "Locate the target again before retrieving context." });
|
|
52
|
+
}
|
|
53
|
+
const candidates = repo.findSymbolsByName(name, { filePath: query.file_path, reference: query.symbol_ref, domain: query.domain });
|
|
54
|
+
if (candidates.length !== 1) {
|
|
55
|
+
return budgetedResponse({ status: candidates.length ? "ambiguous" : "not_found", policy: CONTEXT_POLICY,
|
|
56
|
+
candidate_count: candidates.length, candidates: candidates.slice(0, 5).map(candidate => candidate.symbol_ref),
|
|
57
|
+
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
|
+
}
|
|
59
|
+
const target = candidates[0]!;
|
|
60
|
+
if (!/\.(?:ts|mts|cts)$/.test(target.file_path)) {
|
|
61
|
+
return response({ status: "unsupported", capability: "TypeScript static imports and indexed declarations", message: "Use locate/inspect/impact for other languages." });
|
|
62
|
+
}
|
|
63
|
+
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 });
|
|
65
|
+
let cursor: { query: string; snapshot: string; offset: number; source_offset?: number } | undefined;
|
|
66
|
+
if (query.continuation) {
|
|
67
|
+
try {
|
|
68
|
+
cursor = JSON.parse(Buffer.from(query.continuation, "base64url").toString("utf8"));
|
|
69
|
+
if (!cursor || cursor.query !== queryId || typeof cursor.snapshot !== "string" ||
|
|
70
|
+
!Number.isSafeInteger(cursor.offset) || cursor.offset < 0 ||
|
|
71
|
+
cursor.source_offset !== undefined && (!Number.isSafeInteger(cursor.source_offset) || cursor.source_offset < 0)) throw new Error("invalid");
|
|
72
|
+
} catch { return response({ status: "invalid_continuation", message: "Continuation must match the target, workspace, policy and budget; restart retrieval." }); }
|
|
73
|
+
}
|
|
74
|
+
let freshness: "current" | "stale" | "unavailable" = "current";
|
|
75
|
+
let incomplete = repo.getMeta("sync_state") !== "complete";
|
|
76
|
+
let capacityOmissions = 0;
|
|
77
|
+
let unexpandedFiles = 0;
|
|
78
|
+
let sourceBytes = 0;
|
|
79
|
+
const collected = await collectSourceSkips(root, async () => {
|
|
80
|
+
const items: ContextItem[] = [];
|
|
81
|
+
const add = (item: ContextItem) => {
|
|
82
|
+
if (items.length < MAX_ITEMS) items.push(item);
|
|
83
|
+
else { incomplete = true; capacityOmissions++; }
|
|
84
|
+
};
|
|
85
|
+
const addDiagnostic = (reason: string, file_path?: string, detail?: string) => {
|
|
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);
|
|
282
|
+
const declaration = targetFile?.bound.declaration(target.line_start, target.line_end);
|
|
283
|
+
if (declaration) {
|
|
284
|
+
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
|
+
addDiagnostic("enclosing_declaration_reference_scope", target.file_path);
|
|
287
|
+
enqueueNode(target.file_path, declaration, 0, "target_implementation");
|
|
288
|
+
while (expansionQueue.length > 0) {
|
|
289
|
+
await expandReferences(expansionQueue.shift()!);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
else addDiagnostic("target_ast_declaration_not_found", target.file_path);
|
|
293
|
+
// Source precedes provenance so file-level import records cannot crowd out helpers.
|
|
294
|
+
const priority = (item: ContextItem) => item.kind === "source" ? item.reason === "target_implementation" ? 0 : item.selection_role === "contract" ? 2 : 1 : item.kind === "type_contract" ? 2 : 3;
|
|
295
|
+
items.sort((a, b) => priority(a) - priority(b));
|
|
296
|
+
for (const edge of referencedEdges) add({ kind: "relationship", reason: "target_file_import", relationship: edge });
|
|
297
|
+
return items;
|
|
298
|
+
});
|
|
299
|
+
signal?.throwIfAborted();
|
|
300
|
+
if (repo.getIndexIdentity() !== initialIndex) return response({ status: "index_changed", message: "Index changed during context analysis; retry retrieval." });
|
|
301
|
+
// Negative resolution can change when an unindexed file appears. Observed file
|
|
302
|
+
// reads alone cannot capture that; bind the resolved selection and diagnostics too.
|
|
303
|
+
const snapshot = digest({ index: initialIndex, inputs: collected.inputs.map(({ path, hash }) => ({ path, hash })), observations: collected.observations, selection: collected.value });
|
|
304
|
+
if (cursor && (cursor.snapshot !== snapshot || cursor.offset >= collected.value.length)) {
|
|
305
|
+
return response({ status: "stale_continuation", message: "Input/index identity changed or the page is invalid; restart retrieval." });
|
|
306
|
+
}
|
|
307
|
+
return pageContext({
|
|
308
|
+
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 },
|
|
311
|
+
base: {
|
|
312
|
+
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,
|
|
314
|
+
freshness_scope: "returned source hashes checked against index during response preparation",
|
|
315
|
+
completeness_scope: "target and bound local/referenced declarations in directly imported TypeScript files and up to three import edges",
|
|
316
|
+
capability_limits: "static references, not calls", task_sufficiency: "unknown",
|
|
317
|
+
input_count: collected.inputs.length, selected_source_bytes_read: sourceBytes, dependency_depth: 3,
|
|
318
|
+
},
|
|
319
|
+
});
|
|
320
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import type { SeptumRepository } from "../database/repository.ts";
|
|
3
|
+
import type { SymbolReference } from "../../types/index.ts";
|
|
4
|
+
import { computeContentHash } from "../ingestion/hasher.ts";
|
|
5
|
+
import { collectSourceSkipsSync, probeSourcePath, readSourceFile } from "../resources/source-files.ts";
|
|
6
|
+
import { assertPathContained } from "../resolver/path-resolver.ts";
|
|
7
|
+
import { getOperationCapabilities, PARSER_FINGERPRINT } from "../parser/language-capabilities.ts";
|
|
8
|
+
|
|
9
|
+
/** Content-bound declaration identity, shared across operations; not a continuation token. */
|
|
10
|
+
export function symbolTargetId(workspace: string, ref: SymbolReference): string {
|
|
11
|
+
return computeContentHash(JSON.stringify([resolve(workspace), ref.file_path, ref.language, ref.name, ref.kind,
|
|
12
|
+
ref.signature, ref.start_line, ref.end_line, ref.indexed_content_hash, ref.container ?? null, ref.receiver ?? null]));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function symbolWorkspace(repo: SeptumRepository, explicit?: string): string {
|
|
16
|
+
return resolve(explicit || (typeof repo.getMeta === "function" ? repo.getMeta("workspace_root") : null) || process.cwd());
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type TextResult = { content: Array<{ type: string; text: string }>; metadata?: unknown };
|
|
20
|
+
type EvidenceQuery = { operation: "locate" | "inspect" | "impact"; requested?: SymbolReference; diagnostics?: string[] };
|
|
21
|
+
|
|
22
|
+
/** Checks the selected source and observed reads, without certifying a legacy caller/dependency closure. */
|
|
23
|
+
export function withSymbolEvidence<T extends TextResult>(repo: SeptumRepository, root: string, query: EvidenceQuery, build: () => T): T {
|
|
24
|
+
const meta = (key: string) => typeof repo.getMeta === "function" ? repo.getMeta(key) : null;
|
|
25
|
+
const collected = collectSourceSkipsSync(root, () => {
|
|
26
|
+
const result = build();
|
|
27
|
+
const payload = JSON.parse(result.content[0]!.text);
|
|
28
|
+
const target: SymbolReference | undefined = payload.symbol_ref;
|
|
29
|
+
const reasons = [...(query.diagnostics ?? [])];
|
|
30
|
+
let freshness: "current" | "stale" | "unavailable" = "unavailable";
|
|
31
|
+
let observedHash: string | null = null;
|
|
32
|
+
if (target) {
|
|
33
|
+
try {
|
|
34
|
+
assertPathContained(target.file_path, root, "Symbol evidence source");
|
|
35
|
+
if (probeSourcePath(resolve(root, target.file_path)) !== "file") reasons.push("target_source_unavailable");
|
|
36
|
+
else {
|
|
37
|
+
observedHash = computeContentHash(readSourceFile(resolve(root, target.file_path)));
|
|
38
|
+
const indexed = repo.getFileByPath(target.file_path);
|
|
39
|
+
if (indexed?.content_hash !== target.indexed_content_hash) reasons.push("target_index_changed");
|
|
40
|
+
else {
|
|
41
|
+
freshness = observedHash === target.indexed_content_hash ? "current" : "stale";
|
|
42
|
+
if (freshness === "stale") reasons.push("target_source_differs_from_index");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
} catch { reasons.push("target_source_unavailable_or_out_of_scope"); }
|
|
46
|
+
} else reasons.push(payload.status === "ambiguous" ? "target_ambiguous" : payload.status === "stale_reference" ? "stale_reference" : "target_not_selected");
|
|
47
|
+
const syncState = meta("sync_state");
|
|
48
|
+
if (syncState !== "complete") reasons.push("index_completeness_unverified");
|
|
49
|
+
const parserRevision = meta("parser_revision");
|
|
50
|
+
if (parserRevision !== PARSER_FINGERPRINT) reasons.push("indexed_parser_revision_unverified");
|
|
51
|
+
return { result, payload, target, freshness, observedHash, reasons, syncState, parserRevision };
|
|
52
|
+
});
|
|
53
|
+
const { result, payload, target, freshness, observedHash, reasons, syncState, parserRevision } = collected.value;
|
|
54
|
+
const staleInputs = collected.inputs.filter(input => {
|
|
55
|
+
const indexed = repo.getFileByPath(input.path);
|
|
56
|
+
return indexed && input.hash !== "file_too_large" && indexed.content_hash !== input.hash;
|
|
57
|
+
}).length;
|
|
58
|
+
const unavailableInputs = new Set([
|
|
59
|
+
...collected.observations.paths.filter(input => input.kind !== "file" && repo.getFileByPath(input.path)).map(input => input.path),
|
|
60
|
+
...collected.skipped.filter(input => repo.getFileByPath(input.path)).map(input => input.path),
|
|
61
|
+
]).size;
|
|
62
|
+
if (staleInputs) reasons.push("observed_indexed_inputs_stale");
|
|
63
|
+
if (unavailableInputs) reasons.push("observed_indexed_inputs_unavailable");
|
|
64
|
+
if (collected.skipped.length) reasons.push("source_read_exclusions");
|
|
65
|
+
const leanRetrieval = {
|
|
66
|
+
operation: query.operation,
|
|
67
|
+
target_id: target ? symbolTargetId(root, target) : null,
|
|
68
|
+
...(query.requested ? { requested_target_id: symbolTargetId(root, query.requested) } : {}),
|
|
69
|
+
freshness,
|
|
70
|
+
freshness_scope: "selected_declaration_source_only",
|
|
71
|
+
completeness: "partial",
|
|
72
|
+
analysis_freshness: "unavailable",
|
|
73
|
+
source_version: target ? {
|
|
74
|
+
file_path: target.file_path,
|
|
75
|
+
indexed_hash: target.indexed_content_hash,
|
|
76
|
+
observed_hash: observedHash,
|
|
77
|
+
} : null,
|
|
78
|
+
...(staleInputs > 0 || unavailableInputs > 0 ? {
|
|
79
|
+
observed_inputs: {
|
|
80
|
+
stale_indexed_files: staleInputs,
|
|
81
|
+
unavailable_indexed_files: unavailableInputs,
|
|
82
|
+
},
|
|
83
|
+
} : {}),
|
|
84
|
+
reasons: [...new Set(reasons)].sort(),
|
|
85
|
+
};
|
|
86
|
+
if (query.operation === "locate" && payload.found && freshness !== "current") {
|
|
87
|
+
const note = `[SOURCE ${freshness.toUpperCase()}] Indexed coordinates are not validated against current source; synchronize before editing.`;
|
|
88
|
+
payload.summary = `${payload.summary} | ${note}`;
|
|
89
|
+
payload.message = `${payload.message} | ${note}`;
|
|
90
|
+
}
|
|
91
|
+
const enriched = { ...payload, ...(target ? { capabilities: getOperationCapabilities(target.file_path) } : {}), retrieval: leanRetrieval };
|
|
92
|
+
return {
|
|
93
|
+
...result,
|
|
94
|
+
content: [{ ...result.content[0]!, text: JSON.stringify(enriched, null, 2) }, ...result.content.slice(1)],
|
|
95
|
+
...("metadata" in result ? { metadata: enriched } : { metadata: enriched }),
|
|
96
|
+
} as T;
|
|
97
|
+
}
|