bareloop 0.55.0 → 0.57.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 (92) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +3 -3
  3. package/bareloop.context.md +69 -209
  4. package/package.json +2 -2
  5. package/src/authorflow.js +164 -340
  6. package/src/authoring.js +7 -127
  7. package/src/authorjob.js +139 -472
  8. package/src/authorreadout.js +24 -368
  9. package/src/authorrun.js +21 -215
  10. package/src/behaviour.js +14 -0
  11. package/src/blockasks.js +43 -0
  12. package/src/bundlerun.js +4 -1
  13. package/src/checkblock.js +798 -0
  14. package/src/checklist.js +128 -0
  15. package/src/checkpick.js +39 -312
  16. package/src/checkwords.js +3 -1
  17. package/src/cli.js +3 -3
  18. package/src/declaredclose.js +38 -108
  19. package/src/destpoint.js +4 -2
  20. package/src/draftspend.js +46 -0
  21. package/src/facts.js +8 -1
  22. package/src/index.js +3 -43
  23. package/src/interviewrun.js +13 -8
  24. package/src/job.js +20 -1
  25. package/src/jobblock.js +11 -46
  26. package/src/judged.js +13 -1229
  27. package/src/kinds.js +5 -347
  28. package/src/noteask.js +124 -0
  29. package/src/pagedry.js +27 -5
  30. package/src/pagemap.js +15 -3
  31. package/src/pagerules.js +18 -3
  32. package/src/panel/authorroutes.js +24 -6
  33. package/src/panel/authorsession.js +222 -177
  34. package/src/panel/importrun.js +0 -1
  35. package/src/panel/index.html +198 -26
  36. package/src/panel/jobplan.js +87 -33
  37. package/src/panel/server.js +74 -68
  38. package/src/panel/status.js +3 -0
  39. package/src/pickrecord.js +34 -55
  40. package/src/placerule.js +355 -0
  41. package/src/planrun.js +2 -48
  42. package/src/promptregisters.js +13 -17
  43. package/src/providerrows.js +0 -36
  44. package/src/providers.js +4 -25
  45. package/src/questionbox.js +104 -0
  46. package/src/rowedit.js +115 -0
  47. package/src/rubricstep.js +234 -127
  48. package/src/run.js +11 -16
  49. package/src/userrun.js +60 -112
  50. package/types/authorflow.d.ts +41 -197
  51. package/types/authoring.d.ts +1 -14
  52. package/types/authorjob.d.ts +35 -59
  53. package/types/authorreadout.d.ts +10 -88
  54. package/types/behaviour.d.ts +12 -0
  55. package/types/blockasks.d.ts +36 -0
  56. package/types/checkblock.d.ts +376 -0
  57. package/types/checklist.d.ts +134 -0
  58. package/types/checkpick.d.ts +8 -140
  59. package/types/cli.d.ts +1 -3
  60. package/types/declaredclose.d.ts +7 -33
  61. package/types/destpoint.d.ts +2 -0
  62. package/types/draftspend.d.ts +21 -0
  63. package/types/index.d.ts +2 -4
  64. package/types/job.d.ts +8 -0
  65. package/types/jobblock.d.ts +8 -38
  66. package/types/judged.d.ts +7 -357
  67. package/types/kinds.d.ts +3 -104
  68. package/types/noteask.d.ts +76 -0
  69. package/types/pagedry.d.ts +13 -0
  70. package/types/pagemap.d.ts +4 -0
  71. package/types/pagerules.d.ts +7 -0
  72. package/types/panel/authorsession.d.ts +47 -5
  73. package/types/panel/jobgrid.d.ts +8 -8
  74. package/types/panel/jobplan.d.ts +48 -10
  75. package/types/panel/server.d.ts +27 -18
  76. package/types/panel/status.d.ts +5 -0
  77. package/types/pickrecord.d.ts +20 -13
  78. package/types/placerule.d.ts +194 -0
  79. package/types/planrun.d.ts +1 -22
  80. package/types/providerrows.d.ts +0 -31
  81. package/types/providers.d.ts +3 -19
  82. package/types/questionbox.d.ts +87 -0
  83. package/types/rowedit.d.ts +32 -0
  84. package/types/rubricstep.d.ts +100 -48
  85. package/types/run.d.ts +9 -19
  86. package/types/userrun.d.ts +0 -1
  87. package/src/calibrate.js +0 -702
  88. package/src/cardauthor.js +0 -502
  89. package/src/fitcheck.js +0 -166
  90. package/types/calibrate.d.ts +0 -201
  91. package/types/cardauthor.d.ts +0 -358
  92. package/types/fitcheck.d.ts +0 -113
package/src/authorjob.js CHANGED
@@ -99,30 +99,31 @@
99
99
  // in the stored declaration (forward-compat point 3), and the suite pins it.
100
100
 
101
101
  import { jobSpecHash, validateJob } from './job.js';
102
- import { seedAtHead, seedListing, seedRead as runSeedRead, makeSeedTrees, judgedStages, closeJudges } from './kinds.js';
103
- import { inputLabelsOf, readFrozenInputs, lineRules } from './rubricstep.js';
102
+ import { seedAtHead, seedListing, seedRead as runSeedRead, makeSeedTrees } from './kinds.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.
107
- import { proposeJudgedArtifacts, signJudgedArtifacts, foldJudgedArtifacts } from './cardauthor.js';
108
- import { runCalibration } from './calibrate.js';
109
- import { CALIBRATION_SIZE } from './judged.js';
110
107
  import {
111
108
  GENRE_LANGUAGES, RUBRIC_LANG, DECLARABLE_LANGUAGES, genreForLang, LOCKED_KINDS, TYPES_GENRE, VERDICT_CLASSES, LOCKED_CLASSES, LIVE_CLASSES,
112
109
  UNLISTED_CLASSES, MENU_CLASSES,
113
110
  } from './authoring.js';
114
111
  import {
115
112
  QUESTION_SETS, questionsFor, requiredAnswersFor, authorClose, makeCostBook,
116
- runConfirmTurn, LANGUAGE_PICK_FIELD, normalizeQuestions, MAX_QUESTIONS,
113
+ runConfirmTurn, LANGUAGE_PICK_FIELD, MAX_QUESTIONS,
117
114
  } from './authorflow.js';
118
115
  import { thinkingCallOptions, assertThinkingMode } from './thinking.js';
119
- import { runFitCheck, fitQuestionText, notFoundList, isGoOn } from './fitcheck.js';
120
116
  import { pageContentChars } from './pagefetch.js';
121
117
  import { runAuthorScout, buildSeedListing, SCOUT_ATTEMPTS } from './authorscout.js';
122
- import { runPageMap, askableFromLook, tooManyAsksText } from './pagemap.js';
123
- import { scopedRules, checkAsks } from './checkpick.js';
124
- import { matchRecord, entriesFromAnswers } from './pickrecord.js';
118
+ import { runPageMap, tooManyAsksText } from './pagemap.js';
119
+ import { CheckBlock } from './checkblock.js';
120
+ import { questionsOfBlock, applyChoices } from './blockasks.js';
121
+ import { askNotes } from './noteask.js';
122
+ import { renderJobLines } from './jobblock.js';
123
+ import { scopedRules, codeScope, plainWords, obviousCheck } from './checkpick.js';
124
+ import { matchRecord, entriesFromAnswers, KEPT_WORDS } from './pickrecord.js';
125
125
  import { runCheckSuggest } from './checksuggest.js';
126
+ import { runLedgerSuggest, ledgerRecord } from './checklist.js';
126
127
  import {
127
128
  DECLARED_GAP_PREFIX, DECLARED_GENRES, guardNames, isDeclaredClose, validateCloseDecl,
128
129
  } from './declaredclose.js';
@@ -426,26 +427,24 @@ function composerRefusal(reds) {
426
427
  * one-genre-at-a-time law is untouched.
427
428
  *
428
429
  * @param {{answers: Record<string|number, any>, repoPath?: string|null, lang: string,
429
- * jobLines?: {n: number, text: string}[]|null, inputs?: {n: number, label: string, value: string}[]|null,
430
+ * jobLines?: {n: number, text: string, rule?: string, rules?: string[]}[]|null, inputs?: {n: number, label: string, value: string}[]|null,
430
431
  * verdictType?: string|null,
431
432
  * questions?: Record<string|number, string>|null, generate?: Function, provider?: any,
432
- * seedRef?: string|null, scout?: any, listing?: any, ceilingUsd?: number|null, judgeModel?: string|null,
433
+ * seedRef?: string|null, scout?: any, listing?: any, ceilingUsd?: number|null,
433
434
  * rates?: {in: number, out: number}|null, draftThinking?: 'on'|'off',
434
435
  * onPhase?: (phase: string, data?: any) => void,
435
436
  * onCall?: (call: {label: string, costUsd: number|null, unpricedRounds: number, thinkingStatus?: string}) => void,
436
- * seedFn?: Function, scoutFn?: Function, listingFn?: Function, lookFn?: Function|null, fitFn?: Function|null,
437
- * fitAsk?: ((question: string) => Promise<string|null>)|null, onFit?: (fit: {state: string, asks: any[], notFound: any[]}) => void,
437
+ * seedFn?: Function, scoutFn?: Function, listingFn?: Function, lookFn?: Function|null,
438
438
  * authorFn?: Function, authorOpts?: object, writeScope?: string[]|null,
439
- * signerFix?: Function|any, proposeFn?: Function, compileOpts?: object,
440
439
  * ask?: ((step: {kind: string, [k: string]: any}) => Promise<string|null>)|null,
441
- * answerQuestions?: ((o: {questions: {line: number, question: string, rule?: number, source?: string, ask?: string, reading?: string}[], dropped: {reason: string, raw: any}[], confirmed: any}) =>
442
- * Promise<{jobLines: {n: number, text: string, rule?: string}[], answers: Record<string|number, any>, left?: {line: number, rule: number}[], picks?: any[]}|null>)|null,
443
- * pickGenerate?: Function|null, carriedPicks?: any[]|null, onPicks?: (o: {entries: any[], kept: {line: number, rule: number, entry: any}[]}) => void,
440
+ * answerQuestions?: ((o: {questions: {line: number, question: string, rule?: number, source?: string, ask?: string, reading?: string, key?: string}[], dropped: {reason: string, raw: any}[], confirmed: any}) =>
441
+ * 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,
442
+ * pickGenerate?: Function|null, ledgerGenerate?: Function|null, noteFn?: Function|null, onJobLines?: ((jobLines: any[]) => void)|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,
444
443
  * confirmGenerate?: Function|null, isRepo?: boolean,
445
444
  * langResult?: {kind: string, candidates?: string[], [k: string]: any}|null}} o
446
445
  * @returns {Promise<{ok: boolean, refusal: Refusal|null, verdictType: string|null,
447
- * closeDecl: any, seedRef: string|null, authoring: any, judged: any, reds: Red[],
448
- * stop: string|null, cost: any, interview: any, confirmed: any, checkPicks?: any}>}
446
+ * closeDecl: any, seedRef: string|null, authoring: any, reds: Red[],
447
+ * stop: string|null, cost: any, interview: any, confirmed: any, picked?: {line: number, text: string}[], hasBuiltCheck?: boolean, notBuilt?: {line: number, text: string}[]}>}
449
448
  */
450
449
  export async function authorCloseForJob({
451
450
  answers, repoPath = null, lang, verdictType = null, questions = null,
@@ -463,11 +462,6 @@ export async function authorCloseForJob({
463
462
  // `writeScope`, and this is what carries it into the composer prompt
464
463
  // (`authorPrompt`'s `writeScopeBlock`) instead of letting it vanish.
465
464
  writeScope = null,
466
- // THE JUDGE IDENTITY (PRD item 32.1), required only on the path that actually
467
- // composes a judged stage — the stored calibration set carries the judge that
468
- // certified it, and there is no library pin to fall back to. Absent on a purely
469
- // mechanical close is correct and costs nothing: that close never judges.
470
- judgeModel = null,
471
465
  // THE PROGRESS SEAMS. This composition is the pipeline's long silence — a real
472
466
  // survey, a real declaration ladder, and a real toolchain per close stage — and
473
467
  // it emitted nothing until it returned, so an operator watching a live run
@@ -479,20 +473,23 @@ export async function authorCloseForJob({
479
473
  // PART 1c / IDEA A CORE - the look at a rubric job's inputs: the default is the page-word map (src/pagemap.js `runPageMap`, one paid AI
480
474
  // call per page input, its words kept by code). `null` is an explicit "no look" (a test seam, like a caller-supplied `scout`).
481
475
  lookFn = runPageMap,
482
- // THE FIT CHECK (F243): one paid call BEFORE the look, rubric jobs only. It runs only when the caller supplies the answer seam `fitAsk` (the panel);
483
- // `fitFn` null is an explicit "no check" (a test seam). With no `fitAsk` (the CLI door) it never runs.
484
- fitFn = runFitCheck, fitAsk = null, onFit = () => {},
485
476
  authorFn = authorClose, authorOpts = {},
486
477
  // 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
487
478
  // drafted declaration is validated as it always was (a test seam, like `lookFn: null`).
488
479
  pickGenerate = null,
480
+ // 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
481
+ // (a test seam, like `pickGenerate`); the CLI and the panel always bring it.
482
+ ledgerGenerate = null,
483
+ // 2026-11-14 (b): the note question (src/noteask.js), asked ONLY when a rubric line is facts-only; ABSENT = never asked (every older caller and test)
484
+ noteFn = null,
485
+ // one rule in, one rule out: called with the job lines rebuilt from the check list after an answer (the seam that shows the job text updates itself); ABSENT = nothing shows it
486
+ onJobLines = null,
487
+ // the row-edit turn's own model boundary (src/rowedit.js ROW_EDIT_SYSTEM); a test that replaces `generate` need not bring one
488
+ editGenerate = null,
489
489
  // 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.
490
490
  carriedPicks = null, onPicks = () => {},
491
- // SOFTGREEN modules 4+5. `signerFix` is the D5 seam: a function (or a value)
492
- // carrying the SIGNER's corrected artifacts back. Absent means the proposal is
493
- // signed as proposed, and `signJudgedArtifacts` records which of the two
494
- // happened rather than leaving a reader to guess.
495
- signerFix = null, proposeFn = proposeJudgedArtifacts, compileOpts = {},
491
+ // 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
492
+ carriedChoices = null, onChoices = () => {},
496
493
  // PRD item 33 M3 piece 4 — the confirm turn. ALL FOUR default to nothing so
497
494
  // every existing caller runs byte-identical: `ask` absent means no confirm
498
495
  // turn runs at all, exactly as before this piece existed.
@@ -522,7 +519,7 @@ export async function authorCloseForJob({
522
519
  /** @type {any} */
523
520
  const base = {
524
521
  ok: false, refusal: null, verdictType: null, closeDecl: null, seedRef: null,
525
- authoring: null, judged: null, reds: [], stop: null, cost: null, interview: null,
522
+ authoring: null, reds: [], stop: null, cost: null, interview: null,
526
523
  confirmed: null,
527
524
  };
528
525
 
@@ -613,6 +610,8 @@ export async function authorCloseForJob({
613
610
  // arrived at by accident.
614
611
  /** @type {any} */
615
612
  let survey = scout;
613
+ /** the frozen input texts the list's word proof reads (a rubric job with a look) @type {Record<string, string>|null} */
614
+ let ledgerTexts = null;
616
615
  // 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
617
616
  // look at the person's frozen input text that reports which facts can be checked and with which label (picked from a code-made
618
617
  // list). Without a look (`lookFn` null, or no model boundary) the survey is just the numbered inputs, known to code at $0.
@@ -620,6 +619,7 @@ export async function authorCloseForJob({
620
619
  const inputList = (Array.isArray(inputs) ? inputs : []).map((i) => ({ n: i.n, label: i.label }));
621
620
  const frozen = lookFn && provider && Array.isArray(jobLines) && jobLines.length > 0 && inputList.length > 0
622
621
  ? await readFrozenInputs(workdir, inputList.map((i) => i.label)) : null;
622
+ if (frozen !== null && frozen.ok) ledgerTexts = frozen.texts;
623
623
  if (frozen !== null && !frozen.ok) {
624
624
  survey = { state: 'ABSENT', reason: `the look at your input could not start: ${frozen.why}`, cause: 'call-failed', budgetStop: null, calls: [], raws: [], facts: null };
625
625
  } else if (frozen !== null && lookFn && !Object.values(frozen.texts).some((t) => pageContentChars(t) > 0)) {
@@ -627,25 +627,6 @@ export async function authorCloseForJob({
627
627
  // nothing to check a rule against. Plain words, before any model call.
628
628
  survey = { state: 'ABSENT', reason: 'your input holds nothing to read (it is empty, or only the site\'s own header and menus) - nothing was asked and nothing was spent', cause: 'call-failed', budgetStop: null, calls: [], raws: [], facts: null };
629
629
  } else if (frozen !== null && lookFn) {
630
- if (fitAsk && fitFn) {
631
- // F243: a page that does not show what the job asks for stops here, before the look spends. Failure is OPEN: an `absent` check
632
- // (cut, unreadable twice, call failed, cap) asks nothing and drafting goes on; the answer is NOT a `~` rule and changes nothing in the job.
633
- onPhase('fit-check', {});
634
- const fitCallOptions = thinkingCallOptions(provider, draftThinking);
635
- const fit = await fitFn({
636
- jobLines, texts: frozen.texts, provider, ceilingUsd, onCall, ...(rates ? { rates } : {}),
637
- ...(Object.keys(fitCallOptions).length ? { callOptions: fitCallOptions } : {}),
638
- });
639
- onPhase('fit-check-done', { state: fit.state });
640
- onFit({ state: fit.state, asks: fit.asks, notFound: fit.notFound });
641
- if (fit.state === 'ask') {
642
- 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 }));
643
- if (answer === null) return { ...base, interview, verdictType: picked, seedRef: seed, reds: [], stop: 'confirm-abandoned', cost: null };
644
- if (!isGoOn(answer)) {
645
- return { ...base, interview, verdictType: picked, seedRef: seed, reds: [{ code: 'fit-stopped', path: 'jobLines', detail: notFoundList(fit.notFound) }], stop: 'fit-stopped', cost: null };
646
- }
647
- }
648
- }
649
630
  onPhase('look', {});
650
631
  const lookCallOptions = thinkingCallOptions(provider, draftThinking);
651
632
  survey = await lookFn({
@@ -678,87 +659,98 @@ export async function authorCloseForJob({
678
659
  onPhase('scout-done', { state: survey?.state ?? null, facts: Object.keys(survey?.facts ?? {}).length });
679
660
  }
680
661
 
681
- // 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
682
- // (src/pagemap.js `askableFromLook`; the model never decides whether to ask). Two kinds: a READING the code made of a `~` rule whose limit the
683
- // 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
684
- // 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
685
- // existing one (`answerQuestions`: answer required, no skip, the answer becomes a `~` rule on its line; `normalizeQuestions` keeps at most
686
- // 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
687
- // confirm card, in the signed plan and in the drafter's block, and can never be written back as a check.
688
- /** the look's code-forced asks that were put to the person (they count toward the cap with the pick asks) @type {any[]} */
689
- let lookAsks = [];
690
- if (answerQuestions && lang === RUBRIC_LANG && survey?.state === 'PRESENT' && survey.facts?.look && typeof survey.facts.look === 'object' && Array.isArray(jobLines)) {
691
- // R10: a rule the pick path scopes in is settled by its own ask (a proposal, or "I can't check this"), so the look does not also ask "I can't check this on the page" about it
692
- const picksOwn = pickGenerate ? new Set(scopedRules(jobLines, { inputs, look: survey.facts.look }).map((r) => `${r.line}:${r.rule}`)) : new Set();
693
- const candidates = askableFromLook(survey.facts.look, jobLines).filter((c) => !(c.ask === 'cant-check' && picksOwn.has(`${c.line}:${c.rule}`)));
694
- if (candidates.length > MAX_QUESTIONS) {
695
- 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 };
662
+ // 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:
663
+ // 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
664
+ // 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
665
+ // 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.
666
+ /** @type {import('./checkblock.js').CheckBlock|null} */
667
+ let block = null;
668
+ /** the picks the person made (kept and answered) this draft, as the picks record carries them */
669
+ /** @type {{kept: any[]}|null} */
670
+ let carried = null;
671
+ if (lang === RUBRIC_LANG && survey?.state === 'PRESENT' && Array.isArray(jobLines) && ledgerTexts) {
672
+ const look = survey.facts?.look && typeof survey.facts.look === 'object' ? survey.facts.look : null;
673
+ 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' });
674
+ block.fromJob(jobLines);
675
+ block.addLook(Array.isArray(look?.facts) ? look.facts : [], Array.isArray(look?.dropped) ? look.dropped : []);
676
+ /** the rules a count pick settles, as the record knows them (a scoped rule is a counting `~` rule code scopes in) */
677
+ const scoped = answerQuestions ? scopedRules(jobLines, { inputs, look }) : [];
678
+ const matched = matchRecord(Array.isArray(carriedPicks) ? carriedPicks : [], jobLines, scoped);
679
+ // a rule whose words already are its check is settled by the block as written (no ask, no suggestion call)
680
+ matched.askRules = matched.askRules.filter((r) => !obviousCheck(r.text));
681
+ carried = { kept: matched.kept };
682
+ block.carry({ picks: matched.picks, left: matched.left });
683
+ block.reconcile();
684
+ // the pick call: one suggestion per counting rule the record did not keep; each kept suggestion is a `pick` edit
685
+ if (answerQuestions && pickGenerate && matched.askRules.length > 0) {
686
+ onPhase('check-suggest', { rules: matched.askRules.length });
687
+ const sug = await runCheckSuggest({ jobLines, scoped: matched.askRules, generate: pickGenerate, ceilingUsd, onCall, priorCalls: survey?.calls ?? [], priorRaws: survey?.raws ?? [] });
688
+ survey.calls = [...(survey.calls ?? []), ...sug.calls];
689
+ survey.raws = [...(survey.raws ?? []), ...sug.raws];
690
+ 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 })) });
691
+ block.reconcile();
696
692
  }
697
- const kept = normalizeQuestions(candidates, [...new Set(candidates.map((q) => q.line))]);
698
- if (kept.kept.length > 0) {
699
- lookAsks = candidates;
700
- onPhase('look-ask', { questions: kept.kept.length });
701
- const updated = await answerQuestions({ questions: kept.kept, dropped: kept.dropped, confirmed: null });
702
- if (updated === null) return { ...base, interview, verdictType: picked, seedRef: seed, reds: [], stop: 'confirm-abandoned', cost: null };
703
- jobLines = updated.jobLines;
704
- interview.answers = updated.answers;
705
- for (const lf of Array.isArray(updated.left) ? updated.left : []) {
706
- const ruleText = lineRules(jobLines.find((l) => l.n === lf.line) ?? {})[lf.rule - 1];
707
- if (ruleText === undefined) continue;
708
- const look = survey.facts.look;
709
- look.dropped = [...(Array.isArray(look.dropped) ? look.dropped : []), { line: lf.line, rule: lf.rule, fact: ruleText, reason: 'person-left', source: 'person' }];
693
+ // the call for extra `!` checks (count, phrase): its proposals are edits like the drafter's own
694
+ if (ledgerGenerate) {
695
+ onPhase('ledger-suggest', {});
696
+ const lg = await runLedgerSuggest({ jobLines, texts: ledgerTexts, generate: ledgerGenerate, ceilingUsd, onCall, priorCalls: survey?.calls ?? [], priorRaws: survey?.raws ?? [] });
697
+ survey.calls = [...(survey.calls ?? []), ...lg.calls];
698
+ survey.raws = [...(survey.raws ?? []), ...lg.raws];
699
+ /** @type {any[]} */
700
+ const adds = [];
701
+ for (const e of lg.extra) {
702
+ const line = Number.isInteger(e?.line) ? e.line : 1;
703
+ if (e?.kind === 'count') adds.push({ op: 'add', kind: 'count', line, min: e.min, max: e.max });
704
+ 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 });
710
705
  }
706
+ block.applyDelta({ label: 'pre:ledger-suggest', pre: true, edits: adds });
707
+ block.reconcile();
711
708
  }
712
- }
713
-
714
- // R10 (fwdloop M10 am16, ruled 2026-11-09): for a rubric job, ONE paid call suggests a check from bareguard's own list for each `~` rule that code scopes in (src/checkpick.js
715
- // `scopedRules`); code keeps a suggestion only if its rule is on the list and every number and word is the rule's own (`keepOrDrop`); then CODE asks, through the same ask
716
- // path as the look's asks: a kept check is proposed (not counted toward the cap), nothing kept reads "I can't check this" (counted: the look's asks plus these, at most
717
- // MAX_QUESTIONS). The plan carries exactly the checks the person picked; the drafter writes none.
718
- /** @type {{rules: {line: number, rule: number, text: string}[], picks: any[], left: {line: number, rule: number}[], rows: any[]}|null} */
719
- let checkPicks = null;
720
- if (answerQuestions && pickGenerate && lang === RUBRIC_LANG && survey?.state === 'PRESENT' && Array.isArray(jobLines)) {
721
- const scoped = scopedRules(jobLines, { inputs, look: survey.facts?.look ?? null });
722
- if (scoped.length > 0) {
723
- // am17/am18: a pick follows its line's WORDS and its rule's exact words; one still matching is kept (not sent to the call, not asked, not counted), a changed or new rule is asked
724
- const matched = matchRecord(Array.isArray(carriedPicks) ? carriedPicks : [], jobLines, scoped);
725
- /** @type {ReturnType<typeof checkAsks>} */
726
- let asks = [];
727
- let sug = null;
728
- if (matched.askRules.length > 0) {
729
- onPhase('check-suggest', { rules: matched.askRules.length });
730
- sug = await runCheckSuggest({ jobLines, scoped: matched.askRules, generate: pickGenerate, ceilingUsd, onCall, priorCalls: survey?.calls ?? [], priorRaws: survey?.raws ?? [] });
731
- // the call's spend joins the survey's, so the ONE ceiling the later stages enforce already holds it
732
- survey.calls = [...(survey.calls ?? []), ...sug.calls];
733
- survey.raws = [...(survey.raws ?? []), ...sug.raws];
734
- asks = checkAsks(sug.rows);
735
- }
736
- const counted = asks.filter((a) => a.counted);
737
- if (lookAsks.length + counted.length > MAX_QUESTIONS) {
738
- return { ...base, interview, verdictType: picked, seedRef: seed, reds: [{ code: 'look-asks-too-many', path: 'jobLines', detail: tooManyAsksText([...lookAsks, ...counted]) }], stop: 'look-asks-too-many', cost: null };
739
- }
740
- /** @type {{picks?: any[], left?: {line: number, rule: number}[], jobLines: any[], answers: any}|null} */
741
- let updated = { jobLines, answers: interview.answers, picks: [], left: [] };
742
- if (asks.length > 0) {
743
- onPhase('check-ask', { questions: asks.length });
744
- updated = await answerQuestions({ questions: asks, dropped: [], confirmed: null });
709
+ // the note question: ONE call, only when a line is facts-only. The AI says yes/no per line; code decides (block.setNotes -> a `$` note row and a countable text part). A failed call leaves the line facts-only with a Not checked row.
710
+ survey.calls = [...(survey.calls ?? []), ...(await askNotes({ block, jobLines, noteFn, ceilingUsd, onCall, onPhase }))];
711
+ // a Revise keeps the last draft's Drop/Add choices (the suggestions exist now); code still judges every one when the list is reconciled
712
+ if (Array.isArray(carriedChoices)) { block.carryChoices(carriedChoices); onChoices(block.choicesRecord()); }
713
+ block.reconcile();
714
+ onPhase('ledger-built', { rows: ledgerRecord(/** @type {any} */ (block.rows)) });
715
+ // 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
716
+ // MAX_QUESTIONS counted asks is a job to rewrite, not a questionnaire: nothing is asked and the stop lists every ask.
717
+ if (answerQuestions) {
718
+ /** 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[]}} */
719
+ const answered = { picks: [], left: [] };
720
+ for (let round = 0; round < 3 && block.open.length > 0; round += 1) {
721
+ const asks = questionsOfBlock(block, pickGenerate ? scoped : []);
722
+ const counted = asks.filter((a) => a.counted);
723
+ if (counted.length > MAX_QUESTIONS) {
724
+ 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 };
725
+ }
726
+ // 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
727
+ const shown = asks.map((a) => ({ ...a, question: redactSecrets(a.question) }));
728
+ if (shown.length === 0) break;
729
+ onPhase(shown.every((a) => a.ask === 'check' || a.ask === 'no-check') ? 'check-ask' : 'look-ask', { questions: shown.length });
730
+ const updated = await answerQuestions({ questions: shown, dropped: [], confirmed: null });
745
731
  if (updated === null) return { ...base, interview, verdictType: picked, seedRef: seed, reds: [], stop: 'confirm-abandoned', cost: null };
746
732
  jobLines = updated.jobLines;
747
733
  interview.answers = updated.answers;
734
+ answered.picks.push(...(Array.isArray(updated.picks) ? updated.picks : []));
735
+ answered.left.push(...(Array.isArray(updated.left) ? updated.left : []));
736
+ const refused = applyChoices(block, Array.isArray(updated.choices) ? updated.choices : []);
737
+ // one rule in, one rule out (hamr 2026-11-14): the list replaced each answered rule, so the job text is rebuilt FROM the list (its one owner) and handed back to the seam that shows it
738
+ const rebuilt = block.jobLinesView(jobLines);
739
+ jobLines = rebuilt;
740
+ interview.answers = { ...interview.answers, 1: renderJobLines(rebuilt) };
741
+ if (typeof onJobLines === 'function') onJobLines(rebuilt);
742
+ if (refused.length === 0) break;
748
743
  }
749
- const newPicks = Array.isArray(updated.picks) ? updated.picks : [];
750
- const newLeft = Array.isArray(updated.left) ? updated.left : [];
751
- const keptPicks = matched.picks.map((p) => ({ ...p, kept: true }));
752
- const keptLeft = matched.left.map((l) => ({ ...l, kept: true }));
753
- const answeredLeft = newLeft.filter((l) => scoped.some((r) => r.line === l.line && r.rule === l.rule));
754
- // the record this draft hands on: the picks it kept, as they were, and the picks just answered, keyed by words
755
- onPicks({
756
- entries: [...matched.kept.map((k) => k.entry), ...entriesFromAnswers(jobLines, scoped, newPicks, answeredLeft)],
757
- kept: matched.kept.map((k) => ({ line: k.line, rule: k.rule, entry: k.entry })),
758
- });
759
- checkPicks = { rules: scoped, picks: [...keptPicks, ...newPicks], left: [...keptLeft, ...answeredLeft], rows: sug?.rows ?? [] };
760
- base.checkPicks = checkPicks;
761
- }
744
+ // 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
745
+ if (scoped.length > 0) {
746
+ // the record keeps the FINAL words of each rule (an answer replaced the rule it was asked about), numbered on this card
747
+ const finalRules = jobLines.flatMap((l) => (l.rules ?? []).map((t, i) => ({ line: l.n, rule: i + 1, text: t })));
748
+ onPicks({
749
+ entries: [...carried.kept.map((k) => k.entry), ...entriesFromAnswers(jobLines, finalRules, answered.picks, answered.left.filter((l) => scoped.some((r) => r.line === l.line && r.rule === l.rule)))],
750
+ kept: carried.kept.map((k) => ({ line: k.line, rule: k.rule, entry: k.entry })),
751
+ });
752
+ }
753
+ } else block.reconcile();
762
754
  }
763
755
 
764
756
  // ── THE CONFIRM TURN'S PAID HALF (PRD item 33 M3 piece 4) ──────────────────
@@ -804,8 +796,12 @@ export async function authorCloseForJob({
804
796
  verdictType: picked, answers: interview.answers, questions: questions ?? questionsFor(picked),
805
797
  facts: survey.facts, listing: null, writeScope, isRepo, lang, worseThanBefore, inputs, jobLines,
806
798
  ...(authorOpts?.ticket === true ? { ticket: true } : {}),
807
- ...(checkPicks ? { settled: checkPicks.rules } : {}),
808
799
  generate: confirmGenerate, book: confirmBook, ask, onPhase,
800
+ // the rows the block has built, read by the signed card's own readers (cardOfClose): the confirm card draws them under their lines
801
+ ...(block ? (() => {
802
+ const cardOf = () => cardOfClose({ closeDecl: block.closeView(), jobLines, ledger: block.rows.map((r) => ({ key: r.key, words: r.kind === 'rule' ? [r.text ?? ''] : (r.words ?? []) })) });
803
+ return { card: cardOf(), cardOf, block };
804
+ })() : {}),
809
805
  });
810
806
  // DISTINCT from `runConfirmTurn`'s own per-round 'confirm-done' (fired once
811
807
  // per round when a plan arrives) — this is the WRAPPER's own line, once,
@@ -858,7 +854,7 @@ export async function authorCloseForJob({
858
854
  // PART 1c: a rubric job asks nothing piecemeal on a failed try - it stops, and the person reviews the whole job (the one early
859
855
  // ask is about a `~` rule the look could not find, above)
860
856
  ...(answerQuestions && lang !== RUBRIC_LANG ? { offerQuestions: true } : {}),
861
- ...(checkPicks ? { checkPicks } : {}),
857
+ ...(block ? { block, editGenerate } : {}),
862
858
  ...authorOpts,
863
859
  });
864
860
  // P7 item 5: the drafter, on the last try after two failed ones, asked. The person answers (required, no skip); each
@@ -879,7 +875,7 @@ export async function authorCloseForJob({
879
875
  scout: survey, listing: seeds, generate, ceilingUsd, onPhase, onCall, writeScope,
880
876
  priorCalls: (authored.cost?.calls ?? []).slice(scoutCalls), priorRaws: (authored.raws ?? []).slice(scoutRaws),
881
877
  confirmed, jobLines, inputs,
882
- ...(checkPicks ? { checkPicks } : {}),
878
+ ...(block ? { block, editGenerate } : {}),
883
879
  ...authorOpts,
884
880
  offerQuestions: false,
885
881
  });
@@ -937,98 +933,14 @@ export async function authorCloseForJob({
937
933
  : {}),
938
934
  // 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)
939
935
  ...(authored.declaration.picks?.length ? { picks: structuredClone(authored.declaration.picks) } : {}),
936
+ // the one check list's final rows (no words), signed with the close: what each row ended as, and the part that carries it
937
+ ...(Array.isArray(authored.ledger) && authored.ledger.length ? { list: structuredClone(authored.ledger) } : {}),
940
938
  // the lines the always-on guards cover (names and numbers only, nothing free-text)
941
939
  ...(authored.declaration.guardLines?.length
942
940
  ? { guardLines: authored.declaration.guardLines.map((/** @type {any} */ g) => ({ guard: g.guard, lines: [...g.lines] })) }
943
941
  : {}),
944
942
  };
945
943
 
946
- // ── THE TWO SIGNED ARTIFACTS (softgreen module 4, wired here by module 5) ──
947
- //
948
- // A close that judges needs a rubric card and a calibration set, and until now
949
- // nothing in the pipeline called the compile — module 4 shipped the machinery
950
- // and said so. This is the call: Q6 and Q7 go to the compiler VERBATIM, the
951
- // proposal is SHOWN (`onPhase`, and the driver prints it), the SIGNER's fix is
952
- // what is stored, and both land inside the spec where the hash covers them.
953
- //
954
- // KEYED OFF THE DECLARATION, never off the picked class: a soft-green close
955
- // that composed no judged stage needs no card, and a judged stage is a judged
956
- // stage whatever the radio said. One judged stage is the composition law
957
- // (AT_MOST_ONCE_KINDS), so the fold's own throw is unreachable here — it stays
958
- // as the caller-error guard it is.
959
- /** @type {any} */
960
- let judged = null;
961
- if (closeJudges(closeDecl)) {
962
- // ONE CEILING, ALL THREE PAID SEAMS. The declaration loop's own calls are
963
- // ABSORBED before the compile is asked for, so the ceiling folds in prior
964
- // spend and re-invoking a seam cannot silently widen it. `absorb` deliberately
965
- // does not re-fire `onCall`, so nothing is reported twice.
966
- const book = makeCostBook({ ceilingUsd, onCall });
967
- book.absorb(authored.cost?.calls ?? []);
968
- onPhase('rubric', { size: CALIBRATION_SIZE });
969
- const proposed = await proposeFn({
970
- answers: stageAnswers,
971
- questions: questions ?? questionsFor(picked),
972
- generate,
973
- book,
974
- ...compileOpts,
975
- });
976
- onPhase('rubric-done', { ok: proposed.ok, stop: proposed.stop, attempts: proposed.attempts });
977
- if (!proposed.ok) {
978
- return {
979
- ...base,
980
- verdictType: picked, seedRef: seed, authoring: authored, judged: { proposal: proposed, signed: null },
981
- reds: proposed.reds, stop: proposed.stop, cost: book.report(), interview,
982
- };
983
- }
984
-
985
- // THE D5 MOMENT. `signerFix` is the seam a UI (or an operator's own editor)
986
- // hands the fixed artifacts back through; ABSENT is a legal answer and it is
987
- // recorded as one — `source: 'proposal'` says *nobody changed this*, which is
988
- // a different fact from *a person read it and changed nothing*.
989
- const fix = typeof signerFix === 'function' ? await signerFix(proposed.proposal) : signerFix;
990
- const signed = signJudgedArtifacts({ proposal: proposed.proposal, fix });
991
- judged = { proposal: proposed, signed, scrubbed: signed.scrubbed, source: signed.source };
992
- if (!signed.ok) {
993
- return {
994
- ...base,
995
- verdictType: picked, seedRef: seed, authoring: authored, judged,
996
- reds: signed.reds, stop: 'rubric-invalid', cost: book.report(), interview,
997
- };
998
- }
999
- // THE SCRUB, ANNOUNCED. A signer signs a hash over the STORED bytes, so bytes
1000
- // the ONE inventory masked on the way in are said out loud rather than left
1001
- // for them to notice — by PATH only, because echoing the matched string would
1002
- // be the same leak one hop on.
1003
- if (signed.scrubbed.length) onPhase('rubric-scrubbed', { paths: signed.scrubbed.map((s) => s.path) });
1004
- // `cases` is an array on every ok path — `validateCalibrationSet` reds a
1005
- // non-array before anything can be `ok` — and the narrowing is stated rather
1006
- // than defaulted: `?? []` here would fold an EMPTY signed set into a close,
1007
- // which is the one direction that must never be reachable.
1008
- if (typeof judgeModel !== 'string' || judgeModel.trim() === '') {
1009
- throw new Error('[authorjob] authorCloseForJob composed a JUDGED close and was given no judgeModel (PRD item '
1010
- + '32.1). The stored calibration set carries the judge that certified it, and a set stamped with a model '
1011
- + 'nobody named is exactly the unattributable floor that field exists to prevent.');
1012
- }
1013
- closeDecl = foldJudgedArtifacts(closeDecl, {
1014
- card: signed.card, cases: /** @type {any[]} */ (signed.cases), judgeModel,
1015
- });
1016
- return {
1017
- ok: true,
1018
- refusal: null,
1019
- verdictType: picked,
1020
- closeDecl,
1021
- seedRef: seed,
1022
- authoring: authored,
1023
- judged,
1024
- reds: authored.reds,
1025
- stop: authored.stop,
1026
- cost: book.report(),
1027
- interview,
1028
- confirmed,
1029
- };
1030
- }
1031
-
1032
944
  return {
1033
945
  ok: true,
1034
946
  refusal: null,
@@ -1036,8 +948,11 @@ export async function authorCloseForJob({
1036
948
  closeDecl,
1037
949
  seedRef: seed,
1038
950
  authoring: authored,
1039
- judged,
1040
- ...(checkPicks ? { checkPicks } : {}),
951
+ // the checks the person picked, for the plan card's "You picked" rows (read from the block's rows)
952
+ ...(block ? { hasBuiltCheck: block.hasBuiltCheck() } : {}),
953
+ // the suggestions code could not build, one plain sentence each: the Audit's draft lines, never the card (hamr 2026-11-13, F-b)
954
+ ...(block ? { notBuilt: block.unbuiltSuggestions() } : {}),
955
+ ...(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}` : ''}` })) } : {}),
1041
956
  reds: authored.reds,
1042
957
  stop: authored.stop,
1043
958
  cost: authored.cost,
@@ -1182,184 +1097,6 @@ const scrubRed = (r) => /** @type {any} */ (Object.fromEntries(
1182
1097
  Object.entries(r).map(([k, v]) => [k, typeof v === 'string' ? redactSecrets(v) : v]),
1183
1098
  ));
1184
1099
 
1185
- /**
1186
- * THE one spelling of "a passed calibration gate stands in for the seed red": the
1187
- * close carries a judged stage AND the gate ran and passed. A failed or missing
1188
- * calibration never satisfies it, and a close with no judged stage never reaches it.
1189
- * @param {any[]} judged `judgedStages(closeDecl)` @param {any} calibration `gates.calibration`
1190
- * @returns {boolean}
1191
- */
1192
- export function seedProofIsCalibration(judged, calibration) {
1193
- return judged.length > 0 && calibration?.ok === true;
1194
- }
1195
-
1196
- /**
1197
- * GATE 4 — the calibration gate, and the only gate here that spends money.
1198
- *
1199
- * It answers ONE question: has this close's own ruler been shown to grade the
1200
- * signer's own ten correctly, itemized, and to resist all five attack styles?
1201
- * Anything else it learns — a missing set, an unwired judge, a dead call — is
1202
- * reported under its own name and refuses, because every one of them leaves the
1203
- * question unanswered and an unanswered calibration is not a passed one.
1204
- *
1205
- * THE CASUALTY SPLIT is the same one the judged stage runs (F45, contract (a)): a
1206
- * provider failure, an unpriced call or an unparseable emission after the ladder
1207
- * says NOTHING about the set. It refuses the signature — an ungraded ruler is
1208
- * still ungraded — but it refuses under the TRANSPORT's name, so the operator is
1209
- * sent to the socket or the meter and never to their own rubric.
1210
- * AND IT MEETS THE ONE CEILING. This is the run's THIRD paid seam — the largest of
1211
- * them, at up to `CALIBRATION_SIZE` locate calls plus a five-artifact battery, each
1212
- * under its own retry ladder — and it used to run with no bound at all while the
1213
- * scout and the declaration loop were both stopped by the operator's own number.
1214
- * That is the advertised budget and the enforced budget being two different numbers.
1215
- * The book is built HERE and PRIOR SPEND IS ABSORBED into it, so the ceiling folds in
1216
- * what the earlier seams already spent and re-invoking a seam cannot silently widen
1217
- * it; the gate reads it between calls and stops as a refusal that names money.
1218
- * `judgeModel` is the RESOLVED judge identity (PRD item 32.1), required and with no
1219
- * default: it is stamped onto the graded set and onto the calibration-missing record
1220
- * alike, so both say which judge the close would have been certified by.
1221
- * @param {{spec: any, judgedStages: any[], judgeLoop: Function|null, judgeModel: string,
1222
- * onJudgeCost: ((c: any) => void)|null, calibrateFn: Function,
1223
- * ceilingUsd: number|null, priorCalls: any[]}} o
1224
- * @returns {Promise<{ok: boolean, record: any, reds: Red[], refusal: Refusal|null}>}
1225
- */
1226
- async function calibrationGate({ spec, judgedStages, judgeLoop, judgeModel, onJudgeCost, calibrateFn, ceilingUsd, priorCalls }) {
1227
- const cases = spec.closeDecl?.calibration?.cases ?? null;
1228
- // ONE card, and it is the SIGNED one — the card the calibration is graded
1229
- // against must be the card the close will RUN, or the gate certifies a ruler
1230
- // nobody is going to use. `validateCloseDecl` has already refused a second
1231
- // judged stage (AT_MOST_ONCE_KINDS), so there is exactly one here.
1232
- const card = judgedStages[0]?.params?.card ?? null;
1233
-
1234
- if (cases === null || cases === undefined) {
1235
- const detail = `This close judges with a rubric card, and no calibration set is stored with it. The judged floor `
1236
- + `is only a floor once the whole pipe has graded ${CALIBRATION_SIZE} signed cases correctly — until then the `
1237
- + 'ruler is unmeasured, and an unmeasured ruler cannot be signed.';
1238
- return {
1239
- ok: false,
1240
- record: { ok: false, stop: 'calibration-missing', judgeModel, required: CALIBRATION_SIZE },
1241
- reds: [{ code: 'calibration-missing', path: 'closeDecl.calibration.cases', detail }],
1242
- refusal: refuse({
1243
- kind: 'decision-ready',
1244
- verb: null,
1245
- path: 'closeDecl.calibration',
1246
- detail,
1247
- options: [
1248
- `author the calibration set from the interview's own Q7 answer (${CALIBRATION_SIZE} cases, mixed polarity) and re-sign`,
1249
- 'drop the judged stage and describe a job whose done is machine-checkable',
1250
- 'abandon the job',
1251
- ],
1252
- }),
1253
- };
1254
- }
1255
-
1256
- // ONE CEILING, ALL THE PAID SEAMS (`authorCloseForJob` says the same words over
1257
- // the compile). The book absorbs what the run has already spent, so what the gate
1258
- // reads is the REMAINING balance and never a fresh allowance; `absorb` deliberately
1259
- // does not re-fire a reporter, so nothing is counted twice downstream.
1260
- const book = makeCostBook({ ceilingUsd });
1261
- book.absorb(Array.isArray(priorCalls) ? priorCalls : []);
1262
- const cal = await calibrateFn({
1263
- cases,
1264
- card,
1265
- judgeLoop,
1266
- judgeModel,
1267
- // the gate's own calls join the same tally the ceiling is read against — a
1268
- // ceiling that cannot see the spend it bounds is F45's blind detector in a
1269
- // money coat. The caller's reporter fires with the call's whole record, after.
1270
- onCost: (/** @type {any} */ c) => {
1271
- book.absorb([{ label: c?.label ?? 'calibrate', costUsd: c?.costUsd ?? null, unpricedRounds: c?.unpricedRounds ?? 0 }]);
1272
- if (typeof onJudgeCost === 'function') onJudgeCost(c);
1273
- },
1274
- capStop: () => book.capStop(),
1275
- });
1276
-
1277
- /** what the signing evidence KEEPS about this gate. The per-case artifacts are
1278
- * deliberately not in it — they are already in the signed spec, and a second
1279
- * copy in the evidence file is a second thing to keep in step. Each graded row's
1280
- * `diag` (F192) keeps the judge's own facts and the decision's reds — scrubbed
1281
- * and bounded quotes, never an artifact body — so a refusal reads from its own
1282
- * record. What IS kept is
1283
- * WHICH BYTES were certified (`cardHash`/`casesHash`/`setHash`) and BY WHICH
1284
- * MODEL (`judgeModel`), which is what makes a judge-model bump detectable at
1285
- * all. */
1286
- const record = {
1287
- ok: cal.ok,
1288
- stop: cal.stop,
1289
- judgeModel: cal.judgeModel,
1290
- cardHash: cal.cardHash,
1291
- casesHash: cal.casesHash,
1292
- setHash: cal.setHash,
1293
- graded: cal.graded,
1294
- failures: cal.failures,
1295
- injection: cal.injection,
1296
- casualty: cal.casualty,
1297
- costUsd: cal.costUsd,
1298
- knownUsd: cal.knownUsd,
1299
- spendComplete: cal.spendComplete,
1300
- calls: cal.calls?.length ?? 0,
1301
- };
1302
- if (cal.ok) return { ok: true, record, reds: [], refusal: null };
1303
-
1304
- const reds = cal.reds.map(scrubRed);
1305
- const casualty = cal.casualty !== null && cal.casualty !== undefined;
1306
- /** the OPERATOR's own governance stop, and it is neither a casualty nor a reading
1307
- * of the close: the ceiling ran out mid-question, and what was graded before it
1308
- * did says nothing either way about the rest of the set. */
1309
- const budget = cal.stop === 'cap-halt' || cal.stop === 'pricing-red';
1310
- const detail = budget
1311
- ? (cal.stop === 'cap-halt'
1312
- ? `The calibration gate ran out of CEILING before it could finish: ${cal.graded.length} of `
1313
- + `${Array.isArray(cases) ? cases.length : 0} case(s) were graded and the next call was never made. A `
1314
- + 'part-graded set is an ungraded ruler, so nothing is signable — and nothing here says the ruler is wrong.'
1315
- : 'The calibration gate stopped on an UNPRICED call: with the run\'s total unknown the ceiling cannot be read '
1316
- + 'against it, and unpriced is never free (F6). Nothing here says anything about the set.')
1317
- : casualty
1318
- ? `The calibration gate could not be RUN: the judge produced no usable facts for ${cal.casualty.kind} `
1319
- + `"${cal.casualty.at}" [${cal.casualty.axis}]. A broken judge is a casualty and never a verdict, so this says `
1320
- + 'nothing about the set — but an ungraded ruler is still an ungraded ruler, and it cannot be signed.'
1321
- : cal.stop === 'no-judge'
1322
- ? `This close carries a judged stage and no judge seam was wired, so the ${CALIBRATION_SIZE}-case gate never ran. `
1323
- + 'An absent seam is a wiring gap, never a fall-back: a gate that grades nothing would certify every close.'
1324
- : cal.stop === 'invalid-set'
1325
- ? 'The stored rubric card and calibration set do not compose into something gradeable, so the gate refused '
1326
- + 'before spending anything.'
1327
- : `The whole pipe did not grade this close's own calibration set correctly: `
1328
- + `${cal.failures.length} of ${Array.isArray(cases) ? cases.length : 0} case(s) graded wrong`
1329
- + `${cal.injection.leaks.length ? ` and ${cal.injection.leaks.length} injection style(s) leaked` : ''}. `
1330
- + `The floor is ${CALIBRATION_SIZE}/${CALIBRATION_SIZE} with itemized reds and all styles resisting `
1331
- + '(hamr, 2026-08-18) — the fix for a miss is a new card line or a corrected case, and a re-sign.';
1332
-
1333
- return {
1334
- ok: false,
1335
- record,
1336
- reds,
1337
- refusal: refuse({
1338
- kind: 'decision-ready',
1339
- verb: null,
1340
- path: 'closeDecl.calibration',
1341
- detail,
1342
- options: budget
1343
- ? [
1344
- 'raise the authoring ceiling and re-run the gate — the $0 gates above are already passed',
1345
- 'run the gate unbounded (omit the ceiling) — that is a stated operator choice, never a default',
1346
- 'abandon the job',
1347
- ]
1348
- : casualty || cal.stop === 'no-judge'
1349
- ? [
1350
- 'wire a judge provider pinned to the judged tier and re-run the gate',
1351
- 'wait out the provider and re-run — nothing about the close was judged here',
1352
- 'abandon the job',
1353
- ]
1354
- : [
1355
- 'correct the card line or the case the pipe graded differently, and re-sign',
1356
- 'read the itemized rows above: a case the pipe reds for the WRONG reason is the card talking, not the judge',
1357
- 'abandon the job',
1358
- ],
1359
- }),
1360
- };
1361
- }
1362
-
1363
1100
  /**
1364
1101
  * D9, in code: *nothing JUDGES the close; three mechanical gates plus a
1365
1102
  * signature.* No LLM validates another LLM's close, here or anywhere.
@@ -1373,23 +1110,7 @@ async function calibrationGate({ spec, judgedStages, judgeLoop, judgeModel, onJu
1373
1110
  * A close with NO work stage red at seed has nothing to do and is refused
1374
1111
  * decision-ready — gate-2 round 2's arm B died exactly there, on a mypy that
1375
1112
  * scanned nothing and therefore read clean.
1376
- * 4. THE CALIBRATION GATE (softgreen module 5) — for a close carrying a
1377
- * `judged-floor` stage ONLY. The whole judged pipe runs over the signed ten
1378
- * and the five arbiter-owned injection artifacts, and anything short of
1379
- * 10/10 with itemized reds and 5/5 resisted is an unsignable close. It is
1380
- * the ONE gate here that spends money, so it runs LAST — every free refusal
1381
- * has already had its chance, and nobody pays to discover a broken
1382
- * declaration.
1383
- *
1384
- * D9.3 AND THE JUDGED CLOSE (2026-08-18 second addendum, ruling 3; hamr: *"fix it now,
1385
- * we are delivering softgreen, isn't that the whole point?"*; widened 2026-10-09 to mixed
1386
- * closes, hamr: *"a rubric job should check if judge can judge (calibration) and judge
1387
- * rules can apply properly to pass ... we can't close everything upfront"*). Gate 3
1388
- * protects against a close that cannot fail. A judged stage SKIPS the seed read by ruling
1389
- * 8, so it can never show red there. For ANY close carrying a judged stage (pure or
1390
- * mixed with mechanical stages), a PASSED calibration gate plays the seed-red role
1391
- * (`seedProofIsCalibration`). A close with NO judged stage is UNCHANGED: some work stage
1392
- * must be red at the seed. A failed or missing calibration never satisfies it.
1113
+ * (There was a fourth, paid gate, the calibration gate of the old judge; it is gone with the old judge, 2026-11-14.)
1393
1114
  *
1394
1115
  * Gates 2 and 3 share ONE execution, and that is stated rather than hidden: at
1395
1116
  * job creation the tree IS the seed, so "does every stage run against the real
@@ -1402,35 +1123,18 @@ async function calibrationGate({ spec, judgedStages, judgeLoop, judgeModel, onJu
1402
1123
  * comes back is the resolved spec, its hash, and the evidence to sign against.
1403
1124
  *
1404
1125
  * @param {{spec: any, workdir: string, seedRef?: string|null, shellCapUsd?: number,
1405
- * timeoutMs?: number, seedFn?: Function, listingFn?: Function, seedReadFn?: Function,
1406
- * judgeLoop?: Function|null, judgeModel?: string|null, onJudgeCost?: ((c: any) => void)|null,
1407
- * calibrateFn?: Function, ceilingUsd?: number|null, priorCalls?: any[]}} o
1126
+ * timeoutMs?: number, seedFn?: Function, listingFn?: Function, seedReadFn?: Function}} o
1408
1127
  * @returns {Promise<{ok: boolean, specHash: string|null, seedRef: string|null,
1409
1128
  * gates: any, work: any[], guards: any[], stops: any[], reds: Red[], refusal: Refusal|null}>}
1410
1129
  */
1411
1130
  export async function prepareSigning({
1412
1131
  spec, workdir, seedRef = null, shellCapUsd, timeoutMs,
1413
1132
  seedFn = seedAtHead, listingFn = seedListing, seedReadFn = runSeedRead,
1414
- // THE PAID SEAM, and it is the operator's to wire — this module owns no
1415
- // provider and picks none (the same contract `authorCloseForJob` keeps for the
1416
- // drafting model). Absent is never a fall-back: a judged close whose gate could
1417
- // not run is refused, not waved through. `judgeModel` is the seam's other half
1418
- // (PRD item 32.1) — WHICH model that loop drives, resolved by the caller
1419
- // (`resolveJudge`, src/judged.js). The two travel together: a gate that grades
1420
- // without recording its judge certifies a floor nobody can attribute.
1421
- judgeLoop = null, judgeModel = null, onJudgeCost = null, calibrateFn = runCalibration,
1422
- // THE OPERATOR'S CEILING, and the spend it has already met. `null`/absent is
1423
- // UNBOUNDED and is a stated choice, never a default invented here (the same
1424
- // contract `authorCloseForJob` keeps). `priorCalls` is what the earlier paid
1425
- // seams of this run already cost — a `makeCostBook().report().calls` list — and
1426
- // it is ABSORBED so the gate reads the remaining balance rather than opening a
1427
- // fresh allowance under the same number.
1428
- ceilingUsd = null, priorCalls = [],
1429
1133
  }) {
1430
1134
  /** @type {any} */
1431
1135
  const base = {
1432
1136
  ok: false, specHash: null, seedRef: null, work: [], guards: [], stops: [], reds: [], refusal: null,
1433
- gates: { declaration: null, precheck: null, seedVerdict: null, calibration: null },
1137
+ gates: { declaration: null, precheck: null, seedVerdict: null },
1434
1138
  };
1435
1139
 
1436
1140
  // ── gate 1a: the spec itself. A declared close that is not on a plan-shape
@@ -1485,7 +1189,7 @@ export async function prepareSigning({
1485
1189
  }
1486
1190
  // the class rides from the SPEC (PRD v1.57 §2) — gate 1a already refused a spec
1487
1191
  // whose class is unknown or locked, so this is the class D5's battery hangs off
1488
- const dv = validateCloseDecl(spec.closeDecl, { at: 'closeDecl', listing: listed.files, verdictType: spec.verdictType, writeScope: spec.writeScope, jobLines: Array.isArray(spec.jobLines) ? spec.jobLines : null, inputLabels: inputLabelsOf(spec.inputs) });
1192
+ const dv = validateCloseDecl(spec.closeDecl, { at: 'closeDecl', listing: listed.files, verdictType: spec.verdictType, jobLines: Array.isArray(spec.jobLines) ? spec.jobLines : null, inputLabels: inputLabelsOf(spec.inputs) });
1489
1193
  // the grounded gate's reds quote BOTH untrusted sources — the declaration, and
1490
1194
  // the seed listing itself (the listing rule names what really sits beside an
1491
1195
  // invented path). The listing half is a channel gate 1a structurally cannot
@@ -1533,7 +1237,7 @@ export async function prepareSigning({
1533
1237
  };
1534
1238
  if (stops.length) {
1535
1239
  // M2: a rubric job's readout never uses the code-job wording ("install, build and test commands")
1536
- const rubricJob = (Array.isArray(spec.closeDecl?.stages) ? spec.closeDecl.stages : []).some((/** @type {any} */ st) => st && (st.kind === 'rubric-step' || st.kind === 'judged-floor'));
1240
+ const rubricJob = (Array.isArray(spec.closeDecl?.stages) ? spec.closeDecl.stages : []).some((/** @type {any} */ st) => st && st.kind === 'rubric-step');
1537
1241
  const reds = stops.map((s) => ({
1538
1242
  code: 'broken-close',
1539
1243
  ...(rubricJob ? { rubricJob: true } : {}),
@@ -1569,49 +1273,12 @@ export async function prepareSigning({
1569
1273
  workRed: workRed.map((r) => r.stage),
1570
1274
  };
1571
1275
 
1572
- // ── gate 4: THE CALIBRATION GATE (softgreen module 5). The ONLY paid gate, and
1573
- // it runs LAST for exactly that reason: every $0 refusal above has already had
1574
- // its chance, so a broken declaration or a stage that cannot run is found for
1575
- // free. MANDATORY for any close carrying a judged-floor stage — module 4's
1576
- // validator checks a stored set for LEGALITY only and deliberately allows a
1577
- // judged stage with no set at all, because making it mandatory is a signing
1578
- // decision and this is the signing gate.
1579
- const judged = judgedStages(spec.closeDecl);
1580
- if (judged.length) {
1581
- if (judgeLoop !== null && (typeof judgeModel !== 'string' || judgeModel.trim() === '')) {
1582
- throw new Error('[authorjob] prepareSigning was wired a judgeLoop with no judgeModel (PRD item 32.1). The two '
1583
- + 'halves of the judge seam travel together: the graded set is stamped with the judge that certified it, and '
1584
- + 'there is no library pin to fall back to.');
1585
- }
1586
- const cal = await calibrationGate({
1587
- spec, judgedStages: judged, judgeLoop, judgeModel: /** @type {string} */ (judgeModel),
1588
- onJudgeCost, calibrateFn, ceilingUsd, priorCalls,
1589
- });
1590
- base.gates.calibration = cal.record;
1591
- if (!cal.ok) return { ...base, work, guards, reds: cal.reds, refusal: cal.refusal };
1592
- }
1593
-
1594
1276
  // D9.3 — nothing red at seed means nothing to do. Round 2's arm B read GREEN
1595
1277
  // with value 0 because mypy died on an unrelated broken fixture and scanned
1596
1278
  // nothing: an instrument scanning nothing reads clean, which is F6's shape at
1597
1279
  // the close-authoring layer, and this gate is what refuses it BEFORE a
1598
1280
  // signature rather than after a paid run.
1599
- //
1600
- // THE JUDGED ROUTE (ruling 3, widened 2026-10-09 by hamr: "a rubric job should
1601
- // check if judge can judge (calibration) and judge rules can apply properly to
1602
- // pass ... we can't close everything upfront"). A close carrying ANY judged stage
1603
- // has a work-bearing stage that ruling 8 exempts from the seed read, so the seed
1604
- // cannot show it red — not because it measures nothing, but because it is not
1605
- // measured there. Its proof of failability is the calibration gate, which has
1606
- // just run and passed (a failed one returned above), and which contains signed
1607
- // cases the pipe must RED as well as ones it must pass. That holds for a PURE
1608
- // judged close and a MIXED one alike; a close with NO judged stage takes the
1609
- // original path unchanged (some work stage must be red at the seed).
1610
- if (workRed.length === 0 && seedProofIsCalibration(judged, base.gates.calibration)) {
1611
- // said out loud in the record: this close passed gate 3 on a DIFFERENT proof,
1612
- // and a reader must never have to infer which one from an empty workRed list
1613
- base.gates.seedVerdict.satisfiedBy = 'calibration';
1614
- } else if (!workRed.length) {
1281
+ if (!workRed.length) {
1615
1282
  return {
1616
1283
  ...base,
1617
1284
  work,