Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(search): remove relational triplet scoring (sealed E4 failed: 17% fire rate, +0.39 against the +2.0 bar)

garrytan688619e61b7c
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index b4388173e9..c59b790c25 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -194,8 +194,7 @@ hybrid recall + fusion:
├── vector (HNSW on chunk embeddings, per-page max-pool)
├── keyword (BM25 via tsvector)
├── title-phrase arm
- ├── relational (typed-edge recall arm — relational queries only; triplet-scored
- │ when search.triplet_scoring is on — src/core/search/triplet-score.ts)
+ ├── relational (typed-edge recall arm — relational queries only)
├── source-aware re-rank (CASE in SQL)
├── role-tagged arms; variant/clause lists weighted by search.expansion_variant_budget INSIDE the fusion (fusion-lists.ts)
└── page-grain RRF fusion → cosine re-score → post-fusion boosts
@@ -288,7 +287,7 @@ Two cross-cutting seams sit around the pipeline rather than inside it:
a near-identical candidate set. `search.crag_think=true` (local callers)
escalates a still-weak result to `think`.
-### Use-attributed feedback and triplet scoring
+### Use-attributed feedback
Answers from `query`, `search`, `think`, `synthesize` and `recall` record the
pages they used (with the revision read) and the typed edges on their
@@ -297,10 +296,8 @@ owner) moves each element's weight `w` by `w + α·(r − w)`; the feedback stag
then multiplies the ordering score by `1 + λ·2·(w − 0.5)`. It runs after the
reranker, on the reranker's score when it reordered the list, because a boost
applied before the cross-encoder would be erased; raw scores stay untouched,
-so autocut and evidence grading are unchanged. Triplet scoring orders the
-relational arm by how close each (page, edge, page) triplet is to the query,
-over a wider candidate fetch, so a seed with many neighbors is no longer cut
-alphabetically. Neither ever runs a query-language string: the relational arm
+so autocut and evidence grading are unchanged. No retrieval path runs a
+query-language string: the relational arm
and `traverse_graph` take only typed parameters into fixed SQL, and
`test/raw-query-routing-guard.test.ts` pins that no op accepts query text as
SQL or graph syntax. Guide: [retrieval feedback](../guides/retrieval-feedback.md).
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 27b05e6ac6..1a946e359a 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -41,5 +41,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/db-repair.ts` — `gbrain db-repair [--yes] [--apply-rewrites] [--json] [--force] [--undo-last-rewrite] [--dry-run]`: ENGINE-FREE Postgres-access repair, sibling of pglite-repair (PGLite brains are redirected there). Never calls connectEngine; default invocation is DIAGNOSE-ONLY (`--dry-run` is an explicit alias). Consent is tiered and flag-gated, never TTY-dependent: auto tier under `--yes` (bounded reconnects, pending migrations in-process, `CREATE EXTENSION vector`, `docker start` of gbrain's own container via `docker-postgres.ts`); rewrite tier under `--yes --apply-rewrites` only (config-file `database_url` rewrites — pooler form, session pooler, `?sslmode=require` — printed first, candidate connect-probed BEFORE persisting, receipted, undo-able); manual tier never applied (credentials/paused-project/env recipes printed — relaying the recipe IS the repair). `--apply-rewrites` without `--yes` is an error. Invariants: fix targets derive only from the CURRENT config URL, never error text; the prober uses exactly ONE connection (`poolSize: 1` — diagnosing pool exhaustion with a 10-connection pool would worsen the outage); rewrite cooldown is ≤24h per (reason, action) with `--force` bypass while auto-tier fixes are NEVER cooldown-blocked (availability first); every rewrite stores the prior URL in the 0600 `~/.gbrain/db-repair-undo.json` (a secret — never the redacted receipts) and `--undo-last-rewrite` (`--yes`-gated) restores it — undo runs INSIDE the advisory lock, emits the same `--json` envelope, validates the record's postgres:// scheme before restoring, and is itself reversible (the outgoing URL becomes the new undo record); an `O_EXCL`-created advisory lockfile blocks concurrent double-rewrites (check-then-write race closed; one stale-holder retry; other write failures stay fail-open); a healthy probe exits 0 "nothing to fix" (the forged-marker defense) and additionally REPORTS (never rewrites) stale DB-plane `engine`/`database_url` rows; the schema probe treats a ZERO-ROW `pg_extension` result as `pgvector_missing` (the query never errors on an absent extension); the docker arm matches the container's REAL inspected host port (`deps.docker.hostPort`) as well as the default 5434; a successful rewrite prints the "restart long-lived gbrain processes" note (config rewrites reach NEW processes only). Refusals: thin-client (no local DB), non-host brain resolution (a mount outage must never rewrite host config — mount-targeted repair is a filed TODO), PGLite (→ pglite-repair). Injectable `DbRepairDeps` prober/executor seam for tests; `defaultDeps.probeAccess` is also reused by the init ladder (one prober, one contract). Pinned by `test/db-repair.serial.test.ts`. D2 (`json: 'document'`): a healthy/fixed report is the pretty legacy document; an unfixed one (exit 1) is a one-line `database_error` envelope leading with the report keys (`reason` = diagnosis reason, fix = the tier's next step: `--yes` for auto, `--yes --apply-rewrites` with consent `credentials` for rewrite, none for manual); pre-probe refusals keep their stderr line and add an envelope (`unknown_flag`/`invalid_params` exit 2, `requires_local_engine`, `config_error`, `lock_busy`, `not_found`, `no_brain`). Healthy success shape: `test/e2e/cli-json-commands-postgres.test.ts`.
-- `src/commands/feedback.ts` — `gbrain feedback status [--json]` (settings, answers recorded, ratings by signal, learned weights, triplet importance state, 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.
+- `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.
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 4bc9d8bcf8..e4f6800133 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -31,5 +31,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/feedback-boost.ts` — the use-attributed feedback ranking stage. `applyFeedbackStage(engine, results, { reranked })` reads each result page's learned weight (`retrieval_weights`, half its learned deviation when the page changed since) and current `content_hash` in one query by page id, stamps `content_hash` (answer recording uses it) and, when `feedback.influence` λ > 0, multiplies the ordering score by `1 + λ·2·(w − 0.5)` (bounded `[1 − λ, 1 + λ]`, stamped `feedback_boost`). The ordering score is `rerank_score` when the reranker reordered the list (unscored tail rows stay after the head) and the fused `score` otherwise; raw `score`/`rerank_score` are never modified, so autocut and evidence read the same values. Neutral weights return the list untouched. Called once from `hybrid/rank.ts` `rerankAndPin` (between the reranker and the relational re-pin) and at the end of both keyword-only paths in `hybrid/keyword-only.ts`; paths that bypass `hybridSearch` get no feedback. Fail-open (errors counted, shown by `gbrain feedback status`). Pinned by `test/feedback-boost.test.ts` and `test/e2e/feedback-parity.test.ts`.
-- `src/core/search/triplet-score.ts` — triplet scoring of the relational arm, enabled by `search.triplet_scoring` (penalty `search.triplet_penalty`, default 3.0). Each edge on a row's `relational_path_edges` is a (from page, edge, to page) triplet scored as the sum of page distances (`1 − cosine` of the query vector with the page's first chunk vector in the arm's embedding column, or `1 − content-term overlap` with the title without a vector) and an edge distance (`1 − overlap` with the humanized link type plus the link's context), each scaled by `2 − importance` (importance = feedback weight mapped into `0.5 ± λ`; neutral when feedback is off); missing parts cost the penalty. A row scores its worst triplet; lower is better, ties keep fanout order. `hybrid/arms.ts` `buildRelationalList` widens the fanout (`limit·4`, min 100, max 400 via `RelationalFanoutOpts.wide`) and `scoreRelationalArm` scores and trims back to the caller's limit on every hybrid path (null query vector on keyless paths). Rows carry `triplet: { worst, parts }` for `--explain`. `search/read-enrichment.ts` `readRelationalFanout` supplies `path_edges` (stored-direction `from|type|to` along each row's representative path, also used for feedback attribution) and the `wide` cap. Pure `scoreRow` exported. Pinned by `test/triplet-score.test.ts`.
diff --git a/docs/guides/retrieval-feedback.md b/docs/guides/retrieval-feedback.md
index abc45a7db2..af89a9811c 100644
--- a/docs/guides/retrieval-feedback.md
+++ b/docs/guides/retrieval-feedback.md
@@ -77,7 +77,7 @@ gbrain config set feedback.learn false # keep learned weights, stop learning
| Key | Default | Meaning |
|---|---|---|
-| `feedback.enabled` | true | Recording, ratings, `answer_id` and the ranking effect. Off also makes relational triplet scoring treat every weight as neutral. |
+| `feedback.enabled` | true | Recording, ratings, `answer_id` and the ranking effect. |
| `feedback.learn` | true | Write new learning. Off keeps applying learned weights. |
| `feedback.influence` | 0.1 | λ: the ranking multiplier stays within `[1 - λ, 1 + λ]` (max 0.5). |
| `feedback.implicit` | true | Learn from `think`/`synthesize` citations for the brain owner. |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d0a8c4bde7..5dc5c95ddb 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -22,8 +22,8 @@ src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in
src/core/operations.ts 338 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts)
src/core/pglite-engine.ts 2926 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)
src/core/postgres-engine.ts 2917 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured)
-src/core/search/hybrid.ts 1586 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +2 triplet scoring: scoreRelationalArm before the keyword-only and vector-fallback returns (logic in hybrid/arms.ts + search/triplet-score.ts)
-src/core/types.ts 2136 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +10 retrieval feedback: SearchResult feedback_boost/content_hash/triplet/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field)
+src/core/search/hybrid.ts 1586 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
+src/core/types.ts 2136 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field)
src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
src/commands/init.ts 1869 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1841 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: FEEDBACK_CONFIG_KEYS import and the feedback/triplet keys in KNOWN_CONFIG_KEYS
+src/core/config.ts 1841 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)
diff --git a/src/commands/feedback.ts b/src/commands/feedback.ts
index b2728b89fe..631818f3a1 100644
--- a/src/commands/feedback.ts
+++ b/src/commands/feedback.ts
@@ -52,7 +52,6 @@ export async function runFeedback(engine: BrainEngine, args: string[]): Promise<
const [settings, status] = await Promise.all([loadFeedbackSettings(engine), feedbackStatus(engine)]);
const report = {
settings,
- triplet_importance: settings.enabled && settings.influence > 0 ? 'active' : 'neutral (feedback off)',
...status,
dropped_events_this_process: droppedFeedbackEvents(),
stage_errors_this_process: feedbackStageErrors(),
@@ -66,7 +65,6 @@ export async function runFeedback(engine: BrainEngine, args: string[]): Promise<
`Answers recorded (last ${settings.eventRetentionDays} days): ${status.events}`,
`Ratings: ${status.ratings_explicit} explicit, ${status.ratings_cited} from citations${status.last_rating_at ? ` (last ${status.last_rating_at.toISOString()})` : ''}`,
`Learned weights: ${status.weights_total} (${status.weights_off_neutral} away from neutral)`,
- `Triplet importance: ${report.triplet_importance}`,
];
if (status.top_client_share_7d !== null && status.top_client_share_7d > 0.8 && status.ratings_explicit > 10) {
lines.push(`Warning: one client made ${Math.round(status.top_client_share_7d * 100)}% of ratings in the last 7 days. If that is not expected, run \`gbrain feedback reset\` and review that client's write grant.`);
diff --git a/src/core/config.ts b/src/core/config.ts
index fac199d6c0..638f952097 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1314,9 +1314,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.mcp_keyword_only',
REMOTE_PRIVATE_PAGES_KEY,
'search.track_retrieval',
- // Retrieval feedback (feedback/settings.ts) and relational triplet scoring.
+ // Retrieval feedback (feedback/settings.ts).
'feedback.enabled', 'feedback.learn', 'feedback.influence', 'feedback.implicit', 'feedback.alpha',
- 'feedback.max_ratings_per_hour', 'feedback.event_retention_days', 'feedback.rating_prompt', 'search.triplet_scoring', 'search.triplet_penalty',
+ 'feedback.max_ratings_per_hour', 'feedback.event_retention_days', 'feedback.rating_prompt',
// #4415: per-brain query-intent pattern extensions (JSON bank→regex[]),
// merged over the shipped banks in src/core/search/query-intent.ts.
'search.intent_patterns',
diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.ts
index 881fdec7c1..2be4c1cc08 100644
--- a/src/core/search/explain-formatter.ts
+++ b/src/core/search/explain-formatter.ts
@@ -92,10 +92,6 @@ export function formatResultExplain(
anyBoost = true;
lines.push(` + feedback ×${fmt(result.feedback_boost)} (use-attributed ratings)`);
}
- if (result.triplet !== undefined) {
- anyBoost = true;
- lines.push(` • triplet worst=${fmt(result.triplet.worst)} over ${result.triplet.parts.length} edge(s)`);
- }
if (result.reranker_delta !== undefined && result.reranker_delta !== 0) {
anyBoost = true;
const arrow = result.reranker_delta > 0 ? '↑' : '↓';
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index a25b6cfbda..7a8602f190 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -45,7 +45,7 @@ import {
} from './query-cache.ts';
import { resolveHybridRequest } from './hybrid/request.ts';
import { prepareSemanticCache, resolveCacheSearchMode, semanticCacheSkipped, serveSemanticCacheHit } from './hybrid/cache-stages.ts';
-import { buildPostFusionOpts, buildRelationalList, resolveModalityAndQueries, runLexicalArms, runVectorArms, scoreRelationalArm } from './hybrid/arms.ts';
+import { buildPostFusionOpts, buildRelationalList, resolveModalityAndQueries, runLexicalArms, runVectorArms } from './hybrid/arms.ts';
import { searchVectorFallback, searchWithoutEmbeddings } from './hybrid/keyword-only.ts';
import { expandStructuralNeighbors, finalizeHybridResults, fuseArms, rerankAndPin, sizeReturnPool } from './hybrid/rank.ts';
@@ -1105,14 +1105,12 @@ export async function hybridSearch(
// vector-arm query embedding without the gateway, so provider
// availability is irrelevant — skip the keyword-only short-circuit.
if (opts?.decide?.keywordOnly || (!opts?.queryEmbedFn && !isAvailable('embedding', providerProbe) && !willTryMultimodal)) {
- await scoreRelationalArm(req, relationalList, null);
return searchWithoutEmbeddings(req, lexical, relationalList, postFusionOpts, providerProbe);
}
const { effectiveModality, unifiedRouting, queries } = await resolveModalityAndQueries(req);
const { vectorArms, queryEmbedding, imageQueryEmbedding, unifiedDone } =
await runVectorArms(req, { effectiveModality, unifiedRouting, queries, multimodalProviderProbe });
- await scoreRelationalArm(req, relationalList, vectorArms.length === 0 ? null : queryEmbedding);
if (vectorArms.length === 0) {
return searchVectorFallback(req, lexical, relationalList, postFusionOpts);
}
diff --git a/src/core/search/hybrid/arms.ts b/src/core/search/hybrid/arms.ts
index 846fe478fc..a52a61787e 100644
--- a/src/core/search/hybrid/arms.ts
+++ b/src/core/search/hybrid/arms.ts
@@ -3,7 +3,6 @@
* Each stage reads the resolved request (HybridRequest, request.ts) and
* writes its per-request accumulators only as `req.<field>`.
*/
-import { applyTripletScoring, loadTripletSettings } from '../triplet-score.ts';
import type { ModalityMode } from '../query-intent.ts';
import type { ExactLookupOpts } from '../exact-lookup.ts';
import type { HybridRequest } from './request.ts';
@@ -171,14 +170,11 @@ export async function buildRelationalList(req: HybridRequest): Promise<SearchRes
// path; the parser only matches text-shaped relational queries anyway.)
let relationalList: SearchResult[] = [];
if (resolvedMode.relationalRetrieval) {
- const keep = opts?.limit ?? resolvedMode.searchLimit;
- const triplet = await loadTripletSettings(engine);
relationalList = await buildRelationalArm(engine, query, {
sourceId: opts?.sourceId,
sourceIds: opts?.sourceIds,
depth: resolvedMode.relational_retrieval_depth,
- limit: triplet.enabled ? Math.min(Math.max(keep * 4, 100), 400) : keep,
- wide: triplet.enabled,
+ limit: opts?.limit ?? resolvedMode.searchLimit,
// #4352 remediation: the arm hydrates titles + compiled_truth snippets
// straight from pages — thread the caller's private-page gate or a
// remote relational query bypasses the keyword/vector visibility clause.
@@ -187,27 +183,10 @@ export async function buildRelationalList(req: HybridRequest): Promise<SearchRes
takesHoldersAllowList: opts?.takesHoldersAllowList,
onMeta: opts?.onRelationalMeta,
});
- if (triplet.enabled) tripletKeep.set(relationalList, { keep, penalty: triplet.penalty });
}
return relationalList;
}
-const tripletKeep = new WeakMap<SearchResult[], { keep: number; penalty: number }>();
-
-/**
- * Triplet-score the relational arm in place (no-op unless
- * `search.triplet_scoring` widened it in buildRelationalList), then trim it
- * back to the caller's limit. Keyless paths pass a null query vector.
- */
-export async function scoreRelationalArm(req: HybridRequest, list: SearchResult[], queryEmbedding: Float32Array | null): Promise<void> {
- const pending = tripletKeep.get(list);
- if (!pending) return;
- tripletKeep.delete(list);
- await applyTripletScoring(req.engine, req.query, list, {
- queryEmbedding, column: req.resolvedCol.name, keep: pending.keep, penalty: pending.penalty,
- });
-}
-
/** Modality routing (with the opt-in LLM tie-break) and query expansion. */
export async function resolveModalityAndQueries(req: HybridRequest) {
const { query, opts, resolvedMode, suggestions, degraded } = req;
diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.ts
index cd759bf4dc..1a5467bbec 100644
--- a/src/core/search/read-enrichment.ts
+++ b/src/core/search/read-enrichment.ts
@@ -18,7 +18,7 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
if (!seeds?.length) return [];
const depth = Math.min(Math.max(1, opts?.depth ?? 2), 3);
const direction = opts?.direction ?? 'both';
- const limit = Math.min(Math.max(1, opts?.limit ?? 50), opts?.wide ? 400 : 200);
+ const limit = Math.min(Math.max(1, opts?.limit ?? 50), 200);
const params: unknown[] = [seeds, depth, limit];
const policy = hasReadPolicy(opts) ? opts : undefined;
const seed = pageReadFilter('p', policy, params, !!policy);
diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.ts
index 9f1fd8ed57..ae03fe2043 100644
--- a/src/core/search/relational-recall.ts
+++ b/src/core/search/relational-recall.ts
@@ -41,8 +41,6 @@ export interface RelationalArmOpts extends PageReadPolicy {
sourceIds?: string[];
depth?: number;
limit?: number;
- /** Fetch up to 400 candidates for triplet scoring. */
- wide?: boolean;
vocab?: RelationVocab;
/**
* #4352 remediation — hide `visibility: private` pages from the arm's
@@ -331,7 +329,6 @@ export async function buildRelationalArm(
direction: parsed.direction,
depth: opts.depth,
limit: opts.limit,
- wide: opts.wide,
};
if (parsed.kind === 'connects' && parsed.seeds.length === 2) {
diff --git a/src/core/search/triplet-score.ts b/src/core/search/triplet-score.ts
deleted file mode 100644
index 795c950112..0000000000
--- a/src/core/search/triplet-score.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-/**
- * Triplet scoring for the relational (typed-edge) recall arm.
- *
- * Each edge on a candidate's representative path is a triplet (from page,
- * edge, to page). Its score sums three distances to the query, each in
- * [0, 2] and scaled by (2 − importance):
- * - page distance: 1 − cosine(query vector, the page's first chunk vector),
- * in the same embedding column the vector arm used; lexical fallback
- * (1 − content-term overlap with the title) without a query vector;
- * - edge distance: 1 − content-term overlap of the query with the
- * humanized link type plus the link's context sentence;
- * - a missing part (no chunk, no vector, no context) costs a fixed penalty.
- * Importance is the element's learned feedback weight mapped into
- * 0.5 ± λ (neutral 0.5 when feedback is off). A candidate's score is its
- * worst triplet, so one irrelevant hop is never hidden by a relevant one.
- * Lower is better; ties keep the fanout order. Fail-open.
- */
-import type { BrainEngine } from '../engine.ts';
-import type { SearchResult } from '../types.ts';
-import { contentTerms } from './crag.ts';
-import { effectiveInfluence, loadFeedbackSettings } from '../feedback/settings.ts';
-import { NEUTRAL_WEIGHT, readWeights } from '../feedback/store.ts';
-
-export const DEFAULT_TRIPLET_PENALTY = 3.0;
-
-export interface TripletSettings {
- enabled: boolean;
- penalty: number;
-}
-
-const CACHE_TTL_MS = 30_000;
-let cache: { ts: number; engine: BrainEngine; value: TripletSettings } | null = null;
-
-export async function loadTripletSettings(engine: BrainEngine): Promise<TripletSettings> {
- const now = Date.now();
- if (cache && cache.engine === engine && now - cache.ts < CACHE_TTL_MS) return cache.value;
- const get = async (k: string) => { try { return await engine.getConfig(k); } catch { return null; } };
- const [on, penalty] = await Promise.all([get('search.triplet_scoring'), get('search.triplet_penalty')]);
- const p = Number(penalty);
- const value: TripletSettings = {
- enabled: ['true', '1', 'on', 'yes'].includes((on ?? '').trim().toLowerCase()),
- penalty: Number.isFinite(p) && p > 0 && p <= 10 ? p : DEFAULT_TRIPLET_PENALTY,
- };
- cache = { ts: now, engine, value };
- return value;
-}
-
-export function _resetTripletSettingsCacheForTests(): void {
- cache = null;
-}
-
-export function termOverlap(queryTerms: Set<string>, text: string): number {
- if (queryTerms.size === 0) return 0;
- const terms = contentTerms(text);
- let hit = 0;
- for (const t of queryTerms) if (terms.has(t)) hit++;
- return hit / queryTerms.size;
-}
-
-function cosine(a: Float32Array, b: Float32Array): number {
- let dot = 0, na = 0, nb = 0;
- const n = Math.min(a.length, b.length);
- for (let i = 0; i < n; i++) { dot += a[i]! * b[i]!; na += a[i]! * a[i]!; nb += b[i]! * b[i]!; }
- return na > 0 && nb > 0 ? dot / Math.sqrt(na * nb) : 0;
-}
-
-export interface TripletInputs {
- queryTerms: Set<string>;
- penalty: number;
- /** distance in [0, 2] per page key 'source:slug', absent = missing */
- pageDistance: Map<string, number>;
- /** context text per edge key 'source:from|type|to' ('' = no context), absent = unknown edge */
- edgeContext: Map<string, string>;
- pageImportance: Map<string, number>;
- edgeImportance: Map<string, number>;
-}
-
-/** Pure scorer: worst triplet per row (lower is better). */
-export function scoreRow(row: SearchResult, inp: TripletInputs): SearchResult['triplet'] | undefined {
- const source = row.source_id ?? 'default';
- const edges = row.relational_path_edges ?? [];
- if (edges.length === 0) return undefined;
- const parts: NonNullable<SearchResult['triplet']>['parts'] = [];
- for (const edge of edges) {
- const [from, type, to] = edge.split('|');
- if (!from || !type || !to) continue;
- const scale = (imp: number | undefined) => 2 - (imp ?? NEUTRAL_WEIGHT);
- const dist = (key: string) => inp.pageDistance.get(key) ?? inp.penalty;
- const fromKey = `${source}:${from}`;
- const toKey = `${source}:${to}`;
- const edgeKey = `${source}:${edge}`;
- const ctx = inp.edgeContext.get(edgeKey);
- const edgeText = `${type.replace(/[_-]+/g, ' ')} ${ctx ?? ''}`;
- const edgeDistance = ctx === undefined || ctx === ''
- ? inp.penalty
- : 1 - termOverlap(inp.queryTerms, edgeText);
- const f = dist(fromKey) * scale(inp.pageImportance.get(fromKey));
- const e = edgeDistance * scale(inp.edgeImportance.get(edgeKey));
- const t = dist(toKey) * scale(inp.pageImportance.get(toKey));
- parts.push({ edge, from: round(f), edge_distance: round(e), to: round(t), total: round(f + e + t) });
- }
- if (parts.length === 0) return undefined;
- return { worst: Math.max(...parts.map(p => p.total)), parts };
-}
-
-function round(n: number): number {
- return Math.round(n * 10_000) / 10_000;
-}
-
-/**
- * Score and reorder the relational arm in place, then keep the first
- * `keep` rows. Returns true when scoring ran.
- */
-export async function applyTripletScoring(
- engine: BrainEngine,
- query: string,
- list: SearchResult[],
- opts: { queryEmbedding: Float32Array | null; column: string; keep: number; penalty: number },
-): Promise<boolean> {
- if (list.length === 0) return false;
- try {
- const pageKeys = new Map<string, { source_id: string; slug: string }>();
- const edgeKeys = new Map<string, { source_id: string; from: string; type: string; to: string }>();
- for (const r of list) {
- const source = r.source_id ?? 'default';
- for (const edge of r.relational_path_edges ?? []) {
- const [from, type, to] = edge.split('|');
- if (!from || !type || !to) continue;
- pageKeys.set(`${source}:${from}`, { source_id: source, slug: from });
- pageKeys.set(`${source}:${to}`, { source_id: source, slug: to });
- edgeKeys.set(`${source}:${edge}`, { source_id: source, from, type, to });
- }
- }
- if (edgeKeys.size === 0) return false;
- const pages = [...pageKeys.values()];
- const chunkRows = await engine.executeRaw<{ source_id: string; slug: string; title: string; chunk_id: number | string | null }>(
- `SELECT p.source_id, p.slug, p.title,
- (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = p.id ORDER BY cc.chunk_index ASC LIMIT 1) AS chunk_id
- FROM pages p
- JOIN unnest($1::text[], $2::text[]) AS r(source_id, slug) ON p.source_id = r.source_id AND p.slug = r.slug
- WHERE p.deleted_at IS NULL`,
- [pages.map(p => p.source_id), pages.map(p => p.slug)],
- );
- const queryTerms = contentTerms(query);
- const pageDistance = new Map<string, number>();
- if (opts.queryEmbedding) {
- const ids = chunkRows.map(r => r.chunk_id).filter((id): id is number | string => id != null).map(Number);
- const vectors = ids.length > 0 ? await engine.getEmbeddingsByChunkIds(ids, opts.column) : new Map<number, Float32Array>();
- for (const r of chunkRows) {
- const v = r.chunk_id == null ? undefined : vectors.get(Number(r.chunk_id));
- if (v) pageDistance.set(`${r.source_id}:${r.slug}`, 1 - cosine(opts.queryEmbedding, v));
- }
- } else {
- for (const r of chunkRows) pageDistance.set(`${r.source_id}:${r.slug}`, 1 - termOverlap(queryTerms, `${r.title} ${r.slug.replace(/[/_-]+/g, ' ')}`));
- }
- const edges = [...edgeKeys.values()];
- const ctxRows = await engine.executeRaw<{ source_id: string; from_slug: string; link_type: string; to_slug: string; context: string }>(
- `SELECT fp.source_id, fp.slug AS from_slug, l.link_type, tp.slug AS to_slug, max(l.context) AS context
- FROM links l
- JOIN pages fp ON fp.id = l.from_page_id
- JOIN pages tp ON tp.id = l.to_page_id
- JOIN unnest($1::text[], $2::text[], $3::text[], $4::text[]) AS e(source_id, from_slug, link_type, to_slug)
- ON fp.source_id = e.source_id AND fp.slug = e.from_slug AND l.link_type = e.link_type AND tp.slug = e.to_slug
- GROUP BY fp.source_id, fp.slug, l.link_type, tp.slug`,
- [edges.map(e => e.source_id), edges.map(e => e.from), edges.map(e => e.type), edges.map(e => e.to)],
- );
- const edgeContext = new Map<string, string>();
- for (const r of ctxRows) edgeContext.set(`${r.source_id}:${r.from_slug}|${r.link_type}|${r.to_slug}`, r.context ?? '');
-
- const settings = await loadFeedbackSettings(engine);
- const influence = effectiveInfluence(settings);
- const toImportance = (w: number) => NEUTRAL_WEIGHT + influence * 2 * (w - NEUTRAL_WEIGHT);
- const pageImportance = new Map<string, number>();
- const edgeImportance = new Map<string, number>();
- if (influence > 0) {
- const pw = await readWeights(engine, 'page', pages.map(p => ({ source_id: p.source_id, key: p.slug })));
- for (const [k, w] of pw) pageImportance.set(k, toImportance(w));
- const ew = await readWeights(engine, 'link', edges.map(e => ({ source_id: e.source_id, key: `${e.from}|${e.type}|${e.to}` })));
- for (const [k, w] of ew) edgeImportance.set(k, toImportance(w));
- }
-
- const inputs: TripletInputs = { queryTerms, penalty: opts.penalty, pageDistance, edgeContext, pageImportance, edgeImportance };
- const scored = list.map((r, index) => {
- const t = scoreRow(r, inputs);
- if (t) r.triplet = t;
- return { r, index, score: t?.worst ?? Number.POSITIVE_INFINITY };
- });
- scored.sort((a, b) => (a.score - b.score) || (a.index - b.index));
- list.splice(0, list.length, ...scored.slice(0, Math.max(1, opts.keep)).map(s => s.r));
- return true;
- } catch {
- list.splice(opts.keep);
- return false;
- }
-}
diff --git a/src/core/types.ts b/src/core/types.ts
index faf30920f5..09eefcf26b 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -952,8 +952,6 @@ export interface SearchResult {
feedback_boost?: number;
/** The page's content_hash when this result was retrieved (stamped while retrieval feedback is enabled). */
content_hash?: string | null;
- /** Relational-arm triplet score and its parts (src/core/search/triplet-score.ts); lower is better. */
- triplet?: { worst: number; parts: Array<{ edge: string; from: number; edge_distance: number; to: number; total: number }> };
/** Multiplier applied by applySalienceBoost. */
salience_boost?: number;
/** Multiplier applied by applyRecencyBoost. */
@@ -1544,8 +1542,6 @@ export interface RelationalFanoutOpts extends PageReadPolicy {
sourceIds?: string[];
/** Hard cap on returned candidate nodes. Default 50. */
limit?: number;
- /** Allow up to 400 candidates (triplet scoring re-ranks the wider set). */
- wide?: boolean;
}
// Timeline
diff --git a/test/config-search-registry.test.ts b/test/config-search-registry.test.ts
index f9480e5c4b..d523f5382d 100644
--- a/test/config-search-registry.test.ts
+++ b/test/config-search-registry.test.ts
@@ -28,8 +28,6 @@ const DIRECTLY_READ_SINGLETONS = [
'search.intent_patterns', // search/query-intent.ts
'search.source_boosts', // search/mode.ts snapshot + ops/search.ts
'search.alias_token_hop', // search/mode.ts snapshot
- 'search.triplet_scoring', // search/triplet-score.ts
- 'search.triplet_penalty', // search/triplet-score.ts
'search.adaptive_return', // return-policy.ts via loadConfigWithEngine
'search.adaptive_return_entity_max',
'search.adaptive_return_other_max',
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 174ed83b1a..e69f78d779 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1195,8 +1195,7 @@
"seedRefs?: { source_id: string; slug: string; }[] | undefined",
"sourceId?: string | undefined",
"sourceIds?: string[] | undefined",
- "takesHoldersAllowList?: string[] | undefined",
- "wide?: boolean | undefined"
+ "takesHoldersAllowList?: string[] | undefined"
],
"name": "RelationalFanoutOpts"
},
@@ -1364,7 +1363,6 @@
"thread_id?: string | undefined",
"title: string",
"title_match_boost?: number | undefined",
- "triplet?: { worst: number; parts: Array<{ edge: string; from: number; edge_distance: number; to: number; total: number; }>; } | undefined",
"type: string",
"unverified?: boolean | undefined"
],
@@ -8085,8 +8083,7 @@
"seedRefs?: { source_id: string; slug: string; }[] | undefined",
"sourceId?: string | undefined",
"sourceIds?: string[] | undefined",
- "takesHoldersAllowList?: string[] | undefined",
- "wide?: boolean | undefined"
+ "takesHoldersAllowList?: string[] | undefined"
],
"name": "RelationalFanoutOpts"
},
@@ -8254,7 +8251,6 @@
"thread_id?: string | undefined",
"title: string",
"title_match_boost?: number | undefined",
- "triplet?: { worst: number; parts: Array<{ edge: string; from: number; edge_distance: number; to: number; total: number; }>; } | undefined",
"type: string",
"unverified?: boolean | undefined"
],
diff --git a/test/triplet-score.test.ts b/test/triplet-score.test.ts
deleted file mode 100644
index f791440d9c..0000000000
--- a/test/triplet-score.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * Relational-arm triplet scoring: the pure scorer (summed, importance-scaled
- * distances, missing-part penalty, worst hop) and the end-to-end arm on PGLite
- * (path edges from the fanout, the wider fetch that reaches candidates past
- * the alphabetical cut, lexical fallback without a query vector).
- */
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { installFixtureChunks } from './helpers/page-projection.ts';
-import { buildRelationalArm } from '../src/core/search/relational-recall.ts';
-import { applyTripletScoring, scoreRow, type TripletInputs } from '../src/core/search/triplet-score.ts';
-import type { SearchResult } from '../src/core/types.ts';
-
-function row(slug: string, edges: string[]): SearchResult {
- return {
- slug, page_id: 1, title: slug, type: 'person' as never, chunk_text: '', chunk_source: 'compiled_truth',
- chunk_id: 0, chunk_index: 0, score: 0, stale: false, source_id: 'default', relational_path_edges: edges,
- };
-}
-
-function inputs(over: Partial<TripletInputs> = {}): TripletInputs {
- return {
- queryTerms: new Set(['payment']), penalty: 3, pageDistance: new Map(), edgeContext: new Map(),
- pageImportance: new Map(), edgeImportance: new Map(), ...over,
- };
-}
-
-describe('scoreRow', () => {
- test('sums the three distances, each scaled by (2 - importance)', () => {
- const t = scoreRow(row('people/bo', ['people/bo|works_at|companies/acme']), inputs({
- pageDistance: new Map([['default:people/bo', 0.2], ['default:companies/acme', 0.4]]),
- edgeContext: new Map([['default:people/bo|works_at|companies/acme', 'Bo leads payments at Acme']]),
- }))!;
- expect(t.parts[0]!.from).toBeCloseTo(0.3, 4);
- expect(t.parts[0]!.edge_distance).toBeCloseTo(0, 4);
- expect(t.parts[0]!.to).toBeCloseTo(0.6, 4);
- expect(t.worst).toBeCloseTo(0.9, 4);
- });
-
- test('missing page vectors and empty edge context cost the penalty', () => {
- const t = scoreRow(row('people/bo', ['people/bo|works_at|companies/acme']), inputs({
- edgeContext: new Map([['default:people/bo|works_at|companies/acme', '']]),
- }))!;
- expect(t.worst).toBeCloseTo(3 * 1.5 * 3, 4);
- });
-
- test('higher importance lowers the score; the worst hop decides', () => {
- const base = inputs({
- pageDistance: new Map([['default:a', 0.1], ['default:b', 0.1], ['default:c', 1.5]]),
- edgeContext: new Map([['default:a|knows|b', 'payment'], ['default:b|knows|c', 'payment']]),
- });
- const t = scoreRow(row('c', ['a|knows|b', 'b|knows|c']), base)!;
- expect(t.worst).toBe(Math.max(...t.parts.map(p => p.total)));
- expect(t.worst).toBeCloseTo((0.1 + 0 + 1.5) * 1.5, 4);
- const trusted = scoreRow(row('c', ['b|knows|c']), { ...base, pageImportance: new Map([['default:c', 0.6]]) })!;
- expect(trusted.worst).toBeLessThan((0.1 + 1.5) * 1.5);
- });
-});
-
-describe('relational arm with triplet scoring [pglite]', () => {
- let eng: PGLiteEngine;
-
- beforeAll(async () => {
- eng = new PGLiteEngine();
- await eng.connect({});
- await eng.initSchema();
- await eng.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'A company.', timeline: '' });
- for (let i = 0; i < 60; i++) {
- const slug = `people/a${String(i).padStart(2, '0')}-example`;
- await eng.putPage(slug, { type: 'person', title: `Person ${i}`, compiled_truth: 'Works at Acme.', timeline: '' });
- await installFixtureChunks(eng, slug, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Works at Acme.' }]);
- await eng.addLink(slug, 'companies/acme-example', 'on the sales team', 'works_at', 'manual');
- }
- await eng.putPage('people/zed-example', { type: 'person', title: 'Zed Example', compiled_truth: 'Payments engineer.', timeline: '' });
- await installFixtureChunks(eng, 'people/zed-example', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Payments engineer.' }]);
- await eng.addLink('people/zed-example', 'companies/acme-example', 'leads the payments platform', 'works_at', 'manual');
- }, 60_000);
-
- afterAll(async () => {
- await eng.disconnect();
- });
-
- test('fanout rows carry their stored-direction path edges', async () => {
- const list = await buildRelationalArm(eng, 'who works at acme-example', { limit: 5 });
- expect(list.length).toBeGreaterThan(0);
- for (const r of list) expect(r.relational_path_edges).toEqual([`${r.slug}|works_at|companies/acme-example`]);
- });
-
- test('without scoring the alphabetical cut drops the relevant person; the wide fetch plus scoring keeps it first', async () => {
- const narrow = await buildRelationalArm(eng, 'who works at acme-example', { limit: 10 });
- expect(narrow.map(r => r.slug)).not.toContain('people/zed-example');
- const wide = await buildRelationalArm(eng, 'who works at acme-example', { limit: 100, wide: true });
- expect(wide.map(r => r.slug)).toContain('people/zed-example');
- const ran = await applyTripletScoring(eng, 'who works on payments at acme-example', wide, {
- queryEmbedding: null, column: 'embedding', keep: 10, penalty: 3,
- });
- expect(ran).toBe(true);
- expect(wide).toHaveLength(10);
- expect(wide[0]!.slug).toBe('people/zed-example');
- expect(wide[0]!.triplet!.worst).toBeLessThan(wide[1]!.triplet!.worst);
- });
-});