Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(schema): schema active honors --source and never hides an unreadable database (#6090)
garrytan1b8e882bce84
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex 13fd8a28cf..9c63e50ae2 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -28,6 +28,7 @@ Key files:- `src/core/schema-pack/review.ts` — `schema review-candidates` / `review-orphans`. `findTypeOrphans(engine, manifest, scope, limit)` (shared by the CLI and the `schema_review_orphans` MCP op) returns pages with no active-pack type match (untyped or undeclared, each with `type` + `reason`), the true `orphan_count`, `undeclared_types` counts and `truncated`; a query failure throws instead of reading as zero orphans.- `src/core/schema-pack/sync.ts` — `runSyncCore(engine, opts)` chunked UPDATE in 1000-row batches per declared prefix. Concurrent writers never block on a single row >100ms. Write-side scoping via `ctx.sourceId` directly (NOT `sourceScopeOpts`, which inherits OAuth read federation). Idempotent on `--apply` re-run.- `src/commands/schema.ts` — schema CLI dispatch, including `lint [<pack>] [--with-db] [--json]`. Lint parses `--with-db` as a boolean rather than a pack name, accepts it before or after the optional pack, and rejects unknown flags, boolean values, and multiple pack positionals. The DB-backed lane resolves the active pack and runs DB-plane rules on the same connection; plain lint does not run those rules. `test/schema-cli-lint-with-db.test.ts` drives real isolated CLI subprocesses for implicit/explicit packs, JSON output, missing packs, global source flags, invalid arguments, and plain-lint separation. `withConnectedEngine` routes `loadConfig()` through the canonical `toEngineConfig()` helper and passes the complete result (`database_url` and `database_path`) to factory construction and connect, so PGLite schema commands open the configured brain. Lifecycle-grouped help text (Inspection / Activation / Authoring / Discovery+repair). Pinned by `test/schema-cli-database-path.serial.test.ts`. Help after any subcommand prints usage without running it, and `use`, `downgrade`, `init` and `remove-*` refuse arguments they would ignore (`src/cli/strict-args.ts`).+- `src/commands/schema-active.ts` — `schema active [--source <id>] [--json]` (#6090). Resolves through `engineSchemaInput(engine, { remote: false, sourceId })`, the engine's own tier chain, so the per-source override (`schema_pack.source.<id>`) is honored and the output names the tier (`resolved_from`). An unregistered or archived source (`fetchSource`) refuses with `unknown_source` (fix `gbrain sources list --json`); a database that can't be read is a degraded read: stderr marker in text mode (exit 0), a `database_error` envelope carrying the file-plane answer and `degraded: true` under `--json` (nonzero). `schema.ts`'s `runActive` only parses flags and passes `withConnectedEngine`. Pinned by `test/schema-active-source.test.ts`.- `skills/schema-author/SKILL.md` — Agent dispatcher for "evolve the schema pack." Triggers: 15+ phrasings incl. "add a page type", "my brain has untyped pages", "propose new types from my corpus", "backfill page types". Explicit Non-goals callout to `brain-taxonomist` (files one page) and `eiirp` (schema-check during iteration) so agents pick the right surface. 7-phase workflow: brain → assess → propose → apply → sync → verify → commit. Lists every gbrain schema CLI verb + every MCP op the skill uses. `brain_first: exempt` frontmatter. Required conformance sections: Contract, Anti-Patterns, Output Format.- `skills/conventions/schema-evolution.md` — Canonical convention: "when to add a type vs alias vs prefix." Decision tree: <20 pages → don't pack-codify; 20-100 → alias or narrow prefix on existing type; 100+ → first-class type. Don'ts section + "when to remove a type" + "when to commit the pack" all answered in one place.diff --git a/docs/architecture/schema-packs.md b/docs/architecture/schema-packs.mdindex 08b6cb3c82..41e3ae5f13 100644--- a/docs/architecture/schema-packs.md+++ b/docs/architecture/schema-packs.md@@ -49,7 +49,7 @@ that you author with `gbrain schema init` or `gbrain schema fork`.Inspection verbs:```bash-gbrain schema active # show resolved pack + which tier set it+gbrain schema active [--source <id>] [--json] # show resolved pack + which tier set itgbrain schema list # list bundled + installed packsgbrain schema show # pretty-print the active packgbrain schema validate # validate a manifest's shape@@ -63,6 +63,25 @@ Use `gbrain config unset schema_pack` to remove that database override, then`gbrain config get schema_pack` and `gbrain config show` report the sameresolved pack and name its tier.+### Per-source resolution++`gbrain schema active --source <id>` resolves the pack the engine uses for+that source, including the per-source database override+(`schema_pack.source.<id>`), and prints `Resolved for source <id>: <tier>`+(`per-source-db`, `db-config`, `home-config`, `env` or `default`). Under+`--json` the document carries `pack`, `version`, `identity`,+`resolved_from`, `source_id` and `database` (`read`, `unreadable` or+`not_configured`).++- An unregistered or archived source is refused with `unknown_source`; its fix+ is `gbrain sources list --json`, which lists the ids `--source` accepts.+- When the brain database can't be read, the database tiers are skipped and+ the answer comes from the environment and `~/.gbrain/config.json` only. Text+ mode prints a `Degraded: database unreadable` line on stderr and exits 0;+ `--json` exits nonzero with a `database_error` envelope that still carries+ the file-plane answer (`degraded: true`). Run `gbrain doctor --json`, then+ `gbrain schema active --json` again.+Authoring + discovery verbs:```bashdiff --git a/src/commands/schema-active.ts b/src/commands/schema-active.tsnew file mode 100644index 0000000000..ea3cdea804--- /dev/null+++ b/src/commands/schema-active.ts@@ -0,0 +1,92 @@+/**+ * `gbrain schema active [--source <id>] [--json]` (#6090): report the pack the+ * engine would use, resolved through the same tier chain as the engine+ * (`engineSchemaInput`), including the tier-3 per-source override. An unknown+ * source is refused (`unknown_source`); an unreadable database is a degraded+ * read: text mode marks it on stderr, `--json` exits nonzero with the+ * file-plane answer attached to a `database_error` envelope.+ */+import type { BrainEngine } from '../core/engine.ts';+import { loadConfig } from '../core/config.ts';+import { opError } from '../core/ops/contract.ts';+import { engineSchemaInput } from '../core/schema-pack/engine-resolution.ts';+import { loadActivePack, resolveActivePackNameOnly, type LoadActivePackInput } from '../core/schema-pack/load-active.ts';+import { fetchSource } from '../core/sources-load.ts';+import { writeCliRefusal } from '../cli/cli-error.ts';++type WithEngine = <T>(fn: (engine: BrainEngine) => Promise<T>) => Promise<T>;+type DatabaseRead =+ | { state: 'read'; input: LoadActivePackInput; sourceKnown: boolean }+ | { state: 'unreadable'; error: string }+ | { state: 'not_configured' };++const DOCS = 'docs/architecture/schema-packs.md#per-source-resolution';++async function readDatabasePlane(withEngine: WithEngine, sourceId: string | undefined): Promise<DatabaseRead> {+ try {+ return await withEngine(async (engine) => {+ const input = await engineSchemaInput(engine, { remote: false, sourceId });+ const source = sourceId ? await fetchSource(engine, sourceId) : null;+ return { state: 'read' as const, input, sourceKnown: !sourceId || (source !== null && source.archived !== true) };+ });+ } catch (e) {+ return { state: 'unreadable', error: e instanceof Error ? e.message : String(e) };+ }+}++export async function runSchemaActive(opts: { json: boolean; sourceId?: string }, withEngine: WithEngine): Promise<void> {+ const { json, sourceId } = opts;+ const cfg = loadConfig();+ const db: DatabaseRead = cfg ? await readDatabasePlane(withEngine, sourceId) : { state: 'not_configured' };++ if (db.state === 'read' && !db.sourceKnown) {+ process.exit(writeCliRefusal(opError('unknown_source',+ `Source "${sourceId}" is not registered on this brain (or is archived), so no per-source pack applies to it.`,+ 'Run `gbrain sources list --json` for the registered source ids, then pass one with --source.', {+ docs: DOCS,+ fix: { argv: ['gbrain', 'sources', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Lists the registered source ids that schema active --source accepts.' },+ }), 'schema', { json }));+ }++ const input: LoadActivePackInput = db.state === 'read' ? db.input : { cfg, remote: false, sourceId };+ const resolution = resolveActivePackNameOnly(input);+ const pack = await loadActivePack(input);+ const result = {+ schema_version: 1,+ pack: pack.manifest.name,+ version: pack.manifest.version,+ identity: pack.identity,+ resolved_from: resolution.source,+ source_id: sourceId ?? null,+ database: db.state,+ page_types: pack.manifest.page_types.length,+ link_verbs: pack.manifest.link_types.length,+ takes_kinds: pack.manifest.takes_kinds,+ ...(pack.manifest.description ? { description: pack.manifest.description } : {}),+ };++ if (db.state === 'unreadable') {+ const why = `The brain database could not be read (${db.error}), so the database-plane tiers (brain-wide schema_pack and per-source overrides) were skipped; the pack shown comes from env/config.json only and may not be what the engine uses.`;+ if (json) {+ process.exit(writeCliRefusal(opError('database_error', 'database unreadable: showing the env/config.json resolution only.',+ 'Run `gbrain doctor --json` to diagnose the database, then rerun `gbrain schema active --json`.', {+ why, docs: DOCS,+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Reports why the brain database is unreadable and names the repair.',+ verify: { argv: ['gbrain', 'schema', 'active', '--json'] } },+ }), 'schema', { json, legacy: { ...result, degraded: true } }));+ }+ console.error(`Degraded: database unreadable (${db.error}); showing the env/config.json resolution only. Run: gbrain doctor --json`);+ }++ if (json) { console.log(JSON.stringify(result, null, 2)); return; }+ console.log(`Active pack: ${result.pack} v${result.version}`);+ console.log(`Source: ${result.resolved_from}`);+ if (sourceId) console.log(`Resolved for source ${sourceId}: ${result.resolved_from}`);+ console.log(`Pack identity: ${result.identity}`);+ console.log(`Page types: ${result.page_types}`);+ console.log(`Link verbs: ${result.link_verbs}`);+ console.log(`Takes kinds: ${result.takes_kinds.join(', ')}`);+ if (result.description) console.log(`\n${result.description}`);+}diff --git a/src/commands/schema.ts b/src/commands/schema.tsindex 0f263101de..2b60a19b66 100644--- a/src/commands/schema.ts+++ b/src/commands/schema.ts@@ -203,20 +203,10 @@ async function readDbSchemaPackConfig(cfg: GBrainConfig | null): Promise<string}}-async function runActive(_args: string[]): Promise<void> {- const cfg = loadConfig();- const dbConfig = await readDbSchemaPackConfig(cfg);- const resolution = resolveActivePackNameOnly({ cfg, remote: false, dbConfig });- const pack = await loadActivePack({ cfg, remote: false, dbConfig });- console.log(`Active pack: ${pack.manifest.name} v${pack.manifest.version}`);- console.log(`Source: ${resolution.source}`);- console.log(`Pack identity: ${pack.identity}`);- console.log(`Page types: ${pack.manifest.page_types.length}`);- console.log(`Link verbs: ${pack.manifest.link_types.length}`);- console.log(`Takes kinds: ${pack.manifest.takes_kinds.join(', ')}`);- if (pack.manifest.description) {- console.log(`\n${pack.manifest.description}`);- }+async function runActive(args: string[]): Promise<void> {+ const { json, source } = parseFlags(args);+ const { runSchemaActive } = await import('./schema-active.ts');+ return runSchemaActive({ json, sourceId: source }, withConnectedEngine);}function runList(_args: string[]): void {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 5c56bcf6f5..e585806b6f 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -259,6 +259,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },{ since: '0.0.0-wave11', text: '`gbrain pages purge-deleted`, `cache clear|prune`, `schema use|downgrade|init|remove-*`, `integrity auto|reset-progress` and `search modes --reset` refuse an argument they would ignore (exit 2) instead of running; `pages purge-deleted --source <id>` used to purge every source. Preview with `gbrain pages purge-deleted --dry-run --json`.' },{ since: '0.0.0-wave11', text: '`gbrain apply-migrations` now exits 1 (`migrations_pending`) whenever it leaves the schema behind, which most runs used to report as exit 0; run `gbrain apply-migrations --yes`, or after a failed `--yes` run, `gbrain doctor --json`.' },+ { since: '0.0.0-wave11', text: '`gbrain schema active --json` now exits nonzero on `unknown_source` (an unregistered `--source`) or a degraded read (`database_error`: the brain database could not be read, so only the config.json answer is shown); check sources with `gbrain sources list --json` and the database with `gbrain doctor --json`.' },{ since: '0.0.0-wave11', text: '`gbrain pages purge-deleted` asks before a hard purge: without a terminal it exits 3 with the consent payload, and the `--yes` command it names runs only after the user agrees. The autopilot purge is unchanged.' },];diff --git a/test/schema-active-source.test.ts b/test/schema-active-source.test.tsnew file mode 100644index 0000000000..da44ad76a0--- /dev/null+++ b/test/schema-active-source.test.ts@@ -0,0 +1,111 @@+/**+ * #6090: `schema active --source <id>` resolves the pack the way the engine+ * does for that source (tier-3 `schema_pack.source.<id>`), refuses an unknown+ * source with `unknown_source`, and never presents a config.json-only answer+ * as complete when the database can't be read. Successes run in-process;+ * refusals run the real CLI (their envelope is written to fd 1 directly).+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runSchema } from '../src/commands/schema.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { withEnv } from './helpers/with-env.ts';+import { runCli } from './helpers/cli-spawn.ts';++let home: string;+let brokenHome: string;++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-schema-active-source-'));+ const brain = join(home, '.gbrain');+ mkdirSync(brain, { recursive: true });+ const databasePath = join(brain, 'brain.pglite');+ writeFileSync(join(brain, 'config.json'), JSON.stringify({ engine: 'pglite', database_path: databasePath }));+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: databasePath });+ try {+ await engine.initSchema();+ await engine.setConfig('schema_pack.source.default', 'gbrain-base-v2');+ } finally {+ await engine.disconnect();+ }++ brokenHome = mkdtempSync(join(tmpdir(), 'gbrain-schema-active-broken-'));+ mkdirSync(join(brokenHome, '.gbrain'), { recursive: true });+ const notADirectory = join(brokenHome, 'not-a-database');+ writeFileSync(notADirectory, 'plain file, not a PGLite data directory');+ writeFileSync(join(brokenHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: notADirectory }));+}, 60_000);++afterAll(() => {+ rmSync(home, { recursive: true, force: true });+ rmSync(brokenHome, { recursive: true, force: true });+});++async function run(args: string[], gbrainHome = home): Promise<{ stdout: string; stderr: string; exitCode: number }> {+ const out: string[] = [];+ const err: string[] = [];+ let exitCode = 0;+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(' ')); });+ const error = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.map(String).join(' ')); });+ const stdoutWrite = spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown) => { out.push(String(chunk)); return true; }) as never);+ const stderrWrite = spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { err.push(String(chunk)); return true; }) as never);+ const exit = spyOn(process, 'exit').mockImplementation(((code?: number) => { exitCode = code ?? 0; throw new Error('__exit__'); }) as never);+ try {+ await withEnv({ GBRAIN_HOME: gbrainHome, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SCHEMA_PACK: undefined },+ () => runSchema(['active', ...args]));+ } catch (e) {+ if ((e as Error).message !== '__exit__') throw e;+ } finally {+ log.mockRestore(); error.mockRestore(); stdoutWrite.mockRestore(); stderrWrite.mockRestore(); exit.mockRestore();+ }+ return { stdout: out.join('\n'), stderr: err.join('\n'), exitCode };+}++describe('#6090 schema active --source', () => {+ test('text mode honors the per-source pack and names what it resolved', async () => {+ const r = await run(['--source', 'default']);+ expect(r.exitCode).toBe(0);+ expect(r.stdout).toContain('Active pack: gbrain-base-v2');+ expect(r.stdout).toContain('Resolved for source default: per-source-db');+ }, 60_000);++ test('--json reports the per-source override', async () => {+ const r = await run(['--source', 'default', '--json']);+ expect(r.exitCode).toBe(0);+ expect(JSON.parse(r.stdout)).toMatchObject({+ schema_version: 1, pack: 'gbrain-base-v2', resolved_from: 'per-source-db', source_id: 'default', database: 'read',+ });+ }, 60_000);++ test('without --source the brain-wide resolution stands', async () => {+ const r = await run(['--json']);+ expect(r.exitCode).toBe(0);+ const doc = JSON.parse(r.stdout);+ expect(doc.resolved_from).not.toBe('per-source-db');+ expect(doc.source_id).toBeNull();+ }, 60_000);++ test('an unknown source is refused with unknown_source and a sources list fix', async () => {+ const r = await runCli(['schema', 'active', '--source', 'no-such-source', '--json'], { home, cwd: home, env: { GBRAIN_SCHEMA_PACK: undefined }, timeoutMs: 60_000 });+ expect(r.exitCode).not.toBe(0);+ const doc = JSON.parse(r.stdout);+ expect(doc.code).toBe('unknown_source');+ expect(doc.fix.argv.slice(0, 4)).toEqual(['gbrain', 'sources', 'list', '--json']);+ }, 60_000);++ test('an unreadable database is a degraded read: --json exits nonzero, text mode marks it', async () => {+ const json = await runCli(['schema', 'active', '--json'], { home: brokenHome, cwd: brokenHome, env: { GBRAIN_SCHEMA_PACK: undefined }, timeoutMs: 60_000 });+ expect(json.exitCode).not.toBe(0);+ const doc = JSON.parse(json.stdout);+ expect(doc).toMatchObject({ code: 'database_error', degraded: true, database: 'unreadable' });+ expect(typeof doc.pack).toBe('string');+ expect(doc.fix.argv.slice(0, 3)).toEqual(['gbrain', 'doctor', '--json']);++ const text = await run([], brokenHome);+ expect(text.exitCode).toBe(0);+ expect(text.stderr).toContain('database unreadable');+ }, 60_000);+});