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.
@@ -0,0 +1,103 @@
1
+ // How the CLI finds a bundle: by the run name it was exported under, or by folder (PRD v1.114, one menu). Names come from the
2
+ // `exported` rows `bareloop export` appends to runs.jsonl, numbered by the panel's own `runNumbers`. Also: which stopped bundle runs
3
+ // can be resumed (the menu's Resume list). $0, read-only.
4
+
5
+ import { existsSync, statSync } from 'node:fs';
6
+ import { dirname, resolve } from 'node:path';
7
+ import { askRequired } from './prompts.js';
8
+
9
+ import { readRunList, readExported, runNumbers, runNameOf, runIsAlive } from './runlist.js';
10
+ import { parseJsonl } from './replayio.js';
11
+ import { legsOf } from './legs.js';
12
+ import { readResume, checkpointAgeGate, CHECKPOINT_OUTCOMES } from './reuse.js';
13
+
14
+ /** @param {string} p @returns {boolean} */
15
+ const isDir = (p) => { try { return statSync(p).isDirectory(); } catch { return false; } };
16
+
17
+ /** how many bundles a pick list shows; older ones stay reachable by typing their run name or folder */
18
+ export const RECENT_BUNDLES = 10;
19
+
20
+ /**
21
+ * Every bundle on this machine the CLI knows, NEWEST FIRST, one per folder: the exported ones (the `exported` rows) and any bundle that
22
+ * has `bareloop run` rows (spine `<bundle>/runs/<runid>/spine.jsonl`). `label` = the run name (or the job) and the folder.
23
+ * @param {{ home?: string }} [opts]
24
+ * @returns {{ name: string, dir: string, label: string, atMs: number }[]}
25
+ */
26
+ export function knownBundles(opts = {}) {
27
+ const { rows } = readRunList(opts);
28
+ const nos = runNumbers(rows);
29
+ const ms = (/** @type {any} */ x) => { const t = typeof x === 'string' ? Date.parse(x) : NaN; return Number.isFinite(t) ? t : 0; };
30
+ /** @type {Map<string, { name: string, dir: string, label: string, atMs: number }>} */
31
+ const byDir = new Map();
32
+ const put = (/** @type {string} */ dir, /** @type {string} */ name, /** @type {number} */ atMs, /** @type {boolean} */ named) => {
33
+ if (!isDir(dir)) return;
34
+ const old = byDir.get(dir);
35
+ if (old && old.atMs > atMs && (old.name !== '' || !named)) return;
36
+ const keep = named ? name : (old ? old.name : '');
37
+ byDir.set(dir, { name: keep, dir, label: `${keep || name} ${dir}`, atMs: Math.max(atMs, old ? old.atMs : 0) });
38
+ };
39
+ for (const x of readExported(opts)) {
40
+ const n = nos.get(x.runid);
41
+ put(x.bundle, n === undefined ? `${x.job} (${x.runid})` : runNameOf(x.job, n), ms(x.at), true);
42
+ }
43
+ for (const r of rows) {
44
+ if (r.via !== 'bundle' || typeof r.spine !== 'string') continue;
45
+ put(dirname(dirname(dirname(r.spine))), r.job, ms(r.at), false);
46
+ }
47
+ return [...byDir.values()].sort((a, b) => b.atMs - a.atMs);
48
+ }
49
+
50
+ /**
51
+ * The shared bundle question of `run` and `history`: show the last {@link RECENT_BUNDLES} bundles, newest first, numbered; then ask. A number
52
+ * picks one shown; a run name or a folder reaches an older one. None known: one plain line and the command ends.
53
+ * @param {{ ask: (q: string) => Promise<string>, out: (s: string) => void, home?: string, none: string, cancelled: string }} o
54
+ * @returns {Promise<{ ref: string } | { end: true }>} `end` = the command ends cleanly (exit 0)
55
+ */
56
+ export async function askBundle({ ask, out, home, none, cancelled }) {
57
+ const known = knownBundles(home === undefined ? {} : { home });
58
+ if (known.length === 0) { out(none); return { end: true }; }
59
+ const shown = known.slice(0, RECENT_BUNDLES);
60
+ out(known.length > shown.length ? `Bundles (the last ${shown.length} of ${known.length}; older ones by run name or folder):` : 'Bundles:');
61
+ shown.forEach((b, i) => out(` ${i + 1} ${b.label}`));
62
+ const pick = await askRequired(ask, 'Bundle (a number above, a run name, or a folder): ');
63
+ if (pick === null) { out(cancelled); return { end: true }; }
64
+ return { ref: /^\d+$/.test(pick) && shown[Number(pick) - 1] ? shown[Number(pick) - 1].dir : pick };
65
+ }
66
+
67
+ /**
68
+ * A bundle reference typed by a person: an existing folder (relative to `cwd`), else an exported run name.
69
+ * @param {string} ref @param {{ home?: string, cwd: string }} o
70
+ * @returns {{ ok: true, dir: string } | { ok: false, why: string }}
71
+ */
72
+ export function resolveBundleRef(ref, { home, cwd }) {
73
+ const asPath = resolve(cwd, ref);
74
+ if (isDir(asPath)) return { ok: true, dir: asPath };
75
+ const hit = knownBundles(home === undefined ? {} : { home }).find((b) => b.name === ref);
76
+ if (hit) return { ok: true, dir: hit.dir };
77
+ return { ok: false, why: `"${ref}" is neither a bundle folder nor the name of a bundle you exported (bareloop export makes one)` };
78
+ }
79
+
80
+ /**
81
+ * The stopped / capped runs of `bareloop run` the engine would accept a resume for, newest first: not alive, no answer yet, an
82
+ * attempt to continue, checkpoint not expired, and the bundle folder still on disk.
83
+ * @param {{ home?: string }} [opts]
84
+ * @returns {{ runid: string, job: string, bundleDir: string, outcome: string, label: string }[]}
85
+ */
86
+ export function listResumableBundleRuns(opts = {}) {
87
+ const { rows } = readRunList(opts);
88
+ /** @type {{ runid: string, job: string, bundleDir: string, outcome: string, label: string }[]} */
89
+ const out = [];
90
+ for (const row of rows) {
91
+ if (row.via !== 'bundle' || typeof row.spine !== 'string' || !existsSync(row.spine)) continue;
92
+ if (runIsAlive(row)) continue;
93
+ const bundleDir = dirname(dirname(dirname(row.spine))); // <bundle>/runs/<runid>/spine.jsonl
94
+ if (!isDir(bundleDir)) continue;
95
+ const records = parseJsonl(row.spine).records;
96
+ const dead = readResume(records, { direct: true, resumableOutcomes: CHECKPOINT_OUTCOMES });
97
+ if (!dead.started || dead.greened || dead.ended || !dead.restart) continue;
98
+ if (!checkpointAgeGate(records).ok) continue;
99
+ const outcome = legsOf(records).at(-1)?.outcome ?? 'stopped';
100
+ out.push({ runid: row.runid, job: row.job, bundleDir, outcome, label: `${row.job} run ${row.runid} (${outcome}) ${bundleDir}` });
101
+ }
102
+ return out.reverse(); // newest first
103
+ }
package/src/bundlerun.js CHANGED
@@ -13,45 +13,81 @@
13
13
  // spec — the equality stays a real check (the spec the engine sees is the spec hashed).
14
14
  // `bundleHash` never changes when the runner tightens; `history.jsonl` records both hashes.
15
15
 
16
- import { hostname } from 'node:os';
16
+ import { hostname, userInfo } from 'node:os';
17
17
  import { execFileSync } from 'node:child_process';
18
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
18
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
19
19
  import { join, resolve } from 'node:path';
20
20
 
21
21
  import {
22
- readBundle, resolveBundleSpec, checkEnvelope, bless, verifyBlessing, appendHistory, checkBundleDeps,
22
+ readBundle, resolveBundleSpec, checkEnvelope, capRaises, bless, verifyBlessing, appendHistory, checkBundleDeps,
23
23
  } from './bundle.js';
24
+ import { askRequired, isQuit } from './prompts.js';
25
+ import { askBundle, resolveBundleRef } from './bundleref.js';
26
+ import { rowsForHome, chatLines } from './providerrows.js';
24
27
  import { jobSpecHash } from './job.js';
25
- import { addWorktree, worktreePath } from './worktree.js';
28
+ import { addWorktree, worktreePath, commitWork } from './worktree.js';
26
29
  import { parseJsonl } from './replayio.js';
27
30
  import { legsOf } from './legs.js';
28
31
  import { startRun, resumeRun } from './userrun.js';
29
32
 
33
+ /** the plain sentences for a raised cap (ONE spelling: the prompt, the refusal and the record's reader all read them) */
34
+ const raiseWords = (/** @type {{ field: string, old: number, new: number }} */ r) => (r.field === 'budgetUsd'
35
+ ? `This raises the $ cap from $${r.old} to $${r.new}.`
36
+ : `This raises the time cap from ${r.old / 60_000} min to ${r.new / 60_000} min.`);
37
+
30
38
  /**
31
- * `bareloop run <bundleDir> --repo <path> [--budget N] [--wall MIN] [--approve <bundleHash>]`
32
- * `bareloop run <bundleDir> --resume <runid> [--repo <path>] [--budget N] [--wall MIN] [--approve <bundleHash>]`
39
+ * `bareloop run <bundle> --repo <path> [--model <id>] [--budget N] [--wall MIN] [--yes] [--approve <bundleHash>]`
40
+ * `bareloop run <bundle> --resume <runid> [--repo <path>] [--budget N] [--wall MIN] [--yes] [--approve <bundleHash>]`
41
+ * `<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
42
+ * (when there is something to ask: `canAsk`); a required answer left empty twice ends the command cleanly (exit 0, nothing run).
43
+ * 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.
33
44
  * @param {string[]} args
34
45
  * @param {{
35
46
  * out: (s: string) => void, err: (s: string) => void, cwd: string,
36
47
  * env: Record<string,string|undefined>, now: () => number, deps: any, keysHome?: string,
48
+ * ask?: (q: string) => Promise<string>, canAsk?: boolean, guided?: boolean,
37
49
  * parseFlags: (a: string[]) => { positional: string[], flags: Record<string, string|true> },
38
50
  * printReds: (reds: import('./bundle.js').Red[], err: (s: string) => void) => void,
39
51
  * }} ctx
40
52
  * @returns {Promise<number>}
41
53
  */
42
54
  export async function bundleMain(args, {
43
- out, err, cwd, env, now, deps, keysHome, parseFlags, printReds,
55
+ out, err, cwd, env, now, deps, keysHome, ask, canAsk = false, guided: guidedIn = false, parseFlags, printReds,
44
56
  }) {
45
57
  const { positional, flags } = parseFlags(args);
46
- const bundleDirArg = positional[0];
47
- const repoArg = typeof flags.repo === 'string' ? flags.repo : undefined;
58
+ const askable = canAsk && typeof ask === 'function';
59
+ const home = deps?.runlistHome;
60
+ /** @type {string|undefined} */
61
+ let bundleDirArg = positional[0];
62
+ /** @type {string|undefined} */
63
+ let repoArg = typeof flags.repo === 'string' ? flags.repo : undefined;
48
64
  const resumeArg = typeof flags.resume === 'string' ? flags.resume : undefined;
49
- if (flags.resume === true || (!bundleDirArg) || (resumeArg === undefined && !repoArg)) {
50
- err('usage: bareloop run <bundleDir> --repo <path> [--budget N] [--wall MIN] [--approve <bundleHash>]\n'
51
- + ' bareloop run <bundleDir> --resume <runid> [--repo <path>] [--budget N] [--wall MIN] [--approve <bundleHash>]');
65
+ const usage = () => {
66
+ err('usage: bareloop run <bundle> --repo <path> [--model <id>] [--budget N] [--wall MIN] [--yes] [--approve <bundleHash>]\n'
67
+ + ' bareloop run <bundle> --resume <runid> [--repo <path>] [--budget N] [--wall MIN] [--yes] [--approve <bundleHash>]\n'
68
+ + ' <bundle> is a bundle folder or the name you exported it under, e.g. "my-job (run-3)"');
52
69
  return 1;
70
+ };
71
+ if (flags.resume === true) return usage();
72
+ /** set once any required value had to be asked: the guided run also offers the optional caps */
73
+ let guided = guidedIn;
74
+ if (bundleDirArg === undefined) {
75
+ if (!askable || !ask) return usage();
76
+ const r = await askBundle({ ask, out, ...(home === undefined ? {} : { home }), none: 'No exported bundles yet. Export one with 6.', cancelled: 'No bundle chosen, nothing run.' });
77
+ if ('end' in r) return 0;
78
+ bundleDirArg = r.ref;
79
+ guided = true;
80
+ }
81
+ const found = resolveBundleRef(bundleDirArg, { ...(home === undefined ? {} : { home }), cwd });
82
+ if (!found.ok) { err(found.why); return 1; }
83
+ const bundleDir = found.dir;
84
+ if (resumeArg === undefined && repoArg === undefined) {
85
+ if (!askable || !ask) return usage();
86
+ const r = await askRequired(ask, 'Repo (a folder that is a git repo with at least one commit): ');
87
+ if (r === null) { out('No repo chosen, nothing run.'); return 0; }
88
+ repoArg = r;
89
+ guided = true;
53
90
  }
54
- const bundleDir = resolve(cwd, bundleDirArg);
55
91
 
56
92
  // 1. readBundle — this must complete, clean, before anything else touches the bundle or
57
93
  // the repo. Any red (incl. bundle-tampered) stops here.
@@ -64,9 +100,20 @@ export async function bundleMain(args, {
64
100
  const depsCheck = checkBundleDeps(bundleDir);
65
101
  if (!depsCheck.ok) { printReds(depsCheck.reds, err); return 1; }
66
102
 
67
- // 2. checkEnvelope — tighten-only, wall given in minutes -> ms.
103
+ // 2. the caps. Lowering needs nothing; a cap typed ABOVE the signed one is shown back and signed by `yes` (hamr 2026-10-25).
68
104
  /** @type {{ budgetUsd?: number, maxWallMs?: number }} */
69
105
  const envelope = {};
106
+ if (guided && askable && ask) {
107
+ // a guided run offers the caps; Enter keeps the signed value
108
+ const budgetAns = (await ask(`$ cap (Enter keeps $${bundle.spec.budgetUsd}${resumeArg === undefined ? '' : '; a higher number adds money'}): `)).trim();
109
+ if (isQuit(budgetAns)) { out('Nothing chosen, nothing run.'); return 0; }
110
+ if (budgetAns !== '') flags.budget = budgetAns;
111
+ if (typeof bundle.spec.maxWallMs === 'number') {
112
+ const wallAns = (await ask(`Time cap in minutes (Enter keeps ${bundle.spec.maxWallMs / 60_000}${resumeArg === undefined ? '' : '; a higher number adds time'}): `)).trim();
113
+ if (isQuit(wallAns)) { out('Nothing chosen, nothing run.'); return 0; }
114
+ if (wallAns !== '') flags.wall = wallAns;
115
+ }
116
+ }
70
117
  if (flags.budget !== undefined) {
71
118
  const n = Number(flags.budget);
72
119
  if (!Number.isFinite(n)) { err(`--budget must be a number, got ${JSON.stringify(flags.budget)}`); return 1; }
@@ -77,10 +124,30 @@ export async function bundleMain(args, {
77
124
  if (!Number.isFinite(n)) { err(`--wall must be a number of minutes, got ${JSON.stringify(flags.wall)}`); return 1; }
78
125
  envelope.maxWallMs = n * 60_000;
79
126
  }
80
- const envCheck = checkEnvelope(bundle.spec, envelope);
127
+ const raises = capRaises(bundle.spec, envelope);
128
+ const tighten = { ...envelope };
129
+ for (const r of raises) delete tighten[r.field];
130
+ const envCheck = checkEnvelope(bundle.spec, tighten);
81
131
  if (!envCheck.ok) { printReds(envCheck.reds, err); return 1; }
132
+ /** the raises the person signed, recorded in the run's own folder once the engine has accepted the run */
133
+ /** @type {{ field: string, old: number, new: number }[]} */
134
+ let signedRaises = [];
135
+ if (raises.length > 0) {
136
+ for (const r of raises) out(raiseWords(r));
137
+ if (flags.yes !== undefined) signedRaises = raises;
138
+ else if (askable && ask) {
139
+ const a = (await ask('Type yes to sign it: ')).trim().toLowerCase();
140
+ if (isQuit(a)) { out('Not signed, nothing run.'); return 0; }
141
+ if (a !== 'yes') { err('Not signed (only "yes" signs a raise) — the caps stay as signed. Nothing ran.'); return 1; }
142
+ signedRaises = raises;
143
+ } else {
144
+ printReds(raises.map((r) => ({ code: 'envelope-widen', path: r.field, detail: `${r.new} exceeds the bundle's signed ${r.field} (${r.old}) — a raise needs your yes: run it at a terminal and type yes, or pass --yes` })), err);
145
+ return 1;
146
+ }
147
+ }
82
148
 
83
149
  // 3. blessing — BEFORE any key is read (the engine reads the key last).
150
+ let signedBundle = false;
84
151
  const { manifest } = bundle;
85
152
  if (!bundle.blessing) {
86
153
  // The runid that ACTUALLY minted this bundle's own signed spec — the bridge VERSION
@@ -104,8 +171,17 @@ export async function bundleMain(args, {
104
171
  out(mintRunid ? `minting run: ${mintRunid} (spine not bundled in v1)` : 'no version at this hash');
105
172
  out(`bundleHash: ${manifest.bundleHash}`);
106
173
  if (flags.approve !== manifest.bundleHash) {
107
- err(`--approve ${manifest.bundleHash} is required for the first run of an unblessed bundle`);
108
- return 1;
174
+ // typed at a terminal (the menu): show the hash and sign it with a typed yes, the cap raise's own confirm style (hamr 2026-10-25).
175
+ // Flags only: `--approve <hash>` is still the way (`--yes` signs caps, not a bundle).
176
+ if (askable && ask && flags.approve === undefined) {
177
+ const a = (await ask('Type yes to sign it: ')).trim().toLowerCase();
178
+ if (isQuit(a)) { out('Not signed, nothing run.'); return 0; }
179
+ if (a !== 'yes') { err('Not signed (only "yes" signs a bundle) — nothing ran.'); return 1; }
180
+ signedBundle = true;
181
+ } else {
182
+ err(`--approve ${manifest.bundleHash} is required for the first run of an unblessed bundle`);
183
+ return 1;
184
+ }
109
185
  }
110
186
  } else {
111
187
  const vb = verifyBlessing(bundle);
@@ -190,11 +266,37 @@ export async function bundleMain(args, {
190
266
  addWorktree(repo, worktree);
191
267
  }
192
268
  mkdirSync(runDir, { recursive: true });
269
+ // a raised cap the person signed: who, old, new, at — appended beside the run's own records (never rewritten)
270
+ if (signedBundle) {
271
+ appendFileSync(join(runDir, 'approvals.jsonl'), `${JSON.stringify({
272
+ type: 'bundle-approve', who: userInfo().username, bundleHash: manifest.bundleHash, at: new Date(now()).toISOString(),
273
+ })}\n`);
274
+ }
275
+ for (const r of signedRaises) {
276
+ appendFileSync(join(runDir, 'approvals.jsonl'), `${JSON.stringify({
277
+ type: 'cap-raise', who: userInfo().username, field: r.field, old: r.old, new: r.new, at: new Date(now()).toISOString(), bundleHash: manifest.bundleHash, approveHash,
278
+ })}\n`);
279
+ }
193
280
  writeFileSync(join(runDir, 'run.json'), `${JSON.stringify({
194
281
  runid, worktree, seed, repo, at: firstAt ?? new Date(now()).toISOString(),
195
282
  }, null, 2)}\n`);
196
283
  };
197
284
 
285
+ // 5b. the model: the one the bundle's spec names. A spec that names none takes the one the person picks from the Settings lines.
286
+ if (!bundle.spec.model && typeof flags.model !== 'string' && askable && ask) {
287
+ const lines = chatLines(rowsForHome(keysHome, env));
288
+ if (lines.length > 0) {
289
+ out('This bundle names no model. Models ticked in Settings:');
290
+ lines.forEach((l, i) => out(` ${i + 1} ${l.label}`));
291
+ const pick = await askRequired(ask, 'Model (a number): ');
292
+ if (pick === null) { out('No model chosen, nothing run.'); return 0; }
293
+ const hit = /^\d+$/.test(pick) ? lines[Number(pick) - 1] : undefined;
294
+ if (!hit) { err(`"${pick}" is not one of the numbers above.`); return 1; }
295
+ flags.model = hit.model;
296
+ flags.provider = hit.slot;
297
+ }
298
+ }
299
+
198
300
  // 6. the engine. `deps` passes through exactly as `bareloop run-u` passes it, so every
199
301
  // test seam (provider/providerFor/judgeProvider/runlistHome/keysHome) is the same one.
200
302
  let engineCode;
@@ -239,6 +341,18 @@ export async function bundleMain(args, {
239
341
  const outcome = je.outcome;
240
342
  const spentUsd = je.spentUsd ?? null;
241
343
  const spendComplete = je.spendComplete ?? null;
344
+ // a green's work is committed on its work branch, like the panel does (the folder is kept; the merge stays yours)
345
+ let commitLine = null;
346
+ let commitFailed = false;
347
+ if (outcome === 'green' || outcome === 'already-green') {
348
+ try {
349
+ const fin = commitWork(worktree, `bareloop: ${runSpec.job} (run ${runid})`);
350
+ commitLine = fin.committed ? `final commit ${fin.sha}` : 'nothing left to commit';
351
+ } catch (e) {
352
+ commitFailed = true;
353
+ commitLine = `the final commit FAILED, the work is still in the worktree uncommitted: ${String(/** @type {Error} */ (e).message).split('\n')[0]}`;
354
+ }
355
+ }
242
356
  let branch = null;
243
357
  try { branch = execFileSync('git', ['-C', worktree, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8' }).trim(); } catch { /* leave null — reported honestly below */ }
244
358
  appendHistory(bundleDir, {
@@ -253,6 +367,7 @@ export async function bundleMain(args, {
253
367
  branch,
254
368
  bundleHash: manifest.bundleHash,
255
369
  approveHash,
370
+ ...(signedRaises.length > 0 ? { capsRaised: signedRaises } : {}),
256
371
  // one row per LEG of the one run; the first leg's row keeps the shape it always had
257
372
  ...(legs.length > 1 ? { leg: legs.length } : {}),
258
373
  });
@@ -265,10 +380,12 @@ export async function bundleMain(args, {
265
380
  // 8. the merge hints (the engine printed the outcome/spend readout).
266
381
  out(`branch ${branch ?? 'UNKNOWN (could not read the worktree branch)'}`);
267
382
  out(`worktree ${worktree}`);
383
+ if (commitLine) out(`commit ${commitLine}`);
268
384
  if (branch) out(`merge git merge ${branch} (merge stays human — this CLI never merges)`);
269
385
  out(`the worktree is kept until you remove it: git worktree remove ${worktree}`);
270
386
  // exit 0 ONLY for a real green — every other outcome exits 1 so a caller scripting
271
387
  // `bareloop run` off its exit code cannot mistake a red for a success. The engine's own
272
388
  // 2 (refusal) / 3 (spine leak) are preserved.
389
+ if (commitFailed) return engineCode || 1;
273
390
  return engineCode || (outcome === 'green' || outcome === 'already-green' ? 0 : 1);
274
391
  }