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/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
+ }
@@ -0,0 +1,65 @@
1
+ // The files that sit beside a run's spine, found the one way (panel and CLI both ask here): the source
2
+ // door's manifest, and the signed spec the run's latest leg ran under. Moved out of src/panel/server.js so
3
+ // `bareloop export` and the panel share ONE spelling (PRD v1.114). Pure reads, $0.
4
+
5
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
6
+ import { basename, dirname, join } from 'node:path';
7
+ import { legsOf } from './legs.js';
8
+ import { jobSpecHash } from './job.js';
9
+
10
+ /**
11
+ * `<out>/source-<seed>/<job>-bareloop/u-<runid>.jsonl` -> the two files an
12
+ * authoring session leaves BESIDE that layout — `<out>/resolved-spec.json`
13
+ * (the signed spec `--spec`/a JOBS-table row ran) and
14
+ * `<out>/source-<seed>/source.json` (the source front door's manifest) —
15
+ * verified against `src/userrun.js`'s own construction (`specWorkdir = join(into,
16
+ * 'tree')`, `spineDir = join(wd, '..', target.spine)`, both `--spec` and the
17
+ * `pulselog-person-strict` JOBS-table row read `into` the same way) and a real
18
+ * archived run (pulselog-person-live-2, run mu2p83go): `dirname(spine)` is
19
+ * `<into>/<job>-bareloop`, `dirname(dirname(spine))` is `<into>` itself
20
+ * (`source-<seed>`, carrying `source.json`), and `dirname(dirname(dirname(spine)))`
21
+ * is `<out>` (carrying `resolved-spec.json`).
22
+ *
23
+ * Only resolves when `<into>`'s own name starts with `source-` — the one
24
+ * shape marker this convention always carries — and each file is checked to
25
+ * actually exist before being handed back; any other spine layout (the bundle
26
+ * `spine.jsonl`, a JOBS-table row whose workdir has no source-seed copy, e.g.
27
+ * `litectx-u`) returns both fields `null`, never a guessed path (build spec
28
+ * item 2, 2026-09-25: "don't search the disk broadly — fall through").
29
+ * @param {string} spinePath
30
+ * @returns {{ specPath: string|null, sourceJsonPath: string|null }}
31
+ */
32
+ export function sourceNearSpine(spinePath) {
33
+ const into = dirname(dirname(spinePath)); // <into>/<job>-bareloop/u-x.jsonl -> <into>
34
+ if (!basename(into).startsWith('source-')) return { specPath: null, sourceJsonPath: null };
35
+ const sourceJsonPath = join(into, 'source.json');
36
+ const specPath = join(dirname(into), 'resolved-spec.json'); // <into> -> <out>
37
+ return {
38
+ specPath: existsSync(specPath) ? specPath : null,
39
+ sourceJsonPath: existsSync(sourceJsonPath) ? sourceJsonPath : null,
40
+ };
41
+ }
42
+ /**
43
+ * The signed spec a run's LATEST leg ran under — the `resolved-spec*.json` beside the run whose hash is the one its
44
+ * latest `job-start` carries (the same lookup `resumePlanFor` does). `null` = no such file.
45
+ * @param {{ spine: string }} row
46
+ * @param {any[]} records
47
+ * @returns {{spec: any, specPath: string, specHash: string}|null}
48
+ */
49
+ export function signedSpecForRun(row, records) {
50
+ const jobStart = (legsOf(records).findLast((l) => l.jobStart !== null) ?? null)?.jobStart ?? null;
51
+ if (!jobStart || typeof jobStart.specHash !== 'string') return null;
52
+ const near = sourceNearSpine(row.spine);
53
+ if (!near.specPath) return null;
54
+ const dir = dirname(near.specPath);
55
+ /** @type {string[]} */
56
+ let names = [];
57
+ try { names = readdirSync(dir).filter((n) => n === 'resolved-spec.json' || /^resolved-spec-r\d+\.json$/.test(n)); } catch { names = []; }
58
+ for (const n of names) {
59
+ let spec;
60
+ try { spec = JSON.parse(readFileSync(join(dir, n), 'utf8')); } catch { continue; }
61
+ if (!spec || typeof spec !== 'object') continue;
62
+ if (jobSpecHash(spec) === jobStart.specHash) return { spec, specPath: join(dir, n), specHash: jobStart.specHash };
63
+ }
64
+ return null;
65
+ }
package/src/runlist.js CHANGED
@@ -164,6 +164,37 @@ export function readNeedsRemovals(opts = {}) {
164
164
  return out;
165
165
  }
166
166
 
167
+ /**
168
+ * @typedef {{ type: 'exported', runid: string, job: string, bundle: string, bundleHash: string, at: string }} ExportedRow
169
+ * RULED 2026-10-25 (PRD v1.114): `bareloop export` appends ONE of these per bundle it makes, so `bareloop run` can find the bundle by the
170
+ * run's name. Not a run, a claim or an event: {@link readRunList} ignores it (it has a `type`), so the monthly limit, the run counter and the
171
+ * scheduler never see it. Nothing is rewritten.
172
+ */
173
+
174
+ /**
175
+ * Append one {@link ExportedRow}. THROWS on IO failure.
176
+ * @param {Omit<ExportedRow, 'type'>} row
177
+ * @param {{ home?: string }} [opts]
178
+ * @returns {void}
179
+ */
180
+ export function appendExported(row, opts = {}) {
181
+ const path = runlistPath(opts.home);
182
+ mkdirSync(runlistHome(opts.home), { recursive: true, mode: 0o700 });
183
+ appendFileSync(path, `${JSON.stringify({ ...row, type: 'exported' })}\n`);
184
+ try { chmodSync(path, 0o600); } catch { /* best-effort perms */ }
185
+ }
186
+
187
+ /**
188
+ * Every `exported` row, in file order (a re-export of the same run is a later row). An absent file is an empty list.
189
+ * @param {{ home?: string }} [opts]
190
+ * @returns {ExportedRow[]}
191
+ */
192
+ export function readExported(opts = {}) {
193
+ const path = runlistPath(opts.home);
194
+ if (!existsSync(path)) return [];
195
+ return parseJsonl(path).records.filter((r) => r && r.type === 'exported' && typeof r.bundle === 'string' && typeof r.runid === 'string');
196
+ }
197
+
167
198
  /**
168
199
  * @typedef {{ type: 'leg-start', runid: string, leg: number, pid?: number, capUsd?: number, at: string }} LegStart
169
200
  * A resumed run's NEW claim (P5-R, hamr 2026-10-02: one run, one id, one row): appended beside the run's row
@@ -483,3 +514,44 @@ export function formatRunRow(row) {
483
514
  const missing = existsSync(row.spine) ? '' : ' — file missing';
484
515
  return `${row.job} (${row.runid}) · ${date} · ${row.spine}${missing}`;
485
516
  }
517
+
518
+ /**
519
+ * @param {any} r
520
+ * @returns {number}
521
+ */
522
+ export function atMs(r) {
523
+ const t = typeof r?.at === 'string' ? Date.parse(r.at) : NaN;
524
+ return Number.isFinite(t) ? t : 0;
525
+ }
526
+
527
+ /**
528
+ * A run's name for a person: `job (run-N)`, N from {@link runNumbers}. The ONE spelling (the panel, `bareloop export` and `bareloop run` all print it).
529
+ * @param {string} job @param {number|undefined} n
530
+ * @returns {string}
531
+ */
532
+ export function runNameOf(job, n) { return `${job} (run-${n})`; }
533
+
534
+ /**
535
+ * The ONE owner of run names (P6 item 7): runs of the same job (`row.job`) are numbered oldest `at` first, 1-based
536
+ * (ties keep file order). A resume is one row, so it counts once; died and stopped runs are rows too. Every view
537
+ * reads this number — the page never counts on its own.
538
+ * @param {any[]} rows
539
+ * @returns {Map<string, number>} runid → N
540
+ */
541
+ export function runNumbers(rows) {
542
+ /** @type {Map<string, any[]>} */
543
+ const byJob = new Map();
544
+ rows.forEach((row, index) => {
545
+ if (!row || typeof row.runid !== 'string') return;
546
+ const g = byJob.get(row.job) || [];
547
+ g.push({ row, index });
548
+ byJob.set(row.job, g);
549
+ });
550
+ /** @type {Map<string, number>} */
551
+ const out = new Map();
552
+ for (const g of byJob.values()) {
553
+ g.sort((a, b) => (atMs(a.row) - atMs(b.row)) || (a.index - b.index));
554
+ g.forEach(({ row }, i) => out.set(row.runid, i + 1));
555
+ }
556
+ return out;
557
+ }
package/src/userrun.js CHANGED
@@ -32,7 +32,7 @@ import { commitWork, removeWorktree } from './worktree.js';
32
32
  import { moveFile } from './movefile.js';
33
33
  import { runJob } from './run.js';
34
34
  import { moneyWithDraft } from './replay.js';
35
- import { jobSpecHash, resolveWorkerModel, validateJob } from './job.js';
35
+ import { jobSpecHash, resolveWorkerModel, validateJob, workflowKey } from './job.js';
36
36
  import { readShimArm } from './readshim.js';
37
37
  import { closeStagesOf } from './plan.js';
38
38
  import { resolveCloseTimeoutMs } from './closetimeout.js';
@@ -82,7 +82,7 @@ import { keysForDoor } from './keysfile.js';
82
82
  import { parseJsonl } from './replayio.js';
83
83
  import { claimRun, monthlyRefusalText, legSpend, chainSpend } from './monthly.js';
84
84
  import { ConfigError } from './config.js';
85
- import { learnAtRunEnd, hintsForRun, releaseRun } from './learnstore.js';
85
+ import { learnAtRunEnd, handedHints, releaseRun } from './learnstore.js';
86
86
  import { commandFor } from './invoke.js';
87
87
  import { judgeRatesFor, keyNameFor, keyValueOf, priceReadout, ratesFor, ratesOfLine, resolveWorker, judgeRowFor, rowsForHome, REFUSE_NAME_MODEL } from './providerrows.js';
88
88
  // the banner's wall arithmetic, extracted so it is reachable by a test (F83): the
@@ -1906,7 +1906,10 @@ async function execute(ctx) {
1906
1906
  /** @type {{text: string, ids: string[]}|null} */
1907
1907
  let learnHints = null;
1908
1908
  if (cfgOn) {
1909
- try { learnHints = hintsForRun({ home: cfgHome, spec, specHash }); } catch { learnHints = null; }
1909
+ // an unreadable ledger hands nothing but is never silent: the reason rides a `learnings` spine record (hintsError) the Audit prints
1910
+ const handed = handedHints({ home: cfgHome, spec, workflowKey: workflowKey(spec) });
1911
+ learnHints = handed.hints;
1912
+ if (handed.error !== null) emit('learnings', { phase: 'draft', hintsError: handed.error });
1910
1913
  }
1911
1914
  let outcome;
1912
1915
  try {
@@ -2033,7 +2036,7 @@ async function execute(ctx) {
2033
2036
  try {
2034
2037
  const filedAudit = ctx.bundle ? join(spineDir, 'gate-audit.jsonl') : join(spineDir, `u-${runid}-gate-audit.jsonl`);
2035
2038
  learnAtRunEnd({
2036
- home: cfgHome, runid, events: allEvents, auditFiles: [filedAudit, join(wd, 'gate-audit.jsonl')], spec, specHash, workdir: wd,
2039
+ home: cfgHome, runid, events: allEvents, auditFiles: [filedAudit, join(wd, 'gate-audit.jsonl')], spec, specHash, workflowKey: workflowKey(spec), workdir: wd,
2037
2040
  trust: quarantinesCredit(spec.verdictType) ? 'rubric' : 'deterministic',
2038
2041
  });
2039
2042
  } catch (/** @type {any} */ e) { err(`WARNING: could not record this run's lessons in the learnings ledger (${redactSecrets(String(e?.message ?? e)).split('\n')[0]}) — the run itself is unaffected.`); }
@@ -2140,8 +2143,9 @@ async function execute(ctx) {
2140
2143
  out(` trend ${mh.trend} — ${mh.reading}`);
2141
2144
  if (ctx.bundle) {
2142
2145
  // a bundle's spec is manifest-hashed: there is no budgetUsd to edit and no new hash to sign. The room that
2143
- // is left is the signed ceiling, and the ONLY way to use it is the person typing a larger --budget. The
2144
- // exhausted --budget is never echoed (pasted as printed it halts again at once: the chain folds prior spend),
2146
+ // is left is the signed ceiling, and the way to use it is the person typing a larger --budget. Going PAST the
2147
+ // signed ceiling is allowed only with the person's own yes (hamr 2026-10-25), shown back and recorded in the run.
2148
+ // The exhausted --budget is never echoed (pasted as printed it halts again at once: the chain folds prior spend),
2145
2149
  // and nothing is filled in for them.
2146
2150
  const signed = ctx.bundle.signedBudgetUsd;
2147
2151
  const spentUsd = typeof mh.budgetUsd === 'number' && typeof mh.remainingUsd === 'number' ? mh.budgetUsd - mh.remainingUsd : null;
@@ -2152,12 +2156,12 @@ async function execute(ctx) {
2152
2156
  out(` lever ${lever}`);
2153
2157
  if (spentUsd !== null && spentUsd >= signed) {
2154
2158
  // the whole signed ceiling is spent: "more than spent, at most signed" is unsatisfiable, so no resume line is printed
2155
- out(` · no room left under the signed ceiling: this run spent all of the signed $${signed}, and a bundle's ceiling cannot be raised`);
2159
+ out(` · no room left under the signed ceiling: this run spent all of the signed $${signed}, and raising a bundle's ceiling needs your typed yes (--yes)`);
2156
2160
  out(' · abandon the task');
2157
2161
  } else {
2158
- out(` · choose a larger --budget on the resume line below (the room left is the signed $${signed}; it cannot be raised past that)`);
2162
+ out(` · choose a larger --budget on the resume line below (the room left is the signed $${signed}; going past it asks you to type yes)`);
2159
2163
  out(' · abandon the task');
2160
- out(` resume ${ctx.bundle.invoke}${WALL_FLAG} --resume ${runid}${SHIM_TAIL}${SCOUT_TAIL}${DRAFT_TAIL}${REGISTRY_TAIL} --budget <more than ${spentTxt}, at most $${signed}> --approve ${PRINT_APPROVE}`);
2164
+ out(` resume ${ctx.bundle.invoke}${WALL_FLAG} --resume ${runid}${SHIM_TAIL}${SCOUT_TAIL}${DRAFT_TAIL}${REGISTRY_TAIL} --budget <more than ${spentTxt}, above $${signed} asks you to type yes> --approve ${PRINT_APPROVE}`);
2161
2165
  out(' (type the --budget number yourself — nothing here fills it in, so this line does not run as printed; nothing in the run may widen its own budget)');
2162
2166
  }
2163
2167
  } else {
@@ -2580,7 +2584,7 @@ export async function main(argv, deps = {}) {
2580
2584
  if (!existsSync(specPath)) {
2581
2585
  die(`--job ${jobArg}: there is no spec at ${specPath}.\n`
2582
2586
  + ' The table row is the runner\'s half of a job (patient, seed, spine); the SPEC is yours — authored through\n'
2583
- + ` ${commandFor('interview', deps.invokedAs)} and ${commandFor('author', deps.invokedAs)}, then signed. Nothing here can stand in for it: a job\n`
2587
+ + ' the panel\'s drafting (or node scripts/run-interview.mjs and node scripts/run-author.mjs), then signed. Nothing here can stand in for it: a job\n'
2584
2588
  + ' with no spec has no goal, no close, no budget and no hash to approve.');
2585
2589
  }
2586
2590
  try { spec = JSON.parse(readFileSync(specPath, 'utf8')); } catch (e) {
@@ -2592,7 +2596,7 @@ export async function main(argv, deps = {}) {
2592
2596
  specPath = resolve(/** @type {string} */ (specArg));
2593
2597
  if (!existsSync(specPath)) {
2594
2598
  die(`--spec ${specPath} does not exist — a run needs the resolved-spec.json an authoring session actually wrote `
2595
- + `(${commandFor('author', deps.invokedAs)}'s own \`out/resolved-spec.json\`), never a path nobody authored`);
2599
+ + '(the panel\'s drafting session, or node scripts/run-author.mjs\'s own `out/resolved-spec.json`), never a path nobody authored');
2596
2600
  }
2597
2601
  let raw;
2598
2602
  try { raw = readFileSync(specPath, 'utf8'); } catch (e) {
@@ -2632,8 +2636,8 @@ export async function main(argv, deps = {}) {
2632
2636
  if (candidates.length === 0) {
2633
2637
  die(`--spec ${specPath}: no prepared copy beside it — looked for a source-*/ directory carrying source.json in `
2634
2638
  + `${dirname(specPath)} and found none. A --spec run reads its workdir and seed off the copy the authoring `
2635
- + `session prepared; it is never typed or guessed. Prepare one first: ${commandFor('interview', deps.invokedAs)} (or `
2636
- + `${commandFor('author', deps.invokedAs)} directly against a --source) before running this spec.`);
2639
+ + `session prepared; it is never typed or guessed. Prepare one first: draft the job in the panel (or node scripts/run-interview.mjs, `
2640
+ + 'then node scripts/run-author.mjs against a --source) before running this spec.');
2637
2641
  }
2638
2642
  if (candidates.length > 1) {
2639
2643
  die(`--spec ${specPath}: ${candidates.length} prepared copies sit beside it (${candidates.join(', ')}) — `
package/types/bundle.d.ts CHANGED
@@ -120,6 +120,22 @@ export function checkEnvelope(spec: any, envelope?: {
120
120
  ok: boolean;
121
121
  reds: Red[];
122
122
  };
123
+ /**
124
+ * The caps a typed envelope would RAISE above the bundle's signed ones (hamr 2026-10-25: a raise is allowed, but only signed by the
125
+ * person typing `yes` or passing `--yes`). Same fields and test as {@link checkEnvelope}'s widen red; a field the spec has no ceiling
126
+ * for cannot be raised. Pure.
127
+ * @param {any} spec the (already `$BARELOOP_BUNDLE`-resolved) bundle spec
128
+ * @param {{ budgetUsd?: number, maxWallMs?: number }} envelope
129
+ * @returns {{ field: 'budgetUsd'|'maxWallMs', old: number, new: number }[]}
130
+ */
131
+ export function capRaises(spec: any, envelope?: {
132
+ budgetUsd?: number;
133
+ maxWallMs?: number;
134
+ }): {
135
+ field: "budgetUsd" | "maxWallMs";
136
+ old: number;
137
+ new: number;
138
+ }[];
123
139
  /**
124
140
  * Write `blessing.json`: the FIRST GREEN RUN on the importer's own machine
125
141
  * signs the bundle as trustworthy (hamr Q2), so later runs need no
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Every bundle on this machine the CLI knows, NEWEST FIRST, one per folder: the exported ones (the `exported` rows) and any bundle that
3
+ * has `bareloop run` rows (spine `<bundle>/runs/<runid>/spine.jsonl`). `label` = the run name (or the job) and the folder.
4
+ * @param {{ home?: string }} [opts]
5
+ * @returns {{ name: string, dir: string, label: string, atMs: number }[]}
6
+ */
7
+ export function knownBundles(opts?: {
8
+ home?: string;
9
+ }): {
10
+ name: string;
11
+ dir: string;
12
+ label: string;
13
+ atMs: number;
14
+ }[];
15
+ /**
16
+ * The shared bundle question of `run` and `history`: show the last {@link RECENT_BUNDLES} bundles, newest first, numbered; then ask. A number
17
+ * picks one shown; a run name or a folder reaches an older one. None known: one plain line and the command ends.
18
+ * @param {{ ask: (q: string) => Promise<string>, out: (s: string) => void, home?: string, none: string, cancelled: string }} o
19
+ * @returns {Promise<{ ref: string } | { end: true }>} `end` = the command ends cleanly (exit 0)
20
+ */
21
+ export function askBundle({ ask, out, home, none, cancelled }: {
22
+ ask: (q: string) => Promise<string>;
23
+ out: (s: string) => void;
24
+ home?: string;
25
+ none: string;
26
+ cancelled: string;
27
+ }): Promise<{
28
+ ref: string;
29
+ } | {
30
+ end: true;
31
+ }>;
32
+ /**
33
+ * A bundle reference typed by a person: an existing folder (relative to `cwd`), else an exported run name.
34
+ * @param {string} ref @param {{ home?: string, cwd: string }} o
35
+ * @returns {{ ok: true, dir: string } | { ok: false, why: string }}
36
+ */
37
+ export function resolveBundleRef(ref: string, { home, cwd }: {
38
+ home?: string;
39
+ cwd: string;
40
+ }): {
41
+ ok: true;
42
+ dir: string;
43
+ } | {
44
+ ok: false;
45
+ why: string;
46
+ };
47
+ /**
48
+ * The stopped / capped runs of `bareloop run` the engine would accept a resume for, newest first: not alive, no answer yet, an
49
+ * attempt to continue, checkpoint not expired, and the bundle folder still on disk.
50
+ * @param {{ home?: string }} [opts]
51
+ * @returns {{ runid: string, job: string, bundleDir: string, outcome: string, label: string }[]}
52
+ */
53
+ export function listResumableBundleRuns(opts?: {
54
+ home?: string;
55
+ }): {
56
+ runid: string;
57
+ job: string;
58
+ bundleDir: string;
59
+ outcome: string;
60
+ label: string;
61
+ }[];
62
+ /** how many bundles a pick list shows; older ones stay reachable by typing their run name or folder */
63
+ export const RECENT_BUNDLES: 10;
@@ -1,16 +1,20 @@
1
1
  /**
2
- * `bareloop run <bundleDir> --repo <path> [--budget N] [--wall MIN] [--approve <bundleHash>]`
3
- * `bareloop run <bundleDir> --resume <runid> [--repo <path>] [--budget N] [--wall MIN] [--approve <bundleHash>]`
2
+ * `bareloop run <bundle> --repo <path> [--model <id>] [--budget N] [--wall MIN] [--yes] [--approve <bundleHash>]`
3
+ * `bareloop run <bundle> --resume <runid> [--repo <path>] [--budget N] [--wall MIN] [--yes] [--approve <bundleHash>]`
4
+ * `<bundle>` is a bundle folder or the run name it was exported under (`job (run-N)`). A missing bundle, repo or model is asked for
5
+ * (when there is something to ask: `canAsk`); a required answer left empty twice ends the command cleanly (exit 0, nothing run).
6
+ * A cap typed ABOVE the signed one is shown back and needs `yes` (or `--yes`); the approval is recorded in the run's own folder.
4
7
  * @param {string[]} args
5
8
  * @param {{
6
9
  * out: (s: string) => void, err: (s: string) => void, cwd: string,
7
10
  * env: Record<string,string|undefined>, now: () => number, deps: any, keysHome?: string,
11
+ * ask?: (q: string) => Promise<string>, canAsk?: boolean, guided?: boolean,
8
12
  * parseFlags: (a: string[]) => { positional: string[], flags: Record<string, string|true> },
9
13
  * printReds: (reds: import('./bundle.js').Red[], err: (s: string) => void) => void,
10
14
  * }} ctx
11
15
  * @returns {Promise<number>}
12
16
  */
13
- export function bundleMain(args: string[], { out, err, cwd, env, now, deps, keysHome, parseFlags, printReds, }: {
17
+ export function bundleMain(args: string[], { out, err, cwd, env, now, deps, keysHome, ask, canAsk, guided: guidedIn, parseFlags, printReds, }: {
14
18
  out: (s: string) => void;
15
19
  err: (s: string) => void;
16
20
  cwd: string;
@@ -18,6 +22,9 @@ export function bundleMain(args: string[], { out, err, cwd, env, now, deps, keys
18
22
  now: () => number;
19
23
  deps: any;
20
24
  keysHome?: string;
25
+ ask?: (q: string) => Promise<string>;
26
+ canAsk?: boolean;
27
+ guided?: boolean;
21
28
  parseFlags: (a: string[]) => {
22
29
  positional: string[];
23
30
  flags: Record<string, string | true>;
package/types/cli.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * code, so `bin/bareloop.mjs` can set `process.exitCode` and let node flush
4
4
  * queued stdout on its own (F-something: `process.exit()` can discard it).
5
5
  * @param {string[]} argv
6
- * @param {{ env?: Record<string,string|undefined>, stdout?: any, stderr?: any, cwd?: string, provider?: any, providerFor?: any, judgeProvider?: any, judgeModel?: string|null, now?: () => number, stdin?: any, runlistHome?: string, keysHome?: string, processEnv?: Record<string,string|undefined> }} deps
6
+ * @param {{ env?: Record<string,string|undefined>, stdout?: any, stderr?: any, cwd?: string, provider?: any, providerFor?: any, judgeProvider?: any, judgeModel?: string|null, now?: () => number, stdin?: any, interactive?: boolean, runlistHome?: string, keysHome?: string, processEnv?: Record<string,string|undefined> }} deps
7
7
  * @returns {Promise<number>}
8
8
  */
9
9
  export function main(argv: string[], deps?: {
@@ -17,6 +17,7 @@ export function main(argv: string[], deps?: {
17
17
  judgeModel?: string | null;
18
18
  now?: () => number;
19
19
  stdin?: any;
20
+ interactive?: boolean;
20
21
  runlistHome?: string;
21
22
  keysHome?: string;
22
23
  processEnv?: Record<string, string | undefined>;