fwdloop 0.26.2 → 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.
- package/bin/fwdloop +23 -3
- package/package.json +1 -1
- package/src/authoring.js +10 -0
- package/src/canrun.js +20 -0
- package/src/declaration.js +98 -2
- package/src/drafter.js +23 -10
- package/src/learnstore.js +1 -1
- package/src/panel/author.js +18 -2
- package/src/panel/authorflows.js +9 -4
- package/src/panel/authorstart.js +10 -6
- package/src/panel/authortrigger.js +34 -10
- package/src/panel/data.js +39 -4
- package/src/panel/index.html +516 -60
- package/src/panel/scheduler.js +42 -6
- package/src/panel/server.js +21 -5
- package/src/panel/tickets.js +113 -0
- package/src/runner.js +51 -10
- package/src/schedule.js +5 -0
- package/src/summary-words.js +12 -4
- package/src/ticket-draft.js +87 -0
- package/src/ticket-labels.js +65 -0
- package/src/ticket-mcp.js +66 -0
- package/src/ticket-shape.js +24 -0
- package/src/trigger-files.js +1 -1
- package/src/trigger-line.js +2 -1
- package/src/trigger-tickets.js +209 -0
- package/types/canrun.d.ts +14 -0
- package/types/drafter.d.ts +186 -64
- package/types/panel/author.d.ts +8 -0
- package/types/panel/authorflows.d.ts +2 -0
- package/types/panel/authorstart.d.ts +3 -1
- package/types/panel/authortrigger.d.ts +11 -1
- package/types/panel/data.d.ts +22 -3
- package/types/panel/scheduler.d.ts +7 -2
- package/types/panel/server.d.ts +9 -2
- package/types/panel/tickets.d.ts +81 -0
- package/types/runner.d.ts +21 -3
- package/types/summary-words.d.ts +2 -1
- package/types/ticket-draft.d.ts +96 -0
- package/types/ticket-labels.d.ts +36 -0
- package/types/ticket-mcp.d.ts +40 -0
- package/types/ticket-shape.d.ts +25 -0
- package/types/trigger-files.d.ts +2 -0
- package/types/trigger-line.d.ts +7 -0
- package/types/trigger-tickets.d.ts +91 -0
|
@@ -0,0 +1,87 @@
|
|
|
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 { USER_MCP_CONFIG } from './ticket-mcp.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
|
+
/**
|
|
19
|
+
* M12 piece 3: the ONE reader of a by-hand ticket number (a Run or a Sign & run body) and the ONE writer of its refusals. A whole number from 1, or null.
|
|
20
|
+
* @param {unknown} v @returns {number|null}
|
|
21
|
+
*/
|
|
22
|
+
export const ticketNumberOf = (v) => (typeof v === 'string' && /^[1-9][0-9]{0,8}$/.test(v.trim()) ? Number(v.trim()) : (Number.isInteger(v) && /** @type {number} */ (v) >= 1 ? /** @type {number} */ (v) : null));
|
|
23
|
+
|
|
24
|
+
/** the refusals of a by-hand start's ticket box: a ticket job needs a number; any other job takes none. @param {string|null} ticketRole @param {any} body @returns {{field: string, say: string}[]} */
|
|
25
|
+
export function ticketRefusals(ticketRole, body) {
|
|
26
|
+
if (ticketRole !== null && ticketNumberOf(body?.ticket) === null) return [{ field: 'ticket', say: `This job reads one ticket of "${ticketRole}" per run. Give its ticket number (a whole number from 1). Nothing started.` }];
|
|
27
|
+
if (ticketRole === null && Object.hasOwn(body ?? {}, 'ticket') && body.ticket !== undefined) return [{ field: 'ticket', say: 'This job has no ticket list, so there is no ticket number to give. Nothing started.' }];
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** the server names in the user's own `~/.mcp.json` (what the drafter may name); none when the file is missing or unreadable @param {string} [configPath] @returns {string[]} */
|
|
32
|
+
export function userMcpServers(configPath = USER_MCP_CONFIG()) {
|
|
33
|
+
try { return [...discoverServers([configPath]).keys()]; } catch { return []; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The lines under "Inputs" for one ticket role. The first is F90c's, word for word; the rest tell the drafter the two optional fields it may suggest.
|
|
38
|
+
* @param {string} role @param {string[]} servers @returns {string[]}
|
|
39
|
+
*/
|
|
40
|
+
export function ticketFactsLines(role, servers) {
|
|
41
|
+
return [
|
|
42
|
+
`- ${role}: one ticket's text (a signed input, already frozen at run start; read it by listing "${role}" in a step's reads, do not fetch it)`,
|
|
43
|
+
` The ticket is read through the job's MCP tool "${TICKET_TOOL}" (read-only). Declare the top-level "mcp": {"server": one of ${servers.join(', ')}, "tools": ["${TICKET_TOOL}"]} and put "${TICKET_TOOL}" in "mcpTools" of the step that reads "${role}"; no other step gets it.`,
|
|
44
|
+
' You may SUGGEST a top-level "ticketFilter": {"priority": [P0 to P3 values], "labels": [label names]} ONLY for a guardrail that names a priority or a label (for example "priority P2 only", "only issues labelled bug"); leave it out for any other guardrail, which stays hitl. A human signs it and code decides at run; never invent a label.',
|
|
45
|
+
' You may SUGGEST a top-level "ticketWatch": ["state", "labels"] (one or both) ONLY for a guardrail that says to run a ticket again when its state or its labels change. Any other thing to watch cannot be put there: leave it out and it stays hitl.',
|
|
46
|
+
];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** the schema parts a job with a ticket role adds: top-level `mcp` and `ticketFilter`, per-step `mcpTools` @param {string[]} servers */
|
|
50
|
+
export function ticketSchemaParts(servers) {
|
|
51
|
+
return {
|
|
52
|
+
top: {
|
|
53
|
+
mcp: {
|
|
54
|
+
type: 'object',
|
|
55
|
+
properties: { server: { type: 'string', enum: servers }, tools: { type: 'array', items: { type: 'string', enum: [TICKET_TOOL] } } },
|
|
56
|
+
required: ['server', 'tools'],
|
|
57
|
+
additionalProperties: false,
|
|
58
|
+
description: `the MCP server (from the person's ~/.mcp.json) and the tools the job uses: ["${TICKET_TOOL}"]`,
|
|
59
|
+
},
|
|
60
|
+
ticketFilter: {
|
|
61
|
+
type: 'object',
|
|
62
|
+
properties: {
|
|
63
|
+
priority: { type: 'array', items: { type: 'string', enum: ['P0', 'P1', 'P2', 'P3'] }, description: 'priorities a ticket must have; only when a guardrail names them' },
|
|
64
|
+
labels: { type: 'array', items: { type: 'string' }, description: 'label names, one of which a ticket must carry; only when a guardrail names them' },
|
|
65
|
+
},
|
|
66
|
+
additionalProperties: false,
|
|
67
|
+
description: 'optional: suggest only for a guardrail that names a priority or a label',
|
|
68
|
+
},
|
|
69
|
+
ticketWatch: { type: 'array', items: { type: 'string', enum: ['state', 'labels'] }, description: 'optional: suggest only for a guardrail that says to run a ticket again when its state or its labels change' },
|
|
70
|
+
},
|
|
71
|
+
step: { mcpTools: { type: 'array', items: { type: 'string', enum: [TICKET_TOOL] }, description: `["${TICKET_TOOL}"] on the step that reads the ticket; omit on every other step` } },
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Reds a draft with a ticket role must not pass with: no `mcp`, a server the person's config does not have, or no step that reads the ticket and holds the tool.
|
|
77
|
+
* @param {Record<string, any>} declaration @param {Array<{role: string}>} ticketSources @param {string[]} servers @returns {string[]}
|
|
78
|
+
*/
|
|
79
|
+
export function ticketReds(declaration, ticketSources, servers) {
|
|
80
|
+
const reds = [];
|
|
81
|
+
const roles = ticketSources.map((s) => s.role);
|
|
82
|
+
if (!declaration.mcp) return [`declaration: the job reads the ticket input "${roles[0]}" but lists no "mcp" server and tools`];
|
|
83
|
+
if (!servers.includes(declaration.mcp.server)) reds.push(`declaration: mcp.server "${declaration.mcp.server}" is not a server in your ~/.mcp.json (${servers.join(', ')})`);
|
|
84
|
+
const reader = (declaration.steps ?? []).some((st) => (st.mcpTools ?? []).includes(TICKET_TOOL) && (st.reads ?? []).some((r) => roles.includes(r)));
|
|
85
|
+
if (!reader) reds.push(`declaration: no step reads "${roles[0]}" and lists "${TICKET_TOOL}" in mcpTools`);
|
|
86
|
+
return reds;
|
|
87
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
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
|
+
* @param {{text: string, filter?: {priority?: string[], labels?: string[]}}} a `filter` = the job's signed `ticketFilter` (or absent)
|
|
44
|
+
* @returns {{outcome: 'run', unsure?: string}|{outcome: 'skip', reason: string}}
|
|
45
|
+
*/
|
|
46
|
+
export function decideTicket({ text, filter }) {
|
|
47
|
+
const t = readTicketFields(text);
|
|
48
|
+
if (!t.ok) return { outcome: 'run', unsure: 'the ticket text is not readable as fields, so no label could be checked' };
|
|
49
|
+
if (t.state === 'closed') return { outcome: 'skip', reason: 'closed' };
|
|
50
|
+
if (!filter) return { outcome: 'run' };
|
|
51
|
+
/** @type {string|undefined} */
|
|
52
|
+
let unsure;
|
|
53
|
+
if (filter.priority?.length) {
|
|
54
|
+
const want = filter.priority.join(' or ');
|
|
55
|
+
const p = priorityOf(t.labels);
|
|
56
|
+
if (p === 'none') return { outcome: 'skip', reason: `no ${want} label` };
|
|
57
|
+
if (p === 'unsure') unsure = 'a priority label is not on the P0-P3 scale, or two priorities are present';
|
|
58
|
+
else if (!filter.priority.includes(p)) return { outcome: 'skip', reason: `priority ${p}, not ${want}` };
|
|
59
|
+
}
|
|
60
|
+
if (filter.labels?.length) {
|
|
61
|
+
const have = new Set(t.labels.map((l) => l.trim().toLowerCase()));
|
|
62
|
+
if (!filter.labels.some((l) => have.has(l.trim().toLowerCase()))) return { outcome: 'skip', reason: `no ${filter.labels.join(' or ')} label` };
|
|
63
|
+
}
|
|
64
|
+
return unsure === undefined ? { outcome: 'run' } : { outcome: 'run', unsure };
|
|
65
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
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. A tool the server does not mark `readOnlyHint: true` is refused by name.
|
|
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 } from './ticket-shape.js';
|
|
11
|
+
|
|
12
|
+
/** the user's own MCP config, the only source of a tool */
|
|
13
|
+
export const USER_MCP_CONFIG = () => join(homedir(), '.mcp.json');
|
|
14
|
+
|
|
15
|
+
/** the first line of a message, secrets redacted, clipped: all a refusal ever shows of a server's own error */
|
|
16
|
+
export const firstLine = (e) => redactSecrets(String(e?.message ?? e ?? '')).split('\n').find((l) => l.trim() !== '')?.trim().slice(0, 200) ?? 'no message';
|
|
17
|
+
|
|
18
|
+
/** 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) */
|
|
19
|
+
export const isDeviceLogin = (text) => text.includes('github.com/login/device');
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Read ticket `number` of the list at `listUrl` with the job's `issue_read`.
|
|
23
|
+
* @param {{listUrl: string, number: number, mcp: {server: string, tools: string[]}, configPath?: string, timeoutMs?: number}} o
|
|
24
|
+
* @returns {Promise<{ok: true, text: string, url: string, record: {server: string, exposed: string[], missing: Array<{server: string, tool: string}>, calls: Array<{tool: string, owner: string, repo: string, issue_number: number}>}} | {ok: false, error: string}>}
|
|
25
|
+
* `record` is what the run keeps (in its `run.json` input entry): what the server exposed and lacked, and each call made.
|
|
26
|
+
*/
|
|
27
|
+
export async function readTicketMcp({ listUrl, number, mcp, configPath = USER_MCP_CONFIG(), timeoutMs = 90000 }) {
|
|
28
|
+
const list = parseTicketList(listUrl);
|
|
29
|
+
if (!list.ok) return list;
|
|
30
|
+
if (!Number.isInteger(number) || number < 1) return { ok: false, error: `ticket number ${JSON.stringify(number)} is not a whole number from 1` };
|
|
31
|
+
const { owner, repo } = list;
|
|
32
|
+
const { server, tools } = mcp;
|
|
33
|
+
if (!tools.includes('issue_read')) return { ok: false, error: `the job does not list issue_read, the tool that reads a ticket` };
|
|
34
|
+
if (!discoverServers([configPath]).has(server)) return { ok: false, error: `${server} is not in ~/.mcp.json` };
|
|
35
|
+
let bridge;
|
|
36
|
+
try {
|
|
37
|
+
bridge = await createMCPBridge({ configPaths: [configPath], timeout: timeoutMs, callTimeout: timeoutMs, confirmServer: () => true, allow: { [server]: tools } });
|
|
38
|
+
const failed = bridge.errors.find((e) => e.server === server);
|
|
39
|
+
if (failed) return { ok: false, error: `${server} did not start: ${firstLine(failed.error)}` };
|
|
40
|
+
const lacking = bridge.missing?.[0];
|
|
41
|
+
if (lacking) return { ok: false, error: `${server} does not offer ${lacking.tool}` };
|
|
42
|
+
const prefix = `${server}_`;
|
|
43
|
+
for (const t of bridge.tools) {
|
|
44
|
+
if (t.annotations?.readOnlyHint !== true) return { ok: false, error: `${server} does not mark ${t.name.slice(prefix.length)} read-only (readOnlyHint is not true)` };
|
|
45
|
+
}
|
|
46
|
+
const tool = bridge.tools.find((t) => t.name === `${prefix}issue_read`);
|
|
47
|
+
if (!tool) return { ok: false, error: `${server} does not offer issue_read` };
|
|
48
|
+
const call = { tool: 'issue_read', owner, repo, issue_number: number };
|
|
49
|
+
const record = { server, exposed: bridge.tools.map((t) => t.name), missing: bridge.missing ?? [], calls: [call] };
|
|
50
|
+
const url = list.ticketUrl(number);
|
|
51
|
+
let reply;
|
|
52
|
+
try {
|
|
53
|
+
reply = await tool.execute({ method: 'get', owner, repo, issue_number: number });
|
|
54
|
+
} catch (e) {
|
|
55
|
+
return { ok: false, error: `${server}: issue_read failed: ${firstLine(e)}` };
|
|
56
|
+
}
|
|
57
|
+
const text = typeof reply === 'string' ? reply : (Array.isArray(reply) ? reply : []).map((c) => c?.text ?? '').join('');
|
|
58
|
+
if (isDeviceLogin(text)) return { ok: false, error: 'GitHub token unavailable — the server asked for a login (is pass locked?)' };
|
|
59
|
+
if (text.trim() === '') return { ok: false, error: `${server}: issue_read returned nothing for ${url}` };
|
|
60
|
+
return { ok: true, text, url, record };
|
|
61
|
+
} catch (e) {
|
|
62
|
+
return { ok: false, error: `${server} did not start: ${firstLine(e)}` };
|
|
63
|
+
} finally {
|
|
64
|
+
try { await bridge?.close(); } catch { /* already closed */ }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
}
|
package/src/trigger-files.js
CHANGED
|
@@ -35,7 +35,7 @@ export function readSeen(file, sig) {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
/** 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) {
|
|
38
|
+
export function appendSeen(file, row, sig) {
|
|
39
39
|
if (readSeen(file, sig).some((r) => r.id === row.id)) return false;
|
|
40
40
|
mkdirSync(dirname(file), { recursive: true });
|
|
41
41
|
appendRow(file, sig === undefined ? row : { ...row, sig });
|
package/src/trigger-line.js
CHANGED
|
@@ -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,209 @@
|
|
|
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 { USER_MCP_CONFIG, firstLine, isDeviceLogin } from './ticket-mcp.js';
|
|
11
|
+
import { parseTicketList } 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
|
+
* @param {{listUrl: string, mcp: {server: string, tool: string}, configPath?: string, seen: Set<number>|null, last: Map<number, {state: string, labels: string[]}>, watch: string[], perPage?: number, timeoutMs?: number}} o
|
|
44
|
+
* @returns {Promise<{ok: true, first: boolean, 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}>}
|
|
45
|
+
*/
|
|
46
|
+
export async function lookTickets({
|
|
47
|
+
listUrl, mcp, configPath = USER_MCP_CONFIG(), seen, last, watch, perPage = 10, timeoutMs = 90000,
|
|
48
|
+
}) {
|
|
49
|
+
const parsed = parseTicketList(listUrl);
|
|
50
|
+
if (!parsed.ok) return parsed;
|
|
51
|
+
const { owner, repo } = parsed;
|
|
52
|
+
const { server, tool } = mcp;
|
|
53
|
+
if (!discoverServers([configPath]).has(server)) return { ok: false, error: `${server} is not in ~/.mcp.json` };
|
|
54
|
+
const first = seen === null;
|
|
55
|
+
let bridge;
|
|
56
|
+
try {
|
|
57
|
+
bridge = await createMCPBridge({ configPaths: [configPath], timeout: timeoutMs, callTimeout: timeoutMs, confirmServer: () => true, allow: { [server]: [tool] } });
|
|
58
|
+
const failed = bridge.errors.find((/** @type {any} */ e) => e.server === server);
|
|
59
|
+
if (failed) return { ok: false, error: `${server} did not start: ${firstLine(failed.error)}` };
|
|
60
|
+
if (bridge.missing?.[0]) return { ok: false, error: `${server} does not offer ${bridge.missing[0].tool}` };
|
|
61
|
+
for (const t of bridge.tools) if (t.annotations?.readOnlyHint !== true) return { ok: false, error: `${server} does not mark ${t.name.slice(`${server}_`.length)} read-only (readOnlyHint is not true)` };
|
|
62
|
+
const list = bridge.tools.find((/** @type {any} */ t) => t.name === `${server}_${tool}`);
|
|
63
|
+
if (!list) return { ok: false, error: `${server} does not offer ${tool}` };
|
|
64
|
+
|
|
65
|
+
/** @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) */
|
|
66
|
+
const page = async (args) => {
|
|
67
|
+
let cause = 'no ticket list in the answer';
|
|
68
|
+
for (let n = 0; n < 2; n++) {
|
|
69
|
+
let text;
|
|
70
|
+
try { text = textOf(await list.execute(args)); } catch (e) { cause = `${server}: ${tool} failed: ${firstLine(e)}`; continue; }
|
|
71
|
+
if (isDeviceLogin(text)) return { error: 'GitHub token unavailable — is pass locked?' };
|
|
72
|
+
let o;
|
|
73
|
+
try { o = JSON.parse(text); } catch { o = null; }
|
|
74
|
+
if (o && Array.isArray(o.issues)) return o;
|
|
75
|
+
cause = text.trim() === '' ? 'no ticket list in the answer (it was empty)' : `no ticket list in the answer: ${firstLine(text)}`;
|
|
76
|
+
if (/^\S*Could not|error/i.test(text)) break; // an error text will not change by asking again
|
|
77
|
+
}
|
|
78
|
+
return { error: cause };
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const found = [];
|
|
82
|
+
/** @type {Array<{number: number, reason: string, state: string, labels: string[]}>} */
|
|
83
|
+
const changed = [];
|
|
84
|
+
const tracked = new Set(first ? [] : last.keys());
|
|
85
|
+
const oldestTracked = tracked.size > 0 ? Math.min(...tracked) : Infinity;
|
|
86
|
+
const stillNeeded = new Set(tracked);
|
|
87
|
+
let after;
|
|
88
|
+
let pages = 0;
|
|
89
|
+
let hitSeen = false;
|
|
90
|
+
for (;;) {
|
|
91
|
+
const args = {
|
|
92
|
+
owner, repo, orderBy: 'CREATED_AT', direction: 'DESC', perPage, ...(watch.length === 0 ? { state: 'OPEN' } : {}), fields: ['number', 'created_at', 'state', 'labels'], ...(after ? { after } : {}),
|
|
93
|
+
};
|
|
94
|
+
// eslint-disable-next-line no-await-in-loop
|
|
95
|
+
const r = await page(args);
|
|
96
|
+
if ('error' in r) return { ok: false, error: r.error };
|
|
97
|
+
pages++;
|
|
98
|
+
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"` };
|
|
99
|
+
let lowest = Infinity;
|
|
100
|
+
for (const i of r.issues) {
|
|
101
|
+
const n = i.number;
|
|
102
|
+
if (!Number.isInteger(n)) continue;
|
|
103
|
+
lowest = Math.min(lowest, n);
|
|
104
|
+
const rec = { number: n, ...watchedOf(i), createdAt: typeof i.created_at === 'string' ? i.created_at : null };
|
|
105
|
+
if (first) { found.push(rec); continue; }
|
|
106
|
+
if (seen.has(n)) {
|
|
107
|
+
hitSeen = true;
|
|
108
|
+
const prev = last.get(n);
|
|
109
|
+
stillNeeded.delete(n);
|
|
110
|
+
if (prev && watch.length > 0) {
|
|
111
|
+
const reason = reasonFor(prev, rec, watch);
|
|
112
|
+
if (reason) changed.push({ number: n, reason, state: rec.state, labels: rec.labels });
|
|
113
|
+
}
|
|
114
|
+
} else if (!hitSeen) found.push(rec);
|
|
115
|
+
}
|
|
116
|
+
if (first) break;
|
|
117
|
+
const done = hitSeen && (watch.length === 0 || stillNeeded.size === 0 || lowest < oldestTracked);
|
|
118
|
+
if (done || !r.pageInfo?.hasNextPage || !r.pageInfo?.endCursor) break;
|
|
119
|
+
if (pages >= MAX_PAGES) return { ok: false, error: `more than ${MAX_PAGES} pages of new tickets in one look` };
|
|
120
|
+
after = r.pageInfo.endCursor;
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
ok: true, first, found, changed: changed.sort((a, b) => a.number - b.number), pages,
|
|
124
|
+
};
|
|
125
|
+
} catch (e) {
|
|
126
|
+
return { ok: false, error: `${server} did not start: ${firstLine(e)}` };
|
|
127
|
+
} finally {
|
|
128
|
+
try { await bridge?.close(); } catch { /* already closed */ }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// ---- the ledger rows (THE writers; only the scheduler calls them) ----------------------------------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
/** The numbers a signing has a baseline or an arrived row for. @param {string} ledger @param {string} sig */
|
|
135
|
+
export function seenNumbers(ledger, sig) {
|
|
136
|
+
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));
|
|
137
|
+
}
|
|
138
|
+
/** 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[]}>} */
|
|
139
|
+
export function lastSeen(ledger, sig) {
|
|
140
|
+
const m = new Map();
|
|
141
|
+
for (const r of /** @type {any[]} */ (readSeen(ledger, sig))) if ((r.kind === 'baseline' || r.kind === 'arrived') && r.watch) m.set(r.number, r.watch);
|
|
142
|
+
return m;
|
|
143
|
+
}
|
|
144
|
+
/** Has this signing had its first look (its baseline written)? @param {string} ledger @param {string} sig */
|
|
145
|
+
export const hasBaseline = (ledger, sig) => readSeen(ledger, sig).some((r) => r.kind === 'baseline');
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 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
|
|
149
|
+
* 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.
|
|
150
|
+
* @param {string} ledger @param {string} sig @param {Awaited<ReturnType<typeof lookTickets>>} look @param {number} at
|
|
151
|
+
* @returns {{arrived: number[], unreadable: string|null}}
|
|
152
|
+
*/
|
|
153
|
+
export function recordLook(ledger, sig, look, at) {
|
|
154
|
+
if (!look.ok) {
|
|
155
|
+
appendSeen(ledger, /** @type {any} */ ({ id: `unreadable:${at}`, kind: 'unreadable', sha: `unreadable:${at}`, name: '', size: 0, at, why: look.error }), sig);
|
|
156
|
+
return { arrived: [], unreadable: look.error };
|
|
157
|
+
}
|
|
158
|
+
const arrived = [];
|
|
159
|
+
const watch = (/** @type {{state: string, labels: string[]}} */ w) => ({ state: w.state, labels: w.labels });
|
|
160
|
+
if (look.first) {
|
|
161
|
+
for (const i of [...look.found].reverse()) {
|
|
162
|
+
appendSeen(ledger, /** @type {any} */ ({
|
|
163
|
+
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),
|
|
164
|
+
}), sig);
|
|
165
|
+
}
|
|
166
|
+
return { arrived, unreadable: null };
|
|
167
|
+
}
|
|
168
|
+
for (const i of [...look.found].reverse()) {
|
|
169
|
+
appendSeen(ledger, /** @type {any} */ ({
|
|
170
|
+
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),
|
|
171
|
+
}), sig);
|
|
172
|
+
arrived.push(i.number);
|
|
173
|
+
}
|
|
174
|
+
for (const c of look.changed) {
|
|
175
|
+
const rows = readSeen(ledger, sig);
|
|
176
|
+
if (queueOf(rows).some((q) => /** @type {any} */ (q).number === c.number)) {
|
|
177
|
+
// 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
|
|
178
|
+
// next look does not re-fire this same change once that run has started; a LATER change still differs from it and arrives once.
|
|
179
|
+
const b = rows.filter((r) => r.kind === 'baseline' && /** @type {any} */ (r).number === c.number).length;
|
|
180
|
+
appendSeen(ledger, /** @type {any} */ ({
|
|
181
|
+
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),
|
|
182
|
+
}), sig);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const n = rows.filter((r) => r.kind === 'arrived' && /** @type {any} */ (r).number === c.number).length;
|
|
186
|
+
appendSeen(ledger, /** @type {any} */ ({
|
|
187
|
+
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,
|
|
188
|
+
}), sig);
|
|
189
|
+
arrived.push(c.number);
|
|
190
|
+
}
|
|
191
|
+
return { arrived, unreadable: null };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* 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.
|
|
196
|
+
* 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
|
|
197
|
+
* is refused, never a second run). @param {string} ledger @param {string} sig @param {{number: number, reason: string}} a @param {number} at
|
|
198
|
+
* @returns {{ok: true} | {ok: false, say: string}}
|
|
199
|
+
*/
|
|
200
|
+
export function recordAnyway(ledger, sig, a, at) {
|
|
201
|
+
const rows = readSeen(ledger, sig);
|
|
202
|
+
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.` };
|
|
203
|
+
const n = rows.filter((r) => r.kind === 'arrived' && /** @type {any} */ (r).number === a.number).length;
|
|
204
|
+
const watch = lastSeen(ledger, sig).get(a.number);
|
|
205
|
+
appendSeen(ledger, /** @type {any} */ ({
|
|
206
|
+
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,
|
|
207
|
+
}), sig);
|
|
208
|
+
return { ok: true };
|
|
209
|
+
}
|
package/types/canrun.d.ts
CHANGED
|
@@ -19,6 +19,20 @@ export function unwiredRed(found: {
|
|
|
19
19
|
};
|
|
20
20
|
verb: string;
|
|
21
21
|
}): string;
|
|
22
|
+
/**
|
|
23
|
+
* M12 piece 1a (F105): the first tool the job lists (`declaration.mcp.tools`) that no step grants (`steps[].mcpTools`), or null. A job lists only the tools its
|
|
24
|
+
* steps use (PRD, hamr 2026-10-29); the ticket schedule's own tool lives in `schedule.json`, not here. A declaration without `mcp` has nothing to check.
|
|
25
|
+
* @param {Record<string, any>} declaration `readFlow`'s declaration @returns {{tool: string, server: string}|null}
|
|
26
|
+
*/
|
|
27
|
+
export function findUnusedMcpTool(declaration: Record<string, any>): {
|
|
28
|
+
tool: string;
|
|
29
|
+
server: string;
|
|
30
|
+
} | null;
|
|
31
|
+
/** The preflight refusal sentence for a job tool no step grants. @param {{tool: string, server: string}} found */
|
|
32
|
+
export function unusedMcpToolRed(found: {
|
|
33
|
+
tool: string;
|
|
34
|
+
server: string;
|
|
35
|
+
}): string;
|
|
22
36
|
/**
|
|
23
37
|
* M4e amendment 23: the ONE function that turns "this step's check cannot be built" into a plain sentence. It reads the shape, never
|
|
24
38
|
* bareguard's wording, so no `spec.` path or `checks[` index can reach a human. The steps are numbered by the job line they came from
|