Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
regen:all regenerates every generated artifact; verify runs its read-only check
garrytan69c85066e50b
diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 90c10ef28e..1f01b6b786 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -59,6 +59,62 @@ member of `PageType`). Run `bun run typecheck` once before push, evenwhen only test files changed.+## Generated artifacts++`bun run regen:all` regenerates every generated artifact offline and keyless+(schema bundles, error-code and agent-protocol blocks, harness reference, tool+catalog, skills manifest, metric glossary, CLI flag registry, plugin tree and+persona variants, structural-suites manifest, then `llms.txt`/`llms-full.txt`+last) and lists the files it changed. Run it before pushing whenever a+freshness gate could fail; a second run changes nothing. `bun run verify`+runs the read-only half, `check:regen-all`, whose failure names each stale+artifact and the same fix. Contract goldens (export surface, CLI goldens, SQL+text) are behavior pins, so `regen:all` leaves them alone unless you pass+`--goldens`, and each changed golden needs a reason in the PR body. Goldens+that need Postgres are named in its output with their own command.++## Nightly-red issues++`.github/workflows/nightly-watch.yml` runs `scripts/nightly-issue.ts` after every+scheduled workflow and keeps one issue per workflow titled `Nightly red: <workflow>`+(label `nightly-red`). The issue body lists the failing job and step pairs, the+first red run and the commits since the last green one, the `gh workflow run`+re-check, and a "Next step for the agent" block plus a JSON block.++- **Owner:** the agent on release duty owns every open `nightly-red` issue; Garry is+ the escalation for owner-only actions (secrets, repository settings).+- **Response within 24 hours:** a repair PR, or a row in+ `.github/nightly-known-red.tsv` (job, failure signature, the owning TODOS.md entry,+ a review-by date). The file holds at most 3 rows; fix one before adding another.+ A matching cell keeps the issue open with the `known-red` label; a new failure in+ the same job opens a new incident; a passed review-by date asks for a fix again.+- **Closing:** nightly-watch closes the issue only when a later scheduled run is+ green and every previously failing job executed. A skipped job never closes it.+- **Re-check after a fix:** `gh workflow run <workflow>.yml --ref master`, then+ `gh workflow run nightly-watch.yml -f run_id=<that scheduled run id>` to preview+ (`-f dry_run=true`) or apply the issue update.+- **Dependency advisories:** pull requests block on `bun audit` only when they change+ `bun.lock`, `admin/bun.lock`, `patches/` or a package.json dependency field, or+ carry the `dependency-audit` label; pushes and the nightly run always block, so a+ new upstream advisory shows up as one red nightly instead of every open PR.++## Merge queue++`test.yml` and `e2e.yml` carry `merge_group` triggers. They are inert until the+merge queue is enabled for `master` in the repository settings; check with+`gh api repos/garrytan/gbrain/rulesets` (or the branch protection page). Queue runs use+the pull-request profile against the queued merge commit: primary native scope,+the newest Bun version only in the security and persistence matrices, the+2,500-write soak and the 10,001-page export scale; the E2E selector diffs the+queued commit against `master`.++- Without the queue, a release rebases onto the latest `origin/master` and re-runs+ the full CI (`test.yml`, `e2e.yml`, persistence-validation) immediately before+ merging, because a stale base can break master even when the PR was green.+- With the queue on, `gh pr merge` only enqueues the PR. Wait until the PR is+ actually merged (`gh pr view <n> --json state,mergedAt`) before tagging,+ announcing or starting dependent work.+## CHANGELOG + VERSION are branch-scoped**VERSION and CHANGELOG describe what THIS branch adds vs master, not how we gotdiff --git a/package.json b/package.jsonindex a91018fb95..db448989d7 100644--- a/package.json+++ b/package.json@@ -151,6 +151,8 @@"check:schema-migration-order": "bun scripts/check-schema-migration-order.ts","check:compile-autoload": "bash scripts/check-compile-autoload.sh","check:structural-manifest": "bash scripts/check-structural-manifest.sh",+ "regen:all": "bun scripts/regen-all.ts",+ "check:regen-all": "bun scripts/regen-all.ts --check","check:orphan-modules": "node scripts/check-orphan-modules.mjs","check:test-placeholders": "node scripts/check-test-placeholders.mjs","build:harness-docs": "bun run scripts/build-harness-docs.ts"diff --git a/scripts/regen-all.ts b/scripts/regen-all.tsnew file mode 100644index 0000000000..97717e949e--- /dev/null+++ b/scripts/regen-all.ts@@ -0,0 +1,154 @@+#!/usr/bin/env bun+/**+ * One entry point for every generated artifact (GBRA-47 B8; DX-14).+ *+ * bun run regen:all regenerate every artifact, print what changed+ * bun run regen:all --check read-only: run every artifact's freshness check+ * (what `bun run verify` runs as check:regen-all)+ * bun run regen:all --goldens also regenerate the offline contract goldens+ * (deliberate: justify each changed golden in the PR body)+ *+ * Offline and keyless: generators run with provider keys and database URLs+ * removed from the environment. Idempotent: a second run changes nothing.+ * Goldens that need Postgres are never regenerated here; they are named with+ * their own command. Order matters: llms.txt inlines docs other generators+ * write, so it runs last.+ *+ * Exit: 0 fresh (or regenerated), 1 --check found stale artifacts or a+ * generator failed, 2 usage error.+ */+import { existsSync, readFileSync } from 'node:fs';+import { join, resolve } from 'node:path';++export interface Artifact { name: string; regen: string[]; check: string[] }++const HARNESS_DOCS_CHECK = `import { readFileSync } from 'node:fs';+import { renderHarnessReference } from './src/core/harness/registry.ts';+if (readFileSync('docs/guides/harness-adapters.md', 'utf8') !== renderHarnessReference()) {+ console.error('docs/guides/harness-adapters.md is stale');+ process.exit(1);+}`;++export const ARTIFACTS: Artifact[] = [+ { name: 'schema (src/schema-embedded)', regen: ['bun', 'run', 'scripts/build-schema.ts'], check: ['bash', 'scripts/check-schema-fresh.sh'] },+ { name: 'schema migrations bundle', regen: ['bun', 'run', 'scripts/build-schema-migrations.ts'], check: ['bash', 'scripts/check-schema-migrations-fresh.sh'] },+ { name: 'error-code registry docs', regen: ['bun', 'scripts/build-error-codes.ts'], check: ['bun', 'scripts/build-error-codes.ts', '--check'] },+ { name: 'agent operator protocol blocks', regen: ['bun', 'scripts/build-agent-protocol.ts'], check: ['bun', 'scripts/build-agent-protocol.ts', '--check'] },+ { name: 'harness adapter reference', regen: ['bun', 'run', 'scripts/build-harness-docs.ts'], check: ['bun', '-e', HARNESS_DOCS_CHECK] },+ { name: 'MCP tool catalog', regen: ['bun', 'run', 'scripts/generate-tool-catalog.ts'], check: ['bash', 'scripts/check-tool-catalog-fresh.sh'] },+ { name: 'skills manifest', regen: ['bun', 'run', 'scripts/generate-skills-manifest.ts'], check: ['bash', 'scripts/check-skills-manifest-fresh.sh'] },+ { name: 'eval metric glossary', regen: ['bun', 'run', 'scripts/generate-metric-glossary.ts'], check: ['bash', 'scripts/check-eval-glossary-fresh.sh'] },+ { name: 'CLI flag registry', regen: ['bun', 'run', 'scripts/generate-flag-registry.ts'], check: ['bun', 'test', 'test/generate-flag-registry.test.ts'] },+ { name: 'plugin tree + persona variants', regen: ['bun', 'run', 'scripts/generate-plugin-tree.ts', '--out', 'plugin', '--variants-out', 'plugin-variants'], check: ['bash', 'scripts/check-plugin-tree.sh'] },+ { name: 'structural suites manifest', regen: ['bun', 'scripts/classify-tests.ts'], check: ['bun', 'scripts/classify-tests.ts', '--check'] },+ { name: 'llms.txt + llms-full.txt', regen: ['bun', 'run', 'scripts/build-llms.ts'], check: ['bun', 'test', 'test/build-llms.test.ts'] },+];++/** Offline contract goldens: regenerated only with --goldens, each a reviewer-visible change to justify. */+export const CONTRACT_GOLDENS = [+ 'test/export-surface-golden.test.ts',+ 'test/cli-goldens.test.ts',+ 'test/cli-dispatch-phase.test.ts',+ 'test/engine-sql-sql-text.test.ts',+];++/** Goldens that need a Postgres database; never run here. */+export const POSTGRES_GOLDENS = [+ 'GBRAIN_TEST_UPDATE_GOLDENS=1 DATABASE_URL=<test db> bun test test/e2e/schema-catalog-golden.test.ts',+ 'GBRAIN_TEST_UPDATE_GOLDENS=1 DATABASE_URL=<test db> bun test test/e2e/doctor-json-golden.test.ts',+];++const ROOT = resolve(import.meta.dir, '..');+const DOCS = 'docs/RELEASING.md#generated-artifacts';++export function offlineEnv(env: Record<string, string | undefined> = process.env): Record<string, string> {+ const out: Record<string, string> = {};+ for (const [k, v] of Object.entries(env)) {+ if (v === undefined || /_API_KEY$|_API_TOKEN$/.test(k) || k === 'DATABASE_URL' || k === 'GBRAIN_DATABASE_URL') continue;+ out[k] = v;+ }+ return out;+}++async function run(argv: string[], env: Record<string, string>): Promise<{ code: number; output: string }> {+ const child = Bun.spawn(argv, { cwd: ROOT, env, stdout: 'pipe', stderr: 'pipe' });+ const [out, err, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ return { code, output: `${out}${err}` };+}++/** Dirty paths (git status) with a content hash, so a second change to an already-dirty file still shows. */+function dirtyState(): Map<string, string> {+ const r = Bun.spawnSync(['git', 'status', '--porcelain', '--untracked-files=all'], { cwd: ROOT, stdout: 'pipe' });+ return new Map(r.stdout.toString().split('\n').filter(Boolean).map(line => {+ const path = line.slice(3).replace(/^.* -> /, '');+ const file = join(ROOT, path);+ return [path, existsSync(file) ? String(Bun.hash(readFileSync(file))) : 'deleted'];+ }));+}++/** Run every freshness check (pool of 4); returns the stale artifacts with their output tails. */+export async function checkArtifacts(artifacts: Artifact[], env = offlineEnv()): Promise<Array<{ artifact: Artifact; tail: string }>> {+ const stale: Array<{ artifact: Artifact; tail: string }> = [];+ const queue = [...artifacts];+ await Promise.all(Array.from({ length: 4 }, async () => {+ for (let a = queue.shift(); a; a = queue.shift()) {+ const r = await run(a.check, env);+ if (r.code !== 0) stale.push({ artifact: a, tail: r.output.trim().split('\n').slice(-8).join('\n') });+ }+ }));+ return artifacts.flatMap(a => stale.filter(s => s.artifact === a));+}++export function staleReport(stale: Array<{ artifact: Artifact; tail: string }>): string {+ return [+ ...stale.flatMap(({ artifact, tail }) => [`STALE ${artifact.name} (check: ${artifact.check.slice(0, 3).join(' ')}${artifact.check.length > 3 ? ' …' : ''})`, ...tail.split('\n').map(l => ` | ${l}`)]),+ `regen:all --check: ${stale.length} generated artifact(s) stale: ${stale.map(s => s.artifact.name).join(', ')}`,+ 'Why: a committed artifact no longer matches its generator, so CI fails the freshness gate.',+ 'Fix: bun run regen:all (then commit the changed files it lists)',+ `Docs: ${DOCS}`,+ ].join('\n');+}++if (import.meta.main) {+ const args = process.argv.slice(2);+ const unknown = args.filter(a => a !== '--check' && a !== '--goldens');+ if (unknown.length || (args.includes('--check') && args.includes('--goldens'))) {+ console.log('Usage: bun run regen:all [--check | --goldens]');+ process.exit(2);+ }+ const env = offlineEnv();+ if (args.includes('--check')) {+ const stale = await checkArtifacts(ARTIFACTS, env);+ if (stale.length) {+ console.log(staleReport(stale));+ process.exit(1);+ }+ console.log(`regen:all --check: all ${ARTIFACTS.length} generated artifacts fresh.`);+ process.exit(0);+ }++ const before = dirtyState();+ const steps = [...ARTIFACTS.map(a => ({ name: a.name, argv: a.regen, env })),+ ...(args.includes('--goldens') ? CONTRACT_GOLDENS.map(f => ({ name: `golden ${f}`, argv: ['bun', 'test', f], env: { ...env, GBRAIN_TEST_UPDATE_GOLDENS: '1' } })) : [])];+ const llms = steps.findIndex(s => s.name.startsWith('llms'));+ steps.push(...steps.splice(llms, 1));+ for (const step of steps) {+ const r = await run(step.argv, step.env);+ if (r.code !== 0) {+ console.log(r.output.trim().split('\n').slice(-20).join('\n'));+ console.log(`regen:all: FAILED at ${step.name} (${step.argv.join(' ')}, exit ${r.code}).`);+ console.log(`Fix: run that command directly, fix what it reports, then rerun bun run regen:all. Docs: ${DOCS}`);+ process.exit(1);+ }+ console.log(`regen:all: ${step.name} ok`);+ }+ const changed = [...dirtyState()].filter(([p, h]) => before.get(p) !== h).map(([p]) => p);+ console.log(changed.length+ ? `regen:all: ${changed.length} file(s) changed; commit them:\n${changed.map(p => ` ${p}`).join('\n')}`+ : 'regen:all: every generated artifact was already fresh; nothing changed.');+ if (args.includes('--goldens') && changed.some(p => p.includes('test/fixtures/goldens/'))) {+ console.log('Changed contract goldens are reviewer-visible behavior changes: justify each in the PR body.');+ }+ console.log(`Not regenerated here (need Postgres):\n${POSTGRES_GOLDENS.map(c => ` ${c}`).join('\n')}`);+ if (!args.includes('--goldens')) console.log(`Contract goldens (deliberate): bun run regen:all --goldens regenerates ${CONTRACT_GOLDENS.join(', ')}.`);+}diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex ef451d1f6d..17b85685bf 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -157,6 +157,9 @@ CHECKS=("check:retired-phrases""check:schema-migration-order""check:structural-manifest"+ # Every generated artifact's freshness in one place (GBRA-47 B8); its Fix+ # line is `bun run regen:all`, the same code path that regenerates them.+ "check:regen-all"# v0.50.5.0 security wave: compiled binaries must not autoload a cwd bunfig.toml."check:compile-autoload")@@ -317,6 +320,7 @@ if [ "$FAIL" -gt 0 ]; thenecho "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"printf '%s' "$FAIL_REPORT"echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"+ echo "Generated artifact, golden or manifest drift? Run: bun run regen:all (offline, keyless; prints what changed)."echo "[verify-parallel] elapsed=${ELAPSED}s | pass=$PASS fail=$FAIL"} >&2exit 1diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 7cae9abb04..ef492a0883 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -267,7 +267,7 @@ test/scripts/ci-local-rendering.test.ts ci-local execution coverage 3 readFileSytest/scripts/ci-local-rendering.test.ts local test configuration through run-e2e 2 readFileSynctest/scripts/ci-local-rendering.test.ts required PgBouncer execution through run-e2e 1 readFileSynctest/scripts/ci-manifest-diff.test.ts test.yml dependency-audit scope 2 readFileSync-test/scripts/ci-pr-scope.test.ts pull-request CI scope 8 readFileSync+test/scripts/ci-pr-scope.test.ts pull-request CI scope 9 readFileSynctest/scripts/ci-runner-routing.test.ts CI runner routing 6 readFileSynctest/scripts/classify-tests.test.ts classify-tests detectors 23 bun-file,doctor-source-helper,exec-scan,readFileSync,source-surface-helpertest/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSync@@ -283,6 +283,7 @@ test/scripts/native-lock-prebuilds.test.ts native lock distribution integrity 2test/scripts/nightly-e2e.test.ts nightly E2E scheduling 4 readFileSynctest/scripts/nightly-issue.test.ts .github/nightly-known-red.tsv 2 readFileSynctest/scripts/nightly-issue.test.ts nightly-watch incidents 9 readFileSync+test/scripts/regen-all.test.ts regen:all 4 readFileSynctest/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSynctest/scripts/test-shard.slow.test.ts test-shard.sh — LPT balance contract 5 readFileSynctest/scripts/test-shard.slow.test.ts test-shard.sh — exclusion contract 7 readFileSyncdiff --git a/test/scripts/nightly-issue.test.ts b/test/scripts/nightly-issue.test.tsindex 5b3098cd6d..c81cced1eb 100644--- a/test/scripts/nightly-issue.test.ts+++ b/test/scripts/nightly-issue.test.ts@@ -206,6 +206,7 @@ describe('.github/nightly-known-red.tsv', () => {test('the committed file is valid: at most 3 rows, ISO review-by dates, each TODO present in TODOS.md', () => {expect(validateKnownRed(readFileSync(join(ROOT, '.github/nightly-known-red.tsv'), 'utf8'), todos)).toEqual([]);+ expect(readFileSync(join(ROOT, 'docs/RELEASING.md'), 'utf8')).toContain('\n## Nightly-red issues\n');});test('a fourth row, a bad date, an unknown kind or a missing TODO is refused with the fix', () => {diff --git a/test/scripts/regen-all.test.ts b/test/scripts/regen-all.test.tsnew file mode 100644index 0000000000..1cb4c13a46--- /dev/null+++ b/test/scripts/regen-all.test.ts@@ -0,0 +1,55 @@+/**+ * scripts/regen-all.ts (GBRA-47 B8, DX-14): one table drives both the+ * regeneration and the read-only check verify runs; a stale artifact is named+ * with the fix; generators run offline and keyless; Postgres goldens are+ * excluded and named.+ */+import { describe, expect, test } from 'bun:test';+import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { ARTIFACTS, CONTRACT_GOLDENS, POSTGRES_GOLDENS, checkArtifacts, offlineEnv, staleReport, type Artifact } from '../../scripts/regen-all.ts';++const ROOT = join(import.meta.dir, '../..');++describe('regen:all', () => {+ test('--check names each stale artifact and prints Why/Fix/Docs; fresh ones pass', async () => {+ const fake: Artifact[] = [+ { name: 'fresh artifact', regen: ['true'], check: ['true'] },+ { name: 'drifted artifact', regen: ['true'], check: ['bash', '-c', 'echo "fixture.json differs from its generator"; exit 1'] },+ ];+ const stale = await checkArtifacts(fake, offlineEnv());+ expect(stale.map(s => s.artifact.name)).toEqual(['drifted artifact']);+ const report = staleReport(stale);+ expect(report).toContain('STALE drifted artifact');+ expect(report).toContain(' | fixture.json differs from its generator');+ expect(report).toContain('Fix: bun run regen:all');+ expect(report).toContain('Docs: docs/RELEASING.md#generated-artifacts');+ expect(readFileSync(join(ROOT, 'docs/RELEASING.md'), 'utf8')).toContain('## Generated artifacts');+ });++ test('every generator and check names a script or test that exists, and llms is regenerated last', () => {+ for (const a of ARTIFACTS) {+ for (const argv of [a.regen, a.check]) {+ const path = argv.find(x => /^(scripts|test)\//.test(x));+ if (path) expect(existsSync(join(ROOT, path)), `${a.name}: ${path}`).toBe(true);+ }+ }+ expect(ARTIFACTS.at(-1)!.name).toContain('llms');+ for (const f of CONTRACT_GOLDENS) expect(existsSync(join(ROOT, f)), f).toBe(true);+ for (const c of POSTGRES_GOLDENS) expect(existsSync(join(ROOT, /bun test (\S+)/.exec(c)![1]!)), c).toBe(true);+ });++ test('generators run without provider keys or database URLs', () => {+ const env = offlineEnv({ PATH: '/bin', OPENAI_API_KEY: 'k', UBICLOUD_API_TOKEN: 't', DATABASE_URL: 'postgres://x', GBRAIN_DATABASE_URL: 'y', HOME: '/h' });+ expect(env).toEqual({ PATH: '/bin', HOME: '/h' });+ });++ test('verify runs check:regen-all and its failure hint names regen:all', () => {+ const verify = readFileSync(join(ROOT, 'scripts/run-verify-parallel.sh'), 'utf8');+ expect(verify).toContain('"check:regen-all"');+ expect(verify).toContain('Run: bun run regen:all');+ const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')) as { scripts: Record<string, string> };+ expect(pkg.scripts['check:regen-all']).toBe('bun scripts/regen-all.ts --check');+ expect(pkg.scripts['regen:all']).toBe('bun scripts/regen-all.ts');+ });+});