Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
32.6 KB
Raw Blame

Key files: Entrypoints And Docs

Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • .agents/gbrain-launcher — shared plugin MCP launcher (sh, Unix-only) for the Codex, Claude Code, and OpenClaw (openclaw.plugin.json mcpServers.gbrain) lanes: GBRAIN_BIN → ~/.bun/bin/gbrain → PATH resolution, one stderr resolution line, GBRAIN_SURFACE substitute-or-append override for serve argv, actionable exit-127 recovery copy, no auto-install by design. hook … exits 0 silently on a miss (no per-turn error on plugin-first installs), and with GBRAIN_HOOK_LANE=plugin also when the CLI predates the plugin lane (PLUGIN_LANE_MIN; one --version probe per binary, verdict cached in .gbrain/cache/plugin-hook-cli while newer than the binary). Behavioral branches all pinned in the manifest test.

  • .claude-plugin/plugin.json + .claude-plugin/marketplace.json — the Claude Code plugin lane: inline MCP declaration (command/args/cwd via ${CLAUDE_PLUGIN_ROOT}; no env block — Claude passes the parent env through); the Claude marketplace carries the full plugin PLUS the persona variant entries (gbrain-coding/gbrain-daily → plugin-variants/), while the codex marketplace intentionally stays single-entry until codex's multi-entry handling gets its observation run — variant names are pinned to skills/plugin-lanes.json#personas by test/codex-plugin-manifest.test.ts.

  • .codex-plugin/plugin.json + .codex-plugin/mcp.json + .agents/plugins/marketplace.json — the Codex plugin lane: manifest (skills → the committed plugin/ tree; mcpServers → the NON-root mcp.json), the MCP declaration (serve --surface starter --source-guard, code-derived env_vars passthrough), and the codex-native marketplace. Version lockstep with package.json + the claude/openclaw manifests pinned by test/codex-plugin-manifest.test.ts.

  • AGENTS.md — Local-clone entry point for non-Claude agents (Codex, Cursor, OpenClaw, Aider). Mirrors CLAUDE.md intent via relative links. Claude Code keeps using CLAUDE.md.

  • admin/ — React 19 + Vite + TypeScript admin SPA embedded in the binary via admin/dist/ served by serve-http.ts. Views: Login (bootstrap token or single-use link → session cookie, preserving pending OAuth consent), Dashboard (metrics + SSE feed + token health), Agents (client table + registration), Register (machine/public PKCE/confidential PKCE with permission preview), Client Setup (method-aware instructions + explicit recoverable private download), Request Log (filterable paginated), Agent Detail drawer (setup, permission review, request activity, and token invalidation/revocation/deletion). Design tokens: #0a0a0f bg, Inter for UI, JetBrains Mono for data, 4-32px spacing scale, rounded pill badges. HTTP-only SameSite=Strict cookie auth. About 79KiB gzip for JS/CSS assets. Build: cd admin && bun install && bun run build; output at admin/dist/ is committed for self-contained binaries.

  • docker-compose.ci.yml + scripts/ci-local.sh — Local CI gate. bun run ci:local spins up four pgvector/pgvector:pg16 services (postgres-1..4) + oven/bun:${GBRAIN_CI_BUN_TAG:-1.4.4} with named volumes (gbrain-ci-pg-data-{1..4}, gbrain-ci-node-modules, gbrain-ci-admin-node-modules, gbrain-ci-admin-dist, gbrain-ci-bun-cache; #6756: the runner mounts the worktree's admin/dist read-only at /ci-src/admin-dist and scripts/ci-hydrate-admin-dist.sh makes the gbrain-ci-admin-dist volume an exact copy of it, stale hashed files removed, before bun run build, refusing only when a file git ls-files admin/dist tracks cannot be read from the worktree (the message names the file and bun run build:admin); pinned by test/scripts/ci-hydrate-admin-dist.test.ts), runs gitleaks on host, smoke-tests scripts/run-e2e.sh argv handling, runs the authoritative bun run verify once plus the explicit Bun test-timeout guard, then the complete serial and slow lanes before 4-shard parallel unit + E2E (xargs -P4, one Postgres per shard; unit phase keeps DATABASE_URL unset). --no-shard runs unit/E2E sequentially (debug aid); --diff narrows E2E selection without changing the chosen shard mode. The doc-only --diff fast path runs only the host secrets scans. Also runs a pgbouncer service (edoburu/pgbouncer, POOL_MODE: transaction, AUTH_TYPE: plain — pg16 stores SCRAM verifiers, so the userlist must hold the plaintext password; IGNORE_STARTUP_PARAMETERS whitelists gbrain's statement_timeout/idle_in_transaction_session_timeout startup params the way the Supabase pooler does) fronting postgres-1 on host port GBRAIN_CI_PGBOUNCER_PORT (default 6543); every E2E invocation exports GBRAIN_PGBOUNCER_URL (pooled; dedicated gbrain_pgbouncer_test database so it never races the gbrain_test TRUNCATE fixtures) + GBRAIN_PGBOUNCER_DIRECT_URL, consumed by test/e2e/pgbouncer-teardown.test.ts — which reproduces the transaction-mode teardown failure in the local gate. --no-pull skips upstream pulls; --clean nukes named volumes. Postgres host port defaults to 5434; override with GBRAIN_CI_PG_PORT=NNNN. Full persistence and native runtime matrices run separately; see docs/TESTING.md.

  • docs/UPGRADING_DOWNSTREAM_AGENTS.md — Patches for downstream agent skill forks to apply when upgrading. Each release appends a new section; includes diffs for brain-ops, meeting-ingestion, signal-detector, enrich.

  • docs/architecture/RETRIEVAL.md + docs/incidents/RETRIEVAL_MAXPOOL_INCIDENT.md — retrieval-pipeline architecture reference + the named-thing-miss incident write-up (root cause, the five-layer fix, the eval that pins it).

  • docs/architecture/infra-layer.md — Shared infrastructure documentation

  • docs/designs/HOMEBREW_FOR_PERSONAL_AI.md — 10-star vision for integration system

  • docs/ethos/MARKDOWN_SKILLS_AS_RECIPES.md — "Homebrew for Personal AI" essay

  • docs/ethos/THIN_HARNESS_FAT_SKILLS.md — Architecture philosophy essay

  • docs/eval-bench.md — contributor guide for using captured data to benchmark retrieval changes before merging. Linked from CONTRIBUTING.md under "Running real-world eval benchmarks (touching retrieval code)".

  • docs/eval-capture.md — stable NDJSON schema reference for gbrain-evals consumers.

  • docs/guides/ — Individual SKILLPACK guides (broken out from monolith)

  • docs/guides/diligence-ingestion.md — Data room to brain pages pipeline

  • docs/guides/idea-capture.md — Originality distribution, depth test, cross-linking

  • docs/guides/quiet-hours.md — Notification hold + timezone-aware delivery

  • docs/guides/repo-architecture.md — Two-repo pattern (agent vs brain)

  • docs/guides/skill-development.md — 5-step skill development cycle + MECE

  • docs/guides/sub-agent-routing.md — Model routing table for sub-agents

  • docs/integrations/ — "Getting Data In" guides and integration docs

  • docs/mcp/ — Per-client setup guides (Claude Desktop, Code, Cowork, Perplexity)

  • BrainBench retrieval benchmark (P@5/R@5 corpus + harness): lives in the separate gbrain-evals repo. Not installed alongside gbrain. Distinct from the in-repo cross-harness memory conformance suite (gbrain eval brainbench — src/eval/brainbench/, corpus at evals/brainbench/, methodology in docs/eval/BRAINBENCH.md).

  • docs/operations/conversation-parser-llm-fallback.md — operator and maintainer contract for the default-off LLM parse fallback: exact config key, deterministic-first dispatch boundary, sampled data surface, untrusted-content prompt handling, page-date/cache-key coupling, timestamp validation, cache/checkpoint behavior, observability, limitations, and focused test commands.

  • docs/progress-events.md — Canonical JSON event schema reference. Additive only.

  • docs/protocol/MCP_META_CHANNELS.md — normative _meta conventions for MCP tool responses: one producer per top-level key, additive-forever within a key, producer isolation, and the registered-keys table (brain_hot_memory, retrieval, warnings). Anything the model must SEE rides a content block (mainstream harnesses don't feed _meta to the model); _meta serves structured consumers. Add a key by registering it in the table — one producer, additive-forever.

  • gbrain.yml (brain repo root) — Optional storage tiering config. Top-level storage: section with db_tracked: and db_only: array-valued keys. gbrain sync auto-manages .gitignore for db_only paths on successful sync (skips on dry-run, blocked-by-failures, submodule context, or GBRAIN_NO_GITIGNORE=1). gbrain export --restore-only [--repo P] [--type T] [--slug-prefix S] repopulates missing db_only files from the database.

  • openclaw.plugin.json — ClawHub bundle manifest with installed/slot ID gbrain-context-engine, kind: context-engine, declared legacy/current engine contracts, valid config JSON Schema and root-level sensitive UI hints for database URL and API key. The gbrain-context registration alias does not make an old slot setting valid on current hosts. See docs/mcp/OPENCLAW.md.

  • recipes/ — Integration recipe files (YAML frontmatter + markdown setup instructions)

  • skills/RESOLVER.md — Skill routing table (based on the agent-fork AGENTS.md pattern) with skills/manifest.json: schema-author wired into the dispatcher with the full functional-area trigger list (compressed routing pattern per the dispatcher convention).

  • skills/_brain-filing-rules.md — Cross-cutting brain filing rules (referenced by all brain-writing skills)

  • skills/_friction-protocol.md — shared cross-cutting convention skill (like _brain-filing-rules.md). Tells agents when to call gbrain friction log and how to choose a severity. Routes to friction CLI from any skill the claw-test exercises.

  • skills/_output-rules.md — Output quality standards (deterministic links, no slop, exact phrasing)

  • skills/brain-ops/SKILL.md — Brain-first lookup, read-enrich-write loop, source attribution

  • skills/citation-fixer/SKILL.md — Citation format auditing and fixing

  • skills/conventions/ — Cross-cutting rules (quality, brain-first, model-routing, test-before-bulk, cross-modal)

  • skills/conventions/brain-routing.md — agent-facing convention skill documenting the canonical 6-tier source resolution chain (flag → env → dotfile → local_path → brain_default → seed_default) with paste-ready decision tables. Linked from CLAUDE.md's "Two organizational axes" section and from gbrain sources current's hint output.

  • skills/cron-scheduler/SKILL.md — Schedule staggering, quiet hours, idempotency

  • skills/cross-modal-review/SKILL.md — Quality gate via second model

  • skills/daily-task-manager/SKILL.md — Task lifecycle with priority levels

  • skills/daily-task-prep/SKILL.md — Morning prep with calendar context

  • skills/data-research/SKILL.md — Structured data research: email-to-tracker pipeline with parameterized YAML recipes

  • skills/idea-ingest/SKILL.md — Links/articles/tweets with author people page mandatory

  • skills/media-ingest/SKILL.md — Video/audio/PDF/book with entity extraction

  • skills/meeting-ingestion/SKILL.md — Transcripts with attendee enrichment chaining. The transcript sidecar carries facts_backstop: false, and the meeting page is drafted with it until the verification checklist passes (#6232), so automatic fact extraction reads only the verified page; test/facts-eligibility.test.ts pins both literals.

  • skills/migrations/ — Version migration files with feature_pitch YAML frontmatter

  • skills/minion-orchestrator/SKILL.md — Unified background-work skill. Two lanes: shell jobs via gbrain jobs submit shell --params '{"cmd":"..."}' (operator/CLI only; MCP throws permission_denied for protected names) and LLM subagents via gbrain agent run (user-facing entrypoint). Shared Preconditions block, parent-child DAGs with depth/cap/timeouts, child_done inbox for fan-in, PGLite --follow inline path for dev. Triggers narrowed to "gbrain jobs submit" + "submit a gbrain job" so stats/prune/retry questions fall through to gbrain --help.

  • skills/plugin-lanes.json — curation record for the plugin lanes: lane set = (openclaw bundle ∖ base_exclusions) ∪ additions, a reason per entry; starter_gaps is the generated snapshot of per-skill beyond-starter MCP ops (refresh via --write-gaps). The openclaw lane's own curation is untouched — plugin users ARE the brain host (the downstream-vs-host inversion).

  • skills/repo-architecture/SKILL.md — Filing rules by primary subject

  • skills/reports/SKILL.md — Timestamped reports with keyword routing

  • skills/signal-detector/SKILL.md — Always-on idea+entity capture on every message

  • skills/skill-creator/SKILL.md — Create conforming skills with MECE check

  • skills/soul-audit/SKILL.md — 6-phase interview for SOUL.md, USER.md, ACCESS_POLICY.md, HEARTBEAT.md

  • skills/testing/SKILL.md — Skill validation framework

  • skills/webhook-transforms/SKILL.md — External events to brain signals

  • src/assets/wasm/ — 37 tree-sitter grammar WASMs + tree-sitter runtime. Committed to the repo so bun --compile embeds them deterministically via import path from ... with { type: 'file' }. The CI guard scripts/check-wasm-embedded.sh requires semantic TypeScript and Bash case-statement symbols in the compiled binary. Bash uses the official tree-sitter-bash v0.23.3 ABI-14 release asset, pinned by checksum in scripts/vendor-bash-wasm.sh; src/assets/wasm/README.md records provenance. Code chunker version 7 invalidates old content hashes; gbrain sync --source <id> --full revisits affected history in active repositories. tree-sitter-sql.wasm (DerekStride/tree-sitter-sql @ c2e1e08db1ea20dc23bdb8d228a81a8756e9c450, built with [email protected] --abi 14) adds SQL coverage at 11 MB — larger than peers because the grammar covers PostgreSQL + MySQL + SQLite + T-SQL basics (40 MB generated parser.c); the compiled binary grows ~6%.

  • src/cli.ts — the entry point (bun src/cli.ts, the gbrain bin, the compiled binary): Bun floor, signal handlers and stdout delivery, then either the engine-free fast path (cliFastPath: --version, version, bare gbrain, --help, -h, after global-flag parsing and runCliPreflight) or a dynamic import of the dispatcher, src/cli/main.ts runCli(). Its static imports are paid by every invocation and stay light: the dispatcher's graph (every operation and command module) loads only for real commands, so --version and top-level help skip it. The top-level help text is src/cli/top-help.ts, shared by both paths. Pinned by test/cli-fast-path.test.ts (fast-path branches, output parity, and import-graph bounds for the entry and the dispatcher).

  • src/cli/main.ts — the dispatcher (moved out of src/cli.ts; tests import its helpers from here). It keeps three graphs off every command: completeEngineStartup asks migrate-pending.ts (generated latest version) before loading migrate.ts and its 220 migration modules, thin-client-upgrade-prompt.ts takes compareVersions from migration-ledger.ts instead of the upgrade orchestrator registry, and mcp-client.ts loads the MCP HTTP client SDK on the first remote call. Generic thin-client mutation failures use the shared persistence reporter, retaining request IDs and typed JSON receipts while preserving SIGINT exit 130. test/thin-client-write-errors.serial.test.ts exercises real CLI timeout, cancellation, pending and conflict paths against a loopback MCP fixture. No-DB fallbacks announce themselves on stderr instead of degrading silently. dream dispatch binds the caught engine-connect error and emits [dream] WARNING: could not connect to DB (...) before falling through to filesystem-only phases; the runDream(null, ...) no-DB fallback is preserved (pinned by test/cli-dream-engine-warn.test.ts, 2 subprocess cases against good + bad DATABASE_URL). doctor dispatch does the same: when connectEngine OR the DB-backed runDoctor run throws, it emits [doctor] DB-backed doctor run failed (...) — falling back to filesystem-only checks, scrubbing the error message through BOTH url-redact.ts:redactUrlsInText and redact-connection-info.ts:redactConnectionInfo first, because doctor output is exactly what users paste into issues and CI logs (pinned by the fallback case in test/doctor-minions-check.test.ts: stderr note present, credentials absent, stdout stays parseable --json). main() opens with await runCliPreflight() (core/cli-preflight.ts: cwd-.env quarantine -> `/.gbrain/.env-> guardrails loader) beforeparseGlobalFlags; the former inline #3688 guardrails block lives in the preflight module. get_pageoutput renders throughsrc/cli/page-render.ts: a partial response prints only what it carries plus a stderr note (a --sectionread prints the section text, a--grepread each block under-- lines a-b (match at …), with the heading path or match counts on stderr), and a thin-client gbrain getrefused withpage_too_large_for_inline pages the round-trip markdown to its end (readWholePageMarkdown, size + sha256 checked, restarts if the page changes) before printing. connectEngineis the thin-client backstop: on a config withremote_mcpand nodatabase_urlit refuses the dispatched command throughrefuseThinClientinstead of building an engine, so a command without its own route never dies with "No database URL" or reads an empty in-memory PGLite. Handlers that already route over MCP (salience, anomalies, graph-query, whoknows, founder, and every recall form except an in-process--query/--budget-tokenscall) run engine-free fromprepareConnectedDispatch. Pinned by test/thin-client-connect-engine-guard.test.ts. A read-scope op, gbrain search, sources listand a one-shotrecall(not--watch) connect with oneShotRead: startup, the context build and the read share one config snapshot (takeStartupConfigSnapshot hands it over; pending migrations run outside it and drop its rows), the Postgres pool opens at most two connections (ONE_SHOT_READ_POOL_MAX; GBRAIN_POOL_SIZE still wins), and the retired-marker cleanup only filesystem-guarded writes need is skipped. Inside that snapshot source resolution reads the sources table once (requestSnapshotReadinconfig-snapshot.ts), and the search-statistics guard (missingSearchStatistics) is one statement (test/cold-read-folded-statements.test.ts); a transaction pooler's prepared-statements banner prints once per database (src/core/pooler-notice.ts). Pinned by test/e2e/cli-read-startup-round-trips.test.ts(statement counts from the wire trace). The host connect itself isconnectEngineForServe(hooks, {probeOnly, oneShotRead})insrc/core/engine-connect.ts: throw-only (no_brain, requires_local_engine, repair refusals), it records the engine's config through ENGINE_CONNECT_HOOKSand disconnects an engine whose startup fails after the connect;connectEngine wraps it with the CLI exits (exitOnRepairFailed), and the status-only serve call sites pass it directly (test/engine-connect.test.ts). Size ceiling (src/cli/main.ts): scripts/module-size-limits.tsv(per-change raise history:git log -pon that file). The ceiling covershandleCliOnly's explicit ordered pipeline (@cliPipelineStagefunctions: thin-client guard, deferred-persistence routing, subcommand and help routes, read-only timeout path, sync watchdog and delegation, connectEngine terminator with degraded-serve recovery, teardown), thin-client routing and refusal, help and self-help text, strict flag parsing and process-exit teardown. Per-command dispatch (pre- and post-connect) lives in the command table (entry below), not insrc/cli/main.ts`.

  • src/cli/remember-format.ts — the remember human formatter (formatRememberResult: status, entity with (inferred from mention), expiry, degraded dedup, a note: private line when the call passed visibility: private (#6606; read from the params, so it prints when the write ran on a serve owner too), warnings + hint), kept out of src/cli.ts; --json prints the raw envelope. Pinned by test/remember-entity-inference.test.ts.

  • src/cli/subcommands.ts + src/cli/router-help.ts + src/cli/strict-args.ts — help never acts (#6114). subcommands.ts holds each router command's inventory (ROUTERS: pages, cache, integrity, hook, search, edge-proposals, schema, config, quarantine, core, loops; each router re-exports its list as SUBCOMMANDS and types its dispatch over it, so an unlisted subcommand fails typecheck) and the help grammar: --help/-h anywhere before -- (a flag-value slot included) and a bare help only as the first token after a router command or one of its subcommands (search help stays a query). cli.ts decides cliHelpRequested once, before the update marker, backup nag and key warnings; on help it calls printRouterHelp, which loads only the router's printUsage, before any subcommand, thin-client route or engine. strict-args.ts is the per-subcommand table for destructive subcommands (pages purge-deleted, cache clear/prune, schema use/downgrade/init/remove-*, integrity auto/reset-progress, search modes --reset and its --mode <mode> preview, W4.13: --source <mode> is the deprecated alias, and the handler refuses a missing value or conflicting --mode/--source with exit 2 instead of resetting): an argument the handler would ignore refuses with invalid_params (exit 2) after help and before dispatch, with a read-only fix that itself parses under the table (ask_user for integrity reset-progress). STRICT_SELF_HELP_SUBCOMMANDS is the same table for a self-help command that prints its own per-subcommand help instead of a router inventory: skillpack reference (#5491) accepts <name> or --all, --workspace, --since, --apply-clean-hunks, --dry-run and --json, so a --dry-run=true, a typo or an unknown flag refuses before the apply instead of running it with the flag ignored (the --harness lane keeps its own parser; src/commands/skillpack/reference.ts re-checks on entry so an in-process caller gets the same refusal). strictSpecFor(command, subArgs) is the one lookup of a subcommand's spec, shared by strictArgsRefusal and the CLI entry's = gate, which leaves a strict subcommand's argv to this table. The flag-registry generator skips strict-args.ts (its literals belong to the commands it lists). Pinned by test/cli-help-grammar.test.ts and the four-part subprocess gate test/cli-help-no-side-effects*.serial.test.ts (harness test/helpers/cli-help-gate.ts, child probe test/helpers/cli-side-effect-probe.ts): every self-help command's --help/-h and every router subcommand's --help/-h/help on a copy of a seeded PGLite brain, asserting exit 0 with usage, unchanged table rows and HOME/cwd files, and no fetch or spawn. quarantine (list, clear, scan) is a router since #6259. core and loops are routers since #6521: as SELF_HELP_WITHOUT_ENGINE entries their handlers answered help only as the first token, so core list --help ran list against the null engine (internal_error: null is not an object) and loops show --help exited 2; transcripts keeps its per-subcommand help (recover --help prints a dedicated usage) and its handler answers the flag for status itself. test/cli-help-without-brain.test.ts runs an explicit brainless table of these invocations next to the gate's router walk.

  • src/cli/command-table.ts + src/cli/commands/<name>.ts — one record per CLI-only command (name, phase, thinClient, selfHelp, skipStartupHooks, load: () => import('<literal>'), and the agent-contract fields json, read_only, startup, end_of_options, help: () => import('./help/<name>.ts') — see src/cli/help/ in agent contract). A selfHelp record whose handler needs an engine answers --help brainless through SELF_HELP_WITHOUT_ENGINE in src/cli.ts (an explicit loader, or true to run the record's own module with a null engine). The records derive CLI_ONLY, CLI_ONLY_SELF_HELP, THIN_CLIENT_REFUSED_COMMANDS and STARTUP_HOOK_SKIP_COMMANDS (re-exported from src/cli.ts); cliAliases' collision check runs over the derived CLI_ONLY. Each module holds the body its switch case or plain branch had, moved verbatim, and receives dispatcher-owned pieces through CliDispatchContext. Master's membership inconsistencies are preserved (the dead second auth branch, the unreachable capture --help branch, the connectors and recall refuse hints that only connectEngine's thin-client backstop reaches (the static extractor reports them as never reached), watch refused without a hint, eval whoknows shadowed by the refusal) and pinned by test/fixtures/goldens/cli/membership-sets.json. Contract: test/cli-command-table.test.ts; engine lifecycle per path: test/cli-dispatch-lifecycle.serial.test.ts. json / jsonSubcommands declare the D2 --json contract (record-wide / per subcommand).

  • scripts/build-fence-format.ts — #6188 renders the generated region of docs/guides/fence-format.md (between BEGIN/END GENERATED fence-format) from the fence constants: markers, the column tables and layouts from schema.ts (COLUMNS, BASE_WIDTH, MIN_CELLS, CANONICAL_HEADER, ALLOWED, COLUMN_DEFAULTS, NAMED_COLUMNS, TOLERATED_TRAILING, HEADER_ALIASES), holder outcomes computed with isValidHolder/holderAlias, the Tier 1 rule table from the synonym tables (bound to FixClass by satisfies), screen reasons grouped by tier and the gate table from reasons.ts. It parses both synthetic examples with the strict parsers and throws on any warning. --check exits 1 when the committed region is stale. Drift test: test/fence-format-reference.test.ts (the region, the examples, the reference's links, and one fence-<reason> row per reason in write-refusals.md with the reason table's tier and auto-retry and a link into the reference).

  • scripts/lib/cli-pipeline.ts — flattens handleCliOnly (inlining @cliPipelineStage functions) and reads the command table by AST, for the W0 dispatch-shape extractor (test/helpers/cli-dispatch-extract.ts) and scripts/generate-flag-registry.ts.

  • src/core/operation-manifest.generated.ts + scripts/build-operation-manifest.ts (bun run build:operation-manifest, in regen:all) — every operation in src/core/operations.ts minus its handler, in registry order (OperationMeta in src/core/ops/contract.ts). gbrain serve (stdio initialize/tools/list, surface and publish-gate filtering, skill-resource permission checks) and the CLI dispatcher (src/cli/op-manifest.ts: command, alias, flag and help lookup plus the A1 fix-routing registration) read it, so neither loads the handler graph until an op runs. Freshness, equality with the live registry, and the absence of operations.ts/dispatch.ts from the serve and dispatcher import graphs are pinned by test/operation-manifest.test.ts. The same script writes src/core/operation-loaders.generated.ts: each op's defining module (verbs.ts or ops/*.ts) and export, as string-literal import()s. src/core/operation-load.ts holds the one finalize step (central OP_AREAS + the output-redaction wrapper, idempotent per op object) that operations.ts applies to the registry, and loadOperation(name), which runSharedOperation uses to load and finalize only the op it runs; test/cli-cold-start-graph.test.ts pins that a lone load is the registry's object in the registry's state.

  • src/core/cli-flag-registry.generated.ts (strict flag validation in src/cli/main.ts) + scripts/generate-flag-registry.ts — pre-dispatch, pre-engine unknown-flag rejection for every command: a flag no handler consults fails loud (unknown flag --x for 'gbrain <cmd>', exit 1; --json invocations also get a structured {status:'error', reason:'invalid_flag'} on stdout) instead of being silently ignored while the un-asked-for real operation runs. validateCommandFlags(command, subArgs) runs after the --help short-circuit and before any dispatch or engine connect, in two lanes mirroring dispatch order (CLI_ONLY first — think/salience/anomalies are both ops AND CLI_ONLY members whose handlers parse flags the op contract doesn't declare): CLI_ONLY commands validate against the generated CLI_FLAG_REGISTRY (per-command legal sets derived from each command's source — its src/cli/commands/ module and pipeline branches + imported modules + one level of relative imports + EXTRA_FLAGS + DELEGATED_MODULES, the modules a command hands its argv to through a nested handler (auth → persistence-admin.ts and grants/cli.ts), scanned at module depth without their imports so their safety-flag reads count as consumption; deliberately over-inclusive, help-text mentions count, but // and /* */ comments are stripped at every depth before the scan — a helper's doc comment naming --fresh must not legalise it for a command that only imports one function from that helper; regenerate via bun run build:flag-registry); op commands validate via findUnknownOpFlag, which mirrors parseOpArgs's traversal (non-boolean flags consume their value token; --key=value inline form recognized) plus the CLI-local flags consumed outside the op contract (json, explain, help, source, dry-run); the CLI_ONLY token scan is the exported findUnknownFlag(args, legal), defined in src/cli/flag-equals.ts and re-exported by main.ts; that module's = gate (cliOnlyFlagArgs, see agent contract) splits, keeps or refuses each --flag=value token before this scan runs. parseOpArgs also refuses to let a non-boolean flag swallow a token that is itself a known flag of the same command (op-contract param, a CLI-local, or the --no-<boolean> form): gbrain put x --content --source default fails with --content requires a value, but '--source' is a flag; omit --content (or put it last) to read stdin (exit 1, pre-write) instead of storing the literal --source as the page body. A value that merely starts with -- but names no flag of this command stays a value; the shared isKnownOpFlag predicate (src/core/op-flag-tokens.ts) sits next to isBooleanLiteral so parser and validator cannot disagree. In parseOpArgs, json/dry_run are CLI-local booleans that never consume a value token, so a trailing --dry-run is a real rehearsal switch feeding makeContext's ctx.dryRun. Uppercase flag spellings are treated as unknown (every handler is case-sensitive-lowercase, so they'd be silently ignored downstream — the exact class the validator kills). Exempt by contract: call (arbitrary --param interface), config (arbitrary set values), jobs submit (handler-defined payload params); everything after a literal -- is passthrough and never validated. A command missing from the registry fails OPEN at runtime (never bricks a command); test/cli-flag-validation.test.ts pins registry freshness, per-command drift, and consumption evidence — a safety flag (--dry-run, --yes, --force) may only be advertised if the command's source actually reads it. The generator segments handleCliOnly into per-command text blocks with segmentDispatchBlocks: both case 'X': labels and every if (command === 'X' …) head — plain, compound (&& args[0] === 'sub': the no-DB eval <sub> bypasses such as eval longmemeval, the <cmd> --help pre-engine branches, agent register) and multi-line — are markers, and ownership follows the command === 'X' head, never the condition's tail, so a compound block's flags land on its own command's row (the eval row is a union across eval subcommands, the registry's shape for every multi-subcommand command); a bare command === 'X' inside a non-if expression is deliberately not a marker. Only import('./commands/*.ts') inside a block counts as a command module (core helpers a block reaches for directly are not scanned — a flag the block consumes through one is already a literal in the block's own text), and isValueOnlyImport skips a destructured import whose bindings are all SCREAMING_CASE constants (a borrowed message string, not a handler). Pinned by test/generate-flag-registry.test.ts (acceptance AND rejection: --frobnicate is still refused) and test/eval-longmemeval-cli-smoke.test.ts (the documented gbrain eval longmemeval … --retrieval-only --by-type --no-trajectory --keyword-only invocation exits 0 as a subprocess).

  • src/schema.sql — Full Postgres + pgvector DDL: canonical for every table except the TS fragment tables, whose BEGIN/END GENERATED regions are rewritten from the fragment modules; bun run build:schema derives schema-embedded.generated.ts and the PGLite template from it (docs/ENGINES.md#canonical-schema-sources)

  • templates/ — SOUL.md, USER.md, ACCESS_POLICY.md, HEARTBEAT.md templates