qiyu-cli 0.0.0-stage → 0.2.0

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 +464 -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 +863 -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 +18 -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 +336 -0
  201. package/dist/skill/install.js +1202 -0
  202. package/dist/skill/paths.js +343 -0
  203. package/dist/skill/qiyu/SKILL.md +86 -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,503 @@
1
+ // src/commands/db.ts —— E 组查询命令骨架;Task 6:`db tables`(spec §8.1),
2
+ // Task 7:`db describe`(spec §8.2)。
3
+ //
4
+ // 形态沿 store.ts / sync.ts:parseStoreFlags(值位守卫)→ usageFail/fail 双通道 →
5
+ // 查询层统一错误出口 thrownToQueryExit。
6
+ //
7
+ // 三条硬约束:
8
+ // · 所有查询走 `query/sandbox.ts` 的三层只读沙箱(spec §5.1)——本文件不直接
9
+ // 触碰 DuckDB 驱动(驱动包名字面量禁止出现在 src/commands/,layering 红线);
10
+ // · `db tables` 的清单以 `TABLES` 为权威(spec §8.1):声明有而库中无的表**不出现**
11
+ // 在 `data.tables`(`rows` 恒为真实 COUNT,不编造),与「库中有而声明无」一样
12
+ // 只进 `meta.warnings`(controller 裁决 R4);
13
+ // · `time_range` 的 min/max **所有 kind** 都经 `msToShanghaiIso` 输出 `+08:00`
14
+ // 形态(裁决 R1):iso-day/iso-instant 的 MIN/MAX 是 ISO 字符串,epoch-ms 是
15
+ // 数字字符串(BIGINT 经 JSON 层),三者统一为同一形态。
16
+ // · `db describe` 的列清单同样以 `TABLES` 为权威;声明有而库中无的表**仍输出声明
17
+ // 元数据**(`row_count`/`time_range` 为 null + warning,裁决 R5)——Agent 需要知道
18
+ // 该表应该有什么列,才能判断是没同步还是没建库。
19
+ import { statSync } from 'node:fs';
20
+ import { resolveStoreConfig, currentStoreEnv } from '../store/config.js';
21
+ import { openSandbox } from '../query/sandbox.js';
22
+ import { timeShapeClauses } from '../query/time-shape.js';
23
+ import { suggestNames, thrownToQueryExit } from '../query/errors.js';
24
+ import { TABLES, tableByName } from '../store/schema.js';
25
+ import { msToShanghaiIso } from '../core/time.js';
26
+ import { ok, fail, usageFail, sanitizeControlChars, describeArgs, setPretty } from '../output.js';
27
+ import { parseStoreFlags } from './store-flags.js';
28
+ import { GLOBAL_FLAGS, GLOBAL_FLAG_NAMES, prettyAfterSubcommand, REJECTED_FLAGS, STORE_FLAGS } from './spec-types.js';
29
+ /**
30
+ * 命令契约(F 组 D4):`skill check` 据此判断 skill 正文里的 `qiyu db …` 是否真的存在。
31
+ * `flags` 是**完整接受集**(含全局 flag),`--pretty` 同时在 `rejected` 里。
32
+ * 值位解析走共享的 `parseStoreFlags`(它从 `STORE_FLAGS` 派生接受集),与这里同源。
33
+ */
34
+ export const DB_SPECS = [
35
+ {
36
+ path: ['db', 'tables'],
37
+ flags: [...GLOBAL_FLAGS, ...STORE_FLAGS],
38
+ positionals: [],
39
+ rejected: REJECTED_FLAGS,
40
+ },
41
+ {
42
+ path: ['db', 'describe'],
43
+ flags: [...GLOBAL_FLAGS, ...STORE_FLAGS],
44
+ positionals: [{ name: '表', domain: 'tables' }],
45
+ rejected: REJECTED_FLAGS,
46
+ },
47
+ ];
48
+ const USAGE = `用法:qiyu db <子命令> [参数]
49
+
50
+ 子命令:
51
+ db tables [--db <path>] [--profile <name>] [--backend <name>]
52
+ 列出库中全部表:行数、粒度、时间范围、PII 列
53
+ db describe <表> [--db <path>] [--profile <name>] [--backend <name>]
54
+ 查看单表列定义
55
+
56
+ 存储定位:--db / --profile / --backend(store 命令同族)。
57
+ `;
58
+ const KNOWN = new Set(GLOBAL_FLAG_NAMES);
59
+ /** PII 提示(设计稿 §6.5 要求 `db tables` / `db describe` 必须携带)。 */
60
+ const PII_NOTICE = '本数据库包含客户 PII;不要将其写入日志或对外报表';
61
+ /**
62
+ * 只读命令的库前置检查(ENOENT / 非普通文件 / 权限三分 → 退出码,否则 null)。
63
+ * ⚠️ 与 sync.ts 的私有 statGuard 同款,但**独立落点**:brief 指定 E 族单一落点
64
+ * (本函数由 db.ts 导出给 query/stats 复用,避免三份拷贝漂移;不为它抽独立模块,
65
+ * 两处足够小,YAGNI)。
66
+ * hint 统一指 `qiyu store init`(spec §九)。
67
+ */
68
+ export function statGuard(path) {
69
+ let st;
70
+ try {
71
+ st = statSync(path);
72
+ }
73
+ catch (e) {
74
+ if (e.code === 'ENOENT') {
75
+ return fail({
76
+ code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
77
+ message: `数据库文件不存在:${path}`,
78
+ hint: '数据库尚未初始化。请先运行:qiyu store init',
79
+ });
80
+ }
81
+ return fail({
82
+ code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
83
+ message: `无法访问 ${path}:${e instanceof Error ? e.message : String(e)}`,
84
+ hint: '请检查路径权限(只读命令不需要写权限)',
85
+ });
86
+ }
87
+ if (!st.isFile()) {
88
+ return fail({
89
+ code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
90
+ message: `不是普通文件:${path}`,
91
+ hint: '--db 指向的不是普通文件,请给出 .duckdb 数据库文件路径',
92
+ });
93
+ }
94
+ return null;
95
+ }
96
+ /** 表的 PII 列名(`sensitive: true`,保持声明顺序)——`TABLES` 是唯一权威。 */
97
+ function piiColumnsOf(t) {
98
+ return t.columns.filter((c) => c.sensitive === true).map((c) => c.name);
99
+ }
100
+ /**
101
+ * 时间列的**约定形态**(可注入 SQL 片段,`timeRangeOf` 与 `dirtyTimeValues` 共用同一份
102
+ * ——两处口径一旦分叉,就会出现「算极值时排除、计数时不排除」这种自相矛盾的状态)。
103
+ *
104
+ * 实现与 `query/table-query.ts` 共用 `query/time-shape.ts` 的同一函数 —— 口径由构造保证,
105
+ * 不再靠「逐字一致」的注释与字符串相等测试(同一条 README 承诺:「脏值不进 time_range」;
106
+ * 两处分叉的话,同一条脏库会在 `db tables` 被排除、在 `query --table` 被当成覆盖范围)。
107
+ * 具体判据与实测约束(F3/F5/gap 2)见该模块头注释。
108
+ *
109
+ * 两端都锚定(CodeRabbit 终审 minor):只锚开头会放过 `'2026-10-12garbage'`(它字典序上
110
+ * `g` > `T`,反而赢下 MAX)与只有日期的 `'2026-10-13'`(`msToShanghaiIso` 按 UTC 解析,
111
+ * 输出偏 8 小时)。形态与写路径逐字对应:
112
+ * · iso-day:`shanghaiDayIso` → `YYYY-MM-DDT16:00:00.000Z`(上海日零点的 UTC 形态);
113
+ * · iso-instant:`new Date(ms).toISOString()` → `YYYY-MM-DDTHH:MM:SS.mmmZ`。
114
+ * 兼容旧值:允许省略毫秒(`.000` 之外的零毫秒形态在库里也存在)。
115
+ */
116
+ function shapeSqlOf(kind, col) {
117
+ return timeShapeClauses(kind, col);
118
+ }
119
+ /**
120
+ * 单表时间范围(spec §8.1 / §四)。
121
+ * iso-day / iso-instant:列是 ISO 字符串 → 先按约定形态过滤(见下)再 MIN/MAX;
122
+ * epoch-ms:列是数字字符串 → 先 TRY_CAST 成 BIGINT 再取极值(非数字值不炸、按 NULL 跳过)。
123
+ * 空表(或全 NULL)→ null;非空则两端都过 `msToShanghaiIso`(裁决 R1)。
124
+ *
125
+ * ⚠️ ISO 形态过滤(正确性 P1):脏值(`not-a-date`)会在 VARCHAR 上**赢下** MIN/MAX
126
+ * (字典序上 `n` > `2`),而 `msToShanghaiIso` 对解析不了的值原样回显 —— 于是
127
+ * `time_range.max` 输出一个根本不是时间的字符串。契约要求它是上海 ISO,所以先按
128
+ * 约定形态筛(见 `shapeSqlOf`),脏值不进极值;数量由 `dirtyTimeValues` 单独查,
129
+ * 由调用方进 warnings(不得静默 —— 库漂移/坏数据是 README 承诺要报警的状态)。
130
+ */
131
+ async function timeRangeOf(session, t) {
132
+ const tc = t.timeColumn;
133
+ if (tc === undefined)
134
+ return null;
135
+ const col = `"${tc.name}"`;
136
+ // 形态判据只用于 MIN/MAX 的候选集,不改变列本身的语义(值仍是原样输出的)。
137
+ // ⚠️ 用 `regexp_matches`,**不要**用 `~` 运算符:实测(DuckDB 1.5.6-r.1)`~` 对
138
+ // `'2026-10-13T…' ~ '^2026'` 也返回 false —— 它不是正则匹配,会把所有行都滤掉。
139
+ const shape = shapeSqlOf(tc.kind, col);
140
+ // ⚠️ **三种形态一律按解析后的时刻取极值**(正确性审查 F1/F2):iso-day 的无毫秒形态
141
+ // `…T16:00:00Z` 在字典序上大于同刻的 `…T16:00:00.000Z`,iso-instant 的 `+08:00` 写法
142
+ // 与 `Z` 写法字典序与时间序相反 —— `MIN/MAX(原始串)` 都会取错那一端。
143
+ // `arg_min/arg_max(col, 时刻)` 按时刻排序、**返回原始字符串**(`msToShanghaiIso` 能
144
+ // 解析全部写法)。epoch-ms 用 BIGINT 极值。
145
+ const agg = tc.kind === 'epoch-ms'
146
+ ? `MIN(TRY_CAST(${col} AS BIGINT)) AS mn, MAX(TRY_CAST(${col} AS BIGINT)) AS mx`
147
+ : `arg_min(${col}, TRY_CAST(${col} AS TIMESTAMPTZ)) AS mn, `
148
+ + `arg_max(${col}, TRY_CAST(${col} AS TIMESTAMPTZ)) AS mx`;
149
+ const where = ` WHERE ${shape.join(' AND ')}`;
150
+ const r = await session.run(`SELECT ${agg} FROM "${t.name}"${where}`);
151
+ const row = r.rows[0] ?? {};
152
+ if (row.mn === null || row.mn === undefined || row.mx === null || row.mx === undefined)
153
+ return null;
154
+ return {
155
+ min: msToShanghaiIso(row.mn),
156
+ max: msToShanghaiIso(row.mx),
157
+ };
158
+ }
159
+ /**
160
+ * 时间列里不符合约定形态的非空值计数(正确性 P1)。
161
+ * epoch-ms 用 `TRY_CAST` 判(非数字即脏);iso 两形态用与 `timeRangeOf` 同一份形态。
162
+ * 0 = 干净,不产生任何警告。
163
+ */
164
+ async function dirtyTimeValues(session, t) {
165
+ const tc = t.timeColumn;
166
+ if (tc === undefined)
167
+ return 0;
168
+ const col = `"${tc.name}"`;
169
+ const shape = shapeSqlOf(tc.kind, col);
170
+ // 脏值 = 非空且不满足全部形态条件。
171
+ // ⚠️ 必须 COALESCE(CodeRabbit 复审 minor,实测):epoch-ms 的非数字值让 `TRY_CAST`
172
+ // 为 NULL,`NOT (NULL AND NULL)` 仍是 NULL → WHERE 把该行静默丢掉,脏值计数为 0、
173
+ // 警告也不出现。COALESCE(…, false) 把「无法判定」归为「不符合」。
174
+ const bad = `NOT COALESCE((${shape.join(' AND ')}), false)`;
175
+ const r = await session.run(`SELECT COUNT(*) AS n FROM "${t.name}" WHERE ${col} IS NOT NULL AND ${bad}`);
176
+ return Number((r.rows[0] ?? {}).n);
177
+ }
178
+ /** 脏时间值的公共警告文案(tables 与 describe 同一句话)。 */
179
+ function dirtyTimeWarning(table, column, n) {
180
+ return `表 ${table} 的时间列 ${column} 有 ${n} 个值不符合约定形态(已从 time_range 中排除)`
181
+ + '——可能来自旧版 CLI、外部工具或库损坏;用 `qiyu query --sql` 单独查看它们以确认成因';
182
+ }
183
+ /**
184
+ * 打开「已通过前置检查」的只读沙箱会话(**E 族三个命令共用**):
185
+ * resolveStoreConfig → statGuard → openSandbox → `schema_version` 探测。
186
+ *
187
+ * 返回 `{ exit }` 表示前置检查已产出退出码(调用方直接返回它,不做任何清理);
188
+ * 返回 `{ session }` 时**所有权归调用方**,必须 `finally session.close()`。
189
+ * ⚠️ `schema_version` 探测的失败/缺表分支在这里就把会话关掉——调用方拿不到
190
+ * session,不能指望它的 finally。
191
+ *
192
+ * ⚠️ 落点就在本文件、由 db 导出给 query/stats(与 `statGuard` 同一放宽口径):
193
+ * 这三条命令的「库结构校验」必须逐字一致——探测口径(`table_schema='main'`)、
194
+ * 文案与 hint 任何一处漂移都会让 Agent 在不同命令上得到互相矛盾的解释。
195
+ * 此前 query/stats 各自内联了一份拷贝,已合并到此处(架构审查 Important #2)。
196
+ */
197
+ export async function openGuardedSession(flags) {
198
+ let config;
199
+ try {
200
+ config = resolveStoreConfig({
201
+ flags: { db: flags.db, profile: flags.profile, backend: flags.backend },
202
+ env: currentStoreEnv(),
203
+ }).config;
204
+ }
205
+ catch (e) {
206
+ return { exit: usageFail(sanitizeControlChars(e.message)) };
207
+ }
208
+ const guarded = statGuard(config.path);
209
+ if (guarded !== null)
210
+ return { exit: guarded };
211
+ let session;
212
+ try {
213
+ session = await openSandbox(config);
214
+ }
215
+ catch (e) {
216
+ return { exit: thrownToQueryExit(e, TABLES) };
217
+ }
218
+ try {
219
+ // 库结构校验(spec §十一「库不存在/缺表 → store_not_initialized、退出码 1」)。
220
+ // 口径与实际表集查询一致:限定 table_schema='main'(别库同名表不算数)。
221
+ // ⚠️ 成因分形(sync.ts openRo / store.ts 同款):「有表但无 schema_version」是**他人库**
222
+ // —— store init 会再次拒绝(duckdb.ts init 的他人库防线),无条件引导过去就是
223
+ // store init → db tables 死循环;「零表」才是「init 可补」的成因。
224
+ const tables = await session.run("SELECT table_name FROM information_schema.tables WHERE table_schema='main'");
225
+ const names = tables.rows.map((r) => String(r.table_name));
226
+ if (!names.includes('schema_version')) {
227
+ await session.close();
228
+ return {
229
+ exit: fail({
230
+ code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
231
+ message: `数据库结构不完整(缺表):${config.path}`,
232
+ hint: names.length > 0
233
+ ? '目标数据库不是本 CLI 创建的,请换 --db 路径'
234
+ : '空库(无任何表)。请先运行:qiyu store init',
235
+ }),
236
+ };
237
+ }
238
+ }
239
+ catch (e) {
240
+ await session.close();
241
+ return { exit: thrownToQueryExit(e, TABLES) };
242
+ }
243
+ return { session, dbPath: config.path };
244
+ }
245
+ async function dbTables(argv) {
246
+ // 子命令级次序沿 store.ts:--help 分流 → --pretty 开启缩进(G1) → parseStoreFlags → 未知参数。
247
+ if (argv.includes('--help') || argv.includes('-h')) {
248
+ const rawRest = argv.filter((a) => !KNOWN.has(a));
249
+ if (rawRest.length > 0)
250
+ return usageFail(`未知参数:${rawRest.join(' ')}`);
251
+ process.stdout.write(USAGE);
252
+ return 0;
253
+ }
254
+ // G1:--pretty 已实现 —— 原拒绝点开启缩进输出(次序不变:help → 这里 → 值位解析)。
255
+ if (argv.includes('--pretty'))
256
+ setPretty(true);
257
+ let flags;
258
+ try {
259
+ flags = parseStoreFlags(argv);
260
+ }
261
+ catch (e) {
262
+ return usageFail(sanitizeControlChars(e.message));
263
+ }
264
+ if (flags.rest.length > 0)
265
+ return usageFail(`未知参数:${flags.rest.join(' ')}`);
266
+ const opened = await openGuardedSession(flags);
267
+ if ('exit' in opened)
268
+ return opened.exit;
269
+ const session = opened.session;
270
+ try {
271
+ // 实际表集 → 与声明比对(spec §8.1「声明与实况的差异不得静默」)。
272
+ const actual = await session.run("SELECT table_name FROM information_schema.tables WHERE table_schema='main'");
273
+ const actualNames = actual.rows.map((r) => String(r.table_name));
274
+ const actualSet = new Set(actualNames);
275
+ const declaredSet = new Set(TABLES.map((t) => t.name));
276
+ const warnings = [];
277
+ const declaredMissing = TABLES.map((t) => t.name).filter((n) => !actualSet.has(n));
278
+ if (declaredMissing.length > 0) {
279
+ // ⚠️ 不得承诺 store init 一定能修(审查 Important #1):init 只重放
280
+ // `version > MAX(version)` 的迁移,已迁移到最新版后被 DROP 的表**不会**被
281
+ // 重建(迁移已跳过,返回 ok 而表仍缺)——那是「成功但无效」的修复。
282
+ warnings.push(`声明有而库中无:${declaredMissing.join('、')}。`
283
+ + '这些表不出现在 tables 中。若为建库未完成(迁移未跑完),运行 qiyu store init 可补建缺失的迁移;'
284
+ + '若迁移已完成而表被删或损坏,store init 不会重建该表,重新同步也只会写入失败(缺表)'
285
+ + '——需重建库(删除库文件后重新 qiyu store init 并重新同步)');
286
+ }
287
+ const undeclared = actualNames.filter((n) => !declaredSet.has(n)).sort();
288
+ if (undeclared.length > 0) {
289
+ warnings.push(`库中有而声明无:${undeclared.join('、')}。`
290
+ + '这些表没有元数据声明(可能来自旧版 CLI 或其他工具),不出现在 tables 中');
291
+ }
292
+ // 实际列集一次查全库(25 次往返 → 1 次):时间列被删的表不能让 timeRangeOf 的
293
+ // `MIN("c")` 在 prepare 期抛 Binder Error 把整命令打成退出码 2(Task 7 审查
294
+ // Important #1)——缺列降级为 time_range null + warning。
295
+ const colRows = await session.run("SELECT table_name, column_name FROM information_schema.columns WHERE table_schema='main'");
296
+ const columnsOf = new Map();
297
+ for (const row of colRows.rows) {
298
+ const tableName = String(row.table_name);
299
+ const columnName = String(row.column_name);
300
+ const set = columnsOf.get(tableName);
301
+ if (set === undefined)
302
+ columnsOf.set(tableName, new Set([columnName]));
303
+ else
304
+ set.add(columnName);
305
+ }
306
+ // 逐表:行数 + 时间范围;清单与顺序以 TABLES 为权威(裁决 R4:缺表的表整条跳过)。
307
+ const tables = [];
308
+ for (const t of TABLES) {
309
+ if (!actualSet.has(t.name))
310
+ continue;
311
+ const r = await session.run(`SELECT COUNT(*) AS n FROM "${t.name}"`);
312
+ // ⚠️ COUNT 是 BIGINT,经 getRowObjectsJson() 是**字符串** —— 必须 Number() 收敛。
313
+ const rows = Number((r.rows[0] ?? {}).n);
314
+ let timeRange = null;
315
+ const tc = t.timeColumn;
316
+ // 逐表列核对(审查 I-3):README 承诺「缺表/缺列/多列逐条进 warnings,不静默」,
317
+ // 而 describe 才有的逐列核对在 tables 清单里缺失就是静默漂移。列集已在上面
318
+ // 一次查全库(columnsOf),这里只做集合差,不加往返。
319
+ const declaredCols = new Set(t.columns.map((c) => c.name));
320
+ const actualCols = columnsOf.get(t.name) ?? new Set();
321
+ // 时间列缺了由下面那条专门警告说明(它还要解释 time_range 为何置 null),
322
+ // 这里排除它,避免同一事实说两遍。
323
+ const missingCols = [...declaredCols].filter((n) => !actualCols.has(n) && n !== t.timeColumn?.name);
324
+ const extraCols = [...actualCols].filter((n) => !declaredCols.has(n)).sort();
325
+ if (missingCols.length > 0 || extraCols.length > 0) {
326
+ const parts = [];
327
+ if (extraCols.length > 0)
328
+ parts.push(`多列 ${extraCols.join('、')}`);
329
+ if (missingCols.length > 0)
330
+ parts.push(`少列 ${missingCols.join('、')}`);
331
+ warnings.push(`表 ${t.name} 实际${parts.join('、')}——可能来自旧版 CLI 或库损坏`);
332
+ }
333
+ if (tc !== undefined) {
334
+ if (actualCols.has(tc.name)) {
335
+ timeRange = await timeRangeOf(session, t);
336
+ const dirty = await dirtyTimeValues(session, t);
337
+ if (dirty > 0)
338
+ warnings.push(dirtyTimeWarning(t.name, tc.name, dirty));
339
+ }
340
+ else {
341
+ warnings.push(`表 ${t.name} 缺少时间列 ${tc.name}(可能来自旧版 CLI 或库损坏),time_range 置 null`);
342
+ }
343
+ }
344
+ tables.push({
345
+ name: t.name,
346
+ rows,
347
+ grain: t.grain,
348
+ time_range: timeRange,
349
+ pii_columns: piiColumnsOf(t),
350
+ });
351
+ }
352
+ return ok({ tables }, { notice: PII_NOTICE, warnings });
353
+ }
354
+ catch (e) {
355
+ return thrownToQueryExit(e, TABLES);
356
+ }
357
+ finally {
358
+ await session.close();
359
+ }
360
+ }
361
+ /** 单列的对外形态(spec §8.2):恰好七个键,缺省字段显式 `null`(`sensitive` 缺省 false)。 */
362
+ function describeColumn(c) {
363
+ return {
364
+ name: c.name,
365
+ type: c.type,
366
+ nullable: c.nullable,
367
+ sensitive: c.sensitive ?? false,
368
+ unit: c.unit ?? null,
369
+ observed_enum: c.observed_enum ?? null,
370
+ note: c.note ?? null,
371
+ };
372
+ }
373
+ async function dbDescribe(argv) {
374
+ // 子命令级次序沿 dbTables:--help 分流 → --pretty 开启缩进(G1) → parseStoreFlags → 位置参数。
375
+ if (argv.includes('--help') || argv.includes('-h')) {
376
+ const rawRest = argv.filter((a) => !KNOWN.has(a));
377
+ if (rawRest.length > 0)
378
+ return usageFail(`未知参数:${rawRest.join(' ')}`);
379
+ process.stdout.write(USAGE);
380
+ return 0;
381
+ }
382
+ // G1:--pretty 已实现 —— 原拒绝点开启缩进输出(次序不变:help → 这里 → 值位解析)。
383
+ if (argv.includes('--pretty'))
384
+ setPretty(true);
385
+ let flags;
386
+ try {
387
+ flags = parseStoreFlags(argv);
388
+ }
389
+ catch (e) {
390
+ return usageFail(sanitizeControlChars(e.message));
391
+ }
392
+ // 未知 flag(`--bogus`)会落进 rest —— 先按 `-` 前缀挑出来,避免被当成表名。
393
+ const flagish = flags.rest.filter((a) => a.startsWith('-'));
394
+ if (flagish.length > 0)
395
+ return usageFail(`未知参数:${flagish.join(' ')}`);
396
+ if (flags.rest.length === 0) {
397
+ return usageFail(`缺少表名:请给 db describe <表>\n可用表:${TABLES.map((t) => t.name).join('、')}`);
398
+ }
399
+ if (flags.rest.length > 1)
400
+ return usageFail(`未知参数:${flags.rest.slice(1).join(' ')}`);
401
+ // spec §8.2「未知 → usage + 候选」:闭集校验先于一切 I/O(不打开库就知道表名拼错)。
402
+ // 候选来自 `TABLES`(前缀/编辑距离,大小写不敏感),不裸透 DuckDB 英文原文。
403
+ const name = sanitizeControlChars(flags.rest[0]);
404
+ const table = tableByName(name);
405
+ if (table === undefined) {
406
+ const candidates = suggestNames(name, TABLES.map((t) => t.name));
407
+ return usageFail(`未知表:${describeArgs([name])}`, candidates.length > 0 ? `候选:${candidates.join('、')}` : '用 `qiyu db tables` 查看可用表');
408
+ }
409
+ const opened = await openGuardedSession(flags);
410
+ if ('exit' in opened)
411
+ return opened.exit;
412
+ const session = opened.session;
413
+ try {
414
+ // 表名来自 `TABLES` 闭集(代码内常量),拼进字面量安全;用户输入只用于上面的闭集查找。
415
+ const present = (await session.run(`SELECT 1 FROM information_schema.tables WHERE table_schema='main' AND table_name='${table.name}'`))
416
+ .rows.length > 0;
417
+ const warnings = [];
418
+ let rowCount = null;
419
+ let timeRange = null;
420
+ if (!present) {
421
+ // R5:声明有但库中无 → 仍输出声明元数据,不报错(Agent 靠列清单判断
422
+ // 「没同步」还是「没建库」)。此时 row_count/time_range 无从得知,置 null。
423
+ warnings.push(`表 ${table.name} 在库中不存在(未同步或未建库);以下为声明元数据`);
424
+ }
425
+ else {
426
+ const r = await session.run(`SELECT COUNT(*) AS n FROM "${table.name}"`);
427
+ // ⚠️ COUNT 是 BIGINT,经 getRowObjectsJson() 是**字符串** —— 必须 Number() 收敛。
428
+ rowCount = Number((r.rows[0] ?? {}).n);
429
+ // 实际列集核对(spec §8.2「声明与实况的差异不得静默」)。
430
+ // ⚠️ 必须**先于** timeRangeOf:声明的时间列若已被删,`MIN("c")` 会在 prepare 期
431
+ // 抛 Binder Error 把整命令打成退出码 2,row_count/columns/pii_columns 全丢——
432
+ // 而「时间列被删」只是「列集不一致」的子集,应降级为 warning + time_range null。
433
+ const actual = (await session.run(`SELECT column_name FROM information_schema.columns WHERE table_schema='main' AND table_name='${table.name}'`))
434
+ .rows.map((row) => String(row.column_name));
435
+ const actualSet = new Set(actual);
436
+ const declaredSet = new Set(table.columns.map((c) => c.name));
437
+ const missing = table.columns.map((c) => c.name).filter((n) => !actualSet.has(n));
438
+ const extra = actual.filter((n) => !declaredSet.has(n)).sort();
439
+ const tc = table.timeColumn;
440
+ if (tc !== undefined && actualSet.has(tc.name)) {
441
+ timeRange = await timeRangeOf(session, table);
442
+ const dirty = await dirtyTimeValues(session, table);
443
+ if (dirty > 0)
444
+ warnings.push(dirtyTimeWarning(table.name, tc.name, dirty));
445
+ }
446
+ // tc 缺失时 timeRange 保持 null;下面的「少列」warning 已点名该时间列。
447
+ if (missing.length > 0 || extra.length > 0) {
448
+ const parts = [];
449
+ if (extra.length > 0)
450
+ parts.push(`多列 ${extra.join('、')}`);
451
+ if (missing.length > 0)
452
+ parts.push(`少列 ${missing.join('、')}`);
453
+ warnings.push(`表 ${table.name} 实际${parts.join('、')}——可能来自旧版 CLI 或库损坏`);
454
+ }
455
+ }
456
+ return ok({
457
+ table: table.name,
458
+ grain: table.grain,
459
+ primary_key: table.primaryKey,
460
+ // 无时间列 → null(不编造);有则只出 name/kind 两个键。
461
+ time_column: table.timeColumn === undefined
462
+ ? null : { name: table.timeColumn.name, kind: table.timeColumn.kind },
463
+ row_count: rowCount,
464
+ time_range: timeRange,
465
+ columns: table.columns.map(describeColumn),
466
+ pii_columns: piiColumnsOf(table),
467
+ }, { notice: PII_NOTICE, warnings });
468
+ }
469
+ catch (e) {
470
+ return thrownToQueryExit(e, TABLES);
471
+ }
472
+ finally {
473
+ await session.close();
474
+ }
475
+ }
476
+ export async function dbCommand(argv) {
477
+ setPretty(false); // G1:每条命令入口重置输出格式 —— 同一进程内多次 run(测试)不残留上一条命令的开关。
478
+ const [sub, ...rest] = argv;
479
+ if (sub === undefined || sub === '--help' || sub === '-h') {
480
+ // --help 不吞额外参数;--pretty 豁免(store.ts 同族惯例)
481
+ const extra = rest.filter((a) => !KNOWN.has(a));
482
+ if (extra.length > 0)
483
+ return usageFail(`未知参数:${extra.join(' ')}。--help 不接受额外参数`);
484
+ process.stdout.write(USAGE);
485
+ return 0;
486
+ }
487
+ // G1:--pretty 是输出开关,必须写在具体子命令之后(`db tables --pretty`)。
488
+ if (sub === '--pretty') {
489
+ const unknown = rest.filter((a) => a.startsWith('-') && !KNOWN.has(a));
490
+ const positional = rest.filter((a) => !a.startsWith('-'));
491
+ if (unknown.length + positional.length > 0)
492
+ return usageFail(`未知参数:${[...unknown, ...positional].join(' ')}。--pretty 不接受额外参数`);
493
+ if (rest.includes('--help') || rest.includes('-h')) {
494
+ process.stdout.write(USAGE);
495
+ return 0;
496
+ }
497
+ return usageFail(prettyAfterSubcommand('db'));
498
+ }
499
+ if (sub !== 'tables' && sub !== 'describe') {
500
+ return usageFail(`未知子命令:${sub}\n可用子命令:tables、describe`);
501
+ }
502
+ return sub === 'describe' ? dbDescribe(rest) : dbTables(rest);
503
+ }
@@ -0,0 +1,67 @@
1
+ // src/commands/local-fallback-wiring.ts
2
+ //
3
+ // `retry_strategy` / `fallback` 的真实实现(G1 契约小件):把限流错误里的
4
+ // 「改用本地查询」建议接到同步任务注册表与本地库文件上。
5
+ //
6
+ // ⚠️ 本文件 import `sync/` 与 `store/` —— 只有 `cli.ts`(入口层)允许调用
7
+ // `wireLocalFallback()`。`commands/api.ts` 只 import `local-fallback.ts` 的注入槽
8
+ // (见那里的分层说明)。
9
+ //
10
+ // 诚实边界(写进 hint,也写在这里):
11
+ // · 映射存在 + 库文件存在 **只说明「有表可查」**,不承诺表非空、更不承诺
12
+ // 数据覆盖调用方要的时间窗 —— hint 里明确要求先 `db tables` / `sync status` 确认。
13
+ // · 危险接口**不给**建议:调用方要的是写操作,一个本地读的表名帮不上忙,
14
+ // 反而可能被误读成「本地也能执行这个操作」。
15
+ import { statSync } from 'node:fs';
16
+ import { SYNC_TASKS } from '../sync/registry.js';
17
+ import { resolveStoreConfig, currentStoreEnv } from '../store/config.js';
18
+ import { setLocalFallbackProvider } from './local-fallback.js';
19
+ /**
20
+ * endpoint id → 该接口同步落地的本地表(按 `SYNC_TASKS` 声明顺序去重)。
21
+ *
22
+ * 同一接口可能对应多张表(`ticket.search` 路径同时服务 `tickets` 与 `ticket_logs`),
23
+ * 首表作为 `fallback` 命令的落点,其余在 hint 里点名 —— 只给一张表而不说还有别的,
24
+ * 调用方会以为本地只有那部分数据。
25
+ *
26
+ * ⚠️ 键取 `task.endpoint ?? task.id`:与限频闸门(`RunCtx.gate` 的注释)同一口径。
27
+ * 未声明 endpoint 的任务回退任务 id —— 那种 id 不是注册表接口 id,映射自然不命中。
28
+ */
29
+ export function buildEndpointTableMap() {
30
+ const map = new Map();
31
+ for (const t of SYNC_TASKS) {
32
+ const endpoint = t.endpoint ?? t.id;
33
+ const tables = map.get(endpoint) ?? [];
34
+ if (!tables.includes(t.table))
35
+ tables.push(t.table);
36
+ map.set(endpoint, tables);
37
+ }
38
+ return map;
39
+ }
40
+ const ENDPOINT_TABLES = buildEndpointTableMap();
41
+ /**
42
+ * 默认提供者:映射命中且**库文件存在**(`statSync().isFile()`)才返回建议。
43
+ *
44
+ * ⚠️ 只做 `isFile()` 探测,**不打开 DuckDB**:打开库需要 `@duckdb/node-api`,
45
+ * 与「api call 不加载 DuckDB」的启动成本红线冲突;而且文件存在与否正是本建议
46
+ * 唯一能诚实承诺的事(表里有没有数据、覆盖到哪个窗口,见文件头注)。
47
+ * ⚠️ 任何异常(配置文件不是合法 JSON、路径是目录、权限不足)一律视为「不可用」——
48
+ * 探测失败不能改变原始限流错误(`localFallbackFor` 的 catch 是第二道兜底)。
49
+ */
50
+ export function localFallbackProvider(endpointId) {
51
+ const tables = ENDPOINT_TABLES.get(endpointId);
52
+ if (!tables || tables.length === 0)
53
+ return undefined;
54
+ try {
55
+ const { config } = resolveStoreConfig({ env: currentStoreEnv() });
56
+ if (!statSync(config.path).isFile())
57
+ return undefined;
58
+ }
59
+ catch {
60
+ return undefined;
61
+ }
62
+ return { tables };
63
+ }
64
+ /** cli.ts 启动时调用:把默认提供者装进注入槽。 */
65
+ export function wireLocalFallback() {
66
+ setLocalFallbackProvider(localFallbackProvider);
67
+ }
@@ -0,0 +1,34 @@
1
+ // src/commands/local-fallback.ts
2
+ //
3
+ // 「改用本地查询」的注入槽(G1 契约小件)。设计稿 §9.1 的限流错误示例里声明了
4
+ // `retry_strategy` / `fallback` 两个字段,而它们的值依赖**同步任务注册表**与
5
+ // **本地库文件** —— 两者都在 `sync/` 与 `store/` 里。
6
+ //
7
+ // ⚠️ 本文件必须保持**零依赖**(不 import sync/、store/、node:fs),这是分层红线:
8
+ // `commands/api.ts` 与 `commands/auth.ts` 不得加载 store/(layering.test.ts 用
9
+ // 源文本钉着)。所以 api.ts 只 import 这个槽;真正的映射与库文件探测在
10
+ // `local-fallback-wiring.ts`,由 `cli.ts`(入口层,允许同时 import 两边)在
11
+ // 进程启动时注入。
12
+ //
13
+ // ⚠️ 不用「cli.ts 启动期算好一份快照」而是**惰性回调**:`run()` 在测试里会被
14
+ // 同一进程反复调用,库文件可能在两次调用之间被创建;回调让每次判定都读到当下状态。
15
+ // 探测本身只发生在**限流错误真的出现时**(一次),不是每条命令都付代价。
16
+ let provider;
17
+ /** 设置(或清除,传 undefined)fallback 提供者。cli.ts 注入;测试可直接注入。 */
18
+ export function setLocalFallbackProvider(fn) {
19
+ provider = fn;
20
+ }
21
+ /**
22
+ * 查该接口是否有可用的本地替代。任何异常(提供者内部探测失败、配置畸形等)
23
+ * 一律吞掉返回 `undefined` —— 它只用于给限流错误**附加**一条建议,
24
+ * **绝不能因为探测失败改变原始错误本身**(那会把限流报成 internal)。
25
+ */
26
+ export function localFallbackFor(endpointId) {
27
+ try {
28
+ const fb = provider?.(endpointId);
29
+ return fb && fb.tables.length > 0 ? fb : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }