@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,1061 @@
1
+ // dsh-openfoam-doctor engine: an OpenFOAM dictionary parser plus the checks
2
+ // that catch the failures which do not announce themselves.
3
+ //
4
+ // The OpenFOAM dict format is not JSON and not YAML: C-style /* */ and //
5
+ // comments, nested braces, bare tokens as values, quoted keys like
6
+ // "(U|k|epsilon)", and a banner header of escaped backslashes. A generic
7
+ // parser either chokes on the banner or silently drops entries, so this one
8
+ // strips comments first, then walks braces while tracking a key stack.
9
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+ import { classifySolver } from './knowledge.js'
12
+
13
+ // =====================================================================
14
+ // Dictionary parsing
15
+ // =====================================================================
16
+
17
+ // Remove block and line comments without touching strings or the banner.
18
+ // (The banner contains escaped backslashes, so a naive strip would eat it.)
19
+ function stripComments(text) {
20
+ let out = ''
21
+ let i = 0
22
+ let inString = false
23
+ while (i < text.length) {
24
+ const c = text[i]
25
+ if (inString) {
26
+ out += c
27
+ if (c === '\\' && i + 1 < text.length) {
28
+ out += text[i + 1]
29
+ i += 2
30
+ continue
31
+ }
32
+ if (c === '"') inString = false
33
+ i++
34
+ continue
35
+ }
36
+ if (c === '"') {
37
+ inString = true
38
+ out += c
39
+ i++
40
+ continue
41
+ }
42
+ if (c === '/' && text[i + 1] === '*') {
43
+ const end = text.indexOf('*/', i + 2)
44
+ i = end === -1 ? text.length : end + 2
45
+ out += ' '
46
+ continue
47
+ }
48
+ if (c === '/' && text[i + 1] === '/') {
49
+ const end = text.indexOf('\n', i)
50
+ i = end === -1 ? text.length : end
51
+ out += '\n'
52
+ continue
53
+ }
54
+ out += c
55
+ i++
56
+ }
57
+ return out
58
+ }
59
+
60
+ /**
61
+ * Parse an OpenFOAM dictionary into a nested plain object.
62
+ * Values stay strings (OpenFOAM values are tokens, not JSON scalars); lists
63
+ * become arrays of strings; sub-dictionaries become objects.
64
+ */
65
+ export function parseDict(text) {
66
+ const src = stripComments(text)
67
+ const root = {}
68
+ // stack of {obj, key} where key is the dictionary a `{` opened under
69
+ const stack = [{ obj: root, key: null }]
70
+ let i = 0
71
+ while (i < src.length) {
72
+ const c = src[i]
73
+ if (c === '{') {
74
+ // open a sub-dict under the last seen key of the current object
75
+ const top = stack.at(-1)
76
+ const lastKey = top.key
77
+ if (lastKey === null) {
78
+ // the FoamFile header block: capture nothing, push a scratch object
79
+ stack.push({ obj: {}, key: null })
80
+ i++
81
+ continue
82
+ }
83
+ const child = {}
84
+ top.obj[lastKey] = child
85
+ stack.push({ obj: child, key: null })
86
+ i++
87
+ continue
88
+ }
89
+ if (c === '}') {
90
+ if (stack.length > 1) stack.pop()
91
+ i++
92
+ continue
93
+ }
94
+ if (c === ';') {
95
+ i++
96
+ continue
97
+ }
98
+ if (/\s/.test(c)) {
99
+ i++
100
+ continue
101
+ }
102
+ // read a token: quoted key, or bare run up to whitespace/;{}
103
+ let token = ''
104
+ if (c === '"') {
105
+ let j = i + 1
106
+ while (j < src.length && src[j] !== '"') {
107
+ if (src[j] === '\\' && j + 1 < src.length) {
108
+ token += src[j + 1]
109
+ j += 2
110
+ continue
111
+ }
112
+ token += src[j]
113
+ j++
114
+ }
115
+ i = j + 1
116
+ } else {
117
+ let j = i
118
+ while (j < src.length && !/[\s;{}]/.test(src[j])) {
119
+ token += src[j]
120
+ j++
121
+ }
122
+ i = j
123
+ }
124
+ if (token === '') continue
125
+ // after a token, either `key value`, or `key {`
126
+ const after = src.slice(i)
127
+ const braceAfter = /^\s*\{/.test(after)
128
+ const semiAfter = /^\s*;/.test(after)
129
+ if (braceAfter || semiAfter) {
130
+ // this token is a key whose value is a dict (or an empty entry)
131
+ stack.at(-1).key = token
132
+ if (semiAfter) {
133
+ // `key;` with no value — record as empty so the key exists
134
+ stack.at(-1).obj[token] = ''
135
+ stack.at(-1).key = null
136
+ i = after.indexOf(';') + 1 + i
137
+ }
138
+ continue
139
+ }
140
+ // A preprocessor directive takes the rest of the line and nothing else.
141
+ // Letting the normal token loop run on swallowed the following entry: on
142
+ // OF11's movingCone/0/p the movingWall patch and its BC vanished into the
143
+ // include's value (452 tutorial files carry an #include at the top of a
144
+ // sub-dict).
145
+ if (token.startsWith('#')) {
146
+ let j = i
147
+ while (j < src.length && src[j] !== '\n') j++
148
+ stack.at(-1).obj[token] = src.slice(i, j).trim()
149
+ stack.at(-1).key = null
150
+ i = j
151
+ continue
152
+ }
153
+ // read the value token(s) up to the statement end
154
+ let value = ''
155
+ let j = i
156
+ while (j < src.length) {
157
+ // skip whitespace
158
+ while (j < src.length && /\s/.test(src[j])) j++
159
+ if (j >= src.length || src[j] === ';') break
160
+ if (src[j] === '{') break // value list handled below
161
+ // A `}` while a value is pending means the dict closed early. Breaking
162
+ // (rather than falling into the token reader, which cannot consume it and
163
+ // therefore never advances j) is what kept parseDict spinning forever on
164
+ // `foo\n}` — a hang that blocks the event loop, so no timeout can fire.
165
+ if (src[j] === '}') break
166
+ let v = ''
167
+ if (src[j] === '$') {
168
+ // ${deltaT} / $FOAM_CASE: one token, or the `{` opens a bogus dict level
169
+ let k = j + 1
170
+ if (src[k] === '{') {
171
+ k++
172
+ while (k < src.length && src[k] !== '}') k++
173
+ k++
174
+ } else {
175
+ while (k < src.length && /[A-Za-z0-9_]/.test(src[k])) k++
176
+ }
177
+ v = src.slice(j, k)
178
+ j = k
179
+ value = value === '' ? v : `${value} ${v}`
180
+ continue
181
+ }
182
+ if (src[j] === '"') {
183
+ let k = j + 1
184
+ while (k < src.length && src[k] !== '"') {
185
+ if (src[k] === '\\' && k + 1 < src.length) {
186
+ v += src[k + 1]
187
+ k += 2
188
+ continue
189
+ }
190
+ v += src[k]
191
+ k++
192
+ }
193
+ j = k + 1
194
+ } else {
195
+ let k = j
196
+ while (k < src.length && !/[\s;{}]/.test(src[k])) {
197
+ v += src[k]
198
+ k++
199
+ }
200
+ // never stall: an unconsumable character must still move j forward
201
+ if (k === j) {
202
+ v += src[j]
203
+ k++
204
+ }
205
+ j = k
206
+ }
207
+ value = value === '' ? v : `${value} ${v}`
208
+ }
209
+ const top = stack.at(-1)
210
+ // a `( ... )` list: collect until the closing paren
211
+ if (value.startsWith('(') && !value.endsWith(')')) {
212
+ let raw = value
213
+ while (j < src.length && !raw.trimEnd().endsWith(')')) {
214
+ raw += src[j]
215
+ j++
216
+ }
217
+ value = raw.trim()
218
+ // consume the trailing ;
219
+ while (j < src.length && src[j] !== ';') j++
220
+ }
221
+ top.obj[token] = value.trim()
222
+ top.key = null
223
+ i = j
224
+ }
225
+ return root
226
+ }
227
+
228
+ // =====================================================================
229
+ // Case layout discovery
230
+ // =====================================================================
231
+ export const CASE_FILES = {
232
+ control: 'system/controlDict',
233
+ schemes: 'system/fvSchemes',
234
+ solution: 'system/fvSolution',
235
+ blockMesh: 'system/blockMeshDict',
236
+ snappyMesh: 'system/snappyHexMeshDict',
237
+ decompose: 'system/decomposeParDict',
238
+ surfaceFeatures: 'system/surfaceFeatureExtractDict',
239
+ }
240
+
241
+ const safeRead = (p) => {
242
+ try {
243
+ return readFileSync(p, 'utf8')
244
+ } catch {
245
+ return null
246
+ }
247
+ }
248
+
249
+ /** `system/fvSchemes` -> `system/<region>/fvSchemes` when that file exists. */
250
+ function regionPath(caseDir, rel, region) {
251
+ if (!region) return rel
252
+ const parts = String(rel).split('/')
253
+ if ((parts[0] === 'system' || parts[0] === 'constant') && parts.length >= 2) {
254
+ const alt = [parts[0], region, ...parts.slice(1)].join('/')
255
+ if (existsSync(join(caseDir, alt))) return alt
256
+ }
257
+ return rel
258
+ }
259
+
260
+ export function readCaseDict(caseDir, rel, region = '') {
261
+ const text = safeRead(join(caseDir, regionPath(caseDir, rel, region)))
262
+ return text === null ? null : parseDict(text)
263
+ }
264
+
265
+ /** Numeric-looking tokens: "3000" -> 3000, "1e-07" -> 1e-7, else NaN. */
266
+ export function num(value) {
267
+ if (value === undefined || value === null) return NaN
268
+ const s = String(value).trim()
269
+ if (s === '') return NaN
270
+ const m = /^-?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/.exec(s)
271
+ return m ? Number(s) : NaN
272
+ }
273
+
274
+ /** Time directories that are not the expected start (stray run state). */
275
+ export function strayTimeDirs(caseDir) {
276
+ if (!existsSync(caseDir)) return []
277
+ const out = []
278
+ for (const e of readdirSyncSafe(caseDir)) {
279
+ if (!/^\d+(\.\d+)?$/.test(e)) continue
280
+ // a time dir that holds field data rather than being the uniform start
281
+ if (e === '0' || e === 'uniform') continue
282
+ const p = join(caseDir, e)
283
+ try {
284
+ if (!statSync(p).isDirectory()) continue
285
+ } catch {
286
+ continue
287
+ }
288
+ out.push(e)
289
+ }
290
+ return out.sort((a, b) => Number(a) - Number(b))
291
+ }
292
+
293
+ function readdirSyncSafe(dir) {
294
+ try {
295
+ return readdirSync(dir)
296
+ } catch {
297
+ return []
298
+ }
299
+ }
300
+
301
+ /** Which field files exist under 0/ (or the first time dir). */
302
+ export function fieldFiles(caseDir, region = '') {
303
+ const zeroCandidates = region
304
+ ? ['0', '0.orig', '0_orig'].map((n) => join(caseDir, n, region))
305
+ : ['0', '0.orig', '0_orig'].map((n) => join(caseDir, n))
306
+ const zero = zeroCandidates.find((p) => existsSync(p))
307
+ const dir = zero ?? caseDir
308
+ // h/alphat/pcorr are what a compressible or transient case actually carries;
309
+ // omitting them made `checkBoundaryFields` skip those cases silently.
310
+ return readdirSyncSafe(dir).filter((f) => /^(U|k|epsilon|p|p_rgh|T|nut|nuTilda|omega|phi|h|alphat|pcorr)$/.test(f))
311
+ }
312
+
313
+ // =====================================================================
314
+ // Checks. Each returns findings: {rule, severity, title, detail, fix}
315
+ // =====================================================================
316
+
317
+ const F = (rule, severity, title, detail, fix) => ({ rule, severity, title, detail, fix })
318
+
319
+ // Patch-field types the workbench is confident about. Anything else is reported
320
+ // as advice: the solver prints its own valid list, which is the authority.
321
+ const KNOWN_BC_TYPES = new Set([
322
+ 'fixedValue', 'fixedGradient', 'zeroGradient', 'calculated', 'mixed', 'uniformFixedValue',
323
+ 'noSlip', 'slip', 'partialSlip', 'symmetry', 'symmetryPlane', 'empty', 'wedge', 'cyclic', 'cyclicSlip',
324
+ 'inletOutlet', 'outletInlet', 'inletOutletTotalTemperature', 'pressureInletOutletVelocity',
325
+ 'pressureInletOutletParSlipVelocity', 'totalPressure', 'fixedFluxPressure', 'fixedMean',
326
+ 'waveTransmissive', 'advective', 'freestream', 'freestreamVelocity', 'freestreamPressure',
327
+ 'turbulentInlet', 'turbulentIntensityKineticEnergyInlet', 'turbulentMixingLengthDissipationRateInlet',
328
+ 'turbulentMixingLengthFrequencyInlet', 'turbulentKineticEnergy', 'turbulentOmega',
329
+ 'kqRWallFunction', 'kLowReWallFunction', 'epsilonWallFunction', 'omegaWallFunction',
330
+ 'nutkWallFunction', 'nutUWallFunction', 'nutLowReWallFunction', 'nutUSpaldingWallFunction',
331
+ 'v2WallFunction', 'fWallFunction', // alphat wall functions exist only prefixed (compressible::)
332
+
333
+ 'prghPressure', 'prghTotalPressure', 'fixedInternalValue', 'extrapolatedCalculated',
334
+ 'codedFixedValue', 'codedMixed', 'timeVaryingMappedFixedValue', 'mapped', 'mappedValue',
335
+ 'interfaceCompression', 'flowRateInletVelocity', 'flowRateOutletVelocity', 'uniformInletOutlet',
336
+ // multi-region / conjugate heat transfer
337
+ 'coupledTemperature', 'coupledPressure', 'externalWallHeatFluxTemperature', 'totalTemperature',
338
+ 'turbulentTemperatureCoupledBaffleMixed', 'turbulentTemperatureRadCoupledMixed',
339
+ 'fixedEnergy', 'gradientEnergy', 'mixedEnergy', 'mappedField', 'mappedInternalValue',
340
+ ])
341
+
342
+ export function checkControlDict(caseDir, region = '') {
343
+ const d = readCaseDict(caseDir, CASE_FILES.control)
344
+ const out = []
345
+ if (d === null) return [F('missing-file', 'error', 'system/controlDict not found', 'A case without controlDict cannot run.', 'Restore it from a working case or the tutorial.')]
346
+ const schemes = readCaseDict(caseDir, CASE_FILES.schemes, region)
347
+ const ddt = schemes?.ddtSchemes?.default ?? ''
348
+ const isSteady = /steadyState/.test(ddt)
349
+ const writeControl = String(d.writeControl ?? '')
350
+ const writeInterval = String(d.writeInterval ?? '')
351
+ const endTime = num(d.endTime)
352
+ const deltaT = num(d.deltaT)
353
+ const startTime = num(d.startTime)
354
+ const stopAt = String(d.stopAt ?? '')
355
+ const purgeWrite = num(d.purgeWrite)
356
+
357
+ // 1. steadyState + timeStep writeInterval: writes are per iteration, so a
358
+ // steady case silently produces a huge number of time dirs.
359
+ if (isSteady && writeControl === 'timeStep' && num(writeInterval) > 0 && endTime / num(writeInterval) > 20) {
360
+ out.push(
361
+ F(
362
+ 'steady-write-flood',
363
+ 'warn',
364
+ `steady case writes ${Math.round(endTime / num(writeInterval))} time directories`,
365
+ `ddtSchemes is steadyState but writeControl is timeStep with writeInterval ${writeInterval} over endTime ${endTime}. Every write becomes a time directory, so disk grows by that factor and foamToVTK/converting takes just as long.`,
366
+ 'For a steady run prefer writeControl runTime/writeInterval, or a much larger writeInterval (e.g. 500).',
367
+ ),
368
+ )
369
+ }
370
+
371
+ // 2. writeInterval not a multiple of the step: skipped writes look like lost data.
372
+ if (writeControl === 'timeStep' && num(writeInterval) > 0 && Number.isFinite(deltaT) && deltaT > 0) {
373
+ const perWrite = num(writeInterval)
374
+ if (!Number.isInteger(perWrite)) {
375
+ out.push(
376
+ F(
377
+ 'write-interval-fractional',
378
+ 'error',
379
+ `writeInterval ${writeInterval} is not an integer step count`,
380
+ 'writeControl timeStep interprets writeInterval as a number of time steps, so a fractional value is silently truncated and writes land where you do not expect.',
381
+ 'Use an integer number of steps.',
382
+ ),
383
+ )
384
+ }
385
+ }
386
+
387
+ // 3. purgeWrite 0 with a long run: unbounded disk growth.
388
+ if (purgeWrite === 0 && Number.isFinite(endTime) && endTime > 0 && num(writeInterval) > 0 && endTime / num(writeInterval) > 10) {
389
+ out.push(
390
+ F(
391
+ 'no-purge',
392
+ 'warn',
393
+ 'purgeWrite is 0 on a run that writes many times',
394
+ 'Nothing is ever deleted, so a long parameter sweep fills the disk. purgeWrite 2 keeps only the last two.',
395
+ 'Set purgeWrite 2 (or more) once you no longer need every step.',
396
+ ),
397
+ )
398
+ }
399
+
400
+ // 4. startTime/stopAt mismatch: restarting from the wrong time is silent.
401
+ if (stopAt === 'endTime' && Number.isFinite(startTime) && Number.isFinite(endTime) && startTime > endTime) {
402
+ out.push(F('start-after-end', 'error', `startTime ${startTime} is after endTime ${endTime}`, 'The solver exits immediately with nothing written.', 'Fix the times.'))
403
+ }
404
+
405
+ // 4b. writeInterval longer than the run: a time-based writeControl that is
406
+ // never reached writes nothing at all, and OpenFOAM says nothing — the run
407
+ // looks successful and there is no time directory to post-process.
408
+ if (/^(adjustable)?[Rr]unTime$/.test(writeControl) && Number.isFinite(endTime) && Number.isFinite(startTime)) {
409
+ const span = endTime - startTime
410
+ const every = num(writeInterval)
411
+ if (Number.isFinite(every) && every > 0 && span > 0 && every > span) {
412
+ out.push(
413
+ F(
414
+ 'write-never-fires',
415
+ 'warn',
416
+ `writeControl ${writeControl} with writeInterval ${writeInterval} over a ${span} s run never writes`,
417
+ 'The first write is due at startTime + writeInterval, which is past endTime, so the run finishes with no time directory and nothing to post-process. purgeWrite and foamToVTK then act on an empty case.',
418
+ `Set writeInterval below ${span} (e.g. ${Math.max(1, Math.round(span / 10))}).`,
419
+ ),
420
+ )
421
+ }
422
+ }
423
+
424
+ // 5. functions referencing probeLocations on a case with no field files.
425
+ const funcs = d.functions && typeof d.functions === 'object' ? Object.keys(d.functions) : []
426
+ if (funcs.includes('probes')) {
427
+ const fields = fieldFiles(caseDir)
428
+ if (fields.length === 0) {
429
+ out.push(
430
+ F(
431
+ 'probes-no-fields',
432
+ 'warn',
433
+ 'controlDict defines a probes functionObject but 0/ has no field files',
434
+ 'probes reads the fields named in its `fields` entry; without them it writes empty or fails at the first write step.',
435
+ 'Ensure 0/ contains U, k, epsilon, p (or adjust the probes `fields` list).',
436
+ ),
437
+ )
438
+ }
439
+ }
440
+ return out
441
+ }
442
+
443
+ export function checkFvSchemes(caseDir, region = '') {
444
+ const d = readCaseDict(caseDir, CASE_FILES.schemes, region)
445
+ const out = []
446
+ if (d === null) return [F('missing-file', 'error', `system/${region ? region + '/' : ''}fvSchemes not found`, 'The solver cannot start without numerical schemes.', 'Copy one from a tutorial and adapt it.')]
447
+ if (!d.ddtSchemes?.default) {
448
+ out.push(F('no-ddt', 'error', 'fvSchemes has no ddtSchemes default', 'The solver aborts with "no ddtSchemes" on the first iteration.', 'Add ddtSchemes { default steadyState; } for steady, or Euler for transient.'))
449
+ }
450
+ if (!d.gradSchemes?.default) {
451
+ out.push(F('no-grad', 'error', 'fvSchemes has no gradSchemes default', 'Gradients are required by every convection term.', 'Add gradSchemes { default Gauss linear; }.'))
452
+ }
453
+ const div = d.divSchemes && typeof d.divSchemes === 'object' ? d.divSchemes : {}
454
+ for (const [term, scheme] of Object.entries(div)) {
455
+ const s = String(scheme)
456
+ // limitedLinear k blends toward upwind with psi = clamp(2r/k, 0, 1)
457
+ // (finiteVolume/.../limitedLinear/limitedLinear.H). k -> 0 gives psi -> 1,
458
+ // i.e. plain linear with no limiting; k = 1 is the conservative default and
459
+ // larger k limits harder. Warn only when the limiter is effectively off.
460
+ const lim = /limitedLinear\s+(\S+)/.exec(s)
461
+ const factor = lim ? num(lim[1]) : NaN
462
+ if (Number.isFinite(factor) && factor < 0.1) {
463
+ out.push(
464
+ F(
465
+ 'limiter-wide-open',
466
+ 'warn',
467
+ `${term} uses limitedLinear ${lim[1]}: the limiter is effectively off`,
468
+ 'In this scheme psi = clamp(2r/k, 0, 1), so k -> 0 approaches pure linear convection: the limiter stops blending toward upwind and scalar transport (k, epsilon, h, T) can overshoot near steep gradients, producing negative values that break the turbulence model. OpenFOAM accepts 0 < k <= 1; k = 1 is the strongest limiter of this family.',
469
+ 'Use limitedLinear 1 (the strongest allowed value) for transported scalars, or limitedLinearV 1 for velocity.',
470
+ ),
471
+ )
472
+ }
473
+ // unbounded linear advection of a transport scalar
474
+ if (/Gauss linear;/.test(s) && /div\(phi,(k|epsilon|h|T)\)/.test(term)) {
475
+ out.push(
476
+ F(
477
+ 'unbounded-scalar-advection',
478
+ 'warn',
479
+ `${term} uses unbounded Gauss linear`,
480
+ 'Transport scalars advected with plain Gauss linear overshoot near steep gradients, which for k/epsilon means negative values that then break the turbulence model.',
481
+ 'Prefer bounded Gauss linearUpwind grad(<field>) or a limited scheme.',
482
+ ),
483
+ )
484
+ }
485
+ if (/dev2\(T\(grad\(U\)\)\)/.test(term) && !/bounded/.test(s)) {
486
+ // info, not warn: every stock OpenFOAM 11 tutorial ships the unbounded
487
+ // form, so warning on it flagged the reference cases themselves. The
488
+ // advice is still worth showing once, on skewed meshes.
489
+ out.push(
490
+ F(
491
+ 'unbounded-viscous',
492
+ 'info',
493
+ `${term} is not bounded`,
494
+ 'The viscous term without `bounded` can overshoot on skewed cells, showing up as velocity spikes at the wall. OpenFOAM\'s own tutorials use the unbounded form, so this is advice, not a defect.',
495
+ 'On a skewed mesh, use bounded Gauss linear.',
496
+ ),
497
+ )
498
+ }
499
+ }
500
+ // Compressible solvers assemble an energy flux; with sensible internal energy
501
+ // (org `fluid` + hePsiThermo) they also need the pressure-work term. A missing
502
+ // one kills the first time step with "Cannot find scheme for div(phi,(p|rho))".
503
+ const control = readCaseDict(caseDir, CASE_FILES.control, '')
504
+ const solverName = String(control?.solver ?? control?.application ?? '')
505
+ const solverClass = classifySolver(solverName)
506
+ const compressible = solverClass.compressible === true || /^(fluid|isothermalFluid|multicomponentFluid|shockFluid|XiFluid)$/i.test(solverName)
507
+ if (compressible) {
508
+ const terms = Object.keys(div)
509
+ const hasE = terms.some((t) => /div\(phi,e\)/.test(t))
510
+ const hasH = terms.some((t) => /div\(phi,h\)/.test(t))
511
+ const hasP = terms.some((t) => /div\(phi,\(p\|rho\)\)|div\(phid,\s*p\)/.test(t))
512
+ if (!hasE && !hasH) {
513
+ out.push(F('no-energy-flux-scheme', 'error', 'compressible solver without an energy-flux scheme (div(phi,e) or div(phi,h))', 'The energy equation cannot be assembled, so the solver aborts before the first step.', 'Add div(phi,e) for sensible internal energy (org) or div(phi,h) for enthalpy (com).'))
514
+ } else if (hasE && !hasP) {
515
+ out.push(F('no-pressure-work-scheme', 'warn', 'div(phi,e) is set but there is no div(phi,(p|rho))', 'With sensible internal energy the solver adds a pressure-work flux; without a scheme for it the first time step aborts with "Cannot find scheme for div(phi,(p|rho))".', 'Add div(phi,(p|rho)) Gauss upwind; (or use div(phi,h) with enthalpy).'))
516
+ }
517
+ }
518
+ if (!d.laplacianSchemes?.default) {
519
+ out.push(F('no-laplacian', 'error', 'fvSchemes has no laplacianSchemes default', 'Diffusion terms cannot be assembled.', 'Add laplacianSchemes { default Gauss linear corrected; }.'))
520
+ }
521
+ return out
522
+ }
523
+
524
+ export function checkFvSolution(caseDir, region = '') {
525
+ const d = readCaseDict(caseDir, CASE_FILES.solution, region)
526
+ const out = []
527
+ if (d === null) return [F('missing-file', 'error', `system/${region ? region + '/' : ''}fvSolution not found`, 'The solver cannot start without linear solvers.', 'Copy one from a tutorial and adapt it.')]
528
+ const blockMesh = readCaseDict(caseDir, CASE_FILES.blockMesh, region)
529
+ // A transient case runs PIMPLE/PISO; the SIMPLE block may still exist with 0.
530
+ // Take the correctors from the algorithm the ddt scheme implies.
531
+ const regionSchemes = readCaseDict(caseDir, CASE_FILES.schemes, region)
532
+ const transient = !/steadyState/.test(String(regionSchemes?.ddtSchemes?.default ?? ''))
533
+ const algorithm = transient ? (d.PIMPLE ?? d.PISO ?? d.SIMPLE) : (d.SIMPLE ?? d.PIMPLE)
534
+ const nNonOrtho = num(algorithm?.nNonOrthogonalCorrectors)
535
+ const mesh = readCaseDict(caseDir, CASE_FILES.snappyMesh, region)
536
+ // non-orthogonality comes from the mesh; snappy with high castellatin, or
537
+ // a hand-built multi-block mesh, both raise it. `blocks ( … );` parses as a
538
+ // STRING, and Object.keys on a string returns its indices — the old test was
539
+ // really "the text is longer than 8 chars", so it fired on a single
540
+ // orthogonal hex.
541
+ const blockText = typeof blockMesh?.blocks === 'string' ? blockMesh.blocks : ''
542
+ const blockCount = blockText ? (blockText.match(/\b(?:hex|tet|wedge|prism|splitHex|poly)\b/g) || []).length : Object.keys(blockMesh?.blocks || {}).length
543
+ const skewLikely = Boolean(mesh?.castellatedMesh)
544
+ if (nNonOrtho === 0 && skewLikely) {
545
+ out.push(
546
+ F(
547
+ 'no-nonortho-correctors',
548
+ 'warn',
549
+ 'nNonOrthogonalCorrectors is 0 on a mesh that is likely non-orthogonal',
550
+ 'On skewed cells the face-interpolation correction is what keeps the diffusion term second-order; skipping it makes SIMPLE stall at a residual plateau that looks like convergence trouble but is discretisation error.',
551
+ 'Set nNonOrthogonalCorrectors 1 (2 for strongly skewed meshes).',
552
+ ),
553
+ )
554
+ }
555
+ const solvers = d.solvers && typeof d.solvers === 'object' ? d.solvers : {}
556
+ for (const [field, s] of Object.entries(solvers)) {
557
+ if (!s || typeof s !== 'object') continue
558
+ const tol = num(s.tolerance)
559
+ const relTol = num(s.relTol)
560
+ if (Number.isFinite(tol) && tol > 1e-3) {
561
+ out.push(
562
+ F(
563
+ 'loose-tolerance',
564
+ 'warn',
565
+ `solver for ${field} has tolerance ${s.tolerance}`,
566
+ 'A loose linear tolerance leaves algebraic error in every iteration, which for pressure in SIMPLE shows up as a residual that will not drop further no matter how many iterations you run.',
567
+ 'Tighten to 1e-07 (pressure) / 1e-08 (transport fields).',
568
+ ),
569
+ )
570
+ }
571
+ if (Number.isFinite(relTol) && relTol > 0.2) {
572
+ out.push(
573
+ F(
574
+ 'loose-reltol',
575
+ 'warn',
576
+ `solver for ${field} has relTol ${s.relTol}`,
577
+ 'A large relative tolerance stops the linear solve early. Steady sweeps tolerate it; transient runs do not, because the error accumulates in time.',
578
+ 'Use relTol 0 (absolute) or 0.01-0.05.',
579
+ ),
580
+ )
581
+ }
582
+ }
583
+ // PIMPLE/pimple consistency: only transient runs need outer correctors; the
584
+ // steady chtMultiRegionSimpleFoam tutorials use PIMPLE without them on purpose.
585
+ if (d.PIMPLE && !d.PIMPLE.nOuterCorrectors) {
586
+ const regionSchemes = readCaseDict(caseDir, CASE_FILES.schemes, region)
587
+ const transient = !/steadyState/.test(String(regionSchemes?.ddtSchemes?.default ?? ''))
588
+ if (transient) {
589
+ out.push(F('pimple-no-outer', 'info', 'PIMPLE has no nOuterCorrectors', 'On a transient PIMPLE run the outer correctors are what re-solve pressure after the turbulence update; with one pass the run behaves like PISO with a large Courant limit and diverges instead of complaining.', 'Set nOuterCorrectors 2-3 for transient runs.'))
590
+ }
591
+ }
592
+ return out
593
+ }
594
+
595
+ export function checkBlockMeshDict(caseDir, region = '') {
596
+ const d = readCaseDict(caseDir, CASE_FILES.blockMesh, region)
597
+ const out = []
598
+ if (d === null) return out // many cases use snappy or an imported mesh only
599
+ const scale = num(d.scale)
600
+ if (Number.isFinite(scale) && scale !== 1) {
601
+ out.push(
602
+ F(
603
+ 'non-unit-scale',
604
+ 'info',
605
+ `blockMeshDict scale is ${d.scale}`,
606
+ 'Every coordinate is multiplied by it, so a scale of 0.001 means your "metres" are millimetres. If you imported geometry in another unit and forgot, velocities and areas are wrong by the square of it.',
607
+ 'Keep scale 1 and convert geometry explicitly.',
608
+ ),
609
+ )
610
+ }
611
+ // Blocks share vertices, so "hexCount * 8 vs vertexCount" is not a valid check
612
+ // (5 hex blocks legitimately list 24 shared vertices). Only the trivial
613
+ // structural facts are worth reporting, as advice rather than an error.
614
+ const vertices = String(d.vertices ?? '')
615
+ const vertexCount = (vertices.match(/\(\s*[-+\d.eE]+\s+[-+\d.eE]+\s+[-+\d.eE]+\s*\)/g) || []).length
616
+ if (vertexCount > 0 && vertexCount % 8 !== 0) {
617
+ out.push(
618
+ F(
619
+ 'vertex-count',
620
+ 'info',
621
+ `blockMeshDict lists ${vertexCount} vertices, not a multiple of 8`,
622
+ 'Blocks share vertices, so this is usually fine; it only matters when a block references a label beyond the vertices list, which blockMesh reports with its own error.',
623
+ 'No action; trust blockMesh to report a truly missing vertex.',
624
+ ),
625
+ )
626
+ }
627
+ return out
628
+ }
629
+
630
+ /** Stray time directories left by a previous run inside the case. */
631
+ export function checkStrayTimes(caseDir) {
632
+ const stray = strayTimeDirs(caseDir)
633
+ if (stray.length === 0) return []
634
+ // `startFrom latestTime` is a deliberate resume: those directories are the
635
+ // restart point, not litter, so warning here is wrong.
636
+ const startFrom = String(readCaseDict(caseDir, CASE_FILES.control)?.startFrom ?? '')
637
+ if (/latestTime/.test(startFrom)) return []
638
+ return [
639
+ F(
640
+ 'stray-time-dirs',
641
+ 'warn',
642
+ `case carries ${stray.length} time directories from an earlier run (${stray.slice(0, 6).join(', ')}${stray.length > 6 ? '…' : ''})`,
643
+ 'foamRun picks startFrom startTime/lt;startTime from controlDict, but a case littered with time dirs makes it easy to restart from the wrong one, and foamToVTK converts every directory it finds — turning a 30 s post-process into minutes.',
644
+ 'Keep the sweep results elsewhere (or archive them) and leave only 0/ and uniform/ in the working case.',
645
+ ),
646
+ ]
647
+ }
648
+
649
+ /** Boundary-condition sanity for the common fields. */
650
+ export function checkBoundaryFields(caseDir, region = '') {
651
+ const out = []
652
+ const zero = [join(caseDir, '0'), join(caseDir, '0.orig'), join(caseDir, '0_orig')]
653
+ .map((dir) => (region ? join(dir, region) : dir))
654
+ .find((p) => existsSync(p))
655
+ if (!zero || !existsSync(zero)) return out
656
+ for (const field of fieldFiles(caseDir, region)) {
657
+ const text = safeRead(join(zero, field))
658
+ if (text === null) continue
659
+ const d = parseDict(text)
660
+ const bf = d.boundaryField && typeof d.boundaryField === 'object' ? d.boundaryField : {}
661
+ const patches = Object.keys(bf)
662
+ if (patches.length === 0) {
663
+ out.push(F('no-boundary-field', 'error', `0/${field} declares no boundaryField`, 'The solver cannot map the initial field onto the mesh.', 'Add a boundaryField block with one entry per patch.'))
664
+ continue
665
+ }
666
+ const emptyPatches = []
667
+ for (const patch of patches) {
668
+ const entry = bf[patch]
669
+ const type = entry && typeof entry === 'object' ? String(entry.type ?? '') : ''
670
+ if (field === 'p' && /fixedValue/.test(type)) {
671
+ // An outlet fixing pressure is the standard way to set the pressure
672
+ // level in a duct; only a *wall* doing it is the mistake, because it
673
+ // pins the reference where the flow cannot adjust.
674
+ const wallish = /wall|solid|building|geometry/i.test(patch)
675
+ if (wallish) {
676
+ out.push(
677
+ F(
678
+ 'p-fixed-value',
679
+ 'warn',
680
+ `0/p sets wall patch ${patch} to fixedValue`,
681
+ 'Pressure level in an incompressible closed domain is floating; fixing it at a wall pins the reference and shifts every reported pressure by a constant.',
682
+ 'Use zeroGradient on walls and fix the level at the outlet only.',
683
+ ),
684
+ )
685
+ }
686
+ }
687
+ if (type && !type.includes('::') && !KNOWN_BC_TYPES.has(type)) {
688
+ out.push(
689
+ F(
690
+ 'unknown-bc-type',
691
+ 'warn',
692
+ `0/${region ? region + '/' : ''}${field}: patch ${patch} uses an unknown type "${type}"`,
693
+ 'The solver builds the boundary field from this word; an unknown or mis-spelled type aborts the run with "Unknown patchField type" and prints the valid list. Compressible variants are prefixed, e.g. compressible::alphatWallFunction.',
694
+ 'Compare with the valid list the solver prints, or use openfoam_find_source to check the type name.',
695
+ ),
696
+ )
697
+ }
698
+ if (field === 'U' && /empty/.test(type)) emptyPatches.push(patch)
699
+ }
700
+ if (field === 'U' && emptyPatches.length) {
701
+ out.push(F('u-empty-patch', 'info', `0/U has empty patch(es): ${emptyPatches.join(', ')}`, 'Empty patches mean the case is 2D (or quasi-1D) — not a defect, but blockMesh must create the same empty patches and the flow is not 3D.', 'No action if a 2D/quasi-1D setup is intended.'))
702
+ }
703
+ // internalField must exist
704
+ if (d.internalField === undefined) {
705
+ out.push(F('no-internal-field', 'error', `0/${field} has no internalField`, 'The field cannot be initialised.', 'Add internalField uniform <value>;.'))
706
+ }
707
+ }
708
+ return out
709
+ }
710
+
711
+ /**
712
+ * Rules that need the case's own physics settings to be judged. Each one is a
713
+ * case OpenFOAM accepts and then fails on for a reason it never names.
714
+ */
715
+ export function checkPhysics(caseDir, region = '') {
716
+ const out = []
717
+ const zero = [join(caseDir, '0'), join(caseDir, '0.orig'), join(caseDir, '0_orig')]
718
+ .map((dir) => (region ? join(dir, region) : dir))
719
+ .find((p) => existsSync(p))
720
+ if (!zero || !existsSync(zero)) return out
721
+ const fields = fieldFiles(caseDir, region)
722
+ const turbulence =
723
+ readCaseDict(caseDir, 'constant/momentumTransport', region) ?? readCaseDict(caseDir, 'constant/turbulenceProperties', region)
724
+ const simulationType = String(turbulence?.simulationType ?? '')
725
+ const isLaminar = /^laminar$/i.test(simulationType)
726
+
727
+ // 1. A wall function on a laminar case: OpenFOAM reads the patch type, not the
728
+ // model, so it applies a wall function that has no eddy viscosity to work
729
+ // with and the run either divides by zero or silently behaves as zeroGradient.
730
+ if (isLaminar) {
731
+ const WALL_FUNCTION = /(kqRWallFunction|epsilonWallFunction|omegaWallFunction|nutkWallFunction|nutUSpaldingWallFunction|nutLowReWallFunction|nutkAtmRoughWallFunction|alphatWallFunction)/
732
+ for (const field of fields) {
733
+ const text = safeRead(join(zero, field))
734
+ if (text === null) continue
735
+ const bf = parseDict(text)?.boundaryField
736
+ if (!bf || typeof bf !== 'object') continue
737
+ for (const patch of Object.keys(bf)) {
738
+ const type = String(bf[patch]?.type ?? '')
739
+ if (WALL_FUNCTION.test(type)) {
740
+ out.push(
741
+ F(
742
+ 'wall-function-on-laminar',
743
+ 'error',
744
+ `0/${field} uses ${type} on ${patch} but the case is laminar`,
745
+ 'A wall function needs a turbulence model to produce a wall value; with simulationType laminar OpenFOAM has no nut field, so the boundary is either rejected or quietly treated as zeroGradient.',
746
+ 'Either switch to a RAS/LES model or change that patch to zeroGradient.',
747
+ ),
748
+ )
749
+ }
750
+ }
751
+ }
752
+ }
753
+
754
+ // 2. Buoyancy without gravity: p_rgh means the solver subtracts rho*g*h, so a
755
+ // missing or dimensionally wrong constant/g gives a run with no buoyancy and
756
+ // no warning.
757
+ if (fields.includes('p_rgh')) {
758
+ const g = readCaseDict(caseDir, 'constant/g', region)
759
+ if (g === null) {
760
+ out.push(
761
+ F(
762
+ 'buoyant-without-g',
763
+ 'error',
764
+ '0/p_rgh exists but constant/g is missing',
765
+ 'The buoyant solvers build the hydrostatic part from constant/g; without it there is no body force, so the case runs and produces a purely isothermal-looking field.',
766
+ 'Add constant/g with `value (0 -9.81 0);` and `dimensions [0 1 -2 0 0 0 0];`.',
767
+ ),
768
+ )
769
+ } else {
770
+ const dims = Array.isArray(g.dimensions) ? g.dimensions.map(String) : String(g.dimensions ?? '').replace(/[[\]]/g, '').trim().split(/\s+/)
771
+ // OpenFOAM.com accepts named dimension sets (`dimensions [acceleration];`)
772
+ const named = dims.length === 1 && /^[A-Za-z_]\w*$/.test(dims[0])
773
+ const ok = named || dims.join(' ') === '0 1 -2 0 0 0 0'
774
+ if (!ok) {
775
+ out.push(
776
+ F(
777
+ 'buoyant-g-dimensions',
778
+ 'error',
779
+ `constant/g dimensions are [${dims.join(' ')}], expected [0 1 -2 0 0 0 0]`,
780
+ 'The buoyant solvers dimension-check g against rho*g*h; a wrong dimension list aborts the run at the first pressure correction, far from this file.',
781
+ 'Set `dimensions [0 1 -2 0 0 0 0];`.',
782
+ ),
783
+ )
784
+ }
785
+ }
786
+ }
787
+
788
+ // 3. Closed domain with no pressure reference: every p patch is zeroGradient,
789
+ // so the pressure level is undefined and the linear solver diverges on the
790
+ // first correction with a matrix that is singular but not obviously so.
791
+ if (fields.includes('p') && !fields.includes('p_rgh')) {
792
+ const text = safeRead(join(zero, 'p'))
793
+ const bf = text === null ? null : parseDict(text)?.boundaryField
794
+ const patches = bf && typeof bf === 'object' ? Object.keys(bf) : []
795
+ // Any of these fixes the pressure level or propagates it from a known
796
+ // reference, so the domain is not closed:
797
+ const PRESSURE_BC = /fixedValue|totalPressure|waveTransmissive|fixedFluxPressure|prghPressure|advective|supersonicFreestream|pinnedValue/
798
+ const hasFixed = patches.some((patch) => PRESSURE_BC.test(String(bf[patch]?.type ?? '')))
799
+ const solution = readCaseDict(caseDir, CASE_FILES.solution, region)
800
+ const hasRef = solution?.pRefCell !== undefined || solution?.pRefPoint !== undefined || solution?.pRefValue !== undefined
801
+ if (patches.length > 0 && !hasFixed && !hasRef) {
802
+ out.push(
803
+ F(
804
+ 'closed-domain-no-pref',
805
+ 'error',
806
+ 'pressure has no fixedValue patch and fvSolution sets no pRefCell',
807
+ `Every patch in 0/p is ${[...new Set(patches.map((patch) => String(bf[patch]?.type ?? '?')))].join('/')}, so the pressure level floats. The p matrix is singular and the first solve either diverges or returns a field offset by an arbitrary constant.`,
808
+ 'Set pRefCell 0, pRefValue 0 in fvSolution (or give one outlet a fixedValue).',
809
+ ),
810
+ )
811
+ }
812
+ }
813
+
814
+ return out
815
+ }
816
+
817
+ /**
818
+ * Multi-region trap: splitMeshRegions names interface patches
819
+ * `<region>_to_<other>` and keeps the outer patches, while hand-written or
820
+ * template dictionaries often still say `wall`. Compare every 0/<region>/*
821
+ * boundaryField against the patches that region's polyMesh actually has.
822
+ */
823
+ export function checkRegionFieldPatches(caseDir, region) {
824
+ const out = []
825
+ const boundaryFile = join(caseDir, 'constant', region, 'polyMesh', 'boundary')
826
+ const boundaryText = safeRead(boundaryFile)
827
+ if (boundaryText === null) return out
828
+ const patchTypes = {}
829
+ for (const m of boundaryText.matchAll(/\n (\w+)\n \{([\s\S]*?)\n \}/g)) {
830
+ const type = /\btype\s+(\w+)/.exec(m[2])
831
+ patchTypes[m[1]] = type ? type[1] : ''
832
+ }
833
+ const patches = Object.keys(patchTypes).filter((n) => n !== 'FoamFile')
834
+ if (!patches.length) return out
835
+ const zero = join(caseDir, '0', region)
836
+ let fields = []
837
+ try { fields = readdirSync(zero).filter((f) => !f.startsWith('.')) } catch { return out }
838
+ for (const field of fields) {
839
+ const dict = readCaseDict(caseDir, `0/${region}/${field}`, region)
840
+ if (!dict || typeof dict !== 'object') continue
841
+ const bf = dict.boundaryField
842
+ if (!bf || typeof bf !== 'object') continue
843
+ const entries = Object.keys(bf).filter((k) => !k.startsWith('#'))
844
+ const missing = patches.filter((p) => !entries.includes(p))
845
+ const extra = entries.filter((e) => !patches.includes(e))
846
+ // A coupled/mapped field on a plain wall patch is the classic CHT trap: the
847
+ // interface patch is <region>_to_<other>, and the outer wall is a real wall.
848
+ for (const entry of entries) {
849
+ const bcType = String(bf[entry]?.type || '')
850
+ if (!/^(coupled|mapped)/.test(bcType)) continue
851
+ const patchType = patchTypes[entry]
852
+ if (patchType && !/mapped|cyclic|nonConformal/.test(patchType)) {
853
+ out.push(F(
854
+ 'coupled-bc-on-wall',
855
+ 'error',
856
+ `0/${region}/${field}: ${bcType} on patch ${entry} (type ${patchType})`,
857
+ 'A coupled/mapped boundary condition needs a mapped interface patch; applied to a plain wall the solver aborts ("cannot apply to patch ... which should be a mappedPatchBaseBase type").',
858
+ 'Move the coupled condition to the interface patch (<region>_to_<other>) and give the outer wall a physical condition (zeroGradient, noSlip, ...).',
859
+ ))
860
+ }
861
+ }
862
+ if (extra.length) {
863
+ out.push(F(
864
+ 'region-field-unknown-patch',
865
+ 'warn',
866
+ `0/${region}/${field}: boundaryField has no such patch: ${extra.join(', ')}`,
867
+ `Region "${region}" has patches ${patches.join(', ')}. splitMeshRegions names interface patches <region>_to_<other>, so a template's "wall" entry does not exist and the solver aborts while reading the field.`,
868
+ 'Rename the block to the real interface patch and add blocks for the outer patches (coupledTemperature on the interface, zeroGradient/noSlip on the walls).',
869
+ ))
870
+ }
871
+ if (missing.length) {
872
+ out.push(F(
873
+ 'region-field-missing-patch',
874
+ 'error',
875
+ `0/${region}/${field}: no boundaryField entry for ${missing.join(', ')}`,
876
+ 'Every patch of a region needs a boundary condition in every field; the solver aborts with "Cannot find patchField entry for <patch>".',
877
+ 'Add the missing entries (or copy them from a field that has them).',
878
+ ))
879
+ }
880
+ }
881
+ return out
882
+ }
883
+
884
+ export function checkCase(caseDir, { regions = [] } = {}) {
885
+ // Time controls and stray time directories are case-global; the rest is
886
+ // per region when the case has regions (system/<r>/..., 0/<r>/..., constant/<r>/...).
887
+ const out = [...checkControlDict(caseDir), ...checkStrayTimes(caseDir)]
888
+ if (!regions.length) {
889
+ out.push(...checkFvSchemes(caseDir), ...checkFvSolution(caseDir), ...checkBlockMeshDict(caseDir),
890
+ ...checkBoundaryFields(caseDir), ...checkPhysics(caseDir))
891
+ return out
892
+ }
893
+ for (const region of regions) {
894
+ const tagged = [
895
+ ...checkRegionFieldPatches(caseDir, region),
896
+ ...checkFvSchemes(caseDir, region),
897
+ ...checkFvSolution(caseDir, region),
898
+ ...checkBlockMeshDict(caseDir, region),
899
+ ...checkBoundaryFields(caseDir, region),
900
+ ...checkPhysics(caseDir, region),
901
+ ].map((f) => ({ ...f, region }))
902
+ out.push(...tagged)
903
+ }
904
+ return out
905
+ }
906
+
907
+ // =====================================================================
908
+ // log parsing
909
+ // =====================================================================
910
+
911
+ /**
912
+ * checkMesh output -> the metrics that decide whether a mesh is usable.
913
+ * OpenFOAM prints them as `Name: value` lines inside the report.
914
+ */
915
+ /** First meaningful line of a FOAM error block (for results, not for logs). */
916
+ export function firstFatalLine(text) {
917
+ const src = String(text || '')
918
+ const fatal = /FOAM FATAL (?:IO )?ERROR:\s*([\s\S]{0,600}?)(?:\n\s*From function|\n\s*file:|$)/.exec(src)
919
+ if (fatal) {
920
+ const body = fatal[1].split('\n').map((l) => l.trim()).filter(Boolean)
921
+ return (body[0] ? 'FOAM FATAL ERROR: ' + body[0] : 'FOAM FATAL ERROR').slice(0, 300)
922
+ }
923
+ const line = src.split('\n').map((l) => l.trim()).find((l) => /error|failed|not found/i.test(l))
924
+ return line ? line.slice(0, 300) : ''
925
+ }
926
+
927
+ export function parseCheckMesh(text) {
928
+ const out = {}
929
+ const grab = (label, re) => {
930
+ const m = re.exec(text)
931
+ if (m) out[label] = m[1]
932
+ }
933
+ grab('cells', /^\s*cells:\s*(\d+)/m)
934
+ grab('faces', /^\s*faces:\s*(\d+)/m)
935
+ grab('points', /^\s*points:\s*(\d+)/m)
936
+ grab('boundary patches', /^\s*boundary patches:\s*(\d+)/m)
937
+ grab('max aspect ratio', /[Mm]ax aspect ratio\s*[:=]\s*([\d.eE+-]+)/)
938
+ grab('max non-orthogonality', /Mesh non-orthogonality Max:\s*([\d.]+)/)
939
+ // OpenFOAM prefixes out-of-range metrics with ***, e.g.
940
+ // ***Max skewness = 22.2796, 734 highly skew faces detected
941
+ grab('max skewness', /\**\s*Max skewness\s*=\s*([\d.eE+-]+)/)
942
+ grab('min volume', /Min volume\s*=\s*([\d.eE+-]+?)\.(?=\s)/)
943
+ grab('max volume', /Max volume\s*=\s*([\d.eE+-]+?)\.(?=\s)/)
944
+ const failedChecks = /Failed (\d+) mesh checks\./.exec(text)
945
+ out.failedChecks = failedChecks ? Number(failedChecks[1]) : 0
946
+ // The authoritative verdict is what checkMesh itself says, not our thresholds:
947
+ // a snappy mesh with a few concave cells is a failed check, while a mesh with
948
+ // 37.9 deg non-orthogonality is "Mesh OK." for OpenFOAM.
949
+ out.meshOk = /^\s*Mesh OK\.\s*$/m.test(text)
950
+ const failed = out.failedChecks > 0 || /^\s*Failed \d+ mesh checks\./m.test(text) || /FAILED/.test(text)
951
+ out.failed = failed
952
+ const bad = []
953
+ if (out['max aspect ratio'] && Number(out['max aspect ratio']) > 1000) bad.push(`aspect ratio ${out['max aspect ratio']} (want < 1000)`)
954
+ if (out['max non-orthogonality'] && Number(out['max non-orthogonality']) > 70) bad.push(`non-orthogonality ${out['max non-orthogonality']}° (want < 70°)`)
955
+ if (out['max skewness'] && Number(out['max skewness']) > 4) bad.push(`skewness ${out['max skewness']} (want < 4)`)
956
+ // The real reasons behind "Failed N mesh checks." are the threshold lines
957
+ // (e.g. "faces with face pyramid volume < 2e-11 : 10001"); surface them so a
958
+ // failure never comes back with an empty problems list.
959
+ for (const m of text.matchAll(/^\s*([^\n:]{3,}?)\s*:\s*(\d+)\s*$/gm)) {
960
+ const label = m[1].trim()
961
+ const count = Number(m[2])
962
+ if (count > 0 && /[<>]/.test(label)) bad.push(`${label}: ${count}`)
963
+ }
964
+ // the count of offending faces, when OpenFOAM reports one
965
+ const skewCount = /(\d+)\s+highly skew faces/.exec(text)
966
+ if (skewCount) out.skewFaces = skewCount[1]
967
+ out.problems = [...new Set(bad)].slice(0, 8)
968
+ return out
969
+ }
970
+
971
+ // polyMesh/boundary text -> [{name, type, nFaces, startFace}] (shared by the case tools)
972
+ export function parseBoundaryPatches(text) {
973
+ const patches = []
974
+ const re = /(\w+)\s*\{([^}]*)\}/g
975
+ let m
976
+ while ((m = re.exec(String(text)))) {
977
+ const name = m[1]
978
+ const block = m[2]
979
+ const type = (block.match(/type\s+(\w+)\s*;/) || [])[1] || null
980
+ if (!type) continue
981
+ const nFaces = (block.match(/nFaces\s+(\d+)\s*;/) || [])[1] || null
982
+ const startFace = (block.match(/startFace\s+(\d+)\s*;/) || [])[1] || null
983
+ patches.push({ name, type, nFaces: nFaces ? Number(nFaces) : null, startFace: startFace ? Number(startFace) : null })
984
+ }
985
+ return patches
986
+ }
987
+
988
+ /** A run log -> the things worth telling a human about. */
989
+ export function parseRunLog(text) {
990
+ const out = {
991
+ errors: [], warnings: [], residualFloor: null, diverged: false, finished: false,
992
+ iterations: null, times: [], execSeries: [], execSeconds: null, clockSeconds: null,
993
+ }
994
+ const lines = text.split(/\r?\n/)
995
+ // foamMultiRun / parallel runs indent the time line and append a unit:
996
+ // ` Time = 0.071s`, sometimes prefixed by `[0] `. The original
997
+ // /^Time = .../ never matched those, so the residual floor was taken over the
998
+ // whole log and a live run was judged RERUN.
999
+ const TIME_RE = /^\s*(?:\[\d+\]\s*)?Time\s*=\s*([0-9.eE+-]+)s?\s*$/
1000
+ const timeIdx = []
1001
+ const timeVals = []
1002
+ const BANNER_RE = /Enabling floating point exception trapping|sigFpe\s*:\s*Enabling/
1003
+ for (let i = 0; i < lines.length; i += 1) {
1004
+ const line = lines[i]
1005
+ const t = line.trim()
1006
+ const tm = TIME_RE.exec(line)
1007
+ if (tm) {
1008
+ timeIdx.push(i)
1009
+ const v = Number(tm[1])
1010
+ if (Number.isFinite(v)) timeVals.push(v)
1011
+ }
1012
+ // `--> FOAM FATAL IO ERROR` is the most common OpenFOAM failure (a missing
1013
+ // entry, a malformed dict) and it was excluded by the very guard that was
1014
+ // meant to skip the plain FATAL line.
1015
+ if (/^--> FOAM FATAL( IO)? ERROR/.test(t)) out.errors.push(t)
1016
+ else if (/^--> FOAM FATAL ERROR/.test(t)) out.errors.push(t)
1017
+ else if (/ERROR:/.test(line) && !/FOAM FATAL/.test(line)) out.errors.push(t)
1018
+ if (/Foam::error::printStack/.test(line)) out.errors.push('stack trace printed (see log head)')
1019
+ if (/^--> FOAM Warning/.test(t)) out.warnings.push(t)
1020
+ // "bounding box" is printed by every successful mesh run (Overall mesh /
1021
+ // domain / Refined mesh bounding box), so matching it called a clean snappy
1022
+ // run diverged. Real divergence shows up as the epsilon explosion.
1023
+ // The sigFpe banner is printed by every run at startup, not a signal.
1024
+ if (!BANNER_RE.test(line) && /bounding epsilon|negative.*determinant|face not found|sigFpe|Foam::sigFpe|bounding .*min: -?[1-9]e\+?\d{2,}/.test(line)) out.diverged = true
1025
+ const ex = /ExecutionTime\s*=\s*([0-9.eE+-]+)\s*s/.exec(line)
1026
+ if (ex) { out.execSeconds = Number(ex[1]); out.execSeries.push(Number(ex[1])) }
1027
+ const cl = /ClockTime\s*=\s*([0-9.eE+-]+)\s*s/.exec(line)
1028
+ if (cl) out.clockSeconds = Number(cl[1])
1029
+ }
1030
+ const final = /^\s*End\s*$/m.test(text)
1031
+ out.finished = final
1032
+ out.times = [...new Set(timeVals)]
1033
+ out.iterations = timeVals.length ? String(timeVals[timeVals.length - 1]) : null
1034
+ // residual floor: the WORST initial residual of the last COMPLETE time step,
1035
+ // not the last field printed (k often converges to 1e-09 while U is still at
1036
+ // 0.5) and not the whole log (which reports the startup transient).
1037
+ let start
1038
+ let end
1039
+ if (final && timeIdx.length) {
1040
+ start = timeIdx[timeIdx.length - 1]
1041
+ end = lines.length
1042
+ } else if (timeIdx.length >= 2) {
1043
+ start = timeIdx[timeIdx.length - 2]
1044
+ end = timeIdx[timeIdx.length - 1]
1045
+ } else {
1046
+ start = timeIdx.length ? timeIdx[0] : 0
1047
+ end = lines.length
1048
+ }
1049
+ const tail = lines.slice(start, end)
1050
+ const worst = tail
1051
+ .map((l) => /Initial residual = ([\d.eE+-]+)/.exec(l)?.[1])
1052
+ .filter(Boolean)
1053
+ // keep the printed token, not Number()'s decimal expansion: the report
1054
+ // should read like the log (5.92713e-05, not 0.0000592713)
1055
+ .map((tok) => ({ tok, n: Number(tok) }))
1056
+ .filter((p) => Number.isFinite(p.n))
1057
+ if (worst.length) out.residualFloor = worst.reduce((a, b) => (b.n > a.n ? b : a)).tok
1058
+ return out
1059
+ }
1060
+
1061
+