fwdloop 0.26.1 → 0.27.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 (50) hide show
  1. package/bin/fwdloop +23 -3
  2. package/package.json +3 -3
  3. package/src/authoring.js +10 -0
  4. package/src/canrun.js +20 -0
  5. package/src/declaration.js +98 -2
  6. package/src/drafter.js +23 -10
  7. package/src/launcher.js +3 -2
  8. package/src/learnstore.js +1 -1
  9. package/src/pageask.js +18 -2
  10. package/src/pagefetch.js +10 -5
  11. package/src/panel/author.js +18 -2
  12. package/src/panel/authorflows.js +9 -4
  13. package/src/panel/authorstart.js +10 -6
  14. package/src/panel/authortrigger.js +34 -10
  15. package/src/panel/data.js +39 -4
  16. package/src/panel/index.html +516 -60
  17. package/src/panel/scheduler.js +42 -6
  18. package/src/panel/server.js +21 -5
  19. package/src/panel/tickets.js +113 -0
  20. package/src/runner.js +51 -10
  21. package/src/schedule.js +5 -0
  22. package/src/summary-words.js +12 -4
  23. package/src/ticket-draft.js +87 -0
  24. package/src/ticket-labels.js +65 -0
  25. package/src/ticket-mcp.js +66 -0
  26. package/src/ticket-shape.js +24 -0
  27. package/src/trigger-files.js +1 -1
  28. package/src/trigger-line.js +2 -1
  29. package/src/trigger-tickets.js +209 -0
  30. package/types/canrun.d.ts +14 -0
  31. package/types/drafter.d.ts +186 -64
  32. package/types/pageask.d.ts +1 -0
  33. package/types/pagefetch.d.ts +6 -3
  34. package/types/panel/author.d.ts +8 -0
  35. package/types/panel/authorflows.d.ts +2 -0
  36. package/types/panel/authorstart.d.ts +3 -1
  37. package/types/panel/authortrigger.d.ts +11 -1
  38. package/types/panel/data.d.ts +22 -3
  39. package/types/panel/scheduler.d.ts +7 -2
  40. package/types/panel/server.d.ts +9 -2
  41. package/types/panel/tickets.d.ts +81 -0
  42. package/types/runner.d.ts +21 -3
  43. package/types/summary-words.d.ts +2 -1
  44. package/types/ticket-draft.d.ts +96 -0
  45. package/types/ticket-labels.d.ts +36 -0
  46. package/types/ticket-mcp.d.ts +40 -0
  47. package/types/ticket-shape.d.ts +25 -0
  48. package/types/trigger-files.d.ts +2 -0
  49. package/types/trigger-line.d.ts +7 -0
  50. package/types/trigger-tickets.d.ts +91 -0
@@ -19,14 +19,21 @@ import {
19
19
  createFileTrigger, queueOf, readSeen, recheck, recordArrived, recordDropped, recordRan,
20
20
  } from '../trigger-files.js';
21
21
  import { ledgerOf } from '../schedule.js';
22
+ import {
23
+ TICKET_LOOK_MS, hasBaseline, lastSeen, lookTickets, recordLook, seenNumbers,
24
+ } from '../trigger-tickets.js';
22
25
  import { readOutcomes } from './authortrigger.js';
23
26
 
24
27
  /**
25
- * @param {{ door: ReturnType<typeof import('./authortrigger.js').createTriggerDoor>, now?: () => number, intervalMs?: number }} opts
26
- * `intervalMs` 0 = no timer (a test drives `tick`).
28
+ * @param {{ door: ReturnType<typeof import('./authortrigger.js').createTriggerDoor>, now?: () => number, intervalMs?: number, look?: typeof lookTickets, mcpConfig?: string }} opts
29
+ * `intervalMs` 0 = no timer (a test drives `tick`). `look`/`mcpConfig`: M12 piece 2, the ticket look and the MCP config it reads (default: the person's own ~/.mcp.json).
27
30
  */
28
31
  export function createScheduler(opts) {
29
- const { door, now = Date.now, intervalMs = 500 } = opts;
32
+ const {
33
+ door, now = Date.now, intervalMs = 500, look = lookTickets, mcpConfig,
34
+ } = opts;
35
+ /** M12 piece 2: per ticket schedule, when it last looked and whether a look is out (a look is async; `tick` never waits for one). @type {Map<string, {at: number|null, out: Promise<void>|null}>} */
36
+ const lookers = new Map();
30
37
  /** @type {Map<string, ReturnType<typeof createFileTrigger>>} */
31
38
  const watchers = new Map();
32
39
  /** @type {Set<string>} refusals already written, so a folder that stays gone is told once, not every tick */
@@ -46,7 +53,8 @@ export function createScheduler(opts) {
46
53
  if (queue.length === 0) return;
47
54
  const key = (/** @type {string} */ sha, /** @type {Record<string, any>} */ r) => `${sha}|${r.outcome}|${r.why ?? ''}`; // a refusal is told once PER REASON; busy / monthly carry no `why`
48
55
  const spoken = new Set(readOutcomes(job.flowDir).filter((r) => typeof r.sha === 'string' && r.sig === sig).map((r) => key(r.sha, r)));
49
- const cause = (/** @type {any} */ q) => ({ kind: /** @type {'file'} */ ('file'), path: q.path, sha: q.sha });
56
+ const ticketJob = job.trigger.kind === 'new-ticket'; // M12 piece 2: a ticket has no file to look at again; it is its number
57
+ const cause = (/** @type {any} */ q) => (ticketJob ? { kind: /** @type {'ticket'} */ ('ticket'), number: q.number, sha: q.sha, role: job.trigger.role, list: job.trigger.list, ...(q.reason ? { why: q.reason } : {}), ...(q.anyway === true ? { anyway: true } : {}) } : { kind: /** @type {'file'} */ ('file'), path: q.path, sha: q.sha });
50
58
  const told = (/** @type {any} */ q) => (/** @type {Record<string, any>} */ row) => { const k = key(q.sha, row); const had = spoken.has(k); spoken.add(k); return had; };
51
59
  if (door.busy(job)) {
52
60
  for (const q of queue) door.fire(job, cause(q), { told: told(q) });
@@ -54,7 +62,7 @@ export function createScheduler(opts) {
54
62
  }
55
63
  while (queue.length > 0) {
56
64
  const q = queue[0];
57
- const seen = recheck(q);
65
+ const seen = ticketJob ? { state: /** @type {'ok'} */ ('ok'), path: q.path, sha: q.sha, size: 0 } : recheck(q);
58
66
  if (seen.state !== 'ok') {
59
67
  const why = seen.state === 'deleted' ? 'deleted' : 'changed';
60
68
  recordDropped(ledger, q, why, nowMs, sig);
@@ -69,6 +77,28 @@ export function createScheduler(opts) {
69
77
  }
70
78
  }
71
79
 
80
+ /**
81
+ * M12 piece 2 (items 5, 6, 7): when a ticket schedule's look is due (never looked, or 15 minutes since the last START of one) and none is out, start it. THE writer of the
82
+ * ticket rows is `recordLook`, called once the look settles: first look = baseline rows (nothing runs); later = one `arrived` row per new ticket or watched change;
83
+ * an unreadable list = one `unreadable` row with its cause, and the next look is a first look again while there is no baseline.
84
+ * @param {any} job @param {string} key @param {string} ledger @param {number} nowMs
85
+ */
86
+ function startLook(job, key, ledger, nowMs) {
87
+ let st = lookers.get(key);
88
+ if (!st) { st = { at: null, out: null }; lookers.set(key, st); }
89
+ if (st.out !== null || (st.at !== null && nowMs - st.at < TICKET_LOOK_MS)) return;
90
+ st.at = nowMs;
91
+ const { sig, trigger } = job;
92
+ const first = !hasBaseline(ledger, sig);
93
+ const watch = Array.isArray(trigger.watch) ? trigger.watch : [];
94
+ const out = Promise.resolve(look({
95
+ 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()); })
98
+ .finally(() => { /** @type {any} */ (st).out = null; });
99
+ st.out = out;
100
+ }
101
+
72
102
  function tick() {
73
103
  const nowMs = now();
74
104
  const live = new Set();
@@ -80,7 +110,10 @@ export function createScheduler(opts) {
80
110
  try {
81
111
  const ledger = ledgerOf(job.flowDir);
82
112
  const { trigger } = job;
83
- if (trigger.kind === 'file-updated' || trigger.kind === 'new-file') {
113
+ if (trigger.kind === 'new-ticket') {
114
+ startLook(job, key, ledger, nowMs);
115
+ runQueue(job, ledger, nowMs);
116
+ } else if (trigger.kind === 'file-updated' || trigger.kind === 'new-file') {
84
117
  let w = watchers.get(key);
85
118
  if (!w) {
86
119
  w = createFileTrigger({
@@ -107,10 +140,13 @@ export function createScheduler(opts) {
107
140
  }
108
141
  }
109
142
  for (const k of [...watchers.keys()]) if (!live.has(k)) watchers.delete(k);
143
+ for (const k of [...lookers.keys()]) if (!live.has(k)) lookers.delete(k);
110
144
  }
111
145
 
112
146
  return {
113
147
  tick,
148
+ /** M12 piece 2: resolves when every ticket look now out has been written to its ledger (a test awaits it; the timer never does). */
149
+ async settled() { await Promise.all([...lookers.values()].map((l) => l.out)); },
114
150
  /** Start the real timer (idempotent). */
115
151
  start() {
116
152
  if (intervalMs <= 0 || timer !== null) return;
@@ -60,8 +60,9 @@ 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, getRunDownload, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
63
+ listRuns, listScheduled, summarizeJobs, RUNS_LIST_LIMITS, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, getRunResult, getTicketList, getRunDownload, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
64
64
  } from './data.js';
65
+ import { ticketAnyway, arriveAnywayOf } from './tickets.js';
65
66
  import { createResumer } from './resume.js';
66
67
  import { createScheduler } from './scheduler.js';
67
68
  import { createAuthor } from './author.js';
@@ -370,13 +371,27 @@ function authorPost(res, url, body, author) {
370
371
  refuse(res, 404, 'not-found', url);
371
372
  }
372
373
 
374
+ /**
375
+ * M12 piece 3: `POST /api/author/ticket-anyway` — queue a skipped ticket as a new arrival after a short reason (src/panel/tickets.js decides every refusal).
376
+ * The queue is the schedule builder's seam: `createPanelServer({ticketQueue: {arriveAnyway}})`; production wires `arriveAnywayOf` (one `arrived` row in the schedule ledger).
377
+ * @param {any} res @param {any} body @param {any} opts
378
+ */
379
+ function ticketAnywayRoute(res, body, opts) {
380
+ const loaded = loadCatalogue();
381
+ if (!loaded.ok) { refuse(res, 500, 'catalogue', 'the catalogue failed to load'); return; }
382
+ const r = ticketAnyway({
383
+ body, listOf: (flow, runId) => getTicketList({ root: opts.root, flow, runId, catalogue: loaded.primitives }), queue: opts.ticketQueue,
384
+ });
385
+ sendJson(res, r.status, r.body);
386
+ }
387
+
373
388
  /**
374
389
  * Handle one request against the API + the page. Exported
375
390
  * separately from {@link createPanelServer} so tests can drive it without a
376
391
  * real listening socket where that is simpler.
377
392
  * @param {import('node:http').IncomingMessage} req
378
393
  * @param {import('node:http').ServerResponse} res
379
- * @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 }} opts
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
380
395
  */
381
396
  export function handleRequest(req, res, opts) {
382
397
  const method = req.method ?? 'GET';
@@ -433,6 +448,7 @@ export function handleRequest(req, res, opts) {
433
448
  if (tooBig) return;
434
449
  let body;
435
450
  try { body = JSON.parse(Buffer.concat(parts).toString('utf8')); } catch { refuse(res, 400, 'body-not-json'); return; }
451
+ if (isAuthorPost && req.url === '/api/author/ticket-anyway') { ticketAnywayRoute(res, body, opts); return; }
436
452
  if (isAuthorPost) { authorPost(res, String(req.url), body, opts.author); return; }
437
453
  if (isSettingsPost) { settingsReply(res, opts.settings.handle({ method, pathname: String(req.url), query: new URLSearchParams(), body })); return; }
438
454
  if (isResume) resumeRoute(res, body, opts.root, opts.resumer);
@@ -679,7 +695,7 @@ export function panelUrl(boundPort) {
679
695
  * header). Resolves once actually listening; rejects on a bind error
680
696
  * (including `EADDRINUSE`) with a `.port` field on the error for the
681
697
  * caller's message.
682
- * @param {{ port?: number, root: string, packagePath?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string, now?: () => number }, scheduler?: { intervalMs?: number } }} opts
698
+ * @param {{ port?: number, root: string, packagePath?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: (cmd: string, args: string[], o: object) => any, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string, now?: () => number }, scheduler?: { intervalMs?: number, mcpConfig?: string }, ticketQueue?: {arriveAnyway?: Function} }} opts
683
699
  * `resume` and `author` are for tests only (a fake env/bin, a short retry window); the CLI passes none.
684
700
  * @returns {Promise<{ server: import('node:http').Server, port: number, tick: () => void, close: () => Promise<void> }>}
685
701
  */
@@ -704,7 +720,7 @@ export function createPanelServer(opts) {
704
720
  });
705
721
  // M9: the scheduler runs the clock and the file watch while this server is up (item 3). The clock is the author's `now` (tests inject one);
706
722
  // `scheduler.intervalMs` 0 = no timer, a test calls `tick`. Stopped on close.
707
- const scheduler = createScheduler({ door: author.trigger, now: opts.author?.now, intervalMs: opts.scheduler?.intervalMs });
723
+ const scheduler = createScheduler({ door: author.trigger, now: opts.author?.now, intervalMs: opts.scheduler?.intervalMs, mcpConfig: opts.scheduler?.mcpConfig });
708
724
  // Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
709
725
  // process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
710
726
  const settings = createSettings({
@@ -720,7 +736,7 @@ export function createPanelServer(opts) {
720
736
  const server = createServer((req, res) => {
721
737
  try {
722
738
  handleRequest(req, res, {
723
- root, port: boundPort, resumer, settings, author, version, startedAt, packagePath: opts.packagePath, now: opts.author?.now,
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 }),
724
740
  });
725
741
  } catch (e) {
726
742
  sendText(res, 500, 'internal error');
@@ -0,0 +1,113 @@
1
+ // M12 piece 3 (docs/wiki/the-module-ladder.md, "M12 scope (restart)" item 9; mockup docs/product/m12-ticket-results-mock.html, variant E): the ticket list in the
2
+ // Result tab of the run the ticket schedule was set from. One row per ticket NUMBER, for all time: the ticket's newest run decides its group. The rows are read
3
+ // from the runs themselves (`run.json` keeps `ticket: {number, title}` for every ticket run, M12 p3) and the schedule ledger's `arrived` rows (arrival time, and
4
+ // the reason a watched change made a ticket arrive again). No file of its own; nothing written. Pure of the panel: the run lookups are injected.
5
+ import { join } from 'node:path';
6
+
7
+ import { readSchedule, ledgerOf } from '../schedule.js';
8
+ import { readSeen } from '../trigger-files.js';
9
+ import { readRunInputs } from '../runfile.js';
10
+ import { recordAnyway } from '../trigger-tickets.js';
11
+
12
+ /** the four groups, in the mockup's order: key, label, open at first. The page draws them; it types none of these words. */
13
+ export const TICKET_GROUPS = Object.freeze([
14
+ { key: 'wait', label: 'Needs you', open: true },
15
+ { key: 'stop', label: 'Stopped', open: true },
16
+ { key: 'done', label: 'Passed', open: false },
17
+ { key: 'skip', label: 'Skipped', open: false },
18
+ ]);
19
+
20
+ /** 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({
22
+ '[·]': 'wait', '[▶]': 'wait', '[II]': 'wait', '[!]': 'wait', '[✓]': 'done', '[–]': 'skip', '[✗]': 'stop', '[■]': 'stop', '[?]': 'stop',
23
+ });
24
+
25
+ /**
26
+ * The ticket schedule this run was set from, or null (no schedule, not a ticket schedule, or set from another run).
27
+ * @param {string} flowDir @param {string} runId @param {(dir: string) => any} [readSched]
28
+ */
29
+ export function ticketScheduleOf(flowDir, runId, readSched = readSchedule) {
30
+ const s = readSched(flowDir);
31
+ return s && s.trigger?.kind === 'new-ticket' && s.from === runId ? s : null;
32
+ }
33
+
34
+ /**
35
+ * @param {{flowDir: string, runId: string, runIdsOf: (flowDir: string) => string[], glyphOf: (runId: string) => {glyph: string, label: string}|null, atOf?: (runId: string) => number|null, readSched?: (dir: string) => any}} a
36
+ * @returns {null | {line: string, list: string, groups: Array<{key: string, label: string, open: boolean, rows: any[]}>}}
37
+ */
38
+ export function ticketListOf({ flowDir, runId, runIdsOf, glyphOf, atOf = () => null, readSched }) {
39
+ const sched = ticketScheduleOf(flowDir, runId, readSched);
40
+ if (!sched) return null;
41
+ const arrivals = new Map();
42
+ for (const r of /** @type {any[]} */ (readSeen(ledgerOf(flowDir), sched.sig))) {
43
+ if (r.kind !== 'arrived' || !Number.isInteger(r.number)) continue;
44
+ const a = arrivals.get(r.number) ?? { first: r.at, last: r.at, count: 0, reason: null };
45
+ arrivals.set(r.number, { first: Math.min(a.first, r.at), last: Math.max(a.last, r.at), count: a.count + 1, reason: typeof r.reason === 'string' ? r.reason : a.reason });
46
+ }
47
+ /** @type {Map<number, any>} */
48
+ const byNumber = new Map();
49
+ for (const id of runIdsOf(flowDir)) {
50
+ const runDir = join(flowDir, 'runs', id);
51
+ const inputs = readRunInputs(runDir);
52
+ const entry = inputs.ok ? inputs.entries.find((e) => e && e.ticket && Number.isInteger(e.ticket.number)) : null;
53
+ if (!entry) continue;
54
+ const g = glyphOf(id);
55
+ if (!g) continue;
56
+ const at = atOf(id) ?? Date.now();
57
+ const n = entry.ticket.number;
58
+ const arr = arrivals.get(n);
59
+ const row = {
60
+ number: n, title: typeof entry.ticket.title === 'string' ? entry.ticket.title : null, group: GROUP_OF[g.glyph] ?? 'stop', glyph: g.glyph,
61
+ runId: id, at: arr ? arr.last : at,
62
+ reason: g.glyph === '[–]' ? g.label.replace(/^skipped — ?/, '') || null : null,
63
+ changed: arr && arr.count > 1 ? arr.reason : null,
64
+ };
65
+ const prior = byNumber.get(n);
66
+ if (!prior || Number(id.replace(/\D/g, '')) > Number(prior.runId.replace(/\D/g, ''))) byNumber.set(n, row);
67
+ }
68
+ const rows = [...byNumber.values()].sort((a, b) => b.at - a.at || b.number - a.number);
69
+ return {
70
+ line: `When a new ticket arrives in ${sched.trigger.role} · looks every 15 min`,
71
+ list: sched.trigger.list,
72
+ groups: TICKET_GROUPS.map((g) => ({ ...g, rows: rows.filter((r) => r.group === g.key) })),
73
+ };
74
+ }
75
+
76
+ /** a "Run it anyway" reason: short, never blank. The same bar as a rerun's. */
77
+ export const ANYWAY_REASON_MAX = 500;
78
+
79
+ /**
80
+ * `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
+ * `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
83
+ * @returns {{status: number, body: Record<string, any>}}
84
+ */
85
+ export function ticketAnyway({ body, listOf, queue }) {
86
+ const b = body !== null && typeof body === 'object' ? body : {};
87
+ const reason = typeof b.reason === 'string' ? b.reason.trim() : '';
88
+ if (reason === '') return { status: 400, body: { ok: false, refused: 'reason-required', say: 'Please write a reason to run it anyway.' } };
89
+ 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.' } };
91
+ const list = listOf(b.flow, b.runId);
92
+ const row = list?.groups.find((g) => g.key === 'skip')?.rows.find((r) => r.number === b.number);
93
+ 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
+ const r = queue.arriveAnyway({ flow: b.flow, runId: b.runId, number: b.number, reason });
95
+ if (!r.ok) return { status: 409, body: { ok: false, refused: 'queue', say: r.say ?? 'The ticket was not queued. Nothing started.' } };
96
+ return { status: 202, body: { ok: true, queued: true, number: b.number, say: `Ticket #${b.number} is queued; it runs when its turn comes.` } };
97
+ }
98
+
99
+ /**
100
+ * 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
+ * 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}}}
104
+ */
105
+ export function arriveAnywayOf({ scan, now }) {
106
+ return {
107
+ arriveAnyway({ flow, number, reason }) {
108
+ const job = scan().find((j) => j.flow === flow && j.trigger?.kind === 'new-ticket');
109
+ 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
+ return recordAnyway(ledgerOf(job.flowDir), job.sig, { number, reason }, now());
111
+ },
112
+ };
113
+ }
package/src/runner.js CHANGED
@@ -54,7 +54,7 @@ import {
54
54
  writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen, setAsideAnswer,
55
55
  } from './ask.js';
56
56
  import {
57
- findUnwiredVerbStep, unwiredRed, findUnbuildableCheckStep, unbuildableRed,
57
+ findUnwiredVerbStep, unwiredRed, findUnbuildableCheckStep, unbuildableRed, findUnusedMcpTool, unusedMcpToolRed,
58
58
  } from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
59
59
  import { configHome, configDoorHome } from './config.js';
60
60
  import { closeByClass, isCellsPath } from './closers.js';
@@ -77,6 +77,8 @@ 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';
81
+ import { decideTicket, readTicketFields } from './ticket-labels.js';
80
82
  import {
81
83
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
82
84
  } from './liveness.js';
@@ -419,16 +421,36 @@ export async function freezePage(dir, id, url, { fetchPage = fetchPageText } = {
419
421
  * (never the original again after this) and return the manifest, which `runFlow` records as the `inputs` of `run.json` (M8b). An
420
422
  * unreadable source refuses by name. A source that is a web address
421
423
  * (M10 item 1) is fetched and frozen by `freezePage`, in the same manifest.
422
- * @param {string} runDir @param {Array<{id: string, path: string}>} sources
424
+ * @param {string} runDir @param {Array<{id: string, path: string, ticket?: {number: number, anyway?: true}}>} sources
423
425
  * M10b amendment 1: a CSV input named in `tableRoles` (the sheets a step's `close.sheet` reads) also gets its `tableSha` (bareguard's fingerprint of the table made
424
426
  * from the FROZEN copy) in its manifest entry - the ONE place it is written, once, with the run's inputs; every sheet check of the run uses this recorded value.
425
427
  * A sheet bareguard cannot read as a table refuses the run here, naming the input.
426
- * @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, tableRoles?: string[]}} [o] */
427
- export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = [] } = {}) {
428
+ * M12 piece 1b: a source with `ticket: {number}` is one ticket of the list at its `path`, read through the job's MCP tools (`mcp`, the declaration's `{server, tools}`) by
429
+ * `ticketRead` and frozen like a page; its manifest entry also carries `mcp`, the record of what the server exposed and each call made (kept in `run.json`, no new file).
430
+ * @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, tableRoles?: string[], mcp?: {server: string, tools: string[]}, ticketRead?: typeof readTicketMcp, ticketFilter?: {priority?: string[], labels?: string[]}}} [o] */
431
+ export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = [], mcp, ticketRead = readTicketMcp, ticketFilter } = {}) {
428
432
  const inputsDir = join(runDir, 'inputs');
429
433
  mkdirSync(inputsDir, { recursive: true });
430
434
  const manifest = [];
431
- for (const { id, path: sourcePath } of sources ?? []) {
435
+ /** M12 piece 3: the first ticket the signed labels (or its state) skip: its reason; the run ends `skipped` after its start record is written */
436
+ let skip = null;
437
+ for (const { id, path: sourcePath, ticket } of sources ?? []) {
438
+ if (ticket) {
439
+ if (!mcp) return { ok: false, red: `freeze: input "${id}": the job lists no MCP tools` };
440
+ const got = await ticketRead({ listUrl: sourcePath, number: ticket.number, mcp });
441
+ if (!got.ok) return { ok: false, red: `freeze: input "${id}": ${got.error}` };
442
+ const page = await freezePage(inputsDir, id, got.url, { fetchPage: async () => got });
443
+ if (!page.ok) return page;
444
+ const verdict = decideTicket({ text: got.text, filter: ticketFilter });
445
+ const fields = readTicketFields(got.text);
446
+ // hamr 2026-10-30: a ticket sent with "Run it anyway" is never skipped (labels or closed); the record keeps what the filter would have said
447
+ const anyway = ticket.anyway === true;
448
+ manifest.push({
449
+ ...page.entry, mcp: got.record, ticket: { number: ticket.number, title: fields.ok ? fields.title : null }, filter: anyway ? { outcome: 'anyway', was: verdict } : verdict,
450
+ });
451
+ if (!anyway && verdict.outcome === 'skip' && skip === null) skip = verdict.reason;
452
+ continue;
453
+ }
432
454
  if (isWebUrl(sourcePath)) {
433
455
  const page = await freezePage(inputsDir, id, sourcePath, { fetchPage });
434
456
  if (!page.ok) return page;
@@ -453,7 +475,7 @@ export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = []
453
475
  }
454
476
  manifest.push(entry);
455
477
  }
456
- return { ok: true, manifest };
478
+ return { ok: true, manifest, skip };
457
479
  }
458
480
 
459
481
  /** realpath of a path that may not exist (falls back to the lexical resolve). */
@@ -1233,6 +1255,14 @@ export async function runFlow({
1233
1255
  });
1234
1256
  }
1235
1257
 
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) {
1261
+ return haltRun({
1262
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: unusedMcpToolRed(unusedTool), spent: { value: 0 },
1263
+ });
1264
+ }
1265
+
1236
1266
  // M4e amendment 19 4: every softgreen check is built before the first model call; one that cannot be built is refused at $0, by step name
1237
1267
  const unbuildable = findUnbuildableCheckStep(declaration);
1238
1268
  if (unbuildable) {
@@ -1273,7 +1303,7 @@ export async function runFlow({
1273
1303
  }
1274
1304
  }
1275
1305
 
1276
- const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps) });
1306
+ const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps), mcp: declaration.mcp, ticketFilter: declaration.ticketFilter });
1277
1307
  if (!frozen.ok) {
1278
1308
  return haltRun({
1279
1309
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
@@ -1281,6 +1311,12 @@ export async function runFlow({
1281
1311
  }
1282
1312
  // M8b item 1: the run's start record, written once: the model it started on (M4d am33), the "Thinking on" box (M4d am25) and the frozen inputs
1283
1313
  writeRunStart(runDir, { model: runModel ?? null, thinking: thinkingBox, inputs: /** @type {any[]} */ (frozen.manifest) });
1314
+ // M12 piece 3 (item 9): a ticket the signed labels do not match, or a closed one, ends here: skipped, $0, nothing else runs
1315
+ if (frozen.skip) {
1316
+ return haltRun({
1317
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'skipped', red: '', skip: frozen.skip, spent: { value: 0 },
1318
+ });
1319
+ }
1284
1320
  // M4c: every guard above has passed — this process records itself (pid row) before its first step.
1285
1321
  recordPid(runDir, 'run', now());
1286
1322
 
@@ -2116,6 +2152,8 @@ export async function resumeRun({
2116
2152
  red: unwiredRed(unwiredVerb),
2117
2153
  };
2118
2154
  }
2155
+ const unusedTool = findUnusedMcpTool(preflightRead.declaration);
2156
+ if (unusedTool) return { outcome: 'refused', red: unusedMcpToolRed(unusedTool) };
2119
2157
  const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2120
2158
  if (unbuildable) return { outcome: 'refused', red: unbuildableRed(unbuildable), detail: unbuildable.why };
2121
2159
  }
@@ -2647,6 +2685,8 @@ export async function continueRun({
2647
2685
  if (preflightRead.ok) {
2648
2686
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2649
2687
  if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
2688
+ const unusedTool = findUnusedMcpTool(preflightRead.declaration);
2689
+ if (unusedTool) return refused(unusedMcpToolRed(unusedTool));
2650
2690
  const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2651
2691
  if (unbuildable) return refused(unbuildableRed(unbuildable), unbuildable.why);
2652
2692
  }
@@ -2960,6 +3000,7 @@ export function readAsk(runDir) {
2960
3000
  * @param {{ value: number }} opts.spent
2961
3001
  * @param {any[]} [opts.attempts]
2962
3002
  * @param {Record<string, any>} [opts.artifacts]
3003
+ * @param {string|null} [opts.skip] - M12 p3: the reason a ticket run ends `skipped` (history row `skipReason`, log.json `skipReason`)
2963
3004
  * @param {string|null} [opts.signatureHash] - the flow's `signature.json` `flow`
2964
3005
  * hash, when this halt happened AFTER `readFlow` succeeded (item 9: every
2965
3006
  * history row carries it, halts included). A halt before the signature was
@@ -2977,7 +3018,7 @@ export function readAsk(runDir) {
2977
3018
  */
2978
3019
  function haltRun({
2979
3020
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs = Date.now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
2980
- priorSpendComplete = true, resumeAt = null, stop = null, detail = null,
3021
+ priorSpendComplete = true, resumeAt = null, stop = null, detail = null, skip = null,
2981
3022
  }) {
2982
3023
  // F45 finding 3: `startedAt` here is always the RUN's start (every caller
2983
3024
  // now passes `runStartedAt` under this key — see call sites), so `wallMs`
@@ -2990,7 +3031,7 @@ function haltRun({
2990
3031
  if (existsSync(runDir)) {
2991
3032
  recordLateAnswerIfAny(runDir, now);
2992
3033
  writeLog(runDir, {
2993
- runId, outcome, red, ...(detail ? { detail } : {}), attempts, artifacts,
3034
+ runId, outcome, red, ...(detail ? { detail } : {}), ...(skip ? { skipReason: skip } : {}), attempts, artifacts,
2994
3035
  });
2995
3036
  // M4e amendment 4 item 4: a cap-halted or stopped run leaves the one record Resume continues from (its only writer).
2996
3037
  if (resumeAt && HALT_OUTCOMES.includes(outcome)) {
@@ -3010,7 +3051,7 @@ function haltRun({
3010
3051
  const stoppedWithoutHaltRecord = outcome === 'stopped' && resumeAt && !readHaltRecord(runDir).ok;
3011
3052
  if (!stoppedWithoutHaltRecord) {
3012
3053
  appendHistory(flowDir, {
3013
- runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash, ...(detail ? { detail } : {}), // amendment 23: bareguard's raw reason, never the sentence
3054
+ runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash, ...(detail ? { detail } : {}), ...(skip ? { skipReason: skip } : {}), // amendment 23: bareguard's raw reason, never the sentence
3014
3055
  });
3015
3056
  }
3016
3057
  }
package/src/schedule.js CHANGED
@@ -18,6 +18,7 @@ import { appendRow } from './jsonl-append.js';
18
18
  import { queueOf, readSeen, recordDropped } from './trigger-files.js';
19
19
  import { readRows, validateSchedule } from './trigger-clock.js';
20
20
  import { triggerHash } from './trigger-line.js';
21
+ import { WATCHABLE } from './ticket-shape.js';
21
22
 
22
23
  /** @typedef {import('./trigger-line.js').Trigger} Trigger */
23
24
  /**
@@ -42,11 +43,14 @@ export const ledgerOf = (flowDir) => join(flowDir, LEDGER_FILE);
42
43
  export const sigOf = (bound, signedAt) => createHash('sha256').update(`${bound}\n${signedAt}`).digest('hex');
43
44
 
44
45
  const isFile = (/** @type {any} */ t) => t?.kind === 'new-file' || t?.kind === 'file-updated';
46
+ const isTicket = (/** @type {any} */ t) => t?.kind === 'new-ticket';
45
47
  const str = (/** @type {unknown} */ v) => typeof v === 'string' && v !== '';
46
48
 
47
49
  /** Is this a typed trigger of the five shapes? (the same shapes `trigger-line.js` parses; the schedule file never carries a line) @param {any} t */
48
50
  function triggerOk(t) {
49
51
  if (!t || typeof t !== 'object') return false;
52
+ // M12 piece 2: a ticket trigger carries the list address, the job's server and the look's one tool (signed with the two clicks), and optionally the watched fields
53
+ if (t.kind === 'new-ticket') return str(t.role) && str(t.list) && str(t.server) && str(t.tool) && (t.watch === undefined || (Array.isArray(t.watch) && t.watch.every((/** @type {unknown} */ w) => WATCHABLE.includes(/** @type {string} */ (w)))));
50
54
  if (isFile(t)) return str(t.role) && isAbsolute(String(t.kind === 'new-file' ? t.folder : t.path));
51
55
  try { validateSchedule(t); return true; } catch { return false; }
52
56
  }
@@ -89,6 +93,7 @@ export function removeSchedule(flowDir) {
89
93
 
90
94
  /** Does a re-sign keep the same kind and the same folder/file (so the queue and the baseline stand)? @param {Trigger|null|undefined} cur @param {Trigger|null} next */
91
95
  export function sameTarget(cur, next) {
96
+ if (isTicket(cur) && isTicket(next)) return /** @type {any} */ (cur).role === /** @type {any} */ (next).role && /** @type {any} */ (cur).list === /** @type {any} */ (next).list; // M12: the same list keeps its queue and its starting point
92
97
  if (!cur || !next || !isFile(cur) || !isFile(next) || cur.kind !== next.kind) return false;
93
98
  return cur.kind === 'new-file' ? cur.folder === /** @type {any} */ (next).folder : /** @type {any} */ (cur).path === /** @type {any} */ (next).path;
94
99
  }
@@ -38,6 +38,7 @@ export function scheduledWords(t, home) {
38
38
  if (t.kind === 'weekdays') return `Weekdays at ${hhmm(t)}`;
39
39
  if (t.kind === 'weekly') return `${DAY_PLURAL[/** @type {keyof typeof DAY_PLURAL} */ (t.day)] ?? t.day} at ${hhmm(t)}`;
40
40
  if (t.kind === 'file-updated') return `When ${basename(t.path)} is updated`;
41
+ if (t.kind === 'new-ticket') return `When a new ticket arrives in ${t.role}`;
41
42
  const folder = tilde(/** @type {{folder: string}} */ (t).folder, home);
42
43
  return `When a new file arrives in ${folder.endsWith('/') ? folder : `${folder}/`}`;
43
44
  }
@@ -96,6 +97,7 @@ export function scheduledNextFor(f) {
96
97
  if (!armed) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
97
98
  if (trigger.kind === 'file-updated') return say(`${lead}Watching for it. A run starts when its contents change.`, red);
98
99
  if (trigger.kind === 'new-file') return say(`${lead}Watching for it. A run starts for each new file.`, red);
100
+ if (trigger.kind === 'new-ticket') return say(`${lead}Watching for it. A run starts for each new ticket.`, red);
99
101
  if (nextSlotMs === null) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
100
102
  return say(`${lead}Next run ${slotWords(nextSlotMs)}.`, red);
101
103
  }
@@ -121,12 +123,12 @@ const splitNext = (rows) => ({ next: rows.map(([l, t]) => `${l} ${t}`).join('\n'
121
123
  /**
122
124
  * ENDED / NEXT of a finished run. Every outcome the history row can hold has a fixed sentence; an unknown one gets an honest fixed fallback
123
125
  * that names the code and guesses nothing. `null` when there is no ending (still running, waiting, or no history row and not died).
124
- * @param {{outcome: string|null, died?: boolean, line: number|null, destination: string|null, canResume: boolean, home?: string}} f
126
+ * @param {{outcome: string|null, died?: boolean, line: number|null, destination: string|null, canResume: boolean, home?: string, skipReason?: string}} f
125
127
  * @returns {{reason: string, next: string, rows?: Array<[string, string]>}|null}
126
128
  */
127
129
  export function endedWords(f) {
128
130
  const {
129
- outcome, died = false, line, destination, canResume, home,
131
+ outcome, died = false, line, destination, canResume, home, skipReason,
130
132
  } = f;
131
133
  const resumeOrAgain = canResume ? 'Resume from the Chat card.' : RERUN_NEXT;
132
134
  if (died) return { reason: 'It stopped with no ending recorded.', next: 'See the Audit / logs tab for the last thing it did.' };
@@ -134,6 +136,8 @@ export function endedWords(f) {
134
136
  switch (outcome) {
135
137
  case 'complete':
136
138
  return { reason: 'Goal met.', next: destination ? `The result is in ${tilde(destination, home)}.` : 'The result is in the step cards below.' };
139
+ case 'skipped':
140
+ return { reason: `Skipped: ${typeof skipReason === 'string' && skipReason !== '' ? skipReason : 'the ticket did not match'}. Nothing was spent.`, next: 'Nothing to do. Run it anyway from the ticket list in the Result tab.' };
137
141
  case 'stopped':
138
142
  return { reason: 'Stopped by you.', next: resumeOrAgain };
139
143
  case 'cap-halt':
@@ -212,7 +216,7 @@ export function scheduleFieldWords(f) {
212
216
  /** A run's `trigger.json` record -> the typed pieces of "how it began", or `null` for a hand run. @param {any} rec */
213
217
  function startedKind(rec) {
214
218
  if (!rec || typeof rec !== 'object') return null;
215
- return rec.kind === 'file' || rec.kind === 'clock' ? rec.kind : null;
219
+ return rec.kind === 'file' || rec.kind === 'clock' || rec.kind === 'ticket' ? rec.kind : null;
216
220
  }
217
221
 
218
222
  /**
@@ -231,6 +235,8 @@ export function startedWords(rec, startMs, home) {
231
235
  const name = typeof rec.file === 'string' ? basename(rec.file) : '';
232
236
  const updated = rec.triggerKind === 'file-updated';
233
237
  head = `${updated ? 'By a file update' : 'By a new file'}${name ? `: ${name}` : ''}`;
238
+ } else if (kind === 'ticket') {
239
+ head = `By a new ticket${Number.isInteger(rec.ticket) ? `: #${rec.ticket}` : ''}${typeof rec.why === 'string' && rec.why !== '' ? ` (${rec.why})` : ''}`;
234
240
  }
235
241
  return stamp ? `${head} · ${stamp}` : head;
236
242
  }
@@ -261,7 +267,7 @@ export function scheduleBlockWords(f) {
261
267
  const tr = f.trigger;
262
268
  if (head === null || tr === null) return { line1: 'By hand', line2: null, red: false };
263
269
  const file = tr.kind === 'new-file' || tr.kind === 'file-updated';
264
- const next = file ? 'next: waiting for a new file' : (f.nextSlotMs !== null && f.armed ? `next ${dayStamp(f.nextSlotMs)}` : 'next: not armed yet');
270
+ const next = tr.kind === 'new-ticket' ? 'next: waiting for a new ticket' : file ? 'next: waiting for a new file' : (f.nextSlotMs !== null && f.armed ? `next ${dayStamp(f.nextSlotMs)}` : 'next: not armed yet');
265
271
  const p = f.problem;
266
272
  if (p) {
267
273
  const stamp = `last ${shortStamp(p.at)}`;
@@ -323,6 +329,8 @@ export function scheduleAuditWords(f) {
323
329
  else if (kind === 'file') {
324
330
  const name = typeof f.rec.file === 'string' ? basename(f.rec.file) : '';
325
331
  what = `started by the schedule \u00b7 ${f.rec.triggerKind === 'file-updated' ? 'file update' : 'new file'}${name ? ` ${name}` : ''}`;
332
+ } else if (kind === 'ticket') {
333
+ what = `started by the schedule \u00b7 new ticket${Number.isInteger(f.rec.ticket) ? ` #${f.rec.ticket}` : ''}`;
326
334
  }
327
335
  if (f.from !== null && f.from === f.runId) what += kind === null ? ' The schedule was set from this run.' : '. The schedule was set from this run.';
328
336
  /** @type {Array<{label: string, stamp: string, text: string}>} */