ohos-devloop 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. ohos_devloop/__init__.py +2 -0
  2. ohos_devloop/_version.py +24 -0
  3. ohos_devloop/agents/skills/collab-delegate/SKILL.md +79 -0
  4. ohos_devloop/agents/skills/loop-iterate/SKILL.md +54 -0
  5. ohos_devloop/agents/skills/openharmony-ci/SKILL.md +71 -0
  6. ohos_devloop/agents/skills/openharmony-ci/agents/openai.yaml +4 -0
  7. ohos_devloop/agents/skills/openharmony-ci/scripts/openharmony_ci.py +520 -0
  8. ohos_devloop/agents/skills/pool-status/SKILL.md +47 -0
  9. ohos_devloop/config/e2e-cases.yaml +31 -0
  10. ohos_devloop/config/e2e-hap.yaml +54 -0
  11. ohos_devloop/config/inventory-template.yaml +35 -0
  12. ohos_devloop/config/inventory.yaml +68 -0
  13. ohos_devloop/config/report-templates/analysis-report.md +48 -0
  14. ohos_devloop/config/report-templates/impl-report.md +47 -0
  15. ohos_devloop/config/task-template.md +21 -0
  16. ohos_devloop/config/tdd-board.yaml +31 -0
  17. ohos_devloop/config/tdd-coverage.yaml +47 -0
  18. ohos_devloop/config/tdd-emulator.yaml +36 -0
  19. ohos_devloop/config/tdd-host.yaml +26 -0
  20. ohos_devloop/config/tdd-suites.yaml +34 -0
  21. ohos_devloop/config/templates/agents-user.md +11 -0
  22. ohos_devloop/config/templates/quickstart.md +82 -0
  23. ohos_devloop/config/verify.yaml +45 -0
  24. ohos_devloop/examples/anchor-e2e.yaml +55 -0
  25. ohos_devloop/examples/assert-smoke.yaml +33 -0
  26. ohos_devloop/examples/diffcov-fixture/cov.json +6688 -0
  27. ohos_devloop/examples/diffcov-fixture/diff.txt +24 -0
  28. ohos_devloop/examples/diffcov-smoke.yaml +32 -0
  29. ohos_devloop/examples/e2e-emu-smoke.yaml +45 -0
  30. ohos_devloop/examples/layout-fixture.norm.json +1 -0
  31. ohos_devloop/examples/smoke.yaml +27 -0
  32. ohos_devloop/ohos_cli.py +131 -0
  33. ohos_devloop/scripts/agent-run-v3.sh +149 -0
  34. ohos_devloop/scripts/apply.py +1448 -0
  35. ohos_devloop/scripts/check_env.py +284 -0
  36. ohos_devloop/scripts/collab.py +303 -0
  37. ohos_devloop/scripts/diffcov.py +211 -0
  38. ohos_devloop/scripts/flash.py +511 -0
  39. ohos_devloop/scripts/mount_ws.py +192 -0
  40. ohos_devloop/scripts/release.py +2645 -0
  41. ohos_devloop/scripts/release_audit.py +260 -0
  42. ohos_devloop/scripts/release_metadata.py +397 -0
  43. ohos_devloop/scripts/release_smoke.py +287 -0
  44. ohos_devloop/scripts/report_draft.py +234 -0
  45. ohos_devloop/scripts/server_init.py +310 -0
  46. ohos_devloop/scripts/sgrep.py +82 -0
  47. ohos_devloop/scripts/sign_hap.py +256 -0
  48. ohos_devloop/scripts/telemetry.py +260 -0
  49. ohos_devloop/scripts/ui_probe.py +396 -0
  50. ohos_devloop/scripts/verify_frame_diff.py +138 -0
  51. ohos_devloop/scripts/ws_init.py +131 -0
  52. ohos_devloop/scripts/wsroot.py +192 -0
  53. ohos_devloop-0.1.2.dist-info/METADATA +177 -0
  54. ohos_devloop-0.1.2.dist-info/RECORD +58 -0
  55. ohos_devloop-0.1.2.dist-info/WHEEL +5 -0
  56. ohos_devloop-0.1.2.dist-info/entry_points.txt +2 -0
  57. ohos_devloop-0.1.2.dist-info/licenses/LICENSE +202 -0
  58. ohos_devloop-0.1.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """遥测(M6:遥测与试点)—— opt-in 匿名使用统计,beta → GA 决策数据。
4
+
5
+ 用法:
6
+ python scripts/telemetry.py on # 开启(打印收集范围声明)
7
+ python scripts/telemetry.py off # 关闭(默认关)
8
+ python scripts/telemetry.py status # 开关/积压/端点/本机 user_id
9
+ python scripts/telemetry.py push # 把本地未上报事件批量推到中央收集点
10
+
11
+ 设计(ROADMAP M6 + RUNBOOK「遥测」节):
12
+ - 只收「形状」不收「内容」: 命令名/退出码/耗时、job 与步骤结果(PASS/FAIL/error_kind/耗时)、
13
+ 任务收敛(status/iterations)、check_env 汇总计数、工具版本。不收代码/diff/任务文本/
14
+ 命令参数值/日志正文/路径。
15
+ - opt-in 默认关;事件本地攒 ~/.ohos-devloop/telemetry/events-YYYYMMDD.jsonl;
16
+ push 按 state.json 游标增量推,失败不丢、下次重试。
17
+ - 出口统一在本机 CLI(worker/服务器数据经 status.json 由本机带回,不让 worker 直连外网)。
18
+ - emit 永不抛异常——遥测故障不得影响主流程。
19
+ """
20
+ import argparse
21
+ import datetime
22
+ import hashlib
23
+ import json
24
+ import os
25
+ import platform
26
+ import sys
27
+ import urllib.error
28
+ import urllib.request
29
+ from pathlib import Path
30
+
31
+ # 版本单点(D-08):正本在 ohos_cli.version(metadata → git 兜底(仅裸跑)→ unknown)。
32
+ # 机制 (a):插入包根后裸 import。ohos_cli 对本模块是函数内惰性 import(_telemetry_cmd 先例),
33
+ # 顶部 import 不构成循环;sys.path[0]=脚本目录的裸跑形态也可解析。
34
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
35
+ import ohos_cli # noqa: E402
36
+ tool_version = ohos_cli.version
37
+
38
+ SCHEMA = 1
39
+ # 收集点端点缺省为空(PUB-01 占位化,2026-11-18):包内不再携带内网端点。端点值(beta
40
+ # 中央收集点地址与端口)见 RUNBOOK「遥测」节;等价托管遥测的 write-key:token 仅授权
41
+ # "写入遥测事件"这一个动作,泄露不构成数据面风险。
42
+ # token 不入仓:取 config.json 的 "token" 字段或环境变量 DEVLOOP_TELEMETRY_TOKEN(与服务器
43
+ # ~/telemetry/token.txt 一致);端点经 config.json 的 "endpoint" 键或 push --endpoint 注入。
44
+ DEFAULT_ENDPOINT = ""
45
+
46
+ DIR = Path.home() / ".ohos-devloop" / "telemetry"
47
+ BATCH = 500 # 单次 push 上限行数(与服务端每请求上限一致)
48
+ HTTP_TIMEOUT = 20
49
+
50
+ COLLECT_SCOPE = ("收集:命令名/退出码/耗时、job 与步骤结果(PASS/FAIL/错误类别/耗时)、"
51
+ "任务收敛(status/迭代轮数)、check_env 汇总计数、工具版本。"
52
+ "不收集:代码/diff/任务内容/命令参数值/日志正文/路径。可随时 off。")
53
+
54
+
55
+ def _now() -> str:
56
+ return datetime.datetime.now().astimezone().isoformat(timespec="seconds")
57
+
58
+
59
+ def _machine_user() -> str:
60
+ who = f"{platform.node()}|{os.environ.get('USERNAME') or os.environ.get('USER', '')}"
61
+ return hashlib.sha256(who.encode("utf-8")).hexdigest()[:12]
62
+
63
+
64
+ def config() -> dict:
65
+ """读 ~/.ohos-devloop/telemetry/config.json;首建时生成稳定 user_id。"""
66
+ cfg_path = DIR / "config.json"
67
+ cfg = {}
68
+ try:
69
+ if cfg_path.is_file():
70
+ cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
71
+ except Exception:
72
+ cfg = {}
73
+ if not cfg.get("user"):
74
+ cfg["user"] = _machine_user()
75
+ try:
76
+ DIR.mkdir(parents=True, exist_ok=True)
77
+ cfg_path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2),
78
+ encoding="utf-8")
79
+ except Exception:
80
+ pass
81
+ return cfg
82
+
83
+
84
+ def is_enabled() -> bool:
85
+ return bool(config().get("enabled"))
86
+
87
+
88
+ def set_enabled(on: bool) -> None:
89
+ cfg = config()
90
+ cfg["enabled"] = on
91
+ DIR.mkdir(parents=True, exist_ok=True)
92
+ (DIR / "config.json").write_text(json.dumps(cfg, ensure_ascii=False, indent=2),
93
+ encoding="utf-8")
94
+
95
+
96
+ def emit(event: str, **fields) -> None:
97
+ """落一条事件(开关关时 no-op);任何异常吞掉,绝不影响调用方主流程。"""
98
+ try:
99
+ if not is_enabled():
100
+ return
101
+ envelope = {"schema": SCHEMA, "user": config().get("user", "?"),
102
+ "tool_version": tool_version(), "ts": _now(), "event": event}
103
+ envelope.update(fields)
104
+ day = datetime.datetime.now().strftime("%Y%m%d")
105
+ DIR.mkdir(parents=True, exist_ok=True)
106
+ with open(DIR / f"events-{day}.jsonl", "a", encoding="utf-8", newline="\n") as f:
107
+ f.write(json.dumps(envelope, ensure_ascii=False) + "\n")
108
+ except Exception:
109
+ pass
110
+
111
+
112
+ def classify_error(detail, status: str) -> str:
113
+ """失败原因粗分类(枚举稳定,供 step_done 的 error_kind 字段)。"""
114
+ if status != "fail":
115
+ return ""
116
+ text = " ".join(str(v) for v in (detail or {}).values()) if isinstance(detail, dict) else str(detail or "")
117
+ t = text.lower()
118
+ for kind, marks in (
119
+ ("timeout", ["timeout", "timed out", "超时"]),
120
+ ("version_mismatch", ["版本过低", "min_tool_version", "基线不一致", "software.version"]),
121
+ ("hdc_error", ["hdc", "设备不在线", "not online", "无设备"]),
122
+ ("ssh_error", ["ssh", "connection refused", "permission denied", "scp"]),
123
+ ("build_fail", ["build", "ninja", "编译", "构建失败"]),
124
+ ("assert_fail", ["assert", "断言"]),
125
+ ("sign_fail", ["签名", "sign", "udid"]),
126
+ ("install_fail", ["install", "bm dump", "grant request"]),
127
+ ):
128
+ if any(m in t for m in marks):
129
+ return kind
130
+ return "other"
131
+
132
+
133
+ def _state() -> dict:
134
+ p = DIR / "state.json"
135
+ try:
136
+ return json.loads(p.read_text(encoding="utf-8")) if p.is_file() else {}
137
+ except Exception:
138
+ return {}
139
+
140
+
141
+ def pending_lines() -> list[str]:
142
+ """所有当日/历史文件中未推送的事件行(按文件序 + 行序,截断到 BATCH 上限由 push 控制)。"""
143
+ out: list[str] = []
144
+ st = _state()
145
+ for f in sorted(DIR.glob("events-*.jsonl")):
146
+ try:
147
+ lines = f.read_text(encoding="utf-8").splitlines()
148
+ except Exception:
149
+ continue
150
+ n = st.get(f.name, 0)
151
+ if len(lines) > n:
152
+ out.extend(lines[n:])
153
+ return out
154
+
155
+
156
+ def push(endpoint: str = "", token: str = "") -> tuple[int, str]:
157
+ """增量推送;成功更新游标。返回 (exit_code, message)。"""
158
+ if not is_enabled():
159
+ return 1, "遥测未开启(先 telemetry on;不开启则无数据可推)"
160
+ cfg = config()
161
+ ep = endpoint or cfg.get("endpoint") or DEFAULT_ENDPOINT
162
+ if not ep:
163
+ return 1, ("遥测端点未配置:在 ~/.ohos-devloop/telemetry/config.json 写 \"endpoint\" 键"
164
+ "(端点值见 RUNBOOK「遥测」节),或 push --endpoint <url> 指定")
165
+ url = ep.rstrip("/") + "/collect"
166
+ tok = token or cfg.get("token") or os.environ.get("DEVLOOP_TELEMETRY_TOKEN", "")
167
+ if not tok:
168
+ return 1, ("缺少 token:在 ~/.ohos-devloop/telemetry/config.json 写 \"token\" 字段,"
169
+ "或设环境变量 DEVLOOP_TELEMETRY_TOKEN(与服务器 ~/telemetry/token.txt 一致)")
170
+ total = 0
171
+ while True:
172
+ # 重新扫描而非内存切片:成功一批后下一批的"未推"自然减少
173
+ lines = pending_lines()[:BATCH]
174
+ if not lines:
175
+ break
176
+ body = json.dumps({"events": [json.loads(x) for x in lines]}).encode("utf-8")
177
+ req = urllib.request.Request(url, data=body, method="POST",
178
+ headers={"Content-Type": "application/json",
179
+ "Authorization": f"Bearer {tok}"})
180
+ try:
181
+ with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as resp:
182
+ ok = resp.status == 200
183
+ except urllib.error.HTTPError as e:
184
+ return 1, f"收集点拒绝: HTTP {e.code}(token 不匹配?)"
185
+ except Exception as e:
186
+ return 1, f"推送失败(数据保留本地,可重试): {e}"
187
+ if not ok:
188
+ return 1, "收集点返回非 200"
189
+ _advance_state(lines)
190
+ total += len(lines)
191
+ if total >= 20000:
192
+ break # 单次 push 上限保护(≈40 天满负荷积压)
193
+ return 0, f"已推送 {total} 条事件 → {url}"
194
+
195
+
196
+ def _advance_state(pushed: list[str]) -> None:
197
+ """按各文件行数推进游标。调用方保证 pushed 是扫描序的前缀连续段。"""
198
+ st = _state()
199
+ remain = list(pushed)
200
+ for f in sorted(DIR.glob("events-*.jsonl")):
201
+ if not remain:
202
+ break
203
+ try:
204
+ n_total = len(f.read_text(encoding="utf-8").splitlines())
205
+ except Exception:
206
+ continue
207
+ cur = st.get(f.name, 0)
208
+ can_take = n_total - cur
209
+ take = min(can_take, len(remain))
210
+ if take > 0:
211
+ st[f.name] = cur + take
212
+ remain = remain[take:]
213
+ try:
214
+ (DIR / "state.json").write_text(json.dumps(st, ensure_ascii=False, indent=2),
215
+ encoding="utf-8")
216
+ except Exception:
217
+ pass
218
+
219
+
220
+ def status() -> str:
221
+ cfg = config()
222
+ n_pending = len(pending_lines())
223
+ files = sorted(DIR.glob("events-*.jsonl"))
224
+ ep = cfg.get("endpoint") or DEFAULT_ENDPOINT
225
+ ep_line = ep if ep else "未配置(config.json 写 \"endpoint\" 键,端点值见 RUNBOOK「遥测」节)"
226
+ return (f"开关: {'on' if cfg.get('enabled') else 'off'}(默认关,opt-in)\n"
227
+ f"user_id: {cfg.get('user', '?')}(机器+用户名哈希,匿名)\n"
228
+ f"端点: {ep_line}\n"
229
+ f"本地事件文件: {len(files)} 个,未上报 {n_pending} 条"
230
+ f"{'(telemetry push 上报)' if n_pending else ''}")
231
+
232
+
233
+ def main() -> int:
234
+ try:
235
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
236
+ except Exception:
237
+ pass
238
+ ap = argparse.ArgumentParser(description="遥测开关/上报(opt-in,默认关)")
239
+ ap.add_argument("action", choices=["on", "off", "status", "push"])
240
+ ap.add_argument("--endpoint", help="覆盖收集点地址(默认内置 beta 收集点)")
241
+ ap.add_argument("--token", help="覆盖收集 token")
242
+ args = ap.parse_args()
243
+ if args.action == "on":
244
+ set_enabled(True)
245
+ print(f"遥测已开启。{COLLECT_SCOPE}")
246
+ return 0
247
+ if args.action == "off":
248
+ set_enabled(False)
249
+ print("遥测已关闭(本地未上报事件保留,不再新增)。")
250
+ return 0
251
+ if args.action == "status":
252
+ print(status())
253
+ return 0
254
+ rc, msg = push(endpoint=args.endpoint, token=args.token)
255
+ print(msg)
256
+ return rc
257
+
258
+
259
+ if __name__ == "__main__":
260
+ sys.exit(main())
@@ -0,0 +1,396 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """ui_probe.py —— UI 树取证/断言模块(ArkUI 组件树证据层,ROADMAP M4)。
4
+
5
+ 三层证据模型中负责**语义/结构层**:`uitest dumpLayout` 的组件树是"界面上到底是什么"的
6
+ 地面真值(text/bounds/type 直接可读),截图+frame_diff 负责渲染层、hilog marker 负责事件链。
7
+
8
+ 双形态:
9
+ 库 —— apply.py 薄布线调用(assert node 断言 / capture layout 旗标 / ui_click 步骤)
10
+ CLI —— 主 Agent 交互取证一条命令(替代对截图的像素级推理):
11
+ ohos-devloop ui-probe dump [--out evidence/layout_0.json] [--settle-s 1]
12
+ ohos-devloop ui-probe norm <raw.json> [out.json] # 离线标准化(对既有 raw 取证)
13
+ ohos-devloop ui-probe query <norm.json> --type GridItem --text-re "^item-" --fmt lines
14
+ ohos-devloop ui-probe first-visible <norm.json> --type GridItem --region 0,200,720,1280
15
+ ohos-devloop ui-probe click --text-re "^Prepend" [--dump-after evidence/after.json]
16
+
17
+ 标准化(黑名单策略,非白名单——单一 dump 样本推白名单会漏字段,如 text 的 content 形态):
18
+ raw 每节点 ~37 属性、168 节点 106KB;标准形丢弃空串/"false"/默认值 + 黑名单样式与调试
19
+ 内部字段,未知**非空**字段原名透传(版本演进免疫),bounds 字符串解析为 int 四元组。
20
+ 实测 ~10KB(≈10× 压缩),--fmt lines 树文本 ≈7KB。
21
+
22
+ 坑位(内置):hdc file recv 本地参数必须**反斜杠 Windows 绝对路径**(正斜杠会被当相对路径
23
+ 拼坏);uitest dumpLayout 写 /data/local/tmp 需可写路径。
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import datetime
29
+ import json
30
+ import re
31
+ import subprocess
32
+ import sys
33
+ import time
34
+ from pathlib import Path
35
+
36
+ import yaml
37
+
38
+ import wsroot # inventory 读源(工作区优先、包回落;扁平互 import 现状,wsroot 不依赖任何脚本)
39
+
40
+ BASE = Path(__file__).resolve().parent.parent
41
+ RE_BOUNDS = re.compile(r"\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]")
42
+
43
+ # 黑名单:样式/调试内部字段(实测对断言与取证无用;取证需要全量时用 norm --keep-all)
44
+ NOISE_ATTRS = {
45
+ "hashcode", "hierarchy", "hostWindowId", "displayId", "accessibilityId",
46
+ "backgroundColor", "backgroundImage", "blur", "opacity", "clip", "zIndex",
47
+ "origBounds", "hitTestBehavior",
48
+ }
49
+ # 已知映射之外的 true 型旗标(仅 true 保留);visible/enabled 默认 true、仅 false 时保留
50
+ FLAG_ATTRS = ("clickable", "longClickable", "checkable", "checked",
51
+ "scrollable", "selected", "focused")
52
+ FALSE_MEANS_SOMETHING = ("visible", "enabled")
53
+
54
+
55
+ def sh(args: list[str], timeout: int = 60) -> tuple[int, str, str]:
56
+ try:
57
+ p = subprocess.run(args, capture_output=True, text=True, encoding="utf-8",
58
+ errors="replace", timeout=timeout)
59
+ return p.returncode, p.stdout or "", p.stderr or ""
60
+ except subprocess.TimeoutExpired:
61
+ return 124, "", f"timeout after {timeout}s"
62
+ except FileNotFoundError as e:
63
+ return 127, "", str(e)
64
+
65
+
66
+ def hdc_prefix(hdc: str | None = None) -> list[str]:
67
+ """hdc 命令前缀:--hdc 参数 > UI_PROBE_HDC > inventory local.hdc。"""
68
+ path = hdc or _inv_hdc()
69
+ return [path] if path else ["hdc"]
70
+
71
+
72
+ def _inv_hdc() -> str:
73
+ try:
74
+ inv = yaml.safe_load(wsroot.inventory_path().read_text(encoding="utf-8"))
75
+ return str((inv.get("local") or {}).get("hdc") or "")
76
+ except OSError:
77
+ return ""
78
+
79
+
80
+ # --------------------------------------------------------------------------- 采集
81
+
82
+ def dump_layout(out: Path, hdc: list[str] | None = None, settle_s: float = 0.5,
83
+ keep_raw: bool = True) -> Path:
84
+ """静置 → uitest dumpLayout → recv → 标准化写出。返回标准形路径(raw 落 <out>.raw.json)。"""
85
+ out = Path(out)
86
+ out.parent.mkdir(parents=True, exist_ok=True)
87
+ if settle_s:
88
+ time.sleep(settle_s)
89
+ prefix = list(hdc) if hdc else hdc_prefix()
90
+ dev = "/data/local/tmp/ui_probe_layout.json"
91
+ rc, _, err = sh(prefix + ["shell", f"uitest dumpLayout -p {dev}"], timeout=30)
92
+ raw_local = out.with_name(out.stem + ".raw.json")
93
+ # hdc 坑位:recv 本地参数须 Windows 反斜杠绝对路径(Path 落盘本身就是),rc 不可信以落盘为准
94
+ sh(prefix + ["file", "recv", dev, str(raw_local.resolve())], timeout=60)
95
+ sh(prefix + ["shell", f"rm -f {dev}"])
96
+ if not raw_local.is_file() or raw_local.stat().st_size == 0:
97
+ raise RuntimeError(f"dumpLayout 采集失败(uitest 未产出或 recv 失败): {err.strip()[:200]}")
98
+ raw = json.loads(raw_local.read_text(encoding="utf-8", errors="replace"))
99
+ if not keep_raw:
100
+ raw_local.unlink(missing_ok=True)
101
+ return write_norm(normalize(raw), out)
102
+
103
+
104
+ # --------------------------------------------------------------------------- 标准化
105
+
106
+ def _parse_bounds(s: str) -> list[int] | None:
107
+ m = RE_BOUNDS.fullmatch((s or "").strip())
108
+ return [int(x) for x in m.groups()] if m else None
109
+
110
+
111
+ def normalize(raw, keep_all: bool = False) -> dict:
112
+ """raw dump(list[根节点] 或单根)→ {head, tree}。黑名单 + 默认值裁剪 + 未知非空透传。"""
113
+ roots = raw if isinstance(raw, list) else [raw]
114
+ head = {"dumpedAt": datetime.datetime.now().isoformat(timespec="seconds")}
115
+ count = 0
116
+
117
+ def conv(attrs: dict) -> dict:
118
+ nonlocal count
119
+ count += 1
120
+ if keep_all:
121
+ n = dict(attrs)
122
+ b = _parse_bounds(attrs.get("bounds", ""))
123
+ if b:
124
+ n["bounds"] = b
125
+ return n
126
+ n: dict = {}
127
+ if attrs.get("type"):
128
+ n["t"] = attrs["type"]
129
+ if attrs.get("text"):
130
+ n["x"] = attrs["text"]
131
+ b = _parse_bounds(str(attrs.get("bounds", "")))
132
+ if b:
133
+ n["b"] = b
134
+ k = attrs.get("key") or attrs.get("id")
135
+ if k:
136
+ n["k"] = k
137
+ flags = {f: True for f in FLAG_ATTRS if str(attrs.get(f, "")).lower() == "true"}
138
+ for f in FALSE_MEANS_SOMETHING:
139
+ if str(attrs.get(f, "")).lower() == "false":
140
+ flags[f] = False
141
+ if flags:
142
+ n["f"] = flags
143
+ extra = {k2: v for k2, v in attrs.items()
144
+ if k2 not in NOISE_ATTRS and k2 not in ("type", "text", "bounds", "key", "id",
145
+ *FLAG_ATTRS, *FALSE_MEANS_SOMETHING)
146
+ and v not in ("", None, [], {}, "false", "0.000000", "1.000000", "false ")}
147
+ # 文本语义族(originalText/hint/description/content…)与未来新字段经此透传
148
+ if extra:
149
+ n["extra"] = extra
150
+ for meta in ("bundleName", "abilityName", "pagePath"):
151
+ if attrs.get(meta) and meta not in head:
152
+ head[{"bundleName": "bundle", "abilityName": "ability",
153
+ "pagePath": "page"}[meta]] = attrs[meta]
154
+ return n
155
+
156
+ def walk(node: dict) -> dict:
157
+ n = conv(node.get("attributes") or {})
158
+ children = [walk(c) for c in node.get("children") or []]
159
+ if children:
160
+ n["c"] = children
161
+ return n
162
+
163
+ tree = [walk(r) for r in roots if isinstance(r, dict)]
164
+ head["nodes"] = count
165
+ return {"head": head, "tree": tree}
166
+
167
+
168
+ def write_norm(norm: dict, out: Path) -> Path:
169
+ out = Path(out)
170
+ out.parent.mkdir(parents=True, exist_ok=True)
171
+ out.write_text(json.dumps(norm, ensure_ascii=False, separators=(",", ":")),
172
+ encoding="utf-8", newline="\n")
173
+ return out
174
+
175
+
176
+ def load(path: Path) -> dict:
177
+ return json.loads(Path(path).read_text(encoding="utf-8", errors="replace"))
178
+
179
+
180
+ # --------------------------------------------------------------------------- 查询
181
+
182
+ def node_text(node: dict, rollup: bool = True) -> str:
183
+ """节点自身 text;rollup 时退化取首个后代 text(GridItem 的 label 在 Text 子节点)。"""
184
+ if node.get("x"):
185
+ return node["x"]
186
+ if rollup:
187
+ for c in node.get("c", []):
188
+ t = node_text(c, rollup=True)
189
+ if t:
190
+ return t
191
+ return ""
192
+
193
+
194
+ def query_nodes(norm: dict, sel: dict) -> list[dict]:
195
+ """选择器 → 匹配节点(扁平、按 (y,x) 排序)。
196
+
197
+ sel: {type, text_re, region: [x1,y1,x2,y2](bounds 相交), min_h, rollup_text(默认 true)}
198
+ """
199
+ import re as _re
200
+ type_re = _re.compile(sel["type"]) if sel.get("type") else None
201
+ text_re = _re.compile(sel["text_re"]) if sel.get("text_re") else None
202
+ region = sel.get("region")
203
+ min_h = int(sel.get("min_h") or 0)
204
+ rollup = sel.get("rollup_text", True)
205
+ out: list[dict] = []
206
+
207
+ def hit(node: dict) -> bool:
208
+ if type_re and not type_re.search(node.get("t", "")):
209
+ return False
210
+ if text_re and not text_re.search(node_text(node, rollup)):
211
+ return False
212
+ b = node.get("b")
213
+ if not b:
214
+ return False
215
+ if min_h and b[3] - b[1] < min_h:
216
+ return False
217
+ if region and not (b[0] < region[2] and b[2] > region[0]
218
+ and b[1] < region[3] and b[3] > region[1]):
219
+ return False
220
+ return True
221
+
222
+ def walk(node: dict):
223
+ if hit(node):
224
+ out.append(node)
225
+ for c in node.get("c", []):
226
+ walk(c)
227
+
228
+ for r in norm.get("tree", []):
229
+ walk(r)
230
+ out.sort(key=lambda n: (n["b"][1], n["b"][0]))
231
+ return out
232
+
233
+
234
+ def extract_fact(nodes: list[dict], fact: str, nth: int = 0):
235
+ """fact ∈ text|count|top_y|bottom_y|height;无匹配时 text=''、数值为 None。"""
236
+ if fact == "count":
237
+ return len(nodes)
238
+ if not nodes:
239
+ return "" if fact == "text" else None
240
+ n = nodes[min(nth, len(nodes) - 1)]
241
+ if fact == "text":
242
+ return node_text(n)
243
+ b = n.get("b") or [0, 0, 0, 0]
244
+ return {"top_y": b[1], "bottom_y": b[3], "height": b[3] - b[1]}.get(fact)
245
+
246
+
247
+ def compare(value, op: str, expect) -> bool:
248
+ if op == "re":
249
+ return re.search(str(expect), str(value)) is not None
250
+ try:
251
+ v, e = float(value), float(expect)
252
+ except (TypeError, ValueError):
253
+ return str(value) == str(expect)
254
+ return {"eq": v == e, "le": v <= e, "ge": v >= e,
255
+ "lt": v < e, "gt": v > e}.get(op, v == e)
256
+
257
+
258
+ def render_lines(norm: dict, max_depth: int = 99) -> str:
259
+ """缩进树文本(模型上下文友好)。"""
260
+ lines: list[str] = []
261
+
262
+ def walk(node: dict, d: int):
263
+ if d > max_depth:
264
+ return
265
+ bits = [node.get("t", "?")]
266
+ if node.get("x"):
267
+ bits.append(repr(node["x"]))
268
+ if node.get("k"):
269
+ bits.append(f"#{node['k']}")
270
+ if node.get("b"):
271
+ bits.append(f"b={node['b']}")
272
+ if node.get("f"):
273
+ bits.append("[" + ",".join(f"{k}={v}" for k, v in node["f"].items()) + "]")
274
+ if node.get("extra"):
275
+ bits.append("{" + ",".join(f"{k}={v}" for k, v in node["extra"].items()) + "}")
276
+ lines.append(" " * d + " ".join(bits))
277
+ for c in node.get("c", []):
278
+ walk(c, d + 1)
279
+
280
+ for r in norm.get("tree", []):
281
+ walk(r, 0)
282
+ return "\n".join(lines)
283
+
284
+
285
+ # --------------------------------------------------------------------------- 交互
286
+
287
+ def resolve_and_click(sel: dict, hdc: list[str] | None = None, settle_s: float = 1.5) -> dict:
288
+ """dump → 选择器定位 → bounds 中心 → uinput 点击。返回 {ok, node, x, y}。"""
289
+ import tempfile
290
+ with tempfile.TemporaryDirectory(prefix="ui_probe_") as td:
291
+ tmp = Path(td) / "click.json"
292
+ dump_layout(tmp, hdc=hdc, settle_s=0.3, keep_raw=False)
293
+ nodes = query_nodes(load(tmp), sel)
294
+ if not nodes:
295
+ return {"ok": False, "node": None, "x": None, "y": None}
296
+ n = nodes[0]
297
+ x = (n["b"][0] + n["b"][2]) // 2
298
+ y = (n["b"][1] + n["b"][3]) // 2
299
+ prefix = list(hdc) if hdc else hdc_prefix()
300
+ rc, out, err = sh(prefix + ["shell", f"uinput -T -c {x} {y}"], timeout=30)
301
+ time.sleep(settle_s)
302
+ return {"ok": "fail" not in (out + err).lower(), "node": n, "x": x, "y": y,
303
+ "uinput_out": (out + err).strip()[:120]}
304
+
305
+
306
+ # --------------------------------------------------------------------------- CLI
307
+
308
+ def main() -> int:
309
+ try:
310
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
311
+ except Exception:
312
+ pass
313
+ ap = argparse.ArgumentParser(description="UI 树取证/断言(组件树证据层)")
314
+ sub = ap.add_subparsers(dest="cmd", required=True)
315
+
316
+ p = sub.add_parser("dump", help="板端 dumpLayout → 标准化落盘")
317
+ p.add_argument("--out", default="evidence/layout.json")
318
+ p.add_argument("--settle-s", type=float, default=0.5)
319
+ p.add_argument("--hdc", default="")
320
+
321
+ p = sub.add_parser("norm", help="离线标准化既有 raw dump")
322
+ p.add_argument("raw")
323
+ p.add_argument("out", nargs="?")
324
+ p.add_argument("--keep-all", action="store_true")
325
+
326
+ p = sub.add_parser("query", help="选择器查询标准形")
327
+ p.add_argument("norm_file")
328
+ p.add_argument("--type", dest="type_", default="")
329
+ p.add_argument("--text-re", default="")
330
+ p.add_argument("--region", default="", help="x1,y1,x2,y2")
331
+ p.add_argument("--min-h", type=int, default=0)
332
+ p.add_argument("--nth", type=int, default=0)
333
+ p.add_argument("--no-rollup", action="store_true")
334
+ p.add_argument("--fmt", choices=["lines", "json"], default="json")
335
+ p.add_argument("--max-depth", type=int, default=99)
336
+
337
+ p = sub.add_parser("first-visible", help="region 内首个(按 y)匹配节点")
338
+ p.add_argument("norm_file")
339
+ p.add_argument("--type", dest="type_", default="")
340
+ p.add_argument("--text-re", default="")
341
+ p.add_argument("--region", default="")
342
+
343
+ p = sub.add_parser("click", help="按选择器点击(dump→定位→uinput)")
344
+ p.add_argument("--type", dest="type_", default="")
345
+ p.add_argument("--text-re", default="")
346
+ p.add_argument("--region", default="")
347
+ p.add_argument("--settle-s", type=float, default=1.5)
348
+ p.add_argument("--dump-after", default="", help="点击后再 dump 落此路径")
349
+ p.add_argument("--hdc", default="")
350
+
351
+ a = ap.parse_args()
352
+ if a.cmd == "dump":
353
+ out = write_path = Path(a.out)
354
+ p2 = dump_layout(out, hdc=([a.hdc] if a.hdc else None), settle_s=a.settle_s)
355
+ sz = p2.stat().st_size
356
+ print(f"norm: {p2}({json.loads(p2.read_text(encoding='utf-8'))['head']['nodes']} 节点,{sz} B)")
357
+ print(f"raw: {out.with_name(out.stem + '.raw.json')}")
358
+ elif a.cmd == "norm":
359
+ raw = json.loads(Path(a.raw).read_text(encoding="utf-8", errors="replace"))
360
+ norm = normalize(raw, keep_all=a.keep_all)
361
+ if a.out:
362
+ p2 = write_norm(norm, Path(a.out))
363
+ print(f"norm: {p2}({norm['head']['nodes']} 节点,{p2.stat().st_size} B;"
364
+ f"raw {Path(a.raw).stat().st_size} B)")
365
+ else:
366
+ print(json.dumps(norm, ensure_ascii=False, indent=1)[:4000])
367
+ elif a.cmd in ("query", "first-visible"):
368
+ norm = load(a.norm_file)
369
+ sel = {"type": a.type_, "text_re": a.text_re}
370
+ if a.region:
371
+ sel["region"] = [int(v) for v in a.region.split(",")]
372
+ nodes = query_nodes(norm, sel)
373
+ fmt = getattr(a, "fmt", "json")
374
+ if a.cmd == "first-visible":
375
+ nodes = nodes[:1]
376
+ elif fmt == "json":
377
+ nodes = nodes[max(0, a.nth):max(0, a.nth) + 1]
378
+ if fmt == "lines":
379
+ print("\n".join(f"{n.get('t')} {node_text(n)!r} b={n.get('b')}" for n in nodes))
380
+ else:
381
+ print(json.dumps(nodes, ensure_ascii=False))
382
+ elif a.cmd == "click":
383
+ sel = {"type": a.type_, "text_re": a.text_re}
384
+ if a.region:
385
+ sel["region"] = [int(v) for v in a.region.split(",")]
386
+ r = resolve_and_click(sel, hdc=([a.hdc] if a.hdc else None), settle_s=a.settle_s)
387
+ if r["ok"] and a.dump_after:
388
+ p2 = dump_layout(Path(a.dump_after), hdc=([a.hdc] if a.hdc else None), settle_s=0)
389
+ print(f"after: {p2}")
390
+ print(json.dumps(r, ensure_ascii=False))
391
+ return 0 if r["ok"] else 1
392
+ return 0
393
+
394
+
395
+ if __name__ == "__main__":
396
+ sys.exit(main())