qiyu-cli 0.0.0-stage → 0.2.1

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 (230) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +467 -2
  3. package/dist/cli.js +248 -0
  4. package/dist/commands/api.js +770 -0
  5. package/dist/commands/auth.js +349 -0
  6. package/dist/commands/credentials-source.js +70 -0
  7. package/dist/commands/db.js +503 -0
  8. package/dist/commands/local-fallback-wiring.js +67 -0
  9. package/dist/commands/local-fallback.js +34 -0
  10. package/dist/commands/query.js +564 -0
  11. package/dist/commands/skill-specs.js +64 -0
  12. package/dist/commands/skill.js +908 -0
  13. package/dist/commands/spec-types.js +145 -0
  14. package/dist/commands/stats.js +299 -0
  15. package/dist/commands/store-flags.js +56 -0
  16. package/dist/commands/store.js +258 -0
  17. package/dist/commands/sync-run.js +479 -0
  18. package/dist/commands/sync.js +757 -0
  19. package/dist/commands/tree.js +27 -0
  20. package/dist/core/config.js +259 -0
  21. package/dist/core/credentials.js +71 -0
  22. package/dist/core/edition.js +28 -0
  23. package/dist/core/envelope.js +201 -0
  24. package/dist/core/errors.js +356 -0
  25. package/dist/core/http.js +348 -0
  26. package/dist/core/ratelimit.js +126 -0
  27. package/dist/core/registry/index.js +212 -0
  28. package/dist/core/registry/params/ai.knowledge.addKnowledge.json +88 -0
  29. package/dist/core/registry/params/ai.knowledge.deleteKnowledges.json +46 -0
  30. package/dist/core/registry/params/ai.knowledge.editChannelAnswer.json +60 -0
  31. package/dist/core/registry/params/ai.knowledge.editKnowledge.json +95 -0
  32. package/dist/core/registry/params/ai.knowledge.editKnowledgeNoSimilars.json +102 -0
  33. package/dist/core/registry/params/ai.knowledge.getCategoryTree.json +39 -0
  34. package/dist/core/registry/params/ai.knowledge.getDetail.json +46 -0
  35. package/dist/core/registry/params/ai.knowledge.search.json +67 -0
  36. package/dist/core/registry/params/ai.statistic.transferHuman.json +60 -0
  37. package/dist/core/registry/params/category.list.json +39 -0
  38. package/dist/core/registry/params/chat.queue.group.query.json +39 -0
  39. package/dist/core/registry/params/crm.modifyOrder.json +48 -0
  40. package/dist/core/registry/params/crm.modifyUser.json +48 -0
  41. package/dist/core/registry/params/crm.syncCrmInfo.json +46 -0
  42. package/dist/core/registry/params/crm.tagChange.json +74 -0
  43. package/dist/core/registry/params/data.overview.ipcc.json +32 -0
  44. package/dist/core/registry/params/data.overview.session.json +53 -0
  45. package/dist/core/registry/params/evaluation.setting.get.json +39 -0
  46. package/dist/core/registry/params/event.applyStaff.json +116 -0
  47. package/dist/core/registry/params/event.evaluate.json +74 -0
  48. package/dist/core/registry/params/event.inviteEvaluate.json +81 -0
  49. package/dist/core/registry/params/event.qcResult.json +166 -0
  50. package/dist/core/registry/params/event.queryQueueStatus.json +39 -0
  51. package/dist/core/registry/params/event.queueEnter.json +40 -0
  52. package/dist/core/registry/params/event.queueLeave.json +46 -0
  53. package/dist/core/registry/params/event.quitQueue.json +39 -0
  54. package/dist/core/registry/params/event.sessionChange.json +95 -0
  55. package/dist/core/registry/params/event.sessionData.json +452 -0
  56. package/dist/core/registry/params/event.sessionEnd.json +117 -0
  57. package/dist/core/registry/params/event.sessionStart.json +109 -0
  58. package/dist/core/registry/params/event.updateUInfo.json +46 -0
  59. package/dist/core/registry/params/export.session.check.json +7 -0
  60. package/dist/core/registry/params/export.session.json +7 -0
  61. package/dist/core/registry/params/export.session.one.json +7 -0
  62. package/dist/core/registry/params/export.session.one.message.json +7 -0
  63. package/dist/core/registry/params/get_call_order.json +50 -0
  64. package/dist/core/registry/params/get_call_user_info.json +36 -0
  65. package/dist/core/registry/params/get_order.json +50 -0
  66. package/dist/core/registry/params/get_token.json +22 -0
  67. package/dist/core/registry/params/get_user_info.json +36 -0
  68. package/dist/core/registry/params/icoutcall.callIntercept.list.json +32 -0
  69. package/dist/core/registry/params/icoutcall.dialogFlow.fuzzySearch.json +53 -0
  70. package/dist/core/registry/params/icoutcall.dialogFlow.getDialogFlowList.json +32 -0
  71. package/dist/core/registry/params/icoutcall.get.customer.json +39 -0
  72. package/dist/core/registry/params/icoutcall.get.jobdetail.json +39 -0
  73. package/dist/core/registry/params/icoutcall.get.jobproperties.json +39 -0
  74. package/dist/core/registry/params/icoutcall.history.seat.json +67 -0
  75. package/dist/core/registry/params/icoutcall.history.team.json +67 -0
  76. package/dist/core/registry/params/icoutcall.job.create.json +53 -0
  77. package/dist/core/registry/params/icoutcall.job.importcustomer.json +46 -0
  78. package/dist/core/registry/params/icoutcall.job.pause.json +39 -0
  79. package/dist/core/registry/params/icoutcall.job.readdcustomer.json +109 -0
  80. package/dist/core/registry/params/icoutcall.job.start.json +39 -0
  81. package/dist/core/registry/params/icoutcall.job.terminate.json +39 -0
  82. package/dist/core/registry/params/icoutcall.phone.getLineList.json +32 -0
  83. package/dist/core/registry/params/ipcc.calltask.add.auto.json +117 -0
  84. package/dist/core/registry/params/ipcc.calltask.add.byCustom.json +96 -0
  85. package/dist/core/registry/params/ipcc.calltask.add.byRelation.json +82 -0
  86. package/dist/core/registry/params/ipcc.calltask.add.toGroup.json +89 -0
  87. package/dist/core/registry/params/ipcc.calltask.add.toStaff.json +89 -0
  88. package/dist/core/registry/params/ipcc.calltask.get.json +47 -0
  89. package/dist/core/registry/params/ipcc.calltaskdetail.add.json +54 -0
  90. package/dist/core/registry/params/ipcc.calltaskdetail.delete.json +40 -0
  91. package/dist/core/registry/params/ipcc.calltaskdetail.get.json +54 -0
  92. package/dist/core/registry/params/ipcc.calltaskdetail.update.json +40 -0
  93. package/dist/core/registry/params/ipcc.customfield.template.get.json +47 -0
  94. package/dist/core/registry/params/ipcc.login.json +47 -0
  95. package/dist/core/registry/params/kefu.add.json +130 -0
  96. package/dist/core/registry/params/kefu.delete.json +39 -0
  97. package/dist/core/registry/params/kefu.update.json +137 -0
  98. package/dist/core/registry/params/kefu.v2.query.json +39 -0
  99. package/dist/core/registry/params/kefuGroup.add.json +39 -0
  100. package/dist/core/registry/params/kefuGroup.delete.json +39 -0
  101. package/dist/core/registry/params/kefuGroup.update.json +46 -0
  102. package/dist/core/registry/params/kefuGroup.updateKefus.json +46 -0
  103. package/dist/core/registry/params/merchant.account.login.json +53 -0
  104. package/dist/core/registry/params/merchant.changePassword.json +46 -0
  105. package/dist/core/registry/params/merchant.create.json +81 -0
  106. package/dist/core/registry/params/merchant.disable.json +39 -0
  107. package/dist/core/registry/params/merchant.enable.json +39 -0
  108. package/dist/core/registry/params/merchant.list.json +46 -0
  109. package/dist/core/registry/params/merchant.query.json +46 -0
  110. package/dist/core/registry/params/merchant.update.json +74 -0
  111. package/dist/core/registry/params/message.send.image.json +53 -0
  112. package/dist/core/registry/params/message.send.json +53 -0
  113. package/dist/core/registry/params/message.send.voice.json +53 -0
  114. package/dist/core/registry/params/message.sendFile.json +39 -0
  115. package/dist/core/registry/params/message.uploadFile.json +39 -0
  116. package/dist/core/registry/params/online.session.category.list.json +39 -0
  117. package/dist/core/registry/params/online.session.customfield.template.json +39 -0
  118. package/dist/core/registry/params/online.session.customfield.update.json +74 -0
  119. package/dist/core/registry/params/order.upload.json +40 -0
  120. package/dist/core/registry/params/push.msg.image.json +74 -0
  121. package/dist/core/registry/params/push.msg.richText.json +74 -0
  122. package/dist/core/registry/params/push.msg.text.json +74 -0
  123. package/dist/core/registry/params/receive.message.json +89 -0
  124. package/dist/core/registry/params/robot.data.getQuestionsByCategoryName.json +67 -0
  125. package/dist/core/registry/params/robot.data.knowledge.json +46 -0
  126. package/dist/core/registry/params/robot.data.kpoint.json +46 -0
  127. package/dist/core/registry/params/robot.data.queryStandardByEffectiveQuestion.json +46 -0
  128. package/dist/core/registry/params/robot.data.queryStandardQuestionList.json +46 -0
  129. package/dist/core/registry/params/robot.evaluation.comment.json +67 -0
  130. package/dist/core/registry/params/robot.evaluation.setting.json +46 -0
  131. package/dist/core/registry/params/robot.session.assist.json +74 -0
  132. package/dist/core/registry/params/robot.session.chat.json +74 -0
  133. package/dist/core/registry/params/robot.session.close.json +53 -0
  134. package/dist/core/registry/params/robot.session.commonQuestions.json +74 -0
  135. package/dist/core/registry/params/robot.session.create.json +81 -0
  136. package/dist/core/registry/params/robot.session.evaluation.json +67 -0
  137. package/dist/core/registry/params/robot.session.msgAssociate.json +46 -0
  138. package/dist/core/registry/params/robot.session.msgEvaluation.json +53 -0
  139. package/dist/core/registry/params/robot.session.msgPredict.json +74 -0
  140. package/dist/core/registry/params/robot.session.transfer.json +36 -0
  141. package/dist/core/registry/params/robot.session.uploadFile.json +32 -0
  142. package/dist/core/registry/params/robot.statistic.summary.json +53 -0
  143. package/dist/core/registry/params/robot.transfer.config.json +15 -0
  144. package/dist/core/registry/params/session.user.profile.json +39 -0
  145. package/dist/core/registry/params/settings.wxTemplates.json +46 -0
  146. package/dist/core/registry/params/smstask.create.json +53 -0
  147. package/dist/core/registry/params/smstask.status.json +39 -0
  148. package/dist/core/registry/params/staff.group.list.new.json +39 -0
  149. package/dist/core/registry/params/staff.group.members.new.json +46 -0
  150. package/dist/core/registry/params/staff.list.new.json +46 -0
  151. package/dist/core/registry/params/staff.login.json +47 -0
  152. package/dist/core/registry/params/statistic.overview.json +61 -0
  153. package/dist/core/registry/params/statistic.performance.json +82 -0
  154. package/dist/core/registry/params/statistic.salaryDetail.json +54 -0
  155. package/dist/core/registry/params/statistic.satisfaction.report.json +68 -0
  156. package/dist/core/registry/params/statistic.staffAttendance.json +75 -0
  157. package/dist/core/registry/params/statistic.staffquality.json +75 -0
  158. package/dist/core/registry/params/statistic.staffworklod.json +68 -0
  159. package/dist/core/registry/params/tag.all.json +32 -0
  160. package/dist/core/registry/params/tag.batchUpdate.json +32 -0
  161. package/dist/core/registry/params/tag.update.json +60 -0
  162. package/dist/core/registry/params/ticket.apply.json +46 -0
  163. package/dist/core/registry/params/ticket.batch.modify.json +53 -0
  164. package/dist/core/registry/params/ticket.create.json +151 -0
  165. package/dist/core/registry/params/ticket.filter.count.json +46 -0
  166. package/dist/core/registry/params/ticket.filter.list.json +46 -0
  167. package/dist/core/registry/params/ticket.finish.json +60 -0
  168. package/dist/core/registry/params/ticket.followers.update.json +60 -0
  169. package/dist/core/registry/params/ticket.list.json +74 -0
  170. package/dist/core/registry/params/ticket.log.json +39 -0
  171. package/dist/core/registry/params/ticket.modify.json +74 -0
  172. package/dist/core/registry/params/ticket.new.detail.json +39 -0
  173. package/dist/core/registry/params/ticket.reminder.json +60 -0
  174. package/dist/core/registry/params/ticket.reopen.json +67 -0
  175. package/dist/core/registry/params/ticket.reply.json +60 -0
  176. package/dist/core/registry/params/ticket.search.json +116 -0
  177. package/dist/core/registry/params/ticket.template.fields.json +39 -0
  178. package/dist/core/registry/params/ticket.template.list.json +39 -0
  179. package/dist/core/registry/params/ticket.transfer.json +74 -0
  180. package/dist/core/registry/params/track.event.set.json +32 -0
  181. package/dist/core/registry/params/wecom.robot.switch.json +43 -0
  182. package/dist/core/registry/params.js +84 -0
  183. package/dist/core/registry/specs.json +2172 -0
  184. package/dist/core/registry/validate.json +11 -0
  185. package/dist/core/registry/validation-overrides.js +98 -0
  186. package/dist/core/sanitize.js +24 -0
  187. package/dist/core/sign.js +21 -0
  188. package/dist/core/time.js +194 -0
  189. package/dist/core/validate.js +140 -0
  190. package/dist/output.js +263 -0
  191. package/dist/postinstall.js +178 -0
  192. package/dist/query/errors.js +395 -0
  193. package/dist/query/mask.js +368 -0
  194. package/dist/query/metric-catalog.js +85 -0
  195. package/dist/query/sandbox.js +544 -0
  196. package/dist/query/table-query.js +297 -0
  197. package/dist/query/time-shape.js +44 -0
  198. package/dist/schedule/install.js +377 -0
  199. package/dist/skill/check.js +429 -0
  200. package/dist/skill/detect.js +371 -0
  201. package/dist/skill/install.js +1202 -0
  202. package/dist/skill/paths.js +343 -0
  203. package/dist/skill/qiyu/SKILL.md +92 -0
  204. package/dist/skill/qiyu/errors.md +55 -0
  205. package/dist/skill/qiyu/forbidden.md +52 -0
  206. package/dist/skill/qiyu/metrics.md +65 -0
  207. package/dist/skill/qiyu/protocols.md +55 -0
  208. package/dist/skill/qiyu/setup.md +50 -0
  209. package/dist/skill/refs.js +379 -0
  210. package/dist/store/config.js +137 -0
  211. package/dist/store/duckdb.js +321 -0
  212. package/dist/store/index.js +18 -0
  213. package/dist/store/retry.js +36 -0
  214. package/dist/store/schema.js +419 -0
  215. package/dist/store/types.js +4 -0
  216. package/dist/sync/day.js +8 -0
  217. package/dist/sync/engine.js +818 -0
  218. package/dist/sync/rate-gate.js +95 -0
  219. package/dist/sync/registry.js +22 -0
  220. package/dist/sync/state.js +114 -0
  221. package/dist/sync/tasks/dim.js +186 -0
  222. package/dist/sync/tasks/knowledge.js +252 -0
  223. package/dist/sync/tasks/pace.js +66 -0
  224. package/dist/sync/tasks/pipeline.js +321 -0
  225. package/dist/sync/tasks/reports.js +448 -0
  226. package/dist/sync/tasks/sessions.js +188 -0
  227. package/dist/sync/tasks/tickets.js +219 -0
  228. package/dist/sync/types.js +1 -0
  229. package/dist/sync/windowing.js +56 -0
  230. package/package.json +52 -4
@@ -0,0 +1,757 @@
1
+ // src/commands/sync.ts —— D-T12:sync 命令骨架;D-T13:run 子命令挂载;
2
+ // D-T14:status / verify / install / uninstall 四子命令。
3
+ // 骨架沿 store.ts:parseStoreFlags → usageFail/fail 双通道 → thrownToExit 扩展。
4
+ // --pretty(G1 已实现):输出缩进开关,写在子命令之后。留在这里的只是历史裁决说明——
5
+ // 当年「承诺过、未实现」时的统一拒绝已退役;现在的规则与 api 族一致:未知/位置参数 →
6
+ // help → --pretty,各层同答。
7
+ //
8
+ // T14 语义(spec §7.6 / 简化裁定):
9
+ // · status / verify 以 ro 打开库(spec §6.3:单写者模型下读者走 C1 退避);
10
+ // · verify 对 snapshot 任务做三方核对(本地表行数 / 上游任务 fetch 的 apiCount /
11
+ // sync_state 状态),对 windowed 任务不做上游全量重拉(成本高),只核对
12
+ // local_rows 与 sync_state 成功状态的一致性——expected_from_api 为 null,
13
+ // drift 非空时 detail 说明核对方式;
14
+ // · install/uninstall 的平台条目生成与命令执行在 src/schedule/install.ts,
15
+ // 平台检测与外部命令均为注入点(__setPlatform/__setRun);
16
+ // · install 前置探测(E 高-1):**必须存在真实成功证据** —— sync_state 有
17
+ // `range_status='complete'` 或 `last_synced_at` 非空的行。引擎在窗口执行前就
18
+ // markPending 落行,所以「有行」不等于「跑通过」:全败的 run 同样留下 pending 行,
19
+ // 按「有行」放行会把调度器装在一个从未成功同步的库上(探测名不副实)。
20
+ // · store_not_initialized 的 hint 按**成因**分流(spec §九 + 架构审查 F1):`sync run`
21
+ // 首跑虽会自动建库,但「初始化存储」的最小命令是 store init —— 只对「不存在 / 空库」
22
+ // 成立;「路径不是 DuckDB 文件」「他人库(有表无 schema_version)」「依赖未安装」跑
23
+ // store init 会再次失败,必须指换 --db 路径 / 装依赖,否则 Agent 进
24
+ // store init → sync 死循环(同步侧的 storeInitFail 保留底层 hint 是同一裁定)。
25
+ // 输出键一律下划线命名(spec §七:range_status / gaps_count / local_rows /
26
+ // expected_from_api / state_windows_consistent)——本仓 Agent 契约的统一形态。
27
+ import { homedir } from 'node:os';
28
+ import { statSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
29
+ import { dirname } from 'node:path';
30
+ import { SYNC_TASKS, taskById, UNSUPPORTED_DATASETS } from '../sync/registry.js';
31
+ import { listGaps, listWatermarks } from '../sync/state.js';
32
+ import { resolveStoreConfig, currentStoreEnv } from '../store/config.js';
33
+ import { openStore } from '../store/index.js';
34
+ import { tableByName } from '../store/schema.js';
35
+ import { resolveCredentialsUsingFile, currentCredentialEnv } from './credentials-source.js';
36
+ import { ok, fail, usageFail, setPretty } from '../output.js';
37
+ import { runSyncRun, SYNC_RUN_USAGE, msToShanghaiIso, RUN_FLAGS } from './sync-run.js';
38
+ import { thrownToExit } from './store.js';
39
+ import { currentPlatform, runScheduleCommand, planInstall, planUninstall, } from '../schedule/install.js';
40
+ import { GLOBAL_FLAGS, GLOBAL_FLAG_NAMES, prettyAfterSubcommand, REJECTED_FLAGS, STORE_FLAGS, valueFlagNames } from './spec-types.js';
41
+ import { STORE_VALUE_FLAG_NAMES } from './store-flags.js';
42
+ /** `sync install` 的业务 flag。 */
43
+ const INSTALL_FLAGS = [
44
+ { name: '--schedule', kind: 'value' },
45
+ { name: '--yes', kind: 'bool' },
46
+ ...STORE_FLAGS,
47
+ ];
48
+ /** `sync uninstall` 的业务 flag:**只有** `--yes`(见下方 spec 的说明)。 */
49
+ const UNINSTALL_FLAGS = [{ name: '--yes', kind: 'bool' }];
50
+ /** `sync tasks` 的 flag:没有业务 flag,`flags` 就是全局那一份。 */
51
+ const TASKS_FLAGS = [...GLOBAL_FLAGS];
52
+ /**
53
+ * 命令契约(F 组 D4):`skill check` 据此判断 skill 正文里的 `qiyu sync …` 是否真的存在。
54
+ * `flags` 是**完整接受集**(含全局 flag),`--pretty` 同时在 `rejected` 里。
55
+ *
56
+ * ⚠️ `sync run` 的 spec 在这里而不在 `sync-run.ts`:spec 描述的是**命令路径**,而路径的
57
+ * 分派在 `syncCommand`;`runSyncRun` 只拿到剥掉 `run` 之后的参数。解析器的 flag 常量由
58
+ * `sync-run.ts` 导出(`RUN_FLAGS`)、这里引用,所以 spec 与解析器仍同源。
59
+ *
60
+ * ⚠️ **`sync uninstall` 不列 `STORE_FLAGS`(与 brief 表格的一处刻意偏离)。**
61
+ * brief 写「照实写上,因为 CLI 接受它们」,但实测并非如此:`syncUninstall` 的解析是
62
+ * `parseSubFlags(argv, [], ['--yes'])`,`--db` 会落进「未知参数:--db」退出码 2
63
+ * (`node dist/cli.js sync uninstall --db /tmp/x` 实测)。`sync.ts` 里的存储定位数组
64
+ * 只被 `storeArgsFor` 用于 **install** 的调度命令透传,uninstall 的 `planUninstall`
65
+ * 不接存储参数。把不接受的 flag 写进接受集,正是 `skill check` 要防的假阴性
66
+ * (skill 里写 `qiyu sync uninstall --db …` 会被判合法、实际必失败)——
67
+ * 所以这里以解析器为准。若将来让 uninstall 也透传存储定位,把 `...STORE_FLAGS` 加回来即可。
68
+ */
69
+ export const SYNC_SPECS = [
70
+ { path: ['sync', 'tasks'], flags: TASKS_FLAGS, positionals: [], rejected: REJECTED_FLAGS },
71
+ {
72
+ path: ['sync', 'run'],
73
+ flags: [...GLOBAL_FLAGS, ...RUN_FLAGS],
74
+ positionals: [{ name: '任务', domain: 'task-ids', repeatable: true }],
75
+ rejected: REJECTED_FLAGS,
76
+ },
77
+ {
78
+ path: ['sync', 'status'],
79
+ flags: [...GLOBAL_FLAGS, ...STORE_FLAGS],
80
+ positionals: [{ name: '任务', domain: 'task-ids', repeatable: true }],
81
+ rejected: REJECTED_FLAGS,
82
+ },
83
+ {
84
+ path: ['sync', 'verify'],
85
+ flags: [...GLOBAL_FLAGS, ...STORE_FLAGS],
86
+ positionals: [{ name: '任务', domain: 'task-ids', repeatable: true }],
87
+ rejected: REJECTED_FLAGS,
88
+ },
89
+ {
90
+ path: ['sync', 'install'],
91
+ flags: [...GLOBAL_FLAGS, ...INSTALL_FLAGS],
92
+ positionals: [],
93
+ rejected: REJECTED_FLAGS,
94
+ },
95
+ {
96
+ path: ['sync', 'uninstall'],
97
+ flags: [...GLOBAL_FLAGS, ...UNINSTALL_FLAGS],
98
+ positionals: [],
99
+ rejected: REJECTED_FLAGS,
100
+ },
101
+ ];
102
+ /**
103
+ * 解析器用的 flag 名,全部从上面的常量派生,不另写一份。
104
+ * ⚠️ `sync run` 的解析器在 `sync-run.ts`(它自己从 `RUN_FLAGS` 派生 `RUN_VALUE_FLAGS` /
105
+ * `RUN_BOOL_FLAGS`),这里的 `SYNC_SPECS` 只引用同一个 `RUN_FLAGS` —— 两侧同源。
106
+ */
107
+ const STORE_VALUE_FLAGS = [...STORE_VALUE_FLAG_NAMES];
108
+ const INSTALL_VALUE_FLAGS = valueFlagNames(INSTALL_FLAGS);
109
+ const INSTALL_BOOL_FLAGS = INSTALL_FLAGS.filter((f) => f.kind === 'bool').map((f) => f.name);
110
+ const TASKS_VALUE_FLAGS = valueFlagNames(TASKS_FLAGS);
111
+ const UNINSTALL_BOOL_FLAGS = UNINSTALL_FLAGS.map((f) => f.name);
112
+ const USAGE = `用法:qiyu sync <子命令> [参数]
113
+
114
+ 子命令:
115
+ sync tasks 列出全部同步任务与不支持的实时快照数据集
116
+ (每条含 sensitive_columns:该表标注 sensitive 的 PII 列清单)
117
+ sync run [任务...] 同步数据进本地库(--full / --since / --until / --quiet)
118
+ sync status [任务...] 水位、区间状态(resolved_range)、缺口(gaps)、锁(只读;缺省全部任务)
119
+ sync verify [任务...] 核对本地与远端一致性(快照三方核对;drift 非空退出码 1)
120
+ 快照任务给 expected_from_api(上游行数);windowed 任务不做上游
121
+ 全量重拉、该字段恒为 null,只以本地行数与 sync_state 成功状态核对
122
+ sync install --schedule CRON [--yes]
123
+ 生成并安装系统调度条目(默认 dry-run,--yes 才写入)
124
+ sync uninstall [--yes] 移除系统调度条目(默认 dry-run,--yes 才删除)
125
+
126
+ CRON 为 5 段(分 时 日 月 周),支持 * / 数字 / a-b / a-b/k / */k / 逗号列表。
127
+ 存储定位:--db / --profile / --backend(store 命令同族)。
128
+ install 的平台形态:darwin=launchd plist、linux=systemd unit+timer(crontab 兜底)、
129
+ win32=schtasks。安装前置:库已初始化且至少成功同步过一次(sync_state 有
130
+ range_status=complete 或 last_synced_at 非空的行;全败的 run 只留 pending,不算跑通)。
131
+ `;
132
+ const KNOWN = new Set(GLOBAL_FLAG_NAMES);
133
+ function parseSubFlags(argv, valueFlags, boolFlags = []) {
134
+ const out = { values: {}, flags: new Set(), rest: [] };
135
+ for (let i = 0; i < argv.length; i++) {
136
+ const a = argv[i];
137
+ if (valueFlags.includes(a)) {
138
+ const v = argv[i + 1];
139
+ if (v === undefined || v.startsWith('--'))
140
+ throw new Error(`${a} 缺少取值`);
141
+ out.values[a] = v;
142
+ i++;
143
+ }
144
+ else if (a === '--pretty') {
145
+ // G1:已实现的输出开关 —— 收下(不带值);开启动作在命令层(原拒绝点 setPretty(true))。
146
+ // 值位守卫仍优先:`--since --pretty` 报「--since 缺少取值」。
147
+ out.flags.add('--pretty');
148
+ }
149
+ else if (a === '--help' || a === '-h') {
150
+ out.flags.add('--help');
151
+ }
152
+ else if (boolFlags.includes(a)) {
153
+ out.flags.add(a);
154
+ }
155
+ else if (a.startsWith('-')) {
156
+ throw new Error(`未知参数:${a}`);
157
+ }
158
+ else {
159
+ out.rest.push(a);
160
+ }
161
+ }
162
+ return out;
163
+ }
164
+ /** 子命令的 --help 分流:--help 在则打 USAGE;带非 KNOWN 额外参数 → usage。 */
165
+ function subHelp(argv) {
166
+ if (!argv.includes('--help') && !argv.includes('-h'))
167
+ return null;
168
+ const extra = argv.filter((a) => !KNOWN.has(a));
169
+ if (extra.length > 0)
170
+ return usageFail(`未知参数:${extra.join(' ')}。--help 不接受额外参数`);
171
+ process.stdout.write(USAGE);
172
+ return 0;
173
+ }
174
+ /** 任务 id 校验(usage:未知 id 是参数错误)。 */
175
+ function selectTasks(ids) {
176
+ const unknown = ids.filter((id) => taskById(id) === undefined);
177
+ if (unknown.length > 0) {
178
+ return usageFail(`未知任务:${unknown.join('、')}\n可用任务:${SYNC_TASKS.map((t) => t.id).join('、')}`);
179
+ }
180
+ return ids.length > 0 ? ids.map((id) => taskById(id)) : SYNC_TASKS;
181
+ }
182
+ function resolveConfig(flags) {
183
+ const resolved = resolveStoreConfig({
184
+ flags,
185
+ env: currentStoreEnv(),
186
+ });
187
+ return { path: resolved.config.path, backend: resolved.config.backend, config: resolved.config };
188
+ }
189
+ /** 只读命令的库前置检查(statSync 分流沿 store status;hint 统一指 store init,spec §九)。 */
190
+ function statGuard(path) {
191
+ let st;
192
+ try {
193
+ st = statSync(path);
194
+ }
195
+ catch (e) {
196
+ if (e.code === 'ENOENT') {
197
+ return fail({
198
+ code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
199
+ message: `数据库文件不存在:${path}`,
200
+ hint: '数据库尚未初始化。请先运行:qiyu store init',
201
+ });
202
+ }
203
+ return fail({
204
+ code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
205
+ message: `无法访问 ${path}:${e instanceof Error ? e.message : String(e)}`,
206
+ hint: '请检查路径权限(只读命令不需要写权限)',
207
+ });
208
+ }
209
+ if (!st.isFile()) {
210
+ return fail({
211
+ code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
212
+ message: `不是普通文件:${path}`,
213
+ hint: '--db 指向的不是普通文件,请给出 .duckdb 数据库文件路径',
214
+ });
215
+ }
216
+ return null;
217
+ }
218
+ /** 打开 ro 库;结构不完整(缺 schema_version)视为「不是本 CLI 创建的库」。 */
219
+ async function openRo(config) {
220
+ let store;
221
+ try {
222
+ store = await openStore(config, 'ro');
223
+ }
224
+ catch (e) {
225
+ return { code: thrownToExit(e) };
226
+ }
227
+ try {
228
+ const names = await store.tables();
229
+ if (!names.includes('schema_version')) {
230
+ await store.close();
231
+ // 成因分形(store.ts 同款):有表无 schema_version 是他人库——store init 会再次
232
+ // 拒绝(duckdb.ts init 的他人库防线),引导过去就是 store init → sync status 死循环;
233
+ // 空库(无任何表)才是「init 可补」的成因。
234
+ return { code: fail({
235
+ code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
236
+ message: `数据库结构不完整(缺表):${config.path}`,
237
+ hint: names.length > 0
238
+ ? '目标数据库不是本 CLI 创建的,请换 --db 路径'
239
+ : '空库(无任何表)。请先运行:qiyu store init',
240
+ }) };
241
+ }
242
+ return { store };
243
+ }
244
+ catch (e) {
245
+ try {
246
+ await store.close();
247
+ }
248
+ catch { /* 清理错误不掩盖原异常 */ }
249
+ return { code: thrownToExit(e) };
250
+ }
251
+ }
252
+ // —— sync status ——
253
+ /**
254
+ * sync_state 的 resolved_range 列(epoch 毫秒字符串)→ [ISO, ISO] 输出(G2)。
255
+ * 两端都有值才输出;任一端缺失(v9 前的旧记录 / 从未成功推进)为 null ——
256
+ * 与 run 的 resolved_range 同形态(上海 +08:00 ISO)。
257
+ */
258
+ function resolvedRangeOut(st) {
259
+ const s = st?.resolvedRangeStart;
260
+ const e = st?.resolvedRangeEnd;
261
+ if (s === null || s === undefined || e === null || e === undefined)
262
+ return null;
263
+ return [msToShanghaiIso(s), msToShanghaiIso(e)];
264
+ }
265
+ async function syncStatus(argv) {
266
+ const help = subHelp(argv);
267
+ if (help !== null)
268
+ return help;
269
+ let parsed;
270
+ try {
271
+ parsed = parseSubFlags(argv, STORE_VALUE_FLAGS);
272
+ }
273
+ catch (e) {
274
+ return usageFail(e.message);
275
+ }
276
+ // G1:--pretty 已实现(原拒绝点在 parseSubFlags 的 throw)。次序:未知参数(parse 的
277
+ // throw)→ help(subHelp)→ 这里开 pretty → selectTasks 的未知任务名仍报 usage(缩进)。
278
+ if (parsed.flags.has('--pretty'))
279
+ setPretty(true);
280
+ const tasks = selectTasks(parsed.rest);
281
+ if (typeof tasks === 'number')
282
+ return tasks;
283
+ let resolved;
284
+ try {
285
+ resolved = resolveConfig({ db: parsed.values['--db'], profile: parsed.values['--profile'], backend: parsed.values['--backend'] });
286
+ }
287
+ catch (e) {
288
+ return usageFail(e.message);
289
+ }
290
+ const guarded = statGuard(resolved.path);
291
+ if (guarded !== null)
292
+ return guarded;
293
+ const opened = await openRo(resolved.config);
294
+ if (opened.code !== undefined || !opened.store)
295
+ return opened.code ?? 1;
296
+ const store = opened.store;
297
+ try {
298
+ const states = await listWatermarks(store);
299
+ const gaps = await listGaps(store);
300
+ const gapsByTask = new Map();
301
+ for (const g of gaps) {
302
+ const list = gapsByTask.get(g.dataset) ?? [];
303
+ // 缺口区间原样回显(sync_gaps 存的是引擎写入的毫秒字符串;这里不二次格式化,
304
+ // 与 run 输出的 ISO 形态差异见 spec §七——status 是状态面、run 是结果面)。
305
+ list.push({
306
+ range: [g.rangeStart, g.rangeEnd],
307
+ reason: g.reason, detail: g.detail, recorded_at: g.recordedAt,
308
+ });
309
+ gapsByTask.set(g.dataset, list);
310
+ }
311
+ const tasksOut = tasks.map((t) => {
312
+ const st = states.get(t.id);
313
+ const taskGaps = gapsByTask.get(t.id) ?? [];
314
+ return {
315
+ task: t.id,
316
+ watermark: st?.watermark ?? null,
317
+ range_status: st?.rangeStatus ?? null,
318
+ last_synced_at: st?.lastSyncedAt ?? null,
319
+ // G2 义务(spec §八.2/§十一.17):上次成功推进覆盖的区间,形态与 sync run 的
320
+ // resolved_range 一致([ISO, ISO];列空 = 尚无成功推进或 v9 前的旧记录)。
321
+ resolved_range: resolvedRangeOut(st),
322
+ // 历史缺口的读取通道(spec §三「水位、区间状态、缺口、锁」):逐条输出,
323
+ // gaps_count 保留为计数快照(既有消费者不破坏)。
324
+ gaps: taskGaps,
325
+ gaps_count: taskGaps.length,
326
+ // 锁列(sync_state.locked_by)——引擎盖章后为真;活跃写锁由本命令自身的
327
+ // ro 打开失败(store_locked)表达(DuckDB 单写者模型)。
328
+ locked: (st?.lockedBy ?? null) !== null,
329
+ };
330
+ });
331
+ return ok({ tasks: tasksOut });
332
+ }
333
+ catch (e) {
334
+ return thrownToExit(e);
335
+ }
336
+ finally {
337
+ await store.close();
338
+ }
339
+ }
340
+ async function syncVerify(argv) {
341
+ const help = subHelp(argv);
342
+ if (help !== null)
343
+ return help;
344
+ let parsed;
345
+ try {
346
+ parsed = parseSubFlags(argv, STORE_VALUE_FLAGS);
347
+ }
348
+ catch (e) {
349
+ return usageFail(e.message);
350
+ }
351
+ // G1:同 syncStatus —— 原拒绝点之后开 pretty。
352
+ if (parsed.flags.has('--pretty'))
353
+ setPretty(true);
354
+ const tasks = selectTasks(parsed.rest);
355
+ if (typeof tasks === 'number')
356
+ return tasks;
357
+ // 凭证惰性解析:快照任务需要上游 fetch;纯 windowed 选中时不碰凭证
358
+ //(归因准确:本地核对不该因缺环境变量失败)。
359
+ const needsUpstream = tasks.some((t) => t.kind === 'snapshot');
360
+ let creds;
361
+ if (needsUpstream) {
362
+ const credOutcome = resolveCredentialsUsingFile(currentCredentialEnv());
363
+ if (!credOutcome.ok)
364
+ return fail(credOutcome.error);
365
+ creds = credOutcome.creds;
366
+ }
367
+ let resolved;
368
+ try {
369
+ resolved = resolveConfig({ db: parsed.values['--db'], profile: parsed.values['--profile'], backend: parsed.values['--backend'] });
370
+ }
371
+ catch (e) {
372
+ return usageFail(e.message);
373
+ }
374
+ const guarded = statGuard(resolved.path);
375
+ if (guarded !== null)
376
+ return guarded;
377
+ const opened = await openRo(resolved.config);
378
+ if (opened.code !== undefined || !opened.store)
379
+ return opened.code ?? 1;
380
+ const store = opened.store;
381
+ try {
382
+ const states = await listWatermarks(store);
383
+ const tasksOut = [];
384
+ for (const t of tasks) {
385
+ const localRows = await store.count(t.table);
386
+ const st = states.get(t.id);
387
+ const stateConsistent = st !== undefined && st.rangeStatus === 'complete' && st.watermark !== null;
388
+ const drift = [];
389
+ if (st === undefined) {
390
+ drift.push({
391
+ kind: 'not_synced',
392
+ detail: 'sync_state 无该任务记录(从未同步)。请先运行:qiyu sync run',
393
+ });
394
+ }
395
+ else if (!stateConsistent) {
396
+ drift.push({
397
+ kind: 'state_pending',
398
+ detail: `sync_state.range_status=${st.rangeStatus ?? 'null'}(最后一次运行未完成或中断)。`
399
+ + (t.kind === 'windowed'
400
+ ? 'windowed 任务不做上游全量重拉(成本高):核对方式为本地行数与 sync_state 成功状态一致性——重跑 qiyu sync run 补全后再 verify。'
401
+ : '快照任务将以上游取数核对本地行数。'),
402
+ });
403
+ }
404
+ let expectedFromApi = null;
405
+ if (t.kind === 'snapshot') {
406
+ // 上游取数 = 任务 fetch(配对口径沿引擎:apiCount 为准,缺省取行数)。
407
+ try {
408
+ const res = await t.fetch({ start: 0, end: Date.now(), index: 0, total: 1 }, { store, credentials: creds });
409
+ expectedFromApi = res.apiCount ?? res.rows.length;
410
+ if (localRows !== expectedFromApi) {
411
+ drift.push({
412
+ kind: 'count_mismatch',
413
+ detail: `本地 ${t.table} 表 ${localRows} 行 ≠ 上游 ${expectedFromApi} 行(配对口径:apiCount)`,
414
+ });
415
+ }
416
+ }
417
+ catch (e) {
418
+ expectedFromApi = null;
419
+ drift.push({
420
+ kind: 'fetch_failed',
421
+ detail: `上游取数失败(无法核对 ≠ 一致):${e instanceof Error ? e.message : String(e)}`,
422
+ });
423
+ }
424
+ }
425
+ tasksOut.push({
426
+ task: t.id,
427
+ local_rows: localRows,
428
+ expected_from_api: expectedFromApi,
429
+ state_windows_consistent: stateConsistent,
430
+ drift,
431
+ });
432
+ }
433
+ const code = ok({ tasks: tasksOut });
434
+ const hasDrift = tasksOut.some((t) => t.drift.length > 0);
435
+ return hasDrift ? 1 : code;
436
+ }
437
+ catch (e) {
438
+ return thrownToExit(e);
439
+ }
440
+ finally {
441
+ await store.close();
442
+ }
443
+ }
444
+ // —— sync install / uninstall ——
445
+ const RATELIMIT_PREFIX = '__ratelimit__:';
446
+ /**
447
+ * install 要透传进调度命令的存储定位参数(修复批 4 #4)。
448
+ * 名单取自 `STORE_VALUE_FLAGS`(spec 的 `STORE_FLAGS` 派生)——不再本地手写一份。
449
+ */
450
+ const INSTALL_STORE_PASSTHROUGH = STORE_VALUE_FLAGS;
451
+ /**
452
+ * 调度条目的存储定位参数(修复批 4 #4 + 批 6 #1)。
453
+ * 两条来源、一个顺序(flag 在前、env 固化在后;同一 flag 不重复):
454
+ * ① 用户**显式给出**的 flag(`--db/--profile/--backend`)原样透传 —— 批 4 的既定路径;
455
+ * ② **env 派生**的存储定位:用户没给对应 flag、但 `QIYU_DB_PATH` / `QIYU_PROFILE` /
456
+ * `QIYU_STORE_BACKEND` 有值 —— 把**解析结果**(绝对路径 / profile 名 / backend 名)
457
+ * 固化为稳定参数。原因:launchd/schtasks/cron 的调度上下文**不继承**你的 shell
458
+ * 环境变量,前置探测用 env 指到的库、调度任务却跑默认库 —— 探测通过而同步打偏。
459
+ * 这里只固化「env 派生」:配置文件 store.path(HOME 下,调度任务自己读得到)与
460
+ * 内置默认值**不固化**(批 4 裁定:默认值固化会引入漂移)。
461
+ * 实现约束:**不读配置文件内容来生成参数**(配置路径不固化,调度任务自己会读它);
462
+ * env 已给但解析失败/为空时由 resolveConfig 在更早处抛 usage,不会走到这里。
463
+ * 同一 flag 只在 flag 缺席时才补 env 派生值 —— 显式 flag 永远优先(与 resolveStoreConfig
464
+ * 的 flags > env 优先级一致),不会出现两个 --db。
465
+ */
466
+ function storeArgsFor(parsed, resolved) {
467
+ const args = [];
468
+ const push = (flag, value) => { args.push(flag, value); };
469
+ // ① 显式 flag 原样透传(批 4 #4)
470
+ for (const f of INSTALL_STORE_PASSTHROUGH) {
471
+ const v = parsed.values[f];
472
+ if (v !== undefined)
473
+ push(f, v);
474
+ }
475
+ // ② env 派生 → 固化解析结果(仅当对应 flag 未给)
476
+ if (parsed.values['--db'] === undefined && process.env.QIYU_DB_PATH !== undefined) {
477
+ // 固化的是 resolveStoreConfig 解析后的**绝对路径**(env 的相对路径/`~` 已展开)——
478
+ // 调度任务的 cwd 与 HOME 都可能不同,相对路径会指向别处。
479
+ push('--db', resolved.path);
480
+ }
481
+ if (parsed.values['--profile'] === undefined && process.env.QIYU_PROFILE !== undefined) {
482
+ push('--profile', process.env.QIYU_PROFILE);
483
+ }
484
+ if (parsed.values['--backend'] === undefined && process.env.QIYU_STORE_BACKEND !== undefined) {
485
+ // backend 当前唯一合法值 duckdb(resolveStoreConfig 已校验),固化解析结果而非原始 env 值。
486
+ push('--backend', resolved.backend);
487
+ }
488
+ return args;
489
+ }
490
+ /**
491
+ * install 前置探测(E 高-1):库已初始化(statGuard + schema_version)**且存在真实成功证据**。
492
+ * ⚠️ 判据是 `range_status='complete'` 或 `last_synced_at` 非空 —— 不是「sync_state 里有行」:
493
+ * 引擎在**任何窗口执行之前**就 markPending 落行(runWindowed/planRotation/runSnapshot),
494
+ * 所以一个全败的 run 同样留下 pending 行。按「有行」放行等于把调度器装在一个从未成功
495
+ * 同步过的库上,探测名不副实(且 hint 会劝用户「先跑通一次」却已经被放行)。
496
+ * 冷却行(`__ratelimit__:` 前缀)本就不是任务行,按前缀排除。
497
+ */
498
+ async function probeSynced(config, path) {
499
+ const guarded = statGuard(path);
500
+ if (guarded !== null)
501
+ return guarded;
502
+ const opened = await openRo(config);
503
+ if (opened.code !== undefined || !opened.store)
504
+ return opened.code ?? 1;
505
+ const store = opened.store;
506
+ try {
507
+ const states = await listWatermarks(store);
508
+ const hasSuccess = [...states.values()].some((s) => !s.dataset.startsWith(RATELIMIT_PREFIX)
509
+ && (s.rangeStatus === 'complete' || s.lastSyncedAt !== null));
510
+ if (!hasSuccess) {
511
+ return fail({
512
+ code: 'sync_not_run', kind: 'sync_not_run', retryable: false,
513
+ message: '尚未成功同步过任何任务(sync_state 无 range_status=complete 且无 last_synced_at 的记录)',
514
+ hint: '安装调度前请先跑通一次同步:qiyu sync run',
515
+ });
516
+ }
517
+ return null;
518
+ }
519
+ finally {
520
+ await store.close();
521
+ }
522
+ }
523
+ /** 命令行形态(输出用):argv 以空格连接(含空格的部分已按 shellQuote 引住)。 */
524
+ const commandText = (argv) => argv.join(' ');
525
+ async function syncInstall(argv) {
526
+ const help = subHelp(argv);
527
+ if (help !== null)
528
+ return help;
529
+ let parsed;
530
+ try {
531
+ parsed = parseSubFlags(argv, INSTALL_VALUE_FLAGS, INSTALL_BOOL_FLAGS);
532
+ }
533
+ catch (e) {
534
+ return usageFail(e.message);
535
+ }
536
+ if (parsed.rest.length > 0)
537
+ return usageFail(`未知参数:${parsed.rest.join(' ')}`);
538
+ // G1:--pretty 已实现(原拒绝点在 parseSubFlags 的 throw)。
539
+ if (parsed.flags.has('--pretty'))
540
+ setPretty(true);
541
+ const schedule = parsed.values['--schedule'];
542
+ if (schedule === undefined) {
543
+ return usageFail('缺少 --schedule CRON(5 段:分 时 日 月 周)', '例如:qiyu sync install --schedule "*/30 * * * *"');
544
+ }
545
+ const yes = parsed.flags.has('--yes');
546
+ let platform;
547
+ try {
548
+ platform = currentPlatform();
549
+ }
550
+ catch (e) {
551
+ return usageFail(e.message);
552
+ }
553
+ // 前置探测(dry-run 与 --yes 都查:dry-run 应当预测成功)
554
+ let config;
555
+ let path;
556
+ let backend;
557
+ try {
558
+ const r = resolveConfig({ db: parsed.values['--db'], profile: parsed.values['--profile'], backend: parsed.values['--backend'] });
559
+ config = r.config;
560
+ path = r.path;
561
+ backend = r.backend;
562
+ }
563
+ catch (e) {
564
+ return usageFail(e.message);
565
+ }
566
+ const probe = await probeSynced(config, path);
567
+ if (probe !== null)
568
+ return probe;
569
+ // 计划生成(cron 解析 / 平台映射失败 → usage)
570
+ let plan;
571
+ try {
572
+ const entry = process.argv[1];
573
+ plan = planInstall(platform, schedule, {
574
+ home: homedir(),
575
+ exec: entry ? [process.execPath, entry] : ['qiyu'],
576
+ // 修复批 4 #4 + 批 6 #1:调度命令与前置探测必须是**同一个库** —— 显式 flag 原样
577
+ // 透传(批 4);env 派生的存储定位把解析结果固化为稳定参数(批 6,launchd/schtasks
578
+ // 不继承 shell 环境变量,env 派生不固化会让调度任务跑默认库)。配置文件 store.path
579
+ // 与内置默认值仍不固化(调度任务读得到 HOME 下的配置文件;默认值固化会引入漂移)。
580
+ storeArgs: storeArgsFor(parsed, { path, backend }),
581
+ });
582
+ }
583
+ catch (e) {
584
+ return usageFail(e.message);
585
+ }
586
+ // 部署事实(批 6 #1 连带,写进 dry-run 与 --yes 两路输出):调度条目不继承 shell 环境。
587
+ const envNote = '调度条目不继承你的 shell 环境:若凭证走 QIYU_APP_KEY / QIYU_APP_SECRET,'
588
+ + '请确认其对该调度上下文可用(launchd 的用户域不含 shell rc 变量)——本条目不写入任何凭证。';
589
+ if (!yes) {
590
+ return ok({
591
+ platform, schedule, dry_run: true,
592
+ entries: plan.entries,
593
+ commands: plan.commands.map((c) => ({ command: commandText(c), executed: false, ok: null, error: null })),
594
+ notes: [...plan.notes, envNote, '这是 dry-run:未写入任何文件、未执行任何命令。加 --yes 实际安装。'],
595
+ });
596
+ }
597
+ // --yes:写文件 + 执行命令(逐条记结果,失败不中断、退出码如实报 1)
598
+ const installed = [];
599
+ for (const e of plan.entries) {
600
+ mkdirSync(dirname(e.path), { recursive: true });
601
+ writeFileSync(e.path, e.content);
602
+ installed.push(e.path);
603
+ }
604
+ const cmdResults = [];
605
+ for (const c of plan.commands) {
606
+ try {
607
+ runScheduleCommand(c);
608
+ cmdResults.push({ command: commandText(c), executed: true, ok: true, error: null });
609
+ }
610
+ catch (e) {
611
+ cmdResults.push({ command: commandText(c), executed: true, ok: false, error: e instanceof Error ? e.message : String(e) });
612
+ }
613
+ }
614
+ const code = ok({
615
+ platform, schedule, dry_run: false,
616
+ installed, commands: cmdResults, notes: [...plan.notes, envNote],
617
+ });
618
+ return cmdResults.some((c) => !c.ok) ? 1 : code;
619
+ }
620
+ async function syncUninstall(argv) {
621
+ const help = subHelp(argv);
622
+ if (help !== null)
623
+ return help;
624
+ let parsed;
625
+ try {
626
+ parsed = parseSubFlags(argv, [], UNINSTALL_BOOL_FLAGS);
627
+ }
628
+ catch (e) {
629
+ return usageFail(e.message);
630
+ }
631
+ if (parsed.rest.length > 0)
632
+ return usageFail(`未知参数:${parsed.rest.join(' ')}`);
633
+ // G1:--pretty 已实现(原拒绝点在 parseSubFlags 的 throw)。
634
+ if (parsed.flags.has('--pretty'))
635
+ setPretty(true);
636
+ const yes = parsed.flags.has('--yes');
637
+ let platform;
638
+ try {
639
+ platform = currentPlatform();
640
+ }
641
+ catch (e) {
642
+ return usageFail(e.message);
643
+ }
644
+ const plan = planUninstall(platform, { home: homedir() });
645
+ if (!yes) {
646
+ return ok({
647
+ platform, dry_run: true,
648
+ remove: plan.remove,
649
+ commands: plan.commands.map((c) => ({ command: commandText(c), executed: false, ok: null, error: null })),
650
+ notes: [...plan.notes, '这是 dry-run:未删除任何文件、未执行任何命令。加 --yes 实际卸载。'],
651
+ });
652
+ }
653
+ const anyInstalled = plan.remove.some((r) => r.exists);
654
+ const cmdResults = [];
655
+ if (anyInstalled) {
656
+ // 卸载次序:先停调度器(unload/disable),再删文件
657
+ for (const c of plan.commands) {
658
+ try {
659
+ runScheduleCommand(c);
660
+ cmdResults.push({ command: commandText(c), executed: true, ok: true, error: null });
661
+ }
662
+ catch (e) {
663
+ cmdResults.push({ command: commandText(c), executed: true, ok: false, error: e instanceof Error ? e.message : String(e) });
664
+ }
665
+ }
666
+ }
667
+ const removed = [];
668
+ const absent = [];
669
+ for (const r of plan.remove) {
670
+ rmSync(r.path, { force: true });
671
+ if (r.exists)
672
+ removed.push(r.path);
673
+ else
674
+ absent.push(r.path);
675
+ }
676
+ const code = ok({
677
+ platform, dry_run: false, removed,
678
+ absent: absent.length > 0 ? absent : undefined,
679
+ commands: cmdResults, notes: anyInstalled ? plan.notes : ['未安装(无条目文件):未执行任何命令。'],
680
+ });
681
+ return cmdResults.some((c) => !c.ok) ? 1 : code;
682
+ }
683
+ export async function syncCommand(argv) {
684
+ setPretty(false); // G1:每条命令入口重置输出格式 —— 同一进程内多次 run(测试)不残留上一条命令的开关。
685
+ const [sub, ...rest] = argv;
686
+ if (sub === undefined || sub === '--help' || sub === '-h') {
687
+ const extra = rest.filter((a) => !KNOWN.has(a));
688
+ if (extra.length > 0)
689
+ return usageFail(`未知参数:${extra.join(' ')}。--help 不接受额外参数`);
690
+ process.stdout.write(USAGE);
691
+ return 0;
692
+ }
693
+ // G1:--pretty 是输出开关,必须写在具体子命令之后(`sync status --pretty`)。
694
+ if (sub === '--pretty') {
695
+ const unknown = rest.filter((a) => a.startsWith('-') && !KNOWN.has(a));
696
+ const positional = rest.filter((a) => !a.startsWith('-'));
697
+ if (unknown.length + positional.length > 0) {
698
+ return usageFail(`未知参数:${[...unknown, ...positional].join(' ')}。--pretty 不接受额外参数`);
699
+ }
700
+ if (rest.includes('--help') || rest.includes('-h')) {
701
+ process.stdout.write(USAGE);
702
+ return 0;
703
+ }
704
+ return usageFail(prettyAfterSubcommand('sync'));
705
+ }
706
+ if (sub !== 'tasks' && sub !== 'run' && sub !== 'status' && sub !== 'verify'
707
+ && sub !== 'install' && sub !== 'uninstall') {
708
+ return usageFail(`未知子命令:${sub}\n可用子命令:tasks、run、status、verify、install、uninstall`);
709
+ }
710
+ if (sub === 'run')
711
+ return runSyncRun(rest);
712
+ if (sub === 'status')
713
+ return syncStatus(rest);
714
+ if (sub === 'verify')
715
+ return syncVerify(rest);
716
+ if (sub === 'install')
717
+ return syncInstall(rest);
718
+ if (sub === 'uninstall')
719
+ return syncUninstall(rest);
720
+ // —— tasks ——
721
+ if (rest.includes('--help') || rest.includes('-h')) {
722
+ const rawRest = rest.filter((a) => !KNOWN.has(a));
723
+ if (rawRest.length > 0)
724
+ return usageFail(`未知参数:${rawRest.join(' ')}`);
725
+ process.stdout.write(USAGE);
726
+ return 0;
727
+ }
728
+ // G1:--pretty 已实现 —— 原拒绝点开启缩进输出。
729
+ if (rest.includes('--pretty'))
730
+ setPretty(true);
731
+ try {
732
+ const parsed = parseSubFlags(rest, TASKS_VALUE_FLAGS);
733
+ if (parsed.rest.length > 0)
734
+ return usageFail(`未知参数:${parsed.rest.join(' ')}`);
735
+ }
736
+ catch (e) {
737
+ return usageFail(e.message);
738
+ }
739
+ // tasks:只暴露声明元数据,函数字段(fetch/write/enrich)不进 JSON。
740
+ // sensitive_columns(D 高-1/F 中-2):按 tableByName 取该表的 PII 列清单 —— 这是
741
+ // `sensitive: true` 标记的**运行时出口**(E 的 `db describe` 之外,Agent 现在就能
742
+ // 从 sync tasks 知道哪些列不该 SELECT *)。闭集来自 schema.ts 的列声明,不按名称泛化。
743
+ const tasks = SYNC_TASKS.map((t) => ({
744
+ id: t.id,
745
+ table: t.table,
746
+ kind: t.kind,
747
+ watermark: { field: t.watermark.field, initial: t.watermark.initial },
748
+ maxWindowDays: t.maxWindowDays ?? null,
749
+ overlapDays: t.overlapDays ?? null,
750
+ primaryKey: t.primaryKey,
751
+ sensitive_columns: (tableByName(t.table)?.columns ?? [])
752
+ .filter((c) => c.sensitive === true).map((c) => c.name),
753
+ }));
754
+ const unsupported = UNSUPPORTED_DATASETS.map((u) => ({ id: u.id, unsupported: u.reason }));
755
+ return ok({ tasks, unsupported });
756
+ }
757
+ export { SYNC_RUN_USAGE };