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/cli.js CHANGED
@@ -16,7 +16,8 @@
16
16
  // spec. `history.jsonl` records both hashes side by side (POC fact 2) so the pairing can
17
17
  // never drift silently.
18
18
 
19
- import { createInterface } from 'node:readline/promises';
19
+ import { openAsker, askRequired } from './prompts.js';
20
+ import { listGreenRuns, exportRun } from './runexport.js';
20
21
  import {
21
22
  existsSync, readFileSync,
22
23
  } from 'node:fs';
@@ -36,41 +37,28 @@ import { bundleMain } from './bundlerun.js';
36
37
  // rather than re-parsing argv a second time here keeps exactly one code
37
38
  // path for the flag grammar; `src/cli.js` only supplies the deps shape
38
39
  // (`out`/`err`/`env`) this command's own callers already use.
39
- import { startCmd, stopCmd, statusCmd, installCmd, menuCmd } from './launcher.js';
40
+ import { startCmd, stopCmd, restartCmd, statusCmd, installCmd, menuCmd } from './launcher.js';
41
+ import { askBundle, resolveBundleRef, listResumableBundleRuns, RECENT_BUNDLES } from './bundleref.js';
40
42
  import { makePaint } from './tty-colour.js';
41
43
  import { main as runUMain } from './userrun.js';
42
- // PANEL-BUILD.md P0 task 3/4 — `bareloop interview` and `bareloop author`
43
- // wrap the close-authoring interview and authoring-pipeline flows' own
44
- // argv-parsing entries (`src/interviewrun.js`/`src/authorrun.js`, lifted out
45
- // of `scripts/run-interview.mjs`/`scripts/run-author.mjs` the same way task
46
- // 1/2 lifted `scripts/run-u.mjs`). `scripts/run-interview.mjs`/`scripts/
47
- // run-author.mjs` call these SAME functions directly, so there is exactly
48
- // one place each flag grammar is parsed.
49
- import { main as interviewMain } from './interviewrun.js';
50
- import { main as authorMain } from './authorrun.js';
51
- // PANEL-BUILD.md P0 — the spine/gate-audit read side (`bareloop replay`,
52
- // and `doHistory`'s reader below), lifted out of `scripts/run-replay.mjs`
53
- // into `src/replayio.js` the same way tasks 1-3 lifted their own scripts.
54
- import {
55
- parseJsonl, looksLikeSpine, replayOne, listSpines, readHistoryLog,
56
- } from './replayio.js';
57
- import { formatReplay, formatAllLines } from './replay.js';
58
44
  // PANEL-BUILD.md P1 — the read-only panel HTTP server (`bareloop panel`).
59
45
  // One more caller of the same `src/` library functions this file already
60
46
  // calls (the layering law, PANEL-BUILD.md §2) — `src/panel/server.js` never
61
47
  // re-implements the spine/run-list read side, it calls `src/replayio.js`/
62
48
  // `src/runlist.js` directly, in-process.
63
49
  import { panelMain } from './panel/server.js';
50
+ import { readHistoryLog } from './replayio.js';
64
51
  // PANEL-BUILD.md P1 (2026-09-24 rulings) — the one run list
65
- // (`~/.config/bareloop/runs.jsonl`) and its backfill scan. `bareloop runs`
66
- // (list) and `bareloop runs backfill <dir>` (reconstruct rows from archived
67
- // spines already on disk) are this rung's only new commands.
52
+ // (`~/.config/bareloop/runs.jsonl`); `bareloop runs` prints it. (`runs backfill` left the CLI, PRD v1.114; the library's `backfillRuns` stays.)
68
53
  import { keysForDoor } from './keysfile.js';
69
- import { readRunList, backfillRuns, formatRunRow } from './runlist.js';
54
+ import { readRunList, formatRunRow } from './runlist.js';
70
55
 
71
56
  /** @param {unknown} v @returns {v is Record<string, any>} */
72
57
  const isObj = (v) => typeof v === 'object' && v !== null;
73
58
 
59
+ /** The switches: flags that take no value, so the next word is never theirs (`run --yes <bundle>` keeps the bundle). */
60
+ const SWITCHES = new Set(['yes']);
61
+
74
62
  /** @param {string[]} args @returns {{ positional: string[], flags: Record<string, string|true> }} */
75
63
  function parseFlags(args) {
76
64
  /** @type {string[]} */
@@ -82,7 +70,7 @@ function parseFlags(args) {
82
70
  if (a.startsWith('--')) {
83
71
  const key = a.slice(2);
84
72
  const next = args[i + 1];
85
- if (next !== undefined && !next.startsWith('--')) { flags[key] = next; i++; } else flags[key] = true;
73
+ if (!SWITCHES.has(key) && next !== undefined && !next.startsWith('--')) { flags[key] = next; i++; } else flags[key] = true;
86
74
  } else positional.push(a);
87
75
  }
88
76
  return { positional, flags };
@@ -170,13 +158,83 @@ function doExport(args, { out, err, cwd }) {
170
158
  }
171
159
 
172
160
  /**
173
- * `bareloop history <bundleDir>`
174
- * @param {string[]} args @param {{ out: (s: string) => void, err: (s: string) => void, cwd: string }} ctx
161
+ * `bareloop export ["<job> (run-N)"] [--out <dir>]` — a bundle from a green panel / run-u run (PRD v1.114). No name = pick from the numbered
162
+ * list of green runs; no `--out` = ask for the folder. A required prompt answered empty twice ends the command cleanly (exit 0).
163
+ * @param {string[]} args @param {{ out: (s: string) => void, err: (s: string) => void, cwd: string, ask: (q: string) => Promise<string>, canAsk: boolean, deps: any }} ctx
164
+ * @returns {Promise<number>}
175
165
  */
176
- function doHistory(args, { out, err, cwd }) {
177
- const bundleDirArg = args[0];
178
- if (!bundleDirArg) { err('usage: bareloop history <bundleDir>'); return 1; }
179
- const dir = resolve(cwd, bundleDirArg);
166
+ async function doExportRun(args, { out, err, cwd, ask, canAsk, deps }) {
167
+ const { positional, flags } = parseFlags(args);
168
+ const home = deps.runlistHome;
169
+ /** @type {string|undefined} */
170
+ let name = positional[0];
171
+ if (name === undefined && !canAsk) { err('usage: bareloop export "<job> (run-N)" --out <dir>'); return 1; }
172
+ if (name === undefined) {
173
+ const runs = listGreenRuns(home === undefined ? {} : { home });
174
+ if (runs.length === 0) { out('No green runs to export yet.'); return 0; }
175
+ out('Green runs you can export:');
176
+ runs.forEach((r, i) => out(` ${i + 1} ${r.name}`));
177
+ const pick = await askRequired(ask, 'Number to export: ');
178
+ if (pick === null) { out('Nothing chosen, nothing exported.'); return 0; }
179
+ const hit = /^\d+$/.test(pick) ? runs[Number(pick) - 1] : runs.find((r) => r.name === pick);
180
+ if (!hit) { err(`"${pick}" is not one of the numbers above.`); return 1; }
181
+ name = hit.name;
182
+ }
183
+ /** @type {string|null} */
184
+ let outDirArg = typeof flags.out === 'string' ? flags.out : null;
185
+ if (outDirArg === null && !canAsk) { err('usage: bareloop export "<job> (run-N)" --out <dir>'); return 1; }
186
+ if (outDirArg === null) {
187
+ outDirArg = await askRequired(ask, 'Output folder (new or empty): ');
188
+ if (outDirArg === null) { out('No folder given, nothing exported.'); return 0; }
189
+ }
190
+ const r = exportRun({ name, outDir: resolve(cwd, outDirArg), home, bareloopVersion: readPackageVersion() });
191
+ if (!r.ok) { err(r.why); return 1; }
192
+ out(`exported "${r.name}" to ${r.dir}`);
193
+ out(`bundleHash: ${r.bundleHash}`);
194
+ out(`next: cd ${r.dir} && npm install`);
195
+ out(`then: bareloop run "${r.name}" --repo <your repo>`);
196
+ return 0;
197
+ }
198
+
199
+ /**
200
+ * The menu's Resume: the stopped / capped `bareloop run` runs the engine would resume, numbered; pick one, then the optional more money /
201
+ * more time (a higher cap asks for the typed yes), then it resumes exactly as `bareloop run <bundle> --resume <runid>` does.
202
+ * @param {any} ctx the CLI context with `ask`
203
+ * @returns {Promise<number>}
204
+ */
205
+ async function doResumeMenu(ctx) {
206
+ const { out, ask, deps } = ctx;
207
+ const home = deps.runlistHome;
208
+ const list = listResumableBundleRuns(home === undefined ? {} : { home });
209
+ if (list.length === 0) { out('No stopped runs to resume.'); return 0; }
210
+ const shown = list.slice(0, RECENT_BUNDLES);
211
+ out(list.length > shown.length ? `Stopped runs you can resume (the last ${shown.length} of ${list.length}; older ones by run id or folder):` : 'Stopped runs you can resume:');
212
+ shown.forEach((r, i) => out(` ${i + 1} ${r.label}`));
213
+ const pick = await askRequired(ask, 'Number to resume (or a run id, or a bundle folder): ');
214
+ if (pick === null) { out('Nothing chosen, nothing resumed.'); return 0; }
215
+ const hit = /^\d+$/.test(pick) ? shown[Number(pick) - 1] : list.find((r) => r.runid === pick || r.bundleDir === resolve(ctx.cwd, pick));
216
+ if (!hit) { ctx.err(`"${pick}" is not one of the numbers above, nor the run id or folder of a stopped run.`); return 1; }
217
+ return bundleMain([hit.bundleDir, '--resume', hit.runid], { ...ctx, guided: true, parseFlags, printReds });
218
+ }
219
+
220
+ /**
221
+ * `bareloop history [<bundle>]` — a bundle's run history. The bundle is a folder or the run name it was exported under; with none given
222
+ * it is asked (a number from the exported bundles, a name or a folder).
223
+ * @param {string[]} args @param {{ out: (s: string) => void, err: (s: string) => void, cwd: string, ask: (q: string) => Promise<string>, canAsk: boolean, deps: any }} ctx
224
+ * @returns {Promise<number>}
225
+ */
226
+ async function doHistory(args, { out, err, cwd, ask, canAsk, deps }) {
227
+ const home = deps.runlistHome;
228
+ let bundleDirArg = args[0];
229
+ if (!bundleDirArg) {
230
+ if (!canAsk) { err('usage: bareloop history <bundle>'); return 1; }
231
+ const r = await askBundle({ ask, out, ...(home === undefined ? {} : { home }), none: 'No exported bundles yet. Export one with 6.', cancelled: 'No bundle chosen, nothing shown.' });
232
+ if ('end' in r) return 0;
233
+ bundleDirArg = r.ref;
234
+ }
235
+ const found = resolveBundleRef(bundleDirArg, { ...(home === undefined ? {} : { home }), cwd });
236
+ if (!found.ok) { err(found.why); return 1; }
237
+ const dir = found.dir;
180
238
  const historyFile = join(dir, 'history.jsonl');
181
239
  if (existsSync(historyFile)) {
182
240
  // PANEL-BUILD.md P0 — the one reader for `history.jsonl` (`src/replayio.js`'s
@@ -200,74 +258,13 @@ function doHistory(args, { out, err, cwd }) {
200
258
  }
201
259
 
202
260
  /**
203
- * `bareloop replay <spine.jsonl>` — one run's whole story, reconstructed
204
- * from its spine + gate-audit sidecar, printed as one page
205
- * ({@link formatReplay}). `bareloop replay --all <dir>` — every spine found
206
- * directly in `dir`, one aligned table row each ({@link formatAllLines}).
207
- * Read-only, $0, mints no verdict, writes nothing (PANEL-BUILD.md P0: this
208
- * is the CLI the gap table marked "No" for "Replay an archived run at $0").
209
- * Logic lifted verbatim from `scripts/run-replay.mjs` into
210
- * `src/replayio.js`; this command is that script's one caller now, the same
211
- * shape `bareloop history`/`bareloop run` already are over their own
212
- * library functions.
213
- * @param {string[]} args @param {{ out: (s: string) => void, err: (s: string) => void, cwd: string }} ctx
261
+ * `bareloop runs` — print the one run list, one line per row ({@link formatRunRow}). Read-only, $0: no run trigger, no key ever read.
262
+ * (`runs backfill` left the CLI, PRD v1.114.)
263
+ * @param {string[]} _args @param {{ out: (s: string) => void, deps: any }} ctx
214
264
  */
215
- function doReplay(args, { out, err, cwd }) {
216
- if (args[0] === '--all') {
217
- const dirArg = args[1];
218
- if (!dirArg) { err('usage: bareloop replay --all <dir>'); return 1; }
219
- const dir = resolve(cwd, dirArg);
220
- if (!existsSync(dir)) { err(`no such directory: ${dir}`); return 1; }
221
- const entries = listSpines(dir);
222
- if (entries.length === 0) { out(`no .jsonl files found in ${dir}`); return 0; }
223
- out(formatAllLines(entries));
224
- return 0;
225
- }
226
- const spinePathArg = args[0];
227
- if (!spinePathArg) {
228
- err('usage: bareloop replay <spine.jsonl>');
229
- err(' bareloop replay --all <dir>');
230
- return 1;
231
- }
232
- const spinePath = resolve(cwd, spinePathArg);
233
- if (!existsSync(spinePath)) { err(`no such file: ${spinePath}`); return 1; }
234
- const spine = parseJsonl(spinePath);
235
- if (!looksLikeSpine(spine.records)) {
236
- err(`${spinePath} does not look like a spine (no job-start or run-start record found)`);
237
- return 1;
238
- }
239
- const summary = replayOne(spinePath, { preParsedSpine: spine });
240
- out(formatReplay(summary));
241
- return 0;
242
- }
243
-
244
- /**
245
- * `bareloop runs` — print the one run list, one line per row
246
- * ({@link formatRunRow}). `bareloop runs backfill <dir>` — scan `dir` for
247
- * archived spines and add a row per one not already listed
248
- * ({@link backfillRuns}), printing the count added/already-listed/skipped
249
- * (never silent). Read-only, $0: no interview, no author, no run trigger, no
250
- * key ever read.
251
- * @param {string[]} args @param {{ out: (s: string) => void, err: (s: string) => void, cwd: string }} ctx
252
- */
253
- function doRuns(args, { out, err, cwd }) {
254
- if (args[0] === 'backfill') {
255
- const dirArg = args[1];
256
- if (!dirArg) { err('usage: bareloop runs backfill <dir>'); return 1; }
257
- const dir = resolve(cwd, dirArg);
258
- if (!existsSync(dir)) { err(`no such directory: ${dir}`); return 1; }
259
- let result;
260
- try {
261
- result = backfillRuns(dir);
262
- } catch (e) {
263
- err(`backfill failed: ${/** @type {Error} */ (e).message}`);
264
- return 1;
265
- }
266
- out(`backfill ${dir}: added ${result.added}, already listed ${result.alreadyListed}, skipped ${result.skipped} (not a spine or unreadable)`);
267
- return 0;
268
- }
269
- const { rows, skipped } = readRunList();
270
- if (rows.length === 0) { out('runs: (none listed yet — see `bareloop runs backfill <dir>`)'); }
265
+ function doRuns(_args, { out, deps }) {
266
+ const { rows, skipped } = readRunList(deps.runlistHome === undefined ? {} : { home: deps.runlistHome });
267
+ if (rows.length === 0) { out('runs: (none listed yet)'); }
271
268
  else for (const row of rows) out(formatRunRow(row));
272
269
  if (skipped > 0) out(`(${skipped} malformed line${skipped === 1 ? '' : 's'} skipped)`);
273
270
  return 0;
@@ -278,29 +275,28 @@ function doRuns(args, { out, err, cwd }) {
278
275
  * `src/launcher.js`; this only supplies the home (the SAME one `main` resolved for the keys file and config.json) and the line reader.
279
276
  * `deps.launcher` is the test seam for every OS touch (ports, spawn, kill, opener, clock).
280
277
  * @param {string} cmd 'menu' | 'start' | 'stop' | 'status' | 'install' @param {string[]} rest
281
- * @param {any} deps @param {{ out: (s: string) => void, err: (s: string) => void }} io @param {string|undefined} home
278
+ * @param {any} deps @param {{ out: (s: string) => void, err: (s: string) => void, ask: (q: string) => Promise<string> }} io @param {string|undefined} home
282
279
  * @returns {Promise<number>}
283
280
  */
284
281
  async function runLauncher(cmd, rest, deps, io, home) {
285
- const rl = createInterface({ input: deps.stdin ?? process.stdin, output: deps.stdout ?? process.stdout });
286
- let closed = false;
287
- rl.once('close', () => { closed = true; });
288
282
  // a closed stdin answers '' (= the safe default: quit / "no"), never hangs
289
- const ask = (/** @type {string} */ q) => (closed ? Promise.resolve('') : Promise.race([
290
- rl.question(q),
291
- new Promise((resolve) => { rl.once('close', () => resolve('')); }),
292
- ]).then(String));
283
+ const ask = io.ask;
293
284
  const rawEnv = deps.processEnv ?? process.env;
294
- const d = { home, ask, paint: makePaint(deps.stdout ?? process.stdout, rawEnv), paintErr: makePaint(deps.stderr ?? process.stderr, rawEnv), ...(deps.launcher ?? {}) };
295
- try {
296
- if (cmd === 'start') return await startCmd(io, d);
297
- if (cmd === 'stop') return await stopCmd(rest, io, d);
298
- if (cmd === 'status') return await statusCmd(io, d);
299
- if (cmd === 'install') return await installCmd(io, d);
300
- return await menuCmd(io, d);
301
- } finally {
302
- rl.close();
303
- }
285
+ // the menu's job commands (PRD v1.114): each prompts for what it needs on the SAME asker as the menu
286
+ const jobCtx = /** @type {any} */ ({ ...io, canAsk: true }); // the full CLI context `main` passed as `io`
287
+ const jobs = {
288
+ export: () => doExportRun([], jobCtx),
289
+ run: () => bundleMain([], { ...jobCtx, guided: true, parseFlags, printReds }),
290
+ resume: () => doResumeMenu(jobCtx),
291
+ history: () => doHistory([], jobCtx),
292
+ };
293
+ const d = { home, jobs, ask, paint: makePaint(deps.stdout ?? process.stdout, rawEnv), paintErr: makePaint(deps.stderr ?? process.stderr, rawEnv), ...(deps.launcher ?? {}) };
294
+ if (cmd === 'start') return startCmd(io, d);
295
+ if (cmd === 'stop') return stopCmd(rest, io, d);
296
+ if (cmd === 'restart') return restartCmd(rest, io, d);
297
+ if (cmd === 'status') return statusCmd(io, d);
298
+ if (cmd === 'install') return installCmd(io, d);
299
+ return menuCmd(io, d);
304
300
  }
305
301
 
306
302
  /**
@@ -308,10 +304,20 @@ async function runLauncher(cmd, rest, deps, io, home) {
308
304
  * code, so `bin/bareloop.mjs` can set `process.exitCode` and let node flush
309
305
  * queued stdout on its own (F-something: `process.exit()` can discard it).
310
306
  * @param {string[]} argv
311
- * @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
307
+ * @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
312
308
  * @returns {Promise<number>}
313
309
  */
314
310
  export async function main(argv, deps = {}) {
311
+ /** @type {{ a: { ask: (q: string) => Promise<string>, close: () => void }|null }} */
312
+ const holder = { a: null };
313
+ try { return await mainInner(argv, deps, holder); } finally { holder.a?.close(); }
314
+ }
315
+
316
+ /**
317
+ * @param {string[]} argv @param {any} deps @param {{ a: { ask: (q: string) => Promise<string>, close: () => void }|null }} holder one readline for the whole command, opened on first use
318
+ * @returns {Promise<number>}
319
+ */
320
+ async function mainInner(argv, deps, holder) {
315
321
  // P4a item 1 — the keys file (`~/.config/bareloop/.env`) fills what the shell leaves
316
322
  // unset; the shell wins. An injected `deps.env` skips the file (tests never read the
317
323
  // real one) unless `deps.keysHome` names a home.
@@ -323,15 +329,22 @@ export async function main(argv, deps = {}) {
323
329
  const now = deps.now ?? (() => Date.now());
324
330
  const out = (/** @type {string} */ s) => stdout.write(`${s}\n`);
325
331
  const err = (/** @type {string} */ s) => stderr.write(`${s}\n`);
326
- const ctx = { out, err, cwd, env, now, deps };
332
+ const ask = (/** @type {string} */ q) => { holder.a ??= openAsker({ stdin: deps.stdin, stdout }); return holder.a.ask(q); };
333
+ // something to ask: a terminal, or a stdin the caller handed in as interactive (tests; `deps.interactive` defaults to "an injected stdin is").
334
+ // bin/bareloop.mjs always hands process.stdin in (the menu reads its choices from it, piped or not) and says `interactive: isTTY`, so a
335
+ // pipe or </dev/null never gets a question: a missing argument is the usage error. The menu is unaffected: runLauncher sets canAsk itself.
336
+ const canAsk = deps.interactive ?? (deps.stdin !== undefined || Boolean(process.stdin.isTTY));
337
+ const ctx = { out, err, cwd, env, now, deps, ask, canAsk, keysHome: keys.home };
327
338
 
328
339
  const [cmd, ...rest] = argv;
329
- if (keys.warning && cmd && ['run', 'run-u', 'interview', 'author', 'panel'].includes(cmd)) err(`WARNING: ${keys.warning}`);
340
+ if (keys.warning && cmd && ['run', 'run-u', 'panel'].includes(cmd)) err(`WARNING: ${keys.warning}`);
330
341
  const launcherHome = keys.home ?? deps.runlistHome;
331
342
  if (!cmd) return runLauncher('menu', [], { ...deps, stdout }, ctx, launcherHome);
332
- if (cmd === 'start' || cmd === 'stop' || cmd === 'status' || cmd === 'install') return runLauncher(cmd, rest, { ...deps, stdout }, ctx, launcherHome);
333
- if (cmd === 'export') return doExport(rest, ctx);
343
+ if (cmd === 'start' || cmd === 'stop' || cmd === 'restart' || cmd === 'status' || cmd === 'install') return runLauncher(cmd, rest, { ...deps, stdout }, ctx, launcherHome);
344
+ // the old form (`export <jobs/x.json> --registry <dir> --out <dir>`) is the bench's; the new one is by run name
345
+ if (cmd === 'export') return rest.includes('--registry') ? doExport(rest, ctx) : doExportRun(rest, ctx);
334
346
  if (cmd === 'run') return bundleMain(rest, { ...ctx, keysHome: keys.home, parseFlags, printReds });
347
+
335
348
  if (cmd === 'history') return doHistory(rest, ctx);
336
349
  // `bareloop run-u` — the person-path run flow (PANEL-BUILD.md P0 task
337
350
  // 2/4). `rest` is handed straight to `src/userrun.js`'s own `main(argv,
@@ -343,35 +356,15 @@ export async function main(argv, deps = {}) {
343
356
  // then `env`/`out`/`err` are overridden to the SAME resolved values every
344
357
  // other command here prints through, so `run-u`'s output lands on the
345
358
  // `stdout`/`stderr` a caller of `main` actually passed.
359
+ // (dispatchable, not listed in the menu or the help: the panel spawns it, PRD v1.114)
346
360
  if (cmd === 'run-u') return runUMain(rest, { ...deps, env, out, err, keysHome: keys.home, invokedAs: 'bareloop run-u' });
347
- // `bareloop interview` — the close-authoring interview (PANEL-BUILD.md P0
348
- // task 3/4). This flow reads a TTY (or a piped stdin) directly rather than
349
- // through the `out`/`err` line-functions every other command here uses, so
350
- // it needs the raw streams, not the wrapped ones — `stdout`/`stderr` (both
351
- // already resolved above) are handed through instead.
352
- // `invokedAs: 'bareloop interview'` — the usage message names the command a
353
- // person actually typed, never a script path they never invoked and may
354
- // not have on disk (a branch-review nit; `scripts/run-interview.mjs` still
355
- // supplies none, so it keeps naming itself when run directly).
356
- if (cmd === 'interview') return interviewMain(rest, { ...deps, env, keysHome: keys.home, stdin: deps.stdin ?? process.stdin, stdout, stderr, invokedAs: 'bareloop interview' });
357
- // `bareloop author` — the authoring pipeline (scout, declaration, D9's
358
- // gates), same task. Same raw-stream reasoning: its one interactive seam
359
- // (the confirm turn) reads stdin directly. Same `invokedAs` reasoning too.
360
- if (cmd === 'author') return authorMain(rest, { ...deps, env, keysHome: keys.home, stdin: deps.stdin ?? process.stdin, stdout, stderr, invokedAs: 'bareloop author' });
361
- // `bareloop replay` — the spine/gate-audit read side (PANEL-BUILD.md P0,
362
- // last of the rung's four tasks). Synchronous, file-based, no interactive
363
- // seam — same shape as `doHistory`/`doExport`, not the argv-owning
364
- // `main(argv, deps)` modules the flows above delegate to.
365
- if (cmd === 'replay') return doReplay(rest, ctx);
366
- // `bareloop runs` / `bareloop runs backfill <dir>` — PANEL-BUILD.md P1's
367
- // one run list. Read-only ($0): no interview, no author, no run trigger,
368
- // no key ever read.
361
+ // `bareloop runs` — PANEL-BUILD.md P1's one run list. Read-only ($0): no run trigger, no key ever read.
369
362
  if (cmd === 'runs') return doRuns(rest, ctx);
370
363
  // `bareloop panel [--port N]` — PANEL-BUILD.md P1's read-only HTTP panel.
371
364
  // Never runs a job, spends money, or reads a key: it serves the run list
372
365
  // and spine/gate-audit reads over `127.0.0.1` only. `deps.runlistHome`
373
366
  // rides through the same injectable seam `run`/`run-u` already use.
374
367
  if (cmd === 'panel') return panelMain(rest, { out, err, runlistHome: deps.runlistHome, env: deps.env });
375
- err(`unknown command ${JSON.stringify(cmd)} — one of: export, run, history, run-u, interview, author, replay, runs, panel, start, stop, status, install`);
368
+ err(`unknown command ${JSON.stringify(cmd)} — one of: export, run, history, runs, panel, start, stop, restart, status, install`);
376
369
  return 1;
377
370
  }
package/src/config.js CHANGED
@@ -9,7 +9,7 @@
9
9
  //
10
10
  // Shape (unknown fields are kept, never dropped):
11
11
  // { "monthlyLimitUsd": <number > 0>, // absent = no limit, no check
12
- // "learningHints": true|false, // absent = false: the planner is handed cross-run learnings (src/learn.js); the tally is kept either way
12
+ // "learningHints": true|false, // absent = true (ON by default; only false turns it off): the planner is handed cross-run learnings (src/learn.js); the tally is kept either way
13
13
  // "keys": { "<ENV NAME>": { "shape": "<shape id>", "baseUrl": "http(s)://…", "legacyMaxTokens": true|false } },
14
14
  // "models": { "<ENV NAME>": [ { "model": "<id>", "use": true|false, "inPerM": n, "outPerM": n } ] } }
15
15
  // An older file's `keys.<ENV>.{name,priceInPerM,priceOutPerM}` is tolerated and read as ONE model
package/src/draftspend.js CHANGED
@@ -3,21 +3,26 @@
3
3
  // A panel authoring session pays for model calls (survey, declaration, confirm turn) BEFORE any run exists.
4
4
  // That spend rode only in memory (`state.draftSpentUsd`) and reached disk when the session was signed and run
5
5
  // (`--draft-spent-usd` -> the run's spine). Abandon, a refusal, or a panel restart lost it, while the monthly
6
- // limit and the Money tab never counted it. So the session writes `<session dir>/draft-spend.json` after EVERY
7
- // metered call (one owner: the session's `onCall`, src/panel/authorsession.js), and the money readers
8
- // (`readLegs`, src/monthly.js) add every session folder that carries one and NEVER became a run.
6
+ // limit and the Money tab never counted it. So the session appends one `call` line to `<session dir>/draft-log.jsonl`
7
+ // after EVERY metered call (one owner: the session's `onCall`, src/panel/authorsession.js), and the money readers
8
+ // (`readLegs`, src/monthly.js) fold those lines with `tallyCalls` for every session folder that NEVER became a run.
9
+ // (Records ruling 2026-10-24: the total used to be a second file, `draft-spend.json`, rewritten beside the log. Things
10
+ // written and read together live together, so the log is the only record. A session folder from before the change that
11
+ // has the old file and no call lines is still read from that file, so old money is never lost.)
9
12
  //
10
13
  // "Became a run" = some run-list row's `spine` or `patient` path sits inside that session's folder: a signed run
11
- // already carries its drafting spend through `--draft-spent-usd`, so counting the file too would double it.
12
- // Month attribution is the file's `startedAt` (the first metered call): fixed once written, so a session's
14
+ // already carries its drafting spend through `--draft-spent-usd`, so counting the log too would double it.
15
+ // Month attribution is the first call's `at` (`startedAt`): fixed once written, so a session's
13
16
  // figure never moves between months as spend continues, the same start-date rule a run's leg uses.
14
17
  // `spendComplete: false` = "at least", never $0 (F6).
15
- import { appendFileSync, existsSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
18
+ import { appendFileSync, existsSync, readdirSync, readFileSync } from 'node:fs';
16
19
  import { join, resolve, sep } from 'node:path';
17
20
  import { readRunList, runlistHome } from './runlist.js';
21
+ import { tallyCalls } from './text.js';
18
22
 
23
+ /** the OLD per-session total, no longer written; read only for a session folder that predates the log's call lines carrying it */
19
24
  export const DRAFT_SPEND_FILE = 'draft-spend.json';
20
- /** the session's drafting LOG: an append-only JSONL beside draft-spend.json (one owner: the session, src/panel/authorsession.js). Three event kinds, see {@link DraftEvent}. */
25
+ /** the session's drafting LOG: an append-only JSONL (one owner: the session, src/panel/authorsession.js). Three event kinds, see {@link DraftEvent}. */
21
26
  export const DRAFT_LOG_FILE = 'draft-log.jsonl';
22
27
 
23
28
  /**
@@ -27,7 +32,7 @@ export const DRAFT_LOG_FILE = 'draft-log.jsonl';
27
32
  * - `step-label` {no, label, at} (the step reads `label` from now on, status and times untouched: the thinking row's "the model thought anyway" / "can't change it" / "not confirmed")
28
33
  * - `human` {no, source: 'confirm'|'try-3'|'look', question, answer, line?, at}: one question the person was asked and what they answered (the answer is secret-masked
29
34
  * before it is written; the row is written only when BOTH exist, so a question nobody answered leaves no row)
30
- * - `call` {no, step, label, model, thinking, thinkingSupport, thinkingStatus?, costUsd (null stays null), unpricedRounds, at}: one METERED model call
35
+ * - `call` {no, step, label, model, provider, baseUrl, thinking, thinkingSupport, thinkingStatus?, costUsd (null stays null), unpricedRounds, at}: one METERED model call
31
36
  * (`thinking` = the tick's mode: off | on; `thinkingSupport` = bare-agent's lookup for the model: true | false | 'unverified';
32
37
  * `thinkingStatus` = bare-agent's own verdict for the call's run: applied | unsupported | ignored | unknown, present only when thinkingMode was sent)
33
38
  * (no token counts: the call path does not carry them without reworking the library, so none are recorded)
@@ -35,7 +40,7 @@ export const DRAFT_LOG_FILE = 'draft-log.jsonl';
35
40
  */
36
41
 
37
42
  /**
38
- * Append one event to `<dir>/draft-log.jsonl`. Best-effort like draft-spend.json: a disk fault never stops the draft.
43
+ * Append one event to `<dir>/draft-log.jsonl`. Best-effort: a disk fault never stops the draft.
39
44
  * @param {string} dir the session's folder
40
45
  * @param {DraftEvent} ev
41
46
  * @returns {void}
@@ -56,24 +61,67 @@ export function appendDraftLog(dir, ev) {
56
61
  * @property {string} updatedAt ISO, the latest metered call
57
62
  */
58
63
 
64
+ /** @param {string} p @param {string} dir @returns {boolean} */
65
+ const inside = (p, dir) => typeof p === 'string' && (resolve(p) === dir || resolve(p).startsWith(dir + sep));
66
+
59
67
  /**
60
- * (Re)write `<dir>/draft-spend.json` atomically (tmp + rename).
61
- * @param {string} dir the session's folder
62
- * @param {DraftSpend} rec
63
- * @returns {void}
68
+ * One session's drafting spend from its log's `call` lines (the same `tallyCalls` reader the session's `onCall` uses).
69
+ * `null` = the log holds no call and nothing unparseable. A line that cannot be parsed is skipped like in
70
+ * {@link readDraftSteps}, but it may have been a call, so it makes the figure an "at least" (a torn line never reads low as exact).
71
+ * @param {string} name the session folder name
72
+ * @param {string} text the log
73
+ * @returns {DraftSpend|null}
64
74
  */
65
- export function writeDraftSpend(dir, rec) {
66
- const file = join(dir, DRAFT_SPEND_FILE);
67
- const tmp = `${file}.tmp`;
68
- writeFileSync(tmp, `${JSON.stringify(rec, null, 2)}\n`);
69
- renameSync(tmp, file);
75
+ function spendFromLog(name, text) {
76
+ /** @type {{costUsd: number|null, unpricedRounds: number}[]} */
77
+ const calls = [];
78
+ /** @type {any[]} */
79
+ const lines = [];
80
+ let torn = false;
81
+ for (const line of text.split('\n')) {
82
+ if (!line.trim()) continue;
83
+ let ev;
84
+ try { ev = JSON.parse(line); } catch { torn = true; continue; }
85
+ if (!ev || typeof ev !== 'object') { torn = true; continue; }
86
+ if (ev.kind !== 'call') continue;
87
+ calls.push({ costUsd: typeof ev.costUsd === 'number' ? ev.costUsd : null, unpricedRounds: Number(ev.unpricedRounds) || 0 });
88
+ lines.push(ev);
89
+ }
90
+ if (calls.length === 0) {
91
+ return torn ? { sessionId: name, spentUsd: 0, spendComplete: false, provider: null, baseUrl: null, model: null, startedAt: 'unreadable', updatedAt: 'unreadable' } : null;
92
+ }
93
+ const t = tallyCalls(calls);
94
+ /** @param {string} k @returns {string|null} the latest call line's value that has one */
95
+ const last = (k) => { for (let i = lines.length - 1; i >= 0; i -= 1) if (typeof lines[i][k] === 'string') return lines[i][k]; return null; };
96
+ return {
97
+ sessionId: name, spentUsd: t.knownUsd, spendComplete: t.spendComplete && !torn,
98
+ provider: last('provider'), baseUrl: last('baseUrl'), model: last('model'),
99
+ startedAt: String(lines[0].at), updatedAt: String(lines[lines.length - 1].at),
100
+ };
70
101
  }
71
102
 
72
- /** @param {string} p @param {string} dir @returns {boolean} */
73
- const inside = (p, dir) => typeof p === 'string' && (resolve(p) === dir || resolve(p).startsWith(dir + sep));
103
+ /**
104
+ * One session's LEGACY `draft-spend.json` (written before the log's call lines carried the total). An unreadable one is unknown
105
+ * spend: an "at least" of $0, dated unknown.
106
+ * @param {string} name @param {string} file @returns {DraftSpend}
107
+ */
108
+ function spendFromLegacyFile(name, file) {
109
+ try {
110
+ const j = JSON.parse(readFileSync(file, 'utf8'));
111
+ if (!j || typeof j !== 'object' || !Number.isFinite(j.spentUsd)) throw new Error('unreadable');
112
+ return {
113
+ sessionId: String(j.sessionId ?? name), spentUsd: j.spentUsd, spendComplete: j.spendComplete === true,
114
+ provider: typeof j.provider === 'string' ? j.provider : null, baseUrl: typeof j.baseUrl === 'string' ? j.baseUrl : null,
115
+ model: typeof j.model === 'string' ? j.model : null, startedAt: String(j.startedAt), updatedAt: String(j.updatedAt),
116
+ };
117
+ } catch {
118
+ return { sessionId: name, spentUsd: 0, spendComplete: false, provider: null, baseUrl: null, model: null, startedAt: 'unreadable', updatedAt: 'unreadable' };
119
+ }
120
+ }
74
121
 
75
122
  /**
76
- * Every session folder's drafting spend that never became a run.
123
+ * Every session folder's drafting spend that never became a run: folded from the log's `call` lines, else read from a legacy
124
+ * `draft-spend.json`; a folder with neither is skipped.
77
125
  * @param {{ home?: string, sessionsRoot?: string }} [opts] `home` = the bareloop config dir (as everywhere in src/monthly.js); the sessions live in `<home>/panel-sessions` unless `sessionsRoot` names them
78
126
  * @returns {DraftSpend[]}
79
127
  */
@@ -88,21 +136,27 @@ export function readOrphanDraftSpends(opts = {}) {
88
136
  const out = [];
89
137
  for (const name of names) {
90
138
  const dir = join(root, name);
91
- const file = join(dir, DRAFT_SPEND_FILE);
92
- if (!existsSync(file)) continue;
139
+ const logFile = join(dir, DRAFT_LOG_FILE);
140
+ const legacy = join(dir, DRAFT_SPEND_FILE);
141
+ const hasLog = existsSync(logFile);
142
+ const hasLegacy = existsSync(legacy);
143
+ if (!hasLog && !hasLegacy) continue;
93
144
  if (rows.some((r) => inside(r.spine, dir) || (r.patient && inside(r.patient, dir)))) continue;
94
- try {
95
- const j = JSON.parse(readFileSync(file, 'utf8'));
96
- if (!j || typeof j !== 'object' || !Number.isFinite(j.spentUsd)) throw new Error('unreadable');
97
- out.push({
98
- sessionId: String(j.sessionId ?? name), spentUsd: j.spentUsd, spendComplete: j.spendComplete === true,
99
- provider: typeof j.provider === 'string' ? j.provider : null, baseUrl: typeof j.baseUrl === 'string' ? j.baseUrl : null,
100
- model: typeof j.model === 'string' ? j.model : null, startedAt: String(j.startedAt), updatedAt: String(j.updatedAt),
101
- });
102
- } catch {
103
- // a file that names money but cannot be read is unknown spend: an "at least" of $0, dated unknown
104
- out.push({ sessionId: name, spentUsd: 0, spendComplete: false, provider: null, baseUrl: null, model: null, startedAt: 'unreadable', updatedAt: 'unreadable' });
145
+ /** @type {DraftSpend|null} */
146
+ let d = null;
147
+ if (hasLog) {
148
+ try { d = spendFromLog(name, readFileSync(logFile, 'utf8')); } catch {
149
+ // a log that names money but cannot be read is unknown spend, unless the legacy file still has the figure
150
+ d = hasLegacy ? null : { sessionId: name, spentUsd: 0, spendComplete: false, provider: null, baseUrl: null, model: null, startedAt: 'unreadable', updatedAt: 'unreadable' };
151
+ }
152
+ }
153
+ if (d === null && hasLegacy) d = spendFromLegacyFile(name, legacy);
154
+ else if (d !== null && hasLegacy) {
155
+ // call lines written before they carried the identity: the old file still names the provider row the money lands under
156
+ const old = spendFromLegacyFile(name, legacy);
157
+ d = { ...d, provider: d.provider ?? old.provider, baseUrl: d.baseUrl ?? old.baseUrl, model: d.model ?? old.model };
105
158
  }
159
+ if (d !== null) out.push(d);
106
160
  }
107
161
  return out;
108
162
  }
@@ -754,8 +754,8 @@ export async function main(argv, deps = {}) {
754
754
  }
755
755
 
756
756
  // ── 6. the paid step, which is a DIFFERENT process under a DIFFERENT ceiling ─
757
- // the PACKAGED door (`bin/` ships; `scripts/` does not): `bareloop author` takes the same flags as run-author
758
- const BARELOOP_BIN = fileURLToPath(new URL('../bin/bareloop.mjs', import.meta.url));
757
+ // `bareloop author` left the CLI (PRD v1.114): the paid step is `scripts/run-author.mjs`, which takes the same flags
758
+ const AUTHOR_SCRIPT = fileURLToPath(new URL('../scripts/run-author.mjs', import.meta.url));
759
759
  const childArgs = [
760
760
  '--source', TREE, '--answers', answersFile, '--draft', draftFile,
761
761
  '--verdict', VERDICT, '--out', OUT,
@@ -775,7 +775,7 @@ export async function main(argv, deps = {}) {
775
775
  say(`It runs under the AUTHORING ceiling (${CEILING_USD === null ? 'UNBOUNDED — you gave no --budget' : `$${CEILING_USD}`}), which is not the job's $${draft.budgetUsd}.`);
776
776
  say('It stops at prepareSigning: it never signs, and it never runs the job.');
777
777
  } else {
778
- say('NEXT — running bareloop author on this source stops right away, at $0: no scout, no confirm turn, no model call.');
778
+ say('NEXT — running scripts/run-author.mjs on this source stops right away, at $0: no scout, no confirm turn, no model call.');
779
779
  say('It never signs and never runs the job — bareloop has no checks for this kind of job yet.');
780
780
  }
781
781
  say('');
@@ -790,7 +790,7 @@ export async function main(argv, deps = {}) {
790
790
  const worker = resolveWorker(keyRowsNow, { provider: PROVIDER, baseUrl: draft.baseUrl, model: modelArg });
791
791
  const providerEnvKey = worker.ok ? worker.row.envName : null;
792
792
  say(` ${providerEnvKey ?? 'YOUR_KEY_NAME'}=... ${commandFor('author', deps.invokedAs)} ${childArgs.join(' ')}`);
793
- if (!worker.ok) say(` (${worker.say.replace(' Nothing was spent.', '')} — bareloop author stops at $0 until it is)`);
793
+ if (!worker.ok) say(` (${worker.say.replace(' Nothing was spent.', '')} — scripts/run-author.mjs stops at $0 until it is)`);
794
794
  // NO KEY, NO OFFER. `run-author.mjs` refuses without one and exits 2 at its own door, before a spine exists — so with the shell
795
795
  // unkeyed this question has exactly one possible outcome for the person, and putting it anyway spends their attention on a choice
796
796
  // they do not have. F181 — a key that IS set can still carry a shape run-author will refuse (a line break/control char/stray
@@ -801,11 +801,11 @@ export async function main(argv, deps = {}) {
801
801
  if (!KEYED) {
802
802
  say('');
803
803
  if (providerEnvKey && keyProblem) {
804
- say(` (${providerEnvKey} is set but ${keyProblem} — bareloop author refuses without a clean key; secrets are never trimmed or repaired, only reported)`);
804
+ say(` (${providerEnvKey} is set but ${keyProblem} — scripts/run-author.mjs refuses without a clean key; secrets are never trimmed or repaired, only reported)`);
805
805
  } else {
806
806
  say(providerEnvKey
807
- ? ` (${providerEnvKey} is not set in this shell — bareloop author refuses without it; secrets load from the environment, never the tree)`
808
- : ' (no key row serves this model yet — bareloop author refuses it at $0; this is not a key problem)');
807
+ ? ` (${providerEnvKey} is not set in this shell — scripts/run-author.mjs refuses without it; secrets load from the environment, never the tree)`
808
+ : ' (no key row serves this model yet — scripts/run-author.mjs refuses it at $0; this is not a key problem)');
809
809
  }
810
810
  // The repair, in plain words and WITHOUT a command: which secret store a person
811
811
  // keeps their key in is theirs, and printing one specific incantation would be
@@ -822,9 +822,9 @@ export async function main(argv, deps = {}) {
822
822
  : null;
823
823
  if (depsGapAtHandoff) {
824
824
  say('');
825
- say(` The copy still has no installed packages (${depsGapAtHandoff.reason}) — bareloop author would only instrument-stop on it.`);
825
+ say(` The copy still has no installed packages (${depsGapAtHandoff.reason}) — scripts/run-author.mjs would only instrument-stop on it.`);
826
826
  say(` cd ${prep.tree} && ${depsGapAtHandoff.command}`);
827
- say(' then run bareloop author yourself with the command above.');
827
+ say(' then run scripts/run-author.mjs yourself with the command above.');
828
828
  }
829
829
  say('');
830
830
  // The default is NO, and it is the same lean the pause's doors take: the answer that
@@ -853,9 +853,9 @@ export async function main(argv, deps = {}) {
853
853
  exitCode = 0;
854
854
  } else {
855
855
  say('');
856
- const child = spawnSyncFn(process.execPath, [BARELOOP_BIN, 'author', ...childArgs], { stdio: 'inherit' });
856
+ const child = spawnSyncFn(process.execPath, [AUTHOR_SCRIPT, ...childArgs], { stdio: 'inherit' });
857
857
  if (child.error) {
858
- say(`bareloop author could not be started (${child.error.message}) — the command above still stands.`);
858
+ say(`scripts/run-author.mjs could not be started (${child.error.message}) — the command above still stands.`);
859
859
  exitCode = 2;
860
860
  } else {
861
861
  // the child's own exit is the answer: a refusal there is a RESULT, and flattening