fwdloop 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +54 -13
  3. package/package.json +3 -3
  4. package/src/ask.js +1 -1
  5. package/src/audit-fold.js +9 -1
  6. package/src/authoring.js +22 -5
  7. package/src/canrun.js +19 -16
  8. package/src/checked.js +5 -2
  9. package/src/checkpick.js +257 -0
  10. package/src/checkwords.js +24 -0
  11. package/src/closers.js +8 -1
  12. package/src/config.js +18 -0
  13. package/src/declaration.js +85 -5
  14. package/src/drafter.js +143 -47
  15. package/src/flow.js +2 -1
  16. package/src/launcher.js +4 -2
  17. package/src/learn.js +1 -1
  18. package/src/learnstore.js +8 -7
  19. package/src/mcp-checks.js +50 -0
  20. package/src/mcp-pick.js +33 -0
  21. package/src/mcp-sources.js +84 -0
  22. package/src/mcp-use.js +54 -0
  23. package/src/memo.js +120 -0
  24. package/src/model-step.js +89 -17
  25. package/src/natural.js +23 -0
  26. package/src/pageask.js +9 -6
  27. package/src/pagedropwords.js +9 -0
  28. package/src/panel/author.js +50 -28
  29. package/src/panel/authorcard.js +86 -2
  30. package/src/panel/authorflows.js +18 -14
  31. package/src/panel/authortrigger.js +241 -84
  32. package/src/panel/data.js +99 -11
  33. package/src/panel/index.html +683 -210
  34. package/src/panel/jobgrid.js +127 -0
  35. package/src/panel/result.js +28 -7
  36. package/src/panel/scheduler.js +8 -2
  37. package/src/panel/server.js +17 -7
  38. package/src/panel/settings.js +119 -4
  39. package/src/panel/tickets.js +12 -7
  40. package/src/pickrecord.js +146 -0
  41. package/src/plain-checks.js +1 -0
  42. package/src/primitives.js +34 -5
  43. package/src/provider.js +4 -1
  44. package/src/runfile.js +4 -2
  45. package/src/runner.js +170 -45
  46. package/src/send.js +71 -4
  47. package/src/setup.js +13 -1
  48. package/src/summary-words.js +15 -3
  49. package/src/ticket-draft.js +40 -42
  50. package/src/ticket-labels.js +10 -0
  51. package/src/ticket-mcp.js +33 -10
  52. package/src/ticket-next.js +33 -0
  53. package/src/ticket-shape.js +9 -0
  54. package/src/trigger-clock.js +4 -4
  55. package/src/trigger-files.js +3 -3
  56. package/src/trigger-tickets.js +41 -12
  57. package/types/ask.d.ts +2 -1
  58. package/types/audit-fold.d.ts +13 -2
  59. package/types/authoring.d.ts +10 -2
  60. package/types/canrun.d.ts +5 -12
  61. package/types/checked.d.ts +7 -2
  62. package/types/checkpick.d.ts +149 -0
  63. package/types/checkwords.d.ts +14 -0
  64. package/types/closers.d.ts +2 -1
  65. package/types/config.d.ts +6 -0
  66. package/types/declaration.d.ts +17 -0
  67. package/types/drafter.d.ts +446 -50
  68. package/types/learn.d.ts +1 -0
  69. package/types/learnstore.d.ts +2 -3
  70. package/types/mcp-checks.d.ts +8 -0
  71. package/types/mcp-pick.d.ts +23 -0
  72. package/types/mcp-sources.d.ts +51 -0
  73. package/types/mcp-use.d.ts +12 -0
  74. package/types/memo.d.ts +15 -0
  75. package/types/model-step.d.ts +5 -0
  76. package/types/natural.d.ts +2 -0
  77. package/types/pageask.d.ts +9 -2
  78. package/types/pagedropwords.d.ts +1 -0
  79. package/types/panel/author.d.ts +37 -1
  80. package/types/panel/authorcard.d.ts +52 -0
  81. package/types/panel/authorflows.d.ts +9 -1
  82. package/types/panel/authortrigger.d.ts +73 -7
  83. package/types/panel/data.d.ts +56 -2
  84. package/types/panel/jobgrid.d.ts +109 -0
  85. package/types/panel/result.d.ts +9 -3
  86. package/types/panel/server.d.ts +5 -1
  87. package/types/panel/settings.d.ts +3 -2
  88. package/types/panel/tickets.d.ts +26 -4
  89. package/types/pickrecord.d.ts +88 -0
  90. package/types/primitives.d.ts +15 -2
  91. package/types/runfile.d.ts +7 -2
  92. package/types/runner.d.ts +128 -77
  93. package/types/send.d.ts +10 -2
  94. package/types/setup.d.ts +1 -56
  95. package/types/summary-words.d.ts +22 -3
  96. package/types/ticket-draft.d.ts +40 -32
  97. package/types/ticket-labels.d.ts +6 -0
  98. package/types/ticket-mcp.d.ts +18 -1
  99. package/types/ticket-next.d.ts +23 -0
  100. package/types/ticket-shape.d.ts +5 -0
  101. package/types/trigger-clock.d.ts +4 -3
  102. package/types/trigger-files.d.ts +1 -1
  103. package/types/trigger-tickets.d.ts +18 -4
  104. package/src/attemptdiff.js +0 -118
  105. package/types/attemptdiff.d.ts +0 -38
@@ -0,0 +1,127 @@
1
+ // M13 piece 6 (docs/wiki/the-module-ladder.md, M13 item 8; mock docs/product/m13-setup-mock.html Part 3, variant B): the Result tab's ONE grid for a job.
2
+ // Rows are the job's runs; the four buckets (Needs you / Stopped / Passed / Skipped) are fold rows; columns are `every step: exists, done`, `output judged`,
3
+ // cost and time. Pure of the panel: the run lookups are injected (data.js `getJobGrid`). Nothing is written.
4
+ //
5
+ // ONE decider of a run's bucket: `bucketOf` below reads the run's glyph (`computeGlyph`) through the M12 map in tickets.js (`GROUP_OF`); this module has no second
6
+ // outcome reader. What it throws away: any diary field but a check's `n`, `text`, `ok`, `result` and `source`; a run's money is only the history row's total, or the
7
+ // priced spend rows when the run has no history row yet.
8
+ import { GROUP_OF, TICKET_GROUPS } from './tickets.js';
9
+ import { EVERY_STEP } from '../try-checks.js';
10
+ import { compareNatural } from '../natural.js';
11
+
12
+ /** the buckets, in the mock's order (the same four as the M12 ticket list: one list of words) */
13
+ export const GRID_BUCKETS = TICKET_GROUPS;
14
+
15
+ /** @param {string} glyph @returns {'wait'|'stop'|'done'|'skip'} */
16
+ export const bucketOf = (glyph) => /** @type {any} */ (GROUP_OF[glyph] ?? 'stop');
17
+
18
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
19
+
20
+ /** a figure in dollars: `$0` for an exact zero, `$0.0412`, or `at least $0.0412` when the figure is only a floor (never `$0` for unknown) @param {number} usd @param {boolean} complete */
21
+ export function moneyWords(usd, complete) {
22
+ const body = complete && usd === 0 ? '$0' : `$${usd.toFixed(4)}`;
23
+ return complete ? body : `at least ${body}`;
24
+ }
25
+
26
+ /**
27
+ * One run's money: its history row's total when it has one (complete unless the row says the figure is a floor), else the priced spend rows (always a floor), else unknown.
28
+ * @param {{spentUsd?: unknown, spendComplete?: unknown}|null} history @param {any[]} spendRows
29
+ * @returns {{usd: number|null, complete: boolean}}
30
+ */
31
+ export function runMoney(history, spendRows) {
32
+ if (history && isNum(history.spentUsd)) return { usd: /** @type {number} */ (history.spentUsd), complete: history.spendComplete !== false };
33
+ const priced = (spendRows ?? []).filter((r) => isNum(r?.costUsd));
34
+ return priced.length === 0 ? { usd: null, complete: false } : { usd: priced.reduce((a, r) => a + r.costUsd, 0), complete: false };
35
+ }
36
+
37
+ /** the stats line's money: the sum of the runs' money, a floor when any run's is a floor or unknown; `null` usd = nothing is known @param {Array<{usd: number|null, complete: boolean}>} moneys */
38
+ export function sumMoney(moneys) {
39
+ const known = moneys.filter((m) => m.usd !== null);
40
+ return { usd: known.length === 0 ? null : known.reduce((a, m) => a + (m.usd ?? 0), 0), complete: moneys.every((m) => m.usd !== null && m.complete) };
41
+ }
42
+
43
+ /**
44
+ * The newest try of each step in the run's check record (`diary.jsonl` kind checks), in step order.
45
+ * @param {any[]} diary @returns {Array<{step: string, checks: Array<{n: number, text: string, ok: boolean, result: string|null, source: string|null}>}>}
46
+ */
47
+ function newestTries(diary) {
48
+ const by = new Map();
49
+ for (const r of diary ?? []) {
50
+ if (!r || typeof r.step !== 'string' || !Number.isInteger(r.try) || !Array.isArray(r.checks)) continue;
51
+ const prev = by.get(r.step);
52
+ if (!prev || r.try >= prev.try) by.set(r.step, r);
53
+ }
54
+ return [...by.values()].map((r) => ({
55
+ step: r.step,
56
+ checks: r.checks.filter((c) => c && typeof c.text === 'string' && typeof c.ok === 'boolean')
57
+ .map((c) => ({ n: c.n, text: c.text, ok: c.ok, result: typeof c.result === 'string' ? c.result : null, source: typeof c.source === 'string' ? c.source : null })),
58
+ }));
59
+ }
60
+
61
+ /**
62
+ * The two check columns of one run, from the run's own check record (the Audit grid's rows, by the same identities: #1 and #2 are `every step`, #3 and up are the
63
+ * close's checks, `try-checks.js`). `g` passed, `r` failed, `n` nothing ran or only a human's yes judged it (a human's yes is not a check), `none` steps ran but the job has no output check at all (only #1 and #2), `q` no verdict (the run ended
64
+ * red and its record holds no check at all). Also the detail lines the row opens to.
65
+ * @param {{diary: any[], steps: any[], ended: boolean, red: boolean, skipped: boolean}} a
66
+ * @returns {{ex: 'g'|'r'|'n'|'q', oj: 'g'|'r'|'n'|'none'|'q', lines: string[]}}
67
+ */
68
+ export function checkCells({ diary, steps, ended, red, skipped }) {
69
+ if (skipped) return { ex: 'n', oj: 'n', lines: [] };
70
+ const tries = newestTries(diary);
71
+ if (tries.length === 0) { const v = ended && red ? 'q' : 'n'; return { ex: v, oj: v, lines: [] }; }
72
+ const lines = [];
73
+ let exBad = false;
74
+ let ojBad = false;
75
+ let ojAny = false;
76
+ for (const t of tries) {
77
+ const at = (steps ?? []).findIndex((s) => s?.emits === t.step);
78
+ const goal = at >= 0 && typeof steps[at].goal === 'string' ? steps[at].goal.replace(/[\s,.;:]+$/, '') : t.step;
79
+ const name = `step ${at >= 0 ? at + 1 : '?'} ${goal}`;
80
+ const every = t.checks.filter((c) => c.source === EVERY_STEP || c.n === 1 || c.n === 2);
81
+ const closes = t.checks.filter((c) => !every.includes(c));
82
+ const badEvery = every.find((c) => !c.ok);
83
+ if (badEvery) { exBad = true; lines.push(`${name}: ${badEvery.text}${badEvery.result ? ` (${badEvery.result})` : ''}`); } else lines.push(`${name}: exists, done`);
84
+ for (const c of closes) {
85
+ ojAny = true;
86
+ if (!c.ok) ojBad = true;
87
+ lines.push(`output judged: ${c.text}${c.result ? ` (${c.result})` : ''}${c.ok ? '' : ' - failed'}`);
88
+ }
89
+ }
90
+ return { ex: exBad ? 'r' : 'g', oj: ojBad ? 'r' : (ojAny ? 'g' : 'none'), lines };
91
+ }
92
+
93
+ /**
94
+ * The grid of one job: every run a row in its bucket, newest first inside each bucket, and the stats line's numbers.
95
+ * @param {{runs: Array<{runId: string, glyph: string, ticket: number|null, title?: string|null, unsure?: boolean, at: number|null, history: any, spendRows: any[], diary: any[], steps: any[], reason: string|null}>, anyway?: {runId: string, numbers: Set<number>}|null, now?: number}} a
96
+ */
97
+ export function buildJobGrid({ runs, anyway = null, now = Date.now() }) {
98
+ const rows = runs.map((r) => {
99
+ const bucket = bucketOf(r.glyph);
100
+ const money = runMoney(r.history, r.spendRows);
101
+ const cells = checkCells({ diary: r.diary, steps: r.steps, ended: r.history !== null, red: bucket === 'stop', skipped: bucket === 'skip' });
102
+ const wall = r.history && isNum(r.history.wallMs) ? r.history.wallMs : null;
103
+ const lines = [...cells.lines];
104
+ if (money.usd === null) lines.push('cost unknown, not shown as $0');
105
+ return {
106
+ unsure: r.unsure === true, runId: r.runId, name: r.ticket !== null ? `#${r.ticket}` : r.runId, title: r.ticket !== null && typeof r.title === 'string' ? r.title : null, number: r.ticket, bucket, glyph: r.glyph, at: r.at ?? now,
107
+ ex: cells.ex, oj: cells.oj,
108
+ cost: { mark: money.usd !== null && money.complete ? 'g' : 'q', value: money.usd === null ? '—' : moneyWords(money.usd, money.complete) },
109
+ time: { mark: bucket === 'skip' ? 'n' : (wall !== null ? 'g' : 'q'), value: wall }, // value: ms, or null = unknown
110
+ reason: bucket === 'skip' ? r.reason : null,
111
+ anyway: bucket === 'skip' && r.ticket !== null && anyway !== null && anyway.numbers.has(r.ticket),
112
+ lines, money,
113
+ };
114
+ });
115
+ const order = (a, b) => b.at - a.at || compareNatural(b.runId, a.runId);
116
+ const groups = GRID_BUCKETS.map((g) => ({ ...g, rows: rows.filter((r) => r.bucket === g.key).sort(order).map(({ money, ...row }) => row) }));
117
+ const total = sumMoney(rows.map((r) => r.money));
118
+ return {
119
+ groups,
120
+ anywayRunId: anyway ? anyway.runId : null,
121
+ stats: {
122
+ counts: Object.fromEntries(groups.map((g) => [g.key, g.rows.length])),
123
+ spent: total.usd === null ? null : moneyWords(total.usd, total.complete),
124
+ spentUsd: total.usd, spentComplete: total.complete,
125
+ },
126
+ };
127
+ }
@@ -15,7 +15,8 @@ import { readFileInside } from '../flow.js';
15
15
  import { isCellsPath } from '../closers.js';
16
16
  import { readAcceptedHashesByEmits } from '../ask.js';
17
17
  import { NOT_CHECKED_LABEL } from '../checked.js';
18
- import { checkSendDestination } from '../runner.js';
18
+ import { checkSendDestination, readArtifactResult } from '../runner.js';
19
+ import { flowTypeOf } from '../declaration.js';
19
20
  import { isAgree, readingOfQuestion } from '../pageask.js';
20
21
  import { lineRules } from '../pagebits.js';
21
22
  import { readLineSection, LINE_CHECKS_FILE } from '../line-checks.js';
@@ -49,6 +50,15 @@ export function isResultRun(arbiter) {
49
50
  return sources.some((s) => s && (s.kind === 'page' || (isStr(s.path) && (isCellsPath(s.path) || s.path.toLowerCase().endsWith('.docx')))));
50
51
  }
51
52
 
53
+ /**
54
+ * M15 item 1: the ONE decider of the Result tab and of its cards. Every job has it; a Tickets MCP job keeps what it had (M13 am2: the grid, and M10's cards only when
55
+ * it reads a page, a CSV or a .docx). Read off the signed declaration and arbiter.
56
+ * @param {any} arbiter @param {any} declaration @returns {boolean}
57
+ */
58
+ export function hasResultCards(arbiter, declaration) {
59
+ return flowTypeOf(declaration) === 'tickets' ? isResultRun(arbiter) : true;
60
+ }
61
+
52
62
  /** The run's check type: its distinct close classes, in step order (`hitl + softgreen`). `—` for a declaration with none.
53
63
  * @param {any} declaration @returns {string} */
54
64
  export function checkTypeOf(declaration) {
@@ -166,9 +176,9 @@ export function readDelivered(rec) {
166
176
  }
167
177
 
168
178
  /**
169
- * The files this run's signed sends wrote: for each signed send whose send step ended green in the audit, the file `<flow>-<runId>-<emits>.json`
170
- * in the signed folder, with the sha256 the human's accept recorded for the ask that send reads (`readAcceptedHashesByEmits`, the same record the
171
- * send itself checked). No accepted hash = recorded as null, which reads as "changed", never as ok.
179
+ * The files this run's signed sends wrote: for each signed send whose send step ended green in the audit, the file `<flow>-<runId>-<emits>.md`
180
+ * in the signed folder with the sha256 the send recorded for it (M15), or, for a send older than M15, `.json` with the sha256 the human's accept recorded for the ask that
181
+ * send reads (`readAcceptedHashesByEmits`, the same record the send itself checked). No accepted hash = recorded as null, which reads as "changed", never as ok.
172
182
  * @returns {{path: string, dir: string|null, name: string, sha256: string|null}[]}
173
183
  */
174
184
  export function deliveredOf({
@@ -181,13 +191,16 @@ export function deliveredOf({
181
191
  const out = [];
182
192
  for (const send of arbiter?.sends ?? []) {
183
193
  const step = steps.find((s) => s.fromLine === send.line);
184
- if (!step || !auditRows.some((r) => r.step === step.emits && r.verdict === 'green')) continue; // eslint-disable-line no-continue
185
- const name = `${flow}-${runId}-${step.emits}.json`;
194
+ const sentRow = step ? auditRows.findLast((r) => r.step === step.emits && r.verdict === 'green') : undefined;
195
+ if (!step || !sentRow) continue; // eslint-disable-line no-continue
196
+ // M15 item 4: a send since M15 wrote `<emits>.md` and recorded that file's own sha256 on its green audit row; an older send wrote the JSON, bound to the accept's hash
197
+ const plain = isStr(sentRow.sentSha256) && sentRow.sentSha256 !== '';
198
+ const name = `${flow}-${runId}-${step.emits}.${plain ? 'md' : 'json'}`;
186
199
  const dest = checkSendDestination(`${send.target.kind}:${send.target.path}`, { root, runDir });
187
200
  const [askId] = (step.reads ?? []).filter((id) => askEmits.has(id));
188
201
  out.push({
189
202
  path: join(dest.ok ? dest.dir : send.target.path, name), dir: dest.ok ? dest.dir : null, name,
190
- sha256: hashes.ok && askId !== undefined ? (hashes.byEmits.get(askId) ?? null) : null,
203
+ sha256: plain ? sentRow.sentSha256 : (hashes.ok && askId !== undefined ? (hashes.byEmits.get(askId) ?? null) : null),
191
204
  });
192
205
  }
193
206
  return out;
@@ -242,6 +255,14 @@ export function buildResult({
242
255
  checks: checksOfLine((declaration?.steps ?? []).filter((st) => st.fromLine === l.n), diary),
243
256
  sheet: sheetBlocks.find((b) => b.line === l.n) ?? null,
244
257
  };
258
+ // M15 item 2: a line whose step wrote text (no facts) shows that text, from the step's own artifact (`{text}`); a sheet line keeps its block
259
+ if (!c && out.sheet === null) {
260
+ const written = (declaration?.steps ?? []).filter((st) => st.fromLine === l.n).map((st) => {
261
+ const a = readArtifactResult(runDir, st.emits);
262
+ return a.ok && isStr(a.value?.text) && a.value.text !== '' ? a.value.text : null;
263
+ }).filter((x) => x !== null);
264
+ if (written.length > 0) out.answer = written.join('\n\n');
265
+ }
245
266
  if (c) {
246
267
  out.source = c.source;
247
268
  out.page = urls.get(c.source) ?? null;
@@ -91,10 +91,15 @@ export function createScheduler(opts) {
91
91
  const { sig, trigger } = job;
92
92
  const first = !hasBaseline(ledger, sig);
93
93
  const watch = Array.isArray(trigger.watch) ? trigger.watch : [];
94
+ // M13 piece 5 (F114f): the turn-on wrote the ticket number the first green run read; the first look baselines only tickets up to it
95
+ const armedRow = first ? readRows(ledger, sig).find((r) => r.kind === 'armed') : undefined;
96
+ const cut = Number.isInteger(armedRow?.ticketN) ? armedRow?.ticketN : undefined;
94
97
  const out = Promise.resolve(look({
95
98
  listUrl: trigger.list, mcp: { server: trigger.server, tool: trigger.tool }, ...(mcpConfig ? { configPath: mcpConfig } : {}),
96
- seen: first ? null : seenNumbers(ledger, sig), last: first ? new Map() : lastSeen(ledger, sig), watch,
97
- })).then((r) => { recordLook(ledger, sig, r, now()); }, (e) => { recordLook(ledger, sig, { ok: false, error: String(e?.message ?? e) }, now()); })
99
+ seen: first ? null : seenNumbers(ledger, sig), last: first ? new Map() : lastSeen(ledger, sig), watch, ...(cut === undefined ? {} : { cut }),
100
+ })).catch((e) => ({ ok: /** @type {const} */ (false), error: String(e?.message ?? e) }))
101
+ // M13 item 9.3: a save that throws (ledger path unwritable, disk full) is told once as a refusal and never leaves the look's promise rejected, so the panel stays up
102
+ .then((r) => { try { recordLook(ledger, sig, r, now()); } catch (e) { try { door.refuse(job, `ticket look: its result could not be saved: ${String(/** @type {any} */ (e)?.message ?? e).split('\n')[0]}`); } catch { /* telling is best effort */ } } })
98
103
  .finally(() => { /** @type {any} */ (st).out = null; });
99
104
  st.out = out;
100
105
  }
@@ -103,6 +108,7 @@ export function createScheduler(opts) {
103
108
  const nowMs = now();
104
109
  const live = new Set();
105
110
  try { door.retireStale(); } catch { /* one job's files never stop the others; tried again next tick */ }
111
+ try { door.armWaiting?.(); } catch { /* M13 piece 5: a schedule signed with the job turns on after its first green run; tried again next tick */ }
106
112
  for (const job of door.scan()) {
107
113
  const { sig } = job;
108
114
  const key = `${job.flow}|${sig}`;
@@ -60,7 +60,7 @@ import { resolveRunDir } from '../flow.js';
60
60
  import { readAsk, requestStop, stopParkedRun } from '../runner.js';
61
61
  import { removeFromNeedsYou } from './needsyou.js';
62
62
  import {
63
- listRuns, listScheduled, summarizeJobs, RUNS_LIST_LIMITS, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, getRunResult, getTicketList, getRunDownload, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
63
+ listRuns, listScheduled, summarizeJobs, RUNS_LIST_LIMITS, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, getRunResult, getJobGrid, getTicketList, getRunDownload, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
64
64
  } from './data.js';
65
65
  import { ticketAnyway, arriveAnywayOf } from './tickets.js';
66
66
  import { createResumer } from './resume.js';
@@ -68,6 +68,7 @@ import { createScheduler } from './scheduler.js';
68
68
  import { createAuthor } from './author.js';
69
69
  import { keysForDoor } from '../keysfile.js';
70
70
  import { configDoorHome } from '../config.js';
71
+ import { newestMcpChecks } from '../mcp-checks.js';
71
72
  import { createSettings } from './settings.js';
72
73
  import { removeOldLock } from './lock.js';
73
74
 
@@ -391,7 +392,7 @@ function ticketAnywayRoute(res, body, opts) {
391
392
  * real listening socket where that is simpler.
392
393
  * @param {import('node:http').IncomingMessage} req
393
394
  * @param {import('node:http').ServerResponse} res
394
- * @param {{ root: string, port: number, version?: string|null, startedAt?: string, packagePath?: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor>, now?: () => number, ticketQueue: {arriveAnyway: Function} }} opts
395
+ * @param {{ root: string, port: number, checksHome: { skip: boolean, home: string|undefined }, version?: string|null, startedAt?: string, packagePath?: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor>, now?: () => number, ticketQueue: {arriveAnyway: Function} }} opts
395
396
  */
396
397
  export function handleRequest(req, res, opts) {
397
398
  const method = req.method ?? 'GET';
@@ -574,8 +575,8 @@ export function handleRequest(req, res, opts) {
574
575
  return;
575
576
  }
576
577
 
577
- // /api/runs/:flow/:runId(/audit|/job|/asks|/result|/download)?
578
- const runMatch = /^\/api\/runs\/([^/]+)\/([^/]+)(\/(audit|job|asks|result|download))?$/.exec(pathname);
578
+ // /api/runs/:flow/:runId(/audit|/job|/asks|/result|/grid|/download)?
579
+ const runMatch = /^\/api\/runs\/([^/]+)\/([^/]+)(\/(audit|job|asks|result|grid|download))?$/.exec(pathname);
579
580
  if (runMatch) {
580
581
  let flow;
581
582
  let runId;
@@ -604,6 +605,7 @@ export function handleRequest(req, res, opts) {
604
605
  if (sub === 'job') {
605
606
  const result = getRunJob({
606
607
  root: opts.root, flow, runId, catalogue, scheduleRead: (f) => opts.author?.trigger?.facts(f) ?? null,
608
+ mcpChecks: () => (opts.checksHome.skip ? new Map() : newestMcpChecks(opts.checksHome.home)),
607
609
  });
608
610
  if (!result) { sendText(res, 404, 'no such run'); return; }
609
611
  send(200, result);
@@ -625,6 +627,13 @@ export function handleRequest(req, res, opts) {
625
627
  send(200, result);
626
628
  return;
627
629
  }
630
+ if (sub === 'grid') {
631
+ // M13 piece 6 (item 8): the job's one Result grid (every run of the flow); the run in the URL only names the flow's run the person is looking at
632
+ const result = getJobGrid({ root: opts.root, flow, catalogue, now: opts.now });
633
+ if (!result) { sendText(res, 404, 'no such job'); return; }
634
+ send(200, result);
635
+ return;
636
+ }
628
637
  if (sub === 'download') {
629
638
  const got = getRunDownload({
630
639
  root: opts.root, flow, runId, catalogue, index: url.searchParams.get('i'),
@@ -635,7 +644,8 @@ export function handleRequest(req, res, opts) {
635
644
  res.writeHead(200, {
636
645
  'content-type': `${got.type}; charset=utf-8`,
637
646
  'content-length': got.buf.length,
638
- 'content-disposition': `attachment; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(got.name)}`,
647
+ // M15 item 5: `?view=1` (the top card's file link) opens the saved file in the tab; its type is text/plain or a download type, nosniff stays
648
+ 'content-disposition': `${url.searchParams.get('view') === '1' && /^(text\/plain|text\/csv|application\/json)$/.test(got.type) ? 'inline' : 'attachment'}; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(got.name)}`,
639
649
  'x-content-type-options': 'nosniff',
640
650
  });
641
651
  if (method === 'HEAD') res.end(); else res.end(got.buf);
@@ -724,7 +734,7 @@ export function createPanelServer(opts) {
724
734
  // Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
725
735
  // process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
726
736
  const settings = createSettings({
727
- home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now, openFolderSpawn: opts.settings?.openFolderSpawn, platform: opts.settings?.platform,
737
+ root, home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now, openFolderSpawn: opts.settings?.openFolderSpawn, platform: opts.settings?.platform,
728
738
  });
729
739
  return new Promise((resolve, reject) => {
730
740
  // Bound port is resolved from the live socket (`server.address().port`)
@@ -736,7 +746,7 @@ export function createPanelServer(opts) {
736
746
  const server = createServer((req, res) => {
737
747
  try {
738
748
  handleRequest(req, res, {
739
- root, port: boundPort, resumer, settings, author, version, startedAt, packagePath: opts.packagePath, now: opts.author?.now, ticketQueue: /** @type {any} */ (opts.ticketQueue) ?? arriveAnywayOf({ scan: () => author.trigger.scan(), now: opts.author?.now ?? Date.now }),
749
+ root, port: boundPort, resumer, settings, checksHome: { skip: opts.settings?.home === undefined && door.skip, home: opts.settings?.home ?? door.home }, author, version, startedAt, packagePath: opts.packagePath, now: opts.author?.now, ticketQueue: /** @type {any} */ (opts.ticketQueue) ?? arriveAnywayOf({ scan: () => author.trigger.scan(), startAnyway: (a) => author.trigger.startAnyway(a), now: opts.author?.now ?? Date.now }),
740
750
  });
741
751
  } catch (e) {
742
752
  sendText(res, 500, 'internal error');
@@ -24,16 +24,23 @@ import { spendSummary } from '../monthly.js';
24
24
  import { openInOs } from '../opener.js';
25
25
  import { dirname } from 'node:path';
26
26
  import { homedir } from 'node:os';
27
+ import { listServerTools } from 'bare-agent/mcp';
28
+ import { mcpPathProblem } from '../config.js';
29
+ import { appendMcpCheck, newestMcpChecks } from '../mcp-checks.js';
30
+ import { mcpSources, expandMcpPath, DEFAULT_MCP_PLACES } from '../mcp-sources.js';
31
+ import { countMcpUse } from '../mcp-use.js';
32
+ import { mcpStartOpts } from '../ticket-mcp.js';
27
33
 
28
34
  const TIMEOUT_MS = 4000;
35
+ const MCP_CHECK_MS = 15000;
29
36
 
30
37
  const BROKEN_CONFIG = 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.';
31
38
 
32
39
  const isNumberAbove0 = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
33
40
 
34
41
  /**
35
- * @param {{ home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string }} cfg
36
- * `home` the config home (undefined = the real `~/.config/fwdloop`); `skip` true under a test process
42
+ * @param {{ root?: string, home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string }} cfg
43
+ * `root` the jobs folder (the MCP use counts read its runs); `home` the config home (undefined = the real `~/.config/fwdloop`); `skip` true under a test process
37
44
  * with no `FWDLOOP_CONFIG_HOME` (Settings then touches nothing); `env` the shell side (tests only);
38
45
  * `fetch` and `now` are test seams.
39
46
  */
@@ -56,7 +63,7 @@ export function createSettings(cfg) {
56
63
  /** The row named by a request, or null: only a key that is in the keys file (or the shell) is a row. @param {any} slot */
57
64
  const slotOf = (slot) => (rowNames(keys()).includes(slot) ? slot : null);
58
65
 
59
- /** config.json, or `{problem}` in plain words when it is broken (never read as "nothing set"). */
66
+ /** config.json, or `{problem}` in plain words when it is broken (never read as "nothing set"). @returns {{ config: Record<string, any>, problem: string|null }} */
60
67
  function config() {
61
68
  try { return { config: readConfig({ home: cfg.home }), problem: null }; } catch (e) {
62
69
  if (!(e instanceof ConfigError)) throw e;
@@ -290,18 +297,126 @@ export function createSettings(cfg) {
290
297
  return reply(200, { ok: true, monthlyLimitUsd: clear ? null : raw });
291
298
  }
292
299
 
300
+ // ---- M13 piece 3: Settings > MCP. Reads the MCP config files (never writes them) and shows names, flags and counts only: no command, args, env or key.
301
+ /** @type {Set<string>} */
302
+ const checking = new Set();
303
+ /** a tool hint as the page shows it: only `readOnlyHint: true` is a hint; anything else is "no hint" (null) @param {any} a */
304
+ const hintOf = (a) => (a?.readOnlyHint === true ? 'read-only' : null);
305
+
306
+ function mcpGet() {
307
+ const src = mcpSources({ home: cfg.home });
308
+ const names = [...new Set(src.places.flatMap((p) => p.servers.map((x) => x.name)))];
309
+ const use = cfg.root ? countMcpUse(cfg.root, names) : new Map();
310
+ const checks = newestMcpChecks(cfg.home);
311
+ const places = src.places.map((p) => ({
312
+ path: p.path,
313
+ added: p.added,
314
+ status: p.status,
315
+ servers: p.servers.map((x) => {
316
+ const u = use.get(x.name);
317
+ const c = x.remote || x.shadowedBy !== null ? null : checks.get(`${p.path}\t${x.name}`) ?? null;
318
+ return {
319
+ name: x.name,
320
+ remote: x.remote,
321
+ shadowedBy: x.shadowedBy,
322
+ check: c === null ? null : (c.ok === true && Array.isArray(c.tools)
323
+ ? { at: c.at, ok: true, tools: c.tools.map((/** @type {any} */ t) => ({ name: String(t?.name), hint: t?.hint === 'read-only' ? 'read-only' : null })) }
324
+ : { at: c.at, ok: false, error: typeof c.error === 'string' ? c.error : 'The check failed.' }),
325
+ use: x.remote || x.shadowedBy !== null || !u ? null : { calls: u.calls, runs: u.runs, last: u.last, denied: u.denied, tools: Object.fromEntries(u.tools) },
326
+ };
327
+ }),
328
+ }));
329
+ return reply(200, { ok: true, problem: src.problem, places });
330
+ }
331
+
332
+ /** the plain sentence for a failed `check tools`; the library's own message can hold the start command, so it is never passed on @param {any} e */
333
+ function checkFailure(e) {
334
+ if (e?.context?.timeout === true) return 'The server did not answer in time.';
335
+ if (e?.context?.spawnError === true) return 'The server did not start.';
336
+ if (e?.context?.notFound === true) return 'The server is not in the list any more.';
337
+ return 'The check failed.';
338
+ }
339
+
340
+ /** The one place a press starts a server: ONLY from this POST (never a page load or a GET), that one server, once, with the same start options as a run. */
341
+ async function mcpCheck(body) {
342
+ const server = body?.server;
343
+ if (typeof server !== 'string' || server === '') return refuse('bad-server', 'Pick an MCP to check. Nothing was started.');
344
+ const place = mcpSources({ home: cfg.home }).places.find((p) => p.servers.some((x) => x.name === server));
345
+ const row = place?.servers.find((x) => x.name === server);
346
+ if (!place || !row) return refuse('unknown-mcp', 'That MCP is not in the list. Nothing was started.');
347
+ if (row.remote) return refuse('remote-mcp', 'A remote server is not supported yet. Nothing was started.');
348
+ if (row.shadowedBy !== null) return refuse('shadowed-mcp', 'An earlier path has an MCP with this name, so this one is not used. Nothing was started.');
349
+ if (checking.has(server)) return refuse('already-checking', 'That MCP is being checked right now.', 409);
350
+ checking.add(server);
351
+ const line = { server, path: place.path, at: new Date(cfg.now ? cfg.now() : Date.now()).toISOString() };
352
+ try {
353
+ let entry;
354
+ try {
355
+ const tools = await listServerTools({ server, configPaths: [place.file], ...mcpStartOpts(), confirmServer: () => true, timeout: MCP_CHECK_MS });
356
+ entry = { ...line, ok: true, tools: tools.map((t) => ({ name: t.name, hint: hintOf(t.annotations) })) };
357
+ } catch (e) {
358
+ entry = { ...line, ok: false, error: checkFailure(e) };
359
+ }
360
+ try {
361
+ appendMcpCheck(cfg.home, entry);
362
+ } catch {
363
+ return refuse('log-failed', 'The check ran but its result could not be saved.', 500);
364
+ }
365
+ return reply(200, { ok: true, checked: entry.ok });
366
+ } finally {
367
+ checking.delete(server);
368
+ }
369
+ }
370
+
371
+ function mcpPathAdd(body) {
372
+ const typed = typeof body?.path === 'string' ? body.path.trim() : body?.path;
373
+ const why = mcpPathProblem(typed);
374
+ if (why) return refuse('bad-path', `The path ${why}. Nothing was saved.`);
375
+ const c = config();
376
+ if (c.problem) return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
377
+ const list = Array.isArray(c.config.mcpPaths) ? c.config.mcpPaths : [];
378
+ const same = (/** @type {string} */ a) => expandMcpPath(a) === expandMcpPath(typed);
379
+ if (DEFAULT_MCP_PLACES().some(same) || list.some(same)) return refuse('path-listed', 'That path is already in the list. Nothing was saved.');
380
+ try {
381
+ updateConfig({ mcpPaths: [...list, typed] }, { home: cfg.home });
382
+ } catch (e) {
383
+ if (!(e instanceof ConfigError)) throw e;
384
+ return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
385
+ }
386
+ return reply(200, { ok: true, path: typed });
387
+ }
388
+
389
+ function mcpPathRemove(body) {
390
+ const c = config();
391
+ if (c.problem) return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
392
+ const list = Array.isArray(c.config.mcpPaths) ? c.config.mcpPaths : [];
393
+ if (typeof body?.path !== 'string' || !list.includes(body.path)) return refuse('path-unknown', 'That path is not one you added. Nothing was changed.');
394
+ const next = list.filter((/** @type {string} */ p) => p !== body.path);
395
+ try {
396
+ updateConfig({ mcpPaths: next.length ? next : null }, { home: cfg.home });
397
+ } catch (e) {
398
+ if (!(e instanceof ConfigError)) throw e;
399
+ return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
400
+ }
401
+ return reply(200, { ok: true });
402
+ }
403
+
293
404
  /**
294
405
  * @param {{ method: string, pathname: string, query: URLSearchParams, body: any }} r
295
406
  * @returns {Promise<{ status: number, body: any }>}
296
407
  */
297
408
  async function handle({ method, pathname, query, body }) {
298
409
  if (cfg.skip) return refuse('settings-unavailable', 'Settings is not available here.', 404);
299
- const known = { GET: ['/api/settings/providers', '/api/settings/money'], POST: ['/api/settings/open-keys-folder', '/api/settings/test', '/api/settings/models', '/api/settings/model', '/api/settings/provider', '/api/settings/money'] };
410
+ const known = { GET: ['/api/settings/providers', '/api/settings/money', '/api/settings/mcp'], POST: ['/api/settings/mcp-check', '/api/settings/mcp-path', '/api/settings/mcp-path-remove', '/api/settings/open-keys-folder', '/api/settings/test', '/api/settings/models', '/api/settings/model', '/api/settings/provider', '/api/settings/money'] };
300
411
  if (!(known[method] ?? []).includes(pathname)) return refuse('no-such-settings-route', 'Settings cannot do that. Keys are typed into your keys file by hand.', 404);
301
412
  if (method === 'GET') {
302
413
  if (pathname === '/api/settings/providers') return providers();
414
+ if (pathname === '/api/settings/mcp') return mcpGet();
303
415
  return moneyGet();
304
416
  }
417
+ if (pathname === '/api/settings/mcp-check') return mcpCheck(body);
418
+ if (pathname === '/api/settings/mcp-path') return mcpPathAdd(body);
419
+ if (pathname === '/api/settings/mcp-path-remove') return mcpPathRemove(body);
305
420
  if (pathname === '/api/settings/open-keys-folder') return openKeysFolder(body);
306
421
  if (pathname === '/api/settings/test') return test(body);
307
422
  if (pathname === '/api/settings/models') return models(body);
@@ -6,8 +6,10 @@ import { join } from 'node:path';
6
6
 
7
7
  import { readSchedule, ledgerOf } from '../schedule.js';
8
8
  import { readSeen } from '../trigger-files.js';
9
+ import { compareNatural } from '../natural.js';
9
10
  import { readRunInputs } from '../runfile.js';
10
11
  import { recordAnyway } from '../trigger-tickets.js';
12
+ import { isTicketNumber, TICKET_NUMBER_WORDS } from '../ticket-shape.js';
11
13
 
12
14
  /** the four groups, in the mockup's order: key, label, open at first. The page draws them; it types none of these words. */
13
15
  export const TICKET_GROUPS = Object.freeze([
@@ -18,7 +20,7 @@ export const TICKET_GROUPS = Object.freeze([
18
20
  ]);
19
21
 
20
22
  /** a run's sign -> its group. Running / stuck / expired / waiting all need a person or are still going: Needs you. */
21
- const GROUP_OF = Object.freeze({
23
+ export const GROUP_OF = Object.freeze({
22
24
  '[·]': 'wait', '[▶]': 'wait', '[II]': 'wait', '[!]': 'wait', '[✓]': 'done', '[–]': 'skip', '[✗]': 'stop', '[■]': 'stop', '[?]': 'stop',
23
25
  });
24
26
 
@@ -63,7 +65,7 @@ export function ticketListOf({ flowDir, runId, runIdsOf, glyphOf, atOf = () => n
63
65
  changed: arr && arr.count > 1 ? arr.reason : null,
64
66
  };
65
67
  const prior = byNumber.get(n);
66
- if (!prior || Number(id.replace(/\D/g, '')) > Number(prior.runId.replace(/\D/g, ''))) byNumber.set(n, row);
68
+ if (!prior || compareNatural(id, prior.runId) > 0) byNumber.set(n, row);
67
69
  }
68
70
  const rows = [...byNumber.values()].sort((a, b) => b.at - a.at || b.number - a.number);
69
71
  return {
@@ -79,7 +81,7 @@ export const ANYWAY_REASON_MAX = 500;
79
81
  /**
80
82
  * `POST /api/author/ticket-anyway`: queue a SKIPPED ticket as a new arrival, after a short reason. Without a reason nothing starts. The queue is the schedule builder's:
81
83
  * `queue.arriveAnyway({flow, number, reason})` is the ONE seam (production: `arriveAnywayOf`).
82
- * @param {{body: any, listOf: (flow: string, runId: string) => ReturnType<typeof ticketListOf>, queue: {arriveAnyway: (a: {flow: string, runId: string, number: number, reason: string}) => {ok: boolean, say?: string}}}} a
84
+ * @param {{body: any, listOf: (flow: string, runId: string) => ReturnType<typeof ticketListOf>, queue: {arriveAnyway: (a: {flow: string, runId: string, number: number, reason: string}) => {ok: boolean, say?: string, started?: boolean}}}} a
83
85
  * @returns {{status: number, body: Record<string, any>}}
84
86
  */
85
87
  export function ticketAnyway({ body, listOf, queue }) {
@@ -87,25 +89,28 @@ export function ticketAnyway({ body, listOf, queue }) {
87
89
  const reason = typeof b.reason === 'string' ? b.reason.trim() : '';
88
90
  if (reason === '') return { status: 400, body: { ok: false, refused: 'reason-required', say: 'Please write a reason to run it anyway.' } };
89
91
  if (reason.length > ANYWAY_REASON_MAX) return { status: 400, body: { ok: false, refused: 'reason-too-long', say: `Keep the reason under ${ANYWAY_REASON_MAX} characters. Nothing started.` } };
90
- if (typeof b.flow !== 'string' || typeof b.runId !== 'string' || !Number.isInteger(b.number)) return { status: 400, body: { ok: false, refused: 'bad-request', say: 'Name the job, the run and the ticket number. Nothing started.' } };
92
+ if (typeof b.flow !== 'string' || typeof b.runId !== 'string' || !isTicketNumber(b.number)) return { status: 400, body: { ok: false, refused: 'bad-request', say: `Name the job, the run and the ticket number (${TICKET_NUMBER_WORDS}). Nothing started.` } };
91
93
  const list = listOf(b.flow, b.runId);
92
94
  const row = list?.groups.find((g) => g.key === 'skip')?.rows.find((r) => r.number === b.number);
93
95
  if (!row) return { status: 409, body: { ok: false, refused: 'not-skipped', say: `Ticket #${b.number} is not a skipped ticket of this list. Nothing started.` } };
94
96
  const r = queue.arriveAnyway({ flow: b.flow, runId: b.runId, number: b.number, reason });
95
97
  if (!r.ok) return { status: 409, body: { ok: false, refused: 'queue', say: r.say ?? 'The ticket was not queued. Nothing started.' } };
98
+ if (r.started === true) return { status: 202, body: { ok: true, started: true, number: b.number, say: r.say } }; // M13 am3: the schedule is off, so the run started at once
96
99
  return { status: 202, body: { ok: true, queued: true, number: b.number, say: `Ticket #${b.number} is queued; it runs when its turn comes.` } };
97
100
  }
98
101
 
99
102
  /**
100
103
  * The production queue seam: ONE `arrived` row (`recordAnyway`, the ledger's writer) in the job's schedule ledger, so the scheduler's queue starts the ticket as a new
101
104
  * arrival under the job's normal cap. A job with no live ticket schedule is refused by name, at $0, with nothing written.
102
- * @param {{scan: () => any[], now: () => number}} a
103
- * @returns {{arriveAnyway: (a: {flow: string, runId: string, number: number, reason: string}) => {ok: boolean, say?: string}}}
105
+ * M13 am3: a ticket schedule that is signed but OFF (`startAnyway`, the trigger door's one by-hand start) starts the ticket at once instead; it writes no row.
106
+ * @param {{scan: () => any[], now: () => number, startAnyway?: (a: {flow: string, number: number}) => {ok: boolean, say: string} | null}} a
107
+ * @returns {{arriveAnyway: (a: {flow: string, runId: string, number: number, reason: string}) => {ok: boolean, say?: string, started?: boolean}}}
104
108
  */
105
- export function arriveAnywayOf({ scan, now }) {
109
+ export function arriveAnywayOf({ scan, now, startAnyway }) {
106
110
  return {
107
111
  arriveAnyway({ flow, number, reason }) {
108
112
  const job = scan().find((j) => j.flow === flow && j.trigger?.kind === 'new-ticket');
113
+ if (!job && startAnyway) { const r = startAnyway({ flow, number }); if (r !== null) return { ok: r.ok, say: r.say, started: r.ok }; }
109
114
  if (!job) return { ok: false, say: `Job "${flow}" has no live ticket schedule, so Run it anyway has no queue to join. Nothing started.` };
110
115
  return recordAnyway(ledgerOf(job.flowDir), job.sig, { number, reason }, now());
111
116
  },