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,50 @@
1
+ # 需要人工配置的 ID
2
+
3
+ 有些 ID **无法通过开放 API 获得**,也没有「列表」接口可以枚举。缺它们时,正确的动作是
4
+ **停下来问人类**,而不是猜测、枚举或从别处硬推。
5
+
6
+ ## 机器人编号(robotId)
7
+
8
+ 机器人知识库的查询、机器人统计、机器人会话相关接口都以机器人编号为入参,但官方没有
9
+ 「机器人列表」接口——枚举候选编号只会得到成片的「路由不存在」。
10
+
11
+ 规则:
12
+
13
+ 1. **缺失时问人类**。要「机器人编号清单」,不要自己编造、不要按数字区间试探、
14
+ 不要把会话里见过的编号当全量。
15
+ 2. 人类把编号写进配置文件(两种写法都认):
16
+ - `store.options.knowledgeRobotIds`(正整数数组)—— **优先**;
17
+ - `profiles.<name>.robots`(`{"1000001":"机器人A"}` 映射,键是编号、值是显示名)——
18
+ `knowledgeRobotIds` 缺席时的兜底。
19
+
20
+ `qiyu sync run` 在条目数据集为空(分类树没有可依据的编号来源)时会改用这些编号逐机器人
21
+ 拉取分类树;条目数据非空时以条目数据为准。写错(非正整数)会被 CLI 以用法错误拒绝并点名
22
+ 非法元素。`qiyu auth whoami` 的 `data.robots` 会如实列出配置里的映射(未校验有效性)。
23
+ 3. 编号是否有效应以同步结果为准——同步后用 `qiyu db tables` 看知识库各数据集的行数是否非零。
24
+
25
+ ### 两条补充发现路径(都只覆盖一部分,不替代手工配置)
26
+
27
+ - **从会话数据反推**:机器人会话的处理人编号与机器人编号存在固定的负数关系。会话数据
28
+ 同步完成后,可以按会话类型过滤出机器人会话、对处理人编号取不同值,得到一部分机器人编号。
29
+ **它只能发现产生过会话的机器人**——新建的、没接待过的机器人不在其中。
30
+ - **从知识库条目反推**:知识库条目数据集自带机器人编号与名称字段。全量同步后按该字段
31
+ 分组即可得到一部分机器人编号。**它只能发现知识库非空的机器人**——空知识库的机器人不在其中。
32
+
33
+ 两条路径互补,但**并集仍不完整**:既没有会话又没有知识库的机器人永远发现不了。
34
+ 所以手工配置是基线,这两条只用来校验与补充;发现差异时报告人类,不要擅自改配置。
35
+
36
+ ## 其他无列表接口的 ID
37
+
38
+ 同类无法通过 API 列举、必须由人类提供的还有:
39
+
40
+ - **手动外呼任务编号**:没有「任务列表」接口。
41
+ - **外呼机器人任务编号**:同样没有列表接口。
42
+
43
+ 涉及这两类任务时,先问人类要具体编号;拿 `qiyu sync tasks` 能列出的只是**同步任务**的编号,
44
+ 它们是两回事,不要混用。
45
+
46
+ ## 配置文件归人类
47
+
48
+ 所有需要手工编辑的配置(存储位置、profile、机器人编号清单)都由人类维护在配置文件里。
49
+ Agent 的职责是:识别「缺配置」类错误 → 转述给人类 → 等人类配好 → 重新验证;
50
+ **不代写、不代改配置文件**(原因见 forbidden.md 第 1 条)。
@@ -0,0 +1,379 @@
1
+ // src/skill/refs.ts —— 从 skill 正文里提取「可被机器校验的引用」:命令路径 / flag、错误
2
+ // `kind`、SQL 序列,以及明知无法静态判定的命令(含选择或省略符号)。
3
+ //
4
+ // 本文件是纯函数、零业务依赖(除标准库外无 import,实际上连 node:* 都不用)。它只负责
5
+ // **提取**,不判断引用是否合法 —— 命令是否在 `COMMAND_TREE` 里、kind 是否在 `ERROR_KINDS`
6
+ // 里,是 `skill check`(Task 6)的事。保持这条边界,提取器才能被单独测试,也不会把
7
+ // commands 层拉进 skill 层。
8
+ //
9
+ // 扫描面(collectSurfaces 决定「哪些文本算代码」,scan* 决定算什么引用):
10
+ // · 行内代码:散文里的 `` `qiyu sync status` ``,单反引号包裹,一行可多片段,各自计数。
11
+ // · 围栏代码块:``` 围栏内的行。围栏行**既**按裸文本扫、**也**解析行内反引号 ——
12
+ // `` `qiyu db tables` `` 和裸 `qiyu db tables` 都是真实引用,漏检(Task 6 看不见)
13
+ // 比误报危险;为不双计,裸文本先剥掉行内片段再入列,并按「行 + 内容」去重。
14
+ // shell 命令替换(`` echo `date` ``)的内层片段是 `date`,三条扫描都不命中,无噪声。
15
+ // · 围栏行尾的 `#` 注释剥掉:`qiyu sync status # 不要用 --pretty` 的注释是否定语境,
16
+ // 不是命令的一部分,`--pretty` 进 flags 会让 Task 6 误报 rejected_flag。
17
+ // · 正文散文不算引用:裸散文的 `qiyu …` 不提取 —— 「正文提到命令」与「正文承诺命令
18
+ // 存在」的分界。
19
+ //
20
+ // 围栏配对按**长度**(闭合 ≥ 开启,CommonMark):五反引号外层里的三反引号行是内容不是
21
+ // 闭合,嵌套围栏不翻转;围栏容忍 ≤3 空格缩进(列表项里的代码块),缩进的闭合围栏也能
22
+ // 正常闭合。围栏未闭合时余下全部按围栏内容扫:宁可多扫几行,也不要因为文档末尾漏写
23
+ // ```` ``` ```` 就把后面的示例命令整段漏掉。
24
+ //
25
+ // 命令切词(scanCommand)的裁定语义:
26
+ // · 切词**认识引号**(`splitWords`):`'…'` / `"…"` 整体算一个词(去引号),其余按非空白
27
+ // 切。`--schedule "0 3 * * *"` 是「flag + 一个取值」而不是五个词;未闭合的引号退化为
28
+ // `\S+`,不丢整段(全审查 A2)。
29
+ // · refs 层**不做「哪个 token 是 flag 取值」的判断**:它不认识命令树(零业务依赖),
30
+ // 旧版在这里按「flag 之后紧跟的词就是取值」一刀吞,把 bool flag(`--full`)之后的
31
+ // 位置参数也吞掉,`skill check` 的位置参数域校验因此整段失效(全审查 A1),也把
32
+ // flag 的位置抹平(`db --profile prod tables` 被判通过,全审查 A3)。现在 `tokens`
33
+ // 原样保留**全部** token(命令词 / 位置参数 / flag / flag 取值 / 占位符),由 check
34
+ // 层按 `spec.flags` 的 `kind` 重建位置参数。
35
+ // · 路径 token 在第一个 `<...>` 占位符处封口:占位符是取值或位置参数模板,不是子命令
36
+ // (`qiyu query <表>` 不该把 `<表>` 当成子命令)。封口只影响「命令路径」的判定,
37
+ // 占位符本身留在 `tokens` 里(否则 `--table <表>` 会被误判成「--table 缺少取值」)。
38
+ // · flag 跨占位符继续收(`--since <时间>` 的 `--since` 仍可静态校验),但**在管道 /
39
+ // 选择 / 省略符号处止步** —— 管道右侧是另一条命令,`| head -20` 的 `-20` 不属于 qiyu。
40
+ // 占位符之后的这些符号不判 unverifiable(路径已封口,后面本来就不校验)。
41
+ // · `--table=<表>` 按 `=` 切出 flag 名 —— check 层比对的是 flag 名,取值已内联。
42
+ // · 只有 flag / 占位符、没有命令词的 `qiyu --help` 不记成命令引用(见 scanCommand 内注释)。
43
+ //
44
+ // ⚠️ 本文件**不认识命令树**(零业务依赖、零 import):命令路径的切分、flag 的取值归属、
45
+ // 位置参数的重建都在 check 层做(那里有 `CommandSpec`)。提取器一旦内置 flag 表,就会与
46
+ // `commands/spec-types.ts` 漂成第二事实源 —— 那样 bool flag 与值位 flag 的区别就得写两遍。
47
+ /**
48
+ * 围栏开启:≤3 空格缩进(CommonMark 上限,列表项里的代码块通常缩进)+ ≥3 个反引号,
49
+ * 捕获反引号串用于长度配对;info string(```bash)不算闭合。
50
+ */
51
+ const FENCE_OPEN_RE = /^ {0,3}(`{3,})/;
52
+ /** 围栏闭合:只有反引号(CommonMark 不许闭合行带 info string),长度 ≥ 开启长度才闭合。 */
53
+ const FENCE_CLOSE_RE = /^ {0,3}(`{3,})\s*$/;
54
+ /** 行内代码片段:单反引号包裹、片段内不允许换行(换行就不是「行内」了)。 */
55
+ const INLINE_CODE_RE = /`([^`\n]+)`/g;
56
+ /** 命令形态:片段以程序名开头,后接至少一个空白。 */
57
+ const COMMAND_RE = /^qiyu\s+(.*)$/;
58
+ /** 占位符:整个词就是 `<...>`。只认这种完整形态,`--table=<表>` 靠等号切分归一。 */
59
+ const PLACEHOLDER_RE = /^<[^>]*>$/;
60
+ /** 规则里钉死的话术,`skill check` 把它原样放进 warnings。 */
61
+ const REASON_CHOICE = '含选择/省略符号';
62
+ /** 错误分类的窄形态:`kind: rate_limit`。宽形态(如 `kind: foo/bar`)不提取,见规则 4。 */
63
+ const KIND_RE = /^kind:\s*([a-z_]+)$/;
64
+ /** SQL 判定:同时出现大写的 `SELECT` 与 `FROM`,且各自是独立词。大小写敏感。 */
65
+ const SELECT_RE = /\bSELECT\b/;
66
+ const FROM_RE = /\bFROM\b/;
67
+ /** 围栏行注释:`#` 在行首或前面是空白才算注释,`a#b` / URL 锚点不受影响。 */
68
+ const COMMENT_RE = /(^|\s)#.*$/;
69
+ /**
70
+ * 切词用的引号模式:单引号串 / 双引号串 / 非空白串,三选一,逐个匹配(全审查 A2)。
71
+ * 未闭合的引号匹配不上前两个分支,自然退化为 `\S+` —— 不丢整段。
72
+ */
73
+ const QUOTED_TOKEN_RE = /'([^']*)'|"([^"]*)"|(\S+)/g;
74
+ /** 占位符(整词 `<...>`)判定:check 层重建位置参数时用它跳过模板。 */
75
+ export function isPlaceholderToken(word) {
76
+ return PLACEHOLDER_RE.test(word);
77
+ }
78
+ /**
79
+ * `--flag=<占位符>`:flag 名 + 内联取值模板(`--table=<表>`)。整体按 flag 处理 ——
80
+ * 它的 `<`/`>` 是模板括号而不是重定向:A4 扩了 `>`/`<` 之后,若不先接住这种形态,
81
+ * 一条合法的等号写法会被误降级成「无法静态判定」。
82
+ */
83
+ const INLINE_PLACEHOLDER_FLAG_RE = /^-+[\w-]+=<[^>]*>$/;
84
+ /**
85
+ * 切词:引号内的整段算**一个词**(去引号),其余按非空白切(全审查 A2)。
86
+ *
87
+ * 为什么切词要认引号:`--schedule "0 3 * * *"` 的取值本身就是空格分隔的 5 段 CRON,
88
+ * `--body '{"opStart": 1}'` 的取值是带空格的 JSON —— 按裸空白切会把一个合法取值拆成多个
89
+ * 位置参数,把**正确内容判成违规**(check 自己的原则:误报比漏报更糟)。
90
+ *
91
+ * 原文形态(`raw`)是 A4 的前提:shell 语义下 `"a > b"` 里的 `>` 是**数据**(比较运算符),
92
+ * 只有**引号外**的 `>` 才是重定向。少了这个区分,`--sql 'SELECT a > b'` 会被误判成
93
+ * 「无法静态判定」。
94
+ */
95
+ function tokenize(text) {
96
+ const words = [];
97
+ for (const m of text.matchAll(QUOTED_TOKEN_RE)) {
98
+ if (m[1] !== undefined)
99
+ words.push({ text: m[1], raw: m[0] });
100
+ else if (m[2] !== undefined)
101
+ words.push({ text: m[2], raw: m[0] });
102
+ else
103
+ words.push({ text: m[3], raw: m[0] });
104
+ }
105
+ return words;
106
+ }
107
+ /**
108
+ * 切词的公开形态:只给词本身(去引号后的文本)。
109
+ */
110
+ export function splitWords(text) {
111
+ return tokenize(text).map((w) => w.text);
112
+ }
113
+ /**
114
+ * 剥围栏行的 `#` 注释,但**引号内的 `#` 保留**(全审查 A2)。
115
+ *
116
+ * `qiyu api call ticket.search --body '{"keyword":"a # b"}'` 的 `#` 在单引号里,是 JSON
117
+ * 取值的一部分;旧版直接拿 `COMMENT_RE`(行首或空白后的 `#` 到行尾)剥,会把取值从 `#`
118
+ * 处截断,留下半截 JSON 与两条假位置参数。
119
+ *
120
+ * 做法:先把每个引号段(含未闭合到行尾的那种)临时替换成不含空白、不含 `#` 的编号占位串,
121
+ * 按原口径剥注释,再换回原文。引号段整体可能含空白,编号占位串对切词等价(切词本来就
122
+ * 把引号段当一个词)。
123
+ */
124
+ function stripComment(line) {
125
+ const quoted = [];
126
+ const masked = line.replace(/'(?:[^']*)'|"(?:[^"]*)"|'(?:[^']*)$|"(?:[^"]*)$/g, (seg) => {
127
+ quoted.push(seg);
128
+ return `\u0000${quoted.length - 1}\u0000`;
129
+ });
130
+ const stripped = masked.replace(COMMENT_RE, '$1');
131
+ return stripped.replace(/\u0000(\d+)\u0000/g, (_, i) => quoted[Number(i)]);
132
+ }
133
+ /**
134
+ * 把正文切成待扫描的片段,并按围栏块归组。
135
+ *
136
+ * 围栏行产出的片段 = 行内代码片段 + 夹在片段之间的裸文本(交错产出保持源顺序,同一
137
+ * 内容不会被两个面各记一次);两者都按「行 + 内容」去重。散文行只取行内代码。
138
+ */
139
+ function collectSurfaces(text) {
140
+ const segments = [];
141
+ const seen = new Set();
142
+ const push = (text, line) => {
143
+ const trimmed = text.trim();
144
+ if (trimmed === '')
145
+ return;
146
+ const key = `${line}\u0000${trimmed}`;
147
+ if (seen.has(key))
148
+ return;
149
+ seen.add(key);
150
+ segments.push({ text: trimmed, line });
151
+ };
152
+ const blocks = [];
153
+ let inFence = false;
154
+ let openLen = 0;
155
+ let blockLines = [];
156
+ const closeBlock = () => {
157
+ const lines = blockLines;
158
+ blockLines = [];
159
+ if (lines.length === 0)
160
+ return;
161
+ // 反引号一并剥掉:围栏里 `` `SELECT * FROM x` `` 的反引号是排版不是 SQL 的一部分。
162
+ // 空行不参与拼接,但保留自己的行号 —— 报告定位用 `SELECT` 真正所在的那一行。
163
+ const stripped = lines
164
+ .map((l) => ({ text: l.text.replace(/`/g, '').trim(), line: l.line }))
165
+ .filter((l) => l.text !== '');
166
+ if (stripped.length === 0)
167
+ return;
168
+ const joined = stripped.map((l) => l.text).join('\n');
169
+ if (!(SELECT_RE.test(joined) && FROM_RE.test(joined)))
170
+ return;
171
+ const hit = stripped.find((l) => SELECT_RE.test(l.text));
172
+ blocks.push({
173
+ text: joined,
174
+ selectLine: hit ? hit.line : stripped[0].line,
175
+ firstLine: lines[0].line,
176
+ lastLine: lines[lines.length - 1].line,
177
+ });
178
+ };
179
+ const lines = text.split('\n');
180
+ for (let i = 0; i < lines.length; i++) {
181
+ // 行号按 `\n` 计;CRLF 文档里行尾的 `\r` 属于行分隔符而不是内容,去掉它,
182
+ // 否则 `qiyu sync status\r` 的最后一个词会带上 `\r`,flag/路径切分会失真。
183
+ const raw = lines[i].replace(/\r$/, '');
184
+ const line = i + 1;
185
+ if (!inFence) {
186
+ const open = FENCE_OPEN_RE.exec(raw);
187
+ if (open) {
188
+ inFence = true;
189
+ openLen = open[1].length;
190
+ continue;
191
+ }
192
+ }
193
+ else {
194
+ const close = FENCE_CLOSE_RE.exec(raw);
195
+ if (close && close[1].length >= openLen) {
196
+ inFence = false;
197
+ closeBlock();
198
+ continue;
199
+ }
200
+ }
201
+ if (inFence) {
202
+ // 围栏内容行:先剥注释(引号内的 `#` 保留),再按源文本顺序拆成「行内片段 + 夹在
203
+ // 中间的裸文本」两个面。交错产出(而不是先收行内再收裸文本)是为了让 commands
204
+ // 顺序与原文一致。
205
+ const noComment = stripComment(raw);
206
+ let cursor = 0;
207
+ for (const m of noComment.matchAll(INLINE_CODE_RE)) {
208
+ push(noComment.slice(cursor, m.index), line);
209
+ push(m[1], line);
210
+ cursor = m.index + m[0].length;
211
+ }
212
+ push(noComment.slice(cursor), line);
213
+ blockLines.push({ text: noComment, line });
214
+ continue;
215
+ }
216
+ // 行内代码:一行里可以出现多个片段,各自计数(同内容同行只记一次)。
217
+ for (const m of raw.matchAll(INLINE_CODE_RE))
218
+ push(m[1], line);
219
+ }
220
+ if (inFence)
221
+ closeBlock();
222
+ return { segments, blocks };
223
+ }
224
+ /**
225
+ * 无法静态判定的信号。占位符之前出现 → 整条记 unverifiable(不阻塞);占位符之后出现 →
226
+ * 到此为止(右侧是另一条命令或重定向目标,它的 flag / 位置参数不属于本命令)。
227
+ *
228
+ * ⚠️ 复合 / 重定向符号与 `|` **同等对待**(全审查 A4):旧版只认 `|`,于是
229
+ * `qiyu store init && qiyu sync run` 里的 `&&` / `qiyu` / `sync` / `run` 被当成位置参数
230
+ * 报四条违规,而 `qiyu store init | tee log` 正确降级为 warning —— 同一族 shell 组合语法
231
+ * 两极分化,文档作者被迫拆行。
232
+ *
233
+ * ⚠️ 占位符判定在前:整个词是 `<...>` 的(`<SQL>`、`<表>`)先被 PLACEHOLDER_RE 接走,
234
+ * 单个 `<` 才落到这里。所以 `qiyu query --sql <SQL> > out.json` 的 `>` 出现在占位符之后,
235
+ * 走「止步」分支而不是 unverifiable。
236
+ *
237
+ * 两个正则分开是刻意的(判据不同,理由见 hasShellOperator):
238
+ * · `SHELL_OPERATOR_RE` —— shell **结构**符号,只认**引号外**的;
239
+ * · `ELLIPSIS_RE` —— **内容级**省略信号,整词都认(与引号无关)。
240
+ */
241
+ const SHELL_OPERATOR_RE = /[|]|&&|;|>|</;
242
+ const ELLIPSIS_RE = /…|\.\.\./;
243
+ /**
244
+ * 一个词里是否含 shell 结构符号(引号外)或省略号。
245
+ *
246
+ * 两条判据的差别是有意的:
247
+ * · 结构符号(`|`/`&&`/`;`/`>`/`<`)看**引号外** —— 引号里的是数据;
248
+ * · 省略号(`…`/`...`)**整词**都看 —— 它不表示 shell 结构,只表示「这里有省略,
249
+ * 静态判不了」(`qiyu query --sql "SELECT * FROM x WHERE …"`)。
250
+ */
251
+ function hasShellOperator(word) {
252
+ if (ELLIPSIS_RE.test(word.text))
253
+ return true;
254
+ return SHELL_OPERATOR_RE.test(word.raw.replace(/'[^']*'|"[^"]*"/g, ''));
255
+ }
256
+ /**
257
+ * 导出给 `skill check` 的表名扫描:扫描面与 `extractRefs` 完全一致(行内代码 + 围栏内容行,
258
+ * 含缩进容忍 / 长度配对 / 围栏内反引号)。brief 规则 1「只在行内代码与围栏块里扫」若由
259
+ * Task 6 重写一遍围栏解析,必然与这里的逻辑漂移 —— 复用是唯一不漂的写法。
260
+ * 占位符 / 管道等命令语义不在这里做,本函数只回答「哪些文本算代码面」。
261
+ */
262
+ export function collectSegments(text) {
263
+ return collectSurfaces(text).segments;
264
+ }
265
+ /** `--table=<表>` → `--table`:Task 6 比对的是 flag 名,等号右侧取值不参与比对。 */
266
+ function normalizeFlag(word) {
267
+ const eq = word.indexOf('=');
268
+ return eq === -1 ? word : word.slice(0, eq);
269
+ }
270
+ /**
271
+ * 扫描一个片段里的命令引用。
272
+ *
273
+ * refs 层**只提取、不判断**(本文件的分层约定):它不认识命令树,所以
274
+ * · 不判断「哪个 token 是 flag 的取值」—— 旧版在这里一刀切吞掉 flag 紧邻的词,
275
+ * bool flag(`--full`)之后的位置参数也被吞掉,`skill check` 的位置参数域校验
276
+ * 因此整段失效(审查 A1),flag 的位置也被抹平(审查 A3)。现在 `tokens` 原样保留
277
+ * 全部 token,由 check 层按 `spec.flags` 的 `kind` 重建位置参数。
278
+ * · 不判断「哪些 token 是命令路径」—— 同样交给 check 层(它有命令树)。
279
+ *
280
+ * 这里仍然要裁定的三件事:
281
+ * · **切词**:认引号(`splitWords`),`--schedule "0 3 * * *"` 是一个取值不是五个词
282
+ * (审查 A2)。围栏行的 `#` 注释也认引号(`stripComment`)。
283
+ * · **占位符**:整词 `<...>` 是模板不是字面值。它**留在 `tokens` 里**(否则
284
+ * `--table <表>` 会被误判成「`--table` 缺少取值」),但命令路径到此为止 ——
285
+ * `qiyu query <表>` 的 `<表>` 不是子命令。
286
+ * · **无法静态判定的符号**:`|`、`…`、`...`、`&&`、`;`、`>`、`<`(审查 A4)。占位符
287
+ * 之前遇到 → 整条记 unverifiable(warning,不阻塞);占位符之后遇到 → 到此为止
288
+ * (管道 / 重定向右侧是另一条命令或别的目标,不属于本命令)。
289
+ */
290
+ function scanCommand(content, line, refs) {
291
+ const m = COMMAND_RE.exec(content);
292
+ if (!m)
293
+ return;
294
+ const words = tokenize(m[1]);
295
+ const tokens = [];
296
+ const flags = [];
297
+ let closed = false;
298
+ for (const word of words) {
299
+ const text = word.text;
300
+ if (isPlaceholderToken(text)) {
301
+ // 占位符是前一个 flag 的取值或独立位置参数:命令结构在此封口。它仍进 tokens ——
302
+ // check 层要靠它判断「flag 的取值是模板而不是缺值」。
303
+ closed = true;
304
+ tokens.push(text);
305
+ continue;
306
+ }
307
+ // 引号里的符号是**数据**(`--sql 'SELECT a > b'` 的 `>` 是比较运算符),只有引号外的
308
+ // 才算 shell 语法(A4)。`hasShellOperator` 按**原文**里的真闭合引号段排除,因此
309
+ // `{"k":"a>b"}` 这种引号夹在词中间的形态也判得对。
310
+ if (hasShellOperator(word) && !INLINE_PLACEHOLDER_FLAG_RE.test(text)) {
311
+ if (!closed) {
312
+ // 选择 / 省略 / 复合 / 重定向符号:整条无法判定,记入 unverifiable 而不是猜结构。
313
+ refs.unverifiable.push({ text: content, line, reason: REASON_CHOICE });
314
+ return;
315
+ }
316
+ // 占位符之后:右侧是另一条命令或重定向目标,它的 flag / 位置参数不属于本命令。
317
+ break;
318
+ }
319
+ // flag 判定:`-` 开头一律记为 flag(提取层不判断「这个 token 是不是某个 flag 的取值」
320
+ // ——那要看 spec 的 kind,属 check 层)。
321
+ //
322
+ // ⚠️ 复审纠正:曾经改过「单横线只有单字母短旗才算」,理由是「`--since -7d` 是合法调用」。
323
+ // 那个前提**是错的**:真实 CLI 对 `query --since -7d` 退 2(`--since 无法解析:-7d`),
324
+ // 对 `query --timeout -1` 同样退 2(「必须是非负数」)。解析器的值位守卫只拒 `--` 开头,
325
+ // 但**取值语义层**(`parseTimeArg` / `parseTimeoutMs`)会拒绝它。改了之后这两条非法调用
326
+ // 变成 check 零违规(漏报),比误报更糟。取值是否合法应由 check 层按真实语义校验。
327
+ if (text.startsWith('-')) {
328
+ flags.push({ name: normalizeFlag(text), tokenIndex: tokens.length });
329
+ }
330
+ tokens.push(text);
331
+ }
332
+ // 只有 flag / 占位符、没有命令词的 `qiyu --help` 之类不记成命令引用:`Refs.commands`
333
+ // 的语义是「正文声称存在这条命令路径」,只有 flag 的调用不构成这种声称(而且
334
+ // `--help` 是全局 flag,各命令都接受,记下来反而会让 check 用空路径去匹配、误报
335
+ // 未知命令)。
336
+ const flagIndexes = new Set(flags.map((f) => f.tokenIndex));
337
+ const hasCommandWord = tokens.some((t, i) => !flagIndexes.has(i) && !isPlaceholderToken(t));
338
+ if (!hasCommandWord)
339
+ return;
340
+ refs.commands.push({ tokens, flags, line });
341
+ }
342
+ function scanKind(content, line, refs) {
343
+ const m = KIND_RE.exec(content);
344
+ if (m)
345
+ refs.kinds.push({ name: m[1], line });
346
+ }
347
+ function scanSql(content, line, refs) {
348
+ // 只有 SELECT 没有 FROM(如 `SELECT 1`)不算:单值表达式不是「对某张表取数」,
349
+ // 也就没有可校验的序列。两个词都必须是独立词,避免 `SELECTED` / `FROMAGE` 误命中。
350
+ if (SELECT_RE.test(content) && FROM_RE.test(content)) {
351
+ refs.sqlSequences.push({ text: content, line });
352
+ }
353
+ }
354
+ /**
355
+ * 从 skill 正文里提取全部引用。返回顺序即出现顺序(按行、行内按片段出现位置);
356
+ * 围栏块级 SQL 兜底在最后统一收集,返回前按行稳定排序归位;
357
+ * 同一行同一内容只记一次(围栏面的裸文本与行内片段不双计),不同行不合并、不去重 ——
358
+ * 校验方需要逐处报行号。
359
+ */
360
+ export function extractRefs(text) {
361
+ const refs = { commands: [], kinds: [], sqlSequences: [], unverifiable: [] };
362
+ const { segments, blocks } = collectSurfaces(text);
363
+ for (const segment of segments) {
364
+ scanCommand(segment.text, segment.line, refs);
365
+ scanKind(segment.text, segment.line, refs);
366
+ scanSql(segment.text, segment.line, refs);
367
+ }
368
+ // 围栏块级 SQL 兜底:`SELECT id` 与 `FROM sessions` 分两行时逐行各缺一词,只有整块
369
+ // 能看见。块内已按行/片段记过 SQL 的不再按块重记,避免同一序列双报。
370
+ for (const block of blocks) {
371
+ const hit = refs.sqlSequences.some((s) => s.line >= block.firstLine && s.line <= block.lastLine);
372
+ if (!hit)
373
+ refs.sqlSequences.push({ text: block.text, line: block.selectLine });
374
+ }
375
+ // 块级兜底统一 append 在最后,与逐行条目混排时行号会乱序;稳定排序归位,兑现
376
+ // 「返回顺序即出现顺序」的承诺(同行的多条保持插入顺序)。
377
+ refs.sqlSequences.sort((a, b) => a.line - b.line);
378
+ return refs;
379
+ }
@@ -0,0 +1,137 @@
1
+ // src/store/config.ts
2
+ //
3
+ // store 配置解析(命令行 > 环境变量 > 配置文件 > 内置默认,spec §3.2)。
4
+ //
5
+ // ⚠️ **G1 起「配置文件」这层载体抽到了 `core/config.ts`**:auth/api 需要读写同一份
6
+ // 文件,而它们按分层红线不得 import `store/`。本文件保留全部 store 语义
7
+ // (backend 枚举、路径展开、行为参数上界),配置文件的读取/键校验/权限检查
8
+ // 一律委托 core 层 —— 这样 auth 与 store 看到的「未知键」「JSON 畸形」「权限过宽」
9
+ // 是同一句话,不会出现两套口径。
10
+ import { homedir } from 'node:os';
11
+ import { dirname, join, isAbsolute } from 'node:path';
12
+ import { configPathFor, loadConfigFile, checkPermissions, configHasCredentials } from '../core/config.js';
13
+ export const DEFAULTS = {
14
+ relPath: join('.qiyu', 'duckdb', 'qiyu.duckdb'),
15
+ backend: 'duckdb',
16
+ readOnlyRetryMs: 30000,
17
+ batchSize: 1000,
18
+ };
19
+ // store 块内的已知键 —— 未知键 fail-closed(spec §3.3)。
20
+ // ⚠️ options(D-T13):配置面的「透传不校验内容」键——StoreConfig.options 的落点。
21
+ // config 层只保证它是对象、原样透传(消费方如 sync run 的 knowledgeRobotIds 自行
22
+ // 校验内容);列进已知集让未知键检查放行。
23
+ const KNOWN_STORE = new Set(['backend', 'path', 'readOnlyRetryMs', 'batchSize', 'options']);
24
+ function assertKnownKeys(obj, known, prefix) {
25
+ for (const k of Object.keys(obj)) {
26
+ if (!known.has(k))
27
+ throw new Error(`配置文件未知键:${prefix}${k}`);
28
+ }
29
+ }
30
+ function expandHome(p, home) {
31
+ return p === '~' ? home : p.startsWith('~/') ? join(home, p.slice(2)) : p;
32
+ }
33
+ function assertPositiveInt(v, key, max) {
34
+ if (typeof v !== 'number' || !Number.isInteger(v) || v <= 0) {
35
+ throw new Error(`配置文件 ${key} 必须是正整数,实际为 ${JSON.stringify(v)}`);
36
+ }
37
+ // ⚠️ 上界守卫(R 组 R4):readOnlyRetryMs=1e15 会让 status 撞锁时挂起 ~31 年
38
+ //(assertPositiveInt 放行 1e15)—— 挂起级 DoS。超上界 → usage 拒绝点名键路径。
39
+ if (max !== undefined && v > max) {
40
+ throw new Error(`配置文件 ${key} 不得超过 ${max},实际为 ${JSON.stringify(v)}`);
41
+ }
42
+ return v;
43
+ }
44
+ /**
45
+ * 当前进程的三元环境变量(架构审查 M-3)。
46
+ *
47
+ * 此前 6 个调用点各自手写 `{ QIYU_DB_PATH: process.env.QIYU_DB_PATH, … }` ——
48
+ * `resolveStoreConfig` 对缺省 env 是**静默忽略**(`opts.env ?? {}`),所以加第 4 个
49
+ * 环境变量时漏改任何一处,那条命令就会静默用默认库、与同族命令分叉。
50
+ * 调用方应传 `env: currentStoreEnv()`;需要注入的测试自己传对象。
51
+ */
52
+ export function currentStoreEnv() {
53
+ return {
54
+ QIYU_DB_PATH: process.env.QIYU_DB_PATH,
55
+ QIYU_STORE_BACKEND: process.env.QIYU_STORE_BACKEND,
56
+ QIYU_PROFILE: process.env.QIYU_PROFILE,
57
+ };
58
+ }
59
+ /**
60
+ * 解析 store 配置:命令行 > 环境变量 > 配置文件 > 内置默认(spec §3.2)。
61
+ * ⚠️ 只读不写;写入走 `auth login`(`commands/auth.ts` → `core/config.ts`)。
62
+ */
63
+ export function resolveStoreConfig(opts = {}) {
64
+ const home = opts.home ?? homedir();
65
+ const configPath = opts.configPath ?? configPathFor(home);
66
+ const env = opts.env ?? {};
67
+ const flags = opts.flags ?? {};
68
+ // ⚠️ 读文件与结构解析都在 core 层 —— 「未知键 / JSON 畸形 / 形态不对」的文案
69
+ // 与 auth/api 看到的是同一份,不会出现两套口径。
70
+ const { file, exists: configExists } = loadConfigFile(configPath);
71
+ if (configExists) {
72
+ // ⚠️ 权限检查(spec §3.4):文件权限过宽 → 警告;**含凭证时升级为拒绝**(G1)。
73
+ const perm = checkPermissions(configPath, {
74
+ hasCredentials: configHasCredentials(file),
75
+ onWarn: (m) => process.stderr.write(`${m}\n`),
76
+ });
77
+ if (!perm.ok) {
78
+ // 拒绝路径抛普通 Error(无 kind)→ 调用方按用法错误处理。
79
+ // ⚠️ 文案必须点名**要执行的动作**,否则用户只知道自己错了。
80
+ const dir = dirname(configPath);
81
+ throw new Error(perm.reason === 'file'
82
+ ? `配置文件 ${configPath} 含凭证但权限过宽(group/other 可访问),已拒绝读取 —— 请执行 chmod 600 ${configPath}`
83
+ : `配置目录 ${dir} 权限过宽(group/other 可写,文件可被整体替换)且配置含凭证,已拒绝读取 —— 请执行 chmod 700 ${dir}`);
84
+ }
85
+ }
86
+ const profiles = file.profiles;
87
+ for (const [name, prof] of Object.entries(profiles)) {
88
+ const store = prof.store;
89
+ if (store === undefined)
90
+ continue;
91
+ // store 块的**语义**校验仍在本层(core 只管「是对象、键已知」的通用形态)。
92
+ assertKnownKeys(store, KNOWN_STORE, `profiles.${name}.store.`);
93
+ // options:透传不校验内容(D-T13),但形态必须是对象(数组/标量显式拒绝)。
94
+ if (store.options !== undefined &&
95
+ (store.options === null || typeof store.options !== 'object' || Array.isArray(store.options))) {
96
+ throw new Error(`配置文件 profiles.${name}.store.options 必须是对象`);
97
+ }
98
+ }
99
+ const profileName = flags.profile ?? env.QIYU_PROFILE ?? file.defaultProfile ?? 'default';
100
+ const prof = profiles[profileName] ?? {};
101
+ const storeBlock = (prof.store ?? {});
102
+ const rawBackend = flags.backend ?? env.QIYU_STORE_BACKEND ?? storeBlock.backend ?? DEFAULTS.backend;
103
+ if (rawBackend !== 'duckdb') {
104
+ throw new Error(`未知后端:${rawBackend}。目前仅支持 duckdb`);
105
+ }
106
+ // ⚠️ path 类型守卫(K 组 M1):配置写数字/对象时,expandHome 会对非字符串调
107
+ // startsWith 抛裸英文 TypeError,且不点名键路径 —— 违反 fail-closed 点名键路径约定。
108
+ if (storeBlock.path !== undefined && typeof storeBlock.path !== 'string') {
109
+ throw new Error(`配置文件 profiles.${profileName}.store.path 必须是字符串`);
110
+ }
111
+ const rawPath = flags.db ?? env.QIYU_DB_PATH ?? storeBlock.path ?? DEFAULTS.relPath;
112
+ // ⚠️ 空串守卫(K 组 M4):`--db ""`(脚本里变量未设的典型形态)会穿过所有前置检查
113
+ // 直达 DuckDB,产出难懂的底层错误。空串不是合法路径,usage 拒绝。
114
+ if (rawPath.trim() === '') {
115
+ throw new Error('数据库路径不能为空(--db / QIYU_DB_PATH / store.path 均为空)');
116
+ }
117
+ const readOnlyRetryMs = storeBlock.readOnlyRetryMs === undefined
118
+ ? DEFAULTS.readOnlyRetryMs
119
+ : assertPositiveInt(storeBlock.readOnlyRetryMs, `profiles.${profileName}.store.readOnlyRetryMs`, 300_000);
120
+ const batchSize = storeBlock.batchSize === undefined
121
+ ? DEFAULTS.batchSize
122
+ : assertPositiveInt(storeBlock.batchSize, `profiles.${profileName}.store.batchSize`, 100_000);
123
+ // 相对路径(内置默认 relPath)按 home 解析;~ 前缀展开为 home(M-6)
124
+ const expanded = expandHome(rawPath, home);
125
+ const finalPath = isAbsolute(expanded) ? expanded : join(home, expanded);
126
+ return {
127
+ config: {
128
+ backend: rawBackend, path: finalPath, readOnlyRetryMs, batchSize,
129
+ // options 透传不校验内容(D-T13):消费方(sync run 的 knowledgeRobotIds 等)自校验。
130
+ ...(storeBlock.options !== undefined
131
+ ? { options: storeBlock.options }
132
+ : {}),
133
+ },
134
+ configPath,
135
+ configExists,
136
+ };
137
+ }