@dimassetoid/septum-mcp 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -0,0 +1,293 @@
1
+ import ts from "typescript";
2
+
3
+ export type ContextValue = { kind: "unknown" | "undefined" } |
4
+ { kind: "literal"; value: string | number | boolean | null } |
5
+ { kind: "object"; properties: Record<string, ContextValue> };
6
+
7
+ /** Bind identifiers inside one verified file, without reading libraries or disk.
8
+ * Import resolution remains owned by Septum's observed resolver.
9
+ */
10
+ export function bindContextFile(path: string, text: string) {
11
+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
12
+ const host: ts.CompilerHost = {
13
+ getSourceFile: name => name === path ? source : undefined,
14
+ getDefaultLibFileName: () => "", writeFile: () => {}, getCurrentDirectory: () => "",
15
+ getDirectories: () => [], fileExists: name => name === path,
16
+ readFile: name => name === path ? text : undefined, getCanonicalFileName: name => name,
17
+ useCaseSensitiveFileNames: () => true, getNewLine: () => "\n",
18
+ };
19
+ const program = ts.createProgram([path], { allowJs: true, noLib: true, noResolve: true, jsx: ts.JsxEmit.Preserve }, host);
20
+ const checker = program.getTypeChecker();
21
+ function top(node: ts.Node): ts.Node {
22
+ while (node.parent && node.parent !== source) node = node.parent;
23
+ return node;
24
+ }
25
+ return {
26
+ source,
27
+ checker,
28
+ hasErrors: program.getSyntacticDiagnostics(source).length > 0,
29
+ declaration(start: number, end: number) {
30
+ const stmt = source.statements.find(node => source.getLineAndCharacterOfPosition(node.getStart()).line + 1 <= start &&
31
+ source.getLineAndCharacterOfPosition(node.end).line + 1 >= end);
32
+ if (stmt && ts.isClassDeclaration(stmt)) {
33
+ const member = stmt.members.find(m =>
34
+ source.getLineAndCharacterOfPosition(m.getStart()).line + 1 <= start &&
35
+ source.getLineAndCharacterOfPosition(m.end).line + 1 >= end
36
+ );
37
+ if (member) return member;
38
+ }
39
+ return stmt;
40
+ },
41
+ contract(node: ts.ClassDeclaration) {
42
+ const printer = ts.createPrinter();
43
+ const members: string[] = [];
44
+ const signatures: ts.Node[] = [...(node.typeParameters ?? []), ...(node.heritageClauses ?? [])];
45
+ let inferred = false;
46
+ for (const member of node.members) {
47
+ const modifiers = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined;
48
+ if (modifiers?.some(m => [ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.StaticKeyword].includes(m.kind))) continue;
49
+ if (ts.isConstructorDeclaration(member)) {
50
+ for (const parameter of member.parameters) {
51
+ if (!ts.isIdentifier(parameter.name) || !parameter.modifiers?.some(m => m.kind === ts.SyntaxKind.PublicKeyword || m.kind === ts.SyntaxKind.ReadonlyKeyword) ||
52
+ parameter.modifiers.some(m => m.kind === ts.SyntaxKind.PrivateKeyword || m.kind === ts.SyntaxKind.ProtectedKeyword)) continue;
53
+ if (parameter.type) signatures.push(parameter.type); else inferred = true;
54
+ members.push(printer.printNode(ts.EmitHint.Unspecified, ts.factory.createPropertySignature(
55
+ parameter.modifiers.filter(m => m.kind === ts.SyntaxKind.ReadonlyKeyword), parameter.name, parameter.questionToken,
56
+ parameter.type ?? ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)), source));
57
+ }
58
+ }
59
+ if (!member.name || ts.isPrivateIdentifier(member.name) || ts.isComputedPropertyName(member.name)) continue;
60
+ if (ts.isMethodDeclaration(member)) {
61
+ signatures.push(...(member.typeParameters ?? []));
62
+ const parameters = member.parameters.map(p => {
63
+ if (p.type) signatures.push(p.type); else inferred = true;
64
+ return ts.factory.updateParameterDeclaration(p, undefined, p.dotDotDotToken, p.name,
65
+ p.questionToken ?? (p.initializer ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined),
66
+ p.type ?? ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword), undefined);
67
+ });
68
+ if (member.type) signatures.push(member.type); else inferred = true;
69
+ const signature = ts.factory.createMethodSignature(undefined, member.name, member.questionToken,
70
+ member.typeParameters, parameters, member.type ?? ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword));
71
+ members.push(printer.printNode(ts.EmitHint.Unspecified, signature, source));
72
+ } else if (ts.isPropertyDeclaration(member)) {
73
+ if (member.type) signatures.push(member.type); else inferred = true;
74
+ members.push(printer.printNode(ts.EmitHint.Unspecified, ts.factory.createPropertySignature(
75
+ modifiers?.filter(m => m.kind === ts.SyntaxKind.ReadonlyKeyword), member.name, member.questionToken,
76
+ member.type ?? ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword)), source));
77
+ } else if (ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) {
78
+ const type = ts.isGetAccessorDeclaration(member) ? member.type : member.parameters[0]?.type;
79
+ if (type) signatures.push(type); else inferred = true;
80
+ members.push(`${member.name.getText(source)}: ${type?.getText(source) ?? "unknown"};`);
81
+ }
82
+ }
83
+ const heritage = node.heritageClauses?.find(clause => clause.token === ts.SyntaxKind.ExtendsKeyword);
84
+ return { text: `interface ${node.name?.text ?? "Anonymous"}${node.typeParameters ? `<${node.typeParameters.map(p => p.getText(source)).join(", ")}>` : ""}${heritage ? ` ${heritage.getText(source)}` : ""} {\n${members.map(m => ` ${m}`).join("\n")}\n}`,
85
+ signatures, inferred };
86
+ },
87
+ references(node: ts.Node, argumentFacts?: ContextValue[], signatureNodes?: ts.Node[]) {
88
+ const locals = new Set<ts.Node>();
89
+ const imports = new Map<ts.ImportDeclaration, Set<string>>();
90
+ const calls: Array<{ target: ts.Node; name?: string; arguments: ContextValue[] }> = [];
91
+ const escapes = new Set<ts.Node>();
92
+ const facts = new Map<ts.Symbol, ContextValue>();
93
+ const unknown: ContextValue = { kind: "unknown" };
94
+ const absent: ContextValue = { kind: "undefined" };
95
+ const fn = ts.isFunctionLike(node) ? node : ts.isVariableStatement(node) && node.declarationList.declarations.length === 1
96
+ ? node.declarationList.declarations[0]?.initializer : undefined;
97
+ const evaluate = (expression: ts.Node, depth = 0): ContextValue => {
98
+ if (depth > 8) return unknown;
99
+ if (ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isNonNullExpression(expression)) return evaluate(expression.expression, depth + 1);
100
+ if (expression.kind === ts.SyntaxKind.TrueKeyword) return { kind: "literal", value: true };
101
+ if (expression.kind === ts.SyntaxKind.FalseKeyword) return { kind: "literal", value: false };
102
+ if (expression.kind === ts.SyntaxKind.NullKeyword) return { kind: "literal", value: null };
103
+ if (ts.isStringLiteral(expression) && expression.text.length <= 256) return { kind: "literal", value: expression.text };
104
+ if (ts.isNumericLiteral(expression)) return { kind: "literal", value: Number(expression.text) };
105
+ if (ts.isIdentifier(expression)) {
106
+ const symbol = checker.getSymbolAtLocation(expression);
107
+ if (symbol && facts.has(symbol)) return facts.get(symbol)!;
108
+ if (expression.text === "undefined" && !symbol?.declarations?.length) return absent;
109
+ const declaration = symbol?.valueDeclaration;
110
+ if (declaration && ts.isVariableDeclaration(declaration) && declaration.initializer &&
111
+ ts.isVariableDeclarationList(declaration.parent) && declaration.parent.flags & ts.NodeFlags.Const) {
112
+ // const protects the binding, not a mutable object shared with the caller.
113
+ if (ts.isObjectLiteralExpression(declaration.initializer)) return unknown;
114
+ return evaluate(declaration.initializer, depth + 1);
115
+ }
116
+ return unknown;
117
+ }
118
+ if (ts.isObjectLiteralExpression(expression)) {
119
+ const properties: Record<string, ContextValue> = Object.create(null);
120
+ if (expression.properties.length > 32) return unknown;
121
+ for (const property of expression.properties) {
122
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) return unknown;
123
+ if (!ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name)) return unknown;
124
+ properties[property.name.text] = evaluate(ts.isPropertyAssignment(property) ? property.initializer : property.name, depth + 1);
125
+ }
126
+ return { kind: "object", properties };
127
+ }
128
+ if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) {
129
+ const owner = evaluate(expression.expression, depth + 1);
130
+ const key = ts.isPropertyAccessExpression(expression) ? expression.name.text :
131
+ expression.argumentExpression && ts.isStringLiteral(expression.argumentExpression) ? expression.argumentExpression.text : undefined;
132
+ if (owner.kind === "object" && key !== undefined) return owner.properties[key] ?? absent;
133
+ if (expression.questionDotToken && (owner.kind === "undefined" || owner.kind === "literal" && owner.value === null)) return absent;
134
+ }
135
+ if (ts.isPrefixUnaryExpression(expression) && expression.operator === ts.SyntaxKind.ExclamationToken) {
136
+ const value = evaluate(expression.operand, depth + 1);
137
+ if (value.kind !== "unknown") return { kind: "literal", value: value.kind === "undefined" || value.kind === "literal" && !value.value };
138
+ }
139
+ if (ts.isBinaryExpression(expression) && [ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken].includes(expression.operatorToken.kind)) {
140
+ const left = evaluate(expression.left, depth + 1), right = evaluate(expression.right, depth + 1);
141
+ if ((left.kind === "literal" || left.kind === "undefined") && (right.kind === "literal" || right.kind === "undefined")) {
142
+ const equal = (left.kind === "literal" ? left.value : undefined) === (right.kind === "literal" ? right.value : undefined);
143
+ return { kind: "literal", value: expression.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken ? equal : !equal };
144
+ }
145
+ }
146
+ return unknown;
147
+ };
148
+ if (fn && ts.isFunctionLike(fn)) fn.parameters.forEach((parameter, index) => {
149
+ if (!ts.isIdentifier(parameter.name)) return;
150
+ const symbol = checker.getSymbolAtLocation(parameter.name);
151
+ let value = argumentFacts ? argumentFacts[index] ?? absent : unknown;
152
+ if (value.kind === "undefined" && parameter.initializer) value = evaluate(parameter.initializer);
153
+ if (symbol) facts.set(symbol, value);
154
+ });
155
+ const invalidate = (expression: ts.Node): void => {
156
+ const tracked = new Set<ContextValue>([...facts.values()].filter(value => value.kind === "object"));
157
+ const aliases = (value: ContextValue): boolean => tracked.has(value) ||
158
+ value.kind === "object" && Object.values(value.properties).some(aliases);
159
+ if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression) || aliases(evaluate(expression)))
160
+ for (const [key, value] of facts) if (value.kind === "object") facts.set(key, unknown);
161
+ if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) return invalidate(expression.expression);
162
+ if (!ts.isIdentifier(expression)) return;
163
+ const symbol = checker.getSymbolAtLocation(expression);
164
+ if (symbol) facts.set(symbol, unknown);
165
+ };
166
+ const escapedClosures = new Set<ts.Node>();
167
+ const escape = (expression: ts.Node, depth = 0): void => {
168
+ if (depth > 64) {
169
+ for (const [key, value] of facts) if (value.kind === "object") facts.set(key, unknown);
170
+ return;
171
+ }
172
+ if (evaluate(expression).kind === "object") invalidate(expression);
173
+ // A scalar property read does not expose the containing option object.
174
+ if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) return;
175
+ if (ts.isIdentifier(expression)) {
176
+ const declaration = checker.getSymbolAtLocation(expression)?.valueDeclaration;
177
+ const initializer = declaration && ts.isVariableDeclaration(declaration) ? declaration.initializer : declaration;
178
+ if (initializer && !escapedClosures.has(initializer) &&
179
+ (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer) || ts.isFunctionDeclaration(initializer))) {
180
+ escapedClosures.add(initializer);
181
+ ts.forEachChild(initializer, child => escape(child, depth + 1));
182
+ }
183
+ return;
184
+ }
185
+ ts.forEachChild(expression, child => escape(child, depth + 1));
186
+ };
187
+ let prunedBranches = 0;
188
+ const visit = (child: ts.Node) => {
189
+ if (child !== node && child !== fn && ts.isFunctionLike(child)) {
190
+ const saved = new Map(facts);
191
+ facts.clear();
192
+ ts.forEachChild(child, visit);
193
+ facts.clear();
194
+ for (const [key, value] of saved) facts.set(key, value);
195
+ return;
196
+ }
197
+ if (!signatureNodes && (ts.isIfStatement(child) || ts.isConditionalExpression(child))) {
198
+ const condition = ts.isIfStatement(child) ? child.expression : child.condition;
199
+ const value = evaluate(condition);
200
+ visit(condition);
201
+ if (value.kind !== "unknown") {
202
+ const truthy = value.kind === "object" || value.kind === "literal" && Boolean(value.value);
203
+ const chosen = ts.isIfStatement(child) ? truthy ? child.thenStatement : child.elseStatement : truthy ? child.whenTrue : child.whenFalse;
204
+ prunedBranches++;
205
+ if (chosen) visit(chosen);
206
+ return;
207
+ }
208
+ }
209
+ if (!signatureNodes && ts.isCallExpression(child)) {
210
+ const effectful = (arg: ts.Node): boolean => ts.isCallExpression(arg) || ts.isNewExpression(arg) ||
211
+ ts.isAwaitExpression(arg) || ts.isDeleteExpression(arg) ||
212
+ ts.isBinaryExpression(arg) && arg.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && arg.operatorToken.kind <= ts.SyntaxKind.LastAssignment ||
213
+ ts.isPostfixUnaryExpression(arg) || ts.forEachChild(arg, n => effectful(n) || undefined) === true;
214
+ const callArgs = () => child.arguments.length <= 16
215
+ ? child.arguments.map(arg => child.arguments.some(effectful) ? unknown : evaluate(arg))
216
+ : Array(16).fill(unknown);
217
+
218
+ if (ts.isIdentifier(child.expression)) {
219
+ for (const declaration of checker.getSymbolAtLocation(child.expression)?.declarations ?? []) {
220
+ calls.push({ target: top(declaration),
221
+ name: ts.isImportSpecifier(declaration) ? (declaration.propertyName ?? declaration.name).text :
222
+ ts.isImportClause(declaration) ? "default" : undefined,
223
+ arguments: callArgs() });
224
+ }
225
+ } else if (
226
+ ts.isPropertyAccessExpression(child.expression) &&
227
+ child.expression.expression.kind === ts.SyntaxKind.ThisKeyword &&
228
+ ts.isClassDeclaration(node.parent)
229
+ ) {
230
+ const memberName = child.expression.name.text;
231
+ const sibling = node.parent.members.find(
232
+ (m) =>
233
+ m !== node &&
234
+ (ts.isMethodDeclaration(m) || ts.isGetAccessorDeclaration(m)) &&
235
+ m.name &&
236
+ (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)) &&
237
+ m.name.text === memberName
238
+ );
239
+ if (sibling) {
240
+ locals.add(sibling);
241
+ calls.push({ target: sibling, arguments: callArgs() });
242
+ }
243
+ }
244
+ ts.forEachChild(child, visit);
245
+ // An unknown callee may mutate object arguments. Subsequent guards cannot reuse those facts.
246
+ for (const arg of child.arguments) escape(arg);
247
+ return;
248
+ }
249
+ if (!signatureNodes && ts.isNewExpression(child)) {
250
+ ts.forEachChild(child, visit);
251
+ for (const arg of child.arguments ?? []) escape(arg);
252
+ return;
253
+ }
254
+ if (!signatureNodes && ts.isYieldExpression(child)) {
255
+ if (child.expression) escape(child.expression);
256
+ ts.forEachChild(child, visit);
257
+ return;
258
+ }
259
+ if (!signatureNodes && ts.isBinaryExpression(child) && child.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && child.operatorToken.kind <= ts.SyntaxKind.LastAssignment) invalidate(child.left);
260
+ if (!signatureNodes && ts.isDeleteExpression(child)) invalidate(child.expression);
261
+ if (!signatureNodes && (ts.isPostfixUnaryExpression(child) || ts.isPrefixUnaryExpression(child)) &&
262
+ [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(child.operator)) invalidate(child.operand);
263
+ if (ts.isIdentifier(child)) {
264
+ for (const decl of checker.getSymbolAtLocation(child)?.declarations ?? []) {
265
+ const owner = top(decl);
266
+ if (ts.isImportDeclaration(owner)) {
267
+ if (!(ts.isCallExpression(child.parent) && child.parent.expression === child)) escapes.add(owner);
268
+ const names = imports.get(owner) ?? new Set<string>();
269
+ names.add(ts.isImportSpecifier(decl) ? (decl.propertyName ?? decl.name).text :
270
+ ts.isImportClause(decl) ? "default" : "*");
271
+ imports.set(owner, names);
272
+ } else if (owner !== node && !(owner.pos <= node.pos && owner.end >= node.end) && source.statements.includes(owner as ts.Statement)) {
273
+ locals.add(owner);
274
+ if (!(ts.isCallExpression(child.parent) && child.parent.expression === child)) escapes.add(owner);
275
+ }
276
+ }
277
+ }
278
+ ts.forEachChild(child, visit);
279
+ };
280
+ if (signatureNodes) signatureNodes.forEach(visit); else visit(node);
281
+ return { locals: [...locals], imports, calls, escapes, prunedBranches };
282
+ },
283
+ exported(name: string) {
284
+ return source.statements.find(node => {
285
+ const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined;
286
+ if (!modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword)) return false;
287
+ if (name === "default") return modifiers.some(m => m.kind === ts.SyntaxKind.DefaultKeyword);
288
+ if (ts.isVariableStatement(node)) return node.declarationList.declarations.some(d => ts.isIdentifier(d.name) && d.name.text === name);
289
+ return "name" in node && (node as unknown as ts.NamedDeclaration).name?.getText(source) === name;
290
+ });
291
+ },
292
+ };
293
+ }
@@ -0,0 +1,182 @@
1
+ import { resolve } from "node:path";
2
+ import type { SeptumRepository } from "../database/repository.ts";
3
+ import type { ValidatedSeptumConfig } from "../config/schema.ts";
4
+ import type { SymbolCandidate } from "../../types/index.ts";
5
+ import { computeContentHash } from "../ingestion/hasher.ts";
6
+ import { assertPathContained } from "../resolver/path-resolver.ts";
7
+ import { readSourceFile } from "../resources/source-files.ts";
8
+ import {
9
+ pageContext,
10
+ response,
11
+ budgetedResponse,
12
+ type ContextItem,
13
+ type SourceItem,
14
+ } from "./context-page.ts";
15
+ import type { ContextQuery } from "./context.ts";
16
+
17
+ export const UNIVERSAL_CONTEXT_POLICY = "referenced-universal-declarations/v1";
18
+
19
+ function indexLineOffsets(source: string): { lineStarts: number[]; lineEnds: number[] } {
20
+ const lineStarts = [0];
21
+ const lineEnds: number[] = [];
22
+ for (const match of source.matchAll(/\r\n|\n|\r/g)) {
23
+ const end = match.index!;
24
+ lineEnds.push(end);
25
+ lineStarts.push(end + match[0].length);
26
+ }
27
+ lineEnds.push(source.length);
28
+ return { lineStarts, lineEnds };
29
+ }
30
+
31
+ export async function retrieveUniversalContext(
32
+ repo: SeptumRepository,
33
+ config: ValidatedSeptumConfig,
34
+ query: ContextQuery,
35
+ target: SymbolCandidate,
36
+ workspaceRoot: string,
37
+ signal?: AbortSignal
38
+ ) {
39
+ signal?.throwIfAborted();
40
+ const root = resolve(workspaceRoot);
41
+ const budget = query.budget_bytes ?? 65536;
42
+ const maxDepth = query.max_depth ?? 2;
43
+
44
+ const targetFile = repo.getFileByPath(target.file_path);
45
+ if (!targetFile) {
46
+ return response({ status: "file_not_indexed", message: `File '${target.file_path}' is not indexed.` });
47
+ }
48
+
49
+ let targetSource: string;
50
+ try {
51
+ assertPathContained(target.file_path, root, "Universal context");
52
+ targetSource = readSourceFile(resolve(root, target.file_path));
53
+ } catch {
54
+ return response({ status: "source_unavailable", message: `Could not read source file '${target.file_path}'.` });
55
+ }
56
+
57
+ const currentHash = computeContentHash(targetSource);
58
+ if (currentHash !== targetFile.content_hash) {
59
+ return response({
60
+ status: "stale_reference",
61
+ message: `File '${target.file_path}' has changed on disk since last indexed. Run 'septum sync'.`,
62
+ });
63
+ }
64
+
65
+ const { lineStarts, lineEnds } = indexLineOffsets(targetSource);
66
+ const startIdx = lineStarts[Math.max(0, target.line_start - 1)] ?? 0;
67
+ const endIdx = lineEnds[Math.min(lineEnds.length - 1, target.line_end - 1)] ?? targetSource.length;
68
+ const targetText = targetSource.slice(startIdx, endIdx);
69
+
70
+ const items: ContextItem[] = [];
71
+ const emittedKeys = new Set<string>();
72
+
73
+ const targetKey = `${target.file_path}:${target.line_start}-${target.line_end}`;
74
+ emittedKeys.add(targetKey);
75
+
76
+ // 1. Target implementation
77
+ const targetItem: SourceItem = {
78
+ kind: "source",
79
+ selection_role: "implementation",
80
+ depth: 0,
81
+ name: target.name,
82
+ reason: "target_implementation",
83
+ source: {
84
+ file_path: target.file_path,
85
+ indexed_content_hash: targetFile.content_hash,
86
+ start_line: target.line_start,
87
+ end_line: target.line_end,
88
+ text: targetText,
89
+ },
90
+ };
91
+ items.push(targetItem);
92
+
93
+ // 2. Import relationships from target file
94
+ const fileRels = repo.getImportRelationships(root, target.file_path);
95
+ for (const edge of fileRels) {
96
+ if (edge.source.line >= target.line_start && edge.source.line <= target.line_end) {
97
+ items.push({
98
+ kind: "relationship",
99
+ reason: "target_file_import",
100
+ relationship: edge,
101
+ });
102
+ }
103
+ }
104
+
105
+ // 3. Inspect direct outbound calls & symbol dependencies if maxDepth > 0
106
+ if (maxDepth > 0) {
107
+ const details = repo.getSymbolDetails(target.name, {
108
+ filePath: target.file_path,
109
+ workspaceRoot: root,
110
+ });
111
+
112
+ const calls = details?.outbound_calls ?? [];
113
+ for (const callName of calls) {
114
+ if (items.length >= 32) break;
115
+ const candidates = repo.findSymbolsByName(callName, {
116
+ domain: query.domain,
117
+ });
118
+ const resolved = candidates.find(c => c.file_path === target.file_path) ?? candidates[0];
119
+ if (resolved) {
120
+ const key = `${resolved.file_path}:${resolved.line_start}-${resolved.line_end}`;
121
+ if (emittedKeys.has(key)) continue;
122
+ emittedKeys.add(key);
123
+
124
+ try {
125
+ const resFile = repo.getFileByPath(resolved.file_path);
126
+ if (!resFile) continue;
127
+ const resSource = readSourceFile(resolve(root, resolved.file_path));
128
+ if (computeContentHash(resSource) !== resFile.content_hash) continue;
129
+
130
+ const offsets = indexLineOffsets(resSource);
131
+ const sIdx = offsets.lineStarts[Math.max(0, resolved.line_start - 1)] ?? 0;
132
+ const eIdx = offsets.lineEnds[Math.min(offsets.lineEnds.length - 1, resolved.line_end - 1)] ?? resSource.length;
133
+ const text = resSource.slice(sIdx, eIdx);
134
+
135
+ items.push({
136
+ kind: "source",
137
+ selection_role: "implementation",
138
+ depth: 1,
139
+ name: resolved.name,
140
+ reason: resolved.file_path === target.file_path ? "local_dependency" : "direct_import_declaration",
141
+ source: {
142
+ file_path: resolved.file_path,
143
+ indexed_content_hash: resFile.content_hash,
144
+ start_line: resolved.line_start,
145
+ end_line: resolved.line_end,
146
+ text,
147
+ },
148
+ });
149
+ } catch {
150
+ // Graceful degradation if dependency source is unreadable
151
+ }
152
+ }
153
+ }
154
+ }
155
+
156
+ const queryId = computeContentHash(JSON.stringify({
157
+ root,
158
+ target: target.name,
159
+ file_path: target.file_path,
160
+ policy: UNIVERSAL_CONTEXT_POLICY,
161
+ budget,
162
+ }));
163
+
164
+ return pageContext({
165
+ items,
166
+ start: 0,
167
+ sourceOffset: 0,
168
+ budget,
169
+ incomplete: false,
170
+ base: {
171
+ policy: UNIVERSAL_CONTEXT_POLICY,
172
+ query_id: queryId,
173
+ snapshot_id: currentHash,
174
+ target: target.name,
175
+ file_path: target.file_path,
176
+ },
177
+ accounting: {
178
+ omitted_by_capacity: 0,
179
+ unexpanded_dependency_files: 0,
180
+ },
181
+ });
182
+ }
@@ -0,0 +1,114 @@
1
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
2
+ import { SeptumTelemetry, type SeptumToolCallEvent } from "./telemetry.ts";
3
+
4
+ const SAMPLE_LIMIT = 500;
5
+
6
+ function readLogTail(path: string): string[] {
7
+ let fd;
8
+ try {
9
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
10
+ } catch (error) {
11
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
12
+ throw error;
13
+ }
14
+ try {
15
+ const stat = fstatSync(fd);
16
+ if (!stat.isFile()) throw new Error(`Telemetry log is not a regular file: ${path}`);
17
+ const length = Math.min(stat.size, SeptumTelemetry.MAX_LOG_SIZE_BYTES);
18
+ const offset = stat.size - length;
19
+ const buffer = Buffer.alloc(length);
20
+ let read = 0;
21
+ while (read < length) {
22
+ const count = readSync(fd, buffer, read, length - read, offset + read);
23
+ if (count === 0) break;
24
+ read += count;
25
+ }
26
+ const lines = buffer.subarray(0, read).toString("utf8").split("\n");
27
+ return offset ? lines.slice(1) : lines;
28
+ } finally {
29
+ closeSync(fd);
30
+ }
31
+ }
32
+
33
+ function parseToolEvent(line: string): SeptumToolCallEvent | undefined {
34
+ try {
35
+ const event = JSON.parse(line);
36
+ if ((event?.event === "tool_call_completed" || event?.event === "tool_call_failed") &&
37
+ (event.status === "success" || event.status === "error") &&
38
+ typeof event.tool === "string" && Number.isFinite(event.duration_ms) && event.duration_ms >= 0) return event;
39
+ } catch { /* The log can contain incomplete writes or older formats. */ }
40
+ }
41
+
42
+ function distribution(values: number[]) {
43
+ const sorted = values.sort((a, b) => a - b);
44
+ const percentile = (p: number) => sorted[Math.ceil(sorted.length * p) - 1] ?? null;
45
+ return { samples: sorted.length, p50: percentile(0.5), p95: percentile(0.95), max: sorted.at(-1) ?? null };
46
+ }
47
+
48
+ export function summarizeToolCalls(workspaceRoot: string) {
49
+ const path = SeptumTelemetry.getLogPath(workspaceRoot);
50
+ // Read active first so a concurrent rotation can be deduplicated by trace ID.
51
+ const active = readLogTail(path);
52
+ const seen = new Set<string>();
53
+ const events: SeptumToolCallEvent[] = [];
54
+ for (const lines of [active, readLogTail(`${path}.1`)]) {
55
+ for (let i = lines.length - 1; i >= 0 && events.length < SAMPLE_LIMIT; i--) {
56
+ const event = parseToolEvent(lines[i]!);
57
+ if (!event) continue;
58
+ if (typeof event.trace_id === "string") {
59
+ if (seen.has(event.trace_id)) continue;
60
+ seen.add(event.trace_id);
61
+ }
62
+ events.push(event);
63
+ }
64
+ }
65
+
66
+ const byTool = new Map<string, { calls: number; errors: number; actions: Map<string, { calls: number; errors: number }> }>();
67
+ const responseBytes: number[] = [];
68
+ const durations: number[] = [];
69
+ const recentErrors = [];
70
+ let errors = 0;
71
+ for (const event of events) {
72
+ const tool = byTool.get(event.tool) ?? { calls: 0, errors: 0, actions: new Map() };
73
+ byTool.set(event.tool, tool);
74
+ const action = typeof event.action === "string" ? event.action : "unspecified";
75
+ const counts = tool.actions.get(action) ?? { calls: 0, errors: 0 };
76
+ tool.actions.set(action, counts);
77
+ tool.calls++;
78
+ counts.calls++;
79
+ durations.push(event.duration_ms);
80
+ const bytes = event.metrics?.response_bytes;
81
+ if (typeof bytes === "number" && Number.isFinite(bytes) && bytes >= 0) responseBytes.push(bytes);
82
+ if (event.status === "error") {
83
+ errors++;
84
+ tool.errors++;
85
+ counts.errors++;
86
+ if (recentErrors.length < 10) recentErrors.push({
87
+ tool: event.tool,
88
+ action: event.action,
89
+ timestamp: event.timestamp,
90
+ trace_id: event.trace_id,
91
+ stage: event.stage,
92
+ code: event.error?.code,
93
+ });
94
+ }
95
+ }
96
+
97
+ return {
98
+ workspace: workspaceRoot,
99
+ sample_limit: SAMPLE_LIMIT,
100
+ sources: ["septum.log", "septum.log.1"],
101
+ first_timestamp: events.at(-1)?.timestamp ?? null,
102
+ last_timestamp: events[0]?.timestamp ?? null,
103
+ calls: events.length,
104
+ errors,
105
+ duration_ms: distribution(durations),
106
+ response_bytes: distribution(responseBytes),
107
+ tools: Object.fromEntries([...byTool].map(([name, tool]) => [name, {
108
+ calls: tool.calls,
109
+ errors: tool.errors,
110
+ actions: Object.fromEntries(tool.actions),
111
+ }])),
112
+ recent_errors: recentErrors,
113
+ };
114
+ }