bareloop 0.48.0 → 0.50.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/src/pagerules.js CHANGED
@@ -10,11 +10,11 @@ import { normLabel } from './labelscan.js';
10
10
 
11
11
  /**
12
12
  * @typedef {{op: string, value?: string|number, lo?: string|number, hi?: string|number}} Reading what a `~` rule means as a limit (PRD v1.107 Part 5b): the same shape as a signed fact rule
13
- * @typedef {{name: string, from?: string, shape: string, words?: string[], currency?: string[], unit?: string[], reading?: Reading}} MapFact the AI's map, one fact
13
+ * @typedef {{name: string, from?: string, shape: string, words?: string[], currency?: string[], unit?: string[], reading?: Reading, lang?: string, decimal?: string}} MapFact the AI's map, one fact
14
14
  * @typedef {{facts: MapFact[]}} PageMap
15
- * @typedef {{line: number, name: string, shape: string, from: string, words: string[], unit?: string[], currency?: string[], forRule?: number, reading?: Reading}} KeptFact
15
+ * @typedef {{line: number, name: string, shape: string, from: string, words: string[], unit?: string[], currency?: string[], forRule?: number, reading?: Reading, lang?: string, decimal?: string}} KeptFact
16
16
  * `words` = what the page proves: the labels of a money/number/time fact, or the alternative phrases of a phrase fact (a place is a phrase)
17
- * @typedef {{line: number, rule?: number, fact: string, word?: string, reason: string, other?: string}} Dropped `other` = what the drop is compared to: the first label (R1), the primary form (R1L), the fact it would have repeated (S1), the phrase it looked for (phrase-no-result)
17
+ * @typedef {{line: number, rule?: number, fact: string, word?: string, reason: string, other?: string}} Dropped `other` = what the drop is compared to: the first label (R1), the primary form (R1L), the box a sign listed twice was kept in (sign-twice: unit or currency), the fact it would have repeated (S1), the phrase it looked for (phrase-no-result)
18
18
  */
19
19
 
20
20
  /** @param {unknown} v @returns {v is Record<string, any>} */
@@ -75,6 +75,8 @@ const READ = {
75
75
  money: /^\s*[$€£]?\s*(\d[\d,]*(?:\.\d+)?)/,
76
76
  time: /^\s*(\d{1,2}:\d{2}[\s\u202f\u00a0]?[AaPp][Mm])/,
77
77
  number: /^\s*(\d[\d,]*(?:\.\d+)?)/,
78
+ // R1 same-value only: the date words right after a label, up to the 4-digit year (a day, a month name, a year; or ISO)
79
+ date: /^\s*(\d{4}-\d{2}-\d{2}|\S+(?:\s\S+){0,3}\s\d{4})(?!\d)/,
78
80
  };
79
81
 
80
82
  /**
@@ -123,6 +125,21 @@ export function numberAtEnd(s) {
123
125
  const p = firstDigit(e);
124
126
  return p === -1 ? undefined : s.slice(p, e);
125
127
  }
128
+ /** a number as a page writes it where the decimal mark is a comma: groups of three joined by "." or a space (or none), then an optional comma and decimals */
129
+ export const NUM_COMMA = '\\d{1,3}(?:[. ]\\d{3})+(?:,\\d+)?|\\d+(?:,\\d+)?';
130
+ /**
131
+ * {@link numberAtEnd} for a comma-decimal page: the number written at the very end of `s` (only whitespace after it), as the page writes it
132
+ * ("1.057,65", "1 089", "48,49"). Only the last 24 characters are read (no price is longer), so a long run of digits cannot cost more than that.
133
+ * @param {string} s @returns {string|undefined}
134
+ */
135
+ export function numberAtEndComma(s) {
136
+ const t = s.trimEnd();
137
+ const tail = t.slice(-24);
138
+ const m = new RegExp(`(?<![\\d,.])(?:${NUM_COMMA})$`).exec(tail);
139
+ // a match that starts the tail while the text goes on to the left of it may be the end of a longer run: not a number of its own
140
+ if (!m || (m.index === 0 && t.length > tail.length && /[\d,.]/.test(t[t.length - tail.length - 1]))) return undefined;
141
+ return m[0];
142
+ }
126
143
  const AFTER = new RegExp(`^\\s*(?:[$€£]\\s*)?(${NUM})`);
127
144
  const AFTER_CUR = new RegExp(`^\\s*(${NUM})`);
128
145
  const stripCommas = (/** @type {string} */ s) => s.replace(/,/g, '');
@@ -159,8 +176,123 @@ const ORDINALS = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seven
159
176
 
160
177
  /** the symbols a currency may be (src/facts.js); a code like "EUR" is a word read after the number, so it is a unit */
161
178
  const CURRENCY_SYMBOLS = ['$', '€', '£'];
179
+
180
+ /**
181
+ * The page FORMS of a currency sign in `lines`: `glued` = right after a number ("29,99€"), `spaced` = after a number and one space ("29,99 €"),
182
+ * `before` = in front of a number it does not itself follow ("€399", "€ 399").
183
+ * @param {string[]} lines @param {string} sign @returns {{glued: boolean, spaced: boolean, before: boolean}}
184
+ */
185
+ function signForms(lines, sign) {
186
+ let glued = false; let spaced = false; let before = false;
187
+ for (const [l, i] of occs(lines, sign)) {
188
+ const head = l.slice(0, i);
189
+ if (/\d$/.test(head)) glued = true;
190
+ else if (/\d $/.test(head)) spaced = true;
191
+ else if (/^ ?\d/.test(l.slice(i + sign.length))) before = true;
192
+ }
193
+ return { glued, spaced, before };
194
+ }
195
+ /** the char codes of the digits and of the "." and "," a number is written with */
196
+ const isDigitCode = (/** @type {number} */ c) => c >= 48 && c <= 57;
197
+ const isMarkCode = (/** @type {number} */ c) => c === 46 || c === 44;
198
+ /**
199
+ * The number that ends a string: its last run of digits, "." and ",", from the run's first digit (undefined when the run holds no digit). One
200
+ * backward scan, the linear form of /\d[\d.,]*$/ (that one re-scans a long digit run from every digit).
201
+ * @param {string} s @returns {string | undefined}
202
+ */
203
+ function numberBefore(s) {
204
+ let j = s.length;
205
+ while (j > 0 && (isDigitCode(s.charCodeAt(j - 1)) || isMarkCode(s.charCodeAt(j - 1)))) j--;
206
+ while (j < s.length && isMarkCode(s.charCodeAt(j))) j++;
207
+ return j < s.length ? s.slice(j) : undefined;
208
+ }
209
+ /** a number without the "." and "," marks that end it; the linear form of .replace(/[.,]+$/, '') (that one is quadratic on a long run of marks before a digit) @param {string | undefined} n */
210
+ function trimMarks(n) {
211
+ if (n === undefined) return undefined;
212
+ let e = n.length;
213
+ while (e > 0 && isMarkCode(n.charCodeAt(e - 1))) e--;
214
+ return n.slice(0, e);
215
+ }
216
+ /**
217
+ * How the page writes the decimals of the amounts a money fact's signs touch (a sign right after a number, spaced or glued, or right before one).
218
+ * A CLEAR comma amount ends in a comma and exactly two digits ("1.058,47", "17,00"), a CLEAR dot amount in a dot and exactly two ("29.99"); a comma or
219
+ * dot and exactly three digits ("1,299", "1.299") is ambiguous and counts as neither. Only one kind seen = that mark; both or neither = undefined.
220
+ * @param {string[]} lines @param {string[]} signs @returns {',' | '.' | undefined}
221
+ */
222
+ function pageDecimal(lines, signs) {
223
+ let comma = false; let dot = false;
224
+ for (const sgn of signs) {
225
+ for (const [l, i] of occs(lines, sgn)) {
226
+ const before = numberBefore(l.slice(0, i).replace(/ $/, ''));
227
+ const after = trimMarks(/^ ?(\d[\d.,]*)/.exec(l.slice(i + sgn.length))?.[1]);
228
+ for (const n of [before, after]) {
229
+ if (n === undefined) continue;
230
+ if (/,\d{2}$/.test(n)) comma = true;
231
+ else if (/\.\d{2}$/.test(n)) dot = true;
232
+ }
233
+ }
234
+ }
235
+ return comma === dot ? undefined : comma ? ',' : '.';
236
+ }
162
237
  /** the shapes that read a value after a label */
163
- const VALUE_SHAPES = ['money', 'time', 'number'];
238
+ const VALUE_SHAPES = ['money', 'time', 'number', 'date'];
239
+
240
+ /** the full month names of each language a date may be signed in (bareguard 0.27 reads these and short forms; one full name on the page proves the language is the page's) */
241
+ const MONTHS_FULL = /** @type {Record<string, string[]>} */ ({
242
+ en: ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'],
243
+ de: ['januar', 'februar', 'märz', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'dezember'],
244
+ fr: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
245
+ es: ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'],
246
+ it: ['gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'],
247
+ pt: ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'],
248
+ nl: ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
249
+ });
250
+ /**
251
+ * Does the text hold a comma-decimal amount: a number that stands alone (no digit, comma or point before or after it), its whole part one run of
252
+ * digits or groups of three joined by "." or a space, then a comma and one or two decimals. "133,330 chars" (a thousands-grouped count) is not one.
253
+ * The linear form of /(?<![\d,.])\d{1,3}(?:[. ]\d{3})*,\d{1,2}(?![\d,]|\.\d)|(?<![\d,.])\d+,\d{1,2}(?![\d,]|\.\d)/ (that one re-scans a long
254
+ * run of groups from every group). A start is a digit with no digit, comma or point before it; its digit run is the whole part, or the first group
255
+ * when the run is up to three digits and groups of three follow, and only the end of that chain can carry the comma.
256
+ * @param {string} s @returns {boolean}
257
+ */
258
+ function hasCommaDecimal(s) {
259
+ const n = s.length;
260
+ const digitsAt = (/** @type {number} */ q) => { let e = q; while (e < n && isDigitCode(s.charCodeAt(e))) e++; return e; };
261
+ const decimals = (/** @type {number} */ q) => {
262
+ if (s[q] !== ',') return false;
263
+ let e = q + 1;
264
+ while (e < q + 4 && isDigitCode(s.charCodeAt(e))) e++;
265
+ if (e - q - 1 < 1 || e - q - 1 > 2) return false;
266
+ return s[e] !== ',' && !(s[e] === '.' && isDigitCode(s.charCodeAt(e + 1)));
267
+ };
268
+ /** where the chain of ([. ]\d{3}) groups that starts at a position ends; each position is walked once @type {Map<number, number>} */
269
+ const chainEnd = new Map();
270
+ const endOf = (/** @type {number} */ from) => {
271
+ /** @type {number[]} */
272
+ const path = [];
273
+ let q = from; let end;
274
+ for (;;) {
275
+ const seen = chainEnd.get(q);
276
+ if (seen !== undefined) { end = seen; break; }
277
+ path.push(q);
278
+ if ((s[q] === '.' || s[q] === ' ') && isDigitCode(s.charCodeAt(q + 1)) && isDigitCode(s.charCodeAt(q + 2)) && isDigitCode(s.charCodeAt(q + 3))) q += 4;
279
+ else { end = q; break; }
280
+ }
281
+ for (const x of path) chainEnd.set(x, end);
282
+ return end;
283
+ };
284
+ for (let p = 0; p < n;) {
285
+ if (!isDigitCode(s.charCodeAt(p))) { p++; continue; }
286
+ const d = digitsAt(p);
287
+ const prev = p === 0 ? 0 : s.charCodeAt(p - 1);
288
+ if (p === 0 || !(isDigitCode(prev) || isMarkCode(prev))) {
289
+ if (decimals(d)) return true;
290
+ if (d - p <= 3 && decimals(endOf(d))) return true;
291
+ }
292
+ p = d;
293
+ }
294
+ return false;
295
+ }
164
296
 
165
297
  /**
166
298
  * 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.
@@ -180,13 +312,26 @@ export function applyPageRules(text, mapping, jobLines) {
180
312
  };
181
313
 
182
314
  // ---- S1, name part: a fact whose name counts results is refused before anything else reads it ----
183
- const list = all.filter((f) => {
184
- const hit = String(f.name ?? '').toLowerCase().split(/[^a-z]+/).find((w) => ORDINALS.includes(w));
315
+ const named = all.filter((f) => {
316
+ // "last" directly followed by a word ending in "ed" ("last updated", "last modified") names WHEN a thing changed, not which result: it is not a counting name
317
+ const hit = String(f.name ?? '').toLowerCase().split(/[^a-z]+/).find((w, i, ws) => ORDINALS.includes(w) && !(w === 'last' && /ed$/.test(ws[i + 1] ?? '')));
185
318
  if (hit === undefined) return true;
186
319
  drop(f, undefined, 's1-name');
187
320
  return false;
188
321
  });
189
322
 
323
+ // ---- a signed `lang` / `decimal` must really be on the page, else the whole fact is Not checked: a date in a language the page does not
324
+ // write, or a decimal comma on a page with no comma-decimal amount, could only ever read nothing (or the wrong thing). A field on a shape that
325
+ // does not take it (lang off a date, decimal off a number or money) is not carried; the rest of the fact stands. ----
326
+ const list = named.filter((f) => {
327
+ if (f.shape === 'date' && f.lang !== undefined) {
328
+ const months = Object.hasOwn(MONTHS_FULL, String(f.lang)) ? MONTHS_FULL[String(f.lang)] : [];
329
+ if (!months.some((m) => countPhrase(text, m) >= 1)) { drop(f, undefined, 'lang-not-on-page', String(f.lang)); return false; }
330
+ }
331
+ if ((f.shape === 'number' || f.shape === 'money') && f.decimal === ',' && !hasCommaDecimal(squash(text))) { drop(f, undefined, 'decimal-not-on-page', ','); return false; }
332
+ return true;
333
+ });
334
+
190
335
  // ---- found-on-page, then U1 and R1L for the facts that read an amount ----
191
336
  const lines = linesOf(text);
192
337
  /** @type {{f: MapFact, kept: string[], cur: string[], uni: string[], first?: string|null, anchorless?: boolean}[]} */
@@ -223,38 +368,68 @@ export function applyPageRules(text, mapping, jobLines) {
223
368
  /** @type {string[]} */ let uni = [];
224
369
  /** @type {string[]} */ let cur = [];
225
370
  if (f.shape === 'money') {
226
- // the forms: units first (the U1-moved words, then the AI's listed units), then currency signs. SORT, never drop for the box (money
227
- // build v2): the box is position only - a sign (before the number) is a currency, any other form (a word after it) is a unit - so every
228
- // form the AI listed in either box is pooled and moved to the box its own shape belongs to
371
+ // the forms: units first (the U1-moved words, then the AI's listed units), then currency signs. SORT, never drop for the box: the box is
372
+ // position only. A WORD is a unit. A currency SIGN is filed by how the PAGE writes it next to the number (bareguard 0.27, ruling #68): glued
373
+ // to the number, after it or before it, is a currency; spaced after it is a unit; both boxes when the page writes both. The box the AI
374
+ // listed it in does not matter, and a sign listed in both boxes whose page form needs only one is said once ('sign-twice').
229
375
  const listedCurrencies = (Array.isArray(f.currency) ? f.currency : []).map(String);
230
- // a currency SIGN listed in BOTH unit and currency is said once: the unit copy goes (fwd F71 drafts)
231
- const listedUnits = (Array.isArray(f.unit) ? f.unit : []).map(String).filter((u) => {
232
- if (!(CURRENCY_SYMBOLS.includes(u) && listedCurrencies.includes(u))) return true;
233
- drop(f, u, 'sign-twice');
234
- return false;
235
- });
376
+ // bareguard 0.26: two units equal after whitespace normalization are one form, so trim + collapse here and the twins collapse in the pool
377
+ const listedUnits = (Array.isArray(f.unit) ? f.unit : []).map((u) => String(u).replace(/\s+/g, ' ').trim());
378
+ const plainUnits = listedUnits.filter((u) => !CURRENCY_SYMBOLS.includes(u));
379
+ const plainCurrencies = listedCurrencies.filter((c) => !CURRENCY_SYMBOLS.includes(c));
380
+ // the lines that hold this fact's label are where its sign sits next to ITS number; with no label (U1 moved it, or none) the whole page
381
+ const scope = labels.length ? lines.filter((l) => labels.some((w) => l.includes(w))) : lines;
382
+ /** @type {string[]} */ const signCur = [];
383
+ /** @type {string[]} */ const signUni = [];
384
+ for (const sgn of new Set([...listedCurrencies, ...listedUnits].filter((x) => CURRENCY_SYMBOLS.includes(x)))) {
385
+ let fm = signForms(scope, sgn);
386
+ if (!fm.glued && !fm.spaced && !fm.before) fm = signForms(lines, sgn);
387
+ const asCur = fm.glued || fm.before;
388
+ const asUni = fm.spaced;
389
+ if (asCur || !asUni) signCur.push(sgn); // a sign with no number next to it stays a currency: the not-on-page / reads-no-result rules speak
390
+ if (asUni) signUni.push(sgn);
391
+ if (listedCurrencies.includes(sgn) && listedUnits.includes(sgn) && !(asCur && asUni)) drop(f, sgn, 'sign-twice', asUni ? 'unit' : 'currency');
392
+ }
236
393
  // a WORD listed in both boxes is one form, said once (a record of the double listing is kept, as R1L always said it)
237
- for (const w of new Set(listedCurrencies.filter((c) => !CURRENCY_SYMBOLS.includes(c) && listedUnits.includes(c)))) drop(f, w, 'r1l', w);
238
- const pool = [...moved, ...listedUnits, ...listedCurrencies];
239
- const units = [...new Set(pool.filter((w) => !CURRENCY_SYMBOLS.includes(w)))].filter((u) => {
240
- if (countPhrase(text, u) >= 1) return true;
394
+ for (const w of new Set(plainCurrencies.filter((c) => plainUnits.includes(c)))) drop(f, w, 'r1l', w);
395
+ const units = [...new Set([...moved, ...plainUnits, ...plainCurrencies, ...signUni])].filter((u) => {
396
+ if (CURRENCY_SYMBOLS.includes(u) ? countExact(text, u) >= 1 : countPhrase(text, u) >= 1) return true;
241
397
  drop(f, u, 'not-on-page');
242
398
  return false;
243
399
  });
244
- const curs = [...new Set(pool.filter((w) => CURRENCY_SYMBOLS.includes(w)))].filter((c) => {
400
+ const curs = [...new Set(signCur)].filter((c) => {
245
401
  if (countExact(text, c) >= 1) return true;
246
402
  drop(f, c, 'not-on-page');
247
403
  return false;
248
404
  });
249
405
  /** @type {{kind: 'unit'|'currency', w: string}[]} */
250
406
  const forms = [...units.map((u) => /** @type {const} */ ({ kind: 'unit', w: u })), ...curs.map((c) => /** @type {const} */ ({ kind: 'currency', w: c }))];
407
+ // A page read where the form is written (see R1L): a sign after its number reads the number before it, before its number the one after
408
+ const read = (/** @type {{kind: string, w: string}} */ x) => {
409
+ if (!CURRENCY_SYMBOLS.includes(x.w)) return x.kind === 'unit' ? unitSet(lines, x.w) : curSet(lines, x.w);
410
+ const fm = signForms(lines, x.w);
411
+ return x.kind === 'unit' || fm.glued || !fm.before ? unitSet(lines, x.w) : curSet(lines, x.w);
412
+ };
413
+ // a form that reads NO amount anywhere on the page ("ohne MwSt." alone on its own line) is dropped BEFORE R1L, so R1L never takes it as the
414
+ // reference and then drops the form that does read. When no form reads anything, nothing is dropped here and the later rules speak.
415
+ if (forms.some((x) => read(x).size > 0)) {
416
+ for (let i = forms.length - 1; i >= 0; i -= 1) {
417
+ if (read(forms[i]).size > 0) continue;
418
+ drop(f, forms[i].w, 'reads-no-amount');
419
+ forms.splice(i, 1);
420
+ }
421
+ }
251
422
  if (forms.length) {
252
- // R1L: every form reads the same set of numbers as the primary (the first form); one that reads more or fewer is dropped
253
- const read = (/** @type {{kind: string, w: string}} */ x) => (x.kind === 'unit' ? unitSet(lines, x.w) : curSet(lines, x.w));
423
+ // R1L: every form reads the same set of numbers as the primary (the first form that reads); one that reads more or fewer is dropped.
254
424
  const ps = read(forms[0]);
255
425
  const keep = [forms[0]];
256
- // the same word listed as both a unit and a currency is ONE form: it is never compared with itself, only said (the unit, listed first, stays)
257
- for (const x of forms.slice(1)) { if (x.w !== forms[0].w && sameSet(read(x), ps)) keep.push(x); else drop(f, x.w, 'r1l', forms[0].w); }
426
+ // one SIGN filed in both boxes by its page forms is ONE symbol read in two forms (bareguard 0.27 counts the same amount as one price): it is
427
+ // never compared with itself
428
+ for (const x of forms.slice(1)) {
429
+ if (CURRENCY_SYMBOLS.includes(x.w) && x.w === forms[0].w) keep.push(x);
430
+ else if (x.w !== forms[0].w && sameSet(read(x), ps)) keep.push(x);
431
+ else drop(f, x.w, 'r1l', forms[0].w);
432
+ }
258
433
  uni = keep.filter((x) => x.kind === 'unit').map((x) => x.w);
259
434
  cur = keep.filter((x) => x.kind === 'currency').map((x) => x.w);
260
435
  }
@@ -308,6 +483,15 @@ export function applyPageRules(text, mapping, jobLines) {
308
483
  if (p.uni.length) out.unit = [...p.uni];
309
484
  if (p.cur.length) out.currency = [...p.cur];
310
485
  }
486
+ if (p.f.shape === 'date' && p.f.lang !== undefined) out.lang = String(p.f.lang);
487
+ if ((p.f.shape === 'number' || p.f.shape === 'money') && p.f.decimal !== undefined) out.decimal = String(p.f.decimal);
488
+ // CODE picks the decimal mark of a money fact from how the page writes the amounts its signs touch, over the AI's word when the page is clear
489
+ // (a "1.058,47 €" page read with "." would read wrong); both kinds or neither, the AI's word stands. A clear dot page keeps what was signed
490
+ // ("." is the reader's default, so no field is added).
491
+ if (p.f.shape === 'money') {
492
+ const mark = pageDecimal(lines, [...(out.currency ?? []), ...(out.unit ?? [])]);
493
+ if (mark === ',') out.decimal = ',';
494
+ }
311
495
  if (t.rule !== undefined) out.forRule = t.rule;
312
496
  if (validReading(out.shape, p.f.reading)) out.reading = /** @type {Reading} */ ({ ...p.f.reading });
313
497
  return out;
@@ -53,7 +53,7 @@ import { closeJudges } from '../kinds.js';
53
53
  import { RUBRIC_LANG } from '../authoring.js';
54
54
  import { rubricGoal, reconcileRubricPlan, signedFactNames } from '../rubricstep.js';
55
55
  import { redactSecrets } from '../validate.js';
56
- import { isDropIt, isAgree } from '../pagemap.js';
56
+ import { isDropIt, isAgree, stripAgreeLead } from '../pagemap.js';
57
57
  import { FIT_ABSENT_NOTE } from '../fitcheck.js';
58
58
  import { tallyCalls } from '../text.js';
59
59
  import { appendDraftLog } from '../draftspend.js';
@@ -776,6 +776,8 @@ export function createSession(card, deps = {}) {
776
776
  if (RUBRIC_FILES) {
777
777
  const proved = await proveRubricInputs({ inputs: INPUTS, into, destination: card.destination, ...(deps.fetchUrl ? { fetchUrl: deps.fetchUrl } : {}) });
778
778
  prep = proved.ok ? proved.prep : { stop: proved.error, code: proved.code };
779
+ // what each header-only page read came back with (already secret-masked at capture), so the next live failure shows it
780
+ if (!proved.ok && proved.attempts?.length) appendDraftLog(outDir, { kind: 'page-fetch-attempts', no: Math.max(0, state.steps.length - 1), attempts: proved.attempts, at: new Date().toISOString() });
779
781
  } else {
780
782
  prep = await prepareSource({
781
783
  source: SOURCE, into, ...(isRepoLike || destIsDir ? { destination: card.destination } : {}),
@@ -1067,6 +1069,8 @@ export function createSession(card, deps = {}) {
1067
1069
  // PRD v1.107 Part 5b: a code-forced look question about a `~` rule. A can't-check ask answered "drop it" adds NO rule; the caller puts that
1068
1070
  // rule on the look's Not checked list. A reading ask answered "agree" adds the code's reading, in plain words, as the `~` rule (so the
1069
1071
  // bound is now the person's own words); anything else typed is the person's own rule, word for word.
1072
+ // F240: "yes, check it as ..." is the person's own words minus the leading "yes,"
1073
+ if (q.source === 'look') text = stripAgreeLead(text);
1070
1074
  if (q.source === 'look' && q.ask === 'reading' && typeof q.reading === 'string' && isAgree(text)) text = q.reading;
1071
1075
  if (q.source === 'look' && q.ask === 'cant-check' && Number.isInteger(q.rule) && isDropIt(text)) { left.push({ line: q.line, rule: /** @type {number} */ (q.rule) }); continue; }
1072
1076
  const line = jobLines.find((l) => l.n === q.line);
@@ -5248,8 +5248,8 @@
5248
5248
  fitCardBoxes();
5249
5249
  }
5250
5250
  msgInput.addEventListener("input", renderMain);
5251
- // P7 — the numbered boxes. A plain job line is numbered 1, 2, 3; a line starting `~` is a rule for the line above and has no
5252
- // number; Inputs numbers every line; empty lines have none. A hidden mirror (same font/width/padding) measures each logical
5251
+ // P7 — the numbered boxes. A plain job line is numbered 1, 2, 3; a line starting `~` is a rule for the line above: it shows `~` in
5252
+ // the gutter and takes no number; Inputs numbers every line; empty lines have none. A hidden mirror (same font/width/padding) measures each logical
5253
5253
  // line's wrapped height so every number stays level with its own line — the same rules src/jobblock.js parses by.
5254
5254
  var NUMBERED_IDS = ["jf-job", "jf-inputs"];
5255
5255
  var FIT_IDS = ["jf-job", "jf-inputs", "jf-dest"];
@@ -5261,7 +5261,8 @@
5261
5261
  var n = 0;
5262
5262
  var nums = lines.map(function(l){
5263
5263
  var t = l.trim();
5264
- if(t === "" || (isJob && t.charAt(0) === "~")) return "";
5264
+ if(t === "") return "";
5265
+ if(isJob && t.charAt(0) === "~") return "~";
5265
5266
  n += 1; return String(n);
5266
5267
  });
5267
5268
  mir.style.width = ta.clientWidth ? ta.clientWidth + "px" : "";
package/src/rubricstep.js CHANGED
@@ -3,7 +3,7 @@ import { readFile, lstat } from 'node:fs/promises';
3
3
  import { join, dirname } from 'node:path';
4
4
  import { createRubric, checkStep, renderGaps, numbersInQuote } from 'bareguard';
5
5
  import { dropRows, dropLine } from './pagedropwords.js';
6
- import { factPartOf, factShapeReds, factDecides, factClaims, factRows, plainFactItem, factBrief } from './facts.js';
6
+ import { factPartOf, factShapeReds, factDecides, factClaims, factRows, plainFactItem, factBrief, writtenSpans } from './facts.js';
7
7
 
8
8
  // PART 1a (docs/product/ITEM33-BUILD.md, "Addendum 2026-10-12"): the rubric job on LOCAL FILES — what one job line leaves
9
9
  // behind and how it is told to the worker.
@@ -340,9 +340,10 @@ export function parseStepFile(bytes) {
340
340
  * @param {Record<string, any>} obj
341
341
  * @param {string[]} [countLabels] labels whose claim COUNT a minClaims/maxClaims part reads
342
342
  * @param {any} [factPart] the step's `fact` part: its `results` become claims (text built by code) under `cites:<source>`
343
+ * @param {(Record<number, string>|undefined)[]} [asWritten] per result, the value spans a page-form fact's claim text is written with (see factClaims)
343
344
  * @returns {Record<string, any>}
344
345
  */
345
- export function flattenStep(obj, countLabels = [], factPart = null) {
346
+ export function flattenStep(obj, countLabels = [], factPart = null, asWritten = []) {
346
347
  /** @type {Record<string, any>} */
347
348
  const fields = {};
348
349
  // the number of claims listed under each label a claim-count check names (0 when the label is absent): counted HERE, by
@@ -352,7 +353,7 @@ export function flattenStep(obj, countLabels = [], factPart = null) {
352
353
  fields[`claims:${label}`] = Array.isArray(list) ? list.length : 0;
353
354
  }
354
355
  if (factPart) {
355
- const claims = factClaims(factPart, obj.results);
356
+ const claims = factClaims(factPart, obj.results, asWritten);
356
357
  fields[`claims:${factPart.source}`] = claims.length;
357
358
  fields[`cites:${factPart.source}`] = claims;
358
359
  }
@@ -430,9 +431,18 @@ export async function gradeStep({ params, bytes, outputBytes, inputs, factQuotes
430
431
  }
431
432
  const parsed = parseStepFile(bytes);
432
433
  const countLabels = [...new Set(params.parts.filter((/** @type {any} */ x) => x.class === 'countable' && (x.check === 'minClaims' || x.check === 'maxClaims')).map((/** @type {any} */ x) => String(x.source)))];
433
- const r = await checkStep(rubric, String(params.step), parsed.obj === null ? null : flattenStep(parsed.obj, countLabels, factPartOf(params)), {
434
+ const factPart = factPartOf(params);
435
+ const check = (/** @type {(Record<number, string>|undefined)[]} */ asWritten = []) => checkStep(rubric, String(params.step), parsed.obj === null ? null : flattenStep(parsed.obj, countLabels, factPart, asWritten), {
434
436
  inputs, ...(outputBytes === null ? {} : { outputBytes }),
435
437
  });
438
+ let r = await check();
439
+ // a fact that signs a page form (`lang` / `decimal`) has a canonical value but its claim text must spell it as the quote does: bareguard's own
440
+ // evidence of where it read the value in each quote gives the spelling, and the same file is checked once more with the text written so. Both
441
+ // passes are the one bareguard reader; the verdict, gap and counts below come from the last.
442
+ if (factPart && Array.isArray(factPart.facts) && factPart.facts.some((/** @type {any} */ f) => isRec(f) && (f.lang !== undefined || f.decimal !== undefined))) {
443
+ const written = writtenSpans(factPart, r.full.evidence);
444
+ if (written.some(Boolean)) r = await check(written);
445
+ }
436
446
  // PART 1b: a prose step's numbers are tied to the checked facts of earlier lines (bareguard's `numbersInQuote`: token match on the
437
447
  // numbers, not a canonical compare — a documented limit). Words are free; a number that no checked quote holds is a red.
438
448
  /** @type {string[]} */
@@ -502,6 +512,26 @@ function wordRange(part) {
502
512
  return null;
503
513
  }
504
514
 
515
+ /**
516
+ * bareguard refuses a money unit list whose entries are equal once `**`, `__` and extra spaces are removed, naming the path
517
+ * `...checks[K].decides[N].unit`. K indexes buildStepSpec's checks (id `p<part>-facts`), N the fact within that part.
518
+ * @param {{step: number, parts: any[]}} p @param {unknown} path @returns {{name: string, a: string, b: string}|null} the fact and the two twin units, or null when the path is not that
519
+ */
520
+ function dupUnitWords(p, path) {
521
+ const m = typeof path === 'string' ? /\.checks\[(\d+)\]\.decides\[(\d+)\]\.unit$/.exec(path) : null;
522
+ if (!m) return null;
523
+ const id = buildStepSpec(p, {}).checkpoints[String(p.step)].checks[Number(m[1])]?.id;
524
+ const pm = typeof id === 'string' ? /^p(\d+)-facts$/.exec(id) : null;
525
+ const fact = pm ? p.parts[Number(pm[1]) - 1]?.facts?.[Number(m[2])] : null;
526
+ if (!fact || !Array.isArray(fact.unit)) return null;
527
+ const key = (/** @type {string} */ u) => u.split('**').join('').split('__').join('').replace(/\s+/g, ' ').trim();
528
+ for (let i = 0; i < fact.unit.length; i += 1) {
529
+ const j = fact.unit.findIndex((/** @type {string} */ u, /** @type {number} */ k) => k > i && key(u) === key(fact.unit[i]));
530
+ if (j > i) return { name: String(fact.name), a: fact.unit[i], b: fact.unit[j] };
531
+ }
532
+ return null;
533
+ }
534
+
505
535
  /**
506
536
  * R11 — the drafting-time rules for the `rubric-step` stages of a declaration, each a red in the person's plain words that
507
537
  * names the job line and ends "Nothing spent." where nothing was. Pure; never throws. Judged parts are RED in this build
@@ -591,7 +621,8 @@ export function checkRubricParts(stages, { inputLabels = null, red }) {
591
621
  // bareguard is the judge of whether a fact list is SIGNABLE (anchors, units, bounds): ask it at drafting, at $0, so a list
592
622
  // it would refuse at run time is a red the drafter can fix now
593
623
  try { createRubric(buildStepSpec(/** @type {{step: number, parts: any[]}} */ (p), Object.fromEntries(citedLabels(p).map((l) => [l, '0'.repeat(64)])))); } catch (e) {
594
- red('rubric-fact-invalid', `${at}.params.parts`, `line ${line}: the facts cannot be signed: ${/** @type {Error} */ (e).message}`, { line: step, stage: label });
624
+ const twins = dupUnitWords(/** @type {{step: number, parts: any[]}} */ (p), /** @type {{path?: unknown}} */ (e).path);
625
+ red('rubric-fact-invalid', `${at}.params.parts`, twins ? `line ${line}: the fact '${twins.name}' lists the same unit twice ('${twins.a}' and '${twins.b}' are the same once marks and spaces are removed). Keep one. Nothing spent.` : `line ${line}: the facts cannot be signed: ${/** @type {Error} */ (e).message}`, { line: step, stage: label });
595
626
  }
596
627
  }
597
628
  for (let a = 0; a < ranges.length; a += 1) {
package/src/source.js CHANGED
@@ -1250,8 +1250,8 @@ export function isRubricFilesManifest(manifest) {
1250
1250
  * so run start can fetch it again); a `search:` line is a named refusal (a later build); so is a relative path, a missing file, a folder, a file over
1251
1251
  * {@link RUBRIC_INPUT_MAX_BYTES}, and text that is not valid UTF-8. Every refusal is plain words naming the line and
1252
1252
  * ends "Nothing spent." — nothing here touches a model.
1253
- * @param {{inputs: {n: number, label: string, value: string}[], into: string, destination?: string, fetchUrl?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>}} o `fetchUrl` - how a web address is read (default barebrowse via `fetchPageText`; a test injects a stub, never the network)
1254
- * @returns {Promise<{ok: true, prep: {stop: null, into: string, tree: string, manifestPath: string, manifest: Record<string, any>}}|{ok: false, error: string, code: string}>}
1253
+ * @param {{inputs: {n: number, label: string, value: string}[], into: string, destination?: string, fetchUrl?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string, attempts?: {chars: number, ms: number, head: string}[]}>}} o `fetchUrl` - how a web address is read (default barebrowse via `fetchPageText`; a test injects a stub, never the network)
1254
+ * @returns {Promise<{ok: true, prep: {stop: null, into: string, tree: string, manifestPath: string, manifest: Record<string, any>}}|{ok: false, error: string, code: string, attempts?: {chars: number, ms: number, head: string}[]}>}
1255
1255
  */
1256
1256
  export async function proveRubricInputs({ inputs, into, destination, fetchUrl = (u) => fetchPageText(u) }) {
1257
1257
  /** @param {string} code @param {number} n @param {string} msg @returns {{ok: false, error: string, code: string}} */
@@ -1273,7 +1273,7 @@ export async function proveRubricInputs({ inputs, into, destination, fetchUrl =
1273
1273
  labels.add(label.toLowerCase());
1274
1274
  if (isWebUrl(value)) {
1275
1275
  const got = await fetchUrl(value.trim());
1276
- if (!got.ok) return bad('input-url-unreadable', n, `${got.error.replace(/(?<![.\s])[.\s]+$/, '')}.`);
1276
+ if (!got.ok) return { ...bad('input-url-unreadable', n, `${got.error.replace(/(?<![.\s])[.\s]+$/, '')}.`), ...(got.attempts?.length ? { attempts: got.attempts } : {}) };
1277
1277
  const pageBuf = Buffer.from(got.text, 'utf8');
1278
1278
  const leak = secretPatternNames(got.text);
1279
1279
  if (leak.length) return bad('input-url-secret', n, `the page at ${got.url} carries a known secret shape (${leak.join(', ')}) - refused, secrets never enter a job.`);
@@ -1764,6 +1764,14 @@ export const PARAM_SCHEMAS: Readonly<{
1764
1764
  type: string;
1765
1765
  description: string;
1766
1766
  };
1767
+ lang: {
1768
+ enum: string[];
1769
+ description: string;
1770
+ };
1771
+ decimal: {
1772
+ enum: string[];
1773
+ description: string;
1774
+ };
1767
1775
  };
1768
1776
  required: string[];
1769
1777
  additionalProperties: boolean;
package/types/facts.d.ts CHANGED
@@ -16,13 +16,26 @@ export function factDecides(part: any): Record<string, any>[];
16
16
  * from the values the worker gave (the worker writes no claim text): `name: value; name: value`. A phrase fact contributes its
17
17
  * own signed words. A result that is not an object, or has no string quote, still becomes a claim — an empty one — so
18
18
  * bareguard reds it by name rather than the result vanishing.
19
- * @param {any} part @param {unknown} results @returns {{claim: string, quote: string, values?: Record<string, string>}[]}
19
+ *
20
+ * A fact that signs a page form (`lang` or `decimal`) carries a CANONICAL value ("2026-10-26", "1057.65": bareguard's typed binding, `values.d<j>`),
21
+ * but bareguard's number scan compares the claim TEXT with the quote's own digits, so the text must spell the value the way the quote does
22
+ * ("26 October 2026", "1.057,65"). That spelling is `asWritten[result][fact index]`: the value span bareguard itself reported for that quote
23
+ * ({@link writtenSpans}); a fact with no span there reads the value the worker gave.
24
+ * @param {any} part @param {unknown} results @param {(Record<number, string>|undefined)[]} [asWritten]
25
+ * @returns {{claim: string, quote: string, values?: Record<string, string>}[]}
20
26
  */
21
- export function factClaims(part: any, results: unknown): {
27
+ export function factClaims(part: any, results: unknown, asWritten?: (Record<number, string> | undefined)[]): {
22
28
  claim: string;
23
29
  quote: string;
24
30
  values?: Record<string, string>;
25
31
  }[];
32
+ /**
33
+ * Where bareguard read each page-form fact's value inside each quote, as the quote spells it: from `checkStep`'s `full.evidence` (one entry per
34
+ * claim: `text` = the normalized quote the decides ran on, `spans` = where each decide read its anchor, value and unit/currency). Only a fact that
35
+ * signs `lang` or `decimal` is looked up; the span is the decide's `value` span (the one equal to the claim's own value when bareguard flags it).
36
+ * @param {any} part @param {any[]|undefined} evidence @returns {(Record<number, string>|undefined)[]} per claim index
37
+ */
38
+ export function writtenSpans(part: any, evidence: any[] | undefined): (Record<number, string> | undefined)[];
26
39
  /**
27
40
  * One amount of a money fact in the fact's OWN signed forms, never a hardcoded sign: `symbolFirst` puts the currency sign before the amount
28
41
  * ("$144") when the fact has one, else the unit after it ("144 US dollars"); not `symbolFirst` (a rule's bound) prefers the unit.
@@ -75,6 +88,18 @@ export const FACT_SHAPES: readonly string[];
75
88
  export const FACT_OPS: readonly string[];
76
89
  /** bareguard signs at most this many decides on one `cited` check */
77
90
  export const MAX_FACTS: 10;
91
+ /** the languages whose month names bareguard 0.27 reads on a `date` fact (its `lang`), each with the name a person reads; absent `lang` = ISO YYYY-MM-DD only */
92
+ export const FACT_LANGS: Readonly<{
93
+ en: "English";
94
+ de: "German";
95
+ fr: "French";
96
+ es: "Spanish";
97
+ it: "Italian";
98
+ pt: "Portuguese";
99
+ nl: "Dutch";
100
+ }>;
101
+ /** the decimal marks a number or money fact may sign (bareguard 0.27 `decimal`); absent = "." */
102
+ export const FACT_DECIMALS: readonly string[];
78
103
  /** every field a part of class `fact` may carry (the shared ones are checked by rubricStepShapeReds) */
79
104
  export const FACT_PART_FIELDS: readonly string[];
80
105
  /** the limits bareguard 0.24 puts on a money fact's lists (ruling #65), enforced here first so the red is ours and plain */
@@ -13,7 +13,7 @@ export function countPhrase(source: string, words: string): number;
13
13
  * 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
14
14
  * path has no `dropped` list, so it gives null and the label is proved against the code-made list as before.
15
15
  * @param {{facts?: any[], dropped?: (import('./pagerules.js').Dropped & {source?: string})[]}|null|undefined} look @param {string} source
16
- * @returns {{labels: Set<string>, units: Set<string>, currencies: Set<string>, words: Set<string>, dropped: Map<string, import('./pagerules.js').Dropped>}|null}
16
+ * @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}
17
17
  */
18
18
  export function keptSetOf(look: {
19
19
  facts?: any[];
@@ -26,6 +26,11 @@ export function keptSetOf(look: {
26
26
  currencies: Set<string>;
27
27
  words: Set<string>;
28
28
  dropped: Map<string, import("./pagerules.js").Dropped>;
29
+ forms: {
30
+ labels: Set<string>;
31
+ lang?: string;
32
+ decimal?: string;
33
+ }[];
29
34
  } | null;
30
35
  /**
31
36
  * The reds for ONE fact part against its frozen source text.
@@ -211,6 +211,8 @@ export type LookFact = {
211
211
  labels?: string[];
212
212
  unit?: string[];
213
213
  currency?: string[];
214
+ lang?: string;
215
+ decimal?: string;
214
216
  };
215
217
  export type LookNotFound = {
216
218
  line: number;
@@ -14,6 +14,10 @@
14
14
  * @property {number} [silentWaitMs] how long start keeps asking a taken, silent port (default 10 s)
15
15
  * @property {string} [nodeVersion] default process.versions.node
16
16
  * @property {typeof fetch} [fetchImpl]
17
+ * @property {(cmd: string, args: string[], o: object) => any} [npmSpawn] runs `npm install -g bareloop@latest` for `update` (default node:child_process spawn, no shell)
18
+ * @property {number} [npmDeadlineMs] how long `update`'s npm install may run before its child is killed (default 300 s)
19
+ * @property {boolean} [terminal] false = no person at a terminal (piped / redirected stdin): `update` then never installs, it prints the command (absent = ask)
20
+ * @property {typeof fetch} [npmFetch] the registry check of `update` only (default the global fetch); nothing else ever goes online
17
21
  * @property {(cmd: string, args: string[], o: object) => any} [spawnFn] default node:child_process spawn
18
22
  * @property {(pid: number, sig: string|number) => void} [kill] default process.kill
19
23
  * @property {((target: string) => Promise<boolean>)} [open] default the shared OS opener
@@ -126,6 +130,21 @@ export function statusCmd(io: {
126
130
  lines: string[];
127
131
  panels: Panel[];
128
132
  }): Promise<number>;
133
+ /**
134
+ * `bareloop update` — the only launcher command that goes online, and only when pressed: reads the newest published version from the npm
135
+ * registry (5 s deadline) and says whether there is a newer one. It installs nothing; it tells the person the command.
136
+ * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string}} d @param {{lines: string[], panels: Panel[]}} [shown]
137
+ * @returns {Promise<number>}
138
+ */
139
+ export function updateCmd(io: {
140
+ out: (s: string) => void;
141
+ err: (s: string) => void;
142
+ }, d: LauncherDeps & {
143
+ version?: string;
144
+ }, shown?: {
145
+ lines: string[];
146
+ panels: Panel[];
147
+ }): Promise<number>;
129
148
  /**
130
149
  * `bareloop start` — find a running panel first; else start one detached on the first free port 4700..4709, wait until it answers,
131
150
  * open the page.
@@ -175,8 +194,8 @@ export function restartCmd(args: string[], io: {
175
194
  panels: Panel[];
176
195
  }): Promise<number>;
177
196
  /**
178
- * The bare `bareloop` menu (PRD v1.114, one menu): the panel's four choices, the four job commands, one question. Runs the chosen command
179
- * and returns its exit code. The job commands (6 export, 7 run, 8 resume, 9 history) are `d.jobs`, supplied by the CLI: each prompts for
197
+ * The bare `bareloop` menu (PRD v1.114, one menu): the panel's six choices, the four job commands, one question. Runs the chosen command
198
+ * and returns its exit code. The job commands (7 export, 8 run, 9 resume, 10 history) are `d.jobs`, supplied by the CLI: each prompts for
180
199
  * what it needs on the same asker this menu uses.
181
200
  * @param {{out: (s: string) => void, err: (s: string) => void}} io @param {LauncherDeps & {version?: string, jobs?: {export: () => Promise<number>, run: () => Promise<number>, resume: () => Promise<number>, history: () => Promise<number>}}} d
182
201
  * @returns {Promise<number>}
@@ -242,6 +261,22 @@ export type LauncherDeps = {
242
261
  */
243
262
  nodeVersion?: string | undefined;
244
263
  fetchImpl?: typeof fetch | undefined;
264
+ /**
265
+ * runs `npm install -g bareloop@latest` for `update` (default node:child_process spawn, no shell)
266
+ */
267
+ npmSpawn?: ((cmd: string, args: string[], o: object) => any) | undefined;
268
+ /**
269
+ * how long `update`'s npm install may run before its child is killed (default 300 s)
270
+ */
271
+ npmDeadlineMs?: number | undefined;
272
+ /**
273
+ * false = no person at a terminal (piped / redirected stdin): `update` then never installs, it prints the command (absent = ask)
274
+ */
275
+ terminal?: boolean | undefined;
276
+ /**
277
+ * the registry check of `update` only (default the global fetch); nothing else ever goes online
278
+ */
279
+ npmFetch?: typeof fetch | undefined;
245
280
  /**
246
281
  * default node:child_process spawn
247
282
  */