Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/master into capy/gbra69-write-throughput
time-attack75f0b880f91e
diff --cc docs/architecture/key-files/commands-4.mdindex 6df95bbd2a,2a1ec9d093..0573208a6d--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@@ -7,7 -7,7 +7,7 @@@ Current behavior and load-bearing invar- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both] [--source <id>] [--include-foreign]`: typed-edge relationship traversal (renders indented tree). The local walk is scoped to the resolved source (`--source` / `GBRAIN_SOURCE` / `.gbrain-source` / path match / brain default via `resolveSourceId`, the same scalar scope the `traverse_graph` op gets from `sourceScopeOpts`); an explicit `--source` that fails to resolve throws. `--include-foreign` (or `--source __all__`) drops the scope so the walk spans every source. The foreign-edge footer (`N edges to foreign-source pages hidden; pass --include-foreign`) prints only when the walk was actually scoped, so cross-source edges never disappear silently and the footer never describes a filter that did not apply. The local path uses `engine.traversePathsDetailed` and prints a stderr note when the walk hit `TRAVERSE_PATH_ROW_CAP` (shallowest edges kept; lower `--depth` or narrow with `--type`/`--direction`); the thin-client path goes through the `traverse_graph` op, which has no `source_id` param (the server scopes the walk to the caller's grant): an explicit `--source` there is rejected with exit 1 (same policy + wording as `applyThinClientSourceScope`, never silently dropped) and `--include-foreign` prints a stderr note that it is not forwarded. `--hop <link_type>:<object|subject>` (repeatable, 1-3) runs a typed chain through `runRelationalChain` locally or `traverse_graph` `hops` on a thin client; it is refused with `--type`/`--depth`/`--direction`, a malformed hop names the fix, and a host that ignored `hops` (older gbrain, detected via `ignoredRemoteParams` or a non-chain response) is refused with the upgrade message. Pinned by `test/graph-query.test.ts` (local) + `test/graph-query-thin-client-source-flag.serial.test.ts` (thin client; mocks `isThinClient` + `callRemoteTool`).- - `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.test.ts`. Each `--workers` child pool connects through `connectWithRetry` with `retryConnectTimeout: true` (#5946, see `src/core/db.ts`). A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).A managed import hands its files to `importManagedFiles` in batches (`nextImportBatch`) and accounts each file's settled result, in order, through the same `processFile` bookkeeping; held paths are skipped before the batch. `runImport`'s `onCollected` hands over its completed, unaborted walk (root-relative, before `--exclude`) as a `CollectedWalk`.-- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.test.ts`. Each `--workers` child pool connects through `connectWithRetry` with `retryConnectTimeout: true` (#5946, see `src/core/db.ts`). A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` (listing through `gitLsFiles` in `src/core/git-visible-files.ts`, memoized inside doctor's `withGitListingCache`) falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).`runImport`'s `onCollected` hands over its completed, unaborted walk (root-relative, before `--exclude`) as a `CollectedWalk`.++- `src/commands/import.ts` — `gbrain import <path> [--source-id <id> | --source <id>]`: page import with ordinary-import progress checkpoints and content-hash revalidation; company-brain ingestion resumes an approved committed manifest. `runImport` contains NO `process.exit`: every preflight/argv failure site (deferred-setup embedding sentinel, missing embedding credentials, invalid `--workers`, missing dir arg, unreadable target, symlinked input root in a managed brain, refused source-filesystem lock admission, configured-root refusals) prints its reason and next command to stderr, then throws the exported typed `ImportAbortError` (carries `exitCode` and, for a refused lock admission, the underlying error as `cause`), so in-process callers — the `sync_brain` MCP op, autopilot, the Minions `import` handler — survive a failed preflight as a normal tool/job error instead of the whole serving process dying mid-call. The CLI's `import` case catches it and exits `e.exitCode`. Pinned by `test/import-abort-error.test.ts`. Human-only output (the `info()` lines and the end-of-run `Import complete` summary) goes through `slog()` from `console-prefix.ts` — identical to `console.log` outside a wrap, but an in-process caller in its own `--json` mode (`sync --json` → `performFullSync` → `runImport`, wrapped in `withHumanLogsToStderr`) keeps stdout pure JSON; `import --json` itself sends them to stderr directly. Pinned by `test/sync-json-stdout-clean.test.ts` (first-sync case) + `test/import-json-stdout.test.ts`. The `--json` payload also carries `source_id`, the effective destination the pages were written to (`sourceId ?? 'default'`, identical to the ingest_log row and to the import-file write) — NOT the resolver's tier answer, since `runImport` adopts only flag/env/sole_non_default resolutions and lets dotfile/local_path/brain_default fall through to `default`; pinned by the `--json payload names …` cases in `test/import-source-id.test.ts`. `--source-id <id>` (alias `--source <id>`; passing both with different values aborts) routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`; `graph-query` takes `--source <id>`). Pinned by `test/import-source-id.test.ts`. An unscoped import that resolves to tier `seed_default` runs the default-write assessment through `assessDefaultWriteGuardOnce(engine)` (memoized per engine — in-process callers such as the `sync_brain` op, autopilot, and minion sync invoke `runImport` repeatedly on one engine) and WARNS via `formatDefaultWriteWarning(a, '--source-id')` when the brain's pages overwhelmingly live outside `default` — never aborts, since aborting would take an in-process host down mid-call; `GBRAIN_ALLOW_DEFAULT_WRITE=1` skips it. Pinned by `test/import-default-write-guard-once.test.ts`. `gbrain import` CLI + `runImport` library entrypoint. Ordinary imports use a path-set progress checkpoint via `src/core/import-checkpoint.ts`; their `runImport` path walks all current files, including previously completed paths, through the existing `importFile` content-hash comparison. Persisted path membership and an mtime before checkpoint flush do not prove the imported revision is still current. Unchanged files avoid re-import, while edits, new files, and failed files are reconsidered. Ordinary resume pays the full walk/read/hash cost rather than blindly skipping paths. Company-brain ingestion instead skips completed paths within its immutable approved committed manifest, using protected `op_checkpoints` entries keyed by the admission receipt; it does not resume from the ordinary JSON checkpoint. See [company-brain ingestion](company-brain.md). The walk still applies `sortNewestFirst()` for embed-cost ordering. A file enters `completed: Set<relativePath>` only when its `processFile` returns success (including content-hash short-circuit no-ops); failed files never enter the set so the next run retries them automatically with no manual `~/.gbrain/import-checkpoint.json` delete. Progress remains completion-based and sort-order-independent; old positional checkpoints are discarded with a stderr diagnostic. Checkpoint persists every 100 successful adds, not every 100 processed files. The `managedBookmark` opt (set by `performFullSync` when `runImport` is the full-sync engine) suppresses `runImport`'s own `sync.last_commit` advance so the shared `applySyncFailureGate` (`src/core/sync-failure-ledger.ts`) owns the bookmark + failure-ledger gating on that path — one gate decides advance/block/auto-skip across both sync paths. Pinned by `test/import-checkpoint.test.ts` + `test/import-resume.test.ts` (incl. the SLUG_MISMATCH retry case). `collectSyncableFiles`' shared emit filter `isCollectibleForWalker` applies the SAME segment-level `pruneDir` gate as incremental sync's `classifySync` — load-bearing for the `git ls-files` fast path, which enumerates tracked files under dot-dirs/vendored trees that the FS walk never descends into; without it `sync --full` would import (and resurrect soft-deleted) pages incremental sync excludes. Pinned by `test/import-git-fastpath-prune.test.ts`. `runImport` opts also carry `exclude` (glob filter over dir-relative paths, threaded by `performFullSync` for `sync --exclude`; warns when every file is excluded — NAV-4) and `slugRoot` (slug/`source_path` base for monorepo subdir syncs; the progress checkpoint stays dir-relative; ordinary imports do not use `resumeFilter` to skip paths). The `--json` payload carries, beside the counts, `unchanged` (content-hash no-ops), `malformed_skipped`, and `failures: [{path, error}]` — rethurned per-file failures `importFile` RETURNS (invalid frontmatter, oversize, symlink, slug mismatch) count under both `skipped`, anotd `errors`, are excluded from `unchanged`, and produce `status: "partial"` with a nonzero CLI exit. Failed imports retain their completed-path checkpoint; queued imports report failure instead of successful completion. The failure ledger is written only for gGit- repo dsitories, so the JSON faislure list remains a non-gGit caller's only per-file channel. Pinned by `test/import-json-stdout.test.ts`. Each `--workers` child pool connects through `connectWithRetry` with `retryConnectTimeout: true` (#5946, see `src/core/db.ts`). A directory the enclosing git repository ignores (for example a scratch folder under `.context/`) returns no `git ls-files` rows, so `gitListSyncableFiles` (listing through `gitLsFiles` in `src/core/git-visible-files.ts`, memoized inside doctor's `withGitListingCache`) falls back to the filesystem walk when `git check-ignore` reports the directory itself ignored; an explicit import of it no longer succeeds with zero files (`test/import-ignored-root.test.ts`).A managed import hands its files to `importManagedFiles` in batches (`nextImportBatch`) and accounts each file's settled result, in order, through the same `processFile` bookkeeping; held paths are skipped before the batch. `runImport`'s `onCollected` hands over its completed, unaborted walk (root-relative, before `--exclude`) as a `CollectedWalk`.- `src/commands/init-prefer-postgres.ts` — `runPreferPostgresLadder`: the Postgres-first install ladder behind `gbrain init --prefer-postgres [--allow-docker] [--allow-create-db] [--local-postgres] [--json]` (the zero-config `gbrain init` default stays PGLite; this flag is the harness lane). Five rungs, first usable wins, every reachable-but-unusable rung prints a one-line note and falls through (only the PGLite floor is terminal): (1) env URL; (2) Supabase Management-API DISCOVERY via `supabase-admin.ts` — `SUPABASE_ACCESS_TOKEN` (+ `SUPABASE_PROJECT_REF` on multi-project accounts, auto-selected on single-project ones) + `SUPABASE_DB_PASSWORD` (the API can't return it), ~10s timeouts, the discovered URL is a CANDIDATE connect-probed before anything persists, creation stays dashboard guidance, the token is never persisted/logged/echoed; (3) local Postgres, opportunistic (only when PG* env vars are set or `--local-postgres` — a blind localhost probe on peer-auth dev installs just burns a timeout) and detection-only (`CREATE DATABASE gbrain` needs explicit `--allow-create-db`); (4) docker via `docker-postgres.ts` (explicit `--allow-docker`; idempotent reuse recovers real credentials via docker inspect; readiness-polled); (5) `initPGLite` + explicit upgrade-later note. Calls `initPostgresCore` (typed `InitPostgresFailure`, no `process.exit` — the returnable core that makes rung fall-through possible) and reuses db-repair's `defaultDeps.probeAccess` prober. Prints the rung-entry criterion line (Postgres wins on concurrency/multi-machine/1000+ pages; PGLite keeps the per-turn hook lane) so the preference is informed, not silent. Guards: an ALREADY-CONFIGURED brain refuses the whole ladder (rung choice is environment-dependent, so a re-run during an outage would let the PGLite floor overwrite a healthy Postgres config — outages are db-repair's lane); a bare `DATABASE_URL` (vs the stated-intent `GBRAIN_DATABASE_URL`) is adopted only when the target is already a gbrain brain or holds no tables at all (`classifyDbContent`, fail-closed on foreign/unknown — deploy platforms export DATABASE_URL pointing at the APP's database); the docker rung content-guards BOTH reuse and fresh-create (a fresh container can attach a surviving `gbrain-pgdata` volume) and detects the surviving-volume auth mismatch (fresh password rejected → adoption/clean-start recipe instead of "never became reachable"); rung-note error text is redacted. `--json` emits ONE final `{status, engine, ladder_rung, url_source}` envelope and stdout is EXACTLY that document — `withStdoutToStderr` reroutes both `console.log` (Bun writes it to fd 1 directly) and bare `process.stdout.write` around the inner init cores.