bareloop 0.54.0 → 0.55.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/CHANGELOG.md +83 -0
- package/bareloop.context.md +73 -12
- package/package.json +3 -3
- package/src/authorflow.js +148 -46
- package/src/authoring.js +21 -4
- package/src/authorjob.js +82 -3
- package/src/authorreadout.js +20 -3
- package/src/authorrun.js +1 -1
- package/src/authorscout.js +9 -6
- package/src/bridges.js +4 -3
- package/src/cardschedule.js +42 -0
- package/src/carrystore.js +1 -1
- package/src/checkpick.js +576 -0
- package/src/checksuggest.js +28 -0
- package/src/checkwords.js +25 -0
- package/src/cli.js +1 -1
- package/src/config.js +24 -1
- package/src/declaredclose.js +1 -1
- package/src/destpoint.js +149 -0
- package/src/draftspend.js +39 -0
- package/src/factwords.js +14 -1
- package/src/job.js +81 -1
- package/src/jobblock.js +9 -0
- package/src/labelscan.js +11 -0
- package/src/launcher.js +10 -6
- package/src/learn.js +6 -4
- package/src/mcpchecks.js +52 -0
- package/src/mcppick.js +36 -0
- package/src/mcpsources.js +77 -0
- package/src/mcpuse.js +97 -0
- package/src/natural.js +23 -0
- package/src/pagemap.js +5 -2
- package/src/panel/authorroutes.js +90 -15
- package/src/panel/authorsession.js +183 -21
- package/src/panel/index.html +686 -26
- package/src/panel/jobgrid.js +117 -0
- package/src/panel/jobplan.js +31 -15
- package/src/panel/scheduler.js +80 -13
- package/src/panel/schedules.js +189 -28
- package/src/panel/schedulestart.js +44 -13
- package/src/panel/server.js +438 -33
- package/src/panel/settingsroutes.js +133 -3
- package/src/panel/status.js +22 -2
- package/src/panel/tickets.js +44 -0
- package/src/pickrecord.js +145 -0
- package/src/plan.js +31 -2
- package/src/planrun.js +71 -15
- package/src/prcheckout.js +259 -0
- package/src/readshim.js +3 -2
- package/src/replay.js +6 -0
- package/src/reuse.js +3 -3
- package/src/revises.js +56 -0
- package/src/rubricstep.js +62 -16
- package/src/run.js +10 -1
- package/src/runexport.js +2 -0
- package/src/runlist.js +3 -2
- package/src/schedulewords.js +46 -4
- package/src/source.js +81 -7
- package/src/stepmcp.js +86 -0
- package/src/ticket.js +113 -0
- package/src/ticketfilter.js +76 -0
- package/src/ticketlabels.js +79 -0
- package/src/ticketmcp.js +111 -0
- package/src/ticketnext.js +35 -0
- package/src/ticketrepo.js +98 -0
- package/src/ticketschedule.js +32 -0
- package/src/ticketshape.js +45 -0
- package/src/tools.js +9 -0
- package/src/trigger.js +14 -2
- package/src/triggerclock.js +7 -3
- package/src/triggerfiles.js +19 -11
- package/src/triggertickets.js +244 -0
- package/src/u-readout.js +2 -2
- package/src/userrun.js +146 -10
- package/src/validate.js +3 -1
- package/src/worktree.js +43 -1
- package/types/authorflow.d.ts +128 -28
- package/types/authorjob.d.ts +16 -3
- package/types/authorreadout.d.ts +9 -2
- package/types/authorscout.d.ts +4 -2
- package/types/bridges.d.ts +4 -3
- package/types/cardschedule.d.ts +24 -0
- package/types/checkpick.d.ts +297 -0
- package/types/checksuggest.d.ts +30 -0
- package/types/checkwords.d.ts +14 -0
- package/types/config.d.ts +7 -0
- package/types/destpoint.d.ts +87 -0
- package/types/draftspend.d.ts +16 -0
- package/types/factwords.d.ts +7 -0
- package/types/job.d.ts +13 -0
- package/types/jobblock.d.ts +9 -0
- package/types/labelscan.d.ts +7 -0
- package/types/launcher.d.ts +7 -2
- package/types/mcpchecks.d.ts +8 -0
- package/types/mcppick.d.ts +33 -0
- package/types/mcpsources.d.ts +51 -0
- package/types/mcpuse.d.ts +15 -0
- package/types/natural.d.ts +2 -0
- package/types/pagemap.d.ts +2 -1
- package/types/panel/authorroutes.d.ts +11 -2
- package/types/panel/authorsession.d.ts +58 -3
- package/types/panel/jobgrid.d.ts +405 -0
- package/types/panel/jobplan.d.ts +10 -4
- package/types/panel/scheduler.d.ts +7 -2
- package/types/panel/schedules.d.ts +124 -4
- package/types/panel/schedulestart.d.ts +21 -3
- package/types/panel/server.d.ts +427 -6
- package/types/panel/settingsroutes.d.ts +4 -2
- package/types/panel/status.d.ts +16 -2
- package/types/panel/tickets.d.ts +61 -0
- package/types/pickrecord.d.ts +88 -0
- package/types/plan.d.ts +1 -0
- package/types/prcheckout.d.ts +151 -0
- package/types/readshim.d.ts +4 -3
- package/types/replay.d.ts +3 -0
- package/types/reuse.d.ts +2 -2
- package/types/revises.d.ts +23 -0
- package/types/rubricstep.d.ts +14 -5
- package/types/run.d.ts +18 -1
- package/types/runlist.d.ts +6 -3
- package/types/schedulewords.d.ts +29 -2
- package/types/source.d.ts +40 -4
- package/types/stepmcp.d.ts +40 -0
- package/types/ticket.d.ts +114 -0
- package/types/ticketfilter.d.ts +34 -0
- package/types/ticketlabels.d.ts +44 -0
- package/types/ticketmcp.d.ts +84 -0
- package/types/ticketnext.d.ts +33 -0
- package/types/ticketrepo.d.ts +118 -0
- package/types/ticketschedule.d.ts +21 -0
- package/types/ticketshape.d.ts +37 -0
- package/types/tools.d.ts +1 -0
- package/types/trigger.d.ts +9 -1
- package/types/triggerclock.d.ts +6 -2
- package/types/triggerfiles.d.ts +13 -5
- package/types/triggertickets.d.ts +110 -0
- package/types/userrun.d.ts +50 -0
- package/types/validate.d.ts +1 -0
- package/types/worktree.d.ts +19 -0
package/src/stepmcp.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// A plan step's MCP tools (MCP+tickets piece 6, ITEM33-BUILD addendum 2026-11-02, R2c). A step that carries `mcpTools` starts the person's own MCP server ONCE for
|
|
2
|
+
// the step, with exactly those tools (`allow`), and hands the worker the bridge tools beside its shell and ctx tools; the bridge closes after the step's last try.
|
|
3
|
+
// "Only granted names reach the Loop" (menu-is-inventory): an unsigned tool does not exist for the worker, and the gate's allowlist (below) is the second wall.
|
|
4
|
+
// The start options are the one set every place bareloop starts an MCP uses (src/ticketmcp.js): PATH+HOME only, no provider key; cwd = the home folder.
|
|
5
|
+
import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
|
|
6
|
+
import { TOOL_BY_VERB, toolAction } from './tools.js';
|
|
7
|
+
import { redactSecrets } from './validate.js';
|
|
8
|
+
import { configForServer, remoteRefusal, startRefusal, firstLine, mcpStartOpts, mcpToolName, MCP_TIMEOUT_MS } from './ticketmcp.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The gate `tools.allowlist` for a step that grants MCP tools. bareguard's allowlist is EXCLUSIVE for every action (fwd F116 measured it denying fs too), and its
|
|
12
|
+
* identity for an action is `action.tool ?? action.type` — bareloop's `toolAction` sets no `tool`, so the identity is the action TYPE (`read`, `write`, `edit`,
|
|
13
|
+
* `ctx_stash`...), never the tool name (`shell_read`): a list of names denies the step's own reads (tested against the real Gate). A bridge tool has no
|
|
14
|
+
* translation, so its type IS its name (`github_issue_read`). So: the types of the step's granted verbs, taken from `toolAction` itself (no second spelling that
|
|
15
|
+
* could drift), plus the signed bridge names. Anything else, an unsigned bridge tool included, is denied by `tools.allowlist.exclusive`.
|
|
16
|
+
* @param {string[]} granted the step's verbs @param {string} server @param {string[]} mcpTools @param {string} workdir @returns {string[]}
|
|
17
|
+
*/
|
|
18
|
+
export function mcpAllowlist(granted, server, mcpTools, workdir) {
|
|
19
|
+
const types = new Set(granted.map((v) => /** @type {string} */ (toolAction(/** @type {Record<string, string>} */ (TOOL_BY_VERB)[v], { path: workdir }, workdir).type)));
|
|
20
|
+
return [...types, ...mcpTools.map((t) => mcpToolName(server, t))];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Mask every secret shape in a tool reply with the ONE inventory (`redactSecrets`, src/validate.js), at capture. A reply enters the worker's transcript and a
|
|
25
|
+
* model copies what it reads (into a file, into its reply): measured with a planted `ghp_` token, the raw reply reaches the model and every file the model copies
|
|
26
|
+
* it into, while the audit, the carry memo and the spine never carried it. Masking here, before the model sees it, closes that path at its source (the same rule
|
|
27
|
+
* the ticket freeze follows: a secret in a ticket is MASKED, never refused). Walks strings, arrays and plain objects; anything else passes through.
|
|
28
|
+
* @param {any} v @returns {any}
|
|
29
|
+
*/
|
|
30
|
+
export function maskReply(v) {
|
|
31
|
+
if (typeof v === 'string') return redactSecrets(v);
|
|
32
|
+
if (Array.isArray(v)) return v.map(maskReply);
|
|
33
|
+
if (v !== null && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, maskReply(x)]));
|
|
34
|
+
return v;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** wrap a bridge tool so its reply, and the message of an error it throws, are masked before they leave the tool @param {any} tool */
|
|
38
|
+
function maskedTool(tool) {
|
|
39
|
+
const inner = tool.execute;
|
|
40
|
+
tool.execute = async (/** @type {any} */ args, /** @type {any} */ ctx) => {
|
|
41
|
+
try { return maskReply(await inner.call(tool, args, ctx)); } catch (e) {
|
|
42
|
+
if (e instanceof Error) e.message = redactSecrets(e.message);
|
|
43
|
+
throw e;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
return tool;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Start the bridge for one step. Throws an Error in plain words (the cause named, at $0, before any token) when the server is not configured, will not start, or
|
|
51
|
+
* lacks a tool the job signed; the bridge is closed before it throws.
|
|
52
|
+
* @param {{mcp: {server: string, tools: string[]}, mcpTools: string[], configPath?: string, home?: string, timeoutMs?: number}} o
|
|
53
|
+
* `configPath`/`home` are test seams (an explicit MCP config file; the config home); production passes neither.
|
|
54
|
+
* @returns {Promise<{server: string, mcpTools: string[], tools: any[], names: string[], close: () => Promise<void>}>}
|
|
55
|
+
*/
|
|
56
|
+
export async function startStepMcp({ mcp, mcpTools, configPath: explicit, home, timeoutMs = MCP_TIMEOUT_MS }) {
|
|
57
|
+
const { server } = mcp;
|
|
58
|
+
const { file, remote } = configForServer(server, explicit, home);
|
|
59
|
+
if (!discoverServers([file]).has(server)) throw refusal(`${server} is not in ~/.mcp.json`);
|
|
60
|
+
if (remote) throw refusal(remoteRefusal(server));
|
|
61
|
+
/** @type {any} */ let bridge;
|
|
62
|
+
try {
|
|
63
|
+
// confirmServer must return exactly `true` (bare-agent), and only for the server the job signed
|
|
64
|
+
bridge = await createMCPBridge({ configPaths: [file], ...mcpStartOpts(), timeout: timeoutMs, callTimeout: timeoutMs, confirmServer: (/** @type {string} */ n) => n === server, allow: { [server]: mcpTools } });
|
|
65
|
+
const failed = bridge.errors.find((/** @type {any} */ e) => e.server === server);
|
|
66
|
+
if (failed) throw refusal(`${server} did not start: ${firstLine(failed.error)}`);
|
|
67
|
+
const lacking = bridge.missing?.[0];
|
|
68
|
+
if (lacking) throw refusal(`${server} does not offer ${lacking.tool}`);
|
|
69
|
+
const names = mcpTools.map((t) => mcpToolName(server, t));
|
|
70
|
+
const tools = bridge.tools.filter((/** @type {{name: string}} */ t) => names.includes(t.name)).map(maskedTool);
|
|
71
|
+
const absent = names.find((n) => !tools.some((/** @type {{name: string}} */ t) => t.name === n));
|
|
72
|
+
if (absent) throw refusal(`${server} does not offer ${absent.slice(server.length + 1)}`);
|
|
73
|
+
const b = bridge;
|
|
74
|
+
return { server, mcpTools, tools, names, close: async () => { try { await b.close(); } catch { /* already closed */ } } };
|
|
75
|
+
} catch (e) {
|
|
76
|
+
try { await bridge?.close(); } catch { /* already closed */ }
|
|
77
|
+
throw /** @type {any} */ (e)?.category ? e : refusal(startRefusal(server, e));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** an Error whose message is the plain-words cause; `interpreter-red` is the class a step-setup fault already lands in @param {string} message */
|
|
82
|
+
function refusal(message) {
|
|
83
|
+
const err = /** @type {Error & {category?: string}} */ (new Error(message));
|
|
84
|
+
err.category = 'interpreter-red';
|
|
85
|
+
return err;
|
|
86
|
+
}
|
package/src/ticket.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// MCP + tickets piece 1b (ITEM33-BUILD addendum 2026-11-02): the ONE source-neutral ticket shape, whether a ticket came from an MCP server or from a page
|
|
2
|
+
// read with barebrowse. The filter, the ledger rows, the run's record and the grid read only this shape; none of them knows the source.
|
|
3
|
+
// Every ticket text is MASKED with the one secret inventory (`redactSecrets`, src/validate.js) BEFORE the sha is taken, so the sha, the frozen bytes and every
|
|
4
|
+
// record carry the masked text (a secret in a ticket is masked, never refused). The honest ceiling: `SECRET_PATTERNS` are token shapes only.
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { readTicketMcp } from './ticketmcp.js';
|
|
7
|
+
import { fetchPageText } from './pagefetch.js';
|
|
8
|
+
import { isTicketNumber } from './ticketshape.js';
|
|
9
|
+
import { redactSecrets, scanSecrets } from './validate.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {object} Ticket
|
|
13
|
+
* @property {'mcp'|'page'} source
|
|
14
|
+
* @property {string} url the address of this ticket
|
|
15
|
+
* @property {number|null} number null = a page address that carries no ticket number (the grid row reads `#?`)
|
|
16
|
+
* @property {string} title
|
|
17
|
+
* @property {'open'|'closed'|'unknown'} state
|
|
18
|
+
* @property {string[]|null} labels null = not readable (a page); a priority filter finds none, and `unsure` never skips
|
|
19
|
+
* @property {string} text the MASKED text, as frozen
|
|
20
|
+
* @property {string} sha256 of the masked text's UTF-8 bytes
|
|
21
|
+
* @property {number} bytes
|
|
22
|
+
* @property {number} masked how many secret-shaped strings were masked (a count; never the values)
|
|
23
|
+
* @property {{server: string, exposed: string[], missing: Array<{server: string, tool: string}>, calls: Array<Record<string, any>>}|null} record the MCP read's own record (null for a page)
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** said on the plan card, in code-owned words, when a ticket comes from a page */
|
|
27
|
+
export const PAGE_TICKET_LIMIT_WORDS = 'A ticket read from a page may lack its body, and its labels and state may be missing.';
|
|
28
|
+
|
|
29
|
+
const TITLE_MAX = 200;
|
|
30
|
+
const clip = (/** @type {string} */ s) => s.trim().replace(/\s+/g, ' ').slice(0, TITLE_MAX);
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Mask a text and measure it: the masked text, its sha256 and byte length, and how many secret shapes it carried.
|
|
34
|
+
* @param {string} raw @returns {{text: string, sha256: string, bytes: number, masked: number}}
|
|
35
|
+
*/
|
|
36
|
+
export function maskTicketText(raw) {
|
|
37
|
+
const masked = scanSecrets(raw).length;
|
|
38
|
+
const text = redactSecrets(raw);
|
|
39
|
+
const buf = Buffer.from(text, 'utf8');
|
|
40
|
+
return { text, sha256: createHash('sha256').update(buf).digest('hex'), bytes: buf.length, masked };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** the number a GitHub ticket or pull address carries, or null @param {string} url @returns {number|null} */
|
|
44
|
+
function numberOfUrl(url) {
|
|
45
|
+
const m = /\/(?:issues|pull)\/(\d+)(?:[/?#]|$)/.exec(url);
|
|
46
|
+
const n = m ? Number(m[1]) : NaN;
|
|
47
|
+
return isTicketNumber(n) ? n : null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A ticket from the text of a PAGE (barebrowse act mode). Weaker than an MCP read, said plainly: the body may be missing (fwd F89: a page reader drops it),
|
|
52
|
+
* labels are null (not read from a page), and state is `closed` only when the text says `Closed`, else `unknown`.
|
|
53
|
+
* @param {string} rawText @param {string} url @returns {Ticket}
|
|
54
|
+
*/
|
|
55
|
+
export function ticketFromPage(rawText, url) {
|
|
56
|
+
const m = maskTicketText(rawText);
|
|
57
|
+
const firstLine = m.text.split('\n').map((l) => l.replace(/^#+\s*/, '').trim()).find((l) => l !== '') ?? '';
|
|
58
|
+
return { source: 'page', url, number: numberOfUrl(url), title: clip(firstLine), state: /\bClosed\b/.test(m.text) ? 'closed' : 'unknown', labels: null, ...m, record: null };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* A ticket from an MCP `issue_read` reply (a JSON document on GitHub's server; anything else keeps its text, with the first line as the title and the
|
|
63
|
+
* state and labels unknown).
|
|
64
|
+
* @param {string} rawText @param {string} url @param {number} number
|
|
65
|
+
* @param {Ticket['record']} record @returns {Ticket}
|
|
66
|
+
*/
|
|
67
|
+
export function ticketFromMcp(rawText, url, number, record) {
|
|
68
|
+
const m = maskTicketText(rawText);
|
|
69
|
+
/** @type {any} */
|
|
70
|
+
let doc = null;
|
|
71
|
+
try { doc = JSON.parse(rawText); } catch { doc = null; }
|
|
72
|
+
const obj = doc !== null && typeof doc === 'object' && !Array.isArray(doc) ? doc : null;
|
|
73
|
+
const firstLine = m.text.split('\n').find((l) => l.trim() !== '') ?? '';
|
|
74
|
+
const title = clip(typeof obj?.title === 'string' ? redactSecrets(obj.title) : firstLine);
|
|
75
|
+
const st = typeof obj?.state === 'string' ? obj.state.toLowerCase() : '';
|
|
76
|
+
const state = st === 'open' || st === 'closed' ? st : 'unknown';
|
|
77
|
+
/** @type {string[]|null} */
|
|
78
|
+
let labels = null;
|
|
79
|
+
if (Array.isArray(obj?.labels)) {
|
|
80
|
+
labels = obj.labels.map((/** @type {any} */ l) => (typeof l === 'string' ? l : typeof l?.name === 'string' ? l.name : null)).filter((/** @type {any} */ l) => typeof l === 'string').map((/** @type {string} */ l) => redactSecrets(l));
|
|
81
|
+
}
|
|
82
|
+
return { source: 'mcp', url, number, title, state, labels, ...m, record };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The pull request a `pull_request_read` ticket froze, as the object the checkout reads (`head.sha`, `base.ref`, `base.sha`): the parsed, MASKED reply (the same bytes the
|
|
87
|
+
* sha256 covers - a sha is not a secret shape, so masking leaves it whole). Null when the text is not a JSON object.
|
|
88
|
+
* @param {Ticket} ticket @returns {Record<string, any>|null}
|
|
89
|
+
*/
|
|
90
|
+
export function prRecordOfTicket(ticket) {
|
|
91
|
+
try {
|
|
92
|
+
const doc = JSON.parse(ticket.text);
|
|
93
|
+
return doc !== null && typeof doc === 'object' && !Array.isArray(doc) ? doc : null;
|
|
94
|
+
} catch { return null; }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Read one ticket, whatever its source. An MCP-backed row (`mcp` present) goes to the MCP reader; a page row to the page reader.
|
|
99
|
+
* @param {{mcp?: {server: string, tools: string[]}, listUrl?: string, number?: number, url?: string}} row
|
|
100
|
+
* @param {{configPath?: string, home?: string, timeoutMs?: number, fetchPage?: typeof fetchPageText}} [deps] test seams
|
|
101
|
+
* @returns {Promise<{ok: true, ticket: Ticket} | {ok: false, error: string}>}
|
|
102
|
+
*/
|
|
103
|
+
export async function readTicket(row, deps = {}) {
|
|
104
|
+
if (row.mcp) {
|
|
105
|
+
const r = await readTicketMcp({ listUrl: String(row.listUrl ?? ''), number: /** @type {number} */ (row.number), mcp: row.mcp, ...(deps.configPath ? { configPath: deps.configPath } : {}), ...(deps.home ? { home: deps.home } : {}), ...(deps.timeoutMs ? { timeoutMs: deps.timeoutMs } : {}) });
|
|
106
|
+
if (!r.ok) return r;
|
|
107
|
+
return { ok: true, ticket: ticketFromMcp(r.text, r.url, /** @type {number} */ (row.number), r.record) };
|
|
108
|
+
}
|
|
109
|
+
const url = String(row.url ?? '');
|
|
110
|
+
const p = await (deps.fetchPage ?? fetchPageText)(url);
|
|
111
|
+
if (!p.ok) return { ok: false, error: p.error };
|
|
112
|
+
return { ok: true, ticket: ticketFromPage(p.text, p.url || url) };
|
|
113
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// MCP + tickets piece 2 (R5): the ONE reader of "is this a legal ticketFilter", and the ONE place its legal example and drafter words live.
|
|
2
|
+
// Both doors read it: the signed spec (`validateJob`, src/job.js) and the drafter's proposal (`authorClose`, src/authorflow.js). The drafter is told this rule
|
|
3
|
+
// and shown a legal example in the same words the red carries (a validator rule the drafter is not told about fails every draft).
|
|
4
|
+
|
|
5
|
+
/** a legal filter, as the drafter is shown it: used in the prompt AND in every red's detail */
|
|
6
|
+
export const TICKET_FILTER_EXAMPLE = '{"priority": ["P1"], "labels": ["bug"]}';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @param {unknown} f the filter @param {{hasMcp?: boolean}} [o] `hasMcp: false` adds the "belongs to a job with an MCP" red
|
|
10
|
+
* @returns {Array<{code: string, path: string, detail: string}>} no entry = legal
|
|
11
|
+
*/
|
|
12
|
+
export function ticketFilterReds(f, { hasMcp = true } = {}) {
|
|
13
|
+
/** @type {Array<{code: string, path: string, detail: string}>} */
|
|
14
|
+
const reds = [];
|
|
15
|
+
const red = (/** @type {string} */ code, /** @type {string} */ path, /** @type {string} */ detail) => reds.push({ code, path, detail });
|
|
16
|
+
const isObj = f !== null && typeof f === 'object' && !Array.isArray(f);
|
|
17
|
+
if (!isObj || Object.keys(/** @type {object} */ (f)).length === 0) {
|
|
18
|
+
red('invalid-value', 'ticketFilter', `an object with "priority" and/or "labels", for example ${TICKET_FILTER_EXAMPLE}`);
|
|
19
|
+
return reds;
|
|
20
|
+
}
|
|
21
|
+
const o = /** @type {Record<string, any>} */ (f);
|
|
22
|
+
if (!hasMcp) red('invalid-value', 'ticketFilter', 'filters tickets read through the job\'s "mcp" tools, but the job lists no "mcp" server');
|
|
23
|
+
for (const key of Object.keys(o)) if (key !== 'priority' && key !== 'labels') red('unknown-field', `ticketFilter.${key}`, `declared keys only: priority|labels, for example ${TICKET_FILTER_EXAMPLE}`);
|
|
24
|
+
/** @type {Array<['priority'|'labels', (v: string) => boolean]>} */
|
|
25
|
+
const lists = [['priority', (v) => /^P[0-3]$/.test(v)], ['labels', (v) => v.trim() !== '' && v.length <= 100]];
|
|
26
|
+
for (const [key, ok] of lists) {
|
|
27
|
+
if (!Object.hasOwn(o, key)) continue;
|
|
28
|
+
if (!Array.isArray(o[key]) || o[key].length === 0) { red('invalid-value', `ticketFilter.${key}`, `a non-empty list, for example ${TICKET_FILTER_EXAMPLE}`); continue; }
|
|
29
|
+
const seen = new Set();
|
|
30
|
+
for (const v of o[key]) {
|
|
31
|
+
if (typeof v !== 'string' || !ok(v)) red('invalid-value', `ticketFilter.${key}`, `names ${JSON.stringify(v)}, which is not ${key === 'priority' ? 'a priority from P0 to P3' : 'a label name (1 to 100 characters)'}; for example ${TICKET_FILTER_EXAMPLE}`);
|
|
32
|
+
else if (seen.has(v.toLowerCase())) red('invalid-value', `ticketFilter.${key}`, `names "${v}" twice`);
|
|
33
|
+
else seen.add(v.toLowerCase());
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return reds;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** the schema's description of the `ticketFilter` property (src/authorflow.js): REQUIRED when a job line names a priority or a label, never "optional" (F285, run-e1 shape) */
|
|
40
|
+
export const TICKET_FILTER_SCHEMA_WORDS = 'REQUIRED when a job line names a priority or a label (leave it out only when none does). The person signs it; code decides at run start. Listing the line under "refused" does not filter anything: only this key does';
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The facts a person-facing turn must not ask about (R5 finding F285): the confirm turn asked "which ticket, and is it P1?" in 5 of 10 live drafts. ONE owner of these words;
|
|
44
|
+
* the confirm prompt and the drafting prompt both carry them, for a Tickets job only.
|
|
45
|
+
* @returns {string}
|
|
46
|
+
*/
|
|
47
|
+
export function ticketPerRunFacts() {
|
|
48
|
+
return 'THIS JOB READS A TICKET. The ticket is picked per run (typed on the run card, later the newest new ticket) and is never known when the job is drafted, so NEVER ask the person which ticket it is, or what its priority or labels are. '
|
|
49
|
+
+ 'A job line that names a priority or a label (for example "only priority P1 tickets") is decided by code at run start from the ticket\'s own labels, through the job\'s ticketFilter: it is not a question for the person and not something you can check, so do not turn it into a question.';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** R9 (F122, fwd e89196e): the frozen ticket is read like any input, and reading is a grant; the DRAFTING turn is told (the person-facing confirm turn is not: it speaks of no tools). */
|
|
53
|
+
export const TICKET_READ_FACT = 'A step that reads the ticket input still lists "read" in its tools: the ticket is already frozen at run start, but reading it is a grant, so a step without "read" cannot see it.';
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* What the drafter is told when the job reads tickets (appended to the authoring prompt only then; a plain job's prompt is untouched).
|
|
57
|
+
* Adapted from fwd's `ticketFactsLines` (v0.29.0): the same MUST, the same "never invent a label".
|
|
58
|
+
* @returns {string}
|
|
59
|
+
*/
|
|
60
|
+
export function ticketFilterBlock() {
|
|
61
|
+
return `${ticketPerRunFacts()} ${TICKET_READ_FACT}\n\nTHE TICKET FILTER — this job reads one ticket per run. Code, not you, decides at run start whether a ticket runs or is skipped, from the ticket's labels and state; a closed ticket always skips.
|
|
62
|
+
When a job line (or its ~ rule) names a priority or a label (for example "only priority P1 tickets", "only tickets with priority P1 count", "only issues labelled bug"), you MUST add a top-level "ticketFilter" beside "stages": ${TICKET_FILTER_EXAMPLE}. "priority" is a list of values from P0 to P3, "labels" is a list of label names; each key is optional, and at least one is required. Never invent a label: use only the names the job lines give. Leave "ticketFilter" out entirely when no job line names a priority or a label.
|
|
63
|
+
The filter decides whether a run starts, not whether the work is good, so it is not a check. The job line that names the priority or label has no stage: list it under "refused" with the reason "decided by the ticket filter before the run starts" AND add the ticketFilter: the refused entry alone does not filter anything, only the ticketFilter does. A person reads and signs the filter; you never set the job's server or tools.`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The filter in code-owned plain words (the plan card, the Job tab): never model prose. Null when there is nothing to say.
|
|
68
|
+
* @param {any} f the (legal) filter @returns {string|null}
|
|
69
|
+
*/
|
|
70
|
+
export function ticketFilterWords(f) {
|
|
71
|
+
if (f === null || typeof f !== 'object' || Array.isArray(f)) return null;
|
|
72
|
+
const parts = [];
|
|
73
|
+
if (Array.isArray(f.priority) && f.priority.length) parts.push(`priority ${f.priority.join(' or ')}`);
|
|
74
|
+
if (Array.isArray(f.labels) && f.labels.length) parts.push(`label ${f.labels.join(' or ')}`);
|
|
75
|
+
return parts.length ? `only tickets with ${parts.join(' and ')} run; a closed ticket is skipped` : null;
|
|
76
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// borrowed-from: fwdloop src/ticket-labels.js@v0.29.0 (83b6d02) - copied as is; it imports nothing
|
|
2
|
+
// 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.
|
|
3
|
+
// 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)
|
|
4
|
+
// 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.
|
|
5
|
+
// 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
|
|
6
|
+
// 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.
|
|
7
|
+
|
|
8
|
+
/** `P0`..`P3`, optionally after `priority`, `priority:`, `priority /` or `priority -`; the digit must end the number (`P12` is no priority) */
|
|
9
|
+
const PRIORITY_LABEL = /^(?:priority\s*[:/-]?\s*)?p([0-3])(?![0-9])/;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 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
|
|
13
|
+
* (`priority/important-soon`) and no scale value is present; `none` when no label speaks of priority.
|
|
14
|
+
* @param {string[]} labels @returns {string}
|
|
15
|
+
*/
|
|
16
|
+
export function priorityOf(labels) {
|
|
17
|
+
const found = new Set();
|
|
18
|
+
let offScale = false;
|
|
19
|
+
for (const raw of labels) {
|
|
20
|
+
const name = String(raw).trim().toLowerCase();
|
|
21
|
+
const m = PRIORITY_LABEL.exec(name);
|
|
22
|
+
if (m) found.add(`P${m[1]}`);
|
|
23
|
+
else if (name.split(/[^a-z0-9]+/).includes('priority')) offScale = true;
|
|
24
|
+
}
|
|
25
|
+
if (found.size > 1) return 'unsure';
|
|
26
|
+
if (found.size === 1) return [...found][0];
|
|
27
|
+
return offScale ? 'unsure' : 'none';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 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
|
|
32
|
+
* object is `ok:false`: never read as "no labels".
|
|
33
|
+
* @param {string} text @returns {{ok: true, labels: string[], state: string|null, title: string|null}|{ok: false}}
|
|
34
|
+
*/
|
|
35
|
+
export function readTicketFields(text) {
|
|
36
|
+
let o;
|
|
37
|
+
try { o = JSON.parse(text); } catch { return { ok: false }; }
|
|
38
|
+
if (!o || typeof o !== 'object' || Array.isArray(o)) return { ok: false };
|
|
39
|
+
const labels = (Array.isArray(o.labels) ? o.labels : []).map((l) => (typeof l === 'string' ? l : l?.name)).filter((l) => typeof l === 'string' && l.trim() !== '');
|
|
40
|
+
return { ok: true, labels, state: typeof o.state === 'string' ? o.state.toLowerCase() : null, title: typeof o.title === 'string' ? o.title : null };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** R9 (9.4): the words for it, one owner (the grid's open row and the badge's title read them). */
|
|
44
|
+
export const FILTER_UNSURE_SAY = 'the filter was unsure about this ticket';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 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`
|
|
48
|
+
* 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.
|
|
49
|
+
* @param {any} entry @returns {boolean}
|
|
50
|
+
*/
|
|
51
|
+
export function filterUnsure(entry) {
|
|
52
|
+
const f = entry?.filter;
|
|
53
|
+
return typeof f?.unsure === 'string' || (f?.outcome === 'anyway' && typeof f?.was?.unsure === 'string');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param {{text: string, filter?: {priority?: string[], labels?: string[]}}} a `filter` = the job's signed `ticketFilter` (or absent)
|
|
58
|
+
* @returns {{outcome: 'run', unsure?: string}|{outcome: 'skip', reason: string}}
|
|
59
|
+
*/
|
|
60
|
+
export function decideTicket({ text, filter }) {
|
|
61
|
+
const t = readTicketFields(text);
|
|
62
|
+
if (!t.ok) return { outcome: 'run', unsure: 'the ticket text is not readable as fields, so no label could be checked' };
|
|
63
|
+
if (t.state === 'closed') return { outcome: 'skip', reason: 'closed' };
|
|
64
|
+
if (!filter) return { outcome: 'run' };
|
|
65
|
+
/** @type {string|undefined} */
|
|
66
|
+
let unsure;
|
|
67
|
+
if (filter.priority?.length) {
|
|
68
|
+
const want = filter.priority.join(' or ');
|
|
69
|
+
const p = priorityOf(t.labels);
|
|
70
|
+
if (p === 'none') return { outcome: 'skip', reason: `no ${want} label` };
|
|
71
|
+
if (p === 'unsure') unsure = 'a priority label is not on the P0-P3 scale, or two priorities are present';
|
|
72
|
+
else if (!filter.priority.includes(p)) return { outcome: 'skip', reason: `priority ${p}, not ${want}` };
|
|
73
|
+
}
|
|
74
|
+
if (filter.labels?.length) {
|
|
75
|
+
const have = new Set(t.labels.map((l) => l.trim().toLowerCase()));
|
|
76
|
+
if (!filter.labels.some((l) => have.has(l.trim().toLowerCase()))) return { outcome: 'skip', reason: `no ${filter.labels.join(' or ')} label` };
|
|
77
|
+
}
|
|
78
|
+
return unsure === undefined ? { outcome: 'run' } : { outcome: 'run', unsure };
|
|
79
|
+
}
|
package/src/ticketmcp.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// borrowed-from: fwdloop src/ticket-mcp.js@9650320 (adapted: redactSecrets from src/validate.js, the one inventory; server lookup from src/mcpsources.js)
|
|
2
|
+
// Read ONE ticket through the person's own MCP server, nothing else (bareloop MCP+tickets piece 1, ITEM33-BUILD addendum 2026-11-02).
|
|
3
|
+
// 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
|
|
4
|
+
// `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.
|
|
5
|
+
// 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.
|
|
6
|
+
// Borrowed shape: fwdloop poc/mcp/f100/scratch.diff (`src/ticket-mcp.js`), re-shaped: job-typed tools, explicit config, the three causes kept apart.
|
|
7
|
+
import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { redactSecrets } from './validate.js';
|
|
11
|
+
import { parseTicketList, isTicketNumber, TICKET_NUMBER_WORDS } from './ticketshape.js';
|
|
12
|
+
import { mcpConfigFor } from './mcpsources.js';
|
|
13
|
+
|
|
14
|
+
/** M13 item 9.5: the only parent env names an MCP gets (plus its own settings); the one list for every place bareloop starts an MCP, so no provider key reaches it */
|
|
15
|
+
export const MCP_PASS_ENV = ['PATH', 'HOME'];
|
|
16
|
+
|
|
17
|
+
/** how long a bridge waits to start and for one call (ms): the one number for the ticket read and a plan step's bridge */
|
|
18
|
+
export const MCP_TIMEOUT_MS = 90000;
|
|
19
|
+
|
|
20
|
+
/** the name bare-agent's bridge gives a server's tool: `<server>_<tool>` (the one spelling: the ticket read, a step's worker menu, the gate allowlist) @param {string} server @param {string} tool */
|
|
21
|
+
export const mcpToolName = (server, tool) => `${server}_${tool}`;
|
|
22
|
+
|
|
23
|
+
/** M13 design point 11 (F118): the one start option set for every place bareloop 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) */
|
|
24
|
+
export const mcpStartOpts = () => ({ passEnv: MCP_PASS_ENV, cwd: homedir() });
|
|
25
|
+
|
|
26
|
+
/** 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 */
|
|
27
|
+
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)}`;
|
|
28
|
+
|
|
29
|
+
/** the user's own `~/.mcp.json`: the config a caller that finds the server in no place falls back to (a server found nowhere then reads "not in ~/.mcp.json") */
|
|
30
|
+
export const USER_MCP_CONFIG = () => join(homedir(), '.mcp.json');
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 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,
|
|
34
|
+
* the one decider), or `~/.mcp.json` when no place has it. `remote` true = the winner has no start command (listed, not usable).
|
|
35
|
+
* @param {string} server @param {string} [explicit] @param {string} [home] the config home (tests) @returns {{ file: string, remote: boolean }}
|
|
36
|
+
*/
|
|
37
|
+
export function configForServer(server, explicit, home) {
|
|
38
|
+
if (explicit) return { file: explicit, remote: false };
|
|
39
|
+
return mcpConfigFor(server, home === undefined ? {} : { home }) ?? { file: USER_MCP_CONFIG(), remote: false };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** the refusal for a remote server (no start command), at $0 @param {string} server */
|
|
43
|
+
export const remoteRefusal = (server) => `${server} is a remote server, not supported yet`;
|
|
44
|
+
|
|
45
|
+
/** the first line of a message, secrets redacted, clipped: all a refusal ever shows of a server's own error */
|
|
46
|
+
export const firstLine = (e) => redactSecrets(String(e?.message ?? e ?? '')).split('\n').find((l) => l.trim() !== '')?.trim().slice(0, 200) ?? 'no message';
|
|
47
|
+
|
|
48
|
+
/** 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) */
|
|
49
|
+
export const isDeviceLogin = (text) => text.includes('github.com/login/device');
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The one tool name a PR read uses. Like `issue_read`, it is the only PR tool name hardcoded: the rest of a job's tools come from the server's own list. The limit, said
|
|
53
|
+
* plainly (ITEM33-BUILD piece 1a, PR-verification job): this is GitHub's own server's spelling, measured against the real server 2026-11-04 (`pull_request_read`, method
|
|
54
|
+
* `get`, args owner/repo/pullNumber); a server that spells it differently is not read, and the person's GitHub server must enable the `pull_requests` toolset.
|
|
55
|
+
*/
|
|
56
|
+
export const PR_READ_TOOL = 'pull_request_read';
|
|
57
|
+
|
|
58
|
+
/** the tool and the arguments one read of a list's kind makes @param {'issue'|'pull'} kind @param {string} owner @param {string} repo @param {number} number */
|
|
59
|
+
export function readCall(kind, owner, repo, number) {
|
|
60
|
+
return kind === 'pull'
|
|
61
|
+
? { tool: PR_READ_TOOL, args: { method: 'get', owner, repo, pullNumber: number }, what: 'a pull request' }
|
|
62
|
+
: { tool: 'issue_read', args: { method: 'get', owner, repo, issue_number: number }, what: 'a ticket' };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Read ticket (or pull request) `number` of the list at `listUrl` with the job's `issue_read` (an issues list) or `pull_request_read` (a pulls list).
|
|
67
|
+
* @param {{listUrl: string, number: number, mcp: {server: string, tools: string[]}, configPath?: string, home?: string, timeoutMs?: number}} o
|
|
68
|
+
* @returns {Promise<{ok: true, text: string, url: string, record: {server: string, exposed: string[], missing: Array<{server: string, tool: string}>, calls: Array<Record<string, any>>}} | {ok: false, error: string}>}
|
|
69
|
+
* `record` is what the run keeps (in its `run.json` input entry): what the server exposed and lacked, and each call made.
|
|
70
|
+
*/
|
|
71
|
+
export async function readTicketMcp({ listUrl, number, mcp, configPath: explicitConfig, home, timeoutMs = MCP_TIMEOUT_MS }) {
|
|
72
|
+
const list = parseTicketList(listUrl);
|
|
73
|
+
if (!list.ok) return list;
|
|
74
|
+
if (!isTicketNumber(number)) return { ok: false, error: `ticket number ${JSON.stringify(number)} is not ${TICKET_NUMBER_WORDS}` };
|
|
75
|
+
const { owner, repo } = list;
|
|
76
|
+
const { server, tools } = mcp;
|
|
77
|
+
const { tool: toolId, args, what } = readCall(list.kind, owner, repo, number);
|
|
78
|
+
// M13 piece 4: the frozen read starts the server with the one read tool alone, whatever else the job lists (the job lists every tool of its server)
|
|
79
|
+
if (!tools.includes(toolId)) return { ok: false, error: `the job does not list ${toolId}, the tool that reads ${what}` };
|
|
80
|
+
const { file: configPath, remote } = configForServer(server, explicitConfig, home);
|
|
81
|
+
if (!discoverServers([configPath]).has(server)) return { ok: false, error: `${server} is not in ~/.mcp.json` };
|
|
82
|
+
if (remote) return { ok: false, error: remoteRefusal(server) };
|
|
83
|
+
const notOffered = `${server} does not offer ${toolId}${list.kind === 'pull' ? ' (its GitHub server needs the pull_requests toolset enabled)' : ''}`;
|
|
84
|
+
let bridge;
|
|
85
|
+
try {
|
|
86
|
+
bridge = await createMCPBridge({ configPaths: [configPath], ...mcpStartOpts(), timeout: timeoutMs, callTimeout: timeoutMs, confirmServer: () => true, allow: { [server]: [toolId] } });
|
|
87
|
+
const failed = bridge.errors.find((e) => e.server === server);
|
|
88
|
+
if (failed) return { ok: false, error: `${server} did not start: ${firstLine(failed.error)}` };
|
|
89
|
+
const lacking = bridge.missing?.[0];
|
|
90
|
+
if (lacking) return { ok: false, error: notOffered };
|
|
91
|
+
const tool = bridge.tools.find((t) => t.name === mcpToolName(server, toolId));
|
|
92
|
+
if (!tool) return { ok: false, error: notOffered };
|
|
93
|
+
const call = { tool: toolId, owner, repo, ...(list.kind === 'pull' ? { method: 'get', pullNumber: number } : { issue_number: number }) };
|
|
94
|
+
const record = { server, exposed: bridge.tools.map((t) => t.name), missing: bridge.missing ?? [], calls: [call] };
|
|
95
|
+
const url = list.ticketUrl(number);
|
|
96
|
+
let reply;
|
|
97
|
+
try {
|
|
98
|
+
reply = await tool.execute(args);
|
|
99
|
+
} catch (e) {
|
|
100
|
+
return { ok: false, error: `${server}: ${toolId} failed: ${firstLine(e)}` };
|
|
101
|
+
}
|
|
102
|
+
const text = typeof reply === 'string' ? reply : (Array.isArray(reply) ? reply : []).map((c) => c?.text ?? '').join('');
|
|
103
|
+
if (isDeviceLogin(text)) return { ok: false, error: 'GitHub token unavailable — the server asked for a login (is pass locked?)' };
|
|
104
|
+
if (text.trim() === '') return { ok: false, error: `${server}: ${toolId} returned nothing for ${url}` };
|
|
105
|
+
return { ok: true, text, url, record };
|
|
106
|
+
} catch (e) {
|
|
107
|
+
return { ok: false, error: startRefusal(server, e) };
|
|
108
|
+
} finally {
|
|
109
|
+
try { await bridge?.close(); } catch { /* already closed */ }
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// borrowed-from: fwdloop src/ticket-next.js@v0.29.0 (adapted: "has run" is the job's run-list rows, which carry the ticket number; the look is bareloop's triggertickets.js)
|
|
2
|
+
// MCP + tickets piece 8 / piece 1 (ITEM33-BUILD, R6): a by-hand run of a Tickets job with no ticket number takes the NEWEST UNRUN ticket - the schedule's own look (`lookTickets`, the
|
|
3
|
+
// job's signed `list_issues`, newest first, open tickets), above the highest number this job has already run (a skipped run included: its row carries the number too). A job with no
|
|
4
|
+
// ticket run yet takes the newest open ticket of the first page (the first run reads the newest ticket at the time it starts; older ones never run). Nothing new = one plain line (`nothingNew: true`, so a caller can tell a quiet "nothing to do" from a fault), $0, no run.
|
|
5
|
+
// A typed number still works and never reaches this file. ONE owner: `run-u` calls it for a fresh Tickets run that names no ticket, whether the CLI or the panel started it.
|
|
6
|
+
import { parseTicketList } from './ticketshape.js';
|
|
7
|
+
import { LOOK_TOOL, lookTickets } from './triggertickets.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The ticket numbers this job's runs have read.
|
|
11
|
+
* @param {ReadonlyArray<{job?: string, ticket?: unknown}>} rows the run list's rows @param {string} job @returns {Set<number>}
|
|
12
|
+
*/
|
|
13
|
+
export function ranTicketNumbers(rows, job) {
|
|
14
|
+
const out = new Set();
|
|
15
|
+
for (const r of rows) if (r && r.job === job && Number.isInteger(r.ticket)) out.add(r.ticket);
|
|
16
|
+
return /** @type {Set<number>} */ (out);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {{job: string, rows: ReadonlyArray<any>, inputs: Array<{value: string}>, mcp: {server: string, tools: string[]}, configPath?: string, look?: typeof lookTickets}} o `look` is a test seam
|
|
21
|
+
* @returns {Promise<{ok: true, number: number} | {ok: false, say: string, nothingNew?: true}>}
|
|
22
|
+
*/
|
|
23
|
+
export async function newestUnrunTicket({ job, rows, inputs, mcp, configPath, look = lookTickets }) {
|
|
24
|
+
const again = 'Fix that, then start the job again.';
|
|
25
|
+
const list = inputs.map((i) => ({ value: String(i.value).trim(), p: parseTicketList(i.value) })).find((x) => x.p.ok && x.p.kind === 'issue');
|
|
26
|
+
if (!list) return { ok: false, say: `The newest ticket can only be found on an issues list, so this job cannot pick the newest one. ${again}` };
|
|
27
|
+
if (!mcp.tools.includes(LOOK_TOOL)) return { ok: false, say: `This job's signed tools do not include ${LOOK_TOOL}, the tool that finds the newest ticket. ${again}` };
|
|
28
|
+
const ran = ranTicketNumbers(rows, job);
|
|
29
|
+
const r = await look({ listUrl: list.value, mcp: { server: mcp.server, tool: LOOK_TOOL }, ...(configPath ? { configPath } : {}), seen: ran.size === 0 ? null : ran, last: new Map(), watch: [] });
|
|
30
|
+
// the cause is the look's own words (a locked pass names itself); one full stop at the end, never a doubled `?.`
|
|
31
|
+
if (!r.ok) return { ok: false, say: `The newest ticket could not be looked up. The reason: ${/[.?!]$/.test(r.error) ? r.error : `${r.error}.`} ${again}` };
|
|
32
|
+
const numbers = r.found.map((f) => f.number);
|
|
33
|
+
if (numbers.length === 0) return ran.size === 0 ? { ok: false, say: `No open ticket at ${list.value}.` } : { ok: false, nothingNew: true, say: `No new ticket since #${Math.max(...ran)}. Nothing to run.` };
|
|
34
|
+
return { ok: true, number: Math.max(...numbers) };
|
|
35
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// MCP + tickets piece 1a (ITEM33-BUILD addendum 2026-11-02, "Piece 1a"): a ticket for a deterministic (code-repo) job.
|
|
2
|
+
// The ticket is NOT a tracked repo file and must never reach the person's repo, so it lives OUTSIDE the tracked tree: a frozen file in the run's worktree under
|
|
3
|
+
// `.bareloop-input/<label>.txt`, hidden by git's PRIVATE exclude (the common dir's info/exclude, as installed `node_modules` is). The worker reads it (it sits inside
|
|
4
|
+
// readScope), cannot write it (no signed write fence can contain a folder that is not in the job's listing; see the gate test), and the close never reads or names it.
|
|
5
|
+
// This file: the $0 proof of the Inputs line, and the run-start freeze.
|
|
6
|
+
import { discoverServers } from 'bare-agent/mcp';
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { lstatSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { parseTicketList } from './ticketshape.js';
|
|
11
|
+
import { configForServer, remoteRefusal, readCall } from './ticketmcp.js';
|
|
12
|
+
import { readTicket, prRecordOfTicket } from './ticket.js';
|
|
13
|
+
import { hideTicketInput, TICKET_INPUT_DIR } from './worktree.js';
|
|
14
|
+
|
|
15
|
+
export { TICKET_INPUT_DIR };
|
|
16
|
+
|
|
17
|
+
/** the file a ticket line freezes to, relative to the worktree: the label made file-safe, the way a rubric input is named @param {string} label @returns {string} */
|
|
18
|
+
export function ticketInputRel(label) {
|
|
19
|
+
const stem = label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'ticket';
|
|
20
|
+
return `${TICKET_INPUT_DIR}/${stem}.txt`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The $0 proof of a repo job's ticket line: the job's server is named in the person's MCP config (a file is read; nothing is started), it is not a remote one,
|
|
25
|
+
* and the read tool is among the tools the job signed: `issue_read` for an issues address, `pull_request_read` for a pulls address. The address itself parsed already.
|
|
26
|
+
* @param {{server: string, tools: string[]}} mcp @param {{configPath?: string}} [deps] test seam @param {'issue'|'pull'} [kind]
|
|
27
|
+
* @returns {{ok: true}|{ok: false, error: string}}
|
|
28
|
+
*/
|
|
29
|
+
export function proveTicketLine(mcp, deps = {}, kind = 'issue') {
|
|
30
|
+
const { file, remote } = configForServer(mcp.server, deps.configPath);
|
|
31
|
+
if (!discoverServers([file]).has(mcp.server)) return { ok: false, error: `${mcp.server} is not in ~/.mcp.json` };
|
|
32
|
+
if (remote) return { ok: false, error: remoteRefusal(mcp.server) };
|
|
33
|
+
const { tool, what } = readCall(kind, '', '', 1);
|
|
34
|
+
if (!mcp.tools.includes(tool)) return { ok: false, error: `${tool}, the tool that reads ${what}, is not among the tools this job signed` };
|
|
35
|
+
return { ok: true };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The ONE ticket line of a repo job's Inputs: a line 2+ whose value is a GitHub issues or pulls address.
|
|
40
|
+
* @param {{n: number, label: string, value: string}[]} inputs
|
|
41
|
+
* @returns {{ok: true, line: {n: number, label: string, value: string}}|{ok: false, error: string}}
|
|
42
|
+
*/
|
|
43
|
+
export function repoTicketLine(inputs) {
|
|
44
|
+
const lines = inputs.slice(1).filter((l) => parseTicketList(l.value).ok);
|
|
45
|
+
if (lines.length === 0) return { ok: false, error: 'This job reads a ticket, but none of its Inputs (after the repo) is the issues or pulls page of a GitHub repository (owner/repo/issues or owner/repo/pulls).' };
|
|
46
|
+
if (lines.length > 1) return { ok: false, error: 'This job reads one ticket, but more than one of its Inputs is a GitHub issues or pulls address.' };
|
|
47
|
+
return { ok: true, line: lines[0] };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {object} RepoTicketRecord what the spine's `job-start` keeps of a repo job's ticket: metadata only, never the text
|
|
52
|
+
* @property {string} label @property {string} file the frozen file, relative to the worktree @property {string} url @property {number} number @property {string} title
|
|
53
|
+
* @property {'open'|'closed'|'unknown'} state @property {'mcp'|'page'} source @property {string} sha256 of the masked bytes @property {number} bytes
|
|
54
|
+
* @property {number} masked how many secret shapes were masked (a count, never the values)
|
|
55
|
+
* @property {{server: string, exposed: string[], missing: Array<{server: string, tool: string}>, calls: Array<Record<string, any>>}|null} mcp
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* RUN START for a repo job that reads a ticket: read the ticket through the MCP, MASK it (before the sha), and write it to `<workdir>/.bareloop-input/<label>.txt`.
|
|
60
|
+
* The folder is hidden through git's private exclude BEFORE the file exists, so the ticket is never a worker write and never in the final commit; it sits inside the
|
|
61
|
+
* worker's readScope, and no write fence can contain it (a signed writeScope is a subfolder of the tracked listing). Nothing is committed and the seed does not move.
|
|
62
|
+
* A refusal is plain words at $0 ("The run did not start. Nothing spent.") and writes nothing.
|
|
63
|
+
* @param {{workdir: string, inputs: {n: number, label: string, value: string}[], ticket: {number: number, mcp: {server: string, tools: string[]}}}} o
|
|
64
|
+
* A PULLS address reads the pull request the same way (`pull_request_read`) and also returns `pr` = `{url, record, reread}` for piece 12's run-start checkout: `record` is the
|
|
65
|
+
* parsed MASKED reply (its `head.sha` is what the worktree is checked out at), `reread` reads it once more if the PR moved while the run was starting.
|
|
66
|
+
* @returns {Promise<{ok: true, ticketText: string, record: RepoTicketRecord, pr?: {url: string, record: any, reread: () => Promise<any>}}|{ok: false, error: string}>}
|
|
67
|
+
*/
|
|
68
|
+
export async function freezeRepoTicket({ workdir, inputs, ticket }) {
|
|
69
|
+
const tail = 'The run did not start. Nothing spent.';
|
|
70
|
+
const found = repoTicketLine(inputs);
|
|
71
|
+
if (!found.ok) return { ok: false, error: `${found.error} ${tail}` };
|
|
72
|
+
const { line } = found;
|
|
73
|
+
const fail = (/** @type {string} */ m) => ({ ok: /** @type {const} */ (false), error: `Input "${line.label}": ${m}. ${tail}` });
|
|
74
|
+
const rel = ticketInputRel(line.label);
|
|
75
|
+
// the folder name must be ours: a repo that tracks it (or links it out of the tree) would carry the write elsewhere
|
|
76
|
+
let tracked = '';
|
|
77
|
+
try { tracked = execFileSync('git', ['-C', workdir, 'ls-files', '--', TICKET_INPUT_DIR], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); } catch (e) { return fail(`git could not be read in ${workdir}: ${String(/** @type {any} */ (e)?.message ?? e).split('\n')[0]}`); }
|
|
78
|
+
const dir = join(workdir, TICKET_INPUT_DIR);
|
|
79
|
+
let st = null;
|
|
80
|
+
try { st = lstatSync(dir); } catch { st = null; }
|
|
81
|
+
if (tracked !== '' || (st !== null && !st.isDirectory())) return fail(`${TICKET_INPUT_DIR} is already in this repository, and bareloop keeps the ticket there - rename it, then start the run again`);
|
|
82
|
+
const kind = /** @type {{kind: 'issue'|'pull'}} */ (parseTicketList(line.value)).kind;
|
|
83
|
+
const proof = proveTicketLine(ticket.mcp, {}, kind);
|
|
84
|
+
if (!proof.ok) return fail(proof.error);
|
|
85
|
+
const t = await readTicket({ mcp: ticket.mcp, listUrl: line.value, number: ticket.number });
|
|
86
|
+
if (!t.ok) return fail(t.error);
|
|
87
|
+
try {
|
|
88
|
+
hideTicketInput(workdir);
|
|
89
|
+
mkdirSync(dir, { recursive: true });
|
|
90
|
+
const file = join(workdir, rel);
|
|
91
|
+
rmSync(file, { force: true }); // a leftover link or file from an earlier run of this worktree is replaced, never written through
|
|
92
|
+
writeFileSync(file, t.ticket.text);
|
|
93
|
+
} catch (e) { return fail(`the ticket could not be written (${String(/** @type {any} */ (e)?.message ?? e).split('\n')[0]})`); }
|
|
94
|
+
const k = t.ticket;
|
|
95
|
+
/** @type {{url: string, record: any, reread: () => Promise<any>}|undefined} */
|
|
96
|
+
const pr = kind === 'pull' ? { url: k.url, record: prRecordOfTicket(k) ?? {}, reread: async () => { const again = await readTicket({ mcp: ticket.mcp, listUrl: line.value, number: ticket.number }); return again.ok ? prRecordOfTicket(again.ticket) : null; } } : undefined;
|
|
97
|
+
return { ok: true, ticketText: k.text, ...(pr === undefined ? {} : { pr }), record: { label: line.label, file: rel, url: k.url, number: /** @type {number} */ (k.number), title: k.title, state: k.state, source: k.source, sha256: k.sha256, bytes: k.bytes, masked: k.masked, mcp: k.record } };
|
|
98
|
+
}
|