@yakovlev-i-a/dsh-openfoam-workbench 0.0.0-stage → 0.9.26

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 (56) hide show
  1. package/CHANGELOG.md +683 -0
  2. package/CORE.md +50 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +29 -0
  5. package/README.md +373 -2
  6. package/client.js +48 -0
  7. package/cordis.patch.yml +18 -0
  8. package/icon.png +0 -0
  9. package/lib/buildlib.js +42 -0
  10. package/lib/caselib.js +212 -0
  11. package/lib/core.js +47 -0
  12. package/lib/discover.js +139 -0
  13. package/lib/escalations.js +92 -0
  14. package/lib/explib.js +149 -0
  15. package/lib/impact.js +55 -0
  16. package/lib/index.js +109 -0
  17. package/lib/knowledge.js +108 -0
  18. package/lib/meshlib.js +375 -0
  19. package/lib/needs-input.js +32 -0
  20. package/lib/of-case.js +485 -0
  21. package/lib/of-engine.js +1061 -0
  22. package/lib/paperlib.js +200 -0
  23. package/lib/presentation.js +365 -0
  24. package/lib/registry.js +142 -0
  25. package/lib/routing-guard.js +126 -0
  26. package/lib/runtime.js +580 -0
  27. package/lib/scaffold-cht.js +318 -0
  28. package/lib/scaffold-compressible.js +171 -0
  29. package/lib/scaffold.js +355 -0
  30. package/lib/settings-schema.js +86 -0
  31. package/lib/skills.js +53 -0
  32. package/lib/tools/build.js +90 -0
  33. package/lib/tools/case.js +1082 -0
  34. package/lib/tools/env.js +592 -0
  35. package/lib/tools/experience.js +165 -0
  36. package/lib/tools/mesh.js +408 -0
  37. package/lib/tools/meta.js +95 -0
  38. package/lib/tools/papers.js +105 -0
  39. package/lib/tools/render.js +94 -0
  40. package/lib/tools/run.js +331 -0
  41. package/lib/versions.js +133 -0
  42. package/licenses/dsh-openfoam-doctor-MIT.txt +21 -0
  43. package/locale/en.json +6 -0
  44. package/locale/ru.json +6 -0
  45. package/package.json +44 -4
  46. package/skills/openfoam-analyze/SKILL.md +27 -0
  47. package/skills/openfoam-case-builder/SKILL.md +61 -0
  48. package/skills/openfoam-cht/SKILL.md +83 -0
  49. package/skills/openfoam-code-modify/SKILL.md +32 -0
  50. package/skills/openfoam-mesh-independence/SKILL.md +55 -0
  51. package/skills/openfoam-meshing/SKILL.md +30 -0
  52. package/skills/openfoam-paper-reproduction/SKILL.md +36 -0
  53. package/skills/openfoam-self-evolution/SKILL.md +21 -0
  54. package/skills/openfoam-solver-development/SKILL.md +61 -0
  55. package/skills/openfoam-stats/SKILL.md +46 -0
  56. package/skills/openfoam-viz/SKILL.md +35 -0
@@ -0,0 +1,592 @@
1
+ import { cpSync, existsSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs'
2
+ import { basename, isAbsolute, join } from 'node:path'
3
+ import { bashrcFor, dictEntry, escapeRe, pluginInfo, probeBashrc, readText, resolveCase, resolveCaseInfo, resolveSource, rootFor, run, sourceRoots, stripComments, textOut, walk } from '../runtime.js'
4
+ import { resolveLanguage } from '../discover.js'
5
+ import { scaleGateApplies } from '../needs-input.js'
6
+ import { capsSummary, probeCaps, versionCaps } from '../versions.js'
7
+ import { classifySolver } from '../knowledge.js'
8
+ import { inspectSolverModule, readMakeFiles } from '../buildlib.js'
9
+ import { CASE_FILES, fieldFiles, parseBoundaryPatches, readCaseDict, strayTimeDirs } from '../of-engine.js'
10
+ import { caseBBox, caseRegions, ensureFoamFile, findFoamFile, regionFiles, regionGroups, regionSolvers, zeroDirOf } from '../of-case.js'
11
+
12
+ export default function envTools({ cfg }) {
13
+ return [
14
+ // --- tool: environment check ---
15
+ {
16
+ name: 'openfoam_env_check',
17
+ description: 'Check the OpenFOAM environment. With `distribution` (org|com) checks that one; without it, reports every configured distribution (foamRoots).',
18
+ parameters: {
19
+ type: 'object',
20
+ properties: {
21
+ distribution: { type: 'string', description: 'org | com. Omit to report all configured distributions.' },
22
+ },
23
+ },
24
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
25
+ timeoutMs: 120000,
26
+ isConcurrencySafe: () => true,
27
+ execute: async (args, exec) => {
28
+ const asked = args && args.distribution
29
+ const keys = asked ? [asked] : Object.keys(cfg.foamRoots || {})
30
+ const list = keys.length ? keys : ['']
31
+ const out = []
32
+ for (const key of list) {
33
+ const bash = bashrcFor(cfg, key || '')
34
+ const root = rootFor(cfg, key || '')
35
+ const rep = {
36
+ distribution: key || 'default',
37
+ foamRoot: root || null,
38
+ foamRootExists: !!root && existsSync(root),
39
+ bashrc: bash || null,
40
+ bashrcExists: !!bash && existsSync(bash),
41
+ version: null,
42
+ projectDir: null,
43
+ flavor: null,
44
+ ok: false,
45
+ }
46
+ if (rep.bashrcExists) {
47
+ const r = await probeBashrc(bash, 'echo "$WM_PROJECT_VERSION"; echo "$WM_PROJECT_DIR"; echo "$WM_PROJECT"', { timeoutMs: 20000 })
48
+ const lines = r.stdout.split('\n').map((s) => s.trim())
49
+ rep.version = lines[0] || null
50
+ rep.projectDir = lines[1] || null
51
+ rep.flavor = lines[2] || null
52
+ rep.ok = r.ok && !!rep.version
53
+ }
54
+ rep.distributionKind = rep.version && /^v\d/i.test(rep.version) ? 'com (ESI)' : 'org'
55
+ if (rep.bashrcExists) {
56
+ const caps = await probeCaps(bash, key || '')
57
+ rep.caps = {
58
+ summary: capsSummary(caps),
59
+ support: caps.support,
60
+ modular: caps.modular,
61
+ postProcess: caps.postProcess,
62
+ features: caps.featuresUtility,
63
+ transportFile: caps.transportFile,
64
+ turbulenceFile: caps.turbulenceFile,
65
+ }
66
+ }
67
+ out.push(rep)
68
+ }
69
+ const plugin = { ...pluginInfo(), language: cfg.responseLanguage || resolveLanguage(cfg) }
70
+ if (out.length === 1) return { ...out[0], plugin }
71
+ return { ok: out.every((r) => r.ok), plugin, distributions: out }
72
+ },
73
+ },
74
+ // --- tool: version info ---
75
+ {
76
+ name: 'openfoam_version_info',
77
+ description: 'Return the installed OpenFOAM flavor/version and key paths. Use once per session before solver or source work.',
78
+ parameters: { type: 'object', properties: { refresh: { type: 'boolean' }, distribution: { type: 'string', description: 'org | com' } } },
79
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
80
+ timeoutMs: 60000,
81
+ isConcurrencySafe: () => true,
82
+ execute: async (args, exec) => {
83
+ const bash = bashrcFor(cfg, args && args.distribution)
84
+ if (!bash || !existsSync(bash)) return { ok: false, error: 'bashrc/foamRoot not configured' }
85
+ const r = await probeBashrc(bash, 'echo "$WM_PROJECT_VERSION"; echo "$WM_PROJECT_DIR"; echo "$WM_PROJECT"; echo "$WM_ARCH"', { timeoutMs: 20000 })
86
+ const l = r.stdout.split('\n').map((s) => s.trim())
87
+ const version = l[0] || null
88
+ return {
89
+ ok: r.ok,
90
+ version,
91
+ projectDir: l[1] || null,
92
+ flavor: l[2] || null,
93
+ arch: l[3] || null,
94
+ distribution: version && /^v\d/i.test(version) ? 'com (ESI)' : 'org',
95
+ caps: (() => {
96
+ const caps = versionCaps(version && /^v\d/i.test(version) ? 'com' : 'org', version)
97
+ return { summary: capsSummary(caps), support: caps.support, modular: caps.modular, blockMesh: caps.blockMeshScale, postProcess: caps.postProcess, features: caps.featuresUtility, fieldStats: caps.fieldStats, transportFile: caps.transportFile, turbulenceFile: caps.turbulenceFile, zeroDir: caps.zeroDir }
98
+ })(),
99
+ plugin: pluginInfo(),
100
+ }
101
+ },
102
+ },
103
+ // --- tool: inspect case (read-only) ---
104
+ {
105
+ name: 'openfoam_inspect_case',
106
+ description: 'Inspect an OpenFOAM case: solver, steady/transient, endTime, fields in 0/, patch types, turbulence model. Read-only.',
107
+ parameters: {
108
+ type: 'object',
109
+ properties: {
110
+ casePath: { type: 'string', description: 'Case directory (absolute, or relative to caseRoots[0]).' },
111
+ },
112
+ required: ['casePath'],
113
+ },
114
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
115
+ timeoutMs: 60000,
116
+ isConcurrencySafe: () => true,
117
+ execute: async (args) => {
118
+ const dir = resolveCase(cfg, args && args.casePath)
119
+ if (!dir || !existsSync(dir)) return { ok: false, error: `case not found: ${dir}` }
120
+ const info = {
121
+ ok: true,
122
+ path: dir,
123
+ solver: null,
124
+ steady: null,
125
+ endTime: null,
126
+ deltaT: null,
127
+ fields: [],
128
+ patches: [],
129
+ turbulenceModel: null,
130
+ }
131
+ const cd = readText(join(dir, 'system/controlDict'))
132
+ if (cd) {
133
+ info.solver = dictEntry(cd, 'application') || dictEntry(cd, 'solver')
134
+ info.endTime = dictEntry(cd, 'endTime')
135
+ info.deltaT = dictEntry(cd, 'deltaT')
136
+ }
137
+ const fsText = readText(join(dir, 'system/fvSchemes'))
138
+ if (fsText) {
139
+ const m = stripComments(fsText).match(/ddtSchemes\s*\{([\s\S]*?)\}/)
140
+ info.steady = m ? /steadyState/.test(m[1]) : /steadyState/.test(fsText)
141
+ }
142
+ try {
143
+ info.fields = readdirSync(join(dir, '0')).filter((f) => !f.startsWith('.')).sort()
144
+ } catch {}
145
+ const regions = caseRegions(dir)
146
+ const parsePatches = (rel) => {
147
+ const bnd = readText(join(dir, rel))
148
+ return bnd ? parseBoundaryPatches(bnd).slice(0, 60).map((p) => ({ name: p.name, type: p.type })) : []
149
+ }
150
+ if (regions.length) {
151
+ const solvers = regionSolvers(dir)
152
+ info.multiRegion = true
153
+ info.regions = regions
154
+ info.regionSolvers = solvers
155
+ info.regionGroups = regionGroups(dir)
156
+ info.regionDetails = regions.map((r) => {
157
+ const f = regionFiles(dir, r)
158
+ return {
159
+ region: r,
160
+ solver: solvers[r] || null,
161
+ fields: f.fields,
162
+ systemDicts: f.system,
163
+ constantDicts: f.constant,
164
+ patches: parsePatches(`constant/${r}/polyMesh/boundary`),
165
+ }
166
+ })
167
+ info.fields = [...new Set(info.regionDetails.flatMap((d) => d.fields))].sort()
168
+ info.patches = []
169
+ } else {
170
+ info.fields = (() => { try { const zd = zeroDirOf(dir); return zd ? readdirSync(zd).filter((f) => !f.startsWith('.')).sort() : [] } catch { return [] } })()
171
+ info.patches = parsePatches('constant/polyMesh/boundary')
172
+ }
173
+ const foam = findFoamFile(dir)
174
+ info.foamFile = foam ? basename(foam) : null
175
+ const bbox = caseBBox(dir)
176
+ if (bbox.ok) {
177
+ info.bbox = { min: bbox.min, max: bbox.max, extent: bbox.extent, maxExtent: Number(bbox.maxExtent.toFixed(6)) }
178
+ const askAbove = Number(cfg.scaleAskAbove) || 0
179
+ info.scale = { maxExtent: Number(bbox.maxExtent.toFixed(6)), askAbove, suspicious: scaleGateApplies(bbox.maxExtent, askAbove) }
180
+ }
181
+ const turbFiles = ['constant/momentumTransport', 'constant/turbulenceProperties', 'constant/transportProperties']
182
+ for (const f of turbFiles) {
183
+ const t = readText(join(dir, f))
184
+ if (t) {
185
+ info.turbulenceModel = dictEntry(t, 'model')
186
+ if (info.turbulenceModel) break
187
+ }
188
+ }
189
+ if (!info.turbulenceModel && regions.length) {
190
+ for (const r of regions) {
191
+ for (const f of turbFiles) {
192
+ const t = readText(join(dir, f.replace('constant/', `constant/${r}/`)))
193
+ if (!t) continue
194
+ const model = dictEntry(t, 'model') || (/(^|\n)\s*laminar\s*;/.test(t) ? 'laminar' : null)
195
+ if (model) { info.turbulenceModel = model; break }
196
+ }
197
+ if (info.turbulenceModel) break
198
+ }
199
+ }
200
+ return { ...info, resolvedFrom: (resolveCaseInfo(cfg, args.casePath)).resolvedFrom }
201
+ },
202
+ },
203
+ // --- tool: read native OpenFOAM source (read-only) ---
204
+ {
205
+ name: 'openfoam_read_source',
206
+ description: 'Read a file or list a directory from the OpenFOAM installation (src/, applications/, etc/codeTemplates/) — read-only and outside the workspace. Returns numbered lines with start_line/end_line paging. Use this INSTEAD of cat/ls on the install tree.',
207
+ parameters: {
208
+ type: 'object',
209
+ properties: {
210
+ path: { type: 'string', description: 'Absolute path under foamRoot, or relative to src/.' },
211
+ start_line: { type: 'number' },
212
+ end_line: { type: 'number' },
213
+ max_chars: { type: 'number' },
214
+ },
215
+ required: ['path'],
216
+ },
217
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
218
+ timeoutMs: 60000,
219
+ isConcurrencySafe: () => true,
220
+ execute: async (args) => {
221
+ const r = resolveSource(cfg, args && args.path)
222
+ if (!r.ok) return { ok: false, error: r.error }
223
+ let st
224
+ try { st = statSync(r.path) } catch {
225
+ // A near miss should teach the next call: list files with a similar
226
+ // basename and point at the discovery tool instead of just "not found".
227
+ const stem = basename(String(args.path || '')).replace(/\.[^.]+$/, '').toLowerCase()
228
+ const suggestions = []
229
+ if (stem.length >= 4) {
230
+ for (const root of sourceRoots(cfg)) {
231
+ let n = 0
232
+ walk(root, 6, (file) => {
233
+ if (n >= 5) return
234
+ const name = basename(file).toLowerCase()
235
+ if (name.includes(stem.slice(0, Math.max(4, Math.floor(stem.length * 0.7)))) && suggestions.length < 5) {
236
+ suggestions.push(file)
237
+ n += 1
238
+ }
239
+ })
240
+ if (suggestions.length >= 5) break
241
+ }
242
+ }
243
+ return {
244
+ ok: false,
245
+ error: 'not found: ' + r.path,
246
+ ...(suggestions.length ? { suggestions } : {}),
247
+ hint: 'use openfoam_find_source with kind="source" and a shorter query (e.g. "' + (stem || 'limitedLinear') + '")',
248
+ }
249
+ }
250
+ if (st.isDirectory()) {
251
+ try { return { ok: true, path: r.path, entries: readdirSync(r.path).sort() } } catch (e) { return { ok: false, error: String(e.message || e) } }
252
+ }
253
+ const text = readText(r.path) || ''
254
+ const lines = text.split('\n')
255
+ const s = Math.max(1, Number(args.start_line) || 1)
256
+ const e = Number(args.end_line) ? Math.min(lines.length, Number(args.end_line)) : Math.min(lines.length, s + 399)
257
+ let body = lines.slice(s - 1, e).map((l, i) => `${String(s + i).padStart(6)} ${l}`).join('\n')
258
+ const cap = Math.min(Number(args.max_chars) || 60000, 200000)
259
+ if (body.length > cap) body = body.slice(0, cap) + '\n... (truncated)'
260
+ return { ok: true, path: r.path, start: s, end: e, total: lines.length, text: body }
261
+ },
262
+ },
263
+ // --- tool: search source content ---
264
+ {
265
+ name: 'openfoam_source_search',
266
+ description: 'Search OpenFOAM source content (src/, applications/) by regex or plain text, returning file:line and a snippet. Use this INSTEAD of `grep -r` over $FOAM_SRC to answer "does the solver support X" / "where is it computed". Quote the phrase as it appears in the code (e.g. "does not support LTS"), not as a question.',
267
+ parameters: {
268
+ type: 'object',
269
+ properties: {
270
+ query: { type: 'string' },
271
+ regex: { type: 'boolean' },
272
+ top_k: { type: 'number' },
273
+ file_glob: { type: 'string', description: 'Only files ending with this (e.g. ".C").' },
274
+ },
275
+ required: ['query'],
276
+ },
277
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
278
+ timeoutMs: 300000,
279
+ isConcurrencySafe: () => true,
280
+ execute: async (args) => {
281
+ const q = String(args.query || '')
282
+ if (!q) return { ok: false, error: 'empty query' }
283
+ let re
284
+ try {
285
+ re = args.regex ? new RegExp(q, 'i') : new RegExp(q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')
286
+ } catch (e) {
287
+ return { ok: false, error: 'bad regex: ' + (e.message || e) }
288
+ }
289
+ const topK = Math.min(Number(args.top_k) || 20, 200)
290
+ const hits = []
291
+ const foamRootCfg = rootFor(cfg, '')
292
+ const rel = (file) => (foamRootCfg && file.startsWith(foamRootCfg) ? file.slice(foamRootCfg.length + 1) : file)
293
+ for (const root of sourceRoots(cfg)) {
294
+ if (!existsSync(root)) continue
295
+ walk(root, (file) => {
296
+ if (args.file_glob && !file.endsWith(String(args.file_glob).replace(/^\*/, ''))) return
297
+ if (!/\.(C|H|cc|cpp|hpp|md)$/i.test(file)) return
298
+ let text
299
+ try { text = readFileSync(file, 'utf8') } catch { return }
300
+ if (!re.test(text)) return
301
+ const lines = text.split('\n')
302
+ for (let i = 0; i < lines.length && hits.length < topK; i++) {
303
+ if (re.test(lines[i])) hits.push({ file: rel(file), line: i + 1, text: lines[i].trim().slice(0, 200) })
304
+ }
305
+ return hits.length < topK
306
+ }, 20000)
307
+ if (hits.length >= topK) break
308
+ }
309
+ return { ok: true, count: hits.length, hits }
310
+ },
311
+ },
312
+ // --- tool: find tutorials ---
313
+ {
314
+ name: 'openfoam_find_tutorial',
315
+ description: 'Search the OpenFOAM tutorials/ tree for cases (dirs with system/controlDict) by keyword. Returns candidate paths relative to tutorials/. Use this INSTEAD of browsing tutorials/ with ls/find; pair it with openfoam_clone_tutorial.',
316
+ parameters: {
317
+ type: 'object',
318
+ properties: { query: { type: 'string' }, top_k: { type: 'number' }, distribution: { type: 'string', description: 'org | com' } },
319
+ required: ['query'],
320
+ },
321
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
322
+ timeoutMs: 300000,
323
+ isConcurrencySafe: () => true,
324
+ execute: async (args) => {
325
+ const foamRoot = rootFor(cfg, args.distribution)
326
+ const root = foamRoot ? join(foamRoot, 'tutorials') : ''
327
+ if (!root || !existsSync(root)) return { ok: false, error: 'foamRoot/tutorials not found' }
328
+ const q = String(args.query || '').toLowerCase()
329
+ const topK = Math.min(Number(args.top_k) || 12, 100)
330
+ const out = []
331
+ walk(root, (file) => {
332
+ if (!file.endsWith('/system/controlDict')) return
333
+ const dir = file.slice(0, -'/system/controlDict'.length)
334
+ if (!q || dir.toLowerCase().includes(q)) out.push(dir.slice(root.length + 1))
335
+ return out.length < topK * 4
336
+ }, 200000)
337
+ return { ok: true, count: Math.min(out.length, topK), tutorials: out.slice(0, topK) }
338
+ },
339
+ },
340
+ // --- tool: clone tutorial into workspace ---
341
+ {
342
+ name: 'openfoam_clone_tutorial',
343
+ description: 'Copy a tutorial case into the workspace (caseRoots[0]). tutorial_path may be relative to foamRoot/tutorials or absolute inside it.',
344
+ parameters: {
345
+ type: 'object',
346
+ properties: { tutorial_path: { type: 'string' }, dest: { type: 'string' }, distribution: { type: 'string', description: 'org | com' } },
347
+ required: ['tutorial_path', 'dest'],
348
+ },
349
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
350
+ timeoutMs: 120000,
351
+ isConcurrencySafe: () => false,
352
+ execute: async (args) => {
353
+ const foamRoot = rootFor(cfg, args.distribution)
354
+ const root = foamRoot ? join(foamRoot, 'tutorials') : ''
355
+ if (!root || !existsSync(root)) return { ok: false, error: 'foamRoot/tutorials not found' }
356
+ const src = isAbsolute(args.tutorial_path) ? args.tutorial_path : join(root, args.tutorial_path)
357
+ if (!existsSync(src)) return { ok: false, error: 'tutorial not found: ' + src }
358
+ if (!existsSync(join(src, 'system/controlDict'))) return { ok: false, error: 'not a case (no system/controlDict): ' + src }
359
+ const destRoot = Array.isArray(cfg.caseRoots) && cfg.caseRoots.length ? cfg.caseRoots[0] : process.cwd()
360
+ const dest = isAbsolute(args.dest) ? args.dest : join(destRoot, args.dest)
361
+ if (existsSync(dest)) return { ok: false, error: 'destination exists: ' + dest }
362
+ try { cpSync(src, dest, { recursive: true }) } catch (e) { return { ok: false, error: String(e.message || e) } }
363
+ const foam = ensureFoamFile(dest)
364
+ return { ok: true, tutorial: src, dest, foamFile: foam.ok ? foam.name : null }
365
+ },
366
+ },
367
+ // --- tool: list cases under a directory ---
368
+ {
369
+ name: 'openfoam_list_cases',
370
+ description: 'List OpenFOAM cases under a directory: solver, steady/transient, endTime, fields, stray time dirs, and whether blockMesh/snappy dicts exist.',
371
+ parameters: {
372
+ type: 'object',
373
+ properties: { root: { type: 'string' }, depth: { type: 'number' } },
374
+ required: ['root'],
375
+ },
376
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
377
+ timeoutMs: 120000,
378
+ isConcurrencySafe: () => true,
379
+ execute: async (args) => {
380
+ const root = resolveCase(cfg, args.root)
381
+ if (!root || !existsSync(root)) return { ok: false, error: 'not found: ' + root }
382
+ const depth = Math.max(1, Number(args.depth) || 2)
383
+ const cases = []
384
+ const scan = (dir, d) => {
385
+ let entries
386
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
387
+ for (const e of entries) {
388
+ if (!e.isDirectory()) continue
389
+ if (e.name === '0' || e.name === 'constant' || e.name === 'system' || e.name.startsWith('.')) continue
390
+ const full = join(dir, e.name)
391
+ const cd = readCaseDict(full, CASE_FILES.control)
392
+ if (cd) {
393
+ const schemes = readCaseDict(full, CASE_FILES.schemes)
394
+ const steady = schemes && schemes.ddtSchemes ? /steadyState/.test(String(schemes.ddtSchemes.default ?? '')) : null
395
+ cases.push({
396
+ path: full,
397
+ name: e.name,
398
+ solver: (cd.application ?? cd.solver) ?? null,
399
+ steady,
400
+ endTime: cd.endTime ?? null,
401
+ fields: fieldFiles(full),
402
+ strayTimes: strayTimeDirs(full),
403
+ hasBlockMesh: existsSync(join(full, CASE_FILES.blockMesh)),
404
+ hasSnappy: existsSync(join(full, CASE_FILES.snappyMesh)),
405
+ foamFile: findFoamFile(full) ? 'yes' : null,
406
+ })
407
+ continue
408
+ }
409
+ if (d > 1) scan(full, d - 1)
410
+ }
411
+ }
412
+ scan(root, depth)
413
+ return { ok: true, count: cases.length, cases }
414
+ },
415
+ },
416
+ // --- tool: inspect a solver module ---
417
+ {
418
+ name: 'openfoam_solver_inspect',
419
+ description: 'Inspect an OpenFOAM solver module: Make/files target, main source, includes, fields from createFields.H, loop calls (UEqn/pEqn/controls/CorrectPhi), and risks.',
420
+ parameters: {
421
+ type: 'object',
422
+ properties: { modulePath: { type: 'string' } },
423
+ required: ['modulePath'],
424
+ },
425
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
426
+ timeoutMs: 60000,
427
+ isConcurrencySafe: () => true,
428
+ execute: async (args) => {
429
+ const p = resolveCase(cfg, args.modulePath)
430
+ if (!existsSync(join(p, 'Make/files'))) return { ok: false, error: 'not a module (no Make/files): ' + p }
431
+ return { ok: true, path: p, ...inspectSolverModule(p) }
432
+ },
433
+ },
434
+ // --- tool: clone a native solver into the workspace ---
435
+ {
436
+ name: 'openfoam_clone_solver',
437
+ description: 'Copy a native solver directory into the workspace, rename the main .C to <newName>.C and rewrite Make/files to EXE = $(FOAM_USER_APPBIN)/<newName>. Never edits the installation. Optionally switch a case controlDict.',
438
+ parameters: {
439
+ type: 'object',
440
+ properties: {
441
+ source: { type: 'string', description: 'Solver directory (absolute, usually from find_source kind=solver).' },
442
+ dest: { type: 'string', description: 'Destination directory relative to caseRoots[0].' },
443
+ new_name: { type: 'string' },
444
+ case_path: { type: 'string' },
445
+ },
446
+ required: ['source', 'dest'],
447
+ },
448
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
449
+ timeoutMs: 120000,
450
+ isConcurrencySafe: () => false,
451
+ execute: async (args) => {
452
+ const src = String(args.source || '')
453
+ const destRoot = Array.isArray(cfg.caseRoots) && cfg.caseRoots.length ? cfg.caseRoots[0] : process.cwd()
454
+ const dest = isAbsolute(args.dest) ? args.dest : join(destRoot, args.dest)
455
+ if (!src || !existsSync(src)) return { ok: false, error: 'source not found: ' + src }
456
+ if (existsSync(dest)) return { ok: false, error: 'destination exists: ' + dest }
457
+ const make = readMakeFiles(src)
458
+ if (!make.mainSource) return { ok: false, error: 'source has no main .C in Make/files' }
459
+ const newName = String(args.new_name || basename(dest)).trim()
460
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(newName)) return { ok: false, error: 'bad new_name: ' + newName }
461
+ try { cpSync(src, dest, { recursive: true }) } catch (e) { return { ok: false, error: String(e.message || e) } }
462
+ const oldMain = join(dest, make.mainSource)
463
+ const newMain = join(dest, newName + '.C')
464
+ try {
465
+ if (existsSync(oldMain) && oldMain !== newMain) renameSync(oldMain, newMain)
466
+ } catch (e) {
467
+ return { ok: false, error: 'rename failed: ' + (e.message || e) }
468
+ }
469
+ const mf = join(dest, 'Make/files')
470
+ let text = readText(mf) || ''
471
+ text = text.replace(new RegExp(escapeRe(make.mainSource), 'g'), newName + '.C')
472
+ text = text.replace(/^\s*(EXE|LIB)\s*=\s*\S+/m, `EXE = $(FOAM_USER_APPBIN)/${newName}`)
473
+ try { writeFileSync(mf, text) } catch (e) { return { ok: false, error: 'write Make/files failed: ' + (e.message || e) } }
474
+ if (args.case_path) {
475
+ const caseDir = resolveCase(cfg, args.case_path)
476
+ const cd = readText(join(caseDir, 'system/controlDict'))
477
+ if (cd) {
478
+ const out = cd.replace(/^(\s*(?:application|solver))\s+\S+;/m, `$1 ${newName};`)
479
+ try { writeFileSync(join(caseDir, 'system/controlDict'), out) } catch {}
480
+ }
481
+ }
482
+ return { ok: true, source: src, dest, newName }
483
+ },
484
+ },
485
+ // --- tool: list installed solvers ---
486
+ {
487
+ name: 'openfoam_list_solvers',
488
+ description: 'List the solvers installed in the OpenFOAM distribution (applications/solvers, applications/modules, applications/legacy) with their classified governing family, compressibility and phase count.',
489
+ parameters: {
490
+ type: 'object',
491
+ properties: { filter: { type: 'string', description: 'Optional substring to filter names.' }, distribution: { type: 'string', description: 'org | com' } },
492
+ },
493
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
494
+ timeoutMs: 120000,
495
+ isConcurrencySafe: () => true,
496
+ execute: async (args) => {
497
+ const root = rootFor(cfg, args.distribution)
498
+ if (!root || !existsSync(root)) return { ok: false, error: 'foamRoot not configured' }
499
+ const solvers = []
500
+ const seen = new Set()
501
+ const add = (name, source) => {
502
+ if (seen.has(name)) return
503
+ seen.add(name)
504
+ const cls = classifySolver(name)
505
+ solvers.push({ name, source, governing: cls.governing, compressible: cls.compressible, phases: cls.phases })
506
+ }
507
+ // A solver is a directory with Make/files; intermediate directories are
508
+ // just categories (basic/combustion/heatTransfer/...), so walk recursively.
509
+ const walkSolvers = (dir, rel, depth) => {
510
+ if (depth < 0) return
511
+ let entries
512
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
513
+ for (const e of entries) {
514
+ if (!e.isDirectory() || e.name.startsWith('.')) continue
515
+ const child = join(dir, e.name)
516
+ const childRel = rel ? `${rel}/${e.name}` : e.name
517
+ if (existsSync(join(child, 'Make/files'))) add(e.name, childRel)
518
+ else walkSolvers(child, childRel, depth - 1)
519
+ }
520
+ }
521
+ // applications/modules: every child directory is a modular solver (it may
522
+ // carry Make/files or not, depending on the distribution layout).
523
+ const modulesDir = join(root, 'applications/modules')
524
+ if (existsSync(modulesDir)) {
525
+ for (const e of readdirSync(modulesDir, { withFileTypes: true })) {
526
+ if (e.isDirectory() && e.name !== 'functions' && !e.name.startsWith('.')) add(e.name, 'modules')
527
+ }
528
+ }
529
+ // applications/solvers and applications/legacy: categories above the
530
+ // solver level, so walk down to the directories that hold Make/files.
531
+ for (const base of ['applications/solvers', 'applications/legacy']) {
532
+ const dir = join(root, base)
533
+ if (existsSync(dir)) walkSolvers(dir, base.replace('applications/', ''), 4)
534
+ }
535
+ let out = solvers
536
+ if (args.filter) out = out.filter((s) => s.name.toLowerCase().includes(String(args.filter).toLowerCase()))
537
+ const modular = existsSync(join(root, 'applications/modules'))
538
+ return { ok: true, distribution: modular ? 'org (modular solvers)' : 'com (application solvers)', modular, count: out.length, solvers: out }
539
+ },
540
+ },
541
+ // --- tool: find a native solver or source file by name ---
542
+ {
543
+ name: 'openfoam_find_source',
544
+ description: 'Find a native OpenFOAM solver or source file by name — searches applications/solvers, applications/modules, applications/legacy (directories with Make/files) and/or src/ for paths containing the query. Use this INSTEAD of `find` over the install tree.',
545
+ parameters: {
546
+ type: 'object',
547
+ properties: {
548
+ query: { type: 'string' },
549
+ kind: { type: 'string', enum: ['solver', 'source', 'any'], description: 'Default solver.' },
550
+ top_k: { type: 'number' },
551
+ distribution: { type: 'string', description: 'org | com' },
552
+ },
553
+ required: ['query'],
554
+ },
555
+ output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
556
+ timeoutMs: 120000,
557
+ isConcurrencySafe: () => true,
558
+ execute: async (args) => {
559
+ const root = rootFor(cfg, args.distribution)
560
+ if (!root || !existsSync(root)) return { ok: false, error: 'foamRoot not configured' }
561
+ const q = String(args.query || '').toLowerCase()
562
+ if (!q) return { ok: false, error: 'empty query' }
563
+ const kind = args.kind || 'solver'
564
+ const topK = Math.min(Number(args.top_k) || 10, 50)
565
+ const roots = []
566
+ if (kind === 'solver' || kind === 'any') roots.push(join(root, 'applications'))
567
+ if (kind === 'source' || kind === 'any') roots.push(join(root, 'src'))
568
+ const out = []
569
+ const seen = new Set()
570
+ for (const r of roots) {
571
+ if (!existsSync(r)) continue
572
+ walk(r, (file) => {
573
+ if (out.length >= topK * 3) return false
574
+ const rel = file.slice(root.length + 1)
575
+ if (!rel.toLowerCase().includes(q)) return
576
+ let path
577
+ if (kind === 'solver') {
578
+ if (!file.endsWith('/Make/files')) return
579
+ path = file.slice(0, -'/Make/files'.length)
580
+ } else {
581
+ path = file
582
+ }
583
+ if (seen.has(path)) return
584
+ seen.add(path)
585
+ out.push({ path, name: basename(path) })
586
+ }, 30000)
587
+ }
588
+ return { ok: true, count: Math.min(out.length, topK), candidates: out.slice(0, topK) }
589
+ },
590
+ },
591
+ ]
592
+ }