cwtools-shared 0.2.8 → 0.3.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.
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Steam Workshop workspace detection.
3
+ *
4
+ * Workshop mods live under `steamapps/workshop/content/<appId>/<itemId>`.
5
+ * The App ID in the path is the most reliable game-identification signal
6
+ * available — far better than text/marker scoring — so it is used both to
7
+ * correct misdetection and to gate activation behind explicit user consent.
8
+ *
9
+ * This module deliberately avoids importing `vscode` so unit tests can load
10
+ * it directly without stubs.
11
+ */
12
+ /**
13
+ * Extracts the Steam App ID from a workshop content path.
14
+ * Matches a `workshop` segment immediately followed by `content` and a
15
+ * purely numeric segment, case-insensitively and across path separators.
16
+ */
17
+ export declare function parseWorkshopContentAppId(rootPath: string): string | undefined;
18
+ /**
19
+ * Maps a Steam App ID to a registered game language ID.
20
+ * Placeholder App IDs ('0', e.g. EU5 until the real one is known) never match.
21
+ */
22
+ export declare function getGameIdForWorkshopAppId(appId: string): string | undefined;
@@ -0,0 +1,50 @@
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
+ * Steam Workshop workspace detection.
6
+ *
7
+ * Workshop mods live under `steamapps/workshop/content/<appId>/<itemId>`.
8
+ * The App ID in the path is the most reliable game-identification signal
9
+ * available — far better than text/marker scoring — so it is used both to
10
+ * correct misdetection and to gate activation behind explicit user consent.
11
+ *
12
+ * This module deliberately avoids importing `vscode` so unit tests can load
13
+ * it directly without stubs.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.parseWorkshopContentAppId = parseWorkshopContentAppId;
17
+ exports.getGameIdForWorkshopAppId = getGameIdForWorkshopAppId;
18
+ const workspaceDetectionProfiles_1 = require("./workspaceDetectionProfiles");
19
+ /**
20
+ * Extracts the Steam App ID from a workshop content path.
21
+ * Matches a `workshop` segment immediately followed by `content` and a
22
+ * purely numeric segment, case-insensitively and across path separators.
23
+ */
24
+ function parseWorkshopContentAppId(rootPath) {
25
+ const segments = rootPath.split(/[\\/]+/).filter(Boolean);
26
+ for (let i = 0; i < segments.length - 2; i++) {
27
+ if (segments[i].toLowerCase() === 'workshop' && segments[i + 1].toLowerCase() === 'content') {
28
+ const appId = segments[i + 2];
29
+ if (/^\d+$/.test(appId)) {
30
+ return appId;
31
+ }
32
+ }
33
+ }
34
+ return undefined;
35
+ }
36
+ /**
37
+ * Maps a Steam App ID to a registered game language ID.
38
+ * Placeholder App IDs ('0', e.g. EU5 until the real one is known) never match.
39
+ */
40
+ function getGameIdForWorkshopAppId(appId) {
41
+ if (!/^\d+$/.test(appId) || appId === '0') {
42
+ return undefined;
43
+ }
44
+ for (const profile of (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)()) {
45
+ if (profile.steamAppId === appId) {
46
+ return profile.id;
47
+ }
48
+ }
49
+ return undefined;
50
+ }
@@ -0,0 +1,2 @@
1
+ import type { WorkspaceDetectionProfile } from './workspaceGameDetection';
2
+ export declare function getWorkspaceDetectionProfiles(): WorkspaceDetectionProfile[];
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getWorkspaceDetectionProfiles = getWorkspaceDetectionProfiles;
4
+ const PROFILES = [
5
+ {
6
+ "id": "stellaris",
7
+ "displayName": "Stellaris",
8
+ "steamFolderName": "Stellaris",
9
+ "exeName": "stellaris",
10
+ "alternativeFolderNames": [],
11
+ "steamAppId": "281990"
12
+ },
13
+ {
14
+ "id": "hoi4",
15
+ "displayName": "Hearts of Iron IV",
16
+ "steamFolderName": "Hearts of Iron IV",
17
+ "exeName": "hoi4",
18
+ "alternativeFolderNames": [],
19
+ "steamAppId": "394360"
20
+ },
21
+ {
22
+ "id": "eu4",
23
+ "displayName": "Europa Universalis IV",
24
+ "steamFolderName": "Europa Universalis IV",
25
+ "exeName": "eu4",
26
+ "alternativeFolderNames": [],
27
+ "steamAppId": "236850"
28
+ },
29
+ {
30
+ "id": "ck2",
31
+ "displayName": "Crusader Kings II",
32
+ "steamFolderName": "Crusader Kings II",
33
+ "exeName": "CK2",
34
+ "alternativeFolderNames": [],
35
+ "steamAppId": "203770"
36
+ },
37
+ {
38
+ "id": "ck3",
39
+ "displayName": "Crusader Kings III",
40
+ "steamFolderName": "Crusader Kings III",
41
+ "exeName": "ck3",
42
+ "alternativeFolderNames": [],
43
+ "steamAppId": "1158310"
44
+ },
45
+ {
46
+ "id": "vic2",
47
+ "displayName": "Victoria II",
48
+ "steamFolderName": "Victoria 2",
49
+ "exeName": "v2game",
50
+ "alternativeFolderNames": [
51
+ "Victoria II"
52
+ ],
53
+ "steamAppId": "42960"
54
+ },
55
+ {
56
+ "id": "vic3",
57
+ "displayName": "Victoria 3",
58
+ "steamFolderName": "Victoria 3",
59
+ "exeName": "victoria3",
60
+ "alternativeFolderNames": [],
61
+ "steamAppId": "529340"
62
+ },
63
+ {
64
+ "id": "imperator",
65
+ "displayName": "Imperator: Rome",
66
+ "steamFolderName": "ImperatorRome",
67
+ "exeName": "imperator",
68
+ "alternativeFolderNames": [
69
+ "Imperator"
70
+ ],
71
+ "steamAppId": "859580"
72
+ },
73
+ {
74
+ "id": "eu5",
75
+ "displayName": "Europa Universalis V",
76
+ "steamFolderName": "Europa Universalis V",
77
+ "exeName": "eu5",
78
+ "alternativeFolderNames": [],
79
+ "steamAppId": "0"
80
+ }
81
+ ];
82
+ function getWorkspaceDetectionProfiles() {
83
+ return PROFILES.map(profile => ({ ...profile, alternativeFolderNames: [...profile.alternativeFolderNames] }));
84
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Workspace game detection.
3
+ *
4
+ * Pure, vscode-free evidence classification. Structural evidence decides WHETHER
5
+ * a workspace is supported; scoring only decides WHICH game it targets. The
6
+ * MCP generator publishes this file and its profile adapter to cwtools-shared.
7
+ */
8
+ /** Looks up the user-configured vanilla data path for a game id. */
9
+ export type ConfiguredGamePathLookup = (gameId: string) => string | undefined;
10
+ export interface WorkspaceDetectionProfile {
11
+ id: string;
12
+ displayName: string;
13
+ steamFolderName: string;
14
+ exeName: string;
15
+ alternativeFolderNames: string[];
16
+ steamAppId: string;
17
+ }
18
+ export type WorkspaceProjectKind = 'mod' | 'vanilla' | 'cwt-only' | 'unsupported' | 'ambiguous';
19
+ export type WorkspaceEvidenceStrength = 'strong' | 'composite' | 'none';
20
+ export interface WorkspaceProjectDetection {
21
+ kind: WorkspaceProjectKind;
22
+ gameId?: string;
23
+ matchedAt?: string;
24
+ evidence: string[];
25
+ candidates?: string[];
26
+ strength: WorkspaceEvidenceStrength;
27
+ reason: string;
28
+ }
29
+ export declare function hasWorkspaceModDescriptor(rootPath: string): boolean;
30
+ /** Classify only this exact root; no ancestor or child can change its identity. */
31
+ export declare function classifyWorkspaceRoot(rootPath: string, configuredGamePath: ConfiguredGamePathLookup, options?: {
32
+ allowCwt?: boolean;
33
+ }): WorkspaceProjectDetection;
34
+ /** Resolve a root, a strong ancestor, or exactly one matching immediate child. */
35
+ export declare function detectWorkspaceProject(rootPath: string, configuredGamePath: ConfiguredGamePathLookup): WorkspaceProjectDetection;
36
+ /** True only for game/mod evidence; CWT-only deliberately does not select a game. */
37
+ export declare function workspaceHasParadoxStructure(rootPath: string, configuredGamePath: ConfiguredGamePathLookup): boolean;
38
+ /** Infer the game only after structural support has been established. */
39
+ export declare function inferGameIdFromWorkspace(rootPath: string, configuredGamePath: ConfiguredGamePathLookup): string | undefined;
@@ -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;