Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(schema): pack-authoring subcommands skip flag values when reading names (W4.10)

time-attackae7c218afaab
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.md
index d90633cc44..80cb94af4f 100644
--- a/docs/architecture/key-files/schema-mutation.md
+++ b/docs/architecture/key-files/schema-mutation.md
@@ -30,7 +30,7 @@ Key files:
- `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`.
-- `src/commands/schema-add-type.ts` — `parseAddTypeArgs` for `schema add-type` (#6135). The type name is the first positional that is not a value-flag's value (`--primitive concept archive` names `archive`). A type needs `--prefix <dir/>` or an explicit `--no-prefix`; missing both, `--prefix` with `--no-prefix`, and `--no-prefix` with `--extractable`/`--expert` each refuse with `invalid_params` (exit 2) before the pack is touched. Each refusal's `fix.argv` is one complete corrected command with `<NAME>`/`<PRIMITIVE>`/`<PREFIX>` placeholders described in `inputs`; `NO_PREFIX_NOTE` is the success note (`note` under `--json`). Pinned by `test/schema-add-type-no-prefix.test.ts` (core mutator, batch path, CLI subprocess, and every refusal's fix parsing under the same parser).
+- `src/commands/schema-add-type.ts` — `parseAddTypeArgs` for `schema add-type` (#6135). The type name is the first positional that is not a value-flag's value (`--primitive concept archive` names `archive`). A type needs `--prefix <dir/>` or an explicit `--no-prefix`; missing both, `--prefix` with `--no-prefix`, and `--no-prefix` with `--extractable`/`--expert` each refuse with `invalid_params` (exit 2) before the pack is touched. Each refusal's `fix.argv` is one complete corrected command with `<NAME>`/`<PRIMITIVE>`/`<PREFIX>` placeholders described in `inputs`; `NO_PREFIX_NOTE` is the success note (`note` under `--json`). Pinned by `test/schema-add-type-no-prefix.test.ts` (core mutator, batch path, CLI subprocess, and every refusal's fix parsing under the same parser). W4.10: `schemaPositionals(args, valueFlags)` (exported with `SCHEMA_PACK_VALUE_FLAGS`: `--pack`, `--source`, `--source-id`) gives every other pack-authoring subcommand in `schema.ts` (`remove-type`, `update-type`, `add|remove-alias`, `add|remove-prefix`, `add|remove-link-type`, `set-extractable`, `set-expert-routing`, `scaffold-extractable`) the same rule, with each subcommand's own value flags (`--inverse`, `--page-type`, `--target-type`, `--primitive`, `--dims`, ...); pinned by `test/schema-positionals-w410.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/src/commands/schema-add-type.ts b/src/commands/schema-add-type.ts
index dd654e9c56..45c62b751a 100644
--- a/src/commands/schema-add-type.ts
+++ b/src/commands/schema-add-type.ts
@@ -41,6 +41,25 @@ const INPUT_HOW: Record<string, string> = {
PREFIX: 'The directory the type\'s pages live in, ending in / (for example people/researchers/). For a type set by frontmatter only, use --no-prefix instead of --prefix <PREFIX>.',
};
+/** Value flags every pack-authoring subcommand accepts. */
+export const SCHEMA_PACK_VALUE_FLAGS: readonly string[] = ['--pack', '--source', '--source-id'];
+
+/**
+ * W4.10: the positional arguments of a `schema` subcommand, skipping the value
+ * of each flag in `valueFlags` (`--f v`; `--f=v` is one token), so
+ * `remove-type --pack mine people` names `people`, not `mine`.
+ */
+export function schemaPositionals(args: readonly string[], valueFlags: readonly string[]): string[] {
+ const takesValue = new Set([...SCHEMA_PACK_VALUE_FLAGS, ...valueFlags]);
+ const out: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]!;
+ if (!a.startsWith('--')) { out.push(a); continue; }
+ if (takesValue.has(a)) i++;
+ }
+ return out;
+}
+
/** Drop a value flag (both `--f v` and `--f=v`) from argv. */
function withoutFlag(args: string[], flag: string): string[] {
return args.filter((a, i) => !(a === flag || a.startsWith(`${flag}=`) || args[i - 1] === flag));
diff --git a/src/commands/schema.ts b/src/commands/schema.ts
index 6959b1a9f2..16b5a63790 100644
--- a/src/commands/schema.ts
+++ b/src/commands/schema.ts
@@ -995,6 +995,11 @@ function parseBool(raw: string | undefined): boolean | null {
return null;
}
+/** W4.10: the subcommand's positionals, skipping flag values (`--pack mine` never names the type). */
+async function positionals(args: string[], valueFlags: readonly string[] = []): Promise<string[]> {
+ return (await import('./schema-add-type.ts')).schemaPositionals(args, valueFlags);
+}
+
function pickPackName(parsed: { positional?: string[] }, args: string[]): string {
// Honor --pack <name> before falling back to the active pack.
for (let i = 0; i < args.length; i++) {
@@ -1165,7 +1170,7 @@ async function runAddTypeCmd(args: string[]): Promise<void> {
async function runRemoveTypeCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const name = args.filter((a) => !a.startsWith('--'))[0];
+ const name = (await positionals(args))[0];
if (!name) { console.error('Usage: gbrain schema remove-type <name>'); process.exit(2); }
try { emitMutateResult(await removeTypeFromPack(packName, name), json); }
catch (e) { handleMutationError(e); }
@@ -1174,7 +1179,7 @@ async function runRemoveTypeCmd(args: string[]): Promise<void> {
async function runUpdateTypeCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const name = args.filter((a) => !a.startsWith('--'))[0];
+ const name = (await positionals(args, ['--extractable', '--expert', '--expert-routing', '--primitive']))[0];
if (!name) { console.error('Usage: gbrain schema update-type <name> [--extractable BOOL] [--expert BOOL] [--primitive P]'); process.exit(2); }
const patch: Record<string, unknown> = {};
for (let i = 0; i < args.length; i++) {
@@ -1198,7 +1203,7 @@ async function runUpdateTypeCmd(args: string[]): Promise<void> {
async function runAddAliasCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const pos = args.filter((a) => !a.startsWith('--'));
+ const pos = await positionals(args);
if (pos.length < 2) { console.error('Usage: gbrain schema add-alias <type> <alias>'); process.exit(2); }
try { emitMutateResult(await addAliasToType(packName, pos[0]!, pos[1]!), json); }
catch (e) { handleMutationError(e); }
@@ -1207,7 +1212,7 @@ async function runAddAliasCmd(args: string[]): Promise<void> {
async function runRemoveAliasCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const pos = args.filter((a) => !a.startsWith('--'));
+ const pos = await positionals(args);
if (pos.length < 2) { console.error('Usage: gbrain schema remove-alias <type> <alias>'); process.exit(2); }
try { emitMutateResult(await removeAliasFromType(packName, pos[0]!, pos[1]!), json); }
catch (e) { handleMutationError(e); }
@@ -1216,7 +1221,7 @@ async function runRemoveAliasCmd(args: string[]): Promise<void> {
async function runAddPrefixCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const pos = args.filter((a) => !a.startsWith('--'));
+ const pos = await positionals(args);
if (pos.length < 2) { console.error('Usage: gbrain schema add-prefix <type> <prefix>'); process.exit(2); }
try { emitMutateResult(await addPrefixToType(packName, pos[0]!, pos[1]!), json); }
catch (e) { handleMutationError(e); }
@@ -1225,7 +1230,7 @@ async function runAddPrefixCmd(args: string[]): Promise<void> {
async function runRemovePrefixCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const pos = args.filter((a) => !a.startsWith('--'));
+ const pos = await positionals(args);
if (pos.length < 2) { console.error('Usage: gbrain schema remove-prefix <type> <prefix>'); process.exit(2); }
try { emitMutateResult(await removePrefixFromType(packName, pos[0]!, pos[1]!), json); }
catch (e) { handleMutationError(e); }
@@ -1234,7 +1239,7 @@ async function runRemovePrefixCmd(args: string[]): Promise<void> {
async function runAddLinkTypeCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const name = args.filter((a) => !a.startsWith('--'))[0];
+ const name = (await positionals(args, ['--inverse', '--page-type', '--target-type']))[0];
if (!name) { console.error('Usage: gbrain schema add-link-type <name> [--inverse <verb>] [--page-type <t>] [--target-type <t>]'); process.exit(2); }
let inverse: string | undefined;
let pageType: string | undefined;
@@ -1254,7 +1259,7 @@ async function runAddLinkTypeCmd(args: string[]): Promise<void> {
async function runRemoveLinkTypeCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const name = args.filter((a) => !a.startsWith('--'))[0];
+ const name = (await positionals(args))[0];
if (!name) { console.error('Usage: gbrain schema remove-link-type <name>'); process.exit(2); }
try { emitMutateResult(await removeLinkTypeFromPack(packName, name), json); }
catch (e) { handleMutationError(e); }
@@ -1263,7 +1268,7 @@ async function runRemoveLinkTypeCmd(args: string[]): Promise<void> {
async function runSetExtractableCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const pos = args.filter((a) => !a.startsWith('--'));
+ const pos = await positionals(args);
if (pos.length < 2) { console.error('Usage: gbrain schema set-extractable <type> <true|false>'); process.exit(2); }
const v = parseBool(pos[1]);
if (v === null) { console.error('Second argument must be true|false'); process.exit(2); }
@@ -1274,7 +1279,7 @@ async function runSetExtractableCmd(args: string[]): Promise<void> {
async function runSetExpertRoutingCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const pos = args.filter((a) => !a.startsWith('--'));
+ const pos = await positionals(args);
if (pos.length < 2) { console.error('Usage: gbrain schema set-expert-routing <type> <true|false>'); process.exit(2); }
const v = parseBool(pos[1]);
if (v === null) { console.error('Second argument must be true|false'); process.exit(2); }
@@ -1285,7 +1290,7 @@ async function runSetExpertRoutingCmd(args: string[]): Promise<void> {
async function runScaffoldExtractableCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
const packName = pickPackName({}, args);
- const pos = args.filter((a) => !a.startsWith('--'));
+ const pos = await positionals(args, ['--dims']);
if (pos.length < 1) {
console.error('Usage: gbrain schema scaffold-extractable <type> [--pack <name>] [--dims a,b,c] [--force]');
process.exit(2);
diff --git a/test/schema-positionals-w410.test.ts b/test/schema-positionals-w410.test.ts
new file mode 100644
index 0000000000..3868e67b1e
--- /dev/null
+++ b/test/schema-positionals-w410.test.ts
@@ -0,0 +1,67 @@
+/**
+ * Wave 12 W4.10: pack-authoring `schema` subcommands read their names from the
+ * first positionals that are not flag values. `remove-type --pack mine people`
+ * used to name the type `mine`, and `add-link-type --inverse founded_by founded`
+ * silently wrote a link type called `founded_by`.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { loadPackFromFile } from '../src/core/schema-pack/loader.ts';
+import type { SchemaPackManifest } from '../src/core/schema-pack/manifest-v1.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import { schemaPositionals } from '../src/commands/schema-add-type.ts';
+
+let home: string;
+let auditDir: string;
+let packPath: string;
+
+beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-schema-positionals-'));
+ auditDir = mkdtempSync(join(tmpdir(), 'gbrain-schema-positionals-audit-'));
+ const dir = join(home, '.gbrain', 'schema-packs', 'mine');
+ mkdirSync(dir, { recursive: true });
+ const manifest = {
+ api_version: 'gbrain-schema-pack-v1', name: 'mine', version: '1.0.0', description: '',
+ gbrain_min_version: '0.38.0', extends: null, borrow_from: [],
+ page_types: [
+ { name: 'person', primitive: 'entity', path_prefixes: ['people/'], aliases: ['human'], extractable: false, expert_routing: false },
+ { name: 'company', primitive: 'entity', path_prefixes: ['companies/'], aliases: [], extractable: false, expert_routing: false },
+ ],
+ link_types: [], frontmatter_links: [], takes_kinds: ['fact', 'take', 'bet', 'hunch'], enrichable_types: [], filing_rules: [],
+ } as unknown as SchemaPackManifest;
+ packPath = join(dir, 'pack.json');
+ writeFileSync(packPath, JSON.stringify(manifest, null, 2) + '\n');
+});
+afterEach(() => { rmSync(home, { recursive: true, force: true }); rmSync(auditDir, { recursive: true, force: true }); });
+
+const cli = (...args: string[]) => runCli(['schema', ...args], { home, cwd: home, env: { GBRAIN_AUDIT_DIR: auditDir }, timeoutMs: 60_000 });
+const pack = () => loadPackFromFile(packPath);
+
+describe('W4.10: schema subcommands skip flag values when reading names', () => {
+ test('add-link-type with --inverse before the name writes the named link type', async () => {
+ expect((await cli('add-link-type', '--inverse', 'founded_by', 'founded', '--pack', 'mine')).exitCode).toBe(0);
+ const link = pack().link_types.find(l => l.name === 'founded');
+ expect(link).toBeTruthy();
+ expect(link!.inverse).toBe('founded_by');
+ expect(pack().link_types.find(l => l.name === 'founded_by')).toBeUndefined();
+ }, 90_000);
+
+ test('remove-type with --pack before the name removes that type', async () => {
+ expect((await cli('remove-type', '--pack', 'mine', 'company')).exitCode).toBe(0);
+ expect(pack().page_types.map(t => t.name)).toEqual(['person']);
+ }, 90_000);
+
+ test('remove-alias with --pack before the type and alias', async () => {
+ expect((await cli('remove-alias', '--pack', 'mine', 'person', 'human')).exitCode).toBe(0);
+ expect(pack().page_types.find(t => t.name === 'person')!.aliases).toEqual([]);
+ }, 90_000);
+
+ test('the parser skips the value of each value flag and keeps flags after the name working', () => {
+ expect(schemaPositionals(['--pack', 'mine', 'people'], [])).toEqual(['people']);
+ expect(schemaPositionals(['people', '--pack', 'mine', '--json'], [])).toEqual(['people']);
+ expect(schemaPositionals(['--inverse', 'founded_by', 'founded', '--page-type', 'person'], ['--inverse', '--page-type'])).toEqual(['founded']);
+ expect(schemaPositionals(['--pack=mine', 'people'], [])).toEqual(['people']);
+ });
+});