@bbcsoftwarefactory/cli 0.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/audit-ledger.d.ts +2 -0
  2. package/dist/audit-ledger.js +71 -0
  3. package/dist/bbc-install.d.ts +2 -0
  4. package/dist/bbc-install.js +1250 -0
  5. package/dist/bbc.js +87 -3
  6. package/dist/change-lane/classification.js +3 -1
  7. package/dist/check-issue-claim.d.ts +2 -0
  8. package/dist/check-issue-claim.js +146 -0
  9. package/dist/check-worktree-guard.d.ts +2 -0
  10. package/dist/check-worktree-guard.js +114 -0
  11. package/dist/error-scan.d.ts +3 -0
  12. package/dist/error-scan.js +216 -0
  13. package/dist/export-public.d.ts +9 -0
  14. package/dist/export-public.js +274 -0
  15. package/dist/fetch-issue-attachments.d.ts +22 -0
  16. package/dist/fetch-issue-attachments.js +325 -0
  17. package/dist/issue-claim/evaluation.d.ts +66 -0
  18. package/dist/issue-claim/evaluation.js +259 -0
  19. package/dist/issue-claim/loaders.d.ts +5 -0
  20. package/dist/issue-claim/loaders.js +116 -0
  21. package/dist/list-zed-commands.d.ts +7 -0
  22. package/dist/list-zed-commands.js +288 -0
  23. package/dist/plan-issue-triage.d.ts +3 -0
  24. package/dist/plan-issue-triage.js +404 -0
  25. package/dist/question-gate/ledger.d.ts +5 -0
  26. package/dist/question-gate/ledger.js +115 -0
  27. package/dist/question-gate/rules.d.ts +40 -0
  28. package/dist/question-gate/rules.js +483 -0
  29. package/dist/recap/board.d.ts +5 -0
  30. package/dist/recap/board.js +384 -0
  31. package/dist/recap/git-and-github.d.ts +11 -0
  32. package/dist/recap/git-and-github.js +620 -0
  33. package/dist/recap/report-and-hud.d.ts +2 -0
  34. package/dist/recap/report-and-hud.js +294 -0
  35. package/dist/recap/time-and-refs.d.ts +27 -0
  36. package/dist/recap/time-and-refs.js +148 -0
  37. package/dist/recap.d.ts +2 -0
  38. package/dist/recap.js +217 -0
  39. package/dist/render-workflow.js +12 -14
  40. package/dist/resolve-containers.d.ts +2 -0
  41. package/dist/resolve-containers.js +96 -0
  42. package/dist/review-loop.d.ts +7 -0
  43. package/dist/review-loop.js +622 -0
  44. package/dist/save-counts.d.ts +2 -0
  45. package/dist/save-counts.js +191 -0
  46. package/dist/summarize-logs.d.ts +2 -0
  47. package/dist/summarize-logs.js +41 -0
  48. package/dist/sweep-github.d.ts +10 -0
  49. package/dist/sweep-github.js +453 -0
  50. package/dist/sweep-issues.d.ts +56 -0
  51. package/dist/sweep-issues.js +650 -0
  52. package/dist/sweep.d.ts +2 -0
  53. package/dist/sweep.js +301 -0
  54. package/dist/triage-question.d.ts +2 -0
  55. package/dist/triage-question.js +189 -0
  56. package/dist/validate-skills.d.ts +2 -0
  57. package/dist/validate-skills.js +48 -0
  58. package/dist/watch-live.d.ts +7 -0
  59. package/dist/watch-live.js +83 -0
  60. package/dist/watcher/config.d.ts +11 -0
  61. package/dist/watcher/config.js +265 -0
  62. package/dist/watcher/live-classifier.d.ts +52 -0
  63. package/dist/watcher/live-classifier.js +510 -0
  64. package/dist/watcher/safe-fs.d.ts +9 -0
  65. package/dist/watcher/safe-fs.js +159 -0
  66. package/dist/watcher/stream.d.ts +27 -0
  67. package/dist/watcher/stream.js +340 -0
  68. package/dist/watcher/summarizer.d.ts +19 -0
  69. package/dist/watcher/summarizer.js +121 -0
  70. package/dist/wave3/process.d.ts +14 -0
  71. package/dist/wave3/process.js +84 -0
  72. package/dist/wave4/process.d.ts +14 -0
  73. package/dist/wave4/process.js +128 -0
  74. package/dist/workflow/render.d.ts +1 -1
  75. package/dist/workflow/render.js +1 -1
  76. package/dist/workflow-auditor/audit.d.ts +27 -0
  77. package/dist/workflow-auditor/audit.js +583 -0
  78. package/dist/workflow-auditor/ledger-io.d.ts +5 -0
  79. package/dist/workflow-auditor/ledger-io.js +99 -0
  80. package/dist/workflow-auditor/skills-validator.d.ts +10 -0
  81. package/dist/workflow-auditor/skills-validator.js +533 -0
  82. package/dist/worktree-guard/evaluation.d.ts +19 -0
  83. package/dist/worktree-guard/evaluation.js +84 -0
  84. package/dist/worktree-guard/git.d.ts +3 -0
  85. package/dist/worktree-guard/git.js +61 -0
  86. package/package.json +32 -33
@@ -0,0 +1,259 @@
1
+ export class UnusableClaimError extends Error {
2
+ }
3
+ export const STOP_VERDICTS = new Set([
4
+ 'closed',
5
+ 'claimed-by-other',
6
+ 'contended-lost',
7
+ 'orphan-claim',
8
+ 'invalid-branch',
9
+ 'unrecorded-claim',
10
+ 'still-held',
11
+ 'duplicate-work',
12
+ 'stale-claim',
13
+ ]);
14
+ const STOP_ORDER = [
15
+ 'closed',
16
+ 'claimed-by-other',
17
+ 'contended-lost',
18
+ 'orphan-claim',
19
+ 'invalid-branch',
20
+ 'unrecorded-claim',
21
+ 'still-held',
22
+ 'duplicate-work',
23
+ 'stale-claim',
24
+ ];
25
+ const BRANCH_RE = /^feat\/(\d+)-[a-z0-9][a-z0-9._-]*$/;
26
+ const REFERENCE_RE = /(?:\b([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+))?#(\d+)\b/g;
27
+ const ISSUE_URL_RE = /github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/issues\/(\d+)\b/g;
28
+ const DAY_MS = 86_400_000;
29
+ export function fold(value) {
30
+ return typeof value === 'string' ? value.toLowerCase() : '';
31
+ }
32
+ export function extractLogin(value) {
33
+ const raw = typeof value === 'object' && value !== null && !Array.isArray(value)
34
+ ? value.login
35
+ : value;
36
+ return typeof raw === 'string' && raw.trim() !== '' ? raw : null;
37
+ }
38
+ export function parseIsoTime(value) {
39
+ if (typeof value !== 'string')
40
+ return null;
41
+ const trimmed = value.trim();
42
+ const match = /^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)(Z|[+-]\d{2}:?\d{2})?)?$/.exec(trimmed);
43
+ if (!match)
44
+ return null;
45
+ const [, datePart, timePart, tzPart] = match;
46
+ if (!timePart) {
47
+ const ms = Date.parse(`${datePart}T00:00:00Z`);
48
+ return Number.isNaN(ms) ? null : ms;
49
+ }
50
+ const normalizedTz = !tzPart || tzPart === 'Z'
51
+ ? 'Z'
52
+ : tzPart.includes(':')
53
+ ? tzPart
54
+ : `${tzPart.slice(0, 3)}:${tzPart.slice(3)}`;
55
+ const ms = Date.parse(`${datePart}T${timePart}${normalizedTz}`);
56
+ return Number.isNaN(ms) ? null : ms;
57
+ }
58
+ function mentions(text, issueNumber, repo) {
59
+ const foldedRepo = repo === null ? null : fold(repo);
60
+ for (const match of text.matchAll(REFERENCE_RE)) {
61
+ if (Number(match[2]) !== issueNumber)
62
+ continue;
63
+ if (match[1] === undefined || foldedRepo === null || fold(match[1]) === foldedRepo)
64
+ return true;
65
+ }
66
+ for (const match of text.matchAll(ISSUE_URL_RE)) {
67
+ if (Number(match[2]) !== issueNumber)
68
+ continue;
69
+ if (foldedRepo === null || fold(match[1]) === foldedRepo)
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+ function isIssueBranch(name, issueNumber) {
75
+ const match = BRANCH_RE.exec(name);
76
+ return match !== null && Number(match[1]) === issueNumber;
77
+ }
78
+ function currentAssignments(events) {
79
+ const timed = [];
80
+ for (const item of events) {
81
+ if (item.event !== 'assigned' && item.event !== 'unassigned')
82
+ continue;
83
+ const at = parseIsoTime(item.created_at ?? item.createdAt);
84
+ if (at !== null)
85
+ timed.push({ at, event: item });
86
+ }
87
+ timed.sort((a, b) => a.at - b.at);
88
+ const since = new Map();
89
+ for (const { at, event } of timed) {
90
+ const who = fold(extractLogin(event.assignee));
91
+ if (event.event === 'assigned')
92
+ since.set(who, at);
93
+ else
94
+ since.delete(who);
95
+ }
96
+ return since;
97
+ }
98
+ function labelSetter(events, label) {
99
+ const timed = [];
100
+ for (const item of events) {
101
+ if (item.event !== 'labeled' && item.event !== 'unlabeled')
102
+ continue;
103
+ if (typeof item.label !== 'object' || item.label === null || Array.isArray(item.label))
104
+ continue;
105
+ if (item.label.name !== label)
106
+ continue;
107
+ const at = parseIsoTime(item.created_at ?? item.createdAt);
108
+ if (at !== null)
109
+ timed.push({ at, event: item });
110
+ }
111
+ timed.sort((a, b) => a.at - b.at);
112
+ let setter = null;
113
+ for (const { at, event } of timed) {
114
+ setter = event.event === 'labeled' ? { who: fold(extractLogin(event.actor)), at } : null;
115
+ }
116
+ return setter;
117
+ }
118
+ function computeClaimTimes(issue, events, label) {
119
+ const since = currentAssignments(events);
120
+ const missing = issue.assignees.filter((login) => !since.has(fold(login)));
121
+ if (missing.length > 0) {
122
+ throw new UnusableClaimError(`No assignment event for: ${missing.join(', ')}.`);
123
+ }
124
+ const setter = labelSetter(events, label);
125
+ const reporter = fold(issue.author);
126
+ const times = new Map();
127
+ for (const login of issue.assignees) {
128
+ const who = fold(login);
129
+ const assignedAt = since.get(who);
130
+ if (who !== reporter) {
131
+ times.set(who, assignedAt);
132
+ }
133
+ else if (setter !== null && setter.who === who) {
134
+ times.set(who, Math.max(assignedAt, setter.at));
135
+ }
136
+ else {
137
+ times.set(who, null);
138
+ }
139
+ }
140
+ return times;
141
+ }
142
+ function pickVerdict(findings, fallback) {
143
+ const found = new Set(findings.map((finding) => finding.verdict));
144
+ return STOP_ORDER.find((verdict) => found.has(verdict)) ?? fallback;
145
+ }
146
+ function pushFinding(findings, rule, verdict, detail, who) {
147
+ const finding = { rule, verdict, detail };
148
+ if (who && who.length > 0)
149
+ finding.who = who;
150
+ findings.push(finding);
151
+ }
152
+ export function evaluateClaim(issue, pulls, branches, events, options) {
153
+ const findings = [];
154
+ const { number: issueNumber } = issue;
155
+ const { label, phase, repo } = options;
156
+ const me = fold(options.claimant);
157
+ const hasLabel = issue.labels.includes(label);
158
+ const others = issue.assignees.filter((login) => fold(login) !== me);
159
+ const mine = others.length < issue.assignees.length;
160
+ const reporter = fold(issue.author);
161
+ const nonReporterOthers = others.filter((login) => fold(login) !== reporter);
162
+ const claimers = nonReporterOthers.length > 0 ? nonReporterOthers : hasLabel ? others : [];
163
+ const nonReporterAssignees = issue.assignees.filter((login) => fold(login) !== reporter);
164
+ const holding = nonReporterAssignees.length > 0 ? nonReporterAssignees : hasLabel ? issue.assignees : [];
165
+ const linked = pulls.filter((pull) => mentions(pull.text, issueNumber, repo) || isIssueBranch(pull.head, issueNumber));
166
+ const otherPulls = linked.filter((pull) => fold(pull.author) !== me);
167
+ const claimBranches = branches.filter((name) => isIssueBranch(name, issueNumber));
168
+ const holders = {
169
+ assignees: issue.assignees,
170
+ reporter: issue.author,
171
+ label: hasLabel,
172
+ pulls: linked.map((pull) => ({ number: pull.number, author: pull.author })),
173
+ branches: claimBranches,
174
+ };
175
+ if (phase === 'release') {
176
+ if (mine)
177
+ pushFinding(findings, 'CL10', 'still-held', 'The claimant is still assigned.');
178
+ let kept = others.filter((login) => fold(login) !== reporter);
179
+ if (hasLabel && kept.length === 0 && others.length > 0) {
180
+ if (events === null) {
181
+ throw new UnusableClaimError('The issue author is still assigned: --events-json is needed to tell whether the claim label is theirs.');
182
+ }
183
+ const times = computeClaimTimes(issue, events, label);
184
+ kept = others.filter((login) => times.get(fold(login)) !== null);
185
+ }
186
+ if (hasLabel && kept.length === 0) {
187
+ pushFinding(findings, 'CL10', 'still-held', 'The claim label is still set and no one else holds the issue.');
188
+ }
189
+ return { verdict: pickVerdict(findings, 'released'), findings, holders };
190
+ }
191
+ if (phase === 'status') {
192
+ if (linked.length > 1) {
193
+ pushFinding(findings, 'CL11', 'duplicate-work', 'More than one open pull request works on this issue.', linked.map((pull) => `#${String(pull.number)}`));
194
+ }
195
+ if (hasLabel && issue.assignees.length === 0) {
196
+ pushFinding(findings, 'CL6', 'orphan-claim', 'The claim label is set but nobody is assigned.');
197
+ }
198
+ const held = holding.length > 0 || hasLabel;
199
+ if (held && linked.length === 0 && claimBranches.length === 0) {
200
+ if (issue.updated === null) {
201
+ throw new UnusableClaimError('Issue JSON needs updated_at to judge a stale claim.');
202
+ }
203
+ if (options.now - issue.updated > options.stale_days * DAY_MS) {
204
+ pushFinding(findings, 'CL12', 'stale-claim', `Claimed with no open pull request, no feat/<n>- branch and no activity for more than ${options.stale_days} days.`, holding);
205
+ }
206
+ }
207
+ const claimed = held || linked.length > 0 || claimBranches.length > 0;
208
+ return { verdict: pickVerdict(findings, claimed ? 'claimed' : 'unclaimed'), findings, holders };
209
+ }
210
+ const branch = options.branch ?? '';
211
+ if (!isIssueBranch(branch, issueNumber)) {
212
+ pushFinding(findings, 'CL7', 'invalid-branch', `The delivery branch must be feat/${issueNumber}-<slug>.`);
213
+ }
214
+ if (!issue.open) {
215
+ pushFinding(findings, 'CL2', 'closed', 'The issue is closed; reopen it through issue-dedup before claiming.');
216
+ }
217
+ if (otherPulls.length > 0) {
218
+ pushFinding(findings, 'CL4', 'claimed-by-other', 'An open pull request by someone else works on this issue.', otherPulls.map((pull) => `#${String(pull.number)} @${pull.author}`));
219
+ }
220
+ const foreign = claimBranches.filter((name) => name !== branch);
221
+ if (foreign.length > 0) {
222
+ pushFinding(findings, 'CL5', 'claimed-by-other', `Another feat/${issueNumber}- branch exists on the remote.`, foreign);
223
+ }
224
+ if (phase === 'check') {
225
+ if (claimers.length > 0) {
226
+ pushFinding(findings, 'CL3', 'claimed-by-other', 'The issue is assigned to someone else.', claimers);
227
+ }
228
+ if (hasLabel && issue.assignees.length === 0) {
229
+ pushFinding(findings, 'CL6', 'orphan-claim', 'The claim label is set but nobody is assigned.');
230
+ }
231
+ const yours = mine || linked.some((pull) => fold(pull.author) === me);
232
+ return { verdict: pickVerdict(findings, yours ? 'claimed-by-you' : 'free'), findings, holders };
233
+ }
234
+ if (!mine || !hasLabel) {
235
+ pushFinding(findings, 'CL8', 'unrecorded-claim', 'After claiming, the claimant must be assigned and the label set.');
236
+ }
237
+ if (mine && others.length > 0) {
238
+ if (events === null) {
239
+ throw new UnusableClaimError('Several assignees: --events-json is needed to order the assignments.');
240
+ }
241
+ const times = computeClaimTimes(issue, events, label);
242
+ const claiming = issue.assignees.filter((login) => times.get(fold(login)) !== null);
243
+ let winner = null;
244
+ for (const login of claiming) {
245
+ if (winner === null) {
246
+ winner = login;
247
+ continue;
248
+ }
249
+ const tLogin = times.get(fold(login));
250
+ const tWinner = times.get(fold(winner));
251
+ if (tLogin < tWinner || (tLogin === tWinner && fold(login) < fold(winner)))
252
+ winner = login;
253
+ }
254
+ if (fold(winner) !== me) {
255
+ pushFinding(findings, 'CL9', 'contended-lost', 'Someone else was assigned first; unassign yourself and remove nothing else.', winner === null ? undefined : [winner]);
256
+ }
257
+ }
258
+ return { verdict: pickVerdict(findings, 'claimed-by-you'), findings, holders };
259
+ }
@@ -0,0 +1,5 @@
1
+ import { type EventRecord, type IssueRecord, type PullRecord } from './evaluation.ts';
2
+ export declare function loadIssue(path: string): IssueRecord;
3
+ export declare function loadPulls(path: string): PullRecord[];
4
+ export declare function loadBranches(path: string): string[];
5
+ export declare function loadEvents(path: string): EventRecord[];
@@ -0,0 +1,116 @@
1
+ /**
2
+ * LAYER: Infrastructure
3
+ * Contains: Offline JSON and remote branch list loaders for check-issue-claim.
4
+ * Rules: Read supplied files only; never touch GitHub or run git commands.
5
+ * BigO: O(n) score:3
6
+ * keywords: [IssueJsonLoader, SlurpedPages]
7
+ * GOAL: Parse GitHub issue, pull-request, event, and branch artifacts into domain records.
8
+ */
9
+ import { readFileSync } from 'node:fs';
10
+ import { extractLogin, parseIsoTime, UnusableClaimError, } from "./evaluation.js";
11
+ function readText(path, label) {
12
+ try {
13
+ return readFileSync(path, 'utf8');
14
+ }
15
+ catch {
16
+ throw new UnusableClaimError(`${label} cannot be read.`);
17
+ }
18
+ }
19
+ function loadJson(path, label) {
20
+ const raw = readText(path, label);
21
+ try {
22
+ return JSON.parse(raw);
23
+ }
24
+ catch {
25
+ throw new UnusableClaimError(`${label} is not valid JSON.`);
26
+ }
27
+ }
28
+ function flattenPages(value) {
29
+ if (Array.isArray(value) && value.every(Array.isArray)) {
30
+ return value.flat();
31
+ }
32
+ return value;
33
+ }
34
+ export function loadIssue(path) {
35
+ const raw = loadJson(path, 'Issue JSON');
36
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
37
+ throw new UnusableClaimError('Issue JSON needs a state.');
38
+ }
39
+ const obj = raw;
40
+ if (typeof obj.state !== 'string') {
41
+ throw new UnusableClaimError('Issue JSON needs a state.');
42
+ }
43
+ if (typeof obj.number !== 'number' || !Number.isInteger(obj.number)) {
44
+ throw new UnusableClaimError('Issue JSON needs a numeric number.');
45
+ }
46
+ const labels = [];
47
+ if (Array.isArray(obj.labels)) {
48
+ for (const label of obj.labels) {
49
+ const name = typeof label === 'object' && label !== null && !Array.isArray(label)
50
+ ? label.name
51
+ : label;
52
+ if (typeof name === 'string')
53
+ labels.push(name);
54
+ }
55
+ }
56
+ const assignees = [];
57
+ if (Array.isArray(obj.assignees)) {
58
+ for (const entry of obj.assignees) {
59
+ const login = extractLogin(entry);
60
+ if (login !== null)
61
+ assignees.push(login);
62
+ }
63
+ }
64
+ return {
65
+ number: obj.number,
66
+ author: extractLogin(obj.user) ?? extractLogin(obj.author),
67
+ open: obj.state.toLowerCase() === 'open',
68
+ assignees,
69
+ labels,
70
+ updated: parseIsoTime(obj.updated_at ?? obj.updatedAt),
71
+ };
72
+ }
73
+ export function loadPulls(path) {
74
+ const raw = flattenPages(loadJson(path, 'Pull request JSON'));
75
+ if (!Array.isArray(raw)) {
76
+ throw new UnusableClaimError('Pull request JSON must be an array.');
77
+ }
78
+ const pulls = [];
79
+ for (const item of raw) {
80
+ if (typeof item !== 'object' || item === null || Array.isArray(item))
81
+ continue;
82
+ const obj = item;
83
+ const headObj = typeof obj.head === 'object' && obj.head !== null && !Array.isArray(obj.head)
84
+ ? obj.head
85
+ : undefined;
86
+ const headRef = (typeof headObj?.ref === 'string' ? headObj.ref : undefined)
87
+ ?? (typeof obj.headRefName === 'string' ? obj.headRefName : undefined)
88
+ ?? '';
89
+ const title = typeof obj.title === 'string' ? obj.title : '';
90
+ const body = typeof obj.body === 'string' ? obj.body : '';
91
+ pulls.push({
92
+ number: obj.number,
93
+ author: extractLogin(obj.user) ?? extractLogin(obj.author),
94
+ head: headRef,
95
+ text: `${title}\n${body}`,
96
+ });
97
+ }
98
+ return pulls;
99
+ }
100
+ export function loadBranches(path) {
101
+ const names = [];
102
+ for (const line of readText(path, 'Branch list').split(/\r?\n/)) {
103
+ const match = /refs\/heads\/(\S+)/.exec(line);
104
+ const name = match?.[1] ?? line.trim();
105
+ if (name !== '')
106
+ names.push(name);
107
+ }
108
+ return names;
109
+ }
110
+ export function loadEvents(path) {
111
+ const raw = flattenPages(loadJson(path, 'Issue events JSON'));
112
+ if (!Array.isArray(raw)) {
113
+ throw new UnusableClaimError('Issue events JSON must be an array.');
114
+ }
115
+ return raw.filter((item) => typeof item === 'object' && item !== null && !Array.isArray(item));
116
+ }
@@ -0,0 +1,7 @@
1
+ export declare const listZedCommandsUsage = "bbc list-zed-commands [project-dir] [--agent <name>]";
2
+ export declare function parseZedArgs(argv: readonly string[]): {
3
+ readonly agent: string;
4
+ readonly cwd: string;
5
+ } | null;
6
+ export declare function resolveZedLauncher(name: string): string | null;
7
+ export declare function listZedCommands(argv: readonly string[]): Promise<number>;
@@ -0,0 +1,288 @@
1
+ /**
2
+ * LAYER: Interface
3
+ * Contains: ACP handshake probe for Zed-hosted external agents.
4
+ * Rules: Read-only; open one ACP session, print advertised slash commands, and exit without prompting.
5
+ * BigO: O(n) score:3
6
+ * keywords: [ListZedCommands, AcpHandshake, ZedRegistry, SlashCommands]
7
+ * GOAL: Perform Zed's ACP initialize + session/new handshake and list advertised slash commands.
8
+ */
9
+ import { spawn } from 'node:child_process';
10
+ import { existsSync, readdirSync, realpathSync } from 'node:fs';
11
+ import { homedir } from 'node:os';
12
+ import { join, resolve } from 'node:path';
13
+ export const listZedCommandsUsage = 'bbc list-zed-commands [project-dir] [--agent <name>]';
14
+ const HELP = 'List the slash commands a Zed-hosted agent advertises for a project.\n\n' +
15
+ 'Usage:\n' +
16
+ ' bbc list-zed-commands [project-dir] [--agent cursor]\n';
17
+ const DEFAULT_SESSION_GRACE_MS = 20_000;
18
+ const DEFAULT_OVERALL_TIMEOUT_MS = 60_000;
19
+ const SCOPE_RE = /\((project|user) skill\)$/;
20
+ export function parseZedArgs(argv) {
21
+ if (argv.includes('--help') || argv.includes('-h'))
22
+ return null;
23
+ let agent = 'cursor';
24
+ let agentValIdx = -1;
25
+ const agentFlagIdx = argv.indexOf('--agent');
26
+ if (agentFlagIdx >= 0 && agentFlagIdx + 1 < argv.length) {
27
+ agent = argv[agentFlagIdx + 1];
28
+ agentValIdx = agentFlagIdx + 1;
29
+ }
30
+ let project = null;
31
+ for (let i = 0; i < argv.length; i += 1) {
32
+ const item = argv[i];
33
+ if (i === agentFlagIdx || i === agentValIdx)
34
+ continue;
35
+ if (!item.startsWith('--') && item !== agent) {
36
+ project = item;
37
+ break;
38
+ }
39
+ }
40
+ const target = project ?? process.cwd();
41
+ const realCwd = existsSync(target) ? realpathSync(target) : resolve(target);
42
+ return { agent, cwd: realCwd };
43
+ }
44
+ export function resolveZedLauncher(name) {
45
+ const home = process.env.HOME || homedir();
46
+ const roots = [];
47
+ if (process.env.LOCALAPPDATA) {
48
+ roots.push(join(process.env.LOCALAPPDATA, 'Zed', 'external_agents', 'registry', name));
49
+ }
50
+ roots.push(join(home, 'Library', 'Application Support', 'Zed', 'external_agents', 'registry', name), join(home, '.local', 'share', 'zed', 'external_agents', 'registry', name));
51
+ for (const root of roots) {
52
+ if (!existsSync(root))
53
+ continue;
54
+ let entries;
55
+ try {
56
+ entries = readdirSync(root);
57
+ }
58
+ catch {
59
+ continue;
60
+ }
61
+ const version = entries.find((entry) => entry.startsWith('v_'));
62
+ if (!version)
63
+ continue;
64
+ const dist = join(root, version, 'dist-package');
65
+ const candidates = [
66
+ join(dist, `${name}-agent.ps1`),
67
+ join(dist, `${name}-agent`),
68
+ join(dist, `${name}-agent.cmd`),
69
+ ];
70
+ for (const candidate of candidates) {
71
+ if (existsSync(candidate))
72
+ return candidate;
73
+ }
74
+ }
75
+ return null;
76
+ }
77
+ function isPlainObject(value) {
78
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
79
+ }
80
+ function launcherCommand(launcher) {
81
+ if (process.platform === 'win32' && launcher.endsWith('.ps1')) {
82
+ return ['powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', launcher, 'acp']];
83
+ }
84
+ if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(launcher)) {
85
+ return [process.env.ComSpec || 'cmd.exe', ['/d', '/c', launcher, 'acp']];
86
+ }
87
+ return [launcher, ['acp']];
88
+ }
89
+ export async function listZedCommands(argv) {
90
+ const parsed = parseZedArgs(argv);
91
+ if (parsed === null) {
92
+ process.stdout.write(`${HELP}\n`);
93
+ return 0;
94
+ }
95
+ const { agent, cwd } = parsed;
96
+ const launcher = resolveZedLauncher(agent);
97
+ if (!launcher) {
98
+ process.stderr.write(`No ${agent} agent found in Zed's ACP registry.\n` +
99
+ 'Install it from the Agent Panel (zed: acp registry) or pass --agent <name>.\n');
100
+ return 2;
101
+ }
102
+ const [cmd, args] = launcherCommand(launcher);
103
+ const overallMs = Number.parseInt(process.env.BBC_ZED_OVERALL_MS ?? '', 10) || DEFAULT_OVERALL_TIMEOUT_MS;
104
+ const graceMs = Number.parseInt(process.env.BBC_ZED_GRACE_MS ?? '', 10) || DEFAULT_SESSION_GRACE_MS;
105
+ return new Promise((resolveExit) => {
106
+ let child;
107
+ try {
108
+ child = spawn(cmd, [...args], { cwd, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
109
+ }
110
+ catch (error) {
111
+ const msg = error instanceof Error ? error.message : String(error);
112
+ process.stderr.write(`Could not start ${agent}: ${msg}\n`);
113
+ resolveExit(2);
114
+ return;
115
+ }
116
+ let settled = false;
117
+ let sessionOpen = false;
118
+ let stdoutBuf = '';
119
+ let stderrBuf = '';
120
+ let stderrEnded = false;
121
+ let exitCode = null;
122
+ let overallTimer = null;
123
+ let graceTimer = null;
124
+ const cleanupTimers = () => {
125
+ if (overallTimer)
126
+ clearTimeout(overallTimer);
127
+ if (graceTimer)
128
+ clearTimeout(graceTimer);
129
+ overallTimer = null;
130
+ graceTimer = null;
131
+ };
132
+ const finish = (code) => {
133
+ if (settled)
134
+ return;
135
+ settled = true;
136
+ cleanupTimers();
137
+ try {
138
+ if (exitCode === null && child.exitCode === null) {
139
+ child.kill();
140
+ }
141
+ }
142
+ catch {
143
+ // Ignore errors when child already exited
144
+ }
145
+ resolveExit(code);
146
+ };
147
+ const flushStderrText = (chunk) => {
148
+ stderrBuf += chunk;
149
+ const lines = stderrBuf.split(/\r?\n/);
150
+ stderrBuf = lines.pop() ?? '';
151
+ for (const raw of lines) {
152
+ const trimmed = raw.trim();
153
+ if (trimmed)
154
+ process.stderr.write(`[${agent}] ${trimmed}\n`);
155
+ }
156
+ };
157
+ const flushRemainingStderr = () => {
158
+ const trimmed = stderrBuf.trim();
159
+ stderrBuf = '';
160
+ if (trimmed)
161
+ process.stderr.write(`[${agent}] ${trimmed}\n`);
162
+ };
163
+ const send = (payload) => {
164
+ try {
165
+ child.stdin?.write(`${JSON.stringify(payload)}\n`);
166
+ }
167
+ catch {
168
+ // Ignore broken pipe if child exited early
169
+ }
170
+ };
171
+ overallTimer = setTimeout(() => {
172
+ process.stderr.write(`Timeout: the agent did not advertise commands within ${Math.round(overallMs / 1000)}s.\n`);
173
+ finish(1);
174
+ }, overallMs);
175
+ child.on('error', (error) => {
176
+ const reason = error.code || error.message;
177
+ process.stderr.write(`Could not start ${agent}: ${reason}\n`);
178
+ finish(2);
179
+ });
180
+ child.on('exit', (code) => {
181
+ exitCode = code;
182
+ });
183
+ child.stderr?.on('data', (chunk) => {
184
+ flushStderrText(chunk.toString('utf8'));
185
+ });
186
+ child.stderr?.on('end', () => {
187
+ stderrEnded = true;
188
+ flushRemainingStderr();
189
+ });
190
+ const handleStdoutLine = (rawLine) => {
191
+ const line = rawLine.trim();
192
+ if (!line || settled)
193
+ return;
194
+ let parsedMsg;
195
+ try {
196
+ parsedMsg = JSON.parse(line);
197
+ }
198
+ catch {
199
+ return;
200
+ }
201
+ if (!isPlainObject(parsedMsg))
202
+ return;
203
+ const ident = parsedMsg.id;
204
+ if (ident === 1 && typeof ident === 'number') {
205
+ send({ jsonrpc: '2.0', id: 2, method: 'session/new', params: { cwd, mcpServers: [] } });
206
+ return;
207
+ }
208
+ if (ident === 2 && typeof ident === 'number') {
209
+ if (parsedMsg.error) {
210
+ flushRemainingStderr();
211
+ process.stderr.write(`Session error: ${JSON.stringify(parsedMsg.error)}\n`);
212
+ finish(1);
213
+ return;
214
+ }
215
+ sessionOpen = true;
216
+ if (!graceTimer) {
217
+ graceTimer = setTimeout(() => {
218
+ finish(0);
219
+ }, graceMs);
220
+ }
221
+ return;
222
+ }
223
+ const params = isPlainObject(parsedMsg.params) ? parsedMsg.params : null;
224
+ const update = params && isPlainObject(params.update) ? params.update : null;
225
+ if (update && update.sessionUpdate === 'available_commands_update') {
226
+ const commands = Array.isArray(update.availableCommands) ? update.availableCommands : [];
227
+ process.stdout.write(`${commands.length} commands advertised for ${cwd} (${agent})\n`);
228
+ for (const entry of commands) {
229
+ if (!isPlainObject(entry))
230
+ continue;
231
+ const desc = typeof entry.description === 'string' ? entry.description : null;
232
+ const scope = desc ? SCOPE_RE.exec(desc) : null;
233
+ const scopeSuffix = scope && scope[1] ? ` (${scope[1]} skill)` : '';
234
+ process.stdout.write(` /${String(entry.name)}${scopeSuffix}\n`);
235
+ }
236
+ }
237
+ };
238
+ child.stdout?.on('data', (chunk) => {
239
+ stdoutBuf += chunk.toString('utf8');
240
+ const lines = stdoutBuf.split(/\r?\n/);
241
+ stdoutBuf = lines.pop() ?? '';
242
+ for (const line of lines) {
243
+ handleStdoutLine(line);
244
+ if (settled)
245
+ return;
246
+ }
247
+ });
248
+ child.stdout?.on('end', () => {
249
+ if (stdoutBuf.trim()) {
250
+ handleStdoutLine(stdoutBuf);
251
+ stdoutBuf = '';
252
+ }
253
+ if (settled)
254
+ return;
255
+ if (sessionOpen) {
256
+ finish(0);
257
+ return;
258
+ }
259
+ const waitStderrAndReport = () => {
260
+ flushRemainingStderr();
261
+ const reportedCode = exitCode !== null ? String(exitCode) : 'still running';
262
+ process.stderr.write(`The ${agent} agent exited (code ${reportedCode}) before opening a session.\n`);
263
+ finish(1);
264
+ };
265
+ if (stderrEnded && exitCode !== null) {
266
+ waitStderrAndReport();
267
+ return;
268
+ }
269
+ let checks = 0;
270
+ const pollTimer = setInterval(() => {
271
+ checks += 1;
272
+ if ((stderrEnded && exitCode !== null) || checks >= 20) {
273
+ clearInterval(pollTimer);
274
+ waitStderrAndReport();
275
+ }
276
+ }, 25);
277
+ });
278
+ send({
279
+ jsonrpc: '2.0',
280
+ id: 1,
281
+ method: 'initialize',
282
+ params: {
283
+ protocolVersion: 1,
284
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
285
+ },
286
+ });
287
+ });
288
+ }
@@ -0,0 +1,3 @@
1
+ export declare const planIssueTriageUsage = "bbc plan-issue-triage --repo <owner/repo> --issue-json <file> --labels-json <file> --proposal-json <file> --author-assignable yes|no|unknown [--claim-label status:in-progress]";
2
+ export declare function priorityLevel(name: string): readonly [boolean, number | null];
3
+ export declare function planIssueTriage(argv: readonly string[]): number;