fwdloop 0.37.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 (140) hide show
  1. package/README.md +5 -19
  2. package/bin/fwdloop +51 -29
  3. package/package.json +1 -1
  4. package/src/ask.js +70 -148
  5. package/src/audit-fold.js +5 -4
  6. package/src/auditchecks.js +6 -4
  7. package/src/authoring.js +36 -64
  8. package/src/blockasks.js +2 -1
  9. package/src/blockassemble.js +7 -9
  10. package/src/blockdraft.js +2 -2
  11. package/src/blockpick.js +5 -5
  12. package/src/books.js +217 -12
  13. package/src/checkblock.js +25 -55
  14. package/src/checked.js +2 -3
  15. package/src/checklistsign.js +26 -5
  16. package/src/checklook.js +3 -1
  17. package/src/checkpick.js +5 -76
  18. package/src/cited-source.js +4 -4
  19. package/src/citedcheck.js +6 -11
  20. package/src/citedwords.js +9 -8
  21. package/src/closers.js +9 -6
  22. package/src/declaration.js +22 -55
  23. package/src/diary.js +23 -1
  24. package/src/draft-steps.js +11 -1
  25. package/src/drafter.js +28 -23
  26. package/src/draftfiles.js +127 -0
  27. package/src/draftspend.js +165 -17
  28. package/src/flow.js +42 -87
  29. package/src/flowmodel.js +1 -1
  30. package/src/index.js +3 -2
  31. package/src/inside.js +86 -0
  32. package/src/isrec.js +2 -0
  33. package/src/jsonl-append.js +33 -1
  34. package/src/learn.js +1 -1
  35. package/src/learnstore.js +20 -22
  36. package/src/line-checks.js +2 -3
  37. package/src/liveness.js +3 -0
  38. package/src/mcp-use.js +8 -9
  39. package/src/memo.js +13 -16
  40. package/src/minrule.js +16 -0
  41. package/src/model-step.js +3 -3
  42. package/src/page-words.js +8 -0
  43. package/src/pageask.js +8 -3
  44. package/src/pagebits.js +8 -1
  45. package/src/pagedropwords.js +1 -1
  46. package/src/pagerules.js +6 -3
  47. package/src/panel/author.js +121 -78
  48. package/src/panel/authorcard.js +21 -8
  49. package/src/panel/authorflows.js +3 -3
  50. package/src/panel/authorresume.js +3 -3
  51. package/src/panel/authorstart.js +15 -16
  52. package/src/panel/authortrigger.js +43 -70
  53. package/src/panel/data.js +125 -168
  54. package/src/panel/index.html +154 -63
  55. package/src/panel/jobgrid.js +3 -7
  56. package/src/panel/result.js +7 -10
  57. package/src/panel/resume.js +4 -3
  58. package/src/panel/scheduler.js +9 -9
  59. package/src/panel/server.js +8 -4
  60. package/src/panel/spawn.js +22 -11
  61. package/src/panel/tickets.js +2 -2
  62. package/src/pickrecord.js +51 -31
  63. package/src/placerule.js +3 -4
  64. package/src/planrebuild.js +19 -19
  65. package/src/primitives.js +1 -1
  66. package/src/provider.js +1 -1
  67. package/src/reasons.js +25 -0
  68. package/src/report.js +2 -1
  69. package/src/runfile.js +26 -2
  70. package/src/runner.js +57 -105
  71. package/src/runvalues.js +47 -24
  72. package/src/schedule-choices.js +41 -0
  73. package/src/schedule-shape.js +39 -0
  74. package/src/schedule.js +9 -8
  75. package/src/setup.js +20 -36
  76. package/src/shaperows.js +2 -2
  77. package/src/sheet-record.js +1 -2
  78. package/src/sheetblock.js +3 -4
  79. package/src/sheetbuild.js +5 -5
  80. package/src/sheetchecks.js +1 -2
  81. package/src/sheetclaims.js +1 -2
  82. package/src/sheetoffer.js +1 -1
  83. package/src/sheetrun.js +5 -7
  84. package/src/summary-words.js +2 -1
  85. package/src/thinking.js +5 -2
  86. package/src/ticketrows.js +8 -30
  87. package/src/trigger-clock.js +9 -23
  88. package/src/trigger-files.js +30 -22
  89. package/src/trigger-tickets.js +15 -14
  90. package/src/try-checks.js +2 -1
  91. package/src/types.js +2 -0
  92. package/types/ask.d.ts +25 -20
  93. package/types/authoring.d.ts +8 -42
  94. package/types/blockassemble.d.ts +0 -1
  95. package/types/blockpick.d.ts +1 -1
  96. package/types/books.d.ts +256 -4
  97. package/types/checkblock.d.ts +2 -25
  98. package/types/checklist.d.ts +3 -3
  99. package/types/checklistsign.d.ts +7 -0
  100. package/types/checkpick.d.ts +0 -21
  101. package/types/citedwords.d.ts +7 -4
  102. package/types/closers.d.ts +1 -0
  103. package/types/declaration.d.ts +4 -14
  104. package/types/diary.d.ts +14 -1
  105. package/types/draft-steps.d.ts +7 -0
  106. package/types/drafter.d.ts +3 -2
  107. package/types/draftfiles.d.ts +89 -0
  108. package/types/draftspend.d.ts +74 -0
  109. package/types/flow.d.ts +32 -54
  110. package/types/index.d.ts +3 -3
  111. package/types/inside.d.ts +58 -0
  112. package/types/isrec.d.ts +1 -0
  113. package/types/jsonl-append.d.ts +20 -0
  114. package/types/learnstore.d.ts +0 -2
  115. package/types/liveness.d.ts +1 -0
  116. package/types/minrule.d.ts +6 -0
  117. package/types/page-words.d.ts +6 -0
  118. package/types/pageask.d.ts +2 -0
  119. package/types/pagebits.d.ts +3 -0
  120. package/types/pagerules.d.ts +1 -0
  121. package/types/panel/author.d.ts +7 -3
  122. package/types/panel/authorcard.d.ts +0 -6
  123. package/types/panel/authorflows.d.ts +4 -4
  124. package/types/panel/authortrigger.d.ts +16 -2
  125. package/types/panel/data.d.ts +36 -11
  126. package/types/panel/spawn.d.ts +18 -2
  127. package/types/pickrecord.d.ts +29 -0
  128. package/types/reasons.d.ts +23 -0
  129. package/types/runfile.d.ts +14 -0
  130. package/types/runner.d.ts +6 -38
  131. package/types/runvalues.d.ts +17 -2
  132. package/types/schedule-choices.d.ts +9 -0
  133. package/types/schedule-shape.d.ts +15 -0
  134. package/types/sheetbuild.d.ts +1 -1
  135. package/types/sheetclaims.d.ts +0 -1
  136. package/types/thinking.d.ts +1 -0
  137. package/types/ticketrows.d.ts +0 -9
  138. package/types/trigger-clock.d.ts +3 -2
  139. package/types/trigger-files.d.ts +15 -4
  140. package/types/types.d.ts +8 -0
package/src/pageask.js CHANGED
@@ -3,7 +3,6 @@
3
3
  // borrowed-from: bareloop src/pagemap.js@v0.49.0 (d51a367) (stripAgreeLead, F240; adapted: literal regex, src/ bans new RegExp)
4
4
  // The words of the asks and of the answers to them. M17 am4 (A1): the asks themselves come from the list (src/blockasks.js); the page-look ask path that sat here is gone.
5
5
  import { redactSecrets } from './redact.js';
6
- import { HOW_TO_ANSWER } from './checkpick.js';
7
6
  import { columnTail } from './sheetfind.js';
8
7
 
9
8
  /** the most asks before drafting; more than this is a job to rewrite, not a questionnaire (am1) */
@@ -133,14 +132,20 @@ export function ruleOfAnswer(q, typed, choice) {
133
132
  // M17 am9 item 4: a column picked from a tie is the reading the tie carried for that column (the rule's words are rewritten in place by applyAnswers); anything not on the list never reaches here (the door refuses it)
134
133
  if (choice === 'column') return { rule: q.readings?.[typedText] ?? null, left: q.readings?.[typedText] === undefined };
135
134
  if (choice !== undefined) { // M10 am29: a typed choice decides, never the words; the box (`rule`) keeps its words whole
136
- const shapeC = q.ask === 'check' || q.ask === 'no-check';
135
+ const shapeC = isShapeAsk(q.ask);
137
136
  if (choice === 'agree' && typeof q.proposal === 'string' && (q.ask === 'reading' || q.ask === 'check')) return { rule: q.proposal, left: false, ...(q.ask === 'check' && q.check ? { check: q.check } : {}) };
138
137
  if (choice === 'drop') return { rule: null, left: true };
139
138
  return { rule: typedText, left: false, ...(shapeC ? { own: true } : {}) };
140
139
  }
141
140
  const text = stripAgreeLead(typedText); // F240: "yes, check it as ..." is the person's own words minus the leading "yes,"
142
- const shape = q.ask === 'check' || q.ask === 'no-check';
141
+ const shape = isShapeAsk(q.ask);
143
142
  if ((q.ask === 'reading' || q.ask === 'check') && typeof q.proposal === 'string' && isAgree(text)) return { rule: q.proposal, left: false, ...(q.ask === 'check' && q.check ? { check: q.check } : {}) };
144
143
  if ((q.ask === 'cant-check' || shape) && isDropIt(text)) return { rule: null, left: true };
145
144
  return { rule: text, left: false, ...(shape ? { own: true } : {}) };
146
145
  }
146
+
147
+ /** M20 am8: the one question "is this a shape guardrail's ask" (`check` proposes a check, `no-check` found none) @param {unknown} ask @returns {boolean} */
148
+ export const isShapeAsk = (ask) => ask === 'check' || ask === 'no-check';
149
+
150
+ /** how every answer is told, once (am2 item 2's words) */
151
+ export const HOW_TO_ANSWER = (/** @type {number} */ line, /** @type {boolean} */ agree) => `${agree ? 'Answer "agree" to use it, or type your own words' : 'Type your own words'} (your answer replaces that ~ rule on line ${line}), or answer "drop it" to leave it Not checked.`;
package/src/pagebits.js CHANGED
@@ -7,7 +7,14 @@ export const MAX_CURRENCIES = 3;
7
7
  export const MAX_UNITS = 10;
8
8
  export const MAX_UNIT_CHARS = 100;
9
9
  export const asList = (/** @type {unknown} */ v) => (Array.isArray(v) ? v.map(String) : (typeof v === 'string' ? [v] : []));
10
- export const boundOk = (/** @type {string} */ shape, /** @type {unknown} */ v) => (shape === 'number' || shape === 'money' ? typeof v === 'number' && Number.isFinite(v) : typeof v === 'string' && v !== '');
10
+ /** M20 am8: the one question "is this fact shape phrase-like" (the words of a phrase or a place are looked for on the page) @param {unknown} shape @returns {boolean} */
11
+ export const isPhraseShape = (shape) => shape === 'phrase' || shape === 'place';
12
+ /** M20 am8: the one question "is this a legal result count": `{min, max}` only, at least one of them, whole numbers 1 or more, min no more than max (each caller keeps its own words for a refusal) @param {any} c @returns {boolean} */
13
+ export const isLegalCount = (c) => isRec(c) && Object.keys(c).every((k) => k === 'min' || k === 'max') && (c.min !== undefined || c.max !== undefined)
14
+ && ['min', 'max'].every((k) => c[k] === undefined || (Number.isInteger(c[k]) && c[k] >= 1)) && (c.min === undefined || c.max === undefined || c.min <= c.max);
15
+ /** M20 am8: the one question "is this fact shape an amount" (money or number: read as a plain number, carries the decimal mark, its bounds are numbers) @param {unknown} shape @returns {boolean} */
16
+ export const isAmountShape = (shape) => shape === 'money' || shape === 'number';
17
+ export const boundOk = (/** @type {string} */ shape, /** @type {unknown} */ v) => (isAmountShape(shape) ? typeof v === 'number' && Number.isFinite(v) : typeof v === 'string' && v !== '');
11
18
 
12
19
  // borrowed-from: bareloop src/factwords.js@18ab77c (squash, loose, countExact, countPhrase - rewritten without a built pattern, same count, see test/m10-pagebits.test.js)
13
20
  const WS = /[\s   ]+/g;
@@ -8,7 +8,7 @@
8
8
 
9
9
  // borrowed-from: bareloop src/pagedropwords.js@v0.56.0 (3383cce) (the four reasons the block's drops carry, and the sign-twice sentence by `d.other`; FACT_LANGS lives with the facts in src/citedcheck.js)
10
10
  import { FACT_LANGS } from './citedcheck.js';
11
- import { REASON } from './checkblock.js';
11
+ import { REASON } from './reasons.js';
12
12
 
13
13
  /** the two ways a sign listed twice can be used once (v0.56.0 spells the sentence from `d.other`; no other -> "currency", the sentence fwd has always written) */
14
14
  const SIGN_TWICE_AS = ['currency', 'unit'];
package/src/pagerules.js CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { lineRules } from './pagebits.js';
9
9
  import { MAX_CURRENCIES, MAX_UNITS, MAX_UNIT_CHARS, FACT_OPS, boundOk } from './pagebits.js';
10
- import { countExact, countPhrase, squash, normLabel } from './pagebits.js';
10
+ import { countExact, countPhrase, squash, normLabel, isAmountShape } from './pagebits.js';
11
11
 
12
12
  /**
13
13
  * @typedef {{op: string, value?: string|number, lo?: string|number, hi?: string|number}} Reading what a `~` rule means as a limit (PRD v1.107 Part 5b): the same shape as a signed fact rule
@@ -40,13 +40,16 @@ export function tieOf(from, jobLines) {
40
40
  return out;
41
41
  }
42
42
 
43
+ /** M20 am8: the one question "can CODE read a limit from the person's words for this fact shape" (money or time: readLimit reads those two) @param {unknown} shape @returns {shape is 'money'|'time'} */
44
+ export const canReadLimit = (shape) => shape === 'money' || shape === 'time';
45
+
43
46
  /**
44
47
  * Is this a legal `reading` for a fact of this shape? Only a time or money fact carries one, with the op set and the bound types of a signed
45
48
  * fact rule (src/facts.js): no other key, no missing bound. A malformed one makes the whole map answer malformed (no repair).
46
49
  * @param {unknown} shape @param {unknown} r @returns {boolean}
47
50
  */
48
51
  export function validReading(shape, r) {
49
- if (shape !== 'time' && shape !== 'money') return false;
52
+ if (!canReadLimit(shape)) return false;
50
53
  if (!isRec(r) || !FACT_OPS.includes(r.op)) return false;
51
54
  const keys = Object.keys(r).sort().join();
52
55
  return r.op === 'between' ? keys === 'hi,lo,op' && boundOk(shape, r.lo) && boundOk(shape, r.hi) : keys === 'op,value' && boundOk(shape, r.value);
@@ -220,7 +223,7 @@ export function applyPageRules(text, mapping, jobLines) {
220
223
  }
221
224
  pending.push({ f, kept, cur: [], uni: [] });
222
225
  } else if (VALUE_SHAPES.includes(String(f.shape))) {
223
- const amount = f.shape === 'money' || f.shape === 'number';
226
+ const amount = isAmountShape(f.shape);
224
227
  /** labels the page holds (and, for an amount, that have a number right after them) */
225
228
  const labels = [];
226
229
  /** the AI's labels as U1 leaves them, a word the page does not hold included: the first of these is R1's reference */
@@ -11,7 +11,7 @@
11
11
  // card.json the typed card fields (what the human typed; never a key — checkCard refuses one)
12
12
  // prose.txt the prose file `fwdloop draft` reads, built from the card by `cardToProse` (src/panel/authorcard.js)
13
13
  // child.log the child's stdout+stderr, mode 0600 (quoted to the page only after `scrub`)
14
- // pid.json { pid, procStart } written right after the spawn; the ONE liveness fact (`isFwdloopAlive`, M4c)
14
+ // pid.json { pid, procStart } written right after the spawn; the ONE liveness fact (`childState` in spawn.js, M4c / M20 am3 item 8)
15
15
  // draft/ the CLI's own output (spec.hash, readout.txt, log.json, spend.jsonl, draft-spend.json ...)
16
16
  // card-<n>.json the card as the human submitted it for revise <n> (M4e amendment 14 item 2), written by `revise`, write-once ('wx'), never a key
17
17
  // prose-<n>.txt the prose file built from card-<n>.json (the ONE `cardToProse`); the model gets this card only, never the old plan
@@ -37,16 +37,15 @@ import { userInfo } from 'node:os';
37
37
  import { dirname, join } from 'node:path';
38
38
  import { fileURLToPath } from 'node:url';
39
39
 
40
- import {
41
- ANSWER_FILE, NOT_CHECKED_FILE, OPEN_QUESTION_SAY, PANEL_DRAFTS_DIR, claimPlanDir, readQuestions, readoutHeadIndexes, scrub, signDraft, writePlanFiles,
42
- } from '../authoring.js';
40
+ import { OPEN_QUESTION_SAY, PANEL_DRAFTS_DIR, claimPlanDir, readTargetName, readoutHeadIndexes, signDraft, writePlanFiles } from '../authoring.js';
41
+ import { ANSWER_FILE, draftVerdict, readQuestions, readNotCheckedFile, readCard, cardFileName, readRedraftMarker, redraftFileName, readPlanTexts, scrub } from '../draftfiles.js';
43
42
  import { rowEditPlan } from '../planrebuild.js';
44
43
  import { cardLinesOf } from '../checklistsign.js';
45
44
  import { appendSpendRow } from '../provider.js';
46
45
  import { ruleOfAnswer, panelQuestionText, DROP_IT, TIE_PICK_SAY } from '../pageask.js';
47
- import { checkFlowName, nextRunId, readFileInside, readdirInside } from '../flow.js';
46
+ import { checkFlowName, nextRunId, readJsonFile, readDraftLog } from '../flow.js';
47
+ import { readFileInside, readdirInside } from '../inside.js';
48
48
  import { readModelRecord } from '../flowmodel.js';
49
- import { isFwdloopAlive } from '../liveness.js';
50
49
  import {
51
50
  checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
52
51
  } from '../monthly.js';
@@ -55,16 +54,16 @@ import {
55
54
  } from './authorcard.js';
56
55
  import { checkedLines, notCheckedView } from '../checked.js';
57
56
  import { EVERY_STEP_TEXTS } from '../try-checks.js';
58
- import { recordPath, RECORD_FILE, KEPT_WORDS } from '../pickrecord.js';
57
+ import { recordPath, RECORD_FILE, KEPT_WORDS, readKept, isRowChoice } from '../pickrecord.js';
59
58
  import { csvRolesOf } from '../sheetblock.js';
60
59
  import {
61
60
  readPriceConfig, resolveSlot, resolveUsableModel, tickedLines,
62
61
  } from '../provider.js';
63
62
  import { thinkingSupport as bareagentThinkingSupport, THINKING_FIXED_SAY, THINKING_UNVERIFIED_SAY } from '../thinking.js';
64
63
  import { parseSignedText } from '../signed-text.js';
65
- import { draftStepList, reviseStepList } from '../draft-steps.js';
64
+ import { draftStepList, reviseStepList, CARD_RE, LOG_TAIL_CHARS, draftLogName } from '../draft-steps.js';
66
65
  import {
67
- capTooSmallText, draftingSpent, EARLIER_MISSING_SAY, potSplit, STARTED_OVER_FILE, usdText,
66
+ capTooSmallText, draftedLine, draftingSpent, EARLIER_MISSING_SAY, potSplit, STARTED_OVER_FILE, STEP_LINE_PREFIXES, usdText, withDraftTimes,
68
67
  } from '../draftspend.js';
69
68
  import { jobKeyOfCard } from '../jobkey.js';
70
69
  import { flowValues, valuesHash, parseWaitMs } from '../runvalues.js';
@@ -75,27 +74,31 @@ import { createTriggerDoor } from './authortrigger.js';
75
74
  import { createResumeDoor } from './authorresume.js';
76
75
  import { createStarter } from './authorstart.js';
77
76
  import {
78
- childRunning as childRunningNow, providerKeys, readJsonFile, spawnDetached, writePidFile,
77
+ childAlive, childRunning as childRunningNow, childState, providerKeys, spawnDetached, writePidFile,
79
78
  } from './spawn.js';
80
79
 
81
80
  const HERE = dirname(fileURLToPath(import.meta.url));
82
81
  const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
82
+ /** M19 am14b: the prefix of the one log line `bin/fwdloop`'s `refuseDraft` writes (JSON `{box, words}`). */
83
+ const REFUSAL_RECORD = 'fwdloop: refusal-record ';
83
84
 
84
85
  /** A draft id: `d-` + the start time in base 36 (so ids sort oldest to newest) + 4 random hex. */
85
86
  const ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
86
87
  const newId = () => `d-${Date.now().toString(36).padStart(10, '0')}-${randomBytes(2).toString('hex')}`;
87
88
  /** The phases that end a card's life: Abandon or a sign. Everything else is still on the card (to read, to sign, to retry). */
88
89
  const FINISHED = new Set(['abandoned', 'signed']);
89
- const LOG_TAIL_CHARS = 1500;
90
90
  const STOPPED_SAY = 'The draft process ended before it finished (it was stopped from outside). Nothing was signed and nothing was sent. Draft again.';
91
91
  /** M6 am9: written once into a draft folder when the draft is a red run's redraft of an UNCHANGED job: `{flow, fromRun}`. Sign reads it; nothing else decides. */
92
92
  const RUN_OF_FILE = 'run-of.json';
93
93
  const RED_SAY = 'The drafter\'s plan did not pass the checks. Nothing was signed and nothing was sent. Fix the job and draft again; this draft is kept on disk and is never reused.';
94
94
  /** Up to 2 revises per draft (amendment 14 item 3); a revise is used once its `draft-<n>/` exists (a refusal at $0 makes none). */
95
95
  export const MAX_REVISES = 2;
96
- const CARD_RE = /^card-(\d+)\.json$/;
96
+ /** M20 am8a: the phases in which a revise or the redraft after the human's answers is running over an existing plan (a first draft is `drafting`: another refusal). The panel hands the list to the page. */
97
+ export const REVISE_PHASES = Object.freeze(['revising', 'redrafting']);
98
+ /** M20 am8a: the phases where the draft ended not green, red or stopped (the card is open to fix and draft again). The panel hands the list to the page. */
99
+ export const NOT_GREEN_PHASES = Object.freeze(['red', 'stopped']);
97
100
  /** The phases in which a draft child is running (a first draft, a revise, or the redraft after the human's answers). */
98
- const LIVE_PHASES = new Set(['drafting', 'revising', 'redrafting']);
101
+ const LIVE_PHASES = new Set(['drafting', ...REVISE_PHASES]);
99
102
  const ANSWERS_NOT_DRAFTED_SAY = 'Your answers are saved, but the plan was not drafted again with them (the process did not start). Nothing was signed. Draft again from the card.';
100
103
  const REDRAFT_RED_SAY = 'The plan drafted with your answers did not pass the checks. Nothing can be signed until a plan is green. Your answers are kept in the card: change it and draft again.';
101
104
  const BLANK_ANSWER_SAY = 'Write an answer. A question can\'t be skipped; the plan waits for it.';
@@ -138,7 +141,6 @@ export function createAuthor(opts) {
138
141
  try { return join(realpathSync(root), PANEL_DRAFTS_DIR); } catch { return null; }
139
142
  };
140
143
 
141
- const readJson = readJsonFile;
142
144
  /** every file text scrubbed of the keys, as the draft child writes them @param {Record<string, string>} files @param {string[]} keys */
143
145
  const scrubbed = (files, keys) => Object.fromEntries(Object.entries(files).map(([f, t]) => [f, scrub(t, keys)]));
144
146
  const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -161,10 +163,44 @@ export function createAuthor(opts) {
161
163
  * @param {string} dir the draft folder @param {string} id @param {string[]} keys
162
164
  */
163
165
  function readDraft(dir, id, keys) {
164
- const card = readJson(dir, 'card.json');
166
+ const v = readDraftState(dir, id, keys);
167
+ // M20 am1 items 5-6: the times of every draft's list (the first, each revise and answer redraft: each reads its own child log) and the session's "Drafted in" line,
168
+ // from the step lines (src/draftspend.js, the one owner); an old draft has none
169
+ const sc = (x) => scrub(String(x), keys);
170
+ const out = { ...v };
171
+ if ((v.phase === 'drafting' || Array.isArray(v.stepList)) && !(v.phase === 'questions-open' && v.plan !== 'draft')) {
172
+ // `stepList` is the FIRST draft's list in every phase but an open question on a later plan (that one is its own plan's list, which child.log does not hold)
173
+ const timed = withDraftTimes({ dir, running: v.phase === 'drafting', list: Array.isArray(v.stepList) ? v.stepList : null });
174
+ if (timed.list !== null) out.stepList = timed.list.map((l) => ({ ...l, label: sc(l.label) }));
175
+ if (timed.draftSoFar !== null) out.draftSoFar = timed.draftSoFar;
176
+ }
177
+ if (Array.isArray(v.revises)) {
178
+ out.revises = v.revises.map((rv) => {
179
+ const file = draftLogName(rv.kind, rv.n);
180
+ if (rv.phase === 'running') {
181
+ const t = withDraftTimes({ dir, file, running: true, list: null });
182
+ if (t.draftSoFar !== null) out.draftSoFar = t.draftSoFar;
183
+ return t.list === null ? rv : { ...rv, lines: t.list.map((l) => ({ ...l, label: sc(l.label) })) };
184
+ }
185
+ if (!Array.isArray(rv.lines)) return rv;
186
+ return { ...rv, lines: withDraftTimes({ dir, file, running: false, list: rv.lines, wholeId: 'plan' }).list };
187
+ });
188
+ }
189
+ if (v.phase === 'green') {
190
+ // the money is the session's drafting spend from the one session reader; a session none of whose plans knew its cost shows no line (never a number made of ceilings)
191
+ const known = readdirInside(dir, '.').some((n) => (n === 'draft' || PLAN_DIR_RE.test(n)) && typeof readDraftLog(dir, n)?.costUsd === 'number');
192
+ const spent = draftingSpent(dir, { ceilingUsd: capFloorFor(true, home, v.card) });
193
+ const line = draftedLine({ dir, spentUsd: known ? spent.usd : null, complete: spent.complete });
194
+ if (line !== null) out.draftedLine = line;
195
+ }
196
+ return out;
197
+ }
198
+
199
+ function readDraftState(dir, id, keys) {
200
+ const card = readCard(dir);
165
201
  const base = { draftId: id, card };
166
- if (readJson(dir, 'abandoned.json')) return { ...base, phase: 'abandoned' };
167
- const signed = readJson(dir, 'signed.json');
202
+ if (readJsonFile(dir, 'abandoned.json')) return { ...base, phase: 'abandoned' };
203
+ const signed = readJsonFile(dir, 'signed.json');
168
204
  if (signed) return { ...base, phase: 'signed' };
169
205
 
170
206
  // C9: ask "is it still running" FIRST, then read the result. A child that finishes between the two reads is then seen as finished
@@ -177,13 +213,29 @@ export function createAuthor(opts) {
177
213
  if (first) return { ...base, ...first };
178
214
  // no result yet: the child is the only thing that can still produce one
179
215
  if (running) return { ...base, phase: 'drafting' };
180
- return { ...base, phase: 'stopped', say: logTail(dir, 'child.log', keys) || STOPPED_SAY };
216
+ return { ...base, phase: 'stopped', say: logTail(dir, 'child.log', keys) || STOPPED_SAY, refusal: refusalOf(dir, 'child.log', keys) };
181
217
  }
182
218
 
183
219
  /** The tail of a child's log, scrubbed and without its `fwdloop: ` prefix; '' when there is none. */
184
220
  function logTail(dir, rel, keys) {
185
221
  const logText = readFileInside(dir, rel);
186
- return logText.ok ? scrub(logText.text, keys).trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
222
+ // the typed refusal record (`refusalOf` reads it) is machine text, never part of what the person is told
223
+ return logText.ok ? scrub(logText.text, keys).split('\n').filter((l) => !l.startsWith(REFUSAL_RECORD) && !STEP_LINE_PREFIXES.some((p) => l.startsWith(p))).join('\n').trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
224
+ }
225
+
226
+ /**
227
+ * M19 am14b: the typed refusal `{box, words}` the child's `refuseDraft` wrote as its last `fwdloop: refusal-record {...}` log line (scrubbed), or null when the child
228
+ * stopped for any other reason. The box is what the refusing check named; the words are never read to find it. `say` stays the whole tail.
229
+ */
230
+ function refusalOf(dir, rel, keys) {
231
+ const log = readFileInside(dir, rel);
232
+ if (!log.ok) return null;
233
+ const lines = scrub(log.text, keys).split('\n').filter((l) => l.startsWith(REFUSAL_RECORD));
234
+ if (lines.length === 0) return null;
235
+ try {
236
+ const r = JSON.parse(lines[lines.length - 1].slice(REFUSAL_RECORD.length));
237
+ return { box: typeof r.box === 'string' ? r.box : null, words: String(r.words) };
238
+ } catch { return null; }
187
239
  }
188
240
 
189
241
  /**
@@ -193,8 +245,8 @@ export function createAuthor(opts) {
193
245
  * @param {string} dir @param {string} rel @param {string[]} keys @param {boolean} [questionOpen]
194
246
  */
195
247
  function stepListOf(dir, rel, keys, questionOpen = false) {
196
- const declaration = readJson(dir, `${rel}/declaration.json`) ?? readJson(dir, `${rel}/declaration.rejected.json`);
197
- const list = draftStepList({ log: readJson(dir, `${rel}/log.json`), declaration, questionOpen });
248
+ const declaration = readJsonFile(dir, `${rel}/declaration.json`) ?? readJsonFile(dir, `${rel}/declaration.rejected.json`);
249
+ const list = draftStepList({ log: readDraftLog(dir, rel), declaration, questionOpen });
198
250
  if (list === null) return null;
199
251
  const sc = (x) => scrub(String(x), keys);
200
252
  return list.map((st) => ({ ...st, label: sc(st.label), details: st.details.map(sc) }));
@@ -227,18 +279,14 @@ export function createAuthor(opts) {
227
279
  * @returns {any}
228
280
  */
229
281
  function resultOf(dir, rel, keys) {
230
- const hashFile = readFileInside(dir, `${rel}/spec.hash`);
231
- if (hashFile.ok && hashFile.text.trim() !== '') {
282
+ const v = draftVerdict(dir, rel);
283
+ if (v.verdict === 'green') {
232
284
  const readout = readFileInside(dir, `${rel}/readout.txt`);
233
285
  const text = readout.ok ? scrub(readout.text, keys) : '';
234
- return { phase: 'green', hash: hashFile.text.trim(), readout: text, readoutHeads: readoutHeadIndexes(text), stepList: stepListOf(dir, rel, keys) };
286
+ return { phase: 'green', hash: v.hash, readout: text, readoutHeads: readoutHeadIndexes(text), stepList: stepListOf(dir, rel, keys) };
235
287
  }
236
- const leak = readFileInside(dir, `${rel}/scrub-leak.red`);
237
- const log = readJson(dir, `${rel}/log.json`);
238
- if (leak.ok || (log && log.ok === false)) {
239
- const reds = Array.isArray(log?.reds) ? log.reds.map((r) => scrub(String(r), keys)) : [];
240
- if (leak.ok) reds.push(scrub(leak.text.trim(), keys));
241
- return { phase: 'red', reds, say: RED_SAY, stepList: stepListOf(dir, rel, keys) };
288
+ if (v.verdict === 'red') {
289
+ return { phase: 'red', reds: v.reds.map((r) => scrub(r, keys)), say: RED_SAY, stepList: stepListOf(dir, rel, keys) };
242
290
  }
243
291
  return null;
244
292
  }
@@ -255,36 +303,37 @@ export function createAuthor(opts) {
255
303
  function withRevises(base, dir, first, keys, firstQsRead) {
256
304
  const names = readdirInside(dir, '.');
257
305
  const ns = names.map((n) => CARD_RE.exec(n)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
258
- const redrafts = new Set(ns.filter((n) => readJson(dir, `redraft-${n}.json`) !== null));
306
+ const redrafts = new Set(ns.filter((n) => readRedraftMarker(dir, n) !== null));
259
307
  const used = names.filter((n) => PLAN_DIR_RE.test(n) && !redrafts.has(Number(PLAN_DIR_RE.exec(n)?.[1]))).length;
260
308
  const revisesLeft = Math.max(0, MAX_REVISES - used);
261
309
  const newest = ns.length > 0 ? ns[ns.length - 1] : 0;
262
- const card = newest > 0 ? (readJson(dir, `card-${newest}.json`) ?? base.card) : base.card;
310
+ const card = newest > 0 ? (readCard(dir, newest) ?? base.card) : base.card;
263
311
  let reviseNo = 0;
264
312
  const revises = ns.map((n) => {
265
313
  const kind = redrafts.has(n) ? 'answers' : 'revise';
266
314
  if (kind === 'revise') reviseNo += 1;
267
315
  // M4d am15 (every line of the list): this plan's own line, from its own log, built by `reviseStepList`; the try history is in the Audit Draft group
268
- const rowEdit = kind === 'answers' ? readJson(dir, `redraft-${n}.json`)?.rowEdit : undefined;
316
+ const rowEdit = kind === 'answers' ? readRedraftMarker(dir, n)?.rowEdit : undefined;
269
317
  const name = rowEdit ? (rowEdit.op === 'drop' ? 'a check dropped' : 'a check added') : kind === 'answers' ? 'drafted again with your answers' : `revise ${reviseNo}`;
270
318
  const running = n === newest && childRunning(dir); // C9: running first, then the result
271
319
  // the result BEFORE the log: the child writes log.json first and the result (spec.hash, or the red log itself) after, so a result we see has its log already on disk
272
320
  const res = resultOf(dir, `draft-${n}`, keys);
273
- const lines = reviseStepList({ log: readJson(dir, `draft-${n}/log.json`), name });
321
+ const lines = reviseStepList({ log: readDraftLog(dir, `draft-${n}`), name });
274
322
  const scrubbed = lines === null ? null : lines.map((l) => ({ ...l, label: scrub(l.label, keys) }));
275
323
  if (res && res.phase === 'green') return { n, kind, phase: 'green', hash: res.hash, name, lines: scrubbed };
276
324
  if (res) return { n, kind, phase: 'red', reds: res.reds, say: kind === 'answers' ? REDRAFT_RED_SAY : REVISE_RED_SAY, name, lines: scrubbed };
277
325
  if (running) return { n, kind, phase: 'running', name };
278
- return { n, kind, name, phase: 'stopped', say: logTail(dir, `${kind === 'answers' ? 'redraft' : 'revise'}-${n}.log`, keys) || STOPPED_SAY };
326
+ const logRel = draftLogName(kind, n);
327
+ return { n, kind, name, phase: 'stopped', say: logTail(dir, logRel, keys) || STOPPED_SAY, refusal: refusalOf(dir, logRel, keys) };
279
328
  });
280
- const cur = /** @type {{ phase: string, kind: string, say?: string }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
329
+ const cur = /** @type {{ phase: string, kind: string, say?: string, refusal?: {box: string|null, words: string} | null }} */ (newest > 0 ? revises[revises.length - 1] : { phase: first.phase, kind: 'first' });
281
330
  // a first plan that asked questions did not end red, it ended by asking (open or answered): its plan-checks line is never the red one (am15 item 3)
282
331
  const firstQs = firstQsRead ?? readQuestions(join(dir, 'draft')); // the first plan's questions, read once per poll
283
332
  const asked = firstQs.questions.length > 0;
284
333
  const shared = { ...base, card, revises, revisesLeft, stepList: asked ? stepListOf(dir, 'draft', keys, true) : (first.stepList ?? null) };
285
334
  const rel = newest > 0 ? `draft-${newest}` : 'draft';
286
335
  if (cur.phase === 'running') return { ...shared, phase: cur.kind === 'answers' ? 'redrafting' : 'revising' };
287
- if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say };
336
+ if (cur.phase === 'stopped') return { ...shared, phase: 'stopped', say: cur.say, refusal: cur.refusal ?? null };
288
337
  const res = newest > 0 ? resultOf(dir, rel, keys) : first;
289
338
  // the plan's questions: any open one makes the phase `questions-open`, whatever colour the plan is (the answers are what it was waiting for)
290
339
  const q = rel === 'draft' ? firstQs : readQuestions(join(dir, rel));
@@ -319,14 +368,14 @@ export function createAuthor(opts) {
319
368
  id, dir, v, vet, env, marker, argvOf, failSay, undoToo = [],
320
369
  }) {
321
370
  const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
322
- const files = [`card-${n}.json`, `prose-${n}.txt`, `redraft-${n}.json`].map((f) => join(dir, f));
371
+ const files = [cardFileName(n), `prose-${n}.txt`, redraftFileName(n)].map((f) => join(dir, f));
323
372
  const undo = () => { for (const f of [...files, ...undoToo]) rmSync(f, { force: true }); };
324
373
  let child;
325
374
  try {
326
375
  writeFileSync(files[0], `${JSON.stringify(vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
327
376
  writeFileSync(files[1], vet.prose, { mode: 0o600, flag: 'wx' });
328
377
  writeFileSync(files[2], `${JSON.stringify(marker)}\n`, { mode: 0o600, flag: 'wx' });
329
- child = spawnDetached({ bin, argv: argvOf(n, files[1], realpathSync(root)), env, logPath: join(dir, `redraft-${n}.log`) });
378
+ child = spawnDetached({ bin, argv: argvOf(n, files[1], realpathSync(root)), env, logPath: join(dir, draftLogName('answers', n)) });
330
379
  } catch (e) {
331
380
  undo();
332
381
  return { status: 500, body: { ok: false, refused: 'spawn', say: failSay(String(/** @type {any} */ (e)?.code ?? 'error')), draftId: id } };
@@ -347,19 +396,17 @@ export function createAuthor(opts) {
347
396
  * "Not checked" (the drafter's own list, always with its label). Read-only; neither is signed or in the hash. @param {string} dir @param {string} rel
348
397
  */
349
398
  function planChecks(dir, rel) {
350
- const decl = readJson(dir, `${rel}/declaration.json`);
351
- const prose = readFileInside(dir, `${rel}/prose.txt`);
352
- const parsed = prose.ok ? parseSignedText(prose.text) : null;
353
- const kept = readJson(dir, `${rel}/${RECORD_FILE}`)?.kept;
399
+ const { declaration: decl, parsed } = readPlanTexts(dir, rel);
400
+ const kept = readKept(dir, rel).kept;
354
401
  const opts = {
355
402
  ...(parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line), lines: parsed.lines, csvRoles: csvRolesOf(parsed.arbiter) } : { hasAsk: true }),
356
403
  ...(Array.isArray(kept) ? { keptChecks: kept.filter((k) => k && k.check).map((k) => ({ line: k.line, check: k.check })), keptWords: KEPT_WORDS } : {}),
357
404
  };
358
- const ncFile = readJson(dir, `${rel}/${NOT_CHECKED_FILE}`);
359
- const view = notCheckedView(ncFile?.notChecked, decl);
405
+ const ncFile = readNotCheckedFile(dir, rel);
406
+ const view = notCheckedView(ncFile.notChecked, decl);
360
407
  // M16 item 5: the plan card's list - the rows with their tags and Drop, the suggestions with Add - read from the card the draft saved (src/cardlist.js); a plan without a list has none
361
408
  // M19 am6: a saved draft with a signed list draws its card rows read from the plan (a card saved with the old words is rebuilt); the suggestions, the restorable rows and the Drop flags are the saved card's
362
- const savedLog = cardLinesOf(decl).size > 0 ? readJson(dir, `${rel}/log.json`) : undefined;
409
+ const savedLog = cardLinesOf(decl).size > 0 ? readDraftLog(dir, rel) : undefined;
363
410
  const card = savedLog?.checkCard && parsed?.ok === true && Array.isArray(savedLog.checkCard.rows)
364
411
  ? planCard(savedLog.checkCard, { declaration: decl, lines: parsed.lines, csvRoles: csvRolesOf(parsed.arbiter), kept: Array.isArray(kept) ? kept.filter((/** @type {any} */ k) => k && Number.isInteger(k.line)) : [], log: savedLog.log })
365
412
  : savedLog?.checkCard;
@@ -367,17 +414,17 @@ export function createAuthor(opts) {
367
414
  // M16 P4c (bareloop's plan view): the job's lines with their `~` rules (the signed text's own, split at its "; " joins) and the two checks every step has; a plan with a list draws them
368
415
  const planLines = parsed?.ok === true ? parsed.lines.map((/** @type {any} */ l) => ({ n: l.n, text: l.text, rules: l.guardrail ? l.guardrail.split('; ') : [] })) : [];
369
416
  // M13 am11: the job's action (its last line, when the AI named it or the person agreed or typed it), drawn as `› line <n> writes everything before it [agent]` (no Drop, am11c)
370
- const act = readJson(dir, `${rel}/log.json`)?.action;
417
+ const act = readDraftLog(dir, rel)?.action;
371
418
  const action = isObj(act) && Number.isInteger(act.line) && act.dropped !== true ? { line: act.line, ...(act.by === 'agent' || act.by === 'you' ? { by: act.by } : {}) } : null;
372
419
  return {
373
- ...(action ? { action } : {}), checked: checkedLines(decl, opts), notChecked: { ...view, ...(isObj(ncFile?.by) ? { by: ncFile.by } : {}), rows: ncRowsOf(view.items, isObj(ncFile?.by) ? ncFile.by : {}) }, ...(list ? { list, planLines, always: [...EVERY_STEP_TEXTS] } : {}),
420
+ ...(action ? { action } : {}), checked: checkedLines(decl, opts), notChecked: { ...view, ...(ncFile.by ? { by: ncFile.by } : {}), rows: ncRowsOf(view.items, ncFile.by ?? {}) }, ...(list ? { list, planLines, always: [...EVERY_STEP_TEXTS] } : {}),
374
421
  };
375
422
  }
376
423
 
377
424
  /** The answers an answer-redraft was drafted with, as the marker recorded them: `[{ line, lineText, question, answer }]` (scrubbed). @param {string} dir @param {number} n @param {string[]} keys */
378
425
  function answersOf(dir, n, keys) {
379
- const rec = readJson(dir, `redraft-${n}.json`);
380
- const card = readJson(dir, `card-${n}.json`);
426
+ const rec = readRedraftMarker(dir, n);
427
+ const card = readCard(dir, n);
381
428
  const steps = parseJobBox(typeof card?.job === 'string' ? card.job : '').steps;
382
429
  return (Array.isArray(rec?.answers) ? rec.answers : []).map((a) => ({
383
430
  line: a.line, lineText: steps[a.line - 1]?.text ?? null, question: scrub(String(a.question), keys), answer: scrub(String(a.answer), keys),
@@ -416,8 +463,8 @@ export function createAuthor(opts) {
416
463
  // amendments 24/25: a plan with a question open is never signed from here; signDraft refuses it again from the plan folder (the same check)
417
464
  if (v.phase === 'questions-open') return no(409, 'question-open', OPEN_QUESTION_SAY);
418
465
  if (v.phase !== 'green') return no(409, 'not-green', `This draft is ${v.phase}, not a finished plan, so it cannot be signed.`);
419
- const name = readJson(dir, `${v.plan}/target.json`)?.name;
420
- if (typeof name !== 'string') return no(409, 'no-name', 'The draft has no readable flow name. Nothing was signed.');
466
+ const name = readTargetName(join(dir, v.plan));
467
+ if (name === null) return no(409, 'no-name', 'The draft has no readable flow name. Nothing was signed.');
421
468
  return {
422
469
  ok: true, v: /** @type {any} */ (v), name, dir,
423
470
  };
@@ -607,7 +654,7 @@ export function createAuthor(opts) {
607
654
  mkdirSync(dd, { recursive: true, mode: 0o700 });
608
655
  mkdirSync(dir, { mode: 0o700 });
609
656
  const proseFile = join(dir, 'prose.txt');
610
- writeFileSync(join(dir, 'card.json'), `${JSON.stringify(card, null, 2)}\n`, { mode: 0o600 });
657
+ writeFileSync(join(dir, cardFileName()), `${JSON.stringify(card, null, 2)}\n`, { mode: 0o600 });
611
658
  // amendment 14 item 6: a Start over names the draft it started over from; write-once, here only. An id that is not one of this panel's drafts is ignored.
612
659
  const from = body?.startedOverFrom;
613
660
  if (typeof from === 'string' && ID_RE.test(from) && listIds().includes(from)) {
@@ -681,16 +728,14 @@ export function createAuthor(opts) {
681
728
  }
682
729
  const signedBy = userInfo().username;
683
730
  // M6 am9: a red run's redraft of an unchanged job is signed as the plan of a NEW run of the same workflow (the workflow's files are not written)
684
- const runOfRec = readJson(dir, RUN_OF_FILE);
731
+ const runOfRec = readJsonFile(dir, RUN_OF_FILE);
685
732
  const asRunOf = typeof runOfRec?.flow === 'string' ? { flow: runOfRec.flow } : undefined;
686
733
  if (asRunOf !== undefined && runId !== '') return { status: 400, body: { ok: false, refused: 'run-id', say: 'This plan becomes the next run of its workflow by itself; a run name cannot be typed. Nothing was signed.' } };
687
734
  // M13 piece 5 (signed item 7): the card's Schedule row is checked now, on the plan about to be signed, so a refusal never leaves a signed job without its schedule. A plan that becomes the next
688
735
  // run of its workflow signs no job, so it signs no schedule: the workflow keeps the one it has.
689
736
  let cardSchedule = null;
690
737
  if (asRunOf === undefined && v.card.schedule) {
691
- const planProse = readFileInside(join(dir, v.plan), 'prose.txt');
692
- const planDecl = readJson(join(dir, v.plan), 'declaration.json');
693
- const parsedPlan = planProse.ok ? parseSignedText(planProse.text) : null;
738
+ const { declaration: planDecl, parsed: parsedPlan } = readPlanTexts(join(dir, v.plan));
694
739
  if (!parsedPlan || !parsedPlan.ok || !planDecl) return { status: 409, body: { ok: false, refused: 'schedule', say: 'The plan could not be read to check its schedule. Nothing was signed.' } };
695
740
  const planned = triggerDoor.cardSchedule(v.card.schedule, { arbiter: parsedPlan.arbiter, declaration: planDecl });
696
741
  if (!planned.ok) return { status: 400, body: { ok: false, refused: 'schedule', say: planned.say } };
@@ -712,8 +757,7 @@ export function createAuthor(opts) {
712
757
  let values = null;
713
758
  // M13 am11a 2: a job with an action and no Ask line keeps the card's Ask wait (the stop before the action waits that long) in the same signed values as the Destination and the Cap
714
759
  const cardWait = typeof v.card?.askWait === 'string' ? v.card.askWait.trim().toLowerCase() : '';
715
- const proseNow = readFileInside(join(dir, v.plan), 'prose.txt');
716
- const parsedNow = proseNow.ok ? parseSignedText(proseNow.text) : null;
760
+ const parsedNow = readPlanTexts(join(dir, v.plan)).parsed;
717
761
  const actionWait = parsedNow && parsedNow.ok && parsedNow.arbiter.asks.length === 0 && parsedNow.arbiter.sends.length === 1 && parseWaitMs(cardWait) !== null ? { line: String(parsedNow.arbiter.sends[0].line), wait: cardWait } : null;
718
762
  if (pot.split.spentUsd > 0 || (actionWait !== null && parseWaitMs(actionWait.wait) !== DEFAULT_ACTION_WAIT_MS)) {
719
763
  const parsed = parsedNow;
@@ -751,14 +795,14 @@ export function createAuthor(opts) {
751
795
  const dir = dd === null ? null : join(dd, id);
752
796
  const v = dir === null ? null : /** @type {any} */ (readDraft(dir, id, keys));
753
797
  if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
754
- if (v.phase === 'revising' || v.phase === 'redrafting') return { status: 409, body: { ok: false, refused: 'draft-live', say: 'A plan is already being drafted. Wait for it.' } };
798
+ if (REVISE_PHASES.includes(v.phase)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'A plan is already being drafted. Wait for it.' } };
755
799
  if (v.phase === 'questions-open') return { status: 409, body: { ok: false, refused: 'question-open', say: 'A question the plan raised is still open. Answer it first; it is not a revise.' } };
756
800
  // only a draft whose first plan was green has revises (`withRevises` is the one reader that sets them)
757
801
  if (!Array.isArray(v.revises)) return { status: 409, body: { ok: false, refused: 'not-revisable', say: `This draft is ${v.phase}, so it cannot be revised. Draft again from the card.` } };
758
802
  if (v.revisesLeft <= 0) return { status: 409, body: { ok: false, refused: 'no-revises-left', say: `This draft has used its ${MAX_REVISES} revises. Start over: it keeps the fields and gives ${MAX_REVISES} new revises.` } };
759
803
  if (childRunning(dir)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'The draft process is still finishing. Try again in a moment.' } };
760
804
  if (draftingSpent(dir).missingEarlier) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
761
- const vet = vetCard(body, loaded, draftedSoFar(dir, v.card), readJson(dir, RUN_OF_FILE)?.flow);
805
+ const vet = vetCard(body, loaded, draftedSoFar(dir, v.card), readJsonFile(dir, RUN_OF_FILE)?.flow);
762
806
  if (!vet.ok) return vet.reply;
763
807
  for (const other of listIds()) {
764
808
  if (other === id) continue;
@@ -769,7 +813,7 @@ export function createAuthor(opts) {
769
813
  }
770
814
  const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
771
815
  const proseFile = join(dir, `prose-${n}.txt`);
772
- writeFileSync(join(dir, `card-${n}.json`), `${JSON.stringify(vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
816
+ writeFileSync(join(dir, cardFileName(n)), `${JSON.stringify(vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
773
817
  writeFileSync(proseFile, vet.prose, { mode: 0o600, flag: 'wx' });
774
818
  let child;
775
819
  try {
@@ -777,7 +821,7 @@ export function createAuthor(opts) {
777
821
  bin,
778
822
  argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName, ...carryArgv(dir, v.revises.map((x) => x.n)), ...modelArgv(vet.card), ...actionArgv(vet.card)],
779
823
  env: loaded.env,
780
- logPath: join(dir, `revise-${n}.log`),
824
+ logPath: join(dir, draftLogName('revise', n)),
781
825
  });
782
826
  } catch (e) {
783
827
  return { status: 500, body: { ok: false, refused: 'spawn', say: `The revise could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was spent.`, draftId: id } };
@@ -857,7 +901,7 @@ export function createAuthor(opts) {
857
901
  const jobWithAction = act !== undefined && act.action === 'known' && typeof act.actionLine === 'string' && act.actionLine !== '' ? `${baseJob.replace(/\s+$/, '')}\n${act.actionLine}` : baseJob;
858
902
  const grown = applyAnswers(jobWithAction, all);
859
903
  if (grown.added !== adds.length) return { status: 409, body: { ok: false, refused: 'no-such-line', say: 'An answer is about a job line the card no longer has. Draft again from the card. Nothing was signed.' } };
860
- const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card), readJson(dir, RUN_OF_FILE)?.flow);
904
+ const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card), readJsonFile(dir, RUN_OF_FILE)?.flow);
861
905
  if (!vet.ok) return vet.reply;
862
906
  for (const other of listIds()) {
863
907
  if (other === id) continue;
@@ -901,12 +945,12 @@ export function createAuthor(opts) {
901
945
  if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
902
946
  if (v.phase !== 'green' || typeof v.plan !== 'string' || !Array.isArray(v.revises)) return { status: 409, body: { ok: false, refused: 'not-green', say: `This draft is ${v.phase}, not a finished plan, so its checks cannot be changed.` } };
903
947
  const b = body && typeof body === 'object' ? body : {};
904
- if (b.op !== 'drop' && b.op !== 'add') return { status: 400, body: { ok: false, refused: 'bad-choice', say: 'That is not one of the choices. Nothing was changed.' } };
948
+ if (!isRowChoice(b.op)) return { status: 400, body: { ok: false, refused: 'bad-choice', say: 'That is not one of the choices. Nothing was changed.' } };
905
949
  if (typeof b.key !== 'string' || b.key === '' || b.key.length > 200) return { status: 400, body: { ok: false, refused: 'bad-row', say: 'That check is not on the list. Nothing was changed.' } };
906
950
  if (childRunning(dir)) return { status: 409, body: { ok: false, refused: 'draft-live', say: 'The draft process is still finishing. Try again in a moment.' } };
907
951
  // the plan was drafted with questions on, unless it is the redraft after answers (it never asks); a plan made by a Drop or an Add keeps the one it came from
908
952
  const cur = PLAN_DIR_RE.exec(v.plan)?.[1];
909
- const marker = cur === undefined ? null : readJson(dir, `redraft-${cur}.json`);
953
+ const marker = cur === undefined ? null : readRedraftMarker(dir, Number(cur));
910
954
  const asks = marker === null ? true : (marker.rowEdit ? marker.rowEdit.asks !== false : false);
911
955
  const planDir = join(dir, v.plan);
912
956
  const made = rowEditPlan({ planDir, op: b.op, key: b.key, asks });
@@ -914,7 +958,7 @@ export function createAuthor(opts) {
914
958
  const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
915
959
  const at = new Date().toISOString();
916
960
  const newDir = join(dir, `draft-${n}`);
917
- const prose = readFileInside(planDir, 'prose.txt');
961
+ const proseText = readPlanTexts(planDir).proseText;
918
962
  try {
919
963
  claimPlanDir(newDir);
920
964
  if (Object.keys(made.pages).length > 0) claimPlanDir(join(newDir, 'pages'));
@@ -925,8 +969,8 @@ export function createAuthor(opts) {
925
969
  kind: 'draft', provider: null, price: null, model: readModelRecord(planDir)?.model ?? null, modelReturned: null, tokens: null, costUsd: 0, rounds: 0, calls: 0, spendComplete: true, stop: null, budgetUsd: null, startedAt: at, wallMs: 0,
926
970
  });
927
971
  writePlanFiles(dir, {
928
- [`card-${n}.json`]: `${JSON.stringify(v.card, null, 2)}\n`, [`prose-${n}.txt`]: prose.ok ? prose.text : '',
929
- [`redraft-${n}.json`]: `${JSON.stringify({ fromPlan: v.plan, answers: [], rowEdit: { op: b.op, key: b.key, at, asks } })}\n`,
972
+ [cardFileName(n)]: `${JSON.stringify(v.card, null, 2)}\n`, [`prose-${n}.txt`]: proseText ?? '',
973
+ [redraftFileName(n)]: `${JSON.stringify({ fromPlan: v.plan, answers: [], rowEdit: { op: b.op, key: b.key, at, asks } })}\n`,
930
974
  }, { flag: 'wx', mode: 0o600 });
931
975
  } catch (e) {
932
976
  return { status: 500, body: { ok: false, refused: 'write', say: `The changed plan could not be saved (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was changed.` } };
@@ -960,7 +1004,7 @@ export function createAuthor(opts) {
960
1004
  },
961
1005
 
962
1006
  /**
963
- * `POST /api/author/:id/abandon`: stop the child (by its recorded pid, only after `isFwdloopAlive` says it is ours),
1007
+ * `POST /api/author/:id/abandon`: stop the child (by its recorded pid, only after `childState` says it is ours),
964
1008
  * confirm it is gone, then write `abandoned.json`. No further model call; the spend already booked stays booked.
965
1009
  * @param {string} id
966
1010
  */
@@ -972,22 +1016,21 @@ export function createAuthor(opts) {
972
1016
  const v = dir === null ? null : readDraft(dir, id, keys);
973
1017
  if (dir === null || v === null || v.card === null) return { status: 404, body: { ok: false, refused: 'no-such-draft' } };
974
1018
  if (FINISHED.has(v.phase)) return { status: 409, body: { ok: false, refused: 'not-abandonable', say: `This draft is already ${v.phase}.` } };
975
- const pid = readJson(dir, 'pid.json');
1019
+ const child = childState(dir);
976
1020
  let killed = false;
977
- if (pid && Number.isInteger(pid.pid)) {
978
- const procStart = typeof pid.procStart === 'string' ? pid.procStart : null;
979
- const alive = isFwdloopAlive(pid.pid, procStart);
1021
+ if (child) {
1022
+ const { alive } = child;
980
1023
  if (alive === null) return { status: 409, body: { ok: false, refused: 'cannot-tell', say: 'The panel cannot tell whether the draft process is still running, so it did not stop anything.' } };
981
1024
  if (alive === true) {
982
1025
  // the child leads its own process group (detached), so one signal to the group reaches it and nothing else
983
1026
  for (const { sig, wait } of [{ sig: 'SIGTERM', wait: KILL_WAIT_MS }, { sig: 'SIGKILL', wait: KILL_HARD_WAIT_MS }]) {
984
- try { process.kill(-pid.pid, /** @type {NodeJS.Signals} */ (sig)); } catch { /* already gone */ }
1027
+ try { process.kill(-child.pid, /** @type {NodeJS.Signals} */ (sig)); } catch { /* already gone */ }
985
1028
  const t0 = Date.now();
986
1029
  // eslint-disable-next-line no-await-in-loop
987
- while (isFwdloopAlive(pid.pid, procStart) === true && Date.now() - t0 < wait) await sleep(25);
988
- if (isFwdloopAlive(pid.pid, procStart) !== true) break;
1030
+ while (childAlive(child) === true && Date.now() - t0 < wait) await sleep(25);
1031
+ if (childAlive(child) !== true) break;
989
1032
  }
990
- if (isFwdloopAlive(pid.pid, procStart) === true) {
1033
+ if (childAlive(child) === true) {
991
1034
  return { status: 500, body: { ok: false, refused: 'still-running', say: 'The draft process did not stop. Nothing was marked abandoned.' } };
992
1035
  }
993
1036
  killed = true;