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,429 @@
1
+ // src/skill/check.ts —— `skill check` 的校验逻辑:把 skill 正文里的引用与 CLI 的真实契约
2
+ // (命令树 / 表名 / 错误 kind / 位置参数取值域)比对,产出三档判定(设计稿 D3):
3
+ //
4
+ // · violations:引用不存在的命令 / flag / kind / 位置参数取值;flag 写错了位置;正文
5
+ // 出现表名;出现完整 SQL 序列;推荐了被显式拒绝的 flag(`--pretty`)。
6
+ // · warnings:无法静态判定的引用(含管道 / 选择 / 复合命令符号等),不阻塞,但要指认位置。
7
+ // · 两者皆空:通过。
8
+ //
9
+ // 分工边界:`refs.ts` 只负责**提取**(哪些文本算引用、切成哪些 token),本文件只负责
10
+ // **判定**。表名扫描复用 `collectSegments` 而不是重写一遍围栏解析 —— 两处扫描面一旦各写
11
+ // 一遍必然漂移。
12
+ //
13
+ // 契约事实由调用方通过 `CheckContext` 注入(`COMMAND_TREE` / `TABLES` / `ERROR_KINDS` /
14
+ // 四个取值域闭集),本文件不 import `cli.ts`(会拉进整个 CLI 入口图,层级倒置),也不
15
+ // import `SYNC_TASKS` / `allEndpoints` / `REPORT_TABLES`(那会把 registry 的 `specs.json`
16
+ // 拉进 skill 层并改变它的依赖面),只从 commands 层取 `findSpec` / `CommandSpec` 与
17
+ // `Domain` 类型。分层方向:`skill/` 可以 import `commands/`、`store/`、`core/`,反向禁止。
18
+ //
19
+ // ⚠️ 校验器**不理解否定语境**:`` `tags` `` 出现在「不是 tags 表」这种句子里同样命中
20
+ // `table_name`。skill 正文任何位置都不能写表名,包括用来举例说明「不要写表名」的地方。
21
+ import { readFileSync, readdirSync, lstatSync, statSync, realpathSync } from 'node:fs';
22
+ import { join, resolve, sep } from 'node:path';
23
+ import { findSpec } from '../commands/spec-types.js';
24
+ import { collectSegments, extractRefs, isPlaceholderToken } from './refs.js';
25
+ /**
26
+ * 「第一个位置参数必须紧跟命令词」的判据:**只**读 spec 的第一个槽位(`PositionalSpec.first`)。
27
+ *
28
+ * 真实 CLI 里 `api call` 把 `argv[0]` 直接当接口 id(`callOne` 的 `const [id] = argv`),
29
+ * flag 写在它前面会得到「接口 id 必须是第一个参数」并退出 2。其余命令(`api schema` /
30
+ * `sync run` / `db describe` / `stats fields`)的解析器先剥 flag,flag 与位置参数可以交错,
31
+ * **不能**一并套用这条规则 —— 否则 `qiyu sync run --full dim.staff` 这种合法写法会被误报。
32
+ *
33
+ * ⚠️ 这里**不再**维护命令路径清单(G1 的 `FIRST_POSITIONAL_STRICT` 已删):那份清单是
34
+ * `CommandSpec` 之外的第二事实源,新增同类命令时只改解析器、漏改清单就会静默失效。
35
+ * 现在唯一的声明处是各命令模块的 spec(`api.ts` 的 `API_SPECS`),由
36
+ * `tests/commands/command-tree.test.ts` 的「解析器行为 vs spec 标记」反向对齐用例守着。
37
+ */
38
+ function hasFirstPositionalRule(spec) {
39
+ return spec.positionals[0]?.first === true;
40
+ }
41
+ /** 转义正则元字符:表名来自 `CheckContext` 注入,按字面匹配而不是正则模式。 */
42
+ function escapeRegExp(text) {
43
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
44
+ }
45
+ /** 去掉所有 flag token(取值留在原地)——用于「flag 落在子命令位」时认出用户想写的命令。 */
46
+ function dropFlags(tokens, flagAt) {
47
+ return tokens.filter((_, i) => !flagAt.has(i));
48
+ }
49
+ /**
50
+ * 去掉所有 flag token **连同它们的取值**(假定每个 flag 都吃一个值)——同上。
51
+ *
52
+ * `qiyu db --profile prod tables` 里 `prod` 是 `--profile` 的取值,剥掉它之后剩下的
53
+ * `['db','tables']` 才能匹配到 `db tables` 这条 spec。
54
+ */
55
+ function dropFlagsAndValues(tokens, flagAt) {
56
+ const out = [];
57
+ for (let i = 0; i < tokens.length; i++) {
58
+ if (flagAt.has(i)) {
59
+ const next = tokens[i + 1];
60
+ if (next !== undefined && !flagAt.has(i + 1))
61
+ i++; // 连取值一起吃掉
62
+ continue;
63
+ }
64
+ out.push(tokens[i]);
65
+ }
66
+ return out;
67
+ }
68
+ /**
69
+ * 校验一条命令引用:命中 spec、比对 flag 接受集、判 flag 的位置、重建位置参数并校验取值域。
70
+ *
71
+ * 判定顺序(同一行内多条违规的产出顺序):
72
+ * 1. 命令路径:`findSpec` 最长前缀匹配,未命中 → `unknown_command`;
73
+ * 2. flag 接受集:**先查 `spec.rejected`**,再查 `spec.flags` 的完整接受集。顺序是硬要求 ——
74
+ * `--pretty` 同时在 `GLOBAL_FLAGS`(因而在每条 spec 的 `flags` 里)与 `REJECTED_FLAGS`
75
+ * 里,反过来先查 `flags` 会把它判成合法,`rejected_flag` 永远报不出来;
76
+ * 3. flag 的位置:落在命令路径之内 → `flag_before_subcommand`;落在「第一个位置参数」槽位
77
+ * → `flag_before_positional`;值位 flag 缺取值 → `flag_missing_value`;
78
+ * 4. 位置参数取值域:命令词之后的字面 token 逐个按 `spec.positionals[i].domain` 查注入的
79
+ * 闭集;不在闭集 → `unknown_positional`,位置参数个数超过 spec 声明同样违规。
80
+ */
81
+ function checkCommand(cmd, ctx, violations) {
82
+ const flagAt = new Map();
83
+ for (const flag of cmd.flags)
84
+ flagAt.set(flag.tokenIndex, flag);
85
+ // 命令路径 = 第一个占位符之前的 token(占位符是取值模板,不是子命令)。
86
+ const cut = cmd.tokens.findIndex(isPlaceholderToken);
87
+ const head = cut === -1 ? cmd.tokens : cmd.tokens.slice(0, cut);
88
+ // ⚠️ `findSpec` 必须拿到**原始 argv**(flag 也在里面):`spec-types.ts` 的守卫「路径位
89
+ // 出现以 `-` 开头的 token 即不命中」正是为 `qiyu db --profile prod tables` 这类准备的
90
+ // ——真实分派取 argv[0] 当子命令,flag 落在那里必报「未知子命令」退出 2。旧版 refs 先把
91
+ // flag 剥掉,那条守卫在生产路径上永不触发(审查 A3)。
92
+ let spec = findSpec(ctx.tree, head);
93
+ if (!spec) {
94
+ // flag 落在子命令位时原始 argv 必然不命中(真实分派把 argv[0]/argv[1] 当子命令)。
95
+ // 这里重试两次,只为**认出**用户想写的是哪条命令,好报更准确的 flag 位置违规:
96
+ // ① 只剥 flag token(取值留在原地)→ `qiyu db --profile tables` 这类;
97
+ // ② 连取值一起剥(假定每个 flag 都吃一个值)→ `qiyu db --profile prod tables` 这类。
98
+ for (const candidate of [dropFlags(head, flagAt), dropFlagsAndValues(head, flagAt)]) {
99
+ const hit = findSpec(ctx.tree, candidate);
100
+ if (hit && (!spec || hit.path.length > spec.path.length))
101
+ spec = hit;
102
+ }
103
+ }
104
+ if (!spec) {
105
+ violations.push({
106
+ line: cmd.line,
107
+ rule: 'unknown_command',
108
+ detail: `未知命令:qiyu ${head.join(' ')}(命令树里没有这条路径)`,
109
+ });
110
+ return;
111
+ }
112
+ const accepted = new Map(spec.flags.map((f) => [f.name, f]));
113
+ // 2:flag 接受集。
114
+ for (const flag of cmd.flags) {
115
+ if (spec.rejected.includes(flag.name)) {
116
+ // ⚠️ 必须先于 accepted 判断:--pretty 同时属于两者(见函数注释)。
117
+ violations.push({
118
+ line: cmd.line,
119
+ rule: 'rejected_flag',
120
+ detail: `qiyu ${spec.path.join(' ')} 的 ${flag.name} 已知但未实现,别用`,
121
+ });
122
+ }
123
+ else if (!accepted.has(flag.name)) {
124
+ violations.push({
125
+ line: cmd.line,
126
+ rule: 'unknown_flag',
127
+ detail: `qiyu ${spec.path.join(' ')} 不接受此 flag:${flag.name}`,
128
+ });
129
+ }
130
+ }
131
+ // 3a:flag 落在命令路径之内(`qiyu db --profile prod tables`)——真实分派把 argv[0]/
132
+ // argv[1] 当子命令,flag 落在那里必报「未知子命令」退出 2。
133
+ //
134
+ // ⚠️ 命中这一条时**不再重建位置参数**:命令词与 flag 取值在 token 流里的相对位置已经
135
+ // 不可信(`--profile prod tables` 里 `prod` 到底是取值还是子命令,取决于真实解析器的
136
+ // 顺序),在这种状态下再报「取值不在域闭集里」是**凭空的第二处指控**。一条命令一处
137
+ // 定位清楚的违规,比叠两条可能不实的更有用。
138
+ const inPath = cmd.flags.filter((f) => f.tokenIndex < spec.path.length);
139
+ if (inPath.length > 0) {
140
+ violations.push({
141
+ line: cmd.line,
142
+ rule: 'flag_before_subcommand',
143
+ detail: `qiyu ${spec.path.join(' ')}:flag 必须写在子命令之后,`
144
+ + `${inPath.map((f) => f.name).join('、')} 出现在子命令位`
145
+ + '(真实 CLI 报「未知子命令」,退出码 2)',
146
+ });
147
+ return;
148
+ }
149
+ // 3b:少数命令把 argv[0] 直接当第一个位置参数(`api call` 的接口 id)——flag 落在那个
150
+ // 槽位上同样退出 2(`qiyu api call --yes ticket.search`)。判据来自 spec 的槽位标记
151
+ // (`PositionalSpec.first`),本文件不再维护命令清单。
152
+ if (hasFirstPositionalRule(spec)) {
153
+ const atSlot = cmd.flags.find((f) => f.tokenIndex === spec.path.length);
154
+ if (atSlot) {
155
+ violations.push({
156
+ line: cmd.line,
157
+ rule: 'flag_before_positional',
158
+ detail: `qiyu ${spec.path.join(' ')}:第一个位置参数必须紧跟命令词,`
159
+ + `${atSlot.name} 写在了它前面(真实 CLI 退出码 2)`,
160
+ });
161
+ }
162
+ }
163
+ // 4:重建位置参数。按 `spec.flags` 的 `kind` 决定 flag 吃不吃下一个 token:
164
+ // · `bool` → **不吃**(`--full` 之后的任务 id 是位置参数,不是 flag 取值 —— 审查 A1:
165
+ // 旧版一律吞掉,位置参数域校验整段失效,`qiyu sync run --full no_such_task` 假绿);
166
+ // · `value` / `repeatable` → 吃下一个 token(字面值或 `<占位符>` 模板);
167
+ // · 未知名 / 被拒名 → 不吃(它本身已会报 unknown_flag / rejected_flag,把后一个 token
168
+ // 还回位置参数更安全)。
169
+ const values = [];
170
+ for (let i = 0; i < cmd.tokens.length; i++) {
171
+ const flag = flagAt.get(i);
172
+ if (flag !== undefined) {
173
+ const slot = accepted.get(flag.name);
174
+ if (slot === undefined || spec.rejected.includes(flag.name) || slot.kind === 'bool')
175
+ continue;
176
+ // `--flag=<值>`:取值已经内联在同一个 token 里,不吃下一个。
177
+ if (cmd.tokens[i].includes('='))
178
+ continue;
179
+ const next = cmd.tokens[i + 1];
180
+ if (next === undefined || flagAt.has(i + 1)) {
181
+ violations.push({
182
+ line: cmd.line,
183
+ rule: 'flag_missing_value',
184
+ detail: `qiyu ${spec.path.join(' ')} 的 ${flag.name} 缺少取值(真实 CLI 退出码 2)`,
185
+ });
186
+ continue;
187
+ }
188
+ i++; // 取值被吃掉:它不是位置参数
189
+ continue;
190
+ }
191
+ if (i < spec.path.length)
192
+ continue; // 命令词
193
+ if (isPlaceholderToken(cmd.tokens[i]))
194
+ continue; // 占位符是模板,不是字面值
195
+ values.push(cmd.tokens[i]);
196
+ }
197
+ // 位置参数取值域。槽位数用尽时按**最后一个**槽位处理:repeatable(`sync run [任务...]`)
198
+ // 就把余下取值继续按它的域比;不 repeatable(`db describe <表>` 只收一个)才判「超量」。
199
+ // ⚠️ 对合法的变长调用(`qiyu sync run a b`,两个都是真实任务 id)判超量是误报——
200
+ // 把正确内容判成错误比漏报更糟(终审 fix 自查)。
201
+ for (let i = 0; i < values.length; i++) {
202
+ const value = values[i];
203
+ const slot = spec.positionals[i]
204
+ ?? (spec.positionals.length > 0 && spec.positionals[spec.positionals.length - 1].repeatable
205
+ ? spec.positionals[spec.positionals.length - 1]
206
+ : undefined);
207
+ if (slot === undefined) {
208
+ violations.push({
209
+ line: cmd.line,
210
+ rule: 'unknown_positional',
211
+ detail: `qiyu ${spec.path.join(' ')} 只接受 ${spec.positionals.length} 个位置参数,`
212
+ + `多出的不接受:${value}`,
213
+ });
214
+ continue;
215
+ }
216
+ if (!ctx.domains[slot.domain].includes(value)) {
217
+ violations.push({
218
+ line: cmd.line,
219
+ rule: 'unknown_positional',
220
+ detail: `qiyu ${spec.path.join(' ')} 的位置参数 ${slot.name} 不接受此值:${value}`
221
+ + `(不在 ${slot.domain} 闭集里)`,
222
+ });
223
+ }
224
+ }
225
+ }
226
+ /**
227
+ * 校验一份 skill 文档正文。
228
+ *
229
+ * 判定顺序(violations 最终按行稳定排序,便于按出现位置阅读):
230
+ * 1. 命令路径:`findSpec` 最长前缀匹配,未命中 → `unknown_command`;
231
+ * 2. flag:**先查 `spec.rejected`**,再查 `spec.flags` 的完整接受集。顺序是硬要求 ——
232
+ * `--pretty` 同时在 `GLOBAL_FLAGS`(因而在每条 spec 的 `flags` 里)与 `REJECTED_FLAGS`
233
+ * 里,反过来先查 `flags` 会把它判成合法,`rejected_flag` 永远报不出来;
234
+ * 3. flag 的位置与缺值(见 checkCommand 的注释);
235
+ * 4. 位置参数取值域:命令词之后的字面 token 逐个按 `spec.positionals[i].domain` 查注入的
236
+ * 闭集;不在闭集 → `unknown_positional`,位置参数个数超过 spec 声明同样违规;
237
+ * 5. 表名:只在 `collectSegments` 的代码面片段里扫(与 refs 扫描面一致),词边界、
238
+ * 大小写敏感;
239
+ * 6. SQL 序列:`extractRefs` 已按行 / 围栏块识别;
240
+ * 7. `kind: x`:对 `ERROR_KINDS` 比对;
241
+ * 8. 无法静态判定的命令(含选择 / 省略 / 复合命令符号)进 warnings,不进 violations。
242
+ */
243
+ export function checkSkillDoc(text, ctx) {
244
+ const violations = [];
245
+ const warnings = [];
246
+ const refs = extractRefs(text);
247
+ // 1 + 2 + 3 + 4:命令路径、flag 接受集与位置、位置参数取值域。
248
+ for (const cmd of refs.commands)
249
+ checkCommand(cmd, ctx, violations);
250
+ // 5:表名。代码面片段由 refs.ts 统一收集(行内代码 + 围栏内容行),这里只做词边界匹配。
251
+ //
252
+ // 词边界(审查 52):`(?<![\w-])` 挡住 `my_sessions` / `all_tags` 这类以表名结尾的标识符,
253
+ // `(?![\w-])` 挡住 `staffing`。另加两条**点号**边界:
254
+ // · 左 `(?<!\w\.)`:点号后紧跟词字符时不匹配(`dim.staff`、`staff.list.new` 里的
255
+ // `staff` 是标识符的一部分,不是表名);
256
+ // · 右 `(?!\.\w)`:同理,`staff.list.new` 整体命中不到表名 `staff`。
257
+ // ⚠️ 右边界刻意**不**排除句末的 `staff.`(`staff.` 后面没有词字符)——那确实是在提表名,
258
+ // 仍要命中。
259
+ // 大小写敏感(不加 `i`),避免把 `Staff` 之类的英文单词误判成表名。
260
+ // 表名先过 escapeRegExp:当前 TABLES 全是 `[a-z_]+` 所以不转义也安全,但 `tableNames`
261
+ // 是调用方注入的,契约上不能假定它永远只含标识符字符。
262
+ const matchers = ctx.tableNames.map((name) => ({
263
+ name,
264
+ re: new RegExp(`(?<![\\w-])(?<!\\w\\.)${escapeRegExp(name)}(?![\\w-])(?!\\.\\w)`),
265
+ }));
266
+ for (const segment of collectSegments(text)) {
267
+ for (const { name, re } of matchers) {
268
+ if (re.test(segment.text)) {
269
+ violations.push({
270
+ line: segment.line,
271
+ rule: 'table_name',
272
+ detail: `出现表名 ${name}:数据侧事实不得硬编码,改用 qiyu db tables 在运行时获取`,
273
+ });
274
+ }
275
+ }
276
+ }
277
+ // 6:SQL 关键字序列(`extractRefs` 已处理 SELECT/FROM 独立词、跨行块级判定)。
278
+ // detail 里把换行压成空格,避免多行块级序列把报告撑散。
279
+ for (const sql of refs.sqlSequences) {
280
+ violations.push({
281
+ line: sql.line,
282
+ rule: 'sql_sequence',
283
+ detail: `出现完整 SQL 关键字序列:${sql.text.replace(/\s+/g, ' ')}`,
284
+ });
285
+ }
286
+ // 7:错误 kind。
287
+ for (const kind of refs.kinds) {
288
+ if (!ctx.errorKinds.includes(kind.name)) {
289
+ violations.push({
290
+ line: kind.line,
291
+ rule: 'unknown_kind',
292
+ detail: `未知错误 kind:${kind.name}(ERROR_KINDS 里没有这个成员)`,
293
+ });
294
+ }
295
+ }
296
+ // 8:无法静态判定 → warning(设计稿 D3:退出码 0,不阻塞)。
297
+ for (const item of refs.unverifiable) {
298
+ warnings.push({ line: item.line, detail: `无法静态判定(${item.reason}):${item.text}` });
299
+ }
300
+ // 各规则按出现顺序产出,合并后按行稳定排序(V8 的 sort 是稳定排序),
301
+ // 同一行的多条保持「命令 → flag → 位置参数 → 表名 → SQL → kind」的规则顺序。
302
+ violations.sort((a, b) => a.line - b.line);
303
+ return { violations, warnings };
304
+ }
305
+ /**
306
+ * 递归收集目录下的 `.md` 文件(审查 13)。
307
+ *
308
+ * 为什么要递归:`installSkill` 的 `copyTree` 把 `src/skill/qiyu/` **整棵树**复制到实体
309
+ * 目录(设计稿 D5.1 预期过「拆分 references/」的形态),而 `checkSkillDir` 此前只读顶层
310
+ * `*.md` —— 正文一旦拆出子目录,里面的 `.md` 会被安装却**永远不被校验**,是安装与校验
311
+ * 的不对称。
312
+ *
313
+ * 四条约束:
314
+ * · 隐藏项(`.` 开头)跳过;
315
+ * · 符号链接只在**指向目录内部**时收(避免读目录外的内容);目录环另由递归栈上的
316
+ * realpath 集合挡住(终审 F2:只比 root 挡不住 `loop -> .` 这类指向祖先的链接,
317
+ * 此前靠路径长度撞 ENAMETOOLONG 才停,同一违规会被报几十次);
318
+ * · 目录不存在 / 不可读时**抛错**(由调用方守卫),不静默当成「没有文件」;
319
+ * · 返回的相对路径用**逻辑路径**(相对被检查的目录),不是 realpath —— 展示给用户看
320
+ * 的是「正文里叫什么」,不是「磁盘上实际落在哪儿」。
321
+ */
322
+ function collectMarkdownFiles(dir, root, prefix, out, stack = new Set()) {
323
+ // 递归栈去重:进入一个**真实目录**前记录,返回时移除。环(`loop -> .` 或
324
+ // `a/link -> a`)会在第二次进入同一真实目录时被挡下;而同一目录的不同**逻辑**
325
+ // 路径(两条并列链接)仍会各自展开——栈是路径级的,不是全局 visited。
326
+ let realDir;
327
+ try {
328
+ realDir = realpathSync(dir);
329
+ }
330
+ catch {
331
+ realDir = dir; // realpath 失败:退回字面路径(目录本身仍可能可读)
332
+ }
333
+ if (stack.has(realDir))
334
+ return;
335
+ stack.add(realDir);
336
+ try {
337
+ collectMarkdownFilesInner(dir, root, prefix, out, stack);
338
+ }
339
+ finally {
340
+ stack.delete(realDir);
341
+ }
342
+ }
343
+ function collectMarkdownFilesInner(dir, root, prefix, out, stack) {
344
+ const names = readdirSync(dir); // 目录不存在 → ENOENT(与旧实现同一条错误面)
345
+ for (const name of [...names].sort()) {
346
+ if (name.startsWith('.'))
347
+ continue;
348
+ const full = join(dir, name);
349
+ const rel = prefix === '' ? name : `${prefix}/${name}`;
350
+ let isDir = false;
351
+ let isFile = false;
352
+ let st;
353
+ try {
354
+ st = lstatSync(full);
355
+ }
356
+ catch {
357
+ continue; // 读不到就跳过(不是本组要处理的错误面)
358
+ }
359
+ if (st.isSymbolicLink()) {
360
+ let real;
361
+ try {
362
+ real = realpathSync(full);
363
+ }
364
+ catch {
365
+ continue; // 断链:跳过
366
+ }
367
+ if (real !== root && !real.startsWith(root + sep))
368
+ continue; // 指向目录外:跳过
369
+ try {
370
+ const target = statSync(full);
371
+ isDir = target.isDirectory();
372
+ isFile = target.isFile();
373
+ }
374
+ catch {
375
+ continue;
376
+ }
377
+ }
378
+ else {
379
+ isDir = st.isDirectory();
380
+ isFile = st.isFile();
381
+ }
382
+ if (isDir) {
383
+ collectMarkdownFiles(full, root, rel, out, stack);
384
+ continue;
385
+ }
386
+ if (isFile && name.endsWith('.md'))
387
+ out.push({ abs: full, rel });
388
+ }
389
+ }
390
+ /**
391
+ * 校验一个 skill 文档目录:递归读 `dir` 下的所有 `.md`,逐个 `checkSkillDoc` 并汇总。
392
+ *
393
+ * 汇总时把「文件:行」前缀写进 detail(如 `SKILL.md:3 …`;子目录里的写成
394
+ * `references/foo.md:3 …`)—— `Violation` 没有文件名字段,多文件汇总时只靠行号无法
395
+ * 定位;`line` 仍保留原行号供程序化消费。
396
+ *
397
+ * ⚠️ 抛错边界(本函数不吞错,由调用方守卫,`qiyu skill check` 要接):
398
+ * · `dir` 不存在 → `readdirSync` 抛 `ENOENT`;
399
+ * · `dir` 下有**名为 `*.md` 的子目录** → 递归进去(不再像旧实现那样把目录当文件读、
400
+ * 抛 `EISDIR`);
401
+ * · 某个文件读不出来(权限等)→ `readFileSync` 的原始错误。
402
+ */
403
+ export function checkSkillDir(dir, ctx) {
404
+ const violations = [];
405
+ const warnings = [];
406
+ // realpath 后的根:符号链接的「是否指向目录内」要按**真实落点**比,否则
407
+ // `~/.claude/skills` 这种「目录本身是符号链接」的布局会被误判成「指向目录外」。
408
+ // realpath 失败(目录不存在)不在这里抛 —— 错误面由下面的 readdirSync 统一给
409
+ // (与旧实现同一条:ENOENT 来自 readdirSync,不是 realpathSync)。
410
+ let root = resolve(dir);
411
+ try {
412
+ root = realpathSync(root);
413
+ }
414
+ catch {
415
+ // 目录不存在:交给 readdirSync 抛 ENOENT(错误文案与旧实现一致)。
416
+ }
417
+ const files = [];
418
+ collectMarkdownFiles(dir, root, '', files);
419
+ for (const file of files) {
420
+ const result = checkSkillDoc(readFileSync(file.abs, 'utf8'), ctx);
421
+ for (const v of result.violations) {
422
+ violations.push({ ...v, detail: `${file.rel}:${v.line} ${v.detail}` });
423
+ }
424
+ for (const w of result.warnings) {
425
+ warnings.push({ ...w, detail: `${file.rel}:${w.line} ${w.detail}` });
426
+ }
427
+ }
428
+ return { violations, warnings };
429
+ }