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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +683 -0
  2. package/CORE.md +50 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +29 -0
  5. package/README.md +373 -2
  6. package/client.js +48 -0
  7. package/cordis.patch.yml +18 -0
  8. package/icon.png +0 -0
  9. package/lib/buildlib.js +42 -0
  10. package/lib/caselib.js +212 -0
  11. package/lib/core.js +47 -0
  12. package/lib/discover.js +139 -0
  13. package/lib/escalations.js +92 -0
  14. package/lib/explib.js +149 -0
  15. package/lib/impact.js +55 -0
  16. package/lib/index.js +109 -0
  17. package/lib/knowledge.js +108 -0
  18. package/lib/meshlib.js +375 -0
  19. package/lib/needs-input.js +32 -0
  20. package/lib/of-case.js +485 -0
  21. package/lib/of-engine.js +1061 -0
  22. package/lib/paperlib.js +200 -0
  23. package/lib/presentation.js +365 -0
  24. package/lib/registry.js +142 -0
  25. package/lib/routing-guard.js +126 -0
  26. package/lib/runtime.js +580 -0
  27. package/lib/scaffold-cht.js +318 -0
  28. package/lib/scaffold-compressible.js +171 -0
  29. package/lib/scaffold.js +355 -0
  30. package/lib/settings-schema.js +86 -0
  31. package/lib/skills.js +53 -0
  32. package/lib/tools/build.js +90 -0
  33. package/lib/tools/case.js +1082 -0
  34. package/lib/tools/env.js +592 -0
  35. package/lib/tools/experience.js +165 -0
  36. package/lib/tools/mesh.js +408 -0
  37. package/lib/tools/meta.js +95 -0
  38. package/lib/tools/papers.js +105 -0
  39. package/lib/tools/render.js +94 -0
  40. package/lib/tools/run.js +331 -0
  41. package/lib/versions.js +133 -0
  42. package/licenses/dsh-openfoam-doctor-MIT.txt +21 -0
  43. package/locale/en.json +6 -0
  44. package/locale/ru.json +6 -0
  45. package/package.json +44 -4
  46. package/skills/openfoam-analyze/SKILL.md +27 -0
  47. package/skills/openfoam-case-builder/SKILL.md +61 -0
  48. package/skills/openfoam-cht/SKILL.md +83 -0
  49. package/skills/openfoam-code-modify/SKILL.md +32 -0
  50. package/skills/openfoam-mesh-independence/SKILL.md +55 -0
  51. package/skills/openfoam-meshing/SKILL.md +30 -0
  52. package/skills/openfoam-paper-reproduction/SKILL.md +36 -0
  53. package/skills/openfoam-self-evolution/SKILL.md +21 -0
  54. package/skills/openfoam-solver-development/SKILL.md +61 -0
  55. package/skills/openfoam-stats/SKILL.md +46 -0
  56. package/skills/openfoam-viz/SKILL.md +35 -0
package/lib/of-case.js ADDED
@@ -0,0 +1,485 @@
1
+ // Multi-region case model for the OpenFOAM Workbench.
2
+ //
3
+ // The plugin's original case model assumed one polyMesh at the case root, which
4
+ // is true for single-region cases and false for every CHT / multi-region setup
5
+ // (foamMultiRun, chtMultiRegionFoam, system/<region>/...). These helpers answer
6
+ // the three questions every tool needs: which regions exist, where a dictionary
7
+ // really lives, and what a command is allowed to run.
8
+ import { cpSync, existsSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
9
+ import { basename, dirname, join, resolve, sep } from 'node:path'
10
+ import { parseRunLog } from './of-engine.js'
11
+
12
+ function readText(p) {
13
+ try { return readFileSync(p, 'utf8') } catch { return null }
14
+ }
15
+
16
+ function stripComments(text) {
17
+ return text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')
18
+ }
19
+
20
+ /**
21
+ * Ensure the case carries the PaRaView entry file: `<case-dir-name>.foam`.
22
+ * No compatibility shims: the convention is one file named after the case.
23
+ */
24
+ export function ensureFoamFile(caseDir) {
25
+ const name = basename(caseDir)
26
+ const target = join(caseDir, name + '.foam')
27
+ const existed = existsSync(target)
28
+ if (!existed) {
29
+ try { writeFileSync(target, '') } catch (e) { return { ok: false, error: 'cannot write ' + target + ': ' + (e && e.message) } }
30
+ }
31
+ return { ok: true, path: target, name: name + '.foam', created: !existed }
32
+ }
33
+
34
+ /**
35
+ * The `.foam` file a case is opened through. Strict convention: only
36
+ * `<case-dir-name>.foam` counts; `case.foam` and other names are not accepted.
37
+ */
38
+ export function findFoamFile(caseDir) {
39
+ const target = join(caseDir, basename(caseDir) + '.foam')
40
+ return existsSync(target) ? target : null
41
+ }
42
+
43
+ /**
44
+ * Axis-aligned bounding box of an existing case: region/root polyMesh/points when
45
+ * the file is small enough, otherwise the blockMeshDict vertices.
46
+ */
47
+ export function caseBBox(caseDir, maxBytes = 32 * 1024 * 1024) {
48
+ const candidates = []
49
+ const rootPoints = join(caseDir, 'constant', 'polyMesh', 'points')
50
+ if (existsSync(rootPoints)) candidates.push(rootPoints)
51
+ for (const r of caseRegions(caseDir)) {
52
+ const p = join(caseDir, 'constant', r, 'polyMesh', 'points')
53
+ if (existsSync(p)) candidates.push(p)
54
+ }
55
+ for (const p of candidates) {
56
+ try {
57
+ if (statSync(p).size > maxBytes) continue
58
+ const text = readFileSync(p, 'utf8')
59
+ if (/^\s*format\s+binary/m.test(text.slice(0, 400))) continue
60
+ // coordinates live after the leading count + '(' : skip the FoamFile header
61
+ const body = text.slice(Math.max(0, text.indexOf('(')))
62
+ const nums = body.match(/-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?/g)
63
+ if (!nums || nums.length < 6) continue
64
+ const mn = [Infinity, Infinity, Infinity]
65
+ const mx = [-Infinity, -Infinity, -Infinity]
66
+ const take = nums.slice(0, Math.floor(nums.length / 3) * 3)
67
+ for (let i = 0; i + 2 < take.length; i += 3) {
68
+ for (let k = 0; k < 3; k += 1) {
69
+ const v = Number(take[i + k])
70
+ if (!Number.isFinite(v)) continue
71
+ if (v < mn[k]) mn[k] = v
72
+ if (v > mx[k]) mx[k] = v
73
+ }
74
+ }
75
+ if (Number.isFinite(mn[0]) && Number.isFinite(mx[0])) {
76
+ const ext = [mx[0] - mn[0], mx[1] - mn[1], mx[2] - mn[2]]
77
+ return { ok: true, min: mn, max: mx, extent: ext, maxExtent: Math.max(...ext) }
78
+ }
79
+ } catch {}
80
+ }
81
+ const bm = readText(join(caseDir, 'system', 'blockMeshDict'))
82
+ if (bm) {
83
+ // Only the `vertices (...)` block holds coordinates: `hex (0 1 2 ...) (nx ny nz)`
84
+ // carries a resolution tuple that must not be read as a vertex, and `scale`
85
+ // multiplies every coordinate.
86
+ const stripped = stripComments(bm)
87
+ const vertBlock = /\bvertices\s*\(([\s\S]*?)\);/.exec(stripped)
88
+ const vertText = vertBlock ? vertBlock[1] : ''
89
+ const verts = [...vertText.matchAll(/\(\s*([-\d.eE+]+)\s+([-\d.eE+]+)\s+([-\d.eE+]+)\s*\)/g)].map((m) => [Number(m[1]), Number(m[2]), Number(m[3])])
90
+ const scaleMatch = /\bscale\s+([-\d.eE+]+)\s*;/.exec(stripped)
91
+ const scale = scaleMatch ? Number(scaleMatch[1]) : 1
92
+ const factor = Number.isFinite(scale) && scale !== 0 ? scale : 1
93
+ if (verts.length >= 2) {
94
+ const mn = [0, 1, 2].map((k) => Math.min(...verts.map((v) => v[k] * factor)))
95
+ const mx = [0, 1, 2].map((k) => Math.max(...verts.map((v) => v[k] * factor)))
96
+ const ext = [mx[0] - mn[0], mx[1] - mn[1], mx[2] - mn[2]]
97
+ return { ok: true, min: mn, max: mx, extent: ext, maxExtent: Math.max(...ext), source: 'blockMeshDict', scale: factor }
98
+ }
99
+ }
100
+ return { ok: false, error: 'no mesh points or blockMeshDict' }
101
+ }
102
+
103
+ /** Region names of a case, in declaration order. Empty for single-region cases. */
104
+ export function caseRegions(dir) {
105
+ const regions = []
106
+ const cd = readText(join(dir, 'system', 'controlDict'))
107
+ if (cd) {
108
+ const m = stripComments(cd).match(/regionSolvers\s*\{([\s\S]*?)\}/)
109
+ if (m) {
110
+ // the block may be written on one line, so scan every `region solver;` pair
111
+ for (const mm of m[1].matchAll(/(\w+)\s+(\w+)\s*;/g)) regions.push(mm[1])
112
+ }
113
+ }
114
+ if (!regions.length) {
115
+ // OpenFOAM.com groups MESH regions under solver regions in
116
+ // constant/regionProperties: fluid (bottomAir topAir) solid (heater leftSolid)
117
+ // The mesh regions (the parenthesised names) are what the tools address.
118
+ for (const names of Object.values(regionGroups(dir))) {
119
+ for (const n of names) if (!regions.includes(n)) regions.push(n)
120
+ }
121
+ }
122
+ if (!regions.length) {
123
+ try {
124
+ for (const e of readdirSync(join(dir, 'constant'), { withFileTypes: true })) {
125
+ if (!e.isDirectory()) continue
126
+ if (existsSync(join(dir, 'constant', e.name, 'polyMesh', 'boundary'))) regions.push(e.name)
127
+ }
128
+ } catch {}
129
+ }
130
+ return regions
131
+ }
132
+
133
+ /** region -> solver mapping from system/controlDict (empty when absent). */
134
+ export function regionSolvers(dir) {
135
+ const out = {}
136
+ const cd = readText(join(dir, 'system', 'controlDict'))
137
+ if (!cd) return out
138
+ const m = stripComments(cd).match(/regionSolvers\s*\{([\s\S]*?)\}/)
139
+ if (!m) return out
140
+ for (const mm of m[1].matchAll(/(\w+)\s+(\w+)\s*;/g)) out[mm[1]] = mm[2]
141
+ return out
142
+ }
143
+
144
+ /** Solver regions -> mesh regions from constant/regionProperties (OpenFOAM.com). */
145
+ export function regionGroups(dir) {
146
+ const out = {}
147
+ const rp = readText(join(dir, 'constant', 'regionProperties'))
148
+ if (!rp) return out
149
+ const blockText = stripComments(rp).match(/regions\s*\(([\s\S]*?)\)\s*;/)
150
+ if (!blockText) return out
151
+ for (const m of blockText[1].matchAll(/(\w+)\s*\(([^)]*)\)/g)) {
152
+ out[m[1]] = m[2].split(/\s+/).filter(Boolean)
153
+ }
154
+ return out
155
+ }
156
+
157
+ /**
158
+ * Restore the initial fields the way OpenFOAM's `restore0Dir` does: copy
159
+ * `0.orig/` to `0/` (serial) or to every `processor<N>/0/` (`-processor`).
160
+ * Com tutorials ship `0.orig/` instead of `0/`, so the plugin implements the
161
+ * helper itself — it is a shell function in OpenFOAM, not an executable.
162
+ */
163
+ export function restoreZeroDir(caseDir, { processor = false } = {}) {
164
+ const srcName = ['0.orig', '0_orig'].find((n) => existsSync(join(caseDir, n)))
165
+ if (!srcName) return { ok: false, error: 'neither 0.orig nor 0_orig found in ' + caseDir }
166
+ const src = join(caseDir, srcName)
167
+ const targets = []
168
+ if (processor) {
169
+ let entries = []
170
+ try { entries = readdirSync(caseDir, { withFileTypes: true }) } catch {}
171
+ for (const e of entries) if (e.isDirectory() && /^processor\d+$/.test(e.name)) targets.push(join(caseDir, e.name, '0'))
172
+ } else {
173
+ targets.push(join(caseDir, '0'))
174
+ }
175
+ if (!targets.length) return { ok: false, error: 'no processor* directories for restore0Dir -processor' }
176
+ for (const t of targets) {
177
+ rmSync(t, { recursive: true, force: true })
178
+ cpSync(src, t, { recursive: true })
179
+ }
180
+ return { ok: true, restored: targets.length, processor }
181
+ }
182
+
183
+
184
+ /** Dictionaries of one region: 0/<region> fields, system/<region> and constant/<region>. */
185
+ /**
186
+ * The directory that holds the initial fields. com cases ship `0.orig/`, and
187
+ * some user cases use `0_orig/` (the author of the BFER series does), so all
188
+ * three names are accepted everywhere.
189
+ */
190
+ export const ZERO_DIR_NAMES = ['0', '0.orig', '0_orig']
191
+
192
+ export function zeroDirOf(caseDir) {
193
+ for (const name of ZERO_DIR_NAMES) {
194
+ const dir = join(caseDir, name)
195
+ if (existsSync(dir)) return dir
196
+ }
197
+ return null
198
+ }
199
+
200
+ export function zeroDirName(caseDir) {
201
+ for (const name of ZERO_DIR_NAMES) if (existsSync(join(caseDir, name))) return name
202
+ return null
203
+ }
204
+
205
+ export function regionFiles(dir, region) {
206
+ const out = { fields: [], system: [], constant: [] }
207
+ const list = (sub) => {
208
+ try { return readdirSync(join(dir, sub, region)).filter((n) => !n.startsWith('.')).sort() } catch { return [] }
209
+ }
210
+ out.fields = list('0')
211
+ if (!out.fields.length) {
212
+ // com tutorials ship 0.orig/ and create 0/ via restore0Dir at run time
213
+ for (const alt of ['0.orig', '0_orig']) {
214
+ out.fields = list(alt)
215
+ if (out.fields.length) { out.fieldsFrom = alt; break }
216
+ }
217
+ }
218
+ out.system = list('system')
219
+ out.constant = list('constant')
220
+ return out
221
+ }
222
+
223
+ const CASE_ROOTS = new Set(['system', 'constant', 'postProcessing', 'dynamicCode'])
224
+
225
+ /**
226
+ * Resolve a dictionary path the way a human writes it.
227
+ * Accepts `fluid/fvSchemes`, `system/fluid/fvSchemes`, `constant/fluid/...`,
228
+ * `0/fluid/T`, and bare names (`fvSchemes`, `controlDict`). Never double-prefixes.
229
+ */
230
+ /**
231
+ * Resolve `rel` under `base` and refuse anything that escapes it. `..` segments
232
+ * are rejected outright, symlinks are resolved with realpath when the target
233
+ * exists, and the final path must stay inside the case directory.
234
+ */
235
+ export function containedPath(base, rel) {
236
+ const raw = String(rel || '').trim().replace(/\\/g, '/')
237
+ if (!raw) return { ok: false, error: 'empty path' }
238
+ if (raw.startsWith('/')) return { ok: false, error: 'absolute paths are not allowed here' }
239
+ if (raw.split('/').some((seg) => seg === '..')) return { ok: false, error: 'path traversal ("..") is not allowed' }
240
+ let realBase
241
+ try { realBase = realpathSync(base) } catch { realBase = resolve(base) }
242
+ const target = resolve(realBase, raw)
243
+ const inside = (p) => p === realBase || p.startsWith(realBase + sep)
244
+ if (!inside(target)) return { ok: false, error: 'path escapes the case directory' }
245
+ if (existsSync(target)) {
246
+ try {
247
+ const real = realpathSync(target)
248
+ if (!inside(real)) return { ok: false, error: 'path escapes the case directory through a symlink' }
249
+ return { ok: true, path: real }
250
+ } catch {
251
+ return { ok: false, error: 'cannot resolve: ' + target }
252
+ }
253
+ }
254
+ // The target may not exist yet (a new file): its parent must still be inside.
255
+ const parent = dirname(target)
256
+ if (!inside(parent)) return { ok: false, error: 'path escapes the case directory' }
257
+ return { ok: true, path: target }
258
+ }
259
+
260
+ export function normaliseDictPath(dir, file, region) {
261
+ const raw = String(file || '').trim().replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
262
+ const tried = []
263
+ const ok = (rel) => {
264
+ tried.push(rel)
265
+ const safe = containedPath(dir, rel)
266
+ if (!safe.ok) return false
267
+ return existsSync(safe.path)
268
+ }
269
+ if (!raw) return { ok: false, tried, error: 'empty file name' }
270
+ if (raw.split('/').some((seg) => seg === '..')) {
271
+ return { ok: false, tried, error: 'path traversal ("..") is not allowed', hint: 'pass a path inside the case (system/, constant/, 0/)' }
272
+ }
273
+ const segments = raw.split('/')
274
+ const head = segments[0]
275
+ const caseRelative = CASE_ROOTS.has(head) || /^\d/.test(head) || head === 'processor0'
276
+ if (caseRelative) {
277
+ if (ok(raw)) return { ok: true, rel: raw, tried }
278
+ // com tutorials keep the initial fields in 0.orig/ until restore0Dir
279
+ if (head === '0') {
280
+ const alt = '0.orig/' + segments.slice(1).join('/')
281
+ if (ok(alt)) return { ok: true, rel: alt, tried }
282
+ }
283
+ return { ok: false, tried }
284
+ }
285
+ if (segments.length === 1) {
286
+ if (region && ok(`system/${region}/${raw}`)) return { ok: true, rel: `system/${region}/${raw}`, tried }
287
+ for (const rel of [`system/${raw}`, `constant/${raw}`, `0/${raw}`]) {
288
+ if (ok(rel)) return { ok: true, rel, tried }
289
+ }
290
+ return { ok: false, tried }
291
+ }
292
+ for (const rel of [`system/${raw}`, `constant/${raw}`, `0/${raw}`]) {
293
+ if (ok(rel)) return { ok: true, rel, tried }
294
+ }
295
+ return { ok: false, tried }
296
+ }
297
+
298
+ /** Up to `limit` dictionaries of a case, for a "did you mean" hint. */
299
+ export function availableDicts(dir, limit = 40) {
300
+ const out = []
301
+ const push = (rel) => { if (out.length < limit) out.push(rel) }
302
+ const scan = (base, depthLeft) => {
303
+ let entries = []
304
+ try { entries = readdirSync(join(dir, base), { withFileTypes: true }) } catch { return }
305
+ for (const e of entries) {
306
+ const rel = `${base}/${e.name}`
307
+ if (e.isDirectory()) {
308
+ if (depthLeft > 0 && !e.name.startsWith('.')) scan(rel, depthLeft - 1)
309
+ } else if (!e.name.startsWith('.')) push(rel)
310
+ }
311
+ }
312
+ scan('system', 1)
313
+ scan('constant', 1)
314
+ scan('0', 1)
315
+ return out
316
+ }
317
+
318
+ // Executables the workbench may launch. Kept explicit: the whitelist is the
319
+ // only thing standing between an agent and an arbitrary shell command.
320
+ export const BASE_APPS = [
321
+ 'blockMesh', 'checkMesh', 'snappyHexMesh', 'foamRun', 'foamMultiRun',
322
+ 'simpleFoam', 'pimpleFoam', 'icoFoam', 'buoyantFoam', 'reactingFoam',
323
+ 'chtMultiRegionFoam', 'chtMultiRegionSimpleFoam', 'chtMultiRegionTwoPhaseEulerFoam', 'rhoPimpleFoam', 'rhoSimpleFoam', 'decomposePar', 'reconstructPar',
324
+ 'reconstructParMesh', 'foamToVTK', 'postProcess', 'setFields', 'topoSet',
325
+ 'createPatch', 'renumberMesh', 'potentialFoam', 'restore0Dir',
326
+ 'splitMeshRegions', 'changeDictionary', 'foamListRegions',
327
+ // feature extraction for snappyHexMesh; org 14 renamed the post-processing
328
+ // utility to foamPostProcess
329
+ 'surfaceFeatureExtract', 'surfaceFeatures', 'foamPostProcess', 'foamSetupCHT', 'setsToZones', 'createZones',
330
+ ]
331
+
332
+ const LAUNCHER_RE = /^(mpirun|mpiexec)$/
333
+ // Commands are executed as argv (never as a shell string), so parentheses are
334
+ // legitimate in function-object specs (`-func cellMax(U)`); the characters that
335
+ // would still be dangerous if a shell were ever reintroduced stay forbidden.
336
+ const SHELL_META_RE = /[;&|`$<>\n\r]/
337
+
338
+ /**
339
+ * Decide whether a command may run. `mpirun [-np N] <app>` is allowed when the
340
+ * wrapped app is whitelisted; shell metacharacters are never allowed.
341
+ * Returns { ok, launcher, app, args } or { ok:false, reason, hint, allowed }.
342
+ */
343
+ export function commandAllowed(cmd, extraCommands = []) {
344
+ const apps = [...new Set([...BASE_APPS, ...(Array.isArray(extraCommands) ? extraCommands.map(String) : [])])]
345
+ const c = String(cmd || '').trim()
346
+ if (!c) return { ok: false, reason: 'empty command' }
347
+ if (SHELL_META_RE.test(c)) {
348
+ return {
349
+ ok: false,
350
+ reason: 'shell metacharacters are not allowed in a command',
351
+ hint: 'run one executable with plain arguments; use openfoam_run twice instead of piping',
352
+ }
353
+ }
354
+ const words = c.split(/\s+/)
355
+ let i = 0
356
+ let launcher = null
357
+ if (LAUNCHER_RE.test(words[0])) {
358
+ launcher = words[0]
359
+ i = 1
360
+ while (i < words.length && words[i].startsWith('-')) {
361
+ const w = words[i]
362
+ if (/^-{1,2}(np|n)$/.test(w)) {
363
+ const n = Number(words[i + 1])
364
+ if (!Number.isFinite(n) || n < 1) {
365
+ return { ok: false, reason: `${launcher} ${w} needs a positive process count`, hint: `for example: ${launcher} -np 4 foamRun` }
366
+ }
367
+ i += 2
368
+ continue
369
+ }
370
+ if (/^-{1,2}(np|n)=/.test(w)) { i += 1; continue }
371
+ i += 1
372
+ }
373
+ if (i >= words.length) {
374
+ return { ok: false, reason: `${launcher} without an application`, hint: `for example: ${launcher} -np 4 foamRun` }
375
+ }
376
+ }
377
+ // Arguments that move the run outside the case directory, load extra code or
378
+ // substitute a dictionary/solver. Both `-x value` and `-x=value` forms.
379
+ const FORBIDDEN_ARG = /^--?(libs|case|roots|hostRoots|dict|solver)(=|$)/i
380
+ const badArg = words.find((w) => FORBIDDEN_ARG.test(w))
381
+ if (badArg) {
382
+ return {
383
+ ok: false,
384
+ reason: `argument ${badArg} is not allowed`,
385
+ hint: 'openfoam_run always runs inside the case directory and never loads extra libraries; remove the argument',
386
+ }
387
+ }
388
+ const app = words[i]
389
+ if (!apps.includes(app)) {
390
+ return {
391
+ ok: false,
392
+ reason: `'${app}' is not in the command whitelist`,
393
+ hint: `allowed applications: ${apps.join(', ')}. Add more with the plugin config "extraCommands" (currently ${JSON.stringify(Array.isArray(extraCommands) ? extraCommands : [])}).`,
394
+ allowed: apps,
395
+ }
396
+ }
397
+ return { ok: true, launcher, app, args: words.slice(i + 1), argv: words }
398
+ }
399
+
400
+ /**
401
+ * Progress of a solver run from its log: last time, steps, seconds per step,
402
+ * ETA and the state (running | stalled | finished | failed).
403
+ */
404
+ export function progressFrom(text, { endTime = null, mtimeMs = 0, nowMs = Date.now(), tolerance = 0.001, stepsTotal = null, logWindow = null } = {}) {
405
+ const parsed = parseRunLog(text)
406
+ const times = parsed.times || []
407
+ const n = times.length
408
+ const lastTime = n ? times[n - 1] : null
409
+ const firstTime = n ? times[0] : null
410
+ // Median of adjacent deltas: robust to a trimmed/rotated log where the first
411
+ // visible time is far from the last one.
412
+ const diffs = []
413
+ for (let i = 1; i < n; i += 1) {
414
+ const d = times[i] - times[i - 1]
415
+ if (d > 1e-12) diffs.push(d)
416
+ }
417
+ diffs.sort((a, b) => a - b)
418
+ const stepEstimate = diffs.length ? diffs[Math.floor(diffs.length / 2)] : null
419
+ const execSeconds = parsed.execSeconds != null ? Number(parsed.execSeconds) : null
420
+ const execSeries = parsed.execSeries || []
421
+ // Prefer the ExecutionTime delta between the visible first and last step: it
422
+ // stays correct on a trimmed log, where the cumulative ExecutionTime belongs
423
+ // to the whole run and not to the visible window.
424
+ const execDelta = execSeries.length >= 2 ? execSeries[execSeries.length - 1] - execSeries[0] : null
425
+ const secondsPerStep = execDelta != null && n > 1 ? execDelta / (n - 1) : null
426
+ let etaSeconds = null
427
+ if (endTime != null && lastTime != null && stepEstimate && secondsPerStep != null && endTime > lastTime) {
428
+ etaSeconds = ((endTime - lastTime) / stepEstimate) * secondsPerStep
429
+ }
430
+ const staleMs = mtimeMs ? nowMs - mtimeMs : 0
431
+ let state
432
+ if (parsed.finished) state = 'finished'
433
+ else if (parsed.errors.length || parsed.diverged) state = 'failed'
434
+ else if (mtimeMs && staleMs > 30 * 60 * 1000) state = 'stalled'
435
+ else state = 'running'
436
+ const floor = parsed.residualFloor != null ? Number(parsed.residualFloor) : null
437
+ const pass = parsed.finished && !parsed.diverged && floor != null && floor < tolerance
438
+ let decision
439
+ if (state === 'finished') decision = pass ? 'PROCEED' : parsed.diverged ? 'RERUN' : 'REVISE'
440
+ else if (state === 'running') decision = 'RUNNING'
441
+ else if (state === 'stalled') decision = 'STALLED'
442
+ else decision = 'RERUN'
443
+ return {
444
+ state,
445
+ decision,
446
+ pass: state === 'finished' ? pass : null,
447
+ time: lastTime,
448
+ firstTime,
449
+ // `steps` is the whole run when the file was counted; `stepsInWindow` is what
450
+ // the tail scan actually saw, so a big log can no longer report a window as
451
+ // the total.
452
+ steps: stepsTotal != null ? stepsTotal : n,
453
+ stepsInWindow: n,
454
+ ...(stepsTotal != null ? { stepsTotal } : {}),
455
+ ...(logWindow ? { logWindow } : {}),
456
+ deltaT_nominal: stepEstimate,
457
+ secondsPerStep,
458
+ etaSeconds,
459
+ eta: etaSeconds != null ? humanDuration(etaSeconds) : null,
460
+ elapsed: execSeconds != null ? humanDuration(execSeconds) : null,
461
+ residualFloor: parsed.residualFloor,
462
+ diverged: parsed.diverged,
463
+ finished: parsed.finished,
464
+ errors: parsed.errors.slice(0, 5),
465
+ warnings: parsed.warnings.slice(0, 5),
466
+ staleSeconds: mtimeMs ? Math.round(staleMs / 1000) : null,
467
+ }
468
+ }
469
+
470
+ export function humanDuration(seconds) {
471
+ const s = Math.max(0, Math.round(Number(seconds) || 0))
472
+ const d = Math.floor(s / 86400)
473
+ const h = Math.floor((s % 86400) / 3600)
474
+ const m = Math.floor((s % 3600) / 60)
475
+ const sec = s % 60
476
+ if (d) return `${d}d ${h}h`
477
+ if (h) return `${h}h ${m}m`
478
+ if (m) return `${m}m ${sec}s`
479
+ return `${sec}s`
480
+ }
481
+
482
+ /** mtime of a file in ms, 0 when unknown. */
483
+ export function mtimeOf(p) {
484
+ try { return statSync(p).mtimeMs } catch { return 0 }
485
+ }