fwdloop 0.28.0 → 0.30.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 (74) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +27 -5
  3. package/package.json +3 -3
  4. package/src/added-end.js +60 -0
  5. package/src/ask.js +1 -1
  6. package/src/audit-fold.js +9 -1
  7. package/src/authoring.js +18 -7
  8. package/src/checked.js +14 -9
  9. package/src/checkpick.js +318 -0
  10. package/src/checkwords.js +29 -0
  11. package/src/citedcheck.js +14 -0
  12. package/src/closers.js +40 -3
  13. package/src/declaration.js +102 -5
  14. package/src/draft-steps.js +3 -3
  15. package/src/drafter.js +151 -38
  16. package/src/jobkey.js +3 -1
  17. package/src/learn.js +1 -1
  18. package/src/learnstore.js +6 -6
  19. package/src/memo.js +120 -0
  20. package/src/model-step.js +103 -25
  21. package/src/pageask.js +12 -6
  22. package/src/pagedropwords.js +9 -0
  23. package/src/panel/author.js +33 -10
  24. package/src/panel/authorcard.js +59 -6
  25. package/src/panel/data.js +16 -10
  26. package/src/panel/index.html +151 -59
  27. package/src/panel/result.js +28 -7
  28. package/src/panel/server.js +2 -1
  29. package/src/pickrecord.js +146 -0
  30. package/src/plain-checks.js +16 -3
  31. package/src/provider.js +4 -1
  32. package/src/repairs.js +38 -0
  33. package/src/runfile.js +4 -2
  34. package/src/runner.js +129 -40
  35. package/src/send.js +71 -4
  36. package/src/setup.js +13 -1
  37. package/src/sheetblock.js +2 -1
  38. package/src/ticket-draft.js +2 -2
  39. package/src/ticket-labels.js +2 -2
  40. package/src/try-checks.js +13 -3
  41. package/src/whole-job.js +71 -0
  42. package/types/added-end.d.ts +62 -0
  43. package/types/ask.d.ts +2 -1
  44. package/types/audit-fold.d.ts +13 -2
  45. package/types/authoring.d.ts +6 -2
  46. package/types/checked.d.ts +7 -2
  47. package/types/checkpick.d.ts +183 -0
  48. package/types/checkwords.d.ts +18 -0
  49. package/types/citedcheck.d.ts +6 -0
  50. package/types/closers.d.ts +6 -3
  51. package/types/declaration.d.ts +12 -0
  52. package/types/drafter.d.ts +28 -25
  53. package/types/learn.d.ts +1 -0
  54. package/types/learnstore.d.ts +2 -3
  55. package/types/memo.d.ts +15 -0
  56. package/types/model-step.d.ts +23 -3
  57. package/types/pageask.d.ts +9 -2
  58. package/types/pagedropwords.d.ts +1 -0
  59. package/types/panel/author.d.ts +1 -1
  60. package/types/panel/authorcard.d.ts +41 -0
  61. package/types/panel/data.d.ts +1 -1
  62. package/types/panel/jobgrid.d.ts +1 -1
  63. package/types/panel/result.d.ts +9 -3
  64. package/types/pickrecord.d.ts +88 -0
  65. package/types/plain-checks.d.ts +9 -1
  66. package/types/repairs.d.ts +13 -0
  67. package/types/runfile.d.ts +7 -2
  68. package/types/runner.d.ts +16 -5
  69. package/types/send.d.ts +10 -2
  70. package/types/setup.d.ts +1 -56
  71. package/types/try-checks.d.ts +1 -7
  72. package/types/whole-job.d.ts +70 -0
  73. package/src/attemptdiff.js +0 -118
  74. package/types/attemptdiff.d.ts +0 -38
@@ -46,9 +46,10 @@ import {
46
46
  checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
47
47
  } from '../monthly.js';
48
48
  import {
49
- appendAnswersToJob, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
49
+ applyAnswers, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
50
50
  } from './authorcard.js';
51
51
  import { checkedLines, notCheckedView } from '../checked.js';
52
+ import { recordPath, RECORD_FILE, KEPT_WORDS } from '../pickrecord.js';
52
53
  import { csvRolesOf } from '../sheetblock.js';
53
54
  import {
54
55
  readPriceConfig, resolveSlot, resolveUsableModel, tickedLines,
@@ -289,6 +290,18 @@ export function createAuthor(opts) {
289
290
  return { ...shared, phase: 'red', reds: res.reds, say: newest === 0 ? RED_SAY : cur.say };
290
291
  }
291
292
 
293
+ /**
294
+ * M10 am17: `--carry <record>` for a draft that follows an earlier plan. A Revise follows the newest plan folder that has a record (`draft-<n>` newest first, then `draft`);
295
+ * the redraft after the answers follows the plan that asked (`only`). No record, no flag: every guardrail is asked, as before.
296
+ * @param {string} dir @param {number[]} ns the plans' numbers @param {string} [only] the one plan folder (relative)
297
+ * @returns {string[]}
298
+ */
299
+ function carryArgv(dir, ns, only) {
300
+ const rels = only === undefined ? [...ns].sort((a, b) => b - a).map((x) => `draft-${x}`).concat('draft') : [only];
301
+ const rel = rels.find((r) => readFileInside(join(dir, r), RECORD_FILE).ok);
302
+ return rel === undefined ? [] : ['--carry', recordPath(join(dir, rel))];
303
+ }
304
+
292
305
  /**
293
306
  * What the human is shown beside a green plan at sign: "Checked" (built by `checkedLines` from the plan's typed closes, never model text) and
294
307
  * "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
@@ -297,7 +310,11 @@ export function createAuthor(opts) {
297
310
  const decl = readJson(dir, `${rel}/declaration.json`);
298
311
  const prose = readFileInside(dir, `${rel}/prose.txt`);
299
312
  const parsed = prose.ok ? parseSignedText(prose.text) : null;
300
- const opts = parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line), lines: parsed.lines, csvRoles: csvRolesOf(parsed.arbiter) } : { hasAsk: true };
313
+ const kept = readJson(dir, `${rel}/${RECORD_FILE}`)?.kept;
314
+ const opts = {
315
+ ...(parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line), lines: parsed.lines, csvRoles: csvRolesOf(parsed.arbiter) } : { hasAsk: true }),
316
+ ...(Array.isArray(kept) ? { keptChecks: kept.filter((k) => k && k.check).map((k) => ({ line: k.line, check: k.check })), keptWords: KEPT_WORDS } : {}),
317
+ };
301
318
  return { checked: checkedLines(decl, opts), notChecked: notCheckedView(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked, decl) };
302
319
  }
303
320
 
@@ -504,6 +521,8 @@ export function createAuthor(opts) {
504
521
  // an earlier draft that is gone is never counted as $0: refused here, at $0, in words
505
522
  const startedFrom = body?.startedOverFrom;
506
523
  let priorUsd = 0;
524
+ /** @type {string[]} */
525
+ let carryFrom = [];
507
526
  if (startedFrom !== undefined && startedFrom !== null && startedFrom !== '' && typeof startedFrom !== 'string') {
508
527
  return { status: 400, body: { ok: false, refused: 'started-over-from', say: 'startedOverFrom must be the id of an earlier draft (a string).' } };
509
528
  }
@@ -512,6 +531,8 @@ export function createAuthor(opts) {
512
531
  const spent = draftingSpent(join(dd, startedFrom), { ceilingUsd: capFloorFor(true, home, cardFields(body)) });
513
532
  if (spent.missingEarlier) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
514
533
  priorUsd = spent.usd;
534
+ // M10 am20: a Start over carries the picks of the plan it starts over from, through the same record path as a Revise
535
+ carryFrom = carryArgv(join(dd, startedFrom), (view(startedFrom, keys)?.revises ?? []).map((x) => x.n));
515
536
  }
516
537
  const vet = vetCard(body, loaded, priorUsd, runOf?.flow);
517
538
  if (!vet.ok) return vet.reply;
@@ -538,7 +559,7 @@ export function createAuthor(opts) {
538
559
  let child;
539
560
  try {
540
561
  child = spawnDetached({
541
- bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName, ...modelArgv(card)], env: loaded.env, logPath: join(dir, 'child.log'),
562
+ bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName, ...carryFrom, ...modelArgv(card)], env: loaded.env, logPath: join(dir, 'child.log'),
542
563
  });
543
564
  } catch (e) {
544
565
  return { status: 500, body: { ok: false, refused: 'spawn', say: `The draft could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was spent.`, draftId: id } };
@@ -690,7 +711,7 @@ export function createAuthor(opts) {
690
711
  try {
691
712
  child = spawnDetached({
692
713
  bin,
693
- argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName, ...modelArgv(vet.card)],
714
+ 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)],
694
715
  env: loaded.env,
695
716
  logPath: join(dir, `revise-${n}.log`),
696
717
  });
@@ -706,7 +727,7 @@ export function createAuthor(opts) {
706
727
  * `POST /api/author/:id/answer` body `{ k, answer }` (M4e amendments 24, 25): the human's answer to the plan's question `k` of `n`, one at a time.
707
728
  * A blank answer is refused and the question stays open; there is no skip. The answer is written ONCE ('wx') as `<plan>/answer-<k>.json`. After
708
729
  * the LAST answer the plan is drafted again as a fresh plain `fwdloop draft --no-questions` child (it never asks), from the submitted card with
709
- * each answer added word for word as a `~` guardrail under its line (the one `appendAnswersToJob`, then the one `cardToProse`). It is booked as
730
+ * each answer added word for word as a `~` guardrail under its line (the one `applyAnswers`, then the one `cardToProse`). It is booked as
710
731
  * an answer redraft (`redraft-<n>.json`), not a revise: it uses none of the 2. Synchronous, like `revise`; a refusal at $0 writes nothing.
711
732
  * @param {string} id @param {any} body
712
733
  */
@@ -728,7 +749,8 @@ export function createAuthor(opts) {
728
749
  // M10 piece 3 (am2): a question the page look raised takes bareloop's answer words. A blank answer gets bareloop's sentence; a newline is folded to a
729
750
  // space (one `~` line is one line) instead of refused. Every other question keeps its own gate (blank, one line).
730
751
  const look = q.source === 'look';
731
- const answer = typeof b.answer === 'string' ? (look ? b.answer.replace(/\s*\n\s*/g, ' ') : b.answer).trim() : '';
752
+ // hamr 2026-11-07 (ruling 2A): a leading `~` the person typed is dropped quietly (the job line adds its own); the ONE place, so a tilde-only answer is a blank answer
753
+ const answer = typeof b.answer === 'string' ? (look ? b.answer.replace(/\s*\n\s*/g, ' ') : b.answer).trim().replace(/^(?:~\s*)+/, '') : '';
732
754
  if (answer === '') return { status: 400, body: { ok: false, refused: 'blank-answer', say: look ? LOOK_BLANK_ANSWER_SAY : BLANK_ANSWER_SAY } };
733
755
  if (!look && /[\r\n]/.test(answer)) return { status: 400, body: { ok: false, refused: 'one-line', say: ONE_LINE_ANSWER_SAY } };
734
756
  if (keys.some((k) => k.length >= 8 && answer.includes(k))) return { status: 400, body: { ok: false, refused: 'key', say: 'This answer contains an API key. Keys go in Settings only. Nothing was saved.' } };
@@ -744,10 +766,10 @@ export function createAuthor(opts) {
744
766
  if (last) {
745
767
  const all = full.map((x) => {
746
768
  const typed = x.k === v.openK ? answer : x.answer;
747
- return { line: x.line, question: x.question, answer: typed, ...ruleOfAnswer(x, typed), ruleNo: x.ruleNo };
769
+ return { line: x.line, question: x.question, answer: typed, ...ruleOfAnswer(x, typed), ruleNo: x.ruleNo, ruleText: x.ruleText, ask: x.ask, ...(x.pairRule === undefined ? {} : { pairRule: x.pairRule }) };
748
770
  });
749
771
  const adds = all.filter((x) => x.rule !== null);
750
- const grown = appendAnswersToJob(typeof v.card.job === 'string' ? v.card.job : '', adds.map((x) => ({ line: x.line, answer: /** @type {string} */ (x.rule) })));
772
+ const grown = applyAnswers(typeof v.card.job === 'string' ? v.card.job : '', all);
751
773
  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.' } };
752
774
  const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card));
753
775
  if (!vet.ok) return vet.reply;
@@ -756,7 +778,8 @@ export function createAuthor(opts) {
756
778
  const ov = view(other, keys);
757
779
  if (ov && LIVE_PHASES.has(ov.phase)) return { status: 409, body: { ok: false, refused: 'draft-live', draftId: other, say: 'A draft is already running. Wait for it, or abandon it, before answering.' } };
758
780
  }
759
- redraft = { vet, all, left: all.filter((x) => x.left).map((x) => ({ line: x.line, rule: x.ruleNo })) };
781
+ // M10 am16 (4): what a shape guardrail's answers picked, for the redraft: the check an agree took, or the person's own words (a `~` rule, no check). A rule left Not checked rides `left`.
782
+ redraft = { vet, all, picks: grown.picks, left: grown.left };
760
783
  }
761
784
  try {
762
785
  // the human row of the draft log (am2 item 4): the question, the answer, the line, the time; a look ask also carries what code proposed and the rule the answer added, as their own fields
@@ -778,7 +801,7 @@ export function createAuthor(opts) {
778
801
  writeFileSync(files[2], `${JSON.stringify({ fromPlan: v.plan, answers: redraft.all.map((x) => ({ line: x.line, question: x.question, answer: x.answer })), ...(redraft.left.length ? { left: redraft.left } : {}) })}\n`, { mode: 0o600, flag: 'wx' });
779
802
  child = spawnDetached({
780
803
  bin,
781
- argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions', ...(redraft.left.length ? ['--left', redraft.left.map((x) => `${x.line}.${x.rule}`).join(',')] : []), ...modelArgv(redraft.vet.card)],
804
+ argv: ['draft', files[1], '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', redraft.vet.card.flowName, '--no-questions', ...carryArgv(dir, [], v.plan), ...(redraft.picks.length ? ['--picks', JSON.stringify(redraft.picks)] : []), ...(redraft.left.length ? ['--left', redraft.left.map((x) => `${x.line}.${x.rule}`).join(',')] : []), ...modelArgv(redraft.vet.card)],
782
805
  env: loaded.env,
783
806
  logPath: join(dir, `redraft-${n}.log`),
784
807
  });
@@ -18,6 +18,7 @@ import { checkFlowName } from '../flow.js';
18
18
  import { isWebUrl } from '../pagefetch.js';
19
19
  import { checkSendDestination } from '../runner.js';
20
20
  import { parseSignedText } from '../signed-text.js';
21
+ import { addEnd, typedLinesOf } from '../added-end.js';
21
22
  import { capTooSmallText } from '../draftspend.js';
22
23
  import { startableMcpServers, mcpConfigFor } from '../mcp-sources.js';
23
24
  import { mcpPickFor } from '../mcp-pick.js';
@@ -129,6 +130,50 @@ export function appendAnswersToJob(job, answers) {
129
130
  return { job: out.join('\n'), added };
130
131
  }
131
132
 
133
+ /**
134
+ * M10 am21: the submitted job box with ONE `~` line of a job line replaced by the words of an answer (the edited added line the ask was about). Pure.
135
+ * @param {string} job @param {number} line the job line (step) number @param {string} oldText the `~` words to replace (case and spacing aside) @param {string} newText
136
+ * @returns {{ job: string, replaced: boolean }}
137
+ */
138
+ export function replaceRuleOnJob(job, line, oldText, newText) {
139
+ const norm = (/** @type {string} */ t) => t.toLowerCase().replace(/\s+/g, ' ').trim();
140
+ const raw = String(job).split('\n');
141
+ let step = 0;
142
+ for (let i = 0; i < raw.length; i += 1) {
143
+ const t = raw[i].trim();
144
+ if (t === '') continue;
145
+ if (!t.startsWith('~')) { step += 1; continue; }
146
+ if (step === line && norm(t.slice(1)) === norm(oldText)) { raw[i] = `~ ${newText}`; return { job: raw.join('\n'), replaced: true }; }
147
+ }
148
+ return { job: String(job), replaced: false };
149
+ }
150
+
151
+ /**
152
+ * THE one writer of what a set of answers does to the job box and to the picks (M4e am24, M10 am16 (4), M10 am21): an answer is one more `~` line under its job line
153
+ * (`appendAnswersToJob`), EXCEPT the answer to an ask about an edited added line (`pairRule`), which REPLACES that line's words (the old added line never comes back).
154
+ * Picks and left rules are numbered as the asks carried them; an edited-line pick is kept under its source's number (`pairRule`), with the edited words as `added`.
155
+ * @param {string} job @param {{line: number, rule: string|null, left: boolean, check?: Record<string, any>|null, own?: boolean, ruleNo?: number, ruleText?: string, ask?: string, pairRule?: number}[]} all
156
+ * @returns {{job: string, added: number, picks: {line: number, rule: number|undefined, check: Record<string, any>|null, added: string, own?: boolean}[], left: {line: number, rule: number|undefined}[]}}
157
+ */
158
+ export function applyAnswers(job, all) {
159
+ let out = job;
160
+ let done = 0;
161
+ /** @type {{ line: number, answer: string }[]} */
162
+ const appends = [];
163
+ for (const x of all) {
164
+ if (x.rule === null) continue;
165
+ if (typeof x.pairRule === 'number') {
166
+ const r = replaceRuleOnJob(out, x.line, String(x.ruleText ?? ''), x.rule);
167
+ if (r.replaced) { out = r.job; done += 1; }
168
+ } else appends.push({ line: x.line, answer: x.rule });
169
+ }
170
+ const grown = appendAnswersToJob(out, appends);
171
+ const picks = all.filter((x) => (x.ask === 'check' || x.ask === 'no-check') && !x.left)
172
+ .map((x) => ({ line: x.line, rule: x.pairRule ?? x.ruleNo, check: x.check ?? null, added: /** @type {string} */ (x.rule), ...(x.own ? { own: true } : {}) }));
173
+ const left = all.filter((x) => x.left).flatMap((x) => [{ line: x.line, rule: x.ruleNo }, ...(typeof x.pairRule === 'number' ? [{ line: x.line, rule: x.pairRule }] : [])]);
174
+ return { job: grown.job, added: grown.added + done, picks, left };
175
+ }
176
+
132
177
  /**
133
178
  * THE one place a step's `~` lines become its guardrail: several `~` lines under one step are ONE continuous guardrail (hamr ruling 2026-10-09),
134
179
  * each part verbatim (trimmed), in typed order, joined by "; ". An answer (am24) is one more `~` line, so it joins here too. The signed-text parser
@@ -212,7 +257,7 @@ export function runInputRows(v) {
212
257
  * @returns {string}
213
258
  */
214
259
  export function cardToProse(card) {
215
- const { steps } = parseJobBox(card.job);
260
+ const { steps } = addEnd(parseJobBox(card.job).steps, card.destination); // M13 am8: the end is added by code
216
261
  const out = [...jobFileLines(steps, card.askWait), '', ARBITER_HEADING];
217
262
  out.push(`guardrail: cap $${capText(Number(card.capUsd))} per run`);
218
263
  if (card.destination !== '') out.push(`guardrail: send at line ${steps.length} to file:${card.destination}`);
@@ -239,14 +284,19 @@ export function cardFromSigned({ lines, arbiter }) {
239
284
  const asks = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
240
285
  const jobLines = [];
241
286
  let firstWait = null;
287
+ // M13 am8: the end is added by code (`cardToProse`), so the card's job leaves out the send line (the last line when it is the send) and an added Ask before it
288
+ const lastSend = (arbiter.sends ?? []).length === 1 && arbiter.sends[0].line === lines.length ? arbiter.sends[0].line : null;
289
+ const typed = new Set(typedLinesOf(lines, arbiter).map((l) => l.n));
242
290
  for (const l of lines) {
243
291
  const ak = asks.get(l.n);
244
292
  if (ak) {
245
293
  const w = waitText(ak.ttlMs);
246
294
  if (w === null) return no();
247
295
  firstWait ??= w;
248
- jobLines.push(`Ask ${w}: ${l.text}`);
249
- } else jobLines.push(l.text);
296
+ }
297
+ if (!typed.has(l.n)) continue;
298
+ if (ak) jobLines.push(`Ask ${waitText(ak.ttlMs)}: ${l.text}`);
299
+ else jobLines.push(l.text);
250
300
  if (typeof l.guardrail === 'string' && l.guardrail !== '') jobLines.push(`~ ${l.guardrail}`);
251
301
  }
252
302
  const sends = arbiter.sends ?? [];
@@ -261,7 +311,9 @@ export function cardFromSigned({ lines, arbiter }) {
261
311
  const again = parseSignedText(cardToProse(cardFields({ ...card, flowName: 'x' })));
262
312
  // M9 am1: the trigger is not a box on the card, and signing an Edit clears it (By hand again), so it is not part of the fidelity check
263
313
  const norm = (a) => JSON.stringify({ ...a, trigger: null, asks: (a.asks ?? []).map(({ ttlSigned, ...rest }) => rest) });
264
- const sameLines = again.ok && JSON.stringify(again.lines) === JSON.stringify(lines);
314
+ // a send line signed before am8 is the person's own words; the added one reads `write it out`: the words alone may differ there
315
+ const sendText = (/** @type {{n: number, text: string}[]} */ ls) => ls.map((l) => (l.n === lastSend ? { ...l, text: '' } : l));
316
+ const sameLines = again.ok && JSON.stringify(sendText(again.lines)) === JSON.stringify(sendText(lines));
265
317
  if (!sameLines || norm(again.arbiter) !== norm(arbiter)) return no();
266
318
  return { ok: true, card };
267
319
  }
@@ -393,9 +445,10 @@ export function checkCard(card, { root, keys = [], home, runOf }) {
393
445
  }
394
446
  } else no('capUsd', 'The cap must be a number above 0 (dollars per run).');
395
447
 
396
- // destination: one folder, or empty for no send (it is sent at the last step)
448
+ // destination: one folder, required (M13 am6); the accepted result is sent there at the last step
397
449
  const dest = card.destination;
398
- if (dest !== '') {
450
+ if (dest === '') no('destination', 'Destination is empty. Name the folder the accepted result is sent to, at the last step.');
451
+ else {
399
452
  const why = destinationRefusal(dest, root);
400
453
  if (why !== null) no('destination', why);
401
454
  }
package/src/panel/data.js CHANGED
@@ -23,7 +23,7 @@ import {
23
23
  existsSync, realpathSync,
24
24
  } from 'node:fs';
25
25
  import { createHash } from 'node:crypto';
26
- import { plainPlanCheck } from '../plain-checks.js';
26
+ import { plainPlanCheck, pickPlanRed } from '../plain-checks.js';
27
27
  import { compareNatural } from '../natural.js';
28
28
  import { join, sep } from 'node:path';
29
29
 
@@ -41,17 +41,18 @@ import { applyRunValues, parseWaitMs, pickRunValues, VALUES_FILE_RE } from '../r
41
41
  import { readSetup } from '../setup.js';
42
42
  import { parseHintBlock } from '../learn.js';
43
43
  import { checkedLines, notCheckedView, NOT_CHECKED_LABEL } from '../checked.js';
44
+ import { LABEL_PICKED } from '../checkwords.js';
44
45
  import { csvRolesOf, askSheetCard } from '../sheetblock.js';
45
46
  import { readSheetChecks } from '../sheet-record.js';
46
47
  import {
47
48
  NO_COPY_SAY, catchUpWords, endedLineWords, endedWords, needsLeftWords, nextInWords, nextTimeWords, scheduleAuditWords, scheduleBlockWords, scheduleFieldWords, scheduledNextFor, scheduledWords, startedWords,
48
49
  } from '../summary-words.js';
49
50
  import { MAX_STRUCTURE_RETRIES } from '../drafter.js';
50
- import { isResultRun, checkTypeOf, buildResult, downloadOf, readCitedChecks } from './result.js';
51
+ import { hasResultCards, checkTypeOf, buildResult, downloadOf, readCitedChecks } from './result.js';
51
52
  import { ticketListOf, ticketScheduleOf } from './tickets.js';
52
53
  import { buildJobGrid } from './jobgrid.js';
53
54
  import { readChecks } from '../diary.js';
54
- import { readRunInputs } from '../runfile.js';
55
+ import { readRunInputs, readRunRecord } from '../runfile.js';
55
56
  import { filterUnsure } from '../ticket-labels.js';
56
57
  import { readSchedule } from '../schedule.js';
57
58
  import { flowTypeOf } from '../declaration.js';
@@ -1813,11 +1814,11 @@ export function getRunDetail({
1813
1814
  needsYou: (({ tag, removable }) => ({ tag, removable }))(needsYouOf({
1814
1815
  runDir: run.runDir, ctx, glyph, controls: runControls(ctx, glyph, label), nowMs: now(), reopenAt: reopenableAt(run.runDir, ctx),
1815
1816
  })),
1816
- // M10 am4: the Result tab shows for a job that reads a page, a CSV or a .docx; `checkType` is its distinct close classes (the tab's top card)
1817
- hasResult: isResultRun(ctx.arbiter),
1817
+ // M10 am4 / M15 item 1: the Result tab shows for every job but a Tickets MCP one (that keeps the grid, and M10's cards when it reads a page); `checkType` is its distinct close classes (the tab's top card)
1818
+ hasResult: ctx.flowRead.ok && hasResultCards(ctx.arbiter, ctx.flowRead.declaration),
1818
1819
  // M13 am2 item 2: the ONE decider of the Result tab. The tab shows for a job that has M10's Result page (`hasResult`) or for a Tickets MCP job (the grid, `hasGrid`); a plain or MCP job keeps what it had before M13
1819
1820
  hasGrid,
1820
- resultTab: isResultRun(ctx.arbiter) || hasGrid,
1821
+ resultTab: (ctx.flowRead.ok && hasResultCards(ctx.arbiter, ctx.flowRead.declaration)) || hasGrid,
1821
1822
  checkType: ctx.flowRead.ok ? checkTypeOf(ctx.flowRead.declaration) : '\u2014',
1822
1823
  // M9 piece 6: the block at the top of the run page (ENDED / NEXT, SCHEDULED / NEXT), words set by code
1823
1824
  summary: runSummary(ctx, glyph, { root, catalogue, triggerRead, now, home }),
@@ -1911,7 +1912,7 @@ export function getDraftBlock(flowDir, runDir) {
1911
1912
  // The free retry after a broken reply reads `try N again`. A flow signed before am15 recorded no tries: nothing is added.
1912
1913
  const tryRows = (r, n) => (Array.isArray(r.tries) ? r.tries : []).map((t, k) => {
1913
1914
  const reds = Array.isArray(t.reds) ? t.reds.map(String) : [];
1914
- const gap = t.passed ? '' : (reds.length > 0 ? `${plainPlanCheck(reds[0]).reason}${reds.length > 1 ? ` (and ${reds.length - 1} more)` : ''}` : String(t.outcome ?? ''));
1915
+ const gap = t.passed ? '' : (reds.length > 0 ? `${plainPlanCheck(pickPlanRed(reds)).reason}${reds.length > 1 ? ` (and ${reds.length - 1} more)` : ''}` : String(t.outcome ?? ''));
1915
1916
  return {
1916
1917
  attempt: `${n}.${k + 1}`, step: 'drafting', class: null, verdict: t.passed ? 'green' : 'red', gap, at: r.at ?? null, setup: true, blocked: false,
1917
1918
  action: `${t.label} ${t.passed ? '✓' : '✗'}`, tryRow: true, tokensDisplay: { kind: 'no-model' },
@@ -1940,7 +1941,7 @@ export function getDraftBlock(flowDir, runDir) {
1940
1941
  rows.push(human(r, n, { action: 'card (you)', gap }));
1941
1942
  } else if (r.kind === 'note') rows.push(human(r, n, { action: 'note (you)', gap: String(r.text ?? '') }));
1942
1943
  // M10 am2 item 4: a question the page look raised and your answer, under the drafting step, in bareloop's words (`you were asked:` / `you said:`)
1943
- else if (r.kind === 'human') rows.push(human(r, n, { action: `you were asked: ${r.question}`, gap: `you said: ${r.answer}` }));
1944
+ else if (r.kind === 'human') rows.push(human(r, n, { action: `you were asked: ${r.question}`, gap: `you said: ${r.answer}${r.source === 'look' && typeof r.rule === 'string' && r.rule !== '' ? ` ${LABEL_PICKED}` : ''}` }));
1944
1945
  else if (r.kind === 'draft') { rows.push(model(r, n, 'draft')); rows.push(...tryRows(r, n)); }
1945
1946
  else if (r.kind === 'change') { rows.push(model(r, n, `change ${r.n}`)); rows.push(...tryRows(r, n)); }
1946
1947
  else if (r.kind === 'startover') { rows.push(model(r, n, 'start over')); rows.push(...tryRows(r, n)); }
@@ -1995,11 +1996,16 @@ function attachFolds(groups, runDir, flowDir, { root, flow, catalogue }) {
1995
1996
  const job = readRunJob({ root, name: flow, catalogue, runDir }).read;
1996
1997
  if (job.ok) steps = job.declaration.steps ?? [];
1997
1998
  }
1999
+ // M14 am1 item 1: a rerun's own run.json holds the reason it started with; the Audit shows it on the first step, where that reason was handed
2000
+ const rec = readRunRecord(runDir);
2001
+ const rr = rec.ok ? rec.rec.rerun : null;
2002
+ let rerun = rr && typeof rr === 'object' && rr.decision === 'rerun' && typeof rr.words === 'string' ? { words: rr.words } : null;
1998
2003
  for (const g of groups) {
1999
2004
  if (g.run) continue;
2000
2005
  const decl = steps?.find((x) => x.emits === g.step);
2001
2006
  const read = Array.isArray(decl?.reads) ? decl.reads[0] : null;
2002
- const fold = deriveFold(g, d, { about: typeof read === 'string' ? `artifacts/${read}.json` : null });
2007
+ const fold = deriveFold(g, d, { about: typeof read === 'string' ? `artifacts/${read}.json` : null, rerun });
2008
+ rerun = null;
2003
2009
  if (fold) g.fold = fold;
2004
2010
  }
2005
2011
  }
@@ -2245,7 +2251,7 @@ function resultContext({
2245
2251
  const run = resolveRunPath(root, flow, runId);
2246
2252
  if (!run.ok || !readdirInside(run.flowDir, 'runs').includes(runId)) return null; // the gateway lists real, non-symlink run folders only
2247
2253
  const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue);
2248
- if (!ctx.flowRead.ok || !isResultRun(ctx.arbiter)) return null;
2254
+ if (!ctx.flowRead.ok || !hasResultCards(ctx.arbiter, ctx.flowRead.declaration)) return null;
2249
2255
  return { run, ctx };
2250
2256
  }
2251
2257