JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(proactive recommendation): refresh colour, restrict recommendation in one session.
Haowei_Du6c94f3e9f2ce
diff --git a/jiuwenswarm/agents/harness/common/recommendation/__init__.py b/jiuwenswarm/agents/harness/common/recommendation/__init__.pyindex 1bd49238a4..ecec0f3562 100644--- a/jiuwenswarm/agents/harness/common/recommendation/__init__.py+++ b/jiuwenswarm/agents/harness/common/recommendation/__init__.py@@ -1,27 +1,30 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Proactive recommendation system — background engine for profile extraction,-pain-point reasoning, task reminder, need exploration, and skill matching.+"""Proactive recommendation system — background engine for task reminder,+need exploration, and skill matching based on current conversation.Modules:-- profile_extractor.py — UserProfile data model + persistence+- profile_extractor.py — RecommendationState (cooldown + history) persistence- proactive_engine.py — Background tick loop (ProactiveEngine)-- proactive_actions.py — LLM prompts, decision types, skill discovery, push-- situation_report.py — Multi-session context aggregation for LLM+- proactive_actions.py — Decision types, skill discovery, rate limiting, trigger+- proactive_prompts.py — LLM prompt templates+- proactive_adapter.py — Agent build + trigger + init+- situation_report.py — Current conversation + calendar + skills aggregation+- calendar_source.py — MCP calendar events"""from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (- UserProfile,- load_user_profile,- save_user_profile,+ RecommendationState,+ load_recommendation_state,+ save_recommendation_state,)from jiuwenswarm.agents.harness.common.recommendation.proactive_engine import (ProactiveEngine,)__all__ = [- "UserProfile",- "load_user_profile",- "save_user_profile",+ "RecommendationState",+ "load_recommendation_state",+ "save_recommendation_state","ProactiveEngine",]diff --git a/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.py b/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.pyindex 9c645e9c04..bda86b626b 100644--- a/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.py+++ b/jiuwenswarm/agents/harness/common/recommendation/proactive_actions.py@@ -258,7 +258,6 @@ from jiuwenswarm.agents.harness.common.recommendation.proactive_prompts import (@dataclassclass AnalysisResult:"""Output from the unified LLM analysis call."""- profile_delta: dict[str, Any] = field(default_factory=dict)decision: RecommendationDecision | None = None@@ -284,7 +283,7 @@ async def _analyze_and_decide(duplicate them in the LLM context."""prompt = UNIFIED_ANALYSIS_PROMPT.format(- conversation_summary=report_text[:60000],+ conversation_summary=report_text,)# conversation_id 每次 tick 用唯一值——若用固定 id,DeepAgent 的 context@@ -310,14 +309,8 @@ async def _analyze_and_decide(if not isinstance(delta, dict):return AnalysisResult()- # Extract profile delta (only fields the LLM is allowed to change)- profile_delta: dict[str, Any] = {}- profile_keys = ("preferences", "goals", "interests", "commitments")- for key in profile_keys:- if key in delta and isinstance(delta[key], list):- profile_delta[key] = delta[key]-- # Extract decision+ # Extract decision (画像已废弃——所有推荐基于当前对话)+ decision = Nonedecision = Noneraw_decision = delta.get("decision")if isinstance(raw_decision, dict) and raw_decision.get("type") and raw_decision.get("target"):@@ -350,13 +343,11 @@ async def _analyze_and_decide()logger.info(- "[ProactiveEngine] analysis: delta_keys=%s, decision=%s",- list(profile_delta.keys()),+ "[ProactiveEngine] analysis: decision=%s",f"{decision.type}:{decision.target}" if decision else "null",)return AnalysisResult(- profile_delta=profile_delta,decision=decision,)except Exception as exc:diff --git a/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py b/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.pyindex c0f42ccd3c..ad0b42b8da 100644--- a/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py+++ b/jiuwenswarm/agents/harness/common/recommendation/proactive_engine.py@@ -47,7 +47,7 @@ class ProactiveEngine:def __init__(self, config: dict[str, Any] | None = None) -> None:config = config or {}self._max_per_day: int = int(config.get("max_recommend_per_day", 5))- self._max_sessions: int = int(config.get("max_sessions_per_tick", 10))+ self._max_rounds: int = int(config.get("max_rounds_per_tick", 20))# 默认 False,与 config.yaml 的 proactive_recommendation.enabled 默认值一致,# 防御性默认=关闭,避免配置段缺失时引擎被误启用。self._enabled: bool = config.get("enabled", False)@@ -56,9 +56,12 @@ class ProactiveEngine:# 替代 proactive_actions._analyze_and_decide 里的裸 model.invoke。self._proactive_agent: Any = None# 触发主 agent 跑一轮生成话术的回调。- # 话术交给主 agent 生成 → 自然进其 context engine(save_contexts 持久化)- # → stream 输出推前端。撤掉旧的 push/inject 回调。self._trigger_main_agent_callback: Any = None+ # 检查目标 channel 是否有活跃 agent(避免 agent 被 evict 后白调 LLM)。+ self._check_agent_available_callback: Any = None+ # 推送通知回调——直接推一条文本到前端,不经过主 agent(不进 context)。+ # 用于"今日推荐已达上限"等系统提醒。+ self._send_notification_callback: Any = Nonedef set_proactive_agent(self, agent: Any) -> None:"""Set the proactive lightweight agent used for recommendation decision.@@ -96,26 +99,28 @@ class ProactiveEngine:logger.warning("[ProactiveEngine] proactive agent rebuild failed: %s", exc)def set_trigger_main_agent_callback(self, callback: Any) -> None:- """Set the callback that triggers the main agent to run one round.+ """Set the callback that triggers the main agent to run one round."""+ self._trigger_main_agent_callback = callback- Args:- callback: Async function ``(session_id, channel_id, query, decision) -> bool``.- Constructs an AgentRequest with the directive-style query and- drives ``adapter.process_message_stream`` so the main agent- generates the recommendation message naturally (entering its- own context engine + streaming to the frontend). Returns False- when the session is busy (避让) or delivery fails.+ def set_check_agent_available_callback(self, callback: Any) -> None:+ """Set the callback that checks if the target channel has an active agent."""+ self._check_agent_available_callback = callback++ def set_send_notification_callback(self, callback: Any) -> None:+ """Set the callback for pushing a simple text notification (no LLM, no context).++ 用于"今日推荐已达上限"等系统提醒——直接推文本到前端,不触发主 agent。"""- self._trigger_main_agent_callback = callback+ self._send_notification_callback = callbackdef reload_config(self, config: dict[str, Any]) -> None:"""Hot-reload configuration without restarting the process."""new_enabled = bool(config.get("enabled", False))new_max_per_day = int(config.get("max_recommend_per_day", self._max_per_day))- new_max_sessions = int(config.get("max_sessions_per_tick", self._max_sessions))+ new_max_rounds = int(config.get("max_rounds_per_tick", self._max_rounds))self._max_per_day = new_max_per_day- self._max_sessions = new_max_sessions+ self._max_rounds = new_max_roundsself._enabled = new_enabledlogger.info("[ProactiveEngine] config reloaded (enabled=%s, max_per_day=%d)",new_enabled, new_max_per_day)@@ -168,32 +173,50 @@ class ProactiveEngine:_trigger_main_agent,)from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (- load_user_profile,- save_user_profile,+ load_recommendation_state,+ save_recommendation_state,)from jiuwenswarm.agents.harness.common.recommendation.situation_report import (build_situation_report,)# 每次 tick 顺手清理过期数据(daily_counts 老日期 key、cooldown_records 过期项)。- # 这些数据只增不减,不清理会长期累积(user_profile.json 越来越大)。try:self.run_maintenance()except Exception as exc:logger.debug("[ProactiveEngine] maintenance failed: %s", exc)- # Gate: daily budget (skip for manual triggers)+ # Step 0: 检查目标 channel 是否有活跃 agent——agent 被 evict 后白调 LLM 是浪费 token。+ if self._check_agent_available_callback is not None:+ try:+ if not self._check_agent_available_callback(target_channel):+ logger.debug("[ProactiveEngine] no active agent for channel=%s, skipping tick", target_channel)+ self._last_tick_at = time.time()+ return False+ except Exception as exc:+ logger.debug("[ProactiveEngine] check_agent_available failed: %s", exc)++ # Gate: daily budgetif _today_recommend_count() >= self._max_per_day:- logger.debug("[ProactiveEngine] daily limit reached, skipping tick")+ logger.info("[ProactiveEngine] daily limit reached (%d/%d), skipping tick",+ _today_recommend_count(), self._max_per_day)+ # 推送通知提醒用户已到上限(每天最多推一次上限提醒,用 last_tick_at 兜底避免刷屏)+ if self._send_notification_callback is not None:+ try:+ await self._send_notification_callback(+ target_channel,+ f"今日主动推荐已达每日上限({self._max_per_day} 条),"+ f"明日恢复。",+ )+ except Exception as exc:+ logger.debug("[ProactiveEngine] send_notification failed: %s", exc)self._last_tick_at = time.time()return False# ── Step 1: Build situation report ─────────────────────- # build_situation_report 默认只扫 agent 类会话(mode_prefix="agent"),- # 避免 code/team 会话的技术语境污染推荐决策。_, available_skills = _get_all_skills()report = await build_situation_report(- max_sessions=self._max_sessions,+ max_rounds=self._max_rounds,skills=available_skills,)@@ -205,36 +228,30 @@ class ProactiveEngine:report_text = report.render_for_llm()# ── Step 2: LLM analysis + decision ────────────────────- # 决策由专用 agent 生成(替代裸 model.invoke),无 session、单轮、输出 JSON。- profile = load_user_profile()+ state = load_recommendation_state()if self._proactive_agent is None:logger.debug("[ProactiveEngine] no proactive agent available, skipping tick")self._last_tick_at = time.time()return Falseresult = await _analyze_and_decide(- report_text, profile, available_skills, self._proactive_agent,+ report_text, state, available_skills, self._proactive_agent,)- # ── Step 3: Update profile ─────────────────────────────- if result.profile_delta:- profile.merge(result.profile_delta)- save_user_profile(profile)-- # ── Step 4: Check if we have a recommendation ───────────+ # ── Step 3: Check if we have a recommendation ───────────decision = result.decisionif not decision:logger.debug("[ProactiveEngine] no recommendation this tick")self._last_tick_at = time.time()return False- # ── Step 5: Cooldown check ─────────────────────────────- if not _is_cooled_down(decision.target, profile):+ # ── Step 4: Cooldown check ─────────────────────────────+ if not _is_cooled_down(decision.target, state):logger.debug("[ProactiveEngine] '%s' still in cooldown, skipping", decision.target)self._last_tick_at = time.time()return False- # ── Step 6: Pick delivery target ───────────────────────+ # ── Step 5: Pick delivery target ───────────────────────if target_channel:target_session = report.find_session_for_channel(target_channel)if not target_session:@@ -248,10 +265,7 @@ class ProactiveEngine:self._last_tick_at = time.time()return False- # ── Step 7: Trigger main agent to generate & deliver ────- # 把决策包成指令式 query 触发主 agent 跑一轮,主 agent 自己生成话术- # → 进其 context engine(save_contexts 持久化)→ stream 输出推前端。- # 避让:目标 session 正忙则跳过本次 tick。+ # ── Step 6: Trigger main agent to generate & deliver ────if self._trigger_main_agent_callback is None:logger.warning("[ProactiveEngine] no trigger_main_agent_callback, skipping")self._last_tick_at = time.time()@@ -268,10 +282,10 @@ class ProactiveEngine:self._last_tick_at = time.time()return False- # ── Step 8: Update state ────────────────────────────────+ # ── Step 7: Update state ────────────────────────────────_increment_daily_count()- _mark_recommended(decision.target, profile)- profile.add_recommendation({+ _mark_recommended(decision.target, state)+ state.add_recommendation({"type": decision.type,"target": decision.target,"reason": decision.reason,@@ -279,8 +293,9 @@ class ProactiveEngine:"tick_at": time.time(),"session_id": target_session.session_id,})+ state.touch()- save_user_profile(profile)+ save_recommendation_state(state)self._last_tick_at = time.time()logger.info("[ProactiveEngine] delivered '%s' (type=%s, urgency=%.2f, session=%s)",@@ -302,12 +317,12 @@ class ProactiveEngine:_prune_cooldown_records,)from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (- load_user_profile,- save_user_profile,+ load_recommendation_state,+ save_recommendation_state,)_prune_daily_counts()- profile = load_user_profile()- _prune_cooldown_records(profile)- save_user_profile(profile)+ state = load_recommendation_state()+ _prune_cooldown_records(state)+ save_recommendation_state(state)logger.debug("[ProactiveEngine] maintenance completed")diff --git a/jiuwenswarm/agents/harness/common/recommendation/proactive_prompts.py b/jiuwenswarm/agents/harness/common/recommendation/proactive_prompts.pyindex 64820c0a43..f8e545553e 100644--- a/jiuwenswarm/agents/harness/common/recommendation/proactive_prompts.py+++ b/jiuwenswarm/agents/harness/common/recommendation/proactive_prompts.py@@ -7,75 +7,42 @@from __future__ import annotations-# ── 决策 prompt:画像更新 + 推荐决策 ──────────────────────────────+# ── 决策 prompt:基于当前对话做推荐决策 ───────────────────────────UNIFIED_ANALYSIS_PROMPT = """\-你是用户洞察与推荐助手。以下是用户的综合情境信息(含画像、对话摘要、历史推荐、待办、日程与候选 skill)。+你是用户洞察与推荐助手。以下是用户的综合情境信息(含当前对话、历史推荐、日程与候选 skill)。{conversation_summary}-请完成以下任务,输出 JSON:+请基于以上信息,决定是否需要主动与用户发起推荐。输出 JSON。-1. 更新用户画像(增量更新,只输出需要变更的字段,未变更的字段可以省略或保持原样):+⚠️ 重要:只从「当前对话」的 `[User]:` 消息中理解用户意图。+- `[Assistant]:` 是系统回复(含推荐话术、skill 介绍),不是用户意图+- 「候选 Skill」是系统安装的工具清单,不是用户兴趣+- 「历史推荐记录」是系统推过的内容,不是用户意图,尽量避免重复推荐- ⚠️⚠️⚠️ 画像提取铁律(违反会严重污染用户画像,务必严格遵守):+推荐类型(优先级从高到低):- 【来源限制】画像**只能从对话摘要中 `[User]:` 开头的消息**提取,且必须是用户**字面明确陈述**的事实。- - `[Assistant]:` 是系统/助手的回复(含主动推荐话术、skill 介绍、建议),**绝对不是用户意图**- - 「候选 Skill」列表是系统安装的工具清单,**绝对不是用户兴趣**——禁止把 skill 名(如 gaode-taxi、taobao-shopping-assistant)当用户 interests- - 「历史推荐记录」是系统推送过的推荐,**不是用户意图**- - 日程事件只用于决策提醒,不算用户表达的 goals+a. "task_reminder":用户在当前对话中明确表达未完成的事。+ 另:若「即将到来的日程」中有近期事件(如会议、约会),可提醒,target 为事件标题。- 【禁止推理】禁止从用户行为/问题**推理/引申/联想**出画像:- - 用户问天气 ≠ 用户要去旅游,禁止推断"旅游规划/行程/行李/打车/购物"为 goals/interests- - 用户问代码 ≠ 用户要学 CI/CD,禁止推断- - 只记录用户**字面说的**事实(如"我是Python开发者"→preferences;"明天要交房租"→commitments)- - 用户没明确说的,一律不提取,宁可画像为空也不要推理填空+b. "skill_recommend":基于当前对话 + 日程,判断有已安装的候选 Skill 能帮用户应对场景。+ - 综合分析当前对话内容 + 日程事件 + 候选 Skill 列表+ - reason 必须引用当前对话的 [User]: 或日程事件- 【commitments 严格要求】必须是用户原话表达的"我要去做X"意图,禁止把 assistant 的建议/提议(如"要不要试试")当用户承诺。+c. "need_exploration":基于当前对话中用户明确表达的兴趣,推理潜在方向。+ target 是探索方向(非 skill 名),禁止凭空联想。- 【撤销意图】用户明确表示"不想X了""不要X了""取消了"时,必须从 goals/commitments/interests- 中删掉对应条目(在本次输出中不输出该条目即可)。用户改变主意后不应继续推已撤销的意图。-- 【清理既有误提取】现有画像可能含历史误提取条目(从 assistant/skill/推荐推理的),- 发现无 `[User]:` 字面依据的,应在本次输出中删掉(不输出该条目即可)。-- 字段说明:- - preferences: 长期偏好(技术栈、工作习惯、沟通风格),只保留反复出现的模式或用户明确表达的偏好- - goals: 用户明确说的当前短期任务,已完成或过期的删掉- - interests: 用户主动提及想了解的方向(非推理)- - commitments: 用户明确说"我要去做X"但还没做的--2. 推荐决策:根据画像、对话、日程和历史推荐记录,决定是否需要主动与用户对话。-- 优先级(从高到低):- a. 用户明确表达未完成的事 → "task_reminder"- 另:若「即将到来的日程」中有近期事件(如会议、约会),可用 "task_reminder" 提醒,target 为事件标题。- b. 场景化 skill 推荐:结合用户对话、画像和「即将到来的日程」,判断是否有- 已安装的候选 Skill 能帮用户应对当前或即将到来的场景。- - 综合分析日程事件(标题/地点/时间)+ 候选 Skill 列表,判断哪个 skill 与场景相关- - reason 必须说明场景依据(引用日程事件或 [User]: 对话内容)- → "skill_recommend"- c. 从用户明确表达的兴趣推理潜在方向 → "need_exploration"- (target 是探索方向,非 skill 名;必须有用户明确表达的兴趣为依据,禁止凭空联想)-- ⚠️ 约束:- - decision.type 为 "skill_recommend" 时,decision.target 必须是上方「候选 Skill」列表里实际存在的 skill 名称。- - 若没有完全匹配的已存在 skill,改用 "need_exploration" 或返回 null,不要编造不存在的 skill。- - 「候选 Skill」列表仅供 skill_recommend 选 target 用,不作为用户兴趣来源。- - 「历史推荐记录」仅用于避免重复推荐同类内容,不作为用户意图来源。- - 如当前无合适推荐,decision 返回 null。+⚠️ 约束:+- decision.type 为 "skill_recommend" 时,target 必须是「候选 Skill」列表里实际存在的 skill 名称。+- 如当前无合适推荐,decision 返回 null。输出 JSON 格式:{{- "preferences": ["..."],- "goals": ["..."],- "interests": ["..."],- "commitments": ["..."],"decision": {{"type": "skill_recommend|task_reminder|need_exploration","target": "skill名称/待办事项/探索方向",- "reason": "推荐原因(引用 [User]: 对话内容或日程事件,禁止引用 [Assistant]: 或候选 skill)",+ "reason": "推荐原因(引用 [User]: 对话内容或日程事件)","urgency": 0.0-1.0}} | null}}"""diff --git a/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.py b/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.pyindex f5831b1080..ddfc8e6d64 100644--- a/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.py+++ b/jiuwenswarm/agents/harness/common/recommendation/profile_extractor.py@@ -1,12 +1,10 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""User profile data model and persistence for the proactive recommendation engine.+"""Recommendation state persistence for the proactive recommendation engine.-The profile captures what the LLM has learned about the user from their-conversations across all channels. It is updated incrementally by the-proactive engine on each tick.+只存引擎运行态——冷却记录 + 推荐历史。用户画像已废弃(所有推荐基于当前对话)。-Storage: ``~/.jiuwenswarm/agent/workspace/user_profile.json``+Storage: ``~/.jiuwenswarm/agent/workspace/recommendation.json``"""from __future__ import annotations@@ -21,123 +19,77 @@ from typing import Anylogger = logging.getLogger(__name__)-# ── UserProfile ──────────────────────────────────────────────────+# ── RecommendationState ──────────────────────────────────────────@dataclass-class UserProfile:- """Persistent user profile maintained by the proactive engine.+class RecommendationState:+ """Persistent state for the proactive recommendation engine.- Fields are grouped by who manages them:-- * **LLM-managed** (updated via ``merge()`` from LLM output):- ``preferences``, ``goals``, ``interests``, ``commitments``-- * **Engine-managed** (updated by the engine itself, never by LLM):- ``recommendation_history``+ Only engine-managed runtime state — no user profile fields.+ User profile (preferences/goals/interests/commitments) is deprecated;+ all recommendations are now based on the current conversation."""- # ── LLM-managed fields ──────────────────────────────────────-- preferences: list[str] = field(default_factory=list)- """Long-term preferences: tech stack, work habits, communication style."""-- goals: list[str] = field(default_factory=list)- """Short-term goals: tasks the user is actively working on (days-scale)."""-- interests: list[str] = field(default_factory=list)- """Interest boundaries: areas the user might want to explore but hasn't yet."""-- commitments: list[str] = field(default_factory=list)- """Pending tasks: things the user said they'd do but haven't done yet."""-- # ── Engine-managed fields ───────────────────────────────────-recommendation_history: list[dict[str, Any]] = field(default_factory=list)"""Past recommendations with type, target, reason, timestamp (max 20)."""cooldown_records: dict[str, float] = field(default_factory=dict)- """Cooldown records: target -> last recommended timestamp. Persisted to survive restarts."""+ """Cooldown records: target -> last recommended timestamp."""last_updated: str = ""- # ── Merge ───────────────────────────────────────────────────-- def merge(self, delta: dict[str, Any]) -> None:- """Apply an incremental update from the LLM.-- The LLM outputs the *complete* list for each field it wants to change.- Fields absent from ``delta`` are left untouched. Engine-managed fields- (``recommendation_history``) are never modified here.- """- replace_fields = ("preferences", "goals", "interests", "commitments")- for key in replace_fields:- new_val = delta.get(key)- if isinstance(new_val, list):- setattr(self, key, [v for v in new_val if v])-- self.last_updated = datetime.now(timezone.utc).isoformat()-def add_recommendation(self, rec: dict[str, Any]) -> None:"""Append a recommendation record and cap at 20 entries."""self.recommendation_history.append(rec)if len(self.recommendation_history) > 20:self.recommendation_history = self.recommendation_history[-20:]+ def touch(self) -> None:+ """Update last_updated timestamp."""+ self.last_updated = datetime.now(timezone.utc).isoformat()+# ── File helpers ──────────────────────────────────────────────────-def _default_profile_path() -> Path:+def _default_state_path() -> Path:from jiuwenswarm.common.utils import get_agent_workspace_dir- return get_agent_workspace_dir() / "user_profile.json"+ return get_agent_workspace_dir() / "recommendation.json"-def load_user_profile(path: Path | None = None) -> UserProfile:- """Load profile from disk, returning an empty profile on missing/corrupt file."""- profile_path = path or _default_profile_path()- if not profile_path.exists() or profile_path.stat().st_size == 0:- # Missing or empty file = fresh state, not an error.- return UserProfile()+def load_recommendation_state(path: Path | None = None) -> RecommendationState:+ """Load state from disk, returning empty state on missing/corrupt file."""+ state_path = path or _default_state_path()+ if not state_path.exists() or state_path.stat().st_size == 0:+ return RecommendationState()try:- data = json.loads(profile_path.read_text(encoding="utf-8"))+ data = json.loads(state_path.read_text(encoding="utf-8"))if not isinstance(data, dict):- return UserProfile()-- return UserProfile(- preferences=_safe_list(data, "preferences"),- goals=_safe_list(data, "goals"),- interests=_safe_list(data, "interests"),- commitments=_safe_list(data, "commitments"),- recommendation_history=_safe_list(data, "recommendation_history"),- cooldown_records=_safe_dict(data, "cooldown_records"),+ return RecommendationState()++ return RecommendationState(+ recommendation_history=(+ data.get("recommendation_history", [])+ if isinstance(data.get("recommendation_history"), list)+ else []+ ),+ cooldown_records=data.get("cooldown_records", {}) if isinstance(data.get("cooldown_records"), dict) else {},last_updated=data.get("last_updated", ""),)except Exception as exc:- logger.warning("[UserProfile] load failed: %s", exc)- return UserProfile()---def _safe_list(data: dict, key: str) -> list:- """Extract a list from JSON data, returning [] on missing/wrong type."""- val = data.get(key, [])- return val if isinstance(val, list) else []---def _safe_dict(data: dict, key: str) -> dict:- """Extract a dict from JSON data, returning {} on missing/wrong type."""- val = data.get(key, {})- return val if isinstance(val, dict) else {}+ logger.warning("[RecommendationState] load failed: %s", exc)+ return RecommendationState()-def save_user_profile(profile: UserProfile, path: Path | None = None) -> None:- """Persist profile to disk."""- profile_path = path or _default_profile_path()- profile_path.parent.mkdir(parents=True, exist_ok=True)+def save_recommendation_state(state: RecommendationState, path: Path | None = None) -> None:+ """Persist state to disk."""+ state_path = path or _default_state_path()+ state_path.parent.mkdir(parents=True, exist_ok=True)try:- profile_path.write_text(- json.dumps(asdict(profile), ensure_ascii=False, indent=2),+ state_path.write_text(+ json.dumps(asdict(state), ensure_ascii=False, indent=2),encoding="utf-8",)except Exception as exc:- logger.warning("[UserProfile] save failed: %s", exc)+ logger.warning("[RecommendationState] save failed: %s", exc)diff --git a/jiuwenswarm/agents/harness/common/recommendation/situation_report.py b/jiuwenswarm/agents/harness/common/recommendation/situation_report.pyindex a6d5ac37bf..9793fcb502 100644--- a/jiuwenswarm/agents/harness/common/recommendation/situation_report.py+++ b/jiuwenswarm/agents/harness/common/recommendation/situation_report.py@@ -38,9 +38,7 @@ class SituationReport:"""Aggregated context for the proactive engine's LLM tick."""sessions: list[SessionSummary] = field(default_factory=list)- profile_summary: str = ""recommendation_history_summary: str = ""- pending_commitments: list[str] = field(default_factory=list)skills_summary: str = ""calendar_events: list[dict[str, Any]] = field(default_factory=list)@@ -78,34 +76,21 @@ class SituationReport:"""Render the full report as LLM-readable markdown."""parts: list[str] = []- parts.append("## 用户画像")- parts.append(self.profile_summary or "(尚无画像)")- parts.append("")-- if self.sessions:- parts.append("## 最近对话摘要")- for s in self.sessions:- if not s.compressed_history:- continue- channel_label = s.channel_id or "default"- parts.append(f"### 会话: {s.title or s.session_id[:16]} (channel: {channel_label})")- # Cap each session's contribution to avoid overwhelming the LLM.- # 截最后 8000 字符——最新消息(含用户撤销意图等关键信息)比早期- # 上下文更重要,从头截会丢失末尾的最新 user 消息。- # 8000 字符约 2-3 轮完整对话,够 LLM 理解最新意图。- hist = s.compressed_history- parts.append(hist[-8000:] if len(hist) > 8000 else hist)- parts.append("")+ # sessions 按最近活跃排序(_scan_sessions 已排),第一个是当前对话+ active_sessions = [s for s in self.sessions if s.compressed_history]+ if active_sessions:+ # 当前对话(最近活跃 1 个)——所有推荐都基于此+ # 不额外截断——靠 max_rounds=20 + 每轮 user[:1000]/assistant[:3000] 控制长度+ current = active_sessions[0]+ channel_label = current.channel_id or "default"+ parts.append("## 当前对话(所有推荐基于此)")+ parts.append(f"### 会话: {current.title or current.session_id[:16]} (channel: {channel_label})")+ parts.append(current.compressed_history)+ parts.append("")parts.append("## 历史推荐记录(系统生成,非用户表达,禁止提取进画像)")parts.append(self.recommendation_history_summary or "(无推荐历史)")- if self.pending_commitments:- parts.append("")- parts.append("## 用户待办/承诺")- for c in self.pending_commitments:- parts.append(f"- {c}")-if self.calendar_events:parts.append("")parts.append("## 即将到来的日程")@@ -151,6 +136,7 @@ def _match_session_mode(meta: dict[str, Any], mode_prefix: str | None) -> bool:def _scan_sessions(max_sessions: int = 10,+ max_rounds: int = 20,mode_prefix: str | None = "agent",) -> list[SessionSummary]:"""Scan the sessions directory and build summaries for recent active sessions.@@ -207,7 +193,7 @@ def _scan_sessions(if last_ts <= 0:continue- compressed = _compress_history_for_profile(session_id, max_rounds=10)+ compressed = _compress_history_for_profile(session_id, max_rounds=max_rounds)if not compressed:continue@@ -242,7 +228,7 @@ def _scan_sessions(def _compress_history_for_profile(session_id: str,- max_rounds: int = 10,+ max_rounds: int = 20,) -> str:"""Read a session's history and compress into [User]/[Assistant] rounds.@@ -303,86 +289,6 @@ def _compress_history_for_profile(return "\n\n".join(parts)-# ── Commitment extraction (heuristic) ───────────────────────────---_COMMITMENT_CUES: list[str] = [- "我要去做", "我要去", "帮我记住", "帮我记",- "提醒我", "别忘了", "待办", "我打算",- "我计划", "明天要", "下周要", "我需要完成",- "我需要做", "我还没做完", "还没完成",- "i need to", "i will", "i plan to",- "remind me", "don't forget", "i should",- "i have to", "i'm going to",-]--_COMMITMENT_SPLIT_RE = re.compile(r"[.!?;。\n]")---def _extract_commitments_from_text(text: str) -> list[str]:- """Extract sentences that contain commitment cues from a text block."""- if not text:- return []- sentences = _COMMITMENT_SPLIT_RE.split(text)- commitments: list[str] = []- for s in sentences:- s = s.strip()- if len(s) < 8:- continue- lower = s.lower()- for cue in _COMMITMENT_CUES:- if cue in lower:- commitments.append(s)- break- return commitments---def _extract_commitments(sessions: list[SessionSummary]) -> list[str]:- """Extract pending commitments from recent session histories."""- all_commitments: list[str] = []- for s in sessions:- if s.compressed_history:- all_commitments.extend(_extract_commitments_from_text(s.compressed_history))- # Deduplicate (case-insensitive)- seen: set[str] = set()- unique: list[str] = []- for c in all_commitments:- key = c.lower().strip()- if key not in seen:- seen.add(key)- unique.append(c)- return unique[:10]---# ── Profile formatting ──────────────────────────────────────────---def _format_existing_profile(profile: Any) -> str:- """Render UserProfile fields as readable text for LLM context."""- if not any([- getattr(profile, "preferences", []),- getattr(profile, "goals", []),- getattr(profile, "interests", []),- getattr(profile, "commitments", []),- ]):- return "(尚无画像)"-- parts: list[str] = []- prefs = getattr(profile, "preferences", [])- if prefs:- parts.append("偏好: " + ", ".join(prefs))- goals = getattr(profile, "goals", [])- if goals:- parts.append("短期目标: " + ", ".join(goals))- interests = getattr(profile, "interests", [])- if interests:- parts.append("兴趣边界: " + ", ".join(interests))- commitments = getattr(profile, "commitments", [])- if commitments:- parts.append("待办: " + ", ".join(commitments))- return "\n".join(parts)--# ── Skills formatting ───────────────────────────────────────────@@ -425,7 +331,7 @@ def _format_recommendation_history(history: list[dict[str, Any]]) -> str:async def build_situation_report(- max_sessions: int = 10,+ max_rounds: int = 20,skills: list[dict[str, Any]] | None = None,mode_prefix: str | None = "agent",) -> SituationReport:@@ -441,39 +347,29 @@ async def build_situation_report(推荐决策。传 ``None`` 扫全部会话。"""from jiuwenswarm.agents.harness.common.recommendation.profile_extractor import (- load_user_profile,+ load_recommendation_state,)from jiuwenswarm.agents.harness.common.recommendation.calendar_source import (fetch_calendar_events,)# 1. Scan sessions- sessions = _scan_sessions(max_sessions=max_sessions, mode_prefix=mode_prefix)+ sessions = _scan_sessions(max_sessions=10, max_rounds=max_rounds, mode_prefix=mode_prefix)- # 2. Load profile- profile = load_user_profile()- profile_summary = _format_existing_profile(profile)-- # 3. Recommendation history- rec_history = getattr(profile, "recommendation_history", [])+ # 2. Recommendation history (from state, not profile)+ state = load_recommendation_state()+ rec_history = state.recommendation_historyrec_summary = _format_recommendation_history(rec_history)- # 4. Commitments(每 tick 从最近会话重新提取;跨 tick 保留由 LLM 画像的- # commitments 字段承担——profile 持久化,引擎不另存一套)。- commitments = _extract_commitments(sessions)- commitments = commitments[:10]-- # 5. Skills+ # 3. Skillsskills_summary = _format_skills_for_llm(skills) if skills else ""- # 6. Calendar events (MCP calendar server; [] if unconfigured/unreachable)+ # 4. Calendar events (MCP calendar server; [] if unconfigured/unreachable)calendar_events = await fetch_calendar_events()return SituationReport(sessions=sessions,- profile_summary=profile_summary,recommendation_history_summary=rec_summary,- pending_commitments=commitments,skills_summary=skills_summary,calendar_events=calendar_events,)diff --git a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsxindex 50a642d485..42bca2f7bc 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx@@ -332,7 +332,7 @@ const PROACTIVE_BOOLEAN_KEYS = new Set(["proactive_recommendation_enabled"]);const PROACTIVE_KEYS = new Set([...PROACTIVE_BOOLEAN_KEYS,"proactive_recommendation_max_recommend_per_day",- "proactive_recommendation_max_sessions_per_tick",+ "proactive_recommendation_max_rounds_per_tick",]);// 调度频率已交给定时任务面板,ConfigPanel 不再暴露 tick_interval。// 即便后端残留下发,也在比较/提交时跳过,避免误提交空值。@@ -648,7 +648,7 @@ const KEY_DISPLAY_I18N: Record<string, string> = {skill_retrieval_retrieve_max_exposure_depth: "config.keys.skillRetrievalMaxExposureDepth",proactive_recommendation_enabled: "config.keys.proactiveEnabled",proactive_recommendation_max_recommend_per_day: "config.keys.proactiveMaxPerDay",- proactive_recommendation_max_sessions_per_tick: "config.keys.proactiveMaxSessions",+ proactive_recommendation_max_rounds_per_tick: "config.keys.proactiveMaxRounds",};const KEY_PLACEHOLDER_I18N: Record<string, string> = {memory_forbidden_description: "config.keys.memoryForbiddenDescriptionPlaceholder",@@ -669,7 +669,7 @@ const KEY_SORT_PRIORITY: Record<string, number> = {skill_retrieval_enabled: 1,proactive_recommendation_enabled: 0,proactive_recommendation_max_recommend_per_day: 2,- proactive_recommendation_max_sessions_per_tick: 3,+ proactive_recommendation_max_rounds_per_tick: 3,skill_retrieval_retrieve_max_exposure_depth: 10,skill_retrieval_build_max_depth: 20,skill_retrieval_build_max_workers: 21,diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 6cb63b5439..e86db2657e 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -727,7 +727,7 @@"proactiveEnabled": "Enable proactive recommendation","proactiveTickInterval": "Check interval (minutes)","proactiveMaxPerDay": "Daily recommendation limit",- "proactiveMaxSessions": "Max sessions per check"+ "proactiveMaxRounds": "Max rounds per check"},"keyHelp": {"skillCreate": "Install `skill-creator` and `teamskill-creator` before enabling",@@ -866,8 +866,8 @@"tickIntervalDesc": "How often the engine scans for proactive opportunities","maxPerDay": "Daily Limit","maxPerDayDesc": "Maximum proactive recommendations per day",- "maxSessions": "Sessions per Tick",- "maxSessionsDesc": "Maximum sessions analyzed per check cycle",+ "maxRounds": "Rounds per Tick",+ "maxRoundsDesc": "Maximum conversation rounds read per check","notConnected": "Please connect to the server first.","disabledHint": "Enable proactive recommendation first to use this feature.","typeLabel": {diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 7184cc55ba..0eefa7520d 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -726,7 +726,7 @@"proactiveEnabled": "启用主动推荐","proactiveTickInterval": "检查间隔(分钟)","proactiveMaxPerDay": "每日推荐上限",- "proactiveMaxSessions": "每次检查会话数"+ "proactiveMaxRounds": "每次检查对话轮数"},"keyHelp": {"skillCreate": "建议先安装 `skill-creator` 和 `teamskill-creator`,再开启",@@ -865,8 +865,8 @@"tickIntervalDesc": "引擎扫描主动推荐机会的频率","maxPerDay": "每日上限","maxPerDayDesc": "每日主动推荐次数上限",- "maxSessions": "每次检查会话数",- "maxSessionsDesc": "每轮检查最多分析的会话数",+ "maxRounds": "每次检查对话轮数",+ "maxRoundsDesc": "每次检查最多读取的对话轮数","notConnected": "请先连接服务器。","disabledHint": "请先启用主动推荐,再使用此功能。","typeLabel": {diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex cbdd7d0021..07d6b36905 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -454,7 +454,7 @@ _CONFIG_YAML_KEYS = frozenset({"a2ui_enabled","proactive_recommendation_enabled","proactive_recommendation_max_recommend_per_day",- "proactive_recommendation_max_sessions_per_tick",+ "proactive_recommendation_max_rounds_per_tick","swarmflow_enabled",})@@ -1069,9 +1069,9 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:proactive_cfg = resolved.get("proactive_recommendation") or {}payload["proactive_recommendation_enabled"] = "true" if proactive_cfg.get("enabled", False) else "false"payload["proactive_recommendation_max_recommend_per_day"] = str(- proactive_cfg.get("max_recommend_per_day", 5))- payload["proactive_recommendation_max_sessions_per_tick"] = str(- proactive_cfg.get("max_sessions_per_tick", 10))+ proactive_cfg.get("max_recommend_per_day", 10))+ payload["proactive_recommendation_max_rounds_per_tick"] = str(+ proactive_cfg.get("max_rounds_per_tick", 20))except Exception: # noqa: BLE001payload.setdefault("context_engine_enabled", "false")payload.setdefault("kv_cache_affinity_enabled", "false")@@ -1097,8 +1097,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:payload.setdefault("free_search_ddg_enabled", "false")payload.setdefault("free_search_bing_enabled", "false")payload.setdefault("proactive_recommendation_enabled", "false")- payload.setdefault("proactive_recommendation_max_recommend_per_day", "5")- payload.setdefault("proactive_recommendation_max_sessions_per_tick", "10")+ payload.setdefault("proactive_recommendation_max_recommend_per_day", "10")+ payload.setdefault("proactive_recommendation_max_rounds_per_tick", "20")await channel.send_response(ws, req_id, ok=True, payload=payload)def _persist_env_updates(updates: dict[str, str]) -> None:@@ -1205,8 +1205,8 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:update_proactive_recommendation_in_config({"enabled": parsed})elif param_key == "proactive_recommendation_max_recommend_per_day":update_proactive_recommendation_in_config({"max_recommend_per_day": int(str(val).strip())})- elif param_key == "proactive_recommendation_max_sessions_per_tick":- update_proactive_recommendation_in_config({"max_sessions_per_tick": int(str(val).strip())})+ elif param_key == "proactive_recommendation_max_rounds_per_tick":+ update_proactive_recommendation_in_config({"max_rounds_per_tick": int(str(val).strip())})yaml_updated.append(param_key)except Exception as e: # noqa: BLE001logger.warning("[config.set] 写回 config.yaml 失败 %s: %s", param_key, e)diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex 778a06c0ae..a5429a289f 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -417,10 +417,15 @@ class CronSchedulerService:except Exception as exc: # noqa: BLE001if self._is_croniter_no_next_date(exc):# 已过期的 one-shot:标记 expired 并停用,避免 UI 仍显示 enabled。+ # proactive job 的 enabled 由 ConfigPanel 开关管,scheduler 不碰。try:- job.enabled = False+ is_proactive = getattr(job, "mode", "") == "proactive.tick"+ patch = {"expired": True}+ if not is_proactive:+ patch["enabled"] = False+ job.enabled = Falsejob.expired = True- await self._store.update_job(job.id, {"enabled": False, "expired": True})+ await self._store.update_job(job.id, patch)except Exception as update_exc: # noqa: BLE001logger.warning("[Cron] mark expired failed job=%s: %s",@@ -589,9 +594,13 @@ class CronSchedulerService:except Exception as exc: # 兜底:reschedule 失败不阻断本次 tick 结果(下个 reload 会重排)if self._is_croniter_no_next_date(exc):try:- job.enabled = False+ is_proactive = getattr(job, "mode", "") == "proactive.tick"+ patch = {"expired": True}+ if not is_proactive:+ patch["enabled"] = False+ job.enabled = Falsejob.expired = True- await self._store.update_job(job.id, {"enabled": False, "expired": True})+ await self._store.update_job(job.id, patch)except Exception as update_exc: # 兜底:标记过期失败仅告警,不影响主流程logger.warning("[Cron] mark expired after proactive.tick failed job=%s: %s", job.id, update_exc)else:@@ -658,9 +667,13 @@ class CronSchedulerService:# 不删除,改为标记过期(与自然过期的一次性任务行为一致)logger.info("[Cron] delete_after_run job=%s, marking expired after push", job.id)try:- await self._store.update_job(job.id, {"enabled": False, "expired": True})- job.enabled = False+ is_proactive = getattr(job, "mode", "") == "proactive.tick"+ patch = {"expired": True}+ if not is_proactive:+ patch["enabled"] = False+ job.enabled = Falsejob.expired = True+ await self._store.update_job(job.id, patch)except Exception as update_exc:logger.warning("[Cron] mark expired after push failed job=%s: %s", job.id, update_exc)returndiff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 4bac708f5f..ff48157113 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -190,8 +190,8 @@ memory:proactive_recommendation:enabled: ${PROACTIVE_RECOMMENDATION_ENABLED:-false} # 总开关- max_recommend_per_day: ${MAX_RECOMMEND_PER_DAY:-5} # 每天最多推荐次数- max_sessions_per_tick: ${MAX_SESSIONS_PER_TICK:-10} # 每次 Tick 扫描最多几个会话+ max_recommend_per_day: ${MAX_RECOMMEND_PER_DAY:-10} # 每天最多推荐次数+ max_rounds_per_tick: ${MAX_ROUNDS_PER_TICK:-20} # 每次 Tick 读取最近几轮对话models:defaults:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 0a6056612e..b2bd38866d 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -1827,7 +1827,12 @@ class JiuWenSwarm:event_type="chat.final",content=pending_text,timestamp=time.time(),- extra=_attach_reasoning_content(),+ # 透传 proactive 标记到 history——刷新页面时前端靠 payload.source===+ # 'proactive_recommendation' 渲染推荐卡片,不带则退化白色气泡。+ extra=_attach_reasoning_content({+ k: v for k, v in request.params.items()+ if k in ("source", "proactive_type", "proactive_target")+ }),mode=request.params.get("mode", "unknown"),)durable_final_content = pending_text@@ -2016,6 +2021,10 @@ class JiuWenSwarm:extra_fields[k] = vif et in {"chat.final", "chat.tool_call"}:extra_fields = _attach_reasoning_content(extra_fields)+ # 透传 proactive 标记——刷新页面时前端靠 source 识别卡片+ for pk in ("source", "proactive_type", "proactive_target"):+ if pk not in extra_fields and pk in request.params:+ extra_fields[pk] = request.params[pk]append_history_record(session_id=session_id,request_id=rid,@@ -2110,6 +2119,10 @@ class JiuWenSwarm:extra_fields[k] = vif et in {"chat.final", "chat.tool_call"}:extra_fields = _attach_reasoning_content(extra_fields)+ # 透传 proactive 标记——刷新页面时前端靠 source 识别卡片+ for pk in ("source", "proactive_type", "proactive_target"):+ if pk not in extra_fields and pk in request.params:+ extra_fields[pk] = request.params[pk]append_history_record(session_id=session_id,request_id=rid,@@ -2161,7 +2174,10 @@ class JiuWenSwarm:event_type="chat.final",content=finalized_assistant_message,timestamp=time.time(),- extra=_attach_reasoning_content(),+ extra=_attach_reasoning_content({+ k: v for k, v in request.params.items()+ if k in ("source", "proactive_type", "proactive_target")+ }),mode=request.params.get("mode", "unknown"),)final_answer_content = finalized_assistant_messagediff --git a/jiuwenswarm/server/runtime/proactive_adapter.py b/jiuwenswarm/server/runtime/proactive_adapter.pyindex 2e10f58cc2..c743ca5263 100644--- a/jiuwenswarm/server/runtime/proactive_adapter.py+++ b/jiuwenswarm/server/runtime/proactive_adapter.py@@ -161,6 +161,35 @@ async def init_proactive_engine(server, config: dict[str, Any] | None = None) ->proactive_agent = build_proactive_agent()proactive_engine.set_proactive_agent(proactive_agent)+ # 检查 agent 是否活跃——在调 LLM 之前检查,避免 agent 被 evict 后白调 LLM。+ def _check_agent_cb(channel_id):+ cid = channel_id or "web"+ agent = server.get_agent_manager().get_agent_nowait(cid)+ return agent is not None and hasattr(agent, "process_message_stream")+ proactive_engine.set_check_agent_available_callback(_check_agent_cb)++ # 推送通知回调——直接推文本到前端,不经过主 agent(不进 context)。+ # 用于"今日推荐已达上限"等系统提醒。+ async def _send_notification_cb(channel_id, text):+ cid = channel_id or "web"+ import time as _time+ try:+ await server.send_push({+ "request_id": f"proactive_notification_{int(_time.time() * 1000)}",+ "channel_id": cid,+ "payload": {+ "content": text,+ "event_type": "chat.final",+ "role": "assistant",+ "source": "proactive_notification",+ },+ })+ return True+ except Exception as exc:+ logger.debug("[ProactiveEngine] send_notification push failed: %s", exc)+ return False+ proactive_engine.set_send_notification_callback(_send_notification_cb)+# 触发主 agent 回调:tick 决策后,把决策包成指令式 query 触发主 agent# 跑一轮,主 agent 自己生成话术 → 进 context engine → stream 推前端。async def _trigger_cb(session_id, channel_id, query, decision):diff --git a/tests/symphony/test_proactive_recommendation_flow.py b/tests/symphony/test_proactive_recommendation_flow.pyindex 6d734faee6..d0b96365db 100644--- a/tests/symphony/test_proactive_recommendation_flow.py+++ b/tests/symphony/test_proactive_recommendation_flow.py@@ -56,15 +56,15 @@ def _fake_report() -> MagicMock:return report-def _write_profile(ws_dir: Path, profile_data: dict) -> Path:- """Write user_profile.json into the workspace dir (where the engine reads/writes)."""- profile_path = ws_dir / "user_profile.json"- profile_path.write_text(json.dumps(profile_data, ensure_ascii=False, indent=2), encoding="utf-8")- return profile_path+def _write_state(ws_dir: Path, state_data: dict) -> Path:+ """Write recommendation.json into the workspace dir (where the engine reads/writes)."""+ state_path = ws_dir / "recommendation.json"+ state_path.write_text(json.dumps(state_data, ensure_ascii=False, indent=2), encoding="utf-8")+ return state_path-def _read_profile(ws_dir: Path) -> dict:- return json.loads((ws_dir / "user_profile.json").read_text(encoding="utf-8"))+def _read_state(ws_dir: Path) -> dict:+ return json.loads((ws_dir / "recommendation.json").read_text(encoding="utf-8"))class _MockProactiveAgent:@@ -109,10 +109,6 @@ async def test_tick1_recommend_skill():emitted = []tick1_llm = {- "preferences": ["使用 pytest 做测试"],- "goals": ["搭建测试自动化"],- "interests": ["CI/CD 自动化"],- "commitments": [],"decision": {"type": "need_exploration","target": "auto-test-runner",@@ -125,11 +121,7 @@ async def test_tick1_recommend_skill():with tempfile.TemporaryDirectory() as ws:ws_path = Path(ws)- _write_profile(ws_path, {- "preferences": ["使用 pytest 做测试"],- "goals": ["搭建测试自动化"],- "interests": [],- "commitments": [],+ _write_state(ws_path, {"recommendation_history": [],"last_updated": "",})@@ -151,8 +143,8 @@ async def test_tick1_recommend_skill():assert len(emitted) == 1, f"Should trigger 1 recommendation, got {len(emitted)}"# Verify profile was updated- profile_data = _read_profile(ws_path)- assert len(profile_data["recommendation_history"]) == 1+ state_data = _read_state(ws_path)+ assert len(state_data["recommendation_history"]) == 1# ── Tick 2: Continue recommending different skill ──────@@ -164,11 +156,7 @@ async def test_tick2_recommend_different_skill():with tempfile.TemporaryDirectory() as ws:ws_path = Path(ws)- _write_profile(ws_path, {- "preferences": ["使用 pytest 做测试"],- "goals": ["搭建测试自动化"],- "interests": ["CI/CD 自动化"],- "commitments": [],+ _write_state(ws_path, {"recommendation_history": [{"type": "need_exploration","target": "auto-test-runner",@@ -181,10 +169,6 @@ async def test_tick2_recommend_different_skill():})tick2_llm = {- "preferences": ["使用 pytest 做测试"],- "goals": ["搭建测试自动化"],- "interests": ["CI/CD 自动化"],- "commitments": [],"decision": {"type": "need_exploration","target": "test-coverage",@@ -212,8 +196,8 @@ async def test_tick2_recommend_different_skill():assert len(emitted) == 1, f"Should trigger 1 recommendation, got {len(emitted)}"# Verify profile was updated with new recommendation- profile_data = _read_profile(ws_path)- assert len(profile_data["recommendation_history"]) == 2+ state_data = _read_state(ws_path)+ assert len(state_data["recommendation_history"]) == 2# ── Tick 3: No recommendation when cooldown active ─────@@ -225,11 +209,7 @@ async def test_tick3_cooldown_blocks_recommendation():with tempfile.TemporaryDirectory() as ws:ws_path = Path(ws)- _write_profile(ws_path, {- "preferences": ["使用 pytest 做测试"],- "goals": ["搭建测试自动化"],- "interests": [],- "commitments": [],+ _write_state(ws_path, {"recommendation_history": [{"type": "need_exploration","target": "auto-test-runner",@@ -245,10 +225,6 @@ async def test_tick3_cooldown_blocks_recommendation():})tick3_llm = {- "preferences": ["使用 pytest 做测试"],- "goals": ["搭建测试自动化"],- "interests": [],- "commitments": [],"decision": {"type": "skill_recommend","target": "auto-test-runner",@@ -285,11 +261,7 @@ async def test_no_recommendation_when_decision_null():with tempfile.TemporaryDirectory() as ws:ws_path = Path(ws)- _write_profile(ws_path, {- "preferences": [],- "goals": [],- "interests": [],- "commitments": [],+ _write_state(ws_path, {"recommendation_history": [{"type": "need_exploration","target": "auto-test-runner",@@ -302,10 +274,6 @@ async def test_no_recommendation_when_decision_null():})tick_llm = {- "preferences": [],- "goals": [],- "interests": [],- "commitments": [],"decision": None, # No recommendation}@@ -344,11 +312,7 @@ async def test_daily_limit_blocks_tick():with tempfile.TemporaryDirectory() as ws:ws_path = Path(ws)- _write_profile(ws_path, {- "preferences": [],- "goals": [],- "interests": [],- "commitments": [],+ _write_state(ws_path, {"recommendation_history": [],"last_updated": "",})@@ -382,8 +346,6 @@ async def test_skip_when_main_agent_busy():)tick_llm = {- "preferences": [], "goals": [],- "interests": [], "commitments": [],"decision": {"type": "task_reminder", "target": "项目周会","reason": "时间临近", "urgency": 0.9,@@ -399,9 +361,7 @@ async def test_skip_when_main_agent_busy():with tempfile.TemporaryDirectory() as ws:ws_path = Path(ws)- _write_profile(ws_path, {- "preferences": [], "goals": [],- "interests": [], "commitments": [],+ _write_state(ws_path, {"recommendation_history": [], "last_updated": "",})@@ -422,8 +382,8 @@ async def test_skip_when_main_agent_busy():assert result is False# 不应记冷却/推荐历史(因为没真正投递)- profile_data = _read_profile(ws_path)- assert len(profile_data["recommendation_history"]) == 0+ state_data = _read_state(ws_path)+ assert len(state_data["recommendation_history"]) == 0# ── 专用 agent JSON 解析 ───────────────────────────────────────@@ -435,29 +395,20 @@ async def test_proactive_agent_output_parsed_to_decision():_analyze_and_decide, RecommendationDecision,)tick_llm = {- "preferences": ["Python 异步"],- "goals": ["认证模块重构"],- "interests": ["CI/CD"],- "commitments": ["编写单元测试"],"decision": {"type": "skill_recommend", "target": "auto-test-runner","reason": "手动测试繁琐", "urgency": 0.7,},}dedicated = _make_proactive_agent([tick_llm])- profile = MagicMock(- preferences=[], goals=[],- interests=[], commitments=[],- )+ state = MagicMock()- result = await _analyze_and_decide("report text", profile, SAMPLE_SKILLS, dedicated)+ result = await _analyze_and_decide("report text", state, SAMPLE_SKILLS, dedicated)assert result.decision is not Noneassert result.decision.type == "skill_recommend"assert result.decision.target == "auto-test-runner"assert result.decision.urgency == 0.7- assert "preferences" in result.profile_delta- assert result.profile_delta["preferences"] == ["Python 异步"]@pytest.mark.asyncio@@ -471,10 +422,6 @@ async def test_proactive_agent_invalid_json_returns_empty():async def invoke(self, inputs, session=None):return {"output": "这不是JSON", "result_type": "answer"}- profile = MagicMock(- preferences=[], goals=[],- interests=[], commitments=[],- )- result = await _analyze_and_decide("report", profile, SAMPLE_SKILLS, _BadAgent())+ state = MagicMock()+ result = await _analyze_and_decide("report", state, SAMPLE_SKILLS, _BadAgent())assert result.decision is None- assert result.profile_delta == {}