Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
17.3 KB
Raw Blame

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.ts executes 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 for upstream_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 with reset_upstream_refused a 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 writes refs/gbrain/backup/<UTC stamp>-<sha12> (create-only), runs git reset --keep <upstream>, verifies HEAD, records the baseline and clears the divergence; never fetches. Pinned by test/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 (op sync-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 by gitFollowUpSync: the unfinished managed cursor's resume arguments (readManagedSyncBacklog, managedSyncResumeArgs), so --no-embed and the other processing options carry over instead of starting a second cursor, else the arguments a preparation_stalled hold recorded (meta.stall.sync_argv), else --source <id> --no-pull. preparation_stalled holds count under stalled in the repair route and need no file repair: the receipt and help point to gbrain sources writer status --source <id> --json first. #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 doctor unindexed_files reads (continuing an incomplete stored scan) and prints the follow-up sync with gbrain doctor --only unindexed_files --json as its verify; --dry-run lists them and writes nothing; connector and company-brain sources refuse invalid_params; a complete pass with nothing found prints No unindexed files for <id>., an incomplete one says the scan continues. Both modes build the receipt through receiptOf. 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 op sources_resolve_path (core/ops/sources.ts). Paths come from argv or --stdin (one per line, at most RESOLVE_PATHS_MAX = 200); the human print is one line per path (state, slug, why, fix), --json the 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. The default_source_local_path doctor 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): writes sources.config.strategy through updateSourceConfig (single-key merge; every other config key survives), the value sync --all, autopilot, the dream cycle and the MCP sync op pass to the per-source sync when the caller names no --strategy; unset means markdown. The one writer of that key (no sources add --strategy, no op param). Connector kinds refuse it. [R26]: refuses with sync_run_unfinished (exit 1) while the source has an unfinished managed-sync cursor, 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 --json and listSources report strategy (null when unset). Pinned by test/sources-strategy.test.ts.

  • src/commands/guests.ts — gbrain guests init [--source <id>] [--writer <kind>:<id>]... [--yes] (GBRA-504): previews by default; --yes creates or marks the source database-only, federated, guest: true with trust_ceiling, and its guest_sources row in one transaction (core/guests/sources.ts). Refuses a source with a local_path. gbrain guests promote <slug> [--to] [--source] [--guest-source] [--json] runs op promote_guest_note as 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 changes guest_sources.writers; refuses a source that is not a guest source.

  • src/commands/sources-add-next.ts — GBRA-156: noGrantFloorNext(engine, id), the federate step sources add prints 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 add treats 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-calendar dispatches to src/commands/sources-set-calendar.ts, and set-cr-mode prints contextualModeHint after the write. refresh dispatches to src/commands/sources-refresh.ts (argument parsing, stdout text or --json result/refusal objects, exit 1 on refusal or an unfinished sync; protocol in src/core/persistence/worktree-refresh.ts, where a fence lock timeout (55P03) becomes refresh_lock_timeout naming the open transactions holding the fenced tables, and any other untyped throw becomes an internal_error refusal whose why carries the stack and whose fix names the refresh row it left for the next run to resume, GBRA-250). current [--json] calls resolveSourceWithTier() and prints source_id, tier (flag | env | dotfile | local_path | brain_default | seed_default), and optional detail (decision table in skills/conventions/brain-routing.md). status [--json] — read-only per-source dashboard (last sync, staleness, page count, embedding coverage, unacked failures); thin wrapper around buildSyncStatusReport + printSyncStatusReport from src/commands/sync.ts; --json emits stable {schema_version: 1, sources, ...} on stdout; filters input to local_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; walks sources.local_path, reads each markdown file, runs assessContent() from src/core/content-sanity.ts, aggregates by verdict (ok | warn_oversize | hard_block_junk_pattern). The live runStatus health table gains a BACKFILL column between EMBED and FAILS (active(N) beats queued(N) beats idle, from SourceMetrics.backfill_active / backfill_queued in src/core/source-health.ts) so operators see deferred embed-backfill minion work after sync --all exits 0; jobCountsBySource in source-health.ts widens its minion_jobs SQL with two COUNT(*) FILTER (WHERE name = 'embed-backfill' AND ...) aggregates (best-effort, all-0 on pre-minions brains). remove pre-checks OAuth-client referents (guided refusal via formatClientReferentsBlock — 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. purge runs the same referents pre-check before its hard DELETE. add without --federated or --no-federated stores the source non-federated and warns on stderr that a remote token or agent connection with no source grant cannot read it, naming gbrain sources federate <id> and gbrain auth rescope --token <name> --sources <id>; when the no-grant floor (the default source plus federated sources) then holds no live page it also prints next: gbrain sources federate <id> on stdout (noGrantFloorNext in sources-add-next.ts). add --json prints one object (id, name, local_path, remote_url, federated, and next with command/argv/why when that step applies) and moves the human lines to stderr (test/sources-add-federation-warning.test.ts). federate <id> [--json] and restore <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 --json prints one object (id, federated, pages_exposed) and moves the human lines to stderr. Pinned by test/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 from src/cli/main.ts before any connect so it works before gbrain init and on a thin client; reads and writes only the local record through src/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 the orphans.ts pattern. PageCountsByTier and DiskUsageByTier are distinct nominal types so swaps fail at compile time. The repo and the counted source come from resolveRestoreTarget (src/core/restore-target.ts, the export --restore-only rule), and a page is listed missing exactly when that export would restore it (isDbOnly, then restoreFilePath in the page source's scannerSlugRootMode and nativeFileTarget: the recorded source_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 printed Use: gbrain export --restore-only --source <id> --repo <path> (the path passed through shellQuote, 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 (OperationError from nativeFileTarget) 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 registered local_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 prints Cannot suggest a restore command: and falls back to the --repo / default-source path, counting the active repo owner's pages (dotfile, then longest registered local_path) or every source's pages when no active source owns it. restoreSource / restoreRefusal carry this in the JSON result. Pinned by test/storage-restore-hint.test.ts. The storage shelf subcommands (GST-1943) are storage init, storage adopt (preview, --apply --expect, --finalize [--expect]; logic in src/core/storage-manifest/adopt.ts) and storage export|import --jsonl (src/core/storage-manifest/jsonl.ts); each builds a trusted local OperationContext and renders refusals with writeCliError.

  • src/core/storage-manifest/schema.ts, src/core/storage-manifest/door.ts, src/core/storage-manifest/source.ts, src/core/storage-manifest/find.ts and src/core/ops/storage-manifest.ts — GST-1943 storage shelf (guide: docs/guides/storage-manifest.md). A card is a type: stored-object page in source storage whose card sits under the storage frontmatter key (title and aliases are the page's own); parseCardInput validates every write (strict shapes, credentialShape and the secret scanner on string fields, isCommandKey on every key, registered_by and origin stamped by gbrain only, restore as { skill, args } with flat scalar args), and cardDigest compares two copies. door.ts holds the source id, the role storage_manifest and the STORAGE_DOOR symbol the verbs set on their context, which no request parameter can carry; assertStorageSourceWriter, called by the page door (page-mutations.ts) and remember/forget (memory-mutations.ts), refuses every other writer storage_source_managed, except the owner's import of commits already in the hosted repository. source.ts: shelfWritable/ensureStorageSource create 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 a storage source that is someone else's, and on a repo brain refuse storage_manifest_missing until initStorageSource (gbrain storage init, preview then --expect, through hostRepo, needs managed persistence) hosts it. find.ts: keyless ranked lookup in one statement (exact id, page_aliases, word matches over title, aliases and body, then pg_trgm closest cards on a miss) under the caller's read policy. The ops: storage_find, storage_get and storage_list read under the caller's grant (federatedSearchScope, so a remote client needs a grant naming storage), and storage_get refuses storage_record_invalid, with the revision, for a stored card that fails the rules; storage_register and storage_update are trusted-local only, write through submitPageMutation with the door mark, never overwrite (storage_card_exists), bind an update to expected_revision (storage_revision_conflict) and keep the page's PROTECTED_FRONTMATTER_KEYS (access labels included). Pinned by test/storage-manifest.test.ts, test/storage-manifest-hosted.test.ts and test/e2e/storage-manifest-postgres.test.ts.

  • src/core/storage-manifest/adopt.ts, src/core/storage-manifest/jsonl.ts and src/commands/doctor/checks/storage-manifest.ts — GST-1943 storage shelf recovery. Adopt reads interim stored-object pages 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_KEYS in schema.ts) and validates the rest with parseCardInput; a credential-shaped value (credentialShape) blocks the page whatever is dropped. Apply registers through registerCard (origin: adopt) and tags the original storage-manifest-adopted through submitPageMutation; it never deletes. On a hosted shelf it then indexes its own commits (indexShelfCommits: the managed --no-pull drain under the shelf's drain lease, as a git conversion's strict pass does) and reports index. Finalize soft-deletes tagged originals only when cardDigest of 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 registers origin: import and never overwrites. The doctor check storage_manifest is read-only: schema-failing cards, unadopted interim records outside the shelf, a hosted shelf directory gone; not_applicable with neither shelf nor interim pages. Pinned by test/storage-manifest-adopt.test.ts, test/storage-manifest-jsonl.test.ts, test/doctor-storage-manifest.test.ts and test/storage-manifest-adopt-hosted.test.ts.