septum 0.1.3 → 0.1.5

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 (74) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +105 -102
  3. package/bin/septum.ts +4 -4
  4. package/package.json +63 -63
  5. package/src/cli/commands/check.ts +161 -161
  6. package/src/cli/commands/hook.ts +188 -188
  7. package/src/cli/commands/ingest.ts +29 -29
  8. package/src/cli/commands/init.ts +211 -211
  9. package/src/cli/commands/locate.ts +61 -61
  10. package/src/cli/commands/query.ts +64 -64
  11. package/src/cli/commands/serve.ts +5 -5
  12. package/src/cli/commands/slice.ts +48 -90
  13. package/src/cli/commands/sync.ts +31 -31
  14. package/src/cli/commands/topology.ts +119 -0
  15. package/src/cli/index.ts +210 -199
  16. package/src/cli/templates/hooks.ts +75 -75
  17. package/src/cli/templates/rules.ts +38 -38
  18. package/src/cli/templates/skill.ts +69 -69
  19. package/src/core/boundary/evaluator.ts +232 -210
  20. package/src/core/config/loader.ts +97 -97
  21. package/src/core/config/schema.ts +39 -39
  22. package/src/core/database/client.ts +44 -44
  23. package/src/core/database/repositories/dependency.repository.ts +366 -349
  24. package/src/core/database/repositories/domain.repository.ts +218 -198
  25. package/src/core/database/repositories/environment.repository.ts +207 -0
  26. package/src/core/database/repositories/file.repository.ts +116 -106
  27. package/src/core/database/repositories/meta.repository.ts +33 -33
  28. package/src/core/database/repositories/symbol.repository.ts +443 -424
  29. package/src/core/database/repository.ts +264 -255
  30. package/src/core/database/schema.ts +34 -1
  31. package/src/core/discovery/topology-detector.ts +486 -486
  32. package/src/core/ingestion/hasher.ts +5 -5
  33. package/src/core/ingestion/pipeline.ts +584 -535
  34. package/src/core/parser/behavioral-analyzer.ts +119 -0
  35. package/src/core/parser/boundary-tracker.ts +288 -128
  36. package/src/core/parser/extractors/base.ts +62 -61
  37. package/src/core/parser/extractors/frontend.ts +194 -194
  38. package/src/core/parser/extractors/go.ts +229 -176
  39. package/src/core/parser/extractors/laravel-semantic.ts +1039 -585
  40. package/src/core/parser/extractors/mcp-cli-semantic.ts +199 -199
  41. package/src/core/parser/extractors/nestjs-semantic.ts +119 -119
  42. package/src/core/parser/extractors/php.ts +153 -149
  43. package/src/core/parser/extractors/python.ts +228 -226
  44. package/src/core/parser/extractors/registry.ts +70 -70
  45. package/src/core/parser/extractors/semantic-extractor.interface.ts +21 -21
  46. package/src/core/parser/extractors/typescript.ts +181 -177
  47. package/src/core/parser/schema/providers/laravel-migration-provider.ts +215 -0
  48. package/src/core/parser/schema/providers/prisma-schema-provider.ts +89 -0
  49. package/src/core/parser/schema/schema-provider-registry.ts +43 -0
  50. package/src/core/parser/schema/schema-provider.interface.ts +33 -0
  51. package/src/core/parser/tree-sitter.ts +41 -41
  52. package/src/core/resolver/call-graph-tracer.ts +666 -668
  53. package/src/core/resolver/module-resolver.ts +408 -342
  54. package/src/core/resolver/symbol-locator.ts +543 -543
  55. package/src/core/resolver/vertical-slice-tracer.ts +301 -252
  56. package/src/core/session/session-manager.ts +56 -56
  57. package/src/core/telemetry/telemetry.ts +86 -86
  58. package/src/core/topology/environment-detector.ts +860 -0
  59. package/src/core/topology/types.ts +83 -0
  60. package/src/index.ts +21 -18
  61. package/src/mcp/schemas.ts +578 -238
  62. package/src/mcp/server.ts +875 -656
  63. package/src/mcp/tools/check-boundary.ts +171 -152
  64. package/src/mcp/tools/get-domain-catalog.ts +145 -121
  65. package/src/mcp/tools/get-environment-topology.ts +141 -0
  66. package/src/mcp/tools/get-feature-context.ts +212 -116
  67. package/src/mcp/tools/get-symbol-hotspots.ts +60 -49
  68. package/src/mcp/tools/get-symbol-impact.ts +28 -26
  69. package/src/mcp/tools/get-symbol.ts +65 -63
  70. package/src/mcp/tools/locate-symbol.ts +171 -190
  71. package/src/mcp/tools/register-domain.ts +68 -64
  72. package/src/mcp/tools/register-feature.ts +100 -0
  73. package/src/mcp/tools/trace-vertical-slice.ts +74 -103
  74. package/src/types/index.ts +335 -299
@@ -0,0 +1,141 @@
1
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
+ import type { SeptumRepository } from "../../core/database/repository.ts";
3
+ import { EnvironmentDetector } from "../../core/topology/environment-detector.ts";
4
+ import type { EnvironmentLayer, ResolveLayerInput, ResolveNodeInput } from "../../core/topology/types.ts";
5
+
6
+ export interface GetEnvironmentTopologyArgs {
7
+ resolve?: ResolveLayerInput;
8
+ resolveNode?: ResolveNodeInput;
9
+ refresh?: boolean;
10
+ }
11
+
12
+ export function handleGetEnvironmentTopology(
13
+ repo: SeptumRepository,
14
+ _config: ValidatedSeptumConfig,
15
+ args: GetEnvironmentTopologyArgs,
16
+ workspaceRoot: string
17
+ ) {
18
+ // If layer resolution input is provided, persist into SQLite SSOT
19
+ if (args.resolve) {
20
+ const existing = repo.environment.getLayer(args.resolve.layer);
21
+ repo.environment.saveLayer({
22
+ layer: args.resolve.layer,
23
+ platform: args.resolve.platform,
24
+ canonical_tag: EnvironmentDetector.matchCanonicalTag(args.resolve.platform),
25
+ status: "VERIFIED",
26
+ constraints: args.resolve.constraints && args.resolve.constraints.length > 0 ? args.resolve.constraints : (existing?.constraints ?? []),
27
+ detected_from: ["Manual Developer Resolution via Septum"],
28
+ });
29
+ }
30
+
31
+ // If node resolution input is provided, persist node into SQLite SSOT
32
+ if (args.resolveNode) {
33
+ repo.environment.saveNode({
34
+ id: args.resolveNode.id,
35
+ layer: args.resolveNode.layer,
36
+ name: args.resolveNode.name,
37
+ platform: args.resolveNode.platform,
38
+ canonical_tag: args.resolveNode.canonical_tag || EnvironmentDetector.matchCanonicalTag(args.resolveNode.platform),
39
+ domain_or_ip: args.resolveNode.domain_or_ip,
40
+ role: args.resolveNode.role,
41
+ status: "VERIFIED",
42
+ detected_from: ["Manual Developer Resolution via Septum MCP"],
43
+ constraints: args.resolveNode.constraints ?? [],
44
+ connected_to: args.resolveNode.connected_to ?? [],
45
+ });
46
+ }
47
+
48
+ // Detect current topology merging heuristics with SQLite SSOT
49
+ const topology = EnvironmentDetector.detect(workspaceRoot, repo, args.refresh);
50
+
51
+ // Format into high-density Markdown output
52
+ let output = `### 🌐 Septum Environment & Topology Plane\n\n`;
53
+ output += `> **Overall Status:** \`${topology.overall_status}\`\n`;
54
+ output += `> **Topology Mode:** \`${topology.is_distributed ? "DISTRIBUTED MULTI-NODE GRAPH" : "MONOLITHIC SINGLE-NODE"}\`\n`;
55
+ output += `> **Architecture:** ${topology.architectural_summary}\n\n`;
56
+
57
+ // Section 1: Distributed Nodes Graph
58
+ if (topology.nodes.length > 0) {
59
+ output += `#### 📦 Distributed Topology Nodes (${topology.nodes.length} entities):\n`;
60
+ output += `| Node ID | Layer | Platform / Specs | Role | Domain / Host | Connected To | Status |\n`;
61
+ output += `| :--- | :--- | :--- | :--- | :--- | :--- | :--- |\n`;
62
+ for (const node of topology.nodes) {
63
+ const statusBadge = node.status === "VERIFIED" ? "✅ VERIFIED" : node.status === "DETECTED" ? "🔍 DETECTED" : "⚠️ " + node.status;
64
+ const domain = node.domain_or_ip ? `\`${node.domain_or_ip}\`` : "-";
65
+ const role = node.role ? `\`${node.role}\`` : "-";
66
+ const connected = node.connected_to && node.connected_to.length > 0 ? node.connected_to.join(", ") : "-";
67
+ output += `| **\`${node.id}\`** | ${node.layer.toUpperCase()} | ${node.platform} | ${role} | ${domain} | ${connected} | ${statusBadge} |\n`;
68
+ }
69
+ output += `\n`;
70
+ }
71
+
72
+ // Section 2: 6-Layer Summary
73
+ output += `#### 🗺️ 6-Layer Plane Summary:\n`;
74
+ output += `| Layer | Plane Domain | Platform / Setup | Status | Evidence / Files |\n`;
75
+ output += `| :--- | :--- | :--- | :--- | :--- |\n`;
76
+
77
+ const layerLabels: Record<EnvironmentLayer, string> = {
78
+ edge: "Perimeter & WAF",
79
+ gateway: "Ingress & Web Server",
80
+ host: "Deployment Platform",
81
+ runtime: "Application Engine",
82
+ storage: "Data & Cache",
83
+ telemetry: "Observability & Logs",
84
+ };
85
+
86
+ for (const layerKey of Object.keys(topology.layers) as EnvironmentLayer[]) {
87
+ const info = topology.layers[layerKey];
88
+ const evidence = info.detected_from && info.detected_from.length > 0 ? info.detected_from.join(", ") : "-";
89
+ const statusBadge = info.status === "VERIFIED" ? "✅ VERIFIED" : info.status === "DETECTED" ? "🔍 DETECTED" : "⚠️ " + info.status;
90
+ output += `| **${layerKey.toUpperCase()}** | ${layerLabels[layerKey]} | ${info.platform || "Not Defined"} | ${statusBadge} | ${evidence} |\n`;
91
+ }
92
+
93
+ // Section 3: Active Constraints
94
+ output += `\n#### 📌 Active Architectural Constraints:\n`;
95
+ let hasConstraints = false;
96
+ for (const node of topology.nodes) {
97
+ if (node.constraints && node.constraints.length > 0) {
98
+ hasConstraints = true;
99
+ output += `- **\`${node.id}\` (${node.platform}):**\n`;
100
+ for (const c of node.constraints) {
101
+ output += ` • ${c}\n`;
102
+ }
103
+ }
104
+ }
105
+ if (!hasConstraints) {
106
+ output += `*No specific node constraints recorded.*\n`;
107
+ }
108
+
109
+ // Section 4: Cross-Layer & Distributed Interplays
110
+ if (topology.interplays.length > 0) {
111
+ output += `\n#### ⚡ Cross-Layer & Distributed Invariants:\n`;
112
+ for (const interplay of topology.interplays) {
113
+ const nodeTrace = interplay.involved_node_ids && interplay.involved_node_ids.length > 0 ? ` (Nodes: \`${interplay.involved_node_ids.join(", ")}\`)` : "";
114
+ output += `- **${interplay.title}** (Layers: \`${interplay.involved_layers.join(" ➔ ")}\`)${nodeTrace}:\n`;
115
+ output += ` • *Invarian:* ${interplay.risk_or_rule}\n`;
116
+ output += ` • *Tindakan Wajib:* ${interplay.required_action}\n`;
117
+ }
118
+ }
119
+
120
+ // Section 5: Pending Inquiries
121
+ if (topology.pending_inquiries.length > 0) {
122
+ output += `\n#### ❓ Pending Architectural Inquiries (Self-Aware Inquiry Required):\n`;
123
+ output += `Terdapat layer atau node arsitektural yang belum terkonfirmasi. Sebelum mengeksekusi kode terkait deployment/throttling/cron/cookies, klarifikasikan hal berikut ke pengguna:\n`;
124
+ for (const q of topology.pending_inquiries) {
125
+ output += `- ${q}\n`;
126
+ }
127
+ output += `\n*Untuk mengunci jawaban pengguna ke SQLite SSOT, panggil kembali tool ini dengan argumen:*\n`;
128
+ output += `\`septum_get_environment_topology(resolve: { layer: "<layer_name>", platform: "<platform_name>" })\`\n`;
129
+ output += `*atau untuk entitas terdistribusi:*\n`;
130
+ output += `\`septum_get_environment_topology(resolveNode: { id: "<node_id>", layer: "<layer>", name: "<name>", platform: "<platform>", domain_or_ip: "<domain_or_ip>", role: "<role>" })\`\n`;
131
+ }
132
+
133
+ return {
134
+ content: [
135
+ {
136
+ type: "text" as const,
137
+ text: output,
138
+ },
139
+ ],
140
+ };
141
+ }
@@ -1,116 +1,212 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
4
- import type { SeptumRepository } from "../../core/database/repository.ts";
5
- import { SessionManager } from "../../core/session/session-manager.ts";
6
- import type { FeatureContextResponse } from "../../types/index.ts";
7
-
8
- export interface GetFeatureContextArgs {
9
- feature: string;
10
- }
11
-
12
- export function handleClearFeatureContext(workspaceRoot: string = process.cwd()): boolean {
13
- return SessionManager.clearActiveSession(workspaceRoot);
14
- }
15
-
16
- export function handleGetFeatureContext(
17
- repo: SeptumRepository,
18
- config: ValidatedSeptumConfig,
19
- args: GetFeatureContextArgs
20
- ) {
21
- if (!args.feature) {
22
- throw new Error("Missing required argument: 'feature'");
23
- }
24
-
25
- const features = config.features ?? {};
26
- const featureConfig = features[args.feature];
27
-
28
- if (!featureConfig) {
29
- const available = Object.keys(features).join(", ") || "none";
30
- throw new Error(
31
- `Feature '${args.feature}' not found in configuration. Available features: [${available}]`
32
- );
33
- }
34
-
35
- // Record Active Feature Session Lease (.septum/session.json)
36
- SessionManager.saveActiveSession(process.cwd(), {
37
- feature_key: args.feature,
38
- domain: featureConfig.domain,
39
- touchpoints: featureConfig.allowed_touchpoints ?? [],
40
- locked_at: new Date().toISOString(),
41
- });
42
-
43
- // Deterministically fetch signatures, methods, and properties for reuse_symbols from SQLite
44
- const reuseSymbolsWithMeta: FeatureContextResponse["reuse_symbols"] = [];
45
- const requestedSymbols = featureConfig.reuse_symbols ?? [];
46
-
47
- for (const symName of requestedSymbols) {
48
- const record = repo.findSymbolWithMembers(symName);
49
- if (record) {
50
- reuseSymbolsWithMeta.push({
51
- name: record.symbol_name,
52
- kind: record.kind,
53
- signature: record.signature,
54
- methods: record.methods.length > 0 ? record.methods : undefined,
55
- properties: record.properties.length > 0 ? record.properties : undefined,
56
- file_path: record.file_path,
57
- domain: record.domain_name,
58
- });
59
- } else {
60
- reuseSymbolsWithMeta.push({
61
- name: symName,
62
- kind: "unknown",
63
- domain: featureConfig.domain,
64
- });
65
- }
66
- }
67
-
68
- const response: FeatureContextResponse = {
69
- feature: args.feature,
70
- domain: featureConfig.domain,
71
- description: featureConfig.description,
72
- allowed_touchpoints: featureConfig.allowed_touchpoints,
73
- reuse_symbols: reuseSymbolsWithMeta,
74
- input_contract: (featureConfig.input_contract as Record<string, unknown>) ?? {},
75
- output_contract: (featureConfig.output_contract as Record<string, unknown>) ?? {},
76
- governance_directives: [
77
- "DO NOT modify or edit any files outside allowed_touchpoints.",
78
- "DO NOT create duplicate helpers/services; reuse the existing symbols and methods declared in reuse_symbols.",
79
- "DO NOT emit or expect phantom payload fields outside input_contract and output_contract.",
80
- "DO NOT import cross-domain modules without declared allowed_dependencies in Septum domain boundaries.",
81
- ],
82
- };
83
-
84
- recordFeatureAccess(featureConfig.domain, args.feature);
85
-
86
- return {
87
- content: [
88
- {
89
- type: "text" as const,
90
- text: JSON.stringify(response, null, 2),
91
- },
92
- ],
93
- };
94
- }
95
-
96
- function recordFeatureAccess(domain: string, feature: string): void {
97
- try {
98
- const septumDir = path.resolve(process.cwd(), ".septum");
99
- if (!fs.existsSync(septumDir)) {
100
- fs.mkdirSync(septumDir, { recursive: true });
101
- }
102
- const logPath = path.join(septumDir, "catalog_access.json");
103
- let log: { domains?: Record<string, string>; features?: Record<string, string> } = {};
104
- if (fs.existsSync(logPath)) {
105
- try {
106
- log = JSON.parse(fs.readFileSync(logPath, "utf-8"));
107
- } catch {}
108
- }
109
- log.domains = log.domains || {};
110
- log.features = log.features || {};
111
- const now = new Date().toISOString();
112
- log.domains[domain] = now;
113
- log.features[feature] = now;
114
- fs.writeFileSync(logPath, JSON.stringify(log, null, 2), "utf-8");
115
- } catch {}
116
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
4
+ import type { SeptumRepository } from "../../core/database/repository.ts";
5
+ import { SessionManager } from "../../core/session/session-manager.ts";
6
+ import type { FeatureContextResponse } from "../../types/index.ts";
7
+
8
+ export interface GetFeatureContextArgs {
9
+ feature_key?: string;
10
+ feature?: string;
11
+ workspace_path?: string;
12
+ }
13
+
14
+ export function handleClearFeatureContext(workspaceRoot: string = process.cwd()): boolean {
15
+ return SessionManager.clearActiveSession(workspaceRoot);
16
+ }
17
+
18
+ export function handleGetFeatureContext(
19
+ repo: SeptumRepository,
20
+ config: ValidatedSeptumConfig,
21
+ args: GetFeatureContextArgs,
22
+ workspaceRoot: string = process.cwd()
23
+ ) {
24
+ const featureKey = (args.feature_key || args.feature || "").trim();
25
+ const features = config.features ?? {};
26
+
27
+ // ZERO-ARGUMENT GRACEFUL FALLBACK: Guide the agent instead of throwing validation errors
28
+ if (!featureKey) {
29
+ const available = Object.keys(features);
30
+ return {
31
+ content: [
32
+ {
33
+ type: "text" as const,
34
+ text: JSON.stringify(
35
+ {
36
+ status: "prompt",
37
+ message: "No feature specified. Please specify 'feature_key' from the registered features below or trace routes.",
38
+ available_features: available.length > 0 ? available : [],
39
+ instructions: "Call 'septum_get_feature_context({ feature_key: \"<name>\" })' or register a new feature with 'septum_register_feature'.",
40
+ },
41
+ null,
42
+ 2
43
+ ),
44
+ },
45
+ ],
46
+ };
47
+ }
48
+
49
+ let featureConfig = features[featureKey];
50
+ let isInferred = false;
51
+
52
+ if (!featureConfig) {
53
+ // Attempt auto-derive from vertical slices or domain symbols
54
+ const searchTerm = featureKey.toLowerCase();
55
+ const allSlices = typeof repo.getAllVerticalSlices === "function" ? repo.getAllVerticalSlices() : [];
56
+ const fromRepoSearch = typeof repo.findVerticalSlices === "function" ? repo.findVerticalSlices(searchTerm) : [];
57
+ const matchingSlices = [
58
+ ...fromRepoSearch,
59
+ ...allSlices.filter(
60
+ (s) =>
61
+ s.route_uri.toLowerCase().includes(searchTerm) ||
62
+ (s.route_name && s.route_name.toLowerCase().includes(searchTerm)) ||
63
+ s.controller_class.toLowerCase().includes(searchTerm) ||
64
+ (s.feature_key && s.feature_key.toLowerCase().includes(searchTerm))
65
+ ),
66
+ ];
67
+
68
+ const uniqueSlices = Array.from(
69
+ new Map(matchingSlices.map((s) => [`${s.http_method}:${s.route_uri}`, s])).values()
70
+ );
71
+
72
+ if (uniqueSlices.length > 0) {
73
+ isInferred = true;
74
+ const candidateTouchpoints = new Set<string>();
75
+ const candidateSymbols = new Set<string>();
76
+ let detectedDomain = "app";
77
+
78
+ if (config.domains && config.domains[featureKey]) {
79
+ detectedDomain = featureKey;
80
+ }
81
+
82
+ for (const slice of uniqueSlices) {
83
+ if (slice.controller_file) {
84
+ candidateTouchpoints.add(slice.controller_file);
85
+ }
86
+ candidateSymbols.add(slice.controller_class);
87
+ if (slice.action_name) {
88
+ candidateSymbols.add(`${slice.controller_class}@${slice.action_name}`);
89
+ }
90
+
91
+ if (slice.execution_chain_json) {
92
+ try {
93
+ const chain = JSON.parse(slice.execution_chain_json);
94
+ if (Array.isArray(chain)) {
95
+ for (const node of chain) {
96
+ if (node.file) candidateTouchpoints.add(node.file);
97
+ if (node.symbol) candidateSymbols.add(node.symbol);
98
+ }
99
+ }
100
+ } catch {}
101
+ }
102
+ }
103
+
104
+ featureConfig = {
105
+ domain: detectedDomain,
106
+ description: `[Auto-Derived] Feature context inferred from ${uniqueSlices.length} vertical slices matching '${featureKey}'`,
107
+ allowed_touchpoints: Array.from(candidateTouchpoints),
108
+ reuse_symbols: Array.from(candidateSymbols).slice(0, 10),
109
+ input_contract: {},
110
+ output_contract: {},
111
+ };
112
+ } else {
113
+ const available = Object.keys(features);
114
+ const availableStr = available.length > 0 ? available.join(", ") : "none";
115
+ const recoveryMessage = [
116
+ `Feature '${featureKey}' not found in configuration. Available features: [${availableStr}].`,
117
+ `No matching vertical slices found for auto-derivation.`,
118
+ ``,
119
+ `▶ RECOVERY OPTIONS:`,
120
+ `1. Register this feature on-the-fly:`,
121
+ ` septum_register_feature({ feature_key: "${featureKey}", domain: "<domain_name>", allowed_touchpoints: ["path/to/file"] })`,
122
+ `2. Or discover available routes / vertical slices first:`,
123
+ ` septum_trace_vertical_slice({ entry_file: "routes/web.php" })`,
124
+ ].join("\n");
125
+ throw new Error(recoveryMessage);
126
+ }
127
+ }
128
+
129
+ // Record Active Feature Session Lease (.septum/session.json)
130
+ SessionManager.saveActiveSession(workspaceRoot, {
131
+ feature_key: featureKey,
132
+ domain: featureConfig.domain,
133
+ touchpoints: featureConfig.allowed_touchpoints ?? [],
134
+ locked_at: new Date().toISOString(),
135
+ });
136
+
137
+ // Deterministically fetch signatures, methods, and properties for reuse_symbols from SQLite
138
+ const reuseSymbolsWithMeta: FeatureContextResponse["reuse_symbols"] = [];
139
+ const requestedSymbols = featureConfig.reuse_symbols ?? [];
140
+
141
+ for (const symName of requestedSymbols) {
142
+ const record = repo.findSymbolWithMembers(symName);
143
+ if (record) {
144
+ reuseSymbolsWithMeta.push({
145
+ name: record.symbol_name,
146
+ kind: record.kind,
147
+ signature: record.signature,
148
+ methods: record.methods.length > 0 ? record.methods : undefined,
149
+ properties: record.properties.length > 0 ? record.properties : undefined,
150
+ file_path: record.file_path,
151
+ domain: record.domain_name,
152
+ });
153
+ } else {
154
+ reuseSymbolsWithMeta.push({
155
+ name: symName,
156
+ kind: "unknown",
157
+ domain: featureConfig.domain,
158
+ });
159
+ }
160
+ }
161
+
162
+ const response: FeatureContextResponse = {
163
+ feature_key: featureKey,
164
+ feature: featureKey,
165
+ domain: featureConfig.domain,
166
+ description: featureConfig.description,
167
+ allowed_touchpoints: featureConfig.allowed_touchpoints,
168
+ reuse_symbols: reuseSymbolsWithMeta,
169
+ input_contract: (featureConfig.input_contract as Record<string, unknown>) ?? {},
170
+ output_contract: (featureConfig.output_contract as Record<string, unknown>) ?? {},
171
+ governance_directives: [
172
+ "DO NOT modify or edit any files outside allowed_touchpoints.",
173
+ "DO NOT create duplicate helpers/services; reuse the existing symbols and methods declared in reuse_symbols.",
174
+ "DO NOT emit or expect phantom payload fields outside input_contract and output_contract.",
175
+ "DO NOT import cross-domain modules without declared allowed_dependencies in Septum domain boundaries.",
176
+ ],
177
+ ...(isInferred ? { is_inferred: true } : {}),
178
+ };
179
+
180
+ recordFeatureAccess(featureConfig.domain, featureKey);
181
+
182
+ return {
183
+ content: [
184
+ {
185
+ type: "text" as const,
186
+ text: JSON.stringify(response, null, 2),
187
+ },
188
+ ],
189
+ };
190
+ }
191
+
192
+ function recordFeatureAccess(domain: string, feature: string): void {
193
+ try {
194
+ const septumDir = path.resolve(process.cwd(), ".septum");
195
+ if (!fs.existsSync(septumDir)) {
196
+ fs.mkdirSync(septumDir, { recursive: true });
197
+ }
198
+ const logPath = path.join(septumDir, "catalog_access.json");
199
+ let log: { domains?: Record<string, string>; features?: Record<string, string> } = {};
200
+ if (fs.existsSync(logPath)) {
201
+ try {
202
+ log = JSON.parse(fs.readFileSync(logPath, "utf-8"));
203
+ } catch {}
204
+ }
205
+ log.domains = log.domains || {};
206
+ log.features = log.features || {};
207
+ const now = new Date().toISOString();
208
+ log.domains[domain] = now;
209
+ log.features[feature] = now;
210
+ fs.writeFileSync(logPath, JSON.stringify(log, null, 2), "utf-8");
211
+ } catch {}
212
+ }
@@ -1,49 +1,60 @@
1
- import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
- import type { DatabaseRepository } from "../../core/database/repository.ts";
3
- import type { SymbolKind } from "../../types/index.ts";
4
-
5
- export interface GetSymbolHotspotsArgs {
6
- min_lines?: number;
7
- kind?: SymbolKind;
8
- domain?: string;
9
- limit?: number;
10
- }
11
-
12
- export function handleGetSymbolHotspots(
13
- repo: DatabaseRepository,
14
- _config: ValidatedSeptumConfig,
15
- args: GetSymbolHotspotsArgs
16
- ) {
17
- const minLines = args.min_lines ?? 30;
18
- const limit = args.limit ?? 30;
19
-
20
- const hotspots = repo.getHotspotSymbols({
21
- minLines,
22
- kind: args.kind,
23
- domain: args.domain,
24
- limit,
25
- });
26
-
27
- const payload = {
28
- total_found: hotspots.length,
29
- threshold_min_lines: minLines,
30
- hotspots: hotspots.map((h) => ({
31
- name: h.name,
32
- kind: h.kind,
33
- line_count: h.line_count,
34
- line_span: `${h.line_start}-${h.line_end}`,
35
- file_path: h.file_path,
36
- domain: h.domain_name,
37
- signature: h.signature,
38
- })),
39
- };
40
-
41
- return {
42
- content: [
43
- {
44
- type: "text" as const,
45
- text: JSON.stringify(payload, null, 2),
46
- },
47
- ],
48
- };
49
- }
1
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
+ import type { DatabaseRepository } from "../../core/database/repository.ts";
3
+ import type { SymbolKind } from "../../types/index.ts";
4
+
5
+ export interface GetSymbolHotspotsArgs {
6
+ min_lines?: number;
7
+ min_nesting?: number;
8
+ kind?: SymbolKind | string;
9
+ domain?: string;
10
+ limit?: number;
11
+ sort_by?: "lines" | "nesting" | "risk_score";
12
+ }
13
+
14
+ export function handleGetSymbolHotspots(
15
+ repo: DatabaseRepository,
16
+ _config: ValidatedSeptumConfig,
17
+ args: GetSymbolHotspotsArgs,
18
+ _workspaceRoot?: string
19
+ ) {
20
+ const minLines = args.min_lines ?? (args.min_nesting ? 0 : 30);
21
+ const minNesting = args.min_nesting ?? 1;
22
+ const limit = args.limit ?? 30;
23
+ const sortBy = args.sort_by ?? "risk_score";
24
+
25
+ const hotspots = repo.getHotspotSymbols({
26
+ minLines,
27
+ minNesting,
28
+ kind: args.kind as SymbolKind | undefined,
29
+ domain: args.domain,
30
+ limit,
31
+ sortBy,
32
+ });
33
+
34
+ const payload = {
35
+ total_found: hotspots.length,
36
+ threshold_min_lines: minLines,
37
+ threshold_min_nesting: minNesting,
38
+ sort_by: sortBy,
39
+ hotspots: hotspots.map((h) => ({
40
+ name: h.name,
41
+ kind: h.kind,
42
+ line_count: h.line_count,
43
+ nesting_depth: (h as any).nesting_depth ?? 1,
44
+ risk_score: (h as any).risk_score ?? h.line_count,
45
+ line_span: `${h.line_start}-${h.line_end}`,
46
+ file_path: h.file_path,
47
+ domain: h.domain_name,
48
+ signature: h.signature,
49
+ })),
50
+ };
51
+
52
+ return {
53
+ content: [
54
+ {
55
+ type: "text" as const,
56
+ text: JSON.stringify(payload, null, 2),
57
+ },
58
+ ],
59
+ };
60
+ }
@@ -1,26 +1,28 @@
1
- import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
- import type { SeptumRepository } from "../../core/database/repository.ts";
3
- import type { GetSymbolImpactArgs } from "../../types/index.ts";
4
-
5
- export function handleGetSymbolImpact(
6
- repo: SeptumRepository,
7
- _config: ValidatedSeptumConfig,
8
- args: GetSymbolImpactArgs
9
- ) {
10
- if (!args.symbol) {
11
- throw new Error(
12
- "Missing required argument: 'symbol' (e.g. 'OrderService::cancelOrder', 'OrderService', or 'cancelOrder')"
13
- );
14
- }
15
-
16
- const impact = repo.getSymbolImpact(args.symbol);
17
-
18
- return {
19
- content: [
20
- {
21
- type: "text" as const,
22
- text: JSON.stringify(impact, null, 2),
23
- },
24
- ],
25
- };
26
- }
1
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
+ import type { SeptumRepository } from "../../core/database/repository.ts";
3
+ import type { GetSymbolImpactArgs } from "../../types/index.ts";
4
+
5
+ export function handleGetSymbolImpact(
6
+ repo: SeptumRepository,
7
+ _config: ValidatedSeptumConfig,
8
+ args: GetSymbolImpactArgs,
9
+ _workspaceRoot?: string
10
+ ) {
11
+ const symbol = (args.symbol || (args as unknown as Record<string, unknown>).query || "").toString().trim();
12
+ if (!symbol) {
13
+ throw new Error(
14
+ "Missing required argument: 'symbol' (e.g. 'OrderService::cancelOrder', 'OrderService', or 'cancelOrder')"
15
+ );
16
+ }
17
+
18
+ const impact = repo.getSymbolImpact(symbol);
19
+
20
+ return {
21
+ content: [
22
+ {
23
+ type: "text" as const,
24
+ text: JSON.stringify(impact, null, 2),
25
+ },
26
+ ],
27
+ };
28
+ }