Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/master (#7255 visibility hotfix, #7219) into wave-b-pr4: conversation facts from a private page stay private on the segmented incremental and managed publication paths
garrytand7517c0365de
diff --cc scripts/module-size-limits.tsvindex 3832560236,12172132be..f5a4c6ed49--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@@ -6,8 -6,8 +6,8 @@@src/cli/main.ts 3027 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; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured)src/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 692 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.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts)-src/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)+src/commands/embed.ts 2306 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); +1 PR 4 E (gbrain-evals#180): per-page embedding lease import (lease and still-pending filter live in core/page-embedding-lease.ts); +2 PR 4 E round 2 (gbrain-evals#180): a busy lease skips the page and the install renews the lease (logic in core/page-embedding-lease.ts)- src/commands/extract-conversation-facts.ts 1889 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left+ src/commands/extract-conversation-facts.ts 2045 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; +1 GBRA-159: facts from a private page are private (tightenToPage per page; helper in core/facts/visibility.ts)src/commands/extract.ts 2677 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measuredsrc/commands/jobs.ts 667 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts)src/commands/serve-http.ts 937 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts)diff --cc src/commands/extract-conversation-facts.tsindex 594ca59683,6f264d42ad..670617b049--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@@ -101,8 -103,8 +101,8 @@@ import { assertFactsEmbeddingDimMatchesimport { writeReceipt, shortRunId } from '../core/extract/receipt-writer.ts';import { upsertExtractRollup, classifyRunStop } from '../core/extract/rollup-writer.ts';import { ALLOWED_TYPES, ALLOWED_TYPE_ALIASES, isConversationFactsEligiblePage, pageTypesForAllowed, requireParseableConversationFlag, type AllowedType } from '../core/facts/conversation-types.ts';-import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, stampExtractorVersion } from '../core/facts/audit-sources.ts';+import { TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE } from '../core/facts/audit-sources.ts';- import { resolveDefaultVisibility, type FactVisibility } from '../core/facts/visibility.ts';+ import { resolveDefaultVisibility, tightenToPage, type FactVisibility } from '../core/facts/visibility.ts';import {emptySaveTimeResolutionCounts,formatSaveTimeResolutionCounts,diff --cc src/core/behavior-change-notice.tsindex 9296e5eeb4,b018e70b55..f595ef7ac5--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@@ -1054,28 -1054,9 +1054,31 @@@ export const BEHAVIOR_CHANGES: Readonly{ since: '0.60.338.0', text: 'On Postgres, a keyword search whose words match more than 50,000 chunks now ranks the first 50,000 matches that pass its filters instead of all of them, so a common-word query on a large brain returns ranked rows in about a second instead of running into the keyword statement timeout and returning none; hybrid search reports `keyword_candidates_incomplete` when the bound applies. Its any-word retry (after an all-words match finds nothing) now matches only the words the planner statistics say fit about 20,000 chunks, still ranking with every word, and also reports `keyword_candidates_incomplete` when it drops a word.' },{ since: '0.60.338.0', text: 'The keyword arm keeps one chunk per page in its candidate pool (Postgres and PGLite), so a page with hundreds of matching chunks no longer pushes every other matching page out of the results.' },{ since: '0.60.338.0', text: 'The title arm\'s any-word retry (after an all-words title match finds nothing) now matches page titles only, as remote callers already did, and drops repeated words (#7135): a date in a question no longer pulls every dated timeline into ranking, which cut a 3-5 s title arm to well under a second on a large brain. A local all-words title match is unchanged.' },+ // PR 4 E (one provider call per chunk content version, gbrain-evals#180). `since` is stamped at the merge slot.+ { since: 'TBD', text: 'A page\'s new chunks now go to the embedding provider once per content version. The post-write embedding effect, `gbrain embed --stale`, the embed-backfill job and phase-end embeds each hold a per-page lease (a `gbrain_cycle_locks` row named `embed-page:<page id>`, refreshed while held, expiring within 2 minutes after a holder dies) from reading which chunks lack a vector through installing them; a path that reaches a page another path is embedding waits for it, then embeds only the chunks still missing a vector. The wait ends at the caller\'s deadline or after 2 minutes: a stale drain then skips the page (its chunks stay stale for the next run, not counted as a failure) and an embedding effect retries with `lock_busy`. A holder renews the lease inside its install transaction and installs nothing (`lock_busy`) when the lease expired and another path took it; every release deletes the expired `embed-page:` rows a crashed holder left, so doctor `stale_locks` stops listing them after the next embed. Managed-persistence activation, deactivation and shared-skill activation no longer count `embed-page:` rows, live or expired, as legacy locks or blockers. Before, a stale drain that ran while a write\'s embedding effect was in flight sent the same chunks twice (paid twice on a paid provider). Live `embed-page:` rows can show in the `gbrain status` lock list while an embed runs.' },+ // PR 4 recall (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.+ { since: 'TBD', text: 'Pages over 1 MiB (stored in segments) now cut a long passage that has to be split at a sentence or line end, so a sentence the old cut split across two chunks is found whole by keyword and vector search; and their timeline passages break only between bullet entries, at entries chosen by their own text, so an entry added at the top of the timeline re-embeds at most two passages instead of every passage after it. Pages stored before keep serving their chunks: `gbrain reindex --segmented` lists them with the chunk counts that would change and writes nothing; `--apply` re-chunks only the segments that change and keeps the vectors of unchanged chunk texts, and `gbrain embed --stale` embeds the new ones. Nothing re-chunks on upgrade.' },+ // PR 4 4e (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.+ { since: 'TBD', text: 'New transcript sessions import as one page; existing split sessions stop rewriting every part when a session grows. `gbrain transcripts ingest` writes a session with no part pages as one page up to the page ceiling (`pages.max_bytes` or the content-sanity block line, whichever is lower), at its base slug with the same `<id>-p1` identity; only a message or session over that ceiling continues into `-pN` pages. A session already split into parts keeps them and their grouping. The part count left hashed content (titles read `(part X)`, `transcript_import.of` is gone and `part_bytes` records the part size), so each part is rewritten once on its next import; after that a grown session changes only its last part or adds one. Nothing merges a split session into one page. The part size is read only from parts the importer last wrote, so a remote edit of `transcript_import` cannot change how a session splits, and a session that would render over 2,000 parts is reported as an errored session with nothing written.' },+ // PR 4 (Wave B incremental derivation, transcripts)+ // PR 4 4b+ { since: 'TBD', text: 'Appending to a long conversation now re-extracts facts only for the new messages.' },+ { since: 'TBD', text: 'Atom extraction now covers very large pages, and after an append reads only the new text.' },+ { since: 'TBD', text: 'Fact, atom and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, a call the provider may have billed (a timeout, an abort, a dropped connection, a server or gateway error, each retry the provider SDK made) books its worst case, and only one the provider refused outright (a rate limit, an auth or request error, with no usage reported) or a failed embedding books nothing; metered calls, the synopsis step\'s embedding included, turn the SDK\'s hidden retries off. Doctor lists the pages a cap stopped. A model with no price still reserves its ceiling estimate (about one window per page at the default cap; no default changed and no price is assumed), and its receipt now says `unpriced_model` with the model; doctor `derivation_unpriced_model` warns and names the fix, `gbrain pricing set <model> --input <usd> --output <usd>`, which writes `pricing.overrides`.' },+ { since: 'TBD', text: 'A conversation window whose fact extraction fails for a reason of its own (malformed or truncated output, a refusal, input too long) in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted, and the facts it had before stay; provider outages, auth errors and rate limits never count. `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again. Incremental runs on a large conversation page only add or replace facts window by window; facts are removed only when their exact window is extracted again or when a run finishes the whole page with no failed window, no cap, no window limit and no `--since`, which then clears the facts of windows no longer on the page. The page\'s chat format is detected over the whole page (not its first 64 KB) whenever it is not already known; a page that is no longer a transcript (no message parses even in the format it was extracted in) is marked non-extractable and its conversation facts are cleared, even under `--force`. A page whose format is no longer detected over the whole page (text added around the transcript can outweigh its message lines) but whose messages still parse in that format keeps every fact, settles nothing and leaves a `grammar_lost` receipt doctor lists with the fix; a page that reads as a transcript yet parses no message does the same with a `no_messages` receipt. A run settles and clears only if the page is still the version it read when the publication locks it, so a write that lands during the run leaves the page for the next run with every fact kept. Until a run settles, a page can briefly hold more facts than a settled extraction would: a run that stops partway (an abort, a crash, a limit) adds the facts of the windows it finished, and the facts of windows those replaced on the page stay until a later run extracts their exact window again or settles the page.' },+ // PR 4 (Wave B incremental derivation, transcripts) — 4c, contextual synopsis per segment. `since` is restamped at the merge slot.+ { since: 'TBD', text: 'With contextual retrieval set to `per_chunk_synopsis`, a page stored in segments now gets per-chunk synopses instead of staying on the title tier: each chunk\'s synopsis reads the page title, the first 8 KiB of the page and up to 32 KB of its own segment, so the contextual re-embed (`gbrain reindex --markdown` and the per-chunk synopsis backfill) re-synopsizes only the segments an append or edit rewrote and leaves every other chunk\'s vector as it is. The page\'s synopsis cap (`derive.max_usd_per_page`) bounds the synopsis calls: when it is reached, the rest of the page keeps its title-tier vectors (`budget_limited`) and nothing more is spent. A chunk whose synopsis the model refuses is embedded at the title tier. After `gbrain reindex --segmented --apply` re-chunks a page, the next pass synopsizes its new chunks. Pages read whole are unchanged.' },+ // PR 4 (Wave B incremental derivation, transcripts)+ // PR 4 4a+ { since: 'TBD', text: 'Links, mentions, timeline entries and facts/takes fences of a large (segmented) page are now kept per segment, so a write reads only the segments it changed, and an append reads its new tail instead of the whole page. A rewrite of the whole page does the same work as before. The results are unchanged.' },+ { since: 'TBD', text: 'Forgetting, purging or withdrawing a fact on a large page now also deletes the stored link, mention, timeline and fence results of the segment that held it, and of segments an earlier write replaced, in the same transaction. A fact purge also deletes every stored result anywhere in the source that still holds the claim (including a page since stored inline) and counts them as `page_segment_derivations`; stored fence results keep a digest of the fence, never its text. A derivation that read a page before a purge, forget or edit no longer writes its results after it.' },+ { since: 'TBD', text: 'A fact purge now finds stored link, mention, timeline and fence results by the claim\'s normalized form, as its fact fingerprint does, so a result that states the claim in other letter case, spacing or punctuation, or in a script whose lowercase JavaScript and the database spell differently (Greek, Turkish), is deleted and the receipt sees it. The claim must fill whole words of one stored value. Only results of the pages the purge rewrote, and results no live segment backs any more, are searched and deleted; a result of a live segment of another page holds what that page\'s prose still says, and the receipt lists it under `page_segment_derivations` as `out_of_scope` with that prose.' },+ { since: 'TBD', text: 'A fact purge now also finds stored link, mention, timeline and fence results that spell a Greek claim with a final sigma (ς) where the claim has σ or Σ, or the other way round, or a Turkish dotted capital İ the way JavaScript lowercases it (i̇). It normalizes only the results that contain the claim\'s words in order, so the search costs about what the plain substring search did. When that search still runs past the purge transaction\'s statement budget, the purge fails with `purge_lookup_timeout` and nothing is purged, instead of being retried until the transaction gives up.' },+ { since: 'TBD', text: 'A fact purge now searches stored link, mention, timeline and fence results in batches of 500 rows per statement, and its receipt checks them the same way, so a claim whose words appear in tens of thousands of stored results can be purged instead of always failing with `purge_lookup_timeout`. The purge still commits all at once. It fails with `purge_lookup_timeout`, purging nothing, only when the search runs past two minutes.' },+ { since: 'TBD', text: 'A fact purge no longer searches stored link, mention, timeline and fence results inside its transaction, so other writes to the source are no longer blocked while it walks them. The purge records the claim and commits; it then deletes the results holding the claim in batches of 500 stored results, each in a short transaction of its own, for up to two minutes. From the commit on, a result holding the claim cannot be written back into what the purge covers. When the walk does not finish in that time, the purge still commits, but its receipt reports `page_segment_derivations` as `incomplete`, `completion: incomplete` (exit 75) and `derivation_sweep: pending`. Running the same purge again with its request id, or purging another fact in the source, continues from where the walk stopped. The walk no longer fails a purge with `purge_lookup_timeout` (this replaces the two-minute failure above).' },+ // GBRA-159 visibility hotfix.+ { since: '0.60.341.0', text: 'Nothing derived from a private page is stored wider than the page. Facts extracted from a `visibility: private` page are private even when `facts.default_visibility` is world (before, a fact with no fence page was then returned to remote callers by recall and the entity card), and a page marked private only by `access: private|restricted|confidential` or `confidentiality: confidential|secret|private|restricted` counts as private for its facts, chronicle events, timeline rows and remember saves. `remember` without a `visibility` now saves private when its target page is private or `facts.default_visibility` is explicitly private; otherwise the default stays world. Google Calendar events marked private or confidential sync as `visibility: private` pages, and a connector re-render keeps a page\'s private label. Remote page reads honor the privacy aliases only after `gbrain config set visibility.honor_aliases true`.' },+ { since: '0.60.341.0', text: 'Doctor `derived_visibility` also reports pages that carry a privacy alias but no `visibility`, chronicle events of a private origin, and world facts held in or extracted from a private page (fact ids a remote caller can read today are listed). `gbrain repair visibility` previews all of them and, with `--apply` only, makes them private; nothing runs on upgrade.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --cc src/core/facts/conversation-incremental.tsindex 467cab7589,0000000000..9cedf2a24amode 100644,000000..100644--- a/src/core/facts/conversation-incremental.ts+++ b/src/core/facts/conversation-incremental.ts@@@ -1,423 -1,0 +1,424 @@@+/**+ * Incremental conversation facts for a segmented page (wave-b spec 8.1, 8.2 "Conversation facts", 8.3; PR 4 lane 4b).+ *+ * Windows run over message boundaries across occurrences (conversation-stream.ts), so a window can span a segment cut;+ * each window belongs to the occurrence its first message starts in. Each window's facts carry its key in+ * facts.source_window (owner occurrence, ordinal, rendered-text sha). Per occurrence, a page_segment_derivations row+ * (kind conversation_facts) records the segment sha, a context hash (every page-level input the windows depend on:+ * title, gap setting, date context, extraction model, effective fact visibility), the windows whose facts it holds+ * (ordinal, sha, facts), its predecessor, whether its first message opens a gap group, the page's grammar, and the+ * failed attempts of windows not extracted yet.+ *+ * Deletion invariant. A run deletes a conversation fact in exactly two ways:+ * (a) replacement: the fact's exact window key was extracted again in this run (or, for a move, the same rendered+ * window's standing facts were re-anchored onto it), and its old facts give way in the transaction that adds the+ * new ones;+ * (b) collection at a fully settled run: every current window holds its facts (extracted or reused), none is failed,+ * no cap or --segment-limit stopped the run, no --since filter applied and the page did not change underneath;+ * only then does every fact whose window key is not a current window's (and every unanchored fact of an older+ * full-pass run) go.+ * Every other run (interrupted, capped, limited, failed, --since, or with a failed window anywhere on the page) only+ * adds and replaces. A row claims exactly the window keys whose facts it holds: a window moved to another occurrence is+ * dropped from its old row in the transaction that re-anchors its facts. Purge and forget run separately and win.+ *+ * A run:+ * - finds the first occurrence that is new, rewritten, moved or context-changed and streams the windows from the+ * nearest earlier occurrence that opens a gap group (the windows before it cannot change), one segment at a time+ * and in runs, newest run first, so a stop reads only the runs it reached; a page nothing changed on reads nothing;+ * - parses under the page's grammar: the one detectPagePattern picks over the whole page (the whole-page pass's+ * choice; one unpaid read, counted in conversationDetectionWork), pinned on the rows while the occurrences that+ * recorded it under the same context are mostly unchanged by bytes; a page with no grammar is not a conversation: it settles as+ * non-extractable and its conversation facts are collected; a pinned grammar under which nothing parses is detected+ * again; a detected grammar under which nothing parses leaves a no_messages receipt and changes nothing;+ * - reuses every window an earlier run extracted with the same rendered text under the same context (re-anchored+ * when it moved), so an append extracts only its new windows and the one it grew;+ * - extracts the rest newest first, each call metered against the page's facts cap (meterPaidCall), and publishes+ * every CONVERSATION_FACTS_CHECKPOINT_WINDOWS windows, when it stops and when a window throws or the run aborts;+ * - counts a window whose extraction fails for a reason of its own (malformed or truncated output, a refusal or+ * content filter, a provider refusal of the window's own input; never a transport, provider, auth, rate-limit, 5xx,+ * timeout or abort failure) against it across runs; the run stops there, and once a window has failed+ * WINDOW_FAILURE_LIMIT runs it is marked failed (a failed_windows receipt doctor lists) and the run moves on; the+ * page is then stamped done but never collected until a --force run (retryFailed) extracts it.+ * A title or gap change re-extracts every window (documented cost); a no-op rewrite extracts nothing. Unmanaged brains+ * only: a managed brain keeps the receipted whole-page publication.+ */+import type { BrainEngine } from '../engine.ts';+import type { Page } from '../types.ts';+import { deriveDateContext } from '../conversation-parser/parse.ts';+import { loadPricingOverrides, type PricingOverrides } from '../budget/budget-tracker.ts';+import { providerItemRefusal } from '../ai/errors.ts';+import { writeDerivedFacts } from '../persistence/derived-facts.ts';+import { estimateFactsExtractionUsd, meterPaidCall, unpricedModelReceipt } from '../page-embedding-budget.ts';+import { setExtractionReceipt } from '../extraction-watermark.ts';+import { planSegmentDerivations, segmentDerivationContextHash, sourceWindowFor, sourceWindowKey, type SegmentDerivationInput,+ type SegmentDerivationRow, type SourceWindow } from '../page-body/derivations.ts';+import { conversationDetectionWork, readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';+import { emptySaveTimeResolutionCounts, mergeSaveTimeResolutionCounts } from '../entities/resolve-on-save.ts';+import { conversationEntityHints } from './conversation-entity-hints.ts';+import { countConversationFacts, countWindowFacts, publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';+import { recordFailedPage } from './conversation-run-status.ts';+import { detectPagePattern, startsConversationRun, streamConversationWindows } from './conversation-stream.ts';+import type { ConversationSegment } from './conversation-types.ts';+import { renderSegmentForExtraction } from './conversation-windows.ts';+import { extractConversationWindow, nonExtractableAuditFact, regularPageVersionToken, terminalAuditFact, type ConversationWindowRun } from './conversation-window-extract.ts';+import { getFactsExtractionMaxTokens, resolveFactsExtractionModel, type ExtractInput } from './extract.ts';- import type { FactVisibility } from './visibility.ts';++import { tightenToPage, type FactVisibility } from './visibility.ts';++const KIND = 'conversation_facts';+/** Bump when the windowing or the row output changes shape: every occurrence is extracted again once. */+export const CONVERSATION_FACTS_DERIVATION_VERSION = 3;+/** Windows extracted between two publications of a page's facts and rows. */+export const CONVERSATION_FACTS_CHECKPOINT_WINDOWS = 8;+/**+ * Runs in which one window's extraction may throw before it is marked failed and skipped. extract.ts already retries a+ * truncated or malformed answer inside one run, so a window that still throws in three separate runs fails for a reason+ * of its own; three bounds what a doomed window costs at three reservations.+ */+export const WINDOW_FAILURE_LIMIT = 3;++/** The run counters this pass moves (a subset of ExtractConversationFactsResult). */+export interface SegmentedConversationCounters {+ pages_considered: number; pages_processed: number; pages_skipped: number; pages_skipped_insufficient_turns: number;+ pages_marked_non_extractable: number; pages_failed: number; segments_processed: number; facts_extracted: number;+ facts_inserted: number; orphan_facts_cleaned: number; fallback_slugify_count: number; resolution_errors: number;+ failed_pages: Array<{ slug: string; error: string }>;+}++export interface SegmentedConversationRun extends ConversationWindowRun {+ result: SegmentedConversationCounters;+ dryRun: boolean;+ sleepMs: number;+ /** At most this many windows per page per run (0: no limit). */+ segmentLimit: number;+}++/** A window an occurrence row holds the facts of: ordinal, rendered-text sha, facts its key holds, and why it failed when it did. */+interface WindowRecord { ordinal: number; sha: string; facts: number; failed?: WindowFailure }+/** Failed extraction attempts of one window (by rendered-text sha) and the last error. */+interface WindowFailure { attempts: number; error: string }+interface RowOutput { windows: WindowRecord[]; starts_group?: boolean; prev?: number | null; pattern?: string | null; retries?: Array<{ sha: string } & WindowFailure> }+/** One window of the stream: `reused` (an earlier run's facts stand), `todo`, `extracted` by this run, or `failed` past the limit. */+interface StreamWindow { owner: number; seg: ConversationSegment; text: string | null; window: SourceWindow;+ state: 'reused' | 'todo' | 'extracted' | 'failed'; facts: number; failed?: WindowFailure }+type Stop = 'segment_limit' | 'cap_reached' | 'interrupted' | null;++/** The bounded output a conversation_facts row stores (window anchors and counts; never text). */+function rowOutput(row: SegmentDerivationInput | undefined): RowOutput {+ const output = row?.output as Partial<RowOutput> | null | undefined;+ return { windows: Array.isArray(output?.windows) ? output.windows : [], starts_group: output?.starts_group, prev: output?.prev,+ pattern: output?.pattern ?? null, retries: Array.isArray(output?.retries) ? output.retries : [] };+}++const keyOf = (occurrenceId: number, w: WindowRecord) => sourceWindowKey({ occurrence_id: occurrenceId, window_ordinal: w.ordinal, window_text_sha: w.sha });+const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');++/** Every page-level input the windows depend on: the context hash. */+async function conversationContext(engine: BrainEngine, page: Page, gapMinutes: number | null, visibility: FactVisibility) {+ const dates = deriveDateContext({ page });+ const model = (await resolveFactsExtractionModel(engine)).model;+ return { model, inputs: { title: page.title || page.slug, gap_minutes: gapMinutes, date: dates.fallbackDate, timezone: dates.timezone ?? null, model, visibility } };+}++/** extract.ts failure reasons caused by the window itself (its output or its content), which repeat until it changes. */+const WINDOW_SPECIFIC_REASONS: ReadonlySet<string> = new Set(['malformed_output', 'truncated_output', 'refusal', 'content_filter']);++/**+ * Whether a window's extraction error counts against the window: a failure of the window's own (WINDOW_SPECIFIC_REASONS,+ * or a provider refusal of its own input such as a context-length error). A transport, provider, auth, rate-limit,+ * 5xx, timeout or abort failure, a cap, or an error with no extraction reason never counts.+ */+function windowFailure(error: unknown, signal: AbortSignal | undefined): boolean {+ if (signal?.aborted) return false;+ const reason = (error as { extractionReason?: unknown } | null)?.extractionReason;+ if (typeof reason !== 'string') return false;+ if (WINDOW_SPECIFIC_REASONS.has(reason)) return true;+ return reason === 'provider_error' && providerItemRefusal((error as { cause?: unknown }).cause) !== null;+}++/**+ * One segmented page's conversation facts, incrementally (module doc). `gapMinutes` is the page's own+ * conversation_segment_gap_minutes (null: the default). Returns the end of the newest window it extracted.+ */+export async function processSegmentedConversationPage(run: SegmentedConversationRun, page: Page,+ opts: { gapMinutes: number | null; sinceIso?: string; retryFailed?: boolean; redetect?: boolean }): Promise<{ newestEnd: string | null }> {+ const { engine, sourceId, result } = run;+ if (!opts.redetect) result.pages_considered++;+ const versionToken = regularPageVersionToken(page);- const { model, inputs } = await conversationContext(engine, page, opts.gapMinutes, run.factVisibility);++ const factVisibility = tightenToPage(run.factVisibility, page);++ const { model, inputs } = await conversationContext(engine, page, opts.gapMinutes, factVisibility);+ const contextHash = segmentDerivationContextHash(KIND, { entryState: null, page: inputs });+ const { body, occurrences } = await readConversationOccurrences(engine, page.id);+ const live = occurrences.map(o => ({ occurrenceId: o.row.occurrenceId, sha256: o.row.sha256, contextHash }));+ const liveIds = live.map(segment => segment.occurrenceId);+ const prior = await engine.readSegmentDerivations(page.id, { kind: KIND });+ const plan = planSegmentDerivations(KIND, CONVERSATION_FACTS_DERIVATION_VERSION, live, prior);+ const priorRow = new Map(prior.map(row => [row.occurrenceId, row]));+ const current = new Set(plan.current.map(row => row.occurrenceId));+ const sameContext = (row: SegmentDerivationRow) => row.version === CONVERSATION_FACTS_DERIVATION_VERSION && hex(row.contextHash) === hex(contextHash);+ const prevOf = (i: number) => (i === 0 ? null : liveIds[i - 1]!);+ const intact = (i: number) => {+ const output = rowOutput(priorRow.get(liveIds[i]!));+ return current.has(liveIds[i]!) && (output.prev ?? null) === prevOf(i) && !(opts.retryFailed && output.windows.some(w => w.failed));+ };+ // The first occurrence whose windows may have changed (one past the last when only trailing occurrences left), and+ // the nearest earlier occurrence that opens a gap group: the stream starts there.+ let first = liveIds.findIndex((_, i) => !intact(i));+ if (first < 0) first = plan.retired.length ? liveIds.length : -1;+ let from = first < 0 ? liveIds.length : 0;+ for (let i = Math.min(first, liveIds.length) - 1; i > 0; i--) {+ if (intact(i) && rowOutput(priorRow.get(liveIds[i]!)).starts_group === true) { from = i; break; }+ }+ const position = new Map(liveIds.map((id, i) => [id, i]));+ // The grammar: pinned while the occurrences whose rows recorded it under this context are, by bytes, mostly unchanged+ // (an append or an edit keeps it; a re-import does not), else detected over the whole page.+ const liveOccurrence = new Map(occurrences.map(o => [o.row.occurrenceId, o.row]));+ const recorded = prior.filter(row => sameContext(row) && liveOccurrence.has(row.occurrenceId) && rowOutput(row).pattern);+ const kept = recorded.filter(row => hex(liveOccurrence.get(row.occurrenceId)!.sha256) === hex(row.segmentSha256));+ const bytesOf = (rows: SegmentDerivationRow[]) => rows.reduce((n, row) => n + liveOccurrence.get(row.occurrenceId)!.byteLen, 0);+ let pattern = !opts.redetect && kept.length && 2 * bytesOf(kept) > bytesOf(recorded) ? rowOutput(kept[0]).pattern ?? null : null;+ const pinned = pattern !== null;+ const detectedBytes = conversationDetectionWork.bytes;+ if (!pattern && from < liveIds.length) pattern = await detectPagePattern(occurrences, i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }));+ if (!pattern && from < liveIds.length) {+ if (opts.sinceIso) { result.pages_skipped++; return { newestEnd: null }; }+ // No grammar over the whole page. Only a page that holds no window or fact, or that parses no message under the+ // grammar it was extracted in either, has stopped being a transcript (it settles as non-extractable below and its+ // facts are collected); one that still does (prose added around the transcript can tip the density test) keeps+ // everything and settles nothing.+ const recordedGrammar = prior.map(row => rowOutput(row).pattern).find(Boolean) ?? null;+ const holds = prior.some(row => rowOutput(row).windows.length > 0) || await countConversationFacts(engine, sourceId, page.slug, { active: true }) > 0;+ let still = holds && !recordedGrammar ? null : 0;+ if (holds && recordedGrammar) {+ still = (await streamConversationWindows(occurrences, 0, liveIds.length, { page, gapMinutes: opts.gapMinutes, pattern: recordedGrammar },+ i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }), { window() {}, occurrence() {} })).messages;+ }+ if (still !== 0) {+ await setExtractionReceipt(engine, page.id, KIND, { kind: 'grammar_lost', pipeline: KIND, processed_chars: 0, ...(recordedGrammar ? { pattern: recordedGrammar } : {}),+ ...(still !== null ? { messages: still } : {}) });+ const why = recordedGrammar ? `no chat format is detected over the page any more, yet ${still} message(s) still parse as ${recordedGrammar}`+ : 'no chat format is detected over the page, which holds conversation facts from a run that recorded none';+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${why}; its facts were kept, nothing settled; gbrain doctor lists it\n`);+ result.pages_failed++;+ recordFailedPage(result, page.slug, `${why}; facts kept`);+ return { newestEnd: null };+ }+ from = 0;+ }+ // Earlier windows of the occurrences the stream covers (and of retired ones), reusable by rendered text under the same context.+ const reusable = new Map<string, Array<{ occurrenceId: number; record: WindowRecord }>>();+ const failures = new Map<string, WindowFailure>();+ for (const row of prior) {+ if ((position.get(row.occurrenceId) ?? Infinity) < from || !sameContext(row)) continue;+ const output = rowOutput(row);+ for (const record of output.windows) {+ if (!(record.failed && opts.retryFailed)) reusable.set(record.sha, [...(reusable.get(record.sha) ?? []), { occurrenceId: row.occurrenceId, record }]);+ }+ if (!opts.retryFailed) for (const { sha, attempts, error } of output.retries ?? []) failures.set(sha, { attempts, error });+ }+ const windows: StreamWindow[] = [];+ const pendingMoves: Array<{ from: string; to: SourceWindow }> = [];+ /** Window keys moved off each occurrence's row since the last publication. */+ const movedOff = new Map<number, Set<string>>();+ const rowsNow = new Map<number, SegmentDerivationInput>(prior.map(row => [row.occurrenceId, row]));+ const startsGroup = new Map<number, boolean>();+ const ordinals = new Map<number, number>();+ const pageTitle = page.title || page.slug;+ const streamOpts = { page, gapMinutes: opts.gapMinutes, sinceIso: opts.sinceIso, pattern };+ let parsedMessages = 0;+ const texts = new Map<number, string>();+ const readText = async (i: number) => {+ const cached = texts.get(i);+ if (cached !== undefined) return cached;+ const text = await readOccurrenceText(engine, body, occurrences[i]!.row);+ texts.set(i, text);+ return text;+ };+ /** Stream the newest run not streamed yet: from the nearest occurrence before `end` whose first message opens a gap group (module doc). */+ const streamRun = async (end: number): Promise<{ start: number; windows: StreamWindow[] }> => {+ let start = end - 1;+ while (start > from && !startsConversationRun(occurrences, start, await readText(start), await readText(start - 1), streamOpts)) start--;+ const runWindows: StreamWindow[] = [];+ const streamed = await streamConversationWindows(occurrences, start, end, streamOpts, readText, {+ window(index, seg) {+ const owner = liveIds[index]!;+ const ordinal = ordinals.get(owner) ?? 0;+ ordinals.set(owner, ordinal + 1);+ const text = renderSegmentForExtraction(pageTitle, seg);+ const window = sourceWindowFor(owner, ordinal, text);+ // The same window's own record first, else any record of the same text (the window moved).+ const candidates = reusable.get(window.window_text_sha) ?? [];+ const own = candidates.findIndex(c => c.occurrenceId === owner && c.record.ordinal === ordinal);+ const hit = candidates.splice(own < 0 ? 0 : own, 1)[0];+ if (!hit) { runWindows.push({ owner, seg, text, window, state: 'todo', facts: 0 }); return; }+ const was = keyOf(hit.occurrenceId, hit.record);+ if (was !== sourceWindowKey(window)) {+ pendingMoves.push({ from: was, to: window });+ movedOff.set(hit.occurrenceId, new Set([...(movedOff.get(hit.occurrenceId) ?? []), was]));+ }+ runWindows.push({ owner, seg, text: null, window, state: hit.record.failed ? 'failed' : 'reused', facts: hit.record.facts, failed: hit.record.failed });+ },+ occurrence(index, starts) { startsGroup.set(liveIds[index]!, starts); },+ });+ parsedMessages += streamed.messages;+ for (const i of [...texts.keys()]) if (i > start) texts.delete(i);+ windows.unshift(...runWindows);+ return { start, windows: runWindows };+ };+ if (run.dryRun) {+ let todo = 0;+ for (let end = liveIds.length; pattern && end > from;) { const next = await streamRun(end); todo += next.windows.filter(w => w.state === 'todo').length; end = next.start; }+ result.segments_processed += run.segmentLimit > 0 ? Math.min(todo, run.segmentLimit) : todo;+ result.pages_processed++;+ return { newestEnd: null };+ }++ const resolution = emptySaveTimeResolutionCounts();+ let streamedFrom = pattern ? liveIds.length : from;+ let stop: Stop = null;+ let unpricedModel: string | null = null;+ let newestEnd: string | null = null;+ let extracted = 0;+ let batch: { rows: ConversationFactRow[]; windows: SourceWindow[]; keys: string[] } = { rows: [], windows: [], keys: [] };+ /**+ * Publish the facts extracted since the last publication and the rows of the streamed occurrences; `final` settles a+ * finished page, but only if the page is still the version the run read, checked under the publication's row lock on+ * the page (a write that commits after the check waits for the publication; one that committed before is seen).+ */+ const publish = async (final: boolean) => {+ const owned = new Map<number, StreamWindow[]>();+ for (const w of windows) owned.set(w.owner, [...(owned.get(w.owner) ?? []), w]);+ // Rows of the occurrences this run streamed; an occurrence it never reached keeps its row.+ const derived: SegmentDerivationInput[] = liveIds.slice(streamedFrom).map((occurrenceId, k) => {+ const mine = owned.get(occurrenceId) ?? [];+ const records: WindowRecord[] = mine.filter(w => w.state !== 'todo').map(w => ({ ordinal: w.window.window_ordinal, sha: w.window.window_text_sha,+ facts: w.facts, ...(w.failed && w.state === 'failed' ? { failed: w.failed } : {}) }));+ const retries = mine.flatMap(w => { const failure = w.state === 'todo' ? failures.get(w.window.window_text_sha) : undefined; return failure ? [{ sha: w.window.window_text_sha, ...failure }] : []; });+ const failed = records.filter(r => r.failed).map(r => ({ ordinal: r.ordinal, attempts: r.failed!.attempts, error: r.failed!.error }));+ const finished = records.length === mine.length;+ return { pageId: page.id, kind: KIND, occurrenceId, version: CONVERSATION_FACTS_DERIVATION_VERSION, segmentSha256: live[streamedFrom + k]!.sha256,+ contextHash, state: finished && !opts.sinceIso ? 'done' : 'partial',+ output: { windows: records, starts_group: startsGroup.get(occurrenceId) ?? false, prev: prevOf(streamedFrom + k), pattern, ...(retries.length ? { retries } : {}) },+ receipt: !finished ? unpricedModelReceipt(KIND, unpricedModel, stop ?? 'in_progress', { windows_read: records.length, windows_total: mine.length })+ : failed.length ? { kind: 'failed_windows', pipeline: KIND, windows: failed } : unpricedModelReceipt(KIND, unpricedModel, null, null) };+ });+ // A row whose window moved to another occurrence stops claiming it in the transaction that re-anchors its facts.+ const rewritten = new Set(derived.map(row => row.occurrenceId));+ const released: SegmentDerivationInput[] = [...movedOff].flatMap(([occurrenceId, keys]) => {+ const row = rowsNow.get(occurrenceId);+ if (!row || rewritten.has(occurrenceId)) return [];+ const output = rowOutput(row);+ return [{ ...row, output: { ...(row.output as object), windows: output.windows.filter(w => !keys.has(keyOf(occurrenceId, w))) } }];+ });+ const settledWindows = [...liveIds.slice(0, from).flatMap(id => rowOutput(priorRow.get(id)).windows.map(w => ({ key: keyOf(id, w), failed: !!w.failed }))),+ ...windows.map(w => ({ key: sourceWindowKey(w.window), failed: w.state === 'failed' }))];+ const moves = [...pendingMoves];+ const out = await writeDerivedFacts(engine, sourceId, page.slug, async db => {+ let unchanged = true;+ if (final) {+ await db.executeRaw('SELECT id FROM pages WHERE id = $1 FOR UPDATE', [page.id]);+ const now = await db.getPage(page.slug, { sourceId });+ unchanged = !!now && now.id === page.id && regularPageVersionToken(now) === versionToken;+ }+ const settled = final && unchanged && stop === null && !opts.sinceIso && streamedFrom <= from;+ const liveKeys = settled ? settledWindows.map(w => w.key) : null;+ const collect = settled && !settledWindows.some(w => w.failed);+ const outcome = !liveKeys ? null : liveKeys.length ? terminalAuditFact(page.slug, 0, versionToken)+ : nonExtractableAuditFact(page.slug, 0, versionToken, pattern ? 'fewer than two eligible messages' : 'no conversation messages found');+ const published = await publishConversationFacts(db, sourceId, page.slug, outcome ? [...batch.rows, outcome] : batch.rows,+ { scope: 'window', segments: { windows: batch.windows, moves, replace: batch.keys, live: collect ? liveKeys : null } });+ if (derived.length || released.length) await db.upsertSegmentDerivations([...derived, ...released]);+ if (settled) await db.retireSegmentDerivations(page.id, liveIds, { kind: KIND });+ return { ...published, unchanged, settled, liveKeys, outcome };+ });+ const { unchanged, settled, liveKeys, outcome } = out;+ pendingMoves.splice(0, moves.length);+ movedOff.clear();+ for (const row of [...derived, ...released]) rowsNow.set(row.occurrenceId, row);+ batch = { rows: [], windows: [], keys: [] };+ result.facts_inserted += out.facts_inserted;+ result.orphan_facts_cleaned += out.deleted;+ return { unchanged, settled, liveKeys, outcome };+ };++ const maxTokens = await getFactsExtractionMaxTokens(engine);+ let paid: { pricingOverrides: PricingOverrides | undefined; entityHints: ExtractInput['entityHints'] } | null = null;+ try {+ // Newest runs first, and newest windows first inside each, so a cap or a limit spends on the newest messages.+ for (let end = liveIds.length; pattern && end > from && !stop;) {+ const next = await streamRun(end);+ streamedFrom = end = next.start;+ for (const w of next.windows.filter(x => x.state === 'todo').reverse()) {+ if (run.segmentLimit > 0 && extracted >= run.segmentLimit) { stop = 'segment_limit'; break; }+ if (run.signal?.aborted) throw new Error('aborted');- paid ??= { pricingOverrides: await loadPricingOverrides(engine), entityHints: await conversationEntityHints(engine, sourceId, page.slug, run.factVisibility) };++ paid ??= { pricingOverrides: await loadPricingOverrides(engine), entityHints: await conversationEntityHints(engine, sourceId, page.slug, factVisibility) };+ const { pricingOverrides, entityHints } = paid;+ const text = w.text!;+ const sha = w.window.window_text_sha;+ let metered: Awaited<ReturnType<typeof meterPaidCall<Awaited<ReturnType<typeof extractConversationWindow>>>>>;+ try {+ metered = await meterPaidCall(engine, page, `facts:${model}`, estimateFactsExtractionUsd(model, text.length, maxTokens, pricingOverrides),+ () => extractConversationWindow(run, page, w.seg, text, 0, entityHints), { pricingOverrides });+ } catch (error) {+ if (!windowFailure(error, run.signal)) throw error;+ const failure = { attempts: (failures.get(sha)?.attempts ?? 0) + 1, error: (error instanceof Error ? error.message : String(error)).slice(0, 200) };+ failures.set(sha, failure);+ if (failure.attempts < WINDOW_FAILURE_LIMIT) throw error;+ failures.delete(sha);+ // A failed window keeps whatever facts its key still holds (an earlier context's), and its row claims them.+ Object.assign(w, { state: 'failed', failed: failure, facts: await countWindowFacts(engine, sourceId, page.slug, sourceWindowKey(w.window)), text: null });+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: window ${w.window.window_ordinal} of occurrence ${w.owner} failed ${failure.attempts} runs (${failure.error}); skipped, gbrain doctor lists it, --force retries it\n`);+ continue;+ }+ unpricedModel = metered.unpricedModel ?? unpricedModel;+ if ('refused' in metered) { stop = 'cap_reached'; break; }+ const out = metered.value;+ w.state = 'extracted';+ w.facts = out.extracted;+ w.text = null;+ extracted++;+ result.segments_processed++;+ result.facts_extracted += out.extracted;+ mergeSaveTimeResolutionCounts(resolution, out.resolution);+ for (const row of out.rows) { batch.rows.push(row); batch.windows.push(w.window); }+ batch.keys.push(sourceWindowKey(w.window));+ if (!newestEnd || w.seg.endIso > newestEnd) newestEnd = w.seg.endIso;+ if (batch.keys.length >= CONVERSATION_FACTS_CHECKPOINT_WINDOWS) await publish(false);+ if (run.sleepMs > 0) await new Promise(resolve => setTimeout(resolve, run.sleepMs));+ }+ }+ } catch (error) {+ stop = 'interrupted';+ await publish(false).catch(publishError => {+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: could not publish the finished windows: ${publishError instanceof Error ? publishError.message : String(publishError)}\n`);+ });+ throw error;+ } finally {+ result.fallback_slugify_count += resolution.fallback_slugify_count;+ result.resolution_errors += resolution.resolution_errors;+ }++ if (pattern && from < liveIds.length && parsedMessages === 0) {+ // A pinned grammar reads nothing here: detect the page's grammar again and start over under it.+ if (pinned) return processSegmentedConversationPage(run, page, { ...opts, redetect: true });+ // The grammar detected over the whole page reads no message from the page: a parser fault. Nothing is published.+ await setExtractionReceipt(engine, page.id, KIND, { kind: 'no_messages', pipeline: KIND, processed_chars: 0 });+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: the page reads as ${pattern} but no message parsed under it; its facts were kept, nothing settled\n`);+ result.pages_failed++;+ recordFailedPage(result, page.slug, `the page reads as ${pattern} but no message parsed under it; facts kept`);+ return { newestEnd: null };+ }+ const { unchanged, settled, liveKeys, outcome } = await publish(true);+ await setExtractionReceipt(engine, page.id, KIND, null);+ if (!unchanged) {+ process.stderr.write(`[extract-conversation-facts] ${page.slug} changed during extraction; its finished windows were kept, the rest wait for the next run\n`);+ result.pages_failed++;+ recordFailedPage(result, page.slug, 'the page changed during extraction; left unfinished for replay');+ return { newestEnd: null };+ }+ if (outcome && !liveKeys!.length) { result.pages_skipped++; result.pages_skipped_insufficient_turns++; result.pages_marked_non_extractable++; }+ else result.pages_processed++;+ const detected = conversationDetectionWork.bytes - detectedBytes;+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${extracted} new window(s) of ${windows.length} streamed from occurrence ${streamedFrom + 1} of ${liveIds.length}`+ + `${detected ? `; grammar ${pattern ?? 'none'} detected over ${detected} bytes` : ''}${stop ? `; stopped: ${stop}` : settled ? '; settled' : ''}\n`);+ return { newestEnd };+}diff --cc src/core/facts/conversation-publication.tsindex d9309cb642,afb2382221..bd2ffb4f38--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@@ -77,6 -77,6 +77,7 @@@ import { withWriteTrust } from '../persimport { conversationDerivation } from '../persistence/derived-facts.ts';import { RELINKED_DERIVED_ROW, inheritRelinkedEntities } from './conversation-relink-carry.ts';import { recordReextractMemo } from './conversation-memo.ts';++import { tightenToPage } from './visibility.ts';import { recordTaintEdges } from '../trust/taint.ts';import { applyGateDecision, derivedGateConfig, derivedGateInput } from '../trust/derived-gate.ts';import { decideFactWrite, recordFlaggedRow } from '../write-gate-store.ts';@@@ -806,7 -740,7 +807,7 @@@ export async function enqueueManagedPagrows: ConversationFactRow[], newestEnd: string | null, scope: ConversationScope): Promise<void> {const m = state.managed!;await enqueueEntry(state, await buildConversationPage(m.engine, m.config, { slug: snapshot.page.slug, generation: start.generation, attempt: start.attempt,-- versionToken: snapshot.versionToken, since: start.since, segmentLimit: state.segmentLimit, scope }, rows, { newestEnd, visibility: state.factVisibility }));++ versionToken: snapshot.versionToken, since: start.since, segmentLimit: state.segmentLimit, scope }, rows, { newestEnd, visibility: tightenToPage(state.factVisibility, snapshot.page) }));}async function enqueueEntry(state: ManagedRunState, entry: ConversationPageEntry): Promise<void> {diff --cc src/core/facts/conversation-window-extract.tsindex 3e77419b18,0000000000..d4aff35a69mode 100644,000000..100644--- a/src/core/facts/conversation-window-extract.ts+++ b/src/core/facts/conversation-window-extract.ts@@@ -1,156 -1,0 +1,157 @@@+/**+ * One conversation window through the extractor (extract-conversation-facts, #6267 windows): the model call (or the+ * injected extractor), save-time entity resolution and subject inference, and the fact rows the page publishes. Shared+ * by the command's whole-page pass and the segmented page's per-occurrence pass (conversation-incremental.ts), with the+ * page outcome rows both publish and the parser-input version token they bind to.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine, NewFact } from '../engine.ts';+import type { Page } from '../types.ts';+import { observationDateFrom, resolveObservationDate, type ObservationDate } from '../ai/date-grounding.ts';+import { BudgetExhausted } from '../budget/budget-tracker.ts';+import { deriveDateContext } from '../conversation-parser/parse.ts';+import { resolveExtractedEntitiesForSave, type SaveTimeResolutionCounts } from '../entities/resolve-on-save.ts';+import { NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE, stampExtractorVersion } from './audit-sources.ts';+import { CONVERSATION_ENTITY_HINTS_CAP } from './conversation-entity-hints.ts';+import { CONVERSATION_FACTS_SOURCE_PREFIX, type ConversationFactRow } from './conversation-publication.ts';+import { inferConversationSubjects } from './conversation-subject-infer.ts';+import type { ConversationSegment } from './conversation-types.ts';+import { extractFactsFromTurnWithOutcome, type ExtractInput, type ExtractedFact } from './extract.ts';- import type { FactVisibility } from './visibility.ts';++import { tightenToPage, type FactVisibility } from './visibility.ts';++/** What one window's extraction needs from the run. */+export interface ConversationWindowRun {+ engine: BrainEngine;+ sourceId: string;+ factVisibility: FactVisibility;+ signal: AbortSignal | undefined;+ /** Injected per-segment extractor (BrainBench decision 15); undefined runs the production fail-hard extractor. */+ extractor?: (input: ExtractInput) => Promise<ExtractedFact[]>;+}++/**+ * A conversation fact's valid_from: a validated event date the extractor+ * stated (date-grounding variant) wins; else the segment start, except the+ * epoch fallback (no trustworthy date → the insert's now() default).+ */+function segmentValidFrom(extracted: Date | undefined, startIso: string | undefined): { valid_from?: Date } {+ if (extracted) return { valid_from: extracted };+ return startIso && !startIso.startsWith('1970-') ? { valid_from: new Date(startIso) } : {};+}++/**+ * Observation date of a conversation segment (date-grounding.ts): the+ * segment's own timestamp when it came from the transcript itself or the+ * page's frontmatter date — never the synthetic epoch fallback, and never a+ * timestamp the parser derived from effective_date (which may be an event+ * date). Otherwise the page's observation date, or null (unknown).+ */+export function segmentObservationDate(page: Pick<Page, 'slug' | 'frontmatter' | 'effective_date'>, startIso: string | undefined): ObservationDate | null {+ const day = startIso?.slice(0, 10);+ const context = deriveDateContext({ page: page as Page });+ const explicit = !!day && !day.startsWith('1970-')+ && (context.source === 'explicit' || context.source === 'frontmatter_date' || day !== context.fallbackDate);+ return explicit ? observationDateFrom(startIso) : resolveObservationDate({ slug: page.slug, frontmatter: page.frontmatter });+}++/**+ * Extract one rendered window. The production path is fail-hard with a reason: a failed window aborts the page rather+ * than dropping facts, and BudgetExhausted is rethrown unwrapped (#3669) so the run halts with a budget receipt.+ * Rows are numbered from `rowNum`; publication renumbers them under the page lock.+ */+export async function extractConversationWindow(run: ConversationWindowRun, page: Page, seg: ConversationSegment, text: string, rowNum: number,+ entityHints: ExtractInput['entityHints']): Promise<{ extracted: number; rows: ConversationFactRow[]; resolution: SaveTimeResolutionCounts }> {+ const sessionId = `${CONVERSATION_FACTS_SOURCE_PREFIX}:${page.slug}`;+ let extracted: ExtractedFact[];+ const input: ExtractInput = { turnText: text, sessionId, source: CONVERSATION_FACTS_SOURCE_PREFIX, engine: run.engine, abortSignal: run.signal,+ entityHints, entityHintsCap: CONVERSATION_ENTITY_HINTS_CAP };+ if (run.extractor) {+ extracted = await run.extractor(input);+ } else {+ const extraction = await extractFactsFromTurnWithOutcome({ ...input, observationDate: segmentObservationDate(page, seg.startIso) });+ if (!extraction.ok) {+ if (extraction.error instanceof BudgetExhausted) throw extraction.error;+ const detail = extraction.error instanceof Error ? `: ${extraction.error.message}` : '';+ throw Object.assign(new Error(`segment ${seg.startIso}..${seg.endIso} extraction failed (${extraction.reason})${detail}`,+ extraction.error === undefined ? undefined : { cause: extraction.error }), { extractionReason: extraction.reason });+ }+ extracted = extraction.facts;+ }+ // This bulk path bypasses writeSingleFact and writes through insertFacts: every extractor-provided entity goes+ // through the shipped resolver (alias_exact / prefix / fuzzy / slugify) while source scope is known.+ const resolution = await resolveExtractedEntitiesForSave(run.engine, run.sourceId, extracted, (raw, message) => {+ process.stderr.write(`[extract-conversation-facts] ${page.slug} segment ${seg.startIso}..${seg.endIso} `+ + `entity resolution failed for ${JSON.stringify(raw)}: ${message}; preserving fact without an entity target\n`);+ });+ if (extracted.length === 0) return { extracted: 0, rows: [], resolution };- const rows = await inferConversationSubjects(run.engine, run.sourceId, run.factVisibility, extracted.map((fact, i) => ({ // #6764- ...fact, visibility: run.factVisibility,++ const visibility = tightenToPage(run.factVisibility, page);++ const rows = await inferConversationSubjects(run.engine, run.sourceId, visibility, extracted.map((fact, i) => ({ // #6764++ ...fact, visibility,+ row_num: rowNum + i,+ source_markdown_slug: page.slug,+ source: CONVERSATION_FACTS_SOURCE_PREFIX,+ source_session: sessionId,+ ...segmentValidFrom(fact.valid_from, seg.startIso),+ context: fact.context ?? `from ${page.slug} segment ${seg.startIso}..${seg.endIso}`,+ })));+ return { extracted: extracted.length, rows, resolution };+}++/**+ * The parser-input version token of a page read from its own body. content_hash covers title, type, compiled_truth,+ * timeline, and frontmatter; unlike JavaScript Date, it cannot collapse distinct PostgreSQL updates within one+ * millisecond. effective_date is parser input too.+ */+export function regularPageVersionToken(page: Page): string {+ const hash = page.content_hash ?? createHash('sha256')+ .update(JSON.stringify({+ title: page.title,+ type: page.type,+ compiled_truth: page.compiled_truth,+ timeline: page.timeline || '',+ frontmatter: page.frontmatter || {},+ }))+ .digest('hex');+ const effectiveDate = page.effective_date+ ? new Date(page.effective_date).toISOString().slice(0, 10)+ : 'none';+ return `page-${hash}-${effectiveDate}`;+}++export function outcomeSession(source: string, slug: string, versionToken: string): string {+ return `${source}:${slug}:${versionToken}`;+}++type OutcomeRow = NewFact & { row_num: number; source_markdown_slug: string };++/** The page outcome of a complete extraction, bound to the parser-input version it read. */+export function terminalAuditFact(slug: string, rowNum: number, versionToken: string): OutcomeRow {+ return {+ fact: 'EXTRACTION_COMPLETE',+ kind: 'fact',+ entity_slug: null,+ source: TERMINAL_AUDIT_SOURCE,+ source_session: outcomeSession(TERMINAL_AUDIT_SOURCE, slug, versionToken),+ confidence: 1.0,+ notability: 'low',+ context: stampExtractorVersion(null),+ row_num: rowNum,+ source_markdown_slug: slug,+ };+}++/** The durable not-extractable outcome: stops repeated scans of a page version with nothing to extract. */+export function nonExtractableAuditFact(slug: string, rowNum: number, versionToken: string, reason: string): OutcomeRow {+ return {+ fact: 'EXTRACTION_NOT_APPLICABLE',+ kind: 'fact',+ entity_slug: null,+ source: NON_EXTRACTABLE_AUDIT_SOURCE,+ source_session: outcomeSession(NON_EXTRACTABLE_AUDIT_SOURCE, slug, versionToken),+ confidence: 1.0,+ notability: 'low',+ context: stampExtractorVersion(`scanned, not extractable: ${reason}`),+ row_num: rowNum,+ source_markdown_slug: slug,+ };+}diff --cc src/core/persistence/effects.tsindex f208ae7fec,237f859518..11e6fa1d13--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@@ -439,14 -438,16 +439,23 @@@ async function embedPage(engine: BrainEif (isEmbedSkipped(snapshot.page.frontmatter)) { await completeEffect(engine, effect, { embedding: 'skipped', reason: 'embed_skip' }); return; }const segmented = await readSegmentedEmbedPage(engine, { id: snapshot.page.id });if (segmented) { await embedSegmentedEffect(engine, config, effect, snapshot, segmented, signature, opts); return; }+ await faultPoint('effect:embedding:page_read', { effectId: effect.id, requestId: effect.request_id, sourceId: effect.source_id });+ // A stale drain or another worker embedding this page finishes first; the projection read below then finds its chunks complete.+ await using pageLease = await acquirePageEmbeddingLease(engine, snapshot.page.id, { signal: opts.signal, whileWaiting: async () => {+ if (!await renewPersistenceEffectClaim({ executeRaw: engine.executeRawDirect.bind(engine) }, effect)) throw opError('write_claim_lost', 'The embedding claim changed.',+ `Another worker took over the embedding of ${snapshot.page.slug} in source ${effect.source_id}; this attempt stops without installing vectors and the owning claim finishes it.`,+ { fix: effectStatusFix(effect) });+ } });+ if (pageLease.busy) throw pageEmbeddingLeaseUnavailable(snapshot.page.id, false);- const projection = await readEmbeddingEffectProjection(engine, effect, snapshot, opts.hostId, signature, opts.embedding?.model);+ // A write that committed after the page read above leaves no projection at this revision to wait for: the effect is+ // superseded, as when the page read already saw the newer revision; only the effect's own revision still unsealed retries.+ const projection = await readEmbeddingEffectProjection(engine, effect, snapshot, opts.hostId, signature, opts.embedding?.model).catch(async error => {+ if ((error as { code?: string }).code !== 'projection_pending' || targetedWithdrawalEffect(effect) || effect.data.source_scan) throw error;+ const current = await selectedEffectPage(engine, effect);+ if (!current || current.page.deleted_at || (current.revision === effect.revision && current.page.id === effect.data.page_id)) throw error;+ return null;+ });+ if (!projection) { await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return; }const { prepared } = projection;let pending = projection.pending;// A large page is metered as a whole under embed.max_usd_per_page (page-embedding-budget.ts).diff --cc test/conversation-facts-managed.test.tsindex 9d28e6455d,9d28e6455d..831be9aca1--- a/test/conversation-facts-managed.test.ts+++ b/test/conversation-facts-managed.test.ts@@@ -192,6 -192,6 +192,17 @@@ for (const backend of testBackends())}, { databaseUrl });}, 120_000);++ test(`${backend}: facts from a private transcript publish private on a world-default brain`, async () => {++ await managedBrain(async brain => {++ const { engine } = brain;++ await engine.setConfig('facts.default_visibility', 'world');++ await putPage(brain, transcript().replace('date: 2026-09-28', 'date: 2026-09-28\nvisibility: private'));++ const calls = { n: 0 };++ await extract(engine, calls);++ expect({ calls: calls.n, visibility: [...new Set((await extractorRows(engine)).map(row => row.visibility))] }).toEqual({ calls: 1, visibility: ['private'] });++ }, { databaseUrl });++ });++test(`${backend}: a crash after admission replays the stored batch with zero model calls`, async () => {await managedBrain(async brain => {const { engine } = brain;diff --cc test/helpers/conversation-facts-recovery-cases.tsindex b90afaeb61,0000000000..ddbc9988a7mode 100644,000000..100644--- a/test/helpers/conversation-facts-recovery-cases.ts+++ b/test/helpers/conversation-facts-recovery-cases.ts@@@ -1,302 -1,0 +1,324 @@@+/**+ * Conversation facts on a segmented page when things go wrong (wave-b spec 8.2, 8.3; PR 4 lane 4b round 3), shared by+ * the PGLite arm (test/large-pages/conversation-facts-incremental.test.ts) and the Postgres arm+ * (test/e2e/conversation-facts-incremental-postgres.test.ts). Fake extractors only; appends go through the remote+ * append_page operation (remote=true).+ *+ * 1. Protects: a partial run on a transcript without per-message times (every message at the page date) clears only+ * the windows it extracted again; a time-less transcript whose turns cross segment cuts streams exactly the+ * whole-page windows and settles only then; a checkpoint write that fails keeps the window moves it carried for the+ * write that follows, so no re-anchored fact is lost; a window that fails run after run is marked failed after+ * WINDOW_FAILURE_LIMIT runs and the older windows are extracted, doctor names it and --force retries it.+ * Round 4: a one-window run on oversized turns clears only the pieces that window holds; a page re-imported in+ * another chat format is parsed in that format; a run parsing no message where windows were keeps every fact and+ * leaves a no_messages receipt; provider-wide failures (auth, 503) never count against a window; a failed window+ * keeps the facts of the window it replaced until it is extracted.+ * 2. Fails when: coverage is judged by timestamps or by a message shared by many pieces, a stale grammar pins the page, (one window "covers" every message at the page date), a continuation+ * is dropped by re-detecting the grammar per occurrence, moves are dropped before their write commits, or one+ * failing window stalls every older window of the page.+ */+import { expect, test } from 'bun:test';+import { createHash, randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { AppendBrain } from './append-brain.ts';+import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';+import { PAGE_DERIVATION_CAP_KEY } from '../../src/core/page-spend.ts';+import { parseConversation } from '../../src/core/conversation-parser/parse.ts';+import { renderSegmentForExtraction, splitIntoSegments } from '../../src/core/facts/conversation-windows.ts';+import { WINDOW_FAILURE_LIMIT } from '../../src/core/facts/conversation-incremental.ts';+import { outcomeSession, regularPageVersionToken } from '../../src/core/facts/conversation-window-extract.ts';+import { TERMINAL_AUDIT_SOURCE } from '../../src/core/facts/audit-sources.ts';+import { extractionInputTruncatedEntry } from '../../src/commands/doctor/checks/extraction-input.ts';+import type { DoctorContext } from '../../src/commands/doctor/context.ts';+import type { Check } from '../../src/commands/doctor.ts';+import { __setChatTransportForTests } from '../../src/core/ai/gateway.ts';+import { chatDays, chatPage, derivations, extract, factsOf, PAID_MODEL, paidTransport, turns } from './conversation-facts-incremental-cases.ts';++const WORDS = ['launch', 'pricing', 'budget', 'roadmap', 'hiring', 'review', 'contract', 'latency', 'onboarding', 'forecast'];+const prose = (seed: number, words: number) => Array.from({ length: words }, (_, i) => WORDS[(seed * 7 + i * 3) % WORDS.length]).join(' ');+const sha = (text: string) => createHash('sha256').update(text).digest('hex');+const caps = async (engine: BrainEngine, usd: string) => { await engine.setConfig(PAGE_DERIVATION_CAP_KEY, usd); await engine.setConfig(PAGE_EMBED_CAP_KEY, usd); };++/**+ * A time-less transcript (plain-role-no-time: no per-message times, so every message is at the page date): `turns`+ * turns of a line plus continuation lines; turn `long` (if any) carries `longLines` of them, enough to span segment cuts.+ */+function timeless(count: number, seed: number, long = -1, longLines = 0): string {+ const lines: string[] = [];+ for (let t = 0; t < count; t++) {+ lines.push(`${t % 2 === 0 ? 'user' : 'assistant'}: ${prose(seed + t, 14)}`);+ const continuation = t === long ? longLines : 1 + ((t * 5 + seed) % 4);+ for (let c = 0; c < continuation; c++) lines.push(prose(seed + t + c, 12 + (c % 9)));+ }+ return lines.join('\n');+}++const terminalStamps = async (engine: BrainEngine, slug: string) => {+ const page = await engine.getPage(slug, { sourceId: 'default' });+ return Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug=$1 AND source=$2 AND source_session=$3',+ [slug, TERMINAL_AUDIT_SOURCE, outcomeSession(TERMINAL_AUDIT_SOURCE, slug, regularPageVersionToken(page!))]))[0]!.n);+};++export function defineConversationFactsRecoveryCases(opts: { getBrain: () => AppendBrain }): void {+ test('a partial run on a transcript without message times deletes nothing: the window it extracted is added beside the old facts', async () => {+ const brain = opts.getBrain();+ const slug = `notes/timeless-partial-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Timeless T1', timeless(9000, 1)));+ const all = await extract(brain.engine, slug);+ const before = await factsOf(brain.engine, slug);+ expect((await derivations(brain.engine, slug)).live.length).toBeGreaterThan(2);+ expect(before.length).toBe(all.calls.length);+ expect(before.length).toBeGreaterThan(50);+ await brain.seed(slug, chatPage('Timeless T2', (await brain.body(slug)).truth));+ const limited = await extract(brain.engine, slug, { segmentLimit: 1 });+ const after = await factsOf(brain.engine, slug);+ expect({ calls: limited.calls.length, before: before.length, after: after.length, cleaned: limited.result.orphan_facts_cleaned,+ kept: before.filter(f => after.some(a => a.id === f.id)).length })+ .toEqual({ calls: 1, before: before.length, after: before.length + 1, cleaned: 0, kept: before.length });+ }, 600_000);++ test('a time-less transcript whose turns cross segment cuts streams exactly the whole-page windows before it settles', async () => {+ const brain = opts.getBrain();+ const slug = `notes/timeless-cuts-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Timeless cuts', timeless(9000, 2, 4500, 25000)));+ const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;+ const truth = (await brain.body(slug)).truth;+ expect(truth.length).toBeGreaterThan(3_000_000);+ expect((await brain.engine.readManifest(page.id)).length).toBeGreaterThan(3);+ const expected = splitIntoSegments(parseConversation(truth, { page }).messages, { pageTitle: 'Timeless cuts' }).map(seg => renderSegmentForExtraction('Timeless cuts', seg));+ const { calls } = await extract(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);+ expect(expected.length).toBeGreaterThan(100);+ expect({ calls: calls.length, same: [...calls].sort().join('\n') === [...expected].sort().join('\n'), stamped: await terminalStamps(brain.engine, slug),+ states: [...new Set(rows.states)] }).toEqual({ calls: expected.length, same: true, stamped: 1, states: ['done'] });+ }, 600_000);++ test('a checkpoint write that fails keeps its window moves for the next write; no re-anchored fact is lost', async () => {+ const brain = opts.getBrain();+ const slug = `notes/chat-checkpoint-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Chat checkpoint', chatDays(3000, 100, 21)));+ const first = await extract(brain.engine, slug);+ const before = await factsOf(brain.engine, slug);+ // Three hundred more turns on the last day: one gap group with its earlier turns, so the rewritten tail's windows+ // move to their new occurrence in the same run that extracts the new windows, before its first checkpoint.+ expect(await brain.call('append_page', { slug, text: turns(3099, 50, 300, 21), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });+ let armed = true;+ const failing = (tx: BrainEngine): BrainEngine => new Proxy(tx, {+ get(target, prop) {+ if (prop === 'upsertSegmentDerivations') {+ return async (rows: Parameters<BrainEngine['upsertSegmentDerivations']>[0]) => {+ if (armed && rows.some(row => row.kind === 'conversation_facts')) { armed = false; throw new Error('fixture: checkpoint write failed'); }+ return target.upsertSegmentDerivations(rows);+ };+ }+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ const engine = new Proxy(brain.engine, {+ get(target, prop) {+ if (prop === 'transaction') return <T>(fn: (tx: BrainEngine) => Promise<T>) => target.transaction(tx => fn(failing(tx)));+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ const broken = await extract(engine, slug).catch(error => ({ error, calls: [] as string[] }));+ expect(armed).toBe(false);+ // Right after the failed checkpoint, the write that followed it carried its moves: every fact of a window still on+ // the page is anchored to that window on its live occurrence, not to the occurrence the append retired.+ const mid = await derivations(brain.engine, slug);+ const liveKeys = new Set(mid.rows.filter(row => mid.live.includes(row.occurrenceId))+ .flatMap(row => ((row.output as { windows?: Array<{ ordinal: number; sha: string }> })?.windows ?? []).map(w => `${row.occurrenceId}:${w.ordinal}:${w.sha}`)));+ const liveShasMid = new Set([...liveKeys].map(key => key.split(':')[2]));+ const midFacts = await factsOf(brain.engine, slug);+ expect(midFacts.filter(f => liveShasMid.has(f.key.split(':')[2]) && !liveKeys.has(f.key)).length).toBe(0);+ const resumed = await extract(brain.engine, slug);+ const after = await factsOf(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);+ const liveShas = new Set(rows.keys.map(key => key.split(':')[2]));+ const kept = before.filter(f => liveShas.has(f.key.split(':')[2]));+ const byId = new Map(after.map(f => [f.id, f]));+ const moved = kept.filter(f => byId.get(f.id) && byId.get(f.id)!.key !== f.key);+ expect(moved.length).toBeGreaterThan(0);+ expect({ keptLost: kept.filter(f => !byId.has(f.id)).length, facts: after.length, keys: rows.keys.length,+ repeats: resumed.calls.filter(text => first.calls.includes(text)).length, anchored: after.every(f => rows.keys.includes(f.key)) })+ .toEqual({ keptLost: 0, facts: rows.keys.length, keys: rows.keys.length, repeats: 0, anchored: true });+ expect('error' in broken || broken.calls.length > 0).toBe(true);+ }, 600_000);++ test('a window that fails run after run is marked failed after the limit and the older windows are extracted; doctor names it, --force retries it', async () => {+ const brain = opts.getBrain();+ const slug = `notes/chat-stuck-window-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Chat stuck', chatDays(3200, 100, 22)));+ let stuck = null as string | null;+ const failOn = (text: string) => { stuck ??= text; return text === stuck; };+ const runs: Array<{ calls: number; failed: number }> = [];+ for (let run = 1; run < WINDOW_FAILURE_LIMIT; run++) {+ const { calls, result } = await extract(brain.engine, slug, { failOn });+ runs.push({ calls: calls.length, failed: result.pages_failed });+ expect(calls[0]).toBe(stuck!);+ }+ const last = await extract(brain.engine, slug, { failOn });+ const rows = await derivations(brain.engine, slug);+ const facts = await factsOf(brain.engine, slug);+ expect({ runs, failed: last.result.pages_failed, first: last.calls[0] === stuck, facts: facts.length, stuckFacts: facts.filter(f => f.key.endsWith(':' + sha(stuck!))).length,+ receipts: rows.receipts.filter(Boolean).map(r => (r as { kind: string }).kind), stamped: await terminalStamps(brain.engine, slug) })+ .toEqual({ runs: Array.from({ length: WINDOW_FAILURE_LIMIT - 1 }, () => ({ calls: 1, failed: 1 })), failed: 0, first: true, facts: last.calls.length - 1,+ stuckFacts: 0, receipts: ['failed_windows'], stamped: 1 });+ expect(rows.keys.length).toBe(last.calls.length);+ const check = (await extractionInputTruncatedEntry.run({ engine: brain.engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'extraction_input_truncated')!;+ const groups = (check.details as { groups: Array<{ pipeline: string; kind: string; samples: string[]; remedy: string | null }> }).groups;+ const group = groups.find(g => g.pipeline === 'conversation_facts' && g.kind === 'failed_windows');+ expect({ status: check.status, named: group?.samples.some(s => s.startsWith(`default:${slug} window `)), retry: group?.remedy?.includes('--force') }).toEqual({ status: 'warn', named: true, retry: true });+ expect((await extract(brain.engine, slug, { failOn })).calls).toEqual([]);+ const forced = await extract(brain.engine, slug, { force: true });+ expect({ calls: forced.calls, receipts: (await derivations(brain.engine, slug)).receipts.filter(Boolean) }).toEqual({ calls: [stuck!], receipts: [] });+ }, 600_000);++ test('a one-window run on a page of oversized turns after a title of another length deletes nothing (piece numbers move with the title)', async () => {+ const brain = opts.getBrain();+ const slug = `notes/oversized-turns-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ // Thirty turns of about 100 KB each, a minute apart: each is split into many pieces, one window per few pieces.+ const lines = ['## 2025-04-01', ''];+ for (let t = 0; t < 30; t++) lines.push(`**${['Alice Example', 'Bob Example'][t % 2]}** (9:${String(t).padStart(2, '0')} AM): ${prose(t, 14_000)}.`, '');+ await brain.seed(slug, chatPage('Oversized T1', lines.join('\n')));+ const all = await extract(brain.engine, slug);+ const before = await factsOf(brain.engine, slug);+ expect(before.length).toBe(all.calls.length);+ expect(before.length).toBeGreaterThan(60);+ await brain.seed(slug, chatPage('Oversized turns, retitled with a much longer page title', (await brain.body(slug)).truth));+ const limited = await extract(brain.engine, slug, { segmentLimit: 1 });+ const after = await factsOf(brain.engine, slug);+ expect({ calls: limited.calls.length, after: after.length, cleaned: limited.result.orphan_facts_cleaned, kept: before.filter(f => after.some(a => a.id === f.id)).length })+ .toEqual({ calls: 1, after: before.length + 1, cleaned: 0, kept: before.length });+ }, 600_000);++ test('a page re-imported in another chat format is parsed in its new format, not the grammar its old rows recorded', async () => {+ const brain = opts.getBrain();+ const slug = `notes/reformatted-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Reformatted', chatDays(3400, 100, 23)));+ await extract(brain.engine, slug);+ const before = await factsOf(brain.engine, slug);+ expect(before.length).toBeGreaterThan(100);+ await brain.seed(slug, chatPage('Reformatted', timeless(9000, 3)));+ const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;+ const truth = (await brain.body(slug)).truth;+ const expected = splitIntoSegments(parseConversation(truth, { page }).messages, { pageTitle: 'Reformatted' }).map(seg => renderSegmentForExtraction('Reformatted', seg));+ expect(parseConversation(truth, { page }).matched_pattern_id).toBe('plain-role-no-time');+ const { calls, result } = await extract(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);+ expect({ calls: calls.length, same: [...calls].sort().join('\n') === [...expected].sort().join('\n'), nonExtractable: result.pages_marked_non_extractable,+ facts: (await factsOf(brain.engine, slug)).length, states: [...new Set(rows.states)] })+ .toEqual({ calls: expected.length, same: true, nonExtractable: 0, facts: expected.length, states: ['done'] });+ }, 600_000);++ test('a page that stops being a transcript settles as non-extractable and its conversation facts are collected, under --force too', async () => {+ const brain = opts.getBrain();+ const slug = `notes/unparsed-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Unparsed', chatDays(3500, 100, 24)));+ await extract(brain.engine, slug);+ const before = (await factsOf(brain.engine, slug)).length;+ expect(before).toBeGreaterThan(100);+ const prose = Array.from({ length: 6000 }, (_, i) => `Paragraph ${i} of the notes: the roadmap review moved to next quarter and the budget stays flat.`).join('\n\n');+ await brain.seed(slug, chatPage('Unparsed', prose));+ const { calls, result } = await extract(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);+ expect({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, cleaned: result.orphan_facts_cleaned,+ facts: (await factsOf(brain.engine, slug)).length, states: [...new Set(rows.states)], receipts: rows.receipts.filter(Boolean) })+ .toEqual({ calls: 0, failed: 0, nonExtractable: 1, cleaned: before + 1, facts: 0, states: ['done'], receipts: [] });+ const forced = await extract(brain.engine, slug, { force: true });+ expect({ calls: forced.calls.length, failed: forced.result.pages_failed, facts: (await factsOf(brain.engine, slug)).length }).toEqual({ calls: 0, failed: 0, facts: 0 });+ const check = (await extractionInputTruncatedEntry.run({ engine: brain.engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'extraction_input_truncated')!;+ const groups = ((check.details as { groups?: Array<{ pipeline: string; kind: string; samples: string[] }> } | undefined)?.groups ?? []);+ expect(groups.some(g => g.kind === 'no_messages' && g.samples.includes(`default:${slug}`))).toBe(false);+ }, 600_000);++ test('provider-wide failures (an auth error, a 503) never count against a window: it is never marked failed and extracts once the provider recovers', async () => {+ const brain = opts.getBrain();+ await caps(brain.engine, 'off');+ await brain.engine.setConfig('facts.extraction_model', PAID_MODEL);+ try {+ for (const [label, failure] of [['auth', () => Object.assign(new Error('invalid x-api-key'), { status: 401 })], ['503', () => Object.assign(new Error('upstream unavailable'), { status: 503 })]] as const) {+ const slug = `notes/provider-down-${label}-${randomUUID().slice(0, 8)}`;+ await brain.seed(slug, chatPage('Provider down', chatDays(3600, 100, 25)));+ let attempts = 0;+ __setChatTransportForTests(async () => { attempts++; throw failure(); });+ const runs: Array<{ attempts: number; failed: number }> = [];+ for (let run = 0; run < WINDOW_FAILURE_LIMIT + 2; run++) {+ attempts = 0;+ const result = await extractProductionRun(brain.engine, slug);+ runs.push({ attempts, failed: result.pages_failed });+ }+ const receipts = (await derivations(brain.engine, slug)).receipts.filter(Boolean).map(r => (r as { kind: string }).kind);+ __setChatTransportForTests(paidTransport);+ const recovered = await extractProductionRun(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);+ expect({ label, runs, receipts, recovered: recovered.pages_failed, states: [...new Set(rows.states)], failedWindows: rows.receipts.filter(r => (r as { kind?: string } | null)?.kind === 'failed_windows').length }).toEqual({+ label, runs: Array.from({ length: WINDOW_FAILURE_LIMIT + 2 }, () => ({ attempts: 1, failed: 1 })), receipts: ['unread_windows'], recovered: 0, states: ['done'], failedWindows: 0 });+ }+ } finally {+ __setChatTransportForTests(null);+ await brain.engine.setConfig('facts.extraction_model', '');+ }+ }, 600_000);++ test('a window marked failed blocks collection across two context changes: every earlier fact stands until a --force run extracts it', async () => {+ const brain = opts.getBrain();+ const slug = `notes/failed-keeps-${randomUUID().slice(0, 8)}`;+ await caps(brain.engine, 'off');+ await brain.seed(slug, chatPage('Keeps T1', chatDays(3700, 100, 26)));+ await extract(brain.engine, slug);+ const before = await factsOf(brain.engine, slug);+ const survivors = (facts: Awaited<ReturnType<typeof factsOf>>) => before.filter(f => facts.some(s => s.id === f.id)).length;+ const stuck: string[] = [];+ for (const title of ['Keeps T2', 'Keeps, a third and longer title']) {+ await brain.seed(slug, chatPage(title, (await brain.body(slug)).truth));+ let first = null as string | null;+ const failOn = (text: string) => { first ??= text; return text === first; };+ for (let run = 1; run <= WINDOW_FAILURE_LIMIT; run++) await extract(brain.engine, slug, { failOn });+ stuck.push(first!);+ const facts = await factsOf(brain.engine, slug);+ expect({ title, survivors: survivors(facts), stamped: await terminalStamps(brain.engine, slug) }).toEqual({ title, survivors: before.length, stamped: 1 });+ }+ const forced = await extract(brain.engine, slug, { force: true });+ const after = await factsOf(brain.engine, slug);+ const rows = await derivations(brain.engine, slug);+ expect({ calls: forced.calls, facts: after.length, survivors: survivors(after), anchored: after.every(f => rows.keys.includes(f.key)) })+ .toEqual({ calls: [stuck[1]!], facts: rows.keys.length, survivors: 0, anchored: true });+ }, 600_000);++++ test('facts from a private segmented transcript stay private on a world-default brain, on the import run and on the incremental run after an append', async () => {++ const brain = opts.getBrain();++ const slug = `notes/private-chat-${randomUUID().slice(0, 8)}`;++ const privatePage = (body: string) => chatPage('Private chat', body).replace('date: 2025-01-01', 'date: 2025-01-01\nvisibility: private');++ const visibilities = async () => {++ const ids = (await factsOf(brain.engine, slug)).map(f => f.id);++ const rows = await brain.engine.executeRaw<{ visibility: string }>('SELECT DISTINCT visibility FROM facts WHERE id = ANY($1::bigint[])', [ids]);++ return { facts: ids.length, visibility: rows.map(r => r.visibility) };++ };++ await caps(brain.engine, 'off');++ await brain.engine.setConfig('facts.default_visibility', 'world');++ await brain.seed(slug, privatePage(chatDays(0, 100, 7)));++ const first = await extract(brain.engine, slug);++ expect((await derivations(brain.engine, slug)).live.length).toBeGreaterThan(2);++ expect(await visibilities()).toEqual({ facts: first.calls.length, visibility: ['private'] });++ await brain.seed(slug, privatePage(chatDays(0, 101, 7)));++ const second = await extract(brain.engine, slug);++ expect(second.calls.length).toBeGreaterThan(0);++ expect(second.calls.length).toBeLessThan(first.calls.length);++ expect((await visibilities()).visibility).toEqual(['private']);++ }, 600_000);+}++/** A production-extractor run (no injected extractor): the gateway's fake transport answers or fails. */+async function extractProductionRun(engine: BrainEngine, slug: string) {+ const { runExtractConversationFactsCore } = await import('../../src/commands/extract-conversation-facts.ts');+ return runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [slug], sleepMs: 0 });+}diff --cc test/postgres-unit-arms.txtindex fe73fb0854,71eec66c96..1d1128467e--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@@ -452,8 -448,8 +452,9 @@@ test/trust-held-removals.test.ttest/trust-owner-actions.test.tstest/unbound-source-6536.test.tstest/unindexed-files.test.ts+test/v265-validate-timeouts.test.tstest/vector-manifest-probe-bound.test.ts+ test/visibility-fail-closed-derived-writes.test.tstest/withdrawal-overlay-concurrency.test.tstest/withdrawal-publication-file.test.tstest/worktree-refresh-recovery-row-gbra130.test.ts