Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

ci(scale): scale-tier workflow (paths/label/nightly, pglite+postgres on Ubicloud, corpus-only cache) and trend.ts (F4c)

garrytan934a65cd2ed0
diff --git a/.github/workflows/scale-tier.yml b/.github/workflows/scale-tier.yml
new file mode 100644
index 0000000000..26cd61b519
--- /dev/null
+++ b/.github/workflows/scale-tier.yml
@@ -0,0 +1,195 @@
+name: Scale tier
+
+# F4c scale tier (docs/TESTING.md "Scale tier"; gate shape and cadence: O-CEO-16 /
+# O-ENG-16 / O-CEO-9). Runs scripts/scale/run.ts --enforce on PGLite and Postgres.
+#
+# When it runs (one rule):
+# - pull requests that touch the paths below, or carry the `scale-tier` label: 10k;
+# - nightly: 10k + 20k until the import-rate gate has passed at 20k on five
+# consecutive nights, then 50k (scripts/scale/trend.ts decides from the last
+# five nightly reports);
+# - workflow_dispatch: the size you pass.
+#
+# Enforced from day one: import rate, known answers, no-op re-import, no
+# duplicates across sources, phase timers. Planner health is report-only until
+# F4b (PLANNER_HEALTH_ENFORCED in scripts/scale/gates.ts). Interactive ceilings
+# and calibrated budgets stay report-only until `bun scripts/scale/trend.ts`
+# prints "ceilings stable" and a reviewer sets the repo variable
+# GBRAIN_SCALE_ENFORCE_CEILINGS=1.
+#
+# Only the generated Markdown corpus is cached; an imported database never is,
+# so every run measures a real import.
+
+on:
+ # The paths filter lives in the plan job so the `scale-tier` label can also
+ # select a pull request that touches none of these paths.
+ pull_request:
+ branches: [master]
+ types: [opened, synchronize, reopened, labeled]
+ schedule:
+ - cron: '41 8 * * *'
+ workflow_dispatch:
+ inputs:
+ pages:
+ description: Brain size in pages (10000, 20000 or 50000)
+ type: string
+ default: '10000'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event_name == 'schedule' && '-nightly' || '' }}
+ cancel-in-progress: true
+
+jobs:
+ plan:
+ runs-on: ubicloud-standard-2-ubuntu-2404
+ timeout-minutes: 10
+ permissions:
+ contents: read
+ pull-requests: read
+ actions: read
+ outputs:
+ run: ${{ steps.plan.outputs.run }}
+ pages: ${{ steps.plan.outputs.pages }}
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ sparse-checkout: scripts/scale
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ if: github.event_name == 'schedule'
+ with:
+ bun-version: 1.4.2
+ - id: plan
+ env:
+ GH_TOKEN: ${{ github.token }}
+ EVENT: ${{ github.event_name }}
+ ACTION: ${{ github.event.action }}
+ ADDED_LABEL: ${{ github.event.label.name }}
+ PR_LABELS: ${{ toJSON(github.event.pull_request.labels.*.name) }}
+ PR: ${{ github.event.pull_request.number }}
+ REPO: ${{ github.repository }}
+ CHANGED_FILES: ${{ github.event.pull_request.changed_files }}
+ PAGES_INPUT: ${{ inputs.pages }}
+ run: |
+ set -euo pipefail
+ # Spec 5.4 paths: engine SQL, search, import, sync, doctor, both engines,
+ # schema and migrations, the harness itself (and this workflow).
+ paths='^(src/core/engine-sql/|src/core/search/|src/core/import-file\.ts$|src/commands/import\.ts$|src/commands/sync/|src/core/sync[^/]*\.ts$|src/core/persistence/sync-[^/]*\.ts$|src/commands/doctor/|src/core/pglite-engine\.ts$|src/core/postgres-engine\.ts$|src/schema\.sql$|src/core/schema-migrations/|scripts/scale/|\.github/workflows/scale-tier\.yml$)'
+ run=false
+ pages='[10000]'
+ case "$EVENT" in
+ workflow_dispatch)
+ if ! [[ "$PAGES_INPUT" =~ ^[0-9]+$ ]] || [ "$PAGES_INPUT" -lt 20 ]; then
+ echo "::error::pages must be an integer >= 20, got '$PAGES_INPUT'. Re-run with e.g. pages=10000."
+ exit 1
+ fi
+ run=true
+ pages="[$PAGES_INPUT]"
+ ;;
+ schedule)
+ run=true
+ plan=$(bun scripts/scale/trend.ts --json) || plan='{}'
+ echo "trend: $plan"
+ pages=$(printf '%s' "$plan" | jq -c '.tiers // [10000,20000]')
+ ;;
+ pull_request)
+ if [ "$ACTION" = labeled ]; then
+ # Only the scale-tier label itself starts a run; other labels never do.
+ [ "$ADDED_LABEL" = scale-tier ] && run=true
+ elif printf '%s' "$PR_LABELS" | jq -e 'index("scale-tier") != null' >/dev/null; then
+ run=true
+ elif ! [[ "$CHANGED_FILES" =~ ^[0-9]{1,4}$ ]] || [ "$CHANGED_FILES" -ge 3000 ]; then
+ # The PR files API returns at most 3000 files; an unknown diff runs the tier.
+ run=true
+ elif files=$(gh api --paginate "repos/$REPO/pulls/$PR/files?per_page=100" --jq '.[].filename'); then
+ if printf '%s\n' "$files" | grep -Eq "$paths"; then run=true; fi
+ else
+ run=true
+ fi
+ ;;
+ esac
+ echo "scale tier: run=$run pages=$pages"
+ echo "run=$run" >> "$GITHUB_OUTPUT"
+ echo "pages=$pages" >> "$GITHUB_OUTPUT"
+
+ scale:
+ needs: plan
+ if: needs.plan.outputs.run == 'true'
+ name: scale ${{ matrix.engine }} ${{ matrix.pages }}
+ strategy:
+ fail-fast: false
+ matrix:
+ engine: [pglite, postgres]
+ pages: ${{ fromJSON(needs.plan.outputs.pages) }}
+ runs-on: ubicloud-standard-8-ubuntu-2404
+ # Backstop only: the harness phase timers fail first, naming the phase
+ # (10k <= 20 min, 50k <= 100 min per engine).
+ timeout-minutes: ${{ matrix.pages > 20000 && 130 || 50 }}
+ services:
+ postgres:
+ # An empty image skips the service on the PGLite cell.
+ image: ${{ matrix.engine == 'postgres' && 'pgvector/pgvector:pg16' || '' }}
+ # Loopback-only throwaway server: trust auth, so no password literal is needed.
+ env:
+ POSTGRES_USER: postgres
+ POSTGRES_HOST_AUTH_METHOD: trust
+ POSTGRES_DB: gbrain_test
+ ports:
+ - 5432:5432
+ options: >-
+ --health-cmd pg_isready
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ env:
+ SCALE_SEED: '1'
+ CORPUS_DIR: .context/scale-corpus/${{ matrix.pages }}-seed1
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.4.2
+ - uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: ~/.bun/install/cache
+ key: bun-cache-${{ runner.os }}-${{ hashFiles('bun.lock') }}
+ restore-keys: bun-cache-${{ runner.os }}-
+ - run: bun install --frozen-lockfile
+ # The generated Markdown corpus only (O-CEO-9): never an imported database.
+ - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
+ with:
+ path: ${{ env.CORPUS_DIR }}
+ key: scale-corpus-${{ hashFiles('scripts/scale/fixture.ts') }}-${{ matrix.pages }}-${{ env.SCALE_SEED }}
+ - name: Scale tier (${{ matrix.engine }}, ${{ matrix.pages }} pages, enforce)
+ env:
+ DATABASE_URL: ${{ matrix.engine == 'postgres' && 'postgresql://postgres@localhost:5432/gbrain_test' || '' }}
+ GBRAIN_SCALE_ENFORCE_CEILINGS: ${{ vars.GBRAIN_SCALE_ENFORCE_CEILINGS }}
+ ENGINE: ${{ matrix.engine }}
+ PAGES: ${{ matrix.pages }}
+ run: |
+ bun run test:scale -- --engine "$ENGINE" --pages "$PAGES" --seed "$SCALE_SEED" \
+ --corpus-dir "$CORPUS_DIR" --out ".context/scale/report-$ENGINE-$PAGES-seed$SCALE_SEED.json" --enforce
+ - name: Summary
+ if: always()
+ env:
+ REPORT: .context/scale/report-${{ matrix.engine }}-${{ matrix.pages }}-seed1.json
+ run: |
+ if [ ! -f "$REPORT" ]; then
+ echo "No report: the harness crashed before writing one; see the step log." >> "$GITHUB_STEP_SUMMARY"
+ exit 0
+ fi
+ jq -r '"### " + .headline.metric + ": " + (.headline.p50_ms|tostring) + " ms (" + .engine + ")",
+ "",
+ "| gate | status | enforced | message |", "|---|---|---|---|",
+ (.gates[] | select(.status == "fail" or (.gate|startswith("ceiling") or startswith("import_rate") or startswith("phase"))) |
+ "| " + .gate + " | " + .status + " | " + (.enforced|tostring) + " | " + (.message|gsub("\\|"; "/")) + " |"),
+ "", "Reproduce: `" + .reproduce + "`"' "$REPORT" >> "$GITHUB_STEP_SUMMARY"
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ if: always()
+ with:
+ name: scale-report-${{ matrix.engine }}-${{ matrix.pages }}
+ path: .context/scale/
+ retention-days: 30
+ if-no-files-found: warn
diff --git a/scripts/scale/trend.ts b/scripts/scale/trend.ts
new file mode 100644
index 0000000000..49bfa30a4e
--- /dev/null
+++ b/scripts/scale/trend.ts
@@ -0,0 +1,158 @@
+#!/usr/bin/env bun
+/**
+ * Scale-tier trend reader (F4c; O-CEO-9 / O-CEO-16). Read-only.
+ *
+ * bun scripts/scale/trend.ts [--runs 5] [--dir <reports-dir>] [--json]
+ *
+ * Fetches the scale reports of the last N completed nightly runs of
+ * .github/workflows/scale-tier.yml (`gh run list` + `gh run download`, so a
+ * read-only GITHUB_TOKEN / GH_TOKEN with actions:read is enough), or reads
+ * <reports-dir>/<run-id>/**.json when --dir is given, and answers two
+ * questions:
+ *
+ * 1. Are the interactive ceilings and calibrated budgets stable? Prints
+ * "ceilings stable" when N >= 5 nightly runs each have every engine/size
+ * under every ceiling and budget, with a coefficient of variation <= 15%
+ * per metric. Enforcement then flips with the repo variable
+ * GBRAIN_SCALE_ENFORCE_CEILINGS=1, a reviewed human step.
+ * 2. Which sizes run tonight (the one cadence rule)? 10k + 20k nightly until
+ * the import-rate gate has passed at 20k on five consecutive nights, then
+ * 50k nightly (sticky: once the latest night ran 50k it stays there).
+ *
+ * Exit 0 whatever the verdict (it is advice; the workflow reads --json);
+ * exit 2 on a usage error.
+ */
+import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { ceilingsFor } from './gates.ts';
+
+export const STABLE_RUNS = 5;
+export const CV_MAX = 0.15;
+export const DEFAULT_TIERS = [10_000, 20_000];
+export const PROMOTED_TIERS = [50_000];
+
+export interface TrendReport {
+ engine: string;
+ pages: number;
+ ops: Array<{ op: string; p50_ms: number }>;
+ budgets_ms?: Record<string, number>;
+ gates?: Array<{ gate: string; status: 'pass' | 'fail' }>;
+}
+/** One nightly run: its id and every scale report it uploaded. Newest run first. */
+export interface TrendRun { id: string; reports: TrendReport[] }
+
+const cv = (xs: number[]) => {
+ const mean = xs.reduce((a, b) => a + b, 0) / xs.length;
+ if (mean === 0) return 0;
+ return Math.sqrt(xs.reduce((a, b) => a + (b - mean) ** 2, 0) / xs.length) / mean;
+};
+
+export function assessCeilings(runs: TrendRun[]): { stable: boolean; lines: string[] } {
+ const window = runs.slice(0, STABLE_RUNS);
+ if (window.length < STABLE_RUNS) {
+ return { stable: false, lines: [`only ${window.length} nightly run(s) with scale reports; ceilings need ${STABLE_RUNS} consecutive stable runs before enforcement.`] };
+ }
+ const groups = new Set(window.flatMap(r => r.reports.map(rep => `${rep.engine}:${rep.pages}`)));
+ const lines: string[] = [];
+ let stable = groups.size > 0;
+ for (const group of [...groups].sort()) {
+ const series = window.map(r => r.reports.find(rep => `${rep.engine}:${rep.pages}` === group));
+ if (series.some(s => !s)) {
+ stable = false;
+ lines.push(`${group}: missing from ${series.filter(s => !s).length} of the last ${STABLE_RUNS} nightly runs; not stable.`);
+ continue;
+ }
+ const reports = series as TrendReport[];
+ const limits: Record<string, number> = { ...ceilingsFor(reports[0]!.pages) };
+ for (const [op, budget] of Object.entries(reports[0]!.budgets_ms ?? {})) limits[op] = Math.min(limits[op] ?? Infinity, budget);
+ for (const [op, limit] of Object.entries(limits)) {
+ const values = reports.map(rep => rep.ops.find(o => o.op === op)?.p50_ms);
+ if (values.some(v => v === undefined)) continue;
+ const xs = values as number[];
+ const over = xs.filter(v => v > limit).length;
+ const variation = cv(xs);
+ const ok = over === 0 && variation <= CV_MAX;
+ if (!ok) stable = false;
+ lines.push(`${group} ${op}: p50 ${xs.join('/')} ms vs limit ${limit} ms; ${over} over; CV ${Math.round(variation * 100)}% (max ${CV_MAX * 100}%) -> ${ok ? 'stable' : 'not stable'}`);
+ }
+ }
+ lines.push(stable
+ ? 'ceilings stable: a reviewer may set the repo variable GBRAIN_SCALE_ENFORCE_CEILINGS=1 (gh variable set GBRAIN_SCALE_ENFORCE_CEILINGS --body 1).'
+ : 'ceilings not stable yet: keep them report-only.');
+ return { stable, lines };
+}
+
+export function nightlyTiers(runs: TrendRun[]): { tiers: number[]; reason: string } {
+ if (runs[0]?.reports.some(r => r.pages >= PROMOTED_TIERS[0]!)) return { tiers: PROMOTED_TIERS, reason: 'the latest nightly run already ran 50k (promotion is sticky)' };
+ const window = runs.slice(0, STABLE_RUNS);
+ const ratePassedAt20k = (run: TrendRun) => {
+ const at20k = run.reports.filter(r => r.pages === 20_000);
+ return at20k.length > 0 && at20k.every(r => r.gates?.find(g => g.gate === 'import_rate')?.status === 'pass');
+ };
+ if (window.length === STABLE_RUNS && window.every(ratePassedAt20k)) {
+ return { tiers: PROMOTED_TIERS, reason: `the import-rate gate passed at 20k on the last ${STABLE_RUNS} nights` };
+ }
+ return { tiers: DEFAULT_TIERS, reason: `the import-rate gate has passed at 20k on ${window.filter(ratePassedAt20k).length} of the last ${STABLE_RUNS} nights (needs ${STABLE_RUNS})` };
+}
+
+function reportsUnder(dir: string): TrendReport[] {
+ const found: TrendReport[] = [];
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) { found.push(...reportsUnder(path)); continue; }
+ if (!name.endsWith('.json')) continue;
+ try {
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as TrendReport & { harness?: string };
+ if (parsed.harness === 'gbrain-scale') found.push(parsed);
+ } catch { /* not a scale report */ }
+ }
+ return found;
+}
+
+function gh(args: string[]): string {
+ const r = Bun.spawnSync(['gh', ...args], { stdout: 'pipe', stderr: 'pipe' });
+ if (r.exitCode !== 0) throw new Error(`gh ${args.join(' ')} failed: ${r.stderr.toString().trim()}`);
+ return r.stdout.toString();
+}
+
+function fetchRuns(count: number): TrendRun[] {
+ const listed = JSON.parse(gh(['run', 'list', '--workflow', 'scale-tier.yml', '--event', 'schedule', '--status', 'completed',
+ '--limit', String(count), '--json', 'databaseId'])) as Array<{ databaseId: number }>;
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-scale-trend-'));
+ return listed.map(({ databaseId }) => {
+ const dir = join(root, String(databaseId));
+ try { gh(['run', 'download', String(databaseId), '--pattern', 'scale-report-*', '--dir', dir]); } catch { /* a run with no reports counts as empty */ }
+ return { id: String(databaseId), reports: existsSync(dir) ? reportsUnder(dir) : [] };
+ });
+}
+
+if (import.meta.main) {
+ const flag = (name: string) => { const i = process.argv.indexOf(name); return i >= 0 ? process.argv[i + 1] : undefined; };
+ const count = Number(flag('--runs') ?? STABLE_RUNS);
+ if (!Number.isInteger(count) || count < 1) {
+ console.log('Usage: bun scripts/scale/trend.ts [--runs <N>=5] [--dir <reports-dir>] [--json]');
+ process.exit(2);
+ }
+ const dir = flag('--dir');
+ let runs: TrendRun[] = [];
+ let fetchError: string | undefined;
+ try {
+ runs = dir
+ ? readdirSync(dir).filter(n => statSync(join(dir, n)).isDirectory()).sort().reverse().slice(0, count).map(id => ({ id, reports: reportsUnder(join(dir, id)) }))
+ : fetchRuns(count);
+ } catch (e) {
+ fetchError = `could not read nightly reports (${e instanceof Error ? e.message : String(e)}); treating history as empty. `
+ + 'Check that gh is authenticated (GH_TOKEN with actions:read) and that scale-tier.yml has completed nightly runs.';
+ }
+ const ceilings = assessCeilings(runs);
+ const cadence = nightlyTiers(runs);
+ if (process.argv.includes('--json')) {
+ console.log(JSON.stringify({ runs: runs.map(r => ({ id: r.id, reports: r.reports.length })), ceilings, tiers: cadence.tiers, cadence_reason: cadence.reason, ...(fetchError ? { warning: fetchError } : {}) }));
+ } else {
+ if (fetchError) console.log(`[trend] ${fetchError}`);
+ console.log(`[trend] ${runs.length} nightly run(s): ${runs.map(r => `${r.id} (${r.reports.length} reports)`).join(', ') || 'none'}`);
+ for (const line of ceilings.lines) console.log(`[trend] ${line}`);
+ console.log(`[trend] tonight's sizes: ${cadence.tiers.join(', ')} (${cadence.reason})`);
+ }
+}
diff --git a/test/scripts/scale-trend.test.ts b/test/scripts/scale-trend.test.ts
new file mode 100644
index 0000000000..90deee26dc
--- /dev/null
+++ b/test/scripts/scale-trend.test.ts
@@ -0,0 +1,46 @@
+/**
+ * scripts/scale/trend.ts decides two things the scale-tier workflow acts on:
+ * whether the report-only ceilings may be enforced ("ceilings stable") and
+ * which brain sizes the nightly run uses (10k + 20k until the import-rate gate
+ * passes at 20k five nights in a row, then 50k). Both read only the reports.
+ */
+import { expect, test } from 'bun:test';
+import { assessCeilings, nightlyTiers, type TrendReport, type TrendRun } from '../../scripts/scale/trend.ts';
+
+const report = (engine: string, pages: number, search: number, health: number, rate: 'pass' | 'fail' = 'pass'): TrendReport => ({
+ engine, pages,
+ ops: [{ op: 'search (MCP path, remote)', p50_ms: search }, { op: 'get_health', p50_ms: health }],
+ gates: [{ gate: 'import_rate', status: rate }],
+});
+const runs = (n: number, make: (i: number) => TrendReport[]): TrendRun[] => Array.from({ length: n }, (_, i) => ({ id: String(100 - i), reports: make(i) }));
+
+test('five steady nights under every ceiling read "ceilings stable"', () => {
+ const verdict = assessCeilings(runs(5, i => [report('pglite', 10_000, 200 + i, 400), report('postgres', 10_000, 100, 300 + i)]));
+ expect(verdict.stable).toBe(true);
+ expect(verdict.lines.at(-1)).toContain('ceilings stable');
+ expect(verdict.lines.at(-1)).toContain('GBRAIN_SCALE_ENFORCE_CEILINGS=1');
+});
+
+test('fewer than five nights, one night over a ceiling, or a noisy metric is not stable', () => {
+ expect(assessCeilings(runs(4, () => [report('pglite', 10_000, 200, 400)])).stable).toBe(false);
+ const over = assessCeilings(runs(5, i => [report('pglite', 10_000, i === 2 ? 501 : 200, 400)]));
+ expect(over.stable).toBe(false);
+ expect(over.lines.find(l => l.includes('search (MCP path, remote)'))).toContain('1 over');
+ const noisy = assessCeilings(runs(5, i => [report('pglite', 10_000, [100, 400, 100, 400, 100][i]!, 400)]));
+ expect(noisy.stable).toBe(false);
+ expect(noisy.lines.find(l => l.includes('search (MCP path, remote)'))).toContain('not stable');
+});
+
+test('calibrated budgets in the reports are judged with the ceilings', () => {
+ const withBudget = () => [{ ...report('pglite', 10_000, 200, 400), budgets_ms: { 'search (MCP path, remote)': 150 } }];
+ expect(assessCeilings(runs(5, withBudget)).stable).toBe(false);
+});
+
+test('nightly sizes: 10k + 20k until the 20k rate gate passes five nights in a row, then 50k, sticky', () => {
+ expect(nightlyTiers([]).tiers).toEqual([10_000, 20_000]);
+ const passing = runs(5, () => [report('pglite', 20_000, 1, 1), report('postgres', 20_000, 1, 1)]);
+ expect(nightlyTiers(passing).tiers).toEqual([50_000]);
+ const oneFailed = runs(5, i => [report('pglite', 20_000, 1, 1, i === 3 ? 'fail' : 'pass'), report('postgres', 20_000, 1, 1)]);
+ expect(nightlyTiers(oneFailed)).toMatchObject({ tiers: [10_000, 20_000], reason: expect.stringContaining('4 of the last 5') });
+ expect(nightlyTiers(runs(1, () => [report('pglite', 50_000, 1, 1)])).tiers).toEqual([50_000]);
+});