qiyu-cli 0.2.1 → 0.2.3

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 (72) hide show
  1. package/README.md +433 -72
  2. package/dist/cli.js +48 -7
  3. package/dist/commands/api-notes.js +70 -0
  4. package/dist/commands/api.js +169 -49
  5. package/dist/commands/auth.js +151 -29
  6. package/dist/commands/credentials-source.js +30 -5
  7. package/dist/commands/db-notes.js +75 -0
  8. package/dist/commands/db.js +165 -127
  9. package/dist/commands/query-notes.js +58 -0
  10. package/dist/commands/query.js +449 -61
  11. package/dist/commands/skill.js +445 -51
  12. package/dist/commands/spec-types.js +101 -1
  13. package/dist/commands/stats.js +160 -33
  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 +321 -0
  17. package/dist/commands/store.js +165 -77
  18. package/dist/commands/sync-notes.js +374 -0
  19. package/dist/commands/sync-run.js +180 -47
  20. package/dist/commands/sync.js +232 -127
  21. package/dist/core/config.js +280 -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 +175 -54
  27. package/dist/core/ratelimit.js +5 -1
  28. package/dist/core/registry/index.js +36 -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 +65 -43
  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 +215 -29
  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 +148 -25
  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 +1551 -64
  56. package/dist/store/object-kinds.js +32 -0
  57. package/dist/store/retry.js +190 -7
  58. package/dist/store/schema.js +32 -4
  59. package/dist/sync/engine.js +439 -77
  60. package/dist/sync/registry.js +6 -0
  61. package/dist/sync/state.js +20 -0
  62. package/dist/sync/tasks/dim.js +23 -14
  63. package/dist/sync/tasks/knowledge.js +50 -8
  64. package/dist/sync/tasks/pace.js +27 -0
  65. package/dist/sync/tasks/pipeline.js +29 -9
  66. package/dist/sync/tasks/reports.js +176 -49
  67. package/dist/sync/tasks/sessions.js +88 -21
  68. package/dist/sync/tasks/tickets.js +59 -8
  69. package/dist/sync/types.js +60 -1
  70. package/dist/sync/windowing.js +0 -22
  71. package/dist/sync/write-contract.js +79 -0
  72. package/package.json +2 -2
@@ -15,20 +15,23 @@
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, OBJECT_KINDS_SQL, nonBaseTables, nonBaseTablesWarning, sameObjectName, catalogRows, } 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
- * `flags` 是**完整接受集**(含全局 flag),`--pretty` 同时在 `rejected` 里。
33
+ * `flags` 是**完整接受集**(含全局 flag);`rejected` 直接取 `REJECTED_FLAGS`(当前为空 ——
34
+ * `--pretty` 自 2026-10-24 G1 起已实现,不再是 rejected,见 `spec-types.ts` 顶部)。
32
35
  * 值位解析走共享的 `parseStoreFlags`(它从 `STORE_FLAGS` 派生接受集),与这里同源。
33
36
  */
34
37
  export const DB_SPECS = [
@@ -54,45 +57,22 @@ const USAGE = `用法:qiyu db <子命令> [参数]
54
57
  查看单表列定义
55
58
 
56
59
  存储定位:--db / --profile / --backend(store 命令同族)。
60
+ ${DB_PATH_HELP}
57
61
  `;
58
- const KNOWN = new Set(GLOBAL_FLAG_NAMES);
62
+ // ⚠️ 运行时的「已知 token 集」现在**每个子命令各自取自己的完整接受集**(2026-11-06 审查):
63
+ // 只放全局 flag 会把合法业务 flag 判成「未知参数」——`db describe tickets --help` 退 2、
64
+ // 而 `api list --all --help` 退 0,同一 CLI 两套答案;`skill check` 按 spec 又判它合法。
65
+ // 见 `spec-types.ts` 的 `helpArgsError`。
66
+ const acceptSet = (sub) => DB_SPECS.find((sp) => sp.path[1] === sub)?.flags ?? GLOBAL_FLAGS;
59
67
  /** PII 提示(设计稿 §6.5 要求 `db tables` / `db describe` 必须携带)。 */
60
68
  const PII_NOTICE = '本数据库包含客户 PII;不要将其写入日志或对外报表';
61
69
  /**
62
- * 只读命令的库前置检查(ENOENT / 非普通文件 / 权限三分 → 退出码,否则 null)。
63
- * ⚠️ 与 sync.ts 的私有 statGuard 同款,但**独立落点**:brief 指定 E 族单一落点
64
- * (本函数由 db.ts 导出给 query/stats 复用,避免三份拷贝漂移;不为它抽独立模块,
65
- * 两处足够小,YAGNI)。
66
- * hint 统一指 `qiyu store init`(spec §九)。
70
+ * 只读命令的库前置检查 → 见 `commands/store-precheck.ts` 的 `statGuard`
71
+ * (**唯一实现点**:本轮把它从本文件的私有函数收敛过去,此前 db/sync/store 三份拷贝
72
+ * 已经漂移 —— 同一成因在不同命令上给出互相矛盾、乃至事实错误的 hint)。
73
+ * 本文件不再自带一份;E 族四命令统一经 `openGuardedSession` 走它。
67
74
  */
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
- }
75
+ export { statGuard } from './store-precheck.js';
96
76
  /** 表的 PII 列名(`sensitive: true`,保持声明顺序)——`TABLES` 是唯一权威。 */
97
77
  function piiColumnsOf(t) {
98
78
  return t.columns.filter((c) => c.sensitive === true).map((c) => c.name);
@@ -176,9 +156,10 @@ async function dirtyTimeValues(session, t) {
176
156
  return Number((r.rows[0] ?? {}).n);
177
157
  }
178
158
  /** 脏时间值的公共警告文案(tables 与 describe 同一句话)。 */
179
- function dirtyTimeWarning(table, column, n) {
159
+ function dirtyTimeWarning(table, column, n, loc) {
180
160
  return `表 ${table} 的时间列 ${column} 有 ${n} 个值不符合约定形态(已从 time_range 中排除)`
181
- + '——可能来自旧版 CLI、外部工具或库损坏;用 `qiyu query --sql` 单独查看它们以确认成因';
161
+ + '——可能来自旧版 CLI、外部工具或库损坏;用 `' + querySqlCommand(loc)
162
+ + '` 单独查看它们以确认成因(' + SQL_ARG_REPLACE_NOTE + ')';
182
163
  }
183
164
  /**
184
165
  * 打开「已通过前置检查」的只读沙箱会话(**E 族三个命令共用**):
@@ -194,16 +175,22 @@ function dirtyTimeWarning(table, column, n) {
194
175
  * 文案与 hint 任何一处漂移都会让 Agent 在不同命令上得到互相矛盾的解释。
195
176
  * 此前 query/stats 各自内联了一份拷贝,已合并到此处(架构审查 Important #2)。
196
177
  */
197
- export async function openGuardedSession(flags) {
178
+ export async function openGuardedSession(flags, probeTimeoutHint) {
198
179
  let config;
180
+ let profileFlag;
199
181
  try {
200
- config = resolveStoreConfig({
182
+ const resolved = resolveStoreConfig({
201
183
  flags: { db: flags.db, profile: flags.profile, backend: flags.backend },
202
184
  env: currentStoreEnv(),
203
- }).config;
185
+ });
186
+ config = resolved.config;
187
+ profileFlag = resolved.profileFlag;
204
188
  }
205
189
  catch (e) {
206
- return { exit: usageFail(sanitizeControlChars(e.message)) };
190
+ // ⚠️ failFromTagged(不是 usageFail):配置层会抛带 `kind: config_insecure` 的错误
191
+ // (含凭证且权限过宽 —— 退出码 1、只能由人 chmod)。包成 usageFail 会把它降级成
192
+ // 「改参数重来」退出码 2 并丢掉 hint,与 auth/api 那条路径的说法相反。
193
+ return { exit: failFromTagged(e) };
207
194
  }
208
195
  const guarded = statGuard(config.path);
209
196
  if (guarded !== null)
@@ -213,41 +200,50 @@ export async function openGuardedSession(flags) {
213
200
  session = await openSandbox(config);
214
201
  }
215
202
  catch (e) {
216
- return { exit: thrownToQueryExit(e, TABLES) };
203
+ return { exit: thrownToQueryExit(e, TABLES, false, storeLocationOf(config.path, profileFlag)) };
217
204
  }
205
+ // ⚠️ 这次探测同样会超时,而它的超时**先于**调用方的 `withTimeoutHint` 包装发生 ——
206
+ // 不在这里注入的话,前置检查超时拿到的是 `query` 口径的「缩小时间范围或加过滤条件」,
207
+ // 而 `db tables` / `db describe` / `stats fields` 根本没有这些参数(Codex 2026-11-05
208
+ // 第四轮 P3 实测:同一命令在探测阶段与正式阶段给出互相矛盾的 hint)。
209
+ // ⚠️ 但 hint 由**调用方**决定(CodeRabbit 2026-11-05 第六轮 minor):`query` 也走本函数,
210
+ // 它**有** --since/--limit/--timeout,探测超时沿用 `DEFAULT_TIMEOUT_HINT` 才对 ——
211
+ // 无脑注入元数据口径,会让 `query` 探测超时时建议「改用 qiyu query --sql」这条它正在跑的路。
212
+ const loc = storeLocationOf(config.path, profileFlag);
213
+ const metaHint = probeTimeoutHint === undefined ? session : withTimeoutHint(session, probeTimeoutHint(loc));
218
214
  try {
219
215
  // 库结构校验(spec §十一「库不存在/缺表 → store_not_initialized、退出码 1」)。
220
216
  // 口径与实际表集查询一致:限定 table_schema='main'(别库同名表不算数)。
221
- // ⚠️ 成因分形(sync.ts openRo / store.ts 同款):「有表但无 schema_version」是**他人库**
222
- // —— store init 会再次拒绝(duckdb.ts init 的他人库防线),无条件引导过去就是
223
- // store init → db tables 死循环;「零表」才是「init 可补」的成因。
224
- const tables = await session.run("SELECT table_name FROM information_schema.tables WHERE table_schema='main'");
225
- const names = tables.rows.map((r) => String(r.table_name));
226
- if (!names.includes('schema_version')) {
217
+ // ⚠️ 成因分形与文案走 `store-precheck.ts` 的 `schemaVersionMissing`(**唯一实现点**,
218
+ // 2026-10-31 收敛;此前 store/db/sync 三份已漂移出不同说法)。
219
+ // ⚠️ 经 `catalogRows`(不是裸 `metaHint.run`):目录超过沙箱缺省 1000 行时,那只是
220
+ // **截断页**;被挤掉的对象仍存在,据此判定「缺表 / 他人库」就是假归因。该 SQL 无
221
+ // `ORDER BY`,谁在首页不是契约。
222
+ const tables = await catalogRows(metaHint, "SELECT table_name FROM information_schema.tables WHERE table_schema='main'");
223
+ const names = tables.map((r) => String(r.table_name));
224
+ // ⚠️ 表名不是身份证明(2026-11-07 审查实测):别的工具也会建叫 schema_version 的表。
225
+ // 只有该表在场时才补查列名 —— 零表/无该表时 `schemaVersionMissing` 不需要它。
226
+ const versionColumns = names.some((n) => sameObjectName('schema_version', n))
227
+ ? (await catalogRows(metaHint, SCHEMA_VERSION_COLUMNS_SQL)).map((r) => String(r.column_name))
228
+ : undefined;
229
+ const missing = schemaVersionMissing(config.path, names, versionColumns);
230
+ if (missing !== null) {
227
231
  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
- };
232
+ return { exit: fail(missing) };
237
233
  }
238
234
  }
239
235
  catch (e) {
240
236
  await session.close();
241
- return { exit: thrownToQueryExit(e, TABLES) };
237
+ return { exit: thrownToQueryExit(e, TABLES, false, storeLocationOf(config.path, profileFlag)) };
242
238
  }
243
- return { session, dbPath: config.path };
239
+ return { session, dbPath: config.path, ...(profileFlag !== undefined ? { profileFlag } : {}) };
244
240
  }
245
241
  async function dbTables(argv) {
246
242
  // 子命令级次序沿 store.ts:--help 分流 → --pretty 开启缩进(G1) → parseStoreFlags → 未知参数。
247
243
  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(' ')}`);
244
+ const problem = helpArgsError(argv, acceptSet('tables'));
245
+ if (problem !== undefined)
246
+ return usageFail(problem);
251
247
  process.stdout.write(USAGE);
252
248
  return 0;
253
249
  }
@@ -262,39 +258,40 @@ async function dbTables(argv) {
262
258
  return usageFail(sanitizeControlChars(e.message));
263
259
  }
264
260
  if (flags.rest.length > 0)
265
- return usageFail(`未知参数:${flags.rest.join(' ')}`);
266
- const opened = await openGuardedSession(flags);
261
+ return usageFail(`未知参数:${describeArgs(flags.rest)}`);
262
+ const opened = await openGuardedSession(flags, metadataTimeoutHint);
267
263
  if ('exit' in opened)
268
264
  return opened.exit;
269
- const session = opened.session;
265
+ // 超时 hint 换成元数据命令的说法(本命令没有可调过滤参数,query 那句对它是死路)。
266
+ const session = withTimeoutHint(opened.session, metadataTimeoutHint(storeLocationOf(opened.dbPath, opened.profileFlag)));
270
267
  try {
271
268
  // 实际表集 → 与声明比对(spec §8.1「声明与实况的差异不得静默」)。
272
- const actual = await session.run("SELECT table_name FROM information_schema.tables WHERE table_schema='main'");
273
- const actualNames = actual.rows.map((r) => String(r.table_name));
274
- const actualSet = new Set(actualNames);
275
- const declaredSet = new Set(TABLES.map((t) => t.name));
276
- const warnings = [];
277
- const declaredMissing = TABLES.map((t) => t.name).filter((n) => !actualSet.has(n));
278
- if (declaredMissing.length > 0) {
279
- // ⚠️ 不得承诺 store init 一定能修(审查 Important #1):init 只重放
280
- // `version > MAX(version)` 的迁移,已迁移到最新版后被 DROP 的表**不会**被
281
- // 重建(迁移已跳过,返回 ok 而表仍缺)——那是「成功但无效」的修复。
282
- warnings.push(`声明有而库中无:${declaredMissing.join('、')}。`
283
- + '这些表不出现在 tables 中。若为建库未完成(迁移未跑完),运行 qiyu store init 可补建缺失的迁移;'
284
- + '若迁移已完成而表被删或损坏,store init 不会重建该表,重新同步也只会写入失败(缺表)'
285
- + '——需重建库(删除库文件后重新 qiyu store init 并重新同步)');
286
- }
287
- const undeclared = actualNames.filter((n) => !declaredSet.has(n)).sort();
288
- if (undeclared.length > 0) {
289
- warnings.push(`库中有而声明无:${undeclared.join('、')}。`
290
- + '这些表没有元数据声明(可能来自旧版 CLI 或其他工具),不出现在 tables 中');
291
- }
269
+ // ⚠️ 同时取**对象类型**(2026-11-14,PR #74 合并后自查):`information_schema.tables` 把
270
+ // view 也算作表,而下面按声明名逐表 `SELECT COUNT(*)` 会把同名 view 的本体当查询执行
271
+ // (实测:view 底表被删 → `query_error`、退出码 2;store 连接封锁外部访问后
272
+ // `read_csv_auto` 类 view 同样整条失败)。这与 `store status` 的口径必须一致:
273
+ // 只数基表,非基表进 warnings(`nonBaseTablesWarning` 是唯一渲染点)。
274
+ const actual = await catalogRows(session, OBJECT_KINDS_SQL);
275
+ const actualNames = actual.map((r) => String(r.table_name));
276
+ const nonBase = nonBaseTables(actual);
277
+ // 声明名 → 库内实际名(DuckDB 标识符大小写不敏感,Codex PR#76:`"SCHEMA_VERSION"` 就是
278
+ // `schema_version` 本身)。下面 COUNT 用声明的名字(解析器照样能解析到),只在映射处用。
279
+ const actualNameOf = (declared) => actualNames.find((n) => sameObjectName(n, declared));
280
+ const actualSet = new Set(actualNames.filter((n) => !nonBase.some((x) => sameObjectName(n, x))));
281
+ // ⚠️ 两半漂移的 warning 走 `storeTablesWarnings`(**唯一渲染点**,2026-11-02 收敛):
282
+ // 此前本命令自己拼「声明有而库中无」+ `missingTableCauses`,而 `store status`/`init`
283
+ // 只拼「库中有而声明无」—— 同一库两种漂移,两条命令各报一半,缺表那半在 store 上
284
+ // 静默。这里与 store 现在共用同一个渲染器,`declaredMissing` 也不再单独算。
285
+ const warnings = [
286
+ ...(storeTablesWarnings(actualNames, opened.dbPath, opened.profileFlag) ?? []),
287
+ ...(nonBaseTablesWarning(nonBase) ?? []),
288
+ ];
292
289
  // 实际列集一次查全库(25 次往返 → 1 次):时间列被删的表不能让 timeRangeOf 的
293
290
  // `MIN("c")` 在 prepare 期抛 Binder Error 把整命令打成退出码 2(Task 7 审查
294
291
  // Important #1)——缺列降级为 time_range null + warning。
295
- const colRows = await session.run("SELECT table_name, column_name FROM information_schema.columns WHERE table_schema='main'");
292
+ const colRows = await catalogRows(session, "SELECT table_name, column_name FROM information_schema.columns WHERE table_schema='main'");
296
293
  const columnsOf = new Map();
297
- for (const row of colRows.rows) {
294
+ for (const row of colRows) {
298
295
  const tableName = String(row.table_name);
299
296
  const columnName = String(row.column_name);
300
297
  const set = columnsOf.get(tableName);
@@ -303,10 +300,20 @@ async function dbTables(argv) {
303
300
  else
304
301
  set.add(columnName);
305
302
  }
303
+ // 声明表 → 库内该表**基表**的列集(2026-11-15):同名 view 的列在这里**不算**该表的
304
+ // 列 —— 否则一条列名恰好相同的 view 会让「缺列」warning 静默。取不到就返 undefined,
305
+ // 由调用方跳过逐列核对(该名字已由 `nonBaseTablesWarning` 点名),不报假漂移。
306
+ const baseColumnsOf = (declared) => {
307
+ const actual = actualNameOf(declared);
308
+ if (actual === undefined || !actualSet.has(actual))
309
+ return undefined;
310
+ return columnsOf.get(actual);
311
+ };
306
312
  // 逐表:行数 + 时间范围;清单与顺序以 TABLES 为权威(裁决 R4:缺表的表整条跳过)。
307
313
  const tables = [];
308
314
  for (const t of TABLES) {
309
- if (!actualSet.has(t.name))
315
+ const actualName = actualNameOf(t.name);
316
+ if (actualName === undefined || !actualSet.has(actualName))
310
317
  continue;
311
318
  const r = await session.run(`SELECT COUNT(*) AS n FROM "${t.name}"`);
312
319
  // ⚠️ COUNT 是 BIGINT,经 getRowObjectsJson() 是**字符串** —— 必须 Number() 收敛。
@@ -317,7 +324,7 @@ async function dbTables(argv) {
317
324
  // 而 describe 才有的逐列核对在 tables 清单里缺失就是静默漂移。列集已在上面
318
325
  // 一次查全库(columnsOf),这里只做集合差,不加往返。
319
326
  const declaredCols = new Set(t.columns.map((c) => c.name));
320
- const actualCols = columnsOf.get(t.name) ?? new Set();
327
+ const actualCols = baseColumnsOf(t.name) ?? new Set();
321
328
  // 时间列缺了由下面那条专门警告说明(它还要解释 time_range 为何置 null),
322
329
  // 这里排除它,避免同一事实说两遍。
323
330
  const missingCols = [...declaredCols].filter((n) => !actualCols.has(n) && n !== t.timeColumn?.name);
@@ -335,7 +342,7 @@ async function dbTables(argv) {
335
342
  timeRange = await timeRangeOf(session, t);
336
343
  const dirty = await dirtyTimeValues(session, t);
337
344
  if (dirty > 0)
338
- warnings.push(dirtyTimeWarning(t.name, tc.name, dirty));
345
+ warnings.push(dirtyTimeWarning(t.name, tc.name, dirty, storeLocationOf(opened.dbPath, opened.profileFlag)));
339
346
  }
340
347
  else {
341
348
  warnings.push(`表 ${t.name} 缺少时间列 ${tc.name}(可能来自旧版 CLI 或库损坏),time_range 置 null`);
@@ -349,10 +356,10 @@ async function dbTables(argv) {
349
356
  pii_columns: piiColumnsOf(t),
350
357
  });
351
358
  }
352
- return ok({ tables }, { notice: PII_NOTICE, warnings });
359
+ return ok({ tables }, { notice: PII_NOTICE, warnings, field_notes: tablesFieldNotes() });
353
360
  }
354
361
  catch (e) {
355
- return thrownToQueryExit(e, TABLES);
362
+ return thrownToQueryExit(e, TABLES, false, storeLocationOf(opened.dbPath, opened.profileFlag));
356
363
  }
357
364
  finally {
358
365
  await session.close();
@@ -373,9 +380,9 @@ function describeColumn(c) {
373
380
  async function dbDescribe(argv) {
374
381
  // 子命令级次序沿 dbTables:--help 分流 → --pretty 开启缩进(G1) → parseStoreFlags → 位置参数。
375
382
  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(' ')}`);
383
+ const problem = helpArgsError(argv, acceptSet('describe'));
384
+ if (problem !== undefined)
385
+ return usageFail(problem);
379
386
  process.stdout.write(USAGE);
380
387
  return 0;
381
388
  }
@@ -392,35 +399,55 @@ async function dbDescribe(argv) {
392
399
  // 未知 flag(`--bogus`)会落进 rest —— 先按 `-` 前缀挑出来,避免被当成表名。
393
400
  const flagish = flags.rest.filter((a) => a.startsWith('-'));
394
401
  if (flagish.length > 0)
395
- return usageFail(`未知参数:${flagish.join(' ')}`);
402
+ return usageFail(`未知参数:${describeArgs(flagish)}`);
396
403
  if (flags.rest.length === 0) {
397
404
  return usageFail(`缺少表名:请给 db describe <表>\n可用表:${TABLES.map((t) => t.name).join('、')}`);
398
405
  }
399
406
  if (flags.rest.length > 1)
400
- return usageFail(`未知参数:${flags.rest.slice(1).join(' ')}`);
407
+ return usageFail(`未知参数:${describeArgs(flags.rest.slice(1))}`);
401
408
  // spec §8.2「未知 → usage + 候选」:闭集校验先于一切 I/O(不打开库就知道表名拼错)。
402
409
  // 候选来自 `TABLES`(前缀/编辑距离,大小写不敏感),不裸透 DuckDB 英文原文。
403
410
  const name = sanitizeControlChars(flags.rest[0]);
404
411
  const table = tableByName(name);
405
412
  if (table === undefined) {
406
413
  const candidates = suggestNames(name, TABLES.map((t) => t.name));
407
- return usageFail(`未知表:${describeArgs([name])}`, candidates.length > 0 ? `候选:${candidates.join('、')}` : '用 `qiyu db tables` 查看可用表');
414
+ return usageFail(`未知表:${describeArgs([name])}`, candidates.length > 0
415
+ ? `候选:${candidates.join('、')}`
416
+ : '用 `' + dbTablesCommand(storeLocationFromFlags(flags)) + '` 查看可用表');
408
417
  }
409
- const opened = await openGuardedSession(flags);
418
+ const opened = await openGuardedSession(flags, metadataTimeoutHint);
410
419
  if ('exit' in opened)
411
420
  return opened.exit;
412
- const session = opened.session;
421
+ // 超时 hint 换成元数据命令的说法(本命令没有可调过滤参数,query 那句对它是死路)。
422
+ const session = withTimeoutHint(opened.session, metadataTimeoutHint(storeLocationOf(opened.dbPath, opened.profileFlag)));
413
423
  try {
414
- // 表名来自 `TABLES` 闭集(代码内常量),拼进字面量安全;用户输入只用于上面的闭集查找。
415
- const present = (await session.run(`SELECT 1 FROM information_schema.tables WHERE table_schema='main' AND table_name='${table.name}'`))
416
- .rows.length > 0;
417
424
  const warnings = [];
425
+ // ⚠️ 与 `db tables` / `store status` 同口径(2026-11-15):同名对象不是基表(view 等)就
426
+ // **不执行它** —— 只出声明元数据、由 warnings 点名。此前只看表名在不在,一条底表已删的
427
+ // `daily_overview` view 会让 `COUNT(*)` 执行 view → Catalog Error → 整条命令退出 2,
428
+ // 报文还把 view 定义里的底表名说成「表不存在」。
429
+ const kinds = await catalogRows(session, OBJECT_KINDS_SQL);
430
+ const present = kinds.some((r) => sameObjectName(String(r.table_name), table.name));
431
+ const isNonBase = nonBaseTables(kinds).some((n) => sameObjectName(table.name, n));
432
+ if (isNonBase) {
433
+ warnings.push(`表 ${table.name} 在库中不是基表(view 等),本命令未执行它:以下为声明元数据`
434
+ + '(row_count/time_range 无法得知,置 null)。用 `'
435
+ + dbTablesCommand(storeLocationOf(opened.dbPath, opened.profileFlag))
436
+ + '` 确认该名字实际是什么对象');
437
+ }
418
438
  let rowCount = null;
419
439
  let timeRange = null;
420
440
  if (!present) {
421
- // R5:声明有但库中无 → 仍输出声明元数据,不报错(Agent 靠列清单判断
422
- // 「没同步」还是「没建库」)。此时 row_count/time_range 无从得知,置 null。
423
- warnings.push(`表 ${table.name} 在库中不存在(未同步或未建库);以下为声明元数据`);
441
+ // R5:声明有但库中无 → 仍输出声明元数据,不报错(Agent 需要知道该表「应该」有什么列,
442
+ // 才能核对是不是列漂移)。此时 row_count/time_range 无从得知,置 null。
443
+ // ⚠️ 成因文案**不得**再写「未同步或未建库」(2026-10-29 实测修正,两个成因都到不了
444
+ // 这个分支:未同步的库 25 张声明表全在、库文件缺失/零表早在 openGuardedSession 里
445
+ // 报 store_not_initialized)。与 db tables/query/stats 共用 missingTableCauses()。
446
+ warnings.push(`表 ${table.name} 在库中不存在(声明有而库中无);以下为声明元数据`
447
+ + '(row_count/time_range 无法得知,置 null)。' + missingTableCauses(opened.dbPath, opened.profileFlag));
448
+ }
449
+ else if (isNonBase) {
450
+ // 上面已点名、row_count/time_range 保持 null —— 只出声明元数据
424
451
  }
425
452
  else {
426
453
  const r = await session.run(`SELECT COUNT(*) AS n FROM "${table.name}"`);
@@ -430,8 +457,8 @@ async function dbDescribe(argv) {
430
457
  // ⚠️ 必须**先于** timeRangeOf:声明的时间列若已被删,`MIN("c")` 会在 prepare 期
431
458
  // 抛 Binder Error 把整命令打成退出码 2,row_count/columns/pii_columns 全丢——
432
459
  // 而「时间列被删」只是「列集不一致」的子集,应降级为 warning + time_range null。
433
- const actual = (await session.run(`SELECT column_name FROM information_schema.columns WHERE table_schema='main' AND table_name='${table.name}'`))
434
- .rows.map((row) => String(row.column_name));
460
+ const actual = (await catalogRows(session, `SELECT column_name FROM information_schema.columns WHERE table_schema='main' AND table_name='${table.name}'`))
461
+ .map((row) => String(row.column_name));
435
462
  const actualSet = new Set(actual);
436
463
  const declaredSet = new Set(table.columns.map((c) => c.name));
437
464
  const missing = table.columns.map((c) => c.name).filter((n) => !actualSet.has(n));
@@ -441,7 +468,7 @@ async function dbDescribe(argv) {
441
468
  timeRange = await timeRangeOf(session, table);
442
469
  const dirty = await dirtyTimeValues(session, table);
443
470
  if (dirty > 0)
444
- warnings.push(dirtyTimeWarning(table.name, tc.name, dirty));
471
+ warnings.push(dirtyTimeWarning(table.name, tc.name, dirty, storeLocationOf(opened.dbPath, opened.profileFlag)));
445
472
  }
446
473
  // tc 缺失时 timeRange 保持 null;下面的「少列」warning 已点名该时间列。
447
474
  if (missing.length > 0 || extra.length > 0) {
@@ -464,10 +491,10 @@ async function dbDescribe(argv) {
464
491
  time_range: timeRange,
465
492
  columns: table.columns.map(describeColumn),
466
493
  pii_columns: piiColumnsOf(table),
467
- }, { notice: PII_NOTICE, warnings });
494
+ }, { notice: PII_NOTICE, warnings, field_notes: describeFieldNotes() });
468
495
  }
469
496
  catch (e) {
470
- return thrownToQueryExit(e, TABLES);
497
+ return thrownToQueryExit(e, TABLES, false, storeLocationOf(opened.dbPath, opened.profileFlag));
471
498
  }
472
499
  finally {
473
500
  await session.close();
@@ -476,24 +503,35 @@ async function dbDescribe(argv) {
476
503
  export async function dbCommand(argv) {
477
504
  setPretty(false); // G1:每条命令入口重置输出格式 —— 同一进程内多次 run(测试)不残留上一条命令的开关。
478
505
  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 不接受额外参数`);
506
+ // ⚠️ 无子命令 = 用法错误(退 2 + JSON)—— 见 store.ts 同款注释(2026-11-07 审查)。
507
+ if (sub === undefined) {
508
+ return usageFail(`用法:qiyu db <tables|describe> [参数](\`qiyu db --help\` 查看全部)`, '可用子命令:tables、describe');
509
+ }
510
+ if (sub === '--help' || sub === '-h') {
511
+ // --help 不吞未知参数;已知 flag 与非 flag token(子命令名、取值)一律放行
512
+ //(`db --help describe --db /tmp/x` 是 Agent 的常见写法,此前会退 2)。
513
+ const problem = helpArgsError(rest, DB_SPECS.flatMap((sp) => sp.flags), '。--help 不接受额外参数');
514
+ if (problem !== undefined)
515
+ return usageFail(problem);
484
516
  process.stdout.write(USAGE);
485
517
  return 0;
486
518
  }
487
519
  // G1:--pretty 是输出开关,必须写在具体子命令之后(`db tables --pretty`)。
488
520
  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 不接受额外参数`);
521
+ const problem = helpArgsError(rest, DB_SPECS.flatMap((sp) => sp.flags));
522
+ if (problem !== undefined)
523
+ return usageFail(`${problem}。--pretty 不接受额外参数`);
524
+ const badPos = prettyPositionalProblem(rest, DB_SPECS);
525
+ if (badPos !== undefined)
526
+ return usageFail(badPos);
493
527
  if (rest.includes('--help') || rest.includes('-h')) {
494
528
  process.stdout.write(USAGE);
495
529
  return 0;
496
530
  }
531
+ // ⚠️ 位置参数一律按「顺序写反」引导(2026-11-07 审查):此前把子命令名当
532
+ // 「未知参数」报出(`db --pretty tables` → 「未知参数:tables」),而 `tables`
533
+ // 是本命令**已知**的子命令;同一写法在 stats 上给的是「必须写在子命令之后」。
534
+ // 五个命令族各写一份,答案还互相矛盾 —— 判据收敛到 `prettyAfterSubcommand`。
497
535
  return usageFail(prettyAfterSubcommand('db'));
498
536
  }
499
537
  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
+ }