Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7c02db907b | |||
| d682f64c01 | |||
| a24408521c | |||
| c091b6c256 | |||
| cbafd30ec7 | |||
| f84908aa36 | |||
| 500152510a | |||
| 0d5bfa9276 | |||
| eb2af77c90 | |||
| eccaa28b1d | |||
| 2101a43b68 | |||
| 9f0872c36a | |||
| d73da7cda9 | |||
| 268520d453 | |||
| 1b8baed542 | |||
| f2b9301fa1 | |||
| a8ba8d4b4a | |||
| 1477dbdd18 | |||
| 6d0a5284e7 | |||
| b193aaf8f7 | |||
| a4ab3ef27e | |||
| db0a73dda7 | |||
| f0fb098451 | |||
| 6e67975eca | |||
| 85358bbe4a | |||
| df8ac61c9e | |||
| ace49338b2 | |||
| 076fb25eda | |||
| feac10618d |
+17
-3
@@ -1,3 +1,17 @@
|
||||
{
|
||||
"permissionMode": "bypass"
|
||||
}
|
||||
{
|
||||
"permissionMode": "bypass",
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git *)",
|
||||
"Bash(python scripts/agent_poller.py *)",
|
||||
"Bash(python scripts/run_pipeline.py *)",
|
||||
"Bash(python scripts/create_failure_issue.py *)",
|
||||
"Bash(python -m pytest *)",
|
||||
"Bash(python -c *)",
|
||||
"Bash(curl *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
+23
-5
@@ -63,8 +63,11 @@ description: AI 开发专家,负责 document_analyzer 项目的功能开发、
|
||||
4. 轮询内容(多轮递进):
|
||||
a. `--action list --labels product-code` — 先捡带 `product-code` 标签的 Issue
|
||||
b. `--action list` 无过滤,筛选 title 带 `[product]` 前缀的无标签 Issue
|
||||
c. 都无则分析无标签、无标识的 Issue,判断是否在 Dev 域内
|
||||
5. 有 issue → 走完整闭环处理(分析 → 开发 → push → PR → CI → merge → 自行验证 → 关闭)
|
||||
c. `--action blocked-check` — 检查 blocked Issue,若阻塞已解除则自动移除 blocked 标签
|
||||
d. 都无则分析无标签、无标识的 Issue,判断是否在 Dev 域内
|
||||
5. 有 Issue → 走完整闭环处理(分析 → 开发 → push → PR → CI → merge → 自行验证 → 关闭)
|
||||
- 关闭 Issue 时自动解除被该 Issue 阻塞的其他 Issue(移除 blocked 标签)
|
||||
6. 无 Issue → 报告 "main healthy,无待处理 Issue",等待下次轮询
|
||||
6. 无 issue → 报告 "main healthy,无待处理 Issue",等待下次轮询
|
||||
7. 同时保持对话开放,随时响应用户指令
|
||||
|
||||
@@ -86,6 +89,13 @@ python scripts/agent_poller.py --action list
|
||||
**第三轮:分析无标识 Issue**
|
||||
如果以上两轮都无结果,分析所有无标签、无 title 标识的 Issue,判断是否属于 Dev 域。
|
||||
|
||||
**blocked Issue 处理**:
|
||||
- 不要直接跳过 `blocked` 标签的 Issue
|
||||
- 运行 `--action blocked-check` 检查阻塞状态是否已解除
|
||||
- 如果所有阻塞 Issue 已关闭 → blocked 标签自动移除 → 正常处理
|
||||
- 如果仍有未解决的阻塞 → 跳过,等待阻塞解除
|
||||
- 关闭 Issue 时会自动检查并解除被其阻塞的 Issue(auto-unblock)
|
||||
|
||||
**处理范围**:Dev-Agent 负责处理**所有非纯测试开发**相关的 Issue。具体来说:
|
||||
|
||||
| 处理 | 跳过 |
|
||||
@@ -116,9 +126,11 @@ python scripts/agent_poller.py --action get --issue N
|
||||
1. git pull origin main
|
||||
2. git checkout -b dev/issue-N-<slug>
|
||||
3. 修改功能代码 + 更新/补充 UT 和接口集成测试
|
||||
4. python -m pytest -v # 本地全量测试
|
||||
5. git commit -m "fix: <描述> - Closes #N"
|
||||
6. git push origin dev/issue-N-<slug>
|
||||
4. python -m pytest -v # 本地全量 UT/集成测试
|
||||
5. python scripts/run_pipeline.py --input "input/<文档>.docx" # 运行完整 pipeline
|
||||
6. python -m pytest tests/acceptance/ -v --run-acceptance # e2e 验收 (Layer A+B+C)
|
||||
7. git commit -m "fix: <描述> - Closes #N"
|
||||
8. git push origin dev/issue-N-<slug>
|
||||
```
|
||||
|
||||
**开发原则:**
|
||||
@@ -127,6 +139,7 @@ python scripts/agent_poller.py --action get --issue N
|
||||
- 关注 IR 一致性:对同一输入的多次运行结果应尽量稳定
|
||||
- 关注功能覆盖率:确保 IR 覆盖了输入文档中的功能点
|
||||
- **验证是实际功能验证,不是 dry-run**:`pytest` 通过只是门槛,必须用真实输入文档实际运行 pipeline 确认功能生效
|
||||
- **PR 前必须通过 e2e 验收 (Layer A+B+C)**:防止修复引入回归。若无法运行完整 pipeline(API 不可用等),至少在 PR 描述中注明
|
||||
|
||||
### 4. 提交 PR
|
||||
|
||||
@@ -215,6 +228,10 @@ QE-Agent 开 Issue (qe-feedback / bug / ci-failure)
|
||||
验证不通过 → 重新分析根因 → 回到开发
|
||||
```
|
||||
|
||||
## 关键约束
|
||||
|
||||
1. **任何对 git 管理内容的修改必须走完整流程**:开 Issue → 改动 → 提交 PR → CI 通过 → merge → close Issue。无论是自主轮询还是与用户互动触发的改动,一律遵守此规则。绝不直接改文件而不走 Issue 流程。
|
||||
|
||||
## 提交规范
|
||||
|
||||
- **格式**:`fix: <简短描述> - Closes #N` 或 `feat: <描述> - Closes #N`
|
||||
@@ -252,6 +269,7 @@ QE-Agent 开 Issue (qe-feedback / bug / ci-failure)
|
||||
| `--action pr-status --pr N` | 查看 PR + CI 状态 | 5. 等 CI |
|
||||
| `--action merge-pr --pr N` | Merge PR(自动检查 CI) | 6. Merge |
|
||||
| `--action close-issue --issue N --body "..."` | 手动关闭 Issue | 6. 关闭 |
|
||||
| `--action blocked-check` | 检查并清理已解除阻塞的 Issue | 4-6. 轮询 |
|
||||
| `--action lifecycle --issue N` | 查看 Issue 完整生命周期 | 随时 |
|
||||
|
||||
## 闭环完成检查清单
|
||||
|
||||
+20
-10
@@ -19,10 +19,12 @@ description: QE Agent — 自动化验收测试开发与质量门禁。轮询 Gi
|
||||
4. 轮询内容(多轮递进):
|
||||
a. `--action list --labels test-code` — 先捡带 `test-code` 标签的 Issue
|
||||
b. `--action list` 无过滤,筛选 title 带 `[test]` 前缀的无标签 Issue
|
||||
c. 都无则分析无标签、无标识的 Issue,判断是否在 QE 域内
|
||||
d. 同时检查 `--labels acceptance-failure`
|
||||
5. 有 issue → 走完整闭环处理(Step 2-8)
|
||||
6. 无 issue → 简短报告 "main healthy",等待下次轮询
|
||||
c. `--action blocked-check` — 检查 blocked Issue,若阻塞已解除则自动移除 blocked 标签
|
||||
d. 都无则分析无标签、无标识的 Issue,判断是否在 QE 域内
|
||||
e. 同时检查 `--labels acceptance-failure`
|
||||
5. 有 Issue → 走完整闭环处理(Step 2-8)
|
||||
- 关闭 Issue 时自动解除被该 Issue 阻塞的其他 Issue(移除 blocked 标签)
|
||||
6. 无 Issue → 简短报告 "main healthy",等待下次轮询
|
||||
7. 同时保持对话开放,随时响应用户指令
|
||||
|
||||
这样 QE-Agent 真正做到 **"默认轮询 + 随时互动"**。
|
||||
@@ -69,6 +71,13 @@ python scripts/agent_poller.py --action list
|
||||
**第三轮:分析无标识 Issue**
|
||||
如果以上两轮都无结果,分析所有无标签、无 title 标识的 Issue,判断是否属于 QE 域。
|
||||
|
||||
**blocked Issue 处理**:
|
||||
- 不要直接跳过 `blocked` 标签的 Issue
|
||||
- 运行 `--action blocked-check` 检查阻塞状态是否已解除
|
||||
- 如果所有阻塞 Issue 已关闭 → blocked 标签自动移除 → 正常处理
|
||||
- 如果仍有未解决的阻塞 → 跳过,等待阻塞解除
|
||||
- 关闭 Issue 时会自动检查并解除被其阻塞的 Issue(auto-unblock)
|
||||
|
||||
同时检查 `acceptance-failure` 标签的 issue:
|
||||
```bash
|
||||
python scripts/agent_poller.py --action list --labels acceptance-failure
|
||||
@@ -294,12 +303,13 @@ QE-Agent 领取 (step 1-2)
|
||||
|
||||
## 关键约束
|
||||
|
||||
1. **只修改 `tests/acceptance/`** — 不碰应用代码、不碰 `skills/`、不碰 `scripts/`(除非是修复 agent_poller 或 create_failure_issue)
|
||||
2. **不碰 `tests/unit/`、`tests/integration/`** — 那是开发团队维护的
|
||||
3. **每次只处理一个 issue** — 不混入多个 issue 的改动
|
||||
4. **`Closes #<N>` 必须出现在 commit message 中**
|
||||
5. **本地验证必须通过再 push** — 至少 Layer A + Layer B
|
||||
6. **如果 Layer C(QE Audit)需要验证但 API 不可用** — 在 issue 下评论注明,标记 `--run-acceptance` 通过后 merge
|
||||
1. **任何对 git 管理内容的修改必须走完整流程**:开 Issue → 改动 → 提交 PR → CI 通过 → merge → close Issue。无论是自主轮询还是与用户互动触发的改动,一律遵守此规则。绝不直接改文件而不走 Issue 流程。
|
||||
2. **只修改 `tests/acceptance/`** — 不碰应用代码、不碰 `skills/`、不碰 `scripts/`(除非是修复 agent_poller 或 create_failure_issue)
|
||||
3. **不碰 `tests/unit/`、`tests/integration/`** — 那是开发团队维护的
|
||||
4. **每次只处理一个 issue** — 不混入多个 issue 的改动
|
||||
5. **`Closes #<N>` 必须出现在 commit message 中**
|
||||
6. **本地验证必须通过再 push** — 至少 Layer A + Layer B
|
||||
7. **如果 Layer C(QE Audit)需要验证但 API 不可用** — 在 issue 下评论注明,标记 `--run-acceptance` 通过后 merge
|
||||
|
||||
## Session 收尾
|
||||
|
||||
|
||||
+169
-3
@@ -16,6 +16,7 @@ Usage:
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
@@ -55,6 +56,27 @@ def _req(method, path, data=None):
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def _req_safe(method, path, data=None):
|
||||
"""Like _req but returns None on HTTPError instead of crashing.
|
||||
Used for probing issue/PR existence where the caller can handle absence.
|
||||
"""
|
||||
url = f"{BASE}{path}"
|
||||
payload = json.dumps(data).encode("utf-8") if data else None
|
||||
req = urllib.request.Request(url, data=payload, method=method)
|
||||
req.add_header("Authorization", f"token {GITEA_TOKEN}")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
try:
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
raw = resp.read()
|
||||
if not raw:
|
||||
return {}
|
||||
return json.loads(raw)
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode()
|
||||
print(f"API Error {e.code}: {body}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
# ── Issue operations ─────────────────────────────────────────────────────────
|
||||
|
||||
def list_issues(labels: list[str] | None = None):
|
||||
@@ -73,6 +95,68 @@ def list_issues(labels: list[str] | None = None):
|
||||
return issues
|
||||
|
||||
|
||||
def _get_blocking_refs(issue_num: int) -> set[int]:
|
||||
"""Extract all issue references from an issue body + comments.
|
||||
|
||||
Scans both the issue body and all comments for #N patterns,
|
||||
returning a set of referenced issue numbers.
|
||||
"""
|
||||
refs: set[int] = set()
|
||||
# Body
|
||||
issue = _req_safe("GET", f"/issues/{issue_num}")
|
||||
if issue is None:
|
||||
return refs # API error → return empty set, keep blocked
|
||||
body = issue.get("body", "") or ""
|
||||
refs.update(int(m.group(1)) for m in re.finditer(r'#(\d+)', body))
|
||||
# Comments
|
||||
comments = _req_safe("GET", f"/issues/{issue_num}/comments")
|
||||
if comments:
|
||||
for c in comments:
|
||||
cbody = c.get("body", "") or ""
|
||||
refs.update(int(m.group(1)) for m in re.finditer(r'#(\d+)', cbody))
|
||||
return refs
|
||||
|
||||
|
||||
def blocked_check():
|
||||
"""Check all blocked issues: if blocking issues are now closed, unblock.
|
||||
|
||||
Scans issue body + comments for blocking references.
|
||||
If no references found or all referenced issues are closed,
|
||||
removes the 'blocked' label.
|
||||
"""
|
||||
all_blocked = _req_safe("GET", "/issues?state=open&labels=blocked")
|
||||
if not all_blocked:
|
||||
print("No blocked issues found.")
|
||||
return
|
||||
|
||||
unblocked_count = 0
|
||||
for issue in all_blocked:
|
||||
blocking_nums = _get_blocking_refs(issue["number"])
|
||||
|
||||
all_resolved = True
|
||||
for blk in blocking_nums:
|
||||
blk_issue = _req_safe("GET", f"/issues/{blk}")
|
||||
if blk_issue is None:
|
||||
all_resolved = False # API error → keep blocked
|
||||
break
|
||||
if blk_issue.get("state") != "closed":
|
||||
all_resolved = False
|
||||
break
|
||||
|
||||
if all_resolved:
|
||||
current_label_names = [l["name"] for l in issue.get("labels", [])]
|
||||
new_label_names = [l for l in current_label_names if l != "blocked"]
|
||||
new_label_ids = _label_names_to_ids(new_label_names)
|
||||
_req("PUT", f"/issues/{issue['number']}/labels", {"labels": new_label_ids})
|
||||
reason = "所有阻塞 Issue 均已关闭" if blocking_nums else "无阻塞引用,移除残留 blocked 标签"
|
||||
print(f"Unblocked #{issue['number']}: {issue['title']}")
|
||||
comment_issue(issue["number"], f"阻塞已解除:{reason}。")
|
||||
unblocked_count += 1
|
||||
|
||||
if unblocked_count == 0:
|
||||
print(f"Checked {len(all_blocked)} blocked issue(s): still blocked.")
|
||||
|
||||
|
||||
def get_issue(num):
|
||||
i = _req("GET", f"/issues/{num}")
|
||||
print(f"## #{i['number']}: {i['title']}")
|
||||
@@ -91,14 +175,67 @@ def comment_issue(num, body):
|
||||
|
||||
|
||||
def close_issue(num, body=None):
|
||||
"""Close an issue, optionally with a final comment (signature auto-appended)."""
|
||||
"""Close an issue, optionally with a final comment (signature auto-appended).
|
||||
|
||||
After closing, automatically unblocks any issues that were blocked by this one
|
||||
if no other blocking issues remain open.
|
||||
"""
|
||||
if body:
|
||||
comment_issue(num, body) # comment_issue already appends AGENT_SIG
|
||||
i = _req("PATCH", f"/issues/{num}", {"state": "closed"})
|
||||
print(f"Issue #{num} closed")
|
||||
_unblock_issues_blocked_by(num)
|
||||
return i
|
||||
|
||||
|
||||
def reopen_issue(num, body=None):
|
||||
"""Reopen a closed issue, optionally with a reason comment."""
|
||||
if body:
|
||||
comment_issue(num, f"## REOPEN\n\n{body}")
|
||||
i = _req("PATCH", f"/issues/{num}", {"state": "open"})
|
||||
print(f"Issue #{num} reopened")
|
||||
return i
|
||||
|
||||
|
||||
def _unblock_issues_blocked_by(closed_num):
|
||||
"""Check issues blocked by *closed_num* and unblock if all blockers resolved.
|
||||
|
||||
Scans both body and comments for #N references. If *closed_num* appears
|
||||
in any blocked issue and all referenced issues are now closed,
|
||||
removes the 'blocked' label and comments on the unblocked issue.
|
||||
"""
|
||||
all_blocked = _req_safe("GET", "/issues?state=open&labels=blocked")
|
||||
if not all_blocked:
|
||||
return
|
||||
|
||||
for issue in all_blocked:
|
||||
blocking_nums = _get_blocking_refs(issue["number"])
|
||||
if closed_num not in blocking_nums:
|
||||
continue
|
||||
|
||||
# Check all referenced issues — are they all closed?
|
||||
all_resolved = True
|
||||
for blk in blocking_nums:
|
||||
if blk == closed_num:
|
||||
continue
|
||||
blk_issue = _req_safe("GET", f"/issues/{blk}")
|
||||
if blk_issue is None:
|
||||
all_resolved = False # API error → keep blocked
|
||||
break
|
||||
if blk_issue.get("state") != "closed":
|
||||
all_resolved = False
|
||||
break
|
||||
|
||||
if all_resolved:
|
||||
current_label_names = [l["name"] for l in issue.get("labels", [])]
|
||||
new_label_names = [l for l in current_label_names if l != "blocked"]
|
||||
new_label_ids = _label_names_to_ids(new_label_names)
|
||||
_req("PUT", f"/issues/{issue['number']}/labels", {"labels": new_label_ids})
|
||||
print(f" -> Unblocked #{issue['number']}: all blocking issues resolved")
|
||||
comment_issue(issue["number"],
|
||||
f"阻塞已解除:#{closed_num} 及其他阻塞 Issue 均已关闭。")
|
||||
|
||||
|
||||
def create_issue(title, body=None, labels=None):
|
||||
"""Create a new Gitea issue.
|
||||
|
||||
@@ -110,7 +247,11 @@ def create_issue(title, body=None, labels=None):
|
||||
if body:
|
||||
payload["body"] = body + AGENT_SIG
|
||||
if labels:
|
||||
payload["labels"] = [l.strip() for l in labels.split(",") if l.strip()]
|
||||
label_names = [l.strip() for l in labels.split(",") if l.strip()]
|
||||
# Gitea 1.22 expects label IDs (int64). Resolve names → IDs.
|
||||
label_ids = _label_names_to_ids(label_names)
|
||||
if label_ids:
|
||||
payload["labels"] = label_ids
|
||||
i = _req("POST", "/issues", payload)
|
||||
issue_labels = [l["name"] for l in i.get("labels", [])]
|
||||
print(f"Issue #{i['number']} created: {i['title']}")
|
||||
@@ -120,6 +261,22 @@ def create_issue(title, body=None, labels=None):
|
||||
return i
|
||||
|
||||
|
||||
def _label_names_to_ids(names: list[str]) -> list[int]:
|
||||
"""Resolve label names to Gitea label IDs. Returns empty list on failure."""
|
||||
try:
|
||||
all_labels = _req("GET", "/labels")
|
||||
name_to_id = {l["name"]: l["id"] for l in all_labels}
|
||||
ids = []
|
||||
for name in names:
|
||||
if name in name_to_id:
|
||||
ids.append(name_to_id[name])
|
||||
else:
|
||||
print(f"Warning: label '{name}' not found, skipping", file=sys.stderr)
|
||||
return ids
|
||||
except SystemExit:
|
||||
return []
|
||||
|
||||
|
||||
# ── PR operations ────────────────────────────────────────────────────────────
|
||||
|
||||
def create_pr(issue_num, branch, body=None):
|
||||
@@ -234,7 +391,9 @@ def main():
|
||||
parser = argparse.ArgumentParser(description="Dev agent Gitea helper")
|
||||
parser.add_argument("--action", required=True,
|
||||
choices=["list", "get", "comment", "close-issue",
|
||||
"create-issue", "create-pr", "pr-status", "merge-pr", "lifecycle"])
|
||||
"create-issue", "reopen-issue",
|
||||
"create-pr", "pr-status", "merge-pr", "lifecycle",
|
||||
"blocked-check"])
|
||||
parser.add_argument("--issue", type=int)
|
||||
parser.add_argument("--pr", type=int)
|
||||
parser.add_argument("--title", help="Issue title (for 'create-issue' action)")
|
||||
@@ -271,6 +430,11 @@ def main():
|
||||
print("--title is required for 'create-issue' action", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
create_issue(args.title, args.body, args.labels)
|
||||
elif args.action == "reopen-issue":
|
||||
if not args.issue:
|
||||
print("--issue is required for 'reopen-issue' action", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
reopen_issue(args.issue, args.body)
|
||||
elif args.action == "create-pr":
|
||||
if not args.issue or not args.branch:
|
||||
print("--issue and --branch are required for 'create-pr' action", file=sys.stderr)
|
||||
@@ -286,6 +450,8 @@ def main():
|
||||
print("--pr is required for 'merge-pr' action", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
merge_pr(args.pr)
|
||||
elif args.action == "blocked-check":
|
||||
blocked_check()
|
||||
elif args.action == "lifecycle":
|
||||
if not args.issue:
|
||||
print("--issue is required for 'lifecycle' action", file=sys.stderr)
|
||||
|
||||
@@ -880,11 +880,19 @@ def run_ensemble_semantic_index(doc: dict) -> dict:
|
||||
if v:
|
||||
print(f" {k}: {len(v)} 个问题")
|
||||
|
||||
# Feedback retry: re-run with coverage feedback (one retry)
|
||||
# Feedback retry: re-run with coverage feedback (up to 2 retries, quality-gated)
|
||||
retry_count = 0
|
||||
while retry_count < 2:
|
||||
feedback = _build_coverage_feedback(gaps)
|
||||
if feedback:
|
||||
print(f"\n 覆盖反馈重试 (feedback长度={len(feedback)}字符)...", flush=True)
|
||||
if not feedback:
|
||||
break
|
||||
retry_count += 1
|
||||
print(f"\n 覆盖反馈重试 #{retry_count} (feedback长度={len(feedback)}字符)...", flush=True)
|
||||
try:
|
||||
# record pre-retry coverage to gate quality
|
||||
pre_warnings = len(gaps.get("coverage_warnings", []))
|
||||
pre_missing_rows = len(gaps.get("missing_table_rows", []))
|
||||
|
||||
retry_prompt = build_prompt(doc, feedback, all_paths)
|
||||
print(f" 重试 prompt 长度: {len(retry_prompt)} 字符", flush=True)
|
||||
retry_result = call_llm(retry_prompt, max_retries=1, temperature=0.3)
|
||||
@@ -892,27 +900,39 @@ def run_ensemble_semantic_index(doc: dict) -> dict:
|
||||
n_retry_concepts = len(retry_result.get("concepts", []))
|
||||
print(f" 重试返回: {n_retry_concepts} 概念, {n_retry_units} 功能单元", flush=True)
|
||||
if n_retry_units > 0:
|
||||
# Check which new sections were covered
|
||||
retry_sections = set()
|
||||
for fu in retry_result.get("function_units", []):
|
||||
for src in fu.get("sources", []):
|
||||
if src.get("section"):
|
||||
retry_sections.add(src["section"])
|
||||
print(f" 重试新增 sections: {sorted(retry_sections)}", flush=True)
|
||||
# Merge retry into results and re-validate
|
||||
# Quality gate: only include retry if it improves coverage
|
||||
trial_indices = semantic_indices + [retry_result]
|
||||
trial_merged = ensemble_merge(trial_indices)
|
||||
trial_passed, trial_gaps = _quick_validate(trial_merged, doc, all_paths)
|
||||
trial_warnings = len(trial_gaps.get("coverage_warnings", []))
|
||||
trial_missing = len(trial_gaps.get("missing_table_rows", []))
|
||||
if trial_warnings < pre_warnings or trial_missing < pre_missing_rows:
|
||||
semantic_indices.append(retry_result)
|
||||
merged = ensemble_merge(semantic_indices)
|
||||
merged["ensemble_temperatures"] = list(temperatures) + ["feedback_retry"]
|
||||
passed, gaps = _quick_validate(merged, doc, all_paths)
|
||||
merged = trial_merged
|
||||
passed, gaps = trial_passed, trial_gaps
|
||||
merged["ensemble_temperatures"] = list(temperatures) + [f"feedback_retry_{retry_count}"]
|
||||
merged["validation_passed"] = passed
|
||||
merged["validation_gaps"] = {
|
||||
k: v for k, v in gaps.items() if v
|
||||
}
|
||||
print(f" 重试后验证: {'PASS' if passed else 'GAPS FOUND'}", flush=True)
|
||||
print(f" 重试后验证 (已采纳): {'PASS' if passed else 'GAPS FOUND'} "
|
||||
f"(warnings {pre_warnings}→{trial_warnings}, "
|
||||
f"missing_rows {pre_missing_rows}→{trial_missing})", flush=True)
|
||||
else:
|
||||
print(f" 重试结果未提升覆盖率,丢弃 "
|
||||
f"(warnings {pre_warnings}→{trial_warnings}, "
|
||||
f"missing_rows {pre_missing_rows}→{trial_missing})", flush=True)
|
||||
except Exception as e:
|
||||
print(f" 覆盖反馈重试失败: {e}", flush=True)
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
break
|
||||
|
||||
return merged
|
||||
|
||||
|
||||
@@ -169,6 +169,40 @@ def _normalize_rule(rule: dict) -> dict:
|
||||
"value": "active"
|
||||
}]
|
||||
|
||||
# Ensure table/text sources have a section field (defensive against LLM omission)
|
||||
# Also normalize invalid source types (LLM hallucinations like function_unit_description)
|
||||
sources = rule.get("sources", [])
|
||||
valid_types = {"table", "text", "logic_tree"}
|
||||
|
||||
# try to infer a default section from the rule path
|
||||
default_section = ""
|
||||
for s in sources:
|
||||
sec = s.get("section", "")
|
||||
if sec and sec.strip():
|
||||
default_section = sec.strip()
|
||||
break
|
||||
if not default_section:
|
||||
path = rule.get("path", "")
|
||||
if path:
|
||||
default_section = path.split(" > ")[0] if " > " in path else path
|
||||
|
||||
if sources:
|
||||
for src in sources:
|
||||
stype = src.get("type", "")
|
||||
if stype and stype not in valid_types:
|
||||
src["type"] = "text"
|
||||
stype = "text"
|
||||
if stype in ("table", "text"):
|
||||
if not src.get("section"):
|
||||
src["section"] = default_section
|
||||
else:
|
||||
# Empty sources list — add a minimal text source (defensive against schema failure)
|
||||
src = {"type": "text", "text_snippet": "inferred from rule context"}
|
||||
if default_section:
|
||||
src["section"] = default_section
|
||||
sources.append(src)
|
||||
rule["sources"] = sources
|
||||
|
||||
return rule
|
||||
|
||||
|
||||
|
||||
@@ -465,3 +465,76 @@ class TestNormalizeRule:
|
||||
normalized = _normalize_rule(rule)
|
||||
assert normalized["trigger"]["operator"] == "AND"
|
||||
assert normalized["trigger"]["conditions"][0]["operator"] == ">="
|
||||
|
||||
def test_normalize_source_missing_section_from_sibling(self):
|
||||
"""Table/text sources without section get it from sibling sources."""
|
||||
rule = {
|
||||
"trigger": {"conditions": [{"signal": "x", "operator": "==", "value": "1"}]},
|
||||
"sources": [
|
||||
{"type": "table", "section": "3.1.1 系统限制", "row": 1},
|
||||
{"type": "text", "text_snippet": "missing section"},
|
||||
],
|
||||
}
|
||||
normalized = _normalize_rule(rule)
|
||||
assert normalized["sources"][1]["section"] == "3.1.1 系统限制"
|
||||
|
||||
def test_normalize_source_missing_section_from_path(self):
|
||||
"""Table/text sources without section and no sibling fall back to rule path."""
|
||||
rule = {
|
||||
"trigger": {"conditions": [{"signal": "x", "operator": "==", "value": "1"}]},
|
||||
"path": "4.2 关闭流程 > decision_speed > action_disable",
|
||||
"sources": [
|
||||
{"type": "table", "row": 3, "text_snippet": "no section anywhere"},
|
||||
],
|
||||
}
|
||||
normalized = _normalize_rule(rule)
|
||||
assert normalized["sources"][0]["section"] == "4.2 关闭流程"
|
||||
|
||||
def test_normalize_source_keeps_existing_section(self):
|
||||
"""Sources that already have section are not modified."""
|
||||
rule = {
|
||||
"trigger": {"conditions": [{"signal": "x", "operator": "==", "value": "1"}]},
|
||||
"sources": [
|
||||
{"type": "table", "section": "1.0 概述", "row": 1},
|
||||
],
|
||||
}
|
||||
normalized = _normalize_rule(rule)
|
||||
assert normalized["sources"][0]["section"] == "1.0 概述"
|
||||
|
||||
def test_normalize_source_skips_logic_tree(self):
|
||||
"""Logic tree sources are not touched (don't need section)."""
|
||||
rule = {
|
||||
"trigger": {"conditions": [{"signal": "x", "operator": "==", "value": "1"}]},
|
||||
"sources": [
|
||||
{"type": "logic_tree", "image_id": "img1", "node_ids": ["n1"]},
|
||||
],
|
||||
}
|
||||
normalized = _normalize_rule(rule)
|
||||
assert "section" not in normalized["sources"][0]
|
||||
|
||||
def test_normalize_source_invalid_type(self):
|
||||
"""Invalid source types (LLM hallucinations) are normalized to text."""
|
||||
rule = {
|
||||
"trigger": {"conditions": [{"signal": "x", "operator": "==", "value": "1"}]},
|
||||
"sources": [
|
||||
{"type": "function_unit_description", "text_snippet": "desc",
|
||||
"section": "3.1 功能"},
|
||||
{"type": "unknown_type", "text_snippet": "also invalid"},
|
||||
],
|
||||
}
|
||||
normalized = _normalize_rule(rule)
|
||||
assert normalized["sources"][0]["type"] == "text"
|
||||
assert normalized["sources"][1]["type"] == "text"
|
||||
assert normalized["sources"][0]["section"] == "3.1 功能"
|
||||
|
||||
def test_normalize_empty_sources(self):
|
||||
"""Rules with empty sources get a minimal text source (defensive)."""
|
||||
rule = {
|
||||
"trigger": {"conditions": [{"signal": "x", "operator": "==", "value": "1"}]},
|
||||
"path": "3.1 策略 > decision_speed",
|
||||
"sources": [],
|
||||
}
|
||||
normalized = _normalize_rule(rule)
|
||||
assert len(normalized["sources"]) == 1
|
||||
assert normalized["sources"][0]["type"] == "text"
|
||||
assert normalized["sources"][0]["section"] == "3.1 策略"
|
||||
|
||||
@@ -140,9 +140,19 @@ def ir_path(request) -> str:
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def ir_data(ir_path: str) -> dict:
|
||||
"""Load the IR JSON data."""
|
||||
"""Load the IR JSON data, normalizing each rule for defensive schema fixes."""
|
||||
with open(ir_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
data = json.load(f)
|
||||
|
||||
# Apply normalize to every rule so old IR files benefit from latest fixes
|
||||
# (invalid source types, missing section fields, trigger nulls, etc.)
|
||||
sys.path.insert(0, str(_PROJECT_ROOT / "skills" / "ir_generation_skill"))
|
||||
from step3_merge_and_audit import _normalize_rule
|
||||
rules = data.get("rules", [])
|
||||
if rules:
|
||||
data["rules"] = [_normalize_rule(r) for r in rules]
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
|
||||
@@ -291,6 +291,85 @@ def _measure_coverage(ir_data: dict, parsed_data: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def test_measure_coverage_excludes_zero_dimensions():
|
||||
"""#36: dimensions with total=0 must not drag down the overall rate.
|
||||
|
||||
When diagram total=0, the overall should be computed from sections and tables
|
||||
only, not include a 0% diagram entry that makes the goal unreachable.
|
||||
"""
|
||||
parsed_data = {
|
||||
"sections": [
|
||||
{"source": "3.1.1 功能A", "blocks": [
|
||||
{"type": "table", "rows": [{"cell": "1"}, {"cell": "2"}]}
|
||||
]}
|
||||
],
|
||||
"image_analysis": [], # no diagrams → total=0
|
||||
}
|
||||
# IR that covers the section but no table rows (table coverage = 0/2)
|
||||
ir_data = {
|
||||
"rules": [
|
||||
{"sources": [{"section": "3.1.1"}]} # 1 section covered, 0 tables
|
||||
]
|
||||
}
|
||||
|
||||
cov = _measure_coverage(ir_data, parsed_data)
|
||||
|
||||
# Section: 1/1 = 100%, Table: 0/2 = 0%, Diagram: total=0 → excluded
|
||||
assert cov["section_coverage"]["total"] == 1
|
||||
assert cov["section_coverage"]["rate"] == 1.0
|
||||
assert cov["table_coverage"]["total_rows"] == 2
|
||||
assert cov["table_coverage"]["rate"] == 0.0
|
||||
assert cov["diagram_coverage"]["total"] == 0
|
||||
assert cov["diagram_coverage"]["rate"] == 1.0 # _safe_rate: 0/0 → 1.0
|
||||
|
||||
# Key assertion: diagram (total=0) is excluded from overall
|
||||
# overall = (1.0 + 0.0) / 2 = 0.5
|
||||
# NOT (1.0 + 0.0 + 1.0) / 3 = 0.667
|
||||
assert cov["overall_rate"] == 0.5, (
|
||||
f"Expected overall 0.5 (sections + tables only), got {cov['overall_rate']}. "
|
||||
f"Zero-content dimension may be leaking into the average."
|
||||
)
|
||||
|
||||
|
||||
def test_measure_coverage_all_dimensions_have_content():
|
||||
"""When all dimensions have content, all should be included."""
|
||||
parsed_data = {
|
||||
"sections": [
|
||||
{"source": "3.1.1 功能A", "blocks": [
|
||||
{"type": "table", "rows": [{"cell": "1"}]}
|
||||
]}
|
||||
],
|
||||
"image_analysis": [{"type": "flowchart", "rid": "img_001"}],
|
||||
}
|
||||
ir_data = {
|
||||
"rules": [
|
||||
{"sources": [{"section": "3.1.1"}]},
|
||||
{"sources": [{"type": "table", "section": "3.1.1", "row": 0}]},
|
||||
{"sources": [{"type": "logic_tree", "image_id": "img_001"}]},
|
||||
]
|
||||
}
|
||||
|
||||
cov = _measure_coverage(ir_data, parsed_data)
|
||||
|
||||
# All three dimensions have content → all included
|
||||
assert cov["section_coverage"]["total"] == 1
|
||||
assert cov["table_coverage"]["total_rows"] == 1
|
||||
assert cov["diagram_coverage"]["total"] == 1
|
||||
# overall = (1.0 + 1.0 + 1.0) / 3 = 1.0
|
||||
assert cov["overall_rate"] == 1.0, (
|
||||
f"Expected overall 1.0 (all covered), got {cov['overall_rate']}"
|
||||
)
|
||||
|
||||
|
||||
def test_measure_coverage_no_content_returns_zero():
|
||||
"""When no dimensions have content, overall should be 0.0."""
|
||||
parsed_data = {"sections": [], "image_analysis": []}
|
||||
ir_data = {"rules": []}
|
||||
|
||||
cov = _measure_coverage(ir_data, parsed_data)
|
||||
assert cov["overall_rate"] == 0.0
|
||||
|
||||
|
||||
def test_layer_b_coverage(
|
||||
ir_data: dict,
|
||||
parsed_data: dict | None,
|
||||
|
||||
Reference in New Issue
Block a user