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,424 @@
1
+ "use strict";
2
+ // Generated by tools/generate-mcp-detection.cjs from client/extension.
3
+ // Do not edit by hand; run npm run generate:mcp-detection.
4
+ /**
5
+ * Workspace game detection.
6
+ *
7
+ * Pure, vscode-free evidence classification. Structural evidence decides WHETHER
8
+ * a workspace is supported; scoring only decides WHICH game it targets. The
9
+ * MCP generator publishes this file and its profile adapter to cwtools-shared.
10
+ */
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || (function () {
28
+ var ownKeys = function(o) {
29
+ ownKeys = Object.getOwnPropertyNames || function (o) {
30
+ var ar = [];
31
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
+ return ar;
33
+ };
34
+ return ownKeys(o);
35
+ };
36
+ return function (mod) {
37
+ if (mod && mod.__esModule) return mod;
38
+ var result = {};
39
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
+ __setModuleDefault(result, mod);
41
+ return result;
42
+ };
43
+ })();
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.hasWorkspaceModDescriptor = hasWorkspaceModDescriptor;
46
+ exports.classifyWorkspaceRoot = classifyWorkspaceRoot;
47
+ exports.detectWorkspaceProject = detectWorkspaceProject;
48
+ exports.workspaceHasParadoxStructure = workspaceHasParadoxStructure;
49
+ exports.inferGameIdFromWorkspace = inferGameIdFromWorkspace;
50
+ const fs = __importStar(require("fs"));
51
+ const os = __importStar(require("os"));
52
+ const path = __importStar(require("path"));
53
+ const workshopDetection_1 = require("./workshopDetection");
54
+ const workspaceDetectionProfiles_1 = require("./workspaceDetectionProfiles");
55
+ const WORKSPACE_GAME_MARKERS = {
56
+ stellaris: [
57
+ 'common/solar_system_initializers', 'common/megastructures', 'common/pop_faction_types',
58
+ 'common/starbase_buildings', 'common/ship_sizes', 'common/planet_classes', 'map/star_classes',
59
+ ],
60
+ hoi4: ['common/national_focus', 'common/ideas', 'common/units', 'history/states', 'map/strategicregions'],
61
+ eu4: ['common/countries', 'common/country_tags', 'common/governments', 'common/religions', 'history/provinces', 'missions'],
62
+ ck2: ['common/dynasties', 'common/landed_titles', 'common/religions', 'history/characters', 'history/titles'],
63
+ ck3: ['common/dynasties', 'common/landed_titles', 'common/culture', 'common/religion', 'history/characters', 'history/titles'],
64
+ vic2: ['common/countries', 'history/countries', 'history/provinces', 'poptypes', 'units'],
65
+ vic3: ['common/country_definitions', 'common/interest_groups', 'common/laws', 'common/production_methods', 'common/pop_types'],
66
+ imperator: ['common/cultures', 'common/religions', 'common/governments', 'common/countries', 'setup/main'],
67
+ eu5: ['common/countries', 'common/country_tags', 'common/governments', 'common/laws', 'common/situations'],
68
+ };
69
+ const WORKSPACE_GAME_TEXT_HINTS = {
70
+ stellaris: ['stellaris', 'solar system', 'megastructure', 'pop faction', 'starbase'],
71
+ hoi4: ['hoi4', 'hearts of iron', 'national focus', 'strategic region'],
72
+ eu4: ['eu4', 'europa universalis iv', 'europa universalis 4'],
73
+ ck2: ['ck2', 'crusader kings ii', 'crusader kings 2'],
74
+ ck3: ['ck3', 'crusader kings iii', 'crusader kings 3'],
75
+ vic2: ['vic2', 'victoria ii', 'victoria 2'],
76
+ vic3: ['vic3', 'victoria 3', 'victoria iii'],
77
+ imperator: ['imperator', 'imperator rome', 'imperator: rome'],
78
+ eu5: ['eu5', 'europa universalis v', 'europa universalis 5'],
79
+ };
80
+ const PARADOX_CONTENT_DIRS = new Set([
81
+ 'common', 'events', 'history', 'map', 'map_data', 'prescripted_countries',
82
+ 'localisation', 'localisation_synced', 'localization', 'interface', 'gfx',
83
+ ]);
84
+ const PDX_PAYLOAD_EXTENSIONS = new Set(['.txt', '.yml', '.yaml', '.csv', '.gui', '.gfx', '.asset']);
85
+ const SCAN_IGNORED_DIRS = new Set([
86
+ '.git', '.vscode', '.vscode-test', '.cwtools', '.cwtools-ai', 'node_modules',
87
+ 'bin', 'obj', 'out', 'output', 'release', 'runs', 'artifacts', '.tmp-test',
88
+ ]);
89
+ const MAX_ANCESTORS = 6;
90
+ const MAX_CHILDREN = 64;
91
+ const MAX_PAYLOAD_ENTRIES = 64;
92
+ const MAX_DESCRIPTOR_CHARS = 12000;
93
+ const MAX_PROFILE_BYTES = 2 * 1024 * 1024;
94
+ const MAX_RULE_SCAN_ENTRIES = 5000;
95
+ function normalizeDetectionText(value) {
96
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
97
+ }
98
+ function normalizedPath(value) {
99
+ const fold = (s) => os.platform() === 'win32' ? s.toLowerCase() : s;
100
+ try {
101
+ return fold(path.resolve(value));
102
+ }
103
+ catch {
104
+ return fold(value);
105
+ }
106
+ }
107
+ function sameOrInside(candidate, parent) {
108
+ const resolved = normalizedPath(candidate);
109
+ const root = normalizedPath(parent);
110
+ return resolved === root || resolved.startsWith(root + path.sep);
111
+ }
112
+ function isFile(filePath) {
113
+ try {
114
+ return fs.statSync(filePath).isFile();
115
+ }
116
+ catch {
117
+ return false;
118
+ }
119
+ }
120
+ function isDirectory(dirPath) {
121
+ try {
122
+ return fs.statSync(dirPath).isDirectory();
123
+ }
124
+ catch {
125
+ return false;
126
+ }
127
+ }
128
+ function hasRelativeDirectory(rootPath, relativePath) {
129
+ return isDirectory(path.join(rootPath, ...relativePath.split('/')));
130
+ }
131
+ function readEntries(dirPath) {
132
+ try {
133
+ return fs.readdirSync(dirPath, { withFileTypes: true })
134
+ .sort((a, b) => a.name.localeCompare(b.name));
135
+ }
136
+ catch {
137
+ return [];
138
+ }
139
+ }
140
+ function unsupported(rootPath, reason = `No reliable Paradox/CWT evidence at '${rootPath}'.`) {
141
+ return { kind: 'unsupported', evidence: [], strength: 'none', reason };
142
+ }
143
+ function supported(kind, rootPath, evidence, strength, gameId) {
144
+ return {
145
+ kind,
146
+ matchedAt: rootPath,
147
+ evidence,
148
+ strength,
149
+ reason: evidence.join('; '),
150
+ ...(gameId ? { gameId } : {}),
151
+ };
152
+ }
153
+ function descriptorEvidence(rootPath) {
154
+ const canonical = path.join(rootPath, 'descriptor.mod');
155
+ if (isFile(canonical))
156
+ return 'descriptor.mod';
157
+ for (const entry of readEntries(rootPath)) {
158
+ if (!entry.isFile() || entry.name === 'descriptor.mod' || !entry.name.toLowerCase().endsWith('.mod'))
159
+ continue;
160
+ try {
161
+ const content = fs.readFileSync(path.join(rootPath, entry.name), 'utf8').slice(0, MAX_DESCRIPTOR_CHARS);
162
+ const hasName = /^name\s*=/m.test(content);
163
+ const hasRootOrVersion = /^(path|supported_version)\s*=/m.test(content);
164
+ if (hasName && hasRootOrVersion)
165
+ return `${entry.name} (parsed descriptor fields)`;
166
+ }
167
+ catch {
168
+ // An unreadable non-standard descriptor is not evidence.
169
+ }
170
+ }
171
+ return undefined;
172
+ }
173
+ function hasWorkspaceModDescriptor(rootPath) {
174
+ return descriptorEvidence(rootPath) !== undefined;
175
+ }
176
+ function readWorkspaceGameDescriptor(rootPath) {
177
+ const chunks = [];
178
+ const candidates = [path.join(rootPath, 'descriptor.mod'), path.join(rootPath, '.metadata', 'metadata.json')];
179
+ for (const entry of readEntries(rootPath)) {
180
+ if (entry.isFile() && entry.name.toLowerCase().endsWith('.mod'))
181
+ candidates.push(path.join(rootPath, entry.name));
182
+ }
183
+ for (const filePath of candidates) {
184
+ try {
185
+ if (isFile(filePath))
186
+ chunks.push(fs.readFileSync(filePath, 'utf8').slice(0, MAX_DESCRIPTOR_CHARS));
187
+ }
188
+ catch {
189
+ // Ignore unreadable descriptor files.
190
+ }
191
+ }
192
+ return normalizeDetectionText(chunks.join('\n'));
193
+ }
194
+ function validProjectProfileGame(rootPath) {
195
+ const profilePath = path.join(rootPath, '.cwtools', 'project', 'profile.json');
196
+ try {
197
+ if (!isFile(profilePath) || fs.statSync(profilePath).size > MAX_PROFILE_BYTES)
198
+ return undefined;
199
+ const raw = JSON.parse(fs.readFileSync(profilePath, 'utf8'));
200
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
201
+ return undefined;
202
+ const profile = raw;
203
+ const game = typeof profile.game === 'object' && profile.game !== null && !Array.isArray(profile.game)
204
+ ? profile.game
205
+ : undefined;
206
+ const gameId = typeof game?.id === 'string' ? game.id : '';
207
+ const known = gameId === 'paradox' || (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)().some(profileEntry => profileEntry.id === gameId);
208
+ const workspaceKind = profile.workspaceKind;
209
+ if (profile.schemaVersion !== 4
210
+ || (workspaceKind !== 'paradox_mod' && workspaceKind !== 'mixed')
211
+ || typeof profile.workspaceRoot !== 'string'
212
+ || normalizedPath(profile.workspaceRoot) !== normalizedPath(rootPath)
213
+ || !known)
214
+ return undefined;
215
+ return gameId;
216
+ }
217
+ catch {
218
+ return undefined;
219
+ }
220
+ }
221
+ function hasUsableNestedMetadata(rootPath) {
222
+ try {
223
+ const raw = JSON.parse(fs.readFileSync(path.join(rootPath, '.metadata', 'metadata.json'), 'utf8'));
224
+ return typeof raw === 'object' && raw !== null && !Array.isArray(raw);
225
+ }
226
+ catch {
227
+ return false;
228
+ }
229
+ }
230
+ function contentEvidence(rootPath) {
231
+ const directories = readEntries(rootPath)
232
+ .filter(entry => entry.isDirectory() && PARADOX_CONTENT_DIRS.has(entry.name.toLowerCase()))
233
+ .map(entry => entry.name);
234
+ let payload;
235
+ for (const directory of directories) {
236
+ const result = findPdxPayload(path.join(rootPath, directory), directory, 0);
237
+ if (result) {
238
+ payload = result;
239
+ break;
240
+ }
241
+ }
242
+ return { directories, ...(payload ? { payload } : {}) };
243
+ }
244
+ function findPdxPayload(dirPath, relative, depth) {
245
+ let visited = 0;
246
+ for (const entry of readEntries(dirPath)) {
247
+ if (visited++ >= MAX_PAYLOAD_ENTRIES)
248
+ break;
249
+ if (entry.isDirectory()) {
250
+ if (depth < 2 && !SCAN_IGNORED_DIRS.has(entry.name)) {
251
+ const found = findPdxPayload(path.join(dirPath, entry.name), `${relative}/${entry.name}`, depth + 1);
252
+ if (found)
253
+ return found;
254
+ }
255
+ }
256
+ else if (entry.isFile() && PDX_PAYLOAD_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
257
+ return `${relative}/${entry.name}`;
258
+ }
259
+ }
260
+ return undefined;
261
+ }
262
+ function isCwtRuleWorkspace(rootPath) {
263
+ if (descriptorEvidence(rootPath))
264
+ return false;
265
+ let count = 0;
266
+ let cwtCount = 0;
267
+ let visited = 0;
268
+ const visit = (dirPath) => {
269
+ for (const entry of readEntries(dirPath)) {
270
+ if (visited++ >= MAX_RULE_SCAN_ENTRIES)
271
+ return false;
272
+ if (entry.isDirectory()) {
273
+ if (!SCAN_IGNORED_DIRS.has(entry.name) && visit(path.join(dirPath, entry.name)))
274
+ return true;
275
+ }
276
+ else if (entry.isFile()) {
277
+ const extension = path.extname(entry.name).toLowerCase();
278
+ if (extension === '.cwt')
279
+ cwtCount++;
280
+ if ((extension === '.cwt' || extension === '.log'))
281
+ count++;
282
+ if (count >= 6 && cwtCount >= 1)
283
+ return true;
284
+ }
285
+ }
286
+ return false;
287
+ };
288
+ return visit(rootPath);
289
+ }
290
+ function vanillaEvidence(rootPath, configuredGamePath) {
291
+ const matches = (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)()
292
+ .map(profile => ({ profile, configured: configuredGamePath(profile.id) }))
293
+ .filter(item => item.configured
294
+ && isDirectory(path.join(item.configured, 'common'))
295
+ && sameOrInside(rootPath, item.configured))
296
+ .map(item => ({ id: item.profile.id, configured: item.configured }));
297
+ if (matches.length === 0)
298
+ return {};
299
+ return {
300
+ gameId: matches.length === 1 ? matches[0].id : undefined,
301
+ evidence: `workspace is equal to or inside configured game data path: ${matches.map(item => item.configured).join(', ')}`,
302
+ };
303
+ }
304
+ function markerEvidence(rootPath) {
305
+ const found = [];
306
+ for (const profile of (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)()) {
307
+ for (const marker of WORKSPACE_GAME_MARKERS[profile.id] ?? []) {
308
+ if (hasRelativeDirectory(rootPath, marker))
309
+ found.push(`${profile.id}:${marker}`);
310
+ }
311
+ }
312
+ return found;
313
+ }
314
+ function scoreWorkspaceForGame(rootPath, descriptorText, profile, configuredPath) {
315
+ let score = 0;
316
+ const rootText = normalizeDetectionText(rootPath);
317
+ const profileTexts = [
318
+ profile.id, profile.displayName, profile.steamFolderName, profile.exeName,
319
+ ...profile.alternativeFolderNames, ...(WORKSPACE_GAME_TEXT_HINTS[profile.id] ?? []),
320
+ ].map(normalizeDetectionText).filter(Boolean);
321
+ if (profileTexts.some(hint => rootText.includes(hint)))
322
+ score += 70;
323
+ if (profileTexts.some(hint => descriptorText.includes(hint)))
324
+ score += 90;
325
+ if (configuredPath && sameOrInside(rootPath, configuredPath))
326
+ score += 80;
327
+ for (const marker of WORKSPACE_GAME_MARKERS[profile.id] ?? []) {
328
+ if (hasRelativeDirectory(rootPath, marker))
329
+ score += 25;
330
+ }
331
+ return score;
332
+ }
333
+ function inferSupportedGame(rootPath, configuredGamePath) {
334
+ const descriptorText = readWorkspaceGameDescriptor(rootPath);
335
+ const scores = (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)()
336
+ .map(profile => ({
337
+ id: profile.id,
338
+ score: scoreWorkspaceForGame(rootPath, descriptorText, profile, configuredGamePath(profile.id)),
339
+ }))
340
+ .sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
341
+ const best = scores[0];
342
+ const next = scores[1];
343
+ return best && best.score >= 40 && best.score > (next?.score ?? 0) ? best.id : undefined;
344
+ }
345
+ /** Classify only this exact root; no ancestor or child can change its identity. */
346
+ function classifyWorkspaceRoot(rootPath, configuredGamePath, options) {
347
+ const profiles = (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)();
348
+ const workshopAppId = (0, workshopDetection_1.parseWorkshopContentAppId)(rootPath);
349
+ if (workshopAppId) {
350
+ const game = profiles.find(profile => profile.steamAppId === workshopAppId);
351
+ if (game && workshopAppId !== '0') {
352
+ return supported('mod', rootPath, [`Steam Workshop App ID ${workshopAppId}`], 'strong', game.id);
353
+ }
354
+ }
355
+ const vanilla = vanillaEvidence(rootPath, configuredGamePath);
356
+ if (vanilla.evidence)
357
+ return supported('vanilla', rootPath, [vanilla.evidence], 'strong', vanilla.gameId);
358
+ const profileGame = validProjectProfileGame(rootPath);
359
+ if (profileGame)
360
+ return supported('mod', rootPath, ['valid .cwtools/project/profile.json'], 'strong', profileGame);
361
+ const descriptor = descriptorEvidence(rootPath);
362
+ if (descriptor)
363
+ return supported('mod', rootPath, [descriptor], 'strong', inferSupportedGame(rootPath, configuredGamePath));
364
+ if (options?.allowCwt !== false && isCwtRuleWorkspace(rootPath)) {
365
+ return supported('cwt-only', rootPath, ['bounded CWT rule cluster (at least six rule/log files and one .cwt)'], 'strong');
366
+ }
367
+ const markers = markerEvidence(rootPath);
368
+ if (markers.length > 0)
369
+ return supported('mod', rootPath, markers, 'strong', inferSupportedGame(rootPath, configuredGamePath));
370
+ const content = contentEvidence(rootPath);
371
+ if (content.payload && content.directories.length >= 2) {
372
+ return supported('mod', rootPath, [`content directories: ${content.directories.join(', ')}`, `PDX payload: ${content.payload}`], 'composite', inferSupportedGame(rootPath, configuredGamePath));
373
+ }
374
+ if (content.payload && content.directories.length === 1 && hasUsableNestedMetadata(rootPath)) {
375
+ return supported('mod', rootPath, [`.metadata/metadata.json plus ${content.directories[0]}`, `PDX payload: ${content.payload}`], 'composite', inferSupportedGame(rootPath, configuredGamePath));
376
+ }
377
+ return unsupported(rootPath);
378
+ }
379
+ /** Resolve a root, a strong ancestor, or exactly one matching immediate child. */
380
+ function detectWorkspaceProject(rootPath, configuredGamePath) {
381
+ const atRoot = classifyWorkspaceRoot(rootPath, configuredGamePath);
382
+ if (atRoot.kind !== 'unsupported')
383
+ return atRoot;
384
+ let ancestor = rootPath;
385
+ for (let depth = 0; depth < MAX_ANCESTORS; depth++) {
386
+ const parent = path.dirname(ancestor);
387
+ if (!parent || parent === ancestor)
388
+ break;
389
+ ancestor = parent;
390
+ const match = classifyWorkspaceRoot(ancestor, configuredGamePath, { allowCwt: false });
391
+ // Recursive CWT clustering at an ancestor would scan unrelated sibling trees.
392
+ // Only non-recursive mod/vanilla markers are safe ancestor evidence.
393
+ if ((match.kind === 'mod' || match.kind === 'vanilla') && match.strength === 'strong')
394
+ return match;
395
+ }
396
+ const children = readEntries(rootPath)
397
+ .filter(entry => entry.isDirectory() && entry.name !== 'node_modules')
398
+ .slice(0, MAX_CHILDREN)
399
+ .map(entry => classifyWorkspaceRoot(path.join(rootPath, entry.name), configuredGamePath))
400
+ .filter(result => result.kind !== 'unsupported');
401
+ if (children.length === 1)
402
+ return children[0];
403
+ if (children.length > 1) {
404
+ const candidates = children.map(result => result.matchedAt).sort((a, b) => a.localeCompare(b));
405
+ return {
406
+ kind: 'ambiguous',
407
+ evidence: children.flatMap(result => result.evidence),
408
+ candidates,
409
+ strength: 'none',
410
+ reason: `Multiple Paradox/CWT projects found; pass --workspace explicitly: ${candidates.join(', ')}`,
411
+ };
412
+ }
413
+ return unsupported(rootPath, `No reliable Paradox/CWT evidence at, above, or directly under '${rootPath}'.`);
414
+ }
415
+ /** True only for game/mod evidence; CWT-only deliberately does not select a game. */
416
+ function workspaceHasParadoxStructure(rootPath, configuredGamePath) {
417
+ const result = classifyWorkspaceRoot(rootPath, configuredGamePath);
418
+ return result.kind === 'mod' || result.kind === 'vanilla';
419
+ }
420
+ /** Infer the game only after structural support has been established. */
421
+ function inferGameIdFromWorkspace(rootPath, configuredGamePath) {
422
+ const result = classifyWorkspaceRoot(rootPath, configuredGamePath);
423
+ return result.kind === 'mod' || result.kind === 'vanilla' ? result.gameId : undefined;
424
+ }
@@ -0,0 +1,39 @@
1
+ /** Protocol version this client speaks. Bump when the response shape changes. */
2
+ export declare const HOST_CAPABILITIES_PROTOCOL_VERSION = 1;
3
+ export interface HostCapabilities {
4
+ protocolVersion: number;
5
+ serverVersion: string;
6
+ commands: string[];
7
+ }
8
+ export declare const BACKEND_INCOMPATIBLE_CODE = "backend_incompatible";
9
+ export type HostCapabilitiesVerdict = {
10
+ ok: true;
11
+ capabilities: HostCapabilities;
12
+ } | {
13
+ ok: false;
14
+ reason: 'legacy' | 'malformed' | 'incomplete' | 'protocol';
15
+ message: string;
16
+ };
17
+ /**
18
+ * Validate an untrusted handshake payload. Anything that is not a complete,
19
+ * well-formed, protocol-matching record is a rejection with a precise reason so
20
+ * the caller can report `backend_incompatible` and release the backend rather
21
+ * than running against a server whose command table it cannot trust.
22
+ */
23
+ export declare function parseHostCapabilities(raw: unknown): HostCapabilitiesVerdict;
24
+ /**
25
+ * Every LSP command this client's tool surface actually calls. Derived from the
26
+ * cwtools-shared dispatcher call sites plus the Node diagnostics/revalidation
27
+ * hosts, so a backend missing any one of them is rejected up front instead of
28
+ * degrading a single tool into an empty answer at call time.
29
+ *
30
+ * `cwtools.ai.getHostCapabilities` is deliberately absent: it is the handshake
31
+ * itself and never a model-facing tool.
32
+ */
33
+ export declare const REQUIRED_BACKEND_COMMANDS: readonly string[];
34
+ /**
35
+ * Check a validated capability set against the commands this client requires.
36
+ * A backend that is merely old is still rejected: the client cannot silently
37
+ * degrade a semantic tool into an empty answer.
38
+ */
39
+ export declare function checkRequiredCommands(capabilities: HostCapabilities, required?: readonly string[]): HostCapabilitiesVerdict;
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ // Backend capability handshake.
3
+ //
4
+ // `cwtools.ai.getHostCapabilities` is an internal command: it is answered before
5
+ // the game model loads, it is not part of any model-facing tool schema, and it
6
+ // exists so a host can prove it is talking to a compatible build before it
7
+ // spends seconds (or gigabytes) loading a project.
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.REQUIRED_BACKEND_COMMANDS = exports.BACKEND_INCOMPATIBLE_CODE = exports.HOST_CAPABILITIES_PROTOCOL_VERSION = void 0;
10
+ exports.parseHostCapabilities = parseHostCapabilities;
11
+ exports.checkRequiredCommands = checkRequiredCommands;
12
+ /** Protocol version this client speaks. Bump when the response shape changes. */
13
+ exports.HOST_CAPABILITIES_PROTOCOL_VERSION = 1;
14
+ exports.BACKEND_INCOMPATIBLE_CODE = 'backend_incompatible';
15
+ function isRecord(value) {
16
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
17
+ }
18
+ /**
19
+ * Validate an untrusted handshake payload. Anything that is not a complete,
20
+ * well-formed, protocol-matching record is a rejection with a precise reason so
21
+ * the caller can report `backend_incompatible` and release the backend rather
22
+ * than running against a server whose command table it cannot trust.
23
+ */
24
+ function parseHostCapabilities(raw) {
25
+ if (!isRecord(raw)) {
26
+ return { ok: false, reason: 'legacy', message: 'Backend did not answer cwtools.ai.getHostCapabilities.' };
27
+ }
28
+ if (raw.status === 'unavailable' || isRecord(raw.error)) {
29
+ return {
30
+ ok: false,
31
+ reason: 'legacy',
32
+ message: `Backend rejected the capability handshake: ${String((isRecord(raw.error) ? raw.error.message : undefined) ?? 'unavailable')}.`,
33
+ };
34
+ }
35
+ const protocolVersion = raw.protocolVersion;
36
+ const serverVersion = raw.serverVersion;
37
+ const commands = raw.commands;
38
+ if (typeof protocolVersion !== 'number' || !Number.isInteger(protocolVersion)) {
39
+ return { ok: false, reason: 'malformed', message: 'Backend handshake is missing an integer protocolVersion.' };
40
+ }
41
+ if (typeof serverVersion !== 'string' || serverVersion.trim().length === 0) {
42
+ return { ok: false, reason: 'malformed', message: 'Backend handshake is missing a serverVersion string.' };
43
+ }
44
+ if (!Array.isArray(commands) || commands.some(command => typeof command !== 'string')) {
45
+ return { ok: false, reason: 'malformed', message: 'Backend handshake is missing a string[] commands table.' };
46
+ }
47
+ if (protocolVersion !== exports.HOST_CAPABILITIES_PROTOCOL_VERSION) {
48
+ return {
49
+ ok: false,
50
+ reason: 'protocol',
51
+ message: `Backend speaks capability protocol ${protocolVersion}; this client requires ${exports.HOST_CAPABILITIES_PROTOCOL_VERSION}.`,
52
+ };
53
+ }
54
+ if (commands.length === 0) {
55
+ return { ok: false, reason: 'incomplete', message: 'Backend handshake reported an empty command table.' };
56
+ }
57
+ return {
58
+ ok: true,
59
+ capabilities: { protocolVersion, serverVersion: serverVersion.trim(), commands: [...commands] },
60
+ };
61
+ }
62
+ /**
63
+ * Every LSP command this client's tool surface actually calls. Derived from the
64
+ * cwtools-shared dispatcher call sites plus the Node diagnostics/revalidation
65
+ * hosts, so a backend missing any one of them is rejected up front instead of
66
+ * degrading a single tool into an empty answer at call time.
67
+ *
68
+ * `cwtools.ai.getHostCapabilities` is deliberately absent: it is the handshake
69
+ * itself and never a model-facing tool.
70
+ */
71
+ exports.REQUIRED_BACKEND_COMMANDS = [
72
+ // Readiness, diagnostics and manual revalidation.
73
+ 'cwtools.ai.getValidationStatus',
74
+ 'cwtools.ai.getDiagnosticsFresh',
75
+ 'cwtools.ai.getAllDiagnostics',
76
+ 'cwtools.ai.revalidateFiles',
77
+ // Candidate overlay validation before a domain write is committed.
78
+ 'cwtools.ai.validateOverlay',
79
+ // Completion, symbols and navigation.
80
+ 'cwtools.ai.getCompletionContext',
81
+ 'cwtools.ai.getScopeAtPosition',
82
+ 'cwtools.ai.queryDefinition',
83
+ 'cwtools.ai.queryDefinitionByName',
84
+ 'cwtools.ai.getEntityInfo',
85
+ // Semantic model and project graph.
86
+ 'cwtools.ai.queryTypes',
87
+ 'cwtools.ai.exploreProject',
88
+ 'cwtools.ai.exploreInlineGraph',
89
+ 'cwtools.ai.analyzePdxFlow',
90
+ 'cwtools.ai.compareDefinitionWithVanilla',
91
+ 'cwtools.ai.parseFragment',
92
+ 'cwtools.ai.queryProjectKnowledgeDb',
93
+ 'cwtools.ai.exportProjectKnowledge',
94
+ 'cwtools.ai.queryOverrideModes',
95
+ // Localisation.
96
+ 'cwtools.ai.queryLocalisationAudit',
97
+ // Scripted types and enums.
98
+ 'cwtools.ai.queryScriptedEffects',
99
+ 'cwtools.ai.queryScriptedTriggers',
100
+ 'cwtools.ai.queryEnums',
101
+ 'cwtools.ai.queryStaticModifiers',
102
+ 'cwtools.ai.queryVariables',
103
+ // Shader surface: all seven commands are individually exposed as tools.
104
+ 'cwtools.ai.shader.symbols',
105
+ 'cwtools.ai.shader.compileUnit',
106
+ 'cwtools.ai.shader.variants',
107
+ 'cwtools.ai.shader.callers',
108
+ 'cwtools.ai.shader.reachability',
109
+ 'cwtools.ai.shader.validate',
110
+ 'cwtools.ai.shader.compareVanilla',
111
+ ];
112
+ /**
113
+ * Check a validated capability set against the commands this client requires.
114
+ * A backend that is merely old is still rejected: the client cannot silently
115
+ * degrade a semantic tool into an empty answer.
116
+ */
117
+ function checkRequiredCommands(capabilities, required = exports.REQUIRED_BACKEND_COMMANDS) {
118
+ const present = new Set(capabilities.commands);
119
+ const missing = required.filter(command => !present.has(command));
120
+ if (missing.length > 0) {
121
+ return {
122
+ ok: false,
123
+ reason: 'incomplete',
124
+ message: `Backend is missing required commands: ${missing.join(', ')}.`,
125
+ };
126
+ }
127
+ return { ok: true, capabilities };
128
+ }
@@ -21,6 +21,9 @@ export interface DiagnosticsQueryResult {
21
21
  status: DiagnosticsFreshness;
22
22
  diagnostics: DiagnosticRecord[];
23
23
  totalCount?: number;
24
+ /** Whole-workspace error/warning totals, independent of the requested page. */
25
+ errorCount?: number;
26
+ warningCount?: number;
24
27
  truncated?: boolean;
25
28
  suppressedCount?: number;
26
29
  freshness?: {
@@ -35,7 +38,11 @@ export interface DiagnosticsQueryResult {
35
38
  message: string;
36
39
  };
37
40
  }
41
+ /** Per-call context for a diagnostics query. `signal` cancels the backend work. */
42
+ export interface DiagnosticsQueryContext {
43
+ signal?: AbortSignal;
44
+ }
38
45
  export interface DiagnosticsHost {
39
- getDiagnostics(filter?: DiagnosticsFilter): Promise<DiagnosticsQueryResult>;
46
+ getDiagnostics(filter?: DiagnosticsFilter, context?: DiagnosticsQueryContext): Promise<DiagnosticsQueryResult>;
40
47
  }
41
48
  export declare function createUnavailableDiagnosticsHost(message?: string): DiagnosticsHost;
@@ -11,6 +11,8 @@ export interface DirectoryEntry {
11
11
  export interface FilesystemHost {
12
12
  readTextFile(path: string): Promise<ReadTextFileResult>;
13
13
  writeTextFile(path: string, content: string): Promise<void>;
14
+ readBinaryFile?(path: string): Promise<Buffer>;
15
+ writeBinaryFile?(path: string, content: Buffer): Promise<void>;
14
16
  list(path: string): Promise<DirectoryEntry[]>;
15
17
  glob(pattern: string, options?: {
16
18
  limit?: number;