fwdloop 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/bin/fwdloop +85 -34
  2. package/package.json +4 -3
  3. package/src/ask.js +20 -4
  4. package/src/audit-fold.js +5 -1
  5. package/src/authoring.js +36 -6
  6. package/src/canrun.js +5 -0
  7. package/src/checked.js +32 -4
  8. package/src/cited-record.js +138 -0
  9. package/src/cited-source.js +49 -0
  10. package/src/citedcheck.js +321 -0
  11. package/src/citedwords.js +197 -0
  12. package/src/closers.js +37 -198
  13. package/src/csv.js +69 -12
  14. package/src/ctx-tools.js +2 -14
  15. package/src/declaration.js +143 -5
  16. package/src/diary.js +2 -2
  17. package/src/docx.js +16 -2
  18. package/src/draft-steps.js +1 -1
  19. package/src/drafter.js +322 -33
  20. package/src/flow.js +33 -7
  21. package/src/flowmodel.js +21 -0
  22. package/src/input-facts.js +20 -3
  23. package/src/model-step.js +38 -21
  24. package/src/pageask.js +136 -0
  25. package/src/pagebits.js +107 -0
  26. package/src/pagedropwords.js +171 -0
  27. package/src/pagedry.js +120 -0
  28. package/src/pagefetch.js +164 -0
  29. package/src/pagelook.js +155 -0
  30. package/src/pagemap.js +55 -0
  31. package/src/pageplace.js +103 -0
  32. package/src/pagerules.js +318 -0
  33. package/src/panel/author.js +43 -21
  34. package/src/panel/authorcard.js +20 -3
  35. package/src/panel/authorflows.js +21 -15
  36. package/src/panel/authorstart.js +2 -4
  37. package/src/panel/authortrigger.js +14 -4
  38. package/src/panel/data.js +102 -6
  39. package/src/panel/index.html +321 -12
  40. package/src/panel/result.js +301 -0
  41. package/src/panel/server.js +27 -3
  42. package/src/primitives.js +2 -3
  43. package/src/provider.js +5 -2
  44. package/src/redact.js +17 -0
  45. package/src/runner.js +102 -14
  46. package/src/schedule.js +3 -3
  47. package/src/setup.js +16 -1
  48. package/src/sheet-record.js +57 -0
  49. package/src/sheetblock.js +170 -0
  50. package/src/sheetchecks.js +206 -0
  51. package/src/sheetclaims.js +78 -0
  52. package/src/sheetfind.js +50 -0
  53. package/src/sheetlook.js +157 -0
  54. package/src/sheetoffer.js +125 -0
  55. package/src/sheetrun.js +105 -0
  56. package/src/signed-text.js +11 -1
  57. package/src/thinking.js +1 -1
  58. package/src/try-checks.js +12 -0
  59. package/src/types.js +4 -11
  60. package/types/ask.d.ts +2 -1
  61. package/types/authoring.d.ts +19 -2
  62. package/types/checked.d.ts +19 -3
  63. package/types/cited-record.d.ts +21 -0
  64. package/types/cited-source.d.ts +18 -0
  65. package/types/citedcheck.d.ts +95 -0
  66. package/types/citedwords.d.ts +97 -0
  67. package/types/closers.d.ts +37 -10
  68. package/types/csv.d.ts +25 -4
  69. package/types/ctx-tools.d.ts +0 -1
  70. package/types/declaration.d.ts +20 -1
  71. package/types/docx.d.ts +14 -0
  72. package/types/drafter.d.ts +264 -8
  73. package/types/flow.d.ts +21 -0
  74. package/types/flowmodel.d.ts +15 -0
  75. package/types/input-facts.d.ts +12 -2
  76. package/types/model-step.d.ts +40 -19
  77. package/types/pageask.d.ts +75 -0
  78. package/types/pagebits.d.ts +32 -0
  79. package/types/pagedropwords.d.ts +40 -0
  80. package/types/pagedry.d.ts +38 -0
  81. package/types/pagefetch.d.ts +86 -0
  82. package/types/pagelook.d.ts +75 -0
  83. package/types/pagemap.d.ts +31 -0
  84. package/types/pageplace.d.ts +22 -0
  85. package/types/pagerules.d.ts +86 -0
  86. package/types/panel/authorcard.d.ts +4 -1
  87. package/types/panel/authorflows.d.ts +2 -0
  88. package/types/panel/data.d.ts +26 -0
  89. package/types/panel/result.d.ts +156 -0
  90. package/types/provider.d.ts +3 -1
  91. package/types/redact.d.ts +1 -0
  92. package/types/runner.d.ts +162 -9
  93. package/types/schedule.d.ts +0 -11
  94. package/types/setup.d.ts +13 -0
  95. package/types/sheet-record.d.ts +24 -0
  96. package/types/sheetblock.d.ts +116 -0
  97. package/types/sheetchecks.d.ts +70 -0
  98. package/types/sheetclaims.d.ts +26 -0
  99. package/types/sheetfind.d.ts +46 -0
  100. package/types/sheetlook.d.ts +120 -0
  101. package/types/sheetoffer.d.ts +25 -0
  102. package/types/sheetrun.d.ts +35 -0
  103. package/types/thinking.d.ts +1 -1
  104. package/types/types.d.ts +27 -14
@@ -0,0 +1,301 @@
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
+ import { sheetLineBlocks, csvRolesOf } from '../sheetblock.js';
24
+ import { readSheetChecks } from '../sheet-record.js';
25
+
26
+ /** the two sentences for a saved file that is no longer what the run wrote (code-owned, one spelling) */
27
+ export const RESULT_FILE_GONE = 'the saved file is gone';
28
+ export const RESULT_FILE_CHANGED = 'the saved file changed after the run';
29
+ /** 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 */
30
+ export const RESULT_PAGE_MAY_CHANGE = 'The page may have changed since this run.';
31
+ /** the words after a fact whose limit the person agreed to */
32
+ export const RESULT_YOU_CONFIRMED = '(you confirmed)';
33
+ /** the Your-call card's words (bareloop server.js@2959217 DOOR_WORDS.waiting.head and RESULT_DOOR_ASK); the page types none of them */
34
+ export const RESULT_DOOR_HEAD = 'waiting for you';
35
+ export const RESULT_DOOR_ASK = 'the checks passed; is this what you wanted?';
36
+ /** the M10 cited-check record, in the run's own folder: `writeCitedLine` (src/cited-record.js) is its one writer, `readCitedChecks` its one reader. */
37
+ export { CITED_CHECKS_FILE };
38
+
39
+ /** end-row outcomes that are not a failure of the job */
40
+ const NOT_FAILED = new Set(['complete', 'stopped', 'cap-halt', 'rerun', 'ask-expired']);
41
+ const FACT_KINDS = new Set(['phrase', 'value']);
42
+ const isInt = (x) => Number.isInteger(x);
43
+ const isStr = (x) => typeof x === 'string';
44
+
45
+ /**
46
+ * 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.
47
+ * @param {any} arbiter @returns {boolean}
48
+ */
49
+ export function isResultRun(arbiter) {
50
+ const sources = Array.isArray(arbiter?.sources) ? arbiter.sources : [];
51
+ return sources.some((s) => s && (s.kind === 'page' || (isStr(s.path) && (isCellsPath(s.path) || s.path.toLowerCase().endsWith('.docx')))));
52
+ }
53
+
54
+ /** The run's check type: its distinct close classes, in step order (`hitl + softgreen`). `—` for a declaration with none.
55
+ * @param {any} declaration @returns {string} */
56
+ export function checkTypeOf(declaration) {
57
+ const seen = [];
58
+ for (const s of Array.isArray(declaration?.steps) ? declaration.steps : []) {
59
+ const c = s?.close?.class;
60
+ if (isStr(c) && !seen.includes(c)) seen.push(c);
61
+ }
62
+ return seen.length > 0 ? seen.join(' + ') : '—';
63
+ }
64
+
65
+ /**
66
+ * 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
67
+ * overlapping. Anything else is `null`: the page then shows the plain quote (bareloop's "no proof" path), never marks cut at wrong offsets.
68
+ * @param {any} p @returns {{text: string, marks: number[][]}|null}
69
+ */
70
+ function readProof(p) {
71
+ if (!p || !isStr(p.text) || !Array.isArray(p.marks)) return null;
72
+ let at = 0;
73
+ for (const m of p.marks) {
74
+ 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;
75
+ at = m[1];
76
+ }
77
+ return { text: p.text, marks: p.marks.map((m) => [m[0], m[1]]) };
78
+ }
79
+
80
+ /**
81
+ * The ONE reader of the M10 cited-check record (`<run>/cited-checks.json`). Expected shape (typed, nothing parsed out of prose):
82
+ * { lines: [ { n: int, source: string (the role of a signed source), passed: boolean,
83
+ * facts: [ { name: string, kind: 'phrase'|'value', sentence: string, confirmed?: true } ],
84
+ * rows: [ { n: int, quote: string, cells: string[] (one per fact), proof?: { text: string, marks: [[start, end], ...] } } ] | null,
85
+ * notChecked?: string[] } ] }
86
+ * `{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}`.
87
+ * @param {string} runDir
88
+ * @returns {{present: false}|{present: true, ok: false, red: string}|{present: true, ok: true, lines: any[]}}
89
+ */
90
+ export function readCitedChecks(runDir) {
91
+ const r = readFileInside(runDir, CITED_CHECKS_FILE);
92
+ if (!r.ok) return r.missing ? { present: false } : { present: true, ok: false, red: r.red };
93
+ /** @param {string} why @returns {{present: true, ok: false, red: string}} */
94
+ const red = (why) => ({ present: true, ok: false, red: `${CITED_CHECKS_FILE}: ${why}` });
95
+ let rec;
96
+ try { rec = JSON.parse(r.text); } catch { return red('not valid JSON'); }
97
+ if (!rec || !Array.isArray(rec.lines)) return red('"lines" is not a list');
98
+ const lines = [];
99
+ for (const l of rec.lines) {
100
+ if (!l || !isInt(l.n) || !isStr(l.source)) return red('a line needs an integer "n" and a "source"');
101
+ if (typeof l.passed !== 'boolean') return red(`line ${l.n}: "passed" is not true or false`);
102
+ if (!Array.isArray(l.facts)) return red(`line ${l.n}: "facts" is not a list`);
103
+ const facts = [];
104
+ for (const f of l.facts) {
105
+ if (!f || !isStr(f.name) || !isStr(f.sentence)) return red(`line ${l.n}: a fact needs a "name" and a "sentence"`);
106
+ if (!FACT_KINDS.has(f.kind)) return red(`line ${l.n}: fact "${f.name}" has a "kind" that is not phrase or value`);
107
+ facts.push({ name: f.name, kind: f.kind, sentence: f.sentence, ...(f.confirmed === true ? { confirmed: true } : {}) });
108
+ }
109
+ let rows = null;
110
+ if (l.rows !== null && l.rows !== undefined) {
111
+ if (!Array.isArray(l.rows)) return red(`line ${l.n}: "rows" is not a list`);
112
+ rows = [];
113
+ for (const w of l.rows) {
114
+ if (!w || !isInt(w.n) || !isStr(w.quote)) return red(`line ${l.n}: a row needs an integer "n" and a "quote"`);
115
+ 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})`);
116
+ const proof = readProof(w.proof);
117
+ rows.push({
118
+ n: w.n, quote: w.quote, ...(proof ? { proof } : {}), cells: [...w.cells],
119
+ });
120
+ }
121
+ }
122
+ const nc = Array.isArray(l.notChecked) ? l.notChecked.filter((x) => isStr(x) && x.trim() !== '') : [];
123
+ lines.push({
124
+ n: l.n, source: l.source, passed: l.passed, facts, rows, notChecked: nc,
125
+ });
126
+ }
127
+ return { present: true, ok: true, lines };
128
+ }
129
+
130
+ /**
131
+ * 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,
132
+ * 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
133
+ * 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
134
+ * in the signed rule confirms nothing; nothing is guessed.
135
+ * @param {any[]} setupRows @param {number} lineN @param {string} signedRule the line's signed guardrail @param {string[]} factNames
136
+ * @returns {Set<string>}
137
+ */
138
+ export function confirmedFactNames(setupRows, lineN, signedRule, factNames) {
139
+ const names = new Set();
140
+ const written = lineRules({ rule: signedRule });
141
+ for (const h of Array.isArray(setupRows) ? setupRows : []) {
142
+ if (h?.kind !== 'human' || h.source !== 'look' || h.line !== lineN || !isAgree(h.answer)) continue; // eslint-disable-line no-continue
143
+ const reading = readingOfQuestion(h.question);
144
+ if (reading === null || !written.includes(reading)) continue; // eslint-disable-line no-continue
145
+ for (const name of factNames) if (reading.startsWith(`${name} `)) names.add(name);
146
+ }
147
+ return names;
148
+ }
149
+
150
+ /** the signed `page:` sources, role -> address (http(s) only: the parser already refuses any other) @param {any} arbiter @returns {Map<string, string>} */
151
+ function pageUrlsByRole(arbiter) {
152
+ const out = new Map();
153
+ for (const s of Array.isArray(arbiter?.sources) ? arbiter.sources : []) if (s && s.kind === 'page' && isStr(s.path)) out.set(s.role, s.path);
154
+ return out;
155
+ }
156
+
157
+ /**
158
+ * 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
159
+ * 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:
160
+ * stale bytes are never returned. (Text read, so a file that is not UTF-8 reads as "changed", never as ok.)
161
+ * @param {{name: string, dir: string|null, sha256: string|null}} rec
162
+ * @returns {{state: 'ok', buf: Buffer}|{state: 'gone'|'changed', buf: null}}
163
+ */
164
+ export function readDelivered(rec) {
165
+ if (rec.dir === null) return { state: 'gone', buf: null };
166
+ const r = readFileInside(rec.dir, rec.name);
167
+ if (!r.ok) return { state: 'gone', buf: null };
168
+ const buf = Buffer.from(r.text, 'utf8');
169
+ if (rec.sha256 === null || createHash('sha256').update(buf).digest('hex') !== rec.sha256) return { state: 'changed', buf: null };
170
+ return { state: 'ok', buf };
171
+ }
172
+
173
+ /**
174
+ * 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`
175
+ * in the signed folder, with the sha256 the human's accept recorded for the ask that send reads (`readAcceptedHashesByEmits`, the same record the
176
+ * send itself checked). No accepted hash = recorded as null, which reads as "changed", never as ok.
177
+ * @returns {{path: string, dir: string|null, name: string, sha256: string|null}[]}
178
+ */
179
+ export function deliveredOf({
180
+ arbiter, declaration, runDir, root, flow, runId, auditRows,
181
+ }) {
182
+ const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
183
+ const askLines = new Set((arbiter?.asks ?? []).map((a) => a.line));
184
+ const askEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
185
+ const hashes = readAcceptedHashesByEmits(runDir);
186
+ const out = [];
187
+ for (const send of arbiter?.sends ?? []) {
188
+ const step = steps.find((s) => s.fromLine === send.line);
189
+ if (!step || !auditRows.some((r) => r.step === step.emits && r.verdict === 'green')) continue; // eslint-disable-line no-continue
190
+ const name = `${flow}-${runId}-${step.emits}.json`;
191
+ const dest = checkSendDestination(`${send.target.kind}:${send.target.path}`, { root, runDir });
192
+ const [askId] = (step.reads ?? []).filter((id) => askEmits.has(id));
193
+ out.push({
194
+ path: join(dest.ok ? dest.dir : send.target.path, name), dir: dest.ok ? dest.dir : null, name,
195
+ sha256: hashes.ok && askId !== undefined ? (hashes.byEmits.get(askId) ?? null) : null,
196
+ });
197
+ }
198
+ return out;
199
+ }
200
+
201
+ /**
202
+ * 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
203
+ * 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.
204
+ * @param {any[]} stepsOfLine the declaration's steps for the line @param {any[]} diary `readChecks(runDir)`
205
+ * @returns {{ok: boolean, text: string, result: string|null}[]}
206
+ */
207
+ function checksOfLine(stepsOfLine, diary) {
208
+ const out = [];
209
+ for (const st of stepsOfLine) {
210
+ const rows = diary.filter((r) => r && r.step === st.emits && isInt(r.try) && Array.isArray(r.checks));
211
+ const newest = rows.reduce((m, r) => (m === null || r.try >= m.try ? r : m), null);
212
+ 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 });
213
+ }
214
+ return out;
215
+ }
216
+
217
+ /** 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} */
218
+ function gapOf(text) {
219
+ const rows = isStr(text) ? text.split('\n').map((x) => x.trim()).filter((x) => x !== '') : [];
220
+ if (rows.length === 0) return null;
221
+ const more = rows.length - 1;
222
+ return { line: rows[0], more, moreText: more > 0 ? `(+${more} more)` : null };
223
+ }
224
+
225
+ /**
226
+ * The Result tab's JSON for one run (`GET /api/runs/:flow/:runId/result`).
227
+ * @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
228
+ */
229
+ export function buildResult({
230
+ flow, runId, runDir, root, flowRead, arbiter, historyRow, auditRows, logJson, notChecked, readNotes = [], setupRows = [], door = null,
231
+ }) {
232
+ const declaration = flowRead.declaration;
233
+ const taken = new Set([...(arbiter?.asks ?? []), ...(arbiter?.sends ?? [])].map((x) => x.line));
234
+ const cited = readCitedChecks(runDir);
235
+ const record = cited.present && cited.ok ? cited.lines : [];
236
+ const urls = pageUrlsByRole(arbiter);
237
+ // am9: a page job's card is bareloop's (no checks list); every other job lists what each step checked
238
+ const diary = urls.size === 0 ? readChecks(runDir) : [];
239
+ // M10b am2: the block of every job line that reads a sheet (guardrails, Checked with ✓ / ✗ and what was found, Not checked), from the signed job and the run's
240
+ // sheet-checks.json; it is there with no rows found and when the result is written to a doc
241
+ const sheetBlocks = sheetLineBlocks({ declaration, lines: flowRead.lines, csvRoles: csvRolesOf(arbiter), record: readSheetChecks(runDir) });
242
+ const lines = flowRead.lines.filter((l) => !taken.has(l.n)).map((l) => {
243
+ const c = record.find((x) => x.n === l.n) ?? null;
244
+ const out = {
245
+ notChecked: c ? c.notChecked : [], n: l.n, text: l.text, rules: isStr(l.guardrail) && l.guardrail !== '' ? [l.guardrail] : [],
246
+ kind: c ? 'facts' : 'text', passed: c ? c.passed : false, file: null,
247
+ checks: checksOfLine((declaration?.steps ?? []).filter((st) => st.fromLine === l.n), diary),
248
+ sheet: sheetBlocks.find((b) => b.line === l.n) ?? null,
249
+ };
250
+ if (c) {
251
+ out.source = c.source;
252
+ out.page = urls.get(c.source) ?? null;
253
+ const agreed = confirmedFactNames(setupRows, l.n, isStr(l.guardrail) ? l.guardrail : '', c.facts.map((f) => f.name));
254
+ out.facts = c.facts.map((f) => ({
255
+ name: f.name, kind: f.kind, sentence: f.sentence, ...(f.confirmed || agreed.has(f.name) ? { note: RESULT_YOU_CONFIRMED } : {}),
256
+ }));
257
+ out.rows = c.rows;
258
+ }
259
+ return out;
260
+ });
261
+ const delivered = deliveredOf({
262
+ arbiter, declaration, runDir, root, flow, runId, auditRows,
263
+ }).map((d, i) => {
264
+ const got = readDelivered(d);
265
+ return {
266
+ i, path: d.path, name: d.name, bytes: got.buf ? got.buf.length : null, state: got.state,
267
+ words: got.state === 'gone' ? RESULT_FILE_GONE : (got.state === 'changed' ? RESULT_FILE_CHANGED : null),
268
+ };
269
+ });
270
+ // 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
271
+ // set `computeGlyph` colours `[✗]` by exclusion); a pause has no end row at all.
272
+ let gap = null;
273
+ if (historyRow && !NOT_FAILED.has(historyRow.outcome)) {
274
+ const redRow = auditRows.findLast((r) => r.verdict === 'red' || r.verdict === 'not-done');
275
+ gap = gapOf(isStr(logJson?.red) && logJson.red !== '' ? logJson.red : (redRow ? `${redRow.step}: ${redRow.gap}` : null));
276
+ }
277
+ const pages = [...new Set(urls.values())];
278
+ return {
279
+ 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,
280
+ door: door === null ? null : { head: RESULT_DOOR_HEAD, ask: RESULT_DOOR_ASK, askId: door.askId, draftNo: door.draftNo },
281
+ };
282
+ }
283
+
284
+ /** download content types by extension; anything else is plain bytes */
285
+ const DOWNLOAD_TYPES = { '.json': 'application/json', '.md': 'text/plain', '.txt': 'text/plain', '.csv': 'text/csv' };
286
+
287
+ /**
288
+ * `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.
289
+ * @param {{index: unknown, ctx: any}} a
290
+ * @returns {{ok: true, name: string, type: string, buf: Buffer}|{ok: false, code: number, error: string}}
291
+ */
292
+ export function downloadOf({ index, ctx }) {
293
+ const list = deliveredOf(ctx);
294
+ const i = typeof index === 'string' && /^\d{1,6}$/.test(index) ? Number(index) : -1;
295
+ if (i < 0 || i >= list.length) return { ok: false, code: 404, error: 'this run saved no such file' };
296
+ const got = readDelivered(list[i]);
297
+ if (got.state !== 'ok') return { ok: false, code: 409, error: got.state === 'gone' ? RESULT_FILE_GONE : RESULT_FILE_CHANGED };
298
+ const name = basename(list[i].path);
299
+ const ext = name.includes('.') ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
300
+ return { ok: true, name, type: Object.hasOwn(DOWNLOAD_TYPES, ext) ? DOWNLOAD_TYPES[ext] : 'application/octet-stream', buf: /** @type {Buffer} */ (got.buf) };
301
+ }
@@ -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: what the gate last decided and how many times it was asked, so a tool call's diary row can say `allow`, the deny and its rule,
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, last: /** @type {{outcome:string, rule:string|null}|null} */ (null) };
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
- return (CEILING_INPUT_TOKENS / 1000) * rates.in + (CEILING_OUTPUT_TOKENS / 1000) * rates.out;
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 });