fwdloop 0.27.0 → 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 (67) hide show
  1. package/bin/fwdloop +27 -8
  2. package/package.json +2 -2
  3. package/src/authoring.js +11 -1
  4. package/src/canrun.js +19 -16
  5. package/src/config.js +18 -0
  6. package/src/declaration.js +32 -2
  7. package/src/drafter.js +29 -14
  8. package/src/flow.js +2 -1
  9. package/src/launcher.js +4 -2
  10. package/src/learnstore.js +2 -1
  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 +19 -19
  17. package/src/panel/authorcard.js +35 -0
  18. package/src/panel/authorflows.js +18 -14
  19. package/src/panel/authortrigger.js +241 -84
  20. package/src/panel/data.js +89 -6
  21. package/src/panel/index.html +552 -157
  22. package/src/panel/jobgrid.js +127 -0
  23. package/src/panel/scheduler.js +8 -2
  24. package/src/panel/server.js +15 -6
  25. package/src/panel/settings.js +119 -4
  26. package/src/panel/tickets.js +12 -7
  27. package/src/primitives.js +34 -5
  28. package/src/runner.js +88 -15
  29. package/src/summary-words.js +15 -3
  30. package/src/ticket-draft.js +40 -42
  31. package/src/ticket-labels.js +10 -0
  32. package/src/ticket-mcp.js +33 -10
  33. package/src/ticket-next.js +33 -0
  34. package/src/ticket-shape.js +9 -0
  35. package/src/trigger-clock.js +4 -4
  36. package/src/trigger-files.js +3 -3
  37. package/src/trigger-tickets.js +41 -12
  38. package/types/authoring.d.ts +5 -1
  39. package/types/canrun.d.ts +5 -12
  40. package/types/config.d.ts +6 -0
  41. package/types/declaration.d.ts +8 -0
  42. package/types/drafter.d.ts +447 -38
  43. package/types/mcp-checks.d.ts +8 -0
  44. package/types/mcp-pick.d.ts +23 -0
  45. package/types/mcp-sources.d.ts +51 -0
  46. package/types/mcp-use.d.ts +12 -0
  47. package/types/natural.d.ts +2 -0
  48. package/types/panel/author.d.ts +36 -0
  49. package/types/panel/authorcard.d.ts +11 -0
  50. package/types/panel/authorflows.d.ts +9 -1
  51. package/types/panel/authortrigger.d.ts +73 -7
  52. package/types/panel/data.d.ts +56 -2
  53. package/types/panel/jobgrid.d.ts +109 -0
  54. package/types/panel/server.d.ts +5 -1
  55. package/types/panel/settings.d.ts +3 -2
  56. package/types/panel/tickets.d.ts +26 -4
  57. package/types/primitives.d.ts +15 -2
  58. package/types/runner.d.ts +112 -72
  59. package/types/summary-words.d.ts +22 -3
  60. package/types/ticket-draft.d.ts +40 -32
  61. package/types/ticket-labels.d.ts +6 -0
  62. package/types/ticket-mcp.d.ts +18 -1
  63. package/types/ticket-next.d.ts +23 -0
  64. package/types/ticket-shape.d.ts +5 -0
  65. package/types/trigger-clock.d.ts +4 -3
  66. package/types/trigger-files.d.ts +1 -1
  67. package/types/trigger-tickets.d.ts +18 -4
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';
@@ -77,7 +77,9 @@ 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 } from './ticket-mcp.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';
81
83
  import { decideTicket, readTicketFields } from './ticket-labels.js';
82
84
  import {
83
85
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
@@ -478,6 +480,20 @@ export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = []
478
480
  return { ok: true, manifest, skip };
479
481
  }
480
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
+ });
495
+ }
496
+
481
497
  /** realpath of a path that may not exist (falls back to the lexical resolve). */
482
498
  function realOrResolved(p) {
483
499
  try { return realpathSync(p); } catch { return resolve(p); }
@@ -859,9 +875,10 @@ function makeAuditRow({
859
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
860
876
  * @param {number} [opts.triesDone] - tries a Stop already closed on this step (they count against its limit)
861
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
862
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}}>}
863
880
  */
864
- export async function runStepRalph({
881
+ async function runStepTries({
865
882
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
866
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`.
867
884
  thinkingBox = false,
@@ -881,6 +898,7 @@ export async function runStepRalph({
881
898
  runDir = null,
882
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
883
900
  prevStepId = null,
901
+ mcpGranted = {},
884
902
  }) {
885
903
  /** @type {string|null} */
886
904
  let gap = initialGap ?? null;
@@ -921,7 +939,7 @@ export async function runStepRalph({
921
939
  };
922
940
  }
923
941
 
924
- const grantedTools = Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]]));
942
+ const grantedTools = { ...Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]])), ...mcpGranted };
925
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
926
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
927
945
  // try's row does); any failure hands nothing and rides the row as `hintsError`.
@@ -1149,6 +1167,52 @@ export async function runStepRalph({
1149
1167
  return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — exhausted attempts` };
1150
1168
  }
1151
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
+
1152
1216
  // ---------------------------------------------------------------------------
1153
1217
  // runFlow — the entry point.
1154
1218
  // ---------------------------------------------------------------------------
@@ -1255,11 +1319,11 @@ export async function runFlow({
1255
1319
  });
1256
1320
  }
1257
1321
 
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) {
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) {
1261
1325
  return haltRun({
1262
- flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: unusedMcpToolRed(unusedTool), spent: { value: 0 },
1326
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: mcpRed, spent: { value: 0 },
1263
1327
  });
1264
1328
  }
1265
1329
 
@@ -1372,6 +1436,7 @@ export async function runFlow({
1372
1436
  const acceptedAskEmitsThisRun = new Map();
1373
1437
 
1374
1438
  const result = await foldFromStep({
1439
+ mcpServer: declaration.mcp?.server ?? null,
1375
1440
  i0: 0,
1376
1441
  steps,
1377
1442
  askLines,
@@ -1502,6 +1567,8 @@ async function runAskSlot({
1502
1567
  // state.json on every park/re-park so a later resume can restore it
1503
1568
  // instead of substituting its own process's start.
1504
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),
1505
1572
  }) {
1506
1573
  let redone = initialRedone;
1507
1574
  let currentPrior = priorArtifact;
@@ -1678,7 +1745,7 @@ async function runAskSlot({
1678
1745
  }
1679
1746
  // eslint-disable-next-line no-await-in-loop
1680
1747
  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,
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,
1682
1749
  readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1683
1750
  });
1684
1751
  if (!redoResult.ok) {
@@ -1736,6 +1803,8 @@ async function foldFromStep({
1736
1803
  resumeTries = { numbered: 0, done: 0 },
1737
1804
  // Amendment 13: the redo count a stop-at-ask carried in its halt record, restored for the ask step it re-enters (`i0`).
1738
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),
1739
1808
  }) {
1740
1809
  let runAcceptedThisRun = acceptedThisRun;
1741
1810
  let runUnjudged = unjudgedSinceLastAsk;
@@ -1861,6 +1930,7 @@ async function foldFromStep({
1861
1930
 
1862
1931
  // eslint-disable-next-line no-await-in-loop
1863
1932
  const askResult = await runAskSlot({
1933
+ mcpServer,
1864
1934
  step,
1865
1935
  stepIndex: i,
1866
1936
  askSlot,
@@ -1933,7 +2003,7 @@ async function foldFromStep({
1933
2003
  // redo's `initialGap` above.
1934
2004
  // eslint-disable-next-line no-await-in-loop
1935
2005
  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,
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,
1937
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,
1938
2008
  });
1939
2009
  if (!stepResult.ok) {
@@ -2152,8 +2222,8 @@ export async function resumeRun({
2152
2222
  red: unwiredRed(unwiredVerb),
2153
2223
  };
2154
2224
  }
2155
- const unusedTool = findUnusedMcpTool(preflightRead.declaration);
2156
- if (unusedTool) return { outcome: 'refused', red: unusedMcpToolRed(unusedTool) };
2225
+ const mcpRed = findMcpPlanRed(preflightRead.declaration);
2226
+ if (mcpRed) return { outcome: 'refused', red: mcpRed };
2157
2227
  const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2158
2228
  if (unbuildable) return { outcome: 'refused', red: unbuildableRed(unbuildable), detail: unbuildable.why };
2159
2229
  }
@@ -2448,7 +2518,7 @@ export async function resumeRun({
2448
2518
  // `inputsManifest[].source` since `freezeInputs` first wrote it (M3
2449
2519
  // scope item 7's own note: "persist those in state.json at park if
2450
2520
  // they aren't already" — they already are, via this field).
2451
- const rerunSources = (state.inputsManifest ?? []).map((entry) => ({ id: entry.id, path: entry.source }));
2521
+ const rerunSources = rerunSourcesOf(state.inputsManifest);
2452
2522
 
2453
2523
  if (typeof onRerunStart === 'function') onRerunStart(newRunDir);
2454
2524
  const newRun = await runFlow({
@@ -2534,6 +2604,7 @@ export async function resumeRun({
2534
2604
  const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason, artifactSha256: answer.artifactSha256 });
2535
2605
 
2536
2606
  const askResult = await runAskSlot({
2607
+ mcpServer: declaration.mcp?.server ?? null,
2537
2608
  step,
2538
2609
  stepIndex: state.stepIndex,
2539
2610
  askSlot,
@@ -2588,6 +2659,7 @@ export async function resumeRun({
2588
2659
  acceptedAskEmitsThisRun.set(step.emits, askResult.acceptedSha256 ?? null);
2589
2660
 
2590
2661
  const result = await foldFromStep({
2662
+ mcpServer: declaration.mcp?.server ?? null,
2591
2663
  i0: state.stepIndex + 1,
2592
2664
  steps,
2593
2665
  askLines,
@@ -2685,8 +2757,8 @@ export async function continueRun({
2685
2757
  if (preflightRead.ok) {
2686
2758
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2687
2759
  if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
2688
- const unusedTool = findUnusedMcpTool(preflightRead.declaration);
2689
- if (unusedTool) return refused(unusedMcpToolRed(unusedTool));
2760
+ const mcpRed = findMcpPlanRed(preflightRead.declaration);
2761
+ if (mcpRed) return refused(mcpRed);
2690
2762
  const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2691
2763
  if (unbuildable) return refused(unbuildableRed(unbuildable), unbuildable.why);
2692
2764
  }
@@ -2795,6 +2867,7 @@ export async function continueRun({
2795
2867
  }
2796
2868
 
2797
2869
  const result = await foldFromStep({
2870
+ mcpServer: declaration.mcp?.server ?? null,
2798
2871
  i0: halt.stepIndex,
2799
2872
  resumeTries,
2800
2873
  steps,
@@ -70,6 +70,12 @@ export function nextInWords(ms, now) {
70
70
  return hours < 48 ? `next in ${hours}h` : `next in ${Math.floor(hours / 24)}d`;
71
71
  }
72
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
+
73
79
  /**
74
80
  * NEXT of a job with a trigger. One sentence, first match wins:
75
81
  * 1. a run of this job is waiting at its ask (the next run waits too);
@@ -77,7 +83,8 @@ export function nextInWords(ms, now) {
77
83
  * 3. a clock kind with a next slot; 4. a file kind that is armed; 5. not armed yet.
78
84
  * A last outcome of `refused` goes in front of 3-5, so a trigger that cannot start is never silent.
79
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.
80
- * @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
81
88
  * @returns {{text: string, red: boolean}}
82
89
  */
83
90
  export function scheduledNextFor(f) {
@@ -92,6 +99,8 @@ export function scheduledNextFor(f) {
92
99
  const left = last.atLeast === true ? `at most ${money(last.leftUsd)} left` : `${money(last.leftUsd)} left`;
93
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);
94
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
95
104
  const lead = last !== null && last.outcome === 'refused' && typeof last.why === 'string' && last.why !== '' ? `The last try did not start: ${last.why} ` : '';
96
105
  const red = lead !== '';
97
106
  if (!armed) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
@@ -258,14 +267,17 @@ function monthUsedUpWords(row) {
258
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;
259
268
  * - refused: `refused: <why> · next: fix it in Cancel / modify schedule`, red until a later good start.
260
269
  * `next` otherwise: `next <day stamp>`, `next: waiting for a new file` (file schedule) or `next: not armed yet`.
261
- * @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
262
272
  * `problem`: the newest fire when it started nothing (busy, monthly-exhausted, refused), else null.
263
- * @returns {{line1: string, line2: string|null, red: boolean}}
273
+ * @returns {{line1: string, line2: string|null, red: boolean, grey?: boolean}}
264
274
  */
265
275
  export function scheduleBlockWords(f) {
266
276
  const head = scheduleHead(f.trigger, f.home);
267
277
  const tr = f.trigger;
268
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
269
281
  const file = tr.kind === 'new-file' || tr.kind === 'file-updated';
270
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');
271
283
  const p = f.problem;
@@ -3,7 +3,7 @@
3
3
  // per run through the job's MCP tools). The drafter may SUGGEST the job's `mcp`/`mcpTools` (issue_read) and a `ticketFilter` (priority / label names); a human
4
4
  // signs it and code decides at run. The first facts line is F90c's, the line that made the drafter read a ticket role at all (FINDINGS F90c, F92).
5
5
  import { discoverServers } from 'bare-agent/mcp';
6
- import { USER_MCP_CONFIG } from './ticket-mcp.js';
6
+ import { startableMcpServers } from './mcp-sources.js';
7
7
  import { LIST_URL } from './ticket-shape.js';
8
8
 
9
9
  /** the one tool the first slice reads a ticket with */
@@ -15,48 +15,47 @@ export const isTicketListUrl = (url) => LIST_URL.test(String(url).trim());
15
15
  /** the signed page sources that are ticket roles @param {Array<{kind?: string, role: string, path: string}>} sources */
16
16
  export const ticketSourcesOf = (sources) => (sources ?? []).filter((s) => s.kind === 'page' && isTicketListUrl(s.path));
17
17
 
18
- /**
19
- * M12 piece 3: the ONE reader of a by-hand ticket number (a Run or a Sign & run body) and the ONE writer of its refusals. A whole number from 1, or null.
20
- * @param {unknown} v @returns {number|null}
21
- */
22
- export const ticketNumberOf = (v) => (typeof v === 'string' && /^[1-9][0-9]{0,8}$/.test(v.trim()) ? Number(v.trim()) : (Number.isInteger(v) && /** @type {number} */ (v) >= 1 ? /** @type {number} */ (v) : null));
23
-
24
- /** the refusals of a by-hand start's ticket box: a ticket job needs a number; any other job takes none. @param {string|null} ticketRole @param {any} body @returns {{field: string, say: string}[]} */
25
- export function ticketRefusals(ticketRole, body) {
26
- if (ticketRole !== null && ticketNumberOf(body?.ticket) === null) return [{ field: 'ticket', say: `This job reads one ticket of "${ticketRole}" per run. Give its ticket number (a whole number from 1). Nothing started.` }];
27
- if (ticketRole === null && Object.hasOwn(body ?? {}, 'ticket') && body.ticket !== undefined) return [{ field: 'ticket', say: 'This job has no ticket list, so there is no ticket number to give. Nothing started.' }];
28
- return [];
29
- }
30
-
31
- /** the server names in the user's own `~/.mcp.json` (what the drafter may name); none when the file is missing or unreadable @param {string} [configPath] @returns {string[]} */
32
- export function userMcpServers(configPath = USER_MCP_CONFIG()) {
33
- try { return [...discoverServers([configPath]).keys()]; } catch { return []; }
18
+ /** the startable server names across the MCP sources (src/mcp-sources.js), or in one explicit file (what the drafter may name); none when the file is missing or unreadable @param {string} [configPath] @returns {string[]} */
19
+ export function userMcpServers(configPath) {
20
+ try { return configPath ? [...discoverServers([configPath]).keys()] : startableMcpServers(); } catch { return []; }
34
21
  }
35
22
 
36
23
  /**
37
- * The lines under "Inputs" for one ticket role. The first is F90c's, word for word; the rest tell the drafter the two optional fields it may suggest.
38
- * @param {string} role @param {string[]} servers @returns {string[]}
24
+ * The lines under "Inputs" for one ticket role (M13 piece 4: flow type Tickets). The first is F90c's, word for word. The ticket is already frozen under its role and the job's own
25
+ * tools (`issue_read` to read it, `list_issues` to look for new ones) belong to the job, so no step needs them; a step lists a tool only if it calls it live.
26
+ * @param {string} role @returns {string[]}
39
27
  */
40
- export function ticketFactsLines(role, servers) {
28
+ export function ticketFactsLines(role) {
41
29
  return [
42
30
  `- ${role}: one ticket's text (a signed input, already frozen at run start; read it by listing "${role}" in a step's reads, do not fetch it)`,
43
- ` The ticket is read through the job's MCP tool "${TICKET_TOOL}" (read-only). Declare the top-level "mcp": {"server": one of ${servers.join(', ')}, "tools": ["${TICKET_TOOL}"]} and put "${TICKET_TOOL}" in "mcpTools" of the step that reads "${role}"; no other step gets it.`,
44
- ' You may SUGGEST a top-level "ticketFilter": {"priority": [P0 to P3 values], "labels": [label names]} ONLY for a guardrail that names a priority or a label (for example "priority P2 only", "only issues labelled bug"); leave it out for any other guardrail, which stays hitl. A human signs it and code decides at run; never invent a label.',
31
+ ` A step that reads "${role}" still lists "read" in its primitives: the ticket is frozen, but reading it is a grant.`,
32
+ ` Flow type: Tickets. The ticket is already frozen under "${role}" by the job's own tools ("${TICKET_TOOL}" reads it, "${LOOK_TOOL}" looks for new ones); no step needs them. A step lists a tool in "mcpTools" ONLY if that step calls the tool live; leave "mcpTools" out of every other step. The job's server and tool list are set by the program, not by you.`,
33
+ ' When a guardrail names a priority or a label (for example "priority P1 only", "only tickets with priority P1 count", "only issues labelled bug"), you MUST add a top-level "ticketFilter": {"priority": [P0 to P3 values], "labels": [label names]} for it; leave it out only when no guardrail names a priority or a label, and such a guardrail stays hitl. A human signs it and code decides at run; never invent a label.',
45
34
  ' You may SUGGEST a top-level "ticketWatch": ["state", "labels"] (one or both) ONLY for a guardrail that says to run a ticket again when its state or its labels change. Any other thing to watch cannot be put there: leave it out and it stays hitl.',
46
35
  ];
47
36
  }
48
37
 
49
- /** the schema parts a job with a ticket role adds: top-level `mcp` and `ticketFilter`, per-step `mcpTools` @param {string[]} servers */
50
- export function ticketSchemaParts(servers) {
38
+ /** the lines for a generic MCP job: the server, its tool names (so the drafter can grant them to steps), and the rule that a step lists a tool only if it calls it live @param {string} server @param {string[]} tools @returns {string[]} */
39
+ export function mcpFactsLines(server, tools) {
40
+ return [
41
+ `- Flow type: MCP (generic). The job's MCP server is "${server}" and its tools are: ${tools.join(', ')}. The job's server and tool list are set by the program, not by you.`,
42
+ ' A step lists a tool in "mcpTools" ONLY if that step calls the tool live, using the exact tool name above; at least one step must list at least one tool. Leave "mcpTools" out of every other step.',
43
+ ];
44
+ }
45
+
46
+ /** the one tool a Tickets job looks for new tickets with (src/panel/authortrigger.js) */
47
+ export const LOOK_TOOL = 'list_issues';
48
+
49
+ /**
50
+ * The schema parts a job with an MCP adds (M13 piece 4): per-step `mcpTools` (an enum of the job's tool names) for MCP (generic) and Tickets, and for Tickets the top-level
51
+ * `ticketFilter` and `ticketWatch`. The job's own `mcp` block and `flowType` are NOT offered: code sets them.
52
+ * @param {{flowType: 'mcp'|'tickets', tools: string[]}} o
53
+ */
54
+ export function ticketSchemaParts({ flowType, tools }) {
55
+ const step = { mcpTools: { type: 'array', items: { type: 'string', enum: tools }, description: 'the MCP tools this step calls LIVE (exact names); omit on every step that calls none' } };
56
+ if (flowType !== 'tickets') return { top: {}, step };
51
57
  return {
52
58
  top: {
53
- mcp: {
54
- type: 'object',
55
- properties: { server: { type: 'string', enum: servers }, tools: { type: 'array', items: { type: 'string', enum: [TICKET_TOOL] } } },
56
- required: ['server', 'tools'],
57
- additionalProperties: false,
58
- description: `the MCP server (from the person's ~/.mcp.json) and the tools the job uses: ["${TICKET_TOOL}"]`,
59
- },
60
59
  ticketFilter: {
61
60
  type: 'object',
62
61
  properties: {
@@ -68,20 +67,19 @@ export function ticketSchemaParts(servers) {
68
67
  },
69
68
  ticketWatch: { type: 'array', items: { type: 'string', enum: ['state', 'labels'] }, description: 'optional: suggest only for a guardrail that says to run a ticket again when its state or its labels change' },
70
69
  },
71
- step: { mcpTools: { type: 'array', items: { type: 'string', enum: [TICKET_TOOL] }, description: `["${TICKET_TOOL}"] on the step that reads the ticket; omit on every other step` } },
70
+ step,
72
71
  };
73
72
  }
74
73
 
75
74
  /**
76
- * Reds a draft with a ticket role must not pass with: no `mcp`, a server the person's config does not have, or no step that reads the ticket and holds the tool.
77
- * @param {Record<string, any>} declaration @param {Array<{role: string}>} ticketSources @param {string[]} servers @returns {string[]}
75
+ * M13 piece 4: the $0 refusals before any provider call. Tickets needs a ticket-list Inputs line; MCP (generic) and Tickets need a server that is startable and a tool list from a
76
+ * check (`pick`, src/mcp-pick.js: `{ok, server, tools}` or `{ok:false, say}`).
77
+ * @param {{flowType: string, ticketSources: Array<{role: string}>, pick: any, servers: string[]}} o @returns {string[]}
78
78
  */
79
- export function ticketReds(declaration, ticketSources, servers) {
80
- const reds = [];
81
- const roles = ticketSources.map((s) => s.role);
82
- if (!declaration.mcp) return [`declaration: the job reads the ticket input "${roles[0]}" but lists no "mcp" server and tools`];
83
- if (!servers.includes(declaration.mcp.server)) reds.push(`declaration: mcp.server "${declaration.mcp.server}" is not a server in your ~/.mcp.json (${servers.join(', ')})`);
84
- const reader = (declaration.steps ?? []).some((st) => (st.mcpTools ?? []).includes(TICKET_TOOL) && (st.reads ?? []).some((r) => roles.includes(r)));
85
- if (!reader) reds.push(`declaration: no step reads "${roles[0]}" and lists "${TICKET_TOOL}" in mcpTools`);
86
- return reds;
79
+ export function ticketReds({ flowType, ticketSources, pick, servers }) {
80
+ if (flowType === 'plain') return [];
81
+ if (flowType === 'tickets' && ticketSources.length === 0) return ['Tickets needs the ticket list address as an Inputs line (for example issues: https://github.com/owner/repo/issues)'];
82
+ if (!pick || pick.ok !== true) return [String(pick?.say ?? 'press check tools in Settings > MCP first')];
83
+ if (!servers.includes(pick.server)) return [`the MCP "${pick.server}" is not a server fwdloop can start (${servers.join(', ') || 'none found'})`];
84
+ return [];
87
85
  }
@@ -39,6 +39,16 @@ export function readTicketFields(text) {
39
39
  return { ok: true, labels, state: typeof o.state === 'string' ? o.state.toLowerCase() : null, title: typeof o.title === 'string' ? o.title : null };
40
40
  }
41
41
 
42
+ /**
43
+ * M13 piece 7 (9.4): the ONE reader of "the filter was unsure about this ticket", from a run.json input entry: true when its stored verdict ran with an `unsure`
44
+ * reason (also when the ticket was sent with Run it anyway and the filter's own verdict was unsure). Anything else, a torn entry too, is false.
45
+ * @param {any} entry @returns {boolean}
46
+ */
47
+ export function filterUnsure(entry) {
48
+ const f = entry?.filter;
49
+ return typeof f?.unsure === 'string' || (f?.outcome === 'anyway' && typeof f?.was?.unsure === 'string');
50
+ }
51
+
42
52
  /**
43
53
  * @param {{text: string, filter?: {priority?: string[], labels?: string[]}}} a `filter` = the job's signed `ticketFilter` (or absent)
44
54
  * @returns {{outcome: 'run', unsure?: string}|{outcome: 'skip', reason: string}}
package/src/ticket-mcp.js CHANGED
@@ -1,17 +1,40 @@
1
1
  // M12 piece 1b/1c (docs/wiki/the-module-ladder.md, "M12 scope (restart)" items 1-3, 11): read ONE ticket through the user's own MCP server, nothing else.
2
2
  // The tool source is the user's `~/.mcp.json` (an explicit path; a repo's .mcp.json is never read). The bridge starts ONLY the server the job names, with
3
- // `allow` = exactly the job's tools, so any other tool does not exist for the run. A tool the server does not mark `readOnlyHint: true` is refused by name.
3
+ // `allow` = exactly the job's tools, so any other tool does not exist for the run. M13 item 3: a hint (`readOnlyHint`) is info only; no tool is refused for lacking one.
4
4
  // Every refusal names its real cause (F101), at $0; none ever reads as empty content (F103). Proven by F100 (a ticket as a frozen input), F101, F103.
5
5
  // Borrowed shape: fwdloop poc/mcp/f100/scratch.diff (`src/ticket-mcp.js`), re-shaped: job-typed tools, explicit config, the three causes kept apart.
6
6
  import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
7
7
  import { homedir } from 'node:os';
8
8
  import { join } from 'node:path';
9
9
  import { redactSecrets } from './redact.js';
10
- import { parseTicketList } from './ticket-shape.js';
10
+ import { parseTicketList, isTicketNumber, TICKET_NUMBER_WORDS } from './ticket-shape.js';
11
+ import { mcpConfigFor } from './mcp-sources.js';
11
12
 
12
- /** the user's own MCP config, the only source of a tool */
13
+ /** M13 item 9.5: the only parent env names an MCP gets (plus its own settings); the one list for every place fwdloop starts an MCP, so no provider key reaches it */
14
+ export const MCP_PASS_ENV = ['PATH', 'HOME'];
15
+
16
+ /** M13 design point 11 (F118): the one start option set for every place fwdloop starts an MCP: no provider key (passEnv) and the home folder as the start folder (bare-agent bridge `cwd`; no `~` expansion, so the real path) */
17
+ export const mcpStartOpts = () => ({ passEnv: MCP_PASS_ENV, cwd: homedir() });
18
+
19
+ /** the refusal for a failed bridge start: a bad home folder (bare-agent throws ValidationError before any spawn) says so plainly, any other cause keeps its own first line */
20
+ export const startRefusal = (/** @type {string} */ server, /** @type {any} */ e) => `${server} did not start: ${e?.name === 'ValidationError' ? `the home folder could not be used (${firstLine(e)})` : firstLine(e)}`;
21
+
22
+ /** the user's own `~/.mcp.json`: the config a caller that names no place falls back to (a server found nowhere then reads "not in ~/.mcp.json") */
13
23
  export const USER_MCP_CONFIG = () => join(homedir(), '.mcp.json');
14
24
 
25
+ /**
26
+ * M13 piece 3: the config file a server starts from. An explicit path (a test seam) wins; otherwise the file of the WINNING place for `server` (src/mcp-sources.js,
27
+ * the one decider), or `~/.mcp.json` when no place has it. `remote` true = the winner has no start command (listed, not usable).
28
+ * @param {string} server @param {string} [explicit] @returns {{ file: string, remote: boolean }}
29
+ */
30
+ export function configForServer(server, explicit) {
31
+ if (explicit) return { file: explicit, remote: false };
32
+ return mcpConfigFor(server) ?? { file: USER_MCP_CONFIG(), remote: false };
33
+ }
34
+
35
+ /** the refusal for a remote server (no start command), at $0 @param {string} server */
36
+ export const remoteRefusal = (server) => `${server} is a remote server, not supported yet`;
37
+
15
38
  /** the first line of a message, secrets redacted, clipped: all a refusal ever shows of a server's own error */
16
39
  export const firstLine = (e) => redactSecrets(String(e?.message ?? e ?? '')).split('\n').find((l) => l.trim() !== '')?.trim().slice(0, 200) ?? 'no message';
17
40
 
@@ -24,25 +47,25 @@ export const isDeviceLogin = (text) => text.includes('github.com/login/device');
24
47
  * @returns {Promise<{ok: true, text: string, url: string, record: {server: string, exposed: string[], missing: Array<{server: string, tool: string}>, calls: Array<{tool: string, owner: string, repo: string, issue_number: number}>}} | {ok: false, error: string}>}
25
48
  * `record` is what the run keeps (in its `run.json` input entry): what the server exposed and lacked, and each call made.
26
49
  */
27
- export async function readTicketMcp({ listUrl, number, mcp, configPath = USER_MCP_CONFIG(), timeoutMs = 90000 }) {
50
+ export async function readTicketMcp({ listUrl, number, mcp, configPath: explicitConfig, timeoutMs = 90000 }) {
28
51
  const list = parseTicketList(listUrl);
29
52
  if (!list.ok) return list;
30
- if (!Number.isInteger(number) || number < 1) return { ok: false, error: `ticket number ${JSON.stringify(number)} is not a whole number from 1` };
53
+ if (!isTicketNumber(number)) return { ok: false, error: `ticket number ${JSON.stringify(number)} is not ${TICKET_NUMBER_WORDS}` };
31
54
  const { owner, repo } = list;
32
55
  const { server, tools } = mcp;
56
+ // M13 piece 4: the frozen read starts the server with issue_read alone, whatever else the job lists (the job lists every tool of its server)
33
57
  if (!tools.includes('issue_read')) return { ok: false, error: `the job does not list issue_read, the tool that reads a ticket` };
58
+ const { file: configPath, remote } = configForServer(server, explicitConfig);
34
59
  if (!discoverServers([configPath]).has(server)) return { ok: false, error: `${server} is not in ~/.mcp.json` };
60
+ if (remote) return { ok: false, error: remoteRefusal(server) };
35
61
  let bridge;
36
62
  try {
37
- bridge = await createMCPBridge({ configPaths: [configPath], timeout: timeoutMs, callTimeout: timeoutMs, confirmServer: () => true, allow: { [server]: tools } });
63
+ bridge = await createMCPBridge({ configPaths: [configPath], ...mcpStartOpts(), timeout: timeoutMs, callTimeout: timeoutMs, confirmServer: () => true, allow: { [server]: ['issue_read'] } });
38
64
  const failed = bridge.errors.find((e) => e.server === server);
39
65
  if (failed) return { ok: false, error: `${server} did not start: ${firstLine(failed.error)}` };
40
66
  const lacking = bridge.missing?.[0];
41
67
  if (lacking) return { ok: false, error: `${server} does not offer ${lacking.tool}` };
42
68
  const prefix = `${server}_`;
43
- for (const t of bridge.tools) {
44
- if (t.annotations?.readOnlyHint !== true) return { ok: false, error: `${server} does not mark ${t.name.slice(prefix.length)} read-only (readOnlyHint is not true)` };
45
- }
46
69
  const tool = bridge.tools.find((t) => t.name === `${prefix}issue_read`);
47
70
  if (!tool) return { ok: false, error: `${server} does not offer issue_read` };
48
71
  const call = { tool: 'issue_read', owner, repo, issue_number: number };
@@ -59,7 +82,7 @@ export async function readTicketMcp({ listUrl, number, mcp, configPath = USER_MC
59
82
  if (text.trim() === '') return { ok: false, error: `${server}: issue_read returned nothing for ${url}` };
60
83
  return { ok: true, text, url, record };
61
84
  } catch (e) {
62
- return { ok: false, error: `${server} did not start: ${firstLine(e)}` };
85
+ return { ok: false, error: startRefusal(server, e) };
63
86
  } finally {
64
87
  try { await bridge?.close(); } catch { /* already closed */ }
65
88
  }
@@ -0,0 +1,33 @@
1
+ // M13 piece 4 (hamr ruling R2, 2026-10-31): a by-hand Run on a Tickets job has no ticket # box. It reads the NEWEST ticket that has not run yet; the run then reads it through the
2
+ // job's filter as always (a non-match ends skipped, grey, $0). Nothing new = one plain line at $0 and no run. "Has run" = this job's own runs hold the number (`run.json`
3
+ // `inputs[].ticket.number`, a skipped run included); "newest" is the schedule's own look (`lookTickets`, the job's signed `list_issues`, newest first, open tickets).
4
+ // A job with no ticket run yet takes the newest open ticket of the first page (item 6: the first run reads the newest ticket at the time it starts; older ones never run).
5
+ import { join } from 'node:path';
6
+
7
+ import { listRunIds } from './flow.js';
8
+ import { readRunInputs } from './runfile.js';
9
+ import { lookTickets } from './trigger-tickets.js';
10
+
11
+ /** the ticket numbers this job's runs have read @param {string} flowDir @returns {Set<number>} */
12
+ export function ranTicketNumbers(flowDir) {
13
+ const out = new Set();
14
+ for (const id of listRunIds(flowDir)) {
15
+ const got = readRunInputs(join(flowDir, 'runs', id));
16
+ if (!got.ok) continue;
17
+ for (const e of got.entries) if (Number.isInteger(e?.ticket?.number)) out.add(e.ticket.number);
18
+ }
19
+ return out;
20
+ }
21
+
22
+ /**
23
+ * @param {{flowDir: string, listUrl: string, mcp: {server: string, tool: string}, configPath?: string, look?: typeof lookTickets}} o `look` is a test seam
24
+ * @returns {Promise<{ok: true, number: number} | {ok: false, say: string}>}
25
+ */
26
+ export async function newestUnrunTicket({ flowDir, listUrl, mcp, configPath, look = lookTickets }) {
27
+ const ran = ranTicketNumbers(flowDir);
28
+ const r = await look({ listUrl, mcp, ...(configPath ? { configPath } : {}), seen: ran.size === 0 ? null : ran, last: new Map(), watch: [] });
29
+ if (!r.ok) return { ok: false, say: String(r.error) };
30
+ const numbers = r.found.map((f) => f.number);
31
+ if (numbers.length === 0) return { ok: false, say: ran.size === 0 ? `No open ticket at ${listUrl}.` : `Nothing new: no ticket newer than #${Math.max(...ran)} has come in.` };
32
+ return { ok: true, number: Math.max(...numbers) };
33
+ }
@@ -22,3 +22,12 @@ export function parseTicketList(listUrl) {
22
22
  export function ticketListsOf(arbiter) {
23
23
  return Object.fromEntries((arbiter?.sources ?? []).filter((s) => s.kind === 'page' && LIST_URL.test(String(s.path).trim())).map((s) => [s.role, String(s.path).trim()]));
24
24
  }
25
+
26
+ /** M13 piece 7 (9.7): the one cap on a ticket number, 10 digits. Every door that takes or reads a ticket number uses `isTicketNumber`. Under 2^53, so a safe JS number. */
27
+ export const TICKET_MAX = 9_999_999_999;
28
+
29
+ /** The one check of a ticket number: a whole number from 1 to `TICKET_MAX`. @param {unknown} n @returns {n is number} */
30
+ export const isTicketNumber = (n) => Number.isSafeInteger(n) && /** @type {number} */ (n) >= 1 && /** @type {number} */ (n) <= TICKET_MAX;
31
+
32
+ /** The words every refusal of a ticket number uses. */
33
+ export const TICKET_NUMBER_WORDS = `a whole number from 1 to ${TICKET_MAX.toLocaleString('en-US')}`;
@@ -19,7 +19,7 @@ import { dirname } from 'node:path';
19
19
  import { appendRow, ledgerText } from './jsonl-append.js';
20
20
 
21
21
  /** @typedef {{kind:'daily'|'weekdays', hour:number, minute:number} | {kind:'weekly', day:string, hour:number, minute:number}} Schedule */
22
- /** @typedef {{id:string, kind:'armed'|'fire', at:number, slot?:number, catchUp?:boolean, missed?:number, sig?:string}} ClockRow */
22
+ /** @typedef {{id:string, kind:'armed'|'fire', at:number, slot?:number, catchUp?:boolean, missed?:number, sig?:string, ticketN?:number}} ClockRow */
23
23
  /** @typedef {{fire:boolean, catchUp:boolean, missed:number, slot?:number}} Due */
24
24
 
25
25
  /** A slot seen MORE than this after its set time is a catch-up (M9 am2 item 1). Exactly this late is on time. */
@@ -129,9 +129,9 @@ function appendOnce(file, row, sig) {
129
129
  appendRow(file, sig === undefined ? row : { ...row, sig });
130
130
  }
131
131
 
132
- /** The trigger was set at `now`: no slot before this ever fires. @param {string} file @param {number} now @param {string} [sig] */
133
- export function armTrigger(file, now, sig) {
134
- appendOnce(file, { id: `armed:${now}`, kind: 'armed', at: now }, sig);
132
+ /** The trigger was set at `now`: no slot before this ever fires. M13 piece 5: `ticketN` = the highest ticket number the first green run read; a ticket schedule's first look baselines only tickets up to it. @param {string} file @param {number} now @param {string} [sig] @param {number} [ticketN] */
133
+ export function armTrigger(file, now, sig, ticketN) {
134
+ appendOnce(file, { id: `armed:${now}`, kind: 'armed', at: now, ...(Number.isInteger(ticketN) ? { ticketN } : {}) }, sig);
135
135
  }
136
136
 
137
137
  /**
@@ -18,6 +18,7 @@ import {
18
18
  } from 'node:fs';
19
19
  import { basename, dirname, join } from 'node:path';
20
20
  import { createHash } from 'node:crypto';
21
+ import { compareNatural } from './natural.js';
21
22
 
22
23
  import { appendRow, ledgerText } from './jsonl-append.js';
23
24
 
@@ -78,13 +79,12 @@ export function recordDropped(ledger, item, why, at, sig) {
78
79
  }
79
80
 
80
81
  /**
81
- * The queue: arrived and neither ran nor dropped, oldest arrival first. Identical arrival times: by name, then by sha (deterministic).
82
+ * The queue: arrived and neither ran nor dropped, oldest arrival first. Identical arrival times: by name, then by sha (deterministic); numbers inside a name compare as numbers (`#8` before `#10`).
82
83
  * @param {SeenRow[]} rows @returns {(SeenRow & {path:string})[]}
83
84
  */
84
85
  export function queueOf(rows) {
85
- const cmp = (/** @type {string} */ x, /** @type {string} */ y) => (x < y ? -1 : x > y ? 1 : 0);
86
86
  return /** @type {any} */ (rows.filter((r) => waiting(rows, r)))
87
- .sort((x, y) => x.at - y.at || cmp(x.name, y.name) || cmp(x.sha, y.sha));
87
+ .sort((x, y) => x.at - y.at || compareNatural(x.name, y.name) || compareNatural(x.sha, y.sha));
88
88
  }
89
89
 
90
90
  /**