cwtools-shared 0.3.0 → 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.
- package/dist/debug/zz.d.ts +1 -0
- package/dist/debug/zz.js +12 -0
- package/dist/generated/mcpTools.d.ts +4 -4
- package/dist/generated/mcpTools.js +4 -4
- package/dist/host/capabilities.js +4 -0
- package/dist/host/diagnostics.d.ts +3 -0
- package/dist/host/filesystem.d.ts +2 -0
- package/dist/host/hostServices.d.ts +42 -0
- package/dist/host/indexing.d.ts +3 -0
- package/dist/host/readiness.js +10 -0
- package/dist/index.d.ts +12 -1
- package/dist/index.js +18 -1
- package/dist/knowledge/interfaceKnowledge.d.ts +8 -0
- package/dist/knowledge/interfaceKnowledge.js +222 -0
- package/dist/project/descriptor.d.ts +12 -0
- package/dist/project/descriptor.js +69 -0
- package/dist/project/init.d.ts +11 -0
- package/dist/project/init.js +356 -0
- package/dist/project/knowledge.d.ts +6 -0
- package/dist/project/knowledge.js +20 -8
- package/dist/project/profile.d.ts +62 -7
- package/dist/project/profile.js +4 -3
- package/dist/project/profileBuilder.d.ts +31 -0
- package/dist/project/profileBuilder.js +989 -0
- package/dist/tools/archetypeArtifacts.d.ts +29 -0
- package/dist/tools/archetypeArtifacts.js +136 -0
- package/dist/tools/archetypeSlots.d.ts +32 -0
- package/dist/tools/archetypeSlots.js +257 -0
- package/dist/tools/archetypeTools.d.ts +4 -0
- package/dist/tools/archetypeTools.js +118 -0
- package/dist/tools/callHandler.js +11 -7
- package/dist/tools/catalog.d.ts +4094 -0
- package/dist/tools/catalog.js +5031 -0
- package/dist/tools/domainTools.d.ts +8 -0
- package/dist/tools/domainTools.js +222 -0
- package/dist/tools/mcpSchema.d.ts +8 -11
- package/dist/tools/mcpSchema.js +28 -8
- package/dist/tools/mediaWrites.d.ts +52 -0
- package/dist/tools/mediaWrites.js +322 -0
- package/dist/tools/names.d.ts +4 -4
- package/dist/tools/names.js +13 -0
- package/dist/tools/pdxWriteCore.d.ts +51 -0
- package/dist/tools/pdxWriteCore.js +628 -0
- package/dist/tools/pdxWrites.d.ts +88 -0
- package/dist/tools/pdxWrites.js +629 -0
- package/dist/tools/scopeBridge.d.ts +36 -0
- package/dist/tools/scopeBridge.js +173 -0
- package/dist/tools/symbols.js +22 -2
- package/dist/tools/toolHandlers.js +98 -8
- package/package.json +1 -1
|
@@ -0,0 +1,989 @@
|
|
|
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.PROJECT_PROFILE_RELATIVE_PATH = void 0;
|
|
37
|
+
exports.getProjectProfilePath = getProjectProfilePath;
|
|
38
|
+
exports.isProjectProfile = isProjectProfile;
|
|
39
|
+
exports.readProjectProfile = readProjectProfile;
|
|
40
|
+
exports.writeProjectProfile = writeProjectProfile;
|
|
41
|
+
exports.buildProjectProfile = buildProjectProfile;
|
|
42
|
+
exports.queryProjectProfile = queryProjectProfile;
|
|
43
|
+
exports.getGuidanceCard = getGuidanceCard;
|
|
44
|
+
exports.buildProfileSummary = buildProfileSummary;
|
|
45
|
+
exports.mergeDeepCompatibilityEvidence = mergeDeepCompatibilityEvidence;
|
|
46
|
+
const fs = __importStar(require("fs"));
|
|
47
|
+
const path = __importStar(require("path"));
|
|
48
|
+
const workspaceDetectionProfiles_1 = require("../generated/workspaceDetectionProfiles");
|
|
49
|
+
const descriptor_1 = require("./descriptor");
|
|
50
|
+
const workspaceGameDetection_1 = require("../generated/workspaceGameDetection");
|
|
51
|
+
exports.PROJECT_PROFILE_RELATIVE_PATH = path.join('.cwtools', 'project', 'profile.json');
|
|
52
|
+
const MAX_PROJECT_PROFILE_BYTES = 2 * 1024 * 1024;
|
|
53
|
+
const PROFILE_WORKSPACE_KINDS = new Set(['paradox_mod', 'extension_source', 'mixed', 'generic']);
|
|
54
|
+
const PROFILE_GAME_CONFIDENCE = new Set(['high', 'medium', 'low']);
|
|
55
|
+
const PROFILE_LSP_STATES = new Set(['unknown', 'ready', 'not_ready']);
|
|
56
|
+
const PROFILE_INDEX_STATES = new Set(['unknown', 'ready', 'partial', 'indexing', 'idle', 'unavailable']);
|
|
57
|
+
const PROFILE_VANILLA_STATES = new Set(['unknown', 'configured', 'missing']);
|
|
58
|
+
const NAMESPACE_ORIGINS = new Set(['workspace_owned', 'vanilla_override', 'compatibility', 'external']);
|
|
59
|
+
function getProjectProfilePath(workspaceRoot) {
|
|
60
|
+
return path.join(workspaceRoot, exports.PROJECT_PROFILE_RELATIVE_PATH);
|
|
61
|
+
}
|
|
62
|
+
function isRecord(value) {
|
|
63
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
64
|
+
}
|
|
65
|
+
function isStringArray(value) {
|
|
66
|
+
return Array.isArray(value) && value.every(item => typeof item === 'string');
|
|
67
|
+
}
|
|
68
|
+
function isStringArrayRecord(value) {
|
|
69
|
+
return isRecord(value) && Object.values(value).every(isStringArray);
|
|
70
|
+
}
|
|
71
|
+
/** Validate the generated profile before it reaches prompts, LSP, or MCP paths. */
|
|
72
|
+
function isProjectProfile(value) {
|
|
73
|
+
if (!isRecord(value)
|
|
74
|
+
|| value.schemaVersion !== 4
|
|
75
|
+
|| typeof value.generatedAt !== 'string'
|
|
76
|
+
|| typeof value.workspaceRoot !== 'string'
|
|
77
|
+
|| !PROFILE_WORKSPACE_KINDS.has(String(value.workspaceKind))
|
|
78
|
+
|| typeof value.projectName !== 'string'
|
|
79
|
+
|| !isRecord(value.game)
|
|
80
|
+
|| typeof value.game.id !== 'string'
|
|
81
|
+
|| typeof value.game.displayName !== 'string'
|
|
82
|
+
|| !PROFILE_GAME_CONFIDENCE.has(String(value.game.confidence))
|
|
83
|
+
|| !isStringArray(value.game.evidence)
|
|
84
|
+
|| !Array.isArray(value.keyDirectories)
|
|
85
|
+
|| !isRecord(value.localisation)
|
|
86
|
+
|| !isStringArray(value.localisation.roots)
|
|
87
|
+
|| !isStringArray(value.localisation.languages)
|
|
88
|
+
|| typeof value.localisation.encoding !== 'string'
|
|
89
|
+
|| !isStringArray(value.localisation.sampleFiles)
|
|
90
|
+
|| !isRecord(value.identifiers)
|
|
91
|
+
|| !isStringArray(value.identifiers.namespaces)
|
|
92
|
+
|| (value.identifiers.namespaceDetails !== undefined
|
|
93
|
+
&& (!Array.isArray(value.identifiers.namespaceDetails)
|
|
94
|
+
|| !value.identifiers.namespaceDetails.every(item => isRecord(item)
|
|
95
|
+
&& typeof item.name === 'string'
|
|
96
|
+
&& NAMESPACE_ORIGINS.has(String(item.origin))
|
|
97
|
+
&& isStringArray(item.files)
|
|
98
|
+
&& typeof item.evidence === 'string')))
|
|
99
|
+
|| !isStringArray(value.identifiers.variablePrefixes)
|
|
100
|
+
|| !isStringArrayRecord(value.identifiers.byType)
|
|
101
|
+
|| !isRecord(value.routing)
|
|
102
|
+
|| !isStringArray(value.routing.preferredReadTools)
|
|
103
|
+
|| !isStringArray(value.routing.avoidPatterns)
|
|
104
|
+
|| !isRecord(value.validation)
|
|
105
|
+
|| !PROFILE_LSP_STATES.has(String(value.validation.lspReady))
|
|
106
|
+
|| !PROFILE_INDEX_STATES.has(String(value.validation.indexStatus))
|
|
107
|
+
|| !PROFILE_VANILLA_STATES.has(String(value.validation.vanillaCache))
|
|
108
|
+
|| !isRecord(value.guidanceCards)
|
|
109
|
+
|| !Object.values(value.guidanceCards).every(item => typeof item === 'string')
|
|
110
|
+
|| !isStringArray(value.efficiencyHints)) {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
if (!value.keyDirectories.every(directory => isRecord(directory)
|
|
114
|
+
&& typeof directory.key === 'string'
|
|
115
|
+
&& typeof directory.path === 'string'
|
|
116
|
+
&& typeof directory.exists === 'boolean'
|
|
117
|
+
&& (directory.fileCount === undefined
|
|
118
|
+
|| (typeof directory.fileCount === 'number' && Number.isFinite(directory.fileCount) && directory.fileCount >= 0)))) {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
if (value.modInfo !== undefined
|
|
122
|
+
&& (!isRecord(value.modInfo)
|
|
123
|
+
|| (value.modInfo.name !== undefined && typeof value.modInfo.name !== 'string')
|
|
124
|
+
|| (value.modInfo.version !== undefined && typeof value.modInfo.version !== 'string')
|
|
125
|
+
|| (value.modInfo.tags !== undefined && !isStringArray(value.modInfo.tags))
|
|
126
|
+
|| (value.modInfo.supportedVersion !== undefined && typeof value.modInfo.supportedVersion !== 'string')
|
|
127
|
+
|| (value.modInfo.remoteFileId !== undefined && typeof value.modInfo.remoteFileId !== 'string')
|
|
128
|
+
|| (value.modInfo.dependencies !== undefined && !isStringArray(value.modInfo.dependencies)))) {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
if (value.compatibility !== undefined) {
|
|
132
|
+
if (!isRecord(value.compatibility)
|
|
133
|
+
|| !Array.isArray(value.compatibility.declaredDependencies)
|
|
134
|
+
|| !value.compatibility.declaredDependencies.every(item => isRecord(item) && typeof item.name === 'string' && typeof item.source === 'string')
|
|
135
|
+
|| !Array.isArray(value.compatibility.possibleSoftDependencies)
|
|
136
|
+
|| !value.compatibility.possibleSoftDependencies.every(item => isRecord(item)
|
|
137
|
+
&& typeof item.idOrPrefix === 'string'
|
|
138
|
+
&& typeof item.evidence === 'string'
|
|
139
|
+
&& item.confidence === 'heuristic'
|
|
140
|
+
&& (item.sources === undefined || (isStringArray(item.sources) && item.sources.every(source => ['placeholder', 'ignored_diagnostic', 'definition_stack', 'unresolved_id'].includes(source))))
|
|
141
|
+
&& (item.sampleIds === undefined || isStringArray(item.sampleIds)))
|
|
142
|
+
|| !Array.isArray(value.compatibility.dependencyRoots)
|
|
143
|
+
|| !value.compatibility.dependencyRoots.every(item => isRecord(item) && typeof item.name === 'string' && (item.root === undefined || typeof item.root === 'string') && (item.status === 'resolved' || item.status === 'unresolved') && typeof item.source === 'string')
|
|
144
|
+
|| !isRecord(value.compatibility.loadOrder)
|
|
145
|
+
|| (value.compatibility.loadOrder.source !== 'descriptor_only' && value.compatibility.loadOrder.source !== 'launcher_or_lsp')
|
|
146
|
+
|| (value.compatibility.loadOrder.confidence !== 'partial' && value.compatibility.loadOrder.confidence !== 'active')
|
|
147
|
+
|| !isStringArray(value.compatibility.loadOrder.orderedLayers)
|
|
148
|
+
|| !isStringArray(value.compatibility.loadOrder.warnings)
|
|
149
|
+
|| !isRecord(value.compatibility.coverage)
|
|
150
|
+
|| (value.compatibility.coverage.unresolvedIdInference !== 'not_available' && value.compatibility.coverage.unresolvedIdInference !== 'available')
|
|
151
|
+
|| typeof value.compatibility.coverage.truncated !== 'boolean'
|
|
152
|
+
|| (value.compatibility.coverage.evidenceSources !== undefined && !isStringArray(value.compatibility.coverage.evidenceSources))
|
|
153
|
+
|| (value.compatibility.coverage.unavailableSources !== undefined && !isStringArray(value.compatibility.coverage.unavailableSources)))
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
function readProjectProfileFile(profilePath) {
|
|
159
|
+
try {
|
|
160
|
+
const stat = fs.statSync(profilePath);
|
|
161
|
+
if (!stat.isFile() || stat.size > MAX_PROJECT_PROFILE_BYTES)
|
|
162
|
+
return null;
|
|
163
|
+
const parsed = JSON.parse(fs.readFileSync(profilePath, "utf8"));
|
|
164
|
+
return isProjectProfile(parsed) ? parsed : null;
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function readProjectProfile(workspaceRoot) {
|
|
171
|
+
const profilePath = getProjectProfilePath(workspaceRoot);
|
|
172
|
+
return fs.existsSync(profilePath) ? readProjectProfileFile(profilePath) : null;
|
|
173
|
+
}
|
|
174
|
+
function writeProjectProfile(workspaceRoot, profile) {
|
|
175
|
+
const profilePath = getProjectProfilePath(workspaceRoot);
|
|
176
|
+
fs.mkdirSync(path.dirname(profilePath), { recursive: true });
|
|
177
|
+
fs.writeFileSync(profilePath, `${JSON.stringify(profile, null, 2)}\n`, 'utf8');
|
|
178
|
+
return profilePath;
|
|
179
|
+
}
|
|
180
|
+
function buildProjectProfile(workspaceRoot) {
|
|
181
|
+
const root = path.resolve(workspaceRoot);
|
|
182
|
+
const descriptor = (0, descriptor_1.readDescriptor)(root);
|
|
183
|
+
const projectName = descriptor.name || path.basename(root);
|
|
184
|
+
const hasExtensionSource = fs.existsSync(path.join(root, 'package.json'))
|
|
185
|
+
&& fs.existsSync(path.join(root, 'client', 'extension'));
|
|
186
|
+
const workspaceDetection = (0, workspaceGameDetection_1.classifyWorkspaceRoot)(root, () => undefined);
|
|
187
|
+
const hasModSignals = workspaceDetection.kind === 'mod' || workspaceDetection.kind === 'vanilla';
|
|
188
|
+
const workspaceKind = hasExtensionSource && hasModSignals
|
|
189
|
+
? 'mixed'
|
|
190
|
+
: hasExtensionSource
|
|
191
|
+
? 'extension_source'
|
|
192
|
+
: hasModSignals
|
|
193
|
+
? 'paradox_mod'
|
|
194
|
+
: 'generic';
|
|
195
|
+
const keyDirectories = hasModSignals ? discoverKeyDirectories(root) : [];
|
|
196
|
+
// Prioritize semantic boundary files before the generic directory sample:
|
|
197
|
+
// large mods can otherwise exhaust the cap in alphabetically early common/
|
|
198
|
+
// folders before events or compatibility placeholders are seen.
|
|
199
|
+
const prioritizedScriptFiles = [
|
|
200
|
+
...collectFiles(path.join(root, 'events'), 320, ['.txt']),
|
|
201
|
+
...collectFiles(path.join(root, 'common', 'scripted_triggers'), 160, ['.txt']),
|
|
202
|
+
...collectFiles(path.join(root, 'common', 'scripted_effects'), 80, ['.txt']),
|
|
203
|
+
];
|
|
204
|
+
const scriptFiles = [
|
|
205
|
+
...prioritizedScriptFiles,
|
|
206
|
+
...keyDirectories.flatMap(directory => collectFiles(path.join(root, directory.path), 80, ['.txt'])),
|
|
207
|
+
]
|
|
208
|
+
.filter((file, index, files) => files.indexOf(file) === index)
|
|
209
|
+
.slice(0, 800);
|
|
210
|
+
const namespaceDetails = collectNamespaceDetails(root, scriptFiles);
|
|
211
|
+
const namespaces = namespaceDetails.map(item => item.name);
|
|
212
|
+
const softDependencies = collectSoftDependencies(root, scriptFiles);
|
|
213
|
+
const variablePrefixes = collectVariablePrefixes(scriptFiles);
|
|
214
|
+
const localisation = detectLocalisation(root);
|
|
215
|
+
const game = detectGame(workspaceDetection);
|
|
216
|
+
const vanillaCache = detectVanillaCache(root);
|
|
217
|
+
const warnings = [...localisation.warnings, ...(descriptor.warnings ?? [])];
|
|
218
|
+
const preferredReadTools = [
|
|
219
|
+
'query_project_profile',
|
|
220
|
+
'query_project_knowledge',
|
|
221
|
+
'explore_pdx_project',
|
|
222
|
+
'query_cwt_schema',
|
|
223
|
+
'query_workspace_index',
|
|
224
|
+
'query_localisation_index',
|
|
225
|
+
'go_to_definition',
|
|
226
|
+
'get_pdx_block',
|
|
227
|
+
'document_symbols',
|
|
228
|
+
];
|
|
229
|
+
const profileBase = {
|
|
230
|
+
schemaVersion: 4,
|
|
231
|
+
generatedAt: new Date().toISOString(),
|
|
232
|
+
workspaceRoot: root,
|
|
233
|
+
workspaceKind,
|
|
234
|
+
projectName,
|
|
235
|
+
game,
|
|
236
|
+
modInfo: descriptor.exists ? {
|
|
237
|
+
name: descriptor.name,
|
|
238
|
+
version: descriptor.version,
|
|
239
|
+
tags: descriptor.tags,
|
|
240
|
+
supportedVersion: descriptor.supportedVersion,
|
|
241
|
+
remoteFileId: descriptor.remoteFileId,
|
|
242
|
+
dependencies: descriptor.dependencies,
|
|
243
|
+
} : undefined,
|
|
244
|
+
compatibility: {
|
|
245
|
+
supportedVersion: descriptor.supportedVersion,
|
|
246
|
+
declaredDependencies: (descriptor.dependencies ?? []).map(name => ({ name, source: 'descriptor.mod dependencies' })),
|
|
247
|
+
possibleSoftDependencies: softDependencies,
|
|
248
|
+
dependencyRoots: (descriptor.dependencies ?? []).map(name => ({
|
|
249
|
+
name,
|
|
250
|
+
status: 'unresolved',
|
|
251
|
+
source: 'descriptor.mod declares a display name but not a filesystem root',
|
|
252
|
+
})),
|
|
253
|
+
loadOrder: {
|
|
254
|
+
source: 'descriptor_only',
|
|
255
|
+
confidence: 'partial',
|
|
256
|
+
orderedLayers: ['vanilla', ...(descriptor.dependencies ?? []).map(name => `dependency:${name}`), 'workspace'],
|
|
257
|
+
warnings: descriptor.dependencies?.length
|
|
258
|
+
? ['Descriptor dependency order is declarative evidence only; confirm the active launcher/LSP load order before resolving overrides.']
|
|
259
|
+
: ['No declared dependencies were found; optional soft dependencies still require unresolved-ID evidence.'],
|
|
260
|
+
},
|
|
261
|
+
coverage: {
|
|
262
|
+
unresolvedIdInference: softDependencies.some(item => item.sources?.includes('ignored_diagnostic')) ? 'available' : 'not_available',
|
|
263
|
+
truncated: scriptFiles.length >= 800,
|
|
264
|
+
evidenceSources: Array.from(new Set(softDependencies.flatMap(item => item.sources ?? []))).sort(),
|
|
265
|
+
unavailableSources: ['definition_stack (requires deep CWTools knowledge export)'],
|
|
266
|
+
},
|
|
267
|
+
},
|
|
268
|
+
keyDirectories,
|
|
269
|
+
localisation: {
|
|
270
|
+
roots: localisation.roots,
|
|
271
|
+
languages: localisation.languages,
|
|
272
|
+
defaultLanguage: localisation.defaultLanguage,
|
|
273
|
+
encoding: localisation.encoding,
|
|
274
|
+
encodingByLanguage: localisation.encodingByLanguage,
|
|
275
|
+
sampleFiles: localisation.sampleFiles,
|
|
276
|
+
},
|
|
277
|
+
identifiers: {
|
|
278
|
+
namespaces,
|
|
279
|
+
namespaceDetails,
|
|
280
|
+
variablePrefixes,
|
|
281
|
+
byType: {},
|
|
282
|
+
},
|
|
283
|
+
routing: {
|
|
284
|
+
preferredReadTools,
|
|
285
|
+
avoidPatterns: [
|
|
286
|
+
'Do not broad grep before checking query_project_profile, explore_pdx_project, and query_workspace_index.',
|
|
287
|
+
'Do not invent PDX identifiers, localisation keys, GFX names, or sound names.',
|
|
288
|
+
'Do not write localisation through generic write tools; use write_localisation.',
|
|
289
|
+
],
|
|
290
|
+
},
|
|
291
|
+
validation: {
|
|
292
|
+
lspReady: 'unknown',
|
|
293
|
+
indexStatus: 'unknown',
|
|
294
|
+
vanillaCache: vanillaCache.state,
|
|
295
|
+
vanillaCacheEvidence: vanillaCache.evidence,
|
|
296
|
+
},
|
|
297
|
+
warnings,
|
|
298
|
+
};
|
|
299
|
+
const guidanceCards = buildGuidanceCards(profileBase);
|
|
300
|
+
const efficiencyHints = [
|
|
301
|
+
'Call query_project_profile(section="summary") before broad workspace scans.',
|
|
302
|
+
'Use query_cwt_schema or get_completion_at before inventing common/ entity fields or block shapes.',
|
|
303
|
+
'Use query_project_knowledge for complex cross-subsystem work, then explore_pdx_project/query_workspace_index/go_to_definition for live exact evidence.',
|
|
304
|
+
'Use targeted guidance cards from the profile instead of injecting full project files.',
|
|
305
|
+
'Keep CWTOOLS.md for human-edited rules; use profile.json for machine routing facts.',
|
|
306
|
+
];
|
|
307
|
+
return {
|
|
308
|
+
...profileBase,
|
|
309
|
+
guidanceCards,
|
|
310
|
+
efficiencyHints,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
function queryProjectProfile(workspaceRoot, args = {}) {
|
|
314
|
+
const profilePath = getProjectProfilePath(workspaceRoot);
|
|
315
|
+
try {
|
|
316
|
+
const profile = readProjectProfile(workspaceRoot);
|
|
317
|
+
if (!profile) {
|
|
318
|
+
if (fs.existsSync(profilePath)) {
|
|
319
|
+
return {
|
|
320
|
+
status: 'error',
|
|
321
|
+
profilePath,
|
|
322
|
+
error: 'Project profile is malformed, unreadable, or exceeds the 2 MiB size limit. Call initialize_project in full mode to regenerate it.',
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
status: 'missing',
|
|
327
|
+
profilePath,
|
|
328
|
+
_hint: 'Call initialize_project to generate .cwtools/project/profile.json, then retry query_project_profile.',
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
const section = args.section ?? 'summary';
|
|
332
|
+
const guidanceCard = args.guidance ? getGuidanceCard(profile, args.guidance) : undefined;
|
|
333
|
+
if (section === 'all') {
|
|
334
|
+
return { status: 'ready', profilePath, generatedAt: profile.generatedAt, section, profile, guidanceCard };
|
|
335
|
+
}
|
|
336
|
+
const data = selectProfileSection(profile, section);
|
|
337
|
+
return {
|
|
338
|
+
status: 'ready',
|
|
339
|
+
profilePath,
|
|
340
|
+
generatedAt: profile.generatedAt,
|
|
341
|
+
section,
|
|
342
|
+
summary: buildProfileSummary(profile),
|
|
343
|
+
data,
|
|
344
|
+
guidanceCard,
|
|
345
|
+
_hint: 'Use section="routing", "localisation", "identifiers", or a targeted guidance card for focused context.',
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
catch (e) {
|
|
349
|
+
return {
|
|
350
|
+
status: 'error',
|
|
351
|
+
profilePath,
|
|
352
|
+
error: e instanceof Error ? e.message : String(e),
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function getGuidanceCard(profile, guidance) {
|
|
357
|
+
return profile.guidanceCards[guidance] ?? profile.guidanceCards.implementation ?? '';
|
|
358
|
+
}
|
|
359
|
+
function buildProfileSummary(profile) {
|
|
360
|
+
const dirs = keyDirectoryLines(profile).slice(0, 8).join(', ') || 'none';
|
|
361
|
+
const namespaces = profile.identifiers.namespaces.slice(0, 8).join(', ') || 'none';
|
|
362
|
+
const languages = profile.localisation.languages.join(', ') || 'unknown';
|
|
363
|
+
const supportedVersion = profile.modInfo?.supportedVersion ? ` (${profile.modInfo.supportedVersion})` : '';
|
|
364
|
+
return [
|
|
365
|
+
`Project: ${profile.projectName}`,
|
|
366
|
+
`Kind: ${profile.workspaceKind}`,
|
|
367
|
+
`Game: ${profile.game.displayName}${supportedVersion}`,
|
|
368
|
+
`Key dirs: ${dirs}`,
|
|
369
|
+
`Namespaces: ${namespaces}`,
|
|
370
|
+
`Localisation: ${languages} (${profile.localisation.encoding})`,
|
|
371
|
+
].join('\n');
|
|
372
|
+
}
|
|
373
|
+
/** High-value Stellaris subsystems shown first, then remaining dirs by file count. */
|
|
374
|
+
const HIGH_VALUE_SUBSYSTEMS = [
|
|
375
|
+
'common/inline_scripts',
|
|
376
|
+
'common/scripted_effects',
|
|
377
|
+
'common/scripted_triggers',
|
|
378
|
+
'common/scripted_values',
|
|
379
|
+
'events',
|
|
380
|
+
'common/on_actions',
|
|
381
|
+
'common/situations',
|
|
382
|
+
'common/megastructures',
|
|
383
|
+
'interface',
|
|
384
|
+
'common/special_projects',
|
|
385
|
+
'common/event_chains',
|
|
386
|
+
'common/technologies',
|
|
387
|
+
'common/component_templates',
|
|
388
|
+
'common/section_templates',
|
|
389
|
+
'common/ship_sizes',
|
|
390
|
+
'gfx',
|
|
391
|
+
'sound',
|
|
392
|
+
];
|
|
393
|
+
/** Sort existing key directories: high-value subsystems first, then by file count. */
|
|
394
|
+
function keyDirectoryLines(profile) {
|
|
395
|
+
const existing = profile.keyDirectories.filter(dir => dir.exists);
|
|
396
|
+
const subsystemRank = (pathValue) => {
|
|
397
|
+
const index = HIGH_VALUE_SUBSYSTEMS.indexOf(pathValue);
|
|
398
|
+
return index < 0 ? HIGH_VALUE_SUBSYSTEMS.length : index;
|
|
399
|
+
};
|
|
400
|
+
return existing
|
|
401
|
+
.slice()
|
|
402
|
+
.sort((a, b) => subsystemRank(a.path) - subsystemRank(b.path) || (b.fileCount ?? 0) - (a.fileCount ?? 0) || a.path.localeCompare(b.path))
|
|
403
|
+
.map(dir => dir.path);
|
|
404
|
+
}
|
|
405
|
+
function selectProfileSection(profile, section) {
|
|
406
|
+
switch (section) {
|
|
407
|
+
case 'routing': return profile.routing;
|
|
408
|
+
case 'directories': return profile.keyDirectories;
|
|
409
|
+
case 'localisation': return profile.localisation;
|
|
410
|
+
case 'identifiers': return profile.identifiers;
|
|
411
|
+
case 'validation': return profile.validation;
|
|
412
|
+
case 'compatibility': return {
|
|
413
|
+
...(profile.compatibility ?? {}),
|
|
414
|
+
supportedVersion: profile.compatibility?.supportedVersion ?? profile.modInfo?.supportedVersion,
|
|
415
|
+
remoteFileId: profile.modInfo?.remoteFileId,
|
|
416
|
+
dependencies: profile.modInfo?.dependencies ?? [],
|
|
417
|
+
vanillaCache: profile.validation.vanillaCache,
|
|
418
|
+
vanillaCacheEvidence: profile.validation.vanillaCacheEvidence,
|
|
419
|
+
game: profile.game,
|
|
420
|
+
};
|
|
421
|
+
case 'guidanceCards': return profile.guidanceCards;
|
|
422
|
+
case 'summary':
|
|
423
|
+
default:
|
|
424
|
+
return {
|
|
425
|
+
workspaceKind: profile.workspaceKind,
|
|
426
|
+
projectName: profile.projectName,
|
|
427
|
+
game: profile.game,
|
|
428
|
+
supportedVersion: profile.modInfo?.supportedVersion,
|
|
429
|
+
generatedAt: profile.generatedAt,
|
|
430
|
+
freshness: profile.freshness,
|
|
431
|
+
warnings: profile.warnings ?? [],
|
|
432
|
+
efficiencyHints: profile.efficiencyHints,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
function buildGuidanceCards(profile) {
|
|
437
|
+
const namespaces = profile.identifiers.namespaces.slice(0, 12).join(', ') || 'none detected';
|
|
438
|
+
const languages = profile.localisation.languages.join(', ') || 'unknown';
|
|
439
|
+
const encoding = profile.localisation.encoding;
|
|
440
|
+
const keyDirs = keyDirectoryLines(profile).slice(0, 10).join(', ') || 'none detected';
|
|
441
|
+
return {
|
|
442
|
+
implementation: [
|
|
443
|
+
'Implementation guidance:',
|
|
444
|
+
`- Workspace kind: ${profile.workspaceKind}; game: ${profile.game.displayName}.`,
|
|
445
|
+
`- Key directories: ${keyDirs}.`,
|
|
446
|
+
`- Namespaces: ${namespaces}.`,
|
|
447
|
+
'- Before editing known IDs, prefer explore_pdx_project/query_workspace_index/go_to_definition/get_pdx_block.',
|
|
448
|
+
'- After edits, run get_diagnostics on changed files.',
|
|
449
|
+
].join('\n'),
|
|
450
|
+
planning: [
|
|
451
|
+
'Planning guidance:',
|
|
452
|
+
'- For complex pipelines, query_project_knowledge can supply project patterns, vanilla archetypes, topology, override evidence, and unresolved facts when they materially improve the blueprint.',
|
|
453
|
+
`- Study existing patterns in: ${keyDirs}.`,
|
|
454
|
+
'- Enumerate current TypeDefs and relevant project-graph dependency families before approving a complex pipeline; record only candidates that materially affected the design.',
|
|
455
|
+
'- Use exact vanilla archetypes before inventing cross-type calls or scope flows.',
|
|
456
|
+
`- Existing namespaces: ${namespaces}. Allocate IDs deliberately and record them in the blueprint.`,
|
|
457
|
+
].join('\n'),
|
|
458
|
+
exploration: [
|
|
459
|
+
'Exploration guidance:',
|
|
460
|
+
'- Start with query_project_profile, then explore_pdx_project for a bounded semantic graph.',
|
|
461
|
+
'- Use broad scans only after indexed lookups fail or when the user asks for a full audit.',
|
|
462
|
+
].join('\n'),
|
|
463
|
+
review: [
|
|
464
|
+
'Review guidance:',
|
|
465
|
+
'- Collect diagnostics first, group by rule/category, then inspect representative files.',
|
|
466
|
+
'- Treat cache/rules-sync issues separately from real script defects.',
|
|
467
|
+
'- Verify suspicious missing IDs through at least two independent indexed sources.',
|
|
468
|
+
].join('\n'),
|
|
469
|
+
localisation: [
|
|
470
|
+
'Localisation guidance:',
|
|
471
|
+
`- Languages: ${languages}.`,
|
|
472
|
+
`- Encoding: ${encoding}.`,
|
|
473
|
+
'- Use write_localisation for YML writes; do not patch localisation files with generic write tools.',
|
|
474
|
+
'- Query query_localisation_index before creating keys.',
|
|
475
|
+
].join('\n'),
|
|
476
|
+
assets: [
|
|
477
|
+
'Asset guidance:',
|
|
478
|
+
'- Use find_sprite_candidates/find_sound_candidates with searchContext="both" before replacing asset references.',
|
|
479
|
+
'- Never invent GFX_* or sound names; use verified project or vanilla definitions.',
|
|
480
|
+
'- Check interface, gfx, and sound directories from the profile before scanning everything.',
|
|
481
|
+
].join('\n'),
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
function detectGame(detection) {
|
|
485
|
+
if (detection.gameId) {
|
|
486
|
+
const profile = (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)().find(candidate => candidate.id === detection.gameId);
|
|
487
|
+
if (profile) {
|
|
488
|
+
return {
|
|
489
|
+
id: profile.id,
|
|
490
|
+
displayName: profile.displayName,
|
|
491
|
+
confidence: detection.evidence.some(item => item.includes('profile.json') || item.includes('App ID')) ? 'high' : 'medium',
|
|
492
|
+
evidence: [...detection.evidence],
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (detection.kind === 'mod' || detection.kind === 'vanilla') {
|
|
497
|
+
return { id: 'paradox', displayName: 'Paradox Script', confidence: 'low', evidence: [...detection.evidence, 'Exact game is inconclusive; use generic Paradox capabilities'] };
|
|
498
|
+
}
|
|
499
|
+
return { id: 'unknown', displayName: 'Unknown', confidence: 'low', evidence: detection.evidence.length > 0 ? [...detection.evidence] : ['No Paradox game marker detected'] };
|
|
500
|
+
}
|
|
501
|
+
/** Normalize a language directory/file name to its `l_<tag>` form when possible. */
|
|
502
|
+
function normalizeLanguageTag(value) {
|
|
503
|
+
const trimmed = value.trim();
|
|
504
|
+
if (!trimmed)
|
|
505
|
+
return undefined;
|
|
506
|
+
// Match the final `l_<tag>` segment; a negative lookahead stops greedy
|
|
507
|
+
// consumption across another `l_` marker (e.g. `my_l_cool_l_simp_chinese`).
|
|
508
|
+
const fromName = trimmed.match(/(?:^|_)(l_(?:(?!(?:\b|_)l_)[a-z_])+)(?:\.yml)?$/i)?.[1]?.toLowerCase();
|
|
509
|
+
if (fromName)
|
|
510
|
+
return fromName;
|
|
511
|
+
const directoryTag = trimmed.match(/^(?:l_)?[a-z][a-z_]*$/i);
|
|
512
|
+
if (directoryTag) {
|
|
513
|
+
const raw = directoryTag[0].toLowerCase();
|
|
514
|
+
return raw.startsWith('l_') ? raw : `l_${raw}`;
|
|
515
|
+
}
|
|
516
|
+
return undefined;
|
|
517
|
+
}
|
|
518
|
+
/** Read the declared language header of a localisation file (e.g. `l_english:`). */
|
|
519
|
+
function readLocalisationHeader(filePath) {
|
|
520
|
+
try {
|
|
521
|
+
const buf = fs.readFileSync(filePath);
|
|
522
|
+
const bom = buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf;
|
|
523
|
+
const text = buf.toString('utf8', bom ? 3 : 0);
|
|
524
|
+
const firstLine = text.split(/\r?\n/, 1)[0] ?? '';
|
|
525
|
+
const header = firstLine.match(/^\s*(l_[a-z_]+)\s*:/i)?.[1]?.toLowerCase();
|
|
526
|
+
return { language: header, bom, readable: true };
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
return { bom: false, readable: false };
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
function detectLocalisation(root) {
|
|
533
|
+
const roots = ['localisation', 'localization'].filter(rel => fs.existsSync(path.join(root, rel)));
|
|
534
|
+
const warnings = [];
|
|
535
|
+
const languageFiles = new Map();
|
|
536
|
+
const languageDirectories = new Set();
|
|
537
|
+
for (const rel of roots) {
|
|
538
|
+
const base = path.join(root, rel);
|
|
539
|
+
// 1. Collect every first-level language directory name.
|
|
540
|
+
let entries = [];
|
|
541
|
+
try {
|
|
542
|
+
entries = fs.readdirSync(base, { withFileTypes: true })
|
|
543
|
+
.filter(entry => entry.isDirectory() && !entry.name.startsWith('.'))
|
|
544
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
545
|
+
}
|
|
546
|
+
catch {
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
for (const entry of entries) {
|
|
550
|
+
const language = normalizeLanguageTag(entry.name);
|
|
551
|
+
if (!language)
|
|
552
|
+
continue;
|
|
553
|
+
languageDirectories.add(language);
|
|
554
|
+
// Sample up to three files per language so mixed BOM within one
|
|
555
|
+
// language can be detected instead of being majority-voted away.
|
|
556
|
+
const files = collectFiles(path.join(base, entry.name), 4, ['.yml'])
|
|
557
|
+
.filter(file => path.dirname(file) === path.join(base, entry.name));
|
|
558
|
+
for (const file of files.slice(0, 3)) {
|
|
559
|
+
const bucket = languageFiles.get(language) ?? [];
|
|
560
|
+
bucket.push(file);
|
|
561
|
+
languageFiles.set(language, bucket);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
// 2. Fall back to file-name sampling inside the root.
|
|
565
|
+
if (languageFiles.size === 0) {
|
|
566
|
+
const rootFiles = collectFiles(base, 12, ['.yml'])
|
|
567
|
+
.filter(file => path.dirname(file) === base);
|
|
568
|
+
for (const file of rootFiles) {
|
|
569
|
+
const language = normalizeLanguageTag(path.basename(file));
|
|
570
|
+
if (!language)
|
|
571
|
+
continue;
|
|
572
|
+
const bucket = languageFiles.get(language) ?? [];
|
|
573
|
+
bucket.push(file);
|
|
574
|
+
languageFiles.set(language, bucket);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
const languages = Array.from(new Set([...languageDirectories, ...languageFiles.keys()])).sort();
|
|
579
|
+
const sampleFiles = Array.from(languageFiles.values()).flat().map(file => toRelative(root, file)).sort();
|
|
580
|
+
const samples = languages
|
|
581
|
+
.map(language => ({
|
|
582
|
+
language,
|
|
583
|
+
files: languageFiles.get(language) ?? [],
|
|
584
|
+
}))
|
|
585
|
+
.filter(sample => sample.files.length > 0)
|
|
586
|
+
.flatMap(sample => sample.files.map(file => {
|
|
587
|
+
const header = readLocalisationHeader(file);
|
|
588
|
+
if (header.readable && header.language && header.language !== sample.language) {
|
|
589
|
+
warnings.push(`Localisation file ${toRelative(root, file)} declares header '${header.language}' but sits under a '${sample.language}' name.`);
|
|
590
|
+
}
|
|
591
|
+
if (!header.readable) {
|
|
592
|
+
warnings.push(`Localisation sample ${toRelative(root, file)} could not be read.`);
|
|
593
|
+
}
|
|
594
|
+
return { language: sample.language, file, ...header };
|
|
595
|
+
}));
|
|
596
|
+
// 3. Per-language encoding; mixed BOM inside one language becomes a warning
|
|
597
|
+
// instead of being silently resolved by majority vote.
|
|
598
|
+
const encodingByLanguage = {};
|
|
599
|
+
const languageBomCounts = new Map();
|
|
600
|
+
for (const sample of samples) {
|
|
601
|
+
const counts = languageBomCounts.get(sample.language) ?? { bom: 0, noBom: 0 };
|
|
602
|
+
if (sample.bom)
|
|
603
|
+
counts.bom++;
|
|
604
|
+
else
|
|
605
|
+
counts.noBom++;
|
|
606
|
+
languageBomCounts.set(sample.language, counts);
|
|
607
|
+
}
|
|
608
|
+
for (const [language, counts] of languageBomCounts) {
|
|
609
|
+
const total = counts.bom + counts.noBom;
|
|
610
|
+
if (total === 0)
|
|
611
|
+
continue;
|
|
612
|
+
encodingByLanguage[language] = counts.bom >= counts.noBom ? 'UTF-8 with BOM' : 'UTF-8 without BOM';
|
|
613
|
+
if (counts.bom > 0 && counts.noBom > 0) {
|
|
614
|
+
warnings.push(`Localisation language ${language} mixes BOM and non-BOM files (${counts.bom} BOM / ${counts.noBom} non-BOM); per-language encoding reflects the majority.`);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
let bomCount = 0;
|
|
618
|
+
let noBomCount = 0;
|
|
619
|
+
for (const sample of samples) {
|
|
620
|
+
if (sample.bom)
|
|
621
|
+
bomCount++;
|
|
622
|
+
else
|
|
623
|
+
noBomCount++;
|
|
624
|
+
}
|
|
625
|
+
const dominantEncoding = bomCount + noBomCount > 0
|
|
626
|
+
? (bomCount >= noBomCount ? 'UTF-8 with BOM' : 'UTF-8 without BOM')
|
|
627
|
+
: 'unknown';
|
|
628
|
+
let defaultLanguage;
|
|
629
|
+
if (languages.length === 1) {
|
|
630
|
+
defaultLanguage = languages[0];
|
|
631
|
+
}
|
|
632
|
+
else if (languageBomCounts.size > 0) {
|
|
633
|
+
const totals = [...languageBomCounts.entries()]
|
|
634
|
+
.map(([language, counts]) => ({ language, total: counts.bom + counts.noBom }))
|
|
635
|
+
.sort((a, b) => b.total - a.total || a.language.localeCompare(b.language));
|
|
636
|
+
const top = totals[0];
|
|
637
|
+
const second = totals[1];
|
|
638
|
+
if (top && (!second || top.total > second.total))
|
|
639
|
+
defaultLanguage = top.language;
|
|
640
|
+
}
|
|
641
|
+
return {
|
|
642
|
+
roots,
|
|
643
|
+
languages,
|
|
644
|
+
defaultLanguage,
|
|
645
|
+
encoding: dominantEncoding,
|
|
646
|
+
encodingByLanguage: Object.keys(encodingByLanguage).length > 0 ? encodingByLanguage : undefined,
|
|
647
|
+
sampleFiles,
|
|
648
|
+
warnings,
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
function detectVanillaCache(root) {
|
|
652
|
+
// A bare `.cwtools` directory is not proof of a usable vanilla cache: verify
|
|
653
|
+
// that a serialized cache file or a vanilla data folder is actually present.
|
|
654
|
+
const candidates = [path.join(root, '.cwtools')];
|
|
655
|
+
for (const candidate of candidates) {
|
|
656
|
+
if (!fs.existsSync(candidate))
|
|
657
|
+
continue;
|
|
658
|
+
const cacheFiles = collectFiles(candidate, 8, ['.cwb']);
|
|
659
|
+
if (cacheFiles.length > 0) {
|
|
660
|
+
return { state: 'configured', evidence: toRelative(root, cacheFiles[0]) };
|
|
661
|
+
}
|
|
662
|
+
const vanillaDir = path.join(candidate, 'vanilla');
|
|
663
|
+
if (fs.existsSync(vanillaDir)) {
|
|
664
|
+
const vanillaEntries = collectFiles(vanillaDir, 8, ['.txt', '.yml', '.json']);
|
|
665
|
+
if (vanillaEntries.length > 0) {
|
|
666
|
+
return { state: 'configured', evidence: toRelative(root, vanillaEntries[0]) };
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
const cacheMetadata = path.join(candidate, 'cache.json');
|
|
670
|
+
if (fs.existsSync(cacheMetadata)) {
|
|
671
|
+
return { state: 'configured', evidence: toRelative(root, cacheMetadata) };
|
|
672
|
+
}
|
|
673
|
+
return { state: 'missing', evidence: `${toRelative(root, candidate)} exists but contains no readable vanilla cache` };
|
|
674
|
+
}
|
|
675
|
+
return { state: 'unknown' };
|
|
676
|
+
}
|
|
677
|
+
function discoverKeyDirectories(root) {
|
|
678
|
+
const supportedExtensions = ['.txt', '.gui', '.gfx', '.asset', '.entity', '.yml'];
|
|
679
|
+
const excluded = new Set(['node_modules', 'bin', 'obj', 'release', 'out', 'dist', 'artifacts', 'submodules']);
|
|
680
|
+
const relativePaths = new Set();
|
|
681
|
+
let entries = [];
|
|
682
|
+
try {
|
|
683
|
+
entries = fs.readdirSync(root, { withFileTypes: true })
|
|
684
|
+
.filter(entry => entry.isDirectory() && !entry.name.startsWith('.') && !excluded.has(entry.name.toLowerCase()))
|
|
685
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
686
|
+
}
|
|
687
|
+
catch {
|
|
688
|
+
return [];
|
|
689
|
+
}
|
|
690
|
+
let commonHasSubdirectories = false;
|
|
691
|
+
for (const entry of entries) {
|
|
692
|
+
const absolute = path.join(root, entry.name);
|
|
693
|
+
if (collectFiles(absolute, 1, supportedExtensions).length === 0)
|
|
694
|
+
continue;
|
|
695
|
+
relativePaths.add(entry.name);
|
|
696
|
+
if (entry.name.toLowerCase() !== 'common')
|
|
697
|
+
continue;
|
|
698
|
+
try {
|
|
699
|
+
const childDirectories = fs.readdirSync(absolute, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
700
|
+
for (const child of childDirectories) {
|
|
701
|
+
if (!child.isDirectory() || child.name.startsWith('.'))
|
|
702
|
+
continue;
|
|
703
|
+
const childPath = path.join(absolute, child.name);
|
|
704
|
+
if (collectFiles(childPath, 1, supportedExtensions).length > 0) {
|
|
705
|
+
relativePaths.add(path.join(entry.name, child.name));
|
|
706
|
+
commonHasSubdirectories = true;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
catch {
|
|
711
|
+
// A concurrently removed directory is simply absent from the quick profile.
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return [...relativePaths]
|
|
715
|
+
.sort((a, b) => a.localeCompare(b))
|
|
716
|
+
.map(relativePath => {
|
|
717
|
+
const absolute = path.join(root, relativePath);
|
|
718
|
+
// When `common` is split into subdirectories, count only its direct
|
|
719
|
+
// files so parent and children are not double-counted.
|
|
720
|
+
const fileCount = commonHasSubdirectories && relativePath === 'common'
|
|
721
|
+
? countDirectFiles(absolute, supportedExtensions)
|
|
722
|
+
: collectFiles(absolute, 400, supportedExtensions).length;
|
|
723
|
+
return {
|
|
724
|
+
key: relativePath.replace(/\\/g, '/'),
|
|
725
|
+
path: relativePath.replace(/\\/g, '/'),
|
|
726
|
+
exists: true,
|
|
727
|
+
fileCount,
|
|
728
|
+
};
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
/** Count files directly inside a directory without descending into subdirectories. */
|
|
732
|
+
function countDirectFiles(dir, extensions) {
|
|
733
|
+
const allowed = new Set(extensions.map(ext => ext.toLowerCase()));
|
|
734
|
+
let count = 0;
|
|
735
|
+
try {
|
|
736
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
737
|
+
if (entry.isFile() && !entry.name.startsWith('.') && allowed.has(path.extname(entry.name).toLowerCase()))
|
|
738
|
+
count++;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
catch {
|
|
742
|
+
// Unreadable directory contributes zero direct files.
|
|
743
|
+
}
|
|
744
|
+
return count;
|
|
745
|
+
}
|
|
746
|
+
function collectFiles(dir, maxCount, extensions) {
|
|
747
|
+
const results = [];
|
|
748
|
+
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
|
|
749
|
+
return results;
|
|
750
|
+
const stack = [dir];
|
|
751
|
+
const allowed = extensions ? new Set(extensions.map(ext => ext.toLowerCase())) : undefined;
|
|
752
|
+
while (stack.length > 0 && results.length < maxCount) {
|
|
753
|
+
const current = stack.pop();
|
|
754
|
+
let entries;
|
|
755
|
+
try {
|
|
756
|
+
entries = fs.readdirSync(current, { withFileTypes: true })
|
|
757
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
758
|
+
}
|
|
759
|
+
catch {
|
|
760
|
+
continue;
|
|
761
|
+
}
|
|
762
|
+
for (const entry of entries) {
|
|
763
|
+
if (results.length >= maxCount)
|
|
764
|
+
break;
|
|
765
|
+
if (entry.name.startsWith('.'))
|
|
766
|
+
continue;
|
|
767
|
+
const abs = path.join(current, entry.name);
|
|
768
|
+
if (entry.isDirectory()) {
|
|
769
|
+
if (!['node_modules', 'bin', 'obj', 'release'].includes(entry.name))
|
|
770
|
+
stack.push(abs);
|
|
771
|
+
}
|
|
772
|
+
else if (!allowed || allowed.has(path.extname(entry.name).toLowerCase())) {
|
|
773
|
+
results.push(abs);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
return results;
|
|
778
|
+
}
|
|
779
|
+
function collectNamespaceDetails(root, files) {
|
|
780
|
+
const occurrences = new Map();
|
|
781
|
+
for (const file of files) {
|
|
782
|
+
try {
|
|
783
|
+
const content = fs.readFileSync(file, 'utf8');
|
|
784
|
+
for (const match of content.matchAll(/^namespace\s*=\s*"?([\w.:-]+)"?/gm)) {
|
|
785
|
+
if (!match[1])
|
|
786
|
+
continue;
|
|
787
|
+
const bucket = occurrences.get(match[1]) ?? new Set();
|
|
788
|
+
bucket.add(toRelative(root, file));
|
|
789
|
+
occurrences.set(match[1], bucket);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
catch {
|
|
793
|
+
// Ignore unreadable samples.
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
return [...occurrences.entries()]
|
|
797
|
+
.map(([name, foundFiles]) => {
|
|
798
|
+
const filesForNamespace = [...foundFiles].sort();
|
|
799
|
+
const normalizedPaths = filesForNamespace.map(file => file.toLowerCase());
|
|
800
|
+
let origin = 'workspace_owned';
|
|
801
|
+
let evidence = 'Namespace is declared in ordinary workspace event files.';
|
|
802
|
+
if (normalizedPaths.some(file => /(?:^|\/)(?:compat(?:ibility)?|patch(?:es)?|placeholder|optional)(?:\/|_|\.|$)/.test(file))) {
|
|
803
|
+
origin = 'compatibility';
|
|
804
|
+
evidence = 'Namespace is declared under a compatibility, patch, optional, or placeholder path.';
|
|
805
|
+
}
|
|
806
|
+
else if (normalizedPaths.some(file => /(?:^|\/)(?:override|overrides|overwrite|replace)(?:\/|_|\.|$)/.test(file))) {
|
|
807
|
+
origin = 'vanilla_override';
|
|
808
|
+
evidence = 'Namespace is declared under an explicit override/overwrite path.';
|
|
809
|
+
}
|
|
810
|
+
else if (normalizedPaths.every(file => /(?:^|\/)(?:external|dependency|vendor)(?:\/|_|\.|$)/.test(file))) {
|
|
811
|
+
origin = 'external';
|
|
812
|
+
evidence = 'Namespace is declared only under an external, dependency, or vendor path.';
|
|
813
|
+
}
|
|
814
|
+
return { name, origin, files: filesForNamespace.slice(0, 12), evidence };
|
|
815
|
+
})
|
|
816
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
817
|
+
}
|
|
818
|
+
/** Merge evidence that is available only after the coherent CWTools knowledge
|
|
819
|
+
* export. This keeps quick /init scanning cheap while still classifying
|
|
820
|
+
* definition-stack overrides and unresolved external identifiers. */
|
|
821
|
+
function mergeDeepCompatibilityEvidence(profile, evidence) {
|
|
822
|
+
if (!profile.compatibility)
|
|
823
|
+
return;
|
|
824
|
+
const merged = new Map(profile.compatibility.possibleSoftDependencies.map(item => [item.idOrPrefix, {
|
|
825
|
+
...item,
|
|
826
|
+
sources: new Set(item.sources ?? []),
|
|
827
|
+
sampleIds: new Set(item.sampleIds ?? []),
|
|
828
|
+
}]));
|
|
829
|
+
const workspaceNamespaces = new Set(profile.identifiers.namespaces.map(value => value.toLowerCase()));
|
|
830
|
+
const stringsIn = (value, depth = 0) => {
|
|
831
|
+
if (depth > 4)
|
|
832
|
+
return [];
|
|
833
|
+
if (typeof value === 'string')
|
|
834
|
+
return [value];
|
|
835
|
+
if (Array.isArray(value))
|
|
836
|
+
return value.flatMap(item => stringsIn(item, depth + 1));
|
|
837
|
+
if (isRecord(value))
|
|
838
|
+
return Object.values(value).flatMap(item => stringsIn(item, depth + 1));
|
|
839
|
+
return [];
|
|
840
|
+
};
|
|
841
|
+
const add = (raw, source, sample) => {
|
|
842
|
+
const prefix = dependencyPrefix(raw);
|
|
843
|
+
if (!prefix || (source === 'unresolved_id' && workspaceNamespaces.has(prefix)))
|
|
844
|
+
return;
|
|
845
|
+
const current = merged.get(prefix) ?? {
|
|
846
|
+
idOrPrefix: prefix,
|
|
847
|
+
evidence: '',
|
|
848
|
+
confidence: 'heuristic',
|
|
849
|
+
sources: new Set(),
|
|
850
|
+
sampleIds: new Set(),
|
|
851
|
+
};
|
|
852
|
+
current.sources.add(source);
|
|
853
|
+
if (current.sampleIds.size < 8)
|
|
854
|
+
current.sampleIds.add(sample.slice(0, 200));
|
|
855
|
+
merged.set(prefix, current);
|
|
856
|
+
};
|
|
857
|
+
for (const unresolved of evidence.unresolved ?? []) {
|
|
858
|
+
for (const value of stringsIn(unresolved).filter(value => /^[A-Za-z][A-Za-z0-9_.:-]{2,}$/.test(value)))
|
|
859
|
+
add(value, 'unresolved_id', value);
|
|
860
|
+
}
|
|
861
|
+
for (const stack of evidence.definitionStacks ?? []) {
|
|
862
|
+
const values = stringsIn(stack);
|
|
863
|
+
const serialized = JSON.stringify(stack).toLowerCase();
|
|
864
|
+
for (const value of values.filter(value => /^[A-Za-z][A-Za-z0-9_.:-]{2,}$/.test(value)))
|
|
865
|
+
add(value, 'definition_stack', value);
|
|
866
|
+
profile.identifiers.namespaceDetails = profile.identifiers.namespaceDetails?.map(namespace => {
|
|
867
|
+
const ownsStack = values.some(value => value.toLowerCase() === namespace.name.toLowerCase() || value.toLowerCase().startsWith(`${namespace.name.toLowerCase()}.`));
|
|
868
|
+
if (!ownsStack)
|
|
869
|
+
return namespace;
|
|
870
|
+
if (serialized.includes('workspace') && serialized.includes('vanilla')) {
|
|
871
|
+
return { ...namespace, origin: 'vanilla_override', evidence: 'CWTools definition stack contains both workspace and vanilla layers.' };
|
|
872
|
+
}
|
|
873
|
+
if (serialized.includes('dependency') || serialized.includes('external')) {
|
|
874
|
+
return { ...namespace, origin: 'compatibility', evidence: 'CWTools definition stack links this namespace to a dependency/external layer.' };
|
|
875
|
+
}
|
|
876
|
+
return namespace;
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
profile.compatibility.possibleSoftDependencies = [...merged.values()]
|
|
880
|
+
.map(item => {
|
|
881
|
+
const sources = [...item.sources].sort();
|
|
882
|
+
const sampleIds = [...item.sampleIds].sort();
|
|
883
|
+
return { ...item, sources, sampleIds, evidence: `${sources.join(' + ')} evidence: ${sampleIds.slice(0, 3).join('; ')}` };
|
|
884
|
+
})
|
|
885
|
+
.sort((a, b) => b.sources.length - a.sources.length || a.idOrPrefix.localeCompare(b.idOrPrefix))
|
|
886
|
+
.slice(0, 120);
|
|
887
|
+
const deepSources = [
|
|
888
|
+
...(evidence.unresolved?.length ? ['unresolved_id'] : []),
|
|
889
|
+
...(evidence.definitionStacks?.length ? ['definition_stack'] : []),
|
|
890
|
+
];
|
|
891
|
+
profile.compatibility.coverage = {
|
|
892
|
+
...profile.compatibility.coverage,
|
|
893
|
+
unresolvedIdInference: evidence.unresolved ? 'available' : profile.compatibility.coverage.unresolvedIdInference,
|
|
894
|
+
evidenceSources: Array.from(new Set([...(profile.compatibility.coverage.evidenceSources ?? []), ...deepSources])).sort(),
|
|
895
|
+
unavailableSources: evidence.definitionStacks ? [] : ['definition_stack'],
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
function dependencyPrefix(value) {
|
|
899
|
+
const cleaned = value.trim().replace(/^['"]|['"]$/g, '').toLowerCase();
|
|
900
|
+
const match = cleaned.match(/^([a-z][a-z0-9]{1,15})(?:[_:.-]|$)/)?.[1];
|
|
901
|
+
if (!match || ['is', 'has', 'can', 'set', 'get', 'remove', 'clear', 'country', 'planet', 'ship', 'leader', 'authority', 'technology', 'static'].includes(match))
|
|
902
|
+
return undefined;
|
|
903
|
+
return match;
|
|
904
|
+
}
|
|
905
|
+
/** Infer optional compatibility layers from explicit project-owned evidence only. */
|
|
906
|
+
function collectSoftDependencies(root, scriptFiles) {
|
|
907
|
+
const evidence = new Map();
|
|
908
|
+
const add = (candidate, source, sample) => {
|
|
909
|
+
const prefix = dependencyPrefix(candidate);
|
|
910
|
+
if (!prefix)
|
|
911
|
+
return;
|
|
912
|
+
const bucket = evidence.get(prefix) ?? { sources: new Set(), samples: new Set() };
|
|
913
|
+
bucket.sources.add(source);
|
|
914
|
+
if (bucket.samples.size < 8)
|
|
915
|
+
bucket.samples.add(sample);
|
|
916
|
+
evidence.set(prefix, bucket);
|
|
917
|
+
};
|
|
918
|
+
for (const file of scriptFiles) {
|
|
919
|
+
const relative = toRelative(root, file);
|
|
920
|
+
if (!/(?:placeholder|compat|patch)/i.test(relative))
|
|
921
|
+
continue;
|
|
922
|
+
try {
|
|
923
|
+
const content = fs.readFileSync(file, 'utf8');
|
|
924
|
+
for (const marker of content.matchAll(/^\s*#.*?\|([A-Za-z0-9_/-]{2,80})\|/gm)) {
|
|
925
|
+
for (const token of (marker[1] ?? '').split(/[/|_-]+/))
|
|
926
|
+
add(token, 'placeholder', `${relative}: ${marker[1]}`);
|
|
927
|
+
}
|
|
928
|
+
for (const definition of content.matchAll(/^\s*([A-Za-z][A-Za-z0-9_.:-]{2,})\s*=\s*\{/gm)) {
|
|
929
|
+
if (definition[1])
|
|
930
|
+
add(definition[1], 'placeholder', `${relative}: ${definition[1]}`);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
catch {
|
|
934
|
+
// Unreadable compatibility sample contributes no evidence.
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
const settingsPath = path.join(root, '.vscode', 'settings.json');
|
|
938
|
+
try {
|
|
939
|
+
const raw = fs.readFileSync(settingsPath, 'utf8');
|
|
940
|
+
const settings = JSON.parse(raw);
|
|
941
|
+
if (isRecord(settings)) {
|
|
942
|
+
const ignored = settings['stellarisLanguageServices.ai.ignoredDiagnostics'];
|
|
943
|
+
if (isStringArray(ignored)) {
|
|
944
|
+
for (const item of ignored)
|
|
945
|
+
add(item, 'ignored_diagnostic', `.vscode/settings.json: ${item.slice(0, 120)}`);
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
catch {
|
|
950
|
+
// Settings may be JSONC or absent; quick profile remains deterministic.
|
|
951
|
+
}
|
|
952
|
+
return [...evidence.entries()]
|
|
953
|
+
.filter(([, item]) => item.sources.has('placeholder') || item.sources.has('ignored_diagnostic'))
|
|
954
|
+
.map(([idOrPrefix, item]) => {
|
|
955
|
+
const sources = [...item.sources].sort();
|
|
956
|
+
const sampleIds = [...item.samples].sort();
|
|
957
|
+
return {
|
|
958
|
+
idOrPrefix,
|
|
959
|
+
evidence: `${sources.join(' + ')} evidence: ${sampleIds.slice(0, 3).join('; ')}`,
|
|
960
|
+
confidence: 'heuristic',
|
|
961
|
+
sources,
|
|
962
|
+
sampleIds,
|
|
963
|
+
};
|
|
964
|
+
})
|
|
965
|
+
.sort((a, b) => b.sources.length - a.sources.length || a.idOrPrefix.localeCompare(b.idOrPrefix))
|
|
966
|
+
.slice(0, 80);
|
|
967
|
+
}
|
|
968
|
+
function collectVariablePrefixes(files) {
|
|
969
|
+
const prefixes = new Set();
|
|
970
|
+
for (const file of files) {
|
|
971
|
+
try {
|
|
972
|
+
const content = fs.readFileSync(file, 'utf8');
|
|
973
|
+
for (const match of content.matchAll(/@([A-Za-z_][\w]*)/g)) {
|
|
974
|
+
const prefix = match[1]?.split('_')[0];
|
|
975
|
+
if (prefix && prefix.length > 1)
|
|
976
|
+
prefixes.add(`@${prefix}_`);
|
|
977
|
+
if (prefixes.size >= 30)
|
|
978
|
+
return [...prefixes].sort();
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
catch {
|
|
982
|
+
// Ignore unreadable samples.
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
return [...prefixes].sort();
|
|
986
|
+
}
|
|
987
|
+
function toRelative(root, file) {
|
|
988
|
+
return path.relative(root, file).replace(/\\/g, '/');
|
|
989
|
+
}
|