Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(ci): failing-test step summary from captured logs (B13)

garrytanb93bfec8183e
diff --git a/scripts/capture-test-log.ts b/scripts/capture-test-log.ts
index 1c7c03c820..d8dd58d53d 100644
--- a/scripts/capture-test-log.ts
+++ b/scripts/capture-test-log.ts
@@ -1,13 +1,99 @@
#!/usr/bin/env bun
// Preserve live CI output while recording the timestamps used by the weight miner.
import { spawn } from 'node:child_process';
-import { createWriteStream, mkdirSync } from 'node:fs';
+import { appendFileSync, createWriteStream, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { once } from 'node:events';
import { constants } from 'node:os';
import type { Readable, Writable } from 'node:stream';
const MAX_PENDING_CHARS = 64 * 1024;
+const SUMMARY_FAILURES = 50;
+const ERROR_LINES = 15;
+
+export interface CapturedFailure { file: string; test: string; arm: string; error: string[] }
+
+/**
+ * Reads the live test output line by line and keeps the last 50 failures
+ * with the context an agent needs: file, test, backend arm, the first error
+ * block Bun printed above the `(fail)` line, and a reproduction command.
+ * Memory stays bounded: only the lines since the last test result are held.
+ */
+export class FailureCollector {
+ failures: CapturedFailure[] = [];
+ total = 0;
+ private file = '';
+ private arm = '';
+ private fileFailures = 0;
+ private justFailed = false;
+ private block: string[] = [];
+ private tail: string[] = [];
+ feed(raw: string): void {
+ const line = raw.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
+ this.tail.push(line);
+ if (this.tail.length > 20) this.tail.shift();
+ // Bun prints a timeout or hook note right below its (fail) line.
+ const last = this.failures[this.failures.length - 1];
+ if (this.justFailed && last && /^\s+\^ /.test(line)) { last.error.push(line.trim()); return; }
+ this.justFailed = false;
+ const header = /^(?:::group::|##\[group\])?(\S.*\.test\.[cm]?[jt]sx?):$/.exec(line);
+ if (header) { this.file = header[1]; this.fileFailures = 0; this.block = []; return; }
+ if (/^=== .+ ===$/.test(line)) { this.arm = ''; this.fileFailures = 0; this.block = []; return; }
+ const pooled = /^--- .+ \[(\S+)\] ---$/.exec(line);
+ if (pooled) { this.arm = pooled[1]; this.block = []; return; }
+ const failed = /^(?:\(fail\)|✗) (.*?)(?: \[[0-9.]+m?s\])?$/.exec(line);
+ if (failed) { this.push(failed[1]); return; }
+ const runner = /^FAILED: (.+)$/.exec(line);
+ // run-e2e.sh's per-file verdict: only news when Bun printed no (fail) for that file.
+ if (runner) { if (!this.fileFailures) this.push(`(runner) ${runner[1]}`, [line]); return; }
+ if (/^\((pass|skip|todo)\) /.test(line) || /^[✓»] /.test(line)) { this.block = []; return; }
+ this.block.push(line);
+ if (this.block.length > 200) this.block.splice(0, this.block.length - 200);
+ }
+ private push(test: string, error = this.block): void {
+ const trimmed = [...error];
+ while (trimmed.length && !trimmed[0].trim()) trimmed.shift();
+ while (trimmed.length && !trimmed[trimmed.length - 1].trim()) trimmed.pop();
+ this.failures.push({ file: this.file, test, arm: this.arm, error: trimmed.slice(0, ERROR_LINES) });
+ if (this.failures.length > SUMMARY_FAILURES) this.failures.shift();
+ this.total++;
+ this.fileFailures++;
+ this.justFailed = true;
+ this.block = [];
+ }
+ /** Markdown for $GITHUB_STEP_SUMMARY after a failed run. */
+ render(job: string, out: string, code: number): string {
+ const fence = (lines: string[]) => {
+ const text = lines.join('\n');
+ const ticks = '`'.repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map(m => m[0].length + 1)));
+ return `${ticks}text\n${text}\n${ticks}`;
+ };
+ const esc = (v: string) => v.replace(/([|`*_<[\]\\])/g, '\\$1').replace(/@/g, '@\u200b');
+ const parts = [`### ${esc(job)}: exited ${code}`, '', `Full log: the job's uploaded timing log (${esc(out.split('/').pop() ?? out)}).`, ''];
+ if (!this.failures.length) {
+ parts.push('No `(fail)` lines were printed (setup, import or runner failure). Last log lines:', '', fence(this.tail), '');
+ return `${parts.join('\n')}\n`;
+ }
+ const shown = this.total > this.failures.length ? `last ${this.failures.length} of ${this.total}` : `${this.total}`;
+ parts.push(`Failing tests (${shown}):`, '');
+ for (const f of this.failures) {
+ const where = [f.file || '(unknown file)', f.test].map(esc).join(' › ');
+ parts.push(`#### ${where}${f.arm ? ` [${esc(f.arm)}]` : ''}`, '');
+ if (f.error.length) parts.push(fence(f.error), '');
+ const repro = reproCommand(f);
+ parts.push(repro.includes('`') ? `Reproduce: \`\` ${repro} \`\`` : `Reproduce: \`${repro}\``, '');
+ }
+ return `${parts.join('\n')}\n`;
+ }
+}
+
+export function reproCommand(f: CapturedFailure): string {
+ const quote = (v: string) => `'${v.replace(/'/g, `'\\''`)}'`;
+ if (!f.file) return 'see the full log';
+ if (f.file.startsWith('test/e2e/') || f.test.startsWith('(runner) ')) return `bash scripts/run-e2e.sh ${f.file}`;
+ const pattern = f.test.split(' > ').join(' ').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return `bun test --timeout=60000 ${f.file} -t ${quote(pattern)}`;
+}
export async function captureTestLog(job: string, out: string, command: string[]): Promise<number> {
if (!job || /[\r\n\t]/.test(job) || !out || command.length === 0) {
@@ -46,7 +132,11 @@ export async function captureTestLog(job: string, out: string, command: string[]
if (stream === log && logError) throw logError;
if (!stream.write(data)) await once(stream, 'drain');
};
- const record = (line: string) => write(log, `${job}\tcapture\t${new Date().toISOString()} ${line}\n`);
+ const failures = new FailureCollector();
+ const record = (line: string) => {
+ failures.feed(line);
+ return write(log, `${job}\tcapture\t${new Date().toISOString()} ${line}\n`);
+ };
const consume = async (source: Readable, mirror: Writable) => {
const decoder = new TextDecoder();
let pending = '';
@@ -90,7 +180,16 @@ export async function captureTestLog(job: string, out: string, command: string[]
: result.code ?? 1;
// A Bun summary can pass before its outer runner detects another failure.
// Keep failed artifacts fail-closed when mined without GitHub run metadata.
- if (code !== 0) await record(`##[error]captured command exited ${code}`);
+ if (code !== 0) {
+ await record(`##[error]captured command exited ${code}`);
+ const summary = process.env.GITHUB_STEP_SUMMARY;
+ // B13: CI's --log-failed can come back empty; the step summary keeps the
+ // failing tests, their first error block and a repro command regardless.
+ if (summary) {
+ try { appendFileSync(summary, failures.render(job, out, code)); }
+ catch (error) { console.error(`capture-test-log: could not write the step summary: ${(error as Error).message}`); }
+ }
+ }
await record(`##[gbrain-capture-complete] exit=${code}`);
await new Promise<void>((resolve, reject) => {
log.once('error', reject);
diff --git a/test/scripts/capture-test-log.test.ts b/test/scripts/capture-test-log.test.ts
index d197eca378..2c960d1623 100644
--- a/test/scripts/capture-test-log.test.ts
+++ b/test/scripts/capture-test-log.test.ts
@@ -158,3 +158,58 @@ setInterval(() => {}, 1000);
}, 10000);
}
});
+
+describe('failure step summary (B13)', () => {
+ // Real Bun runs through the capture wrapper: the summary must carry the
+ // file, the test, the first error block and a command that reproduces it.
+ async function failing(name: string, source: string) {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-capture-summary-'));
+ roots.push(root);
+ writeFileSync(join(root, name), source);
+ const summary = join(root, 'summary.md');
+ const proc = Bun.spawn([process.execPath, SCRIPT, '--job', 'test (3)', '--out', join(root, 'unit.log'), '--',
+ process.execPath, 'test', '--timeout=300', name], {
+ cwd: root, stdout: 'ignore', stderr: 'ignore', env: { ...process.env, GITHUB_STEP_SUMMARY: summary },
+ });
+ const code = await proc.exited;
+ return { code, summary: readFileSync(summary, 'utf8') };
+ }
+
+ it('an assertion failure shows the diff and a -t repro for exactly that test', async () => {
+ const r = await failing('math.test.ts', `import { describe, test, expect } from 'bun:test';
+describe('math', () => { test('adds (carry)', () => { expect(1 + 1).toBe(3); }); test('passes', () => {}); });`);
+ expect(r.code).toBe(1);
+ expect(r.summary).toContain('### test (3): exited 1');
+ expect(r.summary).toContain('#### math.test.ts › math > adds (carry)');
+ expect(r.summary).toContain('Expected: 3');
+ expect(r.summary).toContain('Received: 2');
+ expect(r.summary).toContain("Reproduce: `bun test --timeout=60000 math.test.ts -t 'math adds \\(carry\\)'`");
+ expect(r.summary).not.toContain('passes');
+ }, 30000);
+
+ it('a timeout names the test and keeps the timeout message', async () => {
+ const r = await failing('slow.test.ts', `import { test } from 'bun:test';
+test('waits forever', async () => { await new Promise(() => {}); });`);
+ expect(r.code).toBe(1);
+ expect(r.summary).toContain('#### slow.test.ts › waits forever');
+ expect(r.summary).toMatch(/timed out after 300ms/);
+ }, 30000);
+
+ it('a setup failure with no (fail) line falls back to the last log lines', async () => {
+ const r = await failing('broken.test.ts', `import './missing-module';\nimport { test } from 'bun:test';\ntest('never', () => {});`);
+ expect(r.code).not.toBe(0);
+ expect(r.summary).toContain('No `(fail)` lines were printed');
+ expect(r.summary).toContain('missing-module');
+ }, 30000);
+
+ it('green runs and runs outside Actions write no summary', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-capture-summary-'));
+ roots.push(root);
+ const summary = join(root, 'summary.md');
+ const proc = Bun.spawn([process.execPath, SCRIPT, '--job', 'test (1)', '--out', join(root, 'unit.log'), '--', process.execPath, '-e', '0'], {
+ stdout: 'ignore', stderr: 'ignore', env: { ...process.env, GITHUB_STEP_SUMMARY: summary },
+ });
+ expect(await proc.exited).toBe(0);
+ expect(existsSync(summary)).toBe(false);
+ });
+});