fwdloop 0.23.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/fwdloop +62 -32
- 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/cited-record.js +3 -22
- package/src/cited-source.js +5 -6
- package/src/citedwords.js +36 -2
- package/src/config.js +5 -1
- package/src/diary.js +21 -17
- package/src/drafter.js +6 -2
- package/src/flowmodel.js +52 -28
- package/src/keysfile.js +1 -1
- package/src/launcher.js +552 -0
- package/src/learn.js +952 -0
- package/src/learnstore.js +348 -0
- package/src/line-checks.js +55 -0
- package/src/model-step.js +2 -0
- package/src/opener.js +33 -0
- package/src/pagedry.js +3 -4
- package/src/pagefetch.js +9 -2
- package/src/pagerules.js +28 -5
- package/src/panel/author.js +2 -0
- package/src/panel/authorflows.js +9 -9
- package/src/panel/authorresume.js +4 -3
- package/src/panel/data.js +63 -14
- package/src/panel/index.html +162 -16
- package/src/panel/result.js +7 -12
- package/src/panel/server.js +53 -5
- package/src/panel/settings.js +4 -18
- package/src/panel/spawn.js +0 -9
- package/src/prompts.js +33 -0
- package/src/redact.js +6 -6
- package/src/runfile.js +60 -0
- package/src/runner.js +144 -33
- package/src/sheet-record.js +15 -35
- package/src/sheetblock.js +3 -3
- package/src/sheetrun.js +6 -6
- package/src/summary-words.js +13 -5
- package/src/thinking.js +11 -0
- package/src/tty-colour.js +29 -0
- package/types/ask.d.ts +7 -2
- package/types/attemptdiff.d.ts +38 -0
- package/types/cited-record.d.ts +0 -2
- package/types/citedwords.d.ts +14 -0
- package/types/diary.d.ts +2 -5
- package/types/drafter.d.ts +6 -1
- package/types/flowmodel.d.ts +37 -20
- package/types/keysfile.d.ts +7 -0
- package/types/launcher.d.ts +307 -0
- package/types/learn.d.ts +576 -0
- package/types/learnstore.d.ts +168 -0
- package/types/line-checks.d.ts +26 -0
- package/types/opener.d.ts +12 -0
- package/types/pagerules.d.ts +7 -0
- package/types/panel/author.d.ts +2 -0
- package/types/panel/data.d.ts +2 -1
- package/types/panel/result.d.ts +2 -4
- package/types/panel/server.d.ts +24 -3
- package/types/panel/settings.d.ts +2 -2
- package/types/panel/spawn.d.ts +0 -6
- package/types/prompts.d.ts +14 -0
- package/types/runfile.d.ts +48 -0
- package/types/runner.d.ts +14 -5
- package/types/sheet-record.d.ts +0 -2
- package/types/sheetblock.d.ts +2 -2
- package/types/sheetrun.d.ts +1 -1
- package/types/summary-words.d.ts +2 -1
- package/types/thinking.d.ts +11 -0
- package/types/tty-colour.d.ts +33 -0
|
@@ -0,0 +1,348 @@
|
|
|
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 diary.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. F83 bug 2: learnAtRunEnd (the one run-end and seed path) folds with specHash null, so a lesson matches by workflow name alone, the same as the read side (M8 am7 item 1; a redraft's new plan hash no longer opens a new row); its `specHash` argument is accepted and unused. 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 { readRunInputs } from './runfile.js';
|
|
18
|
+
import { readFileInside, readdirInside, listFlowNames, listRunIds } from './flow.js';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 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
|
|
22
|
+
* 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
|
|
23
|
+
* home folder (`path.resolve` alone would make it `<cwd>/~/...`); then `path.resolve` (lexical, no fs: the F48 guard keeps realpathSync out of this file).
|
|
24
|
+
* A web address stays its host (placeOf). Not copied from bareloop: this is the fwdloop-only part of the place.
|
|
25
|
+
* @param {string} p @returns {string}
|
|
26
|
+
*/
|
|
27
|
+
export function resolvePlace(p) {
|
|
28
|
+
return resolve(p === '~' || p.startsWith('~/') ? join(homedir(), p.slice(1)) : p);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 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`,
|
|
33
|
+
* 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
|
|
34
|
+
* drafter's hints (src/authoring.js) all build their spec here. No source (a job with no file input) is no place.
|
|
35
|
+
* @param {string} job the workflow name
|
|
36
|
+
* @param {string|null|undefined} source the run's first input as it reads it
|
|
37
|
+
* @returns {{job: string, inputs: {value: string}[]}}
|
|
38
|
+
*/
|
|
39
|
+
export function placeSpecOf(job, source) {
|
|
40
|
+
return { job, inputs: typeof source === 'string' && source !== '' ? [{ value: source }] : [] };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* `<configHome>/learn/ledger.json`. Under a test process (NODE_ENV=test or node --test) the home is the explicit one or
|
|
45
|
+
* FWDLOOP_CONFIG_HOME; with neither it THROWS rather than fall back to the real ~/.config/fwdloop.
|
|
46
|
+
* @param {string} [home] test seam; production never passes it
|
|
47
|
+
* @returns {string}
|
|
48
|
+
*/
|
|
49
|
+
export function ledgerPath(home) {
|
|
50
|
+
if (home === undefined) {
|
|
51
|
+
const door = configDoorHome();
|
|
52
|
+
if (door.skip) throw new Error('learnings ledger: a test process has no config home (set FWDLOOP_CONFIG_HOME or pass one)');
|
|
53
|
+
home = door.home;
|
|
54
|
+
}
|
|
55
|
+
return join(configHome(home), 'learn', 'ledger.json');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Read the ledger. A missing file is an empty ledger; an unreadable or wrong-shaped one is reported as `problem` (and the
|
|
60
|
+
* writer then refuses to replace it: an append-only record is never silently reset).
|
|
61
|
+
* @param {string} [home]
|
|
62
|
+
* @returns {{ledger: import('./learn.js').Ledger, exists: boolean, problem: string|null}}
|
|
63
|
+
*/
|
|
64
|
+
export function readLedger(home) {
|
|
65
|
+
const file = ledgerPath(home);
|
|
66
|
+
if (!existsSync(file)) return { ledger: emptyLedger(), exists: false, problem: null };
|
|
67
|
+
try {
|
|
68
|
+
const d = JSON.parse(readFileSync(file, 'utf8'));
|
|
69
|
+
if (!d || typeof d !== 'object' || d.version !== 1 || !Array.isArray(d.rows) || !Array.isArray(d.pending)) {
|
|
70
|
+
return { ledger: emptyLedger(), exists: true, problem: `${file} is not a version-1 learnings ledger — fix or remove it` };
|
|
71
|
+
}
|
|
72
|
+
return { ledger: { ...emptyLedger(), ...d }, exists: true, problem: null };
|
|
73
|
+
} catch (/** @type {any} */ e) {
|
|
74
|
+
return { ledger: emptyLedger(), exists: true, problem: `${file} is not readable JSON (${e?.code ?? 'parse error'}) — fix or remove it` };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Write the ledger atomically (temp + rename, mode 600), every string masked through the one secret inventory.
|
|
80
|
+
* @param {import('./learn.js').Ledger} ledger @param {string} [home]
|
|
81
|
+
* @returns {string} the file written
|
|
82
|
+
*/
|
|
83
|
+
export function writeLedger(ledger, home) {
|
|
84
|
+
const file = ledgerPath(home);
|
|
85
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
86
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
87
|
+
writeFileSync(tmp, `${JSON.stringify(redactDeep(ledger), null, 1)}\n`, { mode: 0o600 });
|
|
88
|
+
chmodSync(tmp, 0o600);
|
|
89
|
+
renameSync(tmp, file);
|
|
90
|
+
return file;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Fold ONE finished run into the ledger on disk: every run's cards COUNT now, rubric jobs too (trust kept on new rows;
|
|
95
|
+
* 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.
|
|
96
|
+
* @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
|
|
97
|
+
* @returns {{wrote: boolean, counted: number, held: number, problem: string|null}}
|
|
98
|
+
*/
|
|
99
|
+
export function foldRunIntoLedger({ home, runid, build, workflow, place, specHash, trust, at, now = new Date() }) {
|
|
100
|
+
const cur = readLedger(home);
|
|
101
|
+
if (cur.problem) return { wrote: false, counted: 0, held: 0, problem: cur.problem };
|
|
102
|
+
let L = cur.ledger;
|
|
103
|
+
const before = L.rows.reduce((n, r) => n + r.runIds.filter((x) => x === runid).length, 0);
|
|
104
|
+
L = countLedger(L, { runid, cards: build.cards, workflow, place, specHash, trust, now });
|
|
105
|
+
const counted = L.rows.reduce((n, r) => n + r.runIds.filter((x) => x === runid).length, 0) - before;
|
|
106
|
+
L = recordHealth(L, runid, build, at, now);
|
|
107
|
+
writeLedger(L, home);
|
|
108
|
+
return { wrote: true, counted, held: 0, problem: null };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 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).
|
|
113
|
+
* @param {{home?: string, runid: string, now?: Date}} o
|
|
114
|
+
* @returns {{released: number, problem: string|null}}
|
|
115
|
+
*/
|
|
116
|
+
export function releaseRun({ home, runid, now = new Date() }) {
|
|
117
|
+
const cur = readLedger(home);
|
|
118
|
+
if (cur.problem) return { released: 0, problem: cur.problem };
|
|
119
|
+
const r = releasePending(cur.ledger, runid, now);
|
|
120
|
+
if (r.ledger !== cur.ledger) writeLedger(r.ledger, home);
|
|
121
|
+
return { released: r.released, problem: null };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* M8 am1: the ONE setting, `learningHints` in config.json. Ships OFF (absent = off). OFF still writes the tally ($0); the drafter
|
|
126
|
+
* is simply handed nothing. Copied from bareloop learnstore.js@v0.47.0:96 (borrowed-from header above). Difference: bareloop's
|
|
127
|
+
* `readConfig` returns a problem, fwdloop's THROWS ConfigError on an unreadable / non-JSON / invalid file. The safe reading is kept:
|
|
128
|
+
* a bad or unreadable config reads as OFF (never ON). Under a test process with no explicit home and no FWDLOOP_CONFIG_HOME it
|
|
129
|
+
* reads nothing (OFF), so a test can never reach the real ~/.config/fwdloop.
|
|
130
|
+
* @param {string} [home]
|
|
131
|
+
* @returns {boolean}
|
|
132
|
+
*/
|
|
133
|
+
export function learningHintsOn(home) {
|
|
134
|
+
let h = home;
|
|
135
|
+
if (h === undefined) {
|
|
136
|
+
const door = configDoorHome();
|
|
137
|
+
if (door.skip) return false;
|
|
138
|
+
h = door.home;
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
return readConfig({ home: h }).learningHints === true;
|
|
142
|
+
} catch {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ── the run-end tally (M8 items 2 and 4) ─────────────────────────────────────────────────────────
|
|
148
|
+
|
|
149
|
+
/** 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] */
|
|
150
|
+
function unifiedDiff(a, b, ctx = 1) {
|
|
151
|
+
const A = a === '' ? [] : a.split('\n');
|
|
152
|
+
const B = b.split('\n');
|
|
153
|
+
const n = A.length;
|
|
154
|
+
const m = B.length;
|
|
155
|
+
const L = Array.from({ length: n + 1 }, () => new Int32Array(m + 1));
|
|
156
|
+
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]);
|
|
157
|
+
/** @type {Array<[string, string]>} */
|
|
158
|
+
const ops = [];
|
|
159
|
+
let i = 0;
|
|
160
|
+
let j = 0;
|
|
161
|
+
while (i < n && j < m) {
|
|
162
|
+
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; }
|
|
163
|
+
}
|
|
164
|
+
while (i < n) { ops.push(['-', A[i]]); i += 1; }
|
|
165
|
+
while (j < m) { ops.push(['+', B[j]]); j += 1; }
|
|
166
|
+
const keep = ops.map(() => false);
|
|
167
|
+
ops.forEach((o, k) => { if (o[0] !== ' ') for (let d = -ctx; d <= ctx; d += 1) if (ops[k + d]) keep[k + d] = true; });
|
|
168
|
+
/** @type {string[]} */
|
|
169
|
+
const out = [];
|
|
170
|
+
let ai = 1;
|
|
171
|
+
let bi = 1;
|
|
172
|
+
const pos = ops.map((o) => { const p = [ai, bi]; if (o[0] !== '+') ai += 1; if (o[0] !== '-') bi += 1; return p; });
|
|
173
|
+
let k = 0;
|
|
174
|
+
while (k < ops.length) {
|
|
175
|
+
if (!keep[k]) { k += 1; continue; }
|
|
176
|
+
let e = k;
|
|
177
|
+
while (e < ops.length && keep[e]) e += 1;
|
|
178
|
+
const seg = ops.slice(k, e);
|
|
179
|
+
out.push(`@@ -${pos[k][0]},${seg.filter((o) => o[0] !== '+').length} +${pos[k][1]},${seg.filter((o) => o[0] !== '-').length} @@`);
|
|
180
|
+
for (const [c, t] of seg) out.push(c + t);
|
|
181
|
+
k = e;
|
|
182
|
+
}
|
|
183
|
+
return out.join('\n');
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** @param {string} runDir @param {string} rel @returns {any} the parsed JSON file inside the run folder, or null when absent / unreadable */
|
|
187
|
+
function jsonIn(runDir, rel) {
|
|
188
|
+
const r = readFileInside(runDir, rel);
|
|
189
|
+
if (!r.ok) return null;
|
|
190
|
+
try { return JSON.parse(r.text); } catch { return null; }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 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. */
|
|
194
|
+
const isTry = (/** @type {any} */ r) => Number.isInteger(r.attempt) && ['green', 'hitl', 'softgreen', 'red', 'not-done'].includes(r.verdict) && !(r.class === 'hitl' && r.verdict === 'red');
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* One finished run's folder -> the event list buildCards reads, plus the check texts and the model. ONE adapter, map never invent
|
|
198
|
+
* (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
|
|
199
|
+
* verbatim = B1's flagged line); a later try of the same check that is not red = the pass; Fix touched = `artifacts/<step>.json`;
|
|
200
|
+
* 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.
|
|
201
|
+
* Refused drafts make no run folder, and a human redo is not a try (isTry), so neither makes a note.
|
|
202
|
+
* @param {string} runDir @param {string} workflow
|
|
203
|
+
* @returns {{events: any[], questions: Map<string, string|null>, model: string|null, source: string|null}|null} null when the run has no try
|
|
204
|
+
*/
|
|
205
|
+
export function eventsOfRun(runDir, workflow) {
|
|
206
|
+
const audit = readAudit(runDir);
|
|
207
|
+
const rows = audit.filter(isTry);
|
|
208
|
+
if (!rows.length) return null;
|
|
209
|
+
const log = jsonIn(runDir, 'log.json') ?? {};
|
|
210
|
+
const decl = jsonIn(runDir, 'job/declaration.json') ?? { steps: [] };
|
|
211
|
+
const frozen = readRunInputs(runDir);
|
|
212
|
+
const inputs = frozen.ok ? frozen.entries : null;
|
|
213
|
+
const prose = (() => { const r = readFileInside(runDir, 'job/prose.txt'); return r.ok ? r.text : ''; })();
|
|
214
|
+
const checks = readChecks(runDir);
|
|
215
|
+
const made = new Set(readdirInside(runDir, 'artifacts'));
|
|
216
|
+
const outBy = new Map((log.attempts || []).map((/** @type {any} */ a) => [`${a.step}#${a.attempt}`, a.modelOutput]));
|
|
217
|
+
const lastAt = audit.at(-1)?.at ?? '1970-01-01T00:00:00.000Z';
|
|
218
|
+
const model = audit.find((r) => typeof r.model === 'string')?.model ?? null;
|
|
219
|
+
const stepMeta = new Map((decl.steps || []).map((/** @type {any} */ s) => [s.emits, s]));
|
|
220
|
+
/** @type {Map<string, string|null>} */
|
|
221
|
+
const questions = new Map();
|
|
222
|
+
/** @type {any[]} */
|
|
223
|
+
const events = [];
|
|
224
|
+
let seq = 0;
|
|
225
|
+
let ts = audit[0]?.at ?? lastAt;
|
|
226
|
+
const push = (/** @type {any} */ e) => events.push({ seq: (seq += 1), ts, ...e });
|
|
227
|
+
push({ type: 'job-start', job: workflow, goal: prose.split(/\n\s*\n/)[0].trim(), model });
|
|
228
|
+
push({ type: 'plan-accepted', plan: { steps: (decl.steps || []).map((/** @type {any} */ s) => ({ id: s.emits, action: s.goal })) } });
|
|
229
|
+
/** @type {Map<string, string>} */
|
|
230
|
+
const prevOut = new Map();
|
|
231
|
+
for (const a of rows) {
|
|
232
|
+
ts = a.at ?? ts;
|
|
233
|
+
const meta = /** @type {any} */ (stepMeta.get(a.step));
|
|
234
|
+
const name = `${a.step} (line ${meta?.fromLine ?? '?'}, ${a.class})`;
|
|
235
|
+
push({ type: 'step-start', step: a.step });
|
|
236
|
+
push({ type: 'iteration-start' });
|
|
237
|
+
const mo = outBy.get(`${a.step}#${a.attempt}`);
|
|
238
|
+
let diff = '';
|
|
239
|
+
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); }
|
|
240
|
+
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 });
|
|
241
|
+
if ((a.verdict === 'red' || a.verdict === 'not-done') && typeof a.gap === 'string' && a.gap !== '') {
|
|
242
|
+
const f = checks.find((c) => c.step === a.step && c.try === a.attempt)?.checks?.find((/** @type {any} */ x) => !x.ok);
|
|
243
|
+
if (f && !questions.has(name)) questions.set(name, String(f.text));
|
|
244
|
+
push({ type: 'exit-eval', step: a.step, results: [{ type: name, pass: false, detail: a.gap }] });
|
|
245
|
+
} else {
|
|
246
|
+
push({ type: 'exit-eval', step: a.step, results: [{ type: name, pass: true }] });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
ts = lastAt;
|
|
250
|
+
// M8 am4 item 3: the two noise categories bareloop's buildCards reads off an `escalation` event, seen here in the audit: a provider red
|
|
251
|
+
// (verdict 'provider-red', the transport fault twice) and a closer that crashed or was unparseable (verdict 'close-casualty'). Both end
|
|
252
|
+
// 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.
|
|
253
|
+
const noiseRow = audit.findLast((r) => r.verdict === 'provider-red' || r.verdict === 'close-casualty');
|
|
254
|
+
if (noiseRow) push({ type: 'escalation', category: noiseRow.verdict === 'provider-red' ? 'provider-red' : 'close-crashed' });
|
|
255
|
+
push({ type: 'job-end', outcome: log.outcome === 'complete' ? 'green' : String(log.outcome) });
|
|
256
|
+
return { events, questions, model, source: typeof inputs?.[0]?.source === 'string' ? inputs[0].source : null };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* 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.
|
|
261
|
+
* 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
|
|
262
|
+
* 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
|
|
263
|
+
* the run's diary.jsonl, so a check with no checks row there (a run from before am29) has no `meaning`.
|
|
264
|
+
* Borrowed-from: bareloop src/learnstore.js@v0.47.0:124 (learnAtRunEnd).
|
|
265
|
+
* @param {{home?: string, workflow: string, runId: string, runDir: string, specHash: string|null, now?: Date}} o
|
|
266
|
+
* @returns {{wrote: boolean, counted: number, held: number, problem: string|null, noise: string|null, cards: number}}
|
|
267
|
+
*/
|
|
268
|
+
export function learnAtRunEnd({ home, workflow, runId, runDir, specHash, now = new Date() }) {
|
|
269
|
+
const rec = eventsOfRun(runDir, workflow);
|
|
270
|
+
if (!rec) return { wrote: false, counted: 0, held: 0, problem: null, noise: 'no-tries', cards: 0 };
|
|
271
|
+
const runid = `${workflow}/${runId}`;
|
|
272
|
+
const build = buildCards({ runid, events: rec.events, spec: { job: workflow }, model: rec.model, questions: rec.questions });
|
|
273
|
+
const at = rec.events.findLast((e) => e.type === 'job-end')?.ts ?? now.toISOString();
|
|
274
|
+
const r = foldRunIntoLedger({ home, runid, build, workflow, place: placeOf(placeSpecOf(workflow, rec.source), resolvePlace), specHash: null, trust: 'deterministic', at, now });
|
|
275
|
+
return { ...r, noise: build.noise, cards: build.cards.length };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** 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. */
|
|
279
|
+
export const NOT_A_RUN_END = new Set(['paused', 'stop-failed']);
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* 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
|
|
283
|
+
* (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
|
|
284
|
+
* 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.
|
|
285
|
+
* 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).
|
|
286
|
+
* Under a test process with no door nothing is read or written (`skippedNoDoor`).
|
|
287
|
+
* @param {{root: string, home?: string}} o `home` is a test seam; production leaves it out
|
|
288
|
+
* @returns {{read: number, added: number, skipped: Record<'already-in'|'still-waiting'|'no-end'|'unreadable'|'noise', number>, problem: string|null, skippedNoDoor: boolean}}
|
|
289
|
+
*/
|
|
290
|
+
export function seedLedger({ root, home }) {
|
|
291
|
+
/** @type {{read: number, added: number, skipped: Record<'already-in'|'still-waiting'|'no-end'|'unreadable'|'noise', number>, problem: string|null, skippedNoDoor: boolean}} */
|
|
292
|
+
const out = { read: 0, added: 0, skipped: { 'already-in': 0, 'still-waiting': 0, 'no-end': 0, unreadable: 0, noise: 0 }, problem: null, skippedNoDoor: false };
|
|
293
|
+
if (home === undefined) {
|
|
294
|
+
const door = configDoorHome();
|
|
295
|
+
if (door.skip) return { ...out, skippedNoDoor: true };
|
|
296
|
+
home = door.home;
|
|
297
|
+
}
|
|
298
|
+
/** @type {{workflow: string, runId: string, runDir: string, end: Date, specHash: string|null}[]} */
|
|
299
|
+
const todo = [];
|
|
300
|
+
for (const workflow of listFlowNames(root)) {
|
|
301
|
+
const flowDir = join(root, workflow);
|
|
302
|
+
/** @type {any[]|null} */
|
|
303
|
+
let history = null;
|
|
304
|
+
try { history = readHistory(flowDir); } catch { history = null; }
|
|
305
|
+
for (const runId of listRunIds(flowDir)) {
|
|
306
|
+
out.read += 1;
|
|
307
|
+
const runDir = join(flowDir, 'runs', runId);
|
|
308
|
+
try {
|
|
309
|
+
const log = jsonIn(runDir, 'log.json');
|
|
310
|
+
if (log && NOT_A_RUN_END.has(log.outcome)) { out.skipped['still-waiting'] += 1; continue; }
|
|
311
|
+
if (history === null) { out.skipped.unreadable += 1; continue; }
|
|
312
|
+
const endRow = history.findLast((r) => r?.runId === runId && !NOT_A_RUN_END.has(r.outcome) && Number.isFinite(Date.parse(r.at)));
|
|
313
|
+
if (!endRow) { out.skipped['no-end'] += 1; continue; }
|
|
314
|
+
if (!log) { out.skipped.unreadable += 1; continue; }
|
|
315
|
+
todo.push({ workflow, runId, runDir, end: new Date(endRow.at), specHash: typeof endRow.signatureHash === 'string' ? endRow.signatureHash : null });
|
|
316
|
+
} catch { out.skipped.unreadable += 1; }
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
todo.sort((a, b) => a.end.getTime() - b.end.getTime() || `${a.workflow}/${a.runId}`.localeCompare(`${b.workflow}/${b.runId}`));
|
|
320
|
+
for (const t of todo) {
|
|
321
|
+
const cur = readLedger(home);
|
|
322
|
+
if (cur.problem) { out.problem = cur.problem; return out; }
|
|
323
|
+
if (Object.hasOwn(cur.ledger.health, `${t.workflow}/${t.runId}`)) { out.skipped['already-in'] += 1; continue; }
|
|
324
|
+
try {
|
|
325
|
+
const r = learnAtRunEnd({ home, workflow: t.workflow, runId: t.runId, runDir: t.runDir, specHash: t.specHash, now: t.end });
|
|
326
|
+
if (r.problem) { out.problem = r.problem; return out; }
|
|
327
|
+
if (r.noise) out.skipped.noise += 1;
|
|
328
|
+
else out.added += r.counted;
|
|
329
|
+
} catch { out.skipped.unreadable += 1; }
|
|
330
|
+
}
|
|
331
|
+
return out;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* M8 item 5a: the block the DRAFTER is handed for this job, made from the ledger as it stood: null when `learningHints` is off,
|
|
336
|
+
* 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),
|
|
337
|
+
* never a second. Age (56 days), job version and level are worked out here, at read time, by renderHints.
|
|
338
|
+
* Borrowed-from: bareloop src/learnstore.js@v0.47.0:140 (hintsForRun). `spec` is `{job, inputs: [{value}]}` (job = the workflow name).
|
|
339
|
+
* @param {{home?: string, spec: any, specHash: string|null, now?: Date}} o
|
|
340
|
+
* @returns {{text: string, ids: string[]}|null}
|
|
341
|
+
*/
|
|
342
|
+
export function hintsForRun({ home, spec, specHash, now = new Date() }) {
|
|
343
|
+
if (!learningHintsOn(home)) return null;
|
|
344
|
+
const cur = readLedger(home);
|
|
345
|
+
if (cur.problem) throw new Error(cur.problem); // adapted: bareloop returns null here; the caller (authoring.js) hands nothing AND records why (item 4)
|
|
346
|
+
const r = renderHints(cur.ledger, { workflow: String(spec.job), place: placeOf(spec, resolvePlace), specHash, now });
|
|
347
|
+
return r.text ? r : null;
|
|
348
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// M8b item 3: `line-checks.json`, the run's check record - one file in the run's folder, two sections: `cited` (what each cited check said, per job line: written by
|
|
2
|
+
// `writeCitedLine`, src/cited-record.js) and `sheet` (what each sheet check said, per job line and try: written by `writeSheetLine`, src/sheet-record.js). Each section
|
|
3
|
+
// is `{ lines: [...] }`. THIS file is the one writer of the file (`writeLineSection`) and the one reader of it (`readLineSection`): each section's writer says only what
|
|
4
|
+
// its lines are. The write is a temporary file, then a rename, so a reader sees the old file or the new one; the other section is carried over untouched.
|
|
5
|
+
import { writeFileSync, renameSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { readFileInside } from './flow.js';
|
|
8
|
+
|
|
9
|
+
/** the record's name in the run's own folder */
|
|
10
|
+
export const LINE_CHECKS_FILE = 'line-checks.json';
|
|
11
|
+
|
|
12
|
+
/** @typedef {'cited'|'sheet'} LineSection */
|
|
13
|
+
|
|
14
|
+
const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
15
|
+
|
|
16
|
+
/** The whole file as parsed, or why not. @param {string} runDir @returns {{ok: true, rec: Record<string, any>}|{ok: false, missing: boolean, red: string}} */
|
|
17
|
+
function readWhole(runDir) {
|
|
18
|
+
const r = readFileInside(runDir, LINE_CHECKS_FILE);
|
|
19
|
+
if (!r.ok) return r.missing ? { ok: false, missing: true, red: `no ${LINE_CHECKS_FILE}` } : { ok: false, missing: false, red: r.red };
|
|
20
|
+
try {
|
|
21
|
+
const rec = JSON.parse(r.text);
|
|
22
|
+
return isRec(rec) ? { ok: true, rec } : { ok: false, missing: false, red: 'not a JSON object' };
|
|
23
|
+
} catch { return { ok: false, missing: false, red: 'not valid JSON' }; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* One section of the record: `{ok: true, lines}`, or `{ok: false, missing: true}` when the file or the section is not there, or `{ok: false, missing: false, red}` when
|
|
28
|
+
* the file (or the section) is not what it should be. Read through the safe gateway.
|
|
29
|
+
* @param {string} runDir @param {LineSection} section
|
|
30
|
+
* @returns {{ok: true, lines: any[]}|{ok: false, missing: true}|{ok: false, missing: false, red: string}}
|
|
31
|
+
*/
|
|
32
|
+
export function readLineSection(runDir, section) {
|
|
33
|
+
const whole = readWhole(runDir);
|
|
34
|
+
if (!whole.ok) return whole.missing ? { ok: false, missing: true } : { ok: false, missing: false, red: `${LINE_CHECKS_FILE}: ${whole.red}` };
|
|
35
|
+
if (!Object.hasOwn(whole.rec, section)) return { ok: false, missing: true };
|
|
36
|
+
const s = whole.rec[section];
|
|
37
|
+
return isRec(s) && Array.isArray(s.lines) ? { ok: true, lines: s.lines } : { ok: false, missing: false, red: `${LINE_CHECKS_FILE}: "${section}" has no list of "lines"` };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Change one section's lines and write the file: `change` gets the section's lines now (none when the section or the file is missing or unreadable: the record is started
|
|
42
|
+
* again, this function is its only writer) and returns the lines to keep, or null to write nothing. The other section is carried over as it is. Atomic.
|
|
43
|
+
* @param {string} runDir @param {LineSection} section @param {(lines: any[]) => any[]|null} change @returns {void}
|
|
44
|
+
*/
|
|
45
|
+
export function writeLineSection(runDir, section, change) {
|
|
46
|
+
const whole = readWhole(runDir);
|
|
47
|
+
const rec = whole.ok ? whole.rec : {};
|
|
48
|
+
const had = isRec(rec[section]) && Array.isArray(rec[section].lines) ? rec[section].lines : [];
|
|
49
|
+
const lines = change(had);
|
|
50
|
+
if (lines === null) return;
|
|
51
|
+
const file = join(runDir, LINE_CHECKS_FILE);
|
|
52
|
+
const tmp = `${file}.tmp`;
|
|
53
|
+
writeFileSync(tmp, `${JSON.stringify({ ...rec, [section]: { lines } }, null, 2)}\n`);
|
|
54
|
+
renameSync(tmp, file);
|
|
55
|
+
}
|
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/opener.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/opener.js@d21ae80 (v0.47.1, 704d598)
|
|
2
|
+
// Adaptation: none. Moved here from fwdloop's Settings route (src/panel/settings.js, borrowed-from bareloop src/panel/settingsroutes.js@07c298f) so Settings
|
|
3
|
+
// and the launcher share it.
|
|
4
|
+
// The ONE "open this in the OS" helper: `xdg-open` (linux) / `open` (macOS), argv array, no shell, detached.
|
|
5
|
+
// Settings' "Open keys folder" and the `fwdloop start` launcher both use it. Another OS or a failed spawn
|
|
6
|
+
// resolves `false` (the caller then shows the path/URL as text); it never throws.
|
|
7
|
+
import { spawn as realSpawn } from 'node:child_process';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {string} target a folder path or a URL
|
|
11
|
+
* @param {{ platform?: string, spawnFn?: ((cmd: string, args: string[], o: object) => any)|null, underTest?: boolean }} [opts]
|
|
12
|
+
* `spawnFn: null` = no opener at all (resolves false); undefined = the real spawn, unless `underTest`, which spawns nothing
|
|
13
|
+
* unless a test injected one
|
|
14
|
+
* @returns {Promise<boolean>} true once the opener process has started
|
|
15
|
+
*/
|
|
16
|
+
export function openInOs(target, opts = {}) {
|
|
17
|
+
const platform = opts.platform ?? process.platform;
|
|
18
|
+
const cmd = platform === 'linux' ? 'xdg-open' : (platform === 'darwin' ? 'open' : null);
|
|
19
|
+
const opener = opts.spawnFn === undefined ? (opts.underTest ? null : realSpawn) : opts.spawnFn;
|
|
20
|
+
if (!cmd || !opener) return Promise.resolve(false);
|
|
21
|
+
return new Promise((resolve) => {
|
|
22
|
+
let child;
|
|
23
|
+
try { child = opener(cmd, [target], { detached: true, stdio: 'ignore' }); } catch { resolve(false); return; }
|
|
24
|
+
let settled = false;
|
|
25
|
+
child.once('error', () => { if (!settled) { settled = true; resolve(false); } });
|
|
26
|
+
child.once('spawn', () => {
|
|
27
|
+
if (settled) return;
|
|
28
|
+
settled = true;
|
|
29
|
+
if (typeof child.unref === 'function') child.unref();
|
|
30
|
+
resolve(true);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
}
|
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/author.js
CHANGED
|
@@ -407,6 +407,8 @@ export function createAuthor(opts) {
|
|
|
407
407
|
if (r.status !== 200 || !r.body.flow) return r;
|
|
408
408
|
return { ...r, body: { ...r.body, flow: { ...r.body.flow, trigger: triggerDoor.card(r.body.flow.flow) } } };
|
|
409
409
|
},
|
|
410
|
+
/** M4b am4 item 7: how many drafts are open for `whoami` and the launcher's stop warning: the card `live()` returns (the newest draft not abandoned or signed), 0 or 1. */
|
|
411
|
+
openDrafts() { return this.live().body.draft ? 1 : 0; },
|
|
410
412
|
run: flowsDoor.run,
|
|
411
413
|
reuseCheck: (b) => flowsDoor.reuseCheck(b),
|
|
412
414
|
runPrepare: flowsDoor.runPrepare,
|
package/src/panel/authorflows.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// flows() only flows whose `readFlow` passes (a missing, unsigned or tampered flow is never listed), that `canFlowRun` accepts
|
|
6
6
|
// (the one function shared with the run's own preflight: an unwired verb is not listed; amendment 22) and that have at least one
|
|
7
7
|
// passed run (amendment 7 item 7; Run again reaches the rest), each with its signed
|
|
8
|
-
// cap, its declared source roles, the source paths the NEWEST run of that flow used (its `
|
|
8
|
+
// cap, its declared source roles, the source paths the NEWEST run of that flow used (its `run.json` inputs
|
|
9
9
|
// manifest `source` field; blank when none) and what is left this month (a courtesy: the CLI's own monthly
|
|
10
10
|
// check is what refuses).
|
|
11
11
|
// run(body) { flow, inputs: [{role, path}], runId } -> the SAME $0 input checks as the card (`checkInputRows`), the role set
|
|
@@ -19,7 +19,7 @@ import { canFlowRun, willNotRunSay } from '../canrun.js';
|
|
|
19
19
|
import { loadCatalogue } from '../catalogue.js';
|
|
20
20
|
import { ConfigError, readConfig } from '../config.js';
|
|
21
21
|
import {
|
|
22
|
-
changeSentence, checkFlowName, listFlowNames, listRunIds, nextRunId, planForReuse,
|
|
22
|
+
changeSentence, checkFlowName, listFlowNames, listRunIds, nextRunId, planForReuse, readFlow, resolveRunDir, suggestFlowName,
|
|
23
23
|
} from '../flow.js';
|
|
24
24
|
import { jobKeyOfCard, jobKeyOfSigned } from '../jobkey.js';
|
|
25
25
|
import { spendSummary } from '../monthly.js';
|
|
@@ -36,6 +36,7 @@ import { SCHEDULE_BUSY_SAY } from '../summary-words.js';
|
|
|
36
36
|
import { providerKeys } from './spawn.js';
|
|
37
37
|
import { pageAddressesOf, pageAddressRefusal } from '../pagefetch.js';
|
|
38
38
|
import { readModelRecord, writeModelRecord } from '../flowmodel.js';
|
|
39
|
+
import { readRunInputs, RUN_FILE } from '../runfile.js';
|
|
39
40
|
|
|
40
41
|
/** M6 amendment 1: the sentence the page shows and the sign route refuses with, for a job with a run running or waiting at its ask. @param {string} runId */
|
|
41
42
|
export const editBlockedSay = (runId) => `finish or stop ${runId} first`;
|
|
@@ -90,28 +91,27 @@ export function createFlowsDoor(opts) {
|
|
|
90
91
|
};
|
|
91
92
|
}
|
|
92
93
|
|
|
93
|
-
/** The source paths one run froze: role -> path, from that run's `
|
|
94
|
+
/** The source paths one run froze: role -> path, from that run's `run.json` inputs. Blank = none. @param {string} runDir @param {string[]} roles @param {Record<string, string>} [pages] M10 am3: page role -> signed address */
|
|
94
95
|
function sourcesOf(runDir, roles, pages = {}) {
|
|
95
96
|
/** @type {Record<string, string>} */
|
|
96
97
|
const out = Object.fromEntries(roles.map((r) => [r, pages[r] ?? ''])); // M10 am3: a page input shows its signed address, whatever a run froze
|
|
97
98
|
if (runDir === '') return out;
|
|
98
|
-
const f =
|
|
99
|
-
|
|
100
|
-
try { rows = f.ok ? JSON.parse(f.text) : []; } catch { rows = []; }
|
|
101
|
-
for (const row of Array.isArray(rows) ? rows : []) {
|
|
99
|
+
const f = readRunInputs(runDir);
|
|
100
|
+
for (const row of f.ok ? f.entries : []) {
|
|
102
101
|
if (row && typeof row.id === 'string' && roles.includes(row.id) && !Object.hasOwn(pages, row.id) && typeof row.source === 'string') out[row.id] = row.source;
|
|
103
102
|
}
|
|
104
103
|
return out;
|
|
105
104
|
}
|
|
106
105
|
|
|
107
|
-
/** The source paths the newest run of this flow used: role -> path, from that run's `
|
|
106
|
+
/** The source paths the newest run of this flow used: role -> path, from that run's `run.json` inputs. Blank = none. @param {string} flowDir @param {string[]} roles @param {Record<string, string>} [pages] */
|
|
108
107
|
function lastSources(flowDir, roles, pages = {}) {
|
|
109
108
|
let newest = null;
|
|
110
109
|
for (const id of listRunIds(flowDir)) {
|
|
111
110
|
const r = resolveRunDir(flowDir, id);
|
|
112
111
|
if (!r.ok) continue;
|
|
113
112
|
let t;
|
|
114
|
-
|
|
113
|
+
if (!readRunInputs(r.runDir).ok) continue; // a run that froze no inputs (a refusal at start) is not "the newest run that ran"
|
|
114
|
+
try { t = lstatSync(join(r.runDir, RUN_FILE)).mtimeMs; } catch { continue; }
|
|
115
115
|
if (newest === null || t > newest.t || (t === newest.t && id > newest.id)) newest = { t, id, runDir: r.runDir };
|
|
116
116
|
}
|
|
117
117
|
if (newest === null) return { runId: null, sources: sourcesOf('', roles, pages) };
|