fwdloop 0.38.0 → 0.39.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 (127) hide show
  1. package/bin/fwdloop +21 -19
  2. package/package.json +1 -1
  3. package/src/ask.js +70 -148
  4. package/src/audit-fold.js +5 -4
  5. package/src/auditchecks.js +6 -4
  6. package/src/authoring.js +32 -60
  7. package/src/blockasks.js +2 -1
  8. package/src/blockassemble.js +3 -2
  9. package/src/blockdraft.js +2 -2
  10. package/src/blockpick.js +5 -5
  11. package/src/books.js +217 -12
  12. package/src/checkblock.js +20 -41
  13. package/src/checklistsign.js +25 -3
  14. package/src/checklook.js +3 -1
  15. package/src/checkpick.js +5 -76
  16. package/src/cited-source.js +4 -4
  17. package/src/citedcheck.js +6 -11
  18. package/src/citedwords.js +9 -8
  19. package/src/closers.js +9 -6
  20. package/src/declaration.js +14 -49
  21. package/src/diary.js +23 -1
  22. package/src/draft-steps.js +11 -1
  23. package/src/drafter.js +13 -9
  24. package/src/draftfiles.js +127 -0
  25. package/src/draftspend.js +165 -17
  26. package/src/flow.js +42 -87
  27. package/src/flowmodel.js +1 -1
  28. package/src/index.js +3 -2
  29. package/src/inside.js +86 -0
  30. package/src/jsonl-append.js +33 -1
  31. package/src/learn.js +1 -1
  32. package/src/learnstore.js +20 -22
  33. package/src/line-checks.js +1 -1
  34. package/src/liveness.js +3 -0
  35. package/src/mcp-use.js +8 -9
  36. package/src/memo.js +13 -16
  37. package/src/model-step.js +2 -2
  38. package/src/page-words.js +8 -0
  39. package/src/pageask.js +8 -3
  40. package/src/pagebits.js +8 -1
  41. package/src/pagedropwords.js +1 -1
  42. package/src/pagerules.js +6 -3
  43. package/src/panel/author.js +99 -75
  44. package/src/panel/authorcard.js +21 -8
  45. package/src/panel/authorflows.js +3 -3
  46. package/src/panel/authorresume.js +3 -3
  47. package/src/panel/authorstart.js +15 -16
  48. package/src/panel/authortrigger.js +43 -70
  49. package/src/panel/data.js +125 -168
  50. package/src/panel/index.html +122 -61
  51. package/src/panel/jobgrid.js +3 -7
  52. package/src/panel/result.js +7 -10
  53. package/src/panel/resume.js +4 -3
  54. package/src/panel/scheduler.js +9 -9
  55. package/src/panel/server.js +8 -4
  56. package/src/panel/spawn.js +22 -11
  57. package/src/panel/tickets.js +2 -2
  58. package/src/pickrecord.js +51 -31
  59. package/src/placerule.js +3 -4
  60. package/src/planrebuild.js +19 -19
  61. package/src/primitives.js +1 -1
  62. package/src/provider.js +1 -1
  63. package/src/reasons.js +25 -0
  64. package/src/runfile.js +26 -2
  65. package/src/runner.js +57 -105
  66. package/src/runvalues.js +47 -24
  67. package/src/schedule-choices.js +41 -0
  68. package/src/schedule-shape.js +39 -0
  69. package/src/schedule.js +9 -8
  70. package/src/setup.js +20 -36
  71. package/src/shaperows.js +2 -2
  72. package/src/sheetblock.js +2 -2
  73. package/src/sheetbuild.js +5 -5
  74. package/src/sheetrun.js +4 -5
  75. package/src/summary-words.js +2 -1
  76. package/src/thinking.js +5 -2
  77. package/src/ticketrows.js +7 -28
  78. package/src/trigger-clock.js +9 -23
  79. package/src/trigger-files.js +30 -22
  80. package/src/trigger-tickets.js +15 -14
  81. package/src/try-checks.js +2 -1
  82. package/src/types.js +2 -0
  83. package/types/ask.d.ts +25 -20
  84. package/types/authoring.d.ts +7 -42
  85. package/types/blockpick.d.ts +1 -1
  86. package/types/books.d.ts +256 -4
  87. package/types/checkblock.d.ts +1 -23
  88. package/types/checklist.d.ts +3 -3
  89. package/types/checklistsign.d.ts +7 -0
  90. package/types/checkpick.d.ts +0 -21
  91. package/types/citedwords.d.ts +7 -4
  92. package/types/closers.d.ts +1 -0
  93. package/types/declaration.d.ts +4 -14
  94. package/types/diary.d.ts +14 -1
  95. package/types/draft-steps.d.ts +7 -0
  96. package/types/drafter.d.ts +1 -1
  97. package/types/draftfiles.d.ts +89 -0
  98. package/types/draftspend.d.ts +74 -0
  99. package/types/flow.d.ts +32 -54
  100. package/types/index.d.ts +3 -3
  101. package/types/inside.d.ts +58 -0
  102. package/types/jsonl-append.d.ts +20 -0
  103. package/types/learnstore.d.ts +0 -2
  104. package/types/liveness.d.ts +1 -0
  105. package/types/page-words.d.ts +6 -0
  106. package/types/pageask.d.ts +2 -0
  107. package/types/pagebits.d.ts +3 -0
  108. package/types/pagerules.d.ts +1 -0
  109. package/types/panel/author.d.ts +7 -3
  110. package/types/panel/authorcard.d.ts +0 -6
  111. package/types/panel/authorflows.d.ts +4 -4
  112. package/types/panel/authortrigger.d.ts +16 -2
  113. package/types/panel/data.d.ts +36 -11
  114. package/types/panel/spawn.d.ts +18 -2
  115. package/types/pickrecord.d.ts +29 -0
  116. package/types/reasons.d.ts +23 -0
  117. package/types/runfile.d.ts +14 -0
  118. package/types/runner.d.ts +6 -38
  119. package/types/runvalues.d.ts +17 -2
  120. package/types/schedule-choices.d.ts +9 -0
  121. package/types/schedule-shape.d.ts +15 -0
  122. package/types/sheetbuild.d.ts +1 -1
  123. package/types/thinking.d.ts +1 -0
  124. package/types/ticketrows.d.ts +0 -9
  125. package/types/trigger-clock.d.ts +3 -2
  126. package/types/trigger-files.d.ts +15 -4
  127. package/types/types.d.ts +8 -0
@@ -46,7 +46,8 @@ import { lineRules } from './pagebits.js';
46
46
  import { OFFERED as OFFERED_RULES } from './checkwords.js';
47
47
  import { isColumnChoiceRule } from './sheetoffer.js';
48
48
  import { checkListReds } from './checklistsign.js';
49
- import { ticketListReds } from './ticketrows.js';
49
+ import { ticketListReds } from './checklistsign.js';
50
+ import { guardrailWordNumbers, guardrailWordsPerSection, guardrailSectionCount } from './blockpick.js';
50
51
 
51
52
  /** @typedef {import('./types.js').Arbiter} Arbiter */
52
53
  /** @typedef {import('./types.js').SignedLine} SignedLine */
@@ -104,13 +105,16 @@ const CLOSE_ALLOWED = Object.freeze(['class', 'shape', 'cited', 'columns', 'shee
104
105
  /** M13 piece 4 (signed item 4): the job's flow type, set by code from the job card, signed with the job. */
105
106
  export const FLOW_TYPES = Object.freeze(['plain', 'mcp', 'tickets']);
106
107
 
108
+ /** M20 am8: the one question "is this a flow type" (plain, mcp or tickets): the card doors, the CLI and the schedule choices ask it @param {unknown} t @returns {boolean} */
109
+ export const isFlowType = (t) => typeof t === 'string' && FLOW_TYPES.includes(t);
110
+
107
111
  /**
108
112
  * M13 piece 4: the ONE reader of a job's flow type. The field when present; a job signed before it existed (M12 shape: an `mcp` block, no `flowType`) is a Tickets
109
113
  * job, since M12 only had ticket jobs; no `mcp` block is plain.
110
114
  * @param {Record<string, any>} declaration @returns {'plain'|'mcp'|'tickets'}
111
115
  */
112
116
  export function flowTypeOf(declaration) {
113
- if (typeof declaration?.flowType === 'string' && FLOW_TYPES.includes(declaration.flowType)) return /** @type {any} */ (declaration.flowType);
117
+ if (isFlowType(declaration?.flowType)) return /** @type {any} */ (declaration.flowType);
114
118
  return declaration?.mcp ? 'tickets' : 'plain';
115
119
  }
116
120
 
@@ -119,7 +123,7 @@ export function flowTypeOf(declaration) {
119
123
  function checkFlowType(declaration, reds) {
120
124
  if (!Object.hasOwn(declaration, 'flowType')) return;
121
125
  const t = declaration.flowType;
122
- if (typeof t !== 'string' || !FLOW_TYPES.includes(t)) { reds.push('declaration: flowType must be plain, mcp or tickets'); return; }
126
+ if (!isFlowType(t)) { reds.push('declaration: flowType must be plain, mcp or tickets'); return; }
123
127
  const hasMcp = Object.hasOwn(declaration, 'mcp');
124
128
  if (t === 'plain' && hasMcp) reds.push('declaration: flowType "plain" takes no "mcp" server');
125
129
  if (t !== 'plain' && !hasMcp) reds.push(`declaration: flowType "${t}" needs an "mcp" server`);
@@ -379,24 +383,6 @@ function deriveFromLine(fromLine, lines, guardrailClasses, added = new Set()) {
379
383
  return { ok: true, class: resolved.class, line };
380
384
  }
381
385
 
382
- /** M4e amendment 16 C14: a guardrail number, with or without thousands separators ("1,000" -> 1000). Commas must group by exactly three
383
- * ("1,00" and "1,0000" match nothing), and the number cannot start in the middle of another one. */
384
- const readNumber = (t) => Number(t.replace(/,/g, ''));
385
-
386
- /** Every whole-output word number in a guardrail ("3 sections, under 600 words, each heading at most 3 words" -> [600, 3]), in order; [] when
387
- * there is none. Code does not decide which one is the limit: the AI picks `maxWords` and the validator checks the pick is one of these
388
- * (M4e amendments 28 + 29). A "<n> words each" / "<n> words per section" is the per-section size (amendment 15), never listed here. */
389
- export function guardrailWordNumbers(guardrail) {
390
- if (typeof guardrail !== 'string') return [];
391
- return [...guardrail.matchAll(/(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)\s*words?\b(?!\s*(?:each|per\s+section)\b)/gi)].map((m) => readNumber(m[1]));
392
- }
393
-
394
- /** M10 amendment 14 item 2: every standalone number in a guardrail's own text (digits not joined to letters: "P1" and "250ish" are not one; "1,000" and "2.5" are one number each). */
395
- export function guardrailStandaloneNumbers(guardrail) {
396
- if (typeof guardrail !== 'string') return [];
397
- return [...guardrail.matchAll(/(?<![A-Za-z0-9_.,])(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)(?![A-Za-z0-9_])/g)].map((m) => Number(m[1].replace(/,/g, '')));
398
- }
399
-
400
386
  /** M10 amendment 14 item 1: the send line (a signed send) is where the accepted result is written out and no AI runs, so a guardrail under it is refused at $0, naming the line.
401
387
  * Pure; the card (src/panel/authorcard.js checkCard) and the drafter's pre-flight both call it. @param {any[]} lines `parseSignedText`'s lines @param {{sends?: {line: number}[]}} arbiter */
402
388
  export function checkSendLineGuardrail(lines, arbiter) {
@@ -410,29 +396,8 @@ export function checkSendLineGuardrail(lines, arbiter) {
410
396
  return reds;
411
397
  }
412
398
 
413
- /** M4e amendment 15 item 1: the "<n> words each" / "<n> words per section" size in a guardrail ("about 250 words each", "250ish each" -> 250), or null. */
414
- export function guardrailWordsPerSection(guardrail) {
415
- const m = typeof guardrail === 'string' ? /(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)(?:\s*words?|ish(?:\s+words?)?)\s+(?:each|per\s+section)\b/i.exec(guardrail) : null;
416
- return m ? readNumber(m[1]) : null;
417
- }
418
-
419
- const NUMBER_WORDS = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 };
420
- /** M4e amendment 7 item 1: the first "<N> sections" in a guardrail (N digits, or the words one..ten), or null. */
421
- export function guardrailSectionCount(guardrail) {
422
- const m = typeof guardrail === 'string' ? /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?sections?\b/i.exec(guardrail) : null;
423
- if (!m) return null;
424
- return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
425
- }
426
-
427
- /** M10 amendment 23: the first "<N> bullets / list items / items / lines / points" in a guardrail (N digits, or the words one..ten; not a price like "$5 per item"), or null. */
428
- export function guardrailItemCount(guardrail) {
429
- const m = typeof guardrail === 'string' ? /(?<![$€£\d.,])\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?(?:bullets?|list items?|items?|lines?|points?)\b/i.exec(guardrail) : null;
430
- if (!m) return null;
431
- return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
432
- }
433
-
434
- /** M10 amendment 23: the ONE place that says a guardrail is a count code can check: N words, N bullets / list items / items / lines / points, or N sections. */
435
- export const isCountGuardrail = (guardrail) => guardrailWordNumbers(guardrail).length > 0 || guardrailItemCount(guardrail) !== null || guardrailSectionCount(guardrail) !== null;
399
+ // M20 am8 item 2: the guardrail readers and the count-rule test have one owner, src/blockpick.js; they are named here for the callers that read them from this file
400
+ export { guardrailWordNumbers, guardrailStandaloneNumbers, guardrailWordsPerSection, guardrailSectionCount, guardrailItemCount } from './blockpick.js';
436
401
 
437
402
  /** M4e amendment 15 item 2: for each line whose guardrail gives a size for each section, a section count AND a word number,
438
403
  * size x count more than the LARGEST word number (no possible pick fits) is a red naming the line and the numbers. $0; run before any model
@@ -632,7 +597,7 @@ function checkNumbersFromKey(step, label, steps, reds) {
632
597
  * `{source, facts, count?}`, src/citedcheck.js). Its SHAPE is checked in every mode (a signed flow is read the same way). With `fitJobLine` the number rules
633
598
  * must be the person's own words on the job line; with `pageWords` (the drafting copy of each page and what the page-word map kept) every word is proved on
634
599
  * the page at $0 (src/citedwords.js). Each red names the job line, so a redraft can be told which line.
635
- * @param {any} step @param {string} label @param {{sourceRoles: any[], reads: string[]|null, effectiveClass: string, lines: SignedLine[], fitJobLine?: boolean, pageWords?: {texts: Record<string, string>, look: any, docs?: string[]}}} c @param {string[]} reds
600
+ * @param {any} step @param {string} label @param {{sourceRoles: any[], reads: string[]|null, effectiveClass: string, lines: SignedLine[], fitJobLine?: boolean, addedCounts?: Set<string>, pageWords?: {texts: Record<string, string>, look: any, docs?: string[]}}} c @param {string[]} reds
636
601
  */
637
602
  function checkCitedKey(step, label, c, reds) {
638
603
  const at = `declaration: ${label}.close.cited`;
@@ -650,7 +615,7 @@ function checkCitedKey(step, label, c, reds) {
650
615
  const jl = { n: jobLine.n, text: jobLine.text, ...(jobLine.guardrail ? { rule: jobLine.guardrail } : {}) };
651
616
  // a part that is not valid is not read further: its words would only repeat the same red
652
617
  if (factPartReds(part).length) return;
653
- const words = c.pageWords ? citedWordReds({ part, text: c.pageWords.texts[part.source], line: jl.n, jobLine: jl, look: c.pageWords.look, doc: Array.isArray(c.pageWords.docs) && c.pageWords.docs.includes(part.source) }) : [...numberRuleReds({ part, jobLine: jl }), ...countReds({ part, jobLine: jl })];
618
+ const words = c.pageWords ? citedWordReds({ part, text: c.pageWords.texts[part.source], line: jl.n, jobLine: jl, look: c.pageWords.look, doc: Array.isArray(c.pageWords.docs) && c.pageWords.docs.includes(part.source), added: c.addedCounts }) : [...numberRuleReds({ part, jobLine: jl }), ...countReds({ part, jobLine: jl, added: c.addedCounts })];
654
619
  for (const r of words) reds.push(`declaration: ${r.detail}`);
655
620
  }
656
621
 
@@ -763,11 +728,11 @@ function inputReachVerbs(source) {
763
728
  * `sheetWords` (optional; M10 am8 item 2): `{headers: {role: header names}, facts: the columns the sheet look kept}`. With `fitJobLine`, every column a step's `close.columns` names
764
729
  * is proved a real column of its sheet, and a column the code kept for the step's line (an agreed one included) must be in it.
765
730
  * `sheetWords.tables` (optional; M10b piece 1): `{role: bareguard table}` of the drafting copy. With it, every `close.sheet` check passes bareguard's sign-time test at $0.
766
- * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown, wired?: Set<string>, verbatimGoals?: boolean, fitJobLine?: boolean, pageWords?: {texts: Record<string, string>, look: any, docs?: string[]}, sheetWords?: {headers: Record<string, string[]>, facts: any[], tables?: Record<string, {header: string[], rows: any[]}>} }} [context]
731
+ * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown, wired?: Set<string>, verbatimGoals?: boolean, fitJobLine?: boolean, addedCounts?: Set<string>, pageWords?: {texts: Record<string, string>, look: any, docs?: string[]}, sheetWords?: {headers: Record<string, string[]>, facts: any[], tables?: Record<string, {header: string[], rows: any[]}>} }} [context]
767
732
  * @returns {ValidateDeclarationResult}
768
733
  */
769
734
  export function validateDeclaration(declaration, context = {}) {
770
- const { arbiter, lines, catalogue, wired, verbatimGoals, fitJobLine, pageWords, sheetWords } = context;
735
+ const { arbiter, lines, catalogue, wired, verbatimGoals, fitJobLine, pageWords, sheetWords, addedCounts } = context;
771
736
  const reds = [];
772
737
 
773
738
  if (!isPlainObject(declaration)) {
@@ -1071,7 +1036,7 @@ export function validateDeclaration(declaration, context = {}) {
1071
1036
  reds.push(`declaration: ${label}.close.shape: a step that checks facts carries no count check of the drafter's own; only a check you picked (close.picked, on a line recorded in pickedLines) can sit beside its fact check`);
1072
1037
  }
1073
1038
  if (step.close.numbersFrom !== undefined) checkNumbersFromKey(step, label, steps, reds);
1074
- if (step.close.cited !== undefined) checkCitedKey(step, label, { sourceRoles, reads, effectiveClass, lines: safeLines, fitJobLine, pageWords }, reds);
1039
+ if (step.close.cited !== undefined) checkCitedKey(step, label, { sourceRoles, reads, effectiveClass, lines: safeLines, fitJobLine, pageWords, addedCounts }, reds);
1075
1040
  if (step.close.itemShape !== undefined) checkItemShapeKey(step, label, effectiveClass, reds);
1076
1041
  if (step.close.sheet !== undefined) checkSheetKey(step, label, { cellsRoles, reads, effectiveClass, lines: safeLines, fitJobLine, sheetWords }, reds);
1077
1042
  if (step.close.columns !== undefined || (fitJobLine === true && sheetWords)) checkColumnsKey(step, label, { cellsRoles, reads, effectiveClass, lines: safeLines, sheetWords }, reds);
package/src/diary.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // (src/planrun.js: `new Gate({ audit: { path } })`, the path denied to the worker with `fs.deny`). Every row carries `kind`, in the order the rows were written:
3
3
  // kind 'call' one row per MODEL CALL: step, try, round, cost, tokens, time, stop reason, thinking asked and status
4
4
  // kind 'tool' one row per TOOL CALL: step, try, round, tool, path, the guard's decision (allow / deny + rule / no check)
5
+ // kind 'try-start' one row per model-step TRY, written when it begins: step, try, at (M20 am1 item 8; report-only, the Run tab's NOW row reads it; no check, cost or count reads it)
5
6
  // kind 'checks' one row per TRY that ran checks: each check numbered, ✓/✗, its result, where it comes from, and the output it judged
6
7
  // Never saved: what the model said, what was in any file (a tool row names a path, never its content). Every string is scrubbed with the
7
8
  // ONE secret inventory (`redactSecrets`, src/redact.js) before the row is written. The model can never read this file: the step's
@@ -19,7 +20,7 @@ export const DIARY_FILE = 'diary.jsonl';
19
20
  /** The diary's absolute path for a run, for the model's deny list (a list, as the deny lists take one). @param {string} runDir @returns {string[]} */
20
21
  export const diaryPaths = (runDir) => [join(runDir, DIARY_FILE)];
21
22
 
22
- /** @typedef {'call'|'tool'|'checks'} DiaryKind */
23
+ /** @typedef {'call'|'tool'|'checks'|'try-start'} DiaryKind */
23
24
 
24
25
  /** A copy of a JSON value with every string scrubbed. @param {any} v @returns {any} */
25
26
  function scrub(v) {
@@ -39,6 +40,9 @@ export const appendTool = (runDir, row) => write(runDir, 'tool', row);
39
40
  /** @param {string} runDir @param {{step:string|null, try:number, at:string, lastRound:number, checks:Array<{n:number, text:string, ok:boolean, result:string|null, source:string}>, output:{file:string, bytes:number, sha256:string}|null}} row */
40
41
  export const appendChecks = (runDir, row) => write(runDir, 'checks', row);
41
42
 
43
+ /** @param {string} runDir @param {{step:string|null, try:number, at:string}} row */
44
+ export const appendTryStart = (runDir, row) => write(runDir, 'try-start', row);
45
+
42
46
  /** The rows of one kind, in the order they were written; a torn or unparseable line is skipped (the writer's fresh-line rule is its other half). @param {string} runDir @param {DiaryKind} kind @returns {any[]} */
43
47
  const readKind = (runDir, kind) => readLines(runDir, DIARY_FILE).filter((r) => r.kind === kind);
44
48
  /** @param {string} runDir @returns {any[]} */
@@ -48,6 +52,24 @@ export const readTools = (runDir) => readKind(runDir, 'tool');
48
52
  /** @param {string} runDir @returns {any[]} */
49
53
  export const readChecks = (runDir) => readKind(runDir, 'checks');
50
54
 
55
+ /** @param {string} runDir @returns {any[]} */
56
+ export const readTryStarts = (runDir) => readKind(runDir, 'try-start');
57
+
51
58
  /** The round number of this step's next model call: one more than the highest round it has in the diary, so it counts on across tries and across resumes.
52
59
  * Read off the file each time (the diary is the one record), never a copy held in memory. @param {string} runDir @param {string|null} step */
53
60
  export const nextRound = (runDir, step) => readCalls(runDir).filter((r) => r.step === step).reduce((m, r) => Math.max(m, r.round), 0) + 1;
61
+
62
+ /**
63
+ * M20 am3g item 23: the ONE rule for a step's newest-try checks, over the run's `checks` rows (`readChecks`): a row of this step with a whole-number `try` and a `checks` list;
64
+ * the highest `try`, a tie going to the later row; the row, or null when the step has none. The Audit, the Result tab and the ticket grid ask it and keep their own words
65
+ * and tags; the Audit card's "checks on the last try" count asks it too (its per-try fold is another question).
66
+ * @param {any[]|null|undefined} diary @param {unknown} stepId @returns {any|null}
67
+ */
68
+ export function newestChecksOf(diary, stepId) {
69
+ let newest = null;
70
+ for (const r of diary ?? []) {
71
+ if (!r || r.step !== stepId || !Number.isInteger(r.try) || !Array.isArray(r.checks)) continue;
72
+ if (newest === null || r.try >= newest.try) newest = r;
73
+ }
74
+ return newest;
75
+ }
@@ -8,6 +8,16 @@
8
8
  // Third outcomes: no log -> null (nothing to list); a cost that is null reads "cost unknown", an incomplete sum reads "at least $X", never 0.
9
9
 
10
10
  import { plainPlanCheck, pickPlanRed } from './plain-checks.js';
11
+ import { isThinkingMode } from './thinking.js';
12
+
13
+ /** a plan folder's card file: `card-<n>.json` (n = the redraft or revise number) */
14
+ export const CARD_RE = /^card-(\d+)\.json$/;
15
+ /** how much of the end of a child's log a person is shown when it stopped or refused */
16
+ export const LOG_TAIL_CHARS = 1500;
17
+ /** a revise's or an answer redraft's own log in a plan folder; `kind` is 'answers' for the redraft, anything else for the revise @param {string} kind @param {number} n */
18
+ export const draftLogName = (kind, n) => `${kind === 'answers' ? 'redraft' : 'revise'}-${n}.log`;
19
+ /** a name that is a revise's or a redraft's log */
20
+ export const DRAFT_LOG_RE = /^(revise|redraft)-\d+\.log$/;
11
21
 
12
22
  const REBUILD_RE = /^declaration: steps\[(\d+)\]\.close\.shape cannot be built into a check — (.*)$/s;
13
23
 
@@ -55,7 +65,7 @@ export function draftStepList({ log, declaration, questionOpen = false }) {
55
65
  const out = [];
56
66
 
57
67
  const t = log.thinking;
58
- if (t && (t.asked === 'on' || t.asked === 'off') && typeof t.status === 'string') {
68
+ if (t && isThinkingMode(t.asked) && typeof t.status === 'string') {
59
69
  if (t.status === 'applied') out.push({ id: 'thinking', label: `thinking ${t.asked}`, status: 'done', details: [] });
60
70
  else if (typeof t.say === 'string' && t.say !== '') out.push({ id: 'thinking', label: t.say, status: 'failed', details: [] });
61
71
  }
package/src/drafter.js CHANGED
@@ -49,11 +49,11 @@ import { questionsOfBlock } from './blockasks.js';
49
49
  import { NOTE_KIND, NOTE_TOOL, NOTE_SYSTEM, NOTE_SCHEMA, notePrompt, noteAnswers } from './noteask.js';
50
50
  import { ledgerRecord, LEDGER_SYSTEM, LEDGER_SCHEMA, LEDGER_TOOL, ledgerUserText } from './checklist.js';
51
51
  import { ROW_EDIT_SYSTEM, ROW_EDIT_REVISE, rowEditUserText, rowEditChannel, editsOf, ticketFilterBlock } from './rowedit.js';
52
- import { matchRecord, entriesFromAnswers, columnEntries, columnsOnLines } from './pickrecord.js';
52
+ import { matchRecord, entriesFromAnswers, columnEntries, columnsOnLines, addedCountsOf } from './pickrecord.js';
53
53
  import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
54
54
  import { tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
55
55
  import { lineRules } from './pagebits.js';
56
- import { isCountGuardrail } from './declaration.js';
56
+ import { isCountable } from './blockpick.js';
57
57
  import path from 'node:path';
58
58
  import { isCellsPath } from './closers.js';
59
59
  import { parseCsv, sheetTable } from './csv.js';
@@ -61,13 +61,14 @@ import { sheetSuggestProp, sheetOfferRules, agreedColumnWords } from './sheetoff
61
61
  import { uncoveredRules, csvRolesOf } from './sheetblock.js';
62
62
  import { withSheetRows, withSheetCard } from './sheetrows.js';
63
63
  import { buildSheetChecks, unbuiltSheetLines } from './sheetbuild.js';
64
- import { TICKET_FIELDS, ticketRuleField, proposalReds, withTicketRows } from './ticketrows.js';
64
+ import { ticketRuleField, proposalReds, withTicketRows } from './ticketrows.js';
65
+ import { TICKET_FIELDS } from './checklistsign.js';
65
66
  import {
66
67
  makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
67
68
  } from './provider.js';
68
69
  import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
69
70
  import { ConfigError } from './config.js';
70
- import { thinkingSay, worstThinkingStatus } from './thinking.js';
71
+ import { thinkingSay, worstThinkingStatus, isThinkingMode } from './thinking.js';
71
72
  import { repairTrailingBraces } from './jsonbrace.js';
72
73
 
73
74
  export const MAX_STRUCTURE_RETRIES = 2;
@@ -243,7 +244,7 @@ export function normalizeQuestions(raw, failedLines) {
243
244
 
244
245
  // M10 am27 (1): at draft time a count guardrail is hidden from the AI (the page look and the drafter); code keeps the ORIGINAL rule numbers and text.
245
246
  // M16 S5: not on a line the check block is given (`all`): its count rules are shown like any other (am27 (1) is replaced for the lines of the list)
246
- const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({ rule: guardrail }).filter((r) => all || !isCountGuardrail(r)).join('; ');
247
+ const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({ rule: guardrail }).filter((r) => all || !isCountable(r)).join('; ');
247
248
 
248
249
  /**
249
250
  * The job lines as the page look may see them (no count rule), and `toOriginal`, which takes a look fact's / dropped entry's visible rule number back to the guardrail's own number.
@@ -251,10 +252,10 @@ const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({
251
252
  */
252
253
  export function hideCounts(jobLines, shown = /** @type {Set<number>} */ (new Set())) {
253
254
  // M16 item 5: the lines the check block is given show their count rules to the look (`shown`); every other line is as before
254
- const seenLines = jobLines.map((l) => { const kept = lineRules(l).filter((r) => shown.has(l.n) || !isCountGuardrail(r)); return { n: l.n, text: l.text, ...(kept.length ? { rule: kept.join('; ') } : {}) }; });
255
+ const seenLines = jobLines.map((l) => { const kept = lineRules(l).filter((r) => shown.has(l.n) || !isCountable(r)); return { n: l.n, text: l.text, ...(kept.length ? { rule: kept.join('; ') } : {}) }; });
255
256
  const ruleMap = (/** @type {number} */ line, /** @type {number|undefined} */ vis) => {
256
257
  if (vis === undefined || shown.has(line)) return vis;
257
- const orig = lineRules(jobLines.find((x) => x.n === line)).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountGuardrail(x.r));
258
+ const orig = lineRules(jobLines.find((x) => x.n === line)).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountable(x.r));
258
259
  return orig[vis - 1]?.no ?? vis;
259
260
  };
260
261
  const toOriginal = (/** @type {any} */ f) => (f.forRule !== undefined ? { ...f, forRule: ruleMap(f.line, f.forRule) } : f.rule !== undefined ? { ...f, rule: ruleMap(f.line, f.rule) } : f);
@@ -392,7 +393,7 @@ export async function draft({
392
393
 
393
394
  // ---- $0 gates, before any provider is built -------------------------------
394
395
  // `draftThinking` ('on'|'off', M4d am6 item 7 / am7: the Chat tick-box, per job) is an intent only: turning thinking on or off on the wire is bareagent's (am7 item 3).
395
- if (draftThinking !== 'on' && draftThinking !== 'off') return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
396
+ if (!isThinkingMode(draftThinking)) return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
396
397
  if (actionMode !== null && actionMode !== 'check' && actionMode !== 'known') return fail([`config: actionMode must be check | known, got ${JSON.stringify(actionMode)}`]);
397
398
  const parsed = parseSignedText(proseText);
398
399
  if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`), { box: 'job' });
@@ -456,6 +457,8 @@ export async function draft({
456
457
  let unmetered = 0; // calls that failed with no metering: their cost is unknown
457
458
  const book = (inFlight) => onBook?.({
458
459
  inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
460
+ // M20 am1 item 5: the result so far, in log.json's shape, for the step lines (src/draftspend.js makeStepWriter)
461
+ partial: () => { const m = sumMeterings(meterings); return { ok: false, reds: [], rounds: m.rounds, modelId, costUsd: m.costUsd, spendComplete: unmetered === 0 && m.costUsd !== null, thinking: thinkingOf(), inputs: facts.list, log }; },
459
462
  });
460
463
 
461
464
  /** the result of a draft that stops before any drafting round with what it spent so far (a provider red, the budget); one literal for every such stop */
@@ -729,7 +732,7 @@ export async function draft({
729
732
  const shapeEverywhere = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
730
733
  // M16 S1: the lines the block is given (step lines; a sheet line the sheet look tied to a column stays on the sheet path, R6). Their rules go to the block; every other shape rule keeps today's path.
731
734
  // a job with a CSV input: a line with a rule that is not a count belongs to the sheet path even when the sheet look tied none of its words (its sheet checks are the drafter's, M10b, which the list leaves as they are; the declaration is not there yet to say it)
732
- const csvRuleLines = Object.keys(facts.sheets ?? {}).length ? jobLines.filter((l) => !askLines.has(l.n) && lineRules(l).some((r) => !isCountGuardrail(r))).map((l) => l.n) : [];
735
+ const csvRuleLines = Object.keys(facts.sheets ?? {}).length ? jobLines.filter((l) => !askLines.has(l.n) && lineRules(l).some((r) => !isCountable(r))).map((l) => l.n) : [];
733
736
  const blockPlan = blockJobLines(proseText, undefined, [...new Set([...sheetFacts.filter((f) => f.forRule !== undefined), ...sheetAsks, ...sheetLooks.flatMap((l) => l.dropped)].map((x) => x.line)), ...csvRuleLines]);
734
737
  if (blockPlan && !blockPlan.ok) return fail(blockPlan.reds.map((r) => `signed-text: ${r}`));
735
738
  const blockLineNums = new Set(blockPlan ? blockPlan.jobLines.map((l) => l.n) : []);
@@ -1094,6 +1097,7 @@ export async function draft({
1094
1097
  const planLookFacts = inPlan ? look.facts.filter((f) => !blockLineNums.has(f.line) || inPlan.has(`${f.line}:${f.name}`)) : look.facts;
1095
1098
  const verdict1 = validateDeclaration(declaration, {
1096
1099
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
1100
+ addedCounts: block ? addedCountsOf(block.choicesRecord(), lines) : new Set(),
1097
1101
  // M10 am7 item 1: the words of every cited fact are proved on the drafting copy of the page, against what the page-word map kept
1098
1102
  sheetWords: sheetTables ? { headers: Object.fromEntries(Object.entries(sheetTables).map(([role, t]) => [role, t.header])), facts: sheetFacts.filter((f) => f.shape === 'column' && !(sheetHitl?.lines ?? []).includes(f.line)), tables: sheetTables } : undefined,
1099
1103
  pageWords: { texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, look: pageSources.length ? { facts: planLookFacts, dropped: look.dropped } : null, docs: docRolesOf(arbiter.sources) },
@@ -0,0 +1,127 @@
1
+ // M20 am3b item 2: what a plan folder's own files say, apart from the sign: its verdict, its questions with their answers, and the key scrub. Moved out of
2
+ // src/authoring.js so src/setup.js (which records them) and src/authoring.js (which calls writeSetup) no longer import each other.
3
+ import { readDraftLog, readJsonFile } from './flow.js';
4
+ import { readFileInside } from './inside.js';
5
+ import { isRec } from './isrec.js';
6
+ import { parseSignedText } from './signed-text.js';
7
+
8
+ export const SPEC_HASH_FILE = 'spec.hash';
9
+ /** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
10
+ export const LEAK_MARKER_FILE = 'scrub-leak.red';
11
+ /**
12
+ * M20 am3 item 12: the ONE reader of one plan folder's verdict, from its files (`spec.hash`, `scrub-leak.red`, `log.json`). Green = a
13
+ * non-empty spec.hash; red = a leak marker or a log that says not ok (`reds` = the log's own reds, then the marker's text); none otherwise.
14
+ * `hashFile` and `leak` are the raw reads, so sign can name a missing or refused file in its own words. Callers scrub `reds` themselves.
15
+ * @param {string} dir the folder that holds the plan folder @param {string} [rel] `draft`, `draft-<n>` or `.` (the plan folder itself)
16
+ * @returns {{verdict: 'green'|'red'|'none', hash: string|null, hashFile: ReturnType<typeof readFileInside>, leak: ReturnType<typeof readFileInside>, log: any, reds: string[]}}
17
+ */
18
+ export function draftVerdict(dir, rel = '.') {
19
+ const hashFile = readFileInside(dir, `${rel}/${SPEC_HASH_FILE}`);
20
+ const hash = hashFile.ok && hashFile.text.trim() !== '' ? hashFile.text.trim() : null;
21
+ const leak = readFileInside(dir, `${rel}/${LEAK_MARKER_FILE}`);
22
+ const log = readDraftLog(dir, rel);
23
+ const reds = [...(Array.isArray(log?.reds) ? log.reds.map(String) : []), ...(leak.ok ? [leak.text.trim()] : [])];
24
+ return { verdict: hash ? 'green' : (leak.ok || (log && log.ok === false)) ? 'red' : 'none', hash, hashFile, leak, log, reds };
25
+ }
26
+
27
+ export const QUESTIONS_FILE = 'questions.json';
28
+ export const ANSWER_FILE = (k) => `answer-${k}.json`;
29
+
30
+ /**
31
+ * The questions a plan folder raised and the answers on disk, READ from its files — the ONE reader (the panel's phase reader, the sign
32
+ * checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
33
+ * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
34
+ * @param {string} planDir
35
+ * A question the page look raised (M10 piece 3) also carries `source: 'look'`, `ask` ('reading' | 'cant-check'), `ruleNo`, `ruleText` and `proposal`; an answer file carries `at`.
36
+ * @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, choice?:'agree'|'drop'|'rule'|'column', source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null, check?:Record<string, any>, pairRule?:number, columns?:string[], readings?:Record<string,string>}[], open: {k:number, line:number, question:string, answer:null}[] }}
37
+ */
38
+ export function readQuestions(planDir) {
39
+ const none = { questions: [], open: [] };
40
+ const f = readFileInside(planDir, QUESTIONS_FILE);
41
+ if (!f.ok) return none;
42
+ let list;
43
+ try { list = JSON.parse(f.text)?.questions; } catch { return none; }
44
+ if (!Array.isArray(list)) return none;
45
+ const questions = list.map((q, i) => {
46
+ const k = i + 1;
47
+ const a = readFileInside(planDir, ANSWER_FILE(k));
48
+ let answer = null;
49
+ let at;
50
+ /** @type {string|null|undefined} the `~` rule the answer added (null = it left the rule Not checked), as the answer file recorded it */
51
+ let rule;
52
+ /** @type {'agree'|'drop'|'rule'|'column'|undefined} M10 am29: which one the answer used (`agree`, `drop` or `rule`), when the file records it */
53
+ let choice;
54
+ if (a.ok) {
55
+ try {
56
+ const j = JSON.parse(a.text);
57
+ const t = j?.answer;
58
+ if (typeof t === 'string' && t.trim() !== '') { answer = t; if (typeof j.at === 'string') at = j.at; if (j.rule === null || typeof j.rule === 'string') rule = j.rule; if (j.choice === 'agree' || j.choice === 'drop' || j.choice === 'rule' || j.choice === 'column') choice = j.choice; }
59
+ } catch { /* unreadable = unanswered */ }
60
+ }
61
+ return {
62
+ k, line: q.line, question: String(q.question), answer, ...(at === undefined ? {} : { at }), ...(rule === undefined ? {} : { rule }), ...(choice === undefined ? {} : { choice }),
63
+ ...(q.source === 'look' ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: typeof q.proposal === 'string' ? q.proposal : null, ...(q.check && typeof q.check === 'object' ? { check: q.check } : {}), ...(Number.isInteger(q.pairRule) ? { pairRule: q.pairRule } : {}), ...(Array.isArray(q.columns) && q.columns.length > 0 && q.readings && typeof q.readings === 'object' ? { columns: q.columns.map(String), readings: q.readings } : {}) } : {}),
64
+ };
65
+ });
66
+ return { questions, open: /** @type {any} */ (questions.filter((q) => q.answer === null)) };
67
+ }
68
+
69
+ /** Literal (never RegExp) key scrub; a secret under 8 chars is skipped so it can't blank ordinary text. */
70
+ export function scrub(text, secrets) {
71
+ let out = text;
72
+ for (const s of secrets) if (typeof s === 'string' && s.length >= 8) out = out.split(s).join('[redacted-key]');
73
+ return out;
74
+ }
75
+
76
+
77
+ /** the drafter's own "Not checked" reading, kept in a plan folder (information only; never in the readout, so never in the hash) */
78
+ export const NOT_CHECKED_FILE = 'not-checked.json';
79
+ /**
80
+ * M20 am3 item 10: the ONE reader of a plan folder's `not-checked.json`. `notChecked` is the file's own list as it is (any type; the callers keep what they
81
+ * accept of it: `notCheckedBlock`/`notCheckedView` filter strings, the rebuild keeps strings), `by` the tag of each line when the file holds an object, else null.
82
+ * A missing, refused, unparseable or non-object file reads as `{notChecked: undefined, by: null}` (a plan from before amendment 25 has none).
83
+ * @param {string} dir the folder that holds the plan folder @param {string} [rel] `draft`, `draft-<n>` or `.` (the plan folder itself)
84
+ * @returns {{notChecked: any, by: Record<string, any>|null}}
85
+ */
86
+ export function readNotCheckedFile(dir, rel = '.') {
87
+ const f = readJsonFile(dir, `${rel}/${NOT_CHECKED_FILE}`);
88
+ return { notChecked: f?.notChecked, by: isRec(f?.by) ? f.by : null };
89
+ }
90
+
91
+ /**
92
+ * M20 am3e item 17: a draft session folder's card files, spelled and read here only. `card.json` is the first card (n 0 or none), `card-<n>.json` the card of
93
+ * revise or redraft n. `readCard` is the tolerant read: the card object, or null (missing, refused, not JSON, not an object). A site that only asks "is there a
94
+ * readable file" (src/draftspend.js, the money count) is not this question and keeps its own check.
95
+ * @param {number} [n] @returns {string}
96
+ */
97
+ export const cardFileName = (n = 0) => (n > 0 ? `card-${n}.json` : 'card.json');
98
+ /** @param {string} dir the session folder @param {number} [n] @returns {Record<string, any>|null} */
99
+ export const readCard = (dir, n = 0) => readJsonFile(dir, cardFileName(n));
100
+
101
+ /**
102
+ * M20 am3e item 18: `redraft-<n>.json`, the marker that plan n is a redraft after the person's answers or a Drop/Add edit, not a revise. Its name and its one read:
103
+ * the marker object as written (`fromPlan`, `answers`, `left`), or null (missing, refused, not JSON, not an object). `rowEdit` is typed: an object, or the key is
104
+ * left out (none): a `rowEdit` that is not an object reads as none everywhere.
105
+ * @param {number} n @returns {string}
106
+ */
107
+ export const redraftFileName = (n) => `redraft-${n}.json`;
108
+ /** @param {string} dir the session folder @param {number} n @returns {Record<string, any>|null} */
109
+ export function readRedraftMarker(dir, n) {
110
+ const m = readJsonFile(dir, redraftFileName(n));
111
+ if (m === null || !Object.hasOwn(m, 'rowEdit') || isRec(m.rowEdit)) return m;
112
+ const { rowEdit: _dropped, ...rest } = m;
113
+ return rest;
114
+ }
115
+
116
+ /**
117
+ * M20 am3e item 20: a draft plan folder's job text and steps, the ONE reader. `proseText` is prose.txt as it is (null when missing or refused), `parsed` the signed-text
118
+ * parse of it (`parseSignedText`'s result, ok or not; null when there is no prose), `declaration` declaration.json as an object (null when missing, refused, not JSON or not
119
+ * an object). Each caller keeps its own sentence for what it does when one is null. (A flow folder with a signature is `readFlow`'s; a plan that falls back to
120
+ * declaration.rejected.json is src/panel/author.js `stepListOf`'s own question.)
121
+ * @param {string} dir the folder that holds the plan folder @param {string} [rel] `draft`, `draft-<n>` or `.` (the plan folder itself)
122
+ * @returns {{proseText: string|null, parsed: ReturnType<typeof parseSignedText>|null, declaration: any}}
123
+ */
124
+ export function readPlanTexts(dir, rel = '.') {
125
+ const prose = readFileInside(dir, `${rel}/prose.txt`);
126
+ return { proseText: prose.ok ? prose.text : null, parsed: prose.ok ? parseSignedText(prose.text) : null, declaration: readJsonFile(dir, `${rel}/declaration.json`) };
127
+ }