Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
extract-conversation-facts: slug-keyset enumeration, per-run claims and per-request failure counting (#6500)
garrytan15820f8204de
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 93157d474b..4b0e05bd22 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -23,7 +23,7 @@ src/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grownsrc/core/pglite-engine.ts 3023 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured)src/core/postgres-engine.ts 3027 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured)src/core/search/hybrid.ts 1632 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)-src/core/types.ts 2280 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons+src/core/types.ts 2292 ratchet +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts)src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)src/commands/init.ts 1878 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 70ddfa4e39..4b4ca97005 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -79,6 +79,7 @@ import { configureGatewayIfUninitialized, isAvailable, withBudgetTracker } fromimport { insertDerivedFacts, writeDerivedFacts } from '../core/persistence/derived-facts.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';import { clearConversationFacts, enqueueManagedPage, flushManagedBatch, managedConversationPublisher, startManagedPage, stopsRun, type ManagedConversationPublisher } from '../core/facts/conversation-publication.ts';+import { ConversationRunClaims, listConversationPagesBySlug } from '../core/facts/conversation-enumeration.ts';import { BudgetTracker, BudgetExhausted, loadPricingOverrides, type BudgetReason, type NoPricingGuidance } from '../core/budget/budget-tracker.ts';import { noPricingMessage } from '../core/budget/no-pricing.ts';import { conversationFactsCostCap } from '../core/facts/conversation-budget.ts';@@ -364,6 +365,8 @@ export interface ExtractConversationFactsResult {pages_pending?: number;/** Managed brains: pages whose extraction generation is blocked until the page changes (no model call). */pages_blocked?: number;+ /** Pages the run listed more than once and extracted once (#6500). */+ pages_skipped_duplicate_listing?: number;budget_exhausted?: boolean;budget_reason?: BudgetReason;budget_model?: string;@@ -1431,7 +1434,12 @@ export async function runExtractConversationFactsCore(* page rather than blocking. A hard error from processPage propagates* up; the pool's onError='continue' captures it into failures[].*/+ const claims = new ConversationRunClaims();const processPageWithLock = async (page: Page): Promise<void> => {+ if (!claims.claim(sourceId, page.slug)) {+ state.result.pages_skipped_duplicate_listing = (state.result.pages_skipped_duplicate_listing ?? 0) + 1;+ return;+ }const lockId = extractConversationFactsLockId(sourceId, page.slug);if (opts.force) {state.cpMap.delete(cpMapKey(sourceId, page.slug));@@ -1526,27 +1534,18 @@ export async function runExtractConversationFactsCore(await processPageWithLock(page);} else {// Multi-page enumeration: paginate per-type at small batch size to- // bound memory (Eng-v2 C8 — 10 × 25MB = 250MB worst case).+ // bound memory (Eng-v2 C8 — 10 × 25MB = 250MB worst case), by slug+ // keyset so every page is listed once (#6500, conversation-enumeration.ts).// v0.41.15.0 (D9): inner per-page loop replaced with runSlidingPool// so parallel workers can claim pages from the batch. The pool// honors AbortSignal at each claim boundary and threads// BudgetExhausted abort (D13) automatically.let processedPagesCount = 0;pageLoop: for (const type of concreteTypes) {- let offset = 0;- // eslint-disable-next-line no-constant-condition- while (true) {+ for await (const batch of listConversationPagesBySlug(engine, { type, sourceId, batchSize: PAGE_LIST_BATCH })) {if (signal?.aborted) throw new Error('aborted');if (opts.limit && processedPagesCount >= opts.limit) break pageLoop;- const batch = await engine.listPages({- type,- sourceId,- limit: PAGE_LIST_BATCH,- offset,- });- if (batch.length === 0) break;-let claimable = batch.filter(page => isConversationFactsEligiblePage(page, concreteTypes, strictEligibility));result.pages_skipped += batch.length - claimable.length;// Checkpoints are an intra-page cursor; fresh durable outcomes are@@ -1595,8 +1594,6 @@ export async function runExtractConversationFactsCore(for (const failure of poolResult.failures) recordPageFailure(result, sourceId, failure.label, failure.error);processedPagesCount += claimable.length;- offset += batch.length;- if (batch.length < PAGE_LIST_BATCH) break;// Persist checkpoint between batches so a crash mid-walk// doesn't lose all progress.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 04f73052dd..8ca6b08d25 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -437,6 +437,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.165.0', text: '`gbrain extract --stale` and `extract links|all --source db` skip and count a page another writer changed mid-run (`skipped_concurrent_write`) instead of aborting the run; the page stays stale for the next run. `extract all --source db` marks a page extracted only when both its links and its timeline finished at the same revision. On a managed brain, `extract timeline --from-meetings` (and its job) now writes through the coordinator as one `managed_maintenance_meeting_timeline` request per entity page, gated at the meeting\'s trust tier; a refused or pending write fails the job and the command exits 1. An owner on an older build refuses that request kind until it upgrades. On a managed brain, `extract_entities` now writes stubs, timeline rows and backlinks through the coordinator (creating a stub needs permission to write pages); a refusal or pending write returns its error envelope and names the entities already written, instead of a raw `writer_coordinator_required` error or a silently missing timeline row.' },// Memory proof wave 2 W1 (question-ranked recall).{ since: '0.60.169.0', text: '`recall` takes an optional `question` and returns saved facts ranked by relevance to it (facts below the match threshold are left out); calls without it still return the newest facts, every response now says `facts_order`, and a call that passes only `query` carries a `recall_hint` notice. `gbrain recall --question` passes the question instead of reading its value as an entity name. In `query`, the facts of an entity the question names come only from that entity page\'s own source, and the temporal fact reserve (`search.temporal_fact_reserve`, off by default) scores with the same question scorer: whole-word matches, and a long fact\'s word matches count for less.' },+ // Fix wave 15 G3 (GBRA-79). `since` is provisional (0.60.176.0); the integrator restamps it at the merge slot.+ { since: '0.60.176.0', text: '`gbrain extract-conversation-facts` now walks a source\'s pages by slug (a keyset) instead of OFFSET over `updated_at`, so a page is listed, extracted and frozen once per run even while other writers touch pages that share one timestamp; a page the run sees twice is counted as `pages_skipped_duplicate_listing` with no second model call. A batch request the writer refused as malformed (`invalid_params`, the shape a page listed twice produced) is no longer a permanent block: its stored entries are resubmitted on the next run with zero model calls, up to 3 failed requests per page version, and one failed request counts once however many times it listed the page. `list_pages` sorted by `updated_desc` (the default) now breaks timestamp ties by slug, source and id, so ties page deterministically; offset paging is still unstable under writes that change `updated_at`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 67601faa41..42b045b42c 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -421,6 +421,10 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promisconst slugCondition = slugPrefix? sqlFragment`AND p.slug LIKE ${slugPrefix.replace(/[\\%_]/g, (c) => '\\' + c) + '%'} ESCAPE '\\'`: sqlFragment``;+ // #6500 slug keyset (single-source contract, see PageFilters.slugAfter).+ const slugAfterCondition = filters?.slugAfter !== undefined+ ? sqlFragment`AND p.slug > ${filters.slugAfter}`+ : sqlFragment``;// v0.31.12 + v0.34.1 (#876, D9): scope to a single source OR an array// of sources. When BOTH are set, the array wins (federated semantics// subsume the scalar case). When neither is set, no filter applies.@@ -455,7 +459,7 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promisconst { rows } = await exec.run(sqlFragment`SELECT ${columns}, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso FROM pages p${tagJoin}- WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition} ${sourceCondition} ${deletedCondition} ${privateCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}+ WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition} ${slugAfterCondition} ${sourceCondition} ${deletedCondition} ${privateCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}ORDER BY ${orderBy} LIMIT ${limit} OFFSET ${offset}`);return rows.map(rowToPage);diff --git a/src/core/facts/conversation-enumeration.ts b/src/core/facts/conversation-enumeration.tsnew file mode 100644index 0000000000..1d624b34ed--- /dev/null+++ b/src/core/facts/conversation-enumeration.ts@@ -0,0 +1,56 @@+/**+ * Page enumeration for `gbrain extract-conversation-facts` (#6500).+ *+ * The extractor used to page a source's conversation pages with OFFSET over+ * `updated_desc`, which is not a total order: a bulk import stamps one+ * `now()` across its transaction, and any concurrent non-timestamp write to a+ * tied row (a connector, `embed --stale`, an outcome stamp) reorders the tie+ * cluster between two windows, so one page is listed twice and another never.+ * The second listing extracted the page again (a second paid model call) and+ * froze a second entry into the batch, which the envelope validator refused+ * (`invalid_params`) for every member.+ *+ * Two guards replace that:+ * - `listConversationPagesBySlug` walks ONE source by slug keyset+ * (`sort: 'slug'`, `slugAfter`): slug is a total order inside a source+ * and does not move when a row is touched or deleted. The extractor's+ * core always has a `sourceId` (its strict per-source contract), so the+ * single-source `slugAfter` contract holds here.+ * - `ConversationRunClaims` is the run's claimed set: a page seen twice in+ * one run (a keyset race, or `--slugs` naming it twice) is extracted once+ * and counted as `pages_skipped_duplicate_listing`.+ */+import type { BrainEngine } from '../engine.ts';+import type { Page } from '../types.ts';++/** The pages one run has claimed, by source-qualified slug. */+export class ConversationRunClaims {+ private readonly claimed = new Set<string>();++ /** True the first time this run sees `(sourceId, slug)`; false for every later listing of it. */+ claim(sourceId: string, slug: string): boolean {+ const key = `${sourceId}|${slug}`;+ if (this.claimed.has(key)) return false;+ this.claimed.add(key);+ return true;+ }++ get size(): number { return this.claimed.size; }+}++/**+ * Lists one source's pages of `type` in slug order, `batchSize` at a time,+ * resuming each window after the last slug of the previous one. A window+ * shorter than `batchSize` ends the walk.+ */+export async function* listConversationPagesBySlug(engine: BrainEngine,+ opts: { type: string; sourceId: string; batchSize: number }): AsyncGenerator<Page[]> {+ let slugAfter: string | undefined;+ for (;;) {+ const batch = await engine.listPages({ type: opts.type, sourceId: opts.sourceId, sort: 'slug', slugAfter, limit: opts.batchSize });+ if (batch.length === 0) return;+ yield batch;+ if (batch.length < opts.batchSize) return;+ slugAfter = batch.at(-1)!.slug;+ }+}diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsindex 72d3fb61ea..3d37268c28 100644--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@ -101,8 +101,14 @@ const ROW_BYTES = 4096;/** One embedding dimension as JSON text ("-0.012345678901234567,"). */const DIMENSION_BYTES = 24;-/** Request error codes that fail the same way on every retry. */-const DETERMINISTIC_CODES = new Set(['invalid_params', 'permission_denied', 'request_too_large', 'payload_too_large']);+/**+ * Request error codes that fail the same way on every retry. `invalid_params`+ * is not one (#6500): the envelope validator refuses a batch that names a page+ * twice, which is the run's fault, never a member's, so the stored entries+ * resubmit (de-duplicated) and MAX_GENERATION_ATTEMPTS bounds a genuinely+ * malformed envelope.+ */+const DETERMINISTIC_CODES = new Set(['permission_denied', 'request_too_large', 'payload_too_large']);/** Retryable codes whose stored entries are stale: the next attempt extracts again. */const REEXTRACT_CODES = new Set(['embedding_configuration', 'revision_conflict', 'page_identity_changed', 'page_not_found']);const OUTCOME_SOURCES = new Set([TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE]);@@ -202,11 +208,16 @@ export async function loadGenerationIndex(engine: BrainEngine, authority: Mainte[authority.writer.principal.kind, authority.writer.principal.id, authority.writer.sourceId, ANCHOR_SLUG]);const index = new Map<string, GenerationHistory>();for (const row of rows) {- for (const member of row.members ?? []) {- const history = index.get(member.generation) ?? { pending: null, failed: [] };- if (!isTerminal(row as unknown as WriteRequest)) history.pending = { id: row.id, attempt: Number(member.attempt) };- else history.failed.push({ id: row.id, requestId: row.request_id, code: row.error_code ?? row.state, attempt: Number(member.attempt) });- index.set(member.generation, history);+ // One history entry per DISTINCT request (#6500): an envelope that listed a+ // generation several times failed once, not once per member, so it counts+ // once toward MAX_GENERATION_ATTEMPTS; the member attempt is the largest.+ const attempts = new Map<string, number>();+ for (const member of row.members ?? []) attempts.set(member.generation, Math.max(attempts.get(member.generation) ?? 0, Number(member.attempt)));+ for (const [generation, attempt] of attempts) {+ const history = index.get(generation) ?? { pending: null, failed: [] };+ if (!isTerminal(row as unknown as WriteRequest)) history.pending = { id: row.id, attempt };+ else history.failed.push({ id: row.id, requestId: row.request_id, code: row.error_code ?? row.state, attempt });+ index.set(generation, history);}}return index;@@ -538,6 +549,8 @@ const RUN_STOPPING = new WeakSet<object>();export interface ManagedRunCounters {pages_processed: number; pages_marked_non_extractable: number; pages_skipped_too_large: number; pages_failed: number;orphan_facts_cleaned: number; facts_inserted: number; pages_pending?: number; pages_blocked?: number;+ /** Pages the run listed more than once and extracted once (#6500). */+ pages_skipped_duplicate_listing?: number;}interface ManagedRunState {@@ -667,6 +680,20 @@ export async function enqueueManagedPage(state: ManagedRunState, snapshot: PageSasync function enqueueEntry(state: ManagedRunState, entry: ConversationPageEntry): Promise<void> {const m = state.managed!;+ // De-dup before the byte-cap flush (#6500): the envelope validator refuses a+ // batch naming a page twice. The same generation is the same frozen rows, so+ // the newcomer is dropped; a different generation means the page moved+ // between the two reads, so the earlier entry publishes first (apply skips it+ // as stale) and the newcomer opens the next batch.+ const held = m.batch.find(e => e.slug === entry.slug);+ if (held) {+ if (held.generation === entry.generation) {+ state.result.pages_skipped_duplicate_listing = (state.result.pages_skipped_duplicate_listing ?? 0) + 1;+ log(`${entry.slug}: already frozen in this run's batch at the same generation; the second listing is dropped`);+ return;+ }+ await flushManagedBatch(state);+ }const bytes = jsonBytes(entry);const cap = Math.min(batchCaps.bytes, await conversationIntentByteLimit(m.engine) - 65_536);if (m.batch.length && m.bytes + bytes > cap) await flushManagedBatch(state);diff --git a/src/core/types.ts b/src/core/types.tsindex 93beb0331b..7f53bf068d 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -329,6 +329,14 @@ export interface PageFilters {* value re-selects same-millisecond rows.*/updatedAfterKeyset?: { updatedAt: string; slug: string };+ /**+ * Slug keyset cursor: `WHERE p.slug > slugAfter`, paired with `sort: 'slug'`.+ * Single-source contract (#6500): slug is a total order only inside one+ * `sourceId`, so a federated listing (`sourceIds`) keeps offset paging.+ * Resume from the last row's slug; rows touched or deleted mid-walk shift+ * nothing, unlike OFFSET over a tie cluster.+ */+ slugAfter?: string;/*** Prefix-match filter on slug. Implemented as `WHERE slug LIKE prefix || '%'`* in both engines so it uses the (source_id, slug) UNIQUE constraint's btree@@ -420,7 +428,11 @@ export interface GetPageOpts extends PageReadScope {/** v0.29: literal ORDER BY fragments for the PageFilters.sort enum. Whitelisted. */export const PAGE_SORT_SQL: Record<NonNullable<PageFilters['sort']>, string> = {- updated_desc: 'p.updated_at DESC',+ // #6500: the same tiebreakers as updated_asc, so a tie cluster (bulk+ // imports stamp one now() across a transaction) lists deterministically.+ // OFFSET over it is still unstable under timestamp-changing writes; walk+ // a source by `sort: 'slug'` + `slugAfter` when every page must be seen once.+ updated_desc: 'p.updated_at DESC, p.slug DESC, p.source_id DESC, p.id DESC',// v0.45.7: slug tiebreaker makes updated_asc a TOTAL order, so keyset// pagination (updatedAfterKeyset) can page deterministically through a// cluster of pages sharing one updated_at (bulk syncs stamp identicaldiff --git a/test/conversation-facts-keyset-6500.test.ts b/test/conversation-facts-keyset-6500.test.tsnew file mode 100644index 0000000000..654ca01a4d--- /dev/null+++ b/test/conversation-facts-keyset-6500.test.ts@@ -0,0 +1,217 @@+/**+ * #6500: `extract-conversation-facts` listed a page twice under OFFSET paging+ * over `updated_desc` (not a total order), extracted it twice and submitted a+ * batch naming it twice, which the envelope validator refused+ * (`invalid_params`) and then blocked every member deterministically.+ *+ * Protects: (a) `updated_desc` carries slug/source/id tiebreakers so a tie+ * cluster lists deterministically; (b) `slugAfter` keyset enumeration walks a+ * single source's pages exactly once while tied rows are touched mid-walk;+ * (c) one run never extracts or enqueues the same page twice+ * (`pages_skipped_duplicate_listing`); (d) a failed envelope counts once per+ * request, not once per member, so a historical envelope that listed one+ * generation three times is resubmitted from its stored entry; (e) a refused+ * `invalid_params` envelope is retryable and replays its stored entries with+ * zero model calls, while a genuinely malformed replay still reaches+ * MAX_GENERATION_ATTEMPTS and blocks, with the page's prior rows untouched.+ * Fails when: the tiebreaker is missing (insertion order returned), the+ * keyset filter is ignored (the first window repeats), the claimed set is+ * missing (two model calls, refused batch), failures are counted per member+ * (the page is blocked), or `invalid_params` is deterministic (blocked).+ * Seams: the Core's injected extractor and the persistence fault hook.+ * PGLite always; Postgres when DATABASE_URL is set+ * (test/e2e/conversation-facts-keyset-6500-postgres.test.ts).+ */+import { afterEach, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import type { ExtractedFact } from '../src/core/facts/extract.ts';+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';+import { CONVERSATION_FACTS_INTENT, MAX_GENERATION_ATTEMPTS } from '../src/core/facts/conversation-publication.ts';+import { PAGE_SORT_SQL } from '../src/core/types.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { managedBrain, type ManagedBrain } from './helpers/managed-brain.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const SLUG = 'meetings/2026-09-28-plan-sync';+const transcript = () => [+ '---', 'title: Plan sync', 'type: meeting', 'date: 2026-09-28', '---',+ '**Alice Example:** Can you send me the quarterly plan before the review?',+ '**Owner Example:** Yes, I will send it on Thursday with the finance appendix.',+ '**Alice Example:** Good. I review plans on Mondays, so that works.',+ '**Owner Example:** I will flag any launch date changes in the summary.', '',+].join('\n');++afterEach(() => { installFaultHook(undefined); });++async function putPage(brain: ManagedBrain, content: string, slug = SLUG): Promise<void> {+ await submitPageMutation(brain.ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content } });+ await disposePersistenceConsumer(brain.engine);+}++async function extract(engine: BrainEngine, calls: { n: number }, slugs: string[] = [SLUG]) {+ return runExtractConversationFactsCore(engine, { sourceId: 'default', slugs, sleepMs: 0, overrideDisabled: true,+ extractor: async () => {+ calls.n++;+ return [{ fact: 'Owner Example sends the quarterly plan on Thursday', kind: 'commitment', confidence: 0.9, entity_slug: null,+ source: 'test', notability: 'high' } as ExtractedFact];+ } });+}++/** A direct SQL edit of durable rows on the managed brain (seeding history), outside the writer guard. */+async function seedRaw(engine: BrainEngine, sql: string, params: unknown[] = []): Promise<void> {+ await engine.transaction(async tx => {+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true),set_config('gbrain.persistence_protocol','2',true),set_config('gbrain.write_sources','[\"default\"]',true)");+ await tx.executeRaw(sql, params);+ });+ await disposePersistenceConsumer(engine);+}++async function requests(engine: BrainEngine) {+ return engine.executeRaw<{ id: string; state: string; error_code: string | null; members: number }>(+ `SELECT id::text AS id, state, error_code, jsonb_array_length(intent->'pages')::int AS members FROM persistence_requests WHERE intent->>'kind'=$1 ORDER BY sequence`,+ [CONVERSATION_FACTS_INTENT]);+}++async function factsOf(engine: BrainEngine, slug: string) {+ return (await engine.executeRaw<{ fact: string }>(`SELECT fact FROM facts WHERE source_id='default' AND source_markdown_slug=$1+ AND source LIKE 'cli:extract-conversation-facts%' AND expired_at IS NULL ORDER BY row_num`, [slug])).map(r => r.fact);+}++/** One extraction whose publication the owner refuses once (retryable): leaves one failed request holding the page's stored entry. */+async function seedFailedEnvelope(brain: ManagedBrain, calls: { n: number }): Promise<string> {+ let fail = true;+ installFaultHook(async point => { if (point === 'consumer:prepared' && fail) { fail = false; throw Object.assign(new Error('simulated owner crash'), { code: 'storage_error' }); } });+ const first = await extract(brain.engine, calls);+ installFaultHook(undefined);+ expect(first).toMatchObject({ pages_processed: 0, pages_failed: 1 });+ expect(calls.n).toBe(1);+ const [failed] = await requests(brain.engine);+ expect(failed).toMatchObject({ state: 'failed', members: 1 });+ return failed!.id;+}++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test(`${backend}: updated_desc orders a tie cluster by slug and the slug keyset lists each page once while tied rows are touched`, async () => {+ expect(PAGE_SORT_SQL.updated_desc).toBe('p.updated_at DESC, p.slug DESC, p.source_id DESC, p.id DESC');+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ const slugs = Array.from({ length: 200 }, (_, i) => `meetings/m${String(i).padStart(3, '0')}`);+ for (const slug of slugs) await engine.putPage(slug, { type: 'meeting', title: slug, compiled_truth: `# ${slug}\n\nbody` });+ await engine.executeRaw(`UPDATE pages SET updated_at = '2026-01-01T00:00:00Z' WHERE source_id='default' AND type='meeting'`);++ const desc = await engine.listPages({ type: 'meeting', sourceId: 'default', limit: 200 });+ expect(desc.map(p => p.slug)).toEqual([...slugs].sort().reverse());++ // Keyset walk, touching an already-listed tied row between windows (what any concurrent stamp or connector write does).+ const seen: string[] = [];+ let after: string | undefined;+ for (let window = 0; window < 25; window++) {+ const batch = await engine.listPages({ type: 'meeting', sourceId: 'default', sort: 'slug', slugAfter: after, limit: 10 });+ if (batch.length === 0) break;+ seen.push(...batch.map(p => p.slug));+ after = batch.at(-1)!.slug;+ await engine.executeRaw(`UPDATE pages SET title = title || ' (touched)' WHERE source_id='default' AND slug=$1`, [batch[0]!.slug]);+ if (batch.length < 10) break;+ }+ expect(seen.length).toBe(200);+ expect(new Set(seen).size).toBe(200);+ expect([...seen].sort()).toEqual(slugs);++ // The offset walk over updated_desc is deterministic for fixed timestamps too.+ const offsetSeen: string[] = [];+ for (let offset = 0; offset < 200; offset += 10) {+ const batch = await engine.listPages({ type: 'meeting', sourceId: 'default', limit: 10, offset });+ offsetSeen.push(...batch.map(p => p.slug));+ await engine.executeRaw(`UPDATE pages SET title = title || ' (again)' WHERE source_id='default' AND slug=$1`, [batch[0]!.slug]);+ }+ expect(offsetSeen).toEqual([...slugs].sort().reverse());+ } finally { await close(); }+ }, 120_000);++ test(`${backend}: the same page fed twice to one run is extracted once and published in one request`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ await putPage(brain, transcript());+ const calls = { n: 0 };+ const result = await extract(engine, calls, [SLUG, SLUG]);+ expect(calls.n).toBe(1);+ expect(result).toMatchObject({ pages_processed: 1, facts_inserted: 1, pages_failed: 0, pages_skipped_duplicate_listing: 1 });+ expect(await requests(engine)).toMatchObject([{ state: 'committed', error_code: null, members: 1 }]);+ expect(await factsOf(engine, SLUG)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);+ }, { databaseUrl });+ }, 120_000);++ test(`${backend}: one failed envelope holding a generation three times counts as one failed request; its stored entry is resubmitted without a model call`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ await putPage(brain, transcript());+ const calls = { n: 0 };+ const id = await seedFailedEnvelope(brain, calls);+ // A historical envelope that listed the page three times (the reporter's refused batch shape).+ await seedRaw(engine, `UPDATE persistence_requests SET intent = jsonb_set(intent, '{pages}', (intent->'pages') || (intent->'pages') || (intent->'pages')) WHERE id=$1::uuid`, [id]);+ expect((await requests(engine))[0]).toMatchObject({ state: 'failed', members: 3 });+ const second = await extract(engine, calls);+ expect(second).toMatchObject({ pages_processed: 1, facts_inserted: 1, pages_failed: 0 });+ expect(second.pages_blocked ?? 0).toBe(0);+ expect(calls.n).toBe(1);+ expect((await requests(engine)).map(r => r.state)).toEqual(['failed', 'committed']);+ expect(await factsOf(engine, SLUG)).toEqual(['Owner Example sends the quarterly plan on Thursday', 'EXTRACTION_COMPLETE']);+ }, { databaseUrl });+ }, 120_000);++ test(`${backend}: a refused invalid_params envelope is resubmitted from its stored entries with zero model calls`, async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ await putPage(brain, transcript());+ const calls = { n: 0 };+ const id = await seedFailedEnvelope(brain, calls);+ await seedRaw(engine, `UPDATE persistence_requests SET error_code='invalid_params', error_message='names a page twice' WHERE id=$1::uuid`, [id]);+ const second = await extract(engine, calls);+ expect(second).toMatchObject({ pages_processed: 1, facts_inserted: 1 });+ expect(calls.n).toBe(1);+ expect((await requests(engine)).map(r => [r.state, r.error_code])).toEqual([['failed', 'invalid_params'], ['committed', null]]);+ }, { databaseUrl });+ }, 120_000);+}++test('pglite: a genuinely malformed envelope replays its stored entries with zero model calls until MAX_GENERATION_ATTEMPTS, then stays blocked; the page\'s rows are untouched', async () => {+ await managedBrain(async brain => {+ const { engine } = brain;+ await putPage(brain, transcript());+ // A prior row from another writer on the same page: the refused replays must leave it alone.+ await seedRaw(engine, `INSERT INTO facts (source_id, fact, kind, source, source_markdown_slug, visibility) VALUES ('default', 'A manual note about the plan', 'fact', 'manual', $1, 'private')`, [SLUG]);+ const rowsBefore = await engine.executeRaw<{ id: number; fact: string }>(`SELECT id, fact FROM facts WHERE source_id='default' AND source_markdown_slug=$1 ORDER BY id`, [SLUG]);+ expect(rowsBefore).toHaveLength(1);+ const calls = { n: 0 };+ const id = await seedFailedEnvelope(brain, calls);+ // The stored member names no page: every replay of this envelope is refused by the validator.+ await seedRaw(engine, `UPDATE persistence_requests SET intent = jsonb_set(intent, '{pages,0,slug}', '""'::jsonb) WHERE id=$1::uuid`, [id]);+ const lines: string[] = [];+ const write = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return write(chunk); }) as typeof process.stderr.write;+ try {+ for (let attempt = 2; attempt <= MAX_GENERATION_ATTEMPTS; attempt++) {+ const replay = await extract(engine, calls);+ expect(replay).toMatchObject({ pages_processed: 0, pages_failed: 1 });+ expect(replay.pages_blocked ?? 0).toBe(0);+ expect((await requests(engine)).map(r => r.state)).toEqual(Array(attempt).fill('failed'));+ expect((await requests(engine)).at(-1)!.error_code).toBe('invalid_params');+ }+ const blocked = await extract(engine, calls);+ expect(blocked).toMatchObject({ pages_processed: 0, pages_failed: 0, pages_blocked: 1 });+ expect((await requests(engine)).map(r => r.state)).toEqual(Array(MAX_GENERATION_ATTEMPTS).fill('failed'));+ expect(lines.join('')).toContain(`${MAX_GENERATION_ATTEMPTS} batch requests holding it failed at this page version, so no model call runs again until the page changes`);+ expect(lines.join('')).toContain('gbrain write-request --');+ // The bound is durable: a fresh run still blocks.+ expect((await extract(engine, calls)).pages_blocked).toBe(1);+ } finally { process.stderr.write = write; }+ expect(calls.n).toBe(1);+ expect(await engine.executeRaw(`SELECT id, fact FROM facts WHERE source_id='default' AND source_markdown_slug=$1 ORDER BY id`, [SLUG])).toEqual(rowsBefore);+ });+}, 120_000);diff --git a/test/e2e/conversation-facts-keyset-6500-postgres.test.ts b/test/e2e/conversation-facts-keyset-6500-postgres.test.tsnew file mode 100644index 0000000000..7ba8b81d8f--- /dev/null+++ b/test/e2e/conversation-facts-keyset-6500-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../conversation-facts-keyset-6500.test.ts'));