fwdloop 0.34.0 → 0.35.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.
package/src/drafter.js CHANGED
@@ -20,6 +20,10 @@ import { capTooSmallText, usdText } from './draftspend.js';
20
20
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
21
21
  import { validateDeclaration, checkGuardrailSums, checkSendLineGuardrail } from './declaration.js';
22
22
  import { readEveryStep } from './whole-job.js';
23
+ import {
24
+ RECOGNISE_SYSTEM, RECOGNISE_SCHEMA, RECOGNISE_TOOL, SUGGEST_SYSTEM as ACTION_SUGGEST_SYSTEM, SUGGEST_SCHEMA as ACTION_SUGGEST_SCHEMA, SUGGEST_TOOL as ACTION_SUGGEST_TOOL,
25
+ jobListing, recognisedIsLast, cleanSuggestion, suggestionQuestion, withoutSend,
26
+ } from './action-line.js';
23
27
  import { loadCatalogue } from './catalogue.js';
24
28
  import { findMcpPlanRed } from './canrun.js';
25
29
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
@@ -309,12 +313,12 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines
309
313
  '- close.class MUST equal the class of the guardrail on that step\'s fromLine (guardrailClasses[fromLine]); a line with no guardrail is "hitl". A step cannot claim a class its own line does not earn.',
310
314
  ...greenReadRule(arbiter.sources),
311
315
  '- You write no check. A shape guardrail (a word count, a list size, headings) is settled before you draft: the human picks each check from a list and code puts the picked checks in the plan, so there is no close.shape for you to write. Still answer close.class and guardrailClasses as above; code sets the class of a line whose guardrail it settled from what the human picked.',
312
- '- The send line (the last line, when a Destination is set) writes out what the human accepted; it has no guardrail and no check of its own.',
316
+ '- The send line (the job\'s action: its last line, when it writes out everything before it) ships the output of the step right before it; it has no guardrail and no check of its own.',
313
317
  '- A step whose check reads its reply (softgreen) answers in its reply text and is never granted `write`, `edit` or any other write-class verb; only the send step at the end writes files out.',
314
318
  `- Signed ask line(s): ${askLines.length ? askLines.join(', ') : 'none'}. For each, emit EXACTLY ONE step: fromLine = that line, close.class "hitl", primitives []. It is a stop only — never grant a primitive on it, and never emit a pause at any other line.`,
315
- `- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the ask step that comes before it. Its target and position are signed, not yours.`,
319
+ `- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the step that comes right before it. Its target and position are signed, not yours.`,
316
320
  '- An ask step must read the output of an earlier step, the thing you are asked to check: its FIRST read is what the human sees at the ask (for example reads: ["bucket_assignment"], the nearest earlier step\'s emits). An ask that reads nothing, or reads something no earlier step makes, is refused. Reading is not a grant: the ask still grants no primitive.',
317
- '- Nothing hitl may come after the last signed ask except the send step.',
321
+ ...(sendLines.length ? [] : ['- Nothing hitl may come after the last signed ask except the send step.']),
318
322
  '- You never author a trigger, cap, ask position or TTL, allow-list, send target, or what "done" means.',
319
323
  '',
320
324
  'Inputs, mechanically read (facts, not guesses):',
@@ -354,7 +358,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
354
358
  *
355
359
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
356
360
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
357
- * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
361
+ * questions?:{line:number, question:string}[], proseText?:string, action?:{line:number, by?:'agent'|'you', dropped?:true}|null, droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
358
362
  * checkCard?:ReturnType<typeof cardOfBlock>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
359
363
  * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
360
364
  * `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
@@ -370,6 +374,9 @@ export async function draft({
370
374
  mcpServers = /** @type {string[]|undefined} */ (undefined),
371
375
  // M13 piece 4: the job's flow type and its MCP pick (`mcpPickFor`: `{ok, server, tools}`), both set by code from the card; the drafter is told them, never asked for them
372
376
  flowType = /** @type {'plain'|'mcp'|'tickets'} */ ('plain'), mcp = /** @type {any} */ (null),
377
+ // M13 am11: what the prose's send line is. null = the prose file is the truth (a hand-written send line); 'check' = the card's tentative send on the last line: the AI answers whether
378
+ // it is the action; 'known' = the person agreed or typed the last line (no question)
379
+ actionMode = /** @type {null|'check'|'known'} */ (null),
373
380
  }) {
374
381
  // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
375
382
  const thinkingOf = () => {
@@ -383,16 +390,19 @@ export async function draft({
383
390
  // ---- $0 gates, before any provider is built -------------------------------
384
391
  // `draftThinking` ('on'|'off', M4d am6 item 7 / am7: the Chat tick-box, per job) is an intent only: turning thinking on or off on the wire is bareagent's (am7 item 3).
385
392
  if (draftThinking !== 'on' && draftThinking !== 'off') return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
393
+ if (actionMode !== null && actionMode !== 'check' && actionMode !== 'known') return fail([`config: actionMode must be check | known, got ${JSON.stringify(actionMode)}`]);
386
394
  const parsed = parseSignedText(proseText);
387
395
  if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
388
- const { lines, arbiter } = parsed;
396
+ const { lines } = parsed;
397
+ let { arbiter } = parsed;
389
398
  const ttlReds = unsignedAskTtls(arbiter);
390
399
  if (ttlReds.length) return fail(ttlReds);
391
400
  // M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
392
401
  const sumReds = checkGuardrailSums(lines);
393
402
  if (sumReds.length) return fail(sumReds);
394
403
  // M10 amendment 14 item 1: a guardrail on the send line is refused at $0 (the card says it first; a prose file straight to `fwdloop draft` is caught here).
395
- const sendReds = checkSendLineGuardrail(lines, arbiter);
404
+ // M13 am11: with an actionMode the send is the card's tentative one; the refusal is made after the AI says whether the last line is the action (below)
405
+ const sendReds = actionMode === null ? checkSendLineGuardrail(lines, arbiter) : [];
396
406
  if (sendReds.length) return fail(sendReds);
397
407
  const menu = wiredMenu(skills);
398
408
  // The file inputs are read first, at $0, before a provider is built (a page input is fetched only after the price and cap gates, below).
@@ -447,9 +457,9 @@ export async function draft({
447
457
  /** the result of a draft that stops before any drafting round with what it spent so far (a provider red, the budget); one literal for every such stop */
448
458
  const earlyStop = (/** @type {string[]} */ reds, /** @type {string} */ why) => {
449
459
  const m = sumMeterings(meterings);
450
- return {
460
+ return withAction({
451
461
  ok: false, declaration: null, reds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries: 0, revisions: 0, stop: why, log, thinking: thinkingOf(), inputs: facts.list, questions: [], droppedQuestions: [], notChecked: [], ...pageExtras,
452
- };
462
+ });
453
463
  };
454
464
 
455
465
  // M10 item 1: a web page input is fetched once and frozen into the DRAFT folder (the drafting copy). A run freezes its own copy at its own start
@@ -478,6 +488,111 @@ export async function draft({
478
488
  const pageLooks = [];
479
489
  /** @type {Record<string, any>} */
480
490
  const pageExtras = pageSources.length ? { look, pageLooks } : {};
491
+ /**
492
+ * ONE forced-tool turn, for every turn that is an answer in one typed call (the suggest call, the ledger call, the row-edit turn): the hold against what is left of the cap, Loop's metering of the round,
493
+ * the book before and after, the tool that captures the arguments and halts (no wrap-up round), thinking off (on cannot combine with a forced call), the raw answer kept when the call failed.
494
+ * `repair` (M4d am39): a malformed reply that is a complete object plus trailing `}` is repaired, and used only when `usable(value)` says the caller can read it.
495
+ * Returns `{early}` (a provider red or the budget: the draft's own stop) or `{args, entry}` (`args` null = no usable call in any attempt; `entry` is the last round's log entry).
496
+ * @param {{kind: string, system: string, messages: {role: string, content: string}[], tool: {name: string, description: string, schema: any}, attempts?: number, repair?: boolean, usable?: (v: any) => boolean}} o
497
+ */
498
+ const forcedTurn = async ({ kind, system: sys, messages, tool: spec, attempts = 2, repair = false, usable = () => true }) => {
499
+ /** @type {any} */
500
+ let entry = null;
501
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
502
+ const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
503
+ if (spentBefore + ceilingCostUsd(rates, sys.length + messages.reduce((n, m) => n + m.content.length, 0) + JSON.stringify(spec.schema).length) > budgetUsd) {
504
+ if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)]) }; }
505
+ return { early: earlyStop(['the draft budget is spent'], 'budget') };
506
+ }
507
+ /** @type {any} */
508
+ let captured;
509
+ const roundEvents = [];
510
+ const tool = { name: spec.name, description: spec.description, parameters: spec.schema, execute: async (/** @type {any} */ a) => { captured = a; throw new HaltError(`${kind} captured`, { rule: 'captured' }); } };
511
+ const forcedLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
512
+ calls += 1;
513
+ book(true);
514
+ let res;
515
+ let threw = null;
516
+ try {
517
+ res = await forcedLoop.run([{ role: 'system', content: sys }, ...messages], [tool], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: 'off', toolChoice: { name: spec.name } });
518
+ } catch (err) {
519
+ threw = err;
520
+ if (roundEvents.length === 0) unmetered += 1;
521
+ }
522
+ book(false);
523
+ entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind });
524
+ if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
525
+ if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
526
+ if (threw && !(isPlainObject(captured) && threw instanceof HaltError)) {
527
+ entry.outcome = `provider-red: ${threw.message}`;
528
+ log.push(entry);
529
+ return { early: earlyStop([`provider-red: ${threw.message}`], 'provider-red') };
530
+ }
531
+ if (!isPlainObject(captured)) {
532
+ // the raw answer is kept (log.json), the cut-off said out loud
533
+ const malformed = provider?.lastMalformedToolCall ?? null;
534
+ entry.outcome = res?.stopReason === 'max_tokens' ? 'structure: truncated: the round hit the output cap with no completed tool call' : 'structure: no usable tool call (text instead of the tool)';
535
+ if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
536
+ else if (typeof res?.text === 'string' && res.text !== '') entry.rawText = res.text;
537
+ // M4d am39: only a malformed-JSON round (never a cut-off, never text) whose answer is a complete object plus trailing `}` is repaired
538
+ const fixed = repair && malformed && res?.stopReason !== 'max_tokens' ? repairTrailingBraces(malformed.rawArguments) : null;
539
+ if (fixed) {
540
+ const ok = usable(fixed.value);
541
+ entry.braceRepair = { dropped: fixed.dropped, used: ok };
542
+ if (ok) { entry.outcome = 'answered'; entry.args = fixed.value; log.push(entry); return { args: fixed.value, entry }; }
543
+ }
544
+ log.push(entry);
545
+ continue;
546
+ }
547
+ entry.outcome = 'answered';
548
+ entry.args = captured;
549
+ log.push(entry);
550
+ return { args: captured, entry };
551
+ }
552
+ return { args: null, entry };
553
+ };
554
+
555
+ // M13 am11 rules 1 and 2: the job's last line is the action. The AI answers ONE question (record_action); code checks the answer is the LAST line (never an Ask). With none, and the
556
+ // person's answer not yet given, the AI suggests one line and the question carries the signed words. Nothing is added to the job without the person's answer.
557
+ /** the result with what the AI decided about the action: the prose as kept (the send line stays or is taken out) and the action line, or null */
558
+ // M13 am11b: the ONE writer of the log's `action`: { line, by } (who picked: 'agent' = the AI, 'you' = an Agree or typed line), (an old log may hold a `dropped` record; nothing reads it); null when none
559
+ /** @type {null|{line: number, by?: 'agent'|'you'}} */
560
+ let actionRec = null;
561
+ const withAction = (/** @type {any} */ r) => ({ ...r, proseText, action: actionRec ?? (arbiter.sends.length === 1 ? { line: arbiter.sends[0].line } : null) });
562
+ /** @type {null|{line: number, question: string, source: 'look', ask: 'action', ruleNo: undefined, ruleText: string, reading: string, counted: false}} */
563
+ let actionAsk = null;
564
+ if (actionMode !== null && arbiter.sends.length === 1 && arbiter.sends[0].line === lines.length) {
565
+ const last = lines[lines.length - 1];
566
+ const signedAsks = new Set(arbiter.asks.map((a) => a.line));
567
+ let keep = actionMode === 'known';
568
+ if (actionMode === 'check' && !signedAsks.has(last.n)) {
569
+ const rec = await forcedTurn({
570
+ kind: 'action-recognise', system: RECOGNISE_SYSTEM, messages: [{ role: 'user', content: jobListing(lines, signedAsks, String(arbiter.sends[0].target.path)) }],
571
+ tool: { name: RECOGNISE_TOOL, description: 'Say which last step writes or sends everything before it, or none.', schema: RECOGNISE_SCHEMA },
572
+ });
573
+ if (rec.early) return rec.early;
574
+ keep = recognisedIsLast(rec.args, last.n, false);
575
+ }
576
+ if (keep) {
577
+ const reds = checkSendLineGuardrail(lines, arbiter);
578
+ if (reds.length) return earlyStop(reds, 'action');
579
+ actionRec = { line: last.n, by: actionMode === 'known' ? 'you' : 'agent' };
580
+ } else {
581
+ if (actionMode === 'check' && offerQuestions) {
582
+ const sg = await forcedTurn({
583
+ kind: 'action-suggest', system: ACTION_SUGGEST_SYSTEM, messages: [{ role: 'user', content: jobListing(lines, signedAsks, String(arbiter.sends[0].target.path)) }],
584
+ tool: { name: ACTION_SUGGEST_TOOL, description: 'Suggest one last step that writes or sends everything before it.', schema: ACTION_SUGGEST_SCHEMA },
585
+ });
586
+ if (sg.early) return sg.early;
587
+ const suggested = cleanSuggestion(sg.args);
588
+ if (suggested !== null) actionAsk = { line: last.n, question: suggestionQuestion(suggested), source: 'look', ask: 'action', ruleNo: undefined, ruleText: '', reading: suggested, counted: false };
589
+ }
590
+ proseText = withoutSend(proseText);
591
+ const again = parseSignedText(proseText);
592
+ if (!again.ok) return fail(again.reds.map((r) => `signed-text: ${r}`));
593
+ arbiter = again.arbiter;
594
+ }
595
+ }
481
596
  let mapCut = null;
482
597
  const jobLines = lines.map((l) => ({ n: l.n, text: l.text, ...(l.guardrail ? { rule: l.guardrail } : {}) }));
483
598
  // M10 am27 (1): the page look sees only the non-count rules; `toOriginal` takes a visible rule number back to the original one
@@ -602,70 +717,6 @@ export async function draft({
602
717
  );
603
718
  }
604
719
  if (sheetLooks.length) pageExtras.sheetLooks = sheetLooks; // kept beside the page looks (src/authoring.js writes both into page-look.json)
605
- /**
606
- * ONE forced-tool turn, for every turn that is an answer in one typed call (the suggest call, the ledger call, the row-edit turn): the hold against what is left of the cap, Loop's metering of the round,
607
- * the book before and after, the tool that captures the arguments and halts (no wrap-up round), thinking off (on cannot combine with a forced call), the raw answer kept when the call failed.
608
- * `repair` (M4d am39): a malformed reply that is a complete object plus trailing `}` is repaired, and used only when `usable(value)` says the caller can read it.
609
- * Returns `{early}` (a provider red or the budget: the draft's own stop) or `{args, entry}` (`args` null = no usable call in any attempt; `entry` is the last round's log entry).
610
- * @param {{kind: string, system: string, messages: {role: string, content: string}[], tool: {name: string, description: string, schema: any}, attempts?: number, repair?: boolean, usable?: (v: any) => boolean}} o
611
- */
612
- const forcedTurn = async ({ kind, system: sys, messages, tool: spec, attempts = 2, repair = false, usable = () => true }) => {
613
- /** @type {any} */
614
- let entry = null;
615
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
616
- const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
617
- if (spentBefore + ceilingCostUsd(rates, sys.length + messages.reduce((n, m) => n + m.content.length, 0) + JSON.stringify(spec.schema).length) > budgetUsd) {
618
- if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)]) }; }
619
- return { early: earlyStop(['the draft budget is spent'], 'budget') };
620
- }
621
- /** @type {any} */
622
- let captured;
623
- const roundEvents = [];
624
- const tool = { name: spec.name, description: spec.description, parameters: spec.schema, execute: async (/** @type {any} */ a) => { captured = a; throw new HaltError(`${kind} captured`, { rule: 'captured' }); } };
625
- const forcedLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
626
- calls += 1;
627
- book(true);
628
- let res;
629
- let threw = null;
630
- try {
631
- res = await forcedLoop.run([{ role: 'system', content: sys }, ...messages], [tool], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: 'off', toolChoice: { name: spec.name } });
632
- } catch (err) {
633
- threw = err;
634
- if (roundEvents.length === 0) unmetered += 1;
635
- }
636
- book(false);
637
- entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind });
638
- if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
639
- if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
640
- if (threw && !(isPlainObject(captured) && threw instanceof HaltError)) {
641
- entry.outcome = `provider-red: ${threw.message}`;
642
- log.push(entry);
643
- return { early: earlyStop([`provider-red: ${threw.message}`], 'provider-red') };
644
- }
645
- if (!isPlainObject(captured)) {
646
- // the raw answer is kept (log.json), the cut-off said out loud
647
- const malformed = provider?.lastMalformedToolCall ?? null;
648
- entry.outcome = res?.stopReason === 'max_tokens' ? 'structure: truncated: the round hit the output cap with no completed tool call' : 'structure: no usable tool call (text instead of the tool)';
649
- if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
650
- else if (typeof res?.text === 'string' && res.text !== '') entry.rawText = res.text;
651
- // M4d am39: only a malformed-JSON round (never a cut-off, never text) whose answer is a complete object plus trailing `}` is repaired
652
- const fixed = repair && malformed && res?.stopReason !== 'max_tokens' ? repairTrailingBraces(malformed.rawArguments) : null;
653
- if (fixed) {
654
- const ok = usable(fixed.value);
655
- entry.braceRepair = { dropped: fixed.dropped, used: ok };
656
- if (ok) { entry.outcome = 'answered'; entry.args = fixed.value; log.push(entry); return { args: fixed.value, entry }; }
657
- }
658
- log.push(entry);
659
- continue;
660
- }
661
- entry.outcome = 'answered';
662
- entry.args = captured;
663
- log.push(entry);
664
- return { args: captured, entry };
665
- }
666
- return { args: null, entry };
667
- };
668
-
669
720
  // M10 am16 (1): ONE suggestion call, only when a guardrail on a step line is one this call settles (scope by code, src/checkpick.js). It suggests a check from bareguard's own list
670
721
  // per guardrail, or none; code keeps what passes keep-or-drop. The call is metered, held and booked as a drafting round (the same `meterings`). The redraft after the answers
671
722
  // (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
@@ -720,25 +771,25 @@ export async function draft({
720
771
  // M10 piece 3 (item 4, am1, am2): CODE decides the early asks from the look, after the one map call and BEFORE any drafting round. A signed ask line's own
721
772
  // guardrail is a human stop, not a page check, so it is not asked. More than MAX_LOOK_ASKS is a job to rewrite: nothing is asked, nothing more is spent.
722
773
  // The redraft after the answers (offerQuestions false) never asks. A sheet's offers are reading asks: they come first with the page's, in line order.
723
- if ((sheetAsks.length || blockAsks.length) && offerQuestions) {
774
+ if ((sheetAsks.length || blockAsks.length || actionAsk !== null) && offerQuestions) {
724
775
  // M17 am4 (A1): a question comes from the list (questionsOfBlock) or is the sheet's column offer (M17 am1 1(a)); no question is asked outside the list
725
776
  const lookAsks = [...[...sheetAsks, ...blockAsks.filter((a) => a.ask === 'reading')].sort((a, b) => a.line - b.line), ...blockAsks.filter((a) => a.ask === 'cant-check')];
726
777
  // am16 (3): a shape guardrail's ask follows, in line order. (5): a proposal is not an ask under am1; only a `can't check` ask counts toward the cap (the 4th stops drafting at $0).
727
778
  const blockShape = blockAsks.filter((a) => a.ask === 'no-check' || a.ask === 'check');
728
- const asks = [...lookAsks, ...blockShape];
779
+ const asks = [...lookAsks, ...blockShape, ...(actionAsk === null ? [] : [actionAsk])];
729
780
  if (asks.length > 0) {
730
781
  const m = sumMeterings(meterings);
731
782
  const spent = m.costUsd === null || unmetered > 0 ? (m.costUsd === null ? 'unknown' : `at least ${usdText(m.costUsd)}`) : usdText(m.costUsd);
732
783
  const counted = [...lookAsks, ...blockShape.filter((a) => a.counted).map((a) => ({ ...a, reading: "I can't check this" }))];
733
784
  const tooMany = counted.length > MAX_LOOK_ASKS;
734
785
  if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
735
- return {
786
+ return withAction({
736
787
  ok: false, declaration: null, reds: tooMany ? [`${tooManyAsksText(counted)} Spent so far: ${spent}.`] : [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries: 0, revisions: 0, stop: tooMany ? 'look-asks-too-many' : 'look-asks', log, thinking: thinkingOf(), inputs: facts.list,
737
788
  questions: tooMany ? [] : asks.map((a) => ({
738
- line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: a.rule, ruleText: a.ruleText, proposal: a.reading ?? null, ...('check' in a && a.check ? { check: a.check } : {}),
789
+ line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: 'rule' in a ? a.rule : undefined, ruleText: a.ruleText, proposal: a.reading ?? null, ...('check' in a && a.check ? { check: a.check } : {}),
739
790
  })),
740
791
  droppedQuestions: [], notChecked: pageNotChecked, ...pageExtras,
741
- };
792
+ });
742
793
  }
743
794
  }
744
795
  // the record this draft hands on: what it kept plus what the person just answered (numbered on this card)
@@ -1067,9 +1118,9 @@ export async function draft({
1067
1118
  entry.outcome = 'valid';
1068
1119
  log.push(entry);
1069
1120
  const m = sumMeterings(meterings);
1070
- return {
1121
+ return withAction({
1071
1122
  ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, thinking: thinkingOf(), inputs: facts.list, ...extras, ...pageExtras, ...(block ? { checkCard: (() => { const c = sheetOnList ? withSheetCard(cardOfBlock(block), sheetOnList, sheetDroppedNow) : cardOfBlock(block); return ticketOnList?.card.length ? withSheetCard(c, { card: ticketOnList.card }) : c; })() } : {}),
1072
- };
1123
+ });
1073
1124
  }
1074
1125
  lastReds = [...verdict.reds];
1075
1126
  entry.outcome = `validator: ${verdict.reds.length} red(s)`;
@@ -1089,7 +1140,7 @@ export async function draft({
1089
1140
  const m = sumMeterings(meterings);
1090
1141
  // Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
1091
1142
  // never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
1092
- return {
1143
+ return withAction({
1093
1144
  ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log, thinking: thinkingOf(), inputs: facts.list, ...extras, ...pageExtras,
1094
- };
1145
+ });
1095
1146
  }
package/src/jobkey.js CHANGED
@@ -5,7 +5,6 @@
5
5
  // TWO producers, ONE canonical form: the signed flow (parseSignedText's lines + arbiter) and the card's job box (parseJobBox).
6
6
  import { createHash } from 'node:crypto';
7
7
 
8
- import { typedLinesOf } from './added-end.js';
9
8
  import { joinGuardrails, parseJobBox } from './panel/authorcard.js';
10
9
 
11
10
  /** @param {{ask: boolean, text: string, guardrail: string}[]} steps */
@@ -22,6 +21,6 @@ export function jobKeyOfCard(job) {
22
21
  /** The key of a signed job. @param {{ lines: {n: number, text: string, guardrail: string}[], arbiter: any }} signed `parseSignedText`'s ok result */
23
22
  export function jobKeyOfSigned({ lines, arbiter }) {
24
23
  const asks = new Set((arbiter.asks ?? []).map((a) => a.line));
25
- // M13 am8: the end code adds (and an old job's send line) is not part of the job the person typed
26
- return keyOf(typedLinesOf(lines, arbiter).map((l) => ({ ask: asks.has(l.n), text: String(l.text).trim(), guardrail: String(l.guardrail ?? '').trim() })));
24
+ // M13 am11: every line of a signed job is a line the person typed (code adds none)
25
+ return keyOf(lines.map((l) => ({ ask: asks.has(l.n), text: String(l.text).trim(), guardrail: String(l.guardrail ?? '').trim() })));
27
26
  }
package/src/pageask.js CHANGED
@@ -100,6 +100,19 @@ export function tooManyAsksText(asks) {
100
100
  return redactSecrets(`Your job has ${asks.length} rules I can't check or had to guess. Please rewrite it so each one says what to look for. My readings: ${list}.`);
101
101
  }
102
102
 
103
+ // borrowed-from: bareloop src/draftspend.js@v0.58.0 (decidedWords)
104
+ /**
105
+ * M17 am8: what a button-picked answer decided, as the one Audit line; null when the row has no pick (a box-answered drafter question, an older record).
106
+ * @param {{choice?: string, words?: string}} h
107
+ * @returns {string|null}
108
+ */
109
+ export function decidedWords(h) {
110
+ if (h.choice === 'agree' && typeof h.words === 'string') return `agreed \u2014 ${h.words}`;
111
+ if (h.choice === 'rule' && typeof h.words === 'string') return `you wrote \u2014 ${h.words}`;
112
+ if (h.choice === 'drop') return 'dropped \u2014 Not checked';
113
+ return null;
114
+ }
115
+
103
116
  /**
104
117
  * What a typed answer to a look ask does, the ONE place that decides (the panel's answer route, the setup record and the Result tab all read it).
105
118
  * `agree` / `yes` to a reading ask takes the code's reading; `drop it` to a can't-check ask leaves the rule Not checked (no `~` line); anything else is the
@@ -107,11 +120,16 @@ export function tooManyAsksText(asks) {
107
120
  * M10 am16: a shape guardrail's ask (`ask: 'check'` proposes a check, `'no-check'` found none) takes the same words: `agree` takes the proposal (and the check it
108
121
  * carries, `check`), `drop it` leaves the rule Not checked (either kind), anything else is the person's own words (`own`: a `~` rule on the line, no check).
109
122
  * @param {{source?: string, ask?: string, proposal?: string|null, check?: Record<string, any>}} q @param {unknown} typed @param {'agree'|'drop'|'rule'} [choice] M10 am29: the button used; absent = today's words reading (CLI, old files)
110
- * @returns {{rule: string|null, left: boolean, check?: Record<string, any>, own?: boolean}} `rule` = the words written as a new `~` rule (null when the rule is left Not checked)
123
+ * @returns {{rule: string|null, left: boolean, check?: Record<string, any>, own?: boolean, action?: 'known', actionLine?: string}} `rule` = the words written as a new `~` rule (null when the rule is left Not checked)
111
124
  */
112
125
  export function ruleOfAnswer(q, typed, choice) {
113
126
  const typedText = String(typed ?? '').replace(/\s*\n\s*/g, ' ').trim();
114
127
  if (q.source !== 'look') return { rule: typedText, left: false };
128
+ // M13 am11 rule 2: the question about the job's last action adds no `~` rule. Agree adds the suggested line, the box adds the typed words; there is no Drop it (am11c).
129
+ if (q.source === 'look' && q.ask === 'action') {
130
+ if (choice === 'drop') return { rule: null, left: true }; // M13 am11c: there is no Drop it here; the answer door refuses it (the question is about the job line, not a ~ rule)
131
+ return { rule: null, left: false, action: 'known', actionLine: choice === 'agree' && typeof q.proposal === 'string' ? q.proposal : typedText };
132
+ }
115
133
  if (choice !== undefined) { // M10 am29: a typed choice decides, never the words; the box (`rule`) keeps its words whole
116
134
  const shapeC = q.ask === 'check' || q.ask === 'no-check';
117
135
  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 } : {}) };
package/src/pagemap.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // borrowed-from: bareloop src/pagemap.js@54fa5ca (MAP_SHAPES, MAP_SYSTEM, mapPrompt, parseMapAnswer, MAP_UNREADABLE)
2
+ // fwd change 2026-11-16 (F201, hamr): the prompt states the goal, asks for meaning + a why per fact, and gives a "cannot" list for a rule the page cannot show
2
3
  // Not copied: runPageMap (bareloop's spend and transport plumbing; fwdloop meters through the drafter's own provider call, see src/pagelook.js),
3
4
  // and the ask half (DROP_IT, askableFromLook, ...), which is the next piece.
4
5
  import { lineRules } from './pagebits.js';
@@ -16,9 +17,14 @@ export const MAP_SYSTEM = 'You map a person\'s job to the exact words of ONE sav
16
17
  export function mapPrompt({ jobLines, label, text }) {
17
18
  const job = jobLines.map((l) => `LINE ${l.n}: ${l.text}${lineRules(l).map((r, i) => `\n~ rule ${i + 1}: ${r}`).join('')}`).join('\n');
18
19
  return `THE JOB (each ~ rule applies to the line above it):\n${job}\n\n`
19
- + 'A "result" is one item the page lists (one flight, one stay, one row). For each job line and for each rule, say which fact(s) every result must carry, and give the PAGE\'S OWN WORDS for it.\n\n'
20
+ + 'Your goal: the ~ rules are the person\'s intent. For each rule, say which words on the page would let code check that every result keeps it. Code will look for the words you give, and the person will see them and can drop them.\n\n'
21
+ + 'A "result" is one item the page lists (one flight, one stay, one row).\n\n'
22
+ + 'For each job line and for each ~ rule, do ONE of two things:\n'
23
+ + '1. The page can show the rule. Give a fact: the PAGE\'S OWN WORDS that a result carries when it keeps the rule. The words do not have to be the rule\'s words, but they must carry the rule\'s MEANING. Add a one-line "why" that says what those words on a result mean for the rule.\n'
24
+ + '2. The page cannot show the rule: how the answer is written, its tone or style, or anything the page does not hold. Give NO fact for it. Put it in "cannot" with its line and rule number and a one-line "why".\n'
25
+ + 'Never tie a rule to page words that do not carry its meaning. A rule with no fact is a correct answer when the page cannot show it.\n\n'
20
26
  + 'Return ONLY a JSON object, no prose, no code fence:\n'
21
- + '{"facts":[{"name":"<letters and spaces only>","from":"<line N | line N rule M>","shape":"place|money|time|phrase","words":["<page words>", ...],"currency":["<symbol>"],"unit":["<words after the amount>"],"reading":<optional, see below>}]}\n\n'
27
+ + '{"facts":[{"name":"<letters and spaces only>","from":"<line N | line N rule M>","shape":"place|money|time|phrase","words":["<page words>", ...],"why":"<one line>","currency":["<symbol>"],"unit":["<words after the amount>"],"reading":<optional, see below>}],"cannot":[{"from":"line N rule M","why":"<one line>"}]}\n\n'
22
28
  + 'shape meanings:\n'
23
29
  + '- place: words = ways the page writes the place (a city, an airport name), copied from the page.\n'
24
30
  + '- money: words = the label(s) written right BEFORE the amount, copied from the page. currency / unit = how the page writes the currency ("$") and/or the words after the amount ("US dollars"); give every spelling the page uses, as lists.\n'
@@ -65,7 +65,8 @@ import {
65
65
  capTooSmallText, draftingSpent, EARLIER_MISSING_SAY, potSplit, STARTED_OVER_FILE, usdText,
66
66
  } from '../draftspend.js';
67
67
  import { jobKeyOfCard } from '../jobkey.js';
68
- import { flowValues, valuesHash } from '../runvalues.js';
68
+ import { flowValues, valuesHash, parseWaitMs } from '../runvalues.js';
69
+ import { DEFAULT_ACTION_WAIT_MS } from '../action-stop.js';
69
70
  import { capAboveSpentText, capNotAboveSpent } from './authorvalues.js';
70
71
  import { createFlowsDoor } from './authorflows.js';
71
72
  import { createTriggerDoor } from './authortrigger.js';
@@ -290,7 +291,7 @@ export function createAuthor(opts) {
290
291
  // A child never comes back to life, so a stale "alive" only delays the offer; asked AFTER the files were read, the questions are already on disk (C9's order is for a missing result)
291
292
  if (childRunning(dir)) return { ...shared, phase: newest > 0 ? (cur.kind === 'answers' ? 'redrafting' : 'revising') : 'drafting' };
292
293
  const lineText = (line) => parseJobBox(typeof card?.job === 'string' ? card.job : '').steps[line - 1]?.text ?? null;
293
- const questions = q.questions.map((x) => ({ k: x.k, line: x.line, lineText: lineText(x.line), question: scrub(x.question, keys), answered: x.answer !== null, ...(x.source === 'look' ? { source: 'look', ask: x.ask, proposes: typeof x.proposal === 'string' && (x.ask === 'reading' || x.ask === 'check'), drops: Number.isInteger(x.ruleNo), shown: scrub(panelQuestionText(x), keys) } : {}) }));
294
+ const questions = q.questions.map((x) => ({ k: x.k, line: x.line, lineText: lineText(x.line), question: scrub(x.question, keys), answered: x.answer !== null, ...(x.source === 'look' ? { source: 'look', ask: x.ask, proposes: typeof x.proposal === 'string' && (x.ask === 'reading' || x.ask === 'check' || x.ask === 'action'), drops: Number.isInteger(x.ruleNo), shown: scrub(panelQuestionText(x), keys) } : {}) }));
294
295
  return { ...shared, stepList: stepListOf(dir, rel, keys, true), phase: 'questions-open', plan: rel, questions, openK: q.open[0].k, total: q.questions.length };
295
296
  }
296
297
  if (q.questions.length > 0) return { ...shared, phase: 'stopped', say: ANSWERS_NOT_DRAFTED_SAY };
@@ -307,6 +308,32 @@ export function createAuthor(opts) {
307
308
  * @param {string} dir @param {number[]} ns the plans' numbers @param {string} [only] the one plan folder (relative)
308
309
  * @returns {string[]}
309
310
  */
311
+ /**
312
+ * The ONE writer of an answer-style redraft (M4e am24): `card-<n>.json`, `prose-<n>.txt` and the marker `redraft-<n>.json` written once ('wx'), then
313
+ * `fwdloop draft` as a detached child. A failure removes what it wrote (and `undoToo`) and says so; the redraft uses none of the revises.
314
+ * @param {{id: string, dir: string, v: any, vet: any, env: any, marker: any, argvOf: (n: number, proseFile: string, realRoot: string) => string[], failSay: (code: string) => string, undoToo?: string[]}} o
315
+ */
316
+ function startRedraft({
317
+ id, dir, v, vet, env, marker, argvOf, failSay, undoToo = [],
318
+ }) {
319
+ const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
320
+ const files = [`card-${n}.json`, `prose-${n}.txt`, `redraft-${n}.json`].map((f) => join(dir, f));
321
+ const undo = () => { for (const f of [...files, ...undoToo]) rmSync(f, { force: true }); };
322
+ let child;
323
+ try {
324
+ writeFileSync(files[0], `${JSON.stringify(vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
325
+ writeFileSync(files[1], vet.prose, { mode: 0o600, flag: 'wx' });
326
+ writeFileSync(files[2], `${JSON.stringify(marker)}\n`, { mode: 0o600, flag: 'wx' });
327
+ child = spawnDetached({ bin, argv: argvOf(n, files[1], realpathSync(root)), env, logPath: join(dir, `redraft-${n}.log`) });
328
+ } catch (e) {
329
+ undo();
330
+ return { status: 500, body: { ok: false, refused: 'spawn', say: failSay(String(/** @type {any} */ (e)?.code ?? 'error')), draftId: id } };
331
+ }
332
+ child.on('error', () => {});
333
+ writePidFile(dir, child);
334
+ return { status: 202, body: { ok: true, draftId: id, n, redrafting: true } };
335
+ }
336
+
310
337
  function carryArgv(dir, ns, only) {
311
338
  const rels = only === undefined ? [...ns].sort((a, b) => b - a).map((x) => `draft-${x}`).concat('draft') : [only];
312
339
  const rel = rels.find((r) => readFileInside(join(dir, r), RECORD_FILE).ok);
@@ -333,8 +360,11 @@ export function createAuthor(opts) {
333
360
  const list = card && Array.isArray(card.rows) && Array.isArray(card.suggested) ? { lines: [...cardLinesOf(decl)].sort((a, b) => a - b), rows: card.rows, suggested: card.suggested } : null;
334
361
  // 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
335
362
  const planLines = parsed?.ok === true ? parsed.lines.map((/** @type {any} */ l) => ({ n: l.n, text: l.text, rules: l.guardrail ? l.guardrail.split('; ') : [] })) : [];
363
+ // 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)
364
+ const act = readJson(dir, `${rel}/log.json`)?.action;
365
+ const action = isObj(act) && Number.isInteger(act.line) && act.dropped !== true ? { line: act.line, ...(act.by === 'agent' || act.by === 'you' ? { by: act.by } : {}) } : null;
336
366
  return {
337
- checked: checkedLines(decl, opts), notChecked: { ...view, ...(isObj(ncFile?.by) ? { by: ncFile.by } : {}) }, ...(list ? { list, planLines, always: [...EVERY_STEP_TEXTS] } : {}),
367
+ ...(action ? { action } : {}), checked: checkedLines(decl, opts), notChecked: { ...view, ...(isObj(ncFile?.by) ? { by: ncFile.by } : {}) }, ...(list ? { list, planLines, always: [...EVERY_STEP_TEXTS] } : {}),
338
368
  };
339
369
  }
340
370
 
@@ -405,6 +435,9 @@ export function createAuthor(opts) {
405
435
  return u.ok ? [] : no(`${u.say} Nothing was spent.`);
406
436
  }
407
437
 
438
+ /** M13 am11: with a Destination on the card the prose carries a tentative send on the last line; the draft child asks the AI whether it is the action. @param {any} card */
439
+ const actionArgv = (card) => (typeof card.destination === 'string' && card.destination !== '' ? ['--action', 'check'] : []);
440
+
408
441
  /** The flags that make a draft child use the card's model and thinking choice. @param {any} card */
409
442
  const modelArgv = (card) => ['--model', card.model, '--provider', card.provider, ...(card.thinking === true ? ['--thinking'] : []),
410
443
  // M13 piece 4: the card's Flow type and MCP ride every draft of the job (first, revised, redrafted)
@@ -579,7 +612,7 @@ export function createAuthor(opts) {
579
612
  let child;
580
613
  try {
581
614
  child = spawnDetached({
582
- 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'),
615
+ bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName, ...carryFrom, ...modelArgv(card), ...actionArgv(card)], env: loaded.env, logPath: join(dir, 'child.log'),
583
616
  });
584
617
  } catch (e) {
585
618
  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 } };
@@ -671,11 +704,16 @@ export function createAuthor(opts) {
671
704
  // M4d am16 item 1: the first run gets what is LEFT of the card's cap after drafting, as its own signed values (the flow stays signed at the card's cap, and
672
705
  // every later run that does not draft gets the whole of it). Nothing spent on drafting = no values file = the whole cap.
673
706
  let values = null;
674
- if (pot.split.spentUsd > 0) {
675
- const prose = readFileInside(join(dir, v.plan), 'prose.txt');
676
- const parsed = prose.ok ? parseSignedText(prose.text) : null;
707
+ // 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
708
+ const cardWait = typeof v.card?.askWait === 'string' ? v.card.askWait.trim().toLowerCase() : '';
709
+ const proseNow = readFileInside(join(dir, v.plan), 'prose.txt');
710
+ const parsedNow = proseNow.ok ? parseSignedText(proseNow.text) : null;
711
+ 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;
712
+ if (pot.split.spentUsd > 0 || (actionWait !== null && parseWaitMs(actionWait.wait) !== DEFAULT_ACTION_WAIT_MS)) {
713
+ const parsed = parsedNow;
677
714
  if (parsed && parsed.ok) {
678
- const vals = { ...flowValues(parsed.arbiter), capUsd: pot.split.leftUsd };
715
+ const own = flowValues(parsed.arbiter);
716
+ const vals = { ...own, capUsd: pot.split.spentUsd > 0 ? pot.split.leftUsd : own.capUsd, ...(actionWait === null ? {} : { askWaits: { ...own.askWaits, [actionWait.line]: actionWait.wait } }) };
679
717
  values = { flow: name, flowSignatureHash: result.signature.flow, version: 0, values: vals, hash: valuesHash({ flow: name, flowSignatureHash: result.signature.flow, runId: null, version: 0, values: vals }), signedBy, at: new Date().toISOString() };
680
718
  }
681
719
  }
@@ -731,7 +769,7 @@ export function createAuthor(opts) {
731
769
  try {
732
770
  child = spawnDetached({
733
771
  bin,
734
- 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)],
772
+ 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)],
735
773
  env: loaded.env,
736
774
  logPath: join(dir, `revise-${n}.log`),
737
775
  });
@@ -770,12 +808,12 @@ export function createAuthor(opts) {
770
808
  // space (one `~` line is one line) instead of refused. Every other question keeps its own gate (blank, one line).
771
809
  const look = q.source === 'look';
772
810
  // 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
773
- // M10 am29: the button used rides as a typed `choice`; absent = the words reading (CLI and old pages). agree needs a proposal, drop/agree are look asks only.
811
+ // M10 am29: the button used rides as a typed `choice`. agree needs a proposal, drop/agree are look asks only.
774
812
  const choice = b.choice;
775
813
  // M10 am32 A: every new answer carries its button's choice; an answer with none is refused before anything is written (old answer files are still read by the readers)
776
814
  if (choice === undefined) return { status: 400, body: { ok: false, refused: 'bad-choice', say: 'This page is out of date. Reload it and answer again. Nothing was saved.' } };
777
815
  {
778
- const proposes = look && typeof q.proposal === 'string' && (q.ask === 'reading' || q.ask === 'check');
816
+ const proposes = look && typeof q.proposal === 'string' && (q.ask === 'reading' || q.ask === 'check' || q.ask === 'action');
779
817
  if (choice !== 'agree' && choice !== 'drop' && choice !== 'rule') return { status: 400, body: { ok: false, refused: 'bad-choice', say: 'That answer is not one of the choices. Nothing was saved.' } };
780
818
  if ((choice === 'agree' && !proposes) || (choice === 'drop' && !look)) return { status: 400, body: { ok: false, refused: 'bad-choice', say: 'That choice is not offered for this question. Nothing was saved.' } };
781
819
  }
@@ -801,7 +839,11 @@ export function createAuthor(opts) {
801
839
  return { line: x.line, question: x.question, answer: typed, ...ruleOfAnswer(x, typed, ch), ruleNo: x.ruleNo, ruleText: x.ruleText, ask: x.ask, proposal: x.proposal };
802
840
  });
803
841
  const adds = all.filter((x) => x.rule !== null);
804
- const grown = applyAnswers(typeof v.card.job === 'string' ? v.card.job : '', all);
842
+ // M13 am11 rule 2: the answer to the action question adds the agreed or typed line as the job's LAST line (numbered by the card), (there is no Drop it: the answer door refuses it); the redraft is told
843
+ const act = all.find((x) => x.ask === 'action');
844
+ const baseJob = typeof v.card.job === 'string' ? v.card.job : '';
845
+ const jobWithAction = act !== undefined && act.action === 'known' && typeof act.actionLine === 'string' && act.actionLine !== '' ? `${baseJob.replace(/\s+$/, '')}\n${act.actionLine}` : baseJob;
846
+ const grown = applyAnswers(jobWithAction, all);
805
847
  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.' } };
806
848
  const vet = vetCard({ ...v.card, job: grown.job }, loaded, draftedSoFar(dir, v.card), readJson(dir, RUN_OF_FILE)?.flow);
807
849
  if (!vet.ok) return vet.reply;
@@ -811,39 +853,24 @@ export function createAuthor(opts) {
811
853
  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.' } };
812
854
  }
813
855
  // 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`.
814
- redraft = { vet, all, picks: grown.picks, left: grown.left, columns: grown.columns };
856
+ redraft = { vet, all, picks: grown.picks, left: grown.left, columns: grown.columns, action: act === undefined ? (vet.card.destination === '' ? null : 'check') : act.action };
815
857
  }
816
858
  try {
817
859
  // 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
818
860
  writeFileSync(answerFile, `${JSON.stringify({
819
861
  k: v.openK, line: q.line, question: q.question, answer, ...(choice === undefined ? {} : { choice }), at,
820
- ...(look ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: q.proposal ?? null, rule: effect.rule } : {}),
862
+ ...(look ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: q.proposal ?? null, rule: effect.rule ?? (effect.action === 'known' ? effect.actionLine : null) } : {}),
821
863
  })}\n`, { mode: 0o600, flag: 'wx' });
822
864
  } catch (e) {
823
865
  return { status: 409, body: { ok: false, refused: 'already-answered', say: /** @type {any} */ (e)?.code === 'EEXIST' ? 'That question already has an answer.' : 'The answer could not be saved. Nothing was sent.' } };
824
866
  }
825
867
  if (!last) return { status: 200, body: { ok: true, draftId: id, next: v.openK + 1 } };
826
- const n = Math.max(0, ...v.revises.map((x) => x.n)) + 1;
827
- const files = [`card-${n}.json`, `prose-${n}.txt`, `redraft-${n}.json`].map((f) => join(dir, f));
828
- const undo = () => { for (const f of [...files, answerFile]) rmSync(f, { force: true }); };
829
- let child;
830
- try {
831
- writeFileSync(files[0], `${JSON.stringify(redraft.vet.card, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
832
- writeFileSync(files[1], redraft.vet.prose, { mode: 0o600, flag: 'wx' });
833
- 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' });
834
- child = spawnDetached({
835
- bin,
836
- 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(',')] : []), ...(redraft.columns.length ? ['--columns', JSON.stringify(redraft.columns)] : []), ...modelArgv(redraft.vet.card)],
837
- env: loaded.env,
838
- logPath: join(dir, `redraft-${n}.log`),
839
- });
840
- } catch (e) {
841
- undo();
842
- return { status: 500, body: { ok: false, refused: 'spawn', say: `The plan could not be drafted again (${/** @type {any} */ (e)?.code ?? 'error'}). Your answer was not kept; answer again. Nothing was spent.`, draftId: id } };
843
- }
844
- child.on('error', () => {});
845
- writePidFile(dir, child);
846
- return { status: 202, body: { ok: true, draftId: id, n, redrafting: true } };
868
+ return startRedraft({
869
+ id, dir, v, vet: redraft.vet, env: loaded.env, undoToo: [answerFile],
870
+ marker: { fromPlan: v.plan, answers: redraft.all.map((x) => ({ line: x.line, question: x.question, answer: x.answer })), ...(redraft.left.length ? { left: redraft.left } : {}) },
871
+ argvOf: (n, proseFile, realRoot) => ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realRoot, '--name', redraft.vet.card.flowName, '--no-questions', ...(redraft.action === null ? [] : ['--action', redraft.action]), ...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(',')] : []), ...(redraft.columns.length ? ['--columns', JSON.stringify(redraft.columns)] : []), ...modelArgv(redraft.vet.card)],
872
+ failSay: (code) => `The plan could not be drafted again (${code}). Your answer was not kept; answer again. Nothing was spent.`,
873
+ });
847
874
  },
848
875
 
849
876
  /**