Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(entity): name variants, text mentions, identifier probe, recall --entity (GBRA-155)
garrytanc65fc4348814
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 1da2fb613d..43b9f4c481 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/main.ts 3016 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +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); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +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); +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); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +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); +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); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +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); +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); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +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); +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); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row+src/cli/main.ts 2986 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +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); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +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); +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); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +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); +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); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +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); +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); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +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); +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); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; -30 GBRA-155: the entity card renderer moved to cli/entity-format.tssrc/commands/autopilot.ts 1662 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); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)src/commands/doctor.ts 688 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +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 2304 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); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/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 refreshsrc/commands/hook.ts 1932 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; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 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); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 1989 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key)+src/core/config.ts 1990 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +1 GBRA-155 #7160: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts)src/core/persistence/sync-run.ts 1681 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts)src/core/bootstrap/harness.ts 2592 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; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)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 optiondiff --git a/src/cli/entity-format.ts b/src/cli/entity-format.tsnew file mode 100644index 0000000000..ee5dae451b--- /dev/null+++ b/src/cli/entity-format.ts@@ -0,0 +1,54 @@+/**+ * Human rendering of the `entity` verb (`gbrain entity <name>`); `--json`+ * returns the raw envelope instead. Kept out of cli/main.ts (module-size+ * ratchet), like remember-format.ts.+ */++/* eslint-disable @typescript-eslint/no-explicit-any -- renders the verb's JSON envelope */+export function formatEntityResult(r: any): string {+ if (!r.found) {+ const coverage = r.coverage && r.coverage.state !== 'complete' ? ` Mention coverage: ${r.coverage.state}, ${r.coverage.pending_pages} page(s) pending.` : '';+ const tm = r.text_mentions;+ const lines = tm?.total+ ? [`No entity page. The name appears in the text of ${tm.total}${tm.capped ? '+' : ''} page(s) (unlinked text matches). (${r.latency_ms}ms)${coverage}`,+ ...tm.pages.map((p: any) => ` ${p.date ?? ' '} ${p.slug} — ${p.title}`)]+ : [`No entity found. (${r.latency_ms}ms)${coverage}${tm?.unread ? ` Text matches not checked (${tm.unread}); search the name with gbrain search.` : ''}`];+ if (Array.isArray(r.suggestions) && r.suggestions.length) {+ lines.push(r.ambiguous ? 'Several entities match this name; pick one:' : 'Did you mean:');+ for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title} [${s.create_safety}]`);+ }+ return lines.join('\n') + '\n';+ }+ const c = r.card;+ const lines = [`${c.entity.title} (${c.entity.slug})${c.entity.type ? ` [${c.entity.type}]` : ''} (${r.latency_ms}ms)`];+ if (c.match) lines.push(` matched "${c.match.via}" as a name variant (${c.match.kind}); check the page before relying on it`);+ if (c.summary) lines.push(` ${c.summary}`);+ if (c.aka?.length) lines.push(` aka: ${c.aka.join(', ')}`);+ const lt = c.last_touched || {};+ const touched = lt.updated_at || lt.last_retrieved_at || lt.last_timeline_date;+ if (touched) lines.push(` last touched: ${String(touched).slice(0, 10)}`);+ if (c.open_threads?.length) {+ lines.push(' open threads:');+ for (const t of c.open_threads) lines.push(` [${t.kind}] ${t.text}${t.date ? ` (${String(t.date).slice(0, 10)})` : ''}`);+ }+ if (c.edges?.length) {+ lines.push(' edges:');+ for (const e of c.edges) lines.push(` ${e.direction === 'out' ? '→' : '←'} ${e.type} ${e.slug}`);+ }+ lines.push(` backlinks: ${c.backlink_count} | active facts: ${c.active_fact_count}`);+ if (c.referenced_by_count) lines.push(` referenced by ${c.referenced_by_count} page(s):`, ...c.referenced_by.map((g: any) => ` ${g.canonical_type} (${g.total}): ${g.rows.map((x: any) => x.slug).join(', ')}${g.next ? ', ...' : ''}`));+ if (c.coverage && c.coverage.state !== 'complete') lines.push(` mention coverage: ${c.coverage.state}, ${c.coverage.pending_pages} page(s) pending`);+ if (c.text_mentions?.total) {+ lines.push(` the name appears in the text of ${c.text_mentions.total}${c.text_mentions.capped ? '+' : ''} other page(s) (unlinked text matches, newest first):`);+ for (const p of c.text_mentions.pages) lines.push(` ${p.date ?? ' '} ${p.slug} — ${p.title}`);+ }+ if (c.possible_duplicates?.length) {+ lines.push(' possible duplicate pages (title prefix; review, never merged automatically):');+ for (const d of c.possible_duplicates) lines.push(` ${d.slug} — ${d.title}`);+ }+ if (Array.isArray(r.suggestions) && r.suggestions.length) {+ lines.push(' other matches:');+ for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title}`);+ }+ return lines.join('\n') + '\n';+}diff --git a/src/cli/main.ts b/src/cli/main.tsindex 4e5c06ecab..621d95b679 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -76,6 +76,7 @@ import {type CliDispatchContext,} from './command-table.ts';import { formatRememberResult } from './remember-format.ts';+import { formatEntityResult } from './entity-format.ts';import { applyCliOpNotices, captureCapacityNotices, captureOpNotice } from './op-notices.ts';// db-availability loop: best-effort brain-id for the GBRAIN_DB_ACCESS marker,@@ -1781,38 +1782,7 @@ export function formatResult(}case 'entity': {if (process.argv.includes('--json')) break;- const r = result as any;- if (!r.found) {- const lines = [`No entity found. (${r.latency_ms}ms)${r.coverage && r.coverage.state !== 'complete' ? ` Mention coverage: ${r.coverage.state}, ${r.coverage.pending_pages} page(s) pending.` : ''}`];- if (Array.isArray(r.suggestions) && r.suggestions.length) {- lines.push('Did you mean:');- for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title} [${s.create_safety}]`);- }- return lines.join('\n') + '\n';- }- const c = r.card;- const lines = [`${c.entity.title} (${c.entity.slug})${c.entity.type ? ` [${c.entity.type}]` : ''} (${r.latency_ms}ms)`];- if (c.summary) lines.push(` ${c.summary}`);- if (c.aka?.length) lines.push(` aka: ${c.aka.join(', ')}`);- const lt = c.last_touched || {};- const touched = lt.updated_at || lt.last_retrieved_at || lt.last_timeline_date;- if (touched) lines.push(` last touched: ${String(touched).slice(0, 10)}`);- if (c.open_threads?.length) {- lines.push(' open threads:');- for (const t of c.open_threads) lines.push(` [${t.kind}] ${t.text}${t.date ? ` (${String(t.date).slice(0, 10)})` : ''}`);- }- if (c.edges?.length) {- lines.push(' edges:');- for (const e of c.edges) lines.push(` ${e.direction === 'out' ? '→' : '←'} ${e.type} ${e.slug}`);- }- lines.push(` backlinks: ${c.backlink_count} | active facts: ${c.active_fact_count}`);- if (c.referenced_by_count) lines.push(` referenced by ${c.referenced_by_count} page(s):`, ...c.referenced_by.map((g: any) => ` ${g.canonical_type} (${g.total}): ${g.rows.map((x: any) => x.slug).join(', ')}${g.next ? ', ...' : ''}`));- if (c.coverage && c.coverage.state !== 'complete') lines.push(` mention coverage: ${c.coverage.state}, ${c.coverage.pending_pages} page(s) pending`);- if (Array.isArray(r.suggestions) && r.suggestions.length) {- lines.push(' other matches:');- for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title}`);- }- return lines.join('\n') + '\n';+ return formatEntityResult(result);}case 'synthesize': {if (process.argv.includes('--json')) break;diff --git a/src/commands/recall.ts b/src/commands/recall.tsindex 58c0e4e9fb..f9b0a3514c 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -118,6 +118,7 @@ function parseFlags(args: string[]): ParsedFlags {watchSeconds: null,};let positional = '';+ let entityFlag: string | null = null;let rawBudget: string | undefined;for (let i = 0; i < args.length; i++) {const a = args[i];@@ -148,6 +149,19 @@ function parseFlags(args: string[]): ParsedFlags {i++;continue;}+ // #7166: --entity matches the recall op's `entity` parameter (same as the bare positional).+ if (a === '--entity' || a.startsWith('--entity=')) {+ const raw = a === '--entity' ? args[i + 1] : a.slice('--entity='.length);+ if (raw === undefined || raw.trim() === '' || (a === '--entity' && raw.startsWith('--'))) {+ throw usageError('--entity requires an entity name or slug.', 'Pass it after the flag, e.g. --entity people/alice-example.', {+ why: 'An empty entity must not silently widen recall to every fact.',+ fix: { argv: ['gbrain', 'recall', '--help'], consent: [], actor: 'agent', why: 'Shows the recall selectors.', requires_exclusive: false },+ });+ }+ entityFlag = raw;+ if (a === '--entity') i++;+ continue;+ }if (a === '--grep') { out.grep = (args[++i] ?? '').toLowerCase(); continue; }if (a === '--today') { out.today = true; continue; }if (a === '--supersessions') { out.supersessions = true; continue; }@@ -198,7 +212,15 @@ function parseFlags(args: string[]): ParsedFlags {if (a.startsWith('--')) continue; // skip unknown flags silentlyif (!positional) positional = a;}- if (positional) out.entity = positional;+ if (entityFlag !== null && positional && positional !== entityFlag) {+ throw usageError(`--entity "${entityFlag.slice(0, 60)}" and the positional "${positional.slice(0, 60)}" name different entities.`,+ 'Pass the entity once: either --entity <name> or the bare positional.', {+ why: 'recall reads one entity per call; two different names would silently drop one.',+ fix: { argv: ['gbrain', 'recall', '--entity', entityFlag], consent: [], actor: 'agent', why: 'Recall the --entity value only.', requires_exclusive: false },+ });+ }+ if (entityFlag !== null) out.entity = entityFlag;+ else if (positional) out.entity = positional;out.budgetTokens = (out.budgetPolicy === 'query_first' && out.query?.trim()? Number(rawBudget): parseInt(rawBudget ?? '', 10)) || null;@@ -284,7 +306,7 @@ const RECALL_HELP = `Usage: gbrain recall [<entity>] [options]Find saved facts (MEMORY_VERBS v1). A question goes in --question; the barepositional is an entity name, then a literal piece of fact text.- gbrain recall <entity> facts about one entity (person, company, "user")+ gbrain recall <entity> facts about one entity (person, company, "user"); same as --entity <entity>gbrain recall --question "<q>" facts ranked by relevance to a natural-language questiongbrain recall --query "<q>" facts plus matching pagesgbrain recall --grep <text> facts whose text contains <text>diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex d3a09fecea..8b12ffaf7b 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -101,7 +101,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],- 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],+ 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],diff --git a/src/core/config.ts b/src/core/config.tsindex 8c86e9d9a7..f0df485314 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1642,6 +1642,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['mcp.strict_params','mcp.result_rows', // C1 row shape, read dual-plane by src/mcp/result-rows.ts'mcp.allow_session_widen', // stdio request_tools session widening (default on), read dual-plane by src/mcp/surface.ts+ 'entity.name_variants', // #7160 entity card name-variant arm and possible_duplicates (default on; verbs/entity-variants.ts)'entity.names_references', 'entity.record_types', 'entity.row_page_status', // names-row referenced_by_count + card `next` (default on); canonical page types listed as `records` (default empty); F3 page_status on context_pack/get_backlinks rows (default on); src/core/entity-references-config.ts'mcp.instructions_governing_rule', // instruction 7: in_effect (default: the record in effect on the date asked about governs) | newest (the earlier recency sentence); src/mcp/instructions.ts// Skill-nag suppression (#2180): brain-resident pack install nag off-switch.diff --git a/src/core/entities/name-variants.ts b/src/core/entities/name-variants.tsnew file mode 100644index 0000000000..181d0832ee--- /dev/null+++ b/src/core/entities/name-variants.ts@@ -0,0 +1,186 @@+/**+ * #7160: person and organization name variants for entity lookup (pure).+ *+ * The entity card's precision arms (alias, exact title, exact slug, slug+ * suffix) only match a name as written. Names reach agents in other shapes:+ * a nickname or diminutive ("Allie Example"), an initial ("A. Example"), the+ * surname alone, a one-letter typo, reversed order ("Example, Alice") or a+ * title in front ("Mayor Example", "Dr. Alice Example"). This module decides+ * whether a query and a candidate page name are the same name under one of+ * those shapes, and how strong that match is. It never decides alone: the+ * resolver (verbs/entity-card.ts) accepts a variant only when exactly one+ * entity page holds the strongest match, so a near-name never resolves to a+ * different person.+ *+ * Leaf module: text primitives only, no engine imports.+ */++import { foldNonDecomposingLatin } from '../latin-fold.ts';++/** Variant kinds, strongest first (NAME_MATCH_RANK). */+export type NameMatchKind = 'normalized' | 'honorific' | 'reordered' | 'diminutive' | 'initial' | 'typo' | 'surname';++export const NAME_MATCH_RANK: Readonly<Record<NameMatchKind, number>> = {+ normalized: 0, honorific: 1, reordered: 2, diminutive: 3, initial: 4, typo: 5, surname: 6,+};++/** Kinds that name a person by part of the name only: they also require a single matching page overall. */+export const WEAK_NAME_MATCHES: ReadonlySet<NameMatchKind> = new Set(['typo', 'surname']);++/**+ * Leading honorifics and roles that sit in front of a name in titles, slugs+ * and prose ("mayor-example", "Dr. Alice Example", "CEO Alice Example").+ * Words that are also common given names or surnames (king, judge, chief,+ * general, saint, father, chair) are left out: stripping them would turn a+ * name into a different one ("Judge Example" stays a name).+ */+export const NAME_TITLE_TOKENS: ReadonlySet<string> = new Set([+ 'mr', 'mrs', 'ms', 'mx', 'miss', 'dr', 'doctor', 'prof', 'professor', 'sir', 'dame', 'lord', 'lady',+ 'rev', 'reverend', 'hon', 'honorable', 'mayor', 'senator', 'sen', 'rep', 'representative',+ 'congressman', 'congresswoman', 'gov', 'governor', 'president', 'pres', 'vp',+ 'chancellor', 'minister', 'secretary', 'ambassador', 'councilmember', 'councilman', 'councilwoman',+ 'magistrate',+ 'commissioner', 'sheriff', 'ceo', 'cfo', 'cto', 'coo', 'cmo', 'cpo', 'founder', 'cofounder',+ 'chairman', 'chairwoman', 'col', 'colonel', 'capt', 'captain', 'lt', 'sgt', 'admiral',+]);++const NAME_SUFFIX_TOKENS: ReadonlySet<string> = new Set(['jr', 'sr', 'ii', 'iii', 'iv', 'phd', 'md', 'esq', 'mba', 'cpa']);++/**+ * Common English given-name groups: names in one group are the same given+ * name (formal form, short forms, diminutives). A name may sit in several+ * groups ("alex"). Deliberately conservative: a pair that often names two+ * different people is left out.+ */+const NICKNAME_GROUPS: readonly string[] = [+ 'abigail abby abbie gail', 'alexander alex alec al sasha xander', 'alexandra alex alexa lexi sandra sasha allie',+ 'alice allie ally', 'alison allison ali allie', 'allan alan al', 'albert al bert bertie', 'alfred alf alfie fred',+ 'amanda mandy manda', 'andrew andy drew', 'angela angie', 'anthony tony ant', 'antonio tony', 'arthur art artie',+ 'barbara barb barbie babs', 'benjamin ben benji benny', 'bernard bernie', 'beverly bev', 'bradley brad',+ 'calvin cal', 'cameron cam', 'catherine cathy cat kate katie', 'katherine kathy kate katie kat', 'kathryn kathy kate katie',+ 'charles charlie chuck chas', 'charlotte charlie lottie', 'christina chris tina', 'christine chris tina chrissy',+ 'christopher chris kit topher', 'cynthia cindy', 'daniel dan danny', 'danielle dani', 'david dave davey',+ 'deborah debbie deb debra', 'dennis denny', 'donald don donnie', 'dorothy dot dottie', 'douglas doug',+ 'edward ed eddie ted ned', 'edwin ed eddie', 'eleanor ellie nell nora', 'elizabeth liz lizzie beth betty eliza libby',+ 'emily em emmy', 'eugene gene', 'frances fran franny', 'francis frank fran', 'franklin frank', 'frederick fred freddie rick',+ 'gabriel gabe', 'gabrielle gabby', 'gerald gerry jerry', 'gregory greg', 'harold hal harry', 'harrison harry',+ 'henry hank harry hal', 'herbert herb', 'isabel izzy bella', 'isabella izzy bella', 'jacob jake', 'james jim jimmy jamie',+ 'jane janie', 'janet jan', 'jeffrey jeff', 'jennifer jen jenny', 'jessica jess jessie', 'johnathan jon john',+ 'jonathan jon jonny', 'john johnny jack', 'joseph joe joey', 'josephine jo josie', 'joshua josh', 'judith judy',+ 'kenneth ken kenny', 'kimberly kim', 'lawrence larry', 'leonard leo len lenny', 'louis lou', 'louise lou',+ 'madeline maddie maddy', 'margaret maggie meg peggy marge', 'matthew matt', 'melissa mel missy', 'michael mike mikey mick',+ 'michelle shelly', 'nathan nate', 'nathaniel nate nat', 'nicholas nick nicky', 'nicole nikki', 'oliver ollie',+ 'pamela pam', 'patricia pat patty trish', 'patrick pat paddy', 'peter pete', 'philip phil', 'phillip phil',+ 'rebecca becky becca', 'richard rick ricky dick rich', 'robert rob bob bobby robbie bert', 'roberta bobbie',+ 'ronald ron ronnie', 'rosemary rose rosie', 'samantha sam sammy', 'samuel sam sammy', 'sandra sandy',+ 'sarah sara sally', 'stephanie steph', 'stephen steve stevie', 'steven steve stevie', 'stuart stu', 'susan sue susie',+ 'suzanne sue suzy', 'theodore ted teddy theo', 'thomas tom tommy', 'timothy tim timmy', 'valerie val',+ 'victoria vicky tori', 'vincent vince vinny', 'walter walt wally', 'william will bill billy liam willy',+ 'zachary zach zack',+];++const NICKNAMES: ReadonlyMap<string, ReadonlySet<number>> = (() => {+ const map = new Map<string, Set<number>>();+ NICKNAME_GROUPS.forEach((group, i) => {+ for (const name of group.split(' ')) {+ if (!map.has(name)) map.set(name, new Set());+ map.get(name)!.add(i);+ }+ });+ return map;+})();++/** Lowercase, accent-free name words (punctuation and separators dropped). */+export function nameWords(text: string): string[] {+ const folded = foldNonDecomposingLatin((text ?? '').normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase());+ return folded.split(/[^\p{L}\p{N}]+/u).filter(Boolean);+}++export interface PersonName {+ /** The name words without leading titles or trailing suffixes. */+ core: string[];+ /** The title words removed from the front ("mayor", "dr"). */+ titles: string[];+}++/** Split a name into its core words and the titles in front of it; a name that is only titles keeps them as its core. */+export function parsePersonName(text: string): PersonName {+ const words = nameWords(text);+ let start = 0;+ while (start < words.length - 1 && NAME_TITLE_TOKENS.has(words[start]!)) start++;+ let end = words.length;+ while (end - 1 > start && NAME_SUFFIX_TOKENS.has(words[end - 1]!)) end--;+ return { core: words.slice(start, end), titles: words.slice(0, start) };+}++/** True when the page name starts with a title word ("Mayor Example", `people/dr-alice-example`). */+export function hasLeadingTitle(text: string): boolean {+ return parsePersonName(text).titles.length > 0;+}++function sameGivenName(a: string, b: string): boolean {+ if (a === b) return true;+ const ga = NICKNAMES.get(a);+ const gb = NICKNAMES.get(b);+ if (ga && gb) for (const g of ga) if (gb.has(g)) return true;+ return false;+}++/** Optimal-string-alignment distance, capped: returns cap + 1 once the distance exceeds cap. */+export function editDistance(a: string, b: string, cap = 1): number {+ if (Math.abs(a.length - b.length) > cap) return cap + 1;+ const d: number[][] = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);+ for (let j = 1; j <= b.length; j++) d[0]![j] = j;+ for (let i = 1; i <= a.length; i++) {+ let rowMin = Infinity;+ for (let j = 1; j <= b.length; j++) {+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;+ let v = Math.min(d[i - 1]![j]! + 1, d[i]![j - 1]! + 1, d[i - 1]![j - 1]! + cost);+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) v = Math.min(v, d[i - 2]![j - 2]! + 1);+ d[i]![j] = v;+ rowMin = Math.min(rowMin, v);+ }+ if (rowMin > cap) return cap + 1;+ }+ return d[a.length]![b.length]!;+}++const sameWords = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((w, i) => w === b[i]);+const sortedKey = (a: readonly string[]) => [...a].sort().join(' ');++/**+ * The strongest variant shape under which `query` names `candidate` (a page+ * title or slug basename), or null. Multi-word shapes need a candidate of at+ * least two words; `surname` needs a one-word query of three or more+ * letters equal to the candidate's last word.+ */+export function matchNameVariant(query: string, candidate: string): NameMatchKind | null {+ const q = parsePersonName(query);+ const c = parsePersonName(candidate);+ if (!q.core.length || !c.core.length) return null;+ if (sameWords(q.core, c.core)) return q.titles.length || c.titles.length ? 'honorific' : 'normalized';+ if (c.core.length < 2) return null;+ if (q.core.length === c.core.length && sortedKey(q.core) === sortedKey(c.core)) return 'reordered';+ if (q.core.length === 1) return q.core[0]!.length >= 3 && q.core[0] === c.core[c.core.length - 1] ? 'surname' : null;+ if (q.core.length !== c.core.length) return null;+ const last = q.core.length - 1;+ if (q.core[last] === c.core[last]) {+ const given = q.core.slice(0, last);+ const cGiven = c.core.slice(0, last);+ if (given.every((w, i) => w === cGiven[i] || sameGivenName(w, cGiven[i]!))) return 'diminutive';+ if (given.every((w, i) => w === cGiven[i] || sameGivenName(w, cGiven[i]!) || (w.length === 1 && cGiven[i]!.startsWith(w)))) return 'initial';+ }+ // One edit in the surname only: a given name one letter off (Jon, Joe) is usually another person.+ const qLast = q.core[last]!;+ const cLast = c.core[last]!;+ if (qLast.length >= 5 && q.core.slice(0, last).every((w, i) => w === c.core[i] || sameGivenName(w, c.core[i]!)) && editDistance(qLast, cLast) === 1) return 'typo';+ return null;+}++/**+ * The words a candidate query should probe titles with: the query's core+ * name words of three or more letters (initials and titles carry no signal).+ */+export function probeWords(query: string): string[] {+ return [...new Set(parsePersonName(query).core.filter(w => w.length >= 3))];+}diff --git a/src/core/search/exact-lookup.ts b/src/core/search/exact-lookup.tsindex 98544fbce2..d29575046c 100644--- a/src/core/search/exact-lookup.ts+++ b/src/core/search/exact-lookup.ts@@ -11,6 +11,12 @@* title probe — an exact (normalized) full-title equality match, read off* the ALREADY-FETCHED page-grain title arm (zero extra* queries on the hot path).+ * identifier — #7163: a query that is one phone number, email, URL, long+ * digit run, hex id or code reads candidate chunks through+ * the full-text index in every common written form and keeps+ * the pages whose chunk text really contains it+ * (search/identifier-query.ts). One keyword read, only for+ * identifier-shaped queries.** Supersession-filtered: a page that a `supersedes` link marks stale is* NEVER top-injected by this tier (the organic pipeline still surfaces it,@@ -22,7 +28,7 @@* already in the organic set are promoted to rank-1; absent hits inject at* top-of-organic + epsilon (the alias-hop injection shape, page_id* included). Injected/promoted rows carry:- * - exact_lookup: 'slug' | 'title' (autocut preserve predicate + telemetry)+ * - exact_lookup: 'slug' | 'title' | 'identifier' (autocut preserve predicate + telemetry)* - slug hits: alias_hit=true (evidence → alias_hit → 'exists')* - title hits: title_match_boost (evidence → exact_title_match → 'exists')* so the T4 evidence/create_safety contract reads them as identity matches@@ -39,6 +45,10 @@ import { normalizeAlias } from './alias-normalize.ts';import { isLookupShapedQuery } from './query-intent.ts';import { applySupersedeDownrank } from './hybrid.ts';import { isExcludedIdentity } from './alias-hop.ts';+import { identifierKeywordQuery, parseIdentifier, textContainsIdentifier } from './identifier-query.ts';++/** Keyword rows read for an identifier query before the containment check. */+export const IDENTIFIER_POOL = 30;/** Cap on tier injections per query (mirrors the alias hop's discipline). */export const MAX_EXACT_LOOKUP_INJECT = 3;@@ -157,6 +167,29 @@ export async function structuralExactLookup(}}+ // #7163 identifier probe — a phone number, email, URL, long digit run, hex id+ // or code: candidate chunks through the full-text index in every common+ // written form, kept only when the chunk text really contains it.+ const ident = parseIdentifier(q);+ if (ident) {+ try {+ const rows = await engine.searchKeyword(identifierKeywordQuery(ident), {+ limit: IDENTIFIER_POOL,+ sourceId: opts.sourceId,+ sourceIds: opts.sourceIds,+ excludePrivate: opts.excludePrivate,+ requireSafeChunks: opts.requireSafeChunks,+ ...(opts.type ? { type: opts.type as SearchResult['type'] } : {}),+ ...(opts.types?.length ? { types: opts.types as SearchResult['type'][] } : {}),+ });+ for (const r of rows) {+ if (!r.keyword_relaxed && textContainsIdentifier(r.chunk_text, ident)) push({ ...r, keyword_hit: true, exact_lookup: 'identifier' });+ }+ } catch {+ // fail-open: identifier probe error → no tier hit+ }+ }+if (hits.length === 0) return [];// Supersession filter — a stale (superseded) page never wins the identitydiff --git a/src/core/search/identifier-query.ts b/src/core/search/identifier-query.tsnew file mode 100644index 0000000000..8ad948dcfd--- /dev/null+++ b/src/core/search/identifier-query.ts@@ -0,0 +1,98 @@+/**+ * #7163: identifier-shaped queries (phone numbers, emails, URLs, long digit+ * runs, hex ids, codes like INV-2026-00417). Tokenization splits them, a+ * vector of digits is noise, and the reranker cannot recover a page that+ * never entered the pool, so search runs an exact probe for them before+ * ranking (search/exact-lookup.ts). Pure: detection, the keyword query that+ * finds candidate chunks in every common written format, and the check that+ * a chunk really contains the identifier.+ */++export type IdentifierKind = 'email' | 'url' | 'phone' | 'digits' | 'hex' | 'code';++export interface Identifier {+ kind: IdentifierKind;+ /** The identifier as asked, quotes removed. */+ raw: string;+ /** What a chunk must contain: lowercase text, or the digits of a phone or digit run. */+ needle: string;+}++const EMAIL_RE = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i;+const URL_RE = /^(?:https?:\/\/)?(?:www\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,}(?:[/?#]\S*)?$/i;+const PHONE_RE = /^\+?[\d\s().-]{7,22}$/;+const HEX_RE = /^(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{8,64}$/i;+const CODE_RE = /^(?=.*\d)[a-z0-9]{1,12}(?:[-_/][a-z0-9]{1,12}){1,5}$/i;++const digitsOf = (s: string) => s.replace(/\D/g, '');++/** The identifier a whole query names, or null for any other query. */+export function parseIdentifier(query: string): Identifier | null {+ const raw = query.trim().replace(/^["'`]+|["'`]+$/g, '').trim();+ if (!raw || raw.length > 200 || /^\d{4}-\d{2}-\d{2}$/.test(raw)) return null;+ if (EMAIL_RE.test(raw)) return { kind: 'email', raw, needle: raw.toLowerCase() };+ if (/\s/.test(raw) && !PHONE_RE.test(raw)) return null;+ if (PHONE_RE.test(raw) && /[\s().+-]/.test(raw)) {+ const d = digitsOf(raw);+ if (d.length >= 7 && d.length <= 15) return { kind: 'phone', raw, needle: d };+ }+ if (/^\d{6,}$/.test(raw)) return { kind: 'digits', raw, needle: raw };+ if (HEX_RE.test(raw)) return { kind: 'hex', raw, needle: raw.toLowerCase() };+ if (/[./]/.test(raw) && URL_RE.test(raw) && /[a-z]/i.test(raw)) {+ const needle = raw.toLowerCase().replace(/^https?:\/\//, '').replace(/^www\./, '').replace(/\/$/, '');+ return { kind: 'url', raw, needle };+ }+ if (CODE_RE.test(raw)) return { kind: 'code', raw, needle: raw.toLowerCase() };+ return null;+}++/** National significant number for a phone: the last 10 digits of a longer number, else all of them. */+const nationalDigits = (d: string) => (d.length > 10 ? d.slice(-10) : d);++/**+ * The keyword query (websearch syntax, OR of quoted forms) that finds chunks+ * holding the identifier however it was written: for a ten-digit phone,+ * 4155550142, 415.555.0142, 415-555-0142, (415) 555-0142, 415 555 0142 and+ * the +1 forms all reach the same chunks through the existing full-text index.+ */+export function identifierKeywordQuery(id: Identifier): string {+ if (id.kind !== 'phone') return `"${id.raw.replace(/"/g, '')}"`;+ const n = nationalDigits(id.needle);+ const forms = new Set<string>([id.needle, n]);+ if (n.length === 10) {+ const [a, b, c] = [n.slice(0, 3), n.slice(3, 6), n.slice(6)];+ for (const f of [`${a}.${b}.${c}`, `${a}-${b}-${c}`, `(${a}) ${b}-${c}`, `${a} ${b} ${c}`, `+1 ${a} ${b} ${c}`, `+1${n}`, `1${n}`]) forms.add(f);+ } else if (n.length === 7) {+ forms.add(`${n.slice(0, 3)}-${n.slice(3)}`);+ forms.add(`${n.slice(0, 3)} ${n.slice(3)}`);+ }+ return [...forms].map(f => (/[\s()+-]/.test(f) ? `"${f}"` : f)).join(' OR ');+}++const PHONE_SPAN_RE = /\+?\(?\d[\d\s().-]{5,22}\d/g;++/**+ * Whether `text` contains the identifier: a case-insensitive substring+ * bounded by non-word characters, or for a phone one written phone number+ * whose digits are the asked number (with or without the country code).+ */+export function textContainsIdentifier(text: string, id: Identifier): boolean {+ if (!text) return false;+ if (id.kind === 'phone') {+ const want = nationalDigits(id.needle);+ for (const m of text.matchAll(PHONE_SPAN_RE)) {+ const d = digitsOf(m[0]);+ if (d === id.needle || nationalDigits(d) === want) return true;+ }+ return false;+ }+ const hay = text.toLowerCase();+ let at = hay.indexOf(id.needle);+ while (at >= 0) {+ const before = at === 0 ? '' : hay[at - 1]!;+ const after = hay[at + id.needle.length] ?? '';+ if (!/[a-z0-9]/.test(before) && !/[a-z0-9]/.test(after)) return true;+ at = hay.indexOf(id.needle, at + 1);+ }+ return false;+}diff --git a/src/core/types.ts b/src/core/types.tsindex 7ccf11683d..140abbe46e 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1106,12 +1106,13 @@ export interface SearchResult {keyword_hit?: boolean;/*** #1663 — set when the structural exact-lookup tier promoted/injected this- * result (query was the page's slug or exact normalized title). Drives the+ * result (query was the page's slug or exact normalized title, or #7163 an+ * identifier the page's text contains). Drives the* autocut preserve predicate (tier hits carry no rerank_score) and* `--explain` telemetry; evidence still reads via alias_hit /* title_match_boost so the frozen EVIDENCE_ENUM is untouched.*/- exact_lookup?: 'slug' | 'title';+ exact_lookup?: 'slug' | 'title' | 'identifier';/*** Set when `search.entity_anchoring` moved or added this row for an* entity-scoped current-state query (search/entity-anchor.ts): the nameddiff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 514f46b93f..ece78f44ad 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -223,6 +223,7 @@ const entity: Operation = {names: { type: 'array', items: { type: 'string' }, description: 'Or up to 50 names/codes at once: compact rows.' },source_id: { type: 'string', description: 'Read only this source. Default: your source first, then every source you can read.', fullSurfaceOnly: true },prefer_source_id: { type: 'string', description: 'Source to try first (thin clients send .gbrain-source here); never narrows.', fullSurfaceOnly: true },+ variants: { type: 'boolean', description: 'Default true: when no exact name matches, resolve one unambiguous name variant (nickname, initial, title, order, surname typo, unique surname; card.match says which). false: exact names only.' },},scope: 'read',verb: true,@@ -244,7 +245,7 @@ const entity: Operation = {`Pass either name: "Alice Example" for one full card, or names: ["Alice Example", "WGCO"] (up to ${ENTITY_NAMES_MAX}) for compact rows.`);}const t0 = Date.now();- const out = await lookupEntityNames(ctx.engine, walk.home, names, { remote: ctx.remote !== false, sources: walk.sources, surfaceCeiling: ctx.surfaceCeiling,+ const out = await lookupEntityNames(ctx.engine, walk.home, names, { remote: ctx.remote !== false, sources: walk.sources, surfaceCeiling: ctx.surfaceCeiling, variants: p.variants !== false,emitNotice: n => ctx.emitNotice?.(n) });ambientMiss(out.results.map(r => ({ name: r.name, ...(r.found ? { foundIn: r.source_id } : {}) })));return { protocol_version: 1, latency_ms: Date.now() - t0, ...out };@@ -260,7 +261,7 @@ const entity: Operation = {const t0 = Date.now();const { buildEntityCard } = await import('./verbs/entity-card.ts');const result = await buildEntityCard(ctx.engine, walk.home, name, {- remote: ctx.remote !== false, includeReferences: true, surfaceCeiling: ctx.surfaceCeiling, sources: walk.sources,+ remote: ctx.remote !== false, includeReferences: true, surfaceCeiling: ctx.surfaceCeiling, sources: walk.sources, variants: p.variants !== false,omitQuarantined: ctx.remote !== false, // #5575: like get_page, a remote reader never gets a quarantined page's cardemitNotice: n => ctx.emitNotice?.(n),});@@ -282,6 +283,8 @@ const entity: Operation = {...(result.card ? { card: result.card } : {}),...(result.suggestions !== undefined ? { suggestions: result.suggestions } : {}),...(!result.card && result.coverage ? { coverage: result.coverage } : {}),+ ...(result.text_mentions ? { text_mentions: result.text_mentions } : {}),+ ...(result.ambiguous ? { ambiguous: true } : {}),};},cliHints: { name: 'entity', positional: ['name'] },diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex 59cc8f2184..8de556843f 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -29,7 +29,10 @@ import { isQuarantined } from '../quarantine.ts';import { loadPageTrust } from '../eligibility/stamp.ts';import { loadRelationshipNotes, relationshipNoteKey } from '../link-relationship-notes.ts';import { normalizeAlias } from '../search/alias-normalize.ts';-import { slugify } from '../entities/resolve.ts';+import { isIdentityEntity, slugify } from '../entities/resolve.ts';+import { nameVariantsEnabled, readPossibleDuplicates, resolveNameVariant, type PossibleDuplicate } from './entity-variants.ts';+import { readTextMentions, type TextMentions } from './entity-text-mentions.ts';+import type { NameMatchKind } from '../entities/name-variants.ts';import { exactMatchPreference } from '../entities/exact-match-preference.ts';import { safeSynopsis } from '../context/retrieval-reflex.ts';import { stampEvidence, markKeywordHits } from '../search/evidence.ts';@@ -48,6 +51,8 @@ const EDGE_CAP = 10;const OPEN_THREADS_CAP = 3;const OPEN_THREAD_TIMELINE_WINDOW_DAYS = 90;const SUGGESTION_CAP = 3;+/** Keyword hits read for near-miss suggestions before keeping entity pages only. */+const NEAR_MISS_POOL = 20;const FACT_FETCH_CAP = 100;export const RECENT_FACTS_CAP = 5;@@ -146,6 +151,12 @@ export interface EntityCard {quarantined?: true;/** #5575 CEO-20 (additive): the entity page carries an unconfirmed instruction-family write-gate flag. */unconfirmed?: true;+ /** #7160 (additive): the card resolved through a name variant (nickname, initial, title, reordering, typo or surname), not an exact name. */+ match?: EntityNameMatch;+ /** #7160 (additive): title-prefixed person pages that likely name the same person (reported only, never merged). `entity` verb only. */+ possible_duplicates?: PossibleDuplicate[];+ /** #7161 (additive): on a card with no backlinks and no facts while mention coverage is incomplete, pages whose text contains the title (unlinked text matches, newest first). `entity` verb only. */+ text_mentions?: TextMentions;}export interface ReferenceGroupView {@@ -156,6 +167,13 @@ export interface ReferenceGroupView {next?: { tool: 'get_backlinks'; arguments: Record<string, unknown>; requires_surface?: 'starter' };}+/** #7160: how a name-variant arm matched (absent on alias, exact and suffix hits). */+export interface EntityNameMatch {+ kind: NameMatchKind;+ /** The name as asked. */+ via: string;+}+export interface EntitySuggestion {slug: string;title: string;@@ -170,6 +188,10 @@ export interface EntityCardResult {suggestions?: EntitySuggestion[];/** On a miss with `includeReferences`: the source's mention coverage (a miss may be a not-yet-indexed name). */coverage?: MentionCoverage;+ /** #7161: on a miss with `includeReferences`, pages whose text contains the name (unlinked text matches, newest first). */+ text_mentions?: TextMentions;+ /** #7160: on a miss, the name matched several entity pages as a variant (listed in suggestions); pick one rather than create a page. */+ ambiguous?: true;/** #6723: the source of the resolved page (absent on a miss). */source_id?: string;/**@@ -211,6 +233,12 @@ export interface EntityCardOpts {* the entity verb passes it for remote callers, like get_page.*/omitQuarantined?: boolean;+ /**+ * #7160: run the name-variant arm after the precision arms miss. The+ * `entity` verb and `entity names` ask for it; proactive cards+ * (context_pack, delta) never resolve a guessed name.+ */+ variants?: boolean;}export interface CardPageRow {@@ -227,6 +255,10 @@ export interface CardPageRow {last_retrieved_at: Date | string | null;}+/** The card's page-row projection over `pages` (bounded body prefix, last retrieval). */+const CARD_ROW_COLUMNS = `slug, source_id, title, type, frontmatter, ${boundedBodyPrefixSql('pages')} AS compiled_truth, updated_at,+ GREATEST(last_retrieved_at, (SELECT r.last_retrieved_at FROM page_retrievals r WHERE r.page_id = pages.id)) AS last_retrieved_at`;+/** Resolution arm rank: lower = higher confidence (frozen precedence ladder). */const ARM_ALIAS = 0;const ARM_EXACT = 1;@@ -262,8 +294,8 @@ export async function entityLookupScope(engine: BrainEngine, sourceId: string, r* page `omitQuarantined` leaves out (no suggestion names it).*/export type EntityCandidates =- | { kind: 'hit'; row: CardPageRow; runnersUp: EntitySuggestion[] }- | { kind: 'miss'; suggestions: EntitySuggestion[] }+ | { kind: 'hit'; row: CardPageRow; runnersUp: EntitySuggestion[]; match?: EntityNameMatch }+ | { kind: 'miss'; suggestions: EntitySuggestion[]; ambiguous?: true }| { kind: 'withheld' };/** Resolve a trimmed, non-empty name to its candidates. Every arm is fail-soft. */@@ -272,7 +304,7 @@ export async function selectEntityCandidates(sourceId: string,trimmed: string,scope: EntityLookupScope,- opts: { omitQuarantined?: boolean; suggest?: boolean } = {},+ opts: { omitQuarantined?: boolean; suggest?: boolean; variants?: boolean } = {},): Promise<EntityCandidates> {const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');// Predicate text lives ONCE (private-visibility.ts) — both card queries@@ -310,8 +342,7 @@ export async function selectEntityCandidates(let rows: CardPageRow[] = [];try {rows = await engine.executeRaw<CardPageRow>(- `SELECT slug, source_id, title, type, frontmatter, ${boundedBodyPrefixSql('pages')} AS compiled_truth, updated_at,- GREATEST(last_retrieved_at, (SELECT r.last_retrieved_at FROM page_retrievals r WHERE r.page_id = pages.id)) AS last_retrieved_at+ `SELECT ${CARD_ROW_COLUMNS}FROM pagesWHERE deleted_at IS NULLAND source_id = $1@@ -335,8 +366,7 @@ export async function selectEntityCandidates(if (missing.length) {try {const extra = await engine.executeRaw<CardPageRow>(- `SELECT slug, source_id, title, type, frontmatter, ${boundedBodyPrefixSql('pages')} AS compiled_truth, updated_at,- GREATEST(last_retrieved_at, (SELECT r.last_retrieved_at FROM page_retrievals r WHERE r.page_id = pages.id)) AS last_retrieved_at+ `SELECT ${CARD_ROW_COLUMNS}FROM pagesWHERE deleted_at IS NULL AND source_id = $1 AND slug = ANY($2::text[])${privatePredicate}`,[sourceId, missing],@@ -369,7 +399,26 @@ export async function selectEntityCandidates(candidates.splice(0, candidates.length, ...live);}if (candidates.length === 0) {- return { kind: 'miss', suggestions: opts.suggest === false ? [] : await nearMissSuggestions(engine, sourceId, trimmed, scope.excludePrivate) };+ // #7160: the name-variant arm, after every precision arm missed.+ const variants = opts.variants && await nameVariantsEnabled(engine)+ ? await resolveNameVariant<CardPageRow>(engine, sourceId, trimmed, {+ selectColumns: CARD_ROW_COLUMNS, privatePredicate, entityTypes: scope.entityTypes, omitQuarantined: opts.omitQuarantined,+ retirementPrivacy: scope.excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : '' })+ : { matches: [] };+ const variantSuggestions = (matches: typeof variants.matches): EntitySuggestion[] => matches.map(m => ({+ slug: m.row.slug, title: m.row.title ?? m.row.slug, create_safety: 'exists', source_id: sourceId }));+ if (variants.hit) {+ const hit = variants.hit;+ const [row] = await overlaidBoundedRows(engine, [hit.row]);+ return { kind: 'hit', row, match: { kind: hit.kind, via: trimmed },+ runnersUp: variantSuggestions(variants.matches.filter(m => m.row.slug !== hit.row.slug)).slice(0, SUGGESTION_CAP) };+ }+ const ambiguous = variants.matches.length > 0 ? { ambiguous: true as const } : {};+ if (opts.suggest === false) return { kind: 'miss', suggestions: [], ...ambiguous };+ const seen = new Set<string>();+ const suggestions = [...variantSuggestions(variants.matches), ...await nearMissSuggestions(engine, sourceId, trimmed, scope)]+ .filter(x => !seen.has(x.slug) && (seen.add(x.slug), true));+ return { kind: 'miss', suggestions: suggestions.slice(0, SUGGESTION_CAP), ...ambiguous };}// Large pages: the hit carries a bounded, withdrawal-overlaid body prefix (its summary and lead read only that).@@ -399,16 +448,27 @@ export async function selectAcrossSources(sources: readonly string[],trimmed: string,remote: boolean,- opts: { omitQuarantined?: boolean; scopes?: Map<string, Promise<EntityLookupScope>> } = {},+ opts: { omitQuarantined?: boolean; scopes?: Map<string, Promise<EntityLookupScope>>; variants?: boolean } = {},): Promise<{ sourceId: string; scope: EntityLookupScope; selected: EntityCandidates }> {let first: { sourceId: string; scope: EntityLookupScope; selected: EntityCandidates } | undefined;+ const variantHits: Array<{ sourceId: string; scope: EntityLookupScope; selected: Extract<EntityCandidates, { kind: 'hit' }> }> = [];+ let variantAmbiguous = false;for (const sourceId of sources) {if (opts.scopes && !opts.scopes.has(sourceId)) opts.scopes.set(sourceId, entityLookupScope(engine, sourceId, remote));const scope = await (opts.scopes?.get(sourceId) ?? entityLookupScope(engine, sourceId, remote));- const selected = await selectEntityCandidates(engine, sourceId, trimmed, scope, { omitQuarantined: opts.omitQuarantined, suggest: first === undefined });- if (selected.kind === 'hit') return { sourceId, scope, selected };+ const selected = await selectEntityCandidates(engine, sourceId, trimmed, scope, { omitQuarantined: opts.omitQuarantined, suggest: first === undefined, variants: opts.variants });+ // #7160: an exact hit in any source beats a name-variant guess, and a guess must be unique across every source read.+ if (selected.kind === 'hit' && !selected.match) return { sourceId, scope, selected };+ if (selected.kind === 'hit') variantHits.push({ sourceId, scope, selected });+ if (selected.kind === 'miss' && selected.ambiguous) variantAmbiguous = true;first ??= { sourceId, scope, selected };}+ if (variantHits.length === 1 && !variantAmbiguous) return variantHits[0]!;+ if (variantHits.length && first) {+ const hitSuggestions = variantHits.map(v => ({ slug: v.selected.row.slug, title: v.selected.row.title ?? v.selected.row.slug, create_safety: 'exists', source_id: v.sourceId }));+ const rest = first.selected.kind === 'miss' ? first.selected.suggestions : [];+ return { ...first, selected: { kind: 'miss', ambiguous: true, suggestions: [...hitSuggestions, ...rest].slice(0, SUGGESTION_CAP) } };+ }return first!;}@@ -424,21 +484,41 @@ export async function buildEntityCard(// Covers entity, context_pack, and delta (all route through buildEntityCard).// #6723: the source with the hit owns the card; every read below uses it.const sources = opts.sources?.length ? opts.sources : [sourceId];- const { sourceId: hitSource, scope, selected } = await selectAcrossSources(engine, sources, trimmed, opts.remote, { omitQuarantined: opts.omitQuarantined });+ const { sourceId: hitSource, scope, selected } = await selectAcrossSources(engine, sources, trimmed, opts.remote, { omitQuarantined: opts.omitQuarantined, variants: opts.variants });if (selected.kind === 'withheld') return { found: false, suggestions: [] };if (selected.kind === 'miss') {+ const ambiguous = selected.ambiguous ? { ambiguous: selected.ambiguous } : {};+ if (!opts.includeReferences) return { found: false, suggestions: selected.suggestions, ...ambiguous };+ const textMentions = await readTextMentions(engine, sources, trimmed, { remote: opts.remote, excludePrivate: scope.excludePrivate, omitQuarantined: opts.omitQuarantined });return {found: false, suggestions: selected.suggestions,- ...(opts.includeReferences ? { coverage: await readMentionCoverage(engine, [...sources]).catch(() => undefined) } : {}),+ coverage: await readMentionCoverage(engine, [...sources]).catch(() => undefined),+ ...(textMentions?.total || textMentions?.unread ? { text_mentions: textMentions } : {}),+ ...ambiguous,};}- const { row, runnersUp } = selected;+ const { row, runnersUp, match } = selected;const { card, facts: factRows } = await assembleCard(engine, hitSource, row, opts.remote, scope.excludePrivate, opts.eligibility ?? {});+ if (match) card.match = match;if (opts.includeReferences) {Object.assign(card, await cardReferences(engine, hitSource, row, opts, scope.excludePrivate, scope.entityTypes),await readCardIdentity(engine, hitSource, row, { excludePrivate: scope.excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }));await attachCardRecords(engine, hitSource, card, opts, scope.excludePrivate);+ if (await nameVariantsEnabled(engine)) {+ const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');+ const duplicates = await readPossibleDuplicates<CardPageRow>(engine, hitSource, row, {+ selectColumns: CARD_ROW_COLUMNS, entityTypes: scope.entityTypes, omitQuarantined: opts.omitQuarantined,+ privatePredicate: scope.excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : '',+ retirementPrivacy: scope.excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : '' });+ if (duplicates.length) card.possible_duplicates = duplicates;+ }+ // #7161: a thin card while mentions are behind may be a stale stub; show where the name appears in text.+ if (card.backlink_count === 0 && card.active_fact_count === 0 && card.coverage && card.coverage.state !== 'complete') {+ const textMentions = await readTextMentions(engine, [hitSource], row.title || trimmed,+ { remote: opts.remote, excludePrivate: scope.excludePrivate, omitQuarantined: opts.omitQuarantined, exclude: [row.slug] });+ if (textMentions?.total || textMentions?.unread) card.text_mentions = textMentions;+ }}return {found: true,@@ -730,11 +810,14 @@ async function nearMissSuggestions(engine: BrainEngine,sourceId: string,name: string,- excludePrivate = false,+ scope: Pick<EntityLookupScope, 'excludePrivate' | 'entityTypes'>,): Promise<EntitySuggestion[]> {try {- const raw = await engine.searchKeyword(name, { limit: SUGGESTION_CAP, sourceId, excludePrivate });- const results = raw as SearchResult[];+ // #7160: over-fetch keyword hits and keep entity pages only; index, digest and note pages are never "did you mean".+ const raw = await engine.searchKeyword(name, { limit: NEAR_MISS_POOL, sourceId, excludePrivate: scope.excludePrivate });+ const results = (raw as SearchResult[])+ .filter((r, i, all) => (isIdentityEntity(r.slug, r.type) || scope.entityTypes.has(r.type ?? '')) && all.findIndex(o => o.slug === r.slug) === i)+ .slice(0, SUGGESTION_CAP);// #3783 — direct FTS path: every row is a keyword hit by construction.markKeywordHits(results);stampEvidence(results);diff --git a/src/core/verbs/entity-names.ts b/src/core/verbs/entity-names.tsindex 5335cf4f91..758cc34989 100644--- a/src/core/verbs/entity-names.ts+++ b/src/core/verbs/entity-names.ts@@ -19,7 +19,7 @@* RECORD_ROWS_PER_CALL per call, allotted in input order.*/import type { BrainEngine } from '../engine.ts';-import { readAka, selectAcrossSources, type EntityLookupScope } from './entity-card.ts';+import { readAka, selectAcrossSources, type EntityLookupScope, type EntityNameMatch } from './entity-card.ts';import { readSiblingIdentity } from './entity-card-identity.ts';import { boundedProjectedPrefix } from '../page-window/document.ts';import { boundedBodyPrefixSql, overlaidBoundedRows } from '../page-window/bounded-lead.ts';@@ -34,8 +34,8 @@ const CONCURRENCY = 8;export interface EntityNamePage extends RowReferences { slug: string; title: string; type: string | null; aka: string[]; lead: string }export type EntityNameRow =- | ({ name: string; found: true; source_id: string } & EntityNamePage & { siblings?: EntityNamePage[] })- | { name: string; found: false; suggestions?: Array<{ slug: string; title: string }> };+ | ({ name: string; found: true; source_id: string } & EntityNamePage & { siblings?: EntityNamePage[]; match?: EntityNameMatch })+ | { name: string; found: false; suggestions?: Array<{ slug: string; title: string }>; ambiguous?: true };/** The opening prose of a page body: fences and secrets removed, headings, markers and table rows dropped, up to `max` characters. */export function pageLead(body: string | null, max = ENTITY_LEAD_CHARS): string {@@ -47,7 +47,7 @@ export function pageLead(body: string | null, max = ENTITY_LEAD_CHARS): string {}export async function lookupEntityNames(engine: BrainEngine, sourceId: string, names: string[],- opts: { remote: boolean; sources?: readonly string[]; surfaceCeiling?: 'verbs' | 'starter' | 'full'; emitNotice?: (n: Notice) => void }): Promise<{ results: EntityNameRow[]; found: number; missing: number }> {+ opts: { remote: boolean; sources?: readonly string[]; surfaceCeiling?: 'verbs' | 'starter' | 'full'; emitNotice?: (n: Notice) => void; variants?: boolean }): Promise<{ results: EntityNameRow[]; found: number; missing: number }> {const unique = [...new Set(names.map(n => n.trim()).filter(Boolean))];// #6723: each name resolves in the first source (home first) with a hit; a source's lookup scope is read once per batch.const sources = opts.sources?.length ? opts.sources : [sourceId];@@ -56,7 +56,7 @@ export async function lookupEntityNames(engine: BrainEngine, sourceId: string, nconst rows = new Map<string, EntityNameRow>();for (let i = 0; i < unique.length; i += CONCURRENCY) {await Promise.all(unique.slice(i, i + CONCURRENCY).map(async name => {- const { sourceId: hitSource, scope, selected } = await selectAcrossSources(engine, sources, name, opts.remote, { omitQuarantined: opts.remote, scopes });+ const { sourceId: hitSource, scope, selected } = await selectAcrossSources(engine, sources, name, opts.remote, { omitQuarantined: opts.remote, scopes, variants: opts.variants });excludePrivate.set(hitSource, scope.excludePrivate);rows.set(name, await lookupOne(engine, hitSource, name, scope, selected, opts));}));@@ -91,7 +91,7 @@ async function lookupOne(engine: BrainEngine, sourceId: string, name: string, scselected: Awaited<ReturnType<typeof selectAcrossSources>>['selected'], opts: { remote: boolean }): Promise<EntityNameRow> {if (selected.kind !== 'hit') {const suggestions = (selected.kind === 'miss' ? selected.suggestions : []).slice(0, 3).map(s => ({ slug: s.slug, title: s.title }));- return { name, found: false, ...(suggestions.length ? { suggestions } : {}) };+ return { name, found: false, ...(suggestions.length ? { suggestions } : {}), ...(selected.kind === 'miss' && selected.ambiguous ? { ambiguous: true as const } : {}) };}const { row } = selected;const aka = await readAka(engine, sourceId, row.slug);@@ -107,6 +107,7 @@ async function lookupOne(engine: BrainEngine, sourceId: string, name: string, sc}return {name, found: true, source_id: sourceId, slug: row.slug, title: row.title ?? row.slug, type: row.type ?? null, aka, lead: pageLead(bodies.get(row.slug) ?? null),+ ...(selected.match ? { match: selected.match } : {}),...(siblingPages.length ? { siblings: siblingPages.map(p => ({ slug: p.slug, title: p.title, type: p.type, aka: p.aka, lead: pageLead(bodies.get(p.slug) ?? null) })) } : {}),};}diff --git a/src/core/verbs/entity-text-mentions.ts b/src/core/verbs/entity-text-mentions.tsnew file mode 100644index 0000000000..ba43f5ed0a--- /dev/null+++ b/src/core/verbs/entity-text-mentions.ts@@ -0,0 +1,110 @@+/**+ * #7161: names that only appear in page text. Entity resolution reads pages,+ * aliases and the mention index; while mention extraction is behind, a name+ * that only sits in notes, calendar pages or transcripts resolves to nothing,+ * and a thin stub page hides the fresh mention in a recent note. This probe+ * is one bounded keyword read of the exact name as a phrase, under the same+ * read policy as search (source grant, private pages, safe chunks for+ * untrusted callers, quarantined pages left out), verified against the chunk+ * text, so every listed page really contains the name. The result is+ * labelled as unlinked text matches: it says the name appears there, not+ * that those pages are waiting for extraction.+ */++import type { BrainEngine } from '../engine.ts';+import type { SearchResult } from '../types.ts';+import { isQuarantined } from '../quarantine.ts';+import { nameWords } from '../entities/name-variants.ts';++/** Keyword rows read for one name; a full read reports the total as a floor (`capped`). */+export const TEXT_MENTION_POOL = 50;+/** Pages listed, newest first. */+export const TEXT_MENTION_SHOWN = 5;+/** The probe's wall-clock budget; past it the card reports `unread: 'deadline'` instead of waiting. */+export const TEXT_MENTION_DEADLINE_MS = 1500;+const MAX_NAME_WORDS = 5;++export interface TextMentionPage { slug: string; title: string; type: string | null; source_id: string; date: string | null }++export interface TextMentions {+ /** Pages whose text contains the name, newest first. */+ pages: TextMentionPage[];+ /** Distinct pages found; a floor when `capped`. */+ total: number;+ capped: boolean;+ /** The probe could not finish (TEXT_MENTION_DEADLINE_MS) or failed: the name was not checked, which is not "no matches". */+ unread?: 'deadline' | 'read_failed';+}++/** Whether `name` is worth a text probe: one to five words with a letter, not a slug. */+export function textProbeApplies(name: string): boolean {+ const words = nameWords(name);+ return !name.includes('/') && words.length >= 1 && words.length <= MAX_NAME_WORDS && words.some(w => /\p{L}/u.test(w) && w.length >= 2);+}++const containsName = (text: string, words: string[]) => {+ const hay = ` ${nameWords(text).join(' ')} `;+ return hay.includes(` ${words.join(' ')} `);+};++/**+ * Pages in `sources` whose text contains `name` as a phrase (null when+ * the probe does not apply or the read failed). `exclude` drops pages the+ * caller already shows (the card's own page).+ */+export async function readTextMentions(+ engine: BrainEngine,+ sources: readonly string[],+ name: string,+ opts: { remote: boolean; excludePrivate: boolean; omitQuarantined?: boolean; exclude?: readonly string[] },+): Promise<TextMentions | null> {+ if (!textProbeApplies(name) || !sources.length) return null;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = new Promise<TextMentions>(resolve => {+ timer = setTimeout(() => resolve({ pages: [], total: 0, capped: false, unread: 'deadline' }), TEXT_MENTION_DEADLINE_MS);+ });+ try {+ return await Promise.race([probe(engine, sources, name, opts), deadline]);+ } finally {+ clearTimeout(timer);+ }+}++async function probe(+ engine: BrainEngine,+ sources: readonly string[],+ name: string,+ opts: { remote: boolean; excludePrivate: boolean; omitQuarantined?: boolean; exclude?: readonly string[] },+): Promise<TextMentions> {+ const words = nameWords(name);+ let rows: SearchResult[];+ try {+ rows = await engine.searchKeyword(`"${words.join(' ')}"`, {+ limit: TEXT_MENTION_POOL,+ ...(sources.length === 1 ? { sourceId: sources[0] } : { sourceIds: [...sources] }),+ excludePrivate: opts.excludePrivate,+ requireSafeChunks: opts.remote,+ });+ } catch {+ return { pages: [], total: 0, capped: false, unread: 'read_failed' };+ }+ const exclude = new Set(opts.exclude ?? []);+ const capped = rows.length >= TEXT_MENTION_POOL;+ const hits = new Map<string, SearchResult>();+ for (const r of rows) {+ const key = `${r.source_id ?? ''}:${r.slug}`;+ if (r.keyword_relaxed || exclude.has(r.slug) || hits.has(key) || !containsName(r.chunk_text ?? '', words)) continue;+ hits.set(key, r);+ }+ if (!hits.size) return { pages: [], total: 0, capped: false };+ const meta = await engine.executeRaw<{ slug: string; source_id: string; title: string | null; type: string | null; frontmatter: Record<string, unknown> | null; date: Date | string | null }>(+ `SELECT slug, source_id, title, type, frontmatter, COALESCE(effective_date, updated_at) AS date+ FROM pages WHERE deleted_at IS NULL AND source_id = ANY($1::text[]) AND slug = ANY($2::text[])`,+ [[...sources], [...new Set([...hits.values()].map(h => h.slug))]]).catch(() => []);+ const pages = meta+ .filter(m => hits.has(`${m.source_id}:${m.slug}`) && !(opts.omitQuarantined && isQuarantined(m.frontmatter)))+ .map(m => ({ slug: m.slug, title: m.title ?? m.slug, type: m.type, source_id: m.source_id,+ date: m.date == null ? null : new Date(m.date as string).toISOString().slice(0, 10) }))+ .sort((a, b) => (b.date ?? '').localeCompare(a.date ?? '') || a.slug.localeCompare(b.slug));+ return { pages: pages.slice(0, TEXT_MENTION_SHOWN), total: pages.length, capped };+}diff --git a/src/core/verbs/entity-variants.ts b/src/core/verbs/entity-variants.tsnew file mode 100644index 0000000000..4a1d9b40f1--- /dev/null+++ b/src/core/verbs/entity-variants.ts@@ -0,0 +1,168 @@+/**+ * #7160: the entity card's name-variant arm. Runs only after the precision+ * arms (alias, exact title or slug, slug suffix) found nothing. One indexed+ * candidate read per source (title and slug trigram indexes), then the pure+ * matcher in entities/name-variants.ts scores every candidate. A variant+ * resolves only when exactly one live entity page holds the strongest match+ * and the candidate read was not capped (a full read may hide an equal+ * match), and a weak match (surname alone, one-letter typo) only when it is+ * the one page that matched at all. Anything else is+ * ambiguous: nothing resolves and the matches come back as suggestions, so a+ * near-name never lands on a different person.+ *+ * `entity.name_variants=false` turns the arm off.+ */++import type { BrainEngine } from '../engine.ts';+import { isQuarantined } from '../quarantine.ts';+import { followRetirement, isIdentityEntity } from '../entities/resolve.ts';+import { NAME_MATCH_RANK, NAME_TITLE_TOKENS, WEAK_NAME_MATCHES, hasLeadingTitle, matchNameVariant, parsePersonName, probeWords, type NameMatchKind } from '../entities/name-variants.ts';++/** Candidate rows read per source; a full read means another page may have matched, so nothing resolves. */+export const VARIANT_CANDIDATE_CAP = 200;+/** Names longer than this many words are not person or organization names. */+const MAX_NAME_WORDS = 5;++export interface VariantRow { slug: string; title: string | null; type: string | null; frontmatter: Record<string, unknown> | null }++export interface VariantMatch<R extends VariantRow> { row: R; kind: NameMatchKind }++export interface VariantResult<R extends VariantRow> {+ /** The one page the name resolves to, with how it matched. */+ hit?: VariantMatch<R>;+ /** Every entity page that matched, strongest first (the hit included). */+ matches: Array<VariantMatch<R>>;+}++export async function nameVariantsEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ const v = await engine.getConfig('entity.name_variants').catch(() => null);+ return !(typeof v === 'string' && /^(false|off|0|no)$/i.test(v.trim()));+}++const likeWord = (w: string) => `%${w.replace(/[\\%_]/g, m => `\\${m}`)}%`;+const basenameName = (slug: string) => (slug.split('/').pop() ?? '').replace(/[-_]+/g, ' ');++/** The strongest variant under which `name` names this page (by title or slug basename). */+function bestKind(name: string, row: VariantRow): NameMatchKind | null {+ const kinds = [row.title ?? '', basenameName(row.slug)]+ .filter(candidate => !isTitleStub(candidate))+ .map(candidate => matchNameVariant(name, candidate))+ .filter((k): k is NameMatchKind => k !== null);+ return kinds.length ? kinds.reduce((a, b) => (NAME_MATCH_RANK[b] < NAME_MATCH_RANK[a] ? b : a)) : null;+}++/** "Mayor Example": a title in front of one name word. It names someone only through the page it duplicates, never as a variant target. */+export function isTitleStub(name: string): boolean {+ const parsed = parsePersonName(name);+ return parsed.titles.length > 0 && parsed.core.length === 1;+}++/**+ * Variant candidates for `name` in one source. `selectColumns` is the+ * caller's row projection over `pages`; `privatePredicate` its read+ * predicate (` AND ...` or empty) on `pages`, `retirementPrivacy` the same on+ * alias `p` (followRetirement); `entityTypes` the pack's linkable types.+ */+export async function resolveNameVariant<R extends VariantRow>(+ engine: BrainEngine,+ sourceId: string,+ name: string,+ opts: { selectColumns: string; privatePredicate: string; retirementPrivacy: string; entityTypes: ReadonlySet<string>; omitQuarantined?: boolean; exclude?: readonly string[] },+): Promise<VariantResult<R>> {+ const words = probeWords(name);+ if (!words.length || parsePersonName(name).core.length > MAX_NAME_WORDS || name.includes('/')) return { matches: [] };+ let rows: Array<R & { probe_hits: number }>;+ try {+ rows = await engine.executeRaw<R & { probe_hits: number }>(+ `SELECT ${opts.selectColumns},+ (SELECT count(*)::int FROM unnest($4::text[]) w WHERE pages.title ILIKE w OR pages.slug ILIKE w) AS probe_hits+ FROM pages+ WHERE deleted_at IS NULL AND source_id = $1+ AND (type = ANY($2::text[]) OR slug LIKE ANY($3::text[]))+ AND (title ILIKE ANY($4::text[]) OR slug ILIKE ANY($4::text[]))${opts.privatePredicate}+ ORDER BY probe_hits DESC, length(title), slug+ LIMIT ${VARIANT_CANDIDATE_CAP + 1}`,+ [sourceId, [...opts.entityTypes, 'person', 'company', 'fund', 'organization'],+ ['people/%', 'companies/%', 'funds/%', 'orgs/%', 'organizations/%'], words.map(likeWord)],+ );+ } catch {+ return { matches: [] };+ }+ const capped = rows.length > VARIANT_CANDIDATE_CAP;+ const exclude = new Set(opts.exclude ?? []);+ const best = new Map<string, VariantMatch<R>>();+ for (const row of rows.slice(0, VARIANT_CANDIDATE_CAP)) {+ if (exclude.has(row.slug) || !isIdentityEntity(row.slug, row.type) && !opts.entityTypes.has(row.type ?? '')) continue;+ if (opts.omitQuarantined && isQuarantined(row.frontmatter)) continue;+ const kind = bestKind(name, row);+ if (!kind) continue;+ const live = await followRetirement(engine, sourceId, row.slug, opts.retirementPrivacy).catch(() => null);+ if (!live || exclude.has(live.slug)) continue;+ let target: R | undefined = live.slug === row.slug ? row : rows.find(r => r.slug === live.slug);+ if (!target) {+ const [fetched] = await engine.executeRaw<R>(+ `SELECT ${opts.selectColumns} FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND slug = $2${opts.privatePredicate}`,+ [sourceId, live.slug]).catch(() => [] as R[]);+ if (!fetched || (opts.omitQuarantined && isQuarantined(fetched.frontmatter))) continue;+ target = fetched;+ }+ const prev = best.get(target.slug);+ if (!prev || NAME_MATCH_RANK[kind] < NAME_MATCH_RANK[prev.kind]) best.set(target.slug, { row: target, kind });+ }+ const matches = [...best.values()].sort((a, b) => NAME_MATCH_RANK[a.kind] - NAME_MATCH_RANK[b.kind] || a.row.slug.localeCompare(b.row.slug));+ if (!matches.length) return { matches };+ const top = matches.filter(m => m.kind === matches[0]!.kind);+ const weak = WEAK_NAME_MATCHES.has(matches[0]!.kind);+ const unique = !capped && top.length === 1 && (!weak || matches.length === 1);+ return unique ? { hit: matches[0], matches } : { matches };+}++export interface PossibleDuplicate { slug: string; title: string; reason: 'title_prefix' }++/**+ * #7160: title-prefixed person pages that likely name the same person as+ * `row` ("people/mayor-example" next to "people/alice-example"). Reported,+ * never merged or substituted: a pair qualifies only when the prefixed+ * page's remaining name resolves by the variant rules to exactly one other+ * person page. For a prefixed page that is the unprefixed page it+ * duplicates; for an unprefixed page, every prefixed page whose remainder+ * resolves to it. Fail-soft: a read error reports nothing.+ */+export async function readPossibleDuplicates<R extends VariantRow>(+ engine: BrainEngine,+ sourceId: string,+ row: VariantRow,+ opts: { selectColumns: string; privatePredicate: string; retirementPrivacy: string; entityTypes: ReadonlySet<string>; omitQuarantined?: boolean },+): Promise<PossibleDuplicate[]> {+ if (!row.slug.startsWith('people/') && row.type !== 'person') return [];+ const basename = basenameName(row.slug);+ const resolveRemainder = async (stub: VariantRow): Promise<string | null> => {+ const name = [stub.title ?? '', basenameName(stub.slug)].find(hasLeadingTitle);+ if (!name) return null;+ const res = await resolveNameVariant<R>(engine, sourceId, parsePersonName(name).core.join(' '), { ...opts, exclude: [stub.slug] });+ return res.hit?.row.slug ?? null;+ };+ try {+ if (hasLeadingTitle(row.title ?? '') || hasLeadingTitle(basename)) {+ const target = await resolveRemainder(row);+ if (!target) return [];+ const [t] = await engine.executeRaw<{ slug: string; title: string | null }>('SELECT slug, title FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, target]);+ return t ? [{ slug: t.slug, title: t.title ?? t.slug, reason: 'title_prefix' }] : [];+ }+ const core = parsePersonName(row.title || basename).core;+ if (core.length < 2) return [];+ const last = core[core.length - 1]!;+ const slugs = [...NAME_TITLE_TOKENS].flatMap(t => [`people/${t}-${last}`, `people/${t}-${core.join('-')}`]);+ const stubs = await engine.executeRaw<R>(+ `SELECT ${opts.selectColumns} FROM pages WHERE deleted_at IS NULL AND source_id = $1 AND slug = ANY($2::text[]) AND slug <> $3${opts.privatePredicate}`,+ [sourceId, slugs, row.slug]);+ const out: PossibleDuplicate[] = [];+ for (const stub of stubs) {+ if (opts.omitQuarantined && isQuarantined(stub.frontmatter)) continue;+ if (await resolveRemainder(stub) === row.slug) out.push({ slug: stub.slug, title: stub.title ?? stub.slug, reason: 'title_prefix' });+ }+ return out;+ } catch {+ return [];+ }+}diff --git a/test/entity-card-name-variants.test.ts b/test/entity-card-name-variants.test.tsnew file mode 100644index 0000000000..eecc3a839e--- /dev/null+++ b/test/entity-card-name-variants.test.ts@@ -0,0 +1,162 @@+/**+ * #7160: the entity card's name-variant arm (nickname, initial, title,+ * reordering, typo, surname) on PGLite. Synthetic names only.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { buildEntityCard } from '../src/core/verbs/entity-card.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++const person = (slug: string, title: string, extra: Record<string, unknown> = {}) =>+ engine.putPage(slug, { title, type: 'person', compiled_truth: `${title} works at acme-example.`, frontmatter: extra } as never);++beforeEach(async () => {+ await resetPgliteState(engine);+ await person('people/alice-example', 'Alice Example');+ await person('people/robert-thistlewood', 'Robert Thistlewood');+ await person('people/katherine-quillfeather', 'Katherine Quillfeather');+ await person('people/alicia-sample', 'Alicia Sample');+ await person('people/bob-sample', 'Bob Sample');+ await engine.putPage('notes/people-index', { title: 'People index', type: 'note', compiled_truth: 'Alice Example, Robert Thistlewood, Katherine Quillfeather, Alicia Sample.' } as never);+});++const lookup = async (name: string, remote = false) => buildEntityCard(engine, 'default', name, { remote, variants: true });++describe('name variants resolve to the one matching person', () => {+ const cases: Array<[string, string, string]> = [+ ['Allie Example', 'people/alice-example', 'diminutive'],+ ['A. Example', 'people/alice-example', 'initial'],+ ['example alice', 'people/alice-example', 'reordered'],+ ['Example, Alice', 'people/alice-example', 'reordered'],+ ['Dr. Alice Example', 'people/alice-example', 'honorific'],+ ['Alice Exmaple', 'people/alice-example', 'typo'],+ ['Bob Thistlewood', 'people/robert-thistlewood', 'diminutive'],+ ['Thistlewood', 'people/robert-thistlewood', 'surname'],+ ['Kate Quillfeather', 'people/katherine-quillfeather', 'diminutive'],+ ];+ for (const [name, slug, kind] of cases) {+ test(`${name} -> ${slug} (${kind})`, async () => {+ const res = await lookup(name);+ expect(res.found).toBe(true);+ expect(res.card!.entity.slug).toBe(slug);+ expect(res.card!.match).toEqual({ kind: kind as never, via: name });+ });+ }++ test('an exact title keeps resolving without a match annotation', async () => {+ const res = await lookup('Alice Example');+ expect(res.card!.entity.slug).toBe('people/alice-example');+ expect(res.card!.match).toBeUndefined();+ });+});++describe('ambiguity never resolves to a person', () => {+ test('a surname two people share resolves nothing and suggests both', async () => {+ const res = await lookup('Sample');+ expect(res.found).toBe(false);+ expect(res.suggestions!.map(s => s.slug).sort()).toEqual(['people/alicia-sample', 'people/bob-sample']);+ });++ test('a different given name with the same surname is not a variant', async () => {+ const res = await lookup('Margaret Thistlewood');+ expect(res.found).toBe(false);+ });++ test('two typo candidates refuse', async () => {+ await person('people/alice-exampre', 'Alice Exampre');+ const res = await lookup('Alice Exampe');+ expect(res.found).toBe(false);+ });+});++describe('suggestions are entity pages only', () => {+ test('an index page that names the person never appears in did-you-mean', async () => {+ const res = await lookup('Zed Quillfeather');+ expect(res.found).toBe(false);+ expect((res.suggestions ?? []).map(s => s.slug)).not.toContain('notes/people-index');+ });+});++describe('title-prefixed duplicates are reported, never substituted', () => {+ beforeEach(async () => {+ await engine.putPage('people/mayor-thistlewood', { title: 'Mayor Thistlewood', type: 'person', compiled_truth: 'Mayor of a fictional town.' } as never);+ });++ test('the exact stub stays the card and names the person it likely duplicates', async () => {+ const res = await buildEntityCard(engine, 'default', 'Mayor Thistlewood', { remote: false, includeReferences: true, variants: true });+ expect(res.card!.entity.slug).toBe('people/mayor-thistlewood');+ expect(res.card!.possible_duplicates).toEqual([{ slug: 'people/robert-thistlewood', title: 'Robert Thistlewood', reason: 'title_prefix' }]);+ });++ test('the real page lists its prefixed stub', async () => {+ const res = await buildEntityCard(engine, 'default', 'Robert Thistlewood', { remote: false, includeReferences: true, variants: true });+ expect(res.card!.entity.slug).toBe('people/robert-thistlewood');+ expect(res.card!.possible_duplicates).toEqual([{ slug: 'people/mayor-thistlewood', title: 'Mayor Thistlewood', reason: 'title_prefix' }]);+ });++ test('a surname two people share pairs the stub with nobody', async () => {+ await person('people/margaret-thistlewood', 'Margaret Thistlewood');+ const res = await buildEntityCard(engine, 'default', 'Mayor Thistlewood', { remote: false, includeReferences: true, variants: true });+ expect(res.card!.possible_duplicates).toBeUndefined();+ const real = await buildEntityCard(engine, 'default', 'Robert Thistlewood', { remote: false, includeReferences: true, variants: true });+ expect(real.card!.possible_duplicates).toBeUndefined();+ });++ test('a surname query prefers the real person over the title stub', async () => {+ const res = await lookup('Thistlewood');+ expect(res.card?.entity.slug).toBe('people/robert-thistlewood');+ });+});++describe('guesses stay out of proactive cards and across sources', () => {+ test('a card built without variants (context_pack, delta) never resolves a nickname', async () => {+ const res = await buildEntityCard(engine, 'default', 'Allie Example', { remote: false });+ expect(res.found).toBe(false);+ });++ test('one variant match in each of two sources is ambiguous', async () => {+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('s2', 's2', '{}'::jsonb) ON CONFLICT (id) DO NOTHING");+ await engine.putPage('people/alice-example', { title: 'Alice Example', type: 'person', compiled_truth: 'Another person.' } as never, { sourceId: 's2' });+ const res = await buildEntityCard(engine, 'default', 'Allie Example', { remote: false, variants: true, sources: ['default', 's2'] });+ expect(res.found).toBe(false);+ expect(res.ambiguous).toBe(true);+ expect(res.suggestions!.map(x => x.source_id)).toEqual(['default', 's2']);+ });++ test('an exact name in a later source beats a variant in the home source', async () => {+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('s2', 's2', '{}'::jsonb) ON CONFLICT (id) DO NOTHING");+ await engine.putPage('people/allie-example', { title: 'Allie Example', type: 'person', compiled_truth: 'Exact.' } as never, { sourceId: 's2' });+ const res = await buildEntityCard(engine, 'default', 'Allie Example', { remote: false, variants: true, sources: ['default', 's2'] });+ expect(res.source_id).toBe('s2');+ expect(res.card!.match).toBeUndefined();+ });+});++describe('read policy', () => {+ test('a remote caller never resolves a private person by variant', async () => {+ await engine.putPage('people/carol-hidden', { title: 'Carol Hidden', type: 'person', compiled_truth: 'Private.', frontmatter: { visibility: 'private' } } as never);+ const local = await lookup('C. Hidden', false);+ expect(local.card?.entity.slug).toBe('people/carol-hidden');+ const remote = await lookup('C. Hidden', true);+ expect(remote.found).toBe(false);+ expect((remote.suggestions ?? []).map(s => s.slug)).not.toContain('people/carol-hidden');+ });++ test('entity.name_variants=false turns the arm off', async () => {+ await engine.setConfig('entity.name_variants', 'false');+ const res = await lookup('Allie Example');+ expect(res.found).toBe(false);+ });+});diff --git a/test/entity-card-text-mentions.test.ts b/test/entity-card-text-mentions.test.tsnew file mode 100644index 0000000000..03ce95c060--- /dev/null+++ b/test/entity-card-text-mentions.test.ts@@ -0,0 +1,71 @@+/**+ * #7161: names that only appear in page text (entity miss) and thin stub+ * cards while mention coverage is incomplete. Synthetic names only.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { buildEntityCard } from '../src/core/verbs/entity-card.ts';+import { seedPage } from './helpers/keyword-paging-fixture.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++const note = (slug: string, body: string, frontmatter: Record<string, unknown> = {}) =>+ seedPage(engine, slug, body, { title: slug.split('/').pop()!, frontmatter: { date: slug.split('/').pop(), ...frontmatter } });++beforeEach(async () => {+ await resetPgliteState(engine);+ await note('notes/2026-03-01', 'Coffee with Imogen Farthingale about the pilot.');+ await note('notes/2026-04-02', 'Imogen Farthingale sent the revised budget.');+ await note('notes/2026-05-03', 'Unrelated: Imogen met Farthingale Partners.');+ await note('notes/2026-06-04', 'Private: Imogen Farthingale salary talk.', { visibility: 'private' });+});++const card = (name: string, remote = false) => buildEntityCard(engine, 'default', name, { remote, includeReferences: true, omitQuarantined: remote, variants: true });++describe('a name with no page', () => {+ test('a miss lists the pages whose text contains the name, newest first', async () => {+ const res = await card('Imogen Farthingale');+ expect(res.found).toBe(false);+ expect(res.text_mentions!.pages.map(p => p.slug)).toEqual(['notes/2026-06-04', 'notes/2026-04-02', 'notes/2026-03-01']);+ expect(res.text_mentions!.total).toBe(3);+ expect(res.text_mentions!.capped).toBe(false);+ });++ test('a page with both words but not the name is not listed', async () => {+ const res = await card('Imogen Farthingale');+ expect(res.text_mentions!.pages.map(p => p.slug)).not.toContain('notes/2026-05-03');+ });++ test('a remote caller never sees a private page', async () => {+ const res = await card('Imogen Farthingale', true);+ expect(res.text_mentions!.pages.map(p => p.slug)).toEqual(['notes/2026-04-02', 'notes/2026-03-01']);+ });++ test('a name nobody wrote has no text_mentions', async () => {+ const res = await card('Quentin Nobody');+ expect(res.found).toBe(false);+ expect(res.text_mentions).toBeUndefined();+ });+});++describe('a thin stub card while mentions are behind', () => {+ test('lists the newer text mentions next to the stub', async () => {+ await seedPage(engine, 'people/orla-vantage', 'Speaker.', { type: 'person', title: 'Orla Vantage' });+ await note('notes/2026-07-05', 'Orla Vantage announced a new fund today.');+ const res = await card('Orla Vantage');+ expect(res.card!.entity.slug).toBe('people/orla-vantage');+ expect(res.card!.coverage?.state).not.toBe('complete');+ expect(res.card!.text_mentions!.pages.map(p => p.slug)).toEqual(['notes/2026-07-05']);+ });+});diff --git a/test/entity-name-variants.test.ts b/test/entity-name-variants.test.tsnew file mode 100644index 0000000000..ee5a372325--- /dev/null+++ b/test/entity-name-variants.test.ts@@ -0,0 +1,58 @@+/**+ * #7160: name-variant matching for entity lookup (pure). Synthetic names only.+ */+import { describe, expect, test } from 'bun:test';+import { editDistance, hasLeadingTitle, matchNameVariant, parsePersonName, probeWords } from '../src/core/entities/name-variants.ts';++describe('matchNameVariant', () => {+ const cases: Array<[string, string, string | null]> = [+ ['Alice Example', 'Alice Example', 'normalized'],+ ['alice-example', 'Alice Example', 'normalized'],+ ['Dr. Alice Example', 'Alice Example', 'honorific'],+ ['Mayor Alice Example Jr.', 'Alice Example', 'honorific'],+ ['example alice', 'Alice Example', 'reordered'],+ ['Example, Alice', 'Alice Example', 'reordered'],+ ['Allie Example', 'Alice Example', 'diminutive'],+ ['Bob Thistlewood', 'Robert Thistlewood', 'diminutive'],+ ['Robert Thistlewood', 'Bob Thistlewood', 'diminutive'],+ ['A. Example', 'Alice Example', 'initial'],+ ['A Example', 'Alice Example', 'initial'],+ ['Alice Exmaple', 'Alice Example', 'typo'],+ ['Alicee Example', 'Alice Example', null],+ ['Jon Example', 'Joe Example', null],+ ['Allie Exmaple', 'Alice Example', 'typo'],+ ['Example', 'Alice Example', 'surname'],+ ['Mayor Example', 'Alice Example', 'surname'],+ ['Alicia Example', 'Alice Example', null],+ ['Alice Examples', 'Alice Example', 'typo'],+ ['Bob Example', 'Alice Example', null],+ ['B. Example', 'Alice Example', null],+ ['Ex', 'Alice Example', null],+ ['Alice', 'Alice Example', null],+ ['Alice Example', 'Example', null],+ ['Alice Q Example', 'Alice Example', null],+ ];+ for (const [q, c, kind] of cases) {+ test(`${q} vs ${c} -> ${kind}`, () => expect(matchNameVariant(q, c)).toBe(kind as never));+ }+});++describe('helpers', () => {+ test('parsePersonName strips leading titles and trailing suffixes, keeps a title-only name', () => {+ expect(parsePersonName('Senator Dr. Alice Example III')).toEqual({ core: ['alice', 'example'], titles: ['senator', 'dr'] });+ expect(parsePersonName('Mayor')).toEqual({ core: ['mayor'], titles: [] });+ });+ test('hasLeadingTitle reads titles and slug basenames', () => {+ expect(hasLeadingTitle('Mayor Example')).toBe(true);+ expect(hasLeadingTitle('mayor-example')).toBe(true);+ expect(hasLeadingTitle('Alice Example')).toBe(false);+ });+ test('editDistance counts a transposition as one edit and caps', () => {+ expect(editDistance('example', 'exmaple')).toBe(1);+ expect(editDistance('example', 'exampel')).toBe(1);+ expect(editDistance('example', 'sample')).toBe(2);+ });+ test('probeWords keeps core words of three or more letters', () => {+ expect(probeWords('Dr. A. Example')).toEqual(['example']);+ });+});diff --git a/test/recall-entity-flag.test.ts b/test/recall-entity-flag.test.tsnew file mode 100644index 0000000000..4abbc265a4--- /dev/null+++ b/test/recall-entity-flag.test.ts@@ -0,0 +1,67 @@+/**+ * #7166: `gbrain recall --entity <x>` matches the recall op's `entity`+ * parameter (the bare positional's meaning). PGLite only, synthetic names.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runRecall } from '../src/commands/recall.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';++let engine: PGLiteEngine;+const origWrite = process.stdout.write.bind(process.stdout);+let captured = '';++async function recallJson(args: string[]): Promise<{ facts: Array<{ fact: string }> }> {+ captured = '';+ process.stdout.write = ((chunk: string) => { captured += chunk; return true; }) as typeof process.stdout.write;+ try {+ await runRecall(engine, [...args, '--json', '--source', 'default']);+ } finally {+ process.stdout.write = origWrite;+ }+ return JSON.parse(captured);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.putPage('people/alice-example', { title: 'Alice Example', type: 'person', compiled_truth: 'Founder.' } as never);+ await engine.insertFact({ fact: 'prefers morning meetings', kind: 'preference', entity_slug: 'people/alice-example', source: 'test' }, { source_id: 'default' });+ await engine.insertFact({ fact: 'unrelated fact', kind: 'fact', entity_slug: 'people/bob-example', source: 'test' }, { source_id: 'default' });+});++describe('recall --entity', () => {+ test('--entity <slug> recalls the same facts as the positional', async () => {+ const viaFlag = await recallJson(['--entity', 'people/alice-example']);+ const viaPositional = await recallJson(['people/alice-example']);+ expect(viaFlag.facts.map(f => f.fact)).toEqual(['prefers morning meetings']);+ expect(viaFlag.facts).toEqual(viaPositional.facts);+ });++ test('--entity=<name> works too', async () => {+ const res = await recallJson(['--entity=people/alice-example']);+ expect(res.facts.map(f => f.fact)).toEqual(['prefers morning meetings']);+ });++ test('a missing value is refused, not widened to every fact', async () => {+ await expect(recallJson(['--entity'])).rejects.toThrow(/--entity requires/);+ });++ test('a different positional and --entity are refused', async () => {+ await expect(recallJson(['--entity', 'people/alice-example', 'people/bob-example'])).rejects.toThrow(/name different entities/);+ });++ test('the generated flag registry knows --entity for recall', () => {+ expect(CLI_FLAG_REGISTRY.recall).toContain('--entity');+ });+});diff --git a/test/search-identifier-lookup.test.ts b/test/search-identifier-lookup.test.tsnew file mode 100644index 0000000000..b2e4f115c9--- /dev/null+++ b/test/search-identifier-lookup.test.ts@@ -0,0 +1,101 @@+/**+ * #7163: identifier-shaped queries get an exact probe before ranking.+ * Pure detection and containment, then the probe on PGLite. Synthetic data.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { identifierKeywordQuery, parseIdentifier, textContainsIdentifier } from '../src/core/search/identifier-query.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { seedPage } from './helpers/keyword-paging-fixture.ts';+import { structuralExactLookup } from '../src/core/search/exact-lookup.ts';++describe('parseIdentifier', () => {+ const cases: Array<[string, string | null]> = [+ ['[email protected]', 'email'],+ ['+1 415 555 0142', 'phone'],+ ['(415) 555-0142', 'phone'],+ ['415.555.0142', 'phone'],+ ['4155550142', 'digits'],+ ['https://example.com/a/b?x=1', 'url'],+ ['example.com', 'url'],+ ['a3f9c2e81b7d', 'hex'],+ ['INV-2026-00417', 'code'],+ ['"INV-2026-00417"', 'code'],+ ['2026-10-20', null],+ ['alice example', null],+ ['vendor switch', null],+ ['deadbeef', null],+ ['12345', null],+ ];+ for (const [q, kind] of cases) test(`${q} -> ${kind}`, () => expect(parseIdentifier(q)?.kind ?? null).toBe(kind));+});++describe('textContainsIdentifier', () => {+ const phone = parseIdentifier('415-555-0142')!;+ test('a phone matches every written format and the country code', () => {+ for (const t of ['call (415) 555-0142 now', 'tel: 415.555.0142', '+1 415 555 0142', 'x 4155550142 y', '+14155550142']) {+ expect(textContainsIdentifier(t, phone)).toBe(true);+ }+ });+ test('a phone does not match other digits or a run that merely contains it', () => {+ expect(textContainsIdentifier('id 941555014299 and 0142', phone)).toBe(false);+ expect(textContainsIdentifier('{"a":415,"b":555,"c":142}', phone)).toBe(false);+ });+ test('other identifiers need word boundaries', () => {+ const code = parseIdentifier('INV-2026-00417')!;+ expect(textContainsIdentifier('Invoice INV-2026-00417 paid', code)).toBe(true);+ expect(textContainsIdentifier('XINV-2026-004170', code)).toBe(false);+ expect(textContainsIdentifier('mail [email protected].', parseIdentifier('[email protected]')!)).toBe(true);+ });+ test('the phone keyword query ORs the written forms', () => {+ const q = identifierKeywordQuery(phone);+ expect(q).toContain('4155550142');+ expect(q).toContain('"(415) 555-0142"');+ expect(q).toContain('415.555.0142');+ });+});++describe('identifier probe on PGLite', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ });+ afterAll(async () => {+ await engine.disconnect();+ });+ beforeEach(async () => {+ await resetPgliteState(engine);+ await seedPage(engine, 'notes/vendor-contact', 'Front desk line is (415) 555-0142, ask for the billing team.');+ await seedPage(engine, 'notes/invoice-batch', 'Paid INV-2026-00417 on Friday; INV-2026-00418 pending.');+ await seedPage(engine, 'notes/stats-dump', '{"a":415,"b":555,"c":"0142","d":4155,"e":550142} 415 555 0142 not a phone 9415550142x');+ await seedPage(engine, 'notes/private-contact', 'Home line 415-555-0142.', { frontmatter: { visibility: 'private' } });+ });++ const slugs = async (q: string, excludePrivate = false) => (await structuralExactLookup(engine, q, { excludePrivate })).map(h => h.slug);++ test('a phone in another format finds the page that holds it', async () => {+ expect(await slugs('415-555-0142')).toContain('notes/vendor-contact');+ expect(await slugs('+1 415 555 0142')).toContain('notes/vendor-contact');+ });++ test('every hit is stamped as an identifier lookup', async () => {+ const hits = await structuralExactLookup(engine, '415-555-0142', {});+ expect(hits.every(h => h.exact_lookup === 'identifier')).toBe(true);+ });++ test('a code finds its page and not a page with a neighbouring code', async () => {+ expect(await slugs('INV-2026-00417')).toEqual(['notes/invoice-batch']);+ expect(await slugs('INV-2026-00419')).toEqual([]);+ });++ test('a private page is never injected for a caller that excludes private pages', async () => {+ expect(await slugs('415-555-0142', false)).toContain('notes/private-contact');+ expect(await slugs('415-555-0142', true)).not.toContain('notes/private-contact');+ });++ test('a plain-word query runs no identifier probe', async () => {+ expect(await slugs('billing team')).toEqual([]);+ });+});