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,157 @@
1
+ // M10 piece 5 (item 3 + item 7, for a sheet): the sheet-word look for ONE CSV input. One AI call names the job's own word for each rule (the column it means);
2
+ // CODE keeps a word only when it is a real column of the sheet, and when it is not, finds the column to offer (src/sheetfind.js) and builds the ask. The model
3
+ // names a word and a kind and nothing else: it never names a column to offer, never decides an ask, and never writes a question (the words are code's).
4
+ // The page look's call shape is reused (src/pagelook.js `lookAtPage`): the same system words, one retry on an unreadable answer, the same stop words.
5
+ //
6
+ // Throws away: nothing silently. A word that is no column and gets no offer comes back in `dropped` with its reason code (src/pagedropwords.js, the one table)
7
+ // and as a Not-checked line. Third outcomes: an unreadable answer twice (stop), a cut-off answer (unreadable), a failed call (stop, its reason).
8
+ // A rule the model gave no word for is left alone: a cells guardrail is checked by the cells close as it always was (this look adds checks, it removes none).
9
+ import { parseCsv } from './csv.js';
10
+ import { MAP_UNREADABLE } from './pagemap.js';
11
+ import { tieOf } from './pagerules.js';
12
+ import { lineRules, countPhrase, wordsSaidOn, wordForms } from './pagebits.js';
13
+ import { findColumn, columnQuestion } from './sheetfind.js';
14
+
15
+ /** how many data rows the prompt shows (the header is always shown): enough to see what a column holds, never the whole sheet */
16
+ export const SHEET_PROMPT_ROWS = 5;
17
+ /** the line every sheet prompt carries, so a test provider can tell a sheet call from a page call (the system words are the same) */
18
+ export const SHEET_MARK = 'THE SHEET OR DOCUMENT:';
19
+
20
+ /**
21
+ * The `~` rule an `agree` writes (signed, am8 item 1); a person's own words replace it.
22
+ * @param {string} word @param {string} column @returns {string}
23
+ */
24
+ export const columnRuleWords = (word, column) => `use the column '${column}' for '${word}'`;
25
+
26
+ /**
27
+ * What the AI is told for ONE sheet: the job, and the sheet's header and first rows. It names the job's word for each rule; it does not pick a column to offer.
28
+ * With `headings` (a .docx input, am8 item 3) the document's headings stand where a sheet's columns do and no data rows are shown.
29
+ * @param {{jobLines: {n: number, text: string, rule?: string, rules?: string[]}[], label: string, text: string, headings?: string[]}} o @returns {string}
30
+ */
31
+ export function sheetPrompt({ jobLines, label, text, headings }) {
32
+ const job = jobLines.map((l) => `LINE ${l.n}: ${l.text}${lineRules(l).map((r, i) => `\n~ rule ${i + 1}: ${r}`).join('')}`).join('\n');
33
+ if (headings !== undefined) {
34
+ return `THE JOB (each ~ rule applies to the line above it):\n${job}\n\n`
35
+ + `${SHEET_MARK} the input "${label}" is a document. Its headings:\n${headings.map((h) => `- ${h}`).join('\n') || '(none)'}\n\n`
36
+ + 'For each job line and each ~ rule that is about a part of the document, give the JOB\'S OWN WORD for the heading it means. If the document has a heading for it, copy that heading exactly. '
37
+ + 'If it has none, give the word the job uses. Say "other" for the kind. Leave out a rule that is not about a heading.\n\n'
38
+ + 'Return ONLY a JSON object, no prose, no code fence:\n'
39
+ + '{"facts":[{"from":"<line N | line N rule M>","word":"<the heading, or the job\'s own word>","kind":"other"}]}';
40
+ }
41
+ const { header, rows } = parseCsv(text);
42
+ const shown = rows.slice(0, SHEET_PROMPT_ROWS).map((r) => header.map((h) => r.byName[h] ?? '').join(' | '));
43
+ return `THE JOB (each ~ rule applies to the line above it):\n${job}\n\n`
44
+ + `${SHEET_MARK} the input "${label}" is a spreadsheet. Its columns, then its first rows:\n${header.join(' | ')}\n${shown.join('\n')}\n\n`
45
+ + 'For each job line and each ~ rule that is about a value in the sheet, give the JOB\'S OWN WORD for the column it means, exactly as the job writes it. '
46
+ + 'Never replace the job\'s word with a column name from the sheet, even when the sheet has a column that seems to mean the same: code matches the word to the sheet. Say whether the word means a column of numbers ("number") or anything else ("other"). Leave out a rule that is not about a column.\n\n'
47
+ + 'Return ONLY a JSON object, no prose, no code fence:\n'
48
+ + '{"facts":[{"from":"<line N | line N rule M>","word":"<the column name, or the job\'s own word>","kind":"number|other"}]}';
49
+ }
50
+
51
+ /**
52
+ * Read the AI's answer: ONE JSON object of the answer form, nothing else. No repair: text that is not JSON, or a fact without a `from`, a `word` or a kind of
53
+ * "number" / "other", is a malformed answer.
54
+ * @param {unknown} text @returns {{ok: true, words: {from: string, word: string, kind: 'number'|'other'}[]}|{ok: false}}
55
+ */
56
+ export function parseSheetAnswer(text) {
57
+ /** @type {any} */
58
+ let m;
59
+ try { m = JSON.parse(String(text ?? '').trim()); } catch { return { ok: false }; }
60
+ if (m === null || typeof m !== 'object' || Array.isArray(m) || !Array.isArray(m.facts)) return { ok: false };
61
+ /** @type {{from: string, word: string, kind: 'number'|'other'}[]} */
62
+ const words = [];
63
+ for (const f of m.facts) {
64
+ if (f === null || typeof f !== 'object' || Array.isArray(f)) return { ok: false };
65
+ if (typeof f.from !== 'string' || typeof f.word !== 'string' || f.word.trim() === '' || f.word.length > 100) return { ok: false };
66
+ if (f.kind !== 'number' && f.kind !== 'other') return { ok: false };
67
+ words.push({ from: f.from, word: f.word.trim(), kind: f.kind });
68
+ }
69
+ return { ok: true, words };
70
+ }
71
+
72
+ /**
73
+ * Keep the words that are real columns; for the rest, find the column to offer (or say why none is). Decided by code from the word, the rule and the sheet.
74
+ * @param {string} text the sheet's text @param {{from: string, word: string, kind: 'number'|'other'}[]} words
75
+ * @param {{n: number, text?: string, rule?: string, rules?: string[]}[]} jobLines @param {string} label the input's role
76
+ * @returns {{facts: {line: number, forRule?: number, name: string, shape: 'column', column: string, words: string[], source: string}[], asks: {line: number, rule: number|null, source: 'look', ask: 'reading', ruleText: string, question: string, reading: string, word: string, column: string}[], dropped: import('./pagerules.js').Dropped[]}}
77
+ */
78
+ export function applySheetWords(text, words, jobLines, label) {
79
+ /** @type {any[]} */
80
+ const facts = [];
81
+ /** @type {any[]} */
82
+ const asks = [];
83
+ /** @type {import('./pagerules.js').Dropped[]} */
84
+ const dropped = [];
85
+ const seen = new Set();
86
+ for (const w of words) {
87
+ const at = tieOf(w.from, jobLines);
88
+ const key = `${at.line}\u0000${at.rule ?? ''}\u0000${w.word.toLowerCase()}`;
89
+ if (seen.has(key)) continue;
90
+ seen.add(key);
91
+ const jl = jobLines.find((l) => l.n === at.line);
92
+ const rules = lineRules(jl);
93
+ const ruleText = at.rule === undefined ? String(jl?.text ?? '') : rules[at.rule - 1];
94
+ const fact = (/** @type {string} */ column) => ({ line: at.line, ...(at.rule === undefined ? {} : { forRule: at.rule }), name: column, shape: /** @type {const} */ ('column'), column, words: [column], source: label });
95
+ const rec = { line: at.line, ...(at.rule === undefined ? {} : { rule: at.rule }), fact: w.word, source: label };
96
+ const found = findColumn(text, w.word);
97
+ if (found.kind === 'header') {
98
+ // a real header is kept only when the word is the PERSON'S: in the line or its ~ rules. A header the model picked in the person's place is not a check the person
99
+ // asked for (live walk 2026-10-21: "Price over 500" kept as "Amount", nothing asked)
100
+ if (jl === undefined || !wordForms(w.word).some((f) => countPhrase(wordsSaidOn(jl), f) > 0)) dropped.push({ ...rec, reason: 'word-not-yours' });
101
+ else facts.push(fact(found.column));
102
+ continue;
103
+ }
104
+ if (w.kind !== 'number') { dropped.push({ ...rec, reason: 'no-column' }); continue; }
105
+ if (found.kind === 'tie') { dropped.push({ ...rec, reason: 'column-tie', other: found.columns.map((c) => `"${c}"`).join(', ') }); continue; }
106
+ if (found.kind === 'none') { dropped.push({ ...rec, reason: 'no-fit', other: String(found.rows) }); continue; }
107
+ // the person already named this column in ANOTHER rule of the line (an answer they gave, or their own words): the word is that column, asked no more
108
+ if (rules.some((r, i) => i + 1 !== at.rule && countPhrase(r, found.column) > 0)) { facts.push(fact(found.column)); continue; }
109
+ asks.push({
110
+ line: at.line, rule: at.rule ?? null, source: 'look', ask: 'reading', ruleText, question: columnQuestion(w.word, found, at.line), reading: columnRuleWords(w.word, found.column), word: w.word, column: found.column,
111
+ });
112
+ }
113
+ return { facts, asks, dropped };
114
+ }
115
+
116
+ /**
117
+ * am8 item 3: a .docx's words. A job word that is a heading is kept (the next steps' quotes are still checked word for word on the run's own copy); one that is not is
118
+ * Not checked with its reason, and NOTHING is asked. Same shape as {@link applySheetWords}, with no asks.
119
+ * @param {string[]} headings @param {{from: string, word: string, kind: 'number'|'other'}[]} words
120
+ * @param {{n: number, text?: string, rule?: string, rules?: string[]}[]} jobLines @param {string} label
121
+ * @returns {ReturnType<typeof applySheetWords>}
122
+ */
123
+ export function applyDocWords(headings, words, jobLines, label) {
124
+ const facts = /** @type {any[]} */ ([]);
125
+ const dropped = /** @type {import('./pagerules.js').Dropped[]} */ ([]);
126
+ const seen = new Set();
127
+ const norm = (/** @type {string} */ h) => h.trim().replace(/\s+/g, ' ').toLowerCase();
128
+ for (const w of words) {
129
+ const at = tieOf(w.from, jobLines);
130
+ const key = `${at.line}\u0000${at.rule ?? ''}\u0000${w.word.toLowerCase()}`;
131
+ if (seen.has(key)) continue;
132
+ seen.add(key);
133
+ const hit = headings.find((h) => norm(h) === norm(w.word)) ?? headings.find((h) => wordForms(w.word).includes(norm(h)));
134
+ if (hit !== undefined) facts.push({ line: at.line, ...(at.rule === undefined ? {} : { forRule: at.rule }), name: hit, shape: 'heading', column: hit, words: [hit], source: label });
135
+ else dropped.push(/** @type {any} */ ({ line: at.line, ...(at.rule === undefined ? {} : { rule: at.rule }), fact: w.word, source: label, reason: 'no-heading' }));
136
+ }
137
+ return { facts, asks: [], dropped };
138
+ }
139
+
140
+ /**
141
+ * Look at ONE sheet input: the call (once; once more if the answer is unreadable), then the rules.
142
+ * `callModel(content, attempt)` makes and meters ONE model round and returns `{text}`, `{text, cutOff: true}` or `{error}` (the same seam as `lookAtPage`).
143
+ * @param {{label: string, text: string, jobLines: {n: number, text: string, rule?: string, rules?: string[]}[], callModel: (content: string, attempt: number) => Promise<{text?: string, cutOff?: boolean, error?: string}>, headings?: string[]}} o
144
+ * @returns {Promise<({ok: true, attempts: number} & ReturnType<typeof applySheetWords>)|{ok: false, reason: string, attempts: number}>}
145
+ */
146
+ export async function lookAtSheet({ label, text, jobLines, callModel, headings }) {
147
+ const content = sheetPrompt({ jobLines, label, text, headings });
148
+ let attempts = 0;
149
+ for (;;) {
150
+ attempts += 1;
151
+ const r = await callModel(content, attempts);
152
+ if (r.error !== undefined) return { ok: false, reason: `the call about the sheet failed: ${r.error}`, attempts };
153
+ const parsed = r.cutOff === true ? { ok: false } : parseSheetAnswer(r.text);
154
+ if (parsed.ok) return { ok: true, attempts, ...(headings === undefined ? applySheetWords(text, /** @type {any} */ (parsed).words, jobLines, label) : applyDocWords(headings, /** @type {any} */ (parsed).words, jobLines, label)) };
155
+ if (attempts >= 2) return { ok: false, reason: MAP_UNREADABLE.replace('about the page', 'about the sheet'), attempts };
156
+ }
157
+ }
@@ -357,7 +357,7 @@ function parseArbiter(arbiterRawLines, lineNumbers, reds, asks) {
357
357
  }
358
358
 
359
359
  if (lower.startsWith('source ')) {
360
- const fileIdx = lower.indexOf('file:');
360
+ const fileIdx = lower.search(/(?:file|page):/);
361
361
  const afterFile = fileIdx === -1 ? '' : text.slice(fileIdx);
362
362
  if (SECOND_SOURCE_RE.test(afterFile)) {
363
363
  reds.push(`arbiter: line ${fileLine} field "sources" carries more than one source (";"/"," joined), one source per line: "${text}"`);
@@ -378,6 +378,16 @@ function parseArbiter(arbiterRawLines, lineNumbers, reds, asks) {
378
378
  const colon = rhs.indexOf(':');
379
379
  const kind = colon === -1 ? rhs : rhs.slice(0, colon);
380
380
  const path = colon === -1 ? '' : rhs.slice(colon + 1).trim();
381
+ if (kind.toLowerCase() === 'page') {
382
+ // M10 am3: a web page's address is signed with the job (`source <role> = page:<http(s) address>`);
383
+ if (!/^https?:\/\/[^\s/?#]+/i.test(path)) {
384
+ reds.push(`arbiter: line ${fileLine} field "sources" page address must be a full http:// or https:// address: "${text}"`);
385
+ continue;
386
+ }
387
+ sourceRolesSeen.add(role);
388
+ sources.push({ role, kind: 'page', path });
389
+ continue;
390
+ }
381
391
  if (kind.toLowerCase() !== 'file') {
382
392
  reds.push(`arbiter: line ${fileLine} field "sources" source kind "${kind}" is not available until M9`);
383
393
  continue;
package/src/thinking.js CHANGED
@@ -53,3 +53,42 @@ export function thinkingSay(status) {
53
53
  if (status === 'unknown') return 'thinking off (not confirmed)';
54
54
  return null;
55
55
  }
56
+
57
+ /**
58
+ * M4d am26 items 1-2: the words after a try line in the Audit, from that try's audit-row `thinking` {asked, status} (am25). bareagent confirmed it
59
+ * ('applied'): `thinking on` / `thinking off`. Any other status: `thinkingSay`'s words above, the same ones Chat uses. A row with no `thinking` (before am25,
60
+ * or no model call) has no words: nothing is guessed.
61
+ * M4d am27: a row with a `thinking` record but no status (the model sent no reply: an error, the time limit, a Stop before the first reply) reads
62
+ * `thinking <asked> (no reply)`, from what was ASKED; the words never say thinking happened. Nothing asked (asked null) has no words.
63
+ * @param {{asked?: unknown, status?: unknown}|null|undefined} thinking @returns {string|null}
64
+ */
65
+ export function thinkingTryWords(thinking) {
66
+ if (thinking === null || typeof thinking !== 'object') return null;
67
+ const status = typeof thinking.status === 'string' ? thinking.status : null;
68
+ if (status === null) return thinking.asked === 'on' || thinking.asked === 'off' ? `thinking ${thinking.asked} (no reply)` : null;
69
+ if (status === 'applied') return thinking.asked === 'on' || thinking.asked === 'off' ? `thinking ${thinking.asked}` : null;
70
+ return thinkingSay(status);
71
+ }
72
+
73
+ /**
74
+ * M4d am28 items 2-4 (replaces am26 item 3's words and the hidden row): the Job tab's Thinking value, from the run's own record
75
+ * (`boxOn` = the Chat "Thinking on" box as the run started). A run with no record (before am25) is `null` and reads `—`, never a guess from model.json.
76
+ * Words: bareloop's `thinkingJobText`.
77
+ * // borrowed-from: bareloop src/thinking.js@b79e7d9
78
+ * @param {boolean|null} boxOn
79
+ */
80
+ export function thinkingRuleWords(boxOn) {
81
+ if (boxOn === null) return '—';
82
+ return boxOn ? 'always on' : 'on retries';
83
+ }
84
+
85
+ /**
86
+ * M4d am25 item 1/2: the ONE owner of what thinking a step's model call asks for. Code decides, never the model.
87
+ * Box ticked (the job's Chat "Thinking on" box, kept with the job): every try 'on'. Box off: the 1st try 'off'; the 2nd and later tries 'on'.
88
+ * A step redone after a human Redo is numbered after the step's last try (the runner's `attemptOffset`, am30), so it is always a 2nd-or-later try and thinks 'on'.
89
+ * @param {{boxOn: boolean, attempt: number}} a the runner's 1-based attempt number for this step
90
+ * @returns {'on'|'off'}
91
+ */
92
+ export function stepThinkingMode({ boxOn, attempt }) {
93
+ return boxOn === true || (Number.isInteger(attempt) && attempt >= 2) ? 'on' : 'off';
94
+ }
@@ -0,0 +1,68 @@
1
+ // M4d am29 item 2: what one try saves about its checks. The runner runs the checks (done, happened, the close); this module only words them
2
+ // and records the output they judged. Numbers are identities, not run order: #1 the output exists, #2 the model said done, #3 and up the close's
3
+ // checks. A check that did not run (the done check halts before the others) is not listed. A hitl close has no mechanical check, so it adds none.
4
+ import { createHash } from 'node:crypto';
5
+ import { serializeArtifact } from './ask.js';
6
+
7
+ export const EVERY_STEP = 'every step';
8
+
9
+ /** The size words of a byte count: `412 B`, `7.9 KB`, `1.2 MB`. @param {number} n */
10
+ export function sizeWords(n) {
11
+ if (n < 1024) return `${n} B`;
12
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
13
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
14
+ }
15
+
16
+ /** Where a guardrail check comes from: the job line it belongs to (guardrail n belongs to job line n). @param {{fromLine?: unknown}} step */
17
+ export const lineSource = (step) => (Number.isInteger(step?.fromLine) ? `line ${step.fromLine} ~` : 'the step\'s guardrail');
18
+
19
+ /** #2, the model's own `done`. @param {{verdict: 'done'|'not-done'}} doneCheck @param {unknown} artifact */
20
+ export function doneRecord(doneCheck, artifact) {
21
+ const said = /** @type {any} */ (artifact)?.done;
22
+ return {
23
+ n: 2, text: 'the model said done: true', ok: doneCheck.verdict === 'done', result: doneCheck.verdict === 'done' ? null : (typeof said === 'boolean' ? 'it said done: false' : 'no true/false done'), source: EVERY_STEP,
24
+ };
25
+ }
26
+
27
+ /** #1, the happened check: the output exists and is not empty. @param {{verdict: string, red?: string}} happened @param {unknown} artifact */
28
+ export function happenedRecord(happened, artifact) {
29
+ const ok = happened.verdict !== 'red';
30
+ return {
31
+ n: 1, text: 'the output exists and isn\'t empty', ok, result: ok ? sizeWords(Buffer.byteLength(serializeArtifact(artifact), 'utf8')) : String(happened.red ?? '').replace(/^.*? produced /, ''), source: EVERY_STEP,
32
+ };
33
+ }
34
+
35
+ /** The output a try judged: the file it is saved as when the step closes, with the size and sha256 of those exact bytes. Never its content. @param {{emits?: string}} step @param {unknown} artifact */
36
+ export function outputRecord(step, artifact) {
37
+ const bytes = serializeArtifact(artifact);
38
+ return { file: `artifacts/${step?.emits ?? 'step'}.json`, bytes: Buffer.byteLength(bytes, 'utf8'), sha256: createHash('sha256').update(Buffer.from(bytes, 'utf8')).digest('hex') };
39
+ }
40
+
41
+ /**
42
+ * #3 and up: the close's own checks. A softgreen close carries each of its checks; a green close is one check over all its cited fields; a close that
43
+ * judged nothing (`unparseable`, `crash`) is one check that could not run, with that third outcome as its result.
44
+ * @param {any} step @param {any} artifact @param {{verdict: string, red?: string|null, checks?: Array<{text:string, ok:boolean, result:string|null}>}} closed
45
+ */
46
+ export function closeRecords(step, artifact, closed) {
47
+ const source = lineSource(step);
48
+ if (closed.verdict === 'unparseable' || closed.verdict === 'crash') {
49
+ return [{
50
+ n: 3, text: 'the close could run', ok: false, result: closed.verdict, source,
51
+ }];
52
+ }
53
+ if (step?.close?.class === 'green' && step?.close?.cited) {
54
+ const n = Array.isArray(artifact?.results) ? artifact.results.length : 0;
55
+ return [{
56
+ n: 3, text: 'every result is quoted from the saved copy and passes its rules', ok: closed.verdict === 'green', result: `${n} result${n === 1 ? '' : 's'}`, source,
57
+ }];
58
+ }
59
+ if (step?.close?.class === 'green') {
60
+ const n = Object.keys(artifact?.fields ?? {}).length;
61
+ return [{
62
+ n: 3, text: 'every cited field matches its source', ok: closed.verdict === 'green', result: `${n} field${n === 1 ? '' : 's'}`, source,
63
+ }];
64
+ }
65
+ return (closed.checks ?? []).map((c, i) => ({
66
+ n: 3 + i, text: c.text, ok: c.ok, result: c.result, source,
67
+ }));
68
+ }
package/src/types.js CHANGED
@@ -35,8 +35,8 @@
35
35
  /**
36
36
  * @typedef {object} SourceSlot
37
37
  * @property {string} role - `[a-z][a-z0-9_-]*`, unique across sources.
38
- * @property {'file'} kind - only `file:` sources are available before M9.
39
- * @property {string} path - everything after `file:` to end of line, trimmed.
38
+ * @property {'file'|'page'} kind - `file:` (a path) or `page:` (a web address, M10 am3); nothing else is available.
39
+ * @property {string} path - everything after `file:` / `page:` to end of line, trimmed.
40
40
  */
41
41
 
42
42
  /**
@@ -261,6 +261,8 @@
261
261
  * @property {'green'|'red'|'hitl'|'unparseable'|'crash'} verdict
262
262
  * @property {string|null} [red]
263
263
  * @property {string[]} [reds]
264
+ * @property {Array<{id:string, text:string, ok:boolean, result:string|null}>} [checks] a softgreen close: every check it ran (M4d am29 item 2)
265
+ * @property {{part: any, check: any, results?: unknown}} [cited] a cited green close (M10 piece 4): the fact part and the check's own answer, for the run's cited-check record
264
266
  */
265
267
 
266
268
  /**
@@ -0,0 +1,54 @@
1
+ /** A Stop's notes are not tries: the asked/not-honoured rows, and a `stopped` row that cut no try (no attempt number). @param {any} r */
2
+ export function isTryRow(r: any): boolean;
3
+ /** @param {string} runDir */
4
+ export function loadDiaries(runDir: string): {
5
+ present: boolean;
6
+ calls: any[];
7
+ tools: any[];
8
+ checks: any[];
9
+ };
10
+ /** What the human did, in the signed words, from the ask step's own audit row; `null` for a row that is not an answer. @param {any} r */
11
+ export function humanWords(r: any): string | null;
12
+ /**
13
+ * The fold of one step, or `null` for a step with nothing new to show (an old run, or a step that is neither a model step with records nor an ask).
14
+ * @param {{rows:any[], tryMarks:string[], closeClass:string|null}} group `deriveAuditGroups`' group for the step
15
+ * @param {ReturnType<typeof loadDiaries>} d
16
+ * @param {{about?: string|null}} [info] `about`: the file an ask is about
17
+ */
18
+ export function deriveFold(group: {
19
+ rows: any[];
20
+ tryMarks: string[];
21
+ closeClass: string | null;
22
+ }, d: ReturnType<typeof loadDiaries>, info?: {
23
+ about?: string | null;
24
+ }): {
25
+ who: string;
26
+ tally: string | null;
27
+ tries: any[];
28
+ rows: any[];
29
+ counts: {
30
+ rounds: number;
31
+ tools: number;
32
+ denied: number;
33
+ checksRun: any;
34
+ checksFailed: any;
35
+ lastTry: {
36
+ run: any;
37
+ passed: any;
38
+ } | null;
39
+ };
40
+ lastAnswer: {
41
+ words: string | null;
42
+ at: any;
43
+ } | null;
44
+ } | null;
45
+ /** The step card's one new line (item 6) minus the human step's time (the page formats that); `—` when there is no record. @param {ReturnType<typeof deriveFold>} fold */
46
+ export function cardLine(fold: ReturnType<typeof deriveFold>): string;
47
+ /**
48
+ * The Run summary's two new lines (item 5), from the same diary rows the folds read; `—` for a run with no diaries.
49
+ * @param {ReturnType<typeof loadDiaries>} d
50
+ */
51
+ export function summaryLines(d: ReturnType<typeof loadDiaries>): {
52
+ calls: string;
53
+ checks: string;
54
+ };
@@ -22,7 +22,8 @@ export function specHash({ proseText, declarationText, inputFactsText, readoutTe
22
22
  * checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
23
23
  * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
24
24
  * @param {string} planDir
25
- * @returns {{ questions: {k:number, line:number, question:string, answer:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
25
+ * A question the page look raised (M10 piece 3) also carries `source: 'look'`, `ask` ('reading' | 'cant-check'), `ruleNo`, `ruleText` and `proposal`; an answer file carries `at`.
26
+ * @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
26
27
  */
27
28
  export function readQuestions(planDir: string): {
28
29
  questions: {
@@ -30,6 +31,13 @@ export function readQuestions(planDir: string): {
30
31
  line: number;
31
32
  question: string;
32
33
  answer: string | null;
34
+ at?: string;
35
+ rule?: string | null;
36
+ source?: string;
37
+ ask?: string;
38
+ ruleNo?: number;
39
+ ruleText?: string;
40
+ proposal?: string | null;
33
41
  }[];
34
42
  open: {
35
43
  k: number;
@@ -85,8 +93,9 @@ export function draftKeyRefusal(slot: string, env: Record<string, string | undef
85
93
  * writer (appendSpendRow); an unpriced round books null, never 0.
86
94
  *
87
95
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
96
+ * `onResult({ ok })` (M4d am32): called once, after the spend is booked and just before the result files are written (the CLI gives its monthly hold back there).
88
97
  */
89
- export function draftToDir({ proseFile, dir, root, name, slot, model, draftThinking, keyNames, env, provider, rates, modelId, noQuestions, }: {
98
+ export function draftToDir({ proseFile, dir, root, name, slot, model, draftThinking, keyNames, env, provider, rates, modelId, noQuestions, onResult, fetchPage, leftRules, proseRead, }: {
90
99
  proseFile: any;
91
100
  dir: any;
92
101
  root: any;
@@ -100,6 +109,10 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, draftThink
100
109
  rates: any;
101
110
  modelId: any;
102
111
  noQuestions?: boolean | undefined;
112
+ onResult: any;
113
+ fetchPage: any;
114
+ leftRules: any;
115
+ proseRead: any;
103
116
  }): Promise<{
104
117
  ok: boolean;
105
118
  wrote: boolean;
@@ -191,6 +204,7 @@ export function signDraft({ dir, approve, signedBy, signedAt, env, keyNames, ses
191
204
  modelPick: {
192
205
  slot: string;
193
206
  model: string;
207
+ thinking?: true;
194
208
  } | null;
195
209
  } | {
196
210
  ok: boolean;
@@ -221,6 +235,10 @@ export const LEAK_MARKER_FILE: "scrub-leak.red";
221
235
  * and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
222
236
  export const QUESTIONS_FILE: "questions.json";
223
237
  export const NOT_CHECKED_FILE: "not-checked.json";
238
+ /** M10: the drafting copy of each web page input is kept in this folder of the draft folder (a run freezes its own, never this one). */
239
+ export const PAGES_DIR: "pages";
240
+ /** M10 item 3: what the page-word look kept and dropped, per page input (the map the AI named, the kept facts with their readings, every drop). Not signed. */
241
+ export const PAGE_LOOK_FILE: "page-look.json";
224
242
  export function ANSWER_FILE(k: any): string;
225
243
  export function SIGN_LINE(dir: any, hash: any): string;
226
244
  export const OPEN_QUESTION_SAY: "A question the plan raised is still open. Answer it in the panel (fwdloop panel), then sign the plan it drafts after your answers. Nothing was signed.";
package/types/books.d.ts CHANGED
@@ -17,6 +17,23 @@ export function appendPidRow(runDir: string, row: {
17
17
  * @returns {any[]}
18
18
  */
19
19
  export function readPidRows(runDir: string): any[];
20
+ /**
21
+ * Raw read-back of one JSONL book, one writer's own sibling reader (M4a
22
+ * piece 2, docs/wiki/the-module-ladder.md M4a scope item 2: "one reader per
23
+ * book"). Never throws on a missing file (`[]`) or a malformed line (that
24
+ * one line is skipped, never crashes the whole read) — the panel and any
25
+ * other reader need an honest best-effort array, not a hard failure over one
26
+ * bad byte someone else wrote.
27
+ *
28
+ * F48 round 3: goes through `readFileInside` (`src/flow.js`) — a book file
29
+ * that is itself a symlink, or that sits behind a symlinked ancestor
30
+ * directory, resolving outside `baseDir` reads as `[]`, same as a missing
31
+ * file, never as the outside target's content.
32
+ * @param {string} baseDir - the run dir (audit.jsonl) or flow dir (history.jsonl)
33
+ * @param {string} relPath - the book's own file name, relative to baseDir
34
+ * @returns {any[]}
35
+ */
36
+ export function readLines(baseDir: string, relPath: string): any[];
20
37
  /**
21
38
  * One row per attempt (also used for one row per ask and one row per send —
22
39
  * M2 scope item 9). `row` shape: `{ step, attempt, class, verdict, gap, usd,
@@ -21,5 +21,15 @@ export function notCheckedBlock(items: unknown): {
21
21
  label: string;
22
22
  items: any[];
23
23
  };
24
+ /**
25
+ * M10 am11: the Not checked block split for showing. The drafter's list and code's drop lines are one list on disk (and in the sign row, unchanged);
26
+ * the page shows code's notes about written forms it did not use apart, as "How the page was read" (`readNotes`). The signed facts decide an s1 note.
27
+ * @param {unknown} items @param {any} declaration the plan's declaration (its cited facts are the signed ones)
28
+ */
29
+ export function notCheckedView(items: unknown, declaration: any): {
30
+ label: string;
31
+ items: string[];
32
+ readNotes: string[];
33
+ };
24
34
  /** The label that always sits with the "Not checked" list (am41 item 3: the ONE place these words live; the Job tab and the Chat card read it off their payloads). */
25
35
  export const NOT_CHECKED_LABEL: "not checked (the AI's own reading)";
@@ -0,0 +1,21 @@
1
+ /**
2
+ * One job line's record from the check's own answer.
3
+ * @param {{n: number, part: any, results: unknown, check: Awaited<ReturnType<typeof import('./citedcheck.js').checkCited>>, confirmed?: string[]}} o
4
+ * `confirmed` = names of facts whose limit the person agreed to (the Result tab's "(you confirmed)")
5
+ * @returns {Record<string, any>}
6
+ */
7
+ export function citedLineOf({ n, part, results, check, confirmed, }: {
8
+ n: number;
9
+ part: any;
10
+ results: unknown;
11
+ check: Awaited<ReturnType<typeof import("./citedcheck.js").checkCited>>;
12
+ confirmed?: string[];
13
+ }): Record<string, any>;
14
+ /**
15
+ * Write one job line into the run's record: the line with the same `n` is replaced (a later try of the same step wins), the others stay, lines are kept in
16
+ * order. An unreadable existing record is started again (this function is its only writer). Atomic: a reader sees the old file or the new one.
17
+ * @param {string} runDir @param {Record<string, any>} line @returns {void}
18
+ */
19
+ export function writeCitedLine(runDir: string, line: Record<string, any>): void;
20
+ /** the record's name in the run's own folder; the Result tab's reader takes it from here */
21
+ export const CITED_CHECKS_FILE: "cited-checks.json";
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @param {string} runDir the run's own folder @param {string} role the signed input's role
3
+ * @param {{docx?: boolean}} [o] `docx`: also serve a .docx as its text. Off by default: a step that merely READS a role is never handed a .docx here (it has `readDocx`); only the
4
+ * cited CHECK asks for it, so a quote a step took from a .docx is proved on the same text `readDocx` gives.
5
+ * @returns {{ok: true, text: string, sha256: string, frozen: string}|{ok: false, red: string, code: 'no-manifest'|'not-an-input'|'not-text'|'unreadable'}}
6
+ */
7
+ export function readRunSource(runDir: string, role: string, { docx }?: {
8
+ docx?: boolean;
9
+ }): {
10
+ ok: true;
11
+ text: string;
12
+ sha256: string;
13
+ frozen: string;
14
+ } | {
15
+ ok: false;
16
+ red: string;
17
+ code: "no-manifest" | "not-an-input" | "not-text" | "unreadable";
18
+ };
@@ -0,0 +1,95 @@
1
+ /**
2
+ * A kept look fact as signed facts. The label that comes first becomes the anchor and the limit the look read (`reading`) becomes the number rule. A PLACE
3
+ * fact (the look gave it `phrases`, src/pageplace.js: R2, R2a, R2b) becomes one phrase fact per phrase, because every one of them must be in the quote
4
+ * (R2c); the old choice, the first kept word, is gone (in 2 of 3 saved F71 drafts that word was on no result line, FINDINGS F72). A plain phrase fact
5
+ * ("Nonstop") keeps its first word.
6
+ * @param {any} k a fact from `lookFactOf` (src/pagelook.js) @returns {Record<string, any>[]}
7
+ */
8
+ export function factsOfLook(k: any): Record<string, any>[];
9
+ /**
10
+ * What a fact part may carry, as reds the caller can show before anything is signed or run. Whether bareguard can SIGN the rubric it builds is asked of
11
+ * bareguard itself (`buildCitedSpec` + createRubric); this covers the fields the part owns.
12
+ * @param {any} part @returns {string[]}
13
+ */
14
+ export function factPartReds(part: any): string[];
15
+ /**
16
+ * bareguard's `decides` list for a fact part: one decide per fact, in the fact order (so `d<j>` is the fact's own index).
17
+ * @param {any} part @returns {Record<string, any>[]}
18
+ */
19
+ export function factDecides(part: any): Record<string, any>[];
20
+ /**
21
+ * The claims bareguard reads, built from the step's `results`. The claim TEXT is written here from the values the step gave (`name: value; name: value`),
22
+ * a phrase fact contributes its own signed words. A result that is not an object, or has no string quote, still becomes a claim (an empty one) so
23
+ * bareguard reds it by name rather than the result vanishing.
24
+ * @param {any} part @param {unknown} results @returns {{claim: string, quote: string, values?: Record<string, string>}[]}
25
+ */
26
+ export function factClaims(part: any, results: unknown): {
27
+ claim: string;
28
+ quote: string;
29
+ values?: Record<string, string>;
30
+ }[];
31
+ /**
32
+ * The rubric spec for one fact part: ONE `cited` check (the quote is in the frozen input, every value is in the quote and meets its rule), then the count
33
+ * as a min and a max on the harness-set count of results.
34
+ * @param {any} part @param {string} sha256 the frozen text's sha256 @returns {Record<string, any>}
35
+ */
36
+ export function buildCitedSpec(part: any, sha256: string): Record<string, any>;
37
+ /**
38
+ * One fact as a plain row, written by code from the signed fields: `fact · price — money in US dollars, under 150 US dollars, after "From", quoted from "flights"`.
39
+ * @param {any} f @param {string} source @returns {string}
40
+ */
41
+ export function factSentence(f: any, source: string): string;
42
+ /** @param {any} part @returns {string|null} the "N results" row of a fact part */
43
+ export function countSentence(part: any): string | null;
44
+ /**
45
+ * One fact as the STEP is told it: what to write for it and where in the quote it sits, in plain words, from the signed fields. A phrase fact has no value to
46
+ * write - the quote has to say it. (bareloop's factBrief.)
47
+ * @param {any} f @returns {string}
48
+ */
49
+ export function factBrief(f: any): string;
50
+ /**
51
+ * How a step that quotes a saved page is told to answer: the form of its answer and the facts each result must hold (typed fields in, plain words out).
52
+ * The step is never told a verdict or a way around the check; it is told what to copy and what to write.
53
+ * @param {any} part @returns {{answer: string, eachResultHolds: string[], howMany: string|null}}
54
+ */
55
+ export function citedBrief(part: any): {
56
+ answer: string;
57
+ eachResultHolds: string[];
58
+ howMany: string | null;
59
+ };
60
+ /**
61
+ * Every plan-card row a fact part carries: its facts, then its count (bareloop's factRows).
62
+ * @param {any} part @returns {string[]}
63
+ */
64
+ export function factRows(part: any): string[];
65
+ /**
66
+ * One bareguard `cited` item (`#<result>:d<j>:<reason>[:<detail>]`, or `#<result>:<reason>`) as a sentence. The names and numbers are bareguard's
67
+ * measurements and the signed facts, never inferred here.
68
+ * @param {string} item @param {any} part @returns {string}
69
+ */
70
+ export function plainFactItem(item: string, part: any): string;
71
+ /**
72
+ * Check one step's results against a fact part and the frozen text they must be quoted from.
73
+ * `text` is the run's OWN frozen copy of the source (the caller reads it from the run's folder; this function never reads a file). Its sha256 is taken
74
+ * here and signed into the rubric, so bareguard compares the text it is handed with the text the rubric was built for.
75
+ * @param {{part: any, text: string, results: unknown}} o
76
+ * @returns {Promise<{verdict: 'green'|'red'|'stopped', gapLines: string[], fault: string|null, sha256: string, claims: any[], evidence: any[]}>}
77
+ */
78
+ export function checkCited({ part, text, results }: {
79
+ part: any;
80
+ text: string;
81
+ results: unknown;
82
+ }): Promise<{
83
+ verdict: "green" | "red" | "stopped";
84
+ gapLines: string[];
85
+ fault: string | null;
86
+ sha256: string;
87
+ claims: any[];
88
+ evidence: any[];
89
+ }>;
90
+ /** the shapes a fact may have (bareguard's value kinds, plus `phrase` = a presence decide) */
91
+ export const FACT_SHAPES: readonly string[];
92
+ /** bareguard signs at most this many decides on one `cited` check */
93
+ export const MAX_FACTS: 10;
94
+ export const CITED_ID: "facts";
95
+ export function sha256Text(t: string): string;