fwdloop 0.21.0 → 0.22.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 +85 -34
- package/package.json +4 -3
- package/src/audit-fold.js +5 -1
- package/src/authoring.js +32 -6
- package/src/checked.js +18 -1
- package/src/cited-record.js +138 -0
- package/src/cited-source.js +49 -0
- package/src/citedcheck.js +306 -0
- package/src/citedwords.js +197 -0
- package/src/closers.js +56 -7
- package/src/ctx-tools.js +2 -14
- package/src/declaration.js +85 -5
- package/src/diary.js +2 -2
- package/src/docx.js +16 -2
- package/src/draft-steps.js +1 -1
- package/src/drafter.js +292 -25
- package/src/flow.js +33 -7
- package/src/flowmodel.js +21 -0
- package/src/input-facts.js +20 -3
- package/src/model-step.js +30 -5
- package/src/pageask.js +136 -0
- package/src/pagebits.js +107 -0
- package/src/pagedropwords.js +171 -0
- package/src/pagedry.js +120 -0
- package/src/pagefetch.js +164 -0
- package/src/pagelook.js +155 -0
- package/src/pagemap.js +55 -0
- package/src/pageplace.js +103 -0
- package/src/pagerules.js +318 -0
- package/src/panel/author.js +41 -20
- package/src/panel/authorcard.js +11 -1
- package/src/panel/authorflows.js +21 -15
- package/src/panel/authorstart.js +2 -4
- package/src/panel/authortrigger.js +14 -4
- package/src/panel/data.js +83 -2
- package/src/panel/index.html +279 -12
- package/src/panel/result.js +295 -0
- package/src/panel/server.js +27 -3
- package/src/primitives.js +2 -3
- package/src/provider.js +5 -2
- package/src/redact.js +17 -0
- package/src/runner.js +83 -12
- package/src/schedule.js +3 -3
- package/src/setup.js +16 -1
- package/src/sheetfind.js +50 -0
- package/src/sheetlook.js +157 -0
- package/src/signed-text.js +11 -1
- package/src/thinking.js +1 -1
- package/src/try-checks.js +6 -0
- package/src/types.js +3 -2
- package/types/authoring.d.ts +19 -2
- package/types/checked.d.ts +10 -0
- package/types/cited-record.d.ts +21 -0
- package/types/cited-source.d.ts +18 -0
- package/types/citedcheck.d.ts +95 -0
- package/types/citedwords.d.ts +97 -0
- package/types/closers.d.ts +55 -3
- package/types/ctx-tools.d.ts +0 -1
- package/types/declaration.d.ts +15 -1
- package/types/docx.d.ts +14 -0
- package/types/drafter.d.ts +244 -2
- package/types/flow.d.ts +21 -0
- package/types/flowmodel.d.ts +15 -0
- package/types/input-facts.d.ts +12 -2
- package/types/model-step.d.ts +35 -3
- package/types/pageask.d.ts +75 -0
- package/types/pagebits.d.ts +32 -0
- package/types/pagedropwords.d.ts +40 -0
- package/types/pagedry.d.ts +38 -0
- package/types/pagefetch.d.ts +86 -0
- package/types/pagelook.d.ts +75 -0
- package/types/pagemap.d.ts +31 -0
- package/types/pageplace.d.ts +22 -0
- package/types/pagerules.d.ts +86 -0
- package/types/panel/authorcard.d.ts +2 -0
- package/types/panel/authorflows.d.ts +2 -0
- package/types/panel/data.d.ts +26 -0
- package/types/panel/result.d.ts +156 -0
- package/types/provider.d.ts +3 -1
- package/types/redact.d.ts +1 -0
- package/types/runner.d.ts +156 -7
- package/types/schedule.d.ts +0 -11
- package/types/setup.d.ts +13 -0
- package/types/sheetfind.d.ts +46 -0
- package/types/sheetlook.d.ts +120 -0
- package/types/thinking.d.ts +1 -1
- package/types/types.d.ts +11 -3
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
// M10 amendment 4 (docs/wiki/the-module-ladder.md): the Result tab's server side.
|
|
2
|
+
//
|
|
3
|
+
// borrowed-from: bareloop src/panel/server.js@2959217 (getRunResult :1347, getRunDownload :1470, readDelivered :1186, the strings :1165-1308), adjusted to
|
|
4
|
+
// fwdloop's books: a run is (flow, runId); the job lines are the run's own signed copy; the saved file is the send step's file, found by the accepted
|
|
5
|
+
// ask's recorded hash; a page link is a signed `page:` source. The tab only SHOWS what the books hold; it never decides a check.
|
|
6
|
+
//
|
|
7
|
+
// Every file read goes through `readFileInside` (src/flow.js); this module imports no fs.
|
|
8
|
+
// What it throws away: any file but the ones a signed send wrote; any record field this module does not name (the cited-check record is read by
|
|
9
|
+
// `readCitedChecks` and nothing else). A malformed cited-check record is "no record" for the tab (the lines say "no saved result to show").
|
|
10
|
+
|
|
11
|
+
import { createHash } from 'node:crypto';
|
|
12
|
+
import { basename, join } from 'node:path';
|
|
13
|
+
|
|
14
|
+
import { readFileInside } from '../flow.js';
|
|
15
|
+
import { isCellsPath } from '../closers.js';
|
|
16
|
+
import { readAcceptedHashesByEmits } from '../ask.js';
|
|
17
|
+
import { NOT_CHECKED_LABEL } from '../checked.js';
|
|
18
|
+
import { checkSendDestination } from '../runner.js';
|
|
19
|
+
import { isAgree, readingOfQuestion } from '../pageask.js';
|
|
20
|
+
import { lineRules } from '../pagebits.js';
|
|
21
|
+
import { CITED_CHECKS_FILE } from '../cited-record.js';
|
|
22
|
+
import { readChecks } from '../diary.js';
|
|
23
|
+
|
|
24
|
+
/** the two sentences for a saved file that is no longer what the run wrote (code-owned, one spelling) */
|
|
25
|
+
export const RESULT_FILE_GONE = 'the saved file is gone';
|
|
26
|
+
export const RESULT_FILE_CHANGED = 'the saved file changed after the run';
|
|
27
|
+
/** the words beside a Result-tab page link: the page is read again from the web, so it can differ from what the run read */
|
|
28
|
+
export const RESULT_PAGE_MAY_CHANGE = 'The page may have changed since this run.';
|
|
29
|
+
/** the words after a fact whose limit the person agreed to */
|
|
30
|
+
export const RESULT_YOU_CONFIRMED = '(you confirmed)';
|
|
31
|
+
/** the Your-call card's words (bareloop server.js@2959217 DOOR_WORDS.waiting.head and RESULT_DOOR_ASK); the page types none of them */
|
|
32
|
+
export const RESULT_DOOR_HEAD = 'waiting for you';
|
|
33
|
+
export const RESULT_DOOR_ASK = 'the checks passed; is this what you wanted?';
|
|
34
|
+
/** the M10 cited-check record, in the run's own folder: `writeCitedLine` (src/cited-record.js) is its one writer, `readCitedChecks` its one reader. */
|
|
35
|
+
export { CITED_CHECKS_FILE };
|
|
36
|
+
|
|
37
|
+
/** end-row outcomes that are not a failure of the job */
|
|
38
|
+
const NOT_FAILED = new Set(['complete', 'stopped', 'cap-halt', 'rerun', 'ask-expired']);
|
|
39
|
+
const FACT_KINDS = new Set(['phrase', 'value']);
|
|
40
|
+
const isInt = (x) => Number.isInteger(x);
|
|
41
|
+
const isStr = (x) => typeof x === 'string';
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* M10 job = the run reads a web page, a CSV or a .docx (ladder, M10 am4 item 1). Read off the signed arbiter, never the run's files.
|
|
45
|
+
* @param {any} arbiter @returns {boolean}
|
|
46
|
+
*/
|
|
47
|
+
export function isResultRun(arbiter) {
|
|
48
|
+
const sources = Array.isArray(arbiter?.sources) ? arbiter.sources : [];
|
|
49
|
+
return sources.some((s) => s && (s.kind === 'page' || (isStr(s.path) && (isCellsPath(s.path) || s.path.toLowerCase().endsWith('.docx')))));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The run's check type: its distinct close classes, in step order (`hitl + softgreen`). `—` for a declaration with none.
|
|
53
|
+
* @param {any} declaration @returns {string} */
|
|
54
|
+
export function checkTypeOf(declaration) {
|
|
55
|
+
const seen = [];
|
|
56
|
+
for (const s of Array.isArray(declaration?.steps) ? declaration.steps : []) {
|
|
57
|
+
const c = s?.close?.class;
|
|
58
|
+
if (isStr(c) && !seen.includes(c)) seen.push(c);
|
|
59
|
+
}
|
|
60
|
+
return seen.length > 0 ? seen.join(' + ') : '—';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The proof of one result, kept only when every mark is a real span of its text: integer `[start, end]`, 0 <= start < end <= text length, sorted and not
|
|
65
|
+
* overlapping. Anything else is `null`: the page then shows the plain quote (bareloop's "no proof" path), never marks cut at wrong offsets.
|
|
66
|
+
* @param {any} p @returns {{text: string, marks: number[][]}|null}
|
|
67
|
+
*/
|
|
68
|
+
function readProof(p) {
|
|
69
|
+
if (!p || !isStr(p.text) || !Array.isArray(p.marks)) return null;
|
|
70
|
+
let at = 0;
|
|
71
|
+
for (const m of p.marks) {
|
|
72
|
+
if (!Array.isArray(m) || m.length !== 2 || !isInt(m[0]) || !isInt(m[1]) || m[0] < at || m[1] <= m[0] || m[1] > p.text.length) return null;
|
|
73
|
+
at = m[1];
|
|
74
|
+
}
|
|
75
|
+
return { text: p.text, marks: p.marks.map((m) => [m[0], m[1]]) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The ONE reader of the M10 cited-check record (`<run>/cited-checks.json`). Expected shape (typed, nothing parsed out of prose):
|
|
80
|
+
* { lines: [ { n: int, source: string (the role of a signed source), passed: boolean,
|
|
81
|
+
* facts: [ { name: string, kind: 'phrase'|'value', sentence: string, confirmed?: true } ],
|
|
82
|
+
* rows: [ { n: int, quote: string, cells: string[] (one per fact), proof?: { text: string, marks: [[start, end], ...] } } ] | null,
|
|
83
|
+
* notChecked?: string[] } ] }
|
|
84
|
+
* `{present:false}` = no file. `{present:true, ok:false, red}` = a record that does not match (named, never half-read). Else `{present:true, ok:true, lines}`.
|
|
85
|
+
* @param {string} runDir
|
|
86
|
+
* @returns {{present: false}|{present: true, ok: false, red: string}|{present: true, ok: true, lines: any[]}}
|
|
87
|
+
*/
|
|
88
|
+
export function readCitedChecks(runDir) {
|
|
89
|
+
const r = readFileInside(runDir, CITED_CHECKS_FILE);
|
|
90
|
+
if (!r.ok) return r.missing ? { present: false } : { present: true, ok: false, red: r.red };
|
|
91
|
+
/** @param {string} why @returns {{present: true, ok: false, red: string}} */
|
|
92
|
+
const red = (why) => ({ present: true, ok: false, red: `${CITED_CHECKS_FILE}: ${why}` });
|
|
93
|
+
let rec;
|
|
94
|
+
try { rec = JSON.parse(r.text); } catch { return red('not valid JSON'); }
|
|
95
|
+
if (!rec || !Array.isArray(rec.lines)) return red('"lines" is not a list');
|
|
96
|
+
const lines = [];
|
|
97
|
+
for (const l of rec.lines) {
|
|
98
|
+
if (!l || !isInt(l.n) || !isStr(l.source)) return red('a line needs an integer "n" and a "source"');
|
|
99
|
+
if (typeof l.passed !== 'boolean') return red(`line ${l.n}: "passed" is not true or false`);
|
|
100
|
+
if (!Array.isArray(l.facts)) return red(`line ${l.n}: "facts" is not a list`);
|
|
101
|
+
const facts = [];
|
|
102
|
+
for (const f of l.facts) {
|
|
103
|
+
if (!f || !isStr(f.name) || !isStr(f.sentence)) return red(`line ${l.n}: a fact needs a "name" and a "sentence"`);
|
|
104
|
+
if (!FACT_KINDS.has(f.kind)) return red(`line ${l.n}: fact "${f.name}" has a "kind" that is not phrase or value`);
|
|
105
|
+
facts.push({ name: f.name, kind: f.kind, sentence: f.sentence, ...(f.confirmed === true ? { confirmed: true } : {}) });
|
|
106
|
+
}
|
|
107
|
+
let rows = null;
|
|
108
|
+
if (l.rows !== null && l.rows !== undefined) {
|
|
109
|
+
if (!Array.isArray(l.rows)) return red(`line ${l.n}: "rows" is not a list`);
|
|
110
|
+
rows = [];
|
|
111
|
+
for (const w of l.rows) {
|
|
112
|
+
if (!w || !isInt(w.n) || !isStr(w.quote)) return red(`line ${l.n}: a row needs an integer "n" and a "quote"`);
|
|
113
|
+
if (!Array.isArray(w.cells) || w.cells.length !== facts.length || !w.cells.every(isStr)) return red(`line ${l.n}, result ${w.n}: "cells" must be one text per fact (${facts.length})`);
|
|
114
|
+
const proof = readProof(w.proof);
|
|
115
|
+
rows.push({
|
|
116
|
+
n: w.n, quote: w.quote, ...(proof ? { proof } : {}), cells: [...w.cells],
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const nc = Array.isArray(l.notChecked) ? l.notChecked.filter((x) => isStr(x) && x.trim() !== '') : [];
|
|
121
|
+
lines.push({
|
|
122
|
+
n: l.n, source: l.source, passed: l.passed, facts, rows, notChecked: nc,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return { present: true, ok: true, lines };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The names of the facts of one job line whose limit came from an `agree` answer, read from the setup record's human rows (bareloop's confirmedFactNames,
|
|
130
|
+
* server.js@2959217): a look question on THIS line, answered agree / yes, whose reading (read back from the question's one spelling) is a signed `~` rule of
|
|
131
|
+
* the line word for word. A fact is confirmed when that reading starts with its name. No record, an own-words answer, another line or a reading that is not
|
|
132
|
+
* in the signed rule confirms nothing; nothing is guessed.
|
|
133
|
+
* @param {any[]} setupRows @param {number} lineN @param {string} signedRule the line's signed guardrail @param {string[]} factNames
|
|
134
|
+
* @returns {Set<string>}
|
|
135
|
+
*/
|
|
136
|
+
export function confirmedFactNames(setupRows, lineN, signedRule, factNames) {
|
|
137
|
+
const names = new Set();
|
|
138
|
+
const written = lineRules({ rule: signedRule });
|
|
139
|
+
for (const h of Array.isArray(setupRows) ? setupRows : []) {
|
|
140
|
+
if (h?.kind !== 'human' || h.source !== 'look' || h.line !== lineN || !isAgree(h.answer)) continue; // eslint-disable-line no-continue
|
|
141
|
+
const reading = readingOfQuestion(h.question);
|
|
142
|
+
if (reading === null || !written.includes(reading)) continue; // eslint-disable-line no-continue
|
|
143
|
+
for (const name of factNames) if (reading.startsWith(`${name} `)) names.add(name);
|
|
144
|
+
}
|
|
145
|
+
return names;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** the signed `page:` sources, role -> address (http(s) only: the parser already refuses any other) @param {any} arbiter @returns {Map<string, string>} */
|
|
149
|
+
function pageUrlsByRole(arbiter) {
|
|
150
|
+
const out = new Map();
|
|
151
|
+
for (const s of Array.isArray(arbiter?.sources) ? arbiter.sources : []) if (s && s.kind === 'page' && isStr(s.path)) out.set(s.role, s.path);
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* One saved file, read for the tab or a download, through the one safe gateway (`readFileInside`: not a symlink, real path inside the signed folder's
|
|
157
|
+
* real path, checked at USE time). It must also still hash to the recorded sha256. A missing, refused or changed file is a state, never content:
|
|
158
|
+
* stale bytes are never returned. (Text read, so a file that is not UTF-8 reads as "changed", never as ok.)
|
|
159
|
+
* @param {{name: string, dir: string|null, sha256: string|null}} rec
|
|
160
|
+
* @returns {{state: 'ok', buf: Buffer}|{state: 'gone'|'changed', buf: null}}
|
|
161
|
+
*/
|
|
162
|
+
export function readDelivered(rec) {
|
|
163
|
+
if (rec.dir === null) return { state: 'gone', buf: null };
|
|
164
|
+
const r = readFileInside(rec.dir, rec.name);
|
|
165
|
+
if (!r.ok) return { state: 'gone', buf: null };
|
|
166
|
+
const buf = Buffer.from(r.text, 'utf8');
|
|
167
|
+
if (rec.sha256 === null || createHash('sha256').update(buf).digest('hex') !== rec.sha256) return { state: 'changed', buf: null };
|
|
168
|
+
return { state: 'ok', buf };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* The files this run's signed sends wrote: for each signed send whose send step ended green in the audit, the file `<flow>-<runId>-<emits>.json`
|
|
173
|
+
* in the signed folder, with the sha256 the human's accept recorded for the ask that send reads (`readAcceptedHashesByEmits`, the same record the
|
|
174
|
+
* send itself checked). No accepted hash = recorded as null, which reads as "changed", never as ok.
|
|
175
|
+
* @returns {{path: string, dir: string|null, name: string, sha256: string|null}[]}
|
|
176
|
+
*/
|
|
177
|
+
export function deliveredOf({
|
|
178
|
+
arbiter, declaration, runDir, root, flow, runId, auditRows,
|
|
179
|
+
}) {
|
|
180
|
+
const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
|
|
181
|
+
const askLines = new Set((arbiter?.asks ?? []).map((a) => a.line));
|
|
182
|
+
const askEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
|
|
183
|
+
const hashes = readAcceptedHashesByEmits(runDir);
|
|
184
|
+
const out = [];
|
|
185
|
+
for (const send of arbiter?.sends ?? []) {
|
|
186
|
+
const step = steps.find((s) => s.fromLine === send.line);
|
|
187
|
+
if (!step || !auditRows.some((r) => r.step === step.emits && r.verdict === 'green')) continue; // eslint-disable-line no-continue
|
|
188
|
+
const name = `${flow}-${runId}-${step.emits}.json`;
|
|
189
|
+
const dest = checkSendDestination(`${send.target.kind}:${send.target.path}`, { root, runDir });
|
|
190
|
+
const [askId] = (step.reads ?? []).filter((id) => askEmits.has(id));
|
|
191
|
+
out.push({
|
|
192
|
+
path: join(dest.ok ? dest.dir : send.target.path, name), dir: dest.ok ? dest.dir : null, name,
|
|
193
|
+
sha256: hashes.ok && askId !== undefined ? (hashes.byEmits.get(askId) ?? null) : null,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* M10 am9 item 2: the checks one job line's step(s) ran, from the run's own check record (`checks.jsonl`, written by code at every try), each step's NEWEST
|
|
201
|
+
* try, in the Audit try line's words (`text`, `result`). Never the AI's words. A line no step ran (an ask, a send) has none.
|
|
202
|
+
* @param {any[]} stepsOfLine the declaration's steps for the line @param {any[]} diary `readChecks(runDir)`
|
|
203
|
+
* @returns {{ok: boolean, text: string, result: string|null}[]}
|
|
204
|
+
*/
|
|
205
|
+
function checksOfLine(stepsOfLine, diary) {
|
|
206
|
+
const out = [];
|
|
207
|
+
for (const st of stepsOfLine) {
|
|
208
|
+
const rows = diary.filter((r) => r && r.step === st.emits && isInt(r.try) && Array.isArray(r.checks));
|
|
209
|
+
const newest = rows.reduce((m, r) => (m === null || r.try >= m.try ? r : m), null);
|
|
210
|
+
for (const c of newest ? newest.checks : []) if (c && isStr(c.text) && typeof c.ok === 'boolean') out.push({ ok: c.ok, text: c.text, result: isStr(c.result) ? c.result : null });
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** the check's own gap for a RED run: its first line and how many more @param {string|null} text @returns {{line: string, more: number, moreText: string|null}|null} */
|
|
216
|
+
function gapOf(text) {
|
|
217
|
+
const rows = isStr(text) ? text.split('\n').map((x) => x.trim()).filter((x) => x !== '') : [];
|
|
218
|
+
if (rows.length === 0) return null;
|
|
219
|
+
const more = rows.length - 1;
|
|
220
|
+
return { line: rows[0], more, moreText: more > 0 ? `(+${more} more)` : null };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The Result tab's JSON for one run (`GET /api/runs/:flow/:runId/result`).
|
|
225
|
+
* @param {{flow: string, runId: string, runDir: string, root: string, flowRead: any, arbiter: any, historyRow: any, auditRows: any[], logJson: any, notChecked: string[], readNotes?: string[], setupRows?: any[], door?: {askId: string, draftNo: number}|null}} a
|
|
226
|
+
*/
|
|
227
|
+
export function buildResult({
|
|
228
|
+
flow, runId, runDir, root, flowRead, arbiter, historyRow, auditRows, logJson, notChecked, readNotes = [], setupRows = [], door = null,
|
|
229
|
+
}) {
|
|
230
|
+
const declaration = flowRead.declaration;
|
|
231
|
+
const taken = new Set([...(arbiter?.asks ?? []), ...(arbiter?.sends ?? [])].map((x) => x.line));
|
|
232
|
+
const cited = readCitedChecks(runDir);
|
|
233
|
+
const record = cited.present && cited.ok ? cited.lines : [];
|
|
234
|
+
const urls = pageUrlsByRole(arbiter);
|
|
235
|
+
// am9: a page job's card is bareloop's (no checks list); every other job lists what each step checked
|
|
236
|
+
const diary = urls.size === 0 ? readChecks(runDir) : [];
|
|
237
|
+
const lines = flowRead.lines.filter((l) => !taken.has(l.n)).map((l) => {
|
|
238
|
+
const c = record.find((x) => x.n === l.n) ?? null;
|
|
239
|
+
const out = {
|
|
240
|
+
notChecked: c ? c.notChecked : [], n: l.n, text: l.text, rules: isStr(l.guardrail) && l.guardrail !== '' ? [l.guardrail] : [],
|
|
241
|
+
kind: c ? 'facts' : 'text', passed: c ? c.passed : false, file: null,
|
|
242
|
+
checks: checksOfLine((declaration?.steps ?? []).filter((st) => st.fromLine === l.n), diary),
|
|
243
|
+
};
|
|
244
|
+
if (c) {
|
|
245
|
+
out.source = c.source;
|
|
246
|
+
out.page = urls.get(c.source) ?? null;
|
|
247
|
+
const agreed = confirmedFactNames(setupRows, l.n, isStr(l.guardrail) ? l.guardrail : '', c.facts.map((f) => f.name));
|
|
248
|
+
out.facts = c.facts.map((f) => ({
|
|
249
|
+
name: f.name, kind: f.kind, sentence: f.sentence, ...(f.confirmed || agreed.has(f.name) ? { note: RESULT_YOU_CONFIRMED } : {}),
|
|
250
|
+
}));
|
|
251
|
+
out.rows = c.rows;
|
|
252
|
+
}
|
|
253
|
+
return out;
|
|
254
|
+
});
|
|
255
|
+
const delivered = deliveredOf({
|
|
256
|
+
arbiter, declaration, runDir, root, flow, runId, auditRows,
|
|
257
|
+
}).map((d, i) => {
|
|
258
|
+
const got = readDelivered(d);
|
|
259
|
+
return {
|
|
260
|
+
i, path: d.path, name: d.name, bytes: got.buf ? got.buf.length : null, state: got.state,
|
|
261
|
+
words: got.state === 'gone' ? RESULT_FILE_GONE : (got.state === 'changed' ? RESULT_FILE_CHANGED : null),
|
|
262
|
+
};
|
|
263
|
+
});
|
|
264
|
+
// a run that failed delivered nothing: say its own first gap, never rows. A stop, a cap halt, a rerun and an expired ask are not a failure (the same
|
|
265
|
+
// set `computeGlyph` colours `[✗]` by exclusion); a pause has no end row at all.
|
|
266
|
+
let gap = null;
|
|
267
|
+
if (historyRow && !NOT_FAILED.has(historyRow.outcome)) {
|
|
268
|
+
const redRow = auditRows.findLast((r) => r.verdict === 'red' || r.verdict === 'not-done');
|
|
269
|
+
gap = gapOf(isStr(logJson?.red) && logJson.red !== '' ? logJson.red : (redRow ? `${redRow.step}: ${redRow.gap}` : null));
|
|
270
|
+
}
|
|
271
|
+
const pages = [...new Set(urls.values())];
|
|
272
|
+
return {
|
|
273
|
+
flow, runId, lines, pages, pageNote: pages.length ? RESULT_PAGE_MAY_CHANGE : null, notCheckedLabel: NOT_CHECKED_LABEL.charAt(0).toUpperCase() + NOT_CHECKED_LABEL.slice(1), notChecked, readNotes, delivered, gap,
|
|
274
|
+
door: door === null ? null : { head: RESULT_DOOR_HEAD, ask: RESULT_DOOR_ASK, askId: door.askId, draftNo: door.draftNo },
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** download content types by extension; anything else is plain bytes */
|
|
279
|
+
const DOWNLOAD_TYPES = { '.json': 'application/json', '.md': 'text/plain', '.txt': 'text/plain', '.csv': 'text/csv' };
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* `GET /api/runs/:flow/:runId/download?i=<n>` — saved file `n` (an index into the run's own list), or why not. The path is the books', never the request's.
|
|
283
|
+
* @param {{index: unknown, ctx: any}} a
|
|
284
|
+
* @returns {{ok: true, name: string, type: string, buf: Buffer}|{ok: false, code: number, error: string}}
|
|
285
|
+
*/
|
|
286
|
+
export function downloadOf({ index, ctx }) {
|
|
287
|
+
const list = deliveredOf(ctx);
|
|
288
|
+
const i = typeof index === 'string' && /^\d{1,6}$/.test(index) ? Number(index) : -1;
|
|
289
|
+
if (i < 0 || i >= list.length) return { ok: false, code: 404, error: 'this run saved no such file' };
|
|
290
|
+
const got = readDelivered(list[i]);
|
|
291
|
+
if (got.state !== 'ok') return { ok: false, code: 409, error: got.state === 'gone' ? RESULT_FILE_GONE : RESULT_FILE_CHANGED };
|
|
292
|
+
const name = basename(list[i].path);
|
|
293
|
+
const ext = name.includes('.') ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
|
|
294
|
+
return { ok: true, name, type: Object.hasOwn(DOWNLOAD_TYPES, ext) ? DOWNLOAD_TYPES[ext] : 'application/octet-stream', buf: /** @type {Buffer} */ (got.buf) };
|
|
295
|
+
}
|
package/src/panel/server.js
CHANGED
|
@@ -60,7 +60,7 @@ import { resolveRunDir } from '../flow.js';
|
|
|
60
60
|
import { readAsk, requestStop, stopParkedRun } from '../runner.js';
|
|
61
61
|
import { removeFromNeedsYou } from './needsyou.js';
|
|
62
62
|
import {
|
|
63
|
-
listRuns, listScheduled, summarizeJobs, RUNS_LIST_LIMITS, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
|
|
63
|
+
listRuns, listScheduled, summarizeJobs, RUNS_LIST_LIMITS, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, getRunResult, getRunDownload, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
|
|
64
64
|
} from './data.js';
|
|
65
65
|
import { createResumer } from './resume.js';
|
|
66
66
|
import { createScheduler } from './scheduler.js';
|
|
@@ -551,8 +551,8 @@ export function handleRequest(req, res, opts) {
|
|
|
551
551
|
return;
|
|
552
552
|
}
|
|
553
553
|
|
|
554
|
-
// /api/runs/:flow/:runId(/audit|/job|/asks)?
|
|
555
|
-
const runMatch = /^\/api\/runs\/([^/]+)\/([^/]+)(\/(audit|job|asks))?$/.exec(pathname);
|
|
554
|
+
// /api/runs/:flow/:runId(/audit|/job|/asks|/result|/download)?
|
|
555
|
+
const runMatch = /^\/api\/runs\/([^/]+)\/([^/]+)(\/(audit|job|asks|result|download))?$/.exec(pathname);
|
|
556
556
|
if (runMatch) {
|
|
557
557
|
let flow;
|
|
558
558
|
let runId;
|
|
@@ -594,6 +594,30 @@ export function handleRequest(req, res, opts) {
|
|
|
594
594
|
send(200, result);
|
|
595
595
|
return;
|
|
596
596
|
}
|
|
597
|
+
if (sub === 'result') {
|
|
598
|
+
const result = getRunResult({
|
|
599
|
+
root: opts.root, flow, runId, catalogue, resumeAttempt, now: opts.now,
|
|
600
|
+
});
|
|
601
|
+
if (!result) { sendText(res, 404, 'no such run, or it has no result tab'); return; }
|
|
602
|
+
send(200, result);
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
if (sub === 'download') {
|
|
606
|
+
const got = getRunDownload({
|
|
607
|
+
root: opts.root, flow, runId, catalogue, index: url.searchParams.get('i'),
|
|
608
|
+
});
|
|
609
|
+
if (!got.ok) { sendText(res, got.code, got.error); return; }
|
|
610
|
+
// the name is the saved file's own basename; quotes and control characters never reach the header
|
|
611
|
+
const plain = got.name.replace(/[^A-Za-z0-9._-]/g, '_');
|
|
612
|
+
res.writeHead(200, {
|
|
613
|
+
'content-type': `${got.type}; charset=utf-8`,
|
|
614
|
+
'content-length': got.buf.length,
|
|
615
|
+
'content-disposition': `attachment; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(got.name)}`,
|
|
616
|
+
'x-content-type-options': 'nosniff',
|
|
617
|
+
});
|
|
618
|
+
if (method === 'HEAD') res.end(); else res.end(got.buf);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
597
621
|
const result = getRunDetail({
|
|
598
622
|
root: opts.root, flow, runId, catalogue, resumeAttempt, startingRun, triggerRead: (f) => opts.author?.trigger?.facts(f) ?? null, now: opts.now,
|
|
599
623
|
});
|
package/src/primitives.js
CHANGED
|
@@ -355,14 +355,13 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
|
|
|
355
355
|
return { tools: {}, reds: [`primitives: bareguard refused the step's file scope — ${err.message}`] };
|
|
356
356
|
}
|
|
357
357
|
|
|
358
|
-
// M4d am29 item 1:
|
|
358
|
+
// M4d am29 item 1: how many times the gate was asked, so a tool call's diary row can say `allow`, the deny and its rule,
|
|
359
359
|
// or `no check` (a call that never reached the gate: readDocx, addressCells, a litectx verb with no path). Every tool below carries it as `gateSeen`.
|
|
360
|
-
const gateSeen = { n: 0
|
|
360
|
+
const gateSeen = { n: 0 };
|
|
361
361
|
const askGate = gate.check.bind(gate);
|
|
362
362
|
gate.check = async (action) => {
|
|
363
363
|
const decision = await askGate(action);
|
|
364
364
|
gateSeen.n += 1;
|
|
365
|
-
gateSeen.last = { outcome: decision.outcome, rule: decision.rule ?? null };
|
|
366
365
|
return decision;
|
|
367
366
|
};
|
|
368
367
|
|
package/src/provider.js
CHANGED
|
@@ -208,9 +208,12 @@ export function readPriceConfig(home) {
|
|
|
208
208
|
* The money hold (USD) of one round: the picked model's OWN Settings prices (`rates`, per 1K tokens, from
|
|
209
209
|
* `resolveUsableModel`) times the two token bounds above. Not a table, not a fallback.
|
|
210
210
|
* @param {{ in: number, out: number }} rates
|
|
211
|
+
* @param {number} [promptChars] the length of a prompt known before the call (M10: a page-map prompt carries a whole saved page): the input bound is then
|
|
212
|
+
* the larger of the constant and a deliberately high estimate of that prompt (3 characters per token), never less than the constant.
|
|
211
213
|
*/
|
|
212
|
-
export function ceilingCostUsd(rates) {
|
|
213
|
-
|
|
214
|
+
export function ceilingCostUsd(rates, promptChars = 0) {
|
|
215
|
+
const inputTokens = Math.max(CEILING_INPUT_TOKENS, Math.ceil(promptChars / 3));
|
|
216
|
+
return (inputTokens / 1000) * rates.in + (CEILING_OUTPUT_TOKENS / 1000) * rates.out;
|
|
214
217
|
}
|
|
215
218
|
|
|
216
219
|
/**
|
package/src/redact.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// The one secret inventory: known token shapes only, masked before a value is stored or written.
|
|
2
|
+
// borrowed-from: bareloop src/validate.js@07215d6 (SECRET_PATTERNS). Its own module so a caller that only
|
|
3
|
+
// needs to mask (src/diary.js) does not pull litectx in through src/ctx-tools.js.
|
|
4
|
+
|
|
5
|
+
import { redact } from 'bareguard';
|
|
6
|
+
|
|
7
|
+
const SECRET_PATTERNS = [
|
|
8
|
+
/(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{16,}/,
|
|
9
|
+
/(?<![A-Za-z0-9_-])ghp_[A-Za-z0-9]{20,}/,
|
|
10
|
+
/(?<![A-Za-z0-9_-])github_pat_[A-Za-z0-9_]{20,}/,
|
|
11
|
+
/(?<![A-Za-z0-9_-])AKIA[0-9A-Z]{16}/,
|
|
12
|
+
/(?<![A-Za-z0-9_-])xox[bap]-[A-Za-z0-9-]{10,}/,
|
|
13
|
+
/(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}/,
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
/** Mask known secret shapes. @param {unknown} raw */
|
|
17
|
+
export const redactSecrets = (raw) => redact(String(raw ?? ''), { patterns: SECRET_PATTERNS });
|
package/src/runner.js
CHANGED
|
@@ -58,6 +58,8 @@ import {
|
|
|
58
58
|
} from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
|
|
59
59
|
import { configHome, configDoorHome } from './config.js';
|
|
60
60
|
import { closeByClass, isCellsPath } from './closers.js';
|
|
61
|
+
import { readRunSource } from './cited-source.js';
|
|
62
|
+
import { citedLineOf, writeCitedLine } from './cited-record.js';
|
|
61
63
|
import {
|
|
62
64
|
appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
|
|
63
65
|
} from './books.js';
|
|
@@ -67,7 +69,8 @@ import { appendChecks, nextRound } from './diary.js';
|
|
|
67
69
|
import {
|
|
68
70
|
doneRecord, happenedRecord, outputRecord, closeRecords,
|
|
69
71
|
} from './try-checks.js';
|
|
70
|
-
import { readJobThinking, writeRunThinking } from './flowmodel.js';
|
|
72
|
+
import { readJobThinking, writeRunThinking, writeRunModel } from './flowmodel.js';
|
|
73
|
+
import { fetchPageText, isWebUrl } from './pagefetch.js';
|
|
71
74
|
import {
|
|
72
75
|
readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
|
|
73
76
|
} from './liveness.js';
|
|
@@ -390,14 +393,38 @@ export function checkFreshRunDir(runDir) {
|
|
|
390
393
|
return { ok: true };
|
|
391
394
|
}
|
|
392
395
|
|
|
396
|
+
/** M10 item 1: fetch a web page and freeze its text as `<dir>/<id>.txt`; the sha256 is of the FROZEN bytes, like a file input. The ONE writer of a
|
|
397
|
+
* page's frozen copy: drafting calls it with its draft folder, a run start (via `freezeInputs`) with the run's `inputs/`, so the two are
|
|
398
|
+
* separate files and a run is only ever checked against its own. The fetch is tried once; a refusal names the input and says why in plain words.
|
|
399
|
+
* @param {string} dir @param {string} id @param {string} url
|
|
400
|
+
* @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>}} [o]
|
|
401
|
+
* @returns {Promise<{ok: true, text: string, entry: {id: string, source: string, frozen: string, sha256: string, bytes: number}}|{ok: false, red: string}>} `text` = the frozen text itself, for the caller that reads it (drafting) */
|
|
402
|
+
export async function freezePage(dir, id, url, { fetchPage = fetchPageText } = {}) {
|
|
403
|
+
const got = await fetchPage(url);
|
|
404
|
+
if (!got.ok) return { ok: false, red: `freeze: input "${id}": ${got.error}` };
|
|
405
|
+
mkdirSync(dir, { recursive: true });
|
|
406
|
+
const frozen = join(dir, `${id}.txt`);
|
|
407
|
+
writeFileSync(frozen, got.text, 'utf8');
|
|
408
|
+
return { ok: true, text: got.text, entry: { id, source: url, frozen, sha256: hashFile(frozen), bytes: statSync(frozen).size } };
|
|
409
|
+
}
|
|
410
|
+
|
|
393
411
|
/** Copy each named source into `<runDir>/inputs/`, hash the FROZEN copy
|
|
394
412
|
* (never the original again after this), write `inputs.json`. An
|
|
395
|
-
* unreadable source refuses by name.
|
|
396
|
-
|
|
413
|
+
* unreadable source refuses by name. A source that is a web address
|
|
414
|
+
* (M10 item 1) is fetched and frozen by `freezePage`, in the same manifest.
|
|
415
|
+
* @param {string} runDir @param {Array<{id: string, path: string}>} sources
|
|
416
|
+
* @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>}} [o] */
|
|
417
|
+
export async function freezeInputs(runDir, sources, { fetchPage } = {}) {
|
|
397
418
|
const inputsDir = join(runDir, 'inputs');
|
|
398
419
|
mkdirSync(inputsDir, { recursive: true });
|
|
399
420
|
const manifest = [];
|
|
400
421
|
for (const { id, path: sourcePath } of sources ?? []) {
|
|
422
|
+
if (isWebUrl(sourcePath)) {
|
|
423
|
+
const page = await freezePage(inputsDir, id, sourcePath, { fetchPage });
|
|
424
|
+
if (!page.ok) return page;
|
|
425
|
+
manifest.push(page.entry);
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
401
428
|
if (!existsSync(sourcePath)) {
|
|
402
429
|
return { ok: false, red: `freeze: input "${id}" is unreadable at ${sourcePath}` };
|
|
403
430
|
}
|
|
@@ -569,7 +596,7 @@ export function readArtifact(runDir, id) {
|
|
|
569
596
|
* indistinguishable from "not written yet") into a step.
|
|
570
597
|
* @returns {{ok:true, map:Record<string,any>} | {ok:false, red:string}}
|
|
571
598
|
*/
|
|
572
|
-
function readArtifactsMapChecked(runDir, ids) {
|
|
599
|
+
export function readArtifactsMapChecked(runDir, ids, { docxRoles = /** @type {string[]} */ ([]) } = {}) {
|
|
573
600
|
const map = {};
|
|
574
601
|
for (const id of ids ?? []) {
|
|
575
602
|
const result = readArtifactResult(runDir, id);
|
|
@@ -581,12 +608,21 @@ function readArtifactsMapChecked(runDir, ids) {
|
|
|
581
608
|
const input = readInputCells(runDir, id);
|
|
582
609
|
if (!input.ok && !input.missing) return { ok: false, red: `input "${id}" — ${input.red}` };
|
|
583
610
|
if (input.ok) { map[id] = input.value; continue; }
|
|
611
|
+
// M10 am7 item 3: an id that names a saved web page (or a text file) is read as its text, from the RUN'S OWN frozen copy, sha-checked, through the one safe
|
|
612
|
+
// read gateway (`readFileInside`, in `readRunSource`). By role, text only: a copy that is missing or changed refuses the step; an id that is no text input
|
|
613
|
+
// of this run is left as it was (undefined).
|
|
614
|
+
const page = readRunSource(runDir, id, { docx: docxRoles.includes(id) });
|
|
615
|
+
if (page.ok) { map[id] = { kind: 'text', text: page.text }; continue; }
|
|
616
|
+
if (page.code === 'unreadable') return { ok: false, red: page.red };
|
|
584
617
|
}
|
|
585
618
|
map[id] = result.ok ? result.value : undefined;
|
|
586
619
|
}
|
|
587
620
|
return { ok: true, map };
|
|
588
621
|
}
|
|
589
622
|
|
|
623
|
+
/** M10 piece 5 (item 2): the role a green step quotes from - the one input whose .docx text its check (and so the step itself) may be handed. @param {any} step @returns {string[]} */
|
|
624
|
+
const citedRolesOf = (step) => (step?.close?.class === 'green' && typeof step.close.cited?.source === 'string' ? [step.close.cited.source] : []);
|
|
625
|
+
|
|
590
626
|
/** A frozen CSV input as `{kind:'cells', header, rows}` (the shape `addressCells` gives), checked against the sha256 recorded at freeze.
|
|
591
627
|
* Same three outcomes as `readArtifactResult`: not an input of this run (`missing`), refused (`red`), or the cells. */
|
|
592
628
|
function readInputCells(runDir, id) {
|
|
@@ -727,7 +763,7 @@ function makeAuditRow({
|
|
|
727
763
|
* @param {string|null} [opts.runDir] - M4d am29 item 2: the run's folder, where each try saves its checks
|
|
728
764
|
* @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string, stop?:{where:string, book:Record<string, any>, step?:string|null}}>}
|
|
729
765
|
*/
|
|
730
|
-
async function runStepRalph({
|
|
766
|
+
export async function runStepRalph({
|
|
731
767
|
step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
|
|
732
768
|
// M4d am25: the job's "Thinking on" box as the run's own copy keeps it; read once by the caller (`readJobThinking`), decided per try below by `stepThinkingMode`.
|
|
733
769
|
thinkingBox = false,
|
|
@@ -798,7 +834,9 @@ async function runStepRalph({
|
|
|
798
834
|
// scope item 3's own invariant: the schema is class-only, and the
|
|
799
835
|
// construction test below proves the context itself stays clean).
|
|
800
836
|
// M4d am25: `thinkingMode` is the ONE decision of what this try asks of thinking (`stepThinkingMode`); the model step only passes it on.
|
|
801
|
-
|
|
837
|
+
// M10 am7 item 3: `cited` is the fact part of a green step that quotes a saved page - the form of its ANSWER ({results: [{quote, values}]}) and the facts it must hold,
|
|
838
|
+
// told to the step in plain words by the model step. It is not the check: the quotes are checked by `closeCited` against the run's own copy.
|
|
839
|
+
const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
|
|
802
840
|
|
|
803
841
|
const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
|
|
804
842
|
|
|
@@ -865,6 +903,9 @@ async function runStepRalph({
|
|
|
865
903
|
// step's own failure to produce, not a system halt), strike-eligible
|
|
866
904
|
// like any other close red.
|
|
867
905
|
const red = result?.red ?? 'model step failed with no artifact';
|
|
906
|
+
// The try may have cost money (a length stop: "truncated: N tokens, no tool call"). Its row carries that cost below, so the run's spend
|
|
907
|
+
// - the cap check, the history total - takes it here, the same one add as the stop and transport branches (books must balance).
|
|
908
|
+
if (typeof result?.costUsd === 'number') spent.value += result.costUsd;
|
|
868
909
|
const normalised = normaliseGap(red);
|
|
869
910
|
const strike = seenGaps.has(normalised);
|
|
870
911
|
seenGaps.add(normalised);
|
|
@@ -934,7 +975,16 @@ async function runStepRalph({
|
|
|
934
975
|
continue;
|
|
935
976
|
}
|
|
936
977
|
|
|
937
|
-
|
|
978
|
+
// M10 piece 4: a step that cites quotes reads the run's OWN frozen copy of its source (never the drafting copy); the record of what the check said is
|
|
979
|
+
// written by the one writer, `writeCitedLine`, whatever the verdict - the Result tab says why a line did not pass.
|
|
980
|
+
const citedPart = step?.close?.class === 'green' ? step?.close?.cited : undefined;
|
|
981
|
+
const source = citedPart && runDir !== null ? readRunSource(runDir, citedPart.source, { docx: true }) : undefined;
|
|
982
|
+
const closed = await closeByClass(step, artifact, { reads: readsMap, businessDate, source });
|
|
983
|
+
if (citedPart && runDir !== null && closed.cited) {
|
|
984
|
+
writeCitedLine(runDir, citedLineOf({
|
|
985
|
+
n: step.fromLine, part: closed.cited.part, results: closed.cited.results, check: closed.cited.check,
|
|
986
|
+
}));
|
|
987
|
+
}
|
|
938
988
|
tryChecks.push(...closeRecords(step, artifact, closed));
|
|
939
989
|
saveTry();
|
|
940
990
|
|
|
@@ -991,16 +1041,20 @@ async function runStepRalph({
|
|
|
991
1041
|
* @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
|
|
992
1042
|
* @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
|
|
993
1043
|
* @param {number} [opts.ceilingUsd] - per-attempt ceiling override; the model's hold from Settings prices (`ceilingCostUsd`); absent = no hold.
|
|
1044
|
+
* @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run-model.json) and kept by every resume/continue.
|
|
994
1045
|
* @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
|
|
995
1046
|
* run): a human's rerun reason, carried as the FIRST ordinary step's
|
|
996
1047
|
* starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
|
|
997
1048
|
* own rerun path.
|
|
1049
|
+
* @param {(url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>} [opts.fetchPage] - M10: the web-page fetch (default barebrowse via src/pagefetch.js); a test injects one.
|
|
998
1050
|
* @param {() => number} [opts.nowMs] - F45 finding 3: returns the current
|
|
999
1051
|
* epoch ms; defaults to the wall clock. Mirrors `clock` (ISO) so a test
|
|
1000
1052
|
* can advance wall time across a park/resume boundary without a real wait.
|
|
1001
1053
|
*/
|
|
1002
1054
|
export async function runFlow({
|
|
1003
|
-
root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap,
|
|
1055
|
+
root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap, fetchPage,
|
|
1056
|
+
// M4d am33: the model this run STARTED on ({ slot, model }); recorded once beside the run, kept by every resume/continue. Absent = nothing recorded.
|
|
1057
|
+
runModel,
|
|
1004
1058
|
// F45 finding 3's test needs to advance wall time across a park/resume
|
|
1005
1059
|
// boundary without a real wait, exactly like `clock` already does for ISO
|
|
1006
1060
|
// timestamps — `nowMs` is the same idea for epoch-ms wall-clock reads.
|
|
@@ -1107,8 +1161,9 @@ export async function runFlow({
|
|
|
1107
1161
|
|
|
1108
1162
|
// M4d am25: the run keeps the job's "Thinking on" box as it is now (read by `readJobThinking` on every try and every resume)
|
|
1109
1163
|
writeRunThinking(flowDir, runDir);
|
|
1164
|
+
if (runModel) writeRunModel(runDir, runModel); // M4d am33: the one record of the model this run started on
|
|
1110
1165
|
|
|
1111
|
-
const frozen = freezeInputs(runDir, sources ?? []);
|
|
1166
|
+
const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage });
|
|
1112
1167
|
if (!frozen.ok) {
|
|
1113
1168
|
return haltRun({
|
|
1114
1169
|
flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
|
|
@@ -1259,6 +1314,19 @@ function makeOneShotThenParkAskStep({ decision, reason, artifactSha256 }) {
|
|
|
1259
1314
|
};
|
|
1260
1315
|
}
|
|
1261
1316
|
|
|
1317
|
+
/**
|
|
1318
|
+
* M4d am30: the highest try number a step has used in this run, read from the books (audit.jsonl, the source of truth). A Redo's re-run is
|
|
1319
|
+
* numbered after it, so a number is used once per step. Only the NUMBER moves: the limit counts the re-run's own tries (`n` in `runStepRalph`).
|
|
1320
|
+
* @param {string} runDir @param {string|null} stepId
|
|
1321
|
+
*/
|
|
1322
|
+
function lastTryNumber(runDir, stepId) {
|
|
1323
|
+
let last = 0;
|
|
1324
|
+
for (const r of readAudit(runDir)) {
|
|
1325
|
+
if (r.step === stepId && Number.isInteger(r.attempt) && r.verdict !== 'cap-halt' && r.verdict !== 'stop-asked' && r.verdict !== 'stop-not-honoured' && r.attempt > last) last = r.attempt;
|
|
1326
|
+
}
|
|
1327
|
+
return last;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1262
1330
|
/**
|
|
1263
1331
|
* One signed ask slot's own loop (M2's ask branch, unchanged in spirit,
|
|
1264
1332
|
* extracted so `resumeRun` can re-enter the SAME logic mid-ask instead of
|
|
@@ -1453,13 +1521,13 @@ async function runAskSlot({
|
|
|
1453
1521
|
// swap / unparseable JSON) is tampering, never "not written yet", and
|
|
1454
1522
|
// must halt the redo rather than silently feed forged/garbage content
|
|
1455
1523
|
// into the model step that is about to re-run.
|
|
1456
|
-
const priorReadsResult = readArtifactsMapChecked(runDir, priorStep.reads);
|
|
1524
|
+
const priorReadsResult = readArtifactsMapChecked(runDir, priorStep.reads, { docxRoles: citedRolesOf(priorStep) });
|
|
1457
1525
|
if (!priorReadsResult.ok) {
|
|
1458
1526
|
return { type: 'halted', outcome: 'red', red: `redo: step "${priorStep.goal}" ${priorReadsResult.red}` };
|
|
1459
1527
|
}
|
|
1460
1528
|
// eslint-disable-next-line no-await-in-loop
|
|
1461
1529
|
const redoResult = await runStepRalph({
|
|
1462
|
-
step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset:
|
|
1530
|
+
step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
|
|
1463
1531
|
readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
|
|
1464
1532
|
});
|
|
1465
1533
|
if (!redoResult.ok) {
|
|
@@ -1700,7 +1768,7 @@ async function foldFromStep({
|
|
|
1700
1768
|
// F48 round 4: every id in `step.reads` names an earlier step in THIS
|
|
1701
1769
|
// same fold pass, already run and already written — a `red` read here
|
|
1702
1770
|
// halts rather than silently feeding tampered/unreadable content in.
|
|
1703
|
-
const readsMapResult = readArtifactsMapChecked(runDir, step.reads);
|
|
1771
|
+
const readsMapResult = readArtifactsMapChecked(runDir, step.reads, { docxRoles: citedRolesOf(step) });
|
|
1704
1772
|
if (!readsMapResult.ok) {
|
|
1705
1773
|
return haltRun({
|
|
1706
1774
|
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
@@ -1890,11 +1958,13 @@ function sameRoot(recorded, requested) {
|
|
|
1890
1958
|
* @param {() => string} [opts.clock]
|
|
1891
1959
|
* @param {string} opts.businessDate
|
|
1892
1960
|
* @param {number} [opts.ceilingUsd]
|
|
1961
|
+
* @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run-model.json) and kept by every resume/continue.
|
|
1893
1962
|
* @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
|
|
1894
1963
|
* @param {(newRunDir:string) => void} [opts.onRerunStart] - amendment 16 C2: called with the new run's folder just before a `rerun` starts it.
|
|
1895
1964
|
*/
|
|
1896
1965
|
export async function resumeRun({
|
|
1897
1966
|
root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd,
|
|
1967
|
+
runModel, // M4d am33: the model the resumed run keeps; a rerun (a new run) records it too
|
|
1898
1968
|
// F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
|
|
1899
1969
|
// real `Date.now` for every existing caller.
|
|
1900
1970
|
nowMs,
|
|
@@ -2237,6 +2307,7 @@ export async function resumeRun({
|
|
|
2237
2307
|
clock,
|
|
2238
2308
|
businessDate,
|
|
2239
2309
|
ceilingUsd,
|
|
2310
|
+
runModel,
|
|
2240
2311
|
// Item 7: the reason becomes the new run's FIRST step's starting gap.
|
|
2241
2312
|
initialGap: reason,
|
|
2242
2313
|
});
|