fwdloop 0.8.1 → 0.9.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 CHANGED
@@ -31,7 +31,7 @@ import { makeLiveModelStep } from '../src/model-step.js';
31
31
  import { sendViaPrimitive } from '../src/send.js';
32
32
  import { resolvePrimitives } from '../src/primitives.js';
33
33
  import { checkKeyPreflight } from '../src/provider.js';
34
- import { answerAsk, readAskEvidence } from '../src/ask.js';
34
+ import { answerAsk, readAskEvidence, normalizeDecision } from '../src/ask.js';
35
35
  import { panelMain } from '../src/panel/server.js';
36
36
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
37
37
  import { draftToDir, signDraft, SIGN_LINE, costText } from '../src/authoring.js';
@@ -139,7 +139,7 @@ function findRunDirByAskId(root, askId) {
139
139
  function reportRunResult(result, { rootArg }) {
140
140
  if (result.outcome === 'paused') {
141
141
  process.stdout.write(`parked: askId=${result.askId} expiresAt=${result.expiresAt} spentUsd=${result.spentUsd}\n`);
142
- process.stdout.write(`fwdloop answer ${result.askId} accept|reject "<reason>"|rerun "<reason>" --root ${rootArg}\n`);
142
+ process.stdout.write(`fwdloop answer ${result.askId} accept|redo "<reason>"|rerun "<reason>" --root ${rootArg}\n`);
143
143
  return;
144
144
  }
145
145
  if (result.outcome === 'complete') {
@@ -414,8 +414,8 @@ function cmdAnswer(rest) {
414
414
  allowPositionals: true,
415
415
  });
416
416
  const [askId, decision, reason] = positionals;
417
- if (!askId) fail('answer: an askId is required — fwdloop answer <askId> accept|reject "<reason>"|rerun "<reason>"');
418
- if (!decision) fail(`answer: a decision (accept|reject|rerun) is required for askId "${askId}"`);
417
+ if (!askId) fail('answer: an askId is required — fwdloop answer <askId> accept|redo "<reason>"|rerun "<reason>"');
418
+ if (!decision) fail(`answer: a decision (accept|redo|rerun) is required for askId "${askId}"`);
419
419
 
420
420
  const root = resolveRoot('answer', values.root ?? '.');
421
421
  const runDir = findRunDirByAskId(root, askId);
@@ -426,7 +426,7 @@ function cmdAnswer(rest) {
426
426
  });
427
427
  if (!result.ok) fail(result.red);
428
428
 
429
- process.stdout.write(`answered: askId=${askId} decision=${decision}\n`);
429
+ process.stdout.write(`answered: askId=${askId} decision=${normalizeDecision(decision)}\n`);
430
430
  }
431
431
 
432
432
  // ---------------------------------------------------------------------------
@@ -513,9 +513,11 @@ async function cmdResume(rest) {
513
513
  }
514
514
 
515
515
  // ---------------------------------------------------------------------------
516
- // panel — M4a piece 2 (docs/wiki/the-module-ladder.md, "M4a — read-only
517
- // panel — SIGNED"): `fwdloop panel [--port 4800] [--root <dir>]`. Read-only,
518
- // GET/HEAD only, bound to 127.0.0.1 only (src/panel/server.js). Never picks
516
+ // panel — M4a piece 2 + M4b (docs/wiki/the-module-ladder.md, "M4a — read-only
517
+ // panel" and "M4b — inputs"): `fwdloop panel [--port 4800] [--root <dir>]`.
518
+ // Reads are GET/HEAD; the only writes are POST /api/answer and POST
519
+ // /api/resume (src/panel/server.js), each gated by Origin/Host + a per-process
520
+ // token. Bound to 127.0.0.1 only. Never picks
519
521
  // a different port on collision — a taken port is a loud, non-zero-exit
520
522
  // failure.
521
523
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.8.1",
3
+ "version": "0.9.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",
package/src/ask.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // M2 piece 2 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
2
  // SIGNED", scope item 6): the file-checkpoint ask, in-process. Writes
3
3
  // `ask.json` (question + evidence + askedAt + attempt) into the run dir and
4
- // polls for `answer.json` (`{ decision: accept|reject|rerun, reason?,
4
+ // polls for `answer.json` (`{ decision: accept|redo|rerun, reason?,
5
5
  // answeredAt }`). Consumed exactly once (renamed away on read); a stale
6
6
  // answer — `answeredAt` older than THIS ask's `askedAt` — is quarantined
7
7
  // (renamed to `answer.stale.<n>.json`, audited `stale-answer-ignored`) and
@@ -20,11 +20,30 @@ import {
20
20
  existsSync, mkdirSync, readFileSync, renameSync, writeFileSync,
21
21
  } from 'node:fs';
22
22
  import { join } from 'node:path';
23
- import { randomUUID } from 'node:crypto';
23
+ import { createHash, randomUUID } from 'node:crypto';
24
24
 
25
25
  import { appendAudit } from './books.js';
26
26
  import { readFileInside, resolveInside, readdirInside } from './flow.js';
27
27
 
28
+ /**
29
+ * M4b amendment 3 (SIGNED by hamr 2026-09-30): the ONE translation of a
30
+ * decision. The answer that was spelled `reject` is `redo`; `reject` is still
31
+ * understood (from the CLI, the library, or a file an older version wrote) and
32
+ * means `redo`. `accept`, `redo` and `rerun` pass. Anything else comes back
33
+ * unchanged, so each caller's existing "unrecognised decision" refusal still
34
+ * quotes what it was given. Every decision from outside, and every one read
35
+ * from disk, goes through here; nothing else may compare against the old word.
36
+ * @param {string} decision
37
+ * @returns {string}
38
+ */
39
+ export function normalizeDecision(decision) {
40
+ return decision === 'reject' ? 'redo' : decision;
41
+ }
42
+
43
+ /** The one decision -> status table, used by `listArchivedAsks` here and by the panel's legacy-ask rows.
44
+ * Look it up with `normalizeDecision(decision)`. */
45
+ export const DECISION_STATUS = { accept: 'accepted', redo: 'redo', rerun: 'reran' };
46
+
28
47
  function sleep(ms) {
29
48
  return new Promise((resolve) => { setTimeout(resolve, ms); });
30
49
  }
@@ -101,7 +120,7 @@ export function makeFileAskStep({
101
120
  // ask has been answered.
102
121
  } else {
103
122
  renameSync(answerPath, join(runDir, `answer.${safeStamp(askedAt)}.consumed.json`));
104
- return { decision: parsed.decision, reason: parsed.reason };
123
+ return { decision: normalizeDecision(parsed.decision), reason: parsed.reason, artifactSha256: parsed.artifactSha256 };
105
124
  }
106
125
  }
107
126
  }
@@ -199,18 +218,40 @@ export function readAskEvidence(ask) {
199
218
  // M3 piece 1 (docs/wiki/the-module-ladder.md, "M3 — scope, exit, negative —
200
219
  // SIGNED", scope item 3, the function only — the CLI is piece 2): a separate
201
220
  // process's half of the park protocol. Writes `answer.json` exactly once,
202
- // refusing (never throwing) a blank reason on reject/rerun, an unknown
221
+ // refusing (never throwing) a blank reason on redo/rerun, an unknown
203
222
  // askId, an expired askId, or a second answer to an already-answered ask —
204
223
  // each by name, so an answer for ask A can never be consumed by ask B.
205
224
  // ---------------------------------------------------------------------------
206
225
 
207
226
  /**
208
- * @param {{ runDir: string, askId: string, decision: 'accept'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
227
+ * M4b piece 3: the ONE serialisation of an artifact's bytes — what
228
+ * `writeArtifact` (`src/runner.js`) puts on disk and what `sendViaPrimitive`
229
+ * (`src/send.js`) ships. The accept hash and the send-time re-hash are both
230
+ * over exactly this string, so they can only differ if the content does.
231
+ * @param {unknown} artifact
232
+ * @returns {string}
233
+ */
234
+ export function serializeArtifact(artifact) {
235
+ return JSON.stringify(artifact, null, 2);
236
+ }
237
+
238
+ /**
239
+ * sha256 (hex) of the bytes `serializeArtifact` yields.
240
+ * @param {string} serialised
241
+ * @returns {string}
242
+ */
243
+ export function sha256Hex(serialised) {
244
+ return createHash('sha256').update(Buffer.from(serialised, 'utf8')).digest('hex');
245
+ }
246
+
247
+ /**
248
+ * @param {{ runDir: string, askId: string, decision: 'accept'|'redo'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
209
249
  * @returns {{ ok: true } | { ok: false, red: string }}
210
250
  */
211
251
  export function answerAsk({
212
- runDir, askId, decision, reason, clock,
252
+ runDir, askId, decision: givenDecision, reason, clock,
213
253
  }) {
254
+ const decision = normalizeDecision(givenDecision);
214
255
  const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
215
256
 
216
257
  if (typeof runDir !== 'string' || runDir.length === 0) {
@@ -219,8 +260,8 @@ export function answerAsk({
219
260
  if (typeof askId !== 'string' || askId.length === 0) {
220
261
  return { ok: false, red: 'answerAsk: "askId" must be a non-empty string' };
221
262
  }
222
- if (decision !== 'accept' && decision !== 'reject' && decision !== 'rerun') {
223
- return { ok: false, red: `answerAsk: unrecognised decision "${decision}"` };
263
+ if (decision !== 'accept' && decision !== 'redo' && decision !== 'rerun') {
264
+ return { ok: false, red: `answerAsk: unrecognised decision "${givenDecision}"` };
224
265
  }
225
266
 
226
267
  // F48 round 3: routed through `readFileInside` — a symlinked `ask.json`
@@ -264,12 +305,25 @@ export function answerAsk({
264
305
  }
265
306
 
266
307
  const trimmedReason = typeof reason === 'string' ? reason.trim() : '';
267
- if ((decision === 'reject' || decision === 'rerun') && trimmedReason.length === 0) {
308
+ if ((decision === 'redo' || decision === 'rerun') && trimmedReason.length === 0) {
268
309
  return { ok: false, red: `answerAsk: askId "${askId}" needs a non-blank reason to ${decision}` };
269
310
  }
270
311
 
271
312
  const payload = { askId, decision, answeredAt: nowIso };
272
313
  if (trimmedReason.length > 0) payload.reason = trimmedReason;
314
+ // M4b scope item 4 (F48 finding C): an accept records the sha256 of the
315
+ // artifact the human was shown — `ask.json`'s `evidence.artifact`, the one
316
+ // draft this ask is about — so `send` can prove the bytes it ships are the
317
+ // bytes that were accepted. An accept whose artifact cannot be read from
318
+ // the ask is refused by name and nothing is written. redo/rerun record
319
+ // none (nothing is shipped on them).
320
+ if (decision === 'accept') {
321
+ const artifact = ask.evidence && typeof ask.evidence === 'object' ? ask.evidence.artifact : undefined;
322
+ if (artifact === null || typeof artifact !== 'object' || Array.isArray(artifact)) {
323
+ return { ok: false, red: `answerAsk: askId "${askId}" cannot be accepted — ask.json carries no readable artifact (evidence.artifact) to hash for run ${runDir}` };
324
+ }
325
+ payload.artifactSha256 = sha256Hex(serializeArtifact(artifact));
326
+ }
273
327
  // Orchestrator review fix (5): a plain `existsSync` check followed by a
274
328
  // separate `writeFileSync` is a check-then-act race — two concurrent
275
329
  // answers can both pass the check before either writes, and the second
@@ -320,11 +374,17 @@ export function answerAsk({
320
374
  * what is actually on disk); it is never treated as "before M4a-1" (that
321
375
  * `why` is reserved for a run with NO `asks/` directory at all).
322
376
  *
323
- * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown }} opts
377
+ * M4b amendment 2 (SIGNED by hamr 2026-09-30, F52): the record also carries
378
+ * `emits`, the step output this ask is about, so a later process can join
379
+ * the ask to its consumed answer's recorded hash (`readAcceptedHashesByEmits`).
380
+ * Written once with the rest of the record; an existing archive is never
381
+ * rewritten to add it (the `wx` create refuses).
382
+ *
383
+ * @param {{ runDir: string, askId: string, question: string, askedAt: string, expiresAt: string, evidence: unknown, emits?: string }} opts
324
384
  * @returns {{ ok: true } | { ok: false, red: string }}
325
385
  */
326
386
  export function writeAskArchive({
327
- runDir, askId, question, askedAt, expiresAt, evidence,
387
+ runDir, askId, question, askedAt, expiresAt, evidence, emits,
328
388
  }) {
329
389
  if (typeof runDir !== 'string' || runDir.length === 0) {
330
390
  return { ok: false, red: 'writeAskArchive: "runDir" must be a non-empty string' };
@@ -338,6 +398,7 @@ export function writeAskArchive({
338
398
  const payload = {
339
399
  askId, question, askedAt, expiresAt, evidence,
340
400
  };
401
+ if (typeof emits === 'string' && emits.length > 0) payload.emits = emits;
341
402
  try {
342
403
  writeFileSync(archivePath, JSON.stringify(payload, null, 2), { flag: 'wx' });
343
404
  } catch (err) {
@@ -349,6 +410,44 @@ export function writeAskArchive({
349
410
  return { ok: true };
350
411
  }
351
412
 
413
+ /**
414
+ * M4b amendment 2: for each archived ask that carries `emits`, joins it BY
415
+ * askId to its consumed answer and returns the recorded `artifactSha256` of
416
+ * an ACCEPT. Only `decision: accept` with a string hash counts; never
417
+ * recomputed from any file. No `emits` (old run), no marker, bad JSON, a
418
+ * redo/rerun, or a symlinked/unreadable entry contributes nothing, so the
419
+ * emits stays unrecorded and send refuses by name. Two accepts for one
420
+ * `emits` should be impossible; if seen, the result is a red, never a guess.
421
+ *
422
+ * @param {string} runDir
423
+ * @returns {{ ok: true, byEmits: Map<string, string> } | { ok: false, red: string }}
424
+ */
425
+ export function readAcceptedHashesByEmits(runDir) {
426
+ const byEmits = new Map();
427
+ if (!resolveInside(runDir, 'asks').ok) return { ok: true, byEmits };
428
+ const accepted = new Map(); // emits -> [askId]
429
+ for (const entry of readdirInside(runDir, 'asks').sort()) {
430
+ if (!entry.endsWith('.json')) continue; // eslint-disable-line no-continue
431
+ const askId = entry.slice(0, -'.json'.length);
432
+ const archiveRead = readFileInside(runDir, join('asks', entry));
433
+ if (!archiveRead.ok) continue; // eslint-disable-line no-continue
434
+ let emits;
435
+ try { emits = JSON.parse(archiveRead.text)?.emits; } catch { continue; } // eslint-disable-line no-continue
436
+ if (typeof emits !== 'string' || emits.length === 0) continue; // eslint-disable-line no-continue
437
+ const markerRead = readFileInside(runDir, `answer.${askId}.consumed.json`);
438
+ if (!markerRead.ok) continue; // eslint-disable-line no-continue
439
+ let marker;
440
+ try { marker = JSON.parse(markerRead.text); } catch { continue; } // eslint-disable-line no-continue
441
+ if (marker?.decision !== 'accept' || typeof marker.artifactSha256 !== 'string' || marker.artifactSha256.length === 0) continue; // eslint-disable-line no-continue
442
+ if (accepted.has(emits)) {
443
+ return { ok: false, red: `resume: more than one accepted ask (${accepted.get(emits)}, ${askId}) for step output "${emits}" — refusing to guess which hash applies` };
444
+ }
445
+ accepted.set(emits, askId);
446
+ byEmits.set(emits, marker.artifactSha256);
447
+ }
448
+ return { ok: true, byEmits };
449
+ }
450
+
352
451
  // ---------------------------------------------------------------------------
353
452
  // M4a Amendment M4a-1 reader: pairs each archived ask (`asks/<askId>.json`)
354
453
  // with its consumed answer (`answer.<askId>.consumed.json`), by askId only —
@@ -420,9 +519,8 @@ export function listArchivedAsks(runDir) {
420
519
  let parsed;
421
520
  try {
422
521
  parsed = JSON.parse(consumedRead.text);
423
- const decisionToStatus = { accept: 'accepted', reject: 'rejected', rerun: 'reran' };
424
522
  answer = {
425
- status: decisionToStatus[parsed.decision] ?? `unrecognised: ${parsed.decision}`,
523
+ status: DECISION_STATUS[normalizeDecision(parsed.decision)] ?? `unrecognised: ${parsed.decision}`,
426
524
  answeredAt: parsed.answeredAt,
427
525
  };
428
526
  if (typeof parsed.reason === 'string') answer.reason = parsed.reason;