@harmonyos-arkts/d2h 0.1.35 → 0.1.37

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 (84) hide show
  1. package/.agents/plugins/marketplace.json +22 -0
  2. package/.claude-plugin/marketplace.json +21 -6
  3. package/.claude-plugin/plugin.json +9 -3
  4. package/.codex-plugin/plugin.json +37 -0
  5. package/README.md +1 -1
  6. package/agents/android-to-hmos-00-orchestrator.md +1 -1
  7. package/agents/d2h.md +13 -10
  8. package/assets/agc-apiclient.json +10 -0
  9. package/dist/bin/install-opencode.js +6 -1
  10. package/dist/src/metrics-plugin.js +36 -1
  11. package/docs/environment-check.md +2 -2
  12. package/package.json +4 -1
  13. package/schemas/migration-report-index.schema.json +6 -0
  14. package/skills/d2h-app-solution/SKILL.md +25 -6
  15. package/skills/d2h-app-solution/agents/openai.yaml +2 -2
  16. package/skills/d2h-app-solution/scripts/export_inventory_xlsx.py +377 -0
  17. package/skills/d2h-cloud-knowledge/SKILL.md +172 -58
  18. package/skills/d2h-cloud-knowledge/build-index.mjs +238 -0
  19. package/skills/d2h-cloud-knowledge/scenario-audit.mjs +212 -0
  20. package/skills/d2h-cloud-knowledge/scenario-map.json +72 -0
  21. package/skills/d2h-dashboard/SKILL.md +26 -1
  22. package/skills/d2h-dashboard/app/assets/Analysis-BT2XmI3C.js +1 -0
  23. package/skills/d2h-dashboard/app/assets/CodeAudit-BuyDgDM3.js +1 -0
  24. package/skills/d2h-dashboard/app/assets/CodeAudit-hkE0DSw-.css +1 -0
  25. package/skills/d2h-dashboard/app/assets/FeaturesList-C38X4yvD.js +1 -0
  26. package/skills/d2h-dashboard/app/assets/FeaturesList-DQldjxuT.css +1 -0
  27. package/skills/d2h-dashboard/app/assets/Overview-DcJSNtDr.js +1 -0
  28. package/skills/d2h-dashboard/app/assets/Overview-DfJtZ2zJ.css +1 -0
  29. package/skills/d2h-dashboard/app/assets/Project-CssSwlh6.js +1 -0
  30. package/skills/d2h-dashboard/app/assets/SpecDetail--ohkiDwo.css +1 -0
  31. package/skills/d2h-dashboard/app/assets/SpecDetail-DcAYGyNb.js +1 -0
  32. package/skills/d2h-dashboard/app/assets/SpecItemDetail-CJ-vmNJm.css +1 -0
  33. package/skills/d2h-dashboard/app/assets/{SpecItemDetail-BDl_Qqfx.js → SpecItemDetail-DTViQrsC.js} +9 -9
  34. package/skills/d2h-dashboard/app/assets/{index-CnjP19Vs.css → index-DmIexyDt.css} +1 -1
  35. package/skills/d2h-dashboard/app/assets/index-UvzKcmSu.js +3 -0
  36. package/skills/d2h-dashboard/app/assets/{navigation-BGPexEv8.js → navigation-CuZGAjCp.js} +1 -1
  37. package/skills/d2h-dashboard/app/dashboard.standalone.html +88 -0
  38. package/skills/d2h-dashboard/app/dataApi.mjs +133 -31
  39. package/skills/d2h-dashboard/app/index.html +2 -2
  40. package/skills/d2h-dashboard/app/serve.mjs +75 -1
  41. package/skills/d2h-dashboard/lib/data-subscription.mjs +106 -0
  42. package/skills/d2h-dashboard/lib/stage-timing.mjs +18 -0
  43. package/skills/d2h-hypium-forge/SKILL.md +0 -2
  44. package/skills/d2h-spec-develop/SKILL.md +1 -4
  45. package/skills/d2h-spec-generate/SKILL.md +1 -1
  46. package/skills/language/h5/d2h-webview-analyse/SKILL.md +309 -0
  47. package/skills/language/h5/d2h-webview-analyse/scripts/analyse_android_webview.py +3625 -0
  48. package/skills/language/h5/d2h-webview-jsbridge/SKILL.md +140 -0
  49. package/skills/language/h5/d2h-webview-jsbridge/references/adaptation.md +235 -0
  50. package/skills/language/h5/d2h-webview-jsbridge/references/containers-and-triage.md +30 -0
  51. package/skills/language/h5/d2h-webview-jsbridge/references/detection-rules.md +69 -0
  52. package/skills/language/h5/d2h-webview-jsbridge/references/report-system.md +69 -0
  53. package/skills/language/h5/d2h-webview-jsbridge/scripts/scan_web_jsbridge.py +2080 -0
  54. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/dsbridge-app/app/build.gradle +3 -0
  55. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/dsbridge-app/app/src/main/assets/dsbridge.js +6 -0
  56. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/dsbridge-app/app/src/main/java/demo/DsActivity.java +19 -0
  57. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/empty-app/app/src/main/kotlin/demo/Screen.kt +5 -0
  58. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/java-app/app/build.gradle +3 -0
  59. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/java-app/app/src/main/assets/www/WebViewJavascriptBridge.js +6 -0
  60. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/java-app/app/src/main/assets/www/index.html +6 -0
  61. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/java-app/app/src/main/java/demo/WebActivity.java +79 -0
  62. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/kotlin-app/app/src/main/assets/WebViewJavascriptBridge.js +4 -0
  63. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/kotlin-app/app/src/main/assets/page.html +2 -0
  64. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/kotlin-app/app/src/main/kotlin/demo/Bridge.kt +23 -0
  65. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/kotlin-app/app/src/main/kotlin/demo/WVJBWebView.kt +27 -0
  66. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/xml-app/app/src/main/java/demo/MainActivity.java +8 -0
  67. package/skills/language/h5/d2h-webview-jsbridge/tests/fixtures/xml-app/app/src/main/res/layout/main.xml +9 -0
  68. package/skills/language/h5/d2h-webview-jsbridge/tests/run_tests.py +237 -0
  69. package/skills/managing-d2h-toolchain/environment-requirements.json +2 -2
  70. package/skills/managing-d2h-toolchain/toolchain.json +2 -2
  71. package/skills/preparing-migration-workspace/SKILL.md +4 -3
  72. package/skills/d2h-dashboard/app/assets/Analysis-S3iFh2nP.js +0 -1
  73. package/skills/d2h-dashboard/app/assets/CodeAudit-BI5iNy2f.css +0 -1
  74. package/skills/d2h-dashboard/app/assets/CodeAudit-BeZMoO_s.js +0 -1
  75. package/skills/d2h-dashboard/app/assets/FeaturesList-CZ40orVY.css +0 -1
  76. package/skills/d2h-dashboard/app/assets/FeaturesList-CdKAoNw5.js +0 -1
  77. package/skills/d2h-dashboard/app/assets/Overview-C43KVHdP.js +0 -1
  78. package/skills/d2h-dashboard/app/assets/Overview-CzysQJHh.css +0 -1
  79. package/skills/d2h-dashboard/app/assets/Project-D5loWYjZ.js +0 -1
  80. package/skills/d2h-dashboard/app/assets/SpecDetail-BHB6smtT.css +0 -1
  81. package/skills/d2h-dashboard/app/assets/SpecDetail-XCDyawZ3.js +0 -1
  82. package/skills/d2h-dashboard/app/assets/SpecItemDetail-Bf4pGDEN.css +0 -1
  83. package/skills/d2h-dashboard/app/assets/datetime-DBOJn2GA.js +0 -1
  84. package/skills/d2h-dashboard/app/assets/index-C1bO3C02.js +0 -3
@@ -11,19 +11,102 @@ const MIME = {
11
11
 
12
12
  /** 会话聚合虚拟文件(前端固定订阅路径) */
13
13
  const SESSIONS_KEY = '.harmonybot/_summary.json'
14
+ const PROGRESS_KEY = 'progress.json'
15
+ const BATCH_REPORT_KEY = 'page-specs/batch_report.json'
16
+ const LIVE_PROGRESS_KEYS = [PROGRESS_KEY, BATCH_REPORT_KEY]
14
17
 
15
- /** 自动探测会话目录:数据目录自身、工程根、工程父级下的 .harmonybot */
18
+ function fileStamp(stat) {
19
+ return {
20
+ mtimeMs: stat.mtimeMs,
21
+ size: stat.size,
22
+ revision: `${stat.ino}:${stat.ctimeMs}:${stat.mtimeMs}:${stat.size}`,
23
+ }
24
+ }
25
+
26
+ function timestamp(value) {
27
+ return typeof value === 'string' ? Date.parse(value) || 0 : 0
28
+ }
29
+
30
+ function projectProgress(body, readReport) {
31
+ try {
32
+ const progress = JSON.parse(body)
33
+ const stage = progress?.stages?.find(stage => stage.id === 'code-conversion')
34
+ if (stage?.status !== 'pending' || !progress.summary) return body
35
+ const report = readReport()
36
+ if (!Array.isArray(report?.tasks)) return body
37
+
38
+ let selected
39
+ if (report.planning != null) {
40
+ if (report.planning.phase !== 'bound' || !Array.isArray(report.planning.waves)) return body
41
+ selected = new Set(report.planning.waves.flatMap(wave => wave.task_ids ?? []))
42
+ }
43
+ const statuses = new Set(['in_progress', 'implemented', 'completed', 'blocked', 'failed'])
44
+ const resetTime = stage.lastUpdatedAt === progress.createdAt ? 0 : timestamp(stage.lastUpdatedAt)
45
+ let started = false
46
+ let firstStart = Infinity
47
+ let lastActivity = 0
48
+ for (const task of report.tasks) {
49
+ if (!statuses.has(task?.development) || (selected && !selected.has(task.task_id))) continue
50
+ const start = timestamp(task.started_at)
51
+ const activity = Math.max(start, timestamp(task.updated_at), timestamp(task.ended_at))
52
+ if (resetTime && activity <= resetTime) continue
53
+ started = true
54
+ if (start) firstStart = Math.min(firstStart, start)
55
+ lastActivity = Math.max(lastActivity, activity)
56
+ }
57
+ if (!started) return body
58
+
59
+ stage.status = 'in_progress'
60
+ stage.startedAt ??= Number.isFinite(firstStart) ? new Date(firstStart).toISOString() : null
61
+ if (lastActivity > timestamp(stage.lastUpdatedAt)) stage.lastUpdatedAt = new Date(lastActivity).toISOString()
62
+ if (lastActivity > timestamp(progress.updatedAt)) progress.updatedAt = new Date(lastActivity).toISOString()
63
+ progress.summary.pending--
64
+ progress.summary.inProgress++
65
+ progress.summary.currentStage = progress.stages.find(stage => ['in_progress', 'blocked'].includes(stage.status)).id
66
+ return JSON.stringify(progress)
67
+ } catch {
68
+ // 账本缺失、正在写入或旧格式时仍可读取原始阶段文件。
69
+ return body
70
+ }
71
+ }
72
+
73
+ /**
74
+ * 自动探测会话目录:自数据目录向上最多 5 层。
75
+ * 近层(depth ≤ 2,即数据目录/工程根/工作目录层):查自身 + 直接子目录下的 .harmonybot;
76
+ * 外层(depth ≥ 3,多工程共居层):仅查自身,避免把兄弟工程的会话误聚合进来。最近命中优先。
77
+ */
16
78
  function detectSessionDir(root) {
17
- for (const cand of [
18
- path.join(root, '.harmonybot'),
19
- path.join(root, '..', '.harmonybot'),
20
- path.join(root, '..', '..', '.harmonybot'),
21
- ]) {
79
+ const tryDir = (dir) => {
22
80
  try {
23
- if (fs.statSync(cand).isDirectory()) return path.resolve(cand)
81
+ if (fs.statSync(dir).isDirectory()) return path.resolve(dir)
24
82
  } catch {
25
- // 不存在,继续探测
83
+ // 不存在
26
84
  }
85
+ return null
86
+ }
87
+ let cur = root
88
+ for (let depth = 0; depth < 5; depth++) {
89
+ // ① 该层自身
90
+ const self = tryDir(path.join(cur, '.harmonybot'))
91
+ if (self) return self
92
+ // ② 近层才扫直接子目录(字母序取第一个命中)
93
+ if (depth < 3) {
94
+ try {
95
+ const children = fs
96
+ .readdirSync(cur, { withFileTypes: true })
97
+ .filter((e) => e.isDirectory())
98
+ .sort((a, b) => a.name.localeCompare(b.name))
99
+ for (const child of children) {
100
+ const hit = tryDir(path.join(cur, child.name, '.harmonybot'))
101
+ if (hit) return hit
102
+ }
103
+ } catch {
104
+ // 目录不可读,继续向上
105
+ }
106
+ }
107
+ const parent = path.dirname(cur)
108
+ if (parent === cur) break // 到达文件系统根
109
+ cur = parent
27
110
  }
28
111
  return null
29
112
  }
@@ -111,10 +194,7 @@ export function createDataApi(dataDir, options = {}) {
111
194
  } else if (entry.isFile() && ALLOWED_EXT.has(path.extname(entry.name).toLowerCase())) {
112
195
  try {
113
196
  const stat = fs.statSync(abs)
114
- out[path.relative(root, abs).split(path.sep).join('/')] = {
115
- mtimeMs: stat.mtimeMs,
116
- size: stat.size,
117
- }
197
+ out[path.relative(root, abs).split(path.sep).join('/')] = fileStamp(stat)
118
198
  } catch {
119
199
  // 文件在扫描间隙被删除,跳过
120
200
  }
@@ -122,6 +202,9 @@ export function createDataApi(dataDir, options = {}) {
122
202
  }
123
203
  }
124
204
  walk(root)
205
+ if (out[PROGRESS_KEY]) {
206
+ out[PROGRESS_KEY].revision += `|${out[BATCH_REPORT_KEY]?.revision ?? ''}`
207
+ }
125
208
  const sessions = sessionsSummary()
126
209
  if (sessions) out[SESSIONS_KEY] = sessions.stamp
127
210
  return out
@@ -310,7 +393,10 @@ export function createDataApi(dataDir, options = {}) {
310
393
  return true
311
394
  }
312
395
  try {
313
- const data = fs.readFileSync(abs)
396
+ let data = fs.readFileSync(abs)
397
+ if (p === PROGRESS_KEY) {
398
+ data = projectProgress(data, () => JSON.parse(fs.readFileSync(path.join(root, BATCH_REPORT_KEY), 'utf8')))
399
+ }
314
400
  res.statusCode = 200
315
401
  res.setHeader('Content-Type', MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream')
316
402
  res.setHeader('Cache-Control', 'no-store')
@@ -330,9 +416,8 @@ export function createDataApi(dataDir, options = {}) {
330
416
  }
331
417
 
332
418
  /**
333
- * 监听数据目录(含会话目录)内白名单文件变化,debounce 300ms 后回调变化的相对路径列表。
419
+ * 聚合 150ms 内的文件变化;阶段和任务账本独立轮询,兼容原子替换和 watch 失败。
334
420
  * 会话目录变化统一映射为 .harmonybot/_summary.json。
335
- * 平台不支持 recursive watch 时返回 null(调用方退化为轮询)。
336
421
  */
337
422
  const watch = (onChange) => {
338
423
  const changed = new Set()
@@ -340,18 +425,37 @@ export function createDataApi(dataDir, options = {}) {
340
425
  const watchers = []
341
426
  const dirs = sessionDir ? [root, sessionDir] : [root]
342
427
 
343
- const flush = () => {
344
- if (timer) clearTimeout(timer)
428
+ const enqueue = key => {
429
+ changed.add(key)
430
+ if (key === BATCH_REPORT_KEY) changed.add(PROGRESS_KEY)
431
+ if (timer) return
345
432
  timer = setTimeout(() => {
346
433
  const files = Array.from(changed)
347
434
  changed.clear()
348
435
  timer = null
349
- if (files.length) onChange(files)
350
- }, 300)
436
+ onChange(files)
437
+ }, 150)
351
438
  }
352
439
 
353
- try {
354
- for (const dir of dirs) {
440
+ const revision = key => {
441
+ try {
442
+ return fileStamp(fs.statSync(path.join(root, key))).revision
443
+ } catch {
444
+ return null
445
+ }
446
+ }
447
+ const liveRevisions = new Map(LIVE_PROGRESS_KEYS.map(key => [key, revision(key)]))
448
+ const poll = setInterval(() => {
449
+ for (const [key, previous] of liveRevisions) {
450
+ const next = revision(key)
451
+ if (next === previous) continue
452
+ liveRevisions.set(key, next)
453
+ enqueue(key)
454
+ }
455
+ }, 500)
456
+
457
+ for (const dir of dirs) {
458
+ try {
355
459
  const watcher = fs.watch(dir, { recursive: true }, (_event, filename) => {
356
460
  if (!filename) return
357
461
  const abs = path.isAbsolute(filename) ? filename : path.join(dir, filename)
@@ -359,25 +463,23 @@ export function createDataApi(dataDir, options = {}) {
359
463
  if (dir === sessionDir) {
360
464
  // 会话目录:任何 ses_*.json 变化都触发聚合文件更新
361
465
  if (!/^ses_.*\.json$/.test(path.basename(abs))) return
362
- changed.add(SESSIONS_KEY)
466
+ enqueue(SESSIONS_KEY)
363
467
  } else {
364
468
  const rel = path.relative(root, abs).split(path.sep).join('/')
365
- if (!ALLOWED_EXT.has(path.extname(rel).toLowerCase())) return
366
- changed.add(rel)
469
+ if (LIVE_PROGRESS_KEYS.includes(rel) || !ALLOWED_EXT.has(path.extname(rel).toLowerCase())) return
470
+ enqueue(rel)
367
471
  }
368
- flush()
369
- })
370
- watcher.on('close', () => {
371
- if (timer) clearTimeout(timer)
372
472
  })
473
+ watcher.on('error', () => watcher.close())
373
474
  watchers.push(watcher)
475
+ } catch {
476
+ // 其他文件仍由客户端轮询,阶段和账本仍可走 SSE。
374
477
  }
375
- } catch {
376
- for (const w of watchers) w.close()
377
- return null
378
478
  }
379
479
  return {
380
480
  close() {
481
+ clearInterval(poll)
482
+ clearTimeout(timer)
381
483
  for (const w of watchers) w.close()
382
484
  },
383
485
  }
@@ -4,9 +4,9 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>conversiondashboard</title>
7
- <script type="module" crossorigin src="/assets/index-C1bO3C02.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-UvzKcmSu.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="/assets/_plugin-vue_export-helper-B9l48Cov.js">
9
- <link rel="stylesheet" crossorigin href="/assets/index-CnjP19Vs.css">
9
+ <link rel="stylesheet" crossorigin href="/assets/index-DmIexyDt.css">
10
10
  </head>
11
11
  <body>
12
12
  <div id="app"></div>
@@ -2,9 +2,13 @@
2
2
  // 独立迁移看板服务器(零依赖,Node >= 18):
3
3
  // node server/serve.mjs --dataDir <project>/.migration [--port 8080] [--host 127.0.0.1] [--dir ../web]
4
4
  // node server/serve.mjs --dataDir <project>/.migration --detach [--log-file <path>]
5
+ // node server/serve.mjs --dataDir <project>/.migration --export-snapshot [--out <path>]
5
6
  // --detach:自守护启动——父进程 spawn 分离子进程(stdout/stderr 直写日志文件),
6
7
  // 轮询日志直到子进程就绪后原样打印 stdout 契约并退出;调用方无需 shell 重定向/引号转义。
7
8
  // 默认日志 %TEMP%/d2h-dashboard-<dataDir哈希8位>.log(每次启动截断重写,跨项目天然隔离)。
9
+ // --export-snapshot:枚举数据目录白名单文件(.json/.jsonl/.md,含会话汇总虚拟文件),
10
+ // 注入 dashboard.standalone.html 模板,写出单文件离线快照(默认 <dataDir>/dashboard.html)。
11
+ // 拷走整个 .migration 后双击该 HTML 即可离线查看当时进展;运行期服务器仍只读。
8
12
  // stdout 契约(供 skill 解析):
9
13
  // [dashboard] dataDir=<绝对路径>
10
14
  // [dashboard] http://<host>:<实际端口>
@@ -44,6 +48,76 @@ if (!fs.existsSync(dataDir)) {
44
48
  process.exit(1)
45
49
  }
46
50
 
51
+ // ---- --export-snapshot:枚举数据目录白名单文件 → 注入 standalone 模板 → 写出单文件离线快照 ----
52
+ // 运行期服务器保持只读;本命令是唯一显式写出:默认产出 <dataDir>/dashboard.html(可 --out 覆盖)。
53
+ if (process.argv.includes('--export-snapshot')) {
54
+ const root = path.resolve(dataDir)
55
+ const outPath = path.resolve(argValue('out') ?? path.join(root, 'dashboard.html'))
56
+ const templatePath = [
57
+ path.resolve(__dirname, 'dashboard.standalone.html'), // 内嵌 skill 布局:与 serve.mjs 同目录(app/)
58
+ path.resolve(__dirname, '..', 'dashboard.standalone.html'), // npm 包布局:包根
59
+ ].find((p) => fs.existsSync(p))
60
+ if (!templatePath) {
61
+ console.error('[dashboard] 缺少 dashboard.standalone.html 模板(包应含该文件;源码运行请先 npm run build)')
62
+ process.exit(1)
63
+ }
64
+ const exportApi = createDataApi(dataDir, {})
65
+ const stamps = exportApi.listFiles()
66
+ const files = {}
67
+ const skipped = []
68
+ const readVirtual = (rel) => new Promise((resolve) => {
69
+ const res = {
70
+ statusCode: 0,
71
+ chunks: [],
72
+ setHeader() {},
73
+ end(chunk) {
74
+ if (chunk) this.chunks.push(chunk)
75
+ resolve(this.statusCode === 200 ? this.chunks.join('') : null)
76
+ },
77
+ }
78
+ exportApi.handle({ url: `/api/data/file?p=${encodeURIComponent(rel)}` }, res)
79
+ })
80
+ for (const rel of Object.keys(stamps)) {
81
+ try {
82
+ let text = null
83
+ if (rel === '.harmonybot/_summary.json') {
84
+ text = await readVirtual(rel)
85
+ } else {
86
+ text = fs.readFileSync(path.resolve(root, rel), 'utf8')
87
+ }
88
+ if (text === null) { skipped.push(rel); continue }
89
+ files[rel] = { text, mtimeMs: stamps[rel].mtimeMs, size: stamps[rel].size }
90
+ } catch {
91
+ skipped.push(rel)
92
+ }
93
+ }
94
+ const payload = { generatedAt: new Date().toISOString(), root, files }
95
+ let payloadJson = JSON.stringify(payload)
96
+ for (const [source, escaped] of [['&', '\\u0026'], ['<', '\\u003c'], ['>', '\\u003e'], ['\u2028', '\\u2028'], ['\u2029', '\\u2029']]) {
97
+ payloadJson = payloadJson.split(source).join(escaped)
98
+ }
99
+ const template = fs.readFileSync(templatePath, 'utf8')
100
+ const marker = '/*__D2H_SNAPSHOT__*/null'
101
+ if (template.split(marker).length !== 2) {
102
+ console.error('[dashboard] 模板注入点异常(应恰好 1 处)')
103
+ process.exit(1)
104
+ }
105
+ const html = template.replace(marker, payloadJson)
106
+ fs.mkdirSync(path.dirname(outPath), { recursive: true })
107
+ const temp = `${outPath}.tmp-${process.pid}`
108
+ fs.writeFileSync(temp, html)
109
+ fs.renameSync(temp, outPath)
110
+ console.log(JSON.stringify({
111
+ ok: true,
112
+ out: outPath,
113
+ template: templatePath,
114
+ files: Object.keys(files).length,
115
+ skipped,
116
+ bytes: Buffer.byteLength(html),
117
+ }, null, 2))
118
+ process.exit(0)
119
+ }
120
+
47
121
  // ---- --detach:spawn 分离子进程并等待就绪,然后父进程退出 ----
48
122
  const isDetach = process.argv.includes('--detach')
49
123
  if (isDetach) {
@@ -213,7 +287,7 @@ const server = http.createServer((req, res) => {
213
287
  })
214
288
  res.write(': connected\n\n')
215
289
  sseClients.add(res)
216
- req.on('close', () => sseClients.delete(res))
290
+ res.on('close', () => sseClients.delete(res))
217
291
  return
218
292
  }
219
293
 
@@ -0,0 +1,106 @@
1
+ const apiRoot = '/api/data'
2
+ const liveFiles = new Set(['progress.json', 'page-specs/batch_report.json'])
3
+ const subscriptions = new Set()
4
+ let eventSource
5
+ let pendingManifest
6
+
7
+ function connect() {
8
+ if (eventSource || typeof EventSource === 'undefined') return
9
+ eventSource = new EventSource(`${apiRoot}/events`)
10
+ eventSource.onopen = () => {
11
+ for (const subscription of subscriptions) subscription.refresh()
12
+ }
13
+ eventSource.onmessage = event => {
14
+ let files
15
+ try {
16
+ ({ files } = JSON.parse(event.data))
17
+ } catch {
18
+ return
19
+ }
20
+ if (!Array.isArray(files)) return
21
+ for (const subscription of subscriptions) {
22
+ if (files.includes(subscription.path)) subscription.refresh()
23
+ }
24
+ }
25
+ }
26
+
27
+ function loadManifest() {
28
+ pendingManifest ??= (async () => {
29
+ const response = await fetch(`${apiRoot}/manifest`, {
30
+ cache: 'no-store',
31
+ signal: AbortSignal.timeout(5_000),
32
+ })
33
+ if (!response.ok) throw new Error(`读取 manifest 失败 (HTTP ${response.status})`)
34
+ return response.json()
35
+ })().finally(() => { pendingManifest = undefined })
36
+ return pendingManifest
37
+ }
38
+
39
+ function parseJsonLines(text) {
40
+ const rows = []
41
+ for (const line of text.split(/\r?\n/)) {
42
+ try { rows.push(JSON.parse(line)) } catch { /* 跳过空行或未写完的记录 */ }
43
+ }
44
+ return rows
45
+ }
46
+
47
+ export function subscribeToJson(path, onData, options = {}) {
48
+ const { pollMs = liveFiles.has(path) ? 2_000 : 10_000, immediate = true } = options
49
+ let revision
50
+ let loading = false
51
+ let refreshAgain = false
52
+ let closed = false
53
+
54
+ const refresh = async () => {
55
+ if (closed) return
56
+ if (loading) {
57
+ refreshAgain = true
58
+ return
59
+ }
60
+ loading = true
61
+ try {
62
+ const stamp = (await loadManifest()).files[path]
63
+ if (closed) return
64
+ if (!stamp) {
65
+ revision = undefined
66
+ return
67
+ }
68
+ const next = stamp.revision ?? `${stamp.mtimeMs}:${stamp.size}`
69
+ if (next === revision) return
70
+ const response = await fetch(`${apiRoot}/file?p=${encodeURIComponent(path)}`, {
71
+ cache: 'no-store',
72
+ signal: AbortSignal.timeout(5_000),
73
+ })
74
+ if (!response.ok) throw new Error(`读取失败 (HTTP ${response.status})`)
75
+ const payload = path.toLowerCase().endsWith('.jsonl')
76
+ ? parseJsonLines(await response.text())
77
+ : await response.json()
78
+ if (closed) return
79
+ await onData(payload, { relPath: path, fetchedAt: Date.now(), mtimeMs: stamp.mtimeMs })
80
+ revision = next
81
+ } catch (error) {
82
+ if (!closed) console.warn(`读取 ${path} 失败`, error)
83
+ } finally {
84
+ loading = false
85
+ if (refreshAgain) {
86
+ refreshAgain = false
87
+ void refresh()
88
+ }
89
+ }
90
+ }
91
+
92
+ const subscription = { path, refresh }
93
+ subscriptions.add(subscription)
94
+ connect()
95
+ if (immediate) void refresh()
96
+ const timer = setInterval(refresh, pollMs)
97
+ return () => {
98
+ closed = true
99
+ clearInterval(timer)
100
+ subscriptions.delete(subscription)
101
+ if (!subscriptions.size && eventSource) {
102
+ eventSource.close()
103
+ eventSource = undefined
104
+ }
105
+ }
106
+ }
@@ -0,0 +1,18 @@
1
+ export function formatStageTiming(stage, formatDate, formatDuration) {
2
+ const started = Date.parse(stage.startedAt)
3
+ const ended = Date.parse(stage.endedAt)
4
+ const hasEnd = Number.isFinite(ended)
5
+ const elapsed = ended - started
6
+
7
+ // progress update completed 会为没有开始记录的旧阶段写入相同的起止时间。
8
+ const hasStart = Number.isFinite(started) && (!hasEnd || elapsed > 0)
9
+ const start = hasStart
10
+ ? `开始 ${formatDate(stage.startedAt)}`
11
+ : stage.status === 'pending' ? '未开始' : '开始时间未记录'
12
+ if (!hasEnd) return { start, end: '' }
13
+
14
+ const finished = `完成 ${formatDate(stage.endedAt)}`
15
+ if (!hasStart) return { start, end: `${finished} · 用时未记录` }
16
+ const duration = elapsed < 1000 ? '用时不足 1 秒' : `用时 ${formatDuration(elapsed)}`
17
+ return { start, end: `${finished} · ${duration}` }
18
+ }
@@ -209,8 +209,6 @@ python3 $F/forge_report.py # 产出 test-report.html(Allure 风格:概况
209
209
  ```
210
210
  铁律:修 1 个用例 ≠ 重跑 24 个。run_direct 汇总后 FAIL>0 会直接打印下一步命令——照抄执行。
211
211
 
212
- **调用契约(Windows 管道悬挂防护)**:run_direct/probe 与 `droid2hmos test harmony` 派生的 hdc 常驻服务持有会话输出管道——CLI 已打印结果退出,工具调用却等到自身超时(结果其实已成功)。Windows 下命令末尾一律追加 `; $rc=$LASTEXITCODE; hdc kill; exit $rc`(杀掉持有者即返回,保留退出码;PowerShell 原生 `>` 重定向无效);hdc 不在 PATH 或仍悬挂时用 `cmd /c "… > <log> 2>&1"` 兜底。工具调用超时须大于 runner/CLI 总超时;`timedOut` ≠ 失败——先读落盘 `results.json`/报告定性,仅在证明本次未跑或失败时才重跑(盲目重跑会重复安装 HAP、重复设备测试)。
213
-
214
212
  **范围回归(touched,产品代码变更后的默认门禁策略)**:
215
213
  `--retry-failed` 检测到产品代码变更时不再一律全量——按 `results.meta.json` 的**逐文件指纹**
216
214
  diff 出改动集,若全部是 ids.json 可定位的 UI 文件,则只重跑 `FAIL/SKIP + 引用这些文件的用例`
@@ -59,7 +59,7 @@ If independent page-worker execution is unavailable, return that the required mo
59
59
 
60
60
  - Confirm the task is the earliest incomplete eligible task in ledger planning (or legacy task order when allowed) and no other page is being implemented or awaiting parent acceptance.
61
61
  - Compare the checkout with the dispatch baseline. Preserve and avoid unrelated dirty files; if ownership conflicts with a build-affecting file, return the exact conflict instead of overwriting it.
62
- - Mark only the selected task `in_progress` in `batch_report.json`.
62
+ - Before implementation, mark only the selected task `in_progress` in `batch_report.json`. Record its start and update times and update the batch summary in the same atomic write so the dashboard sees the claim immediately.
63
63
  - Read the complete `spec.md`, the referenced `.migration/utg/page.json` node, every cited Fact, and every cited Android source file. Follow handlers, state transitions, repositories, navigation, persistence, error paths, and platform side effects far enough to establish the observable result.
64
64
  - Inspect the HarmonyOS architecture, routes, resources, shared components, tests, and current implementation. Load `arkts-mvvm-architecture` before planning or writing ArkTS.
65
65
  - Build a private checklist mapping every `F-xxx` to reachable code, a stable semantic locator, an appropriate development check, and an observable result. Do not create another planning file.
@@ -78,8 +78,6 @@ If independent page-worker execution is unavailable, return that the required mo
78
78
  ### 3. Managed build
79
79
 
80
80
  - Run a fresh, non-interactive, bounded build through `droid2hmos build harmony <ANDROID_PROJECT>` using the resolved project configuration.
81
- - Bound the invocation: tool-call `timeout` > CLI `--timeout-ms` > per-case watchdog; never rely on the tool default (suggested: build 15 min / `--timeout-ms 780000`, test 20 min / `--timeout-ms 1080000`).
82
- - On Windows the CLI's lingering hdc server holds the session pipes after the CLI exits, hanging the tool call despite a printed result. Invoke `droid2hmos.cmd` (the `.ps1` shim is policy-blocked) with the kill suffix: `droid2hmos.cmd build harmony <ANDROID_PROJECT> --timeout-ms 780000; $rc=$LASTEXITCODE; hdc kill; exit $rc`. If hdc is not on PATH or the call still hangs, fall back to `cmd /c "droid2hmos.cmd ... > <evidence>/build.log 2>&1"` and read the file back (PowerShell-native redirection does not help). A tool timeout is not a failure verdict: read the on-disk JSON result/report before re-running.
83
81
  - Save the exact command, exit status, timestamps, relevant log, produced HAP path, and HAP SHA-256 in the task evidence directory.
84
82
  - Fix compilation errors caused or exposed by the implementation within this worker until the build passes.
85
83
  - An older HAP, static analysis result, direct Hvigor run, or previous log is not current build evidence.
@@ -103,7 +101,6 @@ The worker runs necessary focused checks during development; the parent reviews
103
101
  - The parent reviews the implementation and current check evidence; rerun or add focused checks only for a failure, a material evidence gap, or a subsequent code change.
104
102
  - Do not load `d2h-hypium-forge`, generate Python Hypium test assets, or start a separate page test cycle by default. Run device/end-to-end tests only when the user explicitly requests them; then load the applicable testing Skill and use managed test entry points.
105
103
  - Record actual commands, results and evidence in the task evidence directory. A build pass does not prove runtime behavior; unexecuted checks are not passed.
106
- - Apply the same timeout ladder and Windows kill-suffix rule to `droid2hmos test harmony`; treat a tool timeout as unverified and read the on-disk Hypium results before re-running.
107
104
  - Fix failures in the current implementation and repeat the affected checks and managed build as needed before handoff or parent approval.
108
105
 
109
106
  ## Parent report and commits
@@ -76,7 +76,7 @@ Before writing Specs, create pages.json with `schema_version: d2h-page-plan/v1`.
76
76
  3. Use `page.json` navigation steps, selectors, guards, expected-arrival rules, required state, and depth to reconstruct the semantic arrival path. Source-derived reachability is planning evidence, not runtime confirmation.
77
77
  4. Translate selectors into semantic control names only when Facts, resources, or Android source support the mapping. Keep missing or ambiguous selectors explicitly unresolved.
78
78
  5. Verify every listed Android path exists under `android_root`. Verify every HarmonyOS path marked `existing` exists under `harmony_root`; otherwise mark it `planned`.
79
- 6. When page features touch platform capabilities (camera, location, files, notifications, Bluetooth, share, Web, background tasks, etc.) or uncertain HarmonyOS APIs (`@kit.*` Kit imports or `@ohos.*` modules), confirm the corresponding Kit/API availability and system-capability limits before writing: read supplied knowledge evidence and `.migration/knowledge/kb_cache.json` first; on a gap return knowledgeRequests with the capability, source and question to the caller. Cite confirmed doc `title`/`uri` in「未决项与平台差异」or the supporting feature item. Do not assume API availability or load another Skill here.
79
+ 6. When page features touch platform capabilities (camera, location, files, notifications, Bluetooth, share, Web, background tasks, etc.) or uncertain HarmonyOS APIs (`@kit.*` Kit imports or `@ohos.*` modules), confirm the corresponding Kit/API availability and system-capability limits before writing: read supplied knowledge evidence first; on a gap return knowledgeRequests with the capability, source and question to the caller. Cite confirmed doc `title`/`uri` in「未决项与平台差异」or the supporting feature item. Do not assume API availability or load another Skill here.
80
80
 
81
81
  ### 5. Write only `spec.md`
82
82