dsh-unreal-python-api 1.2.0 → 1.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/lib/project.js ADDED
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Read-only project inventory.
3
+ *
4
+ * Two kinds of truth are kept apart and labelled:
5
+ * - what the project *declares* (`.uproject`, `Source/`, `Plugins/`), read from
6
+ * the filesystem without loading the editor;
7
+ * - what the editor *indexed* (asset counts, symbol counts, tags), read from
8
+ * Monolith inside the running editor.
9
+ *
10
+ * When the editor is unreachable the declared half is still returned, and the
11
+ * indexed half is `null` with the exact error. Nothing is invented to fill the
12
+ * gap.
13
+ *
14
+ * @module
15
+ */
16
+
17
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+ import { findProjectFile, readUproject } from './engine.js'
20
+
21
+ /** Files per module before the scan stops counting (a safety bound, not a total). */
22
+ const MODULE_FILE_CAP = 5000
23
+
24
+ /** `.uplugin` files visited below the project's plugins directory. */
25
+ const PLUGIN_SCAN_CAP = 500
26
+
27
+ /** Depth below `Plugins/` that is searched for `.uplugin` files. */
28
+ const PLUGIN_SCAN_DEPTH = 6
29
+
30
+ /**
31
+ * Count source files below a directory, bounded.
32
+ *
33
+ * @param {string} directory
34
+ * @returns {{ files: number, truncated: boolean }}
35
+ */
36
+ function countSourceFiles(directory) {
37
+ let files = 0
38
+ const stack = [{ path: directory, depth: 0 }]
39
+ while (stack.length > 0) {
40
+ const current = stack.pop()
41
+ if (!current) continue
42
+ let entries
43
+ try {
44
+ entries = readdirSync(current.path, { withFileTypes: true })
45
+ } catch {
46
+ continue
47
+ }
48
+ for (const entry of entries) {
49
+ if (entry.isDirectory()) {
50
+ if (current.depth < PLUGIN_SCAN_DEPTH) stack.push({ path: join(current.path, entry.name), depth: current.depth + 1 })
51
+ continue
52
+ }
53
+ if (!entry.isFile()) continue
54
+ if (entry.name.endsWith('.h') || entry.name.endsWith('.cpp') || entry.name.endsWith('.cs')) {
55
+ files += 1
56
+ if (files >= MODULE_FILE_CAP) return { files, truncated: true }
57
+ }
58
+ }
59
+ }
60
+ return { files, truncated: false }
61
+ }
62
+
63
+ /**
64
+ * Count plugin descriptors below `Plugins/`, bounded.
65
+ *
66
+ * @param {string} directory
67
+ */
68
+ function scanPlugins(directory) {
69
+ /** @type {string[]} */
70
+ const names = []
71
+ let truncated = false
72
+ const stack = [{ path: directory, depth: 0 }]
73
+ while (stack.length > 0) {
74
+ const current = stack.pop()
75
+ if (!current) continue
76
+ let entries
77
+ try {
78
+ entries = readdirSync(current.path, { withFileTypes: true })
79
+ } catch {
80
+ continue
81
+ }
82
+ for (const entry of entries) {
83
+ if (entry.isDirectory()) {
84
+ if (current.depth < PLUGIN_SCAN_DEPTH) {
85
+ stack.push({ path: join(current.path, entry.name), depth: current.depth + 1 })
86
+ }
87
+ continue
88
+ }
89
+ if (!entry.isFile() || !entry.name.endsWith('.uplugin')) continue
90
+ names.push(entry.name.replace(/\.uplugin$/, ''))
91
+ if (names.length >= PLUGIN_SCAN_CAP) {
92
+ truncated = true
93
+ return { count: names.length, names, truncated }
94
+ }
95
+ }
96
+ }
97
+ return { count: names.length, names, truncated }
98
+ }
99
+
100
+ /**
101
+ * Split Monolith's `level_index_state` into a state and its detail.
102
+ *
103
+ * @param {unknown} value
104
+ */
105
+ function readIndexHealth(value) {
106
+ if (typeof value !== 'string' || value === '') return null
107
+ const separator = value.indexOf(':')
108
+ if (separator === -1) return { state: value, detail: '' }
109
+ return { state: value.slice(0, separator).trim(), detail: value.slice(separator + 1).trim() }
110
+ }
111
+
112
+ /**
113
+ * Collect the inventory of one project directory.
114
+ *
115
+ * @param {{
116
+ * directory: string,
117
+ * client: ReturnType<import('./monolith.js').createMonolithClient>,
118
+ * }} input
119
+ */
120
+ export async function inspectProject(input) {
121
+ const directory = input.directory
122
+ const file = findProjectFile(directory)
123
+ if (!file) {
124
+ throw new Error(`no .uproject file found in ${directory}`)
125
+ }
126
+ const project = readUproject(file)
127
+
128
+ const sourceRoot = join(directory, 'Source')
129
+ const modules = project.modules.map((module) => {
130
+ // Unreal accepts two source layouts: one directory per module
131
+ // (Source/<Module>/) or the module's files flat in Source/ (Source/<Module>.cpp …).
132
+ const moduleDirectory = join(sourceRoot, module.name)
133
+ if (existsSync(moduleDirectory)) {
134
+ const counted = countSourceFiles(moduleDirectory)
135
+ return {
136
+ name: module.name,
137
+ type: module.type,
138
+ loadingPhase: module.loadingPhase,
139
+ sourceDirectory: moduleDirectory,
140
+ sourceLayout: 'directory',
141
+ sourceFiles: counted.files,
142
+ sourceFilesTruncated: counted.truncated,
143
+ }
144
+ }
145
+ let files = 0
146
+ for (const extension of ['.h', '.cpp', '.cs', '.Build.cs']) {
147
+ if (existsSync(join(sourceRoot, `${module.name}${extension}`))) files += 1
148
+ }
149
+ const flat = files > 0
150
+ return {
151
+ name: module.name,
152
+ type: module.type,
153
+ loadingPhase: module.loadingPhase,
154
+ sourceDirectory: flat ? sourceRoot : null,
155
+ sourceLayout: flat ? 'flat' : null,
156
+ sourceFiles: files,
157
+ sourceFilesTruncated: false,
158
+ }
159
+ })
160
+
161
+ const pluginsDirectory = join(directory, 'Plugins')
162
+ const onDisk = existsSync(pluginsDirectory) ? scanPlugins(pluginsDirectory) : { count: 0, names: [], truncated: false }
163
+ const declared = project.plugins
164
+ const declaredNames = new Set(declared.map((plugin) => plugin.name))
165
+ const unlistedOnDisk = onDisk.names.filter((name) => !declaredNames.has(name))
166
+
167
+ /** @type {{ connected: boolean, projectName: string | null, engineVersion: string | null, serverVersion: string | null, actions: number | null, error: { code: string, message: string } | null }} */
168
+ let editor = {
169
+ connected: false,
170
+ projectName: null,
171
+ engineVersion: null,
172
+ serverVersion: null,
173
+ actions: null,
174
+ error: null,
175
+ }
176
+ /** @type {Record<string, number> | null} */
177
+ let index = null
178
+ /** @type {{ state: string, detail: string } | null} */
179
+ let indexHealth = null
180
+
181
+ try {
182
+ const status = await input.client.status()
183
+ editor = {
184
+ connected: true,
185
+ projectName: typeof status?.project_name === 'string' ? status.project_name : null,
186
+ engineVersion: typeof status?.engine_version === 'string' ? status.engine_version : null,
187
+ serverVersion: typeof status?.version === 'string' ? status.version : null,
188
+ actions: typeof status?.total_actions === 'number' ? status.total_actions : null,
189
+ error: null,
190
+ }
191
+ const stats = await input.client.callReadOnly('project_query', { action: 'get_stats', params: {} })
192
+ const values = stats?.stats
193
+ if (values && typeof values === 'object') {
194
+ index = {}
195
+ for (const [key, value] of Object.entries(values)) {
196
+ if (typeof value === 'number') index[key] = value
197
+ if (key === 'level_index_state') indexHealth = readIndexHealth(value)
198
+ }
199
+ }
200
+ } catch (error) {
201
+ editor.error = {
202
+ code: error?.code ?? 'error',
203
+ message: error instanceof Error ? error.message : String(error),
204
+ }
205
+ index = null
206
+ indexHealth = null
207
+ }
208
+
209
+ return {
210
+ directory,
211
+ project: {
212
+ file: project.file,
213
+ name: (project.file.split(/[\\/]/).pop() ?? '').replace(/\.uproject$/i, ''),
214
+ engineAssociation: project.engineAssociation,
215
+ description: project.description,
216
+ modules,
217
+ },
218
+ plugins: {
219
+ declared,
220
+ onDisk: { count: onDisk.count, truncated: onDisk.truncated, unlisted: unlistedOnDisk },
221
+ },
222
+ editor,
223
+ index,
224
+ indexHealth,
225
+ provenance: {
226
+ modules: 'uproject + Source/',
227
+ plugins: 'uproject + Plugins/*.uplugin',
228
+ contentCounts: editor.connected ? 'monolith index' : null,
229
+ editor: editor.connected ? 'monolith server' : null,
230
+ },
231
+ readOnly: true,
232
+ }
233
+ }
234
+
235
+ /** Re-exported for callers that only need to know whether a path is a directory. */
236
+ export function directoryExists(path) {
237
+ try {
238
+ return statSync(path).isDirectory()
239
+ } catch {
240
+ return false
241
+ }
242
+ }
243
+
244
+ /** Read the `.uproject` text directly (used by tests and callers that verify parsing). */
245
+ export function readProjectText(file) {
246
+ return readFileSync(file, 'utf8')
247
+ }
package/lib/scope.js CHANGED
@@ -104,8 +104,8 @@ export function findProjectRoot(directory, options = {}) {
104
104
 
105
105
  /**
106
106
  * Validate and normalize the scope configuration.
107
- * @param {{ scope?: unknown, workspaces?: unknown, projectMarkers?: unknown }} [input]
108
- * @returns {{ scope: string, workspaces: string[], projectMarkers: string[] }}
107
+ * @param {{ scope?: unknown, workspaces?: unknown, projectMarkers?: unknown, exclude?: unknown }} [input]
108
+ * @returns {{ scope: string, workspaces: string[], projectMarkers: string[], exclude: string[] }}
109
109
  */
110
110
  export function resolveScope(input = {}) {
111
111
  const scope = String(input.scope ?? DEFAULT_SCOPE).trim()
@@ -122,31 +122,44 @@ export function resolveScope(input = {}) {
122
122
  const projectMarkers = (configured.length > 0 ? configured : DEFAULT_PROJECT_MARKERS)
123
123
  .map((marker) => String(marker).trim())
124
124
  .filter((marker) => marker !== '')
125
- return { scope, workspaces, projectMarkers }
125
+ const exclude = (Array.isArray(input.exclude) ? input.exclude : [])
126
+ .map((value) => String(value ?? '').trim())
127
+ .filter((value) => value !== '')
128
+ return { scope, workspaces, projectMarkers, exclude }
126
129
  }
127
130
 
128
131
  /**
129
132
  * Human-readable description of an effective scope, used in the prompt
130
133
  * section so the model knows why the tools may be missing.
131
- * @param {{ scope: string, workspaces: string[], projectMarkers: string[] }} resolved
134
+ * @param {{ scope: string, workspaces: string[], projectMarkers: string[], exclude?: string[] }} resolved
132
135
  * @returns {string}
133
136
  */
134
137
  export function describeScope(resolved) {
135
- if (!resolved || resolved.scope === 'anywhere') return 'every workspace'
136
- if (resolved.scope === 'workspaces') return `a configured workspace (${resolved.workspaces.join(', ')})`
137
- return `an Unreal project (a ${resolved.projectMarkers.join(' or ')} file in the working directory or one of its parents)`
138
+ if (!resolved) return 'every workspace'
139
+ const excluded = Array.isArray(resolved.exclude) ? resolved.exclude : []
140
+ const suffix = excluded.length > 0 ? `, excluding ${excluded.join(', ')}` : ''
141
+ if (resolved.scope === 'anywhere') {
142
+ return excluded.length > 0 ? `every workspace except ${excluded.join(', ')}` : 'every workspace'
143
+ }
144
+ if (resolved.scope === 'workspaces') return `a configured workspace (${resolved.workspaces.join(', ')})${suffix}`
145
+ return `an Unreal project (a ${resolved.projectMarkers.join(' or ')} file in the working directory or one of its parents)${suffix}`
138
146
  }
139
147
 
140
148
  /**
141
- * Whether a directory is admitted by the effective scope.
149
+ * Whether a directory is admitted by the effective scope. An exclusion always
150
+ * wins, in every mode, so a non-Unreal workspace can be kept out by name.
142
151
  * @param {unknown} directory
143
- * @param {{ scope: string, workspaces: string[], projectMarkers: string[] }} resolved
152
+ * @param {{ scope: string, workspaces: string[], projectMarkers: string[], exclude?: string[] }} resolved
144
153
  * @param {{ fs?: { readdirSync: (dir: string) => readonly string[] }, maxDepth?: number }} [options]
145
154
  * @returns {boolean}
146
155
  */
147
156
  export function inScope(directory, resolved, options = {}) {
148
- if (!resolved || resolved.scope === 'anywhere') return true
157
+ if (!resolved) return true
158
+ const excluded = Array.isArray(resolved.exclude) ? resolved.exclude : []
159
+ if (resolved.scope === 'anywhere' && excluded.length === 0) return true
149
160
  if (typeof directory !== 'string' || directory.trim() === '') return false
161
+ if (inWorkspaces(directory, excluded)) return false
162
+ if (resolved.scope === 'anywhere') return true
150
163
  if (resolved.scope === 'workspaces') return inWorkspaces(directory, resolved.workspaces)
151
164
  return Boolean(
152
165
  findProjectRoot(directory, {
@@ -160,7 +173,7 @@ export function inScope(directory, resolved, options = {}) {
160
173
  /**
161
174
  * Build a per-step gate that caches its answer briefly.
162
175
  * @param {{
163
- * resolved: { scope: string, workspaces: string[], projectMarkers: string[] },
176
+ * resolved: { scope: string, workspaces: string[], projectMarkers: string[], exclude?: string[] },
164
177
  * directoryOf: (agent: unknown) => string | undefined,
165
178
  * fs?: { readdirSync: (dir: string) => readonly string[] },
166
179
  * ttlMs?: number,
@@ -178,7 +191,9 @@ export function createScopeGate(options) {
178
191
  scope: resolved.scope,
179
192
  describe: () => describeScope(resolved),
180
193
  admits(agent) {
181
- if (!resolved || resolved.scope === 'anywhere') return true
194
+ if (!resolved) return true
195
+ const excluded = Array.isArray(resolved.exclude) ? resolved.exclude.length : 0
196
+ if (resolved.scope === 'anywhere' && excluded === 0) return true
182
197
  let directory
183
198
  try {
184
199
  directory = directoryOf(agent)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-unreal-python-api",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "description": "Unreal Engine Python API context for DSH agents: symbol inventory listing, symbol search, exact syntax from the Epic docs, and tool scaffolding in four styles (ToolsetRegistry toolset, editor script, MCP tool descriptors, DSH defineTool module).",
6
6
  "license": "MIT",
package/test/smoke.mjs CHANGED
@@ -10,6 +10,8 @@ import assert from 'node:assert/strict'
10
10
  import { listChildren, loadInventory, pageUrl, resolveCacheDir, searchSymbols, summarize } from '../lib/inventory.js'
11
11
  import { readSymbolDoc } from '../lib/docs.js'
12
12
  import { buildToolset } from '../lib/builder.js'
13
+ import { detectEngine } from '../lib/engine.js'
14
+ import { inspectProject } from '../lib/project.js'
13
15
  import { execFileSync } from 'node:child_process'
14
16
  import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
15
17
  import { tmpdir } from 'node:os'
@@ -155,7 +157,9 @@ for (const note of built.notes) console.log(` note: ${note}`)
155
157
  assert.equal(built.unresolved.length, 1, 'the invented symbol is reported, not written')
156
158
  assert.ok(built.unresolved[0].startsWith('unreal.Actor.get_actor_scale3d_nonexistent'), 'the invented symbol is named')
157
159
  assert.ok(built.code.includes('class SmokeTestTools(unreal.ToolsetDefinition)'), 'toolset class emitted')
158
- assert.ok(built.code.includes('@toolset_registry.tool_call'), 'tools are decorated')
160
+ assert.ok(built.code.includes('@tool_call'), 'tools are decorated with the UE 5.8 tool_call decorator')
161
+ assert.ok(built.code.includes('from toolset_registry import tool_call'), 'the generated import matches the shipped module')
162
+ assert.ok(built.code.includes('@tool_call') && !built.code.includes('@toolset_registry.tool_call'), 'no stale registry object decorator')
159
163
  assert.ok(built.code.includes('def read_actor_scale(actor: unreal.Actor) -> unreal.Vector:'), 'annotated signature emitted')
160
164
  assert.ok(built.code.includes('unreal.Actor.get_actor_scale3d https://'), 'verified symbol recorded with its page')
161
165
  assert.ok(built.code.includes('#unreal.Actor.get_actor_scale3d'), 'verified symbol deep-links to its anchor')
@@ -246,6 +250,37 @@ const broken = createScopeGate({
246
250
  assert.equal(broken.admits(agent), false, 'a failing directory lookup rejects instead of throwing')
247
251
  console.log(`scope: ${describeScope(projectScope)}`)
248
252
 
253
+ // --- exclusions: a named workspace is never offered the development tier -----
254
+ const excluded = resolveScope({ scope: 'anywhere', exclude: ['D:\\\\HOPRELAY'] })
255
+ assert.equal(inScope('D:\\\\HOPRELAY', excluded), false, 'an excluded root is not admitted even when scope is anywhere')
256
+ assert.equal(inScope('D:\\\\HOPRELAY\\\\Install', excluded), false, 'an excluded subdirectory is not admitted')
257
+ assert.equal(inScope(TDA, excluded), true, 'other workspaces are still admitted')
258
+ assert.equal(inScope('D:\\\\HOPRELAY2', excluded), true, 'a sibling sharing the prefix stays admitted')
259
+ assert.match(describeScope(excluded), /except D:\\\\HOPRELAY/, 'the prompt text names the exclusion')
260
+
261
+ const includedThenExcluded = resolveScope({
262
+ scope: 'workspaces',
263
+ workspaces: [TDA],
264
+ exclude: [join(TDA, 'Intermediate')],
265
+ })
266
+ assert.equal(inScope(join(TDA, 'Source'), includedThenExcluded), true, 'included paths stay admitted')
267
+ assert.equal(inScope(join(TDA, 'Intermediate'), includedThenExcluded), false, 'an exclusion inside an included root wins')
268
+
269
+ const projectExcluded = resolveScope({ scope: 'unreal-project', exclude: [projectRoot] })
270
+ assert.equal(inScope(nested, projectExcluded), false, 'an exclusion beats Unreal project detection')
271
+
272
+ const noStatGate = createScopeGate({
273
+ resolved: excluded,
274
+ directoryOf: () => 'D:\\\\HOPRELAY',
275
+ fs: {
276
+ readdirSync: () => {
277
+ throw new Error('must not list the disk')
278
+ },
279
+ },
280
+ })
281
+ assert.equal(noStatGate.admits(agent), false, 'an exclusion rejects without listing the disk')
282
+ assert.equal(describeScope(excluded), 'every workspace except D:\\\\HOPRELAY', 'the exclusion is described plainly')
283
+
249
284
  // --- the plugin module itself: exports and configuration defaults -------------
250
285
  // The module imports the host-provided '@deepseek-ai/*' packages, which are not
251
286
  // present on a bare checkout or in CI, so these checks run only where the harness
@@ -308,13 +343,24 @@ function fakeContext(directoryOf) {
308
343
 
309
344
  const openContext = fakeContext(() => TDA)
310
345
  plugin.apply(openContext, plugin.Config({}))
311
- assert.equal(openContext.registered.length, 4, 'default scope registers four tools')
346
+ assert.equal(openContext.registered.length, 6, 'default scope registers six tools')
347
+ const registeredNames = openContext.registered.map((entry) => entry.definition.name)
348
+ for (const expected of [
349
+ 'unreal_python_tools_list',
350
+ 'unreal_python_search',
351
+ 'unreal_python_syntax',
352
+ 'unreal_python_tool_builder',
353
+ 'unreal_engine_detect',
354
+ 'unreal_project_inspect',
355
+ ]) {
356
+ assert.ok(registeredNames.includes(expected), `${expected} is registered`)
357
+ }
312
358
  assert.ok(openContext.registered.every((entry) => entry.options.when === undefined), 'default scope attaches no condition')
313
359
  assert.equal(openContext.sections.length, 1, 'default scope registers one prompt section')
314
360
 
315
361
  const scopedContext = fakeContext((session) => (session.id === 'inside' ? join(TDA, 'Source') : 'D:\\elsewhere'))
316
362
  plugin.apply(scopedContext, plugin.Config({ scope: 'workspaces', workspaces: [TDA] }))
317
- assert.equal(scopedContext.registered.length, 4, 'a scoped install still registers four tools')
363
+ assert.equal(scopedContext.registered.length, 6, 'a scoped install still registers six tools')
318
364
  const gated = scopedContext.registered.filter((entry) => typeof entry.options.when === 'function')
319
365
  assert.equal(gated.length, 1, 'only the development tier is gated')
320
366
  assert.equal(gated[0].definition.name, 'unreal_python_tool_builder', 'the development tier is the tool builder')
@@ -322,7 +368,17 @@ const general = scopedContext.registered
322
368
  .filter((entry) => entry.options.when === undefined)
323
369
  .map((entry) => entry.definition.name)
324
370
  .sort()
325
- assert.deepEqual(general, ['unreal_python_search', 'unreal_python_syntax', 'unreal_python_tools_list'], 'the general tier carries no condition')
371
+ assert.deepEqual(
372
+ general,
373
+ [
374
+ 'unreal_engine_detect',
375
+ 'unreal_project_inspect',
376
+ 'unreal_python_search',
377
+ 'unreal_python_syntax',
378
+ 'unreal_python_tools_list',
379
+ ],
380
+ 'the general tier carries no condition',
381
+ )
326
382
  const condition = gated[0].options.when
327
383
  assert.equal(await condition({ agent: { session: { id: 'inside' } } }), true, 'the condition admits the configured workspace')
328
384
  assert.equal(await condition({ agent: { session: { id: 'outside' } } }), false, 'the condition rejects another workspace')
@@ -330,6 +386,117 @@ assert.match(scopedContext.sections[0].text, /admitted only inside/, 'the prompt
330
386
  console.log('apply(): general tier always on, development tier scoped: OK')
331
387
  }
332
388
 
389
+ // --- engine detection and project inspection, without a running editor --------
390
+ const fixture = mkdtempSync(join(tmpdir(), 'unreal-engine-detect-'))
391
+ const engineRoot = join(fixture, 'UE_5.4')
392
+ mkdirSync(join(engineRoot, 'Engine', 'Build'), { recursive: true })
393
+ writeFileSync(
394
+ join(engineRoot, 'Engine', 'Build', 'Build.version'),
395
+ JSON.stringify({ MajorVersion: 5, MinorVersion: 4, PatchVersion: 4, Changelist: 35576357, BranchName: '++UE5+Release-5.4' }),
396
+ )
397
+ const launcherManifest = join(fixture, 'LauncherInstalled.dat')
398
+ writeFileSync(
399
+ launcherManifest,
400
+ JSON.stringify({ InstallationList: [{ InstallLocation: engineRoot, AppName: 'UE_5.4', AppVersion: '5.4.4-35576357' }] }),
401
+ )
402
+ const projectDir = join(fixture, 'ShopifyApp')
403
+ mkdirSync(join(projectDir, 'Source', 'ShopifyApp'), { recursive: true })
404
+ writeFileSync(
405
+ join(projectDir, 'ShopifyApp.uproject'),
406
+ JSON.stringify({
407
+ FileVersion: 3,
408
+ EngineAssociation: '5.4',
409
+ Modules: [{ Name: 'ShopifyApp', Type: 'Runtime' }],
410
+ Plugins: [{ Name: 'PythonScriptPlugin' }, { Name: 'DisabledThing', Enabled: false }],
411
+ }),
412
+ )
413
+ writeFileSync(join(projectDir, 'Source', 'ShopifyApp', 'ShopifyApp.h'), '// header\n')
414
+ writeFileSync(join(projectDir, 'Source', 'ShopifyApp', 'ShopifyApp.cpp'), '// source\n')
415
+ mkdirSync(join(projectDir, 'Plugins', 'LocalThing'), { recursive: true })
416
+ writeFileSync(join(projectDir, 'Plugins', 'LocalThing', 'LocalThing.uplugin'), '{}')
417
+
418
+ /** A Monolith client that cannot connect: every call reports the connection error. */
419
+ function offlineClient() {
420
+ const refuse = async () => {
421
+ throw Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:9316'), { code: 'disconnected' })
422
+ }
423
+ return { status: refuse, callTool: refuse, callReadOnly: refuse }
424
+ }
425
+
426
+ const detected = await detectEngine({
427
+ directory: projectDir,
428
+ engines: { '5.4': engineRoot },
429
+ launcherManifestPath: launcherManifest,
430
+ client: offlineClient(),
431
+ docBaseUrl: DOC_BASE_URL,
432
+ })
433
+ assert.equal(detected.project.engineAssociation, '5.4', 'the association is reported as written in the .uproject')
434
+ assert.equal(detected.installation.path, engineRoot, 'the installation resolves from the launcher manifest entry')
435
+ assert.ok(/^5\.4/.test(detected.installation.build.version), `the installation build version is read, saw ${detected.installation.build.version}`)
436
+ assert.equal(detected.editor.connected, false, 'an unreachable editor is reported, not invented')
437
+ assert.equal(detected.editor.error.code, 'disconnected', 'the connection error is preserved')
438
+ assert.equal(detected.documentation.status, 'unavailable_for_version', 'a 5.4 project has no published Python API inventory')
439
+ assert.ok(detected.documentation.note.includes('5.8'), 'the note names the version that does have documentation')
440
+ assert.deepEqual(detected.conflicts, [], 'agreeing sources report no conflict')
441
+ console.log(' engine: 5.4 project, 5.4 installation, editor unreachable, documentation unavailable_for_version: OK')
442
+
443
+ const conflicted = await detectEngine({
444
+ directory: projectDir,
445
+ engines: { '5.4': engineRoot },
446
+ launcherManifestPath: launcherManifest,
447
+ client: { status: async () => ({ engine_version: '++UE5+Release-5.8-CL-58902052', project_name: 'ShopifyApp', version: '0.25.0', total_actions: 1570 }) },
448
+ docBaseUrl: DOC_BASE_URL,
449
+ })
450
+ assert.ok(conflicted.conflicts.length > 0, 'a 5.4 project with a 5.8 editor reports a conflict')
451
+ assert.equal(conflicted.editor.version, '5.8', 'the editor keeps its own version value')
452
+ assert.ok(/^5\.4/.test(conflicted.installation.build.version), 'the installation keeps its own version value')
453
+ console.log(` engine conflict reported: ${conflicted.conflicts.join(' | ')}`)
454
+
455
+ const inspected = await inspectProject({ directory: projectDir, client: offlineClient() })
456
+ assert.equal(inspected.project.modules[0].name, 'ShopifyApp', 'the declared module is reported')
457
+ assert.equal(inspected.project.modules[0].sourceFiles, 2, 'the module source files are counted')
458
+ assert.equal(inspected.project.modules[0].sourceLayout, 'directory', 'the per-module directory layout is reported')
459
+ assert.equal(inspected.project.modules[0].sourceDirectory, join(projectDir, 'Source', 'ShopifyApp'), 'the module source directory is reported')
460
+ assert.equal(inspected.plugins.onDisk.count, 1, 'the local plugin descriptor is found')
461
+ assert.deepEqual(inspected.plugins.onDisk.unlisted, ['LocalThing'], 'a plugin on disk that the .uproject does not declare is reported')
462
+ assert.equal(inspected.editor.connected, false, 'the editor half reports the connection error')
463
+ assert.equal(inspected.index, null, 'no indexed counts are reported without an editor')
464
+ assert.equal(inspected.readOnly, true, 'the inventory is read-only')
465
+ console.log(' project: declared modules/plugins counted, no indexed counts without an editor: OK')
466
+
467
+ const fakeEditor = {
468
+ status: async () => ({
469
+ project_name: 'ShopifyApp',
470
+ engine_version: '++UE5+Release-5.8-CL-58902052',
471
+ version: '0.25.0',
472
+ total_actions: 1570,
473
+ }),
474
+ callReadOnly: async () => ({
475
+ success: true,
476
+ stats: { assets: 12, nodes: 34, tags: 5, level_index_state: 'degraded: processed 1/2 levels' },
477
+ }),
478
+ }
479
+ const indexed = await inspectProject({ directory: projectDir, client: fakeEditor })
480
+ assert.equal(indexed.index.assets, 12, 'indexed asset count comes from Monolith')
481
+ assert.equal(indexed.index.tags, 5, 'indexed tag count comes from Monolith')
482
+ assert.deepEqual(indexed.indexHealth, { state: 'degraded', detail: 'processed 1/2 levels' }, 'the index health degrades verbatim')
483
+ assert.equal(indexed.provenance.contentCounts, 'monolith index', 'the indexed half is labelled with its provenance')
484
+ console.log(' project: indexed counts and health separated from declared facts: OK')
485
+
486
+ // A module may also live flat in Source/ (Source/<Module>.cpp), which is how TDA
487
+ // itself is laid out; the count must follow the layout the project uses.
488
+ const flatProject = join(fixture, 'FlatProject')
489
+ mkdirSync(join(flatProject, 'Source'), { recursive: true })
490
+ writeFileSync(join(flatProject, 'FlatProject.uproject'), JSON.stringify({ FileVersion: 3, EngineAssociation: '5.8', Modules: [{ Name: 'FlatProject', Type: 'Runtime' }] }))
491
+ writeFileSync(join(flatProject, 'Source', 'FlatProject.cpp'), '// source\n')
492
+ writeFileSync(join(flatProject, 'Source', 'FlatProject.h'), '// header\n')
493
+ writeFileSync(join(flatProject, 'Source', 'FlatProject.Build.cs'), '// build\n')
494
+ const flatInspected = await inspectProject({ directory: flatProject, client: offlineClient() })
495
+ assert.equal(flatInspected.project.modules[0].sourceLayout, 'flat', 'a flat Source/ layout is detected')
496
+ assert.equal(flatInspected.project.modules[0].sourceFiles, 3, 'flat module files are counted')
497
+ assert.equal(flatInspected.project.modules[0].sourceDirectory, join(flatProject, 'Source'), 'the flat layout reports the Source directory')
498
+ console.log(' project: flat Source/ layout counted too: OK')
499
+
333
500
  // --- every generated artifact must parse in its own language -------------------
334
501
  console.log('parse checks:')
335
502
  assertParses('toolset module', built.code, 'py')