Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Commands (3/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/extract.ts—gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]: batch link/timeline extraction. A lost link or timeline write on the fs walks or the slug-scoped path leaves its pages unstamped and throwsextract_write_lostafter stamping the rest (core/extract-watermark.ts); the sync hooks report a page whose link or timeline write failed inerrors, neverprocessed, so the caller leaves it unstamped. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs walk replaces each page's own markdown-derived links throughreplacePageFileLinks(the per-slug contract below; a file with no page row is skipped and not stamped);extract --stalereplaces throughreplaceDerivedLinks, the db link walk throughreplaceDerivedLinksBatch. Timeline rows are inserted in batches of 100 viaaddTimelineEntriesBatch(ON CONFLICT DO NOTHING;createdcounts real inserts) after every path — fs walk, db walk, per-slug, sync hooks,--stale— runsretractRemovedTimelineEntriesfor the page.ExtractOpts.slugs?: string[]enables incremental extract viaextractForSlugs()(single combined links+timeline pass); the cycle path threads sync'spagesAffectedthrough. Every per-slug extractor —extractForSlugs(the cycle's incremental pass) and the two sync hooksextractLinksForSlugs/extractTimelineForSlugs— resolves each requested slug throughresolveSlugRelPath: thebuildSlugPathIndex(walkMarkdownFiles(dir))index first, then — only on an index miss — the legacyjoin(dir, slug + '.md')existence check. The index is the primary becausepathToSluglowercases and slugifies, so a reconstructed path only finds files whose names are already slugs; the legacy fallback stays because sync ADMITS files the walker never emits (_-prefixed names, dot-dirs waived viasync.include_hidden) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on read order. The per-slug extractors reconcile likeput_page: each page's own markdown-derived links are replaced throughreplacePageFileLinks(src/core/link-reconciliation.ts,replaceDerivedLinkswithpreserveExisting; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), andretractRemovedTimelineEntries(src/core/timeline-extract.ts) deletes the non-event rows whose (date, source, summary) any storedpage_versionstext of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out,--infer-datesanchors) are kept, except an extractor row an older reading of that text filed (supersededTimelineReadings, e.g. the pre-#3280 bullet split, #7949), and the version scan only runs when the page holds a row the current text does not produce.gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json](pruneTimelineOrphans) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-lockedwithCoordinatedWritetransaction; these rows are removals, sogbrain repair timeline/timeline_historyexclude them; pinned intest/persistence-managed-lifecycle.test.ts); the read-onlytimeline_orphansdoctor check (src/commands/doctor/checks/timeline-orphans.ts) samples 500 pages and points at it. Pinned bytest/timeline-reconcile-all-paths.test.ts.loadSlugAliasTargetsadds renamed pages' old slugs (slug_aliases) toallSlugsso links written before a rename resolve to the current slug.extractLinksForSlugsreads the requested files first, then loads page metadata only for those pages and their link endpoints (fileLinkOwnership(engine, sourceId, { slugs })); the unscoped whole-brain load happens only when a DB meeting or attendance origin needsreplaceFileLinks. Both returnExtractForSlugsResult { created, processed, errors? };errorsnames pages whose read or write failed, and sync reports them asextract_error(stderr line plus theSyncResultfield) instead of swallowing them.processedis the subset actually read, and the sharedslugsSafeToStamp(links, timeline)intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it fromextract --stalepermanently. All three call sites (src/commands/sync.ts,src/core/github-source.ts,src/core/google/google-source.ts) stamp the intersection.walkMarkdownFiles(brainDir)still runs to buildallSlugsfor link resolution.--source-id <id>scopes extraction to one source on federated brains (resolved viaresolveSourceWithTier()before any SQL; failures hintgbrain sources list).gbrain extract --stale [--source-id <id>] [--catch-up] [--retry-held] [--dry-run] [--json]branch (extractStaleFromDB; on a managed brain it hands the sweep toextractManagedStaleLinksinsrc/core/persistence/links-maintenance.tsfor every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it throughsrc/commands/extract-stale-delegate.ts; failing pages are reported and skipped there, and--retry-heldclears held ones first) — incremental DB-source link+timeline sweep over pages whosepages.links_extracted_atwatermark is stale, then the mention pass. Embedded callers (the cycle) passquiet: trueso the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. InjsonModeevery fs path,extractForSlugsincluded, reports a dropped flush as a{event:'batch_error'}stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check):links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at(theupdated_atarm catches MCPput_page/sync --no-extractedited-since-extract). ThreeBrainEnginemethods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes):countStalePagesForExtraction(opts?),listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})(returns page CONTENT to avoid N+1getPage;rowToStalePagein utils.ts maps the row,StalePageRowin types.ts),markPagesExtractedBatch(refs, defaultExtractedAt)(3-array unnestslug[],source_id[],ts[]; each ref may carry its ownextractedAt).STALE_BATCH_SIZEdefault 25 (GBRAIN_EXTRACT_STALE_BATCH; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound);STALE_TIME_BUDGET_MS30min wall-clock (--catch-upremoves the cap). Non-swallowing flush (the unmanaged sweep): a page's throw aborts the sweep after the batch's finished pages are flushed and stamped (S4), so the failing page and later ones stay stale and re-extract idempotently.extractStaleFromDBstamps with each row's READupdated_at(notnow()), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links (prepareAutomaticLinks), the coordinator's unrecorded canonical timeline tuples (unrecordedCanonicalTimeline, insert-only) and its watermark in one revision-boundwithCoordinatedWritetransaction; a page edited since the read is skipped and stays stale. Tests:test/extract-stale-managed.test.ts,test/persistence-managed-lifecycle.test.ts. Source-correct stamping at DB-extract sites viastampExtracted(best-effort, never throws);extractLinksFromDBonly stamps the combined watermark whensubcommand === 'all'(a links-only run must not hide timeline staleness).LINK_EXTRACTOR_VERSION_TSlives insrc/core/link-extraction.ts(bump likeCHUNKER_VERSIONto invalidate all prior stamps). Migration v112 (pages_links_extracted_at) adds nullableTIMESTAMPTZ+ composite(source_id, links_extracted_at)index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on firstgbrain doctor. Fresh-install schema insrc/schema.sql(both generated blobs follow viabun run build:schema) +REQUIRED_BOOTSTRAP_COVERAGE.src/commands/doctor/checks/extraction-sync.ts:checkLinksExtractionLag(thelinks_extraction_lagcheck, also indoctorReportRemote) warn-only by default (>GBRAIN_EXTRACTION_LAG_WARN_PCT, default 20%; sharedEXTRACTION_LAG_WARN_PCT_DEFAULT+EXTRACTION_LAG_MIN_PAGES=100+ exported_resolveEnvNumber), hard-fails only whenGBRAIN_EXTRACTION_LAG_FAIL_PCTis set; vacuous-skips <100 pages (no--source); pre-v112 brains graceful-skip viaisUndefinedColumnError; pages whose attendance marker (links_attendance_blocked_revision, migration v180) equals their currentknowledge_revisionare left out of the lag count and reported asdetails.attendance_blocked(bothextract --stalesweeps set the marker on an unresolved-attendance skip; pre-v180 brains fall back to the unfiltered count); strictly a SQL COUNT (safe on remote/thin-client).src/commands/sync.tscarries--no-extract(threaded through single-source +--all+syncOneSource), stampslinks_extracted_atat the inline-extract call site for the slugs the extractors actually read, andmaybeExtractionNudgeprints a one-line stderr nudge after asynced | first_sync | up_to_datesync that leaves a backlog (shouldNudgeAfterSyncpure predicate;GBRAIN_SYNC_NO_EXTRACT_NUDGEsuppresses).src/core/retry.tslists'extract.stale'inBATCH_AUDIT_SITES;src/core/doctor-categories.tslistslinks_extraction_laginBRAIN_CHECK_NAMES. Pinned bytest/extract-stale.test.ts(incl. edited-after-stamp + crash-contract),test/sync-inline-extract-stamps.test.ts,test/sync-nudge-status-gate.test.ts,test/doctor-links-extraction-lag.test.ts, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC stringto_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso(carried onStalePageRow.updated_at_iso, populated byrowToStalePagein utils.ts with an ISO-only fallback — neverString(Date), which::timestamptzmisparses);extractStaleFromDBstamps that exact-precision value, not a JSDate(which truncates to milliseconds), so on Postgreslinks_extracted_atequals the row'supdated_atto the microsecond andlinks_extraction_lagclears — a ms-truncated stamp stays strictly below the µsupdated_atand leaves every page perpetually stale, whichextract --stalecould never satisfy.to_char(not raw::text, which isDateStyle-fragile) keeps the projection deterministic. ThemarkPagesExtractedBatchSQL is unchanged, so callers passing an explicit (e.g. backdated)extractedAtstill control the stamp and the edited-since arm is exact. A deterministic PGLite case intest/extract-stale.test.tsinjects a µsupdated_at, runs--stale, and asserts the lag is 0 and stays 0. W4.14: one basename index per slug set (rebuilt as it grows). GBRA-133 2b.1: the sync hooks (extractLinksForSlugs/extractTimelineForSlugs) share oneindexMarkdownTreewalk per run (src/commands/extract-tree.ts, withmarkdownWalkbehindwalkMarkdownFiles) (it yields after each directory) and type link endpoints throughwithEndpointPageTypes, which parses only the walked files the pass asks a type for (repeating until nothing new is asked) instead ofloadFsPageTypesover the whole tree; fullgbrain extractkeeps the whole-tree parse, and the two give the same links (test/pathological/s-sync-offpath-2b.test.ts). #6805:extractTimelineForSlugswrites each page's rows as one batch throughaddProjectedPageTimeline(same tier, write gate and dedup as the per-row path; an absent or soft-deleted page fails the slug with addTimelineEntry'sPageMissingError); a batch the database refuses is retried row by row throughaddProjectedTimelineEntry, so the page keeps its other rows and is still reported inerrors.createdcounts rows inserted (test/extract-timeline-for-slugs-batch.test.ts).src/commands/extract-timeline-db.ts— theextract timeline --source dbwalk (extractTimelineFromDB), also used byrunExtractCorefor a timeline-only pass on a managed brain. Managed brains (every freshgbrain initbrain) publish each page that needs a change as one database-only maintenance request (managed_maintenance_timeline_extract, owner-checked bymaintenancePreflight, request id bound to the page revision;prepareTimelineExtractis dispatched fromprepareMaintenanceMutation): under the page lock it retracts rows the current text no longer produces and inserts the canonical tuples with no stored row (unrecordedCanonicalTimeline); a page with nothing to change admits no request, and a page edited meanwhile is skipped. The retraction'spage_versionsscan runs before the publication transaction, one version body per statement (versionTimelineScan, #9362); inside the transaction it only checks that each version it read is still the page's with the same body, and a row whose versions changed in between stays until the next run. Unmanaged brains batch raw inserts. A refused write printsrefused: <code>; nothing written; existing timeline rows are untouched, the summary counts written versus refused (a request still pending counts as not confirmed) withgbrain extract --staleand thewrite-refusals.md#extract-timeline-refusedanchor, and the CLI exits 1 (theextractjob throws). Pinned bytest/extract-timeline-db-managed.test.ts,test/e2e/extract-timeline-db-postgres.test.ts,test/fresh-init-db-extract.serial.test.ts.src/commands/extract-stale-options.ts—gbrain extract --stalesource-option validation, run byextract-stale-delegate.tsbefore every--staleinvocation connects (so before direct and owner dispatch alike):--sourceis the fs|db read mode, never a source id;--source dbis accepted,--source fsand any other--source <x>refuseinvalid_params(exit 2) with a fix naming--source-id <x>.assertStaleSourceModeUnambiguousrefuses--source dbas ambiguous when a registered source is nameddb(direct path inrunExtract; owner path inwriter_extract_stale, which also takescatch_up). Tests:test/extraction-nudge-6803.test.ts.src/core/extraction-lag.ts— the extraction backlog as doctorlinks_extraction_lag, the end-of-sync nudge (sync/report.tsmaybeExtractionNudge, which runs the doctor check) andextract --stalereport it:readExtractionLag(one statement,extractionLagStatementinengine-sql/pages.ts: live pages, actionable stale pages without attendance-blocked or held ones, attendance-blocked pages, held pages (heldExtractionReport: doctor warns, fix--retry-held), under a statement deadline; the mention-due read only when the mention pass is on),extractionLagVerdict(warn/fail thresholds and the vacuous-skip floor),extractionRoutes(the plaingbrain extract --stalefix verified by the scoped--dry-run --json, the plain and--catch-uproutes with estimates atEXTRACTION_PAGES_PER_SECOND, actoruser/host_adminpastAGENT_TOOL_LIMIT_MS, option argv pinned to the selected brain), andstaleExtractionCounts/formatStaleCounts(actionable,attendance_blocked,held,mention_due,completein everyextract --stalereport). OwnsSTALE_TIME_BUDGET_MS(re-exported byextract.ts). Tests:test/extraction-nudge-6803.test.ts,test/doctor-links-extraction-lag.test.ts,test/pathological/a1-links-extract.test.ts.Extract CLI help —
EXTRACT_HELPinsrc/commands/extract.tsis the canonical detailed usage shared by--helpand invalid-subcommand errors.src/cli.tsroutesextract --helpbefore engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned bytest/cli-help-discoverability.test.ts.src/commands/features.ts—gbrain features --json --auto-fix: usage scan + feature adoption salesman.src/commands/feedback.ts—gbrain feedback status [--json](settings, answers recorded, ratings by signal, learned weights, most and least trusted pages with a next step, a one-client-dominance warning, this process's dropped events and stage errors) andgbrain feedback reset [--source ID] [--page SLUG](learned weights back to neutral). Table recordfeedback(post-connect, thin client refused). The doctor checkretrieval_feedback_health(src/commands/doctor/checks/retrieval-feedback.ts, meta category) reports the same counts and warns when one client made over 80% of ratings in 7 days, or when at leastUNRATED_ANSWERS_WARN(50) answers were recorded with no rating (a host that hides tool result text never shows the answer id; fixgbrain feedback status --json).src/commands/friction.ts+src/core/friction.ts—gbrain friction {log,render,list,summary,diff}reporter. Append-only JSONL under$GBRAIN_HOME/.gbrain/friction/<run-id>.jsonl. Schema is a flat extension ofStructuredAgentError; every claw-test run opens with aphase-marker/startmeta record carryingagent+scenario+harness_schema(agent-name resolution depends on it). Render groups by severity → phase, defaults to--redactfor md output (strips$HOME/$CWDto placeholders so reports paste safely in PRs).diff --base <run-or-agent> --compare <run-or-agent>is the cross-agent instrument: exact run-id wins, else agent name resolves to that agent's latest run; identity is(kind, phase, normalized 80-char message prefix — digit runs collapsed so durations/counts don't split identities)overkind ∈ {friction, delight}as MULTISETS (per-severity counts + totals are the compared attributes:count_changed= volume,severity_changed= distribution shape via exact integer proportion test, so a delight→friction flip or a 2×error+1×nit → 1×error+2×nit redistribution always surfaces; markers/interrupted feed the compatibility banner, which warns on scenario/version mismatch); output labels sections "unique to " — an instrument, never a blame-attributor. Run-id resolves from--run-id>$GBRAIN_FRICTION_RUN_ID>standalone.jsonl. Skills the claw-test exercises carry a_friction-protocol.mdcallout so agents know when to log friction.src/commands/frontmatter-install-hook.ts—gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]: writes the frontmatter pre-commit hook at<git root>/.githooks/pre-commitand setscore.hooksPathwhen unset. The root comes fromdiscoverGitRoot(the samegit rev-parse --show-toplevelwalkgbrain syncuses, realpath'd on both sides), so a source registered as a SUBDIRECTORY of a host repo (bootstrap's<workspace>/brain) is accepted rather than skipped: the hook lands at the host root withgit diff --cachedlimited to that subdirectory via shell-quoted git pathspecs, recorded as# gbrain-scope: <dir>/marker lines (one per guarded scope). The script carries# gbrain-hook-version: N(FRONTMATTER_HOOK_VERSION; no marker = version 1, which validated working-tree bytes), lists staged paths with-z | tr '\0' '\n', collects them in a heredoc-fedwhile IFS= read -rloop (spaces and non-ASCII names survive; a newline inside a name is unsupported) and runs ONEgbrain frontmatter validate --staged -- <paths>, which checks the staged blobs under the strict producer rule and names failures as staged content.inspectFrontmatterHook(localPath, sourceId?)(read-only) returns the installed gbrain hook's version,current, and theinstall-hook --forcerefresh argv for doctor and post-upgrade. One hook per root — nested sources union their scopes on install and drop only their own on uninstall (the last one removes the file); a root-registered source renders the unscoped script and owns the whole hook. A foreign.githooks/pre-commitstill needs--force(.baksaved, restored on uninstall). Both install and uninstall resolve the hook location throughhookPaths(root), which lstat-refuses a symlinked.githooks/orpre-commit(a committed link in a host repo would redirect the write/chmod/rm elsewhere); the CLI prints the refusal as askippedline and continues with the other sources. Only a path outside any repo is otherwise skipped. Every branch that leaves a hook on disk — fresh write,--forceoverwrite, or a byte-identical refresh — reaches the wiring step, because the hook FILE travels with the repo whilecore.hooksPathis per-clone config: a fresh clone of a repo that committed the hook reportsinstalled(and gets wired) rather thanunchangedwhile inert;unchangedmeans current AND wired. Before wiringcore.hooksPath,hooksPathBlocker(root)returns the operator-facing reason wiring is unsafe, or null: acore.hooksPathalready set (any scope — a global/corporate value counts;--type=path-expanded and resolved against the root) to anywhere that does not realpath to.githooks(theirs to keep; git never reads.githooks/then — one resolving to.githookscounts as wired), a foreign executable under.githooks/(wiring would start running it — third-party clones commit hooks there) or an active hook in the repo's own hooks dir (activeGitHooks— executable non-*.sampleentries under<git rev-parse --git-common-dir>/hooks, immune to a foreigncore.hooksPath; wiring would make git ignore them). Every git spawn passesenv: process.env(Bun's default child env is a startup snapshot), soGIT_CONFIG_*overrides reach the child. Acore.hooksPathof/dev/nullin the clone's own (--local) config (a URL source a remote caller added: hooks off on purpose; a global or system value does not count; that one read runs withgitChildEnv()minusGIT_CONFIG_GLOBAL/SYSTEM/NOSYSTEM, so an inheritedGIT_DIR,GIT_WORK_TREEorGIT_CONFIG*cannot redirect it) returnsskipped_hooks_offbefore anything is written,--forceincluded,hooksPathBlockernames it without wiring advice, andinspectFrontmatterHookreturns null so doctor never proposes a refresh install-hook would skip. Any other blocker returnsinstalled_unwired— the hook is written,core.hooksPathstays untouched, and the CLI prints the reason + the manualgit config core.hooksPath .githooksstep. Pinned bytest/frontmatter-install-hook.test.ts.src/commands/doctor/checks/outside-content-fences.ts—outside_content_fences(GBRA-221, BRAIN, registered beforefence_integrity). Lists facts (row_numset, active; world-visible counted apart), active takes andlinks_fencelinks indexed from a fence on an imported page whose body is outside-authored text (Googleemail/meetingpages, every GitHub-source page, pages withtranscript_importfrontmatter). Reads the derived rows, never a page body, so segmented pages are covered. Before GBRA-221 a sender could plant such rows and a re-render carries a stored fence forward; gbrain writers also add rows on purpose, so it only lists pages (location and counts, never a cell value) with anask_userreview fix (gbrain get) and removes nothing.src/commands/doctor/checks/owner-host-stale.ts+src/commands/doctor/checks/embedding-plane.ts— GBRA-248: doctorowner_host_stale(writes waiting on worktrees whose owner is stale per persistence/owner-activity.ts; fix is the read-only writer status) andembedding_plane_disagreement(the config file disables embeddings while the database does not and holds vectors; fix isenableArgvfrom core/readiness.ts for the stored model and width).