bareloop 0.47.0 → 0.48.0

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.
@@ -170,6 +170,8 @@
170
170
  1.2s, matching design/panel-mockup.html's pulsing amber dot exactly —
171
171
  one fixed rhythm, never re-derived per call site. */
172
172
  @keyframes pulse-glyph{0%,100%{opacity:1;}50%{opacity:0.3;}}
173
+ .audit-caret{flex:none;color:var(--text-faint);margin-right:.6em;}
174
+ @media (max-width: 640px){ .audit-caret{margin-right:.2em;} }
173
175
  .dot.amber::before{content:"[▶]";color:var(--amber);}
174
176
  /* RULED 2026-10-15 (matches fwdloop glyphPulses): a sign blinks only while running or waiting for your Accept, keyed to `.pulse` (dotPulses decides) */
175
177
  .dot.pulse::before{animation:pulse-glyph 1.2s ease-in-out infinite;}
@@ -290,6 +292,10 @@
290
292
  .ended-row{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap;margin-bottom:6px;}
291
293
  .ended-label{color:var(--text-faint);font-size:11px;letter-spacing:0.08em;min-width:52px;}
292
294
  .ended-text{flex:1 1 220px;min-width:0;overflow-wrap:anywhere;}
295
+ /* a NEXT with several instructions is one per line: label muted, instructions in a second column (the shape fwdloop copied, 2026-10-25) */
296
+ .next-rows{display:grid;grid-template-columns:max-content minmax(0,1fr);column-gap:10px;row-gap:2px;}
297
+ .next-label{color:var(--text-faint);}
298
+ .next-text{min-width:0;overflow-wrap:anywhere;}
293
299
  .ended-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:8px;}
294
300
  /* P5 item 4: Import (read only) — the folder browser, the imported rows, the view */
295
301
  .import-box{border:1px dashed var(--border-strong);padding:10px;margin-bottom:10px;display:grid;gap:8px;}
@@ -1115,10 +1121,13 @@
1115
1121
  });
1116
1122
  }
1117
1123
 
1118
- // ---- step map renderer (buildStepMapHTML below — ONE renderer, no second hand-authored map anywhere on this page) ----
1124
+ // The one Audit fold arrow (fwdloop's): \u25B6 closed, \u25BC open, faint, never shrinking; the gap after it is CSS (smaller on a phone).
1125
+ function auditCaret(open){ return '<span class="audit-caret">' + (open ? "\u25BC" : "\u25B6") + '</span>'; }
1119
1126
  function escapeXml(s){
1120
1127
  return String(s).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");
1121
1128
  }
1129
+
1130
+ // ---- step map renderer (buildStepMapHTML below — ONE renderer, no second hand-authored map anywhere on this page) ----
1122
1131
  // s.noNumber (F196): a synthetic placeholder box (e.g. "died during
1123
1132
  // planning") is a LABEL, never a real step — it renders without the
1124
1133
  // leading "<n> " step number a real step gets.
@@ -2480,6 +2489,12 @@
2480
2489
  // RULED 2026-10-15 (aligned with fwdloop M9 am7): ONE block, the same shape every time: ENDED (a finished run), NEXT (a finished run), SCHEDULE
2481
2490
  // (always: the schedule's words and a second line, or "By hand"). A schedule that started nothing turns the SCHEDULE row AND the frame red.
2482
2491
  // The sentences are CODE-OWNED on the server (`endedFor`/`endedText` in src/panel/server.js, `detail.schedule` from src/schedulewords.js) — this only paints them.
2492
+ // NEXT: `e.next` is one string; `e.rows` ([label, instruction] pairs, from endedFor) is there only when it holds several instructions
2493
+ function nextRow(e){
2494
+ if(!Array.isArray(e.rows) || e.rows.length < 2) return summaryRow("NEXT", e.next, "ended-next", false);
2495
+ var grid = e.rows.map(function(r){ return '<span class="next-row" style="display:contents"><span class="next-label">' + escapeXml(r[0]) + '</span><span class="next-text">' + escapeXml(r[1]) + '</span></span>'; }).join("");
2496
+ return '<div class="ended-row"><span class="ended-label">NEXT</span><span class="ended-text next-rows" data-testid="ended-next">' + grid + '</span></div>';
2497
+ }
2483
2498
  function renderEnded(detail){
2484
2499
  var box = document.getElementById("ended-block");
2485
2500
  var e = detail.ended;
@@ -2495,7 +2510,7 @@
2495
2510
  var h = "";
2496
2511
  if(e){
2497
2512
  // text only: the ONE place for [Stop] / [Resume] / [Reuse workflow] is the Run tab's top action row (renderRunActions)
2498
- h += summaryRow("ENDED", detail.endedText || e.reason, "ended-reason", false) + summaryRow("NEXT", e.next, "ended-next", false);
2513
+ h += summaryRow("ENDED", detail.endedText || e.reason, "ended-reason", false) + nextRow(e);
2499
2514
  }
2500
2515
  if(sc){
2501
2516
  var w = sc.words || {};
@@ -2868,7 +2883,11 @@
2868
2883
  if(!box || !list) return;
2869
2884
  var items = detail && Array.isArray(detail.learnings) ? detail.learnings : [];
2870
2885
  list.innerHTML = "";
2871
- var head = "What the planner was told from earlier runs";
2886
+ var errLine = detail && typeof detail.learningsError === "string" ? detail.learningsError : "";
2887
+ // only the error and nothing handed: the title says so (hamr 2026-10-24); with hints it stays "What the planner was told ..."
2888
+ var head = items.length === 0 && errLine ? "No lessons were given to the planner" : "What the planner was told from earlier runs";
2889
+ // header mark (hamr 2026-10-24): \u2713 when lessons were handed to the planner, \u2717 when the learnings file could not be read and nothing was handed (hints win if both ever exist)
2890
+ var mark = items.length === 0 && errLine ? "\u2717" : "\u2713";
2872
2891
  items.forEach(function(it, gi){
2873
2892
  var hints = Array.isArray(it.hints) ? it.hints : [];
2874
2893
  var when = it.phase === "replan" ? "first replan" : "draft";
@@ -2922,8 +2941,8 @@
2922
2941
  });
2923
2942
  });
2924
2943
  var label = items.length ? head + " \u00B7 " + first + (first === 1 ? " hint" : " hints") : head;
2925
- // no arrow (hamr 2026-10-23): the state chip leads; aria-expanded carries open/closed. The same `[✓] word` state markup the schedule/step headers wear (stateDotHTML), then the plain-words title
2926
- var paint = function(){ sum.innerHTML = stateDotHTML(glyphClass("\u2713"), "learnings", "audit-learnings-state") + " " + escapeXml(label); };
2944
+ // arrow back (hamr 2026-10-24, latest wins over 2026-10-23): auditCaret (\u25BC open / \u25B6 closed) first, as the schedule header; then the same `[✓] word` state markup the schedule/step headers wear (stateDotHTML), then the plain-words title
2945
+ var paint = function(){ sum.innerHTML = auditCaret(sum.getAttribute("aria-expanded") === "true") + stateDotHTML(glyphClass(mark), "learnings", "audit-learnings-state") + " " + escapeXml(label); };
2927
2946
  paint();
2928
2947
  // ONE fold, same as the other Audit sections: the header button toggles the body (wired once)
2929
2948
  sum.onclick = function(){
@@ -2933,7 +2952,15 @@
2933
2952
  paint();
2934
2953
  };
2935
2954
  }
2936
- box.hidden = items.length === 0;
2955
+ if(errLine){
2956
+ var en = document.createElement("div");
2957
+ en.className = "hint";
2958
+ en.style.cssText = "margin:6px 0;overflow-wrap:anywhere;";
2959
+ en.setAttribute("data-testid", "audit-learnings-error");
2960
+ en.textContent = errLine;
2961
+ list.appendChild(en);
2962
+ }
2963
+ box.hidden = items.length === 0 && !errLine;
2937
2964
  }
2938
2965
 
2939
2966
  // ONE spelling of a step's state: its dot + the bold state word — read by the Run tab's step cards AND the Audit tab's grouped rows
@@ -3451,7 +3478,7 @@
3451
3478
  gBtn.className = "btn audit-part-toggle";
3452
3479
  gBtn.setAttribute("aria-expanded", "false");
3453
3480
  gBtn.setAttribute("data-testid", "audit-schedule-toggle");
3454
- var secHead = function(open){ return (open ? "\u25BE " : "\u25B8 ") + stateDotHTML(glyphClass(sec.sign), sec.word, "audit-schedule-state") + " " + escapeXml(sec.title) + " &middot; " + escapeXml(sec.head); };
3481
+ var secHead = function(open){ return auditCaret(open) + stateDotHTML(glyphClass(sec.sign), sec.word, "audit-schedule-state") + " " + escapeXml(sec.title) + " &middot; " + escapeXml(sec.head); };
3455
3482
  gBtn.innerHTML = secHead(false);
3456
3483
  var gBody = document.createElement("div");
3457
3484
  gBody.className = "audit-part-body";
@@ -3500,11 +3527,15 @@
3500
3527
  headBtn.setAttribute("aria-expanded", startExpanded ? "true" : "false");
3501
3528
  headBtn.setAttribute("data-testid", "audit-part-toggle-" + idx);
3502
3529
  var groupResultGlyph = partResultGlyph(part, box);
3503
- headBtn.innerHTML =
3504
- stepStateHTML(box, 'audit-part-state-' + idx) + ' ' + titleText + ' &middot; ' + partLine1Text(part, detail) +
3505
- (groupResultGlyph !== null ? ' &middot; ' + groupResultGlyph : '') +
3506
- (box.blocked > 0 ? ' <span class="badge red" data-testid="audit-part-blocked-' + idx + '">' + box.blocked + ' blocked</span>' : '') +
3507
- actorMarkHtml(part);
3530
+ // same arrow as the schedule section's secHead (auditCaret): \u25BC open, \u25B6 closed, at the very start of the button text
3531
+ var partHead = function(open){
3532
+ return auditCaret(open) +
3533
+ stepStateHTML(box, 'audit-part-state-' + idx) + ' ' + titleText + ' &middot; ' + partLine1Text(part, detail) +
3534
+ (groupResultGlyph !== null ? ' &middot; ' + groupResultGlyph : '') +
3535
+ (box.blocked > 0 ? ' <span class="badge red" data-testid="audit-part-blocked-' + idx + '">' + box.blocked + ' blocked</span>' : '') +
3536
+ actorMarkHtml(part);
3537
+ };
3538
+ headBtn.innerHTML = partHead(startExpanded);
3508
3539
  var body = document.createElement("div");
3509
3540
  body.className = "audit-part-body";
3510
3541
  body.hidden = !startExpanded;
@@ -3550,6 +3581,7 @@
3550
3581
  var expanded = headBtn.getAttribute("aria-expanded") === "true";
3551
3582
  headBtn.setAttribute("aria-expanded", expanded ? "false" : "true");
3552
3583
  body.hidden = expanded;
3584
+ headBtn.innerHTML = partHead(!expanded);
3553
3585
  if(!expanded && !built) buildBody();
3554
3586
  });
3555
3587
  rowWrap.appendChild(headBtn);
@@ -13,7 +13,7 @@
13
13
 
14
14
  import { spawn as realSpawn } from 'node:child_process';
15
15
  import {
16
- openSync, closeSync, writeFileSync, readFileSync, readdirSync,
16
+ openSync, closeSync, writeFileSync, readFileSync, readdirSync, appendFileSync, statSync,
17
17
  } from 'node:fs';
18
18
  import { dirname, join } from 'node:path';
19
19
  import {
@@ -51,13 +51,33 @@ function nextRevisionName(dir) {
51
51
  }
52
52
 
53
53
  /**
54
- * The tail of the engine's own log — its refusal text, verbatim.
54
+ * The folder's ONE `run.log` for an Accept / Rerun / Pause / Resume child (records ruling 2026-10-24: one log per folder, not a
55
+ * new file per action). One header line says which action's words follow; `offset` is the byte after it, so {@link readLogTail}
56
+ * shows this action's own output and never an older action's.
57
+ * @param {string} dir the run's folder (beside its spec)
58
+ * @param {string} action accept | rerun | pause | resume
59
+ * @param {string} runid
60
+ * @returns {{logFile: string, fd: number|null, offset: number}}
61
+ */
62
+ function openActionLog(dir, action, runid) {
63
+ const logFile = join(dir, 'run.log');
64
+ try {
65
+ appendFileSync(logFile, `== ${action} ${runid} at ${new Date().toISOString()} ==\n`);
66
+ const offset = statSync(logFile).size;
67
+ return { logFile, fd: openSync(logFile, 'a'), offset };
68
+ } catch { return { logFile, fd: null, offset: 0 }; }
69
+ }
70
+
71
+ /**
72
+ * The tail of the engine's own log — its refusal text, verbatim — read only from `offset` (this action's own lines).
55
73
  * @param {string} file
74
+ * @param {number} [offset] byte to start from (0 = the whole file)
56
75
  * @returns {string}
57
76
  */
58
- function readLogTail(file) {
77
+ function readLogTail(file, offset = 0) {
59
78
  try {
60
- const text = readFileSync(file, 'utf8');
79
+ const buf = readFileSync(file);
80
+ const text = buf.subarray(offset).toString('utf8');
61
81
  return text.slice(Math.max(0, text.length - LOG_TAIL_BYTES)).trim();
62
82
  } catch { return ''; }
63
83
  }
@@ -203,7 +223,6 @@ export function createRunRoutes(opts) {
203
223
  }
204
224
  const questionOf = (/** @type {string} */ n) => (signed !== null && opts.stageQuestionsOfSpec ? opts.stageQuestionsOfSpec(signed).get(n) ?? null : null);
205
225
  const dir = dirname(ctx.specPath);
206
- const logFile = join(dir, `${decide}-${runid}-${Date.now()}.log`);
207
226
  const args = [
208
227
  '--wait', 'systemd-inhibit', `--why=bareloop panel ${decide}`,
209
228
  process.execPath, bareloopBin,
@@ -211,9 +230,7 @@ export function createRunRoutes(opts) {
211
230
  // last, so no flag lookup in the engine can land on the person's words
212
231
  ...(decide === 'rerun' ? ['--text', text] : []),
213
232
  ];
214
- /** @type {number|null} */
215
- let logFd = null;
216
- try { logFd = openSync(logFile, 'a'); } catch { logFd = null; }
233
+ const { logFile, fd: logFd, offset: logFrom } = openActionLog(dir, decide, runid);
217
234
  const child = spawnFn('setsid', args, { detached: true, stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'], env: envNow() });
218
235
  if (logFd !== null) { try { closeSync(logFd); } catch { /* the child holds its own copy */ } }
219
236
  if (typeof child?.unref === 'function') child.unref();
@@ -230,7 +247,7 @@ export function createRunRoutes(opts) {
230
247
  child.once('exit', (/** @type {number|null} */ code) => {
231
248
  clearTimeout(timer);
232
249
  if (code === 0) finish(200, { ok: true, ...answered, runid, log: logFile });
233
- else finish(409, { ok: false, error: engineRefusalWords(readLogTail(logFile), decide, logFile, questionOf), log: logFile });
250
+ else finish(409, { ok: false, error: engineRefusalWords(readLogTail(logFile, logFrom), decide, logFile, questionOf), log: logFile });
234
251
  });
235
252
  child.once('error', (/** @type {Error} */ e) => {
236
253
  clearTimeout(timer);
@@ -352,7 +369,6 @@ export function createRunRoutes(opts) {
352
369
  writeFileSync(specPath, `${JSON.stringify(spec, null, 2)}\n`, { flag: 'wx' });
353
370
  }
354
371
 
355
- const logFile = join(dir, `resume-${m[1]}-${Date.now()}.log`);
356
372
  const args = [
357
373
  '--wait', 'systemd-inhibit', '--why=bareloop panel resume',
358
374
  process.execPath, bareloopBin,
@@ -363,9 +379,7 @@ export function createRunRoutes(opts) {
363
379
  // the drafting fold rides every leg of the chain (a leg that dropped it would widen the ceiling)
364
380
  ...(plan.draftSpentUsd !== null ? ['--draft-spent-usd', String(plan.draftSpentUsd), ...(plan.draftSpendComplete === false ? ['--draft-spend-incomplete'] : [])] : []),
365
381
  ];
366
- /** @type {number|null} */
367
- let logFd = null;
368
- try { logFd = openSync(logFile, 'a'); } catch { logFd = null; }
382
+ const { logFile, fd: logFd, offset: logFrom } = openActionLog(dir, 'resume', m[1]);
369
383
  const child = spawnFn('setsid', args, {
370
384
  detached: true, stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'], env: envNow(),
371
385
  });
@@ -389,7 +403,7 @@ export function createRunRoutes(opts) {
389
403
  ok: true, runid: m[1], specHash, capsChanged: changed, log: logFile,
390
404
  });
391
405
  } else {
392
- finish(409, { ok: false, error: engineRefusalWords(readLogTail(logFile), 'resume', logFile), log: logFile });
406
+ finish(409, { ok: false, error: engineRefusalWords(readLogTail(logFile, logFrom), 'resume', logFile), log: logFile });
393
407
  }
394
408
  });
395
409
  child.once('error', (/** @type {Error} */ e) => {
@@ -33,7 +33,9 @@ import {
33
33
  dirname, join, basename, relative, isAbsolute, sep,
34
34
  } from 'node:path';
35
35
  import { fileURLToPath } from 'node:url';
36
- import { readRunList, readNeedsRemovals, DIED_MTIME_MS, runIsAlive } from '../runlist.js';
36
+ import { readRunList, readNeedsRemovals, DIED_MTIME_MS, runIsAlive, atMs, runNumbers, runNameOf } from '../runlist.js';
37
+ import { checkExportable } from '../runexport.js';
38
+ import { sourceNearSpine, signedSpecForRun } from '../runfiles.js';
37
39
  import { webFetchState } from '../source.js';
38
40
  import { isWebUrl } from '../pagefetch.js';
39
41
  import { draftingPartFor, sessionDirForRow, readDraftSteps } from '../draftspend.js';
@@ -47,7 +49,7 @@ import { chainSpend } from '../ledger.js';
47
49
  import { runBehaviour } from '../behaviour.js';
48
50
  import { SPEND_RECORD_TYPES, floorsFromRecords } from '../ledger.js';
49
51
  import { jobSpecHash, workflowKey } from '../job.js';
50
- import { parseHintBlock } from '../learn.js';
52
+ import { parseHintBlock, hintsErrorLine } from '../learn.js';
51
53
  import { confirmProtections } from '../authorflow.js';
52
54
  import { createScheduleDoor } from './schedules.js';
53
55
  import { createStarter } from './schedulestart.js';
@@ -79,7 +81,7 @@ import { stageQuestionsByName } from '../stagewords.js';
79
81
 
80
82
  const HERE = dirname(fileURLToPath(import.meta.url));
81
83
 
82
- /** bareloop's own version, from its package.json (read each time the page is served); 'unknown' if it cannot be read, never a guess
84
+ /** bareloop's own version, from its package.json (read once when the panel starts); 'unknown' if it cannot be read, never a guess
83
85
  * @param {string} [file] test seam: another package.json
84
86
  * @returns {string} */
85
87
  export function packageVersion(file = join(HERE, '..', '..', 'package.json')) {
@@ -91,13 +93,13 @@ export function packageVersion(file = join(HERE, '..', '..', 'package.json')) {
91
93
 
92
94
  /**
93
95
  * `GET /api/whoami` body. `drafts` counts the person's drafting sessions that are not finished (the headless scheduled ones are not drafts).
94
- * @param {{ port: number, packageJsonPath?: string, authorRoutes?: ReturnType<typeof createAuthorRoutes>, schedules?: ReturnType<typeof createScheduleDoor> }} opts
96
+ * @param {{ port: number, version?: string, startedAt?: string, packageJsonPath?: string, authorRoutes?: ReturnType<typeof createAuthorRoutes>, schedules?: ReturnType<typeof createScheduleDoor> }} opts
95
97
  */
96
98
  function whoamiPayload(opts) {
97
99
  const drafts = opts.authorRoutes ? opts.authorRoutes.openDrafts() : 0;
98
100
  let schedules = 0;
99
101
  try { schedules = opts.schedules ? opts.schedules.scan().length : 0; } catch { schedules = 0; }
100
- return { app: 'bareloop', version: packageVersion(opts.packageJsonPath), pid: process.pid, port: opts.port, drafts, schedules };
102
+ return { app: 'bareloop', version: opts.version ?? packageVersion(opts.packageJsonPath), pid: process.pid, port: opts.port, drafts, schedules, ...(opts.startedAt ? { startedAt: opts.startedAt } : {}) };
101
103
  }
102
104
 
103
105
  /** Largest POST body the panel buffers (job cards are short prose); a bigger one is refused with 413. */
@@ -456,9 +458,10 @@ const GOAL_NOT_MET = new Set(['plan-red', 'check-red', 'step-red', 'escalated'])
456
458
  * @param {{outcome: string|null, stopReason: string|null, spentUsd: number|null, budgetUsd: number|null, lastEscalation?: any}} summary
457
459
  * @param {{died: boolean, lastThing: string|null}} death
458
460
  * @param {{resume?: {ok: boolean, why?: string}|null, destinationRefused?: string|null, moneyHalt?: boolean,
459
- * worktree?: {folder: string, repo: string, branch: string|null, exists: boolean}|null}} [o]
461
+ * worktree?: {folder: string, repo: string, branch: string|null, exists: boolean}|null, exportName?: string|null}} [o]
460
462
  * `worktree` (P6 item 1): the run's worktree in the person's repo, from {@link worktreeOfRun}; absent for every other run
461
- * @returns {{reason: string, next: string, line: string, actions: {id: string, label: string}[]}|null}
463
+ * `exportName` (PRD v1.114): the run's `job (run-N)` name; a green worktree run (a repo job) shows the export command to copy beside the merge text
464
+ * @returns {{reason: string, next: string, rows?: [string, string][], line: string, actions: {id: string, label: string}[]}|null}
462
465
  */
463
466
  export function endedFor(summary, death, o = {}) {
464
467
  const base = withReuseAction(endedBase(summary, death, o));
@@ -470,16 +473,46 @@ export function endedFor(summary, death, o = {}) {
470
473
  const green = !death.died && (summary.outcome === 'green' || summary.outcome === 'already-green' || summary.outcome === 'satisfied');
471
474
  if (green) {
472
475
  if (!wt.branch) return base;
473
- const kept = wt.exists ? ` The worktree folder ${wt.folder} is still there.` : '';
474
- return { ...base, next: `In ${wt.repo}: git merge ${wt.branch} — or throw the work away: git branch -D ${wt.branch}.${kept}` };
476
+ // one instruction per row (fwdloop's shape): `in:` names the repo as its own first row, then the commands, then the kept folder
477
+ return {
478
+ ...base,
479
+ ...splitNext([
480
+ ['in:', wt.repo],
481
+ ['keep the work:', `git merge ${wt.branch}`],
482
+ ['throw it away:', `git branch -D ${wt.branch}`],
483
+ ...(o.exportName ? [/** @type {[string, string]} */ (['reusable bundle:', `bareloop export "${o.exportName}" --out "${exportOutDefault(o.exportName)}"`])] : []),
484
+ ...(wt.exists ? [/** @type {[string, string]} */ (['folder still there:', wt.folder])] : []),
485
+ ]),
486
+ };
475
487
  }
488
+ // any other ending: the worktree folder stays (Resume needs it); a multi-instruction NEXT gets it as one more row
489
+ if (wt.exists && base.rows) return { ...base, ...splitNext([...base.rows, ['your work is in:', wt.folder]]) };
476
490
  return wt.exists ? { ...base, next: `${base.next} Your work is in ${wt.folder}.` } : base;
477
491
  }
478
492
 
493
+ /**
494
+ * A real relative folder for the export command, from the run's `job (run-N)` name: the job part with anything a shell would act on turned
495
+ * into `-`, so `--out "./<job>-bundle"` pastes as is; the person may change it. The name is quoted in the command too.
496
+ * @param {string} exportName
497
+ */
498
+ function exportOutDefault(exportName) {
499
+ const job = exportName.replace(/ \(run-\d+\)$/, '').replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'job';
500
+ return `./${job}-bundle`;
501
+ }
502
+
503
+ /**
504
+ * A NEXT with several instructions is `rows` of [label, instruction], one per line (label muted, instruction in a second column);
505
+ * `next` stays the one plain string every other reader gets: the rows joined "label instruction", one per line. The only writer of both
506
+ * (the shape fwdloop copied from bareloop 8cad363 and bareloop copied back, 2026-10-25).
507
+ * @param {[string, string][]} rows
508
+ * @returns {{next: string, rows: [string, string][]}}
509
+ */
510
+ function splitNext(rows) { return { next: rows.map(([l, x]) => `${l} ${x}`).join('\n'), rows }; }
511
+
479
512
  /**
480
513
  * ONE door (hamr 2026-10-15, v1.101): "Reuse workflow" is offered on EVERY ending (green, failed, capped, stopped, died, every other
481
514
  * red), after Resume when both show. ONE place, so no ending branch can forget it.
482
- * @param {{reason: string, next: string, line: string, actions: {id: string, label: string}[]}|null} ended
515
+ * @param {{reason: string, next: string, rows?: [string, string][], line: string, actions: {id: string, label: string}[]}|null} ended
483
516
  */
484
517
  function withReuseAction(ended) {
485
518
  if (!ended || ended.actions.some((a) => a.id === 'reuse')) return ended;
@@ -500,12 +533,14 @@ function endedBase(summary, death, o) {
500
533
  return s.length > 120 ? `${s.slice(0, 120)}…` : s;
501
534
  };
502
535
  /** a resumable ending whose Resume the engine would refuse: say so, never offer the button */
503
- const resumeOr = (/** @type {string} */ okNext) => (resumeOk ? okNext : `Resume is not available for this run${o.resume && o.resume.why ? ` (${o.resume.why})` : ''}. ${CHANGE}`);
536
+ const resumeOr = (/** @type {string} */ okNext) => ({ next: resumeOk ? okNext : `Resume is not available for this run${o.resume && o.resume.why ? ` (${o.resume.why})` : ''}. ${CHANGE}` });
537
+ /** the same, for a two-step ending: rows when the engine would accept the resume, else the one "not available" sentence */
538
+ const resumeRows = (/** @type {[string, string][]} */ rows) => (resumeOk ? splitNext(rows) : resumeOr(''));
504
539
 
505
540
  if (death.died) {
506
541
  return {
507
542
  reason: `Stopped with no ending recorded${death.lastThing ? ` (last thing it did: ${death.lastThing})` : ''}.`,
508
- next: resumeOr('Resume.'),
543
+ ...resumeOr('Resume.'),
509
544
  line: resumeOk ? 'no ending recorded — resume' : 'no ending recorded',
510
545
  actions: resumeOk ? RESUME : [],
511
546
  };
@@ -556,7 +591,7 @@ function endedBase(summary, death, o) {
556
591
  const earned = isReusableGreen(outcome);
557
592
  return {
558
593
  reason: 'Goal met, but the output could not be delivered.',
559
- next: earned ? 'Fix the destination, then Reuse workflow.' : CHANGE,
594
+ ...(earned ? splitNext([['fix the destination:', 'the Destination'], ['then:', 'press Reuse workflow']]) : { next: CHANGE }),
560
595
  line: `${GOAL_MET_LINE} — not delivered`,
561
596
  actions: earned ? REUSE : [],
562
597
  };
@@ -571,7 +606,7 @@ function endedBase(summary, death, o) {
571
606
  ? ` (${panelMoney2(summary.spentUsd)} of ${panelMoney2(summary.budgetUsd)})` : '';
572
607
  return {
573
608
  reason: `Money cap reached${money}.`,
574
- next: resumeOr('Raise the cap, then Resume.'),
609
+ ...resumeRows([['raise the cap:', 'Cap $ on the Chat card'], ['then:', 'press Resume']]),
575
610
  line: resumeOk ? 'money cap — resume' : 'money cap',
576
611
  actions: resumeOk ? RESUME : [],
577
612
  };
@@ -579,7 +614,7 @@ function endedBase(summary, death, o) {
579
614
  if (outcome === 'wall-halt') {
580
615
  return {
581
616
  reason: 'Time cap reached.',
582
- next: resumeOr('Raise the time, then Resume.'),
617
+ ...resumeRows([['raise the time:', 'Time cap (min) on the Chat card'], ['then:', 'press Resume']]),
583
618
  line: resumeOk ? 'time cap — resume' : 'time cap',
584
619
  actions: resumeOk ? RESUME : [],
585
620
  };
@@ -588,7 +623,7 @@ function endedBase(summary, death, o) {
588
623
  // P5 item 5: the PERSON ended the leg (Stop). Nothing failed; the finished steps stand.
589
624
  return {
590
625
  reason: 'You stopped it.',
591
- next: resumeOr('Resume.'),
626
+ ...resumeOr('Resume.'),
592
627
  line: resumeOk ? 'you pressed Stop — resume' : 'you pressed Stop',
593
628
  actions: resumeOk ? RESUME : [],
594
629
  };
@@ -597,7 +632,7 @@ function endedBase(summary, death, o) {
597
632
  const d = detailOf(summary.stopReason);
598
633
  return {
599
634
  reason: `The model provider failed${d ? ` (${d})` : ''}.`,
600
- next: resumeOr('Resume.'),
635
+ ...resumeOr('Resume.'),
601
636
  line: resumeOk ? 'provider failed — resume' : 'provider failed',
602
637
  actions: resumeOk ? RESUME : [],
603
638
  };
@@ -605,7 +640,7 @@ function endedBase(summary, death, o) {
605
640
  if (outcome === 'step-stalled') {
606
641
  return {
607
642
  reason: 'A step stopped making progress.',
608
- next: resumeOr('Resume, or change the job: press Reuse workflow.'),
643
+ ...resumeRows([['resume:', 'press Resume'], ['or change the job:', 'press Reuse workflow']]),
609
644
  line: resumeOk ? 'step stalled — resume' : 'step stalled',
610
645
  actions: resumeOk ? RESUME : [],
611
646
  };
@@ -688,7 +723,7 @@ function liveStepWhy(records, summary) {
688
723
  return `step ${Math.min(done + 1, total)} of ${total}`;
689
724
  }
690
725
 
691
- function endedForRow(row, records, summary, death, withWorktree = false) {
726
+ function endedForRow(row, records, summary, death, withWorktree = false, /** @type {string|null} */ exportName = null) {
692
727
  const out = summary.outcome;
693
728
  const maybeResumable = death.died || out === 'escalated' || (typeof out === 'string' && CHECKPOINT_OUTCOMES.includes(out));
694
729
  const resume = maybeResumable ? resumePlanFor(row, records) : null;
@@ -698,6 +733,7 @@ function endedForRow(row, records, summary, death, withWorktree = false) {
698
733
  moneyHalt: records.some((r) => r && r.type === 'money-halt'),
699
734
  destinationRefused: refused ? String(refused.detail ?? refused.code ?? 'the destination refused it') : null,
700
735
  worktree: withWorktree ? worktreeOfRun(row, records) : null,
736
+ exportName,
701
737
  });
702
738
  const esc = summary.lastEscalation;
703
739
  const status = statusFor({
@@ -935,40 +971,6 @@ export function getNeedsContext(runid, opts = {}) {
935
971
  return { row, needs: summarizeRow(row, nowMs, readNeedsRemovals(opts)).needs ?? null };
936
972
  }
937
973
 
938
- /**
939
- * @param {any} r
940
- * @returns {number}
941
- */
942
- function atMs(r) {
943
- const t = typeof r?.at === 'string' ? Date.parse(r.at) : NaN;
944
- return Number.isFinite(t) ? t : 0;
945
- }
946
-
947
- /**
948
- * The ONE owner of run names (P6 item 7): runs of the same job (`row.job`) are numbered oldest `at` first, 1-based
949
- * (ties keep file order). A resume is one row, so it counts once; died and stopped runs are rows too. Every view
950
- * reads this number — the page never counts on its own.
951
- * @param {any[]} rows
952
- * @returns {Map<string, number>} runid → N
953
- */
954
- function runNumbers(rows) {
955
- /** @type {Map<string, any[]>} */
956
- const byJob = new Map();
957
- rows.forEach((row, index) => {
958
- if (!row || typeof row.runid !== 'string') return;
959
- const g = byJob.get(row.job) || [];
960
- g.push({ row, index });
961
- byJob.set(row.job, g);
962
- });
963
- /** @type {Map<string, number>} */
964
- const out = new Map();
965
- for (const g of byJob.values()) {
966
- g.sort((a, b) => (atMs(a.row) - atMs(b.row)) || (a.index - b.index));
967
- g.forEach(({ row }, i) => out.set(row.runid, i + 1));
968
- }
969
- return out;
970
- }
971
-
972
974
  /** The named limits of the runs list, in ONE place (P9 v2 D.13): quiet after 30 days, 7 older runs shown, a Resume tag ages out after 7 days. Sent in `GET /api/runs`; the page reads them from there. */
973
975
  export const RUNS_LIST_LIMITS = Object.freeze({ quietDays: 30, olderRuns: 7, needsYouDays: 7 });
974
976
 
@@ -1522,22 +1524,22 @@ export function getRunDownload(runid, index, opts = {}) {
1522
1524
  export function getRunDetail(runid, opts = {}) {
1523
1525
  const d = getRunDetailBody(runid, opts);
1524
1526
  if (!d) return d;
1525
- const { rows } = readRunList(opts);
1527
+ const { rows, events } = readRunList(opts);
1526
1528
  const nos = runNumbers(rows);
1527
1529
  const runNo = nos.get(runid);
1528
1530
  // T Part 7: what the Run tab shows of the job's schedule — the SERVER decides every state and word (the page works out nothing)
1529
1531
  const schedule = opts.schedules && typeof d.job === 'string' ? scheduleDetailFor(d.job, rows, nos, opts) : null;
1530
- const extra = opts.schedules && typeof d.job === 'string' ? scheduleExtrasFor(runid, d.job, rows, nos, opts, schedule) : {};
1532
+ const extra = opts.schedules && typeof d.job === 'string' ? scheduleExtrasFor(runid, d.job, rows, events, nos, opts, schedule) : {};
1531
1533
  return { ...d, ...(runNo === undefined ? {} : { runNo }), ...(schedule ? { schedule: extra.schedule ?? schedule } : {}), ...(extra.audit ?? {}) };
1532
1534
  }
1533
1535
 
1534
1536
  /**
1535
1537
  * Aligned with fwdloop M9 am7: the SCHEDULE row's second line and the Audit's schedule rows, made on the server from the door's data.
1536
1538
  * `schedule` = the door's view with `line2`, `problem` (and no raw ledger row); `audit` = `{scheduleSection}` or, for a run a cancelled schedule started, `{startedAudit}`.
1537
- * @param {string} runid @param {string} job @param {any[]} rows @param {Map<string, number>} nos @param {any} opts @param {any} view
1539
+ * @param {string} runid @param {string} job @param {any[]} rows @param {any[]} events @param {Map<string, number>} nos @param {any} opts @param {any} view
1538
1540
  * @returns {{schedule?: any, audit?: {startedAudit?: string, scheduleSection?: any}}}
1539
1541
  */
1540
- function scheduleExtrasFor(runid, job, rows, nos, opts, view) {
1542
+ function scheduleExtrasFor(runid, job, rows, events, nos, opts, view) {
1541
1543
  try {
1542
1544
  const door = /** @type {ReturnType<typeof createScheduleDoor>} */ (opts.schedules);
1543
1545
  /** @type {any} */
@@ -1560,7 +1562,7 @@ function scheduleExtrasFor(runid, job, rows, nos, opts, view) {
1560
1562
  const got = hit ?? fallback;
1561
1563
  const no = got ? nos.get(got.r.runid) : undefined;
1562
1564
  // events: a fire refused at the run-start fetch has no spine, only its settled event; without them it has no status word
1563
- const word = got ? summarizeRow(got.r, Date.now(), undefined, readRunList(opts).events).status?.word : undefined;
1565
+ const word = got ? summarizeRow(got.r, Date.now(), undefined, events).status?.word : undefined;
1564
1566
  lastWords = `last ${dateTimeWords(Number(lastRow.at))}${no ? ` · run-${no}` : ''}${word ? ` · ${word}` : ''}${got?.rec.catchUp === true ? ' · catch-up' : ''}`;
1565
1567
  } else {
1566
1568
  lastWords = `last ${dateTimeWords(Number(lastRow.at))} · ${skippedWords(lastRow, true)}`;
@@ -1630,7 +1632,10 @@ function getRunDetailBody(runid, opts) {
1630
1632
  const specForParts = resolveSpecForRow(row);
1631
1633
  const enrichedParts = enrichPartsWithStageKind(summary.parts, stageKindMetaFromSpec(specForParts), specForParts);
1632
1634
  const death = deriveDeath(row, rawSpineRecords, summary.outcome);
1633
- const { ended, resume, status } = endedForRow(row, rawSpineRecords, summary, death, true);
1635
+ const runName = runNameOf(row.job, runNumbers(readRunList(opts).rows).get(row.runid));
1636
+ // the export row only for a run export would take — the one rule, `checkExportable`, never a copy of it
1637
+ const exportName = checkExportable(row, runName).ok ? runName : null;
1638
+ const { ended, resume, status } = endedForRow(row, rawSpineRecords, summary, death, true, exportName);
1634
1639
  // judgeModel (Summary box "judge:" line): the FIRST `judge-round`'s own
1635
1640
  // `model` field (src/planrun.js:1704's `onJudgeCost` emit) — a soft-green
1636
1641
  // close's own paid judge seam, distinct from the worker `model` above.
@@ -1884,6 +1889,8 @@ function getRunDetailBody(runid, opts) {
1884
1889
  // Cross-run learnings, READ-ONLY (ITEM33 rev 2, RULING 8): the exact block the planner was handed, as the spine recorded it at
1885
1890
  // injection (the draft, and the first replan); `hints` = the same text split into fields by learn.js's parseHintBlock (the one reader). Empty when the setting was off or nothing was readable.
1886
1891
  learnings: rawSpineRecords.filter((e) => e?.type === 'learnings' && typeof e.text === 'string').map((e) => ({ phase: String(e.phase), text: e.text, chars: e.text.length, ids: Array.isArray(e.ids) ? e.ids : [], hints: parseHintBlock(e.text) })),
1892
+ // a learnings file that could not be read: the plain line (null when it could)
1893
+ learningsError: ((r) => (r ? hintsErrorLine(String(r.hintsError)) : null))(rawSpineRecords.find((e) => e?.type === 'learnings' && typeof e.hintsError === 'string')),
1887
1894
  // PRD v1.106 Part 5 F: the two Run summary rows, worded here (the page prints them)
1888
1895
  callsLine: callsLineOf(rawSpineRecords, scopedBehaviour(row, rawSpineRecords)),
1889
1896
  checksLine: checksLineOf(rawSpineRecords, enrichedParts),
@@ -2534,39 +2541,6 @@ function bundleDirForSpine(spinePath) {
2534
2541
  return dirname(runsDir); // <x>/runs -> <x>
2535
2542
  }
2536
2543
 
2537
- /**
2538
- * `<out>/source-<seed>/<job>-bareloop/u-<runid>.jsonl` -> the two files an
2539
- * authoring session leaves BESIDE that layout — `<out>/resolved-spec.json`
2540
- * (the signed spec `--spec`/a JOBS-table row ran) and
2541
- * `<out>/source-<seed>/source.json` (the source front door's manifest) —
2542
- * verified against `src/userrun.js`'s own construction (`specWorkdir = join(into,
2543
- * 'tree')`, `spineDir = join(wd, '..', target.spine)`, both `--spec` and the
2544
- * `pulselog-person-strict` JOBS-table row read `into` the same way) and a real
2545
- * archived run (pulselog-person-live-2, run mu2p83go): `dirname(spine)` is
2546
- * `<into>/<job>-bareloop`, `dirname(dirname(spine))` is `<into>` itself
2547
- * (`source-<seed>`, carrying `source.json`), and `dirname(dirname(dirname(spine)))`
2548
- * is `<out>` (carrying `resolved-spec.json`).
2549
- *
2550
- * Only resolves when `<into>`'s own name starts with `source-` — the one
2551
- * shape marker this convention always carries — and each file is checked to
2552
- * actually exist before being handed back; any other spine layout (the bundle
2553
- * `spine.jsonl`, a JOBS-table row whose workdir has no source-seed copy, e.g.
2554
- * `litectx-u`) returns both fields `null`, never a guessed path (build spec
2555
- * item 2, 2026-09-25: "don't search the disk broadly — fall through").
2556
- * @param {string} spinePath
2557
- * @returns {{ specPath: string|null, sourceJsonPath: string|null }}
2558
- */
2559
- function sourceNearSpine(spinePath) {
2560
- const into = dirname(dirname(spinePath)); // <into>/<job>-bareloop/u-x.jsonl -> <into>
2561
- if (!basename(into).startsWith('source-')) return { specPath: null, sourceJsonPath: null };
2562
- const sourceJsonPath = join(into, 'source.json');
2563
- const specPath = join(dirname(into), 'resolved-spec.json'); // <into> -> <out>
2564
- return {
2565
- specPath: existsSync(specPath) ? specPath : null,
2566
- sourceJsonPath: existsSync(sourceJsonPath) ? sourceJsonPath : null,
2567
- };
2568
- }
2569
-
2570
2544
  /**
2571
2545
  * P6 item 1 — the worktree a run worked on in the person's own repo, read off the run's own `source.json` (the manifest
2572
2546
  * the source door wrote: `worktree` + `repo`) and its spine's `work-branch` record. `null` for every run that has none
@@ -3355,31 +3329,6 @@ function getRunJobBody(runid, opts) {
3355
3329
  // Nothing here drafts: changing the goal, checks, guardrails, judge examples or model is Clear (then draft).
3356
3330
  // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
3357
3331
 
3358
- /**
3359
- * The signed spec a run's LATEST leg ran under — the `resolved-spec*.json` beside the run whose hash is the one its
3360
- * latest `job-start` carries (the same lookup `resumePlanFor` does). `null` = no such file.
3361
- * @param {{ spine: string }} row
3362
- * @param {any[]} records
3363
- * @returns {{spec: any, specPath: string, specHash: string}|null}
3364
- */
3365
- function signedSpecForRun(row, records) {
3366
- const jobStart = (legsOf(records).findLast((l) => l.jobStart !== null) ?? null)?.jobStart ?? null;
3367
- if (!jobStart || typeof jobStart.specHash !== 'string') return null;
3368
- const near = sourceNearSpine(row.spine);
3369
- if (!near.specPath) return null;
3370
- const dir = dirname(near.specPath);
3371
- /** @type {string[]} */
3372
- let names = [];
3373
- try { names = readdirSync(dir).filter((n) => n === 'resolved-spec.json' || /^resolved-spec-r\d+\.json$/.test(n)); } catch { names = []; }
3374
- for (const n of names) {
3375
- let spec;
3376
- try { spec = JSON.parse(readFileSync(join(dir, n), 'utf8')); } catch { continue; }
3377
- if (!spec || typeof spec !== 'object') continue;
3378
- if (jobSpecHash(spec) === jobStart.specHash) return { spec, specPath: join(dir, n), specHash: jobStart.specHash };
3379
- }
3380
- return null;
3381
- }
3382
-
3383
3332
  /**
3384
3333
  * The worker a signed spec ran: provider, baseUrl and model ('' when an older spec names none: bareloop keeps no default).
3385
3334
  * @param {any} spec
@@ -3743,7 +3692,7 @@ function sendText(res, code, text) {
3743
3692
  * only `createPanelServer` below always supplies one.
3744
3693
  * @param {import('node:http').IncomingMessage} req
3745
3694
  * @param {import('node:http').ServerResponse} res
3746
- * @param {{ home?: string, sessionsRoot?: string, packageJsonPath?: string, port: number, token?: string, authorRoutes?: ReturnType<typeof createAuthorRoutes>, settingsRoutes?: ReturnType<typeof createSettingsRoutes>, runRoutes?: ReturnType<typeof createRunRoutes>, importRoutes?: ReturnType<typeof createImportRoutes>, schedules?: ReturnType<typeof createScheduleDoor> }} opts
3695
+ * @param {{ home?: string, sessionsRoot?: string, version?: string, startedAt?: string, packageJsonPath?: string, port: number, token?: string, authorRoutes?: ReturnType<typeof createAuthorRoutes>, settingsRoutes?: ReturnType<typeof createSettingsRoutes>, runRoutes?: ReturnType<typeof createRunRoutes>, importRoutes?: ReturnType<typeof createImportRoutes>, schedules?: ReturnType<typeof createScheduleDoor> }} opts
3747
3696
  */
3748
3697
  export function handleRequest(req, res, opts) {
3749
3698
  /** the ONE writable route family for a path, or null — `/api/author/*` (authoring) or
@@ -3839,9 +3788,9 @@ export function handleRequest(req, res, opts) {
3839
3788
  return;
3840
3789
  }
3841
3790
  html = html.replace(/__BARELOOP_PANEL_PORT__/g, String(opts.port));
3842
- // the topbar reads `bareloop · v<version> · ...`: the version is bareloop's OWN package.json, read when the page is served
3791
+ // the topbar reads `bareloop · v<version> · ...`: the version is bareloop's OWN package.json, read once when the panel starts
3843
3792
  // and templated in exactly like the port — never written into the HTML
3844
- html = html.replace(/__BARELOOP_PANEL_VERSION__/g, packageVersion(opts.packageJsonPath));
3793
+ html = html.replace(/__BARELOOP_PANEL_VERSION__/g, opts.version ?? packageVersion(opts.packageJsonPath));
3845
3794
  // PANEL-BUILD.md P3's human-click guard: a per-server-start token,
3846
3795
  // templated into the page exactly like the port — absent on every P1/P2
3847
3796
  // caller (no `opts.token`), which is fine: the page's own JS only reads
@@ -3968,6 +3917,10 @@ export function createPanelServer(opts = {}) {
3968
3917
  const requestedPort = opts.port ?? DEFAULT_PORT;
3969
3918
  const home = opts.home;
3970
3919
  const token = mintToken();
3920
+ // the version THIS process runs, read once at start: package.json on disk can move on while the panel keeps running old code
3921
+ const version = packageVersion(opts.packageJsonPath);
3922
+ // when THIS process started, ISO, set once here (`GET /api/whoami`'s `startedAt`: the launcher shows it)
3923
+ const startedAt = new Date().toISOString();
3971
3924
  return new Promise((resolve, reject) => {
3972
3925
  // Bound port is resolved from the live socket (`server.address().port`)
3973
3926
  // once listening starts, not the requested value — this is what makes
@@ -3990,7 +3943,7 @@ export function createPanelServer(opts = {}) {
3990
3943
  const server = createServer((req, res) => {
3991
3944
  try {
3992
3945
  handleRequest(req, res, {
3993
- home, sessionsRoot: opts.sessionsRoot, port: boundPort, token, authorRoutes, settingsRoutes, runRoutes, importRoutes, packageJsonPath: opts.packageJsonPath, schedules: schedulesRef,
3946
+ home, sessionsRoot: opts.sessionsRoot, port: boundPort, token, authorRoutes, settingsRoutes, runRoutes, importRoutes, version, startedAt, packageJsonPath: opts.packageJsonPath, schedules: schedulesRef,
3994
3947
  });
3995
3948
  } catch (e) {
3996
3949
  sendText(res, 500, `internal error: ${/** @type {Error} */ (e).message}`);