fwdloop 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/bin/fwdloop +85 -34
  2. package/package.json +4 -3
  3. package/src/audit-fold.js +5 -1
  4. package/src/authoring.js +32 -6
  5. package/src/checked.js +18 -1
  6. package/src/cited-record.js +138 -0
  7. package/src/cited-source.js +49 -0
  8. package/src/citedcheck.js +306 -0
  9. package/src/citedwords.js +197 -0
  10. package/src/closers.js +56 -7
  11. package/src/ctx-tools.js +2 -14
  12. package/src/declaration.js +85 -5
  13. package/src/diary.js +2 -2
  14. package/src/docx.js +16 -2
  15. package/src/draft-steps.js +1 -1
  16. package/src/drafter.js +292 -25
  17. package/src/flow.js +33 -7
  18. package/src/flowmodel.js +21 -0
  19. package/src/input-facts.js +20 -3
  20. package/src/model-step.js +30 -5
  21. package/src/pageask.js +136 -0
  22. package/src/pagebits.js +107 -0
  23. package/src/pagedropwords.js +171 -0
  24. package/src/pagedry.js +120 -0
  25. package/src/pagefetch.js +164 -0
  26. package/src/pagelook.js +155 -0
  27. package/src/pagemap.js +55 -0
  28. package/src/pageplace.js +103 -0
  29. package/src/pagerules.js +318 -0
  30. package/src/panel/author.js +41 -20
  31. package/src/panel/authorcard.js +11 -1
  32. package/src/panel/authorflows.js +21 -15
  33. package/src/panel/authorstart.js +2 -4
  34. package/src/panel/authortrigger.js +14 -4
  35. package/src/panel/data.js +83 -2
  36. package/src/panel/index.html +279 -12
  37. package/src/panel/result.js +295 -0
  38. package/src/panel/server.js +27 -3
  39. package/src/primitives.js +2 -3
  40. package/src/provider.js +5 -2
  41. package/src/redact.js +17 -0
  42. package/src/runner.js +83 -12
  43. package/src/schedule.js +3 -3
  44. package/src/setup.js +16 -1
  45. package/src/sheetfind.js +50 -0
  46. package/src/sheetlook.js +157 -0
  47. package/src/signed-text.js +11 -1
  48. package/src/thinking.js +1 -1
  49. package/src/try-checks.js +6 -0
  50. package/src/types.js +3 -2
  51. package/types/authoring.d.ts +19 -2
  52. package/types/checked.d.ts +10 -0
  53. package/types/cited-record.d.ts +21 -0
  54. package/types/cited-source.d.ts +18 -0
  55. package/types/citedcheck.d.ts +95 -0
  56. package/types/citedwords.d.ts +97 -0
  57. package/types/closers.d.ts +55 -3
  58. package/types/ctx-tools.d.ts +0 -1
  59. package/types/declaration.d.ts +15 -1
  60. package/types/docx.d.ts +14 -0
  61. package/types/drafter.d.ts +244 -2
  62. package/types/flow.d.ts +21 -0
  63. package/types/flowmodel.d.ts +15 -0
  64. package/types/input-facts.d.ts +12 -2
  65. package/types/model-step.d.ts +35 -3
  66. package/types/pageask.d.ts +75 -0
  67. package/types/pagebits.d.ts +32 -0
  68. package/types/pagedropwords.d.ts +40 -0
  69. package/types/pagedry.d.ts +38 -0
  70. package/types/pagefetch.d.ts +86 -0
  71. package/types/pagelook.d.ts +75 -0
  72. package/types/pagemap.d.ts +31 -0
  73. package/types/pageplace.d.ts +22 -0
  74. package/types/pagerules.d.ts +86 -0
  75. package/types/panel/authorcard.d.ts +2 -0
  76. package/types/panel/authorflows.d.ts +2 -0
  77. package/types/panel/data.d.ts +26 -0
  78. package/types/panel/result.d.ts +156 -0
  79. package/types/provider.d.ts +3 -1
  80. package/types/redact.d.ts +1 -0
  81. package/types/runner.d.ts +156 -7
  82. package/types/schedule.d.ts +0 -11
  83. package/types/setup.d.ts +13 -0
  84. package/types/sheetfind.d.ts +46 -0
  85. package/types/sheetlook.d.ts +120 -0
  86. package/types/thinking.d.ts +1 -1
  87. package/types/types.d.ts +11 -3
package/src/model-step.js CHANGED
@@ -30,6 +30,8 @@ import { GateRefusal } from './primitives.js';
30
30
  import { appendCall, appendTool, nextRound } from './diary.js';
31
31
  import { ConfigError } from './config.js';
32
32
  import { worstThinkingStatus } from './thinking.js';
33
+ import { citedBrief } from './citedcheck.js';
34
+ import { citeForms } from './closers.js';
33
35
 
34
36
  import {
35
37
  makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
@@ -98,7 +100,7 @@ const GREEN_SCHEMA = Object.freeze({
98
100
  type: 'object',
99
101
  additionalProperties: {
100
102
  type: 'object',
101
- properties: { value: {}, cite: { type: 'string' } },
103
+ properties: { value: {}, cite: { type: 'string', description: `Where the value comes from: ${citeForms()}.` } },
102
104
  required: ['value', 'cite'],
103
105
  },
104
106
  },
@@ -133,11 +135,32 @@ const HITL_SCHEMA = Object.freeze({
133
135
  additionalProperties: true,
134
136
  });
135
137
 
138
+ // M10 am7 item 3: a green step that quotes a saved web page (its close carries `cited`) answers with the quotes it found, each with the values it read from
139
+ // that quote. The check (src/closers.js closeCited) reads exactly this; nothing else in the artifact is trusted.
140
+ const CITED_SCHEMA = Object.freeze({
141
+ type: 'object',
142
+ properties: {
143
+ results: {
144
+ type: 'array',
145
+ items: {
146
+ type: 'object',
147
+ properties: { quote: { type: 'string' }, values: { type: 'object' } },
148
+ required: ['quote', 'values'],
149
+ },
150
+ },
151
+ ...DONE_PROPS,
152
+ },
153
+ required: ['results', 'done'],
154
+ additionalProperties: false,
155
+ });
156
+
136
157
  /**
137
158
  * Build the `emit_artifact` tool schema from a step's declared close CLASS
138
- * only. `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`.
159
+ * only (plus, for a green step that quotes a saved page, the form of its answer).
160
+ * `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`; `cited` is true for that green step.
139
161
  */
140
- export function buildEmitArtifactSchema(stepClass) {
162
+ export function buildEmitArtifactSchema(stepClass, cited = false) {
163
+ if (stepClass === 'green' && cited) return CITED_SCHEMA;
141
164
  if (stepClass === 'green') return GREEN_SCHEMA;
142
165
  if (stepClass === 'softgreen') return SOFTGREEN_SCHEMA;
143
166
  return HITL_SCHEMA;
@@ -288,7 +311,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
288
311
  * @param {{in:number,out:number}} [opts.rates]
289
312
  * @param {string} [opts.modelId]
290
313
  * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
291
- * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
314
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, cited?:any, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
292
315
  */
293
316
  export function makeLiveModelStep({
294
317
  slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
@@ -329,7 +352,7 @@ export function makeLiveModelStep({
329
352
  const runDir = dirname(spendPath);
330
353
  const diaryStep = stepMeta.step ?? null;
331
354
  const diaryTry = typeof stepMeta.attempt === 'number' ? stepMeta.attempt : null;
332
- const toolSchema = buildEmitArtifactSchema(stepMeta.class);
355
+ const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited));
333
356
  const thinkingMode = stepMeta.thinkingMode === 'on' || stepMeta.thinkingMode === 'off' ? stepMeta.thinkingMode : null;
334
357
  const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
335
358
  + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
@@ -338,6 +361,8 @@ export function makeLiveModelStep({
338
361
  goal: executorContext.goal,
339
362
  reads: executorContext.reads,
340
363
  gap: executorContext.gap,
364
+ // M10 am7 item 3: a step that quotes a saved page is told the form of its answer and what each result must hold
365
+ ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: citedBrief(stepMeta.cited) } : {}),
341
366
  });
342
367
  const messages = [
343
368
  { role: 'system', content: systemPrompt },
package/src/pageask.js ADDED
@@ -0,0 +1,136 @@
1
+ // borrowed-from: bareloop src/pagemap.js@0a34846 (DROP_IT, isDropIt, isAgree, readingQuestion, readingOfQuestion, askableFromLook, ruleBounds, tooManyAsksText)
2
+ // borrowed-from: bareloop src/facts.js@0a34846 (ruleWords, sayBound, moneyAs)
3
+ // 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
4
+ // 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
5
+ // 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
6
+ // agree / yes (code's reading), your own words, and, for a can't-check ask only, "drop it" (am2 item 2).
7
+ // Every rule is one of three kinds:
8
+ // PAGE: a kept page word carries it: no ask.
9
+ // 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
10
+ // reading is NOT in the words the person wrote; a bound they wrote themselves is theirs and nothing is asked.
11
+ // CAN'T CHECK: no kept fact carries it.
12
+ // Throws away: a fact's name, words and source (only its reading and the rule it serves are used).
13
+ import { redactSecrets } from './redact.js';
14
+ import { lineRules, boundInWords, wordsSaidOn } from './pagebits.js';
15
+ import { validReading } from './pagerules.js';
16
+
17
+ /** the most asks before drafting; more than this is a job to rewrite, not a questionnaire (am1) */
18
+ export const MAX_LOOK_ASKS = 3;
19
+ /** the answer that drops a `~` rule the page cannot check: the person types it (any case, a closing full stop allowed) */
20
+ export const DROP_IT = 'drop it';
21
+ /** @param {unknown} text @returns {boolean} */
22
+ export const isDropIt = (text) => String(text ?? '').trim().replace(/\.$/, '').toLowerCase() === DROP_IT;
23
+ /** the answers that accept the code's reading of a rule; anything else the person types is their own reading */
24
+ const AGREE_WORDS = ['agree', 'yes'];
25
+ /** @param {unknown} text @returns {boolean} */
26
+ export const isAgree = (text) => AGREE_WORDS.includes(String(text ?? '').trim().replace(/[.!]$/, '').toLowerCase());
27
+
28
+ /** @typedef {{line: number, rule: number, source: 'look', question: string, ask: 'reading'|'cant-check', ruleText: string, reading?: string}} LookAsk
29
+ * `reading` = the plain words an `agree` writes as a `~` rule (a reading ask only) */
30
+
31
+ /** @param {unknown} n @param {string} shape @param {any} f @returns {string} one bound, as the person would say it */
32
+ function sayBound(n, shape, f) {
33
+ if (shape === 'money') return moneyAs(f, /** @type {string|number} */ (n), false);
34
+ return String(n);
35
+ }
36
+ const asList = (/** @type {unknown} */ v) => (Array.isArray(v) ? v.map(String) : (typeof v === 'string' ? [v] : []));
37
+ /**
38
+ * One amount of a money fact in the fact's OWN forms, never a hardcoded sign: `symbolFirst` puts the currency sign before the amount when the fact has one.
39
+ * @param {any} f @param {string|number} n @param {boolean} symbolFirst @returns {string}
40
+ */
41
+ export function moneyAs(f, n, symbolFirst) {
42
+ const cur = asList(f.currency)[0];
43
+ const uni = asList(f.unit)[0];
44
+ if (symbolFirst) return cur !== undefined ? `${cur}${n}` : `${n} ${uni}`;
45
+ return uni !== undefined ? `${n} ${uni}` : `${cur}${n}`;
46
+ }
47
+ /** @param {any} f a fact with a rule @returns {string} the rule in words, e.g. "under 450 US dollars" */
48
+ export function ruleWords(f) {
49
+ const r = f.rule;
50
+ return r.op === 'between' ? `between ${sayBound(r.lo, f.shape, f)} and ${sayBound(r.hi, f.shape, f)}`
51
+ : `${{ lt: 'under', lte: 'at most', gt: 'over', gte: 'at least' }[/** @type {'lt'|'lte'|'gt'|'gte'} */ (r.op)]} ${sayBound(r.value, f.shape, f)}`;
52
+ }
53
+
54
+ /** the words of a reading ask: the ONE spelling, and {@link readingOfQuestion} reads it back (the Result tab's "(you confirmed)") */
55
+ const READING_HEAD = ' I read it as: ';
56
+ const READING_TAIL = '. Agree? Answer "agree"';
57
+ /** @param {number} n @param {string} rule @param {string} reading @returns {string} */
58
+ const readingQuestion = (n, rule, reading) => `Your line ${n} says "${rule}".${READING_HEAD}${reading}${READING_TAIL}, or type your own reading (your answer is added as a new ~ rule on line ${n}).`;
59
+ /** @param {unknown} q a recorded question @returns {string|null} the reading a reading ask proposed, or null when it was another kind of question */
60
+ export function readingOfQuestion(q) {
61
+ const s = String(q ?? '');
62
+ const a = s.indexOf(READING_HEAD);
63
+ const b = s.indexOf(READING_TAIL);
64
+ return a >= 0 && b > a ? s.slice(a + READING_HEAD.length, b) : null;
65
+ }
66
+
67
+ /**
68
+ * 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
69
+ * asks, each in line order. The caller applies the cap and the answer gate.
70
+ * @param {{facts?: {line: number, forRule?: number, name?: string, shape?: string, unit?: string[], currency?: string[], reading?: import('./pagerules.js').Reading}[]}|null|undefined} look
71
+ * @param {{n: number, text?: string, rule?: string, rules?: string[]}[]|null|undefined} jobLines
72
+ * @returns {LookAsk[]}
73
+ */
74
+ export function askableFromLook(look, jobLines) {
75
+ const facts = Array.isArray(look?.facts) ? look.facts : [];
76
+ /** @type {LookAsk[]} */
77
+ const readings = [];
78
+ /** @type {LookAsk[]} */
79
+ const cants = [];
80
+ /** @type {Set<string>} */
81
+ const seen = new Set();
82
+ for (const l of Array.isArray(jobLines) ? jobLines : []) {
83
+ lineRules(l).forEach((rule, k) => {
84
+ const n = k + 1;
85
+ const key = `${l.n}\u0000${rule.trim().toLowerCase()}`;
86
+ const tied = facts.filter((f) => f.line === l.n && f.forRule === n);
87
+ if (tied.length > 0) {
88
+ const said = wordsSaidOn(l);
89
+ const f = tied.find((x) => x.reading && validReading(x.shape, x.reading) && ruleBounds(x.reading).some((b) => !boundInWords(b, said)));
90
+ if (f === undefined || seen.has(key)) return;
91
+ seen.add(key);
92
+ const reading = `${f.name} ${ruleWords({ shape: f.shape, unit: f.unit, currency: f.currency, rule: f.reading })}`;
93
+ readings.push({
94
+ line: l.n, rule: n, source: 'look', ask: 'reading', ruleText: rule, reading,
95
+ question: readingQuestion(l.n, rule, reading),
96
+ });
97
+ return;
98
+ }
99
+ if (seen.has(key)) return;
100
+ seen.add(key);
101
+ cants.push({
102
+ line: l.n, rule: n, source: 'look', ask: 'cant-check', ruleText: rule,
103
+ question: `Your line ${l.n} says "${rule}". I can't check this on the page. Drop it? Answer "${DROP_IT}", or type how to check it (your answer is added as a new ~ rule on line ${l.n}).`,
104
+ });
105
+ });
106
+ }
107
+ return [...readings, ...cants];
108
+ }
109
+
110
+ /** @param {import('./pagerules.js').Reading} r @returns {unknown[]} the bounds a reading holds */
111
+ const ruleBounds = (r) => (r.op === 'between' ? [r.lo, r.hi] : [r.value]);
112
+
113
+ /**
114
+ * 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
115
+ * suggestion (no extra paid call). A secret in a rule is masked.
116
+ * @param {{line: number, ruleText: string, reading?: string}[]} asks @returns {string}
117
+ */
118
+ export function tooManyAsksText(asks) {
119
+ const list = asks.map((a) => `line ${a.line} "${a.ruleText}" → ${a.reading ?? "I can't check this on the page"}`).join('; ');
120
+ return redactSecrets(`Your job has ${asks.length} rules I can't check or had to guess. Please rewrite it so each one says what to look for. My readings: ${list}.`);
121
+ }
122
+
123
+ /**
124
+ * What a typed answer to a look ask does, the ONE place that decides (the panel's answer route, the setup record and the Result tab all read it).
125
+ * `agree` / `yes` to a reading ask takes the code's reading; `drop it` to a can't-check ask leaves the rule Not checked (no `~` line); anything else is the
126
+ * person's own words, taken word for word with newlines folded to spaces. A question that is not a look ask is never changed: its answer is its rule.
127
+ * @param {{source?: string, ask?: string, proposal?: string|null}} q @param {unknown} typed
128
+ * @returns {{rule: string|null, left: boolean}} `rule` = the words written as a new `~` rule (null when the rule is left Not checked)
129
+ */
130
+ export function ruleOfAnswer(q, typed) {
131
+ const text = String(typed ?? '').replace(/\s*\n\s*/g, ' ').trim();
132
+ if (q.source !== 'look') return { rule: text, left: false };
133
+ if (q.ask === 'reading' && typeof q.proposal === 'string' && isAgree(text)) return { rule: q.proposal, left: false };
134
+ if (q.ask === 'cant-check' && isDropIt(text)) return { rule: null, left: true };
135
+ return { rule: text, left: false };
136
+ }
@@ -0,0 +1,107 @@
1
+ // The small pieces of bareloop's facts.js, factwords.js, labelscan.js and rubricstep.js that the copied page rules need. Each piece is a copy;
2
+ // the rest of those files (bareguard-facing fact checks, label scans, the rubric step) is not wanted here and is not copied.
3
+
4
+ // borrowed-from: bareloop src/facts.js@b7d3306 (FACT_OPS, MAX_CURRENCIES, MAX_UNITS, MAX_UNIT_CHARS, asList, boundOk)
5
+ export const FACT_OPS = Object.freeze(['lt', 'lte', 'gt', 'gte', 'between']);
6
+ export const MAX_CURRENCIES = 3;
7
+ export const MAX_UNITS = 10;
8
+ export const MAX_UNIT_CHARS = 100;
9
+ export const asList = (/** @type {unknown} */ v) => (Array.isArray(v) ? v.map(String) : (typeof v === 'string' ? [v] : []));
10
+ export const boundOk = (/** @type {string} */ shape, /** @type {unknown} */ v) => (shape === 'number' || shape === 'money' ? typeof v === 'number' && Number.isFinite(v) : typeof v === 'string' && v !== '');
11
+
12
+ // borrowed-from: bareloop src/factwords.js@18ab77c (squash, loose, countExact, countPhrase - rewritten without a built pattern, same count, see test/m10-pagebits.test.js)
13
+ const WS = /[\s   ]+/g;
14
+ /** a letter or a digit (any script); the character right at the start of the string tested */
15
+ const WORD_CHAR = /^[\p{L}\p{N}]/u;
16
+
17
+ /** @param {string} t @returns {string} the source with every run of white space made one space */
18
+ export const squash = (t) => String(t ?? '').replace(WS, ' ');
19
+ /** @param {string} t @returns {string} lower case, markdown marks dropped, white space squashed - how a phrase or unit is compared */
20
+ const loose = (t) => squash(t).replace(/[*_`]/g, '').trim().toLowerCase();
21
+
22
+ /**
23
+ * How many times exact words occur in a source, white space blind. Zero for empty words.
24
+ * @param {string} source the raw source text @param {string} words
25
+ * @returns {number}
26
+ */
27
+ export function countExact(source, words) {
28
+ const w = squash(words).trim();
29
+ if (w === '') return 0;
30
+ const hay = squash(source);
31
+ let n = 0;
32
+ for (let i = hay.indexOf(w); i !== -1; i = hay.indexOf(w, i + w.length)) n += 1;
33
+ return n;
34
+ }
35
+
36
+ /**
37
+ * How many times a phrase or unit occurs as WHOLE words, case and spacing aside ("SFO" is not found inside "sfocus").
38
+ * @param {string} source @param {string} words @returns {number}
39
+ */
40
+ export function countPhrase(source, words) {
41
+ const w = loose(words);
42
+ if (w === '') return 0;
43
+ const hay = loose(source);
44
+ // The original is one dynamic RegExp, `(^|[^\p{L}\p{N}])<w>(?=$|[^\p{L}\p{N}])` over every match; this repo bans built patterns in src/, so the same count is
45
+ // taken by hand: a hit has a non-letter-non-digit (or the start) before it and after it, and a hit may not reuse the character the last hit's end left behind.
46
+ let n = 0;
47
+ let consumedTo = 0;
48
+ for (let i = hay.indexOf(w); i !== -1; i = hay.indexOf(w, i + 1)) {
49
+ const prev = i === 0 ? null : /(.)$/su.exec(hay.slice(Math.max(0, i - 2), i))?.[1] ?? null;
50
+ if (prev !== null && (WORD_CHAR.test(prev) || i - prev.length < consumedTo)) continue;
51
+ if (WORD_CHAR.test(hay.slice(i + w.length, i + w.length + 2))) continue;
52
+ n += 1;
53
+ consumedTo = i + w.length;
54
+ i += w.length - 1;
55
+ }
56
+ return n;
57
+ }
58
+
59
+ /**
60
+ * The forms a word may be written in (hamr's ruling 2026-10-21, "a simple plural matches"): the word, its plural and its singular, case aside. A simple plural is
61
+ * `s`, `es` after s/x/z/ch/sh, or `ies` for a consonant + `y`; nothing wider ("amounted" is not "amount"). The ONE place a word is allowed a plural: the
62
+ * sheet look's own-word check, the column finder and the .docx heading match all take their forms from here. A number, a phrase a guardrail names or a
63
+ * money value is never widened by it.
64
+ * @param {string} word @returns {string[]}
65
+ */
66
+ export function wordForms(word) {
67
+ const w = loose(word);
68
+ if (w === '') return [];
69
+ const forms = new Set([w]);
70
+ if (/[^aeiou]y$/.test(w)) forms.add(`${w.slice(0, -1)}ies`);
71
+ else if (/(s|x|z|ch|sh)$/.test(w)) forms.add(`${w}es`);
72
+ else forms.add(`${w}s`);
73
+ if (w.endsWith('ies') && w.length > 4) forms.add(`${w.slice(0, -3)}y`);
74
+ if (/(s|x|z|ch|sh)es$/.test(w)) forms.add(w.slice(0, -2));
75
+ if (w.endsWith('s') && !w.endsWith('ss') && w.length > 2) forms.add(w.slice(0, -1));
76
+ return [...forms];
77
+ }
78
+
79
+ // borrowed-from: bareloop src/labelscan.js@dda9c8f (normLabel)
80
+ /** @param {string} t @returns {string} white space made one space, quote marks at the edges dropped, trimmed - how a label is compared */
81
+ export function normLabel(t) {
82
+ return String(t ?? '').replace(WS, ' ').trim().replace(/^["'“”]+|["'“”]+$/g, '').trim();
83
+ }
84
+
85
+ // borrowed-from: bareloop src/rubricstep.js@2f93962 (lineRules, boundSpellings, boundInWords, wordsSaidOn)
86
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
87
+ /** the ~ rules of one job line, one string each (`rules` when the line has the array, else the joined `rule` split on "; ") @param {any} l @returns {string[]} */
88
+ export function lineRules(l) {
89
+ if (isRec(l) && Array.isArray(l.rules)) return l.rules.filter((/** @type {unknown} */ r) => typeof r === 'string' && r);
90
+ return isRec(l) && typeof l.rule === 'string' && l.rule ? l.rule.split('; ').filter(Boolean) : [];
91
+ }
92
+
93
+ /** @param {unknown} b @returns {string[]} the spellings a rule bound can have in the person's own words */
94
+ const boundSpellings = (b) => {
95
+ const s = String(b);
96
+ return [s, s.replace(/^0+(?=\d)/, ''), s.replace(/\.0+$/, '')];
97
+ };
98
+
99
+ /**
100
+ * Is this rule bound in the words the person wrote? The ONE test for "a number the AI made" (`rubric-fact-unmarked`, the L3 settle, and
101
+ * the early ask of PRD v1.107 Part 5b all read it; never a second spelling).
102
+ * @param {unknown} b @param {string} said @returns {boolean}
103
+ */
104
+ export const boundInWords = (b, said) => boundSpellings(b).some((sp) => said.includes(sp));
105
+
106
+ /** @param {any} jl one job line @returns {string} the words the person wrote on it: the line and its `~` rules */
107
+ export const wordsSaidOn = (jl) => `${jl.text ?? ''} ${lineRules(jl).join(' ')}`;
@@ -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
+ }