@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.
- package/README.md +46 -45
- package/package.json +8 -6
- package/src/cli/commands/check.ts +41 -26
- package/src/cli/commands/hook.ts +77 -105
- package/src/cli/commands/init.ts +35 -9
- package/src/cli/commands/stats.ts +33 -0
- package/src/cli/commands/sync-progress.ts +71 -0
- package/src/cli/commands/sync.ts +35 -9
- package/src/cli/hook-payload.ts +43 -0
- package/src/cli/index.ts +15 -51
- package/src/cli/scaffold/harness-config.ts +48 -8
- package/src/cli/templates/hooks.ts +51 -27
- package/src/cli/templates/rules.ts +34 -49
- package/src/cli/templates/skill.ts +46 -35
- package/src/core/boundary/audit.ts +383 -0
- package/src/core/boundary/evaluator.ts +299 -178
- package/src/core/boundary/staged-auditor.ts +188 -34
- package/src/core/config/domain-ownership.ts +47 -0
- package/src/core/config/domain-registration.ts +141 -0
- package/src/core/config/loader.ts +82 -54
- package/src/core/config/schema.ts +24 -46
- package/src/core/database/client.ts +2 -0
- package/src/core/database/repositories/dependency.repository.ts +326 -543
- package/src/core/database/repositories/domain.repository.ts +48 -4
- package/src/core/database/repositories/file.repository.ts +10 -0
- package/src/core/database/repositories/symbol.repository.ts +97 -259
- package/src/core/database/repository.ts +138 -24
- package/src/core/database/schema.ts +28 -33
- package/src/core/discovery/declarative-routes.ts +69 -0
- package/src/core/discovery/framework-detector.ts +149 -0
- package/src/core/discovery/navigation.ts +269 -0
- package/src/core/discovery/topology-detector.ts +153 -170
- package/src/core/errors.ts +19 -0
- package/src/core/ingestion/pipeline.ts +378 -212
- package/src/core/parser/behavioral-analyzer.ts +26 -22
- package/src/core/parser/boundary-tracker.ts +15 -0
- package/src/core/parser/extractors/base.ts +16 -4
- package/src/core/parser/extractors/csharp.ts +9 -5
- package/src/core/parser/extractors/django-routing.ts +163 -0
- package/src/core/parser/extractors/django-semantic.ts +400 -516
- package/src/core/parser/extractors/elysia-semantic.ts +172 -496
- package/src/core/parser/extractors/express-semantic.ts +195 -398
- package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
- package/src/core/parser/extractors/fastify-semantic.ts +216 -732
- package/src/core/parser/extractors/flask-semantic.ts +92 -388
- package/src/core/parser/extractors/go-routing.ts +344 -0
- package/src/core/parser/extractors/go-semantic.ts +210 -508
- package/src/core/parser/extractors/go.ts +6 -3
- package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
- package/src/core/parser/extractors/hono-semantic.ts +132 -530
- package/src/core/parser/extractors/java.ts +7 -5
- package/src/core/parser/extractors/laravel-routing.ts +263 -0
- package/src/core/parser/extractors/laravel-semantic.ts +169 -333
- package/src/core/parser/extractors/manifest-helpers.ts +64 -0
- package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
- package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
- package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
- package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
- package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
- package/src/core/parser/extractors/php.ts +17 -1
- package/src/core/parser/extractors/python-route-ast.ts +249 -0
- package/src/core/parser/extractors/python.ts +9 -8
- package/src/core/parser/extractors/registry.ts +28 -5
- package/src/core/parser/extractors/route-prefixes.ts +43 -0
- package/src/core/parser/extractors/ruby.ts +10 -7
- package/src/core/parser/extractors/rust.ts +35 -17
- package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
- package/src/core/parser/extractors/symfony-routing.ts +114 -0
- package/src/core/parser/extractors/symfony-semantic.ts +75 -262
- package/src/core/parser/extractors/typescript-bindings.ts +333 -0
- package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
- package/src/core/parser/extractors/typescript-fallback.ts +207 -0
- package/src/core/parser/extractors/typescript-route-context.ts +58 -0
- package/src/core/parser/extractors/typescript.ts +36 -216
- package/src/core/parser/implementation-fingerprint.ts +97 -0
- package/src/core/parser/language-capabilities.ts +23 -7
- package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
- package/src/core/parser/schema/schema-provider-registry.ts +1 -3
- package/src/core/parser/schema/schema-provider.interface.ts +2 -1
- package/src/core/parser/semantic-revision.ts +3 -0
- package/src/core/parser/static-string.ts +51 -0
- package/src/core/parser/wasm-loader.ts +6 -2
- package/src/core/resolver/ast-method-tracer.ts +230 -0
- package/src/core/resolver/call-graph-helpers.ts +72 -0
- package/src/core/resolver/call-graph-tracer.ts +375 -311
- package/src/core/resolver/dependency-analysis.ts +593 -0
- package/src/core/resolver/import-candidates.ts +120 -0
- package/src/core/resolver/import-evidence.ts +88 -0
- package/src/core/resolver/import-resolver.ts +162 -181
- package/src/core/resolver/interpretation-inputs.ts +65 -0
- package/src/core/resolver/languages/go.ts +103 -0
- package/src/core/resolver/languages/managed.ts +200 -0
- package/src/core/resolver/languages/python.ts +133 -0
- package/src/core/resolver/languages/ruby.ts +40 -0
- package/src/core/resolver/languages/rust.ts +127 -0
- package/src/core/resolver/languages/shared.ts +74 -0
- package/src/core/resolver/module-resolver.ts +18 -7
- package/src/core/resolver/path-resolver.ts +6 -3
- package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
- package/src/core/resolver/slice-catalog.ts +94 -0
- package/src/core/resolver/slice-format.ts +22 -0
- package/src/core/resolver/slice-selection.ts +237 -0
- package/src/core/resolver/symbol-impact.ts +477 -0
- package/src/core/resolver/symbol-locator.ts +82 -15
- package/src/core/resolver/vertical-slice-tracer.ts +57 -278
- package/src/core/resources/ignore.ts +21 -1
- package/src/core/resources/limits.ts +2 -1
- package/src/core/resources/source-files.ts +143 -20
- package/src/core/resources/source-inventory.ts +55 -0
- package/src/core/resources/work-queue.ts +167 -4
- package/src/core/retrieval/context-page.ts +116 -0
- package/src/core/retrieval/context.ts +457 -0
- package/src/core/retrieval/resolution-warnings.ts +21 -0
- package/src/core/retrieval/source-context.ts +448 -0
- package/src/core/retrieval/symbol-details.ts +453 -0
- package/src/core/retrieval/symbol-evidence.ts +97 -0
- package/src/core/retrieval/typescript-references.ts +293 -0
- package/src/core/retrieval/universal-context.ts +182 -0
- package/src/core/telemetry/summary.ts +114 -0
- package/src/core/telemetry/telemetry.ts +225 -37
- package/src/index.ts +0 -3
- package/src/mcp/formatters/compact-text.ts +439 -0
- package/src/mcp/resources-and-prompts.ts +253 -0
- package/src/mcp/schemas/boundary.ts +145 -0
- package/src/mcp/schemas/map.ts +250 -0
- package/src/mcp/schemas/shared.ts +52 -0
- package/src/mcp/schemas/slice.ts +60 -0
- package/src/mcp/schemas/symbol.ts +268 -0
- package/src/mcp/schemas.ts +5 -1105
- package/src/mcp/server.ts +263 -597
- package/src/mcp/tool-catalog.ts +331 -0
- package/src/mcp/tools/boundary.ts +69 -4
- package/src/mcp/tools/map.ts +126 -0
- package/src/mcp/tools/slice.ts +101 -3
- package/src/mcp/tools/symbol.ts +480 -26
- package/src/mcp/ui/app-client.ts +899 -0
- package/src/mcp/ui/app.html +478 -0
- package/src/mcp/workflow-playbooks.ts +181 -0
- package/src/mcp/workspace-boundary.ts +50 -0
- package/src/mcp/workspace-manager.ts +102 -18
- package/src/mcp/workspace-watcher.ts +38 -19
- package/src/types/index.ts +47 -53
- package/src/cli/commands/topology.ts +0 -161
- package/src/core/database/repositories/environment.repository.ts +0 -207
- package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
- package/src/core/session/session-manager.ts +0 -107
- package/src/core/topology/environment-detector.ts +0 -973
- package/src/core/topology/types.ts +0 -83
- package/src/mcp/tools/check-boundary.ts +0 -387
- package/src/mcp/tools/domain.ts +0 -40
- package/src/mcp/tools/feature.ts +0 -67
- package/src/mcp/tools/get-domain-catalog.ts +0 -226
- package/src/mcp/tools/get-environment-topology.ts +0 -138
- package/src/mcp/tools/get-feature-context.ts +0 -224
- package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
- package/src/mcp/tools/get-symbol-impact.ts +0 -64
- package/src/mcp/tools/get-symbol.ts +0 -175
- package/src/mcp/tools/locate-symbol.ts +0 -196
- package/src/mcp/tools/register-domain.ts +0 -75
- package/src/mcp/tools/register-feature.ts +0 -110
- package/src/mcp/tools/trace-vertical-slice.ts +0 -80
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
-
import { closeSync, fstatSync, openSync, readSync, statSync } from 'node:fs';
|
|
3
|
-
import { relative } from 'node:path';
|
|
2
|
+
import { closeSync, fstatSync, openSync, readSync, statSync, realpathSync, readdirSync, type Dirent } from 'node:fs';
|
|
3
|
+
import { relative, resolve } from 'node:path';
|
|
4
4
|
import { computeContentHash } from "../ingestion/hasher.ts";
|
|
5
5
|
import { RESOURCE_LIMITS } from './limits.ts';
|
|
6
6
|
|
|
@@ -9,21 +9,120 @@ export class SourceFileLimitError extends Error {
|
|
|
9
9
|
constructor(public readonly filePath: string) { super(`Source file exceeds ${RESOURCE_LIMITS.sourceBytes} bytes: ${filePath}`); }
|
|
10
10
|
}
|
|
11
11
|
export interface SourceReadFingerprint { path: string; hash: string; size: number; mtime: number }
|
|
12
|
-
const
|
|
12
|
+
export const SOURCE_READ_REVISION = "4";
|
|
13
|
+
type SourcePathKind = 'missing' | 'file' | 'directory' | 'other';
|
|
14
|
+
export interface SourcePathObservation { path: string; kind: SourcePathKind; real_path?: string }
|
|
15
|
+
export interface SourceDirectoryObservation { path: string; entries: string[] }
|
|
16
|
+
export interface SourceObservations { paths: SourcePathObservation[]; directories: SourceDirectoryObservation[] }
|
|
17
|
+
type SourceCollector = {
|
|
18
|
+
skipped: Map<string, SkippedSourceFile>;
|
|
19
|
+
inputs: Map<string, SourceReadFingerprint>;
|
|
20
|
+
conflicts: Set<string>;
|
|
21
|
+
paths: Map<string, SourcePathObservation>;
|
|
22
|
+
directories: Map<string, SourceDirectoryObservation>;
|
|
23
|
+
};
|
|
24
|
+
const reads = new AsyncLocalStorage<SourceCollector>();
|
|
25
|
+
|
|
26
|
+
function pathObservation(filePath: string): SourcePathObservation {
|
|
27
|
+
const path = resolve(filePath);
|
|
28
|
+
try {
|
|
29
|
+
const stat = statSync(path);
|
|
30
|
+
return { path, kind: stat.isFile() ? 'file' : stat.isDirectory() ? 'directory' : 'other', real_path: realpathSync(path) };
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) return { path, kind: 'missing' };
|
|
33
|
+
throw error; // Permission/read errors are not negative resolution evidence.
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Track existence/type and symlink destination, including negative lookups. */
|
|
38
|
+
export function probeSourcePath(filePath: string): SourcePathKind {
|
|
39
|
+
const observation = pathObservation(filePath);
|
|
40
|
+
const collector = reads.getStore();
|
|
41
|
+
if (collector) {
|
|
42
|
+
const prior = collector.paths.get(observation.path);
|
|
43
|
+
if (prior && JSON.stringify(prior) !== JSON.stringify(observation)) collector.conflicts.add(observation.path);
|
|
44
|
+
if (!prior) collector.paths.set(observation.path, observation);
|
|
45
|
+
}
|
|
46
|
+
return observation.kind;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function directoryEntries(entries: Dirent[]): string[] {
|
|
50
|
+
return entries.map(entry => `${entry.isDirectory() ? 'directory' : entry.isFile() ? 'file' : entry.isSymbolicLink() ? 'symlink' : 'other'}:${entry.name}`).sort();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Track the membership actually enumerated, not just a directory's mtime. */
|
|
54
|
+
export function readSourceDirectory(directory: string): Dirent[] {
|
|
55
|
+
probeSourcePath(directory);
|
|
56
|
+
const entries = readdirSync(directory, { withFileTypes: true });
|
|
57
|
+
const collector = reads.getStore();
|
|
58
|
+
if (collector) {
|
|
59
|
+
const path = resolve(directory);
|
|
60
|
+
const observation = { path, entries: directoryEntries(entries) };
|
|
61
|
+
const prior = collector.directories.get(path);
|
|
62
|
+
if (prior && JSON.stringify(prior.entries) !== JSON.stringify(observation.entries)) collector.conflicts.add(path);
|
|
63
|
+
if (!prior) collector.directories.set(path, observation);
|
|
64
|
+
}
|
|
65
|
+
return entries;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Revalidate a persisted manifest without collecting these validation reads. */
|
|
69
|
+
export function sourceObservationsCurrent(root: string, observations: SourceObservations): boolean {
|
|
70
|
+
try {
|
|
71
|
+
for (const observation of observations.paths) {
|
|
72
|
+
const path = resolve(root, observation.path);
|
|
73
|
+
const current = pathObservation(path);
|
|
74
|
+
if (current.kind !== observation.kind || current.real_path !== observation.real_path) return false;
|
|
75
|
+
}
|
|
76
|
+
for (const observation of observations.directories) {
|
|
77
|
+
const entries = directoryEntries(readdirSync(resolve(root, observation.path), { withFileTypes: true }));
|
|
78
|
+
if (JSON.stringify(entries) !== JSON.stringify(observation.entries)) return false;
|
|
79
|
+
}
|
|
80
|
+
return true;
|
|
81
|
+
} catch { return false; }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function recordInput(filePath: string, hash: string, size: number, mtime: number): void {
|
|
85
|
+
const collector = reads.getStore();
|
|
86
|
+
if (!collector) return;
|
|
87
|
+
const path = resolve(filePath);
|
|
88
|
+
const prior = collector.inputs.get(path);
|
|
89
|
+
if (prior && prior.hash !== hash) collector.conflicts.add(path);
|
|
90
|
+
// Keep the first version: a subsequent read must not hide already-derived facts.
|
|
91
|
+
if (!prior) collector.inputs.set(path, { path, hash, size, mtime });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function recordSkippedInput(filePath: string, size: number, mtime: number): void {
|
|
95
|
+
const collector = reads.getStore();
|
|
96
|
+
if (!collector) return;
|
|
97
|
+
collector.skipped.set(resolve(filePath), { path: resolve(filePath), reason: 'file_too_large' });
|
|
98
|
+
recordInput(filePath, 'file_too_large', size, mtime);
|
|
99
|
+
}
|
|
13
100
|
|
|
14
101
|
// Read at most the admission limit, even if the file grows after stat.
|
|
15
102
|
export function readSourceFile(filePath: string, _encoding?: string): string {
|
|
16
103
|
const fd = openSync(filePath, 'r');
|
|
17
104
|
try {
|
|
18
|
-
const
|
|
19
|
-
|
|
105
|
+
const stat = fstatSync(fd);
|
|
106
|
+
const size = stat.size;
|
|
107
|
+
if (size > RESOURCE_LIMITS.sourceBytes) {
|
|
108
|
+
recordSkippedInput(filePath, size, stat.mtimeMs);
|
|
109
|
+
throw new SourceFileLimitError(filePath);
|
|
110
|
+
}
|
|
20
111
|
let buffer = Buffer.allocUnsafe(Math.min(Math.max(size + 1, 4096), RESOURCE_LIMITS.sourceBytes + 1));
|
|
21
112
|
let count = 0;
|
|
22
113
|
while (true) {
|
|
23
114
|
const read = readSync(fd, buffer, count, buffer.length - count, null);
|
|
24
|
-
if (!read)
|
|
115
|
+
if (!read) {
|
|
116
|
+
const content = buffer.toString('utf8', 0, count);
|
|
117
|
+
if (reads.getStore()) recordInput(filePath, computeContentHash(content), size, stat.mtimeMs);
|
|
118
|
+
return content;
|
|
119
|
+
}
|
|
25
120
|
count += read;
|
|
26
|
-
if (count > RESOURCE_LIMITS.sourceBytes)
|
|
121
|
+
if (count > RESOURCE_LIMITS.sourceBytes) {
|
|
122
|
+
const current = fstatSync(fd);
|
|
123
|
+
recordSkippedInput(filePath, current.size, current.mtimeMs);
|
|
124
|
+
throw new SourceFileLimitError(filePath);
|
|
125
|
+
}
|
|
27
126
|
if (count === buffer.length) {
|
|
28
127
|
const expanded = Buffer.allocUnsafe(Math.min(buffer.length * 2, RESOURCE_LIMITS.sourceBytes + 1));
|
|
29
128
|
buffer.copy(expanded, 0, 0, count);
|
|
@@ -35,28 +134,52 @@ export function readSourceFile(filePath: string, _encoding?: string): string {
|
|
|
35
134
|
|
|
36
135
|
export function readOptionalSourceFile(filePath: string, encoding?: string): string {
|
|
37
136
|
try {
|
|
38
|
-
|
|
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;
|
|
137
|
+
return readSourceFile(filePath, encoding);
|
|
45
138
|
}
|
|
46
139
|
catch (error) {
|
|
47
140
|
if (!(error instanceof SourceFileLimitError)) throw error;
|
|
48
141
|
const collector = reads.getStore();
|
|
49
142
|
if (!collector) throw error;
|
|
50
|
-
collector.skipped.set(filePath, { path: filePath, reason: 'file_too_large' });
|
|
51
143
|
const stat = statSync(filePath);
|
|
52
|
-
|
|
144
|
+
recordSkippedInput(filePath, stat.size, stat.mtimeMs);
|
|
53
145
|
return '';
|
|
54
146
|
}
|
|
55
147
|
}
|
|
56
148
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
149
|
+
function createSourceCollector(): SourceCollector {
|
|
150
|
+
return { skipped: new Map(), inputs: new Map(), conflicts: new Set(), paths: new Map(), directories: new Map() };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function finalizeSourceCollection<T>(root: string, collector: SourceCollector, value: T) {
|
|
154
|
+
for (const input of collector.inputs.values()) {
|
|
155
|
+
let changed = collector.conflicts.has(input.path);
|
|
156
|
+
try {
|
|
157
|
+
if (input.hash === 'file_too_large') {
|
|
158
|
+
const stat = statSync(input.path);
|
|
159
|
+
changed ||= stat.size !== input.size || stat.mtimeMs !== input.mtime || stat.size <= RESOURCE_LIMITS.sourceBytes;
|
|
160
|
+
} else {
|
|
161
|
+
changed ||= computeContentHash(readSourceFile(input.path)) !== input.hash;
|
|
162
|
+
}
|
|
163
|
+
} catch { changed = true; }
|
|
164
|
+
if (changed) throw new Error(`Source changed during synchronization: ${relative(root, input.path)} changed during analysis. Retry against stable inputs.`);
|
|
165
|
+
}
|
|
166
|
+
if (collector.conflicts.size || !sourceObservationsCurrent(root, { paths: [...collector.paths.values()], directories: [...collector.directories.values()] })) {
|
|
167
|
+
throw new Error('Source changed during synchronization: resolution path or directory observations changed during analysis. Retry against stable inputs.');
|
|
168
|
+
}
|
|
60
169
|
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)}))
|
|
170
|
+
return {value, skipped:[...collector.skipped.values()].map(file => ({...file,path:rel(file)})).sort((a,b)=>a.path.localeCompare(b.path)), inputs:[...collector.inputs.values()].map(file => ({...file,path:rel(file)})).sort((a,b)=>a.path.localeCompare(b.path)),
|
|
171
|
+
observations: {
|
|
172
|
+
paths: [...collector.paths.values()].map(item => ({ ...item, path: rel(item) })).sort((a,b)=>a.path.localeCompare(b.path)),
|
|
173
|
+
directories: [...collector.directories.values()].map(item => ({ ...item, path: rel(item) })).sort((a,b)=>a.path.localeCompare(b.path)),
|
|
174
|
+
} };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function collectSourceSkipsSync<T>(root: string, read: () => T) {
|
|
178
|
+
const collector = createSourceCollector();
|
|
179
|
+
return finalizeSourceCollection(root, collector, reads.run(collector, read));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function collectSourceSkips<T>(root: string, read: () => Promise<T>) {
|
|
183
|
+
const collector = createSourceCollector();
|
|
184
|
+
return finalizeSourceCollection(root, collector, await reads.run(collector, read));
|
|
62
185
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { lstatSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, relative, resolve } from "node:path";
|
|
3
|
+
import { getLanguageCapability } from "../parser/language-capabilities.ts";
|
|
4
|
+
import { shouldIgnoreSourcePath } from "./ignore.ts";
|
|
5
|
+
import { readSourceDirectory } from "./source-files.ts";
|
|
6
|
+
|
|
7
|
+
export interface SourceInventory { root: string; files: readonly string[] }
|
|
8
|
+
export interface ScanOptions {
|
|
9
|
+
directory?: string;
|
|
10
|
+
ignorePatterns?: string[];
|
|
11
|
+
excludeRoots?: string[];
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}
|
|
14
|
+
function contained(file: string, root: string): boolean {
|
|
15
|
+
const rel = relative(root, file).replace(/\\/g, "/");
|
|
16
|
+
return !isAbsolute(rel) && rel !== ".." && !rel.startsWith("../");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Shared source membership. Read failures propagate instead of certifying an empty scan. */
|
|
20
|
+
export function scanSourceFiles(root: string, options: ScanOptions = {}): SourceInventory {
|
|
21
|
+
root = resolve(root);
|
|
22
|
+
const directory = resolve(options.directory ?? root);
|
|
23
|
+
if (!contained(directory, root)) throw new Error(`Source directory escapes workspace: ${directory}`);
|
|
24
|
+
const files: string[] = [];
|
|
25
|
+
const walk = (dir: string) => {
|
|
26
|
+
options.signal?.throwIfAborted();
|
|
27
|
+
let entries;
|
|
28
|
+
try { entries = readSourceDirectory(dir); }
|
|
29
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return; throw error; }
|
|
30
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
31
|
+
options.signal?.throwIfAborted();
|
|
32
|
+
const file = resolve(dir, entry.name);
|
|
33
|
+
const rel = relative(root, file).replace(/\\/g, "/");
|
|
34
|
+
if (shouldIgnoreSourcePath(rel, options.ignorePatterns) || options.excludeRoots?.some(child => rel === child || rel.startsWith(child + "/"))) continue;
|
|
35
|
+
if (entry.isDirectory()) walk(file);
|
|
36
|
+
else if (entry.isSymbolicLink()) {
|
|
37
|
+
try {
|
|
38
|
+
const target = realpathSync(file);
|
|
39
|
+
if (contained(target, realpathSync(root)) && statSync(target).isFile() && getLanguageCapability(target)) files.push(file);
|
|
40
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
41
|
+
} else if (entry.isFile() && getLanguageCapability(file)) files.push(file);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
try {
|
|
45
|
+
if (!contained(realpathSync(directory), realpathSync(root))) throw new Error(`Source directory escapes workspace: ${directory}`);
|
|
46
|
+
if (!lstatSync(directory).isDirectory()) return { root, files };
|
|
47
|
+
walk(directory);
|
|
48
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
49
|
+
return { root, files };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function listSourceFiles(directory: string, pattern: RegExp, inventory?: SourceInventory): string[] {
|
|
53
|
+
const source = inventory ?? scanSourceFiles(directory);
|
|
54
|
+
return source.files.filter(file => contained(file, resolve(directory)) && pattern.test(file));
|
|
55
|
+
}
|
|
@@ -1,7 +1,14 @@
|
|
|
1
|
+
import { WorkspaceBusyError } from "../errors.ts";
|
|
1
2
|
import { RESOURCE_LIMITS } from "./limits.ts";
|
|
2
3
|
|
|
4
|
+
export interface WorkQueue {
|
|
5
|
+
readonly pendingCount: number;
|
|
6
|
+
run<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
7
|
+
drain(): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
|
|
3
10
|
/** One mutation/parse lane per server; failures do not poison later work. */
|
|
4
|
-
export class SerialWorkQueue {
|
|
11
|
+
export class SerialWorkQueue implements WorkQueue {
|
|
5
12
|
private tail: Promise<void> = Promise.resolve();
|
|
6
13
|
private pending = 0;
|
|
7
14
|
private readonly maxPending: number;
|
|
@@ -20,9 +27,9 @@ export class SerialWorkQueue {
|
|
|
20
27
|
}
|
|
21
28
|
|
|
22
29
|
if (this.pending >= this.maxPending) {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
30
|
+
return Promise.reject(
|
|
31
|
+
new WorkspaceBusyError(`Server is busy: request admission limit (${this.maxPending}) exceeded. Retry after current tasks finish.`)
|
|
32
|
+
);
|
|
26
33
|
}
|
|
27
34
|
|
|
28
35
|
this.pending++;
|
|
@@ -72,3 +79,159 @@ export class SerialWorkQueue {
|
|
|
72
79
|
return this.tail;
|
|
73
80
|
}
|
|
74
81
|
}
|
|
82
|
+
|
|
83
|
+
/** Per-workspace reader/writer queue: concurrent readers, exclusive writers, FIFO fairness. */
|
|
84
|
+
export class ReadWriteWorkQueue implements WorkQueue {
|
|
85
|
+
private activeReaders = 0;
|
|
86
|
+
private activeWriter = false;
|
|
87
|
+
private waiters: Array<{ mode: "read" | "write"; start: () => void }> = [];
|
|
88
|
+
private drainResolvers: Array<() => void> = [];
|
|
89
|
+
private readonly maxPending: number;
|
|
90
|
+
|
|
91
|
+
constructor(maxPending = RESOURCE_LIMITS.maxQueuePending) {
|
|
92
|
+
this.maxPending = maxPending;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
get pendingCount(): number {
|
|
96
|
+
return this.waiters.length + this.activeReaders + (this.activeWriter ? 1 : 0);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
run<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
100
|
+
return this.runWrite(work, signal);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
runRead<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
104
|
+
return this.enqueue("read", work, signal);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
runWrite<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
108
|
+
return this.enqueue("write", work, signal);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private enqueue<T>(mode: "read" | "write", work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
112
|
+
if (signal?.aborted) {
|
|
113
|
+
return Promise.reject(signal.reason ?? new Error("Request was cancelled before queueing"));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (this.pendingCount >= this.maxPending) {
|
|
117
|
+
return Promise.reject(
|
|
118
|
+
new WorkspaceBusyError(`Server is busy: request admission limit (${this.maxPending}) exceeded. Retry after current tasks finish.`)
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return new Promise<T>((resolve, reject) => {
|
|
123
|
+
let settled = false;
|
|
124
|
+
let started = false;
|
|
125
|
+
|
|
126
|
+
const execute = async () => {
|
|
127
|
+
started = true;
|
|
128
|
+
if (signal) {
|
|
129
|
+
signal.removeEventListener("abort", abortHandler);
|
|
130
|
+
}
|
|
131
|
+
if (settled || signal?.aborted) {
|
|
132
|
+
if (!settled) {
|
|
133
|
+
settled = true;
|
|
134
|
+
reject(signal?.reason ?? new Error("Request was cancelled before execution"));
|
|
135
|
+
}
|
|
136
|
+
this.release(mode);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
const res = await work();
|
|
141
|
+
if (!settled) {
|
|
142
|
+
settled = true;
|
|
143
|
+
resolve(res);
|
|
144
|
+
}
|
|
145
|
+
} catch (err) {
|
|
146
|
+
if (!settled) {
|
|
147
|
+
settled = true;
|
|
148
|
+
reject(err);
|
|
149
|
+
}
|
|
150
|
+
} finally {
|
|
151
|
+
this.release(mode);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const waiter = { mode, start: () => { void execute(); } };
|
|
156
|
+
|
|
157
|
+
const abortHandler = () => {
|
|
158
|
+
if (started || settled) return;
|
|
159
|
+
settled = true;
|
|
160
|
+
const idx = this.waiters.indexOf(waiter);
|
|
161
|
+
if (idx !== -1) this.waiters.splice(idx, 1);
|
|
162
|
+
reject(signal?.reason ?? new Error("Request was cancelled while queued"));
|
|
163
|
+
this.scheduleNext();
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
if (signal) {
|
|
167
|
+
signal.addEventListener("abort", abortHandler, { once: true });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (mode === "read" && !this.activeWriter && this.waiters.length === 0) {
|
|
171
|
+
this.activeReaders++;
|
|
172
|
+
void execute();
|
|
173
|
+
} else if (mode === "write" && !this.activeWriter && this.activeReaders === 0 && this.waiters.length === 0) {
|
|
174
|
+
this.activeWriter = true;
|
|
175
|
+
void execute();
|
|
176
|
+
} else {
|
|
177
|
+
this.waiters.push(waiter);
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private release(mode: "read" | "write"): void {
|
|
183
|
+
if (mode === "read") {
|
|
184
|
+
this.activeReaders = Math.max(0, this.activeReaders - 1);
|
|
185
|
+
} else {
|
|
186
|
+
this.activeWriter = false;
|
|
187
|
+
}
|
|
188
|
+
this.scheduleNext();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private scheduleNext(): void {
|
|
192
|
+
if (!this.activeWriter && this.waiters.length > 0) {
|
|
193
|
+
if (this.waiters[0]!.mode === "write") {
|
|
194
|
+
if (this.activeReaders === 0) {
|
|
195
|
+
const next = this.waiters.shift()!;
|
|
196
|
+
this.activeWriter = true;
|
|
197
|
+
next.start();
|
|
198
|
+
}
|
|
199
|
+
} else {
|
|
200
|
+
while (this.waiters.length > 0 && this.waiters[0]!.mode === "read") {
|
|
201
|
+
const next = this.waiters.shift()!;
|
|
202
|
+
this.activeReaders++;
|
|
203
|
+
next.start();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (!this.activeWriter && this.activeReaders === 0 && this.waiters.length === 0) {
|
|
209
|
+
const resolvers = this.drainResolvers.splice(0);
|
|
210
|
+
for (const resolve of resolvers) resolve();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
drain(): Promise<void> {
|
|
215
|
+
if (!this.activeWriter && this.activeReaders === 0 && this.waiters.length === 0) {
|
|
216
|
+
return Promise.resolve();
|
|
217
|
+
}
|
|
218
|
+
return new Promise<void>((resolve) => {
|
|
219
|
+
this.drainResolvers.push(resolve);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// A requester can stop waiting without cancelling work owned by a workspace.
|
|
225
|
+
export function waitForSharedWork<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
226
|
+
if (!signal) return work;
|
|
227
|
+
return new Promise<T>((resolve, reject) => {
|
|
228
|
+
const abort = () => {
|
|
229
|
+
detach();
|
|
230
|
+
reject(signal.reason);
|
|
231
|
+
};
|
|
232
|
+
const detach = () => signal.removeEventListener("abort", abort);
|
|
233
|
+
work.then(value => { detach(); resolve(value); }, error => { detach(); reject(error); });
|
|
234
|
+
if (signal.aborted) abort();
|
|
235
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
236
|
+
});
|
|
237
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import type { ImportRelationship } from "../../types/index.ts";
|
|
2
|
+
import type { ContextValue } from "./typescript-references.ts";
|
|
3
|
+
|
|
4
|
+
export type SourceItem = {
|
|
5
|
+
selection_role?: "implementation" | "contract";
|
|
6
|
+
depth?: number;
|
|
7
|
+
kind: "source";
|
|
8
|
+
name: string;
|
|
9
|
+
reason: "target_implementation" | "direct_import_declaration" | "local_dependency";
|
|
10
|
+
source: { file_path: string; indexed_content_hash: string; start_line: number; end_line: number; text: string };
|
|
11
|
+
fragment?: { start_utf16: number; end_utf16: number; total_utf16: number; declaration_start_line: number; declaration_end_line: number };
|
|
12
|
+
};
|
|
13
|
+
type DiagnosticItem = { kind: "diagnostic"; reason: string; file_path?: string; detail?: string };
|
|
14
|
+
export type ContextItem = SourceItem | DiagnosticItem | { kind: "relationship"; reason: "target_file_import"; relationship: ImportRelationship } |
|
|
15
|
+
{ kind: "type_contract"; depth?: number; name: string; file_path: string; indexed_content_hash: string; start_line: number; end_line: number;
|
|
16
|
+
projection: "public_instance_signatures"; text: string; inferred_types: "unknown" | "explicit"; fragment?: SourceItem["fragment"] } |
|
|
17
|
+
{ kind: "selection"; reason: "known_call_arguments"; file_path: string; start_line: number; arguments: ContextValue[]; pruned_branches: number };
|
|
18
|
+
|
|
19
|
+
export function response(payload: object) {
|
|
20
|
+
return { content: [{ type: "text" as const, text: JSON.stringify(payload) }] };
|
|
21
|
+
}
|
|
22
|
+
export function budgetedResponse(payload: Record<string, unknown>, budget: number) {
|
|
23
|
+
let bytes = 0;
|
|
24
|
+
for (;;) {
|
|
25
|
+
const result = response({ ...payload, output_bytes: bytes });
|
|
26
|
+
const measured = Buffer.byteLength(JSON.stringify(result), "utf8");
|
|
27
|
+
if (bytes === measured) {
|
|
28
|
+
if (measured > budget) return response({ status: "budget_too_small", minimum_budget_bytes: measured,
|
|
29
|
+
message: "Required response metadata exceeds this budget; retry with a larger budget." });
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
bytes = measured;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
interface PageOptions {
|
|
36
|
+
items: ContextItem[];
|
|
37
|
+
start: number;
|
|
38
|
+
sourceOffset: number;
|
|
39
|
+
budget: number;
|
|
40
|
+
incomplete: boolean;
|
|
41
|
+
base: Record<string, unknown> & { query_id: string; snapshot_id: string };
|
|
42
|
+
accounting: { omitted_by_capacity: number; unexpanded_dependency_files: number };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function pageContext(options: PageOptions) {
|
|
46
|
+
const { items: all, start, sourceOffset, budget, incomplete, base, accounting } = options;
|
|
47
|
+
const current = all[start];
|
|
48
|
+
const currentText = current?.kind === "source" ? current.source.text : current?.kind === "type_contract" ? current.text : undefined;
|
|
49
|
+
if (sourceOffset && (currentText === undefined || sourceOffset >= currentText.length ||
|
|
50
|
+
currentText.charCodeAt(sourceOffset - 1) >= 0xd800 && currentText.charCodeAt(sourceOffset - 1) <= 0xdbff ||
|
|
51
|
+
currentText[sourceOffset - 1] === "\r" && currentText[sourceOffset] === "\n"))
|
|
52
|
+
return response({ status: "invalid_continuation", message: "Source fragment offset is outside the selected declaration." });
|
|
53
|
+
const envelope = (items: ContextItem[], end: number, nextSourceOffset = 0) => ({
|
|
54
|
+
...base,
|
|
55
|
+
status: incomplete || end < all.length || start > 0 || sourceOffset > 0 ? "partial" : "success",
|
|
56
|
+
completeness: incomplete || end < all.length || start > 0 || sourceOffset > 0 ? "partial" : "complete",
|
|
57
|
+
items,
|
|
58
|
+
accounting: { total: all.length, returned: items.length, offset: start, omitted_before: start,
|
|
59
|
+
omitted_after: all.length - end, source_offset: sourceOffset, next_source_offset: nextSourceOffset,
|
|
60
|
+
...accounting },
|
|
61
|
+
...(end < all.length && (end > start || nextSourceOffset > sourceOffset) ? { continuation: Buffer.from(JSON.stringify({ query: base.query_id, snapshot: base.snapshot_id, offset: end,
|
|
62
|
+
...(nextSourceOffset ? { source_offset: nextSourceOffset } : {}) })).toString("base64url") } : {}),
|
|
63
|
+
budget_bytes: budget,
|
|
64
|
+
});
|
|
65
|
+
let end = start;
|
|
66
|
+
const page: ContextItem[] = [];
|
|
67
|
+
let result = budgetedResponse(envelope([], start), budget);
|
|
68
|
+
for (; end < all.length; end++) {
|
|
69
|
+
const item = all[end]!;
|
|
70
|
+
const offset = end === start ? sourceOffset : 0;
|
|
71
|
+
const text = item.kind === "source" ? item.source.text : item.kind === "type_contract" ? item.text : undefined;
|
|
72
|
+
const fragment = (stop: number): ContextItem => {
|
|
73
|
+
if (text === undefined || (item.kind !== "source" && item.kind !== "type_contract")) return item;
|
|
74
|
+
const location = item.kind === "source" ? item.source : item;
|
|
75
|
+
const portion = text.slice(offset, stop);
|
|
76
|
+
const identity = { start_utf16: offset, end_utf16: stop, total_utf16: text.length,
|
|
77
|
+
declaration_start_line: location.start_line, declaration_end_line: location.end_line };
|
|
78
|
+
if (item.kind === "type_contract") return { ...item, text: portion, fragment: identity };
|
|
79
|
+
const line = item.source.start_line + (text.slice(0, offset).match(/\r\n|\r|\n/g)?.length ?? 0);
|
|
80
|
+
const lastLine = line + (portion.match(/\r\n|\r|\n/g)?.length ?? 0) - (/\r\n$|[\r\n]$/.test(portion) ? 1 : 0);
|
|
81
|
+
return { ...item, source: { ...item.source, text: portion, start_line: line, end_line: Math.max(line, lastLine) }, fragment: identity };
|
|
82
|
+
};
|
|
83
|
+
const whole = offset ? fragment(text!.length) : item;
|
|
84
|
+
const next = budgetedResponse(envelope([...page, whole], end + 1), budget);
|
|
85
|
+
if (JSON.parse(next.content[0]!.text).status === "budget_too_small") {
|
|
86
|
+
if (text !== undefined) {
|
|
87
|
+
let low = offset + 1, high = text.length - 1;
|
|
88
|
+
while (low <= high) {
|
|
89
|
+
const middle = Math.floor((low + high) / 2);
|
|
90
|
+
let stop = middle;
|
|
91
|
+
// Prefer clean line boundaries so fragments do not cut mid-identifier.
|
|
92
|
+
const lastNewline = text.lastIndexOf("\n", middle - 1);
|
|
93
|
+
if (lastNewline >= offset) {
|
|
94
|
+
stop = lastNewline + 1;
|
|
95
|
+
} else {
|
|
96
|
+
// Keep UTF-16 surrogate pairs and CRLF boundaries intact.
|
|
97
|
+
if (stop > offset && ((text.charCodeAt(stop - 1) >= 0xd800 && text.charCodeAt(stop - 1) <= 0xdbff) || text[stop - 1] === "\r" && text[stop] === "\n")) stop--;
|
|
98
|
+
if (stop === offset && offset + 2 < text.length) stop = offset + 2;
|
|
99
|
+
}
|
|
100
|
+
const partial = stop > offset ? budgetedResponse(envelope([...page, fragment(stop)], end, stop), budget) : undefined;
|
|
101
|
+
if (partial && JSON.parse(partial.content[0]!.text).status !== "budget_too_small") {
|
|
102
|
+
result = partial; low = middle + 1;
|
|
103
|
+
} else high = middle - 1;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
page.push(whole);
|
|
109
|
+
result = next;
|
|
110
|
+
}
|
|
111
|
+
if (end === start && all.length > start && !JSON.parse(result.content[0]!.text).continuation) {
|
|
112
|
+
return budgetedResponse({ ...envelope([], start), status: "budget_too_small", completeness: "partial",
|
|
113
|
+
message: "Response metadata and the next item fragment do not fit. Increase budget_bytes; no source was silently omitted." }, budget);
|
|
114
|
+
}
|
|
115
|
+
return result;
|
|
116
|
+
}
|