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 +31 -8
- package/package.json +1 -1
- package/src/ask.js +15 -1
- package/src/attemptdiff.js +118 -0
- package/src/audit-fold.js +2 -0
- package/src/authoring.js +32 -2
- package/src/citedwords.js +36 -2
- package/src/config.js +5 -1
- package/src/drafter.js +6 -2
- package/src/flowmodel.js +56 -1
- package/src/learn.js +952 -0
- package/src/learnstore.js +346 -0
- package/src/model-step.js +2 -0
- package/src/pagedry.js +3 -4
- package/src/pagefetch.js +9 -2
- package/src/pagerules.js +28 -5
- package/src/panel/data.js +61 -13
- package/src/panel/index.html +143 -11
- package/src/redact.js +6 -6
- package/src/runner.js +127 -17
- package/src/thinking.js +11 -0
- package/types/ask.d.ts +7 -2
- package/types/attemptdiff.d.ts +38 -0
- package/types/citedwords.d.ts +14 -0
- package/types/drafter.d.ts +6 -1
- package/types/flowmodel.d.ts +36 -0
- package/types/learn.d.ts +576 -0
- package/types/learnstore.d.ts +168 -0
- package/types/pagerules.d.ts +7 -0
- package/types/panel/data.d.ts +2 -1
- package/types/panel/result.d.ts +1 -1
- package/types/runner.d.ts +11 -2
- package/types/thinking.d.ts +11 -0
|
@@ -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
|
@@ -351,6 +351,8 @@ export function makeLiveModelStep({
|
|
|
351
351
|
goal: executorContext.goal,
|
|
352
352
|
reads: executorContext.reads,
|
|
353
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 } : {}),
|
|
354
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
|
|
355
357
|
...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: citedBrief(stepMeta.cited) } : {}),
|
|
356
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
|
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 =
|
|
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(
|
|
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
|
|
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
|
-
|
|
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 (
|
|
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]) =>
|
|
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
|
|
package/src/panel/data.js
CHANGED
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
} from 'node:fs';
|
|
25
25
|
import { createHash } from 'node:crypto';
|
|
26
26
|
import { plainPlanCheck } from '../plain-checks.js';
|
|
27
|
-
import { join,
|
|
27
|
+
import { join, sep } from 'node:path';
|
|
28
28
|
|
|
29
29
|
import {
|
|
30
30
|
readFlow, readPlan, readRunPlan, readRunJobCopy, listFlowNames, listRunIds, resolveRunDir, checkFlowName, readFileInside, readdirInside,
|
|
@@ -38,6 +38,7 @@ import {
|
|
|
38
38
|
import { readSpendRows } from '../provider.js';
|
|
39
39
|
import { applyRunValues, parseWaitMs, pickRunValues, VALUES_FILE_RE } from '../runvalues.js';
|
|
40
40
|
import { readSetup } from '../setup.js';
|
|
41
|
+
import { parseHintBlock } from '../learn.js';
|
|
41
42
|
import { checkedLines, notCheckedView, NOT_CHECKED_LABEL } from '../checked.js';
|
|
42
43
|
import { csvRolesOf, askSheetCard } from '../sheetblock.js';
|
|
43
44
|
import { readSheetChecks } from '../sheet-record.js';
|
|
@@ -45,9 +46,9 @@ import {
|
|
|
45
46
|
NO_COPY_SAY, catchUpWords, endedLineWords, endedWords, needsLeftWords, nextInWords, nextTimeWords, scheduleAuditWords, scheduleBlockWords, scheduleFieldWords, scheduledNextFor, scheduledWords, startedWords,
|
|
46
47
|
} from '../summary-words.js';
|
|
47
48
|
import { MAX_STRUCTURE_RETRIES } from '../drafter.js';
|
|
48
|
-
import { isResultRun, checkTypeOf, buildResult, downloadOf } from './result.js';
|
|
49
|
+
import { isResultRun, checkTypeOf, buildResult, downloadOf, readCitedChecks } from './result.js';
|
|
49
50
|
import { thinkingRuleWords, thinkingTryWords } from '../thinking.js';
|
|
50
|
-
import { readRunThinking } from '../flowmodel.js';
|
|
51
|
+
import { readRunThinking, readLearningsRecord } from '../flowmodel.js';
|
|
51
52
|
import {
|
|
52
53
|
isTryRow, loadDiaries, deriveFold, cardLine, summaryLines,
|
|
53
54
|
} from '../audit-fold.js';
|
|
@@ -1286,14 +1287,27 @@ export function needsYouOf({
|
|
|
1286
1287
|
}
|
|
1287
1288
|
|
|
1288
1289
|
/**
|
|
1289
|
-
* M11
|
|
1290
|
+
* M11 am22: the ONE read of "does this run offer Reopen": the first of its asks `reopenOffer` (the Ask tab's own rule) says yes to, else null.
|
|
1291
|
+
* The Run tab's `reopen`, Needs you's Reopen tag (`reopenableAt`) and the Ask tab's per-ask `reopen` all come from `reopenOffer`, never a second rule.
|
|
1290
1292
|
* @param {string} runDir @param {any} ctx `loadRunContext`'s result
|
|
1293
|
+
* @returns {{askId: string, waitMs: number, late: boolean, why: string}|null}
|
|
1291
1294
|
*/
|
|
1292
|
-
function
|
|
1295
|
+
function runReopenOffer(runDir, ctx) {
|
|
1293
1296
|
if (ctx.historyRow || !ctx.askJson) return null;
|
|
1294
1297
|
const savedAskId = readSavedAnswer(runDir)?.askId;
|
|
1295
|
-
const
|
|
1296
|
-
|
|
1298
|
+
for (const a of runAsksInOrder(runDir, false)) {
|
|
1299
|
+
const offer = reopenOffer(a, ctx.askJson, ctx.resume, savedAskId === a.askId);
|
|
1300
|
+
if (offer !== null) return { askId: a.askId, ...offer };
|
|
1301
|
+
}
|
|
1302
|
+
return null;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
/**
|
|
1306
|
+
* M11 am11 item 2: the expiry time of this run's ask when it has expired and can still be reopened (the Ask tab's own `reopenOffer` rule), else null.
|
|
1307
|
+
* @param {string} runDir @param {any} ctx `loadRunContext`'s result
|
|
1308
|
+
*/
|
|
1309
|
+
function reopenableAt(runDir, ctx) {
|
|
1310
|
+
return runReopenOffer(runDir, ctx) !== null && typeof ctx.askJson.expiresAt === 'string' ? ctx.askJson.expiresAt : null;
|
|
1297
1311
|
}
|
|
1298
1312
|
|
|
1299
1313
|
/**
|
|
@@ -1768,6 +1782,8 @@ export function getRunDetail({
|
|
|
1768
1782
|
signWords: SIGN_WORDS,
|
|
1769
1783
|
pulse: glyphPulses({ glyph, label }),
|
|
1770
1784
|
controls: runControls(ctx, glyph, label),
|
|
1785
|
+
// M11 am22: the Run tab's Reopen, the Ask tab's own `reopenOffer` answer (`{askId, waitMs, late, why}`), or null
|
|
1786
|
+
reopen: runReopenOffer(run.runDir, ctx),
|
|
1771
1787
|
// M11 am11 item 3: where this run stands in Needs you now; the page shows Remove from Needs you only when `removable`
|
|
1772
1788
|
needsYou: (({ tag, removable }) => ({ tag, removable }))(needsYouOf({
|
|
1773
1789
|
runDir: run.runDir, ctx, glyph, controls: runControls(ctx, glyph, label), nowMs: now(), reopenAt: reopenableAt(run.runDir, ctx),
|
|
@@ -1967,7 +1983,7 @@ function attachFolds(groups, runDir, flowDir, { root, flow, catalogue }) {
|
|
|
1967
1983
|
* shared-sidecar contamination risk here the way bareloop's gate-audit
|
|
1968
1984
|
* sidecar had). `null` when the flow/runId doesn't resolve (404).
|
|
1969
1985
|
* @param {{root: string, flow: string, runId: string, scheduleRead?: (flow: string) => any, home?: string, catalogue?: any, resumeAttempt?: (flow: string, runId: string) => any, startingRun?: (flow: string, runId: string) => boolean, now?: () => number}} opts
|
|
1970
|
-
* @returns {{flow:string, runId:string, rows:any[], groups:any[], draft:ReturnType<typeof getDraftBlock>, needsLeft: string|null, schedule: ReturnType<typeof scheduleAuditWords>, empty:boolean, why:string|null}|null}
|
|
1986
|
+
* @returns {{flow:string, runId:string, rows:any[], groups:any[], draft:ReturnType<typeof getDraftBlock>, learnings: any[], needsLeft: string|null, schedule: ReturnType<typeof scheduleAuditWords>, empty:boolean, why:string|null}|null}
|
|
1971
1987
|
*/
|
|
1972
1988
|
export function getRunAudit({
|
|
1973
1989
|
root, flow, runId, scheduleRead, home, catalogue, resumeAttempt, startingRun, now = Date.now,
|
|
@@ -1995,6 +2011,9 @@ export function getRunAudit({
|
|
|
1995
2011
|
// never a second, client-side re-grouping.
|
|
1996
2012
|
groups,
|
|
1997
2013
|
draft: getDraftBlock(run.flowDir, run.runDir),
|
|
2014
|
+
// M8 item 6: what the planner was told from earlier runs, READ-ONLY (borrowed-from: bareloop src/panel/server.js@v0.46.0:1854): the exact block as the run's record kept it, `hints` = the same text split
|
|
2015
|
+
// into fields by learn.js's parseHintBlock (the one reader). Empty (no box) when the run was handed nothing: no record, or a run that reused its plan.
|
|
2016
|
+
learnings: (() => { const rec = readLearningsRecord(run.runDir); return rec === null ? [] : [{ phase: rec.phase, text: rec.text, chars: rec.text.length, ids: rec.ids, hints: parseHintBlock(rec.text) }]; })(),
|
|
1998
2017
|
// M11 am11 items 3-4: the one row that says why the card left Needs you (by your Remove, or after 7 days); words: src/summary-words.js
|
|
1999
2018
|
needsLeft: catalogue ? needsLeftWords(getRunNeeds({
|
|
2000
2019
|
root, flow, runId, catalogue, nowMs: now(), resumeAttempt,
|
|
@@ -2135,11 +2154,10 @@ export function getRunJob({
|
|
|
2135
2154
|
asks: asks.map((ak) => ({ line: ak.line, question: ak.question, waitMs: ak.ttlMs })),
|
|
2136
2155
|
capUsd: typeof a.capUsd === 'number' ? a.capUsd : null,
|
|
2137
2156
|
redoCap: typeof a.redoCap === 'number' ? a.redoCap : null,
|
|
2138
|
-
// review #5: "
|
|
2139
|
-
//
|
|
2140
|
-
// "to be safe" instruction).
|
|
2157
|
+
// review #5: "Inputs" — role -> the full signed path (a web address
|
|
2158
|
+
// shows its address), by hamr 2026-10-24.
|
|
2141
2159
|
sources: sources.map((s) => ({
|
|
2142
|
-
role: s.role, kind: s.kind, path: s.path,
|
|
2160
|
+
role: s.role, kind: s.kind, path: s.path,
|
|
2143
2161
|
})),
|
|
2144
2162
|
// review #5: "Destination" — one row per send.
|
|
2145
2163
|
sends: sends.map((s) => ({ line: s.line, kind: s.target?.kind ?? null, target: s.target?.path ?? null })),
|
|
@@ -2341,6 +2359,7 @@ function flattenEvidence(evidence) {
|
|
|
2341
2359
|
unjudged: evidence.unjudged,
|
|
2342
2360
|
why: evidence.why,
|
|
2343
2361
|
...(evidence.claims ? { claims: evidence.claims } : {}),
|
|
2362
|
+
...(evidence.results ? { results: evidence.results } : {}),
|
|
2344
2363
|
};
|
|
2345
2364
|
}
|
|
2346
2365
|
|
|
@@ -2637,6 +2656,28 @@ export function groupAskBlocks(asks) {
|
|
|
2637
2656
|
});
|
|
2638
2657
|
}
|
|
2639
2658
|
|
|
2659
|
+
/**
|
|
2660
|
+
* The Result tab's facts line for the results an ask carries (`{quote, values}` each). The run's cited-check record (src/panel/result.js `readCitedChecks`) is the
|
|
2661
|
+
* source when one of its lines holds exactly these quotes: its facts, cells and proof are drawn. Without one (an old run, a record that does not read), the line is
|
|
2662
|
+
* built from the ask's own values: one fact per value name, no proof, never a guess.
|
|
2663
|
+
* @param {{quote: string, values: Record<string, unknown>}[]} results @param {ReturnType<typeof readCitedChecks>|null} record
|
|
2664
|
+
* @returns {{kind: 'facts', passed: boolean, facts: any[], rows: any[]}}
|
|
2665
|
+
*/
|
|
2666
|
+
function citedLineOfResults(results, record) {
|
|
2667
|
+
const quotes = results.map((r) => r.quote);
|
|
2668
|
+
const line = record && record.present && record.ok
|
|
2669
|
+
? record.lines.find((l) => l.rows && l.rows.length === quotes.length && l.rows.every((w, i) => w.quote === quotes[i]))
|
|
2670
|
+
: undefined;
|
|
2671
|
+
if (line) return { kind: 'facts', passed: line.passed, facts: line.facts, rows: line.rows };
|
|
2672
|
+
const names = [...new Set(results.flatMap((r) => Object.keys(r.values)))];
|
|
2673
|
+
return {
|
|
2674
|
+
kind: 'facts',
|
|
2675
|
+
passed: false,
|
|
2676
|
+
facts: names.map((name) => ({ name, kind: 'value', sentence: `fact · ${name}` })),
|
|
2677
|
+
rows: results.map((r, i) => ({ n: i + 1, quote: r.quote, cells: names.map((k) => (r.values[k] === undefined ? '' : String(r.values[k]))) })),
|
|
2678
|
+
};
|
|
2679
|
+
}
|
|
2680
|
+
|
|
2640
2681
|
/**
|
|
2641
2682
|
* `GET /api/runs/:flow/:runId/asks` — the Ask tab (M4a-1 scope item 1):
|
|
2642
2683
|
* every ask this run's books can name, in order, each carrying full
|
|
@@ -2701,7 +2742,14 @@ export function getRunAsks({
|
|
|
2701
2742
|
const { why: _gone, ...rest } = ev;
|
|
2702
2743
|
return { ...ask, evidence: { ...rest, sheet: card } };
|
|
2703
2744
|
};
|
|
2704
|
-
|
|
2745
|
+
// a cited step's ask: its results drawn by the Result tab's own line (the run's cited-check record, matched by the quotes; else the quotes and values alone)
|
|
2746
|
+
const cited = ordered.some((a) => a.evidence?.results) ? readCitedChecks(run.runDir) : null;
|
|
2747
|
+
const withCited = (/** @type {any} */ ask) => {
|
|
2748
|
+
const { results, ...ev } = ask.evidence ?? {};
|
|
2749
|
+
if (!results) return ask;
|
|
2750
|
+
return { ...ask, evidence: { ...ev, cited: citedLineOfResults(results, cited) } };
|
|
2751
|
+
};
|
|
2752
|
+
const asks = ordered.map(withSheet).map(withCited).map((ask, i) => ({
|
|
2705
2753
|
...ask,
|
|
2706
2754
|
...deriveAskOpenFields(ask, hasHistoryRow, resume),
|
|
2707
2755
|
reopen: reopenOffer(ask, openAskJson, resume, readSavedAnswer(run.runDir)?.askId === ask.askId),
|