fwdloop 0.19.1 → 0.21.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 (68) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +22 -13
  3. package/package.json +1 -1
  4. package/src/audit-fold.js +177 -0
  5. package/src/authoring.js +24 -4
  6. package/src/books.js +4 -3
  7. package/src/closers.js +49 -2
  8. package/src/ctx-tools.js +1 -1
  9. package/src/diary.js +49 -0
  10. package/src/flow.js +218 -2
  11. package/src/flowmodel.js +42 -5
  12. package/src/jobkey.js +25 -0
  13. package/src/jsonl-append.js +29 -0
  14. package/src/model-step.js +103 -5
  15. package/src/monthly.js +3 -2
  16. package/src/panel/author.js +44 -18
  17. package/src/panel/authorcard.js +7 -13
  18. package/src/panel/authorflows.js +118 -24
  19. package/src/panel/authorresume.js +8 -4
  20. package/src/panel/authorstart.js +63 -18
  21. package/src/panel/authortrigger.js +250 -125
  22. package/src/panel/authorvalues.js +13 -2
  23. package/src/panel/data.js +279 -43
  24. package/src/panel/index.html +547 -150
  25. package/src/panel/needsyou.js +29 -0
  26. package/src/panel/scheduler.js +21 -22
  27. package/src/panel/server.js +30 -6
  28. package/src/primitives.js +44 -2
  29. package/src/provider.js +3 -2
  30. package/src/runner.js +58 -22
  31. package/src/runvalues.js +10 -2
  32. package/src/schedule.js +135 -0
  33. package/src/setup.js +0 -21
  34. package/src/summary-words.js +180 -7
  35. package/src/thinking.js +39 -0
  36. package/src/trigger-clock.js +18 -16
  37. package/src/trigger-files.js +37 -24
  38. package/src/trigger-line.js +6 -15
  39. package/src/try-checks.js +62 -0
  40. package/src/types.js +2 -1
  41. package/types/audit-fold.d.ts +54 -0
  42. package/types/authoring.d.ts +33 -2
  43. package/types/books.d.ts +17 -0
  44. package/types/ctx-tools.d.ts +1 -0
  45. package/types/diary.d.ts +57 -0
  46. package/types/flow.d.ts +106 -0
  47. package/types/flowmodel.d.ts +25 -3
  48. package/types/jobkey.d.ts +11 -0
  49. package/types/jsonl-append.d.ts +6 -0
  50. package/types/model-step.d.ts +4 -1
  51. package/types/panel/author.d.ts +47 -17
  52. package/types/panel/authorcard.d.ts +3 -6
  53. package/types/panel/authorflows.d.ts +38 -10
  54. package/types/panel/authorstart.d.ts +15 -2
  55. package/types/panel/authortrigger.d.ts +73 -41
  56. package/types/panel/authorvalues.d.ts +6 -0
  57. package/types/panel/data.d.ts +101 -19
  58. package/types/panel/needsyou.d.ts +20 -0
  59. package/types/runvalues.d.ts +5 -0
  60. package/types/schedule.d.ts +69 -0
  61. package/types/setup.d.ts +0 -19
  62. package/types/summary-words.d.ts +105 -2
  63. package/types/thinking.d.ts +31 -0
  64. package/types/trigger-clock.d.ts +8 -7
  65. package/types/trigger-files.d.ts +17 -10
  66. package/types/trigger-line.d.ts +16 -8
  67. package/types/try-checks.d.ts +55 -0
  68. package/types/types.d.ts +10 -1
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/flowmodel.js CHANGED
@@ -11,20 +11,57 @@ export const MODEL_FILE = 'model.json';
11
11
 
12
12
  /**
13
13
  * @param {string} dir a draft folder or a flow folder
14
- * @returns {{ slot: string, model: string }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
14
+ * M4d am25: `thinking: true` is the Chat "Thinking on" box as it was when the job was signed; the key is absent when the box was off.
15
+ * @returns {{ slot: string, model: string, thinking?: true }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
15
16
  */
16
17
  export function readModelRecord(dir) {
17
18
  const r = readFileInside(dir, MODEL_FILE);
18
19
  if (!r.ok) return null;
19
20
  try {
20
21
  const j = JSON.parse(r.text);
21
- return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model } : null;
22
+ return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model, ...(j.thinking === true ? { thinking: true } : {}) } : null;
22
23
  } catch { return null; }
23
24
  }
24
25
 
25
26
  /**
26
- * Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string }} pick
27
+ * Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string, thinking?: boolean }} pick
27
28
  */
28
- export function writeModelRecord(dir, { slot, model }) {
29
- writeFileSync(join(dir, MODEL_FILE), `${JSON.stringify({ slot, model }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
29
+ export function writeModelRecord(dir, { slot, model, thinking }) {
30
+ writeOnce(join(dir, MODEL_FILE), { slot, model, ...(thinking === true ? { thinking: true } : {}) });
31
+ }
32
+
33
+ /** The one file write of this module: JSON, 0600, never over an existing file. */
34
+ function writeOnce(file, obj) {
35
+ writeFileSync(file, `${JSON.stringify(obj, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
36
+ }
37
+
38
+ /** M4d am25: the file in a run's folder that keeps the box as the run started with it (outside `job/`, which holds the three signed files only). */
39
+ export const RUN_THINKING_FILE = 'thinking.json';
40
+
41
+ /**
42
+ * M4d am25: the ONE reader of the job's "Thinking on" box for a run. A run reads its OWN record (`<run>/thinking.json`, written once when the run
43
+ * started) when it has one; otherwise the flow folder's `model.json`. No record, an unreadable one, or one without `thinking` is box OFF: a job
44
+ * signed before am25 stored nothing, and it must not start thinking on every try.
45
+ * @param {string} flowDir @param {string|null} runDir @returns {boolean}
46
+ */
47
+ export function readJobThinking(flowDir, runDir) {
48
+ return readRunThinking(runDir) ?? (readModelRecord(flowDir)?.thinking === true);
49
+ }
50
+
51
+ /**
52
+ * M4d am26: the run's OWN record of the box (`<run>/thinking.json`) and nothing else: `true`/`false`, or `null` when the run has none (a run from before am25).
53
+ * An unreadable record is box off, as `readJobThinking` has always read it. @param {string|null} runDir @returns {boolean|null}
54
+ */
55
+ export function readRunThinking(runDir) {
56
+ const own = typeof runDir === 'string' ? readFileInside(runDir, RUN_THINKING_FILE) : null;
57
+ if (!own?.ok) return null;
58
+ try { return JSON.parse(own.text)?.thinking === true; } catch { return false; }
59
+ }
60
+
61
+ /**
62
+ * M4d am25: a run keeps the box as the job had it when the run started (write-once, so an Edit of the job never changes a run already going).
63
+ * Written for every fresh run, ticked or not. @param {string} flowDir @param {string} runDir
64
+ */
65
+ export function writeRunThinking(flowDir, runDir) {
66
+ writeOnce(join(runDir, RUN_THINKING_FILE), { thinking: readModelRecord(flowDir)?.thinking === true });
30
67
  }
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/model-step.js CHANGED
@@ -24,9 +24,12 @@
24
24
  // (green/softgreen/anything else) — never from the step's `shape` — the
25
25
  // executor context (M2 scope item 3) carries neither.
26
26
 
27
+ import { dirname } from 'node:path';
27
28
  import { Loop, HaltError } from 'bare-agent';
28
29
  import { GateRefusal } from './primitives.js';
30
+ import { appendCall, appendTool, nextRound } from './diary.js';
29
31
  import { ConfigError } from './config.js';
32
+ import { worstThinkingStatus } from './thinking.js';
30
33
 
31
34
  import {
32
35
  makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
@@ -173,7 +176,7 @@ function addMeter(cumulative, metered) {
173
176
  // faulted — caught live: `toolFields` threw on `cumulative.ungranted`
174
177
  // being undefined the very first time a transport fault hit round 1.
175
178
  return {
176
- costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused,
179
+ costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused, thinking: cumulative.thinking,
177
180
  };
178
181
  }
179
182
 
@@ -223,6 +226,7 @@ function toolFields(cumulative) {
223
226
  // M4e amendment 7 item 8: model calls (turns) this attempt made, so a Stop can say "after turn T of try K".
224
227
  turns: cumulative.rounds,
225
228
  tools: cumulative.tools,
229
+ thinking: cumulative.thinking,
226
230
  // Gate refusals this attempt — always present (empty array when none) so
227
231
  // absence can never be confused with "none".
228
232
  refused: cumulative.refused,
@@ -230,6 +234,42 @@ function toolFields(cumulative) {
230
234
  };
231
235
  }
232
236
 
237
+ /**
238
+ * M4d am29 item 1: the thinking status of ONE provider result, read the way bare-agent's Loop reads it for the whole run (`thinkingStatus`; a custom
239
+ * provider's legacy `thinkingApplied` true/false/null maps to applied/ignored/unknown); `null` when the result carried neither.
240
+ * @param {any} r
241
+ */
242
+ function thinkingStatusOf(r) {
243
+ if (typeof r?.thinkingStatus === 'string') return r.thinkingStatus;
244
+ if (r?.thinkingApplied === true) return 'applied';
245
+ if (r?.thinkingApplied === false) return 'ignored';
246
+ if (r?.thinkingApplied === null) return 'unknown';
247
+ return null;
248
+ }
249
+
250
+ /**
251
+ * The provider with one addition: each `generate` result is handed to `seen` before the Loop meters that call, so the call's diary row can say what bare-agent
252
+ * reported for THAT call (thinking status, the tool names it asked for); the Loop's own `onLlmResult` payload carries neither. Everything else reads through.
253
+ * @param {any} provider @param {(result: any) => void} seen
254
+ */
255
+ function watchCalls(provider, seen) {
256
+ const watched = Object.create(provider);
257
+ watched.generate = async (...a) => {
258
+ const r = await provider.generate(...a);
259
+ seen(r);
260
+ return r;
261
+ };
262
+ return watched;
263
+ }
264
+
265
+ /** The path a tool call's diary row names: the path it was given, else the frozen input role, else the stash key. Never a query, a text or a symbol. @param {any} args */
266
+ function toolRowPath(args) {
267
+ if (typeof args?.path === 'string') return args.path;
268
+ if (typeof args?.role === 'string') return args.role;
269
+ if (typeof args?.id === 'string') return `stash: ${args.id}`;
270
+ return null;
271
+ }
272
+
233
273
  const STOP_RULE = 'stop-requested';
234
274
 
235
275
  /** The attempt result for a Stop that landed mid-attempt: every call made is already summed into `cumulative`. */
@@ -248,7 +288,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
248
288
  * @param {{in:number,out:number}} [opts.rates]
249
289
  * @param {string} [opts.modelId]
250
290
  * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
251
- * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
291
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
252
292
  */
253
293
  export function makeLiveModelStep({
254
294
  slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
@@ -285,7 +325,12 @@ export function makeLiveModelStep({
285
325
  }
286
326
  }
287
327
 
328
+ // M4d am29: the three diaries live in the run's own folder, beside spend.jsonl; a row names its step and try from the runner's `stepMeta`
329
+ const runDir = dirname(spendPath);
330
+ const diaryStep = stepMeta.step ?? null;
331
+ const diaryTry = typeof stepMeta.attempt === 'number' ? stepMeta.attempt : null;
288
332
  const toolSchema = buildEmitArtifactSchema(stepMeta.class);
333
+ const thinkingMode = stepMeta.thinkingMode === 'on' || stepMeta.thinkingMode === 'off' ? stepMeta.thinkingMode : null;
289
334
  const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
290
335
  + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
291
336
  + 'reads you were handed or the tools you were granted — never invent a figure.';
@@ -303,12 +348,32 @@ export function makeLiveModelStep({
303
348
  // wrapped so a typed GateRefusal is recorded, then rethrown unchanged so
304
349
  // the model still sees the refusal as its tool result.
305
350
  const refused = /** @type {Array<{verb:string, path:string, rule:string}>} */ ([]);
351
+ // M4d am29 item 1: every call a granted tool takes also gets its diary row - the guard's decision (`allow`, the `deny` and its rule, or `no check` for a
352
+ // call that never reached the gate) - written whether the call worked or not. `round` is the model call that asked for it (set by onLlmResult below).
353
+ let currentRound = 0;
306
354
  const primitiveTools = Object.values(grantedTools ?? {}).filter(Boolean).map((tool) => ({
307
355
  ...tool,
308
356
  execute: async (...a) => {
357
+ const askedBefore = tool.gateSeen?.n ?? 0;
358
+ /** @type {GateRefusal|null} */
359
+ let refusal = null;
309
360
  try { return await tool.execute(...a); } catch (err) {
310
- if (err instanceof GateRefusal) refused.push({ verb: err.verb, path: err.path, rule: err.rule });
361
+ if (err instanceof GateRefusal) {
362
+ refusal = err;
363
+ refused.push({ verb: err.verb, path: err.path, rule: err.rule });
364
+ }
311
365
  throw err;
366
+ } finally {
367
+ appendTool(runDir, {
368
+ step: diaryStep,
369
+ try: diaryTry,
370
+ round: currentRound,
371
+ at: new Date().toISOString(),
372
+ tool: tool.name,
373
+ path: toolRowPath(a[0]),
374
+ decision: refusal ? 'deny' : ((tool.gateSeen?.n ?? 0) > askedBefore ? 'allow' : 'no check'),
375
+ rule: refusal ? refusal.rule : null,
376
+ });
312
377
  }
313
378
  },
314
379
  }));
@@ -329,6 +394,9 @@ export function makeLiveModelStep({
329
394
  tools: /** @type {Record<string, number>} */ ({}),
330
395
  ungranted: /** @type {string[]} */ ([]),
331
396
  refused,
397
+ // M4d am25 item 4: what this attempt asked of thinking (the runner's decision, `stepMeta.thinkingMode`; null = it asked nothing) and the WORST status
398
+ // bareagent reported across its rounds (null = none reported). The ONE place this record is built; `toolFields` hands it to every return.
399
+ thinking: /** @type {{asked: string|null, status: string|null}} */ ({ asked: thinkingMode ?? null, status: null }),
332
400
  };
333
401
  let noToolCallStreak = 0;
334
402
 
@@ -342,17 +410,46 @@ export function makeLiveModelStep({
342
410
  };
343
411
  const tools = [...primitiveTools, emitTool];
344
412
  const roundMeterings = [];
413
+ let lastCall = /** @type {any} */ (null);
345
414
  const stopRequested = seam?.stopRequested;
346
415
  const stopSeam = typeof stopRequested === 'function'
347
416
  ? { assemble: async (msgs) => { if (stopRequested()) throw new HaltError('stop requested', { rule: STOP_RULE }); return msgs; } }
348
417
  : {};
349
- const loop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundMeterings.push(ev); }, ...stopSeam });
418
+ // M4d am29 item 1: each model call gets its diary row the moment it is metered (round = this step's next, counted across its tries)
419
+ const onLlmResult = async (ev) => {
420
+ roundMeterings.push(ev);
421
+ currentRound = nextRound(runDir, diaryStep);
422
+ appendCall(runDir, {
423
+ step: diaryStep,
424
+ try: diaryTry,
425
+ round: currentRound,
426
+ at: new Date().toISOString(),
427
+ model: typeof ev?.model === 'string' ? ev.model : null,
428
+ costUsd: typeof ev?.costUsd === 'number' ? ev.costUsd : null, // an unpriced call stays null, never 0
429
+ tokens: ev?.usage ? { in: ev.usage.inputTokens ?? 0, out: ev.usage.outputTokens ?? 0, cache: ev.usage.cacheReadTokens ?? 0 } : null,
430
+ ms: typeof ev?.durationMs === 'number' ? ev.durationMs : null,
431
+ stopReason: typeof ev?.stopReason === 'string' ? ev.stopReason : null,
432
+ thinking: { asked: thinkingMode, status: thinkingStatusOf(lastCall) },
433
+ });
434
+ // a name the model asked for that was never offered reaches no tool (the Loop answers "Unknown tool"): it still gets its own denied row.
435
+ // A call cut at the output cap runs none of its tool calls, so it gets none.
436
+ if (ev?.stopReason !== 'max_tokens') {
437
+ for (const tc of lastCall?.toolCalls ?? []) {
438
+ if (tc?.name === 'emit_artifact' || primitiveTools.some((t) => t.name === tc?.name)) continue;
439
+ appendTool(runDir, {
440
+ step: diaryStep, try: diaryTry, round: currentRound, at: new Date().toISOString(), tool: String(tc?.name), path: null, decision: 'deny', rule: 'not granted',
441
+ });
442
+ }
443
+ }
444
+ };
445
+ const loop = new Loop({ provider: watchCalls(provider, (r) => { lastCall = r; }), rates, onLlmResult, ...stopSeam });
350
446
 
351
447
  const startedAt = Date.now();
352
448
  let result;
353
449
  try {
354
450
  // eslint-disable-next-line no-await-in-loop
355
- result = await loop.run(messages, tools, { maxTokens: 16000 });
451
+ // M4d am25: the thinking switch is the runner's decision (`stepMeta.thinkingMode`, 'on' | 'off'); bareagent sends it. Absent = send none (a caller that decides nothing).
452
+ result = await loop.run(messages, tools, { maxTokens: 16000, ...(thinkingMode ? { thinkingMode } : {}) });
356
453
  } catch (err) {
357
454
  const wallMs = Date.now() - startedAt;
358
455
  const partial = sumMeterings(roundMeterings);
@@ -419,6 +516,7 @@ export function makeLiveModelStep({
419
516
  const metered = sumMeterings(roundMeterings);
420
517
  cumulative = addMeter(cumulative, metered);
421
518
  cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
519
+ if (result.thinkingStatus !== undefined) cumulative.thinking = { asked: cumulative.thinking.asked, status: worstThinkingStatus([cumulative.thinking.status, result.thinkingStatus]) };
422
520
  appendSpendRow(spendPath, {
423
521
  provider: slot ?? null,
424
522
  price: priceRecord(prices, rates),
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) */