fwdloop 0.23.0 → 0.25.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 (71) hide show
  1. package/bin/fwdloop +62 -32
  2. package/package.json +1 -1
  3. package/src/ask.js +15 -1
  4. package/src/attemptdiff.js +118 -0
  5. package/src/audit-fold.js +2 -0
  6. package/src/authoring.js +32 -2
  7. package/src/cited-record.js +3 -22
  8. package/src/cited-source.js +5 -6
  9. package/src/citedwords.js +36 -2
  10. package/src/config.js +5 -1
  11. package/src/diary.js +21 -17
  12. package/src/drafter.js +6 -2
  13. package/src/flowmodel.js +52 -28
  14. package/src/keysfile.js +1 -1
  15. package/src/launcher.js +552 -0
  16. package/src/learn.js +952 -0
  17. package/src/learnstore.js +348 -0
  18. package/src/line-checks.js +55 -0
  19. package/src/model-step.js +2 -0
  20. package/src/opener.js +33 -0
  21. package/src/pagedry.js +3 -4
  22. package/src/pagefetch.js +9 -2
  23. package/src/pagerules.js +28 -5
  24. package/src/panel/author.js +2 -0
  25. package/src/panel/authorflows.js +9 -9
  26. package/src/panel/authorresume.js +4 -3
  27. package/src/panel/data.js +63 -14
  28. package/src/panel/index.html +162 -16
  29. package/src/panel/result.js +7 -12
  30. package/src/panel/server.js +53 -5
  31. package/src/panel/settings.js +4 -18
  32. package/src/panel/spawn.js +0 -9
  33. package/src/prompts.js +33 -0
  34. package/src/redact.js +6 -6
  35. package/src/runfile.js +60 -0
  36. package/src/runner.js +144 -33
  37. package/src/sheet-record.js +15 -35
  38. package/src/sheetblock.js +3 -3
  39. package/src/sheetrun.js +6 -6
  40. package/src/summary-words.js +13 -5
  41. package/src/thinking.js +11 -0
  42. package/src/tty-colour.js +29 -0
  43. package/types/ask.d.ts +7 -2
  44. package/types/attemptdiff.d.ts +38 -0
  45. package/types/cited-record.d.ts +0 -2
  46. package/types/citedwords.d.ts +14 -0
  47. package/types/diary.d.ts +2 -5
  48. package/types/drafter.d.ts +6 -1
  49. package/types/flowmodel.d.ts +37 -20
  50. package/types/keysfile.d.ts +7 -0
  51. package/types/launcher.d.ts +307 -0
  52. package/types/learn.d.ts +576 -0
  53. package/types/learnstore.d.ts +168 -0
  54. package/types/line-checks.d.ts +26 -0
  55. package/types/opener.d.ts +12 -0
  56. package/types/pagerules.d.ts +7 -0
  57. package/types/panel/author.d.ts +2 -0
  58. package/types/panel/data.d.ts +2 -1
  59. package/types/panel/result.d.ts +2 -4
  60. package/types/panel/server.d.ts +24 -3
  61. package/types/panel/settings.d.ts +2 -2
  62. package/types/panel/spawn.d.ts +0 -6
  63. package/types/prompts.d.ts +14 -0
  64. package/types/runfile.d.ts +48 -0
  65. package/types/runner.d.ts +14 -5
  66. package/types/sheet-record.d.ts +0 -2
  67. package/types/sheetblock.d.ts +2 -2
  68. package/types/sheetrun.d.ts +1 -1
  69. package/types/summary-words.d.ts +2 -1
  70. package/types/thinking.d.ts +11 -0
  71. package/types/tty-colour.d.ts +33 -0
package/bin/fwdloop CHANGED
@@ -32,12 +32,14 @@ import {
32
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
+ import { seedLedger } from '../src/learnstore.js';
35
36
  import { sendViaPrimitive } from '../src/send.js';
36
37
  import { resolvePrimitives } from '../src/primitives.js';
37
38
  import {
38
39
  checkKeyPreflight, resolveUsableModel, pickTicked, readPriceConfig, ceilingCostUsd,
39
40
  } from '../src/provider.js';
40
- import { readModelRecord, readRunModel } from '../src/flowmodel.js';
41
+ import { readModelRecord, readRunModel, LEARNINGS_FILE } from '../src/flowmodel.js';
42
+ import { readRunInputs } from '../src/runfile.js';
41
43
  import { configDoorHome } from '../src/config.js';
42
44
  import {
43
45
  claimHold, settleHold, nameRunDir, monthlyRefusalText, ConfigError,
@@ -47,6 +49,7 @@ import {
47
49
  answerAsk, readAskEvidence, normalizeDecision, stripControl, withReopen,
48
50
  } from '../src/ask.js';
49
51
  import { panelMain } from '../src/panel/server.js';
52
+ import { launcherMain } from '../src/launcher.js';
50
53
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
51
54
  import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
52
55
  import { userInfo } from 'node:os';
@@ -383,7 +386,7 @@ async function cmdRun(rest) {
383
386
  if (!runIdCheck.ok) fail(runIdCheck.red);
384
387
  runDir = runIdCheck.runDir;
385
388
  // 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".
386
- 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`);
389
+ if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json' && n !== TRIGGER_RECORD_FILE && n !== 'job' && n !== 'plan.json' && n !== 'setup.jsonl' && n !== LEARNINGS_FILE).length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
387
390
  }
388
391
  // 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.
389
392
  const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
@@ -573,16 +576,22 @@ function cmdShow(rest) {
573
576
  process.stdout.write(`question: ${stripControl(ask.question)}\n`);
574
577
  process.stdout.write(`expiresAt: ${ask.expiresAt}\n`);
575
578
 
576
- const { draft, unjudged, why } = readAskEvidence(ask);
577
- if (!draft) {
579
+ const {
580
+ draft, unjudged, why, results,
581
+ } = readAskEvidence(ask);
582
+ if (!draft && !results) {
578
583
  process.stdout.write(`\n(no evidence recorded on this ask — ${why})\n`);
579
584
  return;
580
585
  }
581
586
  process.stdout.write('\n--- artifact under review ---\n');
582
- process.stdout.write(`${stripControl(draft.text)}\n`);
587
+ if (draft) process.stdout.write(`${stripControl(draft.text)}\n`);
588
+ else {
589
+ // a cited step's results: each quote with its values
590
+ results.forEach((r, i) => process.stdout.write(`result ${i + 1}: ${stripControl(r.quote)}\n ${Object.entries(r.values).map(([k, v]) => `${stripControl(k)}: ${stripControl(String(v))}`).join('; ')}\n`));
591
+ }
583
592
  for (const item of unjudged) {
584
593
  process.stdout.write(`\n--- unjudged: ${stripControl(item.step)} ---\n`);
585
- process.stdout.write(`${stripControl(item.text)}\n`);
594
+ process.stdout.write(`${item.text !== undefined ? stripControl(item.text) : Object.entries(item.cells).map(([k, v]) => `${stripControl(k)}: ${stripControl(String(v))}`).join('\n')}\n`);
586
595
  }
587
596
  }
588
597
 
@@ -670,24 +679,20 @@ async function cmdResume(rest) {
670
679
  what: 'resume', flow: flowName, runId, runDir, holdUsd: Math.max(0, arbiter.capUsd - priorSpent), spentAtHold: priorSpent,
671
680
  });
672
681
 
673
- // Resume never re-freezes inputs — the run's own `inputs.json` (written at
674
- // park by `freezeInputs`) is the one source of the already-frozen paths a
682
+ // Resume never re-freezes inputs — the run's own `run.json` (its `inputs`,
683
+ // written at start by `runFlow`) is the one source of the already-frozen paths a
675
684
  // sandboxed primitive may read.
676
- // F48 round 3: routed through `readFileInside` (`src/flow.js`) — a
677
- // symlinked `inputs.json` is treated as "no manifest" (empty array) rather
678
- // than followed, which would otherwise let an outside file's content name
679
- // arbitrary "frozen" paths for the sandboxed read/grep/readDocx/
685
+ // F48 round 3: routed through `readFileInside` (`src/flow.js`, inside
686
+ // `readRunInputs`) — a symlinked `run.json` is treated as "no manifest" (empty
687
+ // array) rather than followed, which would otherwise let an outside file's
688
+ // content name arbitrary "frozen" paths for the sandboxed read/grep/readDocx/
680
689
  // addressCells tools built just below.
681
- const inputsManifestRead = readFileInside(runDir, 'inputs.json');
682
- let inputsManifest = [];
683
- if (inputsManifestRead.ok) {
684
- try {
685
- inputsManifest = JSON.parse(inputsManifestRead.text);
686
- } catch (err) {
687
- fail(`resume: inputs.json for run "${runId}" is not valid JSON — ${err.message}`);
688
- return;
689
- }
690
+ const inputsRead = readRunInputs(runDir);
691
+ if (!inputsRead.ok && inputsRead.code === 'invalid') {
692
+ fail(`resume: run "${runId}": ${inputsRead.red}`);
693
+ return;
690
694
  }
695
+ const inputsManifest = inputsRead.ok ? inputsRead.entries : [];
691
696
  const allVerbs = [...new Set(declaration.steps.flatMap((s) => s.primitives ?? []))];
692
697
  // F46's unwired-verb preflight refusal now lives in `resumeRun` itself
693
698
  // (`src/runner.js`) — this CLI no longer keeps a second copy of the check.
@@ -772,16 +777,12 @@ async function cmdContinue(rest) {
772
777
  what: 'resume', flow: flowName, runId, runDir, holdUsd: Math.max(0, applied.arbiter.capUsd - spentSoFar.total), spentAtHold: spentSoFar.total,
773
778
  });
774
779
 
775
- const inputsManifestRead = readFileInside(runDir, 'inputs.json');
776
- let inputsManifest = [];
777
- if (inputsManifestRead.ok) {
778
- try {
779
- inputsManifest = JSON.parse(inputsManifestRead.text);
780
- } catch (err) {
781
- fail(`continue: inputs.json for run "${runId}" is not valid JSON — ${err.message}`);
782
- return;
783
- }
780
+ const inputsRead = readRunInputs(runDir);
781
+ if (!inputsRead.ok && inputsRead.code === 'invalid') {
782
+ fail(`continue: run "${runId}": ${inputsRead.red}`);
783
+ return;
784
784
  }
785
+ const inputsManifest = inputsRead.ok ? inputsRead.entries : [];
785
786
  const allVerbs = [...new Set(declaration.steps.flatMap((s) => s.primitives ?? []))];
786
787
  const { tools: primitives, reds: primitiveReds } = resolvePrimitives(catalogue, allVerbs, {
787
788
  runDir, inputs: inputsManifest.map((m) => ({ id: m.id, frozen: m.frozen })),
@@ -990,11 +991,38 @@ async function cmdSign(rest) {
990
991
  process.stdout.write(`signed: ${result.flowDir} (by ${result.signature.signedBy})\n`);
991
992
  }
992
993
 
994
+ /** M8 am6: `fwdloop learn seed --root <flows folder>`: notes from every ended run already recorded ($0, code only). */
995
+ function cmdLearn(rest) {
996
+ const [sub, ...args] = rest;
997
+ if (sub !== 'seed') fail('learn: expected "seed" — fwdloop learn seed --root <flows folder>');
998
+ const { values } = parseArgs({ args, options: { root: { type: 'string' } } });
999
+ if (!values.root) fail('learn seed: --root <flows folder> is required');
1000
+ const root = resolveRoot('learn seed', values.root);
1001
+ const r = seedLedger({ root });
1002
+ if (r.skippedNoDoor) fail('learn seed: a test process has no config home (set FWDLOOP_CONFIG_HOME)');
1003
+ const k = r.skipped;
1004
+ const total = Object.values(k).reduce((a, b) => a + b, 0);
1005
+ process.stdout.write(`runs read: ${r.read}\nnotes added: ${r.added}\nruns skipped: ${total} (already in: ${k['already-in']}, still waiting: ${k['still-waiting']}, no end: ${k['no-end']}, unreadable: ${k.unreadable}, noise: ${k.noise})\n`);
1006
+ if (r.problem) fail(`learn seed: stopped, the ledger is not usable — ${r.problem}`);
1007
+ }
1008
+
993
1009
  // ---------------------------------------------------------------------------
994
1010
 
1011
+ /**
1012
+ * M4b am4/am5 (the launcher): a bare `fwdloop` shows the menu; `start | stop | restart | status | install` are its five choices as verbs. All logic is src/launcher.js.
1013
+ * `--root <flows folder>` (default '.', like `fwdloop panel`) is the folder the runs line reads and `start` hands the panel; the config home is the real ~/.config/fwdloop.
1014
+ */
1015
+ async function cmdLauncher(cmd, rest) {
1016
+ const at = rest.indexOf('--root');
1017
+ const given = at === -1 ? '.' : rest[at + 1];
1018
+ if (at !== -1 && (given === undefined || given.startsWith('--'))) fail(`${cmd}: --root needs a folder`);
1019
+ const args = at === -1 ? rest : rest.filter((_, i) => i !== at && i !== at + 1);
1020
+ process.exitCode = await launcherMain(cmd, args, { root: resolveRoot(cmd, given) });
1021
+ }
1022
+
995
1023
  async function main() {
996
1024
  const [verb, ...rest] = process.argv.slice(2);
997
- if (!verb) fail('usage: fwdloop draft|sign|run|inbox|show|answer|resume|continue|panel ...');
1025
+ if (!verb || verb === '--root') return cmdLauncher('menu', verb ? [verb, ...rest] : []);
998
1026
 
999
1027
  if (verb === 'draft') return cmdDraft(rest);
1000
1028
  if (verb === 'sign') return cmdSign(rest);
@@ -1005,7 +1033,9 @@ async function main() {
1005
1033
  if (verb === 'resume') return cmdResume(rest);
1006
1034
  if (verb === 'continue') return cmdContinue(rest);
1007
1035
  if (verb === 'panel') return cmdPanel(rest);
1008
- fail(`unknown verb "${verb}" — expected draft | sign | run | inbox | show | answer | resume | continue | panel`);
1036
+ if (verb === 'learn') return cmdLearn(rest);
1037
+ if (verb === 'start' || verb === 'stop' || verb === 'restart' || verb === 'status' || verb === 'install') return cmdLauncher(verb, rest);
1038
+ fail(`unknown verb "${verb}" — expected draft | sign | run | inbox | show | answer | resume | continue | panel | learn | start | stop | restart | status | install (or none, for the menu)`);
1009
1039
  return undefined;
1010
1040
  }
1011
1041
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/ask.js CHANGED
@@ -180,11 +180,16 @@ export function makeFileAskStep({
180
180
  // unparseable shape is a named `why`, never a crash, never silently empty.
181
181
  // ---------------------------------------------------------------------------
182
182
 
183
+ /** @param {unknown} c @returns {c is Record<string, unknown>} a non-empty plain object of cells */
184
+ const isPlainCells = (c) => !!c && typeof c === 'object' && !Array.isArray(c) && Object.keys(c).length > 0;
185
+ /** @param {unknown} r @returns {boolean} a non-empty list of `{quote: string, values: object}` */
186
+ const isResults = (r) => Array.isArray(r) && r.length > 0 && r.every((x) => x && typeof x.quote === 'string' && x.values && typeof x.values === 'object' && !Array.isArray(x.values));
187
+
183
188
  /**
184
189
  * @param {any} ask the parsed ask.json object (or its `evidence` field's
185
190
  * container — pass the whole ask so a missing `evidence` key is itself a
186
191
  * handled case, not the caller's problem).
187
- * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string, claims?: Record<string, any> }}
192
+ * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text?: string, cells?: Record<string, unknown>}>, why?: string, claims?: Record<string, any>, results?: Array<{quote: string, values: Record<string, unknown>}> }}
188
193
  */
189
194
  export function readAskEvidence(ask) {
190
195
  const evidence = ask && typeof ask === 'object' ? ask.evidence : undefined;
@@ -223,8 +228,12 @@ export function readAskEvidence(ask) {
223
228
  const step = item && (item.step ?? item.emits);
224
229
  const emits = item && typeof item.emits === 'string' ? item.emits : undefined;
225
230
  const text = item && item.artifact && typeof item.artifact.text === 'string' ? item.artifact.text : undefined;
231
+ // a step that cites quotes or reads a sheet leaves `cells` (name -> value), no text: kept as `cells`, drawn value by value
232
+ const cells = item && item.artifact && isPlainCells(item.artifact.cells) ? item.artifact.cells : undefined;
226
233
  if (typeof step === 'string' && typeof text === 'string') {
227
234
  unjudged.push(emits ? { step, emits, text } : { step, text });
235
+ } else if (typeof step === 'string' && cells !== undefined) {
236
+ unjudged.push(emits ? { step, emits, cells } : { step, cells });
228
237
  }
229
238
  // An unjudged entry with neither a nameable step nor readable text is
230
239
  // dropped rather than shown as a blank row — the draft itself is
@@ -243,6 +252,11 @@ export function readAskEvidence(ask) {
243
252
  return { draft: { text: evidence.text }, unjudged: [] };
244
253
  }
245
254
 
255
+ // A cited step's artifact is `{results: [{quote, values}]}`: handed on as `results` (the panel matches them to the run's cited-check record). Not the sheet's claim boxes.
256
+ if (evidence.artifact && typeof evidence.artifact === 'object' && isResults(evidence.artifact.results)) {
257
+ return { draft: null, unjudged: readUnjudged(), results: evidence.artifact.results };
258
+ }
259
+
246
260
  // M10b am4: a step with sheet checks answers in claim boxes, an object with no text. They are handed on as `claims` (the panel matches them to the step's checks);
247
261
  // the `why` stays, for the caller that finds no sheet step for them.
248
262
  if (evidence.artifact && typeof evidence.artifact === 'object' && !Array.isArray(evidence.artifact)) {
@@ -0,0 +1,118 @@
1
+ // borrowed-from: bareloop src/attemptdiff.js@v0.46.0 (8b3d815)
2
+ // Adaptations: redactSecrets imported from ./redact.js (fwdloop's one secret inventory) in place of bareloop's ./validate.js; the temp index dir prefix is fwdloop-adiff-. Nothing else changed.
3
+ // attempt-diff — what each worker TRY changed, as a spine record (ITEM33 addendum
4
+ // 2026-10-22). The spine and the gate audit keep only file names and byte sizes of
5
+ // edits; a learnings card could say WHICH files a passing try touched but never WHAT
6
+ // changed. This module is the ONE owner of that capture. It is a record, never a
7
+ // verdict: every failure is caught and returned as a field, nothing here throws.
8
+ //
9
+ // How: a git TREE snapshot at try start and at try end, each through a TEMPORARY
10
+ // index (GIT_INDEX_FILE + `git add -A` + `git write-tree`), then `git diff <t0> <t1>`.
11
+ // The work branch, HEAD, the real index and the stash list are never touched; the
12
+ // temp index is removed. Only unreferenced loose objects are left in the object store.
13
+
14
+ import { execFile } from 'node:child_process';
15
+ import { promisify } from 'node:util';
16
+ import { mkdtemp, rm } from 'node:fs/promises';
17
+ import { tmpdir } from 'node:os';
18
+ import { existsSync } from 'node:fs';
19
+ import { join, relative, resolve } from 'node:path';
20
+ import { redactSecrets } from './redact.js';
21
+
22
+ const exec = promisify(execFile);
23
+
24
+ /** per-file and per-event byte caps for the recorded diff text */
25
+ export const ATTEMPT_DIFF_FILE_MAX = 4096;
26
+ export const ATTEMPT_DIFF_EVENT_MAX = 16384;
27
+
28
+ /**
29
+ * Cut `text` to at most `max` bytes at a LINE boundary (never mid-line).
30
+ * @param {string} text @param {number} max
31
+ * @returns {{text: string, truncated: boolean, cutLines: number}}
32
+ */
33
+ export function cutAtLine(text, max) {
34
+ if (Buffer.byteLength(text) <= max) return { text, truncated: false, cutLines: 0 };
35
+ const lines = text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
36
+ let used = 0;
37
+ let kept = 0;
38
+ for (const l of lines) {
39
+ const b = Buffer.byteLength(l);
40
+ if (used + b > max) break;
41
+ used += b;
42
+ kept++;
43
+ }
44
+ return { text: lines.slice(0, kept).join(''), truncated: true, cutLines: lines.length - kept };
45
+ }
46
+
47
+ /** @param {string} abs @param {string[]} prefixes */
48
+ const inFence = (abs, prefixes) => prefixes.some((p) => abs === p || abs.startsWith(p.endsWith('/') ? p : `${p}/`));
49
+
50
+ // the arbiter's books and installed packages never enter a snapshot, even inside a wide fence
51
+ const NOT_WORK = [':(exclude,glob)**/node_modules/**', ':(exclude,glob)**/.git/**', ':(exclude).smoke', ':(exclude).litectx', ':(exclude)gate-audit.jsonl'];
52
+
53
+ /**
54
+ * Snapshot the FENCE of the working tree to a git tree id via a throwaway index. Only the
55
+ * fence's existing prefixes are added, and with `-f`: a rubric job's `output/` must be seen
56
+ * even when the source folder's own .gitignore lists it (the hidden-git seed ignores that
57
+ * file's meaning; so does this).
58
+ * @param {string} workdir @param {string[]} fence @returns {Promise<string>}
59
+ */
60
+ async function snapshotTree(workdir, fence) {
61
+ const tmp = await mkdtemp(join(tmpdir(), 'fwdloop-adiff-'));
62
+ try {
63
+ const env = { ...process.env, GIT_INDEX_FILE: join(tmp, 'index') };
64
+ const specs = fence.filter((p) => existsSync(p)).map((p) => `:(literal)${relative(workdir, p) || '.'}`);
65
+ if (specs.length > 0) await exec('git', ['add', '-A', '-f', '--', ...specs, ...NOT_WORK], { cwd: workdir, env, maxBuffer: 1 << 26 });
66
+ const { stdout } = await exec('git', ['write-tree'], { cwd: workdir, env });
67
+ return stdout.trim();
68
+ } finally {
69
+ await rm(tmp, { recursive: true, force: true });
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Begin recording one worker try. Call BEFORE the worker's turn; call `finish()` after
75
+ * (in a `finally`). Never throws.
76
+ * @param {{workdir: string, fence: string[], redact?: (s: string) => string}} o
77
+ * `fence` = the ABSOLUTE write-scope prefixes the gate enforces for this try.
78
+ * @returns {Promise<{finish: () => Promise<null | {files: {path: string, diff: string, truncated: boolean, cutLines: number}[], binary: string[], truncated: boolean, gitError?: string}>}>}
79
+ * `finish()` resolves null when the try changed nothing in scope.
80
+ */
81
+ export async function startAttemptDiff({ workdir, fence, redact = redactSecrets }) {
82
+ /** @type {string|null} */
83
+ let t0 = null;
84
+ /** @type {string|null} */
85
+ let startError = null;
86
+ try { t0 = await snapshotTree(workdir, fence); } catch (e) { startError = String(/** @type {any} */ (e)?.message ?? e); }
87
+ return {
88
+ async finish() {
89
+ try {
90
+ if (t0 === null) throw new Error(`start snapshot failed: ${startError}`);
91
+ const t1 = await snapshotTree(workdir, fence);
92
+ if (t1 === t0) return null;
93
+ const g = (/** @type {string[]} */ a) => exec('git', ['-c', 'core.quotepath=false', ...a], { cwd: workdir, maxBuffer: 1 << 26 });
94
+ const { stdout: names } = await g(['diff', '--name-only', '-z', '--relative', /** @type {string} */ (t0), t1]);
95
+ const paths = names.split('\0').filter(Boolean).filter((p) => inFence(resolve(workdir, p), fence));
96
+ /** @type {{path: string, diff: string, truncated: boolean, cutLines: number}[]} */
97
+ const files = [];
98
+ /** @type {string[]} */
99
+ const binary = [];
100
+ let left = ATTEMPT_DIFF_EVENT_MAX;
101
+ let anyCut = false;
102
+ for (const p of paths) {
103
+ const { stdout } = await g(['diff', '-U1', '--no-color', '--no-ext-diff', '--relative', /** @type {string} */ (t0), t1, '--', `:(literal)${p}`]);
104
+ const path = redact(p);
105
+ if (/^Binary files .* differ$/m.test(stdout) || /^GIT binary patch$/m.test(stdout)) { binary.push(path); continue; }
106
+ const cut = cutAtLine(redact(stdout), Math.min(ATTEMPT_DIFF_FILE_MAX, left));
107
+ left -= Buffer.byteLength(cut.text);
108
+ if (cut.truncated) anyCut = true;
109
+ files.push({ path, diff: cut.text, truncated: cut.truncated, cutLines: cut.cutLines });
110
+ }
111
+ if (files.length === 0 && binary.length === 0) return null;
112
+ return { files, binary, truncated: anyCut };
113
+ } catch (e) {
114
+ return { files: [], binary: [], truncated: false, gitError: redact(String(/** @type {any} */ (e)?.message ?? e)).slice(0, 500) };
115
+ }
116
+ },
117
+ };
118
+ }
package/src/audit-fold.js CHANGED
@@ -114,6 +114,8 @@ export function deriveFold(group, d, info = {}) {
114
114
  const rec = saved.length === alike ? saved[k] : null;
115
115
  tries.push({
116
116
  n: r.attempt, mark: group.tryMarks[i] ?? '·', thinking: r.thinkingPhrase ?? null, gap: r.gap || null, answer: null, about: null, checks: rec?.checks ?? [], output: rec?.output ?? null,
117
+ // M8 am7 item 4: the exact text this try was handed, from its own audit row (`hints` count + `hintsText`); null (no line) when nothing was handed
118
+ hints: typeof r.hintsText === 'string' && r.hintsText !== '' && Number.isInteger(r.hints) ? { n: r.hints, text: r.hintsText } : null,
117
119
  });
118
120
  });
119
121
  // rounds count on through all of a step's tries, so they order the calls and tool calls; a try's check row goes after the last round it saw
package/src/authoring.js CHANGED
@@ -32,7 +32,10 @@ import { jobKeyOfSigned } from './jobkey.js';
32
32
  import { checkSendDestination } from './runner.js';
33
33
  import { checkKeyPreflight, appendSpendRow } from './provider.js';
34
34
  import { keyValues } from './keysfile.js';
35
- import { readModelRecord, writeModelRecord } from './flowmodel.js';
35
+ import { readModelRecord, writeModelRecord, writeLearningsRecord, writeLearningsError, copyLearningsRecord } from './flowmodel.js';
36
+ import { configDoorHome } from './config.js';
37
+ import { hintsForRun, placeSpecOf } from './learnstore.js';
38
+ import { redactSecrets } from './redact.js';
36
39
  import { sessionPriorSpend, writeDraftSpend } from './draftspend.js';
37
40
  import { writeSetup } from './setup.js';
38
41
 
@@ -333,13 +336,36 @@ export async function draftToDir({
333
336
  };
334
337
  // M4d am16: a panel draft folder (card.json beside this plan folder) is one job's session: what its earlier plans spent comes off the cap first.
335
338
  const priorSpend = sessionPriorSpend(dir);
339
+ // M8 item 5a: the earlier runs' notes for this draft, made once from the ledger as it stood and handed to every round of it. A record read,
340
+ // never a verdict: any failure hands nothing and rides learnings.json (`error`) below, never a failed draft.
341
+ /** @type {{text: string, ids: string[]}|null} */
342
+ let learnHints = null;
343
+ let hintError = null;
344
+ const door = configDoorHome();
345
+ if (!door.skip) {
346
+ try {
347
+ // a draft is made before any run: it has no run input (`fwdloop draft` takes none), so the first source is the signed prose path, the only file it can know (M8 am8)
348
+ const first = parseSignedText(prose.text);
349
+ learnHints = hintsForRun({ home: door.home, spec: placeSpecOf(name, first.ok ? first.arbiter.sources?.[0]?.path : null), specHash: null });
350
+ } catch (/** @type {any} */ e) {
351
+ learnHints = null;
352
+ hintError = redactSecrets(String(e?.message ?? e)).split('\n')[0];
353
+ }
354
+ }
336
355
  const result = await draft({
337
- proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, ...(leftRules === undefined ? {} : { leftRules }),
356
+ proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, learnHints, ...(leftRules === undefined ? {} : { leftRules }),
338
357
  });
339
358
  if (result.stop === 'pre-flight') {
340
359
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
341
360
  return refuse(cleanReds(result.reds));
342
361
  }
362
+ // M8 item 5a: what was handed is kept once beside the draft (only when a round was actually sent with it); a failure is recorded, never raised.
363
+ try {
364
+ if (hintError === null && learnHints !== null && result.calls > 0) writeLearningsRecord(dir, learnHints);
365
+ } catch (/** @type {any} */ e) { hintError = redactSecrets(String(e?.message ?? e)).split('\n')[0]; }
366
+ if (hintError !== null) {
367
+ try { writeLearningsError(dir, hintError); } catch { /* the record of the failure is itself best-effort */ }
368
+ }
343
369
 
344
370
  // After a paid round: never a silent throw. The cost is returned so the caller prints it; the dir is claimed and stays.
345
371
  const paidFail = (red) => ({
@@ -500,6 +526,8 @@ export function signDraft({
500
526
  const runSetup = writeSetup({
501
527
  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)),
502
528
  });
529
+ // M8 item 6: what this draft was handed goes into the NEW RUN's folder (the Audit box reads it there); a failure never un-signs
530
+ try { copyLearningsRecord(dir, ran.runDir); } catch { /* the box is then hidden; the plan is signed */ }
503
531
  // 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`)
504
532
  return {
505
533
  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),
@@ -521,5 +549,7 @@ export function signDraft({
521
549
  if (pickRecord !== null) {
522
550
  try { writeModelRecord(written.dir, pickRecord); } catch (e) { modelRecord = { ok: false, recorded: false, why: /** @type {any} */ (e)?.code ?? 'error' }; }
523
551
  }
552
+ // M8 item 6: beside the flow's setup record; the first run that starts from this flow takes it (runner.js), so only that run shows the box. A failure never un-signs.
553
+ try { copyLearningsRecord(dir, written.dir); } catch { /* the box is then hidden; the flow is signed */ }
524
554
  return { ok: true, flowDir: written.dir, signature: written.signature, setup, modelRecord };
525
555
  }
@@ -1,5 +1,5 @@
1
1
  // borrowed-from: bareloop src/panel/server.js@2959217 (proofOf, moneyAsRead, resultCell - the row a Result tab shows, read off bareguard's evidence)
2
- // M10 piece 4: the ONE writer of `<run>/cited-checks.json`, the record the Result tab's reader (`readCitedChecks`, src/panel/result.js) takes. One line per
2
+ // M10 piece 4 / M8b item 3: the writer of the `cited` section of `<run>/line-checks.json` (the file's one writer is `writeLineSection`, src/line-checks.js), the record the Result tab's reader (`readCitedChecks`, src/panel/result.js) takes. One line per
3
3
  // job line, written the moment that line's cited check has run, from the check's own answer: nothing here decides a verdict.
4
4
  //
5
5
  // Shape (the reader's, copied from bareloop): { lines: [ { n, source, passed, facts: [{name, kind: 'phrase'|'value', sentence}],
@@ -7,15 +7,10 @@
7
7
  // Extra keys the reader ignores and the separate checker (scripts/check-cited-run.mjs) reads: per line `check` {sha256 of the frozen text, the signed facts,
8
8
  // the count} and per row `values`.
9
9
  // Throws away: bareguard's evidence beyond the marks of the claim's own spans; nothing: a red line keeps its judged rows (am9); only a stopped check has none.
10
- import { writeFileSync, renameSync } from 'node:fs';
11
- import { join } from 'node:path';
12
- import { readFileInside } from './flow.js';
10
+ import { writeLineSection } from './line-checks.js';
13
11
  import { moneyAs } from './pageask.js';
14
12
  import { factSentence, countSentence, CITED_ID } from './citedcheck.js';
15
13
 
16
- /** the record's name in the run's own folder; the Result tab's reader takes it from here */
17
- export const CITED_CHECKS_FILE = 'cited-checks.json';
18
-
19
14
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
20
15
 
21
16
  /**
@@ -120,19 +115,5 @@ export function citedLineOf({
120
115
  * @param {string} runDir @param {Record<string, any>} line @returns {void}
121
116
  */
122
117
  export function writeCitedLine(runDir, line) {
123
- const file = join(runDir, CITED_CHECKS_FILE);
124
- /** @type {Record<string, any>[]} */
125
- let lines = [];
126
- const had = readFileInside(runDir, CITED_CHECKS_FILE);
127
- if (had.ok) {
128
- try {
129
- const rec = JSON.parse(had.text);
130
- if (rec && Array.isArray(rec.lines)) lines = rec.lines.filter((/** @type {any} */ l) => isRec(l) && l.n !== line.n);
131
- } catch { lines = []; }
132
- }
133
- lines.push(line);
134
- lines.sort((a, b) => a.n - b.n);
135
- const tmp = `${file}.tmp`;
136
- writeFileSync(tmp, `${JSON.stringify({ lines }, null, 2)}\n`);
137
- renameSync(tmp, file);
118
+ writeLineSection(runDir, 'cited', (had) => [...had.filter((/** @type {any} */ l) => isRec(l) && l.n !== line.n), line].sort((a, b) => a.n - b.n));
138
119
  }
@@ -1,5 +1,5 @@
1
1
  // M10 piece 4: the text a cited check reads - THE RUN'S OWN frozen copy of a web page or a text/markdown doc (`<run>/inputs/<file>`, written at run start by
2
- // `freezeInputs`), checked against the sha256 `inputs.json` recorded when it was frozen. The drafting copy lives in the draft folder and is never read here.
2
+ // `freezeInputs`), checked against the sha256 `run.json` (its `inputs`) recorded when it was frozen. The drafting copy lives in the draft folder and is never read here.
3
3
  // Same three outcomes as the CSV reader (`readInputCells`): not a text input of this run, a refusal that names why, or the text.
4
4
  // A .docx input (M10 piece 5, item 2 "a quote in a doc") is served as its paragraph text (src/docx.js says what that throws away), its sha256 taken over the file's BYTES from the same
5
5
  // read the text comes from. Throws away: nothing for a page or a text file. A .csv input is not served here (it is read as cells).
@@ -8,6 +8,7 @@
8
8
  import { createHash } from 'node:crypto';
9
9
  import { basename } from 'node:path';
10
10
  import { readFileInside, resolveInside } from './flow.js';
11
+ import { readRunInputs } from './runfile.js';
11
12
  import { readDocxSource } from './docx.js';
12
13
 
13
14
  /** the frozen files served as text: a saved page (.txt) or a text/markdown document. Any other kind (a spreadsheet, a .docx, a binary) is never served as text. */
@@ -20,11 +21,9 @@ const TEXT_EXTS = Object.freeze(['.txt', '.md', '.markdown']);
20
21
  * @returns {{ok: true, text: string, sha256: string, frozen: string}|{ok: false, red: string, code: 'no-manifest'|'not-an-input'|'not-text'|'unreadable'}}
21
22
  */
22
23
  export function readRunSource(runDir, role, { docx = false } = {}) {
23
- const manifest = readFileInside(runDir, 'inputs.json');
24
- if (!manifest.ok) return { ok: false, code: manifest.missing ? 'no-manifest' : 'unreadable', red: manifest.missing ? `input "${role}": this run has no frozen inputs` : `input "${role}": ${manifest.red}` };
25
- let entries;
26
- try { entries = JSON.parse(manifest.text); } catch (err) { return { ok: false, code: 'unreadable', red: `input "${role}": inputs.json is not valid JSON — ${err.message}` }; }
27
- const entry = Array.isArray(entries) ? entries.find((e) => e?.id === role) : undefined;
24
+ const manifest = readRunInputs(runDir);
25
+ if (!manifest.ok) return { ok: false, code: manifest.code === 'missing' ? 'no-manifest' : 'unreadable', red: manifest.code === 'missing' ? `input "${role}": this run has no frozen inputs` : `input "${role}": ${manifest.red}` };
26
+ const entry = manifest.entries.find((e) => e?.id === role);
28
27
  if (!entry || typeof entry.frozen !== 'string' || typeof entry.sha256 !== 'string') return { ok: false, code: 'not-an-input', red: `input "${role}": this run froze no input with that name` };
29
28
  const lower = entry.frozen.toLowerCase();
30
29
  if (docx && lower.endsWith('.docx')) return readRunDocx(runDir, role, entry);
package/src/citedwords.js CHANGED
@@ -9,7 +9,9 @@
9
9
  // Pure: no I/O, no model. Compared white-space blind. Third outcome, named: a source with no page-read (md text, a page the look never read) is a red
10
10
  // `unread` - a check whose words were never proved against the source is never signed. What this throws away: nothing; every red is a sentence.
11
11
 
12
- import { asList, countExact, countPhrase, normLabel, wordsSaidOn } from './pagebits.js';
12
+ import { asList, boundInWords, countExact, countPhrase, normLabel, wordsSaidOn } from './pagebits.js';
13
+ import { validReading } from './pagerules.js';
14
+ import { ruleWords } from './pageask.js';
13
15
  import { dropSentence } from './pagedropwords.js';
14
16
  import { factsOfLook } from './citedcheck.js';
15
17
 
@@ -181,6 +183,38 @@ export function placeReds({ part, line, look }) {
181
183
  return reds;
182
184
  }
183
185
 
186
+ /**
187
+ * A limit the page look read from a guardrail ("under $40" -> price under 40, `reading` on a kept fact, src/pagerules.js) must be carried by a fact of the part,
188
+ * with the same kind, op and bound. A plan that leaves it out would pass a result the guardrail forbids ($48 under "under $40"). Only a reading code accepts
189
+ * (validReading) whose bounds are in the person's own words on the line is demanded; a bound that is not said gets its ask (src/pageask.js), never a refusal.
190
+ * @param {{part: any, line: number, jobLine: any, look: {facts?: any[]}|null|undefined}} o @returns {WordRed[]}
191
+ */
192
+ export function boundReds({
193
+ part, line, jobLine, look,
194
+ }) {
195
+ /** @type {WordRed[]} */
196
+ const reds = [];
197
+ const said = wordsSaidOn(jobLine);
198
+ const facts = Array.isArray(part.facts) ? part.facts : [];
199
+ const seen = new Set();
200
+ for (const k of Array.isArray(look?.facts) ? look.facts : []) {
201
+ if (k.line !== line || k.source !== part.source || !k.reading || !validReading(k.shape, k.reading)) continue;
202
+ const r = k.reading;
203
+ const bounds = r.op === 'between' ? [r.lo, r.hi] : [r.value];
204
+ const key = JSON.stringify([k.shape, r]);
205
+ if (seen.has(key) || !bounds.every((b) => boundInWords(b, said))) continue;
206
+ seen.add(key);
207
+ const has = facts.some((/** @type {any} */ f) => f.shape === k.shape && f.rule && f.rule.op === r.op && f.rule.value === r.value && f.rule.lo === r.lo && f.rule.hi === r.hi);
208
+ if (has) continue;
209
+ const words = ruleWords({ shape: k.shape, unit: k.unit, currency: k.currency, rule: r });
210
+ reds.push({
211
+ code: 'bound-missing',
212
+ detail: `line ${line}: your words on line ${line} set a limit, ${k.name} ${words}, but no ${k.shape} fact of this check carries it. Add "rule": ${JSON.stringify(r)} to the ${k.shape} fact that reads ${k.name}, or a quote over the limit would pass.`,
213
+ });
214
+ }
215
+ return reds;
216
+ }
217
+
184
218
  /**
185
219
  * Every word red for one cited part, in the order a person fixes them.
186
220
  * @param {{part: any, text: string|undefined, line: number, jobLine: any, look: {facts?: any[], dropped?: any[]}|null|undefined, doc?: boolean}} o @returns {WordRed[]}
@@ -193,5 +227,5 @@ export function citedWordReds({
193
227
  if (typeof text !== 'string' || kept === null) {
194
228
  return [{ code: 'unread', detail: `line ${line}: the input "${part.source}" was not read here to prove the words against it, so a check on it cannot be drafted. A check on quotes works on a saved web page.` }];
195
229
  }
196
- return [...factWordReds({ part, text, line, kept }), ...numberRuleReds({ part, jobLine }), ...countReds({ part, jobLine }), ...placeReds({ part, line, look })];
230
+ return [...factWordReds({ part, text, line, kept }), ...numberRuleReds({ part, jobLine }), ...countReds({ part, jobLine }), ...placeReds({ part, line, look }), ...boundReds({ part, line, jobLine, look })];
197
231
  }
package/src/config.js CHANGED
@@ -5,7 +5,8 @@
5
5
  // { "monthlyLimitUsd": <number > 0>, // absent = no limit (piece 3 reads it)
6
6
  // "prices": { "<slot>": { "inPerM": n, "cachedInPerM": n, "outPerM": n } }, // USD per 1M tokens, each optional; a saved "cachedInPerM" is tolerated, never read (M4d amendment 2)
7
7
  // "providers": { "<KEY_NAME>": { "shape": "<shape id>", "baseUrl": "http(s)://…", "legacyMaxTokens": true|false } }, // each optional; a row is a key name from the keys file (M4d amendment 6). An older file's "model" is tolerated and read by nothing.
8
- // "models": { "<KEY_NAME>": [ { "model": "<id>", "use": true|false, "inPerM": n, "outPerM": n } ] } } // M4d amendment 3 C: a price per model
8
+ // "models": { "<KEY_NAME>": [ { "model": "<id>", "use": true|false, "inPerM": n, "outPerM": n } ] }, // M4d amendment 3 C: a price per model
9
+ // "learningHints": true|false } // M8 am1: absent = false; the drafter is handed earlier runs' notes only when true (src/learnstore.js learningHintsOn). No control on the Settings page.
9
10
  // A models line's price is a PAIR or nothing (`modelsProblem` is the one rule): 0 / 0 typed is a chosen price, a
10
11
  // ticked line needs both, a half pair is refused. A slot with no list is migrated on READ (`effectiveModels` in
11
12
  // src/provider.js); the file is only rewritten when the person saves.
@@ -173,6 +174,9 @@ function validateDoc(doc) {
173
174
  if (doc.monthlyLimitUsd !== undefined && !isPrice(doc.monthlyLimitUsd)) {
174
175
  throw new ConfigError('monthlyLimitUsd must be a number above 0 (remove the limit to have none)');
175
176
  }
177
+ if (doc.learningHints !== undefined && typeof doc.learningHints !== 'boolean') {
178
+ throw new ConfigError('learningHints must be true or false');
179
+ }
176
180
  validateProviders(doc.providers);
177
181
  validateModels(doc.models);
178
182
  if (doc.prices === undefined) return;