cwtools-shared 0.2.9 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/debug/zz.d.ts +1 -0
  2. package/dist/debug/zz.js +12 -0
  3. package/dist/generated/mcpTools.d.ts +49 -4
  4. package/dist/generated/mcpTools.js +94 -49
  5. package/dist/generated/workshopDetection.d.ts +22 -0
  6. package/dist/generated/workshopDetection.js +50 -0
  7. package/dist/generated/workspaceDetectionProfiles.d.ts +2 -0
  8. package/dist/generated/workspaceDetectionProfiles.js +84 -0
  9. package/dist/generated/workspaceGameDetection.d.ts +39 -0
  10. package/dist/generated/workspaceGameDetection.js +424 -0
  11. package/dist/host/capabilities.d.ts +39 -0
  12. package/dist/host/capabilities.js +128 -0
  13. package/dist/host/diagnostics.d.ts +8 -1
  14. package/dist/host/filesystem.d.ts +2 -0
  15. package/dist/host/hostServices.d.ts +47 -0
  16. package/dist/host/indexing.d.ts +3 -0
  17. package/dist/host/lsp.d.ts +9 -0
  18. package/dist/host/lsp.js +27 -0
  19. package/dist/host/readiness.js +10 -0
  20. package/dist/host/vanillaCache.js +1 -1
  21. package/dist/index.d.ts +16 -1
  22. package/dist/index.js +22 -1
  23. package/dist/knowledge/interfaceKnowledge.d.ts +8 -0
  24. package/dist/knowledge/interfaceKnowledge.js +222 -0
  25. package/dist/project/descriptor.d.ts +12 -0
  26. package/dist/project/descriptor.js +69 -0
  27. package/dist/project/init.d.ts +11 -0
  28. package/dist/project/init.js +356 -0
  29. package/dist/project/knowledge.d.ts +6 -0
  30. package/dist/project/knowledge.js +20 -8
  31. package/dist/project/profile.d.ts +62 -7
  32. package/dist/project/profile.js +4 -3
  33. package/dist/project/profileBuilder.d.ts +31 -0
  34. package/dist/project/profileBuilder.js +989 -0
  35. package/dist/tools/archetypeArtifacts.d.ts +29 -0
  36. package/dist/tools/archetypeArtifacts.js +136 -0
  37. package/dist/tools/archetypeSlots.d.ts +32 -0
  38. package/dist/tools/archetypeSlots.js +257 -0
  39. package/dist/tools/archetypeTools.d.ts +4 -0
  40. package/dist/tools/archetypeTools.js +118 -0
  41. package/dist/tools/callHandler.d.ts +10 -0
  42. package/dist/tools/callHandler.js +76 -0
  43. package/dist/tools/catalog.d.ts +4094 -0
  44. package/dist/tools/catalog.js +5031 -0
  45. package/dist/tools/domainTools.d.ts +8 -0
  46. package/dist/tools/domainTools.js +222 -0
  47. package/dist/tools/mcpSchema.d.ts +20 -3
  48. package/dist/tools/mcpSchema.js +55 -7
  49. package/dist/tools/mediaWrites.d.ts +52 -0
  50. package/dist/tools/mediaWrites.js +322 -0
  51. package/dist/tools/names.d.ts +4 -4
  52. package/dist/tools/names.js +14 -1
  53. package/dist/tools/pdxWriteCore.d.ts +51 -0
  54. package/dist/tools/pdxWriteCore.js +628 -0
  55. package/dist/tools/pdxWrites.d.ts +88 -0
  56. package/dist/tools/pdxWrites.js +629 -0
  57. package/dist/tools/registry.d.ts +1 -0
  58. package/dist/tools/scopeBridge.d.ts +36 -0
  59. package/dist/tools/scopeBridge.js +173 -0
  60. package/dist/tools/symbols.js +22 -2
  61. package/dist/tools/targetingWeights.d.ts +206 -0
  62. package/dist/tools/targetingWeights.js +350 -0
  63. package/dist/tools/toolHandlers.d.ts +5 -1
  64. package/dist/tools/toolHandlers.js +146 -33
  65. package/package.json +1 -1
@@ -0,0 +1,629 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CANDIDATE_TRANSACTION_FIELDS = exports.TYPED_PDX_WRITE_FIELDS = void 0;
37
+ exports.typedPdxWriteWithHost = typedPdxWriteWithHost;
38
+ exports.candidateTransactionWithHost = candidateTransactionWithHost;
39
+ const crypto_1 = require("crypto");
40
+ const path = __importStar(require("path"));
41
+ const lsp_1 = require("../host/lsp");
42
+ const paths_1 = require("../safety/paths");
43
+ const writes_1 = require("../safety/writes");
44
+ const pdxWriteCore_1 = require("./pdxWriteCore");
45
+ const SOURCE = 'cwtools-domain-writes';
46
+ const MAX_FILE_CHARS = 2000000;
47
+ const MAX_CANDIDATE_FILES = 100;
48
+ const MAX_CANDIDATE_BYTES = 5 * 1024 * 1024;
49
+ const VALIDATION_TIMEOUT_MS = 15000;
50
+ const LOCK_TIMEOUT_MS = 30000;
51
+ const FRESHNESS_TIMEOUT_MS = 8000;
52
+ const FRESHNESS_POLL_MS = 100;
53
+ const DIAGNOSTIC_LIMIT = 2000;
54
+ function asRecordValue(value) {
55
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
56
+ }
57
+ function errorText(error) {
58
+ return error instanceof Error ? error.message : String(error);
59
+ }
60
+ function isAbortLike(error) {
61
+ const name = error?.name;
62
+ return name === 'AbortError' || name === 'TimeoutError';
63
+ }
64
+ function sha256Text(text) {
65
+ return (0, crypto_1.createHash)('sha256').update(text, 'utf8').digest('hex');
66
+ }
67
+ function toFileUri(filePath) {
68
+ const slashed = path.resolve(filePath).replace(/\\/g, '/');
69
+ const prefixed = slashed.startsWith('/') ? slashed : '/' + slashed;
70
+ return 'file://' + encodeURI(prefixed).replace(/#/g, '%23');
71
+ }
72
+ function invalidArguments(message) {
73
+ return { ok: false, status: 'error', source: SOURCE, error: { code: 'invalid_arguments', message } };
74
+ }
75
+ function failure(code, message) {
76
+ return { ok: false, status: 'error', source: SOURCE, error: { code, message } };
77
+ }
78
+ function success(data) {
79
+ return { ok: true, status: 'success', source: SOURCE, data };
80
+ }
81
+ /** Resolve a caller-supplied path inside the workspace, rejecting traversal. */
82
+ function resolveInsideWorkspace(host, inputPath) {
83
+ const trimmed = typeof inputPath === 'string' ? inputPath.trim() : '';
84
+ if (!trimmed)
85
+ return { ok: false, message: 'A file path is required.' };
86
+ const root = (0, paths_1.normalizeWorkspaceRoot)(host.workspaceRoot);
87
+ const resolved = path.resolve(root, trimmed);
88
+ if (!(0, paths_1.isPathInsideOrEqual)(root, resolved)) {
89
+ return { ok: false, message: "Path '" + trimmed + "' is outside the workspace root." };
90
+ }
91
+ return { ok: true, resolvedPath: resolved, relativePath: path.relative(root, resolved).replace(/\\/g, '/') };
92
+ }
93
+ async function readDiskText(host, filePath) {
94
+ const read = await host.filesystem.readTextFile(filePath);
95
+ if (!read.exists)
96
+ return '';
97
+ return read.content.charCodeAt(0) === 0xfeff ? read.content.slice(1) : read.content;
98
+ }
99
+ /**
100
+ * Serialises commits per host. Sorted lock keys are used so two transactions on
101
+ * the same files cannot deadlock by acquiring them in different orders.
102
+ */
103
+ class WriteLockQueue {
104
+ constructor() {
105
+ this.tail = Promise.resolve();
106
+ this.held = new Set();
107
+ }
108
+ static key(filePath) {
109
+ return process.platform === 'win32' ? filePath.toLowerCase() : filePath;
110
+ }
111
+ async run(keys, timeoutMs, work) {
112
+ const ordered = [...new Set(keys)].sort();
113
+ const deadline = Date.now() + timeoutMs;
114
+ while (ordered.some(key => this.held.has(key))) {
115
+ if (Date.now() > deadline)
116
+ throw new Error('Candidate commit timed out waiting for file locks.');
117
+ await new Promise(resolve => setTimeout(resolve, 10));
118
+ }
119
+ const previous = this.tail;
120
+ let release;
121
+ this.tail = new Promise(resolve => { release = resolve; });
122
+ await previous;
123
+ for (const key of ordered)
124
+ this.held.add(key);
125
+ try {
126
+ return await work();
127
+ }
128
+ finally {
129
+ for (const key of ordered)
130
+ this.held.delete(key);
131
+ release();
132
+ }
133
+ }
134
+ }
135
+ /** One queue and one live transaction per host, mirroring the single candidate overlay. */
136
+ const hostLockQueues = new WeakMap();
137
+ const hostTransactions = new WeakMap();
138
+ function lockQueueFor(host) {
139
+ let queue = hostLockQueues.get(host);
140
+ if (!queue) {
141
+ queue = new WriteLockQueue();
142
+ hostLockQueues.set(host, queue);
143
+ }
144
+ return queue;
145
+ }
146
+ class CandidateTransaction {
147
+ constructor() {
148
+ this._state = 'discarded';
149
+ this.staged = new Map();
150
+ this.original = new Map();
151
+ this.validatedOk = false;
152
+ this.stagedBytes = 0;
153
+ }
154
+ get state() { return this._state; }
155
+ get id() { return this._id; }
156
+ get bytes() { return this.stagedBytes; }
157
+ get canValidate() { return this._state === 'active'; }
158
+ get files() { return [...this.staged.values()].sort((a, b) => a.path.localeCompare(b.path)); }
159
+ get paths() { return this.files.map(file => file.path); }
160
+ begin() {
161
+ if (this._state === 'active' || this._state === 'validated')
162
+ throw new Error('A transaction is already active');
163
+ this.staged.clear();
164
+ this.original.clear();
165
+ this.stagedBytes = 0;
166
+ this.validatedOk = false;
167
+ this._id = (0, crypto_1.randomUUID)();
168
+ this._state = 'active';
169
+ return this._id;
170
+ }
171
+ stage(filePath, content, baseHash) {
172
+ if (this._state !== 'active')
173
+ throw new Error('Cannot stage a transaction in ' + this._state + ' state');
174
+ const bytes = Buffer.byteLength(content, 'utf8');
175
+ const previous = this.staged.get(filePath);
176
+ const nextBytes = this.stagedBytes - (previous?.bytes ?? 0) + bytes;
177
+ if (!previous && this.staged.size >= MAX_CANDIDATE_FILES)
178
+ throw new Error('Transaction file limit exceeded');
179
+ if (nextBytes > MAX_CANDIDATE_BYTES)
180
+ throw new Error('Transaction byte limit exceeded');
181
+ if (baseHash !== undefined && !/^[a-f0-9]{64}$/i.test(baseHash))
182
+ throw new Error('baseHash must be a SHA-256 hex digest');
183
+ const entry = { path: filePath, content, contentHash: sha256Text(content), bytes, baseHash: previous?.baseHash ?? baseHash };
184
+ this.staged.set(filePath, entry);
185
+ this.stagedBytes = nextBytes;
186
+ return entry;
187
+ }
188
+ fingerprint() {
189
+ return sha256Text(this.files.map(file => file.path + '|' + file.contentHash).join('|'));
190
+ }
191
+ validate(ok) {
192
+ if (this._state !== 'active')
193
+ throw new Error('Cannot validate a transaction in ' + this._state + ' state');
194
+ this.validatedOk = ok;
195
+ this._state = 'validated';
196
+ }
197
+ discard() {
198
+ if (this._state === 'committed' || this._state === 'discarded')
199
+ return;
200
+ this.staged.clear();
201
+ this.original.clear();
202
+ this.stagedBytes = 0;
203
+ this.validatedOk = false;
204
+ this._state = 'discarded';
205
+ }
206
+ settle(state) {
207
+ this._state = state;
208
+ }
209
+ async commit(host, baselines, deltas, signal) {
210
+ const files = this.files;
211
+ const paths = files.map(file => file.path);
212
+ const noRollback = { attempted: false, succeeded: true, paths: [], errors: [] };
213
+ if (this._state !== 'validated')
214
+ throw new Error('Transaction must be validated before commit');
215
+ // An empty transaction is a no-op, not a drift risk: post-commit freshness
216
+ // would compare a file with its own baseline and could never succeed.
217
+ if (files.length === 0) {
218
+ this._state = 'committed';
219
+ return { committed: true, state: this._state, files: paths, rollback: noRollback };
220
+ }
221
+ if (!this.validatedOk) {
222
+ this._state = 'discarded';
223
+ return { committed: false, state: this._state, files: paths, rollback: noRollback, error: 'Validation failed before commit' };
224
+ }
225
+ const written = [];
226
+ try {
227
+ for (const file of files) {
228
+ (0, lsp_1.throwIfAborted)(signal);
229
+ const current = await readDiskText(host, file.path);
230
+ if (file.baseHash !== undefined && sha256Text(current) !== file.baseHash) {
231
+ const drift = 'External disk drift detected: ' + file.path;
232
+ this._state = 'discarded';
233
+ return { committed: false, state: this._state, files: paths, rollback: noRollback, error: drift };
234
+ }
235
+ this.original.set(file.path, { content: current, existed: current.length > 0 || file.baseHash !== undefined });
236
+ }
237
+ for (const file of files) {
238
+ (0, lsp_1.throwIfAborted)(signal);
239
+ // Record before writing: a partially written file must still roll back.
240
+ written.push(file);
241
+ await host.filesystem.writeTextFile(file.path, file.content);
242
+ }
243
+ const validation = await this.validateOnDisk(host, files, baselines, deltas, signal);
244
+ if (!validation.ok) {
245
+ const rollback = await this.rollback(host, written);
246
+ this._state = rollback.succeeded ? 'discarded' : 'active';
247
+ return { committed: false, state: this._state, files: paths, rollback, error: validation.error };
248
+ }
249
+ this._state = 'committed';
250
+ return { committed: true, state: this._state, files: paths, rollback: noRollback };
251
+ }
252
+ catch (error) {
253
+ const rollback = await this.rollback(host, written);
254
+ this._state = rollback.succeeded ? 'discarded' : 'active';
255
+ if (isAbortLike(error))
256
+ throw error;
257
+ return { committed: false, state: this._state, files: paths, rollback, error: errorText(error) };
258
+ }
259
+ }
260
+ async rollback(host, written) {
261
+ const errors = [];
262
+ for (const file of [...written].reverse()) {
263
+ try {
264
+ const original = this.original.get(file.path);
265
+ if (original?.existed === false) {
266
+ // Only the file this transaction created is removed, never a directory.
267
+ const deletable = host.filesystem;
268
+ if (deletable.deleteFile)
269
+ await deletable.deleteFile(file.path);
270
+ else
271
+ await host.filesystem.writeTextFile(file.path, '');
272
+ }
273
+ else {
274
+ await host.filesystem.writeTextFile(file.path, original?.content ?? '');
275
+ }
276
+ }
277
+ catch (error) {
278
+ errors.push({ path: file.path, error: errorText(error) });
279
+ }
280
+ }
281
+ return { attempted: written.length > 0, succeeded: errors.length === 0, paths: written.map(file => file.path), errors };
282
+ }
283
+ async validateOnDisk(host, files, baselines, deltas, signal) {
284
+ await requestRevalidate(host, files.map(file => file.path), signal);
285
+ let ok = true;
286
+ let error;
287
+ for (const file of files) {
288
+ const baseline = baselines.get(file.path) ?? { snapshot: [], epoch: 0 };
289
+ const current = await waitForFreshDiagnostics(host, file.path, baseline.epoch, signal);
290
+ const delta = diffSnapshots(baseline.snapshot, current.snapshot, current.fresh);
291
+ deltas[file.path] = delta;
292
+ if (!delta.comparable || delta.added.some(entry => entry.severity === 'error')) {
293
+ ok = false;
294
+ error ?? (error = 'Candidate commit introduced errors or diagnostics were not fresh.');
295
+ }
296
+ }
297
+ return { ok, error };
298
+ }
299
+ }
300
+ function activeTransaction(host) {
301
+ const transaction = hostTransactions.get(host);
302
+ return transaction && (transaction.state === 'active' || transaction.state === 'validated') ? transaction : undefined;
303
+ }
304
+ function transactionFor(host) {
305
+ let transaction = hostTransactions.get(host);
306
+ if (!transaction) {
307
+ transaction = new CandidateTransaction();
308
+ hostTransactions.set(host, transaction);
309
+ }
310
+ return transaction;
311
+ }
312
+ // ─── diagnostics and overlay validation ────────────────────────────────────
313
+ function snapshotDiagnostics(entries) {
314
+ return entries.map(entry => ({
315
+ code: entry.code ?? '',
316
+ severity: entry.severity,
317
+ message: entry.message,
318
+ line: entry.line ?? 0,
319
+ column: entry.column ?? 0,
320
+ }));
321
+ }
322
+ function diagnosticKey(entry) {
323
+ return [entry.code, entry.severity, entry.line, entry.column, entry.message].join('\u0000');
324
+ }
325
+ function diffSnapshots(baseline, current, comparable) {
326
+ const before = new Set(baseline.map(diagnosticKey));
327
+ const after = new Set(current.map(diagnosticKey));
328
+ return {
329
+ comparable,
330
+ added: current.filter(entry => !before.has(diagnosticKey(entry))),
331
+ removed: baseline.filter(entry => !after.has(diagnosticKey(entry))),
332
+ };
333
+ }
334
+ function epochOf(result) {
335
+ return result.freshness?.epoch ?? 0;
336
+ }
337
+ async function waitForFreshDiagnostics(host, filePath, baselineEpoch, signal) {
338
+ const deadline = Date.now() + FRESHNESS_TIMEOUT_MS;
339
+ let current = await host.diagnostics.getDiagnostics({ file: filePath, limit: DIAGNOSTIC_LIMIT }, signal ? { signal } : undefined);
340
+ while ((current.status !== 'fresh' || epochOf(current) <= baselineEpoch) && Date.now() < deadline) {
341
+ (0, lsp_1.throwIfAborted)(signal);
342
+ await new Promise(resolve => setTimeout(resolve, FRESHNESS_POLL_MS));
343
+ current = await host.diagnostics.getDiagnostics({ file: filePath, limit: DIAGNOSTIC_LIMIT }, signal ? { signal } : undefined);
344
+ }
345
+ return {
346
+ snapshot: snapshotDiagnostics(current.diagnostics),
347
+ fresh: current.status === 'fresh' && epochOf(current) > baselineEpoch,
348
+ };
349
+ }
350
+ async function requestRevalidate(host, files, signal) {
351
+ if (files.length === 0)
352
+ return;
353
+ // Revalidation is best-effort: the freshness wait below decides the outcome.
354
+ await host.lsp.executeCommand('cwtools.ai.revalidateFiles', [files.map(toFileUri)], signal ? { signal } : undefined)
355
+ .catch(() => undefined);
356
+ }
357
+ async function validateOverlayOnHost(host, files, signal) {
358
+ if (files.length > MAX_CANDIDATE_FILES)
359
+ return { infrastructureError: 'Overlay validation request exceeds the file limit.' };
360
+ // A local controller carries both the caller's abort and the request timeout,
361
+ // so a hung backend cannot strand the transaction.
362
+ const controller = new AbortController();
363
+ const forward = () => controller.abort();
364
+ signal?.addEventListener('abort', forward, { once: true });
365
+ const timer = setTimeout(() => controller.abort(), VALIDATION_TIMEOUT_MS);
366
+ let response;
367
+ try {
368
+ response = await host.lsp.executeCommand('cwtools.ai.validateOverlay', [{ files: files.map(file => ({ uri: toFileUri(file.path), content: file.content, baseHash: file.baseHash })) }], { signal: controller.signal });
369
+ }
370
+ catch (error) {
371
+ if (signal?.aborted)
372
+ throw error;
373
+ return { infrastructureError: isAbortLike(error) ? 'Overlay validation timed out after 15 seconds.' : errorText(error) };
374
+ }
375
+ finally {
376
+ clearTimeout(timer);
377
+ signal?.removeEventListener('abort', forward);
378
+ }
379
+ const record = asRecordValue(response);
380
+ if (record.status === 'unavailable' || asRecordValue(record.error).code === 'lsp_unavailable') {
381
+ return { infrastructureError: 'Overlay validation is not available in this host.' };
382
+ }
383
+ if (record.ok !== true || !Array.isArray(record.files)) {
384
+ return { infrastructureError: typeof record.error === 'string' ? record.error : 'Overlay validation returned an invalid response.' };
385
+ }
386
+ if (record.files.length !== files.length) {
387
+ return { infrastructureError: 'Overlay validation returned ' + record.files.length + ' file result(s) for ' + files.length + ' candidate(s).' };
388
+ }
389
+ const requestedByUri = new Map(files.map(file => [toFileUri(file.path), file]));
390
+ const returned = new Set();
391
+ const normalized = [];
392
+ for (const item of record.files) {
393
+ const entry = asRecordValue(item);
394
+ const uri = typeof entry.uri === 'string' ? entry.uri : undefined;
395
+ if (!uri || !requestedByUri.has(uri) || returned.has(uri)) {
396
+ return { infrastructureError: 'Overlay validation returned an unknown, missing, or duplicate URI: ' + (uri ?? '<missing>') + '.' };
397
+ }
398
+ returned.add(uri);
399
+ if (!Array.isArray(entry.diagnostics))
400
+ return { infrastructureError: 'Overlay validation omitted diagnostics for ' + uri + '.' };
401
+ const diagnostics = [];
402
+ for (const raw of entry.diagnostics) {
403
+ const diagnostic = asRecordValue(raw);
404
+ if (diagnostic.severity !== 'error' && diagnostic.severity !== 'warning' && diagnostic.severity !== 'info' && diagnostic.severity !== 'hint') {
405
+ return { infrastructureError: 'Overlay validation returned an unknown diagnostic severity for ' + uri + '.' };
406
+ }
407
+ diagnostics.push({
408
+ code: typeof diagnostic.code === 'string' ? diagnostic.code : '',
409
+ severity: diagnostic.severity,
410
+ message: typeof diagnostic.message === 'string' ? diagnostic.message : '',
411
+ line: typeof diagnostic.line === 'number' ? diagnostic.line : 0,
412
+ column: typeof diagnostic.column === 'number' ? diagnostic.column : 0,
413
+ });
414
+ }
415
+ normalized.push({
416
+ uri,
417
+ ok: entry.ok === true,
418
+ contentHash: typeof entry.contentHash === 'string' ? entry.contentHash : undefined,
419
+ diagnostics,
420
+ error: typeof entry.error === 'string' ? entry.error : undefined,
421
+ });
422
+ }
423
+ if (returned.size !== requestedByUri.size)
424
+ return { infrastructureError: 'Overlay validation did not cover every candidate file.' };
425
+ return {
426
+ validationLevel: typeof record.validationLevel === 'string' ? record.validationLevel : undefined,
427
+ limitations: Array.isArray(record.limitations)
428
+ ? record.limitations.filter((value) => typeof value === 'string')
429
+ : undefined,
430
+ files: normalized,
431
+ };
432
+ }
433
+ // ─── typed_pdx_write ───────────────────────────────────────────────────────
434
+ exports.TYPED_PDX_WRITE_FIELDS = ['filePath', 'operation', 'expectedHash', 'mode', 'transactionId'];
435
+ async function typedPdxWriteWithHost(host, args, context) {
436
+ const denied = (0, writes_1.ensureToolWriteAllowed)(host, 'typed_pdx_write');
437
+ if (denied)
438
+ return denied;
439
+ (0, lsp_1.throwIfAborted)(context?.signal);
440
+ const extra = Object.keys(args).filter(key => !exports.TYPED_PDX_WRITE_FIELDS.includes(key));
441
+ if (extra.length > 0)
442
+ return invalidArguments('typed_pdx_write contains unsupported field(s): ' + extra.join(', '));
443
+ const operation = asRecordValue(args.operation);
444
+ if (Object.keys(operation).length === 0)
445
+ return invalidArguments('typed_pdx_write requires an operation record.');
446
+ const mode = args.mode === undefined ? 'preview' : args.mode;
447
+ if (mode !== 'preview' && mode !== 'stage')
448
+ return invalidArguments('mode must be "preview" or "stage".');
449
+ if (args.expectedHash !== undefined && (typeof args.expectedHash !== 'string' || !/^[a-f0-9]{64}$/i.test(args.expectedHash))) {
450
+ return invalidArguments('expectedHash must be a SHA-256 hex digest.');
451
+ }
452
+ const resolution = resolveInsideWorkspace(host, args.filePath);
453
+ if (!resolution.ok)
454
+ return failure('outside_workspace', resolution.message);
455
+ if (!resolution.resolvedPath.toLowerCase().endsWith('.txt')) {
456
+ return invalidArguments('typed_pdx_write only supports .txt files.');
457
+ }
458
+ let text;
459
+ try {
460
+ const read = await host.filesystem.readTextFile(resolution.resolvedPath);
461
+ if (!read.exists) {
462
+ // The operation vocabulary edits an existing document; it never invents one.
463
+ return failure('file_not_found', 'typed_pdx_write edits an existing .txt file and never creates one: ' + resolution.relativePath);
464
+ }
465
+ if (read.content.length > MAX_FILE_CHARS)
466
+ return failure('file_oversized', 'File exceeds the ' + MAX_FILE_CHARS + ' character bound.');
467
+ text = read.content.charCodeAt(0) === 0xfeff ? read.content.slice(1) : read.content;
468
+ }
469
+ catch (error) {
470
+ return failure('read_failed', errorText(error));
471
+ }
472
+ let candidate;
473
+ try {
474
+ candidate = (0, pdxWriteCore_1.buildTypedPdxCandidate)(resolution.resolvedPath, text, operation, typeof args.expectedHash === 'string' ? args.expectedHash : undefined);
475
+ }
476
+ catch (error) {
477
+ return invalidArguments(errorText(error));
478
+ }
479
+ if (mode === 'preview') {
480
+ return success({ success: true, mode: 'preview', candidate });
481
+ }
482
+ const transaction = activeTransaction(host);
483
+ if (!transaction) {
484
+ return failure('transaction_inactive', 'Candidate transaction is not active; call candidate_transaction with action "begin" first.');
485
+ }
486
+ if (typeof args.transactionId !== 'string' || args.transactionId !== transaction.id) {
487
+ return failure('transaction_mismatch', 'transactionId does not match the active candidate transaction (' + (transaction.id ?? 'none') + ').');
488
+ }
489
+ if (!transaction.canValidate) {
490
+ return failure('transaction_inactive', 'Candidate transaction is not active.');
491
+ }
492
+ try {
493
+ transaction.stage(resolution.resolvedPath, candidate.content, candidate.beforeHash);
494
+ }
495
+ catch (error) {
496
+ return failure('stage_failed', errorText(error));
497
+ }
498
+ return success({
499
+ success: true,
500
+ mode: 'stage',
501
+ transactionId: transaction.id,
502
+ candidate,
503
+ message: candidate.summary,
504
+ });
505
+ }
506
+ // ─── candidate_transaction ─────────────────────────────────────────────────
507
+ exports.CANDIDATE_TRANSACTION_FIELDS = ['action', 'transactionId', 'validationPassed'];
508
+ async function candidateTransactionWithHost(host, args, context) {
509
+ const denied = (0, writes_1.ensureToolWriteAllowed)(host, 'candidate_transaction');
510
+ if (denied)
511
+ return denied;
512
+ (0, lsp_1.throwIfAborted)(context?.signal);
513
+ const extra = Object.keys(args).filter(key => !exports.CANDIDATE_TRANSACTION_FIELDS.includes(key));
514
+ if (extra.length > 0)
515
+ return invalidArguments('candidate_transaction contains unsupported field(s): ' + extra.join(', '));
516
+ const action = args.action;
517
+ if (action !== 'begin' && action !== 'status' && action !== 'validate' && action !== 'commit' && action !== 'discard') {
518
+ return invalidArguments('action must be one of begin, status, validate, commit, discard.');
519
+ }
520
+ const transaction = transactionFor(host);
521
+ const result = (data, ok) => ({
522
+ ok,
523
+ status: ok ? 'success' : 'error',
524
+ source: SOURCE,
525
+ data,
526
+ error: ok ? undefined : { code: 'commit_failed', message: data.error ?? 'Candidate commit failed.' },
527
+ });
528
+ const stateShape = () => ({
529
+ success: true,
530
+ action,
531
+ transactionId: transaction.id,
532
+ state: transaction.state,
533
+ files: transaction.paths,
534
+ bytes: transaction.bytes,
535
+ });
536
+ if (action === 'begin') {
537
+ if (transaction.state === 'active' || transaction.state === 'validated') {
538
+ return failure('transaction_active', 'A candidate transaction is already active (' + (transaction.id ?? '<unknown>') + ').');
539
+ }
540
+ const id = transaction.begin();
541
+ return result({ success: true, action, transactionId: id, state: transaction.state, files: [], bytes: 0 }, true);
542
+ }
543
+ if (transaction.state === 'discarded' || transaction.state === 'committed') {
544
+ // Status/discard stay answerable after the fact; mutating actions need a new begin.
545
+ if (action === 'status' || action === 'discard') {
546
+ return result({ ...stateShape(), success: action === 'status' }, action === 'status');
547
+ }
548
+ return failure('transaction_inactive', 'No active candidate transaction; call candidate_transaction with action "begin" first.');
549
+ }
550
+ if (typeof args.transactionId === 'string' && args.transactionId !== transaction.id) {
551
+ return failure('transaction_mismatch', 'transactionId does not match the active candidate transaction (' + (transaction.id ?? 'none') + ').');
552
+ }
553
+ if (action === 'status')
554
+ return result(stateShape(), true);
555
+ if (action === 'discard') {
556
+ transaction.discard();
557
+ return result({ ...stateShape(), files: [], bytes: 0 }, true);
558
+ }
559
+ if (action === 'validate') {
560
+ if (!transaction.canValidate) {
561
+ return failure('transaction_inactive', 'Candidate transaction is not active.');
562
+ }
563
+ if (transaction.files.length === 0) {
564
+ // Nothing staged: validation is vacuously satisfied and the detached
565
+ // validator would reject an empty batch, stranding the transaction.
566
+ transaction.validate(true);
567
+ return result({ ...stateShape(), files: [], bytes: 0 }, true);
568
+ }
569
+ if (args.validationPassed === false) {
570
+ transaction.validate(false);
571
+ return result({ ...stateShape(), success: false, error: 'Caller-reported semantic validation failure.' }, true);
572
+ }
573
+ const overlay = await validateOverlayOnHost(host, transaction.files, context?.signal);
574
+ if ('infrastructureError' in overlay) {
575
+ // The candidates were never judged: report the cause and keep the
576
+ // transaction active so the caller can retry or discard it.
577
+ return result({
578
+ ...stateShape(),
579
+ success: false,
580
+ infrastructureError: overlay.infrastructureError,
581
+ error: 'Candidate overlay validation could not run: ' + overlay.infrastructureError,
582
+ }, false);
583
+ }
584
+ const invalid = overlay.files.find(file => file.ok !== true
585
+ || file.contentHash !== transaction.files.find(candidate => toFileUri(candidate.path) === file.uri)?.contentHash
586
+ || (file.diagnostics ?? []).some(diagnostic => diagnostic.severity === 'error'));
587
+ transaction.validate(!invalid);
588
+ return result({
589
+ ...stateShape(),
590
+ success: !invalid,
591
+ validationOk: !invalid,
592
+ overlayValidation: overlay,
593
+ error: invalid ? invalid.error ?? 'Overlay validation rejected ' + (invalid.uri ?? 'a candidate file') + '.' : undefined,
594
+ }, !invalid);
595
+ }
596
+ // action === 'commit'
597
+ if (transaction.state !== 'validated') {
598
+ return failure('transaction_not_validated', 'Candidate transaction must be validated before commit.');
599
+ }
600
+ const files = transaction.files;
601
+ const baselines = new Map();
602
+ for (const file of files) {
603
+ const baseline = await host.diagnostics.getDiagnostics({ file: file.path, limit: DIAGNOSTIC_LIMIT }, context?.signal ? { signal: context.signal } : undefined);
604
+ baselines.set(file.path, { snapshot: snapshotDiagnostics(baseline.diagnostics), epoch: epochOf(baseline) });
605
+ }
606
+ const diagnosticDeltas = {};
607
+ let commit;
608
+ try {
609
+ commit = await lockQueueFor(host).run(files.map(file => WriteLockQueue.key(file.path)), LOCK_TIMEOUT_MS, () => transaction.commit(host, baselines, diagnosticDeltas, context?.signal));
610
+ }
611
+ catch (error) {
612
+ if (isAbortLike(error))
613
+ throw error;
614
+ return failure('commit_failed', errorText(error));
615
+ }
616
+ if (commit.state === 'committed' || commit.state === 'discarded')
617
+ transaction.settle(commit.state);
618
+ return result({
619
+ success: commit.committed,
620
+ action,
621
+ transactionId: transaction.id,
622
+ state: transaction.state,
623
+ files: commit.files,
624
+ bytes: transaction.bytes,
625
+ commit: { committed: commit.committed, state: commit.state, files: commit.files, rollback: commit.rollback },
626
+ diagnosticDeltas,
627
+ error: commit.error,
628
+ }, commit.committed);
629
+ }
@@ -7,4 +7,5 @@ export interface ToolRegistryMetadata {
7
7
  effect: ToolEffect;
8
8
  riskLevel: 0 | 1 | 2 | 3;
9
9
  concurrencyClass: ToolConcurrencyClass;
10
+ mcpSupportsCwtOnly: boolean;
10
11
  }
@@ -0,0 +1,36 @@
1
+ export declare const MAX_SCOPE_BRIDGE_HOPS = 4;
2
+ export declare const MAX_SCOPE_BRIDGE_CANDIDATES = 200;
3
+ export interface ScopeBridgeCandidate {
4
+ name: string;
5
+ supportedScopes: readonly string[];
6
+ pushScope?: string;
7
+ evidence?: string | readonly string[];
8
+ }
9
+ export interface ScopeBridgeInput {
10
+ fromScope: string;
11
+ toScope: string;
12
+ candidates: readonly ScopeBridgeCandidate[];
13
+ }
14
+ export interface ScopeBridgeStep {
15
+ name: string;
16
+ fromScopes: string[];
17
+ toScopes: string[];
18
+ evidence: string[];
19
+ }
20
+ export interface ScopeBridgePath {
21
+ rank: number;
22
+ steps: ScopeBridgeStep[];
23
+ confidence: number;
24
+ evidence: string[];
25
+ }
26
+ export interface ScopeBridgeResult {
27
+ paths: ScopeBridgePath[];
28
+ confidence: number;
29
+ evidence: string[];
30
+ }
31
+ /**
32
+ * Finds evidence-backed scope transitions without consulting a registry or any
33
+ * process state. Inputs are normalized so output is independent of candidate
34
+ * order and spelling case.
35
+ */
36
+ export declare function solveScopeBridge(input: ScopeBridgeInput): ScopeBridgeResult;