qiyu-cli 0.2.1 → 0.2.2

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 (70) hide show
  1. package/README.md +345 -56
  2. package/dist/cli.js +48 -7
  3. package/dist/commands/api-notes.js +54 -0
  4. package/dist/commands/api.js +112 -38
  5. package/dist/commands/auth.js +150 -28
  6. package/dist/commands/credentials-source.js +30 -5
  7. package/dist/commands/db-notes.js +75 -0
  8. package/dist/commands/db.js +112 -113
  9. package/dist/commands/query-notes.js +58 -0
  10. package/dist/commands/query.js +427 -56
  11. package/dist/commands/skill.js +445 -51
  12. package/dist/commands/spec-types.js +101 -1
  13. package/dist/commands/stats.js +139 -30
  14. package/dist/commands/store-flags.js +18 -0
  15. package/dist/commands/store-notes.js +38 -0
  16. package/dist/commands/store-precheck.js +254 -0
  17. package/dist/commands/store.js +128 -75
  18. package/dist/commands/sync-notes.js +367 -0
  19. package/dist/commands/sync-run.js +155 -44
  20. package/dist/commands/sync.js +181 -120
  21. package/dist/core/config.js +274 -24
  22. package/dist/core/credentials.js +38 -4
  23. package/dist/core/edition.js +1 -1
  24. package/dist/core/envelope.js +73 -9
  25. package/dist/core/errors.js +73 -16
  26. package/dist/core/http.js +151 -52
  27. package/dist/core/ratelimit.js +5 -1
  28. package/dist/core/registry/index.js +26 -2
  29. package/dist/core/registry/params/export.session.check.json +17 -2
  30. package/dist/core/registry/params/export.session.json +24 -2
  31. package/dist/core/registry/params/export.session.one.json +10 -2
  32. package/dist/core/registry/params/export.session.one.message.json +17 -2
  33. package/dist/core/registry/specs.json +64 -42
  34. package/dist/core/shell.js +30 -0
  35. package/dist/core/time.js +1 -1
  36. package/dist/core/validate.js +21 -2
  37. package/dist/output.js +204 -28
  38. package/dist/postinstall.js +14 -5
  39. package/dist/query/errors.js +145 -45
  40. package/dist/query/mask.js +1277 -25
  41. package/dist/query/metric-catalog.js +11 -0
  42. package/dist/query/native-error.js +189 -0
  43. package/dist/query/sandbox.js +129 -24
  44. package/dist/query/table-query.js +36 -5
  45. package/dist/schedule/install.js +136 -13
  46. package/dist/skill/check.js +11 -6
  47. package/dist/skill/detect.js +89 -29
  48. package/dist/skill/install.js +233 -43
  49. package/dist/skill/paths.js +54 -0
  50. package/dist/skill/qiyu/SKILL.md +29 -5
  51. package/dist/skill/qiyu/errors.md +5 -4
  52. package/dist/skill/qiyu/protocols.md +57 -5
  53. package/dist/skill/qiyu/setup.md +6 -2
  54. package/dist/store/config.js +92 -16
  55. package/dist/store/duckdb.js +51 -5
  56. package/dist/store/retry.js +92 -4
  57. package/dist/store/schema.js +26 -3
  58. package/dist/sync/engine.js +257 -65
  59. package/dist/sync/registry.js +4 -0
  60. package/dist/sync/state.js +20 -0
  61. package/dist/sync/tasks/dim.js +23 -14
  62. package/dist/sync/tasks/knowledge.js +50 -8
  63. package/dist/sync/tasks/pipeline.js +29 -9
  64. package/dist/sync/tasks/reports.js +176 -49
  65. package/dist/sync/tasks/sessions.js +88 -21
  66. package/dist/sync/tasks/tickets.js +59 -8
  67. package/dist/sync/types.js +60 -1
  68. package/dist/sync/windowing.js +0 -22
  69. package/dist/sync/write-contract.js +47 -0
  70. package/package.json +1 -1
@@ -15,17 +15,19 @@
15
15
  // 数字字符串(BIGINT 经 JSON 层),三者统一为同一形态。
16
16
  // · `db describe` 的列清单同样以 `TABLES` 为权威;声明有而库中无的表**仍输出声明
17
17
  // 元数据**(`row_count`/`time_range` 为 null + warning,裁决 R5)——Agent 需要知道
18
- // 该表应该有什么列,才能判断是没同步还是没建库。
19
- import { statSync } from 'node:fs';
18
+ // 该表应该有什么列,以便核对列漂移。缺表的成因不是「未同步或未建库」(实测两个都
19
+ // 到不了该分支),唯一口径见 `missingTableCauses()`。
20
20
  import { resolveStoreConfig, currentStoreEnv } from '../store/config.js';
21
- import { openSandbox } from '../query/sandbox.js';
21
+ import { openSandbox, withTimeoutHint } from '../query/sandbox.js';
22
22
  import { timeShapeClauses } from '../query/time-shape.js';
23
- import { suggestNames, thrownToQueryExit } from '../query/errors.js';
23
+ import { SCHEMA_VERSION_COLUMNS_SQL, statGuard, schemaVersionMissing, storeTablesWarnings } from './store-precheck.js';
24
+ import { suggestNames, thrownToQueryExit, missingTableCauses } from '../query/errors.js';
24
25
  import { TABLES, tableByName } from '../store/schema.js';
25
26
  import { msToShanghaiIso } from '../core/time.js';
26
- import { ok, fail, usageFail, sanitizeControlChars, describeArgs, setPretty } from '../output.js';
27
- import { parseStoreFlags } from './store-flags.js';
28
- import { GLOBAL_FLAGS, GLOBAL_FLAG_NAMES, prettyAfterSubcommand, REJECTED_FLAGS, STORE_FLAGS } from './spec-types.js';
27
+ import { ok, fail, usageFail, failFromTagged, sanitizeControlChars, describeArgs, setPretty, dbTablesCommand, querySqlCommand, SQL_ARG_REPLACE_NOTE, metadataTimeoutHint, storeLocationFromFlags, storeLocationOf, } from '../output.js';
28
+ import { DB_PATH_HELP, parseStoreFlags } from './store-flags.js';
29
+ import { describeFieldNotes, tablesFieldNotes } from './db-notes.js';
30
+ import { GLOBAL_FLAGS, helpArgsError, prettyAfterSubcommand, prettyPositionalProblem, REJECTED_FLAGS, STORE_FLAGS } from './spec-types.js';
29
31
  /**
30
32
  * 命令契约(F 组 D4):`skill check` 据此判断 skill 正文里的 `qiyu db …` 是否真的存在。
31
33
  * `flags` 是**完整接受集**(含全局 flag),`--pretty` 同时在 `rejected` 里。
@@ -54,45 +56,22 @@ const USAGE = `用法:qiyu db <子命令> [参数]
54
56
  查看单表列定义
55
57
 
56
58
  存储定位:--db / --profile / --backend(store 命令同族)。
59
+ ${DB_PATH_HELP}
57
60
  `;
58
- const KNOWN = new Set(GLOBAL_FLAG_NAMES);
61
+ // ⚠️ 运行时的「已知 token 集」现在**每个子命令各自取自己的完整接受集**(2026-11-06 审查):
62
+ // 只放全局 flag 会把合法业务 flag 判成「未知参数」——`db describe tickets --help` 退 2、
63
+ // 而 `api list --all --help` 退 0,同一 CLI 两套答案;`skill check` 按 spec 又判它合法。
64
+ // 见 `spec-types.ts` 的 `helpArgsError`。
65
+ const acceptSet = (sub) => DB_SPECS.find((sp) => sp.path[1] === sub)?.flags ?? GLOBAL_FLAGS;
59
66
  /** PII 提示(设计稿 §6.5 要求 `db tables` / `db describe` 必须携带)。 */
60
67
  const PII_NOTICE = '本数据库包含客户 PII;不要将其写入日志或对外报表';
61
68
  /**
62
- * 只读命令的库前置检查(ENOENT / 非普通文件 / 权限三分 → 退出码,否则 null)。
63
- * ⚠️ 与 sync.ts 的私有 statGuard 同款,但**独立落点**:brief 指定 E 族单一落点
64
- * (本函数由 db.ts 导出给 query/stats 复用,避免三份拷贝漂移;不为它抽独立模块,
65
- * 两处足够小,YAGNI)。
66
- * hint 统一指 `qiyu store init`(spec §九)。
69
+ * 只读命令的库前置检查 → 见 `commands/store-precheck.ts` 的 `statGuard`
70
+ * (**唯一实现点**:本轮把它从本文件的私有函数收敛过去,此前 db/sync/store 三份拷贝
71
+ * 已经漂移 —— 同一成因在不同命令上给出互相矛盾、乃至事实错误的 hint)。
72
+ * 本文件不再自带一份;E 族四命令统一经 `openGuardedSession` 走它。
67
73
  */
68
- export function statGuard(path) {
69
- let st;
70
- try {
71
- st = statSync(path);
72
- }
73
- catch (e) {
74
- if (e.code === 'ENOENT') {
75
- return fail({
76
- code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
77
- message: `数据库文件不存在:${path}`,
78
- hint: '数据库尚未初始化。请先运行:qiyu store init',
79
- });
80
- }
81
- return fail({
82
- code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
83
- message: `无法访问 ${path}:${e instanceof Error ? e.message : String(e)}`,
84
- hint: '请检查路径权限(只读命令不需要写权限)',
85
- });
86
- }
87
- if (!st.isFile()) {
88
- return fail({
89
- code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
90
- message: `不是普通文件:${path}`,
91
- hint: '--db 指向的不是普通文件,请给出 .duckdb 数据库文件路径',
92
- });
93
- }
94
- return null;
95
- }
74
+ export { statGuard } from './store-precheck.js';
96
75
  /** 表的 PII 列名(`sensitive: true`,保持声明顺序)——`TABLES` 是唯一权威。 */
97
76
  function piiColumnsOf(t) {
98
77
  return t.columns.filter((c) => c.sensitive === true).map((c) => c.name);
@@ -176,9 +155,10 @@ async function dirtyTimeValues(session, t) {
176
155
  return Number((r.rows[0] ?? {}).n);
177
156
  }
178
157
  /** 脏时间值的公共警告文案(tables 与 describe 同一句话)。 */
179
- function dirtyTimeWarning(table, column, n) {
158
+ function dirtyTimeWarning(table, column, n, loc) {
180
159
  return `表 ${table} 的时间列 ${column} 有 ${n} 个值不符合约定形态(已从 time_range 中排除)`
181
- + '——可能来自旧版 CLI、外部工具或库损坏;用 `qiyu query --sql` 单独查看它们以确认成因';
160
+ + '——可能来自旧版 CLI、外部工具或库损坏;用 `' + querySqlCommand(loc)
161
+ + '` 单独查看它们以确认成因(' + SQL_ARG_REPLACE_NOTE + ')';
182
162
  }
183
163
  /**
184
164
  * 打开「已通过前置检查」的只读沙箱会话(**E 族三个命令共用**):
@@ -194,16 +174,22 @@ function dirtyTimeWarning(table, column, n) {
194
174
  * 文案与 hint 任何一处漂移都会让 Agent 在不同命令上得到互相矛盾的解释。
195
175
  * 此前 query/stats 各自内联了一份拷贝,已合并到此处(架构审查 Important #2)。
196
176
  */
197
- export async function openGuardedSession(flags) {
177
+ export async function openGuardedSession(flags, probeTimeoutHint) {
198
178
  let config;
179
+ let profileFlag;
199
180
  try {
200
- config = resolveStoreConfig({
181
+ const resolved = resolveStoreConfig({
201
182
  flags: { db: flags.db, profile: flags.profile, backend: flags.backend },
202
183
  env: currentStoreEnv(),
203
- }).config;
184
+ });
185
+ config = resolved.config;
186
+ profileFlag = resolved.profileFlag;
204
187
  }
205
188
  catch (e) {
206
- return { exit: usageFail(sanitizeControlChars(e.message)) };
189
+ // ⚠️ failFromTagged(不是 usageFail):配置层会抛带 `kind: config_insecure` 的错误
190
+ // (含凭证且权限过宽 —— 退出码 1、只能由人 chmod)。包成 usageFail 会把它降级成
191
+ // 「改参数重来」退出码 2 并丢掉 hint,与 auth/api 那条路径的说法相反。
192
+ return { exit: failFromTagged(e) };
207
193
  }
208
194
  const guarded = statGuard(config.path);
209
195
  if (guarded !== null)
@@ -213,41 +199,47 @@ export async function openGuardedSession(flags) {
213
199
  session = await openSandbox(config);
214
200
  }
215
201
  catch (e) {
216
- return { exit: thrownToQueryExit(e, TABLES) };
202
+ return { exit: thrownToQueryExit(e, TABLES, false, storeLocationOf(config.path, profileFlag)) };
217
203
  }
204
+ // ⚠️ 这次探测同样会超时,而它的超时**先于**调用方的 `withTimeoutHint` 包装发生 ——
205
+ // 不在这里注入的话,前置检查超时拿到的是 `query` 口径的「缩小时间范围或加过滤条件」,
206
+ // 而 `db tables` / `db describe` / `stats fields` 根本没有这些参数(Codex 2026-11-05
207
+ // 第四轮 P3 实测:同一命令在探测阶段与正式阶段给出互相矛盾的 hint)。
208
+ // ⚠️ 但 hint 由**调用方**决定(CodeRabbit 2026-11-05 第六轮 minor):`query` 也走本函数,
209
+ // 它**有** --since/--limit/--timeout,探测超时沿用 `DEFAULT_TIMEOUT_HINT` 才对 ——
210
+ // 无脑注入元数据口径,会让 `query` 探测超时时建议「改用 qiyu query --sql」这条它正在跑的路。
211
+ const loc = storeLocationOf(config.path, profileFlag);
212
+ const metaHint = probeTimeoutHint === undefined ? session : withTimeoutHint(session, probeTimeoutHint(loc));
218
213
  try {
219
214
  // 库结构校验(spec §十一「库不存在/缺表 → store_not_initialized、退出码 1」)。
220
215
  // 口径与实际表集查询一致:限定 table_schema='main'(别库同名表不算数)。
221
- // ⚠️ 成因分形(sync.ts openRo / store.ts 同款):「有表但无 schema_version」是**他人库**
222
- // —— store init 会再次拒绝(duckdb.ts init 的他人库防线),无条件引导过去就是
223
- // store init → db tables 死循环;「零表」才是「init 可补」的成因。
224
- const tables = await session.run("SELECT table_name FROM information_schema.tables WHERE table_schema='main'");
216
+ // ⚠️ 成因分形与文案走 `store-precheck.ts` 的 `schemaVersionMissing`(**唯一实现点**,
217
+ // 2026-10-31 收敛;此前 store/db/sync 三份已漂移出不同说法)。
218
+ const tables = await metaHint.run("SELECT table_name FROM information_schema.tables WHERE table_schema='main'");
225
219
  const names = tables.rows.map((r) => String(r.table_name));
226
- if (!names.includes('schema_version')) {
220
+ // ⚠️ 表名不是身份证明(2026-11-07 审查实测):别的工具也会建叫 schema_version 的表。
221
+ // 只有该表在场时才补查列名 —— 零表/无该表时 `schemaVersionMissing` 不需要它。
222
+ const versionColumns = names.includes('schema_version')
223
+ ? (await metaHint.run(SCHEMA_VERSION_COLUMNS_SQL)).rows.map((r) => String(r.column_name))
224
+ : undefined;
225
+ const missing = schemaVersionMissing(config.path, names, versionColumns);
226
+ if (missing !== null) {
227
227
  await session.close();
228
- return {
229
- exit: fail({
230
- code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
231
- message: `数据库结构不完整(缺表):${config.path}`,
232
- hint: names.length > 0
233
- ? '目标数据库不是本 CLI 创建的,请换 --db 路径'
234
- : '空库(无任何表)。请先运行:qiyu store init',
235
- }),
236
- };
228
+ return { exit: fail(missing) };
237
229
  }
238
230
  }
239
231
  catch (e) {
240
232
  await session.close();
241
- return { exit: thrownToQueryExit(e, TABLES) };
233
+ return { exit: thrownToQueryExit(e, TABLES, false, storeLocationOf(config.path, profileFlag)) };
242
234
  }
243
- return { session, dbPath: config.path };
235
+ return { session, dbPath: config.path, ...(profileFlag !== undefined ? { profileFlag } : {}) };
244
236
  }
245
237
  async function dbTables(argv) {
246
238
  // 子命令级次序沿 store.ts:--help 分流 → --pretty 开启缩进(G1) → parseStoreFlags → 未知参数。
247
239
  if (argv.includes('--help') || argv.includes('-h')) {
248
- const rawRest = argv.filter((a) => !KNOWN.has(a));
249
- if (rawRest.length > 0)
250
- return usageFail(`未知参数:${rawRest.join(' ')}`);
240
+ const problem = helpArgsError(argv, acceptSet('tables'));
241
+ if (problem !== undefined)
242
+ return usageFail(problem);
251
243
  process.stdout.write(USAGE);
252
244
  return 0;
253
245
  }
@@ -262,33 +254,22 @@ async function dbTables(argv) {
262
254
  return usageFail(sanitizeControlChars(e.message));
263
255
  }
264
256
  if (flags.rest.length > 0)
265
- return usageFail(`未知参数:${flags.rest.join(' ')}`);
266
- const opened = await openGuardedSession(flags);
257
+ return usageFail(`未知参数:${describeArgs(flags.rest)}`);
258
+ const opened = await openGuardedSession(flags, metadataTimeoutHint);
267
259
  if ('exit' in opened)
268
260
  return opened.exit;
269
- const session = opened.session;
261
+ // 超时 hint 换成元数据命令的说法(本命令没有可调过滤参数,query 那句对它是死路)。
262
+ const session = withTimeoutHint(opened.session, metadataTimeoutHint(storeLocationOf(opened.dbPath, opened.profileFlag)));
270
263
  try {
271
264
  // 实际表集 → 与声明比对(spec §8.1「声明与实况的差异不得静默」)。
272
265
  const actual = await session.run("SELECT table_name FROM information_schema.tables WHERE table_schema='main'");
273
266
  const actualNames = actual.rows.map((r) => String(r.table_name));
274
267
  const actualSet = new Set(actualNames);
275
- const declaredSet = new Set(TABLES.map((t) => t.name));
276
- const warnings = [];
277
- const declaredMissing = TABLES.map((t) => t.name).filter((n) => !actualSet.has(n));
278
- if (declaredMissing.length > 0) {
279
- // ⚠️ 不得承诺 store init 一定能修(审查 Important #1):init 只重放
280
- // `version > MAX(version)` 的迁移,已迁移到最新版后被 DROP 的表**不会**被
281
- // 重建(迁移已跳过,返回 ok 而表仍缺)——那是「成功但无效」的修复。
282
- warnings.push(`声明有而库中无:${declaredMissing.join('、')}。`
283
- + '这些表不出现在 tables 中。若为建库未完成(迁移未跑完),运行 qiyu store init 可补建缺失的迁移;'
284
- + '若迁移已完成而表被删或损坏,store init 不会重建该表,重新同步也只会写入失败(缺表)'
285
- + '——需重建库(删除库文件后重新 qiyu store init 并重新同步)');
286
- }
287
- const undeclared = actualNames.filter((n) => !declaredSet.has(n)).sort();
288
- if (undeclared.length > 0) {
289
- warnings.push(`库中有而声明无:${undeclared.join('、')}。`
290
- + '这些表没有元数据声明(可能来自旧版 CLI 或其他工具),不出现在 tables 中');
291
- }
268
+ // ⚠️ 两半漂移的 warning 走 `storeTablesWarnings`(**唯一渲染点**,2026-11-02 收敛):
269
+ // 此前本命令自己拼「声明有而库中无」+ `missingTableCauses`,而 `store status`/`init`
270
+ // 只拼「库中有而声明无」—— 同一库两种漂移,两条命令各报一半,缺表那半在 store 上
271
+ // 静默。这里与 store 现在共用同一个渲染器,`declaredMissing` 也不再单独算。
272
+ const warnings = storeTablesWarnings(actualNames, opened.dbPath, opened.profileFlag) ?? [];
292
273
  // 实际列集一次查全库(25 次往返 → 1 次):时间列被删的表不能让 timeRangeOf 的
293
274
  // `MIN("c")` 在 prepare 期抛 Binder Error 把整命令打成退出码 2(Task 7 审查
294
275
  // Important #1)——缺列降级为 time_range null + warning。
@@ -335,7 +316,7 @@ async function dbTables(argv) {
335
316
  timeRange = await timeRangeOf(session, t);
336
317
  const dirty = await dirtyTimeValues(session, t);
337
318
  if (dirty > 0)
338
- warnings.push(dirtyTimeWarning(t.name, tc.name, dirty));
319
+ warnings.push(dirtyTimeWarning(t.name, tc.name, dirty, storeLocationOf(opened.dbPath, opened.profileFlag)));
339
320
  }
340
321
  else {
341
322
  warnings.push(`表 ${t.name} 缺少时间列 ${tc.name}(可能来自旧版 CLI 或库损坏),time_range 置 null`);
@@ -349,10 +330,10 @@ async function dbTables(argv) {
349
330
  pii_columns: piiColumnsOf(t),
350
331
  });
351
332
  }
352
- return ok({ tables }, { notice: PII_NOTICE, warnings });
333
+ return ok({ tables }, { notice: PII_NOTICE, warnings, field_notes: tablesFieldNotes() });
353
334
  }
354
335
  catch (e) {
355
- return thrownToQueryExit(e, TABLES);
336
+ return thrownToQueryExit(e, TABLES, false, storeLocationOf(opened.dbPath, opened.profileFlag));
356
337
  }
357
338
  finally {
358
339
  await session.close();
@@ -373,9 +354,9 @@ function describeColumn(c) {
373
354
  async function dbDescribe(argv) {
374
355
  // 子命令级次序沿 dbTables:--help 分流 → --pretty 开启缩进(G1) → parseStoreFlags → 位置参数。
375
356
  if (argv.includes('--help') || argv.includes('-h')) {
376
- const rawRest = argv.filter((a) => !KNOWN.has(a));
377
- if (rawRest.length > 0)
378
- return usageFail(`未知参数:${rawRest.join(' ')}`);
357
+ const problem = helpArgsError(argv, acceptSet('describe'));
358
+ if (problem !== undefined)
359
+ return usageFail(problem);
379
360
  process.stdout.write(USAGE);
380
361
  return 0;
381
362
  }
@@ -392,24 +373,27 @@ async function dbDescribe(argv) {
392
373
  // 未知 flag(`--bogus`)会落进 rest —— 先按 `-` 前缀挑出来,避免被当成表名。
393
374
  const flagish = flags.rest.filter((a) => a.startsWith('-'));
394
375
  if (flagish.length > 0)
395
- return usageFail(`未知参数:${flagish.join(' ')}`);
376
+ return usageFail(`未知参数:${describeArgs(flagish)}`);
396
377
  if (flags.rest.length === 0) {
397
378
  return usageFail(`缺少表名:请给 db describe <表>\n可用表:${TABLES.map((t) => t.name).join('、')}`);
398
379
  }
399
380
  if (flags.rest.length > 1)
400
- return usageFail(`未知参数:${flags.rest.slice(1).join(' ')}`);
381
+ return usageFail(`未知参数:${describeArgs(flags.rest.slice(1))}`);
401
382
  // spec §8.2「未知 → usage + 候选」:闭集校验先于一切 I/O(不打开库就知道表名拼错)。
402
383
  // 候选来自 `TABLES`(前缀/编辑距离,大小写不敏感),不裸透 DuckDB 英文原文。
403
384
  const name = sanitizeControlChars(flags.rest[0]);
404
385
  const table = tableByName(name);
405
386
  if (table === undefined) {
406
387
  const candidates = suggestNames(name, TABLES.map((t) => t.name));
407
- return usageFail(`未知表:${describeArgs([name])}`, candidates.length > 0 ? `候选:${candidates.join('、')}` : '用 `qiyu db tables` 查看可用表');
388
+ return usageFail(`未知表:${describeArgs([name])}`, candidates.length > 0
389
+ ? `候选:${candidates.join('、')}`
390
+ : '用 `' + dbTablesCommand(storeLocationFromFlags(flags)) + '` 查看可用表');
408
391
  }
409
- const opened = await openGuardedSession(flags);
392
+ const opened = await openGuardedSession(flags, metadataTimeoutHint);
410
393
  if ('exit' in opened)
411
394
  return opened.exit;
412
- const session = opened.session;
395
+ // 超时 hint 换成元数据命令的说法(本命令没有可调过滤参数,query 那句对它是死路)。
396
+ const session = withTimeoutHint(opened.session, metadataTimeoutHint(storeLocationOf(opened.dbPath, opened.profileFlag)));
413
397
  try {
414
398
  // 表名来自 `TABLES` 闭集(代码内常量),拼进字面量安全;用户输入只用于上面的闭集查找。
415
399
  const present = (await session.run(`SELECT 1 FROM information_schema.tables WHERE table_schema='main' AND table_name='${table.name}'`))
@@ -418,9 +402,13 @@ async function dbDescribe(argv) {
418
402
  let rowCount = null;
419
403
  let timeRange = null;
420
404
  if (!present) {
421
- // R5:声明有但库中无 → 仍输出声明元数据,不报错(Agent 靠列清单判断
422
- // 「没同步」还是「没建库」)。此时 row_count/time_range 无从得知,置 null。
423
- warnings.push(`表 ${table.name} 在库中不存在(未同步或未建库);以下为声明元数据`);
405
+ // R5:声明有但库中无 → 仍输出声明元数据,不报错(Agent 需要知道该表「应该」有什么列,
406
+ // 才能核对是不是列漂移)。此时 row_count/time_range 无从得知,置 null。
407
+ // ⚠️ 成因文案**不得**再写「未同步或未建库」(2026-10-29 实测修正,两个成因都到不了
408
+ // 这个分支:未同步的库 25 张声明表全在、库文件缺失/零表早在 openGuardedSession 里
409
+ // 报 store_not_initialized)。与 db tables/query/stats 共用 missingTableCauses()。
410
+ warnings.push(`表 ${table.name} 在库中不存在(声明有而库中无);以下为声明元数据`
411
+ + '(row_count/time_range 无法得知,置 null)。' + missingTableCauses(opened.dbPath, opened.profileFlag));
424
412
  }
425
413
  else {
426
414
  const r = await session.run(`SELECT COUNT(*) AS n FROM "${table.name}"`);
@@ -441,7 +429,7 @@ async function dbDescribe(argv) {
441
429
  timeRange = await timeRangeOf(session, table);
442
430
  const dirty = await dirtyTimeValues(session, table);
443
431
  if (dirty > 0)
444
- warnings.push(dirtyTimeWarning(table.name, tc.name, dirty));
432
+ warnings.push(dirtyTimeWarning(table.name, tc.name, dirty, storeLocationOf(opened.dbPath, opened.profileFlag)));
445
433
  }
446
434
  // tc 缺失时 timeRange 保持 null;下面的「少列」warning 已点名该时间列。
447
435
  if (missing.length > 0 || extra.length > 0) {
@@ -464,10 +452,10 @@ async function dbDescribe(argv) {
464
452
  time_range: timeRange,
465
453
  columns: table.columns.map(describeColumn),
466
454
  pii_columns: piiColumnsOf(table),
467
- }, { notice: PII_NOTICE, warnings });
455
+ }, { notice: PII_NOTICE, warnings, field_notes: describeFieldNotes() });
468
456
  }
469
457
  catch (e) {
470
- return thrownToQueryExit(e, TABLES);
458
+ return thrownToQueryExit(e, TABLES, false, storeLocationOf(opened.dbPath, opened.profileFlag));
471
459
  }
472
460
  finally {
473
461
  await session.close();
@@ -476,24 +464,35 @@ async function dbDescribe(argv) {
476
464
  export async function dbCommand(argv) {
477
465
  setPretty(false); // G1:每条命令入口重置输出格式 —— 同一进程内多次 run(测试)不残留上一条命令的开关。
478
466
  const [sub, ...rest] = argv;
479
- if (sub === undefined || sub === '--help' || sub === '-h') {
480
- // --help 不吞额外参数;--pretty 豁免(store.ts 同族惯例)
481
- const extra = rest.filter((a) => !KNOWN.has(a));
482
- if (extra.length > 0)
483
- return usageFail(`未知参数:${extra.join(' ')}。--help 不接受额外参数`);
467
+ // ⚠️ 无子命令 = 用法错误(退 2 + JSON)—— 见 store.ts 同款注释(2026-11-07 审查)。
468
+ if (sub === undefined) {
469
+ return usageFail(`用法:qiyu db <tables|describe> [参数](\`qiyu db --help\` 查看全部)`, '可用子命令:tables、describe');
470
+ }
471
+ if (sub === '--help' || sub === '-h') {
472
+ // --help 不吞未知参数;已知 flag 与非 flag token(子命令名、取值)一律放行
473
+ //(`db --help describe --db /tmp/x` 是 Agent 的常见写法,此前会退 2)。
474
+ const problem = helpArgsError(rest, DB_SPECS.flatMap((sp) => sp.flags), '。--help 不接受额外参数');
475
+ if (problem !== undefined)
476
+ return usageFail(problem);
484
477
  process.stdout.write(USAGE);
485
478
  return 0;
486
479
  }
487
480
  // G1:--pretty 是输出开关,必须写在具体子命令之后(`db tables --pretty`)。
488
481
  if (sub === '--pretty') {
489
- const unknown = rest.filter((a) => a.startsWith('-') && !KNOWN.has(a));
490
- const positional = rest.filter((a) => !a.startsWith('-'));
491
- if (unknown.length + positional.length > 0)
492
- return usageFail(`未知参数:${[...unknown, ...positional].join(' ')}。--pretty 不接受额外参数`);
482
+ const problem = helpArgsError(rest, DB_SPECS.flatMap((sp) => sp.flags));
483
+ if (problem !== undefined)
484
+ return usageFail(`${problem}。--pretty 不接受额外参数`);
485
+ const badPos = prettyPositionalProblem(rest, DB_SPECS);
486
+ if (badPos !== undefined)
487
+ return usageFail(badPos);
493
488
  if (rest.includes('--help') || rest.includes('-h')) {
494
489
  process.stdout.write(USAGE);
495
490
  return 0;
496
491
  }
492
+ // ⚠️ 位置参数一律按「顺序写反」引导(2026-11-07 审查):此前把子命令名当
493
+ // 「未知参数」报出(`db --pretty tables` → 「未知参数:tables」),而 `tables`
494
+ // 是本命令**已知**的子命令;同一写法在 stats 上给的是「必须写在子命令之后」。
495
+ // 五个命令族各写一份,答案还互相矛盾 —— 判据收敛到 `prettyAfterSubcommand`。
497
496
  return usageFail(prettyAfterSubcommand('db'));
498
497
  }
499
498
  if (sub !== 'tables' && sub !== 'describe') {
@@ -0,0 +1,58 @@
1
+ // src/commands/query-notes.ts
2
+ //
3
+ // `query` 两个通道(`--table` / `--sql`)共用的 `meta.field_notes` —— 9 个键的逐条释义。
4
+ //
5
+ // ⚠️ 为什么需要:`query` 是 skill 协议指定的主查询入口,它的 meta 里有一半是 Agent
6
+ // 要**按值分支**的机器值,而其中三处的字面与事实不符(2026-10-27 真库实测):
7
+ // · `masked: true` ≠ 「有值被改写」—— 它只表示脱敏开关开着,实际改写看 `masked_columns`
8
+ // (实测:脱敏开着而 `masked_columns: []` 是常态);
9
+ // · `mask_warnings: []` ≠ 「脱敏完整」—— `--no-mask` 时它**恒为空**,风险警告在
10
+ // `warnings` 里(实测);
11
+ // · `data_coverage` 只有首尾两点,**看不见内部缺口** —— 实测 7 天窗口里只有第 1、7 天
12
+ // 有数据时它照样报满区间,且 iso-instant / epoch-ms 表**没有任何警告兜底**
13
+ // (`buildCoverageQuery` 只对 iso-day 算 `days`,其余是 `NULL AS days`)。
14
+ //
15
+ // ⚠️ 释义正文不用 `;`:`renderNotes` 系(sync / stats)用它拼 `a = 释义;b = 释义`,
16
+ // 正文里再出现会让反向解析多出幽灵取值(PR #26 踩过两次)。本文件没有枚举字段,
17
+ // 但保持同一约定,将来加枚举时不必回头改。
18
+ /** `query` 的 `meta.field_notes`(导出供测试核对真实渲染路径)。 */
19
+ export function queryFieldNotes() {
20
+ return {
21
+ rows: '本次返回的行数(= data.rows.length,脱敏与截断之后)。'
22
+ + '⚠️ 它不是「命中的总行数」:truncated 为 true 时实际命中更多',
23
+ truncated: 'true = 命中行数超过 limit_applied,本次只返回前 limit_applied 行。'
24
+ + '⚠️ false 只说明「没超过上限」,不说明结果是全表——过滤条件仍可能排除了你要的行',
25
+ limit_applied: '本次生效的行数上限(没给 --limit 时是默认 1000,可设 1–10000)。'
26
+ + '它是上限不是实际行数,实际行数看 rows',
27
+ masked: 'true = 脱敏开着(默认)。false = 本次用了 --no-mask,输出是原始 PII。'
28
+ + '⚠️ true 不代表「有值被改写」——那要看 masked_columns',
29
+ masked_columns: '本次实际被改写的列(至少一行的值在脱敏前后不同)。'
30
+ + '⚠️ 为空不代表「没有敏感列」:只说明本次结果里没有需要改写的值'
31
+ + '(全 null、全空串、敏感列没被查出来,或本次 --no-mask 根本没脱敏)',
32
+ mask_warnings: '脱敏缺口与副作用警告(字符串数组,非空必须逐条读),包括但不限于:'
33
+ + '① 声明为敏感、却没能被脱敏的数据 —— 表定义之外的列、SQL 里被别名或表达式改名的敏感列、'
34
+ + 'payload 里的 JSON 内 PII。'
35
+ + '② 脱敏本身对分析结果的影响 —— GROUP BY / DISTINCT 的「分组键」是敏感列时,'
36
+ + '不同原值被压成同一个脱敏值(分组与计数会失真,别名分组与 GROUP BY 序号也认)、'
37
+ + '用了 query()/query_table()/COLUMNS() 之类嵌套 SQL 构造'
38
+ + '(内层敏感列无法识别)、非敏感列按值形态(手机号/邮箱/IPv4)被误改。'
39
+ + '⚠️ --no-mask 时恒为空数组——空不等于脱敏完整,那是「根本没脱敏」,风险警告在 warnings 里',
40
+ warnings: '非空必须逐条读——0 行成因、截断、窗口内部缺口、库漂移缺列、--no-mask 风险、'
41
+ + 'skill 安装提示都可能出现在这里(本键不是「只装查询警告」的专用通道)。'
42
+ + '忽略它们的 Agent 会把残缺数据当事实汇报',
43
+ resolved_range: '实际生效的时间过滤边界(+08:00 ISO)。⚠️ 它是过滤边界不是「有数据的范围」,'
44
+ + '后者看 data_coverage。null 有四种成因:--sql 通道不判定区间、没给 --since/--until、'
45
+ + '表没有时间列、只给 --until 而该表时间列无可用值(下界解析不出,此时 warnings 里有说明)',
46
+ data_coverage: '时间列在过滤范围内的 MIN/MAX(+08:00 ISO。没有时间过滤时是全表,'
47
+ + '但只算时间值形态合法的行)。'
48
+ + '独立于 --limit 计算,不受截断影响。'
49
+ + '⚠️ 结构上只有首尾两点,看不见内部缺口:7 天里只有第 1、7 天有数据时它照样报满区间。'
50
+ + '⚠️ iso-day 表在给了 --since/--until 时另有 warnings 兜底(「区间内应有 N 个自然日,'
51
+ + '实际只有 M 个有数据」),没有时间过滤时这条兜底不触发。iso-instant 与 epoch-ms 表'
52
+ + '任何情况下都没有兜底,必须自己按自然日 GROUP BY 数行。'
53
+ + 'null 有三种成因:--sql 通道、表没有时间列、范围内没有一行的时间值能过形态谓词'
54
+ + '(空表、过滤后 0 行、时间列全是脏值或 NULL)。第三种最隐蔽:rows 可能大于 0'
55
+ + '(无过滤时脏值行照常返回,给了时间过滤时它们被排除、改由 warnings 报数量)'
56
+ + '而 data_coverage 为 null,没有时间过滤时这份响应里不会有关于它的警告',
57
+ };
58
+ }