Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Commands (5/6, continued)
Subsystem index · Previous entries. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/commands/sources-lifecycle{,-args}.ts— strict source mutation parsing before engine connection, with stable UUIDs and source incarnation preconditions. The private CLI administration envelope delegates to a live PGLite owner, retains request IDs after lost responses, and refuses preactivation administration or legacy hardening rather than changing worktrees through an uncoordinated writer. Managed purge names one archived source; the expiry worker separately coordinates each source.test/persistence-source-cli.test.tsexecutes real CLI subprocesses, checks replay after deletion/recreation, and verifies global page/lifecycle request identity.src/commands/sources-reset-upstream.ts—gbrain sources reset-upstream <id> --expect-local <sha> --expect-upstream <sha> [--dry-run] [--json], the fix forupstream_rewritten/upstream_unknown(src/core/sync-upstream-rewrite.ts). Refuses a managed canonical worktree (writer_coordinator_required) and an in-progress git operation (git_operation_in_progress); under the checkout's commit lock (none on--dry-run) refuses withreset_upstream_refuseda HEAD or upstream other than the expected SHAs (expect_mismatch), no upstream (no_upstream), tracked edits (dirty_tree, names the paths) and local commits not reachable from the upstream, the recorded baseline or any old or new value of the tracking ref's reflog (local_commits, names them and the backup ref). Otherwise writesrefs/gbrain/backup/<UTC stamp>-<sha12>(create-only), runsgit reset --keep <upstream>, verifies HEAD, records the baseline and clears the divergence; never fetches. Pinned bytest/pathological/s-58-upstream-rewrite.test.ts.src/commands/sources-retry-held.ts—gbrain sources retry-held <id> [--dry-run] [--json]: records a re-attempt request for a source's held connector items (and, on a managed brain, their retry-pointer rows) or a re-screen request (opsync-hold-retry) for its held Git files, which the next sync adds to its manifest; nothing runs now, the receipt prints the sync to run. #6278: on a managed brain that follow-up sync is built bygitFollowUpSync: the unfinished managed cursor's resume arguments (readManagedSyncBacklog,managedSyncResumeArgs), so--no-embedand the other processing options carry over instead of starting a second cursor, else the arguments apreparation_stalledhold recorded (meta.stall.sync_argv), else--source <id> --no-pull.preparation_stalledholds count understalledin the repair route and need no file repair: the receipt and help point togbrain sources writer status --source <id> --jsonfirst. #6865:--unindexed(retryUnindexed) runs one bounded pass of the unindexed-file detector (persistence/unindexed-files.ts, 60 s) for a managed Git source, schedules the found files through the same re-screen request, stores the result doctorunindexed_filesreads (continuing an incomplete stored scan) and prints the follow-up sync withgbrain doctor --only unindexed_files --jsonas its verify;--dry-runlists them and writes nothing; connector and company-brain sources refuseinvalid_params; a complete pass with nothing found printsNo unindexed files for <id>., an incomplete one says the scan continues. Both modes build the receipt throughreceiptOf. Tests:test/held-files-walkthrough.test.ts,test/managed-sync-preparation-stalled-holds.test.ts,test/unindexed-files.test.ts.src/commands/sources-resolve-path.ts— GBRA-150:gbrain sources resolve-path <id> <path...> [--stdin] [--json], the CLI face of opsources_resolve_path(core/ops/sources.ts). Paths come from argv or--stdin(one per line, at mostRESOLVE_PATHS_MAX= 200); the human print is one line per path (state, slug, why, fix),--jsonthe op's result. Read-only. Tests:test/sources-resolve-path.test.ts. Harness guide:docs/guides/resolve-paths.md.src/commands/sources-set-path.ts—gbrain sources set-path <id> <path> [--force]: unmanaged installations retain the legacy pointer repair and overlap check. Managed installations use the verified lifecycle rebind; force never bypasses ownership or manifest checks. Relative paths and MSYS spellings are normalized before routing. Thedefault_source_local_pathdoctor check names this as the repair. A guest source is refused (database-only, GBRA-504).src/commands/sources-strategy.ts—gbrain sources set-strategy <id> <markdown|code|auto>(#4899, PR #5955): writessources.config.strategythroughupdateSourceConfig(single-key merge; every other config key survives), the valuesync --all, autopilot, the dream cycle and the MCPsyncop pass to the per-source sync when the caller names no--strategy; unset meansmarkdown. The one writer of that key (nosources add --strategy, no op param). Connector kinds refuse it. [R26]: refuses withsync_run_unfinished(exit 1) while the source has an unfinishedmanaged-synccursor, naming the resume and the orphan repair, because the frozen manifest was classified under the old strategy; re-stating the current value is allowed.sources list --jsonandlistSourcesreportstrategy(nullwhen unset). Pinned bytest/sources-strategy.test.ts.src/commands/guests.ts—gbrain guests init [--source <id>] [--writer <kind>:<id>]... [--yes](GBRA-504): previews by default;--yescreates or marks the source database-only, federated,guest: truewithtrust_ceiling, and itsguest_sourcesrow in one transaction (core/guests/sources.ts). Refuses a source with a local_path.gbrain guests promote <slug> [--to] [--source] [--guest-source] [--json]runs oppromote_guest_noteas the trusted local CLI (core/guests/promote.ts);gbrain guests grant-owner-clients [--source] [--yes] [--json]previews, then adds the guest source to owner credentials' read lists (core/guests/owner-credentials.ts).src/commands/sources-writers.ts—gbrain sources writers <id> [--add|--remove <w>] [--clear] [--json]: lists or changesguest_sources.writers; refuses a source that is not a guest source.src/commands/sources-add-next.ts— GBRA-156:noGrantFloorNext(engine, id), the federate stepsources addprints when a new non-federated source leaves the no-grant floor (localFederatedSourceIds(engine, 'default', 'seed_default'), else['default']) holding no live page a remote read may show (private pages excluded when remote reads exclude them); returns{ command, argv, why }or null; the notice asks the user whether the source should be shared (a private source needs nothing). One read, no write;sources addtreats a failed read as no step.src/commands/sources.ts—gbrain sources {list,add,remove,archive,restore,archived,purge,current,status,audit,refresh,set-calendar};set-calendardispatches tosrc/commands/sources-set-calendar.ts, andset-cr-modeprintscontextualModeHintafter the write.refreshdispatches tosrc/commands/sources-refresh.ts(argument parsing, stdout text or--jsonresult/refusal objects, exit 1 on refusal or an unfinished sync; protocol insrc/core/persistence/worktree-refresh.ts, where a fence lock timeout (55P03) becomesrefresh_lock_timeoutnaming the open transactions holding the fenced tables, and any other untyped throw becomes aninternal_errorrefusal whosewhycarries the stack and whose fix names the refresh row it left for the next run to resume, GBRA-250).current [--json]callsresolveSourceWithTier()and printssource_id,tier(flag | env | dotfile | local_path | brain_default | seed_default), and optionaldetail(decision table inskills/conventions/brain-routing.md).status [--json]— read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper aroundbuildSyncStatusReport+printSyncStatusReportfromsrc/commands/sync.ts;--jsonemits stable{schema_version: 1, sources, ...}on stdout; filters input tolocal_path IS NOT NULL AND archived IS NOT TRUE.audit <id> [--json]— read-only dry-run disk scan for size distribution + would-blocks + junk-pattern hits WITHOUT touching the DB; walkssources.local_path, reads each markdown file, runsassessContent()fromsrc/core/content-sanity.ts, aggregates by verdict (ok | warn_oversize | hard_block_junk_pattern). The liverunStatushealth table gains aBACKFILLcolumn betweenEMBEDandFAILS(active(N)beatsqueued(N)beatsidle, fromSourceMetrics.backfill_active/backfill_queuedinsrc/core/source-health.ts) so operators see deferredembed-backfillminion work aftersync --allexits 0;jobCountsBySourceinsource-health.tswidens itsminion_jobsSQL with twoCOUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...)aggregates (best-effort, all-0 on pre-minions brains).removepre-checks OAuth-client referents (guided refusal viaformatClientReferentsBlock— the raw FK violation never reaches the operator), then commits the row DELETE atomically with an in-tx referents re-check (a registration racing the pre-check maps to the same guided refusal); durability-scaffolding teardown (unhardenBrainRepo: hook/cron/credential) runs only AFTER the commit, so a refused delete leaves the scaffolding intact.purgeruns the same referents pre-check before its hard DELETE.addwithout--federatedor--no-federatedstores the source non-federated and warns on stderr that a remote token or agent connection with no source grant cannot read it, naminggbrain sources federate <id>andgbrain auth rescope --token <name> --sources <id>; when the no-grant floor (the default source plus federated sources) then holds no live page it also printsnext: gbrain sources federate <id>on stdout (noGrantFloorNextinsources-add-next.ts).add --jsonprints one object (id,name,local_path,remote_url,federated, andnextwithcommand/argv/whywhen that step applies) and moves the human lines to stderr (test/sources-add-federation-warning.test.ts).federate <id> [--json]andrestore <id>print on stderr, after the change commits, the pages a remote credential wrote without readers that the change makes readable to no-grant connections (core/access/federation-exposure.ts);federate --jsonprints one object (id,federated,pages_exposed) and moves the human lines to stderr. Pinned bytest/content-sanity.test.ts,test/import-file-content-sanity.test.ts,test/source-health.test.ts.src/commands/status-funnel.ts—gbrain status --funnel [--json] [--enable | --delete](D8 adoption funnel): engine-free, dispatched fromsrc/cli/main.tsbefore any connect so it works beforegbrain initand on a thin client; reads and writes only the local record throughsrc/core/funnel.ts. Guide:docs/guides/adoption-funnel.md. Tests:test/funnel.test.ts,test/funnel-cli.test.ts.src/commands/storage.ts—gbrain storage status [--repo P] [--json]. Split into pure data (getStorageStatus) + JSON formatter + human formatter (ASCII-only) matching theorphans.tspattern.PageCountsByTierandDiskUsageByTierare distinct nominal types so swaps fail at compile time. The repo and the counted source come fromresolveRestoreTarget(src/core/restore-target.ts, theexport --restore-onlyrule), and a page is listed missing exactly when that export would restore it (isDbOnly, thenrestoreFilePathin the page source'sscannerSlugRootModeandnativeFileTarget: the recordedsource_path, else<slug>.md, absent; the repo walk answers without a per-page syscall whenever it saw that exact file as a regular file under real directories, and a recorded path starting with the repo's path inside its git checkout, which export re-anchors, takes the full check), so the printedUse: gbrain export --restore-only --source <id> --repo <path>(the path passed throughshellQuote,src/core/shell-quote.ts) writes exactly the listed files into--dir(default./export, not the repo). An unsafe recorded path or a symlinked/ambiguous file target (OperationErrorfromnativeFileTarget) becomes one warning per reason (lowest slug plus a count of further pages) plus the refusal export would give, printed even when no file is missing; a repo whose own owner (resolveSourceForRepoPath: dotfile, then longest registeredlocal_path) is archived is refused too (unless an active source is registered at the repo's exact path, which owns it outright), although export's exact-path rule would fall back to the only active source; a refused rule printsCannot suggest a restore command:and falls back to the--repo/ default-source path, counting the active repo owner's pages (dotfile, then longest registeredlocal_path) or every source's pages when no active source owns it.restoreSource/restoreRefusalcarry this in the JSON result. Pinned bytest/storage-restore-hint.test.ts. The storage shelf subcommands (GST-1943) arestorage init,storage adopt(preview,--apply --expect,--finalize [--expect]; logic insrc/core/storage-manifest/adopt.ts) andstorage export|import --jsonl(src/core/storage-manifest/jsonl.ts); each builds a trusted localOperationContextand renders refusals withwriteCliError.src/core/storage-manifest/schema.ts,src/core/storage-manifest/door.ts,src/core/storage-manifest/source.ts,src/core/storage-manifest/find.tsandsrc/core/ops/storage-manifest.ts— GST-1943 storage shelf (guide:docs/guides/storage-manifest.md). A card is atype: stored-objectpage in sourcestoragewhose card sits under thestoragefrontmatter key (titleandaliasesare the page's own);parseCardInputvalidates every write (strict shapes,credentialShapeand the secret scanner on string fields,isCommandKeyon every key,registered_byandoriginstamped by gbrain only,restoreas{ skill, args }with flat scalar args), andcardDigestcompares two copies.door.tsholds the source id, the rolestorage_manifestand theSTORAGE_DOORsymbol the verbs set on their context, which no request parameter can carry;assertStorageSourceWriter, called by the page door (page-mutations.ts) andremember/forget(memory-mutations.ts), refuses every other writerstorage_source_managed, except the owner's import of commits already in the hosted repository.source.ts:shelfWritable/ensureStorageSourcecreate the database-only, non-federated shelf on a repo-less brain's first register, finish a creation that stopped part way, refuse an archived shelf or astoragesource that is someone else's, and on a repo brain refusestorage_manifest_missinguntilinitStorageSource(gbrain storage init, preview then--expect, throughhostRepo, needs managed persistence) hosts it.find.ts: keyless ranked lookup in one statement (exact id,page_aliases, word matches over title, aliases and body, thenpg_trgmclosest cards on a miss) under the caller's read policy. The ops:storage_find,storage_getandstorage_listread under the caller's grant (federatedSearchScope, so a remote client needs a grant namingstorage), andstorage_getrefusesstorage_record_invalid, with the revision, for a stored card that fails the rules;storage_registerandstorage_updateare trusted-local only, write throughsubmitPageMutationwith the door mark, never overwrite (storage_card_exists), bind an update toexpected_revision(storage_revision_conflict) and keep the page'sPROTECTED_FRONTMATTER_KEYS(access labels included). Pinned bytest/storage-manifest.test.ts,test/storage-manifest-hosted.test.tsandtest/e2e/storage-manifest-postgres.test.ts.src/core/storage-manifest/adopt.ts,src/core/storage-manifest/jsonl.tsandsrc/commands/doctor/checks/storage-manifest.ts— GST-1943 storage shelf recovery. Adopt reads interimstored-objectpages under a prefix (never<prefix>index) from the bounded body prefix (boundedBodyPrefixSql), takes the JSON block under## Record, strips every field the card refuses (command_field,unknown_field,stamped_field;CARD_KEYSinschema.ts) and validates the rest withparseCardInput; a credential-shaped value (credentialShape) blocks the page whatever is dropped. Apply registers throughregisterCard(origin: adopt) and tags the originalstorage-manifest-adoptedthroughsubmitPageMutation; it never deletes. On a hosted shelf it then indexes its own commits (indexShelfCommits: the managed--no-pulldrain under the shelf's drain lease, as a git conversion's strict pass does) and reportsindex. Finalize soft-deletes tagged originals only whencardDigestof the shelf card equals the mapped card. Every plan_hash covers end state (mapped cards, refusals, blocks, conflicts), never progress, so the printed rerun of a partial apply still applies. JSONL import registersorigin: importand never overwrites. The doctor checkstorage_manifestis read-only: schema-failing cards, unadopted interim records outside the shelf, a hosted shelf directory gone;not_applicablewith neither shelf nor interim pages. Pinned bytest/storage-manifest-adopt.test.ts,test/storage-manifest-jsonl.test.ts,test/doctor-storage-manifest.test.tsandtest/storage-manifest-adopt-hosted.test.ts.