@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,111 @@
1
+ /**
2
+ * LAYER: Interface
3
+ * Contains: extract-diff-scope command.
4
+ * Rules: Emit the legacy YAML sections and exit statuses byte for byte.
5
+ * BigO: O(n^2) score:1
6
+ * keywords: [DiffScopeCommand, GateSections]
7
+ * GOAL: List the changed code lines the quality gates must inspect.
8
+ */
9
+ import { awkQuote, changedFiles, countLines, diffArgs, gates, hasHeadCommit, trackedRecords, untrackedFiles, untrackedLineCount, untrackedRecords, yamlEscape, } from "./diff-scope/git-diff.js";
10
+ import { EOL } from 'node:os';
11
+ export const extractDiffScopeUsage = 'bbc extract-diff-scope [--working|--staged|--range A..B|--head N]';
12
+ const usageText = `extract-diff-scope.py: extract added/modified TypeScript/JavaScript lines as
13
+ structured YAML for code-quality-gate (TypeSafe, EarlyReturn, BigO).
14
+
15
+ Usage:
16
+ python3 -I -B scripts/extract-diff-scope.py # working tree vs HEAD + untracked (default)
17
+ python3 -I -B scripts/extract-diff-scope.py --working # working tree vs HEAD + untracked
18
+ python3 -I -B scripts/extract-diff-scope.py --staged # staged diff only
19
+ python3 -I -B scripts/extract-diff-scope.py --range A..B # commit range
20
+ python3 -I -B scripts/extract-diff-scope.py --head N # last N commits (HEAD~N..HEAD)
21
+ python3 -I -B scripts/extract-diff-scope.py --help
22
+ `;
23
+ const native = (text) => Buffer.from(text.replaceAll('\n', EOL), 'latin1');
24
+ function parseArgs(args) {
25
+ let mode = 'working';
26
+ let value = '';
27
+ for (let index = 0; index < args.length; index += 1) {
28
+ const argument = args[index];
29
+ if (argument === '--working' || argument === '--staged') {
30
+ mode = argument.slice(2);
31
+ continue;
32
+ }
33
+ if (argument === '--range' || argument === '--head') {
34
+ const next = args[index + 1];
35
+ if (next === undefined || next === '') {
36
+ process.stderr.write(native(`error: ${argument} requires ${argument === '--range' ? 'A..B' : 'N'}\n`));
37
+ return undefined;
38
+ }
39
+ mode = argument.slice(2);
40
+ value = next;
41
+ index += 1;
42
+ continue;
43
+ }
44
+ if (argument === '--help' || argument === '-h') {
45
+ process.stdout.write(native(usageText));
46
+ return 'help';
47
+ }
48
+ process.stderr.write(native(`error: unknown option: ${argument}\n${usageText}`));
49
+ return undefined;
50
+ }
51
+ if (mode === 'head' && !/^[1-9][0-9]*$/.test(value)) {
52
+ process.stderr.write(native(`error: --head requires a positive integer: ${value}\n`));
53
+ return undefined;
54
+ }
55
+ return { mode, value };
56
+ }
57
+ function emit(lines) {
58
+ process.stdout.write(Buffer.from(`${lines.join('\n')}\n`, 'latin1'));
59
+ return 0;
60
+ }
61
+ function emptyScope(mode, value, files) {
62
+ const out = ['scope:', ` mode: "${mode}"`];
63
+ if (mode === 'range')
64
+ out.push(` range: "${yamlEscape(value)}"`);
65
+ out.push(` files_changed: ${files.length}`);
66
+ return [
67
+ ...out,
68
+ ' lines_added: 0',
69
+ ' lines_removed: 0',
70
+ ' files: []',
71
+ ' records: []',
72
+ ' typesafe_candidates: []',
73
+ ' earlyreturn_candidates: []',
74
+ ' bigo_candidates: []',
75
+ ];
76
+ }
77
+ export function extractDiffScope(args) {
78
+ const parsed = parseArgs(args);
79
+ if (parsed === undefined)
80
+ return 1;
81
+ if (parsed === 'help')
82
+ return 0;
83
+ const diff = diffArgs(parsed, hasHeadCommit());
84
+ const tracked = changedFiles(diff);
85
+ const untracked = parsed.mode === 'working' ? untrackedFiles() : [];
86
+ const files = [...tracked, ...untracked];
87
+ if (files.length === 0)
88
+ return emit(emptyScope(parsed.mode, parsed.value, files));
89
+ const counted = tracked.length > 0 ? countLines(diff, tracked) : { added: 0, removed: 0 };
90
+ const added = counted.added + untracked.reduce((total, path) => total + untrackedLineCount(path), 0);
91
+ const header = ['scope:', ` mode: "${parsed.mode}"`];
92
+ if (parsed.mode === 'range')
93
+ header.push(` range: "${yamlEscape(parsed.value)}"`);
94
+ header.push(` files_changed: ${files.length}`, ` lines_added: ${added}`, ` lines_removed: ${counted.removed}`, ' files:');
95
+ const out = [...header, ...files.map((path) => ` - "${yamlEscape(path)}"`)];
96
+ const records = tracked.length > 0 ? trackedRecords(diff, tracked) : [];
97
+ for (const path of untracked)
98
+ records.push(...untrackedRecords(path));
99
+ for (const [key, pattern] of gates) {
100
+ const rows = records.filter((row) => pattern === null || pattern.test(row.content));
101
+ if (rows.length === 0) {
102
+ out.push(` ${key}: []`);
103
+ continue;
104
+ }
105
+ out.push(` ${key}:`);
106
+ for (const row of rows) {
107
+ out.push(` - file: "${row.path}"`, ` line: ${row.line}`, ' added: true', ` content: "${awkQuote(row.content)}"`);
108
+ }
109
+ }
110
+ return emit(out);
111
+ }
@@ -0,0 +1,22 @@
1
+ export declare const fetchIssueAttachmentsUsage = "bbc fetch-issue-attachments [--repo <owner/repo> --issue <n> | --stdin] [--out <dir>]";
2
+ export interface ExtractedUrl {
3
+ readonly kind: 'image' | 'attachment';
4
+ readonly url: string;
5
+ }
6
+ export interface AttachmentEntry {
7
+ readonly url: string;
8
+ readonly local_path: string | null;
9
+ readonly content_type: string | null;
10
+ readonly bytes: number;
11
+ readonly status: 'downloaded' | 'downloaded_non_image' | 'error';
12
+ readonly error?: string;
13
+ source?: string;
14
+ kind?: 'image' | 'attachment';
15
+ }
16
+ export type AttachmentDownloader = (url: string, destDir: string, index: number) => Promise<AttachmentEntry>;
17
+ export declare function isAllowedAttachmentUrl(rawUrl: string): boolean;
18
+ export declare function extractUrlsFromHtml(bodyHtml: string, bodyMd?: string): ExtractedUrl[];
19
+ export declare function extensionForContentType(contentType: string, rawUrl: string): string;
20
+ export declare function downloadAttachment(url: string, destDir: string, index: number): Promise<AttachmentEntry>;
21
+ export declare function processIssuePayload(issueData: Record<string, unknown>, commentsData: readonly Record<string, unknown>[], outDir: string, downloader?: AttachmentDownloader): Promise<Record<string, unknown>>;
22
+ export declare function fetchIssueAttachments(argv: readonly string[]): Promise<number>;
@@ -0,0 +1,325 @@
1
+ /**
2
+ * LAYER: Application
3
+ * Contains: Issue attachment extractor and allowlisted HTTPS downloader.
4
+ * Rules: Refuse non-HTTPS and untrusted hosts on both initial URLs and redirects; enforce 20 MiB cap.
5
+ * BigO: O(n) score:4
6
+ * keywords: [FetchAttachments, SafeRedirect, UrlExtractor, IssuePayload]
7
+ * GOAL: Resolve and download visual attachments from a GitHub issue and its comments safely.
8
+ */
9
+ import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
10
+ import { tmpdir } from 'node:os';
11
+ import { extname, join } from 'node:path';
12
+ import { parseCommandOverride, runCommand } from "./wave3/process.js";
13
+ export const fetchIssueAttachmentsUsage = 'bbc fetch-issue-attachments [--repo <owner/repo> --issue <n> | --stdin] [--out <dir>]';
14
+ const IMG_SRC_RE = /<img\b[^>]*\bsrc=["']([^"']+)["']/gi;
15
+ const LINK_HREF_RE = /<a\b[^>]*\bhref=["']([^"']+)["']/gi;
16
+ const MD_IMAGE_RE = /!\[[^\]]*\]\((https?:\/\/[^)\s]+)\)/g;
17
+ const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg']);
18
+ const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
19
+ const ALLOWED_HOSTS = new Set([
20
+ 'github.com',
21
+ 'raw.githubusercontent.com',
22
+ 'user-images.githubusercontent.com',
23
+ 'private-user-images.githubusercontent.com',
24
+ 'objects.githubusercontent.com',
25
+ 'avatars.githubusercontent.com',
26
+ ]);
27
+ const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
28
+ const MIME_TO_EXT = new Map([
29
+ ['image/png', '.png'],
30
+ ['image/jpeg', '.jpg'],
31
+ ['image/gif', '.gif'],
32
+ ['image/webp', '.webp'],
33
+ ['image/svg+xml', '.svg'],
34
+ ['text/plain', '.txt'],
35
+ ['text/html', '.html'],
36
+ ['application/json', '.json'],
37
+ ['application/pdf', '.pdf'],
38
+ ['application/octet-stream', '.bin'],
39
+ ]);
40
+ const HELP = 'Usage: bbc fetch-issue-attachments [--repo <owner/repo> --issue <n> | --stdin] [--out <dir>]\n' +
41
+ 'Resolve and download attachments from a GitHub issue via gh api body_html.\n' +
42
+ ' --repo <owner/repo> GitHub repository in owner/repo format.\n' +
43
+ ' --issue <n> Issue number.\n' +
44
+ ' --out <dir> Output directory for downloaded attachments.\n' +
45
+ ' --stdin Read {"issue": ..., "comments": ...} JSON from stdin.';
46
+ function unescapeHtml(raw) {
47
+ return raw
48
+ .replace(/&amp;/gi, '&')
49
+ .replace(/&lt;/gi, '<')
50
+ .replace(/&gt;/gi, '>')
51
+ .replace(/&quot;/gi, '"')
52
+ .replace(/&#39;|&apos;/gi, "'")
53
+ .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number.parseInt(dec, 10)))
54
+ .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16)));
55
+ }
56
+ export function isAllowedAttachmentUrl(rawUrl) {
57
+ let parsed;
58
+ try {
59
+ parsed = new URL(rawUrl);
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ if (parsed.protocol.toLowerCase() !== 'https:')
65
+ return false;
66
+ const host = parsed.hostname.toLowerCase();
67
+ if (!host)
68
+ return false;
69
+ return ALLOWED_HOSTS.has(host) || host.endsWith('.githubusercontent.com');
70
+ }
71
+ export function extractUrlsFromHtml(bodyHtml, bodyMd = '') {
72
+ const urls = [];
73
+ const seen = new Set();
74
+ for (const match of (bodyHtml || '').matchAll(IMG_SRC_RE)) {
75
+ const clean = unescapeHtml(match[1] ?? '').trim();
76
+ if (clean && !seen.has(clean)) {
77
+ seen.add(clean);
78
+ urls.push({ kind: 'image', url: clean });
79
+ }
80
+ }
81
+ for (const match of (bodyHtml || '').matchAll(LINK_HREF_RE)) {
82
+ const clean = unescapeHtml(match[1] ?? '').trim();
83
+ if (!clean || seen.has(clean))
84
+ continue;
85
+ let parsed;
86
+ try {
87
+ parsed = new URL(clean);
88
+ }
89
+ catch {
90
+ continue;
91
+ }
92
+ const pathLower = parsed.pathname.toLowerCase();
93
+ const isAttachment = parsed.pathname.includes('user-attachments') ||
94
+ parsed.host.includes('private-user-images.githubusercontent.com') ||
95
+ parsed.host.includes('objects.githubusercontent.com') ||
96
+ [...IMAGE_EXTENSIONS].some((ext) => pathLower.endsWith(ext));
97
+ if (isAttachment) {
98
+ seen.add(clean);
99
+ urls.push({ kind: 'attachment', url: clean });
100
+ }
101
+ }
102
+ for (const match of (bodyMd || '').matchAll(MD_IMAGE_RE)) {
103
+ const clean = unescapeHtml(match[1] ?? '').trim();
104
+ if (clean && !seen.has(clean) && !clean.includes('github.com/user-attachments/')) {
105
+ seen.add(clean);
106
+ urls.push({ kind: 'image', url: clean });
107
+ }
108
+ }
109
+ return urls;
110
+ }
111
+ export function extensionForContentType(contentType, rawUrl) {
112
+ const ct = ((contentType || '').split(';')[0] ?? '').trim().toLowerCase();
113
+ if (ct) {
114
+ const mapped = MIME_TO_EXT.get(ct);
115
+ if (mapped)
116
+ return mapped;
117
+ }
118
+ try {
119
+ const pathExt = extname(new URL(rawUrl).pathname).toLowerCase();
120
+ if (IMAGE_EXTENSIONS.has(pathExt))
121
+ return pathExt;
122
+ }
123
+ catch {
124
+ // Ignore malformed URLs and fall back to .bin
125
+ }
126
+ return '.bin';
127
+ }
128
+ async function readBoundedResponse(response) {
129
+ if (!response.body) {
130
+ return Buffer.alloc(0);
131
+ }
132
+ const reader = response.body.getReader();
133
+ const chunks = [];
134
+ let total = 0;
135
+ while (true) {
136
+ const { done, value } = await reader.read();
137
+ if (done)
138
+ break;
139
+ total += value.byteLength;
140
+ if (total > MAX_ATTACHMENT_BYTES) {
141
+ await reader.cancel();
142
+ throw new Error(`Attachment exceeds ${MAX_ATTACHMENT_BYTES} byte limit`);
143
+ }
144
+ chunks.push(value);
145
+ }
146
+ return Buffer.concat(chunks);
147
+ }
148
+ export async function downloadAttachment(url, destDir, index) {
149
+ if (!isAllowedAttachmentUrl(url)) {
150
+ return {
151
+ url,
152
+ local_path: null,
153
+ content_type: null,
154
+ bytes: 0,
155
+ status: 'error',
156
+ error: 'Untrusted attachment URL scheme or host',
157
+ };
158
+ }
159
+ let currentUrl = url;
160
+ let response;
161
+ try {
162
+ let redirects = 0;
163
+ while (true) {
164
+ response = await fetch(currentUrl, {
165
+ headers: { 'User-Agent': 'bbc-issue-reviewer/1.0' },
166
+ redirect: 'manual',
167
+ signal: AbortSignal.timeout(20_000),
168
+ });
169
+ const isRedirect = response.status >= 300 && response.status < 400;
170
+ const location = response.headers.get('location');
171
+ if (!isRedirect || !location)
172
+ break;
173
+ redirects += 1;
174
+ if (redirects > 5)
175
+ throw new Error('Too many redirects');
176
+ const nextUrl = new URL(location, currentUrl).toString();
177
+ if (!isAllowedAttachmentUrl(nextUrl)) {
178
+ throw new Error(`Refusing untrusted redirect host: ${nextUrl}`);
179
+ }
180
+ currentUrl = nextUrl;
181
+ }
182
+ if (!response.ok) {
183
+ throw new Error(`HTTP Error ${response.status}: ${response.statusText}`);
184
+ }
185
+ const contentType = response.headers.get('content-type') ?? '';
186
+ const payload = await readBoundedResponse(response);
187
+ const ext = extensionForContentType(contentType, currentUrl);
188
+ const isImage = contentType.toLowerCase().startsWith('image/') || IMAGE_EXTENSIONS.has(ext);
189
+ const outPath = join(destDir, `attachment-${index}${ext}`);
190
+ writeFileSync(outPath, payload);
191
+ return {
192
+ url,
193
+ local_path: outPath,
194
+ content_type: contentType || null,
195
+ bytes: payload.byteLength,
196
+ status: isImage ? 'downloaded' : 'downloaded_non_image',
197
+ };
198
+ }
199
+ catch (error) {
200
+ return {
201
+ url,
202
+ local_path: null,
203
+ content_type: null,
204
+ bytes: 0,
205
+ status: 'error',
206
+ error: error instanceof Error ? error.message : String(error),
207
+ };
208
+ }
209
+ }
210
+ function fetchGithubJson(endpoint) {
211
+ const ghCmd = parseCommandOverride('FETCH_ATTACHMENTS_GH', 'gh');
212
+ const result = runCommand([...ghCmd, 'api', '-H', 'Accept: application/vnd.github.full+json', endpoint], { timeoutMs: 20_000 });
213
+ if (result.code !== 0) {
214
+ throw new Error(result.stderr || `gh api failed for ${endpoint}`);
215
+ }
216
+ return JSON.parse(result.stdout);
217
+ }
218
+ export async function processIssuePayload(issueData, commentsData, outDir, downloader = downloadAttachment) {
219
+ const entries = [];
220
+ const seenUrls = new Set();
221
+ const sources = [
222
+ ['body', issueData],
223
+ ...(commentsData || []).map((comment, idx) => [
224
+ `comment:${String(comment.id ?? idx + 1)}`,
225
+ comment,
226
+ ]),
227
+ ];
228
+ let counter = 0;
229
+ for (const [sourceName, item] of sources) {
230
+ if (!item || typeof item !== 'object')
231
+ continue;
232
+ const bodyHtml = typeof item.body_html === 'string' ? item.body_html : '';
233
+ const bodyMd = typeof item.body === 'string' ? item.body : '';
234
+ const found = extractUrlsFromHtml(bodyHtml, bodyMd);
235
+ for (const entry of found) {
236
+ if (seenUrls.has(entry.url))
237
+ continue;
238
+ seenUrls.add(entry.url);
239
+ counter += 1;
240
+ const dl = await downloader(entry.url, outDir, counter);
241
+ entries.push({ ...dl, source: sourceName, kind: entry.kind });
242
+ }
243
+ }
244
+ return {
245
+ issue: issueData.number ?? null,
246
+ title: issueData.title ?? null,
247
+ url: issueData.html_url ?? null,
248
+ out_dir: outDir,
249
+ attachments: entries,
250
+ };
251
+ }
252
+ function parseArgs(argv) {
253
+ let repo;
254
+ let issueRaw;
255
+ let out;
256
+ let stdin = false;
257
+ const queue = [...argv];
258
+ while (queue.length > 0) {
259
+ const arg = queue.shift();
260
+ if (arg === '-h' || arg === '--help')
261
+ return { help: true, stdin: false };
262
+ if (arg === '--stdin') {
263
+ stdin = true;
264
+ continue;
265
+ }
266
+ if ((arg === '--repo' || arg === '--issue' || arg === '--out') && queue.length > 0) {
267
+ const value = queue.shift();
268
+ if (arg === '--repo')
269
+ repo = value;
270
+ else if (arg === '--issue')
271
+ issueRaw = value;
272
+ else
273
+ out = value;
274
+ continue;
275
+ }
276
+ return { error: `Unknown or incomplete argument: ${arg}` };
277
+ }
278
+ let issue;
279
+ if (issueRaw !== undefined) {
280
+ if (!/^-?\d+$/.test(issueRaw)) {
281
+ return { error: `Invalid --issue value: ${issueRaw}` };
282
+ }
283
+ issue = Number.parseInt(issueRaw, 10);
284
+ }
285
+ return { repo, issue, out, stdin };
286
+ }
287
+ export async function fetchIssueAttachments(argv) {
288
+ const parsed = parseArgs(argv);
289
+ if ('error' in parsed) {
290
+ process.stdout.write(`${JSON.stringify({ error: parsed.error })}\n`);
291
+ return 2;
292
+ }
293
+ if (parsed.help) {
294
+ process.stdout.write(`${HELP}\n`);
295
+ return 0;
296
+ }
297
+ const outDir = parsed.out
298
+ ? parsed.out
299
+ : mkdtempSync(join(tmpdir(), `bbc-issue-${parsed.issue ?? 'stdin'}-`));
300
+ mkdirSync(outDir, { recursive: true });
301
+ let report;
302
+ if (parsed.stdin) {
303
+ const raw = readFileSync(0, 'utf8');
304
+ const payload = JSON.parse(raw);
305
+ report = await processIssuePayload(payload.issue ?? {}, payload.comments ?? [], outDir);
306
+ }
307
+ else {
308
+ if (!parsed.repo || !parsed.issue || !REPO_RE.test(parsed.repo) || parsed.issue <= 0) {
309
+ process.stdout.write(`${JSON.stringify({ error: 'Pass --repo owner/repo and positive --issue N (or --stdin).' })}\n`);
310
+ return 2;
311
+ }
312
+ try {
313
+ const issueData = fetchGithubJson(`repos/${parsed.repo}/issues/${parsed.issue}`);
314
+ const commentsData = fetchGithubJson(`repos/${parsed.repo}/issues/${parsed.issue}/comments`);
315
+ report = await processIssuePayload(issueData, commentsData, outDir);
316
+ }
317
+ catch (error) {
318
+ const msg = error instanceof Error ? error.message : String(error);
319
+ process.stdout.write(`${JSON.stringify({ error: msg })}\n`);
320
+ return 1;
321
+ }
322
+ }
323
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
324
+ return 0;
325
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * LAYER: Domain
3
+ * Contains: Issue claim rules CL1-CL12, assignment/label ordering, and verdict evaluation.
4
+ * Rules: Pure offline domain logic; never read files or call GitHub.
5
+ * BigO: O(n log n) score:2
6
+ * keywords: [IssueClaimPolicy, ClaimContention]
7
+ * GOAL: Decide whether one person may claim or release a canonical GitHub issue.
8
+ */
9
+ export type ClaimPhase = 'check' | 'verify' | 'release' | 'status';
10
+ export interface IssueRecord {
11
+ number: number;
12
+ author: string | null;
13
+ open: boolean;
14
+ assignees: string[];
15
+ labels: string[];
16
+ updated: number | null;
17
+ }
18
+ export interface PullRecord {
19
+ number: unknown;
20
+ author: string | null;
21
+ head: string;
22
+ text: string;
23
+ }
24
+ export interface EventRecord {
25
+ event?: unknown;
26
+ assignee?: unknown;
27
+ actor?: unknown;
28
+ label?: unknown;
29
+ created_at?: unknown;
30
+ createdAt?: unknown;
31
+ }
32
+ export interface ClaimFinding {
33
+ rule: string;
34
+ verdict: string;
35
+ detail: string;
36
+ who?: string[];
37
+ }
38
+ export interface ClaimOptions {
39
+ phase: ClaimPhase;
40
+ claimant: string | null;
41
+ branch: string | null;
42
+ repo: string | null;
43
+ label: string;
44
+ stale_days: number;
45
+ now: number;
46
+ }
47
+ export declare class UnusableClaimError extends Error {
48
+ }
49
+ export declare const STOP_VERDICTS: Set<string>;
50
+ export declare function fold(value: unknown): string;
51
+ export declare function extractLogin(value: unknown): string | null;
52
+ export declare function parseIsoTime(value: unknown): number | null;
53
+ export declare function evaluateClaim(issue: IssueRecord, pulls: readonly PullRecord[], branches: readonly string[], events: readonly EventRecord[] | null, options: ClaimOptions): {
54
+ verdict: string;
55
+ findings: ClaimFinding[];
56
+ holders: {
57
+ assignees: string[];
58
+ reporter: string | null;
59
+ label: boolean;
60
+ pulls: {
61
+ number: unknown;
62
+ author: string | null;
63
+ }[];
64
+ branches: string[];
65
+ };
66
+ };