Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

ci: versioned failure and execution manifest for nightly-watch

garrytan3a64cfd0a72a
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index a8bc321604..3a091d6139 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -949,6 +949,21 @@ jobs:
retention-days: 14
if-no-files-found: ignore
overwrite: true
+ # Versioned failure and execution manifest bound to this SHA, run and
+ # attempt; nightly-watch reads it to list every failing test and to
+ # prove a file ran and passed before it clears a master-red failure.
+ - name: Failure and execution manifest (nightly-watch evidence)
+ if: always()
+ run: bun scripts/ci-manifest.ts --receipts-dir "$RUNNER_TEMP/receipts" --out "$RUNNER_TEMP/ci-manifest.json" --summary "$GITHUB_STEP_SUMMARY"
+ - name: Upload failure manifest
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: ci-manifest
+ path: ${{ runner.temp }}/ci-manifest.json
+ retention-days: 30
+ if-no-files-found: warn
+ overwrite: true
# The stable aggregate includes full-profile execution lanes when requested.
# Coverage reporting itself remains advisory; failed tests never do.
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index af072997f6..2e71bb1bd6 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -824,6 +824,7 @@ jobs:
with:
sparse-checkout: |
scripts/ci-executed-counts.ts
+ scripts/ci-manifest.ts
docs/test-audit/2026-10-04/expected-deltas.tsv
sparse-checkout-cone-mode: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
@@ -850,6 +851,21 @@ jobs:
retention-days: 14
if-no-files-found: ignore
overwrite: true
+ # Versioned failure and execution manifest bound to this SHA, run and
+ # attempt; nightly-watch reads it to list every failing test and to
+ # prove a file ran and passed before it clears a master-red failure.
+ - name: Failure and execution manifest (nightly-watch evidence)
+ if: always()
+ run: bun scripts/ci-manifest.ts --receipts-dir "$RUNNER_TEMP/receipts" --out "$RUNNER_TEMP/ci-manifest.json" --summary "$GITHUB_STEP_SUMMARY"
+ - name: Upload failure manifest
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: ci-manifest
+ path: ${{ runner.temp }}/ci-manifest.json
+ retention-days: 30
+ if-no-files-found: warn
+ overwrite: true
# The stable aggregate succeeds only when every required lane ran successfully.
# Coverage percentages remain advisory until their separate graduation.
diff --git a/scripts/ci-manifest.ts b/scripts/ci-manifest.ts
new file mode 100644
index 0000000000..c0b2bd2e56
--- /dev/null
+++ b/scripts/ci-manifest.ts
@@ -0,0 +1,118 @@
+#!/usr/bin/env bun
+/**
+ * Failure and execution manifest (green master wave, Lane 4 evidence).
+ *
+ * bun scripts/ci-manifest.ts --receipts-dir <dir> --out <file> [--summary <file>] [--deltas <tsv>]
+ *
+ * Reads every lane's executed-test receipts (the Bun JUnit reports written by
+ * scripts/lib/test-env.sh, loaded through scripts/ci-executed-counts.ts) and
+ * writes one versioned JSON manifest bound to the workflow, event, SHA, run id
+ * and run attempt taken from the GitHub Actions environment
+ * (GITHUB_WORKFLOW, GITHUB_EVENT_NAME, GITHUB_SHA, GITHUB_RUN_ID,
+ * GITHUB_RUN_ATTEMPT). test.yml and e2e.yml upload it as the `ci-manifest`
+ * artifact from their `executed-receipts` job; nightly-watch
+ * (scripts/nightly-issue.ts) reads it to name every failing test and to
+ * prove which files ran and passed before it clears a master-red failure.
+ *
+ * `complete` is false when any lane's receipts are incomplete (a killed
+ * shard, a truncated report, a receipt from an older attempt, a lane that
+ * executed nothing without a declared skip row, no receipts at all). An incomplete manifest still lists the failures it saw, but it never
+ * counts as proof that a file passed. Exit 0 when written, 2 on usage error.
+ * Docs: docs/ci-red-runbook.md#ci-failure-manifest
+ */
+import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { buildSide, compare, DEFAULT_DELTAS, loadReceiptDir, parseDeltas, type DeltaRow, type Receipt } from './ci-executed-counts.ts';
+
+export const MANIFEST_SCHEMA = 'gbrain-ci-manifest/v1';
+export const MANIFEST_ARTIFACT = 'ci-manifest';
+export const MANIFEST_FILE = 'ci-manifest.json';
+export const MANIFEST_DOCS = 'docs/ci-red-runbook.md#ci-failure-manifest';
+
+export interface ManifestFile { file: string; lane: string; arm: string; executed: number; failed: number; skipped: number }
+export interface ManifestFailure { lane: string; file: string; test: string; arm: string }
+export interface CiManifest {
+ schema: typeof MANIFEST_SCHEMA;
+ workflow: string;
+ event: string;
+ sha: string;
+ run_id: number;
+ run_attempt: number;
+ complete: boolean;
+ problems: string[];
+ files: ManifestFile[];
+ failures: ManifestFailure[];
+}
+export interface ManifestBinding { workflow: string; event: string; sha: string; run_id: number; run_attempt: number }
+
+/** `deltas` are the declared skips of docs/test-audit/2026-10-04/expected-deltas.tsv (a keyless lane declared empty is not a problem). */
+export function buildManifest(receipts: Receipt[], bind: ManifestBinding, deltas: { rows: DeltaRow[]; errors: string[] } = { rows: [], errors: [] }): CiManifest {
+ const side = buildSide('manifest', receipts, new Map([[String(bind.run_id), bind.run_attempt]]));
+ const problems = compare(side, undefined, deltas).issues.map(i => i.detail);
+ if (!receipts.length) problems.push('no receipts were downloaded (every receipts-* upload is missing)');
+ const foreign = [...side.shas].filter(s => s && s !== bind.sha);
+ if (foreign.length) problems.push(`receipts come from other commits (${foreign.map(s => s.slice(0, 12)).join(', ')}), not ${bind.sha.slice(0, 12)}`);
+ const files = new Map<string, ManifestFile>();
+ const failures: ManifestFailure[] = [];
+ for (const id of side.identities.values()) {
+ const key = `${id.lane}\u001f${id.file}\u001f${id.arm}`;
+ const entry = files.get(key) ?? { file: id.file, lane: id.lane, arm: id.arm, executed: 0, failed: 0, skipped: 0 };
+ if (id.status === 'pass' || id.status === 'fail') entry.executed++;
+ else entry.skipped++;
+ if (id.status === 'fail') {
+ entry.failed++;
+ failures.push({ lane: id.lane, file: id.file, test: id.test, arm: id.arm });
+ }
+ files.set(key, entry);
+ }
+ const byKey = (a: { lane: string; file: string; arm: string }, b: { lane: string; file: string; arm: string }) =>
+ a.file.localeCompare(b.file) || a.lane.localeCompare(b.lane) || a.arm.localeCompare(b.arm);
+ return {
+ schema: MANIFEST_SCHEMA, ...bind, complete: problems.length === 0, problems,
+ files: [...files.values()].sort(byKey),
+ failures: failures.sort((a, b) => byKey(a, b) || a.test.localeCompare(b.test)),
+ };
+}
+
+/** Validate a downloaded manifest against the run it must describe; a mismatch is a problem string, never a silent pass. */
+export function checkManifest(value: unknown, bind: Pick<ManifestBinding, 'sha' | 'run_id' | 'run_attempt'>): { manifest?: CiManifest; problem?: string } {
+ const m = value as Partial<CiManifest> | null;
+ if (!m || typeof m !== 'object') return { problem: 'the manifest is not a JSON object' };
+ if (m.schema !== MANIFEST_SCHEMA) return { problem: `the manifest schema is '${String(m.schema)}', expected '${MANIFEST_SCHEMA}'` };
+ if (m.sha !== bind.sha || m.run_id !== bind.run_id) return { problem: `the manifest describes run ${String(m.run_id)} at ${String(m.sha).slice(0, 12)}, not run ${bind.run_id} at ${bind.sha.slice(0, 12)}` };
+ if (m.run_attempt !== bind.run_attempt) return { problem: `the manifest comes from attempt ${String(m.run_attempt)}; the run's latest attempt is ${bind.run_attempt} (re-run all jobs so the manifest is rebuilt)` };
+ if (!Array.isArray(m.files) || !Array.isArray(m.failures) || !Array.isArray(m.problems) || typeof m.complete !== 'boolean') return { problem: 'the manifest is missing its files, failures, problems or complete fields' };
+ return { manifest: m as CiManifest };
+}
+
+/** Files that executed at least one test and failed none, across every lane and arm that ran them. */
+export function passedFiles(manifest: CiManifest): Set<string> {
+ const failed = new Set(manifest.files.filter(f => f.failed > 0).map(f => f.file));
+ return new Set(manifest.files.filter(f => f.executed > 0 && !failed.has(f.file)).map(f => f.file));
+}
+
+function main(argv: string[]): number {
+ const flag = (name: string) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined; };
+ const dir = flag('--receipts-dir');
+ const out = flag('--out');
+ const env = process.env;
+ const runId = Number(env.GITHUB_RUN_ID);
+ const attempt = Number(env.GITHUB_RUN_ATTEMPT);
+ if (!dir || !out || !Number.isInteger(runId) || !Number.isInteger(attempt) || !env.GITHUB_SHA) {
+ console.error('usage: bun scripts/ci-manifest.ts --receipts-dir <dir> --out <file> [--summary <file>] [--deltas <tsv>]');
+ console.error('Why: the manifest is bound to GITHUB_SHA, GITHUB_RUN_ID and GITHUB_RUN_ATTEMPT, which only an Actions job sets.');
+ console.error(`Fix: run it inside the executed-receipts job, or export those variables for a local check. Docs: ${MANIFEST_DOCS}`);
+ return 2;
+ }
+ const receipts = existsSync(dir) ? loadReceiptDir(dir) : [];
+ const deltasPath = flag('--deltas') ?? DEFAULT_DELTAS;
+ const deltas = existsSync(deltasPath) ? parseDeltas(readFileSync(deltasPath, 'utf8')) : { rows: [], errors: [] };
+ const manifest = buildManifest(receipts, { workflow: env.GITHUB_WORKFLOW ?? '', event: env.GITHUB_EVENT_NAME ?? '', sha: env.GITHUB_SHA, run_id: runId, run_attempt: attempt }, deltas);
+ writeFileSync(out, `${JSON.stringify(manifest, null, 2)}\n`);
+ const line = `ci-manifest: ${manifest.files.length} file/lane/arm entries, ${manifest.failures.length} failing tests, ${manifest.complete ? 'complete' : `INCOMPLETE (${manifest.problems.length} problems; nightly-watch will not clear failures from this run)`}.`;
+ console.log(line);
+ const summary = flag('--summary');
+ if (summary) appendFileSync(summary, `${line} Docs: ${MANIFEST_DOCS}\n`);
+ return 0;
+}
+
+if (import.meta.main) process.exitCode = main(process.argv.slice(2));
diff --git a/scripts/lib/ci-run.ts b/scripts/lib/ci-run.ts
new file mode 100644
index 0000000000..7d1a0e02b1
--- /dev/null
+++ b/scripts/lib/ci-run.ts
@@ -0,0 +1,179 @@
+/**
+ * One completed workflow run's failure evidence, shared by the nightly-red
+ * and master-red watchers (scripts/nightly-issue.ts, scripts/lib/master-red.ts).
+ *
+ * `collectEvidence` reads the run's jobs, the failing jobs' check-run
+ * annotations and, for workflows that upload it, the `ci-manifest` artifact
+ * (scripts/ci-manifest.ts). It returns structured failure records (job, step,
+ * every failing test file and test identity) kept apart from sanitized error
+ * excerpts, plus `complete` and `problems`: a jobs page, annotation or
+ * manifest that could not be read is incomplete evidence, never zero
+ * failures, and incomplete evidence never clears a failure.
+ *
+ * `reproduceCommand` builds the one reproduce line every issue prints from
+ * validated fields only (a strict test-path pattern), never from run text.
+ */
+import { checkManifest, MANIFEST_ARTIFACT, MANIFEST_FILE, passedFiles, type CiManifest } from '../ci-manifest.ts';
+import { fetchArtifactJson, inert, redactCredentials, type GitHubClient } from './gh-issue.ts';
+
+export interface RunInfo {
+ id: number;
+ name: string;
+ event: string;
+ status?: string;
+ conclusion: string | null;
+ run_number: number;
+ run_attempt: number;
+ path: string;
+ workflow_id: number;
+ head_branch: string;
+ head_sha: string;
+ html_url: string;
+ created_at?: string;
+ head_repository?: { full_name: string };
+ repository?: { full_name: string };
+}
+export interface JobInfo {
+ id: number;
+ name: string;
+ conclusion: string | null;
+ html_url?: string;
+ steps?: Array<{ number: number; name: string; conclusion: string | null }>;
+}
+export interface Annotation { annotation_level: string; title?: string | null; message: string; path?: string }
+
+export interface FailedTest { file: string; test: string; lane: string; arm: string; job?: string; postgres: boolean }
+export interface FailedJob { job: string; job_id: number; step: string; conclusion: string; files: string[]; excerpt: string[]; owner_signal: boolean }
+export interface RunEvidence {
+ verdict: 'red' | 'green' | 'ignored';
+ jobs: JobInfo[];
+ annotations: Record<number, Annotation[]>;
+ failed: FailedJob[];
+ succeeded: string[];
+ tests: FailedTest[];
+ files: string[];
+ passed: string[];
+ manifest: 'read' | 'not-expected' | 'unreadable';
+ complete: boolean;
+ problems: string[];
+}
+
+export const FAILING = new Set(['failure', 'timed_out', 'cancelled', 'startup_failure']);
+export const RED_CONCLUSIONS = new Set(['failure', 'timed_out', 'startup_failure']);
+export const AGGREGATORS = new Set(['test-status', 'e2e-status']);
+export const MANIFEST_WORKFLOWS = new Set(['test.yml', 'e2e.yml']);
+export const TEST_FILE = /^test\/[\w./-]+\.test\.ts$/;
+export const OWNER_SIGNAL = /gh secret set|secret is empty|secrets? (?:is |are )?(?:empty|missing|not configured)/i;
+const GENERIC_ERROR = /^Process completed with exit code \d+\.?$/;
+const FILE_IN_TEXT = /(?:^|[\s(/'"])(test\/[\w./-]+?\.test\.ts)\b/g;
+const POSTGRES_SIGNAL = /PostgreSQL arm|DATABASE_URL|postgres/i;
+export const EXCERPTS_PER_JOB = 5;
+
+export const workflowFile = (run: Pick<RunInfo, 'path'>) => run.path.split('/').pop() ?? run.path;
+
+export function verdictOf(conclusion: string | null): RunEvidence['verdict'] {
+ if (conclusion === 'success') return 'green';
+ return RED_CONCLUSIONS.has(conclusion ?? '') ? 'red' : 'ignored';
+}
+
+/** `bun run test:stress <file> --iterations 10 [--postgres]`, or undefined when the path fails validation. */
+export function reproduceCommand(file: string, postgres: boolean): string | undefined {
+ if (!TEST_FILE.test(file) || file.includes('..')) return undefined;
+ return `bun run test:stress ${file} --iterations 10${postgres ? ' --postgres' : ''}`;
+}
+
+export async function pagedJobs(client: GitHubClient, run: RunInfo): Promise<{ jobs: JobInfo[]; complete: boolean }> {
+ const jobs: JobInfo[] = [];
+ let total = 0;
+ for (let page = 1; page <= 5; page++) {
+ const r = await client.request<{ jobs: JobInfo[]; total_count: number }>('GET', `repos/{repo}/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100&page=${page}`);
+ jobs.push(...r.jobs);
+ total = r.total_count;
+ if (jobs.length >= r.total_count || r.jobs.length < 100) break;
+ }
+ return { jobs, complete: jobs.length >= total };
+}
+
+/** Test files named by failure annotations: the annotation path, else paths quoted in the message (stack frames). */
+export function annotationFiles(annotations: Annotation[]): string[] {
+ const files = new Set<string>();
+ for (const a of annotations.filter(x => x.annotation_level === 'failure')) {
+ if (a.path && TEST_FILE.test(a.path)) files.add(a.path);
+ for (const m of `${a.title ?? ''} ${a.message}`.matchAll(FILE_IN_TEXT)) if (TEST_FILE.test(m[1]!)) files.add(m[1]!);
+ }
+ return [...files].sort();
+}
+
+export function failedJobRecord(job: JobInfo, annotations: Annotation[]): FailedJob {
+ const step = job.steps?.find(s => FAILING.has(s.conclusion ?? ''));
+ const errors = annotations.filter(a => a.annotation_level === 'failure' && !GENERIC_ERROR.test(a.message.trim()))
+ .map(a => [a.title, a.message].filter(Boolean).join(': '));
+ return {
+ job: inert(job.name), job_id: job.id, step: inert(step?.name ?? '(job-level)'), conclusion: inert(job.conclusion ?? '', 20),
+ files: annotationFiles(annotations),
+ excerpt: errors.slice(0, EXCERPTS_PER_JOB).map(e => inert(redactCredentials(e), 400)),
+ owner_signal: errors.length > 0 && OWNER_SIGNAL.test(errors.join(' ')),
+ };
+}
+
+export interface EvidenceOptions { manifest?: (run: RunInfo) => Promise<{ value?: unknown; reason?: string }> }
+
+export async function collectEvidence(client: GitHubClient, run: RunInfo, opts: EvidenceOptions = {}): Promise<RunEvidence> {
+ const problems: string[] = [];
+ const { jobs, complete: jobsComplete } = await pagedJobs(client, run);
+ if (!jobsComplete) problems.push(`the jobs list of run ${run.id} was truncated`);
+ const failing = jobs.filter(j => FAILING.has(j.conclusion ?? ''));
+ const shown = failing.some(j => !AGGREGATORS.has(j.name)) ? failing.filter(j => !AGGREGATORS.has(j.name)) : failing;
+ const failed: FailedJob[] = [];
+ const byJob: Record<number, Annotation[]> = {};
+ for (const job of shown) {
+ let annotations: Annotation[] = [];
+ try {
+ annotations = await client.request<Annotation[]>('GET', `repos/{repo}/check-runs/${job.id}/annotations?per_page=50`);
+ } catch (e) {
+ problems.push(`annotations of job '${inert(job.name)}' could not be read (${inert(e instanceof Error ? e.message : String(e), 120)})`);
+ }
+ byJob[job.id] = annotations;
+ failed.push(failedJobRecord(job, annotations));
+ }
+ const tests: FailedTest[] = [];
+ let passed: string[] = [];
+ let manifestState: RunEvidence['manifest'] = 'not-expected';
+ if (MANIFEST_WORKFLOWS.has(workflowFile(run))) {
+ const got = await (opts.manifest ?? (r => fetchArtifactJson(client, r.id, MANIFEST_ARTIFACT, MANIFEST_FILE)))(run);
+ const checked = got.value === undefined ? { problem: got.reason ?? 'the manifest could not be read' } : checkManifest(got.value, { sha: run.head_sha, run_id: run.id, run_attempt: run.run_attempt });
+ if (checked.manifest) {
+ manifestState = 'read';
+ const m: CiManifest = checked.manifest;
+ if (!m.complete) problems.push(`the ${MANIFEST_ARTIFACT} artifact is incomplete: ${m.problems.slice(0, 3).map(p => inert(p, 160)).join('; ')}${m.problems.length > 3 ? ` (+${m.problems.length - 3} more)` : ''}`);
+ for (const f of m.failures) {
+ if (!TEST_FILE.test(f.file)) continue;
+ tests.push({ file: f.file, test: inert(f.test, 300), lane: inert(f.lane, 60), arm: inert(f.arm, 60), postgres: POSTGRES_SIGNAL.test(`${f.arm} ${f.lane}`) });
+ }
+ passed = [...passedFiles(m)].filter(f => TEST_FILE.test(f)).sort();
+ } else {
+ manifestState = 'unreadable';
+ problems.push(`${checked.problem}`);
+ }
+ }
+ for (const job of failed) {
+ const postgres = POSTGRES_SIGNAL.test(`${job.job} ${job.excerpt.join(' ')}`);
+ for (const file of job.files) {
+ if (!tests.some(t => t.file === file)) tests.push({ file, test: '', lane: '', arm: '', job: job.job, postgres });
+ }
+ }
+ const files = [...new Set([...tests.map(t => t.file), ...failed.flatMap(j => j.files)])].sort();
+ return {
+ verdict: verdictOf(run.conclusion),
+ jobs,
+ annotations: byJob,
+ failed,
+ succeeded: jobs.filter(j => j.conclusion === 'success').map(j => inert(j.name)),
+ tests,
+ files,
+ passed,
+ manifest: manifestState,
+ complete: problems.length === 0,
+ problems,
+ };
+}
diff --git a/scripts/lib/gh-issue.ts b/scripts/lib/gh-issue.ts
index f9a9a92804..8d09039142 100644
--- a/scripts/lib/gh-issue.ts
+++ b/scripts/lib/gh-issue.ts
@@ -12,10 +12,19 @@
* - `findIssueByTitle` looks an issue up through the list API by label and
* exact title (open first, else the most recently updated closed one, so a
* flapping workflow reopens its own issue).
+ * - `fetchArtifactJson` reads one JSON file out of a run artifact's zip
+ * (`readZipEntry`, stored or deflated entries); every failure is returned
+ * as a reason string so callers report incomplete evidence, never zero
+ * failures.
+ * - `redactCredentials` strips user:password from database URLs in any text
+ * shown to an agent.
*/
+import { inflateRawSync } from 'node:zlib';
export interface GitHubClient {
request<T = unknown>(method: 'GET' | 'POST' | 'PATCH', path: string, body?: unknown): Promise<T>;
+ /** Raw bytes of a GET (artifact archives); follows the redirect to blob storage without forwarding the token. */
+ download?(path: string): Promise<Uint8Array>;
}
export interface Issue {
@@ -24,6 +33,7 @@ export interface Issue {
state: 'open' | 'closed';
body?: string | null;
labels?: Array<{ name: string } | string>;
+ created_at?: string;
updated_at?: string;
pull_request?: unknown;
}
@@ -76,6 +86,14 @@ export function restClient(repo: string, token = process.env.GH_TOKEN || process
}
return (res.status === 204 ? undefined : await res.json()) as T;
},
+ async download(path: string): Promise<Uint8Array> {
+ const url = `https://api.github.com/${resolve(path)}`;
+ const res = await fetch(url, { headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json' }, redirect: 'manual' });
+ const location = res.headers.get('location');
+ const body = location ? await fetch(location) : res;
+ if (!body.ok) throw Object.assign(new Error(`GitHub download ${url} -> ${body.status}`), { status: body.status });
+ return new Uint8Array(await body.arrayBuffer());
+ },
};
}
@@ -92,6 +110,11 @@ function ghCliClient(resolve: (path: string) => string): GitHubClient {
const out = r.stdout.toString().trim();
return (out ? JSON.parse(out) : undefined) as T;
},
+ async download(path: string): Promise<Uint8Array> {
+ const r = Bun.spawnSync(['gh', 'api', resolve(path)], { stdout: 'pipe', stderr: 'pipe' });
+ if (r.exitCode !== 0) throw new Error(`gh api ${resolve(path)} failed: ${r.stderr.toString().slice(0, 300)}. Fix: gh auth login, or export GH_TOKEN.`);
+ return new Uint8Array(r.stdout);
+ },
};
}
@@ -145,3 +168,89 @@ export function readJsonBlock<T>(body: string | null | undefined, marker: string
export function jsonBlock(marker: string, value: unknown): string {
return `<!-- ${marker} -->\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``;
}
+
+export async function getIssue(client: GitHubClient, number: number): Promise<Issue> {
+ return client.request<Issue>('GET', `repos/{repo}/issues/${number}`);
+}
+
+/** Issues carrying a label (newest created first), pull requests excluded. */
+export async function listLabeled(client: GitHubClient, label: string, state: 'open' | 'all', maxPages = 3): Promise<Issue[]> {
+ const out: Issue[] = [];
+ for (let page = 1; page <= maxPages; page++) {
+ const batch = await client.request<Issue[]>('GET', `repos/{repo}/issues?labels=${encodeURIComponent(label)}&state=${state}&sort=created&direction=desc&per_page=100&page=${page}`);
+ out.push(...batch.filter(i => !i.pull_request));
+ if (batch.length < 100) break;
+ }
+ return out;
+}
+
+export interface LinkedPull { number: number; merged_at: string | null; state: string; user?: string }
+
+/** Pull requests that cross-reference or connect to an issue (its timeline), oldest first. */
+export async function linkedPulls(client: GitHubClient, number: number): Promise<Array<LinkedPull & { linked_at: string }>> {
+ const events = await client.request<Array<{ event: string; created_at?: string; source?: { issue?: { number: number; state: string; user?: { login: string }; pull_request?: { merged_at?: string | null } } } }>>(
+ 'GET', `repos/{repo}/issues/${number}/timeline?per_page=100`);
+ const seen = new Set<number>();
+ const out: Array<LinkedPull & { linked_at: string }> = [];
+ for (const e of events) {
+ const src = e.source?.issue;
+ if (e.event !== 'cross-referenced' || !src?.pull_request || seen.has(src.number)) continue;
+ seen.add(src.number);
+ out.push({ number: src.number, merged_at: src.pull_request.merged_at ?? null, state: src.state, user: src.user?.login, linked_at: e.created_at ?? '' });
+ }
+ return out;
+}
+
+const DB_URL_CREDENTIALS = /\b((?:postgres(?:ql)?|mysql|redis|mongodb(?:\+srv)?):\/\/)[^\s/@:]*(?::[^\s/@]*)?@/gi;
+
+/** Remove user:password from database URLs (`postgres://u:p@h/db` -> `postgres://<redacted>@h/db`). */
+export function redactCredentials(text: string): string {
+ return text.replace(DB_URL_CREDENTIALS, '$1<redacted>@');
+}
+
+/** Read one file from a zip archive (stored or deflated entries, central directory lookup). */
+export function readZipEntry(zip: Uint8Array, name: string): Uint8Array | undefined {
+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
+ let eocd = -1;
+ for (let i = zip.length - 22; i >= Math.max(0, zip.length - 65_557); i--) {
+ if (view.getUint32(i, true) === 0x06054b50) { eocd = i; break; }
+ }
+ if (eocd < 0) return undefined;
+ const entries = view.getUint16(eocd + 10, true);
+ let at = view.getUint32(eocd + 16, true);
+ const decoder = new TextDecoder();
+ for (let n = 0; n < entries && at + 46 <= zip.length; n++) {
+ if (view.getUint32(at, true) !== 0x02014b50) return undefined;
+ const method = view.getUint16(at + 10, true);
+ const size = view.getUint32(at + 20, true);
+ const nameLen = view.getUint16(at + 28, true);
+ const extraLen = view.getUint16(at + 30, true);
+ const commentLen = view.getUint16(at + 32, true);
+ const local = view.getUint32(at + 42, true);
+ const entryName = decoder.decode(zip.subarray(at + 46, at + 46 + nameLen));
+ at += 46 + nameLen + extraLen + commentLen;
+ if (entryName !== name) continue;
+ const start = local + 30 + view.getUint16(local + 26, true) + view.getUint16(local + 28, true);
+ const data = zip.subarray(start, start + size);
+ if (method === 0) return data;
+ if (method === 8) return new Uint8Array(inflateRawSync(data));
+ return undefined;
+ }
+ return undefined;
+}
+
+/** One JSON file from a run's named artifact; `reason` says why it could not be read (missing, expired, unreadable). */
+export async function fetchArtifactJson(client: GitHubClient, runId: number, artifact: string, file: string): Promise<{ value?: unknown; reason?: string }> {
+ if (!client.download) return { reason: 'this client cannot download artifacts' };
+ try {
+ const list = await client.request<{ artifacts: Array<{ id: number; name: string; expired: boolean }> }>('GET', `repos/{repo}/actions/runs/${runId}/artifacts?name=${encodeURIComponent(artifact)}&per_page=10`);
+ const found = list.artifacts.find(a => a.name === artifact);
+ if (!found) return { reason: `run ${runId} has no '${artifact}' artifact` };
+ if (found.expired) return { reason: `run ${runId}'s '${artifact}' artifact has expired` };
+ const bytes = readZipEntry(await client.download(`repos/{repo}/actions/artifacts/${found.id}/zip`), file);
+ if (!bytes) return { reason: `run ${runId}'s '${artifact}' artifact has no readable ${file}` };
+ return { value: JSON.parse(new TextDecoder().decode(bytes)) };
+ } catch (e) {
+ return { reason: `reading run ${runId}'s '${artifact}' artifact failed: ${e instanceof Error ? e.message : String(e)}` };
+ }
+}