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
@@ -0,0 +1,346 @@
1
+ // borrowed-from: bareloop src/learnstore.js@v0.47.0 (66dc2b0)
2
+ // Adaptations: M8 item 3: the ledger home is fwdloop's configHome() (src/config.js) in place of bareloop's keysHome, so the file is <configHome>/learn/ledger.json (mode 600, as bareloop); with no explicit home under a test process and no FWDLOOP_CONFIG_HOME, ledgerPath throws, so a test can never reach the real ~/.config/fwdloop; hintsForRun is copied at the bottom (M8 item 5a) with a ledger problem THROWN (the caller records why and hands nothing), and with `path.resolve` for the place in place of bareloop's realpathSync (the F48 guard keeps realpathSync out of this file), the same place learnAtRunEnd records; stageQuestionsByName is not copied (see learnAtRunEnd: a card's `meaning` is the failing check's own text from the run's checks.jsonl); learnAtRunEnd reads fwdloop's run folder through eventsOfRun (adapted from fwdloop poc/learn/adapter.mjs, F79) because fwdloop has no bareloop spine; imports trimmed to match. Nothing else changed. Known gap, kept on purpose (M8 item 7): foldRunIntoLedger and releaseRun read, change and replace the file, so two runs ending together can lose a note.
3
+ // The thin reader/writer around src/learn.js (cross-run learnings, ITEM33-BUILD.md rev 2). All file IO lives here and
4
+ // the pure rules live in learn.js; nothing in either file can reach a model.
5
+ //
6
+ // ONE ledger per user: `<config home>/learn/ledger.json` (~/.config/fwdloop/learn/ledger.json in production; tests inject a
7
+ // scratch home and never create the real directory). It lives outside every person's repo, is written atomically
8
+ // (temp file + rename) and mode 600, and every string in it passes the one secret inventory before it is written.
9
+
10
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync } from 'node:fs';
11
+ import { join, dirname, resolve } from 'node:path';
12
+ import { homedir } from 'node:os';
13
+ import { configHome, configDoorHome, readConfig } from './config.js';
14
+ import { emptyLedger, redactDeep, countLedger, releasePending, recordHealth, buildCards, placeOf, renderHints } from './learn.js';
15
+ import { readAudit, readHistory } from './books.js';
16
+ import { readChecks } from './diary.js';
17
+ import { readFileInside, readdirInside, listFlowNames, listRunIds } from './flow.js';
18
+
19
+ /**
20
+ * M8 item 5a (loose end): the ONE function that turns a source as written into a place. The run-end notes (`learnAtRunEnd`: a path the panel/CLI gave the run) and
21
+ * the drafter's hints (`hintsForRun`: the step's first input, or at draft time the path as typed in the prose) both pass through it, so the same file cannot be two places. A leading `~` or `~/` is the
22
+ * home folder (`path.resolve` alone would make it `<cwd>/~/...`); then `path.resolve` (lexical, no fs: the F48 guard keeps realpathSync out of this file).
23
+ * A web address stays its host (placeOf). Not copied from bareloop: this is the fwdloop-only part of the place.
24
+ * @param {string} p @returns {string}
25
+ */
26
+ export function resolvePlace(p) {
27
+ return resolve(p === '~' || p.startsWith('~/') ? join(homedir(), p.slice(1)) : p);
28
+ }
29
+
30
+ /**
31
+ * M8 am8: the ONE function that gives a run's place spec: `{job, inputs}` for `placeOf`, from the run's first input AS THE RUN READS IT (`inputsManifest[0].source`,
32
+ * a path the panel or CLI gave the run), never the path written in the signed job. The step's hints (`stepHintsReader`), the run-end tally (`learnAtRunEnd`) and the
33
+ * drafter's hints (src/authoring.js) all build their spec here. No source (a job with no file input) is no place.
34
+ * @param {string} job the workflow name
35
+ * @param {string|null|undefined} source the run's first input as it reads it
36
+ * @returns {{job: string, inputs: {value: string}[]}}
37
+ */
38
+ export function placeSpecOf(job, source) {
39
+ return { job, inputs: typeof source === 'string' && source !== '' ? [{ value: source }] : [] };
40
+ }
41
+
42
+ /**
43
+ * `<configHome>/learn/ledger.json`. Under a test process (NODE_ENV=test or node --test) the home is the explicit one or
44
+ * FWDLOOP_CONFIG_HOME; with neither it THROWS rather than fall back to the real ~/.config/fwdloop.
45
+ * @param {string} [home] test seam; production never passes it
46
+ * @returns {string}
47
+ */
48
+ export function ledgerPath(home) {
49
+ if (home === undefined) {
50
+ const door = configDoorHome();
51
+ if (door.skip) throw new Error('learnings ledger: a test process has no config home (set FWDLOOP_CONFIG_HOME or pass one)');
52
+ home = door.home;
53
+ }
54
+ return join(configHome(home), 'learn', 'ledger.json');
55
+ }
56
+
57
+ /**
58
+ * Read the ledger. A missing file is an empty ledger; an unreadable or wrong-shaped one is reported as `problem` (and the
59
+ * writer then refuses to replace it: an append-only record is never silently reset).
60
+ * @param {string} [home]
61
+ * @returns {{ledger: import('./learn.js').Ledger, exists: boolean, problem: string|null}}
62
+ */
63
+ export function readLedger(home) {
64
+ const file = ledgerPath(home);
65
+ if (!existsSync(file)) return { ledger: emptyLedger(), exists: false, problem: null };
66
+ try {
67
+ const d = JSON.parse(readFileSync(file, 'utf8'));
68
+ if (!d || typeof d !== 'object' || d.version !== 1 || !Array.isArray(d.rows) || !Array.isArray(d.pending)) {
69
+ return { ledger: emptyLedger(), exists: true, problem: `${file} is not a version-1 learnings ledger — fix or remove it` };
70
+ }
71
+ return { ledger: { ...emptyLedger(), ...d }, exists: true, problem: null };
72
+ } catch (/** @type {any} */ e) {
73
+ return { ledger: emptyLedger(), exists: true, problem: `${file} is not readable JSON (${e?.code ?? 'parse error'}) — fix or remove it` };
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Write the ledger atomically (temp + rename, mode 600), every string masked through the one secret inventory.
79
+ * @param {import('./learn.js').Ledger} ledger @param {string} [home]
80
+ * @returns {string} the file written
81
+ */
82
+ export function writeLedger(ledger, home) {
83
+ const file = ledgerPath(home);
84
+ mkdirSync(dirname(file), { recursive: true });
85
+ const tmp = `${file}.tmp-${process.pid}`;
86
+ writeFileSync(tmp, `${JSON.stringify(redactDeep(ledger), null, 1)}\n`, { mode: 0o600 });
87
+ chmodSync(tmp, 0o600);
88
+ renameSync(tmp, file);
89
+ return file;
90
+ }
91
+
92
+ /**
93
+ * Fold ONE finished run into the ledger on disk: every run's cards COUNT now, rubric jobs too (trust kept on new rows;
94
+ * bareloop v0.47.0). `held` is always 0 (kept in the shape for callers). The run's health line is recorded. Never throws on a bad ledger file: it reports `problem` and writes nothing.
95
+ * @param {{home?: string, runid: string, build: import('./learn.js').CardBuild, workflow: string, place: string|null, specHash: string|null, trust: 'deterministic'|'rubric', at: string, now?: Date}} o
96
+ * @returns {{wrote: boolean, counted: number, held: number, problem: string|null}}
97
+ */
98
+ export function foldRunIntoLedger({ home, runid, build, workflow, place, specHash, trust, at, now = new Date() }) {
99
+ const cur = readLedger(home);
100
+ if (cur.problem) return { wrote: false, counted: 0, held: 0, problem: cur.problem };
101
+ let L = cur.ledger;
102
+ const before = L.rows.reduce((n, r) => n + r.runIds.filter((x) => x === runid).length, 0);
103
+ L = countLedger(L, { runid, cards: build.cards, workflow, place, specHash, trust, now });
104
+ const counted = L.rows.reduce((n, r) => n + r.runIds.filter((x) => x === runid).length, 0) - before;
105
+ L = recordHealth(L, runid, build, at, now);
106
+ writeLedger(L, home);
107
+ return { wrote: true, counted, held: 0, problem: null };
108
+ }
109
+
110
+ /**
111
+ * The human Accept at the review door: release a hold an older version wrote for the run so it counts (new runs write none; only forward, only here).
112
+ * @param {{home?: string, runid: string, now?: Date}} o
113
+ * @returns {{released: number, problem: string|null}}
114
+ */
115
+ export function releaseRun({ home, runid, now = new Date() }) {
116
+ const cur = readLedger(home);
117
+ if (cur.problem) return { released: 0, problem: cur.problem };
118
+ const r = releasePending(cur.ledger, runid, now);
119
+ if (r.ledger !== cur.ledger) writeLedger(r.ledger, home);
120
+ return { released: r.released, problem: null };
121
+ }
122
+
123
+ /**
124
+ * M8 am1: the ONE setting, `learningHints` in config.json. Ships OFF (absent = off). OFF still writes the tally ($0); the drafter
125
+ * is simply handed nothing. Copied from bareloop learnstore.js@v0.47.0:96 (borrowed-from header above). Difference: bareloop's
126
+ * `readConfig` returns a problem, fwdloop's THROWS ConfigError on an unreadable / non-JSON / invalid file. The safe reading is kept:
127
+ * a bad or unreadable config reads as OFF (never ON). Under a test process with no explicit home and no FWDLOOP_CONFIG_HOME it
128
+ * reads nothing (OFF), so a test can never reach the real ~/.config/fwdloop.
129
+ * @param {string} [home]
130
+ * @returns {boolean}
131
+ */
132
+ export function learningHintsOn(home) {
133
+ let h = home;
134
+ if (h === undefined) {
135
+ const door = configDoorHome();
136
+ if (door.skip) return false;
137
+ h = door.home;
138
+ }
139
+ try {
140
+ return readConfig({ home: h }).learningHints === true;
141
+ } catch {
142
+ return false;
143
+ }
144
+ }
145
+
146
+ // ── the run-end tally (M8 items 2 and 4) ─────────────────────────────────────────────────────────
147
+
148
+ /** Unified -U1 line diff (LCS), as the F79 adapter made it; '' when identical. Borrowed-from: fwdloop poc/learn/adapter.mjs (F79, 2026-10-23). @param {string} a @param {string} b @param {number} [ctx] */
149
+ function unifiedDiff(a, b, ctx = 1) {
150
+ const A = a === '' ? [] : a.split('\n');
151
+ const B = b.split('\n');
152
+ const n = A.length;
153
+ const m = B.length;
154
+ const L = Array.from({ length: n + 1 }, () => new Int32Array(m + 1));
155
+ for (let i = n - 1; i >= 0; i -= 1) for (let j = m - 1; j >= 0; j -= 1) L[i][j] = A[i] === B[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
156
+ /** @type {Array<[string, string]>} */
157
+ const ops = [];
158
+ let i = 0;
159
+ let j = 0;
160
+ while (i < n && j < m) {
161
+ if (A[i] === B[j]) { ops.push([' ', A[i]]); i += 1; j += 1; } else if (L[i + 1][j] >= L[i][j + 1]) { ops.push(['-', A[i]]); i += 1; } else { ops.push(['+', B[j]]); j += 1; }
162
+ }
163
+ while (i < n) { ops.push(['-', A[i]]); i += 1; }
164
+ while (j < m) { ops.push(['+', B[j]]); j += 1; }
165
+ const keep = ops.map(() => false);
166
+ ops.forEach((o, k) => { if (o[0] !== ' ') for (let d = -ctx; d <= ctx; d += 1) if (ops[k + d]) keep[k + d] = true; });
167
+ /** @type {string[]} */
168
+ const out = [];
169
+ let ai = 1;
170
+ let bi = 1;
171
+ const pos = ops.map((o) => { const p = [ai, bi]; if (o[0] !== '+') ai += 1; if (o[0] !== '-') bi += 1; return p; });
172
+ let k = 0;
173
+ while (k < ops.length) {
174
+ if (!keep[k]) { k += 1; continue; }
175
+ let e = k;
176
+ while (e < ops.length && keep[e]) e += 1;
177
+ const seg = ops.slice(k, e);
178
+ out.push(`@@ -${pos[k][0]},${seg.filter((o) => o[0] !== '+').length} +${pos[k][1]},${seg.filter((o) => o[0] !== '-').length} @@`);
179
+ for (const [c, t] of seg) out.push(c + t);
180
+ k = e;
181
+ }
182
+ return out.join('\n');
183
+ }
184
+
185
+ /** @param {string} runDir @param {string} rel @returns {any} the parsed JSON file inside the run folder, or null when absent / unreadable */
186
+ function jsonIn(runDir, rel) {
187
+ const r = readFileInside(runDir, rel);
188
+ if (!r.ok) return null;
189
+ try { return JSON.parse(r.text); } catch { return null; }
190
+ }
191
+
192
+ /** audit.jsonl rows that are a step's TRY with a verdict on its output; a human redo (class hitl + red), a pause, a stop and a funding halt are not one. */
193
+ const isTry = (/** @type {any} */ r) => Number.isInteger(r.attempt) && ['green', 'hitl', 'softgreen', 'red', 'not-done'].includes(r.verdict) && !(r.class === 'hitl' && r.verdict === 'red');
194
+
195
+ /**
196
+ * One finished run's folder -> the event list buildCards reads, plus the check texts and the model. ONE adapter, map never invent
197
+ * (F79). Check name = `<step> (line <job line>, <close class>)`; a try with verdict red or not-done and a gap = a red moment (the gap
198
+ * verbatim = B1's flagged line); a later try of the same check that is not red = the pass; Fix touched = `artifacts/<step>.json`;
199
+ * What changed = a -U1 line diff of the try's modelOutput (log.json) against the step's previous try. Reads only the run's own books.
200
+ * Refused drafts make no run folder, and a human redo is not a try (isTry), so neither makes a note.
201
+ * @param {string} runDir @param {string} workflow
202
+ * @returns {{events: any[], questions: Map<string, string|null>, model: string|null, source: string|null}|null} null when the run has no try
203
+ */
204
+ export function eventsOfRun(runDir, workflow) {
205
+ const audit = readAudit(runDir);
206
+ const rows = audit.filter(isTry);
207
+ if (!rows.length) return null;
208
+ const log = jsonIn(runDir, 'log.json') ?? {};
209
+ const decl = jsonIn(runDir, 'job/declaration.json') ?? { steps: [] };
210
+ const inputs = jsonIn(runDir, 'inputs.json');
211
+ const prose = (() => { const r = readFileInside(runDir, 'job/prose.txt'); return r.ok ? r.text : ''; })();
212
+ const checks = readChecks(runDir);
213
+ const made = new Set(readdirInside(runDir, 'artifacts'));
214
+ const outBy = new Map((log.attempts || []).map((/** @type {any} */ a) => [`${a.step}#${a.attempt}`, a.modelOutput]));
215
+ const lastAt = audit.at(-1)?.at ?? '1970-01-01T00:00:00.000Z';
216
+ const model = audit.find((r) => typeof r.model === 'string')?.model ?? null;
217
+ const stepMeta = new Map((decl.steps || []).map((/** @type {any} */ s) => [s.emits, s]));
218
+ /** @type {Map<string, string|null>} */
219
+ const questions = new Map();
220
+ /** @type {any[]} */
221
+ const events = [];
222
+ let seq = 0;
223
+ let ts = audit[0]?.at ?? lastAt;
224
+ const push = (/** @type {any} */ e) => events.push({ seq: (seq += 1), ts, ...e });
225
+ push({ type: 'job-start', job: workflow, goal: prose.split(/\n\s*\n/)[0].trim(), model });
226
+ push({ type: 'plan-accepted', plan: { steps: (decl.steps || []).map((/** @type {any} */ s) => ({ id: s.emits, action: s.goal })) } });
227
+ /** @type {Map<string, string>} */
228
+ const prevOut = new Map();
229
+ for (const a of rows) {
230
+ ts = a.at ?? ts;
231
+ const meta = /** @type {any} */ (stepMeta.get(a.step));
232
+ const name = `${a.step} (line ${meta?.fromLine ?? '?'}, ${a.class})`;
233
+ push({ type: 'step-start', step: a.step });
234
+ push({ type: 'iteration-start' });
235
+ const mo = outBy.get(`${a.step}#${a.attempt}`);
236
+ let diff = '';
237
+ if (mo !== undefined) { const after = JSON.stringify(mo, null, 2); diff = unifiedDiff(prevOut.has(a.step) ? /** @type {string} */ (prevOut.get(a.step)) : '', after); prevOut.set(a.step, after); }
238
+ if (made.has(`${a.step}.json`)) push({ type: 'attempt-diff', files: [{ path: `artifacts/${a.step}.json`, diff: diff.slice(0, 4096), truncated: diff.length > 4096 }], binary: [], truncated: false });
239
+ if ((a.verdict === 'red' || a.verdict === 'not-done') && typeof a.gap === 'string' && a.gap !== '') {
240
+ const f = checks.find((c) => c.step === a.step && c.try === a.attempt)?.checks?.find((/** @type {any} */ x) => !x.ok);
241
+ if (f && !questions.has(name)) questions.set(name, String(f.text));
242
+ push({ type: 'exit-eval', step: a.step, results: [{ type: name, pass: false, detail: a.gap }] });
243
+ } else {
244
+ push({ type: 'exit-eval', step: a.step, results: [{ type: name, pass: true }] });
245
+ }
246
+ }
247
+ ts = lastAt;
248
+ // M8 am4 item 3: the two noise categories bareloop's buildCards reads off an `escalation` event, seen here in the audit: a provider red
249
+ // (verdict 'provider-red', the transport fault twice) and a closer that crashed or was unparseable (verdict 'close-casualty'). Both end
250
+ // the run, so a row of either is the run's last word. Neither is a try (isTry), so it never makes a red moment of its own.
251
+ const noiseRow = audit.findLast((r) => r.verdict === 'provider-red' || r.verdict === 'close-casualty');
252
+ if (noiseRow) push({ type: 'escalation', category: noiseRow.verdict === 'provider-red' ? 'provider-red' : 'close-crashed' });
253
+ push({ type: 'job-end', outcome: log.outcome === 'complete' ? 'green' : String(log.outcome) });
254
+ return { events, questions, model, source: typeof inputs?.[0]?.source === 'string' ? inputs[0].source : null };
255
+ }
256
+
257
+ /**
258
+ * THE RUN-END TALLY ($0, code only, no model; M8 item 2): turn a finished run's folder into cards and fold them into the ledger.
259
+ * The place is the first input's source made absolute lexically (`path.resolve`, no fs: the F48 guard keeps realpathSync out of this file, so a symlinked source is not followed). The ledger run id is `<workflow>/<runId>` (fwdloop's run ids repeat across workflows, bareloop's do not). M8 am4: every run's notes COUNT at once (trust 'deterministic'), a run
260
+ * with a signed ask included; there is no hold. It runs whether `learningHints` is on or off. `questions` (bareloop's stageQuestionsByName) is, here, the failing check's own text from
261
+ * the run's checks.jsonl, so a check with no checks.jsonl row (a run from before am29) has no `meaning`.
262
+ * Borrowed-from: bareloop src/learnstore.js@v0.47.0:124 (learnAtRunEnd).
263
+ * @param {{home?: string, workflow: string, runId: string, runDir: string, specHash: string|null, now?: Date}} o
264
+ * @returns {{wrote: boolean, counted: number, held: number, problem: string|null, noise: string|null, cards: number}}
265
+ */
266
+ export function learnAtRunEnd({ home, workflow, runId, runDir, specHash, now = new Date() }) {
267
+ const rec = eventsOfRun(runDir, workflow);
268
+ if (!rec) return { wrote: false, counted: 0, held: 0, problem: null, noise: 'no-tries', cards: 0 };
269
+ const runid = `${workflow}/${runId}`;
270
+ const build = buildCards({ runid, events: rec.events, spec: { job: workflow }, model: rec.model, questions: rec.questions });
271
+ const at = rec.events.findLast((e) => e.type === 'job-end')?.ts ?? now.toISOString();
272
+ const r = foldRunIntoLedger({ home, runid, build, workflow, place: placeOf(placeSpecOf(workflow, rec.source), resolvePlace), specHash, trust: 'deterministic', at, now });
273
+ return { ...r, noise: build.noise, cards: build.cards.length };
274
+ }
275
+
276
+ /** M8 am4 item 2: a run waiting at an ask has not ended ('paused', or a Stop whose set-aside failed). ONE decider: the runner's run-end tally and the seed both read it. */
277
+ export const NOT_A_RUN_END = new Set(['paused', 'stop-failed']);
278
+
279
+ /**
280
+ * M8 am6: seed the ledger from every run already recorded under `root` (every job, every ended run), oldest first by the run's own end time
281
+ * (the last history row that is a run end). Each run goes through `learnAtRunEnd` (the one note builder) with `now` = its own end time, so
282
+ * ages, decay and lastSeen come from the run. A run already in the ledger (its `<workflow>/<runId>` has a health line) is skipped, so a second seed adds nothing.
283
+ * Code only, $0. A run it cannot read is counted and the seed goes on; a bad ledger file stops it at once (nothing is rewritten).
284
+ * Under a test process with no door nothing is read or written (`skippedNoDoor`).
285
+ * @param {{root: string, home?: string}} o `home` is a test seam; production leaves it out
286
+ * @returns {{read: number, added: number, skipped: Record<'already-in'|'still-waiting'|'no-end'|'unreadable'|'noise', number>, problem: string|null, skippedNoDoor: boolean}}
287
+ */
288
+ export function seedLedger({ root, home }) {
289
+ /** @type {{read: number, added: number, skipped: Record<'already-in'|'still-waiting'|'no-end'|'unreadable'|'noise', number>, problem: string|null, skippedNoDoor: boolean}} */
290
+ const out = { read: 0, added: 0, skipped: { 'already-in': 0, 'still-waiting': 0, 'no-end': 0, unreadable: 0, noise: 0 }, problem: null, skippedNoDoor: false };
291
+ if (home === undefined) {
292
+ const door = configDoorHome();
293
+ if (door.skip) return { ...out, skippedNoDoor: true };
294
+ home = door.home;
295
+ }
296
+ /** @type {{workflow: string, runId: string, runDir: string, end: Date, specHash: string|null}[]} */
297
+ const todo = [];
298
+ for (const workflow of listFlowNames(root)) {
299
+ const flowDir = join(root, workflow);
300
+ /** @type {any[]|null} */
301
+ let history = null;
302
+ try { history = readHistory(flowDir); } catch { history = null; }
303
+ for (const runId of listRunIds(flowDir)) {
304
+ out.read += 1;
305
+ const runDir = join(flowDir, 'runs', runId);
306
+ try {
307
+ const log = jsonIn(runDir, 'log.json');
308
+ if (log && NOT_A_RUN_END.has(log.outcome)) { out.skipped['still-waiting'] += 1; continue; }
309
+ if (history === null) { out.skipped.unreadable += 1; continue; }
310
+ const endRow = history.findLast((r) => r?.runId === runId && !NOT_A_RUN_END.has(r.outcome) && Number.isFinite(Date.parse(r.at)));
311
+ if (!endRow) { out.skipped['no-end'] += 1; continue; }
312
+ if (!log) { out.skipped.unreadable += 1; continue; }
313
+ todo.push({ workflow, runId, runDir, end: new Date(endRow.at), specHash: typeof endRow.signatureHash === 'string' ? endRow.signatureHash : null });
314
+ } catch { out.skipped.unreadable += 1; }
315
+ }
316
+ }
317
+ todo.sort((a, b) => a.end.getTime() - b.end.getTime() || `${a.workflow}/${a.runId}`.localeCompare(`${b.workflow}/${b.runId}`));
318
+ for (const t of todo) {
319
+ const cur = readLedger(home);
320
+ if (cur.problem) { out.problem = cur.problem; return out; }
321
+ if (Object.hasOwn(cur.ledger.health, `${t.workflow}/${t.runId}`)) { out.skipped['already-in'] += 1; continue; }
322
+ try {
323
+ const r = learnAtRunEnd({ home, workflow: t.workflow, runId: t.runId, runDir: t.runDir, specHash: t.specHash, now: t.end });
324
+ if (r.problem) { out.problem = r.problem; return out; }
325
+ if (r.noise) out.skipped.noise += 1;
326
+ else out.added += r.counted;
327
+ } catch { out.skipped.unreadable += 1; }
328
+ }
329
+ return out;
330
+ }
331
+
332
+ /**
333
+ * M8 item 5a: the block the DRAFTER is handed for this job, made from the ledger as it stood: null when `learningHints` is off,
334
+ * when there is no ledger, or when nothing is readable; an unreadable ledger THROWS (the caller hands nothing and records why). The one `renderHints` render (2,000 characters at most),
335
+ * never a second. Age (56 days), job version and level are worked out here, at read time, by renderHints.
336
+ * Borrowed-from: bareloop src/learnstore.js@v0.47.0:140 (hintsForRun). `spec` is `{job, inputs: [{value}]}` (job = the workflow name).
337
+ * @param {{home?: string, spec: any, specHash: string|null, now?: Date}} o
338
+ * @returns {{text: string, ids: string[]}|null}
339
+ */
340
+ export function hintsForRun({ home, spec, specHash, now = new Date() }) {
341
+ if (!learningHintsOn(home)) return null;
342
+ const cur = readLedger(home);
343
+ if (cur.problem) throw new Error(cur.problem); // adapted: bareloop returns null here; the caller (authoring.js) hands nothing AND records why (item 4)
344
+ const r = renderHints(cur.ledger, { workflow: String(spec.job), place: placeOf(spec, resolvePlace), specHash, now });
345
+ return r.text ? r : null;
346
+ }
package/src/model-step.js CHANGED
@@ -31,7 +31,7 @@ import { appendCall, appendTool, nextRound } from './diary.js';
31
31
  import { ConfigError } from './config.js';
32
32
  import { worstThinkingStatus } from './thinking.js';
33
33
  import { citedBrief } from './citedcheck.js';
34
- import { citeForms } from './closers.js';
34
+ import { sheetAnswerProps, sheetBrief } from './sheetclaims.js';
35
35
 
36
36
  import {
37
37
  makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
@@ -93,22 +93,6 @@ const DONE_PROPS = Object.freeze({
93
93
  },
94
94
  });
95
95
 
96
- const GREEN_SCHEMA = Object.freeze({
97
- type: 'object',
98
- properties: {
99
- fields: {
100
- type: 'object',
101
- additionalProperties: {
102
- type: 'object',
103
- properties: { value: {}, cite: { type: 'string', description: `Where the value comes from: ${citeForms()}.` } },
104
- required: ['value', 'cite'],
105
- },
106
- },
107
- ...DONE_PROPS,
108
- },
109
- required: ['fields', 'done'],
110
- });
111
-
112
96
  const SOFTGREEN_SCHEMA = Object.freeze({
113
97
  type: 'object',
114
98
  properties: {
@@ -159,9 +143,15 @@ const CITED_SCHEMA = Object.freeze({
159
143
  * only (plus, for a green step that quotes a saved page, the form of its answer).
160
144
  * `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`; `cited` is true for that green step.
161
145
  */
162
- export function buildEmitArtifactSchema(stepClass, cited = false) {
146
+ /** @param {string|null|undefined} stepClass @param {boolean} [cited] @param {any[]|null} [sheet] M10b piece 2: the step's `close.sheet` (its claim boxes become the answer) */
147
+ export function buildEmitArtifactSchema(stepClass, cited = false, sheet = null) {
148
+ if (stepClass === 'green' && Array.isArray(sheet)) {
149
+ // M10b piece 2: a step that reads a sheet answers in one typed box per claim (bareguard's shapes), never a cite
150
+ const { properties, required } = sheetAnswerProps(sheet);
151
+ return { type: 'object', properties: { ...properties, ...DONE_PROPS }, required: [...required, 'done'], additionalProperties: false };
152
+ }
163
153
  if (stepClass === 'green' && cited) return CITED_SCHEMA;
164
- if (stepClass === 'green') return GREEN_SCHEMA;
154
+ if (stepClass === 'green') throw new Error('a green step answers in quotes (close.cited) or in claim boxes (close.sheet); the cell cite retired in M10b piece 5');
165
155
  if (stepClass === 'softgreen') return SOFTGREEN_SCHEMA;
166
156
  return HITL_SCHEMA;
167
157
  }
@@ -311,7 +301,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
311
301
  * @param {{in:number,out:number}} [opts.rates]
312
302
  * @param {string} [opts.modelId]
313
303
  * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
314
- * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, cited?:any, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
304
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, cited?:any, sheet?:any[]|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
315
305
  */
316
306
  export function makeLiveModelStep({
317
307
  slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
@@ -352,7 +342,7 @@ export function makeLiveModelStep({
352
342
  const runDir = dirname(spendPath);
353
343
  const diaryStep = stepMeta.step ?? null;
354
344
  const diaryTry = typeof stepMeta.attempt === 'number' ? stepMeta.attempt : null;
355
- const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited));
345
+ const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited), stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? stepMeta.sheet : null);
356
346
  const thinkingMode = stepMeta.thinkingMode === 'on' || stepMeta.thinkingMode === 'off' ? stepMeta.thinkingMode : null;
357
347
  const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
358
348
  + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
@@ -361,8 +351,12 @@ export function makeLiveModelStep({
361
351
  goal: executorContext.goal,
362
352
  reads: executorContext.reads,
363
353
  gap: executorContext.gap,
354
+ // M8 am7: on a retry, redo or rerun try only - the earlier runs' block, whole, the same text the drafter's block is made of; it leans the model, the close alone judges
355
+ ...(typeof executorContext.hints === 'string' && executorContext.hints !== '' ? { fromEarlierRuns: executorContext.hints } : {}),
364
356
  // M10 am7 item 3: a step that quotes a saved page is told the form of its answer and what each result must hold
365
357
  ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: citedBrief(stepMeta.cited) } : {}),
358
+ // M10b piece 2: a step that reads a sheet is told the shape of each claim box (bareguard's worked example), never the check
359
+ ...(stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? { answering: sheetBrief(stepMeta.sheet) } : {}),
366
360
  });
367
361
  const messages = [
368
362
  { role: 'system', content: systemPrompt },
package/src/pagedry.js CHANGED
@@ -1,4 +1,4 @@
1
- // borrowed-from: bareloop src/pagedry.js@c550dc8 (c61d227 + dryReadPhrases) (adapted: the REAL checker here is fwdloop's run-time `checkCited`, src/citedcheck.js, fed the fact exactly as it would be signed, `factsOfLook`).
1
+ // borrowed-from: bareloop src/pagedry.js@c550dc8 (c61d227 + dryReadPhrases; numberAtEnd shared from pagerules.js, bareloop @95f14b4) (adapted: the REAL checker here is fwdloop's run-time `checkCited`, src/citedcheck.js, fed the fact exactly as it would be signed, `factsOfLook`).
2
2
  // "CAN IT READ" (F241). After the page rules, a $0 dry read asks of each kept money fact whether the run-time checker can read a price on the page's own
3
3
  // result lines. For every result line it checks an HONEST claim (quote = that line, value = the line's amount) with `checkCited`, the one reader the run
4
4
  // itself uses - no copy of its logic here. A fact that reads no result line is dropped as `reads-no-result` and shows under Not checked.
@@ -6,13 +6,12 @@
6
6
  // No limits, no counts, no pass bar: only "can it read". No I/O, no clock, no model. The caller is src/pagelook.js `lookAtPage`.
7
7
 
8
8
  import { checkCited, factsOfLook } from './citedcheck.js';
9
- import { linesOf } from './pagerules.js';
9
+ import { linesOf, numberAtEnd } from './pagerules.js';
10
10
 
11
11
  /** @typedef {import('./pagerules.js').KeptFact} KeptFact @typedef {import('./pagerules.js').Dropped} Dropped */
12
12
 
13
13
  /** a number as the page writes it, thousands commas allowed: \d[\d,]*(?:\.\d+)? (written out as literals - this repo bans dynamic patterns in src/) */
14
14
  const AFTER_LABEL = /^\s*(?:[$€£]\s*)?(\d[\d,]*(?:\.\d+)?)/;
15
- const BEFORE_UNIT = /(\d[\d,]*(?:\.\d+)?)\s*$/;
16
15
  /** the name every dry-read claim is made under (the checker only needs one name; the fact's own is not read) */
17
16
  const CLAIM = 'price';
18
17
  const SOURCE = 'page';
@@ -37,7 +36,7 @@ export function moneyResultLines(text, k) {
37
36
  }
38
37
  } else {
39
38
  for (const u of k.unit ?? []) {
40
- for (let at = ln.indexOf(u); at !== -1 && amount === undefined; at = ln.indexOf(u, at + u.length)) amount = BEFORE_UNIT.exec(ln.slice(0, at))?.[1];
39
+ for (let at = ln.indexOf(u); at !== -1 && amount === undefined; at = ln.indexOf(u, at + u.length)) amount = numberAtEnd(ln.slice(0, at));
41
40
  if (amount !== undefined) break;
42
41
  }
43
42
  }
package/src/pagefetch.js CHANGED
@@ -1,4 +1,4 @@
1
- // borrowed-from: bareloop src/pagefetch.js@56dc096 (adapted: secret check uses src/redact.js)
1
+ // borrowed-from: bareloop src/pagefetch.js@56dc096 (adapted: secret check uses src/redact.js; TAG: bareloop src/labelscan.js@c59935e)
2
2
  // URL inputs (PART 1c, docs/product/ITEM33-BUILD.md "4. URL inputs" + live fix L1, PRD item 33 RF21/RF22): an Inputs line may be a web
3
3
  // address the person pastes (a results page). bareloop fetches it with barebrowse, READ ONLY, headless and incognito, as published:
4
4
  //
@@ -14,6 +14,13 @@ import { dirname, join } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { redactSecrets } from './redact.js';
16
16
 
17
+ /**
18
+ * The page reader's bracketed tag (`[ref=549]`). The lookahead and lookbehind add no match and drop no match: a `[` that sits inside the run of an earlier
19
+ * `[letters=` (no `]` or white space between) is skipped, because that earlier start reads the same run to the same end - it matches (and consumes this
20
+ * one) or fails (and so does this one). Without them "[a=[a=[a=..." with no `]` is quadratic.
21
+ */
22
+ const TAG = /\[(?=[A-Za-z]+=)(?<!\[[A-Za-z]+=[^\]\s]*?)[A-Za-z]+=[^\]\s]*\]/g;
23
+
17
24
  /** the session options (incognito: no auth ever enters; blockPrivateNetwork: SSRF guard); ONE frozen object so a test can pin them */
18
25
  export const CONNECT_OPTIONS = Object.freeze({ incognito: true, blockPrivateNetwork: true });
19
26
  /** the snapshot options step 0 proved */
@@ -73,7 +80,7 @@ export function pageContentChars(text) {
73
80
  skipIndent = -1;
74
81
  }
75
82
  if (m && CHROME_ROLES.has(m[2])) { skipIndent = indent; continue; }
76
- n += raw.replace(/\[[A-Za-z]+=[^\]\s]*\]/g, ' ').replace(/^\s*-\s*/, '').replace(/\s+/g, ' ').trim().length;
83
+ n += raw.replace(TAG, ' ').replace(/^\s*-\s*/, '').replace(/\s+/g, ' ').trim().length;
77
84
  }
78
85
  return n;
79
86
  }
package/src/pagerules.js CHANGED
@@ -1,5 +1,5 @@
1
- // borrowed-from: bareloop src/pagerules.js@1a0712b
2
- // Copy of bareloop's file; the three number patterns (BEFORE, AFTER, AFTER_CUR) are written as literals, not built from NUM (this repo bans dynamic patterns in src/); only the import lines point at fwdloop's src/pagebits.js (the pieces of facts.js, factwords.js, labelscan.js, rubricstep.js the rules need).
1
+ // borrowed-from: bareloop src/pagerules.js@1a0712b (numberAtEnd: @95f14b4)
2
+ // Copy of bareloop's file; the number patterns (AFTER, AFTER_CUR; BEFORE is numberAtEnd) are written as literals, not built from NUM (this repo bans dynamic patterns in src/); only the import lines point at fwdloop's src/pagebits.js (the pieces of facts.js, factwords.js, labelscan.js, rubricstep.js the rules need).
3
3
  // IDEA A CORE (docs/product/ITEM33-BUILD.md "Addendum 2026-10-18 — Idea A core: build spec", section 4.2): the plain code rules that
4
4
  // keep or drop each page word the AI's map named. The AI never grades: it names words, code keeps only what the saved page proves.
5
5
  // Pure - no I/O, no clock, no model. The rule bodies are PORTED from the frozen POC (scratch idea-a-v2/rules.mjs and
@@ -99,7 +99,30 @@ function valueSet(lines, label, shape) {
99
99
  const sameSet = (a, b) => a.size === b.size && [...a].every((x) => b.has(x));
100
100
 
101
101
  /** a number as the page writes it: digits, thousands commas, optional decimals (a currency sign next to it is not part of it) */
102
- const BEFORE = /(\d[\d,]*(?:\.\d+)?)\s*$/;
102
+ /**
103
+ * The number written at the very end of `s` (only whitespace after it): the leftmost match of NUM followed by `\s*$`. Shared with src/pagedry.js (one copy). Scans back from the end, so a
104
+ * long run of digits and commas costs O(n) where a backtracking regex is quadratic.
105
+ * @param {string} s @returns {string|undefined}
106
+ */
107
+ export function numberAtEnd(s) {
108
+ let e = s.length;
109
+ while (e > 0 && /\s/.test(s[e - 1])) e--;
110
+ /** the first digit of the digit/comma run ending at `end`, or -1 if the run holds none; a start never follows a digit, so it is the run's first digit */
111
+ const firstDigit = (/** @type {number} */ end) => {
112
+ let l = end;
113
+ while (l > 0 && /[\d,]/.test(s[l - 1])) l--;
114
+ while (l < end && s[l] === ',') l++;
115
+ return l < end ? l : -1;
116
+ };
117
+ let d = e;
118
+ while (d > 0 && /\d/.test(s[d - 1])) d--;
119
+ if (d < e && s[d - 1] === '.') {
120
+ const p = firstDigit(d - 1);
121
+ if (p !== -1) return s.slice(p, e);
122
+ }
123
+ const p = firstDigit(e);
124
+ return p === -1 ? undefined : s.slice(p, e);
125
+ }
103
126
  const AFTER = /^\s*(?:[$€£]\s*)?(\d[\d,]*(?:\.\d+)?)/;
104
127
  const AFTER_CUR = /^\s*(\d[\d,]*(?:\.\d+)?)/;
105
128
  const stripCommas = (/** @type {string} */ s) => s.replace(/,/g, '');
@@ -121,13 +144,13 @@ function beforeAfter(lines, label) {
121
144
  let B = 0;
122
145
  let A = 0;
123
146
  for (const [l, i] of occs(lines, label)) {
124
- if (BEFORE.test(l.slice(0, i))) B += 1;
147
+ if (numberAtEnd(l.slice(0, i)) !== undefined) B += 1;
125
148
  if (AFTER.test(l.slice(i + label.length))) A += 1;
126
149
  }
127
150
  return { B, A };
128
151
  }
129
152
  /** R1L: the numbers a UNIT form reads - the one right before each occurrence @param {string[]} lines @param {string} u @returns {Set<string>} */
130
- const unitSet = (lines, u) => new Set(occs(lines, u).map(([l, i]) => BEFORE.exec(l.slice(0, i))?.[1]).filter((v) => typeof v === 'string').map((v) => stripCommas(/** @type {string} */ (v))));
153
+ const unitSet = (lines, u) => new Set(occs(lines, u).map(([l, i]) => numberAtEnd(l.slice(0, i))).filter((v) => typeof v === 'string').map((v) => stripCommas(/** @type {string} */ (v))));
131
154
  /** R1L: the numbers a CURRENCY form reads - the one right after each occurrence @param {string[]} lines @param {string} c @returns {Set<string>} */
132
155
  const curSet = (lines, c) => new Set(occs(lines, c).map(([l, i]) => AFTER_CUR.exec(l.slice(i + c.length))?.[1]).filter((v) => typeof v === 'string').map((v) => stripCommas(/** @type {string} */ (v))));
133
156
 
@@ -49,6 +49,7 @@ import {
49
49
  appendAnswersToJob, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
50
50
  } from './authorcard.js';
51
51
  import { checkedLines, notCheckedView } from '../checked.js';
52
+ import { csvRolesOf } from '../sheetblock.js';
52
53
  import {
53
54
  readPriceConfig, resolveSlot, resolveUsableModel, tickedLines,
54
55
  } from '../provider.js';
@@ -296,7 +297,7 @@ export function createAuthor(opts) {
296
297
  const decl = readJson(dir, `${rel}/declaration.json`);
297
298
  const prose = readFileInside(dir, `${rel}/prose.txt`);
298
299
  const parsed = prose.ok ? parseSignedText(prose.text) : null;
299
- const opts = parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line) } : { hasAsk: true };
300
+ const opts = parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line), lines: parsed.lines, csvRoles: csvRolesOf(parsed.arbiter) } : { hasAsk: true };
300
301
  return { checked: checkedLines(decl, opts), notChecked: notCheckedView(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked, decl) };
301
302
  }
302
303
 
@@ -88,7 +88,8 @@ export function parseJobBox(text) {
88
88
  * M4e amendment 24 item 3: the submitted job box with each answer added WORD FOR WORD as a `~` line under the job line it is about, after
89
89
  * that line's own `~` lines (several answers for one line keep their order). The job box's own lines are untouched; the card -> prose path
90
90
  * (`cardToProse`) then writes the answer as that line's guardrail, so it reaches the signed text and the hash. Pure. An answer for a line
91
- * the box does not have is NOT added (the caller sees the count).
91
+ * the box does not have is NOT added (the caller sees the count). An answer equal (exact string, after trim) to a `~` rule already on that line is not added
92
+ * again, and still counts: it is taken, the line already says it.
92
93
  * @param {string} job @param {{ line: number, answer: string }[]} answers
93
94
  * @returns {{ job: string, added: number }}
94
95
  */
@@ -96,12 +97,15 @@ export function appendAnswersToJob(job, answers) {
96
97
  const raw = String(job).split('\n');
97
98
  /** @type {Map<number, number>} the index of the last non-empty box line that belongs to each step (its own line or a `~` under it) */
98
99
  const lastOf = new Map();
100
+ /** @type {Map<number, Set<string>>} the `~` rules each step already has */
101
+ const have = new Map();
99
102
  let step = 0;
100
103
  raw.forEach((l, i) => {
101
104
  const t = l.trim();
102
105
  if (t === '') return;
103
106
  if (!t.startsWith('~')) step += 1;
104
107
  if (step > 0) lastOf.set(step, i);
108
+ if (step > 0 && t.startsWith('~')) have.set(step, (have.get(step) ?? new Set()).add(t.slice(1).trim()));
105
109
  });
106
110
  /** @type {Map<number, string[]>} */
107
111
  const after = new Map();
@@ -109,8 +113,11 @@ export function appendAnswersToJob(job, answers) {
109
113
  for (const a of answers) {
110
114
  if (!lastOf.has(a.line)) continue;
111
115
  const at = /** @type {number} */ (lastOf.get(a.line));
112
- after.set(at, [...(after.get(at) ?? []), `~ ${a.answer}`]);
113
116
  added += 1;
117
+ const rules = have.get(a.line) ?? new Set();
118
+ if (rules.has(a.answer.trim())) continue;
119
+ have.set(a.line, rules.add(a.answer.trim()));
120
+ after.set(at, [...(after.get(at) ?? []), `~ ${a.answer}`]);
114
121
  }
115
122
  const out = [];
116
123
  raw.forEach((l, i) => { out.push(l); for (const g of after.get(i) ?? []) out.push(g); });