fwdloop 0.5.0 → 0.7.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/bin/fwdloop ADDED
@@ -0,0 +1,559 @@
1
+ #!/usr/bin/env node
2
+ // M3 piece 2 (docs/wiki/the-module-ladder.md, "M3 — scope, exit, negative —
3
+ // SIGNED", scope item 9): the CLI. Stdlib only (`node:util` `parseArgs`),
4
+ // no new dependency. Four verbs — `run`, `inbox`, `answer`, `resume` — wired
5
+ // from `src/` only (this file never imports from `poc/`; the live pieces
6
+ // here are the same ones `poc/m2/live.mjs` proved: `makeLiveModelStep`,
7
+ // `sendViaPrimitive`, `resolvePrimitives`, `checkKeyPreflight`).
8
+ //
9
+ // borrowed-from: fwdloop poc/m2/live.mjs@748359d (the live-run wiring shape:
10
+ // preflight the key before touching a run dir, predict the frozen input
11
+ // paths so `resolvePrimitives` can build sandboxed tools before `runFlow`
12
+ // itself freezes anything, drive `runFlow`/`sendViaPrimitive` for real).
13
+ // Rewritten as the shipped, four-verb CLI (park-and-exit instead of an
14
+ // in-process wait, plus `inbox`/`answer`/`resume`) — src/ never imports
15
+ // from poc/, and poc/ is not part of the published package.
16
+
17
+ import { parseArgs } from 'node:util';
18
+ import { existsSync, realpathSync } from 'node:fs';
19
+ import { extname, join, resolve } from 'node:path';
20
+ import { pathToFileURL } from 'node:url';
21
+ import { randomUUID } from 'node:crypto';
22
+
23
+ import {
24
+ readFlow, checkFlowName, resolveRunDir, listFlowNames, listRunIds, readFileInside,
25
+ } from '../src/flow.js';
26
+ import { loadCatalogue } from '../src/catalogue.js';
27
+ import {
28
+ runFlow, resumeRun, makeParkingAskStep, readAsk,
29
+ } from '../src/runner.js';
30
+ import { makeLiveModelStep } from '../src/model-step.js';
31
+ import { sendViaPrimitive } from '../src/send.js';
32
+ import { resolvePrimitives } from '../src/primitives.js';
33
+ import { checkKeyPreflight } from '../src/provider.js';
34
+ import { answerAsk, readAskEvidence } from '../src/ask.js';
35
+ import { panelMain } from '../src/panel/server.js';
36
+
37
+ // The baseline model (project rule, CLAUDE.md/AGENT_RULES: "deepseek-flash
38
+ // ... Never Claude for fwdloop's own runs") — the ONE provider slot this CLI
39
+ // drives. `PROVIDER_SLOTS.deepseek.envVar` is `DEEPSEEK_API_KEY`; this CLI
40
+ // never reads a key any other way and never prints it.
41
+ const MODEL_SLOT = 'deepseek';
42
+
43
+ function fail(message) {
44
+ process.stderr.write(`fwdloop: ${message}\n`);
45
+ process.exit(1);
46
+ }
47
+
48
+ /**
49
+ * The ONE place a human-typed `--root` becomes a path (hamr ruling
50
+ * 2026-09-29): resolved to its real path once, at command start. Nothing
51
+ * inside the root is ever followed; that stays under bareguard's symlink
52
+ * refusal.
53
+ */
54
+ function resolveRoot(cmd, given) {
55
+ try {
56
+ return realpathSync(resolve(given));
57
+ } catch (err) {
58
+ if (err.code === 'ENOENT') fail(`${cmd}: --root "${given}" does not exist`);
59
+ fail(`${cmd}: --root "${given}" cannot be resolved: ${err.code ?? err.message}`);
60
+ }
61
+ }
62
+
63
+ function today() {
64
+ return new Date().toISOString().slice(0, 10);
65
+ }
66
+
67
+ /**
68
+ * Build the run's `modelStep`. Live by default (`makeLiveModelStep` against
69
+ * `MODEL_SLOT`, refusing an unset/empty/whitespace key via
70
+ * `checkKeyPreflight` BEFORE this function returns — i.e. before the caller
71
+ * has created a run dir or written any book row).
72
+ *
73
+ * Test-only escape hatch, never a user-facing flag: active ONLY when BOTH
74
+ * `NODE_ENV==='test'` AND `FWDLOOP_TEST_MODEL_STEP` (a module path) are set.
75
+ * A live invocation of this CLI is never launched with `NODE_ENV=test`, so
76
+ * there is no way to reach a fake model in production; and setting
77
+ * `FWDLOOP_TEST_MODEL_STEP` alone (without `NODE_ENV=test`) does nothing —
78
+ * two independent gates, neither of them a documented option, so it cannot
79
+ * be hit by a user typing `--something`. This is how the test suite drives
80
+ * every CLI scenario at $0 with zero chance of a real network call.
81
+ */
82
+ async function resolveModelStep(spendPath) {
83
+ if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
84
+ const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
85
+ const mod = await import(pathToFileURL(modulePath).href);
86
+ if (typeof mod.default !== 'function') {
87
+ throw new Error(`FWDLOOP_TEST_MODEL_STEP module "${modulePath}" has no default export function`);
88
+ }
89
+ return mod.default({ spendPath });
90
+ }
91
+ const keyCheck = checkKeyPreflight(MODEL_SLOT);
92
+ if (!keyCheck.ok) throw new Error(keyCheck.message);
93
+ return makeLiveModelStep({ slot: MODEL_SLOT, spendPath });
94
+ }
95
+
96
+ function parseSourceFlags(list) {
97
+ const out = {};
98
+ for (const entry of list ?? []) {
99
+ const eq = entry.indexOf('=');
100
+ if (eq <= 0) throw new Error(`--source "${entry}" is not "role=path"`);
101
+ const role = entry.slice(0, eq);
102
+ const value = entry.slice(eq + 1);
103
+ if (value.length === 0) throw new Error(`--source "${entry}" has an empty path`);
104
+ out[role] = resolve(value);
105
+ }
106
+ return out;
107
+ }
108
+
109
+ // F48 round 3 (docs/logs/FINDINGS.md): this CLI must never build a run path
110
+ // by hand — every flow/runId it walks goes through `listFlowNames`/
111
+ // `listRunIds`/`resolveRunDir` (`src/flow.js`, the same checked builders
112
+ // `src/panel/data.js` already uses), and every `ask.json` it reads goes
113
+ // through `readAsk` (`src/runner.js`, itself routed through
114
+ // `readFileInside`) — never a private `join()` + raw `readFileSync`. Closes
115
+ // the CLI-side half of F48: a symlinked flow/run/ask.json (or a hand-placed
116
+ // directory whose name would fail `checkFlowName`/`checkRunId`) is skipped
117
+ // here exactly as it already is by the panel, instead of being followed.
118
+ function findRunDirByAskId(root, askId) {
119
+ for (const flow of listFlowNames(root)) {
120
+ const flowDir = join(root, flow);
121
+ for (const runId of listRunIds(flowDir)) {
122
+ const resolved = resolveRunDir(flowDir, runId);
123
+ if (!resolved.ok) continue; // eslint-disable-line no-continue
124
+ const ask = readAsk(resolved.runDir);
125
+ if (ask && ask.askId === askId) return resolved.runDir;
126
+ }
127
+ }
128
+ return null;
129
+ }
130
+
131
+ /** Reports a `runFlow`/`resumeRun` result to stdout/stderr and sets the
132
+ * process exit code. A `rerun` outcome also reports the new run it just
133
+ * started (recursively — the new run may itself be paused/complete/a red),
134
+ * so a human watching a `run`/`resume` invocation sees the WHOLE chain,
135
+ * never just the old run's own half of it. */
136
+ function reportRunResult(result, { rootArg }) {
137
+ if (result.outcome === 'paused') {
138
+ process.stdout.write(`parked: askId=${result.askId} expiresAt=${result.expiresAt} spentUsd=${result.spentUsd}\n`);
139
+ process.stdout.write(`fwdloop answer ${result.askId} accept|reject "<reason>"|rerun "<reason>" --root ${rootArg}\n`);
140
+ return;
141
+ }
142
+ if (result.outcome === 'complete') {
143
+ process.stdout.write(`complete: spentUsd=${result.spentUsd}\n`);
144
+ return;
145
+ }
146
+ if (result.outcome === 'rerun') {
147
+ process.stdout.write(`rerun: oldRunId=${result.runId} newRunId=${result.newRunId} spentUsd=${result.spentUsd}\n`);
148
+ reportRunResult(result.newRun, { rootArg });
149
+ return;
150
+ }
151
+ if (result.outcome === 'ask-expired') {
152
+ process.stderr.write(`fwdloop: ask-expired — run cancelled, spentUsd=${result.spentUsd}\n`);
153
+ process.exitCode = 1;
154
+ return;
155
+ }
156
+ process.stderr.write(`fwdloop: ${result.outcome}${result.red ? ` — ${result.red}` : ''}\n`);
157
+ process.exitCode = 1;
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // run
162
+ // ---------------------------------------------------------------------------
163
+
164
+ async function cmdRun(rest) {
165
+ const { values, positionals } = parseArgs({
166
+ args: rest,
167
+ options: {
168
+ root: { type: 'string' },
169
+ source: { type: 'string', multiple: true, default: [] },
170
+ 'run-id': { type: 'string' },
171
+ },
172
+ allowPositionals: true,
173
+ });
174
+
175
+ const flowName = positionals[0];
176
+ if (!flowName) fail('run: a flow name is required — fwdloop run <flow> --root <dir> --source <role>=<path> ...');
177
+ if (!values.root) fail('run: --root <dir> is required');
178
+
179
+ const root = resolveRoot('run', values.root);
180
+ const nameCheck = checkFlowName(flowName);
181
+ if (!nameCheck.ok) fail(nameCheck.red);
182
+
183
+ const loaded = loadCatalogue();
184
+ if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
185
+ const catalogue = loaded.primitives;
186
+
187
+ const read = readFlow({ root, name: flowName, catalogue });
188
+ if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
189
+ const { arbiter, declaration } = read;
190
+
191
+ let parsedSources;
192
+ try {
193
+ parsedSources = parseSourceFlags(values.source);
194
+ } catch (err) {
195
+ fail(`run: ${err.message}`);
196
+ return;
197
+ }
198
+ const declaredRoles = (arbiter.sources ?? []).map((s) => s.role);
199
+ for (const role of declaredRoles) {
200
+ if (!Object.hasOwn(parsedSources, role)) {
201
+ fail(`run: flow "${flowName}" declares source role "${role}" — pass --source ${role}=<path>`);
202
+ }
203
+ }
204
+ for (const role of Object.keys(parsedSources)) {
205
+ if (!declaredRoles.includes(role)) {
206
+ fail(`run: --source role "${role}" is not declared by flow "${flowName}" (known roles: ${declaredRoles.join(', ') || '(none)'})`);
207
+ }
208
+ }
209
+ const sources = declaredRoles.map((role) => ({ id: role, path: parsedSources[role] }));
210
+ for (const src of sources) {
211
+ if (!existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
212
+ }
213
+
214
+ const runId = values['run-id'] ?? `run-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
215
+ const runIdCheck = resolveRunDir(join(root, flowName), runId);
216
+ if (!runIdCheck.ok) fail(runIdCheck.red);
217
+ const { runDir } = runIdCheck;
218
+ if (existsSync(runDir)) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
219
+
220
+ // The key preflight (item A: "refuses at $0 BEFORE any book write") runs
221
+ // here — before ANY directory for this run is created.
222
+ const spendPath = join(runDir, 'spend.jsonl');
223
+ let modelStep;
224
+ try {
225
+ modelStep = await resolveModelStep(spendPath);
226
+ } catch (err) {
227
+ fail(err.message);
228
+ return;
229
+ }
230
+
231
+ // Predict the frozen input paths `runFlow`'s own `freezeInputs` will use
232
+ // (deterministic: `<runDir>/inputs/<id><ext>`) so the primitives map can
233
+ // be built once, before `runFlow` itself freezes anything. Pure path
234
+ // arithmetic — `resolvePrimitives` only needs the STRINGS, never the
235
+ // directory to actually exist yet — so nothing under `runDir` is created
236
+ // here. `runFlow` itself now carries the F46 unwired-verb preflight
237
+ // refusal (moved to `src/runner.js` so any caller — this CLI, M4's web
238
+ // panel — gets it for free); it also owns the ONLY `mkdirSync`/
239
+ // `freezeInputs` for this run dir, so a refusal leaves nothing behind.
240
+ const predictedInputs = sources.map((s) => ({ id: s.id, frozen: join(runDir, 'inputs', `${s.id}${extname(s.path)}`) }));
241
+ const allVerbs = [...new Set(declaration.steps.flatMap((s) => s.primitives ?? []))];
242
+ const { tools: primitives, reds: primitiveReds } = resolvePrimitives(catalogue, allVerbs, { runDir, inputs: predictedInputs });
243
+
244
+ const result = await runFlow({
245
+ root,
246
+ name: flowName,
247
+ runId,
248
+ sources,
249
+ catalogue,
250
+ modelStep,
251
+ askStep: makeParkingAskStep(),
252
+ sendStep: sendViaPrimitive,
253
+ primitives,
254
+ primitiveReds,
255
+ businessDate: today(),
256
+ });
257
+
258
+ reportRunResult(result, { rootArg: values.root });
259
+ }
260
+
261
+ // ---------------------------------------------------------------------------
262
+ // inbox
263
+ // ---------------------------------------------------------------------------
264
+
265
+ function cmdInbox(rest) {
266
+ const { values } = parseArgs({
267
+ args: rest,
268
+ options: { root: { type: 'string' } },
269
+ });
270
+ const root = resolveRoot('inbox', values.root ?? '.');
271
+
272
+ const rows = [];
273
+ // F48 round 3: flow/run identity is walked via `listFlowNames`/
274
+ // `listRunIds`/`resolveRunDir` (never a private `join()`), and `ask.json`
275
+ // is read via `readFileInside` (both `src/flow.js`) — a symlinked
276
+ // ask.json, or a symlinked run/flow dir, is treated as "missing" here,
277
+ // never followed.
278
+ for (const flow of listFlowNames(root)) {
279
+ const flowDir = join(root, flow);
280
+ for (const runId of listRunIds(flowDir)) {
281
+ const resolved = resolveRunDir(flowDir, runId);
282
+ if (!resolved.ok) continue; // eslint-disable-line no-continue
283
+ const runDir = resolved.runDir;
284
+ const askRead = readFileInside(runDir, 'ask.json');
285
+ if (!askRead.ok) continue; // eslint-disable-line no-continue -- missing (or refused) ask.json: nothing to show
286
+ let ask;
287
+ try {
288
+ ask = JSON.parse(askRead.text);
289
+ } catch (err) {
290
+ // A malformed/unparseable ask.json must never crash inbox — show it
291
+ // naming the run as unreadable and move on to the next one.
292
+ rows.push({ flow, runId, status: 'unreadable', detail: `ask.json could not be parsed — ${err.message}` });
293
+ // eslint-disable-next-line no-continue
294
+ continue;
295
+ }
296
+ // An M2-era ask.json carries no `askId`/`expiresAt` (this CLI's
297
+ // answer/resume verbs can't act on it — they key everything off
298
+ // `askId`). Shown as "legacy (not answerable)", never "open": an ask
299
+ // this CLI cannot answer must never be reported as one it can.
300
+ if (typeof ask.askId !== 'string' || typeof ask.expiresAt !== 'string') {
301
+ rows.push({ flow, runId, status: 'legacy', question: ask.question });
302
+ // eslint-disable-next-line no-continue
303
+ continue;
304
+ }
305
+ // Signed item 6: expiry is checked whenever anyone touches the run —
306
+ // for `inbox` that means SHOWING an expired ask, never cancelling it
307
+ // (cancelling happens only at answer/resume, which re-verify anyway).
308
+ // Consumed-marker check also goes through `readFileInside` — a
309
+ // symlinked consumed marker is treated as "not consumed" (still shown
310
+ // as open/expired), never as proof the ask was answered.
311
+ if (readFileInside(runDir, `answer.${ask.askId}.consumed.json`).ok) continue; // eslint-disable-line no-continue -- this specific ask is already answered
312
+ // A present-but-unparseable expiresAt (Date.parse -> NaN) must never
313
+ // read as "not expired" — `Date.now() > NaN` is false, so the naive
314
+ // compare below would show this as [open] with a "NaNs left"
315
+ // countdown. Shown as [unreadable] naming the run instead, same as a
316
+ // malformed ask.json — never [open], never a NaN countdown.
317
+ if (Number.isNaN(Date.parse(ask.expiresAt))) {
318
+ rows.push({
319
+ flow, runId, status: 'unreadable', detail: `ask.json expiresAt "${ask.expiresAt}" is not a parseable date`,
320
+ });
321
+ // eslint-disable-next-line no-continue
322
+ continue;
323
+ }
324
+ const expired = Date.now() > Date.parse(ask.expiresAt);
325
+ const timeLeftMs = Date.parse(ask.expiresAt) - Date.now();
326
+ rows.push({
327
+ askId: ask.askId, flow, runId, question: ask.question, status: expired ? 'expired' : 'open', timeLeftMs,
328
+ });
329
+ }
330
+ }
331
+
332
+ if (rows.length === 0) {
333
+ process.stdout.write('inbox: no open asks\n');
334
+ return;
335
+ }
336
+ for (const row of rows) {
337
+ if (row.status === 'unreadable') {
338
+ process.stdout.write(`flow=${row.flow} run=${row.runId} [unreadable] ${row.detail}\n`);
339
+ continue;
340
+ }
341
+ if (row.status === 'legacy') {
342
+ process.stdout.write(`flow=${row.flow} run=${row.runId} [legacy (not answerable)] — ${row.question}\n`);
343
+ continue;
344
+ }
345
+ const timeLeft = row.status === 'expired' ? 'expired' : `${Math.max(0, Math.round(row.timeLeftMs / 1000))}s left`;
346
+ process.stdout.write(`${row.askId} flow=${row.flow} run=${row.runId} [${row.status}] ${timeLeft} — ${row.question}\n`);
347
+ }
348
+ }
349
+
350
+ // ---------------------------------------------------------------------------
351
+ // show — read-only: prints a parked ask's question, expiry, and evidence
352
+ // (the artifact under review, then each unjudged artifact labelled by
353
+ // step). F45 finding 2's other half: `inbox` says an ask is open, `show`
354
+ // is how a human actually sees what they'd be accepting. Never writes.
355
+ // ---------------------------------------------------------------------------
356
+
357
+ function cmdShow(rest) {
358
+ const { values, positionals } = parseArgs({
359
+ args: rest,
360
+ options: { root: { type: 'string' } },
361
+ allowPositionals: true,
362
+ });
363
+ const [askId] = positionals;
364
+ if (!askId) fail('show: an askId is required — fwdloop show <askId> --root <dir>');
365
+
366
+ const root = resolveRoot('show', values.root ?? '.');
367
+ const runDir = findRunDirByAskId(root, askId);
368
+ if (!runDir) fail(`show: no open ask found for askId "${askId}" under ${root}`);
369
+
370
+ // F48 round 3: routed through `readFileInside` (`src/flow.js`) — a
371
+ // symlinked ask.json is refused by name here, never read through.
372
+ const askRead = readFileInside(runDir, 'ask.json');
373
+ if (!askRead.ok) {
374
+ fail(askRead.missing
375
+ ? `show: no ask.json for askId "${askId}"`
376
+ : `show: ask.json for askId "${askId}" — ${askRead.red}`);
377
+ return;
378
+ }
379
+ let ask;
380
+ try {
381
+ ask = JSON.parse(askRead.text);
382
+ } catch (err) {
383
+ fail(`show: ask.json for askId "${askId}" is not valid JSON — ${err.message}`);
384
+ return;
385
+ }
386
+
387
+ process.stdout.write(`question: ${ask.question}\n`);
388
+ process.stdout.write(`expiresAt: ${ask.expiresAt}\n`);
389
+
390
+ const { draft, unjudged, why } = readAskEvidence(ask);
391
+ if (!draft) {
392
+ process.stdout.write(`\n(no evidence recorded on this ask — ${why})\n`);
393
+ return;
394
+ }
395
+ process.stdout.write('\n--- artifact under review ---\n');
396
+ process.stdout.write(`${draft.text}\n`);
397
+ for (const item of unjudged) {
398
+ process.stdout.write(`\n--- unjudged: ${item.step} ---\n`);
399
+ process.stdout.write(`${item.text}\n`);
400
+ }
401
+ }
402
+
403
+ // ---------------------------------------------------------------------------
404
+ // answer
405
+ // ---------------------------------------------------------------------------
406
+
407
+ function cmdAnswer(rest) {
408
+ const { values, positionals } = parseArgs({
409
+ args: rest,
410
+ options: { root: { type: 'string' } },
411
+ allowPositionals: true,
412
+ });
413
+ const [askId, decision, reason] = positionals;
414
+ if (!askId) fail('answer: an askId is required — fwdloop answer <askId> accept|reject "<reason>"|rerun "<reason>"');
415
+ if (!decision) fail(`answer: a decision (accept|reject|rerun) is required for askId "${askId}"`);
416
+
417
+ const root = resolveRoot('answer', values.root ?? '.');
418
+ const runDir = findRunDirByAskId(root, askId);
419
+ if (!runDir) fail(`answer: no open ask found for askId "${askId}" under ${root}`);
420
+
421
+ const result = answerAsk({
422
+ runDir, askId, decision, reason,
423
+ });
424
+ if (!result.ok) fail(result.red);
425
+
426
+ process.stdout.write(`answered: askId=${askId} decision=${decision}\n`);
427
+ }
428
+
429
+ // ---------------------------------------------------------------------------
430
+ // resume
431
+ // ---------------------------------------------------------------------------
432
+
433
+ async function cmdResume(rest) {
434
+ const { values, positionals } = parseArgs({
435
+ args: rest,
436
+ options: {
437
+ flow: { type: 'string' },
438
+ root: { type: 'string' },
439
+ },
440
+ allowPositionals: true,
441
+ });
442
+ const runId = positionals[0];
443
+ if (!runId) fail('resume: a runId is required — fwdloop resume <runId> --flow <name> --root <dir>');
444
+ if (!values.flow) fail('resume: --flow <name> is required');
445
+ if (!values.root) fail('resume: --root <dir> is required');
446
+
447
+ const root = resolveRoot('resume', values.root);
448
+ const flowName = values.flow;
449
+
450
+ const loaded = loadCatalogue();
451
+ if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
452
+ const catalogue = loaded.primitives;
453
+
454
+ const read = readFlow({ root, name: flowName, catalogue });
455
+ if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
456
+ const { declaration } = read;
457
+
458
+ const runIdCheck = resolveRunDir(join(root, flowName), runId);
459
+ if (!runIdCheck.ok) fail(runIdCheck.red);
460
+ const { runDir } = runIdCheck;
461
+ if (!existsSync(runDir)) fail(`resume: no run dir for runId "${runId}" under flow "${flowName}"`);
462
+
463
+ const spendPath = join(runDir, 'spend.jsonl');
464
+ let modelStep;
465
+ try {
466
+ modelStep = await resolveModelStep(spendPath);
467
+ } catch (err) {
468
+ fail(err.message);
469
+ return;
470
+ }
471
+
472
+ // Resume never re-freezes inputs — the run's own `inputs.json` (written at
473
+ // park by `freezeInputs`) is the one source of the already-frozen paths a
474
+ // sandboxed primitive may read.
475
+ // F48 round 3: routed through `readFileInside` (`src/flow.js`) — a
476
+ // symlinked `inputs.json` is treated as "no manifest" (empty array) rather
477
+ // than followed, which would otherwise let an outside file's content name
478
+ // arbitrary "frozen" paths for the sandboxed read/grep/readDocx/
479
+ // addressCells tools built just below.
480
+ const inputsManifestRead = readFileInside(runDir, 'inputs.json');
481
+ let inputsManifest = [];
482
+ if (inputsManifestRead.ok) {
483
+ try {
484
+ inputsManifest = JSON.parse(inputsManifestRead.text);
485
+ } catch (err) {
486
+ fail(`resume: inputs.json for run "${runId}" is not valid JSON — ${err.message}`);
487
+ return;
488
+ }
489
+ }
490
+ const allVerbs = [...new Set(declaration.steps.flatMap((s) => s.primitives ?? []))];
491
+ // F46's unwired-verb preflight refusal now lives in `resumeRun` itself
492
+ // (`src/runner.js`) — this CLI no longer keeps a second copy of the check.
493
+ const { tools: primitives, reds: primitiveReds } = resolvePrimitives(catalogue, allVerbs, {
494
+ runDir, inputs: inputsManifest.map((m) => ({ id: m.id, frozen: m.frozen })),
495
+ });
496
+
497
+ const result = await resumeRun({
498
+ root,
499
+ name: flowName,
500
+ runId,
501
+ catalogue,
502
+ modelStep,
503
+ sendStep: sendViaPrimitive,
504
+ primitives,
505
+ primitiveReds,
506
+ businessDate: today(),
507
+ });
508
+
509
+ reportRunResult(result, { rootArg: values.root });
510
+ }
511
+
512
+ // ---------------------------------------------------------------------------
513
+ // panel — M4a piece 2 (docs/wiki/the-module-ladder.md, "M4a — read-only
514
+ // panel — SIGNED"): `fwdloop panel [--port 4800] [--root <dir>]`. Read-only,
515
+ // GET/HEAD only, bound to 127.0.0.1 only (src/panel/server.js). Never picks
516
+ // a different port on collision — a taken port is a loud, non-zero-exit
517
+ // failure.
518
+ // ---------------------------------------------------------------------------
519
+
520
+ async function cmdPanel(rest) {
521
+ const { values } = parseArgs({
522
+ args: rest,
523
+ options: {
524
+ port: { type: 'string' },
525
+ root: { type: 'string' },
526
+ },
527
+ });
528
+ const root = resolveRoot('panel', values.root ?? '.');
529
+
530
+ const argv = ['--root', root];
531
+ if (values.port) argv.push('--port', values.port);
532
+
533
+ const code = await panelMain(argv, {
534
+ out: (s) => process.stdout.write(`${s}\n`),
535
+ err: (s) => process.stderr.write(`fwdloop: ${s}\n`),
536
+ });
537
+ process.exitCode = code;
538
+ }
539
+
540
+ // ---------------------------------------------------------------------------
541
+
542
+ async function main() {
543
+ const [verb, ...rest] = process.argv.slice(2);
544
+ if (!verb) fail('usage: fwdloop run|inbox|show|answer|resume|panel ...');
545
+
546
+ if (verb === 'run') return cmdRun(rest);
547
+ if (verb === 'inbox') return cmdInbox(rest);
548
+ if (verb === 'show') return cmdShow(rest);
549
+ if (verb === 'answer') return cmdAnswer(rest);
550
+ if (verb === 'resume') return cmdResume(rest);
551
+ if (verb === 'panel') return cmdPanel(rest);
552
+ fail(`unknown verb "${verb}" — expected run | inbox | show | answer | resume | panel`);
553
+ return undefined;
554
+ }
555
+
556
+ main().catch((err) => {
557
+ process.stderr.write(`fwdloop: ${err.message}\n`);
558
+ process.exit(1);
559
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -11,6 +11,9 @@
11
11
  "default": "./src/index.js"
12
12
  }
13
13
  },
14
+ "bin": {
15
+ "fwdloop": "./bin/fwdloop"
16
+ },
14
17
  "license": "Apache-2.0",
15
18
  "author": "hamr0",
16
19
  "repository": {
@@ -40,13 +43,14 @@
40
43
  },
41
44
  "files": [
42
45
  "src",
46
+ "bin",
43
47
  "types",
44
48
  "LICENSE",
45
49
  "NOTICE"
46
50
  ],
47
51
  "dependencies": {
48
- "bare-agent": "^0.42.0",
49
- "bareguard": "^0.15.0",
52
+ "bare-agent": "^0.48.0",
53
+ "bareguard": "^0.19.2",
50
54
  "litectx": "^0.32.0"
51
55
  },
52
56
  "devDependencies": {