Garry's Opinionated OpenClaw/Hermes Agent Brain
Schema packs: mutation surface (key files cluster)
The schema-pack mutation surface: six foundation modules + a mutate skeleton + stats/sync data plane + CLI verbs + MCP ops + a first-class agent skill.
Key files:
src/core/persistence/staging.ts— journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. Stage digests are read in pieces (large-file.tshashDescriptor). Wave B: abeforestage (.<sha256>.tmp.before-<uuid>, a name older binaries refuse) holds the copy of a prior canonical file over 24 MiB; a live request's recovery keeps it (cleanupRecoveryStaging(record, { keepBefore })) untilrestoreBeforeStagerenames it back over the file with its recorded mode or it is removed because the file already holds the prior bytes. A publication stage's stream still under its in-progress name (<stage>.streaming) is removed unread bycleanupRecoveryStaginganddiscardStreamingStage(never published; its bytes are produced again) and must be absent for final accounting; a partial file at the stage's own name still refuses.publishStreamedStageis the forward half of a version 2 withdrawal-mirror record (effect-model.ts): its verified publication stage, streamed from a segmented page's segments, is renamed over the canonical file; a missing stage refusesunexpected_staging_bytes. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests:atomic-write.test.ts,atomic-long-staging.test.ts,persistence-staging.test.ts, and eight-boundary process-crash harness.src/core/fs-durable.ts— the shared durable-flush leaf (imports onlynode:fs).flushFile(path)fsyncs a file nobody holds open through'r+'on win32 (WindowsFlushFileBuffersneeds write access) and'r'elsewhere (a 0444 file stays flushable); a read-only file on win32 cannot be opened writable and is left to the OS.flushDirectory(path, { bestEffort })is strict by default: every error propagates except the win32 no-directory-flush codes (EISDIR/EPERM/EINVAL/ENOTSUP), a non-directory path failsENOTDIR, andbestEffortswallows everything.sameFileMode(actual, expected)compares every permission bit on POSIX and only the owner write bit on win32, whose stat reports 0444/0666. A writer that still holds its descriptor sets the mode withfchmodSync(fd)and fsyncs that descriptor instead (atomic-write, skill-bundle staging). Callers: atomic-write, the persistence coordinator, identity, root registry, physical-root records, reconcile backups, recovery staging, topology checkouts (flushTopologyDirectoryre-export,flushTopologyTree), skill bundles, agent-install state (syncDirectoryre-export),sources reconcilepreviews and attendance-repair checkpoints.scripts/check-durable-flush.tskeeps new read-handle flushes out ofsrc/(docs/ci-guards.md#durable-flush-guard). Tests:test/fs-durable.test.ts,test/persistence-windows-flush-5595.test.ts,test/bundle-files-windows-5475.test.ts,test/init-packaged-skills-native.test.ts, run natively on windows-latest in the test.yml security-regressions job.src/core/atomic-write.ts— the shared atomic file writer for brain-repo markdown writers: unique short hidden tmp sibling fromatomicStagingPath(.<sha256(full target path)>.tmp.<uuid>, so a valid basename near NAME_MAX still stages, #5861;validateAtomicStagingPathalso accepts the historical<target>.tmp.<uuid>journal form, and recovery (persistence/staging.tsupgradeRecoveryStaging) durably swaps in a short stage only for a recorded historical leaf that returns ENAMETOOLONG;timeline-write-through.tsreuses the same allocator) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optionalverify(onDiskBytes)callback (throw = abort, tmp removed, target untouched) → atomic rename → parent-directory fsync throughfs-durable.tsflushDirectory(rename durability; strict underdurable, the journaled-publication flag, best-effort otherwise). The stage is opened with its final mode andfchmod-ed on the descriptor past the umask before any byte is written:AtomicWriteOpts.modesets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask.mkdirPrivate(dir, root = dir)creates gbrain-private directories: a missingrootgets default-permission ancestors and is itself made exactly 0700, each missing directory betweenrootanddiris created 0700 (O_NOFOLLOWfchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed;diroutsiderootthrows. Consumers of the private modes: the Google connector (google-source.ts,sources-ops.tsGoogle add) and the persistence coordinator's Google publication. Consumed bysrc/commands/backlinks.ts(which verifies withparseMarkdown({validate:true})before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it withwithPageLock(backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.src/core/schema-pack/unify-types-handler.ts+src/core/onboard/checks.ts(checkPackUpgradeAvailable) — pack-upgrade retype (runUnifyTypes, theunify-typesjob). #6196: on a managed brain apply runs the dry run first (applyOnManagedBrain): with nothing to retype, link or alias it only switches the active pack (flipActivePack, DB + file plane); otherwise it refuseswriter_coordinator_requiredwith the counts and a read-onlygbrain onboard --check --explainfix before any lock or write, and the dry run warns that apply waits for coordinated retype.pack_upgrade_availableon a managed brain is an info row (readiness_state: degraded) with that preview as its fix and nounify-typesapply remediation it could not run. Coordinated retype (D2) is deferred.src/core/onboard/checks.ts(checkTypeProliferation) — doctor/onboardtype_proliferation(#6289): oneSELECT DISTINCT source_id, typeread; each source resolves its own pack throughloadActivePackForLocalEngine(engine, { sourceId })(per-source DB config included); sources sharing a pack pool their labels, an alias counts as its canonical type (classifyStoredType), and each pool is graded with the unchanged thresholds (warn above declared + 5, fail above declared × 2). The message names the worst pool's sources, pack and up to five undeclared labels. A source whose pack does not resolve, or a failed query, warns "not verified", never ok. Pinned bytest/onboard-pack-upgrade-checks.test.ts.src/core/schema-pack/pack-lock.ts— AtomicO_CREAT|O_EXCLper-pack lock. DELIBERATELY NOT theexistsSync + writeFileSyncTOCTOU shape fromsrc/core/page-lock.ts. Default 60s TTL, refresh every 10s whilewithPackLock(fn)runs,--forcesemantics = "steal stale lock" NOT "skip locking." Lock path per-pack so two packs never block each other.src/core/schema-pack/write-vocabulary.ts— write-time pack-vocabulary enforcement shared by the write surfaces (capture op,add_linkop,gbrain captureCLI).loadActivePackForWriteVocabulary(ctx)pairs the engine's DB-planeschema_packkey with FILE-ONLY config (theloadActivePackForLocalEngineposture) while threadingremote(fail-closed: anything not strictly false is remote) +sourceId; NEVER throws — null means "no resolvable pack", which callers MUST treat as "no vocabulary to enforce" (the write proceeds exactly as before).packDeclaresPageType/packDeclaresLinkType+ message/suggestion formatters reject an EXPLICIT undeclared name with the pack's declared vocabulary in the error so agents self-correct without agbrain schema explainround-trip. The DEFAULTnotepath is never checked here — callers validate EXPLICIT names only, so baregbrain captureworks under a pack that doesn't declarenote.loadActivePackForWriteVocabularyalso swallows a rejectinggetConfig;previewNamesbounds the vocabulary preview in the error (the first 12 names +(N total)). Pinned bytest/write-vocabulary.test.ts.src/core/schema-pack/mutate-audit.ts— ISO-week JSONL at~/.gbrain/audit/schema-mutations-YYYY-Www.jsonl. Privacy-redacted: type names → sha8, prefixes → first slug segment only, matchescandidate-audit.tsprivacy posture. Logs BOTH success AND failure events so a futureschema_pack_writabilitydoctor check has signal.summarizeMutations()is the cross-surface parity primitive.src/core/schema-pack/registry.ts—resolvePackwalks theextendschain (depth cap viaEXTENDS_DEPTH_WARN/EXTENDS_DEPTH_HARD_CAP), RETAINS each ancestor manifest, materializesborrow_from, and composes all of it intoresolved.manifestthroughmergeInheritedManifest. Every downstream consumer readsresolved.manifest, so doing the merge here is what makes inheritance visible without per-consumer wiring.borrow_fromis selective (only the namedtypes/link_types, and only from the target's OWN declarations), non-transitive, and fail-closed — a missing target throwsUnknownPackErrorvialoadByName, matching the extends path; an omitted category borrows none of it. The alias graph + closure hash are computed on the MERGED manifest, so a cross-pack alias cycle surfaces asAliasCycleErrorat resolve.manifest_sha8/packIdentitystay the CHILD's own bytes — a parent edit does not move the child's identity, so the invalidation path is what keeps a child honest.invalidatePackCache(name?)walks the extends-chain reverse-graph (editing a parent pack must not leave children stale).tryCachedPack(name)TTL-gated fast path: insideSTAT_TTL_MS(default 1000ms, envGBRAIN_PACK_STAT_TTL_MS) returns cached without statting; outside the window it stats every TRACKED file — the extends chain PLUS every borrowed pack — and cascade-invalidates on mtime change (cross-process detection), so editing a borrowed pack invalidates its borrowers. Pinned bytest/schema-pack-registry.test.ts+test/schema-pack-merge.test.ts.src/core/schema-pack/merge.ts— the pure child-wins composition helper behindresolvePack.mergeInheritedManifest(ancestorsBaseFirst, child, borrowed)returns the fully-composed manifest; precedence is child → borrowed → nearest parent … → base. SIX ingest/query-shaping fields inherit:page_types,link_types,frontmatter_links,enrichable_types,filing_rules,takes_kinds.phases+calibration_domainsare DELIBERATELY child-only — they gate real cycle execution (cycle.tspackDeclaresPhase), so inheriting them would silently run phases a pack never declared;mapping_rules,migration_from,extends,borrow_from, and the identity fields are child-only too (all ride the...childspread).mergePageTypescarries the ordering contractinferTypeFromPackdepends on (first-path_prefix-match-wins, array order): the BASE (root,extends: null) pack is the ordered foundation/tail; an override of a base type keeps the base POSITION (Map.setupdates the value, keeps insertion order) so base's curated priority survives; a genuinely-new type from ANY non-base layer — child, borrowed, or a middle pack — is PREPENDED nearest-first, so a more-derived prefix wins regardless of chain depth.mergeByKeykeeps the first occurrence per key walking highest-precedence-first (the order-insensitive keyed fields);frontmatter_linkskeys onpage_type\x00link_type— a NUL, not a space, because both are unconstrained strings and a space-join would collide{"a b","c"}with{"a","b c"}.mergeUnionbackstakes_kinds: UNION not replace, because the Zod default makes an omitted field indistinguishable from an explicit one — so a child can ADD kinds but CANNOT narrow below base ∪ parent. Pure + deterministic: no disk, no engine. Pinned bytest/schema-pack-merge.test.ts.src/core/schema-pack/engine-resolution.ts— schema-only live-engine boundary shared by best-effort, write vocabulary, op trust, import/sync, managed prepared import, and the MCP inspection ops (get_active_schema_pack,schema_explain_type,schema_graph,schema_linton the active pack; #7942,test/schema-pack-source-inspection-7942.test.ts).engineSchemaInputreads selected-engine brain/source schema keys, using file-only config for the fallback while retaining per-call/environment precedence; it never merges model/provider settings. DB lookup failures propagate; only absent/empty keys permit fallback. Best-effort wrappers return null on failure instead of selecting host vocabulary.approvedSchemaIdentityhashes the full resolved manifest, including inherited link/inference definitions, independently of the alias-only hash.checkApprovedSchemaForEnginebypasses the registry TTL and rejects changed approved identities, untrusted callers, conflicting explicit/environment/per-source overrides, and unreadable DB state. It is read-only:allowBindingreturns only{key: 'schema_pack', value, expectedValue}for the caller's selected-DB admission transaction. The caller must check destination compatibility/emptiness and apply the binding under its lifecycle lock/CAS; this helper neither authorizes that write nor writes host config. Tests:test/schema-engine-isolation.serial.test.ts.src/core/schema-pack/query-types.ts— expands scalar/multiple type filters through the selected engine's active alias graph. Scalar and array filters retain intersection semantics; explicit empty arrays deny before any engine/cache access. Missing packs yield an empty filter that consumers return as no results, never as an unrestricted query; DB lookup failures propagate through keyword, hybrid and image readers. Mixed-pack explicit source scopes refuse rather than arbitrarily choosing a closure. Used by hybrid search and the search/query keyword-only/image bypasses; typed hybrid requests bypass semantic result caching. Tests:test/schema-engine-isolation.serial.test.ts,test/ops-search-types.test.ts.src/core/schema-pack/entity-types.ts— #4772: the one answer to "is this stored type an entity" for the counters.entityTypesFromPack(manifest)returns the pack'sprimitive: entitytype names (plus undeclared aliases of them) and the legacy names (entity,person,company,organization) the pack leaves undeclared; a pack that declares a legacy name under another primitive reclassified it and wins.resolveEntityTypes(engine, scope)resolves per source (every requested source id, or brain-wide: the brain's pack plus every registered source with aschema_pack.source.<id>override) into anEntityTypeFilter(default list + per-source lists that differ), and returnspack_unavailablewith an empty filter when any pack in scope fails to load (thebest-effort.tsnull contract: empty filter, never hardcoded defaults).entityTypePredicateSql(alias, filter)renders it as a parameter-boundsqlFragment. #6953:personTypesFromPack/resolvePersonTypesanswer "is this type person-like" the same way (per source, samepack_unavailablecontract):personplus its alias closure (closure.ts), never primitive siblings; consumercycle/edge-contradictions.ts: itsworks_atmembers are admitted before grouping and LIMIT only when the subject is person-like by its source's pack (a pack that does not load admits none) and the target is neither person-like nor aNON_EMPLOYER_TYPEStype (untyped:NON_EMPLOYER_PREFIXES; both lists shared withlink-target-roles.ts'stargetTakesVerb); an open proposal made before that rule is not re-checked when applied (test/edge-employment-roles.test.ts+ Postgres twin;personTypesFromPackintest/schema-pack-person-types-6953.test.ts). Consumers:engine-sql/health.tsthroughHealthDeps.entityTypes(both engines delegate),commands/doctor/checks/graph-health.ts(graph_coverage,orphan_ratio),onboard/checks.ts(entity_link_coverage,timeline_coverage, andvisibleEntityCoverageSqlforonboard/impact-capture.ts; a pack that does not load warnsentity_types_unavailable),onboard/mcp-onboarding.ts(the three entity counts arenullwithentityTypesStatus: pack_unavailable; the timeline result predicate) andextract-ner.ts(the target-type map;pack_unavailablewhen a source's pack does not load).mentions/policy.tskeeps its own linkable-type union. Pinned bytest/onboard-entity-types-pack-4772.test.ts. Lazy-imports the pack loader so the engines can import it statically.src/core/schema-pack/best-effort.ts—loadActivePackBestEffort(ctx)returnsResolvedPack | null. Single source of truth for the pack-aware wiring sites.nullmeans EMPTY FILTER (NOT hardcoded defaults, which would silently violate the pack). Threads the tier-4 DB-planeschema_packfromctx.engine, so every caller resolves the SAME packschema active/get_active_schema_packreport.readDbSchemaPack(engine?)is the ONE spelling of that tier-4 read (null-safe, propagates DB read failures, trims missing/empty values to undefined) — shared by both loaders here, the CLI inspection verbs (schema show/graph/lint/explain, viareadDbSchemaPackConfiginsrc/commands/schema.ts, which keeps the cfg-null gate so an unconfigured home never cold-creates a PGLite dir) and the MCPschema_lint/schema_graph/schema_explain_typeops.loadActivePackForLocalEngine(engine)is theremote: false+ FILE-ONLY-config variant for local engine-backed surfaces. Pinned bytest/schema-pack-best-effort.test.ts,test/operations-schema-pack.test.ts,test/schema-cli-db-config.test.ts.src/core/schema-pack/type-usage.ts— stored-type classifier behind the alias-footgun visibility surfaces:classifyStoredType(type, pack)→ canonical | alias_of (with the canonical type +path_prefixes[0]filing directory) | undeclared, over a STRUCTURAL pack shape so import-file's thinactivePackand the full manifest both satisfy it.sanitizeTypeForDisplaystrips control chars + caps length (type strings come from frontmatter and get echoed into terminals);renderTypeWarningSummaryrenders the once-per-type-per-run lines. Consumers:importFromContent(advisoryImportResult.type_warningat the typeExplicit site — the type is still stored literally, zero filing change), sync/import summary aggregation (+SyncResult.type_warningsso worker-driven syncs surface counts in job results), thestored_type_is_alias/stored_type_undeclareddata-plane lint rules, all gated by configschema.type_warnings(default on; lint rules always active).storedTypeMissesPack(type, pack)(empty type, or undeclared) is the one predicate every pack-conformance surface uses:findTypeOrphans(schema-pack/review.ts),schema_statscoverage, doctorschema_pack_consistency,gbrain lint'stype-undeclaredrule.WRITER_OWNED_PAGE_SQLexempts pages gbrain's own writers wrote, judged by provenance (a code importer page,typeandpage_kindbothcode; adream_generatedextract_receiptunderextracts/), from doctorschema_pack_consistency's undeclared count, so a custom pack copied before gbrain-base-v2 declared those types (#6818) is not reported as drift, while a user's Markdown page typedcodestill is (#8815,test/doctor-schema-pack-own-types-8815.test.ts). Pinned bytest/schema-type-usage.test.tsandtest/schema-pack-type-conformance.test.ts.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 acceptsLintOpts.sourceIdscoping, not yet threaded from the CLI). Single source of truth consumed by CLI lint + MCPschema_lint+ the pre-write validation gate. File-plane rulelink_regex_catastrophic_backtrack— advisory ReDoS pre-screen flagging the classic nested-quantifier shapes ((a+)+,(a*)*,(a+)*,(\w+)+) in a link_type'sinference.regexviaNESTED_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 inredos-guard.tsis 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.tsprovidesMAX_REGEX_INPUT_CHARS(default 64_000, envGBRAIN_MAX_REGEX_INPUT_CHARS) — a hard input-length cap, the real runtime safety net (catastrophic backtracking needs a long input; a link-extractioncontextis normally a sentence or short paragraph). Over the cap,runRegexBoundedthrows the taggedRegexInputTooLargeErrorand the regex is skipped (degrade-to-mentions) without entering thenode:vm.link-inference.ts:inferLinkTypeFromPackno-budget branch (test contexts) routes throughrunRegexBoundedso 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 bytest/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-stepwithMutationskeleton (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 abuild*Mutator(...)pure(manifest) => manifestfunction shared withapplyMutationsAtomic(theschema_apply_mutationsbatch entry point) so single-call and batched mutations can never validate differently.applyMutationsAtomiclocks + reads the pack file ONCE, applies + lint-validates every mutation in the batch against an in-memory manifest, and callswritePackManifestat 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); double-quoted scalars are JSON-escaped andsrc/core/schema-pack/loader.ts'sparseYamlMinidecodes exactly that subset (single quotes are literal with''), so emit → parse is the identity (#6432).writePackManifestparses its own output and compares it to the manifest as normalized structures (key order free) before the atomic write, refusingEMIT_MISMATCHwith the file unchanged;loadPackFromFilerefusesPACK_TOO_LARGEfrom the open descriptor's size before reading (8 MiB,GBRAIN_SCHEMA_PACK_MAX_BYTES), andwithMutation/applyMutationsAtomickeep that typed code instead of wrapping it asPACK_CORRUPT. Doctor'sschema_pack_activewarns on a mutable pack above 1 MiB (GBRAIN_SCHEMA_PACK_WARN_BYTES) with the hand-repair runbook (docs/architecture/schema-packs.md#oversized-pack). Pinned bytest/schema-pack-roundtrip.test.ts, the#6432cases oftest/schema-pack-loader.test.tsandtest/schema-pack-mutate.test.ts, andtest/doctor-schema-pack.test.ts.AddTypeOpts.noPrefix(batch fieldno_prefix) declares a frontmatter-only type withpath_prefixes: [](#6135); it refuses alongside a prefix,extractable(lint ruleextractable_empty_corpus) orexpertRouting(lint ruleexpert_routing_without_prefix), and a missing prefix without it staysINVALID_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,sourceIdsingle, or whole-brain). PGLite + Postgres parity viaexecuteRaw.undeclared_pagescounts pages whose non-empty type the active pack neither declares nor aliases;coverageis 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 theschema_review_orphansMCP op) returns pages with no active-pack type match (untyped or undeclared, each withtype+reason), the trueorphan_count,undeclared_typescounts andtruncated; 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 viactx.sourceIddirectly (NOTsourceScopeOpts, which inherits OAuth read federation). Idempotent on--applyre-run.src/commands/schema.ts— schema CLI dispatch, includinglint [<pack>] [--with-db] [--json]. Lint parses--with-dbas 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.tsdrives real isolated CLI subprocesses for implicit/explicit packs, JSON output, missing packs, global source flags, invalid arguments, and plain-lint separation.withConnectedEngineroutesloadConfig()through the canonicaltoEngineConfig()helper and passes the complete result (database_urlanddatabase_path) to factory construction and connect, so PGLite schema commands open the configured brain. Lifecycle-grouped help text (Inspection / Activation / Authoring / Discovery+repair). Pinned bytest/schema-cli-database-path.serial.test.ts. Help after any subcommand prints usage without running it, anduse,downgrade,initandremove-*refuse arguments they would ignore (src/cli/strict-args.ts).src/commands/schema-active.ts—schema active [--source <id>] [--json](#6090). Resolves throughengineSchemaInput(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 withunknown_source(fixgbrain sources list --json); a database that can't be read is a degraded read: stderr marker in text mode (exit 0), adatabase_errorenvelope carrying the file-plane answer anddegraded: trueunder--json(nonzero).schema.ts'srunActiveonly parses flags and passeswithConnectedEngine. Pinned bytest/schema-active-source.test.ts.src/commands/schema-add-type.ts—parseAddTypeArgsforschema add-type(#6135). The type name is the first positional that is not a value-flag's value (--primitive concept archivenamesarchive). A type needs--prefix <dir/>or an explicit--no-prefix; missing both,--prefixwith--no-prefix, and--no-prefixwith--extractable/--experteach refuse withinvalid_params(exit 2) before the pack is touched. Each refusal'sfix.argvis one complete corrected command with<NAME>/<PRIMITIVE>/<PREFIX>placeholders described ininputs;NO_PREFIX_NOTEis the success note (noteunder--json). A switch written with a value (--extractable=true) refuses withinvalid_params, except--json=true, whichrunAddTypeCmdreads as--json(#7619). Pinned bytest/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 withSCHEMA_PACK_VALUE_FLAGS:--pack,--source,--source-id) gives every other pack-authoring subcommand inschema.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 bytest/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 tobrain-taxonomist(files one page) andeiirp(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: exemptfrontmatter. 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.
Pack-aware wiring is partial. Three follow-ups are filed in TODOS.md: enrichment-service.ts
union widening ('person' | 'company' → string), facts/eligibility.ts
pack-aware ELIGIBLE_TYPES wiring, and 3 doctor checks (schema_pack_coverage,
schema_pack_writability, schema_pack_mutation_audit).
src/core/vector-index.ts+src/commands/doctor/checks/embedding-health.ts:embedding_column_registry— shared pgvector HNSW eligibility policy.hnswIndexExpected(columnType, dims)derives the answer from the canonicalvector/halfvecdimension caps already used by migration index generation. Doctor reports an HNSW-less active embedding column as a healthy exact-scan configuration when its declared width exceeds the applicable pgvector cap, and only emits the index repair recipe when an index is actually supported. Pinned at both cap boundaries bytest/vector-index-lifecycle.test.ts.readExistingEmbeddingShaperesolves the same relation as migration DDL and validates its actual type and width. Historical facts/query-cache replay uses that shape instead of extension/config defaults, preserving existing rows, vectors and compatible indexes; malformed existing shapes refuse before migration writes.test/migration-vector-replay.test.tsand its PostgreSQL wrapper pin both engines.withHnswBuildMemory(engine, table, column, build)wraps every PGLite HNSW build (the deferred ANN build inembedding-ann-build.ts,gbrain reindex --vectors): it setsmaintenance_work_memtohnswBuildMemoryMb(rows, vectorBytes)(stored vector plus 640 B per element, +10%, floor 64 MB) so pgvector keeps the whole graph in memory instead of falling back to on-disk inserts, resets it after, and refuses withpglite_vector_index_too_large(fix: the read-onlygbrain migrate --to postgres --plan --json) before building when the graph passesPGLITE_HNSW_GRAPH_BUDGET_BYTES(1.5 GiB of pglite.wasm's 2 GiB heap, about 300k 1024-dim chunks). Postgres runsbuildunchanged. Measured and pinned bytest/pglite-hnsw-build.test.ts; ceiling documented indocs/ENGINES.md#pglite-vector-index-ceiling.