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(auto-harness): 文档补齐&tui显示调整及任务管理问题修复
ray_le650b43c50b04
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.mdindex dcf98b0cb5..b2bcfc1bbf 100644--- a/docs/en/SlashCommands.md+++ b/docs/en/SlashCommands.md@@ -32,6 +32,7 @@ Executed locally in the terminal UI, not through Gateway control pipeline.| `/evolve_simplify` | Simplify and consolidate one skill's evolution records (see below) || `/evolve_rebuild` | Rebuild `SKILL.md` from archives and evolution records (see below) || `/sandbox` | Set sandbox mode (see below) |+| `/auto-harness` | Auto-Harness task management (`run`/`schedule`, see below) |> Note: `/mode` controlled switching logic is primarily on Gateway side, see "`/mode` and `/switch`" below.@@ -691,6 +692,75 @@ Use the following template to write commands. `input=$(cat)` reads JSON into a v}```+### `/auto-harness` (Auto-Harness Task Management)++Manage Auto-Harness task creation, execution, and monitoring. Auto-Harness generates harness extension packages via automated pipelines, supporting two pipeline types:++- **optimize_expert_harness** (backend value `extended_evolve_pipeline`): Generate a local harness extension package+- **optimize_meta_harness** (backend value `meta_evolve_pipeline`): Submit PR (requires git config)++During pipeline execution, extension packages are **activated automatically by default** — no manual user confirmation is needed. Logs display `harness.extension_ready` (extension ready, showing directory and component info) and `harness.activate_interaction` (activation confirmation prompt) events.++#### Configuration Requirements++Using the `optimize_meta_harness` pipeline requires the following fields to be configured (via `/config edit` or `/status config`):++| Field | Required | Description |+|---|---|---|+| `git.user_name` | Yes | Git commit username |+| `git.user_email` | Yes | Git commit email |+| `git.fork_owner` | Yes | Fork repository owner (e.g., `SnapeK`) |+| `gitcode.access_token` | No | GitCode API token (can also be provided via environment variable `GITCODE_ACCESS_TOKEN`) |++If configuration is incomplete, the task creation will prompt the missing fields.++#### Subcommands++| Command | Description |+|---|---|+| `/auto-harness run [--pipeline <pipeline>] <query>` | Execute a one-time Auto-Harness task |+| `/auto-harness schedule start --interval <hours> [--pipeline <pipeline>] <query>` | Create a scheduled task |+| `/auto-harness schedule list` | List all tasks |+| `/auto-harness schedule status <task_id>` | View task details |+| `/auto-harness schedule logs <task_id> [--history <n>]` | View task execution logs |+| `/auto-harness schedule cancel <task_id>` | Cancel a task |+| `/auto-harness schedule delete <task_id>` | Delete a task |++#### `/auto-harness run` (One-time Execution)++- Usage: `/auto-harness run [--pipeline <pipeline>] <query>`+- Flow:+ 1. If pipeline is not specified, interactively select the pipeline type+ 2. If `optimize_meta_harness` is selected, automatically check git config completeness+ 3. Create and execute a one-time task+ 4. Automatically enter real-time log streaming mode (similar to `tail -f`)+- Examples:+ - `/auto-harness run Optimize database query performance` — No pipeline specified, interactive selection+ - `/auto-harness run --pipeline optimize_expert_harness Optimize context compression` — Specify pipeline++#### `/auto-harness schedule start` (Create Scheduled Task)++- Usage: `/auto-harness schedule start --interval <hours> [--pipeline <pipeline>] <query>`+- Parameters:+ - `--interval` / `-i` (required): Execution interval in hours; options: `1`, `2`, `4`, `8`, `12`, `24`+ - `--pipeline` / `-p` (optional): Pipeline type; interactively selected if not specified+ - `<query>` (required): Optimization target description+- Flow:+ 1. If pipeline is not specified, interactively select+ 2. If `optimize_meta_harness` is selected, check git config+ 3. Interactively confirm whether to run immediately+ 4. Create the scheduled task+- Examples:+ - `/auto-harness schedule start --interval 4 Optimize context compression`+ - `/auto-harness schedule start -i 2 -p optimize_meta_harness Submit database optimization PR`++#### `/auto-harness schedule logs` (View Execution Logs)++- Usage: `/auto-harness schedule logs <task_id> [--history <n>]`+- Modes:+ - Default: Stream current running logs in real-time (`tail -f` mode); Ctrl+C to interrupt+ - `--history <n>`: View historical execution logs (`view` mode, `n` is the history index, 0 = most recent)+---## Planned Featuresdiff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"index 877a257b14..fc4ed02799 100644--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"@@ -32,6 +32,7 @@| `/evolve_simplify` | 整理、合并某个 Skill 的演进经验(见下文) || `/evolve_rebuild` | 基于归档与演进记录重建 `SKILL.md`(见下文) || `/sandbox` | 设置沙箱模式(见下文) |+| `/auto-harness` | Auto-Harness 任务管理(`run`/`schedule`,见下文) |> 说明:`/mode` 的受控切换逻辑以 Gateway 侧行为为主,详见下文「`/mode` 与 `/switch`」。@@ -702,6 +703,75 @@}```+### `/auto-harness`(Auto-Harness 任务管理)++管理 Auto-Harness 任务的创建、执行与监控。Auto-Harness 通过自动化 Pipeline 生成 harness 扩展包,支持两种 Pipeline 类型:++- **optimize_expert_harness**(后端值 `extended_evolve_pipeline`):生成本地 harness 扩展包+- **optimize_meta_harness**(后端值 `meta_evolve_pipeline`):提交 PR(需配置 git)++Pipeline 执行过程中,扩展包**默认自动激活生效**,无需用户手动确认。日志中会展示 `harness.extension_ready`(扩展已就绪,显示目录与组件信息)和 `harness.activate_interaction`(激活确认提示)事件。++#### 配置要求++使用 `optimize_meta_harness` Pipeline 需配置以下字段(通过 `/config edit` 或 `/status config` 编辑):++| 字段 | 必填 | 说明 |+|---|---|---|+| `git.user_name` | 是 | Git commit 用户名 |+| `git.user_email` | 是 | Git commit 箱 |+| `git.fork_owner` | 是 | Fork 仓库所有者(如 `SnapeK`) |+| `gitcode.access_token` | 否 | GitCode API Token(也可通过环境变量 `GITCODE_ACCESS_TOKEN` 提供) |++若配置不完整,创建任务时会提示缺失字段。++#### 子命令++| 命令 | 说明 |+|---|---|+| `/auto-harness run [--pipeline <pipeline>] <query>` | 执行一次性 Auto-Harness 任务 |+| `/auto-harness schedule start --interval <hours> [--pipeline <pipeline>] <query>` | 创建定时任务 |+| `/auto-harness schedule list` | 列出所有任务 |+| `/auto-harness schedule status <task_id>` | 查看任务详情 |+| `/auto-harness schedule logs <task_id> [--history <n>]` | 查看任务执行日志 |+| `/auto-harness schedule cancel <task_id>` | 取消任务 |+| `/auto-harness schedule delete <task_id>` | 删除任务 |++#### `/auto-harness run`(一次性执行)++- 用法:`/auto-harness run [--pipeline <pipeline>] <query>`+- 流程:+ 1. 若未指定 pipeline,交互式选择 Pipeline 类型+ 2. 若选择 `optimize_meta_harness`,自动检查 git 配置是否完整+ 3. 创建并执行一次性任务+ 4. 自动进入实时日志跟踪模式(类似 `tail -f`)+- 示例:+ - `/auto-harness run 优化数据库查询性能` — 未指定 pipeline,交互选择+ - `/auto-harness run --pipeline optimize_expert_harness 优化上下文压缩能力` — 指定 pipeline++#### `/auto-harness schedule start`(创建定时任务)++- 用法:`/auto-harness schedule start --interval <hours> [--pipeline <pipeline>] <query>`+- 参数:+ - `--interval` / `-i`(必填):执行间隔(小时),可选值 `1`、`2`、`4`、`8`、`12`、`24`+ - `--pipeline` / `-p`(可选):Pipeline 类型,未指定时交互选择+ - `<query>`(必填):优化目标描述+- 流程:+ 1. 若未指定 pipeline,交互式选择+ 2. 若选择 `optimize_meta_harness`,检查 git 配置+ 3. 交互确认是否立即执行一次+ 4. 创建定时任务+- 示例:+ - `/auto-harness schedule start --interval 4 优化上下文压缩能力`+ - `/auto-harness schedule start -i 2 -p optimize_meta_harness 提交数据库优化PR`++#### `/auto-harness schedule logs`(查看执行日志)++- 用法:`/auto-harness schedule logs <task_id> [--history <n>]`+- 模式:+ - 默认:实时跟踪当前运行日志(`tail -f` 模式),支持 Ctrl+C 中断+ - `--history <n>`:查看历史执行日志(`view` 模式,`n` 为历史索引,0 为最近一次)+---## 待开发diff --git a/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py b/jiuwenswarm/agents/harness/common/auto_harness/scheduler.pyindex 0f0a7c1b6e..af42049d71 100644--- a/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py+++ b/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py@@ -10,6 +10,7 @@ import jsonimport loggingimport uuidfrom datetime import datetime, timezone, timedelta+from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Optionalfrom openjiuwen.auto_harness.pipelines import META_EVOLVE_PIPELINE@@ -22,6 +23,61 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+_TOLERANT_STAGES = {"build_verify"}+++def _sync_append_log(log_path: Path, line: str) -> None:+ """Synchronous append+flush for log file — called via asyncio.to_thread."""+ with log_path.open("a", encoding="utf-8") as f:+ f.write(line)+ f.flush()+++def _determine_pipeline_status_from_log(log_path) -> dict[str, Any]:+ """Parse a JSON Lines log file and determine whether the pipeline succeeded.++ Rules:+ - Each stage has a harness.stage_result event with scope="" (stage-level).+ - All stages except those in _TOLERANT_STAGES must have status="success".+ - Tolerant stages (build_verify) accept either "success" or "failed".++ Returns:+ {"failed": bool, "error": str}+ """+ pipeline_stages: list[str] = []+ stage_results: dict[str, str] = {}++ try:+ with log_path.open("r", encoding="utf-8") as lf:+ for line in lf:+ try:+ entry = json.loads(line)+ except json.JSONDecodeError:+ continue+ if entry.get("event_type") == "harness.message" and entry.get("stages") and entry.get("pipeline"):+ pipeline_stages = [s.get("slot") for s in entry["stages"]]+ if entry.get("event_type") == "harness.stage_result" and not entry.get("scope"):+ slot = entry.get("stage")+ status = entry.get("status")+ if slot:+ stage_results[slot] = status+ except Exception as exc:+ logger.warning("[Scheduler] Failed to read log %s: %s", log_path, exc)+ return {"failed": False, "error": ""}++ for slot in pipeline_stages:+ result = stage_results.get(slot)+ if slot in _TOLERANT_STAGES:+ continue+ if result != "success":+ return {+ "failed": True,+ "error": f"Stage '{slot}' {stage_results.get(slot, 'not completed')}",+ }++ return {"failed": False, "error": ""}++class Scheduler:"""Async scheduler that triggers scheduled auto_harness tasks.@@ -204,7 +260,7 @@ class Scheduler:if not started_at_str:started_at_str = completed_at.isoformat()- self._task_store.add_execution_record(task_id, {+ await self._task_store.add_execution_record(task_id, {"execution_id": execution_id,"started_at": started_at_str,"completed_at": completed_at.isoformat(),@@ -214,7 +270,7 @@ class Scheduler:})# Update task status to cancelled- self._task_store.update_task(task_id, {+ await self._task_store.update_task(task_id, {"status": "cancelled","current_execution_id": None,})@@ -295,7 +351,7 @@ class Scheduler:session_id = f"sched_{task_id}_{execution_id}"# Update status to running- self._task_store.update_task(task_id, {+ await self._task_store.update_task(task_id, {"status": "running","current_execution_id": execution_id,})@@ -305,11 +361,7 @@ class Scheduler:final_status = "success"error_msg = ""- # Open log file for appending (JSON Lines format)- log_file = None-try:- log_file = log_path.open("a", encoding="utf-8")# Agent should already be set on service by the request handler# (similar to how _handle_command_compact works)logger.info(@@ -351,9 +403,9 @@ class Scheduler:event_type = chunk.payload.get("event_type", "")if event_type in ("context.usage", "context.compression_state"):continue- # Append log chunk immediately (JSON Lines format)- log_file.write(json.dumps(chunk.payload, ensure_ascii=False) + "\n")- log_file.flush()+ # Append log chunk via thread pool (avoids blocking event loop)+ line = json.dumps(chunk.payload, ensure_ascii=False) + "\n"+ await asyncio.to_thread(_sync_append_log, log_path, line)logger.info("[Scheduler] Task %s execution %s completed successfully",@@ -370,13 +422,15 @@ class Scheduler:logger.exception("[Scheduler] Task %s execution %s failed: %s", task_id, execution_id, e)finally:- # Close log file- if log_file:- log_file.close()+ if final_status == "success" and log_path.exists():+ result = _determine_pipeline_status_from_log(log_path)+ if result["failed"]:+ final_status = "failed"+ error_msg = result["error"]# Record executioncompleted_at = datetime.now(timezone.utc)- self._task_store.add_execution_record(task_id, {+ await self._task_store.add_execution_record(task_id, {"execution_id": execution_id,"started_at": started_at.isoformat(),"completed_at": completed_at.isoformat(),@@ -387,25 +441,22 @@ class Scheduler:# Update next run time if not cancelledif final_status != "cancelled":- # Check if this is a one-time taskis_one_time = task.get("is_one_time", False)if is_one_time:- # One-time task: mark as completed (no rescheduling)- self._task_store.update_task(task_id, {- "status": "completed",+ await self._task_store.update_task(task_id, {+ "status": final_status,"current_execution_id": None,})- logger.info("[Scheduler] One-time task %s completed", task_id)+ logger.info("[Scheduler] One-time task %s finished with status: %s", task_id, final_status)else:- # Recurring task: reschedulenext_run = completed_at + timedelta(hours=interval_hours)- self._task_store.update_task(task_id, {+ await self._task_store.update_task(task_id, {"status": "pending","current_execution_id": None,"next_run_time": next_run.isoformat(),})else:- self._task_store.update_task(task_id, {+ await self._task_store.update_task(task_id, {"status": "cancelled","current_execution_id": None,})diff --git a/jiuwenswarm/agents/harness/common/auto_harness/service.py b/jiuwenswarm/agents/harness/common/auto_harness/service.pyindex e2d601bc18..4558ae7f05 100644--- a/jiuwenswarm/agents/harness/common/auto_harness/service.py+++ b/jiuwenswarm/agents/harness/common/auto_harness/service.py@@ -75,7 +75,6 @@ _DEFAULT_REPO_URL = "https://gitcode.com/openJiuwen/agent-core.git"# Default local repo path_DEFAULT_LOCAL_REPO = _AUTO_HARNESS_DATA_DIR / "repo" / "openJiuwen--agent-core"# Default values for ci_gate config-_DEFAULT_CI_GATE_PYTHON_EXECUTABLE = sys.executable_DEFAULT_CI_GATE_INSTALL_COMMAND = "uv sync --active --group dev --extra cli"@@ -266,8 +265,8 @@ class AutoHarnessService:needs_save = Trueci_gate = config_dict.get("ci_gate") or {}- if not ci_gate.get("python_executable"):- ci_gate["python_executable"] = _DEFAULT_CI_GATE_PYTHON_EXECUTABLE+ if ci_gate.get("python_executable"):+ ci_gate["python_executable"] = ""needs_save = Trueif not ci_gate.get("install_command"):@@ -344,6 +343,11 @@ class AutoHarnessService:"""Start the scheduling loop (called by AgentWebSocketServer)."""if self._scheduler is None:self._init_scheduler()+ # Reconcile legacy task statuses (async — requires file I/O)+ if self._task_store is not None and self._task_store.has_legacy_completed_tasks():+ corrected = await self._task_store.reconcile_task_statuses()+ if corrected > 0:+ logger.info("[AutoHarnessService] Reconciled %d legacy task statuses", corrected)if self._scheduler is not None:await self._scheduler.start()logger.info("[AutoHarnessService] Scheduler started")@@ -607,7 +611,7 @@ class AutoHarnessService:# config.yaml so that GitOperations.push() uses a named remote instead# of a raw URL. The named remote is added in clone_or_update_repo().if not config.git_base_branch:- config.git_base_branch = "develop"+ config.git_base_branch = "develop-auto-harness"if not config.git_remote:config.git_remote = "origin"@@ -2441,7 +2445,7 @@ class AutoHarnessService:"pipeline": pipeline, # Pipeline preference}- self._task_store.add_task(task_data)+ await self._task_store.add_task(task_data)logger.info("[AutoHarnessService] Created scheduled task: %s, interval=%sh, next_run=%s, run_immediately=%s",@@ -2509,7 +2513,7 @@ class AutoHarnessService:"pipeline": pipeline, # Pipeline preference}- self._task_store.add_task(task_data)+ await self._task_store.add_task(task_data)logger.info("[AutoHarnessService] Created one-time task: %s, will execute immediately",@@ -2546,7 +2550,7 @@ class AutoHarnessService:await self._scheduler.cancel_execution(task_id)# Update status- self._task_store.update_task(task_id, {"status": "cancelled"})+ await self._task_store.update_task(task_id, {"status": "cancelled"})logger.info("[AutoHarnessService] Cancelled scheduled task: %s", task_id)@@ -2576,7 +2580,7 @@ class AutoHarnessService:await self._scheduler.cancel_execution(task_id)# Delete task from store (includes removing log files)- deleted = self._task_store.delete_task(task_id)+ deleted = await self._task_store.delete_task(task_id)if not deleted:return {"error": "删除失败", "task_id": task_id}@@ -2584,7 +2588,7 @@ class AutoHarnessService:return {"task_id": task_id}- def get_scheduled_task_status(self, task_id: str) -> Optional[dict[str, Any]]:+ async def get_scheduled_task_status(self, task_id: str) -> Optional[dict[str, Any]]:"""Get task status and details.Returns:@@ -2594,7 +2598,7 @@ class AutoHarnessService:return Nonereturn self._task_store.get_task(task_id)- def list_scheduled_tasks(self) -> list[dict[str, Any]]:+ async def list_scheduled_tasks(self) -> list[dict[str, Any]]:"""List all scheduled tasks.Returns:@@ -2604,7 +2608,7 @@ class AutoHarnessService:return []return self._task_store.list_tasks()- def get_scheduled_task_logs(+ async def get_scheduled_task_logs(self,task_id: str,log_type: str = "current",@@ -2626,4 +2630,4 @@ class AutoHarnessService:"""if self._task_store is None:return {"error": "任务存储未初始化"}- return self._task_store.get_logs(task_id, log_type, history_index, offset, limit)+ return await self._task_store.get_logs(task_id, log_type, history_index, offset, limit)diff --git a/jiuwenswarm/agents/harness/common/auto_harness/task_store.py b/jiuwenswarm/agents/harness/common/auto_harness/task_store.pyindex 3e42b83de3..42fc7045f6 100644--- a/jiuwenswarm/agents/harness/common/auto_harness/task_store.py+++ b/jiuwenswarm/agents/harness/common/auto_harness/task_store.py@@ -5,15 +5,24 @@from __future__ import annotations+import asyncioimport jsonimport logging+import shutilfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Optional+from .scheduler import _determine_pipeline_status_from_log+logger = logging.getLogger(__name__)+def _sync_write_json(path: Path, data: str) -> None:+ """Synchronous JSON file write — called via asyncio.to_thread."""+ path.write_text(data, encoding="utf-8")++class TaskStore:"""Manages scheduled task metadata and execution logs.@@ -25,12 +34,17 @@ class TaskStore:├── exec_001/│ └── log.json # Structured log└── latest -> exec_001 # Symlink to latest++ Uses in-memory cache for reads to avoid blocking the asyncio event loop.+ Writes persist to disk via asyncio.to_thread."""def __init__(self, data_dir: Path):self._data_dir = data_dirself._tasks_file = data_dir / "scheduled-tasks.json"self._runs_dir = data_dir / "runs"+ self._tasks_cache: Optional[dict[str, Any]] = None+ self._save_lock: asyncio.Lock = asyncio.Lock()self._ensure_dirs()def _ensure_dirs(self) -> None:@@ -38,42 +52,52 @@ class TaskStore:self._runs_dir.mkdir(parents=True, exist_ok=True)def _load_tasks(self) -> dict[str, Any]:- """Load tasks from JSON file."""+ """Load tasks — returns in-memory cache if available, otherwise reads from file."""+ if self._tasks_cache is not None:+ return self._tasks_cache+if not self._tasks_file.exists():- return {"tasks": [], "last_updated": None}+ result = {"tasks": [], "last_updated": None}+ self._tasks_cache = result+ return result+try:data = json.loads(self._tasks_file.read_text(encoding="utf-8"))+ self._tasks_cache = datareturn dataexcept Exception as e:logger.warning("[TaskStore] Failed to load tasks file: %s", e)- return {"tasks": [], "last_updated": None}+ result = {"tasks": [], "last_updated": None}+ self._tasks_cache = result+ return result- def _save_tasks(self, data: dict[str, Any]) -> None:- """Save tasks to JSON file."""+ async def _save_tasks(self, data: dict[str, Any]) -> None:+ """Save tasks — updates in-memory cache first, then persists to disk via to_thread."""data["last_updated"] = datetime.now(timezone.utc).isoformat()- self._tasks_file.write_text(- json.dumps(data, ensure_ascii=False, indent=2),- encoding="utf-8"- )+ self._tasks_cache = data++ json_str = json.dumps(data, ensure_ascii=False, indent=2)+ async with self._save_lock:+ await asyncio.to_thread(_sync_write_json, self._tasks_file, json_str)- def add_task(self, task: dict[str, Any]) -> None:+ async def add_task(self, task: dict[str, Any]) -> None:"""Add a new scheduled task."""data = self._load_tasks()data["tasks"].append(task)- self._save_tasks(data)+ await self._save_tasks(data)logger.info("[TaskStore] Added task: %s", task.get("task_id"))- def update_task(self, task_id: str, updates: dict[str, Any]) -> None:+ async def update_task(self, task_id: str, updates: dict[str, Any]) -> None:"""Update an existing task."""data = self._load_tasks()for task in data.get("tasks", []):if task.get("task_id") == task_id:task.update(updates)break- self._save_tasks(data)+ await self._save_tasks(data)def get_task(self, task_id: str) -> Optional[dict[str, Any]]:- """Get task by ID."""+ """Get task by ID — reads from in-memory cache (zero I/O)."""data = self._load_tasks()for task in data.get("tasks", []):if task.get("task_id") == task_id:@@ -81,7 +105,7 @@ class TaskStore:return Nonedef list_tasks(self) -> list[dict[str, Any]]:- """List all tasks."""+ """List all tasks — reads from in-memory cache (zero I/O)."""data = self._load_tasks()return data.get("tasks", [])@@ -101,7 +125,6 @@ class TaskStore:if now >= next_run:pending.append(task)except ValueError:- # Invalid ISO format - skip task but log for debugginglogger.warning("[TaskStore] Invalid next_run_time format for task %s: %s",task.get("task_id"), next_run_str@@ -109,7 +132,7 @@ class TaskStore:continuereturn pending- def delete_task(self, task_id: str) -> bool:+ async def delete_task(self, task_id: str) -> bool:"""Delete a task and its log files.Args:@@ -121,7 +144,6 @@ class TaskStore:data = self._load_tasks()tasks = data.get("tasks", [])- # Find and remove the tasktask_found = Falsenew_tasks = []for task in tasks:@@ -133,16 +155,14 @@ class TaskStore:if not task_found:return False- # Update tasks filedata["tasks"] = new_tasks- self._save_tasks(data)+ await self._save_tasks(data)- # Remove log directory+ # Remove log directory (in thread to avoid blocking event loop)run_dir = self._runs_dir / task_idif run_dir.exists():try:- import shutil- shutil.rmtree(run_dir)+ await asyncio.to_thread(shutil.rmtree, run_dir)logger.info("[TaskStore] Removed log directory for task: %s", task_id)except Exception as e:logger.warning("[TaskStore] Failed to remove log directory: %s", e)@@ -150,7 +170,7 @@ class TaskStore:logger.info("[TaskStore] Deleted task: %s", task_id)return True- def add_execution_record(self, task_id: str, record: dict[str, Any]) -> None:+ async def add_execution_record(self, task_id: str, record: dict[str, Any]) -> None:"""Add execution record to task history."""data = self._load_tasks()for task in data.get("tasks", []):@@ -159,7 +179,7 @@ class TaskStore:history.append(record)task["execution_history"] = historybreak- self._save_tasks(data)+ await self._save_tasks(data)def get_log_path(self, task_id: str, execution_id: str) -> Path:"""Get path for execution log file."""@@ -169,10 +189,7 @@ class TaskStore:@staticmethoddef write_log(path: Path, chunks: list[dict[str, Any]]) -> None:- """Write structured log chunks to file (JSON Lines format).-- Each chunk is written as a separate JSON line for streaming support.- """+ """Write structured log chunks to file (JSON Lines format)."""with path.open("w", encoding="utf-8") as f:for chunk in chunks:f.write(json.dumps(chunk, ensure_ascii=False) + "\n")@@ -209,9 +226,8 @@ class TaskStore:if read_all or len(logs) < limit:logs.append(entry)else:- break # Reached limit+ breakexcept json.JSONDecodeError:- # Skip malformed lines, but don't count thempassreturn logsexcept Exception as e:@@ -243,16 +259,16 @@ class TaskStore:if not line:continuetry:- json.loads(line) # Validate but don't store+ json.loads(line)count += 1except json.JSONDecodeError:- pass # Skip invalid lines+ passreturn countexcept Exception as e:logger.warning("[TaskStore] Failed to count log lines: %s", e)return 0- def get_logs(+ async def get_logs(self,task_id: str,log_type: str,@@ -260,7 +276,7 @@ class TaskStore:offset: int = 0,limit: int = 500) -> dict[str, Any]:- """Get logs for a task.+ """Get logs for a task — file reads are done via asyncio.to_thread.Args:task_id: Task identifier@@ -277,14 +293,13 @@ class TaskStore:return {"error": "任务不存在", "task_id": task_id}if log_type == "current":- # Get currently running executioncurrent_exec_id = task.get("current_execution_id")if not current_exec_id:return {"error": "当前无正在执行的日志", "task_id": task_id}log_path = self._runs_dir / task_id / current_exec_id / "log.json"- logs = self.read_log(log_path, offset, limit)- total_lines = self.get_log_line_count(log_path)+ logs = await asyncio.to_thread(self.read_log, log_path, offset, limit)+ total_lines = await asyncio.to_thread(self.get_log_line_count, log_path)return {"logs": logs,"execution_id": current_exec_id,@@ -299,11 +314,9 @@ class TaskStore:if not history:return {"error": "无历史执行记录", "task_id": task_id}- # history_index: 0=latest, 1=second latest, etc.if history_index < 0 or history_index >= len(history):return {"error": f"历史记录索引超出范围 (0-{len(history)-1})", "task_id": task_id}- # Sort by completed_at descendingsorted_history = sorted(history,key=lambda r: r.get("completed_at", ""),@@ -319,8 +332,8 @@ class TaskStore:if not log_path.exists():log_path = self._runs_dir / task_id / record.get("execution_id", "") / "log.json"- logs = self.read_log(log_path, offset, limit)- total_lines = self.get_log_line_count(log_path)+ logs = await asyncio.to_thread(self.read_log, log_path, offset, limit)+ total_lines = await asyncio.to_thread(self.get_log_line_count, log_path)if logs:return {"logs": logs,@@ -333,4 +346,53 @@ class TaskStore:}return {"error": "日志文件不存在或为空", "record": record}- return {"error": f"未知的 log_type: {log_type}"}\ No newline at end of file+ return {"error": f"未知的 log_type: {log_type}"}++ def has_legacy_completed_tasks(self) -> bool:+ """Check if any task still has the blanket "completed" status (pre-migration)."""+ data = self._load_tasks()+ return any(t.get("status") == "completed" for t in data.get("tasks", []))++ async def reconcile_task_statuses(self) -> int:+ """Re-check completed tasks against their logs and fix stale status values."""+ data = self._load_tasks()+ corrected = 0++ for task in data.get("tasks", []):+ task_id = task.get("task_id")+ old_status = task.get("status")++ if old_status not in ("completed", "success", "failed"):+ continue++ history = task.get("execution_history", [])+ if not history:+ continue++ latest = history[-1]+ log_path_str = latest.get("log_path", "")+ if not log_path_str:+ continue++ log_path = Path(log_path_str)+ if not log_path.exists():+ continue++ result = _determine_pipeline_status_from_log(log_path)+ new_status = "failed" if result["failed"] else "success"++ if new_status != old_status:+ task["status"] = new_status+ latest["status"] = new_status+ if result["error"]:+ latest["error"] = result["error"]+ corrected += 1+ logger.info(+ "[TaskStore] Reconciled task %s: %s -> %s",+ task_id, old_status, new_status,+ )++ if corrected > 0:+ await self._save_tasks(data)++ return corrected\ No newline at end of filediff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/auto-harness.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/auto-harness.tsindex 3f79f3cabf..0dc5fcf7d5 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/auto-harness.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/auto-harness.ts@@ -121,7 +121,7 @@ function getPipelineCompletions(_partial: string, parts: string[]): string[] {function parseScheduleStartArgs(args: string): { interval: number; pipeline: string; query: string } {const parts = parseArgs(args);- let interval = 0;+ let interval = -1;let pipeline = "";let queryParts: string[] = [];let i = 0;@@ -130,7 +130,8 @@ function parseScheduleStartArgs(args: string): { interval: number; pipeline: strif (parts[i] === "--interval" || parts[i] === "-i") {i++;if (i < parts.length) {- interval = parseInt(parts[i], 10) || 0;+ const parsed = parseInt(parts[i], 10);+ interval = isNaN(parsed) ? -1 : parsed;i++;}} else if (parts[i] === "--pipeline" || parts[i] === "-p") {@@ -262,9 +263,10 @@ const scheduleStartCommand: SlashCommand = {action: async (ctx, args) => {const parsed = parseScheduleStartArgs(args);- if (!parsed.interval || parsed.interval < 1) {+ if (parsed.interval < 1) {+ const hint = parsed.interval === 0 ? "间隔不能为 0,请设置至少 1 小时" : parsed.interval === -1 ? "请提供有效的 --interval 数值(小时)" : "间隔必须大于 0 小时";ctx.addItem(- addError(ctx.sessionId, "用法: /auto-harness schedule start --interval <hours> [--pipeline <pipeline>] <query>\npipeline: optimize_expert_harness (生成扩展包), optimize_meta_harness (提交 PR)")+ addError(ctx.sessionId, `${hint}`));return;}@@ -383,7 +385,9 @@ const scheduleListCommand: SlashCommand = {for (const task of tasks) {const statusEmoji = task.status === "running" ? "[运行中]" :task.status === "pending" ? "[等待]" :- task.status === "cancelled" ? "[已取消]" : "[已完成]";+ task.status === "cancelled" ? "[已取消]" :+ task.status === "failed" ? "[失败]" :+ task.status === "success" ? "[成功]" : "[已完成]";const isOneTime = task.is_one_time ? "[一次性]" : "";const queryPreview = task.query.length > 50 ? task.query.substring(0, 50) + "..." : task.query;const pipelineInfo = task.pipeline ? `Pipeline: ${pipelineDisplayLabel(task.pipeline)}` : "";@@ -467,6 +471,7 @@ const scheduleStatusCommand: SlashCommand = {const recentHistory = history.slice(-5);for (const record of recentHistory) {const statusText = record.status === "success" ? "[成功]" :+ record.status === "failed" ? "[失败]" :record.status === "cancelled" ? "[取消]" : "[异常]";lines.push(`${statusText} ${record.execution_id} - ${formatLocalTime(record.completed_at) || "进行中"}`);}@@ -810,7 +815,7 @@ async function streamCurrentLogs(}if (pollCount >= maxPolls) {- ctx.addItem(addInfo(ctx.sessionId, `\n【日志跟踪超时终止】`));+ ctx.addItem(addInfo(ctx.sessionId, `\n【日志跟踪退出,任务后台运行中,可再次调用 logs 指令查看。】`));} else {ctx.addItem(addInfo(ctx.sessionId, `\n【日志跟踪完成: ${executionId}】`));}@@ -1227,7 +1232,12 @@ function formatLogSection(section: ParsedLogSection, detailed: boolean = false):const stageDisplayName = section.stages?.find((s) => s.slot === section.stage)?.display_name || section.stage || "?";if (section.status) {- const progressBar = formatStageProgress(section.stages, section.completed_stages, undefined, section.gap_count, section.extension_order?.length);+ const activeStage = section.status !== 'success' && section.status !== 'failed' ? section.stage : undefined;+ const effectiveCompleted = [...(section.completed_stages || [])];+ if (section.status === 'success' && section.stage && !effectiveCompleted.includes(section.stage)) {+ effectiveCompleted.push(section.stage);+ }+ const progressBar = formatStageProgress(section.stages, effectiveCompleted, activeStage, section.gap_count, section.extension_order?.length);const icon = section.status === "success" ? "✅" : section.status === "failed" ? "❌" : "⏸️";const color = section.status === "success" ? ANSI.green : section.status === "failed" ? ANSI.red : ANSI.yellow;const statusText = section.status === "success" ? "完成" : section.status === "failed" ? "失败" : section.status;@@ -1252,8 +1262,9 @@ function formatLogSection(section: ParsedLogSection, detailed: boolean = false):detailLines.push(` 🔄 修复循环: ${section.ci_fix_count} 次`);}}- // Extension status matrix shown AFTER stage-specific content, only when extensions have progress- if (section.extension_order && section.extensions_by_name && section.extension_order.length > 0) {+ // Extension status matrix shown AFTER stage-specific content, only during build_verify+ // (activate stage shows merge/activation info lines instead, not the matrix)+ if (section.stage !== 'activate' && section.extension_order && section.extensions_by_name && section.extension_order.length > 0) {const hasProgress = Object.values(section.extensions_by_name).some(ext => ext.implementStatus !== 'pending' || ext.verifyStatus !== 'pending');@@ -1477,11 +1488,12 @@ function parseAndAggregateLogs(const extName = log.extension_name;const extStage = log.extension_stage || '';- // Handle merge_ext: merged_extensions is a container, not a design extension- // Show merge status as standalone info line, not full stage render- if (extStage === 'merge_ext' && extName === 'merged_extensions') {+ // Handle merge_ext: show concise merge info highlighting N→1, no extension matrix+ if (extStage === 'merge_ext') {const mergeStatus = log.status || 'pending';- const mergeText = mergeStatus === 'success' ? '✅ 合并扩展完成' : mergeStatus === 'failed' ? '❌ 合并扩展失败' : '⏳ 合并扩展进行中';+ const extCount = extensionOrder.length;+ const mergeLabel = extCount > 0 ? `${extCount} 个扩展 → 1 个运行时扩展` : '合并扩展';+ const mergeText = mergeStatus === 'success' ? `✅ ${extName}: ${mergeLabel}完成` : mergeStatus === 'failed' ? `❌ ${extName}: ${mergeLabel}失败` : `⏳ ${extName}: ${mergeLabel}`;sections.push({type: "info",content: mergeText,@@ -1506,6 +1518,22 @@ function parseAndAggregateLogs(break;}+ // Activate-stage extension events should not be added to the design extension+ // matrix — they are runtime activations shown as separate info lines+ if (extStage === 'activate_ext' || log.parent_stage === 'activate') {+ const actText = extStatus === 'success' ? `✅ 激活 ${extName} 完成` : extStatus === 'failed' ? `❌ 激活 ${extName} 失败` : `⏳ 激活 ${extName}`;+ sections.push({+ type: "info",+ content: actText,+ });+ // Still update activateStatus for extensions that were in the matrix from build_verify+ const existing = extensionsByName[extName];+ if (existing) {+ existing.activateStatus = extStatus;+ }+ break;+ }+// Add to extension order if new (only design extensions, not merged)if (!extensionOrder.includes(extName)) {extensionOrder.push(extName);@@ -1551,10 +1579,13 @@ function parseAndAggregateLogs(break;}- // Track completed stage (only for stage-level events, deduplicate)- if (log.stage && !completedStages.includes(log.stage)) {+ if (log.stage && !scope && (log.status === 'success' || log.status === 'failed') && !completedStages.includes(log.stage)) {completedStages.push(log.stage);}+ // Track current running stage (from any scope="" event)+ if (log.stage && !scope && log.stage !== currentStage) {+ currentStage = log.stage;+ }// For activate stage: skip "running" status (merge/interaction sub-events handle display)// Only show the final "success" completion@@ -1622,6 +1653,10 @@ function parseAndAggregateLogs(break;case "harness.session_finished":+ // Mark the final stage as completed when session ends+ if (currentStage && !completedStages.includes(currentStage)) {+ completedStages.push(currentStage);+ }sections.push({type: "session_finished",content: log.status === "success" ? "任务执行成功" : `任务执行${log.status || "完成"}`,@@ -1880,7 +1915,7 @@ const runCommand: SlashCommand = {}ctx.addItem(- addInfo(ctx.sessionId, `\n一次性任务已创建并开始执行\nID: ${result.task_id}\nPipeline: ${pipelineDisplayLabel(pipeline)}\n状态: ${result.status}\n`)+ addInfo(ctx.sessionId, `\n一次性任务已创建并开始执行\nID: ${result.task_id}\nPipeline: ${pipelineDisplayLabel(pipeline)}\n状态: ${result.status}\n任务后台运行,默认读取实时日志,可以通过 ctrl + c 中断查看\n`));// Start streaming logsdiff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.pyindex fb4fb409aa..a6092803e4 100644--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py@@ -48,7 +48,6 @@ _AUTO_HARNESS_CONFIG_FILE = _AUTO_HARNESS_CONFIG_DIR / "config.yaml"_AUTO_HARNESS_LOCAL_REPO = _AUTO_HARNESS_CONFIG_DIR / "repo" / "openJiuwen--agent-core"# Default values for ci_gate config-_DEFAULT_CI_GATE_PYTHON_EXECUTABLE = sys.executable_DEFAULT_CI_GATE_INSTALL_COMMAND = "uv sync --active --group dev --extra cli"@@ -89,8 +88,8 @@ def _get_auto_harness_config() -> dict[str, Any]:config["local_repo"] = str(local_repo)needs_save = True- if not ci_gate.get("python_executable"):- ci_gate["python_executable"] = _DEFAULT_CI_GATE_PYTHON_EXECUTABLE+ if ci_gate.get("python_executable"):+ ci_gate["python_executable"] = ""needs_save = Trueif not ci_gate.get("install_command"):diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 4f45e6f371..706b3b1b42 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -4583,12 +4583,12 @@ class AgentWebSocketServer:payload = await self._scheduler_service.run_task(query, model, pipeline)elif action == "list":- tasks = self._scheduler_service.list_scheduled_tasks()+ tasks = await self._scheduler_service.list_scheduled_tasks()payload = {"tasks": tasks}elif action == "status":task_id = params.get("task_id", "")- task = self._scheduler_service.get_scheduled_task_status(task_id)+ task = await self._scheduler_service.get_scheduled_task_status(task_id)payload = task if task else {"error": "任务不存在", "task_id": task_id}elif action == "logs":@@ -4597,7 +4597,7 @@ class AgentWebSocketServer:history_index = params.get("history_index", -1)offset = params.get("offset", 0)limit = params.get("limit", 500)- payload = self._scheduler_service.get_scheduled_task_logs(+ payload = await self._scheduler_service.get_scheduled_task_logs(task_id, log_type, history_index, offset, limit)diff --git a/pyproject.toml b/pyproject.tomlindex d6b6d63f76..cb31bb9d9f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -110,15 +110,13 @@ jiuwenbox = [[tool.setuptools.exclude-package-data]jiuwenswarm = ["channels/web/frontend/node_modules/**", "channels/web/frontend/node_modules/*"]+[tool.uv]+default-groups = ['dev']+[tool.uv.sources]jiuwenswarm-tui = { path = "./packages/jiuwenswarm-tui" }[dependency-groups]-dev = [- "pytest>=9.0.3",- "pytest-asyncio>=1.3.0",- "pytest-cov>=7.1.0",-]# Testing (keep in sync with optional-dependencies.test)test = ["a2a-sdk[http-server]==1.0.0",@@ -130,3 +128,12 @@ test = ["coverage>=7.7.1","pyyaml>=6.0",]+# Linting & formatting+lint = [+ "ruff>=0.11.2",+ "pylint>=3.0.0",+ "mypy>=1.12.0",+ "codespell>=2.2.4",+ "httpx>=0.28.1",+]+dev = [{ include-group = "test" }, { include-group = "lint" }]