fwdloop 0.19.0 → 0.20.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.
Files changed (52) hide show
  1. package/bin/fwdloop +22 -13
  2. package/package.json +1 -1
  3. package/src/authoring.js +23 -3
  4. package/src/books.js +3 -2
  5. package/src/flow.js +218 -2
  6. package/src/jobkey.js +25 -0
  7. package/src/jsonl-append.js +29 -0
  8. package/src/monthly.js +3 -2
  9. package/src/panel/author.js +44 -18
  10. package/src/panel/authorcard.js +7 -13
  11. package/src/panel/authorflows.js +118 -24
  12. package/src/panel/authorresume.js +8 -4
  13. package/src/panel/authorstart.js +63 -18
  14. package/src/panel/authortrigger.js +252 -128
  15. package/src/panel/authorvalues.js +13 -2
  16. package/src/panel/data.js +233 -36
  17. package/src/panel/index.html +330 -124
  18. package/src/panel/needsyou.js +29 -0
  19. package/src/panel/scheduler.js +23 -23
  20. package/src/panel/server.js +30 -6
  21. package/src/primitives.js +5 -6
  22. package/src/provider.js +3 -2
  23. package/src/runner.js +10 -10
  24. package/src/runvalues.js +10 -2
  25. package/src/schedule.js +135 -0
  26. package/src/setup.js +0 -21
  27. package/src/summary-words.js +180 -12
  28. package/src/trigger-clock.js +18 -16
  29. package/src/trigger-files.js +40 -27
  30. package/src/trigger-line.js +6 -15
  31. package/src/types.js +1 -1
  32. package/types/authoring.d.ts +32 -2
  33. package/types/flow.d.ts +106 -0
  34. package/types/jobkey.d.ts +11 -0
  35. package/types/jsonl-append.d.ts +6 -0
  36. package/types/panel/author.d.ts +48 -38
  37. package/types/panel/authorcard.d.ts +3 -6
  38. package/types/panel/authorflows.d.ts +38 -10
  39. package/types/panel/authorstart.d.ts +15 -2
  40. package/types/panel/authortrigger.d.ts +75 -63
  41. package/types/panel/authorvalues.d.ts +6 -0
  42. package/types/panel/data.d.ts +101 -19
  43. package/types/panel/needsyou.d.ts +20 -0
  44. package/types/primitives.d.ts +5 -0
  45. package/types/runvalues.d.ts +5 -0
  46. package/types/schedule.d.ts +69 -0
  47. package/types/setup.d.ts +0 -19
  48. package/types/summary-words.d.ts +105 -4
  49. package/types/trigger-clock.d.ts +8 -7
  50. package/types/trigger-files.d.ts +17 -10
  51. package/types/trigger-line.d.ts +16 -8
  52. package/types/types.d.ts +1 -1
package/bin/fwdloop CHANGED
@@ -23,13 +23,13 @@ import { draftHoldUsd } from '../src/draftspend.js';
23
23
  import { pathToFileURL } from 'node:url';
24
24
 
25
25
  import {
26
- readFlow, checkFlowName, resolveRunDir, listFlowNames, listRunIds, readFileInside, claimRunId,
26
+ readPlan, readRunPlan, checkFlowName, resolveRunDir, listFlowNames, listRunIds, readFileInside, claimRunId,
27
27
  } from '../src/flow.js';
28
28
  import { loadCatalogue } from '../src/catalogue.js';
29
29
  import {
30
30
  runFlow, resumeRun, continueRun, auditSpend, makeParkingAskStep, readAsk, readRunState,
31
31
  } from '../src/runner.js';
32
- import { applyRunValues, pickRunValues, dropUnstartedValues } from '../src/runvalues.js';
32
+ import { applyRunValues, pickRunValues, dropUnstartedValues, runModelOf } from '../src/runvalues.js';
33
33
  import { TRIGGER_RECORD_FILE } from '../src/trigger-line.js';
34
34
  import { makeLiveModelStep } from '../src/model-step.js';
35
35
  import { sendViaPrimitive } from '../src/send.js';
@@ -160,7 +160,7 @@ function today() {
160
160
  * be hit by a user typing `--something`. This is how the test suite drives
161
161
  * every CLI scenario at $0 with zero chance of a real network call.
162
162
  */
163
- async function resolveModelStep(spendPath, env, flowDir, named = {}) {
163
+ async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel = null) {
164
164
  if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
165
165
  const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
166
166
  const mod = await import(pathToFileURL(modulePath).href);
@@ -172,7 +172,7 @@ async function resolveModelStep(spendPath, env, flowDir, named = {}) {
172
172
  const modelStep = await mod.default({ spendPath });
173
173
  let usable = null;
174
174
  try {
175
- const rec = configDoorHome().skip ? null : readModelRecord(flowDir);
175
+ const rec = configDoorHome().skip ? null : (runModel ?? readModelRecord(flowDir));
176
176
  usable = rec === null ? null : resolveUsableModel(rec.slot, { config: readPriceConfig(), model: rec.model });
177
177
  } catch (err) {
178
178
  if (!(err instanceof ConfigError)) throw err; // a broken config is refused by name at the monthly hold, right after this
@@ -187,7 +187,7 @@ async function resolveModelStep(spendPath, env, flowDir, named = {}) {
187
187
  let slot;
188
188
  try {
189
189
  const config = readPriceConfig();
190
- const rec = readModelRecord(flowDir);
190
+ const rec = runModel ?? readModelRecord(flowDir); // M6 am5/am6: the model signed for THIS run, else the one recorded with the job
191
191
  if (rec !== null && named.model !== undefined && (named.model !== rec.model || (named.provider !== undefined && named.provider !== rec.slot))) {
192
192
  throw new Error(`This job already has its model recorded (${rec.slot} · ${rec.model}); --model cannot change it.`);
193
193
  }
@@ -311,7 +311,8 @@ async function cmdRun(rest) {
311
311
  if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
312
312
  const catalogue = loaded.primitives;
313
313
 
314
- const read = readFlow({ root, name: flowName, catalogue });
314
+ const planRunDir = (id) => { if (typeof id !== 'string') return null; const c = resolveRunDir(join(root, flowName), id); return c.ok ? c.runDir : null; }; // am9: a run that keeps its own plan reads it
315
+ const read = readPlan({ root, name: flowName, catalogue, runDir: planRunDir(values['run-id']) });
315
316
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
316
317
  const { declaration } = read;
317
318
 
@@ -353,7 +354,7 @@ async function cmdRun(rest) {
353
354
  if (!runIdCheck.ok) fail(runIdCheck.red);
354
355
  runDir = runIdCheck.runDir;
355
356
  // M4e amendment 5: the panel's Sign & run puts the run's signed values in the folder BEFORE the start; that one file is not "a run".
356
- if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json' && n !== TRIGGER_RECORD_FILE).length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
357
+ if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json' && n !== TRIGGER_RECORD_FILE && n !== 'job' && n !== 'plan.json' && n !== 'setup.jsonl').length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
357
358
  }
358
359
  // M4e amendment 5 item 3: the cap this run was signed with (its own values file, else the flow's) is what the monthly hold is for.
359
360
  const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
@@ -368,7 +369,7 @@ async function cmdRun(rest) {
368
369
  let modelStep;
369
370
  let ceilingUsd;
370
371
  try {
371
- ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values));
372
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
372
373
  } catch (err) {
373
374
  fail(err.message);
374
375
  return;
@@ -607,7 +608,8 @@ async function cmdResume(rest) {
607
608
  if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
608
609
  const catalogue = loaded.primitives;
609
610
 
610
- const read = readFlow({ root, name: flowName, catalogue });
611
+ const planRunDir = (id) => { if (typeof id !== 'string') return null; const c = resolveRunDir(join(root, flowName), id); return c.ok ? c.runDir : null; }; // am9: a run that keeps its own plan reads it
612
+ const read = planRunDir(runId) === null ? readPlan({ root, name: flowName, catalogue, runDir: null }) : readRunPlan({ root, name: flowName, catalogue, runDir: /** @type {string} */ (planRunDir(runId)) }); // M9 am12: the run's own saved job (a bad runId is refused by name just below)
611
613
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
612
614
  const { declaration } = read;
613
615
 
@@ -624,7 +626,7 @@ async function cmdResume(rest) {
624
626
  let modelStep;
625
627
  let ceilingUsd;
626
628
  try {
627
- ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values));
629
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
628
630
  } catch (err) {
629
631
  fail(err.message);
630
632
  return;
@@ -709,7 +711,8 @@ async function cmdContinue(rest) {
709
711
  if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
710
712
  const catalogue = loaded.primitives;
711
713
 
712
- const read = readFlow({ root, name: flowName, catalogue });
714
+ const planRunDir = (id) => { if (typeof id !== 'string') return null; const c = resolveRunDir(join(root, flowName), id); return c.ok ? c.runDir : null; }; // am9: a run that keeps its own plan reads it
715
+ const read = planRunDir(runId) === null ? readPlan({ root, name: flowName, catalogue, runDir: null }) : readRunPlan({ root, name: flowName, catalogue, runDir: /** @type {string} */ (planRunDir(runId)) }); // M9 am12: the run's own saved job (a bad runId is refused by name just below)
713
716
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
714
717
  const { declaration } = read;
715
718
 
@@ -724,7 +727,7 @@ async function cmdContinue(rest) {
724
727
  let modelStep;
725
728
  let ceilingUsd;
726
729
  try {
727
- ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values));
730
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
728
731
  } catch (err) {
729
732
  fail(err.message);
730
733
  return;
@@ -904,7 +907,7 @@ async function cmdDraft(rest) {
904
907
  async function cmdSign(rest) {
905
908
  const { values, positionals } = parseArgs({
906
909
  args: rest,
907
- options: { approve: { type: 'string' }, 'signed-by': { type: 'string' } },
910
+ options: { approve: { type: 'string' }, 'signed-by': { type: 'string' }, 'run-of': { type: 'string' } },
908
911
  allowPositionals: true,
909
912
  });
910
913
  const keysLoad = keyedLoad(); // sign takes no key, but its leak sweep must know the file's keys too
@@ -925,8 +928,14 @@ async function cmdSign(rest) {
925
928
  if (!typed.ok) fail(`sign refused — ${typed.red}`);
926
929
  const result = signDraft({
927
930
  dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username, env, keyNames: keysLoad.keyNames,
931
+ // M6 am9: a red run's redraft of an unchanged job is signed as the plan of a new run of that workflow (--run-of <workflow>); the same TTY and typed name above
932
+ ...(values['run-of'] ? { asRunOf: { flow: values['run-of'] } } : {}),
928
933
  });
929
934
  if (!result.ok) fail(`sign refused — ${result.reds.join('; ')}`);
935
+ if (result.runId) {
936
+ process.stdout.write(`signed: ${result.runDir} as ${result.runId} of ${values['run-of']} (by ${result.signature.signedBy})\nrun it: fwdloop run ${values['run-of']} --root <dir> --run-id ${result.runId} --source <role>=<path> ...\n`);
937
+ return;
938
+ }
930
939
  process.stdout.write(`signed: ${result.flowDir} (by ${result.signature.signedBy})\n`);
931
940
  }
932
941
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.19.0",
3
+ "version": "0.20.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
@@ -25,7 +25,8 @@ import { validateDeclaration } from './declaration.js';
25
25
  import { loadCatalogue } from './catalogue.js';
26
26
  import { WIRED_VERBS } from './primitives.js';
27
27
  import { canonicalBytes } from './signature.js';
28
- import { writeFlow, readFileInside, readdirInside, checkFlowName } from './flow.js';
28
+ import { writeFlow, writeRunPlan, readFlow, readFileInside, readdirInside, checkFlowName } from './flow.js';
29
+ import { jobKeyOfSigned } from './jobkey.js';
29
30
  import { checkSendDestination } from './runner.js';
30
31
  import { checkKeyPreflight, appendSpendRow } from './provider.js';
31
32
  import { keyValues } from './keysfile.js';
@@ -398,10 +399,12 @@ export async function draftToDir({
398
399
  * `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.
399
400
  * M6: `replaces: {flowHash}` (a draft opened from an existing signed job, carrying that job's signature hash) makes this sign REPLACE that job
400
401
  * (`writeFlow` checks the hash is still the job's); without it a taken name is refused as ever.
401
- * @param {{dir: any, approve?: any, signedBy: any, signedAt?: string, env?: Record<string, string|undefined>, keyNames?: string[], sessionDir?: string, replaces?: {flowHash: string}}} a
402
+ * M6 am9: `asRunOf: {flow}` (a red run's redraft of an UNCHANGED job) signs the plan as the plan of a NEW run of that existing workflow: the workflow's own files are
403
+ * never written (`writeRunPlan`), and a plan whose job key is not the workflow's is refused here, at sign time.
404
+ * @param {{dir: any, approve?: any, signedBy: any, signedAt?: string, env?: Record<string, string|undefined>, keyNames?: string[], sessionDir?: string, replaces?: {flowHash: string}, asRunOf?: {flow: string}}} a
402
405
  */
403
406
  export function signDraft({
404
- dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, keyNames, sessionDir, replaces,
407
+ dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, keyNames, sessionDir, replaces, asRunOf,
405
408
  }) {
406
409
  const refuse = (...reds) => ({ ok: false, reds });
407
410
  if (readFileInside(dir, LEAK_MARKER_FILE).ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
@@ -455,6 +458,23 @@ export function signDraft({
455
458
  }
456
459
  if (reds.length) return { ok: false, reds };
457
460
 
461
+ if (asRunOf !== undefined) {
462
+ if (target.name !== asRunOf.flow) return refuse(`sign: this draft is named "${target.name}", not the workflow "${asRunOf.flow}" it was drafted as a run of — nothing signed`);
463
+ const existing = readFlow({ root: target.root, name: asRunOf.flow, catalogue: cat.primitives });
464
+ if (!existing.ok) return refuse(`sign: the workflow "${asRunOf.flow}" is not a signed flow that reads (${existing.reds[0]}) — nothing signed`);
465
+ if (jobKeyOfSigned(signed) !== jobKeyOfSigned(existing)) return refuse(`sign: the job in this plan is not the job of "${asRunOf.flow}", so it cannot be a run of it (a changed job is a new workflow) — nothing signed`);
466
+ const ran = writeRunPlan({
467
+ root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives,
468
+ });
469
+ if (!ran.ok) return { ok: false, reds: ran.reds };
470
+ const runSetup = writeSetup({
471
+ flowDir: ran.runDir, sessionDir, planDir: dir, hash: h.hash, signedBy, signedAt, flowHash: ran.signature?.flow, secrets: /** @type {string[]} */ (keys.filter((k) => typeof k === 'string' && k.length >= 8)),
472
+ });
473
+ // the draft's model pick is NOT written to the workflow (its files stay untouched): it is returned for the run that follows (`--model/--provider`)
474
+ return {
475
+ ok: true, flowDir: path.join(target.root, target.name), runId: ran.runId, runDir: ran.runDir, signature: ran.signature, setup: runSetup, modelRecord: { ok: true, recorded: false }, modelPick: readModelRecord(dir),
476
+ };
477
+ }
458
478
  const written = writeFlow({
459
479
  root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives, replaces,
460
480
  });
package/src/books.js CHANGED
@@ -18,15 +18,16 @@
18
18
  // history); both throw (never silently coerce) on a violation, so a bad
19
19
  // caller fails loudly at the one place that would otherwise hide it.
20
20
 
21
- import { appendFileSync, mkdirSync } from 'node:fs';
21
+ import { mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
 
24
24
  import { readFileInside, readdirInside } from './flow.js';
25
+ import { appendRow } from './jsonl-append.js';
25
26
  import { TRIGGER_RECORD_FILE } from './trigger-line.js';
26
27
 
27
28
  function appendLine(filePath, row) {
28
29
  mkdirSync(dirname(filePath), { recursive: true });
29
- appendFileSync(filePath, `${JSON.stringify(row)}\n`);
30
+ appendRow(filePath, row);
30
31
  }
31
32
 
32
33
  /**
package/src/flow.js CHANGED
@@ -29,6 +29,7 @@ import { parseSignedText } from './signed-text.js';
29
29
  import { signFlow, verifyFlow } from './signature.js';
30
30
  import { validateDeclaration } from './declaration.js';
31
31
  import { describeChange } from './signed-diff.js';
32
+ import { stripTrigger } from './trigger-line.js';
32
33
 
33
34
  /** @typedef {import('./types.js').WriteFlowResult} WriteFlowResult */
34
35
  /** @typedef {import('./types.js').ReadFlowResult} ReadFlowResult */
@@ -560,13 +561,58 @@ export function signedHashOf(flowDir) {
560
561
  /** 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
562
  const SWAP_NAMES = ['prose.txt', 'declaration.json', SIGNED_COPY_DIR, 'setup.jsonl', 'signature.json'];
562
563
 
564
+ /** The names `replaceSigned` stages (signature last); `setup.jsonl` is only ever moved away, never staged. */
565
+ const STAGE_NAMES = ['prose.txt', 'declaration.json', SIGNED_COPY_DIR, 'signature.json'];
566
+
567
+ /** Is a process with this pid alive? (EPERM = alive, owned by someone else.) @param {number} pid */
568
+ function pidAlive(pid) {
569
+ try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
570
+ }
571
+
572
+ /** Is there a `.replace-old-*` / `.replace-new-*` folder in the flow folder? @param {string} dir */
573
+ function hasSwapLeftover(dir) {
574
+ try { return readdirSync(dir).some((n) => /^\.replace-(?:old|new)-\d+-\d+$/.test(n)); } catch { return false; }
575
+ }
576
+
577
+ /**
578
+ * Recover a swap that a hard kill (SIGKILL, power loss) cut short: `.replace-old-<pid>-<ms>` / `.replace-new-<pid>-<ms>` of a process that is gone.
579
+ * The signature is placed LAST, so while the staged `signature.json` is still in `.replace-new-*` the swap never finished: every moved-away old file
580
+ * goes back and every new file already placed is removed (the old job again, byte for byte). Once the signature has landed the swap was whole: the
581
+ * leftovers are just deleted. Idempotent (a crash inside the recovery is recovered by the next call); a live pid's folders are never touched.
582
+ * @param {string} dir the flow folder @returns {boolean} true when something was recovered or cleaned
583
+ */
584
+ function recoverSwap(dir) {
585
+ let names;
586
+ try { names = readdirSync(dir); } catch { return false; }
587
+ const stamps = new Set(names.map((n) => /^\.replace-(?:old|new)-(\d+-\d+)$/.exec(n)?.[1]).filter((x) => x !== undefined));
588
+ let did = false;
589
+ for (const stamp of stamps) {
590
+ if (pidAlive(Number(String(stamp).split('-')[0]))) continue;
591
+ const stage = path.join(dir, `.replace-new-${stamp}`);
592
+ const backup = path.join(dir, `.replace-old-${stamp}`);
593
+ try {
594
+ if (existsSync(path.join(stage, 'signature.json'))) {
595
+ for (const n of SWAP_NAMES) {
596
+ const placed = STAGE_NAMES.includes(n) && !existsSync(path.join(stage, n));
597
+ if (placed) rmSync(path.join(dir, n), { recursive: true, force: true });
598
+ if (existsSync(path.join(backup, n))) renameSync(path.join(backup, n), path.join(dir, n));
599
+ }
600
+ }
601
+ rmSync(stage, { recursive: true, force: true });
602
+ rmSync(backup, { recursive: true, force: true });
603
+ did = true;
604
+ } catch { /* left for the next call */ }
605
+ }
606
+ return did;
607
+ }
608
+
563
609
  /**
564
610
  * 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
611
  * Refuses (touching nothing) unless the folder holds a signed job whose `signature.json` `flow` hash is `replaces.flowHash` (a draft opened from an
566
612
  * 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
613
  * 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.
614
+ * back. On success the backup is deleted — no old version is kept anywhere (hamr's ruling). A hard kill inside the swap leaves
615
+ * `.replace-old-*` / `.replace-new-*`; `recoverSwap` puts the old job back (or finishes the cleanup) the next time `readFlow` reds or a replace starts.
570
616
  * @param {{root: string, name: string, dir: string, proseText: string, declarationText: string, signature: any, replaces: {flowHash: string}, catalogue: unknown, onReplaceStep?: (step: string) => void}} a
571
617
  * @returns {WriteFlowResult}
572
618
  */
@@ -577,6 +623,7 @@ function replaceSigned({
577
623
  let dirStat;
578
624
  try { dirStat = lstatSync(dir); } catch { return red(`flow: nothing signed to replace — "${name}" has no folder here`); }
579
625
  if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return red(`flow: "${dir}" is not a plain folder, refused`);
626
+ recoverSwap(dir); // a swap cut short by a hard kill is put right before this one reads the folder
580
627
  const current = signedHashOf(dir);
581
628
  if (current === null) return red(`flow: nothing signed to replace — "${name}" has no readable signature.json`);
582
629
  if (typeof replaces?.flowHash !== 'string' || current !== replaces.flowHash) {
@@ -635,6 +682,103 @@ function replaceSigned({
635
682
  return { ok: true, dir, signature };
636
683
  }
637
684
 
685
+ /**
686
+ * M6 am9 ("Each run keeps the plan it ran"): which plan does a reuse of run `runDir` run? `{same:true}` = the workflow's own plan (the run kept no copy, as a run made
687
+ * before M6, or its kept plan is byte-equal to the workflow's declaration and prose, a trigger line aside). `{same:false, read}` = a different kept plan, already verified.
688
+ * `{ok:false, red}` = a kept plan that does not verify: refused by name, never swapped for the workflow's.
689
+ * @param {{root: string, name: string, runDir: string, catalogue: unknown}} a
690
+ * @returns {{ok: true, same: true} | {ok: true, same: false, read: ReadFlowResult & {ok: true}} | {ok: false, red: string}}
691
+ */
692
+ export function planForReuse({
693
+ root, name, runDir, catalogue,
694
+ }) {
695
+ const kept = readRunJobCopy(runDir, catalogue);
696
+ if (!kept.present) return { ok: true, same: true };
697
+ const runId = path.basename(runDir);
698
+ if (!kept.ok) return { ok: false, red: `The plan ${runId} kept does not match its signature (${kept.reds[0]}), so it cannot be reused. Nothing was started.` };
699
+ const flowDir = path.join(root, name);
700
+ const a = readFileInside(runDir, `${RUN_JOB_DIR}/declaration.json`);
701
+ const b = readFileInside(flowDir, 'declaration.json');
702
+ const ap = readFileInside(runDir, `${RUN_JOB_DIR}/prose.txt`);
703
+ const bp = readFileInside(flowDir, 'prose.txt');
704
+ if (a.ok && b.ok && ap.ok && bp.ok && a.text === b.text && stripTrigger(ap.text) === stripTrigger(bp.text)) return { ok: true, same: true };
705
+ const { present, ...rest } = kept;
706
+ void present;
707
+ return { ok: true, same: false, read: /** @type {any} */ (rest) };
708
+ }
709
+
710
+ /**
711
+ * M6 am9: give the run folder `runDir` a verified copy of the plan run `fromRunDir` kept (`job/` write-once, then `plan.json {planOf}`), so the run executes
712
+ * it. Nothing is signed: the bytes already carry a signature, proved here. A failure removes what this call wrote.
713
+ * @param {{fromRunDir: string, runDir: string, catalogue: unknown}} a
714
+ * @returns {{ok: true} | {ok: false, red: string}}
715
+ */
716
+ export function copyRunPlan({ fromRunDir, runDir, catalogue }) {
717
+ const kept = readRunJobCopy(fromRunDir, catalogue);
718
+ if (!kept.present || !kept.ok) return { ok: false, red: `The plan ${path.basename(fromRunDir)} kept is not there or does not verify, so it cannot be reused.` };
719
+ const texts = {};
720
+ for (const f of FLOW_FILES) {
721
+ const r = readFileInside(fromRunDir, `${RUN_JOB_DIR}/${f}`);
722
+ if (!r.ok) return { ok: false, red: `The plan ${path.basename(fromRunDir)} kept cannot be read (${f}).` };
723
+ texts[f] = r.text;
724
+ }
725
+ const jobDir = path.join(runDir, RUN_JOB_DIR);
726
+ try {
727
+ mkdirSync(jobDir);
728
+ for (const f of FLOW_FILES) writeFileSync(path.join(jobDir, f), texts[f], { encoding: 'utf8', flag: 'wx' });
729
+ writeFileSync(path.join(runDir, RUN_PLAN_MARKER), `${JSON.stringify({ planOf: path.basename(fromRunDir) })}\n`, { encoding: 'utf8', flag: 'wx' });
730
+ } catch (err) {
731
+ try { rmSync(jobDir, { recursive: true, force: true }); rmSync(path.join(runDir, RUN_PLAN_MARKER), { force: true }); } catch { /* best-effort */ }
732
+ return { ok: false, red: `The plan could not be copied into the new run (${err.code ?? err.message}). Nothing was started.` };
733
+ }
734
+ return { ok: true };
735
+ }
736
+
737
+ /**
738
+ * M6 am9 ("a red run always drafts"): sign a plan as the plan of a NEW run of an existing workflow. Same checks and the same `signFlow` as `writeFlow`,
739
+ * but nothing of the workflow is written: the run folder is claimed (`claimRunId`) and receives `job/{prose.txt,declaration.json,signature.json}` write-once,
740
+ * then `plan.json` last (the file that makes the run execute it). A failure removes the run folder this call claimed. The caller proves the job is unchanged.
741
+ * @param {{root: unknown, name: unknown, proseText: unknown, declaration: unknown, signedBy: unknown, signedAt: unknown, catalogue: unknown}} a
742
+ * @returns {{ok: true, runId: string, runDir: string, signature: any} | {ok: false, reds: string[]}}
743
+ */
744
+ export function writeRunPlan({
745
+ root, name, proseText, declaration, signedBy, signedAt, catalogue,
746
+ }) {
747
+ const nameCheck = checkFlowName(name);
748
+ if (!nameCheck.ok) return { ok: false, reds: [nameCheck.red] };
749
+ if (typeof root !== 'string' || root.length === 0) return { ok: false, reds: ['flow: "root" must be a non-empty string'] };
750
+ const flowDir = path.join(root, /** @type {string} */ (name));
751
+ if (signedHashOf(flowDir) === null) return { ok: false, reds: [`flow: "${name}" has no signed workflow here, so a plan cannot be signed as a run of it`] };
752
+ const signed = parseSignedText(proseText);
753
+ if (!signed.ok) return { ok: false, reds: signed.reds };
754
+ const validated = validateDeclaration(declaration, { arbiter: signed.arbiter, lines: signed.lines, catalogue });
755
+ if (!validated.ok) return { ok: false, reds: validated.reds };
756
+ let declarationText;
757
+ try { declarationText = `${JSON.stringify(declaration, null, 2)}\n`; } catch (err) { return { ok: false, reds: [`flow: declaration could not be serialised — ${err.message}`] }; }
758
+ const signResult = signFlow({ proseText, declarationText, signedBy, signedAt });
759
+ if (!signResult.ok) return { ok: false, reds: signResult.reds };
760
+ const claimed = claimRunId(flowDir);
761
+ if (!claimed.ok) return { ok: false, reds: [claimed.red] };
762
+ const { runDir, runId } = claimed;
763
+ try {
764
+ const jobDir = path.join(runDir, RUN_JOB_DIR);
765
+ mkdirSync(jobDir);
766
+ writeFileSync(path.join(jobDir, 'prose.txt'), /** @type {string} */ (proseText), { encoding: 'utf8', flag: 'wx' });
767
+ writeFileSync(path.join(jobDir, 'declaration.json'), declarationText, { encoding: 'utf8', flag: 'wx' });
768
+ writeFileSync(path.join(jobDir, 'signature.json'), `${JSON.stringify(signResult.signature, null, 2)}\n`, { encoding: 'utf8', flag: 'wx' });
769
+ writeFileSync(path.join(runDir, RUN_PLAN_MARKER), `${JSON.stringify({ own: true })}\n`, { encoding: 'utf8', flag: 'wx' });
770
+ } catch (err) {
771
+ try { rmSync(runDir, { recursive: true, force: true }); } catch { /* best-effort */ }
772
+ return { ok: false, reds: [`flow: could not write the run's plan — ${err.message}. Nothing was signed.`] };
773
+ }
774
+ const proof = readPlan({ root, name, catalogue, runDir });
775
+ if (!proof.ok) {
776
+ try { rmSync(runDir, { recursive: true, force: true }); } catch { /* best-effort */ }
777
+ return { ok: false, reds: [`flow: the run's plan does not verify (${proof.reds.join('; ')})`] };
778
+ }
779
+ return { ok: true, runId, runDir, signature: signResult.signature };
780
+ }
781
+
638
782
  /**
639
783
  * Read and verify a signed flow from `<root>/<name>/`. Verifies the bytes on
640
784
  * disk against the signature FIRST — before anything in the flow is
@@ -645,6 +789,17 @@ function replaceSigned({
645
789
  * @returns {ReadFlowResult}
646
790
  */
647
791
  export function readFlow({ root, name, catalogue }) {
792
+ const r = readFlowOnce({ root, name, catalogue });
793
+ if (typeof root !== 'string' || root.length === 0 || !checkFlowName(name).ok) return r;
794
+ // a red may be a swap a hard kill cut short (the job refused until files were moved by hand): recover it, read once more.
795
+ // A green read can hold a dead pid's leftover too (killed after the signature landed: the OLD signed job sits in `.replace-old-*`): clear it
796
+ // (only looked for when such a folder exists; a live pid's folders are never touched).
797
+ if (r.ok && !hasSwapLeftover(path.join(root, /** @type {string} */ (name)))) return r;
798
+ return recoverSwap(path.join(root, /** @type {string} */ (name))) ? readFlowOnce({ root, name, catalogue }) : r;
799
+ }
800
+
801
+ /** @param {{root: unknown, name: unknown, catalogue: unknown}} input @returns {ReadFlowResult} */
802
+ function readFlowOnce({ root, name, catalogue }) {
648
803
  const nameCheck = checkFlowName(name);
649
804
  if (!nameCheck.ok) return { ok: false, reds: [nameCheck.red] };
650
805
  const safeName = /** @type {string} */ (name);
@@ -788,6 +943,49 @@ export function writeRunJobCopy(flowDir, runDir, expectedFlowHash) {
788
943
  return { ok: true };
789
944
  }
790
945
 
946
+ /** M6 am9: a run's folder holds this file when the run executes the plan it keeps (`<run>/job/`), not the flow folder's. Written once, by the run's plan writer. */
947
+ export const RUN_PLAN_MARKER = 'plan.json';
948
+
949
+ /** M6 am9: does this run execute its own kept plan? The ONE test (no marker = the flow folder's plan, as every run before am9). @param {string} runDir */
950
+ export function runOwnsPlan(runDir) {
951
+ return existsSync(path.join(runDir, RUN_PLAN_MARKER));
952
+ }
953
+
954
+ /**
955
+ * M6 am9: the ONE reader of the plan a run executes. A run whose folder holds `plan.json` reads its own verified copy (`<run>/job/`); every other
956
+ * run (and a read with no run) reads the flow folder exactly as `readFlow` does. Never throws; a kept plan that does not verify is a red, never swapped for the flow's.
957
+ * @param {{root: unknown, name: unknown, catalogue: unknown, runDir?: string|null}} a
958
+ * @returns {ReadFlowResult}
959
+ */
960
+ export function readPlan({ root, name, catalogue, runDir }) {
961
+ if (typeof runDir !== 'string' || !runOwnsPlan(runDir)) return readFlow({ root, name, catalogue });
962
+ const c = readRunJobCopy(runDir, catalogue);
963
+ if (!c.present) return { ok: false, reds: [`plan: ${runDir} is marked as running its own plan but holds no job/ copy`] };
964
+ if (!c.ok) return { ok: false, reds: c.reds.map((r) => `plan: this run's kept plan — ${r}`) };
965
+ const { present, ...rest } = c;
966
+ void present;
967
+ return /** @type {ReadFlowResult} */ (rest);
968
+ }
969
+
970
+ /**
971
+ * M9 am12: the ONE reader of "the job this run resumes against" (an answer, Resume, Reopen, continue-after-cap, the panel's resume controls).
972
+ * Always the run's OWN kept copy, verified against that copy's own signature (a run with `plan.json` reads it through `readPlan`, the same
973
+ * `<run>/job/`); never the workflow's current job, so a Cancel or an Edit of the workflow does not strand a waiting run. A copy that fails its
974
+ * signature is a red naming it; a run with no copy (it started before M6) is a red with `noCopy: true`, never the flow's job. Never throws.
975
+ * @param {{root: unknown, name: unknown, catalogue: unknown, runDir: string}} a
976
+ * @returns {ReadFlowResult | {ok: false, reds: string[], noCopy: true}}
977
+ */
978
+ export function readRunPlan({ root, name, catalogue, runDir }) {
979
+ if (typeof runDir !== 'string' || runDir === '') return { ok: false, noCopy: true, reds: ['this run has no saved copy of its job (no such run folder)'] };
980
+ if (runOwnsPlan(runDir)) return readPlan({ root, name, catalogue, runDir });
981
+ const c = readRunJobCopy(runDir, catalogue);
982
+ if (!c.present) return { ok: false, noCopy: true, reds: ['this run has no saved copy of its job (it started before runs kept one), so it cannot carry on; start a new run'] };
983
+ if (!c.ok) return { ok: false, reds: c.reds.map((r) => `this run's saved copy of its job — ${r}`) };
984
+ const { present, ...rest } = c;
985
+ void present;
986
+ return /** @type {ReadFlowResult} */ (rest);
987
+ }
988
+
791
989
  /**
792
990
  * 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
991
  * shape as a good `readFlow` (lines, arbiter, declaration, signature, classes), after the copy was verified against the copied signature.
@@ -837,3 +1035,21 @@ function explainEdit(dir, signature, proseText, declarationText) {
837
1035
  if (changes.length === 0) return [CHANGED_PREFIX + 'the files match the saved copy; signature.json itself was changed'];
838
1036
  return changes.map((c) => `${CHANGED_PREFIX}${c}`);
839
1037
  }
1038
+
1039
+ /**
1040
+ * M6 am5 item 2: the name suggested for the new workflow a changed job becomes: `<base>-N`, N the first free number from 2. A trailing `-N` of
1041
+ * `name` is stripped first when what is left is itself a workflow here (aging-live-4-2 -> base aging-live-4; aging-live-4 keeps its 4). "Free" = nothing at all by that name under root (a folder or a file), the same
1042
+ * test the card's name check makes. Pure read; the sign still refuses a name taken meanwhile (writeFlow never overwrites).
1043
+ * @param {string} root @param {string} name
1044
+ */
1045
+ export function suggestFlowName(root, name) {
1046
+ const taken = (/** @type {string} */ n) => { try { lstatSync(path.join(root, n)); return true; } catch { return false; } };
1047
+ // a trailing -N is stripped only when what is left is itself a workflow here (aging-live-4-2 -> aging-live-4); a name that merely ends in a number keeps it
1048
+ const stripped = name.replace(/-[0-9]+$/, '');
1049
+ const base = stripped !== name && stripped !== '' && taken(stripped) ? stripped : name;
1050
+ for (let n = 2; ; n += 1) {
1051
+ const tail = `-${n}`;
1052
+ const candidate = `${base.slice(0, 64 - tail.length)}${tail}`;
1053
+ if (!taken(candidate)) return candidate;
1054
+ }
1055
+ }
package/src/jobkey.js ADDED
@@ -0,0 +1,25 @@
1
+ // borrowed-from: bareloop src/job.js@HEAD (workflowKey: the identity of a workflow is the spec WITHOUT the fields a reuse may change).
2
+ // M6 am5/am6: the JOB's identity. A job is its steps in order: each step's text (an ask carries its question), whether it is an ask, and its
3
+ // guardrail. Run fields (cap, destination, input paths, ask waits, trigger, model) are not in it, so changing one never makes a new workflow.
4
+ // What this throws away: the ask wait, spacing/blank lines/case of the `Ask` mark, and everything outside the job lines. NOT a signature.
5
+ // TWO producers, ONE canonical form: the signed flow (parseSignedText's lines + arbiter) and the card's job box (parseJobBox).
6
+ import { createHash } from 'node:crypto';
7
+
8
+ import { joinGuardrails, parseJobBox } from './panel/authorcard.js';
9
+
10
+ /** @param {{ask: boolean, text: string, guardrail: string}[]} steps */
11
+ function keyOf(steps) {
12
+ return createHash('sha256').update(`job-key-v1\n${JSON.stringify(steps)}`).digest('hex');
13
+ }
14
+
15
+ /** The key of the job as the card's job box types it. @param {string} job */
16
+ export function jobKeyOfCard(job) {
17
+ const { steps } = parseJobBox(String(job));
18
+ return keyOf(steps.map((s) => ({ ask: s.ask !== null, text: s.ask ? s.ask.question.trim() : s.text.trim(), guardrail: joinGuardrails(s.guardrails) })));
19
+ }
20
+
21
+ /** The key of a signed job. @param {{ lines: {n: number, text: string, guardrail: string}[], arbiter: any }} signed `parseSignedText`'s ok result */
22
+ export function jobKeyOfSigned({ lines, arbiter }) {
23
+ const asks = new Set((arbiter.asks ?? []).map((a) => a.line));
24
+ return keyOf(lines.map((l) => ({ ask: asks.has(l.n), text: String(l.text).trim(), guardrail: String(l.guardrail ?? '').trim() })));
25
+ }
@@ -0,0 +1,29 @@
1
+ // The ONE fresh-line rule for every append-only JSONL file (books, trigger ledgers, triggers.jsonl): a crash can tear the last line mid-append, and the
2
+ // next row must not glue onto those bytes (the glued line would fail to parse, be skipped, and the row would be lost). Readers skip an unparseable line;
3
+ // this is its other half, and the two only work together.
4
+ import {
5
+ appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync,
6
+ } from 'node:fs';
7
+
8
+ /** The ledger's text, '' when there is no file yet. @param {string} file */
9
+ export function ledgerText(file) {
10
+ return existsSync(file) ? readFileSync(file, 'utf8') : '';
11
+ }
12
+
13
+ /** True when the file exists, is not empty and does not end in a newline (a torn last line). Reads one byte, however big the file. @param {string} file */
14
+ function endsTorn(file) {
15
+ let fd;
16
+ try { fd = openSync(file, 'r'); } catch { return false; } // no file yet: nothing to tear
17
+ try {
18
+ const { size } = fstatSync(fd);
19
+ if (size === 0) return false;
20
+ const last = Buffer.alloc(1);
21
+ readSync(fd, last, 0, 1, size - 1);
22
+ return last[0] !== 0x0a;
23
+ } finally { closeSync(fd); }
24
+ }
25
+
26
+ /** Append one JSON row as its own line; a torn last line gets its newline first. The parent folder must exist. @param {string} file @param {unknown} row @param {{mode?: number}} [options] e.g. `{ mode: 0o600 }` */
27
+ export function appendRow(file, row, options) {
28
+ appendFileSync(file, `${endsTorn(file) ? '\n' : ''}${JSON.stringify(row)}\n`, options);
29
+ }
package/src/monthly.js CHANGED
@@ -23,7 +23,7 @@
23
23
  // resumed) counts in "to date" only and is counted in `undatedRows`. Model time is the sum of rows' `wallMs`;
24
24
  // a row without one (a draft row) adds nothing and marks that figure "at least"; none at all = null.
25
25
  import {
26
- appendFileSync, mkdirSync, readFileSync, realpathSync,
26
+ mkdirSync, readFileSync, realpathSync,
27
27
  } from 'node:fs';
28
28
  import { basename, dirname, join, resolve } from 'node:path';
29
29
  import { randomUUID } from 'node:crypto';
@@ -31,6 +31,7 @@ import { randomUUID } from 'node:crypto';
31
31
  import { readConfig, configHome, ConfigError } from './config.js';
32
32
  import { isFwdloopAlive, procStartOf } from './liveness.js';
33
33
  import { spendRowCost } from './provider.js';
34
+ import { appendRow as appendLine } from './jsonl-append.js';
34
35
  import { readDirSpendRows } from './draftspend.js';
35
36
 
36
37
  export { ConfigError };
@@ -56,7 +57,7 @@ export function realpathLoose(p) {
56
57
 
57
58
  function appendRow(home, row) {
58
59
  mkdirSync(configHome(home), { recursive: true, mode: 0o700 });
59
- appendFileSync(runsPath(home), `${JSON.stringify(row)}\n`, { mode: 0o600 });
60
+ appendLine(runsPath(home), row, { mode: 0o600 });
60
61
  }
61
62
 
62
63
  /** @param {string} [home] @returns {any[]} every well-formed row in file order (a torn line is skipped) */