fwdloop 0.14.0 → 0.15.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.14.0",
3
+ "version": "0.15.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/authoring.js CHANGED
@@ -391,9 +391,12 @@ export async function draftToDir({
391
391
  * The human step, $0. Every refusal returns reds and writes NO flow.
392
392
  * `signedBy` must come from the human's own invocation (the CLI's --signed-by/username).
393
393
  * `sessionDir` (the panel's draft folder: card, notes, every change) widens the setup record; the CLI has none, so its record is the one plan folder.
394
+ * M6: `replaces: {flowHash}` (a draft opened from an existing signed job, carrying that job's signature hash) makes this sign REPLACE that job
395
+ * (`writeFlow` checks the hash is still the job's); without it a taken name is refused as ever.
396
+ * @param {{dir: any, approve?: any, signedBy: any, signedAt?: string, env?: Record<string, string|undefined>, sessionDir?: string, replaces?: {flowHash: string}}} a
394
397
  */
395
398
  export function signDraft({
396
- dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, sessionDir,
399
+ dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, sessionDir, replaces,
397
400
  }) {
398
401
  const refuse = (...reds) => ({ ok: false, reds });
399
402
  if (readFileInside(dir, LEAK_MARKER_FILE).ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
@@ -448,7 +451,7 @@ export function signDraft({
448
451
  if (reds.length) return { ok: false, reds };
449
452
 
450
453
  const written = writeFlow({
451
- root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives,
454
+ root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives, replaces,
452
455
  });
453
456
  if (!written.ok) return { ok: false, reds: written.reds };
454
457
  // M4e amendment 6 item 4: the draft's record goes into the flow folder once, outside the three signed files. The flow IS signed by now, so a
package/src/checked.js CHANGED
@@ -8,18 +8,21 @@
8
8
  // NOT CHECKED is the drafter's own reading (a list of short phrases it wrote in the same call). It is information only: shown with its label,
9
9
  // never signed, never in the readout, never in the spec hash. What this throws away: anything the drafter did not list; the list is not complete.
10
10
 
11
- /** The label that always sits with the "Not checked" list. */
12
- export const NOT_CHECKED_LABEL = "the drafter's own reading, not a guarantee";
11
+ /** The label that always sits with the "Not checked" list (am41 item 3: the ONE place these words live; the Job tab and the Chat card read it off their payloads). */
12
+ export const NOT_CHECKED_LABEL = "not checked (the AI's own reading)";
13
13
 
14
14
  const list = (xs) => xs.join(', ');
15
15
 
16
16
  /**
17
17
  * One entry per step, in plan order: the plain sentences for what its typed close checks.
18
- * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true)
18
+ * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[] }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
19
+ * askLines = the job lines of the signed asks, which also lets a step after the LAST ask read "you check it after you accept" (am41 item 2, am42: the ONE place for these words)
19
20
  * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[] }[]}
20
21
  */
21
- export function checkedLines(declaration, { hasAsk = true } = {}) {
22
+ export function checkedLines(declaration, { hasAsk = true, askLines } = {}) {
22
23
  const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
24
+ if (Array.isArray(askLines)) hasAsk = askLines.length > 0;
25
+ const lastAsk = Array.isArray(askLines) ? steps.reduce((m, st, i) => (askLines.includes(st?.fromLine) ? i : m), -1) : -1;
23
26
  return steps.map((st, i) => {
24
27
  const cls = st?.close?.class;
25
28
  const shape = st?.close?.shape && typeof st.close.shape === 'object' ? st.close.shape : {};
@@ -35,7 +38,8 @@ export function checkedLines(declaration, { hasAsk = true } = {}) {
35
38
  if (Number.isInteger(shape.linesPerInvoice)) out.push(`The output comes in blocks of ${shape.linesPerInvoice} lines.`);
36
39
  if (Array.isArray(shape.mustCarry) && shape.mustCarry.length > 0) out.push(`Every block carries: ${list(shape.mustCarry)}.`);
37
40
  } else {
38
- out.push(hasAsk ? 'No machine check of the content: you check it at the ask.' : 'No machine check of the content; the machine checks only that the step happened.');
41
+ if (lastAsk !== -1 && i > lastAsk) out.push('No machine check of the content; you check it after you accept.');
42
+ else out.push(hasAsk ? 'No machine check of the content: you check it at the ask.' : 'No machine check of the content; the machine checks only that the step happened.');
39
43
  }
40
44
  return {
41
45
  step: i + 1, line: Number.isInteger(st?.fromLine) ? st.fromLine : null, goal: typeof st?.goal === 'string' ? st.goal : '', class: String(cls), sentences: out,
@@ -490,6 +490,8 @@ export function validateDeclaration(declaration, context = {}) {
490
490
  let unjudgeable = {};
491
491
  if (!Object.prototype.hasOwnProperty.call(declaration, 'unjudgeable')) {
492
492
  reds.push('declaration: "unjudgeable" is required (an object keyed by line number; {} is fine)');
493
+ } else if (Array.isArray(declaration.unjudgeable) && declaration.unjudgeable.length === 0) {
494
+ // am41 item 1 (F63): an empty list carries no data; it counts as {}. A non-empty list falls to the red below.
493
495
  } else if (isPlainObject(declaration.unjudgeable)) {
494
496
  unjudgeable = declaration.unjudgeable;
495
497
  for (const [key, reason] of Object.entries(unjudgeable)) {
package/src/flow.js CHANGED
@@ -28,6 +28,7 @@ import path from 'node:path';
28
28
  import { parseSignedText } from './signed-text.js';
29
29
  import { signFlow, verifyFlow } from './signature.js';
30
30
  import { validateDeclaration } from './declaration.js';
31
+ import { describeChange } from './signed-diff.js';
31
32
 
32
33
  /** @typedef {import('./types.js').WriteFlowResult} WriteFlowResult */
33
34
  /** @typedef {import('./types.js').ReadFlowResult} ReadFlowResult */
@@ -40,6 +41,15 @@ export const FLOW_FILES = Object.freeze(['prose.txt', 'declaration.json', 'signa
40
41
  export const PANEL_STARTS_DIR = '.starts';
41
42
 
42
43
  const RUNS_DIR = 'runs';
44
+ /** Amendment 43: the write-once copy of the two signed files, made at sign by `writeFlow` (the ONE writer). Outside FLOW_FILES: it never enters the signature or `readFlow`'s success path. */
45
+ const SIGNED_COPY_DIR = 'signed';
46
+ const CHANGED_PREFIX = 'changed since signing: ';
47
+
48
+ /** The plain "what changed" sentences inside a readFlow refusal (am43), joined for a sentence a human reads; '' when there are none. @param {string[]} reds */
49
+ export function changeSentence(reds) {
50
+ const xs = reds.filter((r) => typeof r === 'string' && r.startsWith(CHANGED_PREFIX)).map((r) => r.slice(CHANGED_PREFIX.length));
51
+ return xs.length > 0 ? ` What changed: ${xs.join('; ')}.` : '';
52
+ }
43
53
 
44
54
  /**
45
55
  * Check a flow name against the allowed shape: 1..64 characters, lowercase
@@ -404,11 +414,14 @@ function readTextFile(filePath, label, reds) {
404
414
  * last (each via a temp file + rename in the same directory), creates an
405
415
  * empty `runs/`, and proves the result by reading it back with `readFlow`.
406
416
  *
407
- * @param {{root: unknown, name: unknown, proseText: unknown, declaration: unknown, signedBy: unknown, signedAt: unknown, catalogue: unknown}} input
417
+ * M6: with `replaces: {flowHash}` it instead REPLACES the signed job already under that name (see `replaceSigned`), and only if that job is
418
+ * still the one with that signature hash. `onReplaceStep` is a test seam: called after each move of the swap; a throw there is a failure.
419
+ *
420
+ * @param {{root: unknown, name: unknown, proseText: unknown, declaration: unknown, signedBy: unknown, signedAt: unknown, catalogue: unknown, replaces?: {flowHash: string}, onReplaceStep?: (step: string) => void}} input
408
421
  * @returns {WriteFlowResult}
409
422
  */
410
423
  export function writeFlow({
411
- root, name, proseText, declaration, signedBy, signedAt, catalogue,
424
+ root, name, proseText, declaration, signedBy, signedAt, catalogue, replaces, onReplaceStep,
412
425
  }) {
413
426
  const nameCheck = checkFlowName(name);
414
427
  if (!nameCheck.ok) return { ok: false, reds: [nameCheck.red] };
@@ -440,6 +453,12 @@ export function writeFlow({
440
453
 
441
454
  const dir = path.join(root, safeName);
442
455
 
456
+ if (replaces !== undefined) {
457
+ return replaceSigned({
458
+ root, name: safeName, dir, proseText: /** @type {string} */ (proseText), declarationText, signature: signResult.signature, replaces, catalogue, onReplaceStep,
459
+ });
460
+ }
461
+
443
462
  // Refuse if any of the three files already exists — M1 never overwrites a
444
463
  // signed flow (versions are M4).
445
464
  for (const fileName of FLOW_FILES) {
@@ -455,6 +474,10 @@ export function writeFlow({
455
474
  }
456
475
  }
457
476
 
477
+ if (existsSync(path.join(dir, SIGNED_COPY_DIR))) {
478
+ return { ok: false, reds: [`flow: "${SIGNED_COPY_DIR}" already exists at ${path.join(dir, SIGNED_COPY_DIR)}`] };
479
+ }
480
+
458
481
  // Track what THIS call creates so a failure partway through can be rolled
459
482
  // back — a directory must never be left with a signature but a missing
460
483
  // file.
@@ -466,7 +489,7 @@ export function writeFlow({
466
489
  if (createdDir) {
467
490
  rmSync(dir, { recursive: true, force: true });
468
491
  } else {
469
- for (const p of written) rmSync(p, { force: true });
492
+ for (const p of written) rmSync(p, { recursive: true, force: true });
470
493
  }
471
494
  } catch {
472
495
  // best-effort cleanup; the red already reports the real failure
@@ -495,6 +518,12 @@ export function writeFlow({
495
518
  try {
496
519
  writeOne('prose.txt', proseText);
497
520
  writeOne('declaration.json', declarationText);
521
+ // am43: the copy of what is being signed, write-once (`wx` refuses an existing file), before the signature that makes it a signed flow.
522
+ const copyDir = path.join(dir, SIGNED_COPY_DIR);
523
+ mkdirSync(copyDir);
524
+ written.push(copyDir);
525
+ writeFileSync(path.join(copyDir, 'prose.txt'), /** @type {string} */ (proseText), { encoding: 'utf8', flag: 'wx' });
526
+ writeFileSync(path.join(copyDir, 'declaration.json'), declarationText, { encoding: 'utf8', flag: 'wx' });
498
527
  writeOne('signature.json', `${JSON.stringify(signResult.signature, null, 2)}\n`);
499
528
 
500
529
  const runsDir = path.join(dir, RUNS_DIR);
@@ -517,6 +546,95 @@ export function writeFlow({
517
546
  };
518
547
  }
519
548
 
549
+ /**
550
+ * The signature hash (`signature.json` `flow`) of the signed job in `flowDir`, or null when there is no readable one. It does NOT verify the
551
+ * files (that is `readFlow`): it only says which signing this folder is at, for M6's "was this job signed again since you opened it".
552
+ * @param {string} flowDir @returns {string|null}
553
+ */
554
+ export function signedHashOf(flowDir) {
555
+ const f = readFileInside(flowDir, 'signature.json');
556
+ if (!f.ok) return null;
557
+ try { const h = JSON.parse(f.text)?.flow; return typeof h === 'string' && h !== '' ? h : null; } catch { return null; }
558
+ }
559
+
560
+ /** M6: the names `replaceSigned` swaps, signature last (the file that makes the folder a signed flow). `setup.jsonl` is only moved away: the caller writes the new one. */
561
+ const SWAP_NAMES = ['prose.txt', 'declaration.json', SIGNED_COPY_DIR, 'setup.jsonl', 'signature.json'];
562
+
563
+ /**
564
+ * M6 ("Signing replaces the job"): replace the signed job in `<root>/<name>/`, ALL OR NOTHING, keeping the name, `runs/` and the flow's books.
565
+ * Refuses (touching nothing) unless the folder holds a signed job whose `signature.json` `flow` hash is `replaces.flowHash` (a draft opened from an
566
+ * older version of the job, or a job signed again meanwhile, is refused by name). The new files are staged inside the folder first; the swap then moves
567
+ * each old file into a backup folder and its new one into place (signature last); ANY failure, or a proof read that does not verify, moves everything
568
+ * back. On success the backup is deleted — no old version is kept anywhere (hamr's ruling). Only a hard kill inside the swap leaves the backup
569
+ * (`.replace-old-*`) holding the old files; nothing recovers it automatically.
570
+ * @param {{root: string, name: string, dir: string, proseText: string, declarationText: string, signature: any, replaces: {flowHash: string}, catalogue: unknown, onReplaceStep?: (step: string) => void}} a
571
+ * @returns {WriteFlowResult}
572
+ */
573
+ function replaceSigned({
574
+ root, name, dir, proseText, declarationText, signature, replaces, catalogue, onReplaceStep,
575
+ }) {
576
+ const red = (/** @type {string} */ r) => ({ ok: /** @type {false} */ (false), reds: [r] });
577
+ let dirStat;
578
+ try { dirStat = lstatSync(dir); } catch { return red(`flow: nothing signed to replace — "${name}" has no folder here`); }
579
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return red(`flow: "${dir}" is not a plain folder, refused`);
580
+ const current = signedHashOf(dir);
581
+ if (current === null) return red(`flow: nothing signed to replace — "${name}" has no readable signature.json`);
582
+ if (typeof replaces?.flowHash !== 'string' || current !== replaces.flowHash) {
583
+ return red(`flow: "${name}" was signed again since you opened it for editing, so this edit is out of date. Nothing was changed. Open the job again and redo the edit.`);
584
+ }
585
+
586
+ const stamp = `${process.pid}-${Date.now()}`;
587
+ const stage = path.join(dir, `.replace-new-${stamp}`);
588
+ const backup = path.join(dir, `.replace-old-${stamp}`);
589
+ const moved = []; // names whose OLD file is now in backup
590
+ const placed = []; // names whose NEW file is now in dir
591
+ const cleanup = () => {
592
+ for (const p of [stage, backup]) { try { rmSync(p, { recursive: true, force: true }); } catch { /* best-effort */ } }
593
+ };
594
+ const putBack = () => {
595
+ for (const n of [...placed].reverse()) rmSync(path.join(dir, n), { recursive: true, force: true });
596
+ for (const n of [...moved].reverse()) renameSync(path.join(backup, n), path.join(dir, n));
597
+ };
598
+ const fail = (/** @type {string} */ why) => {
599
+ try { putBack(); } catch (err) {
600
+ // the old files could not all be put back: say where they are rather than pretend (the backup is NOT cleaned up)
601
+ return red(`flow: ${why}; the old job could not be fully put back (${err.message}) — its files are in ${backup}`);
602
+ }
603
+ cleanup();
604
+ return red(`flow: ${why}`);
605
+ };
606
+
607
+ try {
608
+ mkdirSync(stage);
609
+ mkdirSync(backup);
610
+ mkdirSync(path.join(stage, SIGNED_COPY_DIR));
611
+ writeFileSync(path.join(stage, 'prose.txt'), proseText, 'utf8');
612
+ writeFileSync(path.join(stage, 'declaration.json'), declarationText, 'utf8');
613
+ writeFileSync(path.join(stage, SIGNED_COPY_DIR, 'prose.txt'), proseText, { encoding: 'utf8', flag: 'wx' });
614
+ writeFileSync(path.join(stage, SIGNED_COPY_DIR, 'declaration.json'), declarationText, { encoding: 'utf8', flag: 'wx' });
615
+ writeFileSync(path.join(stage, 'signature.json'), `${JSON.stringify(signature, null, 2)}\n`, 'utf8');
616
+ } catch (err) {
617
+ cleanup();
618
+ return red(`flow: could not stage the new files — ${err.message}. Nothing was changed.`);
619
+ }
620
+
621
+ try {
622
+ for (const n of SWAP_NAMES) {
623
+ if (existsSync(path.join(dir, n))) { renameSync(path.join(dir, n), path.join(backup, n)); moved.push(n); }
624
+ if (existsSync(path.join(stage, n))) { renameSync(path.join(stage, n), path.join(dir, n)); placed.push(n); }
625
+ onReplaceStep?.(n);
626
+ }
627
+ } catch (err) {
628
+ return fail(`could not replace the job — ${err.message}`);
629
+ }
630
+
631
+ // the mechanical "it happened" check, as at sign: read the replaced job back through the one reader
632
+ const proof = readFlow({ root, name, catalogue });
633
+ if (!proof.ok) return fail(`the replaced job does not verify (${proof.reds.join('; ')})`);
634
+ cleanup();
635
+ return { ok: true, dir, signature };
636
+ }
637
+
520
638
  /**
521
639
  * Read and verify a signed flow from `<root>/<name>/`. Verifies the bytes on
522
640
  * disk against the signature FIRST — before anything in the flow is
@@ -602,8 +720,21 @@ export function readFlow({ root, name, catalogue }) {
602
720
  const verified = verifyFlow({
603
721
  proseText, declarationText, signature: signatureJson,
604
722
  });
605
- if (!verified.ok) return { ok: false, reds: verified.reds };
723
+ if (!verified.ok) return { ok: false, reds: [...verified.reds, ...explainEdit(dir, signatureJson, /** @type {string} */ (proseText), /** @type {string} */ (declarationText))] };
606
724
 
725
+ return interpretSigned({
726
+ proseText: /** @type {string} */ (proseText), declarationJson, signatureJson, catalogue, dir,
727
+ });
728
+ }
729
+
730
+ /**
731
+ * The part of a read that follows a passed signature check, shared by `readFlow` and `readRunJobCopy`: parse the signed text, validate the declaration.
732
+ * @param {{proseText: string, declarationJson: any, signatureJson: any, catalogue: unknown, dir: string}} a
733
+ * @returns {ReadFlowResult}
734
+ */
735
+ function interpretSigned({
736
+ proseText, declarationJson, signatureJson, catalogue, dir,
737
+ }) {
607
738
  const signed = parseSignedText(proseText);
608
739
  if (!signed.ok) return { ok: false, reds: signed.reds };
609
740
 
@@ -613,7 +744,7 @@ export function readFlow({ root, name, catalogue }) {
613
744
  if (!validated.ok) return { ok: false, reds: validated.reds };
614
745
 
615
746
  return {
616
- ok: true,
747
+ ok: /** @type {true} */ (true),
617
748
  dir,
618
749
  lines: signed.lines,
619
750
  arbiter: signed.arbiter,
@@ -622,3 +753,87 @@ export function readFlow({ root, name, catalogue }) {
622
753
  classes: validated.classes,
623
754
  };
624
755
  }
756
+
757
+ /** M6: the folder inside a run that holds the copy of the job it ran. */
758
+ const RUN_JOB_DIR = 'job';
759
+
760
+ /**
761
+ * M6 ("Each run saves a copy of the job it ran when it starts"): the ONE writer of `<runDir>/job/`. Reads the flow's three files, proves them against
762
+ * the flow's own signature first (a flow that does not verify is never copied), then writes them write-once (`wx`). `{ok:false, red}` writes nothing
763
+ * it did not finish (a half-written copy is removed). Never throws.
764
+ * @param {string} flowDir @param {string} runDir @param {string} [expectedFlowHash] the `signature.flow` the caller read; a different job on disk is refused
765
+ * @returns {{ok: true} | {ok: false, red: string}}
766
+ */
767
+ export function writeRunJobCopy(flowDir, runDir, expectedFlowHash) {
768
+ const texts = {};
769
+ for (const f of FLOW_FILES) {
770
+ const r = readFileInside(flowDir, f);
771
+ if (!r.ok) return { ok: false, red: `job copy: could not read ${f} (${r.missing ? 'missing' : r.red})` };
772
+ texts[f] = r.text;
773
+ }
774
+ let signature;
775
+ try { signature = JSON.parse(texts['signature.json']); } catch { return { ok: false, red: 'job copy: signature.json is not valid JSON' }; }
776
+ const verified = verifyFlow({ proseText: texts['prose.txt'], declarationText: texts['declaration.json'], signature });
777
+ if (!verified.ok) return { ok: false, red: `job copy: the flow does not match its signature (${verified.reds[0]})` };
778
+ // M6 F3: the copy must be the job the run verified at its start; a job replaced since is never copied (nothing is written)
779
+ if (typeof expectedFlowHash === 'string' && signature.flow !== expectedFlowHash) return { ok: false, red: 'the job was replaced while this run was starting' };
780
+ const dir = path.join(runDir, RUN_JOB_DIR);
781
+ try {
782
+ mkdirSync(dir);
783
+ for (const f of FLOW_FILES) writeFileSync(path.join(dir, f), texts[f], { encoding: 'utf8', flag: 'wx' });
784
+ } catch (err) {
785
+ try { if (err.code !== 'EEXIST') rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
786
+ return { ok: false, red: err.code === 'EEXIST' ? 'job copy: this run already has its copy — never overwritten' : `job copy: could not write (${err.code ?? err.message})` };
787
+ }
788
+ return { ok: true };
789
+ }
790
+
791
+ /**
792
+ * M6: the job a run ran, from its own copy. `{present:false}` = the run has none (it started before M6). `{present:true, ok:true, ...}` = the same
793
+ * shape as a good `readFlow` (lines, arbiter, declaration, signature, classes), after the copy was verified against the copied signature.
794
+ * `{present:true, ok:false, reds}` = a copy that was edited or is incomplete: refused, never shown as the job.
795
+ * @param {string} runDir @param {unknown} catalogue
796
+ * @returns {{present: false} | ({present: true} & ReadFlowResult)}
797
+ */
798
+ export function readRunJobCopy(runDir, catalogue) {
799
+ const dir = path.join(runDir, RUN_JOB_DIR);
800
+ if (!existsSync(dir)) return { present: false };
801
+ const reds = [];
802
+ const proseText = readTextFile(path.join(dir, 'prose.txt'), 'prose.txt', reds);
803
+ const declarationText = readTextFile(path.join(dir, 'declaration.json'), 'declaration.json', reds);
804
+ const signatureText = readTextFile(path.join(dir, 'signature.json'), 'signature.json', reds);
805
+ let declarationJson;
806
+ let signatureJson;
807
+ try { if (declarationText !== null) declarationJson = JSON.parse(declarationText); } catch { reds.push('flow: declaration.json is not valid JSON'); }
808
+ try { if (signatureText !== null) signatureJson = JSON.parse(signatureText); } catch { reds.push('flow: signature.json is not valid JSON'); }
809
+ if (reds.length > 0) return { present: true, ok: false, reds };
810
+ const verified = verifyFlow({ proseText, declarationText, signature: signatureJson });
811
+ if (!verified.ok) return { present: true, ok: false, reds: [...verified.reds] };
812
+ return {
813
+ present: /** @type {true} */ (true),
814
+ ...interpretSigned({
815
+ proseText: /** @type {string} */ (proseText), declarationJson, signatureJson, catalogue, dir,
816
+ }),
817
+ };
818
+ }
819
+
820
+ /**
821
+ * Amendment 43: after a failed verify, name what changed by comparing with the copy `writeFlow` kept at sign. The copy is trusted ONLY if it
822
+ * verifies against signature.json itself; otherwise it is never compared. Returns extra reds (plain sentences); never throws.
823
+ * @param {string} dir @param {any} signature @param {string} proseText @param {string} declarationText
824
+ * @returns {string[]}
825
+ */
826
+ function explainEdit(dir, signature, proseText, declarationText) {
827
+ const oldProse = readFileInside(dir, `${SIGNED_COPY_DIR}/prose.txt`);
828
+ const oldDecl = readFileInside(dir, `${SIGNED_COPY_DIR}/declaration.json`);
829
+ if (!oldProse.ok && oldProse.missing && !oldDecl.ok && oldDecl.missing) {
830
+ return [CHANGED_PREFIX + '(signed before amendment 43: no copy to compare)'];
831
+ }
832
+ if (!oldProse.ok || !oldDecl.ok) return [CHANGED_PREFIX + "the saved copy of the signed files is incomplete, so it can't be trusted to compare"];
833
+ if (!verifyFlow({ proseText: oldProse.text, declarationText: oldDecl.text, signature }).ok) {
834
+ return [CHANGED_PREFIX + "the saved copy of the signed files does not match the signature, so it can't be trusted to compare"];
835
+ }
836
+ const changes = describeChange({ oldProse: oldProse.text, newProse: proseText, oldDecl: oldDecl.text, newDecl: declarationText });
837
+ if (changes.length === 0) return [CHANGED_PREFIX + 'the files match the saved copy; signature.json itself was changed'];
838
+ return changes.map((c) => `${CHANGED_PREFIX}${c}`);
839
+ }
@@ -229,8 +229,8 @@ export function createAuthor(opts) {
229
229
  const decl = readJson(dir, `${rel}/declaration.json`);
230
230
  const prose = readFileInside(dir, `${rel}/prose.txt`);
231
231
  const parsed = prose.ok ? parseSignedText(prose.text) : null;
232
- const hasAsk = parsed?.ok === true ? parsed.arbiter.asks.length > 0 : true;
233
- return { checked: checkedLines(decl, { hasAsk }), notChecked: notCheckedBlock(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked) };
232
+ const opts = parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line) } : { hasAsk: true };
233
+ return { checked: checkedLines(decl, opts), notChecked: notCheckedBlock(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked) };
234
234
  }
235
235
 
236
236
  /** The answers an answer-redraft was drafted with, as the marker recorded them: `[{ line, lineText, question, answer }]` (scrubbed). @param {string} dir @param {number} n @param {string[]} keys */
@@ -428,8 +428,14 @@ export function createAuthor(opts) {
428
428
  if (!run.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: run.say } };
429
429
  }
430
430
  const signedBy = userInfo().username;
431
+ // M6: a card that edits a signed job signs as a REPLACEMENT of that job, only at the signature hash it was opened at (the writer re-checks it)
432
+ const editOf = v.card.editOf && typeof v.card.editOf === 'object' ? v.card.editOf : null;
433
+ if (editOf !== null && editOf.flow !== name) return { status: 409, body: { ok: false, refused: 'edit-name', say: 'This draft edits another job than the name it was drafted under. Nothing was signed.' } };
434
+ // M6 amendments 1 and 3: a replacing sign is refused while a run of the job is running, waiting at its ask or starting (a stale page cannot get round the greyed button)
435
+ const editBlock = editOf !== null ? flowsDoor.editBlock(name) : null;
436
+ if (editBlock !== null) return { status: 409, body: { ok: false, refused: 'run-live', say: editBlock } };
431
437
  const result = signDraft({
432
- dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, sessionDir: dir,
438
+ dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, sessionDir: dir, replaces: editOf !== null ? { flowHash: String(editOf.flowHash) } : undefined,
433
439
  });
434
440
  if (!result.ok) {
435
441
  const keys = providerKeys(loaded.env);
@@ -14,7 +14,7 @@ import {
14
14
  } from 'node:fs';
15
15
  import { isAbsolute, join } from 'node:path';
16
16
 
17
- import { checkFlowName } from '../flow.js';
17
+ import { checkFlowName, signedHashOf } from '../flow.js';
18
18
  import { checkSendDestination, resolveCeilingUsd } from '../runner.js';
19
19
  import { parseSignedText } from '../signed-text.js';
20
20
  import { PROVIDER_SLOTS } from '../provider.js';
@@ -170,6 +170,8 @@ export function cardFields(body) {
170
170
  inputs: str(b.inputs).replace(/\r\n?/g, '\n'),
171
171
  capUsd: typeof b.capUsd === 'string' && b.capUsd.trim() !== '' ? Number(b.capUsd) : b.capUsd,
172
172
  askWait: str(b.askWait).trim(),
173
+ // M6: present only when this card EDITS a signed job: which job, and the signature hash it was opened at
174
+ ...(typeof b.editOf?.flow === 'string' && typeof b.editOf?.flowHash === 'string' && b.editOf.flowHash !== '' ? { editOf: { flow: b.editOf.flow, flowHash: b.editOf.flowHash } } : {}),
173
175
  };
174
176
  }
175
177
 
@@ -193,6 +195,51 @@ export function cardToProse(card) {
193
195
  return `${out.join('\n')}\n`;
194
196
  }
195
197
 
198
+ /** An ask wait in ms as the card spells it (`30m`, `2h`), or null when it is not a whole number of minutes. @param {number} ms */
199
+ function waitText(ms) {
200
+ if (!Number.isInteger(ms) || ms <= 0 || ms % 60000 !== 0) return null;
201
+ return ms % 3600000 === 0 ? `${ms / 3600000}h` : `${ms / 60000}m`;
202
+ }
203
+
204
+ /**
205
+ * M6: a signed job turned back into the card's fields (the job box, inputs box, destination, cap, ask wait), from `parseSignedText`'s `lines` and
206
+ * `arbiter`. The ONE rule of fidelity is mechanical: the card is offered only if writing it again (`cardToProse` -> `parseSignedText`) gives back the
207
+ * SAME lines and the SAME arbiter (an old unsigned `ask:` wait is the one thing allowed to differ: it comes back signed at its 30m). A setting the
208
+ * card has no box for (a redo cap, a second send, a send off the last line, a wait in seconds) makes the answer `{ok:false, say}`; nothing is dropped.
209
+ * @param {{ lines: {n: number, text: string, guardrail: string}[], arbiter: any }} signed
210
+ * @returns {{ ok: true, card: { job: string, inputs: string, destination: string, capUsd: string, askWait: string } } | { ok: false, say: string }}
211
+ */
212
+ export function cardFromSigned({ lines, arbiter }) {
213
+ const no = () => ({ ok: /** @type {false} */ (false), say: 'This job has a setting the card has no box for, so it cannot be opened for editing here.' });
214
+ const asks = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
215
+ const jobLines = [];
216
+ let firstWait = null;
217
+ for (const l of lines) {
218
+ const ak = asks.get(l.n);
219
+ if (ak) {
220
+ const w = waitText(ak.ttlMs);
221
+ if (w === null) return no();
222
+ firstWait ??= w;
223
+ jobLines.push(`Ask ${w}: ${l.text}`);
224
+ } else jobLines.push(l.text);
225
+ if (typeof l.guardrail === 'string' && l.guardrail !== '') jobLines.push(`~ ${l.guardrail}`);
226
+ }
227
+ const sends = arbiter.sends ?? [];
228
+ if (sends.length > 1 || (sends.length === 1 && sends[0].target?.kind !== 'file')) return no();
229
+ const card = {
230
+ job: jobLines.join('\n'),
231
+ inputs: (arbiter.sources ?? []).map((x) => `${x.role}: ${x.path}`).join('\n'),
232
+ destination: sends.length === 1 ? sends[0].target.path : '',
233
+ capUsd: capText(Number(arbiter.capUsd)),
234
+ askWait: firstWait ?? '1h',
235
+ };
236
+ const again = parseSignedText(cardToProse(cardFields({ ...card, flowName: 'x' })));
237
+ const norm = (a) => JSON.stringify({ ...a, asks: (a.asks ?? []).map(({ ttlSigned, ...rest }) => rest) });
238
+ const sameLines = again.ok && JSON.stringify(again.lines) === JSON.stringify(lines);
239
+ if (!sameLines || norm(again.arbiter) !== norm(arbiter)) return no();
240
+ return { ok: true, card };
241
+ }
242
+
196
243
  /** The refusal for a path that does not name a readable regular file (realpath at the click). @param {string} p */
197
244
  function fileProblem(p) {
198
245
  let real;
@@ -281,10 +328,15 @@ export function checkCard(card, { root, env = {} }) {
281
328
  const refusals = [];
282
329
  const no = (field, say) => refusals.push({ field, say });
283
330
 
284
- // flow name: the CLI's own check, and not an existing flow
331
+ // flow name: the CLI's own check, and not an existing flow (M6: unless this card edits that very job, still at the hash it was opened at)
285
332
  const name = checkFlowName(card.flowName);
286
333
  if (!name.ok) no('flowName', `${name.red}. Use lowercase letters, digits, "-" or "_".`);
287
- else {
334
+ else if (card.editOf) {
335
+ const was = signedHashOf(join(root, card.editOf.flow));
336
+ if (card.flowName !== card.editOf.flow) no('flowName', `The name of a job being edited cannot change. It stays "${card.editOf.flow}".`);
337
+ else if (was === null) no('flowName', `The job "${card.editOf.flow}" is no longer here, so it cannot be edited. Clear the card and start a new job.`);
338
+ else if (was !== card.editOf.flowHash) no('flowName', `"${card.editOf.flow}" was signed again since you opened it for editing. Open it again to edit the new version. Nothing was changed.`);
339
+ } else {
288
340
  let there = true;
289
341
  try { lstatSync(join(root, card.flowName)); } catch { there = false; }
290
342
  if (there) no('flowName', `There is already a flow named "${card.flowName}" here. Pick a name that is not used yet.`);
@@ -19,7 +19,7 @@ import { canFlowRun, willNotRunSay } from '../canrun.js';
19
19
  import { loadCatalogue } from '../catalogue.js';
20
20
  import { ConfigError, readConfig } from '../config.js';
21
21
  import {
22
- checkFlowName, listFlowNames, listRunIds, nextRunId, readFileInside, readFlow, resolveRunDir,
22
+ changeSentence, checkFlowName, listFlowNames, listRunIds, nextRunId, readFileInside, readFlow, resolveRunDir,
23
23
  } from '../flow.js';
24
24
  import { spendSummary } from '../monthly.js';
25
25
  import { userInfo } from 'node:os';
@@ -27,11 +27,16 @@ import {
27
27
  applyRunValues, flowValues, pickRunValues, valuesHash,
28
28
  } from '../runvalues.js';
29
29
  import {
30
- capFloorFor, capFloorText, checkInputRows, runInputRows,
30
+ capFloorFor, capFloorText, cardFromSigned, checkInputRows, runInputRows,
31
31
  } from './authorcard.js';
32
32
  import { checkValues } from './authorvalues.js';
33
+ import { getRunControls } from './data.js';
33
34
  import { providerKeys } from './spawn.js';
34
35
 
36
+ /** M6 amendment 1: the sentence the page shows and the sign route refuses with, for a job with a run running or waiting at its ask. @param {string} runId */
37
+ export const editBlockedSay = (runId) => `finish or stop ${runId} first`;
38
+ /** M6 amendment 3: the sentence for a job with a start still alive (its start folder in phase `starting`). */
39
+ export const EDIT_STARTING_SAY = 'a run is starting';
35
40
  const NO_LIMIT = 'no monthly limit set';
36
41
  /** The body keys a run start takes (amendment 5 item 2): the open boxes plus the hash of the second click. Any other key is refused by name. */
37
42
  const RUN_KEYS = ['flow', 'inputs', 'runId', 'destination', 'capUsd', 'askWaits', 'hash'];
@@ -169,7 +174,7 @@ export function createFlowsDoor(opts) {
169
174
  if (!named.ok) return reply(400, { refused: 'flow', refusals: [{ field: 'flow', say: `${named.red}.` }] });
170
175
  const read = readSigned(realRoot, flow);
171
176
  if (!read.ok) {
172
- return reply(400, { refused: 'flow', refusals: [{ field: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so it will not run.` }], reds: read.reds.map((r) => scrub(String(r), keys)) });
177
+ return reply(400, { refused: 'flow', refusals: [{ field: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so it will not run.${changeSentence(read.reds.map((r) => scrub(String(r), keys)))}` }], reds: read.reds.map((r) => scrub(String(r), keys)) });
173
178
  }
174
179
  const can = canFlowRun(read); // amendment 21 item 1: a flow the list shows refused is refused here too, in the same sentence
175
180
  if (!can.ok) {
@@ -206,6 +211,25 @@ export function createFlowsDoor(opts) {
206
211
  };
207
212
  }
208
213
 
214
+ /**
215
+ * Why a job cannot be edited right now, in the sentence the page shows and the sign route refuses with; `null` when it can. M6 amendment 1:
216
+ * the newest run that is running or waiting at its ask, by the panel's ONE decision (`runControls`, via `getRunControls`: `canStop`) ->
217
+ * "finish or stop run-N first". M6 amendment 3: a start folder in phase `starting` for this flow whose child is alive (`starter.startingFor`,
218
+ * the start door's own rule) -> "a run is starting"; a start that is done, refused or dead unlocks. A stopped, finished or expired run does not count.
219
+ * @param {string} realRoot @param {string} name @returns {string|null}
220
+ */
221
+ function editBlockOf(realRoot, name) {
222
+ const cat = loadCatalogue();
223
+ if (!cat.ok) return null;
224
+ if (starter.startingFor(name, []) !== null) return EDIT_STARTING_SAY;
225
+ const ids = listRunIds(join(realRoot, name)).filter((id) => /^run-\d+$/.test(id)).sort((a, b) => Number(b.slice(4)) - Number(a.slice(4)));
226
+ for (const id of ids) {
227
+ const c = getRunControls({ root: realRoot, flow: name, runId: id, catalogue: cat.primitives });
228
+ if (c?.canStop === true) return editBlockedSay(id);
229
+ }
230
+ return null;
231
+ }
232
+
209
233
  /** One flow's record for the page: its signed values and facts, its last run's inputs, its passed runs and its track record. @param {string} realRoot @param {string} name @param {any} read @param {any} left */
210
234
  function entryFor(realRoot, name, read, left) {
211
235
  const roles = (read.arbiter.sources ?? []).map((s) => s.role);
@@ -216,10 +240,22 @@ export function createFlowsDoor(opts) {
216
240
  flow: name, capUsd: read.arbiter.capUsd, roles, nextRunId: nextRunId(flowDir), lastRunId: last.runId, lastSources: last.sources, leftThisMonth: left,
217
241
  runs: passed, stats,
218
242
  ...formFacts(read),
243
+ // M6: the job as a card to edit (`ok:true, card, flowHash` = the signature hash it is opened at), or why it cannot be (`ok:false, say`)
244
+ edit: (() => {
245
+ const blocked = editBlockOf(realRoot, name);
246
+ if (blocked !== null) return { ok: false, say: blocked };
247
+ const c = cardFromSigned(read); return c.ok ? { ok: true, card: c.card, flowHash: read.signature.flow } : c;
248
+ })(),
219
249
  };
220
250
  }
221
251
 
222
252
  return {
253
+ /** M6 amendments 1 and 3: the sentence that says why this flow cannot be edited now, or null (the sign route's check). @param {string} name */
254
+ editBlock(name) {
255
+ const realRoot = realRootOrNull();
256
+ return realRoot === null ? null : editBlockOf(realRoot, name);
257
+ },
258
+
223
259
  /** `GET /api/author/flows`. */
224
260
  flows() {
225
261
  const realRoot = realRootOrNull();
@@ -16,7 +16,7 @@ import { userInfo } from 'node:os';
16
16
 
17
17
  import { scrub } from '../authoring.js';
18
18
  import { loadCatalogue } from '../catalogue.js';
19
- import { checkFlowName, readFileInside, readFlow, resolveRunDir } from '../flow.js';
19
+ import { changeSentence, checkFlowName, readFileInside, readFlow, resolveRunDir } from '../flow.js';
20
20
  import { readResumeLock } from '../liveness.js';
21
21
  import { auditSpend } from '../runner.js';
22
22
  import {
@@ -56,7 +56,7 @@ export function createResumeDoor(opts) {
56
56
  const cat = loadCatalogue();
57
57
  if (!cat.ok) return no(500, { refused: 'catalogue', say: 'The catalogue could not be loaded. Nothing was signed.' });
58
58
  const read = readFlow({ root: realRoot, name: flow, catalogue: cat.primitives });
59
- if (!read.ok) return no(400, { refused: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so a run of it will not resume.` });
59
+ if (!read.ok) return no(400, { refused: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so a run of it will not resume.${changeSentence(read.reds)}` });
60
60
  const controls = getRunControls({
61
61
  root: realRoot, flow, runId, catalogue: cat.primitives,
62
62
  });