@harmonyos-arkts/droid2hmos 0.0.0-stage → 0.0.8

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +249 -3
  3. package/config/preflight-checklist.json +65 -0
  4. package/dist/cli.js +8994 -0
  5. package/dist/cli.js.map +1 -0
  6. package/package.json +36 -6
  7. package/templates/ohos/AppScope/app.json5 +10 -0
  8. package/templates/ohos/AppScope/resources/base/element/string.json +8 -0
  9. package/templates/ohos/AppScope/resources/base/media/background.png +0 -0
  10. package/templates/ohos/AppScope/resources/base/media/foreground.png +0 -0
  11. package/templates/ohos/AppScope/resources/base/media/layered_image.json +7 -0
  12. package/templates/ohos/build-profile.json5 +42 -0
  13. package/templates/ohos/code-linter.json5 +32 -0
  14. package/templates/ohos/entry/build-profile.json5 +33 -0
  15. package/templates/ohos/entry/hvigorfile.ts +6 -0
  16. package/templates/ohos/entry/obfuscation-rules.txt +23 -0
  17. package/templates/ohos/entry/oh-package.json5 +10 -0
  18. package/templates/ohos/entry/src/main/ets/entryability/EntryAbility.ets +48 -0
  19. package/templates/ohos/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +16 -0
  20. package/templates/ohos/entry/src/main/ets/pages/Index.ets +23 -0
  21. package/templates/ohos/entry/src/main/module.json5 +50 -0
  22. package/templates/ohos/entry/src/main/resources/base/element/color.json +8 -0
  23. package/templates/ohos/entry/src/main/resources/base/element/float.json +8 -0
  24. package/templates/ohos/entry/src/main/resources/base/element/string.json +16 -0
  25. package/templates/ohos/entry/src/main/resources/base/media/background.png +0 -0
  26. package/templates/ohos/entry/src/main/resources/base/media/foreground.png +0 -0
  27. package/templates/ohos/entry/src/main/resources/base/media/layered_image.json +7 -0
  28. package/templates/ohos/entry/src/main/resources/base/media/startIcon.png +0 -0
  29. package/templates/ohos/entry/src/main/resources/base/profile/backup_config.json +3 -0
  30. package/templates/ohos/entry/src/main/resources/base/profile/main_pages.json +5 -0
  31. package/templates/ohos/entry/src/main/resources/dark/element/color.json +8 -0
  32. package/templates/ohos/entry/src/mock/mock-config.json5 +2 -0
  33. package/templates/ohos/entry/src/ohosTest/ets/test/Ability.test.ets +35 -0
  34. package/templates/ohos/entry/src/ohosTest/ets/test/List.test.ets +5 -0
  35. package/templates/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets +48 -0
  36. package/templates/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets +14 -0
  37. package/templates/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ets +41 -0
  38. package/templates/ohos/entry/src/ohosTest/module.json5 +25 -0
  39. package/templates/ohos/entry/src/ohosTest/resources/base/element/color.json +8 -0
  40. package/templates/ohos/entry/src/ohosTest/resources/base/element/string.json +12 -0
  41. package/templates/ohos/entry/src/ohosTest/resources/base/media/icon.png +0 -0
  42. package/templates/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json +5 -0
  43. package/templates/ohos/entry/src/test/List.test.ets +5 -0
  44. package/templates/ohos/entry/src/test/LocalUnit.test.ets +33 -0
  45. package/templates/ohos/hvigor/hvigor-config.json5 +23 -0
  46. package/templates/ohos/hvigorfile.ts +6 -0
  47. package/templates/ohos/oh-package-lock.json5 +28 -0
  48. package/templates/ohos/oh-package.json5 +10 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts","../src/commands/lib/spawn-command.ts","../src/commands/check-android-build.ts","../src/migration-paths.ts","../src/commands/init-migration-report.ts","../src/commands/source-governance.ts","../src/commands/initialize-spec.ts","../src/commands/lib/ui-spec-graph.ts","../src/commands/lib/spec-shards.ts","../src/commands/render-spec-html.ts","../src/commands/render-migration-report.ts","../src/commands/start-background-service.ts","../src/commands/validate-migration-report.ts","../src/commands/init-hmos-project.ts","../src/commands/android-project-name.ts","../src/commands/sdk-version.ts","../src/commands/run-appgraph.ts","../src/commands/harmony-toolchain.ts","../src/commands/run-config-command.ts","../src/commands/check-hmos-device.ts","../src/commands/hypium-report.ts","../src/commands/device-signature.ts","../src/commands/deveco-cli.ts","../src/commands/python-hypium.ts","../src/commands/detect-harmony-sdk.ts","../src/commands/upgrade.ts","../src/commands/migration-config.ts","../src/commands/preflight.ts","../src/commands/detect-android-ui-stack.ts","../src/commands/git-checkpoint.ts","../src/commands/system-checks.ts","../src/commands/preflight-checklist.ts","../src/commands/deveco-auth-login.ts","../src/commands/device-evidence.ts","../src/commands/report-update.ts","../src/commands/mock-server-generator.ts","../src/commands/logs.ts","../src/logging/command-log.ts","../src/runtime-paths.ts","../src/kernel/migration-kernel.ts","../src/planning/facts/reader.ts","../src/planning/util.ts","../src/planning/types.ts","../src/planning/facts/v2-adapter.ts","../src/planning/facts/index.ts","../src/planning/compiler.ts","../src/planning/execution-context.ts","../src/planning/execution-planner.ts","../src/planning/storage.ts","../src/planning/materialize.ts","../src/planning/runtime.ts","../src/planning/validate.ts","../src/planning/index.ts"],"sourcesContent":["#!/usr/bin/env node\r\nimport path from \"node:path\";\r\nimport { existsSync, readFileSync, realpathSync } from \"node:fs\";\r\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\r\nimport { spawnCommandSync } from \"./commands/lib/spawn-command.ts\";\r\nimport { checkAndroidBuild } from \"./commands/check-android-build.ts\";\r\nimport { initMigrationReport } from \"./commands/init-migration-report.ts\";\r\nimport { initializeSpec } from \"./commands/initialize-spec.ts\";\r\nimport { renderSpecHtml } from \"./commands/render-spec-html.ts\";\r\nimport { renderMigrationReport } from \"./commands/render-migration-report.ts\";\r\nimport { runDetachedHost, startBackgroundService, statusBackgroundService, stopBackgroundService } from \"./commands/start-background-service.ts\";\r\nimport { validateMigrationReport } from \"./commands/validate-migration-report.ts\";\r\nimport { initHmosProject } from \"./commands/init-hmos-project.ts\";\r\nimport { runAppGraph } from \"./commands/run-appgraph.ts\";\r\nimport { runHarmonyBuild, runHarmonyTest } from \"./commands/harmony-toolchain.ts\";\r\nimport { runHarmonyPythonHypiumTest } from \"./commands/python-hypium.ts\";\r\nimport { detectHarmonySdk } from \"./commands/detect-harmony-sdk.ts\";\r\nimport { readPackageMetadata, upgradeCli } from \"./commands/upgrade.ts\";\r\nimport { initMigrationConfig, validateMigrationConfig } from \"./commands/migration-config.ts\";\r\nimport { runPreflight } from \"./commands/preflight.ts\";\r\nimport { ensureDeviceSignature, signNewHarmonyProject } from \"./commands/device-signature.ts\";\r\nimport { managedDevEcoCliLogin, runDetachedDevEcoAuthHost } from \"./commands/deveco-auth-login.ts\";\r\nimport { defaultHarmonyProjectPath } from \"./commands/android-project-name.ts\";\r\nimport { gitWorkspaceStatus, createGitCheckpoint } from \"./commands/git-checkpoint.ts\";\r\nimport { checkHarmonyDevice } from \"./commands/check-hmos-device.ts\";\r\nimport { captureDeviceEvidence, compareEvidence, writeFlowBundle } from \"./commands/device-evidence.ts\";\r\nimport { updateReportItem } from \"./commands/report-update.ts\";\r\nimport { managedSourceManifest, sourceRoots } from \"./commands/source-governance.ts\";\r\nimport { generateMockServer } from \"./commands/mock-server-generator.ts\";\r\nimport { queryCommandLogs } from \"./commands/logs.ts\";\r\nimport { withCommandLog } from \"./logging/command-log.ts\";\r\nimport { resolveRuntimePaths, type RuntimePaths } from \"./runtime-paths.ts\";\r\nimport { guardMigrationAction, inspectMigration, recordObservation, type GuardResult } from \"./kernel/migration-kernel.ts\";\r\nimport { migrationDirectory } from \"./migration-paths.ts\";\r\nimport { taskPlanning } from \"./planning/index.ts\";\r\n\r\nconst HELP = `droid2hmos - Android to HarmonyOS migration tools\r\n\r\nUsage:\r\n droid2hmos init [project] [--target <harmony-project>]\r\n droid2hmos status [project]\r\n droid2hmos complete [project]\r\n droid2hmos analyze <android|harmony|all> [project]\r\n droid2hmos preflight [project] [--sdk-path <path>] [--timeout-ms <ms>] [--no-init-harmony]\r\n droid2hmos config <init|validate> [project] [--harmony-project <path>]\r\n droid2hmos build harmony [project] [--timeout-ms <ms>]\r\n droid2hmos test harmony [project] [--runner arkts] (--class <class> [--case <case>] | --all) [--target <serial>] [--case-timeout-ms <ms>] [--ref <report-ref>...] [--timeout-ms <ms>]\r\n droid2hmos test harmony [project] --runner python --hypium-project <path> --test-list <name>... [--target <serial>] [--python <path>] [--report-path <path>] [--ref <report-ref>...] [--timeout-ms <ms>]\r\n droid2hmos report [project] [--require-complete]\r\n droid2hmos report <init|validate|render> [project] [--require-complete]\r\n droid2hmos report update [project] --ref <ref> [--status <status>] [--harmony-file <path>...] [--android-source <path>...] [--evidence <path>...] [--difference <text>|--clear-difference]\r\n droid2hmos task plan [project]\r\n droid2hmos task status [project]\r\n droid2hmos task next [project]\r\n droid2hmos task show [project] <task-or-package-id> [--cursor <cursor>] [--max-source-context <count>]\r\n droid2hmos task validate [project]\r\n droid2hmos checkpoint status [project]\r\n droid2hmos checkpoint create [project] --message <message> (--include <path>...|--all)\r\n droid2hmos device check harmony [--hdc <path>]\r\n droid2hmos auth login [project] [--timeout-ms <ms>]\r\n droid2hmos sign [project] [--target <serial>] [--force] [--timeout-ms <ms>]\r\n droid2hmos evidence capture harmony [project] --name <name> [--target <id>]\r\n droid2hmos evidence compare [project] --name <name> --android <evidence-dir> --harmony <evidence-dir>\r\n droid2hmos evidence flow harmony [project] --name <name> [--target <id>] [--class <class> [--case <case>]|--all] [--case-timeout-ms <ms>] [--ref <report-ref>...]\r\n droid2hmos mock init [project] --spec <protocol-spec.json> [--force]\r\n droid2hmos logs <list|show|failures|stats> [project] [value]\r\n droid2hmos upgrade\r\n droid2hmos service start <name> [project] [--cwd <dir>] [--health-url <url>] [--timeout-ms <ms>] -- <command> [args...]\r\n droid2hmos service <status|stop> <name> [project]\r\n\r\nOptions:\r\n -v, --version Show the installed version\r\n\r\nThe project defaults to the current directory.`;\r\n\r\nconst optionValue = (args: string[], name: string) => {\r\n const index = args.indexOf(name);\r\n if (index < 0) return undefined;\r\n if (!args[index + 1] || args[index + 1].startsWith(\"-\")) throw new Error(`${name} requires a value`);\r\n return args[index + 1];\r\n};\r\n\r\nconst optionValues = (args: string[], name: string) => args.flatMap((argument, index) => argument === name && args[index + 1] && !args[index + 1].startsWith(\"-\") ? [args[index + 1]] : []);\r\n\r\nconst positionals = (args: string[], valueOptions: string[] = []) => args.filter((argument, index) => {\r\n if (valueOptions.includes(argument)) return false;\r\n if (index > 0 && valueOptions.includes(args[index - 1])) return false;\r\n return !argument.startsWith(\"-\");\r\n});\r\n\r\nconst json = (value: unknown) => console.log(JSON.stringify(value, null, 2));\r\n\r\nexport class CliError extends Error {\r\n constructor(message: string, public readonly exitCode = 2, public readonly reported = false) {\r\n super(message);\r\n }\r\n}\r\n\r\nfunction guard(action: string, project: string): GuardResult {\r\n const result = guardMigrationAction({\r\n action,\r\n snapshot: inspectMigration(project),\r\n mode: process.env.DROID2HMOS_GUARD_MODE === \"shadow\" ? \"shadow\" : \"enforce\",\r\n });\r\n if (result.policyDecision === \"deny\" && result.decision === \"allow\") {\r\n console.error(JSON.stringify({ warning: \"migration guard shadow denial\", ...result }));\r\n }\r\n if (result.decision === \"deny\") {\r\n throw new CliError(`Migration guard denied ${action}: ${result.unmet.map((item) => item.message).join(\"; \")}`, 1);\r\n }\r\n return result;\r\n}\r\n\r\nfunction observed(project: string, action: string, result: any, scope: Record<string, unknown> | null, guardResult: GuardResult) {\r\n const observation = recordObservation({ project, action, result, scope, guard: guardResult });\r\n return { ...result, managedEvidence: observation.reference, retry: observation.receipt.retry };\r\n}\r\n\r\nexport async function runCli(argv: string[], runtime: RuntimePaths): Promise<number> {\r\n const args = [...argv];\r\n let command = args.shift();\r\n if (command && [\"-v\", \"--version\"].includes(command)) {\r\n if (args.length > 0) throw new CliError(`${command} does not accept arguments`);\r\n console.log(readPackageMetadata(runtime.packageRoot).version);\r\n return 0;\r\n }\r\n if (!command || [\"help\", \"-h\", \"--help\"].includes(command)) {\r\n console.log(HELP);\r\n return 0;\r\n }\r\n\r\n if (args.includes(\"--help\") || args.includes(\"-h\")) {\r\n console.log(HELP);\r\n return 0;\r\n }\r\n\r\n if (command === \"status\") {\r\n const projects = positionals(args);\r\n if (projects.length > 1) throw new CliError(\"status accepts at most one project directory\");\r\n json(inspectMigration(projects[0] ?? \".\"));\r\n return 0;\r\n }\r\n\r\n if (command === \"complete\") {\r\n const projects = positionals(args);\r\n if (projects.length > 1) throw new CliError(\"complete accepts at most one project directory\");\r\n const project = projects[0] ?? \".\";\r\n const snapshot = inspectMigration(project);\r\n const decision = guardMigrationAction({ action: \"complete\", snapshot, mode: process.env.DROID2HMOS_GUARD_MODE === \"shadow\" ? \"shadow\" : \"enforce\" });\r\n if (decision.decision !== \"allow\") {\r\n json({ status: \"failed\", decision, snapshot });\r\n throw new CliError(`Migration guard denied complete: ${decision.unmet.map((item) => item.message).join(\"; \")}`, 1, true);\r\n }\r\n const { exitCode, ...validation } = validateMigrationReport([project, \"--require-complete\"], { writeResult: true });\r\n json({ status: exitCode === 0 ? \"passed\" : \"failed\", decision, snapshot, validation });\r\n if (exitCode !== 0) return exitCode;\r\n return 0;\r\n }\r\n\r\n if (command === \"init\") {\r\n const projects = positionals(args, [\"--target\"]);\r\n if (projects.length > 1) throw new Error(\"init accepts at most one Android project directory\");\r\n if (!runtime.templatesRoot) throw new Error(`Cannot locate bundled HarmonyOS template (templates/ohos) from ${runtime.entryFile}`);\r\n const project = projects[0] ?? \".\";\r\n const guardResult = guard(\"init\", project);\r\n const auth = await managedDevEcoCliLogin({\r\n project,\r\n hostCommand: [process.execPath, runtime.entryFile, \"internal\", \"devecocli-auth-host\"],\r\n onProgress: (line) => console.error(`[auth] ${line}`),\r\n });\r\n if (auth.status !== \"passed\") throw new Error(auth.summary);\r\n const result = initHmosProject({\r\n androidProject: project,\r\n target: optionValue(args, \"--target\"),\r\n templateRoot: path.join(runtime.templatesRoot, \"ohos\"),\r\n });\r\n const signature = signNewHarmonyProject({\r\n projectRoot: path.resolve(project),\r\n harmonyProject: result.target,\r\n timeoutMs: 5 * 60 * 1000,\r\n });\r\n if (signature.status !== \"passed\") throw new Error(`HarmonyOS project was created, but automatic signature generation failed: ${signature.summary}`);\r\n json(observed(project, \"init\", { ...result, signature }, { target: optionValue(args, \"--target\") ?? null }, guardResult));\r\n return 0;\r\n }\r\n\r\n if (command === \"upgrade\") {\r\n if (args.length > 0) throw new CliError(\"upgrade does not accept arguments\");\r\n json(upgradeCli({ packageRoot: runtime.packageRoot }));\r\n return 0;\r\n }\r\n\r\n if (command === \"config\") {\r\n const action = args.shift();\r\n if (!new Set([\"init\", \"validate\"]).has(action)) throw new CliError(\"config requires init or validate\");\r\n const projects = positionals(args, [\"--harmony-project\"]);\r\n if (projects.length > 1) throw new CliError(\"config accepts at most one project directory\");\r\n const project = projects[0] ?? \".\";\r\n const guardResult = guard(`config:${action}`, project);\r\n const result = action === \"init\" ? initMigrationConfig({\r\n project,\r\n harmonyProject: optionValue(args, \"--harmony-project\"),\r\n }) : validateMigrationConfig(project);\r\n json(observed(project, `config:${action}`, result, null, guardResult));\r\n return action === \"validate\" && !(result as any).valid ? 1 : 0;\r\n }\r\n\r\n if (command === \"preflight\") {\r\n const projects = positionals(args, [\"--sdk-path\", \"--timeout-ms\"]);\r\n if (projects.length > 1) throw new CliError(\"preflight accepts at most one project directory\");\r\n if (!runtime.templatesRoot) throw new Error(\"Cannot locate bundled HarmonyOS template\");\r\n if (!runtime.preflightChecklistPath) throw new Error(\"Cannot locate bundled preflight checklist\");\r\n const timeoutMs = Number(optionValue(args, \"--timeout-ms\") ?? 30 * 60 * 1000);\r\n const project = projects[0] ?? \".\";\r\n const guardResult = guard(\"preflight\", project);\r\n const result = await runPreflight({ project, templatesRoot: runtime.templatesRoot, checklistPath: runtime.preflightChecklistPath, sdkPath: optionValue(args, \"--sdk-path\"), timeoutMs, initializeHarmony: !args.includes(\"--no-init-harmony\") });\r\n json(observed(project, \"preflight\", result, { initializeHarmony: !args.includes(\"--no-init-harmony\") }, guardResult));\r\n return result.status === \"passed\" ? 0 : 1;\r\n }\r\n\r\n if (command === \"analyze\") {\r\n const target = args.shift();\r\n if (!new Set([\"android\", \"harmony\", \"all\"]).has(target)) throw new CliError(\"analyze target must be android, harmony, or all\");\r\n const projects = positionals(args);\r\n if (projects.length > 1) throw new CliError(\"analyze accepts at most one project directory\");\r\n const project = projects[0] ?? \".\";\r\n const projectRoot = path.resolve(project);\r\n if (target === \"android\" || target === \"all\") {\r\n const guardResult = guard(\"analyze:android\", project);\r\n // Android 编译不是迁移前置:facts 由 AppGraph 直接解析源码生成。\r\n // APK 清点只作参考信息(Android 运行时对照能力已移除),存在与否不影响分析结果。\r\n const apkInventory = checkAndroidBuild([project]);\r\n const status = runAppGraph([\"spec\", project]);\r\n json(observed(project, \"analyze:android\", {\r\n status: status === 0 ? \"passed\" : \"failed\",\r\n exitCode: status,\r\n androidApk: { present: apkInventory.present, artifacts: apkInventory.artifacts, inventory: apkInventory.report },\r\n }, null, guardResult));\r\n if (status !== 0) return status;\r\n }\r\n if (target === \"harmony\" || target === \"all\") {\r\n const guardResult = guard(\"analyze:harmony\", project);\r\n const configPath = path.join(migrationDirectory(projectRoot), \"config.json\");\r\n if (!existsSync(configPath)) throw new Error(`Migration config not found: ${configPath}`);\r\n const config = JSON.parse(readFileSync(configPath, \"utf8\"));\r\n const configuredHarmony = config.harmonyProject ?? defaultHarmonyProjectPath(projectRoot);\r\n const harmonyProject = path.isAbsolute(configuredHarmony) ? configuredHarmony : path.resolve(projectRoot, configuredHarmony);\r\n const forwarded = [\"build\", harmonyProject, \"--platform\", \"harmony\"];\r\n if (config.harmonySdk?.path) forwarded.push(\"--harmony-sdk\", config.harmonySdk.path);\r\n const status = runAppGraph(forwarded);\r\n json(observed(project, \"analyze:harmony\", { status: status === 0 ? \"passed\" : \"failed\", exitCode: status }, null, guardResult));\r\n return status;\r\n }\r\n return 0;\r\n }\r\n\r\n if (command === \"report\") {\r\n const explicitAction = [\"init\", \"validate\", \"render\", \"update\"].includes(args[0] ?? \"\") ? args.shift() : null;\r\n const action = explicitAction ?? \"render\";\r\n const projects = positionals(args, [\"--ref\", \"--status\", \"--harmony-file\", \"--android-source\", \"--evidence\", \"--difference\"]);\r\n if (projects.length > 1) throw new CliError(\"report accepts at most one project directory\");\r\n const project = projects[0] ?? \".\";\r\n if (action === \"update\") {\r\n guard(\"report:update\", project);\r\n const ref = optionValue(args, \"--ref\");\r\n if (!ref) throw new CliError(\"report update requires --ref\");\r\n const result = updateReportItem({\r\n project, ref, status: optionValue(args, \"--status\"),\r\n harmonyosFiles: args.includes(\"--harmony-file\") ? optionValues(args, \"--harmony-file\") : undefined,\r\n androidSourceFiles: args.includes(\"--android-source\") ? optionValues(args, \"--android-source\") : undefined,\r\n testEvidence: args.includes(\"--evidence\") ? optionValues(args, \"--evidence\") : undefined,\r\n difference: args.includes(\"--clear-difference\") ? null : optionValue(args, \"--difference\"),\r\n });\r\n json(result); return 0;\r\n }\r\n if (action === \"init\") { guard(\"report:init\", project); json(initMigrationReport([project])); return 0; }\r\n if (action === \"validate\") {\r\n guard(\"report:validate\", project);\r\n const { exitCode, ...result } = validateMigrationReport([project, ...(args.includes(\"--require-complete\") ? [\"--require-complete\"] : [])]);\r\n json(result);\r\n if (exitCode === 0 && args.includes(\"--require-complete\")) guard(\"complete\", project);\r\n return exitCode;\r\n }\r\n if (action === \"render\" && explicitAction) {\r\n guard(\"report:render\", project);\r\n if (args.includes(\"--require-complete\")) {\r\n const { exitCode, ...validation } = validateMigrationReport([project, \"--require-complete\"]);\r\n if (exitCode !== 0) { json(validation); return exitCode; }\r\n guard(\"complete\", project);\r\n }\r\n json(renderMigrationReport(project));\r\n return 0;\r\n }\r\n if (action === \"render\") {\r\n const reportIndex = path.join(migrationDirectory(project), \"report\", \"index.json\");\r\n if (!existsSync(reportIndex)) { guard(\"report:init\", project); json(initMigrationReport([project])); }\r\n guard(\"report:render\", project);\r\n const { exitCode, ...validation } = validateMigrationReport([project, ...(args.includes(\"--require-complete\") ? [\"--require-complete\"] : [])]);\r\n json(validation);\r\n if (exitCode !== 0) return exitCode;\r\n if (args.includes(\"--require-complete\")) guard(\"complete\", project);\r\n json(renderMigrationReport(project));\r\n return 0;\r\n }\r\n throw new Error(\"report requires init, validate, or render\");\r\n }\r\n\r\n if (command === \"task\") {\r\n const action = args.shift();\r\n if (!new Set([\"plan\", \"status\", \"next\", \"show\", \"validate\"]).has(action)) throw new CliError(\"task requires plan, status, next, show, or validate\");\r\n if (action === \"show\") {\r\n const values = positionals(args, [\"--cursor\", \"--max-source-context\"]);\r\n if (values.length < 1 || values.length > 2) throw new CliError(\"task show requires [project] <task-or-package-id>\");\r\n const project = values.length === 2 ? values[0]! : \".\";\r\n const targetId = values.at(-1)!;\r\n if (!/^(task|package):[a-f0-9]{16}$/.test(targetId)) throw new CliError(\"task show requires a valid Resolution Task or Page Work Package id\");\r\n const maxSourceContext = Number(optionValue(args, \"--max-source-context\") ?? 25);\r\n if (!Number.isInteger(maxSourceContext) || maxSourceContext <= 0 || maxSourceContext > 200) throw new CliError(\"--max-source-context must be an integer from 1 to 200\");\r\n const snapshot = inspectMigration(project);\r\n json(taskPlanning.materialize(project, targetId, {\r\n source: {\r\n androidFingerprint: snapshot.source.androidFingerprint,\r\n harmonyFingerprint: snapshot.source.harmonyFingerprint,\r\n fullRegressionFresh: snapshot.evidence.fullRegression.fresh,\r\n },\r\n cursor: optionValue(args, \"--cursor\"),\r\n maxSourceContext,\r\n }));\r\n return 0;\r\n }\r\n const projects = positionals(args);\r\n if (projects.length > 1) throw new CliError(`task ${action} accepts at most one project directory`);\r\n const project = projects[0] ?? \".\";\r\n if (action === \"plan\") {\r\n const guardResult = guard(\"task:plan\", project);\r\n const before = inspectMigration(project);\r\n const plan = taskPlanning.compile(project, { androidFingerprint: before.source.androidFingerprint });\r\n const planning = inspectMigration(project).planning;\r\n const result = {\r\n status: planning.valid && planning.fresh ? \"passed\" : \"failed\",\r\n taskPlanVersion: plan.taskPlanVersion,\r\n executionPlanVersion: plan.executionPlanVersion,\r\n planningPhase: plan.planningPhase,\r\n taskPlanSha256: planning.taskPlanSha256,\r\n totalTasks: plan.tasks.length,\r\n behaviorResponsibilities: plan.behaviorResponsibilities.length,\r\n pageWorkPackages: plan.pageWorkPackages.length,\r\n executionTargets: plan.planningPhase === \"resolution\" ? plan.tasks.length : plan.pageWorkPackages.length,\r\n resolutionTasks: plan.tasks.filter((task) => task.type === \"resolution\").length,\r\n errors: planning.errors,\r\n warnings: planning.warnings,\r\n };\r\n json(observed(project, \"task:plan\", result, null, guardResult));\r\n return result.status === \"passed\" ? 0 : 1;\r\n }\r\n if (action === \"validate\") {\r\n const guardResult = guard(\"task:validate\", project);\r\n const snapshot = inspectMigration(project).planning;\r\n const result = { status: snapshot.valid && snapshot.fresh ? \"passed\" : \"failed\", ...snapshot };\r\n json(observed(project, \"task:validate\", result, null, guardResult));\r\n return result.status === \"passed\" ? 0 : 1;\r\n }\r\n const snapshot = inspectMigration(project).planning;\r\n if (action === \"status\") { json(snapshot); return 0; }\r\n if (!snapshot.present || !snapshot.valid || !snapshot.fresh) {\r\n json({ status: \"failed\", errors: snapshot.errors, planning: snapshot });\r\n return 1;\r\n }\r\n const allComplete = snapshot.totalTasks > 0 && snapshot.completedTasks === snapshot.totalTasks;\r\n json({\r\n status: snapshot.recommendedTargetId ? \"ready\" : (() => { if (allComplete) return \"complete\"; return \"blocked\"; })(),\r\n recommended: snapshot.recommendedTargetId,\r\n alternatives: snapshot.alternatives,\r\n reasons: snapshot.reasons,\r\n });\r\n return snapshot.recommendedTargetId || allComplete ? 0 : 1;\r\n }\r\n\r\n if (command === \"build\") {\r\n const target = args.shift();\r\n if (target !== \"harmony\") throw new CliError(\"build target must be harmony (Android 构建已移除:迁移流程不依赖 Android 编译环境)\");\r\n const projects = positionals(args, [\"--timeout-ms\"]);\r\n if (projects.length > 1) throw new CliError(\"build accepts at most one project directory\");\r\n const projectRoot = path.resolve(projects[0] ?? \".\");\r\n const timeoutMs = Number(optionValue(args, \"--timeout-ms\") ?? 30 * 60 * 1000);\r\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new CliError(\"--timeout-ms must be a positive number\");\r\n const configPath = path.join(migrationDirectory(projectRoot), \"config.json\");\r\n if (!existsSync(configPath)) throw new Error(`Migration config not found: ${configPath}`);\r\n const guardResult = guard(\"build:harmony\", projectRoot);\r\n const config = JSON.parse(readFileSync(configPath, \"utf8\"));\r\n const configuredHarmony = config.harmonyProject ?? defaultHarmonyProjectPath(projectRoot);\r\n const harmonyProject = path.isAbsolute(configuredHarmony) ? configuredHarmony : path.resolve(projectRoot, configuredHarmony);\r\n let result;\r\n try {\r\n result = runHarmonyBuild({ projectRoot, harmonyProject, timeoutMs });\r\n } catch (error) {\r\n result = { status: \"failed\", key: \"harmonyBuild\", summary: error?.message ?? String(error) };\r\n }\r\n result = observed(projectRoot, \"build:harmony\", result, null, guardResult);\r\n json(result);\r\n return result.status === \"passed\" ? 0 : 1;\r\n }\r\n\r\n if (command === \"test\") {\r\n const target = args.shift();\r\n if (target !== \"harmony\") throw new CliError(\"test target must be harmony (Android 测试已移除:迁移流程不依赖 Android 运行环境)\");\r\n const projects = positionals(args, [\"--timeout-ms\", \"--case-timeout-ms\", \"--class\", \"--case\", \"--target\", \"--ref\", \"--runner\", \"--hypium-project\", \"--test-list\", \"--python\", \"--report-path\"]);\r\n if (projects.length > 1) throw new CliError(\"test accepts at most one project directory\");\r\n const projectRoot = path.resolve(projects[0] ?? \".\");\r\n const timeoutMs = Number(optionValue(args, \"--timeout-ms\") ?? 30 * 60 * 1000);\r\n const harmonyTarget = optionValue(args, \"--target\") ?? null;\r\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new CliError(\"--timeout-ms must be a positive number\");\r\n const runner = optionValue(args, \"--runner\") ?? \"arkts\";\r\n if (!new Set([\"arkts\", \"python\"]).has(runner)) throw new CliError(\"--runner must be arkts or python\");\r\n const testClass = optionValue(args, \"--class\") ?? null;\r\n const testCase = optionValue(args, \"--case\") ?? null;\r\n const requestedTarget = optionValue(args, \"--target\") ?? null;\r\n const caseTimeoutMs = Number(optionValue(args, \"--case-timeout-ms\") ?? 30000);\r\n const coveredRefs = [...new Set(optionValues(args, \"--ref\"))];\r\n const fullRun = args.includes(\"--all\");\r\n const action = fullRun ? \"test:harmony:all\" : \"test:harmony:targeted\";\r\n const guardResult = guard(action, projectRoot);\r\n if (!Number.isFinite(caseTimeoutMs) || caseTimeoutMs <= 0) throw new CliError(\"--case-timeout-ms must be a positive number\");\r\n const configPath = path.join(migrationDirectory(projectRoot), \"config.json\");\r\n if (!existsSync(configPath)) throw new Error(`Migration config not found: ${configPath}`);\r\n const config = JSON.parse(readFileSync(configPath, \"utf8\"));\r\n const configuredHarmony = config.harmonyProject ?? defaultHarmonyProjectPath(projectRoot);\r\n const harmonyProject = path.isAbsolute(configuredHarmony) ? configuredHarmony : path.resolve(projectRoot, configuredHarmony);\r\n let result;\r\n try {\r\n if (runner === \"python\") {\r\n if (testClass || testCase || fullRun) throw new CliError(\"Python Hypium uses --test-list instead of --class, --case, or --all\");\r\n const hypiumProject = optionValue(args, \"--hypium-project\");\r\n const testLists = optionValues(args, \"--test-list\").flatMap((value) => value.split(\";\")).map((value) => value.trim()).filter(Boolean);\r\n if (!hypiumProject) throw new CliError(\"Python Hypium requires --hypium-project\");\r\n if (!testLists.length) throw new CliError(\"Python Hypium requires at least one --test-list\");\r\n result = runHarmonyPythonHypiumTest({\r\n projectRoot,\r\n harmonyProject,\r\n hypiumProject,\r\n testLists,\r\n target: requestedTarget ?? undefined,\r\n python: optionValue(args, \"--python\"),\r\n reportPath: optionValue(args, \"--report-path\"),\r\n timeoutMs,\r\n });\r\n } else {\r\n if (args.includes(\"--hypium-project\") || args.includes(\"--test-list\") || args.includes(\"--python\") || args.includes(\"--report-path\")) {\r\n throw new CliError(\"Python Hypium options require --runner python\");\r\n }\r\n if (Boolean(testClass) === fullRun) throw new CliError(\"test harmony with the ArkTS runner requires exactly one of --class or --all\");\r\n if (testCase && !testClass) throw new CliError(\"--case requires --class\");\r\n if (testClass && !/^[A-Za-z0-9_.$#-]+$/.test(testClass)) throw new CliError(\"--class contains unsupported characters\");\r\n if (testCase && !/^[A-Za-z0-9_.$#-]+$/.test(testCase)) throw new CliError(\"--case contains unsupported characters\");\r\n result = runHarmonyTest({ projectRoot, harmonyProject, timeoutMs, testClass, testCase, target: requestedTarget, caseTimeoutMs });\r\n }\r\n } catch (error) {\r\n if (error instanceof CliError) throw error;\r\n result = { status: \"failed\", key: runner === \"python\" ? \"harmonyPythonTest\" : \"harmonyTest\", runner, summary: error?.message ?? String(error) };\r\n }\r\n result = observed(projectRoot, action, result, {\r\n testClass,\r\n testCase,\r\n fullRun,\r\n target: result.target ?? requestedTarget,\r\n coveredRefs,\r\n caseTimeoutMs,\r\n runner,\r\n }, guardResult);\r\n json(result);\r\n return result.status === \"passed\" ? 0 : 1;\r\n }\r\n\r\n if (command === \"checkpoint\") {\r\n const action = args.shift();\r\n if (!new Set([\"status\", \"create\"]).has(action)) throw new CliError(\"checkpoint requires status or create\");\r\n const projects = positionals(args, [\"--message\", \"--include\"]);\r\n if (projects.length > 1) throw new CliError(\"checkpoint accepts at most one project directory\");\r\n const project = projects[0] ?? \".\";\r\n if (action === \"status\") {\r\n const result = gitWorkspaceStatus(project); json(result); return result.status === \"passed\" ? 0 : 1;\r\n }\r\n guard(\"checkpoint:create\", project);\r\n const { exitCode, ...validation } = validateMigrationReport([project], { writeResult: true });\r\n if (exitCode !== 0) throw new CliError(\"checkpoint source governance validation failed\", 1);\r\n const checkpointValidation = validation as any;\r\n const roots = sourceRoots(project);\r\n const provenanceReceipt = {\r\n checkpointProvenanceVersion: \"1.0.0\",\r\n reportValidationVersion: checkpointValidation.reportValidationVersion,\r\n factsSha256: checkpointValidation.factsSha256,\r\n evidenceLevel: checkpointValidation.evidenceLevel,\r\n sourceManifest: managedSourceManifest(project),\r\n sourceClaims: checkpointValidation.sourceClaims,\r\n orderAudit: checkpointValidation.orderAudit,\r\n closureAudit: checkpointValidation.closureAudit,\r\n literalAudit: checkpointValidation.literalAudit,\r\n };\r\n const provenanceFiles = checkpointValidation.sourceClaims.flatMap((claim: any) => [\r\n ...(claim.harmonyosFiles ?? []).map((file: string) => ({ file, role: \"harmony-implementation\" as const })),\r\n ...(claim.sourceProvenance ?? []).map((entry: any) => ({\r\n file: path.relative(roots.projectRoot, path.resolve(roots.androidRoot, entry.androidFile)).replaceAll(\"\\\\\", \"/\"),\r\n role: \"android-source\" as const,\r\n })),\r\n ]);\r\n json(createGitCheckpoint({ project, harmonyProject: roots.harmonyRoot, message: optionValue(args, \"--message\") ?? \"\", include: optionValues(args, \"--include\"), all: args.includes(\"--all\"), provenanceReceipt, provenanceFiles }));\r\n return 0;\r\n }\r\n\r\n if (command === \"device\") {\r\n if (args.shift() !== \"check\") throw new CliError(\"device requires check\");\r\n const platform = args.shift();\r\n if (platform !== \"harmony\") throw new CliError(\"device check requires harmony (Android 设备检测已移除)\");\r\n guard(\"device:check\", \".\");\r\n const result = checkHarmonyDevice({ hdc: optionValue(args, \"--hdc\") });\r\n json(result); return result.status === \"failed\" ? 1 : 0;\r\n }\r\n\r\n if (command === \"auth\") {\r\n if (args.shift() !== \"login\") throw new CliError(\"auth requires login\");\r\n const projects = positionals(args, [\"--timeout-ms\"]);\r\n if (projects.length > 1) throw new CliError(\"auth accepts at most one project directory\");\r\n const timeoutMs = Number(optionValue(args, \"--timeout-ms\") ?? 10 * 60 * 1000);\r\n if (!Number.isFinite(timeoutMs) || timeoutMs < 30_000) throw new CliError(\"--timeout-ms must be at least 30000 for the managed login\");\r\n const result = await managedDevEcoCliLogin({\r\n project: projects[0] ?? \".\",\r\n hostCommand: [process.execPath, runtime.entryFile, \"internal\", \"devecocli-auth-host\"],\r\n timeoutMs,\r\n onProgress: (line) => console.error(`[auth] ${line}`),\r\n });\r\n json(result);\r\n return result.status === \"passed\" ? 0 : 1;\r\n }\r\n\r\n if (command === \"sign\") {\r\n const projects = positionals(args, [\"--target\", \"--timeout-ms\"]);\r\n if (projects.length > 1) throw new CliError(\"sign accepts at most one project directory\");\r\n const project = projects[0] ?? \".\";\r\n const projectRoot = path.resolve(project);\r\n const configPath = path.join(migrationDirectory(projectRoot), \"config.json\");\r\n if (!existsSync(configPath)) throw new Error(`Migration config not found: ${configPath}`);\r\n const config = JSON.parse(readFileSync(configPath, \"utf8\"));\r\n const configuredHarmony = config.harmonyProject ?? defaultHarmonyProjectPath(projectRoot);\r\n const harmonyProject = path.isAbsolute(configuredHarmony) ? configuredHarmony : path.resolve(projectRoot, configuredHarmony);\r\n const timeoutMs = Number(optionValue(args, \"--timeout-ms\") ?? 5 * 60 * 1000);\r\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new CliError(\"--timeout-ms must be a positive number\");\r\n const result = ensureDeviceSignature({\r\n projectRoot,\r\n harmonyProject,\r\n target: optionValue(args, \"--target\"),\r\n force: args.includes(\"--force\"),\r\n timeoutMs,\r\n });\r\n json(result);\r\n return result.status === \"passed\" || result.status === \"skipped\" ? 0 : 1;\r\n }\r\n\r\n if (command === \"evidence\") {\r\n const action = args.shift();\r\n if (!new Set([\"capture\", \"compare\", \"flow\"]).has(action)) throw new CliError(\"evidence requires capture, compare, or flow\");\r\n if (action === \"compare\") {\r\n const projects = positionals(args, [\"--name\", \"--android\", \"--harmony\"]);\r\n const name = optionValue(args, \"--name\");\r\n const android = optionValue(args, \"--android\");\r\n const harmony = optionValue(args, \"--harmony\");\r\n if (!name || !android || !harmony) throw new CliError(\"evidence compare requires --name, --android, and --harmony\");\r\n const project = projects[0] ?? \".\";\r\n guard(\"evidence:compare\", project);\r\n json(compareEvidence({ project, name, android, harmony })); return 0;\r\n }\r\n const platform = args.shift();\r\n if (platform !== \"harmony\") throw new CliError(`evidence ${action} requires harmony (Android 证据采集已移除)`);\r\n const projects = positionals(args, [\"--name\", \"--target\", \"--class\", \"--case\", \"--timeout-ms\", \"--case-timeout-ms\", \"--ref\"]);\r\n const project = projects[0] ?? \".\";\r\n const name = optionValue(args, \"--name\");\r\n if (!name) throw new CliError(`evidence ${action} requires --name`);\r\n if (action === \"capture\") {\r\n guard(\"evidence:capture\", project);\r\n const result = captureDeviceEvidence({ project, platform: platform as any, name, target: optionValue(args, \"--target\") });\r\n json(result); return result.status === \"passed\" ? 0 : 1;\r\n }\r\n const flowGuard = guard(\"evidence:flow\", project);\r\n const before = captureDeviceEvidence({ project, platform: platform as any, name: `${name}-before`, target: optionValue(args, \"--target\") });\r\n const projectRoot = path.resolve(project);\r\n const timeoutMs = Number(optionValue(args, \"--timeout-ms\") ?? 30 * 60 * 1000);\r\n let execution: any;\r\n if (before.status !== \"passed\") execution = { status: \"failed\", skipped: true, summary: \"Baseline evidence capture failed; interaction was not executed\" };\r\n else {\r\n const config = JSON.parse(readFileSync(path.join(migrationDirectory(projectRoot), \"config.json\"), \"utf8\"));\r\n const harmonyProject = path.isAbsolute(config.harmonyProject) ? config.harmonyProject : path.resolve(projectRoot, config.harmonyProject);\r\n const testClass = optionValue(args, \"--class\") ?? null;\r\n const testCase = optionValue(args, \"--case\") ?? null;\r\n if (!testClass && !args.includes(\"--all\")) throw new CliError(\"Harmony evidence flow requires --class or --all\");\r\n const caseTimeoutMs = Number(optionValue(args, \"--case-timeout-ms\") ?? 30000);\r\n if (!Number.isFinite(caseTimeoutMs) || caseTimeoutMs <= 0) throw new CliError(\"--case-timeout-ms must be a positive number\");\r\n execution = runHarmonyTest({ projectRoot, harmonyProject, timeoutMs, testClass, testCase, target: optionValue(args, \"--target\"), caseTimeoutMs });\r\n }\r\n const after = captureDeviceEvidence({ project, platform: platform as any, name: `${name}-after`, target: optionValue(args, \"--target\") });\r\n let result: any = writeFlowBundle({ project, name, platform: platform as any, before, execution, after });\r\n {\r\n const testAction = args.includes(\"--all\") ? \"test:harmony:all\" : \"test:harmony:targeted\";\r\n result = observed(project, testAction, result, {\r\n evidenceFlow: name,\r\n testClass: optionValue(args, \"--class\") ?? null,\r\n testCase: optionValue(args, \"--case\") ?? null,\r\n fullRun: args.includes(\"--all\"),\r\n target: result.execution?.target ?? optionValue(args, \"--target\") ?? null,\r\n coveredRefs: [...new Set(optionValues(args, \"--ref\"))],\r\n caseTimeoutMs: Number(optionValue(args, \"--case-timeout-ms\") ?? 30000),\r\n }, flowGuard);\r\n }\r\n json(result); return result.status === \"passed\" ? 0 : 1;\r\n }\r\n\r\n if (command === \"mock\") {\r\n if (args.shift() !== \"init\") throw new CliError(\"mock requires init\");\r\n const projects = positionals(args, [\"--spec\"]);\r\n const specFile = optionValue(args, \"--spec\");\r\n if (!specFile) throw new CliError(\"mock init requires --spec\");\r\n const project = projects[0] ?? \".\";\r\n guard(\"mock:init\", project);\r\n json(generateMockServer({ project, specFile, force: args.includes(\"--force\") })); return 0;\r\n }\r\n\r\n if (command === \"logs\") {\r\n const action = args.shift();\r\n if (!new Set([\"list\", \"show\", \"failures\", \"stats\"]).has(action)) throw new CliError(\"logs requires list, show, failures, or stats\");\r\n const project = args.shift() ?? \".\";\r\n json(queryCommandLogs(project, action, args.shift())); return 0;\r\n }\r\n\r\n if (command === \"service\") {\r\n const action = args.shift();\r\n if (!new Set([\"start\", \"status\", \"stop\"]).has(action)) throw new CliError(\"service action must be start, status, or stop\");\r\n const name = args.shift();\r\n if (!name || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)) throw new CliError(`service ${action} requires a safe service name`);\r\n const separator = args.indexOf(\"--\");\r\n const serviceArgs = separator >= 0 ? args.slice(0, separator) : args;\r\n const serviceCommand = separator >= 0 ? args.slice(separator + 1) : [];\r\n const projects = positionals(serviceArgs, [\"--cwd\", \"--health-url\", \"--timeout-ms\"]);\r\n if (projects.length > 1) throw new CliError(`service ${action} accepts at most one project directory`);\r\n const project = projects[0] ?? \".\";\r\n const projectRoot = path.resolve(project);\r\n const stateDir = path.join(migrationDirectory(projectRoot), \"services\");\r\n const pidFile = path.join(stateDir, `${name}.pid`);\r\n const healthUrl = optionValue(serviceArgs, \"--health-url\");\r\n if (action === \"status\") {\r\n guard(\"service:status\", project);\r\n json(await statusBackgroundService({ pidFile, healthUrl }));\r\n return 0;\r\n }\r\n if (action === \"stop\") {\r\n guard(\"service:stop\", project);\r\n json(stopBackgroundService({ pidFile }));\r\n return 0;\r\n }\r\n if (separator < 0 || serviceCommand.length === 0) throw new CliError(\"service start requires -- followed by the service command\");\r\n guard(\"service:start\", project);\r\n const cwdValue = optionValue(serviceArgs, \"--cwd\") ?? path.join(projectRoot, name);\r\n const cwd = path.isAbsolute(cwdValue) ? cwdValue : path.resolve(projectRoot, cwdValue);\r\n if (!existsSync(cwd)) throw new Error(`Service working directory not found: ${cwd}`);\r\n const timeoutMs = Number(optionValue(serviceArgs, \"--timeout-ms\") ?? 15000);\r\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new CliError(\"--timeout-ms must be a positive number\");\r\n json(await startBackgroundService({\r\n cwd,\r\n command: serviceCommand,\r\n pidFile,\r\n stdout: path.join(stateDir, `${name}.stdout.log`),\r\n stderr: path.join(stateDir, `${name}.stderr.log`),\r\n healthUrl,\r\n timeoutMs,\r\n hostCommand: [process.execPath, runtime.entryFile, \"internal\", \"background-service-host\"],\r\n }));\r\n return 0;\r\n }\r\n\r\n if (command === \"internal\") {\r\n const action = args.shift();\r\n if (action === \"detect-harmony-sdk\") {\r\n const projects = positionals(args, [\"--sdk-path\"]);\r\n if (projects.length > 1) throw new CliError(\"detect-harmony-sdk accepts at most one project directory\");\r\n json(detectHarmonySdk({\r\n project: projects[0] ?? \".\",\r\n sdkPath: optionValue(args, \"--sdk-path\"),\r\n writeConfig: args.includes(\"--write-config\"),\r\n }));\r\n return 0;\r\n }\r\n if (action === \"initialize-spec\") { json(initializeSpec(args)); return 0; }\r\n if (action === \"render-spec\") { json(renderSpecHtml(args)); return 0; }\r\n if (action === \"background-service-host\") {\r\n if (!args[0]) throw new Error(\"background-service-host requires a launch request\");\r\n runDetachedHost(path.resolve(args[0]));\r\n return 0;\r\n }\r\n if (action === \"devecocli-auth-host\") {\r\n if (!args[0]) throw new Error(\"devecocli-auth-host requires a launch request\");\r\n runDetachedDevEcoAuthHost(path.resolve(args[0]));\r\n return 0;\r\n }\r\n throw new Error(\"unknown internal command\");\r\n }\r\n\r\n if (command === \"dev\") {\r\n const action = args.shift();\r\n if (!runtime.packageRoot || action !== \"build\") throw new Error(\"dev requires build from a source checkout\");\r\n const result = spawnCommandSync(\"npm\", [\"run\", \"build\"], { cwd: runtime.packageRoot, stdio: \"inherit\" });\r\n if (result.error) throw result.error;\r\n return result.status ?? 1;\r\n }\r\n\r\n throw new CliError(`Unknown command: ${command}`);\r\n}\r\n\r\nconst entryHref = import.meta.url;\r\nconst invokedHref = (() => {\r\n try {\r\n return process.argv[1] ? pathToFileURL(realpathSync(process.argv[1])).href : \"\";\r\n } catch {\r\n return \"\";\r\n }\r\n})();\r\nif (invokedHref && invokedHref === entryHref) {\r\n const argv = process.argv.slice(2);\r\n const runtime = resolveRuntimePaths(import.meta.url);\r\n const version = runtime.packageRoot && existsSync(path.join(runtime.packageRoot, \"package.json\"))\r\n ? JSON.parse(readFileSync(path.join(runtime.packageRoot, \"package.json\"), \"utf8\")).version ?? \"unknown\"\r\n : \"unknown\";\r\n const excluded = new Set([\"help\", \"-h\", \"--help\", \"status\", \"internal\", \"dev\", \"logs\"]);\r\n const readOnlyTaskQuery = argv[0] === \"task\" && [\"status\", \"next\", \"show\"].includes(argv[1] ?? \"\");\r\n Promise.resolve(excluded.has(argv[0] ?? \"help\") || readOnlyTaskQuery || process.env.DROID2HMOS_DISABLE_LOGGING === \"1\" ? runCli(argv, runtime) : withCommandLog(argv, version, () => runCli(argv, runtime)))\r\n .then((exitCode) => { process.exitCode = exitCode; })\r\n .catch((error) => {\r\n if (!error?.reported) console.error(error?.message ?? String(error));\r\n process.exitCode = error?.exitCode ?? 1;\r\n });\r\n}\r\n","import { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from \"node:child_process\";\r\nimport type { SpawnOptions, SpawnSyncOptions } from \"node:child_process\";\r\n\r\n/**\r\n * Node 在 CVE-2024-27980 修复后(Node 18.20+/20.12+/22+)禁止在 Windows 上\r\n * 以 `shell: false` spawn 批处理脚本。npm 全局 bin shim(`npm.cmd`、`appgraph`、\r\n * `devecocli` 等)要么是 `.cmd`/`.bat`(直接抛 EINVAL),要么是无扩展名的\r\n * sh 脚本(CreateProcess 无法执行,抛 ENOENT)。\r\n *\r\n * 统一的跨平台 spawn 入口:win32 上把 CLI 调用改走 cmd shell 并按 cmd 规则\r\n * 引用参数,其他平台保持原生 `spawn(command, args, { shell: false })`。\r\n */\r\n\r\n/** cmd.exe 参数引用:包含空白或 cmd 元字符时加双引号,内部引号按 cmd 规则双写。 */\r\nfunction quoteWinArg(arg: string): string {\r\n if (arg === \"\") return '\"\"';\r\n if (!/[\\s\"&|<>()^%]/.test(arg)) return arg;\r\n return `\"${arg.replace(/\"/g, '\"\"')}\"`;\r\n}\r\n\r\n/** 组装 Windows shell 命令行。参数中不应出现 `%`(cmd 会做变量展开)。 */\r\nfunction windowsCommandLine(command: string, args: readonly string[]): string {\r\n return [command, ...args].map((value) => quoteWinArg(String(value))).join(\" \");\r\n}\r\n\r\nexport interface SpawnCommandInvocation {\r\n command: string;\r\n args: string[];\r\n shell: boolean;\r\n}\r\n\r\n/** 将命令解析为当前平台可直接交给 Node child_process 的调用参数。 */\r\nexport function resolveSpawnCommand(command: string, args: readonly string[], platform: NodeJS.Platform = process.platform): SpawnCommandInvocation {\r\n if (platform !== \"win32\") return { command, args: [...args], shell: false };\r\n return { command: windowsCommandLine(command, args), args: [], shell: true };\r\n}\r\n\r\n/** 通用同步进程启动;保持 `(command, args, options)` 签名,便于注入测试 runner。 */\r\nexport function spawnCommandSync(command: string, args: readonly string[], options: SpawnSyncOptions = {}) {\r\n const invocation = resolveSpawnCommand(command, args);\r\n return nodeSpawnSync(invocation.command, invocation.args, { ...options, shell: invocation.shell });\r\n}\r\n\r\n/** 通用异步进程启动。 */\r\nexport function spawnCommand(command: string, args: readonly string[], options: SpawnOptions = {}) {\r\n const invocation = resolveSpawnCommand(command, args);\r\n return nodeSpawn(invocation.command, invocation.args, { ...options, shell: invocation.shell });\r\n}\r\n","#!/usr/bin/env node\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { migrationDirectory, ensureMigrationWorkspace } from \"../migration-paths.ts\";\r\n\r\n/**\r\n * 只读清点 Android 构建产物(APK):迁移流程默认不编译 Android 工程,\r\n * facts 由 AppGraph 直接解析源码生成,APK 存在与否不影响任何门禁。\r\n * 清点结果仅作参考信息(Android 运行时对照能力已移除),\r\n * 因此本函数永远不会返回 failed,没有 APK 时输出 not_applicable。\r\n */\r\nexport function checkAndroidBuild(argv: string[]) {\r\n const [projectArgument] = argv;\r\n if (!projectArgument) {\r\n throw new Error(\"check-android-build requires <android-project>\");\r\n }\r\n\r\n const projectRoot = path.resolve(projectArgument);\r\n ensureMigrationWorkspace(projectRoot);\r\n const reportPath = path.join(migrationDirectory(projectRoot), \"spec\", \"android-apk-inventory.json\");\r\n const ignored = new Set([\".git\", \".gradle\", \".idea\", \".migration\", \"node_modules\", \"ohos\"]);\r\n const artifacts = [];\r\n\r\n function scan(directory) {\r\n if (!fs.existsSync(directory)) return;\r\n for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {\r\n if (entry.isDirectory() && ignored.has(entry.name)) continue;\r\n const absolute = path.join(directory, entry.name);\r\n if (entry.isDirectory()) scan(absolute);\r\n else if (entry.isFile() && entry.name.toLowerCase().endsWith(\".apk\") && /[\\\\/]build[\\\\/]outputs[\\\\/]apk[\\\\/]/i.test(absolute)) {\r\n const stat = fs.statSync(absolute);\r\n if (stat.size > 0) artifacts.push({\r\n path: path.relative(projectRoot, absolute).replaceAll(\"\\\\\", \"/\"),\r\n bytes: stat.size,\r\n modifiedAt: stat.mtime.toISOString(),\r\n });\r\n }\r\n }\r\n }\r\n\r\n scan(projectRoot);\r\n artifacts.sort((left, right) => left.path.localeCompare(right.path));\r\n const present = artifacts.length > 0;\r\n const status = present ? \"passed\" : \"not_applicable\";\r\n const report = {\r\n inventoryVersion: \"1.0.0\",\r\n mode: \"apk-inventory\",\r\n status,\r\n present,\r\n projectRoot,\r\n checkedPattern: \"**/build/outputs/apk/**/*.apk\",\r\n artifacts,\r\n errors: [],\r\n };\r\n fs.mkdirSync(path.dirname(reportPath), { recursive: true });\r\n const temporary = `${reportPath}.tmp`;\r\n fs.writeFileSync(temporary, `${JSON.stringify(report, null, 2)}\\n`, \"utf8\");\r\n fs.renameSync(temporary, reportPath);\r\n return {\r\n present,\r\n kind: \"android-apk-inventory\",\r\n status,\r\n summary: present\r\n ? `发现 ${artifacts.length} 个 APK 构建产物(仅作参考信息)`\r\n : \"未发现 APK 构建产物(迁移不依赖 Android 编译)\",\r\n artifacts: artifacts.length,\r\n report: reportPath,\r\n };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\n\r\n/**\r\n * 安卓工程共享 `.migration/` 工作区的根目录。\r\n *\r\n * 工作区位于被分析工程之外,是其父目录下的兄弟目录\r\n * `<工程名>-migration/`,迁移产物(spec facts、report、logs、evidence)\r\n * 不会写入源工程内部:\r\n *\r\n * <父目录>/<工程名>-migration/.migration/...\r\n *\r\n * 必须与 `../appgraph/src/appgraph/paths.ts` 中的\r\n * `getMigrationWorkspaceDir()` 保持同步。\r\n */\r\nexport function migrationDirectory(project: string): string {\r\n const projectRoot = path.resolve(project);\r\n return path.join(path.dirname(projectRoot), `${path.basename(projectRoot)}-migration`, \".migration\");\r\n}\r\n\r\n/**\r\n * `<工程名>-migration/` 兄弟目录(即 `.migration/` 工作区)的根目录。\r\n * 报告/证据中存储的 `.migration/spec/index.json` 等相对引用以该目录为\r\n * 基准,因此字符串形式与迁移前的\"工程根相对引用\"完全一致。\r\n */\r\nexport function migrationWorkspaceRoot(project: string): string {\r\n return path.dirname(migrationDirectory(project));\r\n}\r\n\r\n/** 迁移前的位置(工程内部 `.migration/`),仅用于读取兼容。 */\r\nexport function legacyInProjectMigrationDirectory(project: string): string {\r\n return path.join(path.resolve(project), \".migration\");\r\n}\r\n\r\n/**\r\n * 创建迁移工作区目录,并确保其中带有忽略 `.migration/` 的 `.gitignore`,\r\n * 防止迁移产物被工作区上层的 Git 仓库提交/推送到远端。\r\n * 可重复调用;不会破坏 `.gitignore` 中的无关内容。\r\n */\r\nexport function ensureMigrationWorkspace(project: string): string {\r\n const workspaceRoot = migrationWorkspaceRoot(project);\r\n fs.mkdirSync(workspaceRoot, { recursive: true });\r\n const gitignorePath = path.join(workspaceRoot, \".gitignore\");\r\n let current = \"\";\r\n try {\r\n current = fs.readFileSync(gitignorePath, \"utf8\");\r\n } catch {\r\n // 尚无 .gitignore\r\n }\r\n if (!current.split(/\\r?\\n/).some((line) => line.trim() === \".migration/\")) {\r\n const prefix = current && !current.endsWith(\"\\n\") ? `${current}\\n` : current;\r\n fs.writeFileSync(gitignorePath, `${prefix}.migration/\\n`, \"utf8\");\r\n }\r\n return workspaceRoot;\r\n}\r\n","#!/usr/bin/env node\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { migrationDirectory, migrationWorkspaceRoot } from \"../migration-paths.ts\";\r\nimport { REPORT_VERSION } from \"./source-governance.ts\";\r\n\r\nexport function initMigrationReport(argv: string[]) {\r\nconst projectRoot = path.resolve(argv[0] ?? \".\");\r\nconst migrationRoot = migrationDirectory(projectRoot);\r\nconst workspaceRoot = migrationWorkspaceRoot(projectRoot);\r\nconst specRoot = path.join(migrationRoot, \"spec\");\r\nconst reportRoot = path.join(migrationRoot, \"report\");\r\nconst indexPath = path.join(specRoot, \"index.json\");\r\nconst fail = (message) => { throw new Error(message); };\r\nconst readJson = (file) => JSON.parse(fs.readFileSync(file, \"utf8\"));\r\nconst writeJson = (file, value) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\"); };\r\nconst writeIfMissing = (file, value) => { if (fs.existsSync(file)) return false; writeJson(file, value); return true; };\r\nconst relReport = (file) => path.relative(reportRoot, file).replaceAll(\"\\\\\", \"/\");\r\nconst relProject = (file) => path.relative(workspaceRoot, file).replaceAll(\"\\\\\", \"/\");\r\nconst reportItemValues = (document) => [document.page, ...(document.controls ?? []), ...(document.entries ?? []), ...(document.interactions ?? []), ...(document.items ?? [])].filter(Boolean);\r\nconst confinedReportFile = (relative) => {\r\n if (typeof relative !== \"string\" || !relative.trim() || path.isAbsolute(relative)) fail(`Legacy report shard path must be report-relative: ${String(relative)}`);\r\n const absolute = path.resolve(reportRoot, relative);\r\n const relation = path.relative(reportRoot, absolute);\r\n if (!relation || relation === \"..\" || relation.startsWith(`..${path.sep}`) || path.isAbsolute(relation)) fail(`Legacy report shard escapes report root: ${relative}`);\r\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) fail(`Legacy report shard not found: ${relative}`);\r\n const realRoot = fs.realpathSync(reportRoot);\r\n const realFile = fs.realpathSync(absolute);\r\n const realRelation = path.relative(realRoot, realFile);\r\n if (realRelation === \"..\" || realRelation.startsWith(`..${path.sep}`) || path.isAbsolute(realRelation)) fail(`Legacy report shard resolves outside report root: ${relative}`);\r\n return realFile;\r\n};\r\n\r\nif (!fs.existsSync(indexPath)) fail(`Deterministic SPEC index not found: ${indexPath}`);\r\nconst specIndex = readJson(indexPath);\r\nif (specIndex.shardFormatVersion !== \"2.0.0\" || !specIndex.files?.facts) fail(\"report init requires deterministic SPEC facts in shardFormatVersion 2.0.0\");\r\nif (!specIndex.factsSha256) fail(\"SPEC index does not contain factsSha256\");\r\nconst specFile = (file) => path.join(specRoot, file);\r\nconst files = specIndex.files.facts;\r\nconst appFacts = readJson(specFile(files.app));\r\nconst pageIndex = readJson(specFile(files.pages));\r\nconst interactionFacts = readJson(specFile(files.interactions));\r\nconst unresolvedFacts = readJson(specFile(files.unresolved));\r\n\r\nconst reportIndexPath = path.join(reportRoot, \"index.json\");\r\nif (fs.existsSync(reportIndexPath)) {\r\n const previous = readJson(reportIndexPath);\r\n if (previous.baseline?.factsSha256 !== specIndex.factsSha256) fail(`Existing report targets facts ${previous.baseline?.factsSha256 ?? \"<unknown>\"}; current facts are ${specIndex.factsSha256}. Remove .migration/report or preserve it under another run.`);\r\n if (previous.reportVersion === \"1.1.0\") {\r\n const shardFiles = [\r\n ...(previous.pages ?? []).map((descriptor) => descriptor.file),\r\n previous.unassignedEntriesFile,\r\n previous.interactionsFile,\r\n previous.discoveriesFile,\r\n ].filter(Boolean);\r\n const migrationTargets = shardFiles.map((relative) => confinedReportFile(relative));\r\n let migratedFiles = 0;\r\n for (const file of migrationTargets) {\r\n const document = readJson(file);\r\n for (const value of reportItemValues(document)) if (!Array.isArray(value.sourceProvenance)) value.sourceProvenance = [];\r\n if (document.reportShardVersion === \"1.1.0\") document.reportShardVersion = REPORT_VERSION;\r\n writeJson(file, document);\r\n migratedFiles++;\r\n }\r\n previous.reportVersion = REPORT_VERSION;\r\n writeJson(reportIndexPath, previous);\r\n return { status: \"passed\", reportRoot, reportVersion: REPORT_VERSION, migratedFrom: \"1.1.0\", migratedFiles };\r\n }\r\n if (previous.reportVersion === REPORT_VERSION) {\r\n // Direct callers may safely refresh deterministic index metadata; existing shards remain untouched.\r\n } else {\r\n fail(`Existing report uses unsupported version ${previous.reportVersion ?? \"<unknown>\"}; move .migration/report before creating the ${REPORT_VERSION} report.`);\r\n }\r\n}\r\n\r\nconst item = (ref, kind, factLabel, extra = {}) => ({\r\n ref,\r\n kind,\r\n factLabel: factLabel || ref,\r\n ...extra,\r\n status: \"pending\",\r\n harmonyosFiles: [],\r\n sourceProvenance: [],\r\n testEvidence: [],\r\n difference: null\r\n});\r\n\r\nlet createdFiles = 0;\r\nlet pageCount = 0;\r\nlet controlCount = 0;\r\nlet entryCount = 0;\r\nconst pages = [];\r\nfor (const descriptor of pageIndex.pages ?? []) {\r\n const factPath = specFile(descriptor.file);\r\n const facts = readJson(factPath);\r\n if (!facts.surface?.surfaceRef) fail(`Invalid surface facts shard: ${factPath}`);\r\n const output = path.join(reportRoot, \"pages\", path.basename(descriptor.file));\r\n const controlRefByCarrier = new Map((facts.controls ?? []).map((value) => [value.sourceCarrierRef, value.controlRef]));\r\n const shard = {\r\n reportShardVersion: REPORT_VERSION, kind: \"page-report\", factsFile: relProject(factPath),\r\n page: item(facts.surface.surfaceRef, \"page\", facts.surface.surfaceName),\r\n controls: (facts.controls ?? []).map((value) => item(value.controlRef, \"control\", value.name)),\r\n entries: (facts.entries ?? []).map((value) => item(\r\n value.entryRef,\r\n \"entry\",\r\n value.displayLabel || value.event || value.entryRef,\r\n { controlRef: controlRefByCarrier.get(value.carrierRef) ?? null }\r\n ))\r\n };\r\n if (writeIfMissing(output, shard)) createdFiles++;\r\n pages.push({ surfaceRef: facts.surface.surfaceRef, file: relReport(output) });\r\n pageCount++; controlCount += shard.controls.length; entryCount += shard.entries.length;\r\n}\r\n\r\nlet unassignedEntriesFile = null;\r\nif (pageIndex.unassignedEntriesFile) {\r\n const factPath = specFile(pageIndex.unassignedEntriesFile);\r\n const facts = readJson(factPath);\r\n const output = path.join(reportRoot, \"pages\", \"unassigned.json\");\r\n const shard = { reportShardVersion: REPORT_VERSION, kind: \"unassigned-entry-report\", factsFile: relProject(factPath), entries: (facts.entries ?? []).map((value) => item(value.entryRef, \"entry\", value.displayLabel || value.event || value.entryRef, { controlRef: null })) };\r\n if (writeIfMissing(output, shard)) createdFiles++;\r\n unassignedEntriesFile = relReport(output); entryCount += shard.entries.length;\r\n}\r\n\r\nconst interactionsPath = path.join(reportRoot, \"interactions.json\");\r\nif (writeIfMissing(interactionsPath, { reportShardVersion: REPORT_VERSION, kind: \"interaction-report\", factsFile: relProject(specFile(files.interactions)), interactions: (interactionFacts.interactions ?? []).map((value) => item(value.id, \"interaction\", value.displayLabel || value.type || value.kind || value.id)) })) createdFiles++;\r\nconst unresolvedPath = path.join(reportRoot, \"unresolved.json\");\r\nif (writeIfMissing(unresolvedPath, { reportShardVersion: \"1.0.0\", kind: \"unresolved-report\", factsFile: relProject(specFile(files.unresolved)), reviews: (unresolvedFacts.facts ?? []).map((value) => ({ unresolvedRef: value.id, decision: \"pending\", reason: null, relatedRefs: [] })) })) createdFiles++;\r\nconst discoveriesPath = path.join(reportRoot, \"discoveries.json\");\r\nif (writeIfMissing(discoveriesPath, { reportShardVersion: REPORT_VERSION, kind: \"ai-discoveries\", items: [] })) createdFiles++;\r\nconst summaryPath = path.join(reportRoot, \"summary.json\");\r\nif (writeIfMissing(summaryPath, { summary: \"\", incomplete: [], nextSteps: [], additionalSections: [] })) createdFiles++;\r\nconst acceptancePath = path.join(reportRoot, \"final-acceptance.json\");\r\nif (writeIfMissing(acceptancePath, { reportShardVersion: \"1.2.0\", kind: \"final-acceptance\", status: \"pending\", tests: [], blockers: [], notes: [] })) createdFiles++;\r\n\r\nconst dimension = (required) => ({ required, pending: required, implemented: 0, verified: 0, blocked: 0 });\r\nconst counts = { page: pageCount, control: controlCount, entry: entryCount, interaction: (interactionFacts.interactions ?? []).length, unresolved: (unresolvedFacts.facts ?? []).length };\r\nconst total = counts.page + counts.control + counts.entry + counts.interaction;\r\nwriteJson(reportIndexPath, {\r\n reportVersion: REPORT_VERSION,\r\n baseline: { specIndex: \".migration/spec/index.json\", specVersion: specIndex.specVersion, factsSha256: specIndex.factsSha256 },\r\n app: { factRef: \"app\", factsFile: relProject(specFile(files.app)), factLabel: appFacts.app?.name ?? \"Android application\", status: \"pending\" },\r\n status: \"in-progress\", pages, unassignedEntriesFile,\r\n interactionsFile: relReport(interactionsPath), unresolvedFile: relReport(unresolvedPath), discoveriesFile: relReport(discoveriesPath), summaryFile: relReport(summaryPath), finalAcceptanceFile: relReport(acceptancePath),\r\n coverage: { page: dimension(counts.page), control: dimension(counts.control), entry: dimension(counts.entry), interaction: dimension(counts.interaction), overall: dimension(total) }\r\n});\r\n\r\nreturn { ok: true, input: indexPath, reportRoot, createdFiles, factsSha256: specIndex.factsSha256, appName: appFacts.app?.name ?? null, counts };\r\n}\r\n","import { createHash } from \"node:crypto\";\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { migrationDirectory, migrationWorkspaceRoot } from \"../migration-paths.ts\";\r\n\r\nexport const REPORT_VERSION = \"1.2.0\" as const;\r\nexport const SOURCE_PROVENANCE_LEVEL = \"declared-hash-validated\" as const;\r\n\r\nexport interface SourceRange {\r\n symbol: string;\r\n startLine: number;\r\n endLine: number;\r\n}\r\n\r\nexport interface SourceProvenance {\r\n androidFile: string;\r\n fileSha256: string;\r\n ranges?: SourceRange[];\r\n}\r\n\r\nexport type SourceOrderAuditStatus = \"passed\" | \"red-flag\" | \"unavailable\";\r\n\r\nexport interface SourceOrderAudit {\r\n auditVersion: \"1.0.0\";\r\n status: SourceOrderAuditStatus;\r\n eventSource: string;\r\n auditedRefs: string[];\r\n findings: string[];\r\n}\r\n\r\nexport interface LiteralDriftAudit {\r\n auditVersion: \"1.0.0\";\r\n status: \"passed\" | \"warning\" | \"not-applicable\";\r\n sampleSeed: string;\r\n sampledRefs: string[];\r\n warnings: string[];\r\n}\r\n\r\nexport interface ManagedSourceManifest {\r\n manifestVersion: \"1.0.0\";\r\n androidRoot: string;\r\n members: Array<{ androidFile: string; fileSha256: string }>;\r\n manifestSha256: string;\r\n}\r\n\r\nexport interface SourceClosureAudit {\r\n auditVersion: \"1.0.0\";\r\n status: \"passed\" | \"red-flag\" | \"unavailable\";\r\n auditedRefs: string[];\r\n findings: string[];\r\n}\r\n\r\ninterface SourceEvent {\r\n sourceEventVersion: \"1.0.0\";\r\n sessionId: string;\r\n epochId: string;\r\n sequence: number;\r\n action: \"read\" | \"write\";\r\n file: string;\r\n reportRefs: string[];\r\n parallelGroup: string | null;\r\n}\r\n\r\nconst ignoredSourceParts = new Set([\".git\", \".gradle\", \".hvigor\", \".idea\", \".migration\", \".codegraph-appgraph\", \"build\", \"node_modules\", \"oh_modules\"]);\r\n\r\nfunction readJson(file: string): any | null {\r\n try { return JSON.parse(fs.readFileSync(file, \"utf8\")); }\r\n catch { return null; }\r\n}\r\n\r\nexport function sourceRoots(projectRootArgument: string): { projectRoot: string; androidRoot: string; harmonyRoot: string } {\r\n const projectRoot = path.resolve(projectRootArgument);\r\n const config = readJson(path.join(migrationDirectory(projectRoot), \"config.json\"));\r\n const androidRoot = path.resolve(projectRoot, config?.androidProject ?? projectRoot);\r\n const harmonyRoot = path.resolve(projectRoot, config?.harmonyProject ?? \"ohos\");\r\n return { projectRoot, androidRoot, harmonyRoot };\r\n}\r\n\r\nfunction inside(root: string, absolute: string): boolean {\r\n const relative = path.relative(root, absolute);\r\n return relative === \"\" || (!relative.startsWith(`..${path.sep}`) && relative !== \"..\" && !path.isAbsolute(relative));\r\n}\r\n\r\nfunction sourceFile(projectRoot: string, value: string): { absolute: string; relative: string } {\r\n if (typeof value !== \"string\" || !value.trim()) throw new Error(\"Android source path must be a non-empty string\");\r\n const { androidRoot, harmonyRoot } = sourceRoots(projectRoot);\r\n const absolute = path.resolve(androidRoot, value);\r\n if (!inside(androidRoot, absolute)) throw new Error(`Android source must stay inside the managed Android project: ${value}`);\r\n if (inside(harmonyRoot, absolute)) throw new Error(`Android source cannot point into the HarmonyOS project: ${value}`);\r\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) throw new Error(`Android source file not found: ${value}`);\r\n const realRoot = fs.realpathSync(androidRoot);\r\n const realFile = fs.realpathSync(absolute);\r\n if (!inside(realRoot, realFile)) throw new Error(`Android source resolves outside the managed Android project: ${value}`);\r\n const relative = path.relative(androidRoot, absolute).replaceAll(\"\\\\\", \"/\");\r\n if (relative.split(\"/\").some((part) => ignoredSourceParts.has(part))) throw new Error(`Android source is outside the managed source list: ${value}`);\r\n return { absolute, relative };\r\n}\r\n\r\nexport function managedHarmonyFile(projectRootArgument: string, value: string): { absolute: string; relative: string } {\r\n if (typeof value !== \"string\" || !value.trim()) throw new Error(\"HarmonyOS path must be a non-empty string\");\r\n const { projectRoot, harmonyRoot } = sourceRoots(projectRootArgument);\r\n const absolute = path.resolve(projectRoot, value);\r\n if (!inside(harmonyRoot, absolute)) throw new Error(`HarmonyOS file must stay inside the configured HarmonyOS project: ${value}`);\r\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) throw new Error(`HarmonyOS file not found: ${value}`);\r\n if (!fs.existsSync(harmonyRoot) || !fs.statSync(harmonyRoot).isDirectory()) throw new Error(`Configured HarmonyOS project not found: ${harmonyRoot}`);\r\n const realRoot = fs.realpathSync(harmonyRoot);\r\n const realFile = fs.realpathSync(absolute);\r\n if (!inside(realRoot, realFile)) throw new Error(`HarmonyOS file resolves outside the configured HarmonyOS project: ${value}`);\r\n return { absolute, relative: path.relative(projectRoot, absolute).replaceAll(\"\\\\\", \"/\") };\r\n}\r\n\r\nexport function sha256File(file: string): string {\r\n return createHash(\"sha256\").update(fs.readFileSync(file)).digest(\"hex\");\r\n}\r\n\r\nexport function provenanceForFiles(projectRoot: string, values: string[]): SourceProvenance[] {\r\n const result = new Map<string, SourceProvenance>();\r\n for (const value of values) {\r\n const source = sourceFile(projectRoot, value);\r\n result.set(source.relative, { androidFile: source.relative, fileSha256: sha256File(source.absolute) });\r\n }\r\n return [...result.values()].sort((left, right) => left.androidFile.localeCompare(right.androidFile));\r\n}\r\n\r\nexport function managedSourceManifest(projectRootArgument: string): ManagedSourceManifest {\r\n const { projectRoot, androidRoot, harmonyRoot } = sourceRoots(projectRootArgument);\r\n if (!fs.existsSync(androidRoot) || !fs.statSync(androidRoot).isDirectory()) throw new Error(`Managed Android project not found: ${androidRoot}`);\r\n const members: Array<{ androidFile: string; fileSha256: string }> = [];\r\n const visit = (directory: string) => {\r\n for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {\r\n if (ignoredSourceParts.has(entry.name)) continue;\r\n const absolute = path.join(directory, entry.name);\r\n if (inside(harmonyRoot, absolute)) continue;\r\n if (entry.isSymbolicLink()) continue;\r\n if (entry.isDirectory()) visit(absolute);\r\n else if (entry.isFile()) {\r\n const managed = sourceFile(projectRoot, path.relative(androidRoot, absolute));\r\n members.push({ androidFile: managed.relative, fileSha256: sha256File(managed.absolute) });\r\n }\r\n }\r\n };\r\n visit(androidRoot);\r\n members.sort((left, right) => left.androidFile.localeCompare(right.androidFile));\r\n const androidRootRelative = path.relative(projectRoot, androidRoot).replaceAll(\"\\\\\", \"/\") || \".\";\r\n const material = { manifestVersion: \"1.0.0\" as const, androidRoot: androidRootRelative, members };\r\n return { ...material, manifestSha256: createHash(\"sha256\").update(JSON.stringify(material)).digest(\"hex\") };\r\n}\r\n\r\nexport function writeManagedSourceManifest(projectRootArgument: string, manifest: ManagedSourceManifest): string {\r\n const projectRoot = path.resolve(projectRootArgument);\r\n const file = path.join(migrationDirectory(projectRoot), \"audit\", \"android-source-manifest.json\");\r\n fs.mkdirSync(path.dirname(file), { recursive: true });\r\n fs.writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\");\r\n return path.relative(migrationWorkspaceRoot(projectRoot), file).replaceAll(\"\\\\\", \"/\");\r\n}\r\n\r\nexport function validateSourceProvenance(projectRoot: string, value: unknown, label: string): string[] {\r\n const errors: string[] = [];\r\n if (!Array.isArray(value)) return [`${label}: sourceProvenance must be an array`];\r\n const seen = new Set<string>();\r\n for (const [index, candidate] of value.entries()) {\r\n const location = `${label}: sourceProvenance[${index}]`;\r\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) {\r\n errors.push(`${location} must be an object`);\r\n continue;\r\n }\r\n const item = candidate as Record<string, any>;\r\n if (typeof item.androidFile !== \"string\" || !item.androidFile.trim()) {\r\n errors.push(`${location}.androidFile is required`);\r\n continue;\r\n }\r\n if (seen.has(item.androidFile)) errors.push(`${location}: duplicate Android source ${item.androidFile}`);\r\n seen.add(item.androidFile);\r\n let source: { absolute: string; relative: string } | null = null;\r\n try { source = sourceFile(projectRoot, item.androidFile); }\r\n catch (error) { errors.push(`${location}: ${error instanceof Error ? error.message : String(error)}`); }\r\n if (!/^[a-f0-9]{64}$/.test(item.fileSha256 ?? \"\")) errors.push(`${location}.fileSha256 must be a lowercase SHA-256`);\r\n if (source && /^[a-f0-9]{64}$/.test(item.fileSha256 ?? \"\")) {\r\n const current = sha256File(source.absolute);\r\n if (current !== item.fileSha256) errors.push(`${location}: sourceProvenance hash mismatch for ${item.androidFile}; expected current ${current}`);\r\n }\r\n if (item.ranges !== undefined) {\r\n if (!Array.isArray(item.ranges) || item.ranges.length === 0) {\r\n errors.push(`${location}.ranges must be a non-empty array when present`);\r\n } else if (source) {\r\n const lines = fs.readFileSync(source.absolute, \"utf8\").split(/\\r?\\n/);\r\n for (const [rangeIndex, range] of item.ranges.entries()) {\r\n const rangeLabel = `${location}.ranges[${rangeIndex}]`;\r\n if (!range || typeof range !== \"object\" || Array.isArray(range)) { errors.push(`${rangeLabel} must be an object`); continue; }\r\n if (typeof range.symbol !== \"string\" || !range.symbol.trim()) errors.push(`${rangeLabel}.symbol is required`);\r\n if (!Number.isInteger(range.startLine) || range.startLine < 1 || !Number.isInteger(range.endLine) || range.endLine < range.startLine || range.endLine > lines.length) {\r\n errors.push(`${rangeLabel} is outside ${item.androidFile}`);\r\n } else if (typeof range.symbol === \"string\" && range.symbol.trim()) {\r\n const excerpt = lines.slice(range.startLine - 1, range.endLine).join(\"\\n\");\r\n const escaped = range.symbol.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\r\n const extension = path.extname(source.absolute).toLowerCase();\r\n const located = extension === \".kt\"\r\n ? new RegExp(`\\\\b(?:class|object|interface|fun|val|var)\\\\s+${escaped}\\\\b`).test(excerpt)\r\n : (() => { if (extension === \".java\") return new RegExp(`\\\\b(?:class|interface|enum|record)\\\\s+${escaped}\\\\b|\\\\b[A-Za-z_$][\\\\w$<>, ?\\\\[\\\\].]*\\\\s+${escaped}\\\\s*\\\\(`).test(excerpt); return (() => { if (extension === \".xml\") return new RegExp(`(?:@\\\\+?id/|\\\\bname\\\\s*=\\\\s*[\"'])${escaped}\\\\b`).test(excerpt); return false; })(); })();\r\n if (!located) errors.push(`${rangeLabel}: symbol ${range.symbol} cannot be deterministically located in the declared ${extension || \"file\"} range; omit ranges to cite the whole file`);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return errors;\r\n}\r\n\r\nfunction eventPath(value: unknown): string | null {\r\n if (typeof value !== \"string\" || !value.trim() || path.isAbsolute(value)) return null;\r\n const normalized = value.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\//, \"\");\r\n if (!normalized || normalized.split(\"/\").includes(\"..\")) return null;\r\n return normalized;\r\n}\r\n\r\nfunction parseSourceEvents(file: string): { events: SourceEvent[]; findings: string[] } {\r\n const events: SourceEvent[] = [];\r\n const findings: string[] = [];\r\n const seen = new Set<string>();\r\n for (const [index, line] of fs.readFileSync(file, \"utf8\").split(/\\r?\\n/).entries()) {\r\n if (!line.trim()) continue;\r\n let value: any;\r\n try { value = JSON.parse(line); }\r\n catch { findings.push(`event line ${index + 1} is not valid JSON`); continue; }\r\n const label = `event line ${index + 1}`;\r\n if (value?.sourceEventVersion !== \"1.0.0\") findings.push(`${label}: sourceEventVersion must be 1.0.0`);\r\n if (typeof value?.sessionId !== \"string\" || !value.sessionId.trim()) findings.push(`${label}: sessionId is required`);\r\n if (typeof value?.epochId !== \"string\" || !value.epochId.trim()) findings.push(`${label}: epochId is required`);\r\n if (!Number.isInteger(value?.sequence) || value.sequence < 0) findings.push(`${label}: sequence must be a non-negative integer`);\r\n if (!new Set([\"read\", \"write\"]).has(value?.action)) findings.push(`${label}: action must be read or write`);\r\n const normalizedFile = eventPath(value?.file);\r\n if (!normalizedFile) findings.push(`${label}: file must be a project-relative path`);\r\n if (!Array.isArray(value?.reportRefs) || value.reportRefs.length === 0 || value.reportRefs.some((ref: unknown) => typeof ref !== \"string\" || !ref.trim())) findings.push(`${label}: reportRefs must contain at least one ref`);\r\n if (value?.parallelGroup !== null && value?.parallelGroup !== undefined && (typeof value.parallelGroup !== \"string\" || !value.parallelGroup.trim())) findings.push(`${label}: parallelGroup must be a non-empty string or null`);\r\n const key = `${value?.sessionId}:${value?.epochId}:${value?.sequence}`;\r\n if (seen.has(key)) findings.push(`${label}: duplicate sequence within session/epoch`);\r\n seen.add(key);\r\n if (findings.some((finding) => finding.startsWith(`${label}:`) || finding === `${label} is not valid JSON`)) continue;\r\n events.push({ ...value, file: normalizedFile, parallelGroup: value.parallelGroup ?? null });\r\n }\r\n return { events, findings };\r\n}\r\n\r\nexport function auditSourceOrder(projectRootArgument: string, items: any[], options: { trusted?: boolean } = {}): SourceOrderAudit {\r\n const projectRoot = path.resolve(projectRootArgument);\r\n const eventSource = \".migration/audit/source-events.jsonl\";\r\n const eventFile = path.join(migrationWorkspaceRoot(projectRoot), eventSource);\r\n const auditable = items.filter((item) => [\"implemented\", \"verified\"].includes(item?.status));\r\n if (!options.trusted || !fs.existsSync(eventFile)) {\r\n return {\r\n auditVersion: \"1.0.0\",\r\n status: \"unavailable\",\r\n eventSource,\r\n auditedRefs: [],\r\n findings: [options.trusted\r\n ? \"trusted ordered Read/Write events are unavailable; only declared hashes can be validated\"\r\n : `${(() => { if (fs.existsSync(eventFile)) return \"project-local event file is not a trusted runner source; \"; return \"\"; })()}trusted ordered Read/Write events are unavailable; only declared hashes can be validated`],\r\n };\r\n }\r\n const parsed = parseSourceEvents(eventFile);\r\n const findings = [...parsed.findings];\r\n const auditedRefs: string[] = [];\r\n for (const item of auditable) {\r\n const events = parsed.events.filter((event) => event.reportRefs.includes(item.ref));\r\n const groups = new Map<string, SourceEvent[]>();\r\n for (const event of events) {\r\n const key = `${event.sessionId}\\u0000${event.epochId}`;\r\n groups.set(key, [...(groups.get(key) ?? []), event]);\r\n }\r\n const writeGroups = [...groups.values()].filter((group) => group.some((event) => event.action === \"write\" && (item.harmonyosFiles ?? []).includes(event.file)));\r\n if (writeGroups.length === 0) {\r\n findings.push(`${item.ref}: no ordered write event matches the declared HarmonyOS files`);\r\n continue;\r\n }\r\n let refPassed = true;\r\n const declaredSources = new Set((item.sourceProvenance ?? []).map((entry: any) => entry.androidFile));\r\n for (const group of writeGroups) {\r\n const ordered = [...group].sort((left, right) => left.sequence - right.sequence);\r\n const firstWrite = ordered.find((event) => event.action === \"write\" && (item.harmonyosFiles ?? []).includes(event.file))!;\r\n const observedManagedSources = new Set(ordered.filter((event) => event.action === \"read\").flatMap((event) => {\r\n try { return [sourceFile(projectRoot, event.file).relative]; } catch { return []; }\r\n }));\r\n const extra = [...observedManagedSources].filter((source) => !declaredSources.has(source));\r\n if (extra.length) {\r\n findings.push(`${item.ref}: runner read set contains managed Android sources missing from sourceProvenance: ${extra.sort().join(\", \")}`);\r\n refPassed = false;\r\n }\r\n for (const source of declaredSources) {\r\n const reads = ordered.filter((event) => event.action === \"read\" && event.file === source);\r\n if (reads.length === 0) {\r\n findings.push(`${item.ref}: no read event for declared Android source ${source} in session ${firstWrite.sessionId} epoch ${firstWrite.epochId}`);\r\n refPassed = false;\r\n continue;\r\n }\r\n const usable = reads.find((read) => read.sequence < firstWrite.sequence\r\n && (!read.parallelGroup || !firstWrite.parallelGroup || read.parallelGroup !== firstWrite.parallelGroup));\r\n if (!usable) {\r\n const sameParallelGroup = reads.some((read) => read.parallelGroup && read.parallelGroup === firstWrite.parallelGroup);\r\n findings.push(`${item.ref}: ${source} was not read before the first write in session ${firstWrite.sessionId} epoch ${firstWrite.epochId}${sameParallelGroup ? \" and Read/Write share the same parallel action group\" : \"\"}`);\r\n refPassed = false;\r\n }\r\n }\r\n }\r\n if (refPassed) auditedRefs.push(item.ref);\r\n }\r\n return {\r\n auditVersion: \"1.0.0\",\r\n status: findings.length === 0 ? \"passed\" : \"red-flag\",\r\n eventSource,\r\n auditedRefs: [...new Set(auditedRefs)].sort(),\r\n findings,\r\n };\r\n}\r\n\r\nexport function auditSourceClosure(projectRootArgument: string, items: any[]): SourceClosureAudit {\r\n const projectRoot = path.resolve(projectRootArgument);\r\n const tasksRoot = path.join(migrationDirectory(projectRoot), \"tasks\");\r\n const executionGraph = path.join(tasksRoot, \"execution-graph.json\");\r\n const graph = readJson(fs.existsSync(executionGraph) ? executionGraph : path.join(tasksRoot, \"graph.json\"));\r\n const auditable = items.filter((item) => [\"implemented\", \"verified\"].includes(item?.status) && item?.kind !== \"feature\");\r\n if (!graph || !Array.isArray(graph.tasks)) return { auditVersion: \"1.0.0\", status: \"unavailable\", auditedRefs: [], findings: [\"Task Plan source closure is unavailable; sourceProvenance hashes remain enforceable\"] };\r\n const findings: string[] = [];\r\n const auditedRefs: string[] = [];\r\n for (const item of auditable) {\r\n const tasks = graph.tasks.filter((task: any) => Array.isArray(task?.acceptance?.reportRefs) && task.acceptance.reportRefs.includes(item.ref));\r\n if (tasks.length === 0) {\r\n findings.push(`${item.ref}: no Task Plan closure maps this report ref`);\r\n continue;\r\n }\r\n const closureSources = new Set<string>();\r\n for (const task of tasks) {\r\n const candidates = [\r\n ...(task?.closure?.sourceEvidence ?? []).map((value: any) => value?.file),\r\n ...(task?.closure?.codeRefs ?? []).map((value: any) => value?.file),\r\n ];\r\n for (const candidate of candidates) {\r\n if (typeof candidate !== \"string\") continue;\r\n try { closureSources.add(sourceFile(projectRoot, candidate).relative); } catch { /* non-source indexes do not enter the managed closure */ }\r\n }\r\n }\r\n const declared = new Set((item.sourceProvenance ?? []).map((value: any) => value.androidFile));\r\n const missing = [...closureSources].filter((file) => !declared.has(file));\r\n if (missing.length) findings.push(`${item.ref}: Task Plan source closure members missing from sourceProvenance: ${missing.sort().join(\", \")}`);\r\n else auditedRefs.push(item.ref);\r\n }\r\n const mappedFindings = findings.filter((finding) => finding.includes(\"members missing\"));\r\n return { auditVersion: \"1.0.0\", status: mappedFindings.length ? \"red-flag\" : ((() => { if (auditedRefs.length === auditable.length) return \"passed\"; return \"unavailable\"; })()), auditedRefs: [...new Set(auditedRefs)].sort(), findings };\r\n}\r\n\r\nexport function writeSourceOrderAudit(projectRootArgument: string, audit: SourceOrderAudit): string {\r\n const projectRoot = path.resolve(projectRootArgument);\r\n const file = path.join(migrationDirectory(projectRoot), \"audit\", \"source-order-audit.json\");\r\n fs.mkdirSync(path.dirname(file), { recursive: true });\r\n fs.writeFileSync(file, `${JSON.stringify(audit, null, 2)}\\n`, \"utf8\");\r\n return path.relative(migrationWorkspaceRoot(projectRoot), file).replaceAll(\"\\\\\", \"/\");\r\n}\r\n\r\nfunction sourceLiterals(content: string): string[] {\r\n const values = new Set<string>();\r\n for (const match of content.matchAll(/([\"'`])([^\"'`\\r\\n]{2,120})\\1/g)) {\r\n const value = match[2].trim();\r\n if (value.length >= 2 && !/^https?:\\/\\//.test(value) && !/^[A-Za-z0-9_.\\/-]+\\.(?:kt|java|xml|ets|ts)$/.test(value)) values.add(value);\r\n }\r\n for (const match of content.matchAll(/#[0-9a-fA-F]{3,8}\\b|\\b\\d+(?:\\.\\d+)?(?:dp|sp|px|vp|fp)\\b/g)) values.add(match[0]);\r\n for (const match of content.matchAll(/\\b(?:if|when|switch)\\s*\\(([^)\\r\\n]{1,160})\\)/g)) values.add(match[1].replace(/\\s+/g, \" \").trim());\r\n return [...values].sort();\r\n}\r\n\r\nexport function auditLiteralDrift(projectRootArgument: string, items: any[], factsSha256: string): LiteralDriftAudit {\r\n const projectRoot = path.resolve(projectRootArgument);\r\n const candidates = items.filter((item) => [\"implemented\", \"verified\"].includes(item?.status)\r\n && (item.sourceProvenance ?? []).length > 0 && (item.harmonyosFiles ?? []).length > 0);\r\n const sample = candidates\r\n .map((item) => ({ item, rank: createHash(\"sha256\").update(`${factsSha256}:${item.ref}`).digest(\"hex\") }))\r\n .sort((left, right) => left.rank.localeCompare(right.rank) || left.item.ref.localeCompare(right.item.ref))\r\n .slice(0, 5)\r\n .map(({ item }) => item);\r\n if (sample.length === 0) return { auditVersion: \"1.0.0\", status: \"not-applicable\", sampleSeed: factsSha256, sampledRefs: [], warnings: [] };\r\n const warnings: string[] = [];\r\n for (const item of sample) {\r\n const harmony = (item.harmonyosFiles ?? []).map((file: string) => {\r\n try { return fs.readFileSync(managedHarmonyFile(projectRoot, file).absolute, \"utf8\"); }\r\n catch { return \"\"; }\r\n }).join(\"\\n\");\r\n for (const provenance of item.sourceProvenance ?? []) {\r\n let source: { absolute: string; relative: string };\r\n try { source = sourceFile(projectRoot, provenance.androidFile); }\r\n catch { continue; }\r\n for (const literal of sourceLiterals(fs.readFileSync(source.absolute, \"utf8\"))) {\r\n if (!harmony.includes(literal)) warnings.push(`${item.ref}: Android literal ${JSON.stringify(literal)} from ${provenance.androidFile} is absent from declared HarmonyOS files`);\r\n }\r\n }\r\n }\r\n warnings.sort();\r\n return {\r\n auditVersion: \"1.0.0\",\r\n status: warnings.length ? \"warning\" : \"passed\",\r\n sampleSeed: factsSha256,\r\n sampledRefs: sample.map((item) => item.ref).sort(),\r\n warnings,\r\n };\r\n}\r\n\r\nexport function writeLiteralDriftAudit(projectRootArgument: string, audit: LiteralDriftAudit): string {\r\n const projectRoot = path.resolve(projectRootArgument);\r\n const file = path.join(migrationDirectory(projectRoot), \"audit\", \"literal-drift-audit.json\");\r\n fs.mkdirSync(path.dirname(file), { recursive: true });\r\n fs.writeFileSync(file, `${JSON.stringify(audit, null, 2)}\\n`, \"utf8\");\r\n return path.relative(migrationWorkspaceRoot(projectRoot), file).replaceAll(\"\\\\\", \"/\");\r\n}\r\n","// @ts-nocheck\r\nimport { createHash } from \"node:crypto\";\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { buildUiSpecGraph } from \"./lib/ui-spec-graph.ts\";\r\nimport { validateSpecShards, writeSpecShards } from \"./lib/spec-shards.ts\";\r\n\r\nexport function initializeSpec(argv: string[]) {\r\nconst [analysisPath, outputPath, sourceRevisionArgument, projectRootArgument] = argv;\r\nif (!analysisPath || !outputPath) {\r\n throw new Error(\"initialize-spec requires <appgraph-analysis.json> <spec-directory> [source-revision] [project-root]\");\r\n}\r\n\r\nconst canonical = (value) => JSON.stringify(value, (_, item) => {\r\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return item;\r\n return Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]]));\r\n});\r\nconst sha256 = (value) => createHash(\"sha256\").update(typeof value === \"string\" ? value : canonical(value)).digest(\"hex\");\r\nconst evidence = (items = []) => items.map((item) => ({\r\n file: item.file,\r\n symbol: item.symbol ?? null,\r\n line: Number.isInteger(item.line) ? item.line : null,\r\n endLine: Number.isInteger(item.endLine) ? item.endLine : null,\r\n}));\r\nconst refs = (items = []) => [...new Set(items.filter((item) => typeof item === \"string\" && item.length > 0))].sort();\r\n\r\nconst graph = JSON.parse(fs.readFileSync(path.resolve(analysisPath), \"utf8\"));\r\nif (!Number.isInteger(graph.schemaVersion) || !graph.source?.app || !Array.isArray(graph.surfaces) || !Array.isArray(graph.entries) || !Array.isArray(graph.edges) || !Array.isArray(graph.unresolved)) {\r\n throw new Error(\"AppGraph analysis is missing schemaVersion, source.app, surfaces, entries, edges, or unresolved facts\");\r\n}\r\nconst knownSurfaceRefs = new Set(graph.surfaces.map((surface) => surface.surfaceRef));\r\n\r\nconst findLauncherNames = (projectRoot) => {\r\n if (!projectRoot || !fs.existsSync(projectRoot)) return [];\r\n const manifests = [];\r\n const visit = (directory) => {\r\n for (const item of fs.readdirSync(directory, { withFileTypes: true })) {\r\n if ([\".git\", \".gradle\", \"build\", \"node_modules\"].includes(item.name)) continue;\r\n const target = path.join(directory, item.name);\r\n if (item.isDirectory()) visit(target);\r\n else if (item.name === \"AndroidManifest.xml\") manifests.push(target);\r\n }\r\n };\r\n visit(path.resolve(projectRoot));\r\n const names = [];\r\n for (const manifest of manifests) {\r\n const xml = fs.readFileSync(manifest, \"utf8\");\r\n for (const match of xml.matchAll(/<activity(?:-alias)?\\b([^>]*)>([\\s\\S]*?)<\\/activity(?:-alias)>/g)) {\r\n if (!/android\\.intent\\.action\\.MAIN/.test(match[2]) || !/android\\.intent\\.category\\.LAUNCHER/.test(match[2])) continue;\r\n const name = match[1].match(/android:name\\s*=\\s*[\"']([^\"']+)[\"']/)?.[1];\r\n if (name) names.push(name);\r\n }\r\n }\r\n return [...new Set(names)];\r\n};\r\n\r\nconst facts = {\r\n schemaVersion: graph.schemaVersion,\r\n app: {\r\n name: graph.source.app.name,\r\n packageName: graph.source.app.packageName ?? \"\",\r\n platform: \"android\",\r\n appGraphHash: graph.source.appGraphHash,\r\n },\r\n surfaces: graph.surfaces.map((surface) => ({\r\n surfaceRef: surface.surfaceRef,\r\n surfaceName: surface.surfaceName,\r\n surfaceType: surface.surfaceType,\r\n parentSurfaceRefs: refs(surface.parentSurfaceRefs),\r\n relation: \"hosts\",\r\n status: surface.status,\r\n sourceEvidence: evidence(surface.sourceEvidence),\r\n })),\r\n entries: graph.entries.map((entry) => ({\r\n entryRef: entry.entryRef,\r\n triggerCategory: entry.triggerCategory,\r\n componentType: entry.componentType,\r\n ownershipStatus: entry.ownershipStatus,\r\n // AppGraph may retain a control/carrier ref while explicitly marking UI\r\n // ownership unresolved. A carrier is not a UI surface; keep it in\r\n // carrierRef and expose the unresolved ownership instead of creating a\r\n // dangling surface reference.\r\n surfaceRef: knownSurfaceRefs.has(entry.surfaceRef) ? entry.surfaceRef : null,\r\n surfaceName: entry.surfaceName,\r\n surfaceType: entry.surfaceType,\r\n carrierRef: entry.carrierRef ?? null,\r\n carrierName: entry.carrierName,\r\n carrierStatus: entry.carrierStatus,\r\n event: entry.event,\r\n displayLabel: entry.displayLabel,\r\n handlerNames: refs(entry.handlerNames),\r\n callTrace: {\r\n handlerRefs: refs(entry.callTrace?.handlerRefs),\r\n codeRefs: entry.callTrace?.codeRefs ?? [],\r\n callEdges: entry.callTrace?.callEdges ?? [],\r\n truncated: entry.callTrace?.truncated === true,\r\n coverageWarnings: entry.callTrace?.coverageWarnings ?? [],\r\n },\r\n sourceEvidence: evidence(entry.sourceEvidence),\r\n warnings: entry.warnings ?? [],\r\n })),\r\n interactions: graph.edges.map((edge) => ({\r\n id: edge.id,\r\n relation: edge.relation,\r\n fromRef: edge.fromRef,\r\n toRef: edge.toRef,\r\n confidence: edge.confidence,\r\n sourceEvidence: evidence(edge.sourceEvidence),\r\n ...(edge.branchCondition ? { branchCondition: edge.branchCondition } : {}),\r\n })),\r\n unresolved: graph.unresolved.map((item) => ({\r\n id: item.id,\r\n kind: item.kind,\r\n ...(item.entryRef ? { entryRef: item.entryRef } : {}),\r\n ...(item.fromRef ? { fromRef: item.fromRef } : {}),\r\n ...(item.relation ? { relation: item.relation } : {}),\r\n ...(item.targetName ? { targetName: item.targetName } : {}),\r\n ...(item.candidateToRefs ? { candidateToRefs: refs(item.candidateToRefs) } : {}),\r\n ...(item.reason ? { reason: item.reason } : {}),\r\n ...(item.reasons ? { reasons: item.reasons } : {}),\r\n sourceEvidence: evidence(item.sourceEvidence),\r\n })),\r\n coverage: graph.coverage,\r\n warnings: graph.warnings ?? [],\r\n};\r\nfacts.uiGraph = buildUiSpecGraph(facts, findLauncherNames(projectRootArgument));\r\n\r\nconst spec = {\r\n specVersion: \"2.0.0\",\r\n language: \"zh-CN\",\r\n generation: {\r\n analyzer: \"appgraph\",\r\n analyzerVersion: graph.generatedBy?.ruleVersion ?? \"unknown\",\r\n sourceRevision: sourceRevisionArgument || null,\r\n generatedAt: new Date().toISOString(),\r\n factsSha256: sha256(facts),\r\n },\r\n facts,\r\n factCorrections: [],\r\n semantics: {\r\n app: { name: null, description: null, status: \"pending\" },\r\n surfaces: facts.surfaces.map((surface) => ({ surfaceRef: surface.surfaceRef, name: null, description: null, businessRole: null, status: \"pending\" })),\r\n controls: facts.uiGraph.controls.map((control) => ({ controlRef: control.controlRef, name: null, description: null, status: \"pending\" })),\r\n entries: facts.entries.map((entry) => ({ entryRef: entry.entryRef, name: null, description: null, userIntent: null, effectType: null, status: \"pending\" })),\r\n unresolvedReviews: facts.unresolved.map((item) => ({ unresolvedRef: item.id, decision: \"pending\", featureRef: null, reason: null })),\r\n },\r\n domains: [],\r\n features: [],\r\n exclusions: [],\r\n review: { status: \"skeleton\", reviewedAt: null, reviewedBy: null, notes: [] },\r\n};\r\n\r\nconst absoluteOutput = path.resolve(outputPath.endsWith(\".json\") ? path.dirname(outputPath) : outputPath);\r\nfs.mkdirSync(absoluteOutput, { recursive: true });\r\nfor (const legacy of [\"spec.json\", \"spec.raw.json\"]) fs.rmSync(path.join(absoluteOutput, legacy), { force: true });\r\nconst { index } = writeSpecShards(spec, absoluteOutput);\r\nconst shardErrors = validateSpecShards(absoluteOutput);\r\nif (shardErrors.length) throw new Error(`Generated SPEC shards are invalid:\\n${shardErrors.join(\"\\n\")}`);\r\nreturn { ok: true, output: path.join(absoluteOutput, \"index.json\"), specSha256: index.specSha256, factsSha256: spec.generation.factsSha256, counts: {\r\n surfaces: facts.surfaces.length,\r\n entries: facts.entries.length,\r\n interactions: index.counts.interactions,\r\n unresolved: facts.unresolved.length,\r\n} };\r\n}\r\n","// @ts-nocheck\r\nimport { createHash } from \"node:crypto\";\r\n\r\nconst UI_SURFACE_TYPES = new Set([\"activity\", \"fragment\", \"dialog\", \"compose\", \"xml-layout\", \"appyx-node\"]);\r\nconst UI_COMPONENT_TYPES = new Set([\"activity\", \"fragment\", \"dialog\", \"control\", \"page\", \"appyx-node\"]);\r\nconst RESULT_RELATIONS = new Set([\"opens\", \"navigates-to\", \"launches-for-result\"]);\r\nconst hash = (value) => createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 16);\r\nconst uniqueEvidence = (items = []) => [...new Map(items.filter(Boolean).map((item) => [`${item.file}:${item.symbol ?? \"\"}:${item.line ?? \"\"}:${item.endLine ?? \"\"}`, item])).values()];\r\n\r\nexport function buildUiSpecGraph(facts, launcherNames = []) {\r\n const uiSurfaces = facts.surfaces.filter((surface) => UI_SURFACE_TYPES.has(surface.surfaceType));\r\n const surfaceRefs = new Set(uiSurfaces.map((surface) => surface.surfaceRef));\r\n const launcherSet = new Set(launcherNames.map((name) => name.split(\".\").at(-1)));\r\n let roots = uiSurfaces.filter((surface) => surface.surfaceType === \"activity\" && launcherSet.has(surface.surfaceName)).map((surface) => surface.surfaceRef);\r\n if (!roots.length) roots = uiSurfaces.filter((surface) => surface.surfaceType === \"activity\" && surface.status === \"root\").map((surface) => surface.surfaceRef);\r\n\r\n const controls = new Map();\r\n const edges = [];\r\n const unresolved = [];\r\n const addEdge = (relation, fromRef, toRef) => edges.push({ id: hash(`${relation}:${fromRef}:${toRef}`), relation, fromRef, toRef });\r\n const resultSourceRefs = new Set(facts.interactions.filter((item) => RESULT_RELATIONS.has(item.relation)).map((item) => item.fromRef));\r\n const uiEntries = facts.entries.filter((entry) => (UI_COMPONENT_TYPES.has(entry.componentType) || surfaceRefs.has(entry.surfaceRef)) && (entry.triggerCategory === \"user\" || (resultSourceRefs.has(entry.entryRef) && surfaceRefs.has(entry.surfaceRef))));\r\n\r\n for (const surface of uiSurfaces) {\r\n for (const parentRef of surface.parentSurfaceRefs ?? []) if (surfaceRefs.has(parentRef)) addEdge(\"hosts\", parentRef, surface.surfaceRef);\r\n }\r\n\r\n for (const entry of uiEntries) {\r\n if (!entry.surfaceRef || !surfaceRefs.has(entry.surfaceRef)) {\r\n unresolved.push({ kind: \"entry-surface\", ref: entry.entryRef, reason: \"UI 入口未确定承载页面\" });\r\n continue;\r\n }\r\n if (entry.triggerCategory !== \"user\") {\r\n addEdge(\"dispatches\", entry.surfaceRef, entry.entryRef);\r\n continue;\r\n }\r\n if (!entry.carrierRef || entry.carrierStatus !== \"determined\") {\r\n unresolved.push({ kind: \"entry-control\", ref: entry.entryRef, reason: \"UI 入口未确定交互元素\" });\r\n continue;\r\n }\r\n const controlRef = `control:${hash(`${entry.surfaceRef}:${entry.carrierRef}`)}`;\r\n const current = controls.get(controlRef);\r\n controls.set(controlRef, {\r\n controlRef,\r\n sourceCarrierRef: entry.carrierRef,\r\n name: entry.carrierName || entry.displayLabel,\r\n surfaceRef: entry.surfaceRef,\r\n status: \"determined\",\r\n sourceEvidence: uniqueEvidence([...(current?.sourceEvidence ?? []), ...(entry.sourceEvidence ?? [])]),\r\n });\r\n addEdge(\"contains-control\", entry.surfaceRef, controlRef);\r\n addEdge(\"triggers\", controlRef, entry.entryRef);\r\n }\r\n\r\n for (const interaction of facts.interactions) {\r\n if (!RESULT_RELATIONS.has(interaction.relation)) continue;\r\n if (!surfaceRefs.has(interaction.toRef)) {\r\n unresolved.push({ kind: \"interaction-target\", ref: interaction.id, reason: \"交互结果未指向已知 UI 页面\" });\r\n continue;\r\n }\r\n const sourceIsSurface = surfaceRefs.has(interaction.fromRef);\r\n if (!sourceIsSurface && !uiEntries.some((entry) => entry.entryRef === interaction.fromRef)) {\r\n unresolved.push({ kind: \"interaction-source\", ref: interaction.id, reason: \"交互结果未从已知 UI 入口发出\" });\r\n continue;\r\n }\r\n addEdge(interaction.relation, interaction.fromRef, interaction.toRef);\r\n }\r\n\r\n const outgoing = new Map();\r\n for (const edge of edges) {\r\n if (!outgoing.has(edge.fromRef)) outgoing.set(edge.fromRef, []);\r\n outgoing.get(edge.fromRef).push(edge.toRef);\r\n }\r\n const reachable = new Set(roots);\r\n const queue = [...roots];\r\n while (queue.length) for (const target of outgoing.get(queue.shift()) ?? []) if (!reachable.has(target)) { reachable.add(target); queue.push(target); }\r\n for (const surface of uiSurfaces) if (!reachable.has(surface.surfaceRef)) unresolved.push({ kind: \"surface-reachability\", ref: surface.surfaceRef, reason: \"页面无法从应用入口沿确定性交互到达\" });\r\n\r\n const dedupEdges = [...new Map(edges.map((edge) => [`${edge.relation}:${edge.fromRef}:${edge.toRef}`, edge])).values()];\r\n const dedupUnresolved = [...new Map(unresolved.map((item) => [`${item.kind}:${item.ref}`, item])).values()];\r\n return {\r\n graphVersion: \"1.0.0\",\r\n roots: [...new Set(roots)].sort(),\r\n surfaces: uiSurfaces.map((surface) => surface.surfaceRef).sort(),\r\n controls: [...controls.values()].sort((a, b) => a.controlRef.localeCompare(b.controlRef)),\r\n entries: uiEntries.map((entry) => entry.entryRef).sort(),\r\n edges: dedupEdges.sort((a, b) => a.id.localeCompare(b.id)),\r\n unresolved: dedupUnresolved.sort((a, b) => `${a.kind}:${a.ref}`.localeCompare(`${b.kind}:${b.ref}`)),\r\n };\r\n}\r\n\r\nexport function validateUiSpecGraph(facts) {\r\n const errors = [];\r\n const graph = facts?.uiGraph;\r\n if (!graph || typeof graph !== \"object\") return [\"spec.facts.uiGraph: object required\"];\r\n const surfaces = new Set((facts.surfaces ?? []).filter((item) => UI_SURFACE_TYPES.has(item.surfaceType)).map((item) => item.surfaceRef));\r\n const entries = new Map((facts.entries ?? []).map((item) => [item.entryRef, item]));\r\n const controls = new Set((graph.controls ?? []).map((item) => item.controlRef));\r\n const unresolved = new Set((graph.unresolved ?? []).map((item) => `${item.kind}:${item.ref}`));\r\n const edgeKeys = new Set((graph.edges ?? []).map((edge) => `${edge.relation}:${edge.fromRef}:${edge.toRef}`));\r\n\r\n if (!(graph.roots ?? []).length) errors.push(\"spec.facts.uiGraph.roots: at least one application entry page required\");\r\n for (const ref of graph.roots ?? []) if (!surfaces.has(ref)) errors.push(`spec.facts.uiGraph.roots: unknown UI surface ${ref}`);\r\n for (const ref of surfaces) if (!(graph.surfaces ?? []).includes(ref)) errors.push(`spec.facts.uiGraph.surfaces: missing ${ref}`);\r\n for (const ref of graph.surfaces ?? []) if (!surfaces.has(ref)) errors.push(`spec.facts.uiGraph.surfaces: unknown ${ref}`);\r\n\r\n for (const control of graph.controls ?? []) {\r\n if (!surfaces.has(control.surfaceRef)) errors.push(`control ${control.controlRef}: unknown surface ${control.surfaceRef}`);\r\n if (!edgeKeys.has(`contains-control:${control.surfaceRef}:${control.controlRef}`)) errors.push(`control ${control.controlRef}: missing contains-control edge`);\r\n }\r\n for (const ref of graph.entries ?? []) {\r\n const entry = entries.get(ref);\r\n if (!entry) { errors.push(`spec.facts.uiGraph.entries: unknown ${ref}`); continue; }\r\n const trigger = (graph.edges ?? []).find((edge) => edge.relation === \"triggers\" && edge.toRef === ref);\r\n const dispatch = (graph.edges ?? []).find((edge) => edge.relation === \"dispatches\" && edge.toRef === ref);\r\n if (entry.triggerCategory === \"user\" && !trigger && !unresolved.has(`entry-control:${ref}`) && !unresolved.has(`entry-surface:${ref}`)) errors.push(`UI entry ${ref}: neither bound to a control nor unresolved`);\r\n if (entry.triggerCategory !== \"user\" && !dispatch) errors.push(`automatic entry ${ref}: missing dispatches edge`);\r\n if (trigger && !controls.has(trigger.fromRef)) errors.push(`UI entry ${ref}: trigger source is not a known control`);\r\n }\r\n for (const edge of graph.edges ?? []) {\r\n if (edge.relation === \"hosts\" && (!surfaces.has(edge.fromRef) || !surfaces.has(edge.toRef))) errors.push(`UI graph edge ${edge.id}: invalid hosts endpoints`);\r\n if (edge.relation === \"dispatches\" && (!surfaces.has(edge.fromRef) || !entries.has(edge.toRef))) errors.push(`UI graph edge ${edge.id}: invalid dispatches endpoints`);\r\n if (edge.relation === \"contains-control\" && (!surfaces.has(edge.fromRef) || !controls.has(edge.toRef))) errors.push(`UI graph edge ${edge.id}: invalid contains-control endpoints`);\r\n if (edge.relation === \"triggers\" && (!controls.has(edge.fromRef) || !entries.has(edge.toRef))) errors.push(`UI graph edge ${edge.id}: invalid triggers endpoints`);\r\n if (RESULT_RELATIONS.has(edge.relation) && (!(entries.has(edge.fromRef) || surfaces.has(edge.fromRef)) || !surfaces.has(edge.toRef))) errors.push(`UI graph edge ${edge.id}: invalid result endpoints`);\r\n }\r\n return errors;\r\n}\r\n","// @ts-nocheck\r\nimport { createHash } from \"node:crypto\";\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\n\r\nconst canonical = (value) => JSON.stringify(value, (_, item) => !item || typeof item !== \"object\" || Array.isArray(item) ? item : Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])));\r\nconst sha256 = (value) => createHash(\"sha256\").update(typeof value === \"string\" ? value : canonical(value)).digest(\"hex\");\r\nconst writeJson = (file, value) => { fs.mkdirSync(path.dirname(file), { recursive: true }); const temporary = `${file}.tmp`; fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\"); fs.renameSync(temporary, file); };\r\nconst readJson = (file) => JSON.parse(fs.readFileSync(file, \"utf8\"));\r\nconst slug = (value) => String(value || \"surface\").replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").replace(/[^a-zA-Z0-9]+/g, \"-\").replace(/^-|-$/g, \"\").toLowerCase() || \"surface\";\r\nconst validateExactKeys = (value, expectedKeys, label, errors) => {\r\n const keys = Object.keys(value).sort();\r\n const expected = [...expectedKeys].sort();\r\n const missing = expected.filter((key) => !keys.includes(key));\r\n const extra = keys.filter((key) => !expected.includes(key));\r\n if (missing.length) errors.push(`${label}: missing required fields ${missing.join(\", \")}`);\r\n if (extra.length) errors.push(`${label}: unsupported fields ${extra.join(\", \")}`);\r\n};\r\n\r\nexport function writeSpecShards(spec, outputDirectory) {\r\n const root = path.resolve(outputDirectory);\r\n const factsRoot = path.join(root, \"facts\");\r\n const semanticsRoot = path.join(root, \"semantics\");\r\n fs.rmSync(factsRoot, { recursive: true, force: true }); fs.rmSync(semanticsRoot, { recursive: true, force: true });\r\n fs.rmSync(path.join(root, \"view\"), { recursive: true, force: true });\r\n fs.rmSync(path.join(root, \"spec.html\"), { force: true });\r\n const factsPages = path.join(factsRoot, \"pages\");\r\n const semanticPages = path.join(semanticsRoot, \"pages\");\r\n fs.mkdirSync(factsPages, { recursive: true }); fs.mkdirSync(semanticPages, { recursive: true });\r\n const surfaceSemantics = new Map(spec.semantics.surfaces.map((item) => [item.surfaceRef, item]));\r\n const controlSemantics = new Map(spec.semantics.controls.map((item) => [item.controlRef, item]));\r\n const entrySemantics = new Map(spec.semantics.entries.map((item) => [item.entryRef, item]));\r\n const controlsBySurface = new Map();\r\n const entriesBySurface = new Map();\r\n const unassignedEntries = [];\r\n for (const control of spec.facts.uiGraph.controls) { if (!controlsBySurface.has(control.surfaceRef)) controlsBySurface.set(control.surfaceRef, []); controlsBySurface.get(control.surfaceRef).push(control); }\r\n for (const entry of spec.facts.entries) { if (!entry.surfaceRef) unassignedEntries.push(entry); else { if (!entriesBySurface.has(entry.surfaceRef)) entriesBySurface.set(entry.surfaceRef, []); entriesBySurface.get(entry.surfaceRef).push(entry); } }\r\n const pages = [];\r\n for (const surface of spec.facts.surfaces) {\r\n const file = `${surface.surfaceRef}-${slug(surface.surfaceName)}.json`;\r\n const relative = `pages/${file}`;\r\n const controls = controlsBySurface.get(surface.surfaceRef) ?? [];\r\n const entries = entriesBySurface.get(surface.surfaceRef) ?? [];\r\n writeJson(path.join(factsRoot, relative), { shardVersion: \"2.0.0\", kind: \"surface-facts\", surface, controls, entries });\r\n writeJson(path.join(semanticsRoot, relative), { shardVersion: \"2.0.0\", kind: \"surface-semantics\", surfaceRef: surface.surfaceRef, surface: surfaceSemantics.get(surface.surfaceRef), controls: controls.map((item) => controlSemantics.get(item.controlRef)), entries: entries.map((item) => entrySemantics.get(item.entryRef)), review: { status: \"pending\", notes: [] } });\r\n pages.push({ surfaceRef: surface.surfaceRef, surfaceType: surface.surfaceType, factsFile: `facts/${relative}`, semanticsFile: `semantics/${relative}` });\r\n }\r\n let unassigned = null;\r\n if (unassignedEntries.length) {\r\n writeJson(path.join(factsPages, \"unassigned.json\"), { shardVersion: \"2.0.0\", kind: \"unassigned-entry-facts\", entries: unassignedEntries });\r\n writeJson(path.join(semanticPages, \"unassigned.json\"), { shardVersion: \"2.0.0\", kind: \"unassigned-entry-semantics\", entries: unassignedEntries.map((item) => entrySemantics.get(item.entryRef)) });\r\n unassigned = { factsFile: \"facts/pages/unassigned.json\", semanticsFile: \"semantics/pages/unassigned.json\" };\r\n }\r\n writeJson(path.join(factsPages, \"index.json\"), { indexVersion: \"2.0.0\", pages: pages.map(({ surfaceRef, surfaceType, factsFile }) => ({ surfaceRef, surfaceType, file: factsFile })), unassignedEntriesFile: unassigned?.factsFile ?? null });\r\n writeJson(path.join(semanticPages, \"index.json\"), { indexVersion: \"2.0.0\", pages: pages.map(({ surfaceRef, semanticsFile }) => ({ surfaceRef, file: semanticsFile })), unassignedEntriesFile: unassigned?.semanticsFile ?? null });\r\n const interactionFacts = spec.facts.interactions.filter((fact) => [\"opens\", \"navigates-to\", \"launches-for-result\"].includes(fact.relation));\r\n writeJson(path.join(factsRoot, \"app.json\"), { shardVersion: \"2.0.0\", generation: spec.generation, app: spec.facts.app, coverage: spec.facts.coverage, warnings: spec.facts.warnings, uiGraph: { roots: spec.facts.uiGraph.roots } });\r\n writeJson(path.join(factsRoot, \"interactions.json\"), { shardVersion: \"2.0.0\", interactions: interactionFacts });\r\n writeJson(path.join(factsRoot, \"unresolved.json\"), { shardVersion: \"2.0.0\", facts: spec.facts.unresolved, graphItems: spec.facts.uiGraph.unresolved });\r\n writeJson(path.join(semanticsRoot, \"app.json\"), { shardVersion: \"2.0.0\", semantic: spec.semantics.app, review: spec.review });\r\n writeJson(path.join(semanticsRoot, \"interactions.json\"), { shardVersion: \"2.0.0\", interactions: interactionFacts.map((fact) => ({ interactionRef: fact.id, name: null, description: null, status: \"pending\" })) });\r\n writeJson(path.join(semanticsRoot, \"features.json\"), { shardVersion: \"2.0.0\", domains: spec.domains ?? [], features: spec.features ?? [] });\r\n writeJson(path.join(semanticsRoot, \"unresolved.json\"), { shardVersion: \"2.0.0\", reviews: spec.semantics.unresolvedReviews });\r\n writeJson(path.join(semanticsRoot, \"corrections.json\"), { shardVersion: \"2.0.0\", factCorrections: spec.factCorrections, exclusions: spec.exclusions });\r\n const files = { facts: { app: \"facts/app.json\", pages: \"facts/pages/index.json\", interactions: \"facts/interactions.json\", unresolved: \"facts/unresolved.json\" }, semantics: { app: \"semantics/app.json\", pages: \"semantics/pages/index.json\", interactions: \"semantics/interactions.json\", features: \"semantics/features.json\", unresolved: \"semantics/unresolved.json\", corrections: \"semantics/corrections.json\" } };\r\n const factsSha256 = sha256({ app: readJson(path.join(root, files.facts.app)), pages: pages.map((item) => readJson(path.join(root, item.factsFile))), unassigned: unassigned ? readJson(path.join(root, unassigned.factsFile)) : null, interactions: readJson(path.join(root, files.facts.interactions)), unresolved: readJson(path.join(root, files.facts.unresolved)) });\r\n const index = { specVersion: spec.specVersion, shardFormatVersion: \"2.0.0\", language: spec.language, generation: spec.generation, files, counts: { surfaces: pages.length, controls: spec.facts.uiGraph.controls.length, entries: spec.facts.entries.length, interactions: interactionFacts.length, features: spec.features?.length ?? 0, unresolved: spec.facts.unresolved.length }, factsSha256, specSha256: null };\r\n writeJson(path.join(root, \"index.json\"), index); return { root, index };\r\n}\r\n\r\nfunction readBundle(root) {\r\n const index = readJson(path.join(root, \"index.json\"));\r\n const read = (relative) => readJson(path.join(root, relative));\r\n const factsApp = read(index.files.facts.app);\r\n const semanticsApp = read(index.files.semantics.app);\r\n const factsIndex = read(index.files.facts.pages);\r\n const semanticsIndex = read(index.files.semantics.pages);\r\n const semanticsBySurface = new Map((semanticsIndex.pages ?? []).map((item) => [item.surfaceRef, item.file]));\r\n const pages = (factsIndex.pages ?? []).map((item) => ({ fact: read(item.file), semantic: read(semanticsBySurface.get(item.surfaceRef)) }));\r\n const unassigned = factsIndex.unassignedEntriesFile ? { fact: read(factsIndex.unassignedEntriesFile), semantic: read(semanticsIndex.unassignedEntriesFile) } : null;\r\n return { root, index, factsApp, semanticsApp, pages, unassigned, interactionFacts: read(index.files.facts.interactions), interactionSemantics: read(index.files.semantics.interactions), featureSemantics: read(index.files.semantics.features), unresolvedFacts: read(index.files.facts.unresolved), unresolvedSemantics: read(index.files.semantics.unresolved), corrections: read(index.files.semantics.corrections) };\r\n}\r\n\r\nexport function validateSpecShards(rootArgument, { requireComplete = false } = {}) {\r\n const root = path.resolve(rootArgument);\r\n const errors = []; let bundle;\r\n try { bundle = readBundle(root); } catch (error) { return [error.message]; }\r\n const { index, pages, unassigned, interactionFacts, interactionSemantics, featureSemantics, unresolvedFacts, unresolvedSemantics } = bundle;\r\n const surfaceRefs = new Set();\r\n const controlRefs = new Set();\r\n const entryRefs = new Set();\r\n for (const { fact, semantic } of pages) {\r\n const surfaceRef = fact.surface?.surfaceRef;\r\n if (!surfaceRef || surfaceRefs.has(surfaceRef)) errors.push(`duplicate or missing surfaceRef ${surfaceRef ?? \"<empty>\"}`); else surfaceRefs.add(surfaceRef);\r\n if (semantic.surfaceRef !== surfaceRef || semantic.surface?.surfaceRef !== surfaceRef) errors.push(`semantic page ${surfaceRef}: surface ref mismatch`);\r\n for (const item of fact.controls ?? []) { if (!item.controlRef || controlRefs.has(item.controlRef)) errors.push(`duplicate or missing controlRef ${item.controlRef ?? \"<empty>\"}`); else controlRefs.add(item.controlRef); }\r\n for (const item of fact.entries ?? []) { if (!item.entryRef || entryRefs.has(item.entryRef)) errors.push(`duplicate or missing entryRef ${item.entryRef ?? \"<empty>\"}`); else entryRefs.add(item.entryRef); }\r\n if ((semantic.controls ?? []).length !== (fact.controls ?? []).length) errors.push(`semantic page ${surfaceRef}: control count differs from facts`);\r\n if ((semantic.entries ?? []).length !== (fact.entries ?? []).length) errors.push(`semantic page ${surfaceRef}: entry count differs from facts`);\r\n }\r\n for (const item of unassigned?.fact.entries ?? []) { if (!item.entryRef || entryRefs.has(item.entryRef)) errors.push(`duplicate or missing entryRef ${item.entryRef ?? \"<empty>\"}`); else entryRefs.add(item.entryRef); }\r\n const addedCorrections = (bundle.corrections.factCorrections ?? []).filter((item) => item.operation === \"add\");\r\n for (const correction of addedCorrections) {\r\n if (correction.entityKind === \"surface\") surfaceRefs.add(correction.targetRef);\r\n else if (correction.entityKind === \"control\") controlRefs.add(correction.targetRef);\r\n else if (correction.entityKind === \"entry\") entryRefs.add(correction.targetRef);\r\n }\r\n for (const fact of interactionFacts.interactions ?? []) {\r\n if (!entryRefs.has(fact.fromRef) && !surfaceRefs.has(fact.fromRef)) errors.push(`interaction ${fact.id}: unknown source entry or surface ${fact.fromRef}`);\r\n if ([\"opens\", \"navigates-to\"].includes(fact.relation) && !surfaceRefs.has(fact.toRef)) errors.push(`interaction ${fact.id}: unknown target surface ${fact.toRef}`);\r\n if (fact.relation === \"launches-for-result\" && !entryRefs.has(fact.toRef)) errors.push(`interaction ${fact.id}: unknown result entry ${fact.toRef}`);\r\n }\r\n const semanticInteractionRefs = new Set((interactionSemantics.interactions ?? []).map((item) => item.interactionRef));\r\n for (const fact of interactionFacts.interactions ?? []) if (!semanticInteractionRefs.has(fact.id)) errors.push(`missing interaction semantic ${fact.id}`);\r\n const featureList = featureSemantics.features ?? [];\r\n const domainList = featureSemantics.domains ?? [];\r\n const featureRefs = new Set();\r\n const domainRefs = new Set();\r\n for (const domain of domainList) { if (!domain.id || domainRefs.has(domain.id)) errors.push(`duplicate or missing domain id ${domain.id ?? \"<empty>\"}`); else domainRefs.add(domain.id); }\r\n for (const feature of featureList) { if (!feature.id || featureRefs.has(feature.id)) errors.push(`duplicate or missing feature id ${feature.id ?? \"<empty>\"}`); else featureRefs.add(feature.id); }\r\n const listedTopFeatures = new Map();\r\n for (const domain of domainList) {\r\n validateExactKeys(domain, [\"description\", \"featureRefs\", \"id\", \"name\", \"parentDomainRef\"], `domain ${domain.id ?? \"<empty>\"}`, errors);\r\n if (domain.parentDomainRef && !domainRefs.has(domain.parentDomainRef)) errors.push(`domain ${domain.id}: unknown parentDomainRef ${domain.parentDomainRef}`);\r\n for (const ref of domain.featureRefs ?? []) {\r\n if (!featureRefs.has(ref)) errors.push(`domain ${domain.id}: unknown featureRef ${ref}`);\r\n else if (listedTopFeatures.has(ref)) errors.push(`feature ${ref}: listed by both domains ${listedTopFeatures.get(ref)} and ${domain.id}`);\r\n else listedTopFeatures.set(ref, domain.id);\r\n }\r\n }\r\n for (const feature of featureList) {\r\n validateExactKeys(feature, [\"description\", \"domainRef\", \"entryRefs\", \"id\", \"name\", \"parentFeatureRef\"], `feature ${feature.id ?? \"<empty>\"}`, errors);\r\n if (/^surface-/i.test(feature.id)) errors.push(`feature ${feature.id}: placeholder surface-* ids are forbidden in completed business features`);\r\n if (!domainRefs.has(feature.domainRef)) errors.push(`feature ${feature.id}: unknown domainRef ${feature.domainRef}`);\r\n if (feature.parentFeatureRef && !featureRefs.has(feature.parentFeatureRef)) errors.push(`feature ${feature.id}: unknown parentFeatureRef ${feature.parentFeatureRef}`);\r\n if (!feature.parentFeatureRef && listedTopFeatures.get(feature.id) !== feature.domainRef) errors.push(`feature ${feature.id}: top-level feature must be listed by its domain ${feature.domainRef}`);\r\n if (feature.parentFeatureRef && listedTopFeatures.has(feature.id)) errors.push(`feature ${feature.id}: child feature must not be listed directly by a domain`);\r\n for (const ref of feature.entryRefs ?? []) if (!entryRefs.has(ref)) errors.push(`feature ${feature.id}: unknown entryRef ${ref}`);\r\n }\r\n const featureByRef = new Map(featureList.map((item) => [item.id, item]));\r\n for (const feature of featureList) {\r\n const seen = new Set([feature.id]); let parent = feature.parentFeatureRef;\r\n while (parent && featureByRef.has(parent)) { if (seen.has(parent)) { errors.push(`feature ${feature.id}: parent cycle through ${parent}`); break; } seen.add(parent); parent = featureByRef.get(parent).parentFeatureRef; }\r\n }\r\n for (const review of unresolvedSemantics.reviews ?? []) {\r\n if (![\"pending\", \"covered-by-feature\", \"excluded\", \"accepted-unknown\"].includes(review.decision)) errors.push(`unresolved ${review.unresolvedRef}: invalid decision ${review.decision}`);\r\n if (review.decision === \"covered-by-feature\" && !featureRefs.has(review.featureRef)) errors.push(`unresolved ${review.unresolvedRef}: covered-by-feature requires a known featureRef`);\r\n if ([\"excluded\", \"accepted-unknown\"].includes(review.decision) && review.featureRef !== null) errors.push(`unresolved ${review.unresolvedRef}: ${review.decision} requires featureRef null`);\r\n if (review.decision !== \"pending\" && !String(review.reason ?? \"\").trim()) errors.push(`unresolved ${review.unresolvedRef}: reviewed decision requires reason`);\r\n }\r\n const unresolvedByRef = new Map((unresolvedFacts.facts ?? []).map((item) => [item.id, item]));\r\n const correctionIds = new Set();\r\n for (const correction of bundle.corrections.factCorrections ?? []) {\r\n if (!correction.id || correctionIds.has(correction.id)) errors.push(`correction ${correction.id ?? \"<empty>\"}: duplicate or missing id`); else correctionIds.add(correction.id);\r\n if (![\"surface\", \"control\", \"entry\", \"interaction\"].includes(correction.entityKind)) errors.push(`correction ${correction.id}: invalid entityKind ${correction.entityKind}`);\r\n if (![\"add\", \"update\", \"remove\"].includes(correction.operation)) errors.push(`correction ${correction.id}: invalid operation ${correction.operation}`);\r\n if (!String(correction.targetRef ?? \"\").trim()) errors.push(`correction ${correction.id}: targetRef is required`);\r\n if (correction.operation === \"add\" && (!correction.factValue || !correction.semanticValue)) errors.push(`correction ${correction.id}: add requires nested factValue and semanticValue`);\r\n if (!String(correction.reason ?? \"\").trim() || !(correction.sourceEvidence ?? []).length) errors.push(`correction ${correction.id}: reason and sourceEvidence are required`);\r\n }\r\n const interactionCorrections = (bundle.corrections.factCorrections ?? []).filter((item) => item.entityKind === \"interaction\" && item.operation === \"add\");\r\n for (const correction of interactionCorrections) {\r\n if (!entryRefs.has(correction.factValue?.fromRef) && !surfaceRefs.has(correction.factValue?.fromRef)) errors.push(`correction ${correction.id}: unknown source entry or surface ${correction.factValue?.fromRef}`);\r\n if ([\"opens\", \"navigates-to\"].includes(correction.factValue?.relation) && !surfaceRefs.has(correction.factValue?.toRef)) errors.push(`correction ${correction.id}: unknown target surface ${correction.factValue?.toRef}`);\r\n if (correction.factValue?.relation === \"launches-for-result\" && !entryRefs.has(correction.factValue?.toRef)) errors.push(`correction ${correction.id}: unknown result entry ${correction.factValue?.toRef}`);\r\n }\r\n for (const review of unresolvedSemantics.reviews ?? []) {\r\n if (review.decision !== \"covered-by-feature\") continue;\r\n const unresolved = unresolvedByRef.get(review.unresolvedRef);\r\n if (unresolved?.kind !== \"interaction\") continue;\r\n const alreadyKnown = (interactionFacts.interactions ?? []).some((item) => item.fromRef === unresolved.fromRef && item.relation === unresolved.relation && (unresolved.candidateToRefs ?? []).includes(item.toRef));\r\n const proposed = interactionCorrections.some((item) => item.factValue?.fromRef === unresolved.fromRef && item.factValue?.relation === unresolved.relation && (unresolved.candidateToRefs ?? []).includes(item.factValue?.toRef));\r\n if (!alreadyKnown && !proposed) errors.push(`unresolved ${review.unresolvedRef}: covered interaction requires a matching add interaction correction`);\r\n }\r\n if (requireComplete) {\r\n const pending = [];\r\n for (const { semantic } of pages) for (const item of [semantic.surface, ...(semantic.controls ?? []), ...(semantic.entries ?? [])]) if (!item || item.status === \"pending\") pending.push(item?.surfaceRef ?? item?.controlRef ?? item?.entryRef ?? semantic.surfaceRef);\r\n for (const item of interactionSemantics.interactions ?? []) if (item.status === \"pending\") pending.push(item.interactionRef);\r\n for (const item of unresolvedSemantics.reviews ?? []) if (item.decision === \"pending\") pending.push(item.unresolvedRef);\r\n if (bundle.semanticsApp.semantic?.status === \"pending\") pending.push(\"app\");\r\n if (pending.length) errors.push(`pending semantic reviews: ${pending.join(\", \")}`);\r\n if (bundle.semanticsApp.review?.status !== \"ai-completed\") errors.push(\"semantics/app.json review.status must be ai-completed\");\r\n const semanticEntries = new Map();\r\n for (const { semantic } of pages) for (const item of semantic.entries ?? []) semanticEntries.set(item.entryRef, item);\r\n for (const item of unassigned?.semantic.entries ?? []) semanticEntries.set(item.entryRef, item);\r\n for (const correction of addedCorrections.filter((item) => item.entityKind === \"entry\")) semanticEntries.set(correction.targetRef, { ...correction.semanticValue, entryRef: correction.targetRef });\r\n const featureAssignments = new Map([...entryRefs].map((ref) => [ref, 0]));\r\n for (const feature of featureList) for (const ref of feature.entryRefs ?? []) if (featureAssignments.has(ref)) featureAssignments.set(ref, featureAssignments.get(ref) + 1);\r\n const excluded = new Set((bundle.corrections.exclusions ?? []).map((item) => item.entryRef));\r\n for (const ref of entryRefs) {\r\n const semantic = semanticEntries.get(ref);\r\n const effectType = semantic?.effectType;\r\n if (![\"ui\", \"business\", \"mixed\"].includes(effectType)) { errors.push(`entry ${ref}: reviewed effectType must be ui, business, or mixed`); continue; }\r\n const count = featureAssignments.get(ref) ?? 0;\r\n if (effectType === \"ui\" && count !== 0) errors.push(`entry ${ref}: ui entry must not belong to a business feature`);\r\n if ([\"business\", \"mixed\"].includes(effectType) && !excluded.has(ref) && count !== 1) errors.push(`entry ${ref}: ${effectType} entry must belong to exactly one leaf feature, found ${count}`);\r\n if (excluded.has(ref) && count !== 0) errors.push(`entry ${ref}: excluded entry must not belong to a feature`);\r\n }\r\n const childCounts = new Map(featureList.map((item) => [item.id, 0]));\r\n for (const feature of featureList) if (feature.parentFeatureRef) childCounts.set(feature.parentFeatureRef, (childCounts.get(feature.parentFeatureRef) ?? 0) + 1);\r\n for (const feature of featureList) {\r\n const isLeaf = (childCounts.get(feature.id) ?? 0) === 0;\r\n if (isLeaf && !(feature.entryRefs ?? []).length) errors.push(`feature ${feature.id}: leaf feature requires at least one business or mixed entry`);\r\n if (!isLeaf && (feature.entryRefs ?? []).length) errors.push(`feature ${feature.id}: parent feature must not own entries directly`);\r\n for (const ref of feature.entryRefs ?? []) if (![\"business\", \"mixed\"].includes(semanticEntries.get(ref)?.effectType)) errors.push(`feature ${feature.id}: entry ${ref} is not business or mixed`);\r\n }\r\n\r\n // A completed UI SPEC must form one reachable interaction graph from the\r\n // application entry page. Having an incoming edge is not enough: an entire\r\n // Dialog chain can still be detached from every launcher page.\r\n const uiTypes = new Set([\"activity\", \"fragment\", \"dialog\", \"compose\", \"xml-layout\", \"appyx-node\"]);\r\n const removedSurfaces = new Set((bundle.corrections.factCorrections ?? []).filter((item) => item.entityKind === \"surface\" && item.operation === \"remove\").map((item) => item.targetRef));\r\n const proposedSurfaces = (bundle.corrections.factCorrections ?? []).filter((item) => item.entityKind === \"surface\" && item.operation === \"add\").map((item) => ({ ...item.factValue, surfaceRef: item.targetRef }));\r\n const effectiveSurfaces = [...pages.map(({ fact }) => fact.surface), ...proposedSurfaces].filter((item) => item && !removedSurfaces.has(item.surfaceRef));\r\n const uiSurfaceRefs = new Set(effectiveSurfaces.filter((item) => uiTypes.has(item.surfaceType)).map((item) => item.surfaceRef));\r\n const removedInteractions = new Set((bundle.corrections.factCorrections ?? []).filter((item) => item.entityKind === \"interaction\" && item.operation === \"remove\").map((item) => item.targetRef));\r\n const proposedInteractions = interactionCorrections.map((item) => ({ ...item.factValue, id: item.targetRef }));\r\n const effectiveInteractions = [...(interactionFacts.interactions ?? []).filter((item) => !removedInteractions.has(item.id)), ...proposedInteractions];\r\n const reachable = new Set((bundle.factsApp.uiGraph?.roots ?? []).filter((ref) => uiSurfaceRefs.has(ref)));\r\n const outgoing = new Map();\r\n const link = (from, to) => { if (!outgoing.has(from)) outgoing.set(from, []); outgoing.get(from).push(to); };\r\n for (const surface of effectiveSurfaces) for (const parent of surface.parentSurfaceRefs ?? []) if (uiSurfaceRefs.has(parent)) link(parent, surface.surfaceRef);\r\n const removedControls = new Set((bundle.corrections.factCorrections ?? []).filter((item) => item.entityKind === \"control\" && item.operation === \"remove\").map((item) => item.targetRef));\r\n const proposedControls = (bundle.corrections.factCorrections ?? []).filter((item) => item.entityKind === \"control\" && item.operation === \"add\").map((item) => ({ ...item.factValue, controlRef: item.targetRef }));\r\n const pageControls = new Map();\r\n for (const control of [...pages.flatMap(({ fact }) => fact.controls ?? []), ...proposedControls].filter((item) => !removedControls.has(item.controlRef))) {\r\n if (!pageControls.has(control.surfaceRef)) pageControls.set(control.surfaceRef, []);\r\n pageControls.get(control.surfaceRef).push(control);\r\n }\r\n const removedEntries = new Set((bundle.corrections.factCorrections ?? []).filter((item) => item.entityKind === \"entry\" && item.operation === \"remove\").map((item) => item.targetRef));\r\n const proposedEntries = (bundle.corrections.factCorrections ?? []).filter((item) => item.entityKind === \"entry\" && item.operation === \"add\").map((item) => ({ ...item.factValue, entryRef: item.targetRef }));\r\n const effectiveEntries = [...pages.flatMap(({ fact }) => fact.entries ?? []), ...(unassigned?.fact.entries ?? []), ...proposedEntries].filter((item) => !removedEntries.has(item.entryRef));\r\n for (const entry of effectiveEntries) {\r\n if (!entry.surfaceRef || !uiSurfaceRefs.has(entry.surfaceRef)) continue;\r\n const connected = entry.triggerCategory !== \"user\" || (pageControls.get(entry.surfaceRef) ?? []).some((control) => control.sourceCarrierRef === entry.carrierRef);\r\n if (connected) link(entry.surfaceRef, entry.entryRef);\r\n }\r\n for (const interaction of effectiveInteractions) if ([\"opens\", \"navigates-to\"].includes(interaction.relation) && uiSurfaceRefs.has(interaction.toRef)) link(interaction.fromRef, interaction.toRef);\r\n const queue = [...reachable];\r\n while (queue.length) for (const target of outgoing.get(queue.shift()) ?? []) if (!reachable.has(target)) { reachable.add(target); queue.push(target); }\r\n const unreachable = effectiveSurfaces.filter((item) => uiTypes.has(item.surfaceType) && !reachable.has(item.surfaceRef));\r\n if (unreachable.length) errors.push(`unreachable UI surfaces from application entry: ${unreachable.map((item) => `${item.surfaceRef}(${item.surfaceName})`).join(\", \")}`);\r\n }\r\n const recomputedFacts = sha256({ app: bundle.factsApp, pages: pages.map((item) => item.fact), unassigned: unassigned?.fact ?? null, interactions: interactionFacts, unresolved: unresolvedFacts });\r\n if (index.factsSha256 !== recomputedFacts) errors.push(\"deterministic SPEC facts were modified\");\r\n return errors;\r\n}\r\n\r\nexport function finalizeSpec(rootArgument) {\r\n const root = path.resolve(rootArgument);\r\n const errors = validateSpecShards(root, { requireComplete: true }); if (errors.length) throw new Error(errors.join(\"\\n\"));\r\n const bundle = readBundle(root); bundle.index.counts.features = bundle.featureSemantics.features?.length ?? 0;\r\n bundle.index.specSha256 = sha256({ factsSha256: bundle.index.factsSha256, app: bundle.semanticsApp, pages: bundle.pages.map((item) => item.semantic), unassigned: bundle.unassigned?.semantic ?? null, interactions: bundle.interactionSemantics, features: bundle.featureSemantics, unresolved: bundle.unresolvedSemantics, corrections: bundle.corrections });\r\n writeJson(path.join(root, \"index.json\"), bundle.index); return bundle.index;\r\n}\r\n\r\nexport function loadSpecShards(indexArgument) {\r\n const indexPath = path.resolve(indexArgument);\r\n const root = fs.statSync(indexPath).isDirectory() ? indexPath : path.dirname(indexPath);\r\n const bundle = readBundle(root);\r\n const surfaces = [];\r\n const controls = [];\r\n const entries = [];\r\n const surfaceSemantics = [];\r\n const controlSemantics = [];\r\n const entrySemantics = [];\r\n for (const { fact, semantic } of bundle.pages) { surfaces.push(fact.surface); surfaceSemantics.push(semantic.surface); controls.push(...(fact.controls ?? [])); controlSemantics.push(...(semantic.controls ?? [])); entries.push(...(fact.entries ?? [])); entrySemantics.push(...(semantic.entries ?? [])); }\r\n if (bundle.unassigned) { entries.push(...(bundle.unassigned.fact.entries ?? [])); entrySemantics.push(...(bundle.unassigned.semantic.entries ?? [])); }\r\n const semanticInteractions = new Map((bundle.interactionSemantics.interactions ?? []).map((item) => [item.interactionRef, item]));\r\n const uiEdges = [];\r\n for (const surface of surfaces) for (const parentRef of surface.parentSurfaceRefs ?? []) uiEdges.push({ id: sha256(`hosts:${parentRef}:${surface.surfaceRef}`).slice(0, 16), relation: \"hosts\", fromRef: parentRef, toRef: surface.surfaceRef });\r\n for (const control of controls) uiEdges.push({ id: sha256(`contains-control:${control.surfaceRef}:${control.controlRef}`).slice(0, 16), relation: \"contains-control\", fromRef: control.surfaceRef, toRef: control.controlRef });\r\n for (const entry of entries) { if (!entry.surfaceRef) continue; const control = controls.find((item) => item.surfaceRef === entry.surfaceRef && item.sourceCarrierRef === entry.carrierRef); const relation = control ? \"triggers\" : \"dispatches\"; const fromRef = control?.controlRef ?? entry.surfaceRef; uiEdges.push({ id: sha256(`${relation}:${fromRef}:${entry.entryRef}`).slice(0, 16), relation, fromRef, toRef: entry.entryRef }); }\r\n for (const fact of bundle.interactionFacts.interactions ?? []) if ([\"opens\", \"navigates-to\"].includes(fact.relation)) uiEdges.push(fact);\r\n return { specVersion: bundle.index.specVersion, language: bundle.index.language, generation: bundle.factsApp.generation, facts: { schemaVersion: 11, app: bundle.factsApp.app, surfaces, entries, interactions: bundle.interactionFacts.interactions ?? [], unresolved: bundle.unresolvedFacts.facts ?? [], coverage: bundle.factsApp.coverage, warnings: bundle.factsApp.warnings, uiGraph: { graphVersion: \"1.0.0\", roots: bundle.factsApp.uiGraph.roots, surfaces: surfaces.map((item) => item.surfaceRef), controls, entries: entries.filter((item) => item.surfaceRef).map((item) => item.entryRef), edges: uiEdges, unresolved: bundle.unresolvedFacts.graphItems ?? [] } }, factCorrections: bundle.corrections.factCorrections ?? [], semantics: { app: bundle.semanticsApp.semantic, surfaces: surfaceSemantics, controls: controlSemantics, entries: entrySemantics, interactions: (bundle.interactionFacts.interactions ?? []).map((fact) => ({ fact, semantic: semanticInteractions.get(fact.id) })), unresolvedReviews: bundle.unresolvedSemantics.reviews ?? [] }, domains: bundle.featureSemantics.domains ?? [], features: bundle.featureSemantics.features ?? [], exclusions: bundle.corrections.exclusions ?? [], review: bundle.semanticsApp.review };\r\n}\r\n","#!/usr/bin/env node\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { loadSpecShards, validateSpecShards } from \"./lib/spec-shards.ts\";\r\n\r\nexport function resolveAndroidProjectRootForSpec(specPath: string): string | null {\r\n const specDirectory = path.dirname(path.resolve(specPath));\r\n const migrationDirectoryOnDisk = path.dirname(specDirectory);\r\n const workspaceRoot = path.dirname(migrationDirectoryOnDisk);\r\n try {\r\n const config = JSON.parse(fs.readFileSync(path.join(migrationDirectoryOnDisk, \"config.json\"), \"utf8\"));\r\n if (typeof config.androidProject === \"string\" && config.androidProject) {\r\n return path.isAbsolute(config.androidProject)\r\n ? path.resolve(config.androidProject)\r\n : path.resolve(workspaceRoot, config.androidProject);\r\n }\r\n } catch {\r\n // 兼容没有 config.json 的独立 SPEC 渲染。\r\n }\r\n if (path.basename(specDirectory) !== \"spec\" || path.basename(migrationDirectoryOnDisk) !== \".migration\") return null;\r\n return workspaceRoot.endsWith(\"-migration\")\r\n ? workspaceRoot.slice(0, -\"-migration\".length)\r\n : workspaceRoot;\r\n}\r\n\r\nexport function renderSpecHtml(argv: string[]) {\r\nconst [specArgument, outputArgument] = argv;\r\nif (!specArgument) {\r\n throw new Error(\"render-spec requires <spec-index.json> [spec.html]\");\r\n}\r\n\r\nconst specPath = path.resolve(specArgument);\r\nconst outputPath = path.resolve(outputArgument || path.join(path.dirname(specPath), \"spec.html\"));\r\nconst parsedInput = JSON.parse(fs.readFileSync(specPath, \"utf8\"));\r\nif (!parsedInput.shardFormatVersion) {\r\n throw new Error(\"SPEC shard index required\");\r\n}\r\nconst spec = loadSpecShards(specPath);\r\nconst errors = validateSpecShards(path.dirname(specPath));\r\nif (errors.length) {\r\n throw new Error(errors.join(\"\\n\"));\r\n}\r\n\r\nconst activityUsage: Record<string, \"launcher\" | \"external\" | \"internal\" | \"unknown\"> = {};\r\nconst specDirectory = path.dirname(specPath);\r\nconst projectRoot = resolveAndroidProjectRootForSpec(specPath);\r\nconst manifests: string[] = [];\r\nconst findManifests = (directory: string) => {\r\n if (!fs.existsSync(directory)) return;\r\n let items: fs.Dirent[];\r\n try { items = fs.readdirSync(directory, { withFileTypes: true }); } catch { return; }\r\n for (const item of items) {\r\n if ([\".git\", \".gradle\", \".migration\", \"build\", \"node_modules\"].includes(item.name)) continue;\r\n const target = path.join(directory, item.name);\r\n if (item.isDirectory()) findManifests(target);\r\n else if (item.name === \"AndroidManifest.xml\") manifests.push(target);\r\n }\r\n};\r\nif (projectRoot) findManifests(projectRoot);\r\nfor (const manifest of manifests) {\r\n const xml = fs.readFileSync(manifest, \"utf8\");\r\n for (const match of xml.matchAll(/<activity(-alias)?\\b([^>]*)>/g)) {\r\n const alias = Boolean(match[1]);\r\n const attrs = match[2] ?? \"\";\r\n const afterTag = (match.index ?? 0) + match[0].length;\r\n const closingTag = `</activity${alias ? \"-alias\" : \"\"}>`;\r\n const closingAt = attrs.trimEnd().endsWith(\"/\") ? -1 : xml.indexOf(closingTag, afterTag);\r\n const body = closingAt >= 0 ? xml.slice(afterTag, closingAt) : \"\";\r\n const declaredName = attrs.match(/android:name\\s*=\\s*[\"']([^\"']+)[\"']/)?.[1];\r\n const targetName = alias ? attrs.match(/android:targetActivity\\s*=\\s*[\"']([^\"']+)[\"']/)?.[1] : declaredName;\r\n if (!targetName) continue;\r\n const name = targetName.split(\".\").filter(Boolean).at(-1)!;\r\n const launcher = /android\\.intent\\.action\\.MAIN/.test(body) && /android\\.intent\\.category\\.LAUNCHER/.test(body);\r\n const exported = attrs.match(/android:exported\\s*=\\s*[\"'](true|false)[\"']/)?.[1];\r\n const usage = launcher ? \"launcher\" : (() => { if (exported === \"true\") return \"external\"; return (() => { if (exported === \"false\") return \"internal\"; return \"unknown\"; })(); })();\r\n if (activityUsage[name] !== \"launcher\" || usage === \"launcher\") activityUsage[name] = usage;\r\n }\r\n}\r\n\r\nconst payload = JSON.stringify(spec).replaceAll(\"<\", \"\\\\u003c\");\r\nconst activityUsagePayload = JSON.stringify(activityUsage).replaceAll(\"<\", \"\\\\u003c\");\r\nconst html = `<!doctype html>\r\n<html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\r\n<title>Android → HarmonyOS · SPEC</title>\r\n<style>\r\n:root{color-scheme:light;--bg:#f4f6fa;--panel:#fff;--ink:#172033;--muted:#667085;--line:#dce2ec;--blue:#2864dc;--blue-soft:#eaf1ff;--purple:#7657d6;--amber:#a76300;--amber-soft:#fff5d8;--green:#087f5b;--red:#c43d3d;--shadow:0 8px 28px rgba(29,43,75,.07)}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.55 Inter,\"Segoe UI\",\"Microsoft YaHei\",sans-serif}button,input{font:inherit}.top{position:sticky;top:0;z-index:10;background:rgba(255,255,255,.96);border-bottom:1px solid var(--line);padding:14px 20px}.headline{display:flex;align-items:center;gap:16px;justify-content:space-between}.title{font-size:21px;font-weight:760}.metrics,.toolbar,.tabs{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.metric,.tag{border:1px solid var(--line);border-radius:999px;background:#fff;padding:4px 9px;color:var(--muted)}.metric b{color:var(--ink)}.toolbar{margin-top:12px}.tabs button,.action{border:1px solid var(--line);border-radius:9px;background:#fff;padding:8px 13px;cursor:pointer}.tabs button.active{background:var(--blue);border-color:var(--blue);color:#fff}.search{min-width:280px;flex:1;border:1px solid var(--line);border-radius:9px;padding:8px 11px}.layout{display:grid;grid-template-columns:360px minmax(0,1fr);height:calc(100vh - 128px)}aside{background:#fff;border-right:1px solid var(--line);overflow:auto;padding:14px 10px}main{overflow:auto;padding:22px}.tree,.tree ul{list-style:none;margin:0;padding:0}.tree ul{margin-left:14px;padding-left:12px;border-left:1px solid var(--line)}.node{width:100%;border:0;border-radius:8px;background:transparent;text-align:left;padding:7px 8px;cursor:pointer;display:flex;gap:8px;align-items:flex-start}.node:hover,.node.active{background:var(--blue-soft);color:#164eaf}.twisty{width:12px;color:#7a879d}.node-title{font-weight:650;overflow-wrap:anywhere}.node-sub{display:block;color:var(--muted);font-size:12px;font-weight:400}.kind{flex:none;margin-top:2px;width:8px;height:8px;border-radius:50%;background:var(--blue)}.kind.entry{background:#e6a400}.kind.surface{background:#4d91dc}.kind.domain{background:var(--purple)}.kind.feature{background:#22a06b}.card{max-width:1050px;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:20px;margin-bottom:14px;box-shadow:var(--shadow)}h1,h2,h3{margin:0 0 10px}h1{font-size:24px}h2{font-size:17px;margin-top:18px}.lead{font-size:15px;color:#42506a}.empty{color:var(--muted);font-style:italic}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.fact{border:1px solid var(--line);border-radius:10px;padding:11px;background:#fbfcfe}.fact b{display:block}.mono{font:12px/1.5 Consolas,monospace;overflow-wrap:anywhere}.evidence{border-left:3px solid #9bb8ee;padding:7px 10px;margin:6px 0;background:#f8faff}.status-reviewed{color:var(--green)}.status-pending{color:var(--amber)}.warning{background:var(--amber-soft);color:#7b4a00;border-radius:9px;padding:10px}.relation{display:flex;gap:8px;align-items:center;padding:8px 0;border-bottom:1px solid #edf0f5}.relation:last-child{border-bottom:0}.arrow{color:var(--purple);font-weight:bold}.hidden{display:none!important}@media(max-width:850px){.headline{align-items:flex-start;flex-direction:column}.layout{display:block;height:auto}aside{height:45vh;border-right:0;border-bottom:1px solid var(--line)}main{overflow:visible}.grid{grid-template-columns:1fr}.search{min-width:180px}}\r\n.kind.control{width:13px;height:15px;border-radius:0;background:#ef6c57;clip-path:polygon(8% 0,92% 63%,58% 68%,78% 96%,61% 100%,42% 72%,17% 100%)}.kind.surface-link,.kind.external-link{width:16px;height:16px;border-radius:5px;display:inline-flex;align-items:center;justify-content:center;font-size:13px;font-weight:800}.kind.surface-link{background:#eaf1ff;color:#2864dc}.kind.surface-link:after{content:'→'}.kind.external-link{background:#fff0df;color:#c45b00}.kind.external-link:after{content:'↗'}.activity-usage{display:inline-flex;margin-left:6px;padding:0 6px;border-radius:999px;font-size:10px;font-weight:650;vertical-align:1px}.activity-usage.launcher{background:#e8f7f1;color:#087f5b}.activity-usage.external{background:#fff0df;color:#a94e00}.activity-usage.internal{background:#eef1f6;color:#526077}.activity-usage.unknown{background:#fff5d8;color:#8a5a00}.caller-links{display:flex;gap:4px;flex-wrap:wrap;margin-top:3px}.caller-jump{display:inline-flex;max-width:250px;padding:1px 6px;border:1px solid #c9d7f0;border-radius:999px;background:#f4f7fd;color:#2864dc;font-size:10px;font-weight:550;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.caller-jump:hover{background:#e3edff}.tree>li.usage-separator{border-bottom:1px solid #cbd4e1;margin-bottom:8px;padding-bottom:8px}.operation-icon{flex:none;width:18px;height:18px;margin-top:-1px;border-radius:5px;display:inline-flex;align-items:center;justify-content:center;background:#fff4d6;color:#a76300;font-size:13px;font-weight:750;line-height:1}.operation-icon.long-press{border-radius:50%;box-shadow:inset 0 0 0 2px #e6a400}.operation-icon.input{font-size:11px}.operation-icon.toggle{color:#087f5b;background:#e8f7f1}.tree-nav{display:none;align-items:center;gap:8px;margin:0 8px 10px;padding-bottom:10px;border-bottom:1px solid var(--line)}.tree-nav.visible{display:flex}.tree-nav button{border:1px solid var(--line);border-radius:7px;background:#fff;padding:5px 9px;cursor:pointer}.tree-nav span{color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nav-view{width:100%;height:100%;overflow:auto;padding:18px}.nav-view h1{margin-bottom:4px}.nav-summary{color:var(--muted);margin:0 0 12px}.nav-shell{display:grid;grid-template-columns:minmax(650px,1fr) 340px;gap:14px;min-height:650px}.nav-canvas,.nav-detail{background:#fff;border:1px solid var(--line);border-radius:14px;box-shadow:var(--shadow)}.nav-canvas{min-height:650px;overflow:hidden}.nav-canvas svg{display:block;width:100%;height:650px}.nav-detail{padding:16px;overflow:auto}.nav-detail .card{border:0;box-shadow:none;padding:0}.graph-edge{fill:none;stroke:#8793a7;stroke-width:1.8;cursor:pointer;opacity:.78}.graph-edge:hover,.graph-edge.active{stroke-width:4;opacity:1}.graph-edge.contains-entry{stroke:#94a3b8;stroke-dasharray:5 4}.graph-edge.opens{stroke:#7657d6}.graph-edge.navigates-to{stroke:#2864dc}.graph-edge.launches-for-result{stroke:#d66a00;stroke-dasharray:8 3}.graph-node{cursor:pointer}.graph-node rect{stroke:#fff;stroke-width:2;filter:drop-shadow(0 2px 4px rgba(28,43,72,.18))}.graph-node:hover rect,.graph-node.active rect{stroke:#172033;stroke-width:3}.graph-node text{fill:#fff;font-size:12px;font-weight:650;pointer-events:none}.graph-node text.meta{font-size:10px;font-weight:450;opacity:.88}.graph-node.surface rect{fill:#397fc7}.graph-node.fragment rect{fill:#5b47a8}.graph-node.compose rect{fill:#b3438c}.graph-edge.hosts{stroke:#98a2b3;stroke-dasharray:5 5}.graph-node.dialog rect{fill:#c47a12}.graph-node.appyx-node rect{fill:#22a06b}.graph-node.entry rect{fill:#d79200}.graph-node.external rect{fill:#c45b00}.graph-legend{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:10px;color:var(--muted);font-size:12px}.graph-legend span{display:inline-flex;align-items:center;gap:5px}.legend-dot{width:10px;height:10px;border-radius:3px;display:inline-block}.rule-frame{width:100%;height:100%;border:0;background:#fff}.layout.rules,.layout.navigation{grid-template-columns:1fr}.layout.rules>aside,.layout.rules>main,.layout.rules .nav-view,.layout.navigation>aside,.layout.navigation>main,.layout.navigation .rule-frame{display:none}.layout:not(.rules) .rule-frame,.layout:not(.navigation) .nav-view{display:none}@media(max-width:900px){.nav-shell{grid-template-columns:1fr}.nav-detail{min-height:260px}}\r\n</style></head><body>\r\n<header class=\"top\"><div class=\"headline\"><div><div class=\"title\" id=\"app-title\">SPEC</div><div class=\"metrics\" id=\"metrics\"></div></div><div class=\"tag\" id=\"review-status\"></div></div><div class=\"toolbar\"><div class=\"tabs\"><button class=\"active\" data-view=\"page\">页面视图</button><button data-view=\"navigation\">页面导航</button><button data-view=\"rules\">规则查看</button></div><input class=\"search\" id=\"search\" placeholder=\"搜索页面、入口、文件…\"><button class=\"action\" id=\"expand\">全部展开</button><button class=\"action\" id=\"collapse\">全部折叠</button></div></header>\r\n<div class=\"layout\" id=\"layout\"><aside><div class=\"tree-nav\" id=\"tree-nav\"><button id=\"tree-home\">← 全部页面</button><span id=\"tree-location\"></span></div><ul class=\"tree\" id=\"tree\"></ul></aside><main id=\"detail\"></main><section class=\"nav-view\" id=\"nav-view\"></section><iframe class=\"rule-frame\" id=\"rule-frame\" src=\"../appgraph/rules.html\" title=\"规则审阅\"></iframe></div>\r\n<script>\r\nconst S=${payload},A=${activityUsagePayload};\r\nconst E=x=>String(x??'').replace(/[&<>\"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'}[c]));\r\nconst surfaces=new Map(S.facts.surfaces.map(x=>[x.surfaceRef,x])),entries=new Map(S.facts.entries.map(x=>[x.entryRef,x])),interactions=new Map(S.facts.interactions.map(x=>[x.id,x])),ui=S.facts.uiGraph,controls=new Map(ui.controls.map(x=>[x.controlRef,x]));\r\nconst surfaceSem=new Map(S.semantics.surfaces.map(x=>[x.surfaceRef,x])),controlSem=new Map(S.semantics.controls.map(x=>[x.controlRef,x])),entrySem=new Map(S.semantics.entries.map(x=>[x.entryRef,x]));\r\nlet showNavigationHosts=false;let view='page',selected=null,query='',focusSurface=null;const collapsed=new Set(),initializedBranches=new Set(),forcedOpen=new Set();\r\nconst label=(kind,id)=>{if(kind==='surface'){const x=surfaces.get(id),m=surfaceSem.get(id);return m?.name||x?.surfaceName||id}if(kind==='control'){const x=controls.get(id),m=controlSem.get(id);return m?.name||x?.name||id}if(kind==='entry'){const x=entries.get(id),m=entrySem.get(id);return m?.name||x?.displayLabel||x?.event||id}return id};\r\nconst operationLabel=id=>{const e=entries.get(id),v=String(e?.event||'').toLowerCase();if(v.includes('long'))return'长按';if(v.includes('menu'))return'点击菜单';if(v.includes('text')||v.includes('value'))return'输入变化';if(v.includes('select')||v.includes('item-selected'))return'选择';if(v.includes('check')||v.includes('toggle')||v.includes('switch'))return'切换';if(v.includes('editor'))return'键盘操作';if(v.includes('click')||v.includes('tap'))return'点击';return e?.displayLabel||e?.event||'用户操作'};\r\nconst operationIcon=id=>{const name=operationLabel(id);if(name==='长按')return['long-press','●'];if(name==='输入变化'||name==='键盘操作')return['input','⌨'];if(name==='选择')return['select','✓'];if(name==='切换')return['toggle','◐'];if(name==='点击菜单')return['menu','☰'];if(name==='点击')return['click','👆'];return['action','◆']};\r\nconst activityUsage=id=>{const x=surfaces.get(id);if(x?.surfaceType!=='activity')return null;const kind=A[x.surfaceName]||'unknown',labels={launcher:'桌面启动',external:'外部可启动',internal:'仅应用内部',unknown:'导出状态未知'};return[kind,labels[kind]]};\r\nconst activityCallers=id=>surfaces.get(id)?.surfaceType==='activity'?S.facts.interactions.filter(x=>x.toRef===id&&['opens','navigates-to'].includes(x.relation)&&entries.has(x.fromRef)).map(x=>entries.get(x.fromRef)):[];\r\nconst operationTitle=id=>{const semantic=entrySem.get(id)?.name;if(semantic)return semantic;const e=entries.get(id),display=String(e?.displayLabel||'').trim();if(display){if(/^菜单点击[::]? */.test(display))return'点击菜单:'+display.replace(/^菜单点击[::]? */, '');if(/^点击[::]? */.test(display))return'点击:'+display.replace(/^点击[::]? */, '');if(/^长按[::]? */.test(display))return'长按:'+display.replace(/^长按[::]? */, '');return display}const event=String(e?.event||'');const detail=event.includes(':')?event.slice(event.indexOf(':')+1):'';return detail?operationLabel(id)+':'+detail:operationLabel(id)};\r\nconst node=(kind,id,children=[],subOverride,titleOverride)=>({kind,id,title:titleOverride||label(kind,id),sub:subOverride||(kind==='entry'?(entrySem.get(id)?.effectType||entries.get(id)?.event||'入口'):(() => { if (kind==='control') return '交互元素'; return (() => { if (kind==='surface') return (surfaces.get(id)?.surfaceType||'页面'); return (() => { if (kind==='feature') return '功能'; return '领域'; })(); })(); })()),children});\r\nfunction pageTree(){\r\n const rendered=new Set(),controlBySurface=new Map(),entryByControl=new Map(),automaticBySurface=new Map(),resultsByEntry=new Map(),hostedBySurface=new Map();\r\n for(const c of ui.controls){if(!controlBySurface.has(c.surfaceRef))controlBySurface.set(c.surfaceRef,[]);controlBySurface.get(c.surfaceRef).push(c.controlRef)}\r\n for(const e of ui.edges){\r\n if(e.relation==='hosts'){if(!hostedBySurface.has(e.fromRef))hostedBySurface.set(e.fromRef,[]);hostedBySurface.get(e.fromRef).push(e.toRef)}\r\n else if(e.relation==='triggers'){if(!entryByControl.has(e.fromRef))entryByControl.set(e.fromRef,[]);entryByControl.get(e.fromRef).push(e.toRef)}\r\n else if(e.relation==='dispatches'){if(!automaticBySurface.has(e.fromRef))automaticBySurface.set(e.fromRef,[]);automaticBySurface.get(e.fromRef).push(e.toRef)}\r\n else if(['opens','navigates-to','launches-for-result'].includes(e.relation)){if(!resultsByEntry.has(e.fromRef))resultsByEntry.set(e.fromRef,[]);resultsByEntry.get(e.fromRef).push(e)}\r\n }\r\n const buildSurface=(ref,path=new Set())=>{\r\n if(rendered.has(ref)||path.has(ref))return node('surface',ref,[],'引用目标');\r\n rendered.add(ref);const next=new Set(path);next.add(ref);\r\n const hosted=(hostedBySurface.get(ref)||[]).map(child=>buildSurface(child,next));\r\n const linkTarget=edge=>surfaces.has(edge.toRef)\r\n ?node('surface-link',edge.toRef,[],'内部跳转 · 点击进入',label('surface',edge.toRef))\r\n :node('external-link',edge.toRef,[],'外部/系统跳转 · 点击查看',(() => { if (entries.has(edge.toRef)) return label('entry',edge.toRef); return '外部目标'; })());\r\n const cs=(controlBySurface.get(ref)||[]).map(c=>node('control',c,(entryByControl.get(c)||[]).map(e=>node('entry',e,(resultsByEntry.get(e)||[]).map(linkTarget),operationLabel(e),operationTitle(e)))));\r\n const automaticVisible=(automaticBySurface.get(ref)||[]).flatMap(e=>(resultsByEntry.get(e)||[]).filter(edge=>edge.toRef!==ref).map(linkTarget));\r\n const pending=ui.entries.filter(e=>entries.get(e)?.surfaceRef===ref&&entries.get(e)?.triggerCategory==='user'&&!ui.edges.some(edge=>edge.relation==='triggers'&&edge.toRef===e)).map(e=>node('entry',e,[],'未解析交互元素',operationTitle(e)));\r\n return node('surface',ref,hosted.concat(cs,automaticVisible,pending));\r\n };\r\n if(focusSurface&&surfaces.has(focusSurface))return[buildSurface(focusSurface)];\r\n const roots=ui.roots.map(r=>buildSurface(r));\r\n const usageRank={launcher:0,external:1,internal:2,unknown:3};\r\n roots.sort((a,b)=>{const au=activityUsage(a.id)?.[0]||'unknown',bu=activityUsage(b.id)?.[0]||'unknown';return usageRank[au]-usageRank[bu]||String(a.title).localeCompare(String(b.title),'zh-CN')});\r\n for(let i=0;i<roots.length;i++){const current=activityUsage(roots[i].id)?.[0],next=activityUsage(roots[i+1]?.id)?.[0];if(current&&current!==next)roots[i].separatorAfter=true}\r\n const remaining=ui.surfaces.filter(r=>!rendered.has(r)).map(r=>buildSurface(r));\r\n if(remaining.length)roots.push({kind:'group',id:'unresolved',title:'未确定归属页面',sub:'脚本已显式暴露',children:remaining});\r\n return roots;\r\n}\r\nfunction matches(n){return !query||JSON.stringify(n).toLowerCase().includes(query)||JSON.stringify(n.kind==='entry'?entries.get(n.id):surfaces.get(n.id)).toLowerCase().includes(query)}\r\nfunction renderNodes(items){return items.map(n=>{const key=n.kind+':'+n.id;if(n.children?.length&&!initializedBranches.has(key)){initializedBranches.add(key);if(!forcedOpen.has(key))collapsed.add(key)}const child=renderNodes(n.children||[]),visible=matches(n)||child.includes('data-visible=\"1\"'),closed=collapsed.has(key)&&!forcedOpen.has(key)&&!query,op=n.kind==='entry'?operationIcon(n.id):null,usage=n.kind==='surface'?activityUsage(n.id):null,callers=n.kind==='surface'?activityCallers(n.id):[],icon=op?'<span class=\"operation-icon '+E(op[0])+'\" title=\"'+E(operationLabel(n.id))+'\" aria-label=\"'+E(operationLabel(n.id))+'\">'+E(op[1])+'</span>':'<span class=\"kind '+E(n.kind)+'\"></span>',badge=usage?'<span class=\"activity-usage '+E(usage[0])+'\">'+E(usage[1])+'</span>':'',callerLinks=callers.length?'<span class=\"caller-links\">'+callers.map(e=>'<span class=\"caller-jump\" data-entry=\"'+E(e.entryRef)+'\" title=\"跳转到 '+E(label('surface',e.surfaceRef))+' / '+E(operationTitle(e.entryRef))+'\">↩ '+E(label('surface',e.surfaceRef))+' · '+E(operationTitle(e.entryRef))+'</span>').join('')+'</span>':'';return '<li class=\"'+(visible?'':'hidden')+(n.separatorAfter?' usage-separator':'')+'\" data-visible=\"'+(visible?'1':'0')+'\"><button class=\"node '+(selected?.kind===n.kind&&selected?.id===n.id?'active':'')+'\" data-kind=\"'+E(n.kind)+'\" data-id=\"'+E(n.id)+'\"><span class=\"twisty\" '+(n.children?.length?'data-key=\"'+E(key)+'\"':'')+'>'+(n.children?.length?((() => { if (closed) return '▸'; return '▾'; })()):'')+'</span>'+icon+'<span><span class=\"node-title\">'+E(n.title)+badge+'</span><span class=\"node-sub\">'+E(n.sub)+'</span>'+callerLinks+'</span></button>'+(n.children?.length?'<ul class=\"'+((() => { if (closed) return 'hidden'; return ''; })())+'\">'+child+'</ul>':'')+'</li>'}).join('')}\r\nconst evidence=list=>list?.length?list.map(x=>'<div class=\"evidence\"><span class=\"mono\">'+E(x.file)+((() => { if (x.line) return ' : '+x.line; return ''; })())+'</span>'+((() => { if (x.symbol) return '<div>'+E(x.symbol)+'</div>'; return ''; })())+'</div>').join(''):'<div class=\"empty\">无源码证据</div>';\r\nconst relations=id=>S.facts.interactions.filter(x=>x.fromRef===id||x.toRef===id).map(x=>'<div class=\"relation\"><span class=\"tag\">'+E(x.relation)+'</span><span>'+E(label(surfaces.has(x.fromRef)?'surface':'entry',x.fromRef))+'</span><span class=\"arrow\">→</span><span>'+E(label(surfaces.has(x.toRef)?'surface':'entry',x.toRef))+'</span></div>').join('')||'<div class=\"empty\">无直接交互</div>';\r\nfunction detail(kind,id){if(kind==='entry'){const x=entries.get(id),m=entrySem.get(id)||{};return '<section class=\"card\"><span class=\"tag\">触发入口</span><h1>'+E(label(kind,id))+'</h1><p class=\"lead\">'+E(m.description||m.userIntent||'语义尚未补充')+'</p><div class=\"grid\"><div class=\"fact\"><b>影响类型</b>'+E(m.effectType||'待分析')+'</div><div class=\"fact\"><b>事件</b>'+E(x.event)+'</div><div class=\"fact\"><b>承载页面</b>'+E(x.surfaceRef?label('surface',x.surfaceRef):'未确定')+'</div><div class=\"fact\"><b>处理函数</b>'+E((x.handlerNames||[]).join(', ')||'未解析')+'</div></div><h2>直接交互</h2>'+relations(id)+'<h2>源码证据</h2>'+evidence(x.sourceEvidence)+'<h2>调用链</h2><div class=\"mono\">'+E((x.callTrace?.handlerRefs||[]).join('\\\\n')||'无')+'</div>'+(x.warnings?.length?'<h2>警告</h2><div class=\"warning\">'+x.warnings.map(E).join('<br>')+'</div>':'')+'</section>'}if(kind==='surface'){const x=surfaces.get(id),m=surfaceSem.get(id)||{},owned=S.facts.entries.filter(e=>e.surfaceRef===id);return '<section class=\"card\"><span class=\"tag\">'+E(x.surfaceType)+'</span><h1>'+E(label(kind,id))+'</h1><p class=\"lead\">'+E(m.description||m.businessRole||'页面语义尚未补充')+'</p><div class=\"grid\"><div class=\"fact\"><b>源码名称</b>'+E(x.surfaceName)+'</div><div class=\"fact\"><b>层级状态</b>'+E(x.status)+'</div><div class=\"fact\"><b>父页面</b>'+E((x.parentSurfaceRefs||[]).map(r=>label('surface',r)).join(', ')||'根页面/未确定')+'</div><div class=\"fact\"><b>入口数量</b>'+owned.length+'</div></div><h2>页面入口</h2>'+owned.map(e=>'<div class=\"fact\"><b>'+E(label('entry',e.entryRef))+'</b><span class=\"mono\">'+E(e.entryRef)+'</span></div>').join('')+'<h2>直接交互</h2>'+relations(id)+'<h2>源码证据</h2>'+evidence(x.sourceEvidence)+'</section>'}if(kind==='feature'){const x=features.get(id),c=featureContext(x);return '<section class=\"card\"><span class=\"tag\">业务功能</span><h1>'+E(x.name)+'</h1><p class=\"lead\">'+E(x.description)+'</p><h2>业务入口</h2>'+x.entryRefs.map(r=>'<div class=\"fact\"><b>'+E(label('entry',r))+'</b><span class=\"mono\">'+E(r)+'</span></div>').join('')+'<h2>推导页面</h2>'+c.surfaceRefs.map(r=>'<span class=\"tag\">'+E(label('surface',r))+'</span>').join(' ')+'<h2>推导交互</h2>'+c.interactionRefs.map(r=>relations(interactions.get(r)?.fromRef)).join('')+'</section>'}if(kind==='domain'){const x=domains.get(id);return '<section class=\"card\"><span class=\"tag\">功能领域</span><h1>'+E(x.name)+'</h1><p class=\"lead\">'+E(x.description)+'</p><h2>直接功能</h2>'+x.featureRefs.map(r=>'<div class=\"fact\">'+E(label('feature',r))+'</div>').join('')+'</section>'}return '<section class=\"card\"><h1>'+E(id==='unassigned'?'未归入功能':'未确定页面')+'</h1><p class=\"lead\">这些确定性事实仍需要 AI 阅读源码后归类。</p></section>'}\r\nfunction renderDetail(kind,id){if(kind!=='control')return detail(kind,id);const x=controls.get(id),owned=ui.edges.filter(e=>e.relation==='triggers'&&e.fromRef===id);return '<section class=\"card\"><span class=\"tag\">交互元素</span><h1>'+E(x.name)+'</h1><div class=\"grid\"><div class=\"fact\"><b>所属页面</b>'+E(label('surface',x.surfaceRef))+'</div><div class=\"fact\"><b>源码载体</b><span class=\"mono\">'+E(x.sourceCarrierRef)+'</span></div><div class=\"fact\"><b>入口数量</b>'+owned.length+'</div><div class=\"fact\"><b>状态</b>'+E(x.status)+'</div></div><h2>触发入口</h2>'+owned.map(e=>'<div class=\"fact\"><b>'+E(label('entry',e.toRef))+'</b></div>').join('')+'<h2>源码证据</h2>'+evidence(x.sourceEvidence)+'</section>'}\r\nfunction openPageAt(surfaceRef,kind,id){view='page';focusSurface=surfaceRef;selected={kind,id};const layout=document.querySelector('#layout');layout.classList.remove('rules','navigation');document.querySelector('#search').classList.remove('hidden');document.querySelector('#expand').classList.remove('hidden');document.querySelector('#collapse').classList.remove('hidden');document.querySelectorAll('[data-view]').forEach(x=>x.classList.toggle('active',x.dataset.view==='page'));forcedOpen.clear();forcedOpen.add('surface:'+surfaceRef);if(kind==='entry'){const trigger=ui.edges.find(edge=>edge.relation==='triggers'&&edge.toRef===id);if(trigger)forcedOpen.add('control:'+trigger.fromRef)}collapsed.clear();initializedBranches.clear();render()}\r\nfunction renderNavigation(){const flows=S.facts.interactions.filter(x=>['opens','navigates-to','launches-for-result'].includes(x.relation)&&entries.has(x.fromRef));const relationMeta=x=>x.relation==='opens'?['opens','打开弹窗']:(() => { if (x.relation==='launches-for-result') return ['external','外部/系统']; return ['internal','内部跳转']; })();document.querySelector('#nav-view').innerHTML='<h1>页面跳转关系</h1><p class=\"nav-summary\">来源页面 → 触发入口 → 目标页面,共 '+flows.length+' 条确定性关系</p><div class=\"nav-flows\">'+flows.map(x=>{const entry=entries.get(x.fromRef),targetSurface=surfaces.get(x.toRef),targetEntry=entries.get(x.toRef),meta=relationMeta(x),targetName=targetSurface?label('surface',x.toRef):(() => { if (targetEntry) return label('entry',x.toRef); return '外部目标'; })();return '<div class=\"nav-flow\"><button class=\"nav-box\" data-nav-surface=\"'+E(entry.surfaceRef)+'\"><b>'+E(label('surface',entry.surfaceRef))+'</b><small>'+E(surfaces.get(entry.surfaceRef)?.surfaceType||'页面')+'</small></button><div class=\"nav-arrow\">→</div><button class=\"nav-box\" data-nav-entry=\"'+E(entry.entryRef)+'\" data-nav-owner=\"'+E(entry.surfaceRef)+'\"><b>'+E(operationTitle(entry.entryRef))+'</b><small><span class=\"nav-relation '+meta[0]+'\">'+meta[1]+'</span></small></button><div class=\"nav-arrow\">→</div>'+(targetSurface?'<button class=\"nav-box\" data-nav-surface=\"'+E(targetSurface.surfaceRef)+'\"><b>'+E(targetName)+'</b><small>'+E(targetSurface.surfaceType)+'</small></button>':'<button class=\"nav-box\" data-nav-entry=\"'+E(targetEntry?.entryRef||'')+'\" data-nav-owner=\"'+E(entry.surfaceRef)+'\"><b>'+E(targetName)+'</b><small>外部或系统结果</small></button>')+'</div>'}).join('')+'</div>';document.querySelectorAll('[data-nav-surface]').forEach(x=>x.onclick=()=>openPageAt(x.dataset.navSurface,'surface',x.dataset.navSurface));document.querySelectorAll('[data-nav-entry]').forEach(x=>x.onclick=()=>openPageAt(x.dataset.navOwner,'entry',x.dataset.navEntry))}\r\nfunction renderNavigationGraph(){const facts=S.facts.interactions.filter(x=>['opens','navigates-to','launches-for-result'].includes(x.relation)&&entries.has(x.fromRef)),nodes=new Map(),edges=[];const addNode=(key,kind,id,title,meta,owner)=>{if(!nodes.has(key))nodes.set(key,{key,kind,id,title,meta,owner,x:0,y:0});return nodes.get(key)};for(const fact of facts){const entry=entries.get(fact.fromRef),source=surfaces.get(entry.surfaceRef),targetSurface=surfaces.get(fact.toRef),targetEntry=entries.get(fact.toRef),a=addNode('s:'+source.surfaceRef,'surface',source.surfaceRef,label('surface',source.surfaceRef),source.surfaceType,source.surfaceRef),b=addNode('e:'+entry.entryRef,'entry',entry.entryRef,operationTitle(entry.entryRef),operationLabel(entry.entryRef),entry.surfaceRef),c=targetSurface?addNode('s:'+targetSurface.surfaceRef,'surface',targetSurface.surfaceRef,label('surface',targetSurface.surfaceRef),targetSurface.surfaceType,targetSurface.surfaceRef):addNode('x:'+fact.toRef,'external',fact.toRef,(() => { if (targetEntry) return label('entry',fact.toRef); return '外部目标'; })(),'外部/系统',entry.surfaceRef);edges.push({from:a,to:b,relation:'contains-entry',confidence:1,evidence:entry.sourceEvidence||[]});edges.push({from:b,to:c,relation:fact.relation,confidence:fact.confidence,evidence:fact.sourceEvidence||[]})}const list=[...nodes.values()],cx=550,cy=330;const surfacesList=list.filter(n=>n.kind==='surface'),otherList=list.filter(n=>n.kind!=='surface');surfacesList.forEach((n,i)=>{const a=2*Math.PI*i/Math.max(1,surfacesList.length)-Math.PI/2;n.x=cx+390*Math.cos(a);n.y=cy+250*Math.sin(a)});otherList.forEach((n,i)=>{const a=2*Math.PI*i/Math.max(1,otherList.length)-Math.PI/2;n.x=cx+185*Math.cos(a);n.y=cy+145*Math.sin(a)});for(let step=0;step<120;step++){for(let i=0;i<list.length;i++)for(let j=i+1;j<list.length;j++){const a=list[i],b=list[j],dx=a.x-b.x,dy=a.y-b.y,d2=Math.max(900,dx*dx+dy*dy),f=2400/d2;a.x+=dx*f;b.x-=dx*f;a.y+=dy*f;b.y-=dy*f}for(const edge of edges){const dx=edge.to.x-edge.from.x,dy=edge.to.y-edge.from.y,d=Math.max(1,Math.hypot(dx,dy)),f=(d-210)*.008,fx=dx/d*f,fy=dy/d*f;edge.from.x+=fx;edge.from.y+=fy;edge.to.x-=fx;edge.to.y-=fy}for(const n of list){n.x+=(cx-n.x)*.002;n.y+=(cy-n.y)*.002;n.x=Math.max(105,Math.min(995,n.x));n.y=Math.max(55,Math.min(605,n.y))}}const relLabel={'contains-entry':'触发','opens':'打开弹窗','navigates-to':'内部跳转','launches-for-result':'外部/系统'},trunc=x=>x.length>22?x.slice(0,21)+'…':x;document.querySelector('#nav-view').innerHTML='<h1>页面跳转关系图</h1><p class=\"nav-summary\">点击节点查看页面或入口,点击连线查看关系证据</p><div class=\"graph-legend\"><span><i class=\"legend-dot\" style=\"background:#397fc7\"></i>页面</span><span><i class=\"legend-dot\" style=\"background:#d79200\"></i>交互入口</span><span><i class=\"legend-dot\" style=\"background:#c45b00\"></i>外部/系统</span><span>蓝线:内部跳转</span><span>紫线:打开弹窗</span><span>橙色虚线:外部跳转</span></div><div class=\"nav-shell\"><div class=\"nav-canvas\"><svg id=\"nav-svg\" viewBox=\"0 0 1100 660\" role=\"img\" aria-label=\"页面导航图\"><defs><marker id=\"graph-arrow\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"6\" markerHeight=\"6\" orient=\"auto\"><path d=\"M0 0L10 5L0 10z\" fill=\"#64748b\"/></marker></defs>'+edges.map((e,i)=>'<line class=\"graph-edge '+E(e.relation)+'\" data-edge=\"'+i+'\" x1=\"'+edgePoints(e).x1.toFixed(1)+'\" y1=\"'+edgePoints(e).y1.toFixed(1)+'\" x2=\"'+edgePoints(e).x2.toFixed(1)+'\" y2=\"'+edgePoints(e).y2.toFixed(1)+'\" marker-end=\"url(#graph-arrow)\"><title>'+E(relLabel[e.relation])+'</title></line>').join('')+list.map(n=>'<g class=\"graph-node '+E(n.kind)+'\" data-node=\"'+E(n.key)+'\" transform=\"translate('+(n.x-85).toFixed(1)+' '+(n.y-22).toFixed(1)+')\"><rect width=\"170\" height=\"44\" rx=\"9\"/><text x=\"10\" y=\"18\">'+E(trunc(n.title))+'</text><text class=\"meta\" x=\"10\" y=\"35\">'+E(n.meta)+'</text></g>').join('')+'</svg></div><aside class=\"nav-detail\" id=\"nav-detail\"><div class=\"empty\">选择节点或连线查看详情</div></aside></div>';document.querySelectorAll('[data-node]').forEach(el=>el.onclick=()=>{document.querySelectorAll('.graph-node,.graph-edge').forEach(x=>x.classList.remove('active'));el.classList.add('active');const n=nodes.get(el.dataset.node),kind=n.kind==='surface'?'surface':'entry',canDetail=kind==='surface'?surfaces.has(n.id):entries.has(n.id);document.querySelector('#nav-detail').innerHTML=(canDetail?renderDetail(kind,n.id):'<section class=\"card\"><h1>'+E(n.title)+'</h1><p class=\"lead\">外部或系统页面</p></section>')+'<button class=\"action\" id=\"nav-locate\">在页面视图中定位</button>';document.querySelector('#nav-locate').onclick=()=>openPageAt(n.owner,kind,n.id)});document.querySelectorAll('[data-edge]').forEach(el=>el.onclick=()=>{document.querySelectorAll('.graph-node,.graph-edge').forEach(x=>x.classList.remove('active'));el.classList.add('active');const edge=edges[Number(el.dataset.edge)];document.querySelector('#nav-detail').innerHTML='<section class=\"card\"><span class=\"tag\">'+E(relLabel[edge.relation])+'</span><h1>'+E(edge.from.title)+' → '+E(edge.to.title)+'</h1><div class=\"grid\"><div class=\"fact\"><b>关系</b>'+E(edge.relation)+'</div><div class=\"fact\"><b>置信度</b>'+E(edge.confidence)+'</div></div><h2>源码证据</h2>'+evidence(edge.evidence)+'</section>'})}\r\nfunction renderActivityNavigationGraph(){renderSurfaceNavigationGraph()}\r\nfunction render(){if(view==='rules')return;if(view==='navigation'){renderActivityNavigationGraph();return}const roots=pageTree(),nav=document.querySelector('#tree-nav');nav.classList.toggle('visible',!!focusSurface);document.querySelector('#tree-location').textContent=focusSurface?label('surface',focusSurface):'';document.querySelector('#tree').innerHTML=renderNodes(roots);document.querySelectorAll('.node').forEach(b=>b.onclick=()=>{if(b.dataset.kind==='surface-link'){focusSurface=b.dataset.id;selected={kind:'surface',id:b.dataset.id};forcedOpen.clear();forcedOpen.add('surface:'+focusSurface);ui.controls.filter(c=>c.surfaceRef===focusSurface).forEach(c=>forcedOpen.add('control:'+c.controlRef));collapsed.clear();initializedBranches.clear();render();return}if(b.dataset.kind==='external-link'){selected={kind:'entry',id:b.dataset.id};document.querySelector('#detail').innerHTML=renderDetail('entry',b.dataset.id);render();return}selected={kind:b.dataset.kind,id:b.dataset.id};document.querySelector('#detail').innerHTML=renderDetail(selected.kind,selected.id);render()});document.querySelectorAll('.caller-jump').forEach(x=>x.onclick=e=>{e.stopPropagation();const entry=entries.get(x.dataset.entry);if(!entry?.surfaceRef)return;openPageAt(entry.surfaceRef,'entry',entry.entryRef)});document.querySelectorAll('.twisty[data-key]').forEach(t=>t.onclick=e=>{e.stopPropagation();forcedOpen.delete(t.dataset.key);collapsed.has(t.dataset.key)?collapsed.delete(t.dataset.key):collapsed.add(t.dataset.key);render()});if(!selected){const first=roots[0];if(first)selected={kind:first.kind,id:first.id}}document.querySelector('#detail').innerHTML=selected?renderDetail(selected.kind,selected.id):'<section class=\"card\"><h1>暂无数据</h1></section>'}\r\ndocument.querySelector('#tree-home').onclick=()=>{focusSurface=null;selected=null;forcedOpen.clear();collapsed.clear();initializedBranches.clear();render()};\r\ndocument.querySelector('#app-title').textContent=(S.semantics.app.name||S.facts.app.name)+' · SPEC';document.querySelector('#review-status').textContent='状态:'+S.review.status;document.querySelector('#metrics').innerHTML=[['页面',ui.surfaces.length],['交互元素',ui.controls.length],['UI入口',ui.entries.length],['未解析',ui.unresolved.length]].map(x=>'<span class=\"metric\"><b>'+x[1]+'</b> '+x[0]+'</span>').join('');\r\ndocument.querySelectorAll('[data-view]').forEach(b=>b.onclick=()=>{view=b.dataset.view;selected=null;const layout=document.querySelector('#layout');layout.classList.toggle('rules',view==='rules');layout.classList.toggle('navigation',view==='navigation');document.querySelector('#search').classList.toggle('hidden',view!=='page');document.querySelector('#expand').classList.toggle('hidden',view!=='page');document.querySelector('#collapse').classList.toggle('hidden',view!=='page');document.querySelectorAll('[data-view]').forEach(x=>x.classList.toggle('active',x===b));render()});document.querySelector('#search').oninput=e=>{query=e.target.value.trim().toLowerCase();render()};document.querySelector('#collapse').onclick=()=>{document.querySelectorAll('.twisty[data-key]').forEach(x=>collapsed.add(x.dataset.key));render()};document.querySelector('#expand').onclick=()=>{collapsed.clear();render()};render();\r\n${String.raw`\r\nfunction renderSurfaceNavigationGraph(){\r\n const typeMeta={activity:id=>'Activity · '+(activityUsage(id)?.[1]||'状态未知'),fragment:()=>'Fragment',compose:()=>'Compose',dialog:()=>'Dialog','appyx-node':()=>'Appyx Node'};\r\n const typeColor={activity:'#397fc7',fragment:'#5b47a8',compose:'#b3438c',dialog:'#c47a12','appyx-node':'#22a06b',screen:'#397fc7'};\r\n const typeTitle={activity:'Activity',fragment:'Fragment',compose:'Compose',dialog:'Dialog','appyx-node':'Appyx Node',screen:'页面'};\r\n const surfaceNodes=S.facts.surfaces.filter(x=>['activity','fragment','compose','dialog','appyx-node','screen'].includes(x.surfaceType)).map(x=>({key:x.surfaceRef,id:x.surfaceRef,title:label('surface',x.surfaceRef),surfaceType:x.surfaceType,meta:(typeMeta[x.surfaceType]||(()=>x.surfaceType))(x.surfaceRef),x:0,y:0}));\r\n const nodes=new Map(surfaceNodes.map(x=>[x.id,x])),edges=[];\r\n const sourceSurface=fact=>{const direct=nodes.get(fact.fromRef);if(direct)return direct;const entry=entries.get(fact.fromRef);return entry?.surfaceRef?nodes.get(entry.surfaceRef):null};\r\n const targetSurface=fact=>nodes.get(fact.toRef);\r\n for(const fact of S.facts.interactions.filter(x=>['opens','navigates-to','launches-for-result'].includes(x.relation))){const from=sourceSurface(fact),to=targetSurface(fact);if(from&&to&&from!==to)edges.push({from,to,fact,entry:entries.get(fact.fromRef)||null})}\r\n if(showNavigationHosts)for(const fact of ui.edges.filter(x=>x.relation==='hosts')){const from=nodes.get(fact.fromRef),to=nodes.get(fact.toRef);if(from&&to)edges.push({from,to,fact,entry:null})}\r\n const cx=550,cy=325,rx=390,ry=245;surfaceNodes.forEach((n,i)=>{const a=2*Math.PI*i/Math.max(1,surfaceNodes.length)-Math.PI/2;n.x=cx+rx*Math.cos(a);n.y=cy+ry*Math.sin(a)});\r\n for(let step=0;step<100;step++){for(let i=0;i<surfaceNodes.length;i++)for(let j=i+1;j<surfaceNodes.length;j++){const a=surfaceNodes[i],b=surfaceNodes[j],dx=a.x-b.x,dy=a.y-b.y,d2=Math.max(1200,dx*dx+dy*dy),f=3000/d2;a.x+=dx*f;b.x-=dx*f;a.y+=dy*f;b.y-=dy*f}for(const edge of edges){const dx=edge.to.x-edge.from.x,dy=edge.to.y-edge.from.y,d=Math.max(1,Math.hypot(dx,dy)),f=(d-300)*.006,fx=dx/d*f,fy=dy/d*f;edge.from.x+=fx;edge.from.y+=fy;edge.to.x-=fx;edge.to.y-=fy}for(const n of surfaceNodes){n.x+=(cx-n.x)*.001;n.y+=(cy-n.y)*.001;n.x=Math.max(105,Math.min(995,n.x));n.y=Math.max(55,Math.min(605,n.y))}}\r\n const relationLabel=x=>({'opens':'展示页面/弹窗','navigates-to':'页面导航','launches-for-result':'启动并等待结果','hosts':'承载(宿主关系)'}[x]||x),trunc=x=>x.length>24?x.slice(0,23)+'…':x,edgePoints=e=>{const dx=e.to.x-e.from.x,dy=e.to.y-e.from.y,scale=1/Math.max(Math.abs(dx)/85,Math.abs(dy)/22,1e-6);return{x1:e.from.x+dx*scale,y1:e.from.y+dy*scale,x2:e.to.x-dx*scale,y2:e.to.y-dy*scale}};\r\n const present=[...new Set(surfaceNodes.map(n=>n.surfaceType))];\r\n const legend=present.map(t=>'<span><i class=\"legend-dot\" style=\"background:'+typeColor[t]+'\"></i>'+typeTitle[t]+'</span>').join('')+'<span>蓝线:页面导航</span><span>紫线:展示页面/弹窗</span><span>灰色虚线:宿主关系</span>';\r\n document.querySelector('#nav-view').innerHTML='<h1>页面导航图</h1><p class=\"nav-summary\">显示 Activity、Fragment、Compose、Dialog 和 Appyx Node 之间的导航;点击节点或连线查看详情</p><label><input type=\"checkbox\" id=\"nav-hosts\" '+(showNavigationHosts?'checked':'')+'> 显示宿主关系(承载)</label><div class=\"graph-legend\">'+legend+'</div><div class=\"nav-shell\"><div class=\"nav-canvas\"><svg id=\"nav-svg\" viewBox=\"0 0 1100 660\" role=\"img\" aria-label=\"页面导航图\"><defs><marker id=\"graph-arrow\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"9\" markerHeight=\"9\" orient=\"auto\" markerUnits=\"strokeWidth\"><path d=\"M0 0L10 5L0 10z\" fill=\"#2864dc\"/></marker><marker id=\"graph-arrow-opens\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"9\" markerHeight=\"9\" orient=\"auto\" markerUnits=\"strokeWidth\"><path d=\"M0 0L10 5L0 10z\" fill=\"#7657d6\"/></marker></defs>'+edges.map((e,i)=>'<line class=\"graph-edge '+E(e.fact.relation)+'\" data-appyx-edge=\"'+i+'\" x1=\"'+edgePoints(e).x1.toFixed(1)+'\" y1=\"'+edgePoints(e).y1.toFixed(1)+'\" x2=\"'+edgePoints(e).x2.toFixed(1)+'\" y2=\"'+edgePoints(e).y2.toFixed(1)+'\" marker-end=\"url(#'+(e.fact.relation==='opens'?'graph-arrow-opens':'graph-arrow')+')\"><title>'+E(e.from.title+' → '+e.to.title+' · '+relationLabel(e.fact.relation))+'</title></line>').join('')+surfaceNodes.map(n=>'<g class=\"graph-node surface '+E(n.surfaceType)+'\" data-appyx-node=\"'+E(n.id)+'\" transform=\"translate('+(n.x-85).toFixed(1)+' '+(n.y-22).toFixed(1)+')\"><rect width=\"170\" height=\"44\" rx=\"9\"/><text x=\"10\" y=\"18\">'+E(trunc(n.title))+'</text><text class=\"meta\" x=\"10\" y=\"35\">'+E(n.meta)+'</text></g>').join('')+'</svg></div><aside class=\"nav-detail\" id=\"nav-detail\"><div class=\"empty\">选择页面或跳转线查看详情</div></aside></div>';\r\n document.querySelector('#nav-hosts').onchange=e=>{showNavigationHosts=e.target.checked;renderSurfaceNavigationGraph()};\r\n document.querySelectorAll('[data-appyx-node]').forEach(el=>el.onclick=()=>{document.querySelectorAll('.graph-node,.graph-edge').forEach(x=>x.classList.remove('active'));el.classList.add('active');const id=el.dataset.appyxNode;document.querySelector('#nav-detail').innerHTML=renderDetail('surface',id)+'<button class=\"action\" id=\"nav-locate\">在页面视图中定位</button>';document.querySelector('#nav-locate').onclick=()=>openPageAt(id,'surface',id)});\r\n document.querySelectorAll('[data-appyx-edge]').forEach(el=>el.onclick=()=>{document.querySelectorAll('.graph-node,.graph-edge').forEach(x=>x.classList.remove('active'));el.classList.add('active');const edge=edges[Number(el.dataset.appyxEdge)],source=edge.entry?operationTitle(edge.entry.entryRef):'页面直接导航';document.querySelector('#nav-detail').innerHTML='<section class=\"card\"><span class=\"tag\">'+E(relationLabel(edge.fact.relation))+'</span><h1>'+E(edge.from.title)+' → '+E(edge.to.title)+'</h1><div class=\"grid\"><div class=\"fact\"><b>来源</b>'+E(source)+'</div><div class=\"fact\"><b>关系</b>'+E(edge.fact.relation)+'</div><div class=\"fact\"><b>置信度</b>'+E(edge.fact.confidence)+'</div></div><div class=\"fact\"><b>分支条件</b>'+E(edge.fact.branchCondition?.expression||'无')+'</div><h2>源码证据</h2>'+evidence(edge.fact.sourceEvidence)+'</section>'})\r\n}\r\n`}</script></body></html>`;\r\n\r\nfs.mkdirSync(path.dirname(outputPath), { recursive: true });\r\nconst temporary = `${outputPath}.tmp`;\r\nfs.writeFileSync(temporary, html, \"utf8\");\r\nfs.renameSync(temporary, outputPath);\r\nreturn { valid: true, kind: \"spec-html\", input: specPath, output: outputPath, views: [\"page\", \"navigation\", \"rules\"] };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\n\r\nexport function renderMigrationReport(projectArgument = \".\") {\r\nconst projectRoot = path.resolve(projectArgument);\r\nconst migrationRoot = migrationDirectory(projectRoot);\r\nconst reportRoot = path.join(migrationRoot, \"report\");\r\nconst specRoot = path.join(migrationRoot, \"spec\");\r\nconst outputPath = path.join(reportRoot, \"report.html\");\r\nconst fail = (message) => { throw new Error(message); };\r\nconst read = (file) => JSON.parse(fs.readFileSync(file, \"utf8\"));\r\nconst required = (file, label) => { if (!fs.existsSync(file)) fail(`${label} not found: ${file}`); return read(file); };\r\nconst requiredReport = (relative, label) => {\r\n if (typeof relative !== \"string\" || !relative.trim() || path.isAbsolute(relative)) fail(`${label} path must be report-relative`);\r\n const absolute = path.resolve(reportRoot, relative);\r\n const relation = path.relative(reportRoot, absolute);\r\n if (!relation || relation === \"..\" || relation.startsWith(`..${path.sep}`) || path.isAbsolute(relation)) fail(`${label} path escapes report root`);\r\n if (!fs.existsSync(absolute)) fail(`${label} not found: ${absolute}`);\r\n const realRoot = fs.realpathSync(reportRoot);\r\n const realFile = fs.realpathSync(absolute);\r\n const realRelation = path.relative(realRoot, realFile);\r\n if (realRelation === \"..\" || realRelation.startsWith(`..${path.sep}`) || path.isAbsolute(realRelation)) fail(`${label} path resolves outside report root`);\r\n return read(realFile);\r\n};\r\nconst esc = (value) => String(value ?? \"\").replaceAll(\"&\", \"&amp;\").replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\").replaceAll('\"', \"&quot;\");\r\nconst list = (values, empty = \"暂无\") => values?.length ? `<ul>${values.map((value) => `<li>${esc(value)}</li>`).join(\"\")}</ul>` : `<span class=\"muted\">${empty}</span>`;\r\nconst statusText = { pending: \"待处理\", implemented: \"已实现·待验证\", verified: \"已验证\", blocked: \"受阻\", passed: \"通过\", failed: \"失败\", \"in-progress\": \"迁移中\", complete: \"已完成\" };\r\nconst status = (value) => `<span class=\"status ${esc(value)}\">${esc(statusText[value] ?? value ?? \"未知\")}</span>`;\r\n\r\nconst index = required(path.join(reportRoot, \"index.json\"), \"report index\");\r\nconst validation = fs.existsSync(path.join(reportRoot, \"validation.json\")) ? read(path.join(reportRoot, \"validation.json\")) : null;\r\nconst acceptance = requiredReport(index.finalAcceptanceFile, \"final acceptance\");\r\nconst specIndex = required(path.join(specRoot, \"index.json\"), \"SPEC index\");\r\nconst pageFactsIndex = required(path.join(specRoot, specIndex.files.facts.pages), \"page facts index\");\r\nconst interactionFacts = required(path.join(specRoot, specIndex.files.facts.interactions), \"interaction facts\");\r\nconst unresolved = requiredReport(index.unresolvedFile, \"unresolved report\");\r\nconst discoveries = requiredReport(index.discoveriesFile, \"discoveries report\");\r\nconst userSummary = requiredReport(index.summaryFile, \"user summary\");\r\nconst interactionReport = requiredReport(index.interactionsFile, \"interaction report\");\r\n\r\nconst factPages = new Map();\r\nfor (const descriptor of pageFactsIndex.pages ?? []) {\r\n const shard = read(path.join(specRoot, descriptor.file));\r\n factPages.set(shard.surface?.surfaceRef, shard);\r\n}\r\nconst pages = (index.pages ?? []).map((descriptor) => {\r\n const report = requiredReport(descriptor.file, \"page report shard\");\r\n return { descriptor, report, facts: factPages.get(descriptor.surfaceRef) ?? {} };\r\n});\r\nconst allItems = [\r\n ...pages.flatMap(({ report }) => [report.page, ...(report.controls ?? []), ...(report.entries ?? [])]),\r\n ...(interactionReport.interactions ?? [])\r\n].filter(Boolean);\r\nconst counts: Record<string, number> = [\"pending\", \"implemented\", \"verified\", \"blocked\"].reduce((result, value) => ({ ...result, [value]: allItems.filter((item) => item.status === value).length }), {});\r\nconst total = allItems.length;\r\nconst done = counts.verified;\r\nconst percent = total ? Math.round(done * 100 / total) : 0;\r\nconst labels = new Map(allItems.map((item) => [item.ref, item.factLabel]));\r\nfor (const { facts } of pages) {\r\n if (facts.surface?.surfaceRef) labels.set(facts.surface.surfaceRef, facts.surface.surfaceName ?? facts.surface.surfaceRef);\r\n for (const control of facts.controls ?? []) {\r\n const label = control.displayLabel || control.name || control.controlRef;\r\n for (const ref of [control.controlRef, control.sourceCarrierRef, control.carrierRef]) if (ref) labels.set(ref, label);\r\n }\r\n for (const entry of facts.entries ?? []) {\r\n const label = entry.displayLabel || entry.event || entry.entryRef;\r\n for (const ref of [entry.entryRef, entry.carrierRef, entry.sourceCarrierRef]) if (ref) labels.set(ref, label);\r\n }\r\n}\r\nconst interactionById = new Map<string, any>((interactionFacts.interactions ?? []).map((item) => [item.id, item]));\r\nconst relationText = { opens: \"打开\", \"navigates-to\": \"导航到\", \"launches-for-result\": \"启动并等待结果\", \"contains-entry\": \"包含入口\" };\r\nconst provenanceList = (values) => values?.length ? `<ul>${values.map((value) => {\r\n const ranges = (() => { if (value.ranges?.length) return ` · ${value.ranges.map((range) => `${range.symbol}:${range.startLine}-${range.endLine}`).join(\"、\")}`; return \" · 整文件\"; })();\r\n return `<li><code>${esc(value.androidFile)}</code> · sha256:${esc(value.fileSha256)}${esc(ranges)}</li>`;\r\n}).join(\"\")}</ul>` : '<span class=\"muted\">暂无</span>';\r\nconst fileDetails = (item) => `<details><summary>技术追溯</summary><div class=\"trace\"><b>实现文件</b>${list(item.harmonyosFiles)}<b>Android 源码依据</b>${provenanceList(item.sourceProvenance)}<b>测试证据</b>${list(item.testEvidence)}<b>事实引用</b><code>${esc(item.ref)}</code></div></details>`;\r\nconst itemRow = (item) => `<div class=\"item\"><div><strong>${esc(item.factLabel)}</strong>${status(item.status)}${item.difference ? `<p class=\"difference\">${esc(item.difference)}</p>` : \"\"}</div>${fileDetails(item)}</div>`;\r\n\r\nconst pageSections = pages.map(({ report, facts }) => {\r\n const type = facts.surface?.surfaceKind ?? facts.surface?.kind ?? \"页面/组件\";\r\n return `<details class=\"page\"><summary><span><strong>${esc(report.page.factLabel)}</strong><small>${esc(type)}</small></span>${status(report.page.status)}</summary>\r\n <div class=\"page-body\">${report.page.difference ? `<p class=\"difference\">${esc(report.page.difference)}</p>` : \"\"}${fileDetails(report.page)}\r\n <h4>用户可见控件 <span>${(report.controls ?? []).length}</span></h4>${(report.controls ?? []).length ? (report.controls ?? []).map(itemRow).join(\"\") : '<p class=\"muted\">未记录控件</p>'}\r\n <h4>交互入口 <span>${(report.entries ?? []).length}</span></h4>${(report.entries ?? []).length ? (report.entries ?? []).map(itemRow).join(\"\") : '<p class=\"muted\">未记录交互入口</p>'}\r\n </div></details>`;\r\n}).join(\"\");\r\n\r\nconst interactionRows = (interactionReport.interactions ?? []).map((item) => {\r\n const fact = interactionById.get(item.ref) ?? {};\r\n const from = labels.get(fact.fromRef) ?? \"未识别来源(见技术追溯)\";\r\n const to = labels.get(fact.toRef) ?? \"未识别目标(见技术追溯)\";\r\n return `<div class=\"flow\"><div><strong>${esc(from)}</strong><span>${esc(relationText[fact.relation] ?? fact.relation ?? item.factLabel)}</span><strong>${esc(to)}</strong></div>${status(item.status)}${item.difference ? `<p class=\"difference\">${esc(item.difference)}</p>` : \"\"}${fileDetails(item)}</div>`;\r\n}).join(\"\");\r\n\r\nconst testRows = (acceptance.tests ?? []).map((test) => `<div class=\"test\"><div><strong>${esc(test.name)}</strong>${status(test.status)}</div><div>${list(test.evidence, \"未记录证据\")}</div></div>`).join(\"\");\r\nconst unresolvedPending = (unresolved.reviews ?? []).filter((item) => item.decision === \"pending\");\r\nconst discoveryItems = discoveries.items ?? [];\r\nconst appName = index.app?.factLabel ?? \"Android 应用\";\r\nconst finalState = validation?.complete && acceptance.status === \"passed\" ? \"complete\" : (() => { if (acceptance.status === \"failed\") return \"failed\"; return \"in-progress\"; })();\r\nconst incompleteItems = allItems.filter((item) => item.status !== \"verified\");\r\nconst kindText = { page: \"页面/组件\", control: \"控件\", entry: \"交互入口\", interaction: \"导航/Dialog\" };\r\nconst automaticIncomplete = [\"page\", \"control\", \"entry\", \"interaction\"].flatMap((kind) => [\"pending\", \"implemented\", \"blocked\"].map((itemStatus) => {\r\n const count = incompleteItems.filter((item) => item.kind === kind && item.status === itemStatus).length;\r\n return count ? `${kindText[kind]}:${count} 项${statusText[itemStatus]}` : null;\r\n})).filter(Boolean);\r\nconst summarySections = (userSummary.additionalSections ?? []).map((section) => `<h3>${esc(section.title)}</h3><p>${esc(section.content)}</p>`).join(\"\");\r\n\r\nconst html = `<!doctype html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${esc(appName)} · 鸿蒙迁移报告</title><style>\r\n:root{--bg:#f4f7fb;--panel:#fff;--text:#162033;--muted:#667085;--line:#e2e8f0;--blue:#2563eb;--green:#15803d;--amber:#b45309;--red:#b42318}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.6 system-ui,-apple-system,\"Segoe UI\",\"Microsoft YaHei\",sans-serif}header{background:linear-gradient(135deg,#172554,#1d4ed8);color:#fff;padding:34px max(24px,calc((100% - 1180px)/2))}header h1{margin:0 0 6px;font-size:30px}header p{margin:0;color:#dbeafe}.wrap{max-width:1180px;margin:auto;padding:24px}.hero,.card,.page{background:var(--panel);border:1px solid var(--line);border-radius:14px;box-shadow:0 4px 18px #0f172a0b}.hero{padding:22px;display:grid;grid-template-columns:180px 1fr;gap:26px;align-items:center}.score{font-size:44px;font-weight:750;color:var(--blue);text-align:center}.score small{display:block;font-size:13px;color:var(--muted);font-weight:500}.bar{height:10px;background:#e5e7eb;border-radius:99px;overflow:hidden}.bar i{display:block;height:100%;background:var(--blue);width:${percent}%}.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-top:15px}.stat{background:#f8fafc;border-radius:9px;padding:9px 12px}.stat b{display:block;font-size:20px}.tabs{display:flex;gap:8px;position:sticky;top:0;background:var(--bg);padding:16px 0;z-index:2}.tabs a{text-decoration:none;color:#344054;background:#fff;border:1px solid var(--line);padding:7px 12px;border-radius:9px}section{scroll-margin-top:75px;margin:20px 0}section>h2{font-size:20px;margin:0 0 12px}.card{padding:18px}.page{margin:10px 0;overflow:hidden}.page>summary{padding:14px 18px;display:flex;justify-content:space-between;align-items:center;cursor:pointer}.page>summary span:first-child{display:flex;gap:12px;align-items:center}.page small{color:var(--muted);font-weight:400}.page-body{border-top:1px solid var(--line);padding:14px 18px 18px}.page h4{margin:18px 0 5px}.page h4 span{color:var(--muted);font-weight:400}.item,.flow,.test{border-top:1px solid #edf0f5;padding:10px 0}.item{display:grid;grid-template-columns:1fr auto;gap:16px}.flow>div:first-child{display:flex;align-items:center;gap:10px}.flow>div:first-child span{color:var(--blue)}.status{display:inline-block;margin-left:10px;padding:2px 8px;border-radius:99px;font-size:12px;background:#eef2f6;color:#475467}.status.verified,.status.passed,.status.complete{background:#dcfce7;color:var(--green)}.status.implemented,.status.in-progress{background:#fef3c7;color:var(--amber)}.status.blocked,.status.failed{background:#fee2e2;color:var(--red)}details summary{cursor:pointer}details>summary::marker{color:#94a3b8}.trace{background:#f8fafc;border-radius:8px;padding:10px;margin-top:8px}.trace b{display:block;margin-top:5px}.trace ul{margin:2px 0}.trace code{word-break:break-all;color:var(--muted)}.difference{color:var(--red);margin:5px 0}.muted{color:var(--muted)}ul{margin:5px 0;padding-left:22px}.notice{border-left:4px solid var(--amber);padding:10px 14px;background:#fffbeb}.ok{border-left-color:var(--green);background:#f0fdf4}@media(max-width:700px){.hero{grid-template-columns:1fr}.stats{grid-template-columns:1fr 1fr}.item{grid-template-columns:1fr}.flow>div:first-child{align-items:flex-start;flex-direction:column}.tabs{overflow:auto}}\r\n</style></head><body><header><h1>${esc(appName)} · 鸿蒙迁移报告</h1><p>面向用户的迁移结果、验证证据与已知差异</p></header><main class=\"wrap\">\r\n<div class=\"hero\"><div class=\"score\">${percent}%<small>已验证 ${done} / ${total}</small></div><div><div class=\"bar\"><i></i></div><div class=\"stats\"><div class=\"stat\"><b>${counts.verified}</b>已验证</div><div class=\"stat\"><b>${counts.implemented}</b>待验证</div><div class=\"stat\"><b>${counts.pending}</b>待处理</div><div class=\"stat\"><b>${counts.blocked}</b>受阻</div></div></div></div>\r\n<nav class=\"tabs\"><a href=\"#summary\">结论</a><a href=\"#tests\">端到端测试</a><a href=\"#issues\">差异与问题</a><a href=\"#trace\">技术追溯</a></nav>\r\n<section id=\"summary\"><h2>迁移结论</h2><div class=\"card\">${finalState !== \"complete\" ? '<p class=\"notice\"><strong>当前是阶段性报告,尚未通过最终完整性验收。</strong></p>' : \"\"}<p>${status(finalState)} ${esc(userSummary.summary || (finalState === \"complete\" ? \"迁移报告完整,且最终端到端验收已通过。\" : \"迁移尚未完成或最终端到端验收尚未通过。\"))}</p><p class=\"muted\">AI 总结用于解释迁移结果;上方状态和下方统计由脚本根据事实覆盖与测试证据计算,并具有优先级。编译成功本身不代表迁移完成。</p><h3>未完成内容</h3>${list(userSummary.incomplete, \"AI 未补充未完成项说明\")}${automaticIncomplete.length ? `<div class=\"notice\"><strong>脚本汇总</strong>${list(automaticIncomplete)}</div>` : '<p class=\"notice ok\">脚本未检测到未完成的事实项。</p>'}<h3>用户下一步</h3>${list(userSummary.nextSteps, \"没有需要用户继续处理的操作\")}${summarySections}</div></section>\r\n<section id=\"tests\"><h2>端到端测试</h2><div class=\"card\">${testRows || '<p class=\"notice\">尚未记录最终端到端测试。必须在 HarmonyOS 模拟器或真机上从真实入口操作应用。</p>'}${acceptance.notes?.length ? `<h3>验收说明</h3>${list(acceptance.notes)}` : \"\"}</div></section>\r\n<section id=\"issues\"><h2>差异、阻塞与分析补充</h2><div class=\"card\">${acceptance.blockers?.length ? `<h3>阻塞项</h3>${list(acceptance.blockers)}` : '<p class=\"notice ok\">最终验收未记录阻塞项。</p>'}<h3>待确认的静态分析项</h3><p>${unresolvedPending.length} 项。内部引用不在用户视图逐条展示,可在 JSON 技术账本中追溯。</p><h3>AI 补充发现</h3><p>${discoveryItems.length} 项</p>${discoveryItems.length ? list(discoveryItems.map((item) => item.label || item.factLabel || \"补充发现(见技术追溯)\")) : \"\"}</div></section>\r\n<section id=\"trace\"><h2>技术追溯附录</h2><details class=\"card\"><summary><strong>展开页面、控件、入口、导航与代码证据</strong></summary><p class=\"muted\">本附录用于证明迁移结论和排查遗漏,不是用户报告主体。</p><h3>页面、控件与交互入口</h3>${pageSections || '<p class=\"muted\">暂无页面记录</p>'}<h3>页面导航与 Dialog</h3><div>${interactionRows || '<p class=\"muted\">暂无交互关系</p>'}</div><details><summary>分析基线与校验信息</summary><div class=\"trace\"><p>SPEC facts:<code>${esc(index.baseline?.factsSha256)}</code></p><p>结构校验:${validation ? ((() => { if (validation.valid) return \"通过\"; return \"失败\"; })()) : \"尚未运行\"};完整性校验:${validation?.complete ? \"通过\" : \"未通过\"}</p></div></details></details></section>\r\n</main></body></html>`;\r\n\r\nfs.mkdirSync(reportRoot, { recursive: true });\r\nfs.writeFileSync(outputPath, html, \"utf8\");\r\nreturn { ok: true, output: outputPath, appName, status: finalState, completionPercent: percent, counts };\r\n}\r\n","import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\r\nimport { dirname, resolve } from \"node:path\";\r\nimport { spawn, spawnSync } from \"node:child_process\";\r\nimport { setTimeout as delay } from \"node:timers/promises\";\r\n\r\nfunction quotePowerShell(value) {\r\n return `'${String(value).replaceAll(\"'\", \"''\")}'`;\r\n}\r\n\r\nfunction quoteWindowsCommandArg(value) {\r\n const text = String(value);\r\n if (!/[\\s\"]/u.test(text)) return text;\r\n return `\"${text.replace(/(\\\\*)\"/gu, \"$1$1\\\\\\\"\").replace(/(\\\\+)$/u, \"$1$1\")}\"`;\r\n}\r\n\r\nfunction isAlive(pid) {\r\n if (!Number.isInteger(pid) || pid <= 0) return false;\r\n try {\r\n process.kill(pid, 0);\r\n return true;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nasync function isHealthy(url) {\r\n if (!url) return true;\r\n try {\r\n const response = await fetch(url, { signal: AbortSignal.timeout(1500) });\r\n return response.ok;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nfunction readPid(pidFile) {\r\n try {\r\n const pid = Number.parseInt(readFileSync(pidFile, \"utf8\").trim(), 10);\r\n return Number.isInteger(pid) ? pid : null;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nexport async function statusBackgroundService(options) {\r\n const pidFile = resolve(options.pidFile);\r\n const pid = readPid(pidFile);\r\n const running = pid !== null && isAlive(pid);\r\n const healthy = running ? await isHealthy(options.healthUrl) : false;\r\n return {\r\n status: running && healthy ? \"running\" : (() => { if (running) return \"unhealthy\"; return \"stopped\"; })(),\r\n pid,\r\n health: options.healthUrl ?? null,\r\n };\r\n}\r\n\r\nexport function stopBackgroundService(options) {\r\n const pidFile = resolve(options.pidFile);\r\n const pid = readPid(pidFile);\r\n if (!pid || !isAlive(pid)) {\r\n if (existsSync(pidFile)) unlinkSync(pidFile);\r\n return { status: \"stopped\", pid: pid ?? null, alreadyStopped: true };\r\n }\r\n process.kill(pid, \"SIGTERM\");\r\n if (existsSync(pidFile)) unlinkSync(pidFile);\r\n return { status: \"stopped\", pid, alreadyStopped: false };\r\n}\r\n\r\nexport function writePidAtomically(pidFile, pid) {\r\n mkdirSync(dirname(pidFile), { recursive: true });\r\n const temporary = `${pidFile}.${process.pid}.tmp`;\r\n writeFileSync(temporary, `${pid}\\n`, \"utf8\");\r\n renameSync(temporary, pidFile);\r\n}\r\n\r\nexport function runDetachedHost(requestPath) {\r\n const request = JSON.parse(readFileSync(requestPath, \"utf8\"));\r\n mkdirSync(dirname(request.stdout), { recursive: true });\r\n mkdirSync(dirname(request.stderr), { recursive: true });\r\n const stdout = openSync(request.stdout, \"a\");\r\n const stderr = openSync(request.stderr, \"a\");\r\n try {\r\n const child = spawn(request.command[0], request.command.slice(1), {\r\n cwd: request.cwd,\r\n detached: true,\r\n env: { ...process.env, ...(request.env ?? {}) },\r\n stdio: [\"ignore\", stdout, stderr],\r\n windowsHide: true,\r\n });\r\n child.once(\"error\", (error) => {\r\n writeFileSync(`${request.pidFile}.error`, `${error.stack ?? error.message}\\n`, \"utf8\");\r\n });\r\n writePidAtomically(request.pidFile, child.pid);\r\n child.unref();\r\n } finally {\r\n closeSync(stdout);\r\n closeSync(stderr);\r\n }\r\n}\r\n\r\nexport function launchHostOutsideRunner(requestPath, hostCommand) {\r\n if (!Array.isArray(hostCommand) || !hostCommand.length) throw new Error(\"缺少后台服务 hostCommand\");\r\n if (process.platform !== \"win32\") {\r\n const host = spawn(hostCommand[0], [...hostCommand.slice(1), requestPath], {\r\n cwd: dirname(requestPath),\r\n detached: true,\r\n stdio: \"ignore\",\r\n });\r\n host.unref();\r\n return;\r\n }\r\n\r\n const windowsHostCommand = [...hostCommand, requestPath]\r\n .map(quoteWindowsCommandArg)\r\n .join(\" \");\r\n const source = [\r\n `$result = ([wmiclass]'Win32_Process').Create(${quotePowerShell(windowsHostCommand)})`,\r\n \"if ($result.ReturnValue -ne 0) { Write-Error (\\\"Win32_Process.Create failed: \\\" + $result.ReturnValue); exit 1 }\",\r\n \"Write-Output $result.ProcessId\",\r\n ].join(\"; \");\r\n const encoded = Buffer.from(source, \"utf16le\").toString(\"base64\");\r\n const powershell = process.env.SystemRoot\r\n ? resolve(process.env.SystemRoot, \"System32\", \"WindowsPowerShell\", \"v1.0\", \"powershell.exe\")\r\n : \"powershell.exe\";\r\n const result = spawnSync(powershell, [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-EncodedCommand\", encoded], {\r\n encoding: \"utf8\",\r\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\r\n timeout: 15000,\r\n windowsHide: true,\r\n });\r\n if (result.error || result.status !== 0) {\r\n throw new Error(`无法通过 Win32_Process.Create 脱离命令运行器启动服务:${result.error?.message ?? result.stderr.trim()}`);\r\n }\r\n}\r\n\r\nexport async function startBackgroundService(options) {\r\n const cwd = resolve(options.cwd);\r\n const pidFile = resolve(options.pidFile);\r\n const stdout = resolve(options.stdout);\r\n const stderr = resolve(options.stderr);\r\n const timeoutMs = options.timeoutMs ?? 15000;\r\n const existingPid = readPid(pidFile);\r\n if (existingPid && isAlive(existingPid) && await isHealthy(options.healthUrl)) {\r\n return { status: \"reused\", pid: existingPid, health: options.healthUrl ?? null, stdout, stderr };\r\n }\r\n if (existingPid && isAlive(existingPid)) {\r\n throw new Error(`PID ${existingPid} 仍在运行但健康检查失败;请先检查日志或显式停止该进程`);\r\n }\r\n\r\n mkdirSync(dirname(pidFile), { recursive: true });\r\n const requestPath = `${pidFile}.launch.json`;\r\n writeFileSync(requestPath, JSON.stringify({\r\n cwd,\r\n pidFile,\r\n stdout,\r\n stderr,\r\n command: options.command,\r\n env: options.env ?? {},\r\n }, null, 2));\r\n launchHostOutsideRunner(requestPath, options.hostCommand);\r\n\r\n const deadline = Date.now() + timeoutMs;\r\n let pid = null;\r\n while (Date.now() < deadline) {\r\n const errorPath = `${pidFile}.error`;\r\n if (existsSync(errorPath)) throw new Error(readFileSync(errorPath, \"utf8\").trim());\r\n pid = readPid(pidFile);\r\n if (pid && isAlive(pid) && await isHealthy(options.healthUrl)) {\r\n return { status: \"started\", pid, health: options.healthUrl ?? null, stdout, stderr };\r\n }\r\n await delay(200);\r\n }\r\n throw new Error(`后台服务未在 ${timeoutMs}ms 内就绪;stdout=${stdout} stderr=${stderr}`);\r\n}\r\n","#!/usr/bin/env node\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { migrationDirectory, migrationWorkspaceRoot } from \"../migration-paths.ts\";\r\nimport { REPORT_VERSION, SOURCE_PROVENANCE_LEVEL, auditLiteralDrift, auditSourceClosure, auditSourceOrder, managedHarmonyFile, managedSourceManifest, validateSourceProvenance, writeLiteralDriftAudit, writeManagedSourceManifest, writeSourceOrderAudit } from \"./source-governance.ts\";\r\n\r\nexport function validateMigrationReport(argv: string[], options: { writeResult?: boolean; trustedSourceEvents?: boolean } = {}) {\r\nconst projectRoot = path.resolve(argv[0] ?? \".\");\r\nconst requireComplete = argv.includes(\"--require-complete\");\r\nconst migrationRoot = migrationDirectory(projectRoot);\r\nconst workspaceRoot = migrationWorkspaceRoot(projectRoot);\r\nconst specRoot = path.join(migrationRoot, \"spec\");\r\nconst reportRoot = path.join(migrationRoot, \"report\");\r\nconst errors = [];\r\nconst completionErrors = [];\r\nconst read = (file) => JSON.parse(fs.readFileSync(file, \"utf8\"));\r\nconst exists = (file, label) => { if (!fs.existsSync(file)) { errors.push(`${label} not found: ${file}`); return false; } return true; };\r\nconst specIndexPath = path.join(specRoot, \"index.json\");\r\nconst reportIndexPath = path.join(reportRoot, \"index.json\");\r\nconst unexpectedKeys = (value, allowed, label) => {\r\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return;\r\n for (const key of Object.keys(value)) if (!allowed.has(key)) errors.push(`${label}: unexpected field ${key}`);\r\n};\r\nconst reportFile = (relative, label) => {\r\n if (typeof relative !== \"string\" || !relative.trim() || path.isAbsolute(relative)) { errors.push(`${label}: path must be report-relative`); return null; }\r\n const absolute = path.resolve(reportRoot, relative);\r\n const relation = path.relative(reportRoot, absolute);\r\n if (!relation || relation === \"..\" || relation.startsWith(`..${path.sep}`) || path.isAbsolute(relation)) { errors.push(`${label}: path escapes the report root`); return null; }\r\n if (!exists(absolute, label)) return null;\r\n const realRoot = fs.realpathSync(reportRoot);\r\n const realFile = fs.realpathSync(absolute);\r\n const realRelation = path.relative(realRoot, realFile);\r\n if (realRelation === \"..\" || realRelation.startsWith(`..${path.sep}`) || path.isAbsolute(realRelation)) { errors.push(`${label}: path resolves outside the report root`); return null; }\r\n if (!fs.statSync(realFile).isFile()) { errors.push(`${label}: path is not a file`); return null; }\r\n return realFile;\r\n};\r\n\r\nif (!exists(specIndexPath, \"SPEC index\") || !exists(reportIndexPath, \"report index\")) {\r\n return { reportValidationVersion: REPORT_VERSION, valid: false, complete: false, errors, completionErrors: [], exitCode: 1 };\r\n}\r\nconst specIndex = read(specIndexPath);\r\nconst reportIndex = read(reportIndexPath);\r\nif (reportIndex.reportVersion !== REPORT_VERSION) errors.push(`reportVersion must be ${REPORT_VERSION}; found ${reportIndex.reportVersion ?? \"<unknown>\"}`);\r\nif (reportIndex.baseline?.factsSha256 !== specIndex.factsSha256) errors.push(\"report baseline factsSha256 does not match current deterministic facts\");\r\nif (reportIndex.baseline?.specIndex !== \".migration/spec/index.json\") errors.push(\"report baseline specIndex must point to .migration/spec/index.json\");\r\n\r\nconst factsFiles = specIndex.files?.facts;\r\nif (!factsFiles) errors.push(\"SPEC index does not expose deterministic facts\");\r\nconst pageFactsIndex = factsFiles && exists(path.join(specRoot, factsFiles.pages), \"page facts index\") ? read(path.join(specRoot, factsFiles.pages)) : { pages: [] };\r\nconst expectedPages = new Map();\r\nconst expectedControls = new Set();\r\nconst expectedEntries = new Set();\r\nfor (const descriptor of pageFactsIndex.pages ?? []) {\r\n const file = path.join(specRoot, descriptor.file);\r\n if (!exists(file, \"page facts shard\")) continue;\r\n const shard = read(file);\r\n const ref = shard.surface?.surfaceRef;\r\n if (!ref) { errors.push(`page facts shard has no surfaceRef: ${descriptor.file}`); continue; }\r\n expectedPages.set(ref, { descriptor, shard });\r\n for (const value of shard.controls ?? []) expectedControls.add(value.controlRef);\r\n for (const value of shard.entries ?? []) expectedEntries.add(value.entryRef);\r\n}\r\nif (pageFactsIndex.unassignedEntriesFile) {\r\n const file = path.join(specRoot, pageFactsIndex.unassignedEntriesFile);\r\n if (exists(file, \"unassigned entry facts\")) for (const value of read(file).entries ?? []) expectedEntries.add(value.entryRef);\r\n}\r\nconst interactionFacts = factsFiles && exists(path.join(specRoot, factsFiles.interactions), \"interaction facts\") ? read(path.join(specRoot, factsFiles.interactions)).interactions ?? [] : [];\r\nconst expectedInteractions = new Set(interactionFacts.map((value) => value.id));\r\nconst actualPages = new Set();\r\nconst actualControls = new Set();\r\nconst actualEntries = new Set();\r\nconst actualInteractions = new Set();\r\nconst actualDiscoveries = new Set();\r\nconst allItems = [];\r\n\r\nfunction addItem(value, expectedKind, target, location) {\r\n if (!value || typeof value !== \"object\") { errors.push(`${location}: invalid report item`); return; }\r\n if (!value.ref) errors.push(`${location}: ref is required`);\r\n if (value.kind !== expectedKind) errors.push(`${location}: expected kind ${expectedKind}, found ${value.kind}`);\r\n if (target.has(value.ref)) errors.push(`${location}: duplicate ref ${value.ref}`); else target.add(value.ref);\r\n if (!new Set([\"pending\", \"implemented\", \"verified\", \"blocked\"]).has(value.status)) errors.push(`${location}: invalid status ${value.status}`);\r\n if (typeof value.factLabel !== \"string\" || !value.factLabel) errors.push(`${location}: factLabel is required`);\r\n for (const field of [\"harmonyosFiles\", \"sourceProvenance\", \"testEvidence\"]) if (!Array.isArray(value[field])) errors.push(`${location}: ${field} must be an array`);\r\n if (!(\"difference\" in value)) errors.push(`${location}: difference field is required`);\r\n allItems.push(value);\r\n}\r\n\r\nfor (const descriptor of reportIndex.pages ?? []) {\r\n const file = reportFile(descriptor.file, \"page report shard\");\r\n if (!file) continue;\r\n const shard = read(file);\r\n const expected = expectedPages.get(descriptor.surfaceRef);\r\n if (!expected) errors.push(`report page ${descriptor.surfaceRef} is not present in deterministic facts`);\r\n if (expected) {\r\n const expectedFactsFile = path.relative(workspaceRoot, path.join(specRoot, expected.descriptor.file)).replaceAll(\"\\\\\", \"/\");\r\n if (shard.factsFile !== expectedFactsFile) errors.push(`page ${descriptor.surfaceRef}: factsFile does not match deterministic shard`);\r\n }\r\n addItem(shard.page, \"page\", actualPages, descriptor.file);\r\n for (const value of shard.controls ?? []) addItem(value, \"control\", actualControls, descriptor.file);\r\n for (const value of shard.entries ?? []) addItem(value, \"entry\", actualEntries, descriptor.file);\r\n}\r\nif (reportIndex.unassignedEntriesFile) {\r\n const file = reportFile(reportIndex.unassignedEntriesFile, \"unassigned entry report\");\r\n if (file) for (const value of read(file).entries ?? []) addItem(value, \"entry\", actualEntries, reportIndex.unassignedEntriesFile);\r\n}\r\nif (reportIndex.interactionsFile) {\r\n const file = reportFile(reportIndex.interactionsFile, \"interaction report\");\r\n if (file) for (const value of read(file).interactions ?? []) addItem(value, \"interaction\", actualInteractions, reportIndex.interactionsFile);\r\n} else errors.push(\"report index has no interactionsFile\");\r\nif (reportIndex.discoveriesFile) {\r\n const file = reportFile(reportIndex.discoveriesFile, \"discoveries report\");\r\n if (file) for (const value of read(file).items ?? []) addItem(value, \"feature\", actualDiscoveries, reportIndex.discoveriesFile);\r\n} else errors.push(\"report index has no discoveriesFile\");\r\n\r\nfunction compare(expected, actual, label) {\r\n for (const ref of expected) if (!actual.has(ref)) errors.push(`${label} missing report ref ${ref}`);\r\n for (const ref of actual) if (!expected.has(ref)) errors.push(`${label} contains unknown report ref ${ref}`);\r\n}\r\ncompare(new Set(expectedPages.keys()), actualPages, \"pages\"); compare(expectedControls, actualControls, \"controls\"); compare(expectedEntries, actualEntries, \"entries\"); compare(expectedInteractions, actualInteractions, \"interactions\");\r\n\r\nfor (const value of allItems.filter((item) => item.kind === \"entry\")) {\r\n if (!(\"controlRef\" in value)) errors.push(`entry ${value.ref}: controlRef field is required (use null for non-UI entries)`);\r\n else if (value.controlRef !== null && !actualControls.has(value.controlRef)) errors.push(`entry ${value.ref}: unknown controlRef ${value.controlRef}`);\r\n}\r\n\r\nfor (const value of allItems) {\r\n if (value.status === \"pending\") completionErrors.push(`${value.kind} ${value.ref} is pending`);\r\n if (value.status === \"implemented\") completionErrors.push(`${value.kind} ${value.ref} is implemented but not verified`);\r\n if (value.status === \"blocked\") completionErrors.push(`${value.kind} ${value.ref} is blocked`);\r\n if ([\"implemented\", \"verified\"].includes(value.status) && !(value.harmonyosFiles ?? []).length) errors.push(`${value.kind} ${value.ref}: ${value.status} requires a HarmonyOS file`);\r\n const provenanceErrors = validateSourceProvenance(projectRoot, value.sourceProvenance, `${value.kind} ${value.ref}`);\r\n if ([\"implemented\", \"verified\"].includes(value.status) && !(value.sourceProvenance ?? []).length) errors.push(`${value.kind} ${value.ref}: ${value.status} requires sourceProvenance`);\r\n errors.push(...provenanceErrors);\r\n for (const file of value.harmonyosFiles ?? []) {\r\n try { managedHarmonyFile(projectRoot, file); }\r\n catch (error) { errors.push(`${value.kind} ${value.ref}: ${error instanceof Error ? error.message : String(error)}`); }\r\n }\r\n if (value.status === \"verified\") {\r\n if (!(value.testEvidence ?? []).length) errors.push(`${value.kind} ${value.ref}: verified item requires test evidence`);\r\n }\r\n if (value.status === \"blocked\" && !value.difference) errors.push(`${value.kind} ${value.ref}: blocked item requires a difference or blocker reason`);\r\n}\r\n\r\nconst unresolvedPath = reportIndex.unresolvedFile && reportFile(reportIndex.unresolvedFile, \"unresolved report\");\r\nif (unresolvedPath) for (const review of read(unresolvedPath).reviews ?? []) if (review.decision === \"pending\") completionErrors.push(`unresolved ${review.unresolvedRef} is pending`);\r\nconst summaryPath = reportIndex.summaryFile && reportFile(reportIndex.summaryFile, \"user summary\");\r\nif (summaryPath) {\r\n const summary = read(summaryPath);\r\n unexpectedKeys(summary, new Set([\"summary\", \"incomplete\", \"nextSteps\", \"additionalSections\"]), \"user summary\");\r\n if (typeof summary.summary !== \"string\") errors.push(\"user summary: summary must be a string\");\r\n for (const field of [\"incomplete\", \"nextSteps\"]) if (!Array.isArray(summary[field]) || summary[field].some((value) => typeof value !== \"string\" || !value.trim())) errors.push(`user summary: ${field} must be an array of non-empty strings`);\r\n if (summary.additionalSections !== undefined && (!Array.isArray(summary.additionalSections) || summary.additionalSections.some((section) => !section?.title || !section?.content))) errors.push(\"user summary: additionalSections must contain a title and content\");\r\n for (const [index, section] of (summary.additionalSections ?? []).entries()) unexpectedKeys(section, new Set([\"title\", \"content\"]), `user summary section ${index + 1}`);\r\n if (!summary.summary.trim()) completionErrors.push(\"user-facing migration summary is empty\");\r\n} else {\r\n errors.push(\"report index has no summaryFile\");\r\n completionErrors.push(\"user-facing migration summary is missing\");\r\n}\r\nconst acceptancePath = reportIndex.finalAcceptanceFile && reportFile(reportIndex.finalAcceptanceFile, \"final acceptance\");\r\nif (acceptancePath) {\r\n const acceptance = read(acceptancePath);\r\n unexpectedKeys(acceptance, new Set([\"reportShardVersion\", \"kind\", \"status\", \"tests\", \"blockers\", \"notes\"]), \"final acceptance\");\r\n if (!new Set([\"1.1.0\", \"1.2.0\"]).has(acceptance.reportShardVersion) || acceptance.kind !== \"final-acceptance\") errors.push(\"final acceptance must use the lightweight 1.1.0 or 1.2.0 contract\");\r\n if (!new Set([\"pending\", \"passed\", \"failed\"]).has(acceptance.status)) errors.push(`final acceptance has invalid status ${acceptance.status}`);\r\n if (!Array.isArray(acceptance.tests) || !Array.isArray(acceptance.blockers) || !Array.isArray(acceptance.notes)) errors.push(\"final acceptance tests, blockers and notes must be arrays\");\r\n const acceptanceRefs = new Set<string>();\r\n for (const [index, test] of (acceptance.tests ?? []).entries()) {\r\n unexpectedKeys(test, new Set([\"ref\", \"name\", \"status\", \"evidence\"]), `final acceptance test ${index + 1}`);\r\n if (acceptance.reportShardVersion === \"1.2.0\" && (typeof test?.ref !== \"string\" || !test.ref.trim())) errors.push(`final acceptance test ${index + 1}: ref is required by 1.2.0`);\r\n if (typeof test?.ref === \"string\" && test.ref.trim()) {\r\n if (acceptanceRefs.has(test.ref)) errors.push(`final acceptance test ${index + 1}: duplicate ref ${test.ref}`);\r\n acceptanceRefs.add(test.ref);\r\n }\r\n if (!test?.name || !new Set([\"passed\", \"failed\"]).has(test.status) || !Array.isArray(test.evidence)) errors.push(`final acceptance test ${index + 1} is invalid`);\r\n if (test?.status === \"passed\" && !(test.evidence ?? []).length) errors.push(`final acceptance test ${test?.name ?? index + 1}: passed requires evidence`);\r\n }\r\n for (const field of [\"blockers\", \"notes\"]) if ((acceptance[field] ?? []).some((value) => typeof value !== \"string\" || !value.trim())) errors.push(`final acceptance ${field} must contain only non-empty strings`);\r\n if (acceptance.status === \"passed\" && !(acceptance.tests ?? []).length) errors.push(\"passed final acceptance requires at least one end-to-end test\");\r\n if (acceptance.status === \"passed\" && (acceptance.tests ?? []).some((test) => test.status !== \"passed\")) errors.push(\"passed final acceptance contains a failed test\");\r\n if (acceptance.status === \"passed\" && (acceptance.blockers ?? []).length) errors.push(\"passed final acceptance cannot contain blockers\");\r\n if (acceptance.status !== \"passed\") completionErrors.push(\"final acceptance is not passed\");\r\n} else completionErrors.push(\"final acceptance is missing\");\r\n\r\nlet sourceManifest = null;\r\ntry { sourceManifest = managedSourceManifest(projectRoot); }\r\ncatch (error) { errors.push(`managed Android source manifest failed: ${error instanceof Error ? error.message : String(error)}`); }\r\nconst orderAudit = auditSourceOrder(projectRoot, allItems, { trusted: options.trustedSourceEvents === true });\r\nif (orderAudit.status === \"red-flag\") errors.push(`source order audit red-flag: ${orderAudit.findings.join(\"; \")}`);\r\nconst closureAudit = auditSourceClosure(projectRoot, allItems);\r\nif (closureAudit.status === \"red-flag\") errors.push(`source closure audit red-flag: ${closureAudit.findings.join(\"; \")}`);\r\nconst literalAudit = auditLiteralDrift(projectRoot, allItems, specIndex?.factsSha256 ?? \"\");\r\nconst warnings = [...(orderAudit.status === \"unavailable\" ? orderAudit.findings : []), ...(closureAudit.status === \"unavailable\" ? closureAudit.findings : []), ...literalAudit.warnings];\r\nconst valid = errors.length === 0;\r\nconst complete = valid && completionErrors.length === 0;\r\nconst sourceClaims = allItems.filter((item) => [\"implemented\", \"verified\"].includes(item?.status)).map((item) => ({ ref: item.ref, kind: item.kind, status: item.status, harmonyosFiles: item.harmonyosFiles, sourceProvenance: item.sourceProvenance }));\r\nconst result = { reportValidationVersion: REPORT_VERSION, valid, complete, factsSha256: specIndex?.factsSha256 ?? null, evidenceLevel: orderAudit.status === \"passed\" ? \"observed-order-audited\" : SOURCE_PROVENANCE_LEVEL, sourceManifest: sourceManifest ? { path: \".migration/audit/android-source-manifest.json\", manifestSha256: sourceManifest.manifestSha256, memberCount: sourceManifest.members.length } : null, sourceClaims, orderAudit, closureAudit, literalAudit, warnings, counts: { pages: actualPages?.size ?? 0, controls: actualControls?.size ?? 0, entries: actualEntries?.size ?? 0, interactions: actualInteractions?.size ?? 0 }, errors, completionErrors };\r\nif (options.writeResult !== false && fs.existsSync(reportRoot)) {\r\n fs.writeFileSync(path.join(reportRoot, \"validation.json\"), `${JSON.stringify(result, null, 2)}\\n`, \"utf8\");\r\n writeSourceOrderAudit(projectRoot, orderAudit);\r\n if (sourceManifest) writeManagedSourceManifest(projectRoot, sourceManifest);\r\n writeLiteralDriftAudit(projectRoot, literalAudit);\r\n}\r\nreturn { ...result, exitCode: valid && (!requireComplete || complete) ? 0 : 1 };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { defaultHarmonyProjectPath, harmonyAppNameForAndroidProject } from \"./android-project-name.ts\";\r\nimport { alignSdkVersionToLocal, detectLocalApiLevel, sdkVersionForApiLevel } from \"./sdk-version.ts\";\r\n\r\nexport interface InitHmosProjectOptions {\r\n androidProject: string;\r\n target?: string;\r\n templateRoot: string;\r\n}\r\n\r\nexport { alignSdkVersionToLocal, detectLocalApiLevel, sdkVersionForApiLevel };\r\n\r\nexport const OHOS_TEST_REQUIRED_FILES = [\r\n \"entry/src/ohosTest/module.json5\",\r\n \"entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ets\",\r\n \"entry/src/ohosTest/ets/testability/TestAbility.ets\",\r\n \"entry/src/ohosTest/resources/base/profile/test_pages.json\",\r\n];\r\n\r\n/** devecocli create 模板不含 ohosTest;从内置模板注入完整脚手架(幂等,已有 module.json5 则跳过)。 */\r\nexport function ensureOhosTestScaffold(options: { harmonyProject: string; templatesRoot: string }) {\r\n const source = path.join(options.templatesRoot, \"ohos\", \"entry\", \"src\", \"ohosTest\");\r\n const target = path.join(options.harmonyProject, \"entry\", \"src\", \"ohosTest\");\r\n if (!fs.existsSync(source)) throw new Error(`Bundled ohosTest template does not exist: ${source}`);\r\n if (fs.existsSync(path.join(target, \"module.json5\"))) {\r\n return { injected: false as const, target, reason: \"existing ohosTest module\" };\r\n }\r\n fs.cpSync(source, target, { recursive: true });\r\n const prefix = \"entry/src/ohosTest/\";\r\n const missing = OHOS_TEST_REQUIRED_FILES.map((relativePath) => relativePath.slice(prefix.length))\r\n .filter((relativePath) => !fs.existsSync(path.join(target, relativePath)));\r\n if (missing.length > 0) throw new Error(`ohosTest scaffold injection is incomplete: ${missing.join(\", \")}`);\r\n return { injected: true as const, target };\r\n}\r\n\r\nexport function initHmosProject(options: InitHmosProjectOptions) {\r\n const projectRoot = path.resolve(options.androidProject);\r\n const templateRoot = path.resolve(options.templateRoot);\r\n const appName = harmonyAppNameForAndroidProject(projectRoot);\r\n const targetRoot = path.resolve(options.target ?? defaultHarmonyProjectPath(projectRoot));\r\n const excludedDirectories = new Set([\".git\", \".hvigor\", \".idea\", \"oh_modules\", \"build\"]);\r\n const excludedFiles = new Set([\"local.properties\", \".DS_Store\"]);\r\n\r\n if (!fs.existsSync(projectRoot) || !fs.statSync(projectRoot).isDirectory()) throw new Error(`Android project directory does not exist: ${projectRoot}`);\r\n if (!fs.existsSync(templateRoot)) throw new Error(`HarmonyOS template does not exist: ${templateRoot}`);\r\n if (fs.existsSync(targetRoot) && fs.readdirSync(targetRoot).length > 0) throw new Error(`Target HarmonyOS directory is not empty: ${targetRoot}`);\r\n\r\n fs.mkdirSync(targetRoot, { recursive: true });\r\n fs.cpSync(templateRoot, targetRoot, {\r\n recursive: true,\r\n errorOnExist: true,\r\n filter(source) {\r\n if (path.resolve(source) === templateRoot) return true;\r\n const name = path.basename(source);\r\n return !excludedDirectories.has(name) && !excludedFiles.has(name);\r\n },\r\n });\r\n\r\n const requiredFiles = [\r\n \"build-profile.json5\", \"oh-package.json5\", \"hvigorfile.ts\", \"entry/build-profile.json5\",\r\n \"entry/src/main/module.json5\", \"entry/src/main/ets/entryability/EntryAbility.ets\",\r\n \"entry/src/main/ets/pages/Index.ets\", \"entry/src/main/resources/base/profile/main_pages.json\",\r\n ...OHOS_TEST_REQUIRED_FILES,\r\n ];\r\n const missing = requiredFiles.filter((relativePath) => !fs.existsSync(path.join(targetRoot, relativePath)));\r\n if (missing.length > 0) throw new Error(`Template copy is incomplete: ${missing.join(\", \")}`);\r\n\r\n const appNameResource = path.join(targetRoot, \"AppScope\", \"resources\", \"base\", \"element\", \"string.json\");\r\n const strings = JSON.parse(fs.readFileSync(appNameResource, \"utf8\"));\r\n const appNameItem = strings.string?.find((item) => item.name === \"app_name\");\r\n if (!appNameItem) throw new Error(`HarmonyOS app_name resource not found: ${appNameResource}`);\r\n appNameItem.value = appName;\r\n fs.writeFileSync(appNameResource, `${JSON.stringify(strings, null, 2)}\\n`, \"utf8\");\r\n\r\n fs.writeFileSync(path.join(targetRoot, \".droid2hmos-managed.json\"), `${JSON.stringify({ owner: \"droid2hmos-init\", version: \"1.0.0\", appName }, null, 2)}\\n`, \"utf8\");\r\n // 与 devecocli 内部流程一致:targetSdkVersion 按本机 DevEco 支持的 API 级别对齐,\r\n // compatibleSdkVersion 固定默认 5.0.0(12),保证任何 API ≥ 12 的手机可安装。\r\n const sdkAlignment = alignSdkVersionToLocal(targetRoot);\r\n return { ok: true, appName, source: templateRoot, target: targetRoot, excluded: [...excludedDirectories, ...excludedFiles], requiredFiles, sdkAlignment };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\n\r\nexport function detectAndroidAppName(project: string) {\r\n const projectRoot = path.resolve(project);\r\n for (const fileName of [\"settings.gradle.kts\", \"settings.gradle\"]) {\r\n const file = path.join(projectRoot, fileName);\r\n if (!fs.existsSync(file)) continue;\r\n const match = fs.readFileSync(file, \"utf8\").match(/\\brootProject\\.name\\s*=\\s*[\"']([^\"']+)[\"']/);\r\n if (match?.[1]?.trim()) return match[1].trim();\r\n }\r\n return path.basename(projectRoot);\r\n}\r\n\r\nexport function harmonyAppNameForAndroidProject(project: string) {\r\n const safeName = detectAndroidAppName(project)\r\n .replace(/[<>:\"/\\\\|?*\\u0000-\\u001f]/g, \"_\")\r\n .trim();\r\n return `${safeName || \"AndroidApp\"}Ohos`;\r\n}\r\n\r\nexport function defaultHarmonyProjectPath(project: string) {\r\n const projectRoot = path.resolve(project);\r\n return path.join(path.dirname(projectRoot), harmonyAppNameForAndroidProject(projectRoot));\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\n\r\n/** 模板默认 SDK 版本(与 devecocli 内置模板一致)。 */\r\nexport const TEMPLATE_SDK_VERSION = \"6.0.2(22)\";\r\n/** 工程固定兼容版本(官方默认 5.0.0(12)):不跟随本机/真机版本,\r\n * 保证产物在任何 API ≥ 12 的鸿蒙手机上可安装。 */\r\nexport const DEFAULT_COMPATIBLE_SDK_VERSION = \"5.0.0(12)\";\r\n/** 模板默认 hvigor/oh-package modelVersion。 */\r\nexport const TEMPLATE_MODEL_VERSION = \"6.0.2\";\r\n/** 探测不到本机 DevEco 时的兜底 API 级别(与 devecocli 行为一致)。 */\r\nexport const DEFAULT_API_LEVEL = 23;\r\n\r\n/** API 级别 → 版本段映射表(旧级别回退用;本机已安装的级别优先读 sdk-pkg.json 动态生成)。\r\n * 12–15 的配对来自官方 build-profile 文档(hvigor 校验 platform 与 API 括号必须匹配,\r\n * 错误配对如 \"5.0.5(13)\" 会直接构建失败)。 */\r\nconst API_LEVEL_TABLE: Record<number, string> = {\r\n 12: \"5.0.0\",\r\n 13: \"5.0.1\",\r\n 14: \"5.0.2\",\r\n 15: \"5.0.3\",\r\n 17: \"5.0.5\",\r\n 18: \"5.1.0\",\r\n 19: \"5.1.1\",\r\n 20: \"6.0.0\",\r\n 21: \"6.0.1\",\r\n 22: \"6.0.2\",\r\n 23: \"6.1.0\",\r\n 24: \"6.1.1\",\r\n};\r\n\r\n/** ABC(ArkTS 字节码)文件魔数 \"PAND\"。 */\r\nconst ABC_MAGIC = [0x50, 0x41, 0x4e, 0x44];\r\n\r\n/**\r\n * 解析 ABC 文件头(前 16 字节)中的字节码版本,如 \"13.0.1.0\"、\"24.0.0.0\"。\r\n * 布局:bytes[0..4)=魔数,bytes[12..16)=版本(major.minor.patch.hotfix)。\r\n * 魔数不符、长度不足或版本全零返回 null。\r\n */\r\nexport function parseAbcHeaderVersion(header: Uint8Array): string | null {\r\n if (header.length < 16) return null;\r\n if (ABC_MAGIC.some((byte, index) => header[index] !== byte)) return null;\r\n if (header[12] === 0 && header[13] === 0 && header[14] === 0 && header[15] === 0) return null;\r\n return `${header[12]}.${header[13]}.${header[14]}.${header[15]}`;\r\n}\r\n\r\n/** API 级别 → 完整 SDK 版本号(如 20 → \"6.0.0(20)\");API ≥ 26 与 devecocli 一致使用\r\n * 裸版本号 \"26.0.0\"(hvigor 对该区间拒绝 \"(26)\" 后缀形式);无映射且 <26 时返回 null(不改写)。 */\r\nexport function sdkVersionForApiLevel(level: number): string | null {\r\n if (level >= 26) return `${level}.0.0`;\r\n const base = API_LEVEL_TABLE[level] ?? null;\r\n return base ? `${base}(${level})` : null;\r\n}\r\n\r\nfunction devecoHomes(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Array<string | undefined> {\r\n const homes: Array<string | undefined> = [env.DEVECO_STUDIO_HOME, env.DEVECO_HOME];\r\n if (platform === \"win32\") {\r\n for (const drive of [\"C:\", \"D:\"]) homes.push(path.join(`${drive}\\\\`, \"Program Files\", \"Huawei\", \"DevEco Studio\"));\r\n } else if (platform === \"darwin\") {\r\n homes.push(\"/Applications/DevEco-Studio.app/Contents\", path.join(env.HOME ?? \"\", \"Applications\", \"DevEco-Studio.app\", \"Contents\"));\r\n }\r\n return homes;\r\n}\r\n\r\n/**\r\n * 动态读取本机 DevEco 自带 SDK 的完整版本信息(apiLevel + sdkVersion)。\r\n * 每次调用都重新读取 `sdk/default/sdk-pkg.json`,因此能适配未来任何\r\n * 新的鸿蒙版本(如 7.0.5(30)),无需依赖代码中的静态映射表。\r\n */\r\nexport function detectLocalSdkVersion(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): { apiLevel: number; sdkVersion: string } | null {\r\n for (const home of devecoHomes(env, platform)) {\r\n if (!home) continue;\r\n const pkg = path.join(home, \"sdk\", \"default\", \"sdk-pkg.json\");\r\n try {\r\n const data = JSON.parse(fs.readFileSync(pkg, \"utf8\"))?.data;\r\n const apiVersion = Number(data?.apiVersion);\r\n const platformVersion = String(data?.platformVersion ?? \"\").trim();\r\n if (Number.isInteger(apiVersion) && apiVersion > 0 && /^\\d+\\.\\d+\\.\\d+$/.test(platformVersion)) {\r\n // API ≥ 26 与 devecocli 内部规则一致:裸 \"{api}.0.0\",不带 \"(api)\" 后缀。\r\n const sdkVersion = apiVersion >= 26 ? `${apiVersion}.0.0` : `${platformVersion}(${apiVersion})`;\r\n return { apiLevel: apiVersion, sdkVersion };\r\n }\r\n } catch {\r\n // 尝试下一个安装位置\r\n }\r\n }\r\n return null;\r\n}\r\n\r\n/**\r\n * 探测本机 DevEco Studio 支持的 API 级别。\r\n * 读取 `<DevEco>/sdk/default/sdk-pkg.json` 的 apiVersion;找不到返回 null。\r\n */\r\nexport function detectLocalApiLevel(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): number | null {\r\n return detectLocalSdkVersion(env, platform)?.apiLevel ?? null;\r\n}\r\n\r\n/**\r\n * 将鸿蒙工程 SDK 版本对齐本机 DevEco 支持的 API 级别(与 devecocli 内部流程一致):\r\n * 版本号优先由本机 `sdk-pkg.json` 动态生成(适配最新鸿蒙版本),静态映射表仅用于\r\n * 显式指定的、本机未安装的历史级别;探测不到兜底 23。仅改写 targetSdkVersion,\r\n * compatibleSdkVersion 固定为默认 5.0.0(12)(不跟随本机/真机版本,保证任何\r\n * API ≥ 12 的手机可安装),并同步 hvigor-config 与 oh-package 的 modelVersion。\r\n * 无映射(如 25)或已是目标值时不产生变更。\r\n * 采用正则替换原文本,保留 JSON5 注释与格式,幂等。\r\n */\r\nexport function alignSdkVersionToLocal(harmonyProject: string, { apiLevel }: { apiLevel?: number } = {}) {\r\n const root = path.resolve(harmonyProject);\r\n const explicit = Number.isInteger(apiLevel) && (apiLevel as number) > 0 ? (apiLevel as number) : null;\r\n // 每次建库时重新读取本机 SDK 元数据,动态生成本机级别的版本号。\r\n const local = detectLocalSdkVersion();\r\n const level = explicit ?? local?.apiLevel ?? DEFAULT_API_LEVEL;\r\n const sdkVersion = (local && level === local.apiLevel ? local.sdkVersion : null) ?? sdkVersionForApiLevel(level);\r\n if (!sdkVersion) {\r\n return {\r\n status: \"passed\" as const,\r\n apiLevel: level,\r\n sdkVersion: TEMPLATE_SDK_VERSION,\r\n compatibleSdkVersion: DEFAULT_COMPATIBLE_SDK_VERSION,\r\n changed: [],\r\n summary: `API 级别 ${level} 无对应 SDK 版本映射,保留模板默认 ${TEMPLATE_SDK_VERSION}`,\r\n evidence: [],\r\n };\r\n }\r\n const modelVersion = sdkVersion.replace(/\\(\\d+\\)$/, \"\");\r\n const replacements: Array<{ file: string; pattern: RegExp; replacement: string }> = [\r\n { file: path.join(root, \"build-profile.json5\"), pattern: /(['\\\"]?targetSdkVersion['\\\"]?\\s*:\\s*)['\\\"][^'\"]*['\"]/g, replacement: `$1\"${sdkVersion}\"` },\r\n { file: path.join(root, \"build-profile.json5\"), pattern: /(['\\\"]?compatibleSdkVersion['\\\"]?\\s*:\\s*)['\\\"][^'\"]*['\"]/g, replacement: `$1\"${DEFAULT_COMPATIBLE_SDK_VERSION}\"` },\r\n { file: path.join(root, \"hvigor\", \"hvigor-config.json5\"), pattern: /(['\\\"]?modelVersion['\\\"]?\\s*:\\s*)['\\\"][^'\"]*['\\\"]/, replacement: `$1\"${modelVersion}\"` },\r\n { file: path.join(root, \"oh-package.json5\"), pattern: /(['\\\"]?modelVersion['\\\"]?\\s*:\\s*)['\\\"][^'\"]*['\\\"]/, replacement: `$1\"${modelVersion}\"` },\r\n ];\r\n const changed: string[] = [];\r\n for (const { file, pattern, replacement } of replacements) {\r\n if (!fs.existsSync(file)) continue;\r\n const before = fs.readFileSync(file, \"utf8\");\r\n const after = before.replace(pattern, replacement);\r\n if (after !== before) {\r\n fs.writeFileSync(file, after, \"utf8\");\r\n if (!changed.includes(path.relative(root, file).replaceAll(\"\\\\\", \"/\"))) {\r\n changed.push(path.relative(root, file).replaceAll(\"\\\\\", \"/\"));\r\n }\r\n }\r\n }\r\n return {\r\n status: \"passed\" as const,\r\n apiLevel: level,\r\n sdkVersion,\r\n compatibleSdkVersion: DEFAULT_COMPATIBLE_SDK_VERSION,\r\n modelVersion,\r\n changed,\r\n summary: `targetSdkVersion 已按本机 API 级别 ${level} 对齐为 ${sdkVersion},compatibleSdkVersion 固定为默认 ${DEFAULT_COMPATIBLE_SDK_VERSION}(modelVersion ${modelVersion})`,\r\n evidence: changed,\r\n };\r\n}\r\n\r\n/**\r\n * 将 compatibleSdkVersion 下调到真机可安装的版本:仅当真机 API 低于当前\r\n * compatibleSdkVersion 的 API 时改写(targetSdkVersion 保持本机最新不动,\r\n * modelVersion 跟随 target 也不动)。幂等,保留 JSON5 注释与格式。\r\n */\r\nexport function capCompatibleSdkVersionTo(harmonyProject: string, deviceSdkVersion: string) {\r\n const file = path.join(path.resolve(harmonyProject), \"build-profile.json5\");\r\n if (!fs.existsSync(file)) {\r\n return { status: \"skipped\" as const, changed: false, summary: \"build-profile.json5 不存在,跳过兼容版本检查\" };\r\n }\r\n const before = fs.readFileSync(file, \"utf8\");\r\n const compatibleValue = /['\\\"]?compatibleSdkVersion['\\\"]?\\s*:\\s*['\"]([^'\"]+)['\"]/.exec(before)?.[1] ?? null;\r\n const currentApi = compatibleValue !== null ? Number(/\\((\\d+)\\)/.exec(compatibleValue)?.[1] ?? NaN) : NaN;\r\n const deviceApi = Number(/\\((\\d+)\\)/.exec(deviceSdkVersion)?.[1] ?? NaN);\r\n if (!Number.isInteger(currentApi) || !Number.isInteger(deviceApi)) {\r\n return { status: \"skipped\" as const, changed: false, summary: \"无法解析 compatibleSdkVersion 或真机版本,跳过兼容版本检查\" };\r\n }\r\n if (deviceApi >= currentApi) {\r\n return { status: \"passed\" as const, changed: false, compatibleApi: currentApi, deviceApi, summary: `真机 API ${deviceApi} ≥ 兼容版本 API ${currentApi},无需下调 compatibleSdkVersion` };\r\n }\r\n const after = before.replace(/(['\\\"]?compatibleSdkVersion['\\\"]?\\s*:\\s*)['\"][^'\"]*['\"]/, `$1\"${deviceSdkVersion}\"`);\r\n fs.writeFileSync(file, after, \"utf8\");\r\n return {\r\n status: \"passed\" as const,\r\n changed: true,\r\n compatibleSdkVersion: deviceSdkVersion,\r\n previousCompatibleApi: currentApi,\r\n deviceApi,\r\n summary: `compatibleSdkVersion 已按真机 API ${deviceApi} 下调为 ${deviceSdkVersion}(targetSdkVersion 保持不变),保证真机可安装`,\r\n evidence: [deviceSdkVersion],\r\n };\r\n}\r\n","import { rmSync } from \"node:fs\";\r\nimport { join, resolve } from \"node:path\";\r\nimport { renderSpecHtml } from \"./render-spec-html.ts\";\r\nimport { migrationDirectory, ensureMigrationWorkspace } from \"../migration-paths.ts\";\r\nimport { spawnCommandSync } from \"./lib/spawn-command.ts\";\r\n\r\nexport function runAppGraph(argv: string[], runCommand: typeof spawnCommandSync = spawnCommandSync) {\r\n if (argv.some((arg) => arg === \"--resolve-dependencies\" || arg.startsWith(\"--resolve-dependencies=\"))) {\r\n throw new Error(\"Android Gradle 依赖分析入口暂时关闭,请移除 --resolve-dependencies 后执行源码静态分析。\");\r\n }\r\n const runManaged = (args: string[]) => {\r\n const result = runCommand(\"appgraph\", args, { stdio: \"inherit\" });\r\n if (result.error) {\r\n throw new Error(`无法执行 appgraph 命令:${result.error.message}。请先安装 AppGraph 并确保 appgraph 在 PATH 中。`);\r\n }\r\n return result;\r\n };\r\n\r\n if (argv[0] !== \"spec\") {\r\n const result = runManaged(argv);\r\n return result.status ?? 1;\r\n }\r\n\r\n const projectPath = argv[1];\r\n if (!projectPath) throw new Error(\"spec 缺少 Android 工程路径\");\r\n const projectRoot = resolve(projectPath);\r\n ensureMigrationWorkspace(projectRoot);\r\n const outputPath = join(migrationDirectory(projectRoot), \"spec\");\r\n const command = [\"spec-analysis\", projectRoot, \"--out\", outputPath];\r\n const graphIndex = argv.indexOf(\"--graph\");\r\n if (graphIndex >= 0 && argv[graphIndex + 1]) command.push(\"--graph\", argv[graphIndex + 1]);\r\n const analysis = runManaged(command);\r\n if ((analysis.status ?? 1) !== 0) return analysis.status ?? 1;\r\n\r\n console.log(JSON.stringify(renderSpecHtml([join(outputPath, \"index.json\"), join(outputPath, \"spec.html\")]), null, 2));\r\n\r\n // 迁移前的位置(工程内部)——仅用于清理遗留产物。\r\n const legacyDirectory = join(projectRoot, \".migration\", \"appgraph\");\r\n for (const legacyName of [\"spec-graph.json\", \"spec-graph.html\", \"spec-graph-index.json\"]) {\r\n rmSync(join(legacyDirectory, legacyName), { force: true });\r\n }\r\n return 0;\r\n}\r\n","import { execFileSync } from \"node:child_process\";\r\nimport { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport JSON5 from \"json5\";\r\nimport { runFiniteCommand } from \"./run-config-command.ts\";\r\nimport { checkHarmonyDevice } from \"./check-hmos-device.ts\";\r\nimport { parseHypiumReport } from \"./hypium-report.ts\";\r\nimport { ensureDeviceSignature, selectPreferredTarget } from \"./device-signature.ts\";\r\n\r\nfunction readJson5(file: string): any {\r\n if (!existsSync(file)) throw new Error(`DevEco 配置不存在: ${file}`);\r\n return JSON5.parse(readFileSync(file, \"utf8\"));\r\n}\r\n\r\nfunction firstExisting(values: Array<string | undefined | null>) {\r\n return values.find((value): value is string => Boolean(value && existsSync(value)));\r\n}\r\n\r\nfunction pathLookup(command: string) {\r\n try {\r\n const lookup = process.platform === \"win32\" ? \"where.exe\" : \"which\";\r\n return execFileSync(lookup, [command], { encoding: \"utf8\", windowsHide: true })\r\n .split(/\\r?\\n/).map((value) => value.trim()).find(Boolean);\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nexport function findHvigor() {\r\n const executable = process.platform === \"win32\" ? \"hvigorw.bat\" : \"hvigorw\";\r\n const home = process.env.DEVECO_STUDIO_HOME || process.env.DEVECO_HOME;\r\n const candidates: Array<string | undefined | null> = [\r\n process.env.DROID2HMOS_HVIGOR,\r\n home && path.join(home, \"tools\", \"hvigor\", \"bin\", \"hvigorw.js\"),\r\n ];\r\n if (process.platform === \"win32\") {\r\n for (const drive of [\"C:\", \"D:\"]) candidates.push(path.join(`${drive}\\\\`, \"Program Files\", \"Huawei\", \"DevEco Studio\", \"tools\", \"hvigor\", \"bin\", \"hvigorw.js\"));\r\n } else if (process.platform === \"darwin\") {\r\n candidates.push(\"/Applications/DevEco-Studio.app/Contents/tools/hvigor/bin/hvigorw.js\");\r\n }\r\n candidates.push(pathLookup(executable));\r\n const found = firstExisting(candidates);\r\n if (!found) throw new Error(\"未找到 Hvigor。请将 hvigorw 加入 PATH,或设置 DROID2HMOS_HVIGOR/DEVECO_STUDIO_HOME\");\r\n return path.resolve(found);\r\n}\r\n\r\nexport function findOhpm() {\r\n const home = process.env.DEVECO_STUDIO_HOME || process.env.DEVECO_HOME;\r\n const candidates: Array<string | undefined | null> = [\r\n process.env.DROID2HMOS_OHPM,\r\n home && path.join(home, \"tools\", \"ohpm\", \"bin\", \"pm-cli.js\"),\r\n ];\r\n if (process.platform === \"win32\") {\r\n for (const drive of [\"C:\", \"D:\"]) candidates.push(path.join(`${drive}\\\\`, \"Program Files\", \"Huawei\", \"DevEco Studio\", \"tools\", \"ohpm\", \"bin\", \"pm-cli.js\"));\r\n } else if (process.platform === \"darwin\") {\r\n candidates.push(\"/Applications/DevEco-Studio.app/Contents/tools/ohpm/bin/pm-cli.js\");\r\n }\r\n candidates.push(pathLookup(\"ohpm\"));\r\n const found = firstExisting(candidates);\r\n if (!found) throw new Error(\"未找到 ohpm。请将 ohpm 加入 PATH,或设置 DROID2HMOS_OHPM/DEVECO_STUDIO_HOME\");\r\n return path.resolve(found);\r\n}\r\n\r\n/** hvigor 直接构建 ohosTest target 不会安装 ohpm 依赖(无 IDE/CLI 的 sync 前置步骤),\r\n * `@ohos/hypium` 未安装时 ArkTS 编译报 Failed to resolve OhmUrl。测试构建前按需补装。 */\r\nexport function ensureOhpmDependencies({ projectRoot, harmonyProject, timeoutMs }: {\r\n projectRoot: string;\r\n harmonyProject: string;\r\n timeoutMs?: number;\r\n}) {\r\n const root = path.resolve(harmonyProject);\r\n if (existsSync(path.join(root, \"oh_modules\", \"@ohos\", \"hypium\"))) {\r\n return { status: \"passed\" as const, key: \"harmonyTest-ohpm\", skipped: true, summary: \"oh_modules 已包含 @ohos/hypium,跳过安装\" };\r\n }\r\n const ohpm = findOhpm();\r\n const invocation = /\\.m?js$/i.test(ohpm) ? `${quote(process.execPath)} ${quote(ohpm)}` : quote(ohpm);\r\n const prefix = process.platform === \"win32\" ? `& ${invocation}` : invocation;\r\n return runFiniteCommand({ command: `${prefix} install --all`, key: \"harmonyTest-ohpm-install\", cwd: root, projectRoot, timeoutMs });\r\n}\r\n\r\nexport function inspectHarmonyProject(harmonyProject: string) {\r\n const root = path.resolve(harmonyProject);\r\n const rootProfile = readJson5(path.join(root, \"build-profile.json5\"));\r\n const product = rootProfile.app?.products?.[0]?.name;\r\n const modules = rootProfile.modules ?? [];\r\n const moduleConfig = modules.find((candidate) => candidate.targets?.some((target) => target.applyToProducts?.includes(product)))\r\n ?? modules.find((candidate) => candidate.name === \"entry\")\r\n ?? modules[0];\r\n if (!product || !moduleConfig?.name || !moduleConfig?.srcPath) throw new Error(\"无法从 build-profile.json5 确定 product 或 module\");\r\n const moduleRoot = path.resolve(root, moduleConfig.srcPath);\r\n const moduleProfile = readJson5(path.join(moduleRoot, \"build-profile.json5\"));\r\n const targetNames = (moduleProfile.targets ?? []).map((target) => target.name).filter(Boolean);\r\n const appTarget = moduleConfig.targets?.find((target) => target.applyToProducts?.includes(product))?.name\r\n ?? targetNames.find((name) => !/test$/i.test(name));\r\n const testTarget = targetNames.find((name) => /ohosTest/i.test(name));\r\n if (!appTarget) throw new Error(\"无法从 DevEco 配置确定应用 target\");\r\n const bundleName = readJson5(path.join(root, \"AppScope\", \"app.json5\")).app?.bundleName;\r\n const testModuleFile = path.join(moduleRoot, \"src\", \"ohosTest\", \"module.json5\");\r\n const testModuleName = existsSync(testModuleFile) ? readJson5(testModuleFile).module?.name : null;\r\n return { root, product, module: moduleConfig.name, moduleRoot, appTarget, testTarget, bundleName, testModuleName };\r\n}\r\n\r\nfunction quote(value: unknown) {\r\n const escaped = String(value).replaceAll('\"', '\\\\\"');\r\n return process.platform === \"win32\" ? `\"${escaped}\"` : `'${escaped.replaceAll(\"'\", \"'\\\\''\")}'`;\r\n}\r\n\r\nexport function hvigorCommand(info: ReturnType<typeof inspectHarmonyProject>, target: string) {\r\n const hvigor = findHvigor();\r\n const invocation = /\\.m?js$/i.test(hvigor) ? `${quote(process.execPath)} ${quote(hvigor)}` : quote(hvigor);\r\n const prefix = process.platform === \"win32\" ? `& ${invocation}` : invocation;\r\n return `${prefix} assembleHap --mode module -p product=${quote(info.product)} -p module=${quote(`${info.module}@${target}`)} --no-daemon`;\r\n}\r\n\r\nfunction listFiles(root: string): string[] {\r\n if (!existsSync(root)) return [];\r\n const result: string[] = [];\r\n for (const entry of readdirSync(root, { withFileTypes: true })) {\r\n const absolute = path.join(root, entry.name);\r\n if (entry.isDirectory()) result.push(...listFiles(absolute));\r\n else result.push(absolute);\r\n }\r\n return result;\r\n}\r\n\r\nfunction newestHap(moduleRoot: string, predicate: (name: string) => boolean) {\r\n return listFiles(path.join(moduleRoot, \"build\"))\r\n .filter((file) => file.toLowerCase().endsWith(\".hap\") && predicate(path.basename(file)))\r\n .map((file) => ({ file, stat: statSync(file) }))\r\n .filter(({ stat }) => stat.size > 0)\r\n .sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs)[0] ?? null;\r\n}\r\n\r\nfunction newestBuildInputMtime(root: string, excludedRoots: string[] = []): number {\r\n const ignored = new Set([\".git\", \".hvigor\", \"build\", \"node_modules\", \"oh_modules\"]);\r\n const excluded = excludedRoots.map((value) => path.resolve(value));\r\n let newest = 0;\r\n const visit = (directory: string) => {\r\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\r\n if (entry.isDirectory() && ignored.has(entry.name)) continue;\r\n const absolute = path.join(directory, entry.name);\r\n if (excluded.some((value) => absolute === value || absolute.startsWith(`${value}${path.sep}`))) continue;\r\n if (entry.isDirectory()) visit(absolute);\r\n else if (entry.isFile()) newest = Math.max(newest, statSync(absolute).mtimeMs);\r\n }\r\n };\r\n visit(root);\r\n return newest;\r\n}\r\n\r\nexport function runHarmonyBuild({ projectRoot, harmonyProject, timeoutMs }: { projectRoot: string; harmonyProject: string; timeoutMs: number }) {\r\n const info = inspectHarmonyProject(harmonyProject);\r\n const appArtifactPredicate = (name: string) => !info.testTarget || !name.toLowerCase().includes(info.testTarget.toLowerCase());\r\n const beforeArtifact = newestHap(info.moduleRoot, appArtifactPredicate);\r\n const result = runFiniteCommand({\r\n command: hvigorCommand(info, info.appTarget), key: \"harmonyBuild\", cwd: info.root, projectRoot, timeoutMs,\r\n });\r\n if (result.status !== \"passed\") return result;\r\n const artifact = newestHap(info.moduleRoot, appArtifactPredicate);\r\n if (!artifact) return { ...result, status: \"failed\", summary: \"Hvigor 返回成功,但没有可安装的应用 HAP\", artifact: null };\r\n if (artifact.stat.mtimeMs + 1000 < newestBuildInputMtime(info.root, [path.join(info.moduleRoot, \"src\", \"ohosTest\")])) {\r\n return { ...result, status: \"failed\", summary: \"Hvigor 返回成功,但应用 HAP 早于当前构建输入\", artifact: artifact.file };\r\n }\r\n const artifactReused = Boolean(beforeArtifact\r\n && beforeArtifact.file === artifact.file\r\n && beforeArtifact.stat.mtimeMs === artifact.stat.mtimeMs\r\n && beforeArtifact.stat.size === artifact.stat.size);\r\n return {\r\n ...result,\r\n artifact: artifact.file,\r\n artifactMtime: artifact.stat.mtime.toISOString(),\r\n artifactReused,\r\n summary: artifactReused ? \"Hvigor 增量构建成功,复用现有非空应用 HAP\" : result.summary,\r\n };\r\n}\r\n\r\nexport function buildHarmonyTestCommand({ harmonyProject }: { projectRoot: string; harmonyProject: string }) {\r\n const info = inspectHarmonyProject(harmonyProject);\r\n if (!info.testTarget || !info.testModuleName || !info.bundleName) throw new Error(\"工程缺少可识别的 ohosTest target、测试模块名或 bundleName\");\r\n return { info, command: hvigorCommand(info, info.testTarget) };\r\n}\r\n\r\nexport function runHarmonyTest({ projectRoot, harmonyProject, timeoutMs, testClass = null, testCase = null, target: requestedTarget = null, caseTimeoutMs = 30000 }: {\r\n projectRoot: string; harmonyProject: string; timeoutMs: number; testClass?: string | null; testCase?: string | null;\r\n target?: string | null; caseTimeoutMs?: number;\r\n}) {\r\n const device = checkHarmonyDevice();\r\n if (device.status !== \"passed\") return { status: \"failed\", key: \"harmonyTest\", stage: \"device\", device };\r\n const hdc = process.env.HDC_BINARY || \"hdc\";\r\n // 目标优先级:显式 --target > 环境变量 DROID2HMOS_HDC_TARGET > 真机优先自动选择。\r\n const explicitTarget = requestedTarget || process.env.DROID2HMOS_HDC_TARGET || null;\r\n if (explicitTarget && !device.responsiveTargets.includes(explicitTarget)) {\r\n return {\r\n status: \"failed\", key: \"harmonyTest\", stage: \"device\", device,\r\n summary: `目标设备 ${explicitTarget} 不可响应。可用目标: ${device.responsiveTargets.join(\", \")}`,\r\n };\r\n }\r\n const target = explicitTarget ?? selectPreferredTarget(device.responsiveTargets);\r\n if (process.env.DROID2HMOS_SKIP_AUTO_SIGN !== \"1\") {\r\n const signature = ensureDeviceSignature({ projectRoot, harmonyProject, target, timeoutMs: Math.min(timeoutMs, 5 * 60 * 1000) });\r\n if (signature.status === \"failed\") {\r\n return { status: \"failed\", key: \"harmonyTest\", stage: \"device-signature\", device, target, signature, summary: `真机自动签名失败: ${signature.summary}。可运行 droid2hmos sign <project> 诊断,或设置 DROID2HMOS_SKIP_AUTO_SIGN=1 跳过` };\r\n }\r\n }\r\n const appBuild: any = runHarmonyBuild({ projectRoot, harmonyProject, timeoutMs });\r\n if (appBuild.status !== \"passed\") return { status: \"failed\", key: \"harmonyTest\", stage: \"app-build\", appBuild };\r\n const ohpmInstall = ensureOhpmDependencies({ projectRoot, harmonyProject, timeoutMs });\r\n if (ohpmInstall.status !== \"passed\") return { status: \"failed\", key: \"harmonyTest\", stage: \"ohpm-install\", appBuild, ohpmInstall };\r\n const { info, command } = buildHarmonyTestCommand({ projectRoot, harmonyProject });\r\n const testBuild = runFiniteCommand({ command, key: \"harmonyTest-build\", cwd: info.root, projectRoot, timeoutMs });\r\n if (testBuild.status !== \"passed\") return { status: \"failed\", key: \"harmonyTest\", stage: \"test-build\", appBuild, testBuild };\r\n const testArtifact = newestHap(info.moduleRoot, (name) => name.toLowerCase().includes(info.testTarget.toLowerCase()));\r\n if (!testArtifact) return { status: \"failed\", key: \"harmonyTest\", stage: \"test-artifact\", summary: \"Hvigor 返回成功,但没有可安装的测试 HAP\", appBuild, testBuild };\r\n if (testArtifact.stat.mtimeMs + 1000 < newestBuildInputMtime(info.root, [path.join(info.moduleRoot, \"src\", \"main\")])) {\r\n return { status: \"failed\", key: \"harmonyTest\", stage: \"test-artifact\", summary: \"Hvigor 返回成功,但测试 HAP 早于当前构建输入\", appBuild, testBuild };\r\n }\r\n const hdcInvocation = /\\.m?js$/i.test(hdc) ? `${quote(process.execPath)} ${quote(hdc)}` : quote(hdc);\r\n const prefix = `${process.platform === \"win32\" ? \"& \" : \"\"}${hdcInvocation} -t ${quote(target)}`;\r\n const installApp = runFiniteCommand({ command: `${prefix} install -r ${quote(appBuild.artifact)}`, key: \"harmonyTest-install-app\", cwd: info.root, projectRoot, timeoutMs });\r\n if (installApp.status !== \"passed\") return { status: \"failed\", key: \"harmonyTest\", stage: \"install-app\", installApp };\r\n const installTest = runFiniteCommand({ command: `${prefix} install -r ${quote(testArtifact.file)}`, key: \"harmonyTest-install-test\", cwd: info.root, projectRoot, timeoutMs });\r\n if (installTest.status !== \"passed\") return { status: \"failed\", key: \"harmonyTest\", stage: \"install-test\", installTest };\r\n // 部分 HarmonyOS 镜像(如 6.0.0.48 emulator)不会由 aa test 自动预启动 uitest daemon,\r\n // Driver.create() 将返回 null 并导致所有 UI 用例报错。此处在执行前 best-effort 预启动\r\n // 设备端 daemon(短命令:hdc 立即返回,daemon 在设备后台,空闲约 30s 自动退出,无需清理)。\r\n runFiniteCommand({\r\n command: `${prefix} shell \"uitest start-daemon 1 > /dev/null 2>&1 &\"`,\r\n key: \"harmonyTest-uitest-daemon\", cwd: info.root, projectRoot, timeoutMs: 15_000,\r\n });\r\n const selector = testClass ? ` -s class ${quote(testClass)}${(() => { if (testCase) return ` -s testCase ${quote(testCase)}`; return \"\"; })()}` : \"\";\r\n const execute = runFiniteCommand({\r\n command: `${prefix} shell aa test -b ${quote(info.bundleName)} -m ${quote(info.testModuleName)} -s unittest OpenHarmonyTestRunner -s timeout ${Math.round(caseTimeoutMs)}${selector}`,\r\n key: \"harmonyTest-execute\", cwd: info.root, projectRoot, timeoutMs,\r\n });\r\n const tests = parseHypiumReport(existsSync(execute.stdout) ? readFileSync(execute.stdout, \"utf8\") : \"\");\r\n const passed = execute.status === \"passed\" && tests.valid;\r\n const hypium = {\r\n found: tests.total > 0,\r\n ok: tests.total > 0,\r\n tests: tests.total,\r\n failure: tests.failed,\r\n error: tests.errors,\r\n pass: tests.passed,\r\n ignore: tests.ignored,\r\n };\r\n return {\r\n status: passed ? \"passed\" : \"failed\",\r\n key: \"harmonyTest\",\r\n stage: \"execute\",\r\n target,\r\n appArtifact: appBuild.artifact,\r\n testArtifact: testArtifact.file,\r\n execute,\r\n tests,\r\n hypium,\r\n summary: passed ? `HarmonyOS 应用与 Hypium 测试执行成功:${tests.summary}` : (() => { if (execute.status === \"passed\") return tests.summary; return \"Hypium 执行失败\"; })(),\r\n };\r\n}\r\n","import { closeSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync } from \"node:fs\";\r\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\r\nimport { spawn, spawnSync } from \"node:child_process\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\n\r\n/**\r\n * 根据 migration config 推导安卓工程根目录。config 位于兄弟迁移工作区\r\n * (`<父目录>/<工程名>-migration/.migration/config.json`),因此相对的\r\n * `androidProject` 以工作区父目录为基准解析;绝对的 `androidProject` 原样生效。\r\n */\r\nfunction androidProjectRoot(absoluteConfig: string, androidProject: unknown): string {\r\n const workspaceParent = resolve(dirname(absoluteConfig), \"..\", \"..\");\r\n return typeof androidProject === \"string\" && androidProject\r\n ? resolve(workspaceParent, androidProject)\r\n : workspaceParent;\r\n}\r\n\r\nconst DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;\r\n// Android 受管命令(androidBuild/androidTest)已移除:迁移流程不再执行 Android 编译或测试。\r\nconst COMMAND_KEYS = new Set([\"harmonyStatic\"]);\r\n\r\ninterface RunConfigCommandOptions {\r\n configPath: string;\r\n key: string;\r\n timeoutMs?: number;\r\n runner?: typeof spawnSync;\r\n replacements?: Record<string, unknown>;\r\n requiredTokens?: string[];\r\n}\r\n\r\nexport function validateFiniteCommand(command) {\r\n const value = String(command ?? \"\").trim();\r\n const errors = [];\r\n if (!value) return [\"命令为空\"];\r\n if (value.includes(\"|\")) errors.push(\"禁止在受管命令中使用输出管道;日志由运行器直接写文件\");\r\n if (/\\bSelect-Object\\s+-Last\\b/i.test(value)) errors.push(\"禁止使用 Select-Object -Last 等等待 EOF 的日志截取\");\r\n if (/\\bcmd(?:\\.exe)?\\s+\\/c\\b/i.test(value)) errors.push(\"禁止使用 cmd /c 增加 Windows 子进程层级\");\r\n if (/\\b(?:gradlew(?:\\.bat)?|gradle)\\b/i.test(value) && !/(?:^|\\s)--no-daemon(?:\\s|$)/i.test(value)) {\r\n errors.push(\"Gradle 命令必须包含 --no-daemon\");\r\n }\r\n if (/\\bhvigorw(?:\\.js)?\\b/i.test(value) && !/(?:^|\\s)--no-daemon(?:\\s|$)/i.test(value)) {\r\n errors.push(\"Hvigor 命令必须包含 --no-daemon\");\r\n }\r\n if (/\\bStart-Process\\b/i.test(value) || /\\bstart\\s+\\/b\\b/i.test(value)) {\r\n errors.push(\"有限命令禁止启动后台进程\");\r\n }\r\n return errors;\r\n}\r\n\r\nexport function runConfigCommand({ configPath, key, timeoutMs = DEFAULT_TIMEOUT_MS, runner = spawnSync, replacements = {}, requiredTokens = [] }: RunConfigCommandOptions) {\r\n if (!configPath || !key) throw new Error(\"缺少 configPath 或 command key\");\r\n if (!COMMAND_KEYS.has(key)) throw new Error(`不支持的 command key: ${key}`);\r\n const absoluteConfig = resolve(configPath);\r\n const config = JSON.parse(readFileSync(absoluteConfig, \"utf8\"));\r\n const configuredCommand = config.commands?.[key];\r\n if (configuredCommand === null) return { status: \"not_applicable\", key, summary: `${key} 未配置` };\r\n for (const token of requiredTokens) {\r\n if (!String(configuredCommand).includes(token)) {\r\n return { status: \"rejected\", key, errors: [`${key} 缺少必要模板 ${token}`], summary: `${key} 不支持本次增量选择器` };\r\n }\r\n }\r\n let command = String(configuredCommand);\r\n for (const [token, value] of Object.entries(replacements)) command = command.replaceAll(token, String(value));\r\n const projectRoot = androidProjectRoot(absoluteConfig, config.androidProject);\r\n const configuredCwd = key.startsWith(\"android\") ? config.androidProject : config.harmonyProject;\r\n const cwd = isAbsolute(configuredCwd) ? configuredCwd : resolve(projectRoot, configuredCwd);\r\n return runFiniteCommand({ command, key, cwd, projectRoot, timeoutMs, runner });\r\n}\r\n\r\nexport function runConfigCommandAsync({ configPath, key, timeoutMs = DEFAULT_TIMEOUT_MS, replacements = {}, requiredTokens = [] }: Omit<RunConfigCommandOptions, \"runner\">) {\r\n if (!configPath || !key) throw new Error(\"缺少 configPath 或 command key\");\r\n if (!COMMAND_KEYS.has(key)) throw new Error(`不支持的 command key: ${key}`);\r\n const absoluteConfig = resolve(configPath);\r\n const config = JSON.parse(readFileSync(absoluteConfig, \"utf8\"));\r\n const configuredCommand = config.commands?.[key];\r\n if (configuredCommand === null) return Promise.resolve({ status: \"not_applicable\", key, summary: `${key} 未配置` });\r\n for (const token of requiredTokens) {\r\n if (!String(configuredCommand).includes(token)) {\r\n return Promise.resolve({ status: \"rejected\", key, errors: [`${key} 缺少必要模板 ${token}`], summary: `${key} 不支持本次增量选择器` });\r\n }\r\n }\r\n let command = String(configuredCommand);\r\n for (const [token, value] of Object.entries(replacements)) command = command.replaceAll(token, String(value));\r\n const projectRoot = androidProjectRoot(absoluteConfig, config.androidProject);\r\n const configuredCwd = key.startsWith(\"android\") ? config.androidProject : config.harmonyProject;\r\n const cwd = isAbsolute(configuredCwd) ? configuredCwd : resolve(projectRoot, configuredCwd);\r\n return runFiniteCommandAsync({ command, key, cwd, projectRoot, timeoutMs });\r\n}\r\n\r\ninterface RunFiniteCommandOptions {\r\n command: string;\r\n key: string;\r\n cwd: string;\r\n projectRoot: string;\r\n timeoutMs?: number;\r\n runner?: typeof spawnSync;\r\n}\r\n\r\ninterface RunFiniteExecutableOptions {\r\n executable: string;\r\n args: string[];\r\n key: string;\r\n cwd: string;\r\n projectRoot: string;\r\n timeoutMs?: number;\r\n runner?: typeof spawnSync;\r\n}\r\n\r\nexport function runFiniteCommand({ command, key, cwd, projectRoot, timeoutMs = DEFAULT_TIMEOUT_MS, runner = spawnSync }: RunFiniteCommandOptions) {\r\n if (!key || !cwd || !projectRoot) throw new Error(\"缺少 key、cwd 或 projectRoot\");\r\n const errors = validateFiniteCommand(command);\r\n if (errors.length) return { status: \"rejected\", key, errors, summary: `${key} 命令违反流程存活门禁` };\r\n if (!existsSync(cwd)) throw new Error(`${key} 工作目录不存在: ${cwd}`);\r\n const logDir = join(migrationDirectory(projectRoot), \"preflight-logs\");\r\n mkdirSync(logDir, { recursive: true });\r\n const stdoutPath = join(logDir, `${key}.stdout.log`);\r\n const stderrPath = join(logDir, `${key}.stderr.log`);\r\n const stdout = openSync(stdoutPath, \"w\");\r\n const stderr = openSync(stderrPath, \"w\");\r\n let result;\r\n try {\r\n const executable = process.platform === \"win32\" ? \"powershell.exe\" : \"/bin/sh\";\r\n const args = process.platform === \"win32\"\r\n ? [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-Command\", command]\r\n : [\"-lc\", command];\r\n result = runner(executable, args, {\r\n cwd,\r\n windowsHide: true,\r\n shell: false,\r\n stdio: [\"ignore\", stdout, stderr],\r\n timeout: Number(timeoutMs),\r\n killSignal: \"SIGKILL\",\r\n });\r\n } finally {\r\n closeSync(stdout);\r\n closeSync(stderr);\r\n }\r\n\r\n const timedOut = result?.error?.code === \"ETIMEDOUT\";\r\n const exitCode = Number.isInteger(result?.status) ? result.status : null;\r\n return {\r\n status: !timedOut && exitCode === 0 ? \"passed\" : \"failed\",\r\n key,\r\n exitCode,\r\n timedOut,\r\n timeoutMs: Number(timeoutMs),\r\n cwd,\r\n stdout: stdoutPath,\r\n stderr: stderrPath,\r\n summary: timedOut\r\n ? `${key} 超过 ${timeoutMs}ms,已终止受管命令`\r\n : (() => { if (exitCode === 0) return `${key} 执行成功`; return `${key} 执行失败,退出码 ${exitCode ?? \"unknown\"}`; })(),\r\n };\r\n}\r\n\r\nexport function runFiniteExecutable({ executable, args, key, cwd, projectRoot, timeoutMs = DEFAULT_TIMEOUT_MS, runner = spawnSync }: RunFiniteExecutableOptions) {\r\n if (!executable || !key || !cwd || !projectRoot) throw new Error(\"缺少 executable、key、cwd 或 projectRoot\");\r\n if (!existsSync(cwd)) throw new Error(`${key} 工作目录不存在: ${cwd}`);\r\n const logDir = join(migrationDirectory(projectRoot), \"preflight-logs\");\r\n mkdirSync(logDir, { recursive: true });\r\n const stdoutPath = join(logDir, `${key}.stdout.log`);\r\n const stderrPath = join(logDir, `${key}.stderr.log`);\r\n const stdout = openSync(stdoutPath, \"w\");\r\n const stderr = openSync(stderrPath, \"w\");\r\n let result;\r\n try {\r\n result = runner(executable, args, {\r\n cwd,\r\n windowsHide: true,\r\n shell: false,\r\n stdio: [\"ignore\", stdout, stderr],\r\n timeout: Number(timeoutMs),\r\n killSignal: \"SIGKILL\",\r\n });\r\n } finally {\r\n closeSync(stdout);\r\n closeSync(stderr);\r\n }\r\n\r\n const timedOut = result?.error?.code === \"ETIMEDOUT\";\r\n const exitCode = Number.isInteger(result?.status) ? result.status : null;\r\n return {\r\n status: !timedOut && exitCode === 0 ? \"passed\" : \"failed\",\r\n key,\r\n executable,\r\n args,\r\n exitCode,\r\n timedOut,\r\n timeoutMs: Number(timeoutMs),\r\n cwd,\r\n stdout: stdoutPath,\r\n stderr: stderrPath,\r\n summary: timedOut\r\n ? `${key} 超过 ${timeoutMs}ms,已终止受管命令`\r\n : (() => { if (exitCode === 0) return `${key} 执行成功`; return `${key} 执行失败,退出码 ${exitCode ?? \"unknown\"}`; })(),\r\n };\r\n}\r\n\r\nexport async function runFiniteCommandAsync({ command, key, cwd, projectRoot, timeoutMs = DEFAULT_TIMEOUT_MS }: Omit<RunFiniteCommandOptions, \"runner\">) {\r\n if (!key || !cwd || !projectRoot) throw new Error(\"缺少 key、cwd 或 projectRoot\");\r\n const errors = validateFiniteCommand(command);\r\n if (errors.length) return { status: \"rejected\", key, errors, summary: `${key} 命令违反流程存活门禁` };\r\n if (!existsSync(cwd)) throw new Error(`${key} 工作目录不存在: ${cwd}`);\r\n const logDir = join(migrationDirectory(projectRoot), \"preflight-logs\");\r\n mkdirSync(logDir, { recursive: true });\r\n const stdoutPath = join(logDir, `${key}.stdout.log`);\r\n const stderrPath = join(logDir, `${key}.stderr.log`);\r\n const stdout = createWriteStream(stdoutPath, { flags: \"w\" });\r\n const stderr = createWriteStream(stderrPath, { flags: \"w\" });\r\n const executable = process.platform === \"win32\" ? \"powershell.exe\" : \"/bin/sh\";\r\n const args = process.platform === \"win32\"\r\n ? [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-Command\", command]\r\n : [\"-lc\", command];\r\n const child = spawn(executable, args, {\r\n cwd,\r\n windowsHide: true,\r\n shell: false,\r\n detached: process.platform !== \"win32\",\r\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\r\n });\r\n child.stdout.pipe(stdout);\r\n child.stderr.pipe(stderr);\r\n let timedOut = false;\r\n const timer = setTimeout(() => {\r\n timedOut = true;\r\n if (process.platform !== \"win32\" && child.pid) {\r\n try { process.kill(-child.pid, \"SIGKILL\"); } catch { child.kill(\"SIGKILL\"); }\r\n } else child.kill(\"SIGKILL\");\r\n }, Number(timeoutMs));\r\n const exitCode = await new Promise<number | null>((resolveExit) => {\r\n child.once(\"error\", () => resolveExit(null));\r\n child.once(\"close\", (code) => resolveExit(code));\r\n });\r\n clearTimeout(timer);\r\n await Promise.all([\r\n new Promise<void>((done) => stdout.end(done)),\r\n new Promise<void>((done) => stderr.end(done)),\r\n ]);\r\n return {\r\n status: !timedOut && exitCode === 0 ? \"passed\" : \"failed\",\r\n key,\r\n exitCode,\r\n timedOut,\r\n timeoutMs: Number(timeoutMs),\r\n cwd,\r\n stdout: stdoutPath,\r\n stderr: stderrPath,\r\n summary: timedOut\r\n ? `${key} 超过 ${timeoutMs}ms,已终止受管命令`\r\n : (() => { if (exitCode === 0) return `${key} 执行成功`; return `${key} 执行失败,退出码 ${exitCode ?? \"unknown\"}`; })(),\r\n };\r\n}\r\n","#!/usr/bin/env node\r\nimport { spawnSync } from \"node:child_process\";\r\n\r\nconst READY_MARKER = \"A2H_DEVICE_READY\";\r\n\r\nfunction command(executable, args, runner) {\r\n const scriptWrapper = /\\.m?js$/i.test(executable);\r\n const result = runner(scriptWrapper ? process.execPath : executable, scriptWrapper ? [executable, ...args] : args, { encoding: \"utf8\", shell: false, timeout: 15000 });\r\n return {\r\n executable,\r\n args,\r\n exitCode: Number.isInteger(result.status) ? result.status : 1,\r\n stdout: result.stdout ?? \"\",\r\n stderr: result.stderr ?? result.error?.message ?? \"\",\r\n };\r\n}\r\n\r\nexport function parseTargets(output) {\r\n return [...new Set(String(output).split(/\\r?\\n/).map((line) => line.trim()).filter((line) => line && !/^\\[?empty\\]?$/i.test(line) && !/^list of targets/i.test(line)))];\r\n}\r\n\r\nexport function checkHarmonyDevice({ hdc = process.env.HDC_BINARY || \"hdc\", runner = spawnSync } = {}) {\r\n const list = command(hdc, [\"list\", \"targets\"], runner);\r\n if (list.exitCode !== 0) return { status: \"failed\", hdc, targets: [], responsiveTargets: [], summary: \"HDC 不可用或无法查询设备\", evidence: [list.stderr || list.stdout] };\r\n const targets = parseTargets(list.stdout);\r\n if (!targets.length) return { status: \"failed\", hdc, targets, responsiveTargets: [], summary: \"未发现可用 HarmonyOS 真机或模拟器\", evidence: [list.stdout || \"hdc list targets returned no targets\"] };\r\n const probes = targets.map((target) => ({ target, result: command(hdc, [\"-t\", target, \"shell\", \"echo\", READY_MARKER], runner) }));\r\n const responsiveTargets = probes.filter(({ result }) => result.exitCode === 0 && result.stdout.includes(READY_MARKER)).map(({ target }) => target);\r\n if (!responsiveTargets.length) return { status: \"failed\", hdc, targets, responsiveTargets, summary: \"发现设备,但设备 Shell 无响应\", evidence: probes.map(({ target, result }) => `${target}: ${result.stderr || result.stdout || `exit ${result.exitCode}`}`) };\r\n return { status: \"passed\", hdc, targets, responsiveTargets, summary: `发现 ${responsiveTargets.length} 个可响应的 HarmonyOS 运行设备`, evidence: responsiveTargets };\r\n}\r\n","export interface HypiumReport {\r\n valid: boolean;\r\n total: number;\r\n passed: number;\r\n failed: number;\r\n errors: number;\r\n ignored: number;\r\n resultCode: number | null;\r\n executedCases: string[];\r\n summary: string;\r\n}\r\n\r\nconst empty = (summary: string): HypiumReport => ({\r\n valid: false,\r\n total: 0,\r\n passed: 0,\r\n failed: 0,\r\n errors: 0,\r\n ignored: 0,\r\n resultCode: null,\r\n executedCases: [],\r\n summary,\r\n});\r\n\r\nexport function parseHypiumReport(output: string): HypiumReport {\r\n const match = String(output).match(/Tests run:\\s*(\\d+)\\s*,\\s*Failure:\\s*(\\d+)\\s*,\\s*Error:\\s*(\\d+)\\s*,\\s*Pass:\\s*(\\d+)\\s*,\\s*Ignore:\\s*(\\d+)/i);\r\n if (!match) return empty(\"Hypium did not produce a machine-readable test summary\");\r\n\r\n const [, totalValue, failedValue, errorValue, passedValue, ignoredValue] = match;\r\n const total = Number(totalValue);\r\n const failed = Number(failedValue);\r\n const errors = Number(errorValue);\r\n const passed = Number(passedValue);\r\n const ignored = Number(ignoredValue);\r\n const resultMatch = [...String(output).matchAll(/(?:TestFinished-ResultCode|OHOS_REPORT_CODE):\\s*(-?\\d+)/gi)].at(-1);\r\n const resultCode = resultMatch ? Number(resultMatch[1]) : null;\r\n const executedCases: string[] = [];\r\n let currentClass: string | null = null;\r\n for (const line of String(output).split(/\\r?\\n/)) {\r\n const classMatch = line.match(/OHOS_REPORT_STATUS:\\s*class=(.+)\\s*$/);\r\n if (classMatch) currentClass = classMatch[1].trim();\r\n const caseMatch = line.match(/OHOS_REPORT_STATUS:\\s*test=(.+)\\s*$/);\r\n if (caseMatch) {\r\n const name = `${currentClass ?? \"unknown\"}#${caseMatch[1].trim()}`;\r\n if (!executedCases.includes(name)) executedCases.push(name);\r\n }\r\n }\r\n\r\n const countsConsistent = total > 0 && passed + failed + errors + ignored === total;\r\n const valid = countsConsistent && failed === 0 && errors === 0 && ignored === 0 && passed === total && (resultCode === null || resultCode === 0);\r\n const problems = [\r\n total === 0 ? \"zero tests\" : null,\r\n failed ? `failed ${failed}` : null,\r\n errors ? `errors ${errors}` : null,\r\n ignored ? `ignored ${ignored}` : null,\r\n !countsConsistent && total > 0 ? \"inconsistent counts\" : null,\r\n resultCode !== null && resultCode !== 0 ? `result code ${resultCode}` : null,\r\n ].filter(Boolean);\r\n return {\r\n valid,\r\n total,\r\n passed,\r\n failed,\r\n errors,\r\n ignored,\r\n resultCode,\r\n executedCases,\r\n summary: valid ? `Hypium ${passed}/${total} passed` : `Hypium rejected: ${problems.join(\", \") || \"invalid result\"}`,\r\n };\r\n}\r\n","import fs from \"node:fs\";\r\nimport os from \"node:os\";\r\nimport path from \"node:path\";\r\nimport { spawnSync } from \"node:child_process\";\r\nimport JSON5 from \"json5\";\r\nimport { checkHarmonyDevice } from \"./check-hmos-device.ts\";\r\nimport { inspectHarmonyProject } from \"./harmony-toolchain.ts\";\r\nimport { checkDevEcoCliAuth, generateHarmonySignatureWithDevEcoCli, listDevEcoDevices } from \"./deveco-cli.ts\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\nimport { capCompatibleSdkVersionTo, parseAbcHeaderVersion, sdkVersionForApiLevel } from \"./sdk-version.ts\";\r\n\r\n/**\r\n * 真机自动签名。\r\n *\r\n * `devecocli signature generate` 在生成签名材料前,会把本地当前连接的所有设备\r\n * (真机或模拟器)注册进账号的调试 profile。droid2hmos 此前只在 `init` 时签名\r\n * 一次,之后新接入的真机在 `hdc install` 时会持续报签名错误,用户必须回\r\n * DevEco Studio 手动重签。\r\n *\r\n * 本模块补齐该缺口:安装到真机前先检查当前签名材料是否已覆盖该设备\r\n * (记录在 `.migration/signature/devices.json`),未覆盖则重新执行\r\n * `devecocli signature generate --force`,随后 hvigor 会在下一次构建中\r\n * 用新签名重新对 HAP 签名。\r\n */\r\n\r\ninterface MaterialFingerprint {\r\n path: string;\r\n mtimeMs: number;\r\n size: number;\r\n}\r\n\r\ninterface SignatureMarker {\r\n schemaVersion: 1;\r\n devices: Record<string, {\r\n target: string;\r\n product: string;\r\n bundleName: string | null;\r\n materials: MaterialFingerprint[];\r\n signedAt: string;\r\n }>;\r\n}\r\n\r\nfunction hdcBinary() {\r\n return process.env.HDC_BINARY || \"hdc\";\r\n}\r\n\r\nfunction runHdc(args: string[], timeoutMs = 30000) {\r\n const hdc = hdcBinary();\r\n const scriptWrapper = /\\.m?js$/i.test(hdc);\r\n const result = spawnSync(scriptWrapper ? process.execPath : hdc, scriptWrapper ? [hdc, ...args] : args, {\r\n encoding: \"utf8\",\r\n shell: false,\r\n timeout: timeoutMs,\r\n windowsHide: true,\r\n });\r\n return {\r\n ok: !result.error && result.status === 0,\r\n exitCode: Number.isInteger(result.status) ? result.status : null,\r\n stdout: String(result.stdout ?? \"\"),\r\n stderr: String(result.stderr ?? result.error?.message ?? \"\"),\r\n invocation: [hdc, ...args],\r\n };\r\n}\r\n\r\n/** `hdc -t <target> shell bm get -u` → 读取设备 UDID。 */\r\nexport function deviceUdid(target: string): { status: \"passed\"; udid: string } | { status: \"failed\"; summary: string; evidence: string[] } {\r\n const result = runHdc([\"-t\", target, \"shell\", \"bm\", \"get\", \"-u\"]);\r\n if (!result.ok) return { status: \"failed\", summary: `无法读取设备 UDID: ${result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`}`, evidence: [result.invocation.join(\" \")] };\r\n const udid = result.stdout\r\n .split(/\\r?\\n/)\r\n .map((line) => line.trim())\r\n .flatMap((line) => line.match(/[A-Fa-f0-9]{32,64}/g) ?? [])\r\n .at(-1);\r\n if (!udid) return { status: \"failed\", summary: `设备未返回可识别的 UDID: ${result.stdout.trim() || \"(empty)\"}`, evidence: [result.invocation.join(\" \")] };\r\n return { status: \"passed\", udid };\r\n}\r\n\r\n/**\r\n * 判断 hdc 目标是否为真机。优先使用 DevEco CLI 返回的 `kind` 字段;\r\n * devecocli 无法列出设备时回退到序列号启发式判断(emulator/localhost),\r\n * 保证该检查始终可用。\r\n */\r\nexport function isRealDeviceTarget(target: string): boolean {\r\n if (/^(emulator|127\\.0\\.0\\.1|localhost)/i.test(target)) return false;\r\n const listed = listDevEcoDevices();\r\n if (listed.status === \"passed\") {\r\n const match = listed.devices.find((device: any) => String(device?.serial ?? \"\") === target || String(device?.name ?? \"\") === target);\r\n if (match?.kind) return String(match.kind).toLowerCase() !== \"emulator\";\r\n }\r\n return true;\r\n}\r\n\r\n/** 对 build-profile.json5 引用的签名材料文件生成指纹(路径+mtime+大小)。 */\r\nexport function readSigningMaterialFingerprints(harmonyRoot: string): MaterialFingerprint[] {\r\n const profile = path.join(harmonyRoot, \"build-profile.json5\");\r\n if (!fs.existsSync(profile)) return [];\r\n let parsed: any;\r\n try {\r\n parsed = JSON5.parse(fs.readFileSync(profile, \"utf8\"));\r\n } catch {\r\n return [];\r\n }\r\n const signingConfigs: any[] = parsed?.app?.signingConfigs ?? [];\r\n const files = [...new Set(signingConfigs\r\n .flatMap((config) => [config?.material?.certpath, config?.material?.profile, config?.material?.storeFile])\r\n .filter((file): file is string => typeof file === \"string\" && file.length > 0)\r\n .map((file) => (path.isAbsolute(file) ? file : path.resolve(harmonyRoot, file))))];\r\n return [...new Set(files)].flatMap((file) => {\r\n if (!fs.existsSync(file)) return [];\r\n const stat = fs.statSync(file);\r\n return [{ path: file, mtimeMs: Math.round(stat.mtimeMs), size: stat.size }];\r\n });\r\n}\r\n\r\nfunction markerPath(projectRoot: string) {\r\n return path.join(migrationDirectory(projectRoot), \"signature\", \"devices.json\");\r\n}\r\n\r\nfunction readMarker(projectRoot: string): SignatureMarker {\r\n try {\r\n const value = JSON.parse(fs.readFileSync(markerPath(projectRoot), \"utf8\"));\r\n if (value?.schemaVersion === 1 && value.devices && typeof value.devices === \"object\") return value;\r\n } catch {\r\n // marker 文件缺失或内容无效\r\n }\r\n return { schemaVersion: 1, devices: {} };\r\n}\r\n\r\nfunction writeMarker(projectRoot: string, marker: SignatureMarker) {\r\n const file = markerPath(projectRoot);\r\n fs.mkdirSync(path.dirname(file), { recursive: true });\r\n const temporary = `${file}.${process.pid}.tmp`;\r\n fs.writeFileSync(temporary, `${JSON.stringify(marker, null, 2)}\\n`, \"utf8\");\r\n fs.renameSync(temporary, file);\r\n}\r\n\r\nexport function materialsMatch(left: MaterialFingerprint[], right: MaterialFingerprint[]) {\r\n return left.length === right.length && left.every((item, index) =>\r\n item.path === right[index]?.path && item.mtimeMs === right[index]?.mtimeMs && item.size === right[index]?.size);\r\n}\r\n\r\n/**\r\n * 记录(不重新生成)当前签名材料已覆盖所连接的真机。用于新工程刚执行完\r\n * `devecocli signature generate` 之后——生成过程已注册所有连接设备,\r\n * 只需写入 marker,避免下一次运行重复生成。\r\n */\r\nexport function recordDeviceSignature({ projectRoot, harmonyProject, target }: {\r\n projectRoot: string;\r\n harmonyProject: string;\r\n target?: string;\r\n}) {\r\n const info = inspectHarmonyProject(harmonyProject);\r\n const resolvedTarget = target ?? process.env.DROID2HMOS_HDC_TARGET ?? (() => {\r\n const device = checkHarmonyDevice();\r\n return device.status === \"passed\" ? selectPreferredTarget(device.responsiveTargets) : null;\r\n })();\r\n if (!resolvedTarget) {\r\n return { status: \"skipped\" as const, summary: \"当前无连接设备,跳过签名覆盖记录(接入真机后首次测试会自动重签)\", evidence: [] };\r\n }\r\n if (!isRealDeviceTarget(resolvedTarget)) {\r\n return { status: \"skipped\" as const, target: resolvedTarget, summary: `目标 ${resolvedTarget} 是模拟器,无需真机签名`, evidence: [resolvedTarget] };\r\n }\r\n const udidResult = deviceUdid(resolvedTarget);\r\n if (udidResult.status === \"failed\") return { ...udidResult, stage: \"udid\" as const, target: resolvedTarget };\r\n const materials = readSigningMaterialFingerprints(info.root);\r\n const marker = readMarker(projectRoot);\r\n marker.devices[udidResult.udid] = { target: resolvedTarget, product: info.product, bundleName: info.bundleName ?? null, materials, signedAt: new Date().toISOString() };\r\n writeMarker(projectRoot, marker);\r\n return {\r\n status: \"passed\" as const,\r\n target: resolvedTarget,\r\n udid: udidResult.udid,\r\n product: info.product,\r\n materials,\r\n summary: `签名材料已记录覆盖真机 ${resolvedTarget}(${materials.length} 个材料文件)`,\r\n evidence: [udidResult.udid, ...materials.map((item) => item.path)],\r\n };\r\n}\r\n\r\n/**\r\n * 为新建的鸿蒙工程签名以便部署真机:先用 DevEco CLI 生成签名材料\r\n * (生成过程会把本地连接的所有设备注册进调试 profile),再记录设备\r\n * 覆盖情况;材料未变化时后续 `test harmony` 不会重复生成。\r\n */\r\nexport function signNewHarmonyProject({ projectRoot, harmonyProject, target, timeoutMs }: {\r\n projectRoot: string;\r\n harmonyProject: string;\r\n target?: string;\r\n timeoutMs?: number;\r\n}) {\r\n const signature = generateHarmonySignatureWithDevEcoCli({\r\n harmonyProject,\r\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\r\n });\r\n if (signature.status !== \"passed\") return { ...signature, status: \"failed\" as const, stage: \"generate\" as const };\r\n // 真机可安装性:新工程版本跟随创建机器,若连接的真机系统更低则下调兼容版本。\r\n const resolvedTarget = target ?? process.env.DROID2HMOS_HDC_TARGET ?? (() => {\r\n const device = checkHarmonyDevice();\r\n return device.status === \"passed\" ? selectPreferredTarget(device.responsiveTargets) : null;\r\n })();\r\n const installable = resolvedTarget && isRealDeviceTarget(resolvedTarget)\r\n ? ensureDeviceInstallable(inspectHarmonyProject(harmonyProject).root, resolvedTarget)\r\n : { status: \"skipped\" as const, changed: false, summary: \"无真机连接,跳过兼容版本检查\" };\r\n const recorded = recordDeviceSignature({ projectRoot, harmonyProject, target: resolvedTarget ?? undefined });\r\n return {\r\n status: \"passed\" as const,\r\n signature,\r\n recorded,\r\n installable,\r\n target: recorded.status === \"passed\" ? recorded.target : (recorded as any).target ?? null,\r\n udid: recorded.status === \"passed\" ? (recorded as any).udid : null,\r\n summary: recorded.status === \"passed\"\r\n ? `新工程签名已生成,并覆盖真机 ${(recorded as any).target}${(() => { if (installable.changed) return `;${installable.summary}`; return \"\"; })()}`\r\n : `新工程签名已生成(${recorded.summary})`,\r\n evidence: [...(signature.evidence ?? []), ...(recorded.evidence ?? [])],\r\n };\r\n}\r\n/** 设备侧系统 ABC 样本路径:其头部版本即该运行时可加载的最高字节码版本。 */\r\nconst DEVICE_SYSTEM_ABC_PATH = \"/system/etc/abc/framework/stateMgmt.abc\";\r\n\r\n/**\r\n * 读取真机系统自带 ABC 的字节码版本(如 \"13.0.1.0\")。\r\n *\r\n * ArkTS 运行时只接受不高于系统自带 ABC 版本的字节码。`param get\r\n * const.ohos.apiversion` 在 log/工程构建的系统镜像上可能虚报(实测\r\n * HUAWEI Mate 60 log 版声称 API 24、运行时仅接受 abc 13.0.1.0,按 24\r\n * 构建的 HAP 可安装但启动即 abort 闪退),因此下调 compatibleSdkVersion\r\n * 前必须以该值为准。读取或解析失败返回 null(不阻塞流程)。\r\n */\r\nexport function readDeviceSystemAbcVersion(target: string): { version: string; major: number } | null {\r\n const temporary = path.join(os.tmpdir(), `droid2hmos-abc-${process.pid}-${Date.now()}`);\r\n const result = runHdc([\"-t\", target, \"file\", \"recv\", DEVICE_SYSTEM_ABC_PATH, temporary]);\r\n if (!result.ok || !fs.existsSync(temporary)) return null;\r\n try {\r\n const header = new Uint8Array(fs.readFileSync(temporary).subarray(0, 16));\r\n const version = parseAbcHeaderVersion(header);\r\n if (!version) return null;\r\n const major = Number(version.split(\".\")[0]);\r\n if (!Number.isInteger(major) || major <= 0) return null;\r\n return { version, major };\r\n } finally {\r\n fs.rmSync(temporary, { force: true });\r\n }\r\n}\r\n\r\n/** `hdc -t <target> shell param get` → 真机系统 SDK 版本(API 级别 + 版本号)。 */\r\nexport function detectDeviceSdkVersion(target: string): {\r\n apiLevel: number;\r\n sdkVersion: string;\r\n claimedApiLevel: number;\r\n systemAbcVersion: string | null;\r\n diverged: boolean;\r\n} | null {\r\n const api = runHdc([\"-t\", target, \"shell\", \"param\", \"get\", \"const.ohos.apiversion\"]);\r\n if (!api.ok) return null;\r\n const claimedApiLevel = Number(api.stdout.split(/\\r?\\n/).map((line) => line.trim()).filter(Boolean).at(-1));\r\n if (!Number.isInteger(claimedApiLevel) || claimedApiLevel <= 0) return null;\r\n // 有效 API 取 param 声称值与系统 ABC 字节码大版本的较小值:param 虚报时\r\n // 按 ABC 实际能力为准,保证构建产物字节码可被该运行时加载。\r\n const systemAbc = readDeviceSystemAbcVersion(target);\r\n const apiLevel = Math.min(claimedApiLevel, systemAbc?.major ?? claimedApiLevel);\r\n const fullname = runHdc([\"-t\", target, \"shell\", \"param\", \"get\", \"const.ohos.fullname\"]);\r\n const platformVersion = fullname.ok ? fullname.stdout.match(/\\d+\\.\\d+\\.\\d+/)?.[0] : null;\r\n // 有效 API 与 param 不一致时禁止用 fullname 版本段拼串(如 \"6.1.1(13)\"\r\n // 是非法配对,hvigor 会直接报 00303083),改走映射表。\r\n const sdkVersion = (apiLevel === claimedApiLevel && platformVersion ? `${platformVersion}(${apiLevel})` : null)\r\n ?? sdkVersionForApiLevel(apiLevel)\r\n ?? \"5.0.0(12)\";\r\n return {\r\n apiLevel,\r\n sdkVersion,\r\n claimedApiLevel,\r\n systemAbcVersion: systemAbc?.version ?? null,\r\n diverged: systemAbc !== null && systemAbc.major < claimedApiLevel,\r\n };\r\n}\r\n\r\n/**\r\n * 真机可安装性保障:真机 API 低于工程 compatibleSdkVersion 时下调兼容版本,\r\n * 避免新工程(跟随创建机器 SDK)在老系统真机上安装失败。\r\n * 字节码版本由 compatibleSdkVersion 决定(targetSdkVersion 保持本机最新\r\n * 不影响产物 abc 版本,已实测验证),因此下调 compatible 即可同时解决\r\n * 「装得上但启动 abort」的低版本运行时问题。\r\n */\r\nfunction ensureDeviceInstallable(harmonyRoot: string, target: string) {\r\n const device = detectDeviceSdkVersion(target);\r\n if (!device) return { status: \"skipped\" as const, changed: false, summary: \"无法读取真机系统版本,跳过兼容版本检查\" };\r\n const capped = capCompatibleSdkVersionTo(harmonyRoot, device.sdkVersion);\r\n const divergence = device.diverged\r\n ? `;真机 param 声称 API ${device.claimedApiLevel},但系统 ABC 字节码上限为 ${device.systemAbcVersion}(log 版镜像常见虚报),已按运行时实际能力取 API ${device.apiLevel}`\r\n : \"\";\r\n return {\r\n ...capped,\r\n deviceApiLevel: device.apiLevel,\r\n deviceSdkVersion: device.sdkVersion,\r\n systemAbcVersion: device.systemAbcVersion,\r\n diverged: device.diverged,\r\n summary: capped.summary + divergence,\r\n evidence: [...(capped.evidence ?? []), ...(device.systemAbcVersion ? [`system abc ${device.systemAbcVersion}`] : [])],\r\n };\r\n}\r\n\r\n/**\r\n * 多设备并存时的目标选择:优先真机,其次按传入顺序回退(通常是模拟器)。\r\n * 序列号形如 emulator-xxx、127.0.0.1:x、localhost:x 的目标直接判为模拟器,\r\n * 其余目标尝试通过 DevEco CLI 的 kind 字段确认。\r\n */\r\nexport function selectPreferredTarget(targets: string[]): string | null {\r\n if (!targets.length) return null;\r\n const real = targets.find((target) => isRealDeviceTarget(target));\r\n return real ?? targets[0];\r\n}\r\n\r\n/** 确保签名材料覆盖指定真机;覆盖记录缺失或过期时用 `--force` 重新生成。 */\r\nexport function ensureDeviceSignature({ projectRoot, harmonyProject, target, force = false, timeoutMs }: {\r\n projectRoot: string;\r\n harmonyProject: string;\r\n target?: string;\r\n force?: boolean;\r\n timeoutMs?: number;\r\n}) {\r\n const info = inspectHarmonyProject(harmonyProject);\r\n const resolvedTarget = target ?? process.env.DROID2HMOS_HDC_TARGET ?? (() => {\r\n const device = checkHarmonyDevice();\r\n return device.status === \"passed\" ? selectPreferredTarget(device.responsiveTargets) : null;\r\n })();\r\n if (!resolvedTarget) {\r\n return { status: \"failed\" as const, stage: \"target\", summary: \"未发现可响应的 HarmonyOS 设备,无法执行真机自动签名\", evidence: [\"hdc list targets\"] };\r\n }\r\n if (!isRealDeviceTarget(resolvedTarget)) {\r\n return { status: \"skipped\" as const, target: resolvedTarget, summary: `目标 ${resolvedTarget} 是模拟器,无需真机签名`, evidence: [resolvedTarget] };\r\n }\r\n // 真机可安装性:真机 API 低于 compatibleSdkVersion 时下调兼容版本(每次执行,幂等)。\r\n const installable = ensureDeviceInstallable(info.root, resolvedTarget);\r\n const udidResult = deviceUdid(resolvedTarget);\r\n if (udidResult.status === \"failed\") return { ...udidResult, stage: \"udid\", target: resolvedTarget, installable };\r\n const { udid } = udidResult;\r\n const materials = readSigningMaterialFingerprints(info.root);\r\n const marker = readMarker(projectRoot);\r\n const tracked = marker.devices[udid];\r\n // 签名 profile 与 bundleName 绑定:包名变更后即使材料文件未变也必须重签。\r\n if (!force && tracked && tracked.product === info.product && tracked.bundleName === (info.bundleName ?? null) && materialsMatch(tracked.materials ?? [], materials)) {\r\n return {\r\n status: \"passed\" as const,\r\n generated: false,\r\n target: resolvedTarget,\r\n udid,\r\n product: info.product,\r\n installable,\r\n summary: `真机 ${resolvedTarget} 的签名材料已是最新(${materials.length} 个材料文件)${installable.changed ? `;${installable.summary}` : \"\"}`,\r\n evidence: [udid, ...materials.map((item) => item.path)],\r\n };\r\n }\r\n\r\n const auth = checkDevEcoCliAuth(timeoutMs !== undefined ? { timeoutMs } : {});\r\n if (auth.status !== \"passed\") {\r\n return {\r\n status: \"failed\" as const,\r\n stage: \"auth\",\r\n target: resolvedTarget,\r\n udid,\r\n summary: `DevEco CLI 未登录,无法为真机 ${resolvedTarget} 自动签名。请先执行受管登录: droid2hmos auth login <android-project>`,\r\n evidence: [\"droid2hmos auth login <android-project>\"],\r\n };\r\n }\r\n const signature = generateHarmonySignatureWithDevEcoCli({\r\n harmonyProject,\r\n force: true,\r\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\r\n });\r\n if (signature.status !== \"passed\") {\r\n return { ...signature, status: \"failed\" as const, stage: \"generate\", target: resolvedTarget, udid };\r\n }\r\n const freshMaterials = readSigningMaterialFingerprints(info.root);\r\n marker.devices[udid] = { target: resolvedTarget, product: info.product, bundleName: info.bundleName ?? null, materials: freshMaterials, signedAt: new Date().toISOString() };\r\n writeMarker(projectRoot, marker);\r\n return {\r\n status: \"passed\" as const,\r\n generated: true,\r\n target: resolvedTarget,\r\n udid,\r\n product: info.product,\r\n installable,\r\n materials: freshMaterials,\r\n summary: `已为真机 ${resolvedTarget} 自动重新生成签名材料(含设备 ${udid.slice(0, 8)}…)${installable.changed ? `;${installable.summary}` : \"\"}`,\r\n evidence: [signature.evidence?.[0] ?? \"devecocli signature generate --force\", udid, ...freshMaterials.map((item) => item.path)],\r\n };\r\n}\r\n","import { existsSync, readdirSync, statSync } from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { inspectHarmonyProject } from \"./harmony-toolchain.ts\";\r\nimport { ensureOhosTestScaffold } from \"./init-hmos-project.ts\";\r\nimport { spawnCommand, spawnCommandSync } from \"./lib/spawn-command.ts\";\r\n\r\nexport const DEVECO_CLI_PACKAGE = \"@deveco/deveco-cli@latest\";\r\nexport const DEVECO_CLI_INSTALL_COMMAND = `npm install -g ${DEVECO_CLI_PACKAGE}`;\r\n\r\ntype Runner = typeof spawnCommandSync;\r\n\r\ninterface DevEcoCliOptions {\r\n executable?: string;\r\n runner?: Runner;\r\n timeoutMs?: number;\r\n}\r\n\r\nfunction executableName() {\r\n return process.env.DEVECO_CLI_BINARY || \"devecocli\";\r\n}\r\n\r\n/** 把 devecocli 调用解析为可直接 spawn 的命令(兼容 .mjs/.js 包装脚本)。 */\r\nexport function devEcoCliSpawn(executable: string, args: string[]) {\r\n const scriptWrapper = /\\.m?js$/i.test(executable);\r\n return scriptWrapper ? [process.execPath, executable, ...args] : [executable, ...args];\r\n}\r\n\r\nfunction runDevEcoCli(args: string[], { executable = executableName(), runner = spawnCommandSync, timeoutMs = 15000 }: DevEcoCliOptions = {}, cwd?: string) {\r\n const [command, ...commandArgs] = devEcoCliSpawn(executable, args);\r\n const result = runner(command, commandArgs, {\r\n cwd,\r\n encoding: \"utf8\",\r\n timeout: timeoutMs,\r\n windowsHide: true,\r\n env: { ...process.env, DEVECO_CLI_SKIP_VERSION_CHECK: \"1\" },\r\n });\r\n return {\r\n executable,\r\n args,\r\n status: !result.error && result.status === 0 ? \"passed\" : \"failed\",\r\n exitCode: Number.isInteger(result.status) ? result.status : null,\r\n stdout: String(result.stdout ?? \"\"),\r\n stderr: String(result.stderr ?? result.error?.message ?? \"\"),\r\n errorCode: result.error && \"code\" in result.error ? result.error.code : null,\r\n };\r\n}\r\n\r\nasync function runDevEcoCliAsync(args: string[], { executable = executableName(), timeoutMs = 15000 }: Omit<DevEcoCliOptions, \"runner\"> = {}, cwd?: string) {\r\n const [command, ...commandArgs] = devEcoCliSpawn(executable, args);\r\n const child = spawnCommand(command, commandArgs, {\r\n cwd,\r\n windowsHide: true,\r\n detached: process.platform !== \"win32\",\r\n env: { ...process.env, DEVECO_CLI_SKIP_VERSION_CHECK: \"1\" },\r\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\r\n });\r\n let stdout = \"\";\r\n let stderr = \"\";\r\n let errorCode: string | null = null;\r\n const childStdout = child.stdout;\r\n const childStderr = child.stderr;\r\n if (!childStdout || !childStderr) throw new Error(\"DevEco CLI output pipes are unavailable\");\r\n childStdout.setEncoding(\"utf8\");\r\n childStderr.setEncoding(\"utf8\");\r\n childStdout.on(\"data\", (chunk) => { stdout += chunk; });\r\n childStderr.on(\"data\", (chunk) => { stderr += chunk; });\r\n let timedOut = false;\r\n const timer = setTimeout(() => {\r\n timedOut = true;\r\n if (process.platform !== \"win32\" && child.pid) {\r\n try { process.kill(-child.pid, \"SIGKILL\"); } catch { child.kill(\"SIGKILL\"); }\r\n } else child.kill(\"SIGKILL\");\r\n }, Number(timeoutMs));\r\n const exitCode = await new Promise<number | null>((resolveExit) => {\r\n child.once(\"error\", (error: NodeJS.ErrnoException) => {\r\n errorCode = error.code ?? null;\r\n stderr ||= error.message;\r\n resolveExit(null);\r\n });\r\n child.once(\"close\", (code) => resolveExit(code));\r\n });\r\n clearTimeout(timer);\r\n return {\r\n executable,\r\n args,\r\n status: !timedOut && exitCode === 0 ? \"passed\" : \"failed\",\r\n exitCode,\r\n stdout,\r\n stderr,\r\n errorCode: timedOut ? \"ETIMEDOUT\" : errorCode,\r\n };\r\n}\r\n\r\nfunction parseJson(output: string, label: string) {\r\n try {\r\n return JSON.parse(output.trim());\r\n } catch (error) {\r\n throw new Error(`${label} returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`);\r\n }\r\n}\r\n\r\nexport function ensureDevEcoCli({ executable = executableName(), runner = spawnCommandSync, timeoutMs = 15000, npmCommand = process.platform === \"win32\" ? \"npm.cmd\" : \"npm\" }: DevEcoCliOptions & { npmCommand?: string } = {}) {\r\n const initial = runDevEcoCli([\"--version\"], { executable, runner, timeoutMs });\r\n if (initial.status === \"passed\") {\r\n return { status: \"passed\", version: initial.stdout.trim(), installed: false, summary: `DevEco CLI ${initial.stdout.trim()} is available`, evidence: [executable] };\r\n }\r\n if (initial.errorCode !== \"ENOENT\") {\r\n return { status: \"failed\", version: null, installed: false, summary: `DevEco CLI is not usable: ${initial.stderr || `exit ${initial.exitCode}`}`, evidence: [DEVECO_CLI_INSTALL_COMMAND] };\r\n }\r\n\r\n const installation = runner(npmCommand, [\"install\", \"--global\", DEVECO_CLI_PACKAGE], {\r\n encoding: \"utf8\",\r\n timeout: Math.max(timeoutMs, 5 * 60 * 1000),\r\n windowsHide: true,\r\n });\r\n if (installation.error || installation.status !== 0) {\r\n const reason = String(installation.stderr ?? installation.error?.message ?? `exit ${installation.status}`);\r\n return { status: \"failed\", version: null, installed: false, summary: `DevEco CLI global installation failed: ${reason.trim()}`, evidence: [DEVECO_CLI_INSTALL_COMMAND] };\r\n }\r\n const verified = runDevEcoCli([\"--version\"], { executable, runner, timeoutMs });\r\n if (verified.status !== \"passed\") {\r\n return { status: \"failed\", version: null, installed: true, summary: `DevEco CLI was installed but is not available on PATH: ${verified.stderr}`, evidence: [DEVECO_CLI_INSTALL_COMMAND] };\r\n }\r\n return { status: \"passed\", version: verified.stdout.trim(), installed: true, summary: `DevEco CLI ${verified.stdout.trim()} was installed globally`, evidence: [DEVECO_CLI_INSTALL_COMMAND, executable] };\r\n}\r\n\r\nexport function checkDevEcoCliAuth(cli: DevEcoCliOptions = {}) {\r\n const result = runDevEcoCli([\"auth\", \"status\"], cli);\r\n const output = [result.stdout, result.stderr].map((value) => value.trim()).filter(Boolean).join(\"\\n\");\r\n const loggedOut = /(?:^|\\n)Not logged in(?:\\n|$)/i.test(output);\r\n const currentUser = output.match(/(?:^|\\n)Current user:\\s*(.+?)(?:\\n|$)/i)?.[1]?.trim();\r\n if (result.status !== \"passed\" || loggedOut || !currentUser) {\r\n return {\r\n status: \"failed\",\r\n loggedIn: false,\r\n summary: \"DevEco CLI is not logged in. Run the managed login: droid2hmos auth login <android-project>\",\r\n evidence: [\"droid2hmos auth login <android-project>\", output].filter(Boolean),\r\n };\r\n }\r\n return {\r\n status: \"passed\",\r\n loggedIn: true,\r\n currentUser,\r\n summary: `Current user: ${currentUser}`,\r\n evidence: [`Current user: ${currentUser}`],\r\n };\r\n}\r\n\r\nexport function generateHarmonySignatureWithDevEcoCli({ harmonyProject, force = false, ...cli }: { harmonyProject: string; force?: boolean } & DevEcoCliOptions) {\r\n const info = inspectHarmonyProject(harmonyProject);\r\n const args = [\"signature\", \"generate\", \"--product\", info.product];\r\n if (force) args.push(\"--force\");\r\n const result = runDevEcoCli(args, { timeoutMs: 5 * 60 * 1000, ...cli }, info.root);\r\n if (result.status !== \"passed\") {\r\n return {\r\n ...result,\r\n status: \"failed\",\r\n summary: result.stderr.trim() || result.stdout.trim() || \"DevEco CLI automatic signature generation failed\",\r\n evidence: [\"droid2hmos auth login <android-project>\", `devecocli signature generate --product ${info.product}${force ? \" --force\" : \"\"}`],\r\n };\r\n }\r\n return {\r\n ...result,\r\n status: \"passed\",\r\n product: info.product,\r\n force,\r\n summary: force\r\n ? \"HarmonyOS signing materials regenerated with DevEco CLI (including connected devices)\"\r\n : \"HarmonyOS automatic signing information generated with DevEco CLI\",\r\n evidence: [`devecocli signature generate --product ${info.product}${force ? \" --force\" : \"\"}`],\r\n };\r\n}\r\n\r\n/** 列出 DevEco CLI 识别的鸿蒙设备/模拟器(`kind`: \"device\" | \"emulator\")。 */\r\nexport function listDevEcoDevices(cli: DevEcoCliOptions = {}) {\r\n const list = runDevEcoCli([\"device\", \"list\", \"--format\", \"json\"], cli);\r\n if (list.status !== \"passed\") {\r\n return { status: \"failed\" as const, devices: [], summary: list.stderr.trim() || \"DevEco CLI could not list devices\", evidence: [list] };\r\n }\r\n try {\r\n const payload = parseJson(list.stdout, \"devecocli device list\");\r\n const devices = Array.isArray(payload) ? payload : [];\r\n return { status: \"passed\" as const, devices, summary: `DevEco CLI listed ${devices.length} device(s)`, evidence: devices.map((device: any) => `${device?.name ?? \"device\"} (${device?.serial ?? \"?\"}) kind=${device?.kind ?? \"?\"}`) };\r\n } catch (error) {\r\n return { status: \"failed\" as const, devices: [], summary: error instanceof Error ? error.message : String(error), evidence: [list.stdout] };\r\n }\r\n}\r\n\r\nexport function ensureHarmonyProjectWithDevEcoCli({ projectRoot, harmonyProject, initialize = true, templatesRoot, ...cli }: {\r\n projectRoot: string;\r\n harmonyProject: string;\r\n initialize?: boolean;\r\n templatesRoot?: string;\r\n} & DevEcoCliOptions) {\r\n const profile = path.join(harmonyProject, \"build-profile.json5\");\r\n if (existsSync(profile)) {\r\n const existing = templatesRoot ? ensureOhosTestScaffold({ harmonyProject, templatesRoot }) : null;\r\n return { status: \"passed\", created: false, summary: \"Existing HarmonyOS project discovered by DevEco CLI convention\", evidence: [profile], ohosTest: existing };\r\n }\r\n if (existsSync(harmonyProject) && readdirSync(harmonyProject).length > 0) {\r\n return { status: \"failed\", created: false, summary: `HarmonyOS directory is not a valid project: ${harmonyProject}`, evidence: [harmonyProject] };\r\n }\r\n if (!initialize) return { status: \"failed\", created: false, summary: `HarmonyOS project not found: ${harmonyProject}`, evidence: [] };\r\n\r\n const rawName = path.basename(harmonyProject).replace(/[^A-Za-z0-9_]/g, \"_\");\r\n const appName = /^[A-Za-z]/.test(rawName) ? rawName : `Harmony_${rawName || \"App\"}`;\r\n const created = runDevEcoCli([\"create\", \"--project-path\", harmonyProject, \"--app-name\", appName], cli, projectRoot);\r\n if (created.status !== \"passed\" || !existsSync(profile)) {\r\n return { status: \"failed\", created: false, summary: created.stderr.trim() || created.stdout.trim() || \"DevEco CLI did not create a valid HarmonyOS project\", evidence: [created] };\r\n }\r\n // SDK 版本改写完全交给 devecocli 内部流程(按本机 API 级别),不做后处理;ohosTest 脚手架内置模板补齐。\r\n const ohosTest = templatesRoot ? ensureOhosTestScaffold({ harmonyProject, templatesRoot }) : null;\r\n return { status: \"passed\", created: true, summary: \"HarmonyOS project initialized with DevEco CLI\", evidence: [profile], command: created, ohosTest };\r\n}\r\n\r\nexport function checkHarmonySdkWithDevEcoCli({ harmonyProject, ...cli }: { harmonyProject: string } & DevEcoCliOptions) {\r\n const result = runDevEcoCli([\"check\", \"compat\", \"versions\", \"--format\", \"json\"], cli, harmonyProject);\r\n if (result.status !== \"passed\") return { status: \"not_applicable\", versions: [], summary: result.stderr.trim() || \"DevEco CLI could not enumerate HarmonyOS SDK versions\", evidence: [result] };\r\n try {\r\n const payload = parseJson(result.stdout, \"devecocli check compat versions\");\r\n const versions = Array.isArray(payload?.versions) ? payload.versions.filter((value) => typeof value === \"string\") : [];\r\n return versions.length\r\n ? { status: \"passed\", versions, summary: `DevEco CLI found ${versions.length} HarmonyOS SDK versions`, evidence: versions }\r\n : { status: \"not_applicable\", versions, summary: \"DevEco CLI found no HarmonyOS SDK versions\", evidence: [] };\r\n } catch (error) {\r\n return { status: \"not_applicable\", versions: [], summary: error instanceof Error ? error.message : String(error), evidence: [result.stdout] };\r\n }\r\n}\r\n\r\nfunction listFiles(root: string): string[] {\r\n if (!existsSync(root)) return [];\r\n return readdirSync(root, { withFileTypes: true }).flatMap((entry) => {\r\n const absolute = path.join(root, entry.name);\r\n return entry.isDirectory() ? listFiles(absolute) : [absolute];\r\n });\r\n}\r\n\r\nexport async function runHarmonyBuildWithDevEcoCli({ projectRoot, harmonyProject, timeoutMs, ...cli }: {\r\n projectRoot: string;\r\n harmonyProject: string;\r\n timeoutMs: number;\r\n} & DevEcoCliOptions) {\r\n const info = inspectHarmonyProject(harmonyProject);\r\n const startedAt = Date.now();\r\n const args = [\"build\", \"--product\", info.product, \"--modules\", `${info.module}@${info.appTarget}`, \"--build-mode\", \"debug\"];\r\n const result = await runDevEcoCliAsync(args, { executable: cli.executable, timeoutMs }, info.root);\r\n if (result.status !== \"passed\") return { ...result, key: \"harmonyBuild\", summary: result.stderr.trim() || result.stdout.trim() || \"DevEco CLI build failed\" };\r\n const artifact = listFiles(path.join(info.moduleRoot, \"build\"))\r\n .filter((file) => file.toLowerCase().endsWith(\".hap\"))\r\n .map((file) => ({ file, stat: statSync(file) }))\r\n .filter(({ stat }) => stat.size > 0)\r\n .sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs)[0];\r\n if (!artifact || artifact.stat.mtimeMs < startedAt - 2000) {\r\n return { ...result, status: \"failed\", key: \"harmonyBuild\", summary: \"DevEco CLI returned success, but this build did not produce a new HAP\", artifact: artifact?.file ?? null };\r\n }\r\n return { ...result, key: \"harmonyBuild\", summary: \"HarmonyOS HAP built with DevEco CLI\", artifact: artifact.file, artifactMtime: artifact.stat.mtime.toISOString(), evidence: [artifact.file] };\r\n}\r\n\r\nexport function checkHarmonyDeviceWithDevEcoCli(cli: DevEcoCliOptions = {}) {\r\n const list = runDevEcoCli([\"device\", \"list\", \"--format\", \"json\"], cli);\r\n if (list.status !== \"passed\") return { status: \"failed\", devices: [], responsiveDevices: [], summary: list.stderr.trim() || \"DevEco CLI could not list HarmonyOS devices\", evidence: [list] };\r\n let devices: any[];\r\n try {\r\n const payload = parseJson(list.stdout, \"devecocli device list\");\r\n devices = Array.isArray(payload) ? payload : [];\r\n } catch (error) {\r\n return { status: \"failed\", devices: [], responsiveDevices: [], summary: error instanceof Error ? error.message : String(error), evidence: [list.stdout] };\r\n }\r\n if (!devices.length) return { status: \"failed\", devices, responsiveDevices: [], summary: \"DevEco CLI found no HarmonyOS device or emulator\", evidence: [] };\r\n const probes = devices.map((device) => ({\r\n device,\r\n result: runDevEcoCli([\"device\", \"view\", \"--target\", String(device.serial || device.name), \"--format\", \"json\"], cli),\r\n }));\r\n const responsiveDevices = probes.filter(({ result }) => result.status === \"passed\").map(({ device, result }) => {\r\n try { return { ...device, ...parseJson(result.stdout, \"devecocli device view\") }; } catch { return device; }\r\n });\r\n if (!responsiveDevices.length) return { status: \"failed\", devices, responsiveDevices, summary: \"HarmonyOS devices were listed, but DevEco CLI could not query their Shell details\", evidence: probes };\r\n return {\r\n status: \"passed\",\r\n devices,\r\n responsiveDevices,\r\n summary: `DevEco CLI found ${responsiveDevices.length} responsive HarmonyOS device(s)`,\r\n evidence: responsiveDevices.map((device) => `${device.name || \"device\"} (${device.serial})${device.osVersion ? ` ${device.osVersion}` : \"\"}`),\r\n };\r\n}\r\n","import { existsSync, statSync } from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { checkHarmonyDevice } from \"./check-hmos-device.ts\";\r\nimport { runHarmonyBuild } from \"./harmony-toolchain.ts\";\r\nimport { runFiniteExecutable } from \"./run-config-command.ts\";\r\nimport { ensureDeviceSignature, selectPreferredTarget } from \"./device-signature.ts\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\n\r\nconst safeTestName = /^[A-Za-z0-9_./-]+$/;\r\n\r\nfunction executableWithArgs(executable: string, args: string[]) {\r\n return /\\.m?js$/i.test(executable)\r\n ? { executable: process.execPath, args: [executable, ...args] }\r\n : { executable, args };\r\n}\r\n\r\nfunction resolveFrom(root: string, value: string) {\r\n return path.isAbsolute(value) ? path.resolve(value) : path.resolve(root, value);\r\n}\r\n\r\nexport function validatePythonHypiumProject(project: string, testLists: string[]) {\r\n const errors: string[] = [];\r\n if (!existsSync(project) || !statSync(project).isDirectory()) {\r\n errors.push(`Python Hypium 工程目录不存在: ${project}`);\r\n return errors;\r\n }\r\n const testcases = path.join(project, \"testcases\");\r\n if (!existsSync(testcases) || !statSync(testcases).isDirectory()) errors.push(`Python Hypium 工程缺少 testcases 目录: ${testcases}`);\r\n for (const name of testLists) {\r\n if (!safeTestName.test(name) || name.split(/[\\\\/]/).includes(\"..\")) {\r\n errors.push(`Python Hypium 用例名不安全: ${name}`);\r\n continue;\r\n }\r\n const relative = name.endsWith(\".json\") ? name : `${name}.json`;\r\n const config = path.resolve(testcases, relative);\r\n const insideTestcases = path.relative(testcases, config);\r\n if (insideTestcases.startsWith(\"..\") || path.isAbsolute(insideTestcases)) errors.push(`Python Hypium 用例超出 testcases 目录: ${name}`);\r\n else if (!existsSync(config)) errors.push(`Python Hypium 用例配置不存在: ${config}`);\r\n }\r\n return errors;\r\n}\r\n\r\nexport function runHarmonyPythonHypiumTest({\r\n projectRoot,\r\n harmonyProject,\r\n hypiumProject,\r\n testLists,\r\n target: requestedTarget,\r\n reportPath,\r\n python = process.env.DROID2HMOS_PYTHON || (process.platform === \"win32\" ? \"python\" : \"python3\"),\r\n timeoutMs,\r\n}: {\r\n projectRoot: string;\r\n harmonyProject: string;\r\n hypiumProject: string;\r\n testLists: string[];\r\n target?: string;\r\n reportPath?: string;\r\n python?: string;\r\n timeoutMs: number;\r\n}) {\r\n const testProjectRoot = resolveFrom(projectRoot, hypiumProject);\r\n const validationErrors = validatePythonHypiumProject(testProjectRoot, testLists);\r\n if (validationErrors.length) {\r\n return { status: \"failed\", key: \"harmonyPythonTest\", stage: \"validate\", errors: validationErrors, summary: validationErrors.join(\"; \") };\r\n }\r\n\r\n const hdc = process.env.HDC_BINARY || \"hdc\";\r\n const device = checkHarmonyDevice({ hdc });\r\n if (device.status !== \"passed\") return { status: \"failed\", key: \"harmonyPythonTest\", stage: \"device\", device };\r\n const explicitTarget = requestedTarget || process.env.DROID2HMOS_HDC_TARGET || null;\r\n if (explicitTarget && !device.responsiveTargets.includes(explicitTarget)) {\r\n return {\r\n status: \"failed\", key: \"harmonyPythonTest\", stage: \"device\", device,\r\n summary: `目标设备 ${explicitTarget} 不可响应。可用目标: ${device.responsiveTargets.join(\", \")}`,\r\n };\r\n }\r\n const target = explicitTarget ?? selectPreferredTarget(device.responsiveTargets);\r\n if (!target) return { status: \"failed\", key: \"harmonyPythonTest\", stage: \"device\", device, summary: \"未找到可用 HarmonyOS 设备\" };\r\n\r\n let signature: any = { status: \"skipped\", summary: \"DROID2HMOS_SKIP_AUTO_SIGN=1\" };\r\n if (process.env.DROID2HMOS_SKIP_AUTO_SIGN !== \"1\") {\r\n signature = ensureDeviceSignature({ projectRoot, harmonyProject, target, timeoutMs: Math.min(timeoutMs, 5 * 60 * 1000) });\r\n if (signature.status === \"failed\") {\r\n return { status: \"failed\", key: \"harmonyPythonTest\", stage: \"device-signature\", device, target, signature, summary: `真机自动签名失败: ${signature.summary}` };\r\n }\r\n }\r\n\r\n const appBuild: any = runHarmonyBuild({ projectRoot, harmonyProject, timeoutMs });\r\n if (appBuild.status !== \"passed\") return { status: \"failed\", key: \"harmonyPythonTest\", stage: \"app-build\", appBuild, signature };\r\n\r\n const installInvocation = executableWithArgs(hdc, [\"-t\", target, \"install\", \"-r\", appBuild.artifact]);\r\n const installApp = runFiniteExecutable({\r\n ...installInvocation,\r\n key: \"harmonyPythonTest-install-app\",\r\n cwd: harmonyProject,\r\n projectRoot,\r\n timeoutMs,\r\n });\r\n if (installApp.status !== \"passed\") {\r\n return { status: \"failed\", key: \"harmonyPythonTest\", stage: \"install-app\", target, appBuild, installApp };\r\n }\r\n\r\n const reports = reportPath\r\n ? resolveFrom(testProjectRoot, reportPath)\r\n : path.join(migrationDirectory(projectRoot), \"hypium-python-reports\");\r\n const names = testLists.map((name) => name.replace(/\\.json$/i, \"\")).join(\";\");\r\n const pythonInvocation = executableWithArgs(python, [\"-m\", \"hypium\", \"run\", \"-l\", names, \"-sn\", target, \"-rp\", reports]);\r\n const execute = runFiniteExecutable({\r\n ...pythonInvocation,\r\n key: \"harmonyPythonTest-execute\",\r\n cwd: testProjectRoot,\r\n projectRoot,\r\n timeoutMs,\r\n });\r\n return {\r\n status: execute.status,\r\n key: \"harmonyPythonTest\",\r\n runner: \"python\",\r\n stage: \"execute\",\r\n target,\r\n appArtifact: appBuild.artifact,\r\n hypiumProject: testProjectRoot,\r\n testLists,\r\n reportPath: reports,\r\n signature,\r\n installApp,\r\n execute,\r\n summary: execute.status === \"passed\"\r\n ? \"HarmonyOS 应用构建、安装和 Python Hypium 测试执行成功\"\r\n : `Python Hypium 执行失败,请确认已为 ${python} 安装 hypium(python -m pip install hypium -U)`,\r\n };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport os from \"node:os\";\r\nimport { defaultHarmonyProjectPath } from \"./android-project-name.ts\";\r\nimport { migrationDirectory, ensureMigrationWorkspace } from \"../migration-paths.ts\";\r\n\r\ntype HarmonySdkSource = \"explicit\" | \"existing-config\" | \"local-properties\" | \"environment\" | \"standard-installation\";\r\n\r\ninterface DetectHarmonySdkOptions {\r\n project: string;\r\n sdkPath?: string;\r\n writeConfig?: boolean;\r\n env?: NodeJS.ProcessEnv;\r\n}\r\n\r\nexport function detectHarmonySdk({ project, sdkPath, writeConfig = false, env = process.env }: DetectHarmonySdkOptions) {\r\n const projectRoot = path.resolve(project);\r\n const configPath = path.join(migrationDirectory(projectRoot), \"config.json\");\r\n const config = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, \"utf8\")) : null;\r\n const candidates: Array<{ path: string; source: HarmonySdkSource }> = [];\r\n\r\n const push = (value: unknown, source: HarmonySdkSource) => {\r\n if (!value || typeof value !== \"string\") return;\r\n const absolute = path.resolve(value.replace(/\\\\:/g, \":\").replace(/\\\\\\\\/g, \"\\\\\"));\r\n if (!candidates.some((candidate) => candidate.path.toLowerCase() === absolute.toLowerCase())) {\r\n candidates.push({ path: absolute, source });\r\n }\r\n };\r\n\r\n push(sdkPath, \"explicit\");\r\n push(config?.harmonySdk?.path, \"existing-config\");\r\n\r\n const configuredHarmony = config?.harmonyProject ?? defaultHarmonyProjectPath(projectRoot);\r\n const harmonyRoot = path.isAbsolute(configuredHarmony)\r\n ? configuredHarmony\r\n : path.resolve(projectRoot, configuredHarmony);\r\n const localProperties = path.join(harmonyRoot, \"local.properties\");\r\n if (fs.existsSync(localProperties)) {\r\n const properties = parseProperties(fs.readFileSync(localProperties, \"utf8\"));\r\n push(properties[\"sdk.dir\"] ?? properties[\"harmony.sdk.dir\"] ?? properties[\"ohos.sdk.dir\"], \"local-properties\");\r\n }\r\n for (const name of [\"HARMONYOS_SDK_HOME\", \"OHOS_SDK_HOME\", \"DEVECO_SDK_HOME\"]) {\r\n push(env[name], \"environment\");\r\n }\r\n if (!sdkPath && process.platform === \"darwin\") {\r\n push(\"/Applications/DevEco-Studio.app/Contents/sdk\", \"standard-installation\");\r\n push(path.join(os.homedir(), \"Library\", \"Huawei\", \"Sdk\"), \"standard-installation\");\r\n } else if (!sdkPath && process.platform === \"win32\") {\r\n for (const drive of [\"C:\", \"D:\"]) push(path.join(`${drive}\\\\`, \"Program Files\", \"Huawei\", \"DevEco Studio\", \"sdk\"), \"standard-installation\");\r\n }\r\n\r\n let resolved: { path: string; source: HarmonySdkSource; declarationSample: string } | null = null;\r\n const rejected: Array<{ path: string; source: HarmonySdkSource; reason: string }> = [];\r\n for (const candidate of candidates) {\r\n const validation = validateSdk(candidate.path);\r\n if (validation.valid) {\r\n resolved = { path: validation.path, source: candidate.source, declarationSample: validation.sample };\r\n break;\r\n }\r\n rejected.push({ path: candidate.path, source: candidate.source, reason: validation.reason });\r\n }\r\n\r\n if (writeConfig && resolved) {\r\n if (!config) throw new Error(`Cannot write HarmonyOS SDK before migration config exists: ${configPath}`);\r\n ensureMigrationWorkspace(projectRoot);\r\n config.harmonySdk = { path: resolved.path, source: resolved.source };\r\n fs.mkdirSync(path.dirname(configPath), { recursive: true });\r\n fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\\n`, \"utf8\");\r\n }\r\n\r\n return {\r\n status: resolved ? \"passed\" : \"not_applicable\",\r\n configPath,\r\n harmonySdk: resolved,\r\n rejected,\r\n message: resolved\r\n ? \"HarmonyOS SDK declaration root verified\"\r\n : \"HarmonyOS SDK was not found; Harmony AppGraph will continue without SDK dependency enrichment\",\r\n };\r\n}\r\n\r\nfunction validateSdk(candidate: string): any {\r\n if (!fs.existsSync(candidate) || !fs.statSync(candidate).isDirectory()) {\r\n return { valid: false, path: candidate, reason: \"directory-not-found\" };\r\n }\r\n if (!hasSdkDescriptor(candidate)) {\r\n return { valid: false, path: candidate, reason: \"missing-sdk-descriptor\" };\r\n }\r\n const sample = findDeclaration(candidate, 7, 4000);\r\n return sample\r\n ? { valid: true, path: fs.realpathSync(candidate), sample }\r\n : { valid: false, path: candidate, reason: \"no-d-ts-or-d-ets-declarations\" };\r\n}\r\n\r\nfunction hasSdkDescriptor(root: string) {\r\n return [\r\n path.join(root, \"sdk-pkg.json\"),\r\n path.join(root, \"ets\", \"sdkConfig.json\"),\r\n path.join(root, \"ets\", \"oh-uni-package.json\"),\r\n path.join(root, \"ets\", \"uni-package.json\"),\r\n path.join(root, \"openharmony\", \"ets\", \"oh-uni-package.json\"),\r\n path.join(root, \"hms\", \"ets\", \"uni-package.json\"),\r\n path.join(root, \"default\", \"sdk-pkg.json\"),\r\n ].some((candidate) => fs.existsSync(candidate));\r\n}\r\n\r\nfunction findDeclaration(root: string, maxDepth: number, maxVisited: number) {\r\n const queue = [{ dir: root, depth: 0 }];\r\n let visited = 0;\r\n while (queue.length && visited < maxVisited) {\r\n const current = queue.shift();\r\n if (!current) break;\r\n let entries;\r\n try { entries = fs.readdirSync(current.dir, { withFileTypes: true }); } catch { continue; }\r\n for (const entry of entries) {\r\n if (++visited >= maxVisited) break;\r\n const full = path.join(current.dir, entry.name);\r\n if (entry.isFile() && /\\.d\\.(?:ts|ets)$/i.test(entry.name)) return full;\r\n if (entry.isDirectory() && current.depth < maxDepth && !new Set([\"build\", \".git\", \".hvigor\", \"node_modules\"]).has(entry.name)) {\r\n queue.push({ dir: full, depth: current.depth + 1 });\r\n }\r\n }\r\n }\r\n return null;\r\n}\r\n\r\nfunction parseProperties(text: string) {\r\n const out: Record<string, string> = {};\r\n for (const raw of text.split(/\\r?\\n/)) {\r\n const line = raw.trim();\r\n if (!line || line.startsWith(\"#\") || line.startsWith(\"!\")) continue;\r\n const separator = line.search(/(?<!\\\\)[=:]/);\r\n if (separator < 0) continue;\r\n out[line.slice(0, separator).trim()] = line.slice(separator + 1).trim();\r\n }\r\n return out;\r\n}\r\n","import { readFileSync } from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { spawnCommandSync } from \"./lib/spawn-command.ts\";\r\n\r\ninterface PackageMetadata {\r\n name?: string;\r\n version?: string;\r\n}\r\n\r\ninterface UpgradeOptions {\r\n packageRoot?: string;\r\n runner?: typeof spawnCommandSync;\r\n npmCommand?: string;\r\n}\r\n\r\nexport function readPackageMetadata(packageRoot?: string): PackageMetadata {\r\n if (!packageRoot) throw new Error(\"Cannot locate droid2hmos package metadata\");\r\n const packagePath = path.join(packageRoot, \"package.json\");\r\n const metadata = JSON.parse(readFileSync(packagePath, \"utf8\")) as PackageMetadata;\r\n if (!metadata.name || !metadata.version) throw new Error(`Invalid package metadata: ${packagePath}`);\r\n return metadata;\r\n}\r\n\r\nexport function upgradeCli({\r\n packageRoot,\r\n runner = spawnCommandSync,\r\n npmCommand = process.platform === \"win32\" ? \"npm.cmd\" : \"npm\",\r\n}: UpgradeOptions) {\r\n const metadata = readPackageMetadata(packageRoot);\r\n const target = `${metadata.name}@latest`;\r\n const result = runner(npmCommand, [\"install\", \"--global\", target], {\r\n stdio: \"inherit\",\r\n });\r\n\r\n if (result.error) throw new Error(`Failed to run ${npmCommand}: ${result.error.message}`);\r\n if (result.status !== 0) {\r\n const detail = result.signal ? ` (signal: ${result.signal})` : \"\";\r\n throw new Error(`Upgrade failed with exit code ${result.status ?? \"unknown\"}${detail}`);\r\n }\r\n\r\n return {\r\n status: \"passed\",\r\n package: metadata.name,\r\n previousVersion: metadata.version,\r\n target: \"latest\",\r\n };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { validateFiniteCommand } from \"./run-config-command.ts\";\r\nimport { defaultHarmonyProjectPath } from \"./android-project-name.ts\";\r\nimport { migrationDirectory, ensureMigrationWorkspace } from \"../migration-paths.ts\";\r\n\r\nexport interface MigrationConfigOptions {\r\n project: string;\r\n harmonyProject?: string;\r\n}\r\n\r\nconst atomicJson = (file: string, value: unknown) => {\r\n fs.mkdirSync(path.dirname(file), { recursive: true });\r\n const temporary = `${file}.${process.pid}.tmp`;\r\n fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\r\n fs.renameSync(temporary, file);\r\n};\r\n\r\n/**\r\n * Android 构建命令不再被迁移流程执行(Android 环境依赖已移除)。\r\n * 已有配置里的 androidBuild/androidTest 字段原样保留以兼容旧工作区,\r\n * 但 CLI 不再提供设置入口,也不再运行这些命令。\r\n */\r\nexport function defaultAndroidBuild(_projectRoot: string, _platform: NodeJS.Platform = process.platform): string | null {\r\n return null;\r\n}\r\n\r\nexport function normalizeAndroidBuildCommand(command: string | null, platform: NodeJS.Platform = process.platform) {\r\n if (typeof command !== \"string\") return command;\r\n if (platform === \"win32\") {\r\n return command.replace(/^(\\s*)(?:&\\s*)?[\"']?\\.\\/gradlew[\"']?(?=\\s|$)/i, \"$1.\\\\gradlew.bat\");\r\n }\r\n return command.replace(/^(\\s*)(?:&\\s*)?[\"']?(?:\\.\\\\gradlew(?:\\.bat)?|gradlew\\.bat)[\"']?(?=\\s|$)/i, \"$1./gradlew\");\r\n}\r\n\r\nfunction validateAndroidBuildPlatform(command: unknown, platform: NodeJS.Platform = process.platform) {\r\n if (typeof command !== \"string\") return null;\r\n if (platform === \"win32\" && /(?:^|\\s)\\.\\/gradlew(?:\\s|$)/i.test(command)) {\r\n return \"commands.androidBuild uses a Unix Gradle wrapper on Windows; use .\\\\gradlew.bat\";\r\n }\r\n if (platform !== \"win32\" && /(?:gradlew\\.bat|\\.\\\\gradlew)(?:\\s|$)/i.test(command)) {\r\n return `commands.androidBuild uses a Windows Gradle wrapper on ${platform}; use ./gradlew`;\r\n }\r\n return null;\r\n}\r\n\r\nexport function validateMigrationConfigValue(config: any, projectRoot: string) {\r\n const errors: string[] = [];\r\n if (!config || typeof config !== \"object\" || Array.isArray(config)) errors.push(\"config must be an object\");\r\n if (!config?.androidProject || typeof config.androidProject !== \"string\") errors.push(\"androidProject is required\");\r\n if (!config?.harmonyProject || typeof config.harmonyProject !== \"string\") errors.push(\"harmonyProject is required\");\r\n if (!config?.commands || typeof config.commands !== \"object\") errors.push(\"commands is required\");\r\n for (const key of [\"androidBuild\", \"androidTest\", \"harmonyStatic\"]) {\r\n if (!(key in (config?.commands ?? {}))) errors.push(`commands.${key} is required`);\r\n else if (config.commands[key] !== null && typeof config.commands[key] !== \"string\") errors.push(`commands.${key} must be a string or null`);\r\n else if (typeof config.commands[key] === \"string\") for (const error of validateFiniteCommand(config.commands[key])) errors.push(`commands.${key}: ${error}`);\r\n }\r\n const androidBuildPlatformError = validateAndroidBuildPlatform(config?.commands?.androidBuild);\r\n if (androidBuildPlatformError) errors.push(androidBuildPlatformError);\r\n const androidRoot = config?.androidProject\r\n ? ((() => { if (path.isAbsolute(config.androidProject)) return config.androidProject; return path.resolve(projectRoot, config.androidProject); })())\r\n : null;\r\n const harmonyRoot = config?.harmonyProject\r\n ? ((() => { if (path.isAbsolute(config.harmonyProject)) return config.harmonyProject; return path.resolve(projectRoot, config.harmonyProject); })())\r\n : null;\r\n if (androidRoot && (!fs.existsSync(androidRoot) || !fs.statSync(androidRoot).isDirectory())) errors.push(`androidProject directory not found: ${androidRoot}`);\r\n return { valid: errors.length === 0, errors, projectRoot, androidRoot, harmonyRoot };\r\n}\r\n\r\nexport function initMigrationConfig(options: MigrationConfigOptions) {\r\n const projectRoot = path.resolve(options.project);\r\n if (!fs.existsSync(projectRoot) || !fs.statSync(projectRoot).isDirectory()) throw new Error(`Android project directory not found: ${projectRoot}`);\r\n ensureMigrationWorkspace(projectRoot);\r\n const configPath = path.join(migrationDirectory(projectRoot), \"config.json\");\r\n const created = !fs.existsSync(configPath);\r\n const existing = created ? {} : JSON.parse(fs.readFileSync(configPath, \"utf8\"));\r\n const config = {\r\n ...existing,\r\n configVersion: existing.configVersion ?? \"1.0.0\",\r\n androidProject: existing.androidProject ?? projectRoot,\r\n harmonyProject: options.harmonyProject ?? existing.harmonyProject ?? path.relative(projectRoot, defaultHarmonyProjectPath(projectRoot)),\r\n ...(existing.harmonySdk ? { harmonySdk: existing.harmonySdk } : {}),\r\n commands: {\r\n ...(existing.commands ?? {}),\r\n androidBuild: normalizeAndroidBuildCommand(existing.commands?.androidBuild ?? null),\r\n androidTest: existing.commands?.androidTest ?? null,\r\n harmonyStatic: existing.commands?.harmonyStatic ?? null,\r\n },\r\n };\r\n const validation = validateMigrationConfigValue(config, projectRoot);\r\n if (!validation.valid) throw new Error(`Invalid migration config: ${validation.errors.join(\"; \")}`);\r\n atomicJson(configPath, config);\r\n return { status: \"passed\", created, configPath, config, validation };\r\n}\r\n\r\nexport function validateMigrationConfig(project: string) {\r\n const projectRoot = path.resolve(project);\r\n const configPath = path.join(migrationDirectory(projectRoot), \"config.json\");\r\n if (!fs.existsSync(configPath)) return { status: \"failed\", valid: false, configPath, errors: [\"migration config not found\"] };\r\n try {\r\n const config = JSON.parse(fs.readFileSync(configPath, \"utf8\"));\r\n const validation = validateMigrationConfigValue(config, projectRoot);\r\n return { status: validation.valid ? \"passed\" : \"failed\", configPath, ...validation };\r\n } catch (error) {\r\n return { status: \"failed\", valid: false, configPath, errors: [error instanceof Error ? error.message : String(error)] };\r\n }\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { detectAndroidUiStack } from \"./detect-android-ui-stack.ts\";\r\nimport { initMigrationConfig, validateMigrationConfig } from \"./migration-config.ts\";\r\nimport { gitWorkspaceStatus } from \"./git-checkpoint.ts\";\r\nimport { checkAppGraphHealth, checkToolchain } from \"./system-checks.ts\";\r\nimport { loadPreflightChecklist, PREFLIGHT_CHECKS, type PreflightCheckId } from \"./preflight-checklist.ts\";\r\nimport { defaultHarmonyProjectPath } from \"./android-project-name.ts\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\nimport {\r\n checkDevEcoCliAuth,\r\n checkHarmonyDeviceWithDevEcoCli,\r\n checkHarmonySdkWithDevEcoCli,\r\n ensureDevEcoCli,\r\n ensureHarmonyProjectWithDevEcoCli,\r\n runHarmonyBuildWithDevEcoCli,\r\n} from \"./deveco-cli.ts\";\r\nimport { signNewHarmonyProject } from \"./device-signature.ts\";\r\n\r\nconst atomicJson = (file: string, value: unknown) => {\r\n fs.mkdirSync(path.dirname(file), { recursive: true });\r\n const temporary = `${file}.${process.pid}.tmp`;\r\n fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\r\n fs.renameSync(temporary, file);\r\n};\r\n\r\nfunction check(id: string, result: any, required = true) {\r\n const raw = result?.status ?? (result?.valid ? \"passed\" : \"failed\");\r\n const status = raw === \"passed\" || raw === \"skipped\" || raw === \"not_applicable\" || raw === \"blocked_external\" ? raw : \"failed\";\r\n const entry: any = { id, status, required, summary: result?.summary ?? result?.message ?? `${id}: ${status}`, evidence: result?.evidence ?? [], details: result };\r\n if (result?.retry) entry.retry = result.retry;\r\n return entry;\r\n}\r\n\r\ninterface PreflightOptions {\r\n project: string;\r\n templatesRoot: string;\r\n checklistPath: string;\r\n sdkPath?: string;\r\n timeoutMs?: number;\r\n initializeHarmony?: boolean;\r\n progress?: boolean;\r\n progressOutput?: NodeJS.WritableStream;\r\n progressIntervalMs?: number;\r\n}\r\n\r\nexport async function runPreflight(options: PreflightOptions) {\r\n const projectRoot = path.resolve(options.project);\r\n if (!fs.existsSync(projectRoot) || !fs.statSync(projectRoot).isDirectory()) throw new Error(`Android project directory not found: ${projectRoot}`);\r\n const timeoutMs = options.timeoutMs ?? 30 * 60 * 1000;\r\n const checks: any[] = [];\r\n const progressOutput = options.progressOutput ?? process.stderr;\r\n const showProgress = options.progress !== false;\r\n const progressIntervalMs = options.progressIntervalMs ?? 10_000;\r\n const checklist = loadPreflightChecklist(options.checklistPath);\r\n const required = (id: PreflightCheckId) => PREFLIGHT_CHECKS.find((item) => item.id === id)!.required;\r\n const enabled = (id: PreflightCheckId) => checklist.isEnabled(id);\r\n const skip = (id: PreflightCheckId) => checks.push(check(id, { status: \"skipped\", summary: \"Skipped by preflight checklist\", evidence: [checklist.checklistPath] }, required(id)));\r\n // 环境类门禁只探测一次:失败时标记为 external 并给出用户可执行的修复指引,\r\n // 避免 Agent 原样重跑 preflight(环境不变化时不会自愈)。\r\n const environmentRemediation: Partial<Record<PreflightCheckId, string>> = {\r\n toolchain: \"主机工具链不完整。请安装/配置缺失组件(git、Node.js 20-24、npm、Python 3.10+、JDK、DevEco 工具链),然后重新运行 droid2hmos preflight。\",\r\n appgraph: \"appgraph CLI 不可用或不兼容。请先执行 npm install -g @harmonyos-arkts/appgraph@latest --force,然后重新运行 droid2hmos preflight。\",\r\n \"harmony-sdk\": \"未发现可用的 HarmonyOS SDK。请在 DevEco Studio 中安装 SDK,然后重新运行 droid2hmos preflight。\",\r\n \"harmony-device\": \"未发现可响应的 HarmonyOS 设备/模拟器。请连接并授权真机或启动模拟器,确保 DevEco CLI 可发现且 shell 可响应,然后重新运行 droid2hmos preflight。\",\r\n };\r\n const markEnvironmentFailure = (id: PreflightCheckId, result: any) => {\r\n const remediation = environmentRemediation[id];\r\n const failed = result?.status !== \"passed\" && result?.status !== \"skipped\" && result?.status !== \"not_applicable\";\r\n return failed && remediation ? { ...result, retry: { kind: \"external\", retry: \"after-environment-change\", remediation } } : result;\r\n };\r\n const displayGate = (id: string) => {\r\n if (showProgress) progressOutput.write(`[preflight] 当前门禁: ${id}\\n`);\r\n };\r\n const displayBuildProgress = async <T>(id: string, action: () => Promise<T>) => {\r\n displayGate(id);\r\n const startedAt = Date.now();\r\n const writeProgress = () => {\r\n if (showProgress) progressOutput.write(`[preflight] 构建进度: ${id} 已运行 ${Math.floor((Date.now() - startedAt) / 1000)}s\\n`);\r\n };\r\n writeProgress();\r\n const timer = setInterval(writeProgress, progressIntervalMs);\r\n try {\r\n return await action();\r\n } finally {\r\n clearInterval(timer);\r\n }\r\n };\r\n let git: any = {};\r\n let harmonyProject = defaultHarmonyProjectPath(projectRoot);\r\n let existingConfig: any = null;\r\n try {\r\n existingConfig = JSON.parse(fs.readFileSync(path.join(migrationDirectory(projectRoot), \"config.json\"), \"utf8\"));\r\n const configuredHarmony = existingConfig.harmonyProject ?? defaultHarmonyProjectPath(projectRoot);\r\n harmonyProject = path.isAbsolute(configuredHarmony) ? configuredHarmony : path.resolve(projectRoot, configuredHarmony);\r\n } catch {\r\n // The first run has no config yet; use the sibling HarmonyOS project path.\r\n }\r\n const relativeHarmony = path.relative(projectRoot, harmonyProject).replaceAll(\"\\\\\", \"/\");\r\n const ignoreUntrackedRoots = existingConfig && relativeHarmony && !relativeHarmony.startsWith(\"../\") ? [relativeHarmony] : [];\r\n git = gitWorkspaceStatus(projectRoot, { ignoreUntrackedRoots });\r\n const hasRequiredFailures = () => checks.some((item) => item.required && item.status !== \"passed\" && item.status !== \"skipped\");\r\n const finish = () => {\r\n const requiredFailures = checks.filter((item) => item.required && item.status !== \"passed\" && item.status !== \"skipped\");\r\n const result = requiredFailures.length ? \"failed\" : \"passed\";\r\n const report = {\r\n createdAt: new Date().toISOString(), configRef: \".migration/config.json\", checklistRef: checklist.checklistPath, projectRoot, harmonyProject,\r\n gitHead: git.head ?? \"unknown\", result,\r\n checks: checks.map(({ id, status, summary, evidence, retry }) => retry ? { id, status, summary, evidence, retry } : { id, status, summary, evidence }),\r\n };\r\n const reportPath = path.join(migrationDirectory(projectRoot), \"preflight-report.json\");\r\n atomicJson(reportPath, report);\r\n if (showProgress) progressOutput.write(`[preflight] 完成: ${result}(共 ${checks.length} 项检查,必需失败 ${requiredFailures.length} 项),报告: ${reportPath}\\n`);\r\n return { status: result, reportPath, checks, failedChecks: requiredFailures.map((item) => item.id) };\r\n };\r\n\r\n if (enabled(\"android-ui-stack\")) {\r\n displayGate(\"android-ui-stack\");\r\n const stack = detectAndroidUiStack(projectRoot);\r\n checks.push(check(\"android-ui-stack\", { status: stack.supported ? \"passed\" : \"failed\", summary: stack.policy, evidence: [...stack.evidence.kotlin, ...stack.evidence.layoutXml, ...stack.evidence.compose], ...stack }));\r\n } else skip(\"android-ui-stack\");\r\n if (enabled(\"git\")) {\r\n displayGate(\"git\");\r\n checks.push(check(\"git\", { ...git, status: git.status === \"passed\" && git.clean ? \"passed\" : \"failed\", summary: git.repository ? ((() => { if (git.clean) return `Git ${git.branch ?? \"detached\"} ${git.head}`; return `Git worktree has ${git.changes?.length ?? 0} relevant changes`; })()) : \"Not a Git repository\", evidence: [git.head, ...(git.changes ?? [])].filter(Boolean) }));\r\n } else skip(\"git\");\r\n if (enabled(\"toolchain\")) {\r\n displayGate(\"toolchain\");\r\n const toolchain = checkToolchain(projectRoot);\r\n const devecoCli = ensureDevEcoCli({ timeoutMs });\r\n toolchain.checks.push({ id: \"devecocli\", ...devecoCli });\r\n if (devecoCli.status !== \"passed\") toolchain.status = \"failed\";\r\n checks.push(check(\"toolchain\", markEnvironmentFailure(\"toolchain\", { ...toolchain, summary: toolchain.status === \"passed\" ? \"Required host toolchain is available\" : \"Host toolchain is incomplete\", evidence: toolchain.checks.map((item) => `${item.id}: ${item.summary}`) })));\r\n } else skip(\"toolchain\");\r\n if (enabled(\"devecocli-auth\")) {\r\n displayGate(\"devecocli-auth\");\r\n const auth: any = checkDevEcoCliAuth({ timeoutMs });\r\n if (auth.status !== \"passed\") {\r\n // 外部账号依赖:需要用户在浏览器完成华为开发者账号授权,不会因重跑 Preflight 自愈;\r\n // remediation 指向受管登录命令,避免 Agent 用短命进程反复尝试交互式登录\r\n // (残留的本地回调服务器进程消亡后,浏览器登录页会重定向到已死端口)。\r\n auth.retry = {\r\n kind: \"external\",\r\n remediation: `droid2hmos auth login ${projectRoot}`,\r\n reason: \"DevEco CLI 登录需要用户在浏览器完成华为开发者账号授权;请执行受管登录命令,不要直接运行 devecocli auth login 或并发发起多次登录\",\r\n };\r\n if (showProgress) progressOutput.write(`[preflight] DevEco CLI 未登录,请执行受管登录: droid2hmos auth login ${projectRoot}\\n`);\r\n }\r\n checks.push(check(\"devecocli-auth\", auth, required(\"devecocli-auth\")));\r\n } else skip(\"devecocli-auth\");\r\n if (enabled(\"appgraph\")) {\r\n displayGate(\"appgraph\");\r\n checks.push(check(\"appgraph\", markEnvironmentFailure(\"appgraph\", checkAppGraphHealth())));\r\n } else skip(\"appgraph\");\r\n if (hasRequiredFailures()) return finish();\r\n\r\n let configInit: any;\r\n if (enabled(\"config\")) displayGate(\"config\");\r\n try {\r\n const existingConfigPath = path.join(migrationDirectory(projectRoot), \"config.json\");\r\n configInit = !enabled(\"config\") && fs.existsSync(existingConfigPath)\r\n ? { configPath: existingConfigPath, config: JSON.parse(fs.readFileSync(existingConfigPath, \"utf8\")) }\r\n : initMigrationConfig({ project: projectRoot });\r\n } catch (error) {\r\n checks.push(check(\"config\", { status: \"failed\", summary: error instanceof Error ? error.message : String(error) }));\r\n return finish();\r\n }\r\n const configPath = configInit.configPath;\r\n const config = configInit.config;\r\n const configuredHarmonyProject = typeof config.harmonyProject === \"string\" ? config.harmonyProject : path.relative(projectRoot, defaultHarmonyProjectPath(projectRoot));\r\n harmonyProject = path.isAbsolute(configuredHarmonyProject) ? configuredHarmonyProject : path.resolve(projectRoot, configuredHarmonyProject);\r\n if (enabled(\"config\")) checks.push(check(\"config\", { ...validateMigrationConfig(projectRoot), summary: \"Migration config initialized and validated\", evidence: [configPath] }));\r\n else skip(\"config\");\r\n if (hasRequiredFailures()) return finish();\r\n\r\n // Android 环境依赖已移除:不再执行 androidBuild 受管命令,也不再探测 adb/模拟器。\r\n // 检查项保留 not_applicable 以兼容既有 checklist 与 preflight 报告结构。\r\n if (!enabled(\"android-build\")) skip(\"android-build\");\r\n else {\r\n displayGate(\"android-build\");\r\n checks.push(check(\"android-build\", {\r\n status: \"not_applicable\",\r\n summary: \"Android 构建能力已移除(迁移流程不依赖 Android 编译环境);双端对照以源码与静态 facts 为基准\",\r\n }, required(\"android-build\")));\r\n }\r\n if (!enabled(\"android-emulator\")) skip(\"android-emulator\");\r\n else {\r\n displayGate(\"android-emulator\");\r\n checks.push(check(\"android-emulator\", {\r\n status: \"not_applicable\",\r\n summary: \"Android 模拟器检测已移除(迁移流程不依赖 Android 运行环境)\",\r\n }, required(\"android-emulator\")));\r\n }\r\n if (hasRequiredFailures()) return finish();\r\n\r\n if (enabled(\"harmony-project\")) {\r\n displayGate(\"harmony-project\");\r\n const ensured = ensureHarmonyProjectWithDevEcoCli({ projectRoot, harmonyProject, initialize: options.initializeHarmony !== false, templatesRoot: options.templatesRoot, timeoutMs });\r\n if (ensured.status === \"passed\" && ensured.created) {\r\n const signature = signNewHarmonyProject({ projectRoot, harmonyProject, timeoutMs: Math.min(timeoutMs, 5 * 60 * 1000) });\r\n // 签名失败不阻塞:工程本身已创建成功,仅提示手动签名,\r\n // 不使 harmony-project 门禁失败。\r\n checks.push(check(\"harmony-project\", signature.status === \"passed\"\r\n ? { ...ensured, signature, summary: \"HarmonyOS project initialized and signed for connected real devices with DevEco CLI\", evidence: [...ensured.evidence, ...(signature.evidence ?? [])] }\r\n : {\r\n ...ensured,\r\n signature,\r\n status: \"passed\",\r\n summary: `HarmonyOS project 已创建;真机自动签名失败(${signature.summary})。请在 DevEco Studio 中手动签名(File > Project Structure > Signing Configs 勾选 Automatically generate signature),或登录后运行 droid2hmos sign <project> 重试`,\r\n evidence: [...ensured.evidence, ...(signature.evidence ?? [])],\r\n }));\r\n } else {\r\n checks.push(check(\"harmony-project\", ensured));\r\n }\r\n } else skip(\"harmony-project\");\r\n if (hasRequiredFailures()) return finish();\r\n\r\n if (enabled(\"harmony-sdk\")) {\r\n displayGate(\"harmony-sdk\");\r\n checks.push(check(\"harmony-sdk\", markEnvironmentFailure(\"harmony-sdk\", checkHarmonySdkWithDevEcoCli({ harmonyProject, timeoutMs })), false));\r\n } else skip(\"harmony-sdk\");\r\n if (enabled(\"harmony-build\")) {\r\n try {\r\n const harmonyBuild = await displayBuildProgress(\"harmony-build\", () => runHarmonyBuildWithDevEcoCli({ projectRoot, harmonyProject, timeoutMs }));\r\n checks.push(check(\"harmony-build\", harmonyBuild));\r\n } catch (error) {\r\n checks.push(check(\"harmony-build\", { status: \"failed\", summary: error instanceof Error ? error.message : String(error) }));\r\n }\r\n } else skip(\"harmony-build\");\r\n if (enabled(\"harmony-device\")) {\r\n displayGate(\"harmony-device\");\r\n checks.push(check(\"harmony-device\", markEnvironmentFailure(\"harmony-device\", checkHarmonyDeviceWithDevEcoCli({ timeoutMs }))));\r\n } else skip(\"harmony-device\");\r\n return finish();\r\n}\r\n","#!/usr/bin/env node\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\n\r\nfunction walk(root, accept, results = []) {\r\n if (!fs.existsSync(root)) return results;\r\n for (const entry of fs.readdirSync(root, { withFileTypes: true })) {\r\n const absolute = path.join(root, entry.name);\r\n if (entry.isDirectory()) walk(absolute, accept, results);\r\n else if (accept(absolute)) results.push(absolute);\r\n }\r\n return results;\r\n}\r\n\r\nfunction relative(root, files) {\r\n return files.map((file) => path.relative(root, file).replaceAll(\"\\\\\", \"/\")).sort();\r\n}\r\n\r\nexport function detectAndroidUiStack(projectRoot) {\r\n const root = path.resolve(projectRoot);\r\n const sourceRoots = walk(root, (file) => /[\\\\/]src[\\\\/](main|\\w+Main)[\\\\/].+\\.(kt|java)$/i.test(file));\r\n const kotlinFiles = sourceRoots.filter((file) => file.endsWith(\".kt\"));\r\n const javaFiles = sourceRoots.filter((file) => file.endsWith(\".java\"));\r\n const layoutFiles = walk(root, (file) => /[\\\\/]src[\\\\/](main|\\w+Main)[\\\\/]res[\\\\/]layout[^\\\\/]*[\\\\/].+\\.xml$/i.test(file));\r\n\r\n const composeEvidence = [];\r\n for (const file of kotlinFiles) {\r\n const text = fs.readFileSync(file, \"utf8\");\r\n if (/@Composable\\b|\\bsetContent\\s*\\{|androidx\\.compose\\.|\\bComposeView\\b/.test(text)) {\r\n composeEvidence.push(path.relative(root, file).replaceAll(\"\\\\\", \"/\"));\r\n }\r\n }\r\n const gradleFiles = walk(root, (file) => /(?:build\\.gradle(?:\\.kts)?|libs\\.versions\\.toml)$/i.test(file));\r\n for (const file of gradleFiles) {\r\n const text = fs.readFileSync(file, \"utf8\");\r\n if (/buildFeatures\\s*\\{[\\s\\S]{0,500}?compose\\s*(?:=\\s*)?true|androidx[.-]compose|composeOptions\\s*\\{/i.test(text)) {\r\n composeEvidence.push(path.relative(root, file).replaceAll(\"\\\\\", \"/\"));\r\n }\r\n }\r\n\r\n const uniqueComposeEvidence = [...new Set(composeEvidence)].sort();\r\n const hasKotlin = kotlinFiles.length > 0;\r\n const hasJava = javaFiles.length > 0;\r\n const hasXml = layoutFiles.length > 0;\r\n const hasCompose = uniqueComposeEvidence.length > 0;\r\n const reasons = [];\r\n if (!hasKotlin && !hasJava) reasons.push(\"未发现生产 Kotlin 或 Java 源码\");\r\n if (!hasXml && !hasCompose) reasons.push(\"未发现 Android XML View 或 Jetpack Compose UI 证据\");\r\n if (hasCompose && !hasKotlin) reasons.push(\"发现 Compose 配置,但未发现承载 Compose UI 的 Kotlin 源码\");\r\n const supported = reasons.length === 0;\r\n let stack = \"unsupported\";\r\n if (supported && hasCompose) stack = hasXml ? \"android-kotlin-mixed\" : \"android-kotlin-compose\";\r\n else if (supported && hasKotlin && hasJava) stack = \"android-jvm-xml\";\r\n else if (supported && hasKotlin) stack = \"android-kotlin-xml\";\r\n else if (supported) stack = \"android-java-xml\";\r\n\r\n return {\r\n supported,\r\n stack,\r\n policy: \"支持 Java/Kotlin + XML View、Kotlin + Jetpack Compose 及 XML/Compose 混合工程;无法识别 UI 来源的工程暂不支持。\",\r\n counts: {\r\n kotlin: kotlinFiles.length,\r\n java: javaFiles.length,\r\n layoutXml: layoutFiles.length,\r\n composeEvidence: uniqueComposeEvidence.length\r\n },\r\n evidence: {\r\n kotlin: relative(root, kotlinFiles).slice(0, 20),\r\n layoutXml: relative(root, layoutFiles).slice(0, 20),\r\n compose: uniqueComposeEvidence.slice(0, 20)\r\n },\r\n reasons\r\n };\r\n}\r\n","import path from \"node:path\";\r\nimport fs from \"node:fs\";\r\nimport { createHash } from \"node:crypto\";\r\nimport { spawnSync } from \"node:child_process\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\n\r\nfunction git(projectRoot: string, args: string[]) {\r\n const result = spawnSync(\"git\", [\"-C\", projectRoot, ...args], { encoding: \"utf8\", shell: false, timeout: 30000, windowsHide: true });\r\n return {\r\n ok: !result.error && result.status === 0,\r\n exitCode: Number.isInteger(result.status) ? result.status : null,\r\n stdout: String(result.stdout ?? \"\").trim(),\r\n stderr: String(result.stderr ?? result.error?.message ?? \"\").trim(),\r\n };\r\n}\r\n\r\nfunction normalized(value: string) {\r\n return value.replaceAll(\"\\\\\", \"/\");\r\n}\r\n\r\nfunction inside(root: string, absolute: string) {\r\n const relative = path.relative(root, absolute);\r\n return relative === \"\" || (relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\r\n}\r\n\r\nfunction repositoryRoot(directory: string) {\r\n const result = git(directory, [\"rev-parse\", \"--show-toplevel\"]);\r\n return result.ok && result.stdout ? path.resolve(result.stdout) : null;\r\n}\r\n\r\nfunction stagedFiles(root: string) {\r\n const result = git(root, [\"diff\", \"--cached\", \"--name-only\"]);\r\n if (!result.ok) throw new Error(result.stderr || `Cannot inspect staged files in ${root}`);\r\n return result.stdout.split(/\\r?\\n/).filter(Boolean);\r\n}\r\n\r\nfunction unstage(root: string, files: string[]) {\r\n if (!files.length) return;\r\n const head = git(root, [\"rev-parse\", \"--verify\", \"HEAD\"]);\r\n if (head.ok) git(root, [\"restore\", \"--staged\", \"--\", ...files]);\r\n else git(root, [\"rm\", \"--cached\", \"-r\", \"--ignore-unmatch\", \"--\", ...files]);\r\n}\r\n\r\nfunction initializeHarmonyRepository(androidRoot: string, harmonyRoot: string) {\r\n const existing = repositoryRoot(harmonyRoot);\r\n if (existing) return { root: existing, initialized: false };\r\n const androidBranch = git(androidRoot, [\"branch\", \"--show-current\"]).stdout || \"main\";\r\n const initialized = git(harmonyRoot, [\"init\", \"-b\", androidBranch]);\r\n if (!initialized.ok) throw new Error(initialized.stderr || `Cannot initialize HarmonyOS Git repository: ${harmonyRoot}`);\r\n for (const key of [\"user.name\", \"user.email\"]) {\r\n const value = git(androidRoot, [\"config\", \"--get\", key]);\r\n if (value.ok && value.stdout) git(harmonyRoot, [\"config\", key, value.stdout]);\r\n }\r\n return { root: path.resolve(harmonyRoot), initialized: true };\r\n}\r\n\r\nfunction relevantStatus(status: string, ignoreUntrackedRoots: string[] = []) {\r\n const ignored = ignoreUntrackedRoots.map((value) => value.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\//, \"\").replace(/\\/$/, \"\"));\r\n return status.split(/\\r?\\n/).filter(Boolean).filter((line) => {\r\n const file = line.slice(3).replaceAll(\"\\\\\", \"/\");\r\n if (file === \".migration\" || file.startsWith(\".migration/\")) return false;\r\n if (line.startsWith(\"?? \") && ignored.some((root) => file === root || file.startsWith(`${root}/`))) return false;\r\n return true;\r\n });\r\n}\r\n\r\nexport function gitWorkspaceStatus(project: string, options: { ignoreUntrackedRoots?: string[] } = {}) {\r\n const projectRoot = path.resolve(project);\r\n const inside = git(projectRoot, [\"rev-parse\", \"--is-inside-work-tree\"]);\r\n if (!inside.ok || inside.stdout !== \"true\") return { status: \"failed\", repository: false, projectRoot, errors: [inside.stderr || \"not a Git worktree\"] };\r\n const head = git(projectRoot, [\"rev-parse\", \"HEAD\"]);\r\n const branch = git(projectRoot, [\"branch\", \"--show-current\"]);\r\n const porcelain = git(projectRoot, [\"status\", \"--porcelain=v1\", \"--untracked-files=all\"]);\r\n const changes = porcelain.ok ? relevantStatus(porcelain.stdout, options.ignoreUntrackedRoots) : [];\r\n return {\r\n status: head.ok && porcelain.ok ? \"passed\" : \"failed\",\r\n repository: true,\r\n projectRoot,\r\n branch: branch.stdout || null,\r\n head: head.stdout || null,\r\n clean: changes.length === 0,\r\n changes,\r\n errors: [head, porcelain].filter((item) => !item.ok).map((item) => item.stderr),\r\n };\r\n}\r\n\r\nexport function createGitCheckpoint(options: {\r\n project: string;\r\n harmonyProject?: string;\r\n message: string;\r\n include: string[];\r\n all?: boolean;\r\n provenanceReceipt?: Record<string, unknown>;\r\n provenanceFiles?: Array<{ file: string; role: \"android-source\" | \"harmony-implementation\" }>;\r\n}) {\r\n const projectRoot = fs.realpathSync(path.resolve(options.project));\r\n const requestedHarmonyRoot = options.harmonyProject ? path.resolve(options.harmonyProject) : null;\r\n if (requestedHarmonyRoot && (!fs.existsSync(requestedHarmonyRoot) || !fs.statSync(requestedHarmonyRoot).isDirectory())) throw new Error(`HarmonyOS project not found: ${requestedHarmonyRoot}`);\r\n const harmonyRoot = requestedHarmonyRoot ? fs.realpathSync(requestedHarmonyRoot) : null;\r\n if (!options.message?.trim()) throw new Error(\"checkpoint create requires --message\");\r\n if (!options.all && options.include.length === 0) throw new Error(\"checkpoint create requires at least one --include or explicit --all\");\r\n const baseline = gitWorkspaceStatus(projectRoot);\r\n if (!baseline.repository) throw new Error(baseline.errors?.[0] ?? \"not a Git repository\");\r\n const androidRepository = repositoryRoot(projectRoot)!;\r\n const harmonyRepository = harmonyRoot\r\n ? (repositoryRoot(harmonyRoot) ?? initializeHarmonyRepository(androidRepository, harmonyRoot).root)\r\n : androidRepository;\r\n const repositories = [...new Set([androidRepository, harmonyRepository])];\r\n for (const root of repositories) {\r\n const before = stagedFiles(root);\r\n if (before.length) throw new Error(`Refusing to mix pre-existing staged changes in ${root}: ${before.join(\", \")}`);\r\n }\r\n\r\n const rollback = () => {\r\n for (const root of repositories) unstage(root, stagedFiles(root));\r\n };\r\n\r\n try {\r\n if (options.all) {\r\n const androidAdd = git(projectRoot, [\"add\", \"-A\", \"--\", \".\", \":!.migration\"]);\r\n if (!androidAdd.ok) throw new Error(androidAdd.stderr || \"git add failed for Android project\");\r\n if (harmonyRoot && harmonyRepository !== androidRepository) {\r\n const harmonyAdd = git(harmonyRoot, [\"add\", \"-A\", \"--\", \".\", \":!.migration\"]);\r\n if (!harmonyAdd.ok) throw new Error(harmonyAdd.stderr || \"git add failed for HarmonyOS project\");\r\n } else if (harmonyRoot && !inside(projectRoot, harmonyRoot)) {\r\n const harmonyPath = normalized(path.relative(androidRepository, harmonyRoot));\r\n const harmonyAdd = git(androidRepository, [\"add\", \"-A\", \"--\", harmonyPath]);\r\n if (!harmonyAdd.ok) throw new Error(harmonyAdd.stderr || \"git add failed for HarmonyOS project\");\r\n }\r\n } else {\r\n for (const value of options.include) {\r\n const absolute = path.resolve(projectRoot, value);\r\n const root = harmonyRoot && inside(harmonyRoot, absolute) ? harmonyRepository : (() => { if (inside(projectRoot, absolute)) return androidRepository; return null; })();\r\n if (!root) throw new Error(`checkpoint include is outside the managed Android and HarmonyOS projects: ${value}`);\r\n const relative = normalized(path.relative(root, absolute));\r\n const add = git(root, [\"add\", \"-A\", \"--\", relative]);\r\n if (!add.ok) throw new Error(add.stderr || `git add failed: ${value}`);\r\n }\r\n }\r\n } catch (error) {\r\n rollback();\r\n throw error;\r\n }\r\n\r\n const stagedByRepository = new Map(repositories.map((root) => [root, stagedFiles(root)]));\r\n if (![...stagedByRepository.values()].some((files) => files.length)) throw new Error(\"checkpoint has no staged changes outside .migration\");\r\n let receiptValue: Record<string, unknown> | null = null;\r\n if (options.provenanceReceipt) {\r\n let committedFiles: Array<{ file: string; role: string; repository: \"android\" | \"harmony\"; repositoryFile: string; fileSha256: string }>;\r\n try {\r\n committedFiles = [...new Map((options.provenanceFiles ?? []).map((item) => [`${item.role}:${item.file}`, item])).values()]\r\n .sort((left, right) => left.file.localeCompare(right.file) || left.role.localeCompare(right.role))\r\n .map((item) => {\r\n const absolute = path.resolve(projectRoot, item.file);\r\n const expectedRoot = item.role === \"harmony-implementation\" ? harmonyRoot : projectRoot;\r\n const root = item.role === \"harmony-implementation\" ? harmonyRepository : androidRepository;\r\n const relative = normalized(path.relative(projectRoot, absolute));\r\n if (!expectedRoot || !inside(expectedRoot, absolute) || !fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) {\r\n throw new Error(`checkpoint provenance file is outside the project or missing: ${item.file}`);\r\n }\r\n const repositoryFile = normalized(path.relative(root, absolute));\r\n const workingBlob = git(root, [\"hash-object\", \"--\", repositoryFile]);\r\n const stagedEntry = git(root, [\"ls-files\", \"--stage\", \"--\", repositoryFile]);\r\n const stagedBlob = stagedEntry.stdout.match(/^\\d+\\s+([a-f0-9]+)\\s+0\\t/)?.[1] ?? null;\r\n if (!workingBlob.ok || !stagedEntry.ok || !stagedBlob || workingBlob.stdout !== stagedBlob) {\r\n throw new Error(`checkpoint provenance file is not represented by the staged commit tree: ${relative}`);\r\n }\r\n return {\r\n file: relative,\r\n role: item.role,\r\n repository: item.role === \"harmony-implementation\" ? \"harmony\" : \"android\",\r\n repositoryFile,\r\n fileSha256: createHash(\"sha256\").update(fs.readFileSync(absolute)).digest(\"hex\"),\r\n };\r\n });\r\n } catch (error) {\r\n rollback();\r\n throw error;\r\n }\r\n receiptValue = {\r\n ...options.provenanceReceipt,\r\n committedFiles,\r\n repositories: {\r\n android: { root: \".\", gitRoot: normalized(path.relative(projectRoot, androidRepository)) || \".\" },\r\n harmony: harmonyRoot ? { root: normalized(path.relative(projectRoot, harmonyRoot)), gitRoot: normalized(path.relative(projectRoot, harmonyRepository)) } : null,\r\n },\r\n };\r\n }\r\n\r\n const commitResults: Array<{ kind: \"android\" | \"harmony\"; root: string; commit: string; files: string[]; summary: string }> = [];\r\n const separateHarmony = harmonyRoot && harmonyRepository !== androidRepository;\r\n if (separateHarmony) {\r\n const files = stagedFiles(harmonyRepository);\r\n if (files.length) {\r\n const commit = git(harmonyRepository, [\"commit\", \"-m\", options.message.trim()]);\r\n if (!commit.ok) {\r\n rollback();\r\n throw new Error(commit.stderr || commit.stdout || \"HarmonyOS git commit failed\");\r\n }\r\n commitResults.push({ kind: \"harmony\", root: harmonyRepository, commit: git(harmonyRepository, [\"rev-parse\", \"HEAD\"]).stdout, files, summary: commit.stdout });\r\n }\r\n }\r\n const androidFiles = stagedFiles(androidRepository);\r\n if (androidFiles.length) {\r\n const androidCommit = git(androidRepository, [\"commit\", \"-m\", options.message.trim()]);\r\n if (!androidCommit.ok) {\r\n unstage(androidRepository, androidFiles);\r\n throw new Error(androidCommit.stderr || androidCommit.stdout || \"Android git commit failed\");\r\n }\r\n commitResults.push({ kind: \"android\", root: androidRepository, commit: git(androidRepository, [\"rev-parse\", \"HEAD\"]).stdout, files: androidFiles, summary: androidCommit.stdout });\r\n }\r\n const androidCheckpoint = commitResults.find((item) => item.kind === \"android\");\r\n if (harmonyRoot && harmonyRepository === androidRepository) {\r\n commitResults.push({ kind: \"harmony\", root: harmonyRepository, commit: androidCheckpoint!.commit, files: androidFiles.filter((file) => inside(harmonyRoot, path.resolve(harmonyRepository, file))), summary: androidCheckpoint!.summary });\r\n } else if (harmonyRoot && !commitResults.some((item) => item.kind === \"harmony\")) {\r\n const harmonyHead = git(harmonyRepository, [\"rev-parse\", \"HEAD\"]).stdout;\r\n if (harmonyHead) commitResults.push({ kind: \"harmony\", root: harmonyRepository, commit: harmonyHead, files: [], summary: \"HarmonyOS repository already clean\" });\r\n }\r\n const harmonyCheckpoint = commitResults.find((item) => item.kind === \"harmony\");\r\n if (receiptValue) {\r\n const receipt = path.join(migrationDirectory(projectRoot), \"audit\", \"checkpoint-provenance.json\");\r\n fs.mkdirSync(path.dirname(receipt), { recursive: true });\r\n const temporary = `${receipt}.${process.pid}.tmp`;\r\n fs.writeFileSync(temporary, `${JSON.stringify({\r\n ...receiptValue,\r\n commits: {\r\n android: androidCheckpoint?.commit ?? null,\r\n harmony: harmonyCheckpoint?.commit ?? null,\r\n },\r\n }, null, 2)}\\n`, \"utf8\");\r\n fs.renameSync(temporary, receipt);\r\n }\r\n const files = [...new Set(commitResults.flatMap((item) => item.files.map((file) => normalized(path.relative(projectRoot, path.resolve(item.root, file))))))].sort();\r\n const commit = androidCheckpoint?.commit ?? harmonyCheckpoint?.commit;\r\n return {\r\n status: \"passed\",\r\n commit,\r\n commits: { android: androidCheckpoint?.commit ?? null, harmony: harmonyCheckpoint?.commit ?? null },\r\n files,\r\n repositories: commitResults,\r\n summary: commitResults.map((item) => `${item.kind}: ${item.summary}`).join(\"\\n\"),\r\n };\r\n}\r\n","import fs from \"node:fs\";\r\nimport { spawnCommandSync } from \"./lib/spawn-command.ts\";\r\n\r\nfunction probe(command: string, args: string[], timeout = 15000) {\r\n const result = spawnCommandSync(command, args, { encoding: \"utf8\", timeout, windowsHide: true });\r\n return {\r\n command,\r\n available: !result.error && result.status === 0,\r\n exitCode: Number.isInteger(result.status) ? result.status : null,\r\n output: String(result.stdout || result.stderr || result.error?.message || \"\").trim().split(/\\r?\\n/)[0] ?? \"\",\r\n };\r\n}\r\n\r\nfunction firstDirectory(values: Array<string | undefined | null>) {\r\n return values.find((value): value is string => Boolean(value && fs.existsSync(value) && fs.statSync(value).isDirectory())) ?? null;\r\n}\r\n\r\nexport function checkToolchain(_project: string, env = process.env) {\r\n const pythonCandidates = [\r\n env.PYTHON_BINARY,\r\n process.platform === \"win32\" ? \"python\" : \"python3\",\r\n \"python\",\r\n process.platform === \"darwin\" ? \"/opt/homebrew/anaconda3/bin/python3\" : null,\r\n ].filter(Boolean) as string[];\r\n const pythonProbes = pythonCandidates.map((candidate) => probe(candidate, [\"--version\"]));\r\n const supportedPython = pythonProbes.find((item) => {\r\n const match = item.output.match(/(\\d+)\\.(\\d+)/);\r\n return item.available && Boolean(match && (Number(match[1]) > 3 || Number(match[1]) === 3 && Number(match[2]) >= 10));\r\n });\r\n const commands = {\r\n git: probe(\"git\", [\"--version\"]),\r\n node: { command: process.execPath, available: true, exitCode: 0, output: process.version },\r\n npm: probe(process.platform === \"win32\" ? \"npm.cmd\" : \"npm\", [\"--version\"]),\r\n python: supportedPython ?? pythonProbes.find((item) => item.available) ?? pythonProbes[0],\r\n java: probe(\"java\", [\"-version\"]),\r\n appgraph: probe(\"appgraph\", [\"--version\"]),\r\n };\r\n // Android SDK / Android 构建入口探测已移除:迁移流程不依赖 Android 编译环境,\r\n // 双端对照退化为源码与静态 facts 基准。java 探测保留(appgraph 依赖类型解析需要 JDK)。\r\n const devecoHome = firstDirectory([\r\n env.DEVECO_STUDIO_HOME,\r\n env.DEVECO_HOME,\r\n process.platform === \"darwin\" ? \"/Applications/DevEco-Studio.app/Contents\" : null,\r\n ]);\r\n const checks = [\r\n ...Object.entries(commands).map(([id, value]) => ({ id, status: value.available ? \"passed\" : \"failed\", summary: value.available ? value.output || `${id} available` : `${id} unavailable`, evidence: [value.command] })),\r\n { id: \"deveco\", status: devecoHome ? \"passed\" : \"failed\", summary: devecoHome ?? \"DevEco Studio not found\", evidence: devecoHome ? [devecoHome] : [] },\r\n ];\r\n const nodeMajor = Number.parseInt(process.versions.node.split(\".\")[0], 10);\r\n const pythonMatch = commands.python.output.match(/(\\d+)\\.(\\d+)/);\r\n const pythonSupported = Boolean(pythonMatch && (Number(pythonMatch[1]) > 3 || Number(pythonMatch[1]) === 3 && Number(pythonMatch[2]) >= 10));\r\n const nodeCheck = checks.find((item) => item.id === \"node\");\r\n if (nodeCheck && (nodeMajor < 20 || nodeMajor > 24)) Object.assign(nodeCheck, { status: \"failed\", summary: `Node.js ${process.versions.node} is outside supported range 20-24` });\r\n const pythonCheck = checks.find((item) => item.id === \"python\");\r\n if (pythonCheck && !pythonSupported) Object.assign(pythonCheck, { status: \"failed\", summary: `${commands.python.output || \"Python unavailable\"}; Python 3.10+ is required` });\r\n return { status: checks.some((item) => item.status === \"failed\") ? \"failed\" : \"passed\", checks, commands, devecoHome };\r\n}\r\n\r\nexport function checkAppGraphHealth() {\r\n const version = probe(\"appgraph\", [\"--version\"]);\r\n if (!version.available) return { status: \"failed\", compatible: false, version: null, checks: [version], summary: \"appgraph is unavailable\" };\r\n const capability = probe(\"appgraph\", [\"spec-analysis\", \"--help\"]);\r\n const compatible = capability.available;\r\n return { status: compatible ? \"passed\" : \"failed\", compatible, version: version.output, checks: [version, capability], summary: compatible ? \"AppGraph CLI and migration analysis capability are available\" : \"AppGraph lacks spec-analysis\" };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\n\r\nexport const PREFLIGHT_CHECKS = [\r\n { id: \"android-ui-stack\", name: \"Android UI 技术栈\", required: true },\r\n { id: \"git\", name: \"Git 仓库和工作区\", required: true },\r\n { id: \"toolchain\", name: \"主机综合工具链\", required: true },\r\n { id: \"devecocli-auth\", name: \"DevEco CLI 登录状态\", required: true },\r\n { id: \"appgraph\", name: \"AppGraph 兼容性和健康状态\", required: true },\r\n { id: \"config\", name: \".migration/config.json\", required: true },\r\n { id: \"android-build\", name: \"Android 基线构建\", required: false },\r\n { id: \"android-emulator\", name: \"Android 模拟器\", required: false },\r\n { id: \"harmony-project\", name: \"HarmonyOS 工程存在或初始化\", required: true },\r\n { id: \"harmony-sdk\", name: \"HarmonyOS SDK 声明根目录\", required: false },\r\n { id: \"harmony-build\", name: \"HarmonyOS 应用 HAP 构建\", required: true },\r\n { id: \"harmony-device\", name: \"HarmonyOS 设备和 Shell\", required: true },\r\n] as const;\r\n\r\nexport type PreflightCheckId = typeof PREFLIGHT_CHECKS[number][\"id\"];\r\n\r\nfunction validateChecklist(value: any) {\r\n const errors: string[] = [];\r\n if (!value || typeof value !== \"object\" || Array.isArray(value)) errors.push(\"checklist must be an object\");\r\n if (value?.version !== 1) errors.push(\"version must be 1\");\r\n if (!value?.checks || typeof value.checks !== \"object\" || Array.isArray(value.checks)) errors.push(\"checks must be an object\");\r\n for (const item of PREFLIGHT_CHECKS) {\r\n if (!value?.checks?.[item.id] || typeof value.checks[item.id] !== \"object\") errors.push(`checks.${item.id} is required`);\r\n else {\r\n if (value.checks[item.id].name !== item.name) errors.push(`checks.${item.id}.name must be ${item.name}`);\r\n if (value.checks[item.id].required !== item.required) errors.push(`checks.${item.id}.required must be ${item.required}`);\r\n if (typeof value.checks[item.id].enabled !== \"boolean\") errors.push(`checks.${item.id}.enabled must be boolean`);\r\n }\r\n }\r\n const known = new Set(PREFLIGHT_CHECKS.map((item) => item.id));\r\n for (const id of Object.keys(value?.checks ?? {})) if (!known.has(id as PreflightCheckId)) errors.push(`unknown check: ${id}`);\r\n if (errors.length) throw new Error(`Invalid preflight checklist: ${errors.join(\"; \")}`);\r\n return value;\r\n}\r\n\r\nexport function loadPreflightChecklist(file: string) {\r\n const checklistPath = path.resolve(file);\r\n if (!fs.existsSync(checklistPath)) throw new Error(`Preflight checklist not found: ${checklistPath}`);\r\n let checklist: any;\r\n try {\r\n checklist = validateChecklist(JSON.parse(fs.readFileSync(checklistPath, \"utf8\")));\r\n } catch (error) {\r\n if (error instanceof Error && error.message.startsWith(\"Invalid preflight checklist:\")) throw error;\r\n throw new Error(`Invalid preflight checklist: ${error instanceof Error ? error.message : String(error)}`);\r\n }\r\n return {\r\n checklistPath,\r\n checklist,\r\n isEnabled: (id: PreflightCheckId) => checklist.checks[id].enabled as boolean,\r\n };\r\n}\r\n","import { spawn, spawnSync } from \"node:child_process\";\r\nimport { closeSync, existsSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { setTimeout as delay } from \"node:timers/promises\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\nimport { checkDevEcoCliAuth, devEcoCliSpawn } from \"./deveco-cli.ts\";\r\nimport { launchHostOutsideRunner, writePidAtomically } from \"./start-background-service.ts\";\r\n\r\n/**\r\n * 受管 DevEco CLI 登录。\r\n *\r\n * `devecocli auth login` 会在本地随机端口启动 OAuth 回调服务器,其生命周期与\r\n * 登录进程绑定:进程被杀或超时退出后,浏览器中残留的华为登录页会重定向到\r\n * 已死端口,表现为「localhost 拒绝了我们的连接请求」且无法自愈。\r\n *\r\n * 本模块把登录改为可安全编排的受管流程:\r\n * 1. 启动前清理孤儿 `devecocli auth login` 进程(陈旧回调服务器的直接根因);\r\n * 2. 通过脱离命令运行器的 host 持久拉起登录进程,stdin 保持打开并自动发送\r\n * 回车触发浏览器,进程存活不受本次 CLI 调用或 Agent 工具调用生命周期影响;\r\n * 3. 从登录进程输出中提取登录 URL 打印到终端(浏览器未弹出时可手动访问);\r\n * 4. 有界轮询 `devecocli auth status`,登录成功立即回收登录进程并返回。\r\n */\r\n\r\nconst MANAGED_LOGIN_SERVICE_NAME = \"devecocli-auth\";\r\nconst LOGIN_URL_PATTERN = /https?:\\/\\/[^\\s\"'<>]+/i;\r\n\r\n/** 仅匹配真正的 devecocli 登录命令行,避免误杀 droid2hmos 自身或无关进程。 */\r\nexport const DEVECO_LOGIN_COMMAND_PATTERN = /(?:^|[\\/\\\\\\s])devecocli(?:\\.(?:mjs|cjs|js|cmd|bat|exe|ps1))?[ \\t]+auth[ \\t]+login(?:[ \\t]|$)/i;\r\n\r\nexport function isDevEcoCliLoginCommand(commandLine: string) {\r\n return DEVECO_LOGIN_COMMAND_PATTERN.test(commandLine);\r\n}\r\n\r\nexport function managedLoginStatePaths(project: string) {\r\n const directory = path.join(migrationDirectory(project), \"services\");\r\n const pidFile = path.join(directory, `${MANAGED_LOGIN_SERVICE_NAME}.pid`);\r\n return {\r\n directory,\r\n pidFile,\r\n stdoutLog: path.join(directory, `${MANAGED_LOGIN_SERVICE_NAME}.stdout.log`),\r\n stderrLog: path.join(directory, `${MANAGED_LOGIN_SERVICE_NAME}.stderr.log`),\r\n exitFile: `${pidFile}.exit`,\r\n errorFile: `${pidFile}.error`,\r\n };\r\n}\r\n\r\nfunction isAlive(pid: number | null) {\r\n if (!Number.isInteger(pid) || pid <= 0) return false;\r\n try {\r\n process.kill(pid, 0);\r\n return true;\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\nfunction readPidFile(pidFile: string): number | null {\r\n try {\r\n const pid = Number.parseInt(readFileSync(pidFile, \"utf8\").trim(), 10);\r\n return Number.isInteger(pid) ? pid : null;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nfunction tailFile(file: string, maxChars: number) {\r\n try {\r\n const content = readFileSync(file, \"utf8\").trim();\r\n return content.length > maxChars ? `…${content.slice(-maxChars)}` : content;\r\n } catch {\r\n return \"\";\r\n }\r\n}\r\n\r\nfunction listPosixProcesses(): Array<{ pid: number; command: string }> {\r\n const result = spawnSync(\"ps\", [\"-eo\", \"pid=,command=\"], { encoding: \"utf8\", timeout: 15000 });\r\n if (result.error || result.status !== 0) return [];\r\n return result.stdout.split(\"\\n\").flatMap((line) => {\r\n const trimmed = line.trim();\r\n if (!trimmed) return [];\r\n const separator = trimmed.indexOf(\" \");\r\n if (separator <= 0) return [];\r\n const pid = Number.parseInt(trimmed.slice(0, separator), 10);\r\n const command = trimmed.slice(separator + 1);\r\n return Number.isInteger(pid) && pid > 0 ? [{ pid, command }] : [];\r\n });\r\n}\r\n\r\nfunction listWindowsProcesses(): Array<{ pid: number; command: string }> {\r\n const source = \"Get-CimInstance Win32_Process -Filter \\\"CommandLine IS NOT NULL\\\" | ForEach-Object { \\\"$($_.ProcessId)`t$($_.CommandLine)\\\" }\";\r\n const encoded = Buffer.from(source, \"utf16le\").toString(\"base64\");\r\n const powershell = process.env.SystemRoot\r\n ? path.resolve(process.env.SystemRoot, \"System32\", \"WindowsPowerShell\", \"v1.0\", \"powershell.exe\")\r\n : \"powershell.exe\";\r\n const result = spawnSync(powershell, [\"-NoLogo\", \"-NoProfile\", \"-NonInteractive\", \"-EncodedCommand\", encoded], {\r\n encoding: \"utf8\",\r\n timeout: 30000,\r\n windowsHide: true,\r\n });\r\n if (result.error || result.status !== 0) return [];\r\n return result.stdout.split(\"\\n\").flatMap((line) => {\r\n const separator = line.indexOf(\"\\t\");\r\n if (separator <= 0) return [];\r\n const pid = Number.parseInt(line.slice(0, separator), 10);\r\n const command = line.slice(separator + 1);\r\n return Number.isInteger(pid) && pid > 0 ? [{ pid, command }] : [];\r\n });\r\n}\r\n\r\nexport function listDevEcoCliLoginProcesses(options: { lister?: () => Array<{ pid: number; command: string }> } = {}) {\r\n const entries = options.lister\r\n ? options.lister()\r\n : (() => { if (process.platform === \"win32\") return listWindowsProcesses(); return listPosixProcesses(); })();\r\n return entries.filter((entry) => entry.pid !== process.pid && isDevEcoCliLoginCommand(entry.command));\r\n}\r\n\r\nasync function terminateProcessTree(pid: number) {\r\n if (process.platform === \"win32\") {\r\n spawnSync(\"taskkill\", [\"/PID\", String(pid), \"/T\", \"/F\"], { encoding: \"utf8\", timeout: 15000, windowsHide: true });\r\n return;\r\n }\r\n try { process.kill(pid, \"SIGTERM\"); } catch { return; }\r\n for (let attempt = 0; attempt < 10; attempt += 1) {\r\n if (!isAlive(pid)) return;\r\n await delay(200);\r\n }\r\n try { process.kill(pid, \"SIGKILL\"); } catch { /* 已退出 */ }\r\n}\r\n\r\nexport async function killOrphanDevEcoCliLogins(options: {\r\n project: string;\r\n excludePids?: number[];\r\n lister?: () => Array<{ pid: number; command: string }>;\r\n terminator?: (pid: number) => Promise<void> | void;\r\n}) {\r\n const state = managedLoginStatePaths(path.resolve(options.project));\r\n const terminate = options.terminator ?? terminateProcessTree;\r\n const targets = new Set<number>();\r\n const managedPid = readPidFile(state.pidFile);\r\n if (managedPid !== null && isAlive(managedPid)) targets.add(managedPid);\r\n for (const entry of listDevEcoCliLoginProcesses({ lister: options.lister })) {\r\n if (entry.pid === process.pid) continue;\r\n if ((options.excludePids ?? []).includes(entry.pid)) continue;\r\n targets.add(entry.pid);\r\n }\r\n const killedPids: number[] = [];\r\n for (const pid of targets) {\r\n try {\r\n await terminate(pid);\r\n killedPids.push(pid);\r\n } catch { /* 目标进程已自行退出 */ }\r\n }\r\n if (managedPid !== null && existsSync(state.pidFile)) {\r\n try { unlinkSync(state.pidFile); } catch { /* 已被清理 */ }\r\n }\r\n return { killedPids, managedPid: managedPid ?? null };\r\n}\r\n\r\n/** internal devecocli-auth-host 的入口:脱离命令运行器持久拉起登录进程。 */\r\nexport function runDetachedDevEcoAuthHost(requestPath: string) {\r\n const request = JSON.parse(readFileSync(requestPath, \"utf8\"));\r\n mkdirSync(path.dirname(request.stdout), { recursive: true });\r\n mkdirSync(path.dirname(request.stderr), { recursive: true });\r\n const stdout = openSync(request.stdout, \"a\");\r\n const stderr = openSync(request.stderr, \"a\");\r\n try {\r\n const child = spawn(request.command[0], request.command.slice(1), {\r\n cwd: request.cwd,\r\n detached: true,\r\n env: { ...process.env, ...(request.env ?? {}) },\r\n stdio: [\"pipe\", stdout, stderr],\r\n windowsHide: true,\r\n });\r\n const stdin = child.stdin;\r\n stdin.on(\"error\", () => { /* 子进程不读 stdin 时忽略 EPIPE */ });\r\n // 立即并再次发送回车,触发「按回车打开浏览器」类提示;stdin 保持打开直到子进程退出。\r\n stdin.write(\"\\n\");\r\n setTimeout(() => { try { stdin.write(\"\\n\"); } catch { /* 子进程已退出 */ } }, 2500).unref();\r\n writePidAtomically(request.pidFile, child.pid);\r\n child.once(\"error\", (error) => {\r\n writeFileSync(`${request.pidFile}.error`, `${error.stack ?? error.message}\\n`, \"utf8\");\r\n });\r\n child.once(\"close\", (code) => {\r\n try { stdin.destroy(); } catch { /* 已销毁 */ }\r\n try { unlinkSync(request.pidFile); } catch { /* 已清理 */ }\r\n try { writeFileSync(`${request.pidFile}.exit`, `${code ?? \"unknown\"}\\n`, \"utf8\"); } catch { /* 磁盘问题不阻塞退出 */ }\r\n });\r\n // host 与登录子进程同生命周期:不 unref 子进程,保持 stdin 打开并等待其退出。\r\n } finally {\r\n closeSync(stdout);\r\n closeSync(stderr);\r\n }\r\n}\r\n\r\nfunction findLoginUrl(state: ReturnType<typeof managedLoginStatePaths>) {\r\n for (const file of [state.stdoutLog, state.stderrLog]) {\r\n try {\r\n const match = readFileSync(file, \"utf8\").match(LOGIN_URL_PATTERN);\r\n if (match) return match[0];\r\n } catch { /* 日志尚未创建 */ }\r\n }\r\n return null;\r\n}\r\n\r\nexport async function managedDevEcoCliLogin(options: {\r\n project: string;\r\n hostCommand: string[];\r\n executable?: string;\r\n timeoutMs?: number;\r\n pollIntervalMs?: number;\r\n statusTimeoutMs?: number;\r\n onProgress?: (line: string) => void;\r\n}) {\r\n const executable = options.executable ?? process.env.DEVECO_CLI_BINARY ?? \"devecocli\";\r\n const timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\r\n const pollIntervalMs = options.pollIntervalMs ?? 2000;\r\n const statusTimeoutMs = options.statusTimeoutMs ?? 15000;\r\n const progress = options.onProgress ?? (() => {});\r\n const projectRoot = path.resolve(options.project);\r\n const state = managedLoginStatePaths(projectRoot);\r\n\r\n const failure = (summary: string, extra: Record<string, unknown> = {}) => ({\r\n status: \"failed\" as const,\r\n loggedIn: false,\r\n loginAttempted: true,\r\n summary,\r\n evidence: [state.stdoutLog, state.stderrLog].filter(existsSync),\r\n stdoutLog: state.stdoutLog,\r\n stderrLog: state.stderrLog,\r\n ...extra,\r\n });\r\n\r\n const initial = checkDevEcoCliAuth({ executable, timeoutMs: statusTimeoutMs });\r\n if (initial.status === \"passed\") {\r\n return {\r\n status: \"passed\" as const,\r\n loggedIn: true,\r\n loginAttempted: false,\r\n currentUser: initial.currentUser,\r\n summary: `DevEco CLI 已登录(Current user: ${initial.currentUser})`,\r\n evidence: initial.evidence,\r\n stdoutLog: state.stdoutLog,\r\n stderrLog: state.stderrLog,\r\n };\r\n }\r\n\r\n progress(\"DevEco CLI 未登录,开始受管登录\");\r\n const cleaned = await killOrphanDevEcoCliLogins({ project: projectRoot });\r\n if (cleaned.killedPids.length) progress(`已清理孤儿登录进程(残留回调服务器): ${cleaned.killedPids.join(\", \")}`);\r\n\r\n mkdirSync(state.directory, { recursive: true });\r\n for (const stale of [state.errorFile, state.exitFile]) {\r\n if (existsSync(stale)) unlinkSync(stale);\r\n }\r\n const requestPath = `${state.pidFile}.launch.json`;\r\n writeFileSync(requestPath, JSON.stringify({\r\n cwd: projectRoot,\r\n pidFile: state.pidFile,\r\n stdout: state.stdoutLog,\r\n stderr: state.stderrLog,\r\n command: devEcoCliSpawn(executable, [\"auth\", \"login\"]),\r\n env: { DEVECO_CLI_SKIP_VERSION_CHECK: \"1\" },\r\n }, null, 2), \"utf8\");\r\n launchHostOutsideRunner(requestPath, options.hostCommand);\r\n progress(`已持久拉起登录进程(回调服务器随进程存活),日志: ${state.stdoutLog}`);\r\n\r\n const deadline = Date.now() + timeoutMs;\r\n let announcedUrl: string | null = null;\r\n let lastCountdownSeconds = Math.ceil(timeoutMs / 1000);\r\n while (Date.now() < deadline) {\r\n if (existsSync(state.errorFile)) {\r\n return failure(`受管登录进程启动失败: ${tailFile(state.errorFile, 800)}`);\r\n }\r\n const pid = readPidFile(state.pidFile);\r\n const url = announcedUrl ?? findLoginUrl(state);\r\n if (url && url !== announcedUrl) {\r\n announcedUrl = url;\r\n progress(`登录 URL: ${url}(浏览器未自动打开时请手动访问)`);\r\n }\r\n const status = checkDevEcoCliAuth({ executable, timeoutMs: statusTimeoutMs });\r\n if (status.status === \"passed\") {\r\n if (pid !== null && isAlive(pid)) await terminateProcessTree(pid);\r\n return {\r\n status: \"passed\" as const,\r\n loggedIn: true,\r\n loginAttempted: true,\r\n currentUser: status.currentUser,\r\n loginUrl: announcedUrl,\r\n pid,\r\n summary: `DevEco CLI 登录完成(Current user: ${status.currentUser})`,\r\n evidence: [`Current user: ${status.currentUser}`, ...(announcedUrl ? [`login url: ${announcedUrl}`] : [])],\r\n stdoutLog: state.stdoutLog,\r\n stderrLog: state.stderrLog,\r\n };\r\n }\r\n if (pid === null && existsSync(state.exitFile)) {\r\n return failure(`登录进程提前退出(exit ${readFileSync(state.exitFile, \"utf8\").trim()}): ${tailFile(state.stderrLog, 800) || tailFile(state.stdoutLog, 800) || \"无输出\"}`);\r\n }\r\n if (pid !== null && !isAlive(pid) && !existsSync(state.pidFile)) {\r\n return failure(`登录进程提前退出(exit ${existsSync(state.exitFile) ? readFileSync(state.exitFile, \"utf8\").trim() : \"unknown\"}): ${tailFile(state.stderrLog, 800) || tailFile(state.stdoutLog, 800) || \"无输出\"}`);\r\n }\r\n const remainingSeconds = Math.round((deadline - Date.now()) / 1000);\r\n if (lastCountdownSeconds - remainingSeconds >= 30) {\r\n lastCountdownSeconds = remainingSeconds;\r\n progress(`等待浏览器完成授权,剩余 ${remainingSeconds}s(请勿并发发起第二次登录)`);\r\n }\r\n await delay(pollIntervalMs);\r\n }\r\n\r\n const pid = readPidFile(state.pidFile);\r\n return failure(\r\n `等待登录超时(${Math.round(timeoutMs / 1000)}s)。登录进程(PID ${pid ?? \"unknown\"})暂时保留,浏览器仍可稍后完成授权;下次 droid2hmos auth login 会先自动清理它`,\r\n { loginUrl: announcedUrl, pid },\r\n );\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { createHash } from \"node:crypto\";\r\nimport { spawnSync } from \"node:child_process\";\r\nimport { inflateSync } from \"node:zlib\";\r\nimport { migrationDirectory, migrationWorkspaceRoot } from \"../migration-paths.ts\";\r\nimport { selectPreferredTarget } from \"./device-signature.ts\";\r\n\r\ntype Platform = \"harmony\";\r\n\r\nfunction safeName(value: string) {\r\n if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) throw new Error(\"evidence name must use letters, digits, dot, underscore, or dash\");\r\n return value;\r\n}\r\n\r\nfunction run(command: string, args: string[], encoding: BufferEncoding | \"buffer\" = \"utf8\") {\r\n const script = /\\.m?js$/i.test(command);\r\n const result = spawnSync(script ? process.execPath : command, script ? [command, ...args] : args, {\r\n encoding: encoding === \"buffer\" ? null : encoding,\r\n shell: false,\r\n timeout: 30000,\r\n windowsHide: true,\r\n maxBuffer: 16 * 1024 * 1024,\r\n });\r\n return {\r\n ok: !result.error && result.status === 0,\r\n status: Number.isInteger(result.status) ? result.status : null,\r\n stdout: result.stdout ?? (encoding === \"buffer\" ? Buffer.alloc(0) : \"\"),\r\n stderr: String(result.stderr ?? result.error?.message ?? \"\"),\r\n invocation: [command, ...args],\r\n };\r\n}\r\n\r\nfunction writeResult(file: string, result: ReturnType<typeof run>) {\r\n if (!result.ok) return false;\r\n const data = Buffer.isBuffer(result.stdout) ? result.stdout : Buffer.from(String(result.stdout));\r\n fs.writeFileSync(file, data);\r\n return data.length > 0;\r\n}\r\n\r\nfunction pngSize(data: Buffer) {\r\n return data.length >= 24 && data.subarray(1, 4).toString(\"ascii\") === \"PNG\"\r\n ? { width: data.readUInt32BE(16), height: data.readUInt32BE(20) }\r\n : null;\r\n}\r\n\r\nfunction fileInfo(file: string) {\r\n if (!fs.existsSync(file)) return null;\r\n const data = fs.readFileSync(file);\r\n return { path: file, bytes: data.length, sha256: createHash(\"sha256\").update(data).digest(\"hex\"), ...(pngSize(data) ?? {}) };\r\n}\r\n\r\nfunction decodePng(file: string) {\r\n if (!fs.existsSync(file)) return null;\r\n const data = fs.readFileSync(file);\r\n const size = pngSize(data);\r\n if (!size || data.readUInt8(24) !== 8) return null;\r\n const colorType = data.readUInt8(25);\r\n const channels = ({ 0: 1, 2: 3, 4: 2, 6: 4 } as Record<number, number>)[colorType];\r\n if (!channels) return null;\r\n const chunks: Buffer[] = [];\r\n for (let offset = 8; offset + 12 <= data.length;) {\r\n const length = data.readUInt32BE(offset);\r\n const type = data.subarray(offset + 4, offset + 8).toString(\"ascii\");\r\n if (type === \"IDAT\") chunks.push(data.subarray(offset + 8, offset + 8 + length));\r\n offset += 12 + length;\r\n if (type === \"IEND\") break;\r\n }\r\n const inflated = inflateSync(Buffer.concat(chunks));\r\n const stride = size.width * channels;\r\n const pixels = Buffer.alloc(stride * size.height);\r\n const paeth = (a: number, b: number, c: number) => {\r\n const p = a + b - c;\r\n const pa = Math.abs(p - a);\r\n const pb = Math.abs(p - b);\r\n const pc = Math.abs(p - c);\r\n return pa <= pb && pa <= pc ? a : (() => { if (pb <= pc) return b; return c; })();\r\n };\r\n for (let y = 0; y < size.height; y++) {\r\n const input = y * (stride + 1);\r\n const filter = inflated[input];\r\n for (let x = 0; x < stride; x++) {\r\n const raw = inflated[input + 1 + x];\r\n const left = x >= channels ? pixels[y * stride + x - channels] : 0;\r\n const up = y > 0 ? pixels[(y - 1) * stride + x] : 0;\r\n const upperLeft = y > 0 && x >= channels ? pixels[(y - 1) * stride + x - channels] : 0;\r\n const value = filter === 0 ? raw : (() => { if (filter === 1) return raw + left; return (() => { if (filter === 2) return raw + up; return (() => { if (filter === 3) return raw + Math.floor((left + up) / 2); return (() => { if (filter === 4) return raw + paeth(left, up, upperLeft); return NaN; })(); })(); })(); })();\r\n if (!Number.isFinite(value)) return null;\r\n pixels[y * stride + x] = value & 0xff;\r\n }\r\n }\r\n return { ...size, channels, colorType, pixels };\r\n}\r\n\r\nfunction pixelMetrics(leftFile: string, rightFile: string) {\r\n try {\r\n const left = decodePng(leftFile);\r\n const right = decodePng(rightFile);\r\n if (!left || !right || left.width !== right.width || left.height !== right.height) return null;\r\n const samples = left.width * left.height * 3;\r\n let absolute = 0;\r\n let different = 0;\r\n for (let pixel = 0; pixel < left.width * left.height; pixel++) {\r\n for (let channel = 0; channel < 3; channel++) {\r\n const leftChannel = left.colorType === 0 || left.colorType === 4 ? 0 : channel;\r\n const rightChannel = right.colorType === 0 || right.colorType === 4 ? 0 : channel;\r\n const a = left.pixels[pixel * left.channels + leftChannel];\r\n const b = right.pixels[pixel * right.channels + rightChannel];\r\n absolute += Math.abs(a - b);\r\n if (a !== b) different++;\r\n }\r\n }\r\n return { meanAbsoluteError: absolute / samples, differentSampleRatio: different / samples, samples };\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nexport function captureDeviceEvidence(options: { project: string; platform: Platform; name: string; target?: string; hdc?: string }) {\r\n const projectRoot = path.resolve(options.project);\r\n const migrationRoot = migrationDirectory(projectRoot);\r\n const workspaceRoot = migrationWorkspaceRoot(projectRoot);\r\n const name = safeName(options.name);\r\n const capturedAt = new Date();\r\n const directory = path.join(migrationRoot, \"evidence\", name, options.platform);\r\n fs.mkdirSync(directory, { recursive: true });\r\n const screenshot = path.join(directory, \"screenshot.png\");\r\n const layout = path.join(directory, \"layout.json\");\r\n const logs = path.join(directory, \"device.log\");\r\n const commands: any[] = [];\r\n let target: string;\r\n\r\n const hdc = options.hdc ?? process.env.HDC_BINARY ?? \"hdc\";\r\n // 多设备并存时优先真机;显式 --target 或环境变量优先。\r\n const listed = run(hdc, [\"list\", \"targets\"]);\r\n const candidates = String(listed.stdout).split(/\\r?\\n/).map((line) => line.trim()).filter((line) => line && !/^\\[?empty\\]?$/i.test(line) && !/^list of targets/i.test(line));\r\n if (!listed.ok || !candidates.length) throw new Error(`${hdc} target discovery failed: ${listed.stderr || \"no targets\"}`);\r\n target = options.target ?? process.env.DROID2HMOS_HDC_TARGET ?? selectPreferredTarget(candidates)!;\r\n const prefix = [\"-t\", target];\r\n const remoteShot = `/data/local/tmp/droid2hmos-${process.pid}.png`;\r\n const remoteLayout = `/data/local/tmp/droid2hmos-${process.pid}.json`;\r\n const shot = run(hdc, [...prefix, \"shell\", \"snapshot_display\", \"-f\", remoteShot]);\r\n commands.push(shot);\r\n const recvShot = run(hdc, [...prefix, \"file\", \"recv\", remoteShot, screenshot]);\r\n commands.push(recvShot);\r\n const dump = run(hdc, [...prefix, \"shell\", \"uitest\", \"dumpLayout\", \"-p\", remoteLayout]);\r\n commands.push(dump);\r\n const recvLayout = run(hdc, [...prefix, \"file\", \"recv\", remoteLayout, layout]);\r\n commands.push(recvLayout);\r\n run(hdc, [...prefix, \"shell\", \"rm\", \"-f\", remoteShot, remoteLayout]);\r\n const log = run(hdc, [...prefix, \"shell\", \"hilog\", \"-x\"]);\r\n commands.push(log);\r\n writeResult(logs, log);\r\n\r\n const artifacts = [screenshot, layout, logs].map(fileInfo).filter(Boolean);\r\n const failures = commands.filter((item) => !item.ok).map((item) => ({ invocation: item.invocation, status: item.status, stderr: item.stderr }));\r\n const metadata = {\r\n evidenceVersion: \"1.0.0\",\r\n name,\r\n platform: options.platform,\r\n target,\r\n capturedAt: capturedAt.toISOString(),\r\n status: failures.length === 0 && artifacts.length === 3 ? \"passed\" : \"failed\",\r\n artifacts: artifacts.map((item: any) => ({ ...item, path: path.relative(workspaceRoot, item.path).replaceAll(\"\\\\\", \"/\") })),\r\n failures,\r\n };\r\n const metadataPath = path.join(directory, \"evidence.json\");\r\n fs.writeFileSync(metadataPath, `${JSON.stringify(metadata, null, 2)}\\n`, \"utf8\");\r\n return { ...metadata, metadataPath };\r\n}\r\n\r\nfunction tokens(file: string) {\r\n if (!fs.existsSync(file)) return new Set<string>();\r\n return new Set(fs.readFileSync(file, \"utf8\").toLowerCase().match(/[\\p{L}\\p{N}_-]{2,}/gu) ?? []);\r\n}\r\n\r\nexport function compareEvidence(options: { project: string; android: string; harmony: string; name: string }) {\r\n const projectRoot = path.resolve(options.project);\r\n const migrationRoot = migrationDirectory(projectRoot);\r\n const resolveEvidence = (value: string) => {\r\n // `.migration/...` refs are workspace-root relative; bare relative paths\r\n // stay relative to the Android project root.\r\n const normalized = value.replaceAll(\"\\\\\", \"/\");\r\n const root = path.isAbsolute(value) ? value\r\n : (() => { if (normalized.startsWith(\".migration/\")) return path.resolve(migrationWorkspaceRoot(projectRoot), value); return path.resolve(projectRoot, value); })();\r\n return fs.statSync(root).isDirectory() ? root : path.dirname(root);\r\n };\r\n const androidRoot = resolveEvidence(options.android);\r\n const harmonyRoot = resolveEvidence(options.harmony);\r\n const androidShot = fileInfo(path.join(androidRoot, \"screenshot.png\"));\r\n const harmonyShot = fileInfo(path.join(harmonyRoot, \"screenshot.png\"));\r\n const pixels = pixelMetrics(path.join(androidRoot, \"screenshot.png\"), path.join(harmonyRoot, \"screenshot.png\"));\r\n const layoutFile = (root: string) => [path.join(root, \"layout.json\"), path.join(root, \"layout.xml\")].find((file) => fs.existsSync(file)) ?? path.join(root, \"layout.json\");\r\n const left = tokens(layoutFile(androidRoot));\r\n const right = tokens(layoutFile(harmonyRoot));\r\n const intersection = [...left].filter((value) => right.has(value));\r\n const union = new Set([...left, ...right]);\r\n const result = {\r\n comparisonVersion: \"1.0.0\",\r\n name: safeName(options.name),\r\n createdAt: new Date().toISOString(),\r\n android: { root: androidRoot, screenshot: androidShot, layoutTokens: left.size },\r\n harmony: { root: harmonyRoot, screenshot: harmonyShot, layoutTokens: right.size },\r\n screenshot: {\r\n sameBytes: Boolean(androidShot && harmonyShot && androidShot.sha256 === harmonyShot.sha256),\r\n sameDimensions: Boolean(androidShot && harmonyShot && androidShot.width === harmonyShot.width && androidShot.height === harmonyShot.height),\r\n pixels,\r\n },\r\n layout: { sharedTokens: intersection.length, unionTokens: union.size, jaccard: union.size ? intersection.length / union.size : 1 },\r\n limitation: \"This deterministic comparison checks PNG pixels when decodable plus screenshot identity/dimensions and layout-token overlap; semantic visual parity still requires image inspection.\",\r\n };\r\n const output = path.join(migrationRoot, \"evidence\", safeName(options.name), \"comparison.json\");\r\n fs.mkdirSync(path.dirname(output), { recursive: true });\r\n fs.writeFileSync(output, `${JSON.stringify(result, null, 2)}\\n`, \"utf8\");\r\n return { status: \"passed\", output, result };\r\n}\r\n\r\nexport function writeFlowBundle(options: { project: string; name: string; platform: Platform; before: any; execution: any; after: any }) {\r\n const projectRoot = path.resolve(options.project);\r\n const migrationRoot = migrationDirectory(projectRoot);\r\n const output = path.join(migrationRoot, \"evidence\", safeName(options.name), \"flow.json\");\r\n const value = {\r\n flowVersion: \"1.0.0\",\r\n name: options.name,\r\n platform: options.platform,\r\n createdAt: new Date().toISOString(),\r\n status: options.before.status === \"passed\" && options.execution.status === \"passed\" && options.after.status === \"passed\" ? \"passed\" : \"failed\",\r\n before: path.relative(migrationWorkspaceRoot(projectRoot), options.before.metadataPath).replaceAll(\"\\\\\", \"/\"),\r\n execution: options.execution,\r\n after: path.relative(migrationWorkspaceRoot(projectRoot), options.after.metadataPath).replaceAll(\"\\\\\", \"/\"),\r\n };\r\n fs.mkdirSync(path.dirname(output), { recursive: true });\r\n fs.writeFileSync(output, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\r\n return { ...value, output };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { migrationDirectory, migrationWorkspaceRoot } from \"../migration-paths.ts\";\r\nimport { managedHarmonyFile, provenanceForFiles, type SourceProvenance } from \"./source-governance.ts\";\r\n\r\nconst allowedStatuses = new Set([\"pending\", \"implemented\", \"verified\", \"blocked\"]);\r\n\r\nfunction readJson(file: string) { return JSON.parse(fs.readFileSync(file, \"utf8\")); }\r\nfunction atomicJson(file: string, value: unknown) {\r\n const temporary = `${file}.${process.pid}.tmp`;\r\n fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\r\n fs.renameSync(temporary, file);\r\n}\r\n\r\nfunction readHarmonyRoot(projectRoot: string): string | null {\r\n const configPath = path.join(migrationDirectory(projectRoot), \"config.json\");\r\n if (!fs.existsSync(configPath)) return null;\r\n const config = readJson(configPath);\r\n const harmonyProject = config?.harmonyProject;\r\n if (typeof harmonyProject !== \"string\" || !harmonyProject) return null;\r\n const harmonyRoot = path.isAbsolute(harmonyProject) ? harmonyProject : path.resolve(projectRoot, harmonyProject);\r\n return fs.existsSync(harmonyRoot) ? harmonyRoot : null;\r\n}\r\n\r\nfunction insideProject(projectRoot: string, harmonyRoot: string | null, workspaceRoot: string, value: string, mustExist: boolean) {\r\n // `.migration/...` 引用相对兄弟迁移工作区根目录(`<工程名>-migration/`)解析;\r\n // 其余路径相对安卓工程根目录解析。\r\n const absolute = value.replaceAll(\"\\\\\", \"/\").startsWith(\".migration/\")\r\n ? path.resolve(workspaceRoot, value)\r\n : path.resolve(projectRoot, value);\r\n const relative = path.relative(projectRoot, absolute).replaceAll(\"\\\\\", \"/\");\r\n const inProject = !!relative && !relative.startsWith(\"../\") && !path.isAbsolute(relative);\r\n let inHarmony = false;\r\n if (!inProject && harmonyRoot) {\r\n const relativeHarmony = path.relative(harmonyRoot, absolute).replaceAll(\"\\\\\", \"/\");\r\n inHarmony = !!relativeHarmony && !relativeHarmony.startsWith(\"../\") && !path.isAbsolute(relativeHarmony) && !relative.startsWith(\"/\");\r\n }\r\n const migrationRelative = path.relative(workspaceRoot, absolute).replaceAll(\"\\\\\", \"/\");\r\n const inMigration = !!migrationRelative && !migrationRelative.startsWith(\"../\") && !path.isAbsolute(migrationRelative);\r\n if (!inProject && !inHarmony && !inMigration) throw new Error(`Path must be inside the project: ${value}`);\r\n if (mustExist && !fs.existsSync(absolute)) throw new Error(`Referenced file not found: ${migrationRelative !== \"\" && inMigration ? migrationRelative : relative}`);\r\n return inMigration ? migrationRelative : relative;\r\n}\r\n\r\nexport function updateReportItem(options: {\r\n project: string;\r\n ref: string;\r\n status?: string;\r\n harmonyosFiles?: string[];\r\n androidSourceFiles?: string[];\r\n sourceProvenance?: SourceProvenance[];\r\n testEvidence?: string[];\r\n difference?: string | null;\r\n}) {\r\n if (!options.status && options.harmonyosFiles === undefined && options.androidSourceFiles === undefined && options.sourceProvenance === undefined && options.testEvidence === undefined && options.difference === undefined) throw new Error(\"report update requires at least one mutable field\");\r\n const projectRoot = path.resolve(options.project);\r\n const harmonyRoot = readHarmonyRoot(projectRoot);\r\n const reportRoot = path.join(migrationDirectory(projectRoot), \"report\");\r\n const indexPath = path.join(reportRoot, \"index.json\");\r\n if (!fs.existsSync(indexPath)) throw new Error(\"Migration report is not initialized\");\r\n if (options.status && !allowedStatuses.has(options.status)) throw new Error(`Invalid report status: ${options.status}`);\r\n const index = readJson(indexPath);\r\n const reportFile = (value: string) => {\r\n if (typeof value !== \"string\" || !value.trim() || path.isAbsolute(value)) throw new Error(`Report shard path must be report-relative: ${String(value)}`);\r\n const absolute = path.resolve(reportRoot, value);\r\n const relation = path.relative(reportRoot, absolute);\r\n if (!relation || relation === \"..\" || relation.startsWith(`..${path.sep}`) || path.isAbsolute(relation)) throw new Error(`Report shard escapes report root: ${value}`);\r\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) throw new Error(`Report shard not found: ${value}`);\r\n const realRoot = fs.realpathSync(reportRoot);\r\n const realFile = fs.realpathSync(absolute);\r\n const realRelation = path.relative(realRoot, realFile);\r\n if (realRelation === \"..\" || realRelation.startsWith(`..${path.sep}`) || path.isAbsolute(realRelation)) throw new Error(`Report shard resolves outside report root: ${value}`);\r\n return realFile;\r\n };\r\n const candidates = [\r\n ...(index.pages ?? []).map((item) => item.file),\r\n index.unassignedEntriesFile,\r\n index.interactionsFile,\r\n index.discoveriesFile,\r\n ].filter(Boolean).map((file) => reportFile(file));\r\n const matches: Array<{ file: string; document: any; item: any }> = [];\r\n const visit = (file: string, document: any) => {\r\n const values = [document.page, ...(document.controls ?? []), ...(document.entries ?? []), ...(document.interactions ?? []), ...(document.items ?? [])].filter(Boolean);\r\n for (const item of values) if (item.ref === options.ref) matches.push({ file, document, item });\r\n };\r\n for (const file of candidates) if (fs.existsSync(file)) visit(file, readJson(file));\r\n if (matches.length === 0) throw new Error(`Report ref not found: ${options.ref}`);\r\n if (matches.length > 1) throw new Error(`Report ref is ambiguous: ${options.ref}`);\r\n const match = matches[0];\r\n if (options.status) match.item.status = options.status;\r\n const workspaceRoot = migrationWorkspaceRoot(projectRoot);\r\n if (options.harmonyosFiles) match.item.harmonyosFiles = [...new Set(options.harmonyosFiles.map((file) => managedHarmonyFile(projectRoot, file).relative))];\r\n if (options.androidSourceFiles) match.item.sourceProvenance = provenanceForFiles(projectRoot, options.androidSourceFiles);\r\n if (options.sourceProvenance) match.item.sourceProvenance = options.sourceProvenance;\r\n if (options.testEvidence) match.item.testEvidence = [...new Set(options.testEvidence.map((file) => insideProject(projectRoot, harmonyRoot, workspaceRoot, file, true)))];\r\n if (options.difference !== undefined) match.item.difference = options.difference?.trim() || null;\r\n if ([\"implemented\", \"verified\"].includes(match.item.status) && !match.item.harmonyosFiles?.length) throw new Error(`${match.item.status} requires at least one HarmonyOS implementation file`);\r\n if ([\"implemented\", \"verified\"].includes(match.item.status) && !match.item.sourceProvenance?.length) throw new Error(`${match.item.status} requires at least one Android source provenance entry`);\r\n if (match.item.status === \"verified\" && !match.item.testEvidence?.length) throw new Error(\"verified requires at least one test evidence file\");\r\n if (match.item.status === \"blocked\" && !match.item.difference) throw new Error(\"blocked requires --difference\");\r\n atomicJson(match.file, match.document);\r\n return { status: \"passed\", ref: options.ref, file: path.relative(projectRoot, match.file).replaceAll(\"\\\\\", \"/\"), item: match.item };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\n\r\nconst requiredScenarios = [\"success\", \"empty\", \"business-failure\", \"boundary\"];\r\n\r\nfunction validateSpec(spec: any) {\r\n const errors: string[] = [];\r\n const routeKeys = new Set<string>();\r\n if (!spec || spec.version !== 1 || !Array.isArray(spec.routes) || spec.routes.length === 0) errors.push(\"spec requires version: 1 and at least one route\");\r\n for (const [index, route] of (spec?.routes ?? []).entries()) {\r\n if (!/^(GET|POST|PUT|PATCH|DELETE)$/i.test(route.method ?? \"\")) errors.push(`routes[${index}].method is invalid`);\r\n if (typeof route.path !== \"string\" || !route.path.startsWith(\"/\")) errors.push(`routes[${index}].path must start with /`);\r\n const routeKey = `${String(route.method).toUpperCase()} ${route.path}`;\r\n if (routeKeys.has(routeKey)) errors.push(`routes[${index}] duplicates ${routeKey}`); else routeKeys.add(routeKey);\r\n for (const scenario of requiredScenarios) {\r\n const response = route.scenarios?.[scenario];\r\n if (!response || !Number.isInteger(response.status) || response.status < 100 || response.status > 599 || !(\"body\" in response)) {\r\n errors.push(`routes[${index}].scenarios.${scenario} requires status and body`);\r\n }\r\n }\r\n if (!Array.isArray(route.sourceEvidence) || route.sourceEvidence.length === 0 || route.sourceEvidence.some((value) => typeof value !== \"string\" || !value.trim())) errors.push(`routes[${index}].sourceEvidence is required; generated protocols must be grounded in Android evidence`);\r\n }\r\n return errors;\r\n}\r\n\r\nconst serverSource = `#!/usr/bin/env node\r\nimport http from \"node:http\";\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { fileURLToPath } from \"node:url\";\r\nconst root = path.dirname(fileURLToPath(import.meta.url));\r\nconst spec = JSON.parse(fs.readFileSync(path.join(root, \"scenarios.json\"), \"utf8\"));\r\nconst host = process.env.MOCK_HOST || \"0.0.0.0\";\r\nconst port = Number(process.env.MOCK_PORT || 8787);\r\nconst secret = /password|passcode|token|secret|api[-_]?key|authorization/i;\r\nconst redact = value => {\r\n if (Array.isArray(value)) return value.map(redact);\r\n if (value && typeof value === \"object\") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, secret.test(key) ? \"<redacted>\" : redact(item)]));\r\n return value;\r\n};\r\nconst safeBody = buffer => {\r\n if (!buffer.length) return \"\";\r\n try { return JSON.stringify(redact(JSON.parse(buffer.toString(\"utf8\")))); }\r\n catch { return \"<non-json body omitted; bytes=\" + buffer.length + \">\"; }\r\n};\r\nconst server = http.createServer(async (request, response) => {\r\n const url = new URL(request.url || \"/\", \"http://mock.local\");\r\n if (url.pathname === \"/health\") { response.writeHead(200, { \"content-type\": \"application/json\" }); response.end(JSON.stringify({ ok: true })); return; }\r\n const route = spec.routes.find(item => item.method.toUpperCase() === (request.method || \"GET\").toUpperCase() && item.path === url.pathname);\r\n if (!route) { response.writeHead(404, { \"content-type\": \"application/json\" }); response.end(JSON.stringify({ error: \"not_found\" })); return; }\r\n const requested = request.headers[\"x-droid2hmos-scenario\"] || url.searchParams.get(\"scenario\") || \"success\";\r\n const scenario = route.scenarios[requested];\r\n if (!scenario) { response.writeHead(400, { \"content-type\": \"application/json\" }); response.end(JSON.stringify({ error: \"unknown_scenario\", available: Object.keys(route.scenarios) })); return; }\r\n const chunks = []; for await (const chunk of request) chunks.push(chunk);\r\n const requestBody = Buffer.concat(chunks);\r\n const transcript = { at: new Date().toISOString(), method: request.method, path: url.pathname, scenario: requested, requestBody: safeBody(requestBody), status: scenario.status };\r\n fs.appendFileSync(path.join(root, \"transcript.jsonl\"), JSON.stringify(transcript) + \"\\\\n\");\r\n response.writeHead(scenario.status, { \"content-type\": \"application/json\", ...(scenario.headers || {}) });\r\n response.end(JSON.stringify(scenario.body));\r\n});\r\nserver.listen(port, host, () => console.log(JSON.stringify({ status: \"ready\", host, port })));\r\n`;\r\n\r\nexport function generateMockServer(options: { project: string; specFile: string; force?: boolean }) {\r\n const projectRoot = path.resolve(options.project);\r\n const specFile = path.resolve(options.specFile);\r\n if (!fs.existsSync(specFile)) throw new Error(`Protocol spec not found: ${specFile}`);\r\n const spec = JSON.parse(fs.readFileSync(specFile, \"utf8\"));\r\n const errors = validateSpec(spec);\r\n if (errors.length) throw new Error(`Invalid protocol spec: ${errors.join(\"; \")}`);\r\n const root = path.join(projectRoot, \"mock-server\");\r\n if (fs.existsSync(root) && fs.readdirSync(root).length && !options.force) throw new Error(`Mock server directory is not empty: ${root}; use --force to replace generated files`);\r\n fs.mkdirSync(root, { recursive: true });\r\n fs.writeFileSync(path.join(root, \"scenarios.json\"), `${JSON.stringify(spec, null, 2)}\\n`, \"utf8\");\r\n fs.writeFileSync(path.join(root, \"server.mjs\"), serverSource, \"utf8\");\r\n fs.writeFileSync(path.join(root, \"README.md\"), `# Mock Server\\n\\nGenerated from \\`${path.relative(projectRoot, specFile).replaceAll(\"\\\\\", \"/\")}\\`.\\n\\nStart safely:\\n\\n\\`\\`\\`text\\ndroid2hmos service start mock-server ${projectRoot} --health-url http://127.0.0.1:8787/health -- node server.mjs\\n\\`\\`\\`\\n\\nSelect a scenario with query parameter \\`?scenario=empty\\` or header \\`x-droid2hmos-scenario\\`.\\n`, \"utf8\");\r\n return { status: \"passed\", root, routes: spec.routes.length, scenariosPerRoute: requiredScenarios };\r\n}\r\n","import { existsSync, readFileSync, readdirSync } from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport type { CommandRunRecord } from \"../logging/command-log.ts\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\n\r\nfunction loadRecords(projectRoot: string): CommandRunRecord[] {\r\n const directory = path.join(migrationDirectory(projectRoot), \"logs\", \"daily\");\r\n if (!existsSync(directory)) return [];\r\n return readdirSync(directory).filter((file) => file.endsWith(\".jsonl\")).sort().flatMap((file) =>\r\n readFileSync(path.join(directory, file), \"utf8\").split(/\\r?\\n/).filter(Boolean).map((line) => JSON.parse(line))\r\n );\r\n}\r\n\r\nexport function queryCommandLogs(project: string, action: string, value?: string): unknown {\r\n const projectRoot = path.resolve(project);\r\n const records = loadRecords(projectRoot);\r\n if (action === \"list\") {\r\n const selected = value ? records.filter((record) => record.date === value) : records;\r\n return { schemaVersion: 1, projectRoot, count: selected.length, runs: selected.slice(-100).reverse() };\r\n }\r\n if (action === \"show\") {\r\n const record = records.find((item) => item.runId === value);\r\n if (!record) throw new Error(`Command run not found: ${value ?? \"<missing run id>\"}`);\r\n return record;\r\n }\r\n if (action === \"failures\") {\r\n const failed = records.filter((record) => record.status === \"failed\");\r\n return { schemaVersion: 1, projectRoot, count: failed.length, runs: failed.slice(-100).reverse() };\r\n }\r\n if (action === \"stats\") {\r\n const commands: Record<string, { total: number; passed: number; failed: number; durationMs: number }> = {};\r\n for (const record of records) {\r\n const item = commands[record.command] ??= { total: 0, passed: 0, failed: 0, durationMs: 0 };\r\n item.total++;\r\n item[record.status]++;\r\n item.durationMs += record.durationMs;\r\n }\r\n return { schemaVersion: 1, projectRoot, total: records.length, passed: records.filter((r) => r.status === \"passed\").length, failed: records.filter((r) => r.status === \"failed\").length, commands };\r\n }\r\n throw new Error(\"logs requires list, show, failures, or stats\");\r\n}\r\n","import { appendFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from \"node:fs\";\r\nimport { randomUUID } from \"node:crypto\";\r\nimport path from \"node:path\";\r\nimport { migrationWorkspaceRoot, ensureMigrationWorkspace } from \"../migration-paths.ts\";\r\n\r\nexport const COMMAND_LOG_SCHEMA_VERSION = 1;\r\n\r\nconst SECRET_OPTIONS = /^(--?(?:password|pass|token|secret|api[-_]?key|access[-_]?key|signing[-_]?key))$/i;\r\n\r\nexport interface CommandRunRecord {\r\n schemaVersion: 1;\r\n runId: string;\r\n date: string;\r\n startedAt: string;\r\n finishedAt: string;\r\n durationMs: number;\r\n command: string;\r\n argv: string[];\r\n projectRoot: string;\r\n workingDirectory: string;\r\n tool: { name: \"droid2hmos\"; version: string; node: string; platform: NodeJS.Platform };\r\n status: \"passed\" | \"failed\";\r\n exitCode: number;\r\n failure?: { summary: string };\r\n artifacts: Array<{ kind: string; path: string }>;\r\n}\r\n\r\nfunction localDate(date: Date): string {\r\n const part = (value: number) => String(value).padStart(2, \"0\");\r\n return `${date.getFullYear()}-${part(date.getMonth() + 1)}-${part(date.getDate())}`;\r\n}\r\n\r\nexport function redactArguments(argv: readonly string[]): string[] {\r\n const result: string[] = [];\r\n let redactNext = false;\r\n for (const argument of argv) {\r\n if (redactNext) {\r\n result.push(\"<redacted>\");\r\n redactNext = false;\r\n continue;\r\n }\r\n const equals = argument.indexOf(\"=\");\r\n if (equals > 0 && SECRET_OPTIONS.test(argument.slice(0, equals))) {\r\n result.push(`${argument.slice(0, equals)}=<redacted>`);\r\n } else {\r\n result.push(argument);\r\n redactNext = SECRET_OPTIONS.test(argument);\r\n }\r\n }\r\n return result;\r\n}\r\n\r\nexport function discoverProjectRoot(argv: readonly string[], cwd = process.cwd()): string {\r\n const valueOptions = new Set([\"--target\", \"--timeout-ms\", \"--case-timeout-ms\", \"--class\", \"--case\", \"--runner\", \"--hypium-project\", \"--test-list\", \"--python\", \"--report-path\", \"--cwd\", \"--health-url\", \"--hdc\", \"--adb\", \"--graph\", \"--sdk-path\", \"--harmony-project\", \"--android-build\", \"--android-test\", \"--task\", \"--ref\", \"--status\", \"--harmony-file\", \"--evidence\", \"--difference\", \"--message\", \"--include\", \"--name\", \"--android\", \"--harmony\", \"--spec\"]);\r\n const reserved = new Set([\"init\", \"spec\", \"report\", \"build\", \"test\", \"start-service\", \"preflight\", \"tools\", \"appgraph\", \"config\", \"checkpoint\", \"device\", \"evidence\", \"mock\", \"android\", \"harmony\", \"all\", \"capture\", \"compare\", \"flow\", \"create\", \"status\", \"complete\", \"update\", \"detect-stack\", \"check-android-build\", \"check-hmos-device\", \"check-android-emulator\", \"validate\", \"render\", \"auth\", \"login\"]);\r\n let skip = false;\r\n for (const argument of argv) {\r\n if (skip) { skip = false; continue; }\r\n if (valueOptions.has(argument)) { skip = true; continue; }\r\n if (argument.startsWith(\"-\") || reserved.has(argument)) continue;\r\n const candidate = path.resolve(cwd, argument);\r\n if (existsSync(candidate)) return candidate;\r\n }\r\n return path.resolve(cwd);\r\n}\r\n\r\nfunction knownArtifacts(projectRoot: string): Array<{ kind: string; path: string }> {\r\n const candidates = [\r\n [\"migration-config\", \".migration/config.json\"],\r\n [\"preflight-report\", \".migration/preflight-report.json\"],\r\n [\"spec-index\", \".migration/spec/index.json\"],\r\n [\"migration-report\", \".migration/report/index.json\"],\r\n [\"report-validation\", \".migration/report/validation.json\"],\r\n [\"report-html\", \".migration/report/report.html\"],\r\n [\"managed-evidence\", \".migration/evidence/index.json\"],\r\n ] as const;\r\n const workspaceRoot = migrationWorkspaceRoot(projectRoot);\r\n return candidates.filter(([, relative]) => existsSync(path.join(workspaceRoot, relative)))\r\n .map(([kind, relative]) => ({ kind, path: relative.replaceAll(\"\\\\\", \"/\") }));\r\n}\r\n\r\nfunction commandName(argv: readonly string[]): string {\r\n const command = argv[0] ?? \"unknown\";\r\n const grouped = new Set([\"analyze\", \"report\", \"build\", \"test\", \"tools\", \"config\", \"checkpoint\", \"device\", \"evidence\", \"mock\", \"service\"]);\r\n return grouped.has(command) && argv[1] ? `${command} ${argv[1]}` : command;\r\n}\r\n\r\nfunction atomicJson(file: string, value: unknown): void {\r\n const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;\r\n writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\r\n renameSync(temporary, file);\r\n}\r\n\r\nexport async function withCommandLog(\r\n argv: readonly string[],\r\n version: string,\r\n execute: () => Promise<number>,\r\n): Promise<number> {\r\n const started = new Date();\r\n const projectRoot = discoverProjectRoot(argv);\r\n let exitCode = 1;\r\n let failure: string | undefined;\r\n try {\r\n exitCode = await execute();\r\n if (exitCode !== 0) failure = `Command returned exit code ${exitCode}`;\r\n return exitCode;\r\n } catch (error) {\r\n failure = error instanceof Error ? error.message : String(error);\r\n throw error;\r\n } finally {\r\n try {\r\n const finished = new Date();\r\n const date = localDate(started);\r\n const runId = `${started.toISOString().replace(/[-:.TZ]/g, \"\").slice(0, 17)}-${randomUUID()}`;\r\n const record: CommandRunRecord = {\r\n schemaVersion: COMMAND_LOG_SCHEMA_VERSION,\r\n runId,\r\n date,\r\n startedAt: started.toISOString(),\r\n finishedAt: finished.toISOString(),\r\n durationMs: finished.getTime() - started.getTime(),\r\n command: commandName(argv),\r\n argv: redactArguments(argv),\r\n projectRoot,\r\n workingDirectory: process.cwd(),\r\n tool: { name: \"droid2hmos\", version, node: process.version, platform: process.platform },\r\n status: exitCode === 0 && !failure ? \"passed\" : \"failed\",\r\n exitCode,\r\n ...(failure ? { failure: { summary: failure } } : {}),\r\n artifacts: knownArtifacts(projectRoot),\r\n };\r\n ensureMigrationWorkspace(projectRoot);\r\n const logsRoot = path.join(migrationWorkspaceRoot(projectRoot), \".migration\", \"logs\");\r\n const runDirectory = path.join(logsRoot, \"runs\", date);\r\n const dailyDirectory = path.join(logsRoot, \"daily\");\r\n mkdirSync(runDirectory, { recursive: true });\r\n mkdirSync(dailyDirectory, { recursive: true });\r\n atomicJson(path.join(runDirectory, `${runId}.json`), record);\r\n appendFileSync(path.join(dailyDirectory, `${date}.jsonl`), `${JSON.stringify(record)}\\n`, \"utf8\");\r\n atomicJson(path.join(logsRoot, \"index.json\"), {\r\n schemaVersion: COMMAND_LOG_SCHEMA_VERSION,\r\n lastRunId: runId,\r\n lastRun: path.relative(path.dirname(logsRoot), path.join(runDirectory, `${runId}.json`)).replaceAll(\"\\\\\", \"/\"),\r\n updatedAt: finished.toISOString(),\r\n });\r\n } catch (logError) {\r\n console.error(`warning: failed to write command log: ${logError instanceof Error ? logError.message : String(logError)}`);\r\n }\r\n }\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { fileURLToPath } from \"node:url\";\r\n\r\nexport interface RuntimePaths {\r\n entryFile: string;\r\n runtimeRoot: string;\r\n packageRoot?: string;\r\n templatesRoot?: string;\r\n preflightChecklistPath?: string;\r\n}\r\n\r\nexport function resolveRuntimePaths(entryUrl: string): RuntimePaths {\r\n const entryFile = fileURLToPath(entryUrl);\r\n const directory = path.dirname(entryFile);\r\n const roots = [path.resolve(directory, \"..\"), directory];\r\n const packageRoot = roots.find((candidate) => fs.existsSync(path.join(candidate, \"package.json\")));\r\n const runtimeRoot = packageRoot ?? path.resolve(directory, \"..\");\r\n const templatesRoot = [\r\n packageRoot && path.join(packageRoot, \"templates\"),\r\n ].filter(Boolean).find((candidate) => fs.existsSync(candidate));\r\n const preflightChecklistPath = packageRoot && path.join(packageRoot, \"config\", \"preflight-checklist.json\");\r\n return { entryFile, runtimeRoot, packageRoot, templatesRoot, preflightChecklistPath };\r\n}\r\n","import { createHash, randomUUID } from \"node:crypto\";\r\nimport { execFileSync } from \"node:child_process\";\r\nimport fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { validateMigrationReport } from \"../commands/validate-migration-report.ts\";\r\nimport { defaultHarmonyProjectPath } from \"../commands/android-project-name.ts\";\r\nimport { migrationDirectory, migrationWorkspaceRoot } from \"../migration-paths.ts\";\r\nimport { taskPlanning, type TaskPlanSnapshot } from \"../planning/index.ts\";\r\n\r\nexport const KERNEL_VERSION = \"1.2.0\";\r\nexport const POLICY_VERSION = \"1.2.0\";\r\n\r\nexport type GuardMode = \"enforce\" | \"shadow\";\r\nexport type GuardDecision = \"allow\" | \"deny\";\r\n\r\nexport interface UnmetCondition {\r\n code: string;\r\n message: string;\r\n}\r\n\r\nexport interface MigrationSnapshot {\r\n kernelVersion: string;\r\n policyVersion: string;\r\n projectRoot: string;\r\n phase: string;\r\n workspace: {\r\n projectPresent: boolean;\r\n androidProject: string;\r\n projectCandidates: string[];\r\n configPresent: boolean;\r\n harmonyProject: string;\r\n harmonyProjectPresent: boolean;\r\n gitHead: string | null;\r\n };\r\n preflight: { present: boolean; result: string; harmonyDevice: string };\r\n source: { factsSha256: string | null; androidFingerprint: string | null; harmonyFingerprint: string | null };\r\n report: { present: boolean; version: string | null; valid: boolean; complete: boolean; errors: string[]; completionErrors: string[]; warnings: string[]; evidenceLevel: string | null; sourceManifest: any; orderAudit: any; closureAudit: any; literalAudit: any };\r\n planning: TaskPlanSnapshot;\r\n evidence: {\r\n androidAnalysis: EvidenceState;\r\n fullRegression: EvidenceState;\r\n claimCoverage: { valid: boolean; missing: Array<{ ref: string; reason: string }> };\r\n };\r\n completion: { eligible: boolean; unmet: UnmetCondition[] };\r\n allowedActions: string[];\r\n}\r\n\r\nexport interface ManagedEvidenceReceipt {\r\n evidenceVersion: \"1.1.0\";\r\n id: string;\r\n producer: \"droid2hmos\";\r\n kind: \"command\" | \"build\" | \"harmony-test\";\r\n action: string;\r\n scope: Record<string, unknown> | null;\r\n status: string;\r\n recordedAt: string;\r\n idempotencyKey: string;\r\n source: {\r\n gitHead: string | null;\r\n factsSha256: string | null;\r\n androidFingerprint: string | null;\r\n harmonyFingerprint: string | null;\r\n };\r\n guard: { mode: GuardMode; decision: GuardDecision; policyDecision: GuardDecision } | null;\r\n retry: { kind: string; retry: string; maxAutomaticAttempts: number; remediation?: string; reason?: string };\r\n resultDigest: string;\r\n result: Record<string, unknown> | null;\r\n artifacts: Array<{ path: string; source: string; sha256: string; size: number }>;\r\n}\r\n\r\nexport interface EvidenceState {\r\n reference: string | null;\r\n present: boolean;\r\n passed: boolean;\r\n fresh: boolean;\r\n}\r\n\r\nexport interface GuardResult {\r\n kernelVersion: string;\r\n policyVersion: string;\r\n action: string;\r\n mode: GuardMode;\r\n decision: GuardDecision;\r\n policyDecision: GuardDecision;\r\n hardGate: boolean;\r\n unmet: UnmetCondition[];\r\n}\r\n\r\nconst actions = [\r\n \"preflight\",\r\n \"config:init\",\r\n \"config:validate\",\r\n \"init\",\r\n \"analyze:android\",\r\n \"analyze:harmony\",\r\n \"build:harmony\",\r\n \"test:harmony:targeted\",\r\n \"test:harmony:all\",\r\n \"report:init\",\r\n \"report:update\",\r\n \"report:validate\",\r\n \"report:render\",\r\n \"task:plan\",\r\n \"task:validate\",\r\n \"checkpoint:status\",\r\n \"checkpoint:create\",\r\n \"device:check\",\r\n \"evidence:capture\",\r\n \"evidence:compare\",\r\n \"evidence:flow\",\r\n \"mock:init\",\r\n \"service:start\",\r\n \"service:status\",\r\n \"service:stop\",\r\n \"complete\",\r\n] as const;\r\n\r\nconst ignoredDirectories = new Set([\".git\", \".gradle\", \".hvigor\", \".idea\", \".migration\", \".codegraph-appgraph\", \"build\", \"node_modules\", \"oh_modules\"]);\r\n\r\nfunction readJson(file: string): any | null {\r\n try { return JSON.parse(fs.readFileSync(file, \"utf8\")); }\r\n catch { return null; }\r\n}\r\n\r\nfunction stableJson(value: any): string {\r\n if (value === undefined) return \"null\";\r\n if (Array.isArray(value)) return `[${value.map(stableJson).join(\",\")}]`;\r\n if (value && typeof value === \"object\") {\r\n return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(\",\")}}`;\r\n }\r\n return JSON.stringify(value);\r\n}\r\n\r\nfunction sha256(value: any): string {\r\n return createHash(\"sha256\").update(typeof value === \"string\" ? value : stableJson(value)).digest(\"hex\");\r\n}\r\n\r\nfunction hashDirectory(root: string | null, excludedRoots: string[] = []): string | null {\r\n if (!root || !fs.existsSync(root) || !fs.statSync(root).isDirectory()) return null;\r\n const excluded = excludedRoots.map((value) => path.resolve(value));\r\n const hash = createHash(\"sha256\");\r\n const visit = (directory: string) => {\r\n const entries = fs.readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));\r\n for (const entry of entries) {\r\n const absolute = path.join(directory, entry.name);\r\n if (entry.isDirectory() && (ignoredDirectories.has(entry.name) || excluded.some((value) => absolute === value || absolute.startsWith(`${value}${path.sep}`)))) continue;\r\n if (entry.name === \".DS_Store\") continue;\r\n const relative = path.relative(root, absolute).replaceAll(\"\\\\\", \"/\");\r\n if (entry.isDirectory()) {\r\n hash.update(`d:${relative}\\0`);\r\n visit(absolute);\r\n } else if (entry.isSymbolicLink()) {\r\n hash.update(`l:${relative}\\0${fs.readlinkSync(absolute)}\\0`);\r\n } else if (entry.isFile()) {\r\n hash.update(`f:${relative}\\0`);\r\n hash.update(fs.readFileSync(absolute));\r\n hash.update(\"\\0\");\r\n }\r\n }\r\n };\r\n visit(root);\r\n return hash.digest(\"hex\");\r\n}\r\n\r\nfunction gitHead(projectRoot: string): string | null {\r\n try {\r\n return execFileSync(\"git\", [\"rev-parse\", \"HEAD\"], { cwd: projectRoot, encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"] }).trim() || null;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nfunction harmonyProjectFor(projectRoot: string, config: any): string {\r\n const configured = config?.harmonyProject ?? defaultHarmonyProjectPath(projectRoot);\r\n return path.isAbsolute(configured) ? configured : path.resolve(projectRoot, configured);\r\n}\r\n\r\nfunction androidProjectFor(projectRoot: string, config: any): string {\r\n const configured = config?.androidProject ?? projectRoot;\r\n return path.isAbsolute(configured) ? configured : path.resolve(projectRoot, configured);\r\n}\r\n\r\nfunction isAndroidProject(root: string): boolean {\r\n if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return false;\r\n const hasBuildRoot = [\"settings.gradle\", \"settings.gradle.kts\", \"build.gradle\", \"build.gradle.kts\", \"gradlew\", \"gradlew.bat\"]\r\n .some((name) => fs.existsSync(path.join(root, name)));\r\n if (!hasBuildRoot) return false;\r\n if (fs.existsSync(path.join(root, \"app\", \"src\", \"main\", \"AndroidManifest.xml\"))) return true;\r\n return fs.readdirSync(root, { withFileTypes: true }).some((entry) => entry.isDirectory()\r\n && !ignoredDirectories.has(entry.name)\r\n && fs.existsSync(path.join(root, entry.name, \"src\", \"main\", \"AndroidManifest.xml\")));\r\n}\r\n\r\nfunction androidProjectCandidates(root: string): string[] {\r\n if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return [];\r\n return fs.readdirSync(root, { withFileTypes: true })\r\n .filter((entry) => entry.isDirectory() && !ignoredDirectories.has(entry.name))\r\n .map((entry) => path.join(root, entry.name))\r\n .filter(isAndroidProject)\r\n .sort();\r\n}\r\n\r\nfunction evidenceRoot(projectRoot: string): string {\r\n return path.join(migrationDirectory(projectRoot), \"evidence\");\r\n}\r\n\r\nfunction evidenceIndex(projectRoot: string): any {\r\n return readJson(path.join(evidenceRoot(projectRoot), \"index.json\")) ?? { evidenceIndexVersion: \"1.0.0\", latestByAction: {} };\r\n}\r\n\r\nfunction projectRelative(projectRoot: string, absolute: string): string {\r\n return path.relative(projectRoot, absolute).replaceAll(\"\\\\\", \"/\");\r\n}\r\n\r\nfunction workspaceRelative(projectRoot: string, absolute: string): string {\r\n return path.relative(migrationWorkspaceRoot(projectRoot), absolute).replaceAll(\"\\\\\", \"/\");\r\n}\r\n\r\nfunction managedReceipt(projectRoot: string, reference: unknown): any | null {\r\n if (typeof reference !== \"string\" || !reference.trim()) return null;\r\n const root = path.resolve(evidenceRoot(projectRoot), \"managed\");\r\n const absolute = path.resolve(migrationWorkspaceRoot(projectRoot), reference);\r\n if (absolute !== root && !absolute.startsWith(`${root}${path.sep}`)) return null;\r\n return readJson(absolute);\r\n}\r\n\r\nfunction reportClaims(projectRoot: string, reportIndex: any): Array<{ ref: string; source: string; status: string; evidence: string[]; discovery?: boolean }> {\r\n if (!reportIndex) return [];\r\n const reportRoot = path.join(migrationDirectory(projectRoot), \"report\");\r\n const claims: Array<{ ref: string; source: string; status: string; evidence: string[]; discovery?: boolean }> = [];\r\n const addItems = (items: any[], source: string, discovery = false) => {\r\n for (const item of items ?? []) claims.push({\r\n ref: item?.ref ?? `${source}:unknown`,\r\n source,\r\n status: item?.status ?? \"unknown\",\r\n evidence: Array.isArray(item?.testEvidence) ? item.testEvidence : [],\r\n discovery,\r\n });\r\n };\r\n for (const descriptor of reportIndex.pages ?? []) {\r\n const shard = readJson(path.join(reportRoot, descriptor.file));\r\n if (!shard) continue;\r\n addItems([shard.page], descriptor.file);\r\n addItems(shard.controls, descriptor.file);\r\n addItems(shard.entries, descriptor.file);\r\n }\r\n if (reportIndex.unassignedEntriesFile) addItems(readJson(path.join(reportRoot, reportIndex.unassignedEntriesFile))?.entries, reportIndex.unassignedEntriesFile);\r\n if (reportIndex.interactionsFile) addItems(readJson(path.join(reportRoot, reportIndex.interactionsFile))?.interactions, reportIndex.interactionsFile);\r\n if (reportIndex.discoveriesFile) addItems(readJson(path.join(reportRoot, reportIndex.discoveriesFile))?.items, \"discoveries\", true);\r\n const acceptance = reportIndex.finalAcceptanceFile ? readJson(path.join(reportRoot, reportIndex.finalAcceptanceFile)) : null;\r\n for (const [index, test] of (acceptance?.tests ?? []).entries()) claims.push({\r\n ref: test?.ref ?? `final-acceptance:${test?.name ?? index + 1}`,\r\n source: reportIndex.finalAcceptanceFile,\r\n status: test?.status === \"passed\" ? \"verified\" : \"failed\",\r\n evidence: Array.isArray(test?.evidence) ? test.evidence : [],\r\n });\r\n return claims;\r\n}\r\n\r\nfunction receiptArtifactsAreIntact(projectRoot: string, receipt: any): boolean {\r\n if (!Array.isArray(receipt?.artifacts) || receipt.artifacts.length === 0) return false;\r\n const blobsRoot = path.resolve(evidenceRoot(projectRoot), \"blobs\");\r\n return receipt.artifacts.every((artifact: any) => {\r\n if (!artifact || typeof artifact.path !== \"string\" || !/^[a-f0-9]{64}$/.test(artifact.sha256) || !Number.isInteger(artifact.size)) return false;\r\n const absolute = path.resolve(migrationWorkspaceRoot(projectRoot), artifact.path);\r\n if (!absolute.startsWith(`${blobsRoot}${path.sep}`) || !fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) return false;\r\n const content = fs.readFileSync(absolute);\r\n return content.byteLength === artifact.size && createHash(\"sha256\").update(content).digest(\"hex\") === artifact.sha256;\r\n });\r\n}\r\n\r\nfunction testReceiptIsFresh(receipt: any, snapshot: MigrationSnapshot): boolean {\r\n const tests = receipt?.result?.tests;\r\n const target = receipt?.scope?.target;\r\n return Boolean(\r\n receipt?.producer === \"droid2hmos\"\r\n && receipt?.kind === \"harmony-test\"\r\n && receipt?.evidenceVersion === \"1.1.0\"\r\n && receipt?.status === \"passed\"\r\n && typeof target === \"string\" && target.trim()\r\n && receipt?.result?.target === target\r\n && tests?.valid === true\r\n && Number.isInteger(tests.total) && tests.total > 0\r\n && tests.passed === tests.total\r\n && tests.failed === 0 && tests.errors === 0 && tests.ignored === 0\r\n && receipt?.source?.harmonyFingerprint\r\n && receipt.source.harmonyFingerprint === snapshot.source.harmonyFingerprint\r\n && receipt?.source?.factsSha256\r\n && receipt.source.factsSha256 === snapshot.source.factsSha256\r\n && receiptArtifactsAreIntact(snapshot.projectRoot, receipt)\r\n );\r\n}\r\n\r\nfunction analysisReceiptIsFresh(receipt: any, snapshot: MigrationSnapshot): boolean {\r\n return Boolean(\r\n receipt?.producer === \"droid2hmos\"\r\n && receipt?.action === \"analyze:android\"\r\n && receipt?.status === \"passed\"\r\n && receipt?.source?.androidFingerprint\r\n && receipt.source.androidFingerprint === snapshot.source.androidFingerprint\r\n && receipt?.source?.factsSha256\r\n && receipt.source.factsSha256 === snapshot.source.factsSha256\r\n );\r\n}\r\n\r\nfunction inspectEvidenceCoverage(projectRoot: string, snapshot: MigrationSnapshot, claims: ReturnType<typeof reportClaims>) {\r\n const missing: Array<{ ref: string; reason: string }> = [];\r\n for (const claim of claims) {\r\n if (claim.discovery && claim.status !== \"verified\") {\r\n missing.push({ ref: claim.ref, reason: `AI 补充发现尚未验证,当前状态为 ${claim.status}` });\r\n continue;\r\n }\r\n if (claim.status !== \"verified\") continue;\r\n const receipts = claim.evidence.map((reference) => managedReceipt(projectRoot, reference)).filter(Boolean);\r\n const fresh = receipts.filter((receipt) => testReceiptIsFresh(receipt, snapshot));\r\n if (!fresh.length) {\r\n missing.push({ ref: claim.ref, reason: \"缺少结果有效、产物完整且与当前 facts 和 HarmonyOS 源码一致的受管测试证据\" });\r\n } else if (!fresh.some((receipt) => Array.isArray(receipt?.scope?.coveredRefs) && receipt.scope.coveredRefs.includes(claim.ref))) {\r\n missing.push({ ref: claim.ref, reason: \"新鲜的受管测试证据未声明覆盖此 ref\" });\r\n }\r\n }\r\n return { valid: missing.length === 0, missing };\r\n}\r\n\r\nconst unmet = (code: string, message: string): UnmetCondition => ({ code, message });\r\n\r\nfunction actionRequirements(action: string, snapshot: MigrationSnapshot): UnmetCondition[] {\r\n const missing: UnmetCondition[] = [];\r\n const requireProject = () => {\r\n if (!snapshot.workspace.projectPresent) {\r\n const candidates = snapshot.workspace.projectCandidates.length ? `;候选项目: ${snapshot.workspace.projectCandidates.join(\", \")}` : \"\";\r\n missing.push(unmet(\"project-missing\", `指定目录不是有效的 Android Gradle 项目${candidates}`));\r\n }\r\n };\r\n const requireConfig = () => { if (!snapshot.workspace.configPresent) missing.push(unmet(\"config-missing\", \"缺少 .migration/config.json\")); };\r\n const requireHarmony = () => { if (!snapshot.workspace.harmonyProjectPresent) missing.push(unmet(\"harmony-project-missing\", \"HarmonyOS 工程不存在\")); };\r\n const requireFacts = () => { if (!snapshot.source.factsSha256) missing.push(unmet(\"facts-missing\", \"缺少确定性 facts\")); };\r\n const requireReport = () => { if (!snapshot.report.present) missing.push(unmet(\"report-missing\", \"迁移报告尚未初始化\")); };\r\n const requireFreshAnalysis = () => { if (!snapshot.evidence.androidAnalysis.fresh) missing.push(unmet(\"android-analysis-missing-or-stale\", \"缺少与当前 Android 源码及 facts 一致的受管分析证据\")); };\r\n\r\n if (![\"device:check\", \"service:status\", \"service:stop\"].includes(action)) requireProject();\r\n if (action === \"config:init\" && snapshot.workspace.configPresent) missing.push(unmet(\"config-present\", \".migration/config.json 已存在\"));\r\n if (action === \"config:validate\") requireConfig();\r\n if (action === \"init\" && snapshot.workspace.harmonyProjectPresent) missing.push(unmet(\"harmony-project-present\", \"HarmonyOS 工程已存在,无需重复初始化\"));\r\n if ([\"analyze:android\", \"analyze:harmony\", \"build:harmony\", \"test:harmony:targeted\", \"test:harmony:all\", \"evidence:flow\"].includes(action)) requireConfig();\r\n if ([\"analyze:harmony\", \"build:harmony\", \"test:harmony:targeted\", \"test:harmony:all\"].includes(action)) requireHarmony();\r\n if (action === \"report:init\") {\r\n requireFacts();\r\n if (snapshot.report.present && snapshot.report.version !== \"1.1.0\") missing.push(unmet(\"report-present\", \"迁移报告已存在,无需重复初始化\"));\r\n }\r\n if ([\"report:update\", \"report:validate\", \"report:render\"].includes(action)) requireReport();\r\n if (action === \"task:plan\") {\r\n requireConfig(); requireFacts(); requireReport(); requireFreshAnalysis();\r\n if (snapshot.planning.present && snapshot.planning.valid && snapshot.planning.fresh) {\r\n const message = snapshot.planning.planningPhase === \"execution\"\r\n ? \"已有新鲜的冻结 Execution Plan;实现阶段必须严格执行现有 Page Work Package,禁止动态 task plan\"\r\n : \"已有新鲜的 Resolution Plan;必须先写入有效 correction/review 使计划过期,再重新 task plan\";\r\n missing.push(unmet(\"task-plan-already-fresh\", message));\r\n }\r\n }\r\n if (action === \"task:validate\" && !snapshot.planning.present) missing.push(unmet(\"task-plan-missing\", \"Task Plan 尚未生成\"));\r\n if (action === \"checkpoint:create\") {\r\n if (!snapshot.workspace.gitHead) missing.push(unmet(\"git-missing\", \"Git 基线不存在,不能创建受管检查点\"));\r\n if (!snapshot.report.present) missing.push(unmet(\"report-missing\", \"迁移报告尚未初始化,不能创建受管检查点\"));\r\n else if (!snapshot.report.valid) missing.push(unmet(\"source-governance-invalid\", \"迁移报告源码溯源或结构校验失败,不能创建受管检查点\"));\r\n }\r\n if (action === \"complete\") missing.push(...snapshot.completion.unmet);\r\n return missing;\r\n}\r\n\r\nfunction derivePhase(snapshot: MigrationSnapshot): string {\r\n if (!snapshot.workspace.configPresent || !snapshot.workspace.harmonyProjectPresent) return \"workspace-preparation\";\r\n if (snapshot.preflight.result !== \"passed\") return \"preflight\";\r\n if (!snapshot.source.factsSha256 || !snapshot.evidence.androidAnalysis.fresh) return \"analysis\";\r\n if (!snapshot.report.present) return \"report-initialization\";\r\n if (!snapshot.planning.present || !snapshot.planning.valid || !snapshot.planning.fresh) return \"task-planning\";\r\n if (snapshot.completion.eligible) return \"ready-to-complete\";\r\n if (snapshot.report.complete) return \"verification\";\r\n return \"implementation\";\r\n}\r\n\r\nexport function inspectMigration(project = \".\"): MigrationSnapshot {\r\n const projectRoot = path.resolve(project);\r\n const migrationRoot = migrationDirectory(projectRoot);\r\n const config = readJson(path.join(migrationRoot, \"config.json\"));\r\n const harmonyProject = harmonyProjectFor(projectRoot, config);\r\n const androidProject = androidProjectFor(projectRoot, config);\r\n const projectPresent = isAndroidProject(androidProject);\r\n const projectCandidates = projectPresent ? [] : androidProjectCandidates(projectRoot);\r\n const preflight = readJson(path.join(migrationRoot, \"preflight-report.json\"));\r\n const specIndex = readJson(path.join(migrationRoot, \"spec\", \"index.json\"));\r\n const reportIndex = readJson(path.join(migrationRoot, \"report\", \"index.json\"));\r\n let validation: any;\r\n try {\r\n validation = validateMigrationReport([projectRoot], { writeResult: false });\r\n } catch (error) {\r\n validation = {\r\n valid: false,\r\n complete: false,\r\n errors: [`迁移报告无法读取: ${error instanceof Error ? error.message : String(error)}`],\r\n completionErrors: [],\r\n };\r\n }\r\n const index = evidenceIndex(projectRoot);\r\n const snapshot: MigrationSnapshot = {\r\n kernelVersion: KERNEL_VERSION,\r\n policyVersion: POLICY_VERSION,\r\n projectRoot,\r\n phase: \"unknown\",\r\n workspace: {\r\n projectPresent,\r\n androidProject,\r\n projectCandidates,\r\n configPresent: Boolean(config),\r\n harmonyProject,\r\n harmonyProjectPresent: fs.existsSync(harmonyProject) && fs.statSync(harmonyProject).isDirectory(),\r\n gitHead: projectPresent ? gitHead(androidProject) : null,\r\n },\r\n preflight: {\r\n present: Boolean(preflight),\r\n result: preflight?.result ?? \"missing\",\r\n harmonyDevice: preflight?.checks?.find((check: any) => check.id === \"harmony-device\")?.status ?? \"missing\",\r\n },\r\n source: {\r\n factsSha256: specIndex?.factsSha256 ?? null,\r\n androidFingerprint: projectPresent ? hashDirectory(androidProject, [harmonyProject]) : null,\r\n harmonyFingerprint: hashDirectory(harmonyProject),\r\n },\r\n report: {\r\n present: Boolean(reportIndex),\r\n version: reportIndex?.reportVersion ?? null,\r\n valid: Boolean(validation.valid),\r\n complete: Boolean(validation.complete),\r\n errors: validation.errors ?? [],\r\n completionErrors: validation.completionErrors ?? [],\r\n warnings: validation.warnings ?? [],\r\n evidenceLevel: validation.evidenceLevel ?? null,\r\n sourceManifest: validation.sourceManifest ?? null,\r\n orderAudit: validation.orderAudit ?? null,\r\n closureAudit: validation.closureAudit ?? null,\r\n literalAudit: validation.literalAudit ?? null,\r\n },\r\n planning: {\r\n present: false,\r\n valid: false,\r\n fresh: false,\r\n taskPlanSha256: null,\r\n planningPhase: null,\r\n totalTasks: 0,\r\n resolutionTasks: 0,\r\n totalTargets: 0,\r\n readyTargets: 0,\r\n completedTargets: 0,\r\n readyTasks: 0,\r\n blockedTasks: 0,\r\n completedTasks: 0,\r\n recommendedTargetId: null,\r\n recommendedTaskId: null,\r\n alternatives: [],\r\n reasons: {},\r\n ownershipCoverage: 0,\r\n closureCoverage: 0,\r\n orphanFactRefs: [],\r\n errors: [],\r\n warnings: [],\r\n tasks: [],\r\n targets: [],\r\n },\r\n evidence: {\r\n androidAnalysis: { reference: null, present: false, passed: false, fresh: false },\r\n fullRegression: { reference: null, present: false, passed: false, fresh: false },\r\n claimCoverage: { valid: false, missing: [] },\r\n },\r\n completion: { eligible: false, unmet: [] },\r\n allowedActions: [],\r\n };\r\n\r\n const analysisReference = index.latestByAction?.[\"analyze:android\"] ?? null;\r\n const analysisReceipt = managedReceipt(projectRoot, analysisReference);\r\n snapshot.evidence.androidAnalysis = {\r\n reference: analysisReference,\r\n present: Boolean(analysisReceipt),\r\n passed: analysisReceipt?.status === \"passed\",\r\n fresh: analysisReceiptIsFresh(analysisReceipt, snapshot),\r\n };\r\n const fullReference = index.latestByAction?.[\"test:harmony:all\"] ?? null;\r\n const fullReceipt = managedReceipt(projectRoot, fullReference);\r\n snapshot.evidence.fullRegression = {\r\n reference: fullReference,\r\n present: Boolean(fullReceipt),\r\n passed: fullReceipt?.status === \"passed\",\r\n fresh: Boolean(fullReceipt?.action === \"test:harmony:all\" && fullReceipt?.scope?.fullRun === true && testReceiptIsFresh(fullReceipt, snapshot)),\r\n };\r\n snapshot.evidence.claimCoverage = inspectEvidenceCoverage(projectRoot, snapshot, reportClaims(projectRoot, reportIndex));\r\n snapshot.planning = taskPlanning.inspect(projectRoot, {\r\n androidFingerprint: snapshot.source.androidFingerprint,\r\n harmonyFingerprint: snapshot.source.harmonyFingerprint,\r\n fullRegressionFresh: snapshot.evidence.fullRegression.fresh,\r\n });\r\n\r\n const completionUnmet: UnmetCondition[] = [];\r\n if (snapshot.preflight.result !== \"passed\") completionUnmet.push(unmet(\"preflight-not-passed\", \"Preflight 尚未通过\"));\r\n if (snapshot.preflight.harmonyDevice !== \"passed\") completionUnmet.push(unmet(\"harmony-device-not-passed\", \"Preflight 没有已通过的 HarmonyOS 设备检查\"));\r\n if (!snapshot.source.factsSha256) completionUnmet.push(unmet(\"facts-missing\", \"缺少确定性 facts\"));\r\n if (!snapshot.evidence.androidAnalysis.fresh) completionUnmet.push(unmet(\"android-analysis-missing-or-stale\", \"缺少与当前 Android 源码及 facts 一致的受管分析证据\"));\r\n if (!snapshot.report.present) completionUnmet.push(unmet(\"report-missing\", \"迁移报告尚未初始化\"));\r\n else {\r\n if (!snapshot.report.valid) completionUnmet.push(unmet(\"report-invalid\", \"迁移报告结构或映射校验失败\"));\r\n if (!snapshot.report.complete) completionUnmet.push(unmet(\"report-incomplete\", \"迁移报告仍有未完成项\"));\r\n }\r\n if (!snapshot.planning.present) completionUnmet.push(unmet(\"task-plan-missing\", \"Task Plan 尚未生成\"));\r\n else {\r\n if (!snapshot.planning.valid) completionUnmet.push(unmet(\"task-plan-invalid\", \"Task Plan 完整性校验失败\"));\r\n if (!snapshot.planning.fresh) completionUnmet.push(unmet(\"task-plan-stale\", \"Task Plan 与当前 Facts、审核输入或 Android 源码不一致\"));\r\n if (snapshot.planning.completedTasks !== snapshot.planning.totalTasks) completionUnmet.push(unmet(\"task-plan-incomplete\", `${snapshot.planning.totalTasks - snapshot.planning.completedTasks} 个内部 Work Item 尚未取得新鲜定向验证证据`));\r\n if (snapshot.planning.orphanFactRefs.length) completionUnmet.push(unmet(\"task-plan-orphans\", `${snapshot.planning.orphanFactRefs.length} 个必要 Fact 没有主所有权`));\r\n }\r\n if (!snapshot.evidence.fullRegression.fresh) completionUnmet.push(unmet(\"full-regression-missing-or-stale\", \"缺少与当前 facts 和 HarmonyOS 源码一致的全量受管回归证据\"));\r\n if (!snapshot.evidence.claimCoverage.valid) {\r\n const examples = snapshot.evidence.claimCoverage.missing.slice(0, 3).map((item) => `${item.ref}: ${item.reason}`).join(\"; \");\r\n completionUnmet.push(unmet(\"claim-evidence-missing-or-stale\", `${snapshot.evidence.claimCoverage.missing.length} 个完成声明缺少有效覆盖${examples ? `(${examples})` : \"\"}`));\r\n }\r\n snapshot.completion = { eligible: completionUnmet.length === 0, unmet: completionUnmet };\r\n snapshot.phase = derivePhase(snapshot);\r\n snapshot.allowedActions = actions.filter((action) => actionRequirements(action, snapshot).length === 0);\r\n return snapshot;\r\n}\r\n\r\nexport function guardMigrationAction(options: { action: string; snapshot: MigrationSnapshot; mode?: GuardMode }): GuardResult {\r\n if (!(actions as readonly string[]).includes(options.action)) throw new Error(`未知的迁移动作: ${options.action}`);\r\n const mode: GuardMode = options.mode === \"shadow\" ? \"shadow\" : \"enforce\";\r\n const missing = actionRequirements(options.action, options.snapshot);\r\n const policyDecision: GuardDecision = missing.length ? \"deny\" : \"allow\";\r\n const hardGate = options.action === \"complete\" || options.action === \"checkpoint:create\";\r\n const decision: GuardDecision = policyDecision === \"deny\" && mode === \"shadow\" && !hardGate ? \"allow\" : policyDecision;\r\n return {\r\n kernelVersion: KERNEL_VERSION,\r\n policyVersion: POLICY_VERSION,\r\n action: options.action,\r\n mode,\r\n decision,\r\n policyDecision,\r\n hardGate,\r\n unmet: missing,\r\n };\r\n}\r\n\r\n// 环境类门禁只探测一次:这些检查依赖本机工具、账号授权或物理设备,Agent 原样重跑\r\n// preflight 不会自愈。失败时应归为 external 并给出 remediation,由 Agent 提示用户修改环境。\r\nconst ENVIRONMENT_PREFLIGHT_CHECKS = new Set([\"toolchain\", \"devecocli-auth\", \"appgraph\", \"harmony-sdk\", \"harmony-device\"]);\r\n\r\nfunction failedCheckEntries(result: any): any[] {\r\n if (!Array.isArray(result?.checks)) return [];\r\n return result.checks.filter((check: any) => check && check.required !== false && check.status !== \"passed\" && check.status !== \"skipped\" && check.status !== \"not_applicable\");\r\n}\r\n\r\nfunction environmentRemediation(result: any, failedChecks: string[]): string | undefined {\r\n const declared = failedCheckEntries(result).find((check) => check.retry?.remediation)?.retry?.remediation;\r\n if (declared) return declared;\r\n const environment = failedChecks.filter((id) => ENVIRONMENT_PREFLIGHT_CHECKS.has(id));\r\n return environment.length ? `环境类门禁未通过(${environment.join(\"、\")})。请先修复本机迁移环境,再重新运行 droid2hmos preflight,不要原样重复执行。` : undefined;\r\n}\r\n\r\nfunction classifyFailure(action: string, result: any) {\r\n if (result?.status === \"passed\" || result?.status === \"not_applicable\") return { kind: \"none\", retry: \"not-needed\", maxAutomaticAttempts: 0 };\r\n if (result?.status === \"rejected\") return { kind: \"policy\", retry: \"after-input-change\", maxAutomaticAttempts: 0 };\r\n const values: any[] = [];\r\n const visit = (value: any) => {\r\n if (!value || typeof value !== \"object\" || values.includes(value)) return;\r\n values.push(value);\r\n for (const child of Object.values(value)) visit(child);\r\n };\r\n visit(result);\r\n if (values.some((value) => value?.timedOut || value?.error?.code === \"ETIMEDOUT\")) return { kind: \"transient\", retry: \"bounded\", maxAutomaticAttempts: 1 };\r\n const failedChecks = Array.isArray(result?.failedChecks) ? result.failedChecks : [];\r\n const environmentFailure = result?.stage === \"device\"\r\n || failedChecks.some((id: string) => ENVIRONMENT_PREFLIGHT_CHECKS.has(id))\r\n || failedCheckEntries(result).some((check) => check.retry?.kind === \"external\")\r\n || /device|hdc|签名|授权|多个 HarmonyOS 设备/i.test(String(result?.summary ?? \"\"));\r\n if (environmentFailure) {\r\n const remediation = environmentRemediation(result, failedChecks);\r\n return { kind: \"external\", retry: \"after-environment-change\", maxAutomaticAttempts: 0, ...(remediation ? { remediation } : {}) };\r\n }\r\n if (action.startsWith(\"build:\") || action.startsWith(\"test:\")) return { kind: \"deterministic\", retry: \"after-diagnosis\", maxAutomaticAttempts: 0 };\r\n if (action === \"preflight\" && failedChecks.length) return { kind: \"deterministic\", retry: \"after-diagnosis\", maxAutomaticAttempts: 0 };\r\n return { kind: \"unknown\", retry: \"agent-decision\", maxAutomaticAttempts: 0 };\r\n}\r\n\r\nfunction observationStatus(result: any): string {\r\n if (typeof result?.status === \"string\") return result.status;\r\n if (result?.ok === true || result?.valid === true || result?.exitCode === 0) return \"passed\";\r\n if (result?.ok === false || result?.valid === false || (typeof result?.exitCode === \"number\" && result.exitCode !== 0)) return \"failed\";\r\n return \"observed\";\r\n}\r\n\r\nfunction artifactPaths(result: any): string[] {\r\n const keys = new Set([\"artifact\", \"appArtifact\", \"testArtifact\", \"stdout\", \"stderr\", \"output\", \"metadataPath\"]);\r\n const values: string[] = [];\r\n const visit = (value: any) => {\r\n if (!value || typeof value !== \"object\") return;\r\n for (const [key, child] of Object.entries(value)) {\r\n if (keys.has(key) && typeof child === \"string\") values.push(child);\r\n else if (child && typeof child === \"object\") visit(child);\r\n }\r\n };\r\n visit(result);\r\n return [...new Set(values)];\r\n}\r\n\r\nfunction archiveArtifacts(projectRoot: string, artifacts: string[]) {\r\n const archived: ManagedEvidenceReceipt[\"artifacts\"] = [];\r\n for (const value of artifacts) {\r\n const absolute = path.isAbsolute(value) ? value : path.resolve(projectRoot, value);\r\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) continue;\r\n const content = fs.readFileSync(absolute);\r\n const digest = createHash(\"sha256\").update(content).digest(\"hex\");\r\n const destination = path.join(evidenceRoot(projectRoot), \"blobs\", digest, path.basename(absolute));\r\n fs.mkdirSync(path.dirname(destination), { recursive: true });\r\n const existingIsIntact = fs.existsSync(destination)\r\n && fs.statSync(destination).isFile()\r\n && fs.statSync(destination).size === content.byteLength\r\n && createHash(\"sha256\").update(fs.readFileSync(destination)).digest(\"hex\") === digest;\r\n if (!existingIsIntact) fs.copyFileSync(absolute, destination);\r\n archived.push({\r\n path: workspaceRelative(projectRoot, destination),\r\n source: projectRelative(projectRoot, absolute),\r\n sha256: digest,\r\n size: content.byteLength,\r\n });\r\n }\r\n return archived;\r\n}\r\n\r\nfunction receiptResult(action: string, result: any): Record<string, unknown> | null {\r\n const testResult = result?.tests ? result : result?.execution ?? result;\r\n if (action.startsWith(\"test:harmony\")) return {\r\n target: testResult?.target ?? null,\r\n tests: testResult?.tests ?? null,\r\n stage: testResult?.stage ?? null,\r\n summary: result?.summary ?? null,\r\n };\r\n return {\r\n stage: result?.stage ?? null,\r\n exitCode: result?.exitCode ?? null,\r\n summary: result?.summary ?? null,\r\n };\r\n}\r\n\r\nfunction writeJsonAtomic(file: string, value: unknown) {\r\n fs.mkdirSync(path.dirname(file), { recursive: true });\r\n const temporary = `${file}.${process.pid}.tmp`;\r\n fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\r\n fs.renameSync(temporary, file);\r\n}\r\n\r\nexport function recordObservation(options: { project?: string; action: string; result: any; scope?: Record<string, unknown> | null; guard?: GuardResult | null }) {\r\n const projectRoot = path.resolve(options.project ?? \".\");\r\n const snapshot = inspectMigration(projectRoot);\r\n const status = observationStatus(options.result);\r\n const kind = options.action.startsWith(\"test:harmony\") ? \"harmony-test\" : (() => { if (options.action.startsWith(\"build:\")) return \"build\"; return \"command\"; })();\r\n const idempotencyKey = sha256({\r\n action: options.action,\r\n scope: options.scope ?? null,\r\n factsSha256: snapshot.source.factsSha256,\r\n androidFingerprint: snapshot.source.androidFingerprint,\r\n harmonyFingerprint: snapshot.source.harmonyFingerprint,\r\n });\r\n const id = `${options.action.replaceAll(\":\", \"-\")}-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;\r\n const receiptFile = path.join(evidenceRoot(projectRoot), \"managed\", `${id}.json`);\r\n const receipt: ManagedEvidenceReceipt = {\r\n evidenceVersion: \"1.1.0\",\r\n id,\r\n producer: \"droid2hmos\",\r\n kind,\r\n action: options.action,\r\n scope: options.scope ?? null,\r\n status,\r\n recordedAt: new Date().toISOString(),\r\n idempotencyKey,\r\n source: {\r\n gitHead: snapshot.workspace.gitHead,\r\n factsSha256: snapshot.source.factsSha256,\r\n androidFingerprint: snapshot.source.androidFingerprint,\r\n harmonyFingerprint: snapshot.source.harmonyFingerprint,\r\n },\r\n guard: options.guard ? { mode: options.guard.mode, decision: options.guard.decision, policyDecision: options.guard.policyDecision } : null,\r\n retry: classifyFailure(options.action, options.result),\r\n resultDigest: sha256(options.result ?? null),\r\n result: receiptResult(options.action, options.result),\r\n artifacts: [],\r\n };\r\n receipt.artifacts = archiveArtifacts(projectRoot, artifactPaths(options.result));\r\n writeJsonAtomic(receiptFile, receipt);\r\n const indexFile = path.join(evidenceRoot(projectRoot), \"index.json\");\r\n const index = evidenceIndex(projectRoot);\r\n index.evidenceIndexVersion = \"1.0.0\";\r\n index.latestByAction ??= {};\r\n const reference = workspaceRelative(projectRoot, receiptFile);\r\n index.latestByAction[options.action] = reference;\r\n writeJsonAtomic(indexFile, index);\r\n return { reference, receipt };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { migrationDirectory } from \"../../migration-paths.ts\";\r\nimport { sha256 } from \"../util.ts\";\r\n\r\nexport class PlanningFactsError extends Error {\r\n constructor(public readonly code: string, message: string) {\r\n super(message);\r\n }\r\n}\r\n\r\nexport interface RawFactsBundleV2 {\r\n projectRoot: string;\r\n specRoot: string;\r\n index: any;\r\n app: any;\r\n pageIndex: any;\r\n pages: any[];\r\n unassigned: any | null;\r\n interactions: any;\r\n unresolved: any;\r\n corrections: any;\r\n unresolvedReviews: any;\r\n}\r\n\r\nfunction readJson(file: string): any {\r\n try {\r\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\r\n } catch (error) {\r\n throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", `Cannot read JSON ${file}: ${error instanceof Error ? error.message : String(error)}`);\r\n }\r\n}\r\n\r\nfunction inside(root: string, relative: unknown, label: string): string {\r\n if (typeof relative !== \"string\" || !relative.trim()) throw new PlanningFactsError(\"FACTS_SHARD_MISSING\", `${label} path is missing`);\r\n const resolvedRoot = path.resolve(root);\r\n const absolute = path.resolve(resolvedRoot, relative);\r\n const rel = path.relative(resolvedRoot, absolute);\r\n if (!rel || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {\r\n throw new PlanningFactsError(\"FACTS_PATH_OUTSIDE_ROOT\", `${label} must stay inside ${resolvedRoot}: ${relative}`);\r\n }\r\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) throw new PlanningFactsError(\"FACTS_SHARD_MISSING\", `${label} not found: ${absolute}`);\r\n const realRoot = fs.realpathSync(resolvedRoot);\r\n const realFile = fs.realpathSync(absolute);\r\n const realRelative = path.relative(realRoot, realFile);\r\n if (!realRelative || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {\r\n throw new PlanningFactsError(\"FACTS_PATH_OUTSIDE_ROOT\", `${label} resolves outside ${realRoot}: ${relative}`);\r\n }\r\n return realFile;\r\n}\r\n\r\nfunction optionalShard(root: string, relative: unknown): any {\r\n if (typeof relative !== \"string\" || !relative.trim()) return null;\r\n return readJson(inside(root, relative, \"Optional planning input\"));\r\n}\r\n\r\nfunction requireVersion(value: any, expected: string, label: string): void {\r\n if (value !== expected) throw new PlanningFactsError(\"FACTS_VERSION_UNSUPPORTED\", `${label} must be ${expected}; found ${value ?? \"<missing>\"}`);\r\n}\r\n\r\nexport function readFactsBundleV2(project: string): RawFactsBundleV2 {\r\n const projectRoot = path.resolve(project);\r\n const specRoot = path.join(migrationDirectory(projectRoot), \"spec\");\r\n const indexFile = path.join(specRoot, \"index.json\");\r\n if (!fs.existsSync(indexFile)) throw new PlanningFactsError(\"FACTS_SHARD_MISSING\", `SPEC index not found: ${indexFile}`);\r\n const index = readJson(indexFile);\r\n requireVersion(index.specVersion, \"2.0.0\", \"SPEC specVersion\");\r\n requireVersion(index.shardFormatVersion, \"2.0.0\", \"Facts shardFormatVersion\");\r\n if (!/^[a-f0-9]{64}$/.test(index.factsSha256 ?? \"\")) throw new PlanningFactsError(\"FACTS_HASH_MISSING\", \"SPEC index does not contain a valid factsSha256\");\r\n const files = index.files?.facts;\r\n if (!files) throw new PlanningFactsError(\"FACTS_SHARD_MISSING\", \"SPEC index does not expose facts shards\");\r\n const app = readJson(inside(specRoot, files.app, \"App facts\"));\r\n const pageIndex = readJson(inside(specRoot, files.pages, \"Page facts index\"));\r\n const interactions = readJson(inside(specRoot, files.interactions, \"Interaction facts\"));\r\n const unresolved = readJson(inside(specRoot, files.unresolved, \"Unresolved facts\"));\r\n requireVersion(app.shardVersion, \"2.0.0\", \"App facts shardVersion\");\r\n requireVersion(pageIndex.indexVersion, \"2.0.0\", \"Page facts indexVersion\");\r\n requireVersion(interactions.shardVersion, \"2.0.0\", \"Interaction facts shardVersion\");\r\n requireVersion(unresolved.shardVersion, \"2.0.0\", \"Unresolved facts shardVersion\");\r\n if (!app.app || !Array.isArray(app.uiGraph?.roots) || !Array.isArray(app.warnings)) throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", \"App facts shard is missing app, uiGraph.roots, or warnings\");\r\n if (!Array.isArray(pageIndex.pages)) throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", \"Page facts index must contain a pages array\");\r\n if (!Array.isArray(interactions.interactions)) throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", \"Interaction facts shard must contain an interactions array\");\r\n if (!Array.isArray(unresolved.facts) || !Array.isArray(unresolved.graphItems)) throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", \"Unresolved facts shard must contain facts and graphItems arrays\");\r\n const seenFiles = new Set<string>();\r\n const pages = (pageIndex.pages ?? []).map((descriptor: any) => {\r\n const file = inside(specRoot, descriptor.file, `Page facts ${descriptor.surfaceRef ?? \"<unknown>\"}`);\r\n if (seenFiles.has(file)) throw new PlanningFactsError(\"FACTS_SHARD_DUPLICATE\", `Page facts shard is listed more than once: ${descriptor.file}`);\r\n seenFiles.add(file);\r\n const shard = readJson(file);\r\n requireVersion(shard.shardVersion, \"2.0.0\", `Page facts ${descriptor.file} shardVersion`);\r\n if (shard.kind !== \"surface-facts\") throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", `Page facts ${descriptor.file} has invalid kind ${shard.kind ?? \"<missing>\"}`);\r\n if (!shard.surface || !Array.isArray(shard.controls) || !Array.isArray(shard.entries)) throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", `Page facts ${descriptor.file} must contain surface, controls, and entries`);\r\n return shard;\r\n });\r\n const unassigned = pageIndex.unassignedEntriesFile\r\n ? readJson(inside(specRoot, pageIndex.unassignedEntriesFile, \"Unassigned entry facts\"))\r\n : null;\r\n if (unassigned) {\r\n requireVersion(unassigned.shardVersion, \"2.0.0\", \"Unassigned entry facts shardVersion\");\r\n if (unassigned.kind !== \"unassigned-entry-facts\") throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", `Unassigned entry facts has invalid kind ${unassigned.kind ?? \"<missing>\"}`);\r\n if (!Array.isArray(unassigned.entries)) throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", \"Unassigned entry facts must contain an entries array\");\r\n }\r\n const recomputed = sha256({ app, pages, unassigned, interactions, unresolved });\r\n if (recomputed !== index.factsSha256) {\r\n throw new PlanningFactsError(\"FACTS_HASH_MISMATCH\", `Facts content hash ${recomputed} does not match index ${index.factsSha256}`);\r\n }\r\n const semanticFiles = index.files?.semantics ?? {};\r\n const corrections = optionalShard(specRoot, semanticFiles.corrections);\r\n const unresolvedReviews = optionalShard(specRoot, semanticFiles.unresolved);\r\n if (corrections) {\r\n requireVersion(corrections.shardVersion, \"2.0.0\", \"Fact corrections shardVersion\");\r\n if (!Array.isArray(corrections.factCorrections) || !Array.isArray(corrections.exclusions)) throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", \"Fact corrections shard must contain factCorrections and exclusions arrays\");\r\n }\r\n if (unresolvedReviews) {\r\n requireVersion(unresolvedReviews.shardVersion, \"2.0.0\", \"Unresolved reviews shardVersion\");\r\n if (!Array.isArray(unresolvedReviews.reviews)) throw new PlanningFactsError(\"FACTS_SHARD_INVALID\", \"Unresolved reviews shard must contain a reviews array\");\r\n }\r\n return {\r\n projectRoot,\r\n specRoot,\r\n index,\r\n app,\r\n pageIndex,\r\n pages,\r\n unassigned,\r\n interactions,\r\n unresolved,\r\n corrections: corrections ?? { shardVersion: \"2.0.0\", factCorrections: [], exclusions: [] },\r\n unresolvedReviews: unresolvedReviews ?? { shardVersion: \"2.0.0\", reviews: [] },\r\n };\r\n}\r\n","import { createHash } from \"node:crypto\";\r\n\r\nexport function sortValue(value: unknown): unknown {\r\n if (Array.isArray(value)) return value.map(sortValue);\r\n if (value && typeof value === \"object\") {\r\n return Object.fromEntries(Object.keys(value as Record<string, unknown>)\r\n .sort()\r\n .map((key) => [key, sortValue((value as Record<string, unknown>)[key])]));\r\n }\r\n return value;\r\n}\r\n\r\nexport function stableJson(value: unknown): string {\r\n return JSON.stringify(sortValue(value));\r\n}\r\n\r\nexport function prettyStableJson(value: unknown): string {\r\n return `${JSON.stringify(sortValue(value), null, 2)}\\n`;\r\n}\r\n\r\nexport function sha256(value: unknown): string {\r\n return createHash(\"sha256\").update(typeof value === \"string\" ? value : stableJson(value)).digest(\"hex\");\r\n}\r\n\r\nexport function uniqueSorted(values: Iterable<string | null | undefined>): string[] {\r\n return [...new Set([...values].filter((value): value is string => typeof value === \"string\" && value.length > 0))].sort();\r\n}\r\n\r\nexport function uniqueBy<T>(values: Iterable<T>, key: (value: T) => string): T[] {\r\n return [...new Map([...values].map((value) => [key(value), value])).values()];\r\n}\r\n\r\n","export const TASK_PLAN_VERSION = \"2.3.0\" as const;\r\nexport const TASK_ENVELOPE_VERSION = \"3.0.0\" as const;\r\nexport const BEHAVIOR_PLAN_VERSION = \"1.0.0\" as const;\r\nexport const EXECUTION_PLAN_VERSION = \"1.3.0\" as const;\r\nexport const PLANNING_MODEL_VERSION = \"2.0.0\" as const;\r\nexport const FACTS_ADAPTER_VERSION = \"1.0.0\" as const;\r\nexport const PLANNER_POLICY_VERSION = \"2.3.0\" as const;\r\nexport const DEFAULT_CLOSURE_BUDGET = {\r\n maxFactCount: 30,\r\n maxSourceFileCount: 15,\r\n maxTraceNodeCount: 50,\r\n maxEstimatedFactTokens: 12_000,\r\n} as const;\r\n\r\nexport const DEFAULT_EXECUTION_BUDGET = {\r\n maxBehaviorCount: 5,\r\n maxObservableOutcomeCount: 3,\r\n maxProductionFileCount: 4,\r\n maxTestFileCount: 2,\r\n maxCapabilityCount: 2,\r\n maxFactCount: 45,\r\n maxSourceFileCount: 8,\r\n maxTraceNodeCount: 60,\r\n maxEstimatedFactTokens: 14_000,\r\n} as const;\r\n\r\nexport interface SourceEvidence {\r\n file: string;\r\n symbol: string | null;\r\n line: number | null;\r\n endLine: number | null;\r\n}\r\n\r\nexport interface PlanningFactsBaseline {\r\n factsSha256: string;\r\n planningInputSha256: string;\r\n specVersion: string;\r\n wireVersion: string;\r\n adapterVersion: typeof FACTS_ADAPTER_VERSION;\r\n}\r\n\r\nexport interface PlanningSurface {\r\n id: string;\r\n name: string;\r\n kind: string;\r\n parentSurfaceIds: string[];\r\n topLevel: boolean;\r\n evidence: SourceEvidence[];\r\n}\r\n\r\nexport interface PlanningControl {\r\n id: string;\r\n name: string;\r\n surfaceId: string | null;\r\n sourceCarrierId: string | null;\r\n evidence: SourceEvidence[];\r\n}\r\n\r\nexport interface PlanningEntry {\r\n id: string;\r\n triggerCategory: \"user\" | \"system\" | \"application\" | \"unknown\";\r\n componentKind: string;\r\n ownershipStatus: string;\r\n ownerSurfaceId: string | null;\r\n carrierId: string | null;\r\n event: string;\r\n label: string;\r\n trace: {\r\n codeRefs: Array<Record<string, unknown>>;\r\n truncated: boolean;\r\n warnings: string[];\r\n };\r\n evidence: SourceEvidence[];\r\n}\r\n\r\nexport type PlanningEffectKind = \"opens\" | \"navigates-to\" | \"launches-for-result\" | \"unknown\";\r\n\r\nexport interface PlanningEffect {\r\n id: string;\r\n kind: PlanningEffectKind;\r\n sourceEntryId: string;\r\n targetKind: \"surface\" | \"entry\" | \"unknown\";\r\n targetId: string;\r\n confidence: number;\r\n evidence: SourceEvidence[];\r\n}\r\n\r\nexport interface PlanningIssue {\r\n id: string;\r\n kind: string;\r\n reason: string;\r\n relatedRefs: string[];\r\n blocking: boolean;\r\n resolved: boolean;\r\n evidence: SourceEvidence[];\r\n}\r\n\r\nexport interface PlanningWarning {\r\n code: string;\r\n message: string;\r\n relatedRefs: string[];\r\n}\r\n\r\nexport interface PlanningFactsSnapshot {\r\n baseline: PlanningFactsBaseline;\r\n app: {\r\n id: string;\r\n name: string;\r\n packageName: string;\r\n launcherSurfaceIds: string[];\r\n launcherEntryIds: string[];\r\n launcherOrigin: \"explicit-fact\" | \"launch-entry-fact\" | \"unresolved\";\r\n };\r\n surfaces: PlanningSurface[];\r\n controls: PlanningControl[];\r\n entries: PlanningEntry[];\r\n effects: PlanningEffect[];\r\n issues: PlanningIssue[];\r\n diagnostics: PlanningWarning[];\r\n requiredFactRefs: string[];\r\n}\r\n\r\nexport type TaskType = \"resolution\" | \"bootstrap\" | \"capability\" | \"journey\" | \"assembly\" | \"regression\";\r\n\r\nexport interface BehaviorResponsibility {\r\n id: string;\r\n type: TaskType;\r\n title: string;\r\n primaryFactRefs: string[];\r\n supportingFactRefs: string[];\r\n dependsOnBehaviorIds: string[];\r\n closure: {\r\n entryRefs: string[];\r\n surfaceRefs: string[];\r\n controlRefs: string[];\r\n interactionRefs: string[];\r\n sourceEvidence: SourceEvidence[];\r\n codeRefs: Array<Record<string, unknown>>;\r\n unresolvedRefs: string[];\r\n warningRefs: string[];\r\n requiresSourceReview: boolean;\r\n };\r\n acceptance: {\r\n observableOutcome: string;\r\n requiredFactRefs: string[];\r\n verificationRequirements: string[];\r\n reportRefs: string[];\r\n };\r\n estimate: {\r\n factCount: number;\r\n sourceFileCount: number;\r\n traceNodeCount: number;\r\n estimatedFactTokens: number;\r\n downstreamUnlockCount: number;\r\n };\r\n}\r\n\r\nexport interface BehaviorPlan {\r\n behaviorPlanVersion: typeof BEHAVIOR_PLAN_VERSION;\r\n planningModelVersion: typeof PLANNING_MODEL_VERSION;\r\n factsAdapterVersion: typeof FACTS_ADAPTER_VERSION;\r\n plannerPolicyVersion: typeof PLANNER_POLICY_VERSION;\r\n baseline: TaskPlanBaseline;\r\n entryResolution: EntryResolution;\r\n responsibilities: BehaviorResponsibility[];\r\n ownership: {\r\n primaryOwnerByFactRef: Record<string, string>;\r\n supportingBehaviorIdsByFactRef: Record<string, string[]>;\r\n };\r\n planningWarnings: PlanningWarning[];\r\n}\r\n\r\nexport interface WorkItemWriteOwnership {\r\n /** Existing HarmonyOS files already claimed by report mappings or execution input. */\r\n ownedFiles: string[];\r\n /** Files consumed through an established Interface and never modified by this item. */\r\n readOnlyFiles: string[];\r\n /** Logical exclusive claims used before a concrete target file exists. */\r\n exclusiveScopes: string[];\r\n /** Global hot spots that this item is explicitly forbidden to modify. */\r\n forbiddenGlobalFiles: string[];\r\n}\r\n\r\nexport interface DependencyInterface {\r\n kind: \"module\" | \"ordering\";\r\n ref: string;\r\n providerTaskId: string | null;\r\n files: string[];\r\n errorModes: string[];\r\n orderingConstraints: string[];\r\n}\r\n\r\nexport interface PlannedTask {\r\n id: string;\r\n type: TaskType;\r\n title: string;\r\n /** Resolution Tasks do not participate in Coding Work Packages. */\r\n workPackageId: string | null;\r\n canonicalPageRef: string | null;\r\n primaryModule: string;\r\n behaviorIds: string[];\r\n primaryFactRefs: string[];\r\n supportingFactRefs: string[];\r\n dependsOnTaskIds: string[];\r\n conflictsWithTaskIds: string[];\r\n writeOwnership: WorkItemWriteOwnership;\r\n dependencyInterfaces: DependencyInterface[];\r\n readyGate: {\r\n semanticsResolved: boolean;\r\n dependencyInterfacesStable: boolean;\r\n writeOwnershipResolved: boolean;\r\n contextWithinBudget: boolean;\r\n acceptanceExecutable: boolean;\r\n };\r\n closure: BehaviorResponsibility[\"closure\"];\r\n acceptance: BehaviorResponsibility[\"acceptance\"] & {\r\n observableOutcomes: string[];\r\n };\r\n estimate: BehaviorResponsibility[\"estimate\"] & {\r\n behaviorCount: number;\r\n observableOutcomeCount: number;\r\n productionFileCount: number;\r\n testFileCount: number;\r\n capabilityCount: number;\r\n };\r\n}\r\n\r\nexport interface PageWorkPackage {\r\n id: string;\r\n canonicalPageRef: string | null;\r\n title: string;\r\n surfaceRefs: string[];\r\n workItemIds: string[];\r\n dependsOnPackageIds: string[];\r\n serialLane: boolean;\r\n exclusiveScopes: string[];\r\n}\r\n\r\nexport interface PageFeatureContract {\r\n ordinal: number;\r\n behaviorId: string;\r\n workItemId: string;\r\n type: TaskType;\r\n title: string;\r\n triggerLabels: string[];\r\n controlNames: string[];\r\n interactionOutcomes: string[];\r\n entryRefs: string[];\r\n surfaceRefs: string[];\r\n controlRefs: string[];\r\n interactionRefs: string[];\r\n unresolvedRefs: string[];\r\n primaryFactRefs: string[];\r\n supportingFactRefs: string[];\r\n requiresSourceReview: boolean;\r\n observableOutcome: string;\r\n requiredFactRefs: string[];\r\n verificationRequirements: string[];\r\n reportRefs: string[];\r\n}\r\n\r\nexport interface PageDependencyInterface {\r\n kind: DependencyInterface[\"kind\"];\r\n ref: string;\r\n providerPackageId: string;\r\n providerWorkItemIds: string[];\r\n files: string[];\r\n errorModes: string[];\r\n orderingConstraints: string[];\r\n}\r\n\r\nexport interface PageWorkPackageContract extends PageWorkPackage {\r\n behaviorIds: string[];\r\n workItems: Array<{\r\n ordinal: number;\r\n id: string;\r\n type: TaskType;\r\n title: string;\r\n behaviorIds: string[];\r\n }>;\r\n features: PageFeatureContract[];\r\n writeOwnership: WorkItemWriteOwnership;\r\n dependencyInterfaces: PageDependencyInterface[];\r\n acceptance: {\r\n observableOutcomes: string[];\r\n requiredFactRefs: string[];\r\n verificationRequirements: string[];\r\n reportRefs: string[];\r\n };\r\n estimate: {\r\n behaviorCount: number;\r\n workItemCount: number;\r\n factCount: number;\r\n sourceFileCount: number;\r\n traceNodeCount: number;\r\n estimatedFactTokens: number;\r\n productionFileCount: number;\r\n testFileCount: number;\r\n capabilityCount: number;\r\n };\r\n}\r\n\r\nexport interface FileConflictEdge {\r\n leftTaskId: string;\r\n rightTaskId: string;\r\n reasons: string[];\r\n}\r\n\r\nexport interface TaskPlanBaseline {\r\n factsSha256: string;\r\n planningInputSha256: string;\r\n androidFingerprint: string | null;\r\n specVersion: string;\r\n factsWireVersion: string;\r\n}\r\n\r\nexport interface EntryResolution {\r\n launcherSurfaceRefs: string[];\r\n launcherEntryRefs: string[];\r\n origin: \"explicit-fact\" | \"launch-entry-fact\" | \"unresolved\";\r\n}\r\n\r\nexport interface TaskPlan {\r\n taskPlanVersion: typeof TASK_PLAN_VERSION;\r\n executionPlanVersion: typeof EXECUTION_PLAN_VERSION;\r\n planningModelVersion: typeof PLANNING_MODEL_VERSION;\r\n factsAdapterVersion: typeof FACTS_ADAPTER_VERSION;\r\n plannerPolicyVersion: typeof PLANNER_POLICY_VERSION;\r\n baseline: TaskPlanBaseline;\r\n /** Resolution plans project Behaviors 1:1 into transient Tasks; execution plans materialize only frozen Coding Work Items. */\r\n planningPhase: \"resolution\" | \"execution\";\r\n entryResolution: EntryResolution;\r\n behaviorResponsibilities: BehaviorResponsibility[];\r\n pageWorkPackages: PageWorkPackage[];\r\n tasks: PlannedTask[];\r\n ownership: {\r\n primaryOwnerByFactRef: Record<string, string>;\r\n supportingTaskIdsByFactRef: Record<string, string[]>;\r\n };\r\n behaviorOwnership: BehaviorPlan[\"ownership\"];\r\n fileConflictEdges: FileConflictEdge[];\r\n planningWarnings: PlanningWarning[];\r\n}\r\n\r\nexport interface TaskContract {\r\n executionPlanSha256: string;\r\n baseline: TaskPlanBaseline;\r\n task: PlannedTask;\r\n}\r\n\r\nexport interface PageWorkPackageEnvelopeContract {\r\n executionPlanSha256: string;\r\n baseline: TaskPlanBaseline;\r\n pageWorkPackage: PageWorkPackageContract;\r\n}\r\n\r\nexport type TaskRuntimeState = \"pending\" | \"ready\" | \"blocked\" | \"implemented\" | \"locally-verified\" | \"stale\" | \"globally-verified\";\r\n\r\nexport interface TaskRuntimeItem {\r\n taskId: string;\r\n state: TaskRuntimeState;\r\n reasons: string[];\r\n}\r\n\r\nexport interface ExecutionTargetRuntimeItem {\r\n targetId: string;\r\n kind: \"resolution-task\" | \"page-work-package\";\r\n state: TaskRuntimeState;\r\n reasons: string[];\r\n workItemIds: string[];\r\n}\r\n\r\nexport interface TaskPlanValidation {\r\n valid: boolean;\r\n fresh: boolean;\r\n errors: string[];\r\n warnings: string[];\r\n orphanFactRefs: string[];\r\n taskPlanSha256: string | null;\r\n}\r\n\r\nexport interface TaskPlanSnapshot {\r\n present: boolean;\r\n valid: boolean;\r\n fresh: boolean;\r\n taskPlanSha256: string | null;\r\n planningPhase: TaskPlan[\"planningPhase\"] | null;\r\n totalTasks: number;\r\n resolutionTasks: number;\r\n totalTargets: number;\r\n readyTargets: number;\r\n completedTargets: number;\r\n readyTasks: number;\r\n blockedTasks: number;\r\n completedTasks: number;\r\n recommendedTargetId: string | null;\r\n /** Present only during resolution; execution recommends a Page Work Package instead. */\r\n recommendedTaskId: string | null;\r\n alternatives: string[];\r\n reasons: Record<string, string[]>;\r\n ownershipCoverage: number;\r\n closureCoverage: number;\r\n orphanFactRefs: string[];\r\n errors: string[];\r\n warnings: string[];\r\n tasks: TaskRuntimeItem[];\r\n targets: ExecutionTargetRuntimeItem[];\r\n}\r\n\r\nexport interface TaskEnvelopePage {\r\n taskEnvelopeVersion: typeof TASK_ENVELOPE_VERSION;\r\n taskPlanSha256: string;\r\n targetKind: \"resolution-task\" | \"page-work-package\";\r\n targetId: string;\r\n task: PlannedTask | null;\r\n pageWorkPackage: PageWorkPackageContract | null;\r\n contract: TaskContract | PageWorkPackageEnvelopeContract;\r\n brief: string;\r\n coreFacts: unknown[];\r\n dependencyInterfaces: Array<DependencyInterface | PageDependencyInterface>;\r\n acceptance: PlannedTask[\"acceptance\"] | PageWorkPackageContract[\"acceptance\"];\r\n sourceContext: unknown[];\r\n continuation: {\r\n cursor: string | null;\r\n remainingSourceContext: number;\r\n };\r\n}\r\n\r\nexport interface PlanningRuntimeSource {\r\n androidFingerprint: string | null;\r\n harmonyFingerprint?: string | null;\r\n fullRegressionFresh?: boolean;\r\n}\r\n","import type {\r\n PlanningControl,\r\n PlanningEffect,\r\n PlanningEntry,\r\n PlanningFactsSnapshot,\r\n PlanningIssue,\r\n PlanningSurface,\r\n PlanningWarning,\r\n SourceEvidence,\r\n} from \"../types.ts\";\r\nimport { FACTS_ADAPTER_VERSION } from \"../types.ts\";\r\nimport { sha256, uniqueBy, uniqueSorted } from \"../util.ts\";\r\nimport type { RawFactsBundleV2 } from \"./reader.ts\";\r\nimport { PlanningFactsError } from \"./reader.ts\";\r\n\r\nfunction evidence(values: any): SourceEvidence[] {\r\n return uniqueBy((Array.isArray(values) ? values : []).flatMap((item: any) => {\r\n if (!item || typeof item.file !== \"string\" || !item.file.trim()) return [];\r\n const line = Number.isInteger(item.line) && item.line > 0 ? item.line : null;\r\n const endLine = Number.isInteger(item.endLine) && item.endLine > 0 ? item.endLine : null;\r\n return [{ file: item.file, symbol: typeof item.symbol === \"string\" ? item.symbol : null, line, endLine }];\r\n }), (item) => `${item.file}:${item.symbol ?? \"\"}:${item.line ?? \"\"}:${item.endLine ?? \"\"}`);\r\n}\r\n\r\nfunction applyCorrections(raw: RawFactsBundleV2) {\r\n const surfaces = raw.pages.map((page) => ({ ...page.surface }));\r\n const controls = raw.pages.flatMap((page) => page.controls ?? []).map((item) => ({ ...item }));\r\n const entries = [...raw.pages.flatMap((page) => page.entries ?? []), ...(raw.unassigned?.entries ?? [])].map((item) => ({ ...item }));\r\n const interactions = (raw.interactions.interactions ?? []).map((item: any) => ({ ...item }));\r\n const tables: Record<string, { values: any[]; id: string }> = {\r\n surface: { values: surfaces, id: \"surfaceRef\" },\r\n control: { values: controls, id: \"controlRef\" },\r\n entry: { values: entries, id: \"entryRef\" },\r\n interaction: { values: interactions, id: \"id\" },\r\n };\r\n for (const correction of raw.corrections.factCorrections ?? []) {\r\n const table = tables[correction.entityKind];\r\n if (!table || ![\"add\", \"update\", \"remove\"].includes(correction.operation)) continue;\r\n const index = table.values.findIndex((item) => item?.[table.id] === correction.targetRef);\r\n if (correction.operation === \"remove\") {\r\n if (index >= 0) table.values.splice(index, 1);\r\n continue;\r\n }\r\n const next = { ...(index >= 0 ? table.values[index] : {}), ...(correction.factValue ?? {}), [table.id]: correction.targetRef };\r\n if (index >= 0) table.values[index] = next;\r\n else table.values.push(next);\r\n }\r\n return { surfaces, controls, entries, interactions };\r\n}\r\n\r\nfunction assertUnique(values: Array<{ id: string }>, label: string): void {\r\n const seen = new Set<string>();\r\n for (const item of values) {\r\n if (!item.id || seen.has(item.id)) throw new PlanningFactsError(\"FACTS_REFERENCE_BROKEN\", `${label} contains duplicate or missing id ${item.id || \"<empty>\"}`);\r\n seen.add(item.id);\r\n }\r\n}\r\n\r\nfunction assertDisjointRefs(groups: Array<{ label: string; values: Array<{ id: string }> }>): void {\r\n const owner = new Map<string, string>();\r\n for (const group of groups) for (const item of group.values) {\r\n const previous = owner.get(item.id);\r\n if (previous) throw new PlanningFactsError(\"FACTS_REFERENCE_BROKEN\", `Reference ${item.id} is reused by ${previous} and ${group.label}`);\r\n owner.set(item.id, group.label);\r\n }\r\n}\r\n\r\nexport function adaptFactsV2(raw: RawFactsBundleV2): PlanningFactsSnapshot {\r\n const effective = applyCorrections(raw);\r\n const surfaces: PlanningSurface[] = effective.surfaces.map((item) => ({\r\n id: item.surfaceRef,\r\n name: item.surfaceName || item.surfaceRef,\r\n kind: item.surfaceType || \"other\",\r\n parentSurfaceIds: uniqueSorted(item.parentSurfaceRefs ?? []),\r\n topLevel: !(item.parentSurfaceRefs ?? []).length,\r\n evidence: evidence(item.sourceEvidence),\r\n })).sort((a, b) => String(a.id).localeCompare(String(b.id)));\r\n const controls: PlanningControl[] = effective.controls.map((item) => ({\r\n id: item.controlRef,\r\n name: item.name || item.controlRef,\r\n surfaceId: typeof item.surfaceRef === \"string\" ? item.surfaceRef : null,\r\n sourceCarrierId: typeof item.sourceCarrierRef === \"string\" ? item.sourceCarrierRef : null,\r\n evidence: evidence(item.sourceEvidence),\r\n })).sort((a, b) => String(a.id).localeCompare(String(b.id)));\r\n const entries: PlanningEntry[] = effective.entries.map((item) => ({\r\n id: item.entryRef,\r\n triggerCategory: [\"user\", \"system\", \"application\"].includes(item.triggerCategory) ? item.triggerCategory : \"unknown\",\r\n componentKind: item.componentType || \"unknown\",\r\n ownershipStatus: item.ownershipStatus || (item.surfaceRef ? \"determined\" : \"unresolved\"),\r\n ownerSurfaceId: typeof item.surfaceRef === \"string\" ? item.surfaceRef : null,\r\n carrierId: typeof item.carrierRef === \"string\" ? item.carrierRef : null,\r\n event: item.event || \"unknown\",\r\n label: item.displayLabel || item.event || item.entryRef,\r\n trace: {\r\n codeRefs: Array.isArray(item.callTrace?.codeRefs) ? item.callTrace.codeRefs : [],\r\n truncated: item.callTrace?.truncated === true,\r\n warnings: uniqueSorted([...(item.callTrace?.coverageWarnings ?? []), ...(item.warnings ?? [])]),\r\n },\r\n evidence: evidence(item.sourceEvidence),\r\n })).sort((a, b) => String(a.id).localeCompare(String(b.id)));\r\n const surfaceIds = new Set(surfaces.map((item) => item.id));\r\n const entryIds = new Set(entries.map((item) => item.id));\r\n const issues: PlanningIssue[] = [];\r\n const diagnostics: PlanningWarning[] = [];\r\n const effects: PlanningEffect[] = effective.interactions.map((item) => {\r\n const kind = [\"opens\", \"navigates-to\", \"launches-for-result\"].includes(item.relation) ? item.relation : \"unknown\";\r\n const targetKind = kind === \"launches-for-result\" ? \"entry\" : (() => { if (kind === \"unknown\") return \"unknown\"; return \"surface\"; })();\r\n if (kind === \"unknown\") {\r\n issues.push({ id: `issue:relation:${item.id}`, kind: \"unsupported-relation\", reason: `Unsupported interaction relation ${item.relation ?? \"<missing>\"}`, relatedRefs: uniqueSorted([item.id, item.fromRef, item.toRef]), blocking: true, resolved: false, evidence: evidence(item.sourceEvidence) });\r\n }\r\n return {\r\n id: item.id,\r\n kind,\r\n sourceEntryId: item.fromRef,\r\n targetKind,\r\n targetId: item.toRef,\r\n confidence: typeof item.confidence === \"number\" ? item.confidence : 0,\r\n evidence: evidence(item.sourceEvidence),\r\n };\r\n }).sort((a, b) => String(a.id).localeCompare(String(b.id)));\r\n assertUnique(surfaces, \"surfaces\");\r\n assertUnique(controls, \"controls\");\r\n assertUnique(entries, \"entries\");\r\n assertUnique(effects, \"effects\");\r\n assertDisjointRefs([\r\n { label: \"surface\", values: surfaces },\r\n { label: \"control\", values: controls },\r\n { label: \"entry\", values: entries },\r\n { label: \"interaction\", values: effects },\r\n ]);\r\n\r\n for (const surface of surfaces) for (const parent of surface.parentSurfaceIds) {\r\n if (!surfaceIds.has(parent)) issues.push({ id: `issue:surface-parent:${surface.id}:${parent}`, kind: \"broken-surface-parent\", reason: `Surface ${surface.id} references unknown parent ${parent}`, relatedRefs: [surface.id, parent], blocking: true, resolved: false, evidence: surface.evidence });\r\n }\r\n for (const control of controls) if (!control.surfaceId || !surfaceIds.has(control.surfaceId)) {\r\n issues.push({ id: `issue:control-surface:${control.id}`, kind: \"broken-control-surface\", reason: `Control ${control.id} has no known owner surface`, relatedRefs: uniqueSorted([control.id, control.surfaceId]), blocking: true, resolved: false, evidence: control.evidence });\r\n }\r\n for (const entry of entries) {\r\n if (entry.ownerSurfaceId && !surfaceIds.has(entry.ownerSurfaceId)) issues.push({ id: `issue:entry-surface:${entry.id}`, kind: \"broken-entry-surface\", reason: `Entry ${entry.id} references unknown surface ${entry.ownerSurfaceId}`, relatedRefs: [entry.id, entry.ownerSurfaceId], blocking: true, resolved: false, evidence: entry.evidence });\r\n if (entry.ownershipStatus !== \"determined\" || !entry.ownerSurfaceId) issues.push({ id: `issue:entry-owner:${entry.id}`, kind: \"entry-owner\", reason: `Entry ${entry.id} does not have a determined owner surface`, relatedRefs: uniqueSorted([entry.id, entry.ownerSurfaceId]), blocking: true, resolved: false, evidence: entry.evidence });\r\n if (entry.trace.truncated) issues.push({ id: `issue:trace-truncated:${entry.id}`, kind: \"trace-truncated\", reason: `Entry ${entry.id} call trace is truncated`, relatedRefs: [entry.id], blocking: true, resolved: false, evidence: entry.evidence });\r\n }\r\n for (const effect of effects) {\r\n if (!entryIds.has(effect.sourceEntryId)) issues.push({ id: `issue:effect-source:${effect.id}`, kind: \"broken-effect-source\", reason: `Effect ${effect.id} references unknown source entry ${effect.sourceEntryId}`, relatedRefs: [effect.id, effect.sourceEntryId], blocking: true, resolved: false, evidence: effect.evidence });\r\n const targetExists = effect.targetKind === \"surface\" ? surfaceIds.has(effect.targetId) : (() => { if (effect.targetKind === \"entry\") return entryIds.has(effect.targetId); return false; })();\r\n if (!targetExists) issues.push({ id: `issue:effect-target:${effect.id}`, kind: \"broken-effect-target\", reason: `Effect ${effect.id} references unknown target ${effect.targetId}`, relatedRefs: [effect.id, effect.targetId], blocking: true, resolved: false, evidence: effect.evidence });\r\n }\r\n\r\n const reviews = new Map((raw.unresolvedReviews.reviews ?? []).map((item: any) => [item.unresolvedRef, item]));\r\n for (const item of raw.unresolved.facts ?? []) {\r\n const review: any = reviews.get(item.id);\r\n const resolved = Boolean(review && review.decision && review.decision !== \"pending\");\r\n issues.push({\r\n id: item.id,\r\n kind: item.kind || \"unresolved\",\r\n reason: item.reason || (item.reasons ?? []).join(\"; \") || \"Unresolved fact\",\r\n relatedRefs: uniqueSorted([item.id, item.entryRef, item.fromRef, ...(item.candidateToRefs ?? [])]),\r\n blocking: !resolved,\r\n resolved,\r\n evidence: evidence(item.sourceEvidence),\r\n });\r\n }\r\n const effectBySource = new Map<string, PlanningEffect[]>();\r\n for (const effect of effects) effectBySource.set(effect.sourceEntryId, [...(effectBySource.get(effect.sourceEntryId) ?? []), effect]);\r\n const explicit = raw.app.entryResolution ?? raw.app.app?.entryResolution;\r\n let launcherSurfaceIds: string[] = [];\r\n let launcherEntryIds: string[] = [];\r\n let launcherOrigin: \"explicit-fact\" | \"launch-entry-fact\" | \"unresolved\" = \"unresolved\";\r\n if (Array.isArray(explicit?.launcherSurfaceRefs) && explicit.launcherSurfaceRefs.length > 0) {\r\n launcherSurfaceIds = uniqueSorted(explicit.launcherSurfaceRefs);\r\n launcherEntryIds = uniqueSorted(explicit.launcherEntryRefs ?? []);\r\n launcherOrigin = \"explicit-fact\";\r\n } else {\r\n const launchEntries = entries.filter((entry) => entry.triggerCategory === \"application\" && entry.event === \"launch\");\r\n const resolvedEntries: string[] = [];\r\n const resolvedSurfaces: string[] = [];\r\n for (const entry of launchEntries) {\r\n const targets = uniqueSorted((effectBySource.get(entry.id) ?? []).filter((effect) => effect.targetKind === \"surface\" && effect.kind === \"navigates-to\").map((effect) => effect.targetId));\r\n if (targets.length === 1 && surfaceIds.has(targets[0]!)) {\r\n resolvedEntries.push(entry.id);\r\n resolvedSurfaces.push(targets[0]!);\r\n } else {\r\n issues.push({ id: `issue:launcher:${entry.id}`, kind: \"launcher\", reason: `Launch entry ${entry.id} must resolve to exactly one surface; found ${targets.length}`, relatedRefs: uniqueSorted([entry.id, ...targets]), blocking: true, resolved: false, evidence: entry.evidence });\r\n }\r\n }\r\n if (resolvedEntries.length > 0 && resolvedEntries.length === launchEntries.length) {\r\n launcherEntryIds = uniqueSorted(resolvedEntries);\r\n launcherSurfaceIds = uniqueSorted(resolvedSurfaces);\r\n launcherOrigin = \"launch-entry-fact\";\r\n }\r\n }\r\n for (const ref of launcherSurfaceIds) if (!surfaceIds.has(ref)) {\r\n issues.push({ id: `issue:launcher-surface:${ref}`, kind: \"launcher\", reason: `Launcher references unknown surface ${ref}`, relatedRefs: [ref], blocking: true, resolved: false, evidence: [] });\r\n launcherOrigin = \"unresolved\";\r\n }\r\n for (const ref of launcherEntryIds) if (!entryIds.has(ref)) {\r\n issues.push({ id: `issue:launcher-entry:${ref}`, kind: \"launcher\", reason: `Launcher references unknown entry ${ref}`, relatedRefs: [ref], blocking: true, resolved: false, evidence: [] });\r\n launcherOrigin = \"unresolved\";\r\n }\r\n if (launcherOrigin === \"unresolved\" || launcherSurfaceIds.length === 0) {\r\n launcherSurfaceIds = [];\r\n launcherEntryIds = [];\r\n issues.push({ id: \"issue:launcher-unresolved\", kind: \"launcher\", reason: \"No reliable launcher surface is available from deterministic Facts\", relatedRefs: [], blocking: true, resolved: false, evidence: [] });\r\n }\r\n const surfaceEdges = new Map<string, string[]>();\r\n const addSurfaceEdge = (from: string, to: string) => surfaceEdges.set(from, [...(surfaceEdges.get(from) ?? []), to]);\r\n for (const surface of surfaces) for (const parent of surface.parentSurfaceIds) if (surfaceIds.has(parent)) addSurfaceEdge(parent, surface.id);\r\n for (const effect of effects) {\r\n if (effect.targetKind !== \"surface\" || !surfaceIds.has(effect.targetId)) continue;\r\n const source = entries.find((entry) => entry.id === effect.sourceEntryId)?.ownerSurfaceId;\r\n if (source && surfaceIds.has(source)) addSurfaceEdge(source, effect.targetId);\r\n }\r\n const reachableSurfaces = new Set(launcherSurfaceIds);\r\n const surfaceQueue = [...launcherSurfaceIds];\r\n while (surfaceQueue.length) {\r\n for (const target of surfaceEdges.get(surfaceQueue.shift()!) ?? []) {\r\n if (reachableSurfaces.has(target)) continue;\r\n reachableSurfaces.add(target);\r\n surfaceQueue.push(target);\r\n }\r\n }\r\n for (const item of raw.unresolved.graphItems ?? []) {\r\n const entry = entries.find((value) => value.id === item.ref);\r\n const effect = effects.find((value) => value.id === item.ref);\r\n const graphItemResolved = item.kind === \"entry-surface\"\r\n ? Boolean(entry?.ownerSurfaceId && entry.ownershipStatus === \"determined\" && surfaceIds.has(entry.ownerSurfaceId))\r\n : (() => { if (item.kind === \"entry-control\") return Boolean(entry?.ownerSurfaceId && entry.carrierId && controls.some((control) => control.surfaceId === entry.ownerSurfaceId && control.sourceCarrierId === entry.carrierId)); return (() => { if (item.kind === \"interaction-target\") return Boolean(effect && ((effect.targetKind === \"surface\" && surfaceIds.has(effect.targetId)) || (effect.targetKind === \"entry\" && entryIds.has(effect.targetId)))); return (() => { if (item.kind === \"interaction-source\") return Boolean(effect && entryIds.has(effect.sourceEntryId)); return (() => { if (item.kind === \"surface-reachability\") return reachableSurfaces.has(item.ref); return false; })(); })(); })(); })();\r\n const id = `unresolved:graph:${sha256({ kind: item.kind, ref: item.ref, reason: item.reason }).slice(0, 16)}`;\r\n issues.push({ id, kind: item.kind || \"graph\", reason: item.reason || \"Unresolved graph item\", relatedRefs: uniqueSorted([id, item.ref]), blocking: !graphItemResolved, resolved: graphItemResolved, evidence: [] });\r\n }\r\n if ((raw.app.uiGraph?.roots ?? []).length) diagnostics.push({ code: \"LEGACY_UI_ROOTS_IGNORED\", message: \"facts/app.json uiGraph.roots is not used as launcher evidence because wire 2.0.0 does not preserve whether it came from Manifest or root fallback\", relatedRefs: uniqueSorted(raw.app.uiGraph.roots) });\r\n\r\n const warnings = uniqueSorted(raw.app.warnings ?? []);\r\n for (const [index, message] of warnings.entries()) diagnostics.push({ code: `FACTS_WARNING_${index + 1}`, message, relatedRefs: [] });\r\n const allIssues = uniqueBy(issues, (item) => item.id).sort((a, b) => a.id.localeCompare(b.id));\r\n const planningInputSha256 = sha256({ factsSha256: raw.index.factsSha256, corrections: raw.corrections, unresolvedReviews: raw.unresolvedReviews });\r\n return {\r\n baseline: { factsSha256: raw.index.factsSha256, planningInputSha256, specVersion: raw.index.specVersion, wireVersion: raw.index.shardFormatVersion, adapterVersion: FACTS_ADAPTER_VERSION },\r\n app: {\r\n id: raw.app.app?.packageName || raw.app.app?.name || \"android-app\",\r\n name: raw.app.app?.name || \"Android application\",\r\n packageName: raw.app.app?.packageName || \"\",\r\n launcherSurfaceIds,\r\n launcherEntryIds,\r\n launcherOrigin,\r\n },\r\n surfaces,\r\n controls,\r\n entries,\r\n effects,\r\n issues: allIssues,\r\n diagnostics,\r\n requiredFactRefs: uniqueSorted([...surfaces.map((item) => item.id), ...controls.map((item) => item.id), ...entries.map((item) => item.id), ...effects.map((item) => item.id)]),\r\n };\r\n}\r\n","import type { PlanningFactsSnapshot } from \"../types.ts\";\r\nimport { readFactsBundleV2 } from \"./reader.ts\";\r\nimport { adaptFactsV2 } from \"./v2-adapter.ts\";\r\n\r\nexport interface PlanningFactsSource {\r\n load(projectRoot: string): PlanningFactsSnapshot;\r\n}\r\n\r\nexport const v2PlanningFactsSource: PlanningFactsSource = {\r\n load(projectRoot: string) {\r\n return adaptFactsV2(readFactsBundleV2(projectRoot));\r\n },\r\n};\r\n\r\n","import type {\r\n BehaviorPlan,\r\n BehaviorResponsibility,\r\n PlanningEffect,\r\n PlanningFactsSnapshot,\r\n PlanningIssue,\r\n PlanningWarning,\r\n SourceEvidence,\r\n TaskType,\r\n} from \"./types.ts\";\r\nimport {\r\n BEHAVIOR_PLAN_VERSION,\r\n DEFAULT_CLOSURE_BUDGET,\r\n FACTS_ADAPTER_VERSION,\r\n PLANNER_POLICY_VERSION,\r\n PLANNING_MODEL_VERSION,\r\n} from \"./types.ts\";\r\nimport { sha256, stableJson, uniqueBy, uniqueSorted } from \"./util.ts\";\r\n\r\ninterface Candidate {\r\n key: string;\r\n memberKeys: string[];\r\n type: TaskType;\r\n title: string;\r\n observableOutcome: string;\r\n entryRefs: Set<string>;\r\n surfaceRefs: Set<string>;\r\n controlRefs: Set<string>;\r\n interactionRefs: Set<string>;\r\n issueRefs: Set<string>;\r\n warningRefs: Set<string>;\r\n sourceSurfaceRefs: Set<string>;\r\n targetEdges: Array<{ sourceSurfaceRef: string | null; targetSurfaceRef: string; effectRef: string }>;\r\n sourceEvidence: SourceEvidence[];\r\n codeRefs: Array<Record<string, unknown>>;\r\n requiresSourceReview: boolean;\r\n primary: Set<string>;\r\n supporting: Set<string>;\r\n}\r\n\r\nconst typeOrder: Record<TaskType, number> = {\r\n resolution: 0,\r\n bootstrap: 1,\r\n journey: 2,\r\n capability: 3,\r\n assembly: 4,\r\n regression: 5,\r\n};\r\n\r\nfunction evidenceKey(item: SourceEvidence): string {\r\n return `${item.file}:${item.symbol ?? \"\"}:${item.line ?? \"\"}:${item.endLine ?? \"\"}`;\r\n}\r\n\r\nfunction targetSurfaceIds(effect: PlanningEffect, facts: PlanningFactsSnapshot): string[] {\r\n if (effect.targetKind === \"surface\") return facts.surfaces.some((surface) => surface.id === effect.targetId) ? [effect.targetId] : [];\r\n if (effect.targetKind !== \"entry\") return [];\r\n const target = facts.entries.find((entry) => entry.id === effect.targetId);\r\n return target?.ownerSurfaceId ? [target.ownerSurfaceId] : [];\r\n}\r\n\r\nfunction effectOutcome(effect: PlanningEffect, facts: PlanningFactsSnapshot): string {\r\n if (effect.targetKind === \"surface\") {\r\n const target = facts.surfaces.find((surface) => surface.id === effect.targetId);\r\n return effect.kind === \"opens\" ? `打开${target?.name ?? effect.targetId}` : `进入${target?.name ?? effect.targetId}`;\r\n }\r\n if (effect.targetKind === \"entry\") {\r\n const target = facts.entries.find((entry) => entry.id === effect.targetId);\r\n return `取得${target?.label ?? effect.targetId}结果`;\r\n }\r\n return `产生${effect.id}对应的可观察结果`;\r\n}\r\n\r\nfunction candidateForEntry(entryId: string, facts: PlanningFactsSnapshot): Candidate {\r\n const entry = facts.entries.find((item) => item.id === entryId)!;\r\n const controls = facts.controls.filter((control) => control.surfaceId === entry.ownerSurfaceId && control.sourceCarrierId && control.sourceCarrierId === entry.carrierId);\r\n const effects = facts.effects.filter((effect) => effect.sourceEntryId === entry.id);\r\n const surfaces = uniqueSorted([\r\n entry.ownerSurfaceId,\r\n ...effects.flatMap((effect) => targetSurfaceIds(effect, facts)),\r\n ]);\r\n const related = new Set(uniqueSorted([\r\n entry.id,\r\n entry.ownerSurfaceId,\r\n ...controls.map((control) => control.id),\r\n ...effects.flatMap((effect) => [effect.id, effect.targetId]),\r\n ]));\r\n const issues = facts.issues.filter((issue) => issue.relatedRefs.some((ref) => related.has(ref)));\r\n const unresolvedIssues = issues.filter((issue) => issue.blocking && !issue.resolved);\r\n const blocking = unresolvedIssues.length > 0;\r\n const isLaunch = facts.app.launcherEntryIds.includes(entry.id) || (entry.triggerCategory === \"application\" && entry.event === \"launch\");\r\n const type: TaskType = blocking ? \"resolution\" : (() => { if (isLaunch) return \"bootstrap\"; return \"journey\"; })();\r\n const sourceName = facts.surfaces.find((surface) => surface.id === entry.ownerSurfaceId)?.name ?? \"未归属入口\";\r\n const outcomes = effects.map((effect) => effectOutcome(effect, facts));\r\n const observableOutcome = blocking\r\n ? `完成入口“${entry.label}”相关歧义的裁决并形成可追溯修正`\r\n : (() => { if (isLaunch) return `从系统 Launcher 启动并显示${outcomes[0]?.replace(/^(进入|打开)/, \"\") ?? sourceName}`; return (() => { if (outcomes.length > 0) return `在${sourceName}触发“${entry.label}”后${outcomes.join(\"、\")}`; return `在${sourceName}触发“${entry.label}”后验证其可观察业务结果`; })(); })();\r\n const title = blocking\r\n ? `裁决:${entry.label}`\r\n : (() => { if (isLaunch) return `建立真实启动入口:${outcomes[0]?.replace(/^(进入|打开)/, \"\") ?? sourceName}`; return (() => { if (outcomes.length > 0) return `${sourceName}:${entry.label}并${outcomes.join(\"、\")}`; return `${sourceName}:迁移${entry.label}`; })(); })();\r\n const warningRefs = entry.trace.warnings.map((warning) => `warning:${sha256({ entry: entry.id, warning }).slice(0, 16)}`);\r\n return {\r\n key: `entry:${entry.id}`,\r\n memberKeys: [`entry:${entry.id}`],\r\n type,\r\n title,\r\n observableOutcome,\r\n entryRefs: new Set([entry.id, ...effects.filter((effect) => effect.targetKind === \"entry\").map((effect) => effect.targetId)]),\r\n surfaceRefs: new Set(surfaces),\r\n controlRefs: new Set(controls.map((control) => control.id)),\r\n interactionRefs: new Set(effects.map((effect) => effect.id)),\r\n issueRefs: new Set(unresolvedIssues.map((issue) => issue.id)),\r\n warningRefs: new Set(warningRefs),\r\n sourceSurfaceRefs: new Set(entry.ownerSurfaceId ? [entry.ownerSurfaceId] : []),\r\n targetEdges: effects.flatMap((effect) => targetSurfaceIds(effect, facts).map((targetSurfaceRef) => ({ sourceSurfaceRef: entry.ownerSurfaceId, targetSurfaceRef, effectRef: effect.id }))),\r\n sourceEvidence: uniqueBy([\r\n ...entry.evidence,\r\n ...controls.flatMap((control) => control.evidence),\r\n ...effects.flatMap((effect) => effect.evidence),\r\n ...unresolvedIssues.flatMap((issue) => issue.evidence),\r\n ], evidenceKey),\r\n codeRefs: entry.trace.codeRefs,\r\n requiresSourceReview: effects.length === 0 || blocking || entry.trace.warnings.length > 0,\r\n primary: new Set([entry.id, ...effects.map((effect) => effect.id)]),\r\n supporting: new Set([...surfaces, ...controls.map((control) => control.id)]),\r\n };\r\n}\r\n\r\nfunction bootstrapCandidateForSurface(surfaceRef: string, facts: PlanningFactsSnapshot): Candidate {\r\n const surface = facts.surfaces.find((item) => item.id === surfaceRef)!;\r\n const key = `launcher-surface:${surfaceRef}`;\r\n return {\r\n key,\r\n memberKeys: [key],\r\n type: \"bootstrap\",\r\n title: `建立真实启动入口:${surface.name}`,\r\n observableOutcome: `从系统 Launcher 启动并显示${surface.name}`,\r\n entryRefs: new Set(),\r\n surfaceRefs: new Set([surfaceRef]),\r\n controlRefs: new Set(),\r\n interactionRefs: new Set(),\r\n issueRefs: new Set(),\r\n warningRefs: new Set(),\r\n sourceSurfaceRefs: new Set(),\r\n targetEdges: [],\r\n sourceEvidence: surface.evidence,\r\n codeRefs: [],\r\n requiresSourceReview: false,\r\n primary: new Set([surfaceRef]),\r\n supporting: new Set(),\r\n };\r\n}\r\n\r\nfunction resolutionCandidate(key: string, title: string, outcome: string, primaryRef: string, issue?: PlanningIssue): Candidate {\r\n return {\r\n key,\r\n memberKeys: [key],\r\n type: \"resolution\",\r\n title,\r\n observableOutcome: outcome,\r\n entryRefs: new Set(),\r\n surfaceRefs: new Set(),\r\n controlRefs: new Set(),\r\n interactionRefs: new Set(),\r\n issueRefs: new Set(issue ? [issue.id] : []),\r\n warningRefs: new Set(),\r\n sourceSurfaceRefs: new Set(),\r\n targetEdges: [],\r\n sourceEvidence: issue?.evidence ?? [],\r\n codeRefs: [],\r\n requiresSourceReview: true,\r\n primary: new Set([primaryRef]),\r\n supporting: new Set(issue?.relatedRefs ?? []),\r\n };\r\n}\r\n\r\nfunction enrichCandidateWithKnownRefs(candidate: Candidate, refs: Iterable<string | null | undefined>, facts: PlanningFactsSnapshot): Candidate {\r\n const queue = uniqueSorted(refs);\r\n const seen = new Set<string>();\r\n while (queue.length) {\r\n const ref = queue.shift()!;\r\n if (seen.has(ref)) continue;\r\n seen.add(ref);\r\n const surface = facts.surfaces.find((item) => item.id === ref);\r\n if (surface) {\r\n candidate.surfaceRefs.add(surface.id);\r\n continue;\r\n }\r\n const control = facts.controls.find((item) => item.id === ref);\r\n if (control) {\r\n candidate.controlRefs.add(control.id);\r\n if (control.surfaceId) queue.push(control.surfaceId);\r\n continue;\r\n }\r\n const entry = facts.entries.find((item) => item.id === ref);\r\n if (entry) {\r\n candidate.entryRefs.add(entry.id);\r\n if (entry.ownerSurfaceId) {\r\n candidate.sourceSurfaceRefs.add(entry.ownerSurfaceId);\r\n queue.push(entry.ownerSurfaceId);\r\n }\r\n for (const controlRef of facts.controls.filter((item) => item.surfaceId === entry.ownerSurfaceId && item.sourceCarrierId === entry.carrierId).map((item) => item.id)) queue.push(controlRef);\r\n continue;\r\n }\r\n const effect = facts.effects.find((item) => item.id === ref);\r\n if (effect) {\r\n candidate.interactionRefs.add(effect.id);\r\n queue.push(effect.sourceEntryId, effect.targetId);\r\n continue;\r\n }\r\n const issue = facts.issues.find((item) => item.id === ref);\r\n if (issue) {\r\n candidate.issueRefs.add(issue.id);\r\n queue.push(...issue.relatedRefs);\r\n }\r\n }\r\n candidate.sourceEvidence = uniqueBy([\r\n ...candidate.sourceEvidence,\r\n ...facts.surfaces.filter((item) => candidate.surfaceRefs.has(item.id)).flatMap((item) => item.evidence),\r\n ...facts.controls.filter((item) => candidate.controlRefs.has(item.id)).flatMap((item) => item.evidence),\r\n ...facts.entries.filter((item) => candidate.entryRefs.has(item.id)).flatMap((item) => item.evidence),\r\n ...facts.effects.filter((item) => candidate.interactionRefs.has(item.id)).flatMap((item) => item.evidence),\r\n ...facts.issues.filter((item) => candidate.issueRefs.has(item.id)).flatMap((item) => item.evidence),\r\n ], evidenceKey);\r\n candidate.codeRefs = uniqueBy([\r\n ...candidate.codeRefs,\r\n ...facts.entries.filter((item) => candidate.entryRefs.has(item.id)).flatMap((item) => item.trace.codeRefs),\r\n ], (item) => stableJson(item));\r\n return candidate;\r\n}\r\n\r\nfunction candidateCost(candidate: Candidate) {\r\n const core = {\r\n entries: uniqueSorted(candidate.entryRefs),\r\n surfaces: uniqueSorted(candidate.surfaceRefs),\r\n controls: uniqueSorted(candidate.controlRefs),\r\n effects: uniqueSorted(candidate.interactionRefs),\r\n issues: uniqueSorted(candidate.issueRefs),\r\n };\r\n return {\r\n factCount: new Set(Object.values(core).flat()).size,\r\n sourceFileCount: uniqueSorted(candidate.sourceEvidence.map((item) => item.file)).length,\r\n traceNodeCount: candidate.codeRefs.length,\r\n estimatedFactTokens: Math.ceil(Buffer.byteLength(stableJson(core), \"utf8\") / 3),\r\n };\r\n}\r\n\r\nfunction withinClosureBudget(candidate: Candidate): boolean {\r\n const cost = candidateCost(candidate);\r\n return cost.factCount <= DEFAULT_CLOSURE_BUDGET.maxFactCount\r\n && cost.sourceFileCount <= DEFAULT_CLOSURE_BUDGET.maxSourceFileCount\r\n && cost.traceNodeCount <= DEFAULT_CLOSURE_BUDGET.maxTraceNodeCount\r\n && cost.estimatedFactTokens <= DEFAULT_CLOSURE_BUDGET.maxEstimatedFactTokens;\r\n}\r\n\r\nfunction targetSignature(candidate: Candidate): string {\r\n return uniqueSorted(candidate.targetEdges.map((edge) => edge.targetSurfaceRef)).join(\"\\0\");\r\n}\r\n\r\nfunction sameSourceSurface(left: Candidate, right: Candidate): boolean {\r\n const leftSources = uniqueSorted(left.sourceSurfaceRefs);\r\n const rightSources = uniqueSorted(right.sourceSurfaceRefs);\r\n return leftSources.length === 1 && leftSources.join(\"\\0\") === rightSources.join(\"\\0\");\r\n}\r\n\r\nfunction combineCandidates(left: Candidate, right: Candidate): Candidate {\r\n const memberKeys = uniqueSorted([...left.memberKeys, ...right.memberKeys]);\r\n return {\r\n key: `merge:${sha256(memberKeys).slice(0, 16)}`,\r\n memberKeys,\r\n type: left.type,\r\n title: `${left.title};${right.title}`,\r\n observableOutcome: `${left.observableOutcome};${right.observableOutcome}`,\r\n entryRefs: new Set([...left.entryRefs, ...right.entryRefs]),\r\n surfaceRefs: new Set([...left.surfaceRefs, ...right.surfaceRefs]),\r\n controlRefs: new Set([...left.controlRefs, ...right.controlRefs]),\r\n interactionRefs: new Set([...left.interactionRefs, ...right.interactionRefs]),\r\n issueRefs: new Set([...left.issueRefs, ...right.issueRefs]),\r\n warningRefs: new Set([...left.warningRefs, ...right.warningRefs]),\r\n sourceSurfaceRefs: new Set([...left.sourceSurfaceRefs, ...right.sourceSurfaceRefs]),\r\n targetEdges: uniqueBy([...left.targetEdges, ...right.targetEdges], (edge) => `${edge.sourceSurfaceRef ?? \"\"}:${edge.targetSurfaceRef}:${edge.effectRef}`),\r\n sourceEvidence: uniqueBy([...left.sourceEvidence, ...right.sourceEvidence], evidenceKey),\r\n codeRefs: uniqueBy([...left.codeRefs, ...right.codeRefs], (item) => stableJson(item)),\r\n requiresSourceReview: left.requiresSourceReview || right.requiresSourceReview,\r\n primary: new Set([...left.primary, ...right.primary]),\r\n supporting: new Set([...left.supporting, ...right.supporting]),\r\n };\r\n}\r\n\r\nfunction codeRefKeys(candidate: Candidate): Set<string> {\r\n return new Set(candidate.codeRefs.map((item) => typeof item.id === \"string\" ? item.id : stableJson(item)));\r\n}\r\n\r\nfunction sharesCodeTrace(left: Candidate, right: Candidate): boolean {\r\n const leftRefs = codeRefKeys(left);\r\n return [...codeRefKeys(right)].some((ref) => leftRefs.has(ref));\r\n}\r\n\r\nfunction hasSystemEntry(candidate: Candidate, facts: PlanningFactsSnapshot): boolean {\r\n return facts.entries.some((entry) => candidate.entryRefs.has(entry.id)\r\n && candidate.sourceSurfaceRefs.has(entry.ownerSurfaceId ?? \"\")\r\n && entry.triggerCategory !== \"user\");\r\n}\r\n\r\nfunction summarizeMergedJourney(candidate: Candidate, facts: PlanningFactsSnapshot): Candidate {\r\n const sourceSurfaceRef = uniqueSorted(candidate.sourceSurfaceRefs)[0];\r\n const sourceName = facts.surfaces.find((surface) => surface.id === sourceSurfaceRef)?.name ?? sourceSurfaceRef ?? \"未归属页面\";\r\n const sourceEntries = facts.entries.filter((entry) => candidate.entryRefs.has(entry.id) && entry.ownerSurfaceId === sourceSurfaceRef);\r\n const userEntries = sourceEntries.filter((entry) => entry.triggerCategory === \"user\");\r\n const systemEntries = sourceEntries.filter((entry) => entry.triggerCategory !== \"user\");\r\n const outcomes = uniqueSorted(facts.effects.filter((effect) => candidate.interactionRefs.has(effect.id)).map((effect) => effectOutcome(effect, facts)));\r\n if (userEntries.length === 1 && systemEntries.length > 0) {\r\n const action = userEntries[0]!.label;\r\n return {\r\n ...candidate,\r\n title: `${sourceName}:完成${action}及后续系统回调`,\r\n observableOutcome: `在${sourceName}触发“${action}”,完成 ${systemEntries.length} 个后续系统回调${outcomes.length ? `并${outcomes.join(\"、\")}` : \"后验证可观察业务结果\"}`,\r\n };\r\n }\r\n return {\r\n ...candidate,\r\n title: `${sourceName}:完成 ${sourceEntries.length} 个关联行为${outcomes.length ? `并${outcomes.join(\"、\")}` : \"\"}`,\r\n observableOutcome: `在${sourceName}完成 ${sourceEntries.length} 个属于同一可观察责任的关联行为${outcomes.length ? `,最终${outcomes.join(\"、\")}` : \"并验证业务结果\"}`,\r\n };\r\n}\r\n\r\nfunction mergeCompatibleEntryCandidates(candidates: Candidate[], facts: PlanningFactsSnapshot): Candidate[] {\r\n const merged: Candidate[] = [];\r\n for (const candidate of [...candidates].sort((a, b) => a.key.localeCompare(b.key))) {\r\n if (candidate.type !== \"journey\") {\r\n merged.push(candidate);\r\n continue;\r\n }\r\n const compatibleIndex = merged.findIndex((current) => current.type === candidate.type\r\n && sameSourceSurface(current, candidate)\r\n && ((!current.requiresSourceReview\r\n && !candidate.requiresSourceReview\r\n && targetSignature(current) === targetSignature(candidate))\r\n || (sharesCodeTrace(current, candidate)\r\n && (hasSystemEntry(current, facts) || hasSystemEntry(candidate, facts))))\r\n && withinClosureBudget(combineCandidates(current, candidate)));\r\n if (compatibleIndex < 0) merged.push(candidate);\r\n else merged[compatibleIndex] = summarizeMergedJourney(combineCandidates(merged[compatibleIndex]!, candidate), facts);\r\n }\r\n return merged;\r\n}\r\n\r\nfunction resolutionSubject(candidate: Candidate): string | null {\r\n const sourceSurfaces = uniqueSorted(candidate.sourceSurfaceRefs);\r\n if (sourceSurfaces.length === 1) return `surface:${sourceSurfaces[0]}`;\r\n const firstEvidenceFile = candidate.sourceEvidence.find((item) => item.file)?.file;\r\n if (firstEvidenceFile) return `file:${firstEvidenceFile}`;\r\n const surfaces = uniqueSorted(candidate.surfaceRefs);\r\n return surfaces.length === 1 ? `surface:${surfaces[0]}` : null;\r\n}\r\n\r\nfunction resolutionSubjectLabel(candidate: Candidate, facts: PlanningFactsSnapshot): string {\r\n const sourceSurfaces = uniqueSorted(candidate.sourceSurfaceRefs);\r\n if (sourceSurfaces.length === 1) return facts.surfaces.find((surface) => surface.id === sourceSurfaces[0])?.name ?? sourceSurfaces[0]!;\r\n const firstEvidenceFile = candidate.sourceEvidence.find((item) => item.file)?.file;\r\n if (firstEvidenceFile) return firstEvidenceFile.split(/[\\\\/]/).at(-1)?.replace(/\\.[^.]+$/, \"\") ?? firstEvidenceFile;\r\n const surfaces = uniqueSorted(candidate.surfaceRefs);\r\n if (surfaces.length === 1) return facts.surfaces.find((surface) => surface.id === surfaces[0])?.name ?? surfaces[0]!;\r\n return \"未解析行为\";\r\n}\r\n\r\nfunction mergeResolutionCandidates(candidates: Candidate[], facts: PlanningFactsSnapshot): Candidate[] {\r\n const merged: Candidate[] = [];\r\n for (const candidate of [...candidates].sort((a, b) => a.key.localeCompare(b.key))) {\r\n const subject = candidate.type === \"resolution\" ? resolutionSubject(candidate) : null;\r\n const compatibleIndex = subject ? merged.findIndex((current) => current.type === \"resolution\"\r\n && resolutionSubject(current) === subject\r\n && withinClosureBudget(combineCandidates(current, candidate))) : -1;\r\n if (compatibleIndex < 0) merged.push(candidate);\r\n else {\r\n const combined = combineCandidates(merged[compatibleIndex]!, candidate);\r\n const label = resolutionSubjectLabel(combined, facts);\r\n merged[compatibleIndex] = {\r\n ...combined,\r\n title: `裁决 ${label} 的 ${combined.memberKeys.length} 组相关入口与关系`,\r\n observableOutcome: `确认 ${label} 中 ${combined.memberKeys.length} 组未解析入口或关系的归属与可观察结果,并形成可追溯修正`,\r\n };\r\n }\r\n }\r\n return merged;\r\n}\r\n\r\nfunction mergeLauncherInitializationCandidates(candidates: Candidate[], facts: PlanningFactsSnapshot): Candidate[] {\r\n let remaining = [...candidates];\r\n for (const launcherSurfaceRef of facts.app.launcherSurfaceIds) {\r\n const bootstrap = remaining.find((candidate) => candidate.type === \"bootstrap\" && candidate.surfaceRefs.has(launcherSurfaceRef));\r\n if (!bootstrap) continue;\r\n let merged = bootstrap;\r\n const absorbedKeys = new Set<string>();\r\n for (const candidate of remaining.filter((item) => item.type === \"journey\" && item.sourceSurfaceRefs.has(launcherSurfaceRef)).sort((a, b) => a.key.localeCompare(b.key))) {\r\n const sourceEntries = facts.entries.filter((entry) => candidate.entryRefs.has(entry.id) && entry.ownerSurfaceId === launcherSurfaceRef);\r\n if (sourceEntries.length === 0 || sourceEntries.some((entry) => entry.triggerCategory === \"user\")) continue;\r\n const combined = combineCandidates(merged, candidate);\r\n if (!withinClosureBudget(combined)) continue;\r\n merged = { ...combined, type: \"bootstrap\", title: bootstrap.title, observableOutcome: bootstrap.observableOutcome };\r\n absorbedKeys.add(candidate.key);\r\n }\r\n if (absorbedKeys.size > 0) remaining = remaining.map((candidate) => candidate.key === bootstrap.key ? merged : candidate).filter((candidate) => !absorbedKeys.has(candidate.key));\r\n }\r\n return remaining;\r\n}\r\n\r\nfunction chooseSurfaceOwners(candidates: Candidate[], facts: PlanningFactsSnapshot): { owners: Map<string, string>; provenSurfaceRefs: Set<string> } {\r\n const owners = new Map<string, string>();\r\n const provenSurfaceRefs = new Set<string>();\r\n const distance = new Map<string, number>();\r\n const choice = new Map<string, string>();\r\n for (const surfaceRef of facts.app.launcherSurfaceIds) {\r\n const launcherCandidates = candidates.filter((candidate) => candidate.type === \"bootstrap\" && candidate.surfaceRefs.has(surfaceRef));\r\n const selected = launcherCandidates.sort((a, b) => a.key.localeCompare(b.key))[0];\r\n if (selected) owners.set(surfaceRef, selected.key);\r\n provenSurfaceRefs.add(surfaceRef);\r\n distance.set(surfaceRef, 0);\r\n }\r\n const edges = candidates.flatMap((candidate) => candidate.targetEdges.map((edge) => ({ ...edge, candidate })))\r\n .sort((a, b) => `${a.effectRef}:${a.candidate.key}`.localeCompare(`${b.effectRef}:${b.candidate.key}`));\r\n let changed = true;\r\n while (changed) {\r\n changed = false;\r\n for (const edge of edges) {\r\n if (!edge.sourceSurfaceRef || !distance.has(edge.sourceSurfaceRef)) continue;\r\n const proposed = distance.get(edge.sourceSurfaceRef)! + 1;\r\n const signature = `${edge.effectRef}:${edge.candidate.key}`;\r\n const current = distance.get(edge.targetSurfaceRef);\r\n if (current === undefined || proposed < current || (proposed === current && signature < (choice.get(edge.targetSurfaceRef) ?? \"~\"))) {\r\n distance.set(edge.targetSurfaceRef, proposed);\r\n choice.set(edge.targetSurfaceRef, signature);\r\n owners.set(edge.targetSurfaceRef, edge.candidate.key);\r\n provenSurfaceRefs.add(edge.targetSurfaceRef);\r\n changed = true;\r\n }\r\n }\r\n }\r\n for (const surface of facts.surfaces) {\r\n if (owners.has(surface.id)) continue;\r\n const local = candidates.filter((candidate) => candidate.sourceSurfaceRefs.has(surface.id)).sort((a, b) => a.key.localeCompare(b.key))[0];\r\n if (local) owners.set(surface.id, local.key);\r\n }\r\n return { owners, provenSurfaceRefs };\r\n}\r\n\r\nfunction reportableRefs(facts: PlanningFactsSnapshot): Set<string> {\r\n return new Set(facts.requiredFactRefs);\r\n}\r\n\r\nfunction behaviorIdFor(candidate: Candidate): string {\r\n return `behavior:${sha256({\r\n type: candidate.type,\r\n primaryFactRefs: uniqueSorted(candidate.primary),\r\n path: {\r\n entries: uniqueSorted(candidate.entryRefs),\r\n effects: uniqueSorted(candidate.interactionRefs),\r\n surfaces: uniqueSorted(candidate.surfaceRefs),\r\n },\r\n }).slice(0, 16)}`;\r\n}\r\n\r\nfunction downstreamCounts(tasks: Array<{ id: string; dependsOnBehaviorIds: string[] }>): Map<string, number> {\r\n const children = new Map<string, string[]>();\r\n for (const task of tasks) for (const dependency of task.dependsOnBehaviorIds) children.set(dependency, [...(children.get(dependency) ?? []), task.id]);\r\n const out = new Map<string, number>();\r\n for (const task of tasks) {\r\n const seen = new Set<string>();\r\n const queue = [...(children.get(task.id) ?? [])];\r\n while (queue.length) {\r\n const next = queue.shift()!;\r\n if (seen.has(next)) continue;\r\n seen.add(next);\r\n queue.push(...(children.get(next) ?? []));\r\n }\r\n out.set(task.id, seen.size);\r\n }\r\n return out;\r\n}\r\n\r\nexport function compileBehaviorPlanFromPlanningFacts(facts: PlanningFactsSnapshot, androidFingerprint: string | null): BehaviorPlan {\r\n let candidates = mergeCompatibleEntryCandidates(facts.entries.map((entry) => candidateForEntry(entry.id, facts)), facts);\r\n for (const surfaceRef of facts.app.launcherSurfaceIds) {\r\n if (!candidates.some((candidate) => candidate.type === \"bootstrap\" && candidate.surfaceRefs.has(surfaceRef))) {\r\n candidates.push(bootstrapCandidateForSurface(surfaceRef, facts));\r\n }\r\n }\r\n candidates = mergeLauncherInitializationCandidates(candidates, facts);\r\n const coveredIssues = new Set(candidates.flatMap((candidate) => [...candidate.issueRefs]));\r\n for (const issue of facts.issues.filter((item) => item.blocking && !item.resolved && !coveredIssues.has(item.id))) {\r\n candidates.push(enrichCandidateWithKnownRefs(resolutionCandidate(`issue:${issue.id}`, `裁决:${issue.kind}`, issue.reason, issue.id, issue), [issue.id], facts));\r\n }\r\n candidates = mergeResolutionCandidates(candidates, facts);\r\n\r\n const ownerKeyByFactRef = new Map<string, string>();\r\n for (const candidate of candidates) {\r\n for (const entryRef of candidate.entryRefs) if (facts.entries.some((entry) => entry.id === entryRef) && !ownerKeyByFactRef.has(entryRef)) ownerKeyByFactRef.set(entryRef, candidate.key);\r\n for (const effectRef of candidate.interactionRefs) if (!ownerKeyByFactRef.has(effectRef)) ownerKeyByFactRef.set(effectRef, candidate.key);\r\n }\r\n for (const control of facts.controls) {\r\n const candidate = candidates.filter((item) => item.controlRefs.has(control.id)).sort((a, b) => a.key.localeCompare(b.key))[0];\r\n if (candidate) ownerKeyByFactRef.set(control.id, candidate.key);\r\n }\r\n const surfaceOwnership = chooseSurfaceOwners(candidates, facts);\r\n for (const [surfaceRef, ownerKey] of surfaceOwnership.owners) ownerKeyByFactRef.set(surfaceRef, ownerKey);\r\n\r\n for (const ref of facts.requiredFactRefs) {\r\n if (ownerKeyByFactRef.has(ref)) continue;\r\n const issue = facts.issues.find((item) => item.relatedRefs.includes(ref));\r\n const candidate = enrichCandidateWithKnownRefs(\r\n resolutionCandidate(`orphan:${ref}`, `补全未归属事实:${ref}`, issue?.reason ?? `为 ${ref} 建立可验证行为归属`, ref, issue),\r\n [ref, issue?.id],\r\n facts,\r\n );\r\n candidates.push(candidate);\r\n ownerKeyByFactRef.set(ref, candidate.key);\r\n }\r\n const candidatesBeforeFinalResolutionMerge = candidates;\r\n candidates = mergeResolutionCandidates(candidates, facts);\r\n for (const [ref, ownerKey] of ownerKeyByFactRef) {\r\n const previousOwner = candidatesBeforeFinalResolutionMerge.find((candidate) => candidate.key === ownerKey);\r\n if (!previousOwner) continue;\r\n const mergedOwner = candidates.find((candidate) => previousOwner.memberKeys.every((memberKey) => candidate.memberKeys.includes(memberKey)));\r\n if (mergedOwner) ownerKeyByFactRef.set(ref, mergedOwner.key);\r\n }\r\n for (const issue of facts.issues.filter((item) => item.blocking && !item.resolved)) {\r\n const candidate = candidates.filter((item) => item.issueRefs.has(issue.id)).sort((a, b) => a.key.localeCompare(b.key))[0];\r\n if (candidate) ownerKeyByFactRef.set(issue.id, candidate.key);\r\n }\r\n for (const candidate of candidates) candidate.primary.clear();\r\n for (const [ref, key] of ownerKeyByFactRef) candidates.find((candidate) => candidate.key === key)?.primary.add(ref);\r\n candidates = candidates.filter((candidate) => candidate.primary.size > 0);\r\n for (const candidate of candidates) {\r\n const closureRefs = new Set([...candidate.entryRefs, ...candidate.surfaceRefs, ...candidate.controlRefs, ...candidate.interactionRefs, ...candidate.issueRefs]);\r\n candidate.supporting = new Set([...closureRefs].filter((ref) => !candidate.primary.has(ref)));\r\n }\r\n\r\n const idByKey = new Map(candidates.map((candidate) => [candidate.key, behaviorIdFor(candidate)]));\r\n if (new Set(idByKey.values()).size !== candidates.length) throw new Error(\"Behavior ID collision while compiling plan\");\r\n const launcherResolvers = candidates.filter((candidate) => candidate.type === \"resolution\" && candidate.issueRefs.has(\"issue:launcher-unresolved\"));\r\n const taskDrafts = candidates.map((candidate) => {\r\n const dependencies = new Set<string>();\r\n if (candidate.type !== \"resolution\") {\r\n for (const sourceSurfaceRef of candidate.sourceSurfaceRefs) {\r\n if (!surfaceOwnership.provenSurfaceRefs.has(sourceSurfaceRef)) continue;\r\n const ownerKey = ownerKeyByFactRef.get(sourceSurfaceRef);\r\n if (ownerKey && ownerKey !== candidate.key) dependencies.add(idByKey.get(ownerKey)!);\r\n }\r\n if (facts.app.launcherOrigin === \"unresolved\") for (const resolver of launcherResolvers) dependencies.add(idByKey.get(resolver.key)!);\r\n }\r\n return { candidate, id: idByKey.get(candidate.key)!, dependsOnBehaviorIds: uniqueSorted(dependencies) };\r\n });\r\n const downstream = downstreamCounts(taskDrafts);\r\n const reportable = reportableRefs(facts);\r\n const responsibilities: BehaviorResponsibility[] = taskDrafts.map(({ candidate, id, dependsOnBehaviorIds }) => {\r\n const primaryFactRefs = uniqueSorted(candidate.primary);\r\n const supportingFactRefs = uniqueSorted(candidate.supporting);\r\n const core = {\r\n entries: uniqueSorted(candidate.entryRefs),\r\n surfaces: uniqueSorted(candidate.surfaceRefs),\r\n controls: uniqueSorted(candidate.controlRefs),\r\n effects: uniqueSorted(candidate.interactionRefs),\r\n issues: uniqueSorted(candidate.issueRefs),\r\n };\r\n const sourceFiles = uniqueSorted(candidate.sourceEvidence.map((item) => item.file));\r\n return {\r\n id,\r\n type: candidate.type,\r\n title: candidate.title,\r\n primaryFactRefs,\r\n supportingFactRefs,\r\n dependsOnBehaviorIds,\r\n closure: {\r\n entryRefs: core.entries,\r\n surfaceRefs: core.surfaces,\r\n controlRefs: core.controls,\r\n interactionRefs: core.effects,\r\n sourceEvidence: candidate.sourceEvidence,\r\n codeRefs: candidate.codeRefs,\r\n unresolvedRefs: core.issues,\r\n warningRefs: uniqueSorted(candidate.warningRefs),\r\n requiresSourceReview: candidate.requiresSourceReview,\r\n },\r\n acceptance: {\r\n observableOutcome: candidate.observableOutcome,\r\n requiredFactRefs: uniqueSorted([...primaryFactRefs.filter((ref) => reportable.has(ref)), ...core.effects]),\r\n verificationRequirements: candidate.type === \"resolution\"\r\n ? [\"复核 Android 源码或运行行为并写入可追溯 correction/discovery\", \"重新生成 Facts 或 TaskPlan 后确认阻塞项消失\"]\r\n : [\"从真实应用入口执行对应行为\", \"在 HarmonyOS 设备上验证可观察结果\", \"通过 Report Ref 绑定新鲜的受管测试证据\"],\r\n reportRefs: primaryFactRefs.filter((ref) => reportable.has(ref)),\r\n },\r\n estimate: {\r\n factCount: new Set([...primaryFactRefs, ...supportingFactRefs]).size,\r\n sourceFileCount: sourceFiles.length,\r\n traceNodeCount: candidate.codeRefs.length,\r\n estimatedFactTokens: Math.ceil(Buffer.byteLength(stableJson(core), \"utf8\") / 3),\r\n downstreamUnlockCount: downstream.get(id) ?? 0,\r\n },\r\n };\r\n }).sort((a, b) => typeOrder[a.type] - typeOrder[b.type] || a.id.localeCompare(b.id));\r\n\r\n const primaryOwnerByFactRef = Object.fromEntries([...ownerKeyByFactRef.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([ref, key]) => [ref, idByKey.get(key)!]));\r\n const supportingBehaviorIdsByFactRef: Record<string, string[]> = {};\r\n for (const responsibility of responsibilities) for (const ref of responsibility.supportingFactRefs) supportingBehaviorIdsByFactRef[ref] = uniqueSorted([...(supportingBehaviorIdsByFactRef[ref] ?? []), responsibility.id]);\r\n const planningWarnings: PlanningWarning[] = [...facts.diagnostics];\r\n for (const responsibility of responsibilities.filter((item) => item.closure.requiresSourceReview && item.type !== \"resolution\")) planningWarnings.push({ code: \"SOURCE_REVIEW_REQUIRED\", message: `${responsibility.id} has no direct observable interaction and requires Android source review`, relatedRefs: responsibility.closure.entryRefs });\r\n return {\r\n behaviorPlanVersion: BEHAVIOR_PLAN_VERSION,\r\n planningModelVersion: PLANNING_MODEL_VERSION,\r\n factsAdapterVersion: FACTS_ADAPTER_VERSION,\r\n plannerPolicyVersion: PLANNER_POLICY_VERSION,\r\n baseline: {\r\n factsSha256: facts.baseline.factsSha256,\r\n planningInputSha256: facts.baseline.planningInputSha256,\r\n androidFingerprint,\r\n specVersion: facts.baseline.specVersion,\r\n factsWireVersion: facts.baseline.wireVersion,\r\n },\r\n entryResolution: {\r\n launcherSurfaceRefs: facts.app.launcherSurfaceIds,\r\n launcherEntryRefs: facts.app.launcherEntryIds,\r\n origin: facts.app.launcherOrigin,\r\n },\r\n responsibilities,\r\n ownership: { primaryOwnerByFactRef, supportingBehaviorIdsByFactRef: Object.fromEntries(Object.entries(supportingBehaviorIdsByFactRef).sort(([a], [b]) => a.localeCompare(b))) },\r\n planningWarnings: uniqueBy(planningWarnings, (item) => `${item.code}:${item.message}:${item.relatedRefs.join(\",\")}`),\r\n };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\nimport { uniqueSorted } from \"./util.ts\";\r\n\r\nexport interface ExecutionPlanningContext {\r\n harmonyFilesByFactRef: Record<string, string[]>;\r\n globalHotspotFiles: string[];\r\n}\r\n\r\nfunction readJson(file: string): any | null {\r\n try { return JSON.parse(fs.readFileSync(file, \"utf8\")); }\r\n catch { return null; }\r\n}\r\n\r\nfunction inside(root: string, target: string): boolean {\r\n const relative = path.relative(root, target);\r\n return relative === \"\" || (relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\r\n}\r\n\r\nfunction validatedHarmonyFile(projectRoot: string, root: string, value: unknown): string {\r\n if (typeof value !== \"string\" || !value.trim()) throw new Error(\"Report HarmonyOS mapping must be a non-empty string\");\r\n const absolute = path.resolve(projectRoot, value);\r\n if (!inside(root, absolute)) throw new Error(`Report HarmonyOS mapping escapes the configured project: ${value}`);\r\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) throw new Error(`Report HarmonyOS mapping does not exist: ${value}`);\r\n const realRoot = fs.realpathSync(root);\r\n const realFile = fs.realpathSync(absolute);\r\n if (!inside(realRoot, realFile)) throw new Error(`Report HarmonyOS mapping resolves outside the configured project: ${value}`);\r\n return path.relative(projectRoot, absolute).replaceAll(\"\\\\\", \"/\");\r\n}\r\n\r\nfunction confinedReportFile(reportRoot: string, relative: string): string {\r\n if (!relative.trim() || path.isAbsolute(relative)) throw new Error(`Report shard path must be relative: ${relative}`);\r\n const absolute = path.resolve(reportRoot, relative);\r\n if (!inside(reportRoot, absolute) || absolute === reportRoot) throw new Error(`Report shard escapes report root: ${relative}`);\r\n if (!fs.existsSync(absolute) || !fs.statSync(absolute).isFile()) throw new Error(`Report shard does not exist: ${relative}`);\r\n const realRoot = fs.realpathSync(reportRoot);\r\n const realFile = fs.realpathSync(absolute);\r\n if (!inside(realRoot, realFile)) throw new Error(`Report shard resolves outside report root: ${relative}`);\r\n return realFile;\r\n}\r\n\r\nfunction reportHarmonyFiles(projectRoot: string, root: string): Record<string, string[]> {\r\n const reportRoot = path.join(migrationDirectory(projectRoot), \"report\");\r\n const index = readJson(path.join(reportRoot, \"index.json\"));\r\n if (!index) return {};\r\n const shardFiles = [\r\n ...(index.pages ?? []).map((item: any) => item.file),\r\n index.unassignedEntriesFile,\r\n index.interactionsFile,\r\n index.discoveriesFile,\r\n ].filter((value): value is string => typeof value === \"string\");\r\n const result: Record<string, string[]> = {};\r\n for (const relative of shardFiles) {\r\n const document = readJson(confinedReportFile(reportRoot, relative));\r\n if (!document) continue;\r\n const items = [\r\n document.page,\r\n ...(document.controls ?? []),\r\n ...(document.entries ?? []),\r\n ...(document.interactions ?? []),\r\n ...(document.items ?? []),\r\n ].filter(Boolean);\r\n for (const item of items) {\r\n if (typeof item.ref !== \"string\" || !Array.isArray(item.harmonyosFiles)) continue;\r\n result[item.ref] = uniqueSorted(item.harmonyosFiles.map((value: unknown) => validatedHarmonyFile(projectRoot, root, value)));\r\n }\r\n }\r\n return Object.fromEntries(Object.entries(result).sort(([left], [right]) => left.localeCompare(right)));\r\n}\r\n\r\nfunction harmonyRoot(projectRoot: string): string {\r\n const config = readJson(path.join(migrationDirectory(projectRoot), \"config.json\"));\r\n const configured = typeof config?.harmonyProject === \"string\" ? config.harmonyProject : \"ohos\";\r\n return path.isAbsolute(configured) ? configured : path.resolve(projectRoot, configured);\r\n}\r\n\r\nfunction existingGlobalHotspots(projectRoot: string): string[] {\r\n const root = harmonyRoot(projectRoot);\r\n if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return [];\r\n const relativeRoot = path.relative(projectRoot, root).replaceAll(\"\\\\\", \"/\");\r\n const candidates = [\r\n \"build-profile.json5\",\r\n \"AppScope/app.json5\",\r\n \"oh-package.json5\",\r\n \"entry/oh-package.json5\",\r\n \"entry/src/main/module.json5\",\r\n \"entry/src/main/resources/base/profile/main_pages.json\",\r\n \"entry/src/main/ets/entryability/EntryAbility.ets\",\r\n \"entry/src/main/ets/pages/Index.ets\",\r\n \"entry/src/main/ets/common/RouteConstants.ets\",\r\n ];\r\n return candidates.filter((relative) => fs.existsSync(path.join(root, relative)))\r\n .map((relative) => `${relativeRoot}/${relative}`.replace(/^\\.\\//, \"\"))\r\n .sort();\r\n}\r\n\r\nexport function loadExecutionPlanningContext(projectRootArgument: string): ExecutionPlanningContext {\r\n const projectRoot = path.resolve(projectRootArgument);\r\n const root = harmonyRoot(projectRoot);\r\n const rootAvailable = fs.existsSync(root) && fs.statSync(root).isDirectory();\r\n return {\r\n harmonyFilesByFactRef: rootAvailable ? reportHarmonyFiles(projectRoot, root) : {},\r\n globalHotspotFiles: existingGlobalHotspots(projectRoot),\r\n };\r\n}\r\n\r\nexport const emptyExecutionPlanningContext: ExecutionPlanningContext = {\r\n harmonyFilesByFactRef: {},\r\n globalHotspotFiles: [],\r\n};\r\n","import { compileBehaviorPlanFromPlanningFacts } from \"./compiler.ts\";\r\nimport { emptyExecutionPlanningContext, type ExecutionPlanningContext } from \"./execution-context.ts\";\r\nimport type {\r\n BehaviorPlan,\r\n BehaviorResponsibility,\r\n FileConflictEdge,\r\n PageWorkPackage,\r\n PlannedTask,\r\n PlanningFactsSnapshot,\r\n TaskPlan,\r\n TaskType,\r\n} from \"./types.ts\";\r\nimport {\r\n DEFAULT_EXECUTION_BUDGET,\r\n EXECUTION_PLAN_VERSION,\r\n TASK_PLAN_VERSION,\r\n} from \"./types.ts\";\r\nimport { sha256, stableJson, uniqueBy, uniqueSorted } from \"./util.ts\";\r\n\r\ninterface ExecutionCandidate {\r\n behaviorIds: string[];\r\n canonicalPageRef: string | null;\r\n type: TaskType;\r\n sourceFiles: string[];\r\n targetPageRefs: string[];\r\n codeRefKeys: string[];\r\n capabilityRefs: string[];\r\n}\r\n\r\nconst typeOrder: Record<TaskType, number> = {\r\n resolution: 0,\r\n bootstrap: 1,\r\n capability: 2,\r\n journey: 3,\r\n assembly: 4,\r\n regression: 5,\r\n};\r\n\r\nfunction isReusableSurface(kind: string): boolean {\r\n return /(?:list[-_ ]?item|item|reusable|layout|custom[-_ ]?view|cell|row)/i.test(kind);\r\n}\r\n\r\nfunction isHostedOverlay(kind: string): boolean {\r\n return /(?:dialog|bottom[-_ ]?sheet|sheet|popup|overlay)/i.test(kind);\r\n}\r\n\r\nexport function canonicalPageRefs(facts: PlanningFactsSnapshot): Record<string, string> {\r\n const byId = new Map(facts.surfaces.map((surface) => [surface.id, surface]));\r\n const memo = new Map<string, string>();\r\n const resolve = (surfaceRef: string, visiting = new Set<string>()): string => {\r\n if (memo.has(surfaceRef)) return memo.get(surfaceRef)!;\r\n const surface = byId.get(surfaceRef);\r\n if (!surface || visiting.has(surfaceRef)) return surfaceRef;\r\n visiting.add(surfaceRef);\r\n const parentPages = uniqueSorted(surface.parentSurfaceIds.filter((ref) => byId.has(ref)).map((ref) => resolve(ref, visiting)));\r\n const canonical = parentPages.length === 1 && (isReusableSurface(surface.kind) || isHostedOverlay(surface.kind) || !surface.topLevel)\r\n ? parentPages[0]!\r\n : surfaceRef;\r\n visiting.delete(surfaceRef);\r\n memo.set(surfaceRef, canonical);\r\n return canonical;\r\n };\r\n for (const surface of facts.surfaces) resolve(surface.id);\r\n return Object.fromEntries([...memo.entries()].sort(([left], [right]) => left.localeCompare(right)));\r\n}\r\n\r\nfunction behaviorSourceSurfaceRefs(behavior: BehaviorResponsibility, facts: PlanningFactsSnapshot): string[] {\r\n const entryRefs = new Set(behavior.closure.entryRefs);\r\n const fromEntries = facts.entries.filter((entry) => entryRefs.has(entry.id) && entry.ownerSurfaceId).map((entry) => entry.ownerSurfaceId!);\r\n if (fromEntries.length) return uniqueSorted(fromEntries);\r\n const primarySurfaces = behavior.primaryFactRefs.filter((ref) => facts.surfaces.some((surface) => surface.id === ref));\r\n return uniqueSorted(primarySurfaces.length ? primarySurfaces : behavior.closure.surfaceRefs);\r\n}\r\n\r\nfunction behaviorCanonicalPage(behavior: BehaviorResponsibility, facts: PlanningFactsSnapshot, canonicalBySurface: Record<string, string>): string | null {\r\n const pages = uniqueSorted(behaviorSourceSurfaceRefs(behavior, facts).map((ref) => canonicalBySurface[ref] ?? ref));\r\n return pages[0] ?? null;\r\n}\r\n\r\nfunction codeRefKey(value: Record<string, unknown>): string {\r\n if (typeof value.id === \"string\") return value.id;\r\n return stableJson(Object.fromEntries([\"file\", \"name\", \"symbol\", \"kind\", \"type\", \"capabilityRef\"].filter((key) => value[key] !== undefined).map((key) => [key, value[key]])));\r\n}\r\n\r\nfunction behaviorCapabilityRefs(behavior: BehaviorResponsibility): string[] {\r\n return uniqueSorted(behavior.closure.codeRefs.flatMap((item) => {\r\n if (typeof item.capabilityRef === \"string\" && item.capabilityRef.length > 0) return [item.capabilityRef];\r\n if (item.kind === \"capability\" && typeof item.id === \"string\" && item.id.length > 0) return [item.id];\r\n return [];\r\n }));\r\n}\r\n\r\nfunction candidateForBehavior(behavior: BehaviorResponsibility, facts: PlanningFactsSnapshot, canonicalBySurface: Record<string, string>): ExecutionCandidate {\r\n const effectRefs = new Set(behavior.closure.interactionRefs);\r\n const targets = facts.effects.filter((effect) => effectRefs.has(effect.id) && effect.targetKind === \"surface\")\r\n .map((effect) => canonicalBySurface[effect.targetId] ?? effect.targetId);\r\n return {\r\n behaviorIds: [behavior.id],\r\n canonicalPageRef: behaviorCanonicalPage(behavior, facts, canonicalBySurface),\r\n type: behavior.type,\r\n sourceFiles: uniqueSorted([\r\n ...behavior.closure.sourceEvidence.map((item) => item.file),\r\n ...behavior.closure.codeRefs.flatMap((item) => typeof item.file === \"string\" ? [item.file] : []),\r\n ]),\r\n targetPageRefs: uniqueSorted(targets),\r\n codeRefKeys: uniqueSorted(behavior.closure.codeRefs.map(codeRefKey)),\r\n capabilityRefs: behaviorCapabilityRefs(behavior),\r\n };\r\n}\r\n\r\nfunction combineCandidates(left: ExecutionCandidate, right: ExecutionCandidate): ExecutionCandidate {\r\n return {\r\n behaviorIds: uniqueSorted([...left.behaviorIds, ...right.behaviorIds]),\r\n canonicalPageRef: left.canonicalPageRef,\r\n type: left.type,\r\n sourceFiles: uniqueSorted([...left.sourceFiles, ...right.sourceFiles]),\r\n targetPageRefs: uniqueSorted([...left.targetPageRefs, ...right.targetPageRefs]),\r\n codeRefKeys: uniqueSorted([...left.codeRefKeys, ...right.codeRefKeys]),\r\n capabilityRefs: uniqueSorted([...left.capabilityRefs, ...right.capabilityRefs]),\r\n };\r\n}\r\n\r\nfunction intersects(left: string[], right: string[]): boolean {\r\n const values = new Set(left);\r\n return right.some((value) => values.has(value));\r\n}\r\n\r\nfunction behaviorRefs(candidate: ExecutionCandidate, behaviors: Map<string, BehaviorResponsibility>): BehaviorResponsibility[] {\r\n return candidate.behaviorIds.map((id) => behaviors.get(id)!).filter(Boolean);\r\n}\r\n\r\nfunction isRoutingAssembly(candidate: ExecutionCandidate): boolean {\r\n return candidate.type === \"journey\"\r\n && candidate.targetPageRefs.some((target) => target !== candidate.canonicalPageRef);\r\n}\r\n\r\nfunction routingHotspotFiles(context: ExecutionPlanningContext): string[] {\r\n return context.globalHotspotFiles.filter((file) => /(?:main_pages\\.json|RouteConstants\\.ets|\\/pages\\/Index\\.ets)$/i.test(file));\r\n}\r\n\r\nfunction mappedTargetFiles(candidate: ExecutionCandidate, primaryRefs: string[], context: ExecutionPlanningContext): string[] {\r\n const mapped = uniqueSorted(primaryRefs.flatMap((ref) => context.harmonyFilesByFactRef[ref] ?? []));\r\n if (candidate.type === \"bootstrap\") return uniqueSorted([...mapped, ...context.globalHotspotFiles]);\r\n if (isRoutingAssembly(candidate)) return uniqueSorted([...mapped, ...routingHotspotFiles(context)]);\r\n return mapped;\r\n}\r\n\r\nfunction executionCost(candidate: ExecutionCandidate, behaviors: Map<string, BehaviorResponsibility>, context: ExecutionPlanningContext) {\r\n const members = behaviorRefs(candidate, behaviors);\r\n const factRefs = uniqueSorted(members.flatMap((item) => [...item.primaryFactRefs, ...item.supportingFactRefs]));\r\n const mappedFiles = mappedTargetFiles(candidate, factRefs, context);\r\n const productionFiles = mappedFiles.filter((file) => !/(?:^|\\/)(?:ohosTest|test|tests)(?:\\/|$)|(?:Test|\\.test)\\.(?:ets|ts)$/i.test(file));\r\n const testFiles = mappedFiles.filter((file) => !productionFiles.includes(file));\r\n return {\r\n behaviorCount: members.length,\r\n observableOutcomeCount: uniqueSorted(members.map((item) => item.acceptance.observableOutcome)).length,\r\n productionFileCount: productionFiles.length,\r\n testFileCount: testFiles.length,\r\n capabilityCount: candidate.capabilityRefs.length,\r\n factCount: new Set(members.flatMap((item) => [...item.primaryFactRefs, ...item.supportingFactRefs])).size,\r\n sourceFileCount: uniqueSorted(members.flatMap((item) => [\r\n ...item.closure.sourceEvidence.map((evidence) => evidence.file),\r\n ...item.closure.codeRefs.flatMap((codeRef) => typeof codeRef.file === \"string\" ? [codeRef.file] : []),\r\n ])).length,\r\n traceNodeCount: uniqueBy(members.flatMap((item) => item.closure.codeRefs), codeRefKey).length,\r\n estimatedFactTokens: members.reduce((total, item) => total + item.estimate.estimatedFactTokens, 0),\r\n };\r\n}\r\n\r\nfunction withinExecutionBudget(candidate: ExecutionCandidate, behaviors: Map<string, BehaviorResponsibility>, context: ExecutionPlanningContext): boolean {\r\n const cost = executionCost(candidate, behaviors, context);\r\n return cost.behaviorCount <= DEFAULT_EXECUTION_BUDGET.maxBehaviorCount\r\n && cost.observableOutcomeCount <= DEFAULT_EXECUTION_BUDGET.maxObservableOutcomeCount\r\n && cost.productionFileCount <= DEFAULT_EXECUTION_BUDGET.maxProductionFileCount\r\n && cost.testFileCount <= DEFAULT_EXECUTION_BUDGET.maxTestFileCount\r\n && cost.capabilityCount <= DEFAULT_EXECUTION_BUDGET.maxCapabilityCount\r\n && cost.factCount <= DEFAULT_EXECUTION_BUDGET.maxFactCount\r\n && cost.sourceFileCount <= DEFAULT_EXECUTION_BUDGET.maxSourceFileCount\r\n && cost.traceNodeCount <= DEFAULT_EXECUTION_BUDGET.maxTraceNodeCount\r\n && cost.estimatedFactTokens <= DEFAULT_EXECUTION_BUDGET.maxEstimatedFactTokens;\r\n}\r\n\r\nfunction shouldMerge(left: ExecutionCandidate, right: ExecutionCandidate, behaviors: Map<string, BehaviorResponsibility>, facts: PlanningFactsSnapshot, context: ExecutionPlanningContext): boolean {\r\n if (left.type !== \"journey\" || right.type !== \"journey\" || left.canonicalPageRef !== right.canonicalPageRef) return false;\r\n const members = [...behaviorRefs(left, behaviors), ...behaviorRefs(right, behaviors)];\r\n if (members.some((item) => item.closure.requiresSourceReview || item.closure.unresolvedRefs.length > 0)) return false;\r\n const combined = combineCandidates(left, right);\r\n if (!withinExecutionBudget(combined, behaviors, context)) return false;\r\n const behaviorEntries = (candidate: ExecutionCandidate) => uniqueSorted(behaviorRefs(candidate, behaviors).flatMap((item) => item.closure.entryRefs));\r\n const targetedEntries = (candidate: ExecutionCandidate) => {\r\n const effects = new Set(behaviorRefs(candidate, behaviors).flatMap((item) => item.closure.interactionRefs));\r\n return uniqueSorted([...effects].flatMap((effectRef) => {\r\n const effect = facts.effects.find((item) => item.id === effectRef);\r\n return effect?.targetKind === \"entry\" ? [effect.targetId] : [];\r\n }));\r\n };\r\n const callbackLinked = intersects(targetedEntries(left), behaviorEntries(right)) || intersects(targetedEntries(right), behaviorEntries(left));\r\n if (callbackLinked || intersects(left.codeRefKeys, right.codeRefKeys)) return true;\r\n const sharedSource = intersects(left.sourceFiles, right.sourceFiles);\r\n const sharedTarget = left.targetPageRefs.length > 0 && right.targetPageRefs.length > 0 && intersects(left.targetPageRefs, right.targetPageRefs);\r\n const sharedCapability = intersects(left.capabilityRefs, right.capabilityRefs);\r\n return sharedSource && (sharedTarget || sharedCapability);\r\n}\r\n\r\nfunction clusterBehaviors(plan: BehaviorPlan, facts: PlanningFactsSnapshot, context: ExecutionPlanningContext): ExecutionCandidate[] {\r\n const behaviors = new Map(plan.responsibilities.map((item) => [item.id, item]));\r\n const canonicalBySurface = canonicalPageRefs(facts);\r\n const clusters: ExecutionCandidate[] = [];\r\n for (const next of plan.responsibilities.map((item) => candidateForBehavior(item, facts, canonicalBySurface))) {\r\n const compatible = clusters.findIndex((current) => shouldMerge(current, next, behaviors, facts, context));\r\n if (compatible < 0) clusters.push(next);\r\n else clusters[compatible] = combineCandidates(clusters[compatible]!, next);\r\n }\r\n return clusters;\r\n}\r\n\r\nfunction workPackageId(candidate: Pick<ExecutionCandidate, \"canonicalPageRef\" | \"type\">): string | null {\r\n if (candidate.type === \"resolution\") return null;\r\n return `package:${sha256({ kind: \"page\", page: candidate.canonicalPageRef ?? \"unassigned\" }).slice(0, 16)}`;\r\n}\r\n\r\nfunction taskId(candidate: ExecutionCandidate): string {\r\n return `task:${sha256({ page: candidate.canonicalPageRef, type: candidate.type, behaviorIds: candidate.behaviorIds }).slice(0, 16)}`;\r\n}\r\n\r\nfunction taskTitle(candidate: ExecutionCandidate, members: BehaviorResponsibility[], facts: PlanningFactsSnapshot): string {\r\n if (members.length === 1) return members[0]!.title;\r\n const pageName = facts.surfaces.find((surface) => surface.id === candidate.canonicalPageRef)?.name ?? candidate.canonicalPageRef ?? \"未归属模块\";\r\n return `${pageName}:完成 ${members.length} 个相关行为闭环`;\r\n}\r\n\r\nfunction aggregateClosure(members: BehaviorResponsibility[]): BehaviorResponsibility[\"closure\"] {\r\n return {\r\n entryRefs: uniqueSorted(members.flatMap((item) => item.closure.entryRefs)),\r\n surfaceRefs: uniqueSorted(members.flatMap((item) => item.closure.surfaceRefs)),\r\n controlRefs: uniqueSorted(members.flatMap((item) => item.closure.controlRefs)),\r\n interactionRefs: uniqueSorted(members.flatMap((item) => item.closure.interactionRefs)),\r\n sourceEvidence: uniqueBy(members.flatMap((item) => item.closure.sourceEvidence), (item) => `${item.file}:${item.symbol ?? \"\"}:${item.line ?? \"\"}:${item.endLine ?? \"\"}`),\r\n codeRefs: uniqueBy(members.flatMap((item) => item.closure.codeRefs), codeRefKey),\r\n unresolvedRefs: uniqueSorted(members.flatMap((item) => item.closure.unresolvedRefs)),\r\n warningRefs: uniqueSorted(members.flatMap((item) => item.closure.warningRefs)),\r\n requiresSourceReview: members.some((item) => item.closure.requiresSourceReview),\r\n };\r\n}\r\n\r\nfunction primaryModule(candidate: ExecutionCandidate): string {\r\n if (candidate.type === \"bootstrap\") return \"foundation:application-shell\";\r\n if (candidate.type === \"resolution\") return `resolution:${candidate.behaviorIds[0]}`;\r\n if (isRoutingAssembly(candidate)) return \"assembly:routing\";\r\n return candidate.canonicalPageRef ? `page:${candidate.canonicalPageRef}` : \"page:unassigned\";\r\n}\r\n\r\nfunction initialTasks(clusters: ExecutionCandidate[], behaviorPlan: BehaviorPlan, facts: PlanningFactsSnapshot, canonicalBySurface: Record<string, string>, context: ExecutionPlanningContext): PlannedTask[] {\r\n const behaviors = new Map(behaviorPlan.responsibilities.map((item) => [item.id, item]));\r\n return clusters.map((candidate) => {\r\n const members = behaviorRefs(candidate, behaviors);\r\n const primaryFactRefs = uniqueSorted(members.flatMap((item) => item.primaryFactRefs));\r\n const supportingFactRefs = uniqueSorted(members.flatMap((item) => item.supportingFactRefs).filter((ref) => !primaryFactRefs.includes(ref)));\r\n const mappedFiles = mappedTargetFiles(candidate, [...primaryFactRefs, ...supportingFactRefs], context);\r\n let ownedFiles: string[];\r\n if (candidate.type === \"resolution\") ownedFiles = [];\r\n else if (candidate.type === \"bootstrap\") ownedFiles = mappedFiles;\r\n else ownedFiles = mappedFiles.filter((file) => isRoutingAssembly(candidate) || !context.globalHotspotFiles.includes(file));\r\n const cost = executionCost(candidate, behaviors, context);\r\n const outcomes = uniqueSorted(members.map((item) => item.acceptance.observableOutcome));\r\n const closure = aggregateClosure(members);\r\n const pageScopes = uniqueSorted(closure.surfaceRefs.map((surfaceRef) => `page:${canonicalBySurface[surfaceRef] ?? surfaceRef}`));\r\n const exclusiveScopes = candidate.type === \"resolution\"\r\n ? [`resolution:${candidate.behaviorIds[0]}`]\r\n : uniqueSorted([\r\n ...(candidate.type === \"bootstrap\" ? [\"foundation:application-shell\"] : []),\r\n ...(isRoutingAssembly(candidate) ? [\"assembly:routing\"] : []),\r\n ...pageScopes,\r\n ...(pageScopes.length === 0 ? [candidate.canonicalPageRef ? `page:${candidate.canonicalPageRef}` : `${candidate.type}:unassigned`] : []),\r\n ]);\r\n const item: PlannedTask = {\r\n id: taskId(candidate),\r\n type: candidate.type,\r\n title: taskTitle(candidate, members, facts),\r\n workPackageId: workPackageId(candidate),\r\n canonicalPageRef: candidate.canonicalPageRef,\r\n primaryModule: primaryModule(candidate),\r\n behaviorIds: candidate.behaviorIds,\r\n primaryFactRefs,\r\n supportingFactRefs,\r\n dependsOnTaskIds: [],\r\n conflictsWithTaskIds: [],\r\n writeOwnership: {\r\n ownedFiles,\r\n readOnlyFiles: [],\r\n exclusiveScopes,\r\n forbiddenGlobalFiles: candidate.type === \"bootstrap\" ? [] : context.globalHotspotFiles.filter((file) => !ownedFiles.includes(file)),\r\n },\r\n dependencyInterfaces: [],\r\n readyGate: {\r\n semanticsResolved: candidate.type === \"resolution\" || closure.unresolvedRefs.length === 0,\r\n dependencyInterfacesStable: true,\r\n writeOwnershipResolved: ownedFiles.length > 0 || exclusiveScopes.length > 0,\r\n contextWithinBudget: members.length === 1 || withinExecutionBudget(candidate, behaviors, context),\r\n acceptanceExecutable: members.every((member) => member.acceptance.verificationRequirements.length > 0),\r\n },\r\n closure,\r\n acceptance: {\r\n observableOutcome: outcomes.join(\";\"),\r\n observableOutcomes: outcomes,\r\n requiredFactRefs: uniqueSorted(members.flatMap((item) => item.acceptance.requiredFactRefs)),\r\n verificationRequirements: uniqueSorted(members.flatMap((item) => item.acceptance.verificationRequirements)),\r\n reportRefs: uniqueSorted(members.flatMap((item) => item.acceptance.reportRefs)),\r\n },\r\n estimate: {\r\n factCount: cost.factCount,\r\n sourceFileCount: cost.sourceFileCount,\r\n traceNodeCount: cost.traceNodeCount,\r\n estimatedFactTokens: cost.estimatedFactTokens,\r\n downstreamUnlockCount: 0,\r\n behaviorCount: cost.behaviorCount,\r\n observableOutcomeCount: cost.observableOutcomeCount,\r\n productionFileCount: cost.productionFileCount,\r\n testFileCount: cost.testFileCount,\r\n capabilityCount: cost.capabilityCount,\r\n },\r\n };\r\n return item;\r\n }).sort((left, right) => typeOrder[left.type] - typeOrder[right.type] || left.id.localeCompare(right.id));\r\n}\r\n\r\nfunction hasPath(tasks: Map<string, PlannedTask>, from: string, to: string): boolean {\r\n const seen = new Set<string>();\r\n const queue = [...(tasks.get(from)?.dependsOnTaskIds ?? [])];\r\n while (queue.length) {\r\n const next = queue.shift()!;\r\n if (next === to) return true;\r\n if (seen.has(next)) continue;\r\n seen.add(next);\r\n queue.push(...(tasks.get(next)?.dependsOnTaskIds ?? []));\r\n }\r\n return false;\r\n}\r\n\r\nfunction addDependency(tasks: Map<string, PlannedTask>, taskId: string, dependencyId: string): void {\r\n if (taskId === dependencyId || hasPath(tasks, dependencyId, taskId)) return;\r\n const task = tasks.get(taskId)!;\r\n task.dependsOnTaskIds = uniqueSorted([...task.dependsOnTaskIds, dependencyId]);\r\n}\r\n\r\nfunction orderPackageLane(items: PlannedTask[]): PlannedTask[] {\r\n const ids = new Set(items.map((item) => item.id));\r\n const remaining = new Set(ids);\r\n const result: PlannedTask[] = [];\r\n while (remaining.size) {\r\n const ready = items.filter((item) => remaining.has(item.id) && item.dependsOnTaskIds.filter((dependency) => ids.has(dependency)).every((dependency) => !remaining.has(dependency)))\r\n .sort((left, right) => typeOrder[left.type] - typeOrder[right.type] || left.id.localeCompare(right.id));\r\n const selected = ready[0] ?? items.filter((item) => remaining.has(item.id)).sort((left, right) => left.id.localeCompare(right.id))[0]!;\r\n result.push(selected);\r\n remaining.delete(selected.id);\r\n }\r\n return result;\r\n}\r\n\r\nfunction packageSerializationRanks(tasks: PlannedTask[]): Map<string, number> {\r\n const packageIds = uniqueSorted(tasks.flatMap((task) => task.workPackageId ? [task.workPackageId] : []));\r\n const taskById = new Map(tasks.map((task) => [task.id, task]));\r\n const dependencies = new Map(packageIds.map((packageId) => [packageId, new Set<string>()]));\r\n for (const task of tasks) {\r\n if (!task.workPackageId) continue;\r\n for (const dependencyId of task.dependsOnTaskIds) {\r\n const dependencyPackageId = taskById.get(dependencyId)?.workPackageId;\r\n if (dependencyPackageId && dependencyPackageId !== task.workPackageId) dependencies.get(task.workPackageId)!.add(dependencyPackageId);\r\n }\r\n }\r\n\r\n const remaining = new Set(packageIds);\r\n const ranks = new Map<string, number>();\r\n while (remaining.size) {\r\n const ready = packageIds.filter((packageId) => remaining.has(packageId)\r\n && [...dependencies.get(packageId)!].every((dependencyId) => !remaining.has(dependencyId)));\r\n // A pre-existing package cycle is rejected by validation. Keep compilation deterministic\r\n // so diagnostics remain reproducible without letting conflict discovery loop forever.\r\n const selected = ready[0] ?? packageIds.find((packageId) => remaining.has(packageId))!;\r\n ranks.set(selected, ranks.size);\r\n remaining.delete(selected);\r\n }\r\n return ranks;\r\n}\r\n\r\nfunction conflictReasons(left: PlannedTask, right: PlannedTask): string[] {\r\n const ownedOverlap = left.writeOwnership.ownedFiles.filter((file) => right.writeOwnership.ownedFiles.includes(file)).map((file) => `owned-file:${file}`);\r\n const scopeOverlap = left.writeOwnership.exclusiveScopes.filter((scope) => right.writeOwnership.exclusiveScopes.includes(scope)).map((scope) => `exclusive-scope:${scope}`);\r\n return uniqueSorted([...ownedOverlap, ...scopeOverlap]);\r\n}\r\n\r\nfunction wireDependenciesAndConflicts(tasks: PlannedTask[], behaviorPlan: BehaviorPlan): FileConflictEdge[] {\r\n const byId = new Map(tasks.map((item) => [item.id, item]));\r\n const taskByBehavior = new Map(tasks.flatMap((item) => item.behaviorIds.map((behaviorId) => [behaviorId, item.id] as const)));\r\n const behaviorById = new Map(behaviorPlan.responsibilities.map((item) => [item.id, item]));\r\n for (const task of tasks) {\r\n const dependencies = task.behaviorIds.flatMap((behaviorId) => behaviorById.get(behaviorId)?.dependsOnBehaviorIds ?? [])\r\n .map((behaviorId) => taskByBehavior.get(behaviorId))\r\n .filter((id): id is string => Boolean(id) && id !== task.id);\r\n task.dependsOnTaskIds = uniqueSorted(dependencies);\r\n }\r\n const packages = new Map<string, PlannedTask[]>();\r\n for (const task of tasks) {\r\n if (task.workPackageId === null) continue;\r\n packages.set(task.workPackageId, [...(packages.get(task.workPackageId) ?? []), task]);\r\n }\r\n for (const items of packages.values()) {\r\n const lane = orderPackageLane(items);\r\n for (let index = 1; index < lane.length; index++) addDependency(byId, lane[index]!.id, lane[index - 1]!.id);\r\n }\r\n const packageRanks = packageSerializationRanks(tasks);\r\n const edges: FileConflictEdge[] = [];\r\n for (let leftIndex = 0; leftIndex < tasks.length; leftIndex++) {\r\n for (let rightIndex = leftIndex + 1; rightIndex < tasks.length; rightIndex++) {\r\n const left = tasks[leftIndex]!;\r\n const right = tasks[rightIndex]!;\r\n const reasons = conflictReasons(left, right);\r\n if (!reasons.length) continue;\r\n edges.push({ leftTaskId: left.id, rightTaskId: right.id, reasons });\r\n left.conflictsWithTaskIds = uniqueSorted([...left.conflictsWithTaskIds, right.id]);\r\n right.conflictsWithTaskIds = uniqueSorted([...right.conflictsWithTaskIds, left.id]);\r\n if (hasPath(byId, left.id, right.id) || hasPath(byId, right.id, left.id)) continue;\r\n const leftPackageRank = left.workPackageId ? packageRanks.get(left.workPackageId) : undefined;\r\n const rightPackageRank = right.workPackageId ? packageRanks.get(right.workPackageId) : undefined;\r\n if (leftPackageRank !== undefined && rightPackageRank !== undefined && leftPackageRank !== rightPackageRank) {\r\n const [later, earlier] = leftPackageRank > rightPackageRank ? [left, right] : [right, left];\r\n addDependency(byId, later.id, earlier.id);\r\n } else {\r\n addDependency(byId, right.id, left.id);\r\n }\r\n }\r\n }\r\n for (const task of tasks) {\r\n const providers = task.dependsOnTaskIds.map((id) => byId.get(id)).filter((item): item is PlannedTask => Boolean(item));\r\n const businessProviderIds = new Set(task.behaviorIds.flatMap((behaviorId) => behaviorById.get(behaviorId)?.dependsOnBehaviorIds ?? [])\r\n .map((behaviorId) => taskByBehavior.get(behaviorId)).filter((id): id is string => Boolean(id)));\r\n task.writeOwnership.readOnlyFiles = uniqueSorted(providers.flatMap((provider) => provider.writeOwnership.ownedFiles)\r\n .filter((file) => !task.writeOwnership.ownedFiles.includes(file)));\r\n task.dependencyInterfaces = providers.map((provider) => {\r\n const kind = businessProviderIds.has(provider.id) ? \"module\" as const : \"ordering\" as const;\r\n return {\r\n kind,\r\n ref: kind === \"module\" ? `interface:${provider.primaryModule}` : `ordering:${provider.id}`,\r\n providerTaskId: provider.id,\r\n files: provider.writeOwnership.ownedFiles.filter((file) => !task.writeOwnership.ownedFiles.includes(file)),\r\n errorModes: kind === \"module\"\r\n ? [\"provider task is not locally verified\", \"provider Interface changed after this execution plan was generated\"]\r\n : [\"serialized predecessor is not locally verified\", \"write ownership changed after this execution plan was generated\"],\r\n orderingConstraints: [`${provider.id} must be locally verified before ${task.id}`],\r\n };\r\n });\r\n }\r\n return edges.sort((left, right) => `${left.leftTaskId}:${left.rightTaskId}`.localeCompare(`${right.leftTaskId}:${right.rightTaskId}`));\r\n}\r\n\r\nfunction downstreamCounts(tasks: PlannedTask[]): Map<string, number> {\r\n const children = new Map<string, string[]>();\r\n for (const task of tasks) for (const dependency of task.dependsOnTaskIds) children.set(dependency, [...(children.get(dependency) ?? []), task.id]);\r\n const result = new Map<string, number>();\r\n for (const task of tasks) {\r\n const seen = new Set<string>();\r\n const queue = [...(children.get(task.id) ?? [])];\r\n while (queue.length) {\r\n const next = queue.shift()!;\r\n if (seen.has(next)) continue;\r\n seen.add(next);\r\n queue.push(...(children.get(next) ?? []));\r\n }\r\n result.set(task.id, seen.size);\r\n }\r\n return result;\r\n}\r\n\r\nfunction pageWorkPackages(tasks: PlannedTask[], facts: PlanningFactsSnapshot, canonicalBySurface: Record<string, string>): PageWorkPackage[] {\r\n const grouped = new Map<string, PlannedTask[]>();\r\n const taskById = new Map(tasks.map((task) => [task.id, task]));\r\n for (const task of tasks) {\r\n if (task.workPackageId === null) continue;\r\n grouped.set(task.workPackageId, [...(grouped.get(task.workPackageId) ?? []), task]);\r\n }\r\n return [...grouped.entries()].map(([id, items]) => {\r\n const canonicalPageRef = items[0]?.canonicalPageRef ?? null;\r\n const title = facts.surfaces.find((surface) => surface.id === canonicalPageRef)?.name ?? canonicalPageRef ?? \"Unassigned\";\r\n const ordered = orderPackageLane(items);\r\n return {\r\n id,\r\n canonicalPageRef,\r\n title: `${title} Page Work Package`,\r\n surfaceRefs: uniqueSorted(facts.surfaces.filter((surface) => (canonicalBySurface[surface.id] ?? surface.id) === canonicalPageRef).map((surface) => surface.id)),\r\n workItemIds: ordered.map((item) => item.id),\r\n dependsOnPackageIds: uniqueSorted(items.flatMap((item) => item.dependsOnTaskIds)\r\n .map((taskId) => taskById.get(taskId)?.workPackageId)\r\n .filter((packageId): packageId is string => Boolean(packageId && packageId !== id))),\r\n serialLane: true,\r\n exclusiveScopes: uniqueSorted(items.flatMap((item) => item.writeOwnership.exclusiveScopes)),\r\n };\r\n }).sort((left, right) => left.id.localeCompare(right.id));\r\n}\r\n\r\nexport function compileExecutionPlan(behaviorPlan: BehaviorPlan, facts: PlanningFactsSnapshot, context: ExecutionPlanningContext = emptyExecutionPlanningContext): TaskPlan {\r\n // Resolution is a pre-execution planning phase, not an implementation dependency.\r\n // Do not aggregate Coding Work Items until all Resolution Responsibilities disappear.\r\n const planningPhase = behaviorPlan.responsibilities.some((behavior) => behavior.type === \"resolution\")\r\n ? \"resolution\" as const\r\n : \"execution\" as const;\r\n const activeBehaviorPlan: BehaviorPlan = planningPhase === \"resolution\"\r\n ? { ...behaviorPlan, responsibilities: behaviorPlan.responsibilities.filter((behavior) => behavior.type === \"resolution\") }\r\n : behaviorPlan;\r\n const canonicalBySurface = canonicalPageRefs(facts);\r\n const clusters = planningPhase === \"resolution\"\r\n // Resolution Responsibilities are already the final decision granularity.\r\n // Project them 1:1 into transient runtime tasks; never run Coding aggregation.\r\n ? activeBehaviorPlan.responsibilities.map((behavior) => candidateForBehavior(behavior, facts, canonicalBySurface))\r\n : clusterBehaviors(activeBehaviorPlan, facts, context);\r\n const tasks = initialTasks(clusters, activeBehaviorPlan, facts, canonicalBySurface, context);\r\n const fileConflictEdges = wireDependenciesAndConflicts(tasks, activeBehaviorPlan);\r\n const downstream = downstreamCounts(tasks);\r\n for (const task of tasks) task.estimate.downstreamUnlockCount = downstream.get(task.id) ?? 0;\r\n const taskByBehavior = new Map(tasks.flatMap((task) => task.behaviorIds.map((behaviorId) => [behaviorId, task.id] as const)));\r\n const primaryOwnerByFactRef = Object.fromEntries(Object.entries(behaviorPlan.ownership.primaryOwnerByFactRef)\r\n .flatMap(([ref, behaviorId]) => {\r\n const taskId = taskByBehavior.get(behaviorId);\r\n return taskId ? [[ref, taskId] as const] : [];\r\n })\r\n .sort(([left], [right]) => left.localeCompare(right)));\r\n const supportingTaskIdsByFactRef: Record<string, string[]> = {};\r\n for (const task of tasks) for (const ref of task.supportingFactRefs) supportingTaskIdsByFactRef[ref] = uniqueSorted([...(supportingTaskIdsByFactRef[ref] ?? []), task.id]);\r\n return {\r\n taskPlanVersion: TASK_PLAN_VERSION,\r\n executionPlanVersion: EXECUTION_PLAN_VERSION,\r\n planningModelVersion: behaviorPlan.planningModelVersion,\r\n factsAdapterVersion: behaviorPlan.factsAdapterVersion,\r\n plannerPolicyVersion: behaviorPlan.plannerPolicyVersion,\r\n baseline: behaviorPlan.baseline,\r\n planningPhase,\r\n entryResolution: behaviorPlan.entryResolution,\r\n behaviorResponsibilities: behaviorPlan.responsibilities,\r\n pageWorkPackages: pageWorkPackages(tasks, facts, canonicalBySurface),\r\n tasks,\r\n ownership: {\r\n primaryOwnerByFactRef,\r\n supportingTaskIdsByFactRef: Object.fromEntries(Object.entries(supportingTaskIdsByFactRef).sort(([left], [right]) => left.localeCompare(right))),\r\n },\r\n behaviorOwnership: behaviorPlan.ownership,\r\n fileConflictEdges,\r\n planningWarnings: behaviorPlan.planningWarnings,\r\n };\r\n}\r\n\r\nexport function compileFromPlanningFacts(facts: PlanningFactsSnapshot, androidFingerprint: string | null, context: ExecutionPlanningContext = emptyExecutionPlanningContext): TaskPlan {\r\n return compileExecutionPlan(compileBehaviorPlanFromPlanningFacts(facts, androidFingerprint), facts, context);\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport type {\r\n PageDependencyInterface,\r\n PageWorkPackage,\r\n PageWorkPackageContract,\r\n PlannedTask,\r\n PlanningFactsSnapshot,\r\n TaskPlan,\r\n} from \"./types.ts\";\r\nimport { BEHAVIOR_PLAN_VERSION } from \"./types.ts\";\r\nimport { prettyStableJson, sha256, stableJson, uniqueBy, uniqueSorted } from \"./util.ts\";\r\nimport { migrationDirectory } from \"../migration-paths.ts\";\r\n\r\nexport function taskPlanRoot(projectRoot: string): string {\r\n return path.join(migrationDirectory(projectRoot), \"tasks\");\r\n}\r\n\r\nexport function taskArtifactStem(taskId: string): string {\r\n return taskId.replace(/^task:/, \"\");\r\n}\r\n\r\nexport function workPackageArtifactStem(workPackageId: string): string {\r\n return workPackageId.replace(/^package:/, \"\");\r\n}\r\n\r\nfunction codeRefIndex(value: Record<string, unknown>): Record<string, unknown> {\r\n const allowed = [\"id\", \"file\", \"name\", \"symbol\", \"kind\", \"type\", \"capabilityRef\", \"line\", \"startLine\", \"endLine\"];\r\n return Object.fromEntries(allowed.filter((key) => value[key] !== undefined).map((key) => [key, value[key]]));\r\n}\r\n\r\nexport function taskContractView(task: PlannedTask): PlannedTask {\r\n return { ...task, closure: { ...task.closure, codeRefs: task.closure.codeRefs.map(codeRefIndex) } };\r\n}\r\n\r\nexport function coreFactsForTask(task: PlannedTask, facts: PlanningFactsSnapshot): unknown[] {\r\n return coreFactsForRefs([...task.primaryFactRefs, ...task.supportingFactRefs], task.closure.unresolvedRefs, facts);\r\n}\r\n\r\nfunction coreFactsForRefs(refsInput: string[], unresolvedRefs: string[], facts: PlanningFactsSnapshot): unknown[] {\r\n const refs = new Set(refsInput);\r\n return [\r\n ...facts.surfaces.filter((item) => refs.has(item.id)).map((value) => ({ kind: \"surface\", value })),\r\n ...facts.controls.filter((item) => refs.has(item.id)).map((value) => ({ kind: \"control\", value })),\r\n ...facts.entries.filter((item) => refs.has(item.id)).map((value) => ({\r\n kind: \"entry\",\r\n value: { ...value, trace: { ...value.trace, codeRefs: value.trace.codeRefs.map(codeRefIndex) } },\r\n })),\r\n ...facts.effects.filter((item) => refs.has(item.id)).map((value) => ({ kind: \"effect\", value })),\r\n ...facts.issues.filter((item) => refs.has(item.id) || unresolvedRefs.includes(item.id)).map((value) => ({ kind: \"issue\", value })),\r\n ];\r\n}\r\n\r\nexport function sourceContextForTask(task: PlannedTask): unknown[] {\r\n return uniqueBy([\r\n ...task.closure.sourceEvidence.map((value) => ({ kind: \"source-evidence\", value })),\r\n ...task.closure.codeRefs.map((value) => ({ kind: \"code-ref\", value: codeRefIndex(value) })),\r\n ], stableJson);\r\n}\r\n\r\nfunction tasksForPackage(workPackage: PageWorkPackage, plan: TaskPlan): PlannedTask[] {\r\n const byId = new Map(plan.tasks.map((task) => [task.id, task]));\r\n return workPackage.workItemIds.map((id) => byId.get(id)).filter((task): task is PlannedTask => Boolean(task));\r\n}\r\n\r\nfunction effectOutcome(effectRef: string, facts: PlanningFactsSnapshot): string {\r\n const effect = facts.effects.find((item) => item.id === effectRef);\r\n if (!effect) return effectRef;\r\n const target = effect.targetKind === \"surface\"\r\n ? facts.surfaces.find((surface) => surface.id === effect.targetId)?.name\r\n : effect.targetKind === \"entry\"\r\n ? facts.entries.find((entry) => entry.id === effect.targetId)?.label\r\n : null;\r\n const label = target ?? effect.targetId;\r\n if (effect.kind === \"opens\") return `打开 ${label}`;\r\n if (effect.kind === \"navigates-to\") return `进入 ${label}`;\r\n if (effect.kind === \"launches-for-result\") return `启动 ${label} 并处理返回结果`;\r\n return `处理 ${label}`;\r\n}\r\n\r\nexport function pageWorkPackageContractView(workPackage: PageWorkPackage, plan: TaskPlan, facts: PlanningFactsSnapshot): PageWorkPackageContract {\r\n const tasks = tasksForPackage(workPackage, plan);\r\n const taskByBehavior = new Map(tasks.flatMap((task) => task.behaviorIds.map((behaviorId) => [behaviorId, task] as const)));\r\n const behaviorById = new Map(plan.behaviorResponsibilities.map((behavior) => [behavior.id, behavior]));\r\n const orderedBehaviors = tasks.flatMap((task) => task.behaviorIds.map((id) => behaviorById.get(id))).filter((item): item is NonNullable<typeof item> => Boolean(item));\r\n const ownedFiles = uniqueSorted(tasks.flatMap((task) => task.writeOwnership.ownedFiles));\r\n const packageByTask = new Map(plan.tasks.flatMap((task) => task.workPackageId ? [[task.id, task.workPackageId] as const] : []));\r\n const dependencyGroups = new Map<string, PageDependencyInterface>();\r\n for (const task of tasks) for (const dependency of task.dependencyInterfaces) {\r\n const providerTaskId = dependency.providerTaskId;\r\n const providerPackageId = providerTaskId ? packageByTask.get(providerTaskId) : null;\r\n if (!providerTaskId || !providerPackageId || providerPackageId === workPackage.id) continue;\r\n const key = `${dependency.kind}:${dependency.ref}:${providerPackageId}`;\r\n const current = dependencyGroups.get(key) ?? {\r\n kind: dependency.kind,\r\n ref: dependency.ref,\r\n providerPackageId,\r\n providerWorkItemIds: [],\r\n files: [],\r\n errorModes: [],\r\n orderingConstraints: [],\r\n };\r\n current.providerWorkItemIds = uniqueSorted([...current.providerWorkItemIds, providerTaskId]);\r\n current.files = uniqueSorted([...current.files, ...dependency.files]);\r\n current.errorModes = uniqueSorted([...current.errorModes, ...dependency.errorModes]);\r\n current.orderingConstraints = uniqueSorted([...current.orderingConstraints, ...dependency.orderingConstraints]);\r\n dependencyGroups.set(key, current);\r\n }\r\n const sourceFiles = uniqueSorted(tasks.flatMap((task) => [\r\n ...task.closure.sourceEvidence.map((item) => item.file),\r\n ...task.closure.codeRefs.flatMap((item) => typeof item.file === \"string\" ? [item.file] : []),\r\n ]));\r\n return {\r\n ...workPackage,\r\n behaviorIds: orderedBehaviors.map((behavior) => behavior.id),\r\n workItems: tasks.map((task, index) => ({\r\n ordinal: index + 1,\r\n id: task.id,\r\n type: task.type,\r\n title: task.title,\r\n behaviorIds: task.behaviorIds,\r\n })),\r\n features: orderedBehaviors.map((behavior, index) => ({\r\n ordinal: index + 1,\r\n behaviorId: behavior.id,\r\n workItemId: taskByBehavior.get(behavior.id)!.id,\r\n type: behavior.type,\r\n title: behavior.title,\r\n triggerLabels: uniqueSorted(facts.entries.filter((entry) => behavior.closure.entryRefs.includes(entry.id)).map((entry) => entry.label)),\r\n controlNames: uniqueSorted(facts.controls.filter((control) => behavior.closure.controlRefs.includes(control.id)).map((control) => control.name)),\r\n interactionOutcomes: uniqueSorted(behavior.closure.interactionRefs.map((ref) => effectOutcome(ref, facts))),\r\n entryRefs: behavior.closure.entryRefs,\r\n surfaceRefs: behavior.closure.surfaceRefs,\r\n controlRefs: behavior.closure.controlRefs,\r\n interactionRefs: behavior.closure.interactionRefs,\r\n unresolvedRefs: behavior.closure.unresolvedRefs,\r\n primaryFactRefs: behavior.primaryFactRefs,\r\n supportingFactRefs: behavior.supportingFactRefs,\r\n requiresSourceReview: behavior.closure.requiresSourceReview,\r\n observableOutcome: behavior.acceptance.observableOutcome,\r\n requiredFactRefs: behavior.acceptance.requiredFactRefs,\r\n verificationRequirements: behavior.acceptance.verificationRequirements,\r\n reportRefs: behavior.acceptance.reportRefs,\r\n })),\r\n writeOwnership: {\r\n ownedFiles,\r\n readOnlyFiles: uniqueSorted(tasks.flatMap((task) => task.writeOwnership.readOnlyFiles).filter((file) => !ownedFiles.includes(file))),\r\n exclusiveScopes: workPackage.exclusiveScopes,\r\n forbiddenGlobalFiles: uniqueSorted(tasks.flatMap((task) => task.writeOwnership.forbiddenGlobalFiles).filter((file) => !ownedFiles.includes(file))),\r\n },\r\n dependencyInterfaces: [...dependencyGroups.values()].sort((left, right) => `${left.providerPackageId}:${left.ref}`.localeCompare(`${right.providerPackageId}:${right.ref}`)),\r\n acceptance: {\r\n observableOutcomes: uniqueSorted(orderedBehaviors.map((behavior) => behavior.acceptance.observableOutcome)),\r\n requiredFactRefs: uniqueSorted(orderedBehaviors.flatMap((behavior) => behavior.acceptance.requiredFactRefs)),\r\n verificationRequirements: uniqueSorted(orderedBehaviors.flatMap((behavior) => behavior.acceptance.verificationRequirements)),\r\n reportRefs: uniqueSorted(orderedBehaviors.flatMap((behavior) => behavior.acceptance.reportRefs)),\r\n },\r\n estimate: {\r\n behaviorCount: orderedBehaviors.length,\r\n workItemCount: tasks.length,\r\n factCount: uniqueSorted(tasks.flatMap((task) => [...task.primaryFactRefs, ...task.supportingFactRefs])).length,\r\n sourceFileCount: sourceFiles.length,\r\n traceNodeCount: uniqueBy(tasks.flatMap((task) => task.closure.codeRefs), stableJson).length,\r\n estimatedFactTokens: tasks.reduce((total, task) => total + task.estimate.estimatedFactTokens, 0),\r\n productionFileCount: uniqueSorted(tasks.flatMap((task) => task.writeOwnership.ownedFiles).filter((file) => !/(^|\\/)(test|ohosTest)(\\/|$)|\\.(test|spec)\\./i.test(file))).length,\r\n testFileCount: uniqueSorted(tasks.flatMap((task) => task.writeOwnership.ownedFiles).filter((file) => /(^|\\/)(test|ohosTest)(\\/|$)|\\.(test|spec)\\./i.test(file))).length,\r\n capabilityCount: tasks.reduce((total, task) => total + task.estimate.capabilityCount, 0),\r\n },\r\n };\r\n}\r\n\r\nexport function coreFactsForPageWorkPackage(workPackage: PageWorkPackageContract, facts: PlanningFactsSnapshot): unknown[] {\r\n const tasksRefs = workPackage.features.flatMap((feature) => [...feature.primaryFactRefs, ...feature.supportingFactRefs]);\r\n return coreFactsForRefs(tasksRefs, workPackage.features.flatMap((feature) => feature.unresolvedRefs), facts);\r\n}\r\n\r\nexport function sourceContextForPageWorkPackage(workPackage: PageWorkPackage, plan: TaskPlan): unknown[] {\r\n return uniqueBy(tasksForPackage(workPackage, plan).flatMap(sourceContextForTask), stableJson);\r\n}\r\n\r\nexport function renderResolutionTaskBrief(task: PlannedTask, plan: TaskPlan): string {\r\n if (task.type !== \"resolution\") throw new Error(\"Resolution brief requires a Resolution Task\");\r\n const list = (values: string[]) => values.length ? values.map((value) => `- \\`${value}\\``).join(\"\\n\") : \"- 无\";\r\n const sourceLocations = [...new Set([\r\n ...task.closure.sourceEvidence.map((item) => `${item.file}${item.line ? `:${item.line}${(() => { if (item.endLine && item.endLine !== item.line) return `-${item.endLine}`; return \"\"; })()}` : \"\"}${item.symbol ? ` — ${item.symbol}` : \"\"}`),\r\n ...task.closure.codeRefs.flatMap((item) => typeof item.file === \"string\"\r\n ? [`${item.file}${(() => { if (typeof item.startLine === \"number\") return `:${item.startLine}${(() => { if (typeof item.endLine === \"number\" && item.endLine !== item.startLine) return `-${item.endLine}`; return \"\"; })()}`; return \"\"; })()}${(() => { if (typeof item.name === \"string\") return ` — ${item.name}`; return \"\"; })()}`]\r\n : []),\r\n ])].sort();\r\n const sourcePreview = sourceLocations.slice(0, 20);\r\n const hiddenSourceCount = sourceLocations.length - sourcePreview.length;\r\n const taskKind = \"Resolution Task\";\r\n const identity = [\r\n `- ${taskKind} ID:\\`${task.id}\\``,\r\n `- Execution Plan Hash:\\`${sha256(plan)}\\``,\r\n `- Facts SHA256:\\`${plan.baseline.factsSha256}\\``,\r\n `- Android Fingerprint:${plan.baseline.androidFingerprint ? `\\`${plan.baseline.androidFingerprint}\\`` : \"未提供\"}`,\r\n `- Behavior IDs:${task.behaviorIds.map((id) => `\\`${id}\\``).join(\"、\")}`,\r\n `- Primary Page / Module:\\`${task.canonicalPageRef ?? \"unassigned\"}\\` / \\`${task.primaryModule}\\``,\r\n ].join(\"\\n\");\r\n const ownership = (values: string[], fallback: string) => values.length ? values.map((value) => `- \\`${value}\\``).join(\"\\n\") : `- ${fallback}`;\r\n return `# ${taskKind}:${task.title}\r\n\r\n## 1. 最终目标\r\n\r\n${task.acceptance.observableOutcome}\r\n\r\n## 2. 身份与基线\r\n\r\n${identity}\r\n\r\n## 3. 完成定义\r\n\r\n${task.acceptance.observableOutcomes.map((outcome) => `- ${outcome}`).join(\"\\n\")}\r\n\r\n## 4. 写入所有权\r\n\r\n### 允许修改\r\n\r\n${ownership(task.writeOwnership.ownedFiles, `无;\\`${task.writeOwnership.exclusiveScopes.join(\"、\")}\\` 是裁决互斥范围,不授予 HarmonyOS 文件写入权`)}\r\n\r\n### 只读依赖\r\n\r\n${ownership(task.writeOwnership.readOnlyFiles, \"无\")}\r\n\r\n### 禁止修改\r\n\r\n${ownership(task.writeOwnership.forbiddenGlobalFiles, \"无\")}\r\n\r\n## 5. 前置依赖与 Interface\r\n\r\n${task.dependencyInterfaces.length ? task.dependencyInterfaces.map((item) => `- ${item.kind === \"module\" ? \"Module Interface\" : \"调度顺序\"} \\`${item.ref}\\`,提供者:${item.providerTaskId ? `\\`${item.providerTaskId}\\`` : \"外部稳定 Interface\"};顺序:${item.orderingConstraints.join(\";\") || \"无\"};错误模式:${item.errorModes.join(\";\") || \"无\"}`).join(\"\\n\") : \"- 无\"}\r\n\r\n## 6. 行为与状态机\r\n\r\n- Task 类型:\\`${task.type}\\`\r\n- Work Package:${task.workPackageId ? `\\`${task.workPackageId}\\`` : \"不适用(Resolution Task 不参与 Coding Work Package)\"}\r\n- 入口数:${task.closure.entryRefs.length}\r\n- 页面数:${task.closure.surfaceRefs.length}\r\n- 控件数:${task.closure.controlRefs.length}\r\n- 交互数:${task.closure.interactionRefs.length}\r\n- 待裁决问题数:${task.closure.unresolvedRefs.length}\r\n- 入口:${task.closure.entryRefs.map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n- 页面:${task.closure.surfaceRefs.map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n- 控件:${task.closure.controlRefs.map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n- 交互:${task.closure.interactionRefs.map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n- 需要源码复核:${task.closure.requiresSourceReview ? \"是\" : \"否\"}\r\n\r\n## 7. Android 证据\r\n\r\n${sourcePreview.length ? `${sourcePreview.map((value) => `- ${value}`).join(\"\\n\")}${hiddenSourceCount > 0 ? `\\n- 其余 ${hiddenSourceCount} 个位置见 source-context.json 或 task show 分页` : \"\"}` : \"- 无直接源码位置,请从 coreFacts 和 unresolvedRefs 开始裁决\"}\r\n\r\n## 8. Facts 闭包\r\n\r\n### 待裁决问题\r\n\r\n${list(task.closure.unresolvedRefs)}\r\n\r\n### 主所有权 Facts\r\n\r\n${list(task.primaryFactRefs)}\r\n\r\n### Supporting Facts\r\n\r\n${list(task.supportingFactRefs)}\r\n\r\n## 9. 实现约束\r\n\r\n- 本 Resolution Task 只裁决 Planning Facts;不得修改 HarmonyOS 业务实现。\r\n- 必须把结论写入受管 fact correction 或 unresolved review;Report discovery 不能单独解除规划阻塞。\r\n- 规划输入变化后必须重新生成 Behavior Plan 与 Resolution Plan;只有 Resolution 清零后才组装 Coding Work Item。\r\n- Ready Gate:语义=${task.readyGate.semanticsResolved ? \"通过\" : \"未通过\"},依赖 Interface=${task.readyGate.dependencyInterfacesStable ? \"稳定\" : \"不稳定\"},写入所有权=${task.readyGate.writeOwnershipResolved ? \"已确定\" : \"未确定\"},上下文预算=${task.readyGate.contextWithinBudget ? \"通过\" : \"超限\"},验收=${task.readyGate.acceptanceExecutable ? \"可执行\" : \"不可执行\"}。\r\n\r\n## 10. 非目标\r\n\r\n- 不扩大到当前 Behavior IDs 之外的独立业务结果。\r\n- 不编写 ArkTS/ArkUI,不把源码阅读本身视为裁决完成。\r\n- 不以报告字段、注释、桩代码或仅编译成功替代真实行为实现。\r\n\r\n## 11. 验收命令与场景\r\n\r\n${task.acceptance.verificationRequirements.map((value) => `- ${value}`).join(\"\\n\")}\r\n\r\n验收必须覆盖的 Report refs:${task.acceptance.reportRefs.map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}。\r\n\r\n## 12. 完成回报格式\r\n\r\n- 裁决的 issue refs、读取的 Android 源码/运行证据,以及写入的 correction/review。\r\n- 每个 Behavior ID 对应的裁决结果。\r\n- 重新规划后的 Plan Hash、planningPhase,以及是否仍有 Resolution;清零后记录新生成的冻结 Coding Plan Hash。\r\n- 未解决问题;没有则明确写“无”。\r\n\r\n## 工作量提示\r\n\r\n- Fact 数:${task.estimate.factCount}\r\n- Behavior 数:${task.estimate.behaviorCount}\r\n- 可观察结果数:${task.estimate.observableOutcomeCount}\r\n- 源码文件数:${task.estimate.sourceFileCount}\r\n- 生产代码文件数:${task.estimate.productionFileCount}\r\n- 测试文件数:${task.estimate.testFileCount}\r\n- Capability 数:${task.estimate.capabilityCount}\r\n- 调用链节点数:${task.estimate.traceNodeCount}\r\n- 估算 Facts Token:${task.estimate.estimatedFactTokens}\r\n- 可解锁下游 Task:${task.estimate.downstreamUnlockCount}\r\n`;\r\n}\r\n\r\nexport function renderPageWorkPackageBrief(workPackage: PageWorkPackageContract, plan: TaskPlan, facts: PlanningFactsSnapshot): string {\r\n const quoteList = (values: string[], fallback = \"无\") => values.length ? values.map((value) => `- \\`${value}\\``).join(\"\\n\") : `- ${fallback}`;\r\n const surfaceNames = workPackage.surfaceRefs.map((ref) => `${facts.surfaces.find((surface) => surface.id === ref)?.name ?? ref}(\\`${ref}\\`)`);\r\n const featureSections = workPackage.features.map((feature) => {\r\n const behavior = plan.behaviorResponsibilities.find((item) => item.id === feature.behaviorId)!;\r\n const sources = uniqueSorted([\r\n ...behavior.closure.sourceEvidence.map((item) => `${item.file}${item.line ? `:${item.line}${item.endLine && item.endLine !== item.line ? `-${item.endLine}` : \"\"}` : \"\"}${item.symbol ? ` — ${item.symbol}` : \"\"}`),\r\n ...behavior.closure.codeRefs.flatMap((item) => typeof item.file === \"string\"\r\n ? [`${item.file}${typeof item.startLine === \"number\" ? `:${item.startLine}${typeof item.endLine === \"number\" && item.endLine !== item.startLine ? `-${item.endLine}` : \"\"}` : \"\"}${typeof item.name === \"string\" ? ` — ${item.name}` : \"\"}`]\r\n : []),\r\n ]);\r\n return `### F-${String(feature.ordinal).padStart(3, \"0\")}:${feature.title}\r\n\r\n- Behavior / Work Item:\\`${feature.behaviorId}\\` / \\`${feature.workItemId}\\`\r\n- 触发:${feature.triggerLabels.join(\"、\") || \"由 Android 源码入口确定\"}\r\n- 控件:${feature.controlNames.join(\"、\") || \"无显式控件\"}\r\n- 交互结果:${feature.interactionOutcomes.join(\"、\") || \"必须沿源码调用链确认状态、数据或系统副作用\"}\r\n- 实现结果:${feature.observableOutcome}\r\n- Required Fact refs:${feature.requiredFactRefs.map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n- 源码复核:${feature.requiresSourceReview ? \"必须;Facts 未完整表达可观察结果或分支\" : \"必须读取下列证据并覆盖其中全部实际分支\"}\r\n- Android 证据:\r\n${sources.length ? sources.map((value) => ` - ${value}`).join(\"\\n\") : \" - 无直接位置;不得猜测实现,先从对应 core facts 继续定位\"}\r\n- Report refs:${feature.reportRefs.map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}`;\r\n }).join(\"\\n\\n\");\r\n const tasksById = new Map(plan.tasks.map((task) => [task.id, task]));\r\n const packageTaskIds = new Set(workPackage.workItemIds);\r\n const internalSequence = workPackage.workItems.map((item) => {\r\n const dependencies = (tasksById.get(item.id)?.dependsOnTaskIds ?? []).filter((id) => packageTaskIds.has(id));\r\n return `${item.ordinal}. \\`${item.id}\\` — ${item.title}${dependencies.length ? `;页面内前置:${dependencies.map((id) => `\\`${id}\\``).join(\"、\")}` : \"\"}`;\r\n }).join(\"\\n\");\r\n const dependencyText = workPackage.dependencyInterfaces.length\r\n ? workPackage.dependencyInterfaces.map((item) => `- \\`${item.providerPackageId}\\` 提供 ${item.kind === \"module\" ? \"Module Interface\" : \"调度前置\"} \\`${item.ref}\\`;来源 Work Items:${item.providerWorkItemIds.map((id) => `\\`${id}\\``).join(\"、\")};错误模式:${item.errorModes.join(\";\") || \"无\"}`).join(\"\\n\")\r\n : \"- 无\";\r\n const acceptanceSequences = workPackage.features.map((feature) => `### F-${String(feature.ordinal).padStart(3, \"0\")}\r\n\r\n1. 从真实应用入口到达本 Page Work Package 承载面。\r\n2. 触发“${feature.triggerLabels.join(\" / \") || feature.title}”。\r\n3. 断言:${feature.observableOutcome}\r\n4. 按 Android 证据覆盖成功、取消、失败、空值和系统回调分支中实际存在的场景;不得用桩代码或仅编译成功代替。`).join(\"\\n\\n\");\r\n return `# Page Work Package:${workPackage.title.replace(/ Page Work Package$/, \"\")}\r\n\r\n> 本 Markdown 是 execution 阶段一次模型调用的最终页面实现输入,由冻结的 Execution Plan 和 Canonical Facts 确定性生成。Work Item 与 Behavior 仅作为本包内部顺序、证据和验收责任,不再分别生成可执行 Markdown。\r\n\r\n## 1. 页面执行契约\r\n\r\n- Page Work Package ID:\\`${workPackage.id}\\`\r\n- Execution Plan Hash:\\`${sha256(plan)}\\`\r\n- Facts SHA256:\\`${plan.baseline.factsSha256}\\`\r\n- Android Fingerprint:${plan.baseline.androidFingerprint ? `\\`${plan.baseline.androidFingerprint}\\`` : \"未提供\"}\r\n- Canonical Page:\\`${workPackage.canonicalPageRef ?? \"unassigned\"}\\`\r\n- 承载面:${surfaceNames.join(\"、\") || \"无\"}\r\n- Work Item 数:${workPackage.workItems.length}\r\n- Behavior / 页面功能数:${workPackage.features.length}\r\n\r\n## 2. 页面范围与最终目标\r\n\r\n本包必须在同一个实现 epoch 内完成以下全部页面功能,并保持页面内顺序。承载面内的 Dialog、Sheet 或系统回调属于本包;未出现在功能列表和 Facts 闭包中的独立业务结果不属于本包。\r\n\r\n${workPackage.acceptance.observableOutcomes.map((outcome) => `- ${outcome}`).join(\"\\n\")}\r\n\r\n## 3. 具体实现功能\r\n\r\n${featureSections}\r\n\r\n## 4. 页面状态与 Facts 闭包\r\n\r\n- Entry refs:${uniqueSorted(workPackage.features.flatMap((feature) => feature.entryRefs)).map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n- Surface refs:${uniqueSorted(workPackage.features.flatMap((feature) => feature.surfaceRefs)).map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n- Control refs:${uniqueSorted(workPackage.features.flatMap((feature) => feature.controlRefs)).map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n- Interaction refs:${uniqueSorted(workPackage.features.flatMap((feature) => feature.interactionRefs)).map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n- 待裁决 refs:${uniqueSorted(workPackage.features.flatMap((feature) => feature.unresolvedRefs)).map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}\r\n\r\n实现前必须沿 source-context 索引读取当前页面涉及的 Android 源码与必要调用链;本节的 refs 和摘要不能替代源码阅读。\r\n\r\n## 5. 页面内实施顺序\r\n\r\n${internalSequence}\r\n\r\n页面内 Work Item 顺序是冻结计划的一部分。可以在一次模型调用中连续完成,但不得遗漏、重排或把其中一项单独声明为整个页面完成。\r\n\r\n## 6. 写入所有权\r\n\r\n### 允许修改\r\n\r\n${quoteList(workPackage.writeOwnership.ownedFiles, `尚无已存在文件;仅可在独占范围 ${workPackage.writeOwnership.exclusiveScopes.map((scope) => `\\`${scope}\\``).join(\"、\")} 内创建或认领文件`)}\r\n\r\n### 只读依赖\r\n\r\n${quoteList(workPackage.writeOwnership.readOnlyFiles)}\r\n\r\n### 禁止修改\r\n\r\n${quoteList(workPackage.writeOwnership.forbiddenGlobalFiles)}\r\n\r\n### 独占范围\r\n\r\n${quoteList(workPackage.writeOwnership.exclusiveScopes)}\r\n\r\n## 7. 跨页面依赖与 Interface\r\n\r\n${dependencyText}\r\n\r\n只有全部前置 Page Work Package 已取得新鲜的本地验证证据,当前包才可执行。不得通过修改上游实现绕过 Interface。\r\n\r\n## 8. UI 操作与验收序列\r\n\r\n${acceptanceSequences}\r\n\r\n通用验证要求:\r\n\r\n${workPackage.acceptance.verificationRequirements.map((value) => `- ${value}`).join(\"\\n\")}\r\n\r\n验收必须覆盖的 Report refs:${workPackage.acceptance.reportRefs.map((ref) => `\\`${ref}\\``).join(\"、\") || \"无\"}。\r\n\r\n## 9. 非目标与实现约束\r\n\r\n- 不扩大到本包 Behavior IDs 之外的独立业务结果。\r\n- 不修改只读或禁止文件,不重构上游 Module 的 Implementation。\r\n- 不预先虚构尚无证据的 ArkTS 文件名、状态字段或失败行为。\r\n- 不以报告字段、注释、桩代码或仅编译成功替代真实行为实现。\r\n- 发现 Facts、页面归属或 Android 行为错误时,终止当前 execution epoch 并返回规划阶段,不在实现中改写派生计划。\r\n\r\n## 10. 完成回报格式\r\n\r\n- 修改文件及对应写入所有权。\r\n- F-001 至 F-${String(workPackage.features.length).padStart(3, \"0\")} 每项的实现、测试和 Report refs 结果。\r\n- 构建、单元测试、页面/Journey 测试命令与结果。\r\n- 未解决问题;没有则明确写“无”。\r\n\r\n## 工作量提示\r\n\r\n- Work Item 数:${workPackage.estimate.workItemCount}\r\n- Behavior 数:${workPackage.estimate.behaviorCount}\r\n- Fact 数:${workPackage.estimate.factCount}\r\n- 源码文件数:${workPackage.estimate.sourceFileCount}\r\n- 生产代码文件数:${workPackage.estimate.productionFileCount}\r\n- 测试文件数:${workPackage.estimate.testFileCount}\r\n- Capability 数:${workPackage.estimate.capabilityCount}\r\n- 调用链节点数:${workPackage.estimate.traceNodeCount}\r\n- 估算 Facts Token:${workPackage.estimate.estimatedFactTokens}\r\n`;\r\n}\r\n\r\nfunction writeFile(file: string, content: string): void {\r\n fs.mkdirSync(path.dirname(file), { recursive: true });\r\n fs.writeFileSync(file, content, \"utf8\");\r\n}\r\n\r\nexport function writeTaskPlan(projectRoot: string, plan: TaskPlan, facts: PlanningFactsSnapshot): { taskPlanSha256: string; graph: string; index: string } {\r\n const root = taskPlanRoot(projectRoot);\r\n const parent = path.dirname(root);\r\n fs.mkdirSync(parent, { recursive: true });\r\n const temporary = path.join(parent, `tasks.${process.pid}.${Date.now()}.tmp`);\r\n const backup = path.join(parent, `tasks.${process.pid}.backup`);\r\n fs.mkdirSync(temporary, { recursive: true });\r\n const taskPlanSha256 = sha256(plan);\r\n const graphFile = path.join(temporary, \"execution-graph.json\");\r\n writeFile(graphFile, prettyStableJson(plan));\r\n writeFile(path.join(temporary, \"behavior-plan.json\"), prettyStableJson({\r\n behaviorPlanVersion: BEHAVIOR_PLAN_VERSION,\r\n planningModelVersion: plan.planningModelVersion,\r\n factsAdapterVersion: plan.factsAdapterVersion,\r\n plannerPolicyVersion: plan.plannerPolicyVersion,\r\n baseline: plan.baseline,\r\n entryResolution: plan.entryResolution,\r\n responsibilities: plan.behaviorResponsibilities,\r\n ownership: plan.behaviorOwnership,\r\n planningWarnings: plan.planningWarnings,\r\n }));\r\n const resolutionTargets = plan.tasks.filter((task) => task.type === \"resolution\").map((task) => {\r\n const stem = taskArtifactStem(task.id);\r\n const taskRoot = `resolution-tasks/${stem}`;\r\n const briefFile = `${taskRoot}/brief.md`;\r\n const contractFile = `${taskRoot}/contract.json`;\r\n const coreFactsFile = `${taskRoot}/core-facts.json`;\r\n const sourceContextFile = `${taskRoot}/source-context.json`;\r\n const acceptanceFile = `${taskRoot}/acceptance.json`;\r\n writeFile(path.join(temporary, briefFile), renderResolutionTaskBrief(task, plan));\r\n writeFile(path.join(temporary, contractFile), prettyStableJson({ executionPlanSha256: taskPlanSha256, baseline: plan.baseline, task: taskContractView(task) }));\r\n writeFile(path.join(temporary, coreFactsFile), prettyStableJson(coreFactsForTask(task, facts)));\r\n writeFile(path.join(temporary, sourceContextFile), prettyStableJson(sourceContextForTask(task)));\r\n writeFile(path.join(temporary, acceptanceFile), prettyStableJson(task.acceptance));\r\n return { id: task.id, kind: \"resolution-task\", title: task.title, briefFile, contractFile, coreFactsFile, sourceContextFile, acceptanceFile };\r\n });\r\n const pageWorkPackageTargets = plan.pageWorkPackages.map((workPackage) => {\r\n const stem = workPackageArtifactStem(workPackage.id);\r\n const packageRoot = `page-work-packages/${stem}`;\r\n const briefFile = `page-work-packages/${stem}.md`;\r\n const contractFile = `${packageRoot}/contract.json`;\r\n const coreFactsFile = `${packageRoot}/core-facts.json`;\r\n const sourceContextFile = `${packageRoot}/source-context.json`;\r\n const acceptanceFile = `${packageRoot}/acceptance.json`;\r\n const contract = pageWorkPackageContractView(workPackage, plan, facts);\r\n writeFile(path.join(temporary, briefFile), renderPageWorkPackageBrief(contract, plan, facts));\r\n writeFile(path.join(temporary, contractFile), prettyStableJson({ executionPlanSha256: taskPlanSha256, baseline: plan.baseline, pageWorkPackage: contract }));\r\n writeFile(path.join(temporary, coreFactsFile), prettyStableJson(coreFactsForPageWorkPackage(contract, facts)));\r\n writeFile(path.join(temporary, sourceContextFile), prettyStableJson(sourceContextForPageWorkPackage(workPackage, plan)));\r\n writeFile(path.join(temporary, acceptanceFile), prettyStableJson(contract.acceptance));\r\n return { id: workPackage.id, kind: \"page-work-package\", title: workPackage.title, workItemIds: workPackage.workItemIds, briefFile, contractFile, coreFactsFile, sourceContextFile, acceptanceFile };\r\n });\r\n const targets = plan.planningPhase === \"resolution\" ? resolutionTargets : pageWorkPackageTargets;\r\n const index = {\r\n taskPlanVersion: plan.taskPlanVersion,\r\n taskPlanSha256,\r\n baseline: plan.baseline,\r\n executionPlanVersion: plan.executionPlanVersion,\r\n planningPhase: plan.planningPhase,\r\n graphFile: \"execution-graph.json\",\r\n behaviorPlanFile: \"behavior-plan.json\",\r\n counts: {\r\n total: plan.tasks.length,\r\n resolution: plan.tasks.filter((task) => task.type === \"resolution\").length,\r\n bootstrap: plan.tasks.filter((task) => task.type === \"bootstrap\").length,\r\n journey: plan.tasks.filter((task) => task.type === \"journey\").length,\r\n workPackages: plan.pageWorkPackages.length,\r\n behaviors: plan.behaviorResponsibilities.length,\r\n executionTargets: targets.length,\r\n },\r\n targets,\r\n workItems: plan.planningPhase === \"execution\" ? plan.tasks.map((task) => ({ id: task.id, type: task.type, title: task.title, workPackageId: task.workPackageId, behaviorIds: task.behaviorIds })) : [],\r\n };\r\n writeFile(path.join(temporary, \"index.json\"), prettyStableJson(index));\r\n try {\r\n if (fs.existsSync(backup)) fs.rmSync(backup, { recursive: true, force: true });\r\n if (fs.existsSync(root)) fs.renameSync(root, backup);\r\n fs.renameSync(temporary, root);\r\n if (fs.existsSync(backup)) fs.rmSync(backup, { recursive: true, force: true });\r\n } catch (error) {\r\n if (!fs.existsSync(root) && fs.existsSync(backup)) fs.renameSync(backup, root);\r\n if (fs.existsSync(temporary)) fs.rmSync(temporary, { recursive: true, force: true });\r\n throw error;\r\n }\r\n return {\r\n taskPlanSha256,\r\n graph: path.relative(path.resolve(projectRoot), path.join(root, \"execution-graph.json\")).replaceAll(\"\\\\\", \"/\"),\r\n index: path.relative(path.resolve(projectRoot), path.join(root, \"index.json\")).replaceAll(\"\\\\\", \"/\"),\r\n };\r\n}\r\n\r\nexport function readTaskPlan(projectRoot: string): TaskPlan | null {\r\n const root = taskPlanRoot(projectRoot);\r\n const file = fs.existsSync(path.join(root, \"execution-graph.json\")) ? path.join(root, \"execution-graph.json\") : path.join(root, \"graph.json\");\r\n if (!fs.existsSync(file)) return null;\r\n return JSON.parse(fs.readFileSync(file, \"utf8\")) as TaskPlan;\r\n}\r\n\r\nexport function hasTaskPlan(projectRoot: string): boolean {\r\n return fs.existsSync(path.join(taskPlanRoot(projectRoot), \"execution-graph.json\")) || fs.existsSync(path.join(taskPlanRoot(projectRoot), \"graph.json\"));\r\n}\r\n\r\nexport function readTaskPlanIndex(projectRoot: string): any | null {\r\n const file = path.join(taskPlanRoot(projectRoot), \"index.json\");\r\n if (!fs.existsSync(file)) return null;\r\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\r\n}\r\n","import type { PlanningFactsSnapshot, TaskEnvelopePage, TaskPlan } from \"./types.ts\";\r\nimport { TASK_ENVELOPE_VERSION } from \"./types.ts\";\r\nimport {\r\n coreFactsForPageWorkPackage,\r\n coreFactsForTask,\r\n pageWorkPackageContractView,\r\n renderPageWorkPackageBrief,\r\n renderResolutionTaskBrief,\r\n sourceContextForPageWorkPackage,\r\n sourceContextForTask,\r\n taskContractView,\r\n} from \"./storage.ts\";\r\nimport { sha256 } from \"./util.ts\";\r\n\r\nfunction cursorFor(targetId: string, taskPlanSha256: string, offset: number): string {\r\n return Buffer.from(JSON.stringify({ targetId, taskPlanSha256, offset }), \"utf8\").toString(\"base64url\");\r\n}\r\n\r\nfunction cursorOffset(cursor: string | undefined, targetId: string, taskPlanSha256: string): number {\r\n if (!cursor) return 0;\r\n try {\r\n const value = JSON.parse(Buffer.from(cursor, \"base64url\").toString(\"utf8\"));\r\n if (value.targetId !== targetId || value.taskPlanSha256 !== taskPlanSha256 || !Number.isInteger(value.offset) || value.offset < 0) throw new Error(\"mismatch\");\r\n return value.offset;\r\n } catch {\r\n throw new Error(\"Invalid or stale task envelope cursor\");\r\n }\r\n}\r\n\r\nexport function materializeEnvelope(plan: TaskPlan, facts: PlanningFactsSnapshot, targetId: string, options: { cursor?: string; maxSourceContext?: number } = {}): TaskEnvelopePage {\r\n const taskPlanSha256 = sha256(plan);\r\n const limit = Math.max(1, Math.min(200, Math.floor(options.maxSourceContext ?? 25)));\r\n const offset = cursorOffset(options.cursor, targetId, taskPlanSha256);\r\n const task = plan.tasks.find((item) => item.id === targetId);\r\n if (task) {\r\n if (plan.planningPhase !== \"resolution\" || task.type !== \"resolution\") throw new Error(\"Execution phase materializes a Page Work Package, not an internal Coding Work Item\");\r\n const coreFacts = coreFactsForTask(task, facts);\r\n const envelopeTask = taskContractView(task);\r\n const sourceContext = sourceContextForTask(task);\r\n if (offset > sourceContext.length) throw new Error(\"Task envelope cursor is past the available source context\");\r\n const page = sourceContext.slice(offset, offset + limit);\r\n const nextOffset = offset + page.length;\r\n return {\r\n taskEnvelopeVersion: TASK_ENVELOPE_VERSION,\r\n taskPlanSha256,\r\n targetKind: \"resolution-task\",\r\n targetId,\r\n task: envelopeTask,\r\n pageWorkPackage: null,\r\n contract: { executionPlanSha256: taskPlanSha256, baseline: plan.baseline, task: envelopeTask },\r\n brief: renderResolutionTaskBrief(task, plan),\r\n coreFacts,\r\n dependencyInterfaces: task.dependencyInterfaces,\r\n acceptance: task.acceptance,\r\n sourceContext: page,\r\n continuation: {\r\n cursor: nextOffset < sourceContext.length ? cursorFor(targetId, taskPlanSha256, nextOffset) : null,\r\n remainingSourceContext: Math.max(0, sourceContext.length - nextOffset),\r\n },\r\n };\r\n }\r\n const workPackage = plan.pageWorkPackages.find((item) => item.id === targetId);\r\n if (!workPackage) throw new Error(`Execution target not found: ${targetId}`);\r\n if (plan.planningPhase !== \"execution\") throw new Error(\"Resolution phase materializes a Resolution Task, not a Page Work Package\");\r\n const contract = pageWorkPackageContractView(workPackage, plan, facts);\r\n const coreFacts = coreFactsForPageWorkPackage(contract, facts);\r\n const sourceContext = sourceContextForPageWorkPackage(workPackage, plan);\r\n if (offset > sourceContext.length) throw new Error(\"Task envelope cursor is past the available source context\");\r\n const page = sourceContext.slice(offset, offset + limit);\r\n const nextOffset = offset + page.length;\r\n return {\r\n taskEnvelopeVersion: TASK_ENVELOPE_VERSION,\r\n taskPlanSha256,\r\n targetKind: \"page-work-package\",\r\n targetId,\r\n task: null,\r\n pageWorkPackage: contract,\r\n contract: { executionPlanSha256: taskPlanSha256, baseline: plan.baseline, pageWorkPackage: contract },\r\n brief: renderPageWorkPackageBrief(contract, plan, facts),\r\n coreFacts,\r\n dependencyInterfaces: contract.dependencyInterfaces,\r\n acceptance: contract.acceptance,\r\n sourceContext: page,\r\n continuation: {\r\n cursor: nextOffset < sourceContext.length ? cursorFor(targetId, taskPlanSha256, nextOffset) : null,\r\n remainingSourceContext: Math.max(0, sourceContext.length - nextOffset),\r\n },\r\n };\r\n}\r\n","import fs from \"node:fs\";\r\nimport path from \"node:path\";\r\nimport { migrationDirectory, migrationWorkspaceRoot } from \"../migration-paths.ts\";\r\nimport type {\r\n ExecutionTargetRuntimeItem,\r\n PageWorkPackage,\r\n PlannedTask,\r\n PlanningFactsSnapshot,\r\n PlanningRuntimeSource,\r\n TaskPlan,\r\n TaskPlanSnapshot,\r\n TaskRuntimeItem,\r\n TaskRuntimeState,\r\n} from \"./types.ts\";\r\nimport { readTaskPlan } from \"./storage.ts\";\r\nimport { validateTaskPlan } from \"./validate.ts\";\r\nimport { uniqueSorted } from \"./util.ts\";\r\n\r\ninterface ReportItem {\r\n ref: string;\r\n status: string;\r\n testEvidence: string[];\r\n}\r\n\r\nfunction readJson(file: string): any | null {\r\n try { return JSON.parse(fs.readFileSync(file, \"utf8\")); }\r\n catch { return null; }\r\n}\r\n\r\nfunction reportItems(projectRoot: string): Map<string, ReportItem> {\r\n const root = path.join(migrationDirectory(projectRoot), \"report\");\r\n const index = readJson(path.join(root, \"index.json\"));\r\n const out = new Map<string, ReportItem>();\r\n if (!index) return out;\r\n const files = [\r\n ...(index.pages ?? []).map((item: any) => item.file),\r\n index.unassignedEntriesFile,\r\n index.interactionsFile,\r\n index.discoveriesFile,\r\n ].filter((value): value is string => typeof value === \"string\");\r\n for (const relative of files) {\r\n const document = readJson(path.join(root, relative));\r\n if (!document) continue;\r\n const values = [document.page, ...(document.controls ?? []), ...(document.entries ?? []), ...(document.interactions ?? []), ...(document.items ?? [])].filter(Boolean);\r\n for (const item of values) if (typeof item.ref === \"string\") out.set(item.ref, { ref: item.ref, status: item.status ?? \"pending\", testEvidence: Array.isArray(item.testEvidence) ? item.testEvidence : [] });\r\n }\r\n return out;\r\n}\r\n\r\nfunction managedReceipt(projectRoot: string, reference: string): any | null {\r\n const managedRoot = path.resolve(migrationDirectory(projectRoot), \"evidence\", \"managed\");\r\n const absolute = reference.replaceAll(\"\\\\\", \"/\").startsWith(\".migration/\")\r\n ? path.resolve(migrationWorkspaceRoot(projectRoot), reference)\r\n : path.resolve(projectRoot, reference);\r\n if (absolute !== managedRoot && !absolute.startsWith(`${managedRoot}${path.sep}`)) return null;\r\n return readJson(absolute);\r\n}\r\n\r\nfunction freshTaskEvidence(projectRoot: string, reference: string, factsSha256: string, harmonyFingerprint: string | null | undefined): boolean {\r\n const receipt = managedReceipt(projectRoot, reference);\r\n return Boolean(receipt?.producer === \"droid2hmos\"\r\n && receipt?.kind === \"harmony-test\"\r\n && receipt?.status === \"passed\"\r\n && receipt?.source?.factsSha256 === factsSha256\r\n && harmonyFingerprint\r\n && receipt?.source?.harmonyFingerprint === harmonyFingerprint);\r\n}\r\n\r\nfunction initialState(task: PlannedTask, reports: Map<string, ReportItem>, projectRoot: string, plan: TaskPlan, source: PlanningRuntimeSource): TaskRuntimeState {\r\n if (task.type === \"resolution\") return \"pending\";\r\n const items = task.acceptance.reportRefs.map((ref) => reports.get(ref)).filter((item): item is ReportItem => Boolean(item));\r\n if (items.some((item) => item.status === \"blocked\")) return \"blocked\";\r\n if (items.length > 0 && items.length === task.acceptance.reportRefs.length && items.every((item) => item.status === \"verified\")) {\r\n const fresh = items.every((item) => item.testEvidence.some((reference) => freshTaskEvidence(projectRoot, reference, plan.baseline.factsSha256, source.harmonyFingerprint)));\r\n if (!fresh) return \"stale\";\r\n return source.fullRegressionFresh ? \"globally-verified\" : \"locally-verified\";\r\n }\r\n if (items.length > 0 && items.length === task.acceptance.reportRefs.length && items.every((item) => [\"implemented\", \"verified\"].includes(item.status))) return \"implemented\";\r\n return \"pending\";\r\n}\r\n\r\nfunction stateReasons(task: PlannedTask, state: TaskRuntimeState, dependencyStates: TaskRuntimeState[]): string[] {\r\n if (state === \"ready\") return uniqueSorted([\r\n task.type === \"resolution\" ? \"规划阻塞项需要源码或运行行为裁决\" : (() => { if (task.type === \"bootstrap\") return \"真实启动入口优先\"; return \"依赖已满足,可实现当前行为闭包\"; })(),\r\n task.estimate.downstreamUnlockCount > 0 ? `完成后可解除 ${task.estimate.downstreamUnlockCount} 个下游任务` : null,\r\n ]);\r\n if (state === \"blocked\") {\r\n const gate = task.readyGate ?? {\r\n semanticsResolved: false,\r\n dependencyInterfacesStable: false,\r\n writeOwnershipResolved: false,\r\n contextWithinBudget: false,\r\n acceptanceExecutable: false,\r\n };\r\n return uniqueSorted([\r\n dependencyStates.length ? \"依赖任务尚未取得新鲜的定向验证证据\" : null,\r\n !gate.semanticsResolved ? \"仍有未裁决语义问题\" : null,\r\n !gate.dependencyInterfacesStable ? \"上游 Module Interface 尚未稳定\" : null,\r\n !gate.writeOwnershipResolved ? \"写入文件或独占范围尚未分配\" : null,\r\n !gate.contextWithinBudget ? \"内部 Work Item 闭包超出当前执行预算\" : null,\r\n !gate.acceptanceExecutable ? \"验收条件当前不可执行\" : null,\r\n !dependencyStates.length && Object.values(gate).every(Boolean) ? \"任务对应的报告项或计划校验仍处于阻塞状态\" : null,\r\n ]);\r\n }\r\n if (state === \"implemented\") return [\"实现映射已存在,但定向设备验证尚未完成\"];\r\n if (state === \"stale\") return [\"报告声明的测试证据与当前 Facts 或 HarmonyOS 源码不一致\"];\r\n if (state === \"locally-verified\") return [\"当前任务已有新鲜定向设备证据\"];\r\n if (state === \"globally-verified\") return [\"当前任务及全量回归证据均新鲜\"];\r\n return [];\r\n}\r\n\r\nfunction rankReady(tasks: PlannedTask[], states: Map<string, TaskRuntimeState>): PlannedTask[] {\r\n const priority = (task: PlannedTask): number => {\r\n if (task.type === \"resolution\") return 0;\r\n const order: Record<string, number> = { bootstrap: 1, journey: 2, capability: 3, assembly: 4, regression: 6 };\r\n return order[task.type] ?? 6;\r\n };\r\n return tasks.filter((task) => states.get(task.id) === \"ready\")\r\n .sort((a, b) => priority(a) - priority(b)\r\n || b.estimate.downstreamUnlockCount - a.estimate.downstreamUnlockCount\r\n || a.estimate.estimatedFactTokens - b.estimate.estimatedFactTokens\r\n || a.id.localeCompare(b.id));\r\n}\r\n\r\nfunction completedState(state: TaskRuntimeState): boolean {\r\n return [\"locally-verified\", \"globally-verified\"].includes(state);\r\n}\r\n\r\nfunction aggregatePackageOwnState(states: TaskRuntimeState[]): TaskRuntimeState {\r\n if (states.length > 0 && states.every((state) => state === \"globally-verified\")) return \"globally-verified\";\r\n if (states.length > 0 && states.every(completedState)) return \"locally-verified\";\r\n if (states.some((state) => state === \"blocked\")) return \"blocked\";\r\n if (states.some((state) => state === \"stale\")) return \"stale\";\r\n if (states.length > 0 && states.every((state) => [\"implemented\", \"locally-verified\", \"globally-verified\"].includes(state))) return \"implemented\";\r\n return \"pending\";\r\n}\r\n\r\nfunction packageStateReasons(workPackage: PageWorkPackage, state: TaskRuntimeState, dependencyStates: TaskRuntimeState[], ownStates: TaskRuntimeState[]): string[] {\r\n if (state === \"ready\") return [\r\n `页面包将在一次实现 epoch 内按冻结顺序完成 ${workPackage.workItemIds.length} 个 Work Item`,\r\n \"跨页面依赖已满足,可加载页面级模型输入\",\r\n ];\r\n if (state === \"blocked\") return uniqueSorted([\r\n dependencyStates.some((dependency) => !completedState(dependency)) ? \"前置 Page Work Package 尚未取得新鲜的定向验证证据\" : null,\r\n ownStates.some((own) => own === \"blocked\") ? \"页面包内存在被报告标记为 blocked 的行为\" : null,\r\n !dependencyStates.length && !ownStates.some((own) => own === \"blocked\") ? \"页面包的静态 Ready Gate 未全部通过\" : null,\r\n ]);\r\n if (state === \"implemented\") return [\"页面包内全部行为已有实现映射,但仍缺少完整的定向设备验证\"];\r\n if (state === \"stale\") return [\"页面包内至少一项验证证据与当前 Facts 或 HarmonyOS 源码不一致\"];\r\n if (state === \"locally-verified\") return [\"页面包内全部行为均有新鲜定向设备证据\"];\r\n if (state === \"globally-verified\") return [\"页面包内全部行为及全量回归证据均新鲜\"];\r\n return [];\r\n}\r\n\r\nfunction packageDownstreamCounts(packages: PageWorkPackage[]): Map<string, number> {\r\n const children = new Map<string, string[]>();\r\n for (const workPackage of packages) for (const dependency of workPackage.dependsOnPackageIds) children.set(dependency, [...(children.get(dependency) ?? []), workPackage.id]);\r\n const result = new Map<string, number>();\r\n for (const workPackage of packages) {\r\n const seen = new Set<string>();\r\n const queue = [...(children.get(workPackage.id) ?? [])];\r\n while (queue.length) {\r\n const next = queue.shift()!;\r\n if (seen.has(next)) continue;\r\n seen.add(next);\r\n queue.push(...(children.get(next) ?? []));\r\n }\r\n result.set(workPackage.id, seen.size);\r\n }\r\n return result;\r\n}\r\n\r\nexport function emptyTaskPlanSnapshot(error?: string): TaskPlanSnapshot {\r\n return {\r\n present: false,\r\n valid: false,\r\n fresh: false,\r\n taskPlanSha256: null,\r\n planningPhase: null,\r\n totalTasks: 0,\r\n resolutionTasks: 0,\r\n totalTargets: 0,\r\n readyTargets: 0,\r\n completedTargets: 0,\r\n readyTasks: 0,\r\n blockedTasks: 0,\r\n completedTasks: 0,\r\n recommendedTargetId: null,\r\n recommendedTaskId: null,\r\n alternatives: [],\r\n reasons: {},\r\n ownershipCoverage: 0,\r\n closureCoverage: 0,\r\n orphanFactRefs: [],\r\n errors: error ? [error] : [],\r\n warnings: [],\r\n tasks: [],\r\n targets: [],\r\n };\r\n}\r\n\r\nexport function inspectCompiledTaskPlan(projectRootArgument: string, facts: PlanningFactsSnapshot, source: PlanningRuntimeSource): TaskPlanSnapshot {\r\n const projectRoot = path.resolve(projectRootArgument);\r\n const plan = readTaskPlan(projectRoot);\r\n if (!plan) return emptyTaskPlanSnapshot();\r\n const validation = validateTaskPlan(plan, facts, source.androidFingerprint);\r\n const reports = reportItems(projectRoot);\r\n const ownStates = new Map(plan.tasks.map((task) => [task.id, initialState(task, reports, projectRoot, plan, source)]));\r\n const states = new Map<string, TaskRuntimeState>();\r\n const resolving = new Set<string>();\r\n const byId = new Map(plan.tasks.map((task) => [task.id, task]));\r\n const resolveState = (task: PlannedTask): TaskRuntimeState => {\r\n if (states.has(task.id)) return states.get(task.id)!;\r\n if (!validation.valid) return \"blocked\";\r\n if (!validation.fresh) return \"stale\";\r\n if (resolving.has(task.id)) return \"blocked\";\r\n resolving.add(task.id);\r\n const own = ownStates.get(task.id)!;\r\n let state = own;\r\n if (own === \"pending\") {\r\n const dependencyStates = task.dependsOnTaskIds.map((id) => byId.get(id)).filter((item): item is PlannedTask => Boolean(item)).map(resolveState);\r\n const satisfied = dependencyStates.every((value) => [\"locally-verified\", \"globally-verified\"].includes(value));\r\n const readyGatePassed = Object.values(task.readyGate).every(Boolean);\r\n state = satisfied && readyGatePassed ? \"ready\" : \"blocked\";\r\n }\r\n resolving.delete(task.id);\r\n states.set(task.id, state);\r\n return state;\r\n };\r\n for (const task of plan.tasks) resolveState(task);\r\n const ready = rankReady(plan.tasks, states);\r\n const runtimeItems: TaskRuntimeItem[] = plan.tasks.map((task) => {\r\n const state = states.get(task.id)!;\r\n const dependencyStates = task.dependsOnTaskIds.map((id) => states.get(id)!).filter(Boolean);\r\n return { taskId: task.id, state, reasons: stateReasons(task, state, dependencyStates) };\r\n });\r\n let targets: ExecutionTargetRuntimeItem[];\r\n let orderedReadyTargetIds: string[];\r\n if (plan.planningPhase === \"resolution\") {\r\n targets = runtimeItems.map((item) => ({ targetId: item.taskId, kind: \"resolution-task\", state: item.state, reasons: item.reasons, workItemIds: [item.taskId] }));\r\n orderedReadyTargetIds = ready.map((task) => task.id);\r\n } else {\r\n const packageById = new Map(plan.pageWorkPackages.map((workPackage) => [workPackage.id, workPackage]));\r\n const packageStates = new Map<string, TaskRuntimeState>();\r\n const packageResolving = new Set<string>();\r\n const resolvePackageState = (workPackage: PageWorkPackage): TaskRuntimeState => {\r\n if (packageStates.has(workPackage.id)) return packageStates.get(workPackage.id)!;\r\n if (!validation.valid) return \"blocked\";\r\n if (!validation.fresh) return \"stale\";\r\n if (packageResolving.has(workPackage.id)) return \"blocked\";\r\n packageResolving.add(workPackage.id);\r\n const memberTasks = workPackage.workItemIds.map((id) => byId.get(id)).filter((task): task is PlannedTask => Boolean(task));\r\n const memberOwnStates = memberTasks.map((task) => ownStates.get(task.id)!);\r\n const own = aggregatePackageOwnState(memberOwnStates);\r\n let state = own;\r\n if (own === \"pending\") {\r\n const dependencyStates = workPackage.dependsOnPackageIds.map((id) => packageById.get(id)).filter((item): item is PageWorkPackage => Boolean(item)).map(resolvePackageState);\r\n const dependenciesSatisfied = dependencyStates.every(completedState);\r\n const readyGatePassed = memberTasks.every((task) => Object.values(task.readyGate).every(Boolean));\r\n state = dependenciesSatisfied && readyGatePassed ? \"ready\" : \"blocked\";\r\n }\r\n packageResolving.delete(workPackage.id);\r\n packageStates.set(workPackage.id, state);\r\n return state;\r\n };\r\n for (const workPackage of plan.pageWorkPackages) resolvePackageState(workPackage);\r\n targets = plan.pageWorkPackages.map((workPackage) => {\r\n const state = packageStates.get(workPackage.id)!;\r\n const dependencyStates = workPackage.dependsOnPackageIds.map((id) => packageStates.get(id)!).filter(Boolean);\r\n const memberOwnStates = workPackage.workItemIds.map((id) => ownStates.get(id)!).filter(Boolean);\r\n return { targetId: workPackage.id, kind: \"page-work-package\", state, reasons: packageStateReasons(workPackage, state, dependencyStates, memberOwnStates), workItemIds: workPackage.workItemIds };\r\n });\r\n const downstream = packageDownstreamCounts(plan.pageWorkPackages);\r\n const targetById = new Map(targets.map((target) => [target.targetId, target]));\r\n orderedReadyTargetIds = plan.pageWorkPackages.filter((workPackage) => targetById.get(workPackage.id)?.state === \"ready\")\r\n .sort((left, right) => {\r\n const leftTasks = left.workItemIds.map((id) => byId.get(id)).filter((task): task is PlannedTask => Boolean(task));\r\n const rightTasks = right.workItemIds.map((id) => byId.get(id)).filter((task): task is PlannedTask => Boolean(task));\r\n const leftBootstrap = leftTasks.some((task) => task.type === \"bootstrap\") ? 0 : 1;\r\n const rightBootstrap = rightTasks.some((task) => task.type === \"bootstrap\") ? 0 : 1;\r\n const leftTokens = leftTasks.reduce((total, task) => total + task.estimate.estimatedFactTokens, 0);\r\n const rightTokens = rightTasks.reduce((total, task) => total + task.estimate.estimatedFactTokens, 0);\r\n return leftBootstrap - rightBootstrap\r\n || (downstream.get(right.id) ?? 0) - (downstream.get(left.id) ?? 0)\r\n || leftTokens - rightTokens\r\n || left.id.localeCompare(right.id);\r\n }).map((workPackage) => workPackage.id);\r\n }\r\n const reasons = Object.fromEntries([\r\n ...runtimeItems.filter((item) => item.reasons.length).map((item) => [item.taskId, item.reasons] as const),\r\n ...targets.filter((item) => item.reasons.length).map((item) => [item.targetId, item.reasons] as const),\r\n ]);\r\n const ownerCount = facts.requiredFactRefs.filter((ref) => plan.behaviorOwnership.primaryOwnerByFactRef[ref]).length;\r\n const behaviorTasks = plan.tasks.filter((task) => task.type !== \"resolution\");\r\n const closedTasks = behaviorTasks.filter((task) => !task.closure.requiresSourceReview\r\n && (task.closure.interactionRefs.length > 0 || (task.type === \"bootstrap\" && task.closure.surfaceRefs.length > 0))).length;\r\n return {\r\n present: true,\r\n valid: validation.valid,\r\n fresh: validation.fresh,\r\n taskPlanSha256: validation.taskPlanSha256,\r\n planningPhase: plan.planningPhase,\r\n totalTasks: plan.tasks.length,\r\n resolutionTasks: plan.tasks.filter((task) => task.type === \"resolution\").length,\r\n totalTargets: targets.length,\r\n readyTargets: orderedReadyTargetIds.length,\r\n completedTargets: targets.filter((item) => completedState(item.state)).length,\r\n readyTasks: ready.length,\r\n blockedTasks: runtimeItems.filter((item) => [\"blocked\", \"stale\"].includes(item.state)).length,\r\n completedTasks: runtimeItems.filter((item) => completedState(item.state)).length,\r\n recommendedTargetId: orderedReadyTargetIds[0] ?? null,\r\n recommendedTaskId: plan.planningPhase === \"resolution\" ? orderedReadyTargetIds[0] ?? null : null,\r\n alternatives: orderedReadyTargetIds.slice(1, 4),\r\n reasons,\r\n ownershipCoverage: facts.requiredFactRefs.length ? ownerCount / facts.requiredFactRefs.length : 1,\r\n closureCoverage: plan.planningPhase === \"resolution\" ? 0 : behaviorTasks.length ? closedTasks / behaviorTasks.length : 1,\r\n orphanFactRefs: validation.orphanFactRefs,\r\n errors: validation.errors,\r\n warnings: validation.warnings,\r\n tasks: runtimeItems,\r\n targets,\r\n };\r\n}\r\n","import type { FileConflictEdge, PlanningFactsSnapshot, TaskPlan, TaskPlanValidation } from \"./types.ts\";\r\nimport {\r\n DEFAULT_EXECUTION_BUDGET,\r\n EXECUTION_PLAN_VERSION,\r\n FACTS_ADAPTER_VERSION,\r\n PLANNER_POLICY_VERSION,\r\n PLANNING_MODEL_VERSION,\r\n TASK_PLAN_VERSION,\r\n} from \"./types.ts\";\r\nimport { canonicalPageRefs } from \"./execution-planner.ts\";\r\nimport { sha256, uniqueSorted } from \"./util.ts\";\r\n\r\nfunction findDependencyCycle(dependencies: Map<string, string[]>): string[] | null {\r\n const visiting = new Set<string>();\r\n const visited = new Set<string>();\r\n const stack: string[] = [];\r\n const visit = (id: string): string[] | null => {\r\n if (visiting.has(id)) return [...stack.slice(stack.indexOf(id)), id];\r\n if (visited.has(id)) return null;\r\n visiting.add(id); stack.push(id);\r\n for (const dependency of dependencies.get(id) ?? []) {\r\n const cycle = visit(dependency);\r\n if (cycle) return cycle;\r\n }\r\n stack.pop(); visiting.delete(id); visited.add(id);\r\n return null;\r\n };\r\n for (const id of dependencies.keys()) {\r\n const cycle = visit(id);\r\n if (cycle) return cycle;\r\n }\r\n return null;\r\n}\r\n\r\nfunction findCycle(plan: TaskPlan): string[] | null {\r\n return findDependencyCycle(new Map(plan.tasks.map((task) => [task.id, task.dependsOnTaskIds])));\r\n}\r\n\r\nfunction hasDependencyPath(plan: TaskPlan, from: string, to: string): boolean {\r\n const byId = new Map(plan.tasks.map((task) => [task.id, task]));\r\n const queue = [...(byId.get(from)?.dependsOnTaskIds ?? [])];\r\n const seen = new Set<string>();\r\n while (queue.length) {\r\n const next = queue.shift()!;\r\n if (next === to) return true;\r\n if (seen.has(next)) continue;\r\n seen.add(next);\r\n queue.push(...(byId.get(next)?.dependsOnTaskIds ?? []));\r\n }\r\n return false;\r\n}\r\n\r\nexport function validateTaskPlan(plan: TaskPlan, facts: PlanningFactsSnapshot, androidFingerprint: string | null): TaskPlanValidation {\r\n const errors: string[] = [];\r\n const warnings: string[] = [];\r\n if (plan.taskPlanVersion !== TASK_PLAN_VERSION) errors.push(`taskPlanVersion must be ${TASK_PLAN_VERSION}`);\r\n if (plan.executionPlanVersion !== EXECUTION_PLAN_VERSION) errors.push(`executionPlanVersion must be ${EXECUTION_PLAN_VERSION}`);\r\n if (plan.planningModelVersion !== PLANNING_MODEL_VERSION) errors.push(`planningModelVersion must be ${PLANNING_MODEL_VERSION}`);\r\n if (plan.factsAdapterVersion !== FACTS_ADAPTER_VERSION) errors.push(`factsAdapterVersion must be ${FACTS_ADAPTER_VERSION}`);\r\n if (plan.plannerPolicyVersion !== PLANNER_POLICY_VERSION) errors.push(`plannerPolicyVersion must be ${PLANNER_POLICY_VERSION}`);\r\n const fresh = plan.baseline?.factsSha256 === facts.baseline.factsSha256\r\n && plan.baseline?.planningInputSha256 === facts.baseline.planningInputSha256\r\n && plan.baseline?.factsWireVersion === facts.baseline.wireVersion\r\n && plan.baseline?.androidFingerprint === androidFingerprint;\r\n if (!fresh) warnings.push(\"Task plan baseline does not match current Facts, planning inputs, or Android source fingerprint\");\r\n const behaviorIds = new Set<string>();\r\n for (const behavior of plan.behaviorResponsibilities ?? []) {\r\n if (!/^behavior:[a-f0-9]{16}$/.test(behavior.id)) errors.push(`invalid behavior id ${behavior.id}`);\r\n if (behaviorIds.has(behavior.id)) errors.push(`duplicate behavior id ${behavior.id}`); else behaviorIds.add(behavior.id);\r\n if (!behavior.primaryFactRefs?.length) errors.push(`${behavior.id}: primaryFactRefs must not be empty`);\r\n if (!behavior.acceptance?.observableOutcome?.trim()) errors.push(`${behavior.id}: observableOutcome is required`);\r\n for (const ref of behavior.supportingFactRefs ?? []) if (behavior.primaryFactRefs.includes(ref)) errors.push(`${behavior.id}: ${ref} cannot be both primary and supporting`);\r\n }\r\n for (const behavior of plan.behaviorResponsibilities ?? []) for (const dependency of behavior.dependsOnBehaviorIds ?? []) {\r\n if (!behaviorIds.has(dependency)) errors.push(`${behavior.id}: unknown behavior dependency ${dependency}`);\r\n if (dependency === behavior.id) errors.push(`${behavior.id}: behavior cannot depend on itself`);\r\n }\r\n const expectedPlanningPhase = (plan.behaviorResponsibilities ?? []).some((behavior) => behavior.type === \"resolution\") ? \"resolution\" : \"execution\";\r\n if (plan.planningPhase !== expectedPlanningPhase) errors.push(`planningPhase must be ${expectedPlanningPhase}`);\r\n const activeBehaviors = (plan.behaviorResponsibilities ?? []).filter((behavior) => expectedPlanningPhase === \"execution\" || behavior.type === \"resolution\");\r\n const activeBehaviorIds = new Set(activeBehaviors.map((behavior) => behavior.id));\r\n if (expectedPlanningPhase === \"resolution\" && (plan.tasks ?? []).some((task) => task.type !== \"resolution\")) {\r\n errors.push(\"resolution phase must materialize only Resolution Tasks; Coding Work Items are assembled after Resolution is cleared\");\r\n }\r\n if (expectedPlanningPhase === \"execution\" && (plan.tasks ?? []).some((task) => task.type === \"resolution\")) {\r\n errors.push(\"execution phase must not contain Resolution Tasks\");\r\n }\r\n if (expectedPlanningPhase === \"resolution\" && (plan.pageWorkPackages ?? []).length > 0) {\r\n errors.push(\"resolution phase must not materialize Coding Work Packages\");\r\n }\r\n const behaviorOwners = new Map<string, string[]>();\r\n const behaviorSupporters = new Map<string, string[]>();\r\n for (const behavior of plan.behaviorResponsibilities ?? []) for (const ref of behavior.primaryFactRefs ?? []) behaviorOwners.set(ref, [...(behaviorOwners.get(ref) ?? []), behavior.id]);\r\n for (const behavior of plan.behaviorResponsibilities ?? []) for (const ref of behavior.supportingFactRefs ?? []) behaviorSupporters.set(ref, [...(behaviorSupporters.get(ref) ?? []), behavior.id]);\r\n const taskIds = new Set<string>();\r\n for (const task of plan.tasks ?? []) {\r\n if (!/^task:[a-f0-9]{16}$/.test(task.id)) errors.push(`invalid task id ${task.id}`);\r\n if (taskIds.has(task.id)) errors.push(`duplicate task id ${task.id}`); else taskIds.add(task.id);\r\n if (!task.title?.trim()) errors.push(`${task.id}: title is required`);\r\n if (expectedPlanningPhase === \"resolution\" && task.workPackageId !== null) errors.push(`${task.id}: Resolution Task must not belong to a Work Package`);\r\n if (expectedPlanningPhase === \"execution\" && !task.workPackageId?.trim()) errors.push(`${task.id}: Coding Work Item requires workPackageId`);\r\n if (!task.primaryModule?.trim()) errors.push(`${task.id}: primaryModule is required`);\r\n if (!task.behaviorIds?.length) errors.push(`${task.id}: behaviorIds must not be empty`);\r\n if (expectedPlanningPhase === \"resolution\" && task.behaviorIds?.length !== 1) errors.push(`${task.id}: Resolution Task must project exactly one Resolution Behavior`);\r\n for (const behaviorId of task.behaviorIds ?? []) if (!behaviorIds.has(behaviorId)) errors.push(`${task.id}: unknown behavior ${behaviorId}`);\r\n if (!task.primaryFactRefs?.length) errors.push(`${task.id}: primaryFactRefs must not be empty`);\r\n if (!task.acceptance?.observableOutcome?.trim()) errors.push(`${task.id}: observableOutcome is required`);\r\n if (!task.acceptance?.verificationRequirements?.length) errors.push(`${task.id}: verificationRequirements must not be empty`);\r\n const overBudget = task.estimate.behaviorCount > DEFAULT_EXECUTION_BUDGET.maxBehaviorCount\r\n || task.estimate.observableOutcomeCount > DEFAULT_EXECUTION_BUDGET.maxObservableOutcomeCount\r\n || task.estimate.productionFileCount > DEFAULT_EXECUTION_BUDGET.maxProductionFileCount\r\n || task.estimate.testFileCount > DEFAULT_EXECUTION_BUDGET.maxTestFileCount\r\n || task.estimate.capabilityCount > DEFAULT_EXECUTION_BUDGET.maxCapabilityCount\r\n || task.estimate.factCount > DEFAULT_EXECUTION_BUDGET.maxFactCount\r\n || task.estimate.sourceFileCount > DEFAULT_EXECUTION_BUDGET.maxSourceFileCount\r\n || task.estimate.traceNodeCount > DEFAULT_EXECUTION_BUDGET.maxTraceNodeCount\r\n || task.estimate.estimatedFactTokens > DEFAULT_EXECUTION_BUDGET.maxEstimatedFactTokens;\r\n if (overBudget && (task.behaviorIds?.length ?? 0) > 1) errors.push(`${task.id}: merged Coding Work Item exceeds the execution budget`);\r\n else if (overBudget) warnings.push(`${task.id}: single-Behavior ${task.type === \"resolution\" ? \"Resolution Task\" : \"Coding Work Item\"} exceeds a soft execution budget; responsibility is preserved and source context must be paged`);\r\n const owned = task.writeOwnership?.ownedFiles ?? [];\r\n const readOnly = task.writeOwnership?.readOnlyFiles ?? [];\r\n const forbidden = task.writeOwnership?.forbiddenGlobalFiles ?? [];\r\n for (const file of owned) if (readOnly.includes(file)) errors.push(`${task.id}: ${file} cannot be both owned and read-only`);\r\n for (const file of owned) if (forbidden.includes(file)) errors.push(`${task.id}: ${file} cannot be both owned and forbidden`);\r\n if (!(task.writeOwnership?.exclusiveScopes?.length || owned.length)) errors.push(`${task.id}: write ownership requires ownedFiles or an exclusive scope`);\r\n if (task.readyGate?.writeOwnershipResolved !== Boolean(task.writeOwnership?.exclusiveScopes?.length || owned.length)) errors.push(`${task.id}: writeOwnershipResolved gate disagrees with the contract`);\r\n if (task.readyGate?.semanticsResolved !== (task.type === \"resolution\" || task.closure.unresolvedRefs.length === 0)) errors.push(`${task.id}: semanticsResolved gate disagrees with unresolved refs`);\r\n if (task.readyGate?.contextWithinBudget !== (!overBudget || (task.behaviorIds?.length ?? 0) === 1)) errors.push(`${task.id}: contextWithinBudget gate disagrees with execution estimate`);\r\n }\r\n for (const task of plan.tasks ?? []) for (const dependency of task.dependsOnTaskIds ?? []) {\r\n if (!taskIds.has(dependency)) errors.push(`${task.id}: unknown dependency ${dependency}`);\r\n if (dependency === task.id) errors.push(`${task.id}: task cannot depend on itself`);\r\n }\r\n for (const task of plan.tasks ?? []) {\r\n const interfaceProviders = (task.dependencyInterfaces ?? []).map((item) => item.providerTaskId).filter((id): id is string => Boolean(id)).sort();\r\n if (JSON.stringify(interfaceProviders) !== JSON.stringify([...(task.dependsOnTaskIds ?? [])].sort())) errors.push(`${task.id}: dependencyInterfaces do not match dependsOnTaskIds`);\r\n for (const dependencyInterface of task.dependencyInterfaces ?? []) {\r\n if (dependencyInterface.providerTaskId && !taskIds.has(dependencyInterface.providerTaskId)) errors.push(`${task.id}: dependency Interface references unknown provider ${dependencyInterface.providerTaskId}`);\r\n }\r\n }\r\n const cycle = findCycle(plan);\r\n if (cycle) errors.push(`task dependency cycle: ${cycle.join(\" -> \")}`);\r\n const owners = new Map<string, string[]>();\r\n const supporters = new Map<string, string[]>();\r\n for (const task of plan.tasks ?? []) {\r\n for (const ref of task.primaryFactRefs ?? []) owners.set(ref, [...(owners.get(ref) ?? []), task.id]);\r\n for (const ref of task.supportingFactRefs ?? []) {\r\n if ((task.primaryFactRefs ?? []).includes(ref)) errors.push(`${task.id}: ${ref} cannot be both primary and supporting`);\r\n supporters.set(ref, [...(supporters.get(ref) ?? []), task.id]);\r\n }\r\n }\r\n const activePrimaryFactRefs = uniqueSorted(activeBehaviors.flatMap((behavior) => behavior.primaryFactRefs));\r\n const behaviorOrphanFactRefs = facts.requiredFactRefs.filter((ref) => (behaviorOwners.get(ref) ?? []).length === 0);\r\n const activeTaskOrphanFactRefs = activePrimaryFactRefs.filter((ref) => (owners.get(ref) ?? []).length === 0);\r\n const orphanFactRefs = uniqueSorted([\r\n ...behaviorOrphanFactRefs,\r\n ...activeTaskOrphanFactRefs.filter((ref) => facts.requiredFactRefs.includes(ref)),\r\n ]);\r\n for (const ref of activeTaskOrphanFactRefs) errors.push(`active Behavior fact has no primary Task owner: ${ref}`);\r\n for (const [ref, ownerIds] of owners) if (ownerIds.length > 1) errors.push(`fact has multiple primary owners: ${ref} -> ${ownerIds.join(\", \")}`);\r\n for (const [ref, ownerId] of Object.entries(plan.ownership?.primaryOwnerByFactRef ?? {})) {\r\n if (!taskIds.has(ownerId)) errors.push(`ownership ${ref} references unknown task ${ownerId}`);\r\n if (!(owners.get(ref) ?? []).includes(ownerId)) errors.push(`ownership map disagrees with task primaryFactRefs for ${ref}`);\r\n }\r\n for (const ref of activePrimaryFactRefs) if (plan.ownership?.primaryOwnerByFactRef?.[ref] !== owners.get(ref)?.[0]) errors.push(`active Task ownership map is missing or incorrect for ${ref}`);\r\n for (const [ref, taskIdsForRef] of Object.entries(plan.ownership?.supportingTaskIdsByFactRef ?? {})) {\r\n const expected = [...(supporters.get(ref) ?? [])].sort();\r\n const actual = [...(taskIdsForRef ?? [])].sort();\r\n if (JSON.stringify(actual) !== JSON.stringify(expected)) errors.push(`supporting ownership map disagrees with tasks for ${ref}`);\r\n }\r\n for (const [ref, expectedIds] of supporters) {\r\n if (!(ref in (plan.ownership?.supportingTaskIdsByFactRef ?? {}))) errors.push(`supporting ownership map is missing for ${ref}: ${[...expectedIds].sort().join(\", \")}`);\r\n }\r\n const behaviorMembership = new Map<string, string[]>();\r\n for (const task of plan.tasks ?? []) for (const behaviorId of task.behaviorIds ?? []) behaviorMembership.set(behaviorId, [...(behaviorMembership.get(behaviorId) ?? []), task.id]);\r\n for (const behavior of plan.behaviorResponsibilities ?? []) {\r\n const ownersForBehavior = behaviorMembership.get(behavior.id) ?? [];\r\n const expectedMembership = activeBehaviorIds.has(behavior.id) ? 1 : 0;\r\n if (ownersForBehavior.length !== expectedMembership) errors.push(`${behavior.id}: must belong to ${expectedMembership} ${expectedPlanningPhase === \"resolution\" ? \"Resolution Task\" : \"Coding Work Item\"}, found ${ownersForBehavior.length}`);\r\n const task = plan.tasks.find((item) => item.id === ownersForBehavior[0]);\r\n if (!task) continue;\r\n for (const ref of behavior.primaryFactRefs) if (!task.primaryFactRefs.includes(ref)) errors.push(`${task.id}: missing primary fact ${ref} from ${behavior.id}`);\r\n for (const ref of behavior.closure.entryRefs) if (!task.closure.entryRefs.includes(ref)) errors.push(`${task.id}: missing entry ${ref} from ${behavior.id}`);\r\n for (const ref of behavior.closure.interactionRefs) if (!task.closure.interactionRefs.includes(ref)) errors.push(`${task.id}: missing interaction ${ref} from ${behavior.id}`);\r\n }\r\n const behaviorById = new Map((plan.behaviorResponsibilities ?? []).map((behavior) => [behavior.id, behavior]));\r\n for (const task of plan.tasks ?? []) {\r\n const members = (task.behaviorIds ?? []).map((id) => behaviorById.get(id)).filter((item): item is NonNullable<typeof item> => Boolean(item));\r\n const expectedPrimary = uniqueSorted(members.flatMap((item) => item.primaryFactRefs));\r\n const expectedSupporting = uniqueSorted(members.flatMap((item) => item.supportingFactRefs).filter((ref) => !expectedPrimary.includes(ref)));\r\n if (JSON.stringify(expectedPrimary) !== JSON.stringify([...(task.primaryFactRefs ?? [])].sort())) errors.push(`${task.id}: primaryFactRefs disagree with member Behaviors`);\r\n if (JSON.stringify(expectedSupporting) !== JSON.stringify([...(task.supportingFactRefs ?? [])].sort())) errors.push(`${task.id}: supportingFactRefs disagree with member Behaviors`);\r\n for (const key of [\"entryRefs\", \"surfaceRefs\", \"controlRefs\", \"interactionRefs\", \"unresolvedRefs\", \"warningRefs\"] as const) {\r\n const expected = uniqueSorted(members.flatMap((item) => item.closure[key]));\r\n if (JSON.stringify(expected) !== JSON.stringify([...(task.closure?.[key] ?? [])].sort())) errors.push(`${task.id}: closure.${key} disagrees with member Behaviors`);\r\n }\r\n const expectedOutcomes = uniqueSorted(members.map((item) => item.acceptance.observableOutcome));\r\n const expectedRequired = uniqueSorted(members.flatMap((item) => item.acceptance.requiredFactRefs));\r\n const expectedReports = uniqueSorted(members.flatMap((item) => item.acceptance.reportRefs));\r\n if (JSON.stringify(expectedOutcomes) !== JSON.stringify([...(task.acceptance?.observableOutcomes ?? [])].sort())) errors.push(`${task.id}: observableOutcomes disagree with member Behaviors`);\r\n if (JSON.stringify(expectedRequired) !== JSON.stringify([...(task.acceptance?.requiredFactRefs ?? [])].sort())) errors.push(`${task.id}: requiredFactRefs disagree with member Behaviors`);\r\n if (JSON.stringify(expectedReports) !== JSON.stringify([...(task.acceptance?.reportRefs ?? [])].sort())) errors.push(`${task.id}: reportRefs disagree with member Behaviors`);\r\n if (members.some((member) => member.type !== task.type)) errors.push(`${task.id}: task type disagrees with a member Behavior`);\r\n }\r\n for (const ref of facts.requiredFactRefs) {\r\n const expectedBehavior = behaviorOwners.get(ref)?.[0];\r\n if (!expectedBehavior || behaviorOwners.get(ref)?.length !== 1) errors.push(`required fact must have exactly one Behavior owner: ${ref}`);\r\n if (plan.behaviorOwnership?.primaryOwnerByFactRef?.[ref] !== expectedBehavior) errors.push(`behavior ownership map is missing or incorrect for ${ref}`);\r\n }\r\n for (const [ref, behaviorId] of Object.entries(plan.behaviorOwnership?.primaryOwnerByFactRef ?? {})) {\r\n if (!behaviorIds.has(behaviorId)) errors.push(`behavior ownership ${ref} references unknown Behavior ${behaviorId}`);\r\n if (!(behaviorOwners.get(ref) ?? []).includes(behaviorId)) errors.push(`behavior ownership map disagrees with Behavior primaryFactRefs for ${ref}`);\r\n }\r\n for (const [ref, expectedIds] of behaviorSupporters) {\r\n const actual = [...(plan.behaviorOwnership?.supportingBehaviorIdsByFactRef?.[ref] ?? [])].sort();\r\n if (JSON.stringify(actual) !== JSON.stringify([...expectedIds].sort())) errors.push(`behavior supporting ownership map is missing or incorrect for ${ref}`);\r\n }\r\n for (const [ref, actualIds] of Object.entries(plan.behaviorOwnership?.supportingBehaviorIdsByFactRef ?? {})) {\r\n const expected = [...(behaviorSupporters.get(ref) ?? [])].sort();\r\n if (JSON.stringify([...actualIds].sort()) !== JSON.stringify(expected)) errors.push(`behavior supporting ownership map disagrees with Behaviors for ${ref}`);\r\n }\r\n const packageIds = new Set<string>();\r\n const knownPackageIds = new Set((plan.pageWorkPackages ?? []).map((workPackage) => workPackage.id));\r\n const packageMembership = new Map<string, string[]>();\r\n const canonicalBySurface = canonicalPageRefs(facts);\r\n for (const workPackage of plan.pageWorkPackages ?? []) {\r\n if (!/^package:[a-f0-9]{16}$/.test(workPackage.id)) errors.push(`invalid work package id ${workPackage.id}`);\r\n if (packageIds.has(workPackage.id)) errors.push(`duplicate work package id ${workPackage.id}`); else packageIds.add(workPackage.id);\r\n for (const dependency of workPackage.dependsOnPackageIds ?? []) {\r\n if (!knownPackageIds.has(dependency)) errors.push(`${workPackage.id}: unknown Page Work Package dependency ${dependency}`);\r\n if (dependency === workPackage.id) errors.push(`${workPackage.id}: Page Work Package cannot depend on itself`);\r\n }\r\n for (const taskId of workPackage.workItemIds ?? []) {\r\n if (!taskIds.has(taskId)) errors.push(`${workPackage.id}: unknown Coding Work Item ${taskId}`);\r\n packageMembership.set(taskId, [...(packageMembership.get(taskId) ?? []), workPackage.id]);\r\n }\r\n if ((workPackage.workItemIds ?? []).some((taskId) => plan.tasks.find((task) => task.id === taskId)?.type === \"resolution\")) errors.push(`${workPackage.id}: Resolution Tasks must not enter a Coding Work Package`);\r\n if (workPackage.canonicalPageRef !== null && !facts.surfaces.some((surface) => surface.id === workPackage.canonicalPageRef)) errors.push(`${workPackage.id}: unknown canonical page ${workPackage.canonicalPageRef}`);\r\n for (const surfaceRef of workPackage.surfaceRefs ?? []) {\r\n if (!facts.surfaces.some((surface) => surface.id === surfaceRef)) errors.push(`${workPackage.id}: unknown surface ${surfaceRef}`);\r\n if ((canonicalBySurface[surfaceRef] ?? surfaceRef) !== workPackage.canonicalPageRef) errors.push(`${workPackage.id}: ${surfaceRef} does not belong to canonical page ${workPackage.canonicalPageRef}`);\r\n }\r\n if (workPackage.serialLane) for (let index = 1; index < workPackage.workItemIds.length; index++) {\r\n if (!hasDependencyPath(plan, workPackage.workItemIds[index]!, workPackage.workItemIds[index - 1]!)) errors.push(`${workPackage.id}: serial lane is missing dependency ${workPackage.workItemIds[index]} -> ${workPackage.workItemIds[index - 1]}`);\r\n }\r\n const expectedScopes = [...new Set(plan.tasks.filter((task) => task.workPackageId === workPackage.id).flatMap((task) => task.writeOwnership?.exclusiveScopes ?? []))].sort();\r\n if (JSON.stringify([...(workPackage.exclusiveScopes ?? [])].sort()) !== JSON.stringify(expectedScopes)) errors.push(`${workPackage.id}: exclusiveScopes disagree with member Work Items`);\r\n const expectedDependencies = uniqueSorted((workPackage.workItemIds ?? []).flatMap((taskId) => plan.tasks.find((task) => task.id === taskId)?.dependsOnTaskIds ?? [])\r\n .map((taskId) => plan.tasks.find((task) => task.id === taskId)?.workPackageId)\r\n .filter((packageId): packageId is string => Boolean(packageId && packageId !== workPackage.id)));\r\n if (JSON.stringify([...(workPackage.dependsOnPackageIds ?? [])].sort()) !== JSON.stringify(expectedDependencies)) errors.push(`${workPackage.id}: dependsOnPackageIds disagree with cross-package Work Item dependencies`);\r\n }\r\n const packageCycle = findDependencyCycle(new Map((plan.pageWorkPackages ?? []).map((workPackage) => [workPackage.id, workPackage.dependsOnPackageIds ?? []])));\r\n if (packageCycle) errors.push(`Page Work Package dependency cycle: ${packageCycle.join(\" -> \")}`);\r\n for (const task of plan.tasks ?? []) {\r\n const memberships = packageMembership.get(task.id) ?? [];\r\n if (task.type === \"resolution\") {\r\n if (memberships.length > 0 || task.workPackageId !== null) errors.push(`${task.id}: Resolution Task must not have Work Package membership`);\r\n continue;\r\n }\r\n if (memberships.length !== 1 || memberships[0] !== task.workPackageId) errors.push(`${task.id}: work package membership is missing or inconsistent`);\r\n const workPackage = plan.pageWorkPackages?.find((item) => item.id === task.workPackageId);\r\n if (workPackage && workPackage.canonicalPageRef !== task.canonicalPageRef) errors.push(`${task.id}: canonicalPageRef disagrees with its Work Package`);\r\n }\r\n const conflictEdges = new Map<string, FileConflictEdge>();\r\n for (const edge of plan.fileConflictEdges ?? []) {\r\n if (!taskIds.has(edge.leftTaskId) || !taskIds.has(edge.rightTaskId)) errors.push(`file conflict references an unknown task: ${edge.leftTaskId}, ${edge.rightTaskId}`);\r\n if (edge.leftTaskId === edge.rightTaskId) errors.push(`${edge.leftTaskId}: file conflict cannot reference itself`);\r\n if (!edge.reasons?.length) errors.push(`${edge.leftTaskId}/${edge.rightTaskId}: file conflict requires a reason`);\r\n const key = [edge.leftTaskId, edge.rightTaskId].sort().join(\":\");\r\n if (conflictEdges.has(key)) errors.push(`duplicate file conflict edge: ${key}`); else conflictEdges.set(key, edge);\r\n }\r\n for (let leftIndex = 0; leftIndex < (plan.tasks ?? []).length; leftIndex++) for (let rightIndex = leftIndex + 1; rightIndex < plan.tasks.length; rightIndex++) {\r\n const left = plan.tasks[leftIndex]!;\r\n const right = plan.tasks[rightIndex]!;\r\n const leftOwned = left.writeOwnership?.ownedFiles ?? [];\r\n const rightOwned = right.writeOwnership?.ownedFiles ?? [];\r\n const leftScopes = left.writeOwnership?.exclusiveScopes ?? [];\r\n const rightScopes = right.writeOwnership?.exclusiveScopes ?? [];\r\n const overlappingFiles = leftOwned.filter((file) => rightOwned.includes(file));\r\n const overlappingScopes = leftScopes.filter((scope) => rightScopes.includes(scope));\r\n const hasConflict = overlappingFiles.length > 0 || overlappingScopes.length > 0;\r\n const edge = conflictEdges.get([left.id, right.id].sort().join(\":\"));\r\n if (hasConflict && !edge) errors.push(`${left.id} and ${right.id}: overlapping write ownership requires a conflict edge`);\r\n if (!hasConflict && edge) errors.push(`${left.id} and ${right.id}: file conflict edge has no overlapping write ownership`);\r\n if (edge) {\r\n const expectedReasons = [...overlappingFiles.map((file) => `owned-file:${file}`), ...overlappingScopes.map((scope) => `exclusive-scope:${scope}`)].sort();\r\n if (JSON.stringify([...edge.reasons].sort()) !== JSON.stringify(expectedReasons)) errors.push(`${left.id} and ${right.id}: file conflict reasons disagree with write ownership`);\r\n }\r\n if (hasConflict && !(hasDependencyPath(plan, left.id, right.id) || hasDependencyPath(plan, right.id, left.id))) errors.push(`${left.id} and ${right.id}: file conflict is not serialized`);\r\n if ((left.conflictsWithTaskIds ?? []).includes(right.id) !== hasConflict || (right.conflictsWithTaskIds ?? []).includes(left.id) !== hasConflict) errors.push(`${left.id} and ${right.id}: conflictsWithTaskIds disagrees with write ownership`);\r\n }\r\n const knownRefs = new Set([...facts.requiredFactRefs, ...facts.issues.map((issue) => issue.id)]);\r\n const entryRefs = new Set(facts.entries.map((entry) => entry.id));\r\n const surfaceRefs = new Set(facts.surfaces.map((surface) => surface.id));\r\n const controlRefs = new Set(facts.controls.map((control) => control.id));\r\n for (const task of plan.tasks ?? []) {\r\n for (const ref of [...(task.primaryFactRefs ?? []), ...(task.supportingFactRefs ?? [])]) if (!knownRefs.has(ref)) errors.push(`${task.id}: unknown fact or issue ref ${ref}`);\r\n for (const ref of task.closure?.entryRefs ?? []) if (!entryRefs.has(ref)) errors.push(`${task.id}: closure references unknown entry ${ref}`);\r\n for (const ref of task.closure?.surfaceRefs ?? []) if (!surfaceRefs.has(ref)) errors.push(`${task.id}: closure references unknown surface ${ref}`);\r\n for (const ref of task.closure?.controlRefs ?? []) if (!controlRefs.has(ref)) errors.push(`${task.id}: closure references unknown control ${ref}`);\r\n for (const ref of task.acceptance?.reportRefs ?? []) if (!facts.requiredFactRefs.includes(ref)) errors.push(`${task.id}: report ref is not a required Facts ref: ${ref}`);\r\n for (const effectRef of task.closure?.interactionRefs ?? []) {\r\n const effect = facts.effects.find((item) => item.id === effectRef);\r\n if (!effect) errors.push(`${task.id}: closure references unknown interaction ${effectRef}`);\r\n else {\r\n const hasBlockingResolution = task.type === \"resolution\" && facts.issues.some((issue) => issue.blocking && !issue.resolved\r\n && issue.relatedRefs.includes(effectRef) && task.closure.unresolvedRefs.includes(issue.id));\r\n if (!(task.closure.entryRefs ?? []).includes(effect.sourceEntryId) && !hasBlockingResolution) errors.push(`${task.id}: interaction ${effectRef} source entry is outside closure`);\r\n if (effect.targetKind === \"surface\" && !(task.closure.surfaceRefs ?? []).includes(effect.targetId) && !hasBlockingResolution) errors.push(`${task.id}: interaction ${effectRef} target surface is outside closure`);\r\n if (effect.targetKind === \"entry\" && !(task.closure.entryRefs ?? []).includes(effect.targetId) && !hasBlockingResolution) errors.push(`${task.id}: interaction ${effectRef} target entry is outside closure`);\r\n }\r\n }\r\n }\r\n for (const issue of facts.issues.filter((item) => item.blocking && !item.resolved)) {\r\n const resolvers = plan.tasks.filter((task) => task.type === \"resolution\" && task.closure.unresolvedRefs.includes(issue.id));\r\n if (resolvers.length === 0) errors.push(`blocking issue must have a resolution task: ${issue.id}`);\r\n }\r\n const launcherValid = plan.entryResolution?.launcherSurfaceRefs?.every((ref) => facts.surfaces.some((surface) => surface.id === ref));\r\n if (!launcherValid) errors.push(\"entryResolution contains an unknown launcher surface\");\r\n if (JSON.stringify(plan.entryResolution?.launcherSurfaceRefs ?? []) !== JSON.stringify(facts.app.launcherSurfaceIds)\r\n || JSON.stringify(plan.entryResolution?.launcherEntryRefs ?? []) !== JSON.stringify(facts.app.launcherEntryIds)\r\n || plan.entryResolution?.origin !== facts.app.launcherOrigin) errors.push(\"entryResolution does not match canonical planning Facts\");\r\n if (!plan.entryResolution?.launcherSurfaceRefs?.length && !plan.tasks.some((task) => task.type === \"resolution\" && task.closure.unresolvedRefs.includes(\"issue:launcher-unresolved\"))) errors.push(\"unresolved launcher requires a resolution task\");\r\n return { valid: errors.length === 0, fresh, errors, warnings, orphanFactRefs, taskPlanSha256: sha256(plan) };\r\n}\r\n","import type { PlanningFactsSource } from \"./facts/index.ts\";\r\nimport { v2PlanningFactsSource } from \"./facts/index.ts\";\r\nimport { compileFromPlanningFacts } from \"./execution-planner.ts\";\r\nimport { loadExecutionPlanningContext } from \"./execution-context.ts\";\r\nimport { materializeEnvelope } from \"./materialize.ts\";\r\nimport { emptyTaskPlanSnapshot, inspectCompiledTaskPlan } from \"./runtime.ts\";\r\nimport { hasTaskPlan, readTaskPlan, writeTaskPlan } from \"./storage.ts\";\r\nimport type { PlanningRuntimeSource, TaskEnvelopePage, TaskPlan, TaskPlanSnapshot } from \"./types.ts\";\r\nimport { validateTaskPlan } from \"./validate.ts\";\r\n\r\nexport interface TaskPlanningModule {\r\n compile(projectRoot: string, options: { androidFingerprint: string | null }): TaskPlan;\r\n inspect(projectRoot: string, source: PlanningRuntimeSource): TaskPlanSnapshot;\r\n materialize(projectRoot: string, target: string | \"next\", request: { source: PlanningRuntimeSource; cursor?: string; maxSourceContext?: number }): TaskEnvelopePage;\r\n}\r\n\r\nexport function createTaskPlanningModule(factsSource: PlanningFactsSource = v2PlanningFactsSource): TaskPlanningModule {\r\n return {\r\n compile(projectRoot, options) {\r\n const facts = factsSource.load(projectRoot);\r\n const plan = compileFromPlanningFacts(facts, options.androidFingerprint, loadExecutionPlanningContext(projectRoot));\r\n const validation = validateTaskPlan(plan, facts, options.androidFingerprint);\r\n if (!validation.valid || !validation.fresh) throw new Error(`Task plan compilation failed: ${[...validation.errors, ...validation.warnings].join(\"; \")}`);\r\n writeTaskPlan(projectRoot, plan, facts);\r\n return plan;\r\n },\r\n inspect(projectRoot, source) {\r\n try {\r\n if (!readTaskPlan(projectRoot)) return emptyTaskPlanSnapshot();\r\n const facts = factsSource.load(projectRoot);\r\n return inspectCompiledTaskPlan(projectRoot, facts, source);\r\n } catch (error) {\r\n return { ...emptyTaskPlanSnapshot(error instanceof Error ? error.message : String(error)), present: hasTaskPlan(projectRoot) };\r\n }\r\n },\r\n materialize(projectRoot, target, request) {\r\n const facts = factsSource.load(projectRoot);\r\n const plan = readTaskPlan(projectRoot);\r\n if (!plan) throw new Error(\"Task plan is not present; run droid2hmos task plan first\");\r\n const validation = validateTaskPlan(plan, facts, request.source.androidFingerprint);\r\n if (!validation.valid || !validation.fresh) throw new Error(`Task plan is invalid or stale: ${[...validation.errors, ...validation.warnings].join(\"; \")}`);\r\n let targetId = target;\r\n if (target === \"next\") {\r\n const snapshot = inspectCompiledTaskPlan(projectRoot, facts, request.source);\r\n if (!snapshot.recommendedTargetId) throw new Error(\"No ready execution target is available\");\r\n targetId = snapshot.recommendedTargetId;\r\n }\r\n return materializeEnvelope(plan, facts, targetId, request);\r\n },\r\n };\r\n}\r\n\r\nexport const taskPlanning = createTaskPlanningModule();\r\n\r\nexport { compileBehaviorPlanFromPlanningFacts } from \"./compiler.ts\";\r\nexport { canonicalPageRefs, compileExecutionPlan, compileFromPlanningFacts } from \"./execution-planner.ts\";\r\nexport { adaptFactsV2 } from \"./facts/v2-adapter.ts\";\r\nexport { readFactsBundleV2, PlanningFactsError } from \"./facts/reader.ts\";\r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5F;AACJ,QAAM,WAAW,oBAAI,IAAI,CAAC,QAAQ,MAAM,UAAU,UAAU,YAAY,OAAO,MAAM,CAAC;AACtF,QAAM,oBAAoB,KAAK,CAAC,MAAM,UAAU,CAAC,UAAU,QAAQ,MAAM,EAAE,SAAS,KAAK,CAAC,KAAK,EAAE;AACjG,UAAQ,QAAQ,SAAS,IAAI,KAAK,CAAC,KAAK,MAAM,KAAK,qBAAqB,QAAQ,IAAI,+BAA+B,MAAM,OAAO,MAAM,OAAO,IAAI,eAAe,MAAM,SAAS,MAAM,OAAO,MAAM,OAAO,CAAC,CAAC,EACxM,KAAK,CAAC,aAAa;AAAE,YAAQ,WAAW;AAAA,EAAU,CAAC,EACnD,MAAM,CAAC,UAAU;AAChB,QAAI,CAAC,OAAO,SAAU,SAAQ,MAAM,OAAO,WAAW,OAAO,KAAK,CAAC;AACnE,YAAQ,WAAW,OAAO,YAAY;AAAA,EACxC,CAAC;AACL;","names":["path","existsSync","readFileSync","command","fs","path","path","fs","fs","path","fs","path","fs","path","harmonyRoot","relative","normalized","path","readJson","fs","writeJson","confinedReportFile","relative","createHash","fs","path","createHash","createHash","fs","path","readJson","relative","path","fs","canonical","sha256","createHash","evidence","fs","path","fs","path","path","fs","fs","path","path","fs","relative","empty","fs","path","path","fs","relative","fs","path","fs","path","safeName","fs","path","path","fs","path","fs","path","fs","resolve","resolve","command","existsSync","readFileSync","readdirSync","statSync","path","JSON5","closeSync","existsSync","mkdirSync","openSync","readFileSync","dirname","join","resolve","spawn","spawnSync","command","command","spawnSync","existsSync","join","mkdirSync","openSync","closeSync","spawnSync","fs","path","spawnSync","existsSync","path","command","path","existsSync","spawnSync","harmonyRoot","path","fs","existsSync","JSON5","readFileSync","command","path","listFiles","readdirSync","statSync","existsSync","statSync","path","path","existsSync","statSync","relative","fs","path","os","path","fs","harmonyRoot","os","readFileSync","path","path","readFileSync","fs","path","fs","path","command","path","harmonyRoot","fs","fs","path","fs","path","sourceRoots","path","fs","createHash","spawnSync","spawnSync","inside","relative","path","harmonyRoot","fs","files","createHash","commit","fs","command","fs","fs","path","atomicJson","fs","path","environmentRemediation","git","evidence","spawn","spawnSync","closeSync","existsSync","mkdirSync","openSync","readFileSync","unlinkSync","writeFileSync","path","delay","path","isAlive","readFileSync","spawnSync","command","delay","existsSync","unlinkSync","mkdirSync","openSync","spawn","writeFileSync","closeSync","pid","fs","path","createHash","spawnSync","command","spawnSync","fs","createHash","path","normalized","harmonyRoot","fs","path","readJson","fs","atomicJson","path","harmonyRoot","relative","fs","path","existsSync","readFileSync","readdirSync","path","path","existsSync","readdirSync","readFileSync","existsSync","mkdirSync","renameSync","writeFileSync","path","path","existsSync","relative","command","atomicJson","writeFileSync","renameSync","mkdirSync","fs","path","createHash","randomUUID","execFileSync","fs","path","fs","path","createHash","sha256","readJson","fs","inside","relative","path","sha256","sha256","sha256","fs","path","readJson","fs","inside","relative","path","typeOrder","resolve","canonical","combineCandidates","evidence","sha256","item","taskId","downstreamCounts","fs","path","path","taskId","workPackageId","effectOutcome","sha256","fs","sha256","coreFacts","sourceContext","page","nextOffset","fs","path","taskId","sha256","readJson","fs","path","relative","readJson","fs","stableJson","sha256","createHash","path","hash","relative","execFileSync","managedReceipt","check","randomUUID","command","path","existsSync","readFileSync","project","snapshot","projects","name","result"]}