Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(schema): add-type --no-prefix for frontmatter-only types; name is the positional (#6135)

garrytanb2daa1d601fb
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.md
index 9c63e50ae2..78f9c0d743 100644
--- a/docs/architecture/key-files/schema-mutation.md
+++ b/docs/architecture/key-files/schema-mutation.md
@@ -23,12 +23,13 @@ Key files:
- `src/core/schema-pack/lint-rules.ts` — 14 pure rule functions. `withMutation`'s pre-write validation gate composes the 10 file-plane rules; the 4 DB-aware rules (`extractable_empty_corpus`, `mutation_count_anomaly`, `stored_type_is_alias`, `stored_type_undeclared`) need an engine (CLI `--with-db`; the stored-type pair accepts `LintOpts.sourceId` scoping, not yet threaded from the CLI). Single source of truth consumed by CLI lint + MCP `schema_lint` + the pre-write validation gate. File-plane rule `link_regex_catastrophic_backtrack` — advisory ReDoS pre-screen flagging the classic nested-quantifier shapes (`(a+)+`, `(a*)*`, `(a+)*`, `(\w+)+`) in a link_type's `inference.regex` via `NESTED_QUANTIFIER_RE`. WARNING not error: a hard reject would disable the whole pack on upgrade (pages fall back to legacy typing). The runtime input-length cap in `redos-guard.ts` is the actual safety net; this rule tells the pack author to fix the pattern.
- `src/core/schema-pack/redos-guard.ts` + `src/core/schema-pack/link-inference.ts` — ReDoS hardening for pack inference regexes. `redos-guard.ts` provides `MAX_REGEX_INPUT_CHARS` (default 64_000, env `GBRAIN_MAX_REGEX_INPUT_CHARS`) — a hard input-length cap, the real runtime safety net (catastrophic backtracking needs a long input; a link-extraction `context` is normally a sentence or short paragraph). Over the cap, `runRegexBounded` throws the tagged `RegexInputTooLargeError` and the regex is skipped (degrade-to-mentions) without entering the `node:vm`. `link-inference.ts:inferLinkTypeFromPack` no-budget branch (test contexts) routes through `runRegexBounded` so the input-length cap + per-regex vm timeout (`PER_REGEX_TIMEOUT_MS = 50`) apply on every path. Defensive hardening + diagnostics; the deterministic ~3100-file sync-wedge root cause remains open. Pinned by `test/redos-hardening.test.ts` + `test/schema-pack-lint-rules.test.ts`.
- `src/core/schema-pack/query-cache-invalidator.ts` — `invalidateQueryCache(engine, sourceId?)` DELETEs query_cache rows so cached search results bound to old page types don't survive a schema mutation.
-- `src/core/schema-pack/mutate.ts` — 8-step `withMutation` skeleton (bundled-guard → lock → read → mutator → validate → atomic write → audit → invalidate) backs the 11 single-mutation primitives: `addTypeToPack`, `removeTypeFromPack` (with reference check), `updateTypeOnPack`, `addAliasToType`, `removeAliasFromType`, `addPrefixToType`, `removePrefixFromType`, `addLinkTypeToPack`, `removeLinkTypeFromPack`, `setExtractableOnType`, `setExpertRoutingOnType`. Each primitive's business-rule validation + transform is factored into a `build*Mutator(...)` pure `(manifest) => manifest` function shared with `applyMutationsAtomic` (the `schema_apply_mutations` batch entry point) so single-call and batched mutations can never validate differently. `applyMutationsAtomic` locks + reads the pack file ONCE, applies + lint-validates every mutation in the batch against an in-memory manifest, and calls `writePackManifest` at MOST ONCE — only after the whole batch checks out — so a batch that fails partway leaves the pack file byte-identical to its pre-batch state. Atomic single write via `.tmp + fsync + rename` — the pack file on disk is NEVER partial, for either a single mutation or a batch. Inline minimal JSON→YAML emitter so YAML packs stay YAML (does NOT preserve comments — pin pack.json if you care about layout).
+- `src/core/schema-pack/mutate.ts` — 8-step `withMutation` skeleton (bundled-guard → lock → read → mutator → validate → atomic write → audit → invalidate) backs the 11 single-mutation primitives: `addTypeToPack`, `removeTypeFromPack` (with reference check), `updateTypeOnPack`, `addAliasToType`, `removeAliasFromType`, `addPrefixToType`, `removePrefixFromType`, `addLinkTypeToPack`, `removeLinkTypeFromPack`, `setExtractableOnType`, `setExpertRoutingOnType`. Each primitive's business-rule validation + transform is factored into a `build*Mutator(...)` pure `(manifest) => manifest` function shared with `applyMutationsAtomic` (the `schema_apply_mutations` batch entry point) so single-call and batched mutations can never validate differently. `applyMutationsAtomic` locks + reads the pack file ONCE, applies + lint-validates every mutation in the batch against an in-memory manifest, and calls `writePackManifest` at MOST ONCE — only after the whole batch checks out — so a batch that fails partway leaves the pack file byte-identical to its pre-batch state. Atomic single write via `.tmp + fsync + rename` — the pack file on disk is NEVER partial, for either a single mutation or a batch. Inline minimal JSON→YAML emitter so YAML packs stay YAML (does NOT preserve comments — pin pack.json if you care about layout). `AddTypeOpts.noPrefix` (batch field `no_prefix`) declares a frontmatter-only type with `path_prefixes: []` (#6135); it refuses alongside a prefix, `extractable` (lint rule `extractable_empty_corpus`) or `expertRouting` (lint rule `expert_routing_without_prefix`), and a missing prefix without it stays `INVALID_RESULT`.
- `src/core/schema-pack/stats.ts` — `runStatsCore(engine, opts)` returns per-source + aggregate page counts + coverage % + `dead_prefixes` (declared prefixes with zero matching pages — agent drilldown signal). Multi-source aware (`sourceIds[]` federated, `sourceId` single, or whole-brain). PGLite + Postgres parity via `executeRaw`. `undeclared_pages` counts pages whose non-empty type the active pack neither declares nor aliases; `coverage` is the share of pages matching the pack (untyped and undeclared both count against it). Empty brain → coverage:1.0 (vacuous truth).
- `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`.
+- `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).
- `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.md
index 41e3ae5f13..aabaaf31e6 100644
--- a/docs/architecture/schema-packs.md
+++ b/docs/architecture/schema-packs.md
@@ -137,7 +137,7 @@ classification as `schema lint --with-db`'s `stored_type_undeclared`:
undeclared type, per source against that source's pack.
Fix one by declaring it (`gbrain schema add-type <type> --primitive <p>
---prefix <dir/>`) or by rewriting the pages with a declared type. On a managed
+--prefix <dir/>`, or `--no-prefix` for a type set by frontmatter only) or by rewriting the pages with a declared type. On a managed
brain the `unify-types` job cannot apply yet, so rewrite the page with
`put_page` (read it with `get_page include_content:true`, change `type:`, put it
back). gbrain's own outputs use declared types: `gbrain report` and the dream
diff --git a/docs/schema-author-tutorial.md b/docs/schema-author-tutorial.md
index b32a908b90..e1633b74f9 100644
--- a/docs/schema-author-tutorial.md
+++ b/docs/schema-author-tutorial.md
@@ -185,6 +185,14 @@ You also exercised the full mutation skeleton: bundled-pack guard, per-pack lock
## Next steps
+**Add a type set by frontmatter only.** Some types don't live in one directory: an `archive` page can sit anywhere and is typed by its frontmatter `type: archive`. Declare it with `--no-prefix` instead of `--prefix`:
+
+```bash
+gbrain schema add-type archive --primitive concept --no-prefix
+```
+
+The pack records `path_prefixes: []`, and the output notes that pages get this type only from frontmatter, never from a file path. Every type needs one of the two: leaving out both `--prefix` and `--no-prefix` is refused (exit 2, `invalid_params`) with a copy-paste example of each, so a forgotten `--prefix` never creates a type nothing infers. `--no-prefix` can't be combined with `--extractable` or `--expert`: extractable types are checked through their prefixes (lint rule `extractable_empty_corpus`), and expert routing without a prefix misses content (lint rule `expert_routing_without_prefix`). The type name is the first argument that isn't a flag value, so `gbrain schema add-type --primitive concept archive --no-prefix` also names the type `archive`.
+
**Add a link verb.** A `researcher` can `author` a `paper`. To model that:
```bash
diff --git a/src/commands/schema-add-type.ts b/src/commands/schema-add-type.ts
new file mode 100644
index 0000000000..dd654e9c56
--- /dev/null
+++ b/src/commands/schema-add-type.ts
@@ -0,0 +1,112 @@
+/**
+ * Argument parsing for `gbrain schema add-type` (#6135).
+ *
+ * gbrain schema add-type <name> --primitive <p> (--prefix <dir/> | --no-prefix)
+ * [--extractable] [--expert] [--alias <a>]... [--pack <name>] [--json]
+ *
+ * The type name is the first positional that is not a flag value (so
+ * `--primitive concept archive` names the type `archive`). A type needs a path
+ * prefix or an explicit `--no-prefix` (a frontmatter-only type); leaving out
+ * both stays refused so a forgotten `--prefix` never creates a type nothing
+ * infers. Every refusal is an agent-first `invalid_params` (exit 2) thrown
+ * before the pack is touched.
+ */
+import type { OperationError } from '../core/ops/contract.ts';
+import { PACK_PRIMITIVES, type PackPrimitive } from '../core/schema-pack/manifest-v1.ts';
+import { usageError } from '../cli/cli-error.ts';
+
+export interface AddTypeArgs {
+ name: string;
+ primitive: PackPrimitive;
+ prefix?: string;
+ noPrefix: boolean;
+ extractable: boolean;
+ expert: boolean;
+ aliases: string[];
+}
+
+export const NO_PREFIX_NOTE = 'No path prefix: pages get this type only from frontmatter `type:`; it is never inferred from a file path.';
+
+const USAGE = 'gbrain schema add-type <name> --primitive <p> (--prefix <dir/> | --no-prefix) [--extractable] [--expert] [--alias <a>] [--pack <name>] [--json]';
+const VALUE_FLAGS = new Set(['--primitive', '--prefix', '--alias', '--pack', '--source', '--source-id']);
+const NO_PREFIX_CONFLICTS: Record<string, string> = {
+ '--extractable': 'Extractable types are checked through their path prefixes (lint rule extractable_empty_corpus), so a type without one cannot be extractable.',
+ '--expert': 'Expert routing without a path prefix silently misses content (lint rule expert_routing_without_prefix).',
+ '--expert-routing': 'Expert routing without a path prefix silently misses content (lint rule expert_routing_without_prefix).',
+};
+
+const INPUT_HOW: Record<string, string> = {
+ NAME: 'The new type name, a slug such as researcher or archive.',
+ PRIMITIVE: `One of ${PACK_PRIMITIVES.join(', ')}.`,
+ 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>.',
+};
+
+/** 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));
+}
+
+/** One complete corrected command: every missing piece becomes a `<PLACEHOLDER>` named in `inputs`. */
+function refusal(message: string, suggestion: string, why: string, argv: string[]): OperationError {
+ const inputs = Object.keys(INPUT_HOW).filter(n => argv.includes(`<${n}>`)).map(name => ({ name, how: INPUT_HOW[name]! }));
+ return usageError(message, suggestion, {
+ why,
+ fix: { argv: ['gbrain', 'schema', 'add-type', ...argv], ...(inputs.length ? { inputs } : {}), consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'The corrected command adds the type.' },
+ });
+}
+
+/** Parse `schema add-type` args; throws an `invalid_params` OperationError on any refusal. */
+export function parseAddTypeArgs(args: string[]): AddTypeArgs {
+ const positional: string[] = [];
+ const aliases: string[] = [];
+ const values: Record<string, string | undefined> = {};
+ const seen = new Set<string>();
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]!;
+ const eq = a.indexOf('=');
+ const flag = a.startsWith('--') && eq > 0 ? a.slice(0, eq) : a;
+ if (!flag.startsWith('--')) { positional.push(a); continue; }
+ seen.add(flag);
+ if (!VALUE_FLAGS.has(flag)) continue;
+ const value = flag !== a ? a.slice(eq + 1) : args[++i];
+ if (flag === '--alias') { if (value !== undefined) aliases.push(value); } else values[flag] = value;
+ }
+ const name = positional[0];
+ const primitive = values['--primitive'];
+ const validPrimitive = !!primitive && (PACK_PRIMITIVES as readonly string[]).includes(primitive);
+ const prefix = values['--prefix'];
+ const noPrefix = seen.has('--no-prefix');
+ const repaired = [
+ ...(name ? [] : ['<NAME>']),
+ ...(validPrimitive ? args : withoutFlag(args, '--primitive')),
+ ...(validPrimitive ? [] : ['--primitive', '<PRIMITIVE>']),
+ ...(prefix || noPrefix ? [] : ['--prefix', '<PREFIX>']),
+ ];
+ if (!name) {
+ throw refusal('schema add-type needs a type name.', `Usage: ${USAGE}`, 'The type name is the first argument that is not a flag value.', repaired);
+ }
+ if (!validPrimitive) {
+ throw refusal(`--primitive must be one of ${PACK_PRIMITIVES.join('|')}`, `Usage: ${USAGE}`, 'Every page type maps to one primitive.', repaired);
+ }
+ const withoutNoPrefix = args.filter(a => a !== '--no-prefix');
+ if (noPrefix && prefix !== undefined) {
+ throw refusal('--prefix and --no-prefix cannot be combined.', 'Keep --prefix <dir/> for a type inferred from file paths, or only --no-prefix for a type set by frontmatter only.',
+ '--no-prefix declares a type with no path prefix, which contradicts --prefix.', withoutNoPrefix);
+ }
+ const conflict = noPrefix ? Object.keys(NO_PREFIX_CONFLICTS).find(f => seen.has(f)) : undefined;
+ if (conflict) {
+ throw refusal(`--no-prefix cannot be combined with ${conflict}.`, `Give the type a prefix (--prefix people/researchers/) or drop ${conflict}.`,
+ NO_PREFIX_CONFLICTS[conflict]!, [...withoutNoPrefix, '--prefix', '<PREFIX>']);
+ }
+ if (!prefix && !noPrefix) {
+ throw refusal('schema add-type needs --prefix <dir/> or --no-prefix.',
+ `Pass the directory its pages live in (--prefix people/researchers/), or --no-prefix for a type set by frontmatter only: gbrain schema add-type ${name} --primitive ${primitive} --no-prefix`,
+ 'A path prefix lets gbrain infer the type from where a file lives; --no-prefix declares a type pages get only from frontmatter `type:`. Leaving out both is refused so a forgotten --prefix never creates a type nothing infers.',
+ repaired);
+ }
+ return {
+ name, primitive: primitive as PackPrimitive, prefix, noPrefix,
+ extractable: seen.has('--extractable'), expert: seen.has('--expert') || seen.has('--expert-routing'), aliases,
+ };
+}
diff --git a/src/commands/schema.ts b/src/commands/schema.ts
index 2b60a19b66..c237c9d6e7 100644
--- a/src/commands/schema.ts
+++ b/src/commands/schema.ts
@@ -1141,37 +1141,24 @@ function runReloadCmd(args: string[]): void {
async function runAddTypeCmd(args: string[]): Promise<void> {
const { json } = parseFlags(args);
- const packName = pickPackName({}, args);
- const positional = args.filter((a) => !a.startsWith('--'));
- const name = positional[0];
- if (!name) { console.error('Usage: gbrain schema add-type <name> --primitive <p> --prefix <dir/>'); process.exit(2); }
- let primitive: string | undefined;
- let prefix: string | undefined;
- let extractable = false;
- let expert = false;
- const aliases: string[] = [];
- for (let i = 0; i < args.length; i++) {
- const a = args[i];
- if (a === '--primitive') primitive = args[++i];
- else if (a?.startsWith('--primitive=')) primitive = a.slice('--primitive='.length);
- else if (a === '--prefix') prefix = args[++i];
- else if (a?.startsWith('--prefix=')) prefix = a.slice('--prefix='.length);
- else if (a === '--extractable') extractable = true;
- else if (a === '--expert' || a === '--expert-routing') expert = true;
- else if (a === '--alias') aliases.push(args[++i]!);
- else if (a?.startsWith('--alias=')) aliases.push(a.slice('--alias='.length));
- }
- if (!primitive || !PACK_PRIMITIVES.includes(primitive as PackPrimitive)) {
- console.error(`--primitive must be one of ${PACK_PRIMITIVES.join('|')}`);
- process.exit(2);
+ const { parseAddTypeArgs, NO_PREFIX_NOTE } = await import('./schema-add-type.ts');
+ let parsed: import('./schema-add-type.ts').AddTypeArgs;
+ try {
+ parsed = parseAddTypeArgs(args);
+ } catch (e) {
+ const { writeCliRefusal } = await import('../cli/cli-error.ts');
+ const err = e as import('../core/ops/contract.ts').OperationError;
+ process.exit(writeCliRefusal(err, 'schema', { json, human: `${err.message}\n ${err.suggestion}` }));
}
- if (!prefix) { console.error('--prefix is required (e.g. --prefix people/researchers/)'); process.exit(2); }
+ const packName = pickPackName({}, args);
try {
const result = await addTypeToPack(packName, {
- name, primitive: primitive as PackPrimitive, prefix,
- extractable, expertRouting: expert, aliases,
+ name: parsed.name, primitive: parsed.primitive, prefix: parsed.prefix, noPrefix: parsed.noPrefix,
+ extractable: parsed.extractable, expertRouting: parsed.expert, aliases: parsed.aliases,
});
- emitMutateResult(result, json);
+ const output: typeof result & { note?: string } = parsed.noPrefix ? { ...result, note: NO_PREFIX_NOTE } : result;
+ emitMutateResult(output, json);
+ if (parsed.noPrefix && !json) console.log(`Note: ${NO_PREFIX_NOTE}`);
} catch (e) { handleMutationError(e); }
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 428783c13b..fee1188af5 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -113,7 +113,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
- 'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
+ 'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
diff --git a/src/core/schema-pack/mutate.ts b/src/core/schema-pack/mutate.ts
index 006db56c7d..a0cc05f902 100644
--- a/src/core/schema-pack/mutate.ts
+++ b/src/core/schema-pack/mutate.ts
@@ -523,7 +523,10 @@ function checkNoReferences(manifest: SchemaPackManifest, typeName: string): void
export interface AddTypeOpts {
name: string;
primitive: PackPrimitive;
- prefix: string;
+ /** Required unless `noPrefix` is set. */
+ prefix?: string;
+ /** Declare a frontmatter-only type (`path_prefixes: []`, #6135). */
+ noPrefix?: boolean;
extractable?: boolean;
expertRouting?: boolean;
aliases?: string[];
@@ -536,10 +539,22 @@ export interface AddTypeOpts {
// (batch path, below) reuses the SAME builders so single-call and batched
// mutations can never drift in what they accept or reject.
+function validateNoPrefix(opts: AddTypeOpts): void {
+ const conflict = opts.prefix !== undefined
+ ? 'a frontmatter-only type takes a prefix or noPrefix, not both'
+ : opts.extractable
+ ? 'a frontmatter-only type cannot be extractable: extractable types are checked through their path prefixes (lint rule extractable_empty_corpus)'
+ : opts.expertRouting
+ ? 'a frontmatter-only type cannot use expert routing: expert routing without a path prefix silently misses content (lint rule expert_routing_without_prefix)'
+ : null;
+ if (conflict) throw new SchemaPackMutationError('INVALID_RESULT', `${conflict} (type: ${JSON.stringify(opts.name)})`);
+}
+
function buildAddTypeMutator(opts: AddTypeOpts): (m: SchemaPackManifest) => SchemaPackManifest {
validateTypeName(opts.name);
validatePrimitive(opts.primitive);
- validatePrefix(opts.prefix);
+ if (opts.noPrefix) validateNoPrefix(opts);
+ else validatePrefix(opts.prefix);
return (m) => {
if (m.page_types.some((pt) => pt.name === opts.name)) {
throw new SchemaPackMutationError(
@@ -551,7 +566,7 @@ function buildAddTypeMutator(opts: AddTypeOpts): (m: SchemaPackManifest) => Sche
const newType: PackPageType = {
name: opts.name,
primitive: opts.primitive,
- path_prefixes: [opts.prefix],
+ path_prefixes: opts.noPrefix ? [] : [opts.prefix!],
aliases: opts.aliases ?? [],
extractable: opts.extractable ?? false,
expert_routing: opts.expertRouting ?? false,
@@ -769,7 +784,8 @@ function buildBatchMutator(
mutate: buildAddTypeMutator({
name: m.name as string,
primitive: m.primitive as never,
- prefix: m.prefix as string,
+ prefix: m.prefix as string | undefined,
+ noPrefix: m.no_prefix === true,
extractable: m.extractable as boolean | undefined,
expertRouting: m.expert_routing as boolean | undefined,
aliases: m.aliases as string[] | undefined,
diff --git a/test/schema-add-type-no-prefix.test.ts b/test/schema-add-type-no-prefix.test.ts
new file mode 100644
index 0000000000..5228e6c23f
--- /dev/null
+++ b/test/schema-add-type-no-prefix.test.ts
@@ -0,0 +1,151 @@
+/**
+ * #6135: `schema add-type --no-prefix` declares a type pages get only from
+ * frontmatter (`path_prefixes: []`). Leaving out both `--prefix` and
+ * `--no-prefix` is still refused, and the refusal names both choices;
+ * `--no-prefix` with `--extractable` / `--expert` is refused naming the flag and
+ * the lint rule. The type name is the first positional, never a flag value.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { addTypeToPack, applyMutationsAtomic } from '../src/core/schema-pack/mutate.ts';
+import { computeMutateAuditPath } from '../src/core/schema-pack/mutate-audit.ts';
+import { loadPackFromFile } from '../src/core/schema-pack/loader.ts';
+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
+import type { SchemaPackManifest } from '../src/core/schema-pack/manifest-v1.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+import { parseAddTypeArgs } from '../src/commands/schema-add-type.ts';
+import type { OperationError } from '../src/core/ops/contract.ts';
+
+let home: string;
+let auditDir: string;
+let lockDir: string;
+let packPath: string;
+
+function seedPack(): string {
+ const dir = join(home, '.gbrain', 'schema-packs', 'my-pack');
+ mkdirSync(dir, { recursive: true });
+ const manifest = {
+ api_version: 'gbrain-schema-pack-v1', name: 'my-pack', 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: [], extractable: false, expert_routing: false }],
+ link_types: [], frontmatter_links: [], takes_kinds: ['fact', 'take', 'bet', 'hunch'], enrichable_types: [], filing_rules: [],
+ } as unknown as SchemaPackManifest;
+ const path = join(dir, 'pack.json');
+ writeFileSync(path, JSON.stringify(manifest, null, 2) + '\n');
+ return path;
+}
+
+const typeNamed = (name: string) => loadPackFromFile(packPath).page_types.find(t => t.name === name);
+
+beforeEach(() => {
+ _resetPackCacheForTests();
+ home = mkdtempSync(join(tmpdir(), 'gbrain-add-type-no-prefix-'));
+ auditDir = mkdtempSync(join(tmpdir(), 'gbrain-add-type-audit-'));
+ lockDir = mkdtempSync(join(tmpdir(), 'gbrain-add-type-locks-'));
+ packPath = seedPack();
+});
+
+afterEach(() => {
+ _resetPackCacheForTests();
+ for (const d of [home, auditDir, lockDir]) rmSync(d, { recursive: true, force: true });
+});
+
+const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: auditDir }, fn);
+
+describe('#6135 addTypeToPack noPrefix (core)', () => {
+ test('writes path_prefixes: [], validates and records an audit row', async () => {
+ await inHome(async () => {
+ await addTypeToPack('my-pack', { name: 'archive', primitive: 'concept', noPrefix: true }, { lockDir });
+ expect(typeNamed('archive')).toMatchObject({ primitive: 'concept', path_prefixes: [] });
+ const rows = readFileSync(computeMutateAuditPath(), 'utf-8').trim().split('\n').map(l => JSON.parse(l));
+ expect(rows.some(r => r.op === 'add_type' && r.outcome === 'success' && r.prefix_first_seg === null)).toBe(true);
+ });
+ });
+
+ test('refuses noPrefix with extractable or expert routing, naming the lint rule', async () => {
+ await inHome(async () => {
+ await expect(addTypeToPack('my-pack', { name: 'archive', primitive: 'concept', noPrefix: true, extractable: true }, { lockDir }))
+ .rejects.toThrow(/extractable_empty_corpus/);
+ await expect(addTypeToPack('my-pack', { name: 'archive', primitive: 'concept', noPrefix: true, expertRouting: true }, { lockDir }))
+ .rejects.toThrow(/expert_routing_without_prefix/);
+ await expect(addTypeToPack('my-pack', { name: 'archive', primitive: 'concept', noPrefix: true, prefix: 'archive/' }, { lockDir }))
+ .rejects.toThrow(/not both/);
+ expect(typeNamed('archive')).toBeUndefined();
+ });
+ });
+
+ test('the batch path accepts no_prefix through the same mutator', async () => {
+ await inHome(async () => {
+ await applyMutationsAtomic('my-pack', [{ op: 'add_type', name: 'archive', primitive: 'concept', no_prefix: true }], { lockDir });
+ expect(typeNamed('archive')).toMatchObject({ path_prefixes: [] });
+ });
+ });
+});
+
+describe('#6135 schema add-type CLI', () => {
+ const cli = (args: string[]) => runCli(['schema', 'add-type', ...args, '--pack', 'my-pack'],
+ { home, cwd: home, env: { GBRAIN_AUDIT_DIR: auditDir }, timeoutMs: 60_000 });
+
+ test('--no-prefix adds a frontmatter-only type and says so', async () => {
+ const r = await cli(['archive', '--primitive', 'concept', '--no-prefix', '--json']);
+ expect(r.exitCode, r.stderr).toBe(0);
+ expect(JSON.parse(r.stdout).note).toContain('frontmatter');
+ expect(typeNamed('archive')).toMatchObject({ primitive: 'concept', path_prefixes: [] });
+ }, 90_000);
+
+ test('the type name is the positional, not a flag value', async () => {
+ const r = await cli(['--primitive', 'concept', 'archive', '--prefix', 'archive/']);
+ expect(r.exitCode, r.stderr).toBe(0);
+ expect(typeNamed('archive')).toMatchObject({ primitive: 'concept', path_prefixes: ['archive/'] });
+ expect(typeNamed('concept')).toBeUndefined();
+ }, 90_000);
+
+ test('missing both --prefix and --no-prefix is refused naming both choices', async () => {
+ const r = await cli(['archive', '--primitive', 'concept', '--json']);
+ expect(r.exitCode).toBe(2);
+ const doc = JSON.parse(r.stdout);
+ expect(doc.code).toBe('invalid_params');
+ const text = `${doc.message} ${doc.suggestion}`;
+ expect(text).toContain('--prefix people/researchers/');
+ expect(text).toContain('--no-prefix');
+ expect(typeNamed('archive')).toBeUndefined();
+ }, 90_000);
+
+ test('--no-prefix with --extractable or --expert is refused naming the flag and lint rule', async () => {
+ for (const [flag, rule] of [['--extractable', 'extractable_empty_corpus'], ['--expert', 'expert_routing_without_prefix']]) {
+ const r = await cli(['archive', '--primitive', 'concept', '--no-prefix', flag, '--json']);
+ expect(r.exitCode, flag).toBe(2);
+ const doc = JSON.parse(r.stdout);
+ expect(doc.code).toBe('invalid_params');
+ expect(doc.message).toContain(flag);
+ expect(`${doc.message} ${doc.why}`).toContain(rule);
+ }
+ expect(typeNamed('archive')).toBeUndefined();
+ }, 90_000);
+});
+
+describe('#6135 add-type refusal fixes are runnable commands', () => {
+ const fill: Record<string, string> = { '<NAME>': 'archive', '<PRIMITIVE>': 'concept', '<PREFIX>': 'archive/' };
+ const refusals: string[][] = [
+ ['--primitive', 'concept'],
+ ['archive'],
+ ['archive', '--primitive', 'concept'],
+ ['archive', '--primitive', 'concept', '--no-prefix', '--extractable'],
+ ['archive', '--primitive', 'concept', '--no-prefix', '--expert'],
+ ['archive', '--primitive', 'concept', '--no-prefix', '--prefix', 'archive/'],
+ ];
+ for (const args of refusals) {
+ test(`fix for [${args.join(' ')}] parses under the same parser`, () => {
+ let err: OperationError | undefined;
+ try { parseAddTypeArgs(args); } catch (e) { err = e as OperationError; }
+ expect(err?.code).toBe('invalid_params');
+ const argv = err!.fix!.argv!;
+ expect(argv.slice(0, 3)).toEqual(['gbrain', 'schema', 'add-type']);
+ for (const input of err!.fix!.inputs ?? []) expect(argv).toContain(`<${input.name}>`);
+ expect(() => parseAddTypeArgs(argv.slice(3).map(a => fill[a] ?? a))).not.toThrow();
+ });
+ }
+});