fwdloop 0.22.0 → 0.24.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 (63) hide show
  1. package/bin/fwdloop +31 -8
  2. package/package.json +2 -2
  3. package/src/ask.js +34 -4
  4. package/src/attemptdiff.js +118 -0
  5. package/src/audit-fold.js +2 -0
  6. package/src/authoring.js +36 -2
  7. package/src/canrun.js +5 -0
  8. package/src/checked.js +14 -3
  9. package/src/citedcheck.js +16 -1
  10. package/src/citedwords.js +36 -2
  11. package/src/closers.js +13 -223
  12. package/src/config.js +5 -1
  13. package/src/csv.js +69 -12
  14. package/src/declaration.js +64 -6
  15. package/src/drafter.js +43 -17
  16. package/src/flowmodel.js +56 -1
  17. package/src/learn.js +952 -0
  18. package/src/learnstore.js +346 -0
  19. package/src/model-step.js +15 -21
  20. package/src/pagedry.js +3 -4
  21. package/src/pagefetch.js +9 -2
  22. package/src/pagerules.js +28 -5
  23. package/src/panel/author.js +2 -1
  24. package/src/panel/authorcard.js +9 -2
  25. package/src/panel/data.js +80 -17
  26. package/src/panel/index.html +186 -12
  27. package/src/panel/result.js +6 -0
  28. package/src/redact.js +6 -6
  29. package/src/runner.js +151 -24
  30. package/src/sheet-record.js +57 -0
  31. package/src/sheetblock.js +170 -0
  32. package/src/sheetchecks.js +206 -0
  33. package/src/sheetclaims.js +78 -0
  34. package/src/sheetoffer.js +125 -0
  35. package/src/sheetrun.js +105 -0
  36. package/src/thinking.js +11 -0
  37. package/src/try-checks.js +6 -0
  38. package/src/types.js +1 -9
  39. package/types/ask.d.ts +8 -2
  40. package/types/attemptdiff.d.ts +38 -0
  41. package/types/checked.d.ts +9 -3
  42. package/types/citedwords.d.ts +14 -0
  43. package/types/closers.d.ts +6 -31
  44. package/types/csv.d.ts +25 -4
  45. package/types/declaration.d.ts +6 -1
  46. package/types/drafter.d.ts +28 -9
  47. package/types/flowmodel.d.ts +36 -0
  48. package/types/learn.d.ts +576 -0
  49. package/types/learnstore.d.ts +168 -0
  50. package/types/model-step.d.ts +19 -30
  51. package/types/pagerules.d.ts +7 -0
  52. package/types/panel/authorcard.d.ts +2 -1
  53. package/types/panel/data.d.ts +2 -1
  54. package/types/panel/result.d.ts +1 -1
  55. package/types/runner.d.ts +19 -6
  56. package/types/sheet-record.d.ts +24 -0
  57. package/types/sheetblock.d.ts +116 -0
  58. package/types/sheetchecks.d.ts +70 -0
  59. package/types/sheetclaims.d.ts +26 -0
  60. package/types/sheetoffer.d.ts +25 -0
  61. package/types/sheetrun.d.ts +35 -0
  62. package/types/thinking.d.ts +11 -0
  63. package/types/types.d.ts +16 -11
package/bin/fwdloop CHANGED
@@ -32,12 +32,13 @@ 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';
41
42
  import { configDoorHome } from '../src/config.js';
42
43
  import {
43
44
  claimHold, settleHold, nameRunDir, monthlyRefusalText, ConfigError,
@@ -383,7 +384,7 @@ async function cmdRun(rest) {
383
384
  if (!runIdCheck.ok) fail(runIdCheck.red);
384
385
  runDir = runIdCheck.runDir;
385
386
  // 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`);
387
+ 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
388
  }
388
389
  // 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
390
  const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
@@ -573,16 +574,22 @@ function cmdShow(rest) {
573
574
  process.stdout.write(`question: ${stripControl(ask.question)}\n`);
574
575
  process.stdout.write(`expiresAt: ${ask.expiresAt}\n`);
575
576
 
576
- const { draft, unjudged, why } = readAskEvidence(ask);
577
- if (!draft) {
577
+ const {
578
+ draft, unjudged, why, results,
579
+ } = readAskEvidence(ask);
580
+ if (!draft && !results) {
578
581
  process.stdout.write(`\n(no evidence recorded on this ask — ${why})\n`);
579
582
  return;
580
583
  }
581
584
  process.stdout.write('\n--- artifact under review ---\n');
582
- process.stdout.write(`${stripControl(draft.text)}\n`);
585
+ if (draft) process.stdout.write(`${stripControl(draft.text)}\n`);
586
+ else {
587
+ // a cited step's results: each quote with its values
588
+ 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`));
589
+ }
583
590
  for (const item of unjudged) {
584
591
  process.stdout.write(`\n--- unjudged: ${stripControl(item.step)} ---\n`);
585
- process.stdout.write(`${stripControl(item.text)}\n`);
592
+ 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
593
  }
587
594
  }
588
595
 
@@ -990,11 +997,26 @@ async function cmdSign(rest) {
990
997
  process.stdout.write(`signed: ${result.flowDir} (by ${result.signature.signedBy})\n`);
991
998
  }
992
999
 
1000
+ /** M8 am6: `fwdloop learn seed --root <flows folder>`: notes from every ended run already recorded ($0, code only). */
1001
+ function cmdLearn(rest) {
1002
+ const [sub, ...args] = rest;
1003
+ if (sub !== 'seed') fail('learn: expected "seed" — fwdloop learn seed --root <flows folder>');
1004
+ const { values } = parseArgs({ args, options: { root: { type: 'string' } } });
1005
+ if (!values.root) fail('learn seed: --root <flows folder> is required');
1006
+ const root = resolveRoot('learn seed', values.root);
1007
+ const r = seedLedger({ root });
1008
+ if (r.skippedNoDoor) fail('learn seed: a test process has no config home (set FWDLOOP_CONFIG_HOME)');
1009
+ const k = r.skipped;
1010
+ const total = Object.values(k).reduce((a, b) => a + b, 0);
1011
+ 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`);
1012
+ if (r.problem) fail(`learn seed: stopped, the ledger is not usable — ${r.problem}`);
1013
+ }
1014
+
993
1015
  // ---------------------------------------------------------------------------
994
1016
 
995
1017
  async function main() {
996
1018
  const [verb, ...rest] = process.argv.slice(2);
997
- if (!verb) fail('usage: fwdloop draft|sign|run|inbox|show|answer|resume|continue|panel ...');
1019
+ if (!verb) fail('usage: fwdloop draft|sign|run|inbox|show|answer|resume|continue|panel|learn ...');
998
1020
 
999
1021
  if (verb === 'draft') return cmdDraft(rest);
1000
1022
  if (verb === 'sign') return cmdSign(rest);
@@ -1005,7 +1027,8 @@ async function main() {
1005
1027
  if (verb === 'resume') return cmdResume(rest);
1006
1028
  if (verb === 'continue') return cmdContinue(rest);
1007
1029
  if (verb === 'panel') return cmdPanel(rest);
1008
- fail(`unknown verb "${verb}" — expected draft | sign | run | inbox | show | answer | resume | continue | panel`);
1030
+ if (verb === 'learn') return cmdLearn(rest);
1031
+ fail(`unknown verb "${verb}" — expected draft | sign | run | inbox | show | answer | resume | continue | panel | learn`);
1009
1032
  return undefined;
1010
1033
  }
1011
1034
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.22.0",
3
+ "version": "0.24.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",
@@ -51,7 +51,7 @@
51
51
  "dependencies": {
52
52
  "bare-agent": "^0.52.0",
53
53
  "barebrowse": "^0.21.0",
54
- "bareguard": "^0.25.1",
54
+ "bareguard": "^0.26.0",
55
55
  "litectx": "^0.32.0"
56
56
  },
57
57
  "devDependencies": {
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 }}
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;
@@ -205,8 +210,8 @@ export function readAskEvidence(ask) {
205
210
  };
206
211
  }
207
212
 
208
- // M3 shape: evidence.artifact.text (+ evidence.unjudged[]).
209
- if (evidence.artifact && typeof evidence.artifact === 'object' && typeof evidence.artifact.text === 'string') {
213
+ // The earlier steps' text carried into the ask (the same for every shape that has an `artifact`).
214
+ const readUnjudged = () => {
210
215
  const rawUnjudged = Array.isArray(evidence.unjudged) ? evidence.unjudged : [];
211
216
  const unjudged = [];
212
217
  for (const item of rawUnjudged) {
@@ -223,14 +228,23 @@ 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
231
240
  // never lost by a malformed sibling entry.
232
241
  }
233
- return { draft: { text: evidence.artifact.text }, unjudged };
242
+ return unjudged;
243
+ };
244
+
245
+ // M3 shape: evidence.artifact.text (+ evidence.unjudged[]).
246
+ if (evidence.artifact && typeof evidence.artifact === 'object' && typeof evidence.artifact.text === 'string') {
247
+ return { draft: { text: evidence.artifact.text }, unjudged: readUnjudged() };
234
248
  }
235
249
 
236
250
  // M2 shape: evidence.text (+ evidence.lines) — no unjudged concept.
@@ -238,6 +252,22 @@ export function readAskEvidence(ask) {
238
252
  return { draft: { text: evidence.text }, unjudged: [] };
239
253
  }
240
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
+
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);
261
+ // the `why` stays, for the caller that finds no sheet step for them.
262
+ if (evidence.artifact && typeof evidence.artifact === 'object' && !Array.isArray(evidence.artifact)) {
263
+ return {
264
+ draft: null,
265
+ unjudged: readUnjudged(),
266
+ claims: evidence.artifact,
267
+ why: `ask.json "evidence" has neither ".artifact.text" (M3) nor ".text" (M2) — unrecognised shape: keys ${JSON.stringify(Object.keys(evidence))}`,
268
+ };
269
+ }
270
+
241
271
  // Present but neither recognised shape — never fall through to
242
272
  // `undefined`/`JSON.stringify(undefined)` ("undefined" the string).
243
273
  return {
@@ -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
@@ -23,6 +23,7 @@ import { draft } from './drafter.js';
23
23
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
24
24
  import { validateDeclaration } from './declaration.js';
25
25
  import { factRows } from './citedcheck.js';
26
+ import { sheetLineBlocks } from './sheetblock.js';
26
27
  import { loadCatalogue } from './catalogue.js';
27
28
  import { WIRED_VERBS } from './primitives.js';
28
29
  import { canonicalBytes } from './signature.js';
@@ -31,7 +32,10 @@ import { jobKeyOfSigned } from './jobkey.js';
31
32
  import { checkSendDestination } from './runner.js';
32
33
  import { checkKeyPreflight, appendSpendRow } from './provider.js';
33
34
  import { keyValues } from './keysfile.js';
34
- 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';
35
39
  import { sessionPriorSpend, writeDraftSpend } from './draftspend.js';
36
40
  import { writeSetup } from './setup.js';
37
41
 
@@ -192,12 +196,15 @@ export function buildReadout({
192
196
  out.push(` ${s.role} = ${s.path}${h ? ` [headings: ${h.join(' | ') || 'none'}]` : ''}`);
193
197
  }
194
198
  out.push('', READOUT_HEADS.steps);
199
+ const sheetBlocks = sheetLineBlocks({ declaration, lines });
195
200
  declaration.steps.forEach((st, i) => {
196
201
  out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
197
202
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
198
203
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
199
204
  // M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
200
205
  if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${row}`);
206
+ // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
207
+ if (Array.isArray(st.close?.sheet)) for (const row of sheetBlocks.find((b) => b.line === st.fromLine)?.checked ?? []) out.push(` sheet check: ${row.text}`);
201
208
  // M10 am8 item 2: the column lock, signed with the readout (typed fields)
202
209
  if (Array.isArray(st.close?.columns)) for (const c of st.close.columns) if (typeof c?.column === 'string' && typeof c?.source === 'string') out.push(` cells only from column '${c.column}' of ${c.source}`);
203
210
  // M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
@@ -329,13 +336,36 @@ export async function draftToDir({
329
336
  };
330
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.
331
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
+ }
332
355
  const result = await draft({
333
- 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 }),
334
357
  });
335
358
  if (result.stop === 'pre-flight') {
336
359
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
337
360
  return refuse(cleanReds(result.reds));
338
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
+ }
339
369
 
340
370
  // After a paid round: never a silent throw. The cost is returned so the caller prints it; the dir is claimed and stays.
341
371
  const paidFail = (red) => ({
@@ -496,6 +526,8 @@ export function signDraft({
496
526
  const runSetup = writeSetup({
497
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)),
498
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 */ }
499
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`)
500
532
  return {
501
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),
@@ -517,5 +549,7 @@ export function signDraft({
517
549
  if (pickRecord !== null) {
518
550
  try { writeModelRecord(written.dir, pickRecord); } catch (e) { modelRecord = { ok: false, recorded: false, why: /** @type {any} */ (e)?.code ?? 'error' }; }
519
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 */ }
520
554
  return { ok: true, flowDir: written.dir, signature: written.signature, setup, modelRecord };
521
555
  }
package/src/canrun.js CHANGED
@@ -70,6 +70,11 @@ export function unbuildableSay(n, shape) {
70
70
  */
71
71
  export function findUnbuildableCheckStep(declaration) {
72
72
  for (const step of declaration.steps) {
73
+ // M10b piece 5 (item 8, hamr's ruling): a green step with neither close.sheet nor close.cited is the old cell cite, which no longer runs. A job signed that
74
+ // way is kept for reference (it still reads and displays) and is refused here, at $0, before any spend.
75
+ if (step.close?.class === 'green' && !step.close.cited && !Array.isArray(step.close.sheet)) {
76
+ return { step, why: 'a green step with no close.sheet or close.cited is the retired cell cite', say: `This flow will not run: Line ${step.fromLine}'s check cannot cite cells any more. Draft it again to run it.` };
77
+ }
73
78
  if (step.close?.class !== 'softgreen') continue;
74
79
  try {
75
80
  buildSoftgreenRubric(step.close.shape ?? {});
package/src/checked.js CHANGED
@@ -12,28 +12,38 @@
12
12
  export const NOT_CHECKED_LABEL = "not checked (the AI's own reading)";
13
13
 
14
14
  import { factRows } from './citedcheck.js';
15
+ import { sheetCheckRows } from './sheetchecks.js';
16
+ import { sheetLineBlocks } from './sheetblock.js';
15
17
  import { splitReadNotes, signedFactNames } from './pagedropwords.js';
16
18
 
17
19
  const list = (xs) => xs.join(', ');
18
20
 
19
21
  /**
20
22
  * One entry per step, in plan order: the plain sentences for what its typed close checks.
21
- * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[] }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
23
+ * M10b piece 4: with `lines` (the signed job lines) a step that reads a sheet also carries `sheet`, its line's block (src/sheetblock.js `sheetLineBlocks`: guardrails,
24
+ * Checked with `covers`, Not checked), and its sentences are only the lead sentence; the surfaces draw the block. Without `lines` the older one-row-per-check sentences.
25
+ * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[], lines?: any[], csvRoles?: string[] }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
22
26
  * askLines = the job lines of the signed asks, which also lets a step after the LAST ask read "you check it after you accept" (am41 item 2, am42: the ONE place for these words)
23
- * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[] }[]}
27
+ * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[], sheet?: ReturnType<typeof sheetLineBlocks>[number] }[]}
24
28
  */
25
- export function checkedLines(declaration, { hasAsk = true, askLines } = {}) {
29
+ export function checkedLines(declaration, { hasAsk = true, askLines, lines, csvRoles = [] } = {}) {
30
+ const blocks = Array.isArray(lines) ? sheetLineBlocks({ declaration, lines, csvRoles }) : [];
26
31
  const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
27
32
  if (Array.isArray(askLines)) hasAsk = askLines.length > 0;
28
33
  const lastAsk = Array.isArray(askLines) ? steps.reduce((m, st, i) => (askLines.includes(st?.fromLine) ? i : m), -1) : -1;
29
34
  return steps.map((st, i) => {
30
35
  const cls = st?.close?.class;
36
+ const firstGreen = steps.findIndex((x) => x?.fromLine === st?.fromLine && x?.close?.class === 'green') === i;
37
+ const sheet = firstGreen ? (blocks.find((b) => b.line === st?.fromLine) ?? null) : null;
31
38
  const shape = st?.close?.shape && typeof st.close.shape === 'object' ? st.close.shape : {};
32
39
  /** @type {string[]} */
33
40
  const out = [];
34
41
  if (cls === 'green' && st.close.cited && typeof st.close.cited === 'object') {
35
42
  // M10 am7 item 1: the facts the drafter wrote, as plain rows written by code from the typed fields
36
43
  out.push(`Each result must be quoted word for word from the saved page "${st.close.cited.source}", and the machine checks every quote, every value and the count against that copy.`, ...factRows(st.close.cited));
44
+ } else if (cls === 'green' && Array.isArray(st.close.sheet)) {
45
+ // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
46
+ out.push('The machine recomputes each of these from the saved sheet and compares it with what the step gave:', ...(sheet ? [] : sheetCheckRows(st.close.sheet)));
37
47
  } else if (cls === 'green') {
38
48
  out.push('Every figure must cite its source cell, or a formula over cells, and the machine recomputes it and compares it with its source.');
39
49
  } else if (cls === 'softgreen') {
@@ -49,6 +59,7 @@ export function checkedLines(declaration, { hasAsk = true, askLines } = {}) {
49
59
  }
50
60
  return {
51
61
  step: i + 1, line: Number.isInteger(st?.fromLine) ? st.fromLine : null, goal: typeof st?.goal === 'string' ? st.goal : '', class: String(cls), sentences: out,
62
+ ...(sheet && cls === 'green' ? { sheet } : {}),
52
63
  };
53
64
  });
54
65
  }
package/src/citedcheck.js CHANGED
@@ -36,6 +36,21 @@ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object'
36
36
  /** @param {string} t @returns {string} the sha256 of the text, hex */
37
37
  export const sha256Text = (t) => createHash('sha256').update(t, 'utf8').digest('hex');
38
38
 
39
+ /**
40
+ * A money unit list with an entry listed twice, equal after the whitespace normalization bareguard's quote matcher applies (bareguard 0.26.0: its
41
+ * rubric refuses such a list), keeps the first of them. The one place a unit list is built into a signed fact.
42
+ * @param {string[]} units @returns {string[]}
43
+ */
44
+ function unitsOnce(units) {
45
+ const seen = new Set();
46
+ return units.filter((u) => {
47
+ const key = String(u).split('**').join('').split('__').join('').replace(/\s+/g, ' ').trim();
48
+ if (seen.has(key)) return false;
49
+ seen.add(key);
50
+ return true;
51
+ });
52
+ }
53
+
39
54
  /**
40
55
  * A kept look fact as signed facts. The label that comes first becomes the anchor and the limit the look read (`reading`) becomes the number rule. A PLACE
41
56
  * fact (the look gave it `phrases`, src/pageplace.js: R2, R2a, R2b) becomes one phrase fact per phrase, because every one of them must be in the quote
@@ -53,7 +68,7 @@ export function factsOfLook(k) {
53
68
  const anchor = k.labels?.[0] ?? k.label ?? k.words?.[0];
54
69
  if (anchor !== undefined) f.anchor = String(anchor);
55
70
  if (f.shape === 'money') {
56
- if (k.unit !== undefined) f.unit = [...k.unit];
71
+ if (k.unit !== undefined) f.unit = unitsOnce(k.unit);
57
72
  if (k.currency !== undefined) f.currency = [...k.currency];
58
73
  }
59
74
  if (isRec(k.reading)) f.rule = { ...k.reading };
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
  }