Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): keep the GBRA-68 null-listing memo; outside-repo verdict lasts the scope, dropped only by sync-git writes or invalidateGitListingCache

time-attackc8bd1ae4b587
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index a9f1d7f66d..d4e1c699ed 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -40,7 +40,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers the façade: re-exports, `Check`/`DoctorReport` and report scoring, the `buildChecks` flag parse, `runDoctor`, output rendering and `--locks`; every check block lives in a registry entry under `doctor/checks/*` (refactor wave 1 W4 doctor), remediation in `doctor/remediate.ts`, wave checks in `doctor/wave-checks.ts`.
- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json`, Codex `config.toml` and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. `agent_contract` reads `readAgentContractEvents()` (7 days) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). `harness_wiring` with no registration drops every detected harness an enabled plugin lane covers (`enabledPluginLanes`): all covered → `ok`, `reason: plugin_lane_enabled` with the plugins, harnesses and a verify hint (plugin lanes are not smoke-tested); partly covered → the missing-registration warning for the uncovered harnesses only. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.
-- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; it lapses when a `.git` marker changes, and any repository-changing `sync-git.ts` command drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
+- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.
diff --git a/src/core/git-visible-files.ts b/src/core/git-visible-files.ts
index 836349d1d9..8042865fb8 100644
--- a/src/core/git-visible-files.ts
+++ b/src/core/git-visible-files.ts
@@ -1,13 +1,12 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import { execFileSync } from 'child_process';
import { lstatSync } from 'fs';
-import { dirname, join, resolve } from 'path';
+import { join, resolve } from 'path';
interface GitScope {
- /** Successful listings; a failure is not memoized (an outside-repo failure is, below, until a `.git` changes). */
- listings: Map<string, string>;
- /** Directories git reported outside any repository, each with the `.git` markers it saw then. */
- outside: Map<string, string>;
+ listings: Map<string, string | null>;
+ /** Directories git reported outside any repository. */
+ outside: Set<string>;
}
const gitScope = new AsyncLocalStorage<GitScope>();
@@ -19,12 +18,11 @@ const gitScope = new AsyncLocalStorage<GitScope>();
* each list or probe the same source checkout (frontmatter scan, fence census,
* slug collisions, the frontmatter hook) spawn git once instead of once per
* check; code outside the scope always spawns. A git command that changes a
- * repository (sync-git.ts) drops the scope's memo (`invalidateGitListingCache`),
- * and an outside-repo verdict lapses as soon as a `.git` appears, changes or
- * goes away in the directory or above it.
+ * repository through sync-git.ts drops the scope's memo
+ * (`invalidateGitListingCache`).
*/
export function withGitListingCache<T>(fn: () => Promise<T>): Promise<T> {
- return gitScope.run({ listings: new Map(), outside: new Map() }, fn);
+ return gitScope.run({ listings: new Map(), outside: new Set() }, fn);
}
/** Drop every listing and verdict memoized in the current scope (no-op outside one): call after changing a checkout inside it. */
@@ -34,55 +32,34 @@ export function invalidateGitListingCache(): void {
scope?.outside.clear();
}
-/** The `.git` entries from `dir` up to the filesystem root: what decides whether git finds a repository there. */
-function gitMarkers(dir: string): string {
- const seen: string[] = [];
- for (let at = dir; ; at = dirname(at)) {
- try {
- const st = lstatSync(join(at, '.git'));
- seen.push(`${at}\0${st.ino}\0${st.mtimeMs}`);
- } catch { /* no marker here */ }
- if (dirname(at) === at) return seen.join('\n');
- }
-}
-
-/** True when the current scope saw git report `dir` outside any repository and no `.git` marker changed since. */
+/** True when the current scope already saw git report `dir` outside any repository. */
export function knownOutsideGitRepo(dir: string): boolean {
- const scope = gitScope.getStore();
- const key = resolve(dir);
- const markers = scope?.outside.get(key);
- if (markers === undefined) return false;
- if (markers === gitMarkers(key)) return true;
- scope!.outside.delete(key);
- return false;
+ return gitScope.getStore()?.outside.has(resolve(dir)) ?? false;
}
/** Record a failed git command run in `dir`: its stderr saying "not a git repository" is remembered for the current scope. */
export function noteGitFailure(dir: string, error: unknown): void {
- const scope = gitScope.getStore();
const stderr = (error as { stderr?: unknown } | null)?.stderr;
- if (!scope || !/not a git repository/i.test(String(stderr ?? ''))) return;
- const key = resolve(dir);
- scope.outside.set(key, gitMarkers(key));
+ if (/not a git repository/i.test(String(stderr ?? ''))) gitScope.getStore()?.outside.add(resolve(dir));
}
/** `git -C <dir> ls-files <args>` stdout, or null when git fails (memoized inside withGitListingCache). */
export function gitLsFiles(dir: string, args: string[]): string | null {
const cache = gitScope.getStore()?.listings;
const key = `${dir}\0${args.join('\0')}`;
- const hit = cache?.get(key);
- if (hit !== undefined) return hit;
- if (knownOutsideGitRepo(dir)) return null;
- try {
- const stdout = execFileSync('git', ['-C', dir, 'ls-files', ...args], {
- encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'],
- });
- cache?.set(key, stdout);
- return stdout;
- } catch (error) {
- noteGitFailure(dir, error);
- return null;
+ if (cache?.has(key)) return cache.get(key)!;
+ let stdout: string | null = null;
+ if (!knownOutsideGitRepo(dir)) {
+ try {
+ stdout = execFileSync('git', ['-C', dir, 'ls-files', ...args], {
+ encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ } catch (error) {
+ noteGitFailure(dir, error);
+ }
}
+ cache?.set(key, stdout);
+ return stdout;
}
/**
diff --git a/test/git-listing-memo.serial.test.ts b/test/git-listing-memo.serial.test.ts
index b81ae9077f..947b878025 100644
--- a/test/git-listing-memo.serial.test.ts
+++ b/test/git-listing-memo.serial.test.ts
@@ -6,10 +6,8 @@
* and the census HEAD probe share the verdict), and the memo never hides a
* change: a git command that changes a repository (sync-git.ts) or an explicit
* `invalidateGitListingCache()` drops it, so a file added mid-run is listed by
- * the next listing; a repository created mid-run (here by a plain `git init`
- * that no hook sees) is found by the next probe because the verdict lapses
- * when a `.git` marker appears; and nothing outlives the run.
- * Fails when: a listing or verdict survives an in-run write or `git init`, the
+ * the next listing; and nothing outlives the run.
+ * Fails when: a listing or verdict survives an in-run sync-git write or invalidation, the
* memo leaks past its scope, or a non-repository directory is probed more than
* once per run.
* Temp directories and the system git ($0); synthetic content only.
@@ -99,17 +97,6 @@ describe('withGitListingCache memo', () => {
});
});
- test('a repository created mid-run with no hook is found by the next listing and discoverGitRoot', async () => {
- const dir = freshDir(false);
- await withGitListingCache(async () => {
- expect(names(dir)).toBeNull();
- expect(() => discoverGitRoot(dir)).toThrow('Not inside a git repository');
- execFileSync('/usr/bin/env', ['git', '-C', dir, 'init', '-q'], { stdio: 'ignore' });
- expect(names(dir)).toEqual(['a.md']);
- expect(discoverGitRoot(dir)).toBe(execFileSync('git', ['-C', dir, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim());
- });
- });
-
test('nothing outlives the run: a repository created after it is seen at once', async () => {
const dir = freshDir(false);
await withGitListingCache(async () => { expect(names(dir)).toBeNull(); });
diff --git a/test/git-visible-files.test.ts b/test/git-visible-files.test.ts
index 62796a6a9d..fe9fc0efa6 100644
--- a/test/git-visible-files.test.ts
+++ b/test/git-visible-files.test.ts
@@ -201,16 +201,13 @@ describe('withGitListingCache — doctor-scoped ls-files memo (GBRA-68)', () =>
});
});
- // GBRA-75 wave 10: the outside-repo verdict is memoized only until a `.git` appears, so a repository created
- // inside the scope is listed by the next call (test/git-listing-memo.serial.test.ts covers the spawn count).
- test('a failed listing is not reused inside the scope once a repository appears', async () => {
+ test('a failed listing is cached as null inside the scope', async () => {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-f6-cache-nogit-'));
cleanups.push(dir);
await withGitListingCache(async () => {
- expect(collectGitVisibleFiles(dir, md)).toBeNull();
expect(collectGitVisibleFiles(dir, md)).toBeNull();
git(dir, ['init', '-q', '-b', 'main']);
- expect(collectGitVisibleFiles(dir, md)).toEqual([]);
+ expect(collectGitVisibleFiles(dir, md)).toBeNull();
});
expect(collectGitVisibleFiles(dir, md)).toEqual([]);
});