fwdloop 0.26.2 → 0.28.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 (73) hide show
  1. package/bin/fwdloop +46 -7
  2. package/package.json +2 -2
  3. package/src/authoring.js +21 -1
  4. package/src/canrun.js +23 -0
  5. package/src/config.js +18 -0
  6. package/src/declaration.js +129 -3
  7. package/src/drafter.js +38 -10
  8. package/src/flow.js +2 -1
  9. package/src/launcher.js +4 -2
  10. package/src/learnstore.js +3 -2
  11. package/src/mcp-checks.js +50 -0
  12. package/src/mcp-pick.js +33 -0
  13. package/src/mcp-sources.js +84 -0
  14. package/src/mcp-use.js +54 -0
  15. package/src/natural.js +23 -0
  16. package/src/panel/author.js +17 -1
  17. package/src/panel/authorcard.js +35 -0
  18. package/src/panel/authorflows.js +15 -6
  19. package/src/panel/authorstart.js +10 -6
  20. package/src/panel/authortrigger.js +263 -82
  21. package/src/panel/data.js +127 -9
  22. package/src/panel/index.html +945 -94
  23. package/src/panel/jobgrid.js +127 -0
  24. package/src/panel/scheduler.js +48 -6
  25. package/src/panel/server.js +33 -8
  26. package/src/panel/settings.js +119 -4
  27. package/src/panel/tickets.js +118 -0
  28. package/src/primitives.js +34 -5
  29. package/src/runner.js +129 -15
  30. package/src/schedule.js +5 -0
  31. package/src/summary-words.js +27 -7
  32. package/src/ticket-draft.js +85 -0
  33. package/src/ticket-labels.js +75 -0
  34. package/src/ticket-mcp.js +89 -0
  35. package/src/ticket-next.js +33 -0
  36. package/src/ticket-shape.js +33 -0
  37. package/src/trigger-clock.js +4 -4
  38. package/src/trigger-files.js +4 -4
  39. package/src/trigger-line.js +2 -1
  40. package/src/trigger-tickets.js +238 -0
  41. package/types/authoring.d.ts +5 -1
  42. package/types/canrun.d.ts +7 -0
  43. package/types/config.d.ts +6 -0
  44. package/types/declaration.d.ts +8 -0
  45. package/types/drafter.d.ts +552 -21
  46. package/types/mcp-checks.d.ts +8 -0
  47. package/types/mcp-pick.d.ts +23 -0
  48. package/types/mcp-sources.d.ts +51 -0
  49. package/types/mcp-use.d.ts +12 -0
  50. package/types/natural.d.ts +2 -0
  51. package/types/panel/author.d.ts +44 -0
  52. package/types/panel/authorcard.d.ts +11 -0
  53. package/types/panel/authorflows.d.ts +11 -1
  54. package/types/panel/authorstart.d.ts +3 -1
  55. package/types/panel/authortrigger.d.ts +83 -7
  56. package/types/panel/data.d.ts +78 -5
  57. package/types/panel/jobgrid.d.ts +109 -0
  58. package/types/panel/scheduler.d.ts +7 -2
  59. package/types/panel/server.d.ts +13 -2
  60. package/types/panel/settings.d.ts +3 -2
  61. package/types/panel/tickets.d.ts +103 -0
  62. package/types/primitives.d.ts +15 -2
  63. package/types/runner.d.ts +133 -75
  64. package/types/summary-words.d.ts +24 -4
  65. package/types/ticket-draft.d.ts +104 -0
  66. package/types/ticket-labels.d.ts +42 -0
  67. package/types/ticket-mcp.d.ts +57 -0
  68. package/types/ticket-next.d.ts +23 -0
  69. package/types/ticket-shape.d.ts +30 -0
  70. package/types/trigger-clock.d.ts +4 -3
  71. package/types/trigger-files.d.ts +3 -1
  72. package/types/trigger-line.d.ts +7 -0
  73. package/types/trigger-tickets.d.ts +105 -0
package/src/primitives.js CHANGED
@@ -68,8 +68,11 @@ function shellTool(name) {
68
68
  * `instanceof` and records `{verb, path, rule}` on the attempt's audit row —
69
69
  * never parsed back out of the message string. */
70
70
  export class GateRefusal extends Error {
71
- constructor(verb, resolved, rule) {
72
- super(`${verb}: "${resolved}" is outside the sandbox — refused (bareguard rule: ${rule})`);
71
+ /** `tool: true` (M13 item 5): a refused MCP tool, `verb` is its name; it names no path, so it gets no filesystem wording */
72
+ constructor(verb, resolved, rule, { tool = false } = {}) {
73
+ super(tool
74
+ ? `tool "${verb}" is not allowed for this step — refused (bareguard rule: ${rule})`
75
+ : `${verb}: "${resolved}" is outside the sandbox — refused (bareguard rule: ${rule})`);
73
76
  this.name = 'GateRefusal';
74
77
  this.verb = verb;
75
78
  this.path = resolved;
@@ -318,6 +321,15 @@ export function wiredMenu(skills) {
318
321
  return cat.primitives.filter((e) => WIRED_VERBS.has(e.verb) && (!skills || skills.includes(e.skill)));
319
322
  }
320
323
 
324
+ /** M13 item 5: the one name an MCP tool wears everywhere (bare-agent's bridge, the step's gate, the model's tool list, the diary row) */
325
+ export const mcpToolName = (server, tool) => `${server}_${tool}`;
326
+
327
+ /** M13 item 5: the job's MCP, as `resolvePrimitives` wants it: the signed server and every tool any step grants; `undefined` when no step has `mcpTools` */
328
+ export function stepMcp(declaration) {
329
+ const tools = [...new Set((declaration?.steps ?? []).flatMap((s) => s.mcpTools ?? []))];
330
+ return declaration?.mcp?.server && tools.length > 0 ? { server: declaration.mcp.server, tools } : undefined;
331
+ }
332
+
321
333
  /**
322
334
  * Resolve the granted tools for one step's model call. Never throws —
323
335
  * a verb absent from the catalogue, or present but unimplemented here, is
@@ -326,11 +338,11 @@ export function wiredMenu(skills) {
326
338
  *
327
339
  * @param {import('./types.js').CatalogueEntry[]} catalogue - `loadCatalogue().primitives` (or an injected test catalogue).
328
340
  * @param {string[]} grantedVerbs - `step.primitives`.
329
- * @param {{ runDir: string, inputs?: Array<{id:string, frozen:string}> }} ctx
341
+ * @param {{ runDir: string, inputs?: Array<{id:string, frozen:string}>, mcp?: {server: string, tools: string[]} }} ctx - `mcp` (`stepMcp`): the signed `<server>_<tool>` names the gate also allows (M13 item 5)
330
342
  * @returns {{ tools: Record<string, any>, reds: string[] }}
331
343
  */
332
344
  export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
333
- const { runDir, inputs = [] } = ctx;
345
+ const { runDir, inputs = [], mcp } = ctx;
334
346
  const inputsByRole = Object.fromEntries(inputs.map((entry) => [entry.id, entry.frozen]));
335
347
  const outDir = path.join(runDir, 'out');
336
348
 
@@ -350,7 +362,11 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
350
362
  let gate;
351
363
  try {
352
364
  // M4d am29 item 3: the diaries are denied to the model by name (bareloop's `fs.deny` of its audit sidecar path)
353
- gate = new Gate({ fs: { readScope, writeScope: [outDir], deny: diaryPaths(runDir) } });
365
+ // M13 item 5: an allowlist is exclusive for EVERY action (F116 measured it denying fs too), so with signed MCP tools it lists the step's verbs as well as their names
366
+ gate = new Gate({
367
+ fs: { readScope, writeScope: [outDir], deny: diaryPaths(runDir) },
368
+ ...(mcp ? { tools: { allowlist: [...(grantedVerbs ?? []), ...mcp.tools.map((t) => mcpToolName(mcp.server, t))] } } : {}),
369
+ });
354
370
  } catch (err) {
355
371
  return { tools: {}, reds: [`primitives: bareguard refused the step's file scope — ${err.message}`] };
356
372
  }
@@ -419,6 +435,19 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
419
435
  }
420
436
  }
421
437
 
438
+ // M13 item 5: one entry per signed MCP tool. The runner binds it to the step's bridge tool; `gatedCall` asks the gate first (the same check, refusal and `gateSeen` as the fs verbs).
439
+ if (mcp) for (const tool of mcp.tools) {
440
+ const name = mcpToolName(mcp.server, tool);
441
+ tools[name] = {
442
+ name,
443
+ gatedCall: async (args, run) => {
444
+ const decision = await gate.check({ type: 'tool', tool: name, args });
445
+ if (decision.outcome !== 'allow') throw new GateRefusal(name, '', decision.rule, { tool: true });
446
+ return run(args);
447
+ },
448
+ };
449
+ }
450
+
422
451
  for (const verb of Object.keys(tools)) tools[verb] = { ...tools[verb], gateSeen };
423
452
  return { tools, reds };
424
453
  }
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,
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';
@@ -77,6 +77,10 @@ import {
77
77
  import { readJobThinking, readModelRecord, takeLearningsRecord } from './flowmodel.js';
78
78
  import { readRunInputs, writeRunStart } from './runfile.js';
79
79
  import { fetchPageText, isWebUrl } from './pagefetch.js';
80
+ import { readTicketMcp, configForServer, remoteRefusal, mcpStartOpts, startRefusal, firstLine } from './ticket-mcp.js';
81
+ import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
82
+ import { mcpToolName } from './primitives.js';
83
+ import { decideTicket, readTicketFields } from './ticket-labels.js';
80
84
  import {
81
85
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
82
86
  } from './liveness.js';
@@ -419,16 +423,36 @@ export async function freezePage(dir, id, url, { fetchPage = fetchPageText } = {
419
423
  * (never the original again after this) and return the manifest, which `runFlow` records as the `inputs` of `run.json` (M8b). An
420
424
  * unreadable source refuses by name. A source that is a web address
421
425
  * (M10 item 1) is fetched and frozen by `freezePage`, in the same manifest.
422
- * @param {string} runDir @param {Array<{id: string, path: string}>} sources
426
+ * @param {string} runDir @param {Array<{id: string, path: string, ticket?: {number: number, anyway?: true}}>} sources
423
427
  * M10b amendment 1: a CSV input named in `tableRoles` (the sheets a step's `close.sheet` reads) also gets its `tableSha` (bareguard's fingerprint of the table made
424
428
  * from the FROZEN copy) in its manifest entry - the ONE place it is written, once, with the run's inputs; every sheet check of the run uses this recorded value.
425
429
  * A sheet bareguard cannot read as a table refuses the run here, naming the input.
426
- * @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, tableRoles?: string[]}} [o] */
427
- export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = [] } = {}) {
430
+ * M12 piece 1b: a source with `ticket: {number}` is one ticket of the list at its `path`, read through the job's MCP tools (`mcp`, the declaration's `{server, tools}`) by
431
+ * `ticketRead` and frozen like a page; its manifest entry also carries `mcp`, the record of what the server exposed and each call made (kept in `run.json`, no new file).
432
+ * @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, tableRoles?: string[], mcp?: {server: string, tools: string[]}, ticketRead?: typeof readTicketMcp, ticketFilter?: {priority?: string[], labels?: string[]}}} [o] */
433
+ export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = [], mcp, ticketRead = readTicketMcp, ticketFilter } = {}) {
428
434
  const inputsDir = join(runDir, 'inputs');
429
435
  mkdirSync(inputsDir, { recursive: true });
430
436
  const manifest = [];
431
- for (const { id, path: sourcePath } of sources ?? []) {
437
+ /** M12 piece 3: the first ticket the signed labels (or its state) skip: its reason; the run ends `skipped` after its start record is written */
438
+ let skip = null;
439
+ for (const { id, path: sourcePath, ticket } of sources ?? []) {
440
+ if (ticket) {
441
+ if (!mcp) return { ok: false, red: `freeze: input "${id}": the job lists no MCP tools` };
442
+ const got = await ticketRead({ listUrl: sourcePath, number: ticket.number, mcp });
443
+ if (!got.ok) return { ok: false, red: `freeze: input "${id}": ${got.error}` };
444
+ const page = await freezePage(inputsDir, id, got.url, { fetchPage: async () => got });
445
+ if (!page.ok) return page;
446
+ const verdict = decideTicket({ text: got.text, filter: ticketFilter });
447
+ const fields = readTicketFields(got.text);
448
+ // hamr 2026-10-30: a ticket sent with "Run it anyway" is never skipped (labels or closed); the record keeps what the filter would have said
449
+ const anyway = ticket.anyway === true;
450
+ manifest.push({
451
+ ...page.entry, mcp: got.record, ticket: { number: ticket.number, title: fields.ok ? fields.title : null }, filter: anyway ? { outcome: 'anyway', was: verdict } : verdict,
452
+ });
453
+ if (!anyway && verdict.outcome === 'skip' && skip === null) skip = verdict.reason;
454
+ continue;
455
+ }
432
456
  if (isWebUrl(sourcePath)) {
433
457
  const page = await freezePage(inputsDir, id, sourcePath, { fetchPage });
434
458
  if (!page.ok) return page;
@@ -453,7 +477,21 @@ export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = []
453
477
  }
454
478
  manifest.push(entry);
455
479
  }
456
- return { ok: true, manifest };
480
+ return { ok: true, manifest, skip };
481
+ }
482
+
483
+ /**
484
+ * 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
485
+ * ticket mark, so the rerun reads the ticket through the job's MCP tools and the signed filter, not as a web page.
486
+ * @param {Array<{id: string, source: string, ticket?: {number: number}, filter?: {outcome?: string}}>} manifest
487
+ */
488
+ export function rerunSourcesOf(manifest) {
489
+ return (manifest ?? []).map((entry) => {
490
+ const n = entry.ticket?.number;
491
+ const tail = `/${n}`;
492
+ if (!Number.isInteger(n) || !entry.source.endsWith(tail)) return { id: entry.id, path: entry.source };
493
+ return { id: entry.id, path: entry.source.slice(0, -tail.length), ticket: { number: n, ...(entry.filter?.outcome === 'anyway' ? { anyway: /** @type {const} */ (true) } : {}) } };
494
+ });
457
495
  }
458
496
 
459
497
  /** realpath of a path that may not exist (falls back to the lexical resolve). */
@@ -837,9 +875,10 @@ function makeAuditRow({
837
875
  * @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
838
876
  * @param {number} [opts.triesDone] - tries a Stop already closed on this step (they count against its limit)
839
877
  * @param {string|null} [opts.runDir] - M4d am29 item 2: the run's folder, where each try saves its checks
878
+ * @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
840
879
  * @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}}>}
841
880
  */
842
- export async function runStepRalph({
881
+ async function runStepTries({
843
882
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
844
883
  // 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`.
845
884
  thinkingBox = false,
@@ -859,6 +898,7 @@ export async function runStepRalph({
859
898
  runDir = null,
860
899
  // 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
861
900
  prevStepId = null,
901
+ mcpGranted = {},
862
902
  }) {
863
903
  /** @type {string|null} */
864
904
  let gap = initialGap ?? null;
@@ -899,7 +939,7 @@ export async function runStepRalph({
899
939
  };
900
940
  }
901
941
 
902
- const grantedTools = Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]]));
942
+ const grantedTools = { ...Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]])), ...mcpGranted };
903
943
  // 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
904
944
  // 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
905
945
  // try's row does); any failure hands nothing and rides the row as `hintsError`.
@@ -1127,6 +1167,52 @@ export async function runStepRalph({
1127
1167
  return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — exhausted attempts` };
1128
1168
  }
1129
1169
 
1170
+ /** 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 */
1171
+ const MCP_START_MS = 30000;
1172
+ const MCP_CALL_MS = 120000;
1173
+
1174
+ /**
1175
+ * 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
1176
+ * 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
1177
+ * 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
1178
+ * (`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.
1179
+ * @param {Parameters<typeof runStepTries>[0] & {mcpServer?: string|null}} opts - `mcpServer`: the job's signed `mcp.server`
1180
+ * @returns {ReturnType<typeof runStepTries>}
1181
+ */
1182
+ export async function runStepRalph({ mcpServer = null, ...opts }) {
1183
+ const signed = opts.step?.mcpTools ?? [];
1184
+ if (signed.length === 0 || !mcpServer) return runStepTries(opts);
1185
+ const refuse = (/** @type {string} */ red) => ({ ok: /** @type {const} */ (false), outcome: 'preflight-red', red });
1186
+ const { file: config, remote } = configForServer(mcpServer);
1187
+ if (!discoverServers([config]).has(mcpServer)) return refuse(`${mcpServer} is not in ~/.mcp.json`);
1188
+ if (remote) return refuse(remoteRefusal(mcpServer));
1189
+ /** @type {any} */
1190
+ let bridge;
1191
+ try {
1192
+ bridge = await createMCPBridge({ configPaths: [config], ...mcpStartOpts(), timeout: MCP_START_MS, callTimeout: MCP_CALL_MS, confirmServer: () => true, allow: { [mcpServer]: signed } });
1193
+ } catch (/** @type {any} */ e) {
1194
+ return refuse(startRefusal(mcpServer, e));
1195
+ }
1196
+ try {
1197
+ const failed = bridge.errors.find((/** @type {any} */ e) => e.server === mcpServer);
1198
+ if (failed) return refuse(`${mcpServer} did not start: ${firstLine(failed.error)}`);
1199
+ const lacking = bridge.missing?.[0];
1200
+ if (lacking) return refuse(`${mcpServer} does not offer ${lacking.tool}`);
1201
+ const mcpGranted = {};
1202
+ for (const tool of signed) {
1203
+ const name = mcpToolName(mcpServer, tool);
1204
+ const real = bridge.tools.find((/** @type {any} */ t) => t.name === name);
1205
+ const gated = opts.primitivesMap?.[name];
1206
+ if (!real) return refuse(`${mcpServer} does not offer ${tool}`);
1207
+ 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)`);
1208
+ mcpGranted[name] = { name, description: real.description, parameters: real.parameters, gateSeen: gated.gateSeen, execute: (/** @type {any} */ args) => gated.gatedCall(args, real.execute) };
1209
+ }
1210
+ return await runStepTries({ ...opts, mcpGranted });
1211
+ } finally {
1212
+ try { await bridge.close(); } catch { /* already closed */ }
1213
+ }
1214
+ }
1215
+
1130
1216
  // ---------------------------------------------------------------------------
1131
1217
  // runFlow — the entry point.
1132
1218
  // ---------------------------------------------------------------------------
@@ -1233,6 +1319,14 @@ export async function runFlow({
1233
1319
  });
1234
1320
  }
1235
1321
 
1322
+ // 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
1323
+ const mcpRed = findMcpPlanRed(declaration);
1324
+ if (mcpRed) {
1325
+ return haltRun({
1326
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: mcpRed, spent: { value: 0 },
1327
+ });
1328
+ }
1329
+
1236
1330
  // M4e amendment 19 4: every softgreen check is built before the first model call; one that cannot be built is refused at $0, by step name
1237
1331
  const unbuildable = findUnbuildableCheckStep(declaration);
1238
1332
  if (unbuildable) {
@@ -1273,7 +1367,7 @@ export async function runFlow({
1273
1367
  }
1274
1368
  }
1275
1369
 
1276
- const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps) });
1370
+ const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps), mcp: declaration.mcp, ticketFilter: declaration.ticketFilter });
1277
1371
  if (!frozen.ok) {
1278
1372
  return haltRun({
1279
1373
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
@@ -1281,6 +1375,12 @@ export async function runFlow({
1281
1375
  }
1282
1376
  // 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
1283
1377
  writeRunStart(runDir, { model: runModel ?? null, thinking: thinkingBox, inputs: /** @type {any[]} */ (frozen.manifest) });
1378
+ // M12 piece 3 (item 9): a ticket the signed labels do not match, or a closed one, ends here: skipped, $0, nothing else runs
1379
+ if (frozen.skip) {
1380
+ return haltRun({
1381
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'skipped', red: '', skip: frozen.skip, spent: { value: 0 },
1382
+ });
1383
+ }
1284
1384
  // M4c: every guard above has passed — this process records itself (pid row) before its first step.
1285
1385
  recordPid(runDir, 'run', now());
1286
1386
 
@@ -1336,6 +1436,7 @@ export async function runFlow({
1336
1436
  const acceptedAskEmitsThisRun = new Map();
1337
1437
 
1338
1438
  const result = await foldFromStep({
1439
+ mcpServer: declaration.mcp?.server ?? null,
1339
1440
  i0: 0,
1340
1441
  steps,
1341
1442
  askLines,
@@ -1466,6 +1567,8 @@ async function runAskSlot({
1466
1567
  // state.json on every park/re-park so a later resume can restore it
1467
1568
  // instead of substituting its own process's start.
1468
1569
  runStartedAt,
1570
+ // 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
1571
+ mcpServer = /** @type {string|null} */ (null),
1469
1572
  }) {
1470
1573
  let redone = initialRedone;
1471
1574
  let currentPrior = priorArtifact;
@@ -1642,7 +1745,7 @@ async function runAskSlot({
1642
1745
  }
1643
1746
  // eslint-disable-next-line no-await-in-loop
1644
1747
  const redoResult = await runStepRalph({
1645
- 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,
1748
+ 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,
1646
1749
  readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1647
1750
  });
1648
1751
  if (!redoResult.ok) {
@@ -1700,6 +1803,8 @@ async function foldFromStep({
1700
1803
  resumeTries = { numbered: 0, done: 0 },
1701
1804
  // Amendment 13: the redo count a stop-at-ask carried in its halt record, restored for the ask step it re-enters (`i0`).
1702
1805
  resumeRedone = 0,
1806
+ // M13 item 5: the job's signed `mcp.server`, for a step that grants MCP tools (`runStepRalph` starts its bridge)
1807
+ mcpServer = /** @type {string|null} */ (null),
1703
1808
  }) {
1704
1809
  let runAcceptedThisRun = acceptedThisRun;
1705
1810
  let runUnjudged = unjudgedSinceLastAsk;
@@ -1825,6 +1930,7 @@ async function foldFromStep({
1825
1930
 
1826
1931
  // eslint-disable-next-line no-await-in-loop
1827
1932
  const askResult = await runAskSlot({
1933
+ mcpServer,
1828
1934
  step,
1829
1935
  stepIndex: i,
1830
1936
  askSlot,
@@ -1897,7 +2003,7 @@ async function foldFromStep({
1897
2003
  // redo's `initialGap` above.
1898
2004
  // eslint-disable-next-line no-await-in-loop
1899
2005
  const stepResult = await runStepRalph({
1900
- 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,
2006
+ 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,
1901
2007
  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,
1902
2008
  });
1903
2009
  if (!stepResult.ok) {
@@ -2116,6 +2222,8 @@ export async function resumeRun({
2116
2222
  red: unwiredRed(unwiredVerb),
2117
2223
  };
2118
2224
  }
2225
+ const mcpRed = findMcpPlanRed(preflightRead.declaration);
2226
+ if (mcpRed) return { outcome: 'refused', red: mcpRed };
2119
2227
  const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2120
2228
  if (unbuildable) return { outcome: 'refused', red: unbuildableRed(unbuildable), detail: unbuildable.why };
2121
2229
  }
@@ -2410,7 +2518,7 @@ export async function resumeRun({
2410
2518
  // `inputsManifest[].source` since `freezeInputs` first wrote it (M3
2411
2519
  // scope item 7's own note: "persist those in state.json at park if
2412
2520
  // they aren't already" — they already are, via this field).
2413
- const rerunSources = (state.inputsManifest ?? []).map((entry) => ({ id: entry.id, path: entry.source }));
2521
+ const rerunSources = rerunSourcesOf(state.inputsManifest);
2414
2522
 
2415
2523
  if (typeof onRerunStart === 'function') onRerunStart(newRunDir);
2416
2524
  const newRun = await runFlow({
@@ -2496,6 +2604,7 @@ export async function resumeRun({
2496
2604
  const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason, artifactSha256: answer.artifactSha256 });
2497
2605
 
2498
2606
  const askResult = await runAskSlot({
2607
+ mcpServer: declaration.mcp?.server ?? null,
2499
2608
  step,
2500
2609
  stepIndex: state.stepIndex,
2501
2610
  askSlot,
@@ -2550,6 +2659,7 @@ export async function resumeRun({
2550
2659
  acceptedAskEmitsThisRun.set(step.emits, askResult.acceptedSha256 ?? null);
2551
2660
 
2552
2661
  const result = await foldFromStep({
2662
+ mcpServer: declaration.mcp?.server ?? null,
2553
2663
  i0: state.stepIndex + 1,
2554
2664
  steps,
2555
2665
  askLines,
@@ -2647,6 +2757,8 @@ export async function continueRun({
2647
2757
  if (preflightRead.ok) {
2648
2758
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2649
2759
  if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
2760
+ const mcpRed = findMcpPlanRed(preflightRead.declaration);
2761
+ if (mcpRed) return refused(mcpRed);
2650
2762
  const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2651
2763
  if (unbuildable) return refused(unbuildableRed(unbuildable), unbuildable.why);
2652
2764
  }
@@ -2755,6 +2867,7 @@ export async function continueRun({
2755
2867
  }
2756
2868
 
2757
2869
  const result = await foldFromStep({
2870
+ mcpServer: declaration.mcp?.server ?? null,
2758
2871
  i0: halt.stepIndex,
2759
2872
  resumeTries,
2760
2873
  steps,
@@ -2960,6 +3073,7 @@ export function readAsk(runDir) {
2960
3073
  * @param {{ value: number }} opts.spent
2961
3074
  * @param {any[]} [opts.attempts]
2962
3075
  * @param {Record<string, any>} [opts.artifacts]
3076
+ * @param {string|null} [opts.skip] - M12 p3: the reason a ticket run ends `skipped` (history row `skipReason`, log.json `skipReason`)
2963
3077
  * @param {string|null} [opts.signatureHash] - the flow's `signature.json` `flow`
2964
3078
  * hash, when this halt happened AFTER `readFlow` succeeded (item 9: every
2965
3079
  * history row carries it, halts included). A halt before the signature was
@@ -2977,7 +3091,7 @@ export function readAsk(runDir) {
2977
3091
  */
2978
3092
  function haltRun({
2979
3093
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs = Date.now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
2980
- priorSpendComplete = true, resumeAt = null, stop = null, detail = null,
3094
+ priorSpendComplete = true, resumeAt = null, stop = null, detail = null, skip = null,
2981
3095
  }) {
2982
3096
  // F45 finding 3: `startedAt` here is always the RUN's start (every caller
2983
3097
  // now passes `runStartedAt` under this key — see call sites), so `wallMs`
@@ -2990,7 +3104,7 @@ function haltRun({
2990
3104
  if (existsSync(runDir)) {
2991
3105
  recordLateAnswerIfAny(runDir, now);
2992
3106
  writeLog(runDir, {
2993
- runId, outcome, red, ...(detail ? { detail } : {}), attempts, artifacts,
3107
+ runId, outcome, red, ...(detail ? { detail } : {}), ...(skip ? { skipReason: skip } : {}), attempts, artifacts,
2994
3108
  });
2995
3109
  // M4e amendment 4 item 4: a cap-halted or stopped run leaves the one record Resume continues from (its only writer).
2996
3110
  if (resumeAt && HALT_OUTCOMES.includes(outcome)) {
@@ -3010,7 +3124,7 @@ function haltRun({
3010
3124
  const stoppedWithoutHaltRecord = outcome === 'stopped' && resumeAt && !readHaltRecord(runDir).ok;
3011
3125
  if (!stoppedWithoutHaltRecord) {
3012
3126
  appendHistory(flowDir, {
3013
- runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash, ...(detail ? { detail } : {}), // amendment 23: bareguard's raw reason, never the sentence
3127
+ runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash, ...(detail ? { detail } : {}), ...(skip ? { skipReason: skip } : {}), // amendment 23: bareguard's raw reason, never the sentence
3014
3128
  });
3015
3129
  }
3016
3130
  }
package/src/schedule.js CHANGED
@@ -18,6 +18,7 @@ import { appendRow } from './jsonl-append.js';
18
18
  import { queueOf, readSeen, recordDropped } from './trigger-files.js';
19
19
  import { readRows, validateSchedule } from './trigger-clock.js';
20
20
  import { triggerHash } from './trigger-line.js';
21
+ import { WATCHABLE } from './ticket-shape.js';
21
22
 
22
23
  /** @typedef {import('./trigger-line.js').Trigger} Trigger */
23
24
  /**
@@ -42,11 +43,14 @@ export const ledgerOf = (flowDir) => join(flowDir, LEDGER_FILE);
42
43
  export const sigOf = (bound, signedAt) => createHash('sha256').update(`${bound}\n${signedAt}`).digest('hex');
43
44
 
44
45
  const isFile = (/** @type {any} */ t) => t?.kind === 'new-file' || t?.kind === 'file-updated';
46
+ const isTicket = (/** @type {any} */ t) => t?.kind === 'new-ticket';
45
47
  const str = (/** @type {unknown} */ v) => typeof v === 'string' && v !== '';
46
48
 
47
49
  /** Is this a typed trigger of the five shapes? (the same shapes `trigger-line.js` parses; the schedule file never carries a line) @param {any} t */
48
50
  function triggerOk(t) {
49
51
  if (!t || typeof t !== 'object') return false;
52
+ // M12 piece 2: a ticket trigger carries the list address, the job's server and the look's one tool (signed with the two clicks), and optionally the watched fields
53
+ if (t.kind === 'new-ticket') return str(t.role) && str(t.list) && str(t.server) && str(t.tool) && (t.watch === undefined || (Array.isArray(t.watch) && t.watch.every((/** @type {unknown} */ w) => WATCHABLE.includes(/** @type {string} */ (w)))));
50
54
  if (isFile(t)) return str(t.role) && isAbsolute(String(t.kind === 'new-file' ? t.folder : t.path));
51
55
  try { validateSchedule(t); return true; } catch { return false; }
52
56
  }
@@ -89,6 +93,7 @@ export function removeSchedule(flowDir) {
89
93
 
90
94
  /** Does a re-sign keep the same kind and the same folder/file (so the queue and the baseline stand)? @param {Trigger|null|undefined} cur @param {Trigger|null} next */
91
95
  export function sameTarget(cur, next) {
96
+ if (isTicket(cur) && isTicket(next)) return /** @type {any} */ (cur).role === /** @type {any} */ (next).role && /** @type {any} */ (cur).list === /** @type {any} */ (next).list; // M12: the same list keeps its queue and its starting point
92
97
  if (!cur || !next || !isFile(cur) || !isFile(next) || cur.kind !== next.kind) return false;
93
98
  return cur.kind === 'new-file' ? cur.folder === /** @type {any} */ (next).folder : /** @type {any} */ (cur).path === /** @type {any} */ (next).path;
94
99
  }
@@ -38,6 +38,7 @@ export function scheduledWords(t, home) {
38
38
  if (t.kind === 'weekdays') return `Weekdays at ${hhmm(t)}`;
39
39
  if (t.kind === 'weekly') return `${DAY_PLURAL[/** @type {keyof typeof DAY_PLURAL} */ (t.day)] ?? t.day} at ${hhmm(t)}`;
40
40
  if (t.kind === 'file-updated') return `When ${basename(t.path)} is updated`;
41
+ if (t.kind === 'new-ticket') return `When a new ticket arrives in ${t.role}`;
41
42
  const folder = tilde(/** @type {{folder: string}} */ (t).folder, home);
42
43
  return `When a new file arrives in ${folder.endsWith('/') ? folder : `${folder}/`}`;
43
44
  }
@@ -69,6 +70,12 @@ export function nextInWords(ms, now) {
69
70
  return hours < 48 ? `next in ${hours}h` : `next in ${Math.floor(hours / 24)}d`;
70
71
  }
71
72
 
73
+ /** M13 piece 5 (signed item 7): a schedule that was signed with the job and is off until the first green run. The Run card's grey line; one owner. */
74
+ export const SCHEDULE_WAITING_SAY = 'Schedule waiting for a green run';
75
+
76
+ /** M13 item 9b.3: the one line for a look that could not read, with its cause (never "0 new"). @param {{at: number, why: string}} p */
77
+ export const lookProblemWords = (p) => `could not read the tickets: ${String(p.why).trim().replace(/\.$/, '')}. It looks again in 15 minutes.`;
78
+
72
79
  /**
73
80
  * NEXT of a job with a trigger. One sentence, first match wins:
74
81
  * 1. a run of this job is waiting at its ask (the next run waits too);
@@ -76,7 +83,8 @@ export function nextInWords(ms, now) {
76
83
  * 3. a clock kind with a next slot; 4. a file kind that is armed; 5. not armed yet.
77
84
  * A last outcome of `refused` goes in front of 3-5, so a trigger that cannot start is never silent.
78
85
  * `red` is the typed flag for "the human must act": monthly-exhausted and the refused lead. The page paints it; it never guesses from the text.
79
- * @param {{trigger: Trigger, armed: boolean, nextSlotMs: number|null, lastOutcome: any, waitingLine: number|null, now: number}} f
86
+ * M13 piece 5: `waiting` (signed with the job, off until the first green run) says SCHEDULE_WAITING_SAY, before every other row but the ask.
87
+ * @param {{trigger: Trigger, armed: boolean, waiting?: boolean, lookProblem?: {at: number, why: string}|null, nextSlotMs: number|null, lastOutcome: any, waitingLine: number|null, now: number}} f
80
88
  * @returns {{text: string, red: boolean}}
81
89
  */
82
90
  export function scheduledNextFor(f) {
@@ -91,11 +99,14 @@ export function scheduledNextFor(f) {
91
99
  const left = last.atLeast === true ? `at most ${money(last.leftUsd)} left` : `${money(last.leftUsd)} left`;
92
100
  return say(`Paused: not enough money left this month (${left}, a run needs up to ${money(last.needUsd)}). Raise the monthly limit in Settings, or it starts again on the 1st.`, true);
93
101
  }
102
+ if (f.waiting === true) return say(SCHEDULE_WAITING_SAY);
103
+ if (f.lookProblem) return say(`The last look ${lookProblemWords(f.lookProblem)}`, true); // M13 item 9b.3
94
104
  const lead = last !== null && last.outcome === 'refused' && typeof last.why === 'string' && last.why !== '' ? `The last try did not start: ${last.why} ` : '';
95
105
  const red = lead !== '';
96
106
  if (!armed) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
97
107
  if (trigger.kind === 'file-updated') return say(`${lead}Watching for it. A run starts when its contents change.`, red);
98
108
  if (trigger.kind === 'new-file') return say(`${lead}Watching for it. A run starts for each new file.`, red);
109
+ if (trigger.kind === 'new-ticket') return say(`${lead}Watching for it. A run starts for each new ticket.`, red);
99
110
  if (nextSlotMs === null) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
100
111
  return say(`${lead}Next run ${slotWords(nextSlotMs)}.`, red);
101
112
  }
@@ -121,12 +132,12 @@ const splitNext = (rows) => ({ next: rows.map(([l, t]) => `${l} ${t}`).join('\n'
121
132
  /**
122
133
  * ENDED / NEXT of a finished run. Every outcome the history row can hold has a fixed sentence; an unknown one gets an honest fixed fallback
123
134
  * that names the code and guesses nothing. `null` when there is no ending (still running, waiting, or no history row and not died).
124
- * @param {{outcome: string|null, died?: boolean, line: number|null, destination: string|null, canResume: boolean, home?: string}} f
135
+ * @param {{outcome: string|null, died?: boolean, line: number|null, destination: string|null, canResume: boolean, home?: string, skipReason?: string}} f
125
136
  * @returns {{reason: string, next: string, rows?: Array<[string, string]>}|null}
126
137
  */
127
138
  export function endedWords(f) {
128
139
  const {
129
- outcome, died = false, line, destination, canResume, home,
140
+ outcome, died = false, line, destination, canResume, home, skipReason,
130
141
  } = f;
131
142
  const resumeOrAgain = canResume ? 'Resume from the Chat card.' : RERUN_NEXT;
132
143
  if (died) return { reason: 'It stopped with no ending recorded.', next: 'See the Audit / logs tab for the last thing it did.' };
@@ -134,6 +145,8 @@ export function endedWords(f) {
134
145
  switch (outcome) {
135
146
  case 'complete':
136
147
  return { reason: 'Goal met.', next: destination ? `The result is in ${tilde(destination, home)}.` : 'The result is in the step cards below.' };
148
+ case 'skipped':
149
+ return { reason: `Skipped: ${typeof skipReason === 'string' && skipReason !== '' ? skipReason : 'the ticket did not match'}. Nothing was spent.`, next: 'Nothing to do. Run it anyway from the ticket list in the Result tab.' };
137
150
  case 'stopped':
138
151
  return { reason: 'Stopped by you.', next: resumeOrAgain };
139
152
  case 'cap-halt':
@@ -212,7 +225,7 @@ export function scheduleFieldWords(f) {
212
225
  /** A run's `trigger.json` record -> the typed pieces of "how it began", or `null` for a hand run. @param {any} rec */
213
226
  function startedKind(rec) {
214
227
  if (!rec || typeof rec !== 'object') return null;
215
- return rec.kind === 'file' || rec.kind === 'clock' ? rec.kind : null;
228
+ return rec.kind === 'file' || rec.kind === 'clock' || rec.kind === 'ticket' ? rec.kind : null;
216
229
  }
217
230
 
218
231
  /**
@@ -231,6 +244,8 @@ export function startedWords(rec, startMs, home) {
231
244
  const name = typeof rec.file === 'string' ? basename(rec.file) : '';
232
245
  const updated = rec.triggerKind === 'file-updated';
233
246
  head = `${updated ? 'By a file update' : 'By a new file'}${name ? `: ${name}` : ''}`;
247
+ } else if (kind === 'ticket') {
248
+ head = `By a new ticket${Number.isInteger(rec.ticket) ? `: #${rec.ticket}` : ''}${typeof rec.why === 'string' && rec.why !== '' ? ` (${rec.why})` : ''}`;
234
249
  }
235
250
  return stamp ? `${head} · ${stamp}` : head;
236
251
  }
@@ -252,16 +267,19 @@ function monthUsedUpWords(row) {
252
267
  * - month used up: `month used up: $0.01 left, needs $0.50 · next: raise the limit in Settings, or it starts on the 1st`, red only while `nowMs` is still that month;
253
268
  * - refused: `refused: <why> · next: fix it in Cancel / modify schedule`, red until a later good start.
254
269
  * `next` otherwise: `next <day stamp>`, `next: waiting for a new file` (file schedule) or `next: not armed yet`.
255
- * @param {{trigger: Trigger|null, home?: string, last: {at: string, runId: string, outcome: string, catchUp: boolean}|null, nextSlotMs: number|null, armed: boolean, problem: any, nowMs?: number}} f
270
+ * M13 piece 5: a schedule signed with the job and still off (`waiting`) has line 2 `Schedule waiting for a green run`, `grey: true` (a red run is normal shaping, never red).
271
+ * @param {{trigger: Trigger|null, home?: string, last: {at: string, runId: string, outcome: string, catchUp: boolean}|null, nextSlotMs: number|null, armed: boolean, waiting?: boolean, lookProblem?: {at: number, why: string}|null, problem: any, nowMs?: number}} f
256
272
  * `problem`: the newest fire when it started nothing (busy, monthly-exhausted, refused), else null.
257
- * @returns {{line1: string, line2: string|null, red: boolean}}
273
+ * @returns {{line1: string, line2: string|null, red: boolean, grey?: boolean}}
258
274
  */
259
275
  export function scheduleBlockWords(f) {
260
276
  const head = scheduleHead(f.trigger, f.home);
261
277
  const tr = f.trigger;
262
278
  if (head === null || tr === null) return { line1: 'By hand', line2: null, red: false };
279
+ if (f.waiting === true) return { line1: head, line2: SCHEDULE_WAITING_SAY, red: false, grey: true };
280
+ if (f.lookProblem) return { line1: head, line2: `last look ${shortStamp(f.lookProblem.at)} · ${lookProblemWords(f.lookProblem)}`, red: true }; // M13 item 9b.3
263
281
  const file = tr.kind === 'new-file' || tr.kind === 'file-updated';
264
- const next = file ? 'next: waiting for a new file' : (f.nextSlotMs !== null && f.armed ? `next ${dayStamp(f.nextSlotMs)}` : 'next: not armed yet');
282
+ const next = tr.kind === 'new-ticket' ? 'next: waiting for a new ticket' : file ? 'next: waiting for a new file' : (f.nextSlotMs !== null && f.armed ? `next ${dayStamp(f.nextSlotMs)}` : 'next: not armed yet');
265
283
  const p = f.problem;
266
284
  if (p) {
267
285
  const stamp = `last ${shortStamp(p.at)}`;
@@ -323,6 +341,8 @@ export function scheduleAuditWords(f) {
323
341
  else if (kind === 'file') {
324
342
  const name = typeof f.rec.file === 'string' ? basename(f.rec.file) : '';
325
343
  what = `started by the schedule \u00b7 ${f.rec.triggerKind === 'file-updated' ? 'file update' : 'new file'}${name ? ` ${name}` : ''}`;
344
+ } else if (kind === 'ticket') {
345
+ what = `started by the schedule \u00b7 new ticket${Number.isInteger(f.rec.ticket) ? ` #${f.rec.ticket}` : ''}`;
326
346
  }
327
347
  if (f.from !== null && f.from === f.runId) what += kind === null ? ' The schedule was set from this run.' : '. The schedule was set from this run.';
328
348
  /** @type {Array<{label: string, stamp: string, text: string}>} */