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,297 @@
1
+ // src/query/table-query.ts —— `query --table` 的 SQL 构造(纯函数,spec §四/§六)。
2
+ //
3
+ // 纯函数边界:不碰 DuckDB、不读文件、不写 stdout/stderr、不读系统时钟(`now` 由调用方注入)。
4
+ // 命令层负责:表名闭集查找、时间参数解析(parseTimeArg)、查表 MIN、执行与脱敏。
5
+ //
6
+ // 三条硬约束:
7
+ // 1. **注入面为零**:表名/列名只来自 `TABLES`(`TableDef`),拼进 SQL 前已过闭集校验并加双引号;
8
+ // 外部取值(时间)只进 `?` 参数位,数值参数保持 number(`String()` 会退化成 VARCHAR 比较,
9
+ // epoch-ms 按字典序排会错)。
10
+ // 2. **时间列三形态**(spec §四):iso-day 两端都向下取整到上海日零点——直接用
11
+ // `ms.toISOString()` 会让「9/15 12:00 的 --since」把 stat_date=9/15 零点的行排除在外;
12
+ // iso-instant 直接字符串比较;epoch-ms 用 `TRY_CAST(... AS BIGINT)`,非数字行按 NULL 被排除。
13
+ // 3. **确定性排序**(契约 E):group-by 用 `count DESC` + 分组列;否则时间列 DESC(无时间列
14
+ // 则只有主键)+ 主键 ASC 作 tiebreaker。没有 tiebreaker 时同值行的顺序由引擎决定,
15
+ // 同一查询两次可能不同 —— Agent 与测试都无法接受。
16
+ //
17
+ // ⚠️ `resolved_range` 回显的是**实际生效**的区间(不是用户原始输入):iso-day 两端都是
18
+ // 上海日零点。这是刻意的 —— Agent 要据此知道过滤实际覆盖了哪个自然日(`--since 9/15 12:00`
19
+ // 实际从 9/15 00:00 起算;`--until 9/20` 实际覆盖到 9/20 全天)。契约 C。
20
+ import { shanghaiDayIso, shanghaiDayStart, shanghaiIso } from '../core/time.js';
21
+ import { timeShapeClauses } from './time-shape.js';
22
+ import { suggestNames } from './errors.js';
23
+ import { describeArgs } from '../output.js';
24
+ /**
25
+ * `--table` 的用法类错误(未知表/列、敏感列、区间无效)。
26
+ * 纯函数只负责抛,命令层统一转 `usageFail`(退出码 2)—— 与 `parseStoreFlags` 的异常形态同款。
27
+ */
28
+ export class TableQueryUsageError extends Error {
29
+ constructor(message) {
30
+ super(message);
31
+ this.name = 'TableQueryUsageError';
32
+ }
33
+ }
34
+ /** 标识符加双引号。调用方保证 name 来自 `TABLES`(闭集)。 */
35
+ function quote(name) {
36
+ return `"${name}"`;
37
+ }
38
+ /**
39
+ * 时间列的比较表达式。
40
+ *
41
+ * ⚠️ **一律按解析后的时刻比较,不按原始字符串**(正确性审查 F1/F2/F3,2026-10-20 实测):
42
+ * · iso-day 无毫秒形态 `'…T16:00:00Z'` 在字典序上**大于** `'…T16:00:00.000Z'`,
43
+ * `<= 上界` 会把它漏掉 → `db describe` 说有数据、`query` 说 0 行;
44
+ * · iso-instant 的 `+08:00` 写法与 `Z` 写法字典序与时间序相反 → 错排/错纳/错漏;
45
+ * · epoch-ms 必须先 TRY_CAST,字符串比较毫秒数会按字典序得出错误结果。
46
+ * `TRY_CAST(... AS TIMESTAMPTZ)` 对非时间值返回 NULL(被谓词排除),与形态谓词同向。
47
+ */
48
+ function timeExprOf(tc) {
49
+ return tc.kind === 'epoch-ms'
50
+ ? `TRY_CAST(${quote(tc.name)} AS BIGINT)`
51
+ : `TRY_CAST(${quote(tc.name)} AS TIMESTAMPTZ)`;
52
+ }
53
+ /**
54
+ * 极值聚合:**按时刻排序、返回原始字符串**(与 `commands/db.ts` 的 `timeRangeOf` 同口径)。
55
+ *
56
+ * 不能直接 `MIN(col)` —— 那按字典序选,遇到混合偏移/无毫秒形态会取错(见 `timeExprOf`)。
57
+ * 也不能直接 `MIN(TRY_CAST(... AS TIMESTAMPTZ))` —— 那会把返回值变成 TIMESTAMPTZ 文本
58
+ * (`2026-10-14 00:00:00+08`),改变 `data_coverage` 的输出形态。
59
+ * `arg_min(col, 时刻键)` 两者兼得:按时刻排序、返回列内原值。
60
+ * 键为 NULL 的行(非时间值)不参与,与形态谓词同向。
61
+ */
62
+ function aggExprOf(tc) {
63
+ if (tc.kind === 'epoch-ms') {
64
+ return {
65
+ mn: `MIN(TRY_CAST(${quote(tc.name)} AS BIGINT))`,
66
+ mx: `MAX(TRY_CAST(${quote(tc.name)} AS BIGINT))`,
67
+ };
68
+ }
69
+ const col = quote(tc.name);
70
+ const key = `TRY_CAST(${col} AS TIMESTAMPTZ)`;
71
+ return { mn: `arg_min(${col}, ${key})`, mx: `arg_max(${col}, ${key})` };
72
+ }
73
+ /**
74
+ * 时间列的**可用值谓词**(脏值不进 MIN/MAX、不进覆盖统计、不进主查询的时间过滤)。
75
+ *
76
+ * 实现与 `commands/db.ts` 共用 `query/time-shape.ts` 的同一函数 —— 口径由构造保证,
77
+ * 不再靠「逐字一致」的注释与字符串相等测试(同一条 README 承诺:「脏值不进 time_range」;
78
+ * 两处分叉的话,同一条脏库会在 `db tables` 被排除、在 `query --table` 被当成覆盖范围)。
79
+ * 具体判据与实测约束(F3/F5/gap 2)见该模块头注释。
80
+ *
81
+ * ⚠️ 主查询的时间谓词也需要它(正确性审查 F8):否则 `'2026-10-15garbage'` 会出现在
82
+ * rows / group-by 计数里,而 `data_coverage` 把它排除,同一响应内自相矛盾。
83
+ */
84
+ function shapeClause(tc) {
85
+ return timeShapeClauses(tc.kind, quote(tc.name));
86
+ }
87
+ /**
88
+ * 生效边界(`resolved_range` 的回显值):iso-day 取上海日零点,其余原值(契约 A/C)。
89
+ * 导出供命令层在「0 行警告」里说明实际生效的上界。
90
+ */
91
+ export function effectiveBound(kind, ms) {
92
+ return kind === 'iso-day' ? shanghaiDayStart(ms) : ms;
93
+ }
94
+ /** 时间谓词的参数占位符:ISO 列必须显式 cast,否则 VARCHAR 与 TIMESTAMPTZ 的比较会退化。 */
95
+ function boundPlaceholder(kind) {
96
+ return kind === 'epoch-ms' ? '?' : 'TRY_CAST(? AS TIMESTAMPTZ)';
97
+ }
98
+ /** 时间谓词的参数值(契约 A):iso-day → 上海日零点 ISO;iso-instant → ISO;epoch-ms → number。 */
99
+ function boundParam(kind, ms) {
100
+ switch (kind) {
101
+ case 'iso-day': return shanghaiDayIso(ms);
102
+ case 'iso-instant': return new Date(ms).toISOString();
103
+ case 'epoch-ms': return ms;
104
+ }
105
+ }
106
+ /**
107
+ * `--group-by` 的闭集校验(契约 F):返回校验通过的列(保持用户给定顺序)。
108
+ * 不支持的行/列一律抛 `TableQueryUsageError`:
109
+ * · 未知列 → 候选来自**本表**列集(suggestNames);
110
+ * · 敏感列 → 拒绝(脱敏会把不同取值归并成同一个分组键,分组与计数都会失真);
111
+ * · 重复列 → 拒绝(不静默去重,否则 Agent 会以为按两列分组)。
112
+ */
113
+ export function validateGroupBy(table, groupBy) {
114
+ const names = table.columns.map((c) => c.name);
115
+ const sensitive = new Set(table.columns.filter((c) => c.sensitive === true).map((c) => c.name));
116
+ const seen = new Set();
117
+ for (const name of groupBy) {
118
+ if (!names.includes(name)) {
119
+ const candidates = suggestNames(name, names);
120
+ const hint = candidates.length > 0
121
+ ? `候选:${candidates.join('、')}`
122
+ : `该表列:${names.join('、')}`;
123
+ throw new TableQueryUsageError(`--group-by 未知列:${describeArgs([name])}(表 ${table.name} 无此列);${hint}`);
124
+ }
125
+ if (sensitive.has(name)) {
126
+ throw new TableQueryUsageError(`--group-by 不接受敏感列 ${name}:脱敏会把不同取值归并成同一个分组键,`
127
+ + '分组结果无法区分(计数本身准确,但每个分组代表哪些原值不可知)。'
128
+ + '确需按原值分组请改用 `qiyu query --sql --no-mask`(显式承担 PII 风险)');
129
+ }
130
+ if (seen.has(name)) {
131
+ throw new TableQueryUsageError(`--group-by 列重复:${name}(同一列只能给一次,不做静默去重)`);
132
+ }
133
+ seen.add(name);
134
+ }
135
+ return [...groupBy];
136
+ }
137
+ /**
138
+ * 时间谓词(契约 A/B)+ resolved_range(契约 C)。`buildTableQuery` 与 `buildCoverageQuery`
139
+ * 共用这一处,保证「主查询的过滤范围」与「覆盖统计的过滤范围」永远是同一个谓词。
140
+ */
141
+ function buildTimeFilter(input) {
142
+ const { table, since, until } = input;
143
+ const tc = table.timeColumn;
144
+ const empty = { clauses: [], params: [], resolvedRange: null, warnings: [] };
145
+ if (tc === undefined) {
146
+ if (since !== undefined || until !== undefined) {
147
+ throw new TableQueryUsageError(`表 ${table.name} 没有时间列,不支持 --since/--until`);
148
+ }
149
+ return empty;
150
+ }
151
+ if (since === undefined && until === undefined)
152
+ return empty;
153
+ const warnings = [];
154
+ let lower = since;
155
+ if (lower === undefined) {
156
+ // 只给了 --until:下界取该表时间列 MIN(命令层已查,契约 B)。
157
+ const mn = input.tableMin;
158
+ if (mn === undefined || mn === null) {
159
+ // ⚠️ 措辞不得断言「表为空」(审查 Minor 3):`MIN(TRY_CAST(...))` 为 NULL 有两种成因
160
+ // ——表真的没有行,或该列全为 NULL/非数字(epoch-ms 列里脏值会被 TRY_CAST 折成 NULL)。
161
+ // 说成「表为空」在第二种情形下是假话,Agent 会据此判断「同步没跑」。
162
+ warnings.push(`表 ${table.name} 的时间列 ${tc.name} 无可用值(表为空,或该列全为 NULL/非数字),`
163
+ + '无法解析缺省下界;本次查询仅限制上界');
164
+ }
165
+ else
166
+ lower = mn;
167
+ }
168
+ // --until 缺省但有 --since → 上界 = 当前时刻(契约 B)。
169
+ const upper = until ?? (since !== undefined ? input.now : undefined);
170
+ const clauses = [];
171
+ const params = [];
172
+ let resolvedRange = null;
173
+ if (lower !== undefined && upper !== undefined) {
174
+ const lo = effectiveBound(tc.kind, lower);
175
+ const hi = effectiveBound(tc.kind, upper);
176
+ // 只有 `lo > hi` 才是用法错误(真·倒置区间)。
177
+ // ⚠️ `lo === hi` **必须放行**:iso-day 列存的就是日零点,`>= X AND <= X` 是合法的
178
+ // 单日查询(「就看 9/15 这一天」「看今天」都落在这里)。早先写成 `>=` 会把这两种
179
+ // 最自然的问法判成「区间无效」,而 `--since 9/14`(不给 until)却能返回 9/14 + 9/15
180
+ // 两行——同一个意图两种结局,Agent 只能改用 --sql。
181
+ // iso-instant/epoch-ms 的单点区间同样放行:结果为 0 行 + 既有 0 行警告,比用法错误更符合事实。
182
+ // ⚠️ 只校验用户给出的 since:`--since` 缺省时下界来自表 MIN,「表里最早的数据晚于
183
+ // --until」是数据事实(0 行 + 0 行警告),不是用法错误 —— 不能把它变成退出码 2。
184
+ if (since !== undefined && lo > hi) {
185
+ throw new TableQueryUsageError(`区间无效:生效下界 ${shanghaiIso(lo)} 晚于生效上界 ${shanghaiIso(hi)}` +
186
+ (tc.kind === 'iso-day' ? '(日期型时间列两端都取上海日零点)' : '') +
187
+ ';请调整 --since / --until');
188
+ }
189
+ resolvedRange = [lo, hi];
190
+ // 下界来自表 MIN 时可能出现 lo > hi(「表里最早的数据晚于 --until」):这不是用法
191
+ // 错误(用户只给了一个端点),但 resolved_range 会回显一个倒置二元组 —— 不说明成因的话
192
+ // Agent 得自己推断为什么 0 行。spec §十「0 行 ≠ 没有数据」的同类:把成因写在明处。
193
+ if (since === undefined && lo > hi) {
194
+ warnings.push(`缺省下界(该表最早数据 ${shanghaiIso(lo)})晚于上界 ${shanghaiIso(hi)},本次查询必然 0 行;`
195
+ + '请放宽 --until 或改用 --sql');
196
+ }
197
+ }
198
+ const expr = timeExprOf(tc);
199
+ // 形态+可解析谓词与时间谓词同一 WHERE(正确性审查 F8):否则脏值会出现在 rows 里,
200
+ // 而 data_coverage 把它们排除 —— 同一响应的两个字段互相矛盾。
201
+ if (lower !== undefined || upper !== undefined)
202
+ clauses.push(...shapeClause(tc));
203
+ if (lower !== undefined) {
204
+ clauses.push(`${expr} >= ${boundPlaceholder(tc.kind)}`);
205
+ params.push(boundParam(tc.kind, lower));
206
+ }
207
+ if (upper !== undefined) {
208
+ clauses.push(`${expr} <= ${boundPlaceholder(tc.kind)}`);
209
+ params.push(boundParam(tc.kind, upper));
210
+ }
211
+ return { clauses, params, resolvedRange, warnings };
212
+ }
213
+ /**
214
+ * 构造 `query --table` 的 SQL(契约 A–F)。
215
+ *
216
+ * SELECT * FROM "t" [WHERE …] [ORDER BY 时间列 DESC, 主键 ASC | 主键 ASC]
217
+ * SELECT "g1", "g2", COUNT(*) AS count FROM "t" [WHERE …]
218
+ * GROUP BY "g1", "g2" ORDER BY count DESC, "g1", "g2"
219
+ *
220
+ * 时间列本身就是主键(daily_overview.stat_date)时 tiebreaker 不再重复同一列。
221
+ */
222
+ export function buildTableQuery(input) {
223
+ const { table } = input;
224
+ const groupBy = validateGroupBy(table, input.groupBy ?? []);
225
+ const filter = buildTimeFilter(input);
226
+ const where = filter.clauses.length > 0 ? ` WHERE ${filter.clauses.join(' AND ')}` : '';
227
+ const tc = table.timeColumn;
228
+ let select;
229
+ let tail;
230
+ if (groupBy.length > 0) {
231
+ const cols = groupBy.map(quote).join(', ');
232
+ select = `${cols}, COUNT(*) AS count`;
233
+ // 确定性(契约 E):count 相同的分组按分组列全序,否则顺序由引擎决定。
234
+ tail = ` GROUP BY ${cols} ORDER BY count DESC, ${cols}`;
235
+ }
236
+ else {
237
+ select = '*';
238
+ const orderBy = [];
239
+ if (tc !== undefined)
240
+ orderBy.push(`${timeExprOf(tc)} DESC`);
241
+ // tiebreaker:主键 ASC(时间列已在前面排过的不再重复)。
242
+ const pk = table.primaryKey
243
+ .filter((k) => tc === undefined || k !== tc.name)
244
+ .map((k) => `${quote(k)} ASC`);
245
+ if (pk.length > 0)
246
+ orderBy.push(pk.join(', '));
247
+ tail = orderBy.length > 0 ? ` ORDER BY ${orderBy.join(', ')}` : '';
248
+ }
249
+ const sql = `SELECT ${select} FROM ${quote(table.name)}${where}${tail}`;
250
+ return { sql, params: filter.params, resolvedRange: filter.resolvedRange, warnings: filter.warnings };
251
+ }
252
+ /**
253
+ * `data_coverage` 的查询(契约 D):与主查询**同一个谓词**(不是全表 MIN/MAX),
254
+ * 独立执行因而不受 `--limit` 截断影响。值原样返回,格式化由命令层统一走 `msToShanghaiIso`。
255
+ *
256
+ * 第二个输出列 `days` 是**区间内的不同自然日数**(端到端场景 F4):MIN/MAX 结构上
257
+ * 表达不了内部空洞 —— 7 天窗口里缺一天时 rows 可能恰好是 7、看什么都没问题。
258
+ * iso-day 列的行粒度就是一天,直接 `COUNT(DISTINCT)` 即自然日数;iso-instant/epoch-ms
259
+ * 的表不是日粒度(hour_ts 是小时),拿它比日历日没有意义,故为 NULL 由调用方跳过。
260
+ */
261
+ export function buildCoverageQuery(input) {
262
+ const { table } = input;
263
+ const tc = table.timeColumn;
264
+ if (tc === undefined) {
265
+ throw new TableQueryUsageError(`表 ${table.name} 没有时间列,无法计算 data_coverage`);
266
+ }
267
+ const filter = buildTimeFilter(input);
268
+ // 形态谓词与时间谓词同一 WHERE:buildTimeFilter 在有任一端时已并入 shapeClause;
269
+ // 两端都缺省时(全表覆盖统计)才需要在这里单独补上,避免重复拼接。
270
+ const clauses = filter.clauses.length > 0 ? [...filter.clauses] : [...shapeClause(tc)];
271
+ const where = clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '';
272
+ const agg = aggExprOf(tc);
273
+ // ⚠️ 自然日数必须按**自然日**去重,不能 COUNT(DISTINCT 原字符串)(正确性审查 F6):
274
+ // 同一上海日可能有两种写法(`…16:00:00.000Z` 与 `…16:00:00Z`),按字符串数会把
275
+ // 一天算成两天,恰好补齐内部缺口、让真缺口零警告。
276
+ const days = tc.kind === 'iso-day'
277
+ ? `, COUNT(DISTINCT timezone('Asia/Shanghai', ${timeExprOf(tc)})::DATE) AS days`
278
+ : ', NULL AS days';
279
+ return {
280
+ sql: `SELECT ${agg.mn} AS mn, ${agg.mx} AS mx${days} FROM ${quote(table.name)}${where}`,
281
+ params: filter.params,
282
+ };
283
+ }
284
+ /** 表时间列的下界查询(只给 `--until` 时解析缺省下界,契约 B)。只带形态谓词。 */
285
+ export function buildMinQuery(table) {
286
+ const tc = table.timeColumn;
287
+ if (tc === undefined) {
288
+ throw new TableQueryUsageError(`表 ${table.name} 没有时间列,无法查询下界`);
289
+ }
290
+ // ⚠️ 必须过滤形态(CodeRabbit 终审 minor):空串在字典序上小于一切 ISO,
291
+ // `MIN` 会返回它 → 命令层判成「该列无可用值」而丢掉缺省下界,尽管表里有合法行。
292
+ // ⚠️ 极值必须按**时刻**取(正确性审查 F2):`MIN(原始字符串)` 在混合偏移写法下会
293
+ // 选到字典序最小、而不是时刻最早的那一行。`aggExprOf` 用 arg_min 返回原始串。
294
+ const shape = shapeClause(tc);
295
+ const where = shape.length > 0 ? ` WHERE ${shape.join(' AND ')}` : '';
296
+ return { sql: `SELECT ${aggExprOf(tc).mn} AS mn FROM ${quote(table.name)}${where}` };
297
+ }
@@ -0,0 +1,44 @@
1
+ // src/query/time-shape.ts —— 时间列「形态合格」SQL 谓词的**唯一**事实源。
2
+ //
3
+ // `db tables` / `db describe` 的 time_range(commands/db.ts)与 `query --table` 的
4
+ // 主查询 / 覆盖查询 / 缺省下界(query/table-query.ts)必须对「哪些行算合格时间值」
5
+ // 给出**同一个**答案:两处分叉的话,同一条脏库会在 db 侧被排除、在 query 侧被当成
6
+ // 覆盖范围 —— 同一状态两种说法。此前两份逐字副本只靠注释与字符串相等测试防守,
7
+ // gap 2 的缺陷正来自这两份副本;现在由构造保证(CodeRabbit nitpick)。
8
+ //
9
+ // 约定:`col` 是**已加双引号的列表达式**(两个调用方的引号风格本就一致 ——
10
+ // 列名全部来自 `TABLES` 闭集,无注入面)。传各自 `quote(name)` 的产物即可:
11
+ // 引号是「拼 SQL」的通用关注点,不属于时间形态,故不在这里收编。
12
+ //
13
+ // 三条实测约束(逐条都有审查编号与失败形态,别再简化):
14
+ // · epoch-ms 也必须有数值判据(正确性审查 F5):`TRY_CAST IS NULL` 只挡非数字,
15
+ // `-1`(七鱼「无值」哨兵)、秒级 / 微秒级误写全部「合法」—— 会让 time_range
16
+ // 声称数据从 1970 年开始。写路径对秒级时间戳已有同口径丢弃(`reports.ts` 的
17
+ // `n <= 1e11`)。
18
+ // · epoch-ms 上界是 `MAX_SHANGHAI_SAFE_MS` 而不是 `MAX_DATE_MS`(F 维度审查 gap 2):
19
+ // 回显要加上海偏移,差这 8 小时就会在 `shanghaiIso` 里抛 `RangeError` ——
20
+ // 「形状合格」必须 ⊆「能回显」。
21
+ // · iso 两形态:用 `regexp_matches`,不要用 `~`(实测 DuckDB 1.5.6-r.1 的 `~`
22
+ // 不是正则匹配,会把所有行都滤掉);秒必须存在(`:[0-9]{2}` 不可选 ——
23
+ // `T02:00Z` 能过宽松正则却 cast 不了);正则之外还要 `TRY_CAST(...) IS NOT NULL`
24
+ // (正确性审查 F3:`'2026-10-14T02:00Z'` 过得了正则,`TRY_CAST` 是 NULL ——
25
+ // 只按正则判会让它在 arg_min 里被静默踢出 time_range)。
26
+ import { MAX_SHANGHAI_SAFE_MS } from '../core/time.js';
27
+ /**
28
+ * 「该列的哪些行算合格时间值」的 WHERE 片段(调用方用 `AND` 连接)。
29
+ *
30
+ * 判据 = 「形态正则命中」**且**「能解析成时刻 / 整数」。
31
+ */
32
+ export function timeShapeClauses(kind, col) {
33
+ if (kind === 'epoch-ms') {
34
+ const n = `TRY_CAST(${col} AS BIGINT)`;
35
+ return [`${n} > 100000000000`, `${n} <= ${MAX_SHANGHAI_SAFE_MS}`];
36
+ }
37
+ const shape = kind === 'iso-day'
38
+ ? '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$'
39
+ : '^[0-9]{4}-[0-9]{2}-[0-9]{2}[T ][0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:?[0-9]{2})$';
40
+ return [
41
+ `regexp_matches(${col}, '${shape}')`,
42
+ `TRY_CAST(${col} AS TIMESTAMPTZ) IS NOT NULL`,
43
+ ];
44
+ }