@dimassetoid/septum-mcp 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +124 -2
- package/bin/septum.ts +4 -0
- package/package.json +70 -4
- package/scripts/postinstall.ts +25 -0
- package/src/cli/commands/check.ts +122 -0
- package/src/cli/commands/hook.ts +268 -0
- package/src/cli/commands/init.ts +553 -0
- package/src/cli/commands/serve.ts +5 -0
- package/src/cli/commands/sync.ts +41 -0
- package/src/cli/commands/topology.ts +161 -0
- package/src/cli/index.ts +167 -0
- package/src/cli/scaffold/harness-config.ts +621 -0
- package/src/cli/templates/hooks.ts +75 -0
- package/src/cli/templates/rules.ts +50 -0
- package/src/cli/templates/skill.ts +51 -0
- package/src/cli/ui/prompts.ts +122 -0
- package/src/core/boundary/evaluator.ts +442 -0
- package/src/core/boundary/staged-auditor.ts +58 -0
- package/src/core/config/loader.ts +122 -0
- package/src/core/config/schema.ts +69 -0
- package/src/core/database/client.ts +60 -0
- package/src/core/database/repositories/dependency.repository.ts +712 -0
- package/src/core/database/repositories/domain.repository.ts +330 -0
- package/src/core/database/repositories/environment.repository.ts +207 -0
- package/src/core/database/repositories/file.repository.ts +117 -0
- package/src/core/database/repositories/meta.repository.ts +33 -0
- package/src/core/database/repositories/symbol.repository.ts +508 -0
- package/src/core/database/repository.ts +303 -0
- package/src/core/database/schema.ts +154 -0
- package/src/core/discovery/topology-detector.ts +805 -0
- package/src/core/ingestion/hasher.ts +5 -0
- package/src/core/ingestion/pipeline.ts +623 -0
- package/src/core/parser/behavioral-analyzer.ts +119 -0
- package/src/core/parser/boundary-tracker.ts +443 -0
- package/src/core/parser/extractors/base.ts +67 -0
- package/src/core/parser/extractors/blade.ts +159 -0
- package/src/core/parser/extractors/csharp.ts +244 -0
- package/src/core/parser/extractors/django-semantic.ts +687 -0
- package/src/core/parser/extractors/elysia-semantic.ts +538 -0
- package/src/core/parser/extractors/express-semantic.ts +444 -0
- package/src/core/parser/extractors/fastapi-semantic.ts +736 -0
- package/src/core/parser/extractors/fastify-semantic.ts +774 -0
- package/src/core/parser/extractors/flask-semantic.ts +515 -0
- package/src/core/parser/extractors/frontend.ts +149 -0
- package/src/core/parser/extractors/go-semantic.ts +611 -0
- package/src/core/parser/extractors/go.ts +491 -0
- package/src/core/parser/extractors/hono-semantic.ts +567 -0
- package/src/core/parser/extractors/java.ts +225 -0
- package/src/core/parser/extractors/laravel-semantic.ts +1122 -0
- package/src/core/parser/extractors/mcp-cli-semantic.ts +368 -0
- package/src/core/parser/extractors/nestjs-semantic.ts +543 -0
- package/src/core/parser/extractors/php.ts +569 -0
- package/src/core/parser/extractors/python.ts +498 -0
- package/src/core/parser/extractors/registry.ts +78 -0
- package/src/core/parser/extractors/ruby.ts +234 -0
- package/src/core/parser/extractors/rust.ts +286 -0
- package/src/core/parser/extractors/semantic-extractor.interface.ts +22 -0
- package/src/core/parser/extractors/symfony-semantic.ts +354 -0
- package/src/core/parser/extractors/typescript.ts +826 -0
- package/src/core/parser/language-capabilities.ts +71 -0
- package/src/core/parser/schema/providers/laravel-migration-provider.ts +216 -0
- package/src/core/parser/schema/providers/prisma-schema-provider.ts +90 -0
- package/src/core/parser/schema/schema-provider-registry.ts +43 -0
- package/src/core/parser/schema/schema-provider.interface.ts +33 -0
- package/src/core/parser/tree-sitter.ts +63 -0
- package/src/core/parser/wasm-assets.ts +25 -0
- package/src/core/parser/wasm-loader.ts +274 -0
- package/src/core/resolver/call-graph-tracer.ts +724 -0
- package/src/core/resolver/import-resolver.ts +437 -0
- package/src/core/resolver/module-resolver.ts +482 -0
- package/src/core/resolver/path-resolver.ts +200 -0
- package/src/core/resolver/symbol-locator.ts +276 -0
- package/src/core/resolver/symbol-reference.ts +53 -0
- package/src/core/resolver/vertical-slice-tracer.ts +366 -0
- package/src/core/resources/ignore.ts +123 -0
- package/src/core/resources/limits.ts +14 -0
- package/src/core/resources/source-files.ts +62 -0
- package/src/core/resources/work-queue.ts +74 -0
- package/src/core/session/session-manager.ts +107 -0
- package/src/core/telemetry/telemetry.ts +97 -0
- package/src/core/topology/environment-detector.ts +973 -0
- package/src/core/topology/types.ts +83 -0
- package/src/index.ts +21 -0
- package/src/mcp/schemas.ts +1105 -0
- package/src/mcp/server.ts +774 -0
- package/src/mcp/tools/boundary.ts +17 -0
- package/src/mcp/tools/check-boundary.ts +387 -0
- package/src/mcp/tools/domain.ts +40 -0
- package/src/mcp/tools/feature.ts +67 -0
- package/src/mcp/tools/get-domain-catalog.ts +226 -0
- package/src/mcp/tools/get-environment-topology.ts +138 -0
- package/src/mcp/tools/get-feature-context.ts +224 -0
- package/src/mcp/tools/get-symbol-hotspots.ts +54 -0
- package/src/mcp/tools/get-symbol-impact.ts +64 -0
- package/src/mcp/tools/get-symbol.ts +175 -0
- package/src/mcp/tools/locate-symbol.ts +196 -0
- package/src/mcp/tools/register-domain.ts +75 -0
- package/src/mcp/tools/register-feature.ts +110 -0
- package/src/mcp/tools/slice.ts +16 -0
- package/src/mcp/tools/symbol.ts +93 -0
- package/src/mcp/tools/trace-vertical-slice.ts +80 -0
- package/src/mcp/workspace-manager.ts +159 -0
- package/src/mcp/workspace-watcher.ts +202 -0
- package/src/types/index.ts +456 -0
- package/src/types/wasm.d.ts +4 -0
- package/src/utils/version-check.ts +209 -0
- package/src/version.ts +1 -0
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { readSourceFile } from "../resources/source-files.ts";
|
|
2
|
+
import { computeContentHash } from "../ingestion/hasher.ts";
|
|
3
|
+
import { assertPathContained } from "./path-resolver.ts";
|
|
4
|
+
import { join, relative, resolve } from "node:path";
|
|
5
|
+
import { collectSourceSkips } from "../resources/source-files.ts";
|
|
6
|
+
import type {
|
|
7
|
+
ExecutionChainNode,
|
|
8
|
+
VerticalSliceRecord,
|
|
9
|
+
VerticalSliceTraceResponse,
|
|
10
|
+
} from "../../types/index.ts";
|
|
11
|
+
import type { SeptumRepository } from "../database/repository.ts";
|
|
12
|
+
import { CallGraphTracer } from "./call-graph-tracer.ts";
|
|
13
|
+
import { SemanticSliceExtractorRegistry } from "../parser/extractors/registry.ts";
|
|
14
|
+
import { TopologyDetector } from "../discovery/topology-detector.ts";
|
|
15
|
+
import { readdirSync } from "node:fs";
|
|
16
|
+
import { ASTParserEngine } from "../parser/tree-sitter.ts";
|
|
17
|
+
import { shouldIgnoreSourcePath } from "../resources/ignore.ts";
|
|
18
|
+
|
|
19
|
+
export class VerticalSliceTracer {
|
|
20
|
+
constructor(private repo: SeptumRepository, private projectRoot: string = process.cwd(), private ignorePatterns: string[] = [], private verifyMembership = true) {}
|
|
21
|
+
|
|
22
|
+
public async traceAsync(rawQuery: string, maxDepth = 5, signal?: AbortSignal): Promise<VerticalSliceTraceResponse> {
|
|
23
|
+
signal?.throwIfAborted();
|
|
24
|
+
if (this.repo.getMeta("sync_state") === "error" || this.repo.getMeta("sync_state") === "running") {
|
|
25
|
+
return { query: rawQuery, found: false, coverage: "partial", diagnostics: ["index_incomplete"], message: "Workspace synchronization is incomplete." };
|
|
26
|
+
}
|
|
27
|
+
let inputsChanged = false;
|
|
28
|
+
let membershipChanged = false;
|
|
29
|
+
try {
|
|
30
|
+
const inputs = JSON.parse(this.repo.getMeta("semantic_inputs") || "[]") as Array<{path:string;hash:string}>;
|
|
31
|
+
inputsChanged = inputs.some(input => {
|
|
32
|
+
signal?.throwIfAborted();
|
|
33
|
+
assertPathContained(input.path,this.projectRoot,"Semantic source");
|
|
34
|
+
return computeContentHash(readSourceFile(resolve(this.projectRoot,input.path))) !== input.hash;
|
|
35
|
+
});
|
|
36
|
+
if (this.verifyMembership) {
|
|
37
|
+
const files = this.listSourceFiles(this.projectRoot);
|
|
38
|
+
membershipChanged = JSON.stringify(files) !== (this.repo.getMeta("semantic_catalog_files") || "[]");
|
|
39
|
+
}
|
|
40
|
+
} catch { signal?.throwIfAborted(); inputsChanged = true; }
|
|
41
|
+
if (inputsChanged || membershipChanged || this.repo.getAllVerticalSlices().length === 0 || this.repo.getMeta("slices_dirty") === "1") {
|
|
42
|
+
try {
|
|
43
|
+
const topology = TopologyDetector.detect(this.projectRoot);
|
|
44
|
+
const extracted = await collectSourceSkips(this.projectRoot, async () => {
|
|
45
|
+
const slices = await SemanticSliceExtractorRegistry.extractAllSlices(this.projectRoot,topology.framework,undefined,signal);
|
|
46
|
+
return slices.length ? slices : new CallGraphTracer(this.repo,this.projectRoot).traceAllSlices(maxDepth);
|
|
47
|
+
});
|
|
48
|
+
signal?.throwIfAborted();
|
|
49
|
+
if (extracted.skipped.length) throw new Error("Semantic source exceeds read limits; catalog is incomplete.");
|
|
50
|
+
this.repo.runInTransaction(() => {
|
|
51
|
+
signal?.throwIfAborted();
|
|
52
|
+
this.repo.clearVerticalSlices();
|
|
53
|
+
for (const slice of extracted.value) this.repo.upsertVerticalSlice(slice);
|
|
54
|
+
this.repo.setMeta("slices_dirty", "");
|
|
55
|
+
this.repo.setMeta("semantic_inputs", JSON.stringify(extracted.inputs));
|
|
56
|
+
if (this.verifyMembership) this.repo.setMeta("semantic_catalog_files", JSON.stringify(this.listSourceFiles(this.projectRoot)));
|
|
57
|
+
});
|
|
58
|
+
} catch (error) {
|
|
59
|
+
signal?.throwIfAborted();
|
|
60
|
+
this.repo.setMeta("slices_dirty", "1");
|
|
61
|
+
return { query: rawQuery, found: false, coverage: "partial", diagnostics: [error instanceof Error ? error.message : String(error)], message: "Semantic extraction failed; no complete catalog was published." };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return this.trace(rawQuery,maxDepth);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private listSourceFiles(root: string): string[] {
|
|
68
|
+
const files: string[] = [];
|
|
69
|
+
const walk = (dir: string) => {
|
|
70
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
71
|
+
const fullPath = join(dir, entry.name);
|
|
72
|
+
const relPath = relative(root, fullPath).replace(/\\/g, "/");
|
|
73
|
+
if (shouldIgnoreSourcePath(relPath, this.ignorePatterns)) continue;
|
|
74
|
+
if (entry.isDirectory()) walk(fullPath);
|
|
75
|
+
else if (entry.isFile() && ASTParserEngine.isSourceFile(fullPath)) files.push(relPath);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
walk(root);
|
|
79
|
+
return files.sort();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Trace an end-to-end vertical slice from route/action/intent query.
|
|
84
|
+
* Examples of queries:
|
|
85
|
+
* - "POST /orders/{id}/status"
|
|
86
|
+
* - "/orders/{id}/status"
|
|
87
|
+
* - "OrderController@updateStatus"
|
|
88
|
+
* - "OrderController::updateStatus"
|
|
89
|
+
* - "orders.update_status"
|
|
90
|
+
* - "createOrder"
|
|
91
|
+
* - "Ubah status order di dashboard"
|
|
92
|
+
*/
|
|
93
|
+
// Synchronous compatibility API reads persisted slices only; use traceAsync for on-demand extraction.
|
|
94
|
+
public trace(rawQuery: string, maxDepth: number = 5): VerticalSliceTraceResponse {
|
|
95
|
+
const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
|
|
96
|
+
const trimmed = rawQuery.trim();
|
|
97
|
+
const lowerTrimmed = trimmed.toLowerCase();
|
|
98
|
+
let allSlices = this.repo.getAllVerticalSlices();
|
|
99
|
+
|
|
100
|
+
if (allSlices.length === 0) {
|
|
101
|
+
return {
|
|
102
|
+
query: trimmed,
|
|
103
|
+
found: false,
|
|
104
|
+
max_depth_applied: effectiveMaxDepth,
|
|
105
|
+
message: "No vertical slices cataloged. Run 'septum sync' to extract framework routes and MVC slices.",
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// 1. Exact HTTP Method + URI match: "POST /orders/{id}/status" or "POST /api/orders"
|
|
110
|
+
const methodUriMatch = trimmed.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(\/[^\s]+)$/i);
|
|
111
|
+
if (methodUriMatch) {
|
|
112
|
+
const httpMethod = methodUriMatch[1].toUpperCase();
|
|
113
|
+
const uri = methodUriMatch[2];
|
|
114
|
+
const candidates = allSlices.filter((s) => s.http_method.toUpperCase() === httpMethod && this.urisMatch(s.route_uri, uri));
|
|
115
|
+
const literal = candidates.filter(s => s.route_uri === uri);
|
|
116
|
+
if (literal.length === 1) {
|
|
117
|
+
return this.formatSuccessResponse(trimmed, literal[0], "exact", undefined, effectiveMaxDepth);
|
|
118
|
+
}
|
|
119
|
+
if (literal.length > 1 || candidates.length > 1) {
|
|
120
|
+
return this.formatSuccessResponse(trimmed, literal[0] ?? candidates[0], "inferred", (literal.length ? literal : candidates).slice(1), effectiveMaxDepth);
|
|
121
|
+
}
|
|
122
|
+
if (candidates.length === 1) {
|
|
123
|
+
return this.formatSuccessResponse(trimmed, candidates[0], "inferred", undefined, effectiveMaxDepth);
|
|
124
|
+
}
|
|
125
|
+
return { query: trimmed, found: false, max_depth_applied: effectiveMaxDepth, message: `No vertical slice found matching query '${trimmed}'.` };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// 2. URI-only match: "/orders" or "orders/{id}"
|
|
129
|
+
const literalUriMatches = allSlices.filter((s) => s.route_uri === trimmed);
|
|
130
|
+
const uriMatches = literalUriMatches.length ? literalUriMatches : allSlices.filter((s) => this.urisMatch(s.route_uri, trimmed));
|
|
131
|
+
if (uriMatches.length > 0) {
|
|
132
|
+
const confidence = literalUriMatches.length ? "exact" : "inferred";
|
|
133
|
+
if (uriMatches.length === 1) {
|
|
134
|
+
return this.formatSuccessResponse(trimmed, uriMatches[0], confidence, undefined, effectiveMaxDepth);
|
|
135
|
+
}
|
|
136
|
+
// Multiple matches (e.g. GET /orders and POST /orders) -> return primary with alternatives
|
|
137
|
+
return this.formatSuccessResponse(trimmed, uriMatches[0], confidence, uriMatches.slice(1), effectiveMaxDepth);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 3. Named Route match: "orders.status.update" or "admin.users.index"
|
|
141
|
+
const nameMatch = allSlices.find(
|
|
142
|
+
(s) => s.route_name && s.route_name.toLowerCase() === lowerTrimmed
|
|
143
|
+
);
|
|
144
|
+
if (nameMatch) {
|
|
145
|
+
return this.formatSuccessResponse(trimmed, nameMatch, "exact", undefined, effectiveMaxDepth);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 3b. Omni-Trigger Match: "JOB ProcessOrderJob", "job:ProcessOrderJob", "CLI order:cleanup", "EVENT OrderPlacedListener"
|
|
149
|
+
const omniTriggerMatch = trimmed.match(/^(JOB|CLI|EVENT)\s+([A-Za-z0-9_:\-]+)$/i);
|
|
150
|
+
if (omniTriggerMatch) {
|
|
151
|
+
const triggerKind = omniTriggerMatch[1].toUpperCase();
|
|
152
|
+
const targetName = omniTriggerMatch[2].toLowerCase();
|
|
153
|
+
const exact = allSlices.find(
|
|
154
|
+
(s) =>
|
|
155
|
+
s.http_method.toUpperCase() === triggerKind &&
|
|
156
|
+
(s.controller_class.toLowerCase() === targetName ||
|
|
157
|
+
s.route_uri.toLowerCase() === targetName ||
|
|
158
|
+
s.route_uri.toLowerCase() === `${triggerKind.toLowerCase()}:${targetName}`)
|
|
159
|
+
);
|
|
160
|
+
if (exact) {
|
|
161
|
+
return this.formatSuccessResponse(trimmed, exact, "exact", undefined, effectiveMaxDepth);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// 4. Controller@Action match: "OrderController@updateStatus" or "OrderController"
|
|
166
|
+
const controllerActionMatch = trimmed.match(/^([A-Za-z0-9_\\/.]+?)(?:(?:@|::)([A-Za-z0-9_]+))?$/);
|
|
167
|
+
if (controllerActionMatch) {
|
|
168
|
+
const [, rawCtrl, act] = controllerActionMatch;
|
|
169
|
+
const ctrl = rawCtrl.split(/[\\/]/).pop()?.replace(/\.(php|ts|js)$/i, "") || rawCtrl;
|
|
170
|
+
const lowerCtrl = ctrl.toLowerCase();
|
|
171
|
+
const lowerAct = act ? act.toLowerCase() : undefined;
|
|
172
|
+
|
|
173
|
+
const exact = allSlices.find((s) => {
|
|
174
|
+
const sCtrlLower = s.controller_class.toLowerCase();
|
|
175
|
+
const ctrlMatch =
|
|
176
|
+
sCtrlLower === lowerCtrl ||
|
|
177
|
+
sCtrlLower.endsWith(`\\${lowerCtrl}`) ||
|
|
178
|
+
sCtrlLower.endsWith(`/${lowerCtrl}`);
|
|
179
|
+
if (!ctrlMatch) return false;
|
|
180
|
+
if (lowerAct) return s.action_name.toLowerCase() === lowerAct;
|
|
181
|
+
if (!act && !lowerCtrl.endsWith("controller") && sCtrlLower !== lowerCtrl) {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
return true;
|
|
185
|
+
});
|
|
186
|
+
if (exact) {
|
|
187
|
+
return this.formatSuccessResponse(trimmed, exact, "exact", undefined, effectiveMaxDepth);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// 5. Symbol Match in Execution Chain or Action Name (e.g. "createOrder", "CreateOrderUseCase", "OrderController")
|
|
192
|
+
const symbolMatch = allSlices.find((s) => {
|
|
193
|
+
if (s.action_name.toLowerCase() === lowerTrimmed) return true;
|
|
194
|
+
if (s.controller_class.toLowerCase() === lowerTrimmed) return true;
|
|
195
|
+
if (s.execution_chain_json) {
|
|
196
|
+
try {
|
|
197
|
+
const chain: ExecutionChainNode[] = JSON.parse(s.execution_chain_json);
|
|
198
|
+
return chain.some(
|
|
199
|
+
(node) =>
|
|
200
|
+
node.symbol.toLowerCase() === lowerTrimmed ||
|
|
201
|
+
node.symbol.toLowerCase().includes(lowerTrimmed) ||
|
|
202
|
+
(node.file && node.file.toLowerCase().includes(lowerTrimmed))
|
|
203
|
+
);
|
|
204
|
+
} catch {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return false;
|
|
209
|
+
});
|
|
210
|
+
if (symbolMatch) {
|
|
211
|
+
return this.formatSuccessResponse(trimmed, symbolMatch, "inferred", undefined, effectiveMaxDepth);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// 6. Semantic / Token Scoring for Natural Language (e.g. "Ubah status order di dashboard")
|
|
215
|
+
const tokens = this.tokenize(trimmed);
|
|
216
|
+
const scoredSlices = allSlices
|
|
217
|
+
.map((slice) => {
|
|
218
|
+
let score = 0;
|
|
219
|
+
const textCorpus = [
|
|
220
|
+
slice.route_uri,
|
|
221
|
+
slice.route_name || "",
|
|
222
|
+
slice.controller_class,
|
|
223
|
+
slice.action_name,
|
|
224
|
+
slice.execution_chain_json || "",
|
|
225
|
+
].join(" ").toLowerCase();
|
|
226
|
+
|
|
227
|
+
for (const token of tokens) {
|
|
228
|
+
if (textCorpus.includes(token)) {
|
|
229
|
+
score += 1;
|
|
230
|
+
if (slice.route_uri.toLowerCase().includes(token)) score += 2;
|
|
231
|
+
if (slice.action_name.toLowerCase().includes(token)) score += 2;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return { slice, score };
|
|
235
|
+
})
|
|
236
|
+
.filter((item) => item.score > 0)
|
|
237
|
+
.sort((a, b) => b.score - a.score);
|
|
238
|
+
|
|
239
|
+
if (scoredSlices.length > 0) {
|
|
240
|
+
const primary = scoredSlices[0].slice;
|
|
241
|
+
const alternatives = scoredSlices.slice(1, 4).map((item) => item.slice);
|
|
242
|
+
return this.formatSuccessResponse(trimmed, primary, "inferred", alternatives, effectiveMaxDepth);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
query: trimmed,
|
|
247
|
+
found: false,
|
|
248
|
+
max_depth_applied: effectiveMaxDepth,
|
|
249
|
+
alternatives: allSlices.slice(0, 5).map((s) => ({
|
|
250
|
+
method: s.http_method,
|
|
251
|
+
uri: s.route_uri,
|
|
252
|
+
controller: s.controller_class,
|
|
253
|
+
action: s.action_name,
|
|
254
|
+
})),
|
|
255
|
+
message: `No vertical slice found matching query '${trimmed}'.`,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private urisMatch(uriA: string, uriB: string): boolean {
|
|
260
|
+
const normA = uriA
|
|
261
|
+
.replace(/\{[^}]+\}/g, ":param")
|
|
262
|
+
.replace(/:[a-zA-Z0-9_]+/g, ":param");
|
|
263
|
+
const normB = uriB
|
|
264
|
+
.replace(/\{[^}]+\}/g, ":param")
|
|
265
|
+
.replace(/:[a-zA-Z0-9_]+/g, ":param");
|
|
266
|
+
return normA === normB;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
private tokenize(str: string): string[] {
|
|
270
|
+
return str
|
|
271
|
+
.replace(/([a-z])([A-Z])/g, "$1 $2")
|
|
272
|
+
.toLowerCase()
|
|
273
|
+
.replace(/[^a-z0-9_]+/g, " ")
|
|
274
|
+
.split(/\s+/)
|
|
275
|
+
.filter((t) => t.length > 2 && !["ubah", "di", "dan", "yang", "the", "for", "and"].includes(t));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private formatSuccessResponse(
|
|
279
|
+
query: string,
|
|
280
|
+
record: VerticalSliceRecord,
|
|
281
|
+
confidence: "exact" | "inferred" = "exact",
|
|
282
|
+
alternatives?: VerticalSliceRecord[],
|
|
283
|
+
effectiveMaxDepth: number = 5
|
|
284
|
+
): VerticalSliceTraceResponse {
|
|
285
|
+
let chain: ExecutionChainNode[] = [];
|
|
286
|
+
if (record.execution_chain_json) {
|
|
287
|
+
try {
|
|
288
|
+
chain = JSON.parse(record.execution_chain_json);
|
|
289
|
+
} catch (err: unknown) {
|
|
290
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
291
|
+
console.error(`[Septum Slice Error] Corrupted execution chain JSON for slice ${record.id}: ${msg}`);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Import expansion is derived per request, so cached depth cannot override the requested hop limit.
|
|
296
|
+
chain = chain.filter(node => node.relationship?.kind !== "imports" && !node.description?.includes("(dependency)"));
|
|
297
|
+
if (
|
|
298
|
+
record.controller_file &&
|
|
299
|
+
typeof (this.repo as any).getAllFiles === "function"
|
|
300
|
+
) {
|
|
301
|
+
try {
|
|
302
|
+
const callGraphTracer = new CallGraphTracer(this.repo, this.projectRoot);
|
|
303
|
+
chain = callGraphTracer.expandChainFromFile(
|
|
304
|
+
record.controller_file,
|
|
305
|
+
chain,
|
|
306
|
+
effectiveMaxDepth
|
|
307
|
+
);
|
|
308
|
+
} catch {
|
|
309
|
+
// Ignore expansion errors on mock/partial repositories
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
let message = `Vertical slice resolved (${confidence}): ${record.http_method} ${record.route_uri} -> ${record.controller_class}@${record.action_name}`;
|
|
314
|
+
if (chain.length > 0) {
|
|
315
|
+
const stageLines = chain.map((node) => {
|
|
316
|
+
const stageLabel = `[${node.stage.toUpperCase()}]`.padEnd(14, " ");
|
|
317
|
+
const loc = node.file ? ` (${node.file}${node.line ? `:${node.line}` : ""})` : "";
|
|
318
|
+
let extra = "";
|
|
319
|
+
if (node.table) {
|
|
320
|
+
extra += ` [table: ${node.table}]`;
|
|
321
|
+
}
|
|
322
|
+
if (node.columns_summary) {
|
|
323
|
+
extra += ` {${node.columns_summary}}`;
|
|
324
|
+
}
|
|
325
|
+
if (node.guards && node.guards.length > 0 && node.stage !== "guard") {
|
|
326
|
+
extra += ` [guards: ${node.guards.join(", ")}]`;
|
|
327
|
+
}
|
|
328
|
+
if (node.mutations && node.mutations.length > 0 && node.stage !== "side_effect") {
|
|
329
|
+
extra += ` [mutates: ${node.mutations.join(", ")}]`;
|
|
330
|
+
}
|
|
331
|
+
if (node.transactions && node.stage !== "transaction") {
|
|
332
|
+
extra += ` [tx: active]`;
|
|
333
|
+
}
|
|
334
|
+
return `${stageLabel} ${node.symbol}${loc}${extra}`;
|
|
335
|
+
});
|
|
336
|
+
message = `=== VERTICAL SLICE TRACE (${confidence.toUpperCase()}) ===\n` + stageLines.join("\n");
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
return {
|
|
340
|
+
query,
|
|
341
|
+
found: true,
|
|
342
|
+
confidence,
|
|
343
|
+
is_exact_match: confidence === "exact",
|
|
344
|
+
architecture_style: record.architecture_style,
|
|
345
|
+
max_depth_applied: effectiveMaxDepth,
|
|
346
|
+
entrypoint: {
|
|
347
|
+
method: record.http_method,
|
|
348
|
+
uri: record.route_uri,
|
|
349
|
+
name: record.route_name,
|
|
350
|
+
controller: record.controller_class,
|
|
351
|
+
action: record.action_name,
|
|
352
|
+
file: record.controller_file,
|
|
353
|
+
line: record.controller_line,
|
|
354
|
+
},
|
|
355
|
+
chain,
|
|
356
|
+
slice: chain,
|
|
357
|
+
alternatives: alternatives?.map((a) => ({
|
|
358
|
+
method: a.http_method,
|
|
359
|
+
uri: a.route_uri,
|
|
360
|
+
controller: a.controller_class,
|
|
361
|
+
action: a.action_name,
|
|
362
|
+
})),
|
|
363
|
+
message,
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
export const DEFAULT_IGNORED_DIRECTORIES: ReadonlySet<string> = new Set([
|
|
2
|
+
// Package managers & dependencies (visible & hidden)
|
|
3
|
+
"node_modules",
|
|
4
|
+
"vendor",
|
|
5
|
+
"bower_components",
|
|
6
|
+
"jspm_packages",
|
|
7
|
+
|
|
8
|
+
// Build, bundle & compilation outputs (visible & hidden)
|
|
9
|
+
"dist",
|
|
10
|
+
"build",
|
|
11
|
+
"out",
|
|
12
|
+
"output",
|
|
13
|
+
".output",
|
|
14
|
+
"target",
|
|
15
|
+
"obj",
|
|
16
|
+
"bin",
|
|
17
|
+
"scripts",
|
|
18
|
+
".next",
|
|
19
|
+
".nuxt",
|
|
20
|
+
".turbo",
|
|
21
|
+
".parcel-cache",
|
|
22
|
+
".svelte-kit",
|
|
23
|
+
".astro",
|
|
24
|
+
".docusaurus",
|
|
25
|
+
|
|
26
|
+
// Python virtual environments and bytecode caches
|
|
27
|
+
".venv",
|
|
28
|
+
"venv",
|
|
29
|
+
"env",
|
|
30
|
+
".env",
|
|
31
|
+
"virtualenv",
|
|
32
|
+
"__pycache__",
|
|
33
|
+
".pytest_cache",
|
|
34
|
+
".mypy_cache",
|
|
35
|
+
".ruff_cache",
|
|
36
|
+
".tox",
|
|
37
|
+
|
|
38
|
+
// Test coverage
|
|
39
|
+
"coverage",
|
|
40
|
+
".nyc_output",
|
|
41
|
+
|
|
42
|
+
// Version control & repository metadata
|
|
43
|
+
".git",
|
|
44
|
+
".svn",
|
|
45
|
+
".hg",
|
|
46
|
+
".github",
|
|
47
|
+
".gitlab",
|
|
48
|
+
|
|
49
|
+
// Tooling, agent & IDE metadata
|
|
50
|
+
".septum",
|
|
51
|
+
".strata",
|
|
52
|
+
".codegraph",
|
|
53
|
+
".system_generated",
|
|
54
|
+
".gemini",
|
|
55
|
+
".claude",
|
|
56
|
+
".agents",
|
|
57
|
+
".codex",
|
|
58
|
+
"opencode",
|
|
59
|
+
".opencode",
|
|
60
|
+
".cursor",
|
|
61
|
+
".vscode",
|
|
62
|
+
".idea",
|
|
63
|
+
".codex-evidence",
|
|
64
|
+
".antigravity",
|
|
65
|
+
".cline",
|
|
66
|
+
".roo",
|
|
67
|
+
".windsurf",
|
|
68
|
+
".continue",
|
|
69
|
+
".copilot",
|
|
70
|
+
".chat",
|
|
71
|
+
|
|
72
|
+
// Cache & Temp
|
|
73
|
+
".cache",
|
|
74
|
+
"tmp",
|
|
75
|
+
"temp",
|
|
76
|
+
".sass-cache",
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
export function isIgnoredDirectory(dirName: string): boolean {
|
|
80
|
+
if (!dirName || dirName === "." || dirName === "..") return false;
|
|
81
|
+
return DEFAULT_IGNORED_DIRECTORIES.has(dirName) || dirName.startsWith(".");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function shouldIgnoreSourcePath(filePath: string, ignorePatterns: string[] = []): boolean {
|
|
85
|
+
const normPath = filePath.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
86
|
+
const segments = normPath.split("/");
|
|
87
|
+
|
|
88
|
+
// Fast check: if any segment is a standard ignored directory or hidden directory/file
|
|
89
|
+
if (segments.some(segment => isIgnoredDirectory(segment))) {
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
for (const pattern of ignorePatterns) {
|
|
94
|
+
const normPattern = pattern.replace(/\\/g, "/").replace(/^\.\//, "").trim();
|
|
95
|
+
if (!normPattern) continue;
|
|
96
|
+
|
|
97
|
+
if (normPattern === "*" || normPattern === "**") {
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (normPath === normPattern) return true;
|
|
102
|
+
|
|
103
|
+
if (normPattern.endsWith("/**")) {
|
|
104
|
+
const prefix = normPattern.slice(0, -3);
|
|
105
|
+
if (normPath === prefix || normPath.startsWith(prefix + "/")) return true;
|
|
106
|
+
} else if (normPattern.endsWith("/*")) {
|
|
107
|
+
const prefix = normPattern.slice(0, -2);
|
|
108
|
+
if (normPath === prefix || normPath.startsWith(prefix + "/")) return true;
|
|
109
|
+
} else if (normPath.startsWith(normPattern + "/")) {
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (normPattern.startsWith("*.") && normPath.endsWith(normPattern.slice(1))) {
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (segments.includes(normPattern)) {
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export const RESOURCE_LIMITS = Object.freeze({
|
|
2
|
+
workspaces: 4,
|
|
3
|
+
workspaceIdleMs: 10 * 60_000,
|
|
4
|
+
watches: 2048,
|
|
5
|
+
pendingPaths: 1000,
|
|
6
|
+
debounceMs: 300,
|
|
7
|
+
pollMs: 5000,
|
|
8
|
+
verifyMs: 60_000,
|
|
9
|
+
sourceBytes: 2 * 1024 * 1024,
|
|
10
|
+
batchFiles: 50,
|
|
11
|
+
batchBytes: 1024 * 1024,
|
|
12
|
+
maxQueuePending: 50,
|
|
13
|
+
shutdownMs: 5000,
|
|
14
|
+
});
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { closeSync, fstatSync, openSync, readSync, statSync } from 'node:fs';
|
|
3
|
+
import { relative } from 'node:path';
|
|
4
|
+
import { computeContentHash } from "../ingestion/hasher.ts";
|
|
5
|
+
import { RESOURCE_LIMITS } from './limits.ts';
|
|
6
|
+
|
|
7
|
+
export interface SkippedSourceFile { path: string; reason: 'file_too_large' }
|
|
8
|
+
export class SourceFileLimitError extends Error {
|
|
9
|
+
constructor(public readonly filePath: string) { super(`Source file exceeds ${RESOURCE_LIMITS.sourceBytes} bytes: ${filePath}`); }
|
|
10
|
+
}
|
|
11
|
+
export interface SourceReadFingerprint { path: string; hash: string; size: number; mtime: number }
|
|
12
|
+
const reads = new AsyncLocalStorage<{skipped: Map<string, SkippedSourceFile>; inputs: Map<string, SourceReadFingerprint>}>();
|
|
13
|
+
|
|
14
|
+
// Read at most the admission limit, even if the file grows after stat.
|
|
15
|
+
export function readSourceFile(filePath: string, _encoding?: string): string {
|
|
16
|
+
const fd = openSync(filePath, 'r');
|
|
17
|
+
try {
|
|
18
|
+
const size = fstatSync(fd).size;
|
|
19
|
+
if (size > RESOURCE_LIMITS.sourceBytes) throw new SourceFileLimitError(filePath);
|
|
20
|
+
let buffer = Buffer.allocUnsafe(Math.min(Math.max(size + 1, 4096), RESOURCE_LIMITS.sourceBytes + 1));
|
|
21
|
+
let count = 0;
|
|
22
|
+
while (true) {
|
|
23
|
+
const read = readSync(fd, buffer, count, buffer.length - count, null);
|
|
24
|
+
if (!read) return buffer.toString('utf8', 0, count);
|
|
25
|
+
count += read;
|
|
26
|
+
if (count > RESOURCE_LIMITS.sourceBytes) throw new SourceFileLimitError(filePath);
|
|
27
|
+
if (count === buffer.length) {
|
|
28
|
+
const expanded = Buffer.allocUnsafe(Math.min(buffer.length * 2, RESOURCE_LIMITS.sourceBytes + 1));
|
|
29
|
+
buffer.copy(expanded, 0, 0, count);
|
|
30
|
+
buffer = expanded;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
} finally { closeSync(fd); }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function readOptionalSourceFile(filePath: string, encoding?: string): string {
|
|
37
|
+
try {
|
|
38
|
+
const content = readSourceFile(filePath, encoding);
|
|
39
|
+
const collector = reads.getStore();
|
|
40
|
+
if (collector) {
|
|
41
|
+
const stat = statSync(filePath);
|
|
42
|
+
collector.inputs.set(filePath, {path:filePath,hash:computeContentHash(content),size:stat.size,mtime:stat.mtimeMs});
|
|
43
|
+
}
|
|
44
|
+
return content;
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (!(error instanceof SourceFileLimitError)) throw error;
|
|
48
|
+
const collector = reads.getStore();
|
|
49
|
+
if (!collector) throw error;
|
|
50
|
+
collector.skipped.set(filePath, { path: filePath, reason: 'file_too_large' });
|
|
51
|
+
const stat = statSync(filePath);
|
|
52
|
+
collector.inputs.set(filePath, {path:filePath,hash:'file_too_large',size:stat.size,mtime:stat.mtimeMs});
|
|
53
|
+
return '';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function collectSourceSkips<T>(root: string, read: () => Promise<T>): Promise<{ value: T; skipped: SkippedSourceFile[]; inputs: SourceReadFingerprint[] }> {
|
|
58
|
+
const collector = {skipped: new Map<string, SkippedSourceFile>(), inputs: new Map<string, SourceReadFingerprint>()};
|
|
59
|
+
const value = await reads.run(collector, read);
|
|
60
|
+
const rel = (file: {path:string}) => relative(root, file.path).replace(/\\/g, '/');
|
|
61
|
+
return {value, skipped:[...collector.skipped.values()].map(file => ({...file,path:rel(file)})), inputs:[...collector.inputs.values()].map(file => ({...file,path:rel(file)}))};
|
|
62
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { RESOURCE_LIMITS } from "./limits.ts";
|
|
2
|
+
|
|
3
|
+
/** One mutation/parse lane per server; failures do not poison later work. */
|
|
4
|
+
export class SerialWorkQueue {
|
|
5
|
+
private tail: Promise<void> = Promise.resolve();
|
|
6
|
+
private pending = 0;
|
|
7
|
+
private readonly maxPending: number;
|
|
8
|
+
|
|
9
|
+
constructor(maxPending = RESOURCE_LIMITS.maxQueuePending) {
|
|
10
|
+
this.maxPending = maxPending;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
get pendingCount(): number {
|
|
14
|
+
return this.pending;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
run<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
18
|
+
if (signal?.aborted) {
|
|
19
|
+
return Promise.reject(signal.reason ?? new Error("Request was cancelled before queueing"));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (this.pending >= this.maxPending) {
|
|
23
|
+
const busyError = new Error(`Server is busy: request admission limit (${this.maxPending}) exceeded. Retry after current tasks finish.`);
|
|
24
|
+
(busyError as any).code = "SERVER_BUSY";
|
|
25
|
+
return Promise.reject(busyError);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
this.pending++;
|
|
29
|
+
|
|
30
|
+
return new Promise<T>((resolve, reject) => {
|
|
31
|
+
let cancelled = false;
|
|
32
|
+
|
|
33
|
+
const abortHandler = () => {
|
|
34
|
+
cancelled = true;
|
|
35
|
+
reject(signal?.reason ?? new Error("Request was cancelled while queued"));
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
if (signal) {
|
|
39
|
+
signal.addEventListener("abort", abortHandler, { once: true });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const execute = async () => {
|
|
43
|
+
if (signal) {
|
|
44
|
+
signal.removeEventListener("abort", abortHandler);
|
|
45
|
+
}
|
|
46
|
+
if (cancelled || signal?.aborted) {
|
|
47
|
+
if (!cancelled) {
|
|
48
|
+
reject(signal?.reason ?? new Error("Request was cancelled before execution"));
|
|
49
|
+
}
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
const res = await work();
|
|
55
|
+
resolve(res);
|
|
56
|
+
} catch (err) {
|
|
57
|
+
reject(err);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const next = this.tail.then(execute, execute);
|
|
62
|
+
this.tail = next.finally(() => {
|
|
63
|
+
this.pending--;
|
|
64
|
+
if (this.pending === 0) {
|
|
65
|
+
this.tail = Promise.resolve();
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
drain(): Promise<void> {
|
|
72
|
+
return this.tail;
|
|
73
|
+
}
|
|
74
|
+
}
|