@mwillbanks/ast-mcp 0.6.3 → 0.6.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.
- package/dist/ast-mcp.js +331 -330
- package/dist/ast-mcp.js.map +87 -30
- package/dist/workers/code-intelligence-worker.js +2 -2
- package/dist/workers/code-intelligence-worker.js.map +4 -4
- package/package.json +2 -2
- package/src/helpers/mcp-schema.ts +91 -8
- package/src/intelligence/mutation/journal.ts +143 -22
- package/src/intelligence/mutation/locks.ts +92 -28
- package/src/intelligence/mutation/service.ts +614 -46
- package/src/intelligence/mutation/types.ts +2 -0
- package/src/patch/engine.ts +213 -85
- package/src/runtime/attributes.ts +293 -1
- package/src/runtime/file-delete.ts +130 -78
- package/src/runtime/file-read.ts +34 -11
- package/src/runtime/file-rename.ts +141 -30
- package/src/runtime/hash.ts +42 -1
- package/src/runtime/parent-directories.ts +114 -0
- package/src/runtime/reference-target-index.ts +35 -0
- package/src/runtime/snapshot-blob.ts +733 -0
- package/src/tools/code-intelligence-compute.ts +14 -6
- package/src/tools/code-intelligence-worker.ts +11 -2
- package/src/tools/code-intelligence.ts +126 -40
- package/src/tools/files.ts +2 -2
- package/src/tools/lifecycle.ts +37 -34
- package/templates/AGENTS.md +1 -0
- package/templates/skills/ast-mcp/SKILL.md +2 -0
- package/templates/skills/ast-mcp/references/agents-guidance.md +1 -0
- package/templates/skills/ast-mcp/references/patch-state-machine.md +8 -2
- package/templates/skills/ast-mcp/references/tool-catalog.md +4 -1
package/package.json
CHANGED
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"diff-match-patch-ts": "^2.0.0",
|
|
37
37
|
"onnxruntime-common": "1.30.0",
|
|
38
38
|
"parse5": "8.0.1",
|
|
39
|
-
"posthog-node": "5.56.
|
|
39
|
+
"posthog-node": "5.56.4",
|
|
40
40
|
"tree-sitter-systemverilog": "0.4.1",
|
|
41
41
|
"tree-sitter-wasm": "2.0.4",
|
|
42
42
|
"typescript-strada": "npm:@typescript/typescript6@6.0.2",
|
|
@@ -133,5 +133,5 @@
|
|
|
133
133
|
},
|
|
134
134
|
"sideEffects": false,
|
|
135
135
|
"type": "module",
|
|
136
|
-
"version": "0.6.
|
|
136
|
+
"version": "0.6.5"
|
|
137
137
|
}
|
|
@@ -27,25 +27,106 @@ export function boundedFileBatch<T extends z.ZodType>(
|
|
|
27
27
|
return z.object({ files: boundedRecord(schema, label) }).strict();
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
function failureCode(value: unknown): string | undefined {
|
|
31
|
+
if (!value || typeof value !== "object") return undefined;
|
|
32
|
+
const error = value as { code?: unknown; name?: unknown };
|
|
33
|
+
if (error.name === "AbortError") return "aborted";
|
|
34
|
+
if (error.name === "TimeoutError") return "timeout";
|
|
35
|
+
return typeof error.code === "string" &&
|
|
36
|
+
error.code.length <= 64 &&
|
|
37
|
+
/^[A-Za-z][A-Za-z0-9_.-]*$/.test(error.code)
|
|
38
|
+
? error.code
|
|
39
|
+
: undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Nested errors can contain source or credentials in messages. Expose only
|
|
43
|
+
// bounded machine diagnostics and explicitly identified filesystem paths.
|
|
44
|
+
function aggregateDiagnostics(error: AggregateError) {
|
|
45
|
+
const causes: Array<{ code: string; name: string }> = [];
|
|
46
|
+
const affectedPaths = new Set<string>();
|
|
47
|
+
const seen = new Set<unknown>();
|
|
48
|
+
const pending: unknown[] = [error];
|
|
49
|
+
let visited = 0;
|
|
50
|
+
let omitted = false;
|
|
51
|
+
while (pending.length && visited < 32) {
|
|
52
|
+
const item = pending.shift();
|
|
53
|
+
if (!item || typeof item !== "object" || seen.has(item)) continue;
|
|
54
|
+
seen.add(item);
|
|
55
|
+
visited++;
|
|
56
|
+
const value = item as {
|
|
57
|
+
name?: unknown;
|
|
58
|
+
details?: unknown;
|
|
59
|
+
cause?: unknown;
|
|
60
|
+
path?: unknown;
|
|
61
|
+
};
|
|
62
|
+
if (item !== error && causes.length >= 16) omitted = true;
|
|
63
|
+
if (item !== error && causes.length < 16)
|
|
64
|
+
causes.push({
|
|
65
|
+
code: failureCode(item) ?? "execution_failed",
|
|
66
|
+
name:
|
|
67
|
+
typeof value.name === "string" &&
|
|
68
|
+
[
|
|
69
|
+
"Error",
|
|
70
|
+
"AggregateError",
|
|
71
|
+
"TypeError",
|
|
72
|
+
"RangeError",
|
|
73
|
+
"SyntaxError",
|
|
74
|
+
"ReferenceError",
|
|
75
|
+
"URIError",
|
|
76
|
+
"EvalError",
|
|
77
|
+
"AbortError",
|
|
78
|
+
"TimeoutError",
|
|
79
|
+
].includes(value.name)
|
|
80
|
+
? value.name
|
|
81
|
+
: "Error",
|
|
82
|
+
});
|
|
83
|
+
const details = value.details as { affectedPaths?: unknown } | undefined;
|
|
84
|
+
const paths = Array.isArray(details?.affectedPaths)
|
|
85
|
+
? details.affectedPaths
|
|
86
|
+
: [];
|
|
87
|
+
if (paths.length > 20) omitted = true;
|
|
88
|
+
for (const path of [...paths.slice(0, 20), value.path]) {
|
|
89
|
+
if (path === undefined) continue;
|
|
90
|
+
if (typeof path !== "string" || path.length > 1024) {
|
|
91
|
+
omitted = true;
|
|
92
|
+
} else if (!affectedPaths.has(path)) {
|
|
93
|
+
if (affectedPaths.size < 20) affectedPaths.add(path);
|
|
94
|
+
else omitted = true;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (item instanceof AggregateError) {
|
|
98
|
+
if (item.errors.length > 16) omitted = true;
|
|
99
|
+
pending.push(...item.errors.slice(0, 16));
|
|
100
|
+
}
|
|
101
|
+
if (value.cause) pending.push(value.cause);
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
affectedPaths: [...affectedPaths],
|
|
105
|
+
causes,
|
|
106
|
+
truncated: omitted || pending.length > 0,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
30
110
|
export function toolFailure(error: unknown) {
|
|
31
111
|
if (error instanceof InputRequiredSignal) return error.result;
|
|
32
|
-
const value = error as Error & {
|
|
33
|
-
code?:
|
|
112
|
+
const value = (error ?? {}) as Error & {
|
|
113
|
+
code?: unknown;
|
|
34
114
|
decision?: unknown;
|
|
35
115
|
details?: unknown;
|
|
36
116
|
retryable?: boolean;
|
|
37
117
|
suggestedNextCall?: string;
|
|
38
118
|
};
|
|
39
119
|
const message = error instanceof Error ? error.message : String(error);
|
|
120
|
+
const normalizedCode = failureCode(value);
|
|
40
121
|
const operatingSystemCode =
|
|
41
|
-
|
|
122
|
+
normalizedCode === "EACCES" || normalizedCode === "EPERM"
|
|
42
123
|
? "permission_denied"
|
|
43
|
-
:
|
|
124
|
+
: normalizedCode === "ENOENT"
|
|
44
125
|
? "file_not_found"
|
|
45
126
|
: undefined;
|
|
46
127
|
const code =
|
|
47
128
|
operatingSystemCode ??
|
|
48
|
-
|
|
129
|
+
normalizedCode ??
|
|
49
130
|
(/(?:hash|expectedSha256|stale file context)/i.test(message)
|
|
50
131
|
? "stale_or_missing_hash"
|
|
51
132
|
: /format/i.test(message)
|
|
@@ -64,9 +145,11 @@ export function toolFailure(error: unknown) {
|
|
|
64
145
|
error: {
|
|
65
146
|
code,
|
|
66
147
|
details:
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
148
|
+
error instanceof AggregateError
|
|
149
|
+
? aggregateDiagnostics(error)
|
|
150
|
+
: (value.details ??
|
|
151
|
+
value.decision ??
|
|
152
|
+
(operatingSystemCode ? { osCode: normalizedCode } : undefined)),
|
|
70
153
|
message,
|
|
71
154
|
retryable:
|
|
72
155
|
value.retryable ??
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isAbsolute, normalize } from "node:path";
|
|
1
|
+
import { isAbsolute, normalize, resolve } from "node:path";
|
|
2
2
|
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
|
|
@@ -40,22 +40,62 @@ const CanonicalAbsolutePathSchema = z
|
|
|
40
40
|
message: "Expected a canonical absolute path",
|
|
41
41
|
});
|
|
42
42
|
|
|
43
|
+
function validBase64(value: string): boolean {
|
|
44
|
+
if (value.length % 4 !== 0) return false;
|
|
45
|
+
const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
|
|
46
|
+
for (let index = 0; index < value.length - padding; index++) {
|
|
47
|
+
const code = value.charCodeAt(index);
|
|
48
|
+
if (
|
|
49
|
+
!(
|
|
50
|
+
(code >= 65 && code <= 90) ||
|
|
51
|
+
(code >= 97 && code <= 122) ||
|
|
52
|
+
(code >= 48 && code <= 57) ||
|
|
53
|
+
code === 43 ||
|
|
54
|
+
code === 47
|
|
55
|
+
)
|
|
56
|
+
)
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const SnapshotBlobSchema = z
|
|
63
|
+
.object({
|
|
64
|
+
id: z.string().regex(/^[1-9][0-9]*-[a-f0-9-]{36}$/),
|
|
65
|
+
sha256: Sha256Schema,
|
|
66
|
+
size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
67
|
+
})
|
|
68
|
+
.strict();
|
|
69
|
+
|
|
43
70
|
const MutationJournalFileSchema = z
|
|
44
71
|
.object({
|
|
45
72
|
candidateSha256: Sha256Schema.nullable(),
|
|
46
73
|
committedDeleted: z.boolean(),
|
|
47
74
|
committedSha256: Sha256Schema.nullable(),
|
|
48
75
|
filePath: CanonicalAbsolutePathSchema,
|
|
76
|
+
sourceBlob: SnapshotBlobSchema.nullable().optional(),
|
|
49
77
|
sourceContentBase64: z
|
|
50
78
|
.string()
|
|
51
|
-
.
|
|
79
|
+
.refine(validBase64, "Invalid Base64")
|
|
52
80
|
.nullable(),
|
|
53
81
|
sourceGid: z.number().int().nonnegative().nullable(),
|
|
54
82
|
sourceMode: z.number().int().nonnegative().nullable(),
|
|
55
83
|
sourceSha256: Sha256Schema.nullable(),
|
|
56
84
|
sourceUid: z.number().int().nonnegative().nullable(),
|
|
57
85
|
})
|
|
58
|
-
.strict()
|
|
86
|
+
.strict()
|
|
87
|
+
.superRefine((file, context) => {
|
|
88
|
+
if (
|
|
89
|
+
file.sourceBlob &&
|
|
90
|
+
(file.sourceContentBase64 !== null ||
|
|
91
|
+
file.sourceBlob.sha256 !== file.sourceSha256)
|
|
92
|
+
)
|
|
93
|
+
context.addIssue({
|
|
94
|
+
code: "custom",
|
|
95
|
+
message: "Snapshot identity must match its source digest",
|
|
96
|
+
path: ["sourceBlob"],
|
|
97
|
+
});
|
|
98
|
+
});
|
|
59
99
|
|
|
60
100
|
const MutationJournalRecordSchema = z
|
|
61
101
|
.object({
|
|
@@ -63,7 +103,8 @@ const MutationJournalRecordSchema = z
|
|
|
63
103
|
checkoutRoot: CanonicalAbsolutePathSchema.optional(),
|
|
64
104
|
createdAt: TimestampSchema,
|
|
65
105
|
errorCode: z.string().min(1).nullable(),
|
|
66
|
-
|
|
106
|
+
// A rename journals both its source and destination for each request.
|
|
107
|
+
files: z.array(MutationJournalFileSchema).max(100),
|
|
67
108
|
operationId: JobIdSchema,
|
|
68
109
|
revisionId: RevisionIdSchema,
|
|
69
110
|
schemaVersion: z.literal("ast-mcp.mutation-journal.v1"),
|
|
@@ -87,7 +128,16 @@ const MutationJournalRecordSchema = z
|
|
|
87
128
|
updatedAt: TimestampSchema,
|
|
88
129
|
workspaceId: WorkspaceIdSchema,
|
|
89
130
|
})
|
|
90
|
-
.strict()
|
|
131
|
+
.strict()
|
|
132
|
+
.superRefine((record, context) => {
|
|
133
|
+
const limit = record.tool === "file_rename" ? 100 : 50;
|
|
134
|
+
if (record.files.length > limit)
|
|
135
|
+
context.addIssue({
|
|
136
|
+
code: "custom",
|
|
137
|
+
message: `Mutation journal permits at most ${limit} paths for ${record.tool}`,
|
|
138
|
+
path: ["files"],
|
|
139
|
+
});
|
|
140
|
+
});
|
|
91
141
|
|
|
92
142
|
function parseRecord(
|
|
93
143
|
value: unknown,
|
|
@@ -108,8 +158,13 @@ function parseRecord(
|
|
|
108
158
|
!required &&
|
|
109
159
|
(!parsed ||
|
|
110
160
|
typeof parsed !== "object" ||
|
|
111
|
-
(parsed as { schemaVersion?: unknown }).schemaVersion !==
|
|
112
|
-
"ast-mcp.mutation-journal.v1"
|
|
161
|
+
((parsed as { schemaVersion?: unknown }).schemaVersion !==
|
|
162
|
+
"ast-mcp.mutation-journal.v1" &&
|
|
163
|
+
!(
|
|
164
|
+
"operationId" in parsed ||
|
|
165
|
+
"checkoutRoot" in parsed ||
|
|
166
|
+
"files" in parsed
|
|
167
|
+
)))
|
|
113
168
|
)
|
|
114
169
|
return null;
|
|
115
170
|
const result = MutationJournalRecordSchema.safeParse(parsed);
|
|
@@ -118,6 +173,84 @@ function parseRecord(
|
|
|
118
173
|
return result.data;
|
|
119
174
|
}
|
|
120
175
|
|
|
176
|
+
/** Scope shared-store recovery before validating unrelated journal payloads. */
|
|
177
|
+
function recoveryRecord(
|
|
178
|
+
value: unknown,
|
|
179
|
+
workspaceId?: string,
|
|
180
|
+
checkoutRoot?: string,
|
|
181
|
+
): MutationJournalRecord | null {
|
|
182
|
+
if (!checkoutRoot) return parseRecord(value);
|
|
183
|
+
let parsed: unknown;
|
|
184
|
+
try {
|
|
185
|
+
if (typeof value !== "string") throw new Error();
|
|
186
|
+
parsed = JSON.parse(value);
|
|
187
|
+
} catch {
|
|
188
|
+
// Workspace identities change with overlays. A row's workspace_id alone
|
|
189
|
+
// cannot prove that an opaque payload belongs to a different checkout.
|
|
190
|
+
throw new Error("mutation_recovery_scope_unknown");
|
|
191
|
+
}
|
|
192
|
+
if (!parsed || typeof parsed !== "object")
|
|
193
|
+
throw new Error("mutation_journal_malformed");
|
|
194
|
+
const envelope = parsed as Record<string, unknown>;
|
|
195
|
+
if (
|
|
196
|
+
envelope.schemaVersion !== "ast-mcp.mutation-journal.v1" &&
|
|
197
|
+
!(
|
|
198
|
+
typeof envelope.schemaVersion === "string" &&
|
|
199
|
+
envelope.schemaVersion.startsWith("ast-mcp.mutation-journal.")
|
|
200
|
+
) &&
|
|
201
|
+
![
|
|
202
|
+
"file_patch",
|
|
203
|
+
"file_write",
|
|
204
|
+
"file_delete",
|
|
205
|
+
"file_rename",
|
|
206
|
+
"file_chattr",
|
|
207
|
+
].includes(String(envelope.tool)) &&
|
|
208
|
+
// These fields distinguish mutation records from ordinary intelligence
|
|
209
|
+
// jobs, even when both mutation discriminators have been damaged.
|
|
210
|
+
!(
|
|
211
|
+
"operationId" in envelope ||
|
|
212
|
+
"checkoutRoot" in envelope ||
|
|
213
|
+
"files" in envelope
|
|
214
|
+
)
|
|
215
|
+
)
|
|
216
|
+
return null;
|
|
217
|
+
if (
|
|
218
|
+
envelope.workspaceId === workspaceId ||
|
|
219
|
+
envelope.checkoutRoot === checkoutRoot
|
|
220
|
+
)
|
|
221
|
+
return parseRecord(value, true);
|
|
222
|
+
if (CanonicalAbsolutePathSchema.safeParse(envelope.checkoutRoot).success) {
|
|
223
|
+
// A conflicting envelope cannot conceal paths in the current checkout.
|
|
224
|
+
// Unrelated malformed payloads remain outside strict recovery validation.
|
|
225
|
+
if (Array.isArray(envelope.files))
|
|
226
|
+
for (const file of envelope.files) {
|
|
227
|
+
const candidate =
|
|
228
|
+
file && typeof file === "object" ? file.filePath : undefined;
|
|
229
|
+
if (
|
|
230
|
+
typeof candidate === "string" &&
|
|
231
|
+
isAbsolute(candidate) &&
|
|
232
|
+
pathWithin(checkoutRoot, resolve(candidate))
|
|
233
|
+
)
|
|
234
|
+
throw new Error("mutation_recovery_scope_unknown");
|
|
235
|
+
}
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
// Legacy records lack a checkout root. Only a complete set of canonical,
|
|
239
|
+
// non-overlapping paths proves that their recovery is unrelated.
|
|
240
|
+
if (!Array.isArray(envelope.files) || envelope.files.length === 0)
|
|
241
|
+
throw new Error("mutation_recovery_scope_unknown");
|
|
242
|
+
for (const file of envelope.files) {
|
|
243
|
+
const candidate =
|
|
244
|
+
file && typeof file === "object" ? file.filePath : undefined;
|
|
245
|
+
if (
|
|
246
|
+
!CanonicalAbsolutePathSchema.safeParse(candidate).success ||
|
|
247
|
+
pathWithin(checkoutRoot, candidate)
|
|
248
|
+
)
|
|
249
|
+
throw new Error("mutation_recovery_scope_unknown");
|
|
250
|
+
}
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
|
|
121
254
|
export class LanceMutationJournal {
|
|
122
255
|
constructor(
|
|
123
256
|
private readonly store: LanceIntelligenceStore,
|
|
@@ -208,7 +341,7 @@ export class LanceMutationJournal {
|
|
|
208
341
|
: undefined,
|
|
209
342
|
);
|
|
210
343
|
return rows
|
|
211
|
-
.map((row) =>
|
|
344
|
+
.map((row) => recoveryRecord(row.payload_json, workspaceId, checkoutRoot))
|
|
212
345
|
.filter((record): record is MutationJournalRecord => Boolean(record))
|
|
213
346
|
.filter(
|
|
214
347
|
(record) =>
|
|
@@ -218,20 +351,6 @@ export class LanceMutationJournal {
|
|
|
218
351
|
(record.state === "failed" &&
|
|
219
352
|
record.files.some((file) => file.committedSha256 !== null)),
|
|
220
353
|
)
|
|
221
|
-
.filter((record) => {
|
|
222
|
-
if (
|
|
223
|
-
!checkoutRoot ||
|
|
224
|
-
record.workspaceId === workspaceId ||
|
|
225
|
-
record.checkoutRoot === checkoutRoot
|
|
226
|
-
)
|
|
227
|
-
return true;
|
|
228
|
-
if (
|
|
229
|
-
!record.checkoutRoot &&
|
|
230
|
-
record.files.some((file) => pathWithin(checkoutRoot, file.filePath))
|
|
231
|
-
)
|
|
232
|
-
throw new Error("mutation_recovery_scope_unknown");
|
|
233
|
-
return false;
|
|
234
|
-
})
|
|
235
354
|
.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
|
|
236
355
|
}
|
|
237
356
|
|
|
@@ -293,6 +412,8 @@ export class LanceMutationJournal {
|
|
|
293
412
|
}
|
|
294
413
|
|
|
295
414
|
private async write(record: MutationJournalRecord): Promise<void> {
|
|
415
|
+
// Reject invalid records before they can poison durable recovery.
|
|
416
|
+
MutationJournalRecordSchema.parse(record);
|
|
296
417
|
await this.store.putRows(
|
|
297
418
|
"jobs",
|
|
298
419
|
[
|
|
@@ -183,13 +183,67 @@ export async function mutationLockPath(filePath: string): Promise<string> {
|
|
|
183
183
|
return path.join(directory, name);
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
+
interface CoordinationDiscovery {
|
|
187
|
+
stats: Map<string, Promise<Awaited<ReturnType<typeof lstat>>>>;
|
|
188
|
+
metadata: Map<string, Promise<string>>;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function coordinationDiscovery(): CoordinationDiscovery {
|
|
192
|
+
return { stats: new Map(), metadata: new Map() };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function discoveryStat(discovery: CoordinationDiscovery, target: string) {
|
|
196
|
+
let pending = discovery.stats.get(target);
|
|
197
|
+
if (!pending) {
|
|
198
|
+
pending = lstat(target);
|
|
199
|
+
discovery.stats.set(target, pending);
|
|
200
|
+
}
|
|
201
|
+
return pending;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function gitMetadataPointer(
|
|
205
|
+
directory: string,
|
|
206
|
+
marker: string,
|
|
207
|
+
): Promise<string> {
|
|
208
|
+
const handle = await open(marker, "r");
|
|
209
|
+
try {
|
|
210
|
+
const bytes = Buffer.alloc(4097);
|
|
211
|
+
const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
|
|
212
|
+
const match = bytes
|
|
213
|
+
.subarray(0, bytesRead)
|
|
214
|
+
.toString("utf8")
|
|
215
|
+
.trim()
|
|
216
|
+
.match(/^gitdir: (.+)$/);
|
|
217
|
+
if (bytesRead > 4096 || !match)
|
|
218
|
+
throw new Error("Invalid Git metadata pointer");
|
|
219
|
+
const metadata = await canonicalizePath(path.resolve(directory, match[1]!));
|
|
220
|
+
if (!(await lstat(metadata)).isDirectory())
|
|
221
|
+
throw new Error("Git metadata is not a directory");
|
|
222
|
+
return metadata;
|
|
223
|
+
} catch (cause) {
|
|
224
|
+
throw new Error("Git metadata pointer is unavailable or invalid", {
|
|
225
|
+
cause,
|
|
226
|
+
});
|
|
227
|
+
} finally {
|
|
228
|
+
await handle.close();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
186
232
|
export async function mutationSharedDatabasePath(
|
|
187
233
|
filePath: string,
|
|
234
|
+
): Promise<string> {
|
|
235
|
+
return discoverSharedDatabasePath(filePath, coordinationDiscovery());
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function discoverSharedDatabasePath(
|
|
239
|
+
filePath: string,
|
|
240
|
+
discovery: CoordinationDiscovery,
|
|
188
241
|
): Promise<string> {
|
|
189
242
|
const canonical = await canonicalizePath(filePath);
|
|
190
243
|
let directory = path.dirname(canonical);
|
|
191
244
|
try {
|
|
192
|
-
if ((await
|
|
245
|
+
if ((await discoveryStat(discovery, canonical)).isDirectory())
|
|
246
|
+
directory = canonical;
|
|
193
247
|
} catch (error) {
|
|
194
248
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
195
249
|
}
|
|
@@ -198,46 +252,33 @@ export async function mutationSharedDatabasePath(
|
|
|
198
252
|
let metadata: string | undefined;
|
|
199
253
|
for (let depth = 0; depth < 256; depth++) {
|
|
200
254
|
try {
|
|
201
|
-
if ((await
|
|
255
|
+
if ((await discoveryStat(discovery, directory)).isDirectory())
|
|
256
|
+
fallback ??= directory;
|
|
202
257
|
const marker = path.join(directory, ".git");
|
|
203
258
|
let git;
|
|
204
259
|
try {
|
|
205
|
-
git = await
|
|
260
|
+
git = await discoveryStat(discovery, marker);
|
|
206
261
|
} catch (error) {
|
|
207
262
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
208
263
|
}
|
|
209
264
|
if (git) {
|
|
210
265
|
if (git.isDirectory()) metadata = marker;
|
|
211
266
|
else if (git.isFile() && git.size <= 4096) {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
const match = bytes
|
|
217
|
-
.subarray(0, bytesRead)
|
|
218
|
-
.toString("utf8")
|
|
219
|
-
.trim()
|
|
220
|
-
.match(/^gitdir: (.+)$/);
|
|
221
|
-
if (bytesRead > 4096 || !match)
|
|
222
|
-
throw new Error("Invalid Git metadata pointer");
|
|
223
|
-
metadata = await canonicalizePath(
|
|
224
|
-
path.resolve(directory, match[1]!),
|
|
225
|
-
);
|
|
226
|
-
if (!(await lstat(metadata)).isDirectory())
|
|
227
|
-
throw new Error("Git metadata is not a directory");
|
|
228
|
-
} catch (cause) {
|
|
229
|
-
throw new Error("Git metadata pointer is unavailable or invalid", {
|
|
230
|
-
cause,
|
|
231
|
-
});
|
|
232
|
-
} finally {
|
|
233
|
-
await handle.close();
|
|
267
|
+
let pending = discovery.metadata.get(marker);
|
|
268
|
+
if (!pending) {
|
|
269
|
+
pending = gitMetadataPointer(directory, marker);
|
|
270
|
+
discovery.metadata.set(marker, pending);
|
|
234
271
|
}
|
|
272
|
+
metadata = await pending;
|
|
235
273
|
} else throw new Error("Unsafe Git metadata marker");
|
|
236
274
|
break;
|
|
237
275
|
}
|
|
238
276
|
if (!configured) {
|
|
239
277
|
try {
|
|
240
|
-
const config = await
|
|
278
|
+
const config = await discoveryStat(
|
|
279
|
+
discovery,
|
|
280
|
+
path.join(directory, "ast-mcp.toml"),
|
|
281
|
+
);
|
|
241
282
|
if (config.isFile()) configured = directory;
|
|
242
283
|
} catch (error) {
|
|
243
284
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
@@ -782,11 +823,31 @@ export async function withFencedFileLock<Result>(
|
|
|
782
823
|
filePath: string,
|
|
783
824
|
operation: (lease: FileLockLease) => Promise<Result>,
|
|
784
825
|
options: FileLockOptions = {},
|
|
826
|
+
): Promise<Result> {
|
|
827
|
+
return withFencedFileLockDiscovery(filePath, operation, options);
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
async function withFencedFileLockDiscovery<Result>(
|
|
831
|
+
filePath: string,
|
|
832
|
+
operation: (lease: FileLockLease) => Promise<Result>,
|
|
833
|
+
options: FileLockOptions,
|
|
834
|
+
discovery?: CoordinationDiscovery,
|
|
785
835
|
): Promise<Result> {
|
|
786
836
|
const canonical = canonicalizePathSync(filePath);
|
|
787
837
|
const identity = lockPathIdentity(canonical);
|
|
788
838
|
return withQueue(identity, options, async () => {
|
|
789
|
-
const lease = await acquireFileLock(
|
|
839
|
+
const lease = await acquireFileLock(
|
|
840
|
+
canonical,
|
|
841
|
+
discovery && !options.sharedDatabasePath
|
|
842
|
+
? {
|
|
843
|
+
...options,
|
|
844
|
+
sharedDatabasePath: await discoverSharedDatabasePath(
|
|
845
|
+
canonical,
|
|
846
|
+
discovery,
|
|
847
|
+
),
|
|
848
|
+
}
|
|
849
|
+
: options,
|
|
850
|
+
);
|
|
790
851
|
const heartbeatMs = Math.max(
|
|
791
852
|
25,
|
|
792
853
|
Math.floor((options.leaseMs ?? DEFAULT_LEASE_MS) / 3),
|
|
@@ -818,12 +879,14 @@ export async function withFencedFileLocks<Result>(
|
|
|
818
879
|
const sorted = [...canonicalPaths.entries()]
|
|
819
880
|
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
820
881
|
.map(([, canonical]) => canonical);
|
|
882
|
+
// Cache observations only for this acquisition batch; later calls revalidate markers.
|
|
883
|
+
const discovery = coordinationDiscovery();
|
|
821
884
|
const leases: FileLockLease[] = [];
|
|
822
885
|
const acquire = async (index: number): Promise<Result> => {
|
|
823
886
|
if (index === sorted.length) return operation(leases);
|
|
824
887
|
const filePath = sorted[index];
|
|
825
888
|
if (!filePath) return operation(leases);
|
|
826
|
-
return
|
|
889
|
+
return withFencedFileLockDiscovery(
|
|
827
890
|
filePath,
|
|
828
891
|
async (lease) => {
|
|
829
892
|
leases.push(lease);
|
|
@@ -834,6 +897,7 @@ export async function withFencedFileLocks<Result>(
|
|
|
834
897
|
}
|
|
835
898
|
},
|
|
836
899
|
options,
|
|
900
|
+
discovery,
|
|
837
901
|
);
|
|
838
902
|
};
|
|
839
903
|
return acquire(0);
|