@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/lib/runtime.js ADDED
@@ -0,0 +1,580 @@
1
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs'
2
+ import { dirname, isAbsolute, join, resolve, sep } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { execFile, spawn } from 'node:child_process'
5
+
6
+ export const PLUGIN_NAME = '@yakovlev-i-a/dsh-openfoam-workbench'
7
+
8
+ export const PLUGIN_VERSION = (() => {
9
+ try {
10
+ return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version || 'unknown'
11
+ } catch {
12
+ return 'unknown'
13
+ }
14
+ })()
15
+
16
+ export const pluginInfo = () => ({ name: PLUGIN_NAME, version: PLUGIN_VERSION })
17
+
18
+ // The always-on core prompt lives in CORE.md, one file, read at runtime.
19
+
20
+ export const DEFAULTS = {
21
+ foamRoot: '',
22
+ openfoamBash: '',
23
+ foamRoots: {},
24
+ foamBashs: {},
25
+ defaultDistribution: '',
26
+ paraviewExe: '',
27
+ paraviewPython: '',
28
+ pythonPath: '',
29
+ caseRoots: [],
30
+ extraCommands: [],
31
+ corePath: '',
32
+ logTailBytes: 4 * 1024 * 1024,
33
+ scaleAskAbove: 0.1,
34
+ runsDir: '',
35
+ writeMode: 'impact',
36
+ enforceToolRouting: 'warn',
37
+ escalationAuthority: 'auto',
38
+ language: '',
39
+ }
40
+
41
+ export function readText(p) {
42
+ try { return readFileSync(p, 'utf8') } catch { return null }
43
+ }
44
+
45
+ /**
46
+ * Read at most `maxBytes` from the end of a log (aligned to a line start).
47
+ * Production logs reach gigabytes; every verdict only needs the last steps plus
48
+ * the tail markers, so scanning the whole file is wasted time and memory.
49
+ */
50
+ export function readLogTail(filePath, maxBytes = 4 * 1024 * 1024) {
51
+ try {
52
+ const st = statSync(filePath)
53
+ if (st.size <= maxBytes) return { text: readFileSync(filePath, 'utf8'), truncated: false, bytes: st.size }
54
+ const fd = openSync(filePath, 'r')
55
+ try {
56
+ const buf = Buffer.alloc(maxBytes)
57
+ readSync(fd, buf, 0, maxBytes, st.size - maxBytes)
58
+ let text = buf.toString('utf8')
59
+ const nl = text.indexOf('\n')
60
+ if (nl >= 0) text = text.slice(nl + 1)
61
+ return { text, truncated: true, bytes: st.size, scannedBytes: maxBytes }
62
+ } finally {
63
+ closeSync(fd)
64
+ }
65
+ } catch {
66
+ return { text: readText(filePath), truncated: false, bytes: 0 }
67
+ }
68
+ }
69
+
70
+ // --- shell execution ---------------------------------------------------------
71
+ // Every OpenFOAM call goes through a *static* script: the bashrc, the working
72
+ // directory, the log path and the command arrive as positional parameters, so a
73
+ // path containing quotes, $(), backticks or a newline can never become shell
74
+ // code. Only whitelisted commands reach runFoam (see commandAllowed).
75
+ export const FOAM_RUN_SCRIPT = [
76
+ 'b="$1"; d="$2"; shift 2; cmd=("$@")',
77
+ // Clear the positional parameters before sourcing: OpenFOAM's bashrc forwards
78
+ // "$@" to etc/config.sh/setup, and a non-empty list makes that path hang.
79
+ 'set --',
80
+ 'source "$b" >/dev/null 2>&1 || { printf "%s\\n" "openfoam-workbench: cannot source $b" >&2; exit 97; }',
81
+ 'cd "$d" || { printf "%s\\n" "openfoam-workbench: cannot cd $d" >&2; exit 98; }',
82
+ 'exec "${cmd[@]}"',
83
+ ].join('\n')
84
+
85
+ export const FOAM_LOG_SCRIPT = [
86
+ 'b="$1"; d="$2"; l="$3"; shift 3; cmd=("$@")',
87
+ 'set --',
88
+ 'source "$b" >/dev/null 2>&1 || { printf "%s\\n" "openfoam-workbench: cannot source $b" >&2; exit 97; }',
89
+ 'cd "$d" || { printf "%s\\n" "openfoam-workbench: cannot cd $d" >&2; exit 98; }',
90
+ 'exec "${cmd[@]}" >"$l" 2>&1',
91
+ ].join('\n')
92
+
93
+ /** Run one OpenFOAM command (argv array) with the environment sourced. */
94
+ export function runFoam(argv, { bashrc = '', dir = process.cwd(), signal, timeoutMs = 600000 } = {}) {
95
+ const args = Array.isArray(argv) ? argv : [String(argv)]
96
+ return run('bash', ['-lc', FOAM_RUN_SCRIPT, 'bash', String(bashrc), String(dir), ...args.map(String)], { signal, timeoutMs })
97
+ }
98
+
99
+ /** Spawn one OpenFOAM command with its output redirected to `logPath`. */
100
+ export function spawnFoamLog(argv, { bashrc = '', dir = process.cwd(), logPath = '' } = {}) {
101
+ const args = Array.isArray(argv) ? argv : [String(argv)]
102
+ return spawn('bash', ['-lc', FOAM_LOG_SCRIPT, 'bash', String(bashrc), String(dir), String(logPath), ...args.map(String)], {
103
+ detached: true,
104
+ stdio: 'ignore',
105
+ })
106
+ }
107
+
108
+ /** Probe the sourced environment with a static script (no interpolation). */
109
+ export function probeBashrc(bashrc, script, { timeoutMs = 60000 } = {}) {
110
+ const wrapped = 'b="$1"; s="$2"; set --; source "$b" >/dev/null 2>&1 || exit 97; eval "$s"'
111
+ return run('bash', ['-lc', wrapped, 'bash', String(bashrc), String(script)], { timeoutMs })
112
+ }
113
+
114
+ export function run(cmd, args, { signal, timeoutMs = 30000 } = {}) {
115
+ return new Promise((res) => {
116
+ let settled = false
117
+ const done = (v) => { if (!settled) { settled = true; res(v) } }
118
+ let child
119
+ try {
120
+ child = execFile(cmd, args, { timeout: timeoutMs, signal, maxBuffer: 4 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }, (err, stdout, stderr) => {
121
+ done({
122
+ ok: !err,
123
+ code: err && typeof err.code === 'number' ? err.code : 0,
124
+ stdout: stdout || '',
125
+ stderr: stderr || '',
126
+ error: err ? String((err && err.message) || err) : null,
127
+ killed: !!(err && err.killed),
128
+ signal: err && err.signal ? String(err.signal) : null,
129
+ })
130
+ })
131
+ } catch (e) {
132
+ done({ ok: false, code: -1, stdout: '', stderr: '', error: String((e && e.message) || e) })
133
+ return
134
+ }
135
+ child.on('error', (e) => done({ ok: false, code: -1, stdout: '', stderr: '', error: String((e && e.message) || e) }))
136
+ })
137
+ }
138
+
139
+ export function stripComments(text) {
140
+ return text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')
141
+ }
142
+
143
+ export function dictEntry(text, key) {
144
+ const re = new RegExp('\\b' + key + '\\b\\s+([^;]+);')
145
+ const m = stripComments(text).match(re)
146
+ return m ? m[1].trim() : null
147
+ }
148
+
149
+ /** Path plus how it was resolved, so an answer can trace itself (K2). */
150
+ export function resolveCaseInfo(cfg, p) {
151
+ if (isAbsolute(String(p || ''))) return { path: p, resolvedFrom: { kind: 'absolute', input: p } }
152
+ const roots = Array.isArray(cfg.caseRoots) && cfg.caseRoots.length ? cfg.caseRoots : [process.cwd()]
153
+ const root = roots[0]
154
+ return {
155
+ path: resolve(root, String(p || '')),
156
+ resolvedFrom: {
157
+ kind: Array.isArray(cfg.caseRoots) && cfg.caseRoots.length ? 'caseRoot' : 'cwd',
158
+ root,
159
+ input: p,
160
+ },
161
+ }
162
+ }
163
+
164
+ export function resolveCase(cfg, p) {
165
+ if (!p) return ''
166
+ if (isAbsolute(p)) return p
167
+ const roots = Array.isArray(cfg.caseRoots) && cfg.caseRoots.length ? cfg.caseRoots : [process.cwd()]
168
+ return resolve(roots[0], p)
169
+ }
170
+
171
+ export function inferCaseDir(cfg, logPath, explicit) {
172
+ if (explicit) {
173
+ const d = resolveCase(cfg, explicit)
174
+ if (d && existsSync(join(d, 'system', 'controlDict'))) return d
175
+ }
176
+ let d = dirname(logPath)
177
+ for (let i = 0; i < 4 && d && d !== dirname(d); i += 1) {
178
+ if (existsSync(join(d, 'system', 'controlDict'))) return d
179
+ d = dirname(d)
180
+ }
181
+ return null
182
+ }
183
+
184
+ export function topLevelKeys(text) {
185
+ const keys = []
186
+ let depth = 0
187
+ for (const line of String(text).split('\n')) {
188
+ const t = line.trim()
189
+ const m = depth === 0 ? /^(\w+)\s/.exec(t) : null
190
+ if (m && !/^(FoamFile|include|includeEtc|libs)$/.test(m[1])) keys.push(m[1])
191
+ depth += (line.match(/{/g) || []).length - (line.match(/}/g) || []).length
192
+ }
193
+ return [...new Set(keys)]
194
+ }
195
+
196
+ export function dirSize(dir) {
197
+ let total = 0
198
+ const stack = [dir]
199
+ while (stack.length) {
200
+ const d = stack.pop()
201
+ let entries = []
202
+ try { entries = readdirSync(d, { withFileTypes: true }) } catch { continue }
203
+ for (const e of entries) {
204
+ const full = join(d, e.name)
205
+ if (e.isDirectory()) stack.push(full)
206
+ else { try { total += statSync(full).size } catch {} }
207
+ }
208
+ }
209
+ return total
210
+ }
211
+
212
+ /** A registry log lives in <caseRoots[0]>/.openfoam-runs/<id>.log; its sibling
213
+ * <id>.json carries casePath, so progress works without an explicit casePath. */
214
+ export function caseFromRunRecord(logPath) {
215
+ try {
216
+ const rec = JSON.parse(readFileSync(logPath.replace(/\.log$/, '.json'), 'utf8'))
217
+ if (rec && typeof rec.casePath === 'string' && existsSync(join(rec.casePath, 'system', 'controlDict'))) return rec.casePath
218
+ } catch {}
219
+ return null
220
+ }
221
+
222
+ export function rootFor(cfg, dist) {
223
+ const d = dist || cfg.defaultDistribution
224
+ if (d && cfg.foamRoots && cfg.foamRoots[d]) return String(cfg.foamRoots[d])
225
+ if (cfg.foamRoot) return String(cfg.foamRoot)
226
+ if (cfg.foamRoots) { const k = Object.keys(cfg.foamRoots)[0]; if (k) return String(cfg.foamRoots[k]) }
227
+ return ''
228
+ }
229
+
230
+ export function bashrcFor(cfg, dist) {
231
+ const d = dist || cfg.defaultDistribution
232
+ if (d && cfg.foamBashs && cfg.foamBashs[d]) return String(cfg.foamBashs[d])
233
+ const root = rootFor(cfg, dist)
234
+ if (!d && cfg.openfoamBash) return String(cfg.openfoamBash)
235
+ return root ? join(root, 'etc/bashrc') : ''
236
+ }
237
+
238
+ export function bashrcOf(cfg) {
239
+ return bashrcFor(cfg, '')
240
+ }
241
+
242
+ /**
243
+ * The log argument accepts both spellings: `log_path` (run tools) and `path`
244
+ * (residual_series). A wrong name must not degrade into an empty path.
245
+ */
246
+ export function pickLogPath(args = {}) {
247
+ for (const key of ['log_path', 'path']) {
248
+ const value = args ? args[key] : undefined
249
+ if (typeof value === 'string' && value.trim()) return { path: value.trim(), key }
250
+ }
251
+ const keys = Object.keys(args || {})
252
+ return {
253
+ error: `log_path (alias: path) is required — accepted names: log_path, path; got: ${keys.length ? keys.join(', ') : '(no arguments)'}`,
254
+ }
255
+ }
256
+
257
+ /** Hint appended to "case not found": which roots were searched. */
258
+ export function caseLookupHint(cfg) {
259
+ const roots = Array.isArray(cfg.caseRoots) && cfg.caseRoots.length ? cfg.caseRoots : [process.cwd()]
260
+ return ` (searched caseRoots: ${roots.join(', ')}; relative paths resolve against caseRoots, not the session cwd)`
261
+ }
262
+
263
+ export function validateConfig(cfg) {
264
+ const warnings = []
265
+ if (cfg.foamRoot && !existsSync(cfg.foamRoot)) warnings.push('foamRoot does not exist: ' + cfg.foamRoot)
266
+ for (const [k, v] of Object.entries(cfg.foamRoots || {})) {
267
+ if (v && !existsSync(v)) warnings.push('foamRoots.' + k + ' does not exist: ' + v)
268
+ }
269
+ const bash = bashrcOf(cfg)
270
+ if (bash && !existsSync(bash)) warnings.push('openfoamBash does not exist: ' + bash)
271
+ if (cfg.pythonPath && !existsSync(cfg.pythonPath)) warnings.push('pythonPath does not exist: ' + cfg.pythonPath)
272
+ if (cfg.paraviewPython && !existsSync(cfg.paraviewPython)) warnings.push('paraviewPython does not exist: ' + cfg.paraviewPython)
273
+ if (cfg.caseRoots && !Array.isArray(cfg.caseRoots)) warnings.push('caseRoots must be an array of paths')
274
+ return warnings
275
+ }
276
+
277
+ export function sourceRoots(cfg) {
278
+ const roots = []
279
+ if (Array.isArray(cfg.allowedReadRoots)) roots.push(...cfg.allowedReadRoots)
280
+ const foamRoot = rootFor(cfg, '')
281
+ if (foamRoot) {
282
+ roots.push(join(foamRoot, 'src'), join(foamRoot, 'applications'), join(foamRoot, 'etc', 'codeTemplates'))
283
+ }
284
+ return roots
285
+ }
286
+
287
+ export function resolveSource(cfg, p) {
288
+ const roots = sourceRoots(cfg).map((r) => resolve(r))
289
+ if (!roots.length) return { ok: false, error: 'no source roots configured (set foamRoot)' }
290
+ const abs = isAbsolute(p) ? resolve(p) : resolve(roots[0], p)
291
+ const ok = roots.some((r) => abs === r || abs.startsWith(r + sep))
292
+ return ok ? { ok: true, path: abs } : { ok: false, error: `outside allowed source roots: ${abs}` }
293
+ }
294
+
295
+ export function walk(root, onFile, maxFiles = 50000) {
296
+ let n = 0
297
+ const stack = [root]
298
+ while (stack.length && n < maxFiles) {
299
+ const d = stack.pop()
300
+ let entries
301
+ try { entries = readdirSync(d, { withFileTypes: true }) } catch { continue }
302
+ for (const e of entries) {
303
+ if (e.name === '.' || e.name === '..') continue
304
+ const p = join(d, e.name)
305
+ if (e.isDirectory()) stack.push(p)
306
+ else if (e.isFile()) {
307
+ n++
308
+ if (onFile(p) === false) return
309
+ }
310
+ }
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Count time steps over the whole log without loading it: a solver log can be
316
+ * hundreds of megabytes, while the verifiers read only the tail. Costs ~0.2 s
317
+ * per 100 MB on a warm page cache; the budget bounds a cold network mount.
318
+ */
319
+ export function countTimeSteps(filePath, { maxBytes = 8 * 1024 * 1024 * 1024, budgetMs = 4000 } = {}) {
320
+ let fd
321
+ try { fd = openSync(filePath, 'r') } catch { return { count: 0, bytes: 0, truncated: false, budgetExceeded: false } }
322
+ const started = Date.now()
323
+ const chunk = Buffer.alloc(4 * 1024 * 1024)
324
+ let count = 0
325
+ let bytes = 0
326
+ let carry = ''
327
+ let budgetExceeded = false
328
+ try {
329
+ for (;;) {
330
+ if (bytes >= maxBytes || Date.now() - started > budgetMs) { budgetExceeded = true; break }
331
+ let read = 0
332
+ try { read = readSync(fd, chunk, 0, chunk.length, bytes) } catch { break }
333
+ if (!read) break
334
+ const text = carry + chunk.toString('utf8', 0, read)
335
+ // A line may be split across chunks: keep the last partial line for the next round.
336
+ const cut = text.lastIndexOf('\n')
337
+ const body = cut >= 0 ? text.slice(0, cut + 1) : ''
338
+ carry = cut >= 0 ? text.slice(cut + 1) : text
339
+ count += (body.match(/^Time\s*=/gm) || []).length
340
+ bytes += read
341
+ if (cut < 0) continue
342
+ }
343
+ if (carry) count += (/^Time\s*=/.test(carry) ? 1 : 0)
344
+ } finally {
345
+ try { closeSync(fd) } catch {}
346
+ }
347
+ return { count, bytes, truncated: false, budgetExceeded }
348
+ }
349
+
350
+ export const HERE = fileURLToPath(new URL('.', import.meta.url))
351
+
352
+ export const STALL_MS = 10 * 60 * 1000
353
+
354
+ // --- durable solver runs -------------------------------------------------
355
+ // Each case keeps its own registry next to itself (`<case>/.openfoam-runs`), so
356
+ // a run never lands in an unrelated project. `runsDir` pins one directory when a
357
+ // user wants a single place; discovery scans the case roots for case-local
358
+ // registries (bounded depth) and remembers every directory it has written to.
359
+
360
+ const RUN_DIR_BY_ID = new Map()
361
+
362
+ /** Registry directory for a run of `caseDir` (falls back to the first case root). */
363
+ export function runsDirOf(cfg, caseDir) {
364
+ if (cfg.runsDir) return cfg.runsDir
365
+ if (caseDir) return join(caseDir, '.openfoam-runs')
366
+ const root = Array.isArray(cfg.caseRoots) && cfg.caseRoots.length ? cfg.caseRoots[0] : process.cwd()
367
+ return join(root, '.openfoam-runs')
368
+ }
369
+
370
+ function collectRunsDirs(dir, depth, out, budget) {
371
+ if (depth < 0 || budget.left <= 0) return
372
+ let entries
373
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
374
+ for (const e of entries) {
375
+ if (!e.isDirectory()) continue
376
+ if (e.name === '.openfoam-runs') { out.add(join(dir, e.name)); continue }
377
+ if (e.name.startsWith('.') || e.name === 'node_modules') continue
378
+ budget.left -= 1
379
+ if (depth > 0) collectRunsDirs(join(dir, e.name), depth - 1, out, budget)
380
+ }
381
+ }
382
+
383
+ /** Every registry directory this configuration can own. */
384
+ export function runsDirsOf(cfg) {
385
+ const out = new Set(RUN_DIR_BY_ID.values())
386
+ if (cfg.runsDir) { out.add(cfg.runsDir); return [...out] }
387
+ const roots = [...(Array.isArray(cfg.caseRoots) ? cfg.caseRoots : []), process.cwd()]
388
+ const budget = { left: 4000 }
389
+ for (const root of roots) {
390
+ out.add(join(root, '.openfoam-runs'))
391
+ collectRunsDirs(root, 3, out, budget)
392
+ }
393
+ return [...out]
394
+ }
395
+
396
+ /** Locate the directory that holds run `id`. */
397
+ export function findRunDir(cfg, id) {
398
+ const cached = RUN_DIR_BY_ID.get(id)
399
+ if (cached) return cached
400
+ for (const dir of runsDirsOf(cfg)) {
401
+ try {
402
+ if (existsSync(join(dir, id + '.json'))) { RUN_DIR_BY_ID.set(id, dir); return dir }
403
+ } catch {}
404
+ }
405
+ return null
406
+ }
407
+
408
+ /** Forget cached run locations (tests and long-lived hosts after a registry move). */
409
+ export function resetRunDirCache() { RUN_DIR_BY_ID.clear() }
410
+
411
+ export function ensureRunsDir(cfg, caseDir) {
412
+ const d = runsDirOf(cfg, caseDir)
413
+ mkdirSync(d, { recursive: true })
414
+ return d
415
+ }
416
+
417
+ export function runJsonPathIn(dir, id) { return join(dir, id + '.json') }
418
+ export function runLogPathIn(dir, id) { return join(dir, id + '.log') }
419
+
420
+ export function runJsonPath(cfg, id) {
421
+ const dir = findRunDir(cfg, id)
422
+ return dir ? runJsonPathIn(dir, id) : runJsonPathIn(runsDirOf(cfg), id)
423
+ }
424
+
425
+ export function runLogPath(cfg, id) {
426
+ const dir = findRunDir(cfg, id)
427
+ return dir ? runLogPathIn(dir, id) : runLogPathIn(runsDirOf(cfg), id)
428
+ }
429
+
430
+ export function readRun(cfg, id) {
431
+ const dir = findRunDir(cfg, id)
432
+ if (!dir) return null
433
+ try { return JSON.parse(readFileSync(join(dir, id + '.json'), 'utf8')) } catch { return null }
434
+ }
435
+
436
+ export function writeRun(cfg, run) {
437
+ const dir = run.runsDir || RUN_DIR_BY_ID.get(run.id) || runsDirOf(cfg, run.casePath)
438
+ mkdirSync(dir, { recursive: true })
439
+ run.runsDir = dir
440
+ const p = join(dir, run.id + '.json')
441
+ const tmp = p + '.tmp'
442
+ writeFileSync(tmp, JSON.stringify(run, null, 2))
443
+ renameSync(tmp, p)
444
+ RUN_DIR_BY_ID.set(run.id, dir)
445
+ }
446
+
447
+ export function listRunIds(cfg) {
448
+ const ids = new Set()
449
+ for (const dir of runsDirsOf(cfg)) {
450
+ try {
451
+ for (const f of readdirSync(dir)) if (f.endsWith('.json')) ids.add(f.slice(0, -5))
452
+ } catch {}
453
+ }
454
+ return [...ids]
455
+ }
456
+
457
+ export function pidAlive(pid) {
458
+ if (!pid) return false
459
+ try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' }
460
+ }
461
+
462
+ export function logTailFile(cfg, id, n = 4000) {
463
+ const r = readLogTail(runLogPath(cfg, id), Math.max(n, 65536))
464
+ return r.text ? r.text.slice(-n) : ''
465
+ }
466
+
467
+ export function logMtime(cfg, id) {
468
+ try { return statSync(runLogPath(cfg, id)).mtimeMs } catch { return 0 }
469
+ }
470
+
471
+ export function logFinished(cfg, id) {
472
+ const t = logTailFile(cfg, id, 16000)
473
+ const lines = t.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)
474
+ return lines.length > 0 && lines[lines.length - 1] === 'End'
475
+ }
476
+
477
+ // Reconcile the on-disk registry after a restart: a run whose pid is gone, or whose
478
+ // log reached `End` while we were not watching, is settled here.
479
+
480
+ export function reconcileAll(cfg) {
481
+ for (const id of listRunIds(cfg)) {
482
+ const r = readRun(cfg, id)
483
+ if (!r || r.status !== 'running') continue
484
+ if (logFinished(cfg, id)) {
485
+ r.status = 'success'
486
+ r.endedAt = logMtime(cfg, id) || Date.now()
487
+ } else if (!pidAlive(r.pid)) {
488
+ r.status = 'interrupted'
489
+ r.endedAt = logMtime(cfg, id) || Date.now()
490
+ }
491
+ try { writeRun(cfg, r) } catch {}
492
+ }
493
+ }
494
+
495
+ export const escapeRe = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
496
+
497
+ export function startSolverRun(cfg, dir, argvOrCommand, bash) {
498
+ const runsDir = ensureRunsDir(cfg, dir)
499
+ const id = 'run' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6)
500
+ const log = runLogPathIn(runsDir, id)
501
+ const argv = Array.isArray(argvOrCommand)
502
+ ? argvOrCommand.map(String)
503
+ : String(argvOrCommand).split(/\s+/).filter(Boolean)
504
+ const child = spawnFoamLog(argv, { bashrc: bash, dir, logPath: log })
505
+ const run = { id, casePath: dir, runsDir, command: argv.join(' '), argv, pid: child.pid, startedAt: Date.now(), status: 'running', log }
506
+ writeRun(cfg, run)
507
+ child.unref()
508
+ return run
509
+ }
510
+
511
+ export function runSnapshot(cfg, id) {
512
+ const r = readRun(cfg, id)
513
+ if (!r) return null
514
+ let status = r.status
515
+ const alive = pidAlive(r.pid)
516
+ const tail = logTailFile(cfg, id)
517
+ if (status === 'running') {
518
+ if (logFinished(cfg, id)) { status = 'success'; r.endedAt = logMtime(cfg, id) || Date.now() }
519
+ else if (!alive) { status = 'interrupted'; r.endedAt = logMtime(cfg, id) || Date.now() }
520
+ else {
521
+ const mtime = logMtime(cfg, id)
522
+ if (mtime && Date.now() - mtime > STALL_MS) status = 'stalled'
523
+ }
524
+ } else if (status === 'stopping') {
525
+ if (!alive) { status = 'stopped'; r.endedAt = Date.now() }
526
+ }
527
+ if (status !== r.status) { r.status = status; try { writeRun(cfg, r) } catch {} }
528
+ const times = [...tail.matchAll(/^Time\s*=\s*([0-9.eE+-]+)/gm)].map((x) => x[1])
529
+ const endedAt = status === 'running' || status === 'stalled' ? Date.now() : (r.endedAt || Date.now())
530
+ return {
531
+ runId: id,
532
+ casePath: r.casePath,
533
+ command: r.command,
534
+ status,
535
+ running: status === 'running' || status === 'stalled',
536
+ pid: r.pid,
537
+ startedAt: r.startedAt,
538
+ durationMs: endedAt - r.startedAt,
539
+ lastTime: times.length ? times[times.length - 1] : null,
540
+ logTail: tail,
541
+ }
542
+ }
543
+
544
+ export function stopRun(cfg, id) {
545
+ const r = readRun(cfg, id)
546
+ if (!r) return { ok: false, error: 'no such run: ' + id }
547
+ if (!pidAlive(r.pid)) {
548
+ const snap = runSnapshot(cfg, id)
549
+ return { ok: true, runId: id, alreadyEnded: true, status: snap && snap.status }
550
+ }
551
+ try { process.kill(r.pid, 'SIGTERM') } catch {}
552
+ setTimeout(() => { try { process.kill(r.pid, 'SIGKILL') } catch {} }, 3000)
553
+ r.status = 'stopping'
554
+ try { writeRun(cfg, r) } catch {}
555
+ return { ok: true, runId: id, stopped: true }
556
+ }
557
+
558
+ // --- geometry helpers ---
559
+
560
+ export function experienceDirOf(cfg) {
561
+ return cfg.experienceDir || join(HERE, '..', '.experience')
562
+ }
563
+
564
+ export function ensureExpDir(cfg) {
565
+ const d = experienceDirOf(cfg)
566
+ mkdirSync(d, { recursive: true })
567
+ return d
568
+ }
569
+
570
+ /** Text-only tool output. */
571
+ export function textOut(v) {
572
+ if (typeof v === 'string') return [{ type: 'text', text: v }]
573
+ const pretty = JSON.stringify(v, null, 2)
574
+ if (pretty.length <= 8000) return [{ type: 'text', text: pretty }]
575
+ // Large payloads (case lists, tutorials, run lists) are token bombs: keep the
576
+ // JSON valid-looking by compacting first, then cut with an explicit note.
577
+ const compact = JSON.stringify(v)
578
+ if (compact.length <= 8000) return [{ type: 'text', text: compact }]
579
+ return [{ type: 'text', text: compact.slice(0, 8000) + `\n... (truncated: ${compact.length} chars; narrow the query)` }]
580
+ }