bareloop 0.47.1 → 0.49.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +16 -9
  3. package/bareloop.context.md +70 -46
  4. package/bin/bareloop.mjs +2 -0
  5. package/package.json +3 -3
  6. package/src/bundle.js +36 -9
  7. package/src/bundleref.js +103 -0
  8. package/src/bundlerun.js +134 -17
  9. package/src/cli.js +138 -144
  10. package/src/config.js +1 -1
  11. package/src/draftspend.js +88 -34
  12. package/src/facts.js +1 -1
  13. package/src/interviewrun.js +11 -11
  14. package/src/invoke.js +3 -2
  15. package/src/launcher.js +122 -12
  16. package/src/learn.js +34 -20
  17. package/src/learnstore.js +30 -14
  18. package/src/pagedropwords.js +1 -0
  19. package/src/pagedry.js +77 -6
  20. package/src/pagemap.js +17 -3
  21. package/src/pagerules.js +2 -1
  22. package/src/panel/authorsession.js +7 -13
  23. package/src/panel/index.html +30 -7
  24. package/src/panel/runroutes.js +28 -14
  25. package/src/panel/server.js +69 -118
  26. package/src/prompts.js +50 -0
  27. package/src/reuse.js +1 -1
  28. package/src/runexport.js +162 -0
  29. package/src/runfiles.js +65 -0
  30. package/src/runlist.js +72 -0
  31. package/src/userrun.js +17 -13
  32. package/types/bundle.d.ts +16 -0
  33. package/types/bundleref.d.ts +63 -0
  34. package/types/bundlerun.d.ts +10 -3
  35. package/types/cli.d.ts +2 -1
  36. package/types/draftspend.d.ts +7 -23
  37. package/types/launcher.d.ts +67 -2
  38. package/types/learn.d.ts +29 -15
  39. package/types/learnstore.d.ts +31 -10
  40. package/types/pagedry.d.ts +26 -0
  41. package/types/pagemap.d.ts +1 -0
  42. package/types/panel/server.d.ts +7 -3
  43. package/types/prompts.d.ts +21 -0
  44. package/types/reuse.d.ts +3 -0
  45. package/types/runexport.d.ts +58 -0
  46. package/types/runfiles.d.ts +40 -0
  47. package/types/runlist.d.ts +55 -0
@@ -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';
@@ -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, version?: string, 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: opts.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, version?: 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
@@ -3970,6 +3919,8 @@ export function createPanelServer(opts = {}) {
3970
3919
  const token = mintToken();
3971
3920
  // the version THIS process runs, read once at start: package.json on disk can move on while the panel keeps running old code
3972
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();
3973
3924
  return new Promise((resolve, reject) => {
3974
3925
  // Bound port is resolved from the live socket (`server.address().port`)
3975
3926
  // once listening starts, not the requested value — this is what makes
@@ -3992,7 +3943,7 @@ export function createPanelServer(opts = {}) {
3992
3943
  const server = createServer((req, res) => {
3993
3944
  try {
3994
3945
  handleRequest(req, res, {
3995
- home, sessionsRoot: opts.sessionsRoot, port: boundPort, token, authorRoutes, settingsRoutes, runRoutes, importRoutes, version, packageJsonPath: opts.packageJsonPath, schedules: schedulesRef,
3946
+ home, sessionsRoot: opts.sessionsRoot, port: boundPort, token, authorRoutes, settingsRoutes, runRoutes, importRoutes, version, startedAt, packageJsonPath: opts.packageJsonPath, schedules: schedulesRef,
3996
3947
  });
3997
3948
  } catch (e) {
3998
3949
  sendText(res, 500, `internal error: ${/** @type {Error} */ (e).message}`);
package/src/prompts.js ADDED
@@ -0,0 +1,50 @@
1
+ // The CLI's one line-asker (PRD v1.114, one menu). Every prompt in `bareloop` — the menu and the job commands — reads through
2
+ // this, so a closed stdin and the "empty Enter" rule behave the same everywhere.
3
+
4
+ import { createInterface } from 'node:readline';
5
+
6
+ /**
7
+ * One readline over `stdin`, with a LINE QUEUE: lines that arrive before the next question (piped input, a paste) wait for it instead
8
+ * of being dropped, and a closed stdin answers '' (the safe default) and never hangs.
9
+ * @param {{ stdin?: any, stdout?: any }} [io]
10
+ * @returns {{ ask: (q: string) => Promise<string>, close: () => void }}
11
+ */
12
+ export function openAsker(io = {}) {
13
+ const stdout = io.stdout ?? process.stdout;
14
+ const stdin = io.stdin ?? process.stdin;
15
+ const tty = Boolean(stdin.isTTY);
16
+ // a real terminal needs readline's output to echo the typed line; piped input echoes nothing
17
+ const rl = createInterface({ input: stdin, ...(tty ? { output: stdout, terminal: true } : { terminal: false }) });
18
+ /** @type {string[]} */
19
+ const queue = [];
20
+ /** @type {((s: string) => void)[]} */
21
+ const waiting = [];
22
+ let closed = false;
23
+ rl.on('line', (line) => { const w = waiting.shift(); if (w) w(line); else queue.push(line); });
24
+ rl.once('close', () => { closed = true; while (waiting.length) /** @type {(s: string) => void} */ (waiting.shift())(''); });
25
+ const ask = (/** @type {string} */ q) => {
26
+ stdout.write(q);
27
+ if (queue.length) return Promise.resolve(/** @type {string} */ (queue.shift()));
28
+ if (closed) return Promise.resolve('');
29
+ return new Promise((resolve) => { waiting.push(resolve); });
30
+ };
31
+ return { ask, close: () => rl.close() };
32
+ }
33
+
34
+ /** `q` (any case, trimmed) at a job question means "leave this command" (hamr 2026-10-25). @param {string} s @returns {boolean} */
35
+ export const isQuit = (s) => s.trim().toLowerCase() === 'q';
36
+
37
+ /**
38
+ * A required prompt (hamr 2026-10-25): an empty Enter asks ONCE more; a second empty Enter gives up; `q` gives up at once. `null` = nothing was chosen
39
+ * (the caller ends its command cleanly: a plain line, nothing run, exit 0).
40
+ * @param {(q: string) => Promise<string>} ask @param {string} question
41
+ * @returns {Promise<string|null>}
42
+ */
43
+ export async function askRequired(ask, question) {
44
+ for (let i = 0; i < 2; i += 1) {
45
+ const a = (await ask(question)).trim();
46
+ if (isQuit(a)) return null;
47
+ if (a !== '') return a;
48
+ }
49
+ return null;
50
+ }
package/src/reuse.js CHANGED
@@ -475,7 +475,7 @@ export async function selectBridge({ registry, job, ask, provider, pinned = null
475
475
 
476
476
  /** what the run's own spine says about a try, read back after it returns
477
477
  * @param {any[]} events @returns {any} */
478
- function readTry(events) {
478
+ export function readTry(events) {
479
479
  const last = (/** @type {string} */ t) => events.filter((e) => e.type === t).at(-1) ?? null;
480
480
  const je = last('job-end');
481
481
  const oc = last('outer-close');
@@ -0,0 +1,162 @@
1
+ // Export by run name (PRD v1.114, F245; EXPORT-BUILD.md addendum 2026-10-25). `bareloop export "<job> (run-N)" --out <dir>`
2
+ // turns a green panel / run-u run into a bundle: the run's OWN signed resolved spec (closeDecl kept as signed, nothing
3
+ // hand-written or edited) plus a bridge-v1 record minted by the library's `mintBridge` from the run's saved plan and
4
+ // its spine. Every number comes off the run's own records; a value that cannot be read is a refusal in plain words
5
+ // naming it, never a guess. $0: nothing here talks to a model.
6
+ //
7
+ // The `job (run-N)` name comes from `runNumbers` (src/runlist.js) — the panel's one owner of run names.
8
+
9
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
10
+ import { tmpdir } from 'node:os';
11
+ import { dirname, join, resolve } from 'node:path';
12
+
13
+ import { readRunList, runNumbers, runNameOf, appendExported } from './runlist.js';
14
+ import { sourceNearSpine, signedSpecForRun } from './runfiles.js';
15
+ import { parseJsonl } from './replayio.js';
16
+ import { legsOf, legsWallMs } from './legs.js';
17
+ import { jobSpecHash } from './job.js';
18
+ import { closeStagesOf } from './plan.js';
19
+ import { readTry } from './reuse.js';
20
+ import { mintBridge, saveBridge, makeRegistry } from './bridges.js';
21
+ import { exportBundle } from './bundle.js';
22
+
23
+ /** the one sentence every refusal of a job that is not a repo job starts with */
24
+ const REPO_ONLY = 'only repo jobs can be exported for now';
25
+
26
+ /**
27
+ * @param {string} name
28
+ * @returns {{ job: string, n: number }|null}
29
+ */
30
+ function parseRunName(name) {
31
+ const m = /^(.*) \(run-(\d+)\)$/.exec(String(name).trim());
32
+ return m ? { job: m[1], n: Number(m[2]) } : null;
33
+ }
34
+
35
+ /**
36
+ * The terminal outcome of a run's latest leg, read off its spine. `null` = no readable spine or no terminal record.
37
+ * @param {string} spine
38
+ * @returns {{ records: any[], outcome: string|null }}
39
+ */
40
+ function readSpineOutcome(spine) {
41
+ if (!existsSync(spine)) return { records: [], outcome: null };
42
+ const records = parseJsonl(spine).records;
43
+ return { records, outcome: legsOf(records).at(-1)?.outcome ?? null };
44
+ }
45
+
46
+ /** @param {unknown} v @returns {boolean} */
47
+ const isUrl = (v) => typeof v === 'string' && /^https?:\/\//i.test(v.trim());
48
+
49
+ /**
50
+ * Everything knowable about a run before any number is read: green (a run that was already green at start saved no plan), a signed spec
51
+ * beside it, a repo job, a saved plan made under that spec. The one check the list and the export share, so the list never offers
52
+ * what export would refuse for one of these reasons.
53
+ * @param {any} row a run-list row @param {string} name its `job (run-N)` name
54
+ * @returns {{ ok: true, records: any[], signed: { spec: any, specHash: string }, bf: any } | { ok: false, why: string }}
55
+ */
56
+ export function checkExportable(row, name) {
57
+ if (typeof row.spine !== 'string' || !existsSync(row.spine)) return { ok: false, why: `"${name}" has no log file on this machine any more (${row.spine ?? 'none recorded'})` };
58
+ const { records, outcome } = readSpineOutcome(row.spine);
59
+ if (outcome !== 'green' && outcome !== 'already-green') return { ok: false, why: `"${name}" did not end green (${outcome ?? 'no ending recorded'}) — only a green run can be exported` };
60
+ const signed = signedSpecForRun(row, records);
61
+ if (!signed) return { ok: false, why: `the signed job file for "${name}" is not beside its log, or none matches the hash it ran under` };
62
+ const spec = signed.spec;
63
+ // repo jobs only for now ($0): say which kind this is
64
+ if (spec.verdictType !== 'green') return { ok: false, why: `${REPO_ONLY}: "${name}" is a rubric job, graded by a judge (${spec.verdictType ?? 'no class recorded'})` };
65
+ if (Array.isArray(spec.inputs) && spec.inputs.some((/** @type {any} */ i) => isUrl(i?.value))) return { ok: false, why: `${REPO_ONLY}: "${name}" reads a page link` };
66
+ const near = sourceNearSpine(row.spine);
67
+ /** @type {any} */
68
+ let source = null;
69
+ if (near.sourceJsonPath) { try { source = JSON.parse(readFileSync(near.sourceJsonPath, 'utf8')); } catch { source = null; } }
70
+ if (!source || typeof source.kind !== 'string') return { ok: false, why: `"${name}" has no record of what it worked on (source.json), so its kind cannot be told` };
71
+ if (source.kind !== 'repo') return { ok: false, why: `${REPO_ONLY}: "${name}" works on a plain ${source.kind}, not a repo` };
72
+ // the saved plan: the panel / run-u engine writes it beside the spine on a green
73
+ const bridgeFile = join(dirname(row.spine), `bridge-${spec.job}-${row.runid}.json`);
74
+ /** @type {any} */
75
+ let bf = null;
76
+ try { bf = JSON.parse(readFileSync(bridgeFile, 'utf8')); } catch { bf = null; }
77
+ if (!bf || typeof bf.plan !== 'object' || bf.plan === null) {
78
+ return { ok: false, why: `"${name}" saved no plan (${bridgeFile}) — a run that was already green at start has none, so it cannot be exported` };
79
+ }
80
+ if (bf.runid !== row.runid || bf.specHash !== signed.specHash || bf.specHash !== jobSpecHash(spec)) {
81
+ return { ok: false, why: `the plan saved by "${name}" was made under a different signed job file than the one beside it` };
82
+ }
83
+ return { ok: true, records, signed, bf };
84
+ }
85
+
86
+ /**
87
+ * The green panel / run-u runs export CAN take, oldest first, as `{name, runid, job}`. A run export would refuse for a reason knowable
88
+ * here (already green with no saved plan, a rubric / page-link / folder job, no signed spec) is not listed; a number it cannot read
89
+ * (cost, time, rounds, patient) is still refused at export, in words. Rows made by `bareloop run` or a backfill are not listed.
90
+ * @param {{ home?: string }} [opts]
91
+ * @returns {{ name: string, runid: string, job: string, at: string, outcome: string, row: any }[]}
92
+ */
93
+ export function listGreenRuns(opts = {}) {
94
+ const { rows } = readRunList(opts);
95
+ const nos = runNumbers(rows);
96
+ /** @type {{ name: string, runid: string, job: string, at: string, outcome: string, row: any }[]} */
97
+ const out = [];
98
+ for (const row of rows) {
99
+ if (row.via !== 'run-u') continue;
100
+ const name = runNameOf(row.job, nos.get(row.runid));
101
+ if (!checkExportable(row, name).ok) continue;
102
+ out.push({ name, runid: row.runid, job: row.job, at: row.at, outcome: 'green', row });
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /**
108
+ * Build the bundle for one green run. Never throws for a run it cannot export: every stop is `{ok:false, why}` in plain words.
109
+ * @param {{ name: string, outDir: string, home?: string, bareloopVersion: string, now?: () => number }} o
110
+ * @returns {{ ok: true, runid: string, job: string, name: string, dir: string, bundleHash: string } | { ok: false, why: string }}
111
+ */
112
+ export function exportRun({ name, outDir, home, bareloopVersion, now = Date.now }) {
113
+ const want = parseRunName(name);
114
+ if (!want) return { ok: false, why: `"${name}" is not a run name — it looks like: my-job (run-3)` };
115
+ const { rows } = readRunList(home === undefined ? {} : { home });
116
+ const nos = runNumbers(rows);
117
+ const row = rows.find((r) => r.job === want.job && nos.get(r.runid) === want.n && r.via === 'run-u') ?? null;
118
+ if (!row) return { ok: false, why: `no run named "${name}" in the run list` };
119
+ const chk = checkExportable(row, name);
120
+ if (!chk.ok) return chk;
121
+ const { records, signed, bf } = chk;
122
+ const spec = signed.spec;
123
+
124
+ // the numbers, all from the run's own spine; nothing guessed
125
+ const legs = legsOf(records);
126
+ const je = legs.at(-1)?.jobEnd ?? null;
127
+ const costUsd = typeof je?.engagementSpentUsd === 'number' ? je.engagementSpentUsd : (typeof je?.spentUsd === 'number' ? je.spentUsd : null);
128
+ if (costUsd === null || !Number.isFinite(costUsd)) return { ok: false, why: `cannot read what "${name}" cost: its log's ending record carries no spend figure` };
129
+ if (typeof je?.spendComplete !== 'boolean') return { ok: false, why: `cannot read whether the cost of "${name}" is complete: its log's ending record does not say` };
130
+ const wall = legsWallMs(legs);
131
+ if (wall.ms === null || !wall.complete) return { ok: false, why: `cannot read how long "${name}" took: its log's time stamps are missing or unreadable` };
132
+ const rounds = readTry(records).rounds;
133
+ if (typeof rounds !== 'number') return { ok: false, why: `cannot read how many rounds "${name}" took: its log shows spend but no round records` };
134
+ if (typeof row.patient !== 'string' || row.patient === '') return { ok: false, why: `cannot read which folder "${name}" worked in: its run-list row records none` };
135
+
136
+ const toolsUsed = [...new Set((Array.isArray(bf.plan.steps) ? bf.plan.steps : []).flatMap((/** @type {any} */ s) => (Array.isArray(s?.tools) ? s.tools : [])))];
137
+ const minted = mintBridge(
138
+ { name: spec.job, goal: spec.goal, specHash: signed.specHash, closeStageNames: (closeStagesOf(spec) ?? []).map((/** @type {any} */ s) => s.name), toolsUsed },
139
+ {
140
+ runid: row.runid, patient: row.patient, at: typeof bf.greenAt === 'string' ? bf.greenAt : null, plan: bf.plan,
141
+ costUsd, spendComplete: je.spendComplete, wallMs: wall.ms, rounds, specHash: signed.specHash, verdictType: spec.verdictType,
142
+ },
143
+ );
144
+ if (!minted.ok) return { ok: false, why: `the run's record did not make a valid bridge: ${minted.reds.map((r) => `${r.code} at ${r.path}`).join(', ')}` };
145
+
146
+ // a throwaway registry: exportBundle ships "a run that actually happened", read from a registry directory
147
+ const tmp = mkdtempSync(join(tmpdir(), 'bareloop-export-'));
148
+ try {
149
+ const reg = join(tmp, 'registry');
150
+ makeRegistry(reg);
151
+ const saved = saveBridge(reg, minted.bridge);
152
+ if (!saved.ok) return { ok: false, why: `could not stage the bridge: ${saved.reds.map((r) => `${r.code} at ${r.path}`).join(', ')}` };
153
+ const dir = resolve(outDir);
154
+ const r = exportBundle({ spec, closeScripts: {}, registryDir: reg, outDir: dir, bareloopVersion });
155
+ if (!r.ok) return { ok: false, why: r.reds.map((x) => `${x.code} at ${x.path}${x.detail ? `: ${x.detail}` : ''}`).join('; ') };
156
+ const bundleHash = /** @type {string} */ (r.bundleHash);
157
+ appendExported({ runid: row.runid, job: row.job, bundle: dir, bundleHash, at: new Date(now()).toISOString() }, home === undefined ? {} : { home });
158
+ return { ok: true, runid: row.runid, job: row.job, name: runNameOf(row.job, want.n), dir, bundleHash };
159
+ } finally {
160
+ rmSync(tmp, { recursive: true, force: true });
161
+ }
162
+ }