Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
13.3 KB
Raw Blame

Shared brain skills

  • src/core/shared-skills/{model,manifest,policy,catalog,compatibility,tool-access}.ts defines source-incarnation-qualified skill keys, bounded declared files, versioned disclosure policy, sealed catalog reads, authorized opaque views and legacy response projections. Tool/resource requirements use the same scope, snapshot, surface and publication constraints as dispatch. Existing positive publication consent remains prose-only; metadata for unapproved files is not returned. skillMetadata refuses an empty or whitespace-only SKILL.md (A-NEW-5) and records tools_declared (#5150): a canonical skill published without tools inherits the caller's sharedSkillToolAccess as usable_tools in v2 list/detail and the v1 compatibility projection (which now reuses the catalog's computed lists), tools: [] permits none, and revisions published before the flag re-read their SKILL.md on detail (skillToolsDeclared) while the list fails closed. SHARED_SKILL_LIMITS.packFiles (128, equal to the persistence BUNDLE_FILE_LIMITS.files) bounds one canonical publication; files (64) bounds one skill (#5476).
  • src/core/shared-skills/publication.ts prepares complete skill and shared-dependency revisions through the canonical journal. Compare-and-swap checks cover the skill, pack and every affected closure. Sealed inventory is checked against current head keys; only affected revision bodies are loaded. Generated inventory fields are rebuilt rather than duplicated in durable intents, and canonical manifests keep one compact inventory entry per line. Host adoption retains original caller intent and inventory hashes across replay; no fake page row anchors a skill revision. knowledge-guard.ts keeps page/sync/restore aliases from changing declared skill paths; inside a screening batch (persistence/screening-paths.ts) it canonicalizes each pack root and resolves each source root's Git scope once. A relative or host-only file:// alias names no local file and is ignored; an absolute file URI that cannot be resolved refuses with invalid_source_uri (not skill_bundle_required).
  • src/core/shared-skills/{schema-all,schema,persistence-schema,membership-schema,access-schema}.ts supplies shared schema migration/bootstrap SQL. Access DDL explicitly enables row-level security for bypass-capable owners even when the database-wide event trigger is unavailable. Protocol guards reject old consumer claims and writes before filesystem effects, each with SQLSTATE 42501 and a fixed <code>: <diagnostic> message; the request and effect guards refuse writer_coordinator_required: writer state is unreadable to this database role when the writing role cannot see the persistence_brain floor, and activation refuses with the same message any role that row-level security filters on sources or the request, effect, worktree and binding tables (only the table owner or a BYPASSRLS role activates). During publication persistence/publication-failure.ts types them by innermost guard frame plus exact diagnostic (#7777: writer_upgrade_required, writer_not_quiesced, unsupported_mutation_protocol, or writer_coordinator_required with relationship unreadable_state) and connector-errors.ts guardRefusalHint names the remedy (also the role remedy UNREADABLE_STATE_HINT for any guard's unreadable_state, whose raise's state table guardDetail keeps owner-only, #7780) (receipts via receiptDeliveredHint, docs anchor protocol-guard, and writer status recent_failures[].next_action; test/protocol-guard-refusal-7777.test.ts, both engines, checks every 42501 raise in persistence-schema.ts is typed); elsewhere the caller gets the raw 42501, which generic database output labels permission_denied. Their function bodies are exported alone so a migration replaces them without re-creating triggers. src/core/persistence/{protocol,skill-activation,bundle-files}.ts implements explicit owner/quiescence activation and bounded whole-set recovery while preserving the existing page target and permanent receipt identity.
  • src/core/shared-skills/{membership,membership-authority,membership-types,adapter}.ts implements own-principal enrollment, source/policy-bound follow approval, issued batch acknowledgments and conflict-safe immutable local caches. Acknowledgments are self-reported delivery, never vendor-native activation. Enforced library admission rechecks freshness and requirements; native instruction routers remain advisory until separately observed. The adapter's leave treats a server membership_inactive (its own enrollment epoch was left or re-enrolled past) as remote cleanup complete (remote_membership_reason: superseded), so harness rotation converges; gbrain bootstrap harness --refresh-skills re-runs join to adopt the current epoch.
  • src/core/harness/{shared-skills,native-router}.ts connects the enrollment protocol to target-local installation and ownership-tracked Claude Code, Codex and opencode router placement. Native registration, restart and actual task use are separate states. Removal keeps modified files and reports retained native state.
  • src/core/shared-skills/{setup,setup-bundle,setup-files,migration,migration-export}.ts owns combined-content roots, compile-safe starter skills, staged legacy adoption and explicitly approved DB-only export with round-trip validation. installPackagedSharedSkills resumes (or keeps, once committed) the caller's newest packaged adoption of the source incarnation's gbrain-memory pack before admitting one, since the adoption key binds the release-stamped skillpack.json and README (#8453). Existing roots, opt-outs, private/excluded skills and grant ceilings survive upgrades. src/commands/migrations/shared-content.ts integrates previews and recurring pending-stage reconciliation into the migration runner; its console summary counts only sources that owe host work by sharedSkillsHostWork's rule, so a source whose only open stage is an unverified client enrollment (members) or a policy-blocked projection is printed as information ((no host action owed)), never as "need host action" (GBRA-585; test/shared-skills-notice-fresh-brain.test.ts). The 0.53 migration retakes an inventory that never completed at a corrected root (#5569), moves a DB-only export checkpoint that stopped before its source was bound (stage inventory or exported, no started claim) to another absent --content-root and rechecks the checkpoint's inventory (#8528): a root inside a Git worktree is refused before any page is staged, the old staging directory is removed under the lock only when it holds nothing but the export's own bytes (else the move is refused, naming it), a filled earlier root is kept and named in earlier_roots and pending_actions, and every run refuses if the checkpoint changed while it waited for its lock, refuses at inventory a pack whose adoption would exceed packFiles (A-NEW-4), and accepts a post-inventory change only through --accept-reviewed-inventory <source>=<inventoryDigest> printed in the conflict reason (#5476).
  • src/core/shared-skills/{setup-source-policy,content-freshness}.ts excludes external, connector, company and opted-out (config.shared_skills=false) sources from owned-root scaffolding and freshness exemptions. A completed content receipt must match the current brain, incarnation, source root and active owner binding. src/commands/doctor/checks/canonical-content.ts reports pending publication and recovery separately; it never invents an upstream sync timestamp. src/core/shared-skills/adopted-packs.ts names the sources holding an adopted pack (source_routing_health skips their zero-page warning) and, of those, the read-only catalogs (no commit, no .git when the checkout is readable) that sync_freshness exempts; a failing read exempts nothing and is a note. staleOwnedContent names a receipt, or an unfinished setup checkpoint, left on an old root (doctor content_receipt_stale); setup.ts refuses a resumed setup whose checkpoint names another root with gbrain repair content-receipt-root --source <id> as the fix, or, for a source with no canonical owner (which the repair cannot list), with the gbrain sources writer claim <id> --path <root> --dry-run --json preview as the first step (#7915). src/core/shared-skills/receipt-root.ts (rebindContentReceipts) rebinds the receipt root and root_identity of every current incarnation on the moved worktrees (nested by relative_path) inside the writer transfer accept and sources set-path transactions. src/core/repair/content-receipt-root.ts (gbrain repair content-receipt-root, explicit-only, preview-bound, owner host) rebinds a stale receipt when the source path is the owner root and the owner tree hashes to the recorded manifest, else lists source_path_mismatch / tree_mismatch (both digests) / not_owner_host / root_missing; it keeps <key>.backup. Test: test/pathological/c7-content-receipt-root.test.ts.
  • src/core/shared-skills/{source-opt-out,inventory-limits}.ts and src/commands/sources-shared-skills.ts implement gbrain sources shared-skills <id> on|off|status: off writes config.shared_skills=false, on deletes it and releases a parked inventory, and every form reports the configured value and the effective policy mode with its reason. Trusted local only; a remote attempt gets trusted_local_only with a host_admin fix and a read-only verify. inventorySkillpack reads its file-count, total-byte, per-file and entry bounds from the capped shared_skills.inventory.* keys; confinement checks are fixed. An overflow (payload_too_large) parks the source in its per-source migration record, so the 0.53.0 orchestrator completes and later runs skip it until the bounds change, it opts out, or it is released. src/commands/doctor/checks/shared-skills.ts (shared_skills_sources) lists opted-out and parked sources. Operator recipe: docs/guides/shared-brain-skills.md#choose-which-sources-adopt-shared-skills.
  • src/core/shared-skills/optimizer.ts stages opt-in optimization outside canonical roots with the original grants, immutable approved closure and protected metadata. Publication rechecks authority and the original revision through the coordinator; provider evaluation cannot write canonical skill files directly.
  • src/core/persistence/{import-mutations,import-prepare}.ts routes managed Markdown, code and image import through prepared canonical publication. Source, input, target, owner and revision checks run before apply; derived content retains the source-scoped skill-path guard. importManagedFiles takes a batch (at most IMPORT_BATCH_MAX_PAGES files and IMPORT_BATCH_MAX_BYTES, cut by nextImportBatch): each file keeps its own durable intent (op_checkpoints managed-file-import, written and cleared in one statement per batch), request id, receipt and result; the new requests are admitted in one transaction (page-batch.ts admitBatch, with its connection-loss re-run and write_outcome_unknown) and carry one intent.import_batch, so the owner publishes them as independent groups. A file refused before admission settles only that file; a slug the batch already holds ends the batch there, and that file and the rest import after it, as they would one by one. GBRA-75 wave 7: the no-op screen (unchangedManagedImport) calls prepareManagedImportMutation with screen: { snapshot }, the snapshot it just read: the preparer then skips its first path check, the input re-normalization and the snapshot re-read, because the screen just made them, validate re-runs every path and byte check last and the no-op kernel re-checks the page revision; a skipped file reads its snapshot once. A canonical input reuses its input hash as the target hash. The plan and screen loops run inside withScreeningPaths (screening-paths.ts). The preparer imports with coordinated: true: publication proves the base revision under its page guard, and the apply reads the page once after its write for the read-back check, the projection target, the text seal and the receipt's postimage. Pinned by test/persistence-import-batch.test.ts (row-by-row state against one-by-one imports on PGLite and Postgres, resume, lost commit acknowledgment). A Markdown file over the single-string ceiling imported from outside its source root refuses (outsideRootTooLarge) with a message that itself names the move into the root and the target path, and a user fix (gbrain import <target> --source <id>; test/large-pages/managed-import-outside-root.test.ts).
  • src/mcp/skill-resources.ts binds gbrain://skills catalog, exact-revision manifests, bodies and approved assets to the equivalent authorized tool dispatch. It does not claim conformance with an unnegotiated draft Skills-over-MCP extension. src/core/ops/brain-membership.ts supplies the public self-member operations.
  • src/core/shared-skills/retention.ts preserves active heads, tombstones, recent history, delivery/pin leases and pending publication references. Publication quota checks use exact scalar source/brain counts instead of operator diagnostics; pending references are materialized once and lease lookups use the complete revision identity index. Pruning and capacity checks stay inside the guarded publication transaction.

The operating guide is docs/guides/shared-brain-skills.md. Tests include the shared-skills catalog, membership, adapter/native-router, transport, setup/export and writer-boundary suites plus actual bundle SIGKILL and retained-old-executable tests.