Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(scripts): weight miner fetches unit capture artifacts and serial job logs per job; GitHub unit refresh requires capture completion
time-attack63467b3bed4a
diff --git a/scripts/mine-shard-weights.ts b/scripts/mine-shard-weights.tsindex a6011b0006..0a5dfeb0a4 100644--- a/scripts/mine-shard-weights.ts+++ b/scripts/mine-shard-weights.ts@@ -70,7 +70,7 @@ export function computeWeights(events: TimingEvent[]): Map<string, number> {}/** Refuse partial/failed sources before any output is replaced. */-export function mineWeights(raw: string, lane: Lane, opts: { expectedJobs?: readonly string[]; e2eProfile?: E2EProfile; expectedFiles?: readonly string[] } = {}): Map<string, number> {+export function mineWeights(raw: string, lane: Lane, opts: { expectedJobs?: readonly string[]; e2eProfile?: E2EProfile; expectedFiles?: readonly string[]; requireCapture?: boolean } = {}): Map<string, number> {const full = opts.e2eProfile === "full";const fullPaths = new Map<string, string>();if (full) {@@ -94,9 +94,9 @@ export function mineWeights(raw: string, lane: Lane, opts: { expectedJobs?: readif (missing.length || unexpected.length) throw new Error(`${lane}: timing job set differs from run metadata (missing: ${missing.join(', ') || 'none'}; unexpected: ${unexpected.join(', ') || 'none'})`);}for (const [job, records] of byJob) {- const captured = records.filter(line => line.step === 'capture');- if (!captured.length) continue;- if (captured[0]!.text !== '##[gbrain-capture-start]' ||+ const captured = records.filter(line => line.step === 'capture' || line.text.startsWith('##[gbrain-capture-'));+ if (!captured.length && !opts.requireCapture) continue;+ if (!captured.length || captured[0]!.text !== '##[gbrain-capture-start]' ||captured.at(-1)!.text !== '##[gbrain-capture-complete] exit=0' ||captured.filter(line => line.text === '##[gbrain-capture-start]').length !== 1 ||captured.filter(line => line.text.startsWith('##[gbrain-capture-complete]')).length !== 1) {@@ -193,6 +193,16 @@ function gh(args: string[]): string {if (r.status !== 0) throw new Error(`gh ${args.join(" ")} failed: ${r.stderr}`);return r.stdout;}+/** The capture artifact a unit shard uploads (`timings-unit-N`, test.yml): its records carry the capture markers. */+function capturedUnitLog(run: string, job: string): string {+ const shard = /^test \((\d+)\)$/.exec(job)?.[1];+ if (!shard) throw new Error(`unit: unexpected job name ${job}`);+ const dir = mkdtempSync(join(tmpdir(), "gbrain-mine-unit-"));+ try {+ gh(["run", "download", run, "--name", `timings-unit-${shard}`, "--dir", dir]);+ return readFileSync(join(dir, "unit.log"), "utf8");+ } finally { rmSync(dir, { recursive: true, force: true }); }+}function git(args: string[]): string {const r = spawnSync("git", args, { cwd: ROOT, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });if (r.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${r.stderr}`);@@ -251,6 +261,7 @@ async function main(): Promise<void> {let expectedFiles: string[] | undefined;let attempt: number | undefined;let fullJobs: Array<{ name: string; databaseId: number }> = [];+ let serialJobs: Array<{ name: string; databaseId: number }> = [];if (run) {const info = JSON.parse(gh(["run", "view", run, "--json", full ? "attempt,conclusion,headSha,jobs" : "conclusion,headSha,jobs"]));if (info.conclusion !== "success") throw new Error(`run ${run} is not successful`);@@ -258,6 +269,10 @@ async function main(): Promise<void> {if (!jobs.length || jobs.some((j: { conclusion: string }) => j.conclusion !== "success")) throw new Error(`run ${run} has no complete ${lane} lane`);expectedJobs = jobs.map((j: { name: string }) => j.name);commit = info.headSha;+ if (lane === "serial") {+ if (jobs.some((j: { databaseId: number }) => !Number.isInteger(j.databaseId) || j.databaseId < 1)) throw new Error("serial: missing job identity");+ serialJobs = jobs.map(({ name, databaseId }: { name: string; databaseId: number }) => ({ name, databaseId }));+ }if (full) {if (!Number.isInteger(info.attempt) || info.attempt < 1 || jobs.some((j: { databaseId: number }) => !Number.isInteger(j.databaseId) || j.databaseId < 1)) throw new Error("full E2E: missing attempt or job identity");attempt = info.attempt;@@ -265,8 +280,11 @@ async function main(): Promise<void> {expectedFiles = sourceE2ECorpus(info.headSha);}}- const raw = full ? fullJobs.map(job => gh(["run", "view", run!, "--attempt", String(attempt), "--job", String(job.databaseId), "--log"])).join("\n") : run ? gh(["run", "view", run, "--log"]) : input ? readFileSync(input, "utf8") : await new Response(Bun.stdin.stream()).text();- const measured = mineWeights(raw, lane, { expectedJobs, e2eProfile, expectedFiles });+ const raw = full ? fullJobs.map(job => gh(["run", "view", run!, "--attempt", String(attempt), "--job", String(job.databaseId), "--log"])).join("\n")+ : run && lane === "unit" ? expectedJobs!.map(job => capturedUnitLog(run!, job)).join("\n")+ : run && lane === "serial" ? serialJobs.map(job => gh(["run", "view", run!, "--job", String(job.databaseId), "--log"])).join("\n")+ : run ? gh(["run", "view", run, "--log"]) : input ? readFileSync(input, "utf8") : await new Response(Bun.stdin.stream()).text();+ const measured = mineWeights(raw, lane, { expectedJobs, e2eProfile, expectedFiles, requireCapture: !!run && lane === "unit" });// Downloaded artifacts/stdin may cover only one shard. Only an authoritative// complete GitHub unit/serial/full-E2E run replaces the full map; selected E2E always// merges because its executed corpus depends on the diff.diff --git a/test/scripts/mine-shard-weights.test.ts b/test/scripts/mine-shard-weights.test.tsindex 2e7cec213f..7de83d4329 100644--- a/test/scripts/mine-shard-weights.test.ts+++ b/test/scripts/mine-shard-weights.test.ts@@ -309,29 +309,35 @@ it('GitHub refresh verifies every eligible job before replacing the complete lanconst dir = mkdtempSync(join(tmpdir(), 'gbrain-mine-github-'));try {const bin = join(dir, 'bin');+ const artifacts = join(dir, 'artifacts');mkdirSync(bin);+ mkdirSync(artifacts);const fakeGh = join(bin, 'gh');- writeFileSync(fakeGh, '#!/bin/sh\ncase "$*" in\n "run view 123 --json conclusion,headSha,jobs") cat "$FIXTURE_GH_INFO" ;;\n "run view 123 --log") cat "$FIXTURE_GH_LOG" ;;\n *) exit 2 ;;\nesac\n');+ writeFileSync(fakeGh, '#!/bin/sh\ncase "$*" in\n "run view 123 --json conclusion,headSha,jobs") cat "$FIXTURE_GH_INFO" ;;\n "run download 123 --name timings-unit-"*) [ -f "$FIXTURE_GH_ARTIFACTS/$5.log" ] && cp "$FIXTURE_GH_ARTIFACTS/$5.log" "$7/unit.log" ;;\n *) exit 2 ;;\nesac\n');chmodSync(fakeGh, 0o755);const info = join(dir, 'run.json');- const input = join(dir, 'unit.log');const out = join(dir, 'weights.json');const meta = join(dir, 'weights.metadata.json');- const line = (job: string, text: string) => `${job}\tRun test shard\t2026-05-25T11:26:50.000Z ${text}\n`;- const complete = (job: string, file: string) => line(job, `##[group]${file}:`) + line(job, '0 fail') + line(job, 'Ran 1 test across 1 file. [1ms]');- const one = complete('test (1)', 'test/one.test.ts');+ const line = (job: string, text: string) => `${job}\tcapture\t2026-05-25T11:26:50.000Z ${text}\n`;+ const complete = (job: string, file: string) => line(job, '##[gbrain-capture-start]') + line(job, `::group::${file}:`) + line(job, '0 fail')+ + line(job, 'Ran 1 test across 1 file. [1ms]') + line(job, '##[gbrain-capture-complete] exit=0');+ const artifact = (shard: number, body: string | null) => {+ const path = join(artifacts, `timings-unit-${shard}.log`);+ if (body === null) rmSync(path, { force: true }); else writeFileSync(path, body);+ };+ artifact(1, complete('test (1)', 'test/one.test.ts'));writeFileSync(info, JSON.stringify({ conclusion: 'success', headSha: 'fixture-commit', jobs: [{ name: 'test (1)', conclusion: 'success' }, { name: 'test (2)', conclusion: 'success' }, { name: 'verify', conclusion: 'success' }] }));writeFileSync(out, '{"test/old.test.ts":42}\n');writeFileSync(meta, '{"existing":true}\n');const args = [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--run', '123', '--out', out];- const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_LOG: input };- for (const partial of [one, one + line('test (2)', 'snapshot setup started')]) {- writeFileSync(input, partial);+ const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_ARTIFACTS: artifacts };+ for (const partial of [null, line('test (2)', '##[gbrain-capture-start]') + line('test (2)', 'snapshot setup started') + line('test (2)', '##[gbrain-capture-complete] exit=0')]) {+ artifact(2, partial);expect(spawnSync(process.execPath, args, { env, encoding: 'utf8' }).status).not.toBe(0);expect(readFileSync(out, 'utf8')).toBe('{"test/old.test.ts":42}\n');expect(readFileSync(meta, 'utf8')).toBe('{"existing":true}\n');}- writeFileSync(input, one + complete('test (2)', 'test/two.test.ts'));+ artifact(2, complete('test (2)', 'test/two.test.ts'));const result = spawnSync(process.execPath, args, { env, encoding: 'utf8' });expect(result.status, result.stderr).toBe(0);expect(JSON.parse(readFileSync(out, 'utf8'))).toEqual({ 'test/one.test.ts': 0, 'test/two.test.ts': 0 });@@ -339,6 +345,43 @@ it('GitHub refresh verifies every eligible job before replacing the complete lan} finally { rmSync(dir, { recursive: true, force: true }); }});+it('GitHub unit refresh requires each shard capture artifact to record a successful completion', () => {+ const job = 'test (1)';+ const github = (text: string) => `${job}\tUNKNOWN STEP\t2026-10-10T06:00:01.000Z ${text}\n`;+ const captured = (text: string) => `${job}\tcapture\t2026-10-10T06:00:01.000Z ${text}\n`;+ const body = (line: (text: string) => string) => line('::group::test/one.test.ts:') + line(' 0 fail') + line('Ran 1 test across 1 file. [1ms]');+ const opts = { expectedJobs: [job], requireCapture: true };+ for (const raw of [body(github), body(captured), captured('##[gbrain-capture-start]') + body(captured),+ captured('##[gbrain-capture-start]') + body(captured) + captured('##[gbrain-capture-complete] exit=1')]) {+ expect(() => mineWeights(raw, 'unit', opts)).toThrow('capture completion');+ }+ expect([...mineWeights(captured('##[gbrain-capture-start]') + body(captured) + captured('##[gbrain-capture-complete] exit=0'), 'unit', opts).keys()]).toEqual(['test/one.test.ts']);+ expect(mineWeights(body(github), 'unit', { expectedJobs: [job] }).size).toBe(1);+});++it('GitHub serial refresh reads each job log by id instead of the whole-run log', () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-mine-serial-'));+ try {+ const bin = join(dir, 'bin');+ mkdirSync(bin);+ writeFileSync(join(bin, 'gh'), '#!/bin/sh\ncase "$*" in\n "run view 123 --json conclusion,headSha,jobs") cat "$FIXTURE_GH_INFO" ;;\n "run view 123 --job 77 --log") cat "$FIXTURE_GH_LOG" ;;\n *) exit 2 ;;\nesac\n', { mode: 0o755 });+ const info = join(dir, 'run.json');+ const log = join(dir, 'serial.log');+ const out = join(dir, 'weights.json');+ const job = 'serial-tests (1)';+ const line = (text: string) => `${job}\tUNKNOWN STEP\t2026-10-10T06:00:01.000Z ${text}\n`;+ writeFileSync(log, line('[serial-tests] PASS 4s test/a.serial.test.ts (1pass)') + line('[serial-tests] all 1 file(s) passed in 4s (pool=4)'));+ const args = [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--lane', 'serial', '--run', '123', '--out', out];+ const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_LOG: log };+ writeFileSync(info, JSON.stringify({ conclusion: 'success', headSha: 'fixture-commit', jobs: [{ name: job, conclusion: 'success' }] }));+ expect(spawnSync(process.execPath, args, { env, encoding: 'utf8' }).stderr).toContain('serial: missing job identity');+ writeFileSync(info, JSON.stringify({ conclusion: 'success', headSha: 'fixture-commit', jobs: [{ name: job, conclusion: 'success', databaseId: 77 }] }));+ const result = spawnSync(process.execPath, args, { env, encoding: 'utf8' });+ expect(result.status, result.stderr).toBe(0);+ expect(JSON.parse(readFileSync(out, 'utf8'))).toEqual({ 'test/a.serial.test.ts': 4 });+ } finally { rmSync(dir, { recursive: true, force: true }); }+});+it('full-profile CLI pins source, attempt and job provenance and preserves both outputs on refused evidence', () => {const dir = mkdtempSync(join(tmpdir(), 'gbrain-mine-full-'));try {