Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
ci(GBRA-47 D8): run unit-lane PostgreSQL arms and guard that every arm has a lane
garrytan16da42bfbf22
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.ymlindex 4623f21cc2..2eaf7c85c0 100644--- a/.github/workflows/persistence-validation.yml+++ b/.github/workflows/persistence-validation.yml@@ -160,6 +160,113 @@ jobs:path: .context/persistence-runtime-matrix.jsonif-no-files-found: error+ # Unit-lane suites whose PostgreSQL arm is gated on DATABASE_URL: the unit,+ # serial and slow lanes unset it, so these arms run only here (both arms per+ # file; the PGLite arm also runs in the unit lane). scripts/check-postgres-lane-coverage.ts+ # fails a new DATABASE_URL-gated arm until it is listed here or wrapped in a+ # test/e2e registerPostgresTests file. The two shards are balanced by measured runtime.+ unit-postgres-arms:+ name: Unit-lane PostgreSQL arms ${{ matrix.shard }}/2 / Bun ${{ matrix.bun }}+ runs-on: ubicloud-standard-4-ubuntu-2404+ timeout-minutes: 30+ strategy:+ fail-fast: false+ matrix:+ shard: [1, 2]+ bun: ['1.4.0', '1.4.2']+ # Pull requests run the primary Bun version; pushes, schedules and+ # manual runs keep every supported version.+ exclude: ${{ fromJSON(github.event_name == 'pull_request' && '[{"bun":"1.4.0"}]' || '[]') }}+ services:+ postgres:+ image: pgvector/pgvector:pg16+ env:+ POSTGRES_USER: gbrain_test+ POSTGRES_PASSWORD: gbrain_test+ POSTGRES_DB: gbrain_test+ ports: ['5432:5432']+ options: >-+ --health-cmd "pg_isready -U gbrain_test -d gbrain_test"+ --health-interval 5s --health-timeout 5s --health-retries 20+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6+ with:+ bun-version: ${{ matrix.bun }}+ - run: bun install --frozen-lockfile --ignore-scripts+ - name: Require PostgreSQL arms of unit-lane suites+ timeout-minutes: 20+ shell: bash+ env:+ DATABASE_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ SHARD: ${{ matrix.shard }}+ run: |+ : "${DATABASE_URL:?unit-lane PostgreSQL arms require the explicit test database}"+ case "$SHARD" in+ 1) files=(+ test/colon-slug-windows-5032.test.ts+ test/decide/conflict-proposals-managed.serial.test.ts+ test/declared-lineage-visibility.test.ts+ test/extract-endpoint-revision.serial.test.ts+ test/grandfather-managed.test.ts+ test/harness-skills-epoch.test.ts+ test/links-attendance-blocked.test.ts+ test/managed-cycle-pull-upstream.test.ts+ test/managed-maintenance-links.test.ts+ test/managed-sync-drain.test.ts+ test/pack-relation-direction-engine.test.ts+ test/page-state-engine.test.ts+ test/persistence-commit-durability.test.ts+ test/persistence-deactivate.test.ts+ test/persistence-file-import.test.ts+ test/persistence-graph-publication.test.ts+ test/persistence-managed-lifecycle.test.ts+ test/persistence-managed-sync.test.ts+ test/persistence-memory-mutations.test.ts+ test/persistence-page-authority.test.ts+ test/persistence-skill-bundles.serial.test.ts+ test/shared-content-freshness.test.ts+ test/shared-skills-writer-boundary.serial.test.ts+ test/source-retire-missing-checkout.test.ts+ test/sync-legacy-holds.test.ts+ test/takes-vector-lifecycle-5885.serial.test.ts+ test/withdrawal-overlay-concurrency.test.ts+ ) ;;+ 2) files=(+ test/alias-source-cascade-5094.test.ts+ test/company-brain-policy.test.ts+ test/company-brain-runtime.test.ts+ test/derived-link-reconciliation.test.ts+ test/doctor-frontmatter-holds.test.ts+ test/embedding-completion-atomic.serial.test.ts+ test/held-read-signals.test.ts+ test/import-frontmatter-key-order-5158.test.ts+ test/import-revision-concurrency.test.ts+ test/managed-sweep-corpus-windows.test.ts+ test/managed-sync-bulk.test.ts+ test/managed-sync-chunker-version.test.ts+ test/persistence-diagnostics.test.ts+ test/persistence-git-subdir-origin.test.ts+ test/persistence-image-import.serial.test.ts+ test/persistence-physical-root-device.test.ts+ test/persistence-skill-crash.slow.test.ts+ test/persistence-sync-cursor-options.test.ts+ test/persistence-sync-holds.test.ts+ test/persistence-writer-fences.test.ts+ test/repair-embedding-effects.test.ts+ test/repair-frontmatter.test.ts+ test/shared-skills-catalog.test.ts+ test/shared-skills-retention-capacity.test.ts+ test/stats-health-source-scope.test.ts+ test/sync-frontmatter-recovery.test.ts+ test/sync-frontmatter-slug-conflict.test.ts+ test/withdrawal-publication-file.test.ts+ ) ;;+ *) echo "::error::unknown shard $SHARD" >&2; exit 1 ;;+ esac+ bun --no-env-file test --timeout=120000 "${files[@]}"+invariants:name: ${{ matrix.engine }} / Bun ${{ matrix.bun }}# The soak uses 1.3-1.8 busy cores: the 2,500-write PGLite soak took 523s ondiff --git a/scripts/check-postgres-lane-coverage.ts b/scripts/check-postgres-lane-coverage.tsnew file mode 100644index 0000000000..e2361be48b--- /dev/null+++ b/scripts/check-postgres-lane-coverage.ts@@ -0,0 +1,191 @@+#!/usr/bin/env bun+/**+ * Postgres-arm lane guard (GBRA-47 D8; docs/TESTING.md#coverage-responsibilities-before-consolidation).+ *+ * The unit, serial and slow lanes unset DATABASE_URL, so a test file whose+ * PostgreSQL arm is gated on it runs that arm only where a Postgres lane names+ * the file. This guard fails on every test/ file outside test/e2e/ that has+ * such an arm and no Postgres lane:+ *+ * - arm: a zero-argument `testBackends()` call, or a `process.env.DATABASE_URL`+ * read (directly or through a variable that holds it) used as a condition,+ * a call or constructor argument, or a `database_url`/`databaseUrl`+ * property value. Code inside a `withEnv({ DATABASE_URL: ... })` callback+ * supplies its own URL and is not an arm.+ * - lane: a workflow step that runs with DATABASE_URL (step, job or workflow+ * env, or exported in its script) and names the file; a test/e2e/ file that+ * imports it (the registerPostgresTests wrappers); a tests/heavy/ script+ * that names it (the heavy job runs with DATABASE_URL); or a row in+ * scripts/e2e-backend-matrix.txt.+ *+ * An arm that is deliberately not run yet is an ALLOWLIST row naming its+ * reason and TODO; a row for a file that is laned, has no arm or is gone fails.+ *+ * Seam: GBRAIN_GUARD_ROOT (fixture tree root).+ */+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { dirname, join, relative, resolve } from 'node:path';+import { safeLoad } from 'js-yaml';+import ts from 'typescript';++const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');+const DOCS = 'docs/TESTING.md#coverage-responsibilities-before-consolidation';+const LANE = '.github/workflows/persistence-validation.yml';+const LANE_STEP = 'Require PostgreSQL arms of unit-lane suites';++/** Arms deliberately left out of every Postgres lane. Each row names its reason and TODO. */+const ALLOWLIST: Record<string, string> = {+ 'test/export-scale.slow.test.ts': 'the 100,001-page Postgres arm passes but takes ~9 minutes; no lane has that budget yet (TODOS: give the export-scale Postgres arm a scheduled lane)',+};++function files(dir: string, keep: (name: string) => boolean): string[] {+ if (!existsSync(dir)) return [];+ const out: string[] = [];+ for (const entry of readdirSync(dir).sort()) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) out.push(...files(full, keep));+ else if (keep(entry)) out.push(full);+ }+ return out;+}+const rel = (abs: string) => relative(ROOT, abs).replace(/\\/g, '/');+const TEST_PATH = /\btest\/[A-Za-z0-9_./-]+\.test\.ts\b/g;++function isDatabaseUrlRead(node: ts.Node): boolean {+ const env = (e: ts.Expression) => ts.isPropertyAccessExpression(e) && e.name.text === 'env'+ && ts.isIdentifier(e.expression) && e.expression.text === 'process';+ if (ts.isPropertyAccessExpression(node)) return node.name.text === 'DATABASE_URL' && env(node.expression);+ if (ts.isElementAccessExpression(node)) return ts.isStringLiteralLike(node.argumentExpression)+ && node.argumentExpression.text === 'DATABASE_URL' && env(node.expression);+ return false;+}++/** How a value flows from `node`: 'gate' (condition, argument, connection URL), a variable name it initializes, or null. */+function use(node: ts.Node): 'gate' | { alias: string } | null {+ let child: ts.Node = node;+ for (let parent = node.parent; parent; child = parent, parent = parent.parent) {+ if (ts.isParenthesizedExpression(parent) || ts.isNonNullExpression(parent) || ts.isAsExpression(parent)+ || ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken) continue;+ if (ts.isConditionalExpression(parent)) { if (parent.condition === child) return 'gate'; continue; }+ if (ts.isBinaryExpression(parent)) {+ const op = parent.operatorToken.kind;+ return op === ts.SyntaxKind.AmpersandAmpersandToken || op === ts.SyntaxKind.BarBarToken ? 'gate' : null;+ }+ if (ts.isIfStatement(parent) || ts.isWhileStatement(parent)) return parent.expression === child ? 'gate' : null;+ if (ts.isCallExpression(parent)) {+ if (parent.expression === child) return null;+ const callee = parent.expression;+ return ts.isIdentifier(callee) && callee.text === 'expect' ? null : 'gate';+ }+ if (ts.isNewExpression(parent)) return parent.expression === child ? null : 'gate';+ if (ts.isPropertyAssignment(parent)) {+ const name = ts.isIdentifier(parent.name) || ts.isStringLiteralLike(parent.name) ? parent.name.text : '';+ return ['database_url', 'databaseUrl'].includes(name) ? 'gate' : null;+ }+ if (ts.isVariableDeclaration(parent)) return ts.isIdentifier(parent.name) ? { alias: parent.name.text } : null;+ return null;+ }+ return null;+}++/** Inside a `withEnv({ DATABASE_URL: ... }, ...)` callback the file supplies the URL itself, so nothing gates on the lane. */+function underOwnDatabaseUrl(node: ts.Node): boolean {+ for (let parent = node.parent; parent; parent = parent.parent) {+ if (ts.isCallExpression(parent) && ts.isIdentifier(parent.expression) && parent.expression.text === 'withEnv') {+ const env = parent.arguments[0];+ if (env && ts.isObjectLiteralExpression(env) && env.properties.some(p => p.name && (ts.isIdentifier(p.name) || ts.isStringLiteralLike(p.name)) && p.name.text === 'DATABASE_URL')) return true;+ }+ }+ return false;+}++/** First line of a Postgres arm in `path`, or null. */+function postgresArm(path: string): { line: number; what: string } | null {+ const sf = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ const line = (n: ts.Node) => sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1;+ const aliases = new Set<string>();+ const found: Array<{ line: number; what: string }> = [];+ const reads: ts.Node[] = [];+ const visit = (node: ts.Node): void => {+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'testBackends' && node.arguments.length === 0+ && !underOwnDatabaseUrl(node)) {+ found.push({ line: line(node), what: 'testBackends()' });+ }+ if (isDatabaseUrlRead(node) && !underOwnDatabaseUrl(node)) reads.push(node);+ ts.forEachChild(node, visit);+ };+ visit(sf);+ for (const read of reads) {+ const flow = use(read);+ if (flow === 'gate') found.push({ line: line(read), what: 'process.env.DATABASE_URL' });+ else if (flow) aliases.add(flow.alias);+ }+ if (aliases.size) {+ const refs = (node: ts.Node): void => {+ if (ts.isIdentifier(node) && aliases.has(node.text) && !(ts.isVariableDeclaration(node.parent) && node.parent.name === node)+ && use(node) === 'gate') found.push({ line: line(node), what: `${node.text} (holds process.env.DATABASE_URL)` });+ ts.forEachChild(node, refs);+ };+ refs(sf);+ }+ return found.sort((a, b) => a.line - b.line)[0] ?? null;+}++/** Test files a Postgres lane runs, with where each is named. */+function postgresLanes(): Map<string, string> {+ const laned = new Map<string, string>();+ const add = (path: string, lane: string) => { if (!laned.has(path)) laned.set(path, lane); };+ for (const workflow of files(join(ROOT, '.github', 'workflows'), name => /\.ya?ml$/.test(name))) {+ const doc = safeLoad(readFileSync(workflow, 'utf8')) as { env?: Record<string, unknown>; jobs?: Record<string, { env?: Record<string, unknown>; steps?: Array<{ name?: string; env?: Record<string, unknown>; run?: string }> }> } | undefined;+ for (const [jobName, job] of Object.entries(doc?.jobs ?? {})) for (const step of job.steps ?? []) {+ const run = String(step.run ?? '');+ if (!(step.env?.DATABASE_URL || job.env?.DATABASE_URL || doc?.env?.DATABASE_URL || /\bDATABASE_URL=/.test(run))) continue;+ for (const [path] of run.matchAll(TEST_PATH)) add(path, `${rel(workflow)} › ${jobName} › ${step.name ?? 'run'}`);+ }+ }+ for (const wrapper of files(join(ROOT, 'test', 'e2e'), name => name.endsWith('.test.ts'))) {+ for (const [, spec] of readFileSync(wrapper, 'utf8').matchAll(/(?:\bimport\s*\(\s*|\bfrom\s+)['"](\.{1,2}\/[^'"]+\.test\.ts)['"]/g)) {+ add(rel(resolve(dirname(wrapper), spec)), rel(wrapper));+ }+ }+ for (const script of files(join(ROOT, 'tests', 'heavy'), name => name.endsWith('.sh'))) {+ for (const [path] of readFileSync(script, 'utf8').matchAll(TEST_PATH)) add(path, rel(script));+ }+ const matrix = join(ROOT, 'scripts', 'e2e-backend-matrix.txt');+ if (existsSync(matrix)) for (const row of readFileSync(matrix, 'utf8').split('\n')) {+ if (row && !row.startsWith('#') && !row.startsWith('!')) add(row.split('\t')[0], 'scripts/e2e-backend-matrix.txt');+ }+ return laned;+}++const laned = postgresLanes();+const failures: string[] = [];+const armed = new Set<string>();+for (const abs of files(join(ROOT, 'test'), name => name.endsWith('.test.ts'))) {+ const path = rel(abs);+ if (path.startsWith('test/e2e/')) continue;+ const arm = postgresArm(abs);+ if (!arm) continue;+ armed.add(path);+ if (laned.has(path) || ALLOWLIST[path]) continue;+ failures.push(`FAIL [postgres_arm_unlaned]: ${path}:${arm.line} gates a PostgreSQL arm on DATABASE_URL (${arm.what}) and no Postgres lane runs it\n`+ + ` Why: the unit, serial and slow lanes unset DATABASE_URL, so this arm skips in every CI lane.\n`+ + ` Fix: add ${path} to the "${LANE_STEP}" list in ${LANE} (or load it from a test/e2e/*-postgres.test.ts wrapper with registerPostgresTests)\n`+ + ` Docs: ${DOCS}`);+}+for (const [path, reason] of Object.entries(ALLOWLIST)) {+ const problem = !existsSync(join(ROOT, path)) ? 'names a missing file'+ : !armed.has(path) ? 'names a file with no DATABASE_URL-gated arm'+ : laned.has(path) ? `names a file a Postgres lane already runs (${laned.get(path)})` : null;+ if (!problem) continue;+ failures.push(`FAIL [postgres_arm_allowlist_stale]: the ALLOWLIST row for ${path} ${problem} (reason was: ${reason})\n`+ + ` Why: a stale row would hide the next arm added to that path.\n`+ + ` Fix: delete the ${path} row from ALLOWLIST in scripts/check-postgres-lane-coverage.ts\n`+ + ` Docs: ${DOCS}`);+}+if (failures.length) {+ console.error(failures.join('\n'));+ console.error(`\n${failures.length} Postgres-arm lane problem(s).`);+ process.exit(1);+}+console.log(`postgres-lane-coverage: ${armed.size} test files with a DATABASE_URL-gated arm; ${armed.size - Object.keys(ALLOWLIST).length} run in a Postgres lane, ${Object.keys(ALLOWLIST).length} allowlisted.`);diff --git a/test/scripts/postgres-lane-coverage.test.ts b/test/scripts/postgres-lane-coverage.test.tsnew file mode 100644index 0000000000..229f67d5a4--- /dev/null+++ b/test/scripts/postgres-lane-coverage.test.ts@@ -0,0 +1,89 @@+/**+ * GBRA-47 D8: scripts/check-postgres-lane-coverage.ts fails on a test file+ * outside test/e2e/ whose PostgreSQL arm is gated on DATABASE_URL and that no+ * Postgres lane runs, and passes once a lane names it.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++const REPO = resolve(import.meta.dir, '..', '..');+const GUARD = join(REPO, 'scripts', 'check-postgres-lane-coverage.ts');+const ALLOWLISTED = { 'test/export-scale.slow.test.ts': "for (const backend of testBackends()) describe(backend, () => {});\n" };+const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function run(files: Record<string, string>) {+ const tree = mkdtempSync(join(tmpdir(), 'gbrain-postgres-lanes-'));+ dirs.push(tree);+ for (const [rel, body] of Object.entries({ ...ALLOWLISTED, ...files })) {+ mkdirSync(join(tree, rel, '..'), { recursive: true });+ writeFileSync(join(tree, rel), body);+ }+ const r = spawnSync(process.execPath, [GUARD], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: tree } });+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };+}+const workflow = (env: string, files: string[]) => `name: lane\non: workflow_dispatch\njobs:\n pg:\n runs-on: ubuntu-latest\n steps:\n - name: Postgres arms\n${env} run: bun test ${files.join(' ')}\n`;+const PG_ENV = ' env:\n DATABASE_URL: postgres://u:[email protected]:5432/gbrain_test\n';++describe('check-postgres-lane-coverage.ts', () => {+ test.each([+ ['a testBackends() loop', "for (const backend of testBackends()) describe(backend, () => {});\n"],+ ['a skipIf on DATABASE_URL', "test.skipIf(!process.env.DATABASE_URL)('postgres arm', () => {});\n"],+ ['a variable holding DATABASE_URL', "const url = process.env.DATABASE_URL;\ndescribe.skipIf(!url)('postgres arm', () => {});\n"],+ ['an if-gated connection', "beforeAll(async () => { if (process.env.DATABASE_URL) await isolatedPersistencePostgres(process.env.DATABASE_URL); });\n"],+ ])('%s with no Postgres lane fails with code, location, why, the exact fix and docs', (_label, body) => {+ const r = run({ 'test/arm.test.ts': body });+ expect(r.code).toBe(1);+ expect(r.out).toContain('FAIL [postgres_arm_unlaned]: test/arm.test.ts:');+ expect(r.out).toContain('Why: the unit, serial and slow lanes unset DATABASE_URL, so this arm skips in every CI lane.');+ expect(r.out).toContain('Fix: add test/arm.test.ts to the "Require PostgreSQL arms of unit-lane suites" list in .github/workflows/persistence-validation.yml');+ expect(r.out).toContain('Docs: docs/TESTING.md#coverage-responsibilities-before-consolidation');+ });++ test('a workflow step without DATABASE_URL is not a Postgres lane', () => {+ const r = run({ 'test/arm.test.ts': ALLOWLISTED['test/export-scale.slow.test.ts'],+ '.github/workflows/lane.yml': workflow('', ['test/arm.test.ts']) });+ expect(r.code).toBe(1);+ expect(r.out).toContain('FAIL [postgres_arm_unlaned]: test/arm.test.ts:1');+ });++ test('arms named by a DATABASE_URL workflow step, an e2e wrapper or a heavy script pass', () => {+ const arm = ALLOWLISTED['test/export-scale.slow.test.ts'];+ const r = run({+ 'test/stepped.test.ts': arm, 'test/wrapped.serial.test.ts': arm, 'test/heavy.test.ts': arm,+ '.github/workflows/lane.yml': workflow(PG_ENV, ['test/stepped.test.ts']),+ 'test/e2e/wrapped-postgres.test.ts': "await registerPostgresTests(() => import('../wrapped.serial.test.ts'));\n",+ 'tests/heavy/arm.sh': 'bun test test/heavy.test.ts\n',+ });+ expect(r.code, r.out).toBe(0);+ expect(r.out).toContain('4 test files with a DATABASE_URL-gated arm; 3 run in a Postgres lane, 1 allowlisted.');+ });++ test('save-and-restore reads, assertions and a self-supplied DATABASE_URL are not arms', () => {+ const r = run({+ 'test/restore.test.ts': "const prev = process.env.DATABASE_URL;\ndelete process.env.DATABASE_URL;\nif (prev !== undefined) process.env.DATABASE_URL = prev;\nexpect(process.env.DATABASE_URL).toBeUndefined();\n",+ 'test/own-url.test.ts': "test('helper', () => withEnv({ DATABASE_URL: 'postgresql://localhost/gbrain_test' }, () => { expect(testBackends()).toEqual(['pglite', 'postgres']); }));\n",+ 'test/strings.test.ts': "const fixture = `await engine.connect({ database_url: process.env.DATABASE_URL });`;\n",+ });+ expect(r.code, r.out).toBe(0);+ });++ test('an allowlist row for a laned file is stale and names the row to delete', () => {+ const r = run({ '.github/workflows/lane.yml': workflow(PG_ENV, ['test/export-scale.slow.test.ts']) });+ expect(r.code).toBe(1);+ expect(r.out).toContain('FAIL [postgres_arm_allowlist_stale]: the ALLOWLIST row for test/export-scale.slow.test.ts names a file a Postgres lane already runs');+ expect(r.out).toContain('Fix: delete the test/export-scale.slow.test.ts row from ALLOWLIST in scripts/check-postgres-lane-coverage.ts');+ });++ test('every DATABASE_URL-gated arm in this repository runs in a Postgres lane or is allowlisted', () => {+ const r = spawnSync(process.execPath, [GUARD], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: REPO } });+ expect(r.status, `${r.stdout}\n${r.stderr}`).toBe(0);+ });++ test('the docs anchor the guard prints exists', () => {+ expect(readFileSync(join(REPO, 'docs', 'TESTING.md'), 'utf8')).toContain('### Coverage responsibilities before consolidation');+ });+});