@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
package/lib/explib.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { basename } from 'node:path'
|
|
3
|
+
|
|
4
|
+
/** Card ids are slugs: reject separators and traversal before touching the disk. */
|
|
5
|
+
function safeId(id) {
|
|
6
|
+
const raw = String(id || '').trim()
|
|
7
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(raw)) return null
|
|
8
|
+
if (basename(raw) !== raw) return null
|
|
9
|
+
return raw
|
|
10
|
+
}
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
import { createHash } from 'node:crypto'
|
|
13
|
+
import { ensureExpDir, experienceDirOf, resolveCase } from './runtime.js'
|
|
14
|
+
import { loadErrorPatterns } from './knowledge.js'
|
|
15
|
+
|
|
16
|
+
export function loadExperience(cfg) {
|
|
17
|
+
const d = experienceDirOf(cfg)
|
|
18
|
+
let names = []
|
|
19
|
+
try { names = readdirSync(d) } catch { return [] }
|
|
20
|
+
const cards = []
|
|
21
|
+
for (const n of names) {
|
|
22
|
+
if (!n.endsWith('.json') || n.startsWith('_')) continue
|
|
23
|
+
try {
|
|
24
|
+
const c = JSON.parse(readFileSync(join(d, n), 'utf8'))
|
|
25
|
+
if (c && c.id) cards.push(c)
|
|
26
|
+
} catch {}
|
|
27
|
+
}
|
|
28
|
+
return cards
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function contentHash(card) {
|
|
32
|
+
return createHash('sha1')
|
|
33
|
+
.update(JSON.stringify({ t: String(card.title || '').toLowerCase().trim(), r: (card.recipe || []).map((x) => String(x).toLowerCase().trim()), k: card.key_params || {}, p: (card.pitfalls || []).map((x) => String(x).toLowerCase().trim()) }))
|
|
34
|
+
.digest('hex')
|
|
35
|
+
.slice(0, 16)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function saveExperience(cfg, input) {
|
|
39
|
+
const d = ensureExpDir(cfg)
|
|
40
|
+
const card = {
|
|
41
|
+
id: '',
|
|
42
|
+
title: String(input.title || 'Untitled'),
|
|
43
|
+
domain: String(input.domain || 'general'),
|
|
44
|
+
triggers: Array.isArray(input.triggers) ? input.triggers.map(String) : [],
|
|
45
|
+
solver: String(input.solver || ''),
|
|
46
|
+
physics: String(input.physics || ''),
|
|
47
|
+
recipe: Array.isArray(input.recipe) ? input.recipe.map(String) : [],
|
|
48
|
+
key_params: input.key_params && typeof input.key_params === 'object' ? input.key_params : {},
|
|
49
|
+
verify_seq: Array.isArray(input.verify_seq) ? input.verify_seq.map(String) : [],
|
|
50
|
+
pitfalls: Array.isArray(input.pitfalls) ? input.pitfalls.map(String) : [],
|
|
51
|
+
provenance: input.provenance && typeof input.provenance === 'object' ? input.provenance : {},
|
|
52
|
+
}
|
|
53
|
+
card.content_hash = contentHash(card)
|
|
54
|
+
const all = loadExperience(cfg)
|
|
55
|
+
const ex = all.find((c) => c.content_hash === card.content_hash)
|
|
56
|
+
if (ex) {
|
|
57
|
+
ex.stats = ex.stats || { hits: 0 }
|
|
58
|
+
ex.stats.hits = (ex.stats.hits || 0) + 1
|
|
59
|
+
ex.stats.updated = Date.now()
|
|
60
|
+
writeFileSync(join(d, ex.id + '.json'), JSON.stringify(ex, null, 2))
|
|
61
|
+
return { ok: true, id: ex.id, deduped: true }
|
|
62
|
+
}
|
|
63
|
+
const slug = (card.solver || card.title).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || 'card'
|
|
64
|
+
card.id = `${card.domain}-${slug}-${card.content_hash.slice(0, 6)}`
|
|
65
|
+
card.stats = { created: Date.now(), updated: Date.now(), hits: 0 }
|
|
66
|
+
writeFileSync(join(d, card.id + '.json'), JSON.stringify(card, null, 2))
|
|
67
|
+
return { ok: true, id: card.id, deduped: false }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function recallExperience(cfg, query, topK = 3) {
|
|
71
|
+
const text = String(query || '').toLowerCase()
|
|
72
|
+
if (!text.trim()) return { ok: true, count: 0, cards: [] }
|
|
73
|
+
const scored = []
|
|
74
|
+
for (const card of loadExperience(cfg)) {
|
|
75
|
+
let score = 0
|
|
76
|
+
for (const t of card.triggers || []) {
|
|
77
|
+
const trig = String(t).toLowerCase().trim()
|
|
78
|
+
if (trig.length >= 3 && text.includes(trig)) score += 1 + Math.min(trig.length / 12, 2)
|
|
79
|
+
}
|
|
80
|
+
const solver = String(card.solver || '').toLowerCase()
|
|
81
|
+
if (solver.length >= 4 && text.includes(solver.split(/[\s(]/)[0])) score += 1.5
|
|
82
|
+
score += Math.min((card.stats && card.stats.hits ? card.stats.hits : 0) * 0.05, 0.5)
|
|
83
|
+
if (score > 0) scored.push({ card, score })
|
|
84
|
+
}
|
|
85
|
+
scored.sort((a, b) => b.score - a.score)
|
|
86
|
+
return { ok: true, count: Math.min(scored.length, topK), cards: scored.slice(0, Math.max(1, topK)).map((x) => x.card) }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function forgetExperience(cfg, id) {
|
|
90
|
+
const safe = safeId(id)
|
|
91
|
+
if (!safe) return { ok: false, error: `invalid card id: ${id}`, hint: 'ids are slugs (letters, digits, ".", "_", "-")' }
|
|
92
|
+
const d = experienceDirOf(cfg)
|
|
93
|
+
const p = join(d, safe + '.json')
|
|
94
|
+
if (!existsSync(p)) return { ok: false, error: 'no such experience: ' + id }
|
|
95
|
+
try { rmSync(p) } catch (e) { return { ok: false, error: String(e.message || e) } }
|
|
96
|
+
return { ok: true, id }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function exportExperience(cfg, outPath) {
|
|
100
|
+
const d = ensureExpDir(cfg)
|
|
101
|
+
const file = outPath ? resolveCase(cfg, outPath) : join(d, 'experience-bundle.json')
|
|
102
|
+
const cards = loadExperience(cfg)
|
|
103
|
+
const payload = { format: 'openfoam-workbench-experience', version: 1, exported_at: Date.now(), cards, error_patterns: loadErrorPatterns(cfg) }
|
|
104
|
+
writeFileSync(file, JSON.stringify(payload, null, 2))
|
|
105
|
+
return { ok: true, count: cards.length, path: file }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function importExperience(cfg, inPath) {
|
|
109
|
+
const file = resolveCase(cfg, inPath)
|
|
110
|
+
if (!existsSync(file)) return { ok: false, error: 'bundle not found: ' + file }
|
|
111
|
+
let data
|
|
112
|
+
try { data = JSON.parse(readFileSync(file, 'utf8')) } catch (e) { return { ok: false, error: 'bad JSON: ' + e.message } }
|
|
113
|
+
let imported = 0
|
|
114
|
+
for (const c of data.cards || []) {
|
|
115
|
+
const r = saveExperience(cfg, c)
|
|
116
|
+
if (r.ok && !r.deduped) imported++
|
|
117
|
+
}
|
|
118
|
+
for (const e of data.error_patterns || []) addErrorPattern(cfg, e)
|
|
119
|
+
return { ok: true, imported, path: file }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function addErrorPattern(cfg, input) {
|
|
123
|
+
const d = ensureExpDir(cfg)
|
|
124
|
+
const pattern = String(input.pattern || '').trim()
|
|
125
|
+
if (!pattern) return { ok: false, error: 'pattern is empty' }
|
|
126
|
+
try { new RegExp(pattern, input.flags || 'i') } catch (e) { return { ok: false, error: 'invalid regex: ' + e.message } }
|
|
127
|
+
const arr = loadErrorPatterns(cfg)
|
|
128
|
+
const cat = String(input.category || 'Learned error')
|
|
129
|
+
const ex = arr.find((e) => e.pattern === pattern && e.category === cat)
|
|
130
|
+
if (ex) {
|
|
131
|
+
ex.hits = (ex.hits || 0) + 1
|
|
132
|
+
writeFileSync(join(d, '_error_patterns.json'), JSON.stringify(arr, null, 2))
|
|
133
|
+
return { ok: true, deduped: true, total: arr.length }
|
|
134
|
+
}
|
|
135
|
+
arr.push({ pattern, flags: input.flags || 'i', category: cat, causes: input.causes || [], steps: input.steps || [], hits: 0, ts: Date.now() })
|
|
136
|
+
writeFileSync(join(d, '_error_patterns.json'), JSON.stringify(arr, null, 2))
|
|
137
|
+
return { ok: true, deduped: false, total: arr.length }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function appendSft(cfg, sample) {
|
|
141
|
+
const d = ensureExpDir(cfg)
|
|
142
|
+
const file = join(d, '_sft.jsonl')
|
|
143
|
+
appendFileSync(file, JSON.stringify(sample) + '\n')
|
|
144
|
+
let total = 0
|
|
145
|
+
try { total = readFileSync(file, 'utf8').split('\n').filter(Boolean).length } catch {}
|
|
146
|
+
return { ok: true, path: file, total }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// --- pvpython render helper ---
|
package/lib/impact.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Impact of a dictionary change, judged by the semantics of the entry — not by
|
|
2
|
+
// the file it lives in. `0/U`, `0/Yi`, `fvSchemes` and `deltaT` can produce a
|
|
3
|
+
// perfectly converged, syntactically valid and physically wrong run, so they
|
|
4
|
+
// are never "safe"; output/organisation keys in controlDict are.
|
|
5
|
+
//
|
|
6
|
+
// low : output and run organisation (writeInterval, writeFormat, ...)
|
|
7
|
+
// high : anything that can change the physics or the numerics
|
|
8
|
+
// critical : can execute code or replace a whole group of files (libs, functions)
|
|
9
|
+
const LOW_CONTROL_ENTRIES = new Set([
|
|
10
|
+
'writeInterval', 'writeControl', 'writeFormat', 'writePrecision', 'writeCompression',
|
|
11
|
+
'timeFormat', 'timePrecision',
|
|
12
|
+
])
|
|
13
|
+
|
|
14
|
+
const CRITICAL_CONTROL_ENTRIES = new Set(['libs', 'functions'])
|
|
15
|
+
|
|
16
|
+
/** Base dictionary name, ignoring region prefixes and the system/ prefix. */
|
|
17
|
+
export function dictBaseName(file) {
|
|
18
|
+
const rel = String(file || '').replace(/^system\//, '')
|
|
19
|
+
return rel.split('/').pop()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @returns {'low'|'high'|'critical'} — the conservative default is 'high'.
|
|
24
|
+
*/
|
|
25
|
+
export function classifyImpact(file, entry, value) {
|
|
26
|
+
const base = dictBaseName(file)
|
|
27
|
+
const name = String(entry || '').trim()
|
|
28
|
+
if (base === 'controlDict') {
|
|
29
|
+
if (CRITICAL_CONTROL_ENTRIES.has(name)) return 'critical'
|
|
30
|
+
// purgeWrite > 0 deletes older time directories: losing a long run's history
|
|
31
|
+
// is not an organisational change, so the *value* decides the impact.
|
|
32
|
+
if (name === 'purgeWrite') {
|
|
33
|
+
// Only a literal zero is harmless; '-1', 'abc' and an empty value all let
|
|
34
|
+
// OpenFOAM write purging behaviour we cannot reason about, so they are high.
|
|
35
|
+
const raw = String(value ?? '').trim()
|
|
36
|
+
return /^0+(\.0*)?$/.test(raw) ? 'low' : 'high'
|
|
37
|
+
}
|
|
38
|
+
if (LOW_CONTROL_ENTRIES.has(name)) return 'low'
|
|
39
|
+
return 'high'
|
|
40
|
+
}
|
|
41
|
+
// fvSchemes, fvSolution, constant/*, 0/* (boundary and initial conditions),
|
|
42
|
+
// blockMeshDict, and anything unknown: capable of changing the physics.
|
|
43
|
+
return 'high'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** What to do with a change: apply, show a preview, or require approval. */
|
|
47
|
+
export function decideAction({ impact, writeMode = 'impact', applyRequested = false, dryRun = false }) {
|
|
48
|
+
if (dryRun) return 'preview'
|
|
49
|
+
if (impact === 'critical') return 'approval'
|
|
50
|
+
if (applyRequested) return 'apply'
|
|
51
|
+
if (writeMode === 'preview') return 'preview'
|
|
52
|
+
if (writeMode === 'apply') return 'apply'
|
|
53
|
+
// writeMode === 'impact' (default)
|
|
54
|
+
return impact === 'low' ? 'apply' : 'preview'
|
|
55
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// dsh-openfoam-workbench — OpenFOAM domain layer for DeepSeek Harness.
|
|
2
|
+
//
|
|
3
|
+
// The entry point only composes: the core prompt (CORE.md), the bundled skills
|
|
4
|
+
// and the tool groups. Everything else lives in focused modules:
|
|
5
|
+
//
|
|
6
|
+
// lib/runtime.js process/paths/runs helpers + config defaults (deps)
|
|
7
|
+
// lib/knowledge.js solver classification + error patterns + diagnosis
|
|
8
|
+
// lib/presentation.js pvpython renders, inline images, tool-call cards, tables
|
|
9
|
+
// lib/registry.js the registration choke point: render, schema, telemetry, safety
|
|
10
|
+
// lib/core.js the always-on prompt section, sourced from CORE.md
|
|
11
|
+
// lib/skills.js reads skills/*/SKILL.md and registers them
|
|
12
|
+
// lib/of-engine.js dictionary parser + doctor checks (MIT, from dsh-openfoam-doctor)
|
|
13
|
+
// lib/of-case.js multi-region model, dict paths, command whitelist, progress
|
|
14
|
+
// lib/tools/*.js one factory per tool group: ({ cfg, attachImage }) => tools
|
|
15
|
+
import { DEFAULTS, reconcileAll, validateConfig } from './runtime.js'
|
|
16
|
+
import { mountCore } from './core.js'
|
|
17
|
+
import { mountSkills } from './skills.js'
|
|
18
|
+
import { makePresentation } from './presentation.js'
|
|
19
|
+
import { makeRegistry } from './registry.js'
|
|
20
|
+
import { discoverFoamRoots, discoverParaview, discoverPython, resolveLanguage } from './discover.js'
|
|
21
|
+
import { evaluateToolCall } from './routing-guard.js'
|
|
22
|
+
import { consumeEscalation } from './escalations.js'
|
|
23
|
+
import envTools from './tools/env.js'
|
|
24
|
+
import caseTools from './tools/case.js'
|
|
25
|
+
import runTools from './tools/run.js'
|
|
26
|
+
import buildTools from './tools/build.js'
|
|
27
|
+
import meshTools from './tools/mesh.js'
|
|
28
|
+
import renderTools from './tools/render.js'
|
|
29
|
+
import paperTools from './tools/papers.js'
|
|
30
|
+
import experienceTools from './tools/experience.js'
|
|
31
|
+
import metaTools from './tools/meta.js'
|
|
32
|
+
|
|
33
|
+
export { Config } from './settings-schema.js'
|
|
34
|
+
|
|
35
|
+
export const name = 'openfoam-workbench'
|
|
36
|
+
export const inject = ['tools', 'systemPrompt', 'skills']
|
|
37
|
+
|
|
38
|
+
export function apply(ctx, config = {}) {
|
|
39
|
+
const cfg = { ...DEFAULTS, ...(config || {}) }
|
|
40
|
+
|
|
41
|
+
// Zero-configuration installs: find the machine's OpenFOAM and ParaView when
|
|
42
|
+
// the profile does not name them. Explicit configuration always wins, so a
|
|
43
|
+
// profile that sets foamRoots/paraview* is untouched.
|
|
44
|
+
// An explicit legacy `foamRoot` also counts as configuration: discovery must
|
|
45
|
+
// not replace it with whatever else is installed on the machine.
|
|
46
|
+
if (!cfg.foamRoot && !Object.keys(cfg.foamRoots || {}).length) {
|
|
47
|
+
const found = discoverFoamRoots()
|
|
48
|
+
if (Object.keys(found.foamRoots).length) {
|
|
49
|
+
cfg.foamRoots = found.foamRoots
|
|
50
|
+
if (!cfg.defaultDistribution) cfg.defaultDistribution = found.defaultDistribution
|
|
51
|
+
console.log('[openfoam-workbench] discovered OpenFOAM: ' + Object.entries(found.foamRoots).map(([k, v]) => k + '=' + v).join(', '))
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (!cfg.paraviewPython || !cfg.paraviewExe) {
|
|
55
|
+
const pv = discoverParaview()
|
|
56
|
+
if (!cfg.paraviewPython && pv.paraviewPython) cfg.paraviewPython = pv.paraviewPython
|
|
57
|
+
if (!cfg.paraviewExe && pv.paraviewExe) cfg.paraviewExe = pv.paraviewExe
|
|
58
|
+
}
|
|
59
|
+
if (!cfg.pythonPath) cfg.pythonPath = discoverPython()
|
|
60
|
+
cfg.responseLanguage = resolveLanguage(cfg)
|
|
61
|
+
|
|
62
|
+
const configWarnings = validateConfig(cfg)
|
|
63
|
+
if (!Array.isArray(cfg.caseRoots) || !cfg.caseRoots.length) {
|
|
64
|
+
configWarnings.push('caseRoots is empty: relative case paths resolve from ' + process.cwd() + ' (set caseRoots in the profile patch to pin a workspace)')
|
|
65
|
+
}
|
|
66
|
+
if (configWarnings.length) console.warn('[openfoam-workbench] config warnings:\n ' + configWarnings.join('\n '))
|
|
67
|
+
try { reconcileAll(cfg) } catch (e) { /* registry may be unwritable */ }
|
|
68
|
+
|
|
69
|
+
mountCore(ctx, cfg)
|
|
70
|
+
mountSkills(ctx)
|
|
71
|
+
|
|
72
|
+
// Route case edits through the plugin: watch every tool call and, depending on
|
|
73
|
+
// `enforceToolRouting`, warn about or refuse direct dictionary writes.
|
|
74
|
+
const routingMode = String(cfg.enforceToolRouting || 'warn')
|
|
75
|
+
try {
|
|
76
|
+
// A restricted context may not expose `on` at all: then the guard is simply
|
|
77
|
+
// not installed, and the write policy still covers this plugin's own tools.
|
|
78
|
+
if (routingMode !== 'off' && typeof ctx.on === 'function') {
|
|
79
|
+
ctx.on('tools/pre-execute', (exec, next) => {
|
|
80
|
+
const verdict = evaluateToolCall({
|
|
81
|
+
toolName: exec && exec.toolName,
|
|
82
|
+
args: (exec && exec.args) || {},
|
|
83
|
+
mode: routingMode,
|
|
84
|
+
consume: (target) => consumeEscalation({ target, agent: exec && exec.agent ? exec.agent.id : null }),
|
|
85
|
+
})
|
|
86
|
+
if (verdict.decision === 'deny') {
|
|
87
|
+
return { kind: 'deny', reason: verdict.reason, info: { redirect: verdict.redirect || 'openfoam_dict_set' } }
|
|
88
|
+
}
|
|
89
|
+
return next()
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
} catch {
|
|
93
|
+
/* no hook seam in this context */
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const presentation = makePresentation(ctx)
|
|
97
|
+
const registry = makeRegistry(ctx, { RENDERS: presentation.RENDERS })
|
|
98
|
+
// Optional service, resolved *at call time*: it may mount after this plugin
|
|
99
|
+
// (bootstrap order), and the restricted context throws on ctx.<prop> access.
|
|
100
|
+
const getApproval = () => (typeof ctx.get === 'function' ? ctx.get('approval') : undefined)
|
|
101
|
+
const deps = { cfg, attachImage: presentation.attachImage, registry, getApproval }
|
|
102
|
+
const factories = [
|
|
103
|
+
envTools, caseTools, runTools, buildTools, meshTools,
|
|
104
|
+
renderTools, paperTools, experienceTools, metaTools,
|
|
105
|
+
]
|
|
106
|
+
for (const factory of factories) {
|
|
107
|
+
for (const tool of factory(deps)) registry.register(tool)
|
|
108
|
+
}
|
|
109
|
+
}
|
package/lib/knowledge.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { experienceDirOf, run } from './runtime.js'
|
|
4
|
+
|
|
5
|
+
const ERROR_PATTERNS = [
|
|
6
|
+
{ re: /floating point exception|FOAM FATAL ERROR.*FPE|signal\s+FPE/i, category: 'NaN/Inf numerical divergence (FPE)', causes: ['CFL too large -> reduce dt or use adaptive deltaT', 'inconsistent BCs cause a division by zero at t=0', '0/ was not setFields-ed, alpha/T are still default', 'a property is zero (e.g. mu=0, sigma=0)'], steps: ['openfoam_solver_status to find the first nan/Inf step', 'openfoam_residual_series to see which field diverges first', 'openfoam_case_probe_facts to confirm properties', 'openfoam_inspect_case to check dimensions/internalField'] },
|
|
7
|
+
{ re: /Cannot find file.*system\/(controlDict|fvSchemes|fvSolution|blockMeshDict)/i, category: 'missing system/ dictionary', causes: ['the case is incomplete', 'the cwd is not the case directory'], steps: ['openfoam_inspect_case to verify system/', 'check the cwd'] },
|
|
8
|
+
{ re: /keyword (\w+) is undefined in dictionary/i, category: 'missing or misspelled dictionary keyword', causes: ['template and solver versions do not match', 'a required entry is missing', 'the keyword was renamed in this OpenFOAM version'], steps: ['openfoam_find_tutorial for a template of the same solver', 'openfoam_read_dict for the accepted keys'] },
|
|
9
|
+
{ re: /unknown patch type|Unknown patchField type|unknown boundary condition/i, category: 'BC / patch type not registered', causes: ['BC name misspelled', 'the required lib is not linked in controlDict.libs', 'the solver does not support that BC'], steps: ['openfoam_find_source for the correct spelling', 'add libs ("...") in controlDict', 'openfoam_case_probe_facts for the BCs the solver supports'] },
|
|
10
|
+
{ re: /dimensions of .* are not (correct|consistent|dimensionally)/i, category: 'inconsistent dimensions', causes: ['wrong dimensions in 0/ (k = [0 2 -2 0 0 0 0])', 'the BC value has wrong units', '0/ out of sync with 0.orig/'], steps: ['read the dimensions line of the failing field', 'openfoam_algo_extract_contract for the paper units', 're-copy from 0.orig'] },
|
|
11
|
+
{ re: /Maximum number of iterations exceeded.*GAMG|smoothSolver.*did not converge|PCG.*did not converge/i, category: 'linear solver did not converge', causes: ['poor mesh quality, maxNonOrtho > 70', 'tolerance/relTol too strict', 'wrong smoother'], steps: ['openfoam_mesh_verify for maxNonOrtho/skewness', 'tune fvSolution: loosen tolerance / GaussSeidel / DIC'] },
|
|
12
|
+
{ re: /Inconsistent\s+addressing|negative volume|negative determinant|skewness exceeds/i, category: 'bad mesh cells', causes: ['snappyHexMesh carved out a region', 'thin sliver cells', 'the STL normals are inverted'], steps: ['openfoam_mesh_verify', 'openfoam_mesh_stl_check', 'raise minVol / reduce first_layer_thickness'] },
|
|
13
|
+
{ re: /Cannot find cellSet|Cannot find cellZone/i, category: 'setFields region selector matched nothing', causes: ['the boxToCell bbox extends beyond the mesh', 'cellSet/cellZone name misspelled', 'setSet/topoSet was not run'], steps: ['shrink the setFieldsDict bbox to the mesh extent', 'run topoSet/setFields'] },
|
|
14
|
+
{ re: /Maximum number of nonlinear iterations|Continuity error/i, category: 'continuity / p-U coupling imbalance', causes: ['not enough PIMPLE nOuterCorrectors', 'inlet/outlet do not conserve mass', 'wrong atmosphere BC type'], steps: ['raise nOuterCorrectors to 3-5', 'openfoam_case_probe_facts to check patch pairing'] },
|
|
15
|
+
{ re: /undefined reference to|error: .*was not declared|fatal error: .*\.H: No such file/i, category: 'C++ compile error', causes: ['header path missing from EXE_INC', 'library missing from LIB_LIBS', 'an inherited virtual function is not implemented'], steps: ['openfoam_dry_compile to catch the first error', 'read Make/options for -I and -l', 'openfoam_find_source for a reference'] },
|
|
16
|
+
{ re: /signal\s+(11|SIGSEGV)|segmentation fault/i, category: 'SegFault', causes: ['out-of-bounds container access', 'inconsistent parallel decomposition', 'an unregistered scheme name'], steps: ['rerun serially', 'validate every scheme name in fvSchemes'] },
|
|
17
|
+
{ re: /not in patches|patches do not match|patches don't match/i, category: 'patch name mismatch', causes: ['patch names in 0/ != polyMesh/boundary', '0/ was not updated after blockMesh regenerated the mesh'], steps: ['openfoam_inspect_case to list actual patches', 'align boundaryField in every 0/ field'] },
|
|
18
|
+
{ re: /Time step continuity errors.*sum local = [\d.eE+-]+, global = [\d.eE+-]+, cumulative/i, category: 'mass conservation drift', causes: ['inlet/outlet fluxes are unbalanced', 'wrong p BC type'], steps: ['openfoam_case_probe_facts for inlet/outlet pairing', 'openfoam_inspect_case for boundaryField of 0/p'] },
|
|
19
|
+
{ re: /No such file or directory/i, category: 'file not found', causes: ['wrong path', 'the previous step never produced it'], steps: ['verify the parent directory', 'check the previous step exit code'] },
|
|
20
|
+
{ re: /Floating point exception.*nan|Foam::error::printStack|FOAM aborting/i, category: 'OpenFOAM aborted deliberately', causes: ['the solver stopped after seeing nan', 'patch pairing error'], steps: ['read the 50 log lines before the abort', 'diagnose the previous error block'] },
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
export function loadErrorPatterns(cfg) {
|
|
24
|
+
try {
|
|
25
|
+
const a = JSON.parse(readFileSync(join(experienceDirOf(cfg), '_error_patterns.json'), 'utf8'))
|
|
26
|
+
return Array.isArray(a) ? a : []
|
|
27
|
+
} catch {
|
|
28
|
+
return []
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function diagnoseError(cfg, text) {
|
|
33
|
+
const s = String(text || '')
|
|
34
|
+
if (!s.trim()) return { ok: false, error: 'text is empty' }
|
|
35
|
+
const learned = loadErrorPatterns(cfg).map((e) => {
|
|
36
|
+
let re
|
|
37
|
+
try { re = new RegExp(e.pattern, e.flags || 'i') } catch { re = /$a^/ }
|
|
38
|
+
return { re, category: (e.category || 'Learned') + ' (learned)', causes: e.causes || [], steps: e.steps || [] }
|
|
39
|
+
})
|
|
40
|
+
const hits = []
|
|
41
|
+
for (const p of ERROR_PATTERNS.concat(learned)) {
|
|
42
|
+
const m = s.match(p.re)
|
|
43
|
+
if (m) hits.push({ category: p.category, matched_snippet: m[0].slice(0, 120), causes: p.causes, next_steps: p.steps })
|
|
44
|
+
}
|
|
45
|
+
if (!hits.length) {
|
|
46
|
+
return { ok: true, matched: false, hint: `No known pattern matched (${ERROR_PATTERNS.length} built-in + ${learned.length} learned). Paste the log tail and, after fixing it, register the pattern with openfoam_learn_error_pattern.` }
|
|
47
|
+
}
|
|
48
|
+
return { ok: true, matched: true, count: hits.length, hits }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const SOLVER_MAP = {
|
|
52
|
+
// OF14 modules (foamRun "solver" values)
|
|
53
|
+
incompressibleFluid: ['incompressible single-phase', false, 1],
|
|
54
|
+
isothermalFluid: ['isothermal compressible single-phase', true, 1],
|
|
55
|
+
multicomponentFluid: ['compressible multicomponent/combustion', true, 1],
|
|
56
|
+
shockFluid: ['compressible (shock capturing)', true, 1],
|
|
57
|
+
XiFluid: ['premixed combustion (Xi)', true, 1],
|
|
58
|
+
incompressibleVoF: ['VOF two-phase (incompressible)', false, 2],
|
|
59
|
+
compressibleVoF: ['VOF two-phase (compressible)', true, 2],
|
|
60
|
+
incompressibleMultiphaseVoF: ['VOF multiphase (incompressible)', false, 2],
|
|
61
|
+
compressibleMultiphaseVoF: ['VOF multiphase (compressible)', true, 2],
|
|
62
|
+
multiphaseEuler: ['Euler-Euler multiphase', null, 2],
|
|
63
|
+
incompressibleDriftFlux: ['drift-flux two-phase (incompressible)', false, 2],
|
|
64
|
+
incompressibleDenseParticleFluid: ['Euler-Lagrange dense particles', false, 1],
|
|
65
|
+
solid: ['solid mechanics', null, 1],
|
|
66
|
+
solidDisplacement: ['solid displacement', null, 1],
|
|
67
|
+
film: ['thin film', null, 1],
|
|
68
|
+
isothermalFilm: ['thin film (isothermal)', null, 1],
|
|
69
|
+
movingMesh: ['mesh motion', null, 1],
|
|
70
|
+
fluid: ['generic fluid', null, 1],
|
|
71
|
+
// application entry points (applications/solvers)
|
|
72
|
+
chemFoam: ['chemical kinetics (0-D reactor)', true, 1],
|
|
73
|
+
potentialFoam: ['potential flow', false, 1],
|
|
74
|
+
boundaryFoam: ['boundary-layer profile', false, 1],
|
|
75
|
+
foamRun: ['generic modular solver runner', null, null],
|
|
76
|
+
foamMultiRun: ['generic multi-region runner', null, null],
|
|
77
|
+
basicFluidSolver: ['base fluid solver module', null, null],
|
|
78
|
+
twoPhaseSolver: ['two-phase base', null, 2],
|
|
79
|
+
// legacy solvers
|
|
80
|
+
icoFoam: ['incompressible single-phase', false, 1],
|
|
81
|
+
simpleFoam: ['incompressible single-phase', false, 1],
|
|
82
|
+
pisoFoam: ['incompressible single-phase', false, 1],
|
|
83
|
+
pimpleFoam: ['incompressible single-phase', false, 1],
|
|
84
|
+
laplacianFoam: ['scalar transport (incompressible)', false, 1],
|
|
85
|
+
porousSimpleFoam: ['incompressible porous', false, 1],
|
|
86
|
+
rhoPorousSimpleFoam: ['compressible porous', true, 1],
|
|
87
|
+
shallowWaterFoam: ['shallow water', false, 1],
|
|
88
|
+
adjointShapeOptimisationFoam: ['incompressible adjoint', false, 1],
|
|
89
|
+
PDRFoam: ['premixed combustion (PDR)', true, 1],
|
|
90
|
+
mhdFoam: ['magnetohydrodynamics', false, 1],
|
|
91
|
+
electrostaticFoam: ['electrostatics', false, 1],
|
|
92
|
+
magneticFoam: ['magnetostatics', false, 1],
|
|
93
|
+
dsmcFoam: ['DSMC (rarefied gas)', true, 1],
|
|
94
|
+
mdFoam: ['molecular dynamics', null, 1],
|
|
95
|
+
mdEquilibrationFoam: ['molecular dynamics (equilibration)', null, 1],
|
|
96
|
+
financialFoam: ['financial (not CFD)', null, 1],
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function classifySolver(name) {
|
|
100
|
+
const sm = SOLVER_MAP[name]
|
|
101
|
+
if (sm) return { governing: sm[0], compressible: sm[1], phases: sm[2] }
|
|
102
|
+
if (/^rho/.test(name)) return { governing: 'compressible single-phase', compressible: true, phases: 1 }
|
|
103
|
+
if (/VoF/i.test(name) || /^inter/.test(name)) return { governing: 'VOF two-phase', compressible: null, phases: 2 }
|
|
104
|
+
if (/(twoPhaseEuler|multiphaseEuler)/.test(name)) return { governing: 'Euler-Euler multiphase', compressible: null, phases: 2 }
|
|
105
|
+
if (/buoyant/.test(name)) return { governing: 'buoyant (T-coupled)', compressible: null, phases: 1 }
|
|
106
|
+
if (/reacting|combustion|Xi/i.test(name)) return { governing: 'reacting/combustion', compressible: true, phases: 1 }
|
|
107
|
+
return { governing: null, compressible: null, phases: null }
|
|
108
|
+
}
|