@thinkingai/ae-cli 6.0.57 → 6.0.60

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 (257) hide show
  1. package/README.md +10 -5
  2. package/README.zh.md +10 -5
  3. package/bin/ai-monitor.js +2 -0
  4. package/dist/ai-monitor-FCXSLHAP.js +32 -0
  5. package/dist/ai-monitor.js +135 -0
  6. package/dist/{auth-YEIJLBFY.js → auth-ATK2SLEV.js} +12 -11
  7. package/dist/{automation-NAR5DDGL.js → automation-FLCPFMN4.js} +5 -5
  8. package/dist/{capability-P7DD4Q73.js → capability-6KTSOI7L.js} +32 -36
  9. package/dist/{chunk-JCWM2TYP.js → chunk-2ETRY2CU.js} +16 -16
  10. package/dist/{chunk-IN7KKL6K.js → chunk-2F64AZYH.js} +1 -1
  11. package/dist/{chunk-JNVVJ273.js → chunk-4PSTYEG5.js} +5 -10
  12. package/dist/{chunk-QEMQKVHW.js → chunk-5E7MTTFN.js} +3 -3
  13. package/dist/{chunk-RJHGDWSC.js → chunk-5M5LBRR3.js} +2 -2
  14. package/dist/chunk-6M7ZEDT2.js +182 -0
  15. package/dist/{chunk-KPQY44JQ.js → chunk-AWW2T2WL.js} +3 -0
  16. package/dist/chunk-AXTO4FTM.js +1285 -0
  17. package/dist/{chunk-TKVVACEJ.js → chunk-BEYLCUZX.js} +17 -12
  18. package/dist/chunk-CF6JTT2U.js +64 -0
  19. package/dist/{chunk-N6XBLRB7.js → chunk-F2VFZUGG.js} +2 -2
  20. package/dist/{chunk-ZGIYG473.js → chunk-HSZAIPUX.js} +48 -13
  21. package/dist/{chunk-H3K5UGYC.js → chunk-HTZ2MLYA.js} +48 -22
  22. package/dist/{chunk-QZUVLFNR.js → chunk-HVMCPKOZ.js} +1 -1
  23. package/dist/{chunk-7JAVT5TK.js → chunk-KTJXD27G.js} +2 -2
  24. package/dist/{chunk-TULINOLS.js → chunk-LOR4IA26.js} +565 -315
  25. package/dist/{chunk-YVG6QD3V.js → chunk-P7QDCWJ6.js} +98 -7
  26. package/dist/{chunk-7ABK2PEJ.js → chunk-SDKW6LYE.js} +88 -36
  27. package/dist/{chunk-752BSLZC.js → chunk-VJUXKVRE.js} +1 -1
  28. package/dist/chunk-VRMGHQKE.js +556 -0
  29. package/dist/{compat-check-PMEGUPZU.js → compat-check-XD2U7PZ2.js} +3 -3
  30. package/dist/{config-VWVPR4WW.js → config-U3GDWU6E.js} +26 -13
  31. package/dist/{context-F6FCGTF3.js → context-YAQG6YQC.js} +3 -3
  32. package/dist/{data-integration-6UAZO4GG.js → data-integration-QE37EQ3A.js} +1 -1
  33. package/dist/{evaluation-4LO2O4AF.js → evaluation-2JSF4V47.js} +13 -158
  34. package/dist/index.js +87 -582
  35. package/dist/{memory-HHPX3NF2.js → memory-WEB27VI6.js} +8 -8
  36. package/dist/{metadata-HEQQEEG3.js → metadata-7FYE4234.js} +8 -8
  37. package/dist/{model-7UHGWYVR.js → model-T7H7Q6BG.js} +3 -3
  38. package/dist/{personal-semantic-preference-V4L6ZWR2.js → personal-semantic-preference-O6VXM74A.js} +7 -7
  39. package/dist/{project-semantic-NKHKJX6M.js → project-semantic-2GGFJWW6.js} +16 -14
  40. package/dist/{sync-ZJMXCRIN.js → sync-ULBB7WO5.js} +5 -5
  41. package/dist/{te-agent-WBKIFEQD.js → te-agent-6RMF7LUV.js} +6 -6
  42. package/dist/{te-analysis-ADX7RKO4.js → te-analysis-HSYC7GNV.js} +383 -194
  43. package/dist/{te-community-PREDRXG3.js → te-community-FLKZGQKB.js} +10 -10
  44. package/dist/{te-dataops-ITWJHO2U.js → te-dataops-OQQGTCUA.js} +5 -5
  45. package/dist/{te-engage-VE2NUH5V.js → te-engage-RIEBHL5T.js} +10 -10
  46. package/dist/{te-kb-WSMOW7WS.js → te-kb-4HG2FMHJ.js} +19 -10
  47. package/dist/{te-system-YM657FKO.js → te-system-AL4B4XZL.js} +3 -3
  48. package/dist/{te-team-T2WRLOOD.js → te-team-5O4UVUWE.js} +6 -6
  49. package/dist/{things-6QOMFXOG.js → things-TSJ64GBT.js} +6 -6
  50. package/dist/{update-I4MOUYOX.js → update-Q5LURAWV.js} +4 -4
  51. package/dist/{workspace-LYDAP647.js → workspace-FF2HXJGR.js} +5 -5
  52. package/package.json +8 -6
  53. package/skills/ae-ai-monitor/SKILL.md +179 -0
  54. package/skills/ae-ai-monitor/references/read-commands.md +866 -0
  55. package/skills/ae-analysis/SKILL.md +10 -4
  56. package/skills/ae-analysis/references/adhoc_export.md +3 -1
  57. package/skills/ae-analysis/references/ai_models.md +1 -0
  58. package/skills/ae-analysis/references/analysis_gateway_assets.md +2 -0
  59. package/skills/ae-analysis/references/asset_search.md +1 -1
  60. package/skills/ae-analysis/references/bad_case_begin.md +12 -0
  61. package/skills/ae-analysis/references/bad_case_get.md +12 -0
  62. package/skills/ae-analysis/references/bad_case_history.md +12 -0
  63. package/skills/ae-analysis/references/bad_case_list.md +12 -0
  64. package/skills/ae-analysis/references/bad_case_review.md +51 -0
  65. package/skills/ae-analysis/references/bad_case_run.md +12 -0
  66. package/skills/ae-analysis/references/bad_case_submit.md +12 -0
  67. package/skills/ae-analysis/references/bad_case_submit_to_page.md +12 -0
  68. package/skills/ae-analysis/references/bad_case_sync_evaluation.md +11 -0
  69. package/skills/ae-analysis/references/bi_panel_list.md +1 -1
  70. package/skills/ae-analysis/references/bi_panel_share.md +3 -1
  71. package/skills/ae-analysis/references/catalog_list.md +2 -0
  72. package/skills/ae-analysis/references/command_index.md +38 -29
  73. package/skills/ae-analysis/references/dashboard_daily_report_update.md +2 -0
  74. package/skills/ae-analysis/references/dashboard_handover.md +3 -1
  75. package/skills/ae-analysis/references/dashboard_list.md +3 -3
  76. package/skills/ae-analysis/references/dashboard_report_data_export.md +1 -1
  77. package/skills/ae-analysis/references/dashboard_share.md +3 -1
  78. package/skills/ae-analysis/references/dashboard_update.md +3 -2
  79. package/skills/ae-analysis/references/filter_value_list.md +2 -0
  80. package/skills/ae-analysis/references/folder_share.md +8 -2
  81. package/skills/ae-analysis/references/governance_recommendation_run_update.md +3 -1
  82. package/skills/ae-analysis/references/project_data_power_upsert.md +3 -1
  83. package/skills/ae-analysis/references/project_mark_time_create.md +2 -0
  84. package/skills/ae-analysis/references/project_mark_time_update.md +2 -0
  85. package/skills/ae-analysis/references/project_member_add.md +3 -1
  86. package/skills/ae-analysis/references/project_member_batch_update.md +3 -1
  87. package/skills/ae-analysis/references/project_member_handover_run.md +3 -1
  88. package/skills/ae-analysis/references/project_member_update.md +3 -1
  89. package/skills/ae-analysis/references/project_owner_update.md +3 -1
  90. package/skills/ae-analysis/references/project_role_upsert.md +5 -3
  91. package/skills/ae-analysis/references/project_semantic_knowledge_wiki.md +16 -1
  92. package/skills/ae-analysis/references/project_semantic_knowledge_wiki_plan_schema.md +14 -1
  93. package/skills/ae-analysis/references/project_space_share.md +8 -2
  94. package/skills/ae-analysis/references/property_get.md +2 -0
  95. package/skills/ae-analysis/references/public_link_list.md +3 -1
  96. package/skills/ae-analysis/references/query_cancel.md +4 -1
  97. package/skills/ae-analysis/references/report_data_run.md +1 -1
  98. package/skills/ae-analysis/references/report_list.md +3 -3
  99. package/skills/ae-analysis/references/scenario_append.md +2 -2
  100. package/skills/ae-analysis/references/scenario_collect.md +15 -4
  101. package/skills/ae-analysis/references/scenario_list.md +2 -1
  102. package/skills/ae-analysis/references/system_oauth2_update.md +3 -1
  103. package/skills/ae-analysis/references/system_third_party_login_upsert.md +4 -2
  104. package/skills/ae-analysis/references/user_tag_create.md +4 -1
  105. package/skills/ae-analysis/references/user_tag_get.md +2 -0
  106. package/skills/ae-analysis/references/user_tag_models.md +8 -2
  107. package/skills/ae-analysis/references/user_tag_update.md +5 -2
  108. package/skills/ae-analysis/references/virtual_property_create.md +12 -1
  109. package/skills/ae-analysis/references/virtual_property_sql_rule_update.md +10 -0
  110. package/skills/ae-analysis/scripts/project-semantic-knowledge-wiki/build-project-semantic-wiki.mjs +55 -13
  111. package/skills/ae-analysis/scripts/project-semantic-knowledge-wiki/company-kb.mjs +2 -2
  112. package/skills/ae-analysis/scripts/project-semantic-knowledge-wiki/default-compile-rules.md +2 -2
  113. package/skills/ae-analysis/scripts/project-semantic-knowledge-wiki/default-compile-schema.md +7 -1
  114. package/skills/ae-analysis/scripts/project-semantic-knowledge-wiki/wait-compile-run.mjs +79 -0
  115. package/skills/ae-automation/SKILL.md +4 -2
  116. package/skills/ae-capability/SKILL.md +9 -5
  117. package/skills/ae-community/SKILL.md +1 -0
  118. package/skills/ae-dataops/SKILL.md +1 -0
  119. package/skills/ae-engage/SKILL.md +1 -0
  120. package/skills/ae-evaluation/SKILL.md +17 -2
  121. package/skills/ae-generate-tracking-plan/SKILL.md +5 -0
  122. package/skills/ae-kb/SKILL.md +9 -5
  123. package/skills/ae-kb/references/analysis-workflow.md +11 -2
  124. package/skills/ae-kb/references/query-workflow.md +9 -6
  125. package/skills/ae-kb/references/versions.md +1 -1
  126. package/skills/ae-kb-discovery/SKILL.md +15 -6
  127. package/skills/ae-metadata/SKILL.md +1 -0
  128. package/skills/ae-migrate-tracking-code/SKILL.md +2 -1
  129. package/skills/ae-team/SKILL.md +1 -1
  130. package/skills/ae-tracking-matrix/SKILL.md +170 -0
  131. package/skills/ae-tracking-matrix/assets//345/237/213/347/202/271/346/250/241/347/211/210.xlsx +0 -0
  132. package/skills/ae-tracking-matrix/i18n.yaml +12 -0
  133. package/skills/ae-tracking-matrix/references/ae-capabilities.md +93 -0
  134. package/skills/ae-tracking-matrix/references/business-semantic-checks.md +30 -0
  135. package/skills/ae-tracking-matrix/references/categories/acquaintance_social_tracking_plan_template.md +256 -0
  136. package/skills/ae-tracking-matrix/references/categories/blockchain_game_tracking_plan_template.md +213 -0
  137. package/skills/ae-tracking-matrix/references/categories/card_game_tracking_plan_template.md +407 -0
  138. package/skills/ae-tracking-matrix/references/categories/casual_game_tracking_plan_template.md +218 -0
  139. package/skills/ae-tracking-matrix/references/categories/casual_music.md +112 -0
  140. package/skills/ae-tracking-matrix/references/categories/chess_cards_tracking_plan_template.md +301 -0
  141. package/skills/ae-tracking-matrix/references/categories/ecommerce_tracking_plan_template.md +356 -0
  142. package/skills/ae-tracking-matrix/references/categories/fishing.md +775 -0
  143. package/skills/ae-tracking-matrix/references/categories/game_basic_module_tracking_plan.md +89 -0
  144. package/skills/ae-tracking-matrix/references/categories/idle_card.md +27 -0
  145. package/skills/ae-tracking-matrix/references/categories/idle_game_tracking_plan_template.md +415 -0
  146. package/skills/ae-tracking-matrix/references/categories/interactive_video.md +133 -0
  147. package/skills/ae-tracking-matrix/references/categories/merge.md +639 -0
  148. package/skills/ae-tracking-matrix/references/categories/mmo_mobile_tracking_plan_template.md +406 -0
  149. package/skills/ae-tracking-matrix/references/categories/mmo_web.md +230 -0
  150. package/skills/ae-tracking-matrix/references/categories/music.md +137 -0
  151. package/skills/ae-tracking-matrix/references/categories/online_education_tracking_plan_template.md +414 -0
  152. package/skills/ae-tracking-matrix/references/categories/qipai_mj.md +199 -0
  153. package/skills/ae-tracking-matrix/references/categories/reading_tracking_plan_template.md +158 -0
  154. package/skills/ae-tracking-matrix/references/categories/roguelike_tracking_plan_template.md +546 -0
  155. package/skills/ae-tracking-matrix/references/categories/rpg.md +195 -0
  156. package/skills/ae-tracking-matrix/references/categories/short_drama_tracking_plan_template.md +115 -0
  157. package/skills/ae-tracking-matrix/references/categories/simulation_business_tracking_plan_template.md +151 -0
  158. package/skills/ae-tracking-matrix/references/categories/slg_tracking_plan_template.md +260 -0
  159. package/skills/ae-tracking-matrix/references/categories/slots_tracking_plan_template.md +232 -0
  160. package/skills/ae-tracking-matrix/references/categories/stranger_social_tracking_plan_template.md +359 -0
  161. package/skills/ae-tracking-matrix/references/categories/tower_defense.md +365 -0
  162. package/skills/ae-tracking-matrix/references/categories/video_editor_tracking_plan_template.md +211 -0
  163. package/skills/ae-tracking-matrix/references/categories/wechat_minigame.md +132 -0
  164. package/skills/ae-tracking-matrix/references/category-registry.md +77 -0
  165. package/skills/ae-tracking-matrix/references/data-verification/diagnosis_kb.md +230 -0
  166. package/skills/ae-tracking-matrix/references/data-verification/sql_checks.md +406 -0
  167. package/skills/ae-tracking-matrix/references/data-verification/tracking_plan_comparison.md +128 -0
  168. package/skills/ae-tracking-matrix/references/eval-cases.md +74 -0
  169. package/skills/ae-tracking-matrix/references/naming-dict.md +238 -0
  170. package/skills/ae-tracking-matrix/references/optimization-checklist.md +85 -0
  171. package/skills/ae-tracking-matrix/references/plan-generation/export-schema.md +142 -0
  172. package/skills/ae-tracking-matrix/references/plan-generation/module-baseline.md +47 -0
  173. package/skills/ae-tracking-matrix/references/plan-generation/reference.md +794 -0
  174. package/skills/ae-tracking-matrix/references/plan-generation/template-catalog.md +94 -0
  175. package/skills/ae-tracking-matrix/references/scene-routing.md +80 -0
  176. package/skills/ae-tracking-matrix/references/sdk/client-sdk/android.md +3787 -0
  177. package/skills/ae-tracking-matrix/references/sdk/client-sdk/c.md +827 -0
  178. package/skills/ae-tracking-matrix/references/sdk/client-sdk/cocos2d-lua.md +655 -0
  179. package/skills/ae-tracking-matrix/references/sdk/client-sdk/cocos2d-x.md +953 -0
  180. package/skills/ae-tracking-matrix/references/sdk/client-sdk/cocoscreator.md +1128 -0
  181. package/skills/ae-tracking-matrix/references/sdk/client-sdk/corona.md +714 -0
  182. package/skills/ae-tracking-matrix/references/sdk/client-sdk/egret.md +1268 -0
  183. package/skills/ae-tracking-matrix/references/sdk/client-sdk/flutter.md +776 -0
  184. package/skills/ae-tracking-matrix/references/sdk/client-sdk/h5-and-app-sdk-integration.md +182 -0
  185. package/skills/ae-tracking-matrix/references/sdk/client-sdk/ios.md +2755 -0
  186. package/skills/ae-tracking-matrix/references/sdk/client-sdk/javascript.md +1182 -0
  187. package/skills/ae-tracking-matrix/references/sdk/client-sdk/layaair.md +1300 -0
  188. package/skills/ae-tracking-matrix/references/sdk/client-sdk/macos.md +1369 -0
  189. package/skills/ae-tracking-matrix/references/sdk/client-sdk/mini-program-mini-game.md +1692 -0
  190. package/skills/ae-tracking-matrix/references/sdk/client-sdk/openharmony.md +902 -0
  191. package/skills/ae-tracking-matrix/references/sdk/client-sdk/react-native.md +763 -0
  192. package/skills/ae-tracking-matrix/references/sdk/client-sdk/uni-app.md +1107 -0
  193. package/skills/ae-tracking-matrix/references/sdk/client-sdk/unity.md +1532 -0
  194. package/skills/ae-tracking-matrix/references/sdk/client-sdk/unreal.md +845 -0
  195. package/skills/ae-tracking-matrix/references/sdk/faq/android_sdk_faq.md +228 -0
  196. package/skills/ae-tracking-matrix/references/sdk/faq/ios_sdk_faq.md +149 -0
  197. package/skills/ae-tracking-matrix/references/sdk/faq/java_sdk_faq.md +407 -0
  198. package/skills/ae-tracking-matrix/references/sdk/faq/javascript_sdk_faq.md +163 -0
  199. package/skills/ae-tracking-matrix/references/sdk/faq/minigame_sdk_faq.md +149 -0
  200. package/skills/ae-tracking-matrix/references/sdk/faq/miniprogram_sdk_faq.md +153 -0
  201. package/skills/ae-tracking-matrix/references/sdk/faq/python_sdk_faq.md +232 -0
  202. package/skills/ae-tracking-matrix/references/sdk/faq/sdk_log_guide.md +314 -0
  203. package/skills/ae-tracking-matrix/references/sdk/faq/sdk_usage_notes.md +117 -0
  204. package/skills/ae-tracking-matrix/references/sdk/faq/unity_sdk_faq.md +148 -0
  205. package/skills/ae-tracking-matrix/references/sdk/integration-tools/filebeat-logstash-guide.md +645 -0
  206. package/skills/ae-tracking-matrix/references/sdk/integration-tools/logbus2_guide.md +307 -0
  207. package/skills/ae-tracking-matrix/references/sdk/integration-tools/logbus2_parser_plugin.md +347 -0
  208. package/skills/ae-tracking-matrix/references/sdk/integration-tools/restful_api_notes.md +72 -0
  209. package/skills/ae-tracking-matrix/references/sdk/integration-tools/ta-datax-writer-guide.md +264 -0
  210. package/skills/ae-tracking-matrix/references/sdk/server-sdk/c.md +566 -0
  211. package/skills/ae-tracking-matrix/references/sdk/server-sdk/erlang.md +409 -0
  212. package/skills/ae-tracking-matrix/references/sdk/server-sdk/golang.md +446 -0
  213. package/skills/ae-tracking-matrix/references/sdk/server-sdk/java.md +557 -0
  214. package/skills/ae-tracking-matrix/references/sdk/server-sdk/lua.md +457 -0
  215. package/skills/ae-tracking-matrix/references/sdk/server-sdk/nodejs.md +490 -0
  216. package/skills/ae-tracking-matrix/references/sdk/server-sdk/php.md +523 -0
  217. package/skills/ae-tracking-matrix/references/sdk/server-sdk/python.md +484 -0
  218. package/skills/ae-tracking-matrix/references/sdk/server-sdk/ruby.md +442 -0
  219. package/skills/ae-tracking-matrix/references/sdk/te-data-rules/data-rules.md +391 -0
  220. package/skills/ae-tracking-matrix/references/sdk/te-data-rules/first-event-validation.md +91 -0
  221. package/skills/ae-tracking-matrix/references/sdk/te-data-rules/preset-properties-system-fields.md +635 -0
  222. package/skills/ae-tracking-matrix/references/sdk/te-data-rules/updatable-events.md +113 -0
  223. package/skills/ae-tracking-matrix/references/sdk/te-data-rules/user-identification-rules.md +466 -0
  224. package/skills/ae-tracking-matrix/references/standard-base/README.md +22 -0
  225. package/skills/ae-tracking-matrix/references/standard-base/basic_event_data.md +174 -0
  226. package/skills/ae-tracking-matrix/references/standard-base/common_event_properties.md +20 -0
  227. package/skills/ae-tracking-matrix/references/standard-base/common_event_properties_setup.md +7 -0
  228. package/skills/ae-tracking-matrix/references/standard-base/data_type_design_principles.md +14 -0
  229. package/skills/ae-tracking-matrix/references/standard-base/gameplay_event_data.md +370 -0
  230. package/skills/ae-tracking-matrix/references/standard-base/id_system_faq.md +47 -0
  231. package/skills/ae-tracking-matrix/references/standard-base/integration_must_know.md +37 -0
  232. package/skills/ae-tracking-matrix/references/standard-base/multi_platform_integration_notes.md +27 -0
  233. package/skills/ae-tracking-matrix/references/standard-base/multi_user_id_system_recommendations.md +23 -0
  234. package/skills/ae-tracking-matrix/references/standard-base/tracking_notes.md +14 -0
  235. package/skills/ae-tracking-matrix/references/standard-base/user_data.md +46 -0
  236. package/skills/ae-tracking-matrix/references/standard-base/user_id_system.md +13 -0
  237. package/skills/ae-tracking-matrix/references/system-fields.md +297 -0
  238. package/skills/ae-tracking-matrix/references/te-field-translations.md +1791 -0
  239. package/skills/ae-tracking-matrix/references/workflows/data-verification.md +232 -0
  240. package/skills/ae-tracking-matrix/references/workflows/feasibility-analysis.md +829 -0
  241. package/skills/ae-tracking-matrix/references/workflows/integration-qna.md +355 -0
  242. package/skills/ae-tracking-matrix/references/workflows/plan-generation.md +283 -0
  243. package/skills/ae-tracking-matrix/references/workflows/plan-lint.md +168 -0
  244. package/skills/ae-tracking-matrix/references/workflows/plan-review-optimize.md +205 -0
  245. package/skills/ae-tracking-matrix/references/workflows/prd-to-suggestions.md +75 -0
  246. package/skills/ae-tracking-matrix/references/workflows/troubleshooting.md +36 -0
  247. package/skills/ae-tracking-matrix/references/workflows/validated-upload.md +107 -0
  248. package/skills/ae-tracking-matrix/scripts/build_template_catalog.py +114 -0
  249. package/skills/ae-tracking-matrix/scripts/export_tracking_plan.py +53 -0
  250. package/skills/ae-tracking-matrix/scripts/finalize_plan.py +166 -0
  251. package/skills/ae-tracking-matrix/scripts/lint_tracking_plan.py +674 -0
  252. package/skills/ae-tracking-matrix/scripts/plan_contract.py +200 -0
  253. package/skills/ae-tracking-matrix/scripts/plan_types.py +60 -0
  254. package/skills/ae-tracking-matrix/scripts/prepare_delivery.py +169 -0
  255. package/skills/ae-tracking-matrix/scripts/sync_plan.py +296 -0
  256. package/skills/ae-tracking-matrix/scripts/upload_plan.py +340 -0
  257. package/dist/chunk-AMBFK2K3.js +0 -28
@@ -0,0 +1,296 @@
1
+ #!/usr/bin/env python3
2
+ """Sync a reviewed plan through tracking.plan.save_items without creating XLSX.
3
+
4
+ Stages: conversation-only delivery -> read-only preflight/dry-run -> semantic
5
+ review and explicit target confirmation -> one structured sync -> readback.
6
+ No delete, replace, hidden workbook, automatic retry or success-only verification.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import subprocess
16
+ import sys
17
+
18
+ from plan_contract import PlanError, counts, ensure_new_path, file_sha256, json_bytes, normalize_plan
19
+ from upload_plan import (UploadError, api, check_target, default_runner, digest,
20
+ import_errors, now, read_json, require_context,
21
+ review_gate, run_help, validate_baseline, write_new_json)
22
+
23
+ TYPE_MAP = {
24
+ "文本": "string", "数值": "number", "布尔": "bool", "时间": "datetime",
25
+ "对象": "object", "对象组": "array_row", "列表": "array_string",
26
+ }
27
+ SYNC_UPDATE_METHODS = {"user_set", "user_setOnce", "user_add"}
28
+
29
+
30
+ def property_payload(record):
31
+ return {
32
+ "name": record["property_name"],
33
+ "display_name": record["display_name"],
34
+ "type": TYPE_MAP[record["property_type"]],
35
+ "desc": record["description"],
36
+ }
37
+
38
+
39
+ def build_payload(source, project_id):
40
+ """Translate canonical JSON losslessly into the inspected snake_case API pools."""
41
+ source = normalize_plan(source)
42
+ events = []
43
+ event_props = {}
44
+ description_variants = {}
45
+ for event in source["events"]:
46
+ item = {
47
+ "event_name": event["event_name"],
48
+ "display_name": event["display_name"],
49
+ "event_desc": event["description"],
50
+ "event_tag": event["tag"],
51
+ "props": [prop["property_name"] for prop in event["properties"]],
52
+ }
53
+ if event["platform"]:
54
+ # The deployment dry-run must accept this value before any write.
55
+ item["data_origin"] = event["platform"]
56
+ events.append(item)
57
+ for prop in event["properties"]:
58
+ converted = property_payload(prop)
59
+ name = prop["property_name"]
60
+ previous = event_props.setdefault(name, converted)
61
+ identity = ("name", "display_name", "type")
62
+ if any(previous[field] != converted[field] for field in identity):
63
+ raise UploadError("Same-name event property identity differs; reconcile definitions before structured sync: " + name)
64
+ description_variants.setdefault(name, []).append((event["event_name"], prop["description"]))
65
+ for name, variants in description_variants.items():
66
+ if len({description for _, description in variants}) > 1:
67
+ # A global property has one description. Preserve event-specific wording
68
+ # explicitly instead of dropping it or treating it as a type conflict.
69
+ event_props[name]["desc"] = "\n".join(f"[{event}] {description}" for event, description in variants)
70
+ user_props = []
71
+ for prop in source["user_properties"]:
72
+ if prop["update_method"] not in SYNC_UPDATE_METHODS:
73
+ raise UploadError("Structured save-items does not support update method " + prop["update_method"] +
74
+ "; keep the plan local, revise the semantics, or choose the Excel import path")
75
+ user_props.append({**property_payload(prop), "update_type": prop["update_method"]})
76
+ payload = {"project_id": project_id}
77
+ for key, values in (
78
+ ("events", events),
79
+ ("event_props", list(event_props.values())),
80
+ ("common_event_props", [property_payload(prop) for prop in source["common_event_properties"]]),
81
+ ("user_props", user_props),
82
+ ):
83
+ if values:
84
+ payload[key] = values
85
+ return payload
86
+
87
+
88
+ def local_gate(delivery):
89
+ root = Path(delivery).resolve()
90
+ validation = read_json(root / "validation.json")
91
+ if (validation.get("schema_version") != 1 or
92
+ validation.get("status") != "review_ready_delivery_choice_pending" or
93
+ validation.get("delivery_choice_pending") is not True or
94
+ validation.get("machine_validation", {}).get("passed") is not None):
95
+ raise UploadError("Structured sync requires a conversation-only delivery awaiting a delivery choice")
96
+ if (root / "plan.xlsx").exists() or (root / "lint.txt").exists():
97
+ raise UploadError("Conversation-only delivery must not contain an Excel workbook or Excel lint log")
98
+ expected = validation.get("fingerprints", {})
99
+ if set(expected) != {"plan.normalized.json", "conversation.md"}:
100
+ raise UploadError("Unexpected structured-delivery artifact fingerprints")
101
+ for name in expected:
102
+ path = root / name
103
+ if path.is_symlink() or not path.is_file() or file_sha256(path) != expected[name]:
104
+ raise UploadError("Delivery changed or fingerprint missing: " + name)
105
+ source = normalize_plan(read_json(root / "plan.normalized.json"))
106
+ if counts(source) != validation.get("counts"):
107
+ raise UploadError("Counts do not match normalized source")
108
+ return root, validation, source
109
+
110
+
111
+ def capability_contract(envelope):
112
+ data = envelope.get("data")
113
+ if not isinstance(data, dict):
114
+ raise UploadError("Unsupported save-items inspection envelope")
115
+ identifier = data.get("capability_id", data.get("id"))
116
+ schema = data.get("input_schema")
117
+ if identifier != "tracking.plan.save_items" or data.get("risk") != "write":
118
+ raise UploadError("Unexpected or destructive save-items capability contract")
119
+ if not isinstance(schema, dict) or schema.get("type") != "object":
120
+ raise UploadError("Unknown save-items input schema")
121
+ properties = schema.get("properties")
122
+ required = {"project_id", "events", "event_props", "common_event_props", "user_props"}
123
+ if not isinstance(properties, dict) or not required.issubset(properties):
124
+ raise UploadError("Save-items schema lacks the documented project/item pools")
125
+ if schema.get("additionalProperties") is not False:
126
+ raise UploadError("Save-items schema changed; inspect new fields before composing input")
127
+ for pool in ("event_props", "common_event_props", "user_props"):
128
+ item_schema = properties[pool].get("items", {})
129
+ if item_schema.get("additionalProperties") is not False:
130
+ raise UploadError("Save-items property schema is open or unknown: " + pool)
131
+ prop_schema = item_schema.get("properties", {})
132
+ if not {"name", "type"}.issubset(item_schema.get("required", [])) or not {"name", "display_name", "type", "desc"}.issubset(prop_schema):
133
+ raise UploadError("Save-items property fields changed: " + pool)
134
+ if set(prop_schema["type"].get("enum", [])) != set(TYPE_MAP.values()):
135
+ raise UploadError("Save-items property types changed: " + pool)
136
+ user_schema = properties["user_props"]["items"].get("properties", {})
137
+ if set(user_schema.get("update_type", {}).get("enum", [])) != SYNC_UPDATE_METHODS:
138
+ raise UploadError("Save-items user update methods changed; review user_append handling")
139
+ return {"capability_id": identifier, "risk": data["risk"], "input_schema": schema}
140
+
141
+
142
+ def discover(cli, runner, target):
143
+ # --host is a global CLI option; subcommand help need not repeat it.
144
+ run_help(cli, [], ["--host"], runner)
145
+ run_help(cli, ["tracking", "plan", "get"], ["--project-id", "--host"], runner)
146
+ run_help(cli, ["capability", "inspect"], ["--project-id"], runner)
147
+ run_help(cli, ["capability", "dry-run"], ["--input"], runner)
148
+ run_help(cli, ["capability", "run"], ["--input"], runner)
149
+ inspected = api(cli, ["capability", "inspect", "tracking.plan.save_items",
150
+ "--project-id", str(target["project_id"]), "--host", target["host"]], runner)
151
+ capability_contract(inspected)
152
+ return inspected
153
+
154
+
155
+ def checked_dry_run(envelope, payload):
156
+ data = envelope.get("data", {})
157
+ if (data.get("dry_run") is not True or
158
+ data.get("capability_id") != "tracking.plan.save_items" or
159
+ data.get("risk") != "write"):
160
+ raise UploadError("Save-items dry-run did not confirm the expected write contract")
161
+ if data.get("normalized_input") != payload:
162
+ raise UploadError("Save-items dry-run normalized the payload unexpectedly; review differences before writing")
163
+ return envelope
164
+
165
+
166
+ def preflight(delivery, project_id, host, output, cli="ae-cli", runner=default_runner, context_cwd=None):
167
+ root, validation, source = local_gate(delivery)
168
+ target = check_target(project_id, host)
169
+ output = ensure_new_path(output, (root / "validation.json", root / "plan.normalized.json", root / "conversation.md"))
170
+ require_context(context_cwd)
171
+ payload = build_payload(source, project_id)
172
+ payload_path = root / "sync-payload.json"
173
+ write_new_json(payload_path, payload)
174
+ schema = discover(cli, runner, target)
175
+ baseline = api(cli, ["tracking", "plan", "get", "--project-id", str(project_id), "--host", target["host"]], runner)
176
+ validate_baseline(baseline, target)
177
+ dry_run = checked_dry_run(api(cli, ["capability", "dry-run", "tracking.plan.save_items",
178
+ "--host", target["host"], "--input", str(payload_path)], runner), payload)
179
+ result = {
180
+ "schema_version": 1, "created_at": now(), "target": target,
181
+ "fingerprints": validation["fingerprints"], "payload_sha256": digest(payload),
182
+ "baseline_sha256": digest(baseline["data"]), "baseline": baseline,
183
+ "sync_capability": schema, "dry_run": dry_run,
184
+ "status": "read_only_preflight_complete",
185
+ "warning": "Dry-run is not persistence evidence. Review baseline conflicts, target and scope before confirmation.",
186
+ }
187
+ write_new_json(output, result)
188
+ return result
189
+
190
+
191
+ def freeze_payload(root, payload):
192
+ snapshot = root / ".sync-snapshot"
193
+ snapshot.mkdir(mode=0o700, exist_ok=False)
194
+ path = snapshot / "payload.json"
195
+ content = json_bytes(payload)
196
+ if digest(payload) != hashlib.sha256(content).hexdigest():
197
+ # digest() hashes the same canonical JSON bytes; this is a defensive invariant.
198
+ raise UploadError("Structured payload canonicalization changed")
199
+ with path.open("xb") as handle:
200
+ handle.write(content)
201
+ handle.flush()
202
+ os.fchmod(handle.fileno(), 0o400)
203
+ return path
204
+
205
+
206
+ def sync(delivery, project_id, host, preflight_path, review_path, confirmed=False,
207
+ cli="ae-cli", runner=default_runner, context_cwd=None):
208
+ if confirmed is not True:
209
+ raise UploadError("Explicit user confirmation of the displayed target and sync scope is required")
210
+ root, validation, source = local_gate(delivery)
211
+ target = check_target(project_id, host)
212
+ prepared = read_json(preflight_path)
213
+ review = read_json(review_path)
214
+ review_gate(review, prepared, validation, target)
215
+ if prepared.get("status") != "read_only_preflight_complete":
216
+ raise UploadError("Read-only structured preflight is incomplete")
217
+ payload = build_payload(source, project_id)
218
+ if digest(payload) != prepared.get("payload_sha256"):
219
+ raise UploadError("Structured payload changed since review; confirmation is stale")
220
+ receipt_path = ensure_new_path(root / "sync-attempt.json")
221
+ require_context(context_cwd)
222
+ inspected = discover(cli, runner, target)
223
+ if capability_contract(inspected) != capability_contract(prepared.get("sync_capability", {})):
224
+ raise UploadError("Save-items capability changed since preflight; review the new scope")
225
+ current = api(cli, ["tracking", "plan", "get", "--project-id", str(project_id), "--host", target["host"]], runner)
226
+ validate_baseline(current, target)
227
+ if digest(current["data"]) != prepared["baseline_sha256"]:
228
+ raise UploadError("Project plan changed since review; inspect the diff and obtain fresh confirmation")
229
+ if source.get("meta", {}).get("blocking_unknowns"):
230
+ raise UploadError("Source still contains blocking unknowns")
231
+ payload_path = freeze_payload(root, payload)
232
+ attempt = {
233
+ "schema_version": 1, "started_at": now(), "target": target,
234
+ "fingerprints": validation["fingerprints"], "payload_sha256": digest(payload),
235
+ "baseline_sha256": prepared["baseline_sha256"],
236
+ "status": "dispatch_started_outcome_unknown", "mode": "structured_save_items",
237
+ "user_confirmation_supplied": True, "snapshot_file": str(payload_path),
238
+ "snapshot_sha256": file_sha256(payload_path), "excel_generated": False,
239
+ }
240
+ write_new_json(receipt_path, attempt)
241
+ try:
242
+ synced = api(cli, ["capability", "run", "tracking.plan.save_items",
243
+ "--host", target["host"], "--input", str(payload_path)], runner)
244
+ readback = api(cli, ["tracking", "plan", "get", "--project-id", str(project_id), "--host", target["host"]], runner)
245
+ errors = import_errors(synced)
246
+ status = "sync_reported_errors_require_review" if errors else "sync_accepted_readback_requires_review"
247
+ result = {
248
+ **attempt, "finished_at": now(), "status": status,
249
+ "sync_response": synced, "sync_errors": errors, "readback": readback,
250
+ "readback_sha256": digest(readback["data"]),
251
+ "management_url": target["host"] + "/#/data/plan",
252
+ "next_step": "Compare event names, collection sides, property types, associations and preserved baseline items; only then report sync verified. Never auto-retry or delete/replace.",
253
+ }
254
+ write_new_json(root / "sync-result.json", result)
255
+ return result
256
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
257
+ write_new_json(root / "sync-error.json", {
258
+ **attempt, "finished_at": now(), "status": "outcome_requires_reconciliation",
259
+ "error": str(exc), "next_step": "Read back the target before any retry; preserve attempt evidence.",
260
+ })
261
+ raise
262
+
263
+
264
+ def main(argv=None):
265
+ parser = argparse.ArgumentParser(description=__doc__)
266
+ parser.add_argument("--delivery", required=True)
267
+ parser.add_argument("--project-id", required=True, type=int)
268
+ parser.add_argument("--host", required=True)
269
+ parser.add_argument("--ae-cli", default="ae-cli")
270
+ parser.add_argument("--preflight", action="store_true")
271
+ parser.add_argument("--output")
272
+ parser.add_argument("--preflight-file")
273
+ parser.add_argument("--review")
274
+ parser.add_argument("--confirm", action="store_true")
275
+ args = parser.parse_args(argv)
276
+ try:
277
+ if args.preflight:
278
+ if not args.output or args.confirm or args.review or args.preflight_file:
279
+ raise UploadError("--preflight requires --output only; never combine it with write confirmation")
280
+ result = preflight(args.delivery, args.project_id, args.host, args.output, args.ae_cli)
281
+ code = 0
282
+ else:
283
+ if not args.preflight_file or not args.review or args.output:
284
+ raise UploadError("Structured sync requires --preflight-file, --review and explicit --confirm")
285
+ result = sync(args.delivery, args.project_id, args.host, args.preflight_file,
286
+ args.review, args.confirm, args.ae_cli)
287
+ code = 3
288
+ print(json.dumps(result, ensure_ascii=False, indent=2))
289
+ return code
290
+ except (OSError, ValueError, KeyError) as exc:
291
+ print("ERROR: " + str(exc), file=sys.stderr)
292
+ return 1
293
+
294
+
295
+ if __name__ == "__main__":
296
+ raise SystemExit(main())
@@ -0,0 +1,340 @@
1
+ #!/usr/bin/env python3
2
+ """Guarded AE upload adapter. No write occurs without --confirm and all gates.
3
+
4
+ Stages: preflight (read-only) -> semantic review and user confirmation -> import
5
+ -> readback evidence. Import success is NOT declared full acceptance: an Agent
6
+ must compare readback fields/associations before reporting 'uploaded and verified'.
7
+ This adapter deliberately has no delete, replace or automatic retry operation.
8
+ """
9
+ from __future__ import annotations
10
+ import argparse
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import re
16
+ import subprocess
17
+ import sys
18
+ from datetime import datetime, timezone
19
+ from urllib.parse import urlsplit
20
+ import openpyxl
21
+
22
+ from plan_contract import (DEFAULT_TEMPLATE, PlanError, file_sha256, json_bytes,
23
+ normalize_plan, counts, ensure_new_path)
24
+ from finalize_plan import verify_round_trip
25
+ from prepare_delivery import REVIEW_CHECKS
26
+
27
+
28
+ class UploadError(PlanError):
29
+ pass
30
+
31
+
32
+ def read_json(path):
33
+ with Path(path).open(encoding='utf-8') as f:
34
+ return json.load(f)
35
+
36
+
37
+ def write_new_json(path, obj):
38
+ path=ensure_new_path(path)
39
+ with path.open('xb') as f:
40
+ f.write(json_bytes(obj))
41
+
42
+
43
+ def digest(value):
44
+ return hashlib.sha256(json_bytes(value)).hexdigest()
45
+
46
+
47
+ def now():
48
+ return datetime.now(timezone.utc).isoformat()
49
+
50
+
51
+ def check_target(project_id, host):
52
+ if isinstance(project_id,bool) or not isinstance(project_id,int) or project_id<=0:
53
+ raise UploadError('project_id must be a positive, verified integer')
54
+ parsed=urlsplit(host)
55
+ if parsed.scheme not in ('https','http') or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('','/'):
56
+ raise UploadError('host must be the verified AE origin, without credentials, query, path or fragment')
57
+ return {'project_id':project_id,'host':host.rstrip('/')}
58
+
59
+
60
+ def local_gate(delivery, template=DEFAULT_TEMPLATE):
61
+ root=Path(delivery).resolve()
62
+ validation=read_json(root/'validation.json')
63
+ if validation.get('schema_version')!=1 or validation.get('status')!='machine_passed_semantic_pending' or validation.get('machine_validation',{}).get('passed') is not True:
64
+ raise UploadError('Delivery has not passed machine validation')
65
+ expected=validation.get('fingerprints',{})
66
+ for name in ('plan.normalized.json','plan.xlsx','conversation.md'):
67
+ path=root/name
68
+ if path.is_symlink() or not path.is_file() or file_sha256(path)!=expected.get(name):
69
+ raise UploadError(f'Delivery changed or fingerprint missing: {name}; regenerate and review again')
70
+ if validation['machine_validation'].get('template_sha256')!=file_sha256(template):
71
+ raise UploadError('Template changed since validation; regenerate')
72
+ source=normalize_plan(read_json(root/'plan.normalized.json'))
73
+ if counts(source)!=validation.get('counts'):
74
+ raise UploadError('Counts do not match normalized source')
75
+ wb=openpyxl.load_workbook(root/'plan.xlsx',data_only=False)
76
+ try:
77
+ verify_round_trip(wb,source)
78
+ finally:
79
+ wb.close()
80
+ result=subprocess.run([sys.executable,str(Path(__file__).with_name('lint_tracking_plan.py')),'--input',str(root/'plan.xlsx'),'--strict-delivery','--template',str(template)],capture_output=True,text=True,check=False)
81
+ if result.returncode!=0:
82
+ raise UploadError('Fresh strict lint failed; upload blocked: '+result.stdout+result.stderr)
83
+ return root,validation,source
84
+
85
+
86
+ def require_context(cwd=None):
87
+ path=Path(cwd or Path.cwd())/'.ae/cli-agent-context.json'
88
+ if not path.is_file():
89
+ raise UploadError('Agent must maintain .ae/cli-agent-context.json before gateway calls (see ae-capability skill)')
90
+ context=read_json(path)
91
+ for name in ('agent_client','agent_session_id','intent_source','user_intent','session_goal'):
92
+ if not isinstance(context.get(name),str) or not context[name].strip():
93
+ raise UploadError(f'Missing agent-context field: {name}')
94
+ if context['intent_source']!='agent_context_file':
95
+ raise UploadError('Invalid agent-context intent_source')
96
+ if not context.get('agent_model') and context.get('context_capture_status')!='partial':
97
+ raise UploadError('Confirm agent_model, or explicitly mark partial when it cannot be confirmed')
98
+
99
+
100
+ def default_runner(argv):
101
+ env=dict(os.environ)
102
+ env['AE_LANG']='zh' # XLSX schema language; conversation language is independent.
103
+ return subprocess.run(argv,capture_output=True,text=True,check=False,env=env)
104
+
105
+
106
+ def run_help(cli, command, flags, runner):
107
+ result=runner([cli,*command,'--help'])
108
+ text=result.stdout+'\n'+result.stderr
109
+ if result.returncode!=0:
110
+ raise UploadError('Unable to inspect installed command: '+' '.join(command))
111
+ for flag in flags:
112
+ if not re.search(re.escape(flag)+r'(?=[\s=,]|$)',text):
113
+ raise UploadError(f'Installed command does not advertise {flag}; stop and rediscover supported interfaces')
114
+
115
+
116
+ def api(cli, command, runner):
117
+ result=runner([cli,*command])
118
+ try:
119
+ envelope=json.loads(result.stdout)
120
+ except (ValueError,TypeError) as exc:
121
+ raise UploadError('CLI response is not one JSON envelope; outcome may be unknown; do not retry a write automatically') from exc
122
+ if not isinstance(envelope,dict):
123
+ raise UploadError('CLI response must be an object envelope, not a scalar/list')
124
+ notice=envelope.get('_notice',{}).get('host_compat') if isinstance(envelope.get('_notice'),dict) else None
125
+ if result.stderr.strip() or notice:
126
+ print('⚠️ AE CLI warning: '+result.stderr.strip(),file=sys.stderr)
127
+ if notice:
128
+ print(json.dumps({'host_compat':notice},ensure_ascii=False),file=sys.stderr)
129
+ if result.returncode!=0 or envelope.get('ok') is not True or 'data' not in envelope:
130
+ raise UploadError('CLI operation did not return a verified success envelope: '+json.dumps(envelope,ensure_ascii=False))
131
+ if not isinstance(envelope['data'],dict):
132
+ raise UploadError('CLI data is inconclusive (not an object); do not infer an empty plan or accepted import')
133
+ return envelope
134
+
135
+
136
+ def capability_contract(envelope):
137
+ data=envelope.get('data')
138
+ if not isinstance(data,dict):
139
+ raise UploadError('Unsupported capability inspection envelope; inspect the deployed schema before adapting')
140
+ identifier=data.get('capability_id',data.get('id'))
141
+ schema=data.get('input_schema')
142
+ if identifier!='tracking.plan.import_excel' or data.get('risk')!='write':
143
+ raise UploadError('Unexpected or destructive capability contract; no import will run')
144
+ if not isinstance(schema,dict) or schema.get('type')!='object' or not isinstance(schema.get('properties'),dict) or not {'project_id','input_file_id'}.issubset(schema['properties']):
145
+ raise UploadError('Unknown import input schema; stop rather than guess input fields')
146
+ return {'capability_id':identifier,'risk':data['risk'],'input_schema':schema}
147
+
148
+
149
+ def discover(cli, runner, target):
150
+ # --host is a global CLI option; capability subcommand help may omit it.
151
+ run_help(cli,[],['--host'],runner)
152
+ run_help(cli,['tracking','plan','get'],['--project-id','--host'],runner)
153
+ run_help(cli,['tracking','plan','import-excel'],['--project-id','--input-file','--lang','--host'],runner)
154
+ run_help(cli,['capability','inspect'],['--project-id'],runner)
155
+ inspected=api(cli,['capability','inspect','tracking.plan.import_excel','--project-id',str(target['project_id']),'--host',target['host']],runner)
156
+ capability_contract(inspected)
157
+ return inspected
158
+
159
+
160
+ def validate_baseline(envelope, target):
161
+ """Recognize documented camelCase and draft-shaped pools; unknown is not empty.
162
+
163
+ Live gateway variants must be inspected and deliberately adapted. This
164
+ conservative guard never interprets null, omitted pools or scalars as empty.
165
+ """
166
+ data=envelope.get('data')
167
+ if not isinstance(data,dict):
168
+ raise UploadError('Project baseline schema is inconclusive (not an object); do not infer an empty plan')
169
+ layouts=[('events','eventProps','commonEventProps','userProps'),
170
+ ('events','event_props','common_event_props','user_props'),
171
+ ('events','event_properties','common_event_properties','user_properties')]
172
+ layout=next((keys for keys in layouts if all(isinstance(data.get(k),list) for k in keys)),None)
173
+ if layout is None and all(isinstance(data.get(k),list) for k in ('events','event_props')):
174
+ # Verified tracking-plan-get behavior: empty common/user pools may be
175
+ # omitted. Events and event_props remain mandatory; null/wrong types fail.
176
+ optional=('common_event_props','user_props')
177
+ if all(k not in data or isinstance(data[k],list) for k in optional):
178
+ layout=('events','event_props',*optional)
179
+ if layout is None:
180
+ raise UploadError('Unsupported or partial baseline pools; inspect the actual get schema before continuing')
181
+ if data.get('projectId',data.get('project_id',target['project_id']))!=target['project_id']:
182
+ raise UploadError('Baseline project identity does not match the confirmed target')
183
+ for key in layout:
184
+ if key in data and any(not isinstance(record,dict) for record in data[key]):
185
+ raise UploadError('Baseline pool has non-object records; cannot verify business scope')
186
+ return data
187
+
188
+
189
+ def freeze_payload(root, fingerprints):
190
+ """Freeze exactly the reviewed bytes after the last remote read, not a mutable path."""
191
+ payloads={}
192
+ for name,expected in fingerprints.items():
193
+ if name not in ('plan.normalized.json','plan.xlsx','conversation.md'):
194
+ raise UploadError('Unexpected artifact name in fingerprint receipt')
195
+ path=root/name
196
+ if path.is_symlink():
197
+ raise UploadError('Artifact became a symlink before dispatch')
198
+ payload=path.read_bytes()
199
+ if hashlib.sha256(payload).hexdigest()!=expected:
200
+ raise UploadError('Artifact changed during preflight; no write dispatched: '+name)
201
+ payloads[name]=payload
202
+ snapshot=root/'.upload-snapshot'
203
+ snapshot.mkdir(mode=0o700,exist_ok=False)
204
+ for name,payload in payloads.items():
205
+ with (snapshot/name).open('xb') as f:
206
+ f.write(payload)
207
+ f.flush()
208
+ os.fchmod(f.fileno(),0o400)
209
+ return snapshot/'plan.xlsx'
210
+
211
+
212
+ def import_errors(envelope):
213
+ errors=[]
214
+ def walk(value):
215
+ if isinstance(value,dict):
216
+ for key,item in value.items():
217
+ if key=='eventErrorMap' and item:
218
+ errors.append({key:item})
219
+ elif key=='return_code' and item not in (0,'0'):
220
+ errors.append({key:item})
221
+ else:
222
+ walk(item)
223
+ elif isinstance(value,list):
224
+ for item in value: walk(item)
225
+ walk(envelope.get('data'))
226
+ return errors
227
+
228
+
229
+ def preflight(delivery,project_id,host,output,cli='ae-cli',runner=default_runner,context_cwd=None,template=DEFAULT_TEMPLATE):
230
+ root,validation,_=local_gate(delivery,template)
231
+ target=check_target(project_id,host)
232
+ output=ensure_new_path(output,(root/'validation.json',root/'plan.normalized.json',root/'plan.xlsx'))
233
+ require_context(context_cwd)
234
+ schema=discover(cli,runner,target)
235
+ baseline=api(cli,['tracking','plan','get','--project-id',str(project_id),'--host',target['host']],runner)
236
+ validate_baseline(baseline,target)
237
+ result={'schema_version':1,'created_at':now(),'target':target,'fingerprints':validation['fingerprints'],'baseline_sha256':digest(baseline['data']),'baseline':baseline,'import_capability':schema,'status':'read_only_preflight_complete','warning':'An empty response/error is not proof of an empty plan. Review this verified baseline before confirming an append.'}
238
+ write_new_json(output,result)
239
+ return result
240
+
241
+
242
+ def review_gate(review,preflight_data,validation,target):
243
+ if review.get('schema_version')!=1 or review.get('status')!='passed':
244
+ raise UploadError('Semantic review has not passed')
245
+ if not isinstance(review.get('reviewer'),str) or not review['reviewer'].strip():
246
+ raise UploadError('Semantic reviewer identity/evidence is missing')
247
+ for obj in (review,preflight_data):
248
+ if obj.get('fingerprints')!=validation['fingerprints'] or obj.get('target')!=target:
249
+ raise UploadError('Review/preflight targets or artifact fingerprints do not match')
250
+ if review.get('baseline_sha256')!=preflight_data.get('baseline_sha256'):
251
+ raise UploadError('Review did not cover the inspected baseline')
252
+ if review.get('blocking_unknowns')!=[] or review.get('conflicts_resolved') is not True:
253
+ raise UploadError('Blocking unknowns or unresolved project conflicts remain')
254
+ checks=review.get('checks',[])
255
+ expected={key for key,_ in REVIEW_CHECKS}
256
+ if not isinstance(checks,list) or any(not isinstance(item,dict) for item in checks):
257
+ raise UploadError('Semantic review checks must be objects')
258
+ if len(checks)!=len(expected) or {item.get('id') for item in checks}!=expected:
259
+ raise UploadError('All fifteen review checks are required exactly once')
260
+ for item in checks:
261
+ if item.get('status') not in ('passed','not_applicable') or not isinstance(item.get('evidence'),str) or not item['evidence'].strip():
262
+ raise UploadError('Pending/failed/unsubstantiated semantic check: '+str(item.get('id')))
263
+
264
+
265
+ def upload(delivery,project_id,host,preflight_path,review_path,confirmed=False,cli='ae-cli',runner=default_runner,context_cwd=None,template=DEFAULT_TEMPLATE):
266
+ if confirmed is not True:
267
+ raise UploadError('Explicit user upload confirmation is required; --confirm is not permission to delete or replace')
268
+ root,validation,_=local_gate(delivery,template)
269
+ target=check_target(project_id,host)
270
+ prepared=read_json(preflight_path)
271
+ review=read_json(review_path)
272
+ review_gate(review,prepared,validation,target)
273
+ if prepared.get('status')!='read_only_preflight_complete':
274
+ raise UploadError('Read-only preflight is incomplete')
275
+ receipt_path=ensure_new_path(root/'upload-attempt.json')
276
+ require_context(context_cwd)
277
+ inspected=discover(cli,runner,target)
278
+ if capability_contract(inspected)!=capability_contract(prepared.get('import_capability',{})):
279
+ raise UploadError('Import capability contract changed since preflight; review the new scope before writing')
280
+ current=api(cli,['tracking','plan','get','--project-id',str(project_id),'--host',target['host']],runner)
281
+ validate_baseline(current,target)
282
+ if digest(current['data'])!=prepared['baseline_sha256']:
283
+ raise UploadError('Project plan changed since review; inspect the diff and obtain fresh confirmation')
284
+ # Recheck after slow discovery/network calls, then upload only a frozen copy.
285
+ _,fresh_validation,source=local_gate(root,template)
286
+ if fresh_validation['fingerprints']!=validation['fingerprints']:
287
+ raise UploadError('Delivery validation changed during preflight; confirmation is stale')
288
+ if source.get('meta',{}).get('blocking_unknowns'):
289
+ raise UploadError('Source still contains blocking unknowns')
290
+ payload_path=freeze_payload(root,validation['fingerprints'])
291
+ # Persist a one-shot attempt BEFORE dispatch. A crash/timeout must not silently retry.
292
+ attempt={'schema_version':1,'started_at':now(),'target':target,'fingerprints':validation['fingerprints'],'baseline_sha256':prepared['baseline_sha256'],'status':'dispatch_started_outcome_unknown','mode':'non_destructive_import','user_confirmation_supplied':True,'snapshot_file':str(payload_path),'snapshot_sha256':file_sha256(payload_path)}
293
+ write_new_json(receipt_path,attempt)
294
+ try:
295
+ imported=api(cli,['tracking','plan','import-excel','--project-id',str(project_id),'--input-file',str(payload_path),'--lang','zh','--host',target['host']],runner)
296
+ # The gateway can return success while rows are rejected: capture fresh content,
297
+ # never claim 'verified' merely from ok=true or a zero process exit status.
298
+ readback=api(cli,['tracking','plan','get','--project-id',str(project_id),'--host',target['host']],runner)
299
+ errors=import_errors(imported)
300
+ status='import_reported_errors_require_review' if errors else 'import_accepted_readback_requires_review'
301
+ result={**attempt,'finished_at':now(),'status':status,'import_response':imported,'import_errors':errors,'readback':readback,'readback_sha256':digest(readback['data']),'management_url':target['host']+'/#/data/plan','next_step':'Compare event names, property types, associations, platform and existing items against the source and baseline; inspect per-item errors; only then report upload verified. Do not auto-run delete/replace or retry.'}
302
+ write_new_json(root/'upload-result.json',result)
303
+ return result
304
+ except (OSError,ValueError,subprocess.SubprocessError) as exc:
305
+ write_new_json(root/'upload-error.json',{**attempt,'finished_at':now(),'status':'outcome_requires_reconciliation','error':str(exc),'next_step':'Read back the target plan before any retry; preserve attempt evidence.'})
306
+ raise
307
+
308
+
309
+ def main(argv=None):
310
+ ap=argparse.ArgumentParser(description=__doc__)
311
+ ap.add_argument('--delivery',required=True)
312
+ ap.add_argument('--project-id',required=True,type=int)
313
+ ap.add_argument('--host',required=True,help='Verified AE origin; not guessed from a template')
314
+ ap.add_argument('--ae-cli',default='ae-cli')
315
+ ap.add_argument('--preflight',action='store_true',help='Read-only discovery and baseline capture; never uploads')
316
+ ap.add_argument('--output',help='NEW preflight evidence JSON')
317
+ ap.add_argument('--preflight-file')
318
+ ap.add_argument('--review')
319
+ ap.add_argument('--confirm',action='store_true',help='Use only after the user explicitly confirms the displayed target and plan')
320
+ args=ap.parse_args(argv)
321
+ try:
322
+ if args.preflight:
323
+ if not args.output or args.confirm or args.review or args.preflight_file:
324
+ raise UploadError('--preflight requires --output only; do not combine with a write confirmation')
325
+ result=preflight(args.delivery,args.project_id,args.host,args.output,args.ae_cli)
326
+ code=0
327
+ else:
328
+ if not args.preflight_file or not args.review or args.output:
329
+ raise UploadError('Upload requires --preflight-file, --review and explicit --confirm')
330
+ result=upload(args.delivery,args.project_id,args.host,args.preflight_file,args.review,args.confirm,args.ae_cli)
331
+ code=3 # accepted, but remote acceptance still requires comparison by the Agent
332
+ print(json.dumps(result,ensure_ascii=False,indent=2))
333
+ return code
334
+ except (OSError,ValueError,KeyError) as exc:
335
+ print(f'ERROR: {exc}',file=sys.stderr)
336
+ return 1
337
+
338
+
339
+ if __name__=='__main__':
340
+ raise SystemExit(main())