fwdloop 0.29.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.29.0",
3
+ "version": "0.30.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -51,7 +51,7 @@
51
51
  "dependencies": {
52
52
  "bare-agent": "^0.59.0",
53
53
  "barebrowse": "^0.26.0",
54
- "bareguard": "^0.31.0",
54
+ "bareguard": "^0.34.1",
55
55
  "litectx": "^0.32.0"
56
56
  },
57
57
  "devDependencies": {
@@ -0,0 +1,60 @@
1
+ // M13 am8: the end of a job is added by code, never typed. ONE writer of the added lines (`addEnd`), ONE reader that finds them again in a plan (`addedLinesOf`).
2
+ // Given the card's parsed job steps and its Destination: no Destination -> nothing added; the last line not an Ask -> `ask <wait>: check the result with me`
3
+ // then `write it out`; the last line an Ask -> only `write it out`. The send is always the added `write it out`. The wait is the card's Ask wait (the
4
+ // caller's `jobFileLines` writes it out, as it does for any ask line with no wait of its own).
5
+ // Throws away: nothing. Third outcomes: an empty job adds nothing (the card refuses an empty job before this runs).
6
+
7
+ export const ADDED_ASK_QUESTION = 'check the result with me';
8
+ export const ADDED_WRITE = 'write it out';
9
+
10
+ /**
11
+ * @param {{ n: number, text: string, ask: null | { wait: string|null, question: string }, guardrails: string[] }[]} steps `parseJobBox` steps
12
+ * @param {string} destination the card's Destination ('' = none)
13
+ * @returns {{ steps: { n: number, text: string, ask: null | { wait: string|null, question: string }, guardrails: string[] }[], added: number[] }} the steps with the end added, and the numbers of the added lines
14
+ */
15
+ export function addEnd(steps, destination) {
16
+ if (destination === '' || steps.length === 0) return { steps, added: [] };
17
+ const out = [...steps];
18
+ /** @type {number[]} */
19
+ const added = [];
20
+ if (out[out.length - 1].ask === null) {
21
+ const n = out.length + 1;
22
+ out.push({ n, text: `ask: ${ADDED_ASK_QUESTION}`, ask: { wait: null, question: ADDED_ASK_QUESTION }, guardrails: [] });
23
+ added.push(n);
24
+ }
25
+ const n = out.length + 1;
26
+ out.push({ n, text: ADDED_WRITE, ask: null, guardrails: [] });
27
+ added.push(n);
28
+ return { steps: out, added };
29
+ }
30
+
31
+ /**
32
+ * The added lines of a plan, found again from its signed lines and arbiter: the send line when it reads `write it out`, and the Ask just before it
33
+ * when that reads `check the result with me`. A job signed before M13 am8 (its send line is the person's own words) finds none.
34
+ * @param {{ n: number, text: string }[]} lines @param {{ sends?: { line: number }[], asks?: { line: number }[] }} arbiter
35
+ * @returns {Set<number>}
36
+ */
37
+ export function addedLinesOf(lines, arbiter) {
38
+ const found = new Set();
39
+ const send = (arbiter?.sends ?? [])[0];
40
+ if (!send) return found;
41
+ const textOf = (/** @type {number} */ n) => lines.find((l) => l.n === n)?.text;
42
+ if (textOf(send.line) !== ADDED_WRITE) return found;
43
+ found.add(send.line);
44
+ if (textOf(send.line - 1) === ADDED_ASK_QUESTION && (arbiter.asks ?? []).some((a) => a.line === send.line - 1)) found.add(send.line - 1);
45
+ return found;
46
+ }
47
+
48
+ /**
49
+ * The lines a person typed, found again from a signed job: the signed lines without the send line (the last line when it is the send; today's `write it out`, or
50
+ * the person's own words in a job signed before am8) and without an added Ask before it. ONE reader for the Edit card (`cardFromSigned`) and the job identity (`jobKeyOfSigned`).
51
+ * @template {{ n: number, text: string }} L
52
+ * @param {L[]} lines @param {{ sends?: { line: number }[], asks?: { line: number }[] }} arbiter
53
+ * @returns {L[]}
54
+ */
55
+ export function typedLinesOf(lines, arbiter) {
56
+ const sends = arbiter?.sends ?? [];
57
+ const lastSend = sends.length === 1 && sends[0].line === lines.length ? sends[0].line : null;
58
+ const added = addedLinesOf(lines, arbiter);
59
+ return lines.filter((l) => l.n !== lastSend && !added.has(l.n));
60
+ }
package/src/authoring.js CHANGED
@@ -22,8 +22,9 @@ import path from 'node:path';
22
22
  import { draft } from './drafter.js';
23
23
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
24
24
  import { validateDeclaration, flowTypeOf } from './declaration.js';
25
+ import { addedLinesOf } from './added-end.js';
25
26
  import { factRows } from './citedcheck.js';
26
- import { plainWords } from './checkwords.js';
27
+ import { plainWords, labelled } from './checkwords.js';
27
28
  import { sheetLineBlocks } from './sheetblock.js';
28
29
  import { loadCatalogue } from './catalogue.js';
29
30
  import { WIRED_VERBS } from './primitives.js';
@@ -214,25 +215,28 @@ export function buildReadout({
214
215
  if (Array.isArray(declaration.ticketWatch) && declaration.ticketWatch.length) out.push(` ticket watch: ${declaration.ticketWatch.join(', ')}`);
215
216
  out.push('', READOUT_HEADS.steps);
216
217
  const sheetBlocks = sheetLineBlocks({ declaration, lines });
218
+ const addedLines = addedLinesOf(lines, arbiter); // M13 am8: the lines code added at the end are marked `added`
217
219
  declaration.steps.forEach((st, i) => {
218
- out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
220
+ out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}${addedLines.has(st.fromLine) ? ' [added]' : ''}`);
219
221
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
220
222
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
221
223
  if (Array.isArray(st.mcpTools) && st.mcpTools.length) out.push(` tools: ${st.mcpTools.join(', ')}`);
222
224
  // M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
223
- if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${row}`);
225
+ if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${labelled(row, 'agent')}`);
224
226
  // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
225
227
  if (Array.isArray(st.close?.sheet)) for (const row of sheetBlocks.find((b) => b.line === st.fromLine)?.checked ?? []) out.push(` sheet check: ${row.text}`);
226
228
  // M10 am8 item 2: the column lock, signed with the readout (typed fields)
227
229
  if (Array.isArray(st.close?.columns)) for (const c of st.close.columns) if (typeof c?.column === 'string' && typeof c?.source === 'string') out.push(` cells only from column '${c.column}' of ${c.source}`);
228
230
  // M10 am16: the checks the person picked, signed with the readout, each in the one set of plain words (typed fields, never model prose)
229
- if (Array.isArray(st.close?.shape?.picked)) for (const c of st.close.shape.picked) out.push(` you picked: ${plainWords(c)}`);
231
+ if (Array.isArray(st.close?.shape?.picked)) for (const c of st.close.shape.picked) out.push(` ${labelled(`you picked: ${plainWords(c)}`, 'picked')}`);
232
+ // M10 am22 (1): the checks the person picked for a fact line are signed with the readout too, in the same words
233
+ if (st.close?.class === 'green' && Array.isArray(st.close.picked)) for (const c of st.close.picked) out.push(` ${labelled(`you picked: ${plainWords(c)}`, 'picked')}`);
230
234
  // M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
231
235
  const shape = st.close?.shape;
232
236
  if (Array.isArray(shape?.sections) && shape.sections.length > 0) {
233
237
  const per = Number.isInteger(shape.wordsPerSection) ? ` · about ${shape.wordsPerSection} words each` : '';
234
238
  const lim = Number.isInteger(shape.maxWords) ? ` · under ${shape.maxWords} words` : '';
235
- out.push(` sections: ${shape.sections.join(' · ')}${per}${lim}`);
239
+ out.push(` ${labelled(`sections: ${shape.sections.join(' · ')}${per}${lim}`, 'agent')}`);
236
240
  }
237
241
  });
238
242
  out.push('', READOUT_HEADS.asks);
package/src/checked.js CHANGED
@@ -12,7 +12,7 @@
12
12
  export const NOT_CHECKED_LABEL = "not checked (the AI's own reading)";
13
13
 
14
14
  import { factRows } from './citedcheck.js';
15
- import { plainWords } from './checkwords.js';
15
+ import { plainWords, labelled } from './checkwords.js';
16
16
  import { sheetCheckRows } from './sheetchecks.js';
17
17
  import { sheetLineBlocks } from './sheetblock.js';
18
18
  import { splitReadNotes, signedFactNames } from './pagedropwords.js';
@@ -41,25 +41,27 @@ export function checkedLines(declaration, { hasAsk = true, askLines, lines, csvR
41
41
  const out = [];
42
42
  if (cls === 'green' && st.close.cited && typeof st.close.cited === 'object') {
43
43
  // M10 am7 item 1: the facts the drafter wrote, as plain rows written by code from the typed fields
44
- out.push(`Each result must be quoted word for word from the saved page "${st.close.cited.source}", and the machine checks every quote, every value and the count against that copy.`, ...factRows(st.close.cited));
44
+ out.push(`Each result must be quoted word for word from the saved page "${st.close.cited.source}", and the machine checks every quote, every value and the count against that copy.`, ...factRows(st.close.cited).map((r) => labelled(r, 'agent')));
45
45
  } else if (cls === 'green' && Array.isArray(st.close.sheet)) {
46
46
  // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
47
- out.push('The machine recomputes each of these from the saved sheet and compares it with what the step gave:', ...(sheet ? [] : sheetCheckRows(st.close.sheet)));
47
+ out.push('The machine recomputes each of these from the saved sheet and compares it with what the step gave:', ...(sheet ? [] : sheetCheckRows(st.close.sheet).map((r) => labelled(r, 'agent'))));
48
48
  } else if (cls === 'green') {
49
49
  out.push('Every figure must cite its source cell, or a formula over cells, and the machine recomputes it and compares it with its source.');
50
50
  } else if (cls === 'softgreen') {
51
51
  out.push('The reply is checked as plain text only.');
52
- if (Number.isInteger(shape.maxWords)) out.push(`The whole output is under ${shape.maxWords} words.`);
53
- if (Array.isArray(shape.sections) && shape.sections.length > 0) out.push(`These section headings are there, in this order: ${list(shape.sections)}.`);
54
- if (Number.isInteger(shape.wordsPerSection) && Array.isArray(shape.sections) && shape.sections.length > 0) out.push(`Each of those sections is about ${shape.wordsPerSection} words.`);
55
- if (Number.isInteger(shape.linesPerInvoice)) out.push(`The output comes in blocks of ${shape.linesPerInvoice} lines.`);
56
- if (Array.isArray(shape.mustCarry) && shape.mustCarry.length > 0) out.push(`Every block carries: ${list(shape.mustCarry)}.`);
52
+ if (Number.isInteger(shape.maxWords)) out.push(labelled(`The whole output is under ${shape.maxWords} words.`, 'agent'));
53
+ if (Array.isArray(shape.sections) && shape.sections.length > 0) out.push(labelled(`These section headings are there, in this order: ${list(shape.sections)}.`, 'agent'));
54
+ if (Number.isInteger(shape.wordsPerSection) && Array.isArray(shape.sections) && shape.sections.length > 0) out.push(labelled(`Each of those sections is about ${shape.wordsPerSection} words.`, 'agent'));
55
+ if (Number.isInteger(shape.linesPerInvoice)) out.push(labelled(`The output comes in blocks of ${shape.linesPerInvoice} lines.`, 'agent'));
56
+ if (Array.isArray(shape.mustCarry) && shape.mustCarry.length > 0) out.push(labelled(`Every block carries: ${list(shape.mustCarry)}.`, 'agent'));
57
57
  // M10 am16: each check the person picked, in the words it was picked in (src/checkwords.js, the one place)
58
- if (Array.isArray(shape.picked)) for (const c of shape.picked) out.push(`You picked: ${plainWords(c)}.${keptChecks.some((k) => k.line === st.fromLine && plainWords(k.check) === plainWords(c)) ? ` (${keptWords})` : ''}`);
58
+ if (Array.isArray(shape.picked)) for (const c of shape.picked) out.push(labelled(`You picked: ${plainWords(c)}.${keptChecks.some((k) => k.line === st.fromLine && plainWords(k.check) === plainWords(c)) ? ` (${keptWords})` : ''}`, 'picked'));
59
59
  } else {
60
60
  if (lastAsk !== -1 && i > lastAsk) out.push('No machine check of the content; you check it after you accept.');
61
61
  else out.push(hasAsk ? 'No machine check of the content: you check it at the ask.' : 'No machine check of the content; the machine checks only that the step happened.');
62
62
  }
63
+ // M10 am22 (1)(4): the checks the person picked for a fact line, beside its fact rows
64
+ if (cls === 'green' && Array.isArray(st.close.picked)) for (const c of st.close.picked) out.push(labelled(`You picked: ${plainWords(c)}.${keptChecks.some((k) => k.line === st.fromLine && plainWords(k.check) === plainWords(c)) ? ` (${keptWords})` : ''}`, 'picked'));
63
65
  return {
64
66
  step: i + 1, line: Number.isInteger(st?.fromLine) ? st.fromLine : null, goal: typeof st?.goal === 'string' ? st.goal : '', class: String(cls), sentences: out,
65
67
  ...(sheet && cls === 'green' ? { sheet } : {}),
package/src/checkpick.js CHANGED
@@ -10,7 +10,7 @@ import { isCellsPath } from './closers.js';
10
10
  import { plainWords, OFFERED } from './checkwords.js';
11
11
 
12
12
  export { plainWords, OFFERED };
13
- import { guardrailWordNumbers, guardrailStandaloneNumbers, guardrailWordsPerSection, guardrailSectionCount } from './declaration.js';
13
+ import { guardrailWordNumbers, guardrailStandaloneNumbers, guardrailWordsPerSection, guardrailSectionCount, guardrailItemCount, isCountGuardrail } from './declaration.js';
14
14
 
15
15
  /** the one tool the suggestion call is forced to use */
16
16
  export const SUGGEST_TOOL = 'suggest_checks';
@@ -24,11 +24,11 @@ const WORD_FIELDS = ['names', 'phrases'];
24
24
  /** @param {any[]|undefined} sources the job's signed inputs @returns {boolean} a CSV file or a web page routes its guardrails to another signed part (M10 items 1-3, M12) */
25
25
  export const hasRoutingInput = (sources) => (sources ?? []).some((s) => (s.kind === 'file' && isCellsPath(s.path)) || s.kind === 'page');
26
26
  /**
27
- * A guardrail goes to this call unless the job signs an input that routes its guardrails elsewhere AND the guardrail names no whole-output word number
28
- * (the one thing the shape reader still takes in such a job). A page job whose guardrail carries a word number therefore counts as in (F144b caveat).
27
+ * A guardrail goes to this call unless the job signs an input that routes its guardrails elsewhere AND the guardrail is not a count code can check (M10 am23: words, items, sections)
28
+ * (the one thing the shape reader still takes in such a job). A page job whose guardrail is a count therefore counts as in (F144b caveat).
29
29
  * @param {any[]|undefined} sources @param {string} g @returns {'in'|'out'}
30
30
  */
31
- export const codeScope = (sources, g) => (hasRoutingInput(sources) && guardrailWordNumbers(g).length === 0 ? 'out' : 'in');
31
+ export const codeScope = (sources, g) => (hasRoutingInput(sources) && !isCountGuardrail(g) ? 'out' : 'in');
32
32
 
33
33
  /**
34
34
  * Every guardrail rule on a step line (not a signed ask or send line) that this call settles, in line order. `rule` is the rule's number on its line (the one
@@ -53,6 +53,12 @@ export function scopedRules(lines, arbiter) {
53
53
  return out;
54
54
  }
55
55
 
56
+ /**
57
+ * The rules the suggestion call offers for a draft: `scopedRules` less the ones a kept page or sheet fact already serves (the look tied it: line + rule number).
58
+ * @param {{n: number, guardrail?: string}[]} lines @param {any} arbiter @param {{line: number, forRule?: number}[]} facts `look.facts` + the sheets' facts
59
+ */
60
+ export const offerRules = (lines, arbiter, facts) => scopedRules(lines, arbiter).filter((r) => isCountGuardrail(r.text) || !facts.some((f) => f.line === r.line && f.forRule === r.rule));
61
+
56
62
  // ---- code's keep-or-drop (am16 (2)) --------------------------------------------------------------------------------------------------------
57
63
  const norm = (/** @type {unknown} */ t) => String(t).toLowerCase().replace(/\s+/g, ' ').trim();
58
64
  const tokens = (/** @type {unknown} */ t) => new Set(norm(t).match(/[\p{L}\p{N}]+/gu) ?? []);
@@ -168,10 +174,33 @@ export function rowsFromAnswer(scoped, args) {
168
174
  return scoped.map((s) => {
169
175
  const e = entries.find((/** @type {any} */ x) => x?.line === s.line && x?.guardrail === s.rule);
170
176
  const res = e === undefined ? /** @type {ReturnType<typeof keepOrDrop>} */ ({ kept: false, why: 'no entry' }) : keepOrDrop(s.text, e);
171
- return { ...s, check: res.kept ? res.check : null, why: res.kept ? null : res.why };
177
+ if (res.kept) return { ...s, check: res.check, why: null };
178
+ // M10 am27 (3): a count rule is never "I can't check this"; with nothing kept from the call, CODE proposes the check its own readers name
179
+ const own = countCheck(s.text);
180
+ return { ...s, check: own, why: own ? null : res.why };
172
181
  });
173
182
  }
174
183
 
184
+ // borrowed-from: bareloop src/checkpick.js@0408a8f (countCheck, 5a81681; one reader file differs: fwdloop's declaration.js has the same three readers)
185
+ /**
186
+ * The check CODE proposes for a count rule when the call yields none: a bullets / list-items / points count -> listItems N, a lines count -> maxLines N, ONE word number ->
187
+ * minWords N when the rule says "at least / minimum / more than", else maxWords N. A section count names no sections, so none is built; a rule naming two different counts is
188
+ * not built either; a rule with several word numbers or a range is not guessed. The result passes `keepOrDrop`, so every number is one the rule names.
189
+ * @param {string} text @returns {Record<string, any>|null}
190
+ */
191
+ export function countCheck(text) {
192
+ const items = guardrailItemCount(text);
193
+ const words = guardrailWordNumbers(text);
194
+ /** @type {Record<string, any>|null} */
195
+ let built = null;
196
+ if (items !== null && (words.length > 0 || guardrailSectionCount(text) !== null)) return null;
197
+ if (items !== null) built = { rule: /\blines?\b/i.test(text) && !/\b(bullets?|items?|points?)\b/i.test(text) ? 'maxLines' : 'listItems', value: items };
198
+ else if (words.length === 1 && !/\bbetween\b|\d\s*(?:-|–|to)\s*\d/i.test(text)) built = { rule: /\b(at least|min(?:imum)?|more than|over|no fewer than)\b/i.test(text) ? 'minWords' : 'maxWords', value: words[0] };
199
+ if (built === null) return null;
200
+ const res = keepOrDrop(text, built);
201
+ return res.kept ? res.check : null;
202
+ }
203
+
175
204
  // ---- the asks (words are item 4's) -----------------------------------------------------------------------------------------------------
176
205
  /** the can't-check ask, as the signed words say it */
177
206
  export const CANT_CHECK_WORDS = "I can't check this. Your own words, or Not checked?";
@@ -235,11 +264,20 @@ export function applyPicks(declaration, rules, settled, sentence) {
235
264
  const green = (/** @type {number} */ n) => declaration.steps.some((/** @type {any} */ st) => st?.fromLine === n && st?.close?.class === 'green');
236
265
  const mine = (/** @type {number} */ n) => lineSet.has(n) && !green(n);
237
266
  const steps = declaration.steps.map((/** @type {any} */ st) => {
267
+ // M10 am22 (1): a fact line keeps its fact close and adds the person's picks to it (`close.picked`); the line stays green
268
+ if (st && typeof st === 'object' && lineSet.has(st.fromLine) && green(st.fromLine)) {
269
+ const { picked: _own, ...close } = st.close ?? {};
270
+ const kept = settled.checks.get(st.fromLine) ?? [];
271
+ return { ...st, close: kept.length && st.close?.class === 'green' ? { ...close, picked: kept } : close };
272
+ }
238
273
  if (!st || typeof st !== 'object' || !mine(st.fromLine)) return st;
239
274
  const picked = settled.checks.get(st.fromLine) ?? [];
240
275
  return { ...st, close: picked.length ? { class: 'softgreen', shape: { picked } } : { class: 'hitl' } };
241
276
  });
242
277
  const out = { ...declaration, steps };
278
+ // M10 am22 (3): the record of the fact lines that carry the person's picks, written here and nowhere else; whatever the drafter sent for it is gone
279
+ const pickedLines = [...new Set(steps.filter((/** @type {any} */ st) => Array.isArray(st?.close?.picked) && st.close.class === 'green').map((/** @type {any} */ st) => st.fromLine))].sort((a, b) => a - b);
280
+ if (pickedLines.length) out.pickedLines = pickedLines; else delete out.pickedLines;
243
281
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
244
282
  if (isRec(declaration.guardrailClasses)) {
245
283
  out.guardrailClasses = { ...declaration.guardrailClasses };
@@ -255,3 +293,26 @@ export function applyPicks(declaration, rules, settled, sentence) {
255
293
  }
256
294
  return out;
257
295
  }
296
+
297
+ // borrowed-from: bareloop src/checkpick.js@0408a8f (retentionOf, 890affa; adapted to fwdloop's one close per line: a unit is one cited fact of the line's step)
298
+ /**
299
+ * M10 am27 (4) RETENTION record of one draft (record only, counts, no words). Per job line: `aiParts` = the cited facts the drafter wrote on that line (a `cited` close counts once per
300
+ * fact, at least 1), `kept` = how many are still in the final declaration, `dropped` = what code removed, `picks` = the line has the person's picks; `classAsked` / `classFinal`
301
+ * = the line's close class as the drafter sent it and as it ended. Pure.
302
+ * @param {any} drafted the declaration as the drafter sent it @param {any} final the declaration the draft ended with @param {any[]|null|undefined} jobLines @param {Iterable<number>} [pickLines]
303
+ * @returns {{line: number, aiParts: number, kept: number, dropped: number, picks: boolean, classAsked: string|null, classFinal: string|null}[]}
304
+ */
305
+ export function retentionOf(drafted, final, jobLines, pickLines = []) {
306
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
307
+ if (!isRec(drafted) || !Array.isArray(drafted.steps) || !isRec(final) || !Array.isArray(final.steps)) return [];
308
+ const stepsOn = (/** @type {any} */ d, /** @type {number} */ n) => d.steps.filter((/** @type {any} */ st) => isRec(st) && st.fromLine === n);
309
+ const units = (/** @type {any[]} */ steps) => steps.reduce((/** @type {number} */ sum, /** @type {any} */ st) => (isRec(st.close) && isRec(st.close.cited) ? sum + Math.max(1, Array.isArray(st.close.cited.facts) ? st.close.cited.facts.length : 0) : sum), 0);
310
+ const classOf = (/** @type {any[]} */ steps) => (isRec(steps[0]?.close) && typeof steps[0].close.class === 'string' ? steps[0].close.class : null);
311
+ const withPicks = new Set(pickLines);
312
+ return (Array.isArray(jobLines) ? jobLines : []).filter((l) => isRec(l) && Number.isInteger(l.n)).map((l) => {
313
+ const was = stepsOn(drafted, l.n); const now = stepsOn(final, l.n);
314
+ const aiParts = units(was);
315
+ const kept = Math.min(aiParts, units(now));
316
+ return { line: l.n, aiParts, kept, dropped: aiParts - kept, picks: withPicks.has(l.n), classAsked: classOf(was), classFinal: classOf(now) };
317
+ });
318
+ }
package/src/checkwords.js CHANGED
@@ -2,6 +2,11 @@
2
2
  // the plan card (src/checked.js), the softgreen close's check list (src/closers.js) and the Audit all read it; nothing else writes these words.
3
3
  /** the rules of bareguard's list a person may pick here (text rules only: the ones a plain answer can be judged by) */
4
4
  export const OFFERED = Object.freeze(['nonEmpty', 'maxWords', 'minWords', 'maxLines', 'listItems', 'sections', 'sectionOrder', 'sectionWords', 'mustCarry', 'blockLines']);
5
+ /** M10 am22 (4): who added a check, the ONE place these two words live. The plan card, the Job tab and the Audit trail write them after the check's words. */
6
+ export const LABEL_AGENT = '[agent]';
7
+ export const LABEL_PICKED = '[you picked]';
8
+ /** @param {string} text @param {'agent'|'picked'} by */
9
+ export const labelled = (text, by) => `${text} ${by === 'picked' ? LABEL_PICKED : LABEL_AGENT}`;
5
10
  const listOf = (/** @type {string[]} */ xs) => xs.join(', ');
6
11
  /**
7
12
  * The check in plain words, one fixed phrase per rule: the ask, the `~` line an agree writes, the plan card and the Audit all read this one function.
package/src/citedcheck.js CHANGED
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { createHash } from 'node:crypto';
17
17
  import { createRubric, checkStep } from 'bareguard';
18
+ import { plainWords } from './checkwords.js';
18
19
  import { asList, FACT_OPS, boundOk, MAX_CURRENCIES, MAX_UNITS, MAX_UNIT_CHARS } from './pagebits.js';
19
20
  import { ruleWords, moneyAs } from './pageask.js';
20
21
 
@@ -236,6 +237,19 @@ export function citedBrief(part) {
236
237
  };
237
238
  }
238
239
 
240
+ /**
241
+ * M10 am28: what a page-quoting step is told about the picks (am22) on its line, one plain line per pick, the values and what counts, never a verdict and never
242
+ * another guardrail. A list item is what bareguard's listItems counts: its own line starting with "1." or "- " followed by a space and its text.
243
+ * @param {any[]} picked @returns {string[]}
244
+ */
245
+ export function toldPicks(picked) {
246
+ return picked.map((c) => {
247
+ if (c.rule === 'listItems') return `Your "text" must have exactly ${c.value} list items; a list item is its own line starting with "1." or "- " followed by a space and its text.`;
248
+ if (c.rule === 'nonEmpty') return 'Your "text" must not be empty.';
249
+ return `Your "text" must have ${plainWords(c)}.`;
250
+ });
251
+ }
252
+
239
253
  /**
240
254
  * Every plan-card row a fact part carries: its facts, then its count (bareloop's factRows).
241
255
  * @param {any} part @returns {string[]}
package/src/closers.js CHANGED
@@ -239,7 +239,7 @@ function describeArtifact(artifact) {
239
239
  * Async because bareguard's `checkStep` is.
240
240
  *
241
241
  * @param {any} artifact
242
- * @param {{ maxWords?: number, sections?: string[], wordsPerSection?: number, linesPerInvoice?: number, mustCarry?: string[] }} shape
242
+ * @param {{ maxWords?: number, sections?: string[], wordsPerSection?: number, linesPerInvoice?: number, mustCarry?: string[], picked?: any[] }} shape
243
243
  * @returns {Promise<CloseVerdict>}
244
244
  */
245
245
  export async function closeSoftgreen(artifact, shape) {
@@ -271,7 +271,7 @@ export async function closeSoftgreen(artifact, shape) {
271
271
  /**
272
272
  * The one dispatcher — `close by declared class` (M2 scope item 4).
273
273
  *
274
- * @param {{ close?: { class?: string, shape?: Record<string, any>, cited?: any, columns?: {source: string, column: string}[], sheet?: any[] } }} step
274
+ * @param {{ close?: { class?: string, shape?: Record<string, any>, picked?: any[], cited?: any, columns?: {source: string, column: string}[], sheet?: any[] } }} step
275
275
  * @param {unknown} artifact
276
276
  * @param {{ reads: Record<string, any>, businessDate: string, source?: {ok: true, text: string, sha256: string}|{ok: false, red: string}|null, sheet?: any }} ctx
277
277
  * `source` (M10 piece 4) = the run's own frozen copy a cited step reads, from `readRunSource`; only a step whose close carries `cited` reads it
@@ -279,6 +279,36 @@ export async function closeSoftgreen(artifact, shape) {
279
279
  * @returns {Promise<CloseVerdict>}
280
280
  */
281
281
  export async function closeByClass(step, artifact, ctx) {
282
+ const cls = step?.close?.class;
283
+ if (cls === 'green' && Array.isArray(step?.close?.picked) && step.close.picked.length > 0) return await closeFactAndPicks(step, artifact, ctx);
284
+ return await closeOne(step, artifact, ctx);
285
+ }
286
+
287
+ /**
288
+ * M10 am22 (1): a fact line (cited / sheet) that also carries the checks the person picked. The artifact is `{results|claims..., text}`: the fact half reads
289
+ * everything but `text`, the picks read `text` (the softgreen close, unchanged). Green only if both are green. A red in either is red (both reasons told);
290
+ * a third outcome (unparseable, crash) of either half is never turned into green: the fact half's wins when it has one, else the picks' own.
291
+ * @param {any} step @param {unknown} artifact @param {Parameters<typeof closeOne>[2]} ctx @returns {Promise<CloseVerdict>}
292
+ */
293
+ async function closeFactAndPicks(step, artifact, ctx) {
294
+ const rec = artifact && typeof artifact === 'object' && !Array.isArray(artifact);
295
+ const { text, ...factArtifact } = rec ? /** @type {Record<string, any>} */ (artifact) : /** @type {Record<string, any>} */ ({});
296
+ const fact = /** @type {any} */ (await closeOne(step, rec ? factArtifact : artifact, ctx));
297
+ // am22 (2): missing text is red, never green. Code adds the `nonEmpty` floor to the person's picks (a count like "at most 80 words" passes an empty text), so empty = missing.
298
+ const picked = step.close.picked.some((/** @type {any} */ c) => c.rule === 'nonEmpty') ? step.close.picked : [...step.close.picked, { rule: 'nonEmpty' }];
299
+ const picks = /** @type {any} */ (typeof text === 'string'
300
+ ? await closeSoftgreen({ text }, { picked })
301
+ : { verdict: 'red', red: 'no text: the answer has no "text" for your checks to read', checks: [{ id: 'text', text: plainWords({ rule: 'nonEmpty' }), ok: false, result: 'no text' }] });
302
+ const pickChecks = Array.isArray(picks.checks) ? picks.checks.filter((/** @type {any} */ c) => c.id !== 'keys') : picks.checks; // the one-key row is code's, always true here
303
+ if (fact.verdict === 'crash' || fact.verdict === 'unparseable') return { ...fact, pickChecks };
304
+ if (picks.verdict === 'crash' || picks.verdict === 'unparseable') return fact.verdict === 'red' ? { ...fact, pickChecks } : { ...picks, cited: fact.cited, sheetRecord: fact.sheetRecord, checks: fact.checks };
305
+ if (fact.verdict === 'green' && picks.verdict === 'green') return { ...fact, pickChecks };
306
+ const reds = [...(fact.verdict === 'red' ? [fact.red] : []), ...(picks.verdict === 'red' ? [picks.red] : [])].filter(Boolean);
307
+ return { ...fact, verdict: 'red', red: reds.join('\n'), reds, pickChecks };
308
+ }
309
+
310
+ /** @param {any} step @param {unknown} artifact @param {{ reads: Record<string, any>, businessDate: string, source?: any, sheet?: any }} ctx @returns {Promise<CloseVerdict>} */
311
+ async function closeOne(step, artifact, ctx) {
282
312
  const cls = step?.close?.class;
283
313
  if (cls === 'green' && step?.close?.cited) return await closeCited(step.close.cited, artifact, ctx.source);
284
314
  if (cls === 'green' && Array.isArray(step?.close?.sheet)) return await closeSheet(step.close.sheet, artifact, ctx.sheet);
@@ -64,6 +64,7 @@ export const DECLARATION_FIELDS = Object.freeze([
64
64
  'flowType',
65
65
  'ticketFilter',
66
66
  'ticketWatch',
67
+ 'pickedLines',
67
68
  // step level
68
69
  'goal',
69
70
  'primitives',
@@ -79,6 +80,7 @@ export const DECLARATION_FIELDS = Object.freeze([
79
80
  'cited',
80
81
  'columns',
81
82
  'sheet',
83
+ 'picked',
82
84
  ]);
83
85
 
84
86
  const VALID_CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
@@ -89,9 +91,9 @@ const VALID_CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
89
91
  // an ask's position, an ask's TTL, the egress allow-list...").
90
92
  const ARBITER_KEYS = Object.freeze(['cap', 'ask', 'ttl', 'send', 'source', 'trigger', 'skills']);
91
93
 
92
- const TOP_LEVEL_ALLOWED = Object.freeze(['steps', 'guardrailClasses', 'unjudgeable', 'refused', 'inputFacts', 'mcp', 'flowType', 'ticketFilter', 'ticketWatch']);
94
+ const TOP_LEVEL_ALLOWED = Object.freeze(['steps', 'guardrailClasses', 'unjudgeable', 'refused', 'inputFacts', 'mcp', 'flowType', 'ticketFilter', 'ticketWatch', 'pickedLines']);
93
95
  const STEP_ALLOWED = Object.freeze(['goal', 'primitives', 'reads', 'emits', 'fromLine', 'close', 'picks', 'mcpTools']);
94
- const CLOSE_ALLOWED = Object.freeze(['class', 'shape', 'cited', 'columns', 'sheet']);
96
+ const CLOSE_ALLOWED = Object.freeze(['class', 'shape', 'cited', 'columns', 'sheet', 'picked']);
95
97
 
96
98
  /** M13 piece 4 (signed item 4): the job's flow type, set by code from the job card, signed with the job. */
97
99
  export const FLOW_TYPES = Object.freeze(['plain', 'mcp', 'tickets']);
@@ -416,6 +418,16 @@ export function guardrailSectionCount(guardrail) {
416
418
  return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
417
419
  }
418
420
 
421
+ /** M10 amendment 23: the first "<N> bullets / list items / items / lines / points" in a guardrail (N digits, or the words one..ten; not a price like "$5 per item"), or null. */
422
+ export function guardrailItemCount(guardrail) {
423
+ const m = typeof guardrail === 'string' ? /(?<![$€£\d.,])\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?(?:bullets?|list items?|items?|lines?|points?)\b/i.exec(guardrail) : null;
424
+ if (!m) return null;
425
+ return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
426
+ }
427
+
428
+ /** M10 amendment 23: the ONE place that says a guardrail is a count code can check: N words, N bullets / list items / items / lines / points, or N sections. */
429
+ export const isCountGuardrail = (guardrail) => guardrailWordNumbers(guardrail).length > 0 || guardrailItemCount(guardrail) !== null || guardrailSectionCount(guardrail) !== null;
430
+
419
431
  /** M4e amendment 15 item 2: for each line whose guardrail gives a size for each section, a section count AND a word number,
420
432
  * size x count more than the LARGEST word number (no possible pick fits) is a red naming the line and the numbers. $0; run before any model
421
433
  * call, when there is no AI pick yet (amendment 29). After the draft the AI's `maxWords` is checked in checkShapeFitsJobLine. */
@@ -544,6 +556,36 @@ function checkShapeBuilds(shape, label, reds, redsBefore) {
544
556
  }
545
557
  }
546
558
 
559
+ /**
560
+ * M10 am22 (3): `pickedLines` is the record of the fact lines that carry the person's picks: a list of line numbers. Code writes it (src/checkpick.js applyPicks).
561
+ * @param {Record<string, any>} declaration @param {string[]} reds
562
+ */
563
+ function checkPickedLines(declaration, reds) {
564
+ if (!Object.hasOwn(declaration, 'pickedLines')) return;
565
+ const v = declaration.pickedLines;
566
+ if (!Array.isArray(v) || v.length === 0 || !v.every((n) => Number.isInteger(n) && n > 0)) reds.push('declaration: "pickedLines" must be a non-empty list of line numbers');
567
+ }
568
+
569
+ /**
570
+ * M10 am22: `close.picked` is the checks the person picked for a fact line, kept beside its fact check and run on the answer's `text`. Code sets it (src/checkpick.js
571
+ * applyPicks); here it must be a green step's, a list of bareguard text rules that builds into a check.
572
+ * It is allowed ONLY on a line the signed plan records in `pickedLines` (written by code from the person's picks); a count on any other fact line is refused.
573
+ * @param {any} step @param {string} label @param {string} effectiveClass @param {string[]} reds @param {Record<string, any>} declaration
574
+ */
575
+ function checkPickedKey(step, label, effectiveClass, reds, declaration) {
576
+ const at = `declaration: ${label}.close.picked`;
577
+ if (step.close.class !== 'green' || effectiveClass !== 'green' || !(isPlainObject(step.close.cited) || Array.isArray(step.close.sheet))) {
578
+ reds.push(`${at} is for a step that checks facts (quotes or a sheet) only; this step's check is "${step.close.class ?? effectiveClass}"`);
579
+ return;
580
+ }
581
+ if (!Array.isArray(declaration.pickedLines) || !declaration.pickedLines.includes(step.fromLine)) {
582
+ reds.push(`${at}: line ${step.fromLine} is not one of the lines you picked checks for (pickedLines), so a count check cannot sit beside its fact check`);
583
+ return;
584
+ }
585
+ if (!SHAPE_TYPE_CHECKS.picked.check(step.close.picked)) { reds.push(`${at} must be ${SHAPE_TYPE_CHECKS.picked.expected}`); return; }
586
+ try { buildSoftgreenRubric({ picked: step.close.picked }); } catch (err) { reds.push(`${at} cannot be built into a check - ${String(err.message).replace(/^invalid rubric: /, '')}`); }
587
+ }
588
+
547
589
  /**
548
590
  * M10 amendment 7 item 1: `close.cited` is the facts a green step checks its quotes against, written by the drafter (a fact part:
549
591
  * `{source, facts, count?}`, src/citedcheck.js). Its SHAPE is checked in every mode (a signed flow is read the same way). With `fitJobLine` the number rules
@@ -724,6 +766,7 @@ export function validateDeclaration(declaration, context = {}) {
724
766
 
725
767
  // --- top level: unknown / arbiter keys -----------------------------------
726
768
  checkOwnKeys(declaration, TOP_LEVEL_ALLOWED, 'declaration', reds);
769
+ checkPickedLines(declaration, reds);
727
770
 
728
771
  // --- steps: must be a non-empty array, or nothing else here is meaningful
729
772
  if (!Array.isArray(declaration.steps) || declaration.steps.length === 0) {
@@ -980,6 +1023,10 @@ export function validateDeclaration(declaration, context = {}) {
980
1023
  if (fitJobLine === true) checkShapeFitsJobLine(step, i, safeLines, reds);
981
1024
  }
982
1025
  }
1026
+ if (step.close.picked !== undefined) checkPickedKey(step, label, effectiveClass, reds, declaration);
1027
+ else if (fitJobLine === true && effectiveClass === 'green' && step.close.shape !== undefined && step.close.shape !== null) {
1028
+ reds.push(`declaration: ${label}.close.shape: a step that checks facts carries no count check of the drafter's own; only a check you picked (close.picked, on a line recorded in pickedLines) can sit beside its fact check`);
1029
+ }
983
1030
  if (step.close.cited !== undefined) checkCitedKey(step, label, { sourceRoles, reads, effectiveClass, lines: safeLines, fitJobLine, pageWords }, reds);
984
1031
  if (step.close.sheet !== undefined) checkSheetKey(step, label, { cellsRoles, reads, effectiveClass, lines: safeLines, fitJobLine, sheetWords }, reds);
985
1032
  if (step.close.columns !== undefined || (fitJobLine === true && sheetWords)) checkColumnsKey(step, label, { cellsRoles, reads, effectiveClass, lines: safeLines, sheetWords }, reds);
@@ -7,7 +7,7 @@
7
7
  // Throws away: the log's per-round tokens, the model's replies, the questions, and every try but the count of refused ones.
8
8
  // Third outcomes: no log -> null (nothing to list); a cost that is null reads "cost unknown", an incomplete sum reads "at least $X", never 0.
9
9
 
10
- import { plainPlanCheck } from './plain-checks.js';
10
+ import { plainPlanCheck, pickPlanRed } from './plain-checks.js';
11
11
 
12
12
  const REBUILD_RE = /^declaration: steps\[(\d+)\]\.close\.shape cannot be built into a check — (.*)$/s;
13
13
 
@@ -88,7 +88,7 @@ export function draftStepList({ log, declaration, questionOpen = false }) {
88
88
  out.push({ id: 'checks', label: 'plan checks · a question for you', status: 'waiting', details: [] });
89
89
  } else {
90
90
  // one plain reason and its one Fix line (every rule has fix wording): the first refusal
91
- const pick = checkReds.map(plainPlanCheck)[0];
91
+ const pick = checkReds.length > 0 ? plainPlanCheck(pickPlanRed(checkReds)) : undefined;
92
92
  out.push({ id: 'checks', label: pick ? `plan checks · ${pick.reason}` : 'plan checks', status: 'failed', details: [] });
93
93
  if (pick) out.push({ id: 'checks-fix', label: `Fix: ${pick.fix}`, status: 'done', details: [], note: true });
94
94
  }
@@ -130,7 +130,7 @@ export function reviseStepList({ log, name }) {
130
130
  if (reds.length > 0) facts.push(reds[0]);
131
131
  return [{ id: 'plan', label: facts.join(' · '), status: 'failed', details: [] }];
132
132
  }
133
- const pick = plainPlanCheck(checkReds[0]);
133
+ const pick = plainPlanCheck(pickPlanRed(checkReds));
134
134
  return [
135
135
  { id: 'plan', label: [name, pick.reason].join(' · '), status: 'failed', details: [] },
136
136
  { id: 'plan-fix', label: `Fix: ${pick.fix}`, status: 'done', details: [], note: true },