bareloop 0.54.1 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/bareloop.context.md +67 -6
  3. package/package.json +3 -3
  4. package/src/authorflow.js +217 -238
  5. package/src/authoring.js +22 -6
  6. package/src/authorjob.js +138 -30
  7. package/src/authorreadout.js +15 -4
  8. package/src/authorrun.js +13 -4
  9. package/src/authorscout.js +9 -6
  10. package/src/behaviour.js +14 -0
  11. package/src/blockasks.js +43 -0
  12. package/src/cardschedule.js +42 -0
  13. package/src/checkblock.js +772 -0
  14. package/src/checklist.js +128 -0
  15. package/src/checkpick.js +294 -0
  16. package/src/checksuggest.js +28 -0
  17. package/src/checkwords.js +27 -0
  18. package/src/cli.js +1 -1
  19. package/src/config.js +24 -1
  20. package/src/declaredclose.js +30 -1
  21. package/src/destpoint.js +151 -0
  22. package/src/draftspend.js +85 -0
  23. package/src/facts.js +8 -1
  24. package/src/factwords.js +14 -1
  25. package/src/fitcheck.js +5 -3
  26. package/src/job.js +81 -1
  27. package/src/jobblock.js +9 -0
  28. package/src/labelscan.js +11 -0
  29. package/src/launcher.js +3 -2
  30. package/src/mcpchecks.js +52 -0
  31. package/src/mcppick.js +36 -0
  32. package/src/mcpsources.js +77 -0
  33. package/src/mcpuse.js +97 -0
  34. package/src/natural.js +23 -0
  35. package/src/pagemap.js +20 -5
  36. package/src/panel/authorroutes.js +105 -18
  37. package/src/panel/authorsession.js +293 -44
  38. package/src/panel/index.html +873 -41
  39. package/src/panel/jobgrid.js +117 -0
  40. package/src/panel/jobplan.js +103 -35
  41. package/src/panel/scheduler.js +80 -13
  42. package/src/panel/schedules.js +189 -28
  43. package/src/panel/schedulestart.js +44 -13
  44. package/src/panel/server.js +471 -39
  45. package/src/panel/settingsroutes.js +133 -3
  46. package/src/panel/status.js +19 -1
  47. package/src/panel/tickets.js +44 -0
  48. package/src/pickrecord.js +163 -0
  49. package/src/placerule.js +355 -0
  50. package/src/plan.js +31 -2
  51. package/src/planrun.js +71 -15
  52. package/src/prcheckout.js +259 -0
  53. package/src/promptregisters.js +11 -0
  54. package/src/questionbox.js +112 -0
  55. package/src/readshim.js +3 -2
  56. package/src/revises.js +56 -0
  57. package/src/rowedit.js +115 -0
  58. package/src/rubricstep.js +265 -132
  59. package/src/run.js +19 -2
  60. package/src/runexport.js +2 -0
  61. package/src/runlist.js +3 -2
  62. package/src/schedulewords.js +46 -4
  63. package/src/source.js +81 -7
  64. package/src/stepmcp.js +86 -0
  65. package/src/ticket.js +113 -0
  66. package/src/ticketfilter.js +76 -0
  67. package/src/ticketlabels.js +79 -0
  68. package/src/ticketmcp.js +111 -0
  69. package/src/ticketnext.js +35 -0
  70. package/src/ticketrepo.js +98 -0
  71. package/src/ticketschedule.js +32 -0
  72. package/src/ticketshape.js +45 -0
  73. package/src/tools.js +9 -0
  74. package/src/trigger.js +14 -2
  75. package/src/triggerclock.js +7 -3
  76. package/src/triggerfiles.js +19 -11
  77. package/src/triggertickets.js +244 -0
  78. package/src/userrun.js +191 -10
  79. package/src/validate.js +3 -1
  80. package/src/worktree.js +43 -1
  81. package/types/authorflow.d.ts +86 -93
  82. package/types/authorjob.d.ts +35 -4
  83. package/types/authorreadout.d.ts +4 -3
  84. package/types/authorscout.d.ts +4 -2
  85. package/types/behaviour.d.ts +12 -0
  86. package/types/blockasks.d.ts +37 -0
  87. package/types/cardschedule.d.ts +24 -0
  88. package/types/checkblock.d.ts +361 -0
  89. package/types/checklist.d.ts +134 -0
  90. package/types/checkpick.d.ts +160 -0
  91. package/types/checksuggest.d.ts +30 -0
  92. package/types/checkwords.d.ts +14 -0
  93. package/types/config.d.ts +7 -0
  94. package/types/declaredclose.d.ts +4 -0
  95. package/types/destpoint.d.ts +89 -0
  96. package/types/draftspend.d.ts +37 -0
  97. package/types/factwords.d.ts +7 -0
  98. package/types/fitcheck.d.ts +7 -1
  99. package/types/job.d.ts +13 -0
  100. package/types/jobblock.d.ts +9 -0
  101. package/types/labelscan.d.ts +7 -0
  102. package/types/launcher.d.ts +2 -2
  103. package/types/mcpchecks.d.ts +8 -0
  104. package/types/mcppick.d.ts +33 -0
  105. package/types/mcpsources.d.ts +51 -0
  106. package/types/mcpuse.d.ts +15 -0
  107. package/types/natural.d.ts +2 -0
  108. package/types/pagemap.d.ts +6 -1
  109. package/types/panel/authorroutes.d.ts +11 -2
  110. package/types/panel/authorsession.d.ts +69 -3
  111. package/types/panel/jobgrid.d.ts +405 -0
  112. package/types/panel/jobplan.d.ts +55 -11
  113. package/types/panel/scheduler.d.ts +7 -2
  114. package/types/panel/schedules.d.ts +124 -4
  115. package/types/panel/schedulestart.d.ts +21 -3
  116. package/types/panel/server.d.ts +432 -10
  117. package/types/panel/settingsroutes.d.ts +4 -2
  118. package/types/panel/status.d.ts +16 -2
  119. package/types/panel/tickets.d.ts +61 -0
  120. package/types/pickrecord.d.ts +100 -0
  121. package/types/placerule.d.ts +194 -0
  122. package/types/plan.d.ts +1 -0
  123. package/types/prcheckout.d.ts +151 -0
  124. package/types/questionbox.d.ts +87 -0
  125. package/types/readshim.d.ts +4 -3
  126. package/types/revises.d.ts +23 -0
  127. package/types/rowedit.d.ts +32 -0
  128. package/types/rubricstep.d.ts +100 -48
  129. package/types/run.d.ts +27 -1
  130. package/types/runlist.d.ts +6 -3
  131. package/types/schedulewords.d.ts +29 -2
  132. package/types/source.d.ts +40 -4
  133. package/types/stepmcp.d.ts +40 -0
  134. package/types/ticket.d.ts +114 -0
  135. package/types/ticketfilter.d.ts +34 -0
  136. package/types/ticketlabels.d.ts +44 -0
  137. package/types/ticketmcp.d.ts +84 -0
  138. package/types/ticketnext.d.ts +33 -0
  139. package/types/ticketrepo.d.ts +118 -0
  140. package/types/ticketschedule.d.ts +21 -0
  141. package/types/ticketshape.d.ts +37 -0
  142. package/types/tools.d.ts +1 -0
  143. package/types/trigger.d.ts +9 -1
  144. package/types/triggerclock.d.ts +6 -2
  145. package/types/triggerfiles.d.ts +13 -5
  146. package/types/triggertickets.d.ts +110 -0
  147. package/types/userrun.d.ts +50 -0
  148. package/types/validate.d.ts +1 -0
  149. package/types/worktree.d.ts +19 -0
package/src/authoring.js CHANGED
@@ -353,21 +353,20 @@ export const KIND_CATALOGUE = Object.freeze({
353
353
  optional: Object.freeze([]),
354
354
  pathParams: Object.freeze([]),
355
355
  shape: 'step: integer (the job line number), parts: [{text: string, class: "countable" | "fact" | "judged" | "guard" | "none", '
356
- + 'check?: "maxWords" | "minWords" | "maxLines" | "sections" | "sectionWords" | "cited" | "minClaims" | "maxClaims", value?: integer, names?: string[], '
357
- + 'wordsPerSection?: integer, source?: string (an input label), domains?: string[], covers?: integer[], rules?: integer[], '
356
+ + 'check?: "cited" | "minClaims" | "maxClaims", value?: integer, '
357
+ + 'source?: string (an input label), domains?: string[], rules?: integer[], '
358
358
  + 'fact parts: facts?: [{name, shape: "money"|"number"|"date"|"time"|"phrase"|"text", unit?|currency? (each one value or a list; money names at least one), phrase?, anchor?, until?, '
359
359
  + 'rule?: {op, value | lo+hi}, aiProposal?: boolean}], count?: {min?, max?}}]',
360
360
  asserts: 'the file output/<step>.json under output/steps/ exists, is a JSON object, and its "text" is present and within the '
361
361
  + 'limits the person asked for. Write ONE rubric-step stage per numbered job line (step = that line number, fromLine = [that line]). '
362
362
  + 'In "parts" list each constraint the person put on that line, in their own words, and SORT it: "countable" when a machine can '
363
- + 'count it (check maxWords/minWords/maxLines with value; sections with names; sectionWords with names and wordsPerSection) or '
363
+ + 'quote it (word, section, line, list-item and phrase counts are never yours: code adds the ones the person picked) or '
364
364
  + 'when claims must be backed by a quote from a named input (check cited, source = the input label), or when a number of '
365
365
  + 'quoted claims is asked for (minClaims / maxClaims with value and source: it counts the claims listed under that input); '
366
366
  + 'a line that FINDS, LISTS or LOOKS UP something gets ONE part of class "fact" instead (source = the input label, '
367
367
  + 'facts = the required facts, count = how many results): its step file holds only filled facts and no free text, so '
368
368
  + 'give such a line no word, section or claim-count parts; list in "rules" the number of every ~ rule a part carries out; '
369
- + 'on every countable part that carries out a CONFIRMED check, list that check\'s number in covers (a confirmed check no part '
370
- + 'covers is moved to Not checked before signing); "judged" when only reading '
369
+ + '"judged" when only reading '
371
370
  + 'it could decide; "guard" for a rule about web sources (domains); "none" when you cannot sort it. Never turn a part you cannot '
372
371
  + 'count or quote into a countable one by guessing a number.',
373
372
  }),
@@ -1526,7 +1525,9 @@ export function validateDeclaration(declaration, opts = {}) {
1526
1525
  if (haveGuards) checkGuards({ declaration, guards: /** @type {any[]} */ (guards), red });
1527
1526
  checkJobLines({ declaration, stages, jobLines, guards: haveGuards ? /** @type {any[]} */ (guards) : [], red });
1528
1527
  // PART 1a (R11): the sorting rules for the rubric-step stages — plain-words reds, judged and web parts refused in this build
1529
- checkRubricParts(stages, { inputLabels, red });
1528
+ // keep-both: the record of the person's picks (code writes it, the signed spec carries it) is what lets a countable part sit beside a fact
1529
+ checkPickRecord(declaration.picks, red);
1530
+ checkRubricParts(stages, { inputLabels, red, picks: Array.isArray(declaration.picks) ? declaration.picks : null });
1530
1531
  // PART 1b (RF16, RF17): every ~ rule is a check or Not checked; the AI's own numbers are marked and a time range is a range
1531
1532
  checkRubricRules(stages, { jobLines, refused: declaration.refused, red });
1532
1533
 
@@ -1534,6 +1535,21 @@ export function validateDeclaration(declaration, opts = {}) {
1534
1535
  return { ok, reds, declaration: ok ? normalizeDeclaration(declaration) : null, grounded: haveListing, scoped, ceiling };
1535
1536
  }
1536
1537
 
1538
+ /**
1539
+ * keep-both: the SHAPE of the record of the person's picks, `picks: [{line, part}]` (code writes it from the settled picks, `applyPicks`; the signed close carries it;
1540
+ * `checkRubricParts` reads it). A bad entry is a plain red, never a crash.
1541
+ * @param {unknown} picks @param {(c: string, p: string, d: string, e?: object) => void} red
1542
+ */
1543
+ function checkPickRecord(picks, red) {
1544
+ if (picks === undefined) return;
1545
+ if (!Array.isArray(picks)) { red('invalid-value', 'picks', 'an array of {line, part} - the person\'s picked checks, written by code'); return; }
1546
+ picks.forEach((/** @type {any} */ e, /** @type {number} */ j) => {
1547
+ if (!isObj(e) || !Number.isInteger(e.line) || !isObj(e.part) || e.part.class !== 'countable') {
1548
+ red('invalid-value', `picks[${j}]`, '{line, part}: a job line number and the picked countable part');
1549
+ }
1550
+ });
1551
+ }
1552
+
1537
1553
  /**
1538
1554
  * P7 rules 1-3 of the job block, at $0, in the gate that can still revise: every `fromLine` is a non-empty, duplicate-free array of real job line numbers (one check may serve several lines);
1539
1555
  * every numbered job line has at least one stage OR a refusal reason in `refused` (a note in `notes` does NOT cover a
package/src/authorjob.js CHANGED
@@ -100,7 +100,7 @@
100
100
 
101
101
  import { jobSpecHash, validateJob } from './job.js';
102
102
  import { seedAtHead, seedListing, seedRead as runSeedRead, makeSeedTrees, judgedStages, closeJudges } from './kinds.js';
103
- import { inputLabelsOf, readFrozenInputs, lineRules } from './rubricstep.js';
103
+ import { inputLabelsOf, readFrozenInputs, lineRules, cardOfClose } from './rubricstep.js';
104
104
  import { proverOf } from './factwords.js';
105
105
  // SOFTGREEN modules 4 and 5 — the compile the interview's Q6/Q7 answers land in,
106
106
  // and the gate that decides whether the ruler they describe is a ruler.
@@ -113,13 +113,19 @@ import {
113
113
  } from './authoring.js';
114
114
  import {
115
115
  QUESTION_SETS, questionsFor, requiredAnswersFor, authorClose, makeCostBook,
116
- runConfirmTurn, LANGUAGE_PICK_FIELD, normalizeQuestions, MAX_QUESTIONS,
116
+ runConfirmTurn, LANGUAGE_PICK_FIELD, MAX_QUESTIONS,
117
117
  } from './authorflow.js';
118
118
  import { thinkingCallOptions, assertThinkingMode } from './thinking.js';
119
119
  import { runFitCheck, fitQuestionText, notFoundList, isGoOn } from './fitcheck.js';
120
120
  import { pageContentChars } from './pagefetch.js';
121
121
  import { runAuthorScout, buildSeedListing, SCOUT_ATTEMPTS } from './authorscout.js';
122
- import { runPageMap, askableFromLook, tooManyAsksText } from './pagemap.js';
122
+ import { runPageMap, tooManyAsksText } from './pagemap.js';
123
+ import { CheckBlock } from './checkblock.js';
124
+ import { questionsOfBlock, applyChoices } from './blockasks.js';
125
+ import { scopedRules, codeScope, plainWords } from './checkpick.js';
126
+ import { matchRecord, entriesFromAnswers, KEPT_WORDS } from './pickrecord.js';
127
+ import { runCheckSuggest } from './checksuggest.js';
128
+ import { runLedgerSuggest, ledgerRecord } from './checklist.js';
123
129
  import {
124
130
  DECLARED_GAP_PREFIX, DECLARED_GENRES, guardNames, isDeclaredClose, validateCloseDecl,
125
131
  } from './declaredclose.js';
@@ -435,13 +441,14 @@ function composerRefusal(reds) {
435
441
  * authorFn?: Function, authorOpts?: object, writeScope?: string[]|null,
436
442
  * signerFix?: Function|any, proposeFn?: Function, compileOpts?: object,
437
443
  * ask?: ((step: {kind: string, [k: string]: any}) => Promise<string|null>)|null,
438
- * answerQuestions?: ((o: {questions: {line: number, question: string, rule?: number, source?: string, ask?: string, reading?: string}[], dropped: {reason: string, raw: any}[], confirmed: any}) =>
439
- * Promise<{jobLines: {n: number, text: string, rule?: string}[], answers: Record<string|number, any>, left?: {line: number, rule: number}[]}|null>)|null,
444
+ * answerQuestions?: ((o: {questions: {line: number, question: string, rule?: number, source?: string, ask?: string, reading?: string, key?: string}[], dropped: {reason: string, raw: any}[], confirmed: any}) =>
445
+ * Promise<{jobLines: {n: number, text: string, rule?: string}[], answers: Record<string|number, any>, left?: {line: number, rule: number}[], picks?: any[], choices?: {key: string, choice: string, text?: string}[]}|null>)|null,
446
+ * pickGenerate?: Function|null, ledgerGenerate?: Function|null, editGenerate?: Function|null, carriedPicks?: any[]|null, carriedChoices?: any[]|null, onChoices?: (rec: any[]) => void, onPicks?: (o: {entries: any[], kept: {line: number, rule: number, entry: any}[]}) => void,
440
447
  * confirmGenerate?: Function|null, isRepo?: boolean,
441
448
  * langResult?: {kind: string, candidates?: string[], [k: string]: any}|null}} o
442
449
  * @returns {Promise<{ok: boolean, refusal: Refusal|null, verdictType: string|null,
443
450
  * closeDecl: any, seedRef: string|null, authoring: any, judged: any, reds: Red[],
444
- * stop: string|null, cost: any, interview: any, confirmed: any}>}
451
+ * stop: string|null, cost: any, interview: any, confirmed: any, picked?: {line: number, text: string}[], hasBuiltCheck?: boolean, notBuilt?: {line: number, text: string}[]}>}
445
452
  */
446
453
  export async function authorCloseForJob({
447
454
  answers, repoPath = null, lang, verdictType = null, questions = null,
@@ -479,6 +486,18 @@ export async function authorCloseForJob({
479
486
  // `fitFn` null is an explicit "no check" (a test seam). With no `fitAsk` (the CLI door) it never runs.
480
487
  fitFn = runFitCheck, fitAsk = null, onFit = () => {},
481
488
  authorFn = authorClose, authorOpts = {},
489
+ // R10 (fwd am16): the model boundary of the check-suggestion call (a `makeLoopGenerate` bound to SUGGEST_SYSTEM). ABSENT = no pick path: nothing is suggested or asked and the
490
+ // drafted declaration is validated as it always was (a test seam, like `lookFn: null`).
491
+ pickGenerate = null,
492
+ // the model boundary of the list call (a `makeLoopGenerate` bound to LEDGER_SYSTEM), rubric jobs only. ABSENT = the list is built from the look and the defaults with no suggestion call
493
+ // (a test seam, like `pickGenerate`); the CLI and the panel always bring it.
494
+ ledgerGenerate = null,
495
+ // the row-edit turn's own model boundary (src/rowedit.js ROW_EDIT_SYSTEM); a test that replaces `generate` need not bring one
496
+ editGenerate = null,
497
+ // R10 (fwd am17/am18): the picks record of the draft this one follows (`readRecordFile`), and the seam that receives this draft's record + the picks it kept. ABSENT = every rule is asked.
498
+ carriedPicks = null, onPicks = () => {},
499
+ // hamr 2026-11-13 (N-2): the Drop/Add choices of the draft this one follows (the picks record file's `rowChoices`); a Revise keeps them, code still judges every one
500
+ carriedChoices = null, onChoices = () => {},
482
501
  // SOFTGREEN modules 4+5. `signerFix` is the D5 seam: a function (or a value)
483
502
  // carrying the SIGNER's corrected artifacts back. Absent means the proposal is
484
503
  // signed as proposed, and `signJudgedArtifacts` records which of the two
@@ -604,6 +623,8 @@ export async function authorCloseForJob({
604
623
  // arrived at by accident.
605
624
  /** @type {any} */
606
625
  let survey = scout;
626
+ /** the frozen input texts the list's word proof reads (a rubric job with a look) @type {Record<string, string>|null} */
627
+ let ledgerTexts = null;
607
628
  // PART 1a: a rubric job on local files has no repository to survey. PART 1c: its survey is the LOOK - a read-only, bounded, paid
608
629
  // look at the person's frozen input text that reports which facts can be checked and with which label (picked from a code-made
609
630
  // list). Without a look (`lookFn` null, or no model boundary) the survey is just the numbered inputs, known to code at $0.
@@ -611,6 +632,7 @@ export async function authorCloseForJob({
611
632
  const inputList = (Array.isArray(inputs) ? inputs : []).map((i) => ({ n: i.n, label: i.label }));
612
633
  const frozen = lookFn && provider && Array.isArray(jobLines) && jobLines.length > 0 && inputList.length > 0
613
634
  ? await readFrozenInputs(workdir, inputList.map((i) => i.label)) : null;
635
+ if (frozen !== null && frozen.ok) ledgerTexts = frozen.texts;
614
636
  if (frozen !== null && !frozen.ok) {
615
637
  survey = { state: 'ABSENT', reason: `the look at your input could not start: ${frozen.why}`, cause: 'call-failed', budgetStop: null, calls: [], raws: [], facts: null };
616
638
  } else if (frozen !== null && lookFn && !Object.values(frozen.texts).some((t) => pageContentChars(t) > 0)) {
@@ -630,7 +652,8 @@ export async function authorCloseForJob({
630
652
  onPhase('fit-check-done', { state: fit.state });
631
653
  onFit({ state: fit.state, asks: fit.asks, notFound: fit.notFound });
632
654
  if (fit.state === 'ask') {
633
- const answer = await fitAsk(fitQuestionText({ found: fit.asks.filter((/** @type {any} */ a) => !a.ignored && a.found).length, total: fit.asks.filter((/** @type {any} */ a) => !a.ignored).length, notFound: fit.notFound }));
655
+ const foundAsks = fit.asks.filter((/** @type {any} */ a) => !a.ignored && a.found).map((/** @type {any} */ a) => ({ line: a.line, ask: a.ask }));
656
+ const answer = await fitAsk(fitQuestionText({ found: foundAsks.length, foundAsks, total: fit.asks.filter((/** @type {any} */ a) => !a.ignored).length, notFound: fit.notFound }));
634
657
  if (answer === null) return { ...base, interview, verdictType: picked, seedRef: seed, reds: [], stop: 'confirm-abandoned', cost: null };
635
658
  if (!isGoOn(answer)) {
636
659
  return { ...base, interview, verdictType: picked, seedRef: seed, reds: [{ code: 'fit-stopped', path: 'jobLines', detail: notFoundList(fit.notFound) }], stop: 'fit-stopped', cost: null };
@@ -669,32 +692,92 @@ export async function authorCloseForJob({
669
692
  onPhase('scout-done', { state: survey?.state ?? null, facts: Object.keys(survey?.facts ?? {}).length });
670
693
  }
671
694
 
672
- // PRD v1.106 Part 5 Q3 (T2) + v1.107 Part 5b: CODE forces the early asks, from the look's own result, before any plan or draft is paid for
673
- // (src/pagemap.js `askableFromLook`; the model never decides whether to ask). Two kinds: a READING the code made of a `~` rule whose limit the
674
- // person did not write (agree / type their own), and a rule the page cannot check (drop it / type how). More than MAX_QUESTIONS asks is a job to
675
- // rewrite, not a questionnaire: nothing is asked, nothing more is spent, and the stop lists every ask with its reading. The question gate is the
676
- // existing one (`answerQuestions`: answer required, no skip, the answer becomes a `~` rule on its line; `normalizeQuestions` keeps at most
677
- // MAX_QUESTIONS). The answer "drop it" adds no rule: the rule is put on the look's own dropped list, so it reads Not checked on the
678
- // confirm card, in the signed plan and in the drafter's block, and can never be written back as a check.
679
- if (answerQuestions && lang === RUBRIC_LANG && survey?.state === 'PRESENT' && survey.facts?.look && typeof survey.facts.look === 'object' && Array.isArray(jobLines)) {
680
- const candidates = askableFromLook(survey.facts.look, jobLines);
681
- if (candidates.length > MAX_QUESTIONS) {
682
- return { ...base, interview, verdictType: picked, seedRef: seed, reds: [{ code: 'look-asks-too-many', path: 'jobLines', detail: tooManyAsksText(candidates) }], stop: 'look-asks-too-many', cost: null };
695
+ // THE CHECK BLOCK of a rubric job (src/checkblock.js; hamr 2026-11-12: "one flow one place ai suggestes ! code adds $ and code decides what worked/doable"). It is made once here, after the look:
696
+ // the person's `~` rules and `$` defaults, then the look's facts (a fact tied to a `~` rule is a link on that row), then the last draft's picks Revise keeps (am17/am18/am21). The AI's two
697
+ // helpers (the pick call for count rules, the call for extra `!` checks) send ROW EDITS through the SAME door as the drafter's reply (`applyDelta`). Code then asks (cap 3) about what it
698
+ // cannot settle and applies the person's CHOICE (agree | drop | their own words) with `applyAnswer`. Every check comes from the rows; no other store holds one.
699
+ /** @type {import('./checkblock.js').CheckBlock|null} */
700
+ let block = null;
701
+ /** the picks the person made (kept and answered) this draft, as the picks record carries them */
702
+ /** @type {{kept: any[]}|null} */
703
+ let carried = null;
704
+ if (lang === RUBRIC_LANG && survey?.state === 'PRESENT' && Array.isArray(jobLines) && ledgerTexts) {
705
+ const look = survey.facts?.look && typeof survey.facts.look === 'object' ? survey.facts.look : null;
706
+ block = new CheckBlock({ texts: ledgerTexts, labels: (Array.isArray(inputs) ? inputs : []).map((i) => i.label), asks: Boolean(answerQuestions), split: true, countScope: (t) => Boolean(pickGenerate) && codeScope(inputs, t) === 'in' });
707
+ block.fromJob(jobLines);
708
+ block.addLook(Array.isArray(look?.facts) ? look.facts : [], Array.isArray(look?.dropped) ? look.dropped : []);
709
+ /** the rules a count pick settles, as the record knows them (a scoped rule is a counting `~` rule code scopes in) */
710
+ const scoped = answerQuestions ? scopedRules(jobLines, { inputs, look }) : [];
711
+ const matched = matchRecord(Array.isArray(carriedPicks) ? carriedPicks : [], jobLines, scoped);
712
+ carried = { kept: matched.kept };
713
+ block.carry({ picks: matched.picks, left: matched.left }, matched.askRules);
714
+ // a rule the record folded into another ask (a broken pair's partner) is neither asked nor given the old check: Not checked, in the pick path's own words
715
+ for (const r of scoped) {
716
+ const row = block.ruleRows(r.line).find((x) => x.rule === r.rule);
717
+ if (row && !matched.askRules.some((a) => a.line === r.line && a.rule === r.rule) && !row.pick && !row.cantAsked && !row.left && !row.parent) row.folded = true;
683
718
  }
684
- const kept = normalizeQuestions(candidates, [...new Set(candidates.map((q) => q.line))]);
685
- if (kept.kept.length > 0) {
686
- onPhase('look-ask', { questions: kept.kept.length });
687
- const updated = await answerQuestions({ questions: kept.kept, dropped: kept.dropped, confirmed: null });
688
- if (updated === null) return { ...base, interview, verdictType: picked, seedRef: seed, reds: [], stop: 'confirm-abandoned', cost: null };
689
- jobLines = updated.jobLines;
690
- interview.answers = updated.answers;
691
- for (const lf of Array.isArray(updated.left) ? updated.left : []) {
692
- const ruleText = lineRules(jobLines.find((l) => l.n === lf.line) ?? {})[lf.rule - 1];
693
- if (ruleText === undefined) continue;
694
- const look = survey.facts.look;
695
- look.dropped = [...(Array.isArray(look.dropped) ? look.dropped : []), { line: lf.line, rule: lf.rule, fact: ruleText, reason: 'person-left', source: 'person' }];
719
+ block.reconcile();
720
+ // the pick call: one suggestion per counting rule the record did not keep; each kept suggestion is a `pick` edit
721
+ if (answerQuestions && pickGenerate && matched.askRules.length > 0) {
722
+ onPhase('check-suggest', { rules: matched.askRules.length });
723
+ const sug = await runCheckSuggest({ jobLines, scoped: matched.askRules, generate: pickGenerate, ceilingUsd, onCall, priorCalls: survey?.calls ?? [], priorRaws: survey?.raws ?? [] });
724
+ survey.calls = [...(survey.calls ?? []), ...sug.calls];
725
+ survey.raws = [...(survey.raws ?? []), ...sug.raws];
726
+ block.applyDelta({ label: 'pre:check-suggest', pre: true, edits: sug.rows.filter((r) => r.check).map((r) => ({ op: 'pick', line: r.line, rules: [r.rule], check: r.check })) });
727
+ block.reconcile();
728
+ }
729
+ // the call for extra `!` checks (count, phrase): its proposals are edits like the drafter's own
730
+ if (ledgerGenerate) {
731
+ onPhase('ledger-suggest', {});
732
+ const lg = await runLedgerSuggest({ jobLines, texts: ledgerTexts, generate: ledgerGenerate, ceilingUsd, onCall, priorCalls: survey?.calls ?? [], priorRaws: survey?.raws ?? [] });
733
+ survey.calls = [...(survey.calls ?? []), ...lg.calls];
734
+ survey.raws = [...(survey.raws ?? []), ...lg.raws];
735
+ /** @type {any[]} */
736
+ const adds = [];
737
+ for (const e of lg.extra) {
738
+ const line = Number.isInteger(e?.line) ? e.line : 1;
739
+ if (e?.kind === 'count') adds.push({ op: 'add', kind: 'count', line, min: e.min, max: e.max });
740
+ else if (e?.kind === 'phrase' && typeof e.phrase === 'string') adds.push({ op: 'add', kind: 'phrase', line, name: e.phrase, words: [e.phrase], source: e.source });
696
741
  }
742
+ block.applyDelta({ label: 'pre:ledger-suggest', pre: true, edits: adds });
743
+ block.reconcile();
697
744
  }
745
+ // a Revise keeps the last draft's Drop/Add choices (the suggestions exist now); code still judges every one when the list is reconciled
746
+ if (Array.isArray(carriedChoices)) { block.carryChoices(carriedChoices); onChoices(block.choicesRecord()); }
747
+ block.reconcile();
748
+ onPhase('ledger-built', { rows: ledgerRecord(/** @type {any} */ (block.rows)) });
749
+ // the code-forced asks (PRD v1.106 Part 5 Q3 T2, v1.107 Part 5b, R10): a reading code proposes, a rule the page cannot check, a check proposed for a counting rule. More than
750
+ // MAX_QUESTIONS counted asks is a job to rewrite, not a questionnaire: nothing is asked and the stop lists every ask.
751
+ if (answerQuestions) {
752
+ /** what the person answered, across the rounds: the picks and the rules they left, for the record this draft hands on @type {{picks: any[], left: any[]}} */
753
+ const answered = { picks: [], left: [] };
754
+ for (let round = 0; round < 3 && block.open.length > 0; round += 1) {
755
+ const asks = questionsOfBlock(block, pickGenerate ? scoped : []);
756
+ const counted = asks.filter((a) => a.counted);
757
+ if (counted.length > MAX_QUESTIONS) {
758
+ return { ...base, interview, verdictType: picked, seedRef: seed, reds: [{ code: 'look-asks-too-many', path: 'jobLines', detail: tooManyAsksText(asks) }], stop: 'look-asks-too-many', cost: null };
759
+ }
760
+ // the asks go to the person whole (key, check, reading, counted, pairRule): normalizeQuestions keeps only a model's question fields and would drop the proposal an Agree button needs
761
+ const shown = asks.map((a) => ({ ...a, question: redactSecrets(a.question) }));
762
+ if (shown.length === 0) break;
763
+ onPhase(shown.every((a) => a.ask === 'check' || a.ask === 'no-check') ? 'check-ask' : 'look-ask', { questions: shown.length });
764
+ const updated = await answerQuestions({ questions: shown, dropped: [], confirmed: null });
765
+ if (updated === null) return { ...base, interview, verdictType: picked, seedRef: seed, reds: [], stop: 'confirm-abandoned', cost: null };
766
+ jobLines = updated.jobLines;
767
+ interview.answers = updated.answers;
768
+ answered.picks.push(...(Array.isArray(updated.picks) ? updated.picks : []));
769
+ answered.left.push(...(Array.isArray(updated.left) ? updated.left : []));
770
+ const refused = applyChoices(block, Array.isArray(updated.choices) ? updated.choices : []);
771
+ if (refused.length === 0) break;
772
+ }
773
+ // the record this draft hands on, written whether or not anything was asked (a draft that kept every pick still carries them forward): the picks it kept, as they were, and the picks just answered, keyed by words
774
+ if (scoped.length > 0) {
775
+ onPicks({
776
+ entries: [...carried.kept.map((k) => k.entry), ...entriesFromAnswers(jobLines, scoped, answered.picks, answered.left.filter((l) => scoped.some((r) => r.line === l.line && r.rule === l.rule)))],
777
+ kept: carried.kept.map((k) => ({ line: k.line, rule: k.rule, entry: k.entry })),
778
+ });
779
+ }
780
+ } else block.reconcile();
698
781
  }
699
782
 
700
783
  // ── THE CONFIRM TURN'S PAID HALF (PRD item 33 M3 piece 4) ──────────────────
@@ -739,7 +822,13 @@ export async function authorCloseForJob({
739
822
  const confirm = await runConfirmTurn({
740
823
  verdictType: picked, answers: interview.answers, questions: questions ?? questionsFor(picked),
741
824
  facts: survey.facts, listing: null, writeScope, isRepo, lang, worseThanBefore, inputs, jobLines,
825
+ ...(authorOpts?.ticket === true ? { ticket: true } : {}),
742
826
  generate: confirmGenerate, book: confirmBook, ask, onPhase,
827
+ // the rows the block has built, read by the signed card's own readers (cardOfClose): the confirm card draws them under their lines
828
+ ...(block ? (() => {
829
+ const cardOf = () => cardOfClose({ closeDecl: block.closeView(), jobLines, ledger: block.rows.map((r) => ({ key: r.key, words: r.kind === 'rule' ? [r.text ?? ''] : (r.words ?? []) })) });
830
+ return { card: cardOf(), cardOf, block };
831
+ })() : {}),
743
832
  });
744
833
  // DISTINCT from `runConfirmTurn`'s own per-round 'confirm-done' (fired once
745
834
  // per round when a plan arrives) — this is the WRAPPER's own line, once,
@@ -792,6 +881,7 @@ export async function authorCloseForJob({
792
881
  // PART 1c: a rubric job asks nothing piecemeal on a failed try - it stops, and the person reviews the whole job (the one early
793
882
  // ask is about a `~` rule the look could not find, above)
794
883
  ...(answerQuestions && lang !== RUBRIC_LANG ? { offerQuestions: true } : {}),
884
+ ...(block ? { block, editGenerate } : {}),
795
885
  ...authorOpts,
796
886
  });
797
887
  // P7 item 5: the drafter, on the last try after two failed ones, asked. The person answers (required, no skip); each
@@ -812,6 +902,7 @@ export async function authorCloseForJob({
812
902
  scout: survey, listing: seeds, generate, ceilingUsd, onPhase, onCall, writeScope,
813
903
  priorCalls: (authored.cost?.calls ?? []).slice(scoutCalls), priorRaws: (authored.raws ?? []).slice(scoutRaws),
814
904
  confirmed, jobLines, inputs,
905
+ ...(block ? { block, editGenerate } : {}),
815
906
  ...authorOpts,
816
907
  offerQuestions: false,
817
908
  });
@@ -867,6 +958,10 @@ export async function authorCloseForJob({
867
958
  ...(authored.declaration.refused?.length
868
959
  ? { refused: authored.declaration.refused.map((/** @type {any} */ r) => ({ line: r.line, ...(Number.isInteger(r.rule) ? { rule: r.rule } : {}), reason: redactSecrets(String(r.reason)) })) }
869
960
  : {}),
961
+ // keep-both: the person's picks, as code recorded them at the draft (the signed close reads this to tell a pick from a drafter-written count beside a fact)
962
+ ...(authored.declaration.picks?.length ? { picks: structuredClone(authored.declaration.picks) } : {}),
963
+ // the one check list's final rows (no words), signed with the close: what each row ended as, and the part that carries it
964
+ ...(Array.isArray(authored.ledger) && authored.ledger.length ? { list: structuredClone(authored.ledger) } : {}),
870
965
  // the lines the always-on guards cover (names and numbers only, nothing free-text)
871
966
  ...(authored.declaration.guardLines?.length
872
967
  ? { guardLines: authored.declaration.guardLines.map((/** @type {any} */ g) => ({ guard: g.guard, lines: [...g.lines] })) }
@@ -967,6 +1062,11 @@ export async function authorCloseForJob({
967
1062
  seedRef: seed,
968
1063
  authoring: authored,
969
1064
  judged,
1065
+ // the checks the person picked, for the plan card's "You picked" rows (read from the block's rows)
1066
+ ...(block ? { hasBuiltCheck: block.hasBuiltCheck() } : {}),
1067
+ // the suggestions code could not build, one plain sentence each: the Audit's draft lines, never the card (hamr 2026-11-13, F-b)
1068
+ ...(block ? { notBuilt: block.unbuiltSuggestions() } : {}),
1069
+ ...(block ? { picked: block.rows.filter((r) => r.kind === 'rule' && r.pick).map((r) => ({ line: r.line, text: `${plainWords(r.pick)}${r.keptFromLast ? ` \u00B7 ${KEPT_WORDS}` : ''}` })) } : {}),
970
1070
  reds: authored.reds,
971
1071
  stop: authored.stop,
972
1072
  cost: authored.cost,
@@ -1072,6 +1172,14 @@ export function assembleSpec(specDraft, { closeDecl, verdictType }) {
1072
1172
  throw new Error('the spec draft carries trigger — a schedule is set only by the person, in the panel\'s two-click schedule '
1073
1173
  + 'door, never by a draft. Remove the field from the draft');
1074
1174
  }
1175
+ // MCP + tickets (piece 1): the MCP source, flow type, ticket filter and watch are set by CODE from the person's card pick, never by a draft
1176
+ // (the agent never widens its own tool menu). Refused by name, like `trigger`.
1177
+ for (const f of ['mcp', 'flowType', 'ticketFilter', 'ticketWatch']) {
1178
+ if (draft[f] !== undefined) {
1179
+ throw new Error(`the spec draft carries ${f} — the MCP source and ticket fields are set by code from the person's card pick, `
1180
+ + 'and signed by the person, never by a draft. Remove the field from the draft');
1181
+ }
1182
+ }
1075
1183
  return { ...draft, verdictType, closeDecl };
1076
1184
  }
1077
1185
 
@@ -316,6 +316,10 @@ export function phaseLine(phase, data = {}) {
316
316
  case 'scout-done': return `· scout ${data.state ?? 'unknown'} — ${data.facts ?? 0} fact(s)`;
317
317
  case 'look': return '· looking at your input — a read-only search for the facts the job asks for…';
318
318
  case 'look-done': return `· look ${data.state ?? 'unknown'} — ${data.facts ?? 0} fact(s) can be checked`;
319
+ case 'ledger-suggest': return '· suggesting extra checks from your input…';
320
+ case 'ledger-built': { const rows = Array.isArray(data.rows) ? data.rows : []; const not = rows.filter((/** @type {any} */ r) => r.state === 'not-checked').length; return `· the list of checks: ${rows.length} row(s), ${not} not checked`; }
321
+ case 'draft-ledger-try': return `· ${data.label}: ${data.kept ?? '?'} edit(s) kept, ${(data.refused ?? []).length} refused`;
322
+ case 'draft-ledger': { const rows = Array.isArray(data.rows) ? data.rows : []; const n = (/** @type {string} */ st) => rows.filter((/** @type {any} */ r) => r.state === st).length; return `· the list at the end: ${n('built')} built, ${n('not-checked')} not checked`; }
319
323
  case 'listing': return '· listing the files the declaration may name…';
320
324
  case 'listing-done': return `· listing ${data.stop ? `STOPPED (${data.stop})` : `${data.files ?? 'unknown'} file(s)`}`;
321
325
  case 'author': return '· authoring the close declaration…';
@@ -676,6 +680,7 @@ export const STOP_HEADS = {
676
680
  'calibration-missing': 'Drafting stopped: the practice cases that prove the rubric were missing, so the check could not be trusted.',
677
681
  'invalid-set': 'Drafting stopped: the rubric and its practice cases do not fit together, so they could not be graded.',
678
682
  'broken-close': 'Drafting stopped: the final check the model wrote could not run.',
683
+ 'plan-red': 'Drafting stopped: the plan code built from your checks did not pass its own gate. That is a fault in the build, not in your job.',
679
684
  'listing-absent': 'Drafting stopped: the list of your files was not available, so the checks could not name any.',
680
685
  'listing-conflict': 'Drafting stopped: the list of your files was given twice and the two did not agree.',
681
686
  'listing-unreadable': 'Drafting stopped: your repo\'s file list could not be read.',
@@ -695,6 +700,7 @@ const STOP_TODO = /** @type {Record<string, string>} */ ({
695
700
  'listing-unreadable': 'check the repo is a readable git repo with at least one commit, then draft again.',
696
701
  'confirm-abandoned': 'start a new draft when you are ready; nothing more was spent.',
697
702
  'confirm-restart': 'change the answers you want and start the draft again.',
703
+ 'plan-red': 'draft again; if it stops the same way twice, report it (nothing was spent on a close).',
698
704
  });
699
705
 
700
706
  /** a stop code this table does not know: still plain words, never the code */
@@ -871,6 +877,10 @@ const listText = (v) => {
871
877
  /** the sentence when the gates refuse with no red at all (the close already passes on the untouched repository) */
872
878
  const SEED_GREEN_SENTENCE = 'Nothing in the close fails on the repository as it is, so there is nothing for a run to do.';
873
879
 
880
+ /** the sentence and the to-do when a rubric / page job's close has no check that can fail (hamr ruling 2026-11-10) */
881
+ const NO_CHECK_SENTENCE = 'This job has no check that can fail: no `~` rule, and no check the AI built was kept. A run needs at least one check, a quoted fact or a count. Without one, its pass would prove nothing. For an answer nobody checks, a plain chat AI is the right tool.';
882
+ const NO_CHECK_TODO = 'add a `~` rule (for example the version, the date, or "under 80 words"), or answer the question with what the output must contain';
883
+
874
884
  /**
875
885
  * Plain sentences for the reds of a refused signing, one or more per red. Card and practice-case reds reuse the
876
886
  * proposal table; an unknown code is a generic sentence that quotes the code.
@@ -904,14 +914,15 @@ export function signingKinds() {
904
914
 
905
915
  /**
906
916
  * THE MESSAGE a person reads when the signing gates refuse. The panel's failed step and the CLI print exactly this.
907
- * @param {{reds: PlainRed[], refusal?: {detail?: string}|null, cases?: any,
908
- * spend?: {knownUsd?: number|null, spendComplete?: boolean|null}|null}} o
917
+ * @param {{reds: PlainRed[], refusal?: {detail?: string}|null, cases?: any, noCheck?: boolean,
918
+ * spend?: {knownUsd?: number|null, spendComplete?: boolean|null}|null}} o `noCheck` = the check block has no built check (block.hasBuiltCheck() is false): the stop is the end check's own words
909
919
  * @returns {string}
910
920
  */
911
- export function signingStopText({ reds, refusal = null, cases = null, spend = null }) {
921
+ export function signingStopText({ reds, refusal = null, cases = null, spend = null, noCheck = false }) {
912
922
  const reasons = signingReasons(reds, { cases });
913
923
  if (reasons.length === 0) {
914
- reasons.push({ kind: 'seed-green', sentence: SEED_GREEN_SENTENCE, todo: 'check that the close measures the right thing, or describe a sharper problem',
924
+ reasons.push({ kind: 'seed-green', sentence: noCheck ? NO_CHECK_SENTENCE : SEED_GREEN_SENTENCE,
925
+ todo: noCheck ? NO_CHECK_TODO : 'check that the close measures the right thing, or describe a sharper problem',
915
926
  red: { code: '', path: '', detail: String(refusal?.detail ?? '') } });
916
927
  }
917
928
  const unique = [...new Set(reasons.map((x) => x.sentence))];
package/src/authorrun.js CHANGED
@@ -114,7 +114,7 @@ import {
114
114
  REFUSAL_LIB, REFUSAL_CATEGORY,
115
115
  } from './authorjob.js';
116
116
  import {
117
- makeLoopGenerate, CONFIRM_MENU, CONFIRM_SYSTEM,
117
+ makeLoopGenerate, CONFIRM_MENU, confirmSystemFor,
118
118
  } from './authorflow.js';
119
119
  import { defaultJudgeLoop, resolveJobJudge } from './judged.js';
120
120
  import { validateJob, jobSpecHash, resolveWorkerModel } from './job.js';
@@ -122,6 +122,8 @@ import { scanSecrets, redactSecrets } from './validate.js';
122
122
  import { detectLanguage } from './detectlang.js';
123
123
  import { RUBRIC_LANG } from './authoring.js';
124
124
  import { rubricGoal } from './rubricstep.js';
125
+ import { LEDGER_SYSTEM } from './checklist.js';
126
+ import { ROW_EDIT_SYSTEM } from './rowedit.js';
125
127
  import { moveFile } from './movefile.js';
126
128
  import { closeJudges, GATE_AUDIT_FILE } from './kinds.js';
127
129
  import { resolveProvider, buildRunnerProviders, apiKeyProblem } from './providers.js';
@@ -822,7 +824,7 @@ export async function main(argv, deps = {}) {
822
824
  * bound to `CONFIRM_SYSTEM`, never the authoring `generate` above (that one
823
825
  * is bound to `AUTHOR_SYSTEM`). Same provider instance, a different system
824
826
  * prompt: reusing `generate` would run the wrong system prompt silently. */
825
- const confirmGenerate = makeLoopGenerate(provider, { system: CONFIRM_SYSTEM, rates: authorPrice?.rates ?? null });
827
+ const confirmGenerate = makeLoopGenerate(provider, { system: confirmSystemFor(LANG), rates: authorPrice?.rates ?? null });
826
828
 
827
829
  // ── PLAIN-FOLDER SOURCE: A NAMED $0 STOP, NO MODEL CALL (F191; PRD item 33 M3
828
830
  // piece 4, step S6, D5 amended 2026-09-21) ──────────────────────────────────
@@ -908,6 +910,10 @@ export async function main(argv, deps = {}) {
908
910
  // travels through unchanged — its `ambiguous` shape is what the confirm
909
911
  // turn's own $0 half (D7) asks about, before the scout.
910
912
  ask, confirmGenerate, isRepo: !RUBRIC_FILES, langResult,
913
+ // the one check list of a rubric job (src/checklist.js): same list as the panel, its one call bound to its own system text; this door asks nothing for it
914
+ ledgerGenerate: RUBRIC_FILES ? makeLoopGenerate(provider, { system: LEDGER_SYSTEM, rates: authorPrice?.rates ?? null }) : null,
915
+ // the drafter's row-edit reply of a rubric job (src/rowedit.js), its own system text
916
+ editGenerate: RUBRIC_FILES ? makeLoopGenerate(provider, { system: ROW_EDIT_SYSTEM, rates: authorPrice?.rates ?? null }) : null,
911
917
  });
912
918
  const authoredFile = writeOut('authored.json', authored);
913
919
  emit('authored', { ok: authored.ok, stop: authored.stop, seedRef: authored.seedRef, cost: authored.cost, reds: authored.reds });
@@ -1173,7 +1179,10 @@ export async function main(argv, deps = {}) {
1173
1179
  out(`\ncalibration gate — REAL judge calls at ${judge.model} on ${judge.provider}, one per case plus the injection battery.`);
1174
1180
  out(' this is the only gate that spends money, and it runs after every free one.');
1175
1181
  }
1176
- const signing = await prepareSigning({
1182
+ // the end check: a rubric close with no real check is refused here, whatever the seed gate would say (the stop words are printed below from signingStopText)
1183
+ const signing = authored.hasBuiltCheck === false
1184
+ ? { ok: false, reds: [], refusal: null, specHash: null, seedRef: authored.seedRef, gates: { declaration: { ok: true, grounded: '-' }, precheck: null, seedVerdict: null }, work: [], guards: [], stops: [] }
1185
+ : await prepareSigning({
1177
1186
  spec, workdir: SOURCE, seedRef: authored.seedRef, timeoutMs: TIMEOUT_MS,
1178
1187
  // gate 1a re-runs the job validator inside prepareSigning — same coupling, or
1179
1188
  // the spec that just passed above would fail the gate that signs it
@@ -1238,7 +1247,7 @@ export async function main(argv, deps = {}) {
1238
1247
  if (!signing.ok) {
1239
1248
  const t = costSoFar();
1240
1249
  out(`\n${signingStopText({
1241
- reds: signing.reds ?? [], refusal: signing.refusal,
1250
+ reds: signing.reds ?? [], refusal: signing.refusal, noCheck: authored.hasBuiltCheck === false,
1242
1251
  spend: { knownUsd: t.knownUsd ?? null, spendComplete: t.spendComplete ?? null },
1243
1252
  })}`);
1244
1253
  }
@@ -376,7 +376,7 @@ const defaultLoop = (/** @type {any} */ { system, policy, onLlmResult, provider,
376
376
  * @param {{workdir: string, provider?: any,
377
377
  * rounds?: number, minBytes?: number, blobMax?: number, maxTokens?: number, ctx?: boolean,
378
378
  * attempts?: number, ceilingUsd?: number|null, callTimeoutMs?: number,
379
- * onCall?: (call: {label: string, costUsd: number|null, unpricedRounds: number, thinkingStatus?: string}) => void,
379
+ * onCall?: (call: {label: string, costUsd: number|null, unpricedRounds: number, thinkingStatus?: string, raw?: string}) => void,
380
380
  * createLoop?: (o: {system: string, policy: any, onLlmResult: any, provider: any, rates?: {in: number, out: number}}) => any,
381
381
  * rates?: {in: number, out: number}|null, callOptions?: Record<string, any>,
382
382
  * createSurveyor?: (o: {workdir: string, granted: readonly string[], ctx: boolean}) => Promise<any>}} o
@@ -438,8 +438,10 @@ export async function runAuthorScout({
438
438
  // raw already rides. It REPORTS and decides nothing; the ceiling still binds
439
439
  // through `capStop` between calls, untouched.
440
440
  // bare-agent's per-run `thinkingStatus` rides the reporting seam only, never the stored entry (see makeCostBook.add)
441
- onCall({ ...call, ...(r?.thinkingStatus === undefined ? {} : { thinkingStatus: r.thinkingStatus }) });
442
- return raws.push(scrubRaw({ label, attempt, text: r?.text })) - 1;
441
+ // R9 (Part B 4): the scrubbed answer rides the same report, so the session's drafting log keeps what an unusable scout answer said (an empty one adds nothing)
442
+ const kept = scrubRaw({ label, attempt, text: r?.text });
443
+ onCall({ ...call, ...(kept.text === '' ? {} : { raw: kept.text }), ...(r?.thinkingStatus === undefined ? {} : { thinkingStatus: r.thinkingStatus }) });
444
+ return raws.push(kept) - 1;
443
445
  };
444
446
  // TIGHTEN-ONLY: an operator may lower the ceiling, never raise it. A garbage
445
447
  // value floors at one attempt rather than at zero — a scout that never ran is
@@ -679,7 +681,7 @@ export const LOOK_RECOVERY_PROMPT = 'You are out of looking turns. Report NOW, f
679
681
  * Run the look. `createLoop` is the same seam the repo scout has; nothing else here needs a live process.
680
682
  * @param {{texts: Record<string, string>, inputs: {n: number, label: string}[], jobLines: {n: number, text: string, rule?: string, rules?: string[]}[],
681
683
  * provider?: any, rounds?: number, maxTokens?: number, ceilingUsd?: number|null, callTimeoutMs?: number,
682
- * onCall?: (call: {label: string, costUsd: number|null, unpricedRounds: number, thinkingStatus?: string}) => void,
684
+ * onCall?: (call: {label: string, costUsd: number|null, unpricedRounds: number, thinkingStatus?: string, raw?: string}) => void,
683
685
  * createLoop?: (o: {system: string, policy: any, onLlmResult: any, provider: any, rates?: {in: number, out: number}}) => any,
684
686
  * rates?: {in: number, out: number}|null, callOptions?: Record<string, any>,
685
687
  * prove?: (source: string, phrase: string) => number}} o
@@ -701,8 +703,9 @@ export async function runInputLook({
701
703
  const record = (/** @type {string} */ label, /** @type {any} */ r) => {
702
704
  const call = { label, ...priceOf(r) };
703
705
  calls.push(call);
704
- onCall({ ...call, ...(r?.thinkingStatus === undefined ? {} : { thinkingStatus: r.thinkingStatus }) });
705
- raws.push(scrubRaw({ label, attempt: 1, text: r?.text }));
706
+ const kept = scrubRaw({ label, attempt: 1, text: r?.text });
707
+ onCall({ ...call, ...(kept.text === '' ? {} : { raw: kept.text }), ...(r?.thinkingStatus === undefined ? {} : { thinkingStatus: r.thinkingStatus }) });
708
+ raws.push(kept);
706
709
  };
707
710
  const settled = async (/** @type {Promise<any>} */ p) => {
708
711
  try { return await p; } catch (e) {
package/src/behaviour.js CHANGED
@@ -122,6 +122,20 @@ export function runBehaviour(events, { runId } = {}) {
122
122
  };
123
123
  }
124
124
 
125
+ /**
126
+ * How many write/edit attempts the gate DENIED (they fell outside the write scope), from gate-audit records alone. One write-class test (action `type`
127
+ * write|edit, as `workerWrites`' reader in src/planrun.js uses), deny-decision only: an allowed write is never counted. Pure.
128
+ * @param {Array<{action?: {type?: string}, decision?: string|null}>} events
129
+ * @returns {number}
130
+ */
131
+ export function writesBlocked(events) {
132
+ let n = 0;
133
+ for (const e of Array.isArray(events) ? events : []) {
134
+ if (e?.decision === 'deny' && (e.action?.type === 'write' || e.action?.type === 'edit')) n += 1;
135
+ }
136
+ return n;
137
+ }
138
+
125
139
  /**
126
140
  * Render a {@link runBehaviour} summary as the agreed printable block
127
141
  * (2–4 short lines). A zero-call run formats plainly ("0 tool calls") rather
@@ -0,0 +1,43 @@
1
+ // The questions of the check block, as the answer gate reads them (`answerQuestions`, src/questionbox.js): ONE spelling of the question words, written by code from a row that
2
+ // code could not settle (reading | cant-check | check). The block's `open` list is the source; the person's CHOICE (agree | drop | rule) goes back through `block.applyAnswer`.
3
+ import { readingQuestion, cantCheckQuestion } from './pagemap.js';
4
+ import { plainWords, HOW_TO_ANSWER, CANT_CHECK_WORDS } from './checkpick.js';
5
+
6
+ /** @typedef {{key: string, rowKey: string, line: number, rule: number, source: 'look', ask: 'reading'|'cant-check'|'no-check'|'check', ruleText: string, question: string, counted: boolean, reading?: string, check?: Record<string, any>, pairRule?: number}} BlockAsk */
7
+
8
+ /**
9
+ * The questions the block has open, in the order the person meets them: the look's readings, then the look's can't-checks, then the pick path's asks (a proposal or a can't-check about a rule the pick path owns) in rule order (a proposal is not counted toward the 3-ask cap).
10
+ * A can't-check about a rule the PICK path owns (`scoped`: src/checkpick.js scopedRules, every `~` rule of a file job) is the pick path's own ask, `no-check`, in fwd's words (a "Line N, guardrail ...: I can't check this" ask
11
+ * whose answer the panel records as a pick, so Revise carries it: am17/am18/am21); any other can't-check is the look's own ask about a page.
12
+ * @param {import('./checkblock.js').CheckBlock} block @param {{line: number, rule: number}[]} [scoped] @returns {BlockAsk[]}
13
+ */
14
+ export function questionsOfBlock(block, scoped = []) {
15
+ const rank = { reading: 0, 'cant-check': 1, 'no-check': 2, check: 2 };
16
+ return block.open.map((/** @type {any} */ q) => {
17
+ const row = block.rows.find((r) => r.key === q.rowKey);
18
+ const rule = Number(row?.rule);
19
+ const base = { key: q.key, rowKey: q.rowKey, line: q.line, rule, source: /** @type {'look'} */ ('look'), ruleText: String(q.ruleText), ...(row?.pairWith !== undefined ? { pairRule: row.pairWith } : {}) };
20
+ if (q.ask === 'reading') return { ...base, ask: /** @type {'reading'} */ ('reading'), counted: true, reading: String(q.proposal), question: readingQuestion(q.line, String(q.ruleText), String(q.proposal)) };
21
+ if (q.ask === 'check') {
22
+ const words = plainWords(q.proposal);
23
+ return { ...base, ask: /** @type {'check'} */ ('check'), counted: false, reading: words, check: q.proposal, question: `Line ${q.line}, guardrail "${q.ruleText}": I propose ${words}. ${HOW_TO_ANSWER(q.line, true)}` };
24
+ }
25
+ if (scoped.some((x) => x.line === q.line && x.rule === rule)) return { ...base, ask: /** @type {'no-check'} */ ('no-check'), counted: true, question: `Line ${q.line}, guardrail "${q.ruleText}": ${CANT_CHECK_WORDS} ${HOW_TO_ANSWER(q.line, false)}` };
26
+ return { ...base, ask: /** @type {'cant-check'} */ ('cant-check'), counted: true, question: cantCheckQuestion(q.line, String(q.ruleText)) };
27
+ }).sort((a, b) => rank[a.ask] - rank[b.ask]);
28
+ }
29
+
30
+ /**
31
+ * The person's choices back into the block, one by one (the choice decides, never the words). A choice the block refuses is returned with its plain reason; the question stays open.
32
+ * @param {import('./checkblock.js').CheckBlock} block @param {{key: string, choice: string, text?: string}[]} choices @returns {{key: string, why: string}[]}
33
+ */
34
+ export function applyChoices(block, choices) {
35
+ /** @type {{key: string, why: string}[]} */
36
+ const refused = [];
37
+ for (const c of choices) {
38
+ const r = block.applyAnswer(c.key, c.choice, c.text);
39
+ if (!r.ok) refused.push({ key: c.key, why: r.why });
40
+ }
41
+ block.reconcile();
42
+ return refused;
43
+ }