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,356 @@
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.initializeProjectWithHost = initializeProjectWithHost;
37
+ const crypto = __importStar(require("crypto"));
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const lsp_1 = require("../host/lsp");
41
+ const profileBuilder_1 = require("./profileBuilder");
42
+ const knowledge_1 = require("./knowledge");
43
+ const workspaceDetectionProfiles_1 = require("../generated/workspaceDetectionProfiles");
44
+ const CAPABILITY_VERSIONS = Object.freeze({
45
+ inlineGraph: 3,
46
+ stateFlow: 3,
47
+ overrideResolution: 2,
48
+ interfaceGraph: 2,
49
+ localisationAudit: 3,
50
+ pdxFlow: 4,
51
+ });
52
+ const inFlight = new Map();
53
+ const RELEVANT_EXTENSIONS = new Set(['.txt', '.gfx', '.asset', '.gui', '.yml', '.cwt', '.mod', '.shader', '.fxh']);
54
+ const EXCLUDED_DIRECTORIES = new Set(['.git', '.cwtools', 'node_modules', 'release', 'artifacts', 'dist', 'out']);
55
+ const OBSOLETE_FILES = ['snapshot.json', 'topology.json', 'definition-stacks.json', 'override-map.json', 'unresolved.json'];
56
+ function keyFor(root) {
57
+ const resolved = path.resolve(root);
58
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
59
+ }
60
+ function asRecord(value) {
61
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
62
+ }
63
+ function normalizeStringList(value, max, field) {
64
+ if (value === undefined)
65
+ return undefined;
66
+ if (!Array.isArray(value) || value.length > max || value.some(item => typeof item !== 'string')) {
67
+ throw new Error(field + ' must be a string array with at most ' + max + ' entries');
68
+ }
69
+ return [...new Set(value.map(item => item.trim()).filter(Boolean))].sort();
70
+ }
71
+ function normalizeArgs(args) {
72
+ const mode = args.mode ?? 'full';
73
+ if (mode !== 'full' && mode !== 'incremental')
74
+ throw new Error('mode must be full or incremental');
75
+ const changedFiles = normalizeStringList(args.changedFiles, 500, 'changedFiles') ?? [];
76
+ for (const file of changedFiles) {
77
+ if (path.isAbsolute(file) || file.split(/[\\/]/).includes('..'))
78
+ throw new Error('changedFiles must be workspace-relative paths without ..');
79
+ }
80
+ return { mode, changedFiles, domains: normalizeStringList(args.domains, 64, 'domains') ?? [] };
81
+ }
82
+ function hashParts(parts) {
83
+ return crypto.createHash('sha256').update(parts.join('\n')).digest('hex');
84
+ }
85
+ function collectProjectFacts(root, maxFiles = 10000) {
86
+ const facts = [];
87
+ const stack = [root];
88
+ while (stack.length > 0 && facts.length < maxFiles) {
89
+ const current = stack.pop();
90
+ let entries;
91
+ try {
92
+ entries = fs.readdirSync(current, { withFileTypes: true });
93
+ }
94
+ catch {
95
+ continue;
96
+ }
97
+ entries.sort((a, b) => a.name.localeCompare(b.name));
98
+ for (const entry of entries) {
99
+ if (facts.length >= maxFiles)
100
+ break;
101
+ if (entry.isDirectory() && EXCLUDED_DIRECTORIES.has(entry.name))
102
+ continue;
103
+ const fullPath = path.join(current, entry.name);
104
+ if (entry.isDirectory()) {
105
+ stack.push(fullPath);
106
+ continue;
107
+ }
108
+ if (!entry.isFile() || !RELEVANT_EXTENSIONS.has(path.extname(entry.name).toLowerCase()))
109
+ continue;
110
+ try {
111
+ const stat = fs.statSync(fullPath);
112
+ facts.push(path.relative(root, fullPath).replace(/\\/g, '/') + ':' + stat.size + ':' + stat.mtimeMs);
113
+ }
114
+ catch { /* concurrent disappearance */ }
115
+ }
116
+ }
117
+ return facts.sort();
118
+ }
119
+ function pathFact(target) {
120
+ if (!target)
121
+ return 'missing';
122
+ try {
123
+ const stat = fs.statSync(target);
124
+ return path.resolve(target) + ':' + stat.size + ':' + stat.mtimeMs;
125
+ }
126
+ catch {
127
+ return path.resolve(target) + ':missing';
128
+ }
129
+ }
130
+ function rulesFingerprint(host, graphVersion) {
131
+ return hashParts([
132
+ host.projectGameId ?? 'paradox',
133
+ ...(host.rules?.configDirs ?? []).map(pathFact),
134
+ String(graphVersion ?? ''),
135
+ ]);
136
+ }
137
+ function writeJsonAtomic(filePath, value) {
138
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
139
+ const temporary = filePath + '.tmp-' + process.pid + '-' + Date.now();
140
+ fs.writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n', 'utf8');
141
+ try {
142
+ fs.renameSync(temporary, filePath);
143
+ }
144
+ catch {
145
+ try {
146
+ fs.rmSync(filePath, { force: true });
147
+ }
148
+ catch { /* ignored */ }
149
+ fs.renameSync(temporary, filePath);
150
+ }
151
+ }
152
+ function instructionsTemplate() {
153
+ return [
154
+ '# CWTools Project Instructions',
155
+ '',
156
+ '<!-- User-owned. initialize_project creates this file only when missing and never rewrites it.',
157
+ 'Machine-generated facts live in .cwtools/project/profile.json and .cwtools/project/knowledge/. -->',
158
+ '',
159
+ '## Project Instructions',
160
+ '',
161
+ '<!-- Add stable project conventions, naming rules, and validation requirements here. -->',
162
+ '',
163
+ ].join('\n');
164
+ }
165
+ function manifestPaths(root) {
166
+ const knowledgeRoot = path.join(root, knowledge_1.PROJECT_KNOWLEDGE_RELATIVE_DIR);
167
+ return {
168
+ knowledgeRoot,
169
+ databasePath: path.join(knowledgeRoot, 'knowledge.sqlite'),
170
+ manifestPath: path.join(knowledgeRoot, 'manifest.json'),
171
+ };
172
+ }
173
+ function baseManifest(host, profile, snapshot) {
174
+ const paths = manifestPaths(host.workspaceRoot);
175
+ const projectRoots = snapshot?.projectRoots?.length ? snapshot.projectRoots : [host.workspaceRoot];
176
+ return {
177
+ schemaVersion: knowledge_1.CURRENT_KNOWLEDGE_SCHEMA_VERSION,
178
+ capabilityVersions: { ...CAPABILITY_VERSIONS, ...(snapshot?.capabilityVersions ?? {}) },
179
+ capabilityStatus: Object.fromEntries(Object.keys(CAPABILITY_VERSIONS).map(key => [
180
+ key,
181
+ snapshot?.capabilityStatus?.[key] === 'ready' ? 'ready' : 'unavailable',
182
+ ])),
183
+ generatedAt: new Date(snapshot?.generatedAtUnixMs ?? Date.now()).toISOString(),
184
+ generationMode: snapshot?.generationMode ?? 'full',
185
+ status: snapshot?.status ?? 'unavailable',
186
+ game: snapshot?.game || profile.game.id,
187
+ graphVersion: snapshot?.graphVersion,
188
+ completeExport: snapshot?.completeExport === true,
189
+ projectRoots,
190
+ domains: Array.isArray(snapshot?.domains)
191
+ ? snapshot.domains.map(item => typeof item.id === 'string' ? item.id : '').filter(Boolean).sort()
192
+ : [],
193
+ counts: snapshot?.counts ?? {},
194
+ fingerprints: {
195
+ project: hashParts(projectRoots.sort().flatMap(root => [path.resolve(root), ...collectProjectFacts(root)])),
196
+ vanilla: hashParts([pathFact(host.vanillaCache?.gamePath), pathFact(host.vanillaCache?.cacheFile)]),
197
+ rules: rulesFingerprint(host, snapshot?.graphVersion),
198
+ },
199
+ freshness: snapshot?.freshness,
200
+ baseline: snapshot?.baseline,
201
+ coverage: snapshot?.coverage,
202
+ warnings: snapshot?.warnings ?? [],
203
+ staleReasons: [],
204
+ artifacts: [],
205
+ database: { path: 'knowledge.sqlite', format: 'sqlite', schemaVersion: knowledge_1.CURRENT_KNOWLEDGE_SCHEMA_VERSION },
206
+ _paths: paths,
207
+ };
208
+ }
209
+ function waitForRetry(delay, signal) {
210
+ return new Promise((resolve, reject) => {
211
+ const onAbort = () => {
212
+ clearTimeout(timer);
213
+ reject(signal?.reason instanceof Error ? signal.reason : new Error('Operation cancelled.'));
214
+ };
215
+ const timer = setTimeout(() => {
216
+ signal?.removeEventListener('abort', onAbort);
217
+ resolve();
218
+ }, delay);
219
+ signal?.addEventListener('abort', onAbort, { once: true });
220
+ });
221
+ }
222
+ async function waitForKnowledgeModel(host, signal) {
223
+ const deadline = Date.now() + 120000;
224
+ while (Date.now() < deadline) {
225
+ (0, lsp_1.throwIfAborted)(signal);
226
+ const status = asRecord(await host.lsp.executeCommand('cwtools.ai.getValidationStatus', [], { timeoutMs: 10000, ...(signal ? { signal } : {}) }));
227
+ const loading = asRecord(status.loading);
228
+ const lastError = loading.lastError ?? asRecord(status.runtime).lastError;
229
+ if (lastError)
230
+ throw new Error('CWTools model load failed: ' + String(lastError));
231
+ if (status.modelReadyForKnowledgeExport === true && loading.phase === 'ready')
232
+ return;
233
+ await waitForRetry(500, signal);
234
+ }
235
+ throw new Error('Timed out waiting for the CWTools game model to finish loading.');
236
+ }
237
+ async function exportKnowledge(host, profile, args, signal) {
238
+ await waitForKnowledgeModel(host, signal);
239
+ const paths = manifestPaths(host.workspaceRoot);
240
+ fs.mkdirSync(paths.knowledgeRoot, { recursive: true });
241
+ let lastError;
242
+ for (const delay of [0, 2000, 5000]) {
243
+ (0, lsp_1.throwIfAborted)(signal);
244
+ if (delay > 0)
245
+ await waitForRetry(delay, signal);
246
+ const raw = await host.lsp.executeCommand('cwtools.ai.exportProjectKnowledge', [{
247
+ domains: args.domains,
248
+ changedFiles: args.changedFiles,
249
+ maxDefinitions: 100000,
250
+ maxTopologyFiles: 1200,
251
+ maxEdges: 8000,
252
+ archetypesPerDomain: 8,
253
+ completeExport: true,
254
+ requireReady: true,
255
+ databasePath: paths.databasePath,
256
+ workspaceRoot: path.resolve(host.workspaceRoot),
257
+ vanillaRoot: host.vanillaCache?.gamePath,
258
+ generationMode: args.mode,
259
+ }], { timeoutMs: 600000, ...(signal ? { signal } : {}) });
260
+ if (raw === null || raw === undefined)
261
+ throw new Error('CWTools exportProjectKnowledge returned no response.');
262
+ const snapshot = asRecord(raw);
263
+ if (snapshot.ok === true)
264
+ return snapshot;
265
+ lastError = new Error(snapshot.error || 'CWTools project knowledge export failed.');
266
+ if (snapshot.status !== 'loading' && snapshot.status !== 'stale')
267
+ break;
268
+ }
269
+ throw lastError ?? new Error('CWTools project knowledge export is unavailable.');
270
+ }
271
+ async function performInitialization(host, rawArgs, signal) {
272
+ const args = normalizeArgs(rawArgs);
273
+ const profile = (0, profileBuilder_1.buildProjectProfile)(host.workspaceRoot);
274
+ const hostGame = host.projectGameId;
275
+ if (hostGame && !['paradox', 'unknown', 'cwt'].includes(hostGame) && profile.game.id !== hostGame) {
276
+ const known = (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)().find(candidate => candidate.id === hostGame);
277
+ profile.game = {
278
+ id: hostGame,
279
+ displayName: known?.displayName ?? hostGame,
280
+ confidence: 'high',
281
+ evidence: ['The active host explicitly selected this game.'],
282
+ };
283
+ }
284
+ const profilePath = (0, profileBuilder_1.writeProjectProfile)(host.workspaceRoot, profile);
285
+ const instructionsPath = path.join(host.workspaceRoot, 'CWTOOLS.md');
286
+ const instructionsCreated = !fs.existsSync(instructionsPath);
287
+ if (instructionsCreated)
288
+ fs.writeFileSync(instructionsPath, instructionsTemplate(), 'utf8');
289
+ const paths = manifestPaths(host.workspaceRoot);
290
+ try {
291
+ const snapshot = await exportKnowledge(host, profile, args, signal);
292
+ if (Number(snapshot.schemaVersion) !== knowledge_1.CURRENT_KNOWLEDGE_SCHEMA_VERSION) {
293
+ throw new Error('Obsolete project knowledge schema V' + Number(snapshot.schemaVersion || 0) + '; expected V' + knowledge_1.CURRENT_KNOWLEDGE_SCHEMA_VERSION + '.');
294
+ }
295
+ if (!fs.existsSync(paths.databasePath))
296
+ throw new Error('CWTools reported success but knowledge.sqlite was not created.');
297
+ (0, profileBuilder_1.mergeDeepCompatibilityEvidence)(profile, snapshot);
298
+ const manifest = baseManifest(host, profile, snapshot);
299
+ manifest.artifacts = ['knowledge.sqlite'];
300
+ profile.freshness = {
301
+ knowledgeStatus: snapshot.status === 'ready' || snapshot.status === 'partial' ? snapshot.status : 'unavailable',
302
+ knowledgeGeneratedAt: manifest.generatedAt,
303
+ staleReasons: [],
304
+ };
305
+ (0, profileBuilder_1.writeProjectProfile)(host.workspaceRoot, profile);
306
+ writeJsonAtomic(paths.manifestPath, manifest);
307
+ for (const name of OBSOLETE_FILES) {
308
+ try {
309
+ fs.rmSync(path.join(paths.knowledgeRoot, name), { force: true });
310
+ }
311
+ catch { /* ignored */ }
312
+ }
313
+ return {
314
+ ok: true,
315
+ status: snapshot.status === 'partial' ? 'partial' : 'ready',
316
+ source: 'cwtools-project-init',
317
+ data: { profilePath, instructionsPath, instructionsCreated, databasePath: paths.databasePath, manifestPath: paths.manifestPath, manifest },
318
+ warnings: snapshot.warnings,
319
+ };
320
+ }
321
+ catch (error) {
322
+ (0, lsp_1.throwIfAborted)(signal);
323
+ const message = error instanceof Error ? error.message : String(error);
324
+ const manifest = baseManifest(host, profile);
325
+ manifest.status = 'unavailable';
326
+ manifest.warnings = [message];
327
+ manifest.staleReasons = ['lsp_export_unavailable'];
328
+ writeJsonAtomic(paths.manifestPath, manifest);
329
+ return {
330
+ ok: false,
331
+ status: 'unavailable',
332
+ source: 'cwtools-project-init',
333
+ data: { profilePath, instructionsPath, instructionsCreated, databasePath: paths.databasePath, manifestPath: paths.manifestPath, manifest },
334
+ error: { code: 'project_knowledge_export_unavailable', message },
335
+ nextSteps: ['Wait for the CWTools game model to become ready, then retry initialize_project.'],
336
+ };
337
+ }
338
+ }
339
+ /** Initialize the current host workspace; concurrent calls share one bounded export. */
340
+ async function initializeProjectWithHost(host, rawArgs = {}, context) {
341
+ if (host.projectKind === 'cwt-only') {
342
+ return {
343
+ ok: false,
344
+ status: 'unavailable',
345
+ source: 'cwtools-project-init',
346
+ error: { code: 'tool_not_available_in_cwt_only', message: 'Project knowledge initialization requires a full Paradox game model.' },
347
+ };
348
+ }
349
+ const key = keyFor(host.workspaceRoot);
350
+ const existing = inFlight.get(key);
351
+ if (existing)
352
+ return existing;
353
+ const pending = performInitialization(host, rawArgs, context?.signal).finally(() => { inFlight.delete(key); });
354
+ inFlight.set(key, pending);
355
+ return pending;
356
+ }
@@ -12,4 +12,10 @@ export interface QueryProjectKnowledgeArgs {
12
12
  includeEventGraph?: boolean;
13
13
  limit?: number;
14
14
  }
15
+ export declare const PROJECT_KNOWLEDGE_RELATIVE_DIR: string;
16
+ export declare const CURRENT_KNOWLEDGE_SCHEMA_VERSION = 7;
17
+ export declare const PROJECT_KNOWLEDGE_DATABASE_FILE = "knowledge.sqlite";
18
+ export declare const PROJECT_KNOWLEDGE_MANIFEST_FILE = "manifest.json";
19
+ export declare function getProjectKnowledgeManifestPath(workspaceRoot: string): string;
20
+ export declare function readProjectKnowledgeManifestWithHost(host: HostServices): Promise<Record<string, unknown> | undefined>;
15
21
  export declare function queryProjectKnowledgeWithHost(host: HostServices, args?: QueryProjectKnowledgeArgs): Promise<SharedToolResult>;
@@ -33,10 +33,22 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.PROJECT_KNOWLEDGE_MANIFEST_FILE = exports.PROJECT_KNOWLEDGE_DATABASE_FILE = exports.CURRENT_KNOWLEDGE_SCHEMA_VERSION = exports.PROJECT_KNOWLEDGE_RELATIVE_DIR = void 0;
37
+ exports.getProjectKnowledgeManifestPath = getProjectKnowledgeManifestPath;
38
+ exports.readProjectKnowledgeManifestWithHost = readProjectKnowledgeManifestWithHost;
36
39
  exports.queryProjectKnowledgeWithHost = queryProjectKnowledgeWithHost;
37
40
  const path = __importStar(require("path"));
38
- const KNOWLEDGE_DIR = path.join('.cwtools', 'project', 'knowledge');
39
- const CURRENT_KNOWLEDGE_SCHEMA_VERSION = 7;
41
+ exports.PROJECT_KNOWLEDGE_RELATIVE_DIR = path.join('.cwtools', 'project', 'knowledge');
42
+ exports.CURRENT_KNOWLEDGE_SCHEMA_VERSION = 7;
43
+ exports.PROJECT_KNOWLEDGE_DATABASE_FILE = 'knowledge.sqlite';
44
+ exports.PROJECT_KNOWLEDGE_MANIFEST_FILE = 'manifest.json';
45
+ function getProjectKnowledgeManifestPath(workspaceRoot) {
46
+ return path.join(workspaceRoot, KNOWLEDGE_DIR, exports.PROJECT_KNOWLEDGE_MANIFEST_FILE);
47
+ }
48
+ async function readProjectKnowledgeManifestWithHost(host) {
49
+ return readJson(host, getProjectKnowledgeManifestPath(host.workspaceRoot));
50
+ }
51
+ const KNOWLEDGE_DIR = exports.PROJECT_KNOWLEDGE_RELATIVE_DIR;
40
52
  function asRecord(value) {
41
53
  return value && typeof value === 'object' && !Array.isArray(value)
42
54
  ? value
@@ -72,30 +84,30 @@ async function queryProjectKnowledgeWithHost(host, args = {}) {
72
84
  domains: [],
73
85
  evidence: [],
74
86
  unresolved: [],
75
- _hint: 'Run /init in the VS Code extension and wait for the deep semantic phase to complete.',
87
+ _hint: 'Call initialize_project and wait for the project knowledge export to complete.',
76
88
  },
77
89
  };
78
90
  }
79
91
  const database = asRecord(manifest.database);
80
92
  const foundSchemaVersion = Number(database.schemaVersion ?? manifest.schemaVersion) || 0;
81
- if (Number(manifest.schemaVersion) !== CURRENT_KNOWLEDGE_SCHEMA_VERSION
82
- || foundSchemaVersion !== CURRENT_KNOWLEDGE_SCHEMA_VERSION) {
93
+ if (Number(manifest.schemaVersion) !== exports.CURRENT_KNOWLEDGE_SCHEMA_VERSION
94
+ || foundSchemaVersion !== exports.CURRENT_KNOWLEDGE_SCHEMA_VERSION) {
83
95
  return {
84
96
  ok: false,
85
97
  status: 'stale',
86
98
  source: 'cwtools-project-knowledge-sqlite',
87
99
  error: {
88
100
  code: 'knowledge_schema_obsolete',
89
- message: `Project knowledge schema V${foundSchemaVersion} is obsolete. Rebuild it with the current V${CURRENT_KNOWLEDGE_SCHEMA_VERSION} extension.`,
101
+ message: `Project knowledge schema V${foundSchemaVersion} is obsolete. Rebuild it with the current V${exports.CURRENT_KNOWLEDGE_SCHEMA_VERSION} extension.`,
90
102
  },
91
103
  data: {
92
104
  status: 'stale',
93
105
  manifestPath,
94
106
  rebuildRequired: true,
95
107
  foundSchemaVersion,
96
- currentSchemaVersion: CURRENT_KNOWLEDGE_SCHEMA_VERSION,
108
+ currentSchemaVersion: exports.CURRENT_KNOWLEDGE_SCHEMA_VERSION,
97
109
  staleReasons: ['schema_version_obsolete'],
98
- _hint: 'Run /init or reopen the project and wait for the automatic full rebuild. Old database schemas are not queried.',
110
+ _hint: 'Call initialize_project in full mode to rebuild obsolete knowledge. Old database schemas are not queried.',
99
111
  },
100
112
  };
101
113
  }
@@ -6,10 +6,10 @@ export interface QueryProjectProfileArgs {
6
6
  guidance?: ProjectGuidanceCard;
7
7
  }
8
8
  export interface ProjectProfile {
9
- schemaVersion: 4;
9
+ schemaVersion: typeof PROJECT_PROFILE_SCHEMA_VERSION;
10
10
  generatedAt: string;
11
11
  workspaceRoot: string;
12
- workspaceKind: string;
12
+ workspaceKind: 'paradox_mod' | 'extension_source' | 'mixed' | 'generic';
13
13
  projectName: string;
14
14
  game: {
15
15
  id: string;
@@ -25,6 +25,38 @@ export interface ProjectProfile {
25
25
  remoteFileId?: string;
26
26
  dependencies?: string[];
27
27
  };
28
+ compatibility?: {
29
+ supportedVersion?: string;
30
+ declaredDependencies: Array<{
31
+ name: string;
32
+ source: string;
33
+ }>;
34
+ possibleSoftDependencies: Array<{
35
+ idOrPrefix: string;
36
+ evidence: string;
37
+ confidence: 'heuristic';
38
+ sources?: Array<'placeholder' | 'ignored_diagnostic' | 'definition_stack' | 'unresolved_id'>;
39
+ sampleIds?: string[];
40
+ }>;
41
+ dependencyRoots: Array<{
42
+ name: string;
43
+ root?: string;
44
+ status: 'resolved' | 'unresolved';
45
+ source: string;
46
+ }>;
47
+ loadOrder: {
48
+ source: 'descriptor_only' | 'launcher_or_lsp';
49
+ confidence: 'partial' | 'active';
50
+ orderedLayers: string[];
51
+ warnings: string[];
52
+ };
53
+ coverage: {
54
+ unresolvedIdInference: 'not_available' | 'available';
55
+ truncated: boolean;
56
+ evidenceSources?: string[];
57
+ unavailableSources?: string[];
58
+ };
59
+ };
28
60
  keyDirectories: Array<{
29
61
  key: string;
30
62
  path: string;
@@ -39,15 +71,38 @@ export interface ProjectProfile {
39
71
  encodingByLanguage?: Record<string, string>;
40
72
  sampleFiles: string[];
41
73
  };
42
- identifiers: Record<string, unknown>;
43
- routing: Record<string, unknown>;
44
- validation: Record<string, unknown>;
45
- freshness?: Record<string, unknown>;
74
+ identifiers: {
75
+ namespaces: string[];
76
+ namespaceDetails?: Array<{
77
+ name: string;
78
+ origin: 'workspace_owned' | 'vanilla_override' | 'compatibility' | 'external';
79
+ files: string[];
80
+ evidence: string;
81
+ }>;
82
+ variablePrefixes: string[];
83
+ byType: Record<string, string[]>;
84
+ byTypeCounts?: Record<string, number>;
85
+ };
86
+ routing: {
87
+ preferredReadTools: string[];
88
+ avoidPatterns: string[];
89
+ };
90
+ validation: {
91
+ lspReady: 'unknown' | 'ready' | 'not_ready';
92
+ indexStatus: 'unknown' | 'ready' | 'partial' | 'indexing' | 'idle' | 'unavailable';
93
+ vanillaCache: 'unknown' | 'configured' | 'missing';
94
+ vanillaCacheEvidence?: string;
95
+ };
96
+ freshness?: {
97
+ knowledgeStatus?: 'ready' | 'partial' | 'stale' | 'unavailable';
98
+ knowledgeGeneratedAt?: string;
99
+ staleReasons?: string[];
100
+ };
46
101
  warnings?: string[];
47
102
  guidanceCards: Partial<Record<ProjectGuidanceCard, string>>;
48
103
  efficiencyHints: string[];
49
- [key: string]: unknown;
50
104
  }
105
+ export declare const PROJECT_PROFILE_SCHEMA_VERSION: 4;
51
106
  export declare const PROJECT_PROFILE_RELATIVE_PATH: string;
52
107
  export declare function getProjectProfilePath(workspaceRoot: string): string;
53
108
  export declare function isProjectProfile(value: unknown): value is ProjectProfile;
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.PROJECT_PROFILE_RELATIVE_PATH = void 0;
36
+ exports.PROJECT_PROFILE_RELATIVE_PATH = exports.PROJECT_PROFILE_SCHEMA_VERSION = void 0;
37
37
  exports.getProjectProfilePath = getProjectProfilePath;
38
38
  exports.isProjectProfile = isProjectProfile;
39
39
  exports.buildProfileSummary = buildProfileSummary;
@@ -41,6 +41,7 @@ exports.getGuidanceCard = getGuidanceCard;
41
41
  exports.selectProfileSection = selectProfileSection;
42
42
  exports.queryProjectProfileWithHost = queryProjectProfileWithHost;
43
43
  const path = __importStar(require("path"));
44
+ exports.PROJECT_PROFILE_SCHEMA_VERSION = 4;
44
45
  exports.PROJECT_PROFILE_RELATIVE_PATH = path.join('.cwtools', 'project', 'profile.json');
45
46
  function getProjectProfilePath(workspaceRoot) {
46
47
  return path.join(workspaceRoot, exports.PROJECT_PROFILE_RELATIVE_PATH);
@@ -48,7 +49,7 @@ function getProjectProfilePath(workspaceRoot) {
48
49
  function isProjectProfile(value) {
49
50
  return !!value
50
51
  && typeof value === 'object'
51
- && value.schemaVersion === 4
52
+ && value.schemaVersion === exports.PROJECT_PROFILE_SCHEMA_VERSION
52
53
  && typeof value.projectName === 'string';
53
54
  }
54
55
  function buildProfileSummary(profile) {
@@ -118,7 +119,7 @@ async function queryProjectProfileWithHost(host, args = {}) {
118
119
  data: {
119
120
  status: 'missing',
120
121
  profilePath,
121
- _hint: 'Run /init in the VS Code extension or create .cwtools/project/profile.json, then retry.',
122
+ _hint: 'Call initialize_project to generate .cwtools/project/profile.json, then retry.',
122
123
  },
123
124
  };
124
125
  }
@@ -0,0 +1,31 @@
1
+ import type { ProjectProfile, ProjectGuidanceCard, QueryProjectProfileArgs } from './profile';
2
+ interface QueryProjectProfileResult {
3
+ status: 'ready' | 'missing' | 'error';
4
+ profilePath: string;
5
+ generatedAt?: string;
6
+ section?: string;
7
+ profile?: ProjectProfile;
8
+ summary?: string;
9
+ data?: unknown;
10
+ guidanceCard?: string;
11
+ _hint?: string;
12
+ error?: string;
13
+ }
14
+ export declare const PROJECT_PROFILE_RELATIVE_PATH: string;
15
+ export declare function getProjectProfilePath(workspaceRoot: string): string;
16
+ /** Validate the generated profile before it reaches prompts, LSP, or MCP paths. */
17
+ export declare function isProjectProfile(value: unknown): value is ProjectProfile;
18
+ export declare function readProjectProfile(workspaceRoot: string): ProjectProfile | null;
19
+ export declare function writeProjectProfile(workspaceRoot: string, profile: ProjectProfile): string;
20
+ export declare function buildProjectProfile(workspaceRoot: string): ProjectProfile;
21
+ export declare function queryProjectProfile(workspaceRoot: string, args?: QueryProjectProfileArgs): QueryProjectProfileResult;
22
+ export declare function getGuidanceCard(profile: ProjectProfile, guidance: ProjectGuidanceCard): string;
23
+ export declare function buildProfileSummary(profile: ProjectProfile): string;
24
+ /** Merge evidence that is available only after the coherent CWTools knowledge
25
+ * export. This keeps quick /init scanning cheap while still classifying
26
+ * definition-stack overrides and unresolved external identifiers. */
27
+ export declare function mergeDeepCompatibilityEvidence(profile: ProjectProfile, evidence: {
28
+ unresolved?: Array<Record<string, unknown>>;
29
+ definitionStacks?: Array<Record<string, unknown>>;
30
+ }): void;
31
+ export {};