Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
23.8 KB
Raw Blame

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 throws extract_write_lost after stamping the rest (core/extract-watermark.ts); the sync hooks report a page whose link or timeline write failed in errors, never processed, 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 through replacePageFileLinks (the per-slug contract below; a file with no page row is skipped and not stamped); extract --stale replaces through replaceDerivedLinks, the db link walk through replaceDerivedLinksBatch. Timeline rows are inserted in batches of 100 via addTimelineEntriesBatch (ON CONFLICT DO NOTHING; created counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, --stale — runs retractRemovedTimelineEntries for the page. ExtractOpts.slugs?: string[] enables incremental extract via extractForSlugs() (single combined links+timeline pass); the cycle path threads sync's pagesAffected through. Every per-slug extractor — extractForSlugs (the cycle's incremental pass) and the two sync hooks extractLinksForSlugs / extractTimelineForSlugs — resolves each requested slug through resolveSlugRelPath: the buildSlugPathIndex(walkMarkdownFiles(dir)) index first, then — only on an index miss — the legacy join(dir, slug + '.md') existence check. The index is the primary because pathToSlug lowercases 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 via sync.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 like put_page: each page's own markdown-derived links are replaced through replacePageFileLinks (src/core/link-reconciliation.ts, replaceDerivedLinks with preserveExisting; 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), and retractRemovedTimelineEntries (src/core/timeline-extract.ts) deletes the non-event rows whose (date, source, summary) any stored page_versions text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, --infer-dates anchors) 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-locked withCoordinatedWrite transaction; these rows are removals, so gbrain repair timeline / timeline_history exclude them; pinned in test/persistence-managed-lifecycle.test.ts); the read-only timeline_orphans doctor check (src/commands/doctor/checks/timeline-orphans.ts) samples 500 pages and points at it. Pinned by test/timeline-reconcile-all-paths.test.ts. loadSlugAliasTargets adds renamed pages' old slugs (slug_aliases) to allSlugs so links written before a rename resolve to the current slug. extractLinksForSlugs reads 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 needs replaceFileLinks. Both return ExtractForSlugsResult { created, processed, errors? }; errors names pages whose read or write failed, and sync reports them as extract_error (stderr line plus the SyncResult field) instead of swallowing them. processed is the subset actually read, and the shared slugsSafeToStamp(links, timeline) intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from extract --stale permanently. 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 build allSlugs for link resolution. --source-id <id> scopes extraction to one source on federated brains (resolved via resolveSourceWithTier() before any SQL; failures hint gbrain 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 to extractManagedStaleLinks in src/core/persistence/links-maintenance.ts for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through src/commands/extract-stale-delegate.ts; failing pages are reported and skipped there, and --retry-held clears held ones first) — incremental DB-source link+timeline sweep over pages whose pages.links_extracted_at watermark is stale, then the mention pass. Embedded callers (the cycle) pass quiet: true so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In jsonMode every fs path, extractForSlugs included, 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 (the updated_at arm catches MCP put_page / sync --no-extract edited-since-extract). Three BrainEngine methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): countStalePagesForExtraction(opts?), listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?}) (returns page CONTENT to avoid N+1 getPage; rowToStalePage in utils.ts maps the row, StalePageRow in types.ts), markPagesExtractedBatch(refs, defaultExtractedAt) (3-array unnest slug[],source_id[],ts[]; each ref may carry its own extractedAt). STALE_BATCH_SIZE default 25 (GBRAIN_EXTRACT_STALE_BATCH; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); STALE_TIME_BUDGET_MS 30min wall-clock (--catch-up removes 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. extractStaleFromDB stamps with each row's READ updated_at (not now()), 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-bound withCoordinatedWrite transaction; 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 via stampExtracted (best-effort, never throws); extractLinksFromDB only stamps the combined watermark when subcommand === 'all' (a links-only run must not hide timeline staleness). LINK_EXTRACTOR_VERSION_TS lives in src/core/link-extraction.ts (bump like CHUNKER_VERSION to invalidate all prior stamps). Migration v112 (pages_links_extracted_at) adds nullable TIMESTAMPTZ + 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 first gbrain doctor. Fresh-install schema in src/schema.sql (both generated blobs follow via bun run build:schema) + REQUIRED_BOOTSTRAP_COVERAGE. src/commands/doctor/checks/extraction-sync.ts:checkLinksExtractionLag (the links_extraction_lag check, also in doctorReportRemote) warn-only by default (>GBRAIN_EXTRACTION_LAG_WARN_PCT, default 20%; shared EXTRACTION_LAG_WARN_PCT_DEFAULT + EXTRACTION_LAG_MIN_PAGES=100 + exported _resolveEnvNumber), hard-fails only when GBRAIN_EXTRACTION_LAG_FAIL_PCT is set; vacuous-skips <100 pages (no --source); pre-v112 brains graceful-skip via isUndefinedColumnError; pages whose attendance marker (links_attendance_blocked_revision, migration v180) equals their current knowledge_revision are left out of the lag count and reported as details.attendance_blocked (both extract --stale sweeps 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.ts carries --no-extract (threaded through single-source + --all + syncOneSource), stamps links_extracted_at at the inline-extract call site for the slugs the extractors actually read, and maybeExtractionNudge prints a one-line stderr nudge after a synced | first_sync | up_to_date sync that leaves a backlog (shouldNudgeAfterSync pure predicate; GBRAIN_SYNC_NO_EXTRACT_NUDGE suppresses). src/core/retry.ts lists 'extract.stale' in BATCH_AUDIT_SITES; src/core/doctor-categories.ts lists links_extraction_lag in BRAIN_CHECK_NAMES. Pinned by test/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 string to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso (carried on StalePageRow.updated_at_iso, populated by rowToStalePage in utils.ts with an ISO-only fallback — never String(Date), which ::timestamptz misparses); extractStaleFromDB stamps that exact-precision value, not a JS Date (which truncates to milliseconds), so on Postgres links_extracted_at equals the row's updated_at to the microsecond and links_extraction_lag clears — a ms-truncated stamp stays strictly below the µs updated_at and leaves every page perpetually stale, which extract --stale could never satisfy. to_char (not raw ::text, which is DateStyle-fragile) keeps the projection deterministic. The markPagesExtractedBatch SQL is unchanged, so callers passing an explicit (e.g. backdated) extractedAt still control the stamp and the edited-since arm is exact. A deterministic PGLite case in test/extract-stale.test.ts injects a µs updated_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 one indexMarkdownTree walk per run (src/commands/extract-tree.ts, with markdownWalk behind walkMarkdownFiles) (it yields after each directory) and type link endpoints through withEndpointPageTypes, which parses only the walked files the pass asks a type for (repeating until nothing new is asked) instead of loadFsPageTypes over the whole tree; full gbrain extract keeps the whole-tree parse, and the two give the same links (test/pathological/s-sync-offpath-2b.test.ts). #6805: extractTimelineForSlugs writes each page's rows as one batch through addProjectedPageTimeline (same tier, write gate and dedup as the per-row path; an absent or soft-deleted page fails the slug with addTimelineEntry's PageMissingError); a batch the database refuses is retried row by row through addProjectedTimelineEntry, so the page keeps its other rows and is still reported in errors. created counts rows inserted (test/extract-timeline-for-slugs-batch.test.ts).

  • src/commands/extract-timeline-db.ts — the extract timeline --source db walk (extractTimelineFromDB), also used by runExtractCore for a timeline-only pass on a managed brain. Managed brains (every fresh gbrain init brain) publish each page that needs a change as one database-only maintenance request (managed_maintenance_timeline_extract, owner-checked by maintenancePreflight, request id bound to the page revision; prepareTimelineExtract is dispatched from prepareMaintenanceMutation): 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's page_versions scan 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 prints refused: <code>; nothing written; existing timeline rows are untouched, the summary counts written versus refused (a request still pending counts as not confirmed) with gbrain extract --stale and the write-refusals.md#extract-timeline-refused anchor, and the CLI exits 1 (the extract job throws). Pinned by test/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 --stale source-option validation, run by extract-stale-delegate.ts before every --stale invocation connects (so before direct and owner dispatch alike): --source is the fs|db read mode, never a source id; --source db is accepted, --source fs and any other --source <x> refuse invalid_params (exit 2) with a fix naming --source-id <x>. assertStaleSourceModeUnambiguous refuses --source db as ambiguous when a registered source is named db (direct path in runExtract; owner path in writer_extract_stale, which also takes catch_up). Tests: test/extraction-nudge-6803.test.ts.

  • src/core/extraction-lag.ts — the extraction backlog as doctor links_extraction_lag, the end-of-sync nudge (sync/report.ts maybeExtractionNudge, which runs the doctor check) and extract --stale report it: readExtractionLag (one statement, extractionLagStatement in engine-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 plain gbrain extract --stale fix verified by the scoped --dry-run --json, the plain and --catch-up routes with estimates at EXTRACTION_PAGES_PER_SECOND, actor user/host_admin past AGENT_TOOL_LIMIT_MS, option argv pinned to the selected brain), and staleExtractionCounts/formatStaleCounts (actionable, attendance_blocked, held, mention_due, complete in every extract --stale report). Owns STALE_TIME_BUDGET_MS (re-exported by extract.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_HELP in src/commands/extract.ts is the canonical detailed usage shared by --help and invalid-subcommand errors. src/cli.ts routes extract --help before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by test/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) and gbrain feedback reset [--source ID] [--page SLUG] (learned weights back to neutral). Table record feedback (post-connect, thin client refused). The doctor check retrieval_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 least UNRATED_ANSWERS_WARN (50) answers were recorded with no rating (a host that hides tool result text never shows the answer id; fix gbrain 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 of StructuredAgentError; every claw-test run opens with a phase-marker/start meta record carrying agent + scenario + harness_schema (agent-name resolution depends on it). Render groups by severity → phase, defaults to --redact for md output (strips $HOME/$CWD to 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) over kind ∈ {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.md callout 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-commit and sets core.hooksPath when unset. The root comes from discoverGitRoot (the same git rev-parse --show-toplevel walk gbrain sync uses, 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 with git diff --cached limited 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-fed while IFS= read -r loop (spaces and non-ASCII names survive; a newline inside a name is unsupported) and runs ONE gbrain 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 the install-hook --force refresh 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-commit still needs --force (.bak saved, restored on uninstall). Both install and uninstall resolve the hook location through hookPaths(root), which lstat-refuses a symlinked .githooks/ or pre-commit (a committed link in a host repo would redirect the write/chmod/rm elsewhere); the CLI prints the refusal as a skipped line 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, --force overwrite, or a byte-identical refresh — reaches the wiring step, because the hook FILE travels with the repo while core.hooksPath is per-clone config: a fresh clone of a repo that committed the hook reports installed (and gets wired) rather than unchanged while inert; unchanged means current AND wired. Before wiring core.hooksPath, hooksPathBlocker(root) returns the operator-facing reason wiring is unsafe, or null: a core.hooksPath already 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 .githooks counts 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-*.sample entries under <git rev-parse --git-common-dir>/hooks, immune to a foreign core.hooksPath; wiring would make git ignore them). Every git spawn passes env: process.env (Bun's default child env is a startup snapshot), so GIT_CONFIG_* overrides reach the child. A core.hooksPath of /dev/null in 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 with gitChildEnv() minus GIT_CONFIG_GLOBAL/SYSTEM/NOSYSTEM, so an inherited GIT_DIR, GIT_WORK_TREE or GIT_CONFIG* cannot redirect it) returns skipped_hooks_off before anything is written, --force included, hooksPathBlocker names it without wiring advice, and inspectFrontmatterHook returns null so doctor never proposes a refresh install-hook would skip. Any other blocker returns installed_unwired — the hook is written, core.hooksPath stays untouched, and the CLI prints the reason + the manual git config core.hooksPath .githooks step. Pinned by test/frontmatter-install-hook.test.ts.

  • src/commands/doctor/checks/outside-content-fences.ts — outside_content_fences (GBRA-221, BRAIN, registered before fence_integrity). Lists facts (row_num set, active; world-visible counted apart), active takes and links_fence links indexed from a fence on an imported page whose body is outside-authored text (Google email/meeting pages, every GitHub-source page, pages with transcript_import frontmatter). 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 an ask_user review fix (gbrain get) and removes nothing.

  • src/commands/doctor/checks/owner-host-stale.ts + src/commands/doctor/checks/embedding-plane.ts — GBRA-248: doctor owner_host_stale (writes waiting on worktrees whose owner is stale per persistence/owner-activity.ts; fix is the read-only writer status) and embedding_plane_disagreement (the config file disables embeddings while the database does not and holds vectors; fix is enableArgv from core/readiness.ts for the stored model and width).