bareloop 0.54.0 → 0.55.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 (139) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/bareloop.context.md +73 -12
  3. package/package.json +3 -3
  4. package/src/authorflow.js +148 -46
  5. package/src/authoring.js +21 -4
  6. package/src/authorjob.js +82 -3
  7. package/src/authorreadout.js +20 -3
  8. package/src/authorrun.js +1 -1
  9. package/src/authorscout.js +9 -6
  10. package/src/bridges.js +4 -3
  11. package/src/cardschedule.js +42 -0
  12. package/src/carrystore.js +1 -1
  13. package/src/checkpick.js +576 -0
  14. package/src/checksuggest.js +28 -0
  15. package/src/checkwords.js +25 -0
  16. package/src/cli.js +1 -1
  17. package/src/config.js +24 -1
  18. package/src/declaredclose.js +1 -1
  19. package/src/destpoint.js +149 -0
  20. package/src/draftspend.js +39 -0
  21. package/src/factwords.js +14 -1
  22. package/src/job.js +81 -1
  23. package/src/jobblock.js +9 -0
  24. package/src/labelscan.js +11 -0
  25. package/src/launcher.js +10 -6
  26. package/src/learn.js +6 -4
  27. package/src/mcpchecks.js +52 -0
  28. package/src/mcppick.js +36 -0
  29. package/src/mcpsources.js +77 -0
  30. package/src/mcpuse.js +97 -0
  31. package/src/natural.js +23 -0
  32. package/src/pagemap.js +5 -2
  33. package/src/panel/authorroutes.js +90 -15
  34. package/src/panel/authorsession.js +183 -21
  35. package/src/panel/index.html +686 -26
  36. package/src/panel/jobgrid.js +117 -0
  37. package/src/panel/jobplan.js +31 -15
  38. package/src/panel/scheduler.js +80 -13
  39. package/src/panel/schedules.js +189 -28
  40. package/src/panel/schedulestart.js +44 -13
  41. package/src/panel/server.js +438 -33
  42. package/src/panel/settingsroutes.js +133 -3
  43. package/src/panel/status.js +22 -2
  44. package/src/panel/tickets.js +44 -0
  45. package/src/pickrecord.js +145 -0
  46. package/src/plan.js +31 -2
  47. package/src/planrun.js +71 -15
  48. package/src/prcheckout.js +259 -0
  49. package/src/readshim.js +3 -2
  50. package/src/replay.js +6 -0
  51. package/src/reuse.js +3 -3
  52. package/src/revises.js +56 -0
  53. package/src/rubricstep.js +62 -16
  54. package/src/run.js +10 -1
  55. package/src/runexport.js +2 -0
  56. package/src/runlist.js +3 -2
  57. package/src/schedulewords.js +46 -4
  58. package/src/source.js +81 -7
  59. package/src/stepmcp.js +86 -0
  60. package/src/ticket.js +113 -0
  61. package/src/ticketfilter.js +76 -0
  62. package/src/ticketlabels.js +79 -0
  63. package/src/ticketmcp.js +111 -0
  64. package/src/ticketnext.js +35 -0
  65. package/src/ticketrepo.js +98 -0
  66. package/src/ticketschedule.js +32 -0
  67. package/src/ticketshape.js +45 -0
  68. package/src/tools.js +9 -0
  69. package/src/trigger.js +14 -2
  70. package/src/triggerclock.js +7 -3
  71. package/src/triggerfiles.js +19 -11
  72. package/src/triggertickets.js +244 -0
  73. package/src/u-readout.js +2 -2
  74. package/src/userrun.js +146 -10
  75. package/src/validate.js +3 -1
  76. package/src/worktree.js +43 -1
  77. package/types/authorflow.d.ts +128 -28
  78. package/types/authorjob.d.ts +16 -3
  79. package/types/authorreadout.d.ts +9 -2
  80. package/types/authorscout.d.ts +4 -2
  81. package/types/bridges.d.ts +4 -3
  82. package/types/cardschedule.d.ts +24 -0
  83. package/types/checkpick.d.ts +297 -0
  84. package/types/checksuggest.d.ts +30 -0
  85. package/types/checkwords.d.ts +14 -0
  86. package/types/config.d.ts +7 -0
  87. package/types/destpoint.d.ts +87 -0
  88. package/types/draftspend.d.ts +16 -0
  89. package/types/factwords.d.ts +7 -0
  90. package/types/job.d.ts +13 -0
  91. package/types/jobblock.d.ts +9 -0
  92. package/types/labelscan.d.ts +7 -0
  93. package/types/launcher.d.ts +7 -2
  94. package/types/mcpchecks.d.ts +8 -0
  95. package/types/mcppick.d.ts +33 -0
  96. package/types/mcpsources.d.ts +51 -0
  97. package/types/mcpuse.d.ts +15 -0
  98. package/types/natural.d.ts +2 -0
  99. package/types/pagemap.d.ts +2 -1
  100. package/types/panel/authorroutes.d.ts +11 -2
  101. package/types/panel/authorsession.d.ts +58 -3
  102. package/types/panel/jobgrid.d.ts +405 -0
  103. package/types/panel/jobplan.d.ts +10 -4
  104. package/types/panel/scheduler.d.ts +7 -2
  105. package/types/panel/schedules.d.ts +124 -4
  106. package/types/panel/schedulestart.d.ts +21 -3
  107. package/types/panel/server.d.ts +427 -6
  108. package/types/panel/settingsroutes.d.ts +4 -2
  109. package/types/panel/status.d.ts +16 -2
  110. package/types/panel/tickets.d.ts +61 -0
  111. package/types/pickrecord.d.ts +88 -0
  112. package/types/plan.d.ts +1 -0
  113. package/types/prcheckout.d.ts +151 -0
  114. package/types/readshim.d.ts +4 -3
  115. package/types/replay.d.ts +3 -0
  116. package/types/reuse.d.ts +2 -2
  117. package/types/revises.d.ts +23 -0
  118. package/types/rubricstep.d.ts +14 -5
  119. package/types/run.d.ts +18 -1
  120. package/types/runlist.d.ts +6 -3
  121. package/types/schedulewords.d.ts +29 -2
  122. package/types/source.d.ts +40 -4
  123. package/types/stepmcp.d.ts +40 -0
  124. package/types/ticket.d.ts +114 -0
  125. package/types/ticketfilter.d.ts +34 -0
  126. package/types/ticketlabels.d.ts +44 -0
  127. package/types/ticketmcp.d.ts +84 -0
  128. package/types/ticketnext.d.ts +33 -0
  129. package/types/ticketrepo.d.ts +118 -0
  130. package/types/ticketschedule.d.ts +21 -0
  131. package/types/ticketshape.d.ts +37 -0
  132. package/types/tools.d.ts +1 -0
  133. package/types/trigger.d.ts +9 -1
  134. package/types/triggerclock.d.ts +6 -2
  135. package/types/triggerfiles.d.ts +13 -5
  136. package/types/triggertickets.d.ts +110 -0
  137. package/types/userrun.d.ts +50 -0
  138. package/types/validate.d.ts +1 -0
  139. package/types/worktree.d.ts +19 -0
@@ -0,0 +1,576 @@
1
+ // borrowed-from: fwdloop src/checkpick.js@v0.29.0 (scope, keepOrDrop, SUGGEST_SYSTEM/SUGGEST_SCHEMA, checkAsks, settleRules) and src/declaration.js@v0.29.0 (the guardrail* readers)
2
+ // R10 = fwdloop M10 amendment 16 ("shape guardrails are settled the way item 3-4 settle a source's words"). ONE AI call suggests, per `~` rule of a rubric job, ONE check
3
+ // from bareguard's own list (`rubricVocabulary`) or none; CODE keeps a suggestion only if its rule is on the list, it carries only that rule's own fields, every number
4
+ // is one the rule names and every word is a word of the rule; the person picks (agree / own words / drop it); the plan carries only the checks picked. The drafter writes
5
+ // no check of its own. The prompt, the per-rule answer form and the keep-or-drop are the ones fwd's F144c proved.
6
+ // Throws away: a suggestion's `id`, `field`, `strict`, `text` (code sets them, or they never decide); every rule that code scopes out; what the model says in words.
7
+ // bareloop differences from fwd (ruled 2026-11-09): rubric jobs only; the call runs over bareloop's own `askStructured` ladder (cost booked and the answer logged like every
8
+ // drafting call); a pick lands as a `countable` part of the line's rubric-step stage (src/rubricstep.js), carrying the `~` rule numbers it settles.
9
+ import { rubricVocabulary } from 'bareguard';
10
+ import { plainWords, OFFERED } from './checkwords.js';
11
+ import { KEPT_WORDS } from './pickrecord.js';
12
+ import { lineRules } from './rubricstep.js';
13
+
14
+ export { plainWords, OFFERED };
15
+
16
+ /** the one tool the suggestion call uses */
17
+ export const SUGGEST_TOOL = 'suggest_checks';
18
+ const VOCAB = /** @type {Record<string, {description: string, fields: Record<string, {type: string, required?: boolean}>}>} */ (rubricVocabulary.rules);
19
+ /** fields code sets, or that never decide: never offered, never kept */
20
+ const IGNORED = new Set(['id', 'field', 'text', 'strict']);
21
+ const NUM_FIELDS = ['value', 'size', 'wordsPerSection'];
22
+ const WORD_FIELDS = ['names', 'phrases'];
23
+
24
+ // ---- the guardrail readers (fwd src/declaration.js@v0.29.0) ------------------------------------------------------------------------------
25
+ const readNumber = (/** @type {string} */ t) => Number(t.replace(/,/g, ''));
26
+ /** every whole-output word number in a guardrail ("under 600 words" -> [600]); a "<n> words each" / "per section" size is never listed here @param {unknown} g @returns {number[]} */
27
+ export function guardrailWordNumbers(g) {
28
+ if (typeof g !== 'string') return [];
29
+ return [...g.matchAll(/(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)\s*words?\b(?!\s*(?:each|per\s+section)\b)/gi)].map((m) => readNumber(m[1]));
30
+ }
31
+ /** every standalone number in a guardrail's own text (digits not joined to letters) @param {unknown} g @returns {number[]} */
32
+ export function guardrailStandaloneNumbers(g) {
33
+ if (typeof g !== 'string') return [];
34
+ return [...g.matchAll(/(?<![A-Za-z0-9_.,])(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)(?![A-Za-z0-9_])/g)].map((m) => Number(m[1].replace(/,/g, '')));
35
+ }
36
+ /** the "<n> words each" / "<n> words per section" size, or null @param {unknown} g @returns {number|null} */
37
+ export function guardrailWordsPerSection(g) {
38
+ const m = typeof g === 'string' ? /(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)(?:\s*words?|ish(?:\s+words?)?)\s+(?:each|per\s+section)\b/i.exec(g) : null;
39
+ return m ? readNumber(m[1]) : null;
40
+ }
41
+ const NUMBER_WORDS = /** @type {Record<string, number>} */ ({ one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 });
42
+ /** the first "<N> sections" in a guardrail (digits, or one..ten), or null @param {unknown} g @returns {number|null} */
43
+ export function guardrailSectionCount(g) {
44
+ const m = typeof g === 'string' ? /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?sections?\b/i.exec(g) : null;
45
+ if (!m) return null;
46
+ return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
47
+ }
48
+ /** the first "<N> bullets / list items / items / lines / points" in a guardrail (digits, or one..ten), or null @param {unknown} g @returns {number|null} */
49
+ export function guardrailItemCount(g) {
50
+ const m = typeof g === 'string' ? /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?(?:bullets?|bullet\s+points?|list\s+items?|items?|lines?|points?)\b/i.exec(g) : null;
51
+ if (!m) return null;
52
+ return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
53
+ }
54
+ /** @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
+ export const isCountable = (g) => guardrailWordNumbers(g).length > 0 || guardrailItemCount(g) !== null || guardrailSectionCount(g) !== null;
56
+
57
+ // ---- scope, decided by CODE before the call ----------------------------------------------------------------------------------------------
58
+ /** @param {unknown} v @returns {boolean} the input is a web page (a URL), which routes its rules to the page words (facts) */
59
+ export const isUrlInput = (v) => /^https?:\/\//i.test(String(v ?? '').trim());
60
+ /** @param {{value?: string}[]|null|undefined} inputs @returns {boolean} the job signs an input that routes its rules to another signed part */
61
+ export const hasRoutingInput = (inputs) => (inputs ?? []).some((i) => isUrlInput(i?.value));
62
+ /**
63
+ * A rule goes to this call unless the job signs an input that routes its rules elsewhere (a web page) AND the rule names no whole-output word number (the one thing the
64
+ * shape reader still takes in such a job). fwd's F144b `codeScope`.
65
+ * @param {{value?: string}[]|null|undefined} inputs @param {string} g @returns {'in'|'out'}
66
+ */
67
+ export const codeScope = (inputs, g) => (hasRoutingInput(inputs) && guardrailWordNumbers(g).length === 0 ? 'out' : 'in');
68
+
69
+ /** @typedef {{line: number, rule: number, text: string}} Rule */
70
+ /**
71
+ * Every `~` rule of a rubric job that this call settles, in line order. `rule` is the rule's number on its line (the number a part's `rules` and the answers use). A rule a
72
+ * kept page word already carries (the look tied it by line and rule number) or that the look already put under Not checked is left to that, EXCEPT a countable rule (`isCountable`: a word, list-item/line or section count), which always comes here: the look's fact stays beside the pick (keep-both). A repeated text on a line is
73
+ * one rule here, asked once.
74
+ * @param {{n: number, rule?: string, rules?: string[]}[]} jobLines @param {{inputs?: {value?: string}[]|null, look?: any}} [o]
75
+ * @returns {Rule[]}
76
+ */
77
+ export function scopedRules(jobLines, { inputs = null, look = null } = {}) {
78
+ const facts = Array.isArray(look?.facts) ? look.facts : [];
79
+ const dropped = Array.isArray(look?.dropped) ? look.dropped : [];
80
+ /** @type {Rule[]} */
81
+ const out = [];
82
+ for (const l of Array.isArray(jobLines) ? jobLines : []) {
83
+ const seen = new Set();
84
+ lineRules(l).forEach((text, i) => {
85
+ const key = text.trim().toLowerCase();
86
+ const n = i + 1;
87
+ if (seen.has(key) || codeScope(inputs, text) !== 'in') return;
88
+ // a countable rule always reaches the pick offer: what the look tied or dropped on it stays (keep-both), but never hides the count from the person
89
+ if (!isCountable(text)) {
90
+ if (facts.some((/** @type {any} */ f) => f?.line === l.n && f?.forRule === n)) return;
91
+ if (dropped.some((/** @type {any} */ d) => d?.line === l.n && d?.rule === n)) return;
92
+ }
93
+ seen.add(key);
94
+ out.push({ line: l.n, rule: n, text });
95
+ });
96
+ }
97
+ return out;
98
+ }
99
+
100
+ // ---- code's keep-or-drop (am16 (2)) ------------------------------------------------------------------------------------------------------
101
+ const norm = (/** @type {unknown} */ t) => String(t).toLowerCase().replace(/\s+/g, ' ').trim();
102
+ const tokens = (/** @type {unknown} */ t) => new Set(norm(t).match(/[\p{L}\p{N}]+/gu) ?? []);
103
+
104
+ /**
105
+ * 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 every word in it
106
+ * is a word of the guardrail. Anything else is dropped, with the reason. `none` is a drop with the reason `none`.
107
+ * @param {string} guardrail @param {any} sug the model's entry for this guardrail
108
+ * @returns {{kept: true, check: Record<string, any>}|{kept: false, why: string}}
109
+ */
110
+ export function keepOrDrop(guardrail, sug) {
111
+ if (sug == null || typeof sug !== 'object') return { kept: false, why: 'unreadable suggestion' };
112
+ const { rule } = sug;
113
+ if (rule === 'none' || rule === undefined || rule === null) return { kept: false, why: 'none' };
114
+ if (typeof rule !== 'string' || !Object.hasOwn(VOCAB, rule)) return { kept: false, why: `rule "${rule}" is not on bareguard's list` };
115
+ if (!OFFERED.includes(rule)) return { kept: false, why: `rule "${rule}" is on bareguard's list but is not offered here` };
116
+ const own = Object.keys(VOCAB[rule].fields).filter((k) => !IGNORED.has(k));
117
+ for (const k of own) if (VOCAB[rule].fields[k].required && sug[k] == null) return { kept: false, why: `${rule} needs ${k}` };
118
+ const allowed = new Set([...own, 'rule', 'line', 'guardrail']);
119
+ for (const k of Object.keys(sug)) if (sug[k] != null && !allowed.has(k)) return { kept: false, why: `${rule} does not take ${k}` };
120
+ /** @type {Record<string, any>} */
121
+ const check = { rule };
122
+ for (const k of own) {
123
+ const v = sug[k];
124
+ if (v == null) continue;
125
+ 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` };
127
+ const named = rule === 'maxWords' || rule === 'minWords' ? guardrailWordNumbers(guardrail)
128
+ : k === 'wordsPerSection' ? [guardrailWordsPerSection(guardrail)].filter((x) => x !== null)
129
+ : guardrailStandaloneNumbers(guardrail);
130
+ if (!named.includes(v)) return { kept: false, why: `${k} ${v} is not a number the guardrail names (${named.join(', ') || 'it names none'})` };
131
+ check[k] = v;
132
+ } else if (WORD_FIELDS.includes(k)) {
133
+ 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` };
134
+ const gTok = tokens(guardrail);
135
+ const gNorm = norm(guardrail);
136
+ for (const s of v) {
137
+ if (!gNorm.includes(norm(s))) return { kept: false, why: `${k} "${s}" is not in the guardrail's words` };
138
+ for (const t of tokens(s)) if (!gTok.has(t)) return { kept: false, why: `${k} word "${t}" is not a word of the guardrail` };
139
+ }
140
+ check[k] = v;
141
+ }
142
+ }
143
+ if (rule === 'sections' || rule === 'sectionOrder' || rule === 'sectionWords') {
144
+ const want = guardrailSectionCount(guardrail);
145
+ if (want !== null && check.names.length !== want) return { kept: false, why: `the guardrail says ${want} sections; the check has ${check.names.length}` };
146
+ }
147
+ return { kept: true, check };
148
+ }
149
+
150
+ // ---- the call: prompt, answer form (fwd F144c, per-rule anyOf) ---------------------------------------------------------------------------
151
+ const vocabBlock = OFFERED.map((r) => `- ${VOCAB[r].description}`).join('\n');
152
+ export const SUGGEST_SYSTEM = `You help a person turn the guardrails written under the lines of a job into mechanical checks.
153
+ 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.
154
+
155
+ 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".
156
+
157
+ Rules:
158
+ - 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.
159
+ - 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.
160
+ - Suggest \`sections\` or \`sectionWords\` only when the guardrail itself names the sections.
161
+ - A guardrail like 'all under N words' or 'under N words' is about the whole answer: use maxWords N.
162
+ - 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".
163
+ - Answer for every guardrail once, using the line number and the guardrail number shown.
164
+
165
+ Checks the checker can run (rule({ fields })):
166
+ ${vocabBlock}`;
167
+
168
+ /**
169
+ * 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.
170
+ * @param {{n: number, text: string}[]} lines @param {Rule[]} scoped @returns {string}
171
+ */
172
+ export function suggestUserText(lines, scoped) {
173
+ const out = ['The job:'];
174
+ for (const l of lines) {
175
+ out.push(`${l.n}. ${l.text}`);
176
+ for (const s of scoped) if (s.line === l.n) out.push(` g${s.rule}: ${s.text}`);
177
+ }
178
+ return out.join('\n');
179
+ }
180
+
181
+ const JSON_TYPE = /** @type {Record<string, any>} */ ({ integer: { type: 'integer', minimum: 1 }, 'string-list': { type: 'array', minItems: 1, items: { type: 'string' } } });
182
+ /** @param {string} rule @returns {object} one variant of the answer form: exactly that rule's own fields, nothing else */
183
+ function variant(rule) {
184
+ /** @type {Record<string, any>} */
185
+ 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 } };
186
+ const required = ['line', 'guardrail', 'rule'];
187
+ if (rule !== 'none') {
188
+ for (const [k, f] of Object.entries(VOCAB[rule].fields)) {
189
+ if (IGNORED.has(k)) continue;
190
+ properties[k] = JSON_TYPE[f.type];
191
+ if (f.required) required.push(k);
192
+ }
193
+ }
194
+ return { type: 'object', properties, required, additionalProperties: false };
195
+ }
196
+ /** the tool's parameter schema: one `anyOf` variant per offered rule, plus `none` */
197
+ export const SUGGEST_SCHEMA = Object.freeze({
198
+ type: 'object',
199
+ properties: { checks: { type: 'array', description: 'One entry per guardrail.', items: { anyOf: [...OFFERED, 'none'].map(variant) } } },
200
+ required: ['checks'],
201
+ additionalProperties: false,
202
+ });
203
+
204
+ /** the instruction a retry carries (the structured ladder's own words, naming this tool) */
205
+ export const SUGGEST_INSTRUCTION = `Your reply did not deliver exactly one ${SUGGEST_TOOL} call. Call ${SUGGEST_TOOL} exactly once, with one entry per guardrail as its arguments. Do not write the answer as text.`;
206
+
207
+ /** @param {{calls: any[]}} box the tool the suggestion call is made through; it records and acknowledges, and takes no action */
208
+ export const suggestTool = (box) => ({
209
+ name: SUGGEST_TOOL,
210
+ description: 'Deliver your suggestion for every guardrail. Call this exactly once, with one entry per guardrail.',
211
+ parameters: SUGGEST_SCHEMA,
212
+ execute: async (/** @type {any} */ args) => { box.calls.push(args); return 'suggestions received'; },
213
+ });
214
+ /** the channel `askStructured` (src/authorflow.js) runs the call over */
215
+ export const suggestChannel = () => ({
216
+ name: SUGGEST_TOOL,
217
+ instruction: SUGGEST_INSTRUCTION,
218
+ textPath: 'checks',
219
+ tool: (/** @type {{calls: any[]}} */ box) => suggestTool(box),
220
+ });
221
+
222
+ /**
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 ->
224
+ * 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
+ * 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
+ * @param {string} text @returns {Record<string, any>|null}
227
+ */
228
+ export function countCheck(text) {
229
+ const items = guardrailItemCount(text);
230
+ const words = guardrailWordNumbers(text);
231
+ /** @type {Record<string, any>|null} */
232
+ let built = null;
233
+ 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 };
235
+ 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
+ if (built === null) return null;
237
+ const res = keepOrDrop(text, built);
238
+ return res.kept ? res.check : null;
239
+ }
240
+
241
+ /**
242
+ * What the call's answer comes to, one row per scoped rule: the check kept (or null) and why it was dropped. A rule the answer never mentions is dropped as `no entry`; an
243
+ * entry for a rule that was not sent is ignored.
244
+ * @param {Rule[]} scoped @param {any} args the tool call's arguments
245
+ * @returns {(Rule & {check: Record<string, any>|null, why: string|null})[]}
246
+ */
247
+ export function rowsFromAnswer(scoped, args) {
248
+ const entries = Array.isArray(args?.checks) ? args.checks : [];
249
+ return scoped.map((s) => {
250
+ const e = entries.find((/** @type {any} */ x) => x?.line === s.line && x?.guardrail === s.rule);
251
+ const res = e === undefined ? /** @type {ReturnType<typeof keepOrDrop>} */ ({ kept: false, why: 'no entry' }) : keepOrDrop(s.text, e);
252
+ if (res.kept) return { ...s, check: res.check, why: null };
253
+ // R10 (hamr 2026-11-09): a count rule is never "I can't check this"; with no kept pick from the call, CODE proposes the check its own readers name
254
+ const own = countCheck(s.text);
255
+ return { ...s, check: own, why: own ? null : res.why };
256
+ });
257
+ }
258
+
259
+ // ---- the asks (words are item 4's) -------------------------------------------------------------------------------------------------------
260
+ /** the can't-check ask, as the signed words say it */
261
+ export const CANT_CHECK_WORDS = "I can't check this. Your own words, or Not checked?";
262
+ /** 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
+ }
380
+
381
+ /** 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
+ export function partOfPick(check, text, rules) {
383
+ const { rule, ...fields } = check;
384
+ return { text, class: 'countable', check: rule, ...fields, rules };
385
+ }
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
+ }
@@ -0,0 +1,28 @@
1
+ // R10 (fwdloop M10 am16 (1)): the ONE paid call that suggests, per `~` rule, a check from bareguard's list. It runs over bareloop's own structured ladder (`askStructured`: the ceiling
2
+ // is read before the call, one retry on an unusable reply, cut-off and malformed arguments are named reds, the answer is logged scrubbed), thinking as the drafter's (off).
3
+ // An unusable answer is NOT a guessed check: every rule then reads "I can't check this" (fwd: "one retry on an unusable answer, then every guardrail reads I can't check this").
4
+ import { askStructured, makeCostBook } from './authorflow.js';
5
+ import { suggestChannel, suggestUserText, rowsFromAnswer } from './checkpick.js';
6
+
7
+ /** the label of the call, as the drafting book and the draft log see it */
8
+ export const SUGGEST_LABEL = 'check-suggest';
9
+
10
+ /**
11
+ * @param {{jobLines: {n: number, text: string}[], scoped: {line: number, rule: number, text: string}[], generate: Function, ceilingUsd?: number|null,
12
+ * onCall?: (call: any) => void, priorCalls?: any[], priorRaws?: any[]}} o
13
+ * @returns {Promise<{state: 'ok'|'absent', reason: string|null, rows: ReturnType<typeof rowsFromAnswer>, calls: any[], raws: any[]}>}
14
+ */
15
+ export async function runCheckSuggest({ jobLines, scoped, generate, ceilingUsd = null, onCall = () => {}, priorCalls = [], priorRaws = [] }) {
16
+ const book = makeCostBook({ ceilingUsd, onCall });
17
+ book.absorb(priorCalls, priorRaws);
18
+ const before = book.report().calls.length;
19
+ const beforeRaws = book.raws().length;
20
+ const r = await askStructured({
21
+ messages: [{ role: 'user', content: suggestUserText(jobLines, scoped) }], generate, mode: 'tool', retries: 1, label: SUGGEST_LABEL, book, channel: suggestChannel(),
22
+ });
23
+ const calls = book.report().calls.slice(before);
24
+ const raws = book.raws().slice(beforeRaws);
25
+ if (r.artifact) return { state: 'ok', reason: null, rows: rowsFromAnswer(scoped, r.artifact), calls, raws };
26
+ const reason = r.budget ? 'the spend ceiling was reached' : (r.providerError ?? r.red?.detail ?? 'the answer could not be read');
27
+ return { state: 'absent', reason, rows: rowsFromAnswer(scoped, { checks: [] }), calls, raws };
28
+ }