fwdloop 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/bin/fwdloop +85 -34
  2. package/package.json +4 -3
  3. package/src/audit-fold.js +5 -1
  4. package/src/authoring.js +32 -6
  5. package/src/checked.js +18 -1
  6. package/src/cited-record.js +138 -0
  7. package/src/cited-source.js +49 -0
  8. package/src/citedcheck.js +306 -0
  9. package/src/citedwords.js +197 -0
  10. package/src/closers.js +56 -7
  11. package/src/ctx-tools.js +2 -14
  12. package/src/declaration.js +85 -5
  13. package/src/diary.js +2 -2
  14. package/src/docx.js +16 -2
  15. package/src/draft-steps.js +1 -1
  16. package/src/drafter.js +292 -25
  17. package/src/flow.js +33 -7
  18. package/src/flowmodel.js +21 -0
  19. package/src/input-facts.js +20 -3
  20. package/src/model-step.js +30 -5
  21. package/src/pageask.js +136 -0
  22. package/src/pagebits.js +107 -0
  23. package/src/pagedropwords.js +171 -0
  24. package/src/pagedry.js +120 -0
  25. package/src/pagefetch.js +164 -0
  26. package/src/pagelook.js +155 -0
  27. package/src/pagemap.js +55 -0
  28. package/src/pageplace.js +103 -0
  29. package/src/pagerules.js +318 -0
  30. package/src/panel/author.js +41 -20
  31. package/src/panel/authorcard.js +11 -1
  32. package/src/panel/authorflows.js +21 -15
  33. package/src/panel/authorstart.js +2 -4
  34. package/src/panel/authortrigger.js +14 -4
  35. package/src/panel/data.js +83 -2
  36. package/src/panel/index.html +279 -12
  37. package/src/panel/result.js +295 -0
  38. package/src/panel/server.js +27 -3
  39. package/src/primitives.js +2 -3
  40. package/src/provider.js +5 -2
  41. package/src/redact.js +17 -0
  42. package/src/runner.js +83 -12
  43. package/src/schedule.js +3 -3
  44. package/src/setup.js +16 -1
  45. package/src/sheetfind.js +50 -0
  46. package/src/sheetlook.js +157 -0
  47. package/src/signed-text.js +11 -1
  48. package/src/thinking.js +1 -1
  49. package/src/try-checks.js +6 -0
  50. package/src/types.js +3 -2
  51. package/types/authoring.d.ts +19 -2
  52. package/types/checked.d.ts +10 -0
  53. package/types/cited-record.d.ts +21 -0
  54. package/types/cited-source.d.ts +18 -0
  55. package/types/citedcheck.d.ts +95 -0
  56. package/types/citedwords.d.ts +97 -0
  57. package/types/closers.d.ts +55 -3
  58. package/types/ctx-tools.d.ts +0 -1
  59. package/types/declaration.d.ts +15 -1
  60. package/types/docx.d.ts +14 -0
  61. package/types/drafter.d.ts +244 -2
  62. package/types/flow.d.ts +21 -0
  63. package/types/flowmodel.d.ts +15 -0
  64. package/types/input-facts.d.ts +12 -2
  65. package/types/model-step.d.ts +35 -3
  66. package/types/pageask.d.ts +75 -0
  67. package/types/pagebits.d.ts +32 -0
  68. package/types/pagedropwords.d.ts +40 -0
  69. package/types/pagedry.d.ts +38 -0
  70. package/types/pagefetch.d.ts +86 -0
  71. package/types/pagelook.d.ts +75 -0
  72. package/types/pagemap.d.ts +31 -0
  73. package/types/pageplace.d.ts +22 -0
  74. package/types/pagerules.d.ts +86 -0
  75. package/types/panel/authorcard.d.ts +2 -0
  76. package/types/panel/authorflows.d.ts +2 -0
  77. package/types/panel/data.d.ts +26 -0
  78. package/types/panel/result.d.ts +156 -0
  79. package/types/provider.d.ts +3 -1
  80. package/types/redact.d.ts +1 -0
  81. package/types/runner.d.ts +156 -7
  82. package/types/schedule.d.ts +0 -11
  83. package/types/setup.d.ts +13 -0
  84. package/types/sheetfind.d.ts +46 -0
  85. package/types/sheetlook.d.ts +120 -0
  86. package/types/thinking.d.ts +1 -1
  87. package/types/types.d.ts +11 -3
package/src/schedule.js CHANGED
@@ -28,10 +28,10 @@ import { triggerHash } from './trigger-line.js';
28
28
  * }} Schedule
29
29
  */
30
30
 
31
- export const SCHEDULE_FILE = 'schedule.json';
32
- export const LEDGER_FILE = 'schedule-ledger.jsonl';
31
+ const SCHEDULE_FILE = 'schedule.json';
32
+ const LEDGER_FILE = 'schedule-ledger.jsonl';
33
33
  /** The words of the am16 row (also for a Cancel): signed text, M9 am16. @param {string} name */
34
- export const droppedSay = (name) => `${name} was waiting when the schedule changed, so it will not run. Drop it in again to run it.`;
34
+ const droppedSay = (name) => `${name} was waiting when the schedule changed, so it will not run. Drop it in again to run it.`;
35
35
 
36
36
  /** @param {string} flowDir */
37
37
  export const scheduleFileOf = (flowDir) => join(flowDir, SCHEDULE_FILE);
package/src/setup.js CHANGED
@@ -11,7 +11,7 @@ import { lstatSync, writeFileSync } from 'node:fs';
11
11
  import { triesOf } from './draft-steps.js';
12
12
  import { join } from 'node:path';
13
13
 
14
- import { scrub } from './authoring.js';
14
+ import { readQuestions, scrub } from './authoring.js';
15
15
  import { notCheckedBlock } from './checked.js';
16
16
  import { readDraftSpend } from './draftspend.js';
17
17
  import { readFileInside, readdirInside } from './flow.js';
@@ -58,6 +58,19 @@ function planRow(sessionDir, rel, kind, n) {
58
58
  };
59
59
  }
60
60
 
61
+ /**
62
+ * M10 am2 item 4: one row per question the page look raised and the person answered, in the plan folder that raised it (the draft log's human rows, read
63
+ * from the answer files). The question, the answer, the line and the time, plus the proposal and the rule the answer added as their own fields (never cut
64
+ * out of the question text). A question nobody answered leaves no row.
65
+ * @param {string} sessionDir @param {string} rel
66
+ */
67
+ function humanRows(sessionDir, rel) {
68
+ return readQuestions(join(sessionDir, rel)).questions.filter((q) => q.source === 'look' && q.answer !== null).map((q) => ({
69
+ kind: 'human', n: q.k, at: q.at ?? null, source: 'look', ask: q.ask, question: q.question, answer: q.answer, line: q.line,
70
+ ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: q.proposal ?? null, rule: q.rule ?? null,
71
+ }));
72
+ }
73
+
61
74
  /**
62
75
  * The rows of a draft's record, oldest first. `sessionDir` is the panel's draft folder (card.json, draft/, card-<n>.json, draft-<n>/); a CLI
63
76
  * draft has none, so its record is its one plan folder (`planDir`, read as `draft`) plus the sign.
@@ -73,6 +86,7 @@ export function buildSetupRows({
73
86
  // amendment 14 item 6: a draft begun by Start over says so (written once by the panel's start); its row reads `start over`
74
87
  const so = readJson(sessionDir, 'started-over-from.json');
75
88
  rows.push(planRow(sessionDir, 'draft', typeof so?.startedOverFrom === 'string' ? 'startover' : 'draft', 0));
89
+ rows.push(...humanRows(sessionDir, 'draft'));
76
90
  // amendment 14 item 6: each revise is the card as submitted, then its plan row (model, cost, verdict, hash); there is no note row
77
91
  const ns = readdirInside(sessionDir, '.').map((f) => CARD_RE.exec(f)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
78
92
  for (const n of ns) {
@@ -80,6 +94,7 @@ export function buildSetupRows({
80
94
  if (card) rows.push({ kind: 'card', n, at: mtimeIso(sessionDir, `card-${n}.json`), card });
81
95
  // M4e amendment 24 item 4: a plan drafted again after the human's answers is booked as `redraft`, not `revise` (it uses none of the 2 revises)
82
96
  rows.push(planRow(sessionDir, `draft-${n}`, readJson(sessionDir, `redraft-${n}.json`) ? 'redraft' : 'revise', n));
97
+ rows.push(...humanRows(sessionDir, `draft-${n}`));
83
98
  }
84
99
  } else {
85
100
  const r = planRow(planDir, '.', 'draft', 0);
@@ -0,0 +1,50 @@
1
+ // M10 piece 5 (docs/wiki/the-module-ladder.md "M10", item 7): when a job's word is not a column of the sheet, CODE finds the column that passes the same test
2
+ // the page words pass - a value of the right kind in the rows - and builds the ask. The model names a word and nothing else; it never names a column to offer and
3
+ // never decides an ask (test/m10-sheetfind.test.js, test/m10-sheetask.test.js).
4
+ // The finder is fwdloop's own (F71 Test 3, C1-C4, $0): bareloop reads "label then value on the same line", and a header sits on line 1, so the discipline
5
+ // transfers, not the code (docs/product/fwd-borrow-from-bareloop-rubric-2026-10-18.md section 3).
6
+ // A column FITS when a plain number fills at least FIT_RATIO of the rows (F71 (b)). A plain number is the whole cell: optional sign, digits, thousands commas,
7
+ // optional decimals. One fitting column with the most rows is the one ask. Two or more fitting columns with equal rows offer nothing (F71 C2, hamr 2026-10-19).
8
+ // Throws away: every column but the winner, the cells' values, and everything but the header and the count of number cells.
9
+ import { parseCsv } from './csv.js';
10
+ import { wordForms } from './pagebits.js';
11
+
12
+ /** a column fits when a plain number fills at least this share of the rows (F71 (b)) */
13
+ export const FIT_RATIO = 0.9;
14
+ const PLAIN_NUMBER = /^[-+]?\d[\d,]*(\.\d+)?$/;
15
+
16
+ /** @param {string} h @returns {string} a header as it is compared: trimmed, white space made one space, lower case */
17
+ const norm = (h) => String(h ?? '').trim().replace(/\s+/g, ' ').toLowerCase();
18
+
19
+ /**
20
+ * @typedef {{kind: 'header', column: string}} FoundHeader the word IS a column (nothing to ask)
21
+ * @typedef {{kind: 'ask', column: string, numbers: number, rows: number}} FoundAsk exactly one column fits: the one ask
22
+ * @typedef {{kind: 'tie', columns: string[], rows: number}} FoundTie two or more columns fit equally: no ask
23
+ * @typedef {{kind: 'none', rows: number}} FoundNone no column fits: no ask
24
+ */
25
+
26
+ /**
27
+ * Where a job word lands in a sheet's columns.
28
+ * @param {string} csvText the sheet's text @param {string} word the job's word
29
+ * @returns {FoundHeader|FoundAsk|FoundTie|FoundNone}
30
+ */
31
+ export function findColumn(csvText, word) {
32
+ const { header, rows } = parseCsv(csvText);
33
+ const hit = header.find((h) => norm(h) === norm(word) && norm(h) !== '') ?? header.find((h) => norm(h) !== '' && wordForms(word).includes(norm(h)));
34
+ if (hit !== undefined) return { kind: 'header', column: hit };
35
+ const n = rows.length;
36
+ const cols = header.map((h) => ({ h, n: rows.filter((r) => PLAIN_NUMBER.test(String(r.byName[h] ?? '').trim())).length }));
37
+ const fit = cols.filter((c) => n > 0 && c.n / n >= FIT_RATIO);
38
+ if (fit.length === 0) return { kind: 'none', rows: n };
39
+ const best = Math.max(...fit.map((c) => c.n));
40
+ const top = fit.filter((c) => c.n === best);
41
+ if (top.length > 1) return { kind: 'tie', columns: top.map((c) => c.h), rows: n };
42
+ return { kind: 'ask', column: top[0].h, numbers: top[0].n, rows: n };
43
+ }
44
+
45
+ /**
46
+ * The question, as signed (item 7's example, then am8 item 1's answer words):
47
+ * `no column 'Price'; 'Amount' has numbers in 40 of 40 rows. Use it? Answer "agree", or type your own words (your answer is added as a new ~ rule on line N).`
48
+ * @param {string} word @param {FoundAsk} found @param {number} line @returns {string}
49
+ */
50
+ export const columnQuestion = (word, found, line) => `no column '${word}'; '${found.column}' has numbers in ${found.numbers} of ${found.rows} rows. Use it? Answer "agree", or type your own words (your answer is added as a new ~ rule on line ${line}).`;
@@ -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
@@ -85,7 +85,7 @@ export function thinkingRuleWords(boxOn) {
85
85
  /**
86
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
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 from its redo count (the runner's `attemptOffset`), so it is always a 2nd-or-later try and thinks '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
89
  * @param {{boxOn: boolean, attempt: number}} a the runner's 1-based attempt number for this step
90
90
  * @returns {'on'|'off'}
91
91
  */
package/src/try-checks.js CHANGED
@@ -50,6 +50,12 @@ export function closeRecords(step, artifact, closed) {
50
50
  n: 3, text: 'the close could run', ok: false, result: closed.verdict, source,
51
51
  }];
52
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
+ }
53
59
  if (step?.close?.class === 'green') {
54
60
  const n = Object.keys(artifact?.fields ?? {}).length;
55
61
  return [{
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
  /**
@@ -262,6 +262,7 @@
262
262
  * @property {string|null} [red]
263
263
  * @property {string[]} [reds]
264
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
265
266
  */
266
267
 
267
268
  /**
@@ -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;
@@ -222,6 +235,10 @@ export const LEAK_MARKER_FILE: "scrub-leak.red";
222
235
  * and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
223
236
  export const QUESTIONS_FILE: "questions.json";
224
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";
225
242
  export function ANSWER_FILE(k: any): string;
226
243
  export function SIGN_LINE(dir: any, hash: any): string;
227
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.";
@@ -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;