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
@@ -10,7 +10,8 @@
10
10
  // · verify 对 snapshot 任务做三方核对(本地表行数 / 上游任务 fetch 的 apiCount /
11
11
  // sync_state 状态),对 windowed 任务不做上游全量重拉(成本高),只核对
12
12
  // local_rows 与 sync_state 成功状态的一致性——expected_from_api 为 null,
13
- // drift 非空时 detail 说明核对方式;
13
+ // drift 非空时 detail 说明核对方式;本地同名对象不是基表(view 等)时不计数、
14
+ // 也不为它发上游请求,drift 报 not_base_table(无法核对 ≠ 一致);
14
15
  // · install/uninstall 的平台条目生成与命令执行在 src/schedule/install.ts,
15
16
  // 平台检测与外部命令均为注入点(__setPlatform/__setRun);
16
17
  // · install 前置探测(E 高-1):**必须存在真实成功证据** —— sync_state 有
@@ -25,20 +26,23 @@
25
26
  // 输出键一律下划线命名(spec §七:range_status / gaps_count / local_rows /
26
27
  // expected_from_api / state_windows_consistent)——本仓 Agent 契约的统一形态。
27
28
  import { homedir } from 'node:os';
28
- import { statSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
29
+ import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
29
30
  import { dirname } from 'node:path';
31
+ import { SCHEMA_VERSION_COLUMNS_SQL, statGuard, schemaVersionMissing, OBJECT_KINDS_SQL, nonBaseTables, sameObjectName } from './store-precheck.js';
30
32
  import { SYNC_TASKS, taskById, UNSUPPORTED_DATASETS } from '../sync/registry.js';
31
33
  import { listGaps, listWatermarks } from '../sync/state.js';
34
+ import { statusFieldNotes, syncInstallFieldNotes, tasksFieldNotes, verifyFieldNotes } from './sync-notes.js';
32
35
  import { resolveStoreConfig, currentStoreEnv } from '../store/config.js';
33
36
  import { openStore } from '../store/index.js';
34
37
  import { tableByName } from '../store/schema.js';
35
38
  import { resolveCredentialsUsingFile, currentCredentialEnv } from './credentials-source.js';
36
- import { ok, fail, usageFail, setPretty } from '../output.js';
39
+ import { ok, fail, usageFail, failFromTagged, setPretty, describeArgs, syncRunCommand, storeInitCommand, storeLocationOf, dbTablesCommand, } from '../output.js';
37
40
  import { runSyncRun, SYNC_RUN_USAGE, msToShanghaiIso, RUN_FLAGS } from './sync-run.js';
38
41
  import { thrownToExit } from './store.js';
39
- import { currentPlatform, runScheduleCommand, planInstall, planUninstall, } from '../schedule/install.js';
40
- import { GLOBAL_FLAGS, GLOBAL_FLAG_NAMES, prettyAfterSubcommand, REJECTED_FLAGS, STORE_FLAGS, valueFlagNames } from './spec-types.js';
41
- import { STORE_VALUE_FLAG_NAMES } from './store-flags.js';
42
+ import { currentPlatform, parseCron, runScheduleCommand, planInstall, planUninstall, } from '../schedule/install.js';
43
+ import { GLOBAL_FLAGS, helpArgsError, prettyAfterSubcommand, prettyPositionalProblem, REJECTED_FLAGS, STORE_FLAGS, valueFlagNames } from './spec-types.js';
44
+ import { DB_PATH_HELP, STORE_VALUE_FLAG_NAMES } from './store-flags.js';
45
+ import { nonEmptyValue } from '../core/config.js';
42
46
  /** `sync install` 的业务 flag。 */
43
47
  const INSTALL_FLAGS = [
44
48
  { name: '--schedule', kind: 'value' },
@@ -51,7 +55,8 @@ const UNINSTALL_FLAGS = [{ name: '--yes', kind: 'bool' }];
51
55
  const TASKS_FLAGS = [...GLOBAL_FLAGS];
52
56
  /**
53
57
  * 命令契约(F 组 D4):`skill check` 据此判断 skill 正文里的 `qiyu sync …` 是否真的存在。
54
- * `flags` 是**完整接受集**(含全局 flag),`--pretty` 同时在 `rejected` 里。
58
+ * `flags` 是**完整接受集**(含全局 flag);`rejected` 直接取 `REJECTED_FLAGS`(当前为空 ——
59
+ * `--pretty` 自 2026-10-24 G1 起已实现,不再是 rejected,见 `spec-types.ts` 顶部)。
55
60
  *
56
61
  * ⚠️ `sync run` 的 spec 在这里而不在 `sync-run.ts`:spec 描述的是**命令路径**,而路径的
57
62
  * 分派在 `syncCommand`;`runSyncRun` 只拿到剥掉 `run` 之后的参数。解析器的 flag 常量由
@@ -125,11 +130,11 @@ const USAGE = `用法:qiyu sync <子命令> [参数]
125
130
 
126
131
  CRON 为 5 段(分 时 日 月 周),支持 * / 数字 / a-b / a-b/k / */k / 逗号列表。
127
132
  存储定位:--db / --profile / --backend(store 命令同族)。
133
+ ${DB_PATH_HELP}
128
134
  install 的平台形态:darwin=launchd plist、linux=systemd unit+timer(crontab 兜底)、
129
135
  win32=schtasks。安装前置:库已初始化且至少成功同步过一次(sync_state 有
130
136
  range_status=complete 或 last_synced_at 非空的行;全败的 run 只留 pending,不算跑通)。
131
137
  `;
132
- const KNOWN = new Set(GLOBAL_FLAG_NAMES);
133
138
  function parseSubFlags(argv, valueFlags, boolFlags = []) {
134
139
  const out = { values: {}, flags: new Set(), rest: [] };
135
140
  for (let i = 0; i < argv.length; i++) {
@@ -138,6 +143,13 @@ function parseSubFlags(argv, valueFlags, boolFlags = []) {
138
143
  const v = argv[i + 1];
139
144
  if (v === undefined || v.startsWith('--'))
140
145
  throw new Error(`${a} 缺少取值`);
146
+ // ⚠️ 重复的取值参数必须报错(2026-11-14,历史审查 PR#4/PR#71 复核):此前静默覆盖,
147
+ // 而 `store` / `query` / `sync run` 三处都拒绝(`store-flags.ts`、`query.ts`、
148
+ // `sync-run.ts`)—— 同一个输入在不同子命令上两种行为。判据是「重复会不会丢掉一个值」,
149
+ // 布尔 flag 反复出现是幂等的,不在其列。
150
+ if (Object.hasOwn(out.values, a)) {
151
+ throw new Error(`${a} 重复出现:只能给一次(不做静默覆盖)`);
152
+ }
141
153
  out.values[a] = v;
142
154
  i++;
143
155
  }
@@ -161,13 +173,19 @@ function parseSubFlags(argv, valueFlags, boolFlags = []) {
161
173
  }
162
174
  return out;
163
175
  }
164
- /** 子命令的 --help 分流:--help 在则打 USAGE;带非 KNOWN 额外参数 → usage。 */
165
- function subHelp(argv) {
176
+ /**
177
+ * 子命令的 --help 分流:--help 在则打 USAGE;只有**未知 flag** 才算额外参数。
178
+ *
179
+ * ⚠️ 此前拿 `GLOBAL_FLAG_NAMES` 过滤 argv:`sync install --schedule "0 3 * * *" --help`
180
+ * 退 2 并说「未知参数:--schedule、0 3 * * *」—— 一个帮助请求被自己的合法参数判了死刑
181
+ *(2026-11-06 审查;`api list --all --help` 却退 0)。完整接受集从 spec 取。
182
+ */
183
+ function subHelp(argv, sub) {
166
184
  if (!argv.includes('--help') && !argv.includes('-h'))
167
185
  return null;
168
- const extra = argv.filter((a) => !KNOWN.has(a));
169
- if (extra.length > 0)
170
- return usageFail(`未知参数:${extra.join(' ')}。--help 不接受额外参数`);
186
+ const problem = helpArgsError(argv, SYNC_SPECS.find((sp) => sp.path[1] === sub)?.flags ?? GLOBAL_FLAGS, '。--help 不接受额外参数');
187
+ if (problem !== undefined)
188
+ return usageFail(problem);
171
189
  process.stdout.write(USAGE);
172
190
  return 0;
173
191
  }
@@ -175,7 +193,9 @@ function subHelp(argv) {
175
193
  function selectTasks(ids) {
176
194
  const unknown = ids.filter((id) => taskById(id) === undefined);
177
195
  if (unknown.length > 0) {
178
- return usageFail(`未知任务:${unknown.join('、')}\n可用任务:${SYNC_TASKS.map((t) => t.id).join('、')}`);
196
+ // describeArgs 渲染取值(空串 → `''`):`sync status ''` 此前冒号后空白,
197
+ // Agent 读不出自己传了什么(sync-run.ts 同款,2026-10-29)。
198
+ return usageFail(`未知任务:${describeArgs(unknown)}\n可用任务:${SYNC_TASKS.map((t) => t.id).join('、')}`);
179
199
  }
180
200
  return ids.length > 0 ? ids.map((id) => taskById(id)) : SYNC_TASKS;
181
201
  }
@@ -184,60 +204,34 @@ function resolveConfig(flags) {
184
204
  flags,
185
205
  env: currentStoreEnv(),
186
206
  });
187
- return { path: resolved.config.path, backend: resolved.config.backend, config: resolved.config };
207
+ return {
208
+ path: resolved.config.path, backend: resolved.config.backend, config: resolved.config,
209
+ ...(resolved.profileFlag !== undefined ? { profileFlag: resolved.profileFlag } : {}),
210
+ };
188
211
  }
189
212
  /** 只读命令的库前置检查(statSync 分流沿 store status;hint 统一指 store init,spec §九)。 */
190
- function statGuard(path) {
191
- let st;
192
- try {
193
- st = statSync(path);
194
- }
195
- catch (e) {
196
- if (e.code === 'ENOENT') {
197
- return fail({
198
- code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
199
- message: `数据库文件不存在:${path}`,
200
- hint: '数据库尚未初始化。请先运行:qiyu store init',
201
- });
202
- }
203
- return fail({
204
- code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
205
- message: `无法访问 ${path}:${e instanceof Error ? e.message : String(e)}`,
206
- hint: '请检查路径权限(只读命令不需要写权限)',
207
- });
208
- }
209
- if (!st.isFile()) {
210
- return fail({
211
- code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
212
- message: `不是普通文件:${path}`,
213
- hint: '--db 指向的不是普通文件,请给出 .duckdb 数据库文件路径',
214
- });
215
- }
216
- return null;
217
- }
218
213
  /** 打开 ro 库;结构不完整(缺 schema_version)视为「不是本 CLI 创建的库」。 */
219
- async function openRo(config) {
214
+ async function openRo(config, profileFlag) {
220
215
  let store;
221
216
  try {
222
217
  store = await openStore(config, 'ro');
223
218
  }
224
219
  catch (e) {
225
- return { code: thrownToExit(e) };
220
+ return { code: thrownToExit(e, profileFlag) };
226
221
  }
227
222
  try {
228
223
  const names = await store.tables();
229
- if (!names.includes('schema_version')) {
224
+ // ⚠️ 表名不是身份证明(2026-11-07 审查实测):他人工具的 schema_version 可能没有
225
+ // version 列 —— 只认表名会让后续查询落 internal,把「不是本 CLI 的库」说成损坏。
226
+ const versionColumns = names.some((n) => sameObjectName('schema_version', n))
227
+ ? (await store.query(SCHEMA_VERSION_COLUMNS_SQL)).rows.map((r) => String(r.column_name))
228
+ : undefined;
229
+ const missing = schemaVersionMissing(config.path, names, versionColumns);
230
+ if (missing !== null) {
230
231
  await store.close();
231
- // 成因分形(store.ts 同款):有表无 schema_version 是他人库——store init 会再次
232
- // 拒绝(duckdb.ts init 的他人库防线),引导过去就是 store init → sync status 死循环;
233
- // 空库(无任何表)才是「init 可补」的成因。
234
- return { code: fail({
235
- code: 'store_not_initialized', kind: 'store_not_initialized', retryable: false,
236
- message: `数据库结构不完整(缺表):${config.path}`,
237
- hint: names.length > 0
238
- ? '目标数据库不是本 CLI 创建的,请换 --db 路径'
239
- : '空库(无任何表)。请先运行:qiyu store init',
240
- }) };
232
+ // 成因分形在共享实现里(有表无 schema_version = 他人库 → 换路径;
233
+ // 零表才是「init 可补」)。关 store 是调用方的所有权责任,故在此 fail。
234
+ return { code: fail(missing) };
241
235
  }
242
236
  return { store };
243
237
  }
@@ -246,7 +240,7 @@ async function openRo(config) {
246
240
  await store.close();
247
241
  }
248
242
  catch { /* 清理错误不掩盖原异常 */ }
249
- return { code: thrownToExit(e) };
243
+ return { code: thrownToExit(e, profileFlag) };
250
244
  }
251
245
  }
252
246
  // —— sync status ——
@@ -263,7 +257,7 @@ function resolvedRangeOut(st) {
263
257
  return [msToShanghaiIso(s), msToShanghaiIso(e)];
264
258
  }
265
259
  async function syncStatus(argv) {
266
- const help = subHelp(argv);
260
+ const help = subHelp(argv, 'status');
267
261
  if (help !== null)
268
262
  return help;
269
263
  let parsed;
@@ -283,14 +277,17 @@ async function syncStatus(argv) {
283
277
  let resolved;
284
278
  try {
285
279
  resolved = resolveConfig({ db: parsed.values['--db'], profile: parsed.values['--profile'], backend: parsed.values['--backend'] });
280
+ // ⚠️ failFromTagged(不是 usageFail):配置层会抛带 `kind: config_insecure` 的错误
281
+ // (含凭证且权限过宽 —— 退出码 1、只能由人 chmod)。包成 usageFail 会把它降级成
282
+ // 「改参数重来」退出码 2 并丢掉 hint,与 auth/api 那条路径的说法相反。
286
283
  }
287
284
  catch (e) {
288
- return usageFail(e.message);
285
+ return failFromTagged(e);
289
286
  }
290
287
  const guarded = statGuard(resolved.path);
291
288
  if (guarded !== null)
292
289
  return guarded;
293
- const opened = await openRo(resolved.config);
290
+ const opened = await openRo(resolved.config, resolved.profileFlag);
294
291
  if (opened.code !== undefined || !opened.store)
295
292
  return opened.code ?? 1;
296
293
  const store = opened.store;
@@ -328,7 +325,7 @@ async function syncStatus(argv) {
328
325
  locked: (st?.lockedBy ?? null) !== null,
329
326
  };
330
327
  });
331
- return ok({ tasks: tasksOut });
328
+ return ok({ tasks: tasksOut }, { field_notes: statusFieldNotes() });
332
329
  }
333
330
  catch (e) {
334
331
  return thrownToExit(e);
@@ -337,8 +334,21 @@ async function syncStatus(argv) {
337
334
  await store.close();
338
335
  }
339
336
  }
337
+ // —— sync verify ——
338
+ /**
339
+ * `sync verify` 的 `drift[].kind` 全部取值 —— Agent 按值分支,所以每个值都必须在
340
+ * README 图例里有释义与动作(`tests/sync-enums.test.ts` 双向钉住:枚举 ⊆ 图例、
341
+ * 图例 ⊆ 枚举)。
342
+ */
343
+ export const DRIFT_KINDS = [
344
+ 'not_synced', // sync_state 无该任务记录(从未同步)
345
+ 'state_pending', // 上次运行未完成/中断(range_status 非 complete)
346
+ 'count_mismatch', // 本地行数 ≠ 上游行数(仅快照任务做上游核对)
347
+ 'fetch_failed', // 上游取数失败 —— 无法核对 ≠ 一致
348
+ 'not_base_table', // 本地同名对象不是基表(view 等)—— 不计数、不核对
349
+ ];
340
350
  async function syncVerify(argv) {
341
- const help = subHelp(argv);
351
+ const help = subHelp(argv, 'verify');
342
352
  if (help !== null)
343
353
  return help;
344
354
  let parsed;
@@ -354,42 +364,82 @@ async function syncVerify(argv) {
354
364
  const tasks = selectTasks(parsed.rest);
355
365
  if (typeof tasks === 'number')
356
366
  return tasks;
357
- // 凭证惰性解析:快照任务需要上游 fetch;纯 windowed 选中时不碰凭证
358
- //(归因准确:本地核对不该因缺环境变量失败)。
359
- const needsUpstream = tasks.some((t) => t.kind === 'snapshot');
360
- let creds;
361
- if (needsUpstream) {
362
- const credOutcome = resolveCredentialsUsingFile(currentCredentialEnv());
363
- if (!credOutcome.ok)
364
- return fail(credOutcome.error);
365
- creds = credOutcome.creds;
366
- }
367
+ // —— store 配置解析(**先于**凭证)——
368
+ // ⚠️ 次序即归因(Codex PR #69):`--profile typo` 是参数错误(usage,退出码 2),
369
+ // 缺凭证是环境错误(auth_missing,退出码 1)。凭证侧按 `--profile` 选档后报
370
+ // 「缺少 appKey」会把拼错的档名说成「没配凭证」—— 参数错误必须排在环境错误之前。
367
371
  let resolved;
368
372
  try {
369
373
  resolved = resolveConfig({ db: parsed.values['--db'], profile: parsed.values['--profile'], backend: parsed.values['--backend'] });
374
+ // ⚠️ failFromTagged(不是 usageFail):配置层会抛带 `kind: config_insecure` 的错误
375
+ // (含凭证且权限过宽 —— 退出码 1、只能由人 chmod)。包成 usageFail 会把它降级成
376
+ // 「改参数重来」退出码 2 并丢掉 hint,与 auth/api 那条路径的说法相反。
370
377
  }
371
378
  catch (e) {
372
- return usageFail(e.message);
379
+ return failFromTagged(e);
380
+ }
381
+ // 凭证懒解析(Codex PR#76 第三轮):只有**真的会发上游请求**的快照任务才算。凭证是
382
+ // 环境问题(auth_missing,退出码 1),而「本地同名对象不是基表」是本地可诊断的 drift ——
383
+ // 若后者成立,先报 auth_missing 会把真正的结论盖住。先解析一次(保持「库打不开时凭证问题
384
+ // 不抢先」的既有次序),**用不用**由下面的循环按实际需要决定;用不上就只告警。
385
+ const needsUpstream = tasks.some((t) => t.kind === 'snapshot');
386
+ let creds;
387
+ let credError = null;
388
+ if (needsUpstream) {
389
+ const credOutcome = resolveCredentialsUsingFile(currentCredentialEnv(), { profile: parsed.values['--profile'] });
390
+ if (credOutcome.ok)
391
+ creds = credOutcome.creds;
392
+ else
393
+ credError = credOutcome.error;
373
394
  }
374
395
  const guarded = statGuard(resolved.path);
375
396
  if (guarded !== null)
376
397
  return guarded;
377
- const opened = await openRo(resolved.config);
398
+ const opened = await openRo(resolved.config, resolved.profileFlag);
378
399
  if (opened.code !== undefined || !opened.store)
379
400
  return opened.code ?? 1;
380
401
  const store = opened.store;
381
402
  try {
382
403
  const states = await listWatermarks(store);
404
+ // ⚠️ 只对**基表**做 COUNT(2026-11-14,PR #75 合并后自查):`information_schema` 把 view
405
+ // 也算作表,同名 view 的 `COUNT(*)` 会把 view 本体当查询执行 —— 底表被删/读外部文件时
406
+ // verify 整条落 internal(实测报文还把 view 定义里的底表名说成存储损坏、建议「备份重建」)。
407
+ // `store status` / `store init` / `db tables` 已是「只认基表、非基表进 warnings」,
408
+ // verify 同口径:数不出来就不报数,按 drift 点名(无法核对 ≠ 一致,沿 fetch_failed 的语义)。
409
+ // ⚠️ 按大小写不敏感比对(Codex PR#76 实测):一条 `"TICKETS"` view 会被 `"tickets"`
410
+ // 解析到并被执行,所以这里不能 `Set.has()` 精确比名字。
411
+ const nonBases = nonBaseTables((await store.query(OBJECT_KINDS_SQL)).rows);
412
+ const isNonBaseTask = (t) => nonBases.some((n) => sameObjectName(t.table, n));
413
+ // 凭证缺失只在**确实要发上游请求**时才致命:所有选中的快照任务本地都不是基表时,
414
+ // 本命令根本用不上凭证 —— 如实报 drift(not_base_table)比报 auth_missing 更有用。
415
+ if (credError !== null && !tasks.filter((t) => t.kind === 'snapshot').every(isNonBaseTask)) {
416
+ return fail(credError);
417
+ }
418
+ const loc = storeLocationOf(resolved.path, resolved.profileFlag);
383
419
  const tasksOut = [];
384
420
  for (const t of tasks) {
385
- const localRows = await store.count(t.table);
421
+ const isNonBase = isNonBaseTask(t);
422
+ const localRows = isNonBase ? null : await store.count(t.table);
386
423
  const st = states.get(t.id);
387
424
  const stateConsistent = st !== undefined && st.rangeStatus === 'complete' && st.watermark !== null;
388
425
  const drift = [];
426
+ if (isNonBase) {
427
+ drift.push({
428
+ kind: 'not_base_table',
429
+ detail: `本地 ${t.table} 不是基表(view 等),未做行数核对 —— 执行它的主体会读到`
430
+ + '错误数据或直接失败,所以「无法核对」不等于一致。用 `' + dbTablesCommand(loc)
431
+ + '` 确认该名字实际是什么对象(非基表会在 meta.warnings 点名);若本 CLI 的表已被'
432
+ + '同名 view 取代:先备份旧库文件,再把 --db 换成新的 .duckdb 路径跑 '
433
+ + storeInitCommand('<新路径>', resolved.profileFlag) + ' 建库、'
434
+ + syncRunCommand('<新路径>', resolved.profileFlag) + ' 重新拉取'
435
+ + '(把 <新路径> 整段替换成新路径,不要指回出问题的文件)',
436
+ });
437
+ }
389
438
  if (st === undefined) {
390
439
  drift.push({
391
440
  kind: 'not_synced',
392
- detail: 'sync_state 无该任务记录(从未同步)。请先运行:qiyu sync run',
441
+ detail: 'sync_state 无该任务记录(从未同步)。请先运行:'
442
+ + syncRunCommand(resolved.path, resolved.profileFlag),
393
443
  });
394
444
  }
395
445
  else if (!stateConsistent) {
@@ -397,12 +447,15 @@ async function syncVerify(argv) {
397
447
  kind: 'state_pending',
398
448
  detail: `sync_state.range_status=${st.rangeStatus ?? 'null'}(最后一次运行未完成或中断)。`
399
449
  + (t.kind === 'windowed'
400
- ? 'windowed 任务不做上游全量重拉(成本高):核对方式为本地行数与 sync_state 成功状态一致性——重跑 qiyu sync run 补全后再 verify。'
450
+ ? 'windowed 任务不做上游全量重拉(成本高):核对方式为本地行数与 sync_state 成功状态一致性——重跑 '
451
+ + syncRunCommand(resolved.path, resolved.profileFlag) + ' 补全后再 verify。'
401
452
  : '快照任务将以上游取数核对本地行数。'),
402
453
  });
403
454
  }
404
455
  let expectedFromApi = null;
405
- if (t.kind === 'snapshot') {
456
+ // 本地没有可数的表时无从核对:不再为此花一次上游请求(`localRows === null` 时
457
+ // `null !== number` 恒真,会白白把每条快照任务打成 count_mismatch)。
458
+ if (t.kind === 'snapshot' && localRows !== null) {
406
459
  // 上游取数 = 任务 fetch(配对口径沿引擎:apiCount 为准,缺省取行数)。
407
460
  try {
408
461
  const res = await t.fetch({ start: 0, end: Date.now(), index: 0, total: 1 }, { store, credentials: creds });
@@ -430,7 +483,7 @@ async function syncVerify(argv) {
430
483
  drift,
431
484
  });
432
485
  }
433
- const code = ok({ tasks: tasksOut });
486
+ const code = ok({ tasks: tasksOut }, { field_notes: verifyFieldNotes() });
434
487
  const hasDrift = tasksOut.some((t) => t.drift.length > 0);
435
488
  return hasDrift ? 1 : code;
436
489
  }
@@ -459,7 +512,9 @@ const INSTALL_STORE_PASSTHROUGH = STORE_VALUE_FLAGS;
459
512
  * 这里只固化「env 派生」:配置文件 store.path(HOME 下,调度任务自己读得到)与
460
513
  * 内置默认值**不固化**(批 4 裁定:默认值固化会引入漂移)。
461
514
  * 实现约束:**不读配置文件内容来生成参数**(配置路径不固化,调度任务自己会读它);
462
- * env 已给但解析失败/为空时由 resolveConfig 在更早处抛 usage,不会走到这里。
515
+ * env 已给但解析失败时由 resolveConfig 在更早处抛 usage,不会走到这里。
516
+ * ⚠️ env 值为**空串**不算「已给」(2026-10-29):空串视为未设置,这条来源整体不成立
517
+ * —— 否则固化的是**回落后的**配置文件/默认值,等于把安装当时的配置悄悄钉进调度命令。
463
518
  * 同一 flag 只在 flag 缺席时才补 env 派生值 —— 显式 flag 永远优先(与 resolveStoreConfig
464
519
  * 的 flags > env 优先级一致),不会出现两个 --db。
465
520
  */
@@ -473,15 +528,26 @@ function storeArgsFor(parsed, resolved) {
473
528
  push(f, v);
474
529
  }
475
530
  // ② env 派生 → 固化解析结果(仅当对应 flag 未给)
476
- if (parsed.values['--db'] === undefined && process.env.QIYU_DB_PATH !== undefined) {
531
+ // ⚠️ 空串视为未设置(2026-10-29,与下面的 --profile 同一条口径):`QIYU_DB_PATH=` 时
532
+ // resolveStoreConfig 会正确回落到配置文件/默认值,但这里若照烘 `--db <解析结果>`,
533
+ // 调度命令就被钉死在**安装当时**的路径上 —— 之后改配置文件的 store.path 不再生效,
534
+ // 且用户从未设过的变量变成了一个显式 flag。
535
+ if (parsed.values['--db'] === undefined && nonEmptyValue(process.env.QIYU_DB_PATH) !== undefined) {
477
536
  // 固化的是 resolveStoreConfig 解析后的**绝对路径**(env 的相对路径/`~` 已展开)——
478
537
  // 调度任务的 cwd 与 HOME 都可能不同,相对路径会指向别处。
479
538
  push('--db', resolved.path);
480
539
  }
481
- if (parsed.values['--profile'] === undefined && process.env.QIYU_PROFILE !== undefined) {
482
- push('--profile', process.env.QIYU_PROFILE);
483
- }
484
- if (parsed.values['--backend'] === undefined && process.env.QIYU_STORE_BACKEND !== undefined) {
540
+ // ⚠️ 空串视为未设置(2026-10-29 实测修):`export QIYU_PROFILE=` 是 shell 里"变量没填"
541
+ // 的典型形态。此前只判 `!== undefined`,于是 `--profile` **带一个空取值**被烘进调度命令:
542
+ // sync run --profile "" → 每次调度执行都报「--profile 不能为空」退出码 2,
543
+ // 而安装时(dry-run 与 --yes 都一样)不报任何错 —— 装完才开始永久失败。
544
+ // 判据与 `resolveProfileName` 的空串口径同源(core/config.ts)。
545
+ if (parsed.values['--profile'] === undefined) {
546
+ const envProfile = nonEmptyValue(process.env.QIYU_PROFILE);
547
+ if (envProfile !== undefined)
548
+ push('--profile', envProfile);
549
+ }
550
+ if (parsed.values['--backend'] === undefined && nonEmptyValue(process.env.QIYU_STORE_BACKEND) !== undefined) {
485
551
  // backend 当前唯一合法值 duckdb(resolveStoreConfig 已校验),固化解析结果而非原始 env 值。
486
552
  push('--backend', resolved.backend);
487
553
  }
@@ -495,11 +561,11 @@ function storeArgsFor(parsed, resolved) {
495
561
  * 同步过的库上,探测名不副实(且 hint 会劝用户「先跑通一次」却已经被放行)。
496
562
  * 冷却行(`__ratelimit__:` 前缀)本就不是任务行,按前缀排除。
497
563
  */
498
- async function probeSynced(config, path) {
564
+ async function probeSynced(config, path, profileFlag) {
499
565
  const guarded = statGuard(path);
500
566
  if (guarded !== null)
501
567
  return guarded;
502
- const opened = await openRo(config);
568
+ const opened = await openRo(config, profileFlag);
503
569
  if (opened.code !== undefined || !opened.store)
504
570
  return opened.code ?? 1;
505
571
  const store = opened.store;
@@ -511,7 +577,7 @@ async function probeSynced(config, path) {
511
577
  return fail({
512
578
  code: 'sync_not_run', kind: 'sync_not_run', retryable: false,
513
579
  message: '尚未成功同步过任何任务(sync_state 无 range_status=complete 且无 last_synced_at 的记录)',
514
- hint: '安装调度前请先跑通一次同步:qiyu sync run',
580
+ hint: '安装调度前请先跑通一次同步:' + syncRunCommand(path, profileFlag),
515
581
  });
516
582
  }
517
583
  return null;
@@ -523,7 +589,7 @@ async function probeSynced(config, path) {
523
589
  /** 命令行形态(输出用):argv 以空格连接(含空格的部分已按 shellQuote 引住)。 */
524
590
  const commandText = (argv) => argv.join(' ');
525
591
  async function syncInstall(argv) {
526
- const help = subHelp(argv);
592
+ const help = subHelp(argv, 'install');
527
593
  if (help !== null)
528
594
  return help;
529
595
  let parsed;
@@ -534,7 +600,7 @@ async function syncInstall(argv) {
534
600
  return usageFail(e.message);
535
601
  }
536
602
  if (parsed.rest.length > 0)
537
- return usageFail(`未知参数:${parsed.rest.join(' ')}`);
603
+ return usageFail(`未知参数:${describeArgs(parsed.rest)}`);
538
604
  // G1:--pretty 已实现(原拒绝点在 parseSubFlags 的 throw)。
539
605
  if (parsed.flags.has('--pretty'))
540
606
  setPretty(true);
@@ -542,6 +608,18 @@ async function syncInstall(argv) {
542
608
  if (schedule === undefined) {
543
609
  return usageFail('缺少 --schedule CRON(5 段:分 时 日 月 周)', '例如:qiyu sync install --schedule "*/30 * * * *"');
544
610
  }
611
+ // ⚠️ cron 解析必须**先于一切 I/O**(2026-10-29 实测修):闭集(`--schedule` 的语法)
612
+ // 校验写在 probeSynced 之后时,未同步过的库上 `sync install --schedule '不是 cron'`
613
+ // 报的是 `sync_not_run`(退出码 1,「先去跑一次同步」)—— 而真正错的是参数,Agent 会
614
+ // 照 hint 去跑一次全量同步、再回来才看到 cron 错误(白跑一轮,且第一次的报错指向
615
+ // 了错误的动作)。query 的 `--table` 早已是同款次序(「闭集校验先于一切 I/O」)。
616
+ // 渲染走 describeArgs:`--schedule ''` 否则是「实际 1 段:」冒号后空白。
617
+ try {
618
+ parseCron(schedule);
619
+ }
620
+ catch (e) {
621
+ return usageFail(e.message);
622
+ }
545
623
  const yes = parsed.flags.has('--yes');
546
624
  let platform;
547
625
  try {
@@ -554,16 +632,19 @@ async function syncInstall(argv) {
554
632
  let config;
555
633
  let path;
556
634
  let backend;
635
+ let profileFlag;
557
636
  try {
558
637
  const r = resolveConfig({ db: parsed.values['--db'], profile: parsed.values['--profile'], backend: parsed.values['--backend'] });
559
638
  config = r.config;
560
639
  path = r.path;
561
640
  backend = r.backend;
641
+ profileFlag = r.profileFlag;
642
+ // ⚠️ 同 syncStatus:带 kind 的错误(config_insecure)必须如实透出。
562
643
  }
563
644
  catch (e) {
564
- return usageFail(e.message);
645
+ return failFromTagged(e);
565
646
  }
566
- const probe = await probeSynced(config, path);
647
+ const probe = await probeSynced(config, path, profileFlag);
567
648
  if (probe !== null)
568
649
  return probe;
569
650
  // 计划生成(cron 解析 / 平台映射失败 → usage)
@@ -592,7 +673,7 @@ async function syncInstall(argv) {
592
673
  entries: plan.entries,
593
674
  commands: plan.commands.map((c) => ({ command: commandText(c), executed: false, ok: null, error: null })),
594
675
  notes: [...plan.notes, envNote, '这是 dry-run:未写入任何文件、未执行任何命令。加 --yes 实际安装。'],
595
- });
676
+ }, { field_notes: syncInstallFieldNotes('install-dry') });
596
677
  }
597
678
  // --yes:写文件 + 执行命令(逐条记结果,失败不中断、退出码如实报 1)
598
679
  const installed = [];
@@ -614,11 +695,11 @@ async function syncInstall(argv) {
614
695
  const code = ok({
615
696
  platform, schedule, dry_run: false,
616
697
  installed, commands: cmdResults, notes: [...plan.notes, envNote],
617
- });
698
+ }, { field_notes: syncInstallFieldNotes('install-real') });
618
699
  return cmdResults.some((c) => !c.ok) ? 1 : code;
619
700
  }
620
701
  async function syncUninstall(argv) {
621
- const help = subHelp(argv);
702
+ const help = subHelp(argv, 'uninstall');
622
703
  if (help !== null)
623
704
  return help;
624
705
  let parsed;
@@ -629,7 +710,7 @@ async function syncUninstall(argv) {
629
710
  return usageFail(e.message);
630
711
  }
631
712
  if (parsed.rest.length > 0)
632
- return usageFail(`未知参数:${parsed.rest.join(' ')}`);
713
+ return usageFail(`未知参数:${describeArgs(parsed.rest)}`);
633
714
  // G1:--pretty 已实现(原拒绝点在 parseSubFlags 的 throw)。
634
715
  if (parsed.flags.has('--pretty'))
635
716
  setPretty(true);
@@ -647,22 +728,33 @@ async function syncUninstall(argv) {
647
728
  platform, dry_run: true,
648
729
  remove: plan.remove,
649
730
  commands: plan.commands.map((c) => ({ command: commandText(c), executed: false, ok: null, error: null })),
731
+ // 条件键:只有 linux 有「删完之后」的命令(daemon-reload),其余平台不出现。
732
+ ...(plan.postRemoveCommands.length > 0
733
+ ? { post_remove_commands: plan.postRemoveCommands.map((c) => ({ command: commandText(c), executed: false, ok: null, error: null })) }
734
+ : {}),
650
735
  notes: [...plan.notes, '这是 dry-run:未删除任何文件、未执行任何命令。加 --yes 实际卸载。'],
651
- });
736
+ }, { field_notes: syncInstallFieldNotes('uninstall-dry') });
652
737
  }
738
+ // 「装没装」的判据:darwin/linux 看条目文件是否存在;win32 没有文件条目可探测
739
+ // (plan.remove 恒为空),任务是否存在只能由 schtasks /Delete 本身回答 —— 不存在时
740
+ // 它报错、落进 commands[].ok=false。所以 win32 一律执行卸载命令,否则已安装的任务
741
+ // 永远删不掉,还会被误报成「未安装」。
653
742
  const anyInstalled = plan.remove.some((r) => r.exists);
743
+ const willRun = anyInstalled || platform === 'win32';
654
744
  const cmdResults = [];
655
- if (anyInstalled) {
656
- // 卸载次序:先停调度器(unload/disable),再删文件
657
- for (const c of plan.commands) {
658
- try {
659
- runScheduleCommand(c);
660
- cmdResults.push({ command: commandText(c), executed: true, ok: true, error: null });
661
- }
662
- catch (e) {
663
- cmdResults.push({ command: commandText(c), executed: true, ok: false, error: e instanceof Error ? e.message : String(e) });
664
- }
745
+ const runOne = (c) => {
746
+ try {
747
+ runScheduleCommand(c);
748
+ cmdResults.push({ command: commandText(c), executed: true, ok: true, error: null });
749
+ }
750
+ catch (e) {
751
+ cmdResults.push({ command: commandText(c), executed: true, ok: false, error: e instanceof Error ? e.message : String(e) });
665
752
  }
753
+ };
754
+ if (willRun) {
755
+ // 卸载次序:先停调度器(unload/disable),再删文件,最后跑「删完之后」的命令。
756
+ for (const c of plan.commands)
757
+ runOne(c);
666
758
  }
667
759
  const removed = [];
668
760
  const absent = [];
@@ -673,34 +765,48 @@ async function syncUninstall(argv) {
673
765
  else
674
766
  absent.push(r.path);
675
767
  }
768
+ if (willRun) {
769
+ // ⚠️ postRemoveCommands(linux 的 daemon-reload)必须在删除之后 —— 见 planUninstall
770
+ // 的注释:提前跑等于重新加载即将被删的 unit,删完后再没人让 systemd 忘掉它。
771
+ for (const c of plan.postRemoveCommands)
772
+ runOne(c);
773
+ }
676
774
  const code = ok({
677
775
  platform, dry_run: false, removed,
678
776
  absent: absent.length > 0 ? absent : undefined,
679
- commands: cmdResults, notes: anyInstalled ? plan.notes : ['未安装(无条目文件):未执行任何命令。'],
680
- });
777
+ commands: cmdResults, notes: willRun ? plan.notes : ['未安装(无条目文件):未执行任何命令。'],
778
+ }, { field_notes: syncInstallFieldNotes('uninstall-real') });
681
779
  return cmdResults.some((c) => !c.ok) ? 1 : code;
682
780
  }
683
781
  export async function syncCommand(argv) {
684
782
  setPretty(false); // G1:每条命令入口重置输出格式 —— 同一进程内多次 run(测试)不残留上一条命令的开关。
685
783
  const [sub, ...rest] = argv;
686
- if (sub === undefined || sub === '--help' || sub === '-h') {
687
- const extra = rest.filter((a) => !KNOWN.has(a));
688
- if (extra.length > 0)
689
- return usageFail(`未知参数:${extra.join(' ')}。--help 不接受额外参数`);
784
+ // ⚠️ 无子命令 = 用法错误(退 2 + JSON)—— 见 store.ts 同款注释(2026-11-07 审查:
785
+ // 四个命令族曾与 `--help` 共用分支,裸文本进 stdout、退 0,与顶层和 api/auth 相反)。
786
+ if (sub === undefined) {
787
+ return usageFail(`用法:qiyu sync <tasks|run|status|verify|install|uninstall> [参数]`
788
+ + '(`qiyu sync --help` 查看全部)');
789
+ }
790
+ if (sub === '--help' || sub === '-h') {
791
+ const problem = helpArgsError(rest, SYNC_SPECS.flatMap((sp) => sp.flags), '。--help 不接受额外参数');
792
+ if (problem !== undefined)
793
+ return usageFail(problem);
690
794
  process.stdout.write(USAGE);
691
795
  return 0;
692
796
  }
693
797
  // G1:--pretty 是输出开关,必须写在具体子命令之后(`sync status --pretty`)。
694
798
  if (sub === '--pretty') {
695
- const unknown = rest.filter((a) => a.startsWith('-') && !KNOWN.has(a));
696
- const positional = rest.filter((a) => !a.startsWith('-'));
697
- if (unknown.length + positional.length > 0) {
698
- return usageFail(`未知参数:${[...unknown, ...positional].join(' ')}。--pretty 不接受额外参数`);
699
- }
799
+ const problem = helpArgsError(rest, SYNC_SPECS.flatMap((sp) => sp.flags));
800
+ if (problem !== undefined)
801
+ return usageFail(`${problem}。--pretty 不接受额外参数`);
802
+ const badPos = prettyPositionalProblem(rest, SYNC_SPECS);
803
+ if (badPos !== undefined)
804
+ return usageFail(badPos);
700
805
  if (rest.includes('--help') || rest.includes('-h')) {
701
806
  process.stdout.write(USAGE);
702
807
  return 0;
703
808
  }
809
+ // ⚠️ 位置参数一律按「顺序写反」引导(2026-11-07 审查)—— 见 db.ts 同款注释。
704
810
  return usageFail(prettyAfterSubcommand('sync'));
705
811
  }
706
812
  if (sub !== 'tasks' && sub !== 'run' && sub !== 'status' && sub !== 'verify'
@@ -718,20 +824,19 @@ export async function syncCommand(argv) {
718
824
  if (sub === 'uninstall')
719
825
  return syncUninstall(rest);
720
826
  // —— tasks ——
721
- if (rest.includes('--help') || rest.includes('-h')) {
722
- const rawRest = rest.filter((a) => !KNOWN.has(a));
723
- if (rawRest.length > 0)
724
- return usageFail(`未知参数:${rawRest.join(' ')}`);
725
- process.stdout.write(USAGE);
726
- return 0;
727
- }
827
+ // ⚠️ 用 `sync tasks` **自己**的 spec(`subHelp`),不是全族并集(Codex PR #69 第四轮):
828
+ // 并集会把兄弟命令的 flag(`--full` / `--db`)当成合法参数,`sync tasks --full --help`
829
+ // 退 0 打印帮助,而正常解析与 `skill check` 都判它非法 —— 运行时与契约校验再次分叉。
830
+ const tasksHelp = subHelp(rest, 'tasks');
831
+ if (tasksHelp !== null)
832
+ return tasksHelp;
728
833
  // G1:--pretty 已实现 —— 原拒绝点开启缩进输出。
729
834
  if (rest.includes('--pretty'))
730
835
  setPretty(true);
731
836
  try {
732
837
  const parsed = parseSubFlags(rest, TASKS_VALUE_FLAGS);
733
838
  if (parsed.rest.length > 0)
734
- return usageFail(`未知参数:${parsed.rest.join(' ')}`);
839
+ return usageFail(`未知参数:${describeArgs(parsed.rest)}`);
735
840
  }
736
841
  catch (e) {
737
842
  return usageFail(e.message);
@@ -752,6 +857,6 @@ export async function syncCommand(argv) {
752
857
  .filter((c) => c.sensitive === true).map((c) => c.name),
753
858
  }));
754
859
  const unsupported = UNSUPPORTED_DATASETS.map((u) => ({ id: u.id, unsupported: u.reason }));
755
- return ok({ tasks, unsupported });
860
+ return ok({ tasks, unsupported }, { field_notes: tasksFieldNotes() });
756
861
  }
757
862
  export { SYNC_RUN_USAGE };