@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.
- package/CHANGELOG.md +683 -0
- package/CORE.md +50 -0
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +373 -2
- package/client.js +48 -0
- package/cordis.patch.yml +18 -0
- package/icon.png +0 -0
- package/lib/buildlib.js +42 -0
- package/lib/caselib.js +212 -0
- package/lib/core.js +47 -0
- package/lib/discover.js +139 -0
- package/lib/escalations.js +92 -0
- package/lib/explib.js +149 -0
- package/lib/impact.js +55 -0
- package/lib/index.js +109 -0
- package/lib/knowledge.js +108 -0
- package/lib/meshlib.js +375 -0
- package/lib/needs-input.js +32 -0
- package/lib/of-case.js +485 -0
- package/lib/of-engine.js +1061 -0
- package/lib/paperlib.js +200 -0
- package/lib/presentation.js +365 -0
- package/lib/registry.js +142 -0
- package/lib/routing-guard.js +126 -0
- package/lib/runtime.js +580 -0
- package/lib/scaffold-cht.js +318 -0
- package/lib/scaffold-compressible.js +171 -0
- package/lib/scaffold.js +355 -0
- package/lib/settings-schema.js +86 -0
- package/lib/skills.js +53 -0
- package/lib/tools/build.js +90 -0
- package/lib/tools/case.js +1082 -0
- package/lib/tools/env.js +592 -0
- package/lib/tools/experience.js +165 -0
- package/lib/tools/mesh.js +408 -0
- package/lib/tools/meta.js +95 -0
- package/lib/tools/papers.js +105 -0
- package/lib/tools/render.js +94 -0
- package/lib/tools/run.js +331 -0
- package/lib/versions.js +133 -0
- package/licenses/dsh-openfoam-doctor-MIT.txt +21 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/package.json +44 -4
- package/skills/openfoam-analyze/SKILL.md +27 -0
- package/skills/openfoam-case-builder/SKILL.md +61 -0
- package/skills/openfoam-cht/SKILL.md +83 -0
- package/skills/openfoam-code-modify/SKILL.md +32 -0
- package/skills/openfoam-mesh-independence/SKILL.md +55 -0
- package/skills/openfoam-meshing/SKILL.md +30 -0
- package/skills/openfoam-paper-reproduction/SKILL.md +36 -0
- package/skills/openfoam-self-evolution/SKILL.md +21 -0
- package/skills/openfoam-solver-development/SKILL.md +61 -0
- package/skills/openfoam-stats/SKILL.md +46 -0
- package/skills/openfoam-viz/SKILL.md +35 -0
|
@@ -0,0 +1,1082 @@
|
|
|
1
|
+
import { checkCase as checkCaseEngine } from '../of-engine.js'
|
|
2
|
+
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { bashrcFor, caseLookupHint, dirSize, readText, resolveCase, resolveCaseInfo, run, runFoam, textOut, topLevelKeys } from '../runtime.js'
|
|
6
|
+
import { capsSummary, probeCaps } from '../versions.js'
|
|
7
|
+
import { diagnoseError } from '../knowledge.js'
|
|
8
|
+
import { parseBoundaryPatches } from '../of-engine.js'
|
|
9
|
+
import { algoCaseAudit, algoExtractContract, caseProbeFacts } from '../caselib.js'
|
|
10
|
+
import { checkBlockMeshDict, checkBoundaryFields, checkControlDict, checkFvSchemes, checkFvSolution, checkStrayTimes, readCaseDict } from '../of-engine.js'
|
|
11
|
+
import { availableDicts, caseBBox, caseRegions, containedPath, ensureFoamFile, normaliseDictPath } from '../of-case.js'
|
|
12
|
+
import { geometryScalePrompt, scaleGateApplies } from '../needs-input.js'
|
|
13
|
+
import { distributionKind, scaffoldFiles } from '../scaffold.js'
|
|
14
|
+
import { scaffoldCht } from '../scaffold-cht.js'
|
|
15
|
+
import { scaffoldCompressible } from '../scaffold-compressible.js'
|
|
16
|
+
import { classifyImpact, decideAction } from '../impact.js'
|
|
17
|
+
|
|
18
|
+
function hashText(text) { return createHash('sha256').update(String(text), 'utf8').digest('hex') }
|
|
19
|
+
|
|
20
|
+
const ENTRY_RE = /^[A-Za-z_][A-Za-z0-9_.:]*$/
|
|
21
|
+
// Any '#' token is a dictionary directive: #codeStream/#calc/#eval execute code,
|
|
22
|
+
// #include/#includeEtc/#includeIfPresent/#includeFunc read other files (absolute
|
|
23
|
+
// paths allowed), #inputMode/#remove rewrite the dictionary. None is a scalar.
|
|
24
|
+
const DANGEROUS_DIRECTIVE = /#\w+|\bcodeStream\b/i
|
|
25
|
+
|
|
26
|
+
/** One-line value validation: a value must not be able to add entries. */
|
|
27
|
+
function validateEntryValue(entry, value) {
|
|
28
|
+
if (!ENTRY_RE.test(String(entry))) {
|
|
29
|
+
return { ok: false, error: `invalid entry name: ${entry}`, hint: 'letters, digits, "_", "." and ":" are allowed' }
|
|
30
|
+
}
|
|
31
|
+
const text = String(value)
|
|
32
|
+
if (/[\r\n]/.test(text)) {
|
|
33
|
+
return { ok: false, error: 'value must be a single line', hint: 'a newline would inject extra dictionary entries' }
|
|
34
|
+
}
|
|
35
|
+
if (text.includes(';')) {
|
|
36
|
+
return { ok: false, error: 'value must not contain ";"', hint: 'the entry is terminated automatically' }
|
|
37
|
+
}
|
|
38
|
+
// A scalar value has no dictionary structure: braces are the only way to close
|
|
39
|
+
// the entry early and start a new one on the same line, so they are refused
|
|
40
|
+
// outright (a balanced pair is enough to smuggle `libs (...)` past the parser).
|
|
41
|
+
if (/[{}]/.test(text)) {
|
|
42
|
+
return {
|
|
43
|
+
ok: false,
|
|
44
|
+
error: 'braces are not allowed in a scalar value (sub-dictionaries cannot be edited by this tool)',
|
|
45
|
+
hint: 'dict_set changes one single-line top-level entry; edit a sub-dictionary with a dedicated tool',
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return { ok: true }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Content that executes code or loads libraries at dictionary-read time. */
|
|
52
|
+
function dangerousContent(text) {
|
|
53
|
+
const hits = []
|
|
54
|
+
if (DANGEROUS_DIRECTIVE.test(String(text))) hits.push('code directive (#codeStream/#calc/#eval/#include)')
|
|
55
|
+
return hits
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sha256(file) {
|
|
59
|
+
try { return createHash('sha256').update(readFileSync(file)).digest('hex') } catch { return null }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function changesDirOf(dir) { return join(dir, '.openfoam-changes') }
|
|
63
|
+
|
|
64
|
+
function listChanges(dir) {
|
|
65
|
+
try { return readdirSync(changesDirOf(dir)).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)).slice(-20) } catch { return [] }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Current value of a top-level entry, or null when it is absent. */
|
|
69
|
+
function topLevelEntryValue(text, entry) {
|
|
70
|
+
const re = new RegExp('^(\\s*)' + entry.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s+([^;]*);')
|
|
71
|
+
const lines = String(text).split('\n')
|
|
72
|
+
let depth = 0
|
|
73
|
+
for (const line of lines) {
|
|
74
|
+
if (depth === 0) {
|
|
75
|
+
const m = re.exec(line)
|
|
76
|
+
if (m) return m[2].trim()
|
|
77
|
+
}
|
|
78
|
+
depth += (line.match(/{/g) || []).length - (line.match(/}/g) || []).length
|
|
79
|
+
}
|
|
80
|
+
return null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Replace (or append) one top-level entry; returns the new text without writing. */
|
|
84
|
+
function replaceTopLevelEntry(text, entry, value, append) {
|
|
85
|
+
const re = new RegExp('^(\\s*)' + entry.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s+([^;]*);')
|
|
86
|
+
const lines = String(text).split('\n')
|
|
87
|
+
let depth = 0
|
|
88
|
+
let oldValue = null
|
|
89
|
+
let replaced = false
|
|
90
|
+
let lineNo = -1
|
|
91
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
92
|
+
const line = lines[i]
|
|
93
|
+
if (!replaced && depth === 0) {
|
|
94
|
+
const m = re.exec(line)
|
|
95
|
+
if (m) {
|
|
96
|
+
oldValue = m[2].trim()
|
|
97
|
+
lines[i] = m[1] + entry + ' ' + value + ';'
|
|
98
|
+
replaced = true
|
|
99
|
+
lineNo = i + 1
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
depth += (line.match(/{/g) || []).length - (line.match(/}/g) || []).length
|
|
103
|
+
}
|
|
104
|
+
if (!replaced) {
|
|
105
|
+
// `functions`, `boundaryField`, `libs`-style blocks are subdictionaries, not
|
|
106
|
+
// single-line values: a line-based editor must refuse them explicitly.
|
|
107
|
+
const subdict = new RegExp('^\\s*' + entry.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*(\\{|$)')
|
|
108
|
+
let depthCheck = 0
|
|
109
|
+
for (const line of lines) {
|
|
110
|
+
if (depthCheck === 0 && subdict.test(line)) return { ok: false, reason: 'subdictionary' }
|
|
111
|
+
depthCheck += (line.match(/{/g) || []).length - (line.match(/}/g) || []).length
|
|
112
|
+
}
|
|
113
|
+
if (!append) return { ok: false, reason: 'not-found' }
|
|
114
|
+
lines.push(`${entry} ${value};`)
|
|
115
|
+
lineNo = lines.length
|
|
116
|
+
}
|
|
117
|
+
return { ok: true, text: lines.join('\n'), old: oldValue, line: lineNo, replaced }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Remove one single-line top-level entry (used to undo an appended key). */
|
|
121
|
+
function removeTopLevelEntry(text, entry) {
|
|
122
|
+
const re = new RegExp('^\\s*' + entry.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s+[^;]*;\\s*$')
|
|
123
|
+
const lines = String(text).split('\n')
|
|
124
|
+
let depth = 0
|
|
125
|
+
let removed = 0
|
|
126
|
+
const kept = []
|
|
127
|
+
for (const line of lines) {
|
|
128
|
+
const atTop = depth === 0
|
|
129
|
+
if (atTop && removed === 0 && re.test(line)) { removed += 1 } else { kept.push(line) }
|
|
130
|
+
depth += (line.match(/{/g) || []).length - (line.match(/}/g) || []).length
|
|
131
|
+
}
|
|
132
|
+
if (removed === 0) return { ok: false, reason: 'not-found' }
|
|
133
|
+
return { ok: true, text: kept.join('\n') }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** One-shot human decision for a critical change; fails closed. */
|
|
137
|
+
async function requestApproval({ approval, exec, toolName, reason }) {
|
|
138
|
+
if (!exec?.agent) {
|
|
139
|
+
return {
|
|
140
|
+
ok: false,
|
|
141
|
+
error: 'critical change requires approval, but this execution context carries no agent identity (fail-closed)',
|
|
142
|
+
hint: 'run the change from a normal agent turn, or edit the file manually',
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (typeof approval?.request !== 'function') {
|
|
146
|
+
return {
|
|
147
|
+
ok: false,
|
|
148
|
+
error: 'critical change requires approval, but the DSH approval service is not mounted (fail-closed)',
|
|
149
|
+
hint: 'mount @deepseek-ai/dsh-user-approval with an answerer, or edit the file manually',
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
const outcome = await approval.request({ agent: exec?.agent, toolName, callId: exec?.callId, reason })
|
|
154
|
+
const value = typeof outcome === 'string' ? outcome : outcome?.type ?? outcome?.outcome
|
|
155
|
+
if (value === 'allowed-once') return { ok: true, outcome: 'allowed-once' }
|
|
156
|
+
return { ok: false, outcome: value || 'unavailable', error: `approval ${value || 'unavailable'}: the change was not applied` }
|
|
157
|
+
} catch (e) {
|
|
158
|
+
return { ok: false, error: 'approval failed: ' + String((e && e.message) || e) }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export default function caseTools({ cfg, getApproval }) {
|
|
163
|
+
return [
|
|
164
|
+
// --- tool: case doctor (silent failures, from dsh-openfoam-doctor, MIT) ---
|
|
165
|
+
{
|
|
166
|
+
name: 'openfoam_check',
|
|
167
|
+
description: 'Audit an OpenFOAM case for the failures that do not announce themselves: steadyState paired with timeStep writes, limiter=1 (negative k/epsilon), unbounded advection, nNonOrthogonalCorrectors 0 on skewed meshes, stray time dirs, boundary mistakes. Deterministic — every finding has a fix. Run before the first solver run.',
|
|
168
|
+
parameters: {
|
|
169
|
+
type: 'object',
|
|
170
|
+
properties: {
|
|
171
|
+
casePath: { type: 'string' },
|
|
172
|
+
file: { type: 'string', description: 'Optional: check only one dict — controlDict | fvSchemes | fvSolution | blockMeshDict | boundaries | times.' },
|
|
173
|
+
region: { type: 'string', description: 'Check one region of a multi-region case; by default every region is checked.' },
|
|
174
|
+
},
|
|
175
|
+
required: ['casePath'],
|
|
176
|
+
},
|
|
177
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
178
|
+
timeoutMs: 60000,
|
|
179
|
+
isConcurrencySafe: () => true,
|
|
180
|
+
execute: async (args) => {
|
|
181
|
+
const dir = resolveCase(cfg, args && args.casePath)
|
|
182
|
+
if (!dir || !existsSync(dir)) return { ok: false, error: 'case not found: ' + dir + caseLookupHint(cfg) }
|
|
183
|
+
const regions = caseRegions(dir)
|
|
184
|
+
if (args.region && regions.length && !regions.includes(args.region)) {
|
|
185
|
+
return { ok: false, error: `no such region: ${args.region}`, regions }
|
|
186
|
+
}
|
|
187
|
+
const wanted = args.region ? [args.region] : regions
|
|
188
|
+
const perRegion = (fn) => (wanted.length
|
|
189
|
+
? wanted.flatMap((r) => fn(dir, r).map((f) => ({ ...f, region: r })))
|
|
190
|
+
: fn(dir))
|
|
191
|
+
let findings
|
|
192
|
+
if (args.file === 'controlDict') findings = checkControlDict(dir)
|
|
193
|
+
else if (args.file === 'fvSchemes') findings = perRegion(checkFvSchemes)
|
|
194
|
+
else if (args.file === 'fvSolution') findings = perRegion(checkFvSolution)
|
|
195
|
+
else if (args.file === 'blockMeshDict') findings = perRegion(checkBlockMeshDict)
|
|
196
|
+
else if (args.file === 'boundaries') findings = perRegion(checkBoundaryFields)
|
|
197
|
+
else if (args.file === 'times') findings = checkStrayTimes(dir)
|
|
198
|
+
else findings = checkCaseEngine(dir, { regions: wanted })
|
|
199
|
+
|
|
200
|
+
// Geometry-scale gate: a metre-sized box is the classic sign of a model
|
|
201
|
+
// built in millimetres that was never rescaled.
|
|
202
|
+
let needsInput = null
|
|
203
|
+
const askAbove = Number(cfg.scaleAskAbove) || 0
|
|
204
|
+
const bbox = caseBBox(dir)
|
|
205
|
+
if (bbox.ok && scaleGateApplies(bbox.maxExtent, askAbove)) {
|
|
206
|
+
const extent = Number(bbox.maxExtent.toFixed(4))
|
|
207
|
+
findings = findings.concat([{
|
|
208
|
+
rule: 'geometry-scale',
|
|
209
|
+
severity: 'ask',
|
|
210
|
+
title: `geometry is ${extent} m across`,
|
|
211
|
+
detail: `The mesh bounding box is ${extent} m. If the model was built in millimetres, everything is 1000x too large and the physics (Reynolds, Courant, time scales) is wrong.`,
|
|
212
|
+
fix: 'Confirm the units with the user; if millimetres, rescale the geometry by 1e-3 and rebuild the mesh.',
|
|
213
|
+
}])
|
|
214
|
+
needsInput = geometryScalePrompt({ extent: bbox.maxExtent, askAbove })
|
|
215
|
+
}
|
|
216
|
+
const caps = await probeCaps(bashrcFor(cfg, args.distribution), args.distribution || cfg.defaultDistribution)
|
|
217
|
+
if (caps.support === 'unknown') {
|
|
218
|
+
findings = findings.concat([{
|
|
219
|
+
rule: 'untested-version',
|
|
220
|
+
severity: 'warn',
|
|
221
|
+
title: `this OpenFOAM release is not covered by the tests (${capsSummary(caps)})`,
|
|
222
|
+
detail: 'The installed version differs from the ones the workbench is validated against (org 14, com v2606). Dictionary conventions are taken from the family and may not match this release.',
|
|
223
|
+
fix: 'Treat findings as advice, check the solver output, and report the version so it can be added to the support matrix.',
|
|
224
|
+
}])
|
|
225
|
+
}
|
|
226
|
+
return {
|
|
227
|
+
ok: true,
|
|
228
|
+
path: dir,
|
|
229
|
+
caps: { summary: capsSummary(caps), support: caps.support, family: caps.family, modular: caps.modular },
|
|
230
|
+
resolvedFrom: resolveCaseInfo(cfg, args.casePath).resolvedFrom,
|
|
231
|
+
...(regions.length ? { regions } : {}),
|
|
232
|
+
...(args.region ? { region: args.region } : {}),
|
|
233
|
+
count: findings.length,
|
|
234
|
+
findings,
|
|
235
|
+
...(needsInput ? { needs_input: needsInput } : {}),
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
// --- tool: read a dictionary as JSON ---
|
|
240
|
+
{
|
|
241
|
+
name: 'openfoam_read_dict',
|
|
242
|
+
description: 'Read an OpenFOAM dictionary as JSON. Accepts `controlDict`, `fluid/fvSchemes`, `system/fluid/fvSchemes`, `constant/fluid/thermophysicalProperties`, `0/fluid/T` — with `region` when the case is multi-region. Use this INSTEAD of reading/cat-ing dictionary files to check what a case actually says. No OpenFOAM run needed.',
|
|
243
|
+
parameters: {
|
|
244
|
+
type: 'object',
|
|
245
|
+
properties: {
|
|
246
|
+
casePath: { type: 'string' },
|
|
247
|
+
file: { type: 'string', description: 'controlDict | fvSchemes | <region>/fvSchemes | system/<region>/<dict> | constant/<region>/<dict> | 0/<region>/<field>' },
|
|
248
|
+
region: { type: 'string', description: 'Region name for multi-region cases (e.g. fluid); a bare file name is then looked up in system/<region> first.' },
|
|
249
|
+
},
|
|
250
|
+
required: ['casePath', 'file'],
|
|
251
|
+
},
|
|
252
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
253
|
+
timeoutMs: 60000,
|
|
254
|
+
isConcurrencySafe: () => true,
|
|
255
|
+
execute: async (args) => {
|
|
256
|
+
const dir = resolveCase(cfg, args && args.casePath)
|
|
257
|
+
if (!dir || !existsSync(dir)) return { ok: false, error: 'case not found: ' + dir + caseLookupHint(cfg) }
|
|
258
|
+
const found = normaliseDictPath(dir, args && args.file, args && args.region)
|
|
259
|
+
if (!found.ok) {
|
|
260
|
+
const available = availableDicts(dir)
|
|
261
|
+
const regions = caseRegions(dir)
|
|
262
|
+
const notFound = {
|
|
263
|
+
ok: false,
|
|
264
|
+
error: found.error || `not found: ${args.file}`,
|
|
265
|
+
...(found.hint ? { hint: found.hint } : {}),
|
|
266
|
+
tried: found.tried,
|
|
267
|
+
hint: regions.length
|
|
268
|
+
? `multi-region case (${regions.join(', ')}): pass file="<region>/<dict>" or region="<region>"; system/<region>/, constant/<region>/ and 0/<region>/ also work`
|
|
269
|
+
: 'file is resolved against system/, constant/ and 0/; system/constant/0 prefixes are accepted as-is',
|
|
270
|
+
}
|
|
271
|
+
if (regions.length) notFound.regions = regions
|
|
272
|
+
if (available.length) notFound.available = available
|
|
273
|
+
return notFound
|
|
274
|
+
}
|
|
275
|
+
const dict = readCaseDict(dir, found.rel)
|
|
276
|
+
if (dict === null) return { ok: false, error: 'cannot parse: ' + found.rel, tried: found.tried }
|
|
277
|
+
const foundDict = { ok: true, file: found.rel, dict }
|
|
278
|
+
if (args && args.region) foundDict.region = args.region
|
|
279
|
+
return foundDict
|
|
280
|
+
},
|
|
281
|
+
},
|
|
282
|
+
// --- tool: patch diff ---
|
|
283
|
+
{
|
|
284
|
+
name: 'openfoam_patch_diff',
|
|
285
|
+
description: 'Report the boundary patches of a case (name, type, nFaces) from constant/polyMesh/boundary; optionally diff against a previous snapshot to find added/missing/type-changed patches.',
|
|
286
|
+
parameters: {
|
|
287
|
+
type: 'object',
|
|
288
|
+
properties: {
|
|
289
|
+
casePath: { type: 'string' },
|
|
290
|
+
snapshot_before: { type: 'string', description: 'Optional JSON from a previous call (patches array) to diff against.' },
|
|
291
|
+
},
|
|
292
|
+
required: ['casePath'],
|
|
293
|
+
},
|
|
294
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
295
|
+
timeoutMs: 60000,
|
|
296
|
+
isConcurrencySafe: () => true,
|
|
297
|
+
execute: async (args) => {
|
|
298
|
+
const dir = resolveCase(cfg, args.casePath)
|
|
299
|
+
if (!dir || !existsSync(dir)) return { ok: false, error: 'case not found: ' + dir + caseLookupHint(cfg) }
|
|
300
|
+
const text = readText(join(dir, 'constant/polyMesh/boundary'))
|
|
301
|
+
if (!text) return { ok: false, error: 'no constant/polyMesh/boundary' }
|
|
302
|
+
const patches = parseBoundaryPatches(text)
|
|
303
|
+
let diff = null
|
|
304
|
+
if (args.snapshot_before) {
|
|
305
|
+
try {
|
|
306
|
+
const before = JSON.parse(args.snapshot_before)
|
|
307
|
+
const beforeArr = Array.isArray(before) ? before : before.patches || []
|
|
308
|
+
const beforeMap = new Map(beforeArr.map((p) => [p.name, p]))
|
|
309
|
+
const nowMap = new Map(patches.map((p) => [p.name, p]))
|
|
310
|
+
const added = patches.filter((p) => !beforeMap.has(p.name)).map((p) => p.name)
|
|
311
|
+
const missing = [...beforeMap.keys()].filter((n) => !nowMap.has(n))
|
|
312
|
+
const typeChanged = patches
|
|
313
|
+
.filter((p) => beforeMap.has(p.name) && beforeMap.get(p.name).type !== p.type)
|
|
314
|
+
.map((p) => ({ name: p.name, from: beforeMap.get(p.name).type, to: p.type }))
|
|
315
|
+
diff = { added, missing, typeChanged }
|
|
316
|
+
} catch (e) {
|
|
317
|
+
diff = { error: 'invalid snapshot_before: ' + ((e && e.message) || e) }
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return { ok: true, patches, diff }
|
|
321
|
+
},
|
|
322
|
+
},
|
|
323
|
+
// --- tool: diagnose an error ---
|
|
324
|
+
{
|
|
325
|
+
name: 'openfoam_diagnose_error',
|
|
326
|
+
description: 'Match a log tail / error section against built-in OpenFOAM/C++ error patterns (plus learned ones) and return category, causes and next steps. Call it first on any non-zero exit or FOAM FATAL ERROR.',
|
|
327
|
+
parameters: {
|
|
328
|
+
type: 'object',
|
|
329
|
+
properties: { text: { type: 'string', description: 'log tail or error section (up to ~8000 chars).' } },
|
|
330
|
+
required: ['text'],
|
|
331
|
+
},
|
|
332
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
333
|
+
timeoutMs: 60000,
|
|
334
|
+
isConcurrencySafe: () => true,
|
|
335
|
+
execute: async (args) => diagnoseError(cfg, args.text),
|
|
336
|
+
},
|
|
337
|
+
// --- tool: four-step step 1 ---
|
|
338
|
+
{
|
|
339
|
+
name: 'openfoam_algo_extract_contract',
|
|
340
|
+
description: 'Heuristically extract an algorithm contract (inputs/outputs/equations/governing_type/assumptions) from an OpenFOAM .H/.C/.py or workspace file. Step 1 of the four-step method.',
|
|
341
|
+
parameters: {
|
|
342
|
+
type: 'object',
|
|
343
|
+
properties: { source_file: { type: 'string' }, algorithm_name: { type: 'string' } },
|
|
344
|
+
required: ['source_file'],
|
|
345
|
+
},
|
|
346
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
347
|
+
timeoutMs: 60000,
|
|
348
|
+
isConcurrencySafe: () => true,
|
|
349
|
+
execute: async (args) => algoExtractContract(cfg, args),
|
|
350
|
+
},
|
|
351
|
+
// --- tool: four-step step 2 ---
|
|
352
|
+
{
|
|
353
|
+
name: 'openfoam_case_probe_facts',
|
|
354
|
+
description: 'Probe a case and return its actual facts: solver, governing family, compressibility, phases, turbulence, dimensions, patches, fields in 0/, transport. Step 2 of the four-step method.',
|
|
355
|
+
parameters: {
|
|
356
|
+
type: 'object',
|
|
357
|
+
properties: { case_path: { type: 'string' } },
|
|
358
|
+
required: ['case_path'],
|
|
359
|
+
},
|
|
360
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
361
|
+
timeoutMs: 60000,
|
|
362
|
+
isConcurrencySafe: () => true,
|
|
363
|
+
execute: async (args) => caseProbeFacts(cfg, args),
|
|
364
|
+
},
|
|
365
|
+
// --- tool: four-step step 3 ---
|
|
366
|
+
{
|
|
367
|
+
name: 'openfoam_algo_case_audit',
|
|
368
|
+
description: 'Compare an algorithm contract (step 1) with case facts (step 2), list mismatches. Entering step 4 while mismatches are non-empty is forbidden.',
|
|
369
|
+
parameters: {
|
|
370
|
+
type: 'object',
|
|
371
|
+
properties: { contract: { type: 'object' }, case_facts: { type: 'object' } },
|
|
372
|
+
required: ['contract', 'case_facts'],
|
|
373
|
+
},
|
|
374
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
375
|
+
timeoutMs: 30000,
|
|
376
|
+
isConcurrencySafe: () => true,
|
|
377
|
+
execute: async (args) => algoCaseAudit(args),
|
|
378
|
+
},
|
|
379
|
+
// --- tool: set a dictionary entry atomically (impact-aware) ---
|
|
380
|
+
{
|
|
381
|
+
name: 'openfoam_dict_set',
|
|
382
|
+
description: 'Set one top-level dictionary entry atomically (write temp + rename, .bak kept). Impact-aware: output/organisation keys in controlDict apply immediately; anything that can change physics or numerics (0/*, fvSchemes, fvSolution, constant/*, deltaT, application) is a preview unless apply:true is passed, and libs/functions require approval. Pass expect to refuse a write whose current value differs. Returns changeId for openfoam_dict_undo. Accepts multi-region paths (`fluid/fvSchemes`, `0/fluid/T`). Use this INSTEAD of sed/python.',
|
|
383
|
+
parameters: {
|
|
384
|
+
type: 'object',
|
|
385
|
+
properties: {
|
|
386
|
+
casePath: { type: 'string' },
|
|
387
|
+
file: { type: 'string', description: 'controlDict | fluid/fvSchemes | system/fluid/fvSchemes | 0/fluid/T' },
|
|
388
|
+
entry: { type: 'string' },
|
|
389
|
+
value: { type: 'string', description: 'OpenFOAM text, e.g. "0.01", "uniform (1 0 0)", "Gauss linear".' },
|
|
390
|
+
region: { type: 'string' },
|
|
391
|
+
dryRun: { type: 'boolean', description: 'Force a preview (never writes).' },
|
|
392
|
+
apply: { type: 'boolean', description: 'Write a high-impact change without a preview.' },
|
|
393
|
+
expect: { type: 'string', description: 'Refuse unless the current value equals this.' },
|
|
394
|
+
backup: { type: 'boolean', description: 'Keep <file>.bak (default true).' },
|
|
395
|
+
append: { type: 'boolean', description: 'Append the entry when it does not exist at top level.' },
|
|
396
|
+
},
|
|
397
|
+
required: ['casePath', 'file', 'entry', 'value'],
|
|
398
|
+
},
|
|
399
|
+
output: {
|
|
400
|
+
schema: { type: 'object' },
|
|
401
|
+
render: (_a, v) => {
|
|
402
|
+
if (v && v.applied === false && v.preview) {
|
|
403
|
+
return [{ type: 'text', text: `NOT APPLIED (preview, ${v.impact} impact)\n` + JSON.stringify(v, null, 2) }]
|
|
404
|
+
}
|
|
405
|
+
return textOut(v)
|
|
406
|
+
},
|
|
407
|
+
},
|
|
408
|
+
timeoutMs: 60000,
|
|
409
|
+
isConcurrencySafe: () => false,
|
|
410
|
+
execute: async (args, exec) => {
|
|
411
|
+
const dir = resolveCase(cfg, args.casePath)
|
|
412
|
+
if (!dir || !existsSync(dir)) return { ok: false, error: 'case not found: ' + dir + caseLookupHint(cfg) }
|
|
413
|
+
const found = normaliseDictPath(dir, args.file, args.region)
|
|
414
|
+
if (!found.ok) {
|
|
415
|
+
return {
|
|
416
|
+
ok: false,
|
|
417
|
+
error: found.error || 'not found: ' + args.file,
|
|
418
|
+
file: args.file,
|
|
419
|
+
...(found.tried ? { tried: found.tried } : {}),
|
|
420
|
+
...(found.hint ? { hint: found.hint } : {}),
|
|
421
|
+
available: availableDicts(dir),
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const target = join(dir, found.rel)
|
|
425
|
+
const text = readText(target)
|
|
426
|
+
if (text == null) return { ok: false, error: 'cannot read: ' + found.rel }
|
|
427
|
+
const beforeHash = hashText(text)
|
|
428
|
+
const entry = String(args.entry)
|
|
429
|
+
const value = String(args.value)
|
|
430
|
+
const valid = validateEntryValue(entry, value)
|
|
431
|
+
if (!valid.ok) return { ok: false, applied: false, file: found.rel, entry, ...valid }
|
|
432
|
+
// A value that carries an executable directive is critical regardless of
|
|
433
|
+
// the entry it is written to.
|
|
434
|
+
const danger = dangerousContent(`${entry} ${value};`)
|
|
435
|
+
const impact = danger.length ? 'critical' : classifyImpact(found.rel, entry, value)
|
|
436
|
+
|
|
437
|
+
// `expect` guard: refuse to write on top of a value the caller did not see.
|
|
438
|
+
if (args.expect !== undefined) {
|
|
439
|
+
const current = topLevelEntryValue(text, entry)
|
|
440
|
+
if (current === null) return { ok: false, error: `entry not found at top level: ${entry}`, file: found.rel, topLevelEntries: topLevelKeys(text).slice(0, 40) }
|
|
441
|
+
if (String(current).trim() !== String(args.expect).trim()) {
|
|
442
|
+
return { ok: false, error: `expect mismatch: expected "${args.expect}", found "${current}"`, file: found.rel, entry, found: current }
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const edit = replaceTopLevelEntry(text, entry, value, Boolean(args.append))
|
|
447
|
+
if (!edit.ok && edit.reason === 'subdictionary') {
|
|
448
|
+
return {
|
|
449
|
+
ok: false,
|
|
450
|
+
error: `${entry} is a sub-dictionary, not a single-line entry`,
|
|
451
|
+
file: found.rel,
|
|
452
|
+
impact,
|
|
453
|
+
hint: 'openfoam_dict_set edits single-line top-level entries only; set a scalar key inside the block instead, or edit the block manually',
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (!edit.ok) {
|
|
457
|
+
return {
|
|
458
|
+
ok: false,
|
|
459
|
+
error: `entry not found at top level: ${entry}`,
|
|
460
|
+
file: found.rel,
|
|
461
|
+
topLevelEntries: topLevelKeys(text).slice(0, 40),
|
|
462
|
+
hint: 'pass append:true to add it (or check that the entry is not inside a sub-dictionary)',
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (edit.text === text) return { ok: true, changed: false, applied: false, impact, file: found.rel, entry, note: 'value already set' }
|
|
466
|
+
// Defence in depth: an edit may only touch its own top-level entry.
|
|
467
|
+
const beforeKeys = new Set(topLevelKeys(text))
|
|
468
|
+
const afterKeys = new Set(topLevelKeys(edit.text))
|
|
469
|
+
const extra = [...afterKeys].filter((k) => !beforeKeys.has(k) && k !== entry)
|
|
470
|
+
const missing = [...beforeKeys].filter((k) => !afterKeys.has(k) && k !== entry)
|
|
471
|
+
if (extra.length || missing.length) {
|
|
472
|
+
return { ok: false, applied: false, error: 'the edit would change the top-level structure of the dictionary', file: found.rel, entry, extra, missing }
|
|
473
|
+
}
|
|
474
|
+
const semisBefore = (text.match(/;/g) || []).length
|
|
475
|
+
const semisAfter = (edit.text.match(/;/g) || []).length
|
|
476
|
+
if (!args.append && semisAfter !== semisBefore) {
|
|
477
|
+
return { ok: false, applied: false, error: 'the edit would add or remove entries (semicolon count changed)', file: found.rel, entry, semisBefore, semisAfter }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const action = decideAction({
|
|
481
|
+
impact,
|
|
482
|
+
writeMode: cfg.writeMode || 'impact',
|
|
483
|
+
applyRequested: args.apply === true,
|
|
484
|
+
dryRun: args.dryRun === true,
|
|
485
|
+
})
|
|
486
|
+
|
|
487
|
+
let approvalInfo = null
|
|
488
|
+
if (action === 'approval') {
|
|
489
|
+
const service = typeof getApproval === 'function' ? getApproval() : undefined
|
|
490
|
+
const asked = await requestApproval({ approval: service, exec, toolName: 'openfoam_dict_set', reason: `set ${found.rel}: ${entry} = ${value} (critical impact)` })
|
|
491
|
+
approvalInfo = {
|
|
492
|
+
outcome: asked.outcome || (asked.ok ? 'allowed-once' : 'unavailable'),
|
|
493
|
+
hasService: Boolean(service && typeof service.request === 'function'),
|
|
494
|
+
hasAgent: Boolean(exec?.agent),
|
|
495
|
+
hasCallId: Boolean(exec?.callId),
|
|
496
|
+
}
|
|
497
|
+
if (!asked.ok) return { ok: false, ...asked, approval: approvalInfo, impact, file: found.rel, entry, old: edit.old, new: value, ...(danger.length ? { danger } : {}) }
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
if (action === 'preview') {
|
|
501
|
+
return {
|
|
502
|
+
ok: true,
|
|
503
|
+
applied: false,
|
|
504
|
+
preview: true,
|
|
505
|
+
changed: true,
|
|
506
|
+
impact,
|
|
507
|
+
file: found.rel,
|
|
508
|
+
entry,
|
|
509
|
+
old: edit.old,
|
|
510
|
+
new: value,
|
|
511
|
+
line: edit.line,
|
|
512
|
+
note: 'NOT APPLIED — this change can alter physics or numerics; re-run with apply:true (or set writeMode:"apply")',
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// Compare-and-swap: the edit was computed from `text`; if the file moved on
|
|
517
|
+
// (another agent, the user, a solver re-reading) refuse instead of
|
|
518
|
+
// overwriting the newer content with a stale copy.
|
|
519
|
+
const currentText = readText(target)
|
|
520
|
+
if (currentText == null || hashText(currentText) !== beforeHash) {
|
|
521
|
+
return {
|
|
522
|
+
ok: false,
|
|
523
|
+
applied: false,
|
|
524
|
+
error: 'the file changed after the change was prepared (concurrent modification); nothing was written',
|
|
525
|
+
file: found.rel,
|
|
526
|
+
entry,
|
|
527
|
+
hint: 're-read the dictionary with openfoam_read_dict and prepare the change again' + (impact === 'critical' ? ' (the approval must be requested again)' : ''),
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
const changeId = 'chg' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6)
|
|
531
|
+
const afterHash = createHash('sha256').update(edit.text, 'utf8').digest('hex')
|
|
532
|
+
const journal = changesDirOf(dir)
|
|
533
|
+
const journalPath = join(journal, changeId + '.json')
|
|
534
|
+
// Record the change *before* touching the case: a write without a durable
|
|
535
|
+
// undo record would advertise an undo that cannot be honoured.
|
|
536
|
+
try {
|
|
537
|
+
mkdirSync(journal, { recursive: true })
|
|
538
|
+
writeFileSync(journalPath, JSON.stringify({
|
|
539
|
+
changeId,
|
|
540
|
+
at: new Date().toISOString(),
|
|
541
|
+
file: found.rel,
|
|
542
|
+
entry,
|
|
543
|
+
old: edit.old,
|
|
544
|
+
new: value,
|
|
545
|
+
existedBefore: Boolean(edit.replaced),
|
|
546
|
+
afterHash,
|
|
547
|
+
tool: 'openfoam_dict_set',
|
|
548
|
+
}, null, 2) + '\n')
|
|
549
|
+
} catch (e) {
|
|
550
|
+
return {
|
|
551
|
+
ok: false,
|
|
552
|
+
error: 'cannot record the change for undo; nothing was written: ' + String((e && e.message) || e),
|
|
553
|
+
file: found.rel,
|
|
554
|
+
entry,
|
|
555
|
+
hint: 'check write permission on ' + journal,
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
const backup = args.backup === false ? null : target + '.bak'
|
|
560
|
+
if (backup) { try { cpSync(target, backup) } catch {} }
|
|
561
|
+
const tmp = `${target}.tmp-${process.pid}-${Date.now().toString(36)}`
|
|
562
|
+
try {
|
|
563
|
+
writeFileSync(tmp, edit.text)
|
|
564
|
+
renameSync(tmp, target)
|
|
565
|
+
} catch (e) {
|
|
566
|
+
try { rmSync(tmp, { force: true }) } catch {}
|
|
567
|
+
try { rmSync(journalPath, { force: true }) } catch {}
|
|
568
|
+
return { ok: false, error: 'write failed: ' + String((e && e.message) || e), file: found.rel, entry }
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
return {
|
|
572
|
+
ok: true,
|
|
573
|
+
applied: true,
|
|
574
|
+
changed: true,
|
|
575
|
+
impact,
|
|
576
|
+
file: found.rel,
|
|
577
|
+
path: target,
|
|
578
|
+
entry,
|
|
579
|
+
old: edit.old,
|
|
580
|
+
new: value,
|
|
581
|
+
backup,
|
|
582
|
+
line: edit.line,
|
|
583
|
+
changeId,
|
|
584
|
+
...(approvalInfo ? { approval: approvalInfo } : {}),
|
|
585
|
+
undo: { tool: 'openfoam_dict_undo', changeId, expectHash: afterHash },
|
|
586
|
+
}
|
|
587
|
+
},
|
|
588
|
+
},
|
|
589
|
+
// --- tool: undo one dict_set change ---
|
|
590
|
+
{
|
|
591
|
+
name: 'openfoam_dict_undo',
|
|
592
|
+
description: 'Revert one openfoam_dict_set change by changeId. Refuses when the file changed after that edit (afterHash mismatch), so a later edit is never silently discarded. Keeps a .bak of the current file.',
|
|
593
|
+
parameters: {
|
|
594
|
+
type: 'object',
|
|
595
|
+
properties: { casePath: { type: 'string' }, changeId: { type: 'string' }, region: { type: 'string' } },
|
|
596
|
+
required: ['casePath', 'changeId'],
|
|
597
|
+
},
|
|
598
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
599
|
+
timeoutMs: 60000,
|
|
600
|
+
isConcurrencySafe: () => false,
|
|
601
|
+
execute: async (args) => {
|
|
602
|
+
const dir = resolveCase(cfg, args.casePath)
|
|
603
|
+
if (!dir || !existsSync(dir)) return { ok: false, error: 'case not found: ' + dir + caseLookupHint(cfg) }
|
|
604
|
+
const record = readText(join(changesDirOf(dir), String(args.changeId) + '.json'))
|
|
605
|
+
if (!record) return { ok: false, error: `no such change: ${args.changeId}`, changes: listChanges(dir) }
|
|
606
|
+
let rec
|
|
607
|
+
try { rec = JSON.parse(record) } catch { return { ok: false, error: 'change record is not valid JSON: ' + args.changeId } }
|
|
608
|
+
const safe = containedPath(dir, rec.file)
|
|
609
|
+
if (!safe.ok) return { ok: false, error: 'the change record points outside the case: ' + safe.error, file: rec.file }
|
|
610
|
+
const target = safe.path
|
|
611
|
+
const text = readText(target)
|
|
612
|
+
if (text == null) return { ok: false, error: 'cannot read: ' + rec.file }
|
|
613
|
+
const currentHash = sha256(target)
|
|
614
|
+
if (rec.afterHash && currentHash !== rec.afterHash) {
|
|
615
|
+
return {
|
|
616
|
+
ok: false,
|
|
617
|
+
error: 'the file changed after this edit; refusing to undo',
|
|
618
|
+
changeId: rec.changeId,
|
|
619
|
+
file: rec.file,
|
|
620
|
+
entry: rec.entry,
|
|
621
|
+
hint: 'revert the later changes first (list them with openfoam_dict_undo? changes=...) or edit the entry manually',
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
const appended = rec.existedBefore === false
|
|
625
|
+
const edit = appended ? removeTopLevelEntry(text, rec.entry) : replaceTopLevelEntry(text, rec.entry, rec.old ?? '', false)
|
|
626
|
+
if (!edit.ok) return { ok: false, error: `entry not found any more: ${rec.entry}`, file: rec.file }
|
|
627
|
+
const backup = target + '.bak'
|
|
628
|
+
try { cpSync(target, backup) } catch {}
|
|
629
|
+
const tmp = `${target}.tmp-${process.pid}-${Date.now().toString(36)}`
|
|
630
|
+
writeFileSync(tmp, edit.text)
|
|
631
|
+
renameSync(tmp, target)
|
|
632
|
+
return {
|
|
633
|
+
ok: true,
|
|
634
|
+
applied: true,
|
|
635
|
+
undoOf: rec.changeId,
|
|
636
|
+
file: rec.file,
|
|
637
|
+
entry: rec.entry,
|
|
638
|
+
restored: appended ? null : rec.old,
|
|
639
|
+
removed: appended,
|
|
640
|
+
was: rec.new,
|
|
641
|
+
afterHash: sha256(target),
|
|
642
|
+
}
|
|
643
|
+
},
|
|
644
|
+
},
|
|
645
|
+
// --- tool: field statistics (min/max) at a time ---
|
|
646
|
+
{
|
|
647
|
+
name: 'openfoam_field_stats',
|
|
648
|
+
description: 'Min/max of one field at the latest (or a given) time, using the distribution-appropriate post-processing utility and function object (org: foamPostProcess + cellMin/cellMax; com: postProcess + cellMin/cellMax). Read-only; use it to judge magnitudes (U range, T rise, p level) without opening ParaView.',
|
|
649
|
+
parameters: {
|
|
650
|
+
type: 'object',
|
|
651
|
+
properties: {
|
|
652
|
+
casePath: { type: 'string' },
|
|
653
|
+
field: { type: 'string', description: 'Field name, e.g. U, T, p, k.' },
|
|
654
|
+
time: { type: 'string', description: 'Time value; default: latest written time.' },
|
|
655
|
+
region: { type: 'string', description: 'Mesh region for multi-region cases (e.g. fluid, solid).' },
|
|
656
|
+
distribution: { type: 'string', description: 'org | com' },
|
|
657
|
+
},
|
|
658
|
+
required: ['casePath', 'field'],
|
|
659
|
+
},
|
|
660
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
661
|
+
timeoutMs: 180000,
|
|
662
|
+
isConcurrencySafe: () => true,
|
|
663
|
+
execute: async (args) => {
|
|
664
|
+
const dir = resolveCase(cfg, args.casePath)
|
|
665
|
+
if (!dir || !existsSync(dir)) return { ok: false, error: 'case not found: ' + dir + caseLookupHint(cfg) }
|
|
666
|
+
const bash = bashrcFor(cfg, args.distribution)
|
|
667
|
+
if (!bash || !existsSync(bash)) return { ok: false, error: 'bashrc/foamRoot not configured' }
|
|
668
|
+
const field = String(args.field || '').trim()
|
|
669
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(field)) return { ok: false, error: 'invalid field name: ' + args.field }
|
|
670
|
+
const dist = String(args.distribution || cfg.defaultDistribution || '')
|
|
671
|
+
const utility = /^(v\d|com)/i.test(dist) ? 'postProcess' : 'foamPostProcess'
|
|
672
|
+
const time = args.time != null && String(args.time).trim() !== '' ? ['-time', String(args.time)] : ['-latestTime']
|
|
673
|
+
const regionArgs = args.region ? ['-region', String(args.region)] : []
|
|
674
|
+
const parse = (text) => {
|
|
675
|
+
const out = {}
|
|
676
|
+
for (const line of String(text).split('\n')) {
|
|
677
|
+
const m = /(?:min|max)\(all\) of \w+ = (?:\(([^)]*)\)|([-\d.eE+]+))/.exec(line)
|
|
678
|
+
if (!m) continue
|
|
679
|
+
const raw = m[1] !== undefined ? m[1].trim().split(/\s+/) : m[2]
|
|
680
|
+
const nums = Array.isArray(raw) ? raw.map(Number) : [Number(raw)]
|
|
681
|
+
if (!nums.every((n) => Number.isFinite(n))) continue
|
|
682
|
+
out[line.includes('min(') ? 'min' : 'max'] = nums.length === 1 ? nums[0] : nums
|
|
683
|
+
}
|
|
684
|
+
return out
|
|
685
|
+
}
|
|
686
|
+
const runOne = async (fn) => {
|
|
687
|
+
const r = await runFoam([utility, ...regionArgs, '-func', `${fn}(${field})`, ...time], { bashrc: bash, dir, timeoutMs: 120000 })
|
|
688
|
+
return { ok: r.ok, text: (r.stdout || '') + (r.stderr || '') }
|
|
689
|
+
}
|
|
690
|
+
const lo = await runOne('cellMin')
|
|
691
|
+
const hi = await runOne('cellMax')
|
|
692
|
+
const min = parse(lo.text).min
|
|
693
|
+
const max = parse(hi.text).max
|
|
694
|
+
if (min === undefined && max === undefined) {
|
|
695
|
+
return {
|
|
696
|
+
ok: false,
|
|
697
|
+
error: `no statistics parsed for ${field}`,
|
|
698
|
+
hint: `check that the field exists at the requested time; the utility was ${utility}`,
|
|
699
|
+
logTail: (lo.text + '\n' + hi.text).slice(-1500),
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
const mag = await runOne('cellMaxMag')
|
|
703
|
+
const maxMag = parse(mag.text).max
|
|
704
|
+
return {
|
|
705
|
+
ok: true,
|
|
706
|
+
field,
|
|
707
|
+
...(args.region ? { region: String(args.region) } : {}),
|
|
708
|
+
time: time[1] || 'latest',
|
|
709
|
+
min,
|
|
710
|
+
max,
|
|
711
|
+
...(maxMag !== undefined ? { maxMagnitude: maxMag } : {}),
|
|
712
|
+
utility,
|
|
713
|
+
}
|
|
714
|
+
},
|
|
715
|
+
},
|
|
716
|
+
// --- tool: clean run artefacts ---
|
|
717
|
+
{
|
|
718
|
+
name: 'openfoam_clean',
|
|
719
|
+
description: 'List (dry run by default) or delete run artefacts: log files, numeric time directories, processor* decomposition and postProcessing/. Never touches 0/, constant/ or system/. Use this INSTEAD of rm -rf, and dry-run first.',
|
|
720
|
+
parameters: {
|
|
721
|
+
type: 'object',
|
|
722
|
+
properties: {
|
|
723
|
+
casePath: { type: 'string' },
|
|
724
|
+
what: { type: 'array', items: { type: 'string', description: 'logs | timeDirs | processorDirs | postProcessing' }, description: 'Default: logs + timeDirs.' },
|
|
725
|
+
keepTimes: { type: 'array', items: { type: 'string' }, description: 'Time directory names to keep (e.g. the latest).' },
|
|
726
|
+
dryRun: { type: 'boolean', description: 'Default true: only report what would be removed.' },
|
|
727
|
+
force: { type: 'boolean', description: 'Clean even when the directory does not look like an OpenFOAM case.' },
|
|
728
|
+
},
|
|
729
|
+
required: ['casePath'],
|
|
730
|
+
},
|
|
731
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
732
|
+
timeoutMs: 120000,
|
|
733
|
+
isConcurrencySafe: () => false,
|
|
734
|
+
execute: async (args, exec) => {
|
|
735
|
+
const dir = resolveCase(cfg, args.casePath)
|
|
736
|
+
if (!dir || !existsSync(dir)) return { ok: false, error: 'case not found: ' + dir + caseLookupHint(cfg) }
|
|
737
|
+
// Only clean something that looks like an OpenFOAM case: a random project
|
|
738
|
+
// folder must not lose its build.log and a directory named "2024".
|
|
739
|
+
const markers = ['system/controlDict', 'constant/polyMesh', 'system/blockMeshDict'].filter((rel) => existsSync(join(dir, rel)))
|
|
740
|
+
const regionMeshes = (() => { try { return caseRegions(dir).length > 0 } catch { return false } })()
|
|
741
|
+
if (!markers.length && !regionMeshes && args.force !== true) {
|
|
742
|
+
return {
|
|
743
|
+
ok: false,
|
|
744
|
+
error: 'not an OpenFOAM case: no system/controlDict, system/blockMeshDict or constant/polyMesh',
|
|
745
|
+
path: dir,
|
|
746
|
+
note: 'cleaning is refused so an arbitrary directory cannot lose files that merely look like logs or time directories',
|
|
747
|
+
hint: 'pass force:true only if you really mean to clean this directory, or use rm deliberately',
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
if (!markers.length && !regionMeshes && args.force === true) {
|
|
751
|
+
// force overrides the case-marker guard: it is a destructive decision and
|
|
752
|
+
// needs the same approval as a critical dictionary edit.
|
|
753
|
+
const service = typeof getApproval === 'function' ? getApproval() : undefined
|
|
754
|
+
const asked = await requestApproval({ approval: service, exec, toolName: 'openfoam_clean', reason: `clean ${dir} even though it is not an OpenFOAM case (force:true)` })
|
|
755
|
+
if (!asked.ok) {
|
|
756
|
+
return {
|
|
757
|
+
ok: false,
|
|
758
|
+
error: asked.error,
|
|
759
|
+
path: dir,
|
|
760
|
+
approval: { outcome: asked.outcome || 'unavailable', hasService: Boolean(service && typeof service.request === 'function'), hasAgent: Boolean(exec?.agent), hasCallId: Boolean(exec?.callId) },
|
|
761
|
+
hint: 'clean with force:true deletes files in a directory that does not look like a case; approve it explicitly',
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
const what = Array.isArray(args.what) && args.what.length ? args.what.map(String) : ['logs', 'timeDirs']
|
|
766
|
+
const keep = new Set((Array.isArray(args.keepTimes) ? args.keepTimes : []).map(String))
|
|
767
|
+
let entries = []
|
|
768
|
+
try { entries = readdirSync(dir, { withFileTypes: true }) } catch {}
|
|
769
|
+
const candidates = []
|
|
770
|
+
for (const w of what) {
|
|
771
|
+
if (w === 'logs') {
|
|
772
|
+
for (const e of entries) {
|
|
773
|
+
if (!e.isFile()) continue
|
|
774
|
+
if (!(/^log([._]|$)/i.test(e.name) || /\.log$/i.test(e.name))) continue
|
|
775
|
+
candidates.push({ kind: 'log', rel: e.name })
|
|
776
|
+
}
|
|
777
|
+
} else if (w === 'timeDirs') {
|
|
778
|
+
for (const e of entries) {
|
|
779
|
+
if (!e.isDirectory() || !/^\d+([.eE][-+]?\d+)?$/.test(e.name)) continue
|
|
780
|
+
if (e.name === '0' || keep.has(e.name)) continue
|
|
781
|
+
candidates.push({ kind: 'timeDir', rel: e.name })
|
|
782
|
+
}
|
|
783
|
+
} else if (w === 'processorDirs') {
|
|
784
|
+
for (const e of entries) {
|
|
785
|
+
if (e.isDirectory() && /^processor\d+$/.test(e.name)) candidates.push({ kind: 'processorDir', rel: e.name })
|
|
786
|
+
}
|
|
787
|
+
} else if (w === 'postProcessing') {
|
|
788
|
+
if (existsSync(join(dir, 'postProcessing'))) candidates.push({ kind: 'postProcessing', rel: 'postProcessing' })
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
let totalBytes = 0
|
|
792
|
+
for (const c of candidates) {
|
|
793
|
+
const full = join(dir, c.rel)
|
|
794
|
+
try {
|
|
795
|
+
const st = statSync(full)
|
|
796
|
+
c.bytes = st.isDirectory() ? dirSize(full) : st.size
|
|
797
|
+
totalBytes += c.bytes
|
|
798
|
+
} catch { c.bytes = null }
|
|
799
|
+
}
|
|
800
|
+
const dryRun = args.dryRun !== false
|
|
801
|
+
if (!dryRun) {
|
|
802
|
+
for (const c of candidates) {
|
|
803
|
+
try { rmSync(join(dir, c.rel), { recursive: true, force: true }) } catch (e) { c.error = String((e && e.message) || e) }
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
return {
|
|
807
|
+
ok: true,
|
|
808
|
+
dryRun,
|
|
809
|
+
casePath: dir,
|
|
810
|
+
what,
|
|
811
|
+
count: candidates.length,
|
|
812
|
+
totalBytes,
|
|
813
|
+
totalHuman: `${(totalBytes / 1024 / 1024).toFixed(1)} MB`,
|
|
814
|
+
removed: dryRun ? null : candidates.map((c) => c.rel),
|
|
815
|
+
candidates,
|
|
816
|
+
hint: dryRun ? 'dry run: nothing was deleted; call again with dryRun:false to remove the listed paths' : null,
|
|
817
|
+
}
|
|
818
|
+
},
|
|
819
|
+
},
|
|
820
|
+
// --- tool: scaffold an incompressible laminar case from scratch ---
|
|
821
|
+
{
|
|
822
|
+
name: 'openfoam_case_scaffold',
|
|
823
|
+
description: 'Write the dictionaries a fresh case needs (controlDict, fvSchemes, fvSolution, constant/*, 0/U, 0/p) for incompressible LAMINAR flow, using the case own patches for the boundary conditions. Distribution-aware: org uses application foamRun + solver incompressibleFluid with momentumTransport/physicalProperties; com uses application simpleFoam with turbulenceProperties/transportProperties. With no mesh yet it falls back to the inlet/outlet/walls set that mesh_plan creates; it then runs the doctor and returns its findings. It writes dictionaries and 0/ fields but NO geometry (no blockMeshDict) - build the mesh with openfoam_mesh_plan or your own blockMeshDict. For a multi-region conjugate-heat-transfer case use family="cht" on a case whose regions already exist (blockMesh -> createZones -> splitMeshRegions): it writes per-region dictionaries, regionSolvers/regionProperties by distribution, coupled boundary conditions on the <region>_to_<other> interface patches and a root fvSolution. Use clone_tutorial for turbulent or compressible cases.',
|
|
824
|
+
parameters: {
|
|
825
|
+
type: 'object',
|
|
826
|
+
properties: {
|
|
827
|
+
casePath: { type: 'string', description: 'Case directory; created when it does not exist.' },
|
|
828
|
+
distribution: { type: 'string', description: 'org | com (default: defaultDistribution or org).' },
|
|
829
|
+
algorithm: { type: 'string', description: 'SIMPLE (steady, default) or PIMPLE (transient).' },
|
|
830
|
+
turbulence: { type: 'string', description: 'Only laminar in this version.' },
|
|
831
|
+
family: { type: 'string', description: 'incompressible (default) | compressible (rho-thermo, family-aware) | cht (multi-region conjugate heat transfer, requires region meshes).' },
|
|
832
|
+
regions: { type: 'array', description: 'For family=cht: [{name, kind:"fluid"|"solid"}] for the existing region meshes; inferred from names when omitted.', items: { type: 'object' } },
|
|
833
|
+
Uinlet: { type: 'number', description: 'For family=cht: inlet velocity magnitude (m/s), default 5.' },
|
|
834
|
+
Tinlet: { type: 'number', description: 'For family=cht: gas inlet temperature (K), default 500.' },
|
|
835
|
+
Tsolid: { type: 'number', description: 'For family=cht: initial solid temperature (K), default 300.' },
|
|
836
|
+
solid: { type: 'object', description: 'For family=cht: {rho, Cv, kappa} of the solid material; small Cv heats fast.', additionalProperties: true },
|
|
837
|
+
U: { type: 'array', items: { type: 'number' }, description: 'Inlet velocity vector (default (1 0 0)).' },
|
|
838
|
+
p: { type: 'number', description: 'Outlet pressure (default 0).' },
|
|
839
|
+
nu: { type: 'number', description: 'Kinematic viscosity (default 1e-5).' },
|
|
840
|
+
endTime: { type: 'number' },
|
|
841
|
+
deltaT: { type: 'number' },
|
|
842
|
+
writeInterval: { type: 'number' },
|
|
843
|
+
patches: { type: 'array', description: 'Patch names (or {name,type} objects) when no polyMesh exists yet.' },
|
|
844
|
+
force: { type: 'boolean', description: 'Overwrite existing dictionaries.' },
|
|
845
|
+
},
|
|
846
|
+
required: ['casePath'],
|
|
847
|
+
},
|
|
848
|
+
output: { schema: { type: 'object' }, render: (_a, v) => textOut(v) },
|
|
849
|
+
timeoutMs: 120000,
|
|
850
|
+
isConcurrencySafe: () => false,
|
|
851
|
+
execute: async (args) => {
|
|
852
|
+
const requested = String(args.casePath || '').trim()
|
|
853
|
+
if (!requested) return { ok: false, error: 'casePath is required' }
|
|
854
|
+
const dir = resolveCase(cfg, requested)
|
|
855
|
+
if (!dir) return { ok: false, error: 'casePath is required' }
|
|
856
|
+
const family = String(args.family || 'incompressible').toLowerCase()
|
|
857
|
+
if (family === 'compressible') {
|
|
858
|
+
const capsC = await probeCaps(bashrcFor(cfg, args.distribution), args.distribution || cfg.defaultDistribution)
|
|
859
|
+
let patches = Array.isArray(args.patches) && args.patches.length
|
|
860
|
+
? args.patches.map((p) => (p && typeof p === 'object' ? { name: String(p.name || ''), type: String(p.type || 'patch') } : { name: String(p), type: 'patch' }))
|
|
861
|
+
: parseBoundaryPatches(readText(join(dir, 'constant', 'polyMesh', 'boundary')) || '').map((p) => ({ name: p.name, type: p.type }))
|
|
862
|
+
if (!patches.length) patches = [{ name: 'inlet', type: 'patch' }, { name: 'outlet', type: 'patch' }, { name: 'walls', type: 'wall' }]
|
|
863
|
+
const planC = scaffoldCompressible({
|
|
864
|
+
caps: capsC,
|
|
865
|
+
patches,
|
|
866
|
+
Uinlet: Number(args.Uinlet) > 0 ? Number(args.Uinlet) : 10,
|
|
867
|
+
Tinlet: Number(args.Tinlet) > 0 ? Number(args.Tinlet) : 300,
|
|
868
|
+
pInitial: Number(args.p) > 0 ? Number(args.p) : 1e5,
|
|
869
|
+
endTime: args.endTime,
|
|
870
|
+
deltaT: args.deltaT,
|
|
871
|
+
writeInterval: args.writeInterval,
|
|
872
|
+
})
|
|
873
|
+
const createdC = []
|
|
874
|
+
const skippedC = []
|
|
875
|
+
for (const [rel, body] of Object.entries(planC.files)) {
|
|
876
|
+
const file = join(dir, rel)
|
|
877
|
+
if (existsSync(file) && !args.force) { skippedC.push(rel); continue }
|
|
878
|
+
mkdirSync(join(file, '..'), { recursive: true })
|
|
879
|
+
writeFileSync(file, body)
|
|
880
|
+
createdC.push(rel)
|
|
881
|
+
}
|
|
882
|
+
writeFileSync(join(dir, 'case-manifest.json'), JSON.stringify({ family: 'compressible', distribution: capsC.family, createdAt: new Date().toISOString() }, null, 2) + '\n')
|
|
883
|
+
createdC.push('case-manifest.json')
|
|
884
|
+
const findingsC = checkCaseEngine(dir)
|
|
885
|
+
return {
|
|
886
|
+
ok: true,
|
|
887
|
+
casePath: dir,
|
|
888
|
+
family: 'compressible',
|
|
889
|
+
distribution: capsC.family,
|
|
890
|
+
caps: { summary: capsSummary(capsC), support: capsC.support, modular: capsC.modular },
|
|
891
|
+
application: planC.files['system/controlDict'].match(/application\s+(\w+);/)[1],
|
|
892
|
+
created: createdC,
|
|
893
|
+
skipped: skippedC,
|
|
894
|
+
warnings: planC.warnings,
|
|
895
|
+
notes: planC.notes,
|
|
896
|
+
findings: findingsC.map((f) => ({ rule: f.rule, severity: f.severity, title: f.title })),
|
|
897
|
+
next: ['openfoam_check', 'openfoam_run_solver_async', 'openfoam_solve_verify', 'openfoam_field_stats'],
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
if (family === 'cht') {
|
|
901
|
+
const regionNames = caseRegions(dir)
|
|
902
|
+
if (!regionNames.length) {
|
|
903
|
+
return {
|
|
904
|
+
ok: false,
|
|
905
|
+
error: 'family=cht needs region meshes: no constant/<region>/polyMesh in this case',
|
|
906
|
+
hint: 'build one mesh, create a cell zone for the solid, then split: blockMesh -> createZones -> splitMeshRegions -cellZones all -defaultRegion fluid',
|
|
907
|
+
regions: regionNames,
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
const requested = Array.isArray(args.regions) ? args.regions : []
|
|
911
|
+
const inferred = requested.length
|
|
912
|
+
? requested
|
|
913
|
+
: regionNames.map((name) => ({ name, kind: /solid|body|metal|wall|rod|sphere/i.test(name) ? 'solid' : 'fluid' }))
|
|
914
|
+
const kinds = inferred.filter((r) => regionNames.includes(r.name))
|
|
915
|
+
if (!kinds.some((r) => r.kind === 'fluid') || !kinds.some((r) => r.kind === 'solid')) {
|
|
916
|
+
return {
|
|
917
|
+
ok: false,
|
|
918
|
+
error: 'family=cht needs at least one fluid and one solid region',
|
|
919
|
+
regions: regionNames,
|
|
920
|
+
hint: 'pass regions: [{name:"fluid", kind:"fluid"}, {name:"solid", kind:"solid"}]',
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
const withPatches = kinds.map((r) => ({
|
|
924
|
+
...r,
|
|
925
|
+
patches: parseBoundaryPatches(readText(join(dir, 'constant', r.name, 'polyMesh', 'boundary')) || ''),
|
|
926
|
+
}))
|
|
927
|
+
const capsCht = await probeCaps(bashrcFor(cfg, args.distribution), args.distribution || cfg.defaultDistribution)
|
|
928
|
+
const Uinlet = Number(args.Uinlet) > 0 ? Number(args.Uinlet) : 5
|
|
929
|
+
const plan = scaffoldCht({
|
|
930
|
+
caps: capsCht,
|
|
931
|
+
regions: withPatches,
|
|
932
|
+
Uinlet,
|
|
933
|
+
Tinlet: Number(args.Tinlet) > 0 ? Number(args.Tinlet) : 500,
|
|
934
|
+
Tsolid: Number(args.Tsolid) > 0 ? Number(args.Tsolid) : 300,
|
|
935
|
+
pInitial: Number(args.p) > 0 ? Number(args.p) : 1e5,
|
|
936
|
+
solid: args.solid && typeof args.solid === 'object' ? args.solid : undefined,
|
|
937
|
+
endTime: args.endTime,
|
|
938
|
+
deltaT: args.deltaT,
|
|
939
|
+
writeInterval: args.writeInterval,
|
|
940
|
+
})
|
|
941
|
+
if (!plan.ok) return plan
|
|
942
|
+
const createdCht = []
|
|
943
|
+
const skippedCht = []
|
|
944
|
+
for (const [rel, body] of Object.entries(plan.files)) {
|
|
945
|
+
const file = join(dir, rel)
|
|
946
|
+
if (existsSync(file) && !args.force) { skippedCht.push(rel); continue }
|
|
947
|
+
mkdirSync(join(file, '..'), { recursive: true })
|
|
948
|
+
writeFileSync(file, body)
|
|
949
|
+
createdCht.push(rel)
|
|
950
|
+
}
|
|
951
|
+
const manifest = {
|
|
952
|
+
family: 'cht',
|
|
953
|
+
distribution: capsCht.family,
|
|
954
|
+
regions: plan.regions,
|
|
955
|
+
createdAt: new Date().toISOString(),
|
|
956
|
+
}
|
|
957
|
+
writeFileSync(join(dir, 'case-manifest.json'), JSON.stringify(manifest, null, 2) + '\n')
|
|
958
|
+
createdCht.push('case-manifest.json')
|
|
959
|
+
const findingsCht = checkCaseEngine(dir, { regions: regionNames })
|
|
960
|
+
return {
|
|
961
|
+
ok: true,
|
|
962
|
+
casePath: dir,
|
|
963
|
+
family: 'cht',
|
|
964
|
+
distribution: capsCht.family,
|
|
965
|
+
caps: { summary: capsSummary(capsCht), support: capsCht.support, modular: capsCht.modular },
|
|
966
|
+
regions: plan.regions,
|
|
967
|
+
created: createdCht,
|
|
968
|
+
skipped: skippedCht,
|
|
969
|
+
warnings: plan.warnings,
|
|
970
|
+
notes: plan.notes,
|
|
971
|
+
findings: findingsCht.map((f) => ({ rule: f.rule, severity: f.severity, title: f.title })),
|
|
972
|
+
next: [
|
|
973
|
+
'openfoam_check, then openfoam_run_solver_async (org: foamMultiRun; com: chtMultiRegionFoam)',
|
|
974
|
+
'openfoam_field_stats with region="<solid>" to watch the solid heat up',
|
|
975
|
+
],
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
if (family !== 'incompressible') {
|
|
979
|
+
return {
|
|
980
|
+
ok: false,
|
|
981
|
+
error: `this version scaffolds incompressible laminar or CHT cases (family="${args.family}")`,
|
|
982
|
+
hint: 'for compressible flow copy the nearest tutorial: openfoam_find_tutorial + openfoam_clone_tutorial (org: fluid/aerofoilNACA0012, com: compressible/rhoPimpleFoam/...)',
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
if (args.turbulence && !/^laminar$/i.test(String(args.turbulence))) {
|
|
986
|
+
return {
|
|
987
|
+
ok: false,
|
|
988
|
+
error: `v1 scaffolds laminar incompressible cases only (got turbulence="${args.turbulence}")`,
|
|
989
|
+
hint: 'use openfoam_find_tutorial + openfoam_clone_tutorial for turbulent, compressible or CHT cases (kOmegaSST, compressibleVoF, multiRegion)',
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
const distribution = String(args.distribution || cfg.defaultDistribution || 'org')
|
|
993
|
+
const kind = distributionKind(distribution)
|
|
994
|
+
|
|
995
|
+
let patches = []
|
|
996
|
+
const boundary = readText(join(dir, 'constant', 'polyMesh', 'boundary'))
|
|
997
|
+
if (boundary) patches = parseBoundaryPatches(boundary).map((p) => ({ name: p.name, type: p.type }))
|
|
998
|
+
if (!patches.length && Array.isArray(args.patches) && args.patches.length) {
|
|
999
|
+
patches = args.patches.map((p) => (p && typeof p === 'object'
|
|
1000
|
+
? { name: String(p.name || ''), type: String(p.type || 'patch') }
|
|
1001
|
+
: { name: String(p), type: 'patch' }))
|
|
1002
|
+
}
|
|
1003
|
+
if (!patches.length) {
|
|
1004
|
+
patches = [
|
|
1005
|
+
{ name: 'inlet', type: 'patch' },
|
|
1006
|
+
{ name: 'outlet', type: 'patch' },
|
|
1007
|
+
{ name: 'walls', type: 'wall' },
|
|
1008
|
+
]
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
const caps = await probeCaps(bashrcFor(cfg, distribution), distribution)
|
|
1012
|
+
const plan = scaffoldFiles({
|
|
1013
|
+
distribution,
|
|
1014
|
+
caps,
|
|
1015
|
+
patches,
|
|
1016
|
+
algorithm: String(args.algorithm || 'SIMPLE'),
|
|
1017
|
+
U: args.U,
|
|
1018
|
+
p: args.p,
|
|
1019
|
+
nu: Number(args.nu) || 1e-5,
|
|
1020
|
+
endTime: args.endTime,
|
|
1021
|
+
deltaT: args.deltaT,
|
|
1022
|
+
writeInterval: args.writeInterval,
|
|
1023
|
+
})
|
|
1024
|
+
|
|
1025
|
+
mkdirSync(dir, { recursive: true })
|
|
1026
|
+
const created = []
|
|
1027
|
+
const skipped = []
|
|
1028
|
+
for (const [rel, body] of Object.entries(plan.files)) {
|
|
1029
|
+
const file = join(dir, rel)
|
|
1030
|
+
if (existsSync(file) && !args.force) { skipped.push(rel); continue }
|
|
1031
|
+
mkdirSync(join(file, '..'), { recursive: true })
|
|
1032
|
+
writeFileSync(file, body)
|
|
1033
|
+
created.push(rel)
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
const foam = ensureFoamFile(dir)
|
|
1037
|
+
// case-manifest.json lets mesh tools read the setup instead of guessing it
|
|
1038
|
+
const manifest = {
|
|
1039
|
+
schema: 'openfoam-workbench/case-manifest@1',
|
|
1040
|
+
application: plan.application,
|
|
1041
|
+
algorithm: plan.transient ? 'PIMPLE' : 'SIMPLE',
|
|
1042
|
+
distribution: kind,
|
|
1043
|
+
compressible: false,
|
|
1044
|
+
phases: 1,
|
|
1045
|
+
turbulence: 'laminar',
|
|
1046
|
+
patches: plan.patchRoles.map((r) => ({ name: r.name, type: r.type, role: r.role })),
|
|
1047
|
+
createdAt: new Date().toISOString(),
|
|
1048
|
+
}
|
|
1049
|
+
const manifestPath = join(dir, 'case-manifest.json')
|
|
1050
|
+
if (!existsSync(manifestPath) || args.force) {
|
|
1051
|
+
writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
|
|
1052
|
+
created.push('case-manifest.json')
|
|
1053
|
+
}
|
|
1054
|
+
const findings = checkCaseEngine(dir)
|
|
1055
|
+
const bySeverity = findings.reduce((acc, f) => { acc[f.severity] = (acc[f.severity] || 0) + 1; return acc }, {})
|
|
1056
|
+
return {
|
|
1057
|
+
ok: true,
|
|
1058
|
+
casePath: dir,
|
|
1059
|
+
distribution: kind,
|
|
1060
|
+
caps: { summary: capsSummary(caps), support: caps.support, family: caps.family, modular: caps.modular },
|
|
1061
|
+
...(caps.support !== 'full' ? { advisory: `this OpenFOAM release is ${caps.support === 'unknown' ? 'not tested' : 'partially tested'}: review the generated ${caps.family} dictionaries before a production run` } : {}),
|
|
1062
|
+
application: plan.application,
|
|
1063
|
+
algorithm: plan.transient ? 'PIMPLE' : 'SIMPLE',
|
|
1064
|
+
patches: plan.patchRoles.map((r) => ({ name: r.name, type: r.type, role: r.role })),
|
|
1065
|
+
created,
|
|
1066
|
+
skipped,
|
|
1067
|
+
foamFile: foam.ok ? foam.name : null,
|
|
1068
|
+
manifest: 'case-manifest.json',
|
|
1069
|
+
findings: findings.map((f) => ({ rule: f.rule, severity: f.severity, title: f.title })),
|
|
1070
|
+
findingCounts: bySeverity,
|
|
1071
|
+
warnings: plan.warnings,
|
|
1072
|
+
notes: plan.notes,
|
|
1073
|
+
next: [
|
|
1074
|
+
'run blockMesh (or snappyHexMesh) if the mesh does not exist yet',
|
|
1075
|
+
'set the real inlet velocity in 0/U and the outlet pressure level in 0/p',
|
|
1076
|
+
'openfoam_check, then openfoam_run_solver_async, then openfoam_solve_verify',
|
|
1077
|
+
],
|
|
1078
|
+
}
|
|
1079
|
+
},
|
|
1080
|
+
},
|
|
1081
|
+
]
|
|
1082
|
+
}
|