bareloop 0.55.0 → 0.56.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 (56) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bareloop.context.md +4 -2
  3. package/package.json +2 -2
  4. package/src/authorflow.js +141 -264
  5. package/src/authoring.js +2 -3
  6. package/src/authorjob.js +117 -88
  7. package/src/authorreadout.js +9 -15
  8. package/src/authorrun.js +13 -4
  9. package/src/behaviour.js +14 -0
  10. package/src/blockasks.js +43 -0
  11. package/src/checkblock.js +772 -0
  12. package/src/checklist.js +128 -0
  13. package/src/checkpick.js +30 -312
  14. package/src/checkwords.js +3 -1
  15. package/src/declaredclose.js +30 -1
  16. package/src/destpoint.js +3 -1
  17. package/src/draftspend.js +46 -0
  18. package/src/facts.js +8 -1
  19. package/src/fitcheck.js +5 -3
  20. package/src/pagemap.js +15 -3
  21. package/src/panel/authorroutes.js +15 -3
  22. package/src/panel/authorsession.js +133 -46
  23. package/src/panel/index.html +194 -22
  24. package/src/panel/jobplan.js +85 -33
  25. package/src/panel/server.js +52 -7
  26. package/src/pickrecord.js +19 -1
  27. package/src/placerule.js +355 -0
  28. package/src/promptregisters.js +11 -0
  29. package/src/questionbox.js +112 -0
  30. package/src/rowedit.js +115 -0
  31. package/src/rubricstep.js +212 -125
  32. package/src/run.js +10 -2
  33. package/src/userrun.js +46 -1
  34. package/types/authorflow.d.ts +32 -139
  35. package/types/authorjob.d.ts +24 -6
  36. package/types/authorreadout.d.ts +4 -10
  37. package/types/behaviour.d.ts +12 -0
  38. package/types/blockasks.d.ts +37 -0
  39. package/types/checkblock.d.ts +361 -0
  40. package/types/checklist.d.ts +134 -0
  41. package/types/checkpick.d.ts +3 -140
  42. package/types/declaredclose.d.ts +4 -0
  43. package/types/destpoint.d.ts +2 -0
  44. package/types/draftspend.d.ts +21 -0
  45. package/types/fitcheck.d.ts +7 -1
  46. package/types/pagemap.d.ts +4 -0
  47. package/types/panel/authorsession.d.ts +13 -2
  48. package/types/panel/jobgrid.d.ts +8 -8
  49. package/types/panel/jobplan.d.ts +48 -10
  50. package/types/panel/server.d.ts +14 -13
  51. package/types/pickrecord.d.ts +12 -0
  52. package/types/placerule.d.ts +194 -0
  53. package/types/questionbox.d.ts +87 -0
  54. package/types/rowedit.d.ts +32 -0
  55. package/types/rubricstep.d.ts +91 -48
  56. package/types/run.d.ts +10 -1
@@ -0,0 +1,128 @@
1
+ // THE ROW VOCABULARY of a rubric job's one check list, and the call that suggests extra `!` checks. The list itself is the CheckBlock (src/checkblock.js): every check the job can have is a row there.
2
+ // `~` rows the person's own rules (by: you; a settled pick builds the rule's check)
3
+ // `!` rows checks the agent suggests once, only from what it sees in the inputs (by: agent): the look's kept facts that carry no `~` rule, plus the call's own
4
+ // proposals (count, phrase). Code proves a word-bearing `!` row against the input text, else drops it with a reason. A `~` always wins over a `!` on the same thing.
5
+ // `$` rows default checks code adds itself (by: default): every claim quotes the input (a text line with one input), the numbers tie (a text line after a fact line);
6
+ // the mechanical floor (file exists, text not empty) is shown as a `$` row but is never counted as a check.
7
+ // Nothing here decides a verdict; the list says what the drafter may build, and code builds the rest.
8
+ import { askStructured, makeCostBook } from './authorflow.js';
9
+ import { lineRules } from './rubricstep.js';
10
+
11
+ /** at most this many `!` checks come from the call */
12
+ export const MAX_BANG = 3;
13
+ /** the reason a check on a version or a date goes under Not checked: it is true only for the input as it is today */
14
+ export const WEEK_ONLY_WORDS = 'It names a version or a date from the input, true only for the input as it is today, so you judge it at Accept.';
15
+ /** the label of the list call, as the drafting book and the draft log see it */
16
+ export const LEDGER_LABEL = 'ledger-suggest';
17
+ export const LEDGER_TOOL = 'suggest_extra_checks';
18
+ /** how much of each input the call is shown */
19
+ const SHOWN_CHARS = 8000;
20
+ /** the reason the empty list is logged with */
21
+ export const EMPTY_LIST_WORDS = 'empty list: nothing to check';
22
+
23
+ /**
24
+ * A check that needs exact words from the input is true only while the input stays as it is when those words hold a VERSION-like token (1.2 or 1.2.3, not after a currency sign or before
25
+ * a percent) or a DATE-like token (2026-11-04, 04/11/2026, "Nov 4, 2026", "4 November 2026", "November 2026"). Code refuses it; a `~` rule is the person's own and is never refused by this.
26
+ * @param {unknown} t @returns {boolean}
27
+ */
28
+ export function weekOnly(t) {
29
+ return weekTokens(t).length > 0;
30
+ }
31
+
32
+ /**
33
+ * The version-like and date-like tokens a text holds (the very tokens {@link weekOnly} reads), each once. Pure.
34
+ * @param {unknown} t @returns {string[]}
35
+ */
36
+ export function weekTokens(t) {
37
+ const s = String(t ?? '');
38
+ const M = '(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)';
39
+ const res = [/(?<![\d.$€£])\d+\.\d+(?:\.\d+)*(?![\d.]*%)/g, /\b\d{4}-\d{2}-\d{2}\b/g, /\b\d{1,2}[/.]\d{1,2}[/.]\d{2,4}\b/g,
40
+ new RegExp(`\\b${M}\\.? \\d{1,2}(?:st|nd|rd|th)?(?:,? \\d{4})?\\b`, 'gi'), new RegExp(`\\b\\d{1,2}(?:st|nd|rd|th)? ${M}\\.?(?: \\d{4})?\\b`, 'gi'), new RegExp(`\\b${M}\\.? \\d{4}\\b`, 'gi')];
41
+ return [...new Set(res.flatMap((re) => [...s.matchAll(re)].map((m) => m[0])))];
42
+ }
43
+
44
+ /**
45
+ * @typedef {{key: string, line: number, kind: 'rule'|'fact'|'cited'|'count'|'phrase'|'numbers'|'floor', from: 'rule'|'pick'|'look'|'agent'|'default', by: 'you'|'agent'|'default',
46
+ * words: string[], text?: string, rule?: number, part?: {line: number, part: number}, source?: string, name?: string, min?: number, max?: number, pick?: string, after?: number[],
47
+ * state: 'listed'|'built'|'not-checked'|'dropped', reason: string|null, forRule?: number, reading?: import('./pagerules.js').Reading}} Row
48
+ */
49
+
50
+ /** an empty list (no row that stands but the floor) is said so, never left as no record at all @param {Row[]} rows @returns {boolean} */
51
+ export const isEmptyList = (rows) => !rows.some((r) => r.kind !== 'floor' && r.state !== 'dropped');
52
+
53
+ /** the record the draft log keeps, one object per row (key, line, rowKind, from, by, words, state, reason), plus ONE explicit record when nothing stands @param {Row[]} rows */
54
+ export const ledgerRecord = (rows) => [
55
+ ...rows.map((r) => ({ key: r.key, line: r.line, rowKind: r.kind, from: r.from, by: r.by, words: r.kind === 'rule' ? [r.text ?? ''] : r.words, state: r.state, reason: r.reason })),
56
+ ...(isEmptyList(rows) ? [{ key: 'empty', line: 0, rowKind: 'empty', from: 'default', by: 'default', words: [], state: 'empty', reason: EMPTY_LIST_WORDS }] : []),
57
+ ];
58
+
59
+ // ---- the one paid call ---------------------------------------------------------------------------------------------------------------------
60
+ /** the list call's own system text (model-facing; used only by the list call of a rubric job with input text) */
61
+ export const LEDGER_SYSTEM = `You look at the inputs of a job and name checks the inputs themselves support, beyond the guardrails the person wrote.
62
+ Call ${LEDGER_TOOL} once with up to ${MAX_BANG} entries, or with an empty list.
63
+ - kind "count": how many results the input shows or the job asks for (min and/or max, whole numbers).
64
+ - kind "phrase": fixed words copied verbatim from an input (phrase, and source = that input's label).
65
+ Use only what you can see in the inputs. Do not repeat a guardrail the person wrote. If the inputs support none, send an empty list.`;
66
+
67
+ export const LEDGER_SCHEMA = Object.freeze({
68
+ type: 'object',
69
+ properties: {
70
+ extra: {
71
+ type: 'array', maxItems: MAX_BANG,
72
+ items: {
73
+ type: 'object',
74
+ properties: {
75
+ line: { type: 'integer', minimum: 1, description: 'the job line number' },
76
+ kind: { enum: ['count', 'phrase'] },
77
+ source: { type: 'string', description: 'the label of the input' },
78
+ phrase: { type: 'string', description: 'phrase only: words copied verbatim from the input' },
79
+ min: { type: 'integer', minimum: 1 },
80
+ max: { type: 'integer', minimum: 1 },
81
+ },
82
+ required: ['line', 'kind'],
83
+ additionalProperties: false,
84
+ },
85
+ },
86
+ },
87
+ required: ['extra'],
88
+ additionalProperties: false,
89
+ });
90
+
91
+ const ledgerChannel = () => ({
92
+ name: LEDGER_TOOL,
93
+ instruction: `Your reply did not deliver exactly one ${LEDGER_TOOL} call. Call ${LEDGER_TOOL} exactly once. Do not write the answer as text.`,
94
+ textPath: 'extra',
95
+ tool: (/** @type {{calls: any[]}} */ box) => ({
96
+ name: LEDGER_TOOL,
97
+ description: 'Deliver the extra checks the inputs support (or an empty list). Call this exactly once.',
98
+ parameters: LEDGER_SCHEMA,
99
+ execute: async (/** @type {any} */ args) => { box.calls.push(args); return 'received'; },
100
+ }),
101
+ });
102
+
103
+ /** @param {{n: number, text: string, rules?: string[], rule?: string}[]} jobLines @param {Record<string, string>} texts @returns {string} */
104
+ export function ledgerUserText(jobLines, texts) {
105
+ const out = ['The job:'];
106
+ for (const l of jobLines) {
107
+ out.push(`${l.n}. ${l.text}`);
108
+ lineRules(l).forEach((r, i) => out.push(` g${i + 1}: ${r}`));
109
+ }
110
+ for (const [label, t] of Object.entries(texts)) out.push('', `Input "${label}":`, String(t).slice(0, SHOWN_CHARS));
111
+ return out.join('\n');
112
+ }
113
+
114
+ /**
115
+ * The one paid call; its spend is booked like the look's. An unusable answer is NOT a guessed list: it yields no `!` proposals and says why.
116
+ * @param {{jobLines: any[], texts: Record<string, string>, generate: Function, ceilingUsd?: number|null, onCall?: (c: any) => void, priorCalls?: any[], priorRaws?: any[]}} o
117
+ * @returns {Promise<{extra: any[], reason: string|null, calls: any[], raws: any[]}>}
118
+ */
119
+ export async function runLedgerSuggest({ jobLines, texts, generate, ceilingUsd = null, onCall = () => {}, priorCalls = [], priorRaws = [] }) {
120
+ const book = makeCostBook({ ceilingUsd, onCall });
121
+ book.absorb(priorCalls, priorRaws);
122
+ const before = book.report().calls.length;
123
+ const beforeRaws = book.raws().length;
124
+ const r = await askStructured({ messages: [{ role: 'user', content: ledgerUserText(jobLines, texts) }], generate, mode: 'tool', retries: 1, label: LEDGER_LABEL, book, channel: ledgerChannel() });
125
+ const extra = r.artifact && Array.isArray(r.artifact.extra) ? r.artifact.extra : [];
126
+ const reason = r.artifact ? null : (r.budget ? 'the spend ceiling was reached' : (r.providerError ?? r.red?.detail ?? 'the answer could not be read'));
127
+ return { extra, reason, calls: book.report().calls.slice(before), raws: book.raws().slice(beforeRaws) };
128
+ }
package/src/checkpick.js CHANGED
@@ -51,6 +51,22 @@ export function guardrailItemCount(g) {
51
51
  if (!m) return null;
52
52
  return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
53
53
  }
54
+ /** a list-bound word the guardrail uses: the count it names, or the one it stands for ("more than 3" = at least 4, "fewer than 3" = at most 2) */
55
+ const MORE_THAN = /(?<!\b(?:no|not)\s)\bmore\s+than\s+(\d+)\b/i;
56
+ const FEWER_THAN = /(?<!\b(?:no|not)\s)\b(?:(?:fewer|less)\s+than|under|below)\s+(\d+)\b/i;
57
+ /** the direction of a list-items rule's wording: 'max', 'min' or null (exact / not said) @param {string} t @returns {'max'|'min'|null} */
58
+ function listDirection(t) {
59
+ if (/\b(at\s+most|up\s+to|no\s+more\s+than|not\s+more\s+than|max(?:imum)?(?:\s+of)?)\b/i.test(t) || FEWER_THAN.test(t)) return 'max';
60
+ if (/\b(at\s+least|min(?:imum)?(?:\s+of)?|no\s+fewer\s+than|not\s+fewer\s+than)\b/i.test(t) || MORE_THAN.test(t)) return 'min';
61
+ return null;
62
+ }
63
+ /** the numbers a rule may carry: the standalone numbers of the guardrail, plus N+1 for "more than N" (min) and N-1 for "fewer than N" (max) @param {string} rule @param {string} g @returns {number[]} */
64
+ function listBoundNumbers(rule, g) {
65
+ const named = guardrailStandaloneNumbers(g);
66
+ if (rule === 'minListItems') { const m = MORE_THAN.exec(g); if (m) named.push(Number(m[1]) + 1); }
67
+ if (rule === 'maxListItems') { const m = FEWER_THAN.exec(g); if (m) named.push(Number(m[1]) - 1); }
68
+ return named;
69
+ }
54
70
  /** @param {unknown} g @returns {boolean} the rule is a COUNT bareguard checks (words, list items or lines, sections): code reads it, whatever the page look said about it */
55
71
  export const isCountable = (g) => guardrailWordNumbers(g).length > 0 || guardrailItemCount(g) !== null || guardrailSectionCount(g) !== null;
56
72
 
@@ -99,6 +115,8 @@ export function scopedRules(jobLines, { inputs = null, look = null } = {}) {
99
115
 
100
116
  // ---- code's keep-or-drop (am16 (2)) ------------------------------------------------------------------------------------------------------
101
117
  const norm = (/** @type {unknown} */ t) => String(t).toLowerCase().replace(/\s+/g, ' ').trim();
118
+ /** a ~ rule's words compared case, spacing and trailing punctuation blind: the one spelling "is this the same rule?" is asked by */
119
+ export const sameRuleWords = (/** @type {unknown} */ a, /** @type {unknown} */ b) => norm(a).replace(/[.,;:!?\s]+$/, '') === norm(b).replace(/[.,;:!?\s]+$/, '');
102
120
  const tokens = (/** @type {unknown} */ t) => new Set(norm(t).match(/[\p{L}\p{N}]+/gu) ?? []);
103
121
 
104
122
  /**
@@ -123,10 +141,11 @@ export function keepOrDrop(guardrail, sug) {
123
141
  const v = sug[k];
124
142
  if (v == null) continue;
125
143
  if (NUM_FIELDS.includes(k)) {
126
- if (!Number.isInteger(v) || v < 1) return { kept: false, why: `${k} ${JSON.stringify(v)} is not a whole number >= 1` };
144
+ const floor = rule === 'maxListItems' ? 0 : 1; // maxListItems 0 = no bullets (bareguard 0.35); every other count starts at 1
145
+ if (!Number.isInteger(v) || v < floor) return { kept: false, why: `${k} ${JSON.stringify(v)} is not a whole number >= ${floor}` };
127
146
  const named = rule === 'maxWords' || rule === 'minWords' ? guardrailWordNumbers(guardrail)
128
147
  : k === 'wordsPerSection' ? [guardrailWordsPerSection(guardrail)].filter((x) => x !== null)
129
- : guardrailStandaloneNumbers(guardrail);
148
+ : listBoundNumbers(rule, guardrail);
130
149
  if (!named.includes(v)) return { kept: false, why: `${k} ${v} is not a number the guardrail names (${named.join(', ') || 'it names none'})` };
131
150
  check[k] = v;
132
151
  } else if (WORD_FIELDS.includes(k)) {
@@ -220,7 +239,7 @@ export const suggestChannel = () => ({
220
239
  });
221
240
 
222
241
  /**
223
- * The check CODE proposes for a count rule when the call yields none (R10, ours; fwd has no such fallback): a bullets / list-items / points count -> listItems N, a lines count ->
242
+ * The check CODE proposes for a count rule when the call yields none (R10, ours; fwd has no such fallback): a bullets / list-items / points count -> listItems N (exact; "at most / up to / no more than / fewer than / under / below" -> maxListItems, "at least / minimum / no fewer than / more than" -> minListItems, F315), a lines count ->
224
243
  * maxLines N, ONE word number -> 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 ("3 bullets under 80 words") is not built either; a rule with
225
244
  * several word numbers or a range ("between 100 and 200 words") is not guessed. The result passes `keepOrDrop`, so every number is one the rule names.
226
245
  * @param {string} text @returns {Record<string, any>|null}
@@ -231,7 +250,13 @@ export function countCheck(text) {
231
250
  /** @type {Record<string, any>|null} */
232
251
  let built = null;
233
252
  if (items !== null && (words.length > 0 || guardrailSectionCount(text) !== null)) return null; // two different counts in one rule: first-match readers would guess, so nothing is built
234
- if (items !== null) built = { rule: /\blines?\b/i.test(text) && !/\b(bullets?|items?|points?)\b/i.test(text) ? 'maxLines' : 'listItems', value: items };
253
+ if (items !== null && /\blines?\b/i.test(text) && !/\b(bullets?|items?|points?)\b/i.test(text)) built = { rule: 'maxLines', value: items };
254
+ else if (items !== null) {
255
+ const dir = listDirection(text);
256
+ if (dir === 'min') built = { rule: 'minListItems', value: MORE_THAN.test(text) ? items + 1 : items };
257
+ else if (dir === 'max') built = { rule: 'maxListItems', value: FEWER_THAN.test(text) ? items - 1 : items };
258
+ else built = { rule: 'listItems', value: items };
259
+ }
235
260
  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] };
236
261
  if (built === null) return null;
237
262
  const res = keepOrDrop(text, built);
@@ -260,317 +285,10 @@ export function rowsFromAnswer(scoped, args) {
260
285
  /** the can't-check ask, as the signed words say it */
261
286
  export const CANT_CHECK_WORDS = "I can't check this. Your own words, or Not checked?";
262
287
  /** how every answer is told, once (fwd am2 item 2's words) */
263
- 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.`;
264
-
265
- /**
266
- * @typedef {{line: number, rule: number, source: 'look', ask: 'check'|'no-check', ruleText: string, question: string, reading?: string, check?: Record<string, any>, counted: boolean, pairRule?: number}} PickAsk
267
- */
268
- /**
269
- * 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
270
- * Not checked?` when nothing was kept. A proposal is not counted toward the 3-ask cap; a can't-check ask is (fwd am16 (5)). Both ride the existing code-forced look ask path
271
- * (`source: 'look'`), so the chat message, the answer words and the draft log rows are the look asks' own.
272
- * @param {ReturnType<typeof rowsFromAnswer>} rows @returns {PickAsk[]}
273
- */
274
- export function checkAsks(rows) {
275
- return rows.map((r) => {
276
- const pair = typeof (/** @type {any} */ (r).pairRule) === 'number' ? { pairRule: /** @type {any} */ (r).pairRule } : {};
277
- if (r.check === null) {
278
- 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)}` };
279
- }
280
- const words = plainWords(/** @type {any} */ (r.check));
281
- 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)}` };
282
- });
283
- }
284
-
285
- // ---- the plan uses only the checks you picked (am16 (4)) ---------------------------------------------------------------------------------
286
- /**
287
- * @typedef {{line: number, rule: number, check: Record<string, any>|null, added?: string, own?: boolean, kept?: boolean}} Pick
288
- * `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
289
- * @typedef {'person-left'|'own-words'|'no-pick'} NoteReason
290
- */
291
- /** the one table of Not checked reasons, in the person's words (fwd src/pagedropwords.js, adapted) @type {Record<NoteReason, string>} */
292
- export const NOTE_WORDS = Object.freeze({
293
- 'person-left': 'You chose to leave it Not checked, so you judge it at Accept.',
294
- 'own-words': 'Your own words are on the line; the machine has no check for them, so you judge it at Accept.',
295
- 'no-pick': 'No check was picked for it, so you judge it at Accept.',
296
- });
297
-
298
- /**
299
- * Settle every scoped rule against the person's answers: a rule with a picked check is checked (and the `~` line an agree wrote is covered by that pick); every other rule is
300
- * Not checked, with the reason (`person-left` = they chose it, `own-words` = they gave their own words, `no-pick` = nothing was picked).
301
- * @param {Rule[]} rules @param {Pick[]} picks @param {{line: number, rule: number, kept?: boolean}[]} left @param {{n: number, rule?: string, rules?: string[]}[]} jobLines the lines AFTER the answers were added
302
- * @returns {{checks: {line: number, text: string, check: Record<string, any>, rules: number[], kept: boolean}[], notes: (Rule & {reason: NoteReason, also: number[], kept: boolean})[]}}
303
- */
304
- export function settleRules(rules, picks, left, jobLines) {
305
- /** @type {{line: number, text: string, check: Record<string, any>, rules: number[], kept: boolean}[]} */
306
- const checks = [];
307
- /** @type {(Rule & {reason: NoteReason, also: number[], kept: boolean})[]} */
308
- const notes = [];
309
- /** the rule number the answer's added `~` line has on its line (a `~` line is a rule of its own) @param {number} line @param {string|undefined} added @returns {number[]} */
310
- const addedNo = (line, added) => {
311
- if (typeof added !== 'string') return [];
312
- const at = lineRules(jobLines.find((l) => l.n === line) ?? {}).findLastIndex((t) => norm(t) === norm(added));
313
- return at >= 0 ? [at + 1] : [];
314
- };
315
- for (const r of rules) {
316
- // the `~` line an answer wrote is covered by its pick (a carried card already holds it as a rule of its own): never settled twice
317
- if (picks.some((p) => p.line === r.line && p.rule !== r.rule && typeof p.added === 'string' && norm(p.added) === norm(r.text))) continue;
318
- const own = picks.find((p) => p.line === r.line && p.rule === r.rule);
319
- if (own?.check) { checks.push({ line: r.line, text: r.text, check: own.check, rules: [r.rule, ...addedNo(r.line, own.added)], kept: own.kept === true }); continue; }
320
- const also = addedNo(r.line, own?.added);
321
- const lf = left.find((l) => l.line === r.line && l.rule === r.rule);
322
- if (lf) notes.push({ ...r, reason: 'person-left', also, kept: lf.kept === true });
323
- else if (own?.own) notes.push({ ...r, reason: 'own-words', also, kept: own.kept === true });
324
- else notes.push({ ...r, reason: 'no-pick', also, kept: false });
325
- }
326
- return { checks, notes };
327
- }
328
-
329
- /** the reason a part the drafter could not express as a check is listed under Not checked (fwd's am16: the drafter writes no check of its own, what no rule can check is the person's to judge) */
330
- export const UNCHECKABLE_WORDS = 'No rule can check this, so you judge it at Accept.';
331
-
332
- /**
333
- * RUBRIC jobs only (the caller gates on the job's lang): a part the drafter wrote as `none` or `judged` is a thing no rule can check, so it is
334
- * listed under Not checked with its own words instead of failing the whole plan (hamr's ruling 2026-11-09, as fwd lists what the drafter cannot check).
335
- * A part that is a verbatim copy of one of the person's `~` rules, or lists rule numbers, gives a `refused` entry per rule no other part carries (shown as that rule's own words); a part that is NOT a verbatim copy of a rule (the job sentence itself, the drafter's own wording) also becomes one line in `notes`, so its words are never lost. Never silent, never a line-level refusal (that would silence the line's other rule reds).
336
- * Runs BEFORE applyPicks, so a rule the person's picks settle gets code's own reason there. `guard` and every other class are untouched.
337
- * A stage left with no parts stays: an empty stage is the legal prose stage ("what the text says - you judge it at Accept"). Pure.
338
- * @param {any} declaration @param {any[]|null|undefined} jobLines @param {boolean} rubric whether the job is a rubric job (the draft gate's `lang === RUBRIC_LANG`); anything else is returned untouched, its reds stand @returns {any}
339
- */
340
- export function moveUncheckable(declaration, jobLines, rubric) {
341
- if (rubric !== true) return declaration;
342
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
343
- if (!isRec(declaration) || !Array.isArray(declaration.stages)) return declaration;
344
- const unchecked = (/** @type {any} */ x) => isRec(x) && (x.class === 'none' || x.class === 'judged');
345
- const isStage = (/** @type {any} */ st) => isRec(st) && st.kind === 'rubric-step' && isRec(st.params) && Array.isArray(st.params.parts);
346
- if (!declaration.stages.some((/** @type {any} */ st) => isStage(st) && st.params.parts.some(unchecked))) return declaration;
347
- const refused = Array.isArray(declaration.refused) ? [...declaration.refused] : [];
348
- const notes = Array.isArray(declaration.notes) ? [...declaration.notes] : [];
349
- /** @type {{line: number, part: any}[]} */
350
- const moved = [];
351
- const stages = declaration.stages.map((/** @type {any} */ st) => {
352
- if (!isStage(st) || !st.params.parts.some(unchecked)) return st;
353
- for (const part of st.params.parts.filter(unchecked)) moved.push({ line: st.params.step, part });
354
- return { ...st, params: { ...st.params, parts: st.params.parts.filter((/** @type {any} */ x) => !unchecked(x)) } };
355
- });
356
- const carried = (/** @type {number} */ line, /** @type {number} */ n) => stages.some((/** @type {any} */ st) => isStage(st) && st.params.step === line
357
- && st.params.parts.some((/** @type {any} */ x) => isRec(x) && Array.isArray(x.rules) && x.rules.includes(n)));
358
- const say = (/** @type {unknown} */ t) => String(t ?? '').replace(/\s+/g, ' ').trim();
359
- const same = (/** @type {unknown} */ a, /** @type {unknown} */ b) => say(a).replace(/[.]$/, '').toLowerCase() === say(b).replace(/[.]$/, '').toLowerCase();
360
- for (const { line, part } of moved) {
361
- const jl = (jobLines ?? []).find((/** @type {any} */ l) => isRec(l) && l.n === line);
362
- const ruleTexts = jl ? lineRules(jl) : [];
363
- /** the `~` rules the part's own words ARE (a verbatim copy of the person's rule: that rule is checked or listed by its own owner, the part says nothing more) */
364
- const echoed = ruleTexts.flatMap((t, i) => (same(t, part.text) ? [i + 1] : []));
365
- const named = Array.isArray(part.rules) ? part.rules.filter((/** @type {any} */ n) => Number.isInteger(n) && n >= 1 && n <= ruleTexts.length) : [];
366
- // the words the person's own rules already say are not repeated as unchecked (a pick may check them): a part reading "<sentence>, <rule>, <rule>" lists the sentence only
367
- const rest = [...ruleTexts].sort((a, b) => b.length - a.length).reduce((w, t) => (t ? w.split(new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')).join(',') : w), say(part.text)).replace(/(\s*[,;]\s*)+/g, ', ').replace(/^[,;\s]+|[,;\s]+$/g, '');
368
- if (echoed.length === 0 && (rest !== '' || say(part.text) === '')) {
369
- const words = rest;
370
- const text = `line ${line}: ${words ? `"${words}"` : 'a part of this line'} \u2014 ${UNCHECKABLE_WORDS}`;
371
- if (!notes.includes(text)) notes.push(text);
372
- }
373
- for (const n of new Set([...echoed, ...named])) {
374
- if (carried(line, n) || refused.some((/** @type {any} */ r) => isRec(r) && r.line === line && r.rule === n)) continue;
375
- refused.push({ line, rule: n, reason: UNCHECKABLE_WORDS });
376
- }
377
- }
378
- return { ...declaration, stages, ...(refused.length ? { refused } : {}), ...(notes.length ? { notes } : {}) };
379
- }
288
+ export 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.`;
380
289
 
381
290
  /** a part of a rubric-step stage, from a pick: the check's own fields, the rule's words, and the `~` rule numbers it carries out @param {Record<string, any>} check @param {string} text @param {number[]} rules */
382
291
  export function partOfPick(check, text, rules) {
383
292
  const { rule, ...fields } = check;
384
293
  return { text, class: 'countable', check: rule, ...fields, rules };
385
294
  }
386
-
387
- /**
388
- * Put the person's picks into the drafted declaration (a pure function; the input is untouched): on every rubric-step stage of a line this call settles, the drafter's own
389
- * word/section/line/list/phrase checks are gone (the drafter writes none, whatever it sent), a part per picked check is added carrying the `~` rule numbers it settles, and every
390
- * other settled rule goes under Not checked (`refused` with a rule number and the reason). A rule a fact or guard part of the draft already carries is left to that part.
391
- * With no picks settled (`null`) it only drops a `picks` record the drafter sent.
392
- * @param {any} declaration @param {ReturnType<typeof settleRules>|null} settled @returns {any}
393
- */
394
- export function applyPicks(declaration, settled) {
395
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
396
- if (!isRec(declaration) || !Array.isArray(declaration.stages)) return declaration;
397
- // the record of picks is code's alone: whatever the drafter sent under `picks` is gone, and with no picks settled none is written
398
- if (settled === null) { const { picks: _drafted, ...rest } = declaration; return rest; }
399
- const lines = new Set([...settled.checks.map((c) => c.line), ...settled.notes.map((n) => n.line)]);
400
- // the drafter writes no count of its own: a shape check or a claim count (minClaims / maxClaims) it sent is gone, whatever the line (fwd am22's strip, one owner here)
401
- const shape = (/** @type {any} */ p) => isRec(p) && p.class === 'countable' && (OFFERED.includes(p.check) || p.check === 'minClaims' || p.check === 'maxClaims');
402
- /** the record of what was added, `{line, part}` each: the signed close keeps it, so a pick beside a fact is told from a drafter's own count @type {{line: number, part: any}[]} */
403
- const record = [];
404
- const stages = declaration.stages.map((/** @type {any} */ st) => {
405
- if (!(isRec(st) && st.kind === 'rubric-step' && isRec(st.params) && Array.isArray(st.params.parts) && lines.has(st.params.step))) return st;
406
- /** the numbers the person's picks on this line check (a picked count) @type {number[]} */
407
- const vals = settled.checks.filter((c) => c.line === st.params.step).map((c) => c.check.value).filter((v) => typeof v === 'number');
408
- // a fact part's `count` that restates a picked count is the drafter's second copy of the person's rule: gone (the fact itself stays)
409
- const restates = (/** @type {any} */ p) => isRec(p) && p.class === 'fact' && isRec(p.count) && [p.count.min, p.count.max].some((v) => vals.includes(v));
410
- const kept = st.params.parts.filter((/** @type {any} */ p) => !shape(p)).map((/** @type {any} */ p) => { if (!restates(p)) return p; const { count: _restated, ...rest } = p; return rest; });
411
- const add = settled.checks.filter((c) => c.line === st.params.step).map((c) => partOfPick(c.check, c.text, c.rules));
412
- for (const part of add) record.push({ line: st.params.step, part });
413
- return { ...st, params: { ...st.params, parts: [...kept, ...add] } };
414
- });
415
- const carried = (/** @type {number} */ line, /** @type {number} */ n) => stages.some((/** @type {any} */ st) => isRec(st) && st.kind === 'rubric-step' && isRec(st.params) && st.params.step === line
416
- && Array.isArray(st.params.parts) && st.params.parts.some((/** @type {any} */ x) => isRec(x) && (x.class === 'fact' || x.class === 'guard' || !shape(x)) && Array.isArray(x.rules) && x.rules.includes(n)));
417
- const refused = Array.isArray(declaration.refused) ? [...declaration.refused] : [];
418
- /** a drafter-listed entry for a rule this call settles is replaced by code's */
419
- const mine = (/** @type {any} */ r) => isRec(r) && Number.isInteger(r.line) && Number.isInteger(r.rule)
420
- && settled.notes.some((x) => x.line === r.line && (x.rule === r.rule || x.also.includes(r.rule)));
421
- const base = refused.filter((r) => !mine(r));
422
- for (const x of settled.notes) {
423
- if (carried(x.line, x.rule)) continue;
424
- for (const n of [x.rule, ...x.also]) base.push({ line: x.line, rule: n, reason: `${NOTE_WORDS[x.reason]}${x.kept ? ` (${KEPT_WORDS})` : ''}` });
425
- }
426
- const { picks: _drafted, ...rest } = declaration;
427
- return { ...rest, stages, ...(record.length ? { picks: record } : {}), ...(base.length ? { refused: base } : {}) };
428
- }
429
-
430
- /** the `source` of a part is missing: absent, not a string, or only white space */
431
- const noSource = (/** @type {any} */ p) => typeof p.source !== 'string' || p.source.trim() === '';
432
- /** the fields a fact part may carry; a part with any other field is never merged (its extra field would be lost) */
433
- const FACT_FIELDS = ['text', 'class', 'covers', 'rules', 'source', 'facts', 'count'];
434
-
435
- /**
436
- * RUBRIC jobs only (the caller gates on the job's lang; anything else is returned untouched, its reds stand). Two small, mechanical steps on every rubric-step stage, run
437
- * before validation (hamr's ruling 2026-11-09):
438
- * F1 source fill: when the job has EXACTLY ONE input label, a `fact` part, or a `cited` part, whose `source` is missing or empty gets that label. With 2+ labels nothing is filled; a
439
- * wrong non-empty source is never rewritten (its red stands).
440
- * F2 fact merge: when ONE stage holds 2+ `fact` parts they become ONE fact part (where the first stood): the `facts` of all in order, the union of `rules` and of `covers`, the one shared
441
- * `source`, the `text`s joined with "; ". Only when it is safe, else the parts stay and the existing second-fact-list red fires: the sources differ (after F1), two facts share a name
442
- * (compared white-space and case blind), the parts' `count`s differ (a part with no count agrees with any; the merged part carries the one count), a part is not a plain object or has a
443
- * field a fact part does not carry, or `facts` is not a list.
444
- * Runs AFTER applyPicks (its strip of a count that restates a pick has already happened). Pure.
445
- * @param {any} declaration @param {string[]|null|undefined} inputLabels the labels of the job's inputs @param {boolean} rubric the draft gate's `lang === RUBRIC_LANG` @returns {any}
446
- */
447
- export function fillAndMergeFacts(declaration, inputLabels, rubric) {
448
- if (rubric !== true) return declaration;
449
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
450
- if (!isRec(declaration) || !Array.isArray(declaration.stages)) return declaration;
451
- const only = Array.isArray(inputLabels) && inputLabels.length === 1 && typeof inputLabels[0] === 'string' && inputLabels[0] !== '' ? inputLabels[0] : null;
452
- const isFact = (/** @type {any} */ p) => isRec(p) && p.class === 'fact';
453
- const sortKeys = (/** @type {any} */ v) => JSON.stringify(v, (_k, x) => (isRec(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : 1))) : x));
454
- const nameOf = (/** @type {any} */ f) => (isRec(f) && typeof f.name === 'string' ? f.name.replace(/\s+/g, ' ').trim().toLowerCase() : null);
455
- const union = (/** @type {any[]} */ parts, /** @type {string} */ key) => {
456
- const all = parts.flatMap((p) => (Array.isArray(p[key]) ? p[key] : []));
457
- return all.filter((x, i) => all.findIndex((y) => sortKeys(y) === sortKeys(x)) === i);
458
- };
459
- /** @param {any[]} parts @returns {any|null} the merged part, or null when merging is not safe */
460
- const merge = (parts) => {
461
- if (!parts.every((p) => Object.keys(p).every((k) => FACT_FIELDS.includes(k)) && Array.isArray(p.facts))) return null;
462
- if (new Set(parts.map((p) => p.source)).size !== 1) return null;
463
- const names = parts.flatMap((p) => p.facts.map(nameOf));
464
- if (names.some((n) => n === null) || new Set(names).size !== names.length) return null;
465
- const counts = parts.filter((p) => p.count !== undefined).map((p) => sortKeys(p.count));
466
- if (new Set(counts).size > 1) return null;
467
- const texts = parts.map((p) => (typeof p.text === 'string' ? p.text.trim() : '')).filter((t, i, a) => t !== '' && a.indexOf(t) === i);
468
- const rules = union(parts, 'rules'), covers = union(parts, 'covers');
469
- const withCount = parts.find((p) => p.count !== undefined);
470
- return {
471
- ...(texts.length ? { text: texts.join('; ') } : {}), class: 'fact', source: parts[0].source,
472
- ...(covers.length ? { covers } : {}), ...(rules.length ? { rules } : {}), facts: parts.flatMap((p) => p.facts),
473
- ...(withCount ? { count: withCount.count } : {}),
474
- };
475
- };
476
- let changed = false;
477
- const stages = declaration.stages.map((/** @type {any} */ st) => {
478
- if (!(isRec(st) && st.kind === 'rubric-step' && isRec(st.params) && Array.isArray(st.params.parts))) return st;
479
- let parts = st.params.parts;
480
- if (only !== null) {
481
- parts = parts.map((/** @type {any} */ p) => (isRec(p) && (p.class === 'fact' || (p.class === 'countable' && p.check === 'cited')) && noSource(p) ? { ...p, source: only } : p));
482
- }
483
- const facts = parts.filter(isFact);
484
- const merged = facts.length > 1 ? merge(facts) : null;
485
- if (merged) parts = parts.flatMap((/** @type {any} */ p) => (p === facts[0] ? [merged] : isFact(p) ? [] : [p]));
486
- if (parts.every((/** @type {any} */ p, /** @type {number} */ i) => p === st.params.parts[i]) && parts.length === st.params.parts.length) return st;
487
- changed = true;
488
- return { ...st, params: { ...st.params, parts } };
489
- });
490
- return changed ? { ...declaration, stages } : declaration;
491
- }
492
-
493
- /**
494
- * RETENTION record of one rubric draft (PRD v1.131 tick 7; record only). Per job line: `aiParts` = what the drafter wrote on it that is the AI's own check or extra (a fact counts once per
495
- * fact it lists, a `cited` part, a part code later moves as `none` / `judged`; guards and the drafter's own count checks are not counted, the picks strip those), `kept` = how many of
496
- * those are still in the final declaration, `dropped` = what code removed (the move to Not checked, the drop after the last try), `picks` = the line has code-matched count picks. A merge
497
- * of fact parts keeps every fact, so it drops nothing. Pure; no words, only counts.
498
- * @param {any} drafted the declaration as the drafter sent it @param {any} final the declaration the draft ended with @param {any[]|null|undefined} jobLines
499
- * @returns {{line: number, aiParts: number, kept: number, dropped: number, picks: boolean}[]}
500
- */
501
- export function retentionOf(drafted, final, jobLines) {
502
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
503
- if (!isRec(drafted) || !Array.isArray(drafted.stages) || !isRec(final) || !Array.isArray(final.stages)) return [];
504
- const partsOn = (/** @type {any} */ d, /** @type {number} */ n) => d.stages.flatMap((/** @type {any} */ st) => (isRec(st) && st.kind === 'rubric-step' && isRec(st.params) && st.params.step === n && Array.isArray(st.params.parts) ? st.params.parts : []));
505
- const units = (/** @type {any[]} */ parts, /** @type {string[]} */ classes) => parts.reduce((/** @type {number} */ sum, /** @type {any} */ p) => {
506
- if (!isRec(p)) return sum;
507
- if (p.class === 'fact') return classes.includes('fact') ? sum + Math.max(1, Array.isArray(p.facts) ? p.facts.length : 0) : sum;
508
- if (p.class === 'countable' && p.check === 'cited') return classes.includes('cited') ? sum + 1 : sum;
509
- return (p.class === 'none' || p.class === 'judged') && classes.includes('moved') ? sum + 1 : sum;
510
- }, 0);
511
- const picks = Array.isArray(final.picks) ? final.picks : [];
512
- return (Array.isArray(jobLines) ? jobLines : []).filter((l) => isRec(l) && Number.isInteger(l.n)).map((l) => {
513
- const aiParts = units(partsOn(drafted, l.n), ['fact', 'cited', 'moved']);
514
- const kept = Math.min(aiParts, units(partsOn(final, l.n), ['fact', 'cited']));
515
- return { line: l.n, aiParts, kept, dropped: aiParts - kept, picks: picks.some((/** @type {any} */ k) => isRec(k) && k.line === l.n) };
516
- });
517
- }
518
-
519
- /** the reason a dropped AI extra is listed under Not checked */
520
- export const DROPPED_WORDS = "The AI couldn't build a working check for this, so you judge it at Accept.";
521
-
522
- /**
523
- * RUBRIC jobs only, run ONLY after the LAST try failed the gate (PRD v1.131 tick 4, hamr's ruling 2026-11-09). When EVERY red points at one part of a rubric-step stage and that part is not
524
- * a code-matched pick (a part in `declaration.picks`) nor code-owned (a guard, `numbersFromFacts`), the AI's parts those reds name are dropped and listed under Not checked: a pure extra as a
525
- * note with its words, a part that served a `~` rule as a `refused` entry for each rule no surviving part carries (rule numbers outside the line's rules are ignored, as moveUncheckable does).
526
- * Any red on a pick / code-owned part, or any red not tied to one part, returns `{refused}` and the plan is refused as today. Pure.
527
- * @param {any} declaration the declaration as the gate validated it @param {{path?: string, code?: string}[]} reds @param {any[]|null|undefined} jobLines
528
- * @returns {{declaration: any, dropped: {line: number, words: string, rules: number[]}[]}|{refused: string}}
529
- */
530
- export function dropExtras(declaration, reds, jobLines) {
531
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
532
- if (!isRec(declaration) || !Array.isArray(declaration.stages)) return { refused: 'no plan to drop from' };
533
- if (!Array.isArray(reds) || reds.length === 0) return { refused: 'no red to drop for' };
534
- const sortKeys = (/** @type {any} */ v) => JSON.stringify(v, (_k, x) => (isRec(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => (a < b ? -1 : 1))) : x));
535
- const pickKeys = (Array.isArray(declaration.picks) ? declaration.picks : []).map((/** @type {any} */ k) => sortKeys(k?.part));
536
- const owned = (/** @type {any} */ p) => !isRec(p) || pickKeys.includes(sortKeys(p)) || p.class === 'guard' || (p.class === 'countable' && p.check === 'numbersFromFacts');
537
- /** @type {Map<string, [number, number]>} */
538
- const hit = new Map();
539
- for (const r of reds) {
540
- const m = /^stages\[(\d+)\]\.params\.parts\[(\d+)\]/.exec(String(r?.path ?? ''));
541
- const st = m ? declaration.stages[Number(m[1])] : null;
542
- if (!m || !(isRec(st) && st.kind === 'rubric-step' && isRec(st.params) && Array.isArray(st.params.parts)) || !isRec(st.params.parts[Number(m[2])])) return { refused: `a red (${r?.code}) is not tied to one part` };
543
- if (owned(st.params.parts[Number(m[2])])) return { refused: `a red (${r?.code}) is on a check code built from your picks` };
544
- hit.set(`${m[1]}.${m[2]}`, [Number(m[1]), Number(m[2])]);
545
- }
546
- const say = (/** @type {unknown} */ t) => String(t ?? '').replace(/\s+/g, ' ').trim();
547
- /** @type {{line: number, words: string, rules: number[], pure: boolean}[]} */
548
- const dropped = [];
549
- const stages = declaration.stages.map((/** @type {any} */ st, /** @type {number} */ si) => {
550
- if (![...hit.values()].some(([s]) => s === si)) return st;
551
- const parts = st.params.parts.filter((/** @type {any} */ p, /** @type {number} */ pi) => {
552
- if (!hit.has(`${si}.${pi}`)) return true;
553
- const names = Array.isArray(p.facts) ? p.facts.map((/** @type {any} */ f) => say(f?.name)).filter(Boolean).join(', ') : '';
554
- const rules = [...new Set([...(Array.isArray(p.rules) ? p.rules : []), ...(Array.isArray(p.covers) ? p.covers : [])].filter((n) => Number.isInteger(n)))];
555
- dropped.push({ line: st.params.step, words: say(p.text) || names, rules, pure: rules.length === 0 });
556
- return false;
557
- });
558
- return { ...st, params: { ...st.params, parts } };
559
- });
560
- const carried = (/** @type {number} */ line, /** @type {number} */ n) => stages.some((/** @type {any} */ st) => isRec(st) && st.kind === 'rubric-step' && isRec(st.params) && st.params.step === line
561
- && Array.isArray(st.params.parts) && st.params.parts.some((/** @type {any} */ x) => isRec(x) && ((Array.isArray(x.rules) && x.rules.includes(n)) || (Array.isArray(x.covers) && x.covers.includes(n)))));
562
- const refused = Array.isArray(declaration.refused) ? [...declaration.refused] : [];
563
- const notes = Array.isArray(declaration.notes) ? [...declaration.notes] : [];
564
- for (const d of dropped) {
565
- const jl = (jobLines ?? []).find((/** @type {any} */ l) => isRec(l) && l.n === d.line);
566
- const ruleTexts = jl ? lineRules(jl) : [];
567
- const ownWords = (/** @type {string} */ w) => ruleTexts.some((t) => say(t).toLowerCase() === w.toLowerCase());
568
- for (const n of d.rules.filter((k) => k >= 1 && k <= ruleTexts.length)) if (!carried(d.line, n) && !refused.some((/** @type {any} */ r) => isRec(r) && r.line === d.line && r.rule === n)) refused.push({ line: d.line, rule: n, reason: DROPPED_WORDS });
569
- // a pure extra, or a ruled part that said more than the rule's own words, is also listed by its words
570
- if (d.pure || !ownWords(d.words)) {
571
- const text = `line ${d.line}: ${d.words ? `"${d.words}"` : 'a part of this line'} — ${DROPPED_WORDS}`;
572
- if (!notes.includes(text)) notes.push(text);
573
- }
574
- }
575
- return { declaration: { ...declaration, stages, ...(refused.length ? { refused } : {}), ...(notes.length ? { notes } : {}) }, dropped: dropped.map(({ line, words, rules }) => ({ line, words, rules })) };
576
- }
package/src/checkwords.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // R10 (fwdloop 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,
3
3
  // the plan card, the draft log and the Audit all read it; nothing else writes these words. Identical to fwdloop v0.29.0 by ruling (match fwd first).
4
4
  /** the rules of bareguard's list a person may pick here (text rules only: the ones a plain answer can be judged by) */
5
- export const OFFERED = Object.freeze(['nonEmpty', 'maxWords', 'minWords', 'maxLines', 'listItems', 'sections', 'sectionOrder', 'sectionWords', 'mustCarry', 'blockLines']);
5
+ export const OFFERED = Object.freeze(['nonEmpty', 'maxWords', 'minWords', 'maxLines', 'listItems', 'maxListItems', 'minListItems', 'sections', 'sectionOrder', 'sectionWords', 'mustCarry', 'blockLines']);
6
6
  const listOf = (/** @type {string[]} */ xs) => xs.join(', ');
7
7
  /**
8
8
  * 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.
@@ -15,6 +15,8 @@ export function plainWords(c) {
15
15
  case 'minWords': return `at least ${c.value} words`;
16
16
  case 'maxLines': return `at most ${c.value} lines`;
17
17
  case 'listItems': return `exactly ${c.value} list items`;
18
+ case 'maxListItems': return `at most ${c.value} list items`;
19
+ case 'minListItems': return `at least ${c.value} list items`;
18
20
  case 'sections': return `sections named ${listOf(c.names ?? [])}`;
19
21
  case 'sectionOrder': return `sections named ${listOf(c.names ?? [])}, in that order`;
20
22
  case 'sectionWords': return `sections named ${listOf(c.names ?? [])}, each about ${c.wordsPerSection} words`;
@@ -102,7 +102,15 @@ export const DECLARED_GENRES = Object.freeze([TYPES_GENRE.name, TEXT_GENRE]);
102
102
  * constrained to the names the genre OWNS, so it can never become an environment
103
103
  * channel of its own.
104
104
  */
105
- export const CLOSE_DECL_FIELDS = Object.freeze(['genre', 'lang', 'stages', 'notes', 'refused', 'guardLines', 'picks', 'genreEnv', 'calibration']);
105
+ export const CLOSE_DECL_FIELDS = Object.freeze(['genre', 'lang', 'stages', 'notes', 'refused', 'guardLines', 'picks', 'list', 'genreEnv', 'calibration']);
106
+
107
+ /** the fields of a row of the one check list that the signed close carries (`closeDecl.list`); the row's own words are never signed */
108
+ export const SIGNED_ROW_FIELDS = Object.freeze(['line', 'key', 'from', 'by', 'kind', 'state', 'rule', 'part', 'reason', 'facts']);
109
+ /** the states a signed row may end in */
110
+ export const SIGNED_STATES = Object.freeze(['built', 'not-checked', 'dropped']);
111
+ const SIGNED_FROM = Object.freeze(['rule', 'pick', 'look', 'agent', 'default']);
112
+ const SIGNED_BY = Object.freeze(['you', 'agent', 'default']);
113
+ const SIGNED_KINDS = Object.freeze(['rule', 'fact', 'cited', 'count', 'phrase', 'numbers', 'floor']);
106
114
 
107
115
  /** what a stored calibration set carries, ENUMERATED: the frozen cases and the judge
108
116
  * tier that graded them. Both are inside the spec, so `jobSpecHash` covers both — which
@@ -321,6 +329,27 @@ export function validateCloseDecl(closeDecl, opts = {}) {
321
329
  + `land here); fields: ${CLOSE_DECL_FIELDS.join(', ')}`);
322
330
  }
323
331
  }
332
+ // the signed copy of the one check list: an array of rows with exactly the signed fields (no words), each in its closed menu
333
+ if (closeDecl.list !== undefined) {
334
+ if (!Array.isArray(closeDecl.list)) red('invalid-value', `${at}.list`, 'the one check list as an array of rows: { line, key, from, by, kind, state, rule?, part?, reason? }');
335
+ else {
336
+ closeDecl.list.forEach((/** @type {any} */ row, /** @type {number} */ i) => {
337
+ const w = `${at}.list[${i}]`;
338
+ if (!isObj(row)) { red('invalid-value', w, 'a row: { line, key, from, by, kind, state, rule?, part?, reason? }'); return; }
339
+ for (const k of Object.keys(row)) if (!SIGNED_ROW_FIELDS.includes(k)) red('unknown-field', `${w}.${k}`, `not a signed row field (the row's own words are never signed); fields: ${SIGNED_ROW_FIELDS.join(', ')}`);
340
+ if (!Number.isInteger(row.line) || row.line < 1) red('invalid-value', `${w}.line`, 'the job line number');
341
+ if (!isNonEmptyString(row.key)) red('invalid-value', `${w}.key`, 'the row key, a non-empty string');
342
+ if (!SIGNED_FROM.includes(row.from)) red('invalid-value', `${w}.from`, `menu: ${SIGNED_FROM.join('|')}`);
343
+ if (!SIGNED_BY.includes(row.by)) red('invalid-value', `${w}.by`, `menu: ${SIGNED_BY.join('|')}`);
344
+ if (!SIGNED_KINDS.includes(row.kind)) red('invalid-value', `${w}.kind`, `menu: ${SIGNED_KINDS.join('|')}`);
345
+ if (!SIGNED_STATES.includes(row.state)) red('invalid-value', `${w}.state`, `menu: ${SIGNED_STATES.join('|')}`);
346
+ if (row.rule !== undefined && !Number.isInteger(row.rule)) red('invalid-value', `${w}.rule`, 'the ~ rule number');
347
+ if (row.part !== undefined && !(isObj(row.part) && Number.isInteger(row.part.line) && Number.isInteger(row.part.part))) red('invalid-value', `${w}.part`, '{ line, part }: the job line and the index of the part that carries the row');
348
+ if (row.reason !== undefined && typeof row.reason !== 'string') red('invalid-value', `${w}.reason`, 'plain words');
349
+ if (row.facts !== undefined && !(Array.isArray(row.facts) && row.facts.every((/** @type {unknown} */ x) => typeof x === 'string'))) red('invalid-value', `${w}.facts`, 'the names of the facts the row built, an array of strings');
350
+ });
351
+ }
352
+ }
324
353
  // PART 1a: a genre is bound to its language — code languages are TYPES, the rubric-files language is TEXT, and neither may
325
354
  // wear the other's label (`lang` is checked just below; an unknown lang reds there)
326
355
  if (!DECLARED_GENRES.includes(closeDecl.genre) || closeDecl.genre !== genreForLang(closeDecl.lang)) {
package/src/destpoint.js CHANGED
@@ -81,8 +81,10 @@ export function decideDestPoint(text, { jobLines, files, destination }) {
81
81
 
82
82
  /** the one question, worded by code @param {DestPoint} p @param {string} destination @returns {string} */
83
83
  export const destQuestionText = (p, destination) => redactSecrets(
84
- `Line ${p.line} needs ${p.file} changed, but Destination is ${destination.trim().replace(/\s*\n\s*/g, ', ')}, so the job could not change it. Set Destination to ${p.folder}? Type yes to set it, or no to keep it as it is.`,
84
+ `Line ${p.line} needs ${p.file} changed, but Destination is ${destination.trim().replace(/\s*\n\s*/g, ', ')}, so the job could not change it. Set Destination to ${p.folder}?${DEST_ANSWER}`,
85
85
  );
86
+ /** the answer words the question ends with (said once, here; the panel's question box shows the question without them and has the buttons instead) */
87
+ export const DEST_ANSWER = ' Type yes to set it, or no to keep it as it is.';
86
88
  /** the answers (any case, a closing full stop allowed) @param {unknown} text @returns {'yes'|'no'|null} */
87
89
  export const yesNoOf = (text) => {
88
90
  const t = String(text ?? '').trim().replace(/\.$/, '').toLowerCase();