Skip to content

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

feat(auto-harness): Tui support GitCode issue fix workflow

openJiuwen-bot5024bfcdede6
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/__init__.py b/jiuwenswarm/agents/harness/common/auto_harness/__init__.py
index 928f20f5cb..c9a47d5091 100644
--- a/jiuwenswarm/agents/harness/common/auto_harness/__init__.py
+++ b/jiuwenswarm/agents/harness/common/auto_harness/__init__.py
@@ -19,4 +19,4 @@ __all__ = [
"Scheduler",
"TaskStore",
"ConfigValidator",
-]
\ No newline at end of file
+]
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/capabilities.py b/jiuwenswarm/agents/harness/common/auto_harness/capabilities.py
new file mode 100644
index 0000000000..94198c100d
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/capabilities.py
@@ -0,0 +1,84 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Capability registry for auto-harness scenario extensions."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Callable, Optional, Protocol
+
+from openjiuwen.core.foundation.llm import Model
+
+from .task_store import TaskStore
+
+
+class AutoHarnessCapability(Protocol):
+ """Scenario extension interface for auto-harness capabilities."""
+
+ async def handle(
+ self,
+ action: str,
+ params: dict[str, Any],
+ model: Optional[Model] = None,
+ ) -> dict[str, Any]:
+ ...
+
+
+class AutoHarnessCapabilityRegistry:
+ """Registry that keeps scenario capabilities out of the core service."""
+
+ def __init__(self) -> None:
+ self._capabilities: dict[str, AutoHarnessCapability] = {}
+
+ def register(self, name: str, capability: AutoHarnessCapability) -> None:
+ self._capabilities[name] = capability
+
+ async def handle(
+ self,
+ name: str,
+ action: str,
+ params: dict[str, Any],
+ model: Optional[Model] = None,
+ ) -> dict[str, Any]:
+ capability = self._capabilities.get(name)
+ if capability is None:
+ return {"error": f"未知 auto-harness 能力: {name}"}
+ return await capability.handle(action, params, model)
+
+
+def create_default_capability_registry(
+ *,
+ data_dir: Path,
+ task_store: TaskStore,
+ harness_service: Any,
+ base_config_getter: Callable[[], Any],
+ default_repo_url: str,
+) -> AutoHarnessCapabilityRegistry:
+ """Create built-in auto-harness capabilities."""
+ from .issue_fix.issue_matrix_store import IssueMatrixStore
+ from .issue_fix.issue_state_store import IssueStateStore
+ from .issue_fix.run_progress import (
+ enrich_issue_fix_progress,
+ infer_issue_fix_skipped_stages,
+ )
+ from .issue_fix.service import IssueFixService
+
+ registry = AutoHarnessCapabilityRegistry()
+ issue_state_store = IssueStateStore(data_dir)
+ issue_matrix_store = IssueMatrixStore(data_dir)
+ task_store.register_run_log_status_extension(
+ skipped_stage_inferer=infer_issue_fix_skipped_stages,
+ progress_enricher=enrich_issue_fix_progress,
+ )
+ registry.register(
+ "issue",
+ IssueFixService(
+ task_store=task_store,
+ issue_state_store=issue_state_store,
+ issue_matrix_store=issue_matrix_store,
+ harness_service=harness_service,
+ base_config_getter=base_config_getter,
+ default_repo_url=default_repo_url,
+ ),
+ )
+ return registry
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/__init__.py b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/__init__.py
new file mode 100644
index 0000000000..029ee502c6
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/__init__.py
@@ -0,0 +1,19 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Issue-fix integration for auto-harness."""
+
+from .gitcode_issue_client import GitCodeIssue, GitCodeIssueClient
+from .issue_runner import GitCodeIssueRunner, IssueWatchOptions
+from .issue_state_store import IssueStateStore
+from .service import IssueFixService
+from .task_factory import build_issue_fix_task
+
+__all__ = [
+ "build_issue_fix_task",
+ "GitCodeIssue",
+ "GitCodeIssueClient",
+ "GitCodeIssueRunner",
+ "IssueFixService",
+ "IssueStateStore",
+ "IssueWatchOptions",
+]
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/code_rule.txt b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/code_rule.txt
new file mode 100644
index 0000000000..bd194963df
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/code_rule.txt
@@ -0,0 +1,201 @@
+ 代码风格
+2.1 命名
+2.1.1 命名风格
+G.NAM.01 使用统一的命名风格
+2.1.2 命名注意事项
+G.NAM.02 命名要有明确含义,以提升代码的可读性
+G.NAM.03“self”应是实例方法的第一个参数,“cls”应是类方法的第一个参数
+G.NAM.04 避免在无关的标识符或无关的概念之间重用名字, 避免因重名而导致的意外赋
+值和错误引用
+G.NAM.05 除了需要重写魔法函数、对象之外,不推荐使用双下划线开头且双下划线结尾的
+标识符来命名一般对象
+2.2 注释
+2.2.1 文档字符串
+G.CMT.01 模块文档字符串写在文件的顶部,Shebang和文件编码声明之后,导入(imports)
+部分之前的位置,不需要缩进
+G.CMT.02 类的文档字符串写在类声明(class ClassName:)所在行的下一行,并向后缩进4
+个空格
+G.CMT.03 公共函数的文档字符串写在函数声明(def function_name(param):)所在行的下
+一行,并向后缩进4个空格
+2.2.2 代码注释
+P.01 注释跟代码一样重要,应按需注释
+G.CMT.04 代码的注释位置和格式应该在项目内保持统一
+G.CMT.05 正式交付给客户的代码不应包含TODO/FIXME注释
+G.CMT.06 文件头注释应该包含版权许可信息
+2.3 格式
+2.3.1 缩进
+G.FMT.01 程序块应该采用4个空格缩进风格编写
+2.3.2 行宽
+G.FMT.02 行宽不宜过长
+2.3.3 空行
+G.FMT.03 合理安排空行
+2.3.4 空格
+G.FMT.04 用空格突出关键字和重要信息
+2.3.5 导入
+G.FMT.05 导入部分(imports)应该置于模块注释和文档字符串之后,模块全局变量和常量
+声明之前
+G.FMT.06 每行只能导入一个模块
+G.FMT.07 导入部分(imports)应该按照标准库、第三方库、应用程序自定义模块的顺序排
+列导入
+2.3.6 单行
+G.FMT.08 一行只写一条语句
+2.3.7 多行与换行
+G.FMT.09 合理的运用换行和缩进
+G.FMT.10 代码行的行尾结束符LF和CRLF不应该混用
+3 编程实践
+3.1 数据模型
+3.1.1 数值
+G.TYP.01 需要精确数值计算的场景,应使用decimal模块,且不要用浮点数构造Decimal
+G.TYP.02 浮点型数据判断相等不要直接使用==
+3.1.2 字符串
+P.02 合理使用字符串格式化
+P.03 合理使用字符串引号
+P.17 不要使用难以理解的字面量
+3.1.3 序列与映射
+G.TYP.04 建议使用if seq或if not seq的方式判断序列是否为空
+G.TYP.05 对序列使用切片操作时,不建议使用负步进值进行切片
+G.TYP.06 同一个字典表达式中各个键值不要相同
+G.TYP.07 使用dict【key】获取 value 时需要注意保证 key 在有效的范围内
+3.1.4 类型检查与使用
+G.TYP.08 必须使用isinstance判断变量类型
+G.TYP.09 建议优先使用语义更明确的内置函数来判断对象的类型或行为
+3.2 运算符与表达式
+3.2.1 运算符
+G.OPR.01 对除法运算和模运算中的除数为0的情况做相应保护
+G.OPR.02 与None作比较要使用is或is not,不要使用等号
+G.OPR.03 禁止使用is或is not运算符在内置类型之间作比较
+G.OPR.04 不建议使用海象运算符
+G.OPR.05 应该使用 is not 运算符而不是not … is
+G.OPR.06 应该使用 not in 测试成员关系
+3.2.2 表达式
+G.EXP.01 尽可能使用隐式布尔值
+G.EXP.02 如果lambda表达式的内容超过一行,建议定义为常规函数
+G.EXP.03 不应将lambda表达式赋值给变量,应该使用常规函数
+G.EXP.04 推导式和生成器表达式仅用于简单的逻辑表达
+3.3 控制语句
+G.CTL.01 同一个函数所有分支的返回值类型和个数保持一致
+G.CTL.02 所有的代码都必须是逻辑可达的
+G.CTL.03 避免在条件/循环控制语句中包含过多的条件
+G.CTL.04 建议使用 for x in iterable 的方式循环处理可迭代对象
+G.CTL.05 建议使用单个下划线代替循环体中未使用的循环变量
+G.CTL.06 避免出现死循环
+3.4 函数与方法
+3.4.1 函数参数
+G.FNM.01 禁止使用可变对象作为参数默认值
+G.FNM.02 函数和lambda表达式不应该使用外部的循环代码中定义的变量
+G.FNM.03 当函数参数个数较多且有相关性时,建议通过class/namedtuple/dataclass等具
+名形式进行封装
+3.4.2 函数返回值
+G.FNM.04 不要将没有返回值的函数调用结果赋值给变量
+G.FNM.05 当函数返回值个数较多时,建议通过class/namedtuple/dataclass等具名形式进
+行封装
+G.FNM.06 使用return代替StopIteration来结束生成器
+3.4.3 函数调用
+G.FNM.07 建议妥善处理函数的返回值和异常
+3.5 变量作用域
+P.04 合理使用全局变量
+G.VAR.01 禁止在变量的生命周期内修改其类型
+G.VAR.02 禁止使用global关键字声明不存在的外部变量
+G.VAR.03 禁止覆盖外部作用域中的标识符
+3.6 类与面向对象
+P.05 类的成员属性应该根据封装的需要来区分访问权限
+G.CLS.01 如果子类和父类中都有__init__方法,则子类中的__init__方法必须正确调用其父
+类__init__方法
+G.CLS.02 子类重写父类的方法时,方法签名应该和被重写的方法一致
+G.CLS.03 建议避免在继承内置类型的同时重写其魔法函数
+G.CLS.04 建议在实现抽象类时使用abc模块
+G.CLS.05 子类调用父类初始化方法的方式,建议使用super类辅助
+G.CLS.06 类的方法建议统一按照一种规则进行排列
+G.CLS.07 类的方法不需要访问实例时,建议定义为staticmethod或classmethod
+G.CLS.08 避免在__init__方法外定义类实例属性
+G.CLS.09 重写类的魔法函数时必须返回其原型指定的类型
+G.CLS.10 未实现的数值运算类型魔法函数必须返回NotImplemented而不是抛出
+NotImplementedError
+G.CLS.11 避免在类外或者子类中访问父类受保护的成员
+G.CLS.12 类实例较多时,推荐使用__slots__来加强管理类的成员属性
+3.7 异常处理
+G.ERR.01 try代码块内只包含可能抛出异常的代码段
+G.ERR.02 用异常来表示异常,而不是用返回值表示异常
+G.ERR.03 异常的类型定义必须继承自Exception
+G.ERR.04 对异常做类型转换时要保留原始异常的错误调用栈信息
+G.ERR.05 使用有明确业务属性的异常类型
+G.ERR.06 raise语句必须包含异常实例
+G.ERR.07 避免抑制或忽略异常
+G.ERR.08 禁止通过异常泄露敏感数据
+G.ERR.09 在单个except代码块内,禁止重复捕获同类异常
+G.ERR.10 同时使用多个except语句时,要注意异常捕获的顺序
+G.ERR.11 避免使用SystemExit和sys.exit(),主进程入口中例外
+G.ERR.12 合理地使用object.__exit__处理异常
+G.ERR.13 捕获异常后避免直接重新抛出
+G.ERR.14 不要使用return、break、continue或抛出异常使finally块非正常结束
+3.8 并行与并发
+P.06 不要依赖于内置类型的原子性
+P.07 Python多线程适用于阻塞式IO场景,不适用于并行计算场景
+G.CNP.01建议为communicate传入超时参数来防止子进程死锁或失去响应
+3.9 包与模块
+P.08 使用package对module分层管理
+P.09 使用__all__声明允许外部访问的变量、函数和类
+G.IMP.01 使用绝对路径导入模块
+G.IMP.02 使用 from … import … 语句的注意事项
+G.IMP.03 避免使用__import__函数
+3.10 标准库
+P.10 注意根据场景选用copy或deepcopy来完成浅拷贝或深拷贝
+G.PSL.01 避免使用已经被标记为弃用并有明确替代的方法
+G.PSL.02 在datetime的使用过程中注意时区的影响,时区敏感的场景建议显式指定时区
+G.PSL.03 修改sys.path时注意避免模块重名问题
+G.PSL.04 建议用functools.wraps定义函数装饰器
+3.11 代码工程
+P.11 建议尽量使用标准库中的功能来替代直接调用操作系统的系统命令
+G.PRJ.01 建议为启动文件添加启动文件头
+G.PRJ.02 建议为启动文件设置执行入口
+G.PRJ.03 产品代码不要包含任何调试入口点
+G.PRJ.04 建议同一项目内的编码方式保持一致,推荐使用UTF-8
+G.PRJ.05 不用的代码段直接删除,不要注释掉
+G.PRJ.06 正式发布的代码及注释内容不应包含开发者个人信息
+G.PRJ.07 禁止代码中包含公网地址
+3.12 文件
+P.12 使用open打开文件时应注意使用正确的模式和编码
+G.FIO.01 在多用户系统中创建文件时应根据需要指定合适的权限
+G.FIO.02 使用外部数据构造的文件路径前必须进行校验,校验前必须对文件路径进行规范化
+处理
+G.FIO.03 禁止使用tempfile.mktemp创建临时文件
+G.FIO.04 临时文件使用完毕应及时删除
+G.FIO.05 构造文件路径时应屏蔽操作系统的差异,建议使用库函数辅助构造
+G.FIO.06 解压文件必须进行安全检查
+3.13 序列化
+G.SER.01 禁止使用pickle.load、_pickle.load和shelve模块加载外部数据
+G.SER.02 禁止序列化未加密的敏感数据
+G.SER.03 禁止使用yaml模块的load函数
+G.SER.04 禁止使用jsonpickle模块的encode/decode或dumps/loads函数
+G.SER.05 在序列化操作时建议使用较为安全的json模块
+3.14 外部数据校验
+P.13 校验跨信任边界传递的外部数据
+G.EDV.01 禁止使用eval和exec函数执行不可信代码
+G.EDV.02 禁止使用OS命令解析器或“危险函数”调用系统命令
+G.EDV.03 避免在命令解析器中使用通配符
+G.EDV.04 禁止使用subprocess模块中的shell=True选项
+G.EDV.05 调用外部可执行程序时建议使用绝对路径
+G.EDV.06 禁止直接使用外部数据来拼接SQL语句
+G.EDV.07 不受信任的外部数据禁止使用.format()进行格式化
+G.EDV.08 防止正则表达式引起的ReDos攻击
+G.EDV.09 禁止直接使用外部数据来拼接XML
+G.EDV.10 禁止在处理XML数据时解析不可信的实体
+3.15 日志
+G.LOG.01 logging模块应尽量使用懒插值的能力记录日志
+G.LOG.02 使用日志记录工具实现日志功能
+G.LOG.03 禁止直接使用外部数据记录日志
+3.16 性能与资源管理
+P.14 在try代码块内如果修改了资源,需要在except子句内将对应的资源还原
+P.15 合并大量字符串时建议根据需求选择合适的方式
+P.16 在内存敏感的场景下建议使用生成器代替一次性生成数据的容器
+G.PRM.01 在list成员个数可以预知的情况下,创建list时建议预留空间容纳所有成员的空间
+G.PRM.02 在成员个数及内容皆不变的场景下建议使用tuple替代list
+G.PRM.03 资源的申请和释放需要成对使用,包括正常和异常场景
+3.17 代码测试
+G.TES.01 禁止在生产版本的业务代码中使用assert
+G.TES.02 使用对应的方法做值断言
+3.18 数据安全处理
+G.DSP.01 将敏感对象发送出信任区域前进行签名并加密
+G.DSP.02 安全场景下必须使用密码学意义上的安全随机数
+G.DSP.03 必须使用ssl.SSLSocket代替socket.Socket来进行安全数据交互
+G.DSP.04 禁止在用户界面、日志中暴露不必要信息
\ No newline at end of file
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/code_rules.py b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/code_rules.py
new file mode 100644
index 0000000000..c47d48b709
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/code_rules.py
@@ -0,0 +1,33 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Code rule loading for GitCode issue-fix tasks."""
+
+from __future__ import annotations
+
+from functools import lru_cache
+from pathlib import Path
+
+
+_CODE_RULE_FILE = "code_rule.txt"
+
+
+@lru_cache(maxsize=1)
+def load_code_rules() -> str:
+ """Load repository code rules for issue-fix prompts."""
+ rule_path = Path(__file__).resolve().parent / _CODE_RULE_FILE
+ if rule_path.is_file():
+ return rule_path.read_text(encoding="utf-8").replace("\r\n", "\n").strip()
+ return ""
+
+
+def format_code_rules_prompt() -> str:
+ """Build the prompt section that constrains generated code style."""
+ rules = load_code_rules()
+ if not rules:
+ return ""
+ return (
+ "编程规范约束(必须遵守仓库 code_rule.txt):\n"
+ "以下规范适用于本次 issue 修复产生的所有产品代码和测试代码;"
+ "若 issue 修复方案与规范冲突,必须优先满足规范并在日志中说明取舍。\n"
+ f"{rules}\n"
+ )
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/gitcode_issue_client.py b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/gitcode_issue_client.py
new file mode 100644
index 0000000000..4cb7b8180b
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/gitcode_issue_client.py
@@ -0,0 +1,226 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Small GitCode API client for auto-harness issue ingestion."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import logging
+from typing import Any, Optional
+
+import httpx
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class GitCodeIssue:
+ """Normalized GitCode issue metadata used by the issue runner."""
+
+ number: int
+ title: str
+ body: str
+ html_url: str
+ labels: tuple[str, ...]
+ raw: dict[str, Any]
+
+
+class GitCodeIssueClient:
+ """HTTP client for the GitCode repository issue and pull-request APIs."""
+
+ def __init__(
+ self,
+ *,
+ token: str,
+ base_url: str = "https://api.gitcode.com/api/v5",
+ timeout: float = 20.0,
+ trust_env: bool = False,
+ ) -> None:
+ self._token = token.strip()
+ self._base_url = base_url.rstrip("/")
+ self._timeout = timeout
+ self._trust_env = trust_env
+
+ def _headers(self) -> dict[str, str]:
+ headers = {
+ "Accept": "application/json",
+ "User-Agent": "jiuwenswarm-auto-harness",
+ }
+ if self._token:
+ # GitCode release code in this repo already uses PRIVATE-TOKEN.
+ # Authorization is included for compatibility with bearer-style APIs.
+ headers["PRIVATE-TOKEN"] = self._token
+ headers["Authorization"] = f"Bearer {self._token}"
+ return headers
+
+ def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ params: Optional[dict[str, Any]] = None,
+ json_body: Optional[dict[str, Any]] = None,
+ ) -> Any:
+ url = f"{self._base_url}{path}"
+ with httpx.Client(
+ timeout=self._timeout,
+ headers=self._headers(),
+ trust_env=self._trust_env,
+ ) as client:
+ response = client.request(method, url, params=params, json=json_body)
+ try:
+ response.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ detail = response.text[:500]
+ logger.warning("[GitCodeIssueClient] %s %s failed: %s", method, path, detail)
+ raise RuntimeError(
+ f"GitCode API {method} {path} failed with {response.status_code}: {detail}"
+ ) from exc
+ if not response.content:
+ return None
+ return response.json()
+
+ @staticmethod
+ def _normalize_labels(raw_labels: Any) -> tuple[str, ...]:
+ labels: list[str] = []
+ if isinstance(raw_labels, list):
+ for item in raw_labels:
+ if isinstance(item, str):
+ labels.append(item)
+ elif isinstance(item, dict):
+ name = item.get("name") or item.get("title")
+ if name:
+ labels.append(str(name))
+ elif isinstance(raw_labels, str):
+ labels.extend(part.strip() for part in raw_labels.split(",") if part.strip())
+ return tuple(labels)
+
+ @classmethod
+ def _normalize_issue(cls, raw: dict[str, Any]) -> GitCodeIssue:
+ number_raw = raw.get("number", raw.get("iid", raw.get("id", 0)))
+ try:
+ number = int(number_raw)
+ except (TypeError, ValueError):
+ number = 0
+ return GitCodeIssue(
+ number=number,
+ title=str(raw.get("title") or ""),
+ body=str(raw.get("body") or raw.get("description") or ""),
+ html_url=str(raw.get("html_url") or raw.get("url") or ""),
+ labels=cls._normalize_labels(raw.get("labels")),
+ raw=raw,
+ )
+
+ def list_issues(
+ self,
+ *,
+ owner: str,
+ repo: str,
+ state: str = "open",
+ labels: Optional[list[str]] = None,
+ sort: str = "updated",
+ direction: str = "desc",
+ page: int = 1,
+ per_page: int = 20,
+ ) -> list[GitCodeIssue]:
+ params: dict[str, Any] = {
+ "state": state,
+ "sort": sort,
+ "direction": direction,
+ "page": page,
+ "per_page": per_page,
+ }
+ if labels:
+ params["labels"] = ",".join(labels)
+ data = self._request("GET", f"/repos/{owner}/{repo}/issues", params=params)
+ if not isinstance(data, list):
+ return []
+ return [self._normalize_issue(item) for item in data if isinstance(item, dict)]
+
+ def list_all_issues(
+ self,
+ *,
+ owner: str,
+ repo: str,
+ state: str = "open",
+ sort: str = "updated",
+ direction: str = "desc",
+ per_page: int = 100,
+ max_pages: int = 20,
+ ) -> dict[int, GitCodeIssue]:
+ """Fetch all issues with pagination, returns dict keyed by issue number.
+
+ Args:
+ owner: Repository owner
+ repo: Repository name
+ state: Issue state filter (open/closed/all)
+ sort: Sort field (updated/created)
+ direction: Sort direction (desc/asc)
+ per_page: Items per page (max 100)
+ max_pages: Maximum pages to fetch (safety limit, default 20 = 2000 issues)
+ """
+ all_issues: dict[int, GitCodeIssue] = {}
+ page = 1
+
+ while page <= max_pages:
+ issues = self.list_issues(
+ owner=owner,
+ repo=repo,
+ state=state,
+ sort=sort,
+ direction=direction,
+ page=page,
+ per_page=per_page,
+ )
+ if not issues:
+ break
+ for issue in issues:
+ all_issues[issue.number] = issue
+ if len(issues) < per_page:
+ break # Last page
+ page += 1
+
+ logger.info("[GitCodeIssueClient] Fetched %d issues for %s/%s", len(all_issues), owner, repo)
+ return all_issues
+
+ def get_issue(self, *, owner: str, repo: str, number: int) -> GitCodeIssue:
+ data = self._request("GET", f"/repos/{owner}/{repo}/issues/{number}")
+ if not isinstance(data, dict):
+ raise RuntimeError(f"GitCode issue #{number} response is not an object")
+ return self._normalize_issue(data)
+
+ def list_issue_pull_requests(self, *, owner: str, repo: str, number: int) -> list[dict[str, Any]]:
+ data = self._request("GET", f"/repos/{owner}/{repo}/issues/{number}/pull_requests")
+ if isinstance(data, list):
+ return [item for item in data if isinstance(item, dict)]
+ return []
+
+ def list_pull_requests(
+ self,
+ *,
+ owner: str,
+ repo: str,
+ state: str = "open",
+ page: int = 1,
+ per_page: int = 50,
+ ) -> list[dict[str, Any]]:
+ data = self._request(
+ "GET",
+ f"/repos/{owner}/{repo}/pulls",
+ params={
+ "state": state,
+ "page": page,
+ "per_page": per_page,
+ },
+ )
+ if isinstance(data, list):
+ return [item for item in data if isinstance(item, dict)]
+ return []
+
+ def create_issue_comment(self, *, owner: str, repo: str, number: int, body: str) -> dict[str, Any]:
+ data = self._request(
+ "POST",
+ f"/repos/{owner}/{repo}/issues/{number}/comments",
+ json_body={"body": body},
+ )
+ return data if isinstance(data, dict) else {}
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/issue_matrix_store.py b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/issue_matrix_store.py
new file mode 100644
index 0000000000..319612d60a
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/issue_matrix_store.py
@@ -0,0 +1,106 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Issue matrix storage for tracking analyzed GitCode issues."""
+
+from __future__ import annotations
+
+import json
+import logging
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+class IssueMatrixStore:
+ """Manages issue matrix data for a specific repository.
+
+ Storage layout:
+ ~/.jiuwenswarm/auto-harness/issue/
+ └── <owner>_<repo>.json
+
+ Each file contains:
+ {
+ "owner": "...",
+ "repo": "...",
+ "last_scan": "2026-06-11T10:00:00Z",
+ "total_open": 127,
+ "matrix": [
+ {
+ "number": 1272,
+ "title": "...",
+ "body": "...",
+ "labels": ["bug"],
+ "difficulty": "medium",
+ "updated_at": "2026-06-11T...",
+ "first_seen": "2026-06-01T...",
+ "last_analyzed": "2026-06-11T...",
+ }
+ ]
+ }
+ """
+
+ def __init__(self, data_dir: Path):
+ self._matrix_dir = data_dir / "issue"
+ self._matrix_dir.mkdir(parents=True, exist_ok=True)
+
+ def _matrix_path(self, owner: str, repo: str) -> Path:
+ """Get matrix file path for a repository."""
+ safe_owner = owner.replace("/", "_").replace("\\", "_")
+ safe_repo = repo.replace("/", "_").replace("\\", "_")
+ return self._matrix_dir / f"{safe_owner}_{safe_repo}_issue_matrix.json"
+
+ def load(self, owner: str, repo: str) -> dict[str, Any]:
+ """Load matrix for a repository, returns empty structure if not exists."""
+ path = self._matrix_path(owner, repo)
+ if not path.exists():
+ return {
+ "owner": owner,
+ "repo": repo,
+ "last_scan": None,
+ "total_open": 0,
+ "matrix": [],
+ }
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return data
+ except Exception as e:
+ logger.warning("[IssueMatrixStore] Failed to load matrix: %s", e)
+ return {
+ "owner": owner,
+ "repo": repo,
+ "last_scan": None,
+ "total_open": 0,
+ "matrix": [],
+ }
+
+ def save(self, owner: str, repo: str, data: dict[str, Any]) -> None:
+ """Save matrix for a repository."""
+ path = self._matrix_path(owner, repo)
+ data["owner"] = owner
+ data["repo"] = repo
+ data["last_scan"] = datetime.now(timezone.utc).isoformat()
+ json_str = json.dumps(data, ensure_ascii=False, indent=2)
+ path.write_text(json_str, encoding="utf-8")
+ logger.info("[IssueMatrixStore] Saved matrix for %s/%s: %d issues", owner, repo, len(data.get("matrix", [])))
+
+ def get_entry(self, owner: str, repo: str, number: int) -> dict[str, Any] | None:
+ """Get a specific issue entry from the matrix."""
+ data = self.load(owner, repo)
+ for entry in data.get("matrix", []):
+ if entry.get("number") == number:
+ return entry
+ return None
+
+ def remove_entry(self, owner: str, repo: str, number: int) -> bool:
+ """Remove an issue entry from the matrix."""
+ data = self.load(owner, repo)
+ matrix = data.get("matrix", [])
+ new_matrix = [e for e in matrix if e.get("number") != number]
+ if len(new_matrix) == len(matrix):
+ return False
+ data["matrix"] = new_matrix
+ data["total_open"] = len(new_matrix)
+ self.save(owner, repo, data)
+ return True
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/issue_runner.py b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/issue_runner.py
new file mode 100644
index 0000000000..78edd21d56
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/issue_runner.py
@@ -0,0 +1,566 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""GitCode issue ingestion and auto-harness task orchestration."""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+import json
+import logging
+import re
+from pathlib import Path
+from typing import Any, Optional, Protocol
+
+from openjiuwen.auto_harness.pipelines import META_EVOLVE_PIPELINE
+
+from .code_rules import format_code_rules_prompt
+from .gitcode_issue_client import GitCodeIssue, GitCodeIssueClient
+from .issue_state_store import IssueStateStore
+from .task_factory import build_issue_fix_task
+
+logger = logging.getLogger(__name__)
+
+
+class AutoHarnessTaskService(Protocol):
+ async def run_task(
+ self,
+ query: str,
+ model: Any = None,
+ pipeline: Optional[str] = None,
+ optimization_task: Any = None,
+ repo_url: str = "",
+ ) -> dict[str, Any]:
+ ...
+
+ async def get_scheduled_task_status(self, task_id: str) -> Optional[dict[str, Any]]:
+ ...
+
+
+@dataclass(frozen=True)
+class IssueWatchOptions:
+ owner: str
+ repo: str
+ issue_numbers: tuple[int, ...] = ()
+ labels: tuple[str, ...] = ("auto-harness",)
+ exclude_labels: tuple[str, ...] = ("blocked", "wontfix", "needs-discussion")
+ max_issues: int = 1
+ per_page: int = 20
+ pipeline: str = META_EVOLVE_PIPELINE
+ comment_on_start: bool = False
+ dry_run: bool = False
+ start_interval_seconds: float = 0.0
+ max_auto_difficulty: str = "medium"
+
+
+class GitCodeIssueRunner:
+ """Turns eligible GitCode issues into one-time auto-harness tasks."""
+
+ TERMINAL_RECORD_STATUSES = {"pr_created", "completed", "skipped", "needs_human"}
+ IN_FLIGHT_RECORD_STATUSES = {"running", "task_created"}
+ RECONCILE_RECORD_STATUSES = IN_FLIGHT_RECORD_STATUSES | {"completed_without_pr", "failed", "skipped"}
+ _DIFFICULTY_ORDER = {"low": 1, "medium": 2, "high": 3, "unclear": 4}
+
+ def __init__(
+ self,
+ *,
+ client: GitCodeIssueClient,
+ state_store: IssueStateStore,
+ harness_service: AutoHarnessTaskService,
+ ) -> None:
+ self._client = client
+ self._state_store = state_store
+ self._harness_service = harness_service
+
+ @staticmethod
+ def build_issue_fix_query(issue: GitCodeIssue, *, owner: str, repo: str) -> str:
+ issue_url = issue.html_url or f"https://gitcode.com/{owner}/{repo}/issues/{issue.number}"
+ labels = ", ".join(issue.labels) if issue.labels else "(none)"
+ code_rules = format_code_rules_prompt()
+ return (
+ f"请自动修复 GitCode Issue #{issue.number}。\n\n"
+ f"仓库: {owner}/{repo}\n"
+ f"Issue URL: {issue_url}\n"
+ f"标题: {issue.title}\n"
+ f"标签: {labels}\n\n"
+ f"Issue 内容:\n{issue.body or '(empty)'}\n\n"
+ "执行要求:\n"
+ "1. 只修改与该 issue 直接相关的代码和测试。\n"
+ "2. 优先补充或更新能够复现问题的测试。\n"
+ "3. 运行仓库现有的相关测试或最小可行验证命令。\n"
+ f"4. 为该 issue 单独提交一个 PR,PR 标题包含 issue #{issue.number}。\n"
+ f"5. PR 正文必须写明修改方案、验证结果、风险和回滚建议,"
+ f"并包含“对应 Issue: #{issue.number}”和单独一行“Closes #{issue.number}”,"
+ "便于 committer 审核并让 GitCode 自动关联 issue。\n"
+ "6. 如果 issue 信息不足以安全修复,请停止并在日志里说明缺失信息。\n"
+ "7. 严禁把本 issue 修复任务扩展成 auto-harness 框架能力建设、"
+ "调度器改造、IssueStateStore 等流程优化;除非 issue 内容明确要求修改这些文件。\n"
+ "8. 如果发现需要改进 auto-harness 流程才能完成自动化,请在日志中记录为后续建议,"
+ "本 PR 仍必须只包含当前 issue 的产品代码和测试修复。\n"
+ "9. 修复前必须提取 issue 中点名的文件、函数或方法;最终 diff 必须命中这些目标。"
+ "如果已有分支/提交修复的是相似但非同一目标,禁止复用。\n"
+ "10. PR 文案必须基于最终 diff 撰写,函数名、文件名和验证结论不能写成中间尝试内容。\n"
+ "11. 测试代码不得直接访问以单下划线开头的受保护或私有成员;"
+ "12. 测试代码也需要满足编程规范约束;"
+ "如果 issue 指向受保护或私有方法,必须通过公开 API、用户可观察行为"
+ "或模块级公共函数间接验证。\n\n"
+ f"{code_rules}"
+ )
+
+ @staticmethod
+ def _normalized_label_set(issue: GitCodeIssue) -> set[str]:
+ return {label.strip().lower() for label in issue.labels if label.strip()}
+
+ @staticmethod
+ def _format_pull_request_info(pulls: list[dict[str, Any]]) -> str:
+ """Format PR info for display."""
+ if not pulls:
+ return ""
+ info_parts: list[str] = []
+ for pull in pulls[:3]: # Show max 3 PRs
+ state = str(pull.get("state") or pull.get("status") or "unknown").lower()
+ url = str(pull.get("html_url") or pull.get("url") or "")
+ number = pull.get("number") or pull.get("id") or ""
+ merged = bool(pull.get("merged") or pull.get("merge_status") == "merged")
+ status = "merged" if merged or state == "merged" else state
+ if url:
+ info_parts.append(f"PR #{number} ({status}): {url}")
+ return "; ".join(info_parts)
+
+ @classmethod
+ def assess_issue_difficulty(cls, issue: GitCodeIssue) -> dict[str, Any]:
+ """Conservative, explainable issue-fix difficulty assessment.
+
+ The goal is not to perfectly estimate engineering effort. It is to avoid
+ handing poorly scoped or high-blast-radius work to automation.
+ """
+ title = issue.title or ""
+ body = issue.body or ""
+ labels = cls._normalized_label_set(issue)
+ text = f"{title}\n{body}"
+ lower = text.lower()
+ reasons: list[str] = []
+ score = 0
+
+ body_len = len(body.strip())
+ if body_len < 80:
+ score += 4
+ reasons.append("issue 描述过短,缺少可执行细节")
+ elif body_len < 220:
+ score += 1
+ reasons.append("issue 描述较短,可能需要额外判断")
+
+ unclear_markers = (
+ "待补充",
+ "不清楚",
+ "无法复现",
+ "偶现",
+ "看情况",
+ "需要讨论",
+ "tbd",
+ "todo",
+ "not sure",
+ "unclear",
+ "unknown",
+ )
+ if any(marker in lower for marker in unclear_markers):
+ score += 4
+ reasons.append("描述包含不确定/待讨论信号")
+
+ high_impact_markers = (
+ "架构",
+ "重构",
+ "安全",
+ "漏洞",
+ "权限",
+ "认证",
+ "鉴权",
+ "协议",
+ "兼容",
+ "迁移",
+ "数据库",
+ "并发",
+ "性能优化",
+ "token消耗",
+ "全局",
+ "framework",
+ "architecture",
+ "refactor",
+ "security",
+ "auth",
+ "permission",
+ "migration",
+ "concurrency",
+ "performance",
+ )
+ impact_hits = [marker for marker in high_impact_markers if marker in lower]
+ if impact_hits:
+ score += min(5, len(impact_hits) * 2)
+ reasons.append("疑似影响面较大: " + ", ".join(impact_hits[:4]))
+
+ complex_markers = (
+ "设计思路",
+ "新增",
+ "支持",
+ "多端",
+ "前端配置",
+ "后端",
+ "api",
+ "sdk",
+ "mcp",
+ "大模型",
+ "上下文",
+ "feature",
+ "frontend",
+ "backend",
+ "protocol",
+ "integration",
+ )
+ complex_hits = [marker for marker in complex_markers if marker in lower]
+ if len(complex_hits) >= 3:
+ score += 2
+ reasons.append("涉及多个功能点/模块: " + ", ".join(complex_hits[:4]))
+
+ if "feature" in labels or "enhancement" in labels:
+ score += 2
+ reasons.append("feature 类 issue,默认比 bug 修复风险更高")
+ if labels.intersection({"bug", "good-first-issue", "easy"}):
+ score -= 1
+ if labels.intersection({"needs-discussion", "blocked", "wontfix"}):
+ score += 5
+ reasons.append("存在阻塞/需讨论标签")
+
+ mentioned_files = re.findall(
+ r"(?:^|[\s`\"'((])((?:jiuwenswarm|tests|openjiuwen|src|packages)/[^\s`\"',,。))]+)",
+ text,
+ )
+ if len(set(mentioned_files)) >= 5:
+ score += 2
+ reasons.append(f"描述涉及较多文件路径: {len(set(mentioned_files))} 个")
+
+ if score >= 7:
+ level = "high"
+ elif score >= 3:
+ level = "medium"
+ else:
+ level = "low"
+ if body_len < 80 or any(marker in lower for marker in ("不清楚", "unclear", "unknown", "待补充")):
+ level = "unclear" if score >= 4 else level
+ if not reasons:
+ reasons.append("描述较明确,影响面看起来可控")
+ return {
+ "level": level,
+ "score": score,
+ "reasons": reasons,
+ "needs_human": cls._DIFFICULTY_ORDER.get(level, 99) > cls._DIFFICULTY_ORDER["medium"],
+ }
+
+ @classmethod
+ def _is_difficulty_within_limit(cls, assessment: dict[str, Any], max_level: str) -> bool:
+ level = str(assessment.get("level") or "unclear")
+ return cls._DIFFICULTY_ORDER.get(level, 99) <= cls._DIFFICULTY_ORDER.get(max_level, 2)
+
+ @staticmethod
+ def _extract_pull_request_number_from_url(url: str) -> int | None:
+ match = re.search(r"/(?:pulls|pull_requests|merge_requests)/(\d+)(?:\D|$)", url)
+ if not match:
+ return None
+ try:
+ return int(match.group(1))
+ except ValueError:
+ return None
+
+ @classmethod
+ def _build_pull_request_record_from_url(cls, url: str) -> dict[str, Any] | None:
+ url = url.strip()
+ if not url.startswith("https://gitcode.com/"):
+ return None
+ if "/merge_requests/new?" in url:
+ return None
+ if not re.search(r"/(?:pulls|pull_requests|merge_requests)/\d+", url):
+ return None
+ result: dict[str, Any] = {"html_url": url, "url": url}
+ number = cls._extract_pull_request_number_from_url(url)
+ if number is not None:
+ result["number"] = number
+ return result
+
+ @classmethod
+ def _find_pull_request_in_task_log(cls, task: Optional[dict[str, Any]]) -> dict[str, Any] | None:
+ """Find a real PR/MR URL in the latest scheduled task log."""
+ if not task:
+ return None
+ history = task.get("execution_history") or []
+ for record in sorted(
+ history,
+ key=lambda item: item.get("completed_at") or item.get("started_at") or "",
+ reverse=True,
+ ):
+ log_path = Path(str(record.get("log_path") or ""))
+ if not log_path.exists():
+ continue
+ try:
+ lines = log_path.read_text(encoding="utf-8").splitlines()
+ except OSError:
+ continue
+ for line in reversed(lines):
+ try:
+ entry = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ text_parts = [
+ str(entry.get("content") or ""),
+ str(entry.get("message") or ""),
+ ]
+ text_parts.extend(str(item) for item in entry.get("messages") or [])
+ for text in text_parts:
+ for url in re.findall(r"https://gitcode\.com/[^\s)>\"]+", text):
+ pr = cls._build_pull_request_record_from_url(url)
+ if pr:
+ return pr
+ return None
+
+ async def _record_skipped_issue(
+ self,
+ options: IssueWatchOptions,
+ issue: GitCodeIssue,
+ reason: str,
+ ) -> dict[str, Any]:
+ await self._state_store.update(
+ options.owner,
+ options.repo,
+ issue.number,
+ {
+ "status": "skipped",
+ "title": issue.title,
+ "reason": reason,
+ },
+ )
+ return {"issue": issue.number, "status": "skipped", "reason": reason}
+
+ async def _record_issue_needs_human(
+ self,
+ options: IssueWatchOptions,
+ issue: GitCodeIssue,
+ assessment: dict[str, Any],
+ ) -> dict[str, Any]:
+ reason = "需要人工修复: " + ";".join(assessment.get("reasons") or [])
+ await self._state_store.update(
+ options.owner,
+ options.repo,
+ issue.number,
+ {
+ "status": "needs_human",
+ "title": issue.title,
+ "reason": reason,
+ "difficulty": assessment,
+ "human_label": "needs-human",
+ },
+ )
+ return {
+ "issue": issue.number,
+ "status": "needs_human",
+ "reason": reason,
+ "difficulty": assessment,
+ "human_label": "needs-human",
+ }
+
+ async def reconcile(self, options: IssueWatchOptions) -> list[dict[str, Any]]:
+ """Refresh stored issue records using task status and linked PRs."""
+
+ results: list[dict[str, Any]] = []
+ for record in self._state_store.list():
+ if record.get("owner") != options.owner or record.get("repo") != options.repo:
+ continue
+ status = str(record.get("status") or "")
+ if status not in self.RECONCILE_RECORD_STATUSES:
+ continue
+ number = int(record.get("number") or 0)
+ if number <= 0:
+ continue
+
+ # 对于已跳过记录,检查是否已在 GitCode 上关闭
+ if status == "skipped":
+ try:
+ issue = self._client.get_issue(owner=options.owner, repo=options.repo, number=number)
+ if issue.raw.get("state") == "closed":
+ updated = await self._state_store.update(
+ options.owner, options.repo, number,
+ {"status": "skipped", "reason": "issue已关闭"},
+ )
+ results.append(updated)
+ except Exception:
+ logger.warning(
+ f"[GitCodeIssueRunner] get issue failed, issue number: {number}"
+ )
+ pass
+ continue
+
+ task_id = str(record.get("task_id") or "")
+ task = await self._harness_service.get_scheduled_task_status(task_id) if task_id else None
+ task_status = str((task or {}).get("status") or "")
+ pulls = self._client.list_issue_pull_requests(owner=options.owner, repo=options.repo, number=number)
+ fallback_pr = self._find_pull_request_in_task_log(task)
+ if pulls or fallback_pr:
+ first = pulls[0] if pulls else (fallback_pr or {})
+ updated = await self._state_store.update(
+ options.owner,
+ options.repo,
+ number,
+ {
+ "status": "pr_created",
+ "task_status": task_status,
+ "pr_source": "gitcode_issue_links" if pulls else "auto_harness_log",
+ "pr_number": first.get("number") or first.get("id"),
+ "pr_url": first.get("html_url") or first.get("url"),
+ },
+ )
+ results.append(updated)
+ elif task_status in {"success", "failed", "cancelled"}:
+ updated = await self._state_store.update(
+ options.owner,
+ options.repo,
+ number,
+ {
+ "status": "completed_without_pr" if task_status == "success" else task_status,
+ "task_status": task_status,
+ },
+ )
+ results.append(updated)
+ elif task_id and task is None:
+ # 任务已被删除(日志/TaskStore 记录已清除),清理 issue 状态
+ await self._state_store.delete(options.owner, options.repo, number)
+ results.append({"deleted": True, "number": number})
+ return results
+
+ async def process_issues_once(self, options: IssueWatchOptions) -> dict[str, Any]:
+ """Fetch eligible issues and create one-time auto-harness tasks."""
+
+ reconciled = await self.reconcile(options)
+ started: list[dict[str, Any]] = []
+ skipped: list[dict[str, Any]] = []
+ if options.issue_numbers:
+ issues = []
+ for number in options.issue_numbers:
+ issue = self._client.get_issue(owner=options.owner, repo=options.repo, number=number)
+ if issue.raw.get("state") == "closed":
+ skipped.append(await self._record_skipped_issue(options, issue, "issue已关闭"))
+ else:
+ issues.append(issue)
+ else:
+ issues = self._client.list_issues(
+ owner=options.owner,
+ repo=options.repo,
+ state="open",
+ labels=list(options.labels),
+ per_page=options.per_page,
+ )
+ required_labels = {label.lower() for label in options.labels if label}
+ blocked_labels = {label.lower() for label in options.exclude_labels if label}
+ max_issues = len(options.issue_numbers) if options.issue_numbers else options.max_issues
+
+ for index, issue in enumerate(issues):
+ if len(started) >= max_issues:
+ break
+ if issue.number <= 0:
+ continue
+
+ labels = self._normalized_label_set(issue)
+ if not options.issue_numbers and required_labels and not required_labels.issubset(labels):
+ skipped.append(await self._record_skipped_issue(options, issue, "missing required labels"))
+ continue
+ if blocked_labels.intersection(labels):
+ skipped.append(await self._record_skipped_issue(options, issue, "excluded label present"))
+ continue
+
+ previous = self._state_store.get(options.owner, options.repo, issue.number)
+ previous_status = str((previous or {}).get("status") or "")
+ if previous_status in self.TERMINAL_RECORD_STATUSES | self.IN_FLIGHT_RECORD_STATUSES:
+ skipped.append({"issue": issue.number, "status": "skipped", "reason": previous_status})
+ continue
+ if previous_status == "completed_without_pr":
+ skipped.append({"issue": issue.number, "status": "skipped", "reason": previous_status})
+ continue
+
+ pulls = self._client.list_issue_pull_requests(
+ owner=options.owner,
+ repo=options.repo,
+ number=issue.number,
+ )
+
+ if pulls:
+ pr_info = self._format_pull_request_info(pulls)
+ skipped.append(await self._record_skipped_issue(
+ options,
+ issue,
+ f"issue 已有关联 PR: {pr_info}",
+ ))
+ continue
+
+ assessment = self.assess_issue_difficulty(issue)
+ if not self._is_difficulty_within_limit(assessment, options.max_auto_difficulty):
+ skipped.append(await self._record_issue_needs_human(options, issue, assessment))
+ continue
+
+ query = self.build_issue_fix_query(issue, owner=options.owner, repo=options.repo)
+ repo_url = f"https://gitcode.com/{options.owner}/{options.repo}.git"
+ task = build_issue_fix_task(issue.number, query)
+ if options.dry_run:
+ started.append({
+ "issue": issue.number,
+ "status": "dry_run",
+ "query": query,
+ "difficulty": assessment,
+ })
+ continue
+
+ record = await self._state_store.update(
+ options.owner,
+ options.repo,
+ issue.number,
+ {
+ "status": "running",
+ "title": issue.title,
+ "issue_url": issue.html_url,
+ "labels": list(issue.labels),
+ "pipeline": options.pipeline,
+ "difficulty": assessment,
+ },
+ )
+ result = await self._harness_service.run_task(
+ query,
+ pipeline=options.pipeline,
+ optimization_task=task,
+ repo_url=repo_url,
+ )
+ updates = {
+ "status": "task_created",
+ "task_id": result.get("task_id"),
+ "task_message": result.get("message"),
+ }
+ if result.get("error"):
+ updates.update({"status": "failed", "last_error": result.get("error")})
+ record = await self._state_store.update(options.owner, options.repo, issue.number, updates)
+ if options.comment_on_start and not result.get("error"):
+ self._client.create_issue_comment(
+ owner=options.owner,
+ repo=options.repo,
+ number=issue.number,
+ body=f"auto-harness 已开始处理该 issue,任务 ID: {result.get('task_id')}",
+ )
+ started.append(record)
+ if (
+ options.start_interval_seconds > 0
+ and index < len(issues) - 1
+ and len(started) < max_issues
+ ):
+ await asyncio.sleep(options.start_interval_seconds)
+
+ return {
+ "owner": options.owner,
+ "repo": options.repo,
+ "fetched": len(issues),
+ "started": started,
+ "skipped": skipped,
+ "reconciled": reconciled,
+ }
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/issue_state_store.py b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/issue_state_store.py
new file mode 100644
index 0000000000..e1f03b8983
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/issue_state_store.py
@@ -0,0 +1,87 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Persistent state for GitCode issue auto-harness runs."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Optional
+
+
+def _write_json(path: Path, payload: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(payload, encoding="utf-8")
+
+
+class IssueStateStore:
+ """Stores issue processing state to avoid duplicate auto-harness runs."""
+
+ def __init__(self, data_dir: Path) -> None:
+ self._path = data_dir / "issue" / "gitcode-issues-status.json"
+ self._cache: Optional[dict[str, Any]] = None
+ self._save_lock = asyncio.Lock()
+
+ def _load(self) -> dict[str, Any]:
+ if self._cache is not None:
+ return self._cache
+ if not self._path.exists():
+ self._cache = {"issues": {}, "last_updated": None}
+ return self._cache
+ try:
+ loaded = json.loads(self._path.read_text(encoding="utf-8"))
+ except Exception:
+ loaded = {"issues": {}, "last_updated": None}
+ if not isinstance(loaded, dict):
+ loaded = {"issues": {}, "last_updated": None}
+ loaded.setdefault("issues", {})
+ self._cache = loaded
+ return loaded
+
+ async def _save(self, data: dict[str, Any]) -> None:
+ data["last_updated"] = datetime.now(timezone.utc).isoformat()
+ self._cache = data
+ payload = json.dumps(data, ensure_ascii=False, indent=2)
+ async with self._save_lock:
+ await asyncio.to_thread(_write_json, self._path, payload)
+
+ @staticmethod
+ def issue_key(owner: str, repo: str, number: int) -> str:
+ return f"{owner}/{repo}#{number}"
+
+ def get(self, owner: str, repo: str, number: int) -> Optional[dict[str, Any]]:
+ return self._load().get("issues", {}).get(self.issue_key(owner, repo, number))
+
+ def list(self) -> list[dict[str, Any]]:
+ issues = self._load().get("issues", {})
+ if not isinstance(issues, dict):
+ return []
+ return list(issues.values())
+
+ async def update(self, owner: str, repo: str, number: int, updates: dict[str, Any]) -> dict[str, Any]:
+ data = self._load()
+ issues = data.setdefault("issues", {})
+ key = self.issue_key(owner, repo, number)
+ record = dict(issues.get(key) or {})
+ record.update(updates)
+ record["key"] = key
+ record["owner"] = owner
+ record["repo"] = repo
+ record["number"] = number
+ record["updated_at"] = datetime.now(timezone.utc).isoformat()
+ issues[key] = record
+ await self._save(data)
+ return record
+
+ async def delete(self, owner: str, repo: str, number: int) -> bool:
+ """删除指定 issue 的处理记录。"""
+ data = self._load()
+ issues = data.setdefault("issues", {})
+ key = self.issue_key(owner, repo, number)
+ if key not in issues:
+ return False
+ del issues[key]
+ await self._save(data)
+ return True
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/run_progress.py b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/run_progress.py
new file mode 100644
index 0000000000..543f67b5de
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/run_progress.py
@@ -0,0 +1,72 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Issue-fix run-log status extensions."""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+_LEGACY_SKIP_STAGE_MARKERS = {
+ "显式 GitCode issue 修复任务,跳过 assess/plan": ("assess", "plan"),
+}
+
+
+def infer_issue_fix_skipped_stages(content: str) -> tuple[str, ...]:
+ """Normalize issue-fix legacy skip messages into structured skipped stages."""
+ return next(
+ (
+ stages for marker, stages in _LEGACY_SKIP_STAGE_MARKERS.items()
+ if marker in content
+ ),
+ (),
+ )
+
+
+def _extract_gitcode_pr_url(text: str) -> str:
+ for url in re.findall(r"https://gitcode\.com/[^\s)>\"]+", text):
+ if re.search(r"/(?:pulls|pull_requests|merge_requests)/\d+", url):
+ return url
+ return ""
+
+
+def _classify_issue_fix_failure(error: str, last_message: str = "") -> str:
+ text = f"{error}\n{last_message}".lower()
+ if "missing required labels" in text:
+ return "missing_required_labels"
+ if (
+ "gitcode pr creation failed" in text
+ or "http error 400" in text
+ or "bad request" in text
+ ):
+ return "pr_api_failed"
+ return ""
+
+
+def enrich_issue_fix_progress(
+ progress: dict[str, Any],
+ logs: list[dict[str, Any]],
+) -> dict[str, Any]:
+ """Add GitCode issue-fix specific diagnostics to generic progress."""
+ enriched = dict(progress)
+ pr_url = str(enriched.get("pr_url") or "")
+ for entry in logs:
+ text_parts = [
+ str(entry.get("content") or ""),
+ str(entry.get("message") or ""),
+ ]
+ text_parts.extend(str(message) for message in entry.get("messages") or [])
+ for text in text_parts:
+ if not pr_url:
+ pr_url = _extract_gitcode_pr_url(text)
+ if pr_url:
+ enriched["pr_url"] = pr_url
+
+ if enriched.get("failed_stage"):
+ issue_failure_code = _classify_issue_fix_failure(
+ str(enriched.get("last_error") or ""),
+ str(enriched.get("last_message") or ""),
+ )
+ if issue_failure_code:
+ enriched["failure_code"] = issue_failure_code
+ return enriched
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/service.py b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/service.py
new file mode 100644
index 0000000000..c3cc4afbc3
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/service.py
@@ -0,0 +1,532 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Issue-fix facade that keeps GitCode issue handling out of core service."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+from openjiuwen.auto_harness.pipelines import META_EVOLVE_PIPELINE
+from openjiuwen.core.foundation.llm import Model
+
+from .gitcode_issue_client import GitCodeIssueClient
+from .issue_matrix_store import IssueMatrixStore
+from .issue_runner import GitCodeIssueRunner, IssueWatchOptions
+from .issue_state_store import IssueStateStore
+
+
+# Running 状态不允许删除
+RUNNING_STATUSES = {"running", "task_created", "queued", "pending"}
+
+
+class IssueFixService:
+ """Coordinates GitCode issue ingestion as an auto-harness capability."""
+
+ def __init__(
+ self,
+ *,
+ task_store: Any,
+ issue_state_store: IssueStateStore,
+ issue_matrix_store: IssueMatrixStore,
+ harness_service: Any,
+ base_config_getter: Callable[[], Any],
+ default_repo_url: str,
+ ) -> None:
+ self._task_store = task_store
+ self._issue_state_store = issue_state_store
+ self._issue_matrix_store = issue_matrix_store
+ self._harness_service = harness_service
+ self._base_config_getter = base_config_getter
+ self._default_repo_url = default_repo_url
+
+ async def handle(
+ self,
+ action: str,
+ params: dict[str, Any],
+ model: Optional[Model] = None,
+ ) -> dict[str, Any]:
+ """Dispatch issue-fix capability actions."""
+ if action in {"process_once", "watch_once"}:
+ return await self.process_gitcode_issues_once(params, model)
+ if action in {"state_list", "list_states"}:
+ return await self.list_gitcode_issue_states()
+ if action == "delete":
+ return await self.delete_issue_states(params)
+ if action == "matrix":
+ return await self.refresh_issue_matrix(params)
+ return {"error": f"未知 issue-fix 操作: {action}"}
+
+ @staticmethod
+ def _parse_repo_identifier(repo: str) -> tuple[str, str]:
+ """Parse owner/repo from a GitCode URL or owner/repo string."""
+ raw = str(repo or "").strip()
+ if not raw:
+ return ("", "")
+ cleaned = raw.rstrip("/")
+ if cleaned.endswith(".git"):
+ cleaned = cleaned[:-4]
+ parts = [part for part in cleaned.split("/") if part]
+ if len(parts) >= 2:
+ return (parts[-2], parts[-1])
+ return ("", "")
+
+ def _resolve_target_repo(self, params: dict[str, Any]) -> tuple[str, str]:
+ owner = str(params.get("owner") or "").strip()
+ repo = str(params.get("repo_name") or "").strip()
+ if owner and repo:
+ return (owner, repo)
+ repo_param = str(params.get("repo") or "").strip()
+ if repo_param:
+ parsed_owner, parsed_repo = self._parse_repo_identifier(repo_param)
+ if parsed_owner and parsed_repo:
+ return (parsed_owner, parsed_repo)
+ base_config = self._base_config_getter()
+ repo_url = (
+ base_config.repo_url
+ if base_config is not None and base_config.repo_url
+ else self._default_repo_url
+ )
+ return self._parse_repo_identifier(repo_url)
+
+ def _resolve_access_token(self, params: dict[str, Any]) -> str:
+ token = str(params.get("access_token") or "").strip()
+ if token:
+ return token
+ env_token = os.getenv("GITCODE_ACCESS_TOKEN")
+ if env_token:
+ return env_token.strip()
+ base_config = self._base_config_getter()
+ if base_config is not None:
+ try:
+ return str(base_config.resolve_gitcode_token() or "").strip()
+ except Exception:
+ pass
+ return ""
+
+ @staticmethod
+ def _parse_string_tuple(value: Any, default: tuple[str, ...]) -> tuple[str, ...]:
+ if value is None:
+ return default
+ if isinstance(value, str):
+ return tuple(part.strip() for part in value.split(",") if part.strip())
+ if isinstance(value, list | tuple):
+ return tuple(str(part).strip() for part in value if str(part).strip())
+ return default
+
+ @staticmethod
+ def _parse_issue_numbers(value: Any) -> tuple[int, ...]:
+ if value is None:
+ return ()
+ raw_parts: list[Any]
+ if isinstance(value, str):
+ raw_parts = [part.strip() for part in value.replace(",", ",").split(",")]
+ elif isinstance(value, int):
+ raw_parts = [value]
+ elif isinstance(value, list | tuple):
+ raw_parts = list(value)
+ else:
+ return ()
+
+ numbers: list[int] = []
+ for part in raw_parts:
+ try:
+ number = int(part)
+ except (TypeError, ValueError):
+ continue
+ if number > 0 and number not in numbers:
+ numbers.append(number)
+ return tuple(numbers)
+
+ async def process_gitcode_issues_once(
+ self,
+ params: dict[str, Any],
+ model: Optional[Model] = None,
+ ) -> dict[str, Any]:
+ """Process GitCode issues once and create auto-harness tasks."""
+ del model
+ token = self._resolve_access_token(params)
+ if not token:
+ return {"error": "缺少 GitCode Access Token,请配置 gitcode.access_token 或 GITCODE_ACCESS_TOKEN"}
+
+ owner, repo = self._resolve_target_repo(params)
+ if not owner or not repo:
+ return {"error": "无法解析 GitCode 仓库,请传入 repo=openJiuwen/jiuwenswarm"}
+
+ try:
+ max_issues = int(params.get("max_issues", 1))
+ except (TypeError, ValueError):
+ max_issues = 1
+ max_issues = max(1, min(max_issues, 5))
+
+ try:
+ per_page = int(params.get("per_page", 20))
+ except (TypeError, ValueError):
+ per_page = 20
+ per_page = max(1, min(per_page, 100))
+
+ pipeline = str(params.get("pipeline") or META_EVOLVE_PIPELINE)
+ issue_numbers = self._parse_issue_numbers(
+ params.get("issue_numbers")
+ or params.get("issues")
+ or params.get("issue")
+ or params.get("numbers")
+ )
+ if issue_numbers:
+ max_issues = len(issue_numbers)
+ try:
+ start_interval_seconds = float(params.get("start_interval_seconds", 0) or 0)
+ except (TypeError, ValueError):
+ start_interval_seconds = 0.0
+ if start_interval_seconds <= 0 and max_issues > 1:
+ # openjiuwen auto_harness currently uses second-level timestamps
+ # for some readonly worktree paths. Stagger immediate issue tasks
+ # to avoid "worktree already exists" collisions.
+ start_interval_seconds = 1.2
+ options = IssueWatchOptions(
+ owner=owner,
+ repo=repo,
+ issue_numbers=issue_numbers,
+ labels=self._parse_string_tuple(params.get("labels"), ("auto-harness",)),
+ exclude_labels=self._parse_string_tuple(
+ params.get("exclude_labels"),
+ ("blocked", "wontfix", "needs-discussion"),
+ ),
+ max_issues=max_issues,
+ per_page=per_page,
+ pipeline=pipeline,
+ comment_on_start=bool(params.get("comment_on_start", False)),
+ dry_run=bool(params.get("dry_run", False)),
+ start_interval_seconds=start_interval_seconds,
+ max_auto_difficulty=str(params.get("max_auto_difficulty") or "medium"),
+ )
+ client = GitCodeIssueClient(token=token)
+ runner = GitCodeIssueRunner(
+ client=client,
+ state_store=self._issue_state_store,
+ harness_service=self._harness_service,
+ )
+ return await runner.process_issues_once(options)
+
+ async def list_gitcode_issue_states(self) -> dict[str, Any]:
+ issues = []
+ for issue in self._issue_state_store.list():
+ enriched = dict(issue)
+ task_id = str(enriched.get("task_id") or "")
+ if task_id:
+ task = self._task_store.get_task(task_id)
+ if task is not None:
+ task_status = str(task.get("status") or "")
+ enriched["task_status"] = task_status
+ enriched["progress"] = await self._task_store.summarize_task_progress(task)
+
+ # 轻量 reconcile:TaskStore 已是终态但 IssueState 仍显示进行中,
+ # 同步 IssueState 反映真实状态(不检查 PR,留待 fix reconcile 处理)
+ issue_status = str(issue.get("status") or "")
+ if issue_status in {"running", "task_created"} \
+ and task_status in {"success", "failed", "cancelled"}:
+ new_status = "completed_without_pr" if task_status == "success" else task_status
+ await self._issue_state_store.update(
+ issue.get("owner", ""),
+ issue.get("repo", ""),
+ issue.get("number", 0),
+ {"status": new_status, "task_status": task_status},
+ )
+ enriched["status"] = new_status
+ else:
+ # 任务已不存在(被删除),标记以清理
+ enriched["task_status"] = "task_deleted"
+ enriched["reason"] = "任务记录已删除"
+ issues.append(enriched)
+ return {"issues": issues}
+
+ async def delete_issue_states(self, params: dict[str, Any]) -> dict[str, Any]:
+ """删除 issue 处理记录和运行日志,running 状态不允许删除。"""
+ deleted: list[dict[str, Any]] = []
+ rejected: list[dict[str, Any]] = []
+
+ issue_numbers = self._parse_issue_numbers(params.get("issue_numbers"))
+ delete_completed = bool(params.get("delete_completed", False))
+ delete_failed = bool(params.get("delete_failed", False))
+
+ # 获取所有 issue 记录
+ all_issues = self._issue_state_store.list()
+
+ # 确定要删除的 issue
+ targets: list[dict[str, Any]] = []
+ if issue_numbers:
+ # 指定编号删除
+ for issue in all_issues:
+ number = int(issue.get("number") or 0)
+ if number in issue_numbers:
+ targets.append(issue)
+ if delete_completed:
+ # 删除所有已完成的记录
+ terminal_statuses = {"success", "pr_created", "completed", "completed_without_pr"}
+ for issue in all_issues:
+ status = str(issue.get("status") or "")
+ if status in terminal_statuses and issue not in targets:
+ targets.append(issue)
+ if delete_failed:
+ # 删除所有失败的记录
+ failed_statuses = {"failed", "cancelled"}
+ for issue in all_issues:
+ status = str(issue.get("status") or "")
+ if status in failed_statuses and issue not in targets:
+ targets.append(issue)
+
+ # 执行删除
+ for issue in targets:
+ number = int(issue.get("number") or 0)
+ owner = str(issue.get("owner") or "")
+ repo = str(issue.get("repo") or "")
+ task_id = str(issue.get("task_id") or "")
+ status = str(issue.get("status") or "")
+
+ # 检查是否正在运行
+ if status in RUNNING_STATUSES:
+ # 如果 task_id 引用的任务已不存在,说明状态是残留的,允许删除
+ if task_id and self._task_store.get_task(task_id) is None:
+ pass
+ else:
+ rejected.append({
+ "issue": number,
+ "reason": f"任务正在执行中 (status: {status}),运行中的任务不支持删除",
+ })
+ continue
+
+ # 检查任务状态(如果有 task_id)
+ if task_id:
+ task = self._task_store.get_task(task_id)
+ if task and str(task.get("status") or "") in RUNNING_STATUSES:
+ rejected.append({
+ "issue": number,
+ "reason": f"任务正在执行中,运行中的任务不支持删除",
+ })
+ continue
+
+ # 删除 IssueStateStore 记录
+ try:
+ await self._issue_state_store.delete(owner, repo, number)
+ except Exception:
+ pass # Best effort
+
+ # 删除 TaskStore 任务记录
+ if task_id:
+ try:
+ await self._task_store.delete_task(task_id)
+ except Exception:
+ pass # Best effort
+
+ deleted.append({
+ "issue": number,
+ "task_id": task_id if task_id else None,
+ })
+
+ return {"deleted": deleted, "rejected": rejected}
+
+ async def refresh_issue_matrix(self, params: dict[str, Any]) -> dict[str, Any]:
+ """Refresh issue matrix with incremental updates.
+
+ Fetches all open issues, compares with cached matrix, and updates:
+ - New issues: analyze and add to matrix
+ - Closed issues: remove from matrix
+ - Updated issues: re-analyze if content changed
+
+ If force_refresh=False and cache exists, returns cache directly (no API call).
+ Labels filter is applied on cached/API results without forcing refresh.
+ """
+ token = self._resolve_access_token(params)
+ if not token:
+ return {"error": "缺少 GitCode Access Token,请配置 gitcode.access_token 或 GITCODE_ACCESS_TOKEN"}
+
+ owner, repo = self._resolve_target_repo(params)
+ if not owner or not repo:
+ return {"error": "无法解析 GitCode 仓库,请传入 repo=openJiuwen/jiuwenswarm"}
+
+ force_refresh = bool(params.get("force_refresh", False))
+ page = int(params.get("page", 1) or 1)
+ page = max(1, page)
+ per_page = int(params.get("per_page", 50) or 50)
+ per_page = max(1, min(per_page, 100))
+
+ # Parse labels filter (comma-separated, lowercase for matching)
+ labels_filter = self._parse_string_tuple(params.get("labels"), ())
+ labels_filter_lower = {label.lower() for label in labels_filter}
+
+ # Load cached matrix
+ cached_data = self._issue_matrix_store.load(owner, repo)
+ cached_matrix = cached_data.get("matrix", [])
+
+ # If not forcing refresh and cache exists, return cache directly (with label filtering)
+ if not force_refresh and cached_matrix:
+ # Apply labels filter on cached results
+ filtered_matrix = cached_matrix
+ if labels_filter_lower:
+ filtered_matrix = [
+ entry for entry in cached_matrix
+ if any(label.lower() in labels_filter_lower for label in (entry.get("labels") or []))
+ ]
+
+ # Build statistics from filtered cache
+ difficulty_counts: dict[str, int] = {}
+ for entry in filtered_matrix:
+ diff = entry.get("difficulty", "unclear")
+ difficulty_counts[diff] = difficulty_counts.get(diff, 0) + 1
+
+ # Paginate filtered results
+ total = len(filtered_matrix)
+ start_idx = (page - 1) * per_page
+ end_idx = start_idx + per_page
+ page_matrix = filtered_matrix[start_idx:end_idx]
+
+ return {
+ "owner": owner,
+ "repo": repo,
+ "total": total,
+ "added": 0,
+ "removed": 0,
+ "updated": 0,
+ "difficulty_counts": difficulty_counts,
+ "matrix": page_matrix,
+ "has_more": end_idx < total,
+ "page": page,
+ "per_page": per_page,
+ "cached": True,
+ "labels_filter": list(labels_filter) if labels_filter else [],
+ }
+
+ # Force refresh: call API and update cache
+ client = GitCodeIssueClient(token=token)
+
+ # Fetch all open issues from GitCode
+ api_issues = client.list_all_issues(owner=owner, repo=repo, state="open")
+
+ # Build cached issue dict for comparison
+ cached_by_number: dict[int, dict[str, Any]] = {
+ entry.get("number"): entry for entry in cached_matrix if entry.get("number")
+ }
+
+ # Three-set comparison
+ api_numbers = set(api_issues.keys())
+ cached_numbers = set(cached_by_number.keys())
+
+ added_numbers = api_numbers - cached_numbers
+ removed_numbers = cached_numbers - api_numbers
+ common_numbers = api_numbers & cached_numbers
+
+ # Process additions
+ added_entries: list[dict[str, Any]] = []
+ for number in added_numbers:
+ issue = api_issues[number]
+ assessment = GitCodeIssueRunner.assess_issue_difficulty(issue)
+ entry = {
+ "number": number,
+ "title": issue.title,
+ "body": issue.body[:200] if issue.body else "", # Truncate for storage
+ "labels": list(issue.labels),
+ "difficulty": assessment.get("level", "unclear"),
+ "updated_at": str(issue.raw.get("updated_at") or ""),
+ "first_seen": _now_iso(),
+ "last_analyzed": _now_iso(),
+ }
+ added_entries.append(entry)
+
+ # Process updates (check for content changes)
+ updated_entries: list[dict[str, Any]] = []
+ for number in common_numbers:
+ issue = api_issues[number]
+ cached_entry = cached_by_number[number]
+
+ # Check if content changed (title, labels, or updated_at)
+ if force_refresh or _has_content_change(issue, cached_entry):
+ assessment = GitCodeIssueRunner.assess_issue_difficulty(issue)
+ cached_entry["title"] = issue.title
+ cached_entry["body"] = issue.body[:200] if issue.body else ""
+ cached_entry["labels"] = list(issue.labels)
+ cached_entry["difficulty"] = assessment.get("level", "unclear")
+ cached_entry["updated_at"] = str(issue.raw.get("updated_at") or "")
+ cached_entry["last_analyzed"] = _now_iso()
+ updated_entries.append(cached_entry)
+
+ # Build new matrix
+ new_matrix: list[dict[str, Any]] = []
+ for number in api_numbers:
+ if number in added_numbers:
+ # Find the added entry
+ for entry in added_entries:
+ if entry.get("number") == number:
+ new_matrix.append(entry)
+ break
+ elif number in common_numbers:
+ # Use cached entry (possibly updated)
+ new_matrix.append(cached_by_number[number])
+
+ # Sort by updated_at descending (most recent first)
+ new_matrix.sort(key=lambda e: e.get("updated_at") or "", reverse=True)
+
+ # Save updated matrix (full matrix, no label filtering in storage)
+ new_data = {
+ "total_open": len(new_matrix),
+ "matrix": new_matrix,
+ }
+ self._issue_matrix_store.save(owner, repo, new_data)
+
+ # Apply labels filter on fresh results (after saving to cache)
+ filtered_matrix = new_matrix
+ if labels_filter_lower:
+ filtered_matrix = [
+ entry for entry in new_matrix
+ if any(label.lower() in labels_filter_lower for label in (entry.get("labels") or []))
+ ]
+
+ # Build statistics from filtered results
+ difficulty_counts: dict[str, int] = {}
+ for entry in filtered_matrix:
+ diff = entry.get("difficulty", "unclear")
+ difficulty_counts[diff] = difficulty_counts.get(diff, 0) + 1
+
+ # Paginate filtered results
+ total = len(filtered_matrix)
+ start_idx = (page - 1) * per_page
+ end_idx = start_idx + per_page
+ page_matrix = filtered_matrix[start_idx:end_idx]
+
+ return {
+ "owner": owner,
+ "repo": repo,
+ "total": total,
+ "added": len(added_numbers),
+ "removed": len(removed_numbers),
+ "updated": len(updated_entries),
+ "difficulty_counts": difficulty_counts,
+ "matrix": page_matrix,
+ "has_more": end_idx < total,
+ "page": page,
+ "per_page": per_page,
+ "cached": False,
+ "labels_filter": list(labels_filter) if labels_filter else [],
+ }
+
+
+def _now_iso() -> str:
+ """Return current UTC time as ISO string."""
+ from datetime import datetime, timezone
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _has_content_change(issue: Any, cached: dict[str, Any]) -> bool:
+ """Check if issue content has changed since last analysis."""
+ if issue.title != cached.get("title"):
+ return True
+ cached_labels = set(cached.get("labels") or [])
+ current_labels = set(issue.labels)
+ if cached_labels != current_labels:
+ return True
+ # Check updated_at if available
+ cached_updated = cached.get("updated_at") or ""
+ current_updated = str(issue.raw.get("updated_at") or "")
+ if current_updated and cached_updated and current_updated != cached_updated:
+ return True
+ return False
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/task_factory.py b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/task_factory.py
new file mode 100644
index 0000000000..04403ea58f
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/issue_fix/task_factory.py
@@ -0,0 +1,17 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Task construction helpers for GitCode issue-fix runs."""
+
+from __future__ import annotations
+
+from openjiuwen.auto_harness.schema import OptimizationTask
+
+
+def build_issue_fix_task(issue_number: int, query: str) -> OptimizationTask:
+ """Build a structured auto-harness task for one GitCode issue."""
+ return OptimizationTask(
+ topic=f"fix-issue-{issue_number}",
+ description=query,
+ issue_ref=f"#{issue_number}",
+ status="pending",
+ )
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/repo_auth/__init__.py b/jiuwenswarm/agents/harness/common/auto_harness/repo_auth/__init__.py
new file mode 100644
index 0000000000..498b976794
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/repo_auth/__init__.py
@@ -0,0 +1,7 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Repository authentication helpers for auto-harness."""
+
+from .gitcode import configure_gitcode_auth
+
+__all__ = ["configure_gitcode_auth"]
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/repo_auth/gitcode.py b/jiuwenswarm/agents/harness/common/auto_harness/repo_auth/gitcode.py
new file mode 100644
index 0000000000..384350d248
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/repo_auth/gitcode.py
@@ -0,0 +1,64 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""GitCode repository authentication helpers."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+
+async def _run_git_config_secret(
+ args: list[str],
+ cwd: Path,
+) -> tuple[int, str, str]:
+ """Run a git config command that may contain secrets.
+
+ Keep this separate from normal git command logging so failures never log the
+ command arguments, which may include an Authorization header.
+ """
+ try:
+ process = await asyncio.create_subprocess_exec(
+ "git",
+ *args,
+ cwd=str(cwd),
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ stdout, stderr = await process.communicate()
+ return (
+ process.returncode or 0,
+ stdout.decode("utf-8", errors="replace"),
+ stderr.decode("utf-8", errors="replace"),
+ )
+ except Exception as exc:
+ logger.error("[GitCodeAuth] Secret git config command failed: %s", exc)
+ return (1, "", str(exc))
+
+
+async def configure_gitcode_auth(
+ local_path: Path,
+ *,
+ username: str,
+ token: str,
+ push_remote: str,
+) -> None:
+ """Configure non-interactive GitCode auth for agent-run git commands."""
+ if not username or not token:
+ return
+ await _run_git_config_secret(["config", "credential.helper", ""], local_path)
+ await _run_git_config_secret(["config", "credential.interactive", "never"], local_path)
+ await _run_git_config_secret(
+ [
+ "config",
+ "--unset-all",
+ "http.https://gitcode.com/.extraheader",
+ ],
+ local_path,
+ )
+ await _run_git_config_secret(["config", "push.default", "current"], local_path)
+ if push_remote:
+ await _run_git_config_secret(["config", "remote.pushDefault", push_remote], local_path)
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/run_log_status.py b/jiuwenswarm/agents/harness/common/auto_harness/run_log_status.py
new file mode 100644
index 0000000000..46cb96643c
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/auto_harness/run_log_status.py
@@ -0,0 +1,438 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Structured run-log status helpers for scheduled auto-harness tasks."""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import Any, Callable
+
+logger = logging.getLogger(__name__)
+
+META_EVOLVE_STAGE_ORDER = [
+ "assess",
+ "plan",
+ "implement",
+ "verify",
+ "commit",
+ "publish",
+ "learnings",
+]
+
+STAGE_DISPLAY_NAMES = {
+ "assess": "评估",
+ "plan": "规划",
+ "implement": "实现",
+ "verify": "验证",
+ "commit": "提交",
+ "publish": "发布 PR",
+ "learnings": "经验总结",
+ "build_verify": "构建验证",
+ "activate": "激活",
+}
+
+SkippedStageInferer = Callable[[str], tuple[str, ...]]
+ProgressEnricher = Callable[[dict[str, Any], list[dict[str, Any]]], dict[str, Any]]
+
+
+def infer_skipped_stages_from_message(
+ content: str,
+ inferers: list[SkippedStageInferer] | None = None,
+) -> tuple[str, ...]:
+ """Infer skipped stages with optional scenario-specific extensions."""
+ skipped: list[str] = []
+ for inferer in inferers or []:
+ for stage in inferer(content):
+ if stage not in skipped:
+ skipped.append(stage)
+ return tuple(skipped)
+
+
+def classify_failure(error: str, last_message: str = "") -> str:
+ """Return a stable failure code suitable for compact UI display."""
+ text = f"{error}\n{last_message}".lower()
+ if (
+ "no allowed files" in text
+ or "no changes" in text
+ or "did not create a new commit" in text
+ ):
+ return "no_effective_diff"
+ if "git branch push failed" in text or "push failed" in text:
+ return "push_rejected"
+ verify_failed_keywords = ["lint", "type-check", "ci", "verify"]
+ if any(k in text for k in verify_failed_keywords):
+ return "verify_failed"
+ if "file must be read before editing" in text or "tool" in text:
+ return "agent_tool_error"
+ return "unknown_failure"
+
+
+def resolve_latest_task_log_path(task: dict[str, Any], runs_dir: Path) -> Path | None:
+ """Resolve the latest existing run log for a scheduled task record."""
+ task_id = str(task.get("task_id") or "")
+ current_execution_id = str(task.get("current_execution_id") or "")
+ if task_id and current_execution_id:
+ current = runs_dir / task_id / current_execution_id / "log.json"
+ if current.exists():
+ return current
+
+ history = task.get("execution_history") or []
+ sorted_history = sorted(
+ history,
+ key=lambda r: r.get("completed_at") or r.get("started_at") or "",
+ reverse=True,
+ )
+ for record in sorted_history:
+ candidates: list[Path] = []
+ log_path_str = str(record.get("log_path") or "")
+ if log_path_str:
+ candidates.append(Path(log_path_str))
+ execution_id = str(record.get("execution_id") or "")
+ if task_id and execution_id:
+ candidates.append(runs_dir / task_id / execution_id / "log.json")
+ for candidate in candidates:
+ if candidate.exists():
+ return candidate
+ return None
+
+
+def format_progress_summary(progress: dict[str, Any]) -> str:
+ failed_stage = progress.get("failed_stage")
+ current_stage = progress.get("current_stage")
+ completed = progress.get("completed_stages") or []
+ total = len(progress.get("stages") or [])
+ if failed_stage:
+ return f"失败于 {STAGE_DISPLAY_NAMES.get(failed_stage, failed_stage)}"
+ if current_stage:
+ current_stage_name = STAGE_DISPLAY_NAMES.get(current_stage, current_stage)
+ return f"{len(completed)}/{total} 已完成,正在 {current_stage_name}"
+ if total and len(completed) >= total:
+ return f"{len(completed)}/{total} 已完成"
+ if total:
+ return f"{len(completed)}/{total} 已完成"
+ return "暂无阶段日志"
+
+
+def summarize_progress_from_logs(
+ logs: list[dict[str, Any]],
+ *,
+ skipped_stage_inferers: list[SkippedStageInferer] | None = None,
+ progress_enrichers: list[ProgressEnricher] | None = None,
+) -> dict[str, Any]:
+ """Summarize stage progress from structured harness logs."""
+ pipeline = ""
+ stage_order: list[str] = []
+ stage_status: dict[str, str] = {}
+ stage_messages: dict[str, list[str]] = {}
+ last_stage_message = ""
+ last_message_stage = ""
+ last_event_type = ""
+ last_error = ""
+
+ for entry in logs:
+ event_type = str(entry.get("event_type") or "")
+ last_event_type = event_type or last_event_type
+ if event_type == "harness.message":
+ if entry.get("pipeline") and entry.get("stages"):
+ pipeline = str(entry.get("pipeline") or pipeline)
+ stage_order = [
+ str(stage.get("slot") or "")
+ for stage in entry.get("stages") or []
+ if stage.get("slot")
+ ]
+ stage = str(entry.get("stage") or "")
+ content = str(entry.get("content") or "")
+ for skipped_stage in infer_skipped_stages_from_message(content, skipped_stage_inferers):
+ stage_status.setdefault(skipped_stage, "skipped")
+ if skipped_stage not in stage_order:
+ stage_order.append(skipped_stage)
+ if stage:
+ last_message_stage = stage
+ if content:
+ last_stage_message = content
+ stage_messages.setdefault(stage, []).append(content)
+ elif event_type == "harness.stage_result" and not entry.get("scope"):
+ stage = str(entry.get("stage") or "")
+ status = str(entry.get("status") or "")
+ if stage:
+ stage_status[stage] = status
+ if entry.get("error"):
+ last_error = str(entry.get("error") or "")
+ if stage not in stage_order:
+ stage_order.append(stage)
+ messages = entry.get("messages") or []
+ if messages:
+ stage_messages.setdefault(stage, []).extend(str(msg) for msg in messages)
+ elif event_type == "harness.session_finished" and entry.get("error"):
+ last_error = str(entry.get("error") or "")
+
+ if not stage_order:
+ stage_order = list(META_EVOLVE_STAGE_ORDER)
+ for stage in stage_status:
+ if stage not in stage_order:
+ stage_order.append(stage)
+
+ completed = [
+ stage for stage in stage_order
+ if stage_status.get(stage) in {"success", "skipped"}
+ ]
+ failed_stage = next(
+ (
+ stage for stage in stage_order
+ if stage_status.get(stage) == "failed"
+ ),
+ "",
+ )
+ current_stage = ""
+ if not failed_stage:
+ if (
+ last_message_stage
+ and stage_status.get(last_message_stage) not in {"success", "failed", "skipped"}
+ ):
+ current_stage = last_message_stage
+ else:
+ current_stage = next(
+ (
+ stage for stage in stage_order
+ if stage_status.get(stage) not in {"success", "skipped"}
+ ),
+ "",
+ )
+
+ stages = []
+ for stage in stage_order:
+ status = stage_status.get(stage)
+ if not status:
+ status = "running" if stage == current_stage else "pending"
+ recent_messages = stage_messages.get(stage) or []
+ stages.append({
+ "stage": stage,
+ "name": STAGE_DISPLAY_NAMES.get(stage, stage),
+ "status": status,
+ "messages": recent_messages[-3:],
+ })
+
+ progress = {
+ "pipeline": pipeline,
+ "stages": stages,
+ "completed_stages": completed,
+ "current_stage": current_stage,
+ "failed_stage": failed_stage,
+ "last_message": last_stage_message,
+ "last_event_type": last_event_type,
+ "last_error": last_error,
+ "failure_code": classify_failure(last_error, last_stage_message) if failed_stage else "",
+ }
+ for enricher in progress_enrichers or []:
+ progress = enricher(progress, logs)
+ progress["summary"] = format_progress_summary(progress)
+ return progress
+
+
+def determine_pipeline_status_from_log(
+ log_path: Path,
+ *,
+ skipped_stage_inferers: list[SkippedStageInferer] | None = None,
+) -> dict[str, Any]:
+ """Parse a JSON Lines log file and determine whether the pipeline succeeded."""
+ pipeline_type = ""
+ 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"]]
+ pipeline_type = entry.get("pipeline", "")
+ if entry.get("event_type") == "harness.message":
+ content = str(entry.get("content") or "")
+ for skipped_stage in infer_skipped_stages_from_message(content, skipped_stage_inferers):
+ stage_results.setdefault(skipped_stage, "skipped")
+ 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("[AutoHarnessRunLogStatus] Failed to read log %s: %s", log_path, exc)
+ return {"failed": False, "error": ""}
+
+ if pipeline_type == "extended_evolve_pipeline":
+ if "build_verify" not in stage_results:
+ return {"failed": True, "error": "Stage 'build_verify' not appeared"}
+ if stage_results.get("activate") not in {"success", "skipped"}:
+ return {
+ "failed": True,
+ "error": f"Stage 'activate' {stage_results.get('activate', 'not completed')}",
+ }
+ return {"failed": False, "error": ""}
+
+ for slot in pipeline_stages:
+ result = stage_results.get(slot)
+ if result not in {"success", "skipped"}:
+ return {
+ "failed": True,
+ "error": f"Stage '{slot}' {stage_results.get(slot, 'not completed')}",
+ }
+
+ return {"failed": False, "error": ""}
+
+
+def has_terminal_session_event(log_path: Path) -> bool:
+ """Return whether a structured run log contains a terminal session event."""
+ 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.session_finished"
+ and entry.get("is_terminal") is True
+ ):
+ return True
+ except Exception as exc:
+ logger.warning("[AutoHarnessRunLogStatus] Failed to scan terminal event in %s: %s", log_path, exc)
+ return False
+
+
+# 终态任务状态集合 - 终态任务不需要读取日志
+TERMINAL_STATUSES = {
+ "success", "failed", "cancelled", "pr_created",
+ "completed", "completed_without_pr", "skipped", "needs_human"
+}
+
+# 关键事件类型 - 只读取这些事件获取进度
+KEY_EVENT_TYPES = {"harness.stage_result", "harness.session_finished"}
+
+
+def read_key_events_reverse(log_path: Path, max_events: int = 20) -> list[dict[str, Any]]:
+ """反向读取日志,只获取关键事件(stage_result, session_finished)。
+
+ 用于智能状态查询:运行中任务只需读取关键事件,无需读取全部日志。
+ """
+ events: list[dict[str, Any]] = []
+
+ try:
+ with log_path.open("r", encoding="utf-8") as f:
+ f.seek(0, 2) # 文件末尾
+ file_size = f.tell()
+
+ chunk_size = 4096
+ buffer = ""
+ pos = file_size
+
+ while pos > 0 and len(events) < max_events:
+ read_size = min(chunk_size, pos)
+ pos -= read_size
+ f.seek(pos)
+ chunk = f.read(read_size)
+ buffer = chunk + buffer
+
+ lines = buffer.split("\n")
+ buffer = lines[0]
+
+ for line in reversed(lines[1:]):
+ if not line.strip():
+ continue
+ try:
+ entry = json.loads(line)
+ if entry.get("event_type") in KEY_EVENT_TYPES:
+ events.append(entry)
+ except json.JSONDecodeError:
+ continue
+
+ except Exception as exc:
+ logger.warning("[AutoHarnessRunLogStatus] Failed to reverse read %s: %s", log_path, exc)
+
+ return events
+
+
+def summarize_progress_from_key_events(key_events: list[dict[str, Any]]) -> dict[str, Any]:
+ """从关键事件(反向读取)构建进度摘要。"""
+ stage_status: dict[str, str] = {}
+ stage_messages: dict[str, list[str]] = {}
+ last_error = ""
+ failed_stage = ""
+ pipeline = ""
+
+ # 反向读取的事件是倒序的,需要反转
+ for entry in reversed(key_events):
+ event_type = str(entry.get("event_type") or "")
+
+ if event_type == "harness.stage_result" and not entry.get("scope"):
+ stage = str(entry.get("stage") or "")
+ status = str(entry.get("status") or "")
+ if stage:
+ stage_status[stage] = status
+ if entry.get("error"):
+ last_error = str(entry.get("error") or "")
+ messages = entry.get("messages") or []
+ if messages:
+ stage_messages.setdefault(stage, []).extend(str(msg) for msg in messages)
+
+ elif event_type == "harness.session_finished":
+ if entry.get("error"):
+ last_error = str(entry.get("error") or "")
+
+ # 确定失败阶段
+ for stage in META_EVOLVE_STAGE_ORDER:
+ if stage_status.get(stage) == "failed":
+ failed_stage = stage
+ break
+
+ # 确定当前阶段
+ current_stage = ""
+ if not failed_stage:
+ for stage in META_EVOLVE_STAGE_ORDER:
+ status = stage_status.get(stage)
+ if status not in {"success", "skipped", "failed"}:
+ if status == "running":
+ current_stage = stage
+ elif status is None and current_stage:
+ break
+
+ completed = [
+ stage for stage in META_EVOLVE_STAGE_ORDER
+ if stage_status.get(stage) in {"success", "skipped"}
+ ]
+
+ stages = []
+ for stage in META_EVOLVE_STAGE_ORDER:
+ status = stage_status.get(stage)
+ if not status:
+ status = "running" if stage == current_stage else "pending"
+ stages.append({
+ "stage": stage,
+ "name": STAGE_DISPLAY_NAMES.get(stage, stage),
+ "status": status,
+ "messages": stage_messages.get(stage, [])[-3:] or [],
+ })
+
+ progress = {
+ "stages": stages,
+ "completed_stages": completed,
+ "current_stage": current_stage,
+ "failed_stage": failed_stage,
+ "last_error": last_error,
+ "failure_code": classify_failure(last_error, "") if failed_stage else "",
+ "summary": format_progress_summary({
+ "stages": stages,
+ "completed_stages": completed,
+ "current_stage": current_stage,
+ "failed_stage": failed_stage,
+ }),
+ }
+ return progress
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py b/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py
index 44bdccbf2b..54929b5bbc 100644
--- a/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py
+++ b/jiuwenswarm/agents/harness/common/auto_harness/scheduler.py
@@ -16,6 +16,8 @@ from typing import TYPE_CHECKING, Any, Optional
from openjiuwen.auto_harness.pipelines import META_EVOLVE_PIPELINE
from openjiuwen.core.foundation.llm import Model
+from .run_log_status import has_terminal_session_event
+
if TYPE_CHECKING:
from .service import AutoHarnessService
from .task_store import TaskStore
@@ -30,57 +32,6 @@ def _sync_append_log(log_path: Path, line: str) -> None:
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:
- - meta_evolve_pipeline: every stage must have harness.stage_result with status="success".
- - extended_evolve_pipeline: build_verify must appear (any status), activate must be "success".
-
- Returns:
- {"failed": bool, "error": str}
- """
- pipeline_type: 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"]]
- pipeline_type = entry.get("pipeline", "")
- 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": ""}
-
- if pipeline_type == "extended_evolve_pipeline":
- if "build_verify" not in stage_results:
- return {"failed": True, "error": "Stage 'build_verify' not appeared"}
- if stage_results.get("activate") != "success":
- return {"failed": True, "error": f"Stage 'activate' {stage_results.get('activate', 'not completed')}"}
- return {"failed": False, "error": ""}
-
- for slot in pipeline_stages:
- result = stage_results.get(slot)
- 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.
@@ -377,16 +328,23 @@ class Scheduler:
# Resolve pipeline preference (use task's pipeline or default to META_EVOLVE_PIPELINE)
pipeline_preference = pipeline if pipeline else META_EVOLVE_PIPELINE
+ params = {
+ "mode": "auto_harness",
+ "scheduled": True,
+ "pipeline_preference": pipeline_preference,
+ }
+ optimization_task = task.get("optimization_task")
+ if isinstance(optimization_task, dict):
+ params["optimization_task"] = optimization_task
+ repo_url = task.get("repo_url", "")
+ if repo_url:
+ params["repo_url"] = repo_url
request = AgentRequest(
request_id=execution_id,
channel_id="tui",
session_id=session_id,
- params={
- "mode": "auto_harness",
- "scheduled": True,
- "pipeline_preference": pipeline_preference,
- },
+ params=params,
)
# Resolve model from jiuwenswarm config (same approach as interface_deep)
@@ -406,9 +364,33 @@ class Scheduler:
event_type = chunk.payload.get("event_type", "")
if event_type in ("context.usage", "context.compression_state"):
continue
+ if event_type == "harness.message" and chunk.payload.get("stage"):
+ logger.info(
+ "[Scheduler] Task %s execution %s stage=%s message=%s",
+ task_id,
+ execution_id,
+ chunk.payload.get("stage"),
+ str(chunk.payload.get("content") or "")[:160],
+ )
+ elif event_type == "harness.stage_result":
+ logger.info(
+ "[Scheduler] Task %s execution %s stage=%s status=%s error=%s",
+ task_id,
+ execution_id,
+ chunk.payload.get("stage"),
+ chunk.payload.get("status"),
+ str(chunk.payload.get("error") or "")[:200],
+ )
# 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)
+ if event_type == "harness.session_finished" and chunk.payload.get("is_terminal") is True:
+ logger.info(
+ "[Scheduler] Task %s execution %s received terminal session event",
+ task_id,
+ execution_id,
+ )
+ break
logger.info(
"[Scheduler] Task %s execution %s completed successfully",
@@ -425,8 +407,14 @@ class Scheduler:
logger.exception("[Scheduler] Task %s execution %s failed: %s", task_id, execution_id, e)
finally:
+ if final_status == "success" and log_path.exists() and not has_terminal_session_event(log_path):
+ logger.warning(
+ "[Scheduler] Task %s execution %s ended without terminal session event",
+ task_id,
+ execution_id,
+ )
if final_status == "success" and log_path.exists():
- result = _determine_pipeline_status_from_log(log_path)
+ result = self._task_store.determine_pipeline_status_from_log(log_path)
if result["failed"]:
final_status = "failed"
error_msg = result["error"]
@@ -465,4 +453,4 @@ class Scheduler:
})
# Remove from running dict
- self._running_executions.pop(task_id, None)
\ No newline at end of file
+ self._running_executions.pop(task_id, None)
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/service.py b/jiuwenswarm/agents/harness/common/auto_harness/service.py
index d67811e988..c44eb12838 100644
--- a/jiuwenswarm/agents/harness/common/auto_harness/service.py
+++ b/jiuwenswarm/agents/harness/common/auto_harness/service.py
@@ -60,9 +60,11 @@ from jiuwenswarm.agents.harness.common.rails.stream_event_rail import JiuSwarmSt
from jiuwenswarm.common.schema.agent import AgentResponseChunk
from jiuwenswarm.common.utils import get_user_workspace_dir
+from .capabilities import AutoHarnessCapabilityRegistry, create_default_capability_registry
from .scheduler import Scheduler
from .task_store import TaskStore
from .config_validator import ConfigValidator
+from .repo_auth import configure_gitcode_auth
logger = logging.getLogger(__name__)
@@ -79,6 +81,46 @@ _DEFAULT_CI_GATE_PYTHON_EXECUTABLE = sys.executable
_DEFAULT_CI_GATE_INSTALL_COMMAND = "uv sync --active --group dev --extra cli"
+def _serialize_optimization_task(task: OptimizationTask | dict[str, Any]) -> dict[str, Any]:
+ """Serialize an explicit optimization task into scheduler-safe metadata."""
+ if isinstance(task, OptimizationTask):
+ status = getattr(task.status, "value", task.status)
+ return {
+ "topic": task.topic,
+ "description": task.description,
+ "files": list(task.files or []),
+ "issue_ref": task.issue_ref,
+ "expected_effect": task.expected_effect,
+ "pipeline_name": task.pipeline_name,
+ "status": status,
+ }
+ return dict(task)
+
+
+def _build_auto_harness_task(query: str, payload: Optional[dict[str, Any]] = None) -> OptimizationTask:
+ """Build the auto-harness task for a run.
+
+ Ordinary queries become plain tasks. Scenario-specific callers can pass an
+ explicit payload so the main auto-harness flow does not infer task type from
+ natural-language query text.
+ """
+ if payload:
+ return OptimizationTask(
+ topic=str(payload.get("topic") or query),
+ description=str(payload.get("description") or query),
+ files=list(payload.get("files") or []),
+ issue_ref=payload.get("issue_ref") or None,
+ expected_effect=str(payload.get("expected_effect") or ""),
+ pipeline_name=str(payload.get("pipeline_name") or ""),
+ status=payload.get("status") or "pending",
+ )
+ return OptimizationTask(
+ topic=query,
+ description=query,
+ status="pending",
+ )
+
+
def reset_harness_packages_state() -> None:
"""Reset harness package state to native agent on service startup.
@@ -214,6 +256,7 @@ class AutoHarnessService:
self._scheduler: Optional[Scheduler] = None
self._task_store: Optional[TaskStore] = None
self._config_validator: Optional[ConfigValidator] = None
+ self._capabilities: Optional[AutoHarnessCapabilityRegistry] = None
# Initialize scheduler components
self._init_scheduler()
@@ -354,6 +397,13 @@ class AutoHarnessService:
service=self,
task_store=self._task_store,
)
+ self._capabilities = create_default_capability_registry(
+ data_dir=self.data_dir,
+ task_store=self._task_store,
+ harness_service=self,
+ base_config_getter=lambda: self._base_config,
+ default_repo_url=_DEFAULT_REPO_URL,
+ )
logger.info("[AutoHarnessService] Scheduler components initialized")
except Exception as e:
logger.warning("[AutoHarnessService] Failed to init scheduler: %s", e)
@@ -362,11 +412,13 @@ 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():
+ # Reconcile stale task statuses (async — requires file I/O).
+ # This also fixes runs that emitted a terminal harness.session_finished
+ # event but were left as "running" by an older scheduler process.
+ if self._task_store is not None:
corrected = await self._task_store.reconcile_task_statuses()
if corrected > 0:
- logger.info("[AutoHarnessService] Reconciled %d legacy task statuses", corrected)
+ logger.info("[AutoHarnessService] Reconciled %d stale task statuses", corrected)
if self._scheduler is not None:
await self._scheduler.start()
logger.info("[AutoHarnessService] Scheduler started")
@@ -409,6 +461,51 @@ class AutoHarnessService:
return result
+ async def handle_capability(
+ self,
+ capability: str,
+ action: str,
+ params: dict[str, Any],
+ model: Optional[Model] = None,
+ ) -> dict[str, Any]:
+ """Dispatch a scenario-specific auto-harness capability."""
+ if self._capabilities is None:
+ self._init_scheduler()
+ if self._capabilities is None:
+ return {"error": "auto-harness 能力服务未初始化"}
+ return await self._capabilities.handle(capability, action, params, model)
+
+ async def process_gitcode_issues_once(
+ self,
+ params: dict[str, Any],
+ model: Optional[Model] = None,
+ ) -> dict[str, Any]:
+ """Compatibility entry for GitCode issue processing."""
+ return await self.handle_capability("issue", "process_once", params, model)
+
+ async def watch_gitcode_issues_once(
+ self,
+ params: dict[str, Any],
+ model: Optional[Model] = None,
+ ) -> dict[str, Any]:
+ """Compatibility entry for the existing issue.watch_once RPC command."""
+ return await self.process_gitcode_issues_once(params, model)
+
+ async def list_gitcode_issue_states(self) -> dict[str, Any]:
+ """Compatibility entry for GitCode issue state listing."""
+ result = await self.handle_capability("issue", "state_list", {})
+ if "issues" not in result:
+ return {"issues": [], **result}
+ return result
+
+ async def delete_issue_states(self, params: dict[str, Any]) -> dict[str, Any]:
+ """删除 GitCode issue 处理记录和运行日志。"""
+ return await self.handle_capability("issue", "delete", params)
+
+ async def refresh_issue_matrix(self, params: dict[str, Any]) -> dict[str, Any]:
+ """刷新 issue 矩阵,增量更新分析结果。"""
+ return await self.handle_capability("issue", "matrix", params)
+
@staticmethod
def _extract_repo_name(repo_url: str) -> str:
"""Extract repository name from URL.
@@ -491,6 +588,7 @@ class AutoHarnessService:
ret, _, stderr = await self._run_git_command(
["fetch", "origin"],
cwd=local_path,
+ env=git_env,
)
if ret != 0:
logger.warning("[AutoHarnessService] Git fetch failed: %s", stderr)
@@ -498,6 +596,7 @@ class AutoHarnessService:
ret, _, stderr = await self._run_git_command(
["reset", "--hard", "origin/HEAD"],
cwd=local_path,
+ env=git_env,
)
if ret != 0:
logger.warning("[AutoHarnessService] Git reset failed: %s", stderr)
@@ -523,16 +622,16 @@ class AutoHarnessService:
# to the fork repo, not the upstream repo.
fork_owner = cfg.fork_owner if cfg else ""
upstream_owner = cfg.upstream_owner if cfg else ""
- if git_remote_name and git_remote_name != "origin":
- # Derive fork URL from repo_url by replacing upstream_owner
- # with fork_owner. If they are the same, reuse repo_url directly.
- fork_url = repo_url
- if fork_owner and upstream_owner and fork_owner != upstream_owner:
- fork_url = repo_url.replace(
- f"/{upstream_owner}/",
- f"/{fork_owner}/",
- )
+ # Derive fork URL from repo_url by replacing upstream_owner with
+ # fork_owner. If they are the same, reuse repo_url directly.
+ fork_url = repo_url
+ if fork_owner and upstream_owner and fork_owner != upstream_owner:
+ fork_url = repo_url.replace(
+ f"/{upstream_owner}/",
+ f"/{fork_owner}/",
+ )
+ if git_remote_name and git_remote_name != "origin":
# Check if the remote already exists
ret, stdout, _ = await self._run_git_command(
["remote"],
@@ -558,6 +657,23 @@ class AutoHarnessService:
fork_url,
)
+ # Keep origin as the upstream fetch remote, but route accidental
+ # `git push origin <branch>` calls to the fork. Some LLM-driven command
+ # paths may bypass GitOperations.push(), so this prevents writes to the
+ # upstream repo and makes manual push commands use the configured fork.
+ if fork_url != repo_url:
+ await self._run_git_command(
+ ["remote", "set-url", "--push", "origin", fork_url],
+ cwd=local_path,
+ )
+
+ await configure_gitcode_auth(
+ local_path,
+ username=gitcode_username,
+ token=gitcode_token,
+ push_remote=git_remote_name or "origin",
+ )
+
# Configure git user identity in the local repo so commits have
# proper authorship even on servers without global git config.
if git_user_name:
@@ -630,7 +746,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-auto-harness"
+ config.git_base_branch = "develop"
if config.pipeline_preference == EXTENDED_EVOLVE_PIPELINE:
config.git_base_branch = "develop"
if not config.git_remote:
@@ -1287,14 +1403,20 @@ class AutoHarnessService:
)
return
- # Resolve repo_url from base config (per §5.6.3)
- # repo_url is configured in config.yaml, not passed in request
- if self._base_config and self._base_config.repo_url:
+ # Resolve repo_url: priority is passed repo_url > config default
+ params = getattr(request, "params", {}) or {}
+
+ passed_repo_url = str(params.get("repo_url") or "").strip()
+
+ if passed_repo_url:
+ repo_url = passed_repo_url
+ logger.info("[AutoHarnessService] Using passed repo_url: %s", repo_url)
+ elif self._base_config and self._base_config.repo_url:
repo_url = self._base_config.repo_url
+ logger.info("[AutoHarnessService] Using repo_url from config: %s", repo_url)
else:
- # Fallback to default if config not loaded
repo_url = _DEFAULT_REPO_URL
- logger.info("[AutoHarnessService] Using repo_url from config: %s", repo_url)
+ logger.info("[AutoHarnessService] Using default repo_url: %s", repo_url)
# Emit processing status
yield AgentResponseChunk(
@@ -1309,7 +1431,6 @@ class AutoHarnessService:
)
active_run: Optional[ActiveAutoHarnessRun] = None
- params = getattr(request, "params", {}) or {}
pipeline_preference = params.get("pipeline_preference")
try:
# Clone/update repository
@@ -1328,14 +1449,15 @@ class AutoHarnessService:
pipeline_preference=pipeline_preference
)
- # Build optimization task from query
- tasks = [
- OptimizationTask(
- topic=query,
- description=query,
- status="pending",
- )
- ]
+ # Issue fix flow: repo_url from request params, force develop branch
+ if passed_repo_url:
+ config.git_base_branch = "develop"
+
+ # Build optimization task from explicit request metadata when a
+ # scenario provides one; otherwise keep ordinary query handling
+ # generic and free of scenario-specific parsing.
+ optimization_task_payload = params.get("optimization_task")
+ tasks = [_build_auto_harness_task(query, optimization_task_payload)]
# Create orchestrator
orchestrator = create_auto_harness_orchestrator(
@@ -2693,7 +2815,9 @@ class AutoHarnessService:
self,
query: str,
model: Optional[Model] = None,
- pipeline: Optional[str] = None
+ pipeline: Optional[str] = None,
+ optimization_task: Optional[OptimizationTask | dict[str, Any]] = None,
+ repo_url: str = "",
) -> dict[str, Any]:
"""Create and immediately execute a one-time task.
@@ -2705,6 +2829,8 @@ class AutoHarnessService:
query: The optimization goal/task description
model: Model configuration from JiuwenSwarm
pipeline: Pipeline preference (extended_evolve_pipeline or meta_evolve_pipeline)
+ optimization_task: Optional explicit task metadata for specialized callers
+ repo_url: Target repository URL for the task (stored at task_data level)
Returns:
{"task_id": str, "status": "running", "message": str}
@@ -2734,6 +2860,10 @@ class AutoHarnessService:
"model_name": model_name,
"pipeline": pipeline, # Pipeline preference
}
+ if optimization_task is not None:
+ task_data["optimization_task"] = _serialize_optimization_task(optimization_task)
+ if repo_url:
+ task_data["repo_url"] = repo_url
await self._task_store.add_task(task_data)
@@ -2818,7 +2948,10 @@ class AutoHarnessService:
"""
if self._task_store is None:
return None
- return self._task_store.get_task(task_id)
+ task = self._task_store.get_task(task_id)
+ if task is None:
+ return None
+ return await self._task_store.enrich_task_with_progress(task)
async def list_scheduled_tasks(self) -> list[dict[str, Any]]:
"""List all scheduled tasks.
@@ -2828,7 +2961,9 @@ class AutoHarnessService:
"""
if self._task_store is None:
return []
- return self._task_store.list_tasks()
+ return await self._task_store.enrich_tasks_with_progress(
+ self._task_store.list_tasks()
+ )
async def get_scheduled_task_logs(
self,
diff --git a/jiuwenswarm/agents/harness/common/auto_harness/task_store.py b/jiuwenswarm/agents/harness/common/auto_harness/task_store.py
index 42fc7045f6..f247db6d33 100644
--- a/jiuwenswarm/agents/harness/common/auto_harness/task_store.py
+++ b/jiuwenswarm/agents/harness/common/auto_harness/task_store.py
@@ -13,7 +13,19 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
-from .scheduler import _determine_pipeline_status_from_log
+from .run_log_status import (
+ META_EVOLVE_STAGE_ORDER,
+ ProgressEnricher,
+ STAGE_DISPLAY_NAMES,
+ SkippedStageInferer,
+ TERMINAL_STATUSES,
+ determine_pipeline_status_from_log,
+ has_terminal_session_event,
+ read_key_events_reverse,
+ resolve_latest_task_log_path,
+ summarize_progress_from_logs,
+ summarize_progress_from_key_events,
+)
logger = logging.getLogger(__name__)
@@ -45,6 +57,8 @@ class TaskStore:
self._runs_dir = data_dir / "runs"
self._tasks_cache: Optional[dict[str, Any]] = None
self._save_lock: asyncio.Lock = asyncio.Lock()
+ self._skipped_stage_inferers: list[SkippedStageInferer] = []
+ self._progress_enrichers: list[ProgressEnricher] = []
self._ensure_dirs()
def _ensure_dirs(self) -> None:
@@ -109,6 +123,94 @@ class TaskStore:
data = self._load_tasks()
return data.get("tasks", [])
+ def register_run_log_status_extension(
+ self,
+ *,
+ skipped_stage_inferer: SkippedStageInferer | None = None,
+ progress_enricher: ProgressEnricher | None = None,
+ ) -> None:
+ """Register optional run-log status extensions for specialized capabilities."""
+ if skipped_stage_inferer is not None and skipped_stage_inferer not in self._skipped_stage_inferers:
+ self._skipped_stage_inferers.append(skipped_stage_inferer)
+ if progress_enricher is not None and progress_enricher not in self._progress_enrichers:
+ self._progress_enrichers.append(progress_enricher)
+
+ def summarize_progress_from_logs(self, logs: Optional[list[dict[str, Any]]] = None) -> dict[str, Any]:
+ """Summarize stage progress from structured harness logs."""
+ if logs is None:
+ logs = []
+ return summarize_progress_from_logs(
+ logs,
+ skipped_stage_inferers=self._skipped_stage_inferers,
+ progress_enrichers=self._progress_enrichers,
+ )
+
+ def determine_pipeline_status_from_log(self, log_path: Path) -> dict[str, Any]:
+ """Determine pipeline status with registered run-log extensions."""
+ return determine_pipeline_status_from_log(
+ log_path,
+ skipped_stage_inferers=self._skipped_stage_inferers,
+ )
+
+ async def summarize_task_progress(self, task: dict[str, Any]) -> dict[str, Any]:
+ """Read the latest task log and return a compact progress summary.
+
+ 智能状态查询:
+ - 终态任务:不读取日志,直接返回状态
+ - 运行中任务:反向读取关键事件(stage_result)
+ """
+ task_status = str(task.get("status") or "")
+
+ # 终态任务:不读取日志
+ if task_status in TERMINAL_STATUSES:
+ return {
+ "summary": f"终态: {task_status}",
+ "stages": [],
+ "completed_stages": [],
+ "current_stage": "",
+ "failed_stage": "",
+ }
+
+ log_path = resolve_latest_task_log_path(task, self._runs_dir)
+ if not log_path:
+ return {
+ "summary": "暂无执行日志",
+ "stages": [
+ {
+ "stage": stage,
+ "name": STAGE_DISPLAY_NAMES.get(stage, stage),
+ "status": "pending",
+ "messages": [],
+ }
+ for stage in META_EVOLVE_STAGE_ORDER
+ ],
+ "completed_stages": [],
+ "current_stage": "",
+ "failed_stage": "",
+ }
+
+ # 运行中任务:反向读取关键事件
+ key_events = await asyncio.to_thread(read_key_events_reverse, log_path, 20)
+ if key_events:
+ progress = summarize_progress_from_key_events(key_events)
+ else:
+ # 关键事件为空,读取完整日志
+ logs = await asyncio.to_thread(self.read_log, log_path, 0, -1)
+ progress = self.summarize_progress_from_logs(logs)
+
+ progress["log_path"] = str(log_path)
+ return progress
+
+ async def enrich_task_with_progress(self, task: dict[str, Any]) -> dict[str, Any]:
+ """Return a shallow task copy with latest progress attached."""
+ enriched = dict(task)
+ enriched["progress"] = await self.summarize_task_progress(task)
+ return enriched
+
+ async def enrich_tasks_with_progress(self, tasks: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Attach progress summaries to a list of tasks."""
+ return [await self.enrich_task_with_progress(task) for task in tasks]
+
def list_pending_tasks(self) -> list[dict[str, Any]]:
"""List tasks with status 'pending' that are due for execution."""
data = self._load_tasks()
@@ -349,12 +451,12 @@ class TaskStore:
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)."""
+ """Check if any task may need log-based status reconciliation."""
data = self._load_tasks()
- return any(t.get("status") == "completed" for t in data.get("tasks", []))
+ return any(t.get("status") in {"completed", "running"} 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."""
+ """Re-check task logs and fix stale status values."""
data = self._load_tasks()
corrected = 0
@@ -362,27 +464,34 @@ class TaskStore:
task_id = task.get("task_id")
old_status = task.get("status")
- if old_status not in ("completed", "success", "failed"):
+ if old_status not in ("completed", "success", "failed", "running"):
continue
history = task.get("execution_history", [])
- if not history:
+ latest = history[-1] if history else None
+ current_execution_id = str(task.get("current_execution_id") or "")
+ log_path = resolve_latest_task_log_path(task, self._runs_dir)
+ if log_path is None:
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():
+ if old_status == "running" and not has_terminal_session_event(log_path):
continue
- result = _determine_pipeline_status_from_log(log_path)
+ result = self.determine_pipeline_status_from_log(log_path)
new_status = "failed" if result["failed"] else "success"
if new_status != old_status:
task["status"] = new_status
+ task["current_execution_id"] = None
+ if latest is None or latest.get("execution_id") != current_execution_id:
+ latest = {
+ "execution_id": current_execution_id,
+ "started_at": task.get("created_at"),
+ "completed_at": datetime.now(timezone.utc).isoformat(),
+ "log_path": str(log_path),
+ }
+ history.append(latest)
+ task["execution_history"] = history
latest["status"] = new_status
if result["error"]:
latest["error"] = result["error"]
@@ -395,4 +504,4 @@ class TaskStore:
if corrected > 0:
await self._save_tasks(data)
- return corrected
\ No newline at end of file
+ return corrected
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/auto-harness-issue-fix.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/auto-harness-issue-fix.ts
new file mode 100644
index 0000000000..e6a9fe539e
--- /dev/null
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/auto-harness-issue-fix.ts
@@ -0,0 +1,683 @@
+import { parseArgs } from "../helpers.js";
+
+export type AutoHarnessIssueStageProgress = {
+ stage: string;
+ name?: string;
+ status: string;
+ messages?: string[];
+};
+
+export type AutoHarnessIssueProgress = {
+ summary?: string;
+ stages?: AutoHarnessIssueStageProgress[];
+ completed_stages?: string[];
+ current_stage?: string;
+ failed_stage?: string;
+ last_message?: string;
+ last_error?: string;
+ failure_code?: string;
+ pr_url?: string;
+};
+
+export type IssueFixTaskStatus = {
+ error?: string;
+ task_id?: string;
+ status?: string;
+ progress?: AutoHarnessIssueProgress;
+};
+
+export type IssueFixWatchItem = {
+ issue: number;
+ taskId?: string;
+ status: string;
+ reason?: string;
+ lastMessage?: string;
+ currentStage?: string;
+ failedStage?: string;
+ failureCode?: string;
+ prUrl?: string;
+};
+
+export type IssueWatchArgs = {
+ repo: string;
+ labels: string[];
+ max_issues: number;
+ dry_run: string;
+ comment_on_start: boolean;
+ pipeline: string;
+ issue_numbers: number[];
+ max_auto_difficulty: string;
+ concurrency: number;
+};
+
+export type IssueFixArgs = {
+ repo: string;
+ issue_numbers: number[];
+ dry_run: string;
+ comment_on_start: boolean;
+ pipeline: string;
+ max_auto_difficulty: string;
+ concurrency: number;
+};
+
+export type IssueWatchResult = {
+ fetched?: number;
+ started?: Array<{
+ number?: number;
+ issue?: number;
+ task_id?: string;
+ status?: string;
+ title?: string;
+ difficulty?: { level?: string; score?: number; reasons?: string[] };
+ }>;
+ skipped?: Array<{
+ issue?: number;
+ reason?: string;
+ status?: string;
+ human_label?: string;
+ difficulty?: { level?: string; score?: number; reasons?: string[] };
+ }>;
+ reconciled?: Array<{ number?: number; status?: string; pr_url?: string }>;
+};
+
+type PipelineNameResolver = (name: string) => string;
+
+// Repo options: friendly aliases → full owner/repo values
+export const REPO_OPTIONS = {
+ jiuwenswarm: { full: "openJiuwen/jiuwenswarm", desc: "jiuwenswarm 代码仓" },
+ agent_core: { full: "openJiuwen/agent-core", desc: "agent-core 代码仓" },
+};
+export const REPO_ALIASES = Object.keys(REPO_OPTIONS);
+export const REPO_FULL_VALUES = Object.values(REPO_OPTIONS).map(v => v.full);
+
+// Resolve friendly alias to full repo value
+export function resolveRepoName(name: string): string {
+ if (name in REPO_OPTIONS) return REPO_OPTIONS[name as keyof typeof REPO_OPTIONS].full;
+ // Already a full value (passed directly) — accept it
+ if (REPO_FULL_VALUES.includes(name)) return name;
+ return name; // Unknown value, pass through
+}
+
+export const ISSUE_FIX_WATCH_INTERVAL_MS = 5000;
+export const ISSUE_FIX_WATCH_MAX_POLLS = 720;
+// Difficulty options: user-selectable levels
+export const DIFFICULTY_OPTIONS = {
+ low: { desc: "简单问题,单文件修改" },
+ medium: { desc: "中等难度,需跨文件协调" },
+ high: { desc: "复杂问题,涉及架构或多方依赖" },
+};
+export const DIFFICULTY_SELECTABLE_VALUES = Object.keys(DIFFICULTY_OPTIONS);
+export const ISSUE_DIFFICULTY_VALUES = new Set(["low", "medium", "high", "unclear"]);
+
+const ISSUE_FIX_TERMINAL_STATUSES = new Set([
+ "success",
+ "failed",
+ "cancelled",
+ "skipped",
+ "needs_human",
+]);
+
+export function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function latestStageWithStatus(
+ progress: AutoHarnessIssueProgress | undefined,
+ status: string,
+): string {
+ if (!progress?.stages) return "";
+ const stage = progress.stages.find((item) => item.status === status);
+ return stage?.stage || "";
+}
+
+export function issueFixTaskStatusToWatchItem(
+ issue: number,
+ taskId: string | undefined,
+ task: IssueFixTaskStatus | undefined,
+ fallbackStatus = "queued",
+ reason = "",
+): IssueFixWatchItem {
+ if (!taskId) {
+ return {
+ issue,
+ status: fallbackStatus,
+ reason,
+ lastMessage: reason,
+ };
+ }
+ if (!task || task.error) {
+ return {
+ issue,
+ taskId,
+ status: "unknown",
+ reason: task?.error || reason || "任务状态暂不可用",
+ lastMessage: task?.error || reason || "任务状态暂不可用",
+ };
+ }
+ const progress = task.progress;
+ const status = task.status || fallbackStatus;
+ return {
+ issue,
+ taskId,
+ status: status === "pending" ? "queued" : status,
+ currentStage: progress?.current_stage || latestStageWithStatus(progress, "running"),
+ failedStage: progress?.failed_stage || latestStageWithStatus(progress, "failed"),
+ failureCode: progress?.failure_code || "",
+ prUrl: progress?.pr_url || "",
+ lastMessage: progress?.last_message || progress?.last_error || reason,
+ };
+}
+
+export function formatIssueFixStatusLine(item: IssueFixWatchItem): string {
+ const issue = `#${item.issue}`.padEnd(7, " ");
+ const status = (item.status || "unknown").padEnd(9, " ");
+ let stageText = "";
+ if (item.status === "running") {
+ stageText = item.currentStage ? `${item.currentStage} …` : "starting …";
+ } else if (item.status === "failed") {
+ stageText = item.failedStage ? `${item.failedStage} ×` : "failed";
+ } else if (item.status === "success") {
+ stageText = "done ✓";
+ } else if (item.status === "queued") {
+ stageText = "";
+ } else if (item.status === "skipped") {
+ stageText = "skipped";
+ } else if (item.status === "needs_human") {
+ stageText = "needs-human";
+ } else {
+ stageText = item.currentStage || item.reason || "";
+ }
+ const fail = item.failureCode ? ` cause: ${item.failureCode}` : "";
+ const pr = item.prUrl ? ` PR: ${item.prUrl}` : "";
+ const last = item.lastMessage ? ` last: ${item.lastMessage}` : "";
+ return `${issue} ${status}${stageText}${fail}${pr}${last}`;
+}
+
+export function formatIssueFixStatusBlock(items: IssueFixWatchItem[]): string {
+ return items
+ .slice()
+ .sort((a, b) => a.issue - b.issue)
+ .map(formatIssueFixStatusLine)
+ .join("\n");
+}
+
+// Issue fix stages with weights for progress calculation
+const ISSUE_FIX_STAGES = [
+ { name: "assess", weight: 0, skip: true },
+ { name: "plan", weight: 0, skip: true },
+ { name: "implement", weight: 40 },
+ { name: "verify", weight: 30 },
+ { name: "commit", weight: 15 },
+ { name: "publish_pr", weight: 15 },
+];
+
+// Calculate progress percentage from stage results
+export function calculateStageProgress(stages: Array<{ stage: string; status: string }>): number {
+ const effectiveStages = ISSUE_FIX_STAGES.filter(s => !s.skip);
+ const totalWeight = effectiveStages.reduce((sum, s) => sum + s.weight, 0);
+
+ let progressPercent = 0;
+ for (const stage of stages) {
+ const stageDef = ISSUE_FIX_STAGES.find(s => s.name === stage.stage);
+ if (!stageDef || stageDef.skip) continue;
+
+ if (stage.status === "success") {
+ progressPercent += stageDef.weight;
+ } else if (stage.status === "running") {
+ progressPercent += stageDef.weight * 0.5;
+ }
+ }
+
+ return Math.round(progressPercent / totalWeight * 100);
+}
+
+// Format progress bar (40 blocks for 40-char column)
+function formatProgressBar(percent: number): string {
+ const filled = Math.round(percent * 29 / 100);
+ const empty = 29 - filled;
+ return "█".repeat(filled) + "░".repeat(empty);
+}
+
+// Table format for issue list display
+export interface IssueListRow {
+ issue: number;
+ status: string;
+ stage?: string;
+ progress?: number;
+ details: string;
+ prUrl?: string;
+}
+
+// Issue matrix row type
+export interface IssueMatrixRow {
+ number: number;
+ title: string;
+ body?: string;
+ labels?: string[];
+ difficulty: string;
+ updated_at?: string;
+}
+
+// Issue matrix result type
+export type IssueMatrixResult = {
+ error?: string;
+ owner?: string;
+ repo?: string;
+ total?: number;
+ added?: number;
+ removed?: number;
+ updated?: number;
+ difficulty_counts?: Record<string, number>;
+ matrix?: IssueMatrixRow[];
+ has_more?: boolean;
+ page?: number;
+ per_page?: number;
+ cached?: boolean;
+ labels_filter?: string[];
+};
+
+// Helper: calculate visual width (CJK chars = 2, ASCII = 1)
+function matrixVisualWidth(str: string): number {
+ let width = 0;
+ for (let i = 0; i < str.length; i++) {
+ const code = str.codePointAt(i) || 0;
+ // Box drawing characters (U+2500-U+257F) are width 1
+ if (code >= 0x2500 && code <= 0x257F) {
+ width += 1;
+ } else if (
+ (code >= 0x4E00 && code <= 0x9FFF) || // CJK Unified Ideographs
+ (code >= 0x3000 && code <= 0x303F) || // CJK Symbols
+ (code >= 0xFF00 && code <= 0xFFEF) || // Halfwidth/Fullwidth
+ code >= 0x1F000 // Emoji
+ ) {
+ width += 2;
+ } else {
+ width += 1;
+ }
+ if (code > 0xFFFF) i++; // Skip low surrogate
+ }
+ return width;
+}
+
+// Helper: pad string to visual width
+function matrixPadRight(str: string, targetWidth: number): string {
+ const currentWidth = matrixVisualWidth(str);
+ if (currentWidth >= targetWidth) return str;
+ return str + " ".repeat(targetWidth - currentWidth);
+}
+
+// Helper: truncate string to visual width
+function matrixTruncateToWidth(str: string, maxWidth: number): string {
+ let result = "";
+ let width = 0;
+ for (let i = 0; i < str.length; i++) {
+ const char = str[i];
+ const code = str.codePointAt(i) || 0;
+ let charWidth = 1;
+ if (
+ (code >= 0x4E00 && code <= 0x9FFF) ||
+ (code >= 0x3000 && code <= 0x303F) ||
+ (code >= 0xFF00 && code <= 0xFFEF) ||
+ code >= 0x1F000
+ ) {
+ charWidth = 2;
+ }
+ if (code > 0xFFFF) i++; // Skip low surrogate
+
+ if (width + charWidth <= maxWidth) {
+ result += char;
+ width += charWidth;
+ } else {
+ break;
+ }
+ }
+ return result;
+}
+
+// Helper: wrap text to fixed visual width, returns array of lines
+// Handles embedded newlines in the input string
+function matrixWrapText(str: string, maxWidth: number): string[] {
+ const result: string[] = [];
+ // First split by existing newlines in the string
+ const paragraphs = str.split(/\r?\n/);
+ for (const paragraph of paragraphs) {
+ if (paragraph.length === 0) {
+ result.push("");
+ continue;
+ }
+ let remaining = paragraph;
+ while (matrixVisualWidth(remaining) > maxWidth) {
+ const line = matrixTruncateToWidth(remaining, maxWidth);
+ result.push(line);
+ remaining = remaining.slice(line.length);
+ }
+ if (remaining.length > 0) {
+ result.push(remaining);
+ }
+ }
+ return result.length > 0 ? result : [""];
+}
+
+// Format issue matrix for display (table format with wrapping)
+export function formatIssueMatrix(result: IssueMatrixResult): string {
+ if (result.error) {
+ return `\n矩阵刷新失败: ${result.error}\n`;
+ }
+
+ // Fixed column widths (visual width)
+ const COL_ISSUE = 8; // "#1270 "
+ const COL_TITLE = 60; // Title column
+ const COL_DIFF = 8; // "low "
+ const COL_DATE = 12; // "2026-06-11 "
+
+ const lines: string[] = [];
+ const page = result.page || 1;
+ const cached = result.cached ? "(缓存)" : "";
+ const labelsInfo = result.labels_filter && result.labels_filter.length > 0 ? ` [${result.labels_filter.join(",")}]` : "";
+ const pageInfo = result.total && result.per_page ? ` 第${page}/${Math.ceil(result.total / result.per_page)}页` : "";
+ lines.push(`\nIssues 信息如下:`);
+
+ // Table header
+ const headerIssue = matrixPadRight("Issue", COL_ISSUE);
+ const headerTitle = matrixPadRight("名称", COL_TITLE);
+ const headerDiff = matrixPadRight("难度", COL_DIFF);
+ const headerDate = matrixPadRight("更新时间", COL_DATE);
+ lines.push(`┌${"─".repeat(COL_ISSUE)}┬${"─".repeat(COL_TITLE)}┬${"─".repeat(COL_DIFF)}┬${"─".repeat(COL_DATE)}┐`);
+ lines.push(`│${headerIssue}│${headerTitle}│${headerDiff}│${headerDate}│`);
+ lines.push(`├${"─".repeat(COL_ISSUE)}┼${"─".repeat(COL_TITLE)}┼${"─".repeat(COL_DIFF)}┼${"─".repeat(COL_DATE)}┤`);
+
+ // Issue rows with wrapping (each issue separated by horizontal line)
+ const matrix = result.matrix || [];
+ const separator = `├${"─".repeat(COL_ISSUE)}┼${"─".repeat(COL_TITLE)}┼${"─".repeat(COL_DIFF)}┼${"─".repeat(COL_DATE)}┤`;
+
+ for (let idx = 0; idx < matrix.length; idx++) {
+ const issue = matrix[idx];
+ const issueNum = matrixPadRight(`${issue.number}`, COL_ISSUE);
+ const titleLines = matrixWrapText(issue.title || "", COL_TITLE);
+ const difficulty = matrixPadRight(issue.difficulty || "unclear", COL_DIFF);
+ const date = matrixPadRight(issue.updated_at?.substring(0, 10) || "-", COL_DATE);
+
+ // First line: all columns
+ const firstTitle = matrixPadRight(titleLines[0], COL_TITLE);
+ lines.push(`│${issueNum}│${firstTitle}│${difficulty}│${date}│`);
+
+ // Subsequent lines: only title column (if wrapped)
+ for (let i = 1; i < titleLines.length; i++) {
+ const wrapTitle = matrixPadRight(titleLines[i], COL_TITLE);
+ lines.push(`│${matrixPadRight("", COL_ISSUE)}│${wrapTitle}│${matrixPadRight("", COL_DIFF)}│${matrixPadRight("", COL_DATE)}│`);
+ }
+
+ // Add separator between issues (not after the last one)
+ if (idx < matrix.length - 1) {
+ lines.push(separator);
+ }
+ }
+
+ // Table footer
+ lines.push(`└${"─".repeat(COL_ISSUE)}┴${"─".repeat(COL_TITLE)}┴${"─".repeat(COL_DIFF)}┴${"─".repeat(COL_DATE)}┘`);
+
+ // Statistics (after table)
+ const counts = result.difficulty_counts || {};
+ const diffStats = Object.entries(counts)
+ .map(([k, v]) => `${k}(${v})`)
+ .join(" ");
+ lines.push(`\n数据汇总: ${result.owner}/${result.repo}${labelsInfo} (${result.total} issues)${pageInfo}${cached}`);
+ lines.push(`难度分布: ${diffStats}`);
+ if (!result.cached && (result.added || result.removed || result.updated)) {
+ lines.push(`本次更新: 新增 ${result.added || 0} | 更新 ${result.updated || 0} | 移除 ${result.removed || 0}`);
+ }
+
+ // Tips
+ if (result.has_more) {
+ lines.push("");
+ const nextPage = (result.page || 1) + 1;
+ lines.push(`💡显示 50 条issue,使用 --page ${nextPage} 查看更多`);
+ }
+ if (result.cached) {
+ lines.push("💡 使用 --force-refresh 强制更新");
+ }
+ lines.push("");
+ lines.push("💡 /auto-harness issue fix 编号 执行修复");
+
+ return lines.join("\n");
+}
+
+// Map status to shorter display name
+function displayStatus(status: string): string {
+ const statusMap: Record<string, string> = {
+ "task_created": "created",
+ "queued": "queued",
+ "pending": "pending",
+ "running": "running",
+ "success": "success",
+ "failed": "failed",
+ "cancelled": "cancelled",
+ "skipped": "skipped",
+ "needs_human": "needs_human",
+ "pr_created": "pr_ok",
+ };
+ return statusMap[status] || status.substring(0, 8);
+}
+
+export function formatIssueTable(rows: IssueListRow[]): string {
+ if (rows.length === 0) {
+ return "\n暂无 GitCode issue 处理记录\n";
+ }
+
+ const lines: string[] = [];
+ // Fixed column widths
+ const COL_ISSUE = 8; // "#1416 "
+ const COL_STATUS = 10; // "created "
+ const COL_STAGE = 14; // "implement "
+ const COL_PROGRESS = 30; // "██░░░░░░░░ "
+ const COL_DETAILS = 30; // Details column
+
+ // Header
+ lines.push(`┌${"─".repeat(COL_ISSUE)}┬${"─".repeat(COL_STATUS)}┬${"─".repeat(COL_STAGE)}┬${"─".repeat(COL_PROGRESS)}┬${"─".repeat(COL_DETAILS)}┐`);
+ lines.push(`│${matrixPadRight("Issue", COL_ISSUE)}│${matrixPadRight("Status", COL_STATUS)}│${matrixPadRight("Stage", COL_STAGE)}│${matrixPadRight("Progress", COL_PROGRESS)}│${matrixPadRight("DeTails", COL_DETAILS)}│`);
+ lines.push(`├${"─".repeat(COL_ISSUE)}┼${"─".repeat(COL_STATUS)}┼${"─".repeat(COL_STAGE)}┼${"─".repeat(COL_PROGRESS)}┼${"─".repeat(COL_DETAILS)}┤`);
+
+ // Rows with separators between each row
+ const separator = `├${"─".repeat(COL_ISSUE)}┼${"─".repeat(COL_STATUS)}┼${"─".repeat(COL_STAGE)}┼${"─".repeat(COL_PROGRESS)}┼${"─".repeat(COL_DETAILS)}┤`;
+ const displayRows = rows.slice(-20);
+ for (let idx = 0; idx < displayRows.length; idx++) {
+ const row = displayRows[idx];
+ const issueNum = matrixPadRight(`#${row.issue}`, COL_ISSUE);
+ const status = matrixPadRight(displayStatus(row.status || "unknown"), COL_STATUS);
+ const stage = matrixPadRight(row.stage || "-", COL_STAGE);
+ const progress = matrixPadRight(formatProgressBar(row.progress || 0), COL_PROGRESS);
+ let details = row.details || "";
+ if (row.prUrl) {
+ details = `PR: ${row.prUrl}`;
+ }
+ // Wrap details to fit column width (support multiline)
+ const detailLines = matrixWrapText(details, COL_DETAILS);
+ const firstDetail = matrixPadRight(detailLines[0], COL_DETAILS);
+ lines.push(`│${issueNum}│${status}│${stage}│${progress}│${firstDetail}│`);
+ for (let i = 1; i < detailLines.length; i++) {
+ const wrapDetail = matrixPadRight(detailLines[i], COL_DETAILS);
+ lines.push(`│${matrixPadRight("", COL_ISSUE)}│${matrixPadRight("", COL_STATUS)}│${matrixPadRight("", COL_STAGE)}│${matrixPadRight("", COL_PROGRESS)}│${wrapDetail}│`);
+ }
+ // Add separator between rows (not after the last one)
+ if (idx < displayRows.length - 1) {
+ lines.push(separator);
+ }
+ }
+
+ // Footer
+ lines.push(`└${"─".repeat(COL_ISSUE)}┴${"─".repeat(COL_STATUS)}┴${"─".repeat(COL_STAGE)}┴${"─".repeat(COL_PROGRESS)}┴${"─".repeat(COL_DETAILS)}┘`);
+ lines.push("");
+ lines.push("💡使用 /auto-harness schedule logs <task id> 查看详细日志信息");
+ return "\n" + lines.join("\n");
+}
+
+export function isIssueFixWatchDone(items: IssueFixWatchItem[]): boolean {
+ return items.every((item) => ISSUE_FIX_TERMINAL_STATUSES.has(item.status));
+}
+
+export function issueStartIntervalSeconds(concurrency: number): number {
+ if (concurrency <= 1) return 8;
+ if (concurrency === 2) return 2;
+ return 1.2;
+}
+
+export function parseIssueNumbers(value: string): number[] {
+ return value
+ .split(/[,\s,]+/)
+ .map((v) => parseInt(v.trim(), 10))
+ .filter((v, index, arr) => Number.isFinite(v) && v > 0 && arr.indexOf(v) === index);
+}
+
+export function parseIssueWatchArgs(
+ args: string,
+ resolvePipelineName: PipelineNameResolver,
+): IssueWatchArgs {
+ const parts = parseArgs(args);
+ let repo = "";
+ let labels = ["auto-harness"];
+ let max_issues = 1;
+ let dry_run = ""; // 空值触发交互
+ let comment_on_start = false;
+ let pipeline = "meta_evolve_pipeline";
+ let issue_numbers: number[] = [];
+ let max_auto_difficulty = "";
+ let concurrency = 1;
+
+ let i = 0;
+ while (i < parts.length) {
+ const part = parts[i];
+ if (part === "--repo" && i + 1 < parts.length) {
+ repo = parts[i + 1];
+ i += 2;
+ } else if ((part === "--label" || part === "--labels") && i + 1 < parts.length) {
+ labels = parts[i + 1]
+ .split(",")
+ .map((v) => v.trim())
+ .filter(Boolean);
+ i += 2;
+ } else if ((part === "--max" || part === "--max-issues") && i + 1 < parts.length) {
+ const parsed = parseInt(parts[i + 1], 10);
+ max_issues = Number.isFinite(parsed) ? parsed : 1;
+ i += 2;
+ } else if ((part === "--issue" || part === "--issues") && i + 1 < parts.length) {
+ issue_numbers = parseIssueNumbers(parts[i + 1]);
+ i += 2;
+ } else if (part === "--pipeline" && i + 1 < parts.length) {
+ pipeline = resolvePipelineName(parts[i + 1]);
+ i += 2;
+ } else if ((part === "--max-difficulty" || part === "--difficulty") && i + 1 < parts.length) {
+ max_auto_difficulty = parts[i + 1].toLowerCase();
+ i += 2;
+ } else if (part === "--concurrency" && i + 1 < parts.length) {
+ const parsed = parseInt(parts[i + 1], 10);
+ concurrency = Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
+ i += 2;
+ } else if (part === "--dry-run") {
+ dry_run = "yes";
+ i += 1;
+ } else if (part === "--comment") {
+ comment_on_start = true;
+ i += 1;
+ } else {
+ i += 1;
+ }
+ }
+
+ if (issue_numbers.length > 0) {
+ max_issues = issue_numbers.length;
+ }
+
+ return {
+ repo,
+ labels,
+ max_issues,
+ dry_run,
+ comment_on_start,
+ pipeline,
+ issue_numbers,
+ max_auto_difficulty,
+ concurrency,
+ };
+}
+
+export function parseIssueFixArgs(
+ args: string,
+ resolvePipelineName: PipelineNameResolver,
+): IssueFixArgs {
+ const parts = parseArgs(args);
+ let repo = "";
+ let dry_run = "no";
+ let comment_on_start = false;
+ let pipeline = "meta_evolve_pipeline";
+ let max_auto_difficulty = "medium";
+ let concurrency = 1;
+ const numberParts: string[] = [];
+
+ let i = 0;
+ while (i < parts.length) {
+ const part = parts[i];
+ if (part === "--repo" && i + 1 < parts.length) {
+ repo = parts[i + 1];
+ i += 2;
+ } else if (part === "--pipeline" && i + 1 < parts.length) {
+ pipeline = resolvePipelineName(parts[i + 1]);
+ i += 2;
+ } else if ((part === "--max-difficulty" || part === "--difficulty") && i + 1 < parts.length) {
+ max_auto_difficulty = parts[i + 1].toLowerCase();
+ i += 2;
+ } else if (part === "--concurrency" && i + 1 < parts.length) {
+ const parsed = parseInt(parts[i + 1], 10);
+ concurrency = Number.isFinite(parsed) && parsed > 0 ? parsed : 1;
+ i += 2;
+ } else if (part === "--dry-run") {
+ dry_run = "yes";
+ i += 1;
+ } else if (part === "--comment") {
+ comment_on_start = true;
+ i += 1;
+ } else {
+ numberParts.push(part);
+ i += 1;
+ }
+ }
+
+ return {
+ repo,
+ issue_numbers: parseIssueNumbers(numberParts.join(",")),
+ dry_run,
+ comment_on_start,
+ pipeline,
+ max_auto_difficulty,
+ concurrency,
+ };
+}
+
+export function formatIssueWatchResult(result: IssueWatchResult): string {
+ const lines = ["\nGitCode issue 处理完成", "━━━━━━━━━━━━━━━━━━━━━━"];
+ lines.push(`拉取数量: ${result.fetched ?? 0}`);
+ lines.push(`新建任务: ${result.started?.length ?? 0}`);
+ for (const item of result.started || []) {
+ const difficulty = item.difficulty?.level ? ` difficulty=${item.difficulty.level}` : "";
+ lines.push(
+ ` #${item.number ?? item.issue}: ${item.task_id || item.status || "dry-run"}${difficulty}`,
+ );
+ }
+ if (result.reconciled && result.reconciled.length > 0) {
+ lines.push(`状态更新: ${result.reconciled.length}`);
+ for (const item of result.reconciled) {
+ lines.push(` #${item.number}: ${item.status}${item.pr_url ? ` ${item.pr_url}` : ""}`);
+ }
+ }
+ if (result.skipped && result.skipped.length > 0) {
+ lines.push(`跳过: ${result.skipped.length}`);
+ for (const item of result.skipped.slice(0, 10)) {
+ const difficulty = item.difficulty?.level ? ` difficulty=${item.difficulty.level}` : "";
+ const human = item.human_label ? ` label=${item.human_label}` : "";
+ lines.push(
+ ` #${item.issue}: ${item.reason || item.status || "skipped"}${difficulty}${human}`,
+ );
+ }
+ }
+ lines.push("━━━━━━━━━━━━━━━━━━━━━━");
+ return lines.join("\n");
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/auto-harness.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/auto-harness.ts
index be825950ff..c114e9877e 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
@@ -2,6 +2,19 @@
import { addError, addInfo, parseArgs } from "../helpers.js";
import { CommandKind, type SlashCommand, type CommandContext } from "../types.js";
+import {
+ ISSUE_DIFFICULTY_VALUES,
+ formatIssueWatchResult,
+ issueStartIntervalSeconds,
+ parseIssueFixArgs,
+ REPO_OPTIONS,
+ resolveRepoName,
+ type IssueListRow,
+ formatIssueTable,
+ calculateStageProgress,
+ formatIssueMatrix,
+ type IssueMatrixResult,
+} from "./auto-harness-issue-fix.js";
// Pipeline options: friendly display names → backend values
export const PIPELINE_DISPLAY_NAMES = {
@@ -118,6 +131,63 @@ function getPipelineCompletions(_partial: string, parts: string[]): string[] {
// Helper functions
+type AutoHarnessStageProgress = {
+ stage: string;
+ name?: string;
+ status: string;
+ messages?: string[];
+};
+
+type AutoHarnessProgress = {
+ summary?: string;
+ stages?: AutoHarnessStageProgress[];
+ completed_stages?: string[];
+ current_stage?: string;
+ failed_stage?: string;
+ last_message?: string;
+ last_error?: string;
+ failure_code?: string;
+ pr_url?: string;
+};
+
+function stageProgressIcon(status?: string): string {
+ switch (status) {
+ case "success":
+ return "✅";
+ case "failed":
+ return "❌";
+ case "running":
+ return "🔄";
+ case "pending":
+ return "⏳";
+ default:
+ return "·";
+ }
+}
+
+function formatProgressLine(progress?: AutoHarnessProgress): string {
+ if (!progress) return "";
+ const summary = progress.summary || "";
+ if (!summary) return "";
+ return ` 进度: ${summary}`;
+}
+
+function formatProgressBlock(progress?: AutoHarnessProgress): string[] {
+ if (!progress || !progress.stages || progress.stages.length === 0) {
+ return [];
+ }
+ const lines = ["", "阶段进度:"];
+ for (const stage of progress.stages) {
+ const name = stage.name || stage.stage;
+ const icon = stageProgressIcon(stage.status);
+ lines.push(` ${icon} ${name}: ${stage.status}`);
+ }
+ if (progress.last_message) {
+ lines.push(` 最近: ${progress.last_message}`);
+ }
+ return lines;
+}
+
function parseScheduleStartArgs(args: string): { interval: number; pipeline: string; query: string } {
const parts = parseArgs(args);
@@ -373,9 +443,9 @@ const scheduleListCommand: SlashCommand = {
action: async (ctx, _args) => {
ctx.addItem(addInfo(ctx.sessionId, "\n🔍 正在查询任务...\n", "i"));
- const result = await ctx.request<{ tasks?: Array<{ task_id: string; query: string; status: string; interval_hours: number; next_run_time: string; created_at: string; is_one_time?: boolean; pipeline?: string }> }>("schedule.list", {});
+ const result = await ctx.request<{ tasks?: Array<{ task_id: string; query: string; status: string; interval_hours: number; next_run_time: string; created_at: string; is_one_time?: boolean; pipeline?: string; progress?: AutoHarnessProgress }> }>("schedule.list", {});
- const tasks = result.tasks as Array<{ task_id: string; query: string; status: string; interval_hours: number; next_run_time: string; created_at: string; is_one_time?: boolean; pipeline?: string }> | undefined;
+ const tasks = result.tasks as Array<{ task_id: string; query: string; status: string; interval_hours: number; next_run_time: string; created_at: string; is_one_time?: boolean; pipeline?: string; progress?: AutoHarnessProgress }> | undefined;
if (!tasks || tasks.length === 0) {
ctx.addItem(addInfo(ctx.sessionId, "\n📭 暂无任务\n💡 使用 /auto-harness schedule start 创建定时任务\n 使用 /auto-harness run 创建一次性任务\n", "i"));
return;
@@ -401,6 +471,8 @@ const scheduleListCommand: SlashCommand = {
} else {
lines.push(` 状态: ${task.status} | 间隔: ${task.interval_hours}h | 下次执行: ${formatLocalTime(task.next_run_time)}${pipelineInfo ? ` | ${pipelineInfo}` : ""}`);
}
+ const progressLine = formatProgressLine(task.progress);
+ if (progressLine) lines.push(progressLine);
lines.push(` 创建时间: ${formatLocalTime(task.created_at)}`);
lines.push("");
}
@@ -439,7 +511,7 @@ const scheduleStatusCommand: SlashCommand = {
return;
}
- const result = await ctx.request<{ error?: string; task_id?: string; query?: string; status?: string; interval_hours?: number; created_at?: string; next_run_time?: string; current_execution_id?: string; execution_history?: Array<{ execution_id: string; status: string; completed_at?: string }>; is_one_time?: boolean; pipeline?: string }>("schedule.status", { task_id });
+ const result = await ctx.request<{ error?: string; task_id?: string; query?: string; status?: string; interval_hours?: number; created_at?: string; next_run_time?: string; current_execution_id?: string; execution_history?: Array<{ execution_id: string; status: string; completed_at?: string }>; is_one_time?: boolean; pipeline?: string; progress?: AutoHarnessProgress }>("schedule.status", { task_id });
if (result.error) {
ctx.addItem(
@@ -473,6 +545,7 @@ const scheduleStatusCommand: SlashCommand = {
lines.push(`\n🔄 当前执行: ${result.current_execution_id}`);
lines.push(`💡 使用 /auto-harness schedule logs ${result.task_id} 查看实时日志`);
}
+ lines.push(...formatProgressBlock(result.progress));
const history = result.execution_history as Array<{ execution_id: string; status: string; completed_at?: string }> | undefined;
if (history && history.length > 0) {
@@ -2078,6 +2151,345 @@ const runCommand: SlashCommand = {
},
};
+const issueScanCommand: SlashCommand = {
+ name: "scan",
+ description: "扫描仓库所有 GitCode issue 并生成分析矩阵",
+ usage: "/auto-harness issue scan [--page <页码>] [--labels <标签>]",
+ example: "/auto-harness issue scan --repo jiuwenswarm",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const parts = parseArgs(args);
+ let repo = "";
+ let forceRefresh = ""; // 空值触发交互
+ let page = 1;
+ let labels = ""; // 默认只显示 bug 类型
+
+ for (let i = 0; i < parts.length; i++) {
+ const part = parts[i];
+ if (part === "--repo" && i + 1 < parts.length) {
+ repo = parts[i + 1];
+ i += 1;
+ } else if (part === "--force-refresh") {
+ forceRefresh = "yes";
+ } else if (part === "--page" && i + 1 < parts.length) {
+ const parsed = parseInt(parts[i + 1], 10);
+ if (Number.isFinite(parsed) && parsed > 0) {
+ page = parsed;
+ }
+ i += 1;
+ } else if (part === "--labels" && i + 1 < parts.length) {
+ labels = parts[i + 1];
+ i += 1;
+ } else if (part === "--all") {
+ // --all 表示显示所有类型,等同于 --labels ""
+ labels = "";
+ }
+ }
+
+ // Repo 二选一交互:未指定则弹出选择框
+ if (!repo) {
+ const [answer] = await ctx.askQuestions([
+ {
+ header: "仓库",
+ question: "请选择目标仓库:",
+ options: [
+ { label: "jiuwenswarm", description: REPO_OPTIONS.jiuwenswarm.desc },
+ { label: "agent_core", description: REPO_OPTIONS.agent_core.desc },
+ ],
+ },
+ ]);
+ if (!answer.selected_options[0]) {
+ ctx.addItem(addInfo(ctx.sessionId, "已取消"));
+ return;
+ }
+ repo = resolveRepoName(answer.selected_options[0]);
+ } else {
+ repo = resolveRepoName(repo);
+ }
+
+ // 强制刷新二选一交互:未指定则弹出选择框
+ if (!forceRefresh) {
+ const [answer] = await ctx.askQuestions([
+ {
+ header: "刷新",
+ question: "是否强制刷新(重新调用 GitCode API)?",
+ options: [
+ { label: "否(推荐)", description: "使用缓存数据,快速返回" },
+ { label: "是", description: "强制调用 API,更新最新数据" },
+ ],
+ },
+ ]);
+ if (!answer.selected_options[0]) {
+ ctx.addItem(addInfo(ctx.sessionId, "已取消"));
+ return;
+ }
+ forceRefresh = answer.selected_options[0] === "是" ? "yes" : "no";
+ }
+
+ const actualForceRefresh = forceRefresh === "yes";
+
+ ctx.addItem(addInfo(ctx.sessionId, `\n正在扫描 GitCode issue 矩阵...\n仓库: ${repo}\n${labels ? `标签过滤: ${labels}\n` : "显示所有类型\n"}${actualForceRefresh ? "强制刷新所有\n" : ""}${page > 1 ? `页码: ${page}\n` : ""}`, "i"));
+
+ const result = await ctx.request<IssueMatrixResult>("issue.matrix", {
+ repo,
+ force_refresh: actualForceRefresh,
+ page,
+ labels,
+ });
+
+ ctx.addItem(addInfo(ctx.sessionId, formatIssueMatrix(result)));
+ },
+};
+
+const issueFixCommand: SlashCommand = {
+ name: "fix",
+ description: "指定单个或多个 GitCode issue 创建独立修复任务",
+ usage: "/auto-harness issue fix <issue_number(s)>",
+ example: "/auto-harness issue fix 1272,1271,1270",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const parsed = parseIssueFixArgs(args, resolvePipelineName);
+ if (parsed.issue_numbers.length === 0) {
+ ctx.addItem(addError(ctx.sessionId, "请提供 issue 编号\n示例: /auto-harness issue fix 1272,1271,1270"));
+ return;
+ }
+
+ // Repo 二选一交互:未指定则弹出选择框
+ if (!parsed.repo) {
+ const [answer] = await ctx.askQuestions([
+ {
+ header: "仓库",
+ question: "请选择目标仓库:",
+ options: [
+ { label: "jiuwenswarm", description: REPO_OPTIONS.jiuwenswarm.desc },
+ { label: "agent_core", description: REPO_OPTIONS.agent_core.desc },
+ ],
+ },
+ ]);
+ if (!answer.selected_options[0]) {
+ ctx.addItem(addInfo(ctx.sessionId, "已取消"));
+ return;
+ }
+ parsed.repo = resolveRepoName(answer.selected_options[0]);
+ } else {
+ // 用户指定了 --repo,解析别名或完整值
+ parsed.repo = resolveRepoName(parsed.repo);
+ }
+
+ if (!PIPELINE_BACKEND_VALUES.includes(parsed.pipeline)) {
+ ctx.addItem(addError(ctx.sessionId, `无效的 pipeline: ${parsed.pipeline}`));
+ return;
+ }
+
+ // 难度已在 scan 矩阵中展示,默认 medium,不再交互
+ if (!ISSUE_DIFFICULTY_VALUES.has(parsed.max_auto_difficulty)) {
+ ctx.addItem(addError(ctx.sessionId, `无效的难度上限: ${parsed.max_auto_difficulty}\n可选值: low, medium, high, unclear`));
+ return;
+ }
+
+ const configCheck = await ctx.request<{ valid: boolean; missing_fields?: Array<{ id: string; prompt: string }> }>("schedule.check_config", {});
+ const missingFields = configCheck.missing_fields as Array<{ id: string; prompt: string }> | undefined;
+ if (missingFields && missingFields.length > 0) {
+ const missingList = missingFields.map(f => ` - ${f.prompt}`).join("\n");
+ ctx.addItem(addInfo(ctx.sessionId, `GitCode issue 自动处理需要配置:\n${missingList}\n\n请使用 /config edit 配置这些字段后重试`));
+ return;
+ }
+
+ const isDryRun = parsed.dry_run === "yes";
+ ctx.addItem(addInfo(ctx.sessionId, `\n正在为指定 GitCode issue 创建修复任务...\n仓库: ${parsed.repo}\nIssue: ${parsed.issue_numbers.map(n => `#${n}`).join(", ")}\n难度上限: ${parsed.max_auto_difficulty}\n执行模式: ${isDryRun ? "预演" : "正式执行"}\n并发启动: ${parsed.concurrency}\n`, "i"));
+ const result = await ctx.request<{
+ error?: string;
+ fetched?: number;
+ started?: Array<{ number?: number; issue?: number; task_id?: string; status?: string; title?: string }>;
+ skipped?: Array<{ issue?: number; reason?: string; status?: string }>;
+ reconciled?: Array<{ number?: number; status?: string; pr_url?: string }>;
+ }>("issue.watch_once", {
+ repo: parsed.repo,
+ issue_numbers: parsed.issue_numbers,
+ max_issues: parsed.issue_numbers.length,
+ dry_run: isDryRun,
+ comment_on_start: parsed.comment_on_start,
+ pipeline: parsed.pipeline,
+ max_auto_difficulty: parsed.max_auto_difficulty,
+ start_interval_seconds: issueStartIntervalSeconds(parsed.concurrency),
+ });
+
+ if (result.error) {
+ ctx.addItem(addError(ctx.sessionId, `创建失败: ${result.error}`));
+ return;
+ }
+
+ ctx.addItem(addInfo(ctx.sessionId, formatIssueWatchResult(result)));
+ if (isDryRun) {
+ return;
+ }
+
+ // Collect created task IDs for guidance display
+ const taskEntries = (result.started || [])
+ .map(s => ({ issue: s.number ?? s.issue ?? 0, taskId: s.task_id || "" }))
+ .filter(e => e.taskId);
+
+ if (taskEntries.length > 0) {
+ const lines: string[] = ["\n后台任务已提交执行", "━━━━━━━━━━━━━━━━━━━━━━"];
+ for (const { issue, taskId } of taskEntries) {
+ lines.push(` #${issue} task: ${taskId}`);
+ }
+ lines.push("━━━━━━━━━━━━━━━━━━━━━━");
+ lines.push("💡 查看进度:");
+ lines.push(" /auto-harness issue status 查看 issue 总体进度");
+ if (taskEntries.length === 1) {
+ lines.push(` /auto-harness schedule status ${taskEntries[0].taskId} 查看该任务详细日志`);
+ } else {
+ lines.push(" /auto-harness schedule status <task_id> 查看各任务详细日志");
+ }
+ ctx.addItem(addInfo(ctx.sessionId, lines.join("\n")));
+ }
+ },
+};
+
+const issueDeleteCommand: SlashCommand = {
+ name: "delete",
+ description: "删除 issue 处理记录和运行日志",
+ usage: "/auto-harness issue delete <issue_numbers> [--completed] [--failed]",
+ example: "/auto-harness issue delete 123 456",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const parts = parseArgs(args);
+ const issueNumbers: number[] = [];
+ let deleteCompleted = false;
+ let deleteFailed = false;
+
+ for (const part of parts) {
+ if (part === "--completed") {
+ deleteCompleted = true;
+ } else if (part === "--failed") {
+ deleteFailed = true;
+ } else {
+ const num = parseInt(part, 10);
+ if (Number.isFinite(num) && num > 0) {
+ issueNumbers.push(num);
+ }
+ }
+ }
+
+ if (issueNumbers.length === 0 && !deleteCompleted && !deleteFailed) {
+ ctx.addItem(addError(ctx.sessionId, "用法: /auto-harness issue delete <issue_numbers> [--completed] [--failed]\n示例:\n /auto-harness issue delete 123\n /auto-harness issue delete 123 456\n /auto-harness issue delete --completed\n /auto-harness issue delete --failed"));
+ return;
+ }
+
+ // 调用后端 delete RPC
+ const result = await ctx.request<{
+ error?: string;
+ deleted?: Array<{ issue: number; task_id?: string; log_size?: string }>;
+ rejected?: Array<{ issue: number; reason: string }>;
+ }>("issue.delete", {
+ issue_numbers: issueNumbers,
+ delete_completed: deleteCompleted,
+ delete_failed: deleteFailed,
+ });
+
+ if (result.error) {
+ ctx.addItem(addError(ctx.sessionId, `删除失败: ${result.error}`));
+ return;
+ }
+
+ const lines = ["\n删除结果", "━━━━━━━━━━━━━━━━━━━━━━"];
+ if (result.deleted && result.deleted.length > 0) {
+ lines.push(`已删除: ${result.deleted.length} 条记录`);
+ for (const item of result.deleted) {
+ lines.push(` #${item.issue}${item.task_id ? ` task: ${item.task_id}` : ""}`);
+ }
+ }
+ if (result.rejected && result.rejected.length > 0) {
+ lines.push(`拒绝删除: ${result.rejected.length} 条`);
+ for (const item of result.rejected) {
+ lines.push(` #${item.issue}: ${item.reason}`);
+ }
+ }
+ lines.push("━━━━━━━━━━━━━━━━━━━━━━");
+ ctx.addItem(addInfo(ctx.sessionId, lines.join("\n")));
+ },
+};
+
+const issueStatusCommand: SlashCommand = {
+ name: "status",
+ description: "查看 GitCode issue 处理状态",
+ usage: "/auto-harness issue status",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: false,
+ action: async (ctx, _args) => {
+ ctx.addItem(addInfo(ctx.sessionId, "\n正在查询 GitCode issue 处理记录...\n", "i"));
+ const result = await ctx.request<{ issues?: Array<{ key?: string; number?: number; status?: string; task_id?: string; task_status?: string; title?: string; pr_url?: string; reason?: string; progress?: AutoHarnessProgress }> }>("issue.state.list", {});
+ const issues = result.issues || [];
+
+ // 转换为表格行格式
+ const rows: IssueListRow[] = issues.map((issue) => {
+ const number = issue.number || parseInt(String(issue.key || "").split("#").pop() || "0", 10);
+ const reason = issue.reason || "";
+ const stage = issue.progress?.current_stage || issue.progress?.stages?.find(s => s.status === "running")?.stage || "";
+ const progressPercent = issue.progress?.stages ? calculateStageProgress(issue.progress.stages) : 0;
+
+ const isTaskDeleted = issue.task_status === "task_deleted";
+ const inFlightStatuses = new Set(["task_created", "running"]);
+ const effectiveStatus = isTaskDeleted
+ ? "task_deleted"
+ : (issue.task_id && issue.task_status && inFlightStatuses.has(issue.status || "")
+ ? issue.task_status
+ : (issue.status || "unknown"));
+
+ // 终态任务进度显示100%或0%
+ const terminalStatuses = new Set(["success", "failed", "pr_created", "completed", "skipped", "needs_human"]);
+ const finalProgress = terminalStatuses.has(effectiveStatus) ? (effectiveStatus === "success" || effectiveStatus === "pr_created" ? 100 : 0) : progressPercent;
+
+ let details = "";
+ if (issue.pr_url) {
+ details = `PR: ${issue.pr_url}`;
+ } else if (issue.task_id) {
+ details = `task: ${issue.task_id}`;
+ } else if (reason) {
+ // Strip URLs from reason for compact display
+ details = reason.replace(/https?:\/\/\S+/g, "").replace(/;+\s*;+/g, ";").replace(/:\s*$/, "").trim();
+ } else if (issue.title) {
+ details = issue.title.substring(0, 30);
+ }
+
+ return {
+ issue: number,
+ status: effectiveStatus,
+ stage,
+ progress: finalProgress,
+ details,
+ prUrl: issue.pr_url,
+ };
+ });
+
+ ctx.addItem(addInfo(ctx.sessionId, formatIssueTable(rows)));
+ },
+};
+
+const issueCommand: SlashCommand = {
+ name: "issue",
+ description: "GitCode issue 自动处理",
+ usage: "/auto-harness issue <scan|fix|status|delete>",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ subCommands: [issueFixCommand, issueScanCommand, issueStatusCommand, issueDeleteCommand],
+ completion: (_ctx, partial) => {
+ const subNames = ["scan", "fix", "status", "delete"];
+ const prefix = partial.trim().toLowerCase();
+ if (!prefix) return subNames;
+ return subNames.filter((n) => n.startsWith(prefix));
+ },
+ action: (ctx, args) => {
+ if (!args.trim()) {
+ ctx.addItem(addError(ctx.sessionId, "用法: /auto-harness issue <fix|scan|status|delete>\n示例:\n /auto-harness issue fix 1272,1271\n /auto-harness issue scan --repo jiuwenswarm\n /auto-harness issue status\n /auto-harness issue delete 123"));
+ }
+ },
+};
+
// Main auto-harness command
export function createAutoHarnessCommand(): SlashCommand {
@@ -2087,9 +2499,9 @@ export function createAutoHarnessCommand(): SlashCommand {
hidden: false, // Temporarily hidden from TUI, core functionality preserved for future re-enable
kind: CommandKind.BUILT_IN,
takesArgs: true,
- subCommands: [runCommand, scheduleCommand],
+ subCommands: [runCommand, scheduleCommand, issueCommand],
completion: (_ctx, partial) => {
- const subNames = ["run", "schedule"];
+ const subNames = ["run", "schedule", "issue"];
const prefix = partial.trim().toLowerCase();
if (!prefix) return subNames;
return subNames.filter((n) => n.startsWith(prefix));
@@ -2098,7 +2510,7 @@ export function createAutoHarnessCommand(): SlashCommand {
const text = args.trim();
if (!text) {
ctx.addItem(
- addError(ctx.sessionId, "用法: /auto-harness <run|schedule> [参数]\n子命令:\n run 创建并执行一次性任务\n schedule 管理定时任务\n示例:\n /auto-harness run 优化上下文压缩能力\n /auto-harness schedule list\n /auto-harness schedule logs <task_id>")
+ addError(ctx.sessionId, "用法: /auto-harness <run|schedule|issue> [参数]\n子命令:\n run 创建并执行一次性任务\n schedule 管理定时任务\n issue 处理 GitCode issue\n示例:\n /auto-harness run 优化上下文压缩能力\n /auto-harness schedule list\n /auto-harness issue fix 1272,1271")
);
}
},
@@ -2145,4 +2557,4 @@ function parseLogArgs(args: string): { task_id: string; log_type: string; histor
}) || "";
return { task_id, log_type, history_index };
-}
\ No newline at end of file
+}
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index 5b3803e3bb..88419a1422 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -190,6 +190,10 @@ class ReqMethod(Enum):
SCHEDULE_LOGS = "schedule.logs"
SCHEDULE_CANCEL = "schedule.cancel"
SCHEDULE_DELETE = "schedule.delete"
+ ISSUE_WATCH_ONCE = "issue.watch_once"
+ ISSUE_STATE_LIST = "issue.state.list"
+ ISSUE_DELETE = "issue.delete"
+ ISSUE_MATRIX = "issue.matrix"
class EventType(Enum):
diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
index 5627c3b397..e4561a51d2 100644
--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
@@ -256,6 +256,10 @@ CLI_FORWARD_REQ_METHODS = frozenset(
"schedule.logs",
"schedule.cancel",
"schedule.delete",
+ "issue.watch_once",
+ "issue.state.list",
+ "issue.matrix",
+ "issue.delete",
}
)
@@ -347,6 +351,10 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset(
"schedule.logs",
"schedule.cancel",
"schedule.delete",
+ "issue.watch_once",
+ "issue.state.list",
+ "issue.matrix",
+ "issue.delete",
}
)
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 1d2b8e7245..3bde539693 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -299,6 +299,10 @@ _FORWARD_REQ_METHODS = frozenset({
"schedule.logs",
"schedule.cancel",
"schedule.delete",
+ "issue.watch_once",
+ "issue.state.list",
+ "issue.matrix",
+ "issue.delete",
})
_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 1e31991480..7ae35d3b1d 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -1070,6 +1070,18 @@ class AgentWebSocketServer:
if request.req_method == ReqMethod.SCHEDULE_DELETE:
await self._handle_schedule_request(ws, request, send_lock, "delete")
return
+ if request.req_method == ReqMethod.ISSUE_WATCH_ONCE:
+ await self._handle_schedule_request(ws, request, send_lock, "issue_watch_once")
+ return
+ if request.req_method == ReqMethod.ISSUE_STATE_LIST:
+ await self._handle_schedule_request(ws, request, send_lock, "issue_state_list")
+ return
+ if request.req_method == ReqMethod.ISSUE_DELETE:
+ await self._handle_schedule_request(ws, request, send_lock, "issue_delete")
+ return
+ if request.req_method == ReqMethod.ISSUE_MATRIX:
+ await self._handle_schedule_request(ws, request, send_lock, "issue_matrix")
+ return
if request.req_method == ReqMethod.AGENTS_LIST:
await self._handle_agents_list(ws, request, send_lock)
return
@@ -5654,7 +5666,7 @@ class AgentWebSocketServer:
payload: dict[str, Any] = {}
# For actions that need agent: get agent and set on service (similar to _handle_command_compact)
- needs_agent = action in ("create", "run", "cancel", "delete")
+ needs_agent = action in ("create", "run", "cancel", "delete", "issue_watch_once")
if needs_agent:
mode, sub_mode = _apply_resolved_mode_to_request(request)
agent_mode = "agent" if mode == "auto_harness" else mode
@@ -5725,6 +5737,20 @@ class AgentWebSocketServer:
task_id = params.get("task_id", "")
payload = await self._scheduler_service.delete_scheduled_task(task_id)
+ elif action == "issue_watch_once":
+ model_name = params.get("model_name")
+ model = self._resolve_model(model_name)
+ payload = await self._scheduler_service.watch_gitcode_issues_once(params, model)
+
+ elif action == "issue_state_list":
+ payload = await self._scheduler_service.list_gitcode_issue_states()
+
+ elif action == "issue_delete":
+ payload = await self._scheduler_service.delete_issue_states(params)
+
+ elif action == "issue_matrix":
+ payload = await self._scheduler_service.refresh_issue_matrix(params)
+
else:
payload = {"error": f"未知的调度操作: {action}"}
diff --git a/tests/unit_tests/agentserver/test_auto_harness_issue_fix_experience.py b/tests/unit_tests/agentserver/test_auto_harness_issue_fix_experience.py
new file mode 100644
index 0000000000..6d2642606a
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_auto_harness_issue_fix_experience.py
@@ -0,0 +1,239 @@
+import asyncio
+from pathlib import Path
+
+from jiuwenswarm.agents.harness.common.auto_harness.issue_fix.gitcode_issue_client import GitCodeIssue
+from jiuwenswarm.agents.harness.common.auto_harness.issue_fix.issue_runner import (
+ GitCodeIssueRunner,
+ IssueWatchOptions,
+)
+from jiuwenswarm.agents.harness.common.auto_harness.issue_fix.issue_state_store import IssueStateStore
+from jiuwenswarm.agents.harness.common.auto_harness.issue_fix.run_progress import (
+ enrich_issue_fix_progress,
+ infer_issue_fix_skipped_stages,
+)
+from jiuwenswarm.agents.harness.common.auto_harness.issue_fix.task_factory import (
+ build_issue_fix_task,
+)
+from jiuwenswarm.agents.harness.common.auto_harness.run_log_status import determine_pipeline_status_from_log
+from jiuwenswarm.agents.harness.common.auto_harness.task_store import TaskStore
+
+
+def _issue(number: int, title: str, body: str, labels: tuple[str, ...] = ("bug",)) -> GitCodeIssue:
+ return GitCodeIssue(
+ number=number,
+ title=title,
+ body=body,
+ html_url=f"https://gitcode.com/openJiuwen/jiuwenswarm/issues/{number}",
+ labels=labels,
+ raw={},
+ )
+
+
+class _FakeClient:
+ def __init__(self, issues):
+ self._issues = {issue.number: issue for issue in issues}
+
+ def get_issue(self, *, owner, repo, number):
+ return self._issues[number]
+
+ def list_issues(self, **_kwargs):
+ return list(self._issues.values())
+
+ @staticmethod
+ def list_issue_pull_requests(**_kwargs):
+ return []
+
+ @staticmethod
+ def list_pull_requests(**_kwargs):
+ return []
+
+
+class _FakeHarnessService:
+ def __init__(self):
+ self.queries = []
+ self.optimization_tasks = []
+
+ async def run_task(self, query: str, model=None, pipeline=None, optimization_task=None, repo_url=""):
+ self.queries.append(query)
+ self.optimization_tasks.append(optimization_task)
+ return {"task_id": "sch_fake", "message": "started"}
+
+ async def get_scheduled_task_status(self, task_id: str):
+ return None
+
+
+def test_assess_issue_difficulty_marks_unclear_or_high_for_human():
+ unclear = _issue(1, "偶现问题", "待补充,暂时不清楚如何复现", ("bug",))
+ result = GitCodeIssueRunner.assess_issue_difficulty(unclear)
+ assert result["level"] == "unclear"
+ assert result["needs_human"] is True
+
+ high = _issue(
+ 2,
+ "MCP 支持前端配置",
+ "新增 MCP 前端配置、后端 API、协议兼容和多模块集成,需要设计思路。",
+ ("feature", "sig/jiuwenclaw"),
+ )
+ result = GitCodeIssueRunner.assess_issue_difficulty(high)
+ assert result["level"] in {"high", "unclear"}
+
+
+def test_process_issues_once_skips_hard_issue_as_needs_human(tmp_path: Path):
+ hard_issue = _issue(
+ 494,
+ "MCP 支持前端配置",
+ "新增 MCP 前端配置、后端 API、协议兼容和多模块集成,需要设计思路。",
+ ("feature", "sig/jiuwenclaw"),
+ )
+ service = _FakeHarnessService()
+ runner = GitCodeIssueRunner(
+ client=_FakeClient([hard_issue]),
+ state_store=IssueStateStore(tmp_path),
+ harness_service=service,
+ )
+
+ result = asyncio.run(
+ runner.process_issues_once(
+ IssueWatchOptions(
+ owner="openJiuwen",
+ repo="jiuwenswarm",
+ issue_numbers=(494,),
+ labels=(),
+ max_auto_difficulty="medium",
+ )
+ )
+ )
+
+ assert result["started"] == []
+ assert result["skipped"][0]["status"] == "needs_human"
+ assert result["skipped"][0]["human_label"] == "needs-human"
+ assert service.queries == []
+
+
+def test_process_issues_once_starts_medium_or_lower_issue(tmp_path: Path):
+ easy_issue = _issue(
+ 1266,
+ "InstanceLock.release Windows NameError",
+ "在 Windows 下调用 InstanceLock.release 会出现 NameError。复现步骤明确,只需修复异常变量名并补充单测。",
+ ("bug", "sig/jiuwenclaw"),
+ )
+ service = _FakeHarnessService()
+ runner = GitCodeIssueRunner(
+ client=_FakeClient([easy_issue]),
+ state_store=IssueStateStore(tmp_path),
+ harness_service=service,
+ )
+
+ result = asyncio.run(
+ runner.process_issues_once(
+ IssueWatchOptions(
+ owner="openJiuwen",
+ repo="jiuwenswarm",
+ issue_numbers=(1266,),
+ labels=(),
+ max_auto_difficulty="medium",
+ )
+ )
+ )
+
+ assert result["started"][0]["task_id"] == "sch_fake"
+ assert "GitCode Issue #1266" in service.queries[0]
+ assert service.optimization_tasks[0].issue_ref == "#1266"
+
+
+def test_issue_fix_query_includes_repository_code_rules():
+ issue = _issue(
+ 1277,
+ "修复一个明确的小问题",
+ "复现步骤明确,修改范围限定在一个函数和一个单测。",
+ ("bug",),
+ )
+
+ query = GitCodeIssueRunner.build_issue_fix_query(
+ issue,
+ owner="openJiuwen",
+ repo="jiuwenswarm",
+ )
+
+ assert "编程规范约束(必须遵守仓库 code_rule.txt)" in query
+ assert "G.ERR.07 避免抑制或忽略异常" in query
+ assert "G.EDV.04 禁止使用subprocess模块中的shell=True选项" in query
+ assert "测试代码不得直接访问以单下划线开头的受保护或私有成员" in query
+ assert "必须通过公开 API、用户可观察行为或模块级公共函数间接验证" in query
+
+
+def test_task_progress_extracts_pr_and_failure_code(tmp_path: Path):
+ logs = [
+ {
+ "event_type": "harness.message",
+ "pipeline": "meta_evolve_pipeline",
+ "stages": [{"slot": "implement"}, {"slot": "verify"}, {"slot": "publish"}],
+ },
+ {"event_type": "harness.stage_result", "stage": "implement", "status": "success"},
+ {
+ "event_type": "harness.stage_result",
+ "stage": "publish",
+ "status": "failed",
+ "error": "GitCode PR creation failed: HTTP 400 Bad Request",
+ "messages": [
+ "PR 发布诊断: http_status=400",
+ "PR 已创建: https://gitcode.com/openJiuwen/jiuwenswarm/merge_requests/2379",
+ ],
+ },
+ ]
+
+ store = TaskStore(tmp_path)
+ store.register_run_log_status_extension(
+ skipped_stage_inferer=infer_issue_fix_skipped_stages,
+ progress_enricher=enrich_issue_fix_progress,
+ )
+ progress = store.summarize_progress_from_logs(logs)
+
+ assert progress["failed_stage"] == "publish"
+ assert progress["failure_code"] == "pr_api_failed"
+ assert progress["pr_url"].endswith("/merge_requests/2379")
+
+
+def test_issue_fix_task_factory_preserves_issue_ref():
+ task = build_issue_fix_task(1272, "请自动修复 GitCode Issue #1272。\n标题: demo")
+
+ assert task.topic == "fix-issue-1272"
+ assert task.issue_ref == "#1272"
+
+
+def test_pipeline_status_accepts_structured_skipped_stages(tmp_path: Path):
+ log_path = tmp_path / "log.json"
+ log_path.write_text(
+ "\n".join([
+ '{"event_type":"harness.message","pipeline":"meta_evolve_pipeline",'
+ '"stages":[{"slot":"assess"},{"slot":"plan"},{"slot":"implement"}]}',
+ '{"event_type":"harness.stage_result","stage":"assess","status":"skipped"}',
+ '{"event_type":"harness.stage_result","stage":"plan","status":"skipped"}',
+ '{"event_type":"harness.stage_result","stage":"implement","status":"success"}',
+ ]),
+ encoding="utf-8",
+ )
+
+ assert determine_pipeline_status_from_log(
+ log_path,
+ skipped_stage_inferers=[infer_issue_fix_skipped_stages],
+ ) == {"failed": False, "error": ""}
+
+
+def test_pipeline_status_accepts_legacy_issue_fix_skip_message(tmp_path: Path):
+ log_path = tmp_path / "legacy-log.json"
+ log_path.write_text(
+ "\n".join([
+ '{"event_type":"harness.message","pipeline":"meta_evolve_pipeline",'
+ '"stages":[{"slot":"assess"},{"slot":"plan"},{"slot":"implement"}]}',
+ '{"event_type":"harness.message","content":"检测到显式 GitCode issue 修复任务,'
+ '跳过 assess/plan,直接进入实现/验证/提交/发布流程。"}',
+ '{"event_type":"harness.stage_result","stage":"implement","status":"success"}',
+ ]),
+ encoding="utf-8",
+ )
+
+ assert determine_pipeline_status_from_log(
+ log_path,
+ skipped_stage_inferers=[infer_issue_fix_skipped_stages],
+ ) == {"failed": False, "error": ""}
diff --git a/tests/unit_tests/auto_harness/test_gitcode_issue_runner.py b/tests/unit_tests/auto_harness/test_gitcode_issue_runner.py
new file mode 100644
index 0000000000..18d122a3fc
--- /dev/null
+++ b/tests/unit_tests/auto_harness/test_gitcode_issue_runner.py
@@ -0,0 +1,286 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.auto_harness.issue_fix.gitcode_issue_client import GitCodeIssue
+from jiuwenswarm.agents.harness.common.auto_harness.issue_fix.issue_runner import (
+ GitCodeIssueRunner,
+ IssueWatchOptions,
+)
+from jiuwenswarm.agents.harness.common.auto_harness.issue_fix.issue_state_store import IssueStateStore
+
+
+class FakeGitCodeClient:
+ def __init__(self, issues: list[GitCodeIssue], pulls: dict[int, list[dict[str, Any]]] | None = None):
+ self.issues = issues
+ self.pulls = pulls or {}
+ self.comments: list[dict[str, Any]] = []
+
+ def list_issues(self, **_kwargs):
+ return self.issues
+
+ def get_issue(self, *, number: int, **_kwargs):
+ for issue in self.issues:
+ if issue.number == number:
+ return issue
+ raise RuntimeError(f"missing issue #{number}")
+
+ def list_issue_pull_requests(self, *, number: int, **_kwargs):
+ return self.pulls.get(number, [])
+
+ @staticmethod
+ def list_pull_requests(**_kwargs):
+ return []
+
+ def create_issue_comment(self, **kwargs):
+ self.comments.append(kwargs)
+ return {"id": len(self.comments)}
+
+
+class FakeHarnessService:
+ def __init__(self):
+ self.queries: list[str] = []
+ self.optimization_tasks: list[Any] = []
+ self.tasks: dict[str, dict[str, Any]] = {}
+
+ async def run_task(self, query: str, model=None, pipeline=None, optimization_task=None, repo_url=""):
+ self.queries.append(query)
+ self.optimization_tasks.append(optimization_task)
+ task_id = f"sch_{len(self.queries):03d}"
+ self.tasks[task_id] = {"task_id": task_id, "status": "running", "pipeline": pipeline}
+ return {"task_id": task_id, "status": "running", "message": "started"}
+
+ async def get_scheduled_task_status(self, task_id: str):
+ return self.tasks.get(task_id)
+
+
+def _issue(number: int, labels: tuple[str, ...] = ("auto-harness",)) -> GitCodeIssue:
+ return GitCodeIssue(
+ number=number,
+ title=f"Issue {number}",
+ body=(
+ "please fix a clearly scoped bug in the local command parser. "
+ "The failure is reproducible with the existing unit test and "
+ "the expected change is limited to one implementation file and "
+ "one matching test file."
+ ),
+ html_url=f"https://gitcode.com/openJiuwen/jiuwenswarm/issues/{number}",
+ labels=labels,
+ raw={},
+ )
+
+
+async def test_process_issues_once_creates_one_task_for_eligible_issue(tmp_path: Path):
+ client = FakeGitCodeClient([_issue(1)])
+ service = FakeHarnessService()
+ runner = GitCodeIssueRunner(
+ client=client,
+ state_store=IssueStateStore(tmp_path),
+ harness_service=service,
+ )
+
+ result = await runner.process_issues_once(IssueWatchOptions(owner="openJiuwen", repo="jiuwenswarm"))
+
+ assert result["fetched"] == 1
+ assert result["started"][0]["task_id"] == "sch_001"
+ assert "Issue #1" in service.queries[0]
+ assert service.optimization_tasks[0].issue_ref == "#1"
+
+
+async def test_process_issues_once_skips_issue_with_existing_open_pr(tmp_path: Path):
+ client = FakeGitCodeClient(
+ [_issue(2)],
+ pulls={
+ 2: [
+ {
+ "number": 9,
+ "state": "open",
+ "html_url": "https://gitcode.com/openJiuwen/jiuwenswarm/pull/9"
+ }
+ ]
+ }
+ )
+ service = FakeHarnessService()
+ runner = GitCodeIssueRunner(
+ client=client,
+ state_store=IssueStateStore(tmp_path),
+ harness_service=service,
+ )
+
+ result = await runner.process_issues_once(IssueWatchOptions(owner="openJiuwen", repo="jiuwenswarm"))
+
+ assert result["started"] == []
+ assert "issue 已有关联 PR" in result["skipped"][0]["reason"]
+ assert service.queries == []
+
+
+async def test_process_issues_once_dry_run_does_not_create_task(tmp_path: Path):
+ client = FakeGitCodeClient([_issue(3)])
+ service = FakeHarnessService()
+ runner = GitCodeIssueRunner(
+ client=client,
+ state_store=IssueStateStore(tmp_path),
+ harness_service=service,
+ )
+
+ result = await runner.process_issues_once(IssueWatchOptions(owner="openJiuwen", repo="jiuwenswarm", dry_run=True))
+
+ assert result["started"][0]["status"] == "dry_run"
+ assert service.queries == []
+
+
+async def test_process_issues_once_does_not_duplicate_existing_task(tmp_path: Path):
+ state = IssueStateStore(tmp_path)
+ await state.update("openJiuwen", "jiuwenswarm", 4, {"status": "task_created", "task_id": "sch_old"})
+ client = FakeGitCodeClient([_issue(4)])
+ service = FakeHarnessService()
+ service.tasks["sch_old"] = {"task_id": "sch_old", "status": "running"}
+ runner = GitCodeIssueRunner(client=client, state_store=state, harness_service=service)
+
+ result = await runner.process_issues_once(IssueWatchOptions(owner="openJiuwen", repo="jiuwenswarm"))
+
+ assert result["started"] == []
+ assert result["skipped"][0]["reason"] == "task_created"
+
+
+async def test_process_issues_once_accepts_explicit_issue_numbers_without_required_label(tmp_path: Path):
+ client = FakeGitCodeClient([
+ _issue(10, labels=("bug",)),
+ _issue(11, labels=("bug", "priority")),
+ ])
+ service = FakeHarnessService()
+ runner = GitCodeIssueRunner(
+ client=client,
+ state_store=IssueStateStore(tmp_path),
+ harness_service=service,
+ )
+
+ result = await runner.process_issues_once(
+ IssueWatchOptions(
+ owner="openJiuwen",
+ repo="jiuwenswarm",
+ issue_numbers=(10, 11),
+ labels=("auto-harness",),
+ )
+ )
+
+ assert result["fetched"] == 2
+ assert [item["number"] for item in result["started"]] == [10, 11]
+ assert "Issue #10" in service.queries[0]
+ assert "Issue #11" in service.queries[1]
+ assert [task.issue_ref for task in service.optimization_tasks] == ["#10", "#11"]
+ assert "PR 正文必须写明修改方案、验证结果、风险和回滚建议" in service.queries[0]
+
+
+async def test_process_issues_once_staggers_multiple_started_tasks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ sleeps: list[float] = []
+
+ async def fake_sleep(seconds: float):
+ sleeps.append(seconds)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.agents.harness.common.auto_harness.issue_fix.issue_runner.asyncio.sleep",
+ fake_sleep,
+ )
+ client = FakeGitCodeClient([
+ _issue(20, labels=("bug",)),
+ _issue(21, labels=("bug",)),
+ ])
+ service = FakeHarnessService()
+ runner = GitCodeIssueRunner(
+ client=client,
+ state_store=IssueStateStore(tmp_path),
+ harness_service=service,
+ )
+
+ result = await runner.process_issues_once(
+ IssueWatchOptions(
+ owner="openJiuwen",
+ repo="jiuwenswarm",
+ issue_numbers=(20, 21),
+ start_interval_seconds=1.2,
+ )
+ )
+
+ assert [item["number"] for item in result["started"]] == [20, 21]
+ assert sleeps == [1.2]
+
+
+async def test_process_issues_once_skips_issue_with_merged_pr(tmp_path: Path):
+ """list_issue_pull_requests returns merged PRs → issue should be skipped."""
+ client = FakeGitCodeClient(
+ [_issue(12, labels=("bug",))],
+ pulls={
+ 12: [
+ {
+ "number": 20,
+ "state": "merged",
+ "html_url": "https://gitcode.com/openJiuwen/jiuwenswarm/pull/20",
+ }
+ ]
+ },
+ )
+ service = FakeHarnessService()
+ runner = GitCodeIssueRunner(
+ client=client,
+ state_store=IssueStateStore(tmp_path),
+ harness_service=service,
+ )
+
+ result = await runner.process_issues_once(
+ IssueWatchOptions(
+ owner="openJiuwen",
+ repo="jiuwenswarm",
+ issue_numbers=(12,),
+ )
+ )
+
+ assert result["started"] == []
+ assert "issue 已有关联 PR" in result["skipped"][0]["reason"]
+ assert service.queries == []
+
+
+async def test_process_issues_once_skips_explicit_issue_with_existing_open_pr(tmp_path: Path):
+ client = FakeGitCodeClient(
+ [_issue(12, labels=("bug",))],
+ pulls={
+ 12: [
+ {
+ "number": 20,
+ "state": "open",
+ "html_url": "https://gitcode.com/openJiuwen/jiuwenswarm/pull/20"
+ }
+ ]
+ }
+ )
+ service = FakeHarnessService()
+ runner = GitCodeIssueRunner(
+ client=client,
+ state_store=IssueStateStore(tmp_path),
+ harness_service=service,
+ )
+
+ result = await runner.process_issues_once(
+ IssueWatchOptions(
+ owner="openJiuwen",
+ repo="jiuwenswarm",
+ issue_numbers=(12,),
+ )
+ )
+
+ assert result["started"] == []
+ assert "issue 已有关联 PR" in result["skipped"][0]["reason"]
+ assert service.queries == []
diff --git a/uv.lock b/uv.lock
index 52df10c666..84a169f7ac 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2656,7 +2656,7 @@ wheels = [
[[package]]
name = "openjiuwen"
version = "0.1.14"
-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#ee92d08bb27c758cf0abd4453852bfcce395ad50" }
+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#fc84d3b059b8a2f1a438d569f8305d9f70bcc228" }
dependencies = [
{ name = "aiofiles" },
{ name = "aiohttp" },