@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.
- package/dist/audit-ledger.d.ts +2 -0
- package/dist/audit-ledger.js +71 -0
- package/dist/bbc-install.d.ts +2 -0
- package/dist/bbc-install.js +1250 -0
- package/dist/bbc.js +87 -3
- package/dist/change-lane/classification.js +3 -1
- package/dist/check-issue-claim.d.ts +2 -0
- package/dist/check-issue-claim.js +146 -0
- package/dist/check-worktree-guard.d.ts +2 -0
- package/dist/check-worktree-guard.js +114 -0
- package/dist/error-scan.d.ts +3 -0
- package/dist/error-scan.js +216 -0
- package/dist/export-public.d.ts +9 -0
- package/dist/export-public.js +274 -0
- package/dist/fetch-issue-attachments.d.ts +22 -0
- package/dist/fetch-issue-attachments.js +325 -0
- package/dist/issue-claim/evaluation.d.ts +66 -0
- package/dist/issue-claim/evaluation.js +259 -0
- package/dist/issue-claim/loaders.d.ts +5 -0
- package/dist/issue-claim/loaders.js +116 -0
- package/dist/list-zed-commands.d.ts +7 -0
- package/dist/list-zed-commands.js +288 -0
- package/dist/plan-issue-triage.d.ts +3 -0
- package/dist/plan-issue-triage.js +404 -0
- package/dist/question-gate/ledger.d.ts +5 -0
- package/dist/question-gate/ledger.js +115 -0
- package/dist/question-gate/rules.d.ts +40 -0
- package/dist/question-gate/rules.js +483 -0
- package/dist/recap/board.d.ts +5 -0
- package/dist/recap/board.js +384 -0
- package/dist/recap/git-and-github.d.ts +11 -0
- package/dist/recap/git-and-github.js +620 -0
- package/dist/recap/report-and-hud.d.ts +2 -0
- package/dist/recap/report-and-hud.js +294 -0
- package/dist/recap/time-and-refs.d.ts +27 -0
- package/dist/recap/time-and-refs.js +148 -0
- package/dist/recap.d.ts +2 -0
- package/dist/recap.js +217 -0
- package/dist/render-workflow.js +12 -14
- package/dist/resolve-containers.d.ts +2 -0
- package/dist/resolve-containers.js +96 -0
- package/dist/review-loop.d.ts +7 -0
- package/dist/review-loop.js +622 -0
- package/dist/save-counts.d.ts +2 -0
- package/dist/save-counts.js +191 -0
- package/dist/summarize-logs.d.ts +2 -0
- package/dist/summarize-logs.js +41 -0
- package/dist/sweep-github.d.ts +10 -0
- package/dist/sweep-github.js +453 -0
- package/dist/sweep-issues.d.ts +56 -0
- package/dist/sweep-issues.js +650 -0
- package/dist/sweep.d.ts +2 -0
- package/dist/sweep.js +301 -0
- package/dist/triage-question.d.ts +2 -0
- package/dist/triage-question.js +189 -0
- package/dist/validate-skills.d.ts +2 -0
- package/dist/validate-skills.js +48 -0
- package/dist/watch-live.d.ts +7 -0
- package/dist/watch-live.js +83 -0
- package/dist/watcher/config.d.ts +11 -0
- package/dist/watcher/config.js +265 -0
- package/dist/watcher/live-classifier.d.ts +52 -0
- package/dist/watcher/live-classifier.js +510 -0
- package/dist/watcher/safe-fs.d.ts +9 -0
- package/dist/watcher/safe-fs.js +159 -0
- package/dist/watcher/stream.d.ts +27 -0
- package/dist/watcher/stream.js +340 -0
- package/dist/watcher/summarizer.d.ts +19 -0
- package/dist/watcher/summarizer.js +121 -0
- package/dist/wave3/process.d.ts +14 -0
- package/dist/wave3/process.js +84 -0
- package/dist/wave4/process.d.ts +14 -0
- package/dist/wave4/process.js +128 -0
- package/dist/workflow/render.d.ts +1 -1
- package/dist/workflow/render.js +1 -1
- package/dist/workflow-auditor/audit.d.ts +27 -0
- package/dist/workflow-auditor/audit.js +583 -0
- package/dist/workflow-auditor/ledger-io.d.ts +5 -0
- package/dist/workflow-auditor/ledger-io.js +99 -0
- package/dist/workflow-auditor/skills-validator.d.ts +10 -0
- package/dist/workflow-auditor/skills-validator.js +533 -0
- package/dist/worktree-guard/evaluation.d.ts +19 -0
- package/dist/worktree-guard/evaluation.js +84 -0
- package/dist/worktree-guard/git.d.ts +3 -0
- package/dist/worktree-guard/git.js +61 -0
- package/package.json +32 -33
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LAYER: Application
|
|
3
|
+
* Contains: Public edition exporter stripping private profiles, release tooling, launch docs, and git history.
|
|
4
|
+
* Rules: Fail closed and remove output directory on any leak, marker error, or validation failure.
|
|
5
|
+
* BigO: O(n^2) score:1
|
|
6
|
+
* keywords: [ExportPublic, LeakScanner, ExportDrop, ProfileIsolation]
|
|
7
|
+
* GOAL: Build a leak-free public edition directory from git-tracked repository files.
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from 'node:fs';
|
|
10
|
+
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import { decodeUtf8Strict, runExecutable } from "./wave4/process.js";
|
|
13
|
+
import { validateRepo } from "./workflow-auditor/skills-validator.js";
|
|
14
|
+
export const exportPublicUsage = 'bbc export-public <out-dir> --public-repo <owner/name> [--repo <repo-root>]';
|
|
15
|
+
const MARKER = 'export' + ':drop';
|
|
16
|
+
const LINE_MARK = new RegExp(`(?:<!-- ${MARKER} -->|(?:^|\\s)# ${MARKER}(?![:\\w])[^\\n]*)\\s*$`);
|
|
17
|
+
const BLOCK_START = new Set([`<!-- ${MARKER}:start -->`, `# ${MARKER}:start`]);
|
|
18
|
+
const BLOCK_END = new Set([`<!-- ${MARKER}:end -->`, `# ${MARKER}:end`]);
|
|
19
|
+
const ALWAYS_DROPPED = ['tools/', 'docs/launch/', 'odd/'];
|
|
20
|
+
const ALLOWED_EMAIL = /@(?:[a-z0-9-]+\.)*(?:example\.(?:com|org|net)|[a-z0-9-]+\.(?:test|invalid|example)|users\.noreply\.github\.com|anthropic\.com)$|^git@github\.com$/i;
|
|
21
|
+
const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
|
|
22
|
+
const SLUG_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}$/;
|
|
23
|
+
const HELP = 'Usage: bbc export-public <out-dir> --public-repo <owner/name> [--repo <repo-root>]\n';
|
|
24
|
+
export class ExportRefusedError extends Error {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = 'ExportRefusedError';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function escapeRegex(value) {
|
|
31
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
32
|
+
}
|
|
33
|
+
function defaultRepoRoot() {
|
|
34
|
+
return fileURLToPath(new URL('../../..', import.meta.url));
|
|
35
|
+
}
|
|
36
|
+
export function trackedFiles(root) {
|
|
37
|
+
const res = runExecutable(['git', '-C', root, 'ls-files', '-z']);
|
|
38
|
+
if (res.code !== 0 || res.error) {
|
|
39
|
+
throw new ExportRefusedError(`git ls-files failed: ${res.stderr.toString('utf8').trim()}`);
|
|
40
|
+
}
|
|
41
|
+
return res.stdout
|
|
42
|
+
.toString('utf8')
|
|
43
|
+
.split('\0')
|
|
44
|
+
.filter((name) => name.length > 0);
|
|
45
|
+
}
|
|
46
|
+
export function privateProfiles(root) {
|
|
47
|
+
const profiles = new Map();
|
|
48
|
+
const commandsDir = join(root, 'commands');
|
|
49
|
+
if (!existsSync(commandsDir))
|
|
50
|
+
return profiles;
|
|
51
|
+
let dirs;
|
|
52
|
+
try {
|
|
53
|
+
dirs = readdirSync(commandsDir).sort();
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return profiles;
|
|
57
|
+
}
|
|
58
|
+
for (const name of dirs) {
|
|
59
|
+
const idFile = join(commandsDir, name, 'profile-identifiers.txt');
|
|
60
|
+
if (!existsSync(idFile))
|
|
61
|
+
continue;
|
|
62
|
+
const raw = readFileSync(idFile, 'utf8');
|
|
63
|
+
const words = raw
|
|
64
|
+
.split(/\r?\n/)
|
|
65
|
+
.map((line) => (line.split('#', 1)[0] ?? '').trim())
|
|
66
|
+
.filter((w) => w.length > 0);
|
|
67
|
+
profiles.set(name, words);
|
|
68
|
+
}
|
|
69
|
+
return profiles;
|
|
70
|
+
}
|
|
71
|
+
function buildLeakPatterns(profiles, privateName) {
|
|
72
|
+
const patterns = [
|
|
73
|
+
[new RegExp(escapeRegex(privateName)), 'reference to the private repository'],
|
|
74
|
+
];
|
|
75
|
+
for (const [name, words] of profiles.entries()) {
|
|
76
|
+
for (const word of words) {
|
|
77
|
+
patterns.push([
|
|
78
|
+
new RegExp(`(?<![A-Za-z0-9])${escapeRegex(word)}(?![A-Za-z0-9])`, 'i'),
|
|
79
|
+
`identifier '${word.toLowerCase()}' of the ${name} profile`,
|
|
80
|
+
]);
|
|
81
|
+
}
|
|
82
|
+
const n = escapeRegex(name);
|
|
83
|
+
patterns.push([
|
|
84
|
+
new RegExp(`commands/${n}\\b|(?<![A-Za-z0-9_-])/${n}\\b|(?<![A-Za-z0-9_./-])${n}/|--skill ${n}\\b`),
|
|
85
|
+
`reference to the removed ${name} profile`,
|
|
86
|
+
]);
|
|
87
|
+
}
|
|
88
|
+
patterns.push([
|
|
89
|
+
new RegExp(`${LINE_MARK.source}|^\\s*(?:<!-- |# )${MARKER}:(?:start|end)`, 'm'),
|
|
90
|
+
`leftover ${MARKER} marker`,
|
|
91
|
+
]);
|
|
92
|
+
return patterns;
|
|
93
|
+
}
|
|
94
|
+
export function dropMarked(text, srcName) {
|
|
95
|
+
const kept = [];
|
|
96
|
+
let inside = false;
|
|
97
|
+
const lines = text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
98
|
+
for (const line of lines) {
|
|
99
|
+
const stripped = line.trim();
|
|
100
|
+
if (BLOCK_START.has(stripped)) {
|
|
101
|
+
if (inside)
|
|
102
|
+
throw new ExportRefusedError(`${srcName}: nested ${MARKER}:start`);
|
|
103
|
+
inside = true;
|
|
104
|
+
}
|
|
105
|
+
else if (BLOCK_END.has(stripped)) {
|
|
106
|
+
if (!inside)
|
|
107
|
+
throw new ExportRefusedError(`${srcName}: ${MARKER}:end without start`);
|
|
108
|
+
inside = false;
|
|
109
|
+
}
|
|
110
|
+
else if (!inside && !LINE_MARK.test(line)) {
|
|
111
|
+
kept.push(line);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (inside)
|
|
115
|
+
throw new ExportRefusedError(`${srcName}: ${MARKER}:start is never closed`);
|
|
116
|
+
return kept.join('');
|
|
117
|
+
}
|
|
118
|
+
function copyFileFiltered(src, dst, renames) {
|
|
119
|
+
const data = readFileSync(src);
|
|
120
|
+
let text = decodeUtf8Strict(data);
|
|
121
|
+
if (text === null) {
|
|
122
|
+
writeFileSync(dst, data);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (text.includes(MARKER)) {
|
|
126
|
+
text = dropMarked(text, src.split(/[\\/]/).pop() ?? src);
|
|
127
|
+
}
|
|
128
|
+
for (const [oldStr, newStr] of renames) {
|
|
129
|
+
text = text.replaceAll(oldStr, newStr);
|
|
130
|
+
}
|
|
131
|
+
writeFileSync(dst, text, 'utf8');
|
|
132
|
+
}
|
|
133
|
+
function walkFilesSorted(dir, rootDir, out) {
|
|
134
|
+
const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
135
|
+
for (const entry of entries) {
|
|
136
|
+
const full = join(dir, entry.name);
|
|
137
|
+
if (entry.isDirectory()) {
|
|
138
|
+
walkFilesSorted(full, rootDir, out);
|
|
139
|
+
}
|
|
140
|
+
else if (entry.isFile()) {
|
|
141
|
+
out.push(relative(rootDir, full).replaceAll('\\', '/'));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function problemsIn(outDir, patterns) {
|
|
146
|
+
const found = [];
|
|
147
|
+
const files = [];
|
|
148
|
+
walkFilesSorted(outDir, outDir, files);
|
|
149
|
+
files.sort();
|
|
150
|
+
for (const rel of files) {
|
|
151
|
+
const text = decodeUtf8Strict(readFileSync(join(outDir, rel)));
|
|
152
|
+
if (text === null)
|
|
153
|
+
continue;
|
|
154
|
+
for (const [pattern, label] of patterns) {
|
|
155
|
+
if (pattern.test(text)) {
|
|
156
|
+
found.push(`${rel}: ${label}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const emails = Array.from(new Set(text.match(EMAIL_RE) ?? [])).sort();
|
|
160
|
+
for (const address of emails) {
|
|
161
|
+
if (!ALLOWED_EMAIL.test(address)) {
|
|
162
|
+
const domain = address.split('@', 2)[1] ?? '';
|
|
163
|
+
found.push(`${rel}: personal or real e-mail address (${domain} domain)`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return found;
|
|
168
|
+
}
|
|
169
|
+
function isSubPath(parent, candidate) {
|
|
170
|
+
const p = parent.endsWith(sep) ? parent : `${parent}${sep}`;
|
|
171
|
+
return candidate.startsWith(p);
|
|
172
|
+
}
|
|
173
|
+
function validatePublicExport(outDir) {
|
|
174
|
+
const report = validateRepo(outDir);
|
|
175
|
+
if (report.verdict !== 'pass') {
|
|
176
|
+
throw new ExportRefusedError(`validate-skills fails on the public edition:\n${report.errors.join('\n')}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
export function exportPublicEdition(rootInput, outInput, publicRepo) {
|
|
180
|
+
const root = resolve(rootInput);
|
|
181
|
+
const out = resolve(outInput);
|
|
182
|
+
if (!SLUG_RE.test(publicRepo)) {
|
|
183
|
+
throw new ExportRefusedError(`--public-repo must be owner/name, got '${publicRepo}'`);
|
|
184
|
+
}
|
|
185
|
+
const exportConfig = JSON.parse(readFileSync(join(root, 'tools', 'export.json'), 'utf8'));
|
|
186
|
+
const privateRepo = String(exportConfig.private_repo ?? '');
|
|
187
|
+
const privateName = privateRepo.split('/')[1] ?? '';
|
|
188
|
+
const publicName = publicRepo.split('/')[1] ?? '';
|
|
189
|
+
const renames = [
|
|
190
|
+
[privateRepo, publicRepo],
|
|
191
|
+
[privateName, publicName],
|
|
192
|
+
];
|
|
193
|
+
if (existsSync(out)) {
|
|
194
|
+
const st = statSync(out);
|
|
195
|
+
if (!st.isDirectory() || readdirSync(out).length > 0) {
|
|
196
|
+
throw new ExportRefusedError(`${out} exists and is not an empty directory; nothing was written`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (out === root || isSubPath(root, out)) {
|
|
200
|
+
throw new ExportRefusedError('the output directory must be outside the repository');
|
|
201
|
+
}
|
|
202
|
+
const profiles = privateProfiles(root);
|
|
203
|
+
const droppedPrefixes = [...ALWAYS_DROPPED, ...Array.from(profiles.keys()).map((name) => `commands/${name}/`)];
|
|
204
|
+
let kept = 0;
|
|
205
|
+
let skipped = 0;
|
|
206
|
+
mkdirSync(out, { recursive: true });
|
|
207
|
+
try {
|
|
208
|
+
for (const name of trackedFiles(root)) {
|
|
209
|
+
if (droppedPrefixes.some((prefix) => name.startsWith(prefix))) {
|
|
210
|
+
skipped += 1;
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const src = join(root, name);
|
|
214
|
+
if (!existsSync(src) || !statSync(src).isFile()) {
|
|
215
|
+
throw new ExportRefusedError(`${name} is tracked but missing from the working tree`);
|
|
216
|
+
}
|
|
217
|
+
const dst = join(out, name);
|
|
218
|
+
mkdirSync(dirname(dst), { recursive: true });
|
|
219
|
+
copyFileFiltered(src, dst, renames);
|
|
220
|
+
kept += 1;
|
|
221
|
+
}
|
|
222
|
+
const found = problemsIn(out, buildLeakPatterns(profiles, privateName));
|
|
223
|
+
if (found.length > 0) {
|
|
224
|
+
throw new ExportRefusedError(`the public edition would leak:\n ${found.join('\n ')}`);
|
|
225
|
+
}
|
|
226
|
+
validatePublicExport(out);
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
rmSync(out, { recursive: true, force: true });
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
return {
|
|
233
|
+
verdict: 'exported',
|
|
234
|
+
output: out,
|
|
235
|
+
files: kept,
|
|
236
|
+
left_out: skipped,
|
|
237
|
+
profiles_removed: Array.from(profiles.keys()).sort(),
|
|
238
|
+
public_repo: publicRepo,
|
|
239
|
+
history: 'none (files only)',
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
export function exportPublic(argv) {
|
|
243
|
+
if (argv.length === 0 || argv[0] === '-h' || argv[0] === '--help') {
|
|
244
|
+
process.stdout.write(`${HELP}\n`);
|
|
245
|
+
return argv.length > 0 ? 0 : 2;
|
|
246
|
+
}
|
|
247
|
+
const outDir = argv[0];
|
|
248
|
+
let root = defaultRepoRoot();
|
|
249
|
+
let publicRepo = null;
|
|
250
|
+
let idx = 1;
|
|
251
|
+
while (idx + 1 < argv.length && (argv[idx] === '--repo' || argv[idx] === '--public-repo')) {
|
|
252
|
+
if (argv[idx] === '--repo') {
|
|
253
|
+
root = argv[idx + 1];
|
|
254
|
+
}
|
|
255
|
+
else {
|
|
256
|
+
publicRepo = argv[idx + 1];
|
|
257
|
+
}
|
|
258
|
+
idx += 2;
|
|
259
|
+
}
|
|
260
|
+
if (idx < argv.length || publicRepo === null) {
|
|
261
|
+
process.stderr.write(`${HELP}\n`);
|
|
262
|
+
return 2;
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
const report = exportPublicEdition(root, outDir, publicRepo);
|
|
266
|
+
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
267
|
+
return 0;
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
271
|
+
process.stderr.write(`export refused: ${msg}\n`);
|
|
272
|
+
return 1;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
@@ -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(/&/gi, '&')
|
|
49
|
+
.replace(/</gi, '<')
|
|
50
|
+
.replace(/>/gi, '>')
|
|
51
|
+
.replace(/"/gi, '"')
|
|
52
|
+
.replace(/'|'/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
|
+
};
|