fwdloop 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +27 -5
  3. package/package.json +3 -3
  4. package/src/ask.js +1 -1
  5. package/src/audit-fold.js +9 -1
  6. package/src/authoring.js +11 -4
  7. package/src/checked.js +5 -2
  8. package/src/checkpick.js +257 -0
  9. package/src/checkwords.js +24 -0
  10. package/src/closers.js +8 -1
  11. package/src/declaration.js +53 -3
  12. package/src/drafter.js +114 -33
  13. package/src/learn.js +1 -1
  14. package/src/learnstore.js +6 -6
  15. package/src/memo.js +120 -0
  16. package/src/model-step.js +89 -17
  17. package/src/pageask.js +9 -6
  18. package/src/pagedropwords.js +9 -0
  19. package/src/panel/author.js +31 -9
  20. package/src/panel/authorcard.js +51 -2
  21. package/src/panel/data.js +12 -7
  22. package/src/panel/index.html +137 -59
  23. package/src/panel/result.js +28 -7
  24. package/src/panel/server.js +2 -1
  25. package/src/pickrecord.js +146 -0
  26. package/src/plain-checks.js +1 -0
  27. package/src/provider.js +4 -1
  28. package/src/runfile.js +4 -2
  29. package/src/runner.js +82 -30
  30. package/src/send.js +71 -4
  31. package/src/setup.js +13 -1
  32. package/types/ask.d.ts +2 -1
  33. package/types/audit-fold.d.ts +13 -2
  34. package/types/authoring.d.ts +6 -2
  35. package/types/checked.d.ts +7 -2
  36. package/types/checkpick.d.ts +149 -0
  37. package/types/checkwords.d.ts +14 -0
  38. package/types/closers.d.ts +2 -1
  39. package/types/declaration.d.ts +9 -0
  40. package/types/drafter.d.ts +12 -25
  41. package/types/learn.d.ts +1 -0
  42. package/types/learnstore.d.ts +2 -3
  43. package/types/memo.d.ts +15 -0
  44. package/types/model-step.d.ts +5 -0
  45. package/types/pageask.d.ts +9 -2
  46. package/types/pagedropwords.d.ts +1 -0
  47. package/types/panel/author.d.ts +1 -1
  48. package/types/panel/authorcard.d.ts +41 -0
  49. package/types/panel/result.d.ts +9 -3
  50. package/types/pickrecord.d.ts +88 -0
  51. package/types/runfile.d.ts +7 -2
  52. package/types/runner.d.ts +16 -5
  53. package/types/send.d.ts +10 -2
  54. package/types/setup.d.ts +1 -56
  55. package/src/attemptdiff.js +0 -118
  56. package/types/attemptdiff.d.ts +0 -38
package/README.md CHANGED
@@ -33,7 +33,7 @@ general agent. Not a chat bot. A workflow that a person can read, approve, rerun
33
33
  A real past run: a job that reads a public flights page, lists 3 Madrid→Rome flights, asks a
34
34
  human to check them, then writes the result out. Shown across the panel's Job, Run, Ask, Audit and Result tabs.
35
35
 
36
- <img src="https://raw.githubusercontent.com/hamr0/fwdloop/main/docs/media/walkthrough.gif" alt="fwdloop panel walkthrough: Job, Run, Ask, Audit, Result" width="100%">
36
+ <img src="https://raw.githubusercontent.com/hamr0/fwdloop/main/docs/media/walkthrough.gif" alt="fwdloop panel walkthrough: Job, Run waiting at the Ask, Ask, passed Run, Audit, Result" width="100%">
37
37
 
38
38
  ## Where it comes from
39
39
 
package/bin/fwdloop CHANGED
@@ -52,6 +52,7 @@ import { panelMain } from '../src/panel/server.js';
52
52
  import { launcherMain } from '../src/launcher.js';
53
53
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
54
54
  import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
55
+ import { readRecordFile } from '../src/pickrecord.js';
55
56
  import { userInfo } from 'node:os';
56
57
  import { pageAddressesOf, pageAddressRefusal } from '../src/pagefetch.js';
57
58
  import { ticketListsOf, isTicketNumber, TICKET_NUMBER_WORDS } from '../src/ticket-shape.js';
@@ -338,7 +339,7 @@ async function cmdRun(rest) {
338
339
  const env = keyedEnv();
339
340
 
340
341
  const flowName = positionals[0];
341
- if (!flowName) fail('run: a flow name is required — fwdloop run <flow> --root <dir> --source <role>=<path> ...');
342
+ if (!flowName) fail('run: a flow name is required — fwdloop run <flow> [--root <dir>] --source <role>=<path> ...');
342
343
 
343
344
  const root = resolveRoot('run', values.root);
344
345
  const nameCheck = checkFlowName(flowName);
@@ -583,7 +584,7 @@ function cmdShow(rest) {
583
584
  allowPositionals: true,
584
585
  });
585
586
  const [askId] = positionals;
586
- if (!askId) fail('show: an askId is required — fwdloop show <askId> --root <dir>');
587
+ if (!askId) fail('show: an askId is required — fwdloop show <askId> [--root <dir>]');
587
588
 
588
589
  const root = resolveRoot('show', values.root);
589
590
  const runDir = findRunDirByAskId(root, askId);
@@ -670,7 +671,7 @@ async function cmdResume(rest) {
670
671
  });
671
672
  const env = keyedEnv();
672
673
  const runId = positionals[0];
673
- if (!runId) fail('resume: a runId is required — fwdloop resume <runId> --flow <name> --root <dir>');
674
+ if (!runId) fail('resume: a runId is required — fwdloop resume <runId> --flow <name> [--root <dir>]');
674
675
  if (!values.flow) fail('resume: --flow <name> is required');
675
676
 
676
677
  const root = resolveRoot('resume', values.root);
@@ -769,7 +770,7 @@ async function cmdContinue(rest) {
769
770
  });
770
771
  const env = keyedEnv();
771
772
  const runId = positionals[0];
772
- if (!runId) fail('continue: a runId is required — fwdloop continue <runId> --flow <name> --root <dir>');
773
+ if (!runId) fail('continue: a runId is required — fwdloop continue <runId> --flow <name> [--root <dir>]');
773
774
  if (!values.flow) fail('continue: --flow <name> is required');
774
775
 
775
776
  const root = resolveRoot('continue', values.root);
@@ -884,6 +885,10 @@ async function cmdDraft(rest) {
884
885
  'no-questions': { type: 'boolean' },
885
886
  // M10 piece 3: the rules the person left Not checked ("drop it"), as `<line>.<rule>` pairs, e.g. `1.2,3.1` (the panel passes this to the redraft after the answers)
886
887
  left: { type: 'string' },
888
+ // M10 am16: the checks the person picked and the answers that were not a pick, as JSON (the panel passes this to the redraft after the answers)
889
+ picks: { type: 'string' },
890
+ // M10 am17: the record file of the plan this draft follows (a Revise, or the redraft after the answers); its kept picks skip the suggestion and the asks
891
+ carry: { type: 'string' },
887
892
  // M4d amendment 6: the model that drafts (and then runs) the job - a line ticked in Settings > Providers; --provider only if two keys tick the same id.
888
893
  // --thinking is the Chat "Thinking on" tick (drafting only; off unless given).
889
894
  model: { type: 'string' }, provider: { type: 'string' }, thinking: { type: 'boolean' },
@@ -909,6 +914,21 @@ async function cmdDraft(rest) {
909
914
  leftRules.push({ line: Number(m[1]), rule: Number(m[2]) });
910
915
  }
911
916
 
917
+ /** @type {any[]|undefined} */
918
+ let checkPicks;
919
+ if (values.picks !== undefined) {
920
+ try { checkPicks = JSON.parse(values.picks); } catch { checkPicks = undefined; }
921
+ if (!Array.isArray(checkPicks) || checkPicks.some((x) => !x || !Number.isInteger(x.line) || !Number.isInteger(x.rule))) fail('draft: --picks takes a JSON list of {line, rule, check|null, added?, own?}');
922
+ }
923
+
924
+ /** @type {any[]|undefined} */
925
+ let carriedPicks;
926
+ if (values.carry !== undefined) {
927
+ const abs = resolve(values.carry);
928
+ const g = readFileInside(dirname(abs), basename(abs));
929
+ if (g.ok) carriedPicks = readRecordFile(abs) ?? undefined; // a missing or unreadable record is no record: every guardrail is asked, as before
930
+ }
931
+
912
932
  let injected = {};
913
933
  if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_DRAFT_PROVIDER) {
914
934
  const mod = await import(pathToFileURL(resolve(process.env.FWDLOOP_TEST_DRAFT_PROVIDER)).href);
@@ -967,6 +987,8 @@ async function cmdDraft(rest) {
967
987
  name: values.name,
968
988
  noQuestions: values['no-questions'] === true,
969
989
  ...(leftRules.length ? { leftRules } : {}),
990
+ ...(checkPicks === undefined ? {} : { checkPicks }),
991
+ ...(carriedPicks === undefined ? {} : { carriedPicks }),
970
992
  draftThinking: values.thinking === true ? 'on' : 'off',
971
993
  flowType,
972
994
  ...(values.mcp ? { mcpServer: values.mcp } : {}),
@@ -1024,7 +1046,7 @@ async function cmdSign(rest) {
1024
1046
  });
1025
1047
  if (!result.ok) fail(`sign refused — ${result.reds.join('; ')}`);
1026
1048
  if (result.runId) {
1027
- process.stdout.write(`signed: ${result.runDir} as ${result.runId} of ${values['run-of']} (by ${result.signature.signedBy})\nrun it: fwdloop run ${values['run-of']} --root <dir> --run-id ${result.runId} --source <role>=<path> ...\n`);
1049
+ process.stdout.write(`signed: ${result.runDir} as ${result.runId} of ${values['run-of']} (by ${result.signature.signedBy})\nrun it: fwdloop run ${values['run-of']} [--root <dir>] --run-id ${result.runId} --source <role>=<path> ...\n`);
1028
1050
  return;
1029
1051
  }
1030
1052
  process.stdout.write(`signed: ${result.flowDir} (by ${result.signature.signedBy})\n`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.28.0",
3
+ "version": "0.29.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",
@@ -49,9 +49,9 @@
49
49
  "NOTICE"
50
50
  ],
51
51
  "dependencies": {
52
- "bare-agent": "^0.57.0",
52
+ "bare-agent": "^0.59.0",
53
53
  "barebrowse": "^0.26.0",
54
- "bareguard": "^0.26.0",
54
+ "bareguard": "^0.31.0",
55
55
  "litectx": "^0.32.0"
56
56
  },
57
57
  "devDependencies": {
package/src/ask.js CHANGED
@@ -699,7 +699,7 @@ export function readAcceptedHashesByEmits(runDir) {
699
699
  /**
700
700
  * @param {string} runDir
701
701
  * @returns {{ archived: true, asks: Array<{ askId: string, question?: string, askedAt?: string, expiresAt?: string,
702
- * evidence: ReturnType<typeof readAskEvidence>,
702
+ * evidence: ReturnType<typeof readAskEvidence>, emits?: string,
703
703
  * answer: { status: string, reason?: string, answeredAt?: string, why?: string } }> } | { archived: false, why: string }}
704
704
  */
705
705
  export function listArchivedAsks(runDir) {
package/src/audit-fold.js CHANGED
@@ -51,6 +51,9 @@ export function humanWords(r) {
51
51
  return null;
52
52
  }
53
53
 
54
+ /** M14 am1 item 1: the words for the reason a rerun started with, shaped like the redo words above. @param {string} words */
55
+ export const rerunWords = (words) => `you said rerun: "${words}"`;
56
+
54
57
  /** The short answer for a card: `accepted`, `redo: "<text>"`, `cancelled`. @param {any} r */
55
58
  function answerShort(r) {
56
59
  const w = humanWords(r);
@@ -61,7 +64,7 @@ function answerShort(r) {
61
64
  * The fold of one step, or `null` for a step with nothing new to show (an old run, or a step that is neither a model step with records nor an ask).
62
65
  * @param {{rows:any[], tryMarks:string[], closeClass:string|null}} group `deriveAuditGroups`' group for the step
63
66
  * @param {ReturnType<typeof loadDiaries>} d
64
- * @param {{about?: string|null}} [info] `about`: the file an ask is about
67
+ * @param {{about?: string|null, rerun?: {words: string}|null}} [info] `about`: the file an ask is about; `rerun`: this run's reason for starting (run.json), given for its first step only
65
68
  */
66
69
  export function deriveFold(group, d, info = {}) {
67
70
  const step = group.rows[0]?.step ?? null;
@@ -116,6 +119,8 @@ export function deriveFold(group, d, info = {}) {
116
119
  n: r.attempt, mark: group.tryMarks[i] ?? '·', thinking: r.thinkingPhrase ?? null, gap: r.gap || null, answer: null, about: null, checks: rec?.checks ?? [], output: rec?.output ?? null,
117
120
  // M8 am7 item 4: the exact text this try was handed, from its own audit row (`hints` count + `hintsText`); null (no line) when nothing was handed
118
121
  hints: typeof r.hintsText === 'string' && r.hintsText !== '' && Number.isInteger(r.hints) ? { n: r.hints, text: r.hintsText } : null,
122
+ // M14 item 7: the exact memo text (what happened so far in this run) this try was handed, from its own audit row (`memoText`); null (no button) when none was
123
+ memo: typeof r.memoText === 'string' && r.memoText !== '' ? { text: r.memoText } : null,
119
124
  });
120
125
  });
121
126
  // rounds count on through all of a step's tries, so they order the calls and tool calls; a try's check row goes after the last round it saw
@@ -123,6 +128,9 @@ export function deriveFold(group, d, info = {}) {
123
128
  calls.forEach((c, i) => items.push({ k: c.round * 2, i, row: { round: c.round, try: c.try, action: 'model call', path: null, decision: callDecision(c), at: c.at } }));
124
129
  tools.forEach((t, i) => items.push({ k: t.round * 2 + 1, i: 1e6 + i, row: { round: t.round, try: t.try, action: `model · ${t.tool}`, path: t.path ?? null, decision: toolDecision(t), at: t.at } }));
125
130
  checkRows.forEach((c, i) => items.push({ k: (c.lastRound ?? 0) * 2 + 1.5, i: 2e6 + i, row: { round: null, try: c.try, action: 'check', path: c.output?.file ?? null, decision: checkDecision(c.checks), at: c.at } }));
131
+ // M14 am1 item 1 / item 11: a rerun's reason was handed to its first step (as its gap and in its memo) and is kept in the run's own run.json; it shows, in the shape of
132
+ // the redo words (`humanWords`), as the first row of that step's first try
133
+ if (info.rerun && tryRows.length > 0) items.push({ k: -1, i: -1, row: { round: null, try: tryRows[0].attempt, action: 'human', path: null, decision: rerunWords(info.rerun.words), at: null } });
126
134
  items.sort((a, b) => a.k - b.k || a.i - b.i);
127
135
  for (const it of items) rows.push(it.row);
128
136
  }
package/src/authoring.js CHANGED
@@ -23,6 +23,7 @@ import { draft } from './drafter.js';
23
23
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
24
24
  import { validateDeclaration, flowTypeOf } from './declaration.js';
25
25
  import { factRows } from './citedcheck.js';
26
+ import { plainWords } from './checkwords.js';
26
27
  import { sheetLineBlocks } from './sheetblock.js';
27
28
  import { loadCatalogue } from './catalogue.js';
28
29
  import { WIRED_VERBS } from './primitives.js';
@@ -38,6 +39,7 @@ import { hintsForRun, placeSpecOf } from './learnstore.js';
38
39
  import { redactSecrets } from './redact.js';
39
40
  import { sessionPriorSpend, writeDraftSpend } from './draftspend.js';
40
41
  import { writeSetup } from './setup.js';
42
+ import { RECORD_FILE } from './pickrecord.js';
41
43
  import { mcpPickHere } from './mcp-pick.js';
42
44
 
43
45
  export const SPEC_HASH_FILE = 'spec.hash';
@@ -88,7 +90,7 @@ export function specHash({
88
90
  * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
89
91
  * @param {string} planDir
90
92
  * A question the page look raised (M10 piece 3) also carries `source: 'look'`, `ask` ('reading' | 'cant-check'), `ruleNo`, `ruleText` and `proposal`; an answer file carries `at`.
91
- * @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null}[], open: {k:number, line:number, question:string, answer:null}[] }}
93
+ * @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null, check?:Record<string, any>, pairRule?:number}[], open: {k:number, line:number, question:string, answer:null}[] }}
92
94
  */
93
95
  export function readQuestions(planDir) {
94
96
  const none = { questions: [], open: [] };
@@ -113,7 +115,7 @@ export function readQuestions(planDir) {
113
115
  }
114
116
  return {
115
117
  k, line: q.line, question: String(q.question), answer, ...(at === undefined ? {} : { at }), ...(rule === undefined ? {} : { rule }),
116
- ...(q.source === 'look' ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: typeof q.proposal === 'string' ? q.proposal : null } : {}),
118
+ ...(q.source === 'look' ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: typeof q.proposal === 'string' ? q.proposal : null, ...(q.check && typeof q.check === 'object' ? { check: q.check } : {}), ...(Number.isInteger(q.pairRule) ? { pairRule: q.pairRule } : {}) } : {}),
117
119
  };
118
120
  });
119
121
  return { questions, open: /** @type {any} */ (questions.filter((q) => q.answer === null)) };
@@ -223,6 +225,8 @@ export function buildReadout({
223
225
  if (Array.isArray(st.close?.sheet)) for (const row of sheetBlocks.find((b) => b.line === st.fromLine)?.checked ?? []) out.push(` sheet check: ${row.text}`);
224
226
  // M10 am8 item 2: the column lock, signed with the readout (typed fields)
225
227
  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
+ // 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)}`);
226
230
  // M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
227
231
  const shape = st.close?.shape;
228
232
  if (Array.isArray(shape?.sections) && shape.sections.length > 0) {
@@ -294,7 +298,7 @@ export function draftKeyRefusal(slot, env) {
294
298
  * `onResult({ ok })` (M4d am32): called once, after the spend is booked and just before the result files are written (the CLI gives its monthly hold back there).
295
299
  */
296
300
  export async function draftToDir({
297
- proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, proseRead,
301
+ proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, checkPicks, carriedPicks, proseRead,
298
302
  flowType = /** @type {'plain'|'mcp'|'tickets'} */ ('plain'), mcpServer = /** @type {string|undefined} */ (undefined), mcpPick = /** @type {any} */ (undefined), mcpServers = /** @type {string[]|undefined} */ (undefined),
299
303
  }) {
300
304
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
@@ -371,8 +375,10 @@ export async function draftToDir({
371
375
  }
372
376
  // M13 piece 4 (R1): the job's MCP is every tool of that server's newest OK check, read here by code (the server is never started); never checked = a $0 refusal in the drafter's pre-flight
373
377
  const mcp = flowType === 'plain' ? null : (mcpPick ?? (typeof mcpServer === 'string' ? mcpPickHere(mcpServer) : { ok: false, say: 'pick an MCP for this flow type' }));
378
+ /** @type {{picks: object[], kept: object[]}|null} */
379
+ let pickRecord = null; // M10 am17: handed by draft() as it learns it; the last one handed is this draft's (written below, the one writer)
374
380
  const result = await draft({
375
- proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, learnHints, ...(leftRules === undefined ? {} : { leftRules }),
381
+ proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, learnHints, ...(leftRules === undefined ? {} : { leftRules }), ...(checkPicks === undefined ? {} : { checkPicks }), ...(carriedPicks === undefined ? {} : { carriedPicks }), onPickRecord: (r) => { pickRecord = r; },
376
382
  flowType, mcp, ...(mcpServers === undefined ? {} : { mcpServers }),
377
383
  });
378
384
  if (result.stop === 'pre-flight') {
@@ -404,6 +410,7 @@ export async function draftToDir({
404
410
  // Amendments 24/25: the questions and the drafter's own "not checked" reading are written BEFORE log.json/spec.hash (the panel reads those
405
411
  // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
406
412
  if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
413
+ if (pickRecord !== null) files[RECORD_FILE] = scrub(dj(pickRecord), secrets); // M10 am17: the picks carried to the next plan (this drafting folder only, never a run folder)
407
414
  files[NOT_CHECKED_FILE] = scrub(dj({ notChecked: result.notChecked ?? [] }), secrets);
408
415
  if (result.pageLooks || result.sheetLooks) files[PAGE_LOOK_FILE] = scrub(dj({ pages: result.pageLooks ?? [], ...(result.sheetLooks ? { sheets: result.sheetLooks } : {}), look: result.look ?? { facts: [], dropped: [] } }), secrets);
409
416
  files['log.json'] = scrub(dj({
package/src/checked.js CHANGED
@@ -12,6 +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
16
  import { sheetCheckRows } from './sheetchecks.js';
16
17
  import { sheetLineBlocks } from './sheetblock.js';
17
18
  import { splitReadNotes, signedFactNames } from './pagedropwords.js';
@@ -22,11 +23,11 @@ const list = (xs) => xs.join(', ');
22
23
  * One entry per step, in plan order: the plain sentences for what its typed close checks.
23
24
  * M10b piece 4: with `lines` (the signed job lines) a step that reads a sheet also carries `sheet`, its line's block (src/sheetblock.js `sheetLineBlocks`: guardrails,
24
25
  * Checked with `covers`, Not checked), and its sentences are only the lead sentence; the surfaces draw the block. Without `lines` the older one-row-per-check sentences.
25
- * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[], lines?: any[], csvRoles?: string[] }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
26
+ * @param {{ steps?: any[] }} declaration @param {{ hasAsk?: boolean, askLines?: number[], lines?: any[], csvRoles?: string[], keptChecks?: {line: number, check: any}[], keptWords?: string }} [opts] hasAsk = the job has a signed ask line (so "you check it at the ask" is true);
26
27
  * askLines = the job lines of the signed asks, which also lets a step after the LAST ask read "you check it after you accept" (am41 item 2, am42: the ONE place for these words)
27
28
  * @returns {{ step: number, line: number|null, goal: string, class: string, sentences: string[], sheet?: ReturnType<typeof sheetLineBlocks>[number] }[]}
28
29
  */
29
- export function checkedLines(declaration, { hasAsk = true, askLines, lines, csvRoles = [] } = {}) {
30
+ export function checkedLines(declaration, { hasAsk = true, askLines, lines, csvRoles = [], keptChecks = [], keptWords = '' } = {}) {
30
31
  const blocks = Array.isArray(lines) ? sheetLineBlocks({ declaration, lines, csvRoles }) : [];
31
32
  const steps = Array.isArray(declaration?.steps) ? declaration.steps : [];
32
33
  if (Array.isArray(askLines)) hasAsk = askLines.length > 0;
@@ -53,6 +54,8 @@ export function checkedLines(declaration, { hasAsk = true, askLines, lines, csvR
53
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.`);
54
55
  if (Number.isInteger(shape.linesPerInvoice)) out.push(`The output comes in blocks of ${shape.linesPerInvoice} lines.`);
55
56
  if (Array.isArray(shape.mustCarry) && shape.mustCarry.length > 0) out.push(`Every block carries: ${list(shape.mustCarry)}.`);
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})` : ''}`);
56
59
  } else {
57
60
  if (lastAsk !== -1 && i > lastAsk) out.push('No machine check of the content; you check it after you accept.');
58
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.');
@@ -0,0 +1,257 @@
1
+ // M10 amendment 16 (docs/wiki/the-module-ladder.md "M10 amendment 16"): shape guardrails are settled the way item 3-4 settle a source's words.
2
+ // One AI call suggests, per guardrail, ONE check from bareguard's own list (`rubricVocabulary`) or none; CODE keeps a suggestion only if its rule is on
3
+ // the list, every number is one the guardrail names and every word is a word of the guardrail; the person picks (src/drafter.js asks, src/panel/author.js
4
+ // takes the answer); the plan carries only the checks picked. The drafter writes no check of its own.
5
+ // The prompt, the per-rule answer form and the keep-or-drop are the ones F144c proved (docs/logs/FINDINGS.md F144c).
6
+ // Throws away: a suggestion's `id`, `field`, `strict`, `text` (code sets them, or they never decide); every guardrail that code scopes out; what the model says in words.
7
+ import { rubricVocabulary } from 'bareguard';
8
+ import { lineRules } from './pagebits.js';
9
+ import { isCellsPath } from './closers.js';
10
+ import { plainWords, OFFERED } from './checkwords.js';
11
+
12
+ export { plainWords, OFFERED };
13
+ import { guardrailWordNumbers, guardrailStandaloneNumbers, guardrailWordsPerSection, guardrailSectionCount } from './declaration.js';
14
+
15
+ /** the one tool the suggestion call is forced to use */
16
+ export const SUGGEST_TOOL = 'suggest_checks';
17
+ const VOCAB = /** @type {Record<string, {description: string, fields: Record<string, {type: string, required?: boolean}>}>} */ (rubricVocabulary.rules);
18
+ /** fields code sets, or that never decide: never offered, never kept */
19
+ const IGNORED = new Set(['id', 'field', 'text', 'strict']);
20
+ const NUM_FIELDS = ['value', 'size', 'wordsPerSection'];
21
+ const WORD_FIELDS = ['names', 'phrases'];
22
+
23
+ // ---- scope, decided by CODE before the call ------------------------------------------------------------------------------------------------
24
+ /** @param {any[]|undefined} sources the job's signed inputs @returns {boolean} a CSV file or a web page routes its guardrails to another signed part (M10 items 1-3, M12) */
25
+ export const hasRoutingInput = (sources) => (sources ?? []).some((s) => (s.kind === 'file' && isCellsPath(s.path)) || s.kind === 'page');
26
+ /**
27
+ * A guardrail goes to this call unless the job signs an input that routes its guardrails elsewhere AND the guardrail 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).
29
+ * @param {any[]|undefined} sources @param {string} g @returns {'in'|'out'}
30
+ */
31
+ export const codeScope = (sources, g) => (hasRoutingInput(sources) && guardrailWordNumbers(g).length === 0 ? 'out' : 'in');
32
+
33
+ /**
34
+ * Every guardrail rule on a step line (not a signed ask or send line) that this call settles, in line order. `rule` is the rule's number on its line (the one
35
+ * number `leftRules`, `ruleNo` and the answers use); a repeated text on a line is one rule here, asked once.
36
+ * @param {{n: number, guardrail?: string}[]} lines `parseSignedText`'s lines @param {{asks?: {line: number}[], sends?: {line: number}[], sources?: any[]}} arbiter
37
+ * @returns {{line: number, rule: number, text: string}[]}
38
+ */
39
+ export function scopedRules(lines, arbiter) {
40
+ const skip = new Set([...(arbiter?.asks ?? []), ...(arbiter?.sends ?? [])].map((x) => x.line));
41
+ /** @type {{line: number, rule: number, text: string}[]} */
42
+ const out = [];
43
+ for (const l of Array.isArray(lines) ? lines : []) {
44
+ if (skip.has(l.n)) continue;
45
+ const seen = new Set();
46
+ lineRules({ rule: l.guardrail }).forEach((text, i) => {
47
+ const key = text.trim().toLowerCase();
48
+ if (seen.has(key) || codeScope(arbiter?.sources, text) !== 'in') return;
49
+ seen.add(key);
50
+ out.push({ line: l.n, rule: i + 1, text });
51
+ });
52
+ }
53
+ return out;
54
+ }
55
+
56
+ // ---- code's keep-or-drop (am16 (2)) --------------------------------------------------------------------------------------------------------
57
+ const norm = (/** @type {unknown} */ t) => String(t).toLowerCase().replace(/\s+/g, ' ').trim();
58
+ const tokens = (/** @type {unknown} */ t) => new Set(norm(t).match(/[\p{L}\p{N}]+/gu) ?? []);
59
+
60
+ /**
61
+ * 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
62
+ * every word in it is a word of the guardrail. Anything else is dropped, with the reason. `none` is a drop with the reason `none`.
63
+ * @param {string} guardrail @param {any} sug the model's entry for this guardrail
64
+ * @returns {{kept: true, check: Record<string, any>}|{kept: false, why: string}}
65
+ */
66
+ export function keepOrDrop(guardrail, sug) {
67
+ if (sug == null || typeof sug !== 'object') return { kept: false, why: 'unreadable suggestion' };
68
+ const { rule } = sug;
69
+ if (rule === 'none' || rule === undefined || rule === null) return { kept: false, why: 'none' };
70
+ if (typeof rule !== 'string' || !Object.hasOwn(VOCAB, rule)) return { kept: false, why: `rule "${rule}" is not on bareguard's list` };
71
+ if (!OFFERED.includes(rule)) return { kept: false, why: `rule "${rule}" is on bareguard's list but is not offered here` };
72
+ const own = Object.keys(VOCAB[rule].fields).filter((k) => !IGNORED.has(k));
73
+ for (const k of own) if (VOCAB[rule].fields[k].required && sug[k] == null) return { kept: false, why: `${rule} needs ${k}` };
74
+ const allowed = new Set([...own, 'rule', 'line', 'guardrail']);
75
+ for (const k of Object.keys(sug)) if (sug[k] != null && !allowed.has(k)) return { kept: false, why: `${rule} does not take ${k}` };
76
+ /** @type {Record<string, any>} */
77
+ const check = { rule };
78
+ for (const k of own) {
79
+ const v = sug[k];
80
+ if (v == null) continue;
81
+ if (NUM_FIELDS.includes(k)) {
82
+ if (!Number.isInteger(v) || v < 1) return { kept: false, why: `${k} ${JSON.stringify(v)} is not a whole number >= 1` };
83
+ const named = rule === 'maxWords' || rule === 'minWords' ? guardrailWordNumbers(guardrail)
84
+ : k === 'wordsPerSection' ? [guardrailWordsPerSection(guardrail)].filter((x) => x !== null)
85
+ : guardrailStandaloneNumbers(guardrail);
86
+ if (!named.includes(v)) return { kept: false, why: `${k} ${v} is not a number the guardrail names (${named.join(', ') || 'it names none'})` };
87
+ check[k] = v;
88
+ } else if (WORD_FIELDS.includes(k)) {
89
+ 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` };
90
+ const gTok = tokens(guardrail);
91
+ const gNorm = norm(guardrail);
92
+ for (const s of v) {
93
+ if (!gNorm.includes(norm(s))) return { kept: false, why: `${k} "${s}" is not in the guardrail's words` };
94
+ for (const t of tokens(s)) if (!gTok.has(t)) return { kept: false, why: `${k} word "${t}" is not a word of the guardrail` };
95
+ }
96
+ check[k] = v;
97
+ }
98
+ }
99
+ if (rule === 'sections' || rule === 'sectionOrder' || rule === 'sectionWords') {
100
+ const want = guardrailSectionCount(guardrail);
101
+ if (want !== null && check.names.length !== want) return { kept: false, why: `the guardrail says ${want} sections; the check has ${check.names.length}` };
102
+ }
103
+ return { kept: true, check };
104
+ }
105
+
106
+ // ---- the call: prompt, answer form -------------------------------------------------------------------------------------------------------
107
+ const vocabBlock = OFFERED.map((r) => `- ${VOCAB[r].description}`).join('\n');
108
+ export const SUGGEST_SYSTEM = `You help a person turn the guardrails written under the lines of a job into mechanical checks.
109
+ 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.
110
+
111
+ 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".
112
+
113
+ Rules:
114
+ - 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.
115
+ - 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.
116
+ - Suggest \`sections\` or \`sectionWords\` only when the guardrail itself names the sections.
117
+ - A guardrail like 'all under N words' or 'under N words' is about the whole answer: use maxWords N.
118
+ - 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".
119
+ - Answer for every guardrail once, using the line number and the guardrail number shown.
120
+
121
+ Checks the checker can run (rule({ fields })):
122
+ ${vocabBlock}`;
123
+
124
+ /**
125
+ * 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.
126
+ * @param {{n: number, text: string}[]} lines @param {{line: number, rule: number, text: string}[]} scoped @returns {string}
127
+ */
128
+ export function suggestUserText(lines, scoped) {
129
+ const out = ['The job:'];
130
+ for (const l of lines) {
131
+ out.push(`${l.n}. ${l.text}`);
132
+ for (const s of scoped) if (s.line === l.n) out.push(` g${s.rule}: ${s.text}`);
133
+ }
134
+ return out.join('\n');
135
+ }
136
+
137
+ const JSON_TYPE = { integer: { type: 'integer', minimum: 1 }, 'string-list': { type: 'array', minItems: 1, items: { type: 'string' } } };
138
+ /** @param {string} rule @returns {object} one variant of the answer form: exactly that rule's own fields, nothing else */
139
+ function variant(rule) {
140
+ /** @type {Record<string, any>} */
141
+ 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 } };
142
+ const required = ['line', 'guardrail', 'rule'];
143
+ if (rule !== 'none') {
144
+ for (const [k, f] of Object.entries(VOCAB[rule].fields)) {
145
+ if (IGNORED.has(k)) continue;
146
+ properties[k] = /** @type {Record<string, any>} */ (JSON_TYPE)[f.type];
147
+ if (f.required) required.push(k);
148
+ }
149
+ }
150
+ return { type: 'object', properties, required, additionalProperties: false };
151
+ }
152
+ /** the forced tool's parameter schema: one `anyOf` variant per offered rule, plus `none` */
153
+ export const SUGGEST_SCHEMA = Object.freeze({
154
+ type: 'object',
155
+ properties: { checks: { type: 'array', description: 'One entry per guardrail.', items: { anyOf: [...OFFERED, 'none'].map(variant) } } },
156
+ required: ['checks'],
157
+ additionalProperties: false,
158
+ });
159
+
160
+ /**
161
+ * What the call's answer comes to, one row per scoped guardrail: the check kept (or null) and why it was dropped. A guardrail the answer never mentions is
162
+ * dropped as `no entry`; an entry for a guardrail that was not sent is ignored.
163
+ * @param {{line: number, rule: number, text: string}[]} scoped @param {any} args the tool call's arguments
164
+ * @returns {{line: number, rule: number, text: string, check: Record<string, any>|null, why: string|null}[]}
165
+ */
166
+ export function rowsFromAnswer(scoped, args) {
167
+ const entries = Array.isArray(args?.checks) ? args.checks : [];
168
+ return scoped.map((s) => {
169
+ const e = entries.find((/** @type {any} */ x) => x?.line === s.line && x?.guardrail === s.rule);
170
+ 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 };
172
+ });
173
+ }
174
+
175
+ // ---- the asks (words are item 4's) -----------------------------------------------------------------------------------------------------
176
+ /** the can't-check ask, as the signed words say it */
177
+ export const CANT_CHECK_WORDS = "I can't check this. Your own words, or Not checked?";
178
+ /** how every answer is told, once (am2 item 2's words) */
179
+ 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.`;
180
+
181
+ /**
182
+ * 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
183
+ * Not checked?` when nothing was kept. A proposal is not counted toward am1's cap; a can't-check ask is (am16 (5)).
184
+ * @param {ReturnType<typeof rowsFromAnswer>} rows
185
+ * @returns {{pairRule?: number, line: number, rule: number, source: 'look', ask: 'check'|'no-check', ruleText: string, question: string, reading?: string, check?: Record<string, any>, counted: boolean}[]}
186
+ */
187
+ export function checkAsks(rows) {
188
+ return rows.map((r) => {
189
+ const pair = typeof (/** @type {any} */ (r).pairRule) === 'number' ? { pairRule: /** @type {any} */ (r).pairRule } : {}; // M10 am21: the asked line is an edited added line
190
+ if (r.check === null) {
191
+ 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)}` };
192
+ }
193
+ const words = plainWords(/** @type {any} */ (r.check));
194
+ 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)}` };
195
+ });
196
+ }
197
+
198
+ // ---- the plan uses only the checks you picked (am16 (4)) -------------------------------------------------------------------------------------
199
+ /**
200
+ * @typedef {{line: number, rule: number, check: Record<string, any>|null, added?: string, own?: boolean}} Pick
201
+ * `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
202
+ */
203
+ /**
204
+ * Settle every scoped rule against the person's answers: a rule with a picked check is checked; the `~` line an agree wrote is covered by that pick; every other
205
+ * rule is Not checked, with the reason (`person-left` = they chose it, `own-words` = they gave their own words, `no-pick` = nothing was picked).
206
+ * @param {ReturnType<typeof scopedRules>} rules @param {Pick[]} picks @param {{line: number, rule: number}[]} left
207
+ * @returns {{checks: Map<number, Record<string, any>[]>, notes: {line: number, rule: number, text: string, reason: 'person-left'|'own-words'|'no-pick'}[]}}
208
+ */
209
+ export function settleRules(rules, picks, left) {
210
+ /** @type {Map<number, Record<string, any>[]>} */
211
+ const checks = new Map();
212
+ /** @type {{line: number, rule: number, text: string, reason: 'person-left'|'own-words'|'no-pick'}[]} */
213
+ const notes = [];
214
+ const sameText = (/** @type {string|undefined} */ a, /** @type {string} */ b) => typeof a === 'string' && norm(a) === norm(b);
215
+ for (const r of rules) {
216
+ const own = picks.find((p) => p.line === r.line && p.rule === r.rule);
217
+ if (own?.check) { checks.set(r.line, [...(checks.get(r.line) ?? []), own.check]); continue; }
218
+ if (picks.some((p) => p.check && p.line === r.line && sameText(p.added, r.text))) continue;
219
+ if (left.some((l) => l.line === r.line && l.rule === r.rule)) notes.push({ ...r, reason: 'person-left' });
220
+ else if (own?.own || picks.some((p) => !p.check && p.own && p.line === r.line && sameText(p.added, r.text))) notes.push({ ...r, reason: 'own-words' });
221
+ else notes.push({ ...r, reason: 'no-pick' });
222
+ }
223
+ return { checks, notes };
224
+ }
225
+
226
+ /**
227
+ * Overwrite the drafter's check on every step of a line this call settles (a green step, which another signed part settles, is left alone): a line with picked checks
228
+ * is softgreen and carries exactly those checks; a line with none is hitl. Whatever `close.shape` the drafter wrote is gone. Pure: returns a new declaration.
229
+ * @param {any} declaration @param {ReturnType<typeof scopedRules>} rules @param {ReturnType<typeof settleRules>} settled
230
+ * @param {(note: {line: number, reason: 'person-left'|'own-words'|'no-pick'}) => string} sentence the one table's words for a reason
231
+ */
232
+ export function applyPicks(declaration, rules, settled, sentence) {
233
+ if (!declaration || !Array.isArray(declaration.steps)) return declaration;
234
+ const lineSet = new Set(rules.map((r) => r.line));
235
+ const green = (/** @type {number} */ n) => declaration.steps.some((/** @type {any} */ st) => st?.fromLine === n && st?.close?.class === 'green');
236
+ const mine = (/** @type {number} */ n) => lineSet.has(n) && !green(n);
237
+ const steps = declaration.steps.map((/** @type {any} */ st) => {
238
+ if (!st || typeof st !== 'object' || !mine(st.fromLine)) return st;
239
+ const picked = settled.checks.get(st.fromLine) ?? [];
240
+ return { ...st, close: picked.length ? { class: 'softgreen', shape: { picked } } : { class: 'hitl' } };
241
+ });
242
+ const out = { ...declaration, steps };
243
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
244
+ if (isRec(declaration.guardrailClasses)) {
245
+ out.guardrailClasses = { ...declaration.guardrailClasses };
246
+ const un = isRec(declaration.unjudgeable) ? { ...declaration.unjudgeable } : {};
247
+ for (const n of lineSet) {
248
+ if (!mine(n) || !declaration.steps.some((/** @type {any} */ st) => st?.fromLine === n)) continue;
249
+ const has = (settled.checks.get(n) ?? []).length > 0;
250
+ out.guardrailClasses[String(n)] = has ? 'softgreen' : 'hitl';
251
+ if (has) delete un[String(n)];
252
+ else un[String(n)] = [...new Set(settled.notes.filter((x) => x.line === n).map(sentence))].join(' ') || 'No check was picked for it, so you judge it at the Ask.';
253
+ }
254
+ if (isRec(declaration.unjudgeable) || Object.keys(un).length) out.unjudgeable = un;
255
+ }
256
+ return out;
257
+ }
@@ -0,0 +1,24 @@
1
+ // M10 amendment 16: the ONE place a picked check is put in plain words (one fixed phrase per bareguard rule, written by code). The ask, the `~` line an agree writes,
2
+ // the plan card (src/checked.js), the softgreen close's check list (src/closers.js) and the Audit all read it; nothing else writes these words.
3
+ /** the rules of bareguard's list a person may pick here (text rules only: the ones a plain answer can be judged by) */
4
+ export const OFFERED = Object.freeze(['nonEmpty', 'maxWords', 'minWords', 'maxLines', 'listItems', 'sections', 'sectionOrder', 'sectionWords', 'mustCarry', 'blockLines']);
5
+ const listOf = (/** @type {string[]} */ xs) => xs.join(', ');
6
+ /**
7
+ * 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.
8
+ * @param {{rule: string, value?: number, size?: number, wordsPerSection?: number, names?: string[], phrases?: string[]}} c @returns {string}
9
+ */
10
+ export function plainWords(c) {
11
+ switch (c.rule) {
12
+ case 'nonEmpty': return 'the answer is not empty';
13
+ case 'maxWords': return `at most ${c.value} words`;
14
+ case 'minWords': return `at least ${c.value} words`;
15
+ case 'maxLines': return `at most ${c.value} lines`;
16
+ case 'listItems': return `exactly ${c.value} list items`;
17
+ case 'sections': return `sections named ${listOf(c.names ?? [])}`;
18
+ case 'sectionOrder': return `sections named ${listOf(c.names ?? [])}, in that order`;
19
+ case 'sectionWords': return `sections named ${listOf(c.names ?? [])}, each about ${c.wordsPerSection} words`;
20
+ case 'mustCarry': return `the answer carries ${listOf(c.phrases ?? [])}`;
21
+ case 'blockLines': return `blocks of ${c.size} lines, each carrying ${listOf(c.phrases ?? [])}`;
22
+ default: return `a ${c.rule} check`;
23
+ }
24
+ }
package/src/closers.js CHANGED
@@ -44,6 +44,7 @@
44
44
  // signed text).
45
45
 
46
46
  import { createRubric, checkStep } from 'bareguard';
47
+ import { plainWords } from './checkwords.js';
47
48
  import { checkCited } from './citedcheck.js';
48
49
  import { closeSheet } from './sheetrun.js';
49
50
 
@@ -105,6 +106,8 @@ export function softgreenSpec(shape) {
105
106
  if (shape.linesPerInvoice !== undefined || shape.mustCarry !== undefined) {
106
107
  checks.push({ id: 'lines', rule: 'blockLines', field: 'text', size: shape.linesPerInvoice, phrases: shape.mustCarry });
107
108
  }
109
+ // M10 am16: each check the person picked is one more bareguard rule on the answer's text, id `pick<k>`; code set it from the person's pick, the drafter never writes one
110
+ if (Array.isArray(shape.picked)) shape.picked.forEach((c, k) => checks.push({ id: `pick${k + 1}`, field: 'text', ...c }));
108
111
  return { schema: 1, goal: 'softgreen', checkpoints: { close: { gating: true, checks } } };
109
112
  }
110
113
 
@@ -123,7 +126,7 @@ const partAfter = (item) => item.slice(item.indexOf(':') + 1);
123
126
  * A gap it has no sentence for is still a red, worded generically, never dropped.
124
127
  *
125
128
  * @param {any[]} gaps
126
- * @param {{ linesPerInvoice?: number, mustCarry?: string[] }} shape
129
+ * @param {{ linesPerInvoice?: number, mustCarry?: string[], picked?: any[] }} shape
127
130
  * @returns {{ red: string, reds: string[] }}
128
131
  */
129
132
  export function renderSoftgreenGaps(gaps, shape) {
@@ -165,6 +168,9 @@ export function renderSoftgreenGaps(gaps, shape) {
165
168
  // bareguard lists (block, word) misses and bounds the list; the tail counts the missing words it left out (amendment 20)
166
169
  const moreWords = (g.itemsTotal ?? 0) - (g.items?.length ?? 0);
167
170
  if (moreWords > 0) reds.push(`${moreWords} more missing word(s)`);
171
+ } else if (/^pick\d+$/.test(String(g.id)) && shape.picked?.[Number(String(g.id).slice(4)) - 1]) {
172
+ // M10 am16: a check the person picked is told in the words it was picked in, with the count bareguard measured when it gives one
173
+ reds.push(`not met: ${plainWords(shape.picked[Number(String(g.id).slice(4)) - 1])}${typeof g.measured === 'number' ? ` (found ${g.measured})` : ''}`);
168
174
  } else {
169
175
  reds.push(`the ${g.check} check failed (${g.kind ?? 'no detail'})`);
170
176
  }
@@ -179,6 +185,7 @@ function softgreenCheckText(c) {
179
185
  if (c.id === 'words') return `at most ${c.value} words`;
180
186
  if (c.id === 'sections') return `the sections are there, in order: ${c.names.join(', ')}`;
181
187
  if (c.id === 'perSection') return `each section is about ${c.wordsPerSection} words`;
188
+ if (/^pick\d+$/.test(c.id)) return plainWords(/** @type {any} */ (c));
182
189
  return `${c.size ?? 'its'} lines per block, each carrying: ${(c.phrases ?? []).join(', ')}`;
183
190
  }
184
191