Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): feedback ranking stage; record answers on query/search/think/synthesize/recall

garrytanad7315fa2a15
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index c8d143f471..8099a95e52 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli.ts 3199 ratchet +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured)
+src/cli.ts 3201 ratchet +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts)
src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)
src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2219 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts)
@@ -19,11 +19,11 @@ src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in th
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
src/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
-src/core/operations.ts 336 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)
+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 1584 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 2124 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)
+src/core/types.ts 2134 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)
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 1838 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)
+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/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/cli.ts b/src/cli.ts
index ad39bb129f..5285314141 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1641,9 +1641,11 @@ export function formatResult(
const incompleteNotice = incompleteStages.length > 0
? `Retrieval incomplete: ${incompleteStages.join(', ')}.\n`
: '';
+ const answerId = typeof meta?.answer_id === 'string' ? meta.answer_id : undefined;
+ if (answerId && results.length > 0) process.stderr.write(`answer: ${answerId} (rate with: gbrain rate ${answerId} 1-5)\n`);
if (params.json === true) {
if (incompleteNotice) process.stderr.write(incompleteNotice);
- return JSON.stringify(results, null, 2) + '\n';
+ return JSON.stringify(answerId ? results.map(r => ({ ...r, answer_id: answerId })) : results, null, 2) + '\n';
}
// T15/FOV-1: an empty result names its cause when the pipeline told us
// (degradation stages from _meta.retrieval / the local meta capture) —
diff --git a/src/core/config.ts b/src/core/config.ts
index e10fb83f24..7684290b30 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1,3 +1,4 @@
+import { FEEDBACK_CONFIG_KEYS } from './feedback/settings.ts';
import { readFileSync, writeFileSync, mkdirSync, chmodSync, existsSync, renameSync } from 'fs';
import { isAbsolute, join } from 'path';
import { homedir } from 'os';
@@ -1314,18 +1315,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'search.mcp_keyword_only',
REMOTE_PRIVATE_PAGES_KEY,
'search.track_retrieval',
- // Use-attributed retrieval feedback (src/core/feedback/settings.ts) and the
- // relational-arm triplet scoring knobs (src/core/search/triplet-score.ts).
- 'feedback.enabled',
- 'feedback.learn',
- 'feedback.influence',
- 'feedback.implicit',
- 'feedback.alpha',
- 'feedback.max_ratings_per_hour',
- 'feedback.event_retention_days',
- 'feedback.hint',
- 'search.triplet_scoring',
- 'search.triplet_penalty',
+ // Retrieval feedback (feedback/settings.ts) and relational triplet scoring.
+ ...FEEDBACK_CONFIG_KEYS, 'search.triplet_scoring', 'search.triplet_penalty',
// #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/feedback/record.ts b/src/core/feedback/record.ts
index 9fb54c34e8..a4888f1da9 100644
--- a/src/core/feedback/record.ts
+++ b/src/core/feedback/record.ts
@@ -224,3 +224,46 @@ export function _resetFeedbackRecordingForTests(): void {
dropped = 0;
answersSinceHint = new Map();
}
+
+/** Additive response-meta fields for an answer (none when feedback is off). */
+export function feedbackMetaFields(meta: AnswerFeedbackMeta | null): Record<string, unknown> {
+ if (!meta) return {};
+ return { ...(meta.answer_id ? { answer_id: meta.answer_id } : {}), feedback: meta.feedback };
+}
+
+/** Typed edges on the representative relational path of each returned relational-arm row. */
+export function relationalPathLinks(
+ rows: Array<{ slug: string; source_id?: string; relational_path_edges?: string[] }>,
+): EventLink[] {
+ const out: EventLink[] = [];
+ for (const r of rows) {
+ for (const edge of r.relational_path_edges ?? []) {
+ out.push({ source_id: r.source_id ?? 'default', edge_key: edge, to_slug: r.slug });
+ }
+ }
+ return out;
+}
+
+/**
+ * Record a think/synthesize answer: gathered pages are the used set; a page is
+ * cited only when synthesis succeeded and its bare cited slug is unambiguous
+ * among the gathered sources.
+ */
+export async function recordThinkAnswer(
+ ctx: OperationContext,
+ op: 'think' | 'synthesize',
+ result: {
+ synthesis_status?: string;
+ citations: Array<{ page_slug: string }>;
+ feedback_evidence?: Array<{ source_id: string; slug: string; content_hash: string | null }>;
+ },
+): Promise<AnswerFeedbackMeta | null> {
+ const evidence = result.feedback_evidence ?? [];
+ const citedSlugs = new Set(result.synthesis_status === 'ok' ? result.citations.map(c => c.page_slug) : []);
+ const sourcesBySlug = new Map<string, number>();
+ for (const e of evidence) sourcesBySlug.set(e.slug, (sourcesBySlug.get(e.slug) ?? 0) + 1);
+ return recordAnswer(ctx, {
+ op,
+ pages: evidence.map(e => ({ ...e, cited: citedSlugs.has(e.slug) && sourcesBySlug.get(e.slug) === 1 })),
+ });
+}
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 397f4a794e..146b96af22 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -1,3 +1,4 @@
+import { feedbackMetaFields, recordAnswer, relationalPathLinks } from '../feedback/record.ts';
import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';
import { deliverEvidence, effectivePlan, resolveEvidencePlan, type DeliveryMeta, type EvidencePlan } from '../search/evidence-delivery.ts';
import { randomUUID } from 'node:crypto';
@@ -563,6 +564,11 @@ const recall: Operation = {
...(r.delivered ? { delivered: r.delivered } : {}),
})),
...(searchDegraded ? { search_degraded: searchDegraded } : {}),
+ ...(searchDegraded ? {} : feedbackMetaFields(await recordAnswer(ctx, {
+ op: 'recall',
+ pages: packedResults.map(r => ({ source_id: r.source_id, slug: r.slug, content_hash: r.content_hash })),
+ links: relationalPathLinks(packedResults),
+ }))),
}
: {}),
...(budgetTokens !== null
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index ecd2fb6e31..8b747b605d 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -1,3 +1,4 @@
+import { feedbackMetaFields, recordAnswer, relationalPathLinks } from '../feedback/record.ts';
import { readHolders } from './context.ts';
/**
* Search operation cluster (search + query) — pure move from operations.ts
@@ -407,7 +408,7 @@ async function buildRetrievalResponseMeta(
queryText: string,
results: unknown[],
meta: HybridSearchMeta | null,
- opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string; declarations?: DeclarationMemo } = {},
+ opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string; declarations?: DeclarationMemo; feedbackOp?: 'query' | 'search' } = {},
): Promise<Record<string, unknown>> {
const m = meta as (HybridSearchMeta & { degraded?: unknown[]; retrieved_count?: number }) | null;
const hint = opts.conceptHint && looksConceptShaped(queryText)
@@ -454,6 +455,11 @@ async function buildRetrievalResponseMeta(
...(aliases.length ? { other_names: aliases } : {}),
...(heldFiles.length ? { held_files: heldFiles } : {}),
...(hint || readiness.hint ? { hint: [hint, readiness.hint].filter(Boolean).join(' ') } : {}),
+ ...(opts.feedbackOp ? feedbackMetaFields(await recordAnswer(ctx, {
+ op: opts.feedbackOp,
+ pages: (results as SearchResult[]).map(r => ({ source_id: r.source_id, slug: r.slug, content_hash: r.content_hash })),
+ links: relationalPathLinks(results as SearchResult[]),
+ })) : {}),
};
}
@@ -647,7 +653,7 @@ const search: Operation = {
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap,
- rows => buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations }));
+ rows => buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search' }));
},
scope: 'read', mutating: false,
cliHints: { name: 'search', positional: ['query'] },
@@ -1045,7 +1051,7 @@ const query: Operation = {
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap,
- async rows => ({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations })), crag }));
+ async rows => ({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query' })), crag }));
},
scope: 'read', mutating: false,
cliHints: { name: 'query', positional: ['query'] },
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index 0395cb51e0..3850266207 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -299,8 +299,12 @@ const think: Operation = {
const { keylessThinkNotice, thinkNotSavedNotice } = await import('../interop-notices.ts');
if (result.synthesis_status === 'no_llm') ctx.emitNotice?.(keylessThinkNotice());
if (remote && (Boolean(p.save) || Boolean(p.take))) ctx.emitNotice?.(thinkNotSavedNotice());
+ const { recordThinkAnswer, feedbackMetaFields } = await import('../feedback/record.ts');
+ const feedbackMeta = feedbackMetaFields(await recordThinkAnswer(ctx, 'think', result));
+ delete result.feedback_evidence;
return {
...result,
+ ...feedbackMeta,
// #1698 (#10): the persist-skip signal returns slug '' — map it (and any
// falsy) to null so callers never see an empty-string "slug".
saved_slug: savedSlug || null,
diff --git a/src/core/search/explain-formatter.ts b/src/core/search/explain-formatter.ts
index 6aeaa7f143..881fdec7c1 100644
--- a/src/core/search/explain-formatter.ts
+++ b/src/core/search/explain-formatter.ts
@@ -88,6 +88,14 @@ export function formatResultExplain(
const prefix = result.graph_session_prefix ?? '?';
lines.push(` - session_demote ×${fmt(result.session_demote_factor)} (prefix=${prefix})`);
}
+ if (result.feedback_boost !== undefined && result.feedback_boost !== 1.0) {
+ 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/feedback-boost.ts b/src/core/search/feedback-boost.ts
new file mode 100644
index 0000000000..9e90a96c53
--- /dev/null
+++ b/src/core/search/feedback-boost.ts
@@ -0,0 +1,100 @@
+/**
+ * Use-attributed feedback stage: multiply each result's ordering score by
+ * m = 1 + λ·2·(w − 0.5), with w the page's learned feedback weight (0.5 when
+ * never rated), so m stays within [1 − λ, 1 + λ] and a brain without ratings
+ * ranks exactly as before.
+ *
+ * It runs on the score that actually orders the list: the reranker's score on
+ * the reranked head when the reranker ran (a boost before the cross-encoder
+ * would be erased), the fused score otherwise. Raw `score` and `rerank_score`
+ * are never modified, so autocut and evidence grading read the same values as
+ * without feedback. The same read stamps each page's current content_hash for
+ * answer recording. Fail-open: any error leaves the list untouched.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { SearchResult } from '../types.ts';
+import { effectiveInfluence, loadFeedbackSettings } from '../feedback/settings.ts';
+import { NEUTRAL_WEIGHT } from '../feedback/store.ts';
+
+export interface FeedbackStageMeta {
+ applied: boolean;
+ boosted: number;
+ errored: boolean;
+}
+
+export function feedbackMultiplier(weight: number, influence: number): number {
+ return 1 + influence * 2 * (weight - NEUTRAL_WEIGHT);
+}
+
+async function readPageFeedback(
+ engine: BrainEngine,
+ pageIds: number[],
+): Promise<Map<number, { content_hash: string | null; weight: number }>> {
+ const rows = await engine.executeRaw<{ id: number | string; content_hash: string | null; weight: number | string | null }>(
+ `SELECT p.id, p.content_hash,
+ CASE WHEN w.weight IS NULL THEN NULL
+ WHEN p.content_hash IS DISTINCT FROM w.content_hash
+ THEN ${NEUTRAL_WEIGHT} + (w.weight - ${NEUTRAL_WEIGHT}) / 2
+ ELSE w.weight END AS weight
+ FROM pages p
+ LEFT JOIN retrieval_weights w
+ ON w.source_id = p.source_id AND w.element_kind = 'page' AND w.element_key = p.slug
+ WHERE p.id = ANY($1::int[])`,
+ [pageIds],
+ );
+ const out = new Map<number, { content_hash: string | null; weight: number }>();
+ for (const r of rows) {
+ out.set(Number(r.id), { content_hash: r.content_hash, weight: r.weight == null ? NEUTRAL_WEIGHT : Number(r.weight) });
+ }
+ return out;
+}
+
+/**
+ * Apply the stage in place and return the (possibly re-sorted) list.
+ * `reranked` says whether the reranker reordered this list.
+ */
+export async function applyFeedbackStage(
+ engine: BrainEngine,
+ results: SearchResult[],
+ opts: { reranked: boolean; onMeta?: (m: FeedbackStageMeta) => void },
+): Promise<SearchResult[]> {
+ if (results.length === 0) return results;
+ let meta: FeedbackStageMeta = { applied: false, boosted: 0, errored: false };
+ try {
+ const settings = await loadFeedbackSettings(engine);
+ if (!settings.enabled) return results;
+ const pageIds = [...new Set(results.map(r => r.page_id).filter(id => Number.isFinite(id)))];
+ const byPage = await readPageFeedback(engine, pageIds);
+ for (const r of results) {
+ const row = byPage.get(r.page_id);
+ if (row) r.content_hash = row.content_hash;
+ }
+ const influence = effectiveInfluence(settings);
+ if (influence <= 0) return results;
+ const scoreOf = (r: SearchResult): number | undefined =>
+ opts.reranked ? r.rerank_score : r.score;
+ let boosted = 0;
+ const keyed = results.map((r, index) => {
+ const base = scoreOf(r);
+ const weight = byPage.get(r.page_id)?.weight ?? NEUTRAL_WEIGHT;
+ if (base === undefined || !Number.isFinite(base) || weight === NEUTRAL_WEIGHT) {
+ return { r, index, key: base, scored: base !== undefined && Number.isFinite(base) };
+ }
+ const m = feedbackMultiplier(weight, influence);
+ r.feedback_boost = Math.round(m * 10_000) / 10_000;
+ boosted++;
+ return { r, index, key: base >= 0 ? base * m : base / m, scored: true };
+ });
+ meta = { applied: true, boosted, errored: false };
+ if (boosted === 0) return results;
+ const scored = keyed.filter(k => k.scored);
+ const unscored = keyed.filter(k => !k.scored);
+ scored.sort((a, b) => (b.key! - a.key!) || (a.index - b.index));
+ return [...scored, ...unscored].map(k => k.r);
+ } catch {
+ meta = { applied: false, boosted: 0, errored: true };
+ return results;
+ } finally {
+ opts.onMeta?.(meta);
+ }
+}
diff --git a/src/core/search/hybrid/keyword-only.ts b/src/core/search/hybrid/keyword-only.ts
index 1b76378d71..4c076a2d33 100644
--- a/src/core/search/hybrid/keyword-only.ts
+++ b/src/core/search/hybrid/keyword-only.ts
@@ -5,6 +5,7 @@
*/
import { type HybridRequest, applyIdentityBoosts, emitHybridMeta } from './request.ts';
import type { LexicalArms } from './arms.ts';
+import { applyFeedbackStage } from '../feedback-boost.ts';
import { type PostFusionOpts, RRF_K, rrfFusionWeighted, runPostFusionStages, stampContentFlags, stampUnverifiedExtractions } from '../hybrid.ts';
import { type RelationalEvidenceSlotDecision, ensureRelationalEvidenceSlot } from '../relational-recall.ts';
import type { SearchResult } from '../../types.ts';
@@ -46,6 +47,7 @@ export async function searchWithoutEmbeddings(
await runPostFusionStages(engine, noEmbedResults, postFusionOpts);
await applyIdentityBoosts(req, noEmbedResults);
noEmbedResults.sort((a, b) => b.score - a.score);
+ noEmbedResults = await applyFeedbackStage(engine, noEmbedResults, { reranked: false });
}
// T3/T4 — alias hop + evidence stamp even without an embedding provider
// (the named-thing fix is most valuable exactly when vector is unavailable).
@@ -149,6 +151,7 @@ export async function searchVectorFallback(
await runPostFusionStages(engine, fallbackResults, postFusionOpts);
await applyIdentityBoosts(req, fallbackResults);
fallbackResults.sort((a, b) => b.score - a.score);
+ fallbackResults = await applyFeedbackStage(engine, fallbackResults, { reranked: false });
}
const kwPreExact = await applyAliasHop(engine, dedupResults(fallbackResults), query, aliasHopOpts);
// #1663 — structural exact-lookup tier (slug / exact-title identity).
diff --git a/src/core/search/hybrid/rank.ts b/src/core/search/hybrid/rank.ts
index c6f01df81b..b2c0e7af8c 100644
--- a/src/core/search/hybrid/rank.ts
+++ b/src/core/search/hybrid/rank.ts
@@ -14,6 +14,7 @@ import { type MetadataBoostGateDecision, decideMetadataBoosts, lexicalArmsVoted
import { type PostFusionOpts, RRF_K, cosineReScore, resolveWalkDedupCap, rrfFusionWeighted, runPostFusionStages, stampContentFlags, stampUnverifiedExtractions, textVectorArmNonEmpty } from '../hybrid.ts';
import { type RelationalEvidenceSlotDecision, ensureRelationalEvidenceSlot } from '../relational-recall.ts';
import { type RelationalRerankPinDecision, pinRelationalRows } from '../relational-rerank-pin.ts';
+import { applyFeedbackStage } from '../feedback-boost.ts';
import { type RerankFailedReason, type RerankPassThroughReason, type RerankSkipReason, applyReranker } from '../rerank.ts';
import type { RerankMeta } from '../../ai/gateway.ts';
import { applyEvidenceGate, recordRerankReceipts, startRerankShadow } from '../decide-stage.ts';
@@ -239,7 +240,7 @@ export async function rerankAndPin(
relationalList: SearchResult[],
effectiveModality: ModalityMode,
) {
- const { query, opts, resolvedMode, degraded } = req;
+ const { engine, query, opts, resolvedMode, degraded } = req;
// v0.35.0.0+: cross-encoder reranker. Slots between dedup and slice so the
// reranker sees the full candidate pool (its own topNIn caps how many
// get sent upstream). Fail-open: any error returns deduped unchanged.
@@ -288,6 +289,7 @@ export async function rerankAndPin(
: deduped;
if (s1 && rerankerOpts.enabled) recordRerankReceipts(req.decide, query, reranked.slice(0, rerankerOpts.topNIn).filter((r) => s1Failure !== undefined || r.rerank_score !== undefined), s1Meta, s1Failure);
if (s1Shadow) await s1Shadow(reranked);
+ const ordered = await applyFeedbackStage(engine, reranked, { reranked: reranked !== deduped });
// Ranker wave (R1 receipt) — relational-arm rows bypass reranker DEMOTION:
// re-pinned above the reranked text rows in fused order, bounded by
@@ -297,8 +299,8 @@ export async function rerankAndPin(
// not fused there). Contract + tie policy: relational-rerank-pin.ts.
let relationalRerankPin: RelationalRerankPinDecision | undefined;
const rerankPinned = reranked !== deduped && effectiveModality !== 'image'
- ? pinRelationalRows(reranked, relationalList, { max: resolvedMode.relational_rerank_pin, fusedOrder: deduped, onPin: (d) => { relationalRerankPin = d; } })
- : reranked;
+ ? pinRelationalRows(ordered, relationalList, { max: resolvedMode.relational_rerank_pin, fusedOrder: deduped, onPin: (d) => { relationalRerankPin = d; } })
+ : ordered;
return { rerankPinned, relationalRerankPin };
}
diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.ts
index 58d7dc58d7..1a5467bbec 100644
--- a/src/core/search/read-enrichment.ts
+++ b/src/core/search/read-enrichment.ts
@@ -35,6 +35,12 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
typeFilter = `AND l.link_type = ANY($${params.length}::text[])`;
}
const mentionsFilter = opts?.includeMentions ? '' : `AND l.link_source IS DISTINCT FROM 'mentions'`;
+ const edgeExpr = direction === 'out'
+ ? `w.slug || '|' || l.link_type || '|' || p2.slug`
+ : direction === 'in'
+ ? `p2.slug || '|' || l.link_type || '|' || w.slug`
+ : `CASE WHEN l.from_page_id = w.id THEN w.slug || '|' || l.link_type || '|' || p2.slug
+ ELSE p2.slug || '|' || l.link_type || '|' || w.slug END`;
const recurStep = direction === 'out'
? 'JOIN links l ON l.from_page_id = w.id JOIN pages p2 ON p2.id = l.to_page_id'
: direction === 'in'
@@ -45,11 +51,11 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
WITH RECURSIVE walk AS (
SELECT p.id, p.slug, p.source_id, 0::int AS depth,
ARRAY[p.id] AS visited, ARRAY[p.slug] AS path,
- p.source_id AS seed_source, NULL::text AS last_link_type
+ p.source_id AS seed_source, NULL::text AS last_link_type, ARRAY[]::text[] AS edges
FROM pages p WHERE p.slug = ANY($1::text[]) AND p.deleted_at IS NULL AND ${seed} ${seedIdentities}
UNION ALL
SELECT p2.id, p2.slug, p2.source_id, w.depth + 1,
- w.visited || p2.id, w.path || p2.slug, w.seed_source, l.link_type
+ w.visited || p2.id, w.path || p2.slug, w.seed_source, l.link_type, w.edges || (${edgeExpr})
FROM walk w ${recurStep}
WHERE w.depth < $2 AND NOT (p2.id = ANY(w.visited))
AND p2.source_id = w.seed_source AND p2.deleted_at IS NULL
@@ -60,6 +66,8 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
array_agg(DISTINCT n.last_link_type) FILTER (WHERE n.last_link_type IS NOT NULL) AS via_link_types,
(array_agg(array_to_string(n.path, chr(9)) ORDER BY n.depth ASC,
array_length(n.path, 1) ASC, array_to_string(n.path, chr(9)) ASC))[1] AS path_str,
+ (array_agg(array_to_string(n.edges, chr(9)) ORDER BY n.depth ASC,
+ array_length(n.path, 1) ASC, array_to_string(n.path, chr(9)) ASC))[1] AS edges_str,
(SELECT cc.id FROM content_chunks cc WHERE cc.page_id = n.id
${requiresSafeChunks(opts) ? `AND EXISTS (SELECT 1 FROM pages cp WHERE cp.id = n.id AND ${safeChunksFilter('cp')})` : ''}
ORDER BY cc.chunk_index ASC LIMIT 1) AS canonical_chunk_id
@@ -70,6 +78,7 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
hop: Number(row.hop), edge_count: Number(row.edge_count),
via_link_types: Array.isArray(row.via_link_types) ? row.via_link_types as string[] : [],
path: row.path_str ? String(row.path_str).split('\t') : [],
+ path_edges: row.edges_str ? String(row.edges_str).split('\t') : [],
canonical_chunk_id: row.canonical_chunk_id == null ? null : Number(row.canonical_chunk_id),
}));
}
diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.ts
index 3ed2a317ec..ae03fe2043 100644
--- a/src/core/search/relational-recall.ts
+++ b/src/core/search/relational-recall.ts
@@ -202,6 +202,7 @@ async function hydrate(
relational_seed: seedSlug,
relational_hop: r.hop,
relational_path: r.path,
+ relational_path_edges: r.path_edges,
});
}
return out;
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index 44541d92c9..63fed24356 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -206,6 +206,8 @@ export interface ThinkResult {
usage?: { input_tokens: number; output_tokens: number } | null;
/** Evidence delivery meta, present only when think.return_unit is not chunk. */
evidence_delivery?: import('../search/evidence-delivery.ts').DeliveryMeta;
+ /** Gathered pages with the revision retrieved, for retrieval-feedback recording; the op layer strips it. */
+ feedback_evidence?: Array<{ source_id: string; slug: string; content_hash: string | null }>;
/** Only set when --save was true and the caller persisted a synthesis page. */
savedSlug?: string;
/** Diagnostics for `--explain` callers (CLI surface for v0.29). */
@@ -959,6 +961,7 @@ export async function runThink(
// ANDs the not-JSON/sentinel flag with a content check (catches valid-but-empty JSON).
synthesisOk: synthesisOk && response.answer.trim().length > 0,
synthesis_status: synthesisStatus,
+ feedback_evidence: gather.pages.map(pg => ({ source_id: pg.source_id ?? 'default', slug: pg.slug, content_hash: pg.content_hash ?? null })),
...(extractive ? { extractive } : {}),
usage, ...(evidenceDelivery ? { evidence_delivery: evidenceDelivery } : {}),
diagnostics: {
diff --git a/src/core/types.ts b/src/core/types.ts
index 652952789f..871ef35c23 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -918,6 +918,8 @@ export interface SearchResult {
relational_hop?: number;
/** Shortest connecting slug path seed→…→result (for "how I know this"). */
relational_path?: string[];
+ /** Stored-direction edges along `relational_path` (for retrieval feedback attribution). */
+ relational_path_edges?: string[];
/**
* Ranker wave — set when `pinRelationalRows` (relational-rerank-pin.ts)
* re-pinned this relational-arm row above the reranked text rows. Autocut
@@ -946,6 +948,12 @@ export interface SearchResult {
cosine?: number;
/** Multiplier applied by applyBacklinkBoost (1.0 = unchanged). */
backlink_boost?: number;
+ /** Use-attributed feedback multiplier on the ordering score (src/core/search/feedback-boost.ts); absent when neutral. */
+ 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. */
@@ -1513,6 +1521,8 @@ export interface RelationalFanoutRow {
edge_count: number;
via_link_types: string[];
path: string[];
+ /** Stored-direction edges ('from_slug|link_type|to_slug') along `path`, in order. */
+ path_edges: string[];
canonical_chunk_id: number | null;
}
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 1cd8c68b92..8410153331 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -298,6 +298,8 @@ const synthesize: Operation = {
// gather → typed error. An answer is NEVER fabricated from nothing
// (ENG-19). Defensive ?? 'ok' mirrors synthesisOk's back-compat posture.
const status = result.synthesis_status ?? 'ok';
+ const { recordThinkAnswer, feedbackMetaFields } = await import('./feedback/record.ts');
+ const feedbackMeta = feedbackMetaFields(await recordThinkAnswer(ctx, 'synthesize', result));
if (status !== 'ok') {
if (result.extractive) {
return {
@@ -309,6 +311,7 @@ const synthesize: Operation = {
pages_gathered: result.pagesGathered,
takes_gathered: result.takesGathered,
warnings: result.warnings,
+ ...feedbackMeta,
protocol_version: MEMORY_VERBS_VERSION,
};
}
@@ -329,6 +332,7 @@ const synthesize: Operation = {
pages_gathered: result.pagesGathered,
takes_gathered: result.takesGathered,
warnings: result.warnings,
+ ...feedbackMeta,
protocol_version: MEMORY_VERBS_VERSION,
};
},
diff --git a/test/feedback-store.test.ts b/test/feedback-store.test.ts
index 0352622da4..08923030b9 100644
--- a/test/feedback-store.test.ts
+++ b/test/feedback-store.test.ts
@@ -156,8 +156,8 @@ describe('rate_answer', () => {
describe('authority', () => {
const base = { remote: true, transport: 'http' as const, sourceId: 'default' };
test('owner CLI and stdio may teach; grants must be unrestricted write on that source', () => {
- expect(canTeachSource({ remote: false }, 'default')).toBe(true);
- expect(canTeachSource({ remote: true, transport: 'stdio' }, 'default')).toBe(true);
+ expect(canTeachSource({ remote: false, sourceId: 'default' }, 'default')).toBe(true);
+ expect(canTeachSource({ remote: true, transport: 'stdio', sourceId: 'default' }, 'default')).toBe(true);
expect(canTeachSource({ ...base, auth: { clientId: 'c', scopes: ['read'] } as never }, 'default')).toBe(false);
expect(canTeachSource({ ...base, auth: { clientId: 'c', scopes: ['write'] } as never }, 'default')).toBe(true);
expect(canTeachSource({ ...base, auth: { clientId: 'c', scopes: ['write'] } as never }, 'other')).toBe(false);