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/drafter.js CHANGED
@@ -20,7 +20,9 @@ import { capTooSmallText, usdText } from './draftspend.js';
20
20
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
21
21
  import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerSection } from './declaration.js';
22
22
  import { loadCatalogue } from './catalogue.js';
23
+ import { findMcpPlanRed } from './canrun.js';
23
24
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
25
+ import { ticketSourcesOf, ticketFactsLines, mcpFactsLines, ticketSchemaParts, ticketReds, userMcpServers } from './ticket-draft.js';
24
26
  import { readInputFacts } from './input-facts.js';
25
27
  import { freezePage } from './runner.js';
26
28
  import { removeFrozenPages } from './flow.js';
@@ -129,10 +131,12 @@ const SHAPE_PROPS = Object.freeze({
129
131
  /**
130
132
  * The forced tool's parameter schema. `menu` = wiredMenu(). `sheets` (M10b piece 3, optional) = the drafting copy's table of each CSV input role: with it a step may carry
131
133
  * `close.sheet`, and every column a check names is an enum of that sheet's exact header (src/sheetoffer.js); without it (no CSV input) no sheet property exists.
132
- * @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>}} [o]
134
+ * M13 piece 4: `ticket` = `{flowType, tools}` for MCP (generic) and Tickets; then a step may carry `mcpTools` (an enum of the job's tools) and, for Tickets, the tool carries `ticketFilter` and `ticketWatch` (src/ticket-draft.js). The job's `mcp` block and `flowType` are set by code, never offered.
135
+ * @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
133
136
  */
134
- export function buildDeclarationSchema(menu, { sheets } = {}) {
137
+ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
135
138
  const sheetProp = sheets ? sheetChecksProp(sheets) : null;
139
+ const ticketParts = ticket ? ticketSchemaParts(ticket) : null;
136
140
  const shapeProps = {};
137
141
  for (const key of SHAPE_KEYS) {
138
142
  if (!SHAPE_PROPS[key]) throw new Error(`schema: SHAPE_KEYS gained "${key}" — add its type to SHAPE_PROPS`);
@@ -152,6 +156,7 @@ export function buildDeclarationSchema(menu, { sheets } = {}) {
152
156
  items: { type: 'string', enum: menu.map((e) => e.verb) },
153
157
  description: 'verbs this step is granted, from the menu only; [] for a pure stop',
154
158
  },
159
+ ...(ticketParts ? ticketParts.step : {}),
155
160
  reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only (an ask step lists the earlier output to be checked FIRST), or the role of a CSV input (a step whose line has a green guardrail must list a CSV input role here)' },
156
161
  emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
157
162
  fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
@@ -182,6 +187,7 @@ export function buildDeclarationSchema(menu, { sheets } = {}) {
182
187
  additionalProperties: false,
183
188
  },
184
189
  },
190
+ ...(ticketParts ? ticketParts.top : {}),
185
191
  guardrailClasses: {
186
192
  type: 'object',
187
193
  additionalProperties: { type: 'string', enum: [...CLASSES] },
@@ -239,9 +245,9 @@ export const QUESTIONS_PROMPT = [
239
245
  ].join('\n');
240
246
 
241
247
  /** The declaration schema plus the optional `notChecked` (every try) and, on try 3 only, `questions`. Neither is in `required`. */
242
- /** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined}} [o] */
243
- export function buildRoundSchema(menu, { questions = false, sheets = undefined } = {}) {
244
- const s = buildDeclarationSchema(menu, { sheets });
248
+ /** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o] */
249
+ export function buildRoundSchema(menu, { questions = false, sheets = undefined, ticket = undefined } = {}) {
250
+ const s = buildDeclarationSchema(menu, { sheets, ticket });
245
251
  const extra = { notChecked: { type: 'array', items: { type: 'string' }, description: 'what the job asks for that no typed check verifies' } };
246
252
  if (questions) {
247
253
  extra.questions = {
@@ -429,6 +435,9 @@ export async function draft({
429
435
  priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
430
436
  draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
431
437
  learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
438
+ mcpServers = /** @type {string[]|undefined} */ (undefined),
439
+ // M13 piece 4: the job's flow type and its MCP pick (`mcpPickFor`: `{ok, server, tools}`), both set by code from the card; the drafter is told them, never asked for them
440
+ flowType = /** @type {'plain'|'mcp'|'tickets'} */ ('plain'), mcp = /** @type {any} */ (null),
432
441
  }) {
433
442
  // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
434
443
  const thinkingOf = () => {
@@ -454,6 +463,12 @@ export async function draft({
454
463
  // The file inputs are read first, at $0, before a provider is built (a page input is fetched only after the price and cap gates, below).
455
464
  const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
456
465
  if (!fileFacts.ok) return fail(fileFacts.reds);
466
+ // M13 piece 4: with flow type Tickets, a GitHub issues list is a ticket role, not a page: never fetched at draft; the drafter is told it exists and may suggest a label filter.
467
+ // The job's flow type and MCP (server + every tool of its newest OK check) come from the card; the refusals are at $0, before any provider is built.
468
+ const ticketSources = flowType === 'tickets' ? ticketSourcesOf(arbiter.sources) : [];
469
+ const servers = flowType === 'plain' ? [] : (mcpServers ?? userMcpServers());
470
+ const flowReds = ticketReds({ flowType, ticketSources, pick: mcp, servers });
471
+ if (flowReds.length) return fail(flowReds);
457
472
 
458
473
  let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
459
474
  let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
@@ -496,7 +511,7 @@ export async function draft({
496
511
 
497
512
  // M10 item 1: a web page input is fetched once and frozen into the DRAFT folder (the drafting copy). A run freezes its own copy at its own start
498
513
  // (`freezeInputs`), so a run is never checked against this one. Only now, after the $0 price and cap gates: a draft refused for money fetches nothing.
499
- const pageSources = (arbiter.sources ?? []).filter((s) => s.kind === 'page');
514
+ const pageSources = (arbiter.sources ?? []).filter((s) => s.kind === 'page' && !ticketSources.includes(s));
500
515
  /** @type {Record<string, {text: string, entry: {id: string, source: string, frozen: string, sha256: string, bytes: number}}>} */
501
516
  const pages = {};
502
517
  if (pageSources.length) {
@@ -507,7 +522,7 @@ export async function draft({
507
522
  pages[s.role] = { text: fr.text, entry: fr.entry };
508
523
  }
509
524
  }
510
- const facts = readInputFacts(arbiter.sources, { pages });
525
+ const facts = readInputFacts((arbiter.sources ?? []).filter((s) => !ticketSources.includes(s)), { pages });
511
526
  if (!facts.ok) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((pg) => pg.entry.frozen)); return fail(facts.reds); }
512
527
 
513
528
  // M10 item 3: ONE map call per page input names the page's own words; code keeps what the saved page proves. Every round goes through the
@@ -656,7 +671,8 @@ export async function draft({
656
671
  }
657
672
  }
658
673
  // The page lines go on the drafter's list of inputs: the first line of a page's block replaces the plain line readInputFacts wrote for it.
659
- const factsInfo = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
674
+ const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
675
+ const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role)), ...(flowType === 'mcp' ? mcpFactsLines(mcp.server, mcp.tools) : [])];
660
676
 
661
677
  // `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
662
678
  // M10b piece 3: the drafting copy's table of each CSV input - the header the drafter may pick from, the table bareguard's sign-time test runs over
@@ -689,7 +705,7 @@ export async function draft({
689
705
  // Amendment 25: a lock is a mechanism. Only try 3 of 3, and only when tries 1 and 2 BOTH failed validation (`revisions` counts the
690
706
  // validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
691
707
  const askOpen = offerQuestions && revisions === MAX_REVISIONS;
692
- const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables });
708
+ const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables, ticket: flowType === 'plain' ? undefined : { flowType, tools: mcp.tools } });
693
709
  const tool = {
694
710
  name: TOOL,
695
711
  description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
@@ -736,6 +752,9 @@ export async function draft({
736
752
  : malformed ? `the tool call's arguments were not valid JSON (${malformed.error})`
737
753
  : 'no usable tool call (text instead of the tool)';
738
754
  entry.outcome = `structure: ${why}`;
755
+ // the raw answer is kept (log.json): the unparseable arguments as sent, else the model's text
756
+ if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
757
+ else if (typeof result?.text === 'string' && result.text !== '') entry.rawText = result.text;
739
758
  log.push(entry);
740
759
  lastReds = [why];
741
760
  // M4d am3 A3: a round cut off at the output cap before tries 1 and 2 are spent is a FAILED TRY, advancing the same counter a
@@ -765,6 +784,10 @@ export async function draft({
765
784
  const { questions: rawQuestions, notChecked: rawNotChecked, ...captureRest } = /** @type {Record<string, any>} */ (captured);
766
785
  /** @type {Record<string, any>} */
767
786
  const declaration = { ...(askOpen ? captureRest : { ...captureRest, ...(rawQuestions === undefined ? {} : { questions: rawQuestions }) }), inputFacts: facts.inputFacts };
787
+ // M13 piece 4: the flow type and the job's MCP (server + every tool of the newest OK check, R1) are set by code; whatever the model sent for them is overwritten.
788
+ declaration.flowType = flowType;
789
+ if (flowType === 'plain') delete declaration.mcp;
790
+ else declaration.mcp = { server: mcp.server, tools: [...mcp.tools] };
768
791
  // M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
769
792
  if (Array.isArray(declaration.steps)) {
770
793
  declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
@@ -780,16 +803,21 @@ export async function draft({
780
803
  });
781
804
  }
782
805
  // M10b piece 4: `covers` (which ~ rules a check verifies) stays on the check and is signed; the validator checks it, the plan card shows it
783
- const verdict = validateDeclaration(declaration, {
806
+ const verdict1 = validateDeclaration(declaration, {
784
807
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
785
808
  // M10 am7 item 1: the words of every cited fact are proved on the drafting copy of the page, against what the page-word map kept
786
809
  sheetWords: sheetTables ? { headers: Object.fromEntries(Object.entries(sheetTables).map(([role, t]) => [role, t.header])), facts: sheetFacts.filter((f) => f.shape === 'column'), tables: sheetTables } : undefined,
787
810
  pageWords: { texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, look: pageSources.length ? { facts: look.facts, dropped: look.dropped } : null, docs: docRolesOf(arbiter.sources) },
788
811
  });
812
+ // M13 piece 4 (F105 rewritten): a generic MCP job whose steps call none of its tools is fed back like any validator red (the run would refuse it at $0, by the same sentence)
813
+ const planRed = verdict1.ok ? findMcpPlanRed(declaration) : null;
814
+ const verdict = planRed ? { ok: false, reds: [planRed] } : verdict1;
789
815
  lastDecl = declaration;
790
816
  const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
791
817
  extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...new Set([...pageNotChecked, ...cleanNotChecked(rawNotChecked), ...uncoveredRules(declaration, jobLines, Object.keys(facts.sheets ?? {}))])] };
792
818
  if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
819
+ // the declaration the model sent, as parsed, before any code overwrite (log.json keeps it per try)
820
+ entry.args = captured;
793
821
  if (verdict.ok) {
794
822
  entry.outcome = 'valid';
795
823
  log.push(entry);
package/src/flow.js CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  } from 'node:fs';
26
26
  import path from 'node:path';
27
27
 
28
+ import { compareNatural } from './natural.js';
28
29
  import { parseSignedText } from './signed-text.js';
29
30
  import { signFlow, verifyFlow } from './signature.js';
30
31
  import { validateDeclaration } from './declaration.js';
@@ -251,7 +252,7 @@ export function listRunIds(flowDir) {
251
252
  return entries
252
253
  .filter((e) => e.isDirectory() && checkRunId(e.name).ok)
253
254
  .map((e) => e.name)
254
- .sort();
255
+ .sort(compareNatural);
255
256
  }
256
257
 
257
258
  /**
package/src/launcher.js CHANGED
@@ -25,7 +25,7 @@ import { openAsker } from './prompts.js';
25
25
  import { dirname, join } from 'node:path';
26
26
  import { fileURLToPath } from 'node:url';
27
27
  import { readConfig, updateConfig, configPath, defaultFlowsRoot, ConfigError } from './config.js';
28
- import { keysHome, keysFilePath, createKeysFile } from './keysfile.js';
28
+ import { keysHome, keysFilePath, createKeysFile, isKeyName } from './keysfile.js';
29
29
  import { openInOs } from './opener.js';
30
30
  import { PLAIN, makePaint } from './tty-colour.js';
31
31
  import { readOwnVersion } from './version.js';
@@ -307,7 +307,9 @@ export function runNpm(args, o = {}) {
307
307
  const spawnImpl = o.spawnImpl ?? realSpawn;
308
308
  return new Promise((resolve) => {
309
309
  let child;
310
- try { child = spawnImpl('npm', args, { shell: false, stdio: 'inherit' }); } catch { resolve(1); return; }
310
+ // M13 am1: npm and its install scripts get the shell's env without any `*_KEY` setting (`isKeyName`); only the panel spawn (startCmd) carries keys
311
+ const env = Object.fromEntries(Object.entries(process.env).filter(([n]) => !isKeyName(n)));
312
+ try { child = spawnImpl('npm', args, { shell: false, stdio: 'inherit', env }); } catch { resolve(1); return; }
311
313
  let done = false;
312
314
  const end = (/** @type {number} */ code) => { if (done) return; done = true; clearTimeout(timer); resolve(code); };
313
315
  const timer = setTimeout(() => { try { child.kill('SIGTERM'); } catch { /* already gone */ } end(1); }, o.deadlineMs ?? NPM_DEADLINE_MS);
package/src/learnstore.js CHANGED
@@ -10,6 +10,7 @@
10
10
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync } from 'node:fs';
11
11
  import { join, dirname, resolve } from 'node:path';
12
12
  import { homedir } from 'node:os';
13
+ import { compareNatural } from './natural.js';
13
14
  import { configHome, configDoorHome, readConfig } from './config.js';
14
15
  import { emptyLedger, redactDeep, countLedger, releasePending, recordHealth, buildCards, placeOf, renderHints } from './learn.js';
15
16
  import { readAudit, readHistory } from './books.js';
@@ -276,7 +277,7 @@ export function learnAtRunEnd({ home, workflow, runId, runDir, specHash, now = n
276
277
  }
277
278
 
278
279
  /** M8 am4 item 2: a run waiting at an ask has not ended ('paused', or a Stop whose set-aside failed). ONE decider: the runner's run-end tally and the seed both read it. */
279
- export const NOT_A_RUN_END = new Set(['paused', 'stop-failed']);
280
+ export const NOT_A_RUN_END = new Set(['paused', 'stop-failed', 'skipped']); // M12 p3: a skipped ticket is not a job run with anything to learn from
280
281
 
281
282
  /**
282
283
  * M8 am6: seed the ledger from every run already recorded under `root` (every job, every ended run), oldest first by the run's own end time
@@ -316,7 +317,7 @@ export function seedLedger({ root, home }) {
316
317
  } catch { out.skipped.unreadable += 1; }
317
318
  }
318
319
  }
319
- todo.sort((a, b) => a.end.getTime() - b.end.getTime() || `${a.workflow}/${a.runId}`.localeCompare(`${b.workflow}/${b.runId}`));
320
+ todo.sort((a, b) => a.end.getTime() - b.end.getTime() || compareNatural(`${a.workflow}/${a.runId}`, `${b.workflow}/${b.runId}`));
320
321
  for (const t of todo) {
321
322
  const cur = readLedger(home);
322
323
  if (cur.problem) { out.problem = cur.problem; return out; }
@@ -0,0 +1,50 @@
1
+ // M13 piece 3 (hamr 2026-10-31): the log of `check tools` presses, `mcp-checks.jsonl` beside config.json. APPEND-ONLY: each press appends one line, nothing is ever rewritten
2
+ // or removed. A line is `{server, path, at, ok, tools:[{name, hint}]}` or `{server, path, at, ok:false, error}`. The page shows the newest line per path and server.
3
+ // A torn or foreign line is skipped when reading, so a half-written last line never hides the earlier ones.
4
+ import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { configHome } from './config.js';
7
+
8
+ export const MCP_CHECKS_FILE = 'mcp-checks.jsonl';
9
+
10
+ /** @param {string|undefined} home the config home */
11
+ export const mcpChecksFile = (home) => join(configHome(home), MCP_CHECKS_FILE);
12
+
13
+ /** append ONE line; throws when it cannot be written @param {string|undefined} home @param {Record<string, any>} entry */
14
+ export function appendMcpCheck(home, entry) {
15
+ mkdirSync(configHome(home), { recursive: true, mode: 0o700 });
16
+ appendFileSync(mcpChecksFile(home), `${JSON.stringify(entry)}\n`, { mode: 0o600 });
17
+ }
18
+
19
+ /** every well-formed line, oldest first; none when the file is missing @param {string|undefined} home @returns {any[]} */
20
+ function checkLines(home) {
21
+ let text = '';
22
+ try { text = readFileSync(mcpChecksFile(home), 'utf8'); } catch { return []; }
23
+ const out = [];
24
+ for (const line of text.split('\n')) {
25
+ let r;
26
+ try { r = JSON.parse(line); } catch { continue; }
27
+ if (typeof r?.server !== 'string' || typeof r?.path !== 'string' || typeof r?.at !== 'string') continue;
28
+ out.push(r);
29
+ }
30
+ return out;
31
+ }
32
+
33
+ /** the newest line per `path\tserver` @param {string|undefined} home @returns {Map<string, any>} */
34
+ export function newestMcpChecks(home) {
35
+ const out = new Map();
36
+ for (const r of checkLines(home)) out.set(`${r.path}\t${r.server}`, r);
37
+ return out;
38
+ }
39
+
40
+ /** M13 piece 4 (R1): the tool names of the newest OK line (with at least one tool) for this server at this path, or null @param {string|undefined} home @param {string} server @param {string} path @returns {string[]|null} */
41
+ export function newestOkMcpTools(home, server, path) {
42
+ /** @type {string[]|null} */
43
+ let tools = null;
44
+ for (const r of checkLines(home)) {
45
+ if (r.server !== server || r.path !== path || r.ok !== true || !Array.isArray(r.tools)) continue;
46
+ const names = r.tools.map((/** @type {any} */ x) => x?.name).filter((/** @type {unknown} */ n) => typeof n === 'string' && n !== '');
47
+ if (names.length > 0) tools = [...new Set(names)];
48
+ }
49
+ return tools;
50
+ }
@@ -0,0 +1,33 @@
1
+ // M13 piece 4 (hamr ruling R1, 2026-10-31): the ONE place that decides the tools a job gets from its MCP. A job with an MCP gets ALL the tools of that MCP's newest OK line in
2
+ // `mcp-checks.jsonl` (src/mcp-checks.js), set by code: never chosen by the drafter, never reviewed by the person, and no server is ever started here (a server starts only on
3
+ // a press of `check tools`). A tool the server gains later is not in the job (signed item 3). Read-only; writes nothing.
4
+ import { newestOkMcpTools } from './mcp-checks.js';
5
+ import { mcpSources, mcpConfigFor } from './mcp-sources.js';
6
+ import { configDoorHome, configHome } from './config.js';
7
+ import { remoteRefusal } from './ticket-mcp.js';
8
+
9
+ /** the one refusal for an MCP nobody has checked (or whose check never succeeded) */
10
+ export const NEVER_CHECKED_SAY = 'press check tools in Settings > MCP first';
11
+
12
+ /**
13
+ * @param {string} server @param {string|undefined|null} home the config home; undefined = the door's decision (`configDoorHome`: a test process with no `FWDLOOP_CONFIG_HOME` has none, so "never checked"; otherwise the default config home); null = none
14
+ * @returns {{ ok: true, server: string, tools: string[] } | { ok: false, say: string }}
15
+ */
16
+ export function mcpPickFor(server, home) {
17
+ if (home === undefined) {
18
+ const door = configDoorHome();
19
+ if (door.skip) return { ok: false, say: NEVER_CHECKED_SAY };
20
+ home = configHome(door.home);
21
+ }
22
+ if (typeof home !== 'string') return { ok: false, say: NEVER_CHECKED_SAY };
23
+ const place = mcpSources({ home }).places.find((p) => p.servers.some((s) => s.name === server));
24
+ if (!place) return { ok: false, say: `${server} is not in any MCP config (Settings > MCP lists the ones found)` };
25
+ if (mcpConfigFor(server, { home })?.remote) return { ok: false, say: remoteRefusal(server) };
26
+ const tools = newestOkMcpTools(home, server, place.path);
27
+ return tools === null ? { ok: false, say: NEVER_CHECKED_SAY } : { ok: true, server, tools };
28
+ }
29
+
30
+ /** `mcpPickFor` at the config home this process uses (a test process with no `FWDLOOP_CONFIG_HOME` has none) @param {string} server */
31
+ export function mcpPickHere(server) {
32
+ return mcpPickFor(server, undefined);
33
+ }
@@ -0,0 +1,84 @@
1
+ // M13 piece 3 (docs/wiki/the-module-ladder.md, M13 scope items 1 and 2): the ONE place that decides where fwdloop's MCP servers come from.
2
+ // Sources, in order: the 4 places bare-agent reads, then the paths the person added on Settings > MCP (config.json `mcpPaths`, in the order added).
3
+ // A project folder's `.mcp.json` is never read: every path here is explicit, bare-agent's default discovery is never called (F108 c).
4
+ // bare-agent's `discoverServers` is called once PER PATH (it merges silently and keeps no file of origin, F108 a); the merge, "first wins" and the shadow mark are done here.
5
+ // A server with no `command` (a remote one) is listed and marked `remote`: it is never started. This file only READS the config files and
6
+ // returns names, flags and file paths; a command, its args and its env are never copied out of `discoverServers`' result.
7
+ import { discoverServers } from 'bare-agent/mcp';
8
+ import { existsSync, readFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { readConfig, configDoorHome, ConfigError } from './config.js';
12
+
13
+ export { mcpPathProblem } from './config.js';
14
+
15
+ /** the 4 places bare-agent reads, in its order (absolute) */
16
+ export const DEFAULT_MCP_PLACES = () => {
17
+ const h = homedir();
18
+ return [join(h, '.mcp.json'), join(h, '.claude', 'mcp_servers.json'), join(h, '.config', 'Claude', 'claude_desktop_config.json'), join(h, '.cursor', 'mcp.json')];
19
+ };
20
+
21
+ /** a typed path as a real one: `~/` is the home folder @param {string} p */
22
+ export const expandMcpPath = (p) => (p === '~' ? homedir() : p.startsWith('~/') ? join(homedir(), p.slice(2)) : p);
23
+
24
+ /** a path as the page shows it: the home folder written `~` @param {string} p */
25
+ export const showMcpPath = (p) => { const h = homedir(); return p === h ? '~' : p.startsWith(`${h}/`) ? `~${p.slice(h.length)}` : p; };
26
+
27
+ /** the added paths in config.json (typed form); none under a test process with no config home, or when config.json is broken (the page says so) @param {string} [home] */
28
+ export function addedMcpPaths(home) {
29
+ let h = home;
30
+ if (h === undefined) { const door = configDoorHome(); if (door.skip) return { paths: [], problem: null }; h = door.home; }
31
+ try {
32
+ const c = readConfig({ home: h });
33
+ return { paths: Array.isArray(c.mcpPaths) ? /** @type {string[]} */ (c.mcpPaths) : [], problem: null };
34
+ } catch (e) {
35
+ if (!(e instanceof ConfigError)) throw e;
36
+ return { paths: [], problem: 'Your settings file (config.json) cannot be read, so added paths are not shown.' };
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Every place, in order, with the servers found in it.
42
+ * `status`: 'found' (a readable file), 'missing' (no file) or 'not-json' (a file that is not JSON; bare-agent skips it silently).
43
+ * A server: `{name, remote, shadowedBy}`; `shadowedBy` is the shown path of the earlier place that has the same name (the earlier one wins), or null.
44
+ * @param {{ home?: string }} [o] `home` the config home (tests); undefined = the door's
45
+ * @returns {{ places: Array<{ path: string, file: string, added: boolean, status: 'found'|'missing'|'not-json', servers: Array<{name: string, remote: boolean, shadowedBy: string|null}> }>, problem: string|null }}
46
+ */
47
+ export function mcpSources(o = {}) {
48
+ const added = addedMcpPaths(o.home);
49
+ const typed = [...DEFAULT_MCP_PLACES().map((p) => ({ path: showMcpPath(p), added: false })), ...added.paths.map((p) => ({ path: p, added: true }))];
50
+ /** @type {Map<string, string>} */
51
+ const first = new Map();
52
+ const places = typed.map(({ path, added: isAdded }) => {
53
+ const file = expandMcpPath(path);
54
+ if (!existsSync(file)) return { path, file, added: isAdded, status: /** @type {const} */ ('missing'), servers: [] };
55
+ try { JSON.parse(readFileSync(file, 'utf8')); } catch { return { path, file, added: isAdded, status: /** @type {const} */ ('not-json'), servers: [] }; }
56
+ const found = discoverServers([file]);
57
+ const servers = [...found].map(([name, def]) => {
58
+ const shadowedBy = first.get(name) ?? null;
59
+ if (shadowedBy === null) first.set(name, path);
60
+ return { name, remote: typeof def?.command !== 'string' || def.command === '', shadowedBy };
61
+ });
62
+ return { path, file, added: isAdded, status: /** @type {const} */ ('found'), servers };
63
+ });
64
+ return { places, problem: added.problem };
65
+ }
66
+
67
+ /**
68
+ * The file that holds the WINNING `server` (the first place in the list that has the name), whether it is remote, or null when no place has it.
69
+ * Every place fwdloop starts an MCP from takes its config file from here.
70
+ * @param {string} server @param {{ home?: string }} [o]
71
+ * @returns {{ file: string, remote: boolean } | null}
72
+ */
73
+ export function mcpConfigFor(server, o = {}) {
74
+ for (const p of mcpSources(o).places) {
75
+ const s = p.servers.find((x) => x.name === server);
76
+ if (s) return { file: p.file, remote: s.remote };
77
+ }
78
+ return null;
79
+ }
80
+
81
+ /** the names of the servers that can be started (winners only, remote left out) @param {{ home?: string }} [o] @returns {string[]} */
82
+ export function startableMcpServers(o = {}) {
83
+ return mcpSources(o).places.flatMap((p) => p.servers.filter((s) => !s.remote && s.shadowedBy === null).map((s) => s.name));
84
+ }
package/src/mcp-use.js ADDED
@@ -0,0 +1,54 @@
1
+ // M13 piece 3 (docs/wiki/the-module-ladder.md, M13 scope item 2 "Use counts come from what runs already record"; FINDINGS F113): how often each MCP server's tools were used,
2
+ // read from what runs already keep. No new run-folder file, nothing is written.
3
+ // - a ticket read: `run.json` `inputs[].mcp.calls` (server + tool; the file holds no time, so `last` is the file's mtime);
4
+ // - a step's tool call: a `kind:"tool"` row of `diary.jsonl` whose tool is `<server>_<tool>` (M13 piece 2); `decision:"deny"` is a denied call, counted apart and not as a use.
5
+ // A torn or unreadable file is skipped, row by row (its rows go missing from the count; it never breaks the page).
6
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+
9
+ const safeDir = (/** @type {string} */ p) => { try { return readdirSync(p); } catch { return []; } };
10
+
11
+ /**
12
+ * @param {string} root the jobs folder (`<root>/<flow>/runs/run-<n>/`)
13
+ * @param {string[]} servers the server names to count for; a step tool row belongs to the LONGEST name that prefixes it with `_`
14
+ * @returns {Map<string, { calls: number, runs: number, last: string|null, denied: number, tools: Map<string, number> }>}
15
+ */
16
+ export function countMcpUse(root, servers) {
17
+ const byLength = [...servers].sort((a, b) => b.length - a.length);
18
+ /** @type {Map<string, { calls: number, runSet: Set<string>, last: string, denied: number, tools: Map<string, number> }>} */
19
+ const acc = new Map(servers.map((s) => [s, { calls: 0, runSet: new Set(), last: '', denied: 0, tools: new Map() }]));
20
+ const use = (/** @type {string} */ server, /** @type {string} */ tool, /** @type {string} */ run, /** @type {string} */ at, /** @type {boolean} */ denied) => {
21
+ const a = acc.get(server);
22
+ if (!a) return;
23
+ if (denied) { a.denied++; return; }
24
+ a.calls++; a.runSet.add(run); a.tools.set(tool, (a.tools.get(tool) ?? 0) + 1);
25
+ if (at && at > a.last) a.last = at;
26
+ };
27
+ for (const flow of safeDir(root)) {
28
+ for (const name of safeDir(join(root, flow, 'runs'))) {
29
+ if (!name.startsWith('run-')) continue;
30
+ const dir = join(root, flow, 'runs', name);
31
+ const key = `${flow}/${name}`;
32
+ try {
33
+ const j = JSON.parse(readFileSync(join(dir, 'run.json'), 'utf8'));
34
+ const mtime = statSync(join(dir, 'run.json')).mtime.toISOString();
35
+ for (const i of Array.isArray(j?.inputs) ? j.inputs : []) {
36
+ const m = i?.mcp;
37
+ if (!m || typeof m.server !== 'string') continue;
38
+ for (const c of Array.isArray(m.calls) ? m.calls : []) if (typeof c?.tool === 'string') use(m.server, c.tool, key, mtime, false);
39
+ }
40
+ } catch { /* no run.json, or torn: nothing counted from it */ }
41
+ let text;
42
+ try { text = readFileSync(join(dir, 'diary.jsonl'), 'utf8'); } catch { continue; }
43
+ for (const line of text.split('\n')) {
44
+ if (!line.includes('"kind":"tool"')) continue;
45
+ let r;
46
+ try { r = JSON.parse(line); } catch { continue; }
47
+ if (r?.kind !== 'tool' || typeof r.tool !== 'string') continue;
48
+ const server = byLength.find((s) => r.tool.startsWith(`${s}_`) && r.tool.length > s.length + 1);
49
+ if (server) use(server, r.tool.slice(server.length + 1), key, typeof r.at === 'string' ? r.at : '', r.decision === 'deny');
50
+ }
51
+ }
52
+ }
53
+ return new Map([...acc].map(([s, a]) => [s, { calls: a.calls, runs: a.runSet.size, last: a.last || null, denied: a.denied, tools: a.tools }]));
54
+ }
package/src/natural.js ADDED
@@ -0,0 +1,23 @@
1
+ // M13 item 9.6: the ONE place that orders names with numbers in them (`run-9` before `run-10`, `#8` before `#10`, `run-3-rerun-1` before `run-25`).
2
+ // Digit runs compare as numbers (by length after leading zeros, then by text, so a long number never loses digits); everything else compares as text.
3
+
4
+ /** @param {string} a @param {string} b digit strings */
5
+ const digits = (a, b) => {
6
+ const x = a.replace(/^0+/, '');
7
+ const y = b.replace(/^0+/, '');
8
+ return x.length - y.length || (x < y ? -1 : x > y ? 1 : 0);
9
+ };
10
+
11
+ /** @param {unknown} x @param {unknown} y @returns {number} negative, 0 or positive, like a sort callback */
12
+ export function compareNatural(x, y) {
13
+ const tx = String(x).match(/\d+|\D+/g) ?? [];
14
+ const ty = String(y).match(/\d+|\D+/g) ?? [];
15
+ for (let i = 0; i < Math.min(tx.length, ty.length); i++) {
16
+ const a = tx[i];
17
+ const b = ty[i];
18
+ if (a === b) continue; // eslint-disable-line no-continue
19
+ const c = /^\d/.test(a) && /^\d/.test(b) ? digits(a, b) : (a < b ? -1 : 1);
20
+ if (c !== 0) return c;
21
+ }
22
+ return tx.length - ty.length;
23
+ }
@@ -369,7 +369,9 @@ export function createAuthor(opts) {
369
369
  }
370
370
 
371
371
  /** The flags that make a draft child use the card's model and thinking choice. @param {any} card */
372
- const modelArgv = (card) => ['--model', card.model, '--provider', card.provider, ...(card.thinking === true ? ['--thinking'] : [])];
372
+ const modelArgv = (card) => ['--model', card.model, '--provider', card.provider, ...(card.thinking === true ? ['--thinking'] : []),
373
+ // M13 piece 4: the card's Flow type and MCP ride every draft of the job (first, revised, redrafted)
374
+ ...(card.flowType ? ['--flow-type', card.flowType, '--mcp', card.mcp] : [])];
373
375
 
374
376
  /**
375
377
  * The $0 checks both a first draft and a revise run on the card as submitted: the card's own checks (a key value, the flow name,
@@ -602,6 +604,18 @@ export function createAuthor(opts) {
602
604
  const runOfRec = readJson(dir, RUN_OF_FILE);
603
605
  const asRunOf = typeof runOfRec?.flow === 'string' ? { flow: runOfRec.flow } : undefined;
604
606
  if (asRunOf !== undefined && runId !== '') return { status: 400, body: { ok: false, refused: 'run-id', say: 'This plan becomes the next run of its workflow by itself; a run name cannot be typed. Nothing was signed.' } };
607
+ // M13 piece 5 (signed item 7): the card's Schedule row is checked now, on the plan about to be signed, so a refusal never leaves a signed job without its schedule. A plan that becomes the next
608
+ // run of its workflow signs no job, so it signs no schedule: the workflow keeps the one it has.
609
+ let cardSchedule = null;
610
+ if (asRunOf === undefined && v.card.schedule) {
611
+ const planProse = readFileInside(join(dir, v.plan), 'prose.txt');
612
+ const planDecl = readJson(join(dir, v.plan), 'declaration.json');
613
+ const parsedPlan = planProse.ok ? parseSignedText(planProse.text) : null;
614
+ if (!parsedPlan || !parsedPlan.ok || !planDecl) return { status: 409, body: { ok: false, refused: 'schedule', say: 'The plan could not be read to check its schedule. Nothing was signed.' } };
615
+ const planned = triggerDoor.cardSchedule(v.card.schedule, { arbiter: parsedPlan.arbiter, declaration: planDecl });
616
+ if (!planned.ok) return { status: 400, body: { ok: false, refused: 'schedule', say: planned.say } };
617
+ cardSchedule = planned.trigger;
618
+ }
605
619
  const result = signDraft({
606
620
  dir: join(dir, v.plan), approve: v.hash, signedBy, env: loaded.env, keyNames: loaded.keyNames, sessionDir: dir, ...(asRunOf ? { asRunOf } : {}),
607
621
  });
@@ -627,6 +641,8 @@ export function createAuthor(opts) {
627
641
  const started = starter.start({
628
642
  kind: 'sign', flow: name, runId, sources: inputs.map((r) => ({ role: r.role, path: r.path })), values, ...(asRunOf ? { planRun: true, pick: result.modelPick ?? null } : {}),
629
643
  }, loaded);
644
+ // M13 piece 5 (signed item 7): the same sign writes the job's schedule.json, OFF; the panel turns it on after the job's first green run. `from` = the run this sign started.
645
+ if (cardSchedule !== null) triggerDoor.signSchedule({ flow: name, flowSignatureHash: result.signature.flow, trigger: cardSchedule, from: started.status === 202 && typeof started.body.runId === 'string' ? started.body.runId : null, signedBy });
630
646
  if (started.status !== 202) return { status: started.status, body: { ...started.body, signed: true, flow: name, say: `${started.body.say ?? 'The run did not start.'} The flow is signed; start it from "Run a signed flow".` } };
631
647
  return { status: 202, body: { ...started.body, signed: true } };
632
648
  },
@@ -19,6 +19,11 @@ import { isWebUrl } from '../pagefetch.js';
19
19
  import { checkSendDestination } from '../runner.js';
20
20
  import { parseSignedText } from '../signed-text.js';
21
21
  import { capTooSmallText } from '../draftspend.js';
22
+ import { startableMcpServers, mcpConfigFor } from '../mcp-sources.js';
23
+ import { mcpPickFor } from '../mcp-pick.js';
24
+ import { isTicketListUrl } from '../ticket-draft.js';
25
+ import { validateSchedule } from '../trigger-clock.js';
26
+ import { remoteRefusal } from '../ticket-mcp.js';
22
27
  import { readPriceConfig, resolveUsableModel, ceilingCostUsd } from '../provider.js';
23
28
 
24
29
  /** The heading line the prose files use (flows/job2-m6a-3/prose.txt); the parser matches `/^arbiter guardrails\b/i`. */
@@ -182,6 +187,11 @@ export function cardFields(body) {
182
187
  // M4d amendment 6: the picked model (a key name and a model id from Chat's menu) and the per-job "Thinking on" tick; present only when sent
183
188
  ...(str(b.provider).trim() !== '' || str(b.model).trim() !== '' ? { provider: str(b.provider).trim(), model: str(b.model).trim() } : {}),
184
189
  ...(b.thinking === true ? { thinking: true } : {}),
190
+ // M13 piece 4: the Flow type (plain | mcp | tickets) and the MCP pick; sent only when the card names one, signed with the job
191
+ ...(str(b.flowType).trim() !== '' && str(b.flowType).trim() !== 'plain' ? { flowType: str(b.flowType).trim(), mcp: str(b.mcp).trim() } : {}),
192
+ // M13 piece 5 (item 7): the Schedule row, signed with the job. Absent = By hand (no schedule.json). Only the typed fields are kept.
193
+ ...(b.schedule && typeof b.schedule === 'object' && !Array.isArray(b.schedule)
194
+ ? { schedule: b.schedule.kind === 'new-ticket' ? { kind: 'new-ticket' } : { kind: b.schedule.kind, hour: b.schedule.hour, minute: b.schedule.minute } } : {}),
185
195
  };
186
196
  }
187
197
 
@@ -390,6 +400,31 @@ export function checkCard(card, { root, keys = [], home, runOf }) {
390
400
  if (why !== null) no('destination', why);
391
401
  }
392
402
 
403
+ // M13 piece 4: the Flow type and its MCP. MCP and Tickets name an MCP fwdloop can start whose tools have been checked (R1: the job gets every tool of the newest OK check;
404
+ // never a started server here). Tickets needs the ticket list address as an Inputs line; MCP may have none.
405
+ const flow = /** @type {{flowType?: string, mcp?: string}} */ (card).flowType ?? 'plain';
406
+ if (!['plain', 'mcp', 'tickets'].includes(flow)) no('flowType', 'Flow type must be plain, MCP or Tickets MCP.');
407
+ else if (flow !== 'plain') {
408
+ const server = String(/** @type {any} */ (card).mcp ?? '');
409
+ if (server === '') no('mcp', 'Pick an MCP.');
410
+ else if (!startableMcpServers({ home }).includes(server)) no('mcp', mcpConfigFor(server, { home })?.remote ? remoteRefusal(server) : `${server} is not an MCP fwdloop can start (Settings > MCP lists the ones found).`);
411
+ else {
412
+ const pick = mcpPickFor(server, home);
413
+ if (!pick.ok) no('mcp', pick.say);
414
+ }
415
+ if (flow === 'tickets' && !parseInputLines(card.inputs).some((i) => isTicketListUrl(i.path))) no('inputs', 'Tickets needs the ticket list address as an Inputs line (for example issues: https://github.com/owner/repo/issues).');
416
+ }
417
+
418
+ // M13 piece 5 (item 7): the Schedule row. Every day at HH:MM for any flow type; When a new ticket arrives only for Tickets. The trigger itself (list, server, tool) is filled from the signed job at sign.
419
+ const sched = /** @type {any} */ (card).schedule;
420
+ if (sched !== undefined) {
421
+ if (sched.kind === 'new-ticket') {
422
+ if (flow !== 'tickets') no('schedule', 'Only a Tickets MCP job can start on a new ticket.');
423
+ } else if (sched.kind === 'daily') {
424
+ try { validateSchedule(sched); } catch { no('schedule', 'The time must be an hour 0-23 and a minute 0-59, like 09:00.'); }
425
+ } else no('schedule', 'Pick when it runs from the choices.');
426
+ }
427
+
393
428
  // inputs: one `name: path` per line; a role and a path on every line, no repeated role; each path a readable regular file (realpath)
394
429
  refusals.push(...checkInputRows(parseInputLines(card.inputs)));
395
430