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.
- package/README.md +2 -0
- package/bin/fwdloop +85 -34
- package/package.json +4 -3
- package/src/audit-fold.js +181 -0
- package/src/authoring.js +33 -7
- package/src/books.js +1 -1
- package/src/checked.js +18 -1
- package/src/cited-record.js +138 -0
- package/src/cited-source.js +49 -0
- package/src/citedcheck.js +306 -0
- package/src/citedwords.js +197 -0
- package/src/closers.js +105 -9
- package/src/ctx-tools.js +2 -14
- package/src/declaration.js +85 -5
- package/src/diary.js +49 -0
- package/src/docx.js +16 -2
- package/src/draft-steps.js +1 -1
- package/src/drafter.js +292 -25
- package/src/flow.js +33 -7
- package/src/flowmodel.js +63 -5
- package/src/input-facts.js +20 -3
- package/src/model-step.js +132 -9
- package/src/pageask.js +136 -0
- package/src/pagebits.js +107 -0
- package/src/pagedropwords.js +171 -0
- package/src/pagedry.js +120 -0
- package/src/pagefetch.js +164 -0
- package/src/pagelook.js +155 -0
- package/src/pagemap.js +55 -0
- package/src/pageplace.js +103 -0
- package/src/pagerules.js +318 -0
- package/src/panel/author.js +41 -20
- package/src/panel/authorcard.js +11 -1
- package/src/panel/authorflows.js +21 -15
- package/src/panel/authorstart.js +2 -4
- package/src/panel/authortrigger.js +14 -4
- package/src/panel/data.js +130 -10
- package/src/panel/index.html +499 -41
- package/src/panel/result.js +295 -0
- package/src/panel/server.js +27 -3
- package/src/primitives.js +43 -2
- package/src/provider.js +5 -2
- package/src/redact.js +17 -0
- package/src/runner.js +128 -21
- package/src/schedule.js +3 -3
- package/src/setup.js +16 -1
- package/src/sheetfind.js +50 -0
- package/src/sheetlook.js +157 -0
- package/src/signed-text.js +11 -1
- package/src/thinking.js +39 -0
- package/src/try-checks.js +68 -0
- package/src/types.js +4 -2
- package/types/audit-fold.d.ts +54 -0
- package/types/authoring.d.ts +20 -2
- package/types/books.d.ts +17 -0
- package/types/checked.d.ts +10 -0
- package/types/cited-record.d.ts +21 -0
- package/types/cited-source.d.ts +18 -0
- package/types/citedcheck.d.ts +95 -0
- package/types/citedwords.d.ts +97 -0
- package/types/closers.d.ts +55 -3
- package/types/declaration.d.ts +15 -1
- package/types/diary.d.ts +57 -0
- package/types/docx.d.ts +14 -0
- package/types/drafter.d.ts +244 -2
- package/types/flow.d.ts +21 -0
- package/types/flowmodel.d.ts +40 -3
- package/types/input-facts.d.ts +12 -2
- package/types/model-step.d.ts +38 -3
- package/types/pageask.d.ts +75 -0
- package/types/pagebits.d.ts +32 -0
- package/types/pagedropwords.d.ts +40 -0
- package/types/pagedry.d.ts +38 -0
- package/types/pagefetch.d.ts +86 -0
- package/types/pagelook.d.ts +75 -0
- package/types/pagemap.d.ts +31 -0
- package/types/pageplace.d.ts +22 -0
- package/types/pagerules.d.ts +86 -0
- package/types/panel/authorcard.d.ts +2 -0
- package/types/panel/authorflows.d.ts +2 -0
- package/types/panel/data.d.ts +26 -0
- package/types/panel/result.d.ts +156 -0
- package/types/provider.d.ts +3 -1
- package/types/redact.d.ts +1 -0
- package/types/runner.d.ts +156 -7
- package/types/schedule.d.ts +0 -11
- package/types/setup.d.ts +13 -0
- package/types/sheetfind.d.ts +46 -0
- package/types/sheetlook.d.ts +120 -0
- package/types/thinking.d.ts +31 -0
- package/types/try-checks.d.ts +55 -0
- package/types/types.d.ts +20 -3
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/pagedropwords.js@b56f177
|
|
2
|
+
// IDEA A CORE (docs/product/ITEM33-BUILD.md "Addendum 2026-10-18 — Idea A core: build spec", sections 4.6 and 7): NO SILENT DROP. The ONE place
|
|
3
|
+
// that writes the sentence for a word, fact or rule that a page rule dropped. The plan card, the Job tab, the confirm card and the drafter's
|
|
4
|
+
// block all read these words; no other file writes a drop reason (a test greps for it). Plain words, written by CODE from the drop's reason
|
|
5
|
+
// code, never a raw code and never model-written. `<label>` is the page's own word.
|
|
6
|
+
|
|
7
|
+
/** @typedef {import('./pagerules.js').Dropped} Dropped */
|
|
8
|
+
|
|
9
|
+
/** reason code -> the plain sentence (`d.word` = the page's word, `d.fact` = the fact's name, `d.other` = what it was compared to) */
|
|
10
|
+
const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
|
|
11
|
+
'not-on-page': (d) => `"${d.word}" is not written on the page.`,
|
|
12
|
+
'no-value': (d) => `The page never shows a number right after or right before "${d.word}".`,
|
|
13
|
+
'n2': (d) => `"${d.word}" is written more than once inside one line of the page, so one result cannot show it once.`,
|
|
14
|
+
'r1': (d) => `"${d.word}" does not show the same values as "${d.other}", so it was not used as a second way to read it.`,
|
|
15
|
+
'sign-twice': (d) => `"${d.word}" was listed twice, as a unit and as a currency; it is used once, as the currency.`,
|
|
16
|
+
'r1l': (d) => d.word === d.other
|
|
17
|
+
? `"${d.word}" was listed twice, as a unit and as a currency; it is used once, as the first way to write the price.`
|
|
18
|
+
: `"${d.word}" does not show the same amounts as "${d.other}", so it was not used as a second way to write the price.`,
|
|
19
|
+
's1-name': () => 'One result is one record; ask for N results instead.',
|
|
20
|
+
's1': (d) => `"${d.fact}" would read the same value as "${d.other}". The page gives no second label for it.`,
|
|
21
|
+
'no-label': (d) => `No word on this page reads "${d.fact}" safely.`,
|
|
22
|
+
'limit-currency': (d) => `Only the first 3 currencies are used; "${d.word}" was left out.`,
|
|
23
|
+
'limit-unit': (d) => `Only the first 10 units are used; "${d.word}" was left out.`,
|
|
24
|
+
'unit-too-long': (d) => `"${d.word}" is longer than 100 characters, so it was not used.`,
|
|
25
|
+
'reads-no-result': () => "the price rule could not read a price in the page's results, so it is not checked.",
|
|
26
|
+
// borrowed-from: bareloop src/pagedropwords.js@c550dc8 (the phrase dry read's sentence)
|
|
27
|
+
'phrase-no-result': (d) => `"${d.other}" is on the page but in none of its results, so it is not checked.`,
|
|
28
|
+
'person-left': () => 'You chose to leave it Not checked.',
|
|
29
|
+
// M10 piece 5 (item 7, am8 item 1): the signed Not-checked reasons for a job word that is not a column. `fact` = the job's word.
|
|
30
|
+
'no-column': (d) => `there is no column '${d.fact}'`,
|
|
31
|
+
'no-fit': (d) => `no column fits '${d.fact}'`,
|
|
32
|
+
'column-tie': (d) => `two columns fit '${d.fact}' equally`,
|
|
33
|
+
// M10 piece 5 (live walk 2026-10-21): the sheet look named a word that is none of the person's own; it is not used (words not signed)
|
|
34
|
+
'word-not-yours': (d) => `the sheet look named '${d.fact}', which is not a word in your job, so it was not used.`,
|
|
35
|
+
'column-declined': () => "you didn't take the offered column",
|
|
36
|
+
// M10 piece 5 (am8 item 3): a job word that is not a .docx heading is Not checked, nothing is asked (the analogue of a missing column; words not signed)
|
|
37
|
+
'no-heading': (d) => `there is no heading '${d.fact}'`,
|
|
38
|
+
'bad-shape': (d) => `The AI named a kind of value for "${d.fact}" that a check cannot read.`,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* M10 am2 item 3: the plan card row for a `~` rule the person chose to leave Not checked ("drop it"), word for word:
|
|
43
|
+
* `not checked · "<rule>" — You chose to leave it Not checked.` (the rule as the person wrote it; the sentence is the one table's).
|
|
44
|
+
* @param {string} rule @returns {string}
|
|
45
|
+
*/
|
|
46
|
+
export const leftRuleLine = (rule) => `not checked · "${rule}" — ${WORDS['person-left'](/** @type {Dropped} */ ({}))}`;
|
|
47
|
+
|
|
48
|
+
/** @param {Dropped} d @returns {string} the plain sentence for one drop */
|
|
49
|
+
export function dropSentence(d) {
|
|
50
|
+
const f = WORDS[d.reason];
|
|
51
|
+
return f ? f(d) : `"${d.word ?? d.fact}" was left out.`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* One row per fact that lost something: the sentences (one per dropped word, then the fact's own), and whether the whole fact went.
|
|
56
|
+
* @param {Dropped[]|undefined|null} dropped
|
|
57
|
+
* @returns {{line: number, rule?: number, fact: string, full: boolean, sentences: string[]}[]}
|
|
58
|
+
*/
|
|
59
|
+
export function dropRows(dropped) {
|
|
60
|
+
/** @type {Map<string, {line: number, rule?: number, fact: string, full: boolean, sentences: string[]}>} */
|
|
61
|
+
const rows = new Map();
|
|
62
|
+
for (const d of Array.isArray(dropped) ? dropped : []) {
|
|
63
|
+
const key = `${d.line}\u0000${d.rule ?? ''}\u0000${d.fact}`;
|
|
64
|
+
let row = rows.get(key);
|
|
65
|
+
if (!row) { row = { line: d.line, ...(d.rule === undefined ? {} : { rule: d.rule }), fact: d.fact, full: false, sentences: [] }; rows.set(key, row); }
|
|
66
|
+
if (d.word === undefined) row.full = true;
|
|
67
|
+
const sentence = dropSentence(d);
|
|
68
|
+
if (!row.sentences.includes(sentence)) row.sentences.push(sentence);
|
|
69
|
+
}
|
|
70
|
+
// a fact's own sentence ("No word ... reads it safely") reads last, after the words that were lost
|
|
71
|
+
return [...rows.values()].map((r) => ({ ...r, sentences: [...r.sentences.filter((s) => !/^No word on this page reads /.test(s)), ...r.sentences.filter((s) => /^No word on this page reads /.test(s))] }));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A row as one Not-checked line, in the person's own words: `line N: "<the ~ rule as written, or the fact's name>" — <sentences>`.
|
|
76
|
+
* @param {{line: number, rule?: number, fact: string, sentences: string[]}} row @param {any[]|null|undefined} jobLines @param {(l: any) => string[]} rulesOf
|
|
77
|
+
* @returns {string}
|
|
78
|
+
*/
|
|
79
|
+
export function dropLine(row, jobLines, rulesOf) {
|
|
80
|
+
const jl = (jobLines ?? []).find((/** @type {any} */ l) => l && l.n === row.line);
|
|
81
|
+
const rule = row.rule === undefined || !jl ? undefined : rulesOf(jl)[row.rule - 1];
|
|
82
|
+
return `line ${row.line}: "${rule ?? row.fact}" — ${row.sentences.join(' ')}`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// HOW THE PAGE WAS READ (M10 am11). // borrowed-from: bareloop src/pagedropwords.js@2d22c0f (isReadNote, splitReadNotes) and @e818c3f (the s1 note with a signed other fact)
|
|
86
|
+
// A drop of ONE WORD whose fact is still checked is a NOTE about the form code did not use, not something left unchecked; a drop of a whole fact
|
|
87
|
+
// stays under Not checked. Classified from the line's own words, so it holds for a signed record already on disk. bareloop builds a regular expression from the
|
|
88
|
+
// WORDS table; src/ builds none dynamically (test/signed-text.test.js), so the same sentence shapes are matched as literal pieces here: each template is
|
|
89
|
+
// the WORDS sentence written once with placeholders, cut at the placeholders; a placeholder reads up to the next `"` (at least one character).
|
|
90
|
+
const WORD_REASONS = ['not-on-page', 'no-value', 'n2', 'r1', 'sign-twice', 'r1l', 'limit-currency', 'limit-unit', 'unit-too-long'];
|
|
91
|
+
const MARK = '\u0001';
|
|
92
|
+
/** @param {string} reason @param {boolean} [same] r1l has two sentences: a word listed twice (word = other) and a second way to write the price @returns {{lits: string[], gaps: string[]}} */
|
|
93
|
+
function templateOf(reason, same = false) {
|
|
94
|
+
const s = WORDS[reason](/** @type {any} */ ({ word: `${MARK}w${MARK}`, other: same ? `${MARK}w${MARK}` : `${MARK}o${MARK}`, fact: `${MARK}f${MARK}`, reason, line: 0 }));
|
|
95
|
+
const parts = s.split(MARK); // lit, name, lit, name, ... : the odd pieces are the placeholders' names
|
|
96
|
+
return { lits: parts.filter((_, i) => i % 2 === 0), gaps: parts.filter((_, i) => i % 2 === 1) };
|
|
97
|
+
}
|
|
98
|
+
const WORD_TEMPLATES = [...WORD_REASONS.flatMap((r) => (r === 'r1l' ? [templateOf(r, true), templateOf(r, false)] : [templateOf(r)]))];
|
|
99
|
+
const S1_TEMPLATE = templateOf('s1');
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Read ONE sentence of `template` at `at` in `text`. Returns where it ended and what each placeholder read, or null.
|
|
103
|
+
* @param {string} text @param {number} at @param {{lits: string[], gaps: string[]}} template @returns {{end: number, got: Record<string, string>}|null}
|
|
104
|
+
*/
|
|
105
|
+
function readSentence(text, at, template) {
|
|
106
|
+
/** @type {Record<string, string>} */
|
|
107
|
+
const got = {};
|
|
108
|
+
let pos = at;
|
|
109
|
+
for (let i = 0; i < template.lits.length; i += 1) {
|
|
110
|
+
if (!text.startsWith(template.lits[i], pos)) return null;
|
|
111
|
+
pos += template.lits[i].length;
|
|
112
|
+
if (i < template.gaps.length) {
|
|
113
|
+
const stop = text.indexOf('"', pos);
|
|
114
|
+
if (stop <= pos) return null;
|
|
115
|
+
got[template.gaps[i]] = text.slice(pos, stop);
|
|
116
|
+
pos = stop;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return { end: pos, got };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* `text` as a run of sentences, each one a word note (or an s1 note whose OTHER fact is signed): true when every sentence is one, and there is at least one.
|
|
124
|
+
* @param {string} text @param {Set<string>} signed @returns {boolean}
|
|
125
|
+
*/
|
|
126
|
+
function allReadNotes(text, signed) {
|
|
127
|
+
let pos = 0;
|
|
128
|
+
let found = 0;
|
|
129
|
+
while (pos < text.length) {
|
|
130
|
+
let next = null;
|
|
131
|
+
for (const t of WORD_TEMPLATES) { next = readSentence(text, pos, t); if (next) break; }
|
|
132
|
+
if (!next) {
|
|
133
|
+
const s1 = readSentence(text, pos, S1_TEMPLATE);
|
|
134
|
+
if (s1 && signed.has(s1.got.o)) next = s1; // borrowed-from: bareloop e818c3f - an S1 copy of a SIGNED fact is a note; the other fact unsigned stays Not checked
|
|
135
|
+
}
|
|
136
|
+
if (!next) return false;
|
|
137
|
+
found += 1;
|
|
138
|
+
pos = next.end;
|
|
139
|
+
if (pos < text.length) { if (text[pos] !== ' ') return false; pos += 1; }
|
|
140
|
+
}
|
|
141
|
+
return found > 0;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* @param {string} text one Not-checked line @param {string[]|null|undefined} [signed] the names of the facts the plan signs (none given: an s1 sentence stays Not checked)
|
|
146
|
+
* @returns {boolean} true when the line only says which written forms of a still-checked fact were not used
|
|
147
|
+
*/
|
|
148
|
+
export function isReadNote(text, signed) {
|
|
149
|
+
const s = String(text);
|
|
150
|
+
if (!s.startsWith('line ')) return false;
|
|
151
|
+
let i = 5;
|
|
152
|
+
while (i < s.length && s[i] >= '0' && s[i] <= '9') i += 1;
|
|
153
|
+
if (i === 5 || !s.startsWith(': "', i)) return false;
|
|
154
|
+
const close = s.indexOf('"', i + 3); // the rule or fact name carries no quote
|
|
155
|
+
if (close < 0 || !s.startsWith(' \u2014 ', close + 1)) return false;
|
|
156
|
+
return allReadNotes(s.slice(close + 4), new Set(Array.isArray(signed) ? signed : []));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** @param {string[]|null|undefined} items @param {string[]|null|undefined} [signed] names of the signed facts (see isReadNote)
|
|
160
|
+
* @returns {{notChecked: string[], readNotes: string[]}} the lines split: what is left unchecked, and how the page was read */
|
|
161
|
+
export function splitReadNotes(items, signed) {
|
|
162
|
+
const all = Array.isArray(items) ? items : [];
|
|
163
|
+
return { notChecked: all.filter((t) => !isReadNote(t, signed)), readNotes: all.filter((t) => isReadNote(t, signed)) };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The names of the facts a signed declaration checks (every cited fact of every step). Pure. @param {any} declaration @returns {string[]} */
|
|
167
|
+
export function signedFactNames(declaration) {
|
|
168
|
+
const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
|
|
169
|
+
return steps.flatMap((/** @type {any} */ st) => (Array.isArray(st?.close?.cited?.facts) ? st.close.cited.facts : [])
|
|
170
|
+
.map((/** @type {any} */ f) => f?.name).filter((/** @type {any} */ n) => typeof n === 'string'));
|
|
171
|
+
}
|
package/src/pagedry.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/pagedry.js@c550dc8 (c61d227 + dryReadPhrases) (adapted: the REAL checker here is fwdloop's run-time `checkCited`, src/citedcheck.js, fed the fact exactly as it would be signed, `factsOfLook`).
|
|
2
|
+
// "CAN IT READ" (F241). After the page rules, a $0 dry read asks of each kept money fact whether the run-time checker can read a price on the page's own
|
|
3
|
+
// result lines. For every result line it checks an HONEST claim (quote = that line, value = the line's amount) with `checkCited`, the one reader the run
|
|
4
|
+
// itself uses - no copy of its logic here. A fact that reads no result line is dropped as `reads-no-result` and shows under Not checked.
|
|
5
|
+
// Throws away: nothing silently (the drop is returned). Third outcomes: a checker that stops (a fault) counts as "did not read" for that line.
|
|
6
|
+
// No limits, no counts, no pass bar: only "can it read". No I/O, no clock, no model. The caller is src/pagelook.js `lookAtPage`.
|
|
7
|
+
|
|
8
|
+
import { checkCited, factsOfLook } from './citedcheck.js';
|
|
9
|
+
import { linesOf } from './pagerules.js';
|
|
10
|
+
|
|
11
|
+
/** @typedef {import('./pagerules.js').KeptFact} KeptFact @typedef {import('./pagerules.js').Dropped} Dropped */
|
|
12
|
+
|
|
13
|
+
/** a number as the page writes it, thousands commas allowed: \d[\d,]*(?:\.\d+)? (written out as literals - this repo bans dynamic patterns in src/) */
|
|
14
|
+
const AFTER_LABEL = /^\s*(?:[$€£]\s*)?(\d[\d,]*(?:\.\d+)?)/;
|
|
15
|
+
const BEFORE_UNIT = /(\d[\d,]*(?:\.\d+)?)\s*$/;
|
|
16
|
+
/** the name every dry-read claim is made under (the checker only needs one name; the fact's own is not read) */
|
|
17
|
+
const CLAIM = 'price';
|
|
18
|
+
const SOURCE = 'page';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The result lines of a kept money fact: with a label, every page line where a kept label is followed by a number (one sign between allowed);
|
|
22
|
+
* with no label (U1 moved it to a unit, e.g. "€533 total"), every line where a number is followed by a kept unit.
|
|
23
|
+
* @param {string} text @param {KeptFact} k @returns {{quote: string, value: string}[]}
|
|
24
|
+
*/
|
|
25
|
+
export function moneyResultLines(text, k) {
|
|
26
|
+
const raw = text.split('\n');
|
|
27
|
+
const squashed = linesOf(text);
|
|
28
|
+
/** @type {{quote: string, value: string}[]} */
|
|
29
|
+
const out = [];
|
|
30
|
+
squashed.forEach((ln, i) => {
|
|
31
|
+
/** @type {string|undefined} */
|
|
32
|
+
let amount;
|
|
33
|
+
if (k.words.length) {
|
|
34
|
+
for (const w of k.words) {
|
|
35
|
+
for (let at = ln.indexOf(w); at !== -1 && amount === undefined; at = ln.indexOf(w, at + w.length)) amount = AFTER_LABEL.exec(ln.slice(at + w.length))?.[1];
|
|
36
|
+
if (amount !== undefined) break;
|
|
37
|
+
}
|
|
38
|
+
} else {
|
|
39
|
+
for (const u of k.unit ?? []) {
|
|
40
|
+
for (let at = ln.indexOf(u); at !== -1 && amount === undefined; at = ln.indexOf(u, at + u.length)) amount = BEFORE_UNIT.exec(ln.slice(0, at))?.[1];
|
|
41
|
+
if (amount !== undefined) break;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (amount !== undefined) out.push({ quote: raw[i].trim(), value: amount.replace(/,/g, '') });
|
|
45
|
+
});
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The fact as the drafter would sign it (same function: `factsOfLook`), under the one claim name, with no number rule: only "can it read".
|
|
51
|
+
* @param {KeptFact} k @returns {Record<string, any>}
|
|
52
|
+
*/
|
|
53
|
+
const signedOf = (k) => factsOfLook({ name: CLAIM, shape: k.shape, words: k.words, ...(k.unit ? { unit: k.unit } : {}), ...(k.currency ? { currency: k.currency } : {}) })[0];
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Dry-read every kept money fact; drop (as `reads-no-result`) the ones whose forms read no result line. Other facts pass through untouched.
|
|
57
|
+
* @param {string} text the frozen page text @param {KeptFact[]} facts what the page rules kept
|
|
58
|
+
* @returns {Promise<{facts: KeptFact[], dropped: Dropped[], reads: Record<string, number>, results: Record<string, number>}>}
|
|
59
|
+
* `reads` / `results` = result lines the checker read / lines found, per fact name (for tests and reports; no verdict derives from the numbers)
|
|
60
|
+
*/
|
|
61
|
+
export async function dryReadMoney(text, facts) {
|
|
62
|
+
/** @type {KeptFact[]} */
|
|
63
|
+
const kept = [];
|
|
64
|
+
/** @type {Dropped[]} */
|
|
65
|
+
const dropped = [];
|
|
66
|
+
/** @type {Record<string, number>} */
|
|
67
|
+
const reads = {};
|
|
68
|
+
/** @type {Record<string, number>} */
|
|
69
|
+
const results = {};
|
|
70
|
+
for (const k of facts) {
|
|
71
|
+
if (k.shape !== 'money') { kept.push(k); continue; }
|
|
72
|
+
const part = { source: SOURCE, facts: [signedOf(k)] };
|
|
73
|
+
const lines = moneyResultLines(text, k);
|
|
74
|
+
let n = 0;
|
|
75
|
+
for (const r of lines) {
|
|
76
|
+
const g = await checkCited({ part, text, results: [{ quote: r.quote, values: { [CLAIM]: r.value } }] });
|
|
77
|
+
if (g.verdict === 'green') n += 1;
|
|
78
|
+
}
|
|
79
|
+
reads[k.name] = n;
|
|
80
|
+
results[k.name] = lines.length;
|
|
81
|
+
if (n > 0) { kept.push(k); continue; }
|
|
82
|
+
dropped.push({ line: k.line, ...(k.forRule === undefined ? {} : { rule: k.forRule }), fact: k.name, reason: 'reads-no-result' });
|
|
83
|
+
}
|
|
84
|
+
return { facts: kept, dropped, reads, results };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The same "can it read" for PHRASE facts (bareloop c550dc8; our failure: m10-walk-flights-3, "Rome" was on the page only in "Track prices from Madrid to
|
|
89
|
+
* Rome" switches, in none of the 18 result lines, so no result could ever say it). A kept phrase fact is read against the page's RESULT LINES = the lines
|
|
90
|
+
* the job's kept money facts read (`moneyResultLines`), each checked as an honest claim by the run's own `checkCited` (quote = that line; a phrase has no
|
|
91
|
+
* value to write). A phrase that reads no result line is dropped whole as `phrase-no-result` and shows under Not checked. With no kept money fact the
|
|
92
|
+
* result lines are unknown, so phrase facts pass through untouched (nothing is guessed about what a result is).
|
|
93
|
+
* Throws away: nothing silently (the drop is returned). Third outcomes: a checker that stops counts as "did not read" for that line.
|
|
94
|
+
* @param {string} text the frozen page text @param {KeptFact[]} facts what the money dry read kept
|
|
95
|
+
* @returns {Promise<{facts: KeptFact[], dropped: Dropped[], reads: Record<string, number>}>} `reads` = result lines that said the phrase, per fact name
|
|
96
|
+
*/
|
|
97
|
+
export async function dryReadPhrases(text, facts) {
|
|
98
|
+
/** @type {Set<string>} */
|
|
99
|
+
const quotes = new Set();
|
|
100
|
+
for (const k of facts) if (k.shape === 'money') for (const r of moneyResultLines(text, k)) quotes.add(r.quote);
|
|
101
|
+
/** @type {KeptFact[]} */
|
|
102
|
+
const kept = [];
|
|
103
|
+
/** @type {Dropped[]} */
|
|
104
|
+
const dropped = [];
|
|
105
|
+
/** @type {Record<string, number>} */
|
|
106
|
+
const reads = {};
|
|
107
|
+
for (const k of facts) {
|
|
108
|
+
if (k.shape !== 'phrase' || quotes.size === 0 || !k.words.length) { kept.push(k); continue; }
|
|
109
|
+
const part = { source: SOURCE, facts: factsOfLook({ name: CLAIM, shape: 'phrase', words: [k.words[0]] }) };
|
|
110
|
+
let n = 0;
|
|
111
|
+
for (const quote of quotes) {
|
|
112
|
+
const g = await checkCited({ part, text, results: [{ quote, values: {} }] });
|
|
113
|
+
if (g.verdict === 'green') n += 1;
|
|
114
|
+
}
|
|
115
|
+
reads[k.name] = n;
|
|
116
|
+
if (n > 0) { kept.push(k); continue; }
|
|
117
|
+
dropped.push({ line: k.line, ...(k.forRule === undefined ? {} : { rule: k.forRule }), fact: k.name, other: k.words[0], reason: 'phrase-no-result' });
|
|
118
|
+
}
|
|
119
|
+
return { facts: kept, dropped, reads };
|
|
120
|
+
}
|
package/src/pagefetch.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/pagefetch.js@56dc096 (adapted: secret check uses src/redact.js)
|
|
2
|
+
// URL inputs (PART 1c, docs/product/ITEM33-BUILD.md "4. URL inputs" + live fix L1, PRD item 33 RF21/RF22): an Inputs line may be a web
|
|
3
|
+
// address the person pastes (a results page). bareloop fetches it with barebrowse, READ ONLY, headless and incognito, as published:
|
|
4
|
+
//
|
|
5
|
+
// page = await connect({ incognito: true, blockPrivateNetwork: true })
|
|
6
|
+
// await page.goto(url); await page.waitForNetworkIdle({ idle, timeout }); await page.snapshot({ mode: 'act' })
|
|
7
|
+
//
|
|
8
|
+
// L1: one-shot `browse()` snapshots at load, before the page's own scripts fill a results list (the same URL gave 77,951 / 8,801 / 719
|
|
9
|
+
// chars). So we wait for the network to go quiet (bounded) before the snapshot. Generic: no site selector. The snapshot mode is the one
|
|
10
|
+
// proven in step 0 ('read' and 'full' returned almost nothing from a results page). The text that comes back is the input. An empty
|
|
11
|
+
// fetch is a plain-words stop, never a silent empty input. Nothing here touches a model.
|
|
12
|
+
import { readFileSync } from 'node:fs';
|
|
13
|
+
import { dirname, join } from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { redactSecrets } from './redact.js';
|
|
16
|
+
|
|
17
|
+
/** the session options (incognito: no auth ever enters; blockPrivateNetwork: SSRF guard); ONE frozen object so a test can pin them */
|
|
18
|
+
export const CONNECT_OPTIONS = Object.freeze({ incognito: true, blockPrivateNetwork: true });
|
|
19
|
+
/** the snapshot options step 0 proved */
|
|
20
|
+
export const SNAPSHOT_OPTIONS = Object.freeze({ mode: 'act' });
|
|
21
|
+
/** the page's network must be quiet this long (ms) before we read it: long enough to span the gap between a page's first load and the
|
|
22
|
+
* script requests that fill the results, short enough not to stretch a plain page */
|
|
23
|
+
export const NETWORK_IDLE_MS = 1500;
|
|
24
|
+
/** the most we wait for the network to go quiet (ms); a page that never settles (polling, streaming) is read as it stands after this */
|
|
25
|
+
export const NETWORK_IDLE_TIMEOUT_MS = 20_000;
|
|
26
|
+
/** the most we wait for the page to load at all (ms) */
|
|
27
|
+
export const GOTO_TIMEOUT_MS = 30_000;
|
|
28
|
+
/** a page that comes back with fewer characters than this (after trimming) is treated as "nothing came back" */
|
|
29
|
+
export const MIN_PAGE_CHARS = 200;
|
|
30
|
+
/** the page text left after the site's own header, menus and footer are taken out must hold at least this many characters, or the page is
|
|
31
|
+
* "only site chrome" (L2: a 719-character fetch of a site's header and sign-in passed the 200-character floor) */
|
|
32
|
+
export const MIN_CONTENT_CHARS = 100;
|
|
33
|
+
/** the page reader's landmark roles for a site's own chrome (the ARIA names of header, menu and footer); everything under one is not the page's content */
|
|
34
|
+
const CHROME_ROLES = new Set(['banner', 'navigation', 'contentinfo']);
|
|
35
|
+
/** our own deadline around one whole fetch (a hung browser leaves no trace; this is the only thing that fires on the absence of an answer) */
|
|
36
|
+
export const PAGE_FETCH_TIMEOUT_MS = 90_000;
|
|
37
|
+
|
|
38
|
+
/** @param {unknown} v @returns {boolean} an http(s) address (the one spelling of "this Inputs value is a web address") */
|
|
39
|
+
export function isWebUrl(v) {
|
|
40
|
+
return typeof v === 'string' && /^https?:\/\//i.test(v.trim());
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** M10 am3: the web pages a signed job names, role -> address (`source <role> = page:<address>`). The ONE reader of which roles are pages and what their signed address is.
|
|
44
|
+
* @param {{sources?: Array<{role: string, kind?: string, path: string}>}} arbiter @returns {Record<string, string>} */
|
|
45
|
+
export function pageAddressesOf(arbiter) {
|
|
46
|
+
return Object.fromEntries((arbiter?.sources ?? []).filter((s) => s.kind === 'page').map((s) => [s.role, s.path]));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** M10 am3: why a run may not name another address for a page input (the signed address is the job's; a different one is a changed job). @param {string} role @param {string} signed */
|
|
50
|
+
export function pageAddressRefusal(role, signed) {
|
|
51
|
+
return `the input "${role}" is a web page signed as ${signed}; a run cannot name a different address (a changed address is a changed job, a new workflow). Nothing started.`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* How much of a fetched page is the page's own content: the snapshot's header lines (url, size note, hint) and every part of the tree
|
|
56
|
+
* under a banner / navigation / contentinfo landmark are taken out, the page reader's bracketed tags are removed, and what is left is
|
|
57
|
+
* counted. Generic - no site names, only the ARIA landmark roles. Text that is not a snapshot tree (a plain file) has no landmark, so it
|
|
58
|
+
* counts whole.
|
|
59
|
+
* @param {string} text @returns {number}
|
|
60
|
+
*/
|
|
61
|
+
export function pageContentChars(text) {
|
|
62
|
+
const lines = String(text ?? '').split('\n');
|
|
63
|
+
let skipIndent = -1;
|
|
64
|
+
let n = 0;
|
|
65
|
+
let head = true;
|
|
66
|
+
for (const raw of lines) {
|
|
67
|
+
if (head && (/^url: /.test(raw) || /^[\d,]+ chars → /.test(raw) || /^hint: /.test(raw))) continue;
|
|
68
|
+
head = false;
|
|
69
|
+
const m = /^(\s*)- ([A-Za-z_]+)\b/.exec(raw);
|
|
70
|
+
const indent = m ? m[1].length : raw.length - raw.trimStart().length;
|
|
71
|
+
if (skipIndent >= 0) {
|
|
72
|
+
if (raw.trim() === '' || indent > skipIndent) continue;
|
|
73
|
+
skipIndent = -1;
|
|
74
|
+
}
|
|
75
|
+
if (m && CHROME_ROLES.has(m[2])) { skipIndent = indent; continue; }
|
|
76
|
+
n += raw.replace(/\[[A-Za-z]+=[^\]\s]*\]/g, ' ').replace(/^\s*-\s*/, '').replace(/\s+/g, ' ').trim().length;
|
|
77
|
+
}
|
|
78
|
+
return n;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @typedef {{goto: (url: string, timeout?: number) => Promise<void>, waitForNetworkIdle: (o?: {idle?: number, timeout?: number}) => Promise<void>,
|
|
83
|
+
* snapshot: (o?: {mode?: string}) => Promise<string>, close: () => Promise<void>}} FetchPage the part of barebrowse's page handle the fetch uses
|
|
84
|
+
*/
|
|
85
|
+
|
|
86
|
+
/** the oldest barebrowse that honours CONNECT_OPTIONS (incognito, blockPrivateNetwork); an older one would drop both guards without a word */
|
|
87
|
+
export const MIN_BAREBROWSE = [0, 21, 0];
|
|
88
|
+
|
|
89
|
+
/** @param {string} v @returns {boolean} true when `v` (x.y.z) is at least MIN_BAREBROWSE */
|
|
90
|
+
export function barebrowseNewEnough(v) {
|
|
91
|
+
const p = String(v).split('.').map((n) => parseInt(n, 10));
|
|
92
|
+
for (let i = 0; i < 3; i += 1) {
|
|
93
|
+
const a = Number.isFinite(p[i]) ? p[i] : 0;
|
|
94
|
+
if (a !== MIN_BAREBROWSE[i]) return a > MIN_BAREBROWSE[i];
|
|
95
|
+
}
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** barebrowse is an optional peer: loaded here, on first use, and refused by name when missing or too old. */
|
|
100
|
+
async function loadConnect() {
|
|
101
|
+
try {
|
|
102
|
+
const mod = /** @type {any} */ (await import('barebrowse'));
|
|
103
|
+
const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.resolve('barebrowse'))), '..', 'package.json'), 'utf8'));
|
|
104
|
+
if (!barebrowseNewEnough(pkg.version)) return { ok: /** @type {const} */ (false), error: `the page reader (barebrowse ${pkg.version}) is too old: a web page needs 0.21.0 or newer, which keeps the browser private and off the local network` };
|
|
105
|
+
return { ok: /** @type {const} */ (true), connect: /** @type {(opts: Record<string, any>) => Promise<FetchPage>} */ (mod.connect) };
|
|
106
|
+
} catch (e) { return { ok: /** @type {const} */ (false), error: `the page reader (barebrowse) could not be loaded: ${/** @type {Error} */ (e).message}` }; }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Fetch one page's text. `connect` is injected (a test never reaches the network); the default is barebrowse's own `connect`.
|
|
111
|
+
* @param {string} url
|
|
112
|
+
* @param {{connect?: (opts: Record<string, any>) => Promise<FetchPage>, timeoutMs?: number, idleMs?: number, idleTimeoutMs?: number, closeWaitMs?: number}} [o]
|
|
113
|
+
* @returns {Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>} `error` is plain words, without a spend line
|
|
114
|
+
*/
|
|
115
|
+
export async function fetchPageText(url, { connect, timeoutMs = PAGE_FETCH_TIMEOUT_MS, idleMs = NETWORK_IDLE_MS, idleTimeoutMs = NETWORK_IDLE_TIMEOUT_MS, closeWaitMs = 3000 } = {}) {
|
|
116
|
+
let u;
|
|
117
|
+
try { u = new URL(url.trim()); } catch { return { ok: false, error: `${url} is not a web address fwdloop can read` }; }
|
|
118
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') return { ok: false, error: `${url} is not an http or https address` };
|
|
119
|
+
if (redactSecrets(u.href) !== u.href) return { ok: false, error: 'the web address carries a known secret shape - secrets never enter a job' };
|
|
120
|
+
if (u.username !== '' || u.password !== '') return { ok: false, error: 'a web address with a user name or password in it is refused - fwdloop reads a page with no credentials at all' };
|
|
121
|
+
/** @type {(opts: Record<string, any>) => Promise<FetchPage>} */
|
|
122
|
+
let open;
|
|
123
|
+
if (connect) open = connect;
|
|
124
|
+
else {
|
|
125
|
+
const loaded = await loadConnect();
|
|
126
|
+
if (!loaded.ok) return loaded;
|
|
127
|
+
open = loaded.connect;
|
|
128
|
+
}
|
|
129
|
+
/** @type {NodeJS.Timeout|undefined} */
|
|
130
|
+
let timer;
|
|
131
|
+
/** @type {Promise<FetchPage>|undefined} */
|
|
132
|
+
let opening;
|
|
133
|
+
try {
|
|
134
|
+
opening = open({ ...CONNECT_OPTIONS });
|
|
135
|
+
const page = opening;
|
|
136
|
+
const text = await Promise.race([
|
|
137
|
+
(async () => {
|
|
138
|
+
const p = await page;
|
|
139
|
+
await p.goto(u.href, GOTO_TIMEOUT_MS);
|
|
140
|
+
// bounded: a page that never goes quiet (polling, streaming) is read as it stands (bareloop); the size and chrome floors below then decide
|
|
141
|
+
try { await p.waitForNetworkIdle({ idle: idleMs, timeout: idleTimeoutMs }); } catch { /* read what is there */ }
|
|
142
|
+
return p.snapshot({ ...SNAPSHOT_OPTIONS });
|
|
143
|
+
})(),
|
|
144
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`no answer inside ${Math.round(timeoutMs / 1000)} seconds`)), timeoutMs); }),
|
|
145
|
+
]);
|
|
146
|
+
if (typeof text !== 'string') return { ok: false, error: `${u.href} did not come back as text` };
|
|
147
|
+
if (/\[BOT CHALLENGE DETECTED\]/.test(text)) return { ok: false, error: `${u.href} asked for a human check (a bot challenge), so the page could not be read` };
|
|
148
|
+
const size = text.trim().length;
|
|
149
|
+
if (size < MIN_PAGE_CHARS) return { ok: false, error: `${u.href} came back with ${size === 0 ? 'no text' : `only ${size} characters of text`} (less than ${MIN_PAGE_CHARS}) - the page did not load, or holds nothing to read` };
|
|
150
|
+
if (pageContentChars(text) < MIN_CONTENT_CHARS) return { ok: false, error: `${u.href} came back with only the site's own header and menus - the page did not load its content, so there is nothing to read` };
|
|
151
|
+
return { ok: true, text, url: u.href };
|
|
152
|
+
} catch (e) {
|
|
153
|
+
return { ok: false, error: `${u.href} could not be read: ${/** @type {Error} */ (e)?.message ?? String(e)}` };
|
|
154
|
+
} finally {
|
|
155
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
156
|
+
// always close the browser, also when the deadline fired while it was still starting or loading
|
|
157
|
+
if (opening) {
|
|
158
|
+
/** @type {NodeJS.Timeout|undefined} */
|
|
159
|
+
let w;
|
|
160
|
+
await Promise.race([opening.then((p) => p.close()).catch(() => {}), new Promise((r) => { w = setTimeout(r, closeWaitMs); })]);
|
|
161
|
+
if (w !== undefined) clearTimeout(w);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
package/src/pagelook.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// M10 item 3 ("the source's own words"): the page-word look for ONE page input. One AI call names the page's own words for each job rule
|
|
2
|
+
// (bareloop's prompt, src/pagemap.js); code keeps only words the saved page proves (bareloop's rules, src/pagerules.js) plus one rule of ours:
|
|
3
|
+
// a label that reads no value is dropped. The AI never grades; every drop is written once, from the one table (src/pagedropwords.js).
|
|
4
|
+
//
|
|
5
|
+
// Throws away: nothing silently. A word, fact or rule that a rule removes comes back in `dropped` with its reason code and as a Not-checked line.
|
|
6
|
+
// Third outcomes: an unreadable answer twice (stop, MAP_UNREADABLE), a cut-off answer (unreadable), a failed call (stop, its reason).
|
|
7
|
+
// The model call itself is the caller's (`callModel`): the drafter meters every round through it.
|
|
8
|
+
|
|
9
|
+
import { mapPrompt, parseMapAnswer, MAP_UNREADABLE } from './pagemap.js';
|
|
10
|
+
import { applyPageRules } from './pagerules.js';
|
|
11
|
+
import { dryReadMoney, dryReadPhrases } from './pagedry.js';
|
|
12
|
+
import { dropRows, dropLine } from './pagedropwords.js';
|
|
13
|
+
import { lineRules, squash } from './pagebits.js';
|
|
14
|
+
import { placePhrases } from './pageplace.js';
|
|
15
|
+
import { ruleWords } from './pageask.js';
|
|
16
|
+
|
|
17
|
+
/** Our rule (signed item 3): a kept money / number / time label must have a value of its kind written right AFTER it on some page line. */
|
|
18
|
+
const READ = {
|
|
19
|
+
money: /^\s*[$€£]?\s*\d[\d,]*(?:\.\d+)?/,
|
|
20
|
+
number: /^\s*\d[\d,]*(?:\.\d+)?/,
|
|
21
|
+
time: /^\s*\d{1,2}:\d{2}[\s\u202f\u00a0]?[AaPp][Mm]/, // h:mm AM/PM, as bareloop's own time reader (src/pagerules.js READ)
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** @param {string[]} lines squashed page lines @param {string} label @param {'money'|'number'|'time'} shape @returns {boolean} */
|
|
25
|
+
function readsValue(lines, label, shape) {
|
|
26
|
+
const p = squash(label).trim();
|
|
27
|
+
if (p === '') return false;
|
|
28
|
+
for (const ln of lines) for (let i = ln.indexOf(p); i !== -1; i = ln.indexOf(p, i + p.length)) if (READ[shape].test(ln.slice(i + p.length))) return true;
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @param {unknown} v @returns {unknown} the list with a repeated entry once (first kept); anything else as it came */
|
|
33
|
+
const once = (v) => (Array.isArray(v) ? [...new Set(v)] : v);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A unit, currency or label listed twice in one list is one entry: removed before the rules run, so no rule can compare a word with itself.
|
|
37
|
+
* @param {any} mapping @returns {any}
|
|
38
|
+
*/
|
|
39
|
+
export function dedupeMap(mapping) {
|
|
40
|
+
if (!mapping || !Array.isArray(mapping.facts)) return mapping;
|
|
41
|
+
return { ...mapping, facts: mapping.facts.map((f) => (f && typeof f === 'object' ? { ...f, ...(f.words === undefined ? {} : { words: once(f.words) }), ...(f.unit === undefined ? {} : { unit: once(f.unit) }), ...(f.currency === undefined ? {} : { currency: once(f.currency) }) } : f)) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The rules over one saved page: bareloop's (found-on-page, N2, R1, U1/R1L, S1, ...), then ours (no-value).
|
|
46
|
+
* @param {string} text the frozen page text @param {import('./pagerules.js').PageMap} mapping @param {{n: number, text?: string, rule?: string, rules?: string[]}[]} jobLines
|
|
47
|
+
* @returns {{facts: import('./pagerules.js').KeptFact[], dropped: import('./pagerules.js').Dropped[]}}
|
|
48
|
+
*/
|
|
49
|
+
export function applyPageWords(text, mapping, jobLines) {
|
|
50
|
+
const r = applyPageRules(text, dedupeMap(mapping), jobLines);
|
|
51
|
+
const lines = text.split('\n').map(squash);
|
|
52
|
+
const dropped = [...r.dropped];
|
|
53
|
+
/** @type {any[]} */
|
|
54
|
+
const facts = [];
|
|
55
|
+
// the kept facts say 'phrase' for a place too; the AI's own map says which were places
|
|
56
|
+
const placeNames = new Set((Array.isArray(mapping?.facts) ? mapping.facts : []).filter((m) => m?.shape === 'place').map((m) => String(m.name)));
|
|
57
|
+
for (const f of r.facts) {
|
|
58
|
+
const shape = f.shape;
|
|
59
|
+
if (shape === 'phrase' && f.words.length > 0 && placeNames.has(f.name)) {
|
|
60
|
+
// M10 am7 item 2 (R2, R2a, R2b): a PLACE word grows to its role word; the phrases are all to be in a result's quote (R2c, src/citedcheck.js factsOfLook)
|
|
61
|
+
facts.push({ ...f, phrases: placePhrases(text, f.words).phrases });
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (!(shape === 'money' || shape === 'number' || shape === 'time') || f.words.length === 0) { facts.push(f); continue; }
|
|
65
|
+
const at = { line: f.line, ...(f.forRule === undefined ? {} : { rule: f.forRule }), fact: f.name };
|
|
66
|
+
const keep = [];
|
|
67
|
+
for (const w of f.words) {
|
|
68
|
+
if (readsValue(lines, w, shape)) keep.push(w);
|
|
69
|
+
else dropped.push({ ...at, word: w, reason: 'no-value' });
|
|
70
|
+
}
|
|
71
|
+
if (keep.length === 0) { dropped.push({ ...at, reason: 'no-label' }); continue; }
|
|
72
|
+
facts.push({ ...f, words: keep });
|
|
73
|
+
}
|
|
74
|
+
return { facts, dropped };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** @param {import('./pagerules.js').Dropped[]} dropped @param {{n: number}[]} jobLines @returns {string[]} one plain line per fact that lost something, in the person's own words */
|
|
78
|
+
export const notCheckedLines = (dropped, jobLines) => dropRows(dropped).map((row) => dropLine(row, jobLines, lineRules));
|
|
79
|
+
|
|
80
|
+
// borrowed-from: bareloop src/inputlook.js@6b5dc74 (lookFactOf, rewritten to a plain function; the `example` field is not used here)
|
|
81
|
+
/**
|
|
82
|
+
* A kept fact as the look carries it: the page words under the name the later pieces read (a phrase holds `phrase`, any other `labels`/`label`).
|
|
83
|
+
* @param {import('./pagerules.js').KeptFact} k @param {string} source @returns {any}
|
|
84
|
+
*/
|
|
85
|
+
export function lookFactOf(k, source) {
|
|
86
|
+
/** @type {any} */
|
|
87
|
+
const out = { line: k.line, name: k.name, shape: k.shape, source, words: [...k.words] };
|
|
88
|
+
if (k.shape === 'phrase') out.phrase = k.words[0];
|
|
89
|
+
if (Array.isArray(/** @type {any} */ (k).phrases)) out.phrases = [.../** @type {any} */ (k).phrases];
|
|
90
|
+
else { out.labels = [...k.words]; if (k.words.length) out.label = k.words[0]; }
|
|
91
|
+
if (k.unit) out.unit = [...k.unit];
|
|
92
|
+
if (k.currency) out.currency = [...k.currency];
|
|
93
|
+
if (k.forRule !== undefined) out.forRule = k.forRule;
|
|
94
|
+
if (k.reading) out.reading = { ...k.reading };
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Look at ONE page input: the map call (once; once more if the answer is unreadable), then the rules.
|
|
100
|
+
* `callModel(content, attempt)` (attempt 1 or 2) makes and meters ONE model round and returns `{text}`, `{text, cutOff: true}` (the round hit its output cap) or `{error}`.
|
|
101
|
+
* @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}>}} o
|
|
102
|
+
* @returns {Promise<{ok: true, look: {facts: any[], dropped: any[]}, notChecked: string[], mapping: any, attempts: number}|{ok: false, reason: string, attempts: number}>}
|
|
103
|
+
*/
|
|
104
|
+
export async function lookAtPage({
|
|
105
|
+
label, text, jobLines, callModel,
|
|
106
|
+
}) {
|
|
107
|
+
const content = mapPrompt({ jobLines, label, text });
|
|
108
|
+
let attempts = 0;
|
|
109
|
+
for (;;) {
|
|
110
|
+
attempts += 1;
|
|
111
|
+
const r = await callModel(content, attempts);
|
|
112
|
+
if (r.error !== undefined) return { ok: false, reason: `the call about the page failed: ${r.error}`, attempts };
|
|
113
|
+
const parsed = r.cutOff === true ? { ok: false } : parseMapAnswer(r.text);
|
|
114
|
+
if (parsed.ok) {
|
|
115
|
+
const { mapping } = /** @type {any} */ (parsed);
|
|
116
|
+
const words = applyPageWords(text, mapping, jobLines);
|
|
117
|
+
// F241 "can it read": a money fact whose forms read no result line, by the run's own checker (src/pagedry.js), is Not checked, never signed
|
|
118
|
+
const read = await dryReadMoney(text, words.facts);
|
|
119
|
+
// a phrase fact is read against the same result lines (only when the job keeps a money fact; bareloop c550dc8)
|
|
120
|
+
const phr = await dryReadPhrases(text, read.facts);
|
|
121
|
+
const kept = { facts: phr.facts, dropped: [...words.dropped, ...read.dropped, ...phr.dropped] };
|
|
122
|
+
const dropped = kept.dropped.map((d) => ({ ...d, source: label }));
|
|
123
|
+
return {
|
|
124
|
+
ok: true, look: { facts: kept.facts.map((f) => lookFactOf(f, label)), dropped }, notChecked: notCheckedLines(kept.dropped, jobLines), mapping, attempts,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
if (attempts >= 2) return { ok: false, reason: MAP_UNREADABLE, attempts };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* What the drafter is told about a page it cannot read for itself: the words code checked against the saved page (kept), and every drop, so it never
|
|
133
|
+
* claims a check the page cannot give (bareloop's withDropNotes, told to the drafter as plain lines).
|
|
134
|
+
* @param {{label: string, address: string, chars: number, look: {facts: any[]}, notChecked: string[]}} o @returns {string[]}
|
|
135
|
+
*/
|
|
136
|
+
export function pageInfoLines({
|
|
137
|
+
label, address, chars, look, notChecked,
|
|
138
|
+
}) {
|
|
139
|
+
const q = (/** @type {string} */ w) => `"${w}"`;
|
|
140
|
+
const say = (/** @type {any} */ f) => {
|
|
141
|
+
const head = `${f.name}${f.forRule === undefined ? '' : ` (rule ${f.forRule})`}`;
|
|
142
|
+
// M10 am7 item 2: a place is told as the phrases it must be checked with (R2c: every one is a fact of its own)
|
|
143
|
+
if (Array.isArray(f.phrases)) return `${head}: place phrases (every one must be its own phrase fact) ${f.phrases.map(q).join(', ')}`;
|
|
144
|
+
const forms = [...(f.unit ?? []).map((/** @type {string} */ u) => `unit ${q(u)}`), ...(f.currency ?? []).map((/** @type {string} */ c) => `currency ${q(c)}`)];
|
|
145
|
+
const read = f.reading ? `, limit read from your words: ${ruleWords({ shape: f.shape, unit: f.unit, currency: f.currency, rule: f.reading })}` : '';
|
|
146
|
+
return `${head}: ${f.shape === 'phrase' ? 'phrase ' : f.words.length ? 'labels ' : ''}${f.words.map(q).join(', ') || '(read by its unit)'}${forms.length ? `, ${forms.join(', ')}` : ''}${read}`;
|
|
147
|
+
};
|
|
148
|
+
return [
|
|
149
|
+
`- ${label}: a web page (${address}), saved at drafting, ${chars} characters. Code checked the page's own words for the job's rules and kept only words the saved page proves.`,
|
|
150
|
+
...(look.facts.length ? [` Kept, line ${[...new Set(look.facts.map((/** @type {any} */ f) => f.line))].join(', ')}: ${look.facts.map(say).join('; ')}`] : [' Kept: nothing.']),
|
|
151
|
+
...(notChecked.length
|
|
152
|
+
? [' Code could not make these a check, so they are Not checked; never claim them as checked:', ...notChecked.map((l) => ` - ${l}`)]
|
|
153
|
+
: []),
|
|
154
|
+
];
|
|
155
|
+
}
|