Files
streamline/scripts/rsi_loop/rsi_loop/proposal.py
T
2026-11-16 17:26:44 -08:00

210 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""把排名最高的问题模式变成一个「只插入新行」的 prompt 候选。
模型只决定写什么;插入、占位符一致和长度限制都由本模块确定性复核。控制面提交时还会
用 shared/src/rsi_loop.ts 再复核一遍。
"""
import json
import re
from typing import Any, List, Optional
from . import llm
STAGES = {"bug.run", "feature.run.first", "feature.run.second"}
# 业务指标(真值来自证据 manifest / 终态)优先;过程指标是机制层面的浪费。
# 口径与生产基线见 shared/src/rsi_loop.ts::LOOP_METRICS。
BUSINESS_METRICS = {"reach_s", "reach_miss", "evidence_fail", "dead_end_s"}
TARGET_METRICS = BUSINESS_METRICS | {
"ui_wait_s", "blind_sleep_s", "failed_calls",
"repeat_fail_calls", "frida_fail_calls", "tool_calls",
}
# 每种重放型能登记哪些目标:离线判的是动作机制,真机复跑判登记的指标,两者要是同一条因果链。
# 等 App 就绪 / 撞墙 / Frida 乱注入都发生在走到复现现场之前或认死路之前,所以都能挂到达和走不通时长;
# 证据校验失败只跟「撞同一堵墙」(重拍)一类有关。
METRICS_BY_REPLAY = {
"T1_repeat": {"repeat_fail_calls", "reach_s", "reach_miss", "dead_end_s", "evidence_fail"},
"T2_wait": {"ui_wait_s", "blind_sleep_s", "reach_s", "reach_miss"},
"T3_frida": {"frida_fail_calls", "reach_s", "dead_end_s"},
}
EVIDENCE_TERMS = re.compile(r"record-evidence|manifest|evidence/|\bbefore-|\bafter-|证据|截图|录屏|拍照|shot\b", re.I)
def gaming_error(metric: str, base: str, candidate: str) -> Optional[str]:
"""与 shared/src/rsi_loop.ts::lintMetricGaming 同一条规则:到达类目标不许改证据采集。"""
if metric not in ("reach_s", "reach_miss"):
return None
added = inserted_text(base, candidate).split("\n")
hit = next((line for line in added if EVIDENCE_TERMS.search(line)), None)
return f"目标是到达复现现场,新增内容却在改证据采集:{hit.strip()[:60]}" if hit else None
def placeholders(template: str) -> List[str]:
return sorted(set(re.findall(r"\{\{\s*([\w.]+)\s*\}\}", template)))
def candidate_error(base: str, candidate: str) -> Optional[str]:
if placeholders(base) != placeholders(candidate):
return "占位符不一致"
if len(candidate) < len(base):
return "候选比现行模板短"
if len(candidate) - len(base) > 4000:
return "新增超过 4000 字"
base_lines = base.split("\n")
j = 0
for line in candidate.split("\n"):
if j < len(base_lines) and line == base_lines[j]:
j += 1
return None if j == len(base_lines) else "候选改动了已有行"
def apply_insertion(base: str, content: str, after_line: Optional[str]) -> str:
addition = content.strip("\n")
if not addition:
raise ValueError("插入内容为空")
lines = base.split("\n")
if after_line:
matches = [i for i, line in enumerate(lines) if line == after_line]
if len(matches) != 1:
raise ValueError("afterLine 必须逐字匹配现行模板中唯一的一行")
at = matches[0] + 1
lines[at:at] = addition.split("\n")
else:
lines.extend(addition.split("\n"))
return "\n".join(lines)
def inserted_text(base: str, candidate: str) -> str:
"""提取候选新增的行;base 不是 candidate 子序列时拒绝。"""
base_lines = base.split("\n")
added: List[str] = []
j = 0
for line in candidate.split("\n"):
if j < len(base_lines) and line == base_lines[j]:
j += 1
else:
added.append(line)
if j != len(base_lines):
raise ValueError("候选不是纯插入")
return "\n".join(added).strip()
def _prompt(cluster: dict, base: str) -> str:
# 提案只需要审计结论,不需要把含工单正文/账号的逐字证据再喂一遍,更不能让它进入提交字段。
safe_samples = [
{"nFail": s.get("nFail"), "rationale": _redact(str(s.get("rationale") or ""))}
for s in (cluster.get("samples") or [])
]
samples = json.dumps(safe_samples, ensure_ascii=False, indent=2)
return f"""你负责给 coding agent 的执行 prompt 提一个小而可归因的改动。
只能针对下面这个已审计的问题模式;一次只插入一段新纪律,不得改写、删除现有行,
不得增加或删除 `{{{{占位符}}}}`。新增不超过 4000 字。
stage: {cluster['stage']}
平台: {cluster.get('platform')}(问题来自这个平台的执行记录。下面的现行模板是按这个平台展开后的版本)
策略范围(scope)二选一:
- "platform":单端策略。规则只对这个平台成立(涉及该平台专有的工具、页面形态、系统行为)。
只在这个平台的实验机复跑,通过后也只上这个平台,另一个平台的模板不变。
- "both":双端策略。规则对两端都成立(与平台无关的执行纪律)。两端实验机各复跑一遍,
两端都通过才两端一起上;只有一端通过就只上那一端。新增内容里出现单端专有的工具词
(adb、catuse、xcrun 等)会被控制面按单端处理。
拿不准就选 "platform" —— 单端通过后,人可以再决定补另一端复跑。
问题类别: {cluster['problemClass']}
模式: {cluster['cluster']} / {cluster.get('clusterTitle')}
浪费: {cluster['wasteCalls']} 次失败调用,{cluster['episodes']} 个片段,
{cluster['transcripts']} 份会话
可引用的审计样本:
{samples}
可事先登记的目标指标(越低越好)。优先登记业务指标 —— 它们是用户真正关心的结果,
真值来自证据清单和任务终态,不来自 agent 自述;过程指标只在该模式与任何业务结果都
没有可信因果链时才登记。
业务指标(2026-10 生产基线,160 批):
- reach_s: 到达复现现场用时 —— 从这批开始到第一张校验通过的修复前证据。中位 Android 30 分、
iOS 44 分,约占整批一半。
- reach_miss: 未到达复现现场 —— 一批结束仍没有合格的修复前证据。修好的批次里 Android 17%、
iOS 14%;复现不了的 12 批里 10 批没到达。
- evidence_fail: 证据校验失败次数(录空 / 太短 / 分辨率不够,需重拍)。每批 Android 0.6、iOS 1.0 次。
- dead_end_s: 走不通时耗掉的时长 —— 没以 FIXED 收尾的批次的整批时长(早期失败识别)。
复跑会混入历史上走不通的单,「修好的个数不少于现行」是底线,所以只能靠更早认出死路,不能靠早放弃。
过程指标:
- ui_wait_s: 等界面状态时长
- blind_sleep_s: 盲等时长
- failed_calls: 失败调用数
- repeat_fail_calls: 同类命令连续失败
- frida_fail_calls: Frida 失败调用
- tool_calls: 工具调用总数
本模式的重放型是 {cluster.get('replayType')},targetMetric 必须从
{sorted(METRICS_BY_REPLAY.get(cluster.get('replayType'), TARGET_METRICS))} 中选,
并在 hypothesis 里写清这个模式怎样因果地影响所选指标(离线重放判的是动作机制,
真机复跑判的是所选指标,两者要是同一条因果链)。
若选 reach_s / reach_miss:新增内容不得涉及证据采集(截图、录屏、record-evidence、
before/after 命名)—— 到达是按第一张合格修复前证据量的,改快门时机会让指标变好而现场没变快,
这种候选会被直接拒收。
现行模板(只能选其中唯一一行作为 afterLine;若放结尾则 afterLine=null):
---BASE---
{base}
---END BASE---
只返回 JSON:
{{
"title": "实验标题",
"summary": "问题总结,引用聚合数字,不泄露账号或工单正文",
"hypothesis": "为什么这一个改动会降低目标指标",
"method": "插入什么纪律、放在哪里、真机复跑时看什么",
"targetMetric": "上面列表中允许的一个",
"afterLine": "现行模板中逐字且唯一的一整行,或 null",
"content": "要插入的新行",
"scope": "platform 或 both",
"scopeReason": "一句话:为什么这条规则只对这个平台 / 对两端都成立"
}}
content 要写可执行决策规则(何时、先做什么、失败后怎么换路),不要写空泛口号,
不要修改评分规则、保留集、指标定义或要求模型自评成功。"""
def _redact(text: str) -> str:
text = re.sub(r"[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}", "<email>", text)
text = re.sub(r"(?i)\b(password|passwd|token|cookie|authorization)\s*[:=]\s*\S+", r"\1=<redacted>", text)
text = re.sub(r"\b[0-9a-f]{24,}\b", "<id>", text, flags=re.I)
return text[:1200]
def create(cluster: dict, base: str) -> dict:
if cluster.get("stage") not in STAGES:
raise ValueError("不支持的 stage")
value: Any = llm.ask_json(_prompt(cluster, base), timeout=1200)
if not isinstance(value, dict):
raise ValueError("提案不是 JSON 对象")
required = ("title", "summary", "hypothesis", "method", "targetMetric", "content")
if any(not str(value.get(k) or "").strip() for k in required):
raise ValueError("提案缺少必填字段")
metric = str(value["targetMetric"])
if metric not in TARGET_METRICS:
raise ValueError("targetMetric 不在目录里")
allowed = METRICS_BY_REPLAY.get(cluster.get("replayType"), TARGET_METRICS)
if metric not in allowed:
raise ValueError("targetMetric 与该模式的离线动作判分不对应")
after = value.get("afterLine")
if after is not None and not isinstance(after, str):
raise ValueError("afterLine 格式错误")
candidate = apply_insertion(base, str(value["content"]), after)
error = candidate_error(base, candidate) or gaming_error(metric, base, candidate)
if error:
raise ValueError(error)
return {
"stage": cluster["stage"],
"platform": cluster.get("platform"),
"title": str(value["title"]).strip()[:200],
"summary": str(value["summary"]).strip()[:6000],
"hypothesis": str(value["hypothesis"]).strip()[:4000],
"method": str(value["method"]).strip()[:4000],
"targetMetric": metric,
"problemClass": cluster["problemClass"],
"cluster": cluster["cluster"],
"candidateTemplate": candidate,
# 策略范围:both = 两端各复跑;其余一律单端(控制面按 platform 处理)
"scope": "both" if str(value.get("scope") or "").strip() == "both" else cluster.get("platform"),
"scopeReason": str(value.get("scopeReason") or "").strip()[:1000],
# 重放按同一个锚点把同样的几行插进历史 prompt,与生产渲染的位置一致(不提交给控制面)
"_insertion": {"afterLine": after, "content": inserted_text(base, candidate)},
}