Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chore(todos): LHF wave 2 bookkeeping; interactive scale ceilings bind 20k (item 11)
garrytan34344500fa7a
diff --git a/TODOS.md b/TODOS.mdindex ea85cd6726..8ab87a447e 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,25 @@# TODOS+## LHF wave 2 follow-ups (filed 2026-10-15, GBRA-107)++Context: gbrain-evals `docs/plans/2026-10-15-lhf-wave-2/PLAN.md` ("NOT in scope" and "Round-2 dispositions"), audits in `docs/plans/2026-10-15-lhf-wave-2/audit/`. Reviewer findings are in `docs/plans/2026-10-15-lhf-wave-2/reviews/`: round-2 ids (`ceo-native-N`, `eng-outside-N`, ...) are in `findings.jsonl` and the matching `<phase>-<voice>.md`; round-1 findings are in the `*.r1.md` files.++- [ ] **P2 — Tool-result size: one payload plan (old item 8 and the larger levers).** **What:** agent tool results are the cost lever left (gbrain's own provider calls are about 1% of a Cat 40 bill; only GPT-6.1 Sol is dearer per successful task than plain files, 0.32 vs 0.24 $ on Hard world M). `chunk_text` is 59% of search output and repeated searches 6.5%. Lean-row default elision needs structured per-brain `row_defaults` that `query` can recover by machine and that keep the `[gbrain dates]` labels and the `create_safety` guard; `context_pack` compaction needs an opt-in format or a v2 protocol decision, because `MEMORY_VERBS_v1` freezes card fields and `budget_used`. **Gate:** a powered, preregistered Cat 40 rule decided before any spend. **Findings:** `eng-native.r1.md` F3, F11; `eng-outside.r1.md` F9, F10, F15; `dx-outside.r1.md` F1, F2, F4; `ceo-outside.r1.md` F2, F3; `audit/cost.md`. **Effort:** L. **Priority:** P2.+- [ ] **P2 — Skip the PGLite keyword count above a page threshold (old item 4).** **What:** the count runs serially with the search on PGLite's one connection, so deferring it saves about 0 ms; the saving is in skipping it. Needs a distinct `skipped` state (not `unavailable`), an honest denominator, and the original grace deadline preserved. **Gate:** the rule in "Measure the keyword count at scale" (under 1% `keyword_count_unavailable`, under 100 ms added p50 on the 55k slot). **Findings:** `eng-native.r1.md` F4; `eng-outside.r1.md` F4; `dx-outside.r1.md` F8. **Effort:** S. **Priority:** P2.+- [ ] **P2 — Expansion model and rewrite count (old item 10).** **What:** Haiku 5.5 for query expansion needs one resolver shared by serving and `gbrain models`, an unchanged OCR fallback (the expansion model is also the OCR fallback) and unchanged init auto-pin rules. Expansion is off by default since item 0, so the saving is small. Goes with TODO-D (`TIER_DEFAULTS`, `synthesize`/`think` on Opus 4.7 at $0.094 per call, other utility-tier callers); #6335 stays open as TODO-D input. **Findings:** `eng-native.r1.md` F14, F15; `eng-outside.r1.md` F14; `ceo-outside.r1.md` F6, F7; `dx-outside.r1.md` F6. **Effort:** M. **Priority:** P2.+- [ ] **P2 — Post-fusion read fan-out, fusion prefetch and the CLI config snapshot (from item 5).** **What:** item 5 kept the MCP per-request config snapshot, one settings statement per search, concurrent response-meta reads and concurrent entity resolve. These three each need their own failure-semantics and staleness design: one `Promise.all` must not become one failure domain for post-fusion ranking, the fan-out needs a pool-2 check, and a CLI snapshot needs a staleness rule for long-running commands. **Findings:** `eng-native.r1.md` F8, F9; `eng-outside.r1.md` F3, F11. **Effort:** M. **Priority:** P2.+- [ ] **P2 — Off-reply `mcp_request_log` insert (dropped from item 5).** **What:** writing the request-log row after the reply takes its insert off every MCP call's reply path, but a bounded queue can drop rows, and an in-memory drop counter in `serve --http` is invisible to `gbrain doctor` (another process) and resets on restart, while the admin dashboard, per-client usage and `last_used_at` read the table. **Fix:** persist losses (a summary row or a counter row doctor reads), a config switch for blocking inserts when an operator needs complete audit rows, usage reports qualified over incomplete windows, and shutdown that awaits in-flight inserts; test forced backpressure, insert failure and restart from a fresh process. **Findings:** `dx-native-1`, `dx-native-2`, `eng-native-9`, `eng-outside-9`, `dx-outside-3`. **Effort:** M. **Priority:** P2.+- [ ] **P2 — Automatic expression-statistics recovery on Postgres (item 6's heavier fix).** **What:** item 6 analyzes after every index build and recovers an already-present expression index automatically on PGLite; on Postgres doctor `planner_stats_stale` names it and an operator runs `gbrain repair planner-stats --apply`, because autovacuum waits for 10% of a table to change. **Fix:** a bounded maintenance owner (for example `post-upgrade` or the resident `serve` running `repairPlannerTable` once for flagged tables), with retry after a failed first ANALYZE, restricted roles kept as unknown, and no statement added to any search. **Findings:** `eng-native-7`, `ceo-outside-4`, `dx-outside-4`, `eng-outside-6`. **Effort:** S. **Priority:** P2.+- [ ] **P3 — Broader attendance verbs behind an anchor-type guard (item 9's heavier fix).** **What:** item 9 added only unambiguous phrasings ("were present at", "was in the room for", "took part in", "participated in", "sat in on", "participants"). "joined", "was at" and "went to" would route employment, education and location questions to attendance unless guarded by the anchor's type, and a guard only in the resolver still changes keyword weights and title-mention ranking (`relational-plan.ts` `isRelationalQuery` feeds `hybrid/rank.ts` and `hybrid/request.ts`). The guard must also follow schema-pack aliases of meeting types instead of hardcoding `meeting`/`event` (`titleSeedTypes`). **Gate:** zero false routes on the competing-intent split measured on chosen relations and returned evidence, and final results equal to master on the negatives. **Findings:** `eng-outside-1`, `eng-native-13`, `ceo-native-11`, `ceo-outside.r1.md` F5. **Effort:** M. **Priority:** P3.+- [ ] **P3 — Year tokens in planner anchors (old item 9b).** **What:** the planner refuses a quoted anchor before the year rule runs, so the year-title exception never applies to it; the fix needs anchor spans kept through the parser. **Findings:** `eng-native.r1.md` F16; `eng-outside.r1.md` F13. **Effort:** S. **Priority:** P3.+- [ ] **P2 — Type-filtered vector search through the index walk.** **What:** a `type`/`types`/date filter marks the vector statement narrowed and disables the walk (`vector-statement.ts`), so the planner seq-scans `content_chunks` and sorts every candidate: `searchVector` p50 with `types: ['email']` 462 ms against 56 ms unfiltered on Postgres 20k, 195 against 58 ms on PGLite 10k. The second half of the email-typed symptom in "Profile email-typed searches on a real-corpus slot". **Fix:** let the walk serve type filters, choosing by the filter's page share from `pg_stats`. **Source:** `audit/latency.md` §2. **Effort:** M. **Priority:** P2.+- [ ] **P3 — PGLite keyword arm computes `stale` for every matched chunk.** **What:** `pglite-engine.ts` evaluates `SELECT MAX(te.created_at) FROM timeline_entries` per chunk before `ORDER BY … LIMIT` (Postgres uses `false AS stale`); removing it took `searchKeyword(limit 60)` at 10k pages from 78.6 to 72.0 ms with an empty timeline. **Fix:** compute it in the outer per-page select, after the limit, with the existing stale-flag tests as the equivalence check. **Source:** `audit/latency.md` §10. **Effort:** S. **Priority:** P3.+- [ ] **P3 — Query-embed in-flight dedupe.** **What:** the query-embed cache stores only resolved vectors, so two concurrent identical queries (an agent's AND/OR prefetch, `query` escalation) both call the provider. **Fix:** memoize the in-flight promise per key. **Source:** `audit/latency.md` §9. **Effort:** S. **Priority:** P3.+- [ ] **P2 — Size budget for the `full` tool surface.** **What:** every registration pins `full` (about 27.5k tokens per turn against 5.1k for `starter`), and the 25k-character ceiling in `test/mcp-schema-budget.test.ts` covers only `starter`. Narrowing the listing is out (hidden-tool tasks fail on `starter`, 0/20 vs 17/20), so the lever is description size on `full`. **Fix:** extend the per-tool budget to full-only tools, largest first, toward about 80k characters, moving long guidance to `docs/mcp/TOOL_REFERENCE.md`. **Gate:** the keyless ceiling test plus a Cat 40 dev smoke on `full` including family H (about $40). **Source:** `audit/cost.md` C5; `eng-native.r1.md` (deferred to its own DX plan). **Effort:** M. **Priority:** P2.+- [ ] **P2 — Chat-key-only `tokenmax` without a reranker.** **What:** with only a chat key the reranker is skipped silently and fused hybrid lost to bare vectors on concept questions (Cat 13: 99 vs 118 of 181 first-place, an old pin). **Fix:** re-measure on the current tree first, then pick the default for reranker-less installs. **Source:** `audit/evals-findings.md` §9. **Effort:** M. **Priority:** P2.+- [ ] **P3 — Retrieval findings carried from gbrain-evals, each needing a fresh measurement before a fix.** Family E (long meeting transcripts ranked below short mail: renewal briefs 4-5/30 hybrid vs 14/30 keyword-only, stale numbers); mention links only on the next stale sweep, not on write; H1 aggregation at the floor on sealed and S worlds (4-11 of 60-120 cells, oracle about 100%); proactive brief gaps (task-start requests without a lexicon word fired 0/8; a cold first `turn_context` of 169-339 ms against the 300 ms cutoff dropped the brief in 3/9 smoke cells); scoped HNSW recall (10% source scope on 1M chunks: recall@50 0.777). **Source:** `audit/evals-findings.md` §11-15. **Effort:** S to L each. **Priority:** P3.+- [ ] **P3 — #6771 (@lubosxyz): repair code metadata without re-embedding.** **What:** a contributor PR in a different subsystem (about $1 avoided per 15M-token repository on repair); out of this wave's scope, to revise in its own fix wave. **Source:** `audit/cost.md` C9. **Effort:** S. **Priority:** P3.+## Cat 40 Hard fix wave follow-ups (filed 2026-10-07, GBRA-39)Context: gbrain-evals `docs/plans/2026-10-07-cat40-hard-fix/PLAN.md`; this wave fixes document retrieval only.@@ -319,8 +339,8 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro- [x] **P2 — `--sources none` for OAuth clients.** **Completed: Foundations 2** — `auth rescope --client <id> --sources none` and `--takes-holders a,b|none` (migration v203).- [x] **P2 — Seat follow-ups (#4618).** **Completed: Foundations 2** — the OpenClaw context-engine heartbeat reports seat reasons (write failure, conflict, invalid label) with their hints, and a pattern page drops a seat its reflections no longer share. The Codex trust-hash item closed with no code: the Codex SessionEnd command never carries a seat (`buildCodexSessionEndCommand` takes only the gbrain binary; `--seat` prints a note to set `GBRAIN_SEAT` instead), so adding a seat cannot change its trust hash.- [x] **P2 — Large-brain ceilings in the scale tier.** **Completed: Foundations 2** — every scale run asserts the F4d ceilings through the real CLI (`scripts/scale/f4d.ts`: progress-aware sync deadline, loud embed budget stop and serve boot window at every tier, the 20,000-file `sources add` at 20k and up), so the 50k tier carries them once `trend.ts` unlocks it; delegated syncs keep the progress-aware deadline.-- [ ] **P2 — MCP search on Postgres slows sharply between 10k and 20k pages.**- **What:** the scale tier's MCP-path search p50 on Postgres is 615 ms at 20k pages (69.5 ms at 10k) and the source-scoped grant search 1,169 ms, while PGLite at 20k answers in 27 and 19 ms. Interactive ceilings are defined only up to 10k, so this is report-only. **Fix:** read the captured plans in the 20k Postgres report (`scale-report-postgres-20000`) for the statement that grows, and add a 20k ceiling once fixed. **Effort:** M. **Priority:** P2.+- [x] **P2 — MCP search on Postgres slows sharply between 10k and 20k pages.** **Closed (2026-10-15, LHF wave 2 item 11):** no longer reproduces. Nightly scale tier `scale-report-postgres-20000` MCP search p50: 74.1 ms (10-06), 45.8 (10-08), 33.7 (10-10), 36.3 ms on 10-15 (run 38708604843; the same run's 10k: 68.4 ms; PGLite 20k 71.1 ms). The 615 ms figure was v0.60.53.0. `scripts/scale/gates.ts` now applies the interactive ceilings (MCP search 500 ms, `get_health` 1000 ms) at 20k as well as 10k, report-only until `trend.ts` says stable.+ **What (as filed):** the scale tier's MCP-path search p50 on Postgres is 615 ms at 20k pages (69.5 ms at 10k) and the source-scoped grant search 1,169 ms, while PGLite at 20k answers in 27 and 19 ms. Interactive ceilings are defined only up to 10k, so this is report-only. **Fix:** read the captured plans in the 20k Postgres report (`scale-report-postgres-20000`) for the statement that grows, and add a 20k ceiling once fixed. **Effort:** M. **Priority:** P2.- [ ] **P3 — `embed --stale` takes far longer than its time budget to stop.****What:** with `GBRAIN_EMBED_TIME_BUDGET_MS=1500` the scale tier's budget-stop check exits 11 correctly but after about 61 s on a 20k brain (2.6 s on an empty one), so the budget does not bound wall time. **Fix:** profile what runs before the first batch and after the stop (stale counting, the remaining-count query) and keep it inside the budget. **Effort:** S. **Priority:** P3.- [ ] **P3 — `findOrphans` recomputes the full orphan set per call.**@@ -397,8 +417,8 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro**What:** the time from the end of `gbrain upgrade` to both new repairs previewed was estimated (target under 5 minutes), not measured. **Fix:** time it once on a seeded PGLite brain with `captured_facts_active` and `loop_facts_drift` present and record it in the upgrade guide. **Effort:** XS. **Priority:** P3.- [ ] **P2 — Corrections lost to the cosine 0.95 drop (V1).****What:** `remember` and `extract_facts` keep the unguarded same-entity cosine ≥ 0.95 drop. Measured with voyage-4, 4 of 20 correction pairs (negation, number or date) and 2 of 10 word-change corrections ("The offsite is in Lisbon" / "... Porto") score ≥ 0.95, so an explicit correction can be dropped as a duplicate. Capture lanes never drop by cosine (shadow-count only), and the `claimsDiverge` negation/number/date guard catches the 4 but not the 2 word-change pairs, so a token guard alone is not enough to re-enable any cosine drop. **Fix:** make the explicit lanes' drop safe for single-word substitutions (or raise the threshold) before relying on it, and only then consider a measured capture threshold, with the V1 pairs in the wave notes as the test table. **Effort:** S. **Priority:** P2.-- [ ] **P3 — JIT off for the remote title arm.**- **What:** on a 40k-page Postgres brain most of the remaining common-term title-arm latency is JIT compilation (for example 17 ms execution, 504 ms JIT): the visibility subplans push the cost estimate past `jit_above_cost`. **Fix:** `SET LOCAL jit = off` around the remote title statement, measured against the same benchmark before shipping. **Effort:** S. **Priority:** P3.+- [x] **P3 — JIT off for the remote title arm.** **Done (#6110, from #6039):** the Postgres title, keyword, CJK and vector search statements pass `jitOff: true` to `withScopedReadTransaction`, which runs `SET LOCAL jit = off` (`src/core/postgres-engine/search-settings.ts`); the LHF wave 2 latency audit's statement log shows it before each title statement, and its JIT scan found only the typed-search type check (wave item 1) still compiling.+ **What (as filed):** on a 40k-page Postgres brain most of the remaining common-term title-arm latency is JIT compilation (for example 17 ms execution, 504 ms JIT): the visibility subplans push the cost estimate past `jit_above_cost`. **Fix:** `SET LOCAL jit = off` around the remote title statement, measured against the same benchmark before shipping. **Effort:** S. **Priority:** P3.- [ ] **P3 — Move `captured-facts` database-only expiry onto the loop-fact retirement mutation.****What:** `repair captured-facts` expires database-only rows through its own maintenance request, while `loops_close` and `repair loop-facts` share `persistence/loop-fact-retirement.ts`. **Fix:** one coordinated fact-retirement mutation for all three, so the expiry rules and receipts cannot drift. **Effort:** S. **Priority:** P3.- [ ] **P3 — Throttle autopilot's per-tick `git fetch` while an upgrade is held.**@@ -496,7 +516,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro**What:** the SessionStart context pack keys its cursor on `sanitizeSessionId(session_id)` (`src/commands/hook.ts`, ambient recall arm), so two raw ids that sanitize to the same string share a cursor. **Fix:** key on a hash of the raw id in both the session-start and compact arms together. **Effort:** S. **Priority:** P3.- [ ] **P3 — Colon-slug escape mapping for Windows portability (#5032 follow-up).****What:** colon slugs such as `calendar:abc` are writable again, but on Windows a write whose file name would contain `:` is refused (`colon_slug_windows_write_through`) and sync skips such files. **Fix:** a reversible slug-to-filename escape for `:` so colon-slug brains stay portable to Windows checkouts. **Cons:** a filename mapping every reader and writer must agree on. **Effort:** M. **Priority:** P3.-- [ ] **P2 — #4951: PGLite `serve --http` wedges on stale planner statistics.**+- [ ] **P2 — #4951: PGLite `serve --http` wedges on stale planner statistics.** **Status (2026-10-15): mitigated, unverified.** F4b analyzes stale hot tables before the first planner-sensitive read, during import and sync and on the consumer's idle tick, and LHF wave 2 item 6 adds an ANALYZE after every index build plus maintenance-pass statistics for expression indexes that have none; doctor `planner_stats_stale` reports what remains. Not verified against the reporter's `readAdjacencyBoosts` plan. **Close when:** that plan (or `get_links`) stays fast on an upgraded PGLite brain without a manual ANALYZE.**What:** a reporter saw `readAdjacencyBoosts` take about 72 s with nested-loop plans; a full `ANALYZE` on pages, links, sources, timeline_entries and content_chunks dropped it to 21 ms. PGLite has no autovacuum and runs queries on the main thread, so a slow plan looks like a wedge. Cause likely, unverified for `get_links`. **Fix:** run `ANALYZE` on the hot tables after migrations, bulk import or sync and periodically from the owner, plus a doctor check for stale `last_analyze`. **Effort:** S-M. **Priority:** P2.- [x] **P3 — #5190: pin `search_path` for the two fact functions.** **Completed: fix wave 9** — every gbrain plpgsql function pins `search_path` (definitions plus the `function_search_path` migration (v211)); the fingerprint SQL functions schema-qualify their built-ins and stay inlinable.**What:** `gbrain_fact_fingerprint` and `gbrain_preserve_fact_withdrawal` (`src/core/facts/withdrawal-schema.ts`) have no pinned `search_path` (Supabase linter warning). `gbrain_fact_fingerprint` backs an index expression and must stay inlinable, so qualify its calls (`pg_catalog.`) instead of `SET search_path`; pin only the trigger function. **Effort:** S. **Priority:** P3.diff --git a/scripts/scale/gates.ts b/scripts/scale/gates.tsindex 8668000224..1c505515dc 100644--- a/scripts/scale/gates.ts+++ b/scripts/scale/gates.ts@@ -95,10 +95,14 @@ export const PLANNER_STATS_MIN_ROWS = PLANNER_STATS_MIN_PENDING;/** The plans the planner-health gate inspects (every captured read statement of these ops). */export const KEY_PLAN_OPS = ['get_backlinks', 'search (MCP path, remote)', 'get_health', 'find_orphans'] as const;export const HEADLINE_OP = 'search (MCP path, remote)';-/** Interactive ceilings (p50 ms), defined at 10k pages; report-only until trend.ts says stable. */+/**+ * Interactive ceilings (p50 ms), defined up to 20k pages; report-only until trend.ts says stable. 20k joined+ * once the Postgres MCP search slowdown between 10k and 20k stopped reproducing (nightly 2026-10-15, run+ * 38708604843, at 20k: MCP search 36.3 ms Postgres / 71.1 ms PGLite, get_health 246 / 585 ms).+ */export const CEILINGS_MS: Record<string, number> = { 'search (MCP path, remote)': 500, get_health: 1000 };-export const CEILING_PAGES = 10_000;-/** The interactive ceilings that apply at a brain size: defined at 10k, so they bind brains up to 10k pages. */+export const CEILING_PAGES = 20_000;+/** The interactive ceilings that apply at a brain size: they bind brains up to 20k pages (both nightly tiers). */export function ceilingsFor(pages: number): Record<string, number> {return pages <= CEILING_PAGES ? CEILINGS_MS : {};}diff --git a/test/scripts/scale-gates.test.ts b/test/scripts/scale-gates.test.tsindex 1702af3a2c..cb36e7afdb 100644--- a/test/scripts/scale-gates.test.ts+++ b/test/scripts/scale-gates.test.ts@@ -7,7 +7,7 @@*/import { describe, expect, test } from 'bun:test';import {- CEILINGS_MS, evaluateScaleGates, importProgressPerFile, RATE_MIN_PAGES, HEADLINE_OP, HOT_TABLES, KEY_PLAN_OPS, phaseLimitsMs, PLANNER_HEALTH_ENFORCED, PLANNER_STATS_MIN_ROWS,+ CEILING_PAGES, CEILINGS_MS, ceilingsFor, evaluateScaleGates, importProgressPerFile, RATE_MIN_PAGES, HEADLINE_OP, HOT_TABLES, KEY_PLAN_OPS, phaseLimitsMs, PLANNER_HEALTH_ENFORCED, PLANNER_STATS_MIN_ROWS,rateMeasure, resultHits, verdictLines, type GatePolicy, type RateMeasure, type ScaleReport,} from '../../scripts/scale/gates.ts';@@ -65,6 +65,16 @@ describe('scale gates under --enforce', () => {expect(enforced.failures[0]!.explain).toContain('Result (actual rows=1 loops=1)');});+ test('the interactive ceilings bind both nightly tiers (10k and 20k) and nothing larger', () => {+ expect(CEILING_PAGES).toBe(20_000);+ expect(ceilingsFor(10_000)).toEqual(CEILINGS_MS);+ expect(ceilingsFor(20_000)).toEqual(CEILINGS_MS);+ expect(ceilingsFor(20_001)).toEqual({});+ const report = { ...passingReport(), pages: 20_000 };+ report.ops[2] = { ...report.ops[2]!, p50_ms: CEILINGS_MS[HEADLINE_OP]! + 1 };+ expect(evaluateScaleGates(report, { ...ENFORCE, enforceCeilings: true }).failures.map(f => f.gate)).toEqual([`ceiling:${HEADLINE_OP}`]);+ });+test('a calibrated budget breach follows the ceilings switch', () => {const report = { ...passingReport(), budgets_ms: { list_pages: 9 } };expect(evaluateScaleGates(report, ENFORCE).reportOnlyBreaches.map(b => b.gate)).toEqual(['budget:list_pages']);