fwdloop 0.21.0 → 0.23.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 (104) hide show
  1. package/bin/fwdloop +85 -34
  2. package/package.json +4 -3
  3. package/src/ask.js +20 -4
  4. package/src/audit-fold.js +5 -1
  5. package/src/authoring.js +36 -6
  6. package/src/canrun.js +5 -0
  7. package/src/checked.js +32 -4
  8. package/src/cited-record.js +138 -0
  9. package/src/cited-source.js +49 -0
  10. package/src/citedcheck.js +321 -0
  11. package/src/citedwords.js +197 -0
  12. package/src/closers.js +37 -198
  13. package/src/csv.js +69 -12
  14. package/src/ctx-tools.js +2 -14
  15. package/src/declaration.js +143 -5
  16. package/src/diary.js +2 -2
  17. package/src/docx.js +16 -2
  18. package/src/draft-steps.js +1 -1
  19. package/src/drafter.js +322 -33
  20. package/src/flow.js +33 -7
  21. package/src/flowmodel.js +21 -0
  22. package/src/input-facts.js +20 -3
  23. package/src/model-step.js +38 -21
  24. package/src/pageask.js +136 -0
  25. package/src/pagebits.js +107 -0
  26. package/src/pagedropwords.js +171 -0
  27. package/src/pagedry.js +120 -0
  28. package/src/pagefetch.js +164 -0
  29. package/src/pagelook.js +155 -0
  30. package/src/pagemap.js +55 -0
  31. package/src/pageplace.js +103 -0
  32. package/src/pagerules.js +318 -0
  33. package/src/panel/author.js +43 -21
  34. package/src/panel/authorcard.js +20 -3
  35. package/src/panel/authorflows.js +21 -15
  36. package/src/panel/authorstart.js +2 -4
  37. package/src/panel/authortrigger.js +14 -4
  38. package/src/panel/data.js +102 -6
  39. package/src/panel/index.html +321 -12
  40. package/src/panel/result.js +301 -0
  41. package/src/panel/server.js +27 -3
  42. package/src/primitives.js +2 -3
  43. package/src/provider.js +5 -2
  44. package/src/redact.js +17 -0
  45. package/src/runner.js +102 -14
  46. package/src/schedule.js +3 -3
  47. package/src/setup.js +16 -1
  48. package/src/sheet-record.js +57 -0
  49. package/src/sheetblock.js +170 -0
  50. package/src/sheetchecks.js +206 -0
  51. package/src/sheetclaims.js +78 -0
  52. package/src/sheetfind.js +50 -0
  53. package/src/sheetlook.js +157 -0
  54. package/src/sheetoffer.js +125 -0
  55. package/src/sheetrun.js +105 -0
  56. package/src/signed-text.js +11 -1
  57. package/src/thinking.js +1 -1
  58. package/src/try-checks.js +12 -0
  59. package/src/types.js +4 -11
  60. package/types/ask.d.ts +2 -1
  61. package/types/authoring.d.ts +19 -2
  62. package/types/checked.d.ts +19 -3
  63. package/types/cited-record.d.ts +21 -0
  64. package/types/cited-source.d.ts +18 -0
  65. package/types/citedcheck.d.ts +95 -0
  66. package/types/citedwords.d.ts +97 -0
  67. package/types/closers.d.ts +37 -10
  68. package/types/csv.d.ts +25 -4
  69. package/types/ctx-tools.d.ts +0 -1
  70. package/types/declaration.d.ts +20 -1
  71. package/types/docx.d.ts +14 -0
  72. package/types/drafter.d.ts +264 -8
  73. package/types/flow.d.ts +21 -0
  74. package/types/flowmodel.d.ts +15 -0
  75. package/types/input-facts.d.ts +12 -2
  76. package/types/model-step.d.ts +40 -19
  77. package/types/pageask.d.ts +75 -0
  78. package/types/pagebits.d.ts +32 -0
  79. package/types/pagedropwords.d.ts +40 -0
  80. package/types/pagedry.d.ts +38 -0
  81. package/types/pagefetch.d.ts +86 -0
  82. package/types/pagelook.d.ts +75 -0
  83. package/types/pagemap.d.ts +31 -0
  84. package/types/pageplace.d.ts +22 -0
  85. package/types/pagerules.d.ts +86 -0
  86. package/types/panel/authorcard.d.ts +4 -1
  87. package/types/panel/authorflows.d.ts +2 -0
  88. package/types/panel/data.d.ts +26 -0
  89. package/types/panel/result.d.ts +156 -0
  90. package/types/provider.d.ts +3 -1
  91. package/types/redact.d.ts +1 -0
  92. package/types/runner.d.ts +162 -9
  93. package/types/schedule.d.ts +0 -11
  94. package/types/setup.d.ts +13 -0
  95. package/types/sheet-record.d.ts +24 -0
  96. package/types/sheetblock.d.ts +116 -0
  97. package/types/sheetchecks.d.ts +70 -0
  98. package/types/sheetclaims.d.ts +26 -0
  99. package/types/sheetfind.d.ts +46 -0
  100. package/types/sheetlook.d.ts +120 -0
  101. package/types/sheetoffer.d.ts +25 -0
  102. package/types/sheetrun.d.ts +35 -0
  103. package/types/thinking.d.ts +1 -1
  104. package/types/types.d.ts +27 -14
@@ -0,0 +1,318 @@
1
+ // borrowed-from: bareloop src/pagerules.js@1a0712b
2
+ // Copy of bareloop's file; the three number patterns (BEFORE, AFTER, AFTER_CUR) are written as literals, not built from NUM (this repo bans dynamic patterns in src/); only the import lines point at fwdloop's src/pagebits.js (the pieces of facts.js, factwords.js, labelscan.js, rubricstep.js the rules need).
3
+ // IDEA A CORE (docs/product/ITEM33-BUILD.md "Addendum 2026-10-18 — Idea A core: build spec", section 4.2): the plain code rules that
4
+ // keep or drop each page word the AI's map named. The AI never grades: it names words, code keeps only what the saved page proves.
5
+ // Pure - no I/O, no clock, no model. The rule bodies are PORTED from the frozen POC (scratch idea-a-v2/rules.mjs and
6
+ // rules-v3-candidate.mjs; sha256 recorded in commit 0bcc5fe), with the OUT branches (R2, R2a, R2b, R2c, R3, R3U, V4, pageClaims) deleted.
7
+
8
+ import { lineRules } from './pagebits.js';
9
+ import { MAX_CURRENCIES, MAX_UNITS, MAX_UNIT_CHARS, FACT_OPS, boundOk } from './pagebits.js';
10
+ import { countExact, countPhrase, squash, normLabel } from './pagebits.js';
11
+
12
+ /**
13
+ * @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
14
+ * @typedef {{name: string, from?: string, shape: string, words?: string[], currency?: string[], unit?: string[], reading?: Reading}} MapFact the AI's map, one fact
15
+ * @typedef {{facts: MapFact[]}} PageMap
16
+ * @typedef {{line: number, name: string, shape: string, from: string, words: string[], unit?: string[], currency?: string[], forRule?: number, reading?: Reading}} KeptFact
17
+ * `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)
18
+ * @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)
19
+ */
20
+
21
+ /** @param {unknown} v @returns {v is Record<string, any>} */
22
+ const isRec = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
23
+
24
+ /**
25
+ * Which job line, and which `~` rule under it, a map fact carries out. The map writes `from` as "line N", "line N rule M", "rule M" or
26
+ * "job line"; anything else is the first job line.
27
+ * @param {unknown} from @param {{n: number, text?: string, rule?: string, rules?: string[]}[]} jobLines
28
+ * @returns {{line: number, rule?: number}}
29
+ */
30
+ export function tieOf(from, jobLines) {
31
+ const s = String(from ?? '');
32
+ const lineM = /line\s*(\d+)/i.exec(s);
33
+ const ruleM = /rule\s*(\d+)/i.exec(s);
34
+ const first = jobLines[0]?.n ?? 1;
35
+ let line = lineM && jobLines.some((l) => l.n === Number(lineM[1])) ? Number(lineM[1]) : null;
36
+ const rule = ruleM ? Number(ruleM[1]) : undefined;
37
+ if (line === null && rule !== undefined) line = jobLines.find((l) => lineRules(l).length >= rule)?.n ?? null;
38
+ const out = { line: line ?? first };
39
+ if (rule !== undefined && lineRules(jobLines.find((l) => l.n === out.line)).length >= rule) return { ...out, rule };
40
+ return out;
41
+ }
42
+
43
+ /**
44
+ * Is this a legal `reading` for a fact of this shape? Only a time or money fact carries one, with the op set and the bound types of a signed
45
+ * fact rule (src/facts.js): no other key, no missing bound. A malformed one makes the whole map answer malformed (no repair).
46
+ * @param {unknown} shape @param {unknown} r @returns {boolean}
47
+ */
48
+ export function validReading(shape, r) {
49
+ if (shape !== 'time' && shape !== 'money') return false;
50
+ if (!isRec(r) || !FACT_OPS.includes(r.op)) return false;
51
+ const keys = Object.keys(r).sort().join();
52
+ return r.op === 'between' ? keys === 'hi,lo,op' && boundOk(shape, r.lo) && boundOk(shape, r.hi) : keys === 'op,value' && boundOk(shape, r.value);
53
+ }
54
+
55
+ /** @param {string} text @returns {string[]} the page's lines, white space squashed (the unit every per-line rule counts in) */
56
+ export const linesOf = (text) => text.split('\n').map(squash);
57
+
58
+ /**
59
+ * How many times a label occurs inside ONE page line, at most (plain indexOf on squashed lines, non-overlapping): the N2 measure.
60
+ * @param {string[]} lines @param {string} phrase @returns {number}
61
+ */
62
+ function maxPerLine(lines, phrase) {
63
+ const p = squash(phrase).trim();
64
+ if (!p) return 0;
65
+ let max = 0;
66
+ for (const ln of lines) {
67
+ let n = 0;
68
+ for (let i = ln.indexOf(p); i !== -1; i = ln.indexOf(p, i + p.length)) n += 1;
69
+ if (n > max) max = n;
70
+ }
71
+ return max;
72
+ }
73
+
74
+ /** the value each shape reads right after a label: a money or number is digits (a sign may come first), a time is h:mm and AM/PM */
75
+ const READ = {
76
+ money: /^\s*[$€£]?\s*(\d[\d,]*(?:\.\d+)?)/,
77
+ time: /^\s*(\d{1,2}:\d{2}[\s\u202f\u00a0]?[AaPp][Mm])/,
78
+ number: /^\s*(\d[\d,]*(?:\.\d+)?)/,
79
+ };
80
+
81
+ /**
82
+ * R1 reader: the set of values of a fact's shape written right after each occurrence of a label on the page.
83
+ * @param {string[]} lines @param {string} label @param {'money'|'time'|'number'} shape @returns {Set<string>}
84
+ */
85
+ function valueSet(lines, label, shape) {
86
+ /** @type {Set<string>} */
87
+ const s = new Set();
88
+ const p = squash(label).trim();
89
+ if (!p) return s;
90
+ for (const ln of lines) {
91
+ for (let i = ln.indexOf(p); i !== -1; i = ln.indexOf(p, i + p.length)) {
92
+ const m = READ[shape].exec(ln.slice(i + p.length));
93
+ if (m) s.add(m[1]);
94
+ }
95
+ }
96
+ return s;
97
+ }
98
+ /** @param {Set<string>} a @param {Set<string>} b @returns {boolean} */
99
+ const sameSet = (a, b) => a.size === b.size && [...a].every((x) => b.has(x));
100
+
101
+ /** a number as the page writes it: digits, thousands commas, optional decimals (a currency sign next to it is not part of it) */
102
+ const BEFORE = /(\d[\d,]*(?:\.\d+)?)\s*$/;
103
+ const AFTER = /^\s*(?:[$€£]\s*)?(\d[\d,]*(?:\.\d+)?)/;
104
+ const AFTER_CUR = /^\s*(\d[\d,]*(?:\.\d+)?)/;
105
+ const stripCommas = (/** @type {string} */ s) => s.replace(/,/g, '');
106
+
107
+ /** @param {string[]} lines @param {string} w @returns {[string, number][]} every occurrence of w as [its line, where it starts] */
108
+ function occs(lines, w) {
109
+ /** @type {[string, number][]} */
110
+ const out = [];
111
+ for (const l of lines) for (let i = l.indexOf(w); i !== -1; i = l.indexOf(w, i + w.length)) out.push([l, i]);
112
+ return out;
113
+ }
114
+
115
+ /**
116
+ * U1: how many times a label has a number right BEFORE it (whitespace only between) and right AFTER it (whitespace and one currency sign
117
+ * between). A marker the page writes after the number ("490 total") has B > 0 and A = 0.
118
+ * @param {string[]} lines @param {string} label @returns {{B: number, A: number}}
119
+ */
120
+ function beforeAfter(lines, label) {
121
+ let B = 0;
122
+ let A = 0;
123
+ for (const [l, i] of occs(lines, label)) {
124
+ if (BEFORE.test(l.slice(0, i))) B += 1;
125
+ if (AFTER.test(l.slice(i + label.length))) A += 1;
126
+ }
127
+ return { B, A };
128
+ }
129
+ /** R1L: the numbers a UNIT form reads - the one right before each occurrence @param {string[]} lines @param {string} u @returns {Set<string>} */
130
+ const unitSet = (lines, u) => new Set(occs(lines, u).map(([l, i]) => BEFORE.exec(l.slice(0, i))?.[1]).filter((v) => typeof v === 'string').map((v) => stripCommas(/** @type {string} */ (v))));
131
+ /** R1L: the numbers a CURRENCY form reads - the one right after each occurrence @param {string[]} lines @param {string} c @returns {Set<string>} */
132
+ const curSet = (lines, c) => new Set(occs(lines, c).map(([l, i]) => AFTER_CUR.exec(l.slice(i + c.length))?.[1]).filter((v) => typeof v === 'string').map((v) => stripCommas(/** @type {string} */ (v))));
133
+
134
+ /** S1: a fact name that counts results ("the second flight") cannot be checked per result - one result is one record, ask for N results instead */
135
+ const ORDINALS = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'latest', 'earliest', 'newest', 'oldest', 'last', 'next', 'previous', 'final', 'nth'];
136
+
137
+ /** 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 */
138
+ const CURRENCY_SYMBOLS = ['$', '€', '£'];
139
+ /** the shapes that read a value after a label */
140
+ const VALUE_SHAPES = ['money', 'time', 'number'];
141
+
142
+ /**
143
+ * 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.
144
+ * 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.
145
+ * @param {string} text the frozen page text @param {PageMap} mapping @param {{n: number, text?: string, rule?: string, rules?: string[]}[]} jobLines
146
+ * @returns {{facts: KeptFact[], dropped: Dropped[]}}
147
+ */
148
+ export function applyPageRules(text, mapping, jobLines) {
149
+ /** @type {Dropped[]} */
150
+ const dropped = [];
151
+ const all = Array.isArray(mapping?.facts) ? mapping.facts.filter(isRec) : [];
152
+ /** @type {Map<MapFact, {line: number, rule?: number}>} */
153
+ const ties = new Map(all.map((f) => [f, tieOf(f.from, jobLines)]));
154
+ const drop = (/** @type {MapFact} */ f, /** @type {string|undefined} */ word, /** @type {string} */ reason, /** @type {string|undefined} */ other = undefined) => {
155
+ const t = /** @type {{line: number, rule?: number}} */ (ties.get(f));
156
+ dropped.push({ line: t.line, ...(t.rule === undefined ? {} : { rule: t.rule }), fact: String(f.name ?? ''), ...(word === undefined ? {} : { word }), reason, ...(other === undefined ? {} : { other }) });
157
+ };
158
+
159
+ // ---- S1, name part: a fact whose name counts results is refused before anything else reads it ----
160
+ const list = all.filter((f) => {
161
+ const hit = String(f.name ?? '').toLowerCase().split(/[^a-z]+/).find((w) => ORDINALS.includes(w));
162
+ if (hit === undefined) return true;
163
+ drop(f, undefined, 's1-name');
164
+ return false;
165
+ });
166
+
167
+ // ---- found-on-page, then U1 and R1L for the facts that read an amount ----
168
+ const lines = linesOf(text);
169
+ /** @type {{f: MapFact, kept: string[], cur: string[], uni: string[], first?: string|null, anchorless?: boolean}[]} */
170
+ const pending = [];
171
+ for (const f of list) {
172
+ const words = (Array.isArray(f.words) ? f.words : []).map((w) => String(w)).filter((w) => w.trim() !== '');
173
+ if (f.shape === 'place' || f.shape === 'phrase') {
174
+ const kept = [];
175
+ for (const w of words) {
176
+ const n = f.shape === 'phrase' ? countPhrase(text, w) : countExact(text, w);
177
+ if (n >= 1) kept.push(w); else drop(f, w, 'not-on-page');
178
+ }
179
+ pending.push({ f, kept, cur: [], uni: [] });
180
+ } else if (VALUE_SHAPES.includes(String(f.shape))) {
181
+ const amount = f.shape === 'money' || f.shape === 'number';
182
+ /** labels the page holds (and, for an amount, that have a number right after them) */
183
+ const labels = [];
184
+ /** the AI's labels as U1 leaves them, a word the page does not hold included: the first of these is R1's reference */
185
+ const asListed = [];
186
+ /** U1: labels the page writes after the number */
187
+ const moved = [];
188
+ for (const w0 of words) {
189
+ const w = normLabel(w0);
190
+ if (!w) continue;
191
+ if (countExact(text, w) < 1) { asListed.push(w0); drop(f, w0, 'not-on-page'); continue; }
192
+ if (amount) {
193
+ const { B, A } = beforeAfter(lines, w);
194
+ if (A === 0 && B > 0) { moved.push(w); continue; }
195
+ if (A === 0 && B === 0) { drop(f, w, 'no-value'); continue; }
196
+ }
197
+ asListed.push(w0);
198
+ labels.push(w);
199
+ }
200
+ /** @type {string[]} */ let uni = [];
201
+ /** @type {string[]} */ let cur = [];
202
+ if (f.shape === 'money') {
203
+ // the forms: units first (the U1-moved words, then the AI's listed units), then currency signs. SORT, never drop for the box (money
204
+ // 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
205
+ // form the AI listed in either box is pooled and moved to the box its own shape belongs to
206
+ const listedCurrencies = (Array.isArray(f.currency) ? f.currency : []).map(String);
207
+ // a currency SIGN listed in BOTH unit and currency is said once: the unit copy goes (fwd F71 drafts)
208
+ const listedUnits = (Array.isArray(f.unit) ? f.unit : []).map(String).filter((u) => {
209
+ if (!(CURRENCY_SYMBOLS.includes(u) && listedCurrencies.includes(u))) return true;
210
+ drop(f, u, 'sign-twice');
211
+ return false;
212
+ });
213
+ // a WORD listed in both boxes is one form, said once (a record of the double listing is kept, as R1L always said it)
214
+ for (const w of new Set(listedCurrencies.filter((c) => !CURRENCY_SYMBOLS.includes(c) && listedUnits.includes(c)))) drop(f, w, 'r1l', w);
215
+ const pool = [...moved, ...listedUnits, ...listedCurrencies];
216
+ const units = [...new Set(pool.filter((w) => !CURRENCY_SYMBOLS.includes(w)))].filter((u) => {
217
+ if (countPhrase(text, u) >= 1) return true;
218
+ drop(f, u, 'not-on-page');
219
+ return false;
220
+ });
221
+ const curs = [...new Set(pool.filter((w) => CURRENCY_SYMBOLS.includes(w)))].filter((c) => {
222
+ if (countExact(text, c) >= 1) return true;
223
+ drop(f, c, 'not-on-page');
224
+ return false;
225
+ });
226
+ /** @type {{kind: 'unit'|'currency', w: string}[]} */
227
+ const forms = [...units.map((u) => /** @type {const} */ ({ kind: 'unit', w: u })), ...curs.map((c) => /** @type {const} */ ({ kind: 'currency', w: c }))];
228
+ if (forms.length) {
229
+ // R1L: every form reads the same set of numbers as the primary (the first form); one that reads more or fewer is dropped
230
+ const read = (/** @type {{kind: string, w: string}} */ x) => (x.kind === 'unit' ? unitSet(lines, x.w) : curSet(lines, x.w));
231
+ const ps = read(forms[0]);
232
+ const keep = [forms[0]];
233
+ // 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)
234
+ 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); }
235
+ uni = keep.filter((x) => x.kind === 'unit').map((x) => x.w);
236
+ cur = keep.filter((x) => x.kind === 'currency').map((x) => x.w);
237
+ }
238
+ // the guard's list limits (src/facts.js), applied here so a longer list is cut by code and SAID, never refused later: the first forms stay
239
+ uni = uni.filter((u, i) => {
240
+ if (u.length > MAX_UNIT_CHARS) { drop(f, u, 'unit-too-long'); return false; }
241
+ if (i >= MAX_UNITS) { drop(f, u, 'limit-unit'); return false; }
242
+ return true;
243
+ });
244
+ cur = cur.filter((c, i) => {
245
+ if (i < MAX_CURRENCIES) return true;
246
+ drop(f, c, 'limit-currency');
247
+ return false;
248
+ });
249
+ }
250
+ pending.push({ f, kept: labels, cur, uni, first: asListed.length ? normLabel(asListed[0]) : null, anchorless: amount && asListed.length === 0 });
251
+ } else drop(f, undefined, 'bad-shape');
252
+ }
253
+
254
+ // ---- R1, same-value: the labels after the AI's FIRST listed one are kept only if they read the same set of values as it does ----
255
+ for (const p of pending) {
256
+ if (!VALUE_SHAPES.includes(String(p.f.shape))) continue;
257
+ const shape = /** @type {'money'|'time'|'number'} */ (p.f.shape);
258
+ const ref = p.first ? valueSet(lines, p.first, shape) : new Set();
259
+ p.kept = p.kept.filter((w) => {
260
+ if (w === p.first) return true;
261
+ if (sameSet(valueSet(lines, w, shape), ref)) return true;
262
+ drop(p.f, w, 'r1', p.first ?? undefined);
263
+ return false;
264
+ });
265
+ }
266
+
267
+ // ---- N2, per line: a label written 2+ times inside one page line cannot say which value is meant, so it is unusable. (R2 grow-left is OUT.) ----
268
+ for (const p of pending) {
269
+ if (!VALUE_SHAPES.includes(String(p.f.shape))) continue;
270
+ p.kept = p.kept.filter((w) => {
271
+ if (maxPerLine(lines, w) <= 1) return true;
272
+ drop(p.f, w, 'n2');
273
+ return false;
274
+ });
275
+ }
276
+
277
+ // ---- the kept facts, in the POC's order: places, phrases, then values ----
278
+ /** @type {KeptFact[]} */
279
+ const signed = [];
280
+ const make = (/** @type {{f: MapFact, kept: string[], cur: string[], uni: string[]}} */ p) => {
281
+ const t = /** @type {{line: number, rule?: number}} */ (ties.get(p.f));
282
+ /** @type {KeptFact} */
283
+ const out = { line: t.line, name: String(p.f.name), shape: p.f.shape === 'place' ? 'phrase' : String(p.f.shape), from: String(p.f.from ?? ''), words: [...p.kept] };
284
+ if (p.f.shape === 'money') {
285
+ if (p.uni.length) out.unit = [...p.uni];
286
+ if (p.cur.length) out.currency = [...p.cur];
287
+ }
288
+ if (t.rule !== undefined) out.forRule = t.rule;
289
+ if (validReading(out.shape, p.f.reading)) out.reading = /** @type {Reading} */ ({ ...p.f.reading });
290
+ return out;
291
+ };
292
+ for (const kind of ['place', 'phrase', 'value']) {
293
+ for (const p of pending) {
294
+ const isValue = VALUE_SHAPES.includes(String(p.f.shape));
295
+ if (kind === 'value' ? !isValue : p.f.shape !== kind) continue;
296
+ // a fact left with no label is dropped, unless U1 moved every label to a unit/currency form of a money fact (it then reads that form
297
+ // alone); a money fact also needs a currency or a unit the page holds
298
+ const forms = p.cur.length + p.uni.length;
299
+ const ok = p.f.shape === 'money' ? forms > 0 && (p.kept.length > 0 || p.anchorless === true) : p.kept.length > 0;
300
+ if (!ok) { drop(p.f, undefined, 'no-label'); continue; }
301
+ signed.push(make(p));
302
+ }
303
+ }
304
+ // ---- S1, shape and label part: two facts of one result may not share a shape AND a label (they would read the same value and can never differ).
305
+ // The first one stays; a fact with no label is keyed by its first unit or currency, so two different amounts are never confused. ----
306
+ /** @type {Map<string, string>} */
307
+ const seen = new Map();
308
+ const kept = signed.filter((k) => {
309
+ const key = `${k.shape}\u0000${k.words[0] ?? k.unit?.[0] ?? k.currency?.[0] ?? ''}`;
310
+ const first = seen.get(key);
311
+ if (first === undefined) { seen.set(key, k.name); return true; }
312
+ const f = /** @type {MapFact} */ (all.find((x) => String(x.name) === k.name));
313
+ drop(f, undefined, 's1', first);
314
+ return false;
315
+ });
316
+ const order = list.map((f) => String(f.name));
317
+ return { facts: kept.sort((a, b) => order.findIndex((n) => a.name.startsWith(n)) - order.findIndex((n) => b.name.startsWith(n))), dropped };
318
+ }
@@ -38,6 +38,7 @@ import { fileURLToPath } from 'node:url';
38
38
  import {
39
39
  ANSWER_FILE, NOT_CHECKED_FILE, OPEN_QUESTION_SAY, PANEL_DRAFTS_DIR, readQuestions, readoutHeadIndexes, scrub, signDraft,
40
40
  } from '../authoring.js';
41
+ import { ruleOfAnswer } from '../pageask.js';
41
42
  import { checkFlowName, nextRunId, readFileInside, readdirInside } from '../flow.js';
42
43
  import { readModelRecord } from '../flowmodel.js';
43
44
  import { isFwdloopAlive } from '../liveness.js';
@@ -47,7 +48,8 @@ import {
47
48
  import {
48
49
  appendAnswersToJob, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
49
50
  } from './authorcard.js';
50
- import { checkedLines, notCheckedBlock } from '../checked.js';
51
+ import { checkedLines, notCheckedView } from '../checked.js';
52
+ import { csvRolesOf } from '../sheetblock.js';
51
53
  import {
52
54
  readPriceConfig, resolveSlot, resolveUsableModel, tickedLines,
53
55
  } from '../provider.js';
@@ -89,6 +91,8 @@ const LIVE_PHASES = new Set(['drafting', 'revising', 'redrafting']);
89
91
  const ANSWERS_NOT_DRAFTED_SAY = 'Your answers are saved, but the plan was not drafted again with them (the process did not start). Nothing was signed. Draft again from the card.';
90
92
  const REDRAFT_RED_SAY = 'The plan drafted with your answers did not pass the checks. Nothing can be signed until a plan is green. Your answers are kept in the card: change it and draft again.';
91
93
  const BLANK_ANSWER_SAY = 'Write an answer. A question can\'t be skipped; the plan waits for it.';
94
+ /** M10 am2 item 1: the sentence for a blank answer to a question the page look raised (bareloop's words). */
95
+ const LOOK_BLANK_ANSWER_SAY = 'An answer is needed here — there is no skip. Type it in the box below and press Send.';
92
96
  const ONE_LINE_ANSWER_SAY = 'Write the answer on one line. It is added to your job as one guardrail line.';
93
97
  const PLAN_DIR_RE = /^draft-(\d+)$/;
94
98
  const REVISE_RED_SAY = 'The revised plan did not pass the checks. Nothing can be signed until a plan is green. Your edits are kept: change the card and draft again.';
@@ -157,7 +161,8 @@ export function createAuthor(opts) {
157
161
  const running = childRunning(dir);
158
162
  const first = resultOf(dir, 'draft', keys);
159
163
  // a first plan that asked questions (green or red) is read by `withRevises` too: it is the ONE function that decides the phase of every plan
160
- if (first && (first.phase === 'green' || readQuestions(join(dir, 'draft')).questions.length > 0)) return withRevises(base, dir, first, keys);
164
+ const firstQs = first && first.phase !== 'green' ? readQuestions(join(dir, 'draft')) : undefined; // read once; withRevises reuses it
165
+ if (first && (first.phase === 'green' || (firstQs?.questions.length ?? 0) > 0)) return withRevises(base, dir, first, keys, firstQs);
161
166
  if (first) return { ...base, ...first };
162
167
  // no result yet: the child is the only thing that can still produce one
163
168
  if (running) return { ...base, phase: 'drafting' };
@@ -234,9 +239,9 @@ export function createAuthor(opts) {
234
239
  * A red or stopped newest plan means nothing is signable (an older green plan was drafted from a different card), and the card shown is the one
235
240
  * last submitted. `phase` is `revising` / `redrafting` only while the newest plan's child runs. A revise uses one of the 2; an answer redraft
236
241
  * (marked by `redraft-<n>.json`) uses none. One reader of every such fact: each `card-<n>.json`, its folder and log, its questions and answers.
237
- * @param {any} base @param {string} dir @param {any} first the first plan's result (green, or red that asked questions) @param {string[]} keys
242
+ * @param {any} base @param {string} dir @param {any} first the first plan's result (green, or red that asked questions) @param {string[]} keys @param {ReturnType<typeof readQuestions>} [firstQsRead] the first plan's questions when the caller already read them
238
243
  */
239
- function withRevises(base, dir, first, keys) {
244
+ function withRevises(base, dir, first, keys, firstQsRead) {
240
245
  const names = readdirInside(dir, '.');
241
246
  const ns = names.map((n) => CARD_RE.exec(n)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
242
247
  const redrafts = new Set(ns.filter((n) => readJson(dir, `redraft-${n}.json`) !== null));
@@ -262,17 +267,18 @@ export function createAuthor(opts) {
262
267
  });
263
268
  const cur = /** @type {{ phase: string, kind: string, say?: string }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
264
269
  // a first plan that asked questions did not end red, it ended by asking (open or answered): its plan-checks line is never the red one (am15 item 3)
265
- const asked = readQuestions(join(dir, 'draft')).questions.length > 0;
270
+ const firstQs = firstQsRead ?? readQuestions(join(dir, 'draft')); // the first plan's questions, read once per poll
271
+ const asked = firstQs.questions.length > 0;
266
272
  const shared = { ...base, card, revises, revisesLeft, stepList: asked ? stepListOf(dir, 'draft', keys, true) : (first.stepList ?? null) };
267
273
  const rel = newest > 0 ? `draft-${newest}` : 'draft';
268
274
  if (cur.phase === 'running') return { ...shared, phase: cur.kind === 'answers' ? 'redrafting' : 'revising' };
269
275
  if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say };
270
276
  const res = newest > 0 ? resultOf(dir, rel, keys) : first;
271
277
  // the plan's questions: any open one makes the phase `questions-open`, whatever colour the plan is (the answers are what it was waiting for)
272
- const q = readQuestions(join(dir, rel));
278
+ const q = rel === 'draft' ? firstQs : readQuestions(join(dir, rel));
273
279
  if (q.open.length > 0) {
274
280
  const lineText = (line) => parseJobBox(typeof card?.job === 'string' ? card.job : '').steps[line - 1]?.text ?? null;
275
- const questions = q.questions.map((x) => ({ k: x.k, line: x.line, lineText: lineText(x.line), question: scrub(x.question, keys), answered: x.answer !== null }));
281
+ const questions = q.questions.map((x) => ({ k: x.k, line: x.line, lineText: lineText(x.line), question: scrub(x.question, keys), answered: x.answer !== null, ...(x.source === 'look' ? { source: 'look' } : {}) }));
276
282
  return { ...shared, stepList: stepListOf(dir, rel, keys, true), phase: 'questions-open', plan: rel, questions, openK: q.open[0].k, total: q.questions.length };
277
283
  }
278
284
  if (q.questions.length > 0) return { ...shared, phase: 'stopped', say: ANSWERS_NOT_DRAFTED_SAY };
@@ -291,8 +297,8 @@ export function createAuthor(opts) {
291
297
  const decl = readJson(dir, `${rel}/declaration.json`);
292
298
  const prose = readFileInside(dir, `${rel}/prose.txt`);
293
299
  const parsed = prose.ok ? parseSignedText(prose.text) : null;
294
- const opts = parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line) } : { hasAsk: true };
295
- return { checked: checkedLines(decl, opts), notChecked: notCheckedBlock(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked) };
300
+ const opts = parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line), lines: parsed.lines, csvRoles: csvRolesOf(parsed.arbiter) } : { hasAsk: true };
301
+ return { checked: checkedLines(decl, opts), notChecked: notCheckedView(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked, decl) };
296
302
  }
297
303
 
298
304
  /** The answers an answer-redraft was drafted with, as the marker recorded them: `[{ line, lineText, question, answer }]` (scrubbed). @param {string} dir @param {number} n @param {string[]} keys */
@@ -697,22 +703,34 @@ export function createAuthor(opts) {
697
703
  if (v.phase !== 'questions-open') return { status: 409, body: { ok: false, refused: 'no-question-open', say: 'This draft has no question waiting for an answer.' } };
698
704
  const b = body && typeof body === 'object' ? body : {};
699
705
  if (b.k !== v.openK) return { status: 409, body: { ok: false, refused: 'stale-question', say: 'That is not the question now open. Reload and answer the one shown.' } };
700
- const answer = typeof b.answer === 'string' ? b.answer.trim() : '';
701
- if (answer === '') return { status: 400, body: { ok: false, refused: 'blank-answer', say: BLANK_ANSWER_SAY } };
702
- if (/[\r\n]/.test(answer)) return { status: 400, body: { ok: false, refused: 'one-line', say: ONE_LINE_ANSWER_SAY } };
706
+ const planDir = join(dir, v.plan);
707
+ const full = readQuestions(planDir).questions;
708
+ const q = full.find((x) => x.k === v.openK);
709
+ if (q === undefined) return { status: 409, body: { ok: false, refused: 'stale-question', say: 'That is not the question now open. Reload and answer the one shown.' } };
710
+ // M10 piece 3 (am2): a question the page look raised takes bareloop's answer words. A blank answer gets bareloop's sentence; a newline is folded to a
711
+ // space (one `~` line is one line) instead of refused. Every other question keeps its own gate (blank, one line).
712
+ const look = q.source === 'look';
713
+ const answer = typeof b.answer === 'string' ? (look ? b.answer.replace(/\s*\n\s*/g, ' ') : b.answer).trim() : '';
714
+ if (answer === '') return { status: 400, body: { ok: false, refused: 'blank-answer', say: look ? LOOK_BLANK_ANSWER_SAY : BLANK_ANSWER_SAY } };
715
+ if (!look && /[\r\n]/.test(answer)) return { status: 400, body: { ok: false, refused: 'one-line', say: ONE_LINE_ANSWER_SAY } };
703
716
  if (keys.some((k) => k.length >= 8 && answer.includes(k))) return { status: 400, body: { ok: false, refused: 'key', say: 'This answer contains an API key. Keys go in Settings only. Nothing was saved.' } };
704
717
  if (childRunning(dir)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'The draft process is still finishing. Try again in a moment.' } };
705
- const planDir = join(dir, v.plan);
706
- const q = v.questions.find((x) => x.k === v.openK);
707
718
  const last = v.questions.filter((x) => !x.answered).length === 1;
708
719
  const answerFile = join(planDir, ANSWER_FILE(v.openK));
720
+ const at = new Date().toISOString();
721
+ // what this answer does (ruleOfAnswer, the one place): the `~` rule it adds, or the rule it leaves Not checked
722
+ const effect = ruleOfAnswer(q, answer);
709
723
  // the whole redraft is checked at $0 BEFORE the answer is written, so a refusal leaves the question open and nothing on disk
710
724
  /** @type {any} */
711
725
  let redraft = null;
712
726
  if (last) {
713
- const all = readQuestions(planDir).questions.map((x) => ({ line: x.line, question: x.question, answer: x.k === v.openK ? answer : x.answer }));
714
- const grown = appendAnswersToJob(typeof v.card.job === 'string' ? v.card.job : '', /** @type {{line:number, answer:string}[]} */ (all));
715
- if (grown.added !== all.length) return { status: 409, body: { ok: false, refused: 'no-such-line', say: 'An answer is about a job line the card no longer has. Draft again from the card. Nothing was signed.' } };
727
+ const all = full.map((x) => {
728
+ const typed = x.k === v.openK ? answer : x.answer;
729
+ return { line: x.line, question: x.question, answer: typed, ...ruleOfAnswer(x, typed), ruleNo: x.ruleNo };
730
+ });
731
+ const adds = all.filter((x) => x.rule !== null);
732
+ const grown = appendAnswersToJob(typeof v.card.job === 'string' ? v.card.job : '', adds.map((x) => ({ line: x.line, answer: /** @type {string} */ (x.rule) })));
733
+ if (grown.added !== adds.length) return { status: 409, body: { ok: false, refused: 'no-such-line', say: 'An answer is about a job line the card no longer has. Draft again from the card. Nothing was signed.' } };
716
734
  const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card));
717
735
  if (!vet.ok) return vet.reply;
718
736
  for (const other of listIds()) {
@@ -720,10 +738,14 @@ export function createAuthor(opts) {
720
738
  const ov = view(other, keys);
721
739
  if (ov && LIVE_PHASES.has(ov.phase)) return { status: 409, body: { ok: false, refused: 'draft-live', draftId: other, say: 'A draft is already running. Wait for it, or abandon it, before answering.' } };
722
740
  }
723
- redraft = { vet, all };
741
+ redraft = { vet, all, left: all.filter((x) => x.left).map((x) => ({ line: x.line, rule: x.ruleNo })) };
724
742
  }
725
743
  try {
726
- writeFileSync(answerFile, `${JSON.stringify({ k: v.openK, line: q.line, question: q.question, answer, at: new Date().toISOString() })}\n`, { mode: 0o600, flag: 'wx' });
744
+ // the human row of the draft log (am2 item 4): the question, the answer, the line, the time; a look ask also carries what code proposed and the rule the answer added, as their own fields
745
+ writeFileSync(answerFile, `${JSON.stringify({
746
+ k: v.openK, line: q.line, question: q.question, answer, at,
747
+ ...(look ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: q.proposal ?? null, rule: effect.rule } : {}),
748
+ })}\n`, { mode: 0o600, flag: 'wx' });
727
749
  } catch (e) {
728
750
  return { status: 409, body: { ok: false, refused: 'already-answered', say: /** @type {any} */ (e)?.code === 'EEXIST' ? 'That question already has an answer.' : 'The answer could not be saved. Nothing was sent.' } };
729
751
  }
@@ -735,10 +757,10 @@ export function createAuthor(opts) {
735
757
  try {
736
758
  writeFileSync(files[0], `${JSON.stringify(redraft.vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
737
759
  writeFileSync(files[1], redraft.vet.prose, { mode: 0o600, flag: 'wx' });
738
- writeFileSync(files[2], `${JSON.stringify({ fromPlan: v.plan, answers: redraft.all.map((x) => ({ line: x.line, question: x.question, answer: x.answer })) })}\n`, { mode: 0o600, flag: 'wx' });
760
+ writeFileSync(files[2], `${JSON.stringify({ fromPlan: v.plan, answers: redraft.all.map((x) => ({ line: x.line, question: x.question, answer: x.answer })), ...(redraft.left.length ? { left: redraft.left } : {}) })}\n`, { mode: 0o600, flag: 'wx' });
739
761
  child = spawnDetached({
740
762
  bin,
741
- argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions', ...modelArgv(redraft.vet.card)],
763
+ argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions', ...(redraft.left.length ? ['--left', redraft.left.map((x) => `${x.line}.${x.rule}`).join(',')] : []), ...modelArgv(redraft.vet.card)],
742
764
  env: loaded.env,
743
765
  logPath: join(dir, `redraft-${n}.log`),
744
766
  });
@@ -15,6 +15,7 @@ import {
15
15
  import { isAbsolute, join } from 'node:path';
16
16
 
17
17
  import { checkFlowName } from '../flow.js';
18
+ import { isWebUrl } from '../pagefetch.js';
18
19
  import { checkSendDestination } from '../runner.js';
19
20
  import { parseSignedText } from '../signed-text.js';
20
21
  import { capTooSmallText } from '../draftspend.js';
@@ -87,7 +88,8 @@ export function parseJobBox(text) {
87
88
  * M4e amendment 24 item 3: the submitted job box with each answer added WORD FOR WORD as a `~` line under the job line it is about, after
88
89
  * that line's own `~` lines (several answers for one line keep their order). The job box's own lines are untouched; the card -> prose path
89
90
  * (`cardToProse`) then writes the answer as that line's guardrail, so it reaches the signed text and the hash. Pure. An answer for a line
90
- * the box does not have is NOT added (the caller sees the count).
91
+ * the box does not have is NOT added (the caller sees the count). An answer equal (exact string, after trim) to a `~` rule already on that line is not added
92
+ * again, and still counts: it is taken, the line already says it.
91
93
  * @param {string} job @param {{ line: number, answer: string }[]} answers
92
94
  * @returns {{ job: string, added: number }}
93
95
  */
@@ -95,12 +97,15 @@ export function appendAnswersToJob(job, answers) {
95
97
  const raw = String(job).split('\n');
96
98
  /** @type {Map<number, number>} the index of the last non-empty box line that belongs to each step (its own line or a `~` under it) */
97
99
  const lastOf = new Map();
100
+ /** @type {Map<number, Set<string>>} the `~` rules each step already has */
101
+ const have = new Map();
98
102
  let step = 0;
99
103
  raw.forEach((l, i) => {
100
104
  const t = l.trim();
101
105
  if (t === '') return;
102
106
  if (!t.startsWith('~')) step += 1;
103
107
  if (step > 0) lastOf.set(step, i);
108
+ if (step > 0 && t.startsWith('~')) have.set(step, (have.get(step) ?? new Set()).add(t.slice(1).trim()));
104
109
  });
105
110
  /** @type {Map<number, string[]>} */
106
111
  const after = new Map();
@@ -108,8 +113,11 @@ export function appendAnswersToJob(job, answers) {
108
113
  for (const a of answers) {
109
114
  if (!lastOf.has(a.line)) continue;
110
115
  const at = /** @type {number} */ (lastOf.get(a.line));
111
- after.set(at, [...(after.get(at) ?? []), `~ ${a.answer}`]);
112
116
  added += 1;
117
+ const rules = have.get(a.line) ?? new Set();
118
+ if (rules.has(a.answer.trim())) continue;
119
+ have.set(a.line, rules.add(a.answer.trim()));
120
+ after.set(at, [...(after.get(at) ?? []), `~ ${a.answer}`]);
113
121
  }
114
122
  const out = [];
115
123
  raw.forEach((l, i) => { out.push(l); for (const g of after.get(i) ?? []) out.push(g); });
@@ -177,6 +185,11 @@ export function cardFields(body) {
177
185
  };
178
186
  }
179
187
 
188
+ /** M10 am3: is this web address whole (a host after the scheme, no spaces)? The ONE reader of a typed page address. @param {string} v */
189
+ export function pageAddressOk(v) {
190
+ return /^https?:\/\/[^\s/?#]+\S*$/i.test(v);
191
+ }
192
+
180
193
  /** The Run-a-signed-flow door's rows (a role is fixed by the signed flow): what the page sent, as `{role, path}`. @param {any} v */
181
194
  export function runInputRows(v) {
182
195
  return (Array.isArray(v) ? v : []).map((r) => ({ role: str(r?.role).trim(), path: str(r?.path).trim() }));
@@ -193,7 +206,7 @@ export function cardToProse(card) {
193
206
  const out = [...jobFileLines(steps, card.askWait), '', ARBITER_HEADING];
194
207
  out.push(`guardrail: cap $${capText(Number(card.capUsd))} per run`);
195
208
  if (card.destination !== '') out.push(`guardrail: send at line ${steps.length} to file:${card.destination}`);
196
- for (const i of parseInputLines(card.inputs)) out.push(`guardrail: source ${i.role} = file:${i.path}`);
209
+ for (const i of parseInputLines(card.inputs)) out.push(`guardrail: source ${i.role} = ${isWebUrl(i.path) ? 'page' : 'file'}:${i.path}`); // M10 am3: a web address is a page
197
210
  return `${out.join('\n')}\n`;
198
211
  }
199
212
 
@@ -279,6 +292,10 @@ export function checkInputRows(rows) {
279
292
  seen.add(row.role);
280
293
  if (row.path === '') { no(`The input "${row.role}" has a role but no path.`); return; }
281
294
  if (CONTROL_RE.test(row.path)) { no(`The path for "${row.role}" has a character that cannot be in a path.`); return; }
295
+ if (isWebUrl(row.path)) { // M10 am3: a web page's address is signed with the job; there is no file to look at
296
+ if (!pageAddressOk(row.path)) no(`The address for "${row.role}" must be a full http:// or https:// address with no spaces.`);
297
+ return;
298
+ }
282
299
  if (!isAbsolute(row.path)) { no(`The path for "${row.role}" must be a full path starting with "/".`); return; }
283
300
  const why = fileProblem(row.path);
284
301
  if (why) no(`The path for "${row.role}" ${why}`);