bareloop 0.47.1 → 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.
package/src/invoke.js CHANGED
@@ -16,7 +16,8 @@ const SCRIPT = /** @type {const} */ ({ 'run-u': 'run-u', interview: 'run-intervi
16
16
  * @returns {string}
17
17
  */
18
18
  export function commandFor(flow, invokedAs) {
19
- return invokedAs !== undefined && /^bareloop(\s|$)/.test(invokedAs)
20
- ? `bareloop ${flow}`
19
+ // `interview` and `author` left the `bareloop` CLI (PRD v1.114): they are only ever the source-tree scripts
20
+ return flow === 'run-u' && invokedAs !== undefined && /^bareloop(\s|$)/.test(invokedAs)
21
+ ? 'bareloop run-u'
21
22
  : `node scripts/${SCRIPT[flow]}.mjs`;
22
23
  }
package/src/launcher.js CHANGED
@@ -18,6 +18,7 @@ import { keysHome, keysFilePath, ensureKeysFile } from './keysfile.js';
18
18
  import { openInOs } from './opener.js';
19
19
  import { PLAIN } from './tty-colour.js';
20
20
  import { runsListForCount, packageVersion, panelUrl } from './panel/server.js';
21
+ import { dateTimeWords } from './schedulewords.js';
21
22
 
22
23
  const HERE = dirname(fileURLToPath(import.meta.url));
23
24
  /** the first port tried, and how many in a row (4700..4709) */
@@ -35,6 +36,7 @@ const RULE_WIDTH = 56;
35
36
  * @typedef {object} Panel one answered probe
36
37
  * @property {number} port @property {number} pid @property {string} version @property {number} drafts @property {number} schedules
37
38
  * @property {string} url
39
+ * @property {string|null} [startedAt] ISO time the panel process started (`whoami`); absent on an older panel
38
40
  */
39
41
 
40
42
  /**
@@ -124,6 +126,7 @@ export async function probePort(o) {
124
126
  drafts: Number(j.drafts) || 0,
125
127
  schedules: Number(j.schedules) || 0,
126
128
  url: panelUrl(port),
129
+ startedAt: typeof j.startedAt === 'string' && Number.isFinite(Date.parse(j.startedAt)) ? j.startedAt : null,
127
130
  },
128
131
  };
129
132
  } catch (e) {
@@ -142,6 +145,12 @@ export async function probePanels(o) {
142
145
  return /** @type {Panel[]} */ (answers.flatMap((a) => (a.state === 'panel' ? [a.panel] : [])));
143
146
  }
144
147
 
148
+ /**
149
+ * ` · started 10/24 21:40` (local, the panel's own date style: `dateTimeWords`); '' for an older panel that reports no start time.
150
+ * @param {Panel} p @returns {string}
151
+ */
152
+ const startedWords = (p) => (p.startedAt ? ` · started ${dateTimeWords(Date.parse(p.startedAt))}` : '');
153
+
145
154
  /** @param {LauncherDeps} d @returns {number[]} */
146
155
  function portsOf(d) {
147
156
  if (d.ports) return d.ports;
@@ -168,8 +177,8 @@ export async function buildHeader(d) {
168
177
  const sep = P.grey(' · ');
169
178
  const where = panels.length === 0
170
179
  ? `panel ${P.grey('not running')}`
171
- : `panel${panels.length > 1 ? 's' : ''} ${P.green('running')} at ${panels.map((p) => P.cyan(p.url) + (p.version !== version ? P.yellow(` (version ${p.version} — stop and start to use ${version})`) : '')).join(', ')}`;
172
- const state = inst.ok ? P.green('installed ✓') : `${P.red('not installed')} — ${inst.problem}, pick ${P.boldCyan('4')} install`;
180
+ : `panel${panels.length > 1 ? 's' : ''} ${P.green('running')} at ${panels.map((p) => P.cyan(p.url) + (p.startedAt ? P.grey(startedWords(p)) : '') + (p.version !== version ? P.yellow(` (version ${p.version} — stop and start to use ${version})`) : '')).join(', ')}`;
181
+ const state = inst.ok ? P.green('installed ✓') : `${P.red('not installed')} — ${inst.problem}, pick ${P.boldCyan('5')} install`;
173
182
  const first = `${P.boldCyan('bareloop')} ${P.grey(version)}${sep}${state}${sep}${where}`;
174
183
  let second;
175
184
  try {
@@ -276,7 +285,7 @@ export async function statusCmd(io, d, shown) {
276
285
  return shown ? 0 : 3;
277
286
  }
278
287
  for (const p of h.panels) {
279
- const body = `pid ${p.pid} · version ${p.version} · ${plural(p.drafts, 'draft', 'drafts')} open · ${plural(p.schedules, 'schedule', 'schedules')} on`;
288
+ const body = `pid ${p.pid} · version ${p.version} · ${plural(p.drafts, 'draft', 'drafts')} open · ${plural(p.schedules, 'schedule', 'schedules')} on${startedWords(p)}`;
280
289
  io.out(h.panels.length > 1 ? `${p.url} · ${body}` : body);
281
290
  }
282
291
  return 0;
@@ -352,7 +361,7 @@ export async function startCmd(io, d, shown) {
352
361
  const verdict = await askTakenPort(d, p);
353
362
  if (verdict.state === 'panel') return alreadyRunning(verdict.panel);
354
363
  if (verdict.state === 'silent') {
355
- fail(io, d, `Port ${p} is taken and not answering. If it's a stuck bareloop, stop it first.`);
364
+ fail(io, d, `Port ${p} is taken and not answering. To see what holds it: lsof -i :${p}. If it is a stuck bareloop, end it: kill <pid>`);
356
365
  return 1;
357
366
  }
358
367
  }
@@ -452,8 +461,33 @@ export async function stopCmd(args, io, d, shown) {
452
461
  }
453
462
 
454
463
  /**
455
- * The bare `bareloop` menu: header, the four choices, one question. Runs the chosen command and returns its exit code.
456
- * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d
464
+ * `bareloop restart [--yes]` — the existing stop (same open-drafts warning and ask; `--yes` skips it), then the existing start, on the
465
+ * port the panel had when it is free again (else the normal first-free-port rule). No panel running: says so and just starts.
466
+ * No new process model, no pid file.
467
+ * @param {string[]} args
468
+ * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d @param {{lines: string[], panels: Panel[]}} [shown]
469
+ * @returns {Promise<number>}
470
+ */
471
+ export async function restartCmd(args, io, d, shown) {
472
+ const h = await headerOnce(io, d, shown);
473
+ if (h.panels.length === 0) {
474
+ io.out('Panel not running — starting it.');
475
+ return startCmd(io, d, { lines: h.lines, panels: [] });
476
+ }
477
+ const rc = await stopCmd(args, io, d, h);
478
+ if (rc !== 0) return rc;
479
+ // a declined "Stop the panel?" is exit 0 too: only start when the panel is really gone
480
+ if ((await probeAll(d)).length > 0) return 0;
481
+ const was = h.panels[0].port;
482
+ const ports = [was, ...portsOf(d).filter((p) => p !== was)];
483
+ return startCmd(io, { ...d, ports }, { lines: h.lines, panels: [] });
484
+ }
485
+
486
+ /**
487
+ * The bare `bareloop` menu (PRD v1.114, one menu): the panel's four choices, the four job commands, one question. Runs the chosen command
488
+ * and returns its exit code. The job commands (6 export, 7 run, 8 resume, 9 history) are `d.jobs`, supplied by the CLI: each prompts for
489
+ * what it needs on the same asker this menu uses.
490
+ * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string, jobs?: {export: () => Promise<number>, run: () => Promise<number>, resume: () => Promise<number>, history: () => Promise<number>}}} d
457
491
  * @returns {Promise<number>}
458
492
  */
459
493
  export async function menuCmd(io, d) {
@@ -463,15 +497,21 @@ export async function menuCmd(io, d) {
463
497
  const P = d.paint ?? PLAIN;
464
498
  if (!P.on) io.out('');
465
499
  const n = (/** @type {string} */ k) => P.boldCyan(k);
466
- const items = `${n('1')} start ${n('2')} stop ${n('3')} status ${n('4')} install ${n('q')} quit`;
467
- io.out(P.on ? ` ${items}` : items);
500
+ const ind = P.on ? ' ' : '';
501
+ io.out(`${ind}panel: ${n('1')} start ${n('2')} stop ${n('3')} restart ${n('4')} status ${n('5')} install`);
502
+ io.out(`${ind}jobs: ${n('6')} export ${n('7')} run ${n('8')} resume ${n('9')} history`);
503
+ io.out(`${ind}${n('q')} quit`);
468
504
  const choice = ask ? (await ask(`${P.cyan('>')} `)).trim().toLowerCase() : 'q';
469
505
  // the header is already on screen: the chosen command reuses it instead of printing it a second time
470
506
  if (choice === '1' || choice === 'start') return startCmd(io, d, h);
471
507
  if (choice === '2' || choice === 'stop') return stopCmd([], io, d, h);
472
- if (choice === '3' || choice === 'status') return statusCmd(io, d, h);
473
- if (choice === '4' || choice === 'install') return installCmd(io, d, h);
508
+ if (choice === '3' || choice === 'restart') return restartCmd([], io, d, h);
509
+ if (choice === '4' || choice === 'status') return statusCmd(io, d, h);
510
+ if (choice === '5' || choice === 'install') return installCmd(io, d, h);
511
+ const jobChoices = { 6: 'export', export: 'export', 7: 'run', run: 'run', 8: 'resume', resume: 'resume', 9: 'history', history: 'history' };
512
+ const job = Object.hasOwn(jobChoices, choice) ? jobChoices[choice] : undefined; // never `constructor` / `__proto__`
513
+ if (job !== undefined && d.jobs) return d.jobs[/** @type {'export'|'run'|'resume'|'history'} */ (job)]();
474
514
  if (choice === '' || choice === 'q' || choice === 'quit') return 0;
475
- fail(io, d, `unknown choice ${JSON.stringify(choice)} — one of: 1, 2, 3, 4, q`);
515
+ fail(io, d, `unknown choice ${JSON.stringify(choice)} — one of: 1, 2, 3, 4, 5, 6, 7, 8, 9, q`);
476
516
  return 1;
477
517
  }
package/src/learn.js CHANGED
@@ -15,6 +15,7 @@
15
15
  // Graduated from the proofs in .claude/scratch/poc-learn/ (pocA2 candidates, pocC cards, pocE2 fold) as a REWRITE.
16
16
  // The 60% threshold is FITTED on known cards (a fit, not a proof; the unseen-card proof is OPEN 2).
17
17
 
18
+ import { homedir } from 'node:os';
18
19
  import { redactSecrets } from './validate.js';
19
20
 
20
21
  // ── constants (every number here is a ruling, not a tuning knob) ─────────────────────────────────
@@ -555,13 +556,14 @@ export function foldCards(cards) {
555
556
  * @property {string[]} runIds
556
557
  * @property {string} firstSeen
557
558
  * @property {string} lastSeen
558
- * @property {string|null} specHash the signed hash the lesson was last seen under (a workflow row of another hash is never matched or read)
559
+ * @property {string|null} specHash the signed hash the lesson was last seen under (a record only; the job version is `workflowKey`)
560
+ * @property {string|null} [workflowKey] the workflow key (Reuse's rule: caps, time, source, destination, inputs and model do not move it) the lesson was last seen under; a workflow row of another key is never matched or read. Absent on rows an older version wrote: those match any version
559
561
  * @property {string} key check + sorted kinds (job-independent); information only since R2 removed the check-wide set-aside
560
562
  */
561
563
  /**
562
564
  * @typedef {object} Pending
563
565
  * @property {string} runid @property {string} at @property {string} workflow @property {string|null} place
564
- * @property {string|null} specHash @property {Card[]} cards
566
+ * @property {string|null} specHash @property {string|null} [workflowKey] @property {Card[]} cards
565
567
  */
566
568
  /**
567
569
  * @typedef {object} Ledger
@@ -606,11 +608,12 @@ function rowId(c) {
606
608
  export const isDecayed = (r, now) => { const t = Date.parse(r.lastSeen); return Number.isFinite(t) && now.getTime() - t > DECAY_DAYS * DAY_MS; };
607
609
 
608
610
  /**
609
- * Is this workflow row from another job version (a different signed hash than this run's)? Decided from the stored
610
- * `specHash`, read-time, never stored. Unknown hash on either side is the same version.
611
- * @param {Row} r @param {string} workflow @param {string|null} specHash
611
+ * Is this workflow row from another job version (a different workflow key than this run's)? Decided from the stored
612
+ * `workflowKey`, read-time, never stored. The key ignores the Reuse-editable fields (caps, source, destination, inputs, model), so a
613
+ * Reuse with a new cap is the same version. An unknown key on either side (a row an older version wrote) is the same version.
614
+ * @param {Row} r @param {string} workflow @param {string|null|undefined} workflowKey
612
615
  */
613
- export const otherJobVersion = (r, workflow, specHash) => r.level === 'workflow' && r.workflow === workflow && r.specHash !== null && specHash !== null && r.specHash !== specHash;
616
+ export const otherJobVersion = (r, workflow, workflowKey) => r.level === 'workflow' && r.workflow === workflow && r.workflowKey != null && workflowKey != null && r.workflowKey !== workflowKey;
614
617
 
615
618
  /** Drop the retired stored `status`/`expiredBy` fields an older ledger file may carry, and reset a stored `level` (never read; stripped on the next write). @param {Row} r */
616
619
  const stripLegacy = (r) => { const { status: _s, expiredBy: _e, ...rest } = /** @type {Row & {status?: unknown, expiredBy?: unknown}} */ (r); return /** @type {Row} */ ({ ...rest, level: 'workflow' }); };
@@ -623,19 +626,19 @@ const byRank = (/** @type {Row} */ a, /** @type {Row} */ b) => b.count - a.count
623
626
  *
624
627
  * +1 per RUN per row: the run's own cards are folded into lessons first, and a row whose `runIds` already holds the
625
628
  * run id is never counted twice (a resumed run, one id, never double counts) but IS refreshed: the resumed leg's card
626
- * replaces the sample, lesson, key, lastSeen, hash and place (a leg-1 NEVER FIXED row becomes the leg-2 FIXED one). A
629
+ * replaces the sample, lesson, key, lastSeen, hash, key and place (a leg-1 NEVER FIXED row becomes the leg-2 FIXED one). A
627
630
  * matching lesson replaces the row's sample, bumps the model count and appends the run id (a row last seen 56+ days ago counts +1 and is read again);
628
631
  * otherwise it opens a new row at count 1. NEVER FIXED cards count like FIXED ones (RULING 3). A workflow row of
629
- * another signed hash is never matched here: the new version opens its own rows. Nothing is ever deleted or stamped.
632
+ * another workflow key is never matched here: the new version opens its own rows. Nothing is ever deleted or stamped.
630
633
  * @param {Ledger} ledger
631
- * @param {{runid: string, cards: Card[], workflow: string, place: string|null, specHash: string|null, trust: 'deterministic'|'rubric', now: Date}} o
634
+ * @param {{runid: string, cards: Card[], workflow: string, place: string|null, specHash: string|null, workflowKey?: string|null, trust: 'deterministic'|'rubric', now: Date}} o
632
635
  * @returns {Ledger}
633
636
  */
634
- export function countLedger(ledger, { runid, cards, workflow, place, specHash, trust, now }) {
637
+ export function countLedger(ledger, { runid, cards, workflow, place, specHash, workflowKey = null, trust, now }) {
635
638
  const rows = ledger.rows.map((r) => ({ ...stripLegacy(r), runIds: [...r.runIds], models: { ...r.models } }));
636
639
  for (const group of foldCards(cards)) {
637
640
  const rep = group.reduce((a, c) => (c.at >= a.at ? c : a));
638
- const hit = [...rows].sort(byRank).find((r) => r.workflow === workflow && !otherJobVersion(r, workflow, specHash) && cardsMatch(rep, r.sample).match);
641
+ const hit = [...rows].sort(byRank).find((r) => r.workflow === workflow && !otherJobVersion(r, workflow, workflowKey) && cardsMatch(rep, r.sample).match);
639
642
  if (hit) {
640
643
  // A row already holding this run id is the run's OWN row (a resumed leg re-reads the whole spine): refresh it from
641
644
  // the new card, but the count, the model tally and the run id stay one per run.
@@ -652,6 +655,7 @@ export function countLedger(ledger, { runid, cards, workflow, place, specHash, t
652
655
  hit.key = keyOfCard(rep);
653
656
  hit.lastSeen = rep.at;
654
657
  hit.specHash = specHash;
658
+ hit.workflowKey = workflowKey;
655
659
  hit.place = place ?? hit.place;
656
660
  }
657
661
  } else {
@@ -659,7 +663,7 @@ export function countLedger(ledger, { runid, cards, workflow, place, specHash, t
659
663
  for (let n = 2; rows.some((r) => r.id === id); n += 1) id = `${rowId(rep)}-${n}`;
660
664
  rows.push({
661
665
  id, lesson: lessonOf(rep), count: 1, sample: rep, models: { [rep.model ?? 'unknown']: 1 }, workflow, place, level: 'workflow',
662
- trust, runIds: [runid], firstSeen: rep.at, lastSeen: rep.at, specHash, key: keyOfCard(rep),
666
+ trust, runIds: [runid], firstSeen: rep.at, lastSeen: rep.at, specHash, workflowKey, key: keyOfCard(rep),
663
667
  });
664
668
  }
665
669
  }
@@ -723,12 +727,12 @@ export function climb(rows) {
723
727
  * Hold a run's cards until a human Accept. NO LONGER CALLED for new runs (v1.112: a rubric run's lessons count at run
724
728
  * end); kept so a hold already in a ledger file still has a writer for tests and a reader in {@link releasePending}. Pure.
725
729
  * @param {Ledger} ledger
726
- * @param {{runid: string, cards: Card[], workflow: string, place: string|null, specHash: string|null, at: string}} o
730
+ * @param {{runid: string, cards: Card[], workflow: string, place: string|null, specHash: string|null, workflowKey?: string|null, at: string}} o
727
731
  * @param {Date} now @returns {Ledger}
728
732
  */
729
- export function holdPending(ledger, { runid, cards, workflow, place, specHash, at }, now) {
733
+ export function holdPending(ledger, { runid, cards, workflow, place, specHash, workflowKey = null, at }, now) {
730
734
  const pending = ledger.pending.filter((p) => p.runid !== runid);
731
- if (cards.length) pending.push({ runid, at, workflow, place, specHash, cards });
735
+ if (cards.length) pending.push({ runid, at, workflow, place, specHash, workflowKey, cards });
732
736
  return finish({ ...ledger, pending }, now);
733
737
  }
734
738
 
@@ -743,7 +747,7 @@ export function releasePending(ledger, runid, now) {
743
747
  if (!p) return { ledger, released: 0 };
744
748
  const rest = { ...ledger, pending: ledger.pending.filter((x) => x.runid !== runid) };
745
749
  if (now.getTime() - Date.parse(p.at) > PENDING_DAYS * DAY_MS) return { ledger: finish(rest, now), released: 0 };
746
- const counted = countLedger(rest, { runid, cards: p.cards, workflow: p.workflow, place: p.place, specHash: p.specHash, trust: 'rubric', now });
750
+ const counted = countLedger(rest, { runid, cards: p.cards, workflow: p.workflow, place: p.place, specHash: p.specHash, workflowKey: p.workflowKey ?? null, trust: 'rubric', now });
747
751
  return { ledger: counted, released: p.cards.length };
748
752
  }
749
753
 
@@ -854,13 +858,13 @@ function hintText(r, n) {
854
858
  * derived HERE by {@link climb} over the rows not decayed at `now` only; the stored level is never read.
855
859
  * Order: this job's, then this place's, then all-jobs LAST (R2: climbing wins, so an all-jobs hint only uses leftover
856
860
  * room); inside each level highest count first (ties: most recent lastSeen, then id), so the order is total and stable.
857
- * @param {Ledger} ledger @param {{workflow: string, place: string|null, specHash?: string|null, now: Date}} o
861
+ * @param {Ledger} ledger @param {{workflow: string, place: string|null, workflowKey?: string|null, now: Date}} o
858
862
  * @returns {Row[]}
859
863
  */
860
- export function readableRows(ledger, { workflow, place, specHash = null, now }) {
864
+ export function readableRows(ledger, { workflow, place, workflowKey = null, now }) {
861
865
  return climb(ledger.rows.filter((r) => !isDecayed(r, now))).filter((r) => {
862
866
  if (r.runIds.length === 0) return false;
863
- if (r.level === 'workflow') return r.workflow === workflow && !otherJobVersion(r, workflow, specHash);
867
+ if (r.level === 'workflow') return r.workflow === workflow && !otherJobVersion(r, workflow, workflowKey);
864
868
  if (r.level === 'place') return place !== null && r.place === place;
865
869
  return true;
866
870
  }).sort((a, b) => LEVEL_RANK[a.level] - LEVEL_RANK[b.level] || byRank(a, b));
@@ -869,7 +873,7 @@ export function readableRows(ledger, { workflow, place, specHash = null, now })
869
873
  /**
870
874
  * THE one render: the block the PLANNER reads at draft and at the first replan. Byte-for-byte reproducible from the
871
875
  * ledger as it stood. Stops at 2,000 characters; a hint is added whole or not at all; nothing readable -> empty text.
872
- * @param {Ledger} ledger @param {{workflow: string, place: string|null, specHash?: string|null, now: Date}} o
876
+ * @param {Ledger} ledger @param {{workflow: string, place: string|null, workflowKey?: string|null, now: Date}} o
873
877
  * @returns {{text: string, ids: string[]}}
874
878
  */
875
879
  export function renderHints(ledger, o) {
@@ -901,6 +905,16 @@ export function renderHints(ledger, o) {
901
905
 
902
906
  const HINT_HEAD_RE = /^(\d+)\. \[(this job|this place|all jobs), seen (\d+) times?\] (.*)$/;
903
907
 
908
+ /**
909
+ * The one plain-words line for a learnings file that could not be read (the Audit prints it; the spine keeps the full
910
+ * reason). The person's home folder is written `~`, so the line stays short and the file can still be found.
911
+ * @param {string} reason @param {string} [userHome] defaults to the OS home @returns {string}
912
+ */
913
+ export function hintsErrorLine(reason, userHome = homedir()) {
914
+ const short = userHome.length > 1 ? reason.split(`${userHome}/`).join('~/') : reason;
915
+ return `The learnings file could not be read, so no lessons were given: ${short}`;
916
+ }
917
+
904
918
  /**
905
919
  * Split a block {@link renderHints} wrote back into its hints. The ONLY reader of that text: it lives beside the
906
920
  * writer ({@link hintText}, {@link lessonOf}) and a test renders real blocks and parses them back. A hint it cannot
package/src/learnstore.js CHANGED
@@ -9,6 +9,7 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFil
9
9
  import { join, dirname } from 'node:path';
10
10
  import { keysHome } from './keysfile.js';
11
11
  import { readConfig } from './config.js';
12
+ import { redactSecrets } from './validate.js';
12
13
  import { emptyLedger, redactDeep, countLedger, releasePending, recordHealth, buildCards, placeOf, renderHints } from './learn.js';
13
14
  import { stageQuestionsByName } from './stagewords.js';
14
15
 
@@ -59,15 +60,15 @@ export function writeLedger(ledger, home) {
59
60
  /**
60
61
  * Fold ONE finished run into the ledger on disk: every run's cards COUNT now, rubric jobs too (trust kept on new rows;
61
62
  * v1.112). `held` is always 0 (kept in the shape for callers). The run's health line is recorded. Never throws on a bad ledger file: it reports `problem` and writes nothing.
62
- * @param {{home?: string, runid: string, build: import('./learn.js').CardBuild, workflow: string, place: string|null, specHash: string|null, trust: 'deterministic'|'rubric', at: string, now?: Date}} o
63
+ * @param {{home?: string, runid: string, build: import('./learn.js').CardBuild, workflow: string, place: string|null, specHash: string|null, workflowKey?: string|null, trust: 'deterministic'|'rubric', at: string, now?: Date}} o
63
64
  * @returns {{wrote: boolean, counted: number, held: number, problem: string|null}}
64
65
  */
65
- export function foldRunIntoLedger({ home, runid, build, workflow, place, specHash, trust, at, now = new Date() }) {
66
+ export function foldRunIntoLedger({ home, runid, build, workflow, place, specHash, workflowKey = null, trust, at, now = new Date() }) {
66
67
  const cur = readLedger(home);
67
68
  if (cur.problem) return { wrote: false, counted: 0, held: 0, problem: cur.problem };
68
69
  let L = cur.ledger;
69
70
  const before = L.rows.reduce((n, r) => n + r.runIds.filter((x) => x === runid).length, 0);
70
- L = countLedger(L, { runid, cards: build.cards, workflow, place, specHash, trust, now });
71
+ L = countLedger(L, { runid, cards: build.cards, workflow, place, specHash, workflowKey, trust, now });
71
72
  const counted = L.rows.reduce((n, r) => n + r.runIds.filter((x) => x === runid).length, 0) - before;
72
73
  L = recordHealth(L, runid, build, at, now);
73
74
  writeLedger(L, home);
@@ -88,14 +89,14 @@ export function releaseRun({ home, runid, now = new Date() }) {
88
89
  }
89
90
 
90
91
  /**
91
- * The ONE setting: `learningHints` in config.json. Ships OFF (absent = off). OFF still writes the tally ($0) and the planner
92
- * is simply handed nothing, so an ON/OFF contrast has data at once. An unreadable config reads as OFF.
92
+ * The ONE setting: `learningHints` in config.json. Ships ON (hamr 2026-10-24): absent = on; only an explicit `false` turns it off. OFF still writes
93
+ * the tally ($0) and the planner is simply handed nothing. An unreadable config reads as OFF (the safe side).
93
94
  * @param {string} [home]
94
95
  * @returns {boolean}
95
96
  */
96
97
  export function learningHintsOn(home) {
97
98
  const c = readConfig({ home });
98
- return c.problem === null && c.config.learningHints === true;
99
+ return c.problem === null && c.config.learningHints !== false;
99
100
  }
100
101
 
101
102
  /** @param {string} p @returns {any[]} the parsed rows of a JSONL file; missing or torn lines are skipped */
@@ -118,29 +119,44 @@ const realOr = (p) => { try { return realpathSync(p); } catch { return p; } };
118
119
  * ledger (a rubric job's count too, trust kept). Called once from the one engine's run-end block (src/userrun.js
119
120
  * `execute`, shared by the panel, the CLI and the bundle runner), inside its own try/catch: it is a record, never a verdict,
120
121
  * and can never change a run's outcome, exit code or spend. It runs whether the hints setting is on or off.
121
- * @param {{home?: string, runid: string, events: any[], auditFiles?: string[], spec: any, specHash: string|null, workdir: string|null, trust: 'deterministic'|'rubric', now?: Date}} o
122
+ * @param {{home?: string, runid: string, events: any[], auditFiles?: string[], spec: any, specHash: string|null, workflowKey?: string|null, workdir: string|null, trust: 'deterministic'|'rubric', now?: Date}} o
122
123
  * @returns {{wrote: boolean, counted: number, held: number, problem: string|null, noise: string|null, cards: number}}
123
124
  */
124
- export function learnAtRunEnd({ home, runid, events, auditFiles = [], spec, specHash, workdir, trust, now = new Date() }) {
125
+ export function learnAtRunEnd({ home, runid, events, auditFiles = [], spec, specHash, workflowKey = null, workdir, trust, now = new Date() }) {
125
126
  const audit = auditFiles.flatMap(readJsonl);
126
127
  const build = buildCards({ runid, events, audit, workdir, spec, questions: stageQuestionsByName(spec) });
127
128
  const at = events.findLast((e) => e?.type === 'job-end')?.ts ?? now.toISOString();
128
129
  const r = foldRunIntoLedger({
129
- home, runid, build, workflow: String(spec.job), place: placeOf(spec, realOr), specHash, trust, at, now,
130
+ home, runid, build, workflow: String(spec.job), place: placeOf(spec, realOr), specHash, workflowKey, trust, at, now,
130
131
  });
131
132
  return { ...r, noise: build.noise, cards: build.cards.length };
132
133
  }
133
134
 
134
135
  /**
135
136
  * The block the planner is handed for this job, made ONCE at run start from the ledger as it stood — empty when the
136
- * setting is off, when there is no ledger, or when nothing is readable. The one `renderHints` render, never a second.
137
- * @param {{home?: string, spec: any, specHash: string|null, now?: Date}} o
137
+ * setting is off, when there is no ledger, or when no lesson fits; an unreadable ledger THROWS (use {@link handedHints}, which
138
+ * hands nothing and keeps the reason). The one `renderHints` render, never a second.
139
+ * @param {{home?: string, spec: any, workflowKey?: string|null, now?: Date}} o
138
140
  * @returns {{text: string, ids: string[]}|null}
139
141
  */
140
- export function hintsForRun({ home, spec, specHash, now = new Date() }) {
142
+ export function hintsForRun({ home, spec, workflowKey = null, now = new Date() }) {
141
143
  if (!learningHintsOn(home)) return null;
142
144
  const cur = readLedger(home);
143
- if (cur.problem) return null;
144
- const r = renderHints(cur.ledger, { workflow: String(spec.job), place: placeOf(spec, realOr), specHash, now });
145
+ if (cur.problem) throw new Error(cur.problem); // an unreadable ledger is never the same as "no lessons yet": the caller hands nothing AND records why
146
+ const r = renderHints(cur.ledger, { workflow: String(spec.job), place: placeOf(spec, realOr), workflowKey, now });
145
147
  return r.text ? r : null;
146
148
  }
149
+
150
+ /**
151
+ * {@link hintsForRun} for the engine: never throws. A broken ledger hands the planner nothing and the reason comes back
152
+ * (first line, secrets masked) so the run records it beside the hints; the run itself goes on.
153
+ * @param {{home?: string, spec: any, workflowKey?: string|null, now?: Date}} o
154
+ * @returns {{hints: {text: string, ids: string[]}|null, error: string|null}}
155
+ */
156
+ export function handedHints(o) {
157
+ try {
158
+ return { hints: hintsForRun(o), error: null };
159
+ } catch (/** @type {any} */ e) {
160
+ return { hints: null, error: redactSecrets(String(e?.message ?? e)).split('\n')[0] };
161
+ }
162
+ }
@@ -56,7 +56,7 @@ import { redactSecrets } from '../validate.js';
56
56
  import { isDropIt, isAgree } from '../pagemap.js';
57
57
  import { FIT_ABSENT_NOTE } from '../fitcheck.js';
58
58
  import { tallyCalls } from '../text.js';
59
- import { writeDraftSpend, appendDraftLog } from '../draftspend.js';
59
+ import { appendDraftLog } from '../draftspend.js';
60
60
  import { PLAIN_PROPOSAL_STOPS, proposalStopText, signingStopText, draftStopText, redsRecord, declarationRecord, calibrationSummary, tryRefusedText } from '../authorreadout.js';
61
61
  import { runNpmCi, NPM_CI_LOCKS } from '../npminstall.js';
62
62
  import {
@@ -648,10 +648,9 @@ export function createSession(card, deps = {}) {
648
648
  state.cost = t.spendComplete ? `$${t.knownUsd.toFixed(4)}` : `≥$${t.knownUsd.toFixed(4)} (unpriced calls present)`;
649
649
  state.draftSpentUsd = t.knownUsd;
650
650
  state.draftSpendComplete = t.spendComplete;
651
- // self-review 2026-10-05 (hamr's ruling A): the figure reaches DISK after every metered call, from this same
652
- // tally, so an abandoned / refused / restarted session's drafting spend still counts (src/draftspend.js)
651
+ // self-review 2026-10-05 (hamr's ruling A): the call reaches DISK as a log line after every metered call, and the money
652
+ // readers fold those lines with this same `tallyCalls`, so an abandoned / refused / restarted session's drafting spend still counts (src/draftspend.js)
653
653
  const nowIso = new Date().toISOString();
654
- draftStartedAt ??= nowIso;
655
654
  // the same call, one line in the drafting LOG (the part a run's views show first): the step running right now,
656
655
  // the call's label, the drafting model, its cost (null stays null: unpriced is never $0). One owner: this onCall.
657
656
  const runningNo = state.steps.findLastIndex((/** @type {any} */ x) => x.status === 'running');
@@ -670,21 +669,14 @@ export function createSession(card, deps = {}) {
670
669
  }
671
670
  appendDraftLog(outDir, {
672
671
  kind: 'call', no: callNo, step: state.steps[callNo]?.id ?? null, label: call.label, model: draftIdentity?.model ?? null,
672
+ provider: draftIdentity?.provider ?? null, baseUrl: draftIdentity?.baseUrl ?? null,
673
673
  thinking: draftThinkingPlan === null ? null : draftThinkingPlan.mode, thinkingSupport: draftThinkingPlan === null ? null : draftThinkingPlan.support,
674
674
  ...(call.thinkingStatus === undefined ? {} : { thinkingStatus: call.thinkingStatus }),
675
675
  // idea A core: the page-word map's scrubbed answer (src/pagemap.js) - unsigned, kept so a run can be replayed at $0
676
676
  ...(typeof call.raw === 'string' ? { raw: call.raw } : {}),
677
677
  costUsd: call.costUsd ?? null, unpricedRounds: call.unpricedRounds ?? 0, at: nowIso,
678
678
  });
679
- try {
680
- writeDraftSpend(outDir, {
681
- sessionId: id, spentUsd: t.knownUsd, spendComplete: t.spendComplete, provider: draftIdentity?.provider ?? null,
682
- baseUrl: draftIdentity?.baseUrl ?? null, model: draftIdentity?.model ?? null, startedAt: draftStartedAt, updatedAt: nowIso,
683
- });
684
- } catch { /* money already spent stays in memory for a signed run; a disk fault never stops the draft */ }
685
679
  };
686
- /** @type {string|null} */
687
- let draftStartedAt = null;
688
680
  /** what the drafting calls will carry for thinking — the tick's mode and bare-agent's support answer — set once the Model resolves; null before
689
681
  * @type {ReturnType<typeof thinkingPlanFor>|null} */
690
682
  let draftThinkingPlan = null;
@@ -292,6 +292,10 @@
292
292
  .ended-row{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap;margin-bottom:6px;}
293
293
  .ended-label{color:var(--text-faint);font-size:11px;letter-spacing:0.08em;min-width:52px;}
294
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;}
295
299
  .ended-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:8px;}
296
300
  /* P5 item 4: Import (read only) — the folder browser, the imported rows, the view */
297
301
  .import-box{border:1px dashed var(--border-strong);padding:10px;margin-bottom:10px;display:grid;gap:8px;}
@@ -1117,12 +1121,13 @@
1117
1121
  });
1118
1122
  }
1119
1123
 
1120
- // ---- step map renderer (buildStepMapHTML below — ONE renderer, no second hand-authored map anywhere on this page) ----
1121
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).
1122
- function auditCaret(open){ return '<span class="audit-caret">' + (open ? "\u25BC" : "\u25B6") + '</span>'; }
1123
- function escapeXml(s){
1125
+ function auditCaret(open){ return '<span class="audit-caret">' + (open ? "\u25BC" : "\u25B6") + '</span>'; }
1126
+ function escapeXml(s){
1124
1127
  return String(s).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");
1125
1128
  }
1129
+
1130
+ // ---- step map renderer (buildStepMapHTML below — ONE renderer, no second hand-authored map anywhere on this page) ----
1126
1131
  // s.noNumber (F196): a synthetic placeholder box (e.g. "died during
1127
1132
  // planning") is a LABEL, never a real step — it renders without the
1128
1133
  // leading "<n> " step number a real step gets.
@@ -2484,6 +2489,12 @@ function escapeXml(s){
2484
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
2485
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.
2486
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
+ }
2487
2498
  function renderEnded(detail){
2488
2499
  var box = document.getElementById("ended-block");
2489
2500
  var e = detail.ended;
@@ -2499,7 +2510,7 @@ function escapeXml(s){
2499
2510
  var h = "";
2500
2511
  if(e){
2501
2512
  // text only: the ONE place for [Stop] / [Resume] / [Reuse workflow] is the Run tab's top action row (renderRunActions)
2502
- 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);
2503
2514
  }
2504
2515
  if(sc){
2505
2516
  var w = sc.words || {};
@@ -2872,7 +2883,11 @@ function escapeXml(s){
2872
2883
  if(!box || !list) return;
2873
2884
  var items = detail && Array.isArray(detail.learnings) ? detail.learnings : [];
2874
2885
  list.innerHTML = "";
2875
- 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";
2876
2891
  items.forEach(function(it, gi){
2877
2892
  var hints = Array.isArray(it.hints) ? it.hints : [];
2878
2893
  var when = it.phase === "replan" ? "first replan" : "draft";
@@ -2927,7 +2942,7 @@ function escapeXml(s){
2927
2942
  });
2928
2943
  var label = items.length ? head + " \u00B7 " + first + (first === 1 ? " hint" : " hints") : head;
2929
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
2930
- var paint = function(){ sum.innerHTML = auditCaret(sum.getAttribute("aria-expanded") === "true") + stateDotHTML(glyphClass("\u2713"), "learnings", "audit-learnings-state") + " " + escapeXml(label); };
2945
+ var paint = function(){ sum.innerHTML = auditCaret(sum.getAttribute("aria-expanded") === "true") + stateDotHTML(glyphClass(mark), "learnings", "audit-learnings-state") + " " + escapeXml(label); };
2931
2946
  paint();
2932
2947
  // ONE fold, same as the other Audit sections: the header button toggles the body (wired once)
2933
2948
  sum.onclick = function(){
@@ -2937,7 +2952,15 @@ function escapeXml(s){
2937
2952
  paint();
2938
2953
  };
2939
2954
  }
2940
- 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;
2941
2964
  }
2942
2965
 
2943
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
@@ -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) => {