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
@@ -0,0 +1,85 @@
1
+ // M12 piece 3 (docs/wiki/the-module-ladder.md, "M12 scope (restart)" item 4): what the DRAFTER is told about a ticket role, and what it may suggest.
2
+ // A ticket role is a signed page input (`source <role> = page:<address>`) whose address is a GitHub issues list: it is never fetched at draft (one ticket is read
3
+ // per run through the job's MCP tools). The drafter may SUGGEST the job's `mcp`/`mcpTools` (issue_read) and a `ticketFilter` (priority / label names); a human
4
+ // signs it and code decides at run. The first facts line is F90c's, the line that made the drafter read a ticket role at all (FINDINGS F90c, F92).
5
+ import { discoverServers } from 'bare-agent/mcp';
6
+ import { startableMcpServers } from './mcp-sources.js';
7
+ import { LIST_URL } from './ticket-shape.js';
8
+
9
+ /** the one tool the first slice reads a ticket with */
10
+ export const TICKET_TOOL = 'issue_read';
11
+
12
+ /** is this signed input address a GitHub issues list (a ticket role), not a page to fetch? @param {unknown} url */
13
+ export const isTicketListUrl = (url) => LIST_URL.test(String(url).trim());
14
+
15
+ /** the signed page sources that are ticket roles @param {Array<{kind?: string, role: string, path: string}>} sources */
16
+ export const ticketSourcesOf = (sources) => (sources ?? []).filter((s) => s.kind === 'page' && isTicketListUrl(s.path));
17
+
18
+ /** the startable server names across the MCP sources (src/mcp-sources.js), or in one explicit file (what the drafter may name); none when the file is missing or unreadable @param {string} [configPath] @returns {string[]} */
19
+ export function userMcpServers(configPath) {
20
+ try { return configPath ? [...discoverServers([configPath]).keys()] : startableMcpServers(); } catch { return []; }
21
+ }
22
+
23
+ /**
24
+ * The lines under "Inputs" for one ticket role (M13 piece 4: flow type Tickets). The first is F90c's, word for word. The ticket is already frozen under its role and the job's own
25
+ * tools (`issue_read` to read it, `list_issues` to look for new ones) belong to the job, so no step needs them; a step lists a tool only if it calls it live.
26
+ * @param {string} role @returns {string[]}
27
+ */
28
+ export function ticketFactsLines(role) {
29
+ return [
30
+ `- ${role}: one ticket's text (a signed input, already frozen at run start; read it by listing "${role}" in a step's reads, do not fetch it)`,
31
+ ` A step that reads "${role}" still lists "read" in its primitives: the ticket is frozen, but reading it is a grant.`,
32
+ ` Flow type: Tickets. The ticket is already frozen under "${role}" by the job's own tools ("${TICKET_TOOL}" reads it, "${LOOK_TOOL}" looks for new ones); no step needs them. A step lists a tool in "mcpTools" ONLY if that step calls the tool live; leave "mcpTools" out of every other step. The job's server and tool list are set by the program, not by you.`,
33
+ ' When a guardrail names a priority or a label (for example "priority P1 only", "only tickets with priority P1 count", "only issues labelled bug"), you MUST add a top-level "ticketFilter": {"priority": [P0 to P3 values], "labels": [label names]} for it; leave it out only when no guardrail names a priority or a label, and such a guardrail stays hitl. A human signs it and code decides at run; never invent a label.',
34
+ ' You may SUGGEST a top-level "ticketWatch": ["state", "labels"] (one or both) ONLY for a guardrail that says to run a ticket again when its state or its labels change. Any other thing to watch cannot be put there: leave it out and it stays hitl.',
35
+ ];
36
+ }
37
+
38
+ /** the lines for a generic MCP job: the server, its tool names (so the drafter can grant them to steps), and the rule that a step lists a tool only if it calls it live @param {string} server @param {string[]} tools @returns {string[]} */
39
+ export function mcpFactsLines(server, tools) {
40
+ return [
41
+ `- Flow type: MCP (generic). The job's MCP server is "${server}" and its tools are: ${tools.join(', ')}. The job's server and tool list are set by the program, not by you.`,
42
+ ' A step lists a tool in "mcpTools" ONLY if that step calls the tool live, using the exact tool name above; at least one step must list at least one tool. Leave "mcpTools" out of every other step.',
43
+ ];
44
+ }
45
+
46
+ /** the one tool a Tickets job looks for new tickets with (src/panel/authortrigger.js) */
47
+ export const LOOK_TOOL = 'list_issues';
48
+
49
+ /**
50
+ * The schema parts a job with an MCP adds (M13 piece 4): per-step `mcpTools` (an enum of the job's tool names) for MCP (generic) and Tickets, and for Tickets the top-level
51
+ * `ticketFilter` and `ticketWatch`. The job's own `mcp` block and `flowType` are NOT offered: code sets them.
52
+ * @param {{flowType: 'mcp'|'tickets', tools: string[]}} o
53
+ */
54
+ export function ticketSchemaParts({ flowType, tools }) {
55
+ const step = { mcpTools: { type: 'array', items: { type: 'string', enum: tools }, description: 'the MCP tools this step calls LIVE (exact names); omit on every step that calls none' } };
56
+ if (flowType !== 'tickets') return { top: {}, step };
57
+ return {
58
+ top: {
59
+ ticketFilter: {
60
+ type: 'object',
61
+ properties: {
62
+ priority: { type: 'array', items: { type: 'string', enum: ['P0', 'P1', 'P2', 'P3'] }, description: 'priorities a ticket must have; only when a guardrail names them' },
63
+ labels: { type: 'array', items: { type: 'string' }, description: 'label names, one of which a ticket must carry; only when a guardrail names them' },
64
+ },
65
+ additionalProperties: false,
66
+ description: 'optional: suggest only for a guardrail that names a priority or a label',
67
+ },
68
+ ticketWatch: { type: 'array', items: { type: 'string', enum: ['state', 'labels'] }, description: 'optional: suggest only for a guardrail that says to run a ticket again when its state or its labels change' },
69
+ },
70
+ step,
71
+ };
72
+ }
73
+
74
+ /**
75
+ * M13 piece 4: the $0 refusals before any provider call. Tickets needs a ticket-list Inputs line; MCP (generic) and Tickets need a server that is startable and a tool list from a
76
+ * check (`pick`, src/mcp-pick.js: `{ok, server, tools}` or `{ok:false, say}`).
77
+ * @param {{flowType: string, ticketSources: Array<{role: string}>, pick: any, servers: string[]}} o @returns {string[]}
78
+ */
79
+ export function ticketReds({ flowType, ticketSources, pick, servers }) {
80
+ if (flowType === 'plain') return [];
81
+ if (flowType === 'tickets' && ticketSources.length === 0) return ['Tickets needs the ticket list address as an Inputs line (for example issues: https://github.com/owner/repo/issues)'];
82
+ if (!pick || pick.ok !== true) return [String(pick?.say ?? 'press check tools in Settings > MCP first')];
83
+ if (!servers.includes(pick.server)) return [`the MCP "${pick.server}" is not a server fwdloop can start (${servers.join(', ') || 'none found'})`];
84
+ return [];
85
+ }
@@ -0,0 +1,75 @@
1
+ // M12 piece 3 (docs/wiki/the-module-ladder.md, "M12 scope (restart)" items 4 and 9): which ticket a job's signed label filter lets through, decided by CODE.
2
+ // The drafter may suggest the labels and a human signs them (`declaration.ticketFilter`); at run start this reads the ticket's typed fields (labels, state)
3
+ // and answers run or skip. No model, no regex over free prose: only the `labels` list and the `state` string of the ticket's own JSON are read.
4
+ // Three outcomes are kept apart: skip (a definite miss, or closed), run (a match), run-with-`unsure` (an off-scale or unreadable label goes to a human at the
5
+ // ask, NEVER skipped). Normaliser borrowed in shape from fwdloop poc/mcp/f96/f96.mjs (the F96 rules, 12 of 12 on real tickets), re-shaped to a pure function.
6
+
7
+ /** `P0`..`P3`, optionally after `priority`, `priority:`, `priority /` or `priority -`; the digit must end the number (`P12` is no priority) */
8
+ const PRIORITY_LABEL = /^(?:priority\s*[:/-]?\s*)?p([0-3])(?![0-9])/;
9
+
10
+ /**
11
+ * One priority value from a ticket's labels: `P0`..`P3`; `unsure` when two different ones are present, or when a label names a priority on another scale
12
+ * (`priority/important-soon`) and no scale value is present; `none` when no label speaks of priority.
13
+ * @param {string[]} labels @returns {string}
14
+ */
15
+ export function priorityOf(labels) {
16
+ const found = new Set();
17
+ let offScale = false;
18
+ for (const raw of labels) {
19
+ const name = String(raw).trim().toLowerCase();
20
+ const m = PRIORITY_LABEL.exec(name);
21
+ if (m) found.add(`P${m[1]}`);
22
+ else if (name.split(/[^a-z0-9]+/).includes('priority')) offScale = true;
23
+ }
24
+ if (found.size > 1) return 'unsure';
25
+ if (found.size === 1) return [...found][0];
26
+ return offScale ? 'unsure' : 'none';
27
+ }
28
+
29
+ /**
30
+ * The typed fields of a ticket read through `issue_read`: its JSON. A missing `labels` key means no labels (GitHub omits it, F98). Text that is not a JSON
31
+ * object is `ok:false`: never read as "no labels".
32
+ * @param {string} text @returns {{ok: true, labels: string[], state: string|null, title: string|null}|{ok: false}}
33
+ */
34
+ export function readTicketFields(text) {
35
+ let o;
36
+ try { o = JSON.parse(text); } catch { return { ok: false }; }
37
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return { ok: false };
38
+ const labels = (Array.isArray(o.labels) ? o.labels : []).map((l) => (typeof l === 'string' ? l : l?.name)).filter((l) => typeof l === 'string' && l.trim() !== '');
39
+ return { ok: true, labels, state: typeof o.state === 'string' ? o.state.toLowerCase() : null, title: typeof o.title === 'string' ? o.title : null };
40
+ }
41
+
42
+ /**
43
+ * M13 piece 7 (9.4): the ONE reader of "the filter was unsure about this ticket", from a run.json input entry: true when its stored verdict ran with an `unsure`
44
+ * reason (also when the ticket was sent with Run it anyway and the filter's own verdict was unsure). Anything else, a torn entry too, is false.
45
+ * @param {any} entry @returns {boolean}
46
+ */
47
+ export function filterUnsure(entry) {
48
+ const f = entry?.filter;
49
+ return typeof f?.unsure === 'string' || (f?.outcome === 'anyway' && typeof f?.was?.unsure === 'string');
50
+ }
51
+
52
+ /**
53
+ * @param {{text: string, filter?: {priority?: string[], labels?: string[]}}} a `filter` = the job's signed `ticketFilter` (or absent)
54
+ * @returns {{outcome: 'run', unsure?: string}|{outcome: 'skip', reason: string}}
55
+ */
56
+ export function decideTicket({ text, filter }) {
57
+ const t = readTicketFields(text);
58
+ if (!t.ok) return { outcome: 'run', unsure: 'the ticket text is not readable as fields, so no label could be checked' };
59
+ if (t.state === 'closed') return { outcome: 'skip', reason: 'closed' };
60
+ if (!filter) return { outcome: 'run' };
61
+ /** @type {string|undefined} */
62
+ let unsure;
63
+ if (filter.priority?.length) {
64
+ const want = filter.priority.join(' or ');
65
+ const p = priorityOf(t.labels);
66
+ if (p === 'none') return { outcome: 'skip', reason: `no ${want} label` };
67
+ if (p === 'unsure') unsure = 'a priority label is not on the P0-P3 scale, or two priorities are present';
68
+ else if (!filter.priority.includes(p)) return { outcome: 'skip', reason: `priority ${p}, not ${want}` };
69
+ }
70
+ if (filter.labels?.length) {
71
+ const have = new Set(t.labels.map((l) => l.trim().toLowerCase()));
72
+ if (!filter.labels.some((l) => have.has(l.trim().toLowerCase()))) return { outcome: 'skip', reason: `no ${filter.labels.join(' or ')} label` };
73
+ }
74
+ return unsure === undefined ? { outcome: 'run' } : { outcome: 'run', unsure };
75
+ }
@@ -0,0 +1,89 @@
1
+ // M12 piece 1b/1c (docs/wiki/the-module-ladder.md, "M12 scope (restart)" items 1-3, 11): read ONE ticket through the user's own MCP server, nothing else.
2
+ // The tool source is the user's `~/.mcp.json` (an explicit path; a repo's .mcp.json is never read). The bridge starts ONLY the server the job names, with
3
+ // `allow` = exactly the job's tools, so any other tool does not exist for the run. M13 item 3: a hint (`readOnlyHint`) is info only; no tool is refused for lacking one.
4
+ // Every refusal names its real cause (F101), at $0; none ever reads as empty content (F103). Proven by F100 (a ticket as a frozen input), F101, F103.
5
+ // Borrowed shape: fwdloop poc/mcp/f100/scratch.diff (`src/ticket-mcp.js`), re-shaped: job-typed tools, explicit config, the three causes kept apart.
6
+ import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
7
+ import { homedir } from 'node:os';
8
+ import { join } from 'node:path';
9
+ import { redactSecrets } from './redact.js';
10
+ import { parseTicketList, isTicketNumber, TICKET_NUMBER_WORDS } from './ticket-shape.js';
11
+ import { mcpConfigFor } from './mcp-sources.js';
12
+
13
+ /** M13 item 9.5: the only parent env names an MCP gets (plus its own settings); the one list for every place fwdloop starts an MCP, so no provider key reaches it */
14
+ export const MCP_PASS_ENV = ['PATH', 'HOME'];
15
+
16
+ /** M13 design point 11 (F118): the one start option set for every place fwdloop starts an MCP: no provider key (passEnv) and the home folder as the start folder (bare-agent bridge `cwd`; no `~` expansion, so the real path) */
17
+ export const mcpStartOpts = () => ({ passEnv: MCP_PASS_ENV, cwd: homedir() });
18
+
19
+ /** the refusal for a failed bridge start: a bad home folder (bare-agent throws ValidationError before any spawn) says so plainly, any other cause keeps its own first line */
20
+ export const startRefusal = (/** @type {string} */ server, /** @type {any} */ e) => `${server} did not start: ${e?.name === 'ValidationError' ? `the home folder could not be used (${firstLine(e)})` : firstLine(e)}`;
21
+
22
+ /** the user's own `~/.mcp.json`: the config a caller that names no place falls back to (a server found nowhere then reads "not in ~/.mcp.json") */
23
+ export const USER_MCP_CONFIG = () => join(homedir(), '.mcp.json');
24
+
25
+ /**
26
+ * M13 piece 3: the config file a server starts from. An explicit path (a test seam) wins; otherwise the file of the WINNING place for `server` (src/mcp-sources.js,
27
+ * the one decider), or `~/.mcp.json` when no place has it. `remote` true = the winner has no start command (listed, not usable).
28
+ * @param {string} server @param {string} [explicit] @returns {{ file: string, remote: boolean }}
29
+ */
30
+ export function configForServer(server, explicit) {
31
+ if (explicit) return { file: explicit, remote: false };
32
+ return mcpConfigFor(server) ?? { file: USER_MCP_CONFIG(), remote: false };
33
+ }
34
+
35
+ /** the refusal for a remote server (no start command), at $0 @param {string} server */
36
+ export const remoteRefusal = (server) => `${server} is a remote server, not supported yet`;
37
+
38
+ /** the first line of a message, secrets redacted, clipped: all a refusal ever shows of a server's own error */
39
+ export const firstLine = (e) => redactSecrets(String(e?.message ?? e ?? '')).split('\n').find((l) => l.trim() !== '')?.trim().slice(0, 200) ?? 'no message';
40
+
41
+ /** GitHub's MCP server answers a request with this text, not data, when it has no usable login (F100, F103: seen with a cold `pass` cache) */
42
+ export const isDeviceLogin = (text) => text.includes('github.com/login/device');
43
+
44
+ /**
45
+ * Read ticket `number` of the list at `listUrl` with the job's `issue_read`.
46
+ * @param {{listUrl: string, number: number, mcp: {server: string, tools: string[]}, configPath?: string, timeoutMs?: number}} o
47
+ * @returns {Promise<{ok: true, text: string, url: string, record: {server: string, exposed: string[], missing: Array<{server: string, tool: string}>, calls: Array<{tool: string, owner: string, repo: string, issue_number: number}>}} | {ok: false, error: string}>}
48
+ * `record` is what the run keeps (in its `run.json` input entry): what the server exposed and lacked, and each call made.
49
+ */
50
+ export async function readTicketMcp({ listUrl, number, mcp, configPath: explicitConfig, timeoutMs = 90000 }) {
51
+ const list = parseTicketList(listUrl);
52
+ if (!list.ok) return list;
53
+ if (!isTicketNumber(number)) return { ok: false, error: `ticket number ${JSON.stringify(number)} is not ${TICKET_NUMBER_WORDS}` };
54
+ const { owner, repo } = list;
55
+ const { server, tools } = mcp;
56
+ // M13 piece 4: the frozen read starts the server with issue_read alone, whatever else the job lists (the job lists every tool of its server)
57
+ if (!tools.includes('issue_read')) return { ok: false, error: `the job does not list issue_read, the tool that reads a ticket` };
58
+ const { file: configPath, remote } = configForServer(server, explicitConfig);
59
+ if (!discoverServers([configPath]).has(server)) return { ok: false, error: `${server} is not in ~/.mcp.json` };
60
+ if (remote) return { ok: false, error: remoteRefusal(server) };
61
+ let bridge;
62
+ try {
63
+ bridge = await createMCPBridge({ configPaths: [configPath], ...mcpStartOpts(), timeout: timeoutMs, callTimeout: timeoutMs, confirmServer: () => true, allow: { [server]: ['issue_read'] } });
64
+ const failed = bridge.errors.find((e) => e.server === server);
65
+ if (failed) return { ok: false, error: `${server} did not start: ${firstLine(failed.error)}` };
66
+ const lacking = bridge.missing?.[0];
67
+ if (lacking) return { ok: false, error: `${server} does not offer ${lacking.tool}` };
68
+ const prefix = `${server}_`;
69
+ const tool = bridge.tools.find((t) => t.name === `${prefix}issue_read`);
70
+ if (!tool) return { ok: false, error: `${server} does not offer issue_read` };
71
+ const call = { tool: 'issue_read', owner, repo, issue_number: number };
72
+ const record = { server, exposed: bridge.tools.map((t) => t.name), missing: bridge.missing ?? [], calls: [call] };
73
+ const url = list.ticketUrl(number);
74
+ let reply;
75
+ try {
76
+ reply = await tool.execute({ method: 'get', owner, repo, issue_number: number });
77
+ } catch (e) {
78
+ return { ok: false, error: `${server}: issue_read failed: ${firstLine(e)}` };
79
+ }
80
+ const text = typeof reply === 'string' ? reply : (Array.isArray(reply) ? reply : []).map((c) => c?.text ?? '').join('');
81
+ if (isDeviceLogin(text)) return { ok: false, error: 'GitHub token unavailable — the server asked for a login (is pass locked?)' };
82
+ if (text.trim() === '') return { ok: false, error: `${server}: issue_read returned nothing for ${url}` };
83
+ return { ok: true, text, url, record };
84
+ } catch (e) {
85
+ return { ok: false, error: startRefusal(server, e) };
86
+ } finally {
87
+ try { await bridge?.close(); } catch { /* already closed */ }
88
+ }
89
+ }
@@ -0,0 +1,33 @@
1
+ // M13 piece 4 (hamr ruling R2, 2026-10-31): a by-hand Run on a Tickets job has no ticket # box. It reads the NEWEST ticket that has not run yet; the run then reads it through the
2
+ // job's filter as always (a non-match ends skipped, grey, $0). Nothing new = one plain line at $0 and no run. "Has run" = this job's own runs hold the number (`run.json`
3
+ // `inputs[].ticket.number`, a skipped run included); "newest" is the schedule's own look (`lookTickets`, the job's signed `list_issues`, newest first, open tickets).
4
+ // A job with no ticket run yet takes the newest open ticket of the first page (item 6: the first run reads the newest ticket at the time it starts; older ones never run).
5
+ import { join } from 'node:path';
6
+
7
+ import { listRunIds } from './flow.js';
8
+ import { readRunInputs } from './runfile.js';
9
+ import { lookTickets } from './trigger-tickets.js';
10
+
11
+ /** the ticket numbers this job's runs have read @param {string} flowDir @returns {Set<number>} */
12
+ export function ranTicketNumbers(flowDir) {
13
+ const out = new Set();
14
+ for (const id of listRunIds(flowDir)) {
15
+ const got = readRunInputs(join(flowDir, 'runs', id));
16
+ if (!got.ok) continue;
17
+ for (const e of got.entries) if (Number.isInteger(e?.ticket?.number)) out.add(e.ticket.number);
18
+ }
19
+ return out;
20
+ }
21
+
22
+ /**
23
+ * @param {{flowDir: string, listUrl: string, mcp: {server: string, tool: string}, configPath?: string, look?: typeof lookTickets}} o `look` is a test seam
24
+ * @returns {Promise<{ok: true, number: number} | {ok: false, say: string}>}
25
+ */
26
+ export async function newestUnrunTicket({ flowDir, listUrl, mcp, configPath, look = lookTickets }) {
27
+ const ran = ranTicketNumbers(flowDir);
28
+ const r = await look({ listUrl, mcp, ...(configPath ? { configPath } : {}), seen: ran.size === 0 ? null : ran, last: new Map(), watch: [] });
29
+ if (!r.ok) return { ok: false, say: String(r.error) };
30
+ const numbers = r.found.map((f) => f.number);
31
+ if (numbers.length === 0) return { ok: false, say: ran.size === 0 ? `No open ticket at ${listUrl}.` : `Nothing new: no ticket newer than #${Math.max(...ran)} has come in.` };
32
+ return { ok: true, number: Math.max(...numbers) };
33
+ }
@@ -0,0 +1,33 @@
1
+ // M12 (docs/wiki/the-module-ladder.md, "M12 scope (restart)" items 5, 7): the signed SHAPES of a ticket job, in one file with no imports so the signing, schedule and
2
+ // declaration code can read them without reaching the MCP bridge. The ticket list address (`tickets:<list page URL>`, a GitHub issues page), the watchable fields.
3
+
4
+ /** The fields a signed schedule may watch (item 7): typed values the list already carries. */
5
+ export const WATCHABLE = Object.freeze(['state', 'labels']);
6
+
7
+ /** the shape of a ticket list address: owner and repo are the two groups */
8
+ export const LIST_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/issues\/?$/;
9
+
10
+ /**
11
+ * The one reader of a ticket list address: its owner and repo and the address of one ticket on it, or the one refusal every caller shows.
12
+ * @param {unknown} listUrl @returns {{ok: true, owner: string, repo: string, ticketUrl: (number: number) => string} | {ok: false, error: string}}
13
+ */
14
+ export function parseTicketList(listUrl) {
15
+ const text = String(listUrl).trim();
16
+ const m = LIST_URL.exec(text);
17
+ if (!m) return { ok: false, error: `${listUrl} is not a GitHub issues address (the issues page of one repository)` };
18
+ return { ok: true, owner: m[1], repo: m[2], ticketUrl: (number) => `${text.replace(/\/$/, '')}/${number}` };
19
+ }
20
+
21
+ /** The ticket lists a signed job names: role -> address, for every page input whose address has the list shape. @param {{sources?: Array<{role: string, kind?: string, path: string}>}} arbiter @returns {Record<string, string>} */
22
+ export function ticketListsOf(arbiter) {
23
+ return Object.fromEntries((arbiter?.sources ?? []).filter((s) => s.kind === 'page' && LIST_URL.test(String(s.path).trim())).map((s) => [s.role, String(s.path).trim()]));
24
+ }
25
+
26
+ /** M13 piece 7 (9.7): the one cap on a ticket number, 10 digits. Every door that takes or reads a ticket number uses `isTicketNumber`. Under 2^53, so a safe JS number. */
27
+ export const TICKET_MAX = 9_999_999_999;
28
+
29
+ /** The one check of a ticket number: a whole number from 1 to `TICKET_MAX`. @param {unknown} n @returns {n is number} */
30
+ export const isTicketNumber = (n) => Number.isSafeInteger(n) && /** @type {number} */ (n) >= 1 && /** @type {number} */ (n) <= TICKET_MAX;
31
+
32
+ /** The words every refusal of a ticket number uses. */
33
+ export const TICKET_NUMBER_WORDS = `a whole number from 1 to ${TICKET_MAX.toLocaleString('en-US')}`;
@@ -19,7 +19,7 @@ import { dirname } from 'node:path';
19
19
  import { appendRow, ledgerText } from './jsonl-append.js';
20
20
 
21
21
  /** @typedef {{kind:'daily'|'weekdays', hour:number, minute:number} | {kind:'weekly', day:string, hour:number, minute:number}} Schedule */
22
- /** @typedef {{id:string, kind:'armed'|'fire', at:number, slot?:number, catchUp?:boolean, missed?:number, sig?:string}} ClockRow */
22
+ /** @typedef {{id:string, kind:'armed'|'fire', at:number, slot?:number, catchUp?:boolean, missed?:number, sig?:string, ticketN?:number}} ClockRow */
23
23
  /** @typedef {{fire:boolean, catchUp:boolean, missed:number, slot?:number}} Due */
24
24
 
25
25
  /** A slot seen MORE than this after its set time is a catch-up (M9 am2 item 1). Exactly this late is on time. */
@@ -129,9 +129,9 @@ function appendOnce(file, row, sig) {
129
129
  appendRow(file, sig === undefined ? row : { ...row, sig });
130
130
  }
131
131
 
132
- /** The trigger was set at `now`: no slot before this ever fires. @param {string} file @param {number} now @param {string} [sig] */
133
- export function armTrigger(file, now, sig) {
134
- appendOnce(file, { id: `armed:${now}`, kind: 'armed', at: now }, sig);
132
+ /** The trigger was set at `now`: no slot before this ever fires. M13 piece 5: `ticketN` = the highest ticket number the first green run read; a ticket schedule's first look baselines only tickets up to it. @param {string} file @param {number} now @param {string} [sig] @param {number} [ticketN] */
133
+ export function armTrigger(file, now, sig, ticketN) {
134
+ appendOnce(file, { id: `armed:${now}`, kind: 'armed', at: now, ...(Number.isInteger(ticketN) ? { ticketN } : {}) }, sig);
135
135
  }
136
136
 
137
137
  /**
@@ -18,6 +18,7 @@ import {
18
18
  } from 'node:fs';
19
19
  import { basename, dirname, join } from 'node:path';
20
20
  import { createHash } from 'node:crypto';
21
+ import { compareNatural } from './natural.js';
21
22
 
22
23
  import { appendRow, ledgerText } from './jsonl-append.js';
23
24
 
@@ -35,7 +36,7 @@ export function readSeen(file, sig) {
35
36
  }
36
37
 
37
38
  /** The ONE appender: write-once by id within a signing (a second row with the same id is not written). Starts on a fresh line when the file does not end in a newline (a torn last line). @param {string} file @param {SeenRow} row @param {string} [sig] stamped on the row @returns {boolean} written */
38
- function appendSeen(file, row, sig) {
39
+ export function appendSeen(file, row, sig) {
39
40
  if (readSeen(file, sig).some((r) => r.id === row.id)) return false;
40
41
  mkdirSync(dirname(file), { recursive: true });
41
42
  appendRow(file, sig === undefined ? row : { ...row, sig });
@@ -78,13 +79,12 @@ export function recordDropped(ledger, item, why, at, sig) {
78
79
  }
79
80
 
80
81
  /**
81
- * The queue: arrived and neither ran nor dropped, oldest arrival first. Identical arrival times: by name, then by sha (deterministic).
82
+ * The queue: arrived and neither ran nor dropped, oldest arrival first. Identical arrival times: by name, then by sha (deterministic); numbers inside a name compare as numbers (`#8` before `#10`).
82
83
  * @param {SeenRow[]} rows @returns {(SeenRow & {path:string})[]}
83
84
  */
84
85
  export function queueOf(rows) {
85
- const cmp = (/** @type {string} */ x, /** @type {string} */ y) => (x < y ? -1 : x > y ? 1 : 0);
86
86
  return /** @type {any} */ (rows.filter((r) => waiting(rows, r)))
87
- .sort((x, y) => x.at - y.at || cmp(x.name, y.name) || cmp(x.sha, y.sha));
87
+ .sort((x, y) => x.at - y.at || compareNatural(x.name, y.name) || compareNatural(x.sha, y.sha));
88
88
  }
89
89
 
90
90
  /**
@@ -15,7 +15,7 @@ import { createHash } from 'node:crypto';
15
15
  import { validateSchedule } from './trigger-clock.js';
16
16
 
17
17
  /** @typedef {import('./trigger-clock.js').Schedule} Schedule */
18
- /** @typedef {Schedule | {kind:'file-updated', role:string, path:string} | {kind:'new-file', role:string, folder:string}} Trigger */
18
+ /** @typedef {Schedule | {kind:'file-updated', role:string, path:string} | {kind:'new-file', role:string, folder:string} | {kind:'new-ticket', role:string, list:string, server:string, tool:string, watch?:string[]}} Trigger */
19
19
 
20
20
  const LINE_RE = /^\s*guardrail:\s*trigger\b/i;
21
21
  const CLOCK_RE = /^(daily|weekdays) (\d{2}):(\d{2})$/;
@@ -52,6 +52,7 @@ export function triggerLine(t) {
52
52
  if (t.kind === 'daily' || t.kind === 'weekdays') return `guardrail: trigger ${t.kind} ${hhmm(t)}`;
53
53
  if (t.kind === 'weekly') return `guardrail: trigger weekly ${t.day} ${hhmm(t)}`;
54
54
  if (t.kind === 'file-updated') return `guardrail: trigger file-updated ${t.role} = file:${t.path}`;
55
+ if (t.kind === 'new-ticket') return `guardrail: trigger new-ticket ${t.role} = tickets:${t.list}`; // M12: written only for the row/reason words; the parser above never reads it back
55
56
  const f = /** @type {{role: string, folder: string}} */ (t);
56
57
  return `guardrail: trigger new-file ${f.role} = file:${f.folder}`;
57
58
  }
@@ -0,0 +1,238 @@
1
+ // M12 piece 2 (docs/wiki/the-module-ladder.md, "M12 scope (restart)" items 5-7, 12; PRD "Update 2026-10-29 (M12 design ...)"): the ticket trigger.
2
+ // Proven first in poc/mcp/f103/look.mjs (newest-first cursor walk, F103) and poc/mcp/f104/watch.mjs (watched fields, F104/F104b), borrowed here.
3
+ //
4
+ // This file only says WHAT is new on a ticket list: `lookTickets` is ONE $0 look through the user's own MCP server, started with `allow` = only the
5
+ // schedule's signed tool, and it writes nothing. The ledger rows (arrived / ran / baseline / unreadable) are the scheduler's, written by the functions
6
+ // below, the same rows as the file trigger's (src/trigger-files.js): a ticket is `sha: ticket:<number>` (a re-arrival by a watched change: `ticket:<number>:<n>`)
7
+ // and `name: #<number>`, so `queueOf`, `recordRan` and `recordDropped` work on it unchanged.
8
+ import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
9
+
10
+ import { configForServer, remoteRefusal, mcpStartOpts, startRefusal, firstLine, isDeviceLogin } from './ticket-mcp.js';
11
+ import { parseTicketList, isTicketNumber, TICKET_MAX } from './ticket-shape.js';
12
+ import { appendSeen, readSeen, queueOf } from './trigger-files.js';
13
+
14
+ /** A look every 15 minutes, fixed (item 8). */
15
+ export const TICKET_LOOK_MS = 15 * 60_000;
16
+ /** The most pages one look follows (a flood bigger than this is `unreadable`, never silently cut). */
17
+ const MAX_PAGES = 20;
18
+
19
+ /** @param {unknown} reply */
20
+ const textOf = (reply) => (typeof reply === 'string' ? reply : (Array.isArray(reply) ? reply : /** @type {any} */ (reply)?.content ?? []).map((/** @type {any} */ c) => c?.text ?? '').join(''));
21
+ /** @param {any} i */
22
+ const labelsOf = (i) => (Array.isArray(i?.labels) ? i.labels : []).map((/** @type {any} */ l) => (typeof l === 'string' ? l : l?.name)).filter((/** @type {unknown} */ n) => typeof n === 'string').sort();
23
+ /** @param {any} i the typed values of the watched fields */
24
+ export const watchedOf = (i) => ({ state: String(i?.state ?? '').toLowerCase(), labels: labelsOf(i) });
25
+
26
+ /**
27
+ * Why a ticket changed, in words, only for the watched fields; '' = nothing changed. @param {{state: string, labels: string[]}} prev @param {{state: string, labels: string[]}} cur @param {string[]} watch
28
+ */
29
+ export function reasonFor(prev, cur, watch) {
30
+ const r = [];
31
+ if (watch.includes('state') && prev.state !== cur.state) r.push(`state ${prev.state}→${cur.state}`);
32
+ if (watch.includes('labels')) {
33
+ for (const l of cur.labels) if (!prev.labels.includes(l)) r.push(`label added: ${l}`);
34
+ for (const l of prev.labels) if (!cur.labels.includes(l)) r.push(`label removed: ${l}`);
35
+ }
36
+ return r.join('; ');
37
+ }
38
+
39
+ /**
40
+ * One look. `seen` null = the first look after signing (the first page is the starting point, nothing runs). Otherwise newest first with the cursor, stopping at a seen
41
+ * number; with watched fields the walk goes on past it only as far as the oldest tracked ticket, comparing each tracked ticket's watched values with `last`.
42
+ * Every failure is `{ok:false, error}` naming its cause, at $0; none reads as "0 new".
43
+ * M13 piece 5 (F114f): `cut` (first look only) = the highest ticket number the job's first green run read. The first look goes on past a page whose tickets are all above it, so
44
+ * every ticket that came in after that run started is seen; `recordLook` then baselines the ones up to `cut` and lets the rest arrive.
45
+ * @param {{listUrl: string, mcp: {server: string, tool: string}, configPath?: string, seen: Set<number>|null, last: Map<number, {state: string, labels: string[]}>, watch: string[], cut?: number, perPage?: number, timeoutMs?: number}} o
46
+ * @returns {Promise<{ok: true, first: boolean, cut?: number, ignored?: number[], found: Array<{number: number, state: string, labels: string[], createdAt: string|null}>, changed: Array<{number: number, reason: string, state: string, labels: string[]}>, pages: number} | {ok: false, error: string}>}
47
+ */
48
+ export async function lookTickets({
49
+ listUrl, mcp, configPath: explicitConfig, seen, last, watch, cut, perPage = 10, timeoutMs = 90000,
50
+ }) {
51
+ const parsed = parseTicketList(listUrl);
52
+ if (!parsed.ok) return parsed;
53
+ const { owner, repo } = parsed;
54
+ const { server, tool } = mcp;
55
+ const { file: configPath, remote } = configForServer(server, explicitConfig);
56
+ if (!discoverServers([configPath]).has(server)) return { ok: false, error: `${server} is not in ~/.mcp.json` };
57
+ if (remote) return { ok: false, error: remoteRefusal(server) };
58
+ const first = seen === null;
59
+ let bridge;
60
+ try {
61
+ bridge = await createMCPBridge({ configPaths: [configPath], ...mcpStartOpts(), timeout: timeoutMs, callTimeout: timeoutMs, confirmServer: () => true, allow: { [server]: [tool] } });
62
+ const failed = bridge.errors.find((/** @type {any} */ e) => e.server === server);
63
+ if (failed) return { ok: false, error: `${server} did not start: ${firstLine(failed.error)}` };
64
+ if (bridge.missing?.[0]) return { ok: false, error: `${server} does not offer ${bridge.missing[0].tool}` };
65
+ const list = bridge.tools.find((/** @type {any} */ t) => t.name === `${server}_${tool}`);
66
+ if (!list) return { ok: false, error: `${server} does not offer ${tool}` };
67
+
68
+ /** @param {Record<string, unknown>} args @returns {Promise<{issues: any[], pageInfo?: any}|{error: string}>} one page; a page with no list is asked for once more (F103) */
69
+ const page = async (args) => {
70
+ let cause = 'no ticket list in the answer';
71
+ for (let n = 0; n < 2; n++) {
72
+ let text;
73
+ try { text = textOf(await list.execute(args)); } catch (e) { cause = `${server}: ${tool} failed: ${firstLine(e)}`; continue; }
74
+ if (isDeviceLogin(text)) return { error: 'GitHub token unavailable — is pass locked?' };
75
+ let o;
76
+ try { o = JSON.parse(text); } catch { o = null; }
77
+ if (o && Array.isArray(o.issues)) return o;
78
+ cause = text.trim() === '' ? 'no ticket list in the answer (it was empty)' : `no ticket list in the answer: ${firstLine(text)}`;
79
+ if (/^\S*Could not|error/i.test(text)) break; // an error text will not change by asking again
80
+ }
81
+ return { error: cause };
82
+ };
83
+
84
+ const found = [];
85
+ /** @type {number[]} */
86
+ const ignored = [];
87
+ /** @type {Array<{number: number, reason: string, state: string, labels: string[]}>} */
88
+ const changed = [];
89
+ const tracked = new Set(first ? [] : last.keys());
90
+ const oldestTracked = tracked.size > 0 ? Math.min(...tracked) : Infinity;
91
+ const stillNeeded = new Set(tracked);
92
+ let after;
93
+ let pages = 0;
94
+ let hitSeen = false;
95
+ // M13 item 6: a ticket is new only if its number is higher than the highest seen (closed seen tickets leave an OPEN-only list; older open ones are not new)
96
+ const maxSeen = first ? 0 : Math.max(0, ...seen);
97
+ for (;;) {
98
+ const args = {
99
+ owner, repo, orderBy: 'CREATED_AT', direction: 'DESC', perPage, ...(watch.length === 0 ? { state: 'OPEN' } : {}), fields: ['number', 'created_at', 'state', 'labels'], ...(after ? { after } : {}),
100
+ };
101
+ // eslint-disable-next-line no-await-in-loop
102
+ const r = await page(args);
103
+ if ('error' in r) return { ok: false, error: r.error };
104
+ pages++;
105
+ if (pages === 1 && r.issues.length === 0) return { ok: false, error: `the list at ${listUrl} came back empty; an empty list is unreadable, not "no new tickets"` };
106
+ let lowest = Infinity;
107
+ for (const i of r.issues) {
108
+ const n = i.number;
109
+ if (!Number.isInteger(n)) continue;
110
+ // M13 piece 7 (9.7): a number over the one cap is ignored, never a crash; the look records one reason
111
+ if (!isTicketNumber(n)) { ignored.push(n); continue; }
112
+ lowest = Math.min(lowest, n);
113
+ const rec = { number: n, ...watchedOf(i), createdAt: typeof i.created_at === 'string' ? i.created_at : null };
114
+ if (first) { found.push(rec); continue; }
115
+ if (seen.has(n)) {
116
+ hitSeen = true;
117
+ const prev = last.get(n);
118
+ stillNeeded.delete(n);
119
+ if (prev && watch.length > 0) {
120
+ const reason = reasonFor(prev, rec, watch);
121
+ if (reason) changed.push({ number: n, reason, state: rec.state, labels: rec.labels });
122
+ }
123
+ } else if (!hitSeen && n > maxSeen) found.push(rec);
124
+ }
125
+ if (first && (cut === undefined || lowest <= cut)) break;
126
+ const done = (hitSeen || lowest <= maxSeen) && (watch.length === 0 || stillNeeded.size === 0 || lowest < oldestTracked);
127
+ if (done || !r.pageInfo?.hasNextPage || !r.pageInfo?.endCursor) break;
128
+ if (pages >= MAX_PAGES) return { ok: false, error: `more than ${MAX_PAGES} pages of new tickets in one look` };
129
+ after = r.pageInfo.endCursor;
130
+ }
131
+ return {
132
+ ok: true, first, ...(first && cut !== undefined ? { cut } : {}), ...(ignored.length ? { ignored } : {}), found, changed: changed.sort((a, b) => a.number - b.number), pages,
133
+ };
134
+ } catch (e) {
135
+ return { ok: false, error: startRefusal(server, e) };
136
+ } finally {
137
+ try { await bridge?.close(); } catch { /* already closed */ }
138
+ }
139
+ }
140
+
141
+ // ---- the ledger rows (THE writers; only the scheduler calls them) ----------------------------------------------------------------------------------------------
142
+
143
+ /** The numbers a signing has a baseline or an arrived row for. @param {string} ledger @param {string} sig */
144
+ export function seenNumbers(ledger, sig) {
145
+ return new Set(readSeen(ledger, sig).filter((r) => (r.kind === 'baseline' || r.kind === 'arrived') && Number.isInteger(/** @type {any} */ (r).number)).map((r) => /** @type {any} */ (r).number));
146
+ }
147
+ /** Last-seen watched values per number: the newest baseline/arrived row's. @param {string} ledger @param {string} sig @returns {Map<number, {state: string, labels: string[]}>} */
148
+ export function lastSeen(ledger, sig) {
149
+ const m = new Map();
150
+ for (const r of /** @type {any[]} */ (readSeen(ledger, sig))) if ((r.kind === 'baseline' || r.kind === 'arrived') && r.watch) m.set(r.number, r.watch);
151
+ return m;
152
+ }
153
+ /** Has this signing had its first look (its baseline written)? @param {string} ledger @param {string} sig */
154
+ /**
155
+ * M13 item 9b.3: the cause of the newest look when it could not read, else null. The newest look row decides: an `unreadable` row is the problem until a later look reads
156
+ * (its `looked`, `baseline` or `arrived` row). @param {import('./trigger-files.js').SeenRow[]} rows @returns {{at: number, why: string}|null}
157
+ */
158
+ export function lookProblemOf(rows) {
159
+ const last = /** @type {any[]} */ (rows).findLast((r) => r.kind === 'unreadable' || r.kind === 'looked' || r.kind === 'baseline' || r.kind === 'arrived');
160
+ return last?.kind === 'unreadable' ? { at: last.at, why: String(last.why ?? 'it could not read the list') } : null;
161
+ }
162
+ export const hasBaseline = (ledger, sig) => readSeen(ledger, sig).some((r) => r.kind === 'baseline');
163
+
164
+ /**
165
+ * Write what a look found, once. First look: a `baseline` row per ticket on the page (never runs). Later: an `arrived` row per new ticket, oldest first (its arrival
166
+ * time is this clock), and one `arrived` row per watched change with its `reason`. A look that could not read writes one `unreadable` row with its cause.
167
+ * @param {string} ledger @param {string} sig @param {Awaited<ReturnType<typeof lookTickets>>} look @param {number} at
168
+ * @returns {{arrived: number[], unreadable: string|null}}
169
+ */
170
+ export function recordLook(ledger, sig, look, at) {
171
+ if (!look.ok) {
172
+ appendSeen(ledger, /** @type {any} */ ({ id: `unreadable:${at}`, kind: 'unreadable', sha: `unreadable:${at}`, name: '', size: 0, at, why: look.error }), sig);
173
+ return { arrived: [], unreadable: look.error };
174
+ }
175
+ // a look that read, after one that could not: one `looked` row ends the problem even when nothing is new (the only look row that is not found tickets)
176
+ // M13 piece 7 (9.7): ticket numbers over the cap were ignored by the look; ONE reason is recorded on the same row
177
+ const note = look.ignored?.length ? `ignored ${look.ignored.length} ticket number${look.ignored.length === 1 ? '' : 's'} over ${TICKET_MAX.toLocaleString('en-US')}: ${look.ignored.slice(0, 5).join(', ')}` : null;
178
+ if (note !== null || lookProblemOf(readSeen(ledger, sig))) appendSeen(ledger, /** @type {any} */ ({ id: `looked:${at}`, kind: 'looked', sha: `looked:${at}`, name: '', size: 0, at, ...(note !== null ? { why: note } : {}) }), sig);
179
+ const arrived = [];
180
+ const watch = (/** @type {{state: string, labels: string[]}} */ w) => ({ state: w.state, labels: w.labels });
181
+ if (look.first) {
182
+ for (const i of [...look.found].reverse()) {
183
+ if (look.cut !== undefined && i.number > look.cut) {
184
+ // M13 piece 5 (F114f): above the number the first green run read = it came in after that run began, so it runs once the schedule is on
185
+ appendSeen(ledger, /** @type {any} */ ({
186
+ id: `arrived:ticket:${i.number}`, kind: 'arrived', sha: `ticket:${i.number}`, name: `#${i.number}`, path: `#${i.number}`, size: 0, at, number: i.number, watch: watch(i),
187
+ }), sig);
188
+ arrived.push(i.number);
189
+ continue;
190
+ }
191
+ appendSeen(ledger, /** @type {any} */ ({
192
+ id: `baseline:ticket:${i.number}`, kind: 'baseline', sha: `ticket:${i.number}`, name: `#${i.number}`, path: `#${i.number}`, size: 0, at, number: i.number, watch: watch(i),
193
+ }), sig);
194
+ }
195
+ return { arrived, unreadable: null };
196
+ }
197
+ for (const i of [...look.found].reverse()) {
198
+ appendSeen(ledger, /** @type {any} */ ({
199
+ id: `arrived:ticket:${i.number}`, kind: 'arrived', sha: `ticket:${i.number}`, name: `#${i.number}`, path: `#${i.number}`, size: 0, at, number: i.number, watch: watch(i),
200
+ }), sig);
201
+ arrived.push(i.number);
202
+ }
203
+ for (const c of look.changed) {
204
+ const rows = readSeen(ledger, sig);
205
+ if (queueOf(rows).some((q) => /** @type {any} */ (q).number === c.number)) {
206
+ // already waiting: the queued run reads the ticket as it is when it starts, so no second run. Advance the last-seen value (a `baseline` row, same writer) so the
207
+ // next look does not re-fire this same change once that run has started; a LATER change still differs from it and arrives once.
208
+ const b = rows.filter((r) => r.kind === 'baseline' && /** @type {any} */ (r).number === c.number).length;
209
+ appendSeen(ledger, /** @type {any} */ ({
210
+ id: `baseline:ticket:${c.number}:${b}`, kind: 'baseline', sha: `ticket:${c.number}`, name: `#${c.number}`, path: `#${c.number}`, size: 0, at, number: c.number, watch: watch(c),
211
+ }), sig);
212
+ continue;
213
+ }
214
+ const n = rows.filter((r) => r.kind === 'arrived' && /** @type {any} */ (r).number === c.number).length;
215
+ appendSeen(ledger, /** @type {any} */ ({
216
+ id: `arrived:ticket:${c.number}:${n}`, kind: 'arrived', sha: `ticket:${c.number}:${n}`, name: `#${c.number}`, path: `#${c.number}`, size: 0, at, number: c.number, watch: watch(c), reason: c.reason,
217
+ }), sig);
218
+ arrived.push(c.number);
219
+ }
220
+ return { arrived, unreadable: null };
221
+ }
222
+
223
+ /**
224
+ * M12 piece 3 (item 9): "Run it anyway" — ONE `arrived` row for a skipped ticket, carrying the person's reason, so the queue starts it as a new arrival on a later tick.
225
+ * Same row shape and id series as a watched change (the count of this number's arrived rows). Nothing is written while this number is still queued (a second click
226
+ * is refused, never a second run). @param {string} ledger @param {string} sig @param {{number: number, reason: string}} a @param {number} at
227
+ * @returns {{ok: true} | {ok: false, say: string}}
228
+ */
229
+ export function recordAnyway(ledger, sig, a, at) {
230
+ const rows = readSeen(ledger, sig);
231
+ if (queueOf(rows).some((q) => /** @type {any} */ (q).number === a.number)) return { ok: false, say: `Ticket #${a.number} is already queued. Nothing more was queued.` };
232
+ const n = rows.filter((r) => r.kind === 'arrived' && /** @type {any} */ (r).number === a.number).length;
233
+ const watch = lastSeen(ledger, sig).get(a.number);
234
+ appendSeen(ledger, /** @type {any} */ ({
235
+ id: `arrived:ticket:${a.number}:${n}`, kind: 'arrived', sha: `ticket:${a.number}:${n}`, name: `#${a.number}`, path: `#${a.number}`, size: 0, at, number: a.number, ...(watch ? { watch } : {}), reason: a.reason, anyway: true,
236
+ }), sig);
237
+ return { ok: true };
238
+ }