fwdloop 0.28.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 (56) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +27 -5
  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 +11 -4
  7. package/src/checked.js +5 -2
  8. package/src/checkpick.js +257 -0
  9. package/src/checkwords.js +24 -0
  10. package/src/closers.js +8 -1
  11. package/src/declaration.js +53 -3
  12. package/src/drafter.js +114 -33
  13. package/src/learn.js +1 -1
  14. package/src/learnstore.js +6 -6
  15. package/src/memo.js +120 -0
  16. package/src/model-step.js +89 -17
  17. package/src/pageask.js +9 -6
  18. package/src/pagedropwords.js +9 -0
  19. package/src/panel/author.js +31 -9
  20. package/src/panel/authorcard.js +51 -2
  21. package/src/panel/data.js +12 -7
  22. package/src/panel/index.html +137 -59
  23. package/src/panel/result.js +28 -7
  24. package/src/panel/server.js +2 -1
  25. package/src/pickrecord.js +146 -0
  26. package/src/plain-checks.js +1 -0
  27. package/src/provider.js +4 -1
  28. package/src/runfile.js +4 -2
  29. package/src/runner.js +82 -30
  30. package/src/send.js +71 -4
  31. package/src/setup.js +13 -1
  32. package/types/ask.d.ts +2 -1
  33. package/types/audit-fold.d.ts +13 -2
  34. package/types/authoring.d.ts +6 -2
  35. package/types/checked.d.ts +7 -2
  36. package/types/checkpick.d.ts +149 -0
  37. package/types/checkwords.d.ts +14 -0
  38. package/types/closers.d.ts +2 -1
  39. package/types/declaration.d.ts +9 -0
  40. package/types/drafter.d.ts +12 -25
  41. package/types/learn.d.ts +1 -0
  42. package/types/learnstore.d.ts +2 -3
  43. package/types/memo.d.ts +15 -0
  44. package/types/model-step.d.ts +5 -0
  45. package/types/pageask.d.ts +9 -2
  46. package/types/pagedropwords.d.ts +1 -0
  47. package/types/panel/author.d.ts +1 -1
  48. package/types/panel/authorcard.d.ts +41 -0
  49. package/types/panel/result.d.ts +9 -3
  50. package/types/pickrecord.d.ts +88 -0
  51. package/types/runfile.d.ts +7 -2
  52. package/types/runner.d.ts +16 -5
  53. package/types/send.d.ts +10 -2
  54. package/types/setup.d.ts +1 -56
  55. package/src/attemptdiff.js +0 -118
  56. package/types/attemptdiff.d.ts +0 -38
package/src/model-step.js CHANGED
@@ -189,7 +189,7 @@ function addMeter(cumulative, metered) {
189
189
  // faulted — caught live: `toolFields` threw on `cumulative.ungranted`
190
190
  // being undefined the very first time a transport fault hit round 1.
191
191
  return {
192
- costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused, thinking: cumulative.thinking,
192
+ costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused, thinking: cumulative.thinking, badCalls: cumulative.badCalls, forcedRefused: cumulative.forcedRefused,
193
193
  };
194
194
  }
195
195
 
@@ -244,6 +244,10 @@ function toolFields(cumulative) {
244
244
  // absence can never be confused with "none".
245
245
  refused: cumulative.refused,
246
246
  ...(cumulative.ungranted.length > 0 ? { ungranted: cumulative.ungranted } : {}),
247
+ // M14 item 10: bare-agent's facts about calls that went wrong (`r.badCalls`, whole attempt, in order); left off once empty, like `ungranted`
248
+ ...(cumulative.badCalls.length > 0 ? { badCalls: cumulative.badCalls } : {}),
249
+ // ruling A: a forced call refused before anything was metered is said on the row, never silently dropped
250
+ ...(cumulative.forcedRefused ? { forcedRefused: FORCED_REFUSED_SAY } : {}),
247
251
  };
248
252
  }
249
253
 
@@ -263,12 +267,15 @@ function thinkingStatusOf(r) {
263
267
  /**
264
268
  * The provider with one addition: each `generate` result is handed to `seen` before the Loop meters that call, so the call's diary row can say what bare-agent
265
269
  * reported for THAT call (thinking status, the tool names it asked for); the Loop's own `onLlmResult` payload carries neither. Everything else reads through.
266
- * @param {any} provider @param {(result: any) => void} seen
270
+ * @param {any} provider @param {(result: any) => void} seen @param {{on: boolean}|null} [force] - M4d am37: while `on`, the next call carries `toolChoice: {name: 'emit_artifact'}`
267
271
  */
268
- function watchCalls(provider, seen) {
272
+ function watchCalls(provider, seen, force = null) {
269
273
  const watched = Object.create(provider);
270
- watched.generate = async (...a) => {
271
- const r = await provider.generate(...a);
274
+ watched.generate = async (messages, tools, options = {}) => {
275
+ // M4d am37: the forced round forces `emit_artifact` on its FIRST call only (forcing every call would make the Loop save again and again)
276
+ const forced = force !== null && force.on;
277
+ if (forced) force.on = false;
278
+ const r = await provider.generate(messages, tools, forced ? { ...options, toolChoice: { name: 'emit_artifact' } } : options);
272
279
  seen(r);
273
280
  return r;
274
281
  };
@@ -285,7 +292,29 @@ function toolRowPath(args) {
285
292
 
286
293
  const STOP_RULE = 'stop-requested';
287
294
 
295
+ /** M4d am37: the one fixed line a step that answered in text is sent, from code; the model never writes it and it never changes. */
296
+ export const NUDGE = 'You answered in text. Call emit_artifact now with that answer; do not reply in text.';
297
+
298
+ /** M4d am37: a provider that says it does not send `toolChoice` (`makeProvider` sets the flag from the row's shape) ignores a forced call; round 2 then sends the line unforced and a save there is the fallback. */
299
+ /** Ruling A (hamr 2026-11-03): the fixed say on the audit row of a try whose forced call was refused with no usage returned; it books $0. */
300
+ export const FORCED_REFUSED_SAY = 'refused, no bill returned';
301
+
302
+ const IGNORES_TOOL_CHOICE = (provider) => provider?.honoursToolChoice === false;
303
+
288
304
  /** The attempt result for a Stop that landed mid-attempt: every call made is already summed into `cumulative`. */
305
+ /**
306
+ * M14 item 9: the retry's gap for a try cut off at the output limit, from bare-agent's own facts (`r.cutOff`): the output tokens, how many of them were thinking, and the limit.
307
+ * A fact bare-agent did not report is said so, never a number. `null` when the run carries no `cutOff` (the caller keeps its older words).
308
+ * @param {{outputTokens: number|null, reasoningTokens: number|null, maxTokensRequested: number|null}|undefined} c
309
+ */
310
+ function cutOffRed(c) {
311
+ if (!c || typeof c !== 'object') return null;
312
+ const out = Number.isFinite(c.outputTokens) ? `${c.outputTokens} output tokens` : 'an output size that was not reported';
313
+ const thinking = Number.isFinite(c.reasoningTokens) ? `${c.reasoningTokens} of them thinking` : 'thinking tokens not reported';
314
+ const limit = Number.isFinite(c.maxTokensRequested) ? `the limit was ${c.maxTokensRequested}` : 'no limit was reported';
315
+ return `truncated: cut off at the output limit with no tool call — ${out}, ${thinking}; ${limit}`;
316
+ }
317
+
289
318
  function stoppedResult(cumulative, modelId, modelMatch) {
290
319
  return {
291
320
  ok: false, stopped: true, red: 'stopped by you', costUsd: cumulative.costUsd, tokens: cumulative.tokens, ...toolFields(cumulative), model: modelId, modelMatch,
@@ -353,12 +382,15 @@ export function makeLiveModelStep({
353
382
  gap: executorContext.gap,
354
383
  // M8 am7: on a retry, redo or rerun try only - the earlier runs' block, whole, the same text the drafter's block is made of; it leans the model, the close alone judges
355
384
  ...(typeof executorContext.hints === 'string' && executorContext.hints !== '' ? { fromEarlierRuns: executorContext.hints } : {}),
385
+ // M14 item 2: what happened so far in this run (src/memo.js), whole, on every try that has any; absent = nothing has happened yet. Text only, it leans the model, the close alone judges
386
+ ...(typeof executorContext.memo === 'string' && executorContext.memo !== '' ? { fromThisRun: executorContext.memo } : {}),
356
387
  // M10 am7 item 3: a step that quotes a saved page is told the form of its answer and what each result must hold
357
388
  ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: citedBrief(stepMeta.cited) } : {}),
358
389
  // M10b piece 2: a step that reads a sheet is told the shape of each claim box (bareguard's worked example), never the check
359
390
  ...(stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? { answering: sheetBrief(stepMeta.sheet) } : {}),
360
391
  });
361
- const messages = [
392
+ /** @type {any[]} */
393
+ let messages = [
362
394
  { role: 'system', content: systemPrompt },
363
395
  { role: 'user', content: userContent },
364
396
  ];
@@ -412,14 +444,25 @@ export function makeLiveModelStep({
412
444
  tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 },
413
445
  tools: /** @type {Record<string, number>} */ ({}),
414
446
  ungranted: /** @type {string[]} */ ([]),
447
+ badCalls: /** @type {any[]} */ ([]),
448
+ forcedRefused: false,
415
449
  refused,
416
450
  // M4d am25 item 4: what this attempt asked of thinking (the runner's decision, `stepMeta.thinkingMode`; null = it asked nothing) and the WORST status
417
451
  // bareagent reported across its rounds (null = none reported). The ONE place this record is built; `toolFields` hands it to every return.
418
452
  thinking: /** @type {{asked: string|null, status: string|null}} */ ({ asked: thinkingMode ?? null, status: null }),
419
453
  };
420
- let noToolCallStreak = 0;
421
-
422
- for (let round = 1; round <= 2; round += 1) {
454
+ // M4d am37: round 1 runs as today. A round 1 that ended in text (no save, no malformed call) sends round 2 the conversation so far plus the fixed line, with
455
+ // `emit_artifact` forced on its first call; a refused or unsaved round 2 sends round 3 the same line unforced. A malformed tool call keeps today's one fresh retry.
456
+ let freshRetry = false;
457
+ let forcedAsked = false;
458
+ const force = { on: false };
459
+ /** @type {'first'|'forced'|'fallback'} */
460
+ let savedBy = 'first';
461
+ // hamr's ask 2026-11-03: the text round 1 ended with, kept so a later round's save can be compared with what the model said (bounded like raw arguments)
462
+ /** @type {string|undefined} */
463
+ let firstText;
464
+
465
+ for (let round = 1; round <= 3; round += 1) {
423
466
  let capturedArtifact;
424
467
  const emitTool = {
425
468
  name: 'emit_artifact',
@@ -461,15 +504,24 @@ export function makeLiveModelStep({
461
504
  }
462
505
  }
463
506
  };
464
- const loop = new Loop({ provider: watchCalls(provider, (r) => { lastCall = r; }), rates, onLlmResult, ...stopSeam });
507
+ // M14 item 10: `checkArgs` - a call whose top-level arguments do not fit the tool's declared parameters (a wrong type, a missing required value) never runs the tool; bare-agent hands the model the refusal and reports it in `badCalls`
508
+ const loop = new Loop({ provider: watchCalls(provider, (r) => { lastCall = r; }, force), rates, onLlmResult, checkArgs: true, ...stopSeam });
465
509
 
466
510
  const startedAt = Date.now();
467
511
  let result;
512
+ force.on = round === 2 && !freshRetry && !IGNORES_TOOL_CHOICE(provider);
513
+ forcedAsked = force.on;
468
514
  try {
469
515
  // eslint-disable-next-line no-await-in-loop
470
516
  // M4d am25: the thinking switch is the runner's decision (`stepMeta.thinkingMode`, 'on' | 'off'); bareagent sends it. Absent = send none (a caller that decides nothing).
471
517
  result = await loop.run(messages, tools, { maxTokens: 16000, ...(thinkingMode ? { thinkingMode } : {}) });
472
518
  } catch (err) {
519
+ // M4d am37: the same refused forced call, when the Loop threw it instead of reporting it (see below)
520
+ if (forcedAsked && round === 2 && roundMeterings.length === 0 && !isTransportFailure(err) && err?.code !== 'EDEADLINE') {
521
+ cumulative.forcedRefused = true;
522
+ // eslint-disable-next-line no-continue
523
+ continue;
524
+ }
473
525
  const wallMs = Date.now() - startedAt;
474
526
  const partial = sumMeterings(roundMeterings);
475
527
  cumulative = addMeter(cumulative, partial);
@@ -529,12 +581,20 @@ export function makeLiveModelStep({
529
581
 
530
582
  const wallMs = Date.now() - startedAt;
531
583
  const stoppedByYou = result.error === `halt:${STOP_RULE}`;
584
+ // M4d am37: a forced call the provider refused before it answered anything (no call metered) is not the end: round 3 sends the same line unforced. It books nothing - the
585
+ // request was refused, no answer was priced - so it adds no unknown to the step's cost. Anything metered, a Stop, and a thrown transport fault or deadline stay as they were.
586
+ if (forcedAsked && round === 2 && roundMeterings.length === 0 && result.error && !stoppedByYou) {
587
+ cumulative.forcedRefused = true;
588
+ // eslint-disable-next-line no-continue
589
+ continue;
590
+ }
532
591
  // A Stop read before this Loop's first call: no call ran, so there is nothing to meter or book — and an empty metering
533
592
  // must never be added as "cost unknown" onto the calls an earlier round already made.
534
593
  if (stoppedByYou && roundMeterings.length === 0) return stoppedResult(cumulative, modelId, null);
535
594
  const metered = sumMeterings(roundMeterings);
536
595
  cumulative = addMeter(cumulative, metered);
537
596
  cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
597
+ if (Array.isArray(result.badCalls)) cumulative = { ...cumulative, badCalls: [...cumulative.badCalls, ...result.badCalls] };
538
598
  if (result.thinkingStatus !== undefined) cumulative.thinking = { asked: cumulative.thinking.asked, status: worstThinkingStatus([cumulative.thinking.status, result.thinkingStatus]) };
539
599
  appendSpendRow(spendPath, {
540
600
  provider: slot ?? null,
@@ -559,7 +619,7 @@ export function makeLiveModelStep({
559
619
  // bigger cap), never a transient fault a retry could fix.
560
620
  return {
561
621
  ok: false,
562
- red: `truncated: ${metered.tokens?.outputTokens ?? '?'} tokens, no tool call`,
622
+ red: cutOffRed(result.cutOff) ?? `truncated: ${metered.tokens?.outputTokens ?? '?'} tokens, no tool call`,
563
623
  costUsd: cumulative.costUsd,
564
624
  tokens: cumulative.tokens,
565
625
  ...toolFields(cumulative),
@@ -569,9 +629,14 @@ export function makeLiveModelStep({
569
629
  }
570
630
 
571
631
  if (capturedArtifact === undefined) {
572
- noToolCallStreak += 1;
573
- if (noToolCallStreak >= 2) {
574
- const malformed = provider?.lastMalformedToolCall ?? null;
632
+ const malformed = provider?.lastMalformedToolCall ?? null;
633
+ // today's path: a malformed tool call on round 1 is retried once fresh; a second round without a save ends the step
634
+ if (round === 1 && (malformed || result.error)) {
635
+ freshRetry = true;
636
+ // eslint-disable-next-line no-continue
637
+ continue;
638
+ }
639
+ if (freshRetry || round === 3) {
575
640
  if (malformed) {
576
641
  // bare-agent >=0.50 delivers the FULL `rawArguments` (verbatim, uncapped; `rawTruncated` is never set), and only when the provider was
577
642
  // built with `exposeMalformedArgs: true`. We bound what is logged and shown, with the cut said out loud. Absent -> no "; raw:" suffix.
@@ -586,9 +651,10 @@ export function makeLiveModelStep({
586
651
  modelMatch,
587
652
  };
588
653
  }
654
+ const tried = freshRetry ? 'twice in a row' : 'after the forced save and the fallback were tried';
589
655
  return {
590
656
  ok: false,
591
- red: `a FINISHED round (stopReason=${result.stopReason}) returned text instead of the tool twice in a row. Text: ${JSON.stringify(result.text)}`,
657
+ red: `a FINISHED round (stopReason=${result.stopReason}) returned text instead of the tool ${tried}. Text: ${JSON.stringify(result.text)}`,
592
658
  costUsd: cumulative.costUsd,
593
659
  tokens: cumulative.tokens,
594
660
  ...toolFields(cumulative),
@@ -596,8 +662,11 @@ export function makeLiveModelStep({
596
662
  modelMatch,
597
663
  };
598
664
  }
665
+ if (round === 1 && !result.error && typeof result.text === 'string' && result.text !== '') firstText = boundRaw(result.text);
666
+ // round 1 ended in text (round 2 then continues it, forced) or round 2 ended unsaved (round 3 sends the line again); a round that ended in an error continues from the messages it was sent
667
+ if (!result.error) messages = [...result.msgs, { role: 'user', content: NUDGE }];
599
668
  // eslint-disable-next-line no-continue
600
- continue; // retry once, same attempt
669
+ continue;
601
670
  }
602
671
 
603
672
  if (cumulative.costUsd === null) {
@@ -606,8 +675,11 @@ export function makeLiveModelStep({
606
675
  };
607
676
  }
608
677
 
678
+ // M4d am37: which way it saved - round 1 (or the malformed-call retry, as today), the forced call, or the unforced fallback
679
+ if (!freshRetry && round === 2) savedBy = forcedAsked ? 'forced' : 'fallback';
680
+ if (round === 3) savedBy = 'fallback';
609
681
  return {
610
- ok: true, artifact: capturedArtifact, costUsd: cumulative.costUsd, model: modelId, modelMatch, tokens: cumulative.tokens, ...toolFields(cumulative),
682
+ ok: true, artifact: capturedArtifact, savedBy, ...(savedBy !== 'first' && firstText !== undefined ? { firstText } : {}), costUsd: cumulative.costUsd, model: modelId, modelMatch, tokens: cumulative.tokens, ...toolFields(cumulative),
611
683
  };
612
684
  }
613
685
 
package/src/pageask.js CHANGED
@@ -22,7 +22,7 @@ export const DROP_IT = 'drop it';
22
22
  /** @param {unknown} text @returns {boolean} */
23
23
  export const isDropIt = (text) => String(text ?? '').trim().replace(/\.$/, '').toLowerCase() === DROP_IT;
24
24
  /** the answers that accept the code's reading of a rule; anything else the person types is their own reading */
25
- const AGREE_WORDS = ['agree', 'yes'];
25
+ export const AGREE_WORDS = ['agree', 'yes'];
26
26
  /** @param {unknown} text @returns {boolean} */
27
27
  export const isAgree = (text) => AGREE_WORDS.includes(String(text ?? '').trim().replace(/[.!]$/, '').toLowerCase());
28
28
 
@@ -139,14 +139,17 @@ export function tooManyAsksText(asks) {
139
139
  * 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).
140
140
  * `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
141
141
  * person's own words, taken word for word with newlines folded to spaces. A question that is not a look ask is never changed: its answer is its rule.
142
- * @param {{source?: string, ask?: string, proposal?: string|null}} q @param {unknown} typed
143
- * @returns {{rule: string|null, left: boolean}} `rule` = the words written as a new `~` rule (null when the rule is left Not checked)
142
+ * 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
143
+ * 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).
144
+ * @param {{source?: string, ask?: string, proposal?: string|null, check?: Record<string, any>}} q @param {unknown} typed
145
+ * @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)
144
146
  */
145
147
  export function ruleOfAnswer(q, typed) {
146
148
  const typedText = String(typed ?? '').replace(/\s*\n\s*/g, ' ').trim();
147
149
  if (q.source !== 'look') return { rule: typedText, left: false };
148
150
  const text = stripAgreeLead(typedText); // F240: "yes, check it as ..." is the person's own words minus the leading "yes,"
149
- if (q.ask === 'reading' && typeof q.proposal === 'string' && isAgree(text)) return { rule: q.proposal, left: false };
150
- if (q.ask === 'cant-check' && isDropIt(text)) return { rule: null, left: true };
151
- return { rule: text, left: false };
151
+ const shape = q.ask === 'check' || q.ask === 'no-check';
152
+ if ((q.ask === 'reading' || q.ask === 'check') && typeof q.proposal === 'string' && isAgree(text)) return { rule: q.proposal, left: false, ...(q.ask === 'check' && q.check ? { check: q.check } : {}) };
153
+ if ((q.ask === 'cant-check' || shape) && isDropIt(text)) return { rule: null, left: true };
154
+ return { rule: text, left: false, ...(shape ? { own: true } : {}) };
152
155
  }
@@ -26,6 +26,9 @@ const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
26
26
  // borrowed-from: bareloop src/pagedropwords.js@c550dc8 (the phrase dry read's sentence)
27
27
  'phrase-no-result': (d) => `"${d.other}" is on the page but in none of its results, so it is not checked.`,
28
28
  'person-left': () => 'You chose to leave it Not checked.',
29
+ // M10 am16 (items 4, 5): a shape guardrail with no check picked is Not checked, and you judge it at the Ask
30
+ 'no-pick': () => 'No check was picked for it, so you judge it at the Ask.',
31
+ 'own-words': () => 'Your own words are on the line; the machine has no check for them, so you judge it at the Ask.',
29
32
  // M10 piece 5 (item 7, am8 item 1): the signed Not-checked reasons for a job word that is not a column. `fact` = the job's word.
30
33
  'no-column': (d) => `there is no column '${d.fact}'`,
31
34
  'no-fit': (d) => `no column fits '${d.fact}'`,
@@ -45,6 +48,12 @@ const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
45
48
  */
46
49
  export const leftRuleLine = (rule) => `not checked · "${rule}" — ${WORDS['person-left'](/** @type {Dropped} */ ({}))}`;
47
50
 
51
+ /**
52
+ * M10 am16 (item 5): the plan card row for a shape guardrail that has no picked check, in the same form as {@link leftRuleLine}: `not checked · "<rule>" — <reason>`.
53
+ * @param {string} rule @param {'no-pick'|'own-words'} reason @returns {string}
54
+ */
55
+ export const pickNoteLine = (rule, reason) => `not checked · "${rule}" — ${WORDS[reason](/** @type {Dropped} */ ({}))}`;
56
+
48
57
  /** @param {Dropped} d @returns {string} the plain sentence for one drop */
49
58
  export function dropSentence(d) {
50
59
  const f = WORDS[d.reason];
@@ -46,9 +46,10 @@ import {
46
46
  checkMonthlyRoom, ConfigError, monthlyNote, monthlyRefusalText,
47
47
  } from '../monthly.js';
48
48
  import {
49
- appendAnswersToJob, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
49
+ applyAnswers, capFloorFor, capFloorOf, capFloorUsd, cardFields, checkCard, checkInputRows, parseInputLines, parseJobBox,
50
50
  } from './authorcard.js';
51
51
  import { checkedLines, notCheckedView } from '../checked.js';
52
+ import { recordPath, RECORD_FILE, KEPT_WORDS } from '../pickrecord.js';
52
53
  import { csvRolesOf } from '../sheetblock.js';
53
54
  import {
54
55
  readPriceConfig, resolveSlot, resolveUsableModel, tickedLines,
@@ -289,6 +290,18 @@ export function createAuthor(opts) {
289
290
  return { ...shared, phase: 'red', reds: res.reds, say: newest === 0 ? RED_SAY : cur.say };
290
291
  }
291
292
 
293
+ /**
294
+ * M10 am17: `--carry <record>` for a draft that follows an earlier plan. A Revise follows the newest plan folder that has a record (`draft-<n>` newest first, then `draft`);
295
+ * the redraft after the answers follows the plan that asked (`only`). No record, no flag: every guardrail is asked, as before.
296
+ * @param {string} dir @param {number[]} ns the plans' numbers @param {string} [only] the one plan folder (relative)
297
+ * @returns {string[]}
298
+ */
299
+ function carryArgv(dir, ns, only) {
300
+ const rels = only === undefined ? [...ns].sort((a, b) => b - a).map((x) => `draft-${x}`).concat('draft') : [only];
301
+ const rel = rels.find((r) => readFileInside(join(dir, r), RECORD_FILE).ok);
302
+ return rel === undefined ? [] : ['--carry', recordPath(join(dir, rel))];
303
+ }
304
+
292
305
  /**
293
306
  * What the human is shown beside a green plan at sign: "Checked" (built by `checkedLines` from the plan's typed closes, never model text) and
294
307
  * "Not checked" (the drafter's own list, always with its label). Read-only; neither is signed or in the hash. @param {string} dir @param {string} rel
@@ -297,7 +310,11 @@ export function createAuthor(opts) {
297
310
  const decl = readJson(dir, `${rel}/declaration.json`);
298
311
  const prose = readFileInside(dir, `${rel}/prose.txt`);
299
312
  const parsed = prose.ok ? parseSignedText(prose.text) : null;
300
- const opts = parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line), lines: parsed.lines, csvRoles: csvRolesOf(parsed.arbiter) } : { hasAsk: true };
313
+ const kept = readJson(dir, `${rel}/${RECORD_FILE}`)?.kept;
314
+ const opts = {
315
+ ...(parsed?.ok === true ? { askLines: parsed.arbiter.asks.map((x) => x.line), lines: parsed.lines, csvRoles: csvRolesOf(parsed.arbiter) } : { hasAsk: true }),
316
+ ...(Array.isArray(kept) ? { keptChecks: kept.filter((k) => k && k.check).map((k) => ({ line: k.line, check: k.check })), keptWords: KEPT_WORDS } : {}),
317
+ };
301
318
  return { checked: checkedLines(decl, opts), notChecked: notCheckedView(readJson(dir, `${rel}/${NOT_CHECKED_FILE}`)?.notChecked, decl) };
302
319
  }
303
320
 
@@ -504,6 +521,8 @@ export function createAuthor(opts) {
504
521
  // an earlier draft that is gone is never counted as $0: refused here, at $0, in words
505
522
  const startedFrom = body?.startedOverFrom;
506
523
  let priorUsd = 0;
524
+ /** @type {string[]} */
525
+ let carryFrom = [];
507
526
  if (startedFrom !== undefined && startedFrom !== null && startedFrom !== '' && typeof startedFrom !== 'string') {
508
527
  return { status: 400, body: { ok: false, refused: 'started-over-from', say: 'startedOverFrom must be the id of an earlier draft (a string).' } };
509
528
  }
@@ -512,6 +531,8 @@ export function createAuthor(opts) {
512
531
  const spent = draftingSpent(join(dd, startedFrom), { ceilingUsd: capFloorFor(true, home, cardFields(body)) });
513
532
  if (spent.missingEarlier) return { status: 400, body: { ok: false, refused: 'earlier-missing', say: EARLIER_MISSING_SAY } };
514
533
  priorUsd = spent.usd;
534
+ // M10 am20: a Start over carries the picks of the plan it starts over from, through the same record path as a Revise
535
+ carryFrom = carryArgv(join(dd, startedFrom), (view(startedFrom, keys)?.revises ?? []).map((x) => x.n));
515
536
  }
516
537
  const vet = vetCard(body, loaded, priorUsd, runOf?.flow);
517
538
  if (!vet.ok) return vet.reply;
@@ -538,7 +559,7 @@ export function createAuthor(opts) {
538
559
  let child;
539
560
  try {
540
561
  child = spawnDetached({
541
- bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName, ...modelArgv(card)], env: loaded.env, logPath: join(dir, 'child.log'),
562
+ bin, argv: ['draft', proseFile, '--out', join(dir, 'draft'), '--root', realpathSync(root), '--name', card.flowName, ...carryFrom, ...modelArgv(card)], env: loaded.env, logPath: join(dir, 'child.log'),
542
563
  });
543
564
  } catch (e) {
544
565
  return { status: 500, body: { ok: false, refused: 'spawn', say: `The draft could not be started (${/** @type {any} */ (e)?.code ?? 'error'}). Nothing was spent.`, draftId: id } };
@@ -690,7 +711,7 @@ export function createAuthor(opts) {
690
711
  try {
691
712
  child = spawnDetached({
692
713
  bin,
693
- argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName, ...modelArgv(vet.card)],
714
+ argv: ['draft', proseFile, '--out', join(dir, `draft-${n}`), '--root', realpathSync(root), '--name', vet.card.flowName, ...carryArgv(dir, v.revises.map((x) => x.n)), ...modelArgv(vet.card)],
694
715
  env: loaded.env,
695
716
  logPath: join(dir, `revise-${n}.log`),
696
717
  });
@@ -706,7 +727,7 @@ export function createAuthor(opts) {
706
727
  * `POST /api/author/:id/answer` body `{ k, answer }` (M4e amendments 24, 25): the human's answer to the plan's question `k` of `n`, one at a time.
707
728
  * A blank answer is refused and the question stays open; there is no skip. The answer is written ONCE ('wx') as `<plan>/answer-<k>.json`. After
708
729
  * the LAST answer the plan is drafted again as a fresh plain `fwdloop draft --no-questions` child (it never asks), from the submitted card with
709
- * each answer added word for word as a `~` guardrail under its line (the one `appendAnswersToJob`, then the one `cardToProse`). It is booked as
730
+ * each answer added word for word as a `~` guardrail under its line (the one `applyAnswers`, then the one `cardToProse`). It is booked as
710
731
  * an answer redraft (`redraft-<n>.json`), not a revise: it uses none of the 2. Synchronous, like `revise`; a refusal at $0 writes nothing.
711
732
  * @param {string} id @param {any} body
712
733
  */
@@ -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,6 +18,7 @@ import { checkFlowName } from '../flow.js';
18
18
  import { isWebUrl } from '../pagefetch.js';
19
19
  import { checkSendDestination } from '../runner.js';
20
20
  import { parseSignedText } from '../signed-text.js';
21
+ import { checkSendLineGuardrail } from '../declaration.js';
21
22
  import { capTooSmallText } from '../draftspend.js';
22
23
  import { startableMcpServers, mcpConfigFor } from '../mcp-sources.js';
23
24
  import { mcpPickFor } from '../mcp-pick.js';
@@ -129,6 +130,50 @@ export function appendAnswersToJob(job, answers) {
129
130
  return { job: out.join('\n'), added };
130
131
  }
131
132
 
133
+ /**
134
+ * M10 am21: the submitted job box with ONE `~` line of a job line replaced by the words of an answer (the edited added line the ask was about). Pure.
135
+ * @param {string} job @param {number} line the job line (step) number @param {string} oldText the `~` words to replace (case and spacing aside) @param {string} newText
136
+ * @returns {{ job: string, replaced: boolean }}
137
+ */
138
+ export function replaceRuleOnJob(job, line, oldText, newText) {
139
+ const norm = (/** @type {string} */ t) => t.toLowerCase().replace(/\s+/g, ' ').trim();
140
+ const raw = String(job).split('\n');
141
+ let step = 0;
142
+ for (let i = 0; i < raw.length; i += 1) {
143
+ const t = raw[i].trim();
144
+ if (t === '') continue;
145
+ if (!t.startsWith('~')) { step += 1; continue; }
146
+ if (step === line && norm(t.slice(1)) === norm(oldText)) { raw[i] = `~ ${newText}`; return { job: raw.join('\n'), replaced: true }; }
147
+ }
148
+ return { job: String(job), replaced: false };
149
+ }
150
+
151
+ /**
152
+ * THE one writer of what a set of answers does to the job box and to the picks (M4e am24, M10 am16 (4), M10 am21): an answer is one more `~` line under its job line
153
+ * (`appendAnswersToJob`), EXCEPT the answer to an ask about an edited added line (`pairRule`), which REPLACES that line's words (the old added line never comes back).
154
+ * Picks and left rules are numbered as the asks carried them; an edited-line pick is kept under its source's number (`pairRule`), with the edited words as `added`.
155
+ * @param {string} job @param {{line: number, rule: string|null, left: boolean, check?: Record<string, any>|null, own?: boolean, ruleNo?: number, ruleText?: string, ask?: string, pairRule?: number}[]} all
156
+ * @returns {{job: string, added: number, picks: {line: number, rule: number|undefined, check: Record<string, any>|null, added: string, own?: boolean}[], left: {line: number, rule: number|undefined}[]}}
157
+ */
158
+ export function applyAnswers(job, all) {
159
+ let out = job;
160
+ let done = 0;
161
+ /** @type {{ line: number, answer: string }[]} */
162
+ const appends = [];
163
+ for (const x of all) {
164
+ if (x.rule === null) continue;
165
+ if (typeof x.pairRule === 'number') {
166
+ const r = replaceRuleOnJob(out, x.line, String(x.ruleText ?? ''), x.rule);
167
+ if (r.replaced) { out = r.job; done += 1; }
168
+ } else appends.push({ line: x.line, answer: x.rule });
169
+ }
170
+ const grown = appendAnswersToJob(out, appends);
171
+ const picks = all.filter((x) => (x.ask === 'check' || x.ask === 'no-check') && !x.left)
172
+ .map((x) => ({ line: x.line, rule: x.pairRule ?? x.ruleNo, check: x.check ?? null, added: /** @type {string} */ (x.rule), ...(x.own ? { own: true } : {}) }));
173
+ const left = all.filter((x) => x.left).flatMap((x) => [{ line: x.line, rule: x.ruleNo }, ...(typeof x.pairRule === 'number' ? [{ line: x.line, rule: x.pairRule }] : [])]);
174
+ return { job: grown.job, added: grown.added + done, picks, left };
175
+ }
176
+
132
177
  /**
133
178
  * THE one place a step's `~` lines become its guardrail: several `~` lines under one step are ONE continuous guardrail (hamr ruling 2026-10-09),
134
179
  * each part verbatim (trimmed), in typed order, joined by "; ". An answer (am24) is one more `~` line, so it joins here too. The signed-text parser
@@ -393,9 +438,10 @@ export function checkCard(card, { root, keys = [], home, runOf }) {
393
438
  }
394
439
  } else no('capUsd', 'The cap must be a number above 0 (dollars per run).');
395
440
 
396
- // 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
397
442
  const dest = card.destination;
398
- 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 {
399
445
  const why = destinationRefusal(dest, root);
400
446
  if (why !== null) no('destination', why);
401
447
  }
@@ -447,5 +493,8 @@ export function checkCard(card, { root, keys = [], home, runOf }) {
447
493
  }
448
494
  return { ok: false, refusals };
449
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 };
450
499
  return { ok: true, prose };
451
500
  }
package/src/panel/data.js CHANGED
@@ -47,11 +47,11 @@ import {
47
47
  NO_COPY_SAY, catchUpWords, endedLineWords, endedWords, needsLeftWords, nextInWords, nextTimeWords, scheduleAuditWords, scheduleBlockWords, scheduleFieldWords, scheduledNextFor, scheduledWords, startedWords,
48
48
  } from '../summary-words.js';
49
49
  import { MAX_STRUCTURE_RETRIES } from '../drafter.js';
50
- import { isResultRun, checkTypeOf, buildResult, downloadOf, readCitedChecks } from './result.js';
50
+ import { hasResultCards, checkTypeOf, buildResult, downloadOf, readCitedChecks } from './result.js';
51
51
  import { ticketListOf, ticketScheduleOf } from './tickets.js';
52
52
  import { buildJobGrid } from './jobgrid.js';
53
53
  import { readChecks } from '../diary.js';
54
- import { readRunInputs } from '../runfile.js';
54
+ import { readRunInputs, readRunRecord } from '../runfile.js';
55
55
  import { filterUnsure } from '../ticket-labels.js';
56
56
  import { readSchedule } from '../schedule.js';
57
57
  import { flowTypeOf } from '../declaration.js';
@@ -1813,11 +1813,11 @@ export function getRunDetail({
1813
1813
  needsYou: (({ tag, removable }) => ({ tag, removable }))(needsYouOf({
1814
1814
  runDir: run.runDir, ctx, glyph, controls: runControls(ctx, glyph, label), nowMs: now(), reopenAt: reopenableAt(run.runDir, ctx),
1815
1815
  })),
1816
- // M10 am4: the Result tab shows for a job that reads a page, a CSV or a .docx; `checkType` is its distinct close classes (the tab's top card)
1817
- hasResult: isResultRun(ctx.arbiter),
1816
+ // M10 am4 / M15 item 1: the Result tab shows for every job but a Tickets MCP one (that keeps the grid, and M10's cards when it reads a page); `checkType` is its distinct close classes (the tab's top card)
1817
+ hasResult: ctx.flowRead.ok && hasResultCards(ctx.arbiter, ctx.flowRead.declaration),
1818
1818
  // M13 am2 item 2: the ONE decider of the Result tab. The tab shows for a job that has M10's Result page (`hasResult`) or for a Tickets MCP job (the grid, `hasGrid`); a plain or MCP job keeps what it had before M13
1819
1819
  hasGrid,
1820
- resultTab: isResultRun(ctx.arbiter) || hasGrid,
1820
+ resultTab: (ctx.flowRead.ok && hasResultCards(ctx.arbiter, ctx.flowRead.declaration)) || hasGrid,
1821
1821
  checkType: ctx.flowRead.ok ? checkTypeOf(ctx.flowRead.declaration) : '\u2014',
1822
1822
  // M9 piece 6: the block at the top of the run page (ENDED / NEXT, SCHEDULED / NEXT), words set by code
1823
1823
  summary: runSummary(ctx, glyph, { root, catalogue, triggerRead, now, home }),
@@ -1995,11 +1995,16 @@ function attachFolds(groups, runDir, flowDir, { root, flow, catalogue }) {
1995
1995
  const job = readRunJob({ root, name: flow, catalogue, runDir }).read;
1996
1996
  if (job.ok) steps = job.declaration.steps ?? [];
1997
1997
  }
1998
+ // M14 am1 item 1: a rerun's own run.json holds the reason it started with; the Audit shows it on the first step, where that reason was handed
1999
+ const rec = readRunRecord(runDir);
2000
+ const rr = rec.ok ? rec.rec.rerun : null;
2001
+ let rerun = rr && typeof rr === 'object' && rr.decision === 'rerun' && typeof rr.words === 'string' ? { words: rr.words } : null;
1998
2002
  for (const g of groups) {
1999
2003
  if (g.run) continue;
2000
2004
  const decl = steps?.find((x) => x.emits === g.step);
2001
2005
  const read = Array.isArray(decl?.reads) ? decl.reads[0] : null;
2002
- const fold = deriveFold(g, d, { about: typeof read === 'string' ? `artifacts/${read}.json` : null });
2006
+ const fold = deriveFold(g, d, { about: typeof read === 'string' ? `artifacts/${read}.json` : null, rerun });
2007
+ rerun = null;
2003
2008
  if (fold) g.fold = fold;
2004
2009
  }
2005
2010
  }
@@ -2245,7 +2250,7 @@ function resultContext({
2245
2250
  const run = resolveRunPath(root, flow, runId);
2246
2251
  if (!run.ok || !readdirInside(run.flowDir, 'runs').includes(runId)) return null; // the gateway lists real, non-symlink run folders only
2247
2252
  const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue);
2248
- if (!ctx.flowRead.ok || !isResultRun(ctx.arbiter)) return null;
2253
+ if (!ctx.flowRead.ok || !hasResultCards(ctx.arbiter, ctx.flowRead.declaration)) return null;
2249
2254
  return { run, ctx };
2250
2255
  }
2251
2256