Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: address local review gate findings on LoRA training
Adam Eivyb5e8c1150264
diff --git a/client/src/components/loraTraining/DatasetImageGrid.jsx b/client/src/components/loraTraining/DatasetImageGrid.jsxindex bf77d9b6ab..1dc67b2e3e 100644--- a/client/src/components/loraTraining/DatasetImageGrid.jsx+++ b/client/src/components/loraTraining/DatasetImageGrid.jsx@@ -109,6 +109,10 @@ export default function DatasetImageGrid({ dataset, onImagesChange, onCaptionRunplaceholder={img.status === 'ready' ? 'Caption (must include the trigger word)…' : ''}disabled={img.status !== 'ready'}rows={3}+ // Per-grid-cell field — a visible label would be noise, so the+ // accessible name comes from aria-label (the source + view give+ // a screen-reader user enough to tell cells apart).+ aria-label={`Caption for ${img.source}${img.variation?.view ? ` ${img.variation.view}` : ''} image`}className="w-full bg-port-bg border border-port-border rounded p-2 text-xs text-gray-200 resize-y disabled:opacity-50"/><div className="flex items-center justify-between text-xs">diff --git a/scripts/train_flux2_lora.py b/scripts/train_flux2_lora.pyindex 39f7c75fd5..3537007859 100644--- a/scripts/train_flux2_lora.py+++ b/scripts/train_flux2_lora.py@@ -28,7 +28,6 @@ SIGTERM → finish the current step, save a cancel checkpoint, exit 143.import argparseimport gcimport json-import mathimport osimport signalimport sys@@ -36,6 +35,7 @@ from pathlib import Pathos.environ.setdefault("PYTORCH_MPS_FAST_MATH", "1")+import numpy as npimport torchfrom PIL import Image@@ -90,7 +90,7 @@ def load_image_tensor(path: str, resolution: int) -> torch.Tensor:w, h = img.sizeleft, top = (w - resolution) // 2, (h - resolution) // 2img = img.crop((left, top, left + resolution, top + resolution))- t = torch.from_numpy(__import__("numpy").asarray(img)).float() / 127.5 - 1.0+ t = torch.from_numpy(np.asarray(img)).float() / 127.5 - 1.0return t.permute(2, 0, 1).unsqueeze(0) # (1, 3, H, W)diff --git a/scripts/train_mflux_lora.py b/scripts/train_mflux_lora.pyindex 1cb4234054..0c20449816 100644--- a/scripts/train_mflux_lora.py+++ b/scripts/train_mflux_lora.py@@ -101,6 +101,18 @@ TQDM_RE = re.compile(r"(\d+)\s*/\s*(\d+)\s*\[")STEP_LOSS_RE = re.compile(r"[Ss]teps?[\s:=]+(\d+)\s*/\s*(\d+).*?[Ll]oss[\s:=]+([\d.eE+-]+)")NOISE_RE = re.compile(r"FutureWarning|UserWarning|DeprecationWarning", re.I)+# We merge the mflux child's stderr into its stdout (so tqdm + prints stay in+# order), which means the Node side tags every line `stream='stdout'` and the+# JS failure classifier's stderr-tail stays empty for mflux runs. To keep+# OOM / missing-module / gated-repo errors classifiable, sniff them out of the+# merged stream and re-emit a structured USER_ERROR line (which the Node line+# parser captures regardless of stream). Codes mirror failure.js.+FATAL_PATTERNS = [+ ("OOM", re.compile(r"out of memory|Insufficient Memory|Metal.*out of memory|std::bad_alloc", re.I)),+ ("MODULE_NOT_FOUND", re.compile(r"ModuleNotFoundError|No module named", re.I)),+ ("HF_AUTH", re.compile(r"GatedRepoError|401 Client Error|is restricted|Repo.*is gated", re.I)),+]+def resolve_mflux_output(configured: Path) -> Path:"""mflux appends `_YYYYMMDD_HHMMSS` to checkpoint.output_path when the@@ -218,11 +230,21 @@ def main():CHILD.terminate()in_training = False+ fatal_emitted = Falsefor raw in stream_lines(CHILD.stdout):line = raw.strip()if not line or NOISE_RE.search(line):continue+ # Surface the first fatal error in a structured form the Node+ # classifier can read (once — don't spam if it repeats in a traceback).+ if not fatal_emitted:+ for code, pat in FATAL_PATTERNS:+ if pat.search(line):+ print(f"USER_ERROR:{code}:{line[:300]}", file=sys.stderr, flush=True)+ fatal_emitted = True+ break+m = STEP_LOSS_RE.search(line) or TQDM_RE.search(line)if m:cur, total = int(m.group(1)), int(m.group(2))diff --git a/server/services/loraDatasets.js b/server/services/loraDatasets.jsindex 065619ec4d..2d476b8884 100644--- a/server/services/loraDatasets.js+++ b/server/services/loraDatasets.js@@ -23,6 +23,7 @@ import {computeDatasetReadiness,deriveTriggerWord,isValidTriggerWord,+ prefixCaption,sanitizeLoraDataset,} from '../lib/loraDataset.js';import { ServerError } from '../lib/errorHandler.js';@@ -164,7 +165,16 @@ export async function patchDataset(id, { triggerWord } = {}) {}return updateDataset(id, (current) => {if (triggerWord === undefined || triggerWord === current.triggerWord) return null;- return { ...current, triggerWord };+ // Re-prefix every captioned image so the binding token follows the+ // rename. Without this, computeDatasetReadiness (which gates `captioned`+ // on the caption containing the trigger word) silently drops every+ // previously-captioned image and any training binds the stale token.+ // Empty captions are left untouched — don't fabricate a caption.+ const prev = current.triggerWord;+ const images = current.images.map((img) => (img.caption+ ? { ...img, caption: prefixCaption(triggerWord, img.caption, { previousTriggerWord: prev }) }+ : img));+ return { ...current, triggerWord, images };});}@@ -180,7 +190,11 @@ export async function deleteDataset(id) {/*** Normalize an uploaded image to PNG inside the dataset's images dir and* append its entry. `tmpPath` is the multipart parser's staged temp file —- * always unlinked, success or failure.+ * always unlinked, success or failure. The route's mimetype `fileFilter` is+ * only an early reject of obvious non-images (the declared MIME is+ * client-controlled) — `sharp` below is the real gate: it transcodes any+ * format it can decode and 422s anything it can't, so a wrong-extension+ * upload is normalized rather than trusted by its claimed type.*/export async function addUploadedImage(id, { tmpPath, originalname = '' }) {await requireDataset(id);@@ -294,7 +308,8 @@ export async function reconcileRenderingImages(id, { jobLookup = getJob } = {})return res ? { ...img, status: res.status } : img;}),}));- const healed = [...resolutions.values()];- console.log(`🩹 Dataset ${id} reconciled ${healed.length} rendering image(s) (${healed.filter((r) => r.status === 'ready').length} ready)`);+ const resolved = [...resolutions.values()];+ const readyCount = resolved.filter((r) => r.status === 'ready').length;+ console.log(`🩹 Dataset ${id} reconciled ${resolved.length} rendering image(s) → ${readyCount} ready, ${resolved.length - readyCount} failed`);return updated;}diff --git a/server/services/loraDatasets.test.js b/server/services/loraDatasets.test.jsindex 01e96f1933..fe3dd45b78 100644--- a/server/services/loraDatasets.test.js+++ b/server/services/loraDatasets.test.js@@ -104,6 +104,29 @@ describe('patchDataset / listDatasets', () => {.rejects.toMatchObject({ status: 400 });});+ it('re-prefixes existing captions when the trigger word changes', async () => {+ const { dataset } = await createDataset({ universeId: 'uni-1', entryId: 'char-1' });+ const tmpA = join(TEST_DATA_ROOT, 'a.png');+ const tmpB = join(TEST_DATA_ROOT, 'b.png');+ await makePng(tmpA); await makePng(tmpB);+ const a = await addUploadedImage(dataset.id, { tmpPath: tmpA });+ const b = await addUploadedImage(dataset.id, { tmpPath: tmpB });+ await updateImageCaption(dataset.id, a.id, 'kessa_brightwater, front view');+ // b stays uncaptioned — must not be fabricated.++ const next = await patchDataset(dataset.id, { triggerWord: 'kessa_v2' });+ const captioned = next.images.find((i) => i.id === a.id);+ const uncaptioned = next.images.find((i) => i.id === b.id);+ // Old prefix swapped for the new token, body preserved — so the image+ // still counts toward computeDatasetReadiness.captioned under the new word.+ expect(captioned.caption).toBe('kessa_v2, front view');+ expect(uncaptioned.caption).toBe('');+ // readiness is attached by getDataset (the route layer); the re-prefixed+ // caption must still count under the new trigger word.+ const reread = await getDataset(dataset.id);+ expect(reread.readiness.captioned).toBe(1);+ });+it('filters list by character ids', async () => {await createDataset({ universeId: 'uni-1', entryId: 'char-1' });await createDataset({ universeId: 'uni-1', entryId: 'char-2' });diff --git a/server/services/loraTraining/db.js b/server/services/loraTraining/db.jsindex 5894e096be..d8330be39c 100644--- a/server/services/loraTraining/db.js+++ b/server/services/loraTraining/db.js@@ -3,9 +3,16 @@** One row per run: id/status/character_id mirrored as columns for* filtering, the full record in `data` JSONB (returned verbatim — columns- * are never read back). Single writer (the training service) per run, so- * plain read-modify-write suffices; no row locking needed. Mirrors the- * `creative_director_projects` adapter pattern.+ * are never read back). Mirrors the `creative_director_projects` adapter+ * pattern.+ *+ * Within a single run, `updateRun` has overlapping callers — the debounced+ * progress-mirror flush (checkpoint/sample array appends) races the+ * status/startedAt/completedAt writes. A bare read-modify-write would let a+ * stale read clobber a concurrent append, so `updateRun` chains every+ * mutation for the same id onto a per-id tail promise (the same discipline+ * as `issueWriteTail` in pipeline/issues.js). Writes to DIFFERENT runs stay+ * parallel; the map entry is pruned once its chain settles.*/import { query } from '../../lib/db.js';@@ -13,6 +20,19 @@ import { ServerError } from '../../lib/errorHandler.js';const rowToRun = (row) => row?.data ?? null;+// id → tail Promise. Serializes read-modify-write cycles for one run.+const writeTails = new Map();+function queueRunWrite(id, fn) {+ const prev = writeTails.get(id) || Promise.resolve();+ const next = prev.then(fn, fn);+ const silenced = next.catch(() => {});+ writeTails.set(id, silenced);+ silenced.finally(() => {+ if (writeTails.get(id) === silenced) writeTails.delete(id);+ });+ return next;+}+async function persist(run) {await query(`INSERT INTO lora_training_runs (id, status, character_id, data, created_at, updated_at)@@ -51,13 +71,20 @@ export async function getRunRequired(id) {return run;}-/** Read-modify-write. `patch` is an object merged shallowly, or a function. */+/**+ * Read-modify-write, serialized per run id so a concurrent append (e.g. the+ * debounced checkpoint-array flush) can't be clobbered by a stale read from+ * a parallel status write. `patch` is an object merged shallowly, or a+ * function `(current) => next` (return falsy to abort without writing).+ */export async function updateRun(id, patch) {- const current = await getRunRequired(id);- const next = typeof patch === 'function' ? patch(current) : { ...current, ...patch };- if (!next) return current;- next.updatedAt = new Date().toISOString();- return persist(next);+ return queueRunWrite(id, async () => {+ const current = await getRunRequired(id);+ const next = typeof patch === 'function' ? patch(current) : { ...current, ...patch };+ if (!next) return current;+ next.updatedAt = new Date().toISOString();+ return persist(next);+ });}export async function listRuns({ status = null, characterId = null, datasetId = null, limit = 50 } = {}) {diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex 4b3bafca14..d3142ee87d 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -199,87 +199,106 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {const run = await runsDb.getRun(runId);if (!run) return fail(`run record missing: ${runId}`);+ // Terminal failure BEFORE the child spawns: flip the run record to failed+ // AND release the dataset's `training` status, then emit the failed event.+ // Every pre-spawn exit funnels through here so none can leave the run row+ // stuck `running` (lingering until the next boot reconcile) or the dataset+ // stuck on its `training` chip.+ const failBeforeSpawn = async (message) => {+ await runsDb.updateRun(runId, {+ status: 'failed', error: message, completedAt: new Date().toISOString(),+ }).catch(() => {});+ await flipDatasetAfterRun(run.datasetId, { trained: false });+ return fail(message);+ };+// Re-validate — the dataset may have been edited/deleted while queued.let manifest;try {({ manifest } = await validateDatasetReady(run.datasetId));} catch (err) {- await runsDb.updateRun(runId, { status: 'failed', error: err.message }).catch(() => {});- return fail(err.message);+ return failBeforeSpawn(err.message);}const dir = runDir(runId);const checkpointsDir = join(dir, 'checkpoints');const samplesDir = join(dir, 'samples');- await mkdir(checkpointsDir, { recursive: true });- await mkdir(samplesDir, { recursive: true });let bin;let args;- if (run.runtime === TRAINING_RUNTIMES.FLUX2) {- bin = resolveFlux2Python();- if (!bin) {- await runsDb.updateRun(runId, { status: 'failed', error: 'FLUX.2 venv missing' }).catch(() => {});- return fail('FLUX.2 python environment disappeared — re-run scripts/setup-image-video.sh');- }- const manifestPath = join(dir, 'manifest.json');- await atomicWrite(manifestPath, {- triggerWord: manifest.triggerWord,- images: manifest.images.map((img) => ({ path: img.path, caption: img.caption })),- });- args = buildFlux2TrainArgs({- scriptPath: TRAINER_SCRIPTS.flux2,- trainRepo: run.trainRepo,- manifestPath,- runDir: dir,- triggerWord: run.triggerWord,- params: run.params,- samplePrompt: run.params?.samplePrompt || null,- });- } else {- bin = pythonPath;- if (!bin || !isMfluxTrainAvailable(bin)) {- await runsDb.updateRun(runId, { status: 'failed', error: 'mflux trainer not available' }).catch(() => {});- return fail('mflux-train not found next to the configured python — update mflux (≥0.17) or set up the FLUX.2 venv');- }- // Stage the dataset in mflux's auto-discovery layout: NNNN.png +- // NNNN.txt caption pairs, plus preview_1.txt for the periodic sample- // render. mflux resolves everything from the config's `data` dir.- const dataDir = join(dir, 'data');- await mkdir(dataDir, { recursive: true });- for (let i = 0; i < manifest.images.length; i += 1) {- const stem = String(i + 1).padStart(4, '0');- await copyFile(manifest.images[i].path, join(dataDir, `${stem}.png`));- await writeFile(join(dataDir, `${stem}.txt`), `${manifest.images[i].caption}\n`);- }- if ((run.params?.sampleEvery ?? TRAINING_DEFAULTS.sampleEvery) > 0) {- const samplePrompt = run.params?.samplePrompt || `${run.triggerWord} portrait, neutral background`;- await writeFile(join(dataDir, 'preview_1.txt'), `${samplePrompt}\n`);+ // Staging I/O (mkdir + copyFile/writeFile/atomicWrite) is wrapped: a throw+ // here — e.g. a dataset image deleted in the window after validateDatasetReady's+ // existence check (TOCTOU), or disk-full — would otherwise propagate to the+ // queue's catch (no crash) but leave the run record `running` forever.+ try {+ await mkdir(checkpointsDir, { recursive: true });+ await mkdir(samplesDir, { recursive: true });++ if (run.runtime === TRAINING_RUNTIMES.FLUX2) {+ bin = resolveFlux2Python();+ if (!bin) {+ return failBeforeSpawn('FLUX.2 python environment disappeared — re-run scripts/setup-image-video.sh');+ }+ const manifestPath = join(dir, 'manifest.json');+ await atomicWrite(manifestPath, {+ triggerWord: manifest.triggerWord,+ images: manifest.images.map((img) => ({ path: img.path, caption: img.caption })),+ });+ args = buildFlux2TrainArgs({+ scriptPath: TRAINER_SCRIPTS.flux2,+ trainRepo: run.trainRepo,+ manifestPath,+ runDir: dir,+ triggerWord: run.triggerWord,+ params: run.params,+ samplePrompt: run.params?.samplePrompt || null,+ });+ } else {+ bin = pythonPath;+ if (!bin || !isMfluxTrainAvailable(bin)) {+ return failBeforeSpawn('mflux-train not found next to the configured python — update mflux (≥0.17) or set up the FLUX.2 venv');+ }+ // Stage the dataset in mflux's auto-discovery layout: NNNN.png ++ // NNNN.txt caption pairs, plus preview_1.txt for the periodic sample+ // render. mflux resolves everything from the config's `data` dir.+ const dataDir = join(dir, 'data');+ await mkdir(dataDir, { recursive: true });+ for (let i = 0; i < manifest.images.length; i += 1) {+ const stem = String(i + 1).padStart(4, '0');+ await copyFile(manifest.images[i].path, join(dataDir, `${stem}.png`));+ await writeFile(join(dataDir, `${stem}.txt`), `${manifest.images[i].caption}\n`);+ }+ if ((run.params?.sampleEvery ?? TRAINING_DEFAULTS.sampleEvery) > 0) {+ const samplePrompt = run.params?.samplePrompt || `${run.triggerWord} portrait, neutral background`;+ await writeFile(join(dataDir, 'preview_1.txt'), `${samplePrompt}\n`);+ }+ // output_path must NOT pre-exist — mflux appends a timestamp suffix to+ // an existing dir (its new_folder behavior), which would break the+ // wrapper's artifact watcher. mflux creates checkpoints/ + preview/+ // (+ loss/) inside it.+ const mfluxOutputDir = join(dir, 'mflux');+ const config = buildMfluxTrainConfig({+ params: run.params,+ variant: run.fluxVariant,+ mfluxModel: run.mfluxModel,+ dataDir,+ imageCount: manifest.images.length,+ outputDir: mfluxOutputDir,+ // Memory-derived quantize/low_ram (see deriveMfluxMemoryConfig) —+ // a bf16 base + in-RAM latent cache OOM-killed a 48 GB machine.+ totalMemGb: totalmem() / 2 ** 30,+ });+ const configPath = join(dir, 'mflux-train.json');+ await atomicWrite(configPath, config);+ args = buildMfluxTrainArgs({+ scriptPath: TRAINER_SCRIPTS.mflux,+ configPath,+ runDir: dir,+ totalSteps: run.params?.steps || TRAINING_DEFAULTS.steps,+ });}- // output_path must NOT pre-exist — mflux appends a timestamp suffix to- // an existing dir (its new_folder behavior), which would break the- // wrapper's artifact watcher. mflux creates checkpoints/ + preview/- // (+ loss/) inside it.- const mfluxOutputDir = join(dir, 'mflux');- const config = buildMfluxTrainConfig({- params: run.params,- variant: run.fluxVariant,- mfluxModel: run.mfluxModel,- dataDir,- imageCount: manifest.images.length,- outputDir: mfluxOutputDir,- // Memory-derived quantize/low_ram (see deriveMfluxMemoryConfig) —- // a bf16 base + in-RAM latent cache OOM-killed a 48 GB machine.- totalMemGb: totalmem() / 2 ** 30,- });- const configPath = join(dir, 'mflux-train.json');- await atomicWrite(configPath, config);- args = buildMfluxTrainArgs({- scriptPath: TRAINER_SCRIPTS.mflux,- configPath,- runDir: dir,- totalSteps: run.params?.steps || TRAINING_DEFAULTS.steps,- });+ } catch (err) {+ return failBeforeSpawn(`staging failed: ${err.message}`);}await runsDb.updateRun(runId, { status: 'running', startedAt: new Date().toISOString() });@@ -346,21 +365,35 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {const makeSplitter = (stream) => {let buf = '';- return (chunk) => {- buf += chunk.toString();- let idx;- while ((idx = buf.indexOf('\n')) >= 0) {- // try/catch: this runs inside a child-process data callback — an- // uncaught throw here would crash the server process.- try { handleLine(buf.slice(0, idx), stream); } catch (err) {- console.error(`❌ training [${shortId(jobId)}] line handler failed: ${err?.message}`);- }- buf = buf.slice(idx + 1);+ const safeLine = (text) => {+ // try/catch: this runs inside a child-process data/end callback — an+ // uncaught throw here would crash the server process.+ try { handleLine(text, stream); } catch (err) {+ console.error(`❌ training [${shortId(jobId)}] line handler failed: ${err?.message}`);}};+ return {+ push: (chunk) => {+ buf += chunk.toString();+ let idx;+ while ((idx = buf.indexOf('\n')) >= 0) {+ safeLine(buf.slice(0, idx));+ buf = buf.slice(idx + 1);+ }+ },+ // Flush any trailing line that arrived without a final newline. The+ // trainers hard-exit via os._exit (teardown-hang defense), which can+ // truncate the pipe before the final `RESULT:{...}\n` newline flushes+ // — without this drain that line (the run's only success signal) is lost.+ flush: () => { if (buf) { safeLine(buf); buf = ''; } },+ };};- proc.stdout.on('data', makeSplitter('stdout'));- proc.stderr.on('data', makeSplitter('stderr'));+ const stdoutSplitter = makeSplitter('stdout');+ const stderrSplitter = makeSplitter('stderr');+ proc.stdout.on('data', stdoutSplitter.push);+ proc.stdout.on('end', stdoutSplitter.flush);+ proc.stderr.on('data', stderrSplitter.push);+ proc.stderr.on('end', stderrSplitter.flush);proc.on('error', (err) => {if (activeProcess === proc) { activeProcess = null; activeJobId = null; }@@ -384,6 +417,17 @@ async function finalizeTraining({ jobId, runId, code, signal, state }) {const job = getJob(jobId);const canceled = !!job?.cancelRequested;+ // Run record vanished mid-training (direct DB edit / race — the DELETE+ // route blocks active runs, so this is defensive). Don't register a LoRA+ // with no run to anchor its sidecar lineage — that would leave an orphan+ // .safetensors in data/loras/. Just settle the job terminally.+ if (!run) {+ const msg = canceled ? 'Canceled' : `Run record vanished during finalize (exit ${code})`;+ console.error(`❌ training [${shortId(jobId)}] ${msg}`);+ trainingEvents.emit('failed', { generationId: jobId, error: msg });+ return;+ }+if (code === 0 && state.result?.adapter_path) {const filename = trainedLoraFilename({name: run?.name, characterName: run?.character?.name, runId,@@ -419,11 +463,28 @@ async function finalizeTraining({ jobId, runId, code, signal, state }) {// record keeps the checkpoint lineage for a future resume.await runsDb.updateRun(runId, { status: 'canceled', completedAt: new Date().toISOString(), error: 'Canceled' }).catch(() => {});- await flipDatasetAfterRun(run?.datasetId, { trained: false });+ await flipDatasetAfterRun(run.datasetId, { trained: false });trainingEvents.emit('failed', { generationId: jobId, error: 'Canceled' });return;}+ if (code === 0) {+ // Exited cleanly but emitted no parseable RESULT: line (success with a+ // result was handled above) — the trainer finished without producing an+ // adapter. Report the trainer's own USER_ERROR if it surfaced one,+ // otherwise a clear message instead of the confusing "exited with code 0".+ const message = state.userError?.message+ || 'Trainer exited cleanly but produced no adapter — check the dataset and run logs';+ await runsDb.updateRun(runId, {+ status: 'failed', completedAt: new Date().toISOString(),+ error: message, errorCode: state.userError?.kind || 'NO_RESULT',+ }).catch(() => {});+ await flipDatasetAfterRun(run.datasetId, { trained: false });+ console.error(`❌ training [${shortId(jobId)}] no-result: ${message}`);+ trainingEvents.emit('failed', { generationId: jobId, error: message });+ return;+ }+const { code: failCode, message } = classifyTrainingFailure({stderrTail: state.stderrTail, exitCode: code, signal, userError: state.userError,});diff --git a/server/services/loraTraining/progress.js b/server/services/loraTraining/progress.jsindex 5367cd22cc..9c47662ca3 100644--- a/server/services/loraTraining/progress.js+++ b/server/services/loraTraining/progress.js@@ -43,7 +43,11 @@ export function makeTrainingLineHandler({if (!line) return;if (PYTHON_NOISE_RE.test(line)) return;- if (stream === 'stderr') {+ // Keep a rolling stderr tail for failure classification — but skip the+ // python heartbeat keep-alives (STAGE:<stage>:heartbeat:Ns), or a stalled+ // run would fill the tail with heartbeats and classifyTrainingFailure's+ // "last few lines" would show those instead of the real error.+ if (stream === 'stderr' && !/:heartbeat:\d+s\b/.test(line)) {state.stderrTail.push(line);if (state.stderrTail.length > STDERR_TAIL_LINES) state.stderrTail.shift();}