fwdloop 0.4.1 → 0.6.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,480 @@
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 {
19
+ existsSync, mkdirSync, readFileSync, readdirSync,
20
+ } from 'node:fs';
21
+ import { extname, join, resolve } from 'node:path';
22
+ import { pathToFileURL } from 'node:url';
23
+ import { randomUUID } from 'node:crypto';
24
+
25
+ import { readFlow, checkFlowName } from '../src/flow.js';
26
+ import { loadCatalogue } from '../src/catalogue.js';
27
+ import { runFlow, resumeRun, makeParkingAskStep } from '../src/runner.js';
28
+ import { makeLiveModelStep } from '../src/model-step.js';
29
+ import { sendViaPrimitive } from '../src/send.js';
30
+ import { resolvePrimitives } from '../src/primitives.js';
31
+ import { checkKeyPreflight } from '../src/provider.js';
32
+ import { answerAsk } from '../src/ask.js';
33
+
34
+ // The baseline model (project rule, CLAUDE.md/AGENT_RULES: "deepseek-flash
35
+ // ... Never Claude for fwdloop's own runs") — the ONE provider slot this CLI
36
+ // drives. `PROVIDER_SLOTS.deepseek.envVar` is `DEEPSEEK_API_KEY`; this CLI
37
+ // never reads a key any other way and never prints it.
38
+ const MODEL_SLOT = 'deepseek';
39
+
40
+ function fail(message) {
41
+ process.stderr.write(`fwdloop: ${message}\n`);
42
+ process.exit(1);
43
+ }
44
+
45
+ function today() {
46
+ return new Date().toISOString().slice(0, 10);
47
+ }
48
+
49
+ /**
50
+ * Build the run's `modelStep`. Live by default (`makeLiveModelStep` against
51
+ * `MODEL_SLOT`, refusing an unset/empty/whitespace key via
52
+ * `checkKeyPreflight` BEFORE this function returns — i.e. before the caller
53
+ * has created a run dir or written any book row).
54
+ *
55
+ * Test-only escape hatch, never a user-facing flag: active ONLY when BOTH
56
+ * `NODE_ENV==='test'` AND `FWDLOOP_TEST_MODEL_STEP` (a module path) are set.
57
+ * A live invocation of this CLI is never launched with `NODE_ENV=test`, so
58
+ * there is no way to reach a fake model in production; and setting
59
+ * `FWDLOOP_TEST_MODEL_STEP` alone (without `NODE_ENV=test`) does nothing —
60
+ * two independent gates, neither of them a documented option, so it cannot
61
+ * be hit by a user typing `--something`. This is how the test suite drives
62
+ * every CLI scenario at $0 with zero chance of a real network call.
63
+ */
64
+ async function resolveModelStep(spendPath) {
65
+ if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
66
+ const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
67
+ const mod = await import(pathToFileURL(modulePath).href);
68
+ if (typeof mod.default !== 'function') {
69
+ throw new Error(`FWDLOOP_TEST_MODEL_STEP module "${modulePath}" has no default export function`);
70
+ }
71
+ return mod.default({ spendPath });
72
+ }
73
+ const keyCheck = checkKeyPreflight(MODEL_SLOT);
74
+ if (!keyCheck.ok) throw new Error(keyCheck.message);
75
+ return makeLiveModelStep({ slot: MODEL_SLOT, spendPath });
76
+ }
77
+
78
+ function parseSourceFlags(list) {
79
+ const out = {};
80
+ for (const entry of list ?? []) {
81
+ const eq = entry.indexOf('=');
82
+ if (eq <= 0) throw new Error(`--source "${entry}" is not "role=path"`);
83
+ const role = entry.slice(0, eq);
84
+ const value = entry.slice(eq + 1);
85
+ if (value.length === 0) throw new Error(`--source "${entry}" has an empty path`);
86
+ out[role] = resolve(value);
87
+ }
88
+ return out;
89
+ }
90
+
91
+ function listDirNames(dir) {
92
+ if (!existsSync(dir)) return [];
93
+ return readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
94
+ }
95
+
96
+ function findRunDirByAskId(root, askId) {
97
+ for (const flow of listDirNames(root)) {
98
+ const runsDir = join(root, flow, 'runs');
99
+ for (const runId of listDirNames(runsDir)) {
100
+ const askPath = join(runsDir, runId, 'ask.json');
101
+ if (!existsSync(askPath)) continue;
102
+ let ask;
103
+ try {
104
+ ask = JSON.parse(readFileSync(askPath, 'utf8'));
105
+ } catch {
106
+ // eslint-disable-next-line no-continue
107
+ continue;
108
+ }
109
+ if (ask.askId === askId) return join(runsDir, runId);
110
+ }
111
+ }
112
+ return null;
113
+ }
114
+
115
+ /** Reports a `runFlow`/`resumeRun` result to stdout/stderr and sets the
116
+ * process exit code. A `rerun` outcome also reports the new run it just
117
+ * started (recursively — the new run may itself be paused/complete/a red),
118
+ * so a human watching a `run`/`resume` invocation sees the WHOLE chain,
119
+ * never just the old run's own half of it. */
120
+ function reportRunResult(result, { rootArg }) {
121
+ if (result.outcome === 'paused') {
122
+ process.stdout.write(`parked: askId=${result.askId} expiresAt=${result.expiresAt} spentUsd=${result.spentUsd}\n`);
123
+ process.stdout.write(`fwdloop answer ${result.askId} accept|reject "<reason>"|rerun "<reason>" --root ${rootArg}\n`);
124
+ return;
125
+ }
126
+ if (result.outcome === 'complete') {
127
+ process.stdout.write(`complete: spentUsd=${result.spentUsd}\n`);
128
+ return;
129
+ }
130
+ if (result.outcome === 'rerun') {
131
+ process.stdout.write(`rerun: oldRunId=${result.runId} newRunId=${result.newRunId} spentUsd=${result.spentUsd}\n`);
132
+ reportRunResult(result.newRun, { rootArg });
133
+ return;
134
+ }
135
+ if (result.outcome === 'ask-expired') {
136
+ process.stderr.write(`fwdloop: ask-expired — run cancelled, spentUsd=${result.spentUsd}\n`);
137
+ process.exitCode = 1;
138
+ return;
139
+ }
140
+ process.stderr.write(`fwdloop: ${result.outcome}${result.red ? ` — ${result.red}` : ''}\n`);
141
+ process.exitCode = 1;
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // run
146
+ // ---------------------------------------------------------------------------
147
+
148
+ async function cmdRun(rest) {
149
+ const { values, positionals } = parseArgs({
150
+ args: rest,
151
+ options: {
152
+ root: { type: 'string' },
153
+ source: { type: 'string', multiple: true, default: [] },
154
+ 'run-id': { type: 'string' },
155
+ },
156
+ allowPositionals: true,
157
+ });
158
+
159
+ const flowName = positionals[0];
160
+ if (!flowName) fail('run: a flow name is required — fwdloop run <flow> --root <dir> --source <role>=<path> ...');
161
+ if (!values.root) fail('run: --root <dir> is required');
162
+
163
+ const root = resolve(values.root);
164
+ const nameCheck = checkFlowName(flowName);
165
+ if (!nameCheck.ok) fail(nameCheck.red);
166
+
167
+ const loaded = loadCatalogue();
168
+ if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
169
+ const catalogue = loaded.primitives;
170
+
171
+ const read = readFlow({ root, name: flowName, catalogue });
172
+ if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
173
+ const { arbiter, declaration } = read;
174
+
175
+ let parsedSources;
176
+ try {
177
+ parsedSources = parseSourceFlags(values.source);
178
+ } catch (err) {
179
+ fail(`run: ${err.message}`);
180
+ return;
181
+ }
182
+ const declaredRoles = (arbiter.sources ?? []).map((s) => s.role);
183
+ for (const role of declaredRoles) {
184
+ if (!Object.hasOwn(parsedSources, role)) {
185
+ fail(`run: flow "${flowName}" declares source role "${role}" — pass --source ${role}=<path>`);
186
+ }
187
+ }
188
+ for (const role of Object.keys(parsedSources)) {
189
+ if (!declaredRoles.includes(role)) {
190
+ fail(`run: --source role "${role}" is not declared by flow "${flowName}" (known roles: ${declaredRoles.join(', ') || '(none)'})`);
191
+ }
192
+ }
193
+ const sources = declaredRoles.map((role) => ({ id: role, path: parsedSources[role] }));
194
+ for (const src of sources) {
195
+ if (!existsSync(src.path)) fail(`run: source "${src.id}" is unreadable at ${src.path}`);
196
+ }
197
+
198
+ const runId = values['run-id'] ?? `run-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
199
+ const runDir = join(root, flowName, 'runs', runId);
200
+ if (existsSync(runDir)) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
201
+
202
+ // The key preflight (item A: "refuses at $0 BEFORE any book write") runs
203
+ // here — before ANY directory for this run is created.
204
+ const spendPath = join(runDir, 'spend.jsonl');
205
+ let modelStep;
206
+ try {
207
+ modelStep = await resolveModelStep(spendPath);
208
+ } catch (err) {
209
+ fail(err.message);
210
+ return;
211
+ }
212
+
213
+ // Predict the frozen input paths `runFlow`'s own `freezeInputs` will use
214
+ // (deterministic: `<runDir>/inputs/<id><ext>`) so the primitives map can
215
+ // be built once, before `runFlow` itself freezes anything.
216
+ mkdirSync(join(runDir, 'inputs'), { recursive: true });
217
+ const predictedInputs = sources.map((s) => ({ id: s.id, frozen: join(runDir, 'inputs', `${s.id}${extname(s.path)}`) }));
218
+ const allVerbs = [...new Set(declaration.steps.flatMap((s) => s.primitives ?? []))];
219
+ const { tools: primitives, reds: primitiveReds } = resolvePrimitives(catalogue, allVerbs, { runDir, inputs: predictedInputs });
220
+ for (const red of primitiveReds) process.stderr.write(`run: ${red}\n`);
221
+
222
+ const result = await runFlow({
223
+ root,
224
+ name: flowName,
225
+ runId,
226
+ sources,
227
+ catalogue,
228
+ modelStep,
229
+ askStep: makeParkingAskStep(),
230
+ sendStep: sendViaPrimitive,
231
+ primitives,
232
+ businessDate: today(),
233
+ });
234
+
235
+ reportRunResult(result, { rootArg: values.root });
236
+ }
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // inbox
240
+ // ---------------------------------------------------------------------------
241
+
242
+ function cmdInbox(rest) {
243
+ const { values } = parseArgs({
244
+ args: rest,
245
+ options: { root: { type: 'string' } },
246
+ });
247
+ const root = resolve(values.root ?? '.');
248
+ if (!existsSync(root)) fail(`inbox: root "${root}" does not exist`);
249
+
250
+ const rows = [];
251
+ for (const flow of listDirNames(root)) {
252
+ const runsDir = join(root, flow, 'runs');
253
+ for (const runId of listDirNames(runsDir)) {
254
+ const runDir = join(runsDir, runId);
255
+ const askPath = join(runDir, 'ask.json');
256
+ if (!existsSync(askPath)) continue;
257
+ let ask;
258
+ try {
259
+ ask = JSON.parse(readFileSync(askPath, 'utf8'));
260
+ } catch (err) {
261
+ // A malformed/unparseable ask.json must never crash inbox — show it
262
+ // naming the run as unreadable and move on to the next one.
263
+ rows.push({ flow, runId, status: 'unreadable', detail: `ask.json could not be parsed — ${err.message}` });
264
+ // eslint-disable-next-line no-continue
265
+ continue;
266
+ }
267
+ // An M2-era ask.json carries no `askId`/`expiresAt` (this CLI's
268
+ // answer/resume verbs can't act on it — they key everything off
269
+ // `askId`). Shown as "legacy (not answerable)", never "open": an ask
270
+ // this CLI cannot answer must never be reported as one it can.
271
+ if (typeof ask.askId !== 'string' || typeof ask.expiresAt !== 'string') {
272
+ rows.push({ flow, runId, status: 'legacy', question: ask.question });
273
+ // eslint-disable-next-line no-continue
274
+ continue;
275
+ }
276
+ // Signed item 6: expiry is checked whenever anyone touches the run —
277
+ // for `inbox` that means SHOWING an expired ask, never cancelling it
278
+ // (cancelling happens only at answer/resume, which re-verify anyway).
279
+ const consumedPath = join(runDir, `answer.${ask.askId}.consumed.json`);
280
+ if (existsSync(consumedPath)) continue; // this specific ask is already answered
281
+ // A present-but-unparseable expiresAt (Date.parse -> NaN) must never
282
+ // read as "not expired" — `Date.now() > NaN` is false, so the naive
283
+ // compare below would show this as [open] with a "NaNs left"
284
+ // countdown. Shown as [unreadable] naming the run instead, same as a
285
+ // malformed ask.json — never [open], never a NaN countdown.
286
+ if (Number.isNaN(Date.parse(ask.expiresAt))) {
287
+ rows.push({
288
+ flow, runId, status: 'unreadable', detail: `ask.json expiresAt "${ask.expiresAt}" is not a parseable date`,
289
+ });
290
+ // eslint-disable-next-line no-continue
291
+ continue;
292
+ }
293
+ const expired = Date.now() > Date.parse(ask.expiresAt);
294
+ const timeLeftMs = Date.parse(ask.expiresAt) - Date.now();
295
+ rows.push({
296
+ askId: ask.askId, flow, runId, question: ask.question, status: expired ? 'expired' : 'open', timeLeftMs,
297
+ });
298
+ }
299
+ }
300
+
301
+ if (rows.length === 0) {
302
+ process.stdout.write('inbox: no open asks\n');
303
+ return;
304
+ }
305
+ for (const row of rows) {
306
+ if (row.status === 'unreadable') {
307
+ process.stdout.write(`flow=${row.flow} run=${row.runId} [unreadable] ${row.detail}\n`);
308
+ continue;
309
+ }
310
+ if (row.status === 'legacy') {
311
+ process.stdout.write(`flow=${row.flow} run=${row.runId} [legacy (not answerable)] — ${row.question}\n`);
312
+ continue;
313
+ }
314
+ const timeLeft = row.status === 'expired' ? 'expired' : `${Math.max(0, Math.round(row.timeLeftMs / 1000))}s left`;
315
+ process.stdout.write(`${row.askId} flow=${row.flow} run=${row.runId} [${row.status}] ${timeLeft} — ${row.question}\n`);
316
+ }
317
+ }
318
+
319
+ // ---------------------------------------------------------------------------
320
+ // show — read-only: prints a parked ask's question, expiry, and evidence
321
+ // (the artifact under review, then each unjudged artifact labelled by
322
+ // step). F45 finding 2's other half: `inbox` says an ask is open, `show`
323
+ // is how a human actually sees what they'd be accepting. Never writes.
324
+ // ---------------------------------------------------------------------------
325
+
326
+ function artifactText(artifact) {
327
+ if (artifact && typeof artifact === 'object' && typeof artifact.text === 'string') return artifact.text;
328
+ return JSON.stringify(artifact, null, 2);
329
+ }
330
+
331
+ function cmdShow(rest) {
332
+ const { values, positionals } = parseArgs({
333
+ args: rest,
334
+ options: { root: { type: 'string' } },
335
+ allowPositionals: true,
336
+ });
337
+ const [askId] = positionals;
338
+ if (!askId) fail('show: an askId is required — fwdloop show <askId> --root <dir>');
339
+
340
+ const root = resolve(values.root ?? '.');
341
+ if (!existsSync(root)) fail(`show: root "${root}" does not exist`);
342
+ const runDir = findRunDirByAskId(root, askId);
343
+ if (!runDir) fail(`show: no open ask found for askId "${askId}" under ${root}`);
344
+
345
+ let ask;
346
+ try {
347
+ ask = JSON.parse(readFileSync(join(runDir, 'ask.json'), 'utf8'));
348
+ } catch (err) {
349
+ fail(`show: ask.json for askId "${askId}" is not valid JSON — ${err.message}`);
350
+ return;
351
+ }
352
+
353
+ process.stdout.write(`question: ${ask.question}\n`);
354
+ process.stdout.write(`expiresAt: ${ask.expiresAt}\n`);
355
+
356
+ const evidence = ask.evidence ?? null;
357
+ if (!evidence) {
358
+ process.stdout.write('\n(no evidence recorded on this ask — legacy park, before F45 finding 2 was fixed)\n');
359
+ return;
360
+ }
361
+ process.stdout.write('\n--- artifact under review ---\n');
362
+ process.stdout.write(`${artifactText(evidence.artifact)}\n`);
363
+ for (const item of evidence.unjudged ?? []) {
364
+ process.stdout.write(`\n--- unjudged: ${item.step ?? item.emits ?? '(step)'} ---\n`);
365
+ process.stdout.write(`${artifactText(item.artifact)}\n`);
366
+ }
367
+ }
368
+
369
+ // ---------------------------------------------------------------------------
370
+ // answer
371
+ // ---------------------------------------------------------------------------
372
+
373
+ function cmdAnswer(rest) {
374
+ const { values, positionals } = parseArgs({
375
+ args: rest,
376
+ options: { root: { type: 'string' } },
377
+ allowPositionals: true,
378
+ });
379
+ const [askId, decision, reason] = positionals;
380
+ if (!askId) fail('answer: an askId is required — fwdloop answer <askId> accept|reject "<reason>"|rerun "<reason>"');
381
+ if (!decision) fail(`answer: a decision (accept|reject|rerun) is required for askId "${askId}"`);
382
+
383
+ const root = resolve(values.root ?? '.');
384
+ if (!existsSync(root)) fail(`answer: root "${root}" does not exist`);
385
+ const runDir = findRunDirByAskId(root, askId);
386
+ if (!runDir) fail(`answer: no open ask found for askId "${askId}" under ${root}`);
387
+
388
+ const result = answerAsk({
389
+ runDir, askId, decision, reason,
390
+ });
391
+ if (!result.ok) fail(result.red);
392
+
393
+ process.stdout.write(`answered: askId=${askId} decision=${decision}\n`);
394
+ }
395
+
396
+ // ---------------------------------------------------------------------------
397
+ // resume
398
+ // ---------------------------------------------------------------------------
399
+
400
+ async function cmdResume(rest) {
401
+ const { values, positionals } = parseArgs({
402
+ args: rest,
403
+ options: {
404
+ flow: { type: 'string' },
405
+ root: { type: 'string' },
406
+ },
407
+ allowPositionals: true,
408
+ });
409
+ const runId = positionals[0];
410
+ if (!runId) fail('resume: a runId is required — fwdloop resume <runId> --flow <name> --root <dir>');
411
+ if (!values.flow) fail('resume: --flow <name> is required');
412
+ if (!values.root) fail('resume: --root <dir> is required');
413
+
414
+ const root = resolve(values.root);
415
+ const flowName = values.flow;
416
+
417
+ const loaded = loadCatalogue();
418
+ if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
419
+ const catalogue = loaded.primitives;
420
+
421
+ const read = readFlow({ root, name: flowName, catalogue });
422
+ if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
423
+ const { declaration } = read;
424
+
425
+ const runDir = join(root, flowName, 'runs', runId);
426
+ if (!existsSync(runDir)) fail(`resume: no run dir for runId "${runId}" under flow "${flowName}"`);
427
+
428
+ const spendPath = join(runDir, 'spend.jsonl');
429
+ let modelStep;
430
+ try {
431
+ modelStep = await resolveModelStep(spendPath);
432
+ } catch (err) {
433
+ fail(err.message);
434
+ return;
435
+ }
436
+
437
+ // Resume never re-freezes inputs — the run's own `inputs.json` (written at
438
+ // park by `freezeInputs`) is the one source of the already-frozen paths a
439
+ // sandboxed primitive may read.
440
+ const inputsManifestPath = join(runDir, 'inputs.json');
441
+ const inputsManifest = existsSync(inputsManifestPath) ? JSON.parse(readFileSync(inputsManifestPath, 'utf8')) : [];
442
+ const allVerbs = [...new Set(declaration.steps.flatMap((s) => s.primitives ?? []))];
443
+ const { tools: primitives, reds: primitiveReds } = resolvePrimitives(catalogue, allVerbs, {
444
+ runDir, inputs: inputsManifest.map((m) => ({ id: m.id, frozen: m.frozen })),
445
+ });
446
+ for (const red of primitiveReds) process.stderr.write(`resume: ${red}\n`);
447
+
448
+ const result = await resumeRun({
449
+ root,
450
+ name: flowName,
451
+ runId,
452
+ catalogue,
453
+ modelStep,
454
+ sendStep: sendViaPrimitive,
455
+ primitives,
456
+ businessDate: today(),
457
+ });
458
+
459
+ reportRunResult(result, { rootArg: values.root });
460
+ }
461
+
462
+ // ---------------------------------------------------------------------------
463
+
464
+ async function main() {
465
+ const [verb, ...rest] = process.argv.slice(2);
466
+ if (!verb) fail('usage: fwdloop run|inbox|show|answer|resume ...');
467
+
468
+ if (verb === 'run') return cmdRun(rest);
469
+ if (verb === 'inbox') return cmdInbox(rest);
470
+ if (verb === 'show') return cmdShow(rest);
471
+ if (verb === 'answer') return cmdAnswer(rest);
472
+ if (verb === 'resume') return cmdResume(rest);
473
+ fail(`unknown verb "${verb}" — expected run | inbox | show | answer | resume`);
474
+ return undefined;
475
+ }
476
+
477
+ main().catch((err) => {
478
+ process.stderr.write(`fwdloop: ${err.message}\n`);
479
+ process.exit(1);
480
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.4.1",
3
+ "version": "0.6.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,6 +43,7 @@
40
43
  },
41
44
  "files": [
42
45
  "src",
46
+ "bin",
43
47
  "types",
44
48
  "LICENSE",
45
49
  "NOTICE"