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.
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
@@ -1,6 +1,6 @@
1
1
  // L (PANEL-BUILD.md addendum 2026-10-24) — the `bareloop` launcher: the bare-`bareloop` menu and `bareloop start | stop | status | install`.
2
2
  //
3
- // No pid file: the panel is FOUND by asking 127.0.0.1:4700..4709 for `GET /api/whoami` (src/panel/server.js), several at once, 300 ms
3
+ // No pid file: the panel is FOUND by asking 127.0.0.1:4700..4709 for `GET /api/whoami` (src/panel/server.js), several at once, 2000 ms
4
4
  // each; a reply with `app === "bareloop"` is a panel. Every call prints the same two header lines first, from {@link buildHeader}.
5
5
  // The run counts are the panel's own (`runsListForCount`: the `listRuns` rows' `status.key` and `needs`, plus the schedules that gave up) — never a second spelling of "running" or "needs you".
6
6
  // This file owns no arbiter state: it starts/stops the panel process and reads the run list at $0. Every OS touch (spawn, kill, open,
@@ -18,13 +18,16 @@ 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) */
24
25
  export const PORT_START = 4700;
25
26
  export const PORT_COUNT = 10;
26
- const PROBE_TIMEOUT_MS = 300;
27
+ const PROBE_TIMEOUT_MS = 2000;
27
28
  const WAIT_DEADLINE_MS = 10_000;
29
+ /** how long `start` keeps asking a TAKEN port that stays silent before it refuses to open another panel next to it */
30
+ const SILENT_PORT_WAIT_MS = 10_000;
28
31
  const POLL_MS = 100;
29
32
  const MIN_NODE_MAJOR = 22;
30
33
  const RULE_WIDTH = 56;
@@ -33,6 +36,7 @@ const RULE_WIDTH = 56;
33
36
  * @typedef {object} Panel one answered probe
34
37
  * @property {number} port @property {number} pid @property {string} version @property {number} drafts @property {number} schedules
35
38
  * @property {string} url
39
+ * @property {string|null} [startedAt] ISO time the panel process started (`whoami`); absent on an older panel
36
40
  */
37
41
 
38
42
  /**
@@ -42,10 +46,11 @@ const RULE_WIDTH = 56;
42
46
  * @property {number[]} [ports] an explicit port list (tests); wins over portStart/portCount
43
47
  * @property {number} [timeoutMs] probe timeout per port
44
48
  * @property {number} [deadlineMs] start/stop wait deadline
49
+ * @property {number} [silentWaitMs] how long start keeps asking a taken, silent port (default 10 s)
45
50
  * @property {string} [nodeVersion] default process.versions.node
46
51
  * @property {typeof fetch} [fetchImpl]
47
52
  * @property {(cmd: string, args: string[], o: object) => any} [spawnFn] default node:child_process spawn
48
- * @property {(pid: number, sig: string) => void} [kill] default process.kill
53
+ * @property {(pid: number, sig: string|number) => void} [kill] default process.kill
49
54
  * @property {((target: string) => Promise<boolean>)} [open] default the shared OS opener
50
55
  * @property {(port: number) => Promise<boolean>} [portFree] default: try to bind 127.0.0.1:port
51
56
  * @property {(ms: number) => Promise<void>} [sleep]
@@ -98,32 +103,54 @@ export function installState(o) {
98
103
  }
99
104
 
100
105
  /**
101
- * Ask 127.0.0.1 across the ports in parallel; a reply with `app === "bareloop"` is a panel. Never throws.
102
- * @param {{ports: number[], timeoutMs?: number, fetchImpl?: typeof fetch}} o
103
- * @returns {Promise<Panel[]>} in port order
106
+ * Ask one port for `/api/whoami`. Never throws. `silent` = no reply inside the timeout (a loaded or stuck process may still be a
107
+ * panel); `other` = something replied (or refused) and it is not a bareloop whoami.
108
+ * @param {{port: number, timeoutMs?: number, fetchImpl?: typeof fetch}} o
109
+ * @returns {Promise<{state: 'panel', panel: Panel}|{state: 'other'}|{state: 'silent'}>}
104
110
  */
105
- export async function probePanels(o) {
111
+ export async function probePort(o) {
106
112
  const f = o.fetchImpl ?? fetch;
107
113
  const ms = o.timeoutMs ?? PROBE_TIMEOUT_MS;
108
- const answers = await Promise.all(o.ports.map(async (port) => {
109
- try {
110
- const res = await f(`${panelUrl(port)}/api/whoami`, { signal: AbortSignal.timeout(ms) });
111
- if (!res.ok) return null;
112
- const j = /** @type {any} */ (await res.json());
113
- if (!j || j.app !== 'bareloop') return null;
114
- return /** @type {Panel} */ ({
114
+ const port = o.port;
115
+ try {
116
+ const res = await f(`${panelUrl(port)}/api/whoami`, { signal: AbortSignal.timeout(ms) });
117
+ if (!res.ok) return { state: 'other' };
118
+ const j = /** @type {any} */ (await res.json());
119
+ if (!j || j.app !== 'bareloop') return { state: 'other' };
120
+ return {
121
+ state: 'panel',
122
+ panel: {
115
123
  port,
116
124
  pid: Number(j.pid),
117
125
  version: String(j.version ?? ''),
118
126
  drafts: Number(j.drafts) || 0,
119
127
  schedules: Number(j.schedules) || 0,
120
128
  url: panelUrl(port),
121
- });
122
- } catch { return null; }
123
- }));
124
- return /** @type {Panel[]} */ (answers.filter((a) => a !== null));
129
+ startedAt: typeof j.startedAt === 'string' && Number.isFinite(Date.parse(j.startedAt)) ? j.startedAt : null,
130
+ },
131
+ };
132
+ } catch (e) {
133
+ const name = /** @type {any} */ (e)?.name;
134
+ return name === 'TimeoutError' || name === 'AbortError' ? { state: 'silent' } : { state: 'other' };
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Ask 127.0.0.1 across the ports in parallel; a reply with `app === "bareloop"` is a panel. Never throws.
140
+ * @param {{ports: number[], timeoutMs?: number, fetchImpl?: typeof fetch}} o
141
+ * @returns {Promise<Panel[]>} in port order
142
+ */
143
+ export async function probePanels(o) {
144
+ const answers = await Promise.all(o.ports.map((port) => probePort({ port, timeoutMs: o.timeoutMs, fetchImpl: o.fetchImpl })));
145
+ return /** @type {Panel[]} */ (answers.flatMap((a) => (a.state === 'panel' ? [a.panel] : [])));
125
146
  }
126
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
+
127
154
  /** @param {LauncherDeps} d @returns {number[]} */
128
155
  function portsOf(d) {
129
156
  if (d.ports) return d.ports;
@@ -150,8 +177,8 @@ export async function buildHeader(d) {
150
177
  const sep = P.grey(' · ');
151
178
  const where = panels.length === 0
152
179
  ? `panel ${P.grey('not running')}`
153
- : `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(', ')}`;
154
- 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`;
155
182
  const first = `${P.boldCyan('bareloop')} ${P.grey(version)}${sep}${state}${sep}${where}`;
156
183
  let second;
157
184
  try {
@@ -258,7 +285,7 @@ export async function statusCmd(io, d, shown) {
258
285
  return shown ? 0 : 3;
259
286
  }
260
287
  for (const p of h.panels) {
261
- 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)}`;
262
289
  io.out(h.panels.length > 1 ? `${p.url} · ${body}` : body);
263
290
  }
264
291
  return 0;
@@ -272,7 +299,9 @@ export async function statusCmd(io, d, shown) {
272
299
  async function waitFor(d, port, gone) {
273
300
  const sleep = sleepOf(d);
274
301
  const deadline = d.deadlineMs ?? WAIT_DEADLINE_MS;
275
- for (let waited = 0; waited <= deadline; waited += POLL_MS) {
302
+ // real clock time (CLOCK_MONOTONIC): a probe can take up to its whole timeout, so counting POLL_MS a turn would overshoot the deadline many times over
303
+ const t0 = performance.now();
304
+ while (performance.now() - t0 <= deadline) {
276
305
  const found = await probePanels({ ports: [port], timeoutMs: d.timeoutMs, fetchImpl: d.fetchImpl });
277
306
  if (gone ? found.length === 0 : found.length > 0) return true;
278
307
  await sleep(POLL_MS);
@@ -280,6 +309,24 @@ async function waitFor(d, port, gone) {
280
309
  return false;
281
310
  }
282
311
 
312
+ /**
313
+ * A taken port that no probe recognised: ask it again until it answers or ~10 s of real time pass. A bareloop whoami = a panel;
314
+ * any other reply = not ours (move on); still silent at the end = `silent`.
315
+ * @param {LauncherDeps} d @param {number} port
316
+ * @returns {Promise<{state: 'panel', panel: Panel}|{state: 'other'}|{state: 'silent'}>}
317
+ */
318
+ async function askTakenPort(d, port) {
319
+ const sleep = sleepOf(d);
320
+ const limit = d.silentWaitMs ?? SILENT_PORT_WAIT_MS;
321
+ const t0 = performance.now();
322
+ for (;;) {
323
+ const r = await probePort({ port, timeoutMs: d.timeoutMs, fetchImpl: d.fetchImpl });
324
+ if (r.state !== 'silent') return r;
325
+ if (performance.now() - t0 >= limit) return r;
326
+ await sleep(POLL_MS);
327
+ }
328
+ }
329
+
283
330
  /**
284
331
  * `bareloop start` — find a running panel first; else start one detached on the first free port 4700..4709, wait until it answers,
285
332
  * open the page.
@@ -296,17 +343,28 @@ export async function startCmd(io, d, shown) {
296
343
  io.out(opened ? `${said} — opening the page.` : `${said} — open it in your browser.`);
297
344
  return 0;
298
345
  };
299
- if (h.panels.length > 0) {
300
- const rc = await finish(h.panels[0].url, `Panel already running at ${P.cyan(h.panels[0].url)}`);
346
+ /** @param {Panel} found */
347
+ const alreadyRunning = async (found) => {
348
+ const rc = await finish(found.url, `Panel already running at ${P.cyan(found.url)}`);
301
349
  const mine = d.version ?? packageVersion();
302
- if (h.panels[0].version !== mine) io.out(P.yellow(`It is version ${h.panels[0].version}; this bareloop is ${mine}. Run bareloop stop, then bareloop start, to use ${mine}.`));
350
+ if (found.version !== mine) io.out(P.yellow(`It is version ${found.version}; this bareloop is ${mine}. Run bareloop stop, then bareloop start, to use ${mine}.`));
303
351
  return rc;
304
- }
352
+ };
353
+ if (h.panels.length > 0) return alreadyRunning(h.panels[0]);
305
354
  const free = d.portFree ?? bindFree;
306
355
  const ports = portsOf(d);
307
356
  /** @type {number|null} */
308
357
  let chosen = null;
309
- for (const p of ports) { if (await free(p)) { chosen = p; break; } }
358
+ for (const p of ports) {
359
+ if (await free(p)) { chosen = p; break; }
360
+ // taken: if it is a loaded panel that missed the probe, a second panel next to it would double every scheduled run
361
+ const verdict = await askTakenPort(d, p);
362
+ if (verdict.state === 'panel') return alreadyRunning(verdict.panel);
363
+ if (verdict.state === 'silent') {
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>`);
365
+ return 1;
366
+ }
367
+ }
310
368
  if (chosen === null) {
311
369
  fail(io, d, `Every port from ${ports[0]} to ${ports[ports.length - 1]} is taken by something else, so the panel was not started.`);
312
370
  return 1;
@@ -373,6 +431,25 @@ export async function stopCmd(args, io, d, shown) {
373
431
  return 1;
374
432
  }
375
433
  }
434
+ // the pid being gone is the truth (signal 0: ESRCH = gone, EPERM = alive); the port going quiet is checked after, for those that went
435
+ const t0 = performance.now();
436
+ const limit = d.deadlineMs ?? WAIT_DEADLINE_MS;
437
+ const sleep = sleepOf(d);
438
+ let pending = panels.slice();
439
+ while (pending.length > 0) {
440
+ pending = pending.filter((p) => {
441
+ try { kill(p.pid, 0); return true; } catch (e) { return /** @type {any} */ (e)?.code !== 'ESRCH'; }
442
+ });
443
+ if (pending.length === 0 || performance.now() - t0 > limit) break;
444
+ await sleep(POLL_MS);
445
+ }
446
+ if (pending.length > 0) {
447
+ for (const p of panels) {
448
+ if (!pending.includes(p)) io.out(`The panel at ${p.url} (pid ${p.pid}) stopped.`);
449
+ }
450
+ for (const p of pending) fail(io, d, `The panel at ${p.url} (pid ${p.pid}) did not stop.`);
451
+ return 1;
452
+ }
376
453
  for (const p of panels) {
377
454
  if (!(await waitFor(d, p.port, true))) {
378
455
  fail(io, d, `The panel at ${p.url} still answers after ${(d.deadlineMs ?? WAIT_DEADLINE_MS) / 1000} seconds (pid ${p.pid}).`);
@@ -384,8 +461,33 @@ export async function stopCmd(args, io, d, shown) {
384
461
  }
385
462
 
386
463
  /**
387
- * The bare `bareloop` menu: header, the four choices, one question. Runs the chosen command and returns its exit code.
388
- * @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
389
491
  * @returns {Promise<number>}
390
492
  */
391
493
  export async function menuCmd(io, d) {
@@ -395,15 +497,21 @@ export async function menuCmd(io, d) {
395
497
  const P = d.paint ?? PLAIN;
396
498
  if (!P.on) io.out('');
397
499
  const n = (/** @type {string} */ k) => P.boldCyan(k);
398
- const items = `${n('1')} start ${n('2')} stop ${n('3')} status ${n('4')} install ${n('q')} quit`;
399
- 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`);
400
504
  const choice = ask ? (await ask(`${P.cyan('>')} `)).trim().toLowerCase() : 'q';
401
505
  // the header is already on screen: the chosen command reuses it instead of printing it a second time
402
506
  if (choice === '1' || choice === 'start') return startCmd(io, d, h);
403
507
  if (choice === '2' || choice === 'stop') return stopCmd([], io, d, h);
404
- if (choice === '3' || choice === 'status') return statusCmd(io, d, h);
405
- 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)]();
406
514
  if (choice === '' || choice === 'q' || choice === 'quit') return 0;
407
- 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`);
408
516
  return 1;
409
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;