fwdloop 0.28.0 → 0.30.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 (74) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +27 -5
  3. package/package.json +3 -3
  4. package/src/added-end.js +60 -0
  5. package/src/ask.js +1 -1
  6. package/src/audit-fold.js +9 -1
  7. package/src/authoring.js +18 -7
  8. package/src/checked.js +14 -9
  9. package/src/checkpick.js +318 -0
  10. package/src/checkwords.js +29 -0
  11. package/src/citedcheck.js +14 -0
  12. package/src/closers.js +40 -3
  13. package/src/declaration.js +102 -5
  14. package/src/draft-steps.js +3 -3
  15. package/src/drafter.js +151 -38
  16. package/src/jobkey.js +3 -1
  17. package/src/learn.js +1 -1
  18. package/src/learnstore.js +6 -6
  19. package/src/memo.js +120 -0
  20. package/src/model-step.js +103 -25
  21. package/src/pageask.js +12 -6
  22. package/src/pagedropwords.js +9 -0
  23. package/src/panel/author.js +33 -10
  24. package/src/panel/authorcard.js +59 -6
  25. package/src/panel/data.js +16 -10
  26. package/src/panel/index.html +151 -59
  27. package/src/panel/result.js +28 -7
  28. package/src/panel/server.js +2 -1
  29. package/src/pickrecord.js +146 -0
  30. package/src/plain-checks.js +16 -3
  31. package/src/provider.js +4 -1
  32. package/src/repairs.js +38 -0
  33. package/src/runfile.js +4 -2
  34. package/src/runner.js +129 -40
  35. package/src/send.js +71 -4
  36. package/src/setup.js +13 -1
  37. package/src/sheetblock.js +2 -1
  38. package/src/ticket-draft.js +2 -2
  39. package/src/ticket-labels.js +2 -2
  40. package/src/try-checks.js +13 -3
  41. package/src/whole-job.js +71 -0
  42. package/types/added-end.d.ts +62 -0
  43. package/types/ask.d.ts +2 -1
  44. package/types/audit-fold.d.ts +13 -2
  45. package/types/authoring.d.ts +6 -2
  46. package/types/checked.d.ts +7 -2
  47. package/types/checkpick.d.ts +183 -0
  48. package/types/checkwords.d.ts +18 -0
  49. package/types/citedcheck.d.ts +6 -0
  50. package/types/closers.d.ts +6 -3
  51. package/types/declaration.d.ts +12 -0
  52. package/types/drafter.d.ts +28 -25
  53. package/types/learn.d.ts +1 -0
  54. package/types/learnstore.d.ts +2 -3
  55. package/types/memo.d.ts +15 -0
  56. package/types/model-step.d.ts +23 -3
  57. package/types/pageask.d.ts +9 -2
  58. package/types/pagedropwords.d.ts +1 -0
  59. package/types/panel/author.d.ts +1 -1
  60. package/types/panel/authorcard.d.ts +41 -0
  61. package/types/panel/data.d.ts +1 -1
  62. package/types/panel/jobgrid.d.ts +1 -1
  63. package/types/panel/result.d.ts +9 -3
  64. package/types/pickrecord.d.ts +88 -0
  65. package/types/plain-checks.d.ts +9 -1
  66. package/types/repairs.d.ts +13 -0
  67. package/types/runfile.d.ts +7 -2
  68. package/types/runner.d.ts +16 -5
  69. package/types/send.d.ts +10 -2
  70. package/types/setup.d.ts +1 -56
  71. package/types/try-checks.d.ts +1 -7
  72. package/types/whole-job.d.ts +70 -0
  73. package/src/attemptdiff.js +0 -118
  74. package/types/attemptdiff.d.ts +0 -38
@@ -0,0 +1,318 @@
1
+ // M10 amendment 16 (docs/wiki/the-module-ladder.md "M10 amendment 16"): shape guardrails are settled the way item 3-4 settle a source's words.
2
+ // One AI call suggests, per guardrail, ONE check from bareguard's own list (`rubricVocabulary`) or none; CODE keeps a suggestion only if its rule is on
3
+ // the list, every number is one the guardrail names and every word is a word of the guardrail; the person picks (src/drafter.js asks, src/panel/author.js
4
+ // takes the answer); the plan carries only the checks picked. The drafter writes no check of its own.
5
+ // The prompt, the per-rule answer form and the keep-or-drop are the ones F144c proved (docs/logs/FINDINGS.md F144c).
6
+ // Throws away: a suggestion's `id`, `field`, `strict`, `text` (code sets them, or they never decide); every guardrail that code scopes out; what the model says in words.
7
+ import { rubricVocabulary } from 'bareguard';
8
+ import { lineRules } from './pagebits.js';
9
+ import { isCellsPath } from './closers.js';
10
+ import { plainWords, OFFERED } from './checkwords.js';
11
+
12
+ export { plainWords, OFFERED };
13
+ import { guardrailWordNumbers, guardrailStandaloneNumbers, guardrailWordsPerSection, guardrailSectionCount, guardrailItemCount, isCountGuardrail } from './declaration.js';
14
+
15
+ /** the one tool the suggestion call is forced to use */
16
+ export const SUGGEST_TOOL = 'suggest_checks';
17
+ const VOCAB = /** @type {Record<string, {description: string, fields: Record<string, {type: string, required?: boolean}>}>} */ (rubricVocabulary.rules);
18
+ /** fields code sets, or that never decide: never offered, never kept */
19
+ const IGNORED = new Set(['id', 'field', 'text', 'strict']);
20
+ const NUM_FIELDS = ['value', 'size', 'wordsPerSection'];
21
+ const WORD_FIELDS = ['names', 'phrases'];
22
+
23
+ // ---- scope, decided by CODE before the call ------------------------------------------------------------------------------------------------
24
+ /** @param {any[]|undefined} sources the job's signed inputs @returns {boolean} a CSV file or a web page routes its guardrails to another signed part (M10 items 1-3, M12) */
25
+ export const hasRoutingInput = (sources) => (sources ?? []).some((s) => (s.kind === 'file' && isCellsPath(s.path)) || s.kind === 'page');
26
+ /**
27
+ * A guardrail goes to this call unless the job signs an input that routes its guardrails elsewhere AND the guardrail is not a count code can check (M10 am23: words, items, sections)
28
+ * (the one thing the shape reader still takes in such a job). A page job whose guardrail is a count therefore counts as in (F144b caveat).
29
+ * @param {any[]|undefined} sources @param {string} g @returns {'in'|'out'}
30
+ */
31
+ export const codeScope = (sources, g) => (hasRoutingInput(sources) && !isCountGuardrail(g) ? 'out' : 'in');
32
+
33
+ /**
34
+ * Every guardrail rule on a step line (not a signed ask or send line) that this call settles, in line order. `rule` is the rule's number on its line (the one
35
+ * number `leftRules`, `ruleNo` and the answers use); a repeated text on a line is one rule here, asked once.
36
+ * @param {{n: number, guardrail?: string}[]} lines `parseSignedText`'s lines @param {{asks?: {line: number}[], sends?: {line: number}[], sources?: any[]}} arbiter
37
+ * @returns {{line: number, rule: number, text: string}[]}
38
+ */
39
+ export function scopedRules(lines, arbiter) {
40
+ const skip = new Set([...(arbiter?.asks ?? []), ...(arbiter?.sends ?? [])].map((x) => x.line));
41
+ /** @type {{line: number, rule: number, text: string}[]} */
42
+ const out = [];
43
+ for (const l of Array.isArray(lines) ? lines : []) {
44
+ if (skip.has(l.n)) continue;
45
+ const seen = new Set();
46
+ lineRules({ rule: l.guardrail }).forEach((text, i) => {
47
+ const key = text.trim().toLowerCase();
48
+ if (seen.has(key) || codeScope(arbiter?.sources, text) !== 'in') return;
49
+ seen.add(key);
50
+ out.push({ line: l.n, rule: i + 1, text });
51
+ });
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /**
57
+ * The rules the suggestion call offers for a draft: `scopedRules` less the ones a kept page or sheet fact already serves (the look tied it: line + rule number).
58
+ * @param {{n: number, guardrail?: string}[]} lines @param {any} arbiter @param {{line: number, forRule?: number}[]} facts `look.facts` + the sheets' facts
59
+ */
60
+ export const offerRules = (lines, arbiter, facts) => scopedRules(lines, arbiter).filter((r) => isCountGuardrail(r.text) || !facts.some((f) => f.line === r.line && f.forRule === r.rule));
61
+
62
+ // ---- code's keep-or-drop (am16 (2)) --------------------------------------------------------------------------------------------------------
63
+ const norm = (/** @type {unknown} */ t) => String(t).toLowerCase().replace(/\s+/g, ' ').trim();
64
+ const tokens = (/** @type {unknown} */ t) => new Set(norm(t).match(/[\p{L}\p{N}]+/gu) ?? []);
65
+
66
+ /**
67
+ * Keep a suggestion only if its rule is on bareguard's list, it carries only that rule's own fields, every number in it is a number the guardrail names and
68
+ * every word in it is a word of the guardrail. Anything else is dropped, with the reason. `none` is a drop with the reason `none`.
69
+ * @param {string} guardrail @param {any} sug the model's entry for this guardrail
70
+ * @returns {{kept: true, check: Record<string, any>}|{kept: false, why: string}}
71
+ */
72
+ export function keepOrDrop(guardrail, sug) {
73
+ if (sug == null || typeof sug !== 'object') return { kept: false, why: 'unreadable suggestion' };
74
+ const { rule } = sug;
75
+ if (rule === 'none' || rule === undefined || rule === null) return { kept: false, why: 'none' };
76
+ if (typeof rule !== 'string' || !Object.hasOwn(VOCAB, rule)) return { kept: false, why: `rule "${rule}" is not on bareguard's list` };
77
+ if (!OFFERED.includes(rule)) return { kept: false, why: `rule "${rule}" is on bareguard's list but is not offered here` };
78
+ const own = Object.keys(VOCAB[rule].fields).filter((k) => !IGNORED.has(k));
79
+ for (const k of own) if (VOCAB[rule].fields[k].required && sug[k] == null) return { kept: false, why: `${rule} needs ${k}` };
80
+ const allowed = new Set([...own, 'rule', 'line', 'guardrail']);
81
+ for (const k of Object.keys(sug)) if (sug[k] != null && !allowed.has(k)) return { kept: false, why: `${rule} does not take ${k}` };
82
+ /** @type {Record<string, any>} */
83
+ const check = { rule };
84
+ for (const k of own) {
85
+ const v = sug[k];
86
+ if (v == null) continue;
87
+ if (NUM_FIELDS.includes(k)) {
88
+ if (!Number.isInteger(v) || v < 1) return { kept: false, why: `${k} ${JSON.stringify(v)} is not a whole number >= 1` };
89
+ const named = rule === 'maxWords' || rule === 'minWords' ? guardrailWordNumbers(guardrail)
90
+ : k === 'wordsPerSection' ? [guardrailWordsPerSection(guardrail)].filter((x) => x !== null)
91
+ : guardrailStandaloneNumbers(guardrail);
92
+ if (!named.includes(v)) return { kept: false, why: `${k} ${v} is not a number the guardrail names (${named.join(', ') || 'it names none'})` };
93
+ check[k] = v;
94
+ } else if (WORD_FIELDS.includes(k)) {
95
+ if (!Array.isArray(v) || v.length === 0 || v.some((s) => typeof s !== 'string' || s.trim() === '')) return { kept: false, why: `${k} is not a list of words` };
96
+ const gTok = tokens(guardrail);
97
+ const gNorm = norm(guardrail);
98
+ for (const s of v) {
99
+ if (!gNorm.includes(norm(s))) return { kept: false, why: `${k} "${s}" is not in the guardrail's words` };
100
+ for (const t of tokens(s)) if (!gTok.has(t)) return { kept: false, why: `${k} word "${t}" is not a word of the guardrail` };
101
+ }
102
+ check[k] = v;
103
+ }
104
+ }
105
+ if (rule === 'sections' || rule === 'sectionOrder' || rule === 'sectionWords') {
106
+ const want = guardrailSectionCount(guardrail);
107
+ if (want !== null && check.names.length !== want) return { kept: false, why: `the guardrail says ${want} sections; the check has ${check.names.length}` };
108
+ }
109
+ return { kept: true, check };
110
+ }
111
+
112
+ // ---- the call: prompt, answer form -------------------------------------------------------------------------------------------------------
113
+ const vocabBlock = OFFERED.map((r) => `- ${VOCAB[r].description}`).join('\n');
114
+ export const SUGGEST_SYSTEM = `You help a person turn the guardrails written under the lines of a job into mechanical checks.
115
+ You are given the job's lines. Under a line, its guardrails are numbered g1, g2, ... You are also given the checks the checker can run.
116
+
117
+ For EACH guardrail, call ${SUGGEST_TOOL} with one entry: the one check from the list that checks exactly what that guardrail says, or the rule "none".
118
+
119
+ Rules:
120
+ - Use only a rule from the list below, with only the fields that rule takes. Do not set id, field, strict or text: code sets them.
121
+ - Use only numbers the guardrail itself states, and only words the guardrail itself contains. Never add a section name, phrase or number the guardrail does not state.
122
+ - Suggest \`sections\` or \`sectionWords\` only when the guardrail itself names the sections.
123
+ - A guardrail like 'all under N words' or 'under N words' is about the whole answer: use maxWords N.
124
+ - If no check on the list checks exactly what the guardrail says (it is about content, sources, prices, columns, or a count the list cannot check exactly), answer "none". A check that is weaker than, or different from, the guardrail is worse than "none".
125
+ - Answer for every guardrail once, using the line number and the guardrail number shown.
126
+
127
+ Checks the checker can run (rule({ fields })):
128
+ ${vocabBlock}`;
129
+
130
+ /**
131
+ * The user message: the job's lines, and under a line only the guardrails this call settles, numbered by their rule number on the line.
132
+ * @param {{n: number, text: string}[]} lines @param {{line: number, rule: number, text: string}[]} scoped @returns {string}
133
+ */
134
+ export function suggestUserText(lines, scoped) {
135
+ const out = ['The job:'];
136
+ for (const l of lines) {
137
+ out.push(`${l.n}. ${l.text}`);
138
+ for (const s of scoped) if (s.line === l.n) out.push(` g${s.rule}: ${s.text}`);
139
+ }
140
+ return out.join('\n');
141
+ }
142
+
143
+ const JSON_TYPE = { integer: { type: 'integer', minimum: 1 }, 'string-list': { type: 'array', minItems: 1, items: { type: 'string' } } };
144
+ /** @param {string} rule @returns {object} one variant of the answer form: exactly that rule's own fields, nothing else */
145
+ function variant(rule) {
146
+ /** @type {Record<string, any>} */
147
+ const properties = { line: { type: 'integer', description: 'the job line number' }, guardrail: { type: 'integer', description: 'the guardrail number under that line (g1 = 1)' }, rule: { const: rule } };
148
+ const required = ['line', 'guardrail', 'rule'];
149
+ if (rule !== 'none') {
150
+ for (const [k, f] of Object.entries(VOCAB[rule].fields)) {
151
+ if (IGNORED.has(k)) continue;
152
+ properties[k] = /** @type {Record<string, any>} */ (JSON_TYPE)[f.type];
153
+ if (f.required) required.push(k);
154
+ }
155
+ }
156
+ return { type: 'object', properties, required, additionalProperties: false };
157
+ }
158
+ /** the forced tool's parameter schema: one `anyOf` variant per offered rule, plus `none` */
159
+ export const SUGGEST_SCHEMA = Object.freeze({
160
+ type: 'object',
161
+ properties: { checks: { type: 'array', description: 'One entry per guardrail.', items: { anyOf: [...OFFERED, 'none'].map(variant) } } },
162
+ required: ['checks'],
163
+ additionalProperties: false,
164
+ });
165
+
166
+ /**
167
+ * What the call's answer comes to, one row per scoped guardrail: the check kept (or null) and why it was dropped. A guardrail the answer never mentions is
168
+ * dropped as `no entry`; an entry for a guardrail that was not sent is ignored.
169
+ * @param {{line: number, rule: number, text: string}[]} scoped @param {any} args the tool call's arguments
170
+ * @returns {{line: number, rule: number, text: string, check: Record<string, any>|null, why: string|null}[]}
171
+ */
172
+ export function rowsFromAnswer(scoped, args) {
173
+ const entries = Array.isArray(args?.checks) ? args.checks : [];
174
+ return scoped.map((s) => {
175
+ const e = entries.find((/** @type {any} */ x) => x?.line === s.line && x?.guardrail === s.rule);
176
+ const res = e === undefined ? /** @type {ReturnType<typeof keepOrDrop>} */ ({ kept: false, why: 'no entry' }) : keepOrDrop(s.text, e);
177
+ if (res.kept) return { ...s, check: res.check, why: null };
178
+ // M10 am27 (3): a count rule is never "I can't check this"; with nothing kept from the call, CODE proposes the check its own readers name
179
+ const own = countCheck(s.text);
180
+ return { ...s, check: own, why: own ? null : res.why };
181
+ });
182
+ }
183
+
184
+ // borrowed-from: bareloop src/checkpick.js@0408a8f (countCheck, 5a81681; one reader file differs: fwdloop's declaration.js has the same three readers)
185
+ /**
186
+ * The check CODE proposes for a count rule when the call yields none: a bullets / list-items / points count -> listItems N, a lines count -> maxLines N, ONE word number ->
187
+ * minWords N when the rule says "at least / minimum / more than", else maxWords N. A section count names no sections, so none is built; a rule naming two different counts is
188
+ * not built either; a rule with several word numbers or a range is not guessed. The result passes `keepOrDrop`, so every number is one the rule names.
189
+ * @param {string} text @returns {Record<string, any>|null}
190
+ */
191
+ export function countCheck(text) {
192
+ const items = guardrailItemCount(text);
193
+ const words = guardrailWordNumbers(text);
194
+ /** @type {Record<string, any>|null} */
195
+ let built = null;
196
+ if (items !== null && (words.length > 0 || guardrailSectionCount(text) !== null)) return null;
197
+ if (items !== null) built = { rule: /\blines?\b/i.test(text) && !/\b(bullets?|items?|points?)\b/i.test(text) ? 'maxLines' : 'listItems', value: items };
198
+ else if (words.length === 1 && !/\bbetween\b|\d\s*(?:-|–|to)\s*\d/i.test(text)) built = { rule: /\b(at least|min(?:imum)?|more than|over|no fewer than)\b/i.test(text) ? 'minWords' : 'maxWords', value: words[0] };
199
+ if (built === null) return null;
200
+ const res = keepOrDrop(text, built);
201
+ return res.kept ? res.check : null;
202
+ }
203
+
204
+ // ---- the asks (words are item 4's) -----------------------------------------------------------------------------------------------------
205
+ /** the can't-check ask, as the signed words say it */
206
+ export const CANT_CHECK_WORDS = "I can't check this. Your own words, or Not checked?";
207
+ /** how every answer is told, once (am2 item 2's words) */
208
+ const HOW_TO_ANSWER = (/** @type {number} */ line, /** @type {boolean} */ agree) => `${agree ? 'Answer "agree" to use it, or type your own words' : 'Type your own words'} (your answer is added as a new ~ rule on line ${line}), or answer "drop it" to leave it Not checked.`;
209
+
210
+ /**
211
+ * The asks for the rows: `Line n, guardrail "<…>": I propose <check in plain words>.` for a kept check, `Line n, guardrail "<…>": I can't check this. Your own words, or
212
+ * Not checked?` when nothing was kept. A proposal is not counted toward am1's cap; a can't-check ask is (am16 (5)).
213
+ * @param {ReturnType<typeof rowsFromAnswer>} rows
214
+ * @returns {{pairRule?: number, line: number, rule: number, source: 'look', ask: 'check'|'no-check', ruleText: string, question: string, reading?: string, check?: Record<string, any>, counted: boolean}[]}
215
+ */
216
+ export function checkAsks(rows) {
217
+ return rows.map((r) => {
218
+ const pair = typeof (/** @type {any} */ (r).pairRule) === 'number' ? { pairRule: /** @type {any} */ (r).pairRule } : {}; // M10 am21: the asked line is an edited added line
219
+ if (r.check === null) {
220
+ return { ...pair, line: r.line, rule: r.rule, source: 'look', ask: 'no-check', ruleText: r.text, counted: true, question: `Line ${r.line}, guardrail "${r.text}": ${CANT_CHECK_WORDS} ${HOW_TO_ANSWER(r.line, false)}` };
221
+ }
222
+ const words = plainWords(/** @type {any} */ (r.check));
223
+ return { ...pair, line: r.line, rule: r.rule, source: 'look', ask: 'check', ruleText: r.text, counted: false, reading: words, check: r.check, question: `Line ${r.line}, guardrail "${r.text}": I propose ${words}. ${HOW_TO_ANSWER(r.line, true)}` };
224
+ });
225
+ }
226
+
227
+ // ---- the plan uses only the checks you picked (am16 (4)) -------------------------------------------------------------------------------------
228
+ /**
229
+ * @typedef {{line: number, rule: number, check: Record<string, any>|null, added?: string, own?: boolean}} Pick
230
+ * `check` = the check the person agreed to (null for their own words); `added` = the `~` rule the answer wrote on the line; `own` = their own words
231
+ */
232
+ /**
233
+ * Settle every scoped rule against the person's answers: a rule with a picked check is checked; the `~` line an agree wrote is covered by that pick; every other
234
+ * rule is Not checked, with the reason (`person-left` = they chose it, `own-words` = they gave their own words, `no-pick` = nothing was picked).
235
+ * @param {ReturnType<typeof scopedRules>} rules @param {Pick[]} picks @param {{line: number, rule: number}[]} left
236
+ * @returns {{checks: Map<number, Record<string, any>[]>, notes: {line: number, rule: number, text: string, reason: 'person-left'|'own-words'|'no-pick'}[]}}
237
+ */
238
+ export function settleRules(rules, picks, left) {
239
+ /** @type {Map<number, Record<string, any>[]>} */
240
+ const checks = new Map();
241
+ /** @type {{line: number, rule: number, text: string, reason: 'person-left'|'own-words'|'no-pick'}[]} */
242
+ const notes = [];
243
+ const sameText = (/** @type {string|undefined} */ a, /** @type {string} */ b) => typeof a === 'string' && norm(a) === norm(b);
244
+ for (const r of rules) {
245
+ const own = picks.find((p) => p.line === r.line && p.rule === r.rule);
246
+ if (own?.check) { checks.set(r.line, [...(checks.get(r.line) ?? []), own.check]); continue; }
247
+ if (picks.some((p) => p.check && p.line === r.line && sameText(p.added, r.text))) continue;
248
+ if (left.some((l) => l.line === r.line && l.rule === r.rule)) notes.push({ ...r, reason: 'person-left' });
249
+ else if (own?.own || picks.some((p) => !p.check && p.own && p.line === r.line && sameText(p.added, r.text))) notes.push({ ...r, reason: 'own-words' });
250
+ else notes.push({ ...r, reason: 'no-pick' });
251
+ }
252
+ return { checks, notes };
253
+ }
254
+
255
+ /**
256
+ * Overwrite the drafter's check on every step of a line this call settles (a green step, which another signed part settles, is left alone): a line with picked checks
257
+ * is softgreen and carries exactly those checks; a line with none is hitl. Whatever `close.shape` the drafter wrote is gone. Pure: returns a new declaration.
258
+ * @param {any} declaration @param {ReturnType<typeof scopedRules>} rules @param {ReturnType<typeof settleRules>} settled
259
+ * @param {(note: {line: number, reason: 'person-left'|'own-words'|'no-pick'}) => string} sentence the one table's words for a reason
260
+ */
261
+ export function applyPicks(declaration, rules, settled, sentence) {
262
+ if (!declaration || !Array.isArray(declaration.steps)) return declaration;
263
+ const lineSet = new Set(rules.map((r) => r.line));
264
+ const green = (/** @type {number} */ n) => declaration.steps.some((/** @type {any} */ st) => st?.fromLine === n && st?.close?.class === 'green');
265
+ const mine = (/** @type {number} */ n) => lineSet.has(n) && !green(n);
266
+ const steps = declaration.steps.map((/** @type {any} */ st) => {
267
+ // M10 am22 (1): a fact line keeps its fact close and adds the person's picks to it (`close.picked`); the line stays green
268
+ if (st && typeof st === 'object' && lineSet.has(st.fromLine) && green(st.fromLine)) {
269
+ const { picked: _own, ...close } = st.close ?? {};
270
+ const kept = settled.checks.get(st.fromLine) ?? [];
271
+ return { ...st, close: kept.length && st.close?.class === 'green' ? { ...close, picked: kept } : close };
272
+ }
273
+ if (!st || typeof st !== 'object' || !mine(st.fromLine)) return st;
274
+ const picked = settled.checks.get(st.fromLine) ?? [];
275
+ return { ...st, close: picked.length ? { class: 'softgreen', shape: { picked } } : { class: 'hitl' } };
276
+ });
277
+ const out = { ...declaration, steps };
278
+ // M10 am22 (3): the record of the fact lines that carry the person's picks, written here and nowhere else; whatever the drafter sent for it is gone
279
+ const pickedLines = [...new Set(steps.filter((/** @type {any} */ st) => Array.isArray(st?.close?.picked) && st.close.class === 'green').map((/** @type {any} */ st) => st.fromLine))].sort((a, b) => a - b);
280
+ if (pickedLines.length) out.pickedLines = pickedLines; else delete out.pickedLines;
281
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
282
+ if (isRec(declaration.guardrailClasses)) {
283
+ out.guardrailClasses = { ...declaration.guardrailClasses };
284
+ const un = isRec(declaration.unjudgeable) ? { ...declaration.unjudgeable } : {};
285
+ for (const n of lineSet) {
286
+ if (!mine(n) || !declaration.steps.some((/** @type {any} */ st) => st?.fromLine === n)) continue;
287
+ const has = (settled.checks.get(n) ?? []).length > 0;
288
+ out.guardrailClasses[String(n)] = has ? 'softgreen' : 'hitl';
289
+ if (has) delete un[String(n)];
290
+ else un[String(n)] = [...new Set(settled.notes.filter((x) => x.line === n).map(sentence))].join(' ') || 'No check was picked for it, so you judge it at the Ask.';
291
+ }
292
+ if (isRec(declaration.unjudgeable) || Object.keys(un).length) out.unjudgeable = un;
293
+ }
294
+ return out;
295
+ }
296
+
297
+ // borrowed-from: bareloop src/checkpick.js@0408a8f (retentionOf, 890affa; adapted to fwdloop's one close per line: a unit is one cited fact of the line's step)
298
+ /**
299
+ * M10 am27 (4) RETENTION record of one draft (record only, counts, no words). Per job line: `aiParts` = the cited facts the drafter wrote on that line (a `cited` close counts once per
300
+ * fact, at least 1), `kept` = how many are still in the final declaration, `dropped` = what code removed, `picks` = the line has the person's picks; `classAsked` / `classFinal`
301
+ * = the line's close class as the drafter sent it and as it ended. Pure.
302
+ * @param {any} drafted the declaration as the drafter sent it @param {any} final the declaration the draft ended with @param {any[]|null|undefined} jobLines @param {Iterable<number>} [pickLines]
303
+ * @returns {{line: number, aiParts: number, kept: number, dropped: number, picks: boolean, classAsked: string|null, classFinal: string|null}[]}
304
+ */
305
+ export function retentionOf(drafted, final, jobLines, pickLines = []) {
306
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
307
+ if (!isRec(drafted) || !Array.isArray(drafted.steps) || !isRec(final) || !Array.isArray(final.steps)) return [];
308
+ const stepsOn = (/** @type {any} */ d, /** @type {number} */ n) => d.steps.filter((/** @type {any} */ st) => isRec(st) && st.fromLine === n);
309
+ const units = (/** @type {any[]} */ steps) => steps.reduce((/** @type {number} */ sum, /** @type {any} */ st) => (isRec(st.close) && isRec(st.close.cited) ? sum + Math.max(1, Array.isArray(st.close.cited.facts) ? st.close.cited.facts.length : 0) : sum), 0);
310
+ const classOf = (/** @type {any[]} */ steps) => (isRec(steps[0]?.close) && typeof steps[0].close.class === 'string' ? steps[0].close.class : null);
311
+ const withPicks = new Set(pickLines);
312
+ return (Array.isArray(jobLines) ? jobLines : []).filter((l) => isRec(l) && Number.isInteger(l.n)).map((l) => {
313
+ const was = stepsOn(drafted, l.n); const now = stepsOn(final, l.n);
314
+ const aiParts = units(was);
315
+ const kept = Math.min(aiParts, units(now));
316
+ return { line: l.n, aiParts, kept, dropped: aiParts - kept, picks: withPicks.has(l.n), classAsked: classOf(was), classFinal: classOf(now) };
317
+ });
318
+ }
@@ -0,0 +1,29 @@
1
+ // M10 amendment 16: the ONE place a picked check is put in plain words (one fixed phrase per bareguard rule, written by code). The ask, the `~` line an agree writes,
2
+ // the plan card (src/checked.js), the softgreen close's check list (src/closers.js) and the Audit all read it; nothing else writes these words.
3
+ /** the rules of bareguard's list a person may pick here (text rules only: the ones a plain answer can be judged by) */
4
+ export const OFFERED = Object.freeze(['nonEmpty', 'maxWords', 'minWords', 'maxLines', 'listItems', 'sections', 'sectionOrder', 'sectionWords', 'mustCarry', 'blockLines']);
5
+ /** M10 am22 (4): who added a check, the ONE place these two words live. The plan card, the Job tab and the Audit trail write them after the check's words. */
6
+ export const LABEL_AGENT = '[agent]';
7
+ export const LABEL_PICKED = '[you picked]';
8
+ /** @param {string} text @param {'agent'|'picked'} by */
9
+ export const labelled = (text, by) => `${text} ${by === 'picked' ? LABEL_PICKED : LABEL_AGENT}`;
10
+ const listOf = (/** @type {string[]} */ xs) => xs.join(', ');
11
+ /**
12
+ * The check in plain words, one fixed phrase per rule: the ask, the `~` line an agree writes, the plan card and the Audit all read this one function.
13
+ * @param {{rule: string, value?: number, size?: number, wordsPerSection?: number, names?: string[], phrases?: string[]}} c @returns {string}
14
+ */
15
+ export function plainWords(c) {
16
+ switch (c.rule) {
17
+ case 'nonEmpty': return 'the answer is not empty';
18
+ case 'maxWords': return `at most ${c.value} words`;
19
+ case 'minWords': return `at least ${c.value} words`;
20
+ case 'maxLines': return `at most ${c.value} lines`;
21
+ case 'listItems': return `exactly ${c.value} list items`;
22
+ case 'sections': return `sections named ${listOf(c.names ?? [])}`;
23
+ case 'sectionOrder': return `sections named ${listOf(c.names ?? [])}, in that order`;
24
+ case 'sectionWords': return `sections named ${listOf(c.names ?? [])}, each about ${c.wordsPerSection} words`;
25
+ case 'mustCarry': return `the answer carries ${listOf(c.phrases ?? [])}`;
26
+ case 'blockLines': return `blocks of ${c.size} lines, each carrying ${listOf(c.phrases ?? [])}`;
27
+ default: return `a ${c.rule} check`;
28
+ }
29
+ }
package/src/citedcheck.js CHANGED
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { createHash } from 'node:crypto';
17
17
  import { createRubric, checkStep } from 'bareguard';
18
+ import { plainWords } from './checkwords.js';
18
19
  import { asList, FACT_OPS, boundOk, MAX_CURRENCIES, MAX_UNITS, MAX_UNIT_CHARS } from './pagebits.js';
19
20
  import { ruleWords, moneyAs } from './pageask.js';
20
21
 
@@ -236,6 +237,19 @@ export function citedBrief(part) {
236
237
  };
237
238
  }
238
239
 
240
+ /**
241
+ * M10 am28: what a page-quoting step is told about the picks (am22) on its line, one plain line per pick, the values and what counts, never a verdict and never
242
+ * another guardrail. A list item is what bareguard's listItems counts: its own line starting with "1." or "- " followed by a space and its text.
243
+ * @param {any[]} picked @returns {string[]}
244
+ */
245
+ export function toldPicks(picked) {
246
+ return picked.map((c) => {
247
+ if (c.rule === 'listItems') return `Your "text" must have exactly ${c.value} list items; a list item is its own line starting with "1." or "- " followed by a space and its text.`;
248
+ if (c.rule === 'nonEmpty') return 'Your "text" must not be empty.';
249
+ return `Your "text" must have ${plainWords(c)}.`;
250
+ });
251
+ }
252
+
239
253
  /**
240
254
  * Every plan-card row a fact part carries: its facts, then its count (bareloop's factRows).
241
255
  * @param {any} part @returns {string[]}
package/src/closers.js CHANGED
@@ -44,6 +44,7 @@
44
44
  // signed text).
45
45
 
46
46
  import { createRubric, checkStep } from 'bareguard';
47
+ import { plainWords } from './checkwords.js';
47
48
  import { checkCited } from './citedcheck.js';
48
49
  import { closeSheet } from './sheetrun.js';
49
50
 
@@ -105,6 +106,8 @@ export function softgreenSpec(shape) {
105
106
  if (shape.linesPerInvoice !== undefined || shape.mustCarry !== undefined) {
106
107
  checks.push({ id: 'lines', rule: 'blockLines', field: 'text', size: shape.linesPerInvoice, phrases: shape.mustCarry });
107
108
  }
109
+ // M10 am16: each check the person picked is one more bareguard rule on the answer's text, id `pick<k>`; code set it from the person's pick, the drafter never writes one
110
+ if (Array.isArray(shape.picked)) shape.picked.forEach((c, k) => checks.push({ id: `pick${k + 1}`, field: 'text', ...c }));
108
111
  return { schema: 1, goal: 'softgreen', checkpoints: { close: { gating: true, checks } } };
109
112
  }
110
113
 
@@ -123,7 +126,7 @@ const partAfter = (item) => item.slice(item.indexOf(':') + 1);
123
126
  * A gap it has no sentence for is still a red, worded generically, never dropped.
124
127
  *
125
128
  * @param {any[]} gaps
126
- * @param {{ linesPerInvoice?: number, mustCarry?: string[] }} shape
129
+ * @param {{ linesPerInvoice?: number, mustCarry?: string[], picked?: any[] }} shape
127
130
  * @returns {{ red: string, reds: string[] }}
128
131
  */
129
132
  export function renderSoftgreenGaps(gaps, shape) {
@@ -165,6 +168,9 @@ export function renderSoftgreenGaps(gaps, shape) {
165
168
  // bareguard lists (block, word) misses and bounds the list; the tail counts the missing words it left out (amendment 20)
166
169
  const moreWords = (g.itemsTotal ?? 0) - (g.items?.length ?? 0);
167
170
  if (moreWords > 0) reds.push(`${moreWords} more missing word(s)`);
171
+ } else if (/^pick\d+$/.test(String(g.id)) && shape.picked?.[Number(String(g.id).slice(4)) - 1]) {
172
+ // M10 am16: a check the person picked is told in the words it was picked in, with the count bareguard measured when it gives one
173
+ reds.push(`not met: ${plainWords(shape.picked[Number(String(g.id).slice(4)) - 1])}${typeof g.measured === 'number' ? ` (found ${g.measured})` : ''}`);
168
174
  } else {
169
175
  reds.push(`the ${g.check} check failed (${g.kind ?? 'no detail'})`);
170
176
  }
@@ -179,6 +185,7 @@ function softgreenCheckText(c) {
179
185
  if (c.id === 'words') return `at most ${c.value} words`;
180
186
  if (c.id === 'sections') return `the sections are there, in order: ${c.names.join(', ')}`;
181
187
  if (c.id === 'perSection') return `each section is about ${c.wordsPerSection} words`;
188
+ if (/^pick\d+$/.test(c.id)) return plainWords(/** @type {any} */ (c));
182
189
  return `${c.size ?? 'its'} lines per block, each carrying: ${(c.phrases ?? []).join(', ')}`;
183
190
  }
184
191
 
@@ -232,7 +239,7 @@ function describeArtifact(artifact) {
232
239
  * Async because bareguard's `checkStep` is.
233
240
  *
234
241
  * @param {any} artifact
235
- * @param {{ maxWords?: number, sections?: string[], wordsPerSection?: number, linesPerInvoice?: number, mustCarry?: string[] }} shape
242
+ * @param {{ maxWords?: number, sections?: string[], wordsPerSection?: number, linesPerInvoice?: number, mustCarry?: string[], picked?: any[] }} shape
236
243
  * @returns {Promise<CloseVerdict>}
237
244
  */
238
245
  export async function closeSoftgreen(artifact, shape) {
@@ -264,7 +271,7 @@ export async function closeSoftgreen(artifact, shape) {
264
271
  /**
265
272
  * The one dispatcher — `close by declared class` (M2 scope item 4).
266
273
  *
267
- * @param {{ close?: { class?: string, shape?: Record<string, any>, cited?: any, columns?: {source: string, column: string}[], sheet?: any[] } }} step
274
+ * @param {{ close?: { class?: string, shape?: Record<string, any>, picked?: any[], cited?: any, columns?: {source: string, column: string}[], sheet?: any[] } }} step
268
275
  * @param {unknown} artifact
269
276
  * @param {{ reads: Record<string, any>, businessDate: string, source?: {ok: true, text: string, sha256: string}|{ok: false, red: string}|null, sheet?: any }} ctx
270
277
  * `source` (M10 piece 4) = the run's own frozen copy a cited step reads, from `readRunSource`; only a step whose close carries `cited` reads it
@@ -272,6 +279,36 @@ export async function closeSoftgreen(artifact, shape) {
272
279
  * @returns {Promise<CloseVerdict>}
273
280
  */
274
281
  export async function closeByClass(step, artifact, ctx) {
282
+ const cls = step?.close?.class;
283
+ if (cls === 'green' && Array.isArray(step?.close?.picked) && step.close.picked.length > 0) return await closeFactAndPicks(step, artifact, ctx);
284
+ return await closeOne(step, artifact, ctx);
285
+ }
286
+
287
+ /**
288
+ * M10 am22 (1): a fact line (cited / sheet) that also carries the checks the person picked. The artifact is `{results|claims..., text}`: the fact half reads
289
+ * everything but `text`, the picks read `text` (the softgreen close, unchanged). Green only if both are green. A red in either is red (both reasons told);
290
+ * a third outcome (unparseable, crash) of either half is never turned into green: the fact half's wins when it has one, else the picks' own.
291
+ * @param {any} step @param {unknown} artifact @param {Parameters<typeof closeOne>[2]} ctx @returns {Promise<CloseVerdict>}
292
+ */
293
+ async function closeFactAndPicks(step, artifact, ctx) {
294
+ const rec = artifact && typeof artifact === 'object' && !Array.isArray(artifact);
295
+ const { text, ...factArtifact } = rec ? /** @type {Record<string, any>} */ (artifact) : /** @type {Record<string, any>} */ ({});
296
+ const fact = /** @type {any} */ (await closeOne(step, rec ? factArtifact : artifact, ctx));
297
+ // am22 (2): missing text is red, never green. Code adds the `nonEmpty` floor to the person's picks (a count like "at most 80 words" passes an empty text), so empty = missing.
298
+ const picked = step.close.picked.some((/** @type {any} */ c) => c.rule === 'nonEmpty') ? step.close.picked : [...step.close.picked, { rule: 'nonEmpty' }];
299
+ const picks = /** @type {any} */ (typeof text === 'string'
300
+ ? await closeSoftgreen({ text }, { picked })
301
+ : { verdict: 'red', red: 'no text: the answer has no "text" for your checks to read', checks: [{ id: 'text', text: plainWords({ rule: 'nonEmpty' }), ok: false, result: 'no text' }] });
302
+ const pickChecks = Array.isArray(picks.checks) ? picks.checks.filter((/** @type {any} */ c) => c.id !== 'keys') : picks.checks; // the one-key row is code's, always true here
303
+ if (fact.verdict === 'crash' || fact.verdict === 'unparseable') return { ...fact, pickChecks };
304
+ if (picks.verdict === 'crash' || picks.verdict === 'unparseable') return fact.verdict === 'red' ? { ...fact, pickChecks } : { ...picks, cited: fact.cited, sheetRecord: fact.sheetRecord, checks: fact.checks };
305
+ if (fact.verdict === 'green' && picks.verdict === 'green') return { ...fact, pickChecks };
306
+ const reds = [...(fact.verdict === 'red' ? [fact.red] : []), ...(picks.verdict === 'red' ? [picks.red] : [])].filter(Boolean);
307
+ return { ...fact, verdict: 'red', red: reds.join('\n'), reds, pickChecks };
308
+ }
309
+
310
+ /** @param {any} step @param {unknown} artifact @param {{ reads: Record<string, any>, businessDate: string, source?: any, sheet?: any }} ctx @returns {Promise<CloseVerdict>} */
311
+ async function closeOne(step, artifact, ctx) {
275
312
  const cls = step?.close?.class;
276
313
  if (cls === 'green' && step?.close?.cited) return await closeCited(step.close.cited, artifact, ctx.source);
277
314
  if (cls === 'green' && Array.isArray(step?.close?.sheet)) return await closeSheet(step.close.sheet, artifact, ctx.sheet);