fwdloop 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +54 -13
  3. package/package.json +3 -3
  4. package/src/ask.js +1 -1
  5. package/src/audit-fold.js +9 -1
  6. package/src/authoring.js +22 -5
  7. package/src/canrun.js +19 -16
  8. package/src/checked.js +5 -2
  9. package/src/checkpick.js +257 -0
  10. package/src/checkwords.js +24 -0
  11. package/src/closers.js +8 -1
  12. package/src/config.js +18 -0
  13. package/src/declaration.js +85 -5
  14. package/src/drafter.js +143 -47
  15. package/src/flow.js +2 -1
  16. package/src/launcher.js +4 -2
  17. package/src/learn.js +1 -1
  18. package/src/learnstore.js +8 -7
  19. package/src/mcp-checks.js +50 -0
  20. package/src/mcp-pick.js +33 -0
  21. package/src/mcp-sources.js +84 -0
  22. package/src/mcp-use.js +54 -0
  23. package/src/memo.js +120 -0
  24. package/src/model-step.js +89 -17
  25. package/src/natural.js +23 -0
  26. package/src/pageask.js +9 -6
  27. package/src/pagedropwords.js +9 -0
  28. package/src/panel/author.js +50 -28
  29. package/src/panel/authorcard.js +86 -2
  30. package/src/panel/authorflows.js +18 -14
  31. package/src/panel/authortrigger.js +241 -84
  32. package/src/panel/data.js +99 -11
  33. package/src/panel/index.html +683 -210
  34. package/src/panel/jobgrid.js +127 -0
  35. package/src/panel/result.js +28 -7
  36. package/src/panel/scheduler.js +8 -2
  37. package/src/panel/server.js +17 -7
  38. package/src/panel/settings.js +119 -4
  39. package/src/panel/tickets.js +12 -7
  40. package/src/pickrecord.js +146 -0
  41. package/src/plain-checks.js +1 -0
  42. package/src/primitives.js +34 -5
  43. package/src/provider.js +4 -1
  44. package/src/runfile.js +4 -2
  45. package/src/runner.js +170 -45
  46. package/src/send.js +71 -4
  47. package/src/setup.js +13 -1
  48. package/src/summary-words.js +15 -3
  49. package/src/ticket-draft.js +40 -42
  50. package/src/ticket-labels.js +10 -0
  51. package/src/ticket-mcp.js +33 -10
  52. package/src/ticket-next.js +33 -0
  53. package/src/ticket-shape.js +9 -0
  54. package/src/trigger-clock.js +4 -4
  55. package/src/trigger-files.js +3 -3
  56. package/src/trigger-tickets.js +41 -12
  57. package/types/ask.d.ts +2 -1
  58. package/types/audit-fold.d.ts +13 -2
  59. package/types/authoring.d.ts +10 -2
  60. package/types/canrun.d.ts +5 -12
  61. package/types/checked.d.ts +7 -2
  62. package/types/checkpick.d.ts +149 -0
  63. package/types/checkwords.d.ts +14 -0
  64. package/types/closers.d.ts +2 -1
  65. package/types/config.d.ts +6 -0
  66. package/types/declaration.d.ts +17 -0
  67. package/types/drafter.d.ts +446 -50
  68. package/types/learn.d.ts +1 -0
  69. package/types/learnstore.d.ts +2 -3
  70. package/types/mcp-checks.d.ts +8 -0
  71. package/types/mcp-pick.d.ts +23 -0
  72. package/types/mcp-sources.d.ts +51 -0
  73. package/types/mcp-use.d.ts +12 -0
  74. package/types/memo.d.ts +15 -0
  75. package/types/model-step.d.ts +5 -0
  76. package/types/natural.d.ts +2 -0
  77. package/types/pageask.d.ts +9 -2
  78. package/types/pagedropwords.d.ts +1 -0
  79. package/types/panel/author.d.ts +37 -1
  80. package/types/panel/authorcard.d.ts +52 -0
  81. package/types/panel/authorflows.d.ts +9 -1
  82. package/types/panel/authortrigger.d.ts +73 -7
  83. package/types/panel/data.d.ts +56 -2
  84. package/types/panel/jobgrid.d.ts +109 -0
  85. package/types/panel/result.d.ts +9 -3
  86. package/types/panel/server.d.ts +5 -1
  87. package/types/panel/settings.d.ts +3 -2
  88. package/types/panel/tickets.d.ts +26 -4
  89. package/types/pickrecord.d.ts +88 -0
  90. package/types/primitives.d.ts +15 -2
  91. package/types/runfile.d.ts +7 -2
  92. package/types/runner.d.ts +128 -77
  93. package/types/send.d.ts +10 -2
  94. package/types/setup.d.ts +1 -56
  95. package/types/summary-words.d.ts +22 -3
  96. package/types/ticket-draft.d.ts +40 -32
  97. package/types/ticket-labels.d.ts +6 -0
  98. package/types/ticket-mcp.d.ts +18 -1
  99. package/types/ticket-next.d.ts +23 -0
  100. package/types/ticket-shape.d.ts +5 -0
  101. package/types/trigger-clock.d.ts +4 -3
  102. package/types/trigger-files.d.ts +1 -1
  103. package/types/trigger-tickets.d.ts +18 -4
  104. package/src/attemptdiff.js +0 -118
  105. package/types/attemptdiff.d.ts +0 -38
package/src/runner.js CHANGED
@@ -54,7 +54,7 @@ import {
54
54
  writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen, setAsideAnswer,
55
55
  } from './ask.js';
56
56
  import {
57
- findUnwiredVerbStep, unwiredRed, findUnbuildableCheckStep, unbuildableRed, findUnusedMcpTool, unusedMcpToolRed,
57
+ findUnwiredVerbStep, unwiredRed, findUnbuildableCheckStep, unbuildableRed, findMcpPlanRed,
58
58
  } from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
59
59
  import { configHome, configDoorHome } from './config.js';
60
60
  import { closeByClass, isCellsPath } from './closers.js';
@@ -76,8 +76,11 @@ import {
76
76
  } from './try-checks.js';
77
77
  import { readJobThinking, readModelRecord, takeLearningsRecord } from './flowmodel.js';
78
78
  import { readRunInputs, writeRunStart } from './runfile.js';
79
+ import { buildMemo } from './memo.js';
79
80
  import { fetchPageText, isWebUrl } from './pagefetch.js';
80
- import { readTicketMcp } from './ticket-mcp.js';
81
+ import { readTicketMcp, configForServer, remoteRefusal, mcpStartOpts, startRefusal, firstLine } from './ticket-mcp.js';
82
+ import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
83
+ import { mcpToolName } from './primitives.js';
81
84
  import { decideTicket, readTicketFields } from './ticket-labels.js';
82
85
  import {
83
86
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
@@ -224,9 +227,9 @@ const holdOf = (ceilingUsd) => (Number.isFinite(ceilingUsd) && /** @type {number
224
227
  // WITHOUT the cap (M2 scope item 3, the load-bearing invariant).
225
228
  // ---------------------------------------------------------------------------
226
229
 
227
- const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap', 'hints']);
230
+ const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap', 'hints', 'memo']);
228
231
 
229
- /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null, hints?:string|null}} opts `hints` (M8 am7): the earlier runs' block, text only, for a retry / redo / rerun try */
232
+ /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null, hints?:string|null, memo?:string|null}} opts `hints` (M8 am7): the earlier runs' block, text only, for a retry / redo / rerun try; `memo` (M14): what happened so far in this run, text only, every try */
230
233
  export function buildExecutorContext(opts) {
231
234
  for (const key of Object.keys(opts ?? {})) {
232
235
  if (!EXECUTOR_FIELDS.includes(key)) {
@@ -234,7 +237,7 @@ export function buildExecutorContext(opts) {
234
237
  }
235
238
  }
236
239
  const {
237
- goal, primitives = [], reads = {}, gap = null, hints = null,
240
+ goal, primitives = [], reads = {}, gap = null, hints = null, memo = null,
238
241
  } = opts ?? {};
239
242
  return Object.freeze({
240
243
  goal,
@@ -242,6 +245,7 @@ export function buildExecutorContext(opts) {
242
245
  reads: Object.freeze({ ...reads }),
243
246
  gap: gap ?? null,
244
247
  hints: hints ?? null,
248
+ memo: memo ?? null,
245
249
  });
246
250
  }
247
251
 
@@ -249,7 +253,7 @@ export function buildExecutorContext(opts) {
249
253
  * construction test, negative vi). Walks any depth, any key, any array
250
254
  * entry; also catches a bare function value anywhere in the tree. */
251
255
  const FORBIDDEN_CONTEXT_KEYS = Object.freeze([
252
- 'close', 'shape', 'cap', 'strike', 'maxWords', 'sections', 'linesPerInvoice', 'mustCarry',
256
+ 'close', 'shape', 'cap', 'strike', 'maxWords', 'sections', 'linesPerInvoice', 'mustCarry', 'picked',
253
257
  ]);
254
258
 
255
259
  /**
@@ -478,6 +482,20 @@ export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = []
478
482
  return { ok: true, manifest, skip };
479
483
  }
480
484
 
485
+ /**
486
+ * The sources a rerun re-freezes: each input's original source. M13 item 9.1: a ticket input's source is the ticket's own address; it goes back as its LIST address with the
487
+ * ticket mark, so the rerun reads the ticket through the job's MCP tools and the signed filter, not as a web page.
488
+ * @param {Array<{id: string, source: string, ticket?: {number: number}, filter?: {outcome?: string}}>} manifest
489
+ */
490
+ export function rerunSourcesOf(manifest) {
491
+ return (manifest ?? []).map((entry) => {
492
+ const n = entry.ticket?.number;
493
+ const tail = `/${n}`;
494
+ if (!Number.isInteger(n) || !entry.source.endsWith(tail)) return { id: entry.id, path: entry.source };
495
+ return { id: entry.id, path: entry.source.slice(0, -tail.length), ticket: { number: n, ...(entry.filter?.outcome === 'anyway' ? { anyway: /** @type {const} */ (true) } : {}) } };
496
+ });
497
+ }
498
+
481
499
  /** realpath of a path that may not exist (falls back to the lexical resolve). */
482
500
  function realOrResolved(p) {
483
501
  try { return realpathSync(p); } catch { return resolve(p); }
@@ -722,17 +740,17 @@ function recordLateAnswerIfAny(runDir, now = () => new Date().toISOString()) {
722
740
  export const LEARN_ERROR_FILE = 'learn-error.jsonl';
723
741
 
724
742
  /**
725
- * @param {{flowName: string, runId: string, runDir: string, outcome: string, specHash: string|null, now: () => string}} o
743
+ * @param {{flowName: string, runId: string, runDir: string, outcome: string, now: () => string}} o
726
744
  */
727
745
  function recordRunNotes({
728
- flowName, runId, runDir, outcome, specHash, now,
746
+ flowName, runId, runDir, outcome, now,
729
747
  }) {
730
748
  if (NOT_A_RUN_END.has(outcome)) return;
731
749
  const door = configDoorHome();
732
750
  if (door.skip) return;
733
751
  try {
734
752
  const r = learnAtRunEnd({
735
- home: door.home, workflow: flowName, runId, runDir, specHash, now: new Date(now()),
753
+ home: door.home, workflow: flowName, runId, runDir, now: new Date(now()),
736
754
  });
737
755
  if (r.problem) throw new Error(r.problem);
738
756
  } catch (/** @type {any} */ e) {
@@ -803,6 +821,11 @@ function makeAuditRow({
803
821
  hintsText = /** @type {string|undefined} */ (undefined),
804
822
  hintIds = /** @type {string[]|undefined} */ (undefined),
805
823
  hintsError = /** @type {string|undefined} */ (undefined),
824
+ memoText = /** @type {string|undefined} */ (undefined),
825
+ badCalls = /** @type {any[]|undefined} */ (undefined),
826
+ sentSha256 = /** @type {string|undefined} */ (undefined),
827
+ savedBy = /** @type {string|undefined} */ (undefined),
828
+ forcedRefused = /** @type {string|undefined} */ (undefined),
806
829
  }) {
807
830
  const row = {
808
831
  step: step?.emits ?? step?.goal ?? null,
@@ -828,6 +851,16 @@ function makeAuditRow({
828
851
  // (this row, written after the call from what the try held in memory); a failed ask for the block is `hintsError`, the first line, secrets redacted.
829
852
  if (hints !== undefined) { row.hints = hints; row.hintsText = hintsText; row.hintIds = hintIds; }
830
853
  if (hintsError !== undefined) row.hintsError = hintsError;
854
+ // M14 item 7: the exact memo text this try was handed (what happened so far in the run); the key is absent when the try got none. The ONE place the text is kept.
855
+ if (memoText !== undefined) row.memoText = memoText;
856
+ // M14 item 10: bare-agent's facts about this try's calls that went wrong (`badCalls`), as the model step returned them; the key is absent when there were none. The ONE writer.
857
+ if (Array.isArray(badCalls) && badCalls.length > 0) row.badCalls = badCalls;
858
+ // M15 item 4: the sha256 of the plain-text file a send wrote; the key is only on a green send row. The ONE writer; the Result tab reads it to tell the file changed.
859
+ if (typeof sentSha256 === 'string') row.sentSha256 = sentSha256;
860
+ // M4d am37 item 5: which way the model step saved its artifact - `first` (round 1), `forced` (the forced call after the fixed line), `fallback` (the unforced call); absent when it did not save. The ONE writer.
861
+ if (savedBy === 'first' || savedBy === 'forced' || savedBy === 'fallback') row.savedBy = savedBy;
862
+ // M4d am37, ruling A: the fixed say of a try whose forced call the provider refused with no usage returned (it booked $0); absent otherwise. The ONE writer.
863
+ if (typeof forcedRefused === 'string') row.forcedRefused = forcedRefused;
831
864
  return row;
832
865
  }
833
866
 
@@ -859,9 +892,10 @@ function makeAuditRow({
859
892
  * @param {string|null} [opts.prevStepId] - the id of step stepNo-1 (null for step 1): the step a "stopped after step N-1" row is filed under
860
893
  * @param {number} [opts.triesDone] - tries a Stop already closed on this step (they count against its limit)
861
894
  * @param {string|null} [opts.runDir] - M4d am29 item 2: the run's folder, where each try saves its checks
895
+ * @param {Record<string, any>} [opts.mcpGranted] - M13 item 5: this step's signed MCP tools, already bound to its bridge (`runStepRalph` builds them); handed to the model with the verbs
862
896
  * @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string, stop?:{where:string, book:Record<string, any>, step?:string|null}}>}
863
897
  */
864
- export async function runStepRalph({
898
+ async function runStepTries({
865
899
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
866
900
  // M4d am25: the job's "Thinking on" box as the run's own copy keeps it; read once by the caller (`readJobThinking`), decided per try below by `stepThinkingMode`.
867
901
  thinkingBox = false,
@@ -881,6 +915,7 @@ export async function runStepRalph({
881
915
  runDir = null,
882
916
  // the id of step stepNo-1 (null for step 1): a Stop before this step's first call words itself "after step N-1" and is filed under that step
883
917
  prevStepId = null,
918
+ mcpGranted = {},
884
919
  }) {
885
920
  /** @type {string|null} */
886
921
  let gap = initialGap ?? null;
@@ -921,7 +956,7 @@ export async function runStepRalph({
921
956
  };
922
957
  }
923
958
 
924
- const grantedTools = Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]]));
959
+ const grantedTools = { ...Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]])), ...mcpGranted };
925
960
  // M8 am7: the earlier runs' block for THIS try only - a retry, a redo or a rerun (`stepHintsWanted`; the Chat box never decides it). It is the drafter's one block
926
961
  // function asked again now. What it handed is kept in memory and rides EVERY audit row this try writes (the row is written after the call, so the record exists once the
927
962
  // try's row does); any failure hands nothing and rides the row as `hintsError`.
@@ -938,13 +973,26 @@ export async function runStepRalph({
938
973
  }
939
974
  }
940
975
  // every row this try writes from here on carries how many hints it was handed, which, and what (none handed = no field)
941
- const rowOf = (/** @type {any} */ a) => makeAuditRow({
976
+ // M14 items 2 and 7: the memo is built fresh from the run's files before EVERY try (src/memo.js), handed whole, and kept on every row this try writes
977
+ const memo = buildMemo(runDir, { step: step?.emits ?? step?.goal ?? null });
978
+ // M14 item 10: this try's `badCalls` come back with the model step's result; every row the try writes carries them
979
+ /** @type {any[]|undefined} */
980
+ let badCalls;
981
+ // M4d am37: how this try's model step saved, as it returned it
982
+ let savedBy;
983
+ let forcedRefused;
984
+ let firstText;
985
+ const rowOf = (/** @type {any} */ a) => withFirstText(makeAuditRow({
942
986
  ...a,
987
+ ...(memo !== '' ? { memoText: memo } : {}),
988
+ ...(badCalls !== undefined ? { badCalls } : {}),
989
+ ...(savedBy !== undefined ? { savedBy } : {}),
990
+ ...(forcedRefused !== undefined ? { forcedRefused } : {}),
943
991
  ...(handed !== null ? { hints: handed.ids.length, hintsText: handed.text, hintIds: handed.ids } : {}),
944
992
  ...(handedError !== undefined ? { hintsError: handedError } : {}),
945
- });
993
+ }), firstText);
946
994
  const executorContext = buildExecutorContext({
947
- goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap, hints: handed === null ? null : handed.text,
995
+ goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap, hints: handed === null ? null : handed.text, memo: memo === '' ? null : memo,
948
996
  });
949
997
 
950
998
  // `stepMeta` is a SEPARATE argument from `executorContext` — never a
@@ -987,10 +1035,15 @@ export async function runStepRalph({
987
1035
  const tools = first.tools || result.tools ? { ...(first.tools ?? {}) } : null;
988
1036
  if (tools) for (const [k, v] of Object.entries(result.tools ?? {})) tools[k] = (tools[k] ?? 0) + v;
989
1037
  const ungranted = [...new Set([...(first.ungranted ?? []), ...(result.ungranted ?? [])])].sort();
990
- result = { ...result, refused, tools, ...(ungranted.length > 0 ? { ungranted } : {}) };
1038
+ const bad = [...(first.badCalls ?? []), ...(result.badCalls ?? [])];
1039
+ result = { ...result, refused, tools, ...(ungranted.length > 0 ? { ungranted } : {}), ...(bad.length > 0 ? { badCalls: bad } : {}) };
991
1040
  }
992
1041
  }
993
1042
  const wallMs = Date.now() - startedAt;
1043
+ badCalls = Array.isArray(result?.badCalls) ? result.badCalls : undefined;
1044
+ savedBy = typeof result?.savedBy === 'string' ? result.savedBy : undefined;
1045
+ forcedRefused = typeof result?.forcedRefused === 'string' ? result.forcedRefused : undefined;
1046
+ firstText = typeof result?.firstText === 'string' ? result.firstText : undefined;
994
1047
 
995
1048
  // A Stop landed during this try: the call in flight finished and is booked here (its cost into the run's spend and onto the one
996
1049
  // `stopped` row), no new call started. Unknown cost stays unknown (usd null, spend incomplete), never 0.
@@ -1149,6 +1202,52 @@ export async function runStepRalph({
1149
1202
  return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — exhausted attempts` };
1150
1203
  }
1151
1204
 
1205
+ /** M13 item 5: the bridge's start deadline per round-trip (bare-agent applies a total ceiling over connect + list) and one tool call's own limit */
1206
+ const MCP_START_MS = 30000;
1207
+ const MCP_CALL_MS = 120000;
1208
+
1209
+ /**
1210
+ * One step's tries (`runStepTries`), with the step's signed MCP tools (M13 items 3 and 5): the bridge starts ONCE here, before the first try, with `allow` = exactly
1211
+ * the step's `mcpTools` (any other tool does not exist for the run), and closes in a `finally` after the last. A server that is not configured, will not start or lacks a signed
1212
+ * tool refuses by name at $0 before any provider call, in `readTicketMcp`'s own words (src/ticket-mcp.js). Each tool the model sees is the bridge's, bound to the run's gated entry
1213
+ * (`resolvePrimitives`), so every call is the Gate's decision and the model step's diary row. A step with no `mcpTools` takes the plain path, untouched.
1214
+ * @param {Parameters<typeof runStepTries>[0] & {mcpServer?: string|null}} opts - `mcpServer`: the job's signed `mcp.server`
1215
+ * @returns {ReturnType<typeof runStepTries>}
1216
+ */
1217
+ export async function runStepRalph({ mcpServer = null, ...opts }) {
1218
+ const signed = opts.step?.mcpTools ?? [];
1219
+ if (signed.length === 0 || !mcpServer) return runStepTries(opts);
1220
+ const refuse = (/** @type {string} */ red) => ({ ok: /** @type {const} */ (false), outcome: 'preflight-red', red });
1221
+ const { file: config, remote } = configForServer(mcpServer);
1222
+ if (!discoverServers([config]).has(mcpServer)) return refuse(`${mcpServer} is not in ~/.mcp.json`);
1223
+ if (remote) return refuse(remoteRefusal(mcpServer));
1224
+ /** @type {any} */
1225
+ let bridge;
1226
+ try {
1227
+ bridge = await createMCPBridge({ configPaths: [config], ...mcpStartOpts(), timeout: MCP_START_MS, callTimeout: MCP_CALL_MS, confirmServer: () => true, allow: { [mcpServer]: signed } });
1228
+ } catch (/** @type {any} */ e) {
1229
+ return refuse(startRefusal(mcpServer, e));
1230
+ }
1231
+ try {
1232
+ const failed = bridge.errors.find((/** @type {any} */ e) => e.server === mcpServer);
1233
+ if (failed) return refuse(`${mcpServer} did not start: ${firstLine(failed.error)}`);
1234
+ const lacking = bridge.missing?.[0];
1235
+ if (lacking) return refuse(`${mcpServer} does not offer ${lacking.tool}`);
1236
+ const mcpGranted = {};
1237
+ for (const tool of signed) {
1238
+ const name = mcpToolName(mcpServer, tool);
1239
+ const real = bridge.tools.find((/** @type {any} */ t) => t.name === name);
1240
+ const gated = opts.primitivesMap?.[name];
1241
+ if (!real) return refuse(`${mcpServer} does not offer ${tool}`);
1242
+ if (!gated?.gatedCall) return refuse(`${name} has no gate in this run's tools (the run's primitives were not built with the job's mcp)`);
1243
+ mcpGranted[name] = { name, description: real.description, parameters: real.parameters, gateSeen: gated.gateSeen, execute: (/** @type {any} */ args) => gated.gatedCall(args, real.execute) };
1244
+ }
1245
+ return await runStepTries({ ...opts, mcpGranted });
1246
+ } finally {
1247
+ try { await bridge.close(); } catch { /* already closed */ }
1248
+ }
1249
+ }
1250
+
1152
1251
  // ---------------------------------------------------------------------------
1153
1252
  // runFlow — the entry point.
1154
1253
  // ---------------------------------------------------------------------------
@@ -1162,13 +1261,14 @@ export async function runStepRalph({
1162
1261
  * @param {unknown} opts.catalogue - passed straight through to `readFlow`.
1163
1262
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<{ok:boolean, artifact?:unknown, costUsd:number|null, red?:string, transport?:boolean, model?:string, modelMatch?:boolean}>} opts.modelStep
1164
1263
  * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'redo'|'rerun'|'timeout'|'park', reason?:string, artifactSha256?:string}>} opts.askStep
1165
- * @param {(target:string, filename:string, content:unknown, acceptedSha256?:string|null) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
1264
+ * @param {(target:string, filename:string, content:unknown, acceptedSha256?:string|null) => Promise<{ok:boolean, red?:string, bytes?:number, sha256?:string}>} opts.sendStep
1166
1265
  * @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
1167
1266
  * @param {string[]} [opts.primitiveReds] - `resolvePrimitives`'s own `reds` (e.g. bareguard refusing a symlinked file scope); any entry refuses the run at $0 like an unwired verb, before the run dir exists.
1168
1267
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
1169
1268
  * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
1170
1269
  * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; the model's hold from Settings prices (`ceilingCostUsd`); absent = no hold.
1171
1270
  * @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run.json) and kept by every resume/continue.
1271
+ * @param {{decision: 'rerun', words: string, afterStep: string|null}} [opts.rerunOf] - M14 am1 item 1: only `resumeRun`'s rerun path passes it; kept in the new run's run.json
1172
1272
  * @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
1173
1273
  * run): a human's rerun reason, carried as the FIRST ordinary step's
1174
1274
  * starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
@@ -1180,6 +1280,8 @@ export async function runStepRalph({
1180
1280
  */
1181
1281
  export async function runFlow({
1182
1282
  root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap, fetchPage,
1283
+ // M14 am1 item 1: set only by `resumeRun`'s rerun path ({decision, words, afterStep}); written once into run.json by `writeRunStart`
1284
+ rerunOf,
1183
1285
  // M4d am33: the model this run STARTED on ({ slot, model }); recorded once beside the run, kept by every resume/continue. Absent = nothing recorded.
1184
1286
  runModel,
1185
1287
  // F45 finding 3's test needs to advance wall time across a park/resume
@@ -1255,11 +1357,11 @@ export async function runFlow({
1255
1357
  });
1256
1358
  }
1257
1359
 
1258
- // M12 piece 1a (F105): a job tool no step grants is refused at $0, by name
1259
- const unusedTool = findUnusedMcpTool(declaration);
1260
- if (unusedTool) {
1360
+ // M12 piece 1a (F105), M13 piece 4: a step tool the job does not list, or a generic MCP job whose steps call none, is refused at $0, by name
1361
+ const mcpRed = findMcpPlanRed(declaration);
1362
+ if (mcpRed) {
1261
1363
  return haltRun({
1262
- flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: unusedMcpToolRed(unusedTool), spent: { value: 0 },
1364
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: mcpRed, spent: { value: 0 },
1263
1365
  });
1264
1366
  }
1265
1367
 
@@ -1310,7 +1412,7 @@ export async function runFlow({
1310
1412
  });
1311
1413
  }
1312
1414
  // M8b item 1: the run's start record, written once: the model it started on (M4d am33), the "Thinking on" box (M4d am25) and the frozen inputs
1313
- writeRunStart(runDir, { model: runModel ?? null, thinking: thinkingBox, inputs: /** @type {any[]} */ (frozen.manifest) });
1415
+ writeRunStart(runDir, { model: runModel ?? null, thinking: thinkingBox, inputs: /** @type {any[]} */ (frozen.manifest), rerun: rerunOf ?? null });
1314
1416
  // M12 piece 3 (item 9): a ticket the signed labels do not match, or a closed one, ends here: skipped, $0, nothing else runs
1315
1417
  if (frozen.skip) {
1316
1418
  return haltRun({
@@ -1344,9 +1446,7 @@ export async function runFlow({
1344
1446
  appendAudit(runDir, fullRow);
1345
1447
  if (row.spendComplete === false) spendComplete.value = false;
1346
1448
  if (modelOutput !== undefined) {
1347
- attemptsLog.push({
1348
- step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
1349
- });
1449
+ attemptsLog.push(attemptEntry(row, modelOutput));
1350
1450
  }
1351
1451
  };
1352
1452
  const spent = { value: 0 };
@@ -1372,6 +1472,7 @@ export async function runFlow({
1372
1472
  const acceptedAskEmitsThisRun = new Map();
1373
1473
 
1374
1474
  const result = await foldFromStep({
1475
+ mcpServer: declaration.mcp?.server ?? null,
1375
1476
  i0: 0,
1376
1477
  steps,
1377
1478
  askLines,
@@ -1413,7 +1514,7 @@ export async function runFlow({
1413
1514
  firstStepGap: initialGap ?? null,
1414
1515
  });
1415
1516
  recordRunNotes({
1416
- flowName: name, runId, runDir, outcome: result.outcome, specHash: signature.flow, now,
1517
+ flowName: name, runId, runDir, outcome: result.outcome, now,
1417
1518
  });
1418
1519
 
1419
1520
  if (result.outcome === 'complete') return { ...result, auditRows };
@@ -1502,6 +1603,8 @@ async function runAskSlot({
1502
1603
  // state.json on every park/re-park so a later resume can restore it
1503
1604
  // instead of substituting its own process's start.
1504
1605
  runStartedAt,
1606
+ // M13 item 5: the job's signed `mcp.server`; a redo of the step before the ask runs it again with its signed MCP tools
1607
+ mcpServer = /** @type {string|null} */ (null),
1505
1608
  }) {
1506
1609
  let redone = initialRedone;
1507
1610
  let currentPrior = priorArtifact;
@@ -1678,7 +1781,7 @@ async function runAskSlot({
1678
1781
  }
1679
1782
  // eslint-disable-next-line no-await-in-loop
1680
1783
  const redoResult = await runStepRalph({
1681
- step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
1784
+ step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
1682
1785
  readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1683
1786
  });
1684
1787
  if (!redoResult.ok) {
@@ -1736,6 +1839,8 @@ async function foldFromStep({
1736
1839
  resumeTries = { numbered: 0, done: 0 },
1737
1840
  // Amendment 13: the redo count a stop-at-ask carried in its halt record, restored for the ask step it re-enters (`i0`).
1738
1841
  resumeRedone = 0,
1842
+ // M13 item 5: the job's signed `mcp.server`, for a step that grants MCP tools (`runStepRalph` starts its bridge)
1843
+ mcpServer = /** @type {string|null} */ (null),
1739
1844
  }) {
1740
1845
  let runAcceptedThisRun = acceptedThisRun;
1741
1846
  let runUnjudged = unjudgedSinceLastAsk;
@@ -1811,11 +1916,12 @@ async function foldFromStep({
1811
1916
  });
1812
1917
  }
1813
1918
  const content = contentResult.value;
1814
- const filename = `${flowName}-${runId}-${step.emits}.json`;
1919
+ const filename = `${flowName}-${runId}-${step.emits}.md`;
1815
1920
  // eslint-disable-next-line no-await-in-loop
1816
1921
  const sendResult = await sendStep(target, filename, content, acceptedAskEmitsThisRun.get(askArtifactId), { root: flowRoot, runDir });
1817
1922
  const sendRow = makeAuditRow({
1818
1923
  step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1924
+ ...(sendResult.ok && typeof sendResult.sha256 === 'string' ? { sentSha256: sendResult.sha256 } : {}),
1819
1925
  });
1820
1926
  recordAudit(sendRow);
1821
1927
  if (!sendResult.ok) {
@@ -1861,6 +1967,7 @@ async function foldFromStep({
1861
1967
 
1862
1968
  // eslint-disable-next-line no-await-in-loop
1863
1969
  const askResult = await runAskSlot({
1970
+ mcpServer,
1864
1971
  step,
1865
1972
  stepIndex: i,
1866
1973
  askSlot,
@@ -1933,7 +2040,7 @@ async function foldFromStep({
1933
2040
  // redo's `initialGap` above.
1934
2041
  // eslint-disable-next-line no-await-in-loop
1935
2042
  const stepResult = await runStepRalph({
1936
- step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
2043
+ step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, mcpServer, initialGap: i === i0 ? firstStepGap : null, thinkingBox: readJobThinking(flowDir, runDir), learnHints: stepHintsReader({ flowName, source: inputsManifest?.[0]?.source ?? null, now }), now, runDir,
1937
2044
  readStop: () => stopPending(runDir), stepNo: i + 1, prevStepId: i > 0 ? (steps[i - 1].emits ?? steps[i - 1].goal ?? null) : null, attemptOffset: i === i0 ? resumeTries.numbered : 0, triesDone: i === i0 ? resumeTries.done : 0,
1938
2045
  });
1939
2046
  if (!stepResult.ok) {
@@ -2103,7 +2210,7 @@ function sameRoot(recorded, requested) {
2103
2210
  * @param {string} opts.runId
2104
2211
  * @param {unknown} opts.catalogue
2105
2212
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
2106
- * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
2213
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number, sha256?:string}>} opts.sendStep
2107
2214
  * @param {Record<string, any>} [opts.primitives]
2108
2215
  * @param {string[]} [opts.primitiveReds] - see `runFlow`'s own.
2109
2216
  * @param {() => string} [opts.clock]
@@ -2152,8 +2259,8 @@ export async function resumeRun({
2152
2259
  red: unwiredRed(unwiredVerb),
2153
2260
  };
2154
2261
  }
2155
- const unusedTool = findUnusedMcpTool(preflightRead.declaration);
2156
- if (unusedTool) return { outcome: 'refused', red: unusedMcpToolRed(unusedTool) };
2262
+ const mcpRed = findMcpPlanRed(preflightRead.declaration);
2263
+ if (mcpRed) return { outcome: 'refused', red: mcpRed };
2157
2264
  const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2158
2265
  if (unbuildable) return { outcome: 'refused', red: unbuildableRed(unbuildable), detail: unbuildable.why };
2159
2266
  }
@@ -2393,7 +2500,7 @@ export async function resumeRun({
2393
2500
  runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2394
2501
  });
2395
2502
  recordRunNotes({
2396
- flowName: name, runId, runDir, outcome: 'ask-expired', specHash: state.signatureHash, now,
2503
+ flowName: name, runId, runDir, outcome: 'ask-expired', now,
2397
2504
  });
2398
2505
  return { outcome: 'ask-expired', runDir, spentUsd: spent.value };
2399
2506
  }
@@ -2430,7 +2537,7 @@ export async function resumeRun({
2430
2537
  }
2431
2538
  // M8 am4: a rerun ends THIS run, so its notes count now (the new run, started below, makes its own).
2432
2539
  recordRunNotes({
2433
- flowName: name, runId, runDir, outcome: 'rerun', specHash: state.signatureHash, now,
2540
+ flowName: name, runId, runDir, outcome: 'rerun', now,
2434
2541
  });
2435
2542
 
2436
2543
  // Deterministic derived id (M3 scope item 7) — refused by name, never
@@ -2448,7 +2555,7 @@ export async function resumeRun({
2448
2555
  // `inputsManifest[].source` since `freezeInputs` first wrote it (M3
2449
2556
  // scope item 7's own note: "persist those in state.json at park if
2450
2557
  // they aren't already" — they already are, via this field).
2451
- const rerunSources = (state.inputsManifest ?? []).map((entry) => ({ id: entry.id, path: entry.source }));
2558
+ const rerunSources = rerunSourcesOf(state.inputsManifest);
2452
2559
 
2453
2560
  if (typeof onRerunStart === 'function') onRerunStart(newRunDir);
2454
2561
  const newRun = await runFlow({
@@ -2470,6 +2577,8 @@ export async function resumeRun({
2470
2577
  runModel,
2471
2578
  // Item 7: the reason becomes the new run's FIRST step's starting gap.
2472
2579
  initialGap: reason,
2580
+ // M14 am1 item 1: the new run keeps the reason in its own run.json (decision, words, the step the old run's ask followed; null = the ask was first)
2581
+ rerunOf: { decision: 'rerun', words: reason, afterStep: steps[state.stepIndex - 1]?.emits ?? null },
2473
2582
  });
2474
2583
 
2475
2584
  return {
@@ -2512,9 +2621,7 @@ export async function resumeRun({
2512
2621
  appendAudit(runDir, fullRow);
2513
2622
  if (row.spendComplete === false) spendComplete.value = false;
2514
2623
  if (modelOutput !== undefined) {
2515
- attemptsLog.push({
2516
- step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
2517
- });
2624
+ attemptsLog.push(attemptEntry(row, modelOutput));
2518
2625
  }
2519
2626
  };
2520
2627
 
@@ -2534,6 +2641,7 @@ export async function resumeRun({
2534
2641
  const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason, artifactSha256: answer.artifactSha256 });
2535
2642
 
2536
2643
  const askResult = await runAskSlot({
2644
+ mcpServer: declaration.mcp?.server ?? null,
2537
2645
  step,
2538
2646
  stepIndex: state.stepIndex,
2539
2647
  askSlot,
@@ -2588,6 +2696,7 @@ export async function resumeRun({
2588
2696
  acceptedAskEmitsThisRun.set(step.emits, askResult.acceptedSha256 ?? null);
2589
2697
 
2590
2698
  const result = await foldFromStep({
2699
+ mcpServer: declaration.mcp?.server ?? null,
2591
2700
  i0: state.stepIndex + 1,
2592
2701
  steps,
2593
2702
  askLines,
@@ -2624,7 +2733,7 @@ export async function resumeRun({
2624
2733
  attemptsLog,
2625
2734
  });
2626
2735
  recordRunNotes({
2627
- flowName: name, runId, runDir, outcome: result.outcome, specHash: state.signatureHash, now,
2736
+ flowName: name, runId, runDir, outcome: result.outcome, now,
2628
2737
  });
2629
2738
 
2630
2739
  if (result.outcome === 'complete') return { ...result, auditRows };
@@ -2660,7 +2769,7 @@ export function auditSpend(runDir) {
2660
2769
  * @param {string} opts.runId
2661
2770
  * @param {unknown} opts.catalogue
2662
2771
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
2663
- * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
2772
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number, sha256?:string}>} opts.sendStep
2664
2773
  * @param {Record<string, any>} [opts.primitives]
2665
2774
  * @param {string[]} [opts.primitiveReds]
2666
2775
  * @param {() => string} [opts.clock]
@@ -2685,8 +2794,8 @@ export async function continueRun({
2685
2794
  if (preflightRead.ok) {
2686
2795
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2687
2796
  if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
2688
- const unusedTool = findUnusedMcpTool(preflightRead.declaration);
2689
- if (unusedTool) return refused(unusedMcpToolRed(unusedTool));
2797
+ const mcpRed = findMcpPlanRed(preflightRead.declaration);
2798
+ if (mcpRed) return refused(mcpRed);
2690
2799
  const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2691
2800
  if (unbuildable) return refused(unbuildableRed(unbuildable), unbuildable.why);
2692
2801
  }
@@ -2777,9 +2886,7 @@ export async function continueRun({
2777
2886
  appendAudit(runDir, fullRow);
2778
2887
  if (row.spendComplete === false) spendComplete.value = false;
2779
2888
  if (modelOutput !== undefined) {
2780
- attemptsLog.push({
2781
- step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
2782
- });
2889
+ attemptsLog.push(attemptEntry(row, modelOutput));
2783
2890
  }
2784
2891
  };
2785
2892
  const runStartedAt = typeof halt.startedAt === 'number' ? halt.startedAt : startedAt;
@@ -2795,6 +2902,7 @@ export async function continueRun({
2795
2902
  }
2796
2903
 
2797
2904
  const result = await foldFromStep({
2905
+ mcpServer: declaration.mcp?.server ?? null,
2798
2906
  i0: halt.stepIndex,
2799
2907
  resumeTries,
2800
2908
  steps,
@@ -2832,7 +2940,7 @@ export async function continueRun({
2832
2940
  attemptsLog,
2833
2941
  });
2834
2942
  recordRunNotes({
2835
- flowName: name, runId, runDir, outcome: result.outcome, specHash: halt.signatureHash, now,
2943
+ flowName: name, runId, runDir, outcome: result.outcome, now,
2836
2944
  });
2837
2945
  if (result.outcome === 'complete') return { ...result, auditRows };
2838
2946
  return result;
@@ -2936,6 +3044,23 @@ export async function stopParkedRun({
2936
3044
  }
2937
3045
  }
2938
3046
 
3047
+ /** hamr's ask 2026-11-03: the round-1 text of a try a later round saved. Held beside the audit row (rows stay small), read by `attemptEntry` only. */
3048
+ const FIRST_TEXT = new WeakMap();
3049
+
3050
+ /** Registers a try's round-1 text against its audit row (the row itself is unchanged). */
3051
+ function withFirstText(row, firstText) {
3052
+ if (firstText !== undefined) FIRST_TEXT.set(row, firstText);
3053
+ return row;
3054
+ }
3055
+
3056
+ /** The ONE builder of a try's log.json entry (what the model said, per try), for the three `recordAudit`s; `firstText` is there only when a later round saved. */
3057
+ function attemptEntry(row, modelOutput) {
3058
+ const firstText = FIRST_TEXT.get(row);
3059
+ return {
3060
+ step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput, ...(firstText !== undefined ? { firstText } : {}),
3061
+ };
3062
+ }
3063
+
2939
3064
  /** log.json's one writer, called from every exit path (complete + every
2940
3065
  * halt) — M2 scope item 9 / the M0 ruling: what the model wrote, every
2941
3066
  * attempt, red runs included, never just the final artifacts. */
package/src/send.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // in-memory content handed in — so a write that silently truncates to 0
12
12
  // bytes reds here, not upstream).
13
13
 
14
+ import { createHash } from 'node:crypto';
14
15
  import { lstatSync, readFileSync } from 'node:fs';
15
16
  import { join } from 'node:path';
16
17
  import { createShellTools } from 'bare-agent/tools';
@@ -23,15 +24,81 @@ const FOUND_WRITE_TOOL = SHELL_TOOLS.find((t) => t.name === 'shell_write');
23
24
  if (!FOUND_WRITE_TOOL) throw new Error('send: bare-agent/tools does not export a "shell_write" tool');
24
25
  const WRITE_TOOL = FOUND_WRITE_TOOL;
25
26
 
27
+ const SCALAR = ['string', 'number', 'boolean'];
28
+
29
+ /** one value as leaf lines `{parts, text}`: parts are the names on the way in; text is a string as it is, a number or boolean written out; a list of plain values joined by ", "; null as empty */
30
+ /** @param {string[]} parts @param {any} v @returns {{parts: string[], text: string}[]} */
31
+ function leaves(parts, v) {
32
+ if (v === null || v === undefined) return [{ parts, text: '' }];
33
+ if (SCALAR.includes(typeof v)) return [{ parts, text: `${v}` }];
34
+ if (Array.isArray(v) && v.every((x) => x === null || SCALAR.includes(typeof x))) return [{ parts, text: v.join(', ') }];
35
+ if (Array.isArray(v)) return v.flatMap((x, i) => leaves([...parts, `${i + 1}`], x));
36
+ return Object.entries(v).flatMap(([k, x]) => leaves([...parts, k], x));
37
+ }
38
+
39
+ /** @param {string} name split only at a lowercase-to-capital boundary, `_` and `-`, so `ID` stays one word */
40
+ const words = (name) => name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[_\-\s]+/).filter(Boolean);
41
+
42
+ /** M15 am2 (1): the names as plain words; a last name of `value` or `rows` is left out; the first letter capital, the later words lowercase */
43
+ /** @param {string[]} parts */
44
+ function friendlyName(parts) {
45
+ const p = parts.length > 1 && (parts[parts.length - 1] === 'value' || parts[parts.length - 1] === 'rows') ? parts.slice(0, -1) : parts;
46
+ const w = p.flatMap(words).map((x) => x.toLowerCase());
47
+ if (!w.length) return parts.join('.');
48
+ return w[0][0].toUpperCase() + w[0].slice(1) + (w.length > 1 ? ` ${w.slice(1).join(' ')}` : '');
49
+ }
50
+
51
+ /** the lines of one block (the flat part, or one result); two lines with the same words both keep today's `a.b` form */
52
+ /** @param {{parts: string[], text: string}[]} ls */
53
+ function blockLines(ls) {
54
+ const f = ls.map((l) => friendlyName(l.parts));
55
+ /** @type {Record<string, number>} */
56
+ const n = {};
57
+ for (const x of f) n[x] = (n[x] || 0) + 1;
58
+ return ls.map((l, i) => `${n[f[i]] > 1 ? l.parts.join('.') : f[i]}: ${l.text}`);
59
+ }
60
+
61
+ /** a list of results: every item an object holding a `values` object (flights' `results`, with a `quote` written as its last line) */
62
+ /** @param {any} v */
63
+ const isResultList = (v) => Array.isArray(v) && v.length > 0 && v.every((r) => r && typeof r === 'object' && !Array.isArray(r) && r.values && typeof r.values === 'object' && !Array.isArray(r.values));
64
+
65
+ /**
66
+ * M15 items 3 and am1, am2: the accepted answer as the plain-text file the send writes. `{text}` alone is the text exactly; any other flat object is one
67
+ * `Name words: value` line per field; a list of results is one `## Result k` block per result with one line per value, in the order the answer holds
68
+ * them, then `from the page: "<quote>"`. Never JSON braces, never check marks. What it throws away: a result's keys other than `quote` and `values`.
69
+ * @param {Record<string, any>} content @returns {string}
70
+ */
71
+ export function renderSentMd(content) {
72
+ const keys = Object.keys(content);
73
+ if (keys.length === 1 && keys[0] === 'text' && typeof content.text === 'string') return content.text;
74
+ /** @type {string[]} */
75
+ const parts = [];
76
+ /** @type {{parts: string[], text: string}[]} */
77
+ let flat = [];
78
+ const flush = () => { if (flat.length) parts.push(blockLines(flat).join('\n')); flat = []; };
79
+ for (const [k, v] of Object.entries(content)) {
80
+ if (isResultList(v)) {
81
+ flush();
82
+ v.forEach((r, i) => {
83
+ const lines = blockLines(Object.entries(r.values).flatMap(([n, x]) => leaves([n], x)));
84
+ if (typeof r.quote === 'string') lines.push(`from the page: "${r.quote}"`);
85
+ parts.push([`## Result ${i + 1}`, ...lines].join('\n'));
86
+ });
87
+ } else flat.push(...leaves([k], v));
88
+ }
89
+ flush();
90
+ return parts.join('\n\n');
91
+ }
92
+
26
93
  /**
27
94
  * @param {string} target - a signed arbiter target, e.g. `file:poc/m0/out`.
28
95
  * @param {string} filename
29
- * @param {unknown} content - JSON-serialised before writing.
96
+ * @param {unknown} content - the accepted artifact; hash-checked as its JSON, written as plain text (`renderSentMd`).
30
97
  * @param {string|null} [acceptedSha256] - the sha256 the human's accept recorded
31
98
  * (`answerAsk`, M4b piece 3). Required: none recorded (an answer written by an
32
99
  * older version, or no accept in this process) refuses by name.
33
100
  * @param {{root?: string, runDir?: string}} [ctx] the flow root and this run's folder, for the destination refusals
34
- * @returns {Promise<{ok:true, path:string, bytes:number} | {ok:false, red:string}>}
101
+ * @returns {Promise<{ok:true, path:string, bytes:number, sha256:string} | {ok:false, red:string}>}
35
102
  */
36
103
  export async function sendViaPrimitive(target, filename, content, acceptedSha256, ctx = {}) {
37
104
  const destination = checkSendDestination(target, ctx);
@@ -77,11 +144,11 @@ export async function sendViaPrimitive(target, filename, content, acceptedSha256
77
144
  let present = true;
78
145
  try { lstatSync(path); } catch (err) { if (err.code === 'ENOENT') present = false; }
79
146
  if (present) return { ok: false, red: `send: "${path}" already exists — never overwritten (nothing shipped)` };
80
- await WRITE_TOOL.execute({ path, content: serialised });
147
+ await WRITE_TOOL.execute({ path, content: renderSentMd(/** @type {Record<string, unknown>} */ (content)) });
81
148
 
82
149
  const bytes = readFileSync(path);
83
150
  if (bytes.byteLength === 0) {
84
151
  return { ok: false, red: `send: "${path}" wrote 0 bytes` };
85
152
  }
86
- return { ok: true, path, bytes: bytes.byteLength };
153
+ return { ok: true, path, bytes: bytes.byteLength, sha256: createHash('sha256').update(bytes).digest('hex') };
87
154
  }