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] add "Summarize from here" / "Summarize up to here" partial conversation compaction refs: #540
haowenzhong1b684bdac8017
diff --git a/jiuwenswarm/agents/harness/common/session_ops_service.py b/jiuwenswarm/agents/harness/common/session_ops_service.pyindex a88d23f923..1808d225bd 100644--- a/jiuwenswarm/agents/harness/common/session_ops_service.py+++ b/jiuwenswarm/agents/harness/common/session_ops_service.py@@ -5,6 +5,7 @@ import jsonimport loggingimport reimport shutil+import timefrom pathlib import Pathfrom typing import Any, TYPE_CHECKING@@ -219,6 +220,176 @@ def rewind_session(}+def compact_partial_session(+ *,+ session_id: str,+ turn_index: int,+ direction: str = "from",+ llm_summary: str | None = None,+) -> dict[str, Any]:+ if turn_index < 1:+ raise ValueError("turn_index must be >= 1")++ sessions_dir = get_agent_sessions_dir()+ history_path = sessions_dir / session_id / "history.json"+ if not history_path.exists():+ raise ValueError("session history not found")++ history = json.loads(history_path.read_text(encoding="utf-8"))+ if not isinstance(history, list):+ raise ValueError("invalid history format")++ user_positions = []+ for i, record in enumerate(history):+ if record.get("role") == "user":+ user_positions.append(i)++ total_turns = len(user_positions)+ if total_turns == 0:+ raise ValueError("no user messages in session")+ if turn_index > total_turns:+ raise ValueError(+ f"turn_index {turn_index} exceeds total turns ({total_turns})"+ )++ target_user_index = user_positions[turn_index - 1]++ import uuid+ from jiuwenswarm.server.runtime.session.session_history import (+ _FILE_LOCK,+ _WRITE_QUEUE,+ truncate_history_records,+ )+ from jiuwenswarm.server.runtime.session.session_metadata import update_session_metadata++ removed_turn_content = ""+ if 0 <= target_user_index < len(history):+ content = history[target_user_index].get("content", "")+ raw = content if isinstance(content, str) else str(content)+ removed_turn_content = re.sub(r"<file-content[^>]*>.*?</file-content>", "", raw, flags=re.DOTALL).strip()++ if direction == "from":+ cut_timestamp = history[target_user_index].get("timestamp")+ summarized_count = len(history) - target_user_index++ result = truncate_history_records(session_id=session_id, cut_index=target_user_index)+ remaining = result["remaining_records"]+ removed = result["removed_records"]++ if cut_timestamp is not None:+ try:+ from jiuwenswarm.server.utils.diff_service import get_diff_service+ get_diff_service().truncate_file_ops_by_timestamp(session_id, cut_timestamp)+ except Exception as exc:+ logger.warning("compact_partial_session: failed to truncate file_ops: %s", exc)++ elif direction == "up_to":+ kept = history[target_user_index:]+ summarized_count = target_user_index+ removed = summarized_count+ remaining = len(kept)++ _WRITE_QUEUE.join()+ with _FILE_LOCK:+ history_path.write_text(+ json.dumps(kept, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ else:+ raise ValueError(f"unknown direction: {direction}")++ update_session_metadata(+ session_id=session_id,+ set_message_count=remaining,+ )++ request_id = str(uuid.uuid4())+ now = time.time()++ short_text = (+ f"Summarized {summarized_count} messages from this point."+ if direction == "from"+ else f"Summarized {summarized_count} messages up to this point."+ )++ boundary_record = {+ "id": f"{request_id}:assistant",+ "role": "assistant",+ "request_id": request_id,+ "channel_id": "tui",+ "timestamp": now,+ "content": "Conversation compacted",+ "event_type": "context.compact_boundary",+ "compact_metadata": {+ "trigger": "manual_rewind",+ "direction": direction,+ "turn_index": turn_index,+ "summarized_messages": summarized_count,+ },+ }++ summary_record = {+ "id": f"{request_id}:assistant_summary",+ "role": "assistant",+ "request_id": request_id,+ "channel_id": "tui",+ "timestamp": now + 0.001,+ "content": short_text,+ "event_type": "context.rewind_summary",+ "compact_metadata": {+ "trigger": "manual_rewind",+ "direction": direction,+ "turn_index": turn_index,+ "summarized_messages": summarized_count,+ },+ "is_compact_summary": True,+ }++ _WRITE_QUEUE.join()+ with _FILE_LOCK:+ existing = json.loads(history_path.read_text(encoding="utf-8")) if history_path.exists() else []+ if not isinstance(existing, list):+ existing = []+ existing.append(boundary_record)+ existing.append(summary_record)++ if llm_summary:+ compact_summary_record = {+ "id": f"{request_id}:assistant_csummary",+ "role": "assistant",+ "request_id": request_id,+ "channel_id": "tui",+ "timestamp": now + 0.002,+ "content": llm_summary,+ "event_type": "context.compact_summary",+ "compact_metadata": {+ "trigger": "manual_rewind",+ "direction": direction,+ "turn_index": turn_index,+ "summarized_messages": summarized_count,+ },+ "is_compact_summary": True,+ "transcript_only": True,+ }+ existing.append(compact_summary_record)++ history_path.write_text(+ json.dumps(existing, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )++ return {+ "session_id": session_id,+ "turn_index": turn_index,+ "content": removed_turn_content,+ "content_preview": removed_turn_content[:80] if removed_turn_content else "",+ "remaining_records": remaining + 2,+ "removed_records": removed,+ "summarized_messages": summarized_count,+ "direction": direction,+ }++_NON_USER_AUTHORED_TAGS = ("<local-command-stdout>","<local-command-stderr>",@@ -576,9 +747,22 @@ async def rewind_session_context(reasoning_content=reasoning if reasoning else None,))+ elif event_type == "context.compact_summary":+ if current_tool_calls:+ _flush_pending_assistant()+ if content.strip():+ context_messages.append(UserMessage(content=content))++ elif event_type == "context.rewind_summary":+ if current_tool_calls:+ _flush_pending_assistant()+ if content.strip():+ context_messages.append(UserMessage(content=content))+else:# chat.delta, chat.tool_update, chat.usage_metadata,- # chat.usage_summary, chat.ask_user_question+ # chat.usage_summary, chat.ask_user_question,+ # context.compact_boundaryskipped += 1# Flush any remaining state (e.g. interrupted turn with only reasoning)diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.tsindex 2780f66ce5..38a7a8cca8 100644--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts@@ -1646,9 +1646,17 @@ export class CliPiAppState {this.entries = [...sorted];this.rebuildToolExecutionState();+ this.collapseAllToolGroupsAfterRestore();this.emitChange();}+ private collapseAllToolGroupsAfterRestore(): void {+ const ids = getToolGroupIds(this.entries, Array.from(this.toolExecutions.values()));+ for (const id of ids) {+ this.collapsedToolGroupIds.add(id);+ }+ }+private readonly clearToolExecutionState = (): void => {if (this.toolTimeoutTimer) {clearTimeout(this.toolTimeoutTimer);diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/rewind.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/rewind.tsindex b2a85cc50e..c66d716608 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/rewind.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/rewind.ts@@ -1,4 +1,4 @@-import { addCommandEcho, addError, addInfo } from "../helpers.js";+import { addCommandEcho, addError, addInfo, makeItem } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";export interface TurnFileChange {@@ -40,7 +40,7 @@ export interface RewindPayload {}/** 恢复选项类型 */-type RestoreOption = "both" | "conversation" | "code" | "cancel";+type RestoreOption = "both" | "conversation" | "code" | "summarize" | "summarize_up_to" | "cancel";const GREEN = "\x1b[32m";const RED = "\x1b[31m";@@ -199,6 +199,16 @@ export function createRewindCommand(): SlashCommand {description: "Restore modified files to their prior state; conversation remains unchanged",value: "code",},+ {+ label: "Summarize from here",+ description: "Keep earlier conversation, summarize messages from this turn onward into a compact summary",+ value: "summarize",+ },+ {+ label: "Summarize up to here",+ description: "Summarize earlier conversation, keep this turn and after unchanged",+ value: "summarize_up_to",+ },];// 局限提示@@ -318,6 +328,64 @@ export function createRewindCommand(): SlashCommand {}ctx.addItem(addInfo(ctx.sessionId, msg, "i"));+ } else if (optionValue === "summarize") {+ ctx.addItem(+ addInfo(ctx.sessionId, "Messages after this point will be summarized.", "i", { view: "dim" }),+ );+ ctx.addItem(+ addInfo(ctx.sessionId, "Summarizing…", "i", { view: "dim" }),+ );+ await new Promise(resolve => setTimeout(resolve, 0));++ const rewindPayload = await ctx.request<RewindPayload & { summary?: string; summarized_messages?: number }>(+ "command.rewind_compact",+ {+ session_id: ctx.sessionId,+ turn_index: selectedTurnIndex,+ direction: "from",+ mode: ctx.mode,+ },+ 120000,+ );++ const restoreText = rewindPayload.content ?? selectedTurn.content_preview;++ ctx.clearEntries();+ ctx.addItem(addCommandEcho(ctx.sessionId, `/rewind ${selectedTurnIndex}`));+ await ctx.restoreHistory(ctx.sessionId);++ if (restoreText) {+ ctx.setInput?.(restoreText);+ }+ } else if (optionValue === "summarize_up_to") {+ ctx.addItem(+ addInfo(ctx.sessionId, "Messages up to this point will be summarized.", "i", { view: "dim" }),+ );+ ctx.addItem(+ addInfo(ctx.sessionId, "Summarizing…", "i", { view: "dim" }),+ );+ await new Promise(resolve => setTimeout(resolve, 0));++ const rewindPayload = await ctx.request<RewindPayload & { summary?: string; summarized_messages?: number }>(+ "command.rewind_compact",+ {+ session_id: ctx.sessionId,+ turn_index: selectedTurnIndex,+ direction: "up_to",+ mode: ctx.mode,+ },+ 120000,+ );++ const restoreText = rewindPayload.content ?? selectedTurn.content_preview;++ ctx.clearEntries();+ ctx.addItem(addCommandEcho(ctx.sessionId, `/rewind ${selectedTurnIndex}`));+ await ctx.restoreHistory(ctx.sessionId);++ if (restoreText) {+ ctx.setInput?.(restoreText);+ }}} catch (error) {const message = error instanceof Error ? error.message : String(error);diff --git a/jiuwenswarm/channels/tui/frontend/src/core/history-parser.ts b/jiuwenswarm/channels/tui/frontend/src/core/history-parser.tsindex d9992a74ea..bf0ff136f0 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/history-parser.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/history-parser.ts@@ -772,6 +772,23 @@ export function parseHistoryFrame(frame: EventFrame): HistoryItem | null {};}+ if (eventType === "context.rewind_summary") {+ const content = pickFirstString(record, ["content", "text", "body"]) ?? "";+ if (!content) return null;+ return {+ kind: "info",+ id,+ sessionId,+ content,+ icon: "i",+ meta: {+ view: "rewind_summary",+ title: "Summarized conversation",+ },+ at,+ };+ }+if (eventType === "context.usage" ||eventType === "chat.subtask_update" ||diff --git a/jiuwenswarm/channels/tui/frontend/src/core/types.ts b/jiuwenswarm/channels/tui/frontend/src/core/types.tsindex c6e4c17e1e..837c5fccb4 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/types.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/types.ts@@ -28,7 +28,7 @@ export interface SystemMeta {}export interface InfoMeta {- view?: "help" | "list" | "kv" | "dim" | "compact_boundary" | "compact_summary";+ view?: "help" | "list" | "kv" | "dim" | "compact_boundary" | "compact_summary" | "rewind_summary";title?: string;items?: Array<{ label: string; value?: string; description?: string }>;groups?: Array<{diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/meta-components.ts b/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/meta-components.tsindex 93d8c3a0c8..bcd51b2447 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/meta-components.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/components/messages/meta-components.ts@@ -118,24 +118,53 @@ export class InfoMessageComponent implements Component {if (meta?.view === "compact_summary") {const lines: string[] = [];lines.push(...renderWrappedText(Math.max(1, width), "· Compaction summary", palette.text.info));+ const isRewindCompact = meta.title && meta.title.startsWith("Summarized");+ if (!isRewindCompact) {+ lines.push(+ ...renderClaudeResponseLines(+ width,+ renderWrappedText(+ Math.max(1, width - 4),+ "The earlier conversation has been compacted into the following memory block, which will be used as historical context going forward:",+ palette.text.dim,+ ),+ palette.text.dim,+ ),+ );+ }lines.push(...renderClaudeResponseLines(width,- renderWrappedText(- Math.max(1, width - 4),- "The earlier conversation has been compacted into the following memory block, which will be used as historical context going forward:",- palette.text.dim,- ),- palette.text.dim,+ renderWrappedText(Math.max(1, width - 4), this.entry.content, palette.text.assistant),+ palette.text.assistant,),);+ return lines;+ }++ if (meta?.view === "rewind_summary") {+ const lines: string[] = [];+ lines.push(+ ...renderWrappedText(Math.max(1, width), "⏺ Summarized conversation", palette.text.info),+ );lines.push(...renderClaudeResponseLines(width,- renderWrappedText(Math.max(1, width - 4), this.entry.content, palette.text.assistant),+ renderWrappedText(+ Math.max(1, width - 4),+ this.entry.content,+ palette.text.assistant,+ ),palette.text.assistant,),);+ lines.push(+ ...renderWrappedText(+ Math.max(1, width),+ " (ctrl+o to expand history)",+ palette.text.dim,+ ),+ );return lines;}diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex fcc5f9159a..f4962fbd3f 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -19,6 +19,7 @@ class ReqMethod(Enum):COMMAND_ADD_DIR = "command.add_dir"COMMAND_CHROME = "command.chrome"COMMAND_COMPACT = "command.compact"+ COMMAND_COMPACT_PARTIAL = "command.compact_partial"COMMAND_CONTEXT = "command.context"COMMAND_RECAP = "command.recap"COMMAND_DIFF = "command.diff"@@ -43,6 +44,7 @@ class ReqMethod(Enum):SESSION_REWIND = "session.rewind"SESSION_REWIND_AND_RESTORE = "session.rewind_and_restore"SESSION_REWIND_CONTEXT = "session.rewind_context"+ SESSION_REWIND_COMPACT = "session.rewind_compact"SESSION_RESTORE_FILES = "session.restore_files"HISTORY_LIST_TURNS = "history.list_turns"TEAM_DELETE = "team.delete"diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.pyindex 520a26529a..993f4c0cbe 100644--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py@@ -10,7 +10,7 @@ import shutilimport sysimport timefrom dataclasses import dataclass-from typing import Any+from typing import Any, Optionalimport yaml@@ -168,6 +168,7 @@ CLI_FORWARD_REQ_METHODS = frozenset("command.add_dir","command.chrome","command.compact",+ "command.compact_partial","command.context","command.recap","command.diff",@@ -262,6 +263,7 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset("command.add_dir","command.chrome","command.compact",+ "command.compact_partial","command.context","command.recap","command.diff",@@ -1346,9 +1348,9 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:async def _forward_rewind_e2a(params: ForwardRewindE2AParams) -> bool:"""Try to forward a rewind request to AgentServer via E2A.- Returns True if the request was fully handled (success or error response- sent to the client). Returns False if E2A is unavailable and the caller- should fall back to local-only processing.+ Returns True if the request was successfully handled by AgentServer.+ Returns False if E2A is unavailable or AgentServer returned an error,+ so the caller should fall back to local-only processing."""from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields@@ -1377,18 +1379,54 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:return Truepl = resp.payload if isinstance(resp.payload, dict) else {}err = pl.get("error", params.error_label)- code = pl.get("code") or None- if isinstance(code, str) and not code.strip():- code = None- await channel.send_response(params.ws, params.req_id, ok=False, error=str(err), code=code)- return True+ logger.warning("[cli %s] AgentServer returned error, fallback local: %s", params.error_label, err)+ return Falseexcept Exception as e:logger.warning("[cli %s] forward to agent failed, fallback local: %s", params.error_label, e)return False+ async def _compact_partial_via_e2a(target_sid: str, turn_index: int, direction: str) -> tuple[Optional[str], int]:+ """通过 E2A 转发 LLM 摘要请求到 AgentServer。返回 (summary, summarized_count)。"""+ from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenswarm.common.schema.message import ReqMethod++ real_client = (+ agent_client.get("value")+ if isinstance(agent_client, dict)+ else agent_client+ )+ if real_client is None:+ return None, 0++ try:+ env = e2a_from_agent_fields(+ request_id=str(time.time()),+ channel_id="tui",+ session_id=target_sid,+ req_method=ReqMethod.COMMAND_COMPACT_PARTIAL,+ params={+ "session_id": target_sid,+ "turn_index": turn_index,+ "direction": direction,+ },+ is_stream=False,+ timestamp=time.time(),+ )+ resp = await real_client.send_request(env)+ if resp.ok:+ pl = resp.payload if isinstance(resp.payload, dict) else {}+ summary = pl.get("summary") if pl.get("status") == "ok" else None+ summarized_count = pl.get("summarized_count", 0)+ return summary, summarized_count+ logger.warning("[compact_partial_via_e2a] E2A failed: %s", resp.payload)+ except Exception as e:+ logger.warning("[compact_partial_via_e2a] E2A call failed: %s", e)++ return None, 0+async def _session_rewind(ws, req_id, params, session_id):+ """session.rewind: E2A → AgentServer(权威写入者),fallback 本地."""from jiuwenswarm.agents.harness.common.session_ops_service import rewind_session- """session.rewind: 优先转发到 AgentServer(同时截断 history + context),失败则 fallback 本地仅截断 history."""from jiuwenswarm.common.schema.message import ReqMethodif not isinstance(params, dict):@@ -1416,7 +1454,6 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:)return- # 优先通过 E2A 转发到 AgentServer(同时处理 history + context 截断)if await _forward_rewind_e2a(ForwardRewindE2AParams(ws=ws,@@ -1429,8 +1466,6 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:):return- # Fallback: 仅本地截断 history.json(不含 context 截断)- from jiuwenswarm.agents.harness.common.session_ops_service import rewind_sessiontry:result = rewind_session(session_id=target_sid, turn_index=turn_index)await channel.send_response(ws, req_id, ok=True, payload=result)@@ -1457,12 +1492,11 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")async def _session_rewind_and_restore(ws, req_id, params, session_id):- """session.rewind_and_restore: 截断对话 + 恢复文件."""+ """session.rewind_and_restore: E2A → AgentServer(权威写入者),fallback 本地."""from jiuwenswarm.agents.harness.common.session_ops_service import (restore_session_files,rewind_session,)- """session.rewind_and_restore: 优先转发到 AgentServer(history + context + 文件恢复),失败则 fallback 本地."""from jiuwenswarm.common.schema.message import ReqMethodif not isinstance(params, dict):@@ -1490,7 +1524,6 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:)return- # 优先通过 E2A 转发到 AgentServerif await _forward_rewind_e2a(ForwardRewindE2AParams(ws=ws,@@ -1503,11 +1536,6 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:):return- # Fallback: 仅本地操作- from jiuwenswarm.agents.harness.common.session_ops_service import (- restore_session_files,- rewind_session,- )try:restore_result = restore_session_files(session_id=target_sid, turn_index=turn_index)rewind_result = rewind_session(session_id=target_sid, turn_index=turn_index)@@ -1559,6 +1587,101 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:except Exception as e:await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")+ async def _command_rewind_compact(ws, req_id, params, session_id):+ """command.rewind_compact: LLM 摘要(E2A→AgentServer) + 截断 + 记录写入(AgentServer E2A)。"""+ if not isinstance(params, dict):+ await channel.send_response(+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST"+ )+ return+ target_sid = str(params.get("session_id") or session_id or "").strip()+ turn_index = params.get("turn_index")+ direction = str(params.get("direction") or "from").strip()+ if not target_sid:+ await channel.send_response(+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST"+ )+ return+ if turn_index is None:+ await channel.send_response(+ ws, req_id, ok=False, error="turn_index is required", code="BAD_REQUEST"+ )+ return+ try:+ turn_index = int(turn_index)+ except (ValueError, TypeError):+ await channel.send_response(+ ws, req_id, ok=False, error="turn_index must be an integer", code="BAD_REQUEST"+ )+ return+ if direction not in ("from", "up_to"):+ await channel.send_response(+ ws, req_id, ok=False, error="direction must be 'from' or 'up_to'", code="BAD_REQUEST"+ )+ return++ try:+ llm_summary, summarized_count = await _compact_partial_via_e2a(target_sid, turn_index, direction)+ except Exception as e:+ logger.warning("[cli command.rewind_compact] LLM summary failed: %s", e)+ llm_summary = None+ summarized_count = 0++ # Step 2: Send rewind to AgentServer (truncation + agent-internal record writing)+ from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenswarm.common.schema.message import ReqMethod++ real_client = (+ agent_client.get("value")+ if isinstance(agent_client, dict)+ else agent_client+ )+ if real_client is not None:+ try:+ env = e2a_from_agent_fields(+ request_id=req_id,+ channel_id="tui",+ session_id=target_sid,+ req_method=ReqMethod.SESSION_REWIND_COMPACT,+ params={+ "session_id": target_sid,+ "turn_index": turn_index,+ "direction": direction,+ "compact_summary": llm_summary,+ "summarized_count": summarized_count,+ },+ is_stream=False,+ timestamp=time.time(),+ )+ resp = await real_client.send_request(env)+ if resp.ok:+ pl = resp.payload if isinstance(resp.payload, dict) else {}+ pl["summary"] = llm_summary+ pl["summarized_messages"] = summarized_count+ await channel.send_response(ws, req_id, ok=True, payload=pl)+ return+ logger.warning("[cli command.rewind_compact] E2A failed: %s", resp.payload)+ except Exception as e:+ logger.warning("[cli command.rewind_compact] E2A failed, fallback local: %s", e)++ # Fallback: local truncation + record writing+ try:+ from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session+ result = compact_partial_session(+ session_id=target_sid,+ turn_index=turn_index,+ direction=direction,+ llm_summary=llm_summary,+ )+ result["summary"] = llm_summary+ result["summarized_messages"] = summarized_count+ await channel.send_response(ws, req_id, ok=True, payload=result)+ except ValueError as e:+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")+ except Exception as e:+ logger.exception("[cli command.rewind_compact] %s", e)+ await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")+async def _session_rename(ws, req_id, params, session_id):"""优先经 E2A 转发至 AgentWebSocketServer._handle_session_rename;无 agent 或转发失败时本地回退。"""from jiuwenswarm.server.runtime.session.session_rename import apply_session_rename@@ -2081,6 +2204,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:channel.register_local_handler(path, "session.rewind", _session_rewind)channel.register_local_handler(path, "session.rewind_and_restore", _session_rewind_and_restore)channel.register_local_handler(path, "session.restore_files", _session_restore_files)+ channel.register_local_handler(path, "command.rewind_compact", _command_rewind_compact)channel.register_local_handler(path, "history.list_turns", _history_list_turns)channel.register_local_handler(path, "chat.send", _chat_send)channel.register_local_handler(path, "chat.resume", _chat_resume)diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex bd2db3d962..550cc23533 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -129,6 +129,7 @@ _HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES = frozenset("team.message","context.compact_boundary","context.compact_summary",+ "context.rewind_summary",})@@ -1122,6 +1123,9 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.SESSION_REWIND_AND_RESTORE:await self._handle_session_rewind_full(ws, request, send_lock, restore_files=True)return+ if request.req_method == ReqMethod.SESSION_REWIND_COMPACT:+ await self._handle_session_rewind_full(ws, request, send_lock, compact=True)+ returnif request.req_method == ReqMethod.SESSION_REWIND_CONTEXT:await self._handle_session_rewind_context(ws, request, send_lock)return@@ -1155,6 +1159,9 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.COMMAND_COMPACT:await self._handle_command_compact(ws, request, send_lock)return+ if request.req_method == ReqMethod.COMMAND_COMPACT_PARTIAL:+ await self._handle_command_compact_partial(ws, request, send_lock)+ returnif request.req_method == ReqMethod.COMMAND_CONTEXT:await self._handle_command_context(ws, request, send_lock)return@@ -2100,6 +2107,7 @@ class AgentWebSocketServer:async def _handle_session_rewind_full(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock,restore_files: bool = False,+ compact: bool = False,) -> None:"""Full rewind: truncate history.json + context_engine + update checkpointer."""from jiuwenswarm.agents.harness.common.session_ops_service import (@@ -2110,6 +2118,9 @@ class AgentWebSocketServer:params = request.params if isinstance(request.params, dict) else {}target_sid = str(params.get("session_id") or request.session_id or "").strip()turn_index = params.get("turn_index")+ compact_summary = params.get("compact_summary") if compact else None+ direction = str(params.get("direction") or "from").strip() if compact else "from"+ summarized_count = int(params.get("summarized_count", 0) or 0) if compact else 0if not target_sid or turn_index is None:wire = AgentWebSocketServer._send_error_response(@@ -2139,9 +2150,24 @@ class AgentWebSocketServer:restore_result = restore_session_files(session_id=target_sid, turn_index=turn_index)# Step 2: Truncate history.json (local file operation)- rewind_result = rewind_session(session_id=target_sid, turn_index=turn_index)+ # "up_to" direction: keep messages from turn_index onward, summarize the prefix.+ # compact_partial_session handles this correctly (rewind_session only supports+ # the "from" direction — keeping the prefix and truncating the tail).+ if compact and direction == "up_to":+ from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session+ rewind_result = compact_partial_session(+ session_id=target_sid,+ turn_index=turn_index,+ direction="up_to",+ llm_summary=compact_summary,+ )+ else:+ rewind_result = rewind_session(session_id=target_sid, turn_index=turn_index)- # Step 3: Truncate context_engine in-place + persist to checkpointer+ # Step 3: Truncate context_engine in-place + persist to checkpointer.+ # rewind_session_context reads the already-truncated history.json and+ # converts ALL records to context messages, so it naturally produces the+ # correct result for both "from" and "up_to" directions.context_ok = Falsepair = self._resolve_rewind_agent(request.channel_id or "default")if pair is not None:@@ -2163,6 +2189,81 @@ class AgentWebSocketServer:payload["deleted_files"] = restore_result.get("deleted_files", [])payload["restore_errors"] = restore_result.get("errors", [])+ # Step 4: For compact mode, append boundary + rewind_summary + compact_summary records.+ # compact_partial_session already writes these for "up_to", so only append for "from".+ if compact and direction == "from":+ import uuid as _uuid+ import time as _time+ from jiuwenswarm.server.runtime.session.session_history import append_history_record+ request_id = str(_uuid.uuid4())+ now = _time.time()++ short_text = (+ f"Summarized {summarized_count} messages from this point."+ if direction == "from"+ else f"Summarized {summarized_count} messages up to this point."+ )++ append_history_record(+ session_id=target_sid,+ request_id=request_id,+ channel_id=request.channel_id or "tui",+ role="assistant",+ event_type="context.compact_boundary",+ content="Conversation compacted",+ timestamp=now,+ extra={+ "compact_metadata": {+ "trigger": "manual_rewind",+ "direction": direction,+ "turn_index": turn_index,+ "summarized_messages": summarized_count,+ },+ },+ )++ append_history_record(+ session_id=target_sid,+ request_id=request_id,+ channel_id=request.channel_id or "tui",+ role="assistant",+ event_type="context.rewind_summary",+ content=short_text,+ timestamp=now + 0.001,+ extra={+ "compact_metadata": {+ "trigger": "manual_rewind",+ "direction": direction,+ "turn_index": turn_index,+ "summarized_messages": summarized_count,+ },+ "is_compact_summary": True,+ },+ )++ if isinstance(compact_summary, str) and compact_summary.strip():+ append_history_record(+ session_id=target_sid,+ request_id=request_id,+ channel_id=request.channel_id or "tui",+ role="assistant",+ event_type="context.compact_summary",+ content=compact_summary.strip(),+ timestamp=now + 0.002,+ extra={+ "compact_metadata": {+ "trigger": "manual_rewind",+ "direction": direction,+ "turn_index": turn_index,+ "summarized_messages": summarized_count,+ },+ "is_compact_summary": True,+ "transcript_only": True,+ },+ )++ payload["summarized_messages"] = summarized_count+resp = AgentResponse(request_id=request.request_id,channel_id=request.channel_id,@@ -2715,6 +2816,55 @@ class AgentWebSocketServer:async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))+ async def _handle_command_compact_partial(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ try:+ session_id = request.session_id or "default"+ params = request.params or {}+ turn_index = int(params.get("turn_index", 0))+ direction = str(params.get("direction") or "from").strip()++ channel_id = request.channel_id or "default"+ mode, sub_mode, _ = resolve_agent_request_mode(params.get("mode", "agent.plan"))+ agent_mode = "agent" if mode == "auto_harness" else mode+ agent = await self._agent_manager.get_agent(+ channel_id=channel_id,+ mode=agent_mode,+ project_dir=resolve_request_project_dir(request),+ sub_mode=sub_mode,+ )++ if agent is None:+ raise ValueError("Failed to get agent")++ result_data = await agent.compact_partial(+ session_id=session_id,+ turn_index=turn_index,+ direction=direction,+ )++ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload=result_data,+ )+ except BaseException as e:+ if isinstance(e, (KeyboardInterrupt, asyncio.CancelledError)):+ raise+ logger.exception("[AgentWebSocketServer] command.compact_partial failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={+ "status": "failed",+ "error": str(e),+ },+ )+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))+async def _handle_command_context(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:try:session_id = request.session_id or "default"diff --git a/jiuwenswarm/server/runtime/agent_adapter/compact_partial_prompts.py b/jiuwenswarm/server/runtime/agent_adapter/compact_partial_prompts.pynew file mode 100644index 0000000000..b904246a1a--- /dev/null+++ b/jiuwenswarm/server/runtime/agent_adapter/compact_partial_prompts.py@@ -0,0 +1,201 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++""" /rewind summarize 的 partial compact prompt 模板 """++NO_TOOLS_PREAMBLE = (+ "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.\n\n"+ "- Do NOT use any tools whatsoever.\n"+ "- You already have all the context you need in the conversation above.\n"+ "- Tool calls will be REJECTED and will waste your only turn.\n"+ "- Your entire response must be plain text: an <analysis> block followed by a <summary> block.\n\n"+)++# 'from': model sees messages after the pivot (tail). Summary will follow retained prefix.+PARTIAL_COMPACT_PROMPT = (+ "Your task is to create a detailed summary of the RECENT portion "+ "of the conversation \u2014 the messages that follow earlier "+ "retained context. The earlier messages are being kept intact and "+ "do NOT need to be summarized. Focus your summary on what was "+ "discussed, learned, and accomplished in the recent messages only.\n"+ "\n"+ "Before providing your final summary, wrap your analysis in "+ "<analysis> tags to organize your thoughts. In your analysis "+ "process:\n"+ "1. Chronologically analyze each message and section. Thoroughly "+ "identify:\n"+ " - The user's explicit requests and intents\n"+ " - Your approach to addressing the user's requests\n"+ " - Key decisions, technical concepts and code patterns\n"+ " - Specific details like file names, code snippets, function "+ "signatures, file edits\n"+ " - Errors that you ran into and how you fixed them\n"+ " - Specific user feedback, especially if the user told you to "+ "do something differently\n"+ "2. Double-check for technical accuracy and completeness.\n"+ "\n"+ "Your summary should include the following sections:\n"+ "\n"+ "1. Primary Request and Intent: Capture the user's explicit "+ "requests and intents from the recent messages\n"+ "2. Key Technical Concepts: List important technical concepts, "+ "technologies, and frameworks discussed recently.\n"+ "3. Files and Code Sections: Enumerate specific files and code "+ "sections examined, modified, or created. Include full code "+ "snippets where applicable and include a summary of why this file "+ "read or edit is important.\n"+ "4. Errors and fixes: List errors encountered and how they were "+ "fixed.\n"+ "5. Problem Solving: Document problems solved and any ongoing "+ "troubleshooting efforts.\n"+ "6. All user messages: List ALL user messages from the recent "+ "portion that are not tool results.\n"+ "7. Pending Tasks: Outline any pending tasks from the recent "+ "messages.\n"+ "8. Current Work: Describe precisely what was being worked on "+ "immediately before this summary request.\n"+ "9. Optional Next Step: List the next step related to the most "+ "recent work. Include direct quotes from the most recent "+ "conversation.\n"+ "\n"+ "Here's an example of how your output should be structured:\n"+ "\n"+ "<example>\n"+ "<analysis>\n"+ "[Your thought process, ensuring all points are covered thoroughly "+ "and accurately]\n"+ "</analysis>\n"+ "\n"+ "<summary>\n"+ "1. Primary Request and Intent:\n"+ " [Detailed description]\n"+ "\n"+ "2. Key Technical Concepts:\n"+ " - [Concept 1]\n"+ " - [Concept 2]\n"+ "\n"+ "3. Files and Code Sections:\n"+ " - [File Name 1]\n"+ " - [Summary of why this file is important]\n"+ " - [Important Code Snippet]\n"+ "\n"+ "4. Errors and fixes:\n"+ " - [Error description]:\n"+ " - [How you fixed it]\n"+ "\n"+ "5. Problem Solving:\n"+ " [Description]\n"+ "\n"+ "6. All user messages:\n"+ " - [Detailed non tool use user message]\n"+ "\n"+ "7. Pending Tasks:\n"+ " - [Task 1]\n"+ "\n"+ "8. Current Work:\n"+ " [Precise description of current work]\n"+ "\n"+ "9. Optional Next Step:\n"+ " [Optional Next step to take]\n"+ "\n"+ "</summary>\n"+ "</example>\n"+ "\n"+ "Please provide your summary based on the RECENT messages only "+ "(after the retained earlier context), following this structure "+ "and ensuring precision and thoroughness in your response.\n"+)++# 'up_to': model sees messages before the pivot (prefix). Summary will precede kept recent messages.+PARTIAL_COMPACT_UP_TO_PROMPT = (+ "Your task is to create a detailed summary of this conversation. "+ "This summary will be placed at the start of a continuing session; "+ "newer messages that build on this context will follow after your "+ "summary (you do not see them here). Summarize thoroughly so that "+ "someone reading only your summary and then the newer messages can "+ "fully understand what happened and continue the work.\n"+ "\n"+ "Before providing your final summary, wrap your analysis in "+ "<analysis> tags to organize your thoughts. In your analysis "+ "process:\n"+ "1. Chronologically analyze each message and section. Thoroughly "+ "identify:\n"+ " - The user's explicit requests and intents\n"+ " - Your approach to addressing the user's requests\n"+ " - Key decisions, technical concepts and code patterns\n"+ " - Specific details like file names, code snippets, function "+ "signatures, file edits\n"+ " - Errors that you ran into and how you fixed them\n"+ " - Specific user feedback, especially if the user told you to "+ "do something differently\n"+ "2. Double-check for technical accuracy and completeness.\n"+ "\n"+ "Your summary should include the following sections:\n"+ "\n"+ "1. Primary Request and Intent: Capture the user's explicit "+ "requests and intents in detail\n"+ "2. Key Technical Concepts: List important technical concepts, "+ "technologies, and frameworks discussed.\n"+ "3. Files and Code Sections: Enumerate specific files and code "+ "sections examined, modified, or created. Include full code "+ "snippets where applicable and include a summary of why this file "+ "read or edit is important.\n"+ "4. Errors and fixes: List errors encountered and how they were "+ "fixed.\n"+ "5. Problem Solving: Document problems solved and any ongoing "+ "troubleshooting efforts.\n"+ "6. All user messages: List ALL user messages that are not tool "+ "results.\n"+ "7. Pending Tasks: Outline any pending tasks.\n"+ "8. Work Completed: Describe what was accomplished by the end of "+ "this portion.\n"+ "9. Context for Continuing Work: Summarize any context, decisions, "+ "or state that would be needed to understand and continue the work "+ "in subsequent messages.\n"+ "\n"+ "Here's an example of how your output should be structured:\n"+ "\n"+ "<example>\n"+ "<analysis>\n"+ "[Your thought process, ensuring all points are covered thoroughly "+ "and accurately]\n"+ "</analysis>\n"+ "\n"+ "<summary>\n"+ "1. Primary Request and Intent:\n"+ " [Detailed description]\n"+ "\n"+ "2. Key Technical Concepts:\n"+ " - [Concept 1]\n"+ " - [Concept 2]\n"+ "\n"+ "3. Files and Code Sections:\n"+ " - [File Name 1]\n"+ " - [Summary of why this file is important]\n"+ " - [Important Code Snippet]\n"+ "\n"+ "4. Errors and fixes:\n"+ " - [Error description]:\n"+ " - [How you fixed it]\n"+ "\n"+ "5. Problem Solving:\n"+ " [Description]\n"+ "\n"+ "6. All user messages:\n"+ " - [Detailed non tool use user message]\n"+ "\n"+ "7. Pending Tasks:\n"+ " - [Task 1]\n"+ "\n"+ "8. Work Completed:\n"+ " [What was accomplished]\n"+ "\n"+ "9. Context for Continuing Work:\n"+ " [Context needed to continue]\n"+ "\n"+ "</summary>\n"+ "</example>\n"+ "\n"+ "Please provide your summary based on the conversation, following "+ "this structure and ensuring precision and thoroughness in your "+ "response.\n"+)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex ff1b214da8..e2da5c3d12 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -1412,6 +1412,35 @@ class JiuWenSwarm:raise ValueError("Agent adapter not available")return await adapter.generate_recap(session_id=session_id)+ async def compact_partial(+ self,+ session_id: str,+ turn_index: int,+ direction: str = "from",+ ) -> dict[str, Any]:+ """部分对话压缩 — 对指定 turn 之前或之后的消息进行 LLM 摘要。++ Args:+ session_id: 会话ID+ turn_index: 基准 turn 号+ direction: "from" (摘要 turn 及之后) 或 "up_to" (摘要 turn 之前)++ Returns:+ 包含压缩结果的字典:+ - status: "ok" | "no_turn" | "failed"+ - summary: 摘要文本(仅当 status == "ok" 时)+ - summarized_count: 被摘要的消息数+ - error: 错误信息(仅当 status == "failed" 时)+ """+ adapter = self._adapter+ if adapter is None:+ raise ValueError("Agent adapter not available")+ return await adapter.compact_partial(+ session_id=session_id,+ turn_index=turn_index,+ direction=direction,+ )+# ---------- 资源清理 ----------async def cancel_inflight_work(self, log_prefix: str = "[gateway disconnect] ") -> None:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex c6429dfeeb..ecb5151f62 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -6430,6 +6430,132 @@ class JiuWenSwarmDeepAdapter:return outputreturn str(result) if result is not None else None+ async def compact_partial(+ self,+ session_id: str,+ turn_index: int,+ direction: str = "from",+ ) -> dict[str, Any]:+ """部分对话压缩 — /rewind summarize from here 的核心实现。++ 从 history.json 读取消息,找到指定 turn 的 pivot 位置,将对应范围的消息+ 发送给 LLM 生成结构化摘要(9 节:Primary Request, Technical Concepts,+ Files, Errors, Problem Solving, User Messages, Pending Tasks,+ Current Work, Optional Next Step)。++ Args:+ session_id: 会话ID+ turn_index: 基准 turn 号(1-based)+ direction: "from" (摘要 turn 及之后) 或 "up_to" (摘要 turn 之前)++ Returns:+ - status: "ok" | "no_turn" | "failed"+ - summary: 摘要文本+ - summarized_count: 被摘要的消息 record 数+ """+ from jiuwenswarm.agents.harness.common.session_ops_service import (+ get_agent_sessions_dir,+ )+ from jiuwenswarm.server.runtime.session.session_history import _read_history+ from jiuwenswarm.server.runtime.agent_adapter.compact_partial_prompts import (+ NO_TOOLS_PREAMBLE,+ PARTIAL_COMPACT_PROMPT,+ PARTIAL_COMPACT_UP_TO_PROMPT,+ )++ sessions_dir = get_agent_sessions_dir()+ history_path = sessions_dir / session_id / "history.json"+ history = _read_history(history_path)+ if not history:+ return {"status": "no_turn"}++ user_positions = []+ for i, record in enumerate(history):+ if record.get("role") == "user":+ user_positions.append(i)++ total_turns = len(user_positions)+ if total_turns == 0 or turn_index > total_turns:+ return {"status": "no_turn"}++ pivot_idx = user_positions[turn_index - 1]++ if direction == "from":+ messages_to_summarize = history[pivot_idx:]+ elif direction == "up_to":+ messages_to_summarize = history[:pivot_idx]+ else:+ return {"status": "failed", "error": f"unknown direction: {direction}"}++ if not messages_to_summarize:+ return {"status": "no_turn"}++ summarized_count = len(messages_to_summarize)++ prompt = (+ NO_TOOLS_PREAMBLE + PARTIAL_COMPACT_UP_TO_PROMPT+ if direction == "up_to"+ else NO_TOOLS_PREAMBLE + PARTIAL_COMPACT_PROMPT+ )++ recap_messages = self._build_messages_for_model(messages_to_summarize)+ if not recap_messages:+ return {"status": "no_turn"}++ # Add the prompt as the final user message+ from openjiuwen.core.foundation.llm.schema.message import UserMessage+ recap_messages.append(UserMessage(content=prompt))++ try:+ result = await self._model.invoke(recap_messages, temperature=0)+ raw = getattr(result, "content", None) or str(result)+ except Exception:+ logger.exception("[compact_partial] model call failed")+ return {"status": "failed", "error": "Model call failed"}++ summary = raw if isinstance(raw, str) else str(raw)+ if not summary.strip():+ return {"status": "failed", "error": "Model returned empty response"}++ # Strip <analysis> block to get clean summary+ import re+ cleaned = re.sub(r"<analysis>.*?</analysis>", "", summary, flags=re.DOTALL).strip()++ return {+ "status": "ok",+ "summary": cleaned or summary.strip(),+ "summarized_count": summarized_count,+ }++ @staticmethod+ def _build_messages_for_model(records: list[dict[str, Any]]) -> list[Any]:+ from openjiuwen.core.foundation.llm.schema.message import UserMessage, AssistantMessage++ messages: list[Any] = []+ for rec in records:+ if not isinstance(rec, dict):+ continue+ role = rec.get("role")+ content = rec.get("content")+ if not isinstance(content, str) or not content.strip():+ continue++ event_type = rec.get("event_type")+ # skip tool call/result records — they contain JSON blobs, not useful for summary+ if role == "user":+ # strip file-content blocks to save tokens+ import re+ cleaned = re.sub(r"<file-content[^>]*>.*?</file-content>", "", content, flags=re.DOTALL).strip()+ if cleaned:+ messages.append(UserMessage(content=cleaned))+ elif role == "assistant":+ if event_type in ("chat.final", "context.compact_summary", "context.rewind_summary") or not event_type:+ if event_type in ("context.compact_boundary",):+ continue+ messages.append(AssistantMessage(content=content))++ return messages+async def _count_full_context_tokens(self,context: Any,diff --git a/tests/unit_tests/test_compact_partial.py b/tests/unit_tests/test_compact_partial.pynew file mode 100644index 0000000000..8ea176235f--- /dev/null+++ b/tests/unit_tests/test_compact_partial.py@@ -0,0 +1,570 @@+from __future__ import annotations++import json+import time+from pathlib import Path+from unittest.mock import patch++import pytest+++# ---------------------------------------------------------------------------+# helpers+# ---------------------------------------------------------------------------+def _write_history(path: Path, records: list[dict]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(records, ensure_ascii=False, indent=2), encoding="utf-8")+++def _read_history(path: Path) -> list[dict]:+ deadline = time.time() + 5+ while time.time() < deadline:+ if path.exists():+ data = json.loads(path.read_text(encoding="utf-8"))+ if data:+ return data+ time.sleep(0.05)+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else []+++def _make_user_record(index: int, content: str | None = None, ts: float | None = None) -> dict:+ content = content or f"user message {index}"+ return {+ "id": f"u{index}",+ "role": "user",+ "content": content,+ "request_id": f"r{index}",+ "timestamp": ts if ts is not None else float(index),+ }+++def _make_assistant_record(+ index: int,+ content: str | None = None,+ event_type: str | None = None,+ ts: float | None = None,+) -> dict:+ content = content or f"assistant response {index}"+ return {+ "id": f"a{index}",+ "role": "assistant",+ "content": content,+ "request_id": f"r{index}",+ "timestamp": ts if ts is not None else float(index) + 0.5,+ "event_type": event_type,+ }+++# ---------------------------------------------------------------------------+# compact_partial_session tests+# ---------------------------------------------------------------------------+def _setup_compact_patches(monkeypatch, tmp_path):+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.session_history.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.session_metadata.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.session.session_metadata._enqueue_write",+ lambda *args, **kwargs: None,+ )+++# ---------------------------------------------------------------------------+# compact_partial_session tests+# ---------------------------------------------------------------------------+class TestCompactPartialSessionFrom:+ @staticmethod+ def test_compact_from_direction_truncates_history(tmp_path, monkeypatch):+ _setup_compact_patches(monkeypatch, tmp_path)++ records = [+ _make_user_record(1, "first question"),+ _make_assistant_record(1, "first answer"),+ _make_user_record(2, "second question"),+ _make_assistant_record(2, "second answer"),+ _make_user_record(3, "third question"),+ _make_assistant_record(3, "third answer"),+ ]+ _write_history(tmp_path / "s1" / "history.json", records)++ from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session++ result = compact_partial_session(session_id="s1", turn_index=2, direction="from")++ assert result["direction"] == "from"+ assert result["turn_index"] == 2+ assert result["summarized_messages"] == 4+ assert result["removed_records"] == 4+ assert "second question" in result["content"]++ final_history = _read_history(tmp_path / "s1" / "history.json")+ event_types = [r.get("event_type") for r in final_history]+ assert "context.compact_boundary" in event_types+ assert "context.rewind_summary" in event_types++ @staticmethod+ def test_compact_from_with_llm_summary(tmp_path, monkeypatch):+ _setup_compact_patches(monkeypatch, tmp_path)++ records = [+ _make_user_record(1, "hello"),+ _make_assistant_record(1, "hi there"),+ ]+ _write_history(tmp_path / "s2" / "history.json", records)++ from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session++ result = compact_partial_session(+ session_id="s2",+ turn_index=1,+ direction="from",+ llm_summary="LLM generated summary text",+ )++ final_history = _read_history(tmp_path / "s2" / "history.json")+ event_types = [r.get("event_type") for r in final_history]+ assert event_types == [+ "context.compact_boundary",+ "context.rewind_summary",+ "context.compact_summary",+ ]+ compact_entry = final_history[2]+ assert compact_entry["content"] == "LLM generated summary text"+ assert compact_entry["is_compact_summary"] is True+ assert compact_entry["transcript_only"] is True+++class TestCompactPartialSessionUpTo:+ @staticmethod+ def test_compact_up_to_direction_keeps_later_turns(tmp_path, monkeypatch):+ _setup_compact_patches(monkeypatch, tmp_path)++ records = [+ _make_user_record(1, "first question"),+ _make_assistant_record(1, "first answer"),+ _make_user_record(2, "second question"),+ _make_assistant_record(2, "second answer"),+ _make_user_record(3, "third question"),+ _make_assistant_record(3, "third answer"),+ ]+ _write_history(tmp_path / "s3" / "history.json", records)++ from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session++ result = compact_partial_session(session_id="s3", turn_index=3, direction="up_to")++ assert result["direction"] == "up_to"+ assert result["removed_records"] == 4+ assert result["summarized_messages"] == 4+ assert "third question" in result["content"]++ final_history = _read_history(tmp_path / "s3" / "history.json")+ event_types = [r.get("event_type") for r in final_history]+ assert "context.compact_boundary" in event_types+ assert "context.rewind_summary" in event_types+++class TestCompactPartialSessionErrors:+ @staticmethod+ def test_raises_on_invalid_turn_index(tmp_path, monkeypatch):+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ records = [+ _make_user_record(1, "hello"),+ _make_assistant_record(1, "hi"),+ ]+ _write_history(tmp_path / "s4" / "history.json", records)++ from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session++ with pytest.raises(ValueError, match="turn_index must be >= 1"):+ compact_partial_session(session_id="s4", turn_index=0, direction="from")++ with pytest.raises(ValueError, match="exceeds total turns"):+ compact_partial_session(session_id="s4", turn_index=99, direction="from")++ @staticmethod+ def test_raises_on_missing_history(tmp_path, monkeypatch):+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session++ with pytest.raises(ValueError, match="session history not found"):+ compact_partial_session(session_id="no_such", turn_index=1, direction="from")++ @staticmethod+ def test_raises_on_no_user_messages(tmp_path, monkeypatch):+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ records = [+ {+ "id": "a1",+ "role": "assistant",+ "content": "only assistant",+ "request_id": "r1",+ "timestamp": 1.0,+ },+ ]+ _write_history(tmp_path / "s5" / "history.json", records)++ from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session++ with pytest.raises(ValueError, match="no user messages"):+ compact_partial_session(session_id="s5", turn_index=1, direction="from")++ @staticmethod+ def test_raises_on_unknown_direction(tmp_path, monkeypatch):+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ records = [+ _make_user_record(1, "hello"),+ _make_assistant_record(1, "hi"),+ ]+ _write_history(tmp_path / "s6" / "history.json", records)++ from jiuwenswarm.agents.harness.common.session_ops_service import compact_partial_session++ with pytest.raises(ValueError, match="unknown direction"):+ compact_partial_session(session_id="s6", turn_index=1, direction="bad")+++# ---------------------------------------------------------------------------+# _build_messages_for_model tests+# ---------------------------------------------------------------------------+class TestBuildMessagesForModel:+ @staticmethod+ def test_filters_system_and_tool_records():+ records = [+ {"role": "system", "content": "system prompt"},+ {"role": "user", "content": "user query"},+ {"role": "assistant", "content": "assistant reply", "event_type": "chat.final"},+ {"role": "tool", "content": '{"result": "ok"}'},+ ]+ result = _build_model_messages(records)++ assert len(result) == 2+ assert result[0].content == "user query"+ assert result[1].content == "assistant reply"++ @staticmethod+ def test_skips_tool_call_event_types():+ records = [+ {"role": "user", "content": "do something"},+ {"role": "assistant", "content": "calling tool", "event_type": "chat.tool_call"},+ {"role": "assistant", "content": "final answer", "event_type": "chat.final"},+ ]+ result = _build_model_messages(records)++ assert len(result) == 2+ assert result[0].content == "do something"+ assert result[1].content == "final answer"++ @staticmethod+ def test_strips_file_content_blocks():+ records = [+ {+ "role": "user",+ "content": "Look at this file\n<file-content path='x.py'>code here</file-content>\nWhat do you think?",+ },+ ]+ result = _build_model_messages(records)++ assert len(result) == 1+ assert "<file-content" not in result[0].content+ assert "Look at this file" in result[0].content+ assert "What do you think?" in result[0].content++ @staticmethod+ def test_skips_empty_content():+ records = [+ {"role": "user", "content": ""},+ {"role": "user", "content": " "},+ {"role": "user", "content": "actual message"},+ ]+ result = _build_model_messages(records)++ assert len(result) == 1+ assert result[0].content == "actual message"++ @staticmethod+ def test_includes_compact_and_rewind_summary_events():+ records = [+ {"role": "user", "content": "start"},+ {"role": "assistant", "content": "compact summary", "event_type": "context.compact_summary"},+ {"role": "assistant", "content": "rewind summary", "event_type": "context.rewind_summary"},+ ]+ result = _build_model_messages(records)++ assert len(result) == 3+ assert result[1].content == "compact summary"+ assert result[2].content == "rewind summary"++ @staticmethod+ def test_skips_compact_boundary_events():+ records = [+ {"role": "user", "content": "before compact"},+ {"role": "assistant", "content": "Conversation compacted", "event_type": "context.compact_boundary"},+ {"role": "user", "content": "after compact"},+ ]+ result = _build_model_messages(records)++ assert len(result) == 2+ contents = [m.content for m in result]+ assert "Conversation compacted" not in contents++ @staticmethod+ def test_skips_non_dict_records():+ records = [+ "not a dict",+ {"role": "user", "content": "valid message"},+ ]+ result = _build_model_messages(records)++ assert len(result) == 1+ assert result[0].content == "valid message"+++def _build_model_messages(records):+ from openjiuwen.core.foundation.llm.schema.message import UserMessage, AssistantMessage++ messages = []+ for rec in records:+ if not isinstance(rec, dict):+ continue+ role = rec.get("role")+ content = rec.get("content")+ if not isinstance(content, str) or not content.strip():+ continue++ event_type = rec.get("event_type")+ if role == "user":+ import re+ cleaned = re.sub(r"<file-content[^>]*>.*?</file-content>", "", content, flags=re.DOTALL).strip()+ if cleaned:+ messages.append(UserMessage(content=cleaned))+ elif role == "assistant":+ if event_type in ("chat.final", "context.compact_summary", "context.rewind_summary") or not event_type:+ if event_type in ("context.compact_boundary",):+ continue+ messages.append(AssistantMessage(content=content))++ return messages+++# ---------------------------------------------------------------------------+# compact_partial_prompts tests+# ---------------------------------------------------------------------------+class TestCompactPartialPrompts:+ @staticmethod+ def test_no_tools_preamble_contains_critical():+ from jiuwenswarm.server.runtime.agent_adapter.compact_partial_prompts import NO_TOOLS_PREAMBLE++ assert "CRITICAL" in NO_TOOLS_PREAMBLE+ assert "Do NOT call any tools" in NO_TOOLS_PREAMBLE+ assert "<analysis>" in NO_TOOLS_PREAMBLE++ @staticmethod+ def test_partial_compact_prompt_has_required_sections():+ from jiuwenswarm.server.runtime.agent_adapter.compact_partial_prompts import PARTIAL_COMPACT_PROMPT++ assert "Primary Request and Intent" in PARTIAL_COMPACT_PROMPT+ assert "Key Technical Concepts" in PARTIAL_COMPACT_PROMPT+ assert "Files and Code Sections" in PARTIAL_COMPACT_PROMPT+ assert "Errors and fixes" in PARTIAL_COMPACT_PROMPT+ assert "Problem Solving" in PARTIAL_COMPACT_PROMPT+ assert "All user messages" in PARTIAL_COMPACT_PROMPT+ assert "Pending Tasks" in PARTIAL_COMPACT_PROMPT+ assert "Current Work" in PARTIAL_COMPACT_PROMPT+ assert "Optional Next Step" in PARTIAL_COMPACT_PROMPT++ @staticmethod+ def test_partial_compact_up_to_prompt_has_required_sections():+ from jiuwenswarm.server.runtime.agent_adapter.compact_partial_prompts import PARTIAL_COMPACT_UP_TO_PROMPT++ assert "Primary Request and Intent" in PARTIAL_COMPACT_UP_TO_PROMPT+ assert "Key Technical Concepts" in PARTIAL_COMPACT_UP_TO_PROMPT+ assert "Files and Code Sections" in PARTIAL_COMPACT_UP_TO_PROMPT+ assert "Errors and fixes" in PARTIAL_COMPACT_UP_TO_PROMPT+ assert "Problem Solving" in PARTIAL_COMPACT_UP_TO_PROMPT+ assert "All user messages" in PARTIAL_COMPACT_UP_TO_PROMPT+ assert "Pending Tasks" in PARTIAL_COMPACT_UP_TO_PROMPT+ assert "Work Completed" in PARTIAL_COMPACT_UP_TO_PROMPT+ assert "Context for Continuing Work" in PARTIAL_COMPACT_UP_TO_PROMPT++ @staticmethod+ def test_prompt_strings_are_not_empty():+ from jiuwenswarm.server.runtime.agent_adapter.compact_partial_prompts import (+ NO_TOOLS_PREAMBLE,+ PARTIAL_COMPACT_PROMPT,+ PARTIAL_COMPACT_UP_TO_PROMPT,+ )+ assert len(NO_TOOLS_PREAMBLE.strip()) > 0+ assert len(PARTIAL_COMPACT_PROMPT.strip()) > 0+ assert len(PARTIAL_COMPACT_UP_TO_PROMPT.strip()) > 0+++# ---------------------------------------------------------------------------+# rewind_session_context with compact_summary / rewind_summary injection+# ---------------------------------------------------------------------------+class TestRewindSessionContextInjectsSummaries:+ @pytest.mark.asyncio+ async def test_compact_summary_injected_as_user_message(self, tmp_path, monkeypatch):+ sessions_dir = tmp_path / "sessions"+ sessions_dir.mkdir()++ history = [+ {+ "role": "user", "id": "u1", "request_id": "r1",+ "content": "first question", "timestamp": 1.0,+ },+ {+ "role": "assistant", "content": "first answer",+ "event_type": "chat.final", "timestamp": 1.5,+ },+ {+ "role": "assistant", "content": "Conversation compacted",+ "event_type": "context.compact_boundary", "timestamp": 2.0,+ },+ {+ "role": "assistant",+ "content": "Summarized 2 messages from this point.",+ "event_type": "context.rewind_summary", "timestamp": 2.001,+ },+ {+ "role": "assistant",+ "content": "LLM summary: user asked a question and got an answer.",+ "event_type": "context.compact_summary", "timestamp": 2.002,+ },+ ]+ _write_history(sessions_dir / "s1" / "history.json", history)++ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",+ lambda: sessions_dir,+ )++ from unittest.mock import AsyncMock, MagicMock++ mock_context_engine = MagicMock()+ mock_context_engine.get_context.return_value = None+ mock_context_engine.clear_context = AsyncMock()+ mock_context_engine.create_context = AsyncMock()+ mock_context_engine.save_contexts = AsyncMock()++ mock_react_agent = MagicMock()+ mock_react_agent.context_engine = mock_context_engine++ mock_session = MagicMock()+ mock_session.pre_run = AsyncMock()+ mock_session.post_run = AsyncMock()+ mock_session.update_state = MagicMock()++ mock_deep_agent = MagicMock()+ mock_deep_agent.react_agent = mock_react_agent+ mock_deep_agent.card = MagicMock()+ mock_deep_agent.save_state = MagicMock()++ with patch(+ "openjiuwen.core.single_agent.create_agent_session",+ return_value=mock_session,+ ):+ from jiuwenswarm.agents.harness.common.session_ops_service import rewind_session_context++ result = await rewind_session_context(+ deep_agent=mock_deep_agent,+ session_id="s1",+ turn_index=1,+ )++ assert result is True+ mock_context_engine.create_context.assert_called_once()+ _, kwargs = mock_context_engine.create_context.call_args+ history_messages = kwargs["history_messages"]+ from openjiuwen.core.foundation.llm.schema.message import UserMessage+ user_contents = [m.content for m in history_messages if isinstance(m, UserMessage)]+ assert "LLM summary: user asked a question and got an answer." in user_contents+ assert "Summarized 2 messages from this point." in user_contents++ @pytest.mark.asyncio+ async def test_rewind_summary_without_compact_summary(self, tmp_path, monkeypatch):+ sessions_dir = tmp_path / "sessions"+ sessions_dir.mkdir()++ history = [+ {+ "role": "user", "id": "u1", "request_id": "r1",+ "content": "hello world", "timestamp": 1.0,+ },+ {+ "role": "assistant", "content": "hi there",+ "event_type": "chat.final", "timestamp": 1.5,+ },+ {+ "role": "assistant",+ "content": "Summarized 2 messages up to this point.",+ "event_type": "context.rewind_summary", "timestamp": 2.0,+ },+ ]+ _write_history(sessions_dir / "s2" / "history.json", history)++ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.session_ops_service.get_agent_sessions_dir",+ lambda: sessions_dir,+ )++ from unittest.mock import AsyncMock, MagicMock++ mock_context_engine = MagicMock()+ mock_context_engine.get_context.return_value = None+ mock_context_engine.clear_context = AsyncMock()+ mock_context_engine.create_context = AsyncMock()+ mock_context_engine.save_contexts = AsyncMock()++ mock_react_agent = MagicMock()+ mock_react_agent.context_engine = mock_context_engine++ mock_session = MagicMock()+ mock_session.pre_run = AsyncMock()+ mock_session.post_run = AsyncMock()+ mock_session.update_state = MagicMock()++ mock_deep_agent = MagicMock()+ mock_deep_agent.react_agent = mock_react_agent+ mock_deep_agent.card = MagicMock()+ mock_deep_agent.save_state = MagicMock()++ with patch(+ "openjiuwen.core.single_agent.create_agent_session",+ return_value=mock_session,+ ):+ from jiuwenswarm.agents.harness.common.session_ops_service import rewind_session_context++ result = await rewind_session_context(+ deep_agent=mock_deep_agent,+ session_id="s2",+ turn_index=1,+ )++ assert result is True+ mock_context_engine.create_context.assert_called_once()+ _, kwargs = mock_context_engine.create_context.call_args+ history_messages = kwargs["history_messages"]+ from openjiuwen.core.foundation.llm.schema.message import UserMessage+ user_contents = [m.content for m in history_messages if isinstance(m, UserMessage)]+ assert "Summarized 2 messages up to this point." in user_contents