From bad53e32fe352ed9dd17894524d2bf50af1d5b86 Mon Sep 17 00:00:00 2001 From: Agent Console Contributors <33415988+zhx8702@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:29:10 +0800 Subject: [PATCH 1/5] feat(memory): automate group relationship extraction --- .env.example | 54 ++- app/common/config.py | 27 +- docker-compose.yml | 27 +- plugins/memory/plugin.py | 74 ++++ plugins/memory/router.py | 4 + plugins/memory/store_group_graph.py | 303 +++++++++++++++- tests/unit/test_config_precedence.py | 28 ++ .../test_memory_group_graph_auto_extract.py | 343 ++++++++++++++++++ tests/unit/test_memory_router.py | 2 + 9 files changed, 828 insertions(+), 34 deletions(-) create mode 100644 tests/unit/test_memory_group_graph_auto_extract.py diff --git a/.env.example b/.env.example index ab92a2b..13ca216 100644 --- a/.env.example +++ b/.env.example @@ -83,21 +83,21 @@ ORCHESTRATOR_FLOW_SHADOW_MODE=noop ORCHESTRATOR_FLOW_SHADOW_CORE_PREVIEW_ENABLED=false ORCHESTRATOR_FLOW_SHADOW_PLUGIN_DRY_RUN_ENABLED=false ORCHESTRATOR_FLOW_SHADOW_EFFECT_DRY_RUN_ENABLED=false -MEMORY_LLM_EXTRACTION_ENABLED=false -MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS=1.0 +MEMORY_LLM_EXTRACTION_ENABLED=true +MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS=30.0 MEMORY_LLM_EXTRACTION_MAX_ACTIONS=4 MEMORY_LLM_EXTRACTION_MIN_CONFIDENCE=0.75 MEMORY_ACCEPTANCE_AUTO_ACCEPT_MIN=0.78 MEMORY_ACCEPTANCE_REJECT_BELOW=0.35 MEMORY_LLM_EXTRACTION_JOB_ENABLED=true -MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED=false +MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED=true MEMORY_LLM_EXTRACTION_JOB_SCOPE_ALLOWLIST= MEMORY_LLM_EXTRACTION_JOB_DRAIN_BATCH_SIZE=5 MEMORY_LLM_EXTRACTION_JOB_DRAIN_MAX_CLAIMS=0 MEMORY_LLM_EXTRACTION_JOB_MAX_ATTEMPTS=3 MEMORY_LLM_EXTRACTION_JOB_BACKOFF_SECONDS=30.0 -MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS=5.0 -MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS=60.0 +MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS=90.0 +MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS=150.0 MEMORY_LLM_EXTRACTION_JOB_DRAIN_INTERVAL_SECONDS=5.0 MEMORY_RETRIEVAL_ENABLED=true MEMORY_HYBRID_RETRIEVAL_ENABLED=false @@ -114,13 +114,13 @@ MEMORY_VECTOR_TIMEOUT_SECONDS=2.0 MEMORY_VECTOR_TOP_K=12 MEMORY_GRAPH_VECTOR_TOP_K=12 MEMORY_VECTOR_INDEX_STRICT_STARTUP_CHECK=false -MEMORY_GRAPH_RETRIEVAL_ENABLED=false +MEMORY_GRAPH_RETRIEVAL_ENABLED=true MEMORY_GRAPH_RETRIEVAL_FACT_TOP_K=3 MEMORY_GRAPH_RETRIEVAL_EPISODE_TOP_K=2 MEMORY_GRAPH_RETRIEVAL_BUDGET_CHARS=600 # Runtime app setting for non-Compose launches; Docker Compose uses COMPOSE_* flags below. -MEMORY_GRAPH_LLM_EXTRACTION_ENABLED=false -MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS=1.0 +MEMORY_GRAPH_LLM_EXTRACTION_ENABLED=true +MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS=90.0 MEMORY_GRAPH_LLM_EXTRACTION_MAX_ACTIONS=16 MEMORY_GRAPH_LLM_EXTRACTION_MAX_ENTITIES=8 MEMORY_GRAPH_LLM_EXTRACTION_MAX_FACTS=4 @@ -128,6 +128,17 @@ MEMORY_GRAPH_LLM_EXTRACTION_MAX_EPISODES=2 MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE=0.8 MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED=true MEMORY_GOVERNANCE_INTERVAL_SECONDS=86400 +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED=true +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED=true +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS=3600 +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LOOKBACK_DAYS=7 +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_SESSIONS_PER_TICK=10 +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_WINDOWS_PER_SESSION=20 +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE=50 +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS=180 +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES=scheduler +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=true +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES=200 MEMORY_NEEDS_REVIEW_RETENTION_DAYS=30 MEMORY_REJECTED_RETENTION_DAYS=7 MEMORY_AUTO_EXPIRE_DAYS=180 @@ -352,21 +363,21 @@ COMPOSE_ORCHESTRATOR_FLOW_SHADOW_PLUGIN_DRY_RUN_ENABLED=false COMPOSE_ORCHESTRATOR_FLOW_SHADOW_EFFECT_DRY_RUN_ENABLED=false COMPOSE_MEMORY_RETRIEVAL_ENABLED=true COMPOSE_MEMORY_HYBRID_RETRIEVAL_ENABLED=false -COMPOSE_MEMORY_LLM_EXTRACTION_ENABLED=false -COMPOSE_MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS=1.0 +COMPOSE_MEMORY_LLM_EXTRACTION_ENABLED=true +COMPOSE_MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS=30.0 COMPOSE_MEMORY_LLM_EXTRACTION_MAX_ACTIONS=4 COMPOSE_MEMORY_LLM_EXTRACTION_MIN_CONFIDENCE=0.75 COMPOSE_MEMORY_ACCEPTANCE_AUTO_ACCEPT_MIN=0.78 COMPOSE_MEMORY_ACCEPTANCE_REJECT_BELOW=0.35 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_ENABLED=true -COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED=false +COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED=true COMPOSE_MEMORY_LLM_EXTRACTION_JOB_SCOPE_ALLOWLIST= COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_BATCH_SIZE=5 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_MAX_CLAIMS=0 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_MAX_ATTEMPTS=3 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_BACKOFF_SECONDS=30.0 -COMPOSE_MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS=5.0 -COMPOSE_MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS=60.0 +COMPOSE_MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS=90.0 +COMPOSE_MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS=150.0 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_INTERVAL_SECONDS=5.0 COMPOSE_MEMORY_GROUP_IDENTITY_MEMORY_ENABLED=false COMPOSE_MEMORY_RETRIEVAL_TOP_K=6 @@ -379,12 +390,12 @@ COMPOSE_MEMORY_VECTOR_TIMEOUT_SECONDS=2.0 COMPOSE_MEMORY_VECTOR_TOP_K=12 COMPOSE_MEMORY_GRAPH_VECTOR_TOP_K=12 COMPOSE_MEMORY_VECTOR_INDEX_STRICT_STARTUP_CHECK=false -COMPOSE_MEMORY_GRAPH_RETRIEVAL_ENABLED=false +COMPOSE_MEMORY_GRAPH_RETRIEVAL_ENABLED=true COMPOSE_MEMORY_GRAPH_RETRIEVAL_FACT_TOP_K=3 COMPOSE_MEMORY_GRAPH_RETRIEVAL_EPISODE_TOP_K=2 COMPOSE_MEMORY_GRAPH_RETRIEVAL_BUDGET_CHARS=600 -COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_ENABLED=false -COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS=1.0 +COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_ENABLED=true +COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS=90.0 COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_ACTIONS=16 COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_ENTITIES=8 COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_FACTS=4 @@ -392,6 +403,17 @@ COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_EPISODES=2 COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE=0.8 COMPOSE_MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED=true COMPOSE_MEMORY_GOVERNANCE_INTERVAL_SECONDS=86400 +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED=true +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED=true +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS=3600 +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LOOKBACK_DAYS=7 +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_SESSIONS_PER_TICK=10 +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_WINDOWS_PER_SESSION=20 +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE=50 +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS=180 +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES=scheduler +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=true +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES=200 COMPOSE_MEMORY_NEEDS_REVIEW_RETENTION_DAYS=30 COMPOSE_MEMORY_REJECTED_RETENTION_DAYS=7 COMPOSE_MEMORY_AUTO_EXPIRE_DAYS=180 diff --git a/app/common/config.py b/app/common/config.py index 9c2e7b0..270841b 100644 --- a/app/common/config.py +++ b/app/common/config.py @@ -344,21 +344,21 @@ def guarded_dotenv_settings() -> dict[str, Any]: orchestrator_flow_shadow_core_preview_enabled: bool = False orchestrator_flow_shadow_plugin_dry_run_enabled: bool = False orchestrator_flow_shadow_effect_dry_run_enabled: bool = False - memory_llm_extraction_enabled: bool = False - memory_llm_extraction_timeout_seconds: float = Field(default=1.0, gt=0) + memory_llm_extraction_enabled: bool = True + memory_llm_extraction_timeout_seconds: float = Field(default=30.0, gt=0) memory_llm_extraction_max_actions: int = Field(default=4, ge=1) memory_llm_extraction_min_confidence: float = Field(default=0.75, ge=0.0, le=1.0) memory_acceptance_auto_accept_min: float = Field(default=0.78, ge=0.0, le=1.0) memory_acceptance_reject_below: float = Field(default=0.35, ge=0.0, le=1.0) memory_llm_extraction_job_enabled: bool = True - memory_llm_extraction_job_drain_enabled: bool = False + memory_llm_extraction_job_drain_enabled: bool = True memory_llm_extraction_job_scope_allowlist: str = "" memory_llm_extraction_job_drain_batch_size: int = Field(default=5, ge=1) memory_llm_extraction_job_drain_max_claims: int = Field(default=0, ge=0) memory_llm_extraction_job_max_attempts: int = Field(default=3, ge=1) memory_llm_extraction_job_backoff_seconds: float = Field(default=30.0, gt=0) - memory_llm_extraction_job_timeout_seconds: float = Field(default=5.0, gt=0) - memory_llm_extraction_job_lock_ttl_seconds: float = Field(default=60.0, gt=0) + memory_llm_extraction_job_timeout_seconds: float = Field(default=90.0, gt=0) + memory_llm_extraction_job_lock_ttl_seconds: float = Field(default=150.0, gt=0) memory_llm_extraction_job_drain_interval_seconds: float = Field(default=5.0, gt=0) memory_retrieval_enabled: bool = True # Identity-wide memory can contain facts learned in private conversations. @@ -376,12 +376,12 @@ def guarded_dotenv_settings() -> dict[str, Any]: memory_vector_top_k: int = Field(default=12, ge=1, le=100) memory_graph_vector_top_k: int = Field(default=12, ge=1, le=100) memory_vector_index_strict_startup_check: bool = False - memory_graph_retrieval_enabled: bool = False + memory_graph_retrieval_enabled: bool = True memory_graph_retrieval_fact_top_k: int = Field(default=3, ge=1, le=10) memory_graph_retrieval_episode_top_k: int = Field(default=2, ge=1, le=10) memory_graph_retrieval_budget_chars: int = Field(default=600, ge=100, le=3000) - memory_graph_llm_extraction_enabled: bool = False - memory_graph_llm_extraction_timeout_seconds: float = Field(default=1.0, gt=0) + memory_graph_llm_extraction_enabled: bool = True + memory_graph_llm_extraction_timeout_seconds: float = Field(default=90.0, gt=0) memory_graph_llm_extraction_max_actions: int = Field(default=16, ge=1) memory_graph_llm_extraction_max_entities: int = Field(default=8, ge=1) memory_graph_llm_extraction_max_facts: int = Field(default=4, ge=1) @@ -389,6 +389,17 @@ def guarded_dotenv_settings() -> dict[str, Any]: memory_graph_llm_extraction_min_confidence: float = Field(default=0.8, ge=0.0, le=1.0) memory_governance_auto_cleanup_enabled: bool = True memory_governance_interval_seconds: float = Field(default=86_400.0, gt=0) + memory_group_graph_auto_extract_enabled: bool = True + memory_group_graph_auto_extract_llm_enabled: bool = True + memory_group_graph_auto_extract_interval_seconds: float = Field(default=3_600.0, gt=0) + memory_group_graph_auto_extract_lookback_days: int = Field(default=7, ge=1, le=14) + memory_group_graph_auto_extract_max_sessions_per_tick: int = Field(default=10, ge=1, le=20) + memory_group_graph_auto_extract_max_windows_per_session: int = Field(default=20, ge=1, le=100) + memory_group_graph_auto_extract_window_size: int = Field(default=50, ge=10, le=100) + memory_group_graph_auto_extract_time_budget_seconds: int = Field(default=180, ge=5, le=180) + memory_group_graph_auto_extract_roles: str = "scheduler" + memory_group_graph_auto_extract_sync_enabled: bool = True + memory_group_graph_auto_extract_sync_max_messages: int = Field(default=200, ge=20, le=500) memory_needs_review_retention_days: int = Field(default=30, ge=1) memory_rejected_retention_days: int = Field(default=7, ge=1) memory_auto_expire_days: int = Field(default=180, ge=1) diff --git a/docker-compose.yml b/docker-compose.yml index 0300763..178a5fd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -89,21 +89,21 @@ x-app-env: &app-env ORCHESTRATOR_FLOW_SHADOW_EFFECT_DRY_RUN_ENABLED: ${COMPOSE_ORCHESTRATOR_FLOW_SHADOW_EFFECT_DRY_RUN_ENABLED:-false} MEMORY_RETRIEVAL_ENABLED: ${COMPOSE_MEMORY_RETRIEVAL_ENABLED:-true} MEMORY_HYBRID_RETRIEVAL_ENABLED: ${COMPOSE_MEMORY_HYBRID_RETRIEVAL_ENABLED:-false} - MEMORY_LLM_EXTRACTION_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_ENABLED:-false} - MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS:-1.0} + MEMORY_LLM_EXTRACTION_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_ENABLED:-true} + MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS:-30.0} MEMORY_LLM_EXTRACTION_MAX_ACTIONS: ${COMPOSE_MEMORY_LLM_EXTRACTION_MAX_ACTIONS:-4} MEMORY_LLM_EXTRACTION_MIN_CONFIDENCE: ${COMPOSE_MEMORY_LLM_EXTRACTION_MIN_CONFIDENCE:-0.75} MEMORY_ACCEPTANCE_AUTO_ACCEPT_MIN: ${COMPOSE_MEMORY_ACCEPTANCE_AUTO_ACCEPT_MIN:-0.78} MEMORY_ACCEPTANCE_REJECT_BELOW: ${COMPOSE_MEMORY_ACCEPTANCE_REJECT_BELOW:-0.35} MEMORY_LLM_EXTRACTION_JOB_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_ENABLED:-true} - MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED:-false} + MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED:-true} MEMORY_LLM_EXTRACTION_JOB_SCOPE_ALLOWLIST: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_SCOPE_ALLOWLIST:-} MEMORY_LLM_EXTRACTION_JOB_DRAIN_BATCH_SIZE: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_BATCH_SIZE:-5} MEMORY_LLM_EXTRACTION_JOB_DRAIN_MAX_CLAIMS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_MAX_CLAIMS:-0} MEMORY_LLM_EXTRACTION_JOB_MAX_ATTEMPTS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_MAX_ATTEMPTS:-3} MEMORY_LLM_EXTRACTION_JOB_BACKOFF_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_BACKOFF_SECONDS:-30.0} - MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS:-5.0} - MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS:-60.0} + MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS:-90.0} + MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS:-150.0} MEMORY_LLM_EXTRACTION_JOB_DRAIN_INTERVAL_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_INTERVAL_SECONDS:-5.0} MEMORY_GROUP_IDENTITY_MEMORY_ENABLED: ${COMPOSE_MEMORY_GROUP_IDENTITY_MEMORY_ENABLED:-false} MEMORY_RETRIEVAL_TOP_K: ${COMPOSE_MEMORY_RETRIEVAL_TOP_K:-6} @@ -116,12 +116,12 @@ x-app-env: &app-env MEMORY_VECTOR_TOP_K: ${COMPOSE_MEMORY_VECTOR_TOP_K:-12} MEMORY_GRAPH_VECTOR_TOP_K: ${COMPOSE_MEMORY_GRAPH_VECTOR_TOP_K:-12} MEMORY_VECTOR_INDEX_STRICT_STARTUP_CHECK: ${COMPOSE_MEMORY_VECTOR_INDEX_STRICT_STARTUP_CHECK:-false} - MEMORY_GRAPH_RETRIEVAL_ENABLED: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_ENABLED:-false} + MEMORY_GRAPH_RETRIEVAL_ENABLED: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_ENABLED:-true} MEMORY_GRAPH_RETRIEVAL_FACT_TOP_K: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_FACT_TOP_K:-3} MEMORY_GRAPH_RETRIEVAL_EPISODE_TOP_K: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_EPISODE_TOP_K:-2} MEMORY_GRAPH_RETRIEVAL_BUDGET_CHARS: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_BUDGET_CHARS:-600} - MEMORY_GRAPH_LLM_EXTRACTION_ENABLED: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_ENABLED:-false} - MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS:-1.0} + MEMORY_GRAPH_LLM_EXTRACTION_ENABLED: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_ENABLED:-true} + MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS:-90.0} MEMORY_GRAPH_LLM_EXTRACTION_MAX_ACTIONS: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_ACTIONS:-16} MEMORY_GRAPH_LLM_EXTRACTION_MAX_ENTITIES: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_ENTITIES:-8} MEMORY_GRAPH_LLM_EXTRACTION_MAX_FACTS: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_FACTS:-4} @@ -129,6 +129,17 @@ x-app-env: &app-env MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE:-0.8} MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED: ${COMPOSE_MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED:-true} MEMORY_GOVERNANCE_INTERVAL_SECONDS: ${COMPOSE_MEMORY_GOVERNANCE_INTERVAL_SECONDS:-86400} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED:-true} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED:-true} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS:-3600} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LOOKBACK_DAYS: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LOOKBACK_DAYS:-7} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_SESSIONS_PER_TICK: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_SESSIONS_PER_TICK:-10} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_WINDOWS_PER_SESSION: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_WINDOWS_PER_SESSION:-20} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE:-50} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS:-180} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES:-scheduler} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED:-true} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES:-200} MEMORY_NEEDS_REVIEW_RETENTION_DAYS: ${COMPOSE_MEMORY_NEEDS_REVIEW_RETENTION_DAYS:-30} MEMORY_REJECTED_RETENTION_DAYS: ${COMPOSE_MEMORY_REJECTED_RETENTION_DAYS:-7} MEMORY_AUTO_EXPIRE_DAYS: ${COMPOSE_MEMORY_AUTO_EXPIRE_DAYS:-180} diff --git a/plugins/memory/plugin.py b/plugins/memory/plugin.py index 2c49916..69a11bf 100644 --- a/plugins/memory/plugin.py +++ b/plugins/memory/plugin.py @@ -44,6 +44,7 @@ def __init__(self) -> None: self._ctx: PluginContext | None = None self._effect_handler_enabled = False self._governance_task: asyncio.Task[None] | None = None + self._group_graph_auto_extract_task: asyncio.Task[None] | None = None async def initialize(self, ctx: PluginContext) -> None: self._ctx = ctx @@ -72,6 +73,11 @@ async def initialize(self, ctx: PluginContext) -> None: self._governance_loop(), name="memory-governance-cleanup", ) + if self._should_run_group_graph_auto_extract(): + self._group_graph_auto_extract_task = asyncio.create_task( + self._group_graph_auto_extract_loop(), + name="memory-group-graph-auto-extract", + ) async def _scope_execution_allowed( self, @@ -148,6 +154,10 @@ async def shutdown(self) -> None: self._governance_task.cancel() await asyncio.gather(self._governance_task, return_exceptions=True) self._governance_task = None + if self._group_graph_auto_extract_task is not None: + self._group_graph_auto_extract_task.cancel() + await asyncio.gather(self._group_graph_auto_extract_task, return_exceptions=True) + self._group_graph_auto_extract_task = None self._store = None self._ctx = None self._effect_handler_enabled = False @@ -174,6 +184,70 @@ async def _governance_loop(self) -> None: ) await asyncio.sleep(max(60.0, interval)) + def _should_run_group_graph_auto_extract(self) -> bool: + if self._ctx is None: + return False + if not bool(getattr(self._ctx.settings, "memory_group_graph_auto_extract_enabled", True)): + return False + role = str(getattr(self._ctx.settings, "app_process_role", "api") or "api").strip().lower() + raw = str( + getattr(self._ctx.settings, "memory_group_graph_auto_extract_roles", "scheduler") + or "scheduler" + ) + roles = {item.strip().lower() for item in raw.split(",") if item.strip()} + return role in roles + + async def _group_graph_auto_extract_loop(self) -> None: + while self._store is not None and self._ctx is not None: + try: + settings = self._ctx.settings + await self._store.run_group_graph_auto_extract_tick( + lookback_days=int( + getattr(settings, "memory_group_graph_auto_extract_lookback_days", 7) or 7 + ), + max_sessions=int( + getattr(settings, "memory_group_graph_auto_extract_max_sessions_per_tick", 10) + or 10 + ), + max_windows_per_session=int( + getattr(settings, "memory_group_graph_auto_extract_max_windows_per_session", 20) + or 20 + ), + window_size=int( + getattr(settings, "memory_group_graph_auto_extract_window_size", 50) or 50 + ), + time_budget_seconds=int( + getattr(settings, "memory_group_graph_auto_extract_time_budget_seconds", 180) + or 180 + ), + include_llm=bool( + getattr(settings, "memory_group_graph_auto_extract_llm_enabled", True) + ), + sync_missing_history=bool( + getattr(settings, "memory_group_graph_auto_extract_sync_enabled", True) + ), + sync_max_messages=int( + getattr(settings, "memory_group_graph_auto_extract_sync_max_messages", 200) + or 200 + ), + ) + except asyncio.CancelledError: + raise + except Exception as exc: + logger.exception( + "memory.group_graph_auto_extract_failed", + error_type=exc.__class__.__name__, + ) + interval = float( + getattr( + self._ctx.settings, + "memory_group_graph_auto_extract_interval_seconds", + 3_600.0, + ) + or 3_600.0 + ) + await asyncio.sleep(max(60.0, interval)) + def get_api_router(self): if self._store is None: return None diff --git a/plugins/memory/router.py b/plugins/memory/router.py index 9d823d6..0c91265 100644 --- a/plugins/memory/router.py +++ b/plugins/memory/router.py @@ -466,6 +466,7 @@ class MemoryWindowRelationshipExtractionRequest(StrictRequestModel): max_windows: int | None = None cursor_event_id: int | None = None dry_run: bool = False + include_llm: bool = True def extraction_controls(self) -> dict[str, int | bool]: return { @@ -473,6 +474,7 @@ def extraction_controls(self) -> dict[str, int | bool]: "max_windows": max(1, min(int(self.max_windows or 1), 10)), "cursor_event_id": max(0, int(self.cursor_event_id or 0)), "dry_run": bool(self.dry_run), + "include_llm": bool(self.include_llm), } @@ -488,6 +490,7 @@ class MemoryWindowRelationshipCatchupRequest(StrictRequestModel): cursor_event_id: int | None = None dry_run: bool = False time_budget_seconds: int | None = None + include_llm: bool = True def extraction_controls(self) -> dict[str, int | bool]: return { @@ -496,6 +499,7 @@ def extraction_controls(self) -> dict[str, int | bool]: "cursor_event_id": max(0, int(self.cursor_event_id or 0)), "dry_run": bool(self.dry_run), "time_budget_seconds": max(1, min(int(self.time_budget_seconds or 60), 180)), + "include_llm": bool(self.include_llm), } diff --git a/plugins/memory/store_group_graph.py b/plugins/memory/store_group_graph.py index ae8d9c5..85f6f4d 100644 --- a/plugins/memory/store_group_graph.py +++ b/plugins/memory/store_group_graph.py @@ -5,7 +5,7 @@ import json import re from collections.abc import Iterable -from datetime import timedelta +from datetime import UTC, datetime, timedelta from typing import Any from app.common.types import ChatMessage, ChatRequest, Role @@ -64,6 +64,36 @@ def monotonic() -> float: return _store_runtime.monotonic() +def _group_graph_item_value(item: dict[str, Any] | None) -> dict[str, Any]: + if not item: + return {} + value = item.get("value") + if isinstance(value, dict): + return value + loaded = _safe_json_loads(item.get("value_json"), {}) + return loaded if isinstance(loaded, dict) else {} + + +def _group_graph_edge_quality(item: dict[str, Any] | None) -> dict[str, Any]: + value = _group_graph_item_value(item) + acceptance = value.get("acceptance") if isinstance(value.get("acceptance"), dict) else {} + dates = value.get("evidence_dates") + evidence_dates = ( + [str(entry).strip()[:10] for entry in dates if str(entry).strip()] + if isinstance(dates, list) + else [] + ) + score = acceptance.get("score") + if score is None: + score = item.get("acceptance_score") if item else None + reason = str(acceptance.get("reason") or (item or {}).get("acceptance_reason") or "").strip() + return { + "evidence_dates": list(dict.fromkeys(evidence_dates))[:90], + "acceptance_score": _clamp_score(score) if score is not None else None, + "acceptance_reason": reason[:80] or None, + } + + class MemoryGroupGraphStoreMixin: async def list_memory_graph_entities( self, @@ -473,6 +503,10 @@ async def get_group_relationship_graph( _append_unique_int(memory_item_ids_for_edge, evidence_item_id) source_ref_count = len(set(source_event_ids)) + len(set(memory_item_ids_for_edge)) + quality = _group_graph_edge_quality(backing_item) + evidence_dates = quality["evidence_dates"] + if not evidence_dates and timestamp: + evidence_dates = [str(timestamp)[:10]] edge = { "id": _group_graph_edge_id(fact), "source": source_node_id, @@ -481,7 +515,10 @@ async def get_group_relationship_graph( "label": predicate, "confidence": confidence, "acceptance_status": edge_acceptance, + "acceptance_score": quality["acceptance_score"], + "acceptance_reason": quality["acceptance_reason"], "evidence_count": max(1, source_ref_count), + "evidence_dates": evidence_dates, "first_seen": timestamp, "last_seen": _group_graph_timestamp(fact, "updated_at", "valid_at", "created_at"), "source_event_ids": source_event_ids, @@ -1182,6 +1219,7 @@ async def run_group_relationship_window_extraction( max_windows: int | None = None, cursor_event_id: int | None = None, dry_run: bool = False, + include_llm: bool = True, ) -> dict[str, Any]: session_id = str(session_id or "").strip() if not session_id: @@ -1260,6 +1298,7 @@ async def run_group_relationship_window_extraction( "max_windows": effective_max_windows, "cursor_event_id": effective_cursor, "dry_run": bool(dry_run), + "include_llm": bool(include_llm), }, "windows": window_summaries, "totals": { @@ -1279,7 +1318,9 @@ async def run_group_relationship_window_extraction( return base_payload llm_available = bool( - self.graph_extractor.config.enabled and self.graph_extractor.llm_service is not None + include_llm + and self.graph_extractor.config.enabled + and self.graph_extractor.llm_service is not None ) total_candidates = 0 @@ -1382,6 +1423,7 @@ async def run_group_relationship_window_catchup( cursor_event_id: int | None = None, dry_run: bool = False, time_budget_seconds: int | None = None, + include_llm: bool = True, ) -> dict[str, Any]: effective_window_size = _clamp_int(window_size, 50, minimum=10, maximum=100) effective_max_windows = _clamp_int(max_windows_per_run, 20, minimum=1, maximum=100) @@ -1395,6 +1437,7 @@ async def run_group_relationship_window_catchup( "cursor_event_id": effective_cursor, "dry_run": bool(dry_run), "time_budget_seconds": effective_time_budget, + "include_llm": bool(include_llm), } windows_processed = 0 more_remain = False @@ -1419,6 +1462,7 @@ async def run_group_relationship_window_catchup( max_windows=batch_limit, cursor_event_id=next_cursor_event_id, dry_run=dry_run, + include_llm=include_llm, ) result_totals = result.get("totals") if isinstance(result.get("totals"), dict) else {} processed = int(result_totals.get("windows") or 0) @@ -1967,6 +2011,261 @@ async def review_group_relationship_edge( "evidence_ids": evidence.get("evidence_ids") or {}, } + async def _group_graph_auto_extract_scope_allowed( + self, + tenant_id: str, + session_id: str, + ) -> bool: + if not bool(getattr(self, "runtime_scope_gates_required", False)): + return True + gate = getattr(self, "combined_history_scope_execution_allowed", None) + if not callable(gate): + return False + try: + return await gate(str(tenant_id or ""), str(session_id or "")) is True + except Exception: + logger.warning( + "memory.group_graph_auto_extract_scope_failed", + tenant_id=tenant_id, + session_id=session_id, + exc_info=True, + ) + return False + + async def list_known_group_graph_sessions( + self, + *, + lookback_days: int = 30, + max_sessions: int = 10, + start_at: datetime | None = None, + ) -> list[dict[str, Any]]: + effective_lookback = _clamp_int(lookback_days, 30, minimum=1, maximum=90) + effective_max_sessions = _clamp_int(max_sessions, 10, minimum=1, maximum=20) + cutoff = start_at or ( + datetime.now(UTC).replace(tzinfo=None) - timedelta(days=effective_lookback) + ) + rows = await _exec( + "SELECT tenant_id, channel, source_key, session_id, " + "COUNT(*) AS event_count, MAX(created_at) AS last_seen " + "FROM plugin_memory_event " + "WHERE created_at >= :start_at " + "AND user_id = :group_uid " + "AND session_id LIKE '%@chatroom' " + "GROUP BY tenant_id, channel, source_key, session_id " + "ORDER BY last_seen DESC, event_count DESC " + "LIMIT :lim", + { + "start_at": cutoff, + "group_uid": GROUP_HISTORY_USER_ID_SCOPE, + "lim": effective_max_sessions, + }, + ) + sessions: list[dict[str, Any]] = [] + for row in rows: + session_id = str(row.get("session_id") or "").strip() + if not _is_group_session_id(session_id): + continue + sessions.append( + { + "tenant_id": str(row.get("tenant_id") or "").strip(), + "channel": str(row.get("channel") or "").strip() or "wechat", + "source_key": str(row.get("source_key") or "").strip() or "wxbot", + "session_id": session_id, + "event_count": int(row.get("event_count") or 0), + } + ) + return sessions + + async def list_imported_group_graph_targets( + self, + *, + lookback_days: int = 7, + max_targets: int = 3, + start_at: datetime | None = None, + ) -> list[dict[str, Any]]: + effective_lookback = _clamp_int(lookback_days, 7, minimum=1, maximum=14) + effective_max_targets = _clamp_int(max_targets, 3, minimum=1, maximum=20) + cutoff = start_at or ( + datetime.now(UTC).replace(tzinfo=None) - timedelta(days=effective_lookback) + ) + fetch_limit = _clamp_int( + effective_max_targets * max(effective_lookback, 1) * 4, + 40, + minimum=10, + maximum=200, + ) + rows = await _exec( + "SELECT tenant_id, channel, source_key, session_id, " + "CAST(created_at AS date) AS day, COUNT(*) AS event_count " + "FROM plugin_memory_event " + "WHERE created_at >= :start_at " + "AND user_id = :group_uid " + "AND session_id LIKE '%@chatroom' " + "GROUP BY tenant_id, channel, source_key, session_id, CAST(created_at AS date) " + "ORDER BY day DESC, event_count DESC " + "LIMIT :lim", + { + "start_at": cutoff, + "group_uid": GROUP_HISTORY_USER_ID_SCOPE, + "lim": fetch_limit, + }, + ) + targets: list[dict[str, Any]] = [] + for row in rows: + session_id = str(row.get("session_id") or "").strip() + if not _is_group_session_id(session_id): + continue + day = row.get("day") + if hasattr(day, "isoformat"): + date_value = day.isoformat() + else: + date_value = str(day or "")[:10] + if not date_value: + continue + targets.append( + { + "tenant_id": str(row.get("tenant_id") or "").strip(), + "channel": str(row.get("channel") or "").strip() or "wechat", + "source_key": str(row.get("source_key") or "").strip() or "wxbot", + "session_id": session_id, + "date": date_value, + "event_count": int(row.get("event_count") or 0), + } + ) + if len(targets) >= effective_max_targets: + break + return targets + + async def run_group_graph_auto_extract_tick( + self, + *, + lookback_days: int = 7, + max_sessions: int = 10, + max_windows_per_session: int = 20, + window_size: int = 50, + time_budget_seconds: int = 180, + include_llm: bool = True, + sync_missing_history: bool = False, + sync_max_messages: int = 200, + ) -> dict[str, Any]: + skipped: list[dict[str, Any]] = [] + synced: list[dict[str, Any]] = [] + if sync_missing_history: + known_sessions = await self.list_known_group_graph_sessions( + lookback_days=max(lookback_days, 14), + max_sessions=max_sessions, + ) + for session in known_sessions: + tenant_id = str(session.get("tenant_id") or "") + session_id = str(session.get("session_id") or "") + if not tenant_id or not session_id: + skipped.append({**session, "reason": "incomplete_scope"}) + continue + if not await self._group_graph_auto_extract_scope_allowed(tenant_id, session_id): + skipped.append({**session, "reason": "scope_disabled"}) + continue + try: + backfill = await self.backfill_from_sdk( + tenant_id=tenant_id, + channel=str(session.get("channel") or "wechat"), + source_key=str(session.get("source_key") or "wxbot"), + user_id=None, + session_ids=[session_id], + connection_id="legacy-wechat-default", + days_limit=lookback_days, + max_messages_per_session=_clamp_int( + sync_max_messages, 200, minimum=20, maximum=500 + ), + enqueue_llm_jobs=True, + ) + except Exception as exc: + logger.warning( + "memory.group_graph_auto_extract_sync_failed", + tenant_id=tenant_id, + session_id=session_id, + error_type=exc.__class__.__name__, + error=_truncate_error(exc), + ) + skipped.append( + { + **session, + "reason": "sync_failed", + "error_type": exc.__class__.__name__, + } + ) + continue + synced.append( + { + **session, + "imported_count": backfill.get("imported_count"), + "events_inserted": backfill.get("events_inserted"), + "ok": backfill.get("ok"), + } + ) + targets = await self.list_imported_group_graph_targets( + lookback_days=lookback_days, + max_targets=max_sessions, + ) + results: list[dict[str, Any]] = [] + for target in targets: + tenant_id = str(target.get("tenant_id") or "") + session_id = str(target.get("session_id") or "") + if not tenant_id or not session_id: + skipped.append({**target, "reason": "incomplete_scope"}) + continue + if not await self._group_graph_auto_extract_scope_allowed(tenant_id, session_id): + skipped.append({**target, "reason": "scope_disabled"}) + continue + try: + catchup = await self.run_group_relationship_window_catchup( + tenant_id=tenant_id, + channel=str(target.get("channel") or "wechat"), + source_key=str(target.get("source_key") or "wxbot"), + session_id=session_id, + date=str(target.get("date") or ""), + window_size=window_size, + max_windows_per_run=max_windows_per_session, + time_budget_seconds=time_budget_seconds, + include_llm=include_llm, + ) + except Exception as exc: + logger.warning( + "memory.group_graph_auto_extract_target_failed", + tenant_id=tenant_id, + session_id=session_id, + date=target.get("date"), + error_type=exc.__class__.__name__, + error=_truncate_error(exc), + ) + results.append( + { + **target, + "status": "failed", + "error_type": exc.__class__.__name__, + } + ) + continue + results.append( + { + **target, + "status": str(catchup.get("status") or ""), + "stop_reason": catchup.get("stop_reason"), + "totals": catchup.get("totals") or {}, + "more_remain": bool(catchup.get("more_remain")), + } + ) + return { + "ok": True, + "lookback_days": _clamp_int(lookback_days, 7, minimum=1, maximum=14), + "include_llm": bool(include_llm), + "sync_missing_history": bool(sync_missing_history), + "target_count": len(targets), + "ran": len([item for item in results if item.get("status") != "failed"]), + "synced": synced, + "skipped": skipped, + "results": results, + } + async def sync_memory_graph( self, *, diff --git a/tests/unit/test_config_precedence.py b/tests/unit/test_config_precedence.py index 86665f7..4645957 100644 --- a/tests/unit/test_config_precedence.py +++ b/tests/unit/test_config_precedence.py @@ -172,6 +172,34 @@ def test_quota_environment_is_part_of_the_settings_contract(monkeypatch) -> None assert settings.tenant_default_daily_tokens == 4321 +def test_memory_llm_extraction_defaults_are_enabled() -> None: + settings = Settings(_env_file=None) + + assert settings.memory_llm_extraction_enabled is True + assert settings.memory_llm_extraction_job_drain_enabled is True + assert settings.memory_graph_llm_extraction_enabled is True + assert settings.memory_group_graph_auto_extract_llm_enabled is True + assert settings.memory_graph_retrieval_enabled is True + assert settings.memory_group_graph_auto_extract_lookback_days == 7 + assert settings.memory_group_graph_auto_extract_sync_enabled is True + assert settings.memory_group_graph_auto_extract_sync_max_messages == 200 + assert settings.memory_llm_extraction_job_timeout_seconds == 90.0 + assert settings.memory_llm_extraction_job_lock_ttl_seconds == 150.0 + + +def test_group_graph_auto_extract_environment_is_part_of_settings_contract(monkeypatch) -> None: + monkeypatch.setenv("MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED", "false") + monkeypatch.setenv("MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED", "true") + monkeypatch.setenv("MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS", "1800") + monkeypatch.setenv("MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES", "scheduler,inbound") + + settings = Settings(_env_file=None) + + assert settings.memory_group_graph_auto_extract_enabled is False + assert settings.memory_group_graph_auto_extract_llm_enabled is True + assert settings.memory_group_graph_auto_extract_interval_seconds == 1800.0 + assert settings.memory_group_graph_auto_extract_roles == "scheduler,inbound" + def test_admin_and_organization_specific_features_default_fail_closed( monkeypatch, ) -> None: diff --git a/tests/unit/test_memory_group_graph_auto_extract.py b/tests/unit/test_memory_group_graph_auto_extract.py new file mode 100644 index 0000000..9a0d5db --- /dev/null +++ b/tests/unit/test_memory_group_graph_auto_extract.py @@ -0,0 +1,343 @@ +from __future__ import annotations + +from datetime import date +from types import SimpleNamespace +from typing import Any + +import pytest + +import plugins.memory.store as memory_store_module +from plugins.memory.plugin import MemoryPlugin +from plugins.memory.store import MemoryStore +from plugins.memory.store_group_graph import _group_graph_edge_quality + + +def test_group_graph_edge_quality_reads_safe_value_payload() -> None: + quality = _group_graph_edge_quality( + { + "value": { + "evidence_dates": ["2026-08-30", "2026-08-31"], + "acceptance": {"score": 0.72, "reason": "window_relation"}, + } + } + ) + + assert quality["evidence_dates"] == ["2026-08-30", "2026-08-31"] + assert quality["acceptance_score"] == 0.72 + assert quality["acceptance_reason"] == "window_relation" + + +@pytest.mark.asyncio +async def test_list_imported_group_graph_targets_keeps_group_days( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + assert "plugin_memory_event" in sql + assert params is not None + assert params["group_uid"] == "__group__" + return [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "day": date(2026, 8, 31), + "event_count": 12, + }, + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "direct-user", + "day": date(2026, 8, 31), + "event_count": 9, + }, + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-b@chatroom", + "day": "2026-08-30", + "event_count": 4, + }, + ] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + + targets = await store.list_imported_group_graph_targets(lookback_days=2, max_targets=3) + + assert [item["session_id"] for item in targets] == [ + "room-a@chatroom", + "room-b@chatroom", + ] + assert targets[0]["date"] == "2026-08-31" + assert targets[1]["date"] == "2026-08-30" + assert targets[0]["event_count"] == 12 + + +@pytest.mark.asyncio +async def test_auto_extract_tick_skips_disabled_scope_and_runs_deterministic_catchup( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + store.runtime_scope_gates_required = True + async def allowed(tenant_id: str, session_id: str = "") -> bool: + return tenant_id == "demo" and session_id == "room-a@chatroom" + + store.combined_history_scope_execution_allowed = allowed + catchup_calls: list[dict[str, Any]] = [] + + async def fake_targets(**kwargs: Any) -> list[dict[str, Any]]: + return [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "date": "2026-08-31", + "event_count": 8, + }, + { + "tenant_id": "other", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-b@chatroom", + "date": "2026-08-31", + "event_count": 3, + }, + ] + + async def fake_catchup(**kwargs: Any) -> dict[str, Any]: + catchup_calls.append(kwargs) + return { + "status": "completed", + "stop_reason": "no_more_events", + "totals": {"windows": 1, "applied": 2}, + "more_remain": False, + } + + monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + + result = await store.run_group_graph_auto_extract_tick( + lookback_days=2, + max_sessions=3, + include_llm=False, + ) + + assert result["ok"] is True + assert result["include_llm"] is False + assert result["ran"] == 1 + assert result["skipped"] == [ + { + "tenant_id": "other", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-b@chatroom", + "date": "2026-08-31", + "event_count": 3, + "reason": "scope_disabled", + } + ] + assert catchup_calls == [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "date": "2026-08-31", + "window_size": 50, + "max_windows_per_run": 20, + "time_budget_seconds": 180, + "include_llm": False, + } + ] + + +@pytest.mark.asyncio +async def test_auto_extract_tick_defaults_to_llm_catchup( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + catchup_calls: list[dict[str, Any]] = [] + + async def fake_targets(**kwargs: Any) -> list[dict[str, Any]]: + return [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "date": "2026-08-31", + "event_count": 8, + } + ] + + async def fake_catchup(**kwargs: Any) -> dict[str, Any]: + catchup_calls.append(kwargs) + return {"status": "completed", "totals": {}, "more_remain": False} + + monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + + result = await store.run_group_graph_auto_extract_tick() + + assert result["include_llm"] is True + assert catchup_calls[0]["include_llm"] is True + assert catchup_calls[0]["max_windows_per_run"] == 20 + assert catchup_calls[0]["time_budget_seconds"] == 180 + + +@pytest.mark.asyncio +async def test_window_extraction_include_llm_false_does_not_call_extractor( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + store.graph_extractor.config = SimpleNamespace(enabled=True) + store.graph_extractor.llm_service = object() + extract_calls: list[dict[str, Any]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + if "FROM plugin_memory_event" in sql and "id > :cursor_event_id" in sql: + return [ + { + "id": 501, + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "user_id": "__group__", + "session_id": "room-a@chatroom", + "user_text": "wxid_a: hello", + "assistant_text": "", + "trace_id": "trace-501", + "event_key": "event-501", + "created_at": "2026-05-15T08:00:00", + }, + { + "id": 502, + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "user_id": "__group__", + "session_id": "room-a@chatroom", + "user_text": "wxid_b: 回复: hi", + "assistant_text": "", + "trace_id": "trace-502", + "event_key": "event-502", + "created_at": "2026-05-15T08:01:00", + }, + ] + return [] + + async def fake_extract(**kwargs: Any) -> dict[str, Any]: + extract_calls.append(kwargs) + return {} + + async def fake_apply(**kwargs: Any) -> dict[str, Any]: + return {"id": 1} + + async def noop(*args: Any, **kwargs: Any) -> None: + return None + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + monkeypatch.setattr(store, "_extract_group_relationship_window_candidates", fake_extract) + monkeypatch.setattr(store, "_apply_group_relationship_window_candidate", fake_apply) + monkeypatch.setattr(store, "_refresh_legacy_cache_for_item_scope", noop) + monkeypatch.setattr(store, "_sync_memory_graph_for_item_safe", noop) + monkeypatch.setattr(store, "_sync_memory_vector_for_item_safe", noop) + + result = await store.run_group_relationship_window_extraction( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="room-a@chatroom", + date="2026-05-15", + include_llm=False, + ) + + assert extract_calls == [] + assert result["controls"]["include_llm"] is False + assert "llm_window_extractor" not in result["generated_from"] + assert result["totals"]["candidates"] >= 1 + + +@pytest.mark.asyncio +async def test_auto_extract_tick_can_sync_known_sessions_before_catchup( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + backfill_calls: list[dict[str, Any]] = [] + catchup_calls: list[dict[str, Any]] = [] + + async def fake_sessions(**kwargs: Any) -> list[dict[str, Any]]: + return [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "event_count": 8, + } + ] + + async def fake_targets(**kwargs: Any) -> list[dict[str, Any]]: + return [ + { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "date": "2026-08-31", + "event_count": 8, + } + ] + + async def fake_backfill(**kwargs: Any) -> dict[str, Any]: + backfill_calls.append(kwargs) + return {"ok": True, "imported_count": 3, "events_inserted": 3} + + async def fake_catchup(**kwargs: Any) -> dict[str, Any]: + catchup_calls.append(kwargs) + return {"status": "completed", "totals": {}, "more_remain": False} + + async def allowed(tenant_id: str, session_id: str = "") -> bool: + return tenant_id == "demo" + + store.combined_history_scope_execution_allowed = allowed + monkeypatch.setattr(store, "list_known_group_graph_sessions", fake_sessions) + monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "backfill_from_sdk", fake_backfill) + monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + + result = await store.run_group_graph_auto_extract_tick( + lookback_days=7, + sync_missing_history=True, + include_llm=False, + ) + + assert result["sync_missing_history"] is True + assert result["synced"][0]["session_id"] == "room-a@chatroom" + assert backfill_calls[0]["session_ids"] == ["room-a@chatroom"] + assert backfill_calls[0]["days_limit"] == 7 + assert backfill_calls[0]["enqueue_llm_jobs"] is True + assert catchup_calls[0]["session_id"] == "room-a@chatroom" + + +def test_group_graph_auto_extract_only_starts_on_configured_roles() -> None: + plugin = MemoryPlugin() + plugin._ctx = SimpleNamespace( + settings=SimpleNamespace( + memory_group_graph_auto_extract_enabled=True, + memory_group_graph_auto_extract_roles="scheduler", + app_process_role="api", + ) + ) + assert plugin._should_run_group_graph_auto_extract() is False + + plugin._ctx.settings.app_process_role = "scheduler" + assert plugin._should_run_group_graph_auto_extract() is True + + plugin._ctx.settings.memory_group_graph_auto_extract_enabled = False + assert plugin._should_run_group_graph_auto_extract() is False diff --git a/tests/unit/test_memory_router.py b/tests/unit/test_memory_router.py index 4ab84ee..5849b17 100644 --- a/tests/unit/test_memory_router.py +++ b/tests/unit/test_memory_router.py @@ -2903,6 +2903,7 @@ async def test_memory_router_window_group_relationship_extraction_requires_admin "max_windows": 10, "cursor_event_id": 0, "dry_run": True, + "include_llm": True, }] serialized = str(payload) assert "content" not in serialized @@ -2961,6 +2962,7 @@ async def test_memory_router_window_catchup_requires_admin_scrubs_and_passes_con "cursor_event_id": 0, "dry_run": True, "time_budget_seconds": 180, + "include_llm": True, }] serialized = str(payload) assert "content" not in serialized From 217050aa31d6c264f26cd06ef6333f8767bfb4fc Mon Sep 17 00:00:00 2001 From: Agent Console Contributors <33415988+zhx8702@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:29:21 +0800 Subject: [PATCH 2/5] feat(ui): operationalize group relationship graph --- frontend/src/lib/api.ts | 49 +++ .../RelationshipDetailsAndDanger.tsx | 144 ++++++- .../RelationshipFiltersAndStatus.tsx | 15 +- .../RelationshipGraphPresentation.tsx | 387 +++++++++++++++--- .../RelationshipGraphWorkspace.tsx | 7 +- .../RelationshipModules.test.tsx | 125 +++++- .../pages/relationship-graph/graphModel.tsx | 196 +++++++++ .../useRelationshipGraphController.test.tsx | 128 ++++++ .../useRelationshipGraphController.ts | 385 ++++++++++++++++- .../src/styles/pages/relationship-graph.css | 86 +++- .../PLAN.md | 85 ++++ 11 files changed, 1517 insertions(+), 90 deletions(-) create mode 100644 tasks/group-relationship-graph-review-and-auto-extract/PLAN.md diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 70822c8..7146031 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -507,6 +507,9 @@ export type GroupGraphEdge = { extraction_method?: string; review_state?: string; acceptance?: Record; + acceptance_score?: number | null; + acceptance_reason?: string | null; + evidence_dates?: string[]; history?: unknown[]; }; @@ -763,6 +766,7 @@ export type GroupGraphWindowExtractionRequest = { max_windows?: number; cursor_event_id?: number; dry_run?: boolean; + include_llm?: boolean; }; export type GroupGraphWindowCatchupRequest = { @@ -777,6 +781,7 @@ export type GroupGraphWindowCatchupRequest = { cursor_event_id?: number; dry_run?: boolean; time_budget_seconds?: number; + include_llm?: boolean; }; export type GroupGraphWindowExtractionResponse = { @@ -866,6 +871,27 @@ export type GroupGraphWindowStatsResponse = { [key: string]: unknown; }; +export type GroupGraphEdgeReviewAction = "accept" | "reject" | "needs_review" | "expire" | "supersede"; + +export type GroupGraphEdgeReviewRequest = { + tenant_id: string; + channel?: string; + source_key?: string; + session_id?: string; + action: GroupGraphEdgeReviewAction; + review_reason?: string; + superseded_by_item_id?: number; + supersedes_item_id?: number; +}; + +export type GroupGraphEdgeReviewResponse = { + ok?: boolean; + edge_id?: string; + action?: string; + result?: Record; + [key: string]: unknown; +}; + export async function getGroupGraph(config: ConsoleConfig, query: GroupGraphQuery) { return apiRequest(config, "/plugins/memory/group-graph", { query }); } @@ -933,6 +959,29 @@ export async function runGroupGraphWindowCatchup(config: ConsoleConfig, body: Gr }); } +export async function reviewGroupGraphEdge( + config: ConsoleConfig, + edgeId: string, + body: GroupGraphEdgeReviewRequest, + options?: { idempotencyKey?: string }, +) { + return apiRequest( + config, + `/plugins/memory/group-graph/edges/${encodeURIComponent(edgeId)}/acceptance-review`, + { + auth: true, + init: { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(options?.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}), + }, + body: JSON.stringify(body), + }, + }, + ); +} + export async function backfillMemoryHistory(config: ConsoleConfig, body: MemoryBackfillRequest) { return apiRequest(config, "/plugins/memory/backfill", { init: { diff --git a/frontend/src/pages/relationship-graph/RelationshipDetailsAndDanger.tsx b/frontend/src/pages/relationship-graph/RelationshipDetailsAndDanger.tsx index 115d30c..ce136ec 100644 --- a/frontend/src/pages/relationship-graph/RelationshipDetailsAndDanger.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipDetailsAndDanger.tsx @@ -13,6 +13,17 @@ import { safeNodeDisplayLabel, nodeTypeLabel, dateStatusClass, + edgeCanAccept, + edgeCanExpire, + edgeCanReject, + edgeCanReturnToReview, + evidenceQuality, + extractionMethodLabel, + counterpartEdges, + firstMemoryItemId, + formatAcceptanceScore, + safeNodeAliases, + safeNodeTechnicalLabel, } from "./graphModel"; import type { RelationshipGraphController } from "./useRelationshipGraphController"; @@ -33,6 +44,7 @@ export type RelationshipMutationController = Pick< | "runWindowExtraction" | "windowCatchupMaxWindowsValue" | "runWindowCatchup" + | "runRecentCoverage" | "loadGraphAndStatus" | "dateLoading" | "jobStatsLoading" @@ -59,6 +71,7 @@ export function RelationshipMutationActions({ runWindowExtraction, windowCatchupMaxWindowsValue, runWindowCatchup, + runRecentCoverage, loadGraphAndStatus, dateLoading, jobStatsLoading, @@ -68,6 +81,21 @@ export function RelationshipMutationActions({ return (
历史与抽取 + +
目标群
{selectedGroupId ? "当前已验证群聊" : "未选择"}
+
范围
最近 7 天历史导入,并按日追平窗口抽取。
+
影响
会调用历史同步和语义抽取;新关系进入待审核,不展示聊天原文。
+ + )} + onConfirm={runRecentCoverage} + /> @@ -162,13 +197,15 @@ export function RelationshipDetailPanel(controller: RelationshipGraphController) {!selection && (
尚未选择对象 - 选择一个节点或关系,即可查看安全摘要。 + 可在画布、待审核队列或列表中选择对象。默认只显示已接受关系;新抽取的关系会出现在待审核队列。
)} {selectedNode && ( <>
名称
{safeNodeDisplayLabel(selectedNode)}
+
技术标识
{safeNodeTechnicalLabel(selectedNode)}
+
别名
{safeNodeAliases(selectedNode)}
类型
{nodeTypeLabel(selectedNode.type)}
审核状态
{acceptanceStatusLabel(selectedNode.acceptance_status)}
置信度
{formatConfidence(selectedNode.confidence)}
@@ -186,12 +223,117 @@ export function RelationshipDetailPanel(controller: RelationshipGraphController)
起点
{safeNodeDisplayLabel(nodesById.get(displayEdgeSource(selectedEdge))) || "未命名节点"}
终点
{safeNodeDisplayLabel(nodesById.get(displayEdgeTarget(selectedEdge))) || "未命名节点"}
审核状态
{acceptanceStatusLabel(selectedEdge.acceptance_status)}
+
抽取方式
{extractionMethodLabel(selectedEdge.extraction_method)}
+
验收分
{formatAcceptanceScore(selectedEdge.acceptance_score ?? evidenceQuality(evidence).score)}
+
验收原因
{selectedEdge.acceptance_reason || evidenceQuality(evidence).reason || "-"}
+
可能冲突
{evidenceQuality(evidence).conflicts || 0}
置信度
{formatConfidence(selectedEdge.confidence)}
证据数
{selectedEdge.evidence_count ?? 0}
消息数
{selectedEdge.source_message_count ?? "-"}
首次出现
{formatTimestamp(selectedEdge.first_seen)}
最近出现
{formatTimestamp(selectedEdge.last_seen)}
+ {( + edgeCanAccept(selectedEdge.acceptance_status) + || edgeCanReject(selectedEdge.acceptance_status) + || edgeCanExpire(selectedEdge.acceptance_status) + || edgeCanReturnToReview(selectedEdge.acceptance_status) + || replaceableEdges.some((item) => firstMemoryItemId(item) > 0) + ) && ( +
+

审核只改这条关系的验收状态,不展示也不改写聊天原文。

+ {edgeCanAccept(selectedEdge.acceptance_status) && ( + +
关系
{readableRelationType(selectedEdge.label || selectedEdge.type)}
+
当前状态
{acceptanceStatusLabel(selectedEdge.acceptance_status)}
+
影响
写入记忆验收记录,并进入默认关系图。
+ + )} + onConfirm={() => reviewEdge("accept")} + /> + )} + {edgeCanReject(selectedEdge.acceptance_status) && ( + +
关系
{readableRelationType(selectedEdge.label || selectedEdge.type)}
+
当前状态
{acceptanceStatusLabel(selectedEdge.acceptance_status)}
+
影响
标记为已拒绝;默认关系图不再显示该边。
+ + )} + onConfirm={() => reviewEdge("reject")} + /> + )} + {edgeCanReturnToReview(selectedEdge.acceptance_status) && ( + +
关系
{readableRelationType(selectedEdge.label || selectedEdge.type)}
+
当前状态
{acceptanceStatusLabel(selectedEdge.acceptance_status)}
+
影响
该关系会离开默认图,重新进入待审核队列。
+ + )} + onConfirm={() => reviewEdge("needs_review")} + /> + )} + {edgeCanExpire(selectedEdge.acceptance_status) && ( + +
关系
{readableRelationType(selectedEdge.label || selectedEdge.type)}
+
当前状态
{acceptanceStatusLabel(selectedEdge.acceptance_status)}
+
影响
标记为已过期;默认关系图不再显示该边。
+ + )} + onConfirm={() => reviewEdge("expire")} + /> + )} + {replaceableEdges.map((other) => { + const otherItemId = firstMemoryItemId(other); + if (!otherItemId) return null; + return ( + +
当前关系
{readableRelationType(selectedEdge.label || selectedEdge.type)}
+
被替代
{readableRelationType(other.label || other.type)} · {acceptanceStatusLabel(other.acceptance_status)}
+
影响
当前关系保持有效,被替代关系标记为已被替代,不再进入默认图。
+ + )} + onConfirm={() => reviewEdge("supersede", selectedEdge, { supersedes_item_id: otherItemId })} + /> + ); + })} +
+ )}
diff --git a/frontend/src/pages/relationship-graph/RelationshipFiltersAndStatus.tsx b/frontend/src/pages/relationship-graph/RelationshipFiltersAndStatus.tsx index 5a10474..5fbf9db 100644 --- a/frontend/src/pages/relationship-graph/RelationshipFiltersAndStatus.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipFiltersAndStatus.tsx @@ -62,6 +62,10 @@ export function RelationshipFiltersAndStatus(controller: RelationshipGraphContro windowStatsStatus, windowStatsTotals, windowStatsAcceptance, + applyPlaybackDate, + playbackDate, + governanceStatus, + governanceStatusText, } = controller; return ( @@ -192,8 +196,11 @@ export function RelationshipFiltersAndStatus(controller: RelationshipGraphContro + ))} +
{GRAPH_VIEW_MODES.map((mode) => (
+ {playbackDates.length > 1 && ( +
+ + {playbackDate || "区间概览"} + +
+ )} {!!graphNodes.length && (

- {graphSummaryText} 画布仅作视觉概览;请选择右侧的关系列表或节点列表查看详情。 + {graphSummaryText} 可在画布上点选、拖动画布平移、滚轮缩放;待审关系用虚线,线宽表示证据数,透明度表示新旧。

)} {loading ? ( @@ -131,67 +284,111 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese ) : graphNodes.length ? ( ) : (
@@ -202,6 +399,72 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese
+
+
+
+

审核

+

待审核队列

+
+ {pendingEdges.length} +
+
+ {pendingEdges.map((edge) => ( +
+ +
+ +
关系
{readableRelationType(edge.label || edge.type)}
+
当前状态
{acceptanceStatusLabel(edge.acceptance_status)}
+
影响
写入记忆验收记录,并进入默认关系图。
+ + )} + onConfirm={() => reviewEdge("accept", edge)} + /> + +
关系
{readableRelationType(edge.label || edge.type)}
+
当前状态
{acceptanceStatusLabel(edge.acceptance_status)}
+
影响
标记为已拒绝;默认关系图不再显示该边。
+ + )} + onConfirm={() => reviewEdge("reject", edge)} + /> +
+
+ ))} + {!pendingEdges.length && ( +

{loading ? "正在加载待审核关系..." : "当前时间范围内没有待审核关系。"}

+ )} +
+
+
@@ -220,7 +483,9 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese > {relationLabel(edge, nodesById)} {acceptanceStatusLabel(edge.acceptance_status)} - {readableRelationType(edge.label || edge.type)} · 置信度 {formatConfidence(edge.confidence)} · {edge.evidence_count ?? 0} 条证据 + + {readableRelationType(edge.label || edge.type)} · {extractionMethodLabel(edge.extraction_method)} · 置信度 {formatConfidence(edge.confidence)} · {edge.evidence_count ?? 0} 条证据 + ))} {!graphEdges.length &&

{loading ? "正在加载关系..." : "没有关系匹配当前查询、搜索条件或视图模式。"}

} diff --git a/frontend/src/pages/relationship-graph/RelationshipGraphWorkspace.tsx b/frontend/src/pages/relationship-graph/RelationshipGraphWorkspace.tsx index c06f4c2..88c1acd 100644 --- a/frontend/src/pages/relationship-graph/RelationshipGraphWorkspace.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipGraphWorkspace.tsx @@ -17,7 +17,7 @@ export function RelationshipGraphWorkspace() { ); } @@ -27,12 +27,15 @@ export function RelationshipGraphWorkspace() { + diff --git a/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx b/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx index 51b24cd..f0adcf5 100644 --- a/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx @@ -4,10 +4,12 @@ import { describe, expect, it, vi } from "vitest"; import type { GroupGraphEdge, GroupGraphNode } from "../../lib/api"; import { + RelationshipDetailPanel, RelationshipMutationActions, RelationshipUnavailableReset, type RelationshipMutationController, } from "./RelationshipDetailsAndDanger"; +import type { RelationshipGraphController } from "./useRelationshipGraphController"; import { RelationshipGraphPresentation, type RelationshipGraphPresentationProps, @@ -44,6 +46,7 @@ describe("relationship graph modules", () => { runWindowExtraction: vi.fn(), windowCatchupMaxWindowsValue: 20, runWindowCatchup: vi.fn(), + runRecentCoverage: vi.fn(), loadGraphAndStatus: vi.fn(), dateLoading: false, jobStatsLoading: false, @@ -61,9 +64,11 @@ describe("relationship graph modules", () => { expect(runDailyExtraction).toHaveBeenCalledTimes(1); }); - it("uses the accessible lists as the sole graph selection controls", async () => { + it("lets the canvas and review queue select graph objects", async () => { const user = userEvent.setup(); const setSelection = vi.fn(); + const reviewEdge = vi.fn().mockResolvedValue(undefined); + const applyGraphRangeDays = vi.fn(); const node: GroupGraphNode = { id: "person:member-a", type: "person", @@ -91,6 +96,18 @@ describe("relationship graph modules", () => { acceptance_status: "accepted", confidence: 0.85, evidence_count: 2, + extraction_method: "deterministic", + }; + const pendingEdge: GroupGraphEdge = { + id: "edge-pending", + from: node.id, + to: otherNode.id, + type: "replied_to", + label: "replied_to", + acceptance_status: "needs_review", + confidence: 0.61, + evidence_count: 4, + extraction_method: "llm_window", }; const controller = { modeHiddenNodeCount: 0, @@ -121,11 +138,20 @@ describe("relationship graph modules", () => { graphEdges: [edge], nodesById: new Map([[node.id, node], [otherNode.id, otherNode]]), modeFilteredNodes: [node, otherNode], + graphRangeDays: 7, + applyGraphRangeDays, + playbackDate: "", + applyPlaybackDate: vi.fn(), + playbackDates: ["2026-08-25", "2026-08-26", "2026-08-27"], + pendingEdges: [pendingEdge], + reviewing: false, + reviewEdge, } satisfies RelationshipGraphPresentationProps; render(); const nodeList = screen.getByRole("region", { name: "节点列表" }); const edgeList = screen.getByRole("region", { name: "关系列表" }); + const queue = screen.getByRole("region", { name: "待审核队列" }); const nodeRow = within(nodeList).getByRole("button", { name: /成员甲/ }); await user.click(nodeRow); @@ -133,17 +159,90 @@ describe("relationship graph modules", () => { expect(nodeRow).toHaveAttribute("aria-pressed", "false"); await user.click(within(edgeList).getByRole("button")); expect(setSelection).toHaveBeenLastCalledWith({ kind: "edge", item: edge }); - expect(screen.getByText(/画布仅作视觉概览/)).toBeInTheDocument(); - - const canvas = document.querySelector("svg.relationship-canvas"); - expect(canvas).toHaveAttribute("aria-hidden", "true"); - expect(canvas).toHaveAttribute("focusable", "false"); - expect(canvas).toHaveAttribute("pointer-events", "none"); - expect(canvas?.querySelectorAll("[tabindex], [role='button']")).toHaveLength(0); - setSelection.mockClear(); - fireEvent.click(canvas?.querySelector(".relationship-node") as SVGElement); - fireEvent.click(canvas?.querySelector(".relationship-edge") as SVGElement); - expect(setSelection).not.toHaveBeenCalled(); - expect(screen.queryByRole("img", { name: "群聊关系图" })).not.toBeInTheDocument(); + expect(screen.getByText(/可在画布上点选/)).toBeInTheDocument(); + expect(within(queue).getByRole("button", { name: /成员甲 — 回复 — 项目甲/ })).toBeInTheDocument(); + + const canvas = screen.getByRole("img", { name: "群聊关系图" }); + expect(canvas).not.toHaveAttribute("pointer-events", "none"); + fireEvent.click(canvas.querySelector("[data-graph-item='node']") as SVGElement); + expect(setSelection).toHaveBeenCalledWith({ kind: "node", item: node }); + fireEvent.click(canvas.querySelector("[data-graph-item='edge']") as SVGElement); + expect(setSelection).toHaveBeenCalledWith({ kind: "edge", item: edge }); + + await user.click(screen.getByRole("button", { name: "近14天" })); + expect(applyGraphRangeDays).toHaveBeenCalledWith(14); + expect(screen.getByRole("slider")).toBeInTheDocument(); + + await user.click(within(queue).getByRole("button", { name: "接受" })); + const dialog = screen.getByRole("dialog", { name: "确认接受该关系" }); + await user.click(within(dialog).getByRole("button", { name: "确认接受" })); + expect(reviewEdge).toHaveBeenCalledWith("accept", pendingEdge); + }); + + it("confirms edge acceptance, expiry and return-to-review from the detail panel", async () => { + const user = userEvent.setup(); + const reviewEdge = vi.fn().mockResolvedValue(undefined); + const node: GroupGraphNode = { + id: "person:member-a", + type: "person", + label: "成员甲", + display_label: "成员甲", + }; + const otherNode: GroupGraphNode = { + id: "person:member-b", + type: "person", + label: "成员乙", + display_label: "成员乙", + }; + const edge: GroupGraphEdge = { + id: "edge-review-1", + from: node.id, + to: otherNode.id, + type: "replied_to", + label: "replied_to", + acceptance_status: "needs_review", + confidence: 0.62, + evidence_count: 2, + extraction_method: "llm_window", + acceptance_score: 0.62, + acceptance_reason: "window_relation", + }; + const controller = { + selection: { kind: "edge", item: edge }, + selectedNode: null, + selectedEdge: edge, + nodesById: new Map([[node.id, node], [otherNode.id, otherNode]]), + evidence: null, + evidenceLoading: false, + evidenceStatus: "选择一条关系后会自动加载证据来源。", + loadEdgeEvidence: vi.fn(), + reviewing: false, + reviewEdge, + graphEdges: [edge], + pendingEdges: [], + } as unknown as RelationshipGraphController; + + const { rerender } = render(); + expect(screen.getByText("语义抽取")).toBeInTheDocument(); + expect(screen.getByText("验收分")).toBeInTheDocument(); + expect(screen.getByText("window_relation")).toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "接受关系" })); + + const dialog = screen.getByRole("dialog", { name: "确认接受该关系" }); + expect(within(dialog).getByText(/回复/)).toBeInTheDocument(); + expect(within(dialog).getByText(/待审核/)).toBeInTheDocument(); + await user.click(within(dialog).getByRole("button", { name: "确认接受" })); + + expect(reviewEdge).toHaveBeenCalledWith("accept"); + + const acceptedEdge = { ...edge, acceptance_status: "accepted" }; + rerender(); + await user.click(screen.getByRole("button", { name: "标记过期" })); + await user.click(within(screen.getByRole("dialog", { name: "确认将该关系标记为过期" })).getByRole("button", { name: "确认过期" })); + expect(reviewEdge).toHaveBeenCalledWith("expire"); + + await user.click(screen.getByRole("button", { name: "退回待审" })); + await user.click(within(screen.getByRole("dialog", { name: "确认退回待审核" })).getByRole("button", { name: "确认退回" })); + expect(reviewEdge).toHaveBeenCalledWith("needs_review"); }); }); diff --git a/frontend/src/pages/relationship-graph/graphModel.tsx b/frontend/src/pages/relationship-graph/graphModel.tsx index 9636429..07425d5 100644 --- a/frontend/src/pages/relationship-graph/graphModel.tsx +++ b/frontend/src/pages/relationship-graph/graphModel.tsx @@ -3,6 +3,7 @@ import type { GroupGraphEdgeEvidenceEntity, GroupGraphEdgeEvidenceResponse, GroupGraphNode, + GroupGraphResponse, MemoryBackfillResponse, MemoryExtractionJobStatsResponse, MemoryExtractionJobStatusCounts, @@ -28,6 +29,7 @@ export const DEFAULT_EDGE_TYPES = [ "tested", ]; export const HISTORY_RECENT_DAYS = 14; +export const GRAPH_OVERVIEW_DAYS = 7; export const GRAPH_CANVAS_WIDTH = 920; export const GRAPH_CANVAS_HEIGHT = 620; export const LOW_VALUE_EDGE_TYPES = new Set(["said", "says", "quoted", "mentions_raw", "raw_mention", "message"]); @@ -148,6 +150,194 @@ export function acceptanceStatusLabel(value?: string | null) { return ACCEPTANCE_LABELS[String(value || "unknown").toLowerCase()] || "其他状态"; } +export function normalizedAcceptanceStatus(value?: string | null) { + return String(value || "").trim().toLowerCase(); +} + +export function edgeCanAccept(status?: string | null) { + const normalized = normalizedAcceptanceStatus(status); + return normalized !== "accepted" && normalized !== "superseded" && normalized !== "expired"; +} + +export function edgeCanReject(status?: string | null) { + const normalized = normalizedAcceptanceStatus(status); + return normalized !== "rejected" && normalized !== "superseded" && normalized !== "expired"; +} + +export function edgeCanExpire(status?: string | null) { + const normalized = normalizedAcceptanceStatus(status); + return normalized !== "expired" && normalized !== "superseded"; +} + +export function edgeCanReturnToReview(status?: string | null) { + const normalized = normalizedAcceptanceStatus(status); + return normalized === "accepted" || normalized === "rejected" || normalized === "candidate"; +} + +export const PENDING_REVIEW_STATUS = "needs_review,candidate"; + +export const GRAPH_RANGE_PRESETS = [ + { days: 7, label: "近7天" }, + { days: 14, label: "近14天" }, + { days: 30, label: "近30天" }, + { days: 0, label: "全部时间" }, +] as const; + +export function localDateSeries(days: number, end = new Date()) { + return Array.from({ length: Math.max(1, days) }, (_, index) => localDateDaysAgo(days - 1 - index, end)); +} + +export function extractionMethodLabel(value?: string | null) { + const normalized = String(value || "").trim().toLowerCase(); + if (!normalized) return "来源未知"; + if (normalized.includes("llm")) return "语义抽取"; + if (normalized.includes("deterministic") || normalized.includes("rule") || normalized.includes("stat")) { + return "规则抽取"; + } + return "混合抽取"; +} + +export function isPendingReviewStatus(status?: string | null) { + const normalized = normalizedAcceptanceStatus(status); + return normalized === "needs_review" || normalized === "candidate"; +} + +export function edgeStrokeWidth(edge: GroupGraphEdge) { + return Math.min(5, 1.15 + Number(edge.evidence_count || 0) * 0.32); +} + +export function edgeRecencyOpacity(edge: GroupGraphEdge) { + if (!edge.last_seen) return 0.82; + const ageDays = (Date.now() - new Date(edge.last_seen).getTime()) / 86_400_000; + if (!Number.isFinite(ageDays) || ageDays <= 7) return 0.9; + if (ageDays <= 14) return 0.68; + if (ageDays <= 30) return 0.46; + return 0.28; +} + +export function restoreGraphSelection(selection: Selection, graph: GroupGraphResponse): Selection { + if (!selection) return null; + if (selection.kind === "edge") { + const edge = (graph.edges || []).find((item) => item.id === selection.item.id); + return edge ? { kind: "edge", item: edge } : null; + } + const node = (graph.nodes || []).find((item) => item.id === selection.item.id); + return node ? { kind: "node", item: node } : null; +} + +export function reviewActionMessage(action: string) { + if (action === "accept") return "已接受该关系。"; + if (action === "reject") return "已拒绝该关系。"; + if (action === "expire") return "已将该关系标记为过期。"; + if (action === "needs_review") return "已将该关系退回待审核。"; + if (action === "supersede") return "已用当前关系替代另一条关系。"; + return "已更新该关系的审核状态。"; +} + +export function localDateAdd(value: string, days: number) { + const [year, month, day] = value.split("-").map(Number); + if (!year || !month || !day) return value; + const date = new Date(year, month - 1, day); + date.setDate(date.getDate() + days); + return localDateValue(date); +} + +export function edgeEvidenceDates(edge: GroupGraphEdge) { + const dates = (edge.evidence_dates || []) + .map((value) => String(value || "").slice(0, 10)) + .filter(Boolean); + if (edge.first_seen) dates.push(String(edge.first_seen).slice(0, 10)); + if (edge.last_seen) dates.push(String(edge.last_seen).slice(0, 10)); + return Array.from(new Set(dates)); +} + +export function edgeSeenOnDate(edge: GroupGraphEdge, date?: string | null) { + if (!date) return false; + return edgeEvidenceDates(edge).includes(date); +} + +export function playbackDateSeries(rangeDays: number, fromDate = "") { + if (rangeDays > 0) return localDateSeries(rangeDays); + if (fromDate) return [fromDate]; + return localDateSeries(GRAPH_OVERVIEW_DAYS); +} + +export function counterpartEdges(edge: GroupGraphEdge, pool: GroupGraphEdge[]) { + const source = displayEdgeSource(edge); + const target = displayEdgeTarget(edge); + return pool.filter((item) => { + if (!item.id || item.id === edge.id) return false; + const from = displayEdgeSource(item); + const to = displayEdgeTarget(item); + return (from === source && to === target) || (from === target && to === source); + }); +} + +export function firstMemoryItemId(edge?: GroupGraphEdge | null) { + const value = Number(edge?.memory_item_ids?.[0]); + return Number.isFinite(value) && value > 0 ? value : 0; +} + +export function edgePairKey(edge: GroupGraphEdge) { + const source = displayEdgeSource(edge); + const target = displayEdgeTarget(edge); + return source < target ? `${source}::${target}` : `${target}::${source}`; +} + +export function edgeBundleOffsets(edges: GroupGraphEdge[]) { + const groups = new Map(); + for (const edge of edges) { + const key = edgePairKey(edge); + const group = groups.get(key) || []; + group.push(edge); + groups.set(key, group); + } + const offsets = new Map(); + for (const group of groups.values()) { + group.forEach((edge, index) => { + offsets.set(edgeKey(edge), group.length === 1 ? 0 : index - (group.length - 1) / 2); + }); + } + return offsets; +} + +export function quadraticEdgePath( + from: { x: number; y: number }, + to: { x: number; y: number }, + offset: number, +) { + if (!offset) return `M ${from.x} ${from.y} L ${to.x} ${to.y}`; + const midX = (from.x + to.x) / 2; + const midY = (from.y + to.y) / 2; + const deltaX = to.x - from.x; + const deltaY = to.y - from.y; + const length = Math.hypot(deltaX, deltaY) || 1; + return `M ${from.x} ${from.y} Q ${midX + (-deltaY / length) * offset * 22} ${midY + (deltaX / length) * offset * 22} ${to.x} ${to.y}`; +} + +export function evidenceQuality(evidence?: GroupGraphEdgeEvidenceResponse | null) { + const items = evidence?.memory_items || []; + const scores = items + .map((item) => Number(item.acceptance_score)) + .filter((value) => Number.isFinite(value)); + const reasons = items + .map((item) => String(item.acceptance_reason || "").trim()) + .filter(Boolean); + const conflicts = items.flatMap((item) => ( + Array.isArray(item.possible_conflicts) ? item.possible_conflicts : [] + )); + return { + score: scores.length ? Math.max(...scores) : null, + reason: reasons[0] || "", + conflicts: conflicts.length, + }; +} + +export function formatAcceptanceScore(value?: number | null) { + if (value === undefined || value === null || Number.isNaN(Number(value))) return "-"; + return `${Math.round(Number(value) * 100)}%`; +} + export function nodeTypeLabel(value?: string | null) { return NODE_TYPE_LABELS[String(value || "").toLowerCase()] || "其他类型"; } @@ -738,6 +928,12 @@ export function localDateValue(date = new Date()) { return `${year}-${month}-${day}`; } +export function localDateDaysAgo(days: number, date = new Date()) { + const value = new Date(date); + value.setDate(value.getDate() - Math.max(0, days)); + return localDateValue(value); +} + export function dateStatusClass(status?: string) { if (status === "extracted") return "relationship-date-status is-ready"; if (status === "partial") return "relationship-date-status is-imported"; diff --git a/frontend/src/pages/relationship-graph/useRelationshipGraphController.test.tsx b/frontend/src/pages/relationship-graph/useRelationshipGraphController.test.tsx index 7716e16..bc0fdea 100644 --- a/frontend/src/pages/relationship-graph/useRelationshipGraphController.test.tsx +++ b/frontend/src/pages/relationship-graph/useRelationshipGraphController.test.tsx @@ -6,9 +6,11 @@ import { useRelationshipGraphController } from "./useRelationshipGraphController const apiMocks = vi.hoisted(() => ({ getGroupGraph: vi.fn(), + getGroupGraphEdgeEvidence: vi.fn(), getGroupGraphHistoryDates: vi.fn(), getGroupGraphWindowStats: vi.fn(), getMemoryExtractionJobStats: vi.fn(), + reviewGroupGraphEdge: vi.fn(), })); const consoleHarness = vi.hoisted(() => ({ @@ -29,9 +31,11 @@ vi.mock("../../lib/api", async (importOriginal) => { return { ...actual, getGroupGraph: apiMocks.getGroupGraph, + getGroupGraphEdgeEvidence: apiMocks.getGroupGraphEdgeEvidence, getGroupGraphHistoryDates: apiMocks.getGroupGraphHistoryDates, getGroupGraphWindowStats: apiMocks.getGroupGraphWindowStats, getMemoryExtractionJobStats: apiMocks.getMemoryExtractionJobStats, + reviewGroupGraphEdge: apiMocks.reviewGroupGraphEdge, }; }); @@ -69,9 +73,11 @@ describe("useRelationshipGraphController verified group loading", () => { userId: "", }; apiMocks.getGroupGraph.mockReset(); + apiMocks.getGroupGraphEdgeEvidence.mockReset().mockResolvedValue({ edge: { id: "edge-1" } }); apiMocks.getGroupGraphHistoryDates.mockReset().mockResolvedValue({ items: [] }); apiMocks.getGroupGraphWindowStats.mockReset().mockResolvedValue({ totals: {} }); apiMocks.getMemoryExtractionJobStats.mockReset().mockResolvedValue({ counts: {} }); + apiMocks.reviewGroupGraphEdge.mockReset().mockResolvedValue({ ok: true, action: "accept", edge_id: "edge-1" }); }); it("auto-loads a switched group and ignores the previous group's late response", async () => { @@ -121,4 +127,126 @@ describe("useRelationshipGraphController verified group loading", () => { expect(result.current.graph).toEqual(groupBGraph); expect(result.current.loading).toBe(false); }); + + it("reviews the selected edge and reloads the graph", async () => { + const edge = { + id: "edge-1", + from: "person:a", + to: "person:b", + type: "replied_to", + acceptance_status: "needs_review", + }; + const graph = { + scope: { session_id: "group-a@chatroom" }, + nodes: [ + { id: "person:a", type: "person", label: "甲" }, + { id: "person:b", type: "person", label: "乙" }, + ], + edges: [edge], + }; + apiMocks.getGroupGraph.mockResolvedValue(graph); + + const { result } = renderHook(() => useRelationshipGraphController()); + await waitFor(() => expect(result.current.graph).toEqual(graph)); + + act(() => { + result.current.setSelection({ kind: "edge", item: edge }); + }); + await act(async () => { + await result.current.reviewEdge("accept"); + }); + + expect(apiMocks.reviewGroupGraphEdge).toHaveBeenCalledWith( + expect.anything(), + "edge-1", + expect.objectContaining({ + tenant_id: "default", + channel: "wechat", + source_key: "wxbot", + session_id: "group-a@chatroom", + action: "accept", + }), + expect.objectContaining({ idempotencyKey: expect.any(String) }), + ); + expect(apiMocks.getGroupGraph.mock.calls.length).toBeGreaterThan(1); + }); + + it("keeps the selected edge after a graph reload and can review a queued edge", async () => { + const edge = { + id: "edge-1", + from: "person:a", + to: "person:b", + type: "replied_to", + acceptance_status: "needs_review", + }; + const nextEdge = { ...edge, evidence_count: 4 }; + const graph = { + scope: { session_id: "group-a@chatroom" }, + nodes: [ + { id: "person:a", type: "person", label: "甲" }, + { id: "person:b", type: "person", label: "乙" }, + ], + edges: [edge], + }; + apiMocks.getGroupGraph.mockResolvedValue(graph); + + const { result } = renderHook(() => useRelationshipGraphController()); + await waitFor(() => expect(result.current.graph).toEqual(graph)); + + act(() => { + result.current.setSelection({ kind: "edge", item: edge }); + }); + + apiMocks.getGroupGraph.mockResolvedValue({ ...graph, edges: [nextEdge] }); + await act(async () => { + await result.current.loadGraph(); + }); + expect(result.current.selectedEdge).toEqual(nextEdge); + + await act(async () => { + await result.current.reviewEdge("expire", nextEdge); + }); + expect(apiMocks.reviewGroupGraphEdge).toHaveBeenCalledWith( + expect.anything(), + "edge-1", + expect.objectContaining({ action: "expire" }), + expect.objectContaining({ idempotencyKey: expect.any(String) }), + ); + }); + + it("loads pending review and recent range filters", async () => { + apiMocks.getGroupGraph.mockResolvedValue({ + scope: { session_id: "group-a@chatroom" }, + nodes: [], + edges: [], + }); + const { result } = renderHook(() => useRelationshipGraphController()); + await waitFor(() => expect(result.current.graph).not.toBeNull()); + + await act(async () => { + await result.current.showPendingReview(); + }); + expect(apiMocks.getGroupGraph).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ acceptance_status: "needs_review,candidate" }), + ); + + await act(async () => { + await result.current.applyGraphRangeDays(14); + }); + expect(result.current.graphRangeDays).toBe(14); + expect(apiMocks.getGroupGraph).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ from: expect.any(String) }), + ); + + await act(async () => { + await result.current.applyPlaybackDate("2026-08-20"); + }); + expect(result.current.playbackDate).toBe("2026-08-20"); + expect(apiMocks.getGroupGraph).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ from: "2026-08-20", to: "2026-08-21" }), + ); + }); }); diff --git a/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts b/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts index 95f5b9b..da799bb 100644 --- a/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts +++ b/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts @@ -9,10 +9,12 @@ import { getGroupGraphHistoryDates, getGroupGraphWindowStats, getMemoryExtractionJobStats, + reviewGroupGraphEdge, runGroupGraphDailyExtraction, runGroupGraphWindowCatchup, runGroupGraphWindowExtraction, type GroupGraphEdge, + type GroupGraphEdgeReviewAction, type GroupGraphEdgeEvidenceResponse, type GroupGraphHistoryDateRow, type GroupGraphResponse, @@ -24,11 +26,19 @@ import { useStableIdempotencyKeys } from "../../lib/idempotency"; import { requireSelectedGroup, useConsoleConfig } from "../../state/console-config"; import { + GRAPH_OVERVIEW_DAYS, HISTORY_RECENT_DAYS, + PENDING_REVIEW_STATUS, type Selection, type GraphViewMode, sanitizeEdgeEvidence, + localDateAdd, + localDateDaysAgo, + localDateSeries, localDateValue, + playbackDateSeries, + restoreGraphSelection, + reviewActionMessage, safeBackfillDebug, } from "./graphModel"; import { useRelationshipGraphProjection } from "./useRelationshipGraphProjection"; @@ -45,8 +55,19 @@ export function useRelationshipGraphController() { const [edgeType, setEdgeType] = useState(""); const [minConfidence, setMinConfidence] = useState(""); const [limit, setLimit] = useState("100"); - const [fromDate, setFromDate] = useState(""); + const [fromDate, setFromDate] = useState(() => localDateDaysAgo(GRAPH_OVERVIEW_DAYS - 1)); const [toDate, setToDate] = useState(""); + const [graphRangeDays, setGraphRangeDays] = useState(GRAPH_OVERVIEW_DAYS); + const [playbackDate, setPlaybackDate] = useState(""); + const [governanceStatus, setGovernanceStatus] = useState<{ + auto_cleanup_enabled?: boolean | null; + needs_review_retention_days?: number | null; + rejected_retention_days?: number | null; + auto_expire_days?: number | null; + expired_items?: number; + expiring_within_7_days?: number; + } | null>(null); + const [governanceStatusText, setGovernanceStatusText] = useState("选择已验证群聊后可查看治理保留策略。"); const [nodeSearch, setNodeSearch] = useState(""); const [edgeSearch, setEdgeSearch] = useState(""); const [graphViewMode, setGraphViewMode] = useState("readable"); @@ -81,6 +102,7 @@ export function useRelationshipGraphController() { const [loading, setLoading] = useState(false); const [syncing, setSyncing] = useState(false); const [extracting, setExtracting] = useState(false); + const [reviewing, setReviewing] = useState(false); const [evidence, setEvidence] = useState(null); const [evidenceLoading, setEvidenceLoading] = useState(false); const [evidenceStatus, setEvidenceStatus] = useState("选择一条关系后会自动加载证据来源。"); @@ -91,8 +113,11 @@ export function useRelationshipGraphController() { const [jobStatsStatus, setJobStatsStatus] = useState("填写 tenant_id 和群聊ID后可查看 AI 抽取任务数量。"); const [windowStats, setWindowStats] = useState(null); const [windowStatsStatus, setWindowStatsStatus] = useState("选择已验证群聊后可查看窗口关系统计。"); + const [pendingEdges, setPendingEdges] = useState([]); const selectedNode = selection?.kind === "node" ? selection.item : null; const selectedEdge = selection?.kind === "edge" ? selection.item : null; + const selectionRef = useRef(selection); + selectionRef.current = selection; const projection = useRelationshipGraphProjection({ config, @@ -154,6 +179,9 @@ export function useRelationshipGraphController() { neighborNodeIds, graphStateMessage, } = projection; + const pendingReviewCount = pendingEdges.length + || Number(windowStatsAcceptance.needs_review || 0) + + Number(windowStatsAcceptance.candidate || 0); const scopeQuery = useMemo(() => { const tenantId = config.tenantId.trim(); @@ -272,9 +300,12 @@ export function useRelationshipGraphController() { if (graphRequestIdRef.current !== requestId || activeGraphScopeKeyRef.current !== requestScopeKey) return; setLoadedGraph(result); setLoadedGraphScopeKey(requestScopeKey); - setSelection(null); - setEvidence(null); - setEvidenceStatus("选择一条关系后会自动加载证据来源。"); + const nextSelection = restoreGraphSelection(selectionRef.current, result); + setSelection(nextSelection); + if (!nextSelection) { + setEvidence(null); + setEvidenceStatus("选择一条关系后会自动加载证据来源。"); + } setOutput(formatJson({ schema: result.schema, scope: result.scope, @@ -375,9 +406,86 @@ export function useRelationshipGraphController() { } }, [channel, config, currentGraphScopeKey, loadJobStats, selectedGroupId, selectedGroupIsVerified, sourceKey]); + const loadPendingEdges = useCallback(async (overrides: { fromDate?: string; toDate?: string } = {}) => { + const tenantId = config.tenantId.trim(); + if (!tenantId || !selectedGroupIsVerified) { + setPendingEdges([]); + return; + } + const requestScopeKey = currentGraphScopeKey; + try { + const result = await getGroupGraph(config, { + tenant_id: tenantId, + channel, + source_key: sourceKey, + session_id: selectedGroupId, + acceptance_status: PENDING_REVIEW_STATUS, + limit: "100", + from: (overrides.fromDate ?? fromDate) || undefined, + to: (overrides.toDate ?? toDate) || undefined, + }); + if (activeGraphScopeKeyRef.current !== requestScopeKey) return; + setPendingEdges(result.edges || []); + } catch { + if (activeGraphScopeKeyRef.current !== requestScopeKey) return; + setPendingEdges([]); + } + }, [channel, config, currentGraphScopeKey, fromDate, selectedGroupId, selectedGroupIsVerified, sourceKey, toDate]); + + const loadGovernanceStatus = useCallback(async () => { + const tenantId = config.tenantId.trim(); + if (!tenantId || !selectedGroupIsVerified) { + setGovernanceStatus(null); + setGovernanceStatusText("无法加载治理摘要:缺少已验证群聊。"); + return; + } + const requestScopeKey = currentGraphScopeKey; + try { + const result = await apiRequest<{ + governance?: { + auto_cleanup_enabled?: boolean | null; + needs_review_retention_days?: number | null; + rejected_retention_days?: number | null; + auto_expire_days?: number | null; + expired_items?: number; + expiring_within_7_days?: number; + }; + }>(config, "/plugins/memory/management-status", { + auth: true, + query: { + tenant_id: tenantId, + channel: channel.trim(), + source_key: sourceKey.trim(), + session_id: selectedGroupId, + }, + }); + if (activeGraphScopeKeyRef.current !== requestScopeKey) return; + setGovernanceStatus(result.governance || null); + setGovernanceStatusText("治理摘要已加载;仅显示保留天数和到期计数。"); + } catch (err) { + if (activeGraphScopeKeyRef.current !== requestScopeKey) return; + setGovernanceStatus(null); + setGovernanceStatusText( + `治理摘要暂不可用:${err instanceof ApiError || err instanceof Error ? err.message : "status request failed"}`, + ); + } + }, [channel, config, currentGraphScopeKey, selectedGroupId, selectedGroupIsVerified, sourceKey]); + const loadGraphAndStatus = useCallback(async (graphOverrides?: Parameters[0]) => { - await Promise.all([loadGraph(graphOverrides), loadDateStatuses(), loadJobStats(), loadWindowStats()]); - }, [loadDateStatuses, loadGraph, loadJobStats, loadWindowStats]); + await Promise.all([ + loadGraph(graphOverrides), + loadDateStatuses(), + loadJobStats(), + loadWindowStats(), + loadPendingEdges({ + fromDate: graphOverrides?.fromDate, + toDate: graphOverrides?.toDate, + }), + loadGovernanceStatus(), + ]); + }, [loadDateStatuses, loadGovernanceStatus, loadGraph, loadJobStats, loadPendingEdges, loadWindowStats]); + const loadGraphAndStatusRef = useRef(loadGraphAndStatus); + loadGraphAndStatusRef.current = loadGraphAndStatus; const showAllGraph = useCallback(async () => { setGraphViewMode("all"); @@ -387,6 +495,8 @@ export function useRelationshipGraphController() { setMinConfidence(""); setFromDate(""); setToDate(""); + setGraphRangeDays(0); + setPlaybackDate(""); setNodeSearch(""); setEdgeSearch(""); setLimit("500"); @@ -401,6 +511,111 @@ export function useRelationshipGraphController() { }); }, [loadGraphAndStatus]); + const showPendingReview = useCallback(async () => { + setGraphViewMode("all"); + setAcceptanceStatus(PENDING_REVIEW_STATUS); + setNodeType(""); + setEdgeType(""); + setMinConfidence(""); + await loadGraphAndStatus({ + acceptanceStatus: PENDING_REVIEW_STATUS, + nodeType: "", + edgeType: "", + minConfidence: "", + }); + }, [loadGraphAndStatus]); + + const applyGraphRangeDays = useCallback(async (days: number) => { + setGraphRangeDays(days); + setPlaybackDate(""); + const nextFrom = days > 0 ? localDateDaysAgo(days - 1) : ""; + setFromDate(nextFrom); + setToDate(""); + await loadGraphAndStatus({ + fromDate: nextFrom, + toDate: "", + }); + }, [loadGraphAndStatus]); + + const applyPlaybackDate = useCallback(async (date: string) => { + setPlaybackDate(date); + if (!date) { + const nextFrom = graphRangeDays > 0 ? localDateDaysAgo(graphRangeDays - 1) : ""; + setFromDate(nextFrom); + setToDate(""); + await loadGraphAndStatus({ fromDate: nextFrom, toDate: "" }); + return; + } + setTargetDate(date); + const nextTo = localDateAdd(date, 1); + setFromDate(date); + setToDate(nextTo); + await loadGraphAndStatus({ fromDate: date, toDate: nextTo }); + }, [graphRangeDays, loadGraphAndStatus]); + + const reviewEdge = async ( + action: GroupGraphEdgeReviewAction, + edge?: GroupGraphEdge, + extras?: { supersedes_item_id?: number; superseded_by_item_id?: number }, + ) => { + const tenantId = config.tenantId.trim(); + const sessionId = requireSelectedGroup(config, verifiedGroupIds); + const target = edge ?? selectedEdge; + if (!target) { + const error = new Error("请先选择一条关系"); + setOutput(formatJson({ + status: "validation_failed", + message: error.message, + no_api_request_sent: true, + })); + throw error; + } + const nextSelection = { kind: "edge" as const, item: target }; + selectionRef.current = nextSelection; + setSelection(nextSelection); + setReviewing(true); + try { + const intent = `relationship:review:${tenantId}:${sessionId}:${target.id}:${action}:${extras?.supersedes_item_id || ""}`; + const result = await reviewGroupGraphEdge( + config, + target.id, + { + tenant_id: tenantId, + channel: channel.trim(), + source_key: sourceKey.trim(), + session_id: sessionId, + action, + ...(extras?.supersedes_item_id ? { supersedes_item_id: extras.supersedes_item_id } : {}), + ...(extras?.superseded_by_item_id ? { superseded_by_item_id: extras.superseded_by_item_id } : {}), + }, + { idempotencyKey: keyFor(intent) }, + ); + await loadGraphAndStatus(); + setOutput(formatJson({ + status: "success", + message: reviewActionMessage(action), + action, + edge_id: target.id, + result: { + ok: result.ok, + action: result.action, + edge_id: result.edge_id, + }, + note: "调试输出不包含原始聊天文本。", + })); + clear(intent); + } catch (err) { + setOutput(formatJson({ + status: "failed", + message: "关系审核失败:请确认登录会话/权限,以及当前选中的关系仍存在。", + error: err instanceof ApiError || err instanceof Error ? err.message : "edge review failed", + })); + throw err; + } finally { + setReviewing(false); + } + }; + const runHistorySync = async () => { const tenantId = config.tenantId.trim(); const sessionId = requireSelectedGroup(config, verifiedGroupIds); @@ -638,6 +853,7 @@ export function useRelationshipGraphController() { max_windows: windowExtractionMaxWindowsValue, cursor_event_id: windowExtractionCursor, dry_run: windowExtractionDryRun, + include_llm: true, }; const intent = `relationship:window:${tenantId}:${sessionId}:${targetDate}:${windowExtractionSizeValue}:${windowExtractionMaxWindowsValue}:${windowExtractionCursor}:${windowExtractionDryRun}`; const result = await apiRequest>>( @@ -748,6 +964,7 @@ export function useRelationshipGraphController() { cursor_event_id: windowExtractionCursor, dry_run: windowExtractionDryRun, time_budget_seconds: extractionTimeBudgetSeconds, + include_llm: true, }; const intent = `relationship:catchup:${tenantId}:${sessionId}:${targetDate}:${windowExtractionSizeValue}:${windowCatchupMaxWindowsValue}:${windowExtractionCursor}:${windowExtractionDryRun}`; const result = await apiRequest>>( @@ -818,6 +1035,140 @@ export function useRelationshipGraphController() { } }; + const runRecentCoverage = async () => { + const tenantId = config.tenantId.trim(); + const sessionId = requireSelectedGroup(config, verifiedGroupIds); + const normalizedChannel = channel.trim(); + const normalizedSourceKey = sourceKey.trim(); + const connectionId = "legacy-wechat-default"; + const dates = localDateSeries(GRAPH_OVERVIEW_DAYS); + if (!tenantId) { + setSyncOutput(formatJson({ + status: "validation_failed", + message: "校验失败:缺少 tenant_id,未发送近期覆盖请求。", + no_api_request_sent: true, + })); + return; + } + + setSyncing(true); + setExtracting(true); + setSyncOutput(formatJson({ + status: "submitting", + message: `正在同步并抽取最近 ${GRAPH_OVERVIEW_DAYS} 天;不展示聊天原文。`, + scope: { + tenant_id: tenantId, + channel: normalizedChannel, + source_key: normalizedSourceKey, + connection_id: connectionId, + user_scope: optionalUserScopeLabel, + session_id: sessionId, + days_limit: GRAPH_OVERVIEW_DAYS, + dates, + }, + })); + try { + const backfillIntent = `relationship:recent-sync:${tenantId}:${connectionId}:${sessionId}:${GRAPH_OVERVIEW_DAYS}`; + const backfill = await apiRequest(config, "/plugins/memory/backfill", { + auth: true, + init: { + method: "POST", + headers: { + "Content-Type": "application/json", + "Idempotency-Key": keyFor(backfillIntent), + }, + body: JSON.stringify({ + tenant_id: tenantId, + channel: normalizedChannel, + source_key: normalizedSourceKey, + connection_id: connectionId, + session_ids: [sessionId], + days_limit: GRAPH_OVERVIEW_DAYS, + enqueue_llm_jobs: true, + }), + }, + }); + clear(backfillIntent); + + const catchups: Array> = []; + for (const date of dates) { + const intent = `relationship:recent-catchup:${tenantId}:${sessionId}:${date}:${windowExtractionSizeValue}:${windowCatchupMaxWindowsValue}`; + try { + const result = await apiRequest>>( + config, + "/plugins/memory/group-graph/extract-window-catchup", + { + auth: true, + init: { + method: "POST", + headers: { + "Content-Type": "application/json", + "Idempotency-Key": keyFor(intent), + }, + body: JSON.stringify({ + tenant_id: tenantId, + channel: normalizedChannel, + source_key: normalizedSourceKey, + session_id: sessionId, + date, + window_size: windowExtractionSizeValue, + max_windows_per_run: windowCatchupMaxWindowsValue, + cursor_event_id: 0, + dry_run: false, + time_budget_seconds: extractionTimeBudgetSeconds, + include_llm: true, + }), + }, + }, + ); + catchups.push({ + date, + ok: result.ok, + status: result.status, + windows_processed: result.windows_processed ?? 0, + more_remain: result.more_remain, + stop_reason: result.stop_reason, + }); + clear(intent); + } catch (err) { + catchups.push({ + date, + ok: false, + error: err instanceof ApiError || err instanceof Error ? err.message : "window catchup failed", + }); + } + } + + await loadGraphAndStatus({ + fromDate: dates[0] || localDateDaysAgo(GRAPH_OVERVIEW_DAYS - 1), + toDate: "", + }); + setGraphRangeDays(GRAPH_OVERVIEW_DAYS); + setFromDate(dates[0] || localDateDaysAgo(GRAPH_OVERVIEW_DAYS - 1)); + setToDate(""); + setSyncOutput(formatJson({ + status: backfill.ok === false || catchups.some((item) => item.ok === false) + ? "completed_with_warning" + : "success", + message: "近期覆盖已完成:已同步最近几天历史并尽量追平窗口抽取;关系图已刷新。", + days_limit: GRAPH_OVERVIEW_DAYS, + debug: safeBackfillDebug(backfill), + catchups, + note: "调试输出不包含原始聊天文本。", + })); + } catch (err) { + setSyncOutput(formatJson({ + status: "failed", + message: "近期同步抽取失败:请确认登录会话/权限和群聊范围。", + error: err instanceof ApiError || err instanceof Error ? err.message : "recent coverage failed", + })); + throw err; + } finally { + setSyncing(false); + setExtracting(false); + } + }; + useEffect(() => { if (!selectedEdge) { setEvidence(null); @@ -828,8 +1179,8 @@ export function useRelationshipGraphController() { }, [loadEdgeEvidence, selectedEdge?.id, selection]); useEffect(() => { - void Promise.all([loadDateStatuses(), loadJobStats()]); - }, [loadDateStatuses, loadJobStats]); + void Promise.all([loadDateStatuses(), loadJobStats(), loadWindowStats()]); + }, [loadDateStatuses, loadJobStats, loadWindowStats]); useEffect(() => { if (autoLoadedGroupScopeKeyRef.current === autoLoadGroupScopeKey) return; @@ -839,6 +1190,9 @@ export function useRelationshipGraphController() { setLoadedGraphScopeKey(""); setSelection(null); setEvidence(null); + setPendingEdges([]); + setPlaybackDate(""); + setGovernanceStatus(null); setDateRows([]); setJobStats(null); setWindowStats(null); @@ -853,7 +1207,7 @@ export function useRelationshipGraphController() { message: "已切换到当前已验证群聊,正在自动加载关系图。", session_id: selectedGroupId, })); - void loadGraphRef.current(); + void loadGraphAndStatusRef.current(); }, [autoLoadGroupScopeKey, selectedGroupId, selectedGroupIsVerified]); return { @@ -878,6 +1232,11 @@ export function useRelationshipGraphController() { setFromDate, toDate, setToDate, + graphRangeDays, + applyGraphRangeDays, + playbackDate, + applyPlaybackDate, + playbackDates: playbackDateSeries(graphRangeDays, fromDate), nodeSearch, setNodeSearch, edgeSearch, @@ -913,6 +1272,7 @@ export function useRelationshipGraphController() { loading, syncing, extracting, + reviewing, evidence, evidenceLoading, evidenceStatus, @@ -955,12 +1315,19 @@ export function useRelationshipGraphController() { historyNextStep, windowStatsTotals, windowStatsAcceptance, + pendingReviewCount, + pendingEdges, + governanceStatus, + governanceStatusText, neighborNodeIds, graphStateMessage, loadGraph, loadEdgeEvidence, loadGraphAndStatus, showAllGraph, + showPendingReview, + reviewEdge, + runRecentCoverage, runHistorySync, runDailyExtraction, runWindowExtraction, diff --git a/frontend/src/styles/pages/relationship-graph.css b/frontend/src/styles/pages/relationship-graph.css index e4bd755..472ecc8 100644 --- a/frontend/src/styles/pages/relationship-graph.css +++ b/frontend/src/styles/pages/relationship-graph.css @@ -482,6 +482,28 @@ flex-wrap: wrap; } +.relationship-playback { + display: flex; + align-items: center; + gap: var(--space-3); + margin: 0 0 var(--space-2-5); + flex-wrap: wrap; +} + +.relationship-playback label { + display: inline-flex; + align-items: center; + gap: var(--space-2); + min-width: min(100%, 360px); + color: var(--text-muted); + font-size: var(--font-size-sm); + font-weight: 700; +} + +.relationship-playback input[type="range"] { + flex: 1; +} + .relationship-view-tabs { display: inline-flex; gap: var(--space-1); @@ -545,6 +567,48 @@ grid-column: 1 / -1; } +.relationship-queue-count { + min-width: 1.75rem; + padding: var(--space-1) var(--space-2); + border-radius: 999px; + background: var(--color-orange-50); + color: var(--color-orange-700); + font-size: var(--font-size-xs); + font-weight: 800; + text-align: center; +} + +.relationship-queue-item { + display: grid; + gap: var(--space-2); +} + +.relationship-queue-item.is-selected .relationship-list-item { + border-color: rgba(15, 118, 110, 0.45); +} + +.relationship-queue-actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.relationship-review-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2); + margin: var(--space-3) 0 var(--space-2); +} + +.relationship-review-note { + flex: 1 1 100%; + margin: 0; + color: var(--text-muted); + font-size: var(--font-size-sm); + font-weight: 600; +} + .relationship-canvas { width: 100%; aspect-ratio: 46 / 31; @@ -556,6 +620,12 @@ linear-gradient(180deg, rgba(167, 179, 169, 0.1) 1px, transparent 1px), var(--panel); background-size: 32px 32px; + cursor: grab; + touch-action: none; +} + +.relationship-canvas.is-panning { + cursor: grabbing; } .relationship-graph-summary { @@ -592,11 +662,23 @@ } .relationship-edge { - cursor: default; + cursor: pointer; transition: opacity 0.16s ease; } +.relationship-edge-hit { + fill: none; + stroke: transparent; + stroke-width: 14; + stroke-linecap: round; +} + +.relationship-edge.is-playback .relationship-edge-line { + stroke: var(--color-orange-600); +} + .relationship-edge-line { + fill: none; stroke: var(--color-ink-500); stroke-width: 1.5; stroke-linecap: round; @@ -632,7 +714,7 @@ } .relationship-node { - cursor: default; + cursor: pointer; transition: opacity 0.16s ease; } diff --git a/tasks/group-relationship-graph-review-and-auto-extract/PLAN.md b/tasks/group-relationship-graph-review-and-auto-extract/PLAN.md new file mode 100644 index 0000000..2764c5a --- /dev/null +++ b/tasks/group-relationship-graph-review-and-auto-extract/PLAN.md @@ -0,0 +1,85 @@ +# 群聊关系图:边审核 + 自动抽取 + +## 目标 + +把 `/relationship-graph` 从“只能看、只能手点抽取”补成可运营的半成品闭环: + +1. 在详情面板接受或拒绝一条关系(后端 API 已存在)。 +2. 调度进程按已导入的 `plugin_memory_event` 自动做窗口追平,默认同时跑确定性规则和语义 LLM。 + +不提交、不部署,除非另外明确要求。 + +## 不做什么 + +- 不展示聊天原文;不把 `content` / `original_text` / `user_text` 带回 UI。 +- 不改远程 delay/timeout,不上传未配套的 restyle 页面。 +- 不做力导向布局、跨昵称自动身份合并、矛盾自动消解、衰减引擎、聚类算法。 +- 不做角色权限矩阵、重置/清空端点。 +- 窗口抽取的手动 API 行为保持兼容:未显式关闭时仍可走 LLM。 + +## 阶段 1 — 边审核 UI + +### 已有能力 + +- `POST /plugins/memory/group-graph/edges/{id}/acceptance-review` +- `MemoryStore.review_group_relationship_edge` 映射到记忆验收模型 +- 默认图查询只返回已接受边;`acceptance_status=needs_review` 才能看到待审边 + +### 要做 + +- `frontend/src/lib/api.ts` 增加 `reviewGroupGraphEdge` +- 控制器增加 `reviewEdge(action)`、`showPendingReview()`、`reviewing` +- 详情面板对选中边提供「接受 / 拒绝」,走现有 `DangerAction` 确认 +- 页头增加「查看待审核」,切到 `needs_review` 并刷新 +- 测试:模块确认框会调用 controller;controller 会打审核 API 并刷新图 + +### 验收 + +- 待审核边可在 UI 中接受或拒绝,刷新后状态与默认过滤一致 +- 确认框展示群/关系摘要,不含原文 +- 拒绝后默认视图不再显示该边 + +## 阶段 2 — 自动窗口追平 + +### 约束 + +- 只读已导入事件,不在 tick 里打 wxbot 历史接口 +- 默认 `include_llm=True`,并打开图/结构化抽取与任务 drain +- 不按额度做额外限流;调度仍有每轮窗口和时间预算,避免单 tick 占死 +- 仅 `scheduler` 进程跑循环,避免 api/worker 重复写 +- 新边写入 `needs_review` + +### 要做 + +- Settings / `.env.example` / `docker-compose.yml` 增加开关与限额 +- `run_group_relationship_window_extraction` / `catchup` 增加 `include_llm` +- `list_imported_group_graph_targets` 从 `plugin_memory_event` 列出群日 +- `run_group_graph_auto_extract_tick` 做范围门控后追平 +- `MemoryPlugin` 增加可取消循环,镜像治理循环的失败隔离 + +### 验收 + +- 关闭开关或非 scheduler 角色不启动循环 +- `include_llm=False` 时即使 extractor 可用也不调用 LLM +- tick 只处理 `@chatroom` + `__group__` 已导入日 +- 范围门控拒绝的租户/群被跳过,不让整轮失败 + +## 阶段 3 — 验证 + +- 后端已跑:`test_memory_group_graph_auto_extract.py`、`test_config_precedence.py`、`test_memory_graph.py`、`test_memory_router.py -k edge_review or group_graph` +- 前端已跑:`RelationshipModules.test.tsx`、`useRelationshipGraphController.test.tsx` +- 本机没有已登录的控制台会话,未做浏览器点击验收 +- 概览默认最近 7 天;页头展示待审核数量;手动窗口抽取显式带 `include_llm=true` + +## 阶段 4 — 补全可运营缺口 + +已补: + +- 待审核队列(含 `needs_review,candidate`)、过期 / 退回待审、刷新后尽量保留选中 +- 画布点选、平移、滚轮缩放、适应画布;待审虚线、证据线宽、新旧透明度、抽取方式标签 +- 近 7/14/30/全部时间范围;「同步并抽取近 7 天」;自动抽取回看默认 7 天 +- 默认打开 `memory_graph_retrieval_enabled`,已接受关系可进入提示词 + +阶段 5 已补:按日回放、并行边曲线、验收分/别名/替代关系、治理保留摘要、调度对已知群补同步后再抽取。 + +仍不做:跨昵称自动身份合并、矛盾自动消解、衰减/评测引擎、力导向聚类、角色权限矩阵、提交部署 From 40ae0cde724fb4b5de15340b3ab72eb018f076fe Mon Sep 17 00:00:00 2001 From: Agent Console Contributors <33415988+zhx8702@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:44:01 +0800 Subject: [PATCH 3/5] fix(memory): make relationship extraction resumable and safe --- plugins/memory/plugin.py | 17 +- plugins/memory/router.py | 4 + plugins/memory/store_group_graph.py | 329 +++++++++++++++--- .../test_memory_group_graph_auto_extract.py | 299 +++++++++++++++- tests/unit/test_memory_router.py | 4 + 5 files changed, 597 insertions(+), 56 deletions(-) diff --git a/plugins/memory/plugin.py b/plugins/memory/plugin.py index 69a11bf..7836805 100644 --- a/plugins/memory/plugin.py +++ b/plugins/memory/plugin.py @@ -73,11 +73,7 @@ async def initialize(self, ctx: PluginContext) -> None: self._governance_loop(), name="memory-governance-cleanup", ) - if self._should_run_group_graph_auto_extract(): - self._group_graph_auto_extract_task = asyncio.create_task( - self._group_graph_auto_extract_loop(), - name="memory-group-graph-auto-extract", - ) + self._ensure_group_graph_auto_extract_task() async def _scope_execution_allowed( self, @@ -197,6 +193,17 @@ def _should_run_group_graph_auto_extract(self) -> bool: roles = {item.strip().lower() for item in raw.split(",") if item.strip()} return role in roles + def _ensure_group_graph_auto_extract_task(self) -> None: + if not self._should_run_group_graph_auto_extract(): + return + current = self._group_graph_auto_extract_task + if current is not None and not current.done(): + return + self._group_graph_auto_extract_task = asyncio.create_task( + self._group_graph_auto_extract_loop(), + name="memory-group-graph-auto-extract", + ) + async def _group_graph_auto_extract_loop(self) -> None: while self._store is not None and self._ctx is not None: try: diff --git a/plugins/memory/router.py b/plugins/memory/router.py index 0c91265..fb7a53a 100644 --- a/plugins/memory/router.py +++ b/plugins/memory/router.py @@ -467,6 +467,7 @@ class MemoryWindowRelationshipExtractionRequest(StrictRequestModel): cursor_event_id: int | None = None dry_run: bool = False include_llm: bool = True + llm_timeout_seconds: int | None = None def extraction_controls(self) -> dict[str, int | bool]: return { @@ -475,6 +476,9 @@ def extraction_controls(self) -> dict[str, int | bool]: "cursor_event_id": max(0, int(self.cursor_event_id or 0)), "dry_run": bool(self.dry_run), "include_llm": bool(self.include_llm), + "llm_timeout_seconds": max( + 1, min(int(self.llm_timeout_seconds or 60), 180) + ), } diff --git a/plugins/memory/store_group_graph.py b/plugins/memory/store_group_graph.py index 85f6f4d..4b2df90 100644 --- a/plugins/memory/store_group_graph.py +++ b/plugins/memory/store_group_graph.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import json import re from collections.abc import Iterable @@ -40,6 +41,7 @@ _is_group_session_id, _loads_json_object_or_array, _looks_like_wechat_username, + _memory_status_for_acceptance, _merge_group_graph_aliases, _merge_int_lists, _normalize_key, @@ -94,6 +96,18 @@ def _group_graph_edge_quality(item: dict[str, Any] | None) -> dict[str, Any]: } +def _group_graph_auto_cursor_key( + *, + tenant_id: str, + channel: str, + source_key: str, + session_id: str, + target_date: str, +) -> str: + scope = "\x1f".join((tenant_id, channel, source_key, session_id, target_date)) + return f"group-graph-auto-cursor:v1:{_normalize_key(scope)}" + + class MemoryGroupGraphStoreMixin: async def list_memory_graph_entities( self, @@ -1097,6 +1111,8 @@ async def _apply_group_relationship_window_candidate( relation_payload = dict(candidate) relation_payload["evidence_event_ids"] = evidence_event_ids evidence_dates = [target_date] + existing_item: dict[str, Any] | None = None + existing_acceptance: dict[str, Any] = {} existing_items = await self._find_memory_item_by_normalized_key( tenant_id=tenant_id, @@ -1109,11 +1125,17 @@ async def _apply_group_relationship_window_candidate( limit=1, ) if existing_items: - existing_value = existing_items[0].get("value") + existing_item = existing_items[0] + existing_value = existing_item.get("value") if not isinstance(existing_value, dict): - existing_value = _safe_json_loads(existing_items[0].get("value_json"), {}) + existing_value = _safe_json_loads(existing_item.get("value_json"), {}) if not isinstance(existing_value, dict): existing_value = {} + existing_acceptance = ( + dict(existing_value.get("acceptance")) + if isinstance(existing_value.get("acceptance"), dict) + else {} + ) existing_relation = ( existing_value.get("relation") if isinstance(existing_value.get("relation"), dict) @@ -1144,7 +1166,9 @@ async def _apply_group_relationship_window_candidate( )[-90:] relation_source_type = str( - relation_payload.get("extraction_method") or LLM_GROUP_WINDOW_SOURCE_TYPE + (existing_item or {}).get("source_type") + or relation_payload.get("extraction_method") + or LLM_GROUP_WINDOW_SOURCE_TYPE ) if relation_source_type not in { LLM_GROUP_WINDOW_SOURCE_TYPE, @@ -1154,7 +1178,33 @@ async def _apply_group_relationship_window_candidate( # Deterministic means reproducible, not necessarily true. Adjacency and # same-window co-participation are weak evidence and must not enter the # prompt graph without review. - acceptance_status = "needs_review" + prior_acceptance_status = str( + existing_acceptance.get("status") + or (existing_item or {}).get("acceptance_status") + or "" + ).strip().lower() + acceptance_status = ( + prior_acceptance_status + if prior_acceptance_status in {"accepted", "rejected"} + else "needs_review" + ) + acceptance_payload = { + **existing_acceptance, + "status": acceptance_status, + "score": max( + _clamp_score(existing_acceptance.get("score"), 0.0), + _clamp_score(relation_payload.get("confidence"), 0.0), + ), + "reason": str( + existing_acceptance.get("reason") + or relation_payload.get("reason") + or "group_window_relation" + )[:80], + "extraction_confidence": max( + _clamp_score(existing_acceptance.get("extraction_confidence"), 0.0), + _clamp_score(relation_payload.get("confidence"), 0.0), + ), + } value_payload = { "kind": "group_window_relation", "date": target_date, @@ -1168,12 +1218,7 @@ async def _apply_group_relationship_window_candidate( }, "relation": relation_payload, "source_event_ids": evidence_event_ids, - "acceptance": { - "status": acceptance_status, - "score": relation_payload["confidence"], - "reason": str(relation_payload.get("reason") or "group_window_relation")[:80], - "extraction_confidence": relation_payload["confidence"], - }, + "acceptance": acceptance_payload, } is_group_history_scope = user_id == GROUP_HISTORY_USER_ID_SCOPE return await self._insert_or_touch_memory_item( @@ -1192,7 +1237,12 @@ async def _apply_group_relationship_window_candidate( value_json=value_payload, normalized_key=normalized_key, confidence=relation_payload["confidence"], - status="active" if acceptance_status == "accepted" else "pending", + status=( + str(existing_item.get("status") or "pending") + if existing_item is not None + and acceptance_status in {"accepted", "rejected"} + else _memory_status_for_acceptance(acceptance_status, sensitivity="normal") + ), pinned=False, priority=0, sensitivity="normal", @@ -1220,6 +1270,7 @@ async def run_group_relationship_window_extraction( cursor_event_id: int | None = None, dry_run: bool = False, include_llm: bool = True, + llm_timeout_seconds: int | None = None, ) -> dict[str, Any]: session_id = str(session_id or "").strip() if not session_id: @@ -1231,6 +1282,9 @@ async def run_group_relationship_window_extraction( effective_window_size = _clamp_int(window_size, 50, minimum=10, maximum=100) effective_max_windows = _clamp_int(max_windows, 1, minimum=1, maximum=10) effective_cursor = max(0, int(cursor_event_id or 0)) + effective_llm_timeout = _clamp_int( + llm_timeout_seconds, 60, minimum=1, maximum=180 + ) user_id_scope, user_id_auto = _group_history_user_scope(session_id, user_id) if not user_id_scope: raise RuntimeError("user_id required") @@ -1299,6 +1353,7 @@ async def run_group_relationship_window_extraction( "cursor_event_id": effective_cursor, "dry_run": bool(dry_run), "include_llm": bool(include_llm), + "llm_timeout_seconds": effective_llm_timeout, }, "windows": window_summaries, "totals": { @@ -1334,13 +1389,16 @@ async def run_group_relationship_window_extraction( llm_candidates: list[dict[str, Any]] = [] if llm_available: try: - raw_payload = await self._extract_group_relationship_window_candidates( - tenant_id=tenant_id, - trace_id=f"group-window:{target_date}:{window['first_event_id']}:{window['last_event_id']}", - target_date=target_date, - session_id=session_id, - event_ids=window["event_ids"], - transcript=window["transcript"], + raw_payload = await asyncio.wait_for( + self._extract_group_relationship_window_candidates( + tenant_id=tenant_id, + trace_id=f"group-window:{target_date}:{window['first_event_id']}:{window['last_event_id']}", + target_date=target_date, + session_id=session_id, + event_ids=window["event_ids"], + transcript=window["transcript"], + ), + timeout=float(effective_llm_timeout), ) except Exception as exc: logger.warning( @@ -1429,6 +1487,9 @@ async def run_group_relationship_window_catchup( effective_max_windows = _clamp_int(max_windows_per_run, 20, minimum=1, maximum=100) effective_cursor = max(0, int(cursor_event_id or 0)) effective_time_budget = _clamp_int(time_budget_seconds, 60, minimum=1, maximum=180) + per_window_llm_timeout = max( + 1, effective_time_budget // effective_max_windows + ) started_at = monotonic() totals = {"events": 0, "windows": 0, "candidates": 0, "applied": 0, "skipped": 0} controls = { @@ -1438,6 +1499,7 @@ async def run_group_relationship_window_catchup( "dry_run": bool(dry_run), "time_budget_seconds": effective_time_budget, "include_llm": bool(include_llm), + "llm_timeout_seconds": per_window_llm_timeout, } windows_processed = 0 more_remain = False @@ -1446,24 +1508,45 @@ async def run_group_relationship_window_catchup( next_cursor_event_id = effective_cursor while windows_processed < effective_max_windows: - if monotonic() - started_at >= effective_time_budget: + elapsed = monotonic() - started_at + if elapsed >= effective_time_budget: stop_reason = "time_budget_reached" more_remain = True break - batch_limit = min(effective_max_windows - windows_processed, 10) - result = await self.run_group_relationship_window_extraction( - tenant_id=tenant_id, - channel=channel, - source_key=source_key, - session_id=session_id, - user_id=user_id, - date=date, - window_size=effective_window_size, - max_windows=batch_limit, - cursor_event_id=next_cursor_event_id, - dry_run=dry_run, - include_llm=include_llm, + remaining_budget = max(0.001, effective_time_budget - elapsed) + # Keep LLM-backed calls to one window so each successful return is + # also a durable checkpoint for the automatic runner. + batch_limit = ( + 1 + if include_llm + else min(effective_max_windows - windows_processed, 10) ) + try: + result = await asyncio.wait_for( + self.run_group_relationship_window_extraction( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + session_id=session_id, + user_id=user_id, + date=date, + window_size=effective_window_size, + max_windows=batch_limit, + cursor_event_id=next_cursor_event_id, + dry_run=dry_run, + include_llm=include_llm, + llm_timeout_seconds=max( + 1, + min(per_window_llm_timeout, int(remaining_budget)), + ), + ), + timeout=remaining_budget, + ) + except TimeoutError: + stop_reason = "time_budget_reached" + more_remain = True + status = "partial" + break result_totals = result.get("totals") if isinstance(result.get("totals"), dict) else {} processed = int(result_totals.get("windows") or 0) for key in totals: @@ -2084,7 +2167,7 @@ async def list_imported_group_graph_targets( start_at: datetime | None = None, ) -> list[dict[str, Any]]: effective_lookback = _clamp_int(lookback_days, 7, minimum=1, maximum=14) - effective_max_targets = _clamp_int(max_targets, 3, minimum=1, maximum=20) + effective_max_targets = _clamp_int(max_targets, 3, minimum=1, maximum=200) cutoff = start_at or ( datetime.now(UTC).replace(tzinfo=None) - timedelta(days=effective_lookback) ) @@ -2096,7 +2179,7 @@ async def list_imported_group_graph_targets( ) rows = await _exec( "SELECT tenant_id, channel, source_key, session_id, " - "CAST(created_at AS date) AS day, COUNT(*) AS event_count " + "CAST(created_at AS date) AS day, COUNT(*) AS event_count, MAX(id) AS last_event_id " "FROM plugin_memory_event " "WHERE created_at >= :start_at " "AND user_id = :group_uid " @@ -2130,12 +2213,115 @@ async def list_imported_group_graph_targets( "session_id": session_id, "date": date_value, "event_count": int(row.get("event_count") or 0), + "last_event_id": int(row.get("last_event_id") or 0), } ) if len(targets) >= effective_max_targets: break return targets + async def _load_group_graph_auto_extract_cursor( + self, + *, + tenant_id: str, + channel: str, + source_key: str, + session_id: str, + target_date: str, + ) -> int: + cursor_key = _group_graph_auto_cursor_key( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + session_id=session_id, + target_date=target_date, + ) + rows = await _exec( + "SELECT result_json FROM plugin_memory_extraction_job " + "WHERE idempotency_key = :cursor_key LIMIT 1", + {"cursor_key": cursor_key}, + ) + if not rows: + return 0 + raw_payload = rows[0].get("result_json") + payload = ( + raw_payload + if isinstance(raw_payload, dict) + else _safe_json_loads(raw_payload, {}) + ) + if not isinstance(payload, dict) or payload.get("kind") != "group_graph_auto_cursor": + return 0 + expected_scope = { + "tenant_id": tenant_id, + "channel": channel, + "source_key": source_key, + "session_id": session_id, + "date": target_date, + } + if payload.get("scope") != expected_scope: + return 0 + return max(0, _safe_int(payload.get("cursor_event_id"), 0)) + + async def _save_group_graph_auto_extract_cursor( + self, + *, + tenant_id: str, + channel: str, + source_key: str, + session_id: str, + target_date: str, + cursor_event_id: int, + ) -> None: + cursor = max(0, int(cursor_event_id or 0)) + cursor_key = _group_graph_auto_cursor_key( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + session_id=session_id, + target_date=target_date, + ) + payload = json.dumps( + { + "kind": "group_graph_auto_cursor", + "version": 1, + "scope": { + "tenant_id": tenant_id, + "channel": channel, + "source_key": source_key, + "session_id": session_id, + "date": target_date, + }, + "cursor_event_id": cursor, + }, + ensure_ascii=False, + separators=(",", ":"), + ) + await _exec( + "INSERT INTO plugin_memory_extraction_job " + "(tenant_id, channel, source_key, user_id, session_id, source_event_id, " + "source_trace_id, status, attempts, max_attempts, next_run_at, result_json, " + "idempotency_key, created_at, updated_at) " + "VALUES (:tid, :channel, :source_key, :group_uid, :sid, NULL, :trace, " + "'succeeded', 0, 1, NOW(), :result_json, :cursor_key, NOW(), NOW()) " + "ON CONFLICT (idempotency_key) DO UPDATE SET " + "result_json = CASE WHEN COALESCE(NULLIF(" + "plugin_memory_extraction_job.result_json, '')::jsonb ->> 'cursor_event_id', '0')::bigint " + "< :cursor_event_id THEN EXCLUDED.result_json " + "ELSE plugin_memory_extraction_job.result_json END, " + "status = 'succeeded', locked_until = NULL, locked_by = '', updated_at = NOW()", + { + "tid": tenant_id, + "channel": channel, + "source_key": source_key, + "group_uid": GROUP_HISTORY_USER_ID_SCOPE, + "sid": session_id, + "trace": cursor_key[:128], + "result_json": payload, + "cursor_key": cursor_key, + "cursor_event_id": cursor, + }, + ) + async def run_group_graph_auto_extract_tick( self, *, @@ -2148,6 +2334,9 @@ async def run_group_graph_auto_extract_tick( sync_missing_history: bool = False, sync_max_messages: int = 200, ) -> dict[str, Any]: + effective_time_budget = _clamp_int( + time_budget_seconds, 180, minimum=1, maximum=180 + ) skipped: list[dict[str, Any]] = [] synced: list[dict[str, Any]] = [] if sync_missing_history: @@ -2165,18 +2354,21 @@ async def run_group_graph_auto_extract_tick( skipped.append({**session, "reason": "scope_disabled"}) continue try: - backfill = await self.backfill_from_sdk( - tenant_id=tenant_id, - channel=str(session.get("channel") or "wechat"), - source_key=str(session.get("source_key") or "wxbot"), - user_id=None, - session_ids=[session_id], - connection_id="legacy-wechat-default", - days_limit=lookback_days, - max_messages_per_session=_clamp_int( - sync_max_messages, 200, minimum=20, maximum=500 + backfill = await asyncio.wait_for( + self.backfill_from_sdk( + tenant_id=tenant_id, + channel=str(session.get("channel") or "wechat"), + source_key=str(session.get("source_key") or "wxbot"), + user_id=None, + session_ids=[session_id], + connection_id="legacy-wechat-default", + days_limit=lookback_days, + max_messages_per_session=_clamp_int( + sync_max_messages, 200, minimum=20, maximum=500 + ), + enqueue_llm_jobs=bool(include_llm), ), - enqueue_llm_jobs=True, + timeout=float(effective_time_budget), ) except Exception as exc: logger.warning( @@ -2204,9 +2396,13 @@ async def run_group_graph_auto_extract_tick( ) targets = await self.list_imported_group_graph_targets( lookback_days=lookback_days, - max_targets=max_sessions, + max_targets=min( + 200, + max(1, int(max_sessions or 10)) * max(1, int(lookback_days or 7)) * 4, + ), ) results: list[dict[str, Any]] = [] + attempted = 0 for target in targets: tenant_id = str(target.get("tenant_id") or "") session_id = str(target.get("session_id") or "") @@ -2216,16 +2412,34 @@ async def run_group_graph_auto_extract_tick( if not await self._group_graph_auto_extract_scope_allowed(tenant_id, session_id): skipped.append({**target, "reason": "scope_disabled"}) continue + channel = str(target.get("channel") or "wechat") + source_key = str(target.get("source_key") or "wxbot") + target_date = str(target.get("date") or "") + cursor_event_id = await self._load_group_graph_auto_extract_cursor( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + session_id=session_id, + target_date=target_date, + ) + last_event_id = max(0, int(target.get("last_event_id") or 0)) + if last_event_id > 0 and cursor_event_id >= last_event_id: + skipped.append({**target, "reason": "up_to_date"}) + continue + if attempted >= _clamp_int(max_sessions, 10, minimum=1, maximum=20): + break + attempted += 1 try: catchup = await self.run_group_relationship_window_catchup( tenant_id=tenant_id, - channel=str(target.get("channel") or "wechat"), - source_key=str(target.get("source_key") or "wxbot"), + channel=channel, + source_key=source_key, session_id=session_id, - date=str(target.get("date") or ""), + date=target_date, window_size=window_size, max_windows_per_run=max_windows_per_session, - time_budget_seconds=time_budget_seconds, + cursor_event_id=cursor_event_id, + time_budget_seconds=effective_time_budget, include_llm=include_llm, ) except Exception as exc: @@ -2245,6 +2459,19 @@ async def run_group_graph_auto_extract_tick( } ) continue + next_cursor_event_id = max( + cursor_event_id, + int(catchup.get("next_cursor_event_id") or cursor_event_id), + ) + if next_cursor_event_id > cursor_event_id: + await self._save_group_graph_auto_extract_cursor( + tenant_id=tenant_id, + channel=channel, + source_key=source_key, + session_id=session_id, + target_date=target_date, + cursor_event_id=next_cursor_event_id, + ) results.append( { **target, @@ -2252,6 +2479,8 @@ async def run_group_graph_auto_extract_tick( "stop_reason": catchup.get("stop_reason"), "totals": catchup.get("totals") or {}, "more_remain": bool(catchup.get("more_remain")), + "cursor_event_id": cursor_event_id, + "next_cursor_event_id": next_cursor_event_id, } ) return { diff --git a/tests/unit/test_memory_group_graph_auto_extract.py b/tests/unit/test_memory_group_graph_auto_extract.py index 9a0d5db..82fc24d 100644 --- a/tests/unit/test_memory_group_graph_auto_extract.py +++ b/tests/unit/test_memory_group_graph_auto_extract.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio from datetime import date from types import SimpleNamespace from typing import Any @@ -45,6 +46,7 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any] "session_id": "room-a@chatroom", "day": date(2026, 8, 31), "event_count": 12, + "last_event_id": 512, }, { "tenant_id": "demo", @@ -61,6 +63,7 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any] "session_id": "room-b@chatroom", "day": "2026-08-30", "event_count": 4, + "last_event_id": 404, }, ] @@ -75,6 +78,7 @@ async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any] assert targets[0]["date"] == "2026-08-31" assert targets[1]["date"] == "2026-08-30" assert targets[0]["event_count"] == 12 + assert targets[0]["last_event_id"] == 512 @pytest.mark.asyncio @@ -88,6 +92,7 @@ async def allowed(tenant_id: str, session_id: str = "") -> bool: store.combined_history_scope_execution_allowed = allowed catchup_calls: list[dict[str, Any]] = [] + saved_cursors: list[dict[str, Any]] = [] async def fake_targets(**kwargs: Any) -> list[dict[str, Any]]: return [ @@ -116,10 +121,19 @@ async def fake_catchup(**kwargs: Any) -> dict[str, Any]: "stop_reason": "no_more_events", "totals": {"windows": 1, "applied": 2}, "more_remain": False, + "next_cursor_event_id": 500, } + async def fake_load_cursor(**kwargs: Any) -> int: + return 400 + + async def fake_save_cursor(**kwargs: Any) -> None: + saved_cursors.append(kwargs) + monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + monkeypatch.setattr(store, "_load_group_graph_auto_extract_cursor", fake_load_cursor) + monkeypatch.setattr(store, "_save_group_graph_auto_extract_cursor", fake_save_cursor) result = await store.run_group_graph_auto_extract_tick( lookback_days=2, @@ -150,10 +164,12 @@ async def fake_catchup(**kwargs: Any) -> dict[str, Any]: "date": "2026-08-31", "window_size": 50, "max_windows_per_run": 20, + "cursor_event_id": 400, "time_budget_seconds": 180, "include_llm": False, } ] + assert saved_cursors[0]["cursor_event_id"] == 500 @pytest.mark.asyncio @@ -181,6 +197,9 @@ async def fake_catchup(**kwargs: Any) -> dict[str, Any]: monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + monkeypatch.setattr( + store, "_load_group_graph_auto_extract_cursor", lambda **kwargs: asyncio.sleep(0, result=0) + ) result = await store.run_group_graph_auto_extract_tick() @@ -263,6 +282,68 @@ async def noop(*args: Any, **kwargs: Any) -> None: assert result["totals"]["candidates"] >= 1 +@pytest.mark.asyncio +async def test_window_extraction_cancels_hung_llm_at_configured_timeout( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + store.graph_extractor.config = SimpleNamespace(enabled=True) + store.graph_extractor.llm_service = object() + cancelled = asyncio.Event() + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + if "FROM plugin_memory_event" in sql and "id > :cursor_event_id" in sql: + return [ + { + "id": 601, + "user_id": "__group__", + "user_text": "wxid_a: hello", + "created_at": "2026-05-15T08:00:00", + }, + { + "id": 602, + "user_id": "__group__", + "user_text": "wxid_b: 回复: hi", + "created_at": "2026-05-15T08:01:00", + }, + ] + return [] + + async def hung_extract(**kwargs: Any) -> dict[str, Any]: + try: + await asyncio.Event().wait() + finally: + cancelled.set() + + async def fake_apply(**kwargs: Any) -> dict[str, Any]: + return {"id": 1} + + async def noop(*args: Any, **kwargs: Any) -> None: + return None + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + monkeypatch.setattr(store, "_extract_group_relationship_window_candidates", hung_extract) + monkeypatch.setattr(store, "_apply_group_relationship_window_candidate", fake_apply) + monkeypatch.setattr(store, "_refresh_legacy_cache_for_item_scope", noop) + monkeypatch.setattr(store, "_sync_memory_graph_for_item_safe", noop) + monkeypatch.setattr(store, "_sync_memory_vector_for_item_safe", noop) + + result = await store.run_group_relationship_window_extraction( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="room-a@chatroom", + date="2026-05-15", + include_llm=True, + llm_timeout_seconds=1, + ) + + assert result["controls"]["llm_timeout_seconds"] == 1 + assert result["status"] == "partial" + assert result["next_cursor_event_id"] == 602 + assert cancelled.is_set() + + @pytest.mark.asyncio async def test_auto_extract_tick_can_sync_known_sessions_before_catchup( monkeypatch: pytest.MonkeyPatch, @@ -310,6 +391,9 @@ async def allowed(tenant_id: str, session_id: str = "") -> bool: monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) monkeypatch.setattr(store, "backfill_from_sdk", fake_backfill) monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + monkeypatch.setattr( + store, "_load_group_graph_auto_extract_cursor", lambda **kwargs: asyncio.sleep(0, result=0) + ) result = await store.run_group_graph_auto_extract_tick( lookback_days=7, @@ -321,7 +405,7 @@ async def allowed(tenant_id: str, session_id: str = "") -> bool: assert result["synced"][0]["session_id"] == "room-a@chatroom" assert backfill_calls[0]["session_ids"] == ["room-a@chatroom"] assert backfill_calls[0]["days_limit"] == 7 - assert backfill_calls[0]["enqueue_llm_jobs"] is True + assert backfill_calls[0]["enqueue_llm_jobs"] is False assert catchup_calls[0]["session_id"] == "room-a@chatroom" @@ -341,3 +425,216 @@ def test_group_graph_auto_extract_only_starts_on_configured_roles() -> None: plugin._ctx.settings.memory_group_graph_auto_extract_enabled = False assert plugin._should_run_group_graph_auto_extract() is False + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("acceptance_status", "item_status"), + [("accepted", "active"), ("rejected", "pending")], +) +async def test_window_candidate_rerun_preserves_human_review( + monkeypatch: pytest.MonkeyPatch, + acceptance_status: str, + item_status: str, +) -> None: + store = MemoryStore(SimpleNamespace()) + inserted: list[dict[str, Any]] = [] + + async def fake_find(**kwargs: Any) -> list[dict[str, Any]]: + return [{ + "id": 91, + "source_type": "deterministic_group_window", + "status": item_status, + "acceptance_status": acceptance_status, + "value": { + "relation": {"confidence": 0.6, "evidence_event_ids": [10]}, + "evidence_dates": ["2026-08-31"], + "acceptance": { + "status": acceptance_status, + "reviewed_by": "human-admin", + "history": [{"action": acceptance_status}], + }, + }, + }] + + async def fake_insert(**kwargs: Any) -> dict[str, Any]: + inserted.append(kwargs) + return {"id": 91, **kwargs} + + monkeypatch.setattr(store, "_find_memory_item_by_normalized_key", fake_find) + monkeypatch.setattr(store, "_insert_or_touch_memory_item", fake_insert) + + await store._apply_group_relationship_window_candidate( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + user_id="__group__", + session_id="room-a@chatroom", + target_date="2026-08-31", + window={"index": 2, "first_event_id": 10, "last_event_id": 20}, + candidate={ + "subject": "wxid_a", + "subject_type": "person", + "predicate": "knows", + "object": "wxid_b", + "object_type": "person", + "confidence": 0.8, + "evidence_event_ids": [20], + "reason": "rerun", + "extraction_method": "llm_group_window", + }, + ) + + assert inserted[0]["source_type"] == "deterministic_group_window" + assert inserted[0]["status"] == item_status + acceptance = inserted[0]["value_json"]["acceptance"] + assert acceptance["status"] == acceptance_status + assert acceptance["reviewed_by"] == "human-admin" + assert acceptance["history"] == [{"action": acceptance_status}] + + +@pytest.mark.asyncio +async def test_auto_extract_cursor_round_trips_in_durable_job_state( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + state: dict[str, str] = {} + writes: list[tuple[str, dict[str, Any]]] = [] + + async def fake_exec(sql: str, params: dict | None = None) -> list[dict[str, Any]]: + params = params or {} + writes.append((sql, params)) + if sql.startswith("SELECT result_json"): + payload = state.get(str(params["cursor_key"])) + return [{"result_json": payload}] if payload else [] + if sql.startswith("INSERT INTO plugin_memory_extraction_job"): + state[str(params["cursor_key"])] = str(params["result_json"]) + return [] + + monkeypatch.setattr(memory_store_module, "_exec", fake_exec) + scope = { + "tenant_id": "demo", + "channel": "wechat", + "source_key": "wxbot", + "session_id": "room-a@chatroom", + "target_date": "2026-08-31", + } + assert await store._load_group_graph_auto_extract_cursor(**scope) == 0 + await store._save_group_graph_auto_extract_cursor(**scope, cursor_event_id=731) + assert await store._load_group_graph_auto_extract_cursor(**scope) == 731 + insert_sql, insert_params = next( + (sql, params) for sql, params in writes if sql.startswith("INSERT INTO") + ) + assert "ON CONFLICT (idempotency_key) DO UPDATE" in insert_sql + assert "< :cursor_event_id" in insert_sql + assert insert_params["cursor_event_id"] == 731 + + +@pytest.mark.asyncio +async def test_auto_extract_skips_completed_front_target_without_starving_next( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + catchup_sessions: list[str] = [] + + async def fake_targets(**kwargs: Any) -> list[dict[str, Any]]: + return [ + { + "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", + "session_id": "room-a@chatroom", "date": "2026-08-31", + "event_count": 10, "last_event_id": 100, + }, + { + "tenant_id": "demo", "channel": "wechat", "source_key": "wxbot", + "session_id": "room-b@chatroom", "date": "2026-08-31", + "event_count": 10, "last_event_id": 200, + }, + ] + + async def fake_load_cursor(**kwargs: Any) -> int: + return 100 if kwargs["session_id"] == "room-a@chatroom" else 150 + + async def fake_catchup(**kwargs: Any) -> dict[str, Any]: + catchup_sessions.append(kwargs["session_id"]) + return { + "status": "completed", + "stop_reason": "no_more_events", + "totals": {"windows": 1}, + "more_remain": False, + "next_cursor_event_id": 200, + } + + async def fake_save_cursor(**kwargs: Any) -> None: + return None + + monkeypatch.setattr(store, "list_imported_group_graph_targets", fake_targets) + monkeypatch.setattr(store, "_load_group_graph_auto_extract_cursor", fake_load_cursor) + monkeypatch.setattr(store, "_save_group_graph_auto_extract_cursor", fake_save_cursor) + monkeypatch.setattr(store, "run_group_relationship_window_catchup", fake_catchup) + + result = await store.run_group_graph_auto_extract_tick(max_sessions=1) + + assert catchup_sessions == ["room-b@chatroom"] + assert result["skipped"][0]["reason"] == "up_to_date" + assert result["results"][0]["cursor_event_id"] == 150 + assert result["results"][0]["next_cursor_event_id"] == 200 + + +@pytest.mark.asyncio +async def test_window_catchup_hard_stops_a_hung_window_at_time_budget( + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = MemoryStore(SimpleNamespace()) + cancelled = asyncio.Event() + + async def hung_window(**kwargs: Any) -> dict[str, Any]: + try: + await asyncio.Event().wait() + finally: + cancelled.set() + + monkeypatch.setattr(store, "run_group_relationship_window_extraction", hung_window) + + result = await store.run_group_relationship_window_catchup( + tenant_id="demo", + channel="wechat", + source_key="wxbot", + session_id="room-a@chatroom", + date="2026-08-31", + time_budget_seconds=1, + ) + + assert result["status"] == "partial" + assert result["stop_reason"] == "time_budget_reached" + assert result["more_remain"] is True + assert cancelled.is_set() + + +@pytest.mark.asyncio +async def test_group_graph_auto_extract_task_start_is_unique() -> None: + plugin = MemoryPlugin() + plugin._ctx = SimpleNamespace( + settings=SimpleNamespace( + memory_group_graph_auto_extract_enabled=True, + memory_group_graph_auto_extract_roles="scheduler", + app_process_role="scheduler", + ) + ) + plugin._store = object() # type: ignore[assignment] + started = asyncio.Event() + release = asyncio.Event() + + async def fake_loop() -> None: + started.set() + await release.wait() + + plugin._group_graph_auto_extract_loop = fake_loop # type: ignore[method-assign] + plugin._ensure_group_graph_auto_extract_task() + first_task = plugin._group_graph_auto_extract_task + plugin._ensure_group_graph_auto_extract_task() + + assert plugin._group_graph_auto_extract_task is first_task + assert first_task is not None + await started.wait() + release.set() + await first_task diff --git a/tests/unit/test_memory_router.py b/tests/unit/test_memory_router.py index 5849b17..01b9d72 100644 --- a/tests/unit/test_memory_router.py +++ b/tests/unit/test_memory_router.py @@ -350,6 +350,7 @@ async def run_group_relationship_window_extraction(self, **kwargs): "max_windows": kwargs["max_windows"], "cursor_event_id": kwargs["cursor_event_id"], "dry_run": kwargs["dry_run"], + "llm_timeout_seconds": kwargs["llm_timeout_seconds"], }, "windows": [{ "index": 1, @@ -2872,6 +2873,7 @@ async def test_memory_router_window_group_relationship_extraction_requires_admin "max_windows": 50, "cursor_event_id": -10, "dry_run": True, + "llm_timeout_seconds": 999, } async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: forbidden_resp = await client.post("/plugins/memory/group-graph/extract-window", json=body) @@ -2890,6 +2892,7 @@ async def test_memory_router_window_group_relationship_extraction_requires_admin "max_windows": 10, "cursor_event_id": 0, "dry_run": True, + "llm_timeout_seconds": 180, } assert payload["totals"]["applied"] == 1 assert store.window_relationship_calls == [{ @@ -2904,6 +2907,7 @@ async def test_memory_router_window_group_relationship_extraction_requires_admin "cursor_event_id": 0, "dry_run": True, "include_llm": True, + "llm_timeout_seconds": 180, }] serialized = str(payload) assert "content" not in serialized From 0337bc599d9ece261efc2a1f3579fa3904c6277e Mon Sep 17 00:00:00 2001 From: Agent Console Contributors <33415988+zhx8702@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:44:30 +0800 Subject: [PATCH 4/5] fix(ui): authenticate and surface relationship graph reviews --- frontend/src/lib/api.ts | 19 ++-- .../src/pages/ScopedDomainSafety.test.tsx | 2 +- .../RelationshipGraphPresentation.tsx | 13 ++- .../RelationshipGraphWorkspace.tsx | 6 ++ .../RelationshipModules.test.tsx | 13 ++- .../relationshipGraphApi.test.ts | 69 ++++++++++++ .../useRelationshipGraphController.test.tsx | 97 ++++++++++++++++- .../useRelationshipGraphController.ts | 101 ++++++++++++------ 8 files changed, 274 insertions(+), 46 deletions(-) create mode 100644 frontend/src/pages/relationship-graph/relationshipGraphApi.test.ts diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 7146031..5316886 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -892,8 +892,14 @@ export type GroupGraphEdgeReviewResponse = { [key: string]: unknown; }; -export async function getGroupGraph(config: ConsoleConfig, query: GroupGraphQuery) { - return apiRequest(config, "/plugins/memory/group-graph", { query }); +export async function getGroupGraph( + config: ConsoleConfig, + query: GroupGraphQuery, +) { + return apiRequest(config, "/plugins/memory/group-graph", { + auth: true, + query, + }); } export async function getGroupGraphEdgeEvidence( @@ -904,12 +910,15 @@ export async function getGroupGraphEdgeEvidence( return apiRequest( config, `/plugins/memory/group-graph/evidence/${encodeURIComponent(edgeId)}`, - { query }, + { auth: true, query }, ); } export async function getGroupGraphHistoryDates(config: ConsoleConfig, query: GroupGraphHistoryDatesQuery) { - return apiRequest(config, "/plugins/memory/group-graph/history-dates", { query }); + return apiRequest(config, "/plugins/memory/group-graph/history-dates", { + auth: true, + query, + }); } export async function getMemoryExtractionJobStats(config: ConsoleConfig, query: MemoryExtractionJobStatsQuery) { @@ -963,7 +972,6 @@ export async function reviewGroupGraphEdge( config: ConsoleConfig, edgeId: string, body: GroupGraphEdgeReviewRequest, - options?: { idempotencyKey?: string }, ) { return apiRequest( config, @@ -974,7 +982,6 @@ export async function reviewGroupGraphEdge( method: "POST", headers: { "Content-Type": "application/json", - ...(options?.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}), }, body: JSON.stringify(body), }, diff --git a/frontend/src/pages/ScopedDomainSafety.test.tsx b/frontend/src/pages/ScopedDomainSafety.test.tsx index 8900316..f38346d 100644 --- a/frontend/src/pages/ScopedDomainSafety.test.tsx +++ b/frontend/src/pages/ScopedDomainSafety.test.tsx @@ -79,7 +79,7 @@ describe("scoped domain pages with HttpOnly authentication", () => { await waitFor(() => expect(action).toBeEnabled()); const writeCall = apiRequestMock.mock.calls.find(([, path]) => path === "/plugins/memory/group-graph/extract-daily"); expect(writeCall?.[2]?.auth).toBe(true); - expect((writeCall?.[2]?.init?.headers as Record)["Idempotency-Key"]).toMatch(/^agent-console:/); + expect((writeCall?.[2]?.init?.headers as Record)["Idempotency-Key"]).toBeUndefined(); unmount(); }); diff --git a/frontend/src/pages/relationship-graph/RelationshipGraphPresentation.tsx b/frontend/src/pages/relationship-graph/RelationshipGraphPresentation.tsx index 1cb381e..9c76ec4 100644 --- a/frontend/src/pages/relationship-graph/RelationshipGraphPresentation.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipGraphPresentation.tsx @@ -62,6 +62,8 @@ export type RelationshipGraphPresentationProps = Pick< | "applyPlaybackDate" | "playbackDates" | "pendingEdges" + | "pendingReviewError" + | "pendingReviewLoading" | "reviewing" | "reviewEdge" >; @@ -181,6 +183,8 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese applyPlaybackDate, playbackDates, pendingEdges, + pendingReviewError, + pendingReviewLoading, reviewing, reviewEdge, } = controller; @@ -408,6 +412,11 @@ export function RelationshipGraphPresentation(controller: RelationshipGraphPrese {pendingEdges.length}
+ {pendingReviewError && ( +

+ {pendingReviewError} +

+ )} {pendingEdges.map((edge) => (
))} - {!pendingEdges.length && ( -

{loading ? "正在加载待审核关系..." : "当前时间范围内没有待审核关系。"}

+ {!pendingReviewError && !pendingEdges.length && ( +

{pendingReviewLoading ? "正在加载待审核关系..." : "当前时间范围内没有待审核关系。"}

)}
diff --git a/frontend/src/pages/relationship-graph/RelationshipGraphWorkspace.tsx b/frontend/src/pages/relationship-graph/RelationshipGraphWorkspace.tsx index 88c1acd..021c424 100644 --- a/frontend/src/pages/relationship-graph/RelationshipGraphWorkspace.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipGraphWorkspace.tsx @@ -51,6 +51,12 @@ export function RelationshipGraphWorkspace() { } /> + {(controller.graphError || controller.reviewError) && ( +

+ {controller.reviewError || controller.graphError} +

+ )} +
diff --git a/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx b/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx index f0adcf5..1b53f9e 100644 --- a/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx +++ b/frontend/src/pages/relationship-graph/RelationshipModules.test.tsx @@ -144,11 +144,13 @@ describe("relationship graph modules", () => { applyPlaybackDate: vi.fn(), playbackDates: ["2026-08-25", "2026-08-26", "2026-08-27"], pendingEdges: [pendingEdge], + pendingReviewError: "", + pendingReviewLoading: false, reviewing: false, reviewEdge, } satisfies RelationshipGraphPresentationProps; - render(); + const { rerender } = render(); const nodeList = screen.getByRole("region", { name: "节点列表" }); const edgeList = screen.getByRole("region", { name: "关系列表" }); const queue = screen.getByRole("region", { name: "待审核队列" }); @@ -177,6 +179,15 @@ describe("relationship graph modules", () => { const dialog = screen.getByRole("dialog", { name: "确认接受该关系" }); await user.click(within(dialog).getByRole("button", { name: "确认接受" })); expect(reviewEdge).toHaveBeenCalledWith("accept", pendingEdge); + + rerender( + , + ); + expect(screen.getByRole("alert")).toHaveTextContent("待审核关系加载失败"); }); it("confirms edge acceptance, expiry and return-to-review from the detail panel", async () => { diff --git a/frontend/src/pages/relationship-graph/relationshipGraphApi.test.ts b/frontend/src/pages/relationship-graph/relationshipGraphApi.test.ts new file mode 100644 index 0000000..0261be8 --- /dev/null +++ b/frontend/src/pages/relationship-graph/relationshipGraphApi.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import type { ConsoleConfig } from "../../state/console-config"; +import { + getGroupGraph, + getGroupGraphEdgeEvidence, + getGroupGraphHistoryDates, + reviewGroupGraphEdge, +} from "../../lib/api"; + +const config: ConsoleConfig = { + apiBaseUrl: "http://console.test", + adminToken: "admin-token", + tenantId: "default", + sessionId: "group-a@chatroom", + userId: "", +}; + +describe("relationship graph API contracts", () => { + beforeEach(() => { + vi.stubGlobal( + "fetch", + vi.fn().mockImplementation(() => Promise.resolve( + new Response(JSON.stringify({ nodes: [], edges: [], items: [] }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), + )), + ); + }); + + it("uses management authentication for graph, pending, evidence and history queries", async () => { + await getGroupGraph(config, { + tenant_id: "default", + session_id: "group-a@chatroom", + }); + await getGroupGraph(config, { + tenant_id: "default", + session_id: "group-a@chatroom", + acceptance_status: "needs_review,candidate", + }); + await getGroupGraphEdgeEvidence(config, "edge/1", { + tenant_id: "default", + session_id: "group-a@chatroom", + }); + await getGroupGraphHistoryDates(config, { + tenant_id: "default", + session_id: "group-a@chatroom", + }); + + for (const [, init] of vi.mocked(fetch).mock.calls) { + expect(init).toEqual(expect.objectContaining({ credentials: "include" })); + expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer admin-token"); + } + }); + + it("does not send a fake idempotency key for non-idempotent edge review", async () => { + await reviewGroupGraphEdge(config, "edge-1", { + tenant_id: "default", + session_id: "group-a@chatroom", + action: "accept", + }); + + const [, init] = vi.mocked(fetch).mock.calls[0]; + const headers = new Headers(init?.headers); + expect(headers.get("Authorization")).toBe("Bearer admin-token"); + expect(headers.has("Idempotency-Key")).toBe(false); + }); +}); diff --git a/frontend/src/pages/relationship-graph/useRelationshipGraphController.test.tsx b/frontend/src/pages/relationship-graph/useRelationshipGraphController.test.tsx index bc0fdea..291962a 100644 --- a/frontend/src/pages/relationship-graph/useRelationshipGraphController.test.tsx +++ b/frontend/src/pages/relationship-graph/useRelationshipGraphController.test.tsx @@ -5,6 +5,7 @@ import type { GroupGraphResponse } from "../../lib/api"; import { useRelationshipGraphController } from "./useRelationshipGraphController"; const apiMocks = vi.hoisted(() => ({ + apiRequest: vi.fn(), getGroupGraph: vi.fn(), getGroupGraphEdgeEvidence: vi.fn(), getGroupGraphHistoryDates: vi.fn(), @@ -30,6 +31,7 @@ vi.mock("../../lib/api", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, + apiRequest: apiMocks.apiRequest, getGroupGraph: apiMocks.getGroupGraph, getGroupGraphEdgeEvidence: apiMocks.getGroupGraphEdgeEvidence, getGroupGraphHistoryDates: apiMocks.getGroupGraphHistoryDates, @@ -72,6 +74,7 @@ describe("useRelationshipGraphController verified group loading", () => { sessionId: "group-a@chatroom", userId: "", }; + apiMocks.apiRequest.mockReset().mockResolvedValue({ ok: true, jobs: {}, counts: {} }); apiMocks.getGroupGraph.mockReset(); apiMocks.getGroupGraphEdgeEvidence.mockReset().mockResolvedValue({ edge: { id: "edge-1" } }); apiMocks.getGroupGraphHistoryDates.mockReset().mockResolvedValue({ items: [] }); @@ -166,7 +169,6 @@ describe("useRelationshipGraphController verified group loading", () => { session_id: "group-a@chatroom", action: "accept", }), - expect.objectContaining({ idempotencyKey: expect.any(String) }), ); expect(apiMocks.getGroupGraph.mock.calls.length).toBeGreaterThan(1); }); @@ -210,7 +212,6 @@ describe("useRelationshipGraphController verified group loading", () => { expect.anything(), "edge-1", expect.objectContaining({ action: "expire" }), - expect.objectContaining({ idempotencyKey: expect.any(String) }), ); }); @@ -249,4 +250,96 @@ describe("useRelationshipGraphController verified group loading", () => { expect.objectContaining({ from: "2026-08-20", to: "2026-08-21" }), ); }); + + it("uses admin auth for pending queries and keeps their endpoint nodes", async () => { + const pendingEdge = { + id: "edge-pending", + from: "person:review-a", + to: "topic:review-b", + type: "replied_to", + acceptance_status: "needs_review", + }; + apiMocks.getGroupGraph.mockImplementation((_config, query) => { + if (query.acceptance_status === "needs_review,candidate") { + return Promise.resolve({ + nodes: [ + { id: "person:review-a", type: "person", label: "待审成员甲" }, + { id: "topic:review-b", type: "topic", label: "待审话题乙" }, + ], + edges: [pendingEdge], + }); + } + return Promise.resolve(graphFor("group-a@chatroom")); + }); + + const { result } = renderHook(() => useRelationshipGraphController()); + + await waitFor(() => expect(result.current.pendingEdges).toEqual([pendingEdge])); + expect(apiMocks.getGroupGraph).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ acceptance_status: "needs_review,candidate" }), + ); + expect(result.current.nodesById.get("person:review-a")?.label).toBe("待审成员甲"); + expect(result.current.nodesById.get("topic:review-b")?.label).toBe("待审话题乙"); + }); + + it("exposes pending-query and review failures without claiming review idempotency", async () => { + const edge = { + id: "edge-1", + from: "person:a", + to: "person:b", + type: "replied_to", + acceptance_status: "needs_review", + }; + apiMocks.getGroupGraph.mockImplementation((_config, query) => ( + query.acceptance_status === "needs_review,candidate" + ? Promise.reject(new Error("admin session required")) + : Promise.resolve({ + nodes: [ + { id: "person:a", type: "person", label: "甲" }, + { id: "person:b", type: "person", label: "乙" }, + ], + edges: [edge], + }) + )); + apiMocks.reviewGroupGraphEdge.mockRejectedValue(new Error("review conflict")); + + const { result } = renderHook(() => useRelationshipGraphController()); + await waitFor(() => expect(result.current.pendingReviewError).toContain("admin session required")); + + act(() => { + result.current.setSelection({ kind: "edge", item: edge }); + }); + await act(async () => { + await expect(result.current.reviewEdge("accept")).rejects.toThrow("review conflict"); + }); + + expect(result.current.reviewError).toContain("review conflict"); + expect(apiMocks.reviewGroupGraphEdge).toHaveBeenCalledWith( + expect.anything(), + "edge-1", + expect.objectContaining({ action: "accept" }), + ); + expect(apiMocks.reviewGroupGraphEdge.mock.calls[0]).toHaveLength(3); + }); + + it("calls extraction endpoints without attaching frontend-only idempotency options", async () => { + apiMocks.getGroupGraph.mockResolvedValue(graphFor("group-a@chatroom")); + const { result } = renderHook(() => useRelationshipGraphController()); + await waitFor(() => expect(result.current.graph).not.toBeNull()); + + await act(async () => { + await result.current.runDailyExtraction(); + }); + + expect(apiMocks.apiRequest).toHaveBeenCalledWith( + expect.anything(), + "/plugins/memory/group-graph/extract-daily", + expect.objectContaining({ auth: true }), + ); + const extractionCall = apiMocks.apiRequest.mock.calls.find(([, path]) => ( + path === "/plugins/memory/group-graph/extract-daily" + )); + expect(new Headers(extractionCall?.[2]?.init?.headers).has("Idempotency-Key")).toBe(false); + }); }); diff --git a/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts b/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts index da799bb..c7d2b40 100644 --- a/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts +++ b/frontend/src/pages/relationship-graph/useRelationshipGraphController.ts @@ -17,6 +17,7 @@ import { type GroupGraphEdgeReviewAction, type GroupGraphEdgeEvidenceResponse, type GroupGraphHistoryDateRow, + type GroupGraphNode, type GroupGraphResponse, type GroupGraphWindowStatsResponse, type MemoryBackfillResponse, @@ -103,6 +104,9 @@ export function useRelationshipGraphController() { const [syncing, setSyncing] = useState(false); const [extracting, setExtracting] = useState(false); const [reviewing, setReviewing] = useState(false); + const [graphError, setGraphError] = useState(""); + const [pendingReviewError, setPendingReviewError] = useState(""); + const [reviewError, setReviewError] = useState(""); const [evidence, setEvidence] = useState(null); const [evidenceLoading, setEvidenceLoading] = useState(false); const [evidenceStatus, setEvidenceStatus] = useState("选择一条关系后会自动加载证据来源。"); @@ -114,6 +118,8 @@ export function useRelationshipGraphController() { const [windowStats, setWindowStats] = useState(null); const [windowStatsStatus, setWindowStatsStatus] = useState("选择已验证群聊后可查看窗口关系统计。"); const [pendingEdges, setPendingEdges] = useState([]); + const [pendingNodes, setPendingNodes] = useState([]); + const [pendingReviewLoading, setPendingReviewLoading] = useState(false); const selectedNode = selection?.kind === "node" ? selection.item : null; const selectedEdge = selection?.kind === "edge" ? selection.item : null; const selectionRef = useRef(selection); @@ -146,7 +152,7 @@ export function useRelationshipGraphController() { edgeTypeOptions, nodes, edges, - nodesById, + nodesById: graphNodesById, modeFilteredNodes, graphNodes, graphEdges, @@ -177,8 +183,16 @@ export function useRelationshipGraphController() { estimatedExtractionClicks, historyNextStep, neighborNodeIds, - graphStateMessage, + graphStateMessage: projectedGraphStateMessage, } = projection; + const nodesById = useMemo(() => { + const merged = new Map(pendingNodes.map((node) => [node.id, node])); + for (const [nodeId, node] of graphNodesById) { + merged.set(nodeId, node); + } + return merged; + }, [graphNodesById, pendingNodes]); + const graphStateMessage = graphError || projectedGraphStateMessage; const pendingReviewCount = pendingEdges.length || Number(windowStatsAcceptance.needs_review || 0) + Number(windowStatsAcceptance.candidate || 0); @@ -281,14 +295,16 @@ export function useRelationshipGraphController() { graphRequestIdRef.current = requestId; const requestScopeKey = currentGraphScopeKey; const queryEdgeType = overrides.edgeType ?? edgeType; + const queryAcceptanceStatus = overrides.acceptanceStatus ?? acceptanceStatus; setLoading(true); + setGraphError(""); try { const result = await getGroupGraph(config, { tenant_id: config.tenantId, channel, source_key: sourceKey, session_id: selectedGroupId, - acceptance_status: overrides.acceptanceStatus ?? acceptanceStatus, + acceptance_status: queryAcceptanceStatus, node_type: overrides.nodeType ?? nodeType, edge_type: queryEdgeType, relation_type: queryEdgeType, @@ -300,6 +316,7 @@ export function useRelationshipGraphController() { if (graphRequestIdRef.current !== requestId || activeGraphScopeKeyRef.current !== requestScopeKey) return; setLoadedGraph(result); setLoadedGraphScopeKey(requestScopeKey); + setGraphError(""); const nextSelection = restoreGraphSelection(selectionRef.current, result); setSelection(nextSelection); if (!nextSelection) { @@ -325,8 +342,11 @@ export function useRelationshipGraphController() { setSelection(null); setEvidence(null); setEvidenceStatus("关系图加载失败,暂无证据来源。"); + const message = err instanceof ApiError || err instanceof Error ? err.message : "group graph request failed"; + setGraphError(`关系图加载失败:${message}`); setOutput(formatJson({ - error: err instanceof ApiError || err instanceof Error ? err.message : "group graph request failed", + status: "failed", + error: message, })); } finally { if (graphRequestIdRef.current === requestId && activeGraphScopeKeyRef.current === requestScopeKey) { @@ -410,9 +430,14 @@ export function useRelationshipGraphController() { const tenantId = config.tenantId.trim(); if (!tenantId || !selectedGroupIsVerified) { setPendingEdges([]); + setPendingNodes([]); + setPendingReviewError(""); + setPendingReviewLoading(false); return; } const requestScopeKey = currentGraphScopeKey; + setPendingReviewLoading(true); + setPendingReviewError(""); try { const result = await getGroupGraph(config, { tenant_id: tenantId, @@ -426,9 +451,21 @@ export function useRelationshipGraphController() { }); if (activeGraphScopeKeyRef.current !== requestScopeKey) return; setPendingEdges(result.edges || []); - } catch { + setPendingNodes(result.nodes || []); + setPendingReviewError(""); + } catch (err) { if (activeGraphScopeKeyRef.current !== requestScopeKey) return; setPendingEdges([]); + setPendingNodes([]); + setPendingReviewError( + `待审核关系加载失败:${ + err instanceof ApiError || err instanceof Error ? err.message : "pending review request failed" + }`, + ); + } finally { + if (activeGraphScopeKeyRef.current === requestScopeKey) { + setPendingReviewLoading(false); + } } }, [channel, config, currentGraphScopeKey, fromDate, selectedGroupId, selectedGroupIsVerified, sourceKey, toDate]); @@ -563,6 +600,7 @@ export function useRelationshipGraphController() { const target = edge ?? selectedEdge; if (!target) { const error = new Error("请先选择一条关系"); + setReviewError(error.message); setOutput(formatJson({ status: "validation_failed", message: error.message, @@ -574,8 +612,8 @@ export function useRelationshipGraphController() { selectionRef.current = nextSelection; setSelection(nextSelection); setReviewing(true); + setReviewError(""); try { - const intent = `relationship:review:${tenantId}:${sessionId}:${target.id}:${action}:${extras?.supersedes_item_id || ""}`; const result = await reviewGroupGraphEdge( config, target.id, @@ -588,7 +626,6 @@ export function useRelationshipGraphController() { ...(extras?.supersedes_item_id ? { supersedes_item_id: extras.supersedes_item_id } : {}), ...(extras?.superseded_by_item_id ? { superseded_by_item_id: extras.superseded_by_item_id } : {}), }, - { idempotencyKey: keyFor(intent) }, ); await loadGraphAndStatus(); setOutput(formatJson({ @@ -603,12 +640,14 @@ export function useRelationshipGraphController() { }, note: "调试输出不包含原始聊天文本。", })); - clear(intent); + setReviewError(""); } catch (err) { + const message = err instanceof ApiError || err instanceof Error ? err.message : "edge review failed"; + setReviewError(`关系审核失败:${message}`); setOutput(formatJson({ status: "failed", message: "关系审核失败:请确认登录会话/权限,以及当前选中的关系仍存在。", - error: err instanceof ApiError || err instanceof Error ? err.message : "edge review failed", + error: message, })); throw err; } finally { @@ -742,7 +781,6 @@ export function useRelationshipGraphController() { continuous: extractionContinuous, time_budget_seconds: extractionTimeBudgetSeconds, }; - const intent = `relationship:daily:${tenantId}:${sessionId}:${targetDate}:${extractionBatchSize}:${extractionMaxJobCount}:${extractionContinuous}`; const result = await apiRequest>>( config, "/plugins/memory/group-graph/extract-daily", @@ -750,10 +788,7 @@ export function useRelationshipGraphController() { auth: true, init: { method: "POST", - headers: { - "Content-Type": "application/json", - "Idempotency-Key": keyFor(intent), - }, + headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }, }, @@ -790,7 +825,6 @@ export function useRelationshipGraphController() { }, note: "调试输出仅保留状态和计数,不显示原始聊天内容。", })); - clear(intent); } catch (err) { setSyncOutput(formatJson({ status: "failed", @@ -855,7 +889,6 @@ export function useRelationshipGraphController() { dry_run: windowExtractionDryRun, include_llm: true, }; - const intent = `relationship:window:${tenantId}:${sessionId}:${targetDate}:${windowExtractionSizeValue}:${windowExtractionMaxWindowsValue}:${windowExtractionCursor}:${windowExtractionDryRun}`; const result = await apiRequest>>( config, "/plugins/memory/group-graph/extract-window", @@ -863,10 +896,7 @@ export function useRelationshipGraphController() { auth: true, init: { method: "POST", - headers: { - "Content-Type": "application/json", - "Idempotency-Key": keyFor(intent), - }, + headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }, }, @@ -899,7 +929,6 @@ export function useRelationshipGraphController() { }, note: "调试输出不包含原始聊天文本。", })); - clear(intent); } catch (err) { setSyncOutput(formatJson({ status: "failed", @@ -966,7 +995,6 @@ export function useRelationshipGraphController() { time_budget_seconds: extractionTimeBudgetSeconds, include_llm: true, }; - const intent = `relationship:catchup:${tenantId}:${sessionId}:${targetDate}:${windowExtractionSizeValue}:${windowCatchupMaxWindowsValue}:${windowExtractionCursor}:${windowExtractionDryRun}`; const result = await apiRequest>>( config, "/plugins/memory/group-graph/extract-window-catchup", @@ -974,10 +1002,7 @@ export function useRelationshipGraphController() { auth: true, init: { method: "POST", - headers: { - "Content-Type": "application/json", - "Idempotency-Key": keyFor(intent), - }, + headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }, }, @@ -996,8 +1021,13 @@ export function useRelationshipGraphController() { }); setWindowStats(refreshedWindowStats); setWindowStatsStatus("窗口关系统计已加载;仅显示计数。"); - } catch { + } catch (err) { refreshedWindowStats = null; + setWindowStatsStatus( + `窗口关系统计刷新失败:${ + err instanceof ApiError || err instanceof Error ? err.message : "window stats request failed" + }`, + ); } await loadGraphAndStatus(); setSyncOutput(formatJson({ @@ -1022,7 +1052,6 @@ export function useRelationshipGraphController() { }, note: "调试输出不包含原始聊天文本。", })); - clear(intent); } catch (err) { setSyncOutput(formatJson({ status: "failed", @@ -1092,7 +1121,6 @@ export function useRelationshipGraphController() { const catchups: Array> = []; for (const date of dates) { - const intent = `relationship:recent-catchup:${tenantId}:${sessionId}:${date}:${windowExtractionSizeValue}:${windowCatchupMaxWindowsValue}`; try { const result = await apiRequest>>( config, @@ -1101,10 +1129,7 @@ export function useRelationshipGraphController() { auth: true, init: { method: "POST", - headers: { - "Content-Type": "application/json", - "Idempotency-Key": keyFor(intent), - }, + headers: { "Content-Type": "application/json" }, body: JSON.stringify({ tenant_id: tenantId, channel: normalizedChannel, @@ -1129,7 +1154,6 @@ export function useRelationshipGraphController() { more_remain: result.more_remain, stop_reason: result.stop_reason, }); - clear(intent); } catch (err) { catchups.push({ date, @@ -1191,6 +1215,11 @@ export function useRelationshipGraphController() { setSelection(null); setEvidence(null); setPendingEdges([]); + setPendingNodes([]); + setGraphError(""); + setPendingReviewError(""); + setReviewError(""); + setPendingReviewLoading(false); setPlaybackDate(""); setGovernanceStatus(null); setDateRows([]); @@ -1273,6 +1302,9 @@ export function useRelationshipGraphController() { syncing, extracting, reviewing, + graphError, + pendingReviewError, + reviewError, evidence, evidenceLoading, evidenceStatus, @@ -1317,6 +1349,7 @@ export function useRelationshipGraphController() { windowStatsAcceptance, pendingReviewCount, pendingEdges, + pendingReviewLoading, governanceStatus, governanceStatusText, neighborNodeIds, From 3f8e0d860cf2816c93cc4a488b48e2780ff55621 Mon Sep 17 00:00:00 2001 From: Agent Console Contributors <33415988+zhx8702@users.noreply.github.com> Date: Wed, 2 Sep 2026 17:00:32 +0800 Subject: [PATCH 5/5] refactor(memory): keep automatic graph extraction opt-in --- .env.example | 44 ++++++++++++++-------------- app/common/config.py | 22 +++++++------- docker-compose.yml | 22 +++++++------- tests/unit/test_config_precedence.py | 19 ++++++------ 4 files changed, 54 insertions(+), 53 deletions(-) diff --git a/.env.example b/.env.example index 13ca216..8d2446c 100644 --- a/.env.example +++ b/.env.example @@ -83,21 +83,21 @@ ORCHESTRATOR_FLOW_SHADOW_MODE=noop ORCHESTRATOR_FLOW_SHADOW_CORE_PREVIEW_ENABLED=false ORCHESTRATOR_FLOW_SHADOW_PLUGIN_DRY_RUN_ENABLED=false ORCHESTRATOR_FLOW_SHADOW_EFFECT_DRY_RUN_ENABLED=false -MEMORY_LLM_EXTRACTION_ENABLED=true -MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS=30.0 +MEMORY_LLM_EXTRACTION_ENABLED=false +MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS=1.0 MEMORY_LLM_EXTRACTION_MAX_ACTIONS=4 MEMORY_LLM_EXTRACTION_MIN_CONFIDENCE=0.75 MEMORY_ACCEPTANCE_AUTO_ACCEPT_MIN=0.78 MEMORY_ACCEPTANCE_REJECT_BELOW=0.35 MEMORY_LLM_EXTRACTION_JOB_ENABLED=true -MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED=true +MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED=false MEMORY_LLM_EXTRACTION_JOB_SCOPE_ALLOWLIST= MEMORY_LLM_EXTRACTION_JOB_DRAIN_BATCH_SIZE=5 MEMORY_LLM_EXTRACTION_JOB_DRAIN_MAX_CLAIMS=0 MEMORY_LLM_EXTRACTION_JOB_MAX_ATTEMPTS=3 MEMORY_LLM_EXTRACTION_JOB_BACKOFF_SECONDS=30.0 -MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS=90.0 -MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS=150.0 +MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS=5.0 +MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS=60.0 MEMORY_LLM_EXTRACTION_JOB_DRAIN_INTERVAL_SECONDS=5.0 MEMORY_RETRIEVAL_ENABLED=true MEMORY_HYBRID_RETRIEVAL_ENABLED=false @@ -114,13 +114,13 @@ MEMORY_VECTOR_TIMEOUT_SECONDS=2.0 MEMORY_VECTOR_TOP_K=12 MEMORY_GRAPH_VECTOR_TOP_K=12 MEMORY_VECTOR_INDEX_STRICT_STARTUP_CHECK=false -MEMORY_GRAPH_RETRIEVAL_ENABLED=true +MEMORY_GRAPH_RETRIEVAL_ENABLED=false MEMORY_GRAPH_RETRIEVAL_FACT_TOP_K=3 MEMORY_GRAPH_RETRIEVAL_EPISODE_TOP_K=2 MEMORY_GRAPH_RETRIEVAL_BUDGET_CHARS=600 # Runtime app setting for non-Compose launches; Docker Compose uses COMPOSE_* flags below. -MEMORY_GRAPH_LLM_EXTRACTION_ENABLED=true -MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS=90.0 +MEMORY_GRAPH_LLM_EXTRACTION_ENABLED=false +MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS=1.0 MEMORY_GRAPH_LLM_EXTRACTION_MAX_ACTIONS=16 MEMORY_GRAPH_LLM_EXTRACTION_MAX_ENTITIES=8 MEMORY_GRAPH_LLM_EXTRACTION_MAX_FACTS=4 @@ -128,8 +128,8 @@ MEMORY_GRAPH_LLM_EXTRACTION_MAX_EPISODES=2 MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE=0.8 MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED=true MEMORY_GOVERNANCE_INTERVAL_SECONDS=86400 -MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED=true -MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED=true +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED=false +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED=false MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS=3600 MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LOOKBACK_DAYS=7 MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_SESSIONS_PER_TICK=10 @@ -137,7 +137,7 @@ MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_WINDOWS_PER_SESSION=20 MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE=50 MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS=180 MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES=scheduler -MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=true +MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=false MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES=200 MEMORY_NEEDS_REVIEW_RETENTION_DAYS=30 MEMORY_REJECTED_RETENTION_DAYS=7 @@ -363,21 +363,21 @@ COMPOSE_ORCHESTRATOR_FLOW_SHADOW_PLUGIN_DRY_RUN_ENABLED=false COMPOSE_ORCHESTRATOR_FLOW_SHADOW_EFFECT_DRY_RUN_ENABLED=false COMPOSE_MEMORY_RETRIEVAL_ENABLED=true COMPOSE_MEMORY_HYBRID_RETRIEVAL_ENABLED=false -COMPOSE_MEMORY_LLM_EXTRACTION_ENABLED=true -COMPOSE_MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS=30.0 +COMPOSE_MEMORY_LLM_EXTRACTION_ENABLED=false +COMPOSE_MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS=1.0 COMPOSE_MEMORY_LLM_EXTRACTION_MAX_ACTIONS=4 COMPOSE_MEMORY_LLM_EXTRACTION_MIN_CONFIDENCE=0.75 COMPOSE_MEMORY_ACCEPTANCE_AUTO_ACCEPT_MIN=0.78 COMPOSE_MEMORY_ACCEPTANCE_REJECT_BELOW=0.35 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_ENABLED=true -COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED=true +COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED=false COMPOSE_MEMORY_LLM_EXTRACTION_JOB_SCOPE_ALLOWLIST= COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_BATCH_SIZE=5 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_MAX_CLAIMS=0 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_MAX_ATTEMPTS=3 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_BACKOFF_SECONDS=30.0 -COMPOSE_MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS=90.0 -COMPOSE_MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS=150.0 +COMPOSE_MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS=5.0 +COMPOSE_MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS=60.0 COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_INTERVAL_SECONDS=5.0 COMPOSE_MEMORY_GROUP_IDENTITY_MEMORY_ENABLED=false COMPOSE_MEMORY_RETRIEVAL_TOP_K=6 @@ -390,12 +390,12 @@ COMPOSE_MEMORY_VECTOR_TIMEOUT_SECONDS=2.0 COMPOSE_MEMORY_VECTOR_TOP_K=12 COMPOSE_MEMORY_GRAPH_VECTOR_TOP_K=12 COMPOSE_MEMORY_VECTOR_INDEX_STRICT_STARTUP_CHECK=false -COMPOSE_MEMORY_GRAPH_RETRIEVAL_ENABLED=true +COMPOSE_MEMORY_GRAPH_RETRIEVAL_ENABLED=false COMPOSE_MEMORY_GRAPH_RETRIEVAL_FACT_TOP_K=3 COMPOSE_MEMORY_GRAPH_RETRIEVAL_EPISODE_TOP_K=2 COMPOSE_MEMORY_GRAPH_RETRIEVAL_BUDGET_CHARS=600 -COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_ENABLED=true -COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS=90.0 +COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_ENABLED=false +COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS=1.0 COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_ACTIONS=16 COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_ENTITIES=8 COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_FACTS=4 @@ -403,8 +403,8 @@ COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_EPISODES=2 COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE=0.8 COMPOSE_MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED=true COMPOSE_MEMORY_GOVERNANCE_INTERVAL_SECONDS=86400 -COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED=true -COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED=true +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED=false +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED=false COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS=3600 COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LOOKBACK_DAYS=7 COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_SESSIONS_PER_TICK=10 @@ -412,7 +412,7 @@ COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_WINDOWS_PER_SESSION=20 COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE=50 COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS=180 COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES=scheduler -COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=true +COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED=false COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES=200 COMPOSE_MEMORY_NEEDS_REVIEW_RETENTION_DAYS=30 COMPOSE_MEMORY_REJECTED_RETENTION_DAYS=7 diff --git a/app/common/config.py b/app/common/config.py index 270841b..a56d608 100644 --- a/app/common/config.py +++ b/app/common/config.py @@ -344,21 +344,21 @@ def guarded_dotenv_settings() -> dict[str, Any]: orchestrator_flow_shadow_core_preview_enabled: bool = False orchestrator_flow_shadow_plugin_dry_run_enabled: bool = False orchestrator_flow_shadow_effect_dry_run_enabled: bool = False - memory_llm_extraction_enabled: bool = True - memory_llm_extraction_timeout_seconds: float = Field(default=30.0, gt=0) + memory_llm_extraction_enabled: bool = False + memory_llm_extraction_timeout_seconds: float = Field(default=1.0, gt=0) memory_llm_extraction_max_actions: int = Field(default=4, ge=1) memory_llm_extraction_min_confidence: float = Field(default=0.75, ge=0.0, le=1.0) memory_acceptance_auto_accept_min: float = Field(default=0.78, ge=0.0, le=1.0) memory_acceptance_reject_below: float = Field(default=0.35, ge=0.0, le=1.0) memory_llm_extraction_job_enabled: bool = True - memory_llm_extraction_job_drain_enabled: bool = True + memory_llm_extraction_job_drain_enabled: bool = False memory_llm_extraction_job_scope_allowlist: str = "" memory_llm_extraction_job_drain_batch_size: int = Field(default=5, ge=1) memory_llm_extraction_job_drain_max_claims: int = Field(default=0, ge=0) memory_llm_extraction_job_max_attempts: int = Field(default=3, ge=1) memory_llm_extraction_job_backoff_seconds: float = Field(default=30.0, gt=0) - memory_llm_extraction_job_timeout_seconds: float = Field(default=90.0, gt=0) - memory_llm_extraction_job_lock_ttl_seconds: float = Field(default=150.0, gt=0) + memory_llm_extraction_job_timeout_seconds: float = Field(default=5.0, gt=0) + memory_llm_extraction_job_lock_ttl_seconds: float = Field(default=60.0, gt=0) memory_llm_extraction_job_drain_interval_seconds: float = Field(default=5.0, gt=0) memory_retrieval_enabled: bool = True # Identity-wide memory can contain facts learned in private conversations. @@ -376,12 +376,12 @@ def guarded_dotenv_settings() -> dict[str, Any]: memory_vector_top_k: int = Field(default=12, ge=1, le=100) memory_graph_vector_top_k: int = Field(default=12, ge=1, le=100) memory_vector_index_strict_startup_check: bool = False - memory_graph_retrieval_enabled: bool = True + memory_graph_retrieval_enabled: bool = False memory_graph_retrieval_fact_top_k: int = Field(default=3, ge=1, le=10) memory_graph_retrieval_episode_top_k: int = Field(default=2, ge=1, le=10) memory_graph_retrieval_budget_chars: int = Field(default=600, ge=100, le=3000) - memory_graph_llm_extraction_enabled: bool = True - memory_graph_llm_extraction_timeout_seconds: float = Field(default=90.0, gt=0) + memory_graph_llm_extraction_enabled: bool = False + memory_graph_llm_extraction_timeout_seconds: float = Field(default=1.0, gt=0) memory_graph_llm_extraction_max_actions: int = Field(default=16, ge=1) memory_graph_llm_extraction_max_entities: int = Field(default=8, ge=1) memory_graph_llm_extraction_max_facts: int = Field(default=4, ge=1) @@ -389,8 +389,8 @@ def guarded_dotenv_settings() -> dict[str, Any]: memory_graph_llm_extraction_min_confidence: float = Field(default=0.8, ge=0.0, le=1.0) memory_governance_auto_cleanup_enabled: bool = True memory_governance_interval_seconds: float = Field(default=86_400.0, gt=0) - memory_group_graph_auto_extract_enabled: bool = True - memory_group_graph_auto_extract_llm_enabled: bool = True + memory_group_graph_auto_extract_enabled: bool = False + memory_group_graph_auto_extract_llm_enabled: bool = False memory_group_graph_auto_extract_interval_seconds: float = Field(default=3_600.0, gt=0) memory_group_graph_auto_extract_lookback_days: int = Field(default=7, ge=1, le=14) memory_group_graph_auto_extract_max_sessions_per_tick: int = Field(default=10, ge=1, le=20) @@ -398,7 +398,7 @@ def guarded_dotenv_settings() -> dict[str, Any]: memory_group_graph_auto_extract_window_size: int = Field(default=50, ge=10, le=100) memory_group_graph_auto_extract_time_budget_seconds: int = Field(default=180, ge=5, le=180) memory_group_graph_auto_extract_roles: str = "scheduler" - memory_group_graph_auto_extract_sync_enabled: bool = True + memory_group_graph_auto_extract_sync_enabled: bool = False memory_group_graph_auto_extract_sync_max_messages: int = Field(default=200, ge=20, le=500) memory_needs_review_retention_days: int = Field(default=30, ge=1) memory_rejected_retention_days: int = Field(default=7, ge=1) diff --git a/docker-compose.yml b/docker-compose.yml index 178a5fd..f263c58 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -89,21 +89,21 @@ x-app-env: &app-env ORCHESTRATOR_FLOW_SHADOW_EFFECT_DRY_RUN_ENABLED: ${COMPOSE_ORCHESTRATOR_FLOW_SHADOW_EFFECT_DRY_RUN_ENABLED:-false} MEMORY_RETRIEVAL_ENABLED: ${COMPOSE_MEMORY_RETRIEVAL_ENABLED:-true} MEMORY_HYBRID_RETRIEVAL_ENABLED: ${COMPOSE_MEMORY_HYBRID_RETRIEVAL_ENABLED:-false} - MEMORY_LLM_EXTRACTION_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_ENABLED:-true} - MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS:-30.0} + MEMORY_LLM_EXTRACTION_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_ENABLED:-false} + MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_TIMEOUT_SECONDS:-1.0} MEMORY_LLM_EXTRACTION_MAX_ACTIONS: ${COMPOSE_MEMORY_LLM_EXTRACTION_MAX_ACTIONS:-4} MEMORY_LLM_EXTRACTION_MIN_CONFIDENCE: ${COMPOSE_MEMORY_LLM_EXTRACTION_MIN_CONFIDENCE:-0.75} MEMORY_ACCEPTANCE_AUTO_ACCEPT_MIN: ${COMPOSE_MEMORY_ACCEPTANCE_AUTO_ACCEPT_MIN:-0.78} MEMORY_ACCEPTANCE_REJECT_BELOW: ${COMPOSE_MEMORY_ACCEPTANCE_REJECT_BELOW:-0.35} MEMORY_LLM_EXTRACTION_JOB_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_ENABLED:-true} - MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED:-true} + MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_ENABLED:-false} MEMORY_LLM_EXTRACTION_JOB_SCOPE_ALLOWLIST: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_SCOPE_ALLOWLIST:-} MEMORY_LLM_EXTRACTION_JOB_DRAIN_BATCH_SIZE: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_BATCH_SIZE:-5} MEMORY_LLM_EXTRACTION_JOB_DRAIN_MAX_CLAIMS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_MAX_CLAIMS:-0} MEMORY_LLM_EXTRACTION_JOB_MAX_ATTEMPTS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_MAX_ATTEMPTS:-3} MEMORY_LLM_EXTRACTION_JOB_BACKOFF_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_BACKOFF_SECONDS:-30.0} - MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS:-90.0} - MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS:-150.0} + MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_TIMEOUT_SECONDS:-5.0} + MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_LOCK_TTL_SECONDS:-60.0} MEMORY_LLM_EXTRACTION_JOB_DRAIN_INTERVAL_SECONDS: ${COMPOSE_MEMORY_LLM_EXTRACTION_JOB_DRAIN_INTERVAL_SECONDS:-5.0} MEMORY_GROUP_IDENTITY_MEMORY_ENABLED: ${COMPOSE_MEMORY_GROUP_IDENTITY_MEMORY_ENABLED:-false} MEMORY_RETRIEVAL_TOP_K: ${COMPOSE_MEMORY_RETRIEVAL_TOP_K:-6} @@ -116,12 +116,12 @@ x-app-env: &app-env MEMORY_VECTOR_TOP_K: ${COMPOSE_MEMORY_VECTOR_TOP_K:-12} MEMORY_GRAPH_VECTOR_TOP_K: ${COMPOSE_MEMORY_GRAPH_VECTOR_TOP_K:-12} MEMORY_VECTOR_INDEX_STRICT_STARTUP_CHECK: ${COMPOSE_MEMORY_VECTOR_INDEX_STRICT_STARTUP_CHECK:-false} - MEMORY_GRAPH_RETRIEVAL_ENABLED: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_ENABLED:-true} + MEMORY_GRAPH_RETRIEVAL_ENABLED: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_ENABLED:-false} MEMORY_GRAPH_RETRIEVAL_FACT_TOP_K: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_FACT_TOP_K:-3} MEMORY_GRAPH_RETRIEVAL_EPISODE_TOP_K: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_EPISODE_TOP_K:-2} MEMORY_GRAPH_RETRIEVAL_BUDGET_CHARS: ${COMPOSE_MEMORY_GRAPH_RETRIEVAL_BUDGET_CHARS:-600} - MEMORY_GRAPH_LLM_EXTRACTION_ENABLED: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_ENABLED:-true} - MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS:-90.0} + MEMORY_GRAPH_LLM_EXTRACTION_ENABLED: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_ENABLED:-false} + MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_TIMEOUT_SECONDS:-1.0} MEMORY_GRAPH_LLM_EXTRACTION_MAX_ACTIONS: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_ACTIONS:-16} MEMORY_GRAPH_LLM_EXTRACTION_MAX_ENTITIES: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_ENTITIES:-8} MEMORY_GRAPH_LLM_EXTRACTION_MAX_FACTS: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MAX_FACTS:-4} @@ -129,8 +129,8 @@ x-app-env: &app-env MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE: ${COMPOSE_MEMORY_GRAPH_LLM_EXTRACTION_MIN_CONFIDENCE:-0.8} MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED: ${COMPOSE_MEMORY_GOVERNANCE_AUTO_CLEANUP_ENABLED:-true} MEMORY_GOVERNANCE_INTERVAL_SECONDS: ${COMPOSE_MEMORY_GOVERNANCE_INTERVAL_SECONDS:-86400} - MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED:-true} - MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED:-true} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ENABLED:-false} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LLM_ENABLED:-false} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_INTERVAL_SECONDS:-3600} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LOOKBACK_DAYS: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_LOOKBACK_DAYS:-7} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_SESSIONS_PER_TICK: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_MAX_SESSIONS_PER_TICK:-10} @@ -138,7 +138,7 @@ x-app-env: &app-env MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_WINDOW_SIZE:-50} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_TIME_BUDGET_SECONDS:-180} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_ROLES:-scheduler} - MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED:-true} + MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_ENABLED:-false} MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES: ${COMPOSE_MEMORY_GROUP_GRAPH_AUTO_EXTRACT_SYNC_MAX_MESSAGES:-200} MEMORY_NEEDS_REVIEW_RETENTION_DAYS: ${COMPOSE_MEMORY_NEEDS_REVIEW_RETENTION_DAYS:-30} MEMORY_REJECTED_RETENTION_DAYS: ${COMPOSE_MEMORY_REJECTED_RETENTION_DAYS:-7} diff --git a/tests/unit/test_config_precedence.py b/tests/unit/test_config_precedence.py index 4645957..21aa66b 100644 --- a/tests/unit/test_config_precedence.py +++ b/tests/unit/test_config_precedence.py @@ -172,19 +172,20 @@ def test_quota_environment_is_part_of_the_settings_contract(monkeypatch) -> None assert settings.tenant_default_daily_tokens == 4321 -def test_memory_llm_extraction_defaults_are_enabled() -> None: +def test_memory_llm_extraction_defaults_are_opt_in() -> None: settings = Settings(_env_file=None) - assert settings.memory_llm_extraction_enabled is True - assert settings.memory_llm_extraction_job_drain_enabled is True - assert settings.memory_graph_llm_extraction_enabled is True - assert settings.memory_group_graph_auto_extract_llm_enabled is True - assert settings.memory_graph_retrieval_enabled is True + assert settings.memory_llm_extraction_enabled is False + assert settings.memory_llm_extraction_job_drain_enabled is False + assert settings.memory_graph_llm_extraction_enabled is False + assert settings.memory_group_graph_auto_extract_enabled is False + assert settings.memory_group_graph_auto_extract_llm_enabled is False + assert settings.memory_graph_retrieval_enabled is False assert settings.memory_group_graph_auto_extract_lookback_days == 7 - assert settings.memory_group_graph_auto_extract_sync_enabled is True + assert settings.memory_group_graph_auto_extract_sync_enabled is False assert settings.memory_group_graph_auto_extract_sync_max_messages == 200 - assert settings.memory_llm_extraction_job_timeout_seconds == 90.0 - assert settings.memory_llm_extraction_job_lock_ttl_seconds == 150.0 + assert settings.memory_llm_extraction_job_timeout_seconds == 5.0 + assert settings.memory_llm_extraction_job_lock_ttl_seconds == 60.0 def test_group_graph_auto_extract_environment_is_part_of_settings_contract(monkeypatch) -> None: