fwdloop 0.23.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.
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.23.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",
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
  }
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;
package/src/drafter.js CHANGED
@@ -326,7 +326,7 @@ function greenReadRule(sources) {
326
326
  '- Fact shapes: money takes unit or currency, rule, anchor; number, date and time take rule, anchor; text takes anchor and until (until needs an anchor); phrase takes only phrase (fixed words every result must say). Never put a field on a shape that does not take it.',
327
327
  '- A label (anchor, until) is PICKED from the kept labels listed under Inputs for that page, never typed. A phrase, a unit or a currency is copied from the page words listed there. A word listed as Not checked or dropped can never be used.',
328
328
  '- A place listed under Inputs as "place phrases" must have EVERY one of its phrases as its own phrase fact (one fact per phrase, the phrase word for word). A place name alone does not tell a result that leaves the other way.',
329
- '- A fact\'s rule (under, over, between) may only use a number that is in the person\'s own words on that job line (the line or its guardrail). Never make a number up; leave the rule out if the person gave none.',
329
+ '- A fact\'s rule (under, over, between) may only use a number that is in the person\'s own words on that job line (the line or its guardrail). Never make a number up; leave the rule out if the person gave none. When the Kept list says "limit read from your words" for a fact, the fact that reads that value MUST carry that rule (same kind, op and bound), or the line is refused.',
330
330
  '- A label or a phrase that sits in each result must appear on the page at least as many times as close.cited.count.min, or the line is refused.',
331
331
  ...(docRoles.length ? ['- For a document input there is no list of kept labels: a label (anchor) or a phrase is words the document really says, copied from it, and each must be in the document at least as many times as close.cited.count.min.'] : []),
332
332
  );
@@ -421,12 +421,14 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
421
421
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
422
422
  * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
423
423
  * look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
424
+ * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
424
425
  * `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
425
426
  */
426
427
  export async function draft({
427
428
  proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
428
429
  priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
429
430
  draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
431
+ learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
430
432
  }) {
431
433
  // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
432
434
  const thinkingOf = () => {
@@ -660,7 +662,9 @@ export async function draft({
660
662
  // M10b piece 3: the drafting copy's table of each CSV input - the header the drafter may pick from, the table bareguard's sign-time test runs over
661
663
  const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
662
664
  const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo });
663
- const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}`;
665
+ // M8 item 5a: the earlier runs' notes go on the DRAFTER's system prompt only (F81's B arm), the one `system` every round of this draft uses (revise and structure retries too).
666
+ // Absent or empty: the prompt is byte-identical to what it was.
667
+ const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
664
668
  let structureRetries = 0;
665
669
  let revisions = 0;
666
670
  let lastReds = [];
package/src/flowmodel.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // and a model id - is recorded in `model.json`, beside the draft and then beside the signed flow. It is NOT one of the signed files: which model
3
3
  // runs, and at what price, is Settings' to say (a line that is no longer ticked is refused by name at run time), so the record only remembers the choice.
4
4
  // One writer (`writeModelRecord`), one reader (`readModelRecord`); both go through the safe gateway.
5
- import { writeFileSync } from 'node:fs';
5
+ import { writeFileSync, renameSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { readFileInside } from './flow.js';
8
8
  import { isKeyName } from './provider.js';
@@ -86,3 +86,58 @@ export function readRunModel(runDir) {
86
86
  export function writeRunModel(runDir, { slot, model }) {
87
87
  writeOnce(join(runDir, RUN_MODEL_FILE), { slot, model });
88
88
  }
89
+
90
+ /**
91
+ * M8 item 5a: the file that keeps EXACTLY what the drafter was handed from earlier runs (the Audit box of item 6 reads it). Bareloop's
92
+ * `learnings` spine record shape, `{phase, text, ids, chars}`. Write-once (never over an existing record); written with something handed, or by `writeLearningsError` with an empty `text`
93
+ * (a failed ask: nothing handed, why in `error`); a reader treats empty text as no record, so no file or empty text = nothing handed = no box. Borrowed-from: bareloop src/planrun.js@v0.46.0:3092 (emit('learnings', ...)).
94
+ */
95
+ export const LEARNINGS_FILE = 'learnings.json';
96
+
97
+ /** @param {string} dir @param {{text: string, ids: string[]}} hints */
98
+ export function writeLearningsRecord(dir, { text, ids }) {
99
+ writeOnce(join(dir, LEARNINGS_FILE), { phase: 'draft', text, ids, chars: text.length });
100
+ }
101
+
102
+ /**
103
+ * The drafter's failed ask for the block (or failed record write) rides the same record: nothing handed (`text: ''`, no ids), and `error` (first line, secrets redacted).
104
+ * `readLearningsRecord` reads an empty text as no record, so the Audit box stays hidden and `copyLearningsRecord` copies nothing.
105
+ * @param {string} dir @param {string} error
106
+ */
107
+ export function writeLearningsError(dir, error) {
108
+ writeOnce(join(dir, LEARNINGS_FILE), { phase: 'draft', text: '', ids: [], chars: 0, error });
109
+ }
110
+
111
+ /**
112
+ * M8 item 6: the Audit box reads the record in the RUN's folder. It reaches the run the way `model.json` does: a draft's record is copied (write-once) into the folder it is signed
113
+ * into (`copyLearningsRecord`: the flow folder at a new job's sign, the new run's folder at a red run's redraft), and the first run that starts from a flow folder TAKES it
114
+ * (`takeLearningsRecord`: a rename, so it moves once and a second run of the same job never shows it). A run that reused its plan has no draft, so it has none.
115
+ * @param {string} fromDir a draft folder @param {string} toDir a flow folder or a run folder @returns {boolean} true when a record was copied
116
+ */
117
+ export function copyLearningsRecord(fromDir, toDir) {
118
+ const rec = readLearningsRecord(fromDir);
119
+ if (rec === null) return false;
120
+ writeOnce(join(toDir, LEARNINGS_FILE), rec); // `writeOnce`, the same write-once JSON writer and shape as `writeLearningsRecord`: a record that reads is copied, one that does not is not
121
+ return true;
122
+ }
123
+
124
+ /** @param {string} flowDir @param {string} runDir @returns {boolean} true when the flow's record moved into the run (it is no longer in the flow folder) */
125
+ export function takeLearningsRecord(flowDir, runDir) {
126
+ if (!readFileInside(flowDir, LEARNINGS_FILE).ok || readFileInside(runDir, LEARNINGS_FILE).ok) return false;
127
+ renameSync(join(flowDir, LEARNINGS_FILE), join(runDir, LEARNINGS_FILE));
128
+ return true;
129
+ }
130
+
131
+ /**
132
+ * The ONE reader of a run's record. null = no record, or one that is not `{phase, text, ids, chars}` (the box is then hidden, never guessed).
133
+ * @param {string} runDir @returns {{phase: string, text: string, ids: string[], chars: number}|null}
134
+ */
135
+ export function readLearningsRecord(runDir) {
136
+ const r = readFileInside(runDir, LEARNINGS_FILE);
137
+ if (!r.ok) return null;
138
+ try {
139
+ const j = JSON.parse(r.text);
140
+ return j && typeof j.text === 'string' && j.text !== '' && Array.isArray(j.ids) && j.ids.every((/** @type {any} */ x) => typeof x === 'string')
141
+ ? { phase: String(j.phase ?? 'draft'), text: j.text, ids: j.ids, chars: Number.isInteger(j.chars) ? j.chars : j.text.length } : null;
142
+ } catch { return null; }
143
+ }