fwdloop 0.27.0 → 0.29.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 (105) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +54 -13
  3. package/package.json +3 -3
  4. package/src/ask.js +1 -1
  5. package/src/audit-fold.js +9 -1
  6. package/src/authoring.js +22 -5
  7. package/src/canrun.js +19 -16
  8. package/src/checked.js +5 -2
  9. package/src/checkpick.js +257 -0
  10. package/src/checkwords.js +24 -0
  11. package/src/closers.js +8 -1
  12. package/src/config.js +18 -0
  13. package/src/declaration.js +85 -5
  14. package/src/drafter.js +143 -47
  15. package/src/flow.js +2 -1
  16. package/src/launcher.js +4 -2
  17. package/src/learn.js +1 -1
  18. package/src/learnstore.js +8 -7
  19. package/src/mcp-checks.js +50 -0
  20. package/src/mcp-pick.js +33 -0
  21. package/src/mcp-sources.js +84 -0
  22. package/src/mcp-use.js +54 -0
  23. package/src/memo.js +120 -0
  24. package/src/model-step.js +89 -17
  25. package/src/natural.js +23 -0
  26. package/src/pageask.js +9 -6
  27. package/src/pagedropwords.js +9 -0
  28. package/src/panel/author.js +50 -28
  29. package/src/panel/authorcard.js +86 -2
  30. package/src/panel/authorflows.js +18 -14
  31. package/src/panel/authortrigger.js +241 -84
  32. package/src/panel/data.js +99 -11
  33. package/src/panel/index.html +683 -210
  34. package/src/panel/jobgrid.js +127 -0
  35. package/src/panel/result.js +28 -7
  36. package/src/panel/scheduler.js +8 -2
  37. package/src/panel/server.js +17 -7
  38. package/src/panel/settings.js +119 -4
  39. package/src/panel/tickets.js +12 -7
  40. package/src/pickrecord.js +146 -0
  41. package/src/plain-checks.js +1 -0
  42. package/src/primitives.js +34 -5
  43. package/src/provider.js +4 -1
  44. package/src/runfile.js +4 -2
  45. package/src/runner.js +170 -45
  46. package/src/send.js +71 -4
  47. package/src/setup.js +13 -1
  48. package/src/summary-words.js +15 -3
  49. package/src/ticket-draft.js +40 -42
  50. package/src/ticket-labels.js +10 -0
  51. package/src/ticket-mcp.js +33 -10
  52. package/src/ticket-next.js +33 -0
  53. package/src/ticket-shape.js +9 -0
  54. package/src/trigger-clock.js +4 -4
  55. package/src/trigger-files.js +3 -3
  56. package/src/trigger-tickets.js +41 -12
  57. package/types/ask.d.ts +2 -1
  58. package/types/audit-fold.d.ts +13 -2
  59. package/types/authoring.d.ts +10 -2
  60. package/types/canrun.d.ts +5 -12
  61. package/types/checked.d.ts +7 -2
  62. package/types/checkpick.d.ts +149 -0
  63. package/types/checkwords.d.ts +14 -0
  64. package/types/closers.d.ts +2 -1
  65. package/types/config.d.ts +6 -0
  66. package/types/declaration.d.ts +17 -0
  67. package/types/drafter.d.ts +446 -50
  68. package/types/learn.d.ts +1 -0
  69. package/types/learnstore.d.ts +2 -3
  70. package/types/mcp-checks.d.ts +8 -0
  71. package/types/mcp-pick.d.ts +23 -0
  72. package/types/mcp-sources.d.ts +51 -0
  73. package/types/mcp-use.d.ts +12 -0
  74. package/types/memo.d.ts +15 -0
  75. package/types/model-step.d.ts +5 -0
  76. package/types/natural.d.ts +2 -0
  77. package/types/pageask.d.ts +9 -2
  78. package/types/pagedropwords.d.ts +1 -0
  79. package/types/panel/author.d.ts +37 -1
  80. package/types/panel/authorcard.d.ts +52 -0
  81. package/types/panel/authorflows.d.ts +9 -1
  82. package/types/panel/authortrigger.d.ts +73 -7
  83. package/types/panel/data.d.ts +56 -2
  84. package/types/panel/jobgrid.d.ts +109 -0
  85. package/types/panel/result.d.ts +9 -3
  86. package/types/panel/server.d.ts +5 -1
  87. package/types/panel/settings.d.ts +3 -2
  88. package/types/panel/tickets.d.ts +26 -4
  89. package/types/pickrecord.d.ts +88 -0
  90. package/types/primitives.d.ts +15 -2
  91. package/types/runfile.d.ts +7 -2
  92. package/types/runner.d.ts +128 -77
  93. package/types/send.d.ts +10 -2
  94. package/types/setup.d.ts +1 -56
  95. package/types/summary-words.d.ts +22 -3
  96. package/types/ticket-draft.d.ts +40 -32
  97. package/types/ticket-labels.d.ts +6 -0
  98. package/types/ticket-mcp.d.ts +18 -1
  99. package/types/ticket-next.d.ts +23 -0
  100. package/types/ticket-shape.d.ts +5 -0
  101. package/types/trigger-clock.d.ts +4 -3
  102. package/types/trigger-files.d.ts +1 -1
  103. package/types/trigger-tickets.d.ts +18 -4
  104. package/src/attemptdiff.js +0 -118
  105. package/types/attemptdiff.d.ts +0 -38
@@ -46,16 +46,16 @@ 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,
55
56
  } from '../provider.js';
56
57
  import { thinkingSupport as bareagentThinkingSupport, THINKING_FIXED_SAY, THINKING_UNVERIFIED_SAY } from '../thinking.js';
57
58
  import { parseSignedText } from '../signed-text.js';
58
- import { ticketNumberOf, ticketRefusals, ticketSourcesOf } from '../ticket-draft.js';
59
59
  import { draftStepList, reviseStepList } from '../draft-steps.js';
60
60
  import {
61
61
  capTooSmallText, draftingSpent, EARLIER_MISSING_SAY, potSplit, STARTED_OVER_FILE, usdText,
@@ -195,16 +195,6 @@ export function createAuthor(opts) {
195
195
  return draftingSpent(dir, { ceilingUsd: capFloorFor(true, home, card) }).usd;
196
196
  }
197
197
 
198
- /**
199
- * M12 piece 3: the ticket-list input of a plan's signed text (the role a by-hand start picks ONE ticket of), or null. The ONE reader; the green view shows the box from it and the sign door checks it.
200
- * @param {string} dir the draft folder @param {string} rel the plan folder @returns {string|null}
201
- */
202
- function ticketRoleOfPlan(dir, rel) {
203
- const prose = readFileInside(dir, `${rel}/prose.txt`);
204
- const parsed = prose.ok ? parseSignedText(prose.text) : null;
205
- return parsed?.ok === true ? (ticketSourcesOf(parsed.arbiter.sources)[0]?.role ?? null) : null;
206
- }
207
-
208
198
  /**
209
199
  * M4d am16: the split of the card's Cap $ at Sign & run, from ALL of this job's drafting (the one writer of that total, `draftingSpent`). Unpriced rounds count at their
210
200
  * worst case (the picked model's Settings ceiling). `refusal` = what is left cannot pay one run round at its worst case: refused at $0.
@@ -295,11 +285,23 @@ export function createAuthor(opts) {
295
285
  if (q.questions.length > 0) return { ...shared, phase: 'stopped', say: ANSWERS_NOT_DRAFTED_SAY };
296
286
  if (res.phase === 'green') {
297
287
  const answers = newest > 0 && redrafts.has(newest) ? answersOf(dir, newest, keys) : [];
298
- return { ...shared, phase: 'green', hash: res.hash, readout: res.readout, readoutHeads: res.readoutHeads, plan: rel, ticketRole: ticketRoleOfPlan(dir, rel), answers, ...planChecks(dir, rel) };
288
+ return { ...shared, phase: 'green', hash: res.hash, readout: res.readout, readoutHeads: res.readoutHeads, plan: rel, answers, ...planChecks(dir, rel) };
299
289
  }
300
290
  return { ...shared, phase: 'red', reds: res.reds, say: newest === 0 ? RED_SAY : cur.say };
301
291
  }
302
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
+
303
305
  /**
304
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
305
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
@@ -308,7 +310,11 @@ export function createAuthor(opts) {
308
310
  const decl = readJson(dir, `${rel}/declaration.json`);
309
311
  const prose = readFileInside(dir, `${rel}/prose.txt`);
310
312
  const parsed = prose.ok ? parseSignedText(prose.text) : null;
311
- 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
+ };
312
318
  return { checked: checkedLines(decl, opts), notChecked: notCheckedView(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked, decl) };
313
319
  }
314
320
 
@@ -380,7 +386,9 @@ export function createAuthor(opts) {
380
386
  }
381
387
 
382
388
  /** The flags that make a draft child use the card's model and thinking choice. @param {any} card */
383
- const modelArgv = (card) => ['--model', card.model, '--provider', card.provider, ...(card.thinking === true ? ['--thinking'] : [])];
389
+ const modelArgv = (card) => ['--model', card.model, '--provider', card.provider, ...(card.thinking === true ? ['--thinking'] : []),
390
+ // M13 piece 4: the card's Flow type and MCP ride every draft of the job (first, revised, redrafted)
391
+ ...(card.flowType ? ['--flow-type', card.flowType, '--mcp', card.mcp] : [])];
384
392
 
385
393
  /**
386
394
  * The $0 checks both a first draft and a revise run on the card as submitted: the card's own checks (a key value, the flow name,
@@ -513,6 +521,8 @@ export function createAuthor(opts) {
513
521
  // an earlier draft that is gone is never counted as $0: refused here, at $0, in words
514
522
  const startedFrom = body?.startedOverFrom;
515
523
  let priorUsd = 0;
524
+ /** @type {string[]} */
525
+ let carryFrom = [];
516
526
  if (startedFrom !== undefined && startedFrom !== null && startedFrom !== '' && typeof startedFrom !== 'string') {
517
527
  return { status: 400, body: { ok: false, refused: 'started-over-from', say: 'startedOverFrom must be the id of an earlier draft (a string).' } };
518
528
  }
@@ -521,6 +531,8 @@ export function createAuthor(opts) {
521
531
  const spent = draftingSpent(join(dd, startedFrom), { ceilingUsd: capFloorFor(true, home, cardFields(body)) });
522
532
  if (spent.missingEarlier) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
523
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));
524
536
  }
525
537
  const vet = vetCard(body, loaded, priorUsd, runOf?.flow);
526
538
  if (!vet.ok) return vet.reply;
@@ -547,7 +559,7 @@ export function createAuthor(opts) {
547
559
  let child;
548
560
  try {
549
561
  child = spawnDetached({
550
- 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'),
551
563
  });
552
564
  } catch (e) {
553
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 } };
@@ -608,16 +620,23 @@ export function createAuthor(opts) {
608
620
  const run = starter.checkRun(name, runId);
609
621
  if (!run.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: run.say } };
610
622
  }
611
- // M12 piece 3 (hamr 2026-10-29): a ticket job reads ONE ticket per run, so Sign & run takes its number too; refused at $0 BEFORE signing (nothing signed, no run folder)
612
- const ticketRole = ticketRoleOfPlan(dir, v.plan);
613
- const ticketBad = ticketRefusals(ticketRole, b);
614
- if (ticketBad.length > 0) return { status: 400, body: { ok: false, refused: 'ticket', refusals: ticketBad } };
615
- const ticket = ticketNumberOf(b.ticket);
616
623
  const signedBy = userInfo().username;
617
624
  // 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)
618
625
  const runOfRec = readJson(dir, RUN_OF_FILE);
619
626
  const asRunOf = typeof runOfRec?.flow === 'string' ? { flow: runOfRec.flow } : undefined;
620
627
  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.' } };
628
+ // 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
629
+ // run of its workflow signs no job, so it signs no schedule: the workflow keeps the one it has.
630
+ let cardSchedule = null;
631
+ if (asRunOf === undefined && v.card.schedule) {
632
+ const planProse = readFileInside(join(dir, v.plan), 'prose.txt');
633
+ const planDecl = readJson(join(dir, v.plan), 'declaration.json');
634
+ const parsedPlan = planProse.ok ? parseSignedText(planProse.text) : null;
635
+ 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.' } };
636
+ const planned = triggerDoor.cardSchedule(v.card.schedule, { arbiter: parsedPlan.arbiter, declaration: planDecl });
637
+ if (!planned.ok) return { status: 400, body: { ok: false, refused: 'schedule', say: planned.say } };
638
+ cardSchedule = planned.trigger;
639
+ }
621
640
  const result = signDraft({
622
641
  dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, keyNames: loaded.keyNames, sessionDir: dir, ...(asRunOf ? { asRunOf } : {}),
623
642
  });
@@ -641,8 +660,10 @@ export function createAuthor(opts) {
641
660
  }
642
661
  }
643
662
  const started = starter.start({
644
- kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path, ...(r.role === ticketRole ? { ticket: /** @type {number} */ (ticket) } : {}) })), values, ...(asRunOf ? { planRun: true, pick: result.modelPick ?? null } : {}),
663
+ kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })), values, ...(asRunOf ? { planRun: true, pick: result.modelPick ?? null } : {}),
645
664
  }, loaded);
665
+ // M13 piece 5 (signed item 7): the same sign writes the job's schedule.json, OFF; the panel turns it on after the job's first green run. `from` = the run this sign started.
666
+ if (cardSchedule !== null) triggerDoor.signSchedule({ flow: name, flowSignatureHash: result.signature.flow, trigger: cardSchedule, from: started.status === 202 && typeof started.body.runId === 'string' ? started.body.runId : null, signedBy });
646
667
  if (started.status !== 202) return { status: started.status, body: { ...started.body, signed: true, flow: name, say: `${started.body.say ?? 'The run did not start.'} The flow is signed; start it from "Run a signed flow".` } };
647
668
  return { status: 202, body: { ...started.body, signed: true } };
648
669
  },
@@ -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
  */
@@ -744,10 +765,10 @@ export function createAuthor(opts) {
744
765
  if (last) {
745
766
  const all = full.map((x) => {
746
767
  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 };
768
+ 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
769
  });
749
770
  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) })));
771
+ const grown = applyAnswers(typeof v.card.job === 'string' ? v.card.job : '', all);
751
772
  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
773
  const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card));
753
774
  if (!vet.ok) return vet.reply;
@@ -756,7 +777,8 @@ export function createAuthor(opts) {
756
777
  const ov = view(other, keys);
757
778
  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
779
  }
759
- redraft = { vet, all, left: all.filter((x) => x.left).map((x) => ({ line: x.line, rule: x.ruleNo })) };
780
+ // 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`.
781
+ redraft = { vet, all, picks: grown.picks, left: grown.left };
760
782
  }
761
783
  try {
762
784
  // 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 +800,7 @@ export function createAuthor(opts) {
778
800
  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
801
  child = spawnDetached({
780
802
  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)],
803
+ 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
804
  env: loaded.env,
783
805
  logPath: join(dir, `redraft-${n}.log`),
784
806
  });
@@ -18,7 +18,13 @@ 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 { checkSendLineGuardrail } from '../declaration.js';
21
22
  import { capTooSmallText } from '../draftspend.js';
23
+ import { startableMcpServers, mcpConfigFor } from '../mcp-sources.js';
24
+ import { mcpPickFor } from '../mcp-pick.js';
25
+ import { isTicketListUrl } from '../ticket-draft.js';
26
+ import { validateSchedule } from '../trigger-clock.js';
27
+ import { remoteRefusal } from '../ticket-mcp.js';
22
28
  import { readPriceConfig, resolveUsableModel, ceilingCostUsd } from '../provider.js';
23
29
 
24
30
  /** The heading line the prose files use (flows/job2-m6a-3/prose.txt); the parser matches `/^arbiter guardrails\b/i`. */
@@ -124,6 +130,50 @@ export function appendAnswersToJob(job, answers) {
124
130
  return { job: out.join('\n'), added };
125
131
  }
126
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
+
127
177
  /**
128
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),
129
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
@@ -182,6 +232,11 @@ export function cardFields(body) {
182
232
  // M4d amendment 6: the picked model (a key name and a model id from Chat's menu) and the per-job "Thinking on" tick; present only when sent
183
233
  ...(str(b.provider).trim() !== '' || str(b.model).trim() !== '' ? { provider: str(b.provider).trim(), model: str(b.model).trim() } : {}),
184
234
  ...(b.thinking === true ? { thinking: true } : {}),
235
+ // M13 piece 4: the Flow type (plain | mcp | tickets) and the MCP pick; sent only when the card names one, signed with the job
236
+ ...(str(b.flowType).trim() !== '' && str(b.flowType).trim() !== 'plain' ? { flowType: str(b.flowType).trim(), mcp: str(b.mcp).trim() } : {}),
237
+ // M13 piece 5 (item 7): the Schedule row, signed with the job. Absent = By hand (no schedule.json). Only the typed fields are kept.
238
+ ...(b.schedule && typeof b.schedule === 'object' && !Array.isArray(b.schedule)
239
+ ? { schedule: b.schedule.kind === 'new-ticket' ? { kind: 'new-ticket' } : { kind: b.schedule.kind, hour: b.schedule.hour, minute: b.schedule.minute } } : {}),
185
240
  };
186
241
  }
187
242
 
@@ -383,13 +438,39 @@ export function checkCard(card, { root, keys = [], home, runOf }) {
383
438
  }
384
439
  } else no('capUsd', 'The cap must be a number above 0 (dollars per run).');
385
440
 
386
- // destination: one folder, or empty for no send (it is sent at the last step)
441
+ // destination: one folder, required (M13 am6); the accepted result is sent there at the last step
387
442
  const dest = card.destination;
388
- if (dest !== '') {
443
+ if (dest === '') no('destination', 'Destination is empty. Name the folder the accepted result is sent to, at the last step.');
444
+ else {
389
445
  const why = destinationRefusal(dest, root);
390
446
  if (why !== null) no('destination', why);
391
447
  }
392
448
 
449
+ // M13 piece 4: the Flow type and its MCP. MCP and Tickets name an MCP fwdloop can start whose tools have been checked (R1: the job gets every tool of the newest OK check;
450
+ // never a started server here). Tickets needs the ticket list address as an Inputs line; MCP may have none.
451
+ const flow = /** @type {{flowType?: string, mcp?: string}} */ (card).flowType ?? 'plain';
452
+ if (!['plain', 'mcp', 'tickets'].includes(flow)) no('flowType', 'Flow type must be plain, MCP or Tickets MCP.');
453
+ else if (flow !== 'plain') {
454
+ const server = String(/** @type {any} */ (card).mcp ?? '');
455
+ if (server === '') no('mcp', 'Pick an MCP.');
456
+ else if (!startableMcpServers({ home }).includes(server)) no('mcp', mcpConfigFor(server, { home })?.remote ? remoteRefusal(server) : `${server} is not an MCP fwdloop can start (Settings > MCP lists the ones found).`);
457
+ else {
458
+ const pick = mcpPickFor(server, home);
459
+ if (!pick.ok) no('mcp', pick.say);
460
+ }
461
+ if (flow === 'tickets' && !parseInputLines(card.inputs).some((i) => isTicketListUrl(i.path))) no('inputs', 'Tickets needs the ticket list address as an Inputs line (for example issues: https://github.com/owner/repo/issues).');
462
+ }
463
+
464
+ // M13 piece 5 (item 7): the Schedule row. Every day at HH:MM for any flow type; When a new ticket arrives only for Tickets. The trigger itself (list, server, tool) is filled from the signed job at sign.
465
+ const sched = /** @type {any} */ (card).schedule;
466
+ if (sched !== undefined) {
467
+ if (sched.kind === 'new-ticket') {
468
+ if (flow !== 'tickets') no('schedule', 'Only a Tickets MCP job can start on a new ticket.');
469
+ } else if (sched.kind === 'daily') {
470
+ try { validateSchedule(sched); } catch { no('schedule', 'The time must be an hour 0-23 and a minute 0-59, like 09:00.'); }
471
+ } else no('schedule', 'Pick when it runs from the choices.');
472
+ }
473
+
393
474
  // inputs: one `name: path` per line; a role and a path on every line, no repeated role; each path a readable regular file (realpath)
394
475
  refusals.push(...checkInputRows(parseInputLines(card.inputs)));
395
476
 
@@ -412,5 +493,8 @@ export function checkCard(card, { root, keys = [], home, runOf }) {
412
493
  }
413
494
  return { ok: false, refusals };
414
495
  }
496
+ // M10 am14 item 1: a guardrail on the send line is refused at $0, before drafting, naming the line
497
+ for (const r of checkSendLineGuardrail(parsed.lines, parsed.arbiter)) no('job', r);
498
+ if (refusals.length > 0) return { ok: false, refusals };
415
499
  return { ok: true, prose };
416
500
  }
@@ -14,7 +14,8 @@ import { lstatSync, realpathSync } from 'node:fs';
14
14
  import { join } from 'node:path';
15
15
 
16
16
  import { scrub } from '../authoring.js';
17
- import { ticketNumberOf, ticketRefusals, ticketSourcesOf } from '../ticket-draft.js';
17
+ import { ticketSourcesOf } from '../ticket-draft.js';
18
+ import { flowTypeOf } from '../declaration.js';
18
19
  import { endRow, readHistory } from '../books.js';
19
20
  import { canFlowRun, willNotRunSay } from '../canrun.js';
20
21
  import { loadCatalogue } from '../catalogue.js';
@@ -45,7 +46,7 @@ export const editBlockedSay = (runId) => `finish or stop ${runId} first`;
45
46
  export const EDIT_STARTING_SAY = 'a run is starting';
46
47
  const NO_LIMIT = 'no monthly limit set';
47
48
  /** The body keys a run start takes (amendment 5 item 2): the open boxes plus the hash of the second click. Any other key is refused by name. */
48
- const RUN_KEYS = ['flow', 'inputs', 'runId', 'destination', 'capUsd', 'askWaits', 'hash', 'provider', 'model', 'planOf', 'ticket'];
49
+ const RUN_KEYS = ['flow', 'inputs', 'runId', 'destination', 'capUsd', 'askWaits', 'hash', 'provider', 'model', 'planOf'];
49
50
 
50
51
  /**
51
52
  * What the Run / Resume forms show of a signed flow (read from its own files, never from a model): the job lines as the signed text has them
@@ -230,10 +231,6 @@ export function createFlowsDoor(opts) {
230
231
  if (Object.hasOwn(pages, r.role) && r.path !== pages[r.role]) refusals.push({ field: `inputs.${n}`, say: pageAddressRefusal(r.role, pages[r.role]) });
231
232
  });
232
233
  const declared = (read.arbiter.sources ?? []).map((s) => s.role);
233
- // M12 piece 3 (hamr 2026-10-29): a by-hand Run on a job with a ticket list picks ONE ticket by number; any other job takes none
234
- const ticketRole = ticketSourcesOf(read.arbiter.sources)[0]?.role ?? null;
235
- const ticket = ticketNumberOf(body?.ticket);
236
- refusals.push(...ticketRefusals(ticketRole, body));
237
234
  for (const role of declared) {
238
235
  if (!Object.hasOwn(pages, role) && !rows.some((r) => r.role === role)) refusals.push({ field: 'inputs', say: `This flow needs an input named "${role}". Add it.` });
239
236
  }
@@ -251,7 +248,7 @@ export function createFlowsDoor(opts) {
251
248
  flow, flowSignatureHash: read.signature.flow, runId: null, version: 0, values,
252
249
  });
253
250
  return {
254
- ok: /** @type {true} */ (true), flow, read, declared, rows: declared.map((role) => rows.find((r) => r.role === role) ?? { role, path: pages[role] }), ticketRole, ticket, runId, values, differs: checked.differs || runModel !== null, hash, newPick, flowDir: join(realRoot, flow), planFrom,
251
+ ok: /** @type {true} */ (true), flow, read, declared, rows: declared.map((role) => rows.find((r) => r.role === role) ?? { role, path: pages[role] }), runId, values, differs: checked.differs || runModel !== null, hash, newPick, flowDir: join(realRoot, flow), planFrom,
255
252
  };
256
253
  }
257
254
 
@@ -303,11 +300,11 @@ export function createFlowsDoor(opts) {
303
300
  const last = lastSources(flowDir, roles, pageAddressesOf(read.arbiter));
304
301
  const { passed, stats } = runsOf(flowDir, name, read, roles);
305
302
  return {
306
- flow: name, capUsd: read.arbiter.capUsd, roles, pages: pageAddressesOf(read.arbiter), tickets: ticketSourcesOf(read.arbiter.sources).map((x) => x.role), nextRunId: nextRunId(flowDir), lastRunId: last.runId, lastSources: last.sources, leftThisMonth: left,
303
+ flow: name, capUsd: read.arbiter.capUsd, roles, pages: pageAddressesOf(read.arbiter), tickets: flowTypeOf(read.declaration) === 'tickets' ? ticketSourcesOf(read.arbiter.sources).map((x) => x.role) : [], flowType: flowTypeOf(read.declaration), mcp: read.declaration?.mcp?.server ?? null, nextRunId: nextRunId(flowDir), lastRunId: last.runId, lastSources: last.sources, leftThisMonth: left,
307
304
  runs: passed, stats,
308
305
  ...formFacts(read, home, flowDir),
309
306
  // M6 am5/am6: the job as the card Reuse workflow opens (`ok:true, card`), or why the card cannot hold it (`ok:false, say`). Nothing blocks it: a reuse never changes the job it is opened from.
310
- edit: (() => { const c = cardFromSigned(read); return c.ok ? { ok: true, card: c.card } : c; })(),
307
+ edit: (() => { const c = cardFromSigned(read); return c.ok ? { ok: true, card: { ...c.card, ...(flowTypeOf(read.declaration) === 'plain' ? {} : { flowType: flowTypeOf(read.declaration), mcp: read.declaration?.mcp?.server ?? '' }) } } : c; })(),
311
308
  };
312
309
  }
313
310
 
@@ -325,7 +322,7 @@ export function createFlowsDoor(opts) {
325
322
  },
326
323
 
327
324
  /**
328
- * M6 am9: is this run red, as the panel's glyph rule reads it (`[✗]` and nothing else; stopped `[■]` and waiting are not)? The server decides this itself,
325
+ * M6 am9: is this run red, as the panel's glyph rule reads it (`[✗]` and nothing else; stopped `[■]` and waiting are not; M13 9b.2: not a run that failed preflight)? The server decides this itself,
329
326
  * never from the page's word. False for a run that does not resolve.
330
327
  * @param {string} flow @param {unknown} runId
331
328
  */
@@ -334,7 +331,10 @@ export function createFlowsDoor(opts) {
334
331
  if (realRoot === null || !checkFlowName(flow).ok || typeof runId !== 'string' || runId === '') return false;
335
332
  const cat = loadCatalogue();
336
333
  if (!cat.ok) return false;
337
- return getRunGlyph({ root: realRoot, flow, runId, catalogue: cat.primitives })?.glyph === '[✗]';
334
+ if (getRunGlyph({ root: realRoot, flow, runId, catalogue: cat.primitives })?.glyph !== '[✗]') return false;
335
+ // M13 item 9b.2: a run that failed preflight never ran its plan (no step, $0), so its plan did not fail: reusing it unchanged is Run now, not a paid redraft
336
+ const end = endRow(readHistory(join(realRoot, flow)), join(realRoot, flow, 'runs', runId), runId);
337
+ return end?.outcome !== 'preflight-red';
338
338
  },
339
339
 
340
340
  /**
@@ -356,11 +356,15 @@ export function createFlowsDoor(opts) {
356
356
  * @param {any} body
357
357
  */
358
358
  reuseCheck(body) {
359
- const { job, fromRun, ...rest } = body && typeof body === 'object' ? body : /** @type {any} */ ({});
359
+ // M13 am4 item 1: `flowType` and `mcp` are job fields like the lines; read here, never reach the run door. An absent field = unchanged; plain has no server.
360
+ const { job, fromRun, flowType, mcp, ...rest } = body && typeof body === 'object' ? body : /** @type {any} */ ({});
360
361
  const realRoot = realRootOrNull();
361
362
  if (realRoot !== null && typeof job === 'string' && typeof rest.flow === 'string' && checkFlowName(rest.flow).ok) {
362
363
  const read = readSigned(realRoot, rest.flow);
363
- if (read.ok && jobKeyOfCard(job) !== jobKeyOfSigned(read)) {
364
+ const signedType = read.ok ? flowTypeOf(read.declaration) : 'plain';
365
+ const typeChanged = typeof flowType === 'string' && flowType !== signedType;
366
+ const mcpChanged = typeof mcp === 'string' && (flowType ?? signedType) !== 'plain' && mcp !== (read.ok ? read.declaration?.mcp?.server ?? '' : '');
367
+ if (read.ok && (jobKeyOfCard(job) !== jobKeyOfSigned(read) || typeChanged || mcpChanged)) {
364
368
  return { status: 200, body: { ok: true, kind: 'draft', suggestedName: suggestFlowName(realRoot, rest.flow) } };
365
369
  }
366
370
  // M6 am9: a RED run always drafts. The job is unchanged here, so the new plan is the next run of the SAME workflow (no new name). Only `[✗]` is red.
@@ -467,7 +471,7 @@ export function createFlowsDoor(opts) {
467
471
  };
468
472
  }
469
473
  const started = starter.start({
470
- kind: 'run', flow: s.flow, runId: s.runId, sources: s.declared.map((role) => ({ role, path: /** @type {{path: string}} */ (s.rows.find((r) => r.role === role)).path, ...(role === s.ticketRole ? { ticket: /** @type {number} */ (s.ticket) } : {}) })), values, pick: s.newPick, planOf: s.planFrom,
474
+ kind: 'run', flow: s.flow, runId: s.runId, sources: s.declared.map((role) => ({ role, path: /** @type {{path: string}} */ (s.rows.find((r) => r.role === role)).path })), values, pick: s.newPick, planOf: s.planFrom,
471
475
  }, loaded);
472
476
  // M4d amendment 7b: the pick of a flow that had no record is written only once the start succeeded (a refused start leaves none), beside the signed files, never in them
473
477
  if (started.status === 202 && s.newPick !== null) {