Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(feedback): gbrain feedback status/reset, purge-phase retention, guide and error codes
garrytanf143dca3f050
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 25ff219388..64e94b36dd 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -4,7 +4,7 @@<!-- Regenerate: bun run scripts/generate-tool-catalog.ts --><!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->-Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **Starter** marks membership in the ~39-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.+Every non-localOnly operation on the MCP surface: 138 tools across 24 areas. **Starter** marks membership in the ~39-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.## admin@@ -155,6 +155,12 @@ Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **S| `ontology_get` | Life Chronicle: the current resolved per-entity ontology (dimension → value) at `asof` (default now), with provenance + confidence + validity. | read | | || `ontology_propose` | Life Chronicle: record one ontology observation (entity has dimension=value), sourced + confidence-weighted + bi-temporal. | write | | |+## other++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `rate_answer` | Rate how useful an answer's retrieved evidence was, so this brain ranks better next time (zero LLM calls). | write | | |+## pages| Tool | Description | Scope | Starter | Gate |diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 13f925c9a0..328e8cc710 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -79,6 +79,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| The legacy id matches multiple readable pages. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### ambiguous_ref++<a id="ambiguous_ref"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A page reference in a rating matches pages in more than one source of that answer. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/retrieval-feedback.md#ambiguous_ref](../../docs/guides/retrieval-feedback.md#ambiguous_ref)+### ambiguous_skill<a id="ambiguous_skill"></a>@@ -87,6 +97,36 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| This name belongs to multiple authorized sources. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### answer_not_yours++<a id="answer_not_yours"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The rated answer was returned to a different client. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/retrieval-feedback.md#answer_not_yours](../../docs/guides/retrieval-feedback.md#answer_not_yours)++### answer_pending++<a id="answer_pending"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The rated answer is still being recorded; retry in a few seconds. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |++More: [docs/guides/retrieval-feedback.md#answer_pending](../../docs/guides/retrieval-feedback.md#answer_pending)++### answer_unavailable++<a id="answer_unavailable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The rated answer is not recorded: unknown, dropped, or older than the retention window. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/retrieval-feedback.md#answer_unavailable](../../docs/guides/retrieval-feedback.md#answer_unavailable)+### api_not_enabled<a id="api_not_enabled"></a>@@ -743,6 +783,26 @@ More: [docs/guides/write-refusals.md#facts_absorb_write_refused](../../docs/guid|---|---|---|---|---|---|---|| The accepted fact extraction failed and its retained payload has expired. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |+### feedback_disabled++<a id="feedback_disabled"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Retrieval feedback is off (or not learning) on this brain, so ratings are not recorded. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/retrieval-feedback.md#feedback_disabled](../../docs/guides/retrieval-feedback.md#feedback_disabled)++### feedback_not_authorized++<a id="feedback_not_authorized"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| This caller may not change the brain's shared ranking for that source. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/retrieval-feedback.md#feedback_not_authorized](../../docs/guides/retrieval-feedback.md#feedback_not_authorized)+### fetch_failed<a id="fetch_failed"></a>@@ -963,6 +1023,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| A parameter is missing, has the wrong type, or has an invalid value. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 2 | no |+### invalid_rating++<a id="invalid_rating"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A rating must be an integer from 1 to 5. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/retrieval-feedback.md#invalid_rating](../../docs/guides/retrieval-feedback.md#invalid_rating)+### invalid_request<a id="invalid_request"></a>@@ -1405,6 +1475,16 @@ More: [docs/guides/repair.md#projection-owner-resident](../../docs/guides/repairMore: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### ref_not_in_answer++<a id="ref_not_in_answer"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The rated page is not one of the pages the answer used. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/retrieval-feedback.md#ref_not_in_answer](../../docs/guides/retrieval-feedback.md#ref_not_in_answer)+### refresh_dirty<a id="refresh_dirty"></a>diff --git a/docs/guides/retrieval-feedback.md b/docs/guides/retrieval-feedback.mdnew file mode 100644index 0000000000..660834c9a6--- /dev/null+++ b/docs/guides/retrieval-feedback.md@@ -0,0 +1,135 @@+# Retrieval feedback: teach the brain which evidence helped++GBrain learns from use. Every answer from `query`, `search`, `think`,+`synthesize` and `recall` (when it searched pages) records which pages it used+and the revision of each page it read. When your agent rates an answer, the+weights of those pages move a little, and later searches rank them up or down.+It costs no LLM calls: a rating is a small database update.++**Say to your agent:** *"That last answer used the wrong page; rate it down."*+**Say to your agent:** *"The second page was the one that helped. Tell the brain."*+**Say to your agent:** *"Show me which pages the brain has learned to distrust."*++## How it works++- An answer carries an `answer_id` (`ans_…`) and `feedback: { rateable: true }`+ in its response meta. On the CLI, `query`, `search` and `think` print+ `answer: ans_… (rate with: gbrain rate ans_… 1-5)` on stderr, and `--json`+ rows carry `answer_id`.+- A rating of 1-5 maps to a target `r = (rating - 1) / 4`. Each rated page's+ weight `w` (0.5 when never rated) moves by `w + 0.1 * (r - w)`, clipped to+ [0, 1]. Edges on the relational path into a rated page move the same way.+- Ranking multiplies each result's ordering score by `1 + λ * 2 * (w - 0.5)`,+ so the effect stays within `[1 - λ, 1 + λ]` (`feedback.influence`, λ). The+ multiplier applies to the reranker's score when the reranker ran, otherwise to+ the fused score. A brain with no ratings ranks exactly as before.+- When `think` or `synthesize` produces a real answer for the brain owner+ (CLI or stdio MCP), each cited page counts as a rating of 4 at half the+ learning rate (`feedback.implicit`). Uncited pages are left alone.+- A rating applies only to the revision the answer read. If the page changed+ since, that page is skipped (`stale_revision`): a corrected page is never+ penalized for its old text. A page edited after it was rated reads at half+ its learned deviation from neutral until it is rated again.+- Only callers that may change this brain's shared ranking record answers: the+ owner's CLI and stdio MCP, and remote clients with an unrestricted write+ grant on that source. Read-only, slug-fenced or delegated callers see no+ `answer_id`.+- No query text is stored. Answers are kept for `feedback.event_retention_days`+ (30); learned weights persist in the database (database backups include them;+ markdown export does not).++## Rating++Whole answer:++```bash+gbrain query "who leads the acme-example renewal" --json+# stderr: answer: ans_01J9Z8Q6W5K3M7T2R4V8X0Y1ZC (rate with: gbrain rate ans_01J9Z8Q6W5K3M7T2R4V8X0Y1ZC 1-5)+gbrain rate ans_01J9Z8Q6W5K3M7T2R4V8X0Y1ZC 2+gbrain search "who leads the acme-example renewal" --explain # shows "+ feedback ×0.99"+```++Single pages, over MCP:++```json+{ "answer_id": "ans_01J9Z8Q6W5K3M7T2R4V8X0Y1ZC",+ "pages": [ { "ref": "default:notes/old-renewal-plan", "rating": 1 },+ { "ref": "default:people/alice-example", "rating": 5 } ] }+```++A whole-answer rating applies to the cited pages of a `think`/`synthesize`+answer (all gathered pages if nothing was cited) and to every returned page of+a search-shaped answer. Targeted ratings touch only the named pages. Each page+can be rated once per answer; an identical retry returns the same receipt.+The receipt lists each weight before and after, the ranking multiplier, and+anything skipped with its reason. A rating never edits stored facts or repairs+an answer: fix the page itself when it is wrong.++## Inspecting and resetting++```bash+gbrain feedback status # counts, weight spread, lowest-weighted pages with a next step+gbrain feedback reset --page notes/old-renewal-plan+gbrain feedback reset --source default+gbrain config set feedback.enabled false # off: no recording, no ratings, no ranking effect+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.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. |+| `feedback.alpha` | 0.1 | Learning rate; the citation signal uses half. |+| `feedback.max_ratings_per_hour` | 120 | Rating calls per client per hour. |+| `feedback.event_retention_days` | 30 | How long answers stay rateable. |+| `feedback.hint` | true | Show the one-line rating hint on answers. |++## Refusals++Every refusal carries `code`, `message` and `fix`; `gbrain errors <code>`+explains it offline.++### invalid_rating++The rating was not an integer from 1 to 5. Use 1 for wrong or useless evidence+and 5 for exactly the evidence needed.++### answer_pending++The answer was made moments ago and is still being recorded. Retry the same+call in about two seconds.++### answer_unavailable++The answer is not recorded: the id is unknown, the record was dropped, or it is+older than the retention window. Run the query again and rate the new+`answer_id`.++### answer_not_yours++The answer was returned to a different client. A connection rates only its+own answers.++### ref_not_in_answer++The page reference is not one of the pages the answer used. Use the refs the+answer listed (`source_id:slug`).++### ambiguous_ref++A bare slug matched pages in more than one source of that answer. Use the full+`source_id:slug` from the choices in the message.++### feedback_not_authorized++This connection may not change the shared ranking of the sources the answer+used. The brain owner grants an unrestricted write grant on that source; then+run the query again and rate the new answer (authority is checked when the+answer is made and again when it is rated).++### feedback_disabled++Ratings are off on this brain (`feedback.enabled=false`) or not learning+(`feedback.learn=false`). Only the brain owner turns them on, on the brain host.diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 8099a95e52..0960cfb2d1 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 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/cli.ts 3202 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); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.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.tssrc/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)@@ -13,7 +13,7 @@ src/commands/jobs.ts 660 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/commands/serve-http.ts 919 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities)src/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts)src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured)-src/core/cycle.ts 3224 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224)+src/core/cycle.ts 3227 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback)src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)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)diff --git a/src/cli.ts b/src/cli.tsindex 5285314141..6aa4e8129c 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -151,7 +151,7 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, true | (() => Promise<(engine: ne// answered before any engine or job-queue work (cathedral-6).agent: async () => (await import('./commands/agent.ts')).runAgent as never,// D3: post-connect records whose handler answers --help before the engine; run through the table.- advisor: true, anomalies: true, backfill: true, 'book-mirror': true, 'edges-backfill': true, embed: true, features: true,+ advisor: true, anomalies: true, feedback: true, backfill: true, 'book-mirror': true, 'edges-backfill': true, embed: true, features: true,founder: true, 'graph-query': true, orphans: true, salience: true, think: true,brainstorm: true, lsd: true, migrate: true, pages: true, pricing: true, 'retrieval-upgrade': true, whoknows: true,};@@ -3045,6 +3045,7 @@ TOOLSorphans [--json] [--count] Find pages with no inbound wikilinkssalience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salienceanomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)+ feedback <status|reset> retrieval feedback: learned page weights; rate answers with gbrain ratetranscripts <ingest|status|recent> v0.46: import agent session logs + chat exports (local-only)dream [--dry-run] [--json] Run the overnight maintenance cycle once (cron-friendly).See also: autopilot --install (continuous daemon).diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 243b738041..57b437877d 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -315,6 +315,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp{ name: 'reindex', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/reindex.ts') },{ name: 'salience', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/salience.ts') },{ name: 'anomalies', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/anomalies.ts') },+ { name: 'feedback', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/feedback.ts') },{ name: 'status', phase: 'post-connect', thinClient: 'none', help: () => import('./help/status.ts'), load: () => import('./commands/status.ts') },{ name: 'advisor', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/advisor.ts') },{ name: 'conversation-parser', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/conversation-parser.ts') },diff --git a/src/cli/commands/feedback.ts b/src/cli/commands/feedback.tsnew file mode 100644index 0000000000..fd2d930c09--- /dev/null+++ b/src/cli/commands/feedback.ts@@ -0,0 +1,10 @@+/**+ * `gbrain feedback`: post-connect dispatch; the record lives in+ * src/cli/command-table.ts.+ */+import type { BrainEngine } from '../../core/engine.ts';++export async function run(engine: BrainEngine, args: string[]): Promise<void> {+ const { runFeedback } = await import('../../commands/feedback.ts');+ await runFeedback(engine, args);+}diff --git a/src/commands/feedback.ts b/src/commands/feedback.tsnew file mode 100644index 0000000000..4985509a51--- /dev/null+++ b/src/commands/feedback.ts@@ -0,0 +1,87 @@+/**+ * gbrain feedback — inspect and reset use-attributed retrieval feedback.+ *+ * Usage:+ * gbrain feedback status [--json]+ * gbrain feedback reset [--source ID] [--page SLUG]+ *+ * Zero LLM calls. Ratings come from `gbrain rate` / the rate_answer op.+ */+import type { BrainEngine } from '../core/engine.ts';+import { loadFeedbackSettings } from '../core/feedback/settings.ts';+import { droppedFeedbackEvents } from '../core/feedback/record.ts';+import { feedbackStatus, resetRetrievalWeights } from '../core/feedback/store.ts';+import { feedbackStageErrors } from '../core/search/feedback-boost.ts';++const HELP = `Usage: gbrain feedback <status|reset> [options]++Inspect and reset the brain's use-attributed retrieval feedback (ratings from+\`gbrain rate\` / rate_answer and think/synthesize citations).++ status [--json] counts, weight spread, lowest-weighted pages with a next step+ reset [--source ID] [--page SLUG] return learned weights to neutral (all, one source, or one page)++Guide: docs/guides/retrieval-feedback.md+`;++function flag(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ return i >= 0 ? args[i + 1] : undefined;+}++export async function runFeedback(engine: BrainEngine, args: string[]): Promise<void> {+ const sub = args[0];+ if (!sub || sub === '--help' || sub === '-h' || args.includes('--help')) {+ process.stdout.write(HELP);+ return;+ }+ if (sub === 'reset') {+ const sourceId = flag(args, '--source');+ const slug = flag(args, '--page');+ const removed = await resetRetrievalWeights(engine, { sourceId, slug });+ const scope = slug ? `page ${slug}` : sourceId ? `source ${sourceId}` : 'the whole brain';+ process.stdout.write(`Reset ${removed} learned weight${removed === 1 ? '' : 's'} to neutral for ${scope}.\n`);+ return;+ }+ if (sub !== 'status') {+ process.stderr.write(`Unknown subcommand: ${sub}\n\n${HELP}`);+ process.exitCode = 2;+ return;+ }+ 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(),+ };+ if (args.includes('--json')) {+ process.stdout.write(JSON.stringify(report, null, 2) + '\n');+ return;+ }+ const lines = [+ `Retrieval feedback: ${settings.enabled ? 'on' : 'off'}${settings.enabled && !settings.learn ? ' (not learning)' : ''}, influence λ=${settings.influence}, implicit=${settings.implicit ? 'on' : 'off'}`,+ `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.`);+ }+ if (status.highest.length > 0) {+ lines.push('', 'Most trusted pages:');+ for (const h of status.highest) lines.push(` ${h.weight.toFixed(3)} ${h.source_id}:${h.slug}`);+ }+ if (status.lowest.length > 0) {+ lines.push('', 'Least trusted pages (open each and check whether it is wrong, stale or simply off-topic for those questions):');+ for (const l of status.lowest) {+ lines.push(` ${l.weight.toFixed(3)} ${l.source_id}:${l.slug} rated low on ${l.low_ratings} answer${l.low_ratings === 1 ? '' : 's'}`);+ }+ }+ if (status.events === 0) {+ lines.push('', 'No answers recorded yet. Answers from query/search/think/synthesize/recall carry an answer_id; rate one with `gbrain rate <answer_id> 1-5`.');+ }+ process.stdout.write(lines.join('\n') + '\n');+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 742267af39..7450e37753 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -60,6 +60,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--source'],'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--expect', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],+ 'feedback': ['--brain', '--help', '--json', '--page', '--source'],'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--wait', '--yes'],'forget': ['--brain', '--help', '--json', '--reason', '--request-id', '--source'],'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],@@ -171,6 +172,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {'extract-conversation-facts': ['--brain'],'facts': ['--brain', '--source'],'features': ['--brain'],+ 'feedback': ['--brain'],'files': ['--brain', '--source'],'forget': ['--brain'],'founder': ['--brain'],diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 4ae8dad37a..7403a58c55 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1745,6 +1745,8 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phas// System One: decision receipts past decide.receipts.retention_days (reported only when rows were pruned).let purgedDecisionReceipts = 0;try { purgedDecisionReceipts = await (await import('./ai/decide/store.ts')).pruneReceiptsForCycle(engine); } catch { /* pre-v179 brain */ }+ let purgedFeedback = { events: 0, weights: 0 };+ try { purgedFeedback = await (await import('./feedback/store.ts')).pruneRetrievalFeedback(engine, (await (await import('./feedback/settings.ts')).loadFeedbackSettings(engine)).eventRetentionDays); } catch { /* pre-v201 brain */ }return {phase: 'purge',status: purgedPages.error ? 'fail' : 'ok', error: purgedPages.error,@@ -1770,6 +1772,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise<Phaspurged_batch_retry_audit_files_count: purgedBatchRetryAuditFiles,purged_volunteer_events_count: purgedVolunteerEvents,...(purgedDecisionReceipts > 0 ? { purged_decision_receipts_count: purgedDecisionReceipts } : {}),+ ...(purgedFeedback.events + purgedFeedback.weights > 0 ? { purged_retrieval_feedback_events_count: purgedFeedback.events, purged_retrieval_weights_count: purgedFeedback.weights } : {}),},};} catch (e) {diff --git a/src/core/feedback/record.ts b/src/core/feedback/record.tsindex a4888f1da9..e94d3c6677 100644--- a/src/core/feedback/record.ts+++ b/src/core/feedback/record.ts@@ -225,10 +225,10 @@ export function _resetFeedbackRecordingForTests(): void {answersSinceHint = new Map();}-/** Additive response-meta fields for an answer (none when feedback is off). */+/** Additive response-meta fields: present only on a rateable answer, so readers see no change. */export function feedbackMetaFields(meta: AnswerFeedbackMeta | null): Record<string, unknown> {- if (!meta) return {};- return { ...(meta.answer_id ? { answer_id: meta.answer_id } : {}), feedback: meta.feedback };+ if (!meta?.answer_id) return {};+ return { answer_id: meta.answer_id, feedback: meta.feedback };}/** Typed edges on the representative relational path of each returned relational-arm row. */diff --git a/src/core/search/feedback-boost.ts b/src/core/search/feedback-boost.tsindex 9e90a96c53..93519157fe 100644--- a/src/core/search/feedback-boost.ts+++ b/src/core/search/feedback-boost.ts@@ -22,6 +22,13 @@ export interface FeedbackStageMeta {errored: boolean;}+let stageErrors = 0;++/** Fail-open errors of the stage in this process (shown by `gbrain feedback status`). */+export function feedbackStageErrors(): number {+ return stageErrors;+}+export function feedbackMultiplier(weight: number, influence: number): number {return 1 + influence * 2 * (weight - NEUTRAL_WEIGHT);}@@ -92,6 +99,7 @@ export async function applyFeedbackStage(scored.sort((a, b) => (b.key! - a.key!) || (a.index - b.index));return [...scored, ...unscored].map(k => k.r);} catch {+ stageErrors++;meta = { applied: false, boosted: 0, errored: true };return results;} finally {