fwdloop 0.32.0 → 0.34.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 (114) hide show
  1. package/bin/fwdloop +20 -2
  2. package/package.json +2 -2
  3. package/src/auditchecks.js +55 -0
  4. package/src/authoring.js +53 -12
  5. package/src/blockasks.js +45 -0
  6. package/src/blockassemble.js +159 -0
  7. package/src/blockdraft.js +86 -0
  8. package/src/blocklines.js +30 -0
  9. package/src/blockpick.js +175 -0
  10. package/src/cardlist.js +19 -0
  11. package/src/checkblock.js +843 -0
  12. package/src/checked.js +48 -9
  13. package/src/checklist.js +99 -0
  14. package/src/checklistsign.js +93 -0
  15. package/src/checkpick.js +7 -73
  16. package/src/checkwords.js +20 -1
  17. package/src/cited-record.js +21 -1
  18. package/src/citedcheck.js +162 -7
  19. package/src/closers.js +41 -3
  20. package/src/declaration.js +34 -9
  21. package/src/declaredclose.js +4 -0
  22. package/src/draft-steps.js +3 -1
  23. package/src/drafter.js +311 -206
  24. package/src/factwords.js +112 -0
  25. package/src/inputlook.js +53 -0
  26. package/src/labelscan.js +162 -0
  27. package/src/noteask.js +62 -0
  28. package/src/pageask.js +9 -69
  29. package/src/pagedropwords.js +11 -1
  30. package/src/pagedry.js +27 -4
  31. package/src/pagerules.js +19 -3
  32. package/src/panel/author.js +76 -7
  33. package/src/panel/authorcard.js +43 -17
  34. package/src/panel/data.js +41 -9
  35. package/src/panel/index.html +208 -13
  36. package/src/panel/result.js +4 -3
  37. package/src/panel/server.js +3 -1
  38. package/src/pickrecord.js +70 -54
  39. package/src/placerule.js +398 -0
  40. package/src/planrebuild.js +216 -0
  41. package/src/rowedit.js +148 -0
  42. package/src/rubricstep.js +272 -0
  43. package/src/runfile.js +4 -2
  44. package/src/runner.js +67 -10
  45. package/src/setup.js +11 -5
  46. package/src/sheetblock.js +22 -8
  47. package/src/sheetbuild.js +151 -0
  48. package/src/sheetchecks.js +52 -66
  49. package/src/sheetclaims.js +12 -32
  50. package/src/sheetfind.js +4 -4
  51. package/src/sheetlook.js +14 -3
  52. package/src/sheetoffer.js +74 -57
  53. package/src/sheetrows.js +123 -0
  54. package/src/sheetrun.js +13 -10
  55. package/src/summary-words.js +3 -3
  56. package/src/ticket-draft.js +4 -21
  57. package/src/ticketrows.js +100 -0
  58. package/src/try-checks.js +31 -12
  59. package/src/types.js +1 -0
  60. package/types/auditchecks.d.ts +25 -0
  61. package/types/authoring.d.ts +21 -2
  62. package/types/blockasks.d.ts +36 -0
  63. package/types/blockassemble.d.ts +50 -0
  64. package/types/blockdraft.d.ts +75 -0
  65. package/types/blocklines.d.ts +31 -0
  66. package/types/blockpick.d.ts +46 -0
  67. package/types/cardlist.d.ts +21 -0
  68. package/types/checkblock.d.ts +378 -0
  69. package/types/checked.d.ts +16 -2
  70. package/types/checklist.d.ts +115 -0
  71. package/types/checklistsign.d.ts +27 -0
  72. package/types/checkpick.d.ts +4 -34
  73. package/types/checkwords.d.ts +5 -0
  74. package/types/cited-record.d.ts +9 -0
  75. package/types/citedcheck.d.ts +33 -2
  76. package/types/closers.d.ts +24 -2
  77. package/types/declaration.d.ts +7 -0
  78. package/types/declaredclose.d.ts +2 -0
  79. package/types/drafter.d.ts +29 -715
  80. package/types/factwords.d.ts +38 -0
  81. package/types/inputlook.d.ts +49 -0
  82. package/types/labelscan.d.ts +35 -0
  83. package/types/noteask.d.ts +52 -0
  84. package/types/pageask.d.ts +2 -35
  85. package/types/pagedry.d.ts +13 -0
  86. package/types/pagerules.d.ts +7 -0
  87. package/types/panel/author.d.ts +41 -0
  88. package/types/panel/authorcard.d.ts +14 -9
  89. package/types/panel/authorflows.d.ts +4 -4
  90. package/types/panel/data.d.ts +5 -3
  91. package/types/panel/jobgrid.d.ts +1 -1
  92. package/types/pickrecord.d.ts +69 -13
  93. package/types/placerule.d.ts +208 -0
  94. package/types/planrebuild.d.ts +52 -0
  95. package/types/provider.d.ts +1 -1
  96. package/types/rowedit.d.ts +48 -0
  97. package/types/rubricstep.d.ts +63 -0
  98. package/types/runfile.d.ts +5 -2
  99. package/types/runner.d.ts +45 -1
  100. package/types/sheetblock.d.ts +12 -4
  101. package/types/sheetbuild.d.ts +84 -0
  102. package/types/sheetchecks.d.ts +12 -18
  103. package/types/sheetclaims.d.ts +2 -1
  104. package/types/sheetfind.d.ts +2 -2
  105. package/types/sheetoffer.d.ts +31 -6
  106. package/types/sheetrows.d.ts +81 -0
  107. package/types/sheetrun.d.ts +4 -4
  108. package/types/summary-words.d.ts +2 -1
  109. package/types/ticket-draft.d.ts +3 -49
  110. package/types/ticketrows.d.ts +61 -0
  111. package/types/try-checks.d.ts +4 -2
  112. package/types/types.d.ts +8 -0
  113. package/src/repairs.js +0 -38
  114. package/types/repairs.d.ts +0 -13
@@ -0,0 +1,112 @@
1
+ // borrowed-from: bareloop src/factwords.js@v0.56.0 (3383cce) (checkFactWords, keptSetOf and what they call; squash, countExact and countPhrase are fwd's, src/pagebits.js, the same counts with no built pattern; fwd's own keptSetOf, src/citedwords.js, is a different older copy and stays for the page-word path)
2
+ // THE FOUND-ONCE CHECK: code proves, at $0, that every word a fact check depends on is really in the person's source, and that every label (anchor) is one PICKED
3
+ // from the list code made from that source (src/labelscan.js), never typed. Nothing is graded here and no model is involved.
4
+ import { labelOnList, scanLabels } from './labelscan.js';
5
+ import { asList, normLabel, countExact, countPhrase } from './pagebits.js';
6
+ import { dropSentence } from './pagedropwords.js';
7
+
8
+ /** @param {string} shape @returns {'money'|'number'|'date'|'time'|'text'} the label list a fact's anchor is picked from */
9
+ const listOf = (shape) => /** @type {any} */ (['money', 'number', 'date', 'time'].includes(shape) ? shape : 'text');
10
+
11
+ /**
12
+ * What the page-word map (src/pagemap.js) KEPT and DROPPED for one input: the sets the second proof reads. A look from the old search-and-read
13
+ * path has no `dropped` list, so it gives null and the label is proved against the code-made list as before.
14
+ * @param {{facts?: any[], dropped?: (import('./pagerules.js').Dropped & {source?: string})[]}|null|undefined} look @param {string} source
15
+ * @returns {{labels: Set<string>, units: Set<string>, currencies: Set<string>, words: Set<string>, dropped: Map<string, import('./pagerules.js').Dropped>, forms: {labels: Set<string>, lang?: string, decimal?: string}[]}|null}
16
+ */
17
+ export function keptSetOf(look, source) {
18
+ if (!look || !Array.isArray(look.dropped)) return null;
19
+ const facts = (Array.isArray(look.facts) ? look.facts : []).filter((f) => f && f.source === source && Array.isArray(f.words));
20
+ const set = (/** @type {string[]} */ a) => new Set(a.map((w) => normLabel(String(w))));
21
+ /** @type {Map<string, import('./pagerules.js').Dropped>} */
22
+ const dropped = new Map();
23
+ for (const d of look.dropped) if (d.source === source && typeof d.word === 'string' && !dropped.has(normLabel(d.word))) dropped.set(normLabel(d.word), d);
24
+ return {
25
+ labels: set(facts.filter((f) => f.shape !== 'phrase').flatMap((f) => f.words)),
26
+ units: set(facts.flatMap((f) => f.unit ?? [])),
27
+ currencies: set(facts.flatMap((f) => f.currency ?? [])),
28
+ words: set(facts.flatMap((f) => [...f.words, ...(f.unit ?? []), ...(f.currency ?? [])])),
29
+ dropped,
30
+ forms: facts.filter((f) => f.shape !== 'phrase' && (f.lang !== undefined || f.decimal !== undefined))
31
+ .map((f) => ({ labels: new Set(f.words.map((w) => normLabel(String(w)))), lang: f.lang, decimal: f.decimal })),
32
+ };
33
+ }
34
+
35
+ /**
36
+ * The reds for ONE fact part against its frozen source text.
37
+ * @param {{part: any, text: string, line: number|string, scan?: import('./labelscan.js').LabelScan, kept?: ReturnType<typeof keptSetOf>}} o
38
+ * @returns {{code: string, detail: string}[]}
39
+ */
40
+ export function checkFactWords({ part, text, line, scan = scanLabels(text), kept = null }) {
41
+ /** @type {{code: string, detail: string}[]} */
42
+ const reds = [];
43
+ const src = part.source;
44
+ const red = (/** @type {string} */ code, /** @type {string} */ msg) => reds.push({ code, detail: `line ${line}: ${msg} Nothing was signed.` });
45
+ for (const f of Array.isArray(part.facts) ? part.facts : []) {
46
+ const who = `fact "${f.name}"`;
47
+ // a word the page rules DROPPED (and no other fact kept) can never come back through the drafter (idea A core, spec 4.3)
48
+ const dropRed = (/** @type {string} */ what, /** @type {unknown} */ w) => {
49
+ const n = normLabel(String(w));
50
+ const d = kept?.dropped.get(n);
51
+ if (!kept || !d || kept.words.has(n)) return false;
52
+ red('rubric-fact-word-dropped', `${who}: the ${what} ${JSON.stringify(n)} cannot be used. ${dropSentence(d)}`);
53
+ return true;
54
+ };
55
+ if (f.anchor !== undefined && f.shape !== 'phrase' && kept) {
56
+ // a page input read by the page-word map: the label must be one the map KEPT (the code-made list cannot hold a marker after a number)
57
+ const label = normLabel(String(f.anchor));
58
+ if (dropRed('label', f.anchor)) { /* said above */ } else if (!kept.labels.has(label)) {
59
+ const some = [...kept.labels].slice(0, 12).map((l) => JSON.stringify(l)).join(', ');
60
+ red('rubric-fact-label-off-list', `${who}: the label ${JSON.stringify(label)} is not one of the labels the page words for "${src}" kept. A label is picked from those, never typed${some ? `: ${some}` : ' (there are none - leave the label out)'}.`);
61
+ } else if (countExact(text, label) < 1) {
62
+ red('rubric-fact-word-missing', `${who}: the label ${JSON.stringify(label)} is not in the input "${src}".`);
63
+ } else if (Number.isInteger(part.count?.min) && countExact(text, label) < part.count.min) {
64
+ const n = part.count.min;
65
+ const seen = countExact(text, label);
66
+ red('rubric-fact-label-rare', `${who}: the label ${JSON.stringify(label)} is in the input "${src}" only ${seen} time${seen === 1 ? '' : 's'}, but this line asks for ${n} results, so a label that sits in each result must be there at least ${n} times. Pick a label that is counted ${n} or more times.`);
67
+ }
68
+ } else if (f.anchor !== undefined && f.shape !== 'phrase') {
69
+ const list = listOf(f.shape);
70
+ const row = labelOnList(scan, list, f.anchor);
71
+ if (!row) {
72
+ const some = scan[list].slice(0, 12).map((r) => JSON.stringify(r.label)).join(', ');
73
+ red('rubric-fact-label-off-list', `${who}: the label ${JSON.stringify(normLabel(String(f.anchor)))} is not one of the labels the input "${src}" holds before a ${f.shape === 'text' ? 'text value' : f.shape}. A label is picked from that list, never typed${some ? `: ${some}` : ' (the list is empty - leave the label out)'}.`);
74
+ } else if (countExact(text, row.label) < 1) {
75
+ red('rubric-fact-word-missing', `${who}: the label ${JSON.stringify(row.label)} is not in the input "${src}".`);
76
+ } else if (Number.isInteger(part.count?.min) && row.count < part.count.min) {
77
+ // M1: a label that starts each result must repeat as often as results were asked for; one that sits once on the page
78
+ // (a sort tab, a switch) is in no result, so no one-result quote can hold it
79
+ const n = part.count.min;
80
+ red('rubric-fact-label-rare', `${who}: the label ${JSON.stringify(row.label)} is in the input "${src}" only ${row.count} time${row.count === 1 ? '' : 's'}, but this line asks for ${n} results, so a label that sits in each result must be there at least ${n} times. Pick a label from the list that is counted ${n} or more times.`);
81
+ }
82
+ }
83
+ // a look fact that carries lang / decimal: the signed fact must sign the same, or a drafter that drops it signs a fact that reds at run time
84
+ if (kept && f.anchor !== undefined && f.shape !== 'phrase') {
85
+ const mine = kept.forms.filter((k) => k.labels.has(normLabel(String(f.anchor))));
86
+ if (mine.length && !mine.some((k) => (k.lang === undefined || k.lang === f.lang) && (k.decimal === undefined || k.decimal === (f.decimal ?? '.')))) {
87
+ const k = mine[0];
88
+ const [field, value] = k.lang !== undefined && k.lang !== f.lang ? ['lang', k.lang] : ['decimal', k.decimal];
89
+ reds.push({ code: 'rubric-fact-form-unsigned', detail: `line ${line}: the fact ${JSON.stringify(f.name)} must sign ${field} ${JSON.stringify(value)}, as the page look found. Nothing spent.` });
90
+ }
91
+ }
92
+ if (f.until !== undefined) dropRed('closing label', f.until);
93
+ if (f.until !== undefined && countExact(text, f.until) < 1) red('rubric-fact-word-missing', `${who}: ${JSON.stringify(f.until)} is not in the input "${src}". Copy the closing words from the input, or leave them out.`);
94
+ if (f.shape === 'phrase' && typeof f.phrase === 'string') {
95
+ const seen = countPhrase(text, f.phrase);
96
+ if (seen < 1) red('rubric-fact-word-missing', `${who}: ${JSON.stringify(f.phrase)} is not in the input "${src}". Copy the words the input really uses, or remove the check.`);
97
+ else if (Number.isInteger(part.count?.min) && seen < part.count.min) {
98
+ // M4: the words each result's quote must say must repeat as often as results were asked for; page-header words (counted
99
+ // once or twice) are in no result, so no one-result quote can say them
100
+ const n = part.count.min;
101
+ red('rubric-fact-phrase-rare', `${who}: the words ${JSON.stringify(f.phrase)} are in the input "${src}" only ${seen} time${seen === 1 ? '' : 's'}, but this line asks for ${n} results - each result's own quote must say them. Pick words every result says, or drop this check.`);
102
+ }
103
+ }
104
+ // a unit (one string, or every one of a list) must be found as whole words; a currency sign (each of a list) must be found as written
105
+ for (const u of asList(f.unit)) dropRed('unit', u);
106
+ for (const c of asList(f.currency)) dropRed('currency', c);
107
+ for (const u of asList(f.unit)) if (countPhrase(text, u) < 1) red('rubric-fact-word-missing', `${who}: the unit ${JSON.stringify(u)} is not in the input "${src}". Copy the words the input really uses.`);
108
+ for (const c of asList(f.currency)) if (countExact(text, c) < 1) red('rubric-fact-word-missing', `${who}: the currency ${JSON.stringify(c)} is not in the input "${src}". Copy the sign the input really uses.`);
109
+ }
110
+ return reds;
111
+ }
112
+
@@ -0,0 +1,53 @@
1
+ // borrowed-from: bareloop src/inputlook.js@v0.56.0 (3383cce) (renderLookReport only: the look itself is fwd's, src/pagelook.js and src/sheetlook.js)
2
+ import { dropRows } from './pagedropwords.js';
3
+
4
+ /** @typedef {{line: number, name: string, shape: string, source: string, label?: string, labelId?: string, value?: string, phrase?: string, example: string, rule?: any, aiProposal?: boolean, forRule?: number, reading?: import('./pagerules.js').Reading,
5
+ * words?: string[], labels?: string[], unit?: string[], currency?: string[], lang?: string, decimal?: string}} LookFact `words` / `labels` / `unit` / `currency`: what the page-word map kept (idea A core) */
6
+ /** @typedef {{line: number, rule?: number, words?: string, why: string}} LookNotFound */
7
+
8
+ /** @typedef {{facts: LookFact[], prose: {line: number, text?: string}[], notFound: LookNotFound[], dropped?: import('./pagerules.js').Dropped[]}} LookReport */
9
+
10
+ /**
11
+ * The look's report as the DRAFTER reads it: one block, per job line, of what can be checked (with the exact words to copy) and what
12
+ * could not be found. Written by code from the verified report.
13
+ * @param {LookReport} report @returns {string}
14
+ */
15
+ export function renderLookReport(report) {
16
+ const byLine = new Map();
17
+ const add = (/** @type {number} */ n, /** @type {string} */ s) => byLine.set(n, [...(byLine.get(n) ?? []), s]);
18
+ for (const f of report.facts) {
19
+ const bits = [`${f.name} - ${f.shape}`, `from "${f.source}"`];
20
+ if (Array.isArray(f.words)) {
21
+ // a fact the page-word map kept (idea A core): the words the page holds, each one proven by code; the first is the main one
22
+ const quote = (/** @type {string[]|undefined} */ a) => (a ?? []).map((w) => JSON.stringify(w)).join(' or ');
23
+ if (f.shape === 'phrase') bits.push(`the quote must say ${f.words.length > 1 ? 'ONE of these page words, copied exactly' : 'this page word'}: ${quote(f.words)}`);
24
+ else {
25
+ if (f.words.length) bits.push(`label ${quote(f.words)}${f.words.length > 1 ? ' (the first is the main one)' : ''}`);
26
+ else bits.push('no label (read by its unit or sign alone)');
27
+ if (f.unit?.length) bits.push(`unit ${quote(f.unit)}`);
28
+ if (f.currency?.length) bits.push(`currency ${quote(f.currency)}`);
29
+ // a page form the page rules proved is on the page: the drafter signs it as given, never a guess (the run reads that form and no other)
30
+ if (f.lang !== undefined) bits.push(`lang ${JSON.stringify(f.lang)} (the page writes the month name in this language: sign it as the fact's lang)`);
31
+ if (f.decimal !== undefined) bits.push(`decimal ${JSON.stringify(f.decimal)} (the page writes this mark before the decimals: sign it as the fact's decimal)`);
32
+ }
33
+ } else if (f.phrase !== undefined) bits.push(`the quote must say ${JSON.stringify(f.phrase)}`);
34
+ else if (f.label !== undefined) bits.push(`label ${JSON.stringify(f.label)} (id ${f.labelId})`);
35
+ else bits.push('no label (the value as the quote writes it)');
36
+ if (f.example) bits.push(`seen: ${JSON.stringify(f.example)}`);
37
+ if (f.rule) bits.push(`rule ${JSON.stringify(f.rule)}`);
38
+ if (f.aiProposal) bits.push("AI's proposal");
39
+ if (f.forRule !== undefined) bits.push(`carries ~ rule ${f.forRule}`);
40
+ add(f.line, `CAN CHECK: ${bits.join(', ')}`);
41
+ }
42
+ // NO SILENT DROP: a word, fact or rule the page rules removed is said to the drafter too, so it is never written back as a check
43
+ for (const row of dropRows(report.dropped)) {
44
+ add(row.line, row.full
45
+ ? `NOT CHECKED${row.rule !== undefined ? ` (rule ${row.rule})` : ''}: "${row.fact}" - ${row.sentences.join(' ')}`
46
+ : `LEFT OUT of "${row.fact}" (the rest is still checked): ${row.sentences.join(' ')}`);
47
+ }
48
+ for (const p of report.prose) add(p.line, 'WRITTEN TEXT (not looked up; keep its word/section counts)');
49
+ for (const n of report.notFound) add(n.line, `NOT FOUND${n.rule ? ` (rule ${n.rule})` : ''}: ${n.words ? `${JSON.stringify(n.words)} - ` : ''}${n.why}`);
50
+ const lines = [...byLine.keys()].sort((a, b) => a - b).map((n) => `line ${n}:\n${byLine.get(n).map((/** @type {string} */ s) => ` ${s}`).join('\n')}`);
51
+ return `WHAT THE LOOK AT THE INPUTS FOUND - write the facts from this; copy the label and phrase words exactly\n\n${lines.join('\n') || '(the look reported nothing)'}`;
52
+ }
53
+
@@ -0,0 +1,162 @@
1
+ // borrowed-from: bareloop src/labelscan.js@v0.56.0 (3383cce) (scanLabels, labelOnList and what they call; normLabel is fwd's, src/pagebits.js; the date finder is a literal, not a built pattern: src/ builds none, test/signed-text.test.js)
2
+ // THE LABEL LIST: before the look, code scans a source at $0 and lists, per shape (money, number, date, time, text), the words that sit right before a value of
3
+ // that shape, with how often each occurs. A label is picked ONLY from this list. ONE generic scan for every page or file; plain string work, no model.
4
+ import { normLabel } from './pagebits.js';
5
+
6
+ /** @typedef {{id: string, label: string, count: number, example: string}} LabelEntry */
7
+ /** @typedef {Record<'money'|'number'|'date'|'time'|'text', LabelEntry[]>} LabelScan */
8
+
9
+ export const LABEL_SHAPES = Object.freeze(['money', 'number', 'date', 'time', 'text']);
10
+
11
+ /** a label must occur at least this often to be listed (1: a one-page document with one total still has its label; the list is cut to the highest counts) */
12
+ export const MIN_COUNT = 1;
13
+
14
+ /** how many labels one shape's list holds at most (the highest counts first) */
15
+ export const MAX_PER_SHAPE = 40;
16
+
17
+ /** the longest label, in characters */
18
+ const MAX_LABEL = 40;
19
+
20
+ /** the longest whole gap taken as a label when it is short */
21
+ const MAX_GAP_LABEL = 24;
22
+
23
+ /** a phrase must repeat this often to be a repeated phrase */
24
+ const MIN_PHRASE = 3;
25
+
26
+ /** how many repeated phrases are looked behind */
27
+ const MAX_PHRASES = 20;
28
+
29
+ /** a line is scanned up to this many characters, and for this many values (a minified page is one huge line; the bound caps the work per line, each finder's own regex is kept linear below) */
30
+ const MAX_LINE = 20000;
31
+
32
+ const MAX_VALUES_PER_LINE = 400;
33
+
34
+ /** only this much of a source is scanned (a source over it is scanned up to a line end) */
35
+ export const SCAN_MAX_CHARS = 2_000_000;
36
+
37
+ const WS = /[\s   ]+/g;
38
+
39
+ /**
40
+ * The page reader's bracketed tag (`[ref=549]`), shared by the three places that strip it. The lookahead and lookbehind add no match and drop no
41
+ * match: a `[` that sits inside the run of an earlier `[letters=` (no `]` or white space between) is skipped, because that earlier start reads the same
42
+ * run to the same end - it matches (and consumes this one) or fails (and so does this one). Without them "[a=[a=[a=..." with no `]` is quadratic.
43
+ */
44
+ export const TAG = /\[(?=[A-Za-z]+=)(?<!\[[A-Za-z]+=[^\]\s]*?)[A-Za-z]+=[^\]\s]*\]/g;
45
+
46
+
47
+ /** value finders in priority order: an earlier shape owns a span a later one would also match */
48
+ const FINDERS = /** @type {[string, RegExp][]} */ ([
49
+ ['date', /\b\d{4}-\d{2}-\d{2}\b|\b\d{1,2}\/\d{1,2}\/\d{2,4}\b|\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\.? \d{1,2}(?:, \d{4})?\b|\b\d{1,2} (?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\.? \d{4}\b/g],
50
+ ['time', /\b\d{1,2}:\d{2}(?: ?[AaPp]\.?[Mm]\.?)?(?![\w:])/g],
51
+ // the 2nd shape's leading lookbehind skips a start inside a digit/comma run that an earlier start of the run already covers (that start reads the same
52
+ // run to the same end, so it matches first or fails like this one); without it "1,1,1,...x" is quadratic. The covering start is never one right after
53
+ // a "." - the digits of a decimal can already belong to an earlier match ("$1.5,2 dollars" reads "2 dollars" as its own)
54
+ ['money', /[$€£] ?\d[\d,]*(?:\.\d+)?|(?<!(?<!\.)\b\d[\d,]*?)\b\d[\d,]*(?:\.\d+)? ?(?:US dollars?|dollars?|USD|euros?|EUR|pounds?|GBP)\b/g],
55
+ ['number', /(?<![\w.,])\d[\d,]*(?:\.\d+)?(?![\w]|\.\d)/g],
56
+ // (?<![A-Za-z]): a start inside a run of letters is covered by the run's first letter (same match, earlier), so a long run of letters with no digit is linear
57
+ ['text', /(?<![A-Za-z])[A-Za-z]*\d[\w.\-]*/g],
58
+ ]);
59
+
60
+ const PHRASE = /\b[A-Z][a-z]+(?: [A-Z][a-z]+)+\b/g;
61
+
62
+ /** @param {string} gap @returns {string[]} the labels a gap of text before a value offers */
63
+ function candidates(gap) {
64
+ const g = normLabel(gap);
65
+ if (g === '') return [];
66
+ const tokens = g.split(' ');
67
+ /** @type {Set<string>} */
68
+ const out = new Set();
69
+ out.add(normLabel(tokens.at(-1) ?? ''));
70
+ if (tokens.length >= 2) out.add(normLabel(tokens.slice(-2).join(' ')));
71
+ if (g.length <= MAX_GAP_LABEL) out.add(g);
72
+ return [...out].filter((c) => c !== '' && c.length <= MAX_LABEL && !/\d/.test(c) && !/ref=/.test(c));
73
+ }
74
+
75
+ /**
76
+ * Scan one source text for the labels that sit before values, per shape.
77
+ * @param {string} text
78
+ * @returns {LabelScan}
79
+ */
80
+ export function scanLabels(text) {
81
+ let src = String(text ?? '');
82
+ if (src.length > SCAN_MAX_CHARS) { const nl = src.lastIndexOf('\n', SCAN_MAX_CHARS); src = src.slice(0, nl > 0 ? nl : SCAN_MAX_CHARS); }
83
+ /** @type {Record<string, Map<string, {count: number, example: string}>>} */
84
+ const seen = Object.fromEntries(LABEL_SHAPES.map((s) => [s, new Map()]));
85
+ const bump = (/** @type {string} */ shape, /** @type {string} */ label, /** @type {string} */ example) => {
86
+ const m = seen[shape];
87
+ const cur = m.get(label);
88
+ if (cur) cur.count += 1; else m.set(label, { count: 1, example });
89
+ };
90
+ /** @type {Map<string, number>} */
91
+ const phraseCount = new Map();
92
+ /** @type {string[]} */
93
+ const lines = [];
94
+ /** @type {{line: string, at: number, phrase: string}[]} */
95
+ const variants = [];
96
+ for (const raw of src.split('\n')) {
97
+ const line = raw.slice(0, MAX_LINE).replace(TAG, ' ').replace(WS, ' ').trim();
98
+ if (line === '') continue;
99
+ lines.push(line);
100
+ for (const m of line.matchAll(PHRASE)) {
101
+ // a capitalised run may start with a sentence-initial word ("Leaves San Francisco ..."): the run is also read without its first word
102
+ const words = m[0].split(' ');
103
+ let off = m.index ?? 0;
104
+ for (let j = 0; j <= 1 && words.length - j >= 2; j += 1) {
105
+ const phrase = words.slice(j).join(' ');
106
+ phraseCount.set(phrase, (phraseCount.get(phrase) ?? 0) + 1);
107
+ variants.push({ line, at: off, phrase });
108
+ off += words[j].length + 1;
109
+ }
110
+ }
111
+ }
112
+ for (const line of lines) {
113
+ /** @type {{shape: string, s: number, e: number, v: string}[]} */
114
+ const found = [];
115
+ for (const [shape, re] of FINDERS) {
116
+ for (const m of line.matchAll(re)) {
117
+ const s = m.index ?? 0;
118
+ const e = s + m[0].length;
119
+ if (found.length >= MAX_VALUES_PER_LINE) break;
120
+ if (found.some((f) => s < f.e && e > f.s)) continue;
121
+ found.push({ shape, s, e, v: m[0] });
122
+ }
123
+ }
124
+ found.sort((a, b) => a.s - b.s);
125
+ let prevEnd = 0;
126
+ for (const f of found) {
127
+ for (const c of candidates(line.slice(prevEnd, f.s))) bump(f.shape, c, f.v);
128
+ prevEnd = f.e;
129
+ }
130
+ }
131
+ // the words before each REPEATED capitalised phrase (a place, a name): text facts
132
+ const phrases = new Set([...phraseCount].filter(([, n]) => n >= MIN_PHRASE).sort((a, b) => b[1] - a[1]).slice(0, MAX_PHRASES).map(([p]) => p));
133
+ for (const v of variants) {
134
+ if (!phrases.has(v.phrase)) continue;
135
+ for (const c of candidates(v.line.slice(0, v.at))) bump('text', c, v.phrase);
136
+ }
137
+ /** @type {Record<string, string>} */
138
+ const prefix = { money: 'm', number: 'n', date: 'd', time: 't', text: 'x' };
139
+ return /** @type {LabelScan} */ (Object.fromEntries(LABEL_SHAPES.map((shape) => {
140
+ const rows = [...seen[shape]].filter(([, v]) => v.count >= MIN_COUNT)
141
+ .sort((a, b) => b[1].count - a[1].count || a[0].length - b[0].length || (a[0] < b[0] ? -1 : 1))
142
+ .slice(0, MAX_PER_SHAPE)
143
+ .map(([label, v], i) => ({ id: `${prefix[shape]}${i + 1}`, label, count: v.count, example: v.example }));
144
+ return [shape, rows];
145
+ })));
146
+ }
147
+
148
+ /**
149
+ * Is this label on the list for this shape? Compared the way a label is read: white space of any kind is one space, quote marks at the
150
+ * edges are dropped. `idOrText` may be a list id (`t1`) or the exact words.
151
+ * @param {LabelScan} scan @param {string} shape @param {unknown} idOrText
152
+ * @returns {LabelEntry|null}
153
+ */
154
+ export function labelOnList(scan, shape, idOrText) {
155
+ const rows = scan[/** @type {'money'} */ (shape)];
156
+ if (!rows || typeof idOrText !== 'string') return null;
157
+ const asId = rows.find((r) => r.id === idOrText.trim());
158
+ if (asId) return asId;
159
+ const want = normLabel(idOrText);
160
+ return rows.find((r) => r.label === want) ?? null;
161
+ }
162
+
package/src/noteask.js ADDED
@@ -0,0 +1,62 @@
1
+ // borrowed-from: bareloop src/noteask.js@v0.57.0 (c18df406) (NOTE_SYSTEM, the question's wording, decideNote's reading of the typed answer; the call itself is fwd's forced tool turn, src/drafter.js forcedTurn, not bareloop's text reply)
2
+ // The note question (M17 am1 1(e)). A facts-only line ("find these on the page") may also ask for written words ("and write a one-sentence note"). Code cannot read that from the line, so the AI is
3
+ // asked ONCE per draft, only when a line is facts-only: yes or no per line, typed. CODE decides what it means (src/checkblock.js buildNote: a `$` note row and a countable nonEmpty part, so the step
4
+ // is told to write `text`). The AI sees the numbered line text only, never a `~` rule. A call with no usable answer leaves each asked line facts-only with a Not checked row, never a guess.
5
+ // What this throws away: everything but yes/no per asked line (a line it was not asked about, any other field).
6
+
7
+ /** the label of the forced turn, as the draft's log and the replay in src/planrebuild.js see it */
8
+ export const NOTE_KIND = 'note-ask';
9
+ export const NOTE_TOOL = 'answer_note_question';
10
+
11
+ export const NOTE_SYSTEM = 'You read the numbered lines of a job. You answer only about what each line says; you never invent words.';
12
+
13
+ export const NOTE_SCHEMA = Object.freeze({
14
+ type: 'object',
15
+ properties: {
16
+ lines: {
17
+ type: 'array',
18
+ items: {
19
+ type: 'object',
20
+ properties: { line: { type: 'integer', minimum: 1, description: 'the job line number' }, writtenWords: { enum: ['yes', 'no'] } },
21
+ required: ['line', 'writtenWords'],
22
+ additionalProperties: false,
23
+ },
24
+ },
25
+ },
26
+ required: ['lines'],
27
+ additionalProperties: false,
28
+ });
29
+
30
+ /** What the AI is told: the numbered job lines (text only) and the one question. @param {{n: number, text: string}[]} lines @returns {string} */
31
+ export function notePrompt(lines) {
32
+ return `THE JOB:\n${lines.map((l) => `LINE ${l.n}: ${l.text}`).join('\n')}\n\n`
33
+ + 'For EACH line answer ONE question: does the line also ask for written words (a note, a sentence, a paragraph, a summary) beyond the facts found on the page (items, numbers, dates, quoted words)? '
34
+ + 'A line that only asks to list, find or give items with their fields is "no". '
35
+ + `Call ${NOTE_TOOL} once with one entry per line: {"line": <line number>, "writtenWords": "yes" or "no"}. `
36
+ + 'Example: for "LINE 1: List the 3 newest posts with title and date" and "LINE 2: Write a two-sentence recap of the newest post" the entries are line 1 "no" and line 2 "yes".';
37
+ }
38
+
39
+ /**
40
+ * Code reads the typed answer: every asked line answered exactly yes or no, else null (no repair). An answer for a line not asked is unreadable too.
41
+ * @param {any} args the tool's arguments @param {{n: number}[]} lines @returns {Map<number, 'yes'|'no'>|null}
42
+ */
43
+ export function decideNote(args, lines) {
44
+ if (args === null || typeof args !== 'object' || !Array.isArray(args.lines)) return null;
45
+ /** @type {Map<number, 'yes'|'no'>} */
46
+ const out = new Map();
47
+ for (const e of args.lines) {
48
+ if (e === null || typeof e !== 'object' || !Number.isInteger(e.line) || (e.writtenWords !== 'yes' && e.writtenWords !== 'no') || !lines.some((l) => l.n === e.line)) return null;
49
+ out.set(e.line, e.writtenWords);
50
+ }
51
+ return lines.every((l) => out.has(l.n)) ? out : null;
52
+ }
53
+
54
+ /**
55
+ * The answers per asked line as the block reads them: the typed answer, or `failed` for every asked line when there is none. ONE function, shared by the draft and the replay.
56
+ * @param {number[]} asked the facts-only lines asked @param {any} args the tool's arguments, or null @param {{n: number}[]} lines
57
+ * @returns {{line: number, answer: 'yes'|'no'|'failed'}[]}
58
+ */
59
+ export function noteAnswers(asked, args, lines) {
60
+ const d = args === null ? null : decideNote(args, lines.filter((l) => asked.includes(l.n)));
61
+ return asked.map((n) => ({ line: n, answer: d?.get(n) ?? 'failed' }));
62
+ }
package/src/pageask.js CHANGED
@@ -1,21 +1,8 @@
1
- // borrowed-from: bareloop src/pagemap.js@0a34846 (DROP_IT, isDropIt, isAgree, readingQuestion, readingOfQuestion, askableFromLook, ruleBounds, tooManyAsksText)
1
+ // borrowed-from: bareloop src/pagemap.js@0a34846 (DROP_IT, isDropIt, isAgree, readingQuestion, readingOfQuestion, tooManyAsksText)
2
2
  // borrowed-from: bareloop src/facts.js@0a34846 (ruleWords, sayBound, moneyAs)
3
3
  // borrowed-from: bareloop src/pagemap.js@v0.49.0 (d51a367) (stripAgreeLead, F240; adapted: literal regex, src/ bans new RegExp)
4
- // M10 piece 3 (docs/wiki/the-module-ladder.md "M10", item 4, am1, am2, am5): the early asks CODE forces before any paid drafting, from the page look's own
5
- // result. The model never decides whether to ask: this file reads a kept fact's own keys (line, forRule, name, shape, unit, currency, reading) and the job
6
- // lines, and nothing else (test/m10-pageask.test.js greps for it). The question words are bareloop's, verbatim (am5 item 1); the answer words are
7
- // agree / yes (code's reading), your own words, and, for a can't-check ask only, "drop it" (am2 item 2).
8
- // Every rule is one of three kinds:
9
- // PAGE: a kept page word carries it: no ask.
10
- // READING: a kept fact carries it with a `reading` (a limit the page cannot hold in words, e.g. "not a red-eye"). Asked only when a bound of the
11
- // reading is NOT in the words the person wrote; a bound they wrote themselves is theirs and nothing is asked.
12
- // CAN'T CHECK: no kept fact carries it.
13
- // A COUNT guardrail (declaration.js isCountGuardrail) is none of these: it is asked once, as a pick (M10 am24).
14
- // Throws away: a fact's name, words and source (only its reading and the rule it serves are used).
4
+ // The words of the asks and of the answers to them. M17 am4 (A1): the asks themselves come from the list (src/blockasks.js); the page-look ask path that sat here is gone.
15
5
  import { redactSecrets } from './redact.js';
16
- import { lineRules, boundInWords, wordsSaidOn } from './pagebits.js';
17
- import { validReading } from './pagerules.js';
18
- import { isCountGuardrail } from './declaration.js';
19
6
  import { HOW_TO_ANSWER } from './checkpick.js';
20
7
  import { columnTail } from './sheetfind.js';
21
8
 
@@ -44,9 +31,6 @@ export const stripAgreeLead = (text) => {
44
31
  return m ? m[1].trim() : String(text ?? '');
45
32
  };
46
33
 
47
- /** @typedef {{line: number, rule: number, source: 'look', question: string, ask: 'reading'|'cant-check', ruleText: string, reading?: string}} LookAsk
48
- * `reading` = the plain words an `agree` writes as a `~` rule (a reading ask only) */
49
-
50
34
  /** @param {unknown} n @param {string} shape @param {any} f @returns {string} one bound, as the person would say it */
51
35
  function sayBound(n, shape, f) {
52
36
  if (shape === 'money') return moneyAs(f, /** @type {string|number} */ (n), false);
@@ -77,11 +61,14 @@ const READING_ASKED = '. Agree?';
77
61
  const READING_ANSWER = ' Answer "agree"';
78
62
  const READING_TAIL = `${READING_ASKED}${READING_ANSWER}`;
79
63
  /** @param {number} n @returns {string} the rest of a reading ask after its answer words */
80
- const readingRest = (n) => `, or type your own reading (your answer is added as a new ~ rule on line ${n}).`;
64
+ const readingRest = (n) => `, or type your own reading (your answer replaces that ~ rule on line ${n}).`;
81
65
  /** @param {number} n @returns {string} the answer words a can't-check ask ends with (said once, here, and cut in the panel) */
82
- const cantCheckTail = (n) => ` Answer "${DROP_IT}", or type how to check it (your answer is added as a new ~ rule on line ${n}).`;
66
+ const cantCheckTail = (n) => ` Answer "${DROP_IT}", or type how to check it (your answer replaces that ~ rule on line ${n}).`;
83
67
  /** @param {number} n @param {string} rule @param {string} reading @returns {string} */
84
- const readingQuestion = (n, rule, reading) => `Your line ${n} says "${rule}".${READING_HEAD}${reading}${READING_TAIL}${readingRest(n)}`;
68
+ export const readingQuestion = (n, rule, reading) => `Your line ${n} says "${rule}".${READING_HEAD}${reading}${READING_TAIL}${readingRest(n)}`;
69
+ // borrowed-from: bareloop src/pagemap.js@v0.56.0 (3383cce) (cantCheckQuestion; readingQuestion above is exported for the block's asks)
70
+ /** @param {number} n @param {string} rule @returns {string} the can't-check ask in its one spelling */
71
+ export const cantCheckQuestion = (n, rule) => `Your line ${n} says "${rule}". I can't check this on the page. Drop it?${cantCheckTail(n)}`;
85
72
  /** @param {unknown} q a recorded question @returns {string|null} the reading a reading ask proposed, or null when it was another kind of question */
86
73
  export function readingOfQuestion(q) {
87
74
  const s = String(q ?? '');
@@ -98,58 +85,11 @@ export function readingOfQuestion(q) {
98
85
  export function panelQuestionText(q) {
99
86
  const text = String(q.question);
100
87
  if (q.source !== 'look') return text;
101
- const tails = [`${READING_ANSWER}${readingRest(q.line)}`, cantCheckTail(q.line), columnTail(q.line), ` ${HOW_TO_ANSWER(q.line, true)}`, ` ${HOW_TO_ANSWER(q.line, false)}`];
88
+ const tails = [`${READING_ANSWER}${readingRest(q.line)}`, cantCheckTail(q.line), columnTail(q.line), columnTail(q.line, true), ` ${HOW_TO_ANSWER(q.line, true)}`, ` ${HOW_TO_ANSWER(q.line, false)}`];
102
89
  const hit = tails.find((t) => text.endsWith(t));
103
90
  return hit === undefined ? text : text.slice(0, text.length - hit.length);
104
91
  }
105
92
 
106
- /**
107
- * The early asks CODE forces before any paid drafting, from the look's own result. One ask per rule text on a line; readings first, then can't-check
108
- * asks, each in line order. The caller applies the cap and the answer gate.
109
- * @param {{facts?: {line: number, forRule?: number, name?: string, shape?: string, unit?: string[], currency?: string[], reading?: import('./pagerules.js').Reading}[]}|null|undefined} look
110
- * @param {{n: number, text?: string, rule?: string, rules?: string[]}[]|null|undefined} jobLines
111
- * @returns {LookAsk[]}
112
- */
113
- export function askableFromLook(look, jobLines) {
114
- const facts = Array.isArray(look?.facts) ? look.facts : [];
115
- /** @type {LookAsk[]} */
116
- const readings = [];
117
- /** @type {LookAsk[]} */
118
- const cants = [];
119
- /** @type {Set<string>} */
120
- const seen = new Set();
121
- for (const l of Array.isArray(jobLines) ? jobLines : []) {
122
- lineRules(l).forEach((rule, k) => {
123
- const n = k + 1;
124
- if (isCountGuardrail(rule)) return; // M10 am24: a count guardrail is asked only as a pick (src/checkpick.js), never as a page question; its look facts stay
125
- const key = `${l.n}\u0000${rule.trim().toLowerCase()}`;
126
- const tied = facts.filter((f) => f.line === l.n && f.forRule === n);
127
- if (tied.length > 0) {
128
- const said = wordsSaidOn(l);
129
- const f = tied.find((x) => x.reading && validReading(x.shape, x.reading) && ruleBounds(x.reading).some((b) => !boundInWords(b, said)));
130
- if (f === undefined || seen.has(key)) return;
131
- seen.add(key);
132
- const reading = `${f.name} ${ruleWords({ shape: f.shape, unit: f.unit, currency: f.currency, rule: f.reading })}`;
133
- readings.push({
134
- line: l.n, rule: n, source: 'look', ask: 'reading', ruleText: rule, reading,
135
- question: readingQuestion(l.n, rule, reading),
136
- });
137
- return;
138
- }
139
- if (seen.has(key)) return;
140
- seen.add(key);
141
- cants.push({
142
- line: l.n, rule: n, source: 'look', ask: 'cant-check', ruleText: rule,
143
- question: `Your line ${l.n} says "${rule}". I can't check this on the page. Drop it?${cantCheckTail(l.n)}`,
144
- });
145
- });
146
- }
147
- return [...readings, ...cants];
148
- }
149
-
150
- /** @param {import('./pagerules.js').Reading} r @returns {unknown[]} the bounds a reading holds */
151
- const ruleBounds = (r) => (r.op === 'between' ? [r.lo, r.hi] : [r.value]);
152
-
153
93
  /**
154
94
  * More asks than the cap means the job needs a rewrite, not a questionnaire. The code-owned stop words list EVERY ask and its reading as the
155
95
  * suggestion (no extra paid call). A secret in a rule is masked.
@@ -6,13 +6,20 @@
6
6
 
7
7
  /** @typedef {import('./pagerules.js').Dropped} Dropped */
8
8
 
9
+ // borrowed-from: bareloop src/pagedropwords.js@v0.56.0 (3383cce) (the four reasons the block's drops carry, and the sign-twice sentence by `d.other`; FACT_LANGS lives with the facts in src/citedcheck.js)
10
+ import { FACT_LANGS } from './citedcheck.js';
11
+
12
+ /** the two ways a sign listed twice can be used once (v0.56.0 spells the sentence from `d.other`; no other -> "currency", the sentence fwd has always written) */
13
+ const SIGN_TWICE_AS = ['currency', 'unit'];
14
+
9
15
  /** 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
16
  const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
11
17
  'not-on-page': (d) => `"${d.word}" is not written on the page.`,
12
18
  'no-value': (d) => `The page never shows a number right after or right before "${d.word}".`,
19
+ 'reads-no-amount': (d) => `The page never shows an amount next to "${d.word}", so it was not used to write the price.`,
13
20
  'n2': (d) => `"${d.word}" is written more than once inside one line of the page, so one result cannot show it once.`,
14
21
  '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.`,
22
+ 'sign-twice': (d) => `"${d.word}" was listed twice, as a unit and as a currency; it is used once, as the ${SIGN_TWICE_AS.find((kind) => kind === d.other) ?? 'currency'}.`,
16
23
  'r1l': (d) => d.word === d.other
17
24
  ? `"${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
25
  : `"${d.word}" does not show the same amounts as "${d.other}", so it was not used as a second way to write the price.`,
@@ -23,6 +30,9 @@ const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
23
30
  'limit-unit': (d) => `Only the first 10 units are used; "${d.word}" was left out.`,
24
31
  'unit-too-long': (d) => `"${d.word}" is longer than 100 characters, so it was not used.`,
25
32
  'reads-no-result': () => "the price rule could not read a price in the page's results, so it is not checked.",
33
+ 'reads-no-time': (d) => `the page never shows a time right after "${d.other}", so it is not checked.`,
34
+ 'lang-not-on-page': (d) => `the page shows no month name in ${FACT_LANGS[/** @type {keyof typeof FACT_LANGS} */ (d.other ?? '')] ?? d.other}, so the date is not checked.`,
35
+ 'decimal-not-on-page': () => 'the page shows no amount written with a comma before the decimals, so it is not checked.',
26
36
  // borrowed-from: bareloop src/pagedropwords.js@c550dc8 (the phrase dry read's sentence)
27
37
  'phrase-no-result': (d) => `"${d.other}" is on the page but in none of its results, so it is not checked.`,
28
38
  'person-left': () => 'You chose to leave it Not checked.',
package/src/pagedry.js CHANGED
@@ -83,6 +83,31 @@ export async function dryReadMoney(text, facts) {
83
83
  return { facts: kept, dropped, reads, results };
84
84
  }
85
85
 
86
+ // borrowed-from: bareloop src/pagedry.js@v0.57.0 (c18df406) (resultQuotes, phraseInNoResult: 637e76ad)
87
+ /**
88
+ * The page's RESULT LINES: the lines the given money facts read (`moneyResultLines`), each quote once. Empty when no money fact reads a line (the result lines are then unknown).
89
+ * The one owner of "what is a result row" for phrase facts, shared by the dry read below and by the check list's `!` rows (`phraseInNoResult`).
90
+ * @param {string} text @param {KeptFact[]} facts @returns {string[]}
91
+ */
92
+ export function resultQuotes(text, facts) {
93
+ /** @type {Set<string>} */
94
+ const quotes = new Set();
95
+ for (const k of facts) if (k.shape === 'money') for (const r of moneyResultLines(text, k)) quotes.add(r.quote);
96
+ return [...quotes];
97
+ }
98
+
99
+ /**
100
+ * Is this phrase in the page but in NONE of its result lines (the `phrase-no-result` case)? Sync, for a `!` row the check list is about to build.
101
+ * True only when result lines exist and no line holds the words (case and spacing aside, a plain substring: it never refuses a phrase the run's presence check could pass).
102
+ * With no result line known nothing is guessed (false).
103
+ * @param {string} text @param {KeptFact[]} moneyFacts the line's money facts @param {string} words @returns {boolean}
104
+ */
105
+ export function phraseInNoResult(text, moneyFacts, words) {
106
+ const rows = resultQuotes(text, moneyFacts);
107
+ const w = words.replace(/\s+/g, ' ').trim().toLowerCase();
108
+ return rows.length > 0 && w !== '' && !rows.some((q) => q.replace(/\s+/g, ' ').toLowerCase().includes(w));
109
+ }
110
+
86
111
  /**
87
112
  * 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
88
113
  * 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
@@ -94,9 +119,7 @@ export async function dryReadMoney(text, facts) {
94
119
  * @returns {Promise<{facts: KeptFact[], dropped: Dropped[], reads: Record<string, number>}>} `reads` = result lines that said the phrase, per fact name
95
120
  */
96
121
  export async function dryReadPhrases(text, facts) {
97
- /** @type {Set<string>} */
98
- const quotes = new Set();
99
- for (const k of facts) if (k.shape === 'money') for (const r of moneyResultLines(text, k)) quotes.add(r.quote);
122
+ const quotes = resultQuotes(text, facts);
100
123
  /** @type {KeptFact[]} */
101
124
  const kept = [];
102
125
  /** @type {Dropped[]} */
@@ -104,7 +127,7 @@ export async function dryReadPhrases(text, facts) {
104
127
  /** @type {Record<string, number>} */
105
128
  const reads = {};
106
129
  for (const k of facts) {
107
- if (k.shape !== 'phrase' || quotes.size === 0 || !k.words.length) { kept.push(k); continue; }
130
+ if (k.shape !== 'phrase' || quotes.length === 0 || !k.words.length) { kept.push(k); continue; }
108
131
  const part = { source: SOURCE, facts: factsOfLook({ name: CLAIM, shape: 'phrase', words: [k.words[0]] }) };
109
132
  let n = 0;
110
133
  for (const quote of quotes) {
package/src/pagerules.js CHANGED
@@ -162,6 +162,19 @@ const CURRENCY_SYMBOLS = ['$', '€', '£'];
162
162
  /** the shapes that read a value after a label */
163
163
  const VALUE_SHAPES = ['money', 'time', 'number'];
164
164
 
165
+ // borrowed-from: bareloop src/pagerules.js@v0.57.0 (c18df406) (withColon, 1583d563)
166
+ /**
167
+ * The ONE owner of a label's separator: the label as the page writes it. The run's checker reads a value right after the signed label, so a page that
168
+ * writes "Departure time: 10:24 AM." can only be read by the label "Departure time:". When EVERY place the page holds the label has a colon right after
169
+ * it, the label is signed with that colon; one bare place leaves it as the look gave it. A plain count of the page's own text, no pattern.
170
+ * @param {string} text the frozen page text @param {string} label a label as normLabel leaves it @returns {string}
171
+ */
172
+ export function withColon(text, label) {
173
+ if (label.endsWith(':')) return label;
174
+ const n = countExact(text, label);
175
+ return n >= 1 && countExact(text, `${label}:`) === n ? `${label}:` : label;
176
+ }
177
+
165
178
  /**
166
179
  * Apply the rules to the AI's map over one saved page. Returns the kept facts and, for everything a rule removed, one `dropped` entry.
167
180
  * The order of the rules is the POC's (apply-v3.mjs): found-on-page, then the rules that read the page. A place is read as a phrase.
@@ -208,9 +221,12 @@ export function applyPageRules(text, mapping, jobLines) {
208
221
  const asListed = [];
209
222
  /** U1: labels the page writes after the number */
210
223
  const moved = [];
211
- for (const w0 of words) {
212
- const w = normLabel(w0);
213
- if (!w) continue;
224
+ for (const w00 of words) {
225
+ const base = normLabel(w00);
226
+ if (!base) continue;
227
+ // a label the page always writes with a colon right after it ("Departure time: 10:24 AM.") is signed as the page writes it (run mwgsl7zx)
228
+ const w = withColon(text, base);
229
+ const w0 = w === base ? w00 : w;
214
230
  if (countExact(text, w) < 1) { asListed.push(w0); drop(f, w0, 'not-on-page'); continue; }
215
231
  if (amount) {
216
232
  const { B, A } = beforeAfter(lines, w);