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
@@ -26,9 +26,12 @@ import { readWatermark } from '../sync/state.js';
26
26
  // callPaced 静态导入(范围外发现③):wireCategories 的注入路径也必须过任务层的限频闸门 ——
27
27
  // 该接口(ai.knowledge.getCategoryTree)限频 1 次/秒,裸 call 不落冷却行。
28
28
  import { callPaced } from '../sync/tasks/pace.js';
29
- import { DAY_MS, parseTimeArg, msToShanghaiIso, shanghaiIso } from '../core/time.js';
30
- import { ok, fail, usageFail, describeArgs, setPretty } from '../output.js';
29
+ import { DAY_MS, parseTimeArg, msToShanghaiIso, shanghaiIso, shanghaiDayStart, shanghaiYesterdayStart } from '../core/time.js';
30
+ import { ok, fail, usageFail, failFromTagged, describeArgs, setPretty } from '../output.js';
31
31
  import { thrownToExit } from './store.js';
32
+ import { classifyOpenFailure, openFailureHint } from '../store/retry.js';
33
+ import { storeNotInitializedHint } from './store-precheck.js';
34
+ import { runFieldNotes } from './sync-notes.js';
32
35
  import { GLOBAL_FLAGS, STORE_FLAGS, renderFlagNames, valueFlagNames } from './spec-types.js';
33
36
  /**
34
37
  * `sync run` 的业务 flag。事实源是这份常量:解析器的值位判定与「可用:…」错误文案
@@ -170,7 +173,10 @@ function wireCategories(task, robotIds, clock) {
170
173
  */
171
174
  function robotsFromConfig(configPath, profileFlag) {
172
175
  try {
173
- const r = fileProfile(configPath, profileFlag ?? process.env.QIYU_PROFILE);
176
+ // 空串口径与 resolveStoreConfig 同源(core/config.ts 的 nonEmptyValue 是唯一实现):
177
+ // `--profile`/`QIYU_PROFILE` 的显式空取值不得变成一个名叫空串的档。
178
+ // flag 与 env 各走各的槽位(与 credentials-source 同形),优先级由 resolveProfileName 定。
179
+ const r = fileProfile(configPath, process.env.QIYU_PROFILE, profileFlag);
174
180
  return Object.keys(r.profile?.robots ?? {})
175
181
  .map((k) => Number(k))
176
182
  .filter((n) => Number.isInteger(n) && n > 0);
@@ -179,8 +185,12 @@ function robotsFromConfig(configPath, profileFlag) {
179
185
  return [];
180
186
  }
181
187
  }
182
- /** 任务条目 → 输出形态(spec §七字段名)。 */
183
- function taskOut(r, watermark, lastSyncedAt, notes = []) {
188
+ /** 任务条目 → 输出形态(spec §七字段名)。
189
+ *
190
+ * 导出供测试**推导**真实键集:`runFieldNotes()` 的 `tasks[].x` 路径必须都落在
191
+ * 这里的返回对象上,否则 Agent 会照图例去找一个不存在的字段。键集手抄在测试里
192
+ * 就是假护栏 —— 删掉这里的键,手抄的清单不会跟着红。 */
193
+ export function taskOut(r, watermark, lastSyncedAt, notes = []) {
184
194
  return {
185
195
  task: r.taskId,
186
196
  status: r.status,
@@ -210,16 +220,21 @@ function taskOut(r, watermark, lastSyncedAt, notes = []) {
210
220
  * `sync run → store init → sync run` 死循环,且与 `store status`/`db tables` 对同一失败
211
221
  * 给出的 hint 互相矛盾。现在只在**没有**底层 hint 时补缺省建议。
212
222
  */
213
- function storeInitFail(e) {
223
+ function storeInitFail(e, path) {
214
224
  const err = e;
215
225
  const msg = err.message ?? String(e);
216
- if (err.kind === 'store_not_initialized' || /not a valid DuckDB database/i.test(msg)) {
217
- // 成因优先于缺省建议:底层 hint(依赖缺失 / 他人库 / 权限)原样保留;
218
- // 「路径存在但不是 DuckDB 文件」由 DuckDB 原文判定(store.ts 同款文案)。
219
- const hint = err.hint
220
- ?? (/not a valid DuckDB database/i.test(msg)
221
- ? '该路径已存在且不是 DuckDB 数据库,请换 --db 路径'
222
- : '数据库尚未初始化。请先运行:qiyu store init');
226
+ // ⚠️ 「不是 DuckDB 文件」的判据走 `store/retry.ts` 的 `classifyOpenFailure`(2026-10-31
227
+ // 单一实现点)—— 此前这里自己写了一份 `/not a valid DuckDB database/i` 子串判据,
228
+ // 与 `commands/store.ts`、`query/sandbox.ts` 三处各写各的。判据的形态要求(DuckDB 原生报文、
229
+ // 句尾锚定)见那里的注释。
230
+ const openFailure = classifyOpenFailure(e);
231
+ if (err.kind === 'store_not_initialized' || openFailure !== null) {
232
+ // 成因优先于缺省建议:底层 hint(依赖缺失 / 他人库 / 权限 / 已损坏)原样保留;
233
+ // 无底层 hint 的打开失败按 `classifyOpenFailure` 的成因取**同一份**文案
234
+ //(与 store.ts、sandbox.ts 共用 `openFailureHint`,不再各写各的)。
235
+ const hint = err.hint ?? (openFailure !== null
236
+ ? openFailureHint(openFailure)
237
+ : storeNotInitializedHint(path));
223
238
  return fail({
224
239
  code: 'store_not_initialized', kind: 'store_not_initialized',
225
240
  retryable: false,
@@ -265,6 +280,10 @@ export async function runSyncRun(argv) {
265
280
  if (v === undefined || v.startsWith('--')) {
266
281
  return usageFail(`${a} 缺少取值`);
267
282
  }
283
+ // 重复出现必须报错(Codex 2026-11-10 P2):本命令自己解析这三个 flag(不走
284
+ // parseStoreFlags),此前直接赋值 —— `sync run --db a --db b` 静默作用在后一个库。
285
+ if (flags[a] !== undefined)
286
+ return usageFail(`${a} 重复出现:只能给一次(不做静默覆盖)`);
268
287
  flags[a] = v;
269
288
  i++;
270
289
  }
@@ -279,33 +298,66 @@ export async function runSyncRun(argv) {
279
298
  taskIds.push(a);
280
299
  }
281
300
  }
282
- if (flags['--full'] && (flags['--since'] || flags['--until'])) {
301
+ // ⚠️ 值位 flag 的**空白取值**是用法错误,不是「没给」(2026-10-29 实测修)。
302
+ // `flags['--since']` 此前按**真值**判(`||` / `? :`),而 `''` 是假值 —— 于是
303
+ // `sync run --since ''` 与 `sync run --until ''` 被静默当成「没给区间」:
304
+ // · `--full --since ''` 直接**绕过互斥守卫**(判据 `flags['--full'] && flags['--since']`),
305
+ // 用户以为「--full 与区间同传会报错」,实际拿到一次全量重刷、退出码 0;
306
+ // · 单独 `--since ''` 落到水位续跑分支,形态与不带该 flag 逐字相同。
307
+ // 同一个输入 `query --table X --since ''` 是 usage(resolveTimeFlag 走 `!== undefined`),
308
+ // 两个命令对同一份参数给出相反结论 —— 与 README 的空串口径(env 空串=未设置、
309
+ // **显式** flag 空串=用法错误)一致的是 query 那一侧,故本命令对齐它。
310
+ // 空白串(`' '`)同样拒绝:它不是「未设置」,也不是合法时间。
311
+ // 渲染走 describeArgs(`''` / `' '`),否则消息会是「无法解析:。」冒号后空白。
312
+ for (const f of ['--since', '--until']) {
313
+ const v = flags[f];
314
+ if (v !== undefined && v.trim() === '') {
315
+ return usageFail(`${f} 的取值不能是空串或纯空白(收到 ${describeArgs([v])})。`
316
+ + '要「不给区间」就别传这个 flag —— 空白取值不是合法时间,也不会被当成未设置');
317
+ }
318
+ }
319
+ // ⚠️ 互斥/分支判据一律用 `!== undefined`(「给了没给」)而非真值(「值是否非空」)。
320
+ // **边界(实测):有了上面的空白守卫,这两个判据在本函数里已经等价** —— 空白取值
321
+ // 在到达它们之前就被拦成 usage,`flags['--full']` 又恒是 flag 名字符串(真值即存在)。
322
+ // 保留存在性写法是**防御性**的:日后有人挪走或收窄上面的守卫,真值判据会立刻重新
323
+ // 分叉出「静默当成没给」分支(本轮缺陷正是这么来的)。变异验证如实记录:
324
+ // 把这两处改回真值,全部用例**仍然绿**(等价变异,不是覆盖缺口)。
325
+ if (flags['--full'] !== undefined && (flags['--since'] !== undefined || flags['--until'] !== undefined)) {
283
326
  return usageFail('--full 与 --since/--until 互斥:全量重刷不叠加区间参数');
284
327
  }
285
328
  // —— 任务 id 校验(usage:未知 id 是参数错误)——
286
329
  const unknown = taskIds.filter((id) => taskById(id) === undefined);
287
330
  if (unknown.length > 0) {
288
- return usageFail(`未知任务:${unknown.join('、')}\n可用任务:${SYNC_TASKS.map((t) => t.id).join('、')}`);
331
+ // ⚠️ describeArgs 渲染取值(空串 → `''`):`sync run ''` 此前报「未知任务:」冒号后空白,
332
+ // Agent 读不出自己传了什么(与 query 的 `未知表:''` 同族,2026-10-29 一并修)。
333
+ return usageFail(`未知任务:${describeArgs(unknown)}\n可用任务:${SYNC_TASKS.map((t) => t.id).join('、')}`);
289
334
  }
290
- // —— 凭证前置(api.ts 同族:缺凭证是环境问题 → auth_missing 退出码 1)——
291
- const credOutcome = resolveCredentialsUsingFile(currentCredentialEnv());
292
- if (!credOutcome.ok)
293
- return fail(credOutcome.error);
294
- const creds = credOutcome.creds;
295
- // —— store 打开(rw 单写者)——
296
- // ⚠️ close 覆盖 openStore 之后的**所有**路径(B 低-1,沿 store.ts 的 C1 形态):
297
- // 迁移失败 / 他人库 / 后续任何异常,连接与 DuckDB instance 都必须在 finally 释放 ——
298
- // 此前 close 只挂在第二个 try 的 finally 上,第一个 try(open+init)失败即泄漏。
335
+ // —— store 配置解析(**先于**凭证)——
336
+ // ⚠️ 次序即归因(Codex PR #69):`--profile typo` 是**参数错误**(usage,退出码 2),
337
+ // 而缺凭证是环境错误(auth_missing,退出码 1)。凭证侧按 `--profile` 选档后报
338
+ // 「缺少 appKey」会把拼错的档名说成「没配凭证」—— 参数错误必须排在环境错误之前。
299
339
  let resolved;
300
340
  try {
301
341
  resolved = resolveStoreConfig({
302
342
  flags: { db: flags['--db'], profile: flags['--profile'], backend: flags['--backend'] },
303
343
  env: currentStoreEnv(),
304
344
  });
345
+ // ⚠️ failFromTagged(不是 usageFail):配置层会抛带 `kind: config_insecure` 的错误
346
+ // (含凭证且权限过宽 —— 退出码 1、只能由人 chmod)。包成 usageFail 会把它降级成
347
+ // 「改参数重来」退出码 2 并丢掉 hint,与 auth/api 那条路径的说法相反。
305
348
  }
306
349
  catch (e) {
307
- return usageFail(e.message);
350
+ return failFromTagged(e);
308
351
  }
352
+ // —— 凭证前置(api.ts 同族:缺凭证是环境问题 → auth_missing 退出码 1)——
353
+ const credOutcome = resolveCredentialsUsingFile(currentCredentialEnv(), { profile: flags['--profile'] });
354
+ if (!credOutcome.ok)
355
+ return fail(credOutcome.error);
356
+ const creds = credOutcome.creds;
357
+ // —— store 打开(rw 单写者)——
358
+ // ⚠️ close 覆盖 openStore 之后的**所有**路径(B 低-1,沿 store.ts 的 C1 形态):
359
+ // 迁移失败 / 他人库 / 后续任何异常,连接与 DuckDB instance 都必须在 finally 释放 ——
360
+ // 此前 close 只挂在第二个 try 的 finally 上,第一个 try(open+init)失败即泄漏。
309
361
  let store;
310
362
  try {
311
363
  try {
@@ -313,36 +365,45 @@ export async function runSyncRun(argv) {
313
365
  await store.init();
314
366
  }
315
367
  catch (e) {
316
- return storeInitFail(e);
368
+ return storeInitFail(e, resolved.config.path);
317
369
  }
318
370
  // —— 区间合成(时钟注入点:parseTimeArg 接受 clock;Nd/yesterday 已带区间,
319
- // YYYY-MM-DD/ISO 只给起点 → end=clock 当前或配对的另一端)——
371
+ // YYYY-MM-DD/ISO 只给起点 → end 取本次区间合成的 now 或配对的另一端)——
372
+ // ⚠️ 判据用 `!== undefined`(「给了」)而非真值:上面已把空白取值拦成 usage,
373
+ // 两边用同一种判据才不会在日后又分叉出一个静默分支。
374
+ //
375
+ // ⚠️ **整段只读一次时钟**(2026-11-11 CI 实测修):`--since 1d` 由 parseTimeArg 内部
376
+ // 的 clock() 算出 `end`,此前这个 end 被丢掉、`--until` 缺省时又调一次 clock()——
377
+ // 两次 Date.now() 之间只要过去 ≥1ms,区间就从「1 天」变成「1 天 + ε」,
378
+ // `sliceByMaxWindow(…, 6, 1)` 于是切出第二窗(起点 = end−1d,几乎与首窗重合),
379
+ // 被 contained 合并;覆盖窗失败时按 skipped 结算 → `windows.total` 从 1 变 2。
380
+ // 区间两端必须来自**同一时刻**,否则「最近 N 天」的窗数取决于解析耗时。
381
+ const now = clock();
382
+ const clockAt = () => now;
320
383
  let rangeOverride;
321
- if (flags['--full']) {
322
- rangeOverride = { start: 0, end: clock() };
384
+ const sinceRaw = flags['--since'];
385
+ const untilRaw = flags['--until'];
386
+ if (flags['--full'] !== undefined) {
387
+ rangeOverride = { start: 0, end: now };
323
388
  }
324
- else if (flags['--since'] || flags['--until']) {
325
- const untilMs = flags['--until']
326
- ? parseTimeArg(flags['--until'], clock, '--until')
327
- : null;
328
- if (flags['--until'] && untilMs === null) {
329
- return usageFail(`--until 无法解析:${flags['--until']}。支持 Nd / yesterday / YYYY-MM-DD / ISO 8601`);
389
+ else if (sinceRaw !== undefined || untilRaw !== undefined) {
390
+ const untilMs = untilRaw !== undefined ? parseTimeArg(untilRaw, clockAt, '--until') : null;
391
+ if (untilRaw !== undefined && untilMs === null) {
392
+ return usageFail(`--until 无法解析:${describeArgs([untilRaw])}。支持 Nd / yesterday / YYYY-MM-DD / ISO 8601`);
330
393
  }
331
- const sinceMs = flags['--since']
332
- ? parseTimeArg(flags['--since'], clock, '--since')
333
- : null;
334
- if (flags['--since'] && sinceMs === null) {
335
- return usageFail(`--since 无法解析:${flags['--since']}。支持 Nd / yesterday / YYYY-MM-DD / ISO 8601`);
394
+ const sinceMs = sinceRaw !== undefined ? parseTimeArg(sinceRaw, clockAt, '--since') : null;
395
+ if (sinceRaw !== undefined && sinceMs === null) {
396
+ return usageFail(`--since 无法解析:${describeArgs([sinceRaw])}。支持 Nd / yesterday / YYYY-MM-DD / ISO 8601`);
336
397
  }
337
398
  // 归一:Nd/yesterday 返回完整区间(起点优先);日期/ISO 返回时刻。
338
399
  // 单 --until(分段回补):start=0、end=until 时刻;单 --since:start=since 时刻、
339
400
  // end=now;成对:[since 时刻, until 时刻];--since 带 Nd 区间时用其 start。
340
401
  const start = sinceMs === null ? 0
341
402
  : typeof sinceMs === 'object' ? sinceMs.start : sinceMs;
342
- const end = untilMs === null ? clock()
403
+ const end = untilMs === null ? now
343
404
  : typeof untilMs === 'object' ? untilMs.end : untilMs;
344
405
  if (start >= end) {
345
- return usageFail(`区间无效:start >= end(${new Date(start).toISOString()} >= ${new Date(end).toISOString()})`);
406
+ return usageFail(`区间无效:解析后的起点不早于终点(start=${shanghaiIso(start)} >= end=${shanghaiIso(end)})`, EMPTY_RANGE_HINT);
346
407
  }
347
408
  rangeOverride = { start, end };
348
409
  }
@@ -357,12 +418,12 @@ export async function runSyncRun(argv) {
357
418
  // 此前 `map(Number).filter(...)` 会把 `["abc", -1]` 静默丢成空数组:用户 typo
358
419
  // 了 robotId 却毫无反馈(注入面静默失效)。非数组的错误分支保留。
359
420
  if (rawIds !== undefined && !Array.isArray(rawIds)) {
360
- return usageFail('配置文件 store.options.knowledgeRobotIds 必须是数字数组');
421
+ return usageFail('配置文件 profiles.<name>.store.options.knowledgeRobotIds 必须是数字数组');
361
422
  }
362
423
  if (Array.isArray(rawIds)) {
363
424
  const bad = rawIds.find((x) => !Number.isInteger(x) || x <= 0);
364
425
  if (bad !== undefined) {
365
- return usageFail(`配置文件 store.options.knowledgeRobotIds 必须是正整数数组(非法元素:${String(bad)})`);
426
+ return usageFail(`配置文件 profiles.<name>.store.options.knowledgeRobotIds 必须是正整数数组(非法元素:${String(bad)})`);
366
427
  }
367
428
  }
368
429
  const robotIds = rawIds !== undefined
@@ -378,6 +439,8 @@ export async function runSyncRun(argv) {
378
439
  credentials: creds,
379
440
  gate: new RateGate(store, clock),
380
441
  clock,
442
+ // gap detail 的恢复动作要复现本次库选择(裸命令会去操作默认库)
443
+ storeLocation: { db: resolved.config.path, ...(resolved.profileFlag !== undefined ? { profileFlag: resolved.profileFlag } : {}) },
381
444
  };
382
445
  const onProgress = flags['--quiet'] === undefined
383
446
  ? (line) => { process.stderr.write(line + '\n'); }
@@ -401,6 +464,10 @@ export async function runSyncRun(argv) {
401
464
  for (const t of selected) {
402
465
  if (t.windowStartFloorDays === undefined)
403
466
  continue;
467
+ // ⚠️ 这里**当场读钟**,不用区间合成的 `now`(Codex 2026-11-12 P2):本 note 是在
468
+ // 预测**引擎**的 `windowStartFloorDays` 钳制,而引擎按任务**执行时刻**的
469
+ // `nowOf(ctx)` 计算。整轮同步若跨过上海午夜,越早的钟越容易把「明天就能拉到」
470
+ // 说成「永远拉不到」。读得越晚越接近引擎的判据。
404
471
  const floor = clock() - t.windowStartFloorDays * DAY_MS;
405
472
  if (rangeOverride.end <= floor) {
406
473
  floorNotes.set(t.id, [
@@ -412,6 +479,54 @@ export async function runSyncRun(argv) {
412
479
  }
413
480
  }
414
481
  }
482
+ // 非日界 `--until` + 日对齐任务(2026-11-10 审计):末窗 end 不在上海日界 → 末残段
483
+ // 被跳过(半日聚合不落日行),用户说「同步到 10/15 中午」却一行 10/15 都没有,
484
+ // 而输出是 complete、gaps 为空 —— 必须用 notes 把这一条说在明处,并给出真能用的写法。
485
+ const untilNotes = new Map();
486
+ if (rangeOverride !== undefined && untilRaw !== undefined) {
487
+ // 与区间合成同一时刻(clockAt):再读一次 clock 可能跨过上海日界,
488
+ // 提示会描述一个与实际区间不同的日子。
489
+ const untilEnd = parseTimeArg(untilRaw, clockAt, '--until');
490
+ // 只对「日期 / ISO 时刻」这两种定点写法提示:Nd / yesterday 解析成区间(end=now),
491
+ // 那是「最近 N 天」的常规用法,今天不满一天属既有语义(每日残段由次日 run 补全),
492
+ // 每次都提示只会变成噪音。
493
+ const boundary = untilEnd === null || typeof untilEnd === 'object' ? null : untilEnd;
494
+ if (boundary !== null && boundary !== shanghaiDayStart(boundary)) {
495
+ for (const t of selected) {
496
+ if (t.windowAlign !== 'shanghaiDay')
497
+ continue;
498
+ // ⚠️ 声明了末端上限的任务(考勤/绩效 `windowEndClamp: 'shanghaiYesterday'`):
499
+ // 目标日已过日界但**晚于上限**时,把 --until 写到次日也拉不到 —— 增量拉取永远
500
+ // 停在「昨天 0 点」,剩下的只能等上限自然前移(Codex 2026-11-10 第二轮 P2:
501
+ // 旧文案一律劝「写到次日 0 点」,照做后提示消失、该日仍未同步)。
502
+ const dayStart = shanghaiDayStart(boundary);
503
+ if (t.windowEndClamp === 'shanghaiYesterday') {
504
+ // ⚠️ 当场读钟(Codex 2026-11-12 P2):本 note 预测的是引擎 `windowEndLimit`
505
+ // = `shanghaiYesterdayStart(nowOf(ctx))`,而 `nowOf(ctx)` 是任务**执行时刻**。
506
+ // 整轮同步跨过上海午夜时,早先采样的 now 会让上限停在昨天,提示于是误报
507
+ // 「调整 --until 也无法拉到」——而午夜后引擎上限已前移一天,把 --until 写到
508
+ // 次日 0 点其实能同步该整日。读得越晚越接近引擎的判据。
509
+ const limit = shanghaiYesterdayStart(clock());
510
+ if (dayStart >= limit) {
511
+ untilNotes.set(t.id, [
512
+ `--until 终点 ${shanghaiIso(boundary)} 不是上海日界(00:00),且 ` +
513
+ `${shanghaiIso(dayStart)} 这一天不早于本任务的末端上限 ${shanghaiIso(limit)}`
514
+ + '(该接口 endTime 不能晚于昨天 0 点,越界会被拒):调整 --until 也无法拉到这段 ——'
515
+ + '本任务最多同步到上限之前,之后的日期要等上限自然前移(次日)再跑增量。',
516
+ ]);
517
+ continue;
518
+ }
519
+ }
520
+ untilNotes.set(t.id, [
521
+ `--until 解析到的终点 ${shanghaiIso(boundary)} 不是上海日界(00:00):本任务按上海`
522
+ + '自然日对齐切窗(每窗一个整日聚合),末窗是半个自然日、按残段窗跳过(不拉、不写)——'
523
+ + `从 ${shanghaiIso(dayStart)} 起的这一天不会进库,`
524
+ + '结果里的 complete 与 gaps 为空不代表这一段已同步。要含该日请把 --until 写到次日 0 点'
525
+ + '(如 --until 2026-10-16 含 10/15 整天)。',
526
+ ]);
527
+ }
528
+ }
529
+ }
415
530
  const ranks = [...new Set(selected.map((t) => taskRank(t)))].sort((a, b) => a - b);
416
531
  for (const rank of ranks) {
417
532
  const layer = selected.filter((t) => taskRank(t) === rank);
@@ -431,13 +546,13 @@ export async function runSyncRun(argv) {
431
546
  const tasksOut = [];
432
547
  for (const r of results) {
433
548
  const st = await readWatermark(store, r.taskId);
434
- tasksOut.push(taskOut(r, st.watermark, st.lastSyncedAt, floorNotes.get(r.taskId) ?? []));
549
+ tasksOut.push(taskOut(r, st.watermark, st.lastSyncedAt, [...(floorNotes.get(r.taskId) ?? []), ...(untilNotes.get(r.taskId) ?? [])]));
435
550
  }
436
551
  // 全失败判定(T13 fix 中-1):引擎对 windowed 全窗失败权威产出 partial('failed'
437
552
  // 只留给快照 gate 拦截路径)——「全失败」必须补判窗口级:succeeded=0 且 failed>0
438
553
  // 的任务与 status='failed' 并列计入退出码 1。
439
554
  const allFailed = results.every((r) => r.status === 'failed' || (r.windows.succeeded === 0 && r.windows.failed > 0));
440
- const code = ok({ tasks: tasksOut, truncated: false });
555
+ const code = ok({ tasks: tasksOut, truncated: false }, { field_notes: runFieldNotes() });
441
556
  // stderr 汇总(spec §二:核对不符等在 run 结束的 stderr 汇总中列出;下界裁剪的
442
557
  // notes 同样进 stderr——--quiet 时只看 stdout 的 tasks[].notes)。
443
558
  if (flags['--quiet'] === undefined) {
@@ -446,6 +561,9 @@ export async function runSyncRun(argv) {
446
561
  process.stderr.write(`[${r.taskId}] ${r.gaps.length} 个缺口:` +
447
562
  r.gaps.map((g) => g.reason).join('、') + '\n');
448
563
  }
564
+ for (const n of untilNotes.get(r.taskId) ?? []) {
565
+ process.stderr.write(`[${r.taskId}] 提示:${n}\n`);
566
+ }
449
567
  for (const n of floorNotes.get(r.taskId) ?? []) {
450
568
  process.stderr.write(`[${r.taskId}] 提示:${n}\n`);
451
569
  }
@@ -463,13 +581,28 @@ export async function runSyncRun(argv) {
463
581
  await store.close();
464
582
  }
465
583
  }
584
+ /**
585
+ * 区间两端的解析(`--since` / `--until` 共用)与「区间为空」的统一判定。
586
+ *
587
+ * `--until YYYY-MM-DD` 解析成**该日 0 点**,区间按半开 `[start, end)` 取 —— 所以
588
+ * 「同一天的 --since 与 --until」区间为零宽、什么都不会拉(2026-11-10 审计:此前的
589
+ * 报错只说「start >= end」并回显两个相同的 ISO 时刻,用户看不出这是日期语义导致的)。
590
+ * `--since 2026-09-01 --until 2026-09-20` 覆盖 9/1…9/19 —— 要含 9/20 当天,`--until` 写 9/21。
591
+ */
592
+ const EMPTY_RANGE_HINT = '按半开区间 [--since, --until) 计:--since 与 --until 解析到同一时刻时什么都不拉;'
593
+ + '`--until YYYY-MM-DD` 是该日 0 点(不包含当天)—— 要含那一天请把 --until 写到次日';
466
594
  export const SYNC_RUN_USAGE = `用法:qiyu sync run [任务...] [参数]
467
595
 
468
596
  qiyu sync run 增量同步全部任务(缺省 = 注册表全部)
469
597
  qiyu sync run <任务...> 只跑指定任务
470
598
  --full 全区间重刷(与 --since/--until 互斥)
471
599
  --since T --until T 指定区间;T 支持 Nd / yesterday / YYYY-MM-DD / ISO 8601
472
- (相对时间与日期按 Asia/Shanghai 解析)
600
+ (相对时间与日期按 Asia/Shanghai 解析;区间按半开
601
+ [--since, --until) 计,--until YYYY-MM-DD 不含当天;
602
+ 日对齐任务(报表)的 --until 请写日界,否则末残段跳过;
603
+ 只给 --until 不给 --since 时起点是「最早」——报表这类没声明
604
+ 接口下界的任务会从 1970 按天切出上万窗(等同 --full 的量级),
605
+ 只补某一段请成对给 --since)
473
606
  --quiet 关闭 stderr 进度
474
607
  --db / --profile / --backend 存储定位(store 命令同族)
475
608