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

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 +692 -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
package/client.js ADDED
@@ -0,0 +1,48 @@
1
+ // Browser half of the OpenFOAM Workbench.
2
+ //
3
+ // The Host half registers the tools; this half is pure presentation: every tool
4
+ // row whose wire name starts with `openfoam_` gets an orange accent bar, so the
5
+ // CFD tools are distinguishable from bash/read/edit calls at a glance.
6
+ //
7
+ // The row contract comes from @deepseek-ai/dsh-client-ui-tool: the root of every
8
+ // atomic tool row carries data-tool="<wire name>" and data-state. The shipped UI
9
+ // already styles by that attribute prefix (`[data-tool^=cordis_]`), so no slot
10
+ // registration and no per-tool view is needed here.
11
+ //
12
+ // Styles are package-owned: the tag carries data-plugin-css and is removed with
13
+ // the Client run through ctx.effect's cleanup.
14
+ window.__ModuleLoader__.load({
15
+ id: '@yakovlev-i-a/dsh-openfoam-workbench',
16
+ factory() {
17
+ const TAG = '@yakovlev-i-a/dsh-openfoam-workbench/tool-accent.css'
18
+ // Light/dark come from the Host palette attribute on <body>. The row shows
19
+ // `Tool call` as the title and `openfoam_x · <argument summary>` in the
20
+ // summary element (css-module local name `_summary`; its hash prefix changes
21
+ // between builds). Blue marks the call itself; the ring and the orange title
22
+ // are gone by request.
23
+ const CSS = [
24
+ '/* OpenFOAM Workbench: blue call summary on every openfoam_* tool row */',
25
+ '[data-tool^="openfoam_"] [class*="_summary"] { color: #3b518c; }',
26
+ 'body[data-ds-dark-theme] [data-tool^="openfoam_"] [class*="_summary"] { color: #9db4e0; }',
27
+ ].join('\n')
28
+
29
+ return {
30
+ apply(ctx) {
31
+ ctx.effect(() => {
32
+ if (typeof document === 'undefined') return () => {}
33
+ const selector = 'style[data-plugin-css=' + JSON.stringify(TAG) + ']'
34
+ let tag = document.querySelector(selector)
35
+ if (!tag) {
36
+ tag = document.createElement('style')
37
+ tag.setAttribute('data-plugin-css', TAG)
38
+ tag.textContent = CSS
39
+ document.head.appendChild(tag)
40
+ }
41
+ return () => {
42
+ if (tag && typeof tag.remove === 'function') tag.remove()
43
+ }
44
+ }, 'openfoam tool accent')
45
+ },
46
+ }
47
+ },
48
+ })
@@ -0,0 +1,18 @@
1
+ # dsh-openfoam-workbench bundle: mount the OpenFOAM Workbench plugin.
2
+ #
3
+ # The configuration is deliberately machine-neutral: OpenFOAM installs are
4
+ # discovered at startup (directories under /opt, /usr/lib/openfoam, /usr/local
5
+ # and ~/OpenFOAM that contain etc/bashrc), ParaView is looked up in /opt and on
6
+ # PATH, and cases resolve from the workspace working directory.
7
+ #
8
+ # Optional overrides (put them in your profile patch, keyed by the row id
9
+ # `openfoam-workbench`, so this bundle stays untouched):
10
+ # foamRoots: { org: /opt/openfoam14, com: /usr/lib/openfoam/openfoam2606 }
11
+ # defaultDistribution: org
12
+ # paraviewPython: /opt/paraview/bin/pvpython
13
+ # caseRoots: [/path/to/cases]
14
+ # language: ru # '' follows the OS locale; 'ru'/'en'/... forces one
15
+ - insert:
16
+ - id: openfoam-workbench
17
+ name: '@yakovlev-i-a/dsh-openfoam-workbench'
18
+ config: {}
package/icon.png ADDED
Binary file
@@ -0,0 +1,42 @@
1
+ import { join } from 'node:path'
2
+ import { readText } from './runtime.js'
3
+
4
+ export function readMakeFiles(modulePath) {
5
+ const text = readText(join(modulePath, 'Make/files')) || ''
6
+ const lines = text.split('\n').map((s) => s.trim()).filter(Boolean)
7
+ const isLib = /^\s*LIB\s*=/m.test(text)
8
+ const mainSource = lines.find((l) => /\.C$/.test(l) && !/^\s*(LIB|EXE)\s*=/.test(l)) || null
9
+ const targetMatch = text.match(/^\s*(EXE|LIB)\s*=\s*(\S+)/m)
10
+ return { text, isLib, mainSource, target: targetMatch ? targetMatch[2] : null }
11
+ }
12
+
13
+ export function firstError(log) {
14
+ const lines = String(log || '').split('\n')
15
+ for (let i = 0; i < lines.length; i++) {
16
+ if (/(^|\s)(error|Error):|\bundefined reference\b|make: \*\*\*|Error \d+/.test(lines[i])) {
17
+ return lines.slice(Math.max(0, i - 2), i + 2).join('\n')
18
+ }
19
+ }
20
+ return null
21
+ }
22
+
23
+ export function inspectSolverModule(modulePath) {
24
+ const make = readMakeFiles(modulePath)
25
+ const main = make.mainSource ? join(modulePath, make.mainSource) : null
26
+ const code = main ? (readText(main) || '') : ''
27
+ const header = readText(join(modulePath, 'createFields.H')) || ''
28
+ const fields = []
29
+ const fre = /(volScalarField|volVectorField|volTensorField|volSymmTensorField|surfaceScalarField|surfaceVectorField)\s+(\w+)/g
30
+ let m
31
+ while ((m = fre.exec(header)) && fields.length < 60) fields.push({ name: m[2], type: m[1] })
32
+ const includes = []
33
+ const ire = /#include\s+"([^"]+)"/g
34
+ while ((m = ire.exec(code)) && includes.length < 60) includes.push(m[1])
35
+ const loop = ['UEqn', 'pEqn', 'rhoU', 'rhoE', 'simpleControl', 'pimpleControl', 'pisoControl', 'CorrectPhi', 'fvModels', 'fvConstraints', 'thermophysicalTransport'].filter((k) => code.includes(k))
36
+ const risks = []
37
+ if (!make.target) risks.push('Make/files has no EXE/LIB target')
38
+ if (!make.mainSource) risks.push('Make/files has no .C source')
39
+ if (make.target && make.target.includes('$(FOAM_APPBIN)')) risks.push('EXE points at the system install; use $(FOAM_USER_APPBIN)')
40
+ if (code && !/simpleControl|pimpleControl|pisoControl/.test(code)) risks.push('no simple/pimple/piso control header detected')
41
+ return { make, fields, includes, loop, risks }
42
+ }
package/lib/caselib.js ADDED
@@ -0,0 +1,212 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+ import { basename, extname, isAbsolute, join } from 'node:path'
3
+ import { readText, resolveCase, resolveCaseInfo, resolveSource, caseLookupHint } from './runtime.js'
4
+ import { classifySolver } from './knowledge.js'
5
+ import { caseRegions, regionFiles, regionGroups, regionSolvers, zeroDirName, zeroDirOf } from './of-case.js'
6
+ import { parseBoundaryPatches } from './of-engine.js'
7
+
8
+ export function algoExtractContract(cfg, args) {
9
+ const source_file = String(args.source_file || '')
10
+ let f = ''
11
+ if (isAbsolute(source_file)) f = source_file
12
+ else {
13
+ const inCase = resolveCase(cfg, source_file)
14
+ if (existsSync(inCase)) f = inCase
15
+ else {
16
+ const src = resolveSource(cfg, source_file)
17
+ if (src.ok) f = src.path
18
+ }
19
+ }
20
+ if (!f || !existsSync(f)) return { ok: false, error: 'file not found: ' + source_file }
21
+ const ext = extname(source_file).toLowerCase()
22
+ const raw = readText(f) || ''
23
+ const contract = {
24
+ algorithm: args.algorithm_name || basename(source_file, ext),
25
+ source_file,
26
+ source_kind: ext,
27
+ inputs: [],
28
+ outputs: [],
29
+ equations: [],
30
+ governing_type: null,
31
+ assumes: { compressible: null, phases: null, turbulence: null, dimensions: null },
32
+ raw_notes: [],
33
+ }
34
+ if (ext === '.h' || ext === '.c' || ext === '.cpp' || ext === '.cxx') {
35
+ const inherit = raw.match(/class\s+(\w+)\s*:\s*public\s+([\w:]+)/)
36
+ if (inherit) {
37
+ contract.raw_notes.push(`class ${inherit[1]} : public ${inherit[2]}`)
38
+ const base = inherit[2].toLowerCase()
39
+ if (/dragmodel/.test(base)) { contract.governing_type = 'two-phase drag (Euler-Euler)'; contract.assumes.phases = 2 }
40
+ else if (/turbulencemodel|rasmodel|lesmodel/.test(base)) contract.governing_type = 'turbulence closure'
41
+ else if (/phasemodel/.test(base)) { contract.governing_type = 'phase model'; contract.assumes.phases = 2 }
42
+ else if (/fvpatchfield/.test(base)) contract.governing_type = 'boundary condition'
43
+ else if (/fvoption/.test(base)) contract.governing_type = 'fvOption / source term'
44
+ }
45
+ const fnRe = /(?:virtual\s+)?(\w+(?:::\w+)*)\s+(\w+)\s*\(([^)]*)\)\s*(?:const)?\s*[{;]/g
46
+ let mm
47
+ let cnt = 0
48
+ while ((mm = fnRe.exec(raw)) !== null && cnt < 12) {
49
+ const [, ret, name, params] = mm
50
+ if (/^(operator|if|for|while|switch|return)$/.test(name)) continue
51
+ if (/^[A-Z]\w*$/.test(name) && inherit && name === inherit[1]) continue
52
+ contract.outputs.push({ name, return_type: ret, params: params.trim().slice(0, 200) })
53
+ cnt++
54
+ }
55
+ for (const line of raw.split(/\r?\n/)) {
56
+ if (/\b(Eq\.?|Equation)\s*\(?\d/.test(line) || /^\s*\/\/\s*[A-Za-z_]+\s*=\s*/.test(line)) {
57
+ const s = line.replace(/^\s*\/\/\s*/, '').trim()
58
+ if (s && s.length < 200) contract.equations.push(s)
59
+ if (contract.equations.length >= 8) break
60
+ }
61
+ }
62
+ } else if (ext === '.pdf') {
63
+ contract.raw_notes.push('the source is a PDF — read it with openfoam_read_paper, then fill inputs/outputs/equations by hand. This tool is a heuristic only.')
64
+ } else if (ext === '.py') {
65
+ const fnRe = /def\s+(\w+)\s*\(([^)]*)\):\s*(?:\n\s*"""([^"]+)""")?/g
66
+ let mm
67
+ while ((mm = fnRe.exec(raw)) !== null) {
68
+ contract.outputs.push({ name: mm[1], params: mm[2], doc: (mm[3] || '').trim().slice(0, 200) })
69
+ if (contract.outputs.length >= 10) break
70
+ }
71
+ }
72
+ if (/compressible/i.test(raw)) contract.assumes.compressible = true
73
+ if (/incompressible/i.test(raw)) contract.assumes.compressible = false
74
+ if (/twoPhase|two-?phase|alpha\.water|alpha\.air/i.test(raw)) contract.assumes.phases = 2
75
+ if (/singlePhase|single-?phase/i.test(raw)) contract.assumes.phases = 1
76
+ for (const t of ['kEpsilon', 'kOmegaSST', 'SpalartAllmaras', 'LES', 'RAS', 'laminar']) {
77
+ if (new RegExp(`\\b${t}\\b`).test(raw)) { contract.assumes.turbulence = t; break }
78
+ }
79
+ contract.note = '⚠ Heuristic extraction: outputs from function signatures, equations from comments. Verify by hand before treating it as a contract.'
80
+ return { ok: true, ...contract }
81
+ }
82
+
83
+ // Full OpenFOAM.org 14 solver map: name -> [governing, compressible, phases]
84
+
85
+ export function caseProbeFacts(cfg, args) {
86
+ const requested = (args && (args.case_path || args.casePath)) || ''
87
+ const cd = resolveCase(cfg, requested)
88
+ if (!cd || !existsSync(cd)) {
89
+ return { ok: false, error: 'case not found: ' + cd + caseLookupHint(cfg), hint: 'pass case_path (alias: casePath) — a directory inside caseRoots or an absolute path' }
90
+ }
91
+ const resolved = resolveCaseInfo(cfg, requested)
92
+ const facts = { case_path: requested, resolvedFrom: resolved.resolvedFrom, solver: null, governing: null, compressible: null, phases: null, turbulence: null, dimensions_xyz: null, patches: [], fields_in_0: [], extras: {} }
93
+ const cdText = readText(join(cd, 'system/controlDict'))
94
+ if (cdText) {
95
+ const m = cdText.match(/^\s*(?:application|solver)\s+(\w+)\s*;/m)
96
+ if (m) {
97
+ facts.solver = m[1]
98
+ const cls = classifySolver(m[1])
99
+ facts.governing = cls.governing
100
+ facts.compressible = cls.compressible
101
+ facts.phases = cls.phases
102
+ }
103
+ const lm = cdText.match(/libs\s*\(([^)]+)\)/)
104
+ if (lm) facts.extras.libs = lm[1].trim()
105
+ }
106
+ for (const tf of ['constant/momentumTransport', 'constant/turbulenceProperties']) {
107
+ const tp = readText(join(cd, tf))
108
+ if (!tp) continue
109
+ const mm = tp.match(/RAS\s*\{[^}]*model\s+(\w+)/) || tp.match(/LES\s*\{[^}]*model\s+(\w+)/) || tp.match(/(?:RASModel|LESModel|model)\s+(\w+)/)
110
+ if (mm) { facts.turbulence = mm[1]; break }
111
+ if (/simulationType\s+laminar/.test(tp)) { facts.turbulence = 'laminar'; break }
112
+ }
113
+ const bm = readText(join(cd, 'system/blockMeshDict'))
114
+ if (bm) {
115
+ const verts = [...bm.matchAll(/\(([-\d.eE+]+)\s+([-\d.eE+]+)\s+([-\d.eE+]+)\)/g)].slice(0, 8).map((m) => m.slice(1, 4).map(Number))
116
+ if (verts.length >= 8) {
117
+ const xs = verts.map((v) => v[0]), ys = verts.map((v) => v[1]), zs = verts.map((v) => v[2])
118
+ facts.dimensions_xyz = [Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys), Math.max(...zs) - Math.min(...zs)].map((x) => +x.toFixed(6))
119
+ }
120
+ }
121
+ try {
122
+ const zeroDir = zeroDirOf(cd)
123
+ facts.fields_in_0 = zeroDir ? readdirSync(zeroDir).filter((n) => !n.startsWith('.')) : []
124
+ if (zeroDir) facts.fields_from = zeroDirName(cd)
125
+ // patch names come from the mesh, not from a field file: a case whose
126
+ // initial fields live in 0_orig/ still has a boundary file.
127
+ const bndText = readText(join(cd, 'constant', 'polyMesh', 'boundary'))
128
+ if (bndText) facts.patches = parseBoundaryPatches(bndText).slice(0, 60).map((p) => p.name)
129
+ for (const fn of facts.fields_in_0.slice(0, 4)) {
130
+ const txt = zeroDir ? readText(join(zeroDir, fn)) : null
131
+ if (!txt) continue
132
+ const bf = txt.match(/boundaryField\s*\{([\s\S]*?)\n\}/)
133
+ if (bf) {
134
+ const patches = [...bf[1].matchAll(/^\s*(\w+)\s*\n?\s*\{/gm)].map((m) => m[1])
135
+ if (patches.length > facts.patches.length) facts.patches = patches
136
+ }
137
+ }
138
+ } catch {}
139
+ const regions = caseRegions(cd)
140
+ if (regions.length) {
141
+ const solvers = regionSolvers(cd)
142
+ facts.multiRegion = true
143
+ facts.regions = regions
144
+ facts.region_solvers = solvers
145
+ facts.region_groups = regionGroups(cd)
146
+ facts.region_facts = regions.map((r) => {
147
+ const f = regionFiles(cd, r)
148
+ const bnd = readText(join(cd, 'constant', r, 'polyMesh', 'boundary'))
149
+ const patches = bnd ? parseBoundaryPatches(bnd).slice(0, 60).map((p) => p.name) : []
150
+ return { region: r, solver: solvers[r] || null, fields: f.fields, patches }
151
+ })
152
+ facts.fields_in_0 = [...new Set(facts.region_facts.flatMap((d) => d.fields))].sort()
153
+ facts.patches = []
154
+ facts.region_governing = regions.map((r) => ({ region: r, solver: solvers[r] || null, ...classifySolver(solvers[r] || '') }))
155
+ if (facts.region_governing.some((g) => g.compressible === true)) facts.compressible = true
156
+ }
157
+ const tp = readText(join(cd, 'constant/transportProperties')) || readText(join(cd, 'constant/physicalProperties'))
158
+ if (tp) {
159
+ const ex = {}
160
+ for (const k of ['nu', 'rho', 'mu', 'sigma']) {
161
+ const mm = tp.match(new RegExp(`\\b${k}\\s+\\[[^\\]]+\\]\\s+([-\\d.eE+]+)`))
162
+ if (mm) ex[k] = Number(mm[1])
163
+ }
164
+ if (Object.keys(ex).length) facts.extras.transport = ex
165
+ }
166
+ return { ok: true, ...facts }
167
+ }
168
+
169
+ export function algoCaseAudit(args) {
170
+ const mismatches = []
171
+ const c = args.contract || {}
172
+ const f = args.case_facts || {}
173
+ const A = c.assumes || {}
174
+ if (A.compressible != null && f.compressible != null && A.compressible !== f.compressible) {
175
+ mismatches.push({ axis: 'compressibility', contract: A.compressible, case: f.compressible, severity: 'high', hint: 'compressible mismatch -> wrong continuity equation' })
176
+ }
177
+ if (A.phases != null && f.phases != null && A.phases !== f.phases) {
178
+ mismatches.push({ axis: 'phase count', contract: A.phases, case: f.phases, severity: 'high', hint: 'phase count mismatch -> Euler-Euler cannot drop into VOF' })
179
+ }
180
+ if (A.turbulence && f.turbulence && A.turbulence.toLowerCase() !== f.turbulence.toLowerCase() && !/laminar/i.test(f.turbulence)) {
181
+ mismatches.push({ axis: 'turbulence model', contract: A.turbulence, case: f.turbulence, severity: 'mid', hint: 'turbulence quantities may not exist or differ' })
182
+ }
183
+ if (c.governing_type && f.governing) {
184
+ const cgt = String(c.governing_type).toLowerCase()
185
+ const fgt = String(f.governing).toLowerCase()
186
+ if (cgt.includes('euler-euler') && fgt.includes('vof')) {
187
+ mismatches.push({ axis: 'governing equation family', contract: cgt, case: fgt, severity: 'high', hint: 'contract needs Euler-Euler but the case is VOF' })
188
+ }
189
+ if (cgt.includes('compressible') && !fgt.includes('compressible')) {
190
+ mismatches.push({ axis: 'governing equation family', contract: cgt, case: fgt, severity: 'high', hint: 'contract needs a compressible solver but the case is incompressible' })
191
+ }
192
+ }
193
+ const fields0 = new Set(f.fields_in_0 || [])
194
+ for (const o of c.outputs || []) {
195
+ const n = String(o.name || '').toLowerCase()
196
+ for (const target of ['k', 'omega', 'epsilon', 'nut', 'alpha.water', 'alpha.air', 't']) {
197
+ if (n.includes(target) && !fields0.has(target.charAt(0).toUpperCase() + target.slice(1)) && !fields0.has(target)) {
198
+ mismatches.push({ axis: 'missing field in 0/', contract: o.name, case: `0/ has no ${target}`, severity: 'low', hint: `the algorithm outputs ${target}, but 0/ does not have it` })
199
+ break
200
+ }
201
+ }
202
+ }
203
+ return {
204
+ ok: true,
205
+ pass: mismatches.length === 0,
206
+ mismatch_count: mismatches.length,
207
+ mismatches,
208
+ verdict: mismatches.length === 0 ? '✅ contract and case are compatible; proceed to step 4.' : `❌ ${mismatches.length} mismatches — step 4 is forbidden until resolved.`,
209
+ }
210
+ }
211
+
212
+ // --- experience store ---
package/lib/core.js ADDED
@@ -0,0 +1,47 @@
1
+ import { resolve } from 'node:path'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { readText } from './runtime.js'
4
+ import { resolveLanguage } from './discover.js'
5
+
6
+ export const DEFAULT_CORE_PATH = fileURLToPath(new URL('../CORE.md', import.meta.url))
7
+
8
+ export function mountCore(ctx, cfg) {
9
+ // --- thin core prompt section (always in context, sourced from CORE.md) ---
10
+ // The text is a function: DSH re-assembles the system prompt on every model
11
+ // step, so an edit to CORE.md takes effect on the next message, without a
12
+ // restart. A missing or empty file fails loudly at mount time; a file that
13
+ // becomes unreadable later keeps the last good text instead of breaking the
14
+ // request.
15
+ const corePath = cfg.corePath ? resolve(String(cfg.corePath)) : DEFAULT_CORE_PATH
16
+ const readCore = () => {
17
+ const raw = readText(corePath)
18
+ if (raw == null || !raw.trim()) return null
19
+ return raw.trim()
20
+ }
21
+ let coreText = readCore()
22
+ if (coreText == null) {
23
+ throw new Error(`[openfoam-workbench] CORE.md is missing or empty: ${corePath}`)
24
+ }
25
+ if (Buffer.byteLength(coreText) > 32768) {
26
+ console.error(`[openfoam-workbench] CORE.md is ${Buffer.byteLength(coreText)} bytes; the system prompt should stay well under 32 KB`)
27
+ }
28
+ let coreWarned = false
29
+ const coreSectionText = () => {
30
+ const next = readCore()
31
+ if (next != null) {
32
+ coreText = next
33
+ coreWarned = false
34
+ } else if (!coreWarned) {
35
+ console.error(`[openfoam-workbench] cannot re-read CORE.md (${corePath}); keeping the last good version`)
36
+ coreWarned = true
37
+ }
38
+ const language = cfg.responseLanguage || resolveLanguage(cfg)
39
+ return coreText.replace(/\{\{language\}\}/g, language)
40
+ }
41
+ ctx.systemPrompt.section({
42
+ name: 'openfoam-workbench:core',
43
+ order: 250,
44
+ text: coreSectionText,
45
+ interpolate: false,
46
+ })
47
+ }
@@ -0,0 +1,139 @@
1
+ // Zero-configuration environment discovery.
2
+ //
3
+ // A bundle installed from the marketplace cannot ship the author's absolute
4
+ // paths, so the plugin finds the local OpenFOAM installs and ParaView itself:
5
+ // known parent directories are scanned for `<dir>/etc/bashrc`, and ParaView is
6
+ // looked up in /opt and on PATH. Explicit configuration always wins.
7
+ import { existsSync, readdirSync, statSync } from 'node:fs'
8
+ import { basename, join } from 'node:path'
9
+ import { homedir } from 'node:os'
10
+
11
+ /** Parent directories that commonly hold OpenFOAM installations. */
12
+ const DEFAULT_PARENTS = [
13
+ '/opt',
14
+ '/usr/lib',
15
+ '/usr/lib/openfoam',
16
+ '/usr/local',
17
+ join(homedir(), 'OpenFOAM'),
18
+ join(homedir(), '.OpenFOAM'),
19
+ // container images (e.g. dicehub/openfoam) install under the build user's home
20
+ '/home/openfoam/OpenFOAM',
21
+ '/root/OpenFOAM',
22
+ '/home/ubuntu/OpenFOAM',
23
+ ]
24
+
25
+ function candidateDirs(parent) {
26
+ const out = []
27
+ try {
28
+ for (const e of readdirSync(parent, { withFileTypes: true })) {
29
+ if (!e.isDirectory()) continue
30
+ const dir = join(parent, e.name)
31
+ if (existsSync(join(dir, 'etc', 'bashrc'))) out.push(dir)
32
+ }
33
+ } catch {}
34
+ return out
35
+ }
36
+
37
+ /**
38
+ * Flavour and version hint from the directory name alone (the version itself is
39
+ * read from the sourced environment by openfoam_version_info later).
40
+ * openfoam14 -> org, 14
41
+ * OpenFOAM-14 -> org, 14
42
+ * openfoam2606 -> com, v2606
43
+ * OpenFOAM-v2606 -> com, v2606
44
+ */
45
+ export function classifyInstall(dir) {
46
+ const name = basename(dir)
47
+ const base = name.replace(/^openfoam[-_]?/i, '')
48
+ // OpenFOAM.com versions are vYYMM (v2606); org versions are small integers (14).
49
+ let m = /^v(\d{2}\.?\d{2})/i.exec(base)
50
+ if (m) return { kind: 'com', version: 'v' + m[1].replace('.', '') }
51
+ m = /^(\d{4})/.exec(base)
52
+ if (m) return { kind: 'com', version: 'v' + m[1] }
53
+ m = /^(\d{1,2})/.exec(base)
54
+ if (m) return { kind: 'org', version: m[1] }
55
+ return { kind: 'org', version: null }
56
+ }
57
+
58
+ /**
59
+ * OpenFOAM installations found on this machine.
60
+ * Returns { foamRoots: { <key>: <dir> }, defaultDistribution, found: [...] }.
61
+ * Keys follow the distribution (org/com); a second install of the same flavour
62
+ * gets a numeric suffix (org2, com2).
63
+ */
64
+ export function discoverFoamRoots(extraParents = []) {
65
+ const envRoot = String(process.env.WM_PROJECT_DIR || '').trim()
66
+ const parents = [...new Set([...extraParents.filter(Boolean), ...DEFAULT_PARENTS])]
67
+ const dirs = new Set()
68
+ if (envRoot && existsSync(join(envRoot, 'etc', 'bashrc'))) dirs.add(envRoot)
69
+ for (const parent of parents) for (const dir of candidateDirs(parent)) dirs.add(dir)
70
+ const foamRoots = {}
71
+ const found = []
72
+ const home = homedir()
73
+ const ordered = [...dirs].sort((a, b) => {
74
+ const ha = a.startsWith(home) ? 1 : 0
75
+ const hb = b.startsWith(home) ? 1 : 0
76
+ return ha - hb || a.localeCompare(b)
77
+ })
78
+ for (const dir of ordered) {
79
+ const { kind, version } = classifyInstall(dir)
80
+ let key = kind
81
+ let n = 2
82
+ while (foamRoots[key]) key = kind + n++
83
+ foamRoots[key] = dir
84
+ found.push({ key, dir, kind, version })
85
+ }
86
+ const keys = Object.keys(foamRoots)
87
+ const defaultDistribution = foamRoots.org ? 'org' : keys[0] || ''
88
+ return { foamRoots, defaultDistribution, found }
89
+ }
90
+
91
+ function executableOnPath(name, pathEnv) {
92
+ for (const dir of String(pathEnv || '').split(':')) {
93
+ if (!dir) continue
94
+ try {
95
+ if (existsSync(join(dir, name)) && statSync(join(dir, name)).isFile()) return join(dir, name)
96
+ } catch {}
97
+ }
98
+ return ''
99
+ }
100
+
101
+ /** ParaView for headless renders: /opt/paraview*, then PATH. */
102
+ export function discoverParaview(extraParents = [], pathEnv = process.env.PATH, options = {}) {
103
+ const parents = options.parents ?? [...new Set([...extraParents.filter(Boolean), '/opt', '/usr/local'])]
104
+ for (const parent of parents) {
105
+ let entries = []
106
+ try { entries = readdirSync(parent, { withFileTypes: true }) } catch { continue }
107
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
108
+ if (!e.isDirectory() || !/paraview/i.test(e.name)) continue
109
+ const bin = join(parent, e.name, 'bin')
110
+ const python = join(bin, 'pvpython')
111
+ if (existsSync(python)) return { paraviewExe: join(bin, 'paraview'), paraviewPython: python }
112
+ }
113
+ }
114
+ const pvpython = executableOnPath('pvpython', pathEnv)
115
+ if (!pvpython) return { paraviewExe: '', paraviewPython: '' }
116
+ return { paraviewExe: executableOnPath('paraview', pathEnv) || '', paraviewPython: pvpython }
117
+ }
118
+
119
+ /** python3 for the PDF-text fallback (pdftotext is optional). */
120
+ export function discoverPython(pathEnv = process.env.PATH) {
121
+ return executableOnPath('python3', pathEnv) || executableOnPath('python', pathEnv) || ''
122
+ }
123
+
124
+ /**
125
+ * Resolve the language the agent should answer in.
126
+ * Priority: explicit config > OS locale (LC_ALL/LC_MESSAGES/LANG) > English.
127
+ * An explicit value may be a code ('ru') or a name ('Russian') and is used as given.
128
+ */
129
+ export function resolveLanguage(cfg = {}, env = process.env) {
130
+ const names = {
131
+ ru: 'Russian', en: 'English', de: 'German', fr: 'French', es: 'Spanish', it: 'Italian',
132
+ pt: 'Portuguese', pl: 'Polish', uk: 'Ukrainian', zh: 'Chinese', ja: 'Japanese', ko: 'Korean', tr: 'Turkish',
133
+ }
134
+ const explicit = String(cfg.language || '').trim()
135
+ if (explicit) return names[explicit.toLowerCase()] || explicit
136
+ const raw = String(env.LC_ALL || env.LC_MESSAGES || env.LANG || '').trim()
137
+ const code = raw.split(/[.@]/)[0].split('_')[0].toLowerCase()
138
+ return names[code] || 'English'
139
+ }
@@ -0,0 +1,92 @@
1
+ // Escalation: the audited way out of the strict write policy.
2
+ //
3
+ // In `strict` mode a direct edit of a case dictionary is refused. When no plugin
4
+ // tool can express the change, the agent asks for an explicit, single-use token
5
+ // that covers one target for a short time. The request must carry evidence: the
6
+ // tools it tried must actually have been called (and failed) recently, so the
7
+ // exception is checkable rather than a claim.
8
+ import { randomUUID } from 'node:crypto'
9
+
10
+ export const TTL_MS = 10 * 60 * 1000
11
+ export const EVIDENCE_WINDOW_MS = 15 * 60 * 1000
12
+
13
+ const store = new Map()
14
+ const events = []
15
+
16
+ /** Which of the named tools were really called recently, and which of those failed. */
17
+ export function evidenceCheck({ registry, toolsTried = [], windowMs = EVIDENCE_WINDOW_MS, now = Date.now() }) {
18
+ const tried = []
19
+ for (const tool of toolsTried) {
20
+ const calls = registry && typeof registry.history === 'function' ? registry.history({ ms: windowMs, name: tool }) : []
21
+ tried.push({ tool, calls: calls.length, failed: calls.filter((r) => r.ok === false).length })
22
+ }
23
+ return { verified: tried.some((t) => t.failed > 0), windowMs, tried }
24
+ }
25
+
26
+ /**
27
+ * Request one escalation token.
28
+ * Returns { ok: true, id, expiresAt, scope } or { ok: false, error, evidence }.
29
+ */
30
+ export function createEscalation({ target, operation, why, toolsTried = [], authority = 'auto', registry, agent = null, ttlMs = TTL_MS, now = Date.now() }) {
31
+ const cleanTarget = String(target || '').trim()
32
+ if (!cleanTarget) return { ok: false, error: 'escalation needs a target path' }
33
+ const evidence = evidenceCheck({ registry, toolsTried, now })
34
+ if (!evidence.verified) {
35
+ return {
36
+ ok: false,
37
+ error: 'escalation not verified: none of the named tools failed recently, so there is no evidence that the plugin tools cannot do this',
38
+ hint: 'call the plugin tool first; if it fails, escalate with that tool in toolsTried (within 15 minutes)',
39
+ evidence,
40
+ }
41
+ }
42
+ const id = 'esc_' + randomUUID().slice(0, 8)
43
+ const token = {
44
+ id,
45
+ target: cleanTarget,
46
+ operation: String(operation || 'direct-write'),
47
+ why: String(why || ''),
48
+ authority,
49
+ agent: agent || null,
50
+ createdAt: now,
51
+ expiresAt: now + Math.min(Math.max(Number(ttlMs) || TTL_MS, 60_000), TTL_MS),
52
+ used: false,
53
+ }
54
+ store.set(id, token)
55
+ events.push({ at: now, kind: 'created', id, target: token.target, operation: token.operation, authority, evidence: evidence.tried })
56
+ return { ok: true, id, target: token.target, operation: token.operation, expiresAt: token.expiresAt, ttlMs: token.expiresAt - now, evidence, authority }
57
+ }
58
+
59
+ /**
60
+ * Take a token for `target` (single use). The hook calls this before it lets a
61
+ * direct write through, so one escalation authorises exactly one write.
62
+ */
63
+ export function consumeEscalation({ target, agent = null, now = Date.now() }) {
64
+ const wanted = String(target || '')
65
+ for (const token of store.values()) {
66
+ if (token.used || token.expiresAt <= now) continue
67
+ if (agent && token.agent && token.agent !== agent) continue
68
+ if (token.target !== wanted) continue
69
+ token.used = true
70
+ token.usedAt = now
71
+ events.push({ at: now, kind: 'consumed', id: token.id, target: token.target, operation: token.operation })
72
+ return { ok: true, id: token.id, operation: token.operation }
73
+ }
74
+ return { ok: false }
75
+ }
76
+
77
+ /** Report for openfoam_usage_report. */
78
+ export function escalationsReport(now = Date.now()) {
79
+ const all = [...store.values()]
80
+ return {
81
+ count: all.length,
82
+ active: all.filter((t) => !t.used && t.expiresAt > now).map((t) => ({ id: t.id, target: t.target, operation: t.operation, expiresAt: t.expiresAt })),
83
+ used: all.filter((t) => t.used).length,
84
+ expired: all.filter((t) => !t.used && t.expiresAt <= now).length,
85
+ recent: events.slice(-20),
86
+ }
87
+ }
88
+
89
+ export function resetEscalations() {
90
+ store.clear()
91
+ events.length = 0
92
+ }