Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Test Plan
Generated by /plan-eng-review (autoplan Phase 3, primary Eng voice) on 2026-09-29 Branch: refactor/wave-1 (planned; baseline master @ 608a174, v0.60.10.0) Repo: garrytan/gbrain
Scope: behavior-preserving structural refactor (W0 gates, W5 function-size ratchet, W3 migrations split, W2 generated schema text, W1 engine-sql executor + domains, W4 god-function decomposition, W6 landing, W7 contributor DX). Every item below protects an existing contract; nothing here approves new behavior.
Affected Pages/Routes
gbrain --help,gbrain --tools-json,gbrain <unknown>— CLI command table replaces the 62-case switch; output, exit codes and flag validation must be byte-identical to master goldens.- Every CLI-only command (111
CLI_ONLYmembers) — dispatch phase (pre-connect engine-free vs post-connect) and thin-client handling (none / refuse / route-then-refuse) must equal master. gbrain status,gbrain db-repair,gbrain pglite-repair,gbrain bootstrap,gbrain hook— engine-free commands must still answer with the database unreachable.gbrain sources writer|reconcile|add|...,gbrain takes add|update|supersede|resolve,gbrain capture|forget|call— subcommand-level routing to the deferred persistence delegate must be unchanged.gbrain doctor(--json,--fast,--fix --dry-run,--scope=brain,--source <id>) on PGLite, Postgres and one degraded config — ordered check names, categories, statuses and normalized JSON identical.gbrain sync(full, incremental, working-tree, resume from checkpoint, timeout, stall) — phase breadcrumbs, checkpoint contents and result counts identical.gbrain serve --http:/mcp(GET/POST),/token,/register,/revoke,/authorize, legacy PRM path,/.well-known/gbrain,/health,/admin/login,/admin/api/issue-magic-link,/admin/auth/:token,/metrics,/admin/api/*(19 routes),/admin/events,/adminstatic + SPA fallback — global middleware order, per-route middleware chain and auth outcomes identical.gbrain init/ any engine connect on PGLite and Postgres (direct and PgBouncer) — schema bootstrap, blob replay and migrations reach the identical catalog on fresh AND existing brains.gbrain search/gbrain query/ MCPsearch,query— hybrid ranked(id, score)identical, cold and warm cache.gbrain jobs work/ supervisor probe (cut-line) — 24 handlers registered in the same order;registerBuiltinHandlersimportable fromsrc/commands/jobs.ts.
Key Interactions to Verify
- Store write inside
engine.transaction()that then throws is rolled back, on PGLite and Postgres (engine-sql executor resolves the connection per call). - A read that was RLS-scoped on master (23
withScopedReadTransactionsites) still bindsapp.scopeswithGBRAIN_RLS_SCOPE_BINDING=1; a read that was NOT scoped on master still runs on the pool with no transaction. - Repeated engine-sql call on direct Postgres reuses a named prepared statement; on PgBouncer transaction mode it does not; zero-parameter queries never use the simple protocol.
- Driver errors (23505, 57014, deadlock via
isDeadlockError) reach callers with the same class,.codeand message through the executor on PGLite, direct Postgres and PgBouncer. - Abort signal forwarded only where the engine forwarded it on master; cancellation settles before the connection is reused.
- Existing PGLite brain created by master, opened by the branch:
initSchemareplays the generated blob and migrations without error and the catalog equals master's. - Duplicate migration version after rebase: generator fails naming both files with the
git mvrecipe. - Dropping
requireAdminfrom any route in anyserve-http-*.tsmodule fails the admin-route guard with that module file:line. - New command added through the table: accepted flag passes, unknown flag rejected,
--helpworks without an engine. - Sync phase await vs stall watchdog, and phase await vs timeout, in both completion orders: abort observed, checkpoint reflects only committed work.
Edge Cases
- Empty array params (
setEmotionalWeightBatch([])returns 0) on both engines through the executor. Value: protects=empty-array binding returns today's result; fails_when=adapter binds [] as NULL or text '{}' differently per engine; why_new=no executor exists on master; seam=none - bigint > 2^53, Date with timezone, JSONB object and array, text[]/int[]/real[], vector literal, null, boolean bound through the executor (E5 matrix), both engines. Value: protects=parameter encoding parity for every declared kind; fails_when=postgres.js infers a different type via unsafe() or JSONB double-encodes; why_new=tagged templates hid inference differences; seam=none
- Row count from UPDATE/DELETE: Postgres
.countvs PGLite.affectedRowsnormalized to oneaffectedRowsfield. Value: protects=boolean/number results of facts/takes/code-edges write methods; fails_when=adapter drops count on one engine and methods return 0/false; why_new=per-engine modules read different fields today (facts.ts:128 vs :123); seam=none - Previously inlined SQL literals (vector literal in
postgres-engine/facts.ts:489, decay-map LIKE prefixes and coefficients frombuildRecencyComponentSql) remain inlined text, not bound params. Value: protects=query plans and HNSW index use on hot search paths; fails_when=conversion binds them as $N and the planner switches to a generic plan; why_new=SQL-text golden did not exist per domain; seam=none - Dynamic SQL scanner: a raw string interpolated into engine-sql SQL fails; a vetted fragment builder call and a Number.isFinite-checked numeric pass.
Value: protects=no injection path introduced by tagged-to-positional conversion; fails_when=scanner allowlist accepts any
${}or rejects the vetted builders; why_new=new directory, no scanner covers it; seam=none - Migration registry: filename
v176-add-x.tswithversion: 177inside; duplicate v176 across two files; file missing from generated registry; gaps 17-19 and 100 preserved. Value: protects=schema_version history and apply order; fails_when=generator silently sorts or drops a file; why_new=registry is new; seam=none - Snapshot hash: removing any module in the transitive import closure of the PGLite schema, the migration registry or the engine-sql bootstrap from the hash list fails a test naming the file and all 11 CI key homes. Value: protects=unit suite never runs on a stale PGLite snapshot; fails_when=bootstrap moves to engine-sql and is not hashed; why_new=today's list omits pglite-engine.ts where the bootstrap lives; seam=none
- Doctor with null engine, with a connection failure, and with
--fast: early-stop behavior and partial check list identical. Value: protects=doctor's DB-down contract and smoke-test branch fields; fails_when=registry runner keeps running entries after STOP or drops the synthesized connection check; why_new=registry runner is new; seam=none - Function-size guard: arrow function assigned to a property, object-literal method, class property initializer, anonymous route handler over 300 lines each fail; shifting a baselined function down 10 lines leaves the baseline untouched. Value: protects=ratchet cannot be bypassed by syntax form; fails_when=guard counts declarations only; why_new=guard is new; seam=none
- Command table: every
loadis an arrow returningimport('<string literal>'). Value: protects=compiled binary bundles every command module; fails_when=a computed specifier is added and bun --compile omits the module; why_new=switch cases were literal by construction; seam=none - PGLite master-vs-branch catalog comparison includes column ordinal positions.
Value: protects=
SELECT *consumers and snapshot contents after the generated bootstrap reorders DDL; fails_when=generator emits columns in ALTER order; why_new=schema-diff compares by column name only; seam=none
Critical Paths
- Fresh install on PGLite, direct Postgres and PgBouncer reaches the master catalog (E4: columns incl. ordinal on PGLite, defaults, indexes, constraints incl. CHECK text, triggers, function signature+body hash, views). Value: protects=schema end state after W2/W3 generation and split; fails_when=generated blob or registry differs from master; why_new=schema-drift compares columns+indexes only; seam=none
- Existing PGLite brain upgrade: master-built data dir opened by branch,
initSchemacompletes, catalog unchanged, second boot is a no-op. Value: protects=every existing PGLite user's first boot after upgrade; fails_when=regenerated blob adds a forward reference or non-idempotent ALTER; why_new=E4 covers fresh installs only; seam=none - Existing Postgres brain at an older schema_version applies pending migrations from the split registry and reaches the E4 catalog. Value: protects=migration apply order and handler behavior after W3; fails_when=registry drops or reorders a migration; why_new=migrations golden checks content, not apply; seam=none
- Engine transaction atomicity through engine-sql on both engines (write + throw -> rollback; reads outside see nothing). Value: protects=transaction() semantics for every migrated write; fails_when=executor is cached on the instance and bound to the pool; why_new=no test drives a peeled-module write inside transaction(); seam=none
- RLS scoping status per read method preserved with GBRAIN_RLS_SCOPE_BINDING=1 (e2e asserts
current_setting('app.scopes')inside scoped reads, and no BEGIN for unscoped reads). Value: protects=RLS layer-2 defense and the #1794 no-per-read-pool-hold rule; fails_when=a migrated read loses or gains the scoped transaction; why_new=fake-sql unit pins only the helper, not each migrated read; seam=none - Engine parity suite (28 parity/drift files) and source-isolation matrix pass unchanged after each W1 domain commit, on PGLite, direct Postgres and PgBouncer. Value: protects=storage behavior parity; fails_when=a converted query changes semantics on one engine; why_new=existing owner, run per domain commit; seam=none
- CLI goldens: help, tools-json, unknown command, per-command dispatch phase, thin-client refusal and subcommand routing matrix, generated flag registry and TOOL_CATALOG byte-identical. Value: protects=public CLI contract; fails_when=table record omits phase/thin-client mode or generator loses a flag; why_new=no golden of dispatch phase exists; seam=none
- serve-http route table golden (method, path, ordered middleware identities, global app.use order, SPA fallthrough) plus authenticated outcome tests for OAuth preflight/CORS order and admin 401/200. Value: protects=auth and CORS order across the module split; fails_when=a mount call moves or a module omits requireAdmin; why_new=admin guard scans serve-http.ts text only; seam=none
- Doctor normalized
--jsongoldens on PGLite, Postgres and degraded config; registry order equals master's AST-extracted check-name order. Value: protects=doctor output contract used by smoke tests and agents; fails_when=registry reorders or drops a check; why_new=no ordered-name golden exists; seam=none - Hybrid search deterministic golden (stub embedder, seeded PGLite, fixed config), exact
(id, score), cold and warm (hybridSearchCached). Value: protects=retrieval quality unchanged; fails_when=stage extraction changes ordering or float math; why_new=existing hybrid tests assert properties, not exact output; seam=none - Sync controlled-order tests (phase await vs watchdog, phase await vs timeout, both orders) using a latch-wrapped BrainEngine and fake timers. Value: protects=no stale snapshot of mutable sync state across awaits; fails_when=a phase destructures run fields; why_new=closure lets made this implicit; seam=none
- Perf budgets: searchVector, searchKeyword, _upsertChunksOnce, getPage, hybrid warm/cold, import throughput, SQL round trips per op,
gbrain --versioncold start and PGLite engine connect cold start, each within noise / +20 ms. Value: protects=no latency regression from prepare/simple/Describe or 170-module load; fails_when=adapter drops prepare or adds round trips; why_new=no before/after budget exists; seam=none
Tests to Retire
- none (behavior-preserving; ~133 source-text tests are re-pointed through per-surface loaders, never deleted or loosened)
Pending Decisions
- UC1 (CEO user challenge): W1 breadth (W1-core 5 domains + E1 vs also the 7 W1-extended domains). Test requirements for W1-extended domains apply only to domains the owner includes.
- Cut-line items (jobs, hybrid, autopilot): their golden tests (24-handler order, hybrid golden, autopilot dispatch) apply only if those functions land in this PR.