@bbcsoftwarefactory/cli 0.1.0 → 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 (126) 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.d.ts +2 -0
  6. package/dist/bbc.js +124 -0
  7. package/dist/bigo/complexity.d.ts +18 -0
  8. package/dist/bigo/complexity.js +139 -0
  9. package/dist/bigo/functions.d.ts +5 -0
  10. package/dist/bigo/functions.js +174 -0
  11. package/dist/bigo/keywords.d.ts +1 -0
  12. package/dist/bigo/keywords.js +43 -0
  13. package/dist/bigo/lexical.d.ts +14 -0
  14. package/dist/bigo/lexical.js +69 -0
  15. package/dist/bigo/source-files.d.ts +1 -0
  16. package/dist/bigo/source-files.js +80 -0
  17. package/dist/change-lane/classification.d.ts +41 -0
  18. package/dist/change-lane/classification.js +104 -0
  19. package/dist/change-lane/git.d.ts +8 -0
  20. package/dist/change-lane/git.js +105 -0
  21. package/dist/check-issue-claim.d.ts +2 -0
  22. package/dist/check-issue-claim.js +146 -0
  23. package/dist/check-worktree-guard.d.ts +2 -0
  24. package/dist/check-worktree-guard.js +114 -0
  25. package/dist/classify-change-lane.d.ts +2 -0
  26. package/dist/classify-change-lane.js +128 -0
  27. package/dist/diff-scope/git-diff.d.ts +25 -0
  28. package/dist/diff-scope/git-diff.js +146 -0
  29. package/dist/error-scan.d.ts +3 -0
  30. package/dist/error-scan.js +216 -0
  31. package/dist/export-public.d.ts +9 -0
  32. package/dist/export-public.js +274 -0
  33. package/dist/extract-diff-scope.d.ts +2 -0
  34. package/dist/extract-diff-scope.js +111 -0
  35. package/dist/fetch-issue-attachments.d.ts +22 -0
  36. package/dist/fetch-issue-attachments.js +325 -0
  37. package/dist/issue-claim/evaluation.d.ts +66 -0
  38. package/dist/issue-claim/evaluation.js +259 -0
  39. package/dist/issue-claim/loaders.d.ts +5 -0
  40. package/dist/issue-claim/loaders.js +116 -0
  41. package/dist/list-zed-commands.d.ts +7 -0
  42. package/dist/list-zed-commands.js +288 -0
  43. package/dist/measure-bigo.d.ts +2 -0
  44. package/dist/measure-bigo.js +84 -0
  45. package/dist/plan-issue-triage.d.ts +3 -0
  46. package/dist/plan-issue-triage.js +404 -0
  47. package/dist/question-gate/ledger.d.ts +5 -0
  48. package/dist/question-gate/ledger.js +115 -0
  49. package/dist/question-gate/rules.d.ts +40 -0
  50. package/dist/question-gate/rules.js +483 -0
  51. package/dist/recap/board.d.ts +5 -0
  52. package/dist/recap/board.js +384 -0
  53. package/dist/recap/git-and-github.d.ts +11 -0
  54. package/dist/recap/git-and-github.js +620 -0
  55. package/dist/recap/report-and-hud.d.ts +2 -0
  56. package/dist/recap/report-and-hud.js +294 -0
  57. package/dist/recap/time-and-refs.d.ts +27 -0
  58. package/dist/recap/time-and-refs.js +148 -0
  59. package/dist/recap.d.ts +2 -0
  60. package/dist/recap.js +217 -0
  61. package/dist/render-workflow.d.ts +2 -0
  62. package/dist/render-workflow.js +142 -0
  63. package/dist/resolve-containers.d.ts +2 -0
  64. package/dist/resolve-containers.js +96 -0
  65. package/dist/review-loop.d.ts +7 -0
  66. package/dist/review-loop.js +622 -0
  67. package/dist/save-counts.d.ts +2 -0
  68. package/dist/save-counts.js +191 -0
  69. package/dist/summarize-logs.d.ts +2 -0
  70. package/dist/summarize-logs.js +41 -0
  71. package/dist/sweep-github.d.ts +10 -0
  72. package/dist/sweep-github.js +453 -0
  73. package/dist/sweep-issues.d.ts +56 -0
  74. package/dist/sweep-issues.js +650 -0
  75. package/dist/sweep.d.ts +2 -0
  76. package/dist/sweep.js +301 -0
  77. package/dist/triage-question.d.ts +2 -0
  78. package/dist/triage-question.js +189 -0
  79. package/dist/validate-skills.d.ts +2 -0
  80. package/dist/validate-skills.js +48 -0
  81. package/dist/watch-live.d.ts +7 -0
  82. package/dist/watch-live.js +83 -0
  83. package/dist/watcher/config.d.ts +11 -0
  84. package/dist/watcher/config.js +265 -0
  85. package/dist/watcher/live-classifier.d.ts +52 -0
  86. package/dist/watcher/live-classifier.js +510 -0
  87. package/dist/watcher/safe-fs.d.ts +9 -0
  88. package/dist/watcher/safe-fs.js +159 -0
  89. package/dist/watcher/stream.d.ts +27 -0
  90. package/dist/watcher/stream.js +340 -0
  91. package/dist/watcher/summarizer.d.ts +19 -0
  92. package/dist/watcher/summarizer.js +121 -0
  93. package/dist/wave3/process.d.ts +14 -0
  94. package/dist/wave3/process.js +84 -0
  95. package/dist/wave4/process.d.ts +14 -0
  96. package/dist/wave4/process.js +128 -0
  97. package/dist/workflow/render.d.ts +13 -0
  98. package/dist/workflow/render.js +31 -0
  99. package/dist/workflow/schema.d.ts +25 -0
  100. package/dist/workflow/schema.js +99 -0
  101. package/dist/workflow-auditor/audit.d.ts +27 -0
  102. package/dist/workflow-auditor/audit.js +583 -0
  103. package/dist/workflow-auditor/ledger-io.d.ts +5 -0
  104. package/dist/workflow-auditor/ledger-io.js +99 -0
  105. package/dist/workflow-auditor/skills-validator.d.ts +10 -0
  106. package/dist/workflow-auditor/skills-validator.js +533 -0
  107. package/dist/worktree-guard/evaluation.d.ts +19 -0
  108. package/dist/worktree-guard/evaluation.js +84 -0
  109. package/dist/worktree-guard/git.d.ts +3 -0
  110. package/dist/worktree-guard/git.js +61 -0
  111. package/package.json +32 -33
  112. package/src/bbc.ts +0 -39
  113. package/src/bigo/complexity.ts +0 -138
  114. package/src/bigo/functions.ts +0 -183
  115. package/src/bigo/keywords.ts +0 -41
  116. package/src/bigo/lexical.ts +0 -68
  117. package/src/bigo/source-files.ts +0 -80
  118. package/src/change-lane/classification.ts +0 -128
  119. package/src/change-lane/git.ts +0 -110
  120. package/src/classify-change-lane.ts +0 -140
  121. package/src/diff-scope/git-diff.ts +0 -161
  122. package/src/extract-diff-scope.ts +0 -130
  123. package/src/measure-bigo.ts +0 -86
  124. package/src/render-workflow.ts +0 -144
  125. package/src/workflow/render.ts +0 -40
  126. package/src/workflow/schema.ts +0 -141
@@ -0,0 +1,453 @@
1
+ /**
2
+ * LAYER: Application
3
+ * Contains: GitHub GraphQL snapshot fetcher and exact plan applier for /issue-clean-and-close.
4
+ * Rules: Bodies never leave toSnapshot; apply executes only approved plan steps in order.
5
+ * BigO: O(n) score:4
6
+ * keywords: [SweepGithub, GraphQLSnapshot, PlanApplier, SweepCommands]
7
+ * GOAL: Isolate all GitHub reads and writes for issue sweeping behind strict snapshot/plan contracts.
8
+ */
9
+ import { readFileSync, writeFileSync } from 'node:fs';
10
+ import { parseCommandOverride, percentEncodeAll, runCommand } from "./wave3/process.js";
11
+ export const sweepGithubUsage = 'bbc sweep-github <fetch|apply> --repo <owner/repo> [--out <snapshot.json> | --plan <plan.json>] [--only 12,15] [--dry-run]';
12
+ const DEFAULT_SWEEPER = 'github-actions[bot]';
13
+ const PAGE_SIZE = 30;
14
+ const MAX_PAGES = 100;
15
+ const PR_TEXT_LIMIT = 4000;
16
+ const ISSUE_REFERENCE_RE = /#\d|\/issues\/\d/;
17
+ const MARKER_RE = /<!-- issue-sweeper:([A-Za-z0-9]+) -->/;
18
+ const REPORT_MARKER = '<!-- issue-sweeper:report -->';
19
+ const PR_FIELDS = 'number url state mergedAt title body repository { nameWithOwner } mergeCommit { oid }';
20
+ const REPO_RE = /^[\w.-]+\/[\w.-]+$/;
21
+ const QUERY = `
22
+ query($owner: String!, $name: String!, $cursor: String) {
23
+ repository(owner: $owner, name: $name) {
24
+ nameWithOwner
25
+ labels(first: 100) { nodes { name } }
26
+ issues(states: OPEN, first: ${PAGE_SIZE}, after: $cursor, orderBy: {field: CREATED_AT, direction: ASC}) {
27
+ pageInfo { hasNextPage endCursor }
28
+ nodes {
29
+ number title url createdAt body
30
+ author { login }
31
+ labels(first: 50) { nodes { name } }
32
+ assignees(first: 10) { nodes { login } }
33
+ refs: timelineItems(first: 25, itemTypes: [CONNECTED_EVENT, DISCONNECTED_EVENT, CROSS_REFERENCED_EVENT]) {
34
+ pageInfo { hasNextPage }
35
+ nodes {
36
+ __typename
37
+ ... on ConnectedEvent { createdAt subject { ... on PullRequest { ${PR_FIELDS} } } }
38
+ ... on DisconnectedEvent { createdAt subject { ... on PullRequest { ${PR_FIELDS} } } }
39
+ ... on CrossReferencedEvent { createdAt willCloseTarget source { ... on PullRequest { ${PR_FIELDS} } } }
40
+ }
41
+ }
42
+ recent: timelineItems(last: 25, itemTypes: [ISSUE_COMMENT, LABELED_EVENT, UNLABELED_EVENT, REOPENED_EVENT]) {
43
+ nodes {
44
+ __typename
45
+ ... on IssueComment { createdAt author { login } body }
46
+ ... on LabeledEvent { createdAt actor { login } label { name } }
47
+ ... on UnlabeledEvent { createdAt actor { login } label { name } }
48
+ ... on ReopenedEvent { createdAt actor { login } }
49
+ }
50
+ }
51
+ }
52
+ }
53
+ }
54
+ }
55
+ `;
56
+ const LABEL_EVENTS = {
57
+ LabeledEvent: 'labeled',
58
+ UnlabeledEvent: 'unlabeled',
59
+ };
60
+ const HELP = 'Usage: bbc sweep-github fetch --repo <owner/repo> --out <snapshot.json> [--sweeper-login github-actions[bot]]\n' +
61
+ ' bbc sweep-github apply --repo <owner/repo> --plan <plan.json> [--only 12,15] [--dry-run]\n' +
62
+ 'Needs an authenticated gh CLI (SWEEP_GH overrides the command); bbc sweep runs both steps.\n' +
63
+ 'Exit 0: done; 1: some writes failed (listed); 2: unusable input.';
64
+ export class SweepGithubUnusableError extends Error {
65
+ }
66
+ function isPlainObject(value) {
67
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
68
+ }
69
+ function fold(value) {
70
+ return typeof value === 'string' ? value.trim().toLowerCase() : '';
71
+ }
72
+ function bare(login) {
73
+ const f = fold(login);
74
+ return f.endsWith('[bot]') ? f.slice(0, -5) : f;
75
+ }
76
+ function extractLogin(value) {
77
+ const login = isPlainObject(value) ? value.login : null;
78
+ return typeof login === 'string' && login ? login : 'ghost';
79
+ }
80
+ function extractNodes(value) {
81
+ const nodes = isPlainObject(value) && Array.isArray(value.nodes) ? value.nodes : [];
82
+ return nodes.filter((node) => isPlainObject(node));
83
+ }
84
+ function extractPull(node) {
85
+ return isPlainObject(node) && 'state' in node && typeof node.number === 'number' && Number.isInteger(node.number)
86
+ ? node
87
+ : null;
88
+ }
89
+ function buildPrEntry(pr, at) {
90
+ const body = typeof pr.body === 'string' ? pr.body : '';
91
+ const references = body
92
+ .split(/\r?\n/)
93
+ .map((line) => line.trim())
94
+ .filter((line) => ISSUE_REFERENCE_RE.test(line));
95
+ const title = typeof pr.title === 'string' ? pr.title : '';
96
+ const text = [title, ...references].join('\n').slice(0, PR_TEXT_LIMIT);
97
+ const merge = isPlainObject(pr.mergeCommit) ? pr.mergeCommit : {};
98
+ const repo = isPlainObject(pr.repository) ? pr.repository : {};
99
+ return {
100
+ number: pr.number,
101
+ repo: repo.nameWithOwner ?? null,
102
+ state: pr.state ?? null,
103
+ merged_at: pr.mergedAt ?? null,
104
+ merge_commit: merge.oid ?? null,
105
+ url: pr.url ?? null,
106
+ will_close: false,
107
+ manual_link: false,
108
+ text,
109
+ referenced_at: at ?? null,
110
+ };
111
+ }
112
+ function extractPrs(refs) {
113
+ const found = new Map();
114
+ const sorted = [...extractNodes(refs)].sort((a, b) => String(a.createdAt ?? '').localeCompare(String(b.createdAt ?? '')));
115
+ for (const node of sorted) {
116
+ const kind = node.__typename;
117
+ const pr = extractPull(kind === 'CrossReferencedEvent' ? node.source : node.subject);
118
+ if (!pr)
119
+ continue;
120
+ const repoObj = isPlainObject(pr.repository) ? pr.repository : {};
121
+ const key = `${fold(repoObj.nameWithOwner)}:${String(pr.number)}`;
122
+ let entry = found.get(key);
123
+ if (!entry) {
124
+ entry = buildPrEntry(pr, node.createdAt);
125
+ found.set(key, entry);
126
+ }
127
+ if (kind === 'CrossReferencedEvent') {
128
+ entry.will_close = Boolean(entry.will_close) || node.willCloseTarget === true;
129
+ }
130
+ else {
131
+ entry.manual_link = kind === 'ConnectedEvent';
132
+ }
133
+ }
134
+ return [...found.values()];
135
+ }
136
+ function extractEvents(recent) {
137
+ const events = [];
138
+ for (const node of extractNodes(recent)) {
139
+ const kind = node.__typename;
140
+ const at = node.createdAt ?? null;
141
+ if (kind === 'IssueComment') {
142
+ const body = typeof node.body === 'string' ? node.body : '';
143
+ const match = MARKER_RE.exec(body);
144
+ events.push({
145
+ type: 'comment',
146
+ at,
147
+ actor: extractLogin(node.author),
148
+ marker: match ? match[1] : null,
149
+ });
150
+ }
151
+ else if (typeof kind === 'string' && kind in LABEL_EVENTS) {
152
+ const label = isPlainObject(node.label) ? node.label : {};
153
+ events.push({
154
+ type: LABEL_EVENTS[kind],
155
+ label: label.name ?? null,
156
+ at,
157
+ actor: extractLogin(node.actor),
158
+ });
159
+ }
160
+ else if (kind === 'ReopenedEvent') {
161
+ events.push({
162
+ type: 'reopened',
163
+ at,
164
+ actor: extractLogin(node.actor),
165
+ });
166
+ }
167
+ }
168
+ return events;
169
+ }
170
+ export function toSnapshot(pages, fetchedAt, sweeperLogin = DEFAULT_SWEEPER) {
171
+ const sweeper = bare(sweeperLogin);
172
+ if (pages.length === 0) {
173
+ throw new SweepGithubUnusableError('No GraphQL pages.');
174
+ }
175
+ const repos = pages.map((page) => isPlainObject(page) && isPlainObject(page.data) && isPlainObject(page.data.repository)
176
+ ? page.data.repository
177
+ : null);
178
+ if (repos.some((r) => r === null)) {
179
+ throw new SweepGithubUnusableError('GraphQL response has no repository; check the name and the token.');
180
+ }
181
+ const validRepos = repos;
182
+ const firstRepo = validRepos[0];
183
+ const snapshot = {
184
+ repo: firstRepo.nameWithOwner ?? null,
185
+ fetched_at: fetchedAt,
186
+ labels: extractNodes(firstRepo.labels).map((node) => node.name ?? null),
187
+ report_issue: null,
188
+ issues: [],
189
+ };
190
+ for (const repo of validRepos) {
191
+ for (const node of extractNodes(repo.issues)) {
192
+ const body = typeof node.body === 'string' ? node.body : '';
193
+ if (body.includes(REPORT_MARKER) && bare(extractLogin(node.author)) === sweeper) {
194
+ snapshot.report_issue = snapshot.report_issue ?? (typeof node.number === 'number' ? node.number : null);
195
+ continue;
196
+ }
197
+ const refs = isPlainObject(node.refs) ? node.refs : {};
198
+ const refsPageInfo = isPlainObject(refs.pageInfo) ? refs.pageInfo : {};
199
+ snapshot.issues.push({
200
+ number: node.number ?? null,
201
+ title: node.title ?? null,
202
+ url: node.url ?? null,
203
+ author: extractLogin(node.author),
204
+ created_at: node.createdAt ?? null,
205
+ labels: extractNodes(node.labels).map((lbl) => lbl.name ?? null),
206
+ assignees: extractNodes(node.assignees).map((user) => extractLogin(user)),
207
+ prs: extractPrs(refs),
208
+ events: extractEvents(node.recent),
209
+ incomplete: refsPageInfo.hasNextPage === true,
210
+ });
211
+ }
212
+ }
213
+ return snapshot;
214
+ }
215
+ export function issueCommands(plan, repo) {
216
+ const commands = [];
217
+ const actions = Array.isArray(plan.actions) ? plan.actions : [];
218
+ for (const entry of actions) {
219
+ if (!isPlainObject(entry))
220
+ continue;
221
+ const issueNum = entry.issue;
222
+ const base = `repos/${repo}/issues/${issueNum}`;
223
+ const steps = Array.isArray(entry.steps) ? entry.steps : [];
224
+ for (const step of steps) {
225
+ if (!isPlainObject(step))
226
+ continue;
227
+ const action = step.action;
228
+ let argv;
229
+ if (action === 'comment') {
230
+ argv = ['api', '-X', 'POST', `${base}/comments`, '-f', `body=${String(step.body)}`];
231
+ }
232
+ else if (action === 'close') {
233
+ argv = ['api', '-X', 'PATCH', base, '-f', 'state=closed', '-f', `state_reason=${String(step.state_reason)}`];
234
+ }
235
+ else if (action === 'add-label') {
236
+ argv = ['api', '-X', 'POST', `${base}/labels`, '-f', `labels[]=${String(step.label)}`];
237
+ }
238
+ else if (action === 'remove-label') {
239
+ argv = ['api', '-X', 'DELETE', `${base}/labels/${percentEncodeAll(String(step.label))}`];
240
+ }
241
+ else {
242
+ throw new SweepGithubUnusableError(`Unknown plan step: ${String(action)}`);
243
+ }
244
+ commands.push([issueNum, argv]);
245
+ }
246
+ }
247
+ return commands;
248
+ }
249
+ export function reportCommand(plan, repo) {
250
+ const body = `body=${String(plan.report_markdown)}`;
251
+ if (typeof plan.report_issue === 'number' && Number.isInteger(plan.report_issue)) {
252
+ return ['api', '-X', 'PATCH', `repos/${repo}/issues/${plan.report_issue}`, '-f', body];
253
+ }
254
+ return ['api', '-X', 'POST', `repos/${repo}/issues`, '-f', `title=${String(plan.report_title)}`, '-f', body];
255
+ }
256
+ function runGh(argv) {
257
+ const cmd = parseCommandOverride('SWEEP_GH', 'gh');
258
+ try {
259
+ const res = runCommand([...cmd, ...argv]);
260
+ return { code: res.code, stdout: res.stdout, stderr: res.stderr.slice(0, 500) };
261
+ }
262
+ catch (error) {
263
+ const msg = error instanceof Error ? error.message : String(error);
264
+ throw new SweepGithubUnusableError(`gh CLI is not available: ${msg}`);
265
+ }
266
+ }
267
+ export function sweepFetch(repo, outPath, sweeperLogin) {
268
+ const slashIdx = repo.indexOf('/');
269
+ const owner = repo.slice(0, slashIdx);
270
+ const name = repo.slice(slashIdx + 1);
271
+ const pages = [];
272
+ let cursor = null;
273
+ let finished = false;
274
+ for (let i = 0; i < MAX_PAGES; i++) {
275
+ const argv = ['api', 'graphql', '-f', `query=${QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`];
276
+ if (cursor)
277
+ argv.push('-f', `cursor=${cursor}`);
278
+ const res = runGh(argv);
279
+ if (res.code !== 0) {
280
+ throw new SweepGithubUnusableError(`GraphQL query failed: ${res.stderr}`);
281
+ }
282
+ let page;
283
+ try {
284
+ page = JSON.parse(res.stdout);
285
+ }
286
+ catch {
287
+ throw new SweepGithubUnusableError('GraphQL response is not JSON.');
288
+ }
289
+ if (!isPlainObject(page)) {
290
+ throw new SweepGithubUnusableError('GraphQL response is not JSON.');
291
+ }
292
+ pages.push(page);
293
+ const data = isPlainObject(page.data) ? page.data : {};
294
+ const repoObj = isPlainObject(data.repository) ? data.repository : {};
295
+ const issuesObj = isPlainObject(repoObj.issues) ? repoObj.issues : {};
296
+ const info = isPlainObject(issuesObj.pageInfo) ? issuesObj.pageInfo : {};
297
+ if (!info.hasNextPage) {
298
+ finished = true;
299
+ break;
300
+ }
301
+ cursor = typeof info.endCursor === 'string' ? info.endCursor : null;
302
+ }
303
+ if (!finished) {
304
+ throw new SweepGithubUnusableError(`More than ${MAX_PAGES * PAGE_SIZE} open issues; raise MAX_PAGES deliberately.`);
305
+ }
306
+ const fetchedAt = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
307
+ const snapshot = toSnapshot(pages, fetchedAt, sweeperLogin);
308
+ writeFileSync(outPath, JSON.stringify(snapshot, null, 2), 'utf8');
309
+ return {
310
+ snapshot: outPath,
311
+ issues: snapshot.issues.length,
312
+ pages: pages.length,
313
+ report_issue: snapshot.report_issue,
314
+ };
315
+ }
316
+ function loadPlan(path, repo) {
317
+ let raw;
318
+ try {
319
+ raw = JSON.parse(readFileSync(path, 'utf8'));
320
+ }
321
+ catch {
322
+ throw new SweepGithubUnusableError('Plan cannot be read as JSON.');
323
+ }
324
+ if (!isPlainObject(raw) || raw.verdict !== 'ok') {
325
+ throw new SweepGithubUnusableError('Plan verdict is not ok; nothing is written.');
326
+ }
327
+ if (fold(raw.repo) !== fold(repo)) {
328
+ throw new SweepGithubUnusableError(`Plan is for ${String(raw.repo)}, not ${repo}.`);
329
+ }
330
+ if (!Array.isArray(raw.actions) || typeof raw.report_markdown !== 'string') {
331
+ throw new SweepGithubUnusableError('Plan needs actions and report_markdown.');
332
+ }
333
+ return raw;
334
+ }
335
+ function selectPlan(plan, only) {
336
+ if (only === null)
337
+ return plan;
338
+ const actions = plan.actions;
339
+ const planned = new Set(actions.map((entry) => entry.issue));
340
+ const unknown = [...only].filter((n) => !planned.has(n)).sort((a, b) => a - b);
341
+ if (unknown.length > 0) {
342
+ throw new SweepGithubUnusableError(`--only lists issues the plan does not act on: ${unknown.join(', ')}`);
343
+ }
344
+ return {
345
+ ...plan,
346
+ actions: actions.filter((entry) => only.has(entry.issue)),
347
+ };
348
+ }
349
+ export function sweepApply(repo, planPath, dryRun, only = null) {
350
+ const plan = selectPlan(loadPlan(planPath, repo), only);
351
+ const commands = issueCommands(plan, repo);
352
+ commands.push(['report', reportCommand(plan, repo)]);
353
+ if (dryRun) {
354
+ return [
355
+ {
356
+ dry_run: true,
357
+ writes: commands.map(([issue, argv]) => ({ issue, argv })),
358
+ },
359
+ 0,
360
+ ];
361
+ }
362
+ const applied = [];
363
+ const errors = [];
364
+ const failed = new Set();
365
+ for (const [issue, argv] of commands) {
366
+ if (failed.has(issue)) {
367
+ errors.push({ issue, argv: argv.slice(0, 4), error: 'skipped after an earlier failure' });
368
+ continue;
369
+ }
370
+ const res = runGh(argv);
371
+ if (res.code === 0) {
372
+ applied.push({ issue, argv: argv.slice(0, 4) });
373
+ }
374
+ else {
375
+ failed.add(issue);
376
+ errors.push({ issue, argv: argv.slice(0, 4), error: res.stderr });
377
+ }
378
+ }
379
+ return [{ dry_run: false, applied, errors }, errors.length > 0 ? 1 : 0];
380
+ }
381
+ export function parseOnly(value) {
382
+ const numbers = value
383
+ .split(',')
384
+ .map((item) => item.trim().replace(/^#+/, ''))
385
+ .filter((item) => item.length > 0);
386
+ if (numbers.length === 0 || !numbers.every((item) => /^\d+$/.test(item))) {
387
+ throw new SweepGithubUnusableError('--only must be issue numbers separated by commas, e.g. 12,15.');
388
+ }
389
+ return new Set(numbers.map((item) => Number.parseInt(item, 10)));
390
+ }
391
+ function parseArgs(argv) {
392
+ if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h' || argv.includes('--help')) {
393
+ return null;
394
+ }
395
+ const command = argv[0];
396
+ if (command !== 'fetch' && command !== 'apply') {
397
+ throw new SweepGithubUnusableError(`Unknown command: ${command}`);
398
+ }
399
+ const tail = argv.slice(1);
400
+ const dryRun = tail.includes('--dry-run');
401
+ const rest = tail.filter((item) => item !== '--dry-run');
402
+ const required = command === 'fetch' ? ['--repo', '--out'] : ['--repo', '--plan'];
403
+ const allowed = new Set([...required, command === 'fetch' ? '--sweeper-login' : '--only']);
404
+ const values = { 'sweeper-login': DEFAULT_SWEEPER };
405
+ for (let idx = 0; idx < rest.length; idx += 2) {
406
+ const flag = rest[idx];
407
+ const value = rest[idx + 1];
408
+ if (!allowed.has(flag) || value === undefined) {
409
+ throw new SweepGithubUnusableError(`Unknown or incomplete argument: ${flag}`);
410
+ }
411
+ values[flag.slice(2)] = value;
412
+ }
413
+ for (const key of required) {
414
+ if (!(key.slice(2) in values)) {
415
+ throw new SweepGithubUnusableError(`Missing ${key}.`);
416
+ }
417
+ }
418
+ const repoVal = values.repo ?? '';
419
+ if (!REPO_RE.test(repoVal)) {
420
+ throw new SweepGithubUnusableError('--repo must be owner/name.');
421
+ }
422
+ const only = values.only !== undefined ? parseOnly(values.only) : null;
423
+ return {
424
+ command,
425
+ repo: repoVal,
426
+ out: values.out,
427
+ plan: values.plan,
428
+ sweeperLogin: values['sweeper-login'] ?? DEFAULT_SWEEPER,
429
+ dryRun,
430
+ only,
431
+ };
432
+ }
433
+ export function sweepGithub(argv) {
434
+ try {
435
+ const args = parseArgs(argv);
436
+ if (args === null) {
437
+ process.stdout.write(`${HELP}\n`);
438
+ return 0;
439
+ }
440
+ const [result, code] = args.command === 'fetch'
441
+ ? [sweepFetch(args.repo, args.out, args.sweeperLogin), 0]
442
+ : sweepApply(args.repo, args.plan, args.dryRun, args.only);
443
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
444
+ return code;
445
+ }
446
+ catch (error) {
447
+ if (error instanceof SweepGithubUnusableError) {
448
+ process.stdout.write(`${JSON.stringify({ verdict: 'unusable', reason: error.message })}\n`);
449
+ return 2;
450
+ }
451
+ throw error;
452
+ }
453
+ }
@@ -0,0 +1,56 @@
1
+ export declare const sweepIssuesUsage = "bbc sweep-issues --snapshot <file> --sweeper-login <login> [--config <file>] [--now <ISO-8601>]";
2
+ export declare class SweepUnusableError extends Error {
3
+ }
4
+ export interface SweepConfig {
5
+ readonly language: string;
6
+ readonly max_writes_per_run: number;
7
+ readonly needs_info_days: number;
8
+ readonly claim_stale_days: number;
9
+ readonly inactive_days: number;
10
+ readonly sweeper_login: string;
11
+ readonly labels: {
12
+ readonly stale: string;
13
+ readonly needs_info: string;
14
+ readonly close_review: string;
15
+ readonly claim: string;
16
+ };
17
+ readonly exempt_labels: readonly string[];
18
+ readonly exempt_priorities: readonly string[];
19
+ readonly report_title: string;
20
+ }
21
+ export interface SweepStep {
22
+ readonly action: string;
23
+ readonly label?: string;
24
+ readonly marker?: string;
25
+ readonly body?: string;
26
+ readonly state_reason?: string;
27
+ }
28
+ export interface SweepPlanEntry {
29
+ readonly issue: number;
30
+ readonly rule: string;
31
+ readonly url: string | null;
32
+ readonly steps: readonly SweepStep[];
33
+ }
34
+ export interface SweepPlan {
35
+ readonly verdict: 'ok';
36
+ readonly repo: string;
37
+ readonly run_by: string;
38
+ readonly generated_at: string;
39
+ readonly report_issue: number | null;
40
+ readonly report_title: string;
41
+ readonly actions: readonly SweepPlanEntry[];
42
+ readonly deferred: readonly {
43
+ readonly issue: number;
44
+ readonly rule: string;
45
+ readonly url: string | null;
46
+ }[];
47
+ readonly report_only: readonly SweepPlanEntry[];
48
+ readonly gaps: readonly Record<string, unknown>[];
49
+ readonly metrics: Record<string, number>;
50
+ readonly report_markdown: string;
51
+ }
52
+ export declare function loadSweepConfig(path: string | undefined, sweeperLogin: string): SweepConfig;
53
+ export declare function loadSnapshot(path: string): Record<string, unknown>;
54
+ export declare function renderSweepReport(plan: Omit<SweepPlan, 'report_markdown'>, language: string): string;
55
+ export declare function evaluateSweepPlan(snapshot: Record<string, unknown>, config: SweepConfig, nowMs: number): SweepPlan;
56
+ export declare function sweepIssues(argv: readonly string[]): number;