fwdloop 0.20.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.
Files changed (92) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +85 -34
  3. package/package.json +4 -3
  4. package/src/audit-fold.js +181 -0
  5. package/src/authoring.js +33 -7
  6. package/src/books.js +1 -1
  7. package/src/checked.js +18 -1
  8. package/src/cited-record.js +138 -0
  9. package/src/cited-source.js +49 -0
  10. package/src/citedcheck.js +306 -0
  11. package/src/citedwords.js +197 -0
  12. package/src/closers.js +105 -9
  13. package/src/ctx-tools.js +2 -14
  14. package/src/declaration.js +85 -5
  15. package/src/diary.js +49 -0
  16. package/src/docx.js +16 -2
  17. package/src/draft-steps.js +1 -1
  18. package/src/drafter.js +292 -25
  19. package/src/flow.js +33 -7
  20. package/src/flowmodel.js +63 -5
  21. package/src/input-facts.js +20 -3
  22. package/src/model-step.js +132 -9
  23. package/src/pageask.js +136 -0
  24. package/src/pagebits.js +107 -0
  25. package/src/pagedropwords.js +171 -0
  26. package/src/pagedry.js +120 -0
  27. package/src/pagefetch.js +164 -0
  28. package/src/pagelook.js +155 -0
  29. package/src/pagemap.js +55 -0
  30. package/src/pageplace.js +103 -0
  31. package/src/pagerules.js +318 -0
  32. package/src/panel/author.js +41 -20
  33. package/src/panel/authorcard.js +11 -1
  34. package/src/panel/authorflows.js +21 -15
  35. package/src/panel/authorstart.js +2 -4
  36. package/src/panel/authortrigger.js +14 -4
  37. package/src/panel/data.js +130 -10
  38. package/src/panel/index.html +499 -41
  39. package/src/panel/result.js +295 -0
  40. package/src/panel/server.js +27 -3
  41. package/src/primitives.js +43 -2
  42. package/src/provider.js +5 -2
  43. package/src/redact.js +17 -0
  44. package/src/runner.js +128 -21
  45. package/src/schedule.js +3 -3
  46. package/src/setup.js +16 -1
  47. package/src/sheetfind.js +50 -0
  48. package/src/sheetlook.js +157 -0
  49. package/src/signed-text.js +11 -1
  50. package/src/thinking.js +39 -0
  51. package/src/try-checks.js +68 -0
  52. package/src/types.js +4 -2
  53. package/types/audit-fold.d.ts +54 -0
  54. package/types/authoring.d.ts +20 -2
  55. package/types/books.d.ts +17 -0
  56. package/types/checked.d.ts +10 -0
  57. package/types/cited-record.d.ts +21 -0
  58. package/types/cited-source.d.ts +18 -0
  59. package/types/citedcheck.d.ts +95 -0
  60. package/types/citedwords.d.ts +97 -0
  61. package/types/closers.d.ts +55 -3
  62. package/types/declaration.d.ts +15 -1
  63. package/types/diary.d.ts +57 -0
  64. package/types/docx.d.ts +14 -0
  65. package/types/drafter.d.ts +244 -2
  66. package/types/flow.d.ts +21 -0
  67. package/types/flowmodel.d.ts +40 -3
  68. package/types/input-facts.d.ts +12 -2
  69. package/types/model-step.d.ts +38 -3
  70. package/types/pageask.d.ts +75 -0
  71. package/types/pagebits.d.ts +32 -0
  72. package/types/pagedropwords.d.ts +40 -0
  73. package/types/pagedry.d.ts +38 -0
  74. package/types/pagefetch.d.ts +86 -0
  75. package/types/pagelook.d.ts +75 -0
  76. package/types/pagemap.d.ts +31 -0
  77. package/types/pageplace.d.ts +22 -0
  78. package/types/pagerules.d.ts +86 -0
  79. package/types/panel/authorcard.d.ts +2 -0
  80. package/types/panel/authorflows.d.ts +2 -0
  81. package/types/panel/data.d.ts +26 -0
  82. package/types/panel/result.d.ts +156 -0
  83. package/types/provider.d.ts +3 -1
  84. package/types/redact.d.ts +1 -0
  85. package/types/runner.d.ts +156 -7
  86. package/types/schedule.d.ts +0 -11
  87. package/types/setup.d.ts +13 -0
  88. package/types/sheetfind.d.ts +46 -0
  89. package/types/sheetlook.d.ts +120 -0
  90. package/types/thinking.d.ts +31 -0
  91. package/types/try-checks.d.ts +55 -0
  92. package/types/types.d.ts +20 -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
+ }
@@ -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
@@ -32,6 +32,8 @@ import { primitiveFor, loadCatalogue } from './catalogue.js';
32
32
  import { readDocxText } from './docx.js';
33
33
  import { parseCsv } from './csv.js';
34
34
  import { makeCtxTools } from './ctx-tools.js';
35
+ import { diaryPaths } from './diary.js';
36
+ import { readdirInside } from './flow.js';
35
37
 
36
38
  // bare-agent >=0.47.0: `noFollowSymlinks: true` makes shell_read/write/edit/
37
39
  // grep throw `err.code === 'ELOOP'` when the path's FINAL component is a
@@ -172,6 +174,9 @@ function sandboxedReadTool(gate, runDir, inputsByRole) {
172
174
  };
173
175
  }
174
176
 
177
+ /** bare-agent's shell_grep default cap (DEFAULT_GREP_MAX_MATCHES, not exported) — mirrored for the entry-by-entry grep. */
178
+ const GREP_DEFAULT_MAX_MATCHES = 200;
179
+
175
180
  function sandboxedGrepTool(gate, runDir, inputsByRole) {
176
181
  const real = shellTool('shell_grep');
177
182
  const textRoles = Object.keys(inputsByRole).filter((r) => rolePrimitiveFor(inputsByRole[r]) === 'read');
@@ -181,7 +186,31 @@ function sandboxedGrepTool(gate, runDir, inputsByRole) {
181
186
  parameters: roleParameters(real, textRoles),
182
187
  execute: async (args) => {
183
188
  const resolvedPath = await resolveRoleOrPath(gate, 'grep', 'grep', runDir, args, inputsByRole, textRoles);
184
- return real.execute({ ...args, path: resolvedPath });
189
+ // M4d am29 item 3: the gate only denies the diaries by name, and bare-agent's grep stops at its cap with no exclude option. A folder that holds a diary
190
+ // (the run folder itself) is therefore grepped entry by entry, diaries left out BEFORE the cap, each entry through the same gate.
191
+ const diaries = new Set(diaryPaths(runDir).map((p) => path.resolve(p)));
192
+ const dir = path.resolve(resolvedPath);
193
+ let found;
194
+ if (dir === path.resolve(runDir)) {
195
+ const cap = args.maxMatches || GREP_DEFAULT_MAX_MATCHES;
196
+ const hits = [];
197
+ let fileCount = 0;
198
+ for (const name of readdirInside(runDir, '').sort()) {
199
+ const entry = path.join(dir, name);
200
+ if (diaries.has(entry) || hits.length >= cap) continue;
201
+ // not recursive: top-level files only; readdirInside lists a directory's entries and nothing for a file
202
+ if (args.recursive === false && readdirInside(runDir, name).length) continue;
203
+ const gated = await resolveAndGate(gate, 'grep', 'grep', runDir, entry);
204
+ const part = await real.execute({ ...args, path: gated, maxMatches: cap - hits.length });
205
+ hits.push(...(part?.hits ?? []));
206
+ fileCount += part?.fileCount ?? 0;
207
+ }
208
+ found = { hits, truncated: hits.length >= cap, fileCount };
209
+ } else {
210
+ found = await real.execute({ ...args, path: resolvedPath });
211
+ }
212
+ // safety net for any other path shape: a diary hit never reaches the model
213
+ return found && Array.isArray(found.hits) ? { ...found, hits: found.hits.filter((h) => !diaries.has(path.resolve(String(h?.file)))) } : found;
185
214
  },
186
215
  };
187
216
  }
@@ -320,11 +349,22 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
320
349
  // and a red naming bareguard's own message, so the caller refuses the run.
321
350
  let gate;
322
351
  try {
323
- gate = new Gate({ fs: { readScope, writeScope: [outDir] } });
352
+ // M4d am29 item 3: the diaries are denied to the model by name (bareloop's `fs.deny` of its audit sidecar path)
353
+ gate = new Gate({ fs: { readScope, writeScope: [outDir], deny: diaryPaths(runDir) } });
324
354
  } catch (err) {
325
355
  return { tools: {}, reds: [`primitives: bareguard refused the step's file scope — ${err.message}`] };
326
356
  }
327
357
 
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
+ // 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 };
361
+ const askGate = gate.check.bind(gate);
362
+ gate.check = async (action) => {
363
+ const decision = await askGate(action);
364
+ gateSeen.n += 1;
365
+ return decision;
366
+ };
367
+
328
368
  const tools = {};
329
369
  const reds = [];
330
370
  // Built on demand, once: nothing is opened or created here (the store is opened per call, inside a tool).
@@ -379,5 +419,6 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
379
419
  }
380
420
  }
381
421
 
422
+ for (const verb of Object.keys(tools)) tools[verb] = { ...tools[verb], gateSeen };
382
423
  return { tools, reds };
383
424
  }
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 });