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
@@ -37,8 +37,11 @@ function assertOpWindow(w) {
37
37
  throw usageError(`工单 op 窗口无效:opEnd 缺省/为 0 时服务端会静默返回全量,` +
38
38
  `opStart<=0(1970 哨兵)会被静默钳制(窗口 start=${w.start}, end=${w.end})`);
39
39
  }
40
- if (w.start > w.end) {
41
- throw usageError(`工单 op 窗口顺序颠倒(opStart > opEnd 会静默失效):start=${w.start} > end=${w.end}`);
40
+ // ⚠️ 零宽窗(start === end)同样拒绝(2026-11-09 审计):它的 opStart 不早于 opEnd,
41
+ // 若被发出去,服务端对它是否等于「未传 opEnd」没有契约保证 —— 姊妹管线
42
+ // (pipeline.ts 的会话导出)对同一形态已经是 `w.end <= w.start` 拒绝,两处判据必须同向。
43
+ if (w.start >= w.end) {
44
+ throw usageError(`工单 op 窗口无效(opStart 必须早于 opEnd):start=${w.start} >= end=${w.end}`);
42
45
  }
43
46
  }
44
47
  /** usage 错误(退出码 2):本地参数问题,重试无用。 */
@@ -136,12 +139,39 @@ async function fetchTickets(w, ctx) {
136
139
  assertOpWindow(w);
137
140
  const nowIso = nowIsoOf(ctx);
138
141
  const out = [];
142
+ let dropped = 0;
139
143
  for (const r of await searchAllPages(w, ctx)) {
140
144
  const row = ticketRow(r, nowIso);
141
145
  if (row)
142
146
  out.push(row);
147
+ else
148
+ dropped++;
143
149
  }
144
- return { rows: out, apiCount: out.length };
150
+ return { rows: out, apiCount: out.length, ...droppedTicketHint('tickets.search', dropped, 'id') };
151
+ }
152
+ /**
153
+ * 行被丢弃(缺主键列)时的 task gapHint(`row_missing_key`)。
154
+ *
155
+ * ⚠️ 与 reports.ts 的 `droppedHint` 同形(审查 #5,2026-11-03):`apiCount` 取的是过滤后
156
+ * 的行数,配对核对恒等 → 缺键行静默消失、窗口仍 complete。这些行真的没落库,必须留痕。
157
+ * (两处各写一份是有意的:tickets 与 reports 是两个任务文件,分层上不互相 import;
158
+ * `tests/sync-enums.test.ts` 保证 reason 值同属一个枚举、README 图例只释义一次。)
159
+ */
160
+ function droppedTicketHint(taskId, dropped, keyName, skippedTickets = 0) {
161
+ if (dropped === 0 && skippedTickets === 0)
162
+ return {};
163
+ const parts = [];
164
+ if (dropped > 0)
165
+ parts.push(`${dropped} 行缺 ${keyName}(主键列,缺键或空串)被丢弃、未落库`);
166
+ if (skippedTickets > 0)
167
+ parts.push(`${skippedTickets} 张 touched 工单缺 ${keyName},其日志整单未拉取(规模未知)`);
168
+ return {
169
+ gapHint: {
170
+ reason: 'row_missing_key',
171
+ detail: `${taskId}: ${parts.join(';')}`
172
+ + ' —— 上游响应形态漂移,请核对接口返回;本次按已落库的行覆盖窗口',
173
+ },
174
+ };
145
175
  }
146
176
  /**
147
177
  * ticket.logs 任务 fetch:先用同窗口的 search 找出 touched 工单(窗口内有操作 = op 语义),
@@ -153,12 +183,20 @@ async function fetchTicketLogs(w, ctx) {
153
183
  const nowIso = nowIsoOf(ctx);
154
184
  // —— touched 工单:与 tickets.search 同窗同分页(同一份实现,短读/翻页上限语义一致)——
155
185
  const touched = [];
186
+ let skippedTickets = 0;
156
187
  for (const r of await searchAllPages(w, ctx)) {
157
- if (!isEmptyKey(r.id))
158
- touched.push(String(r.id));
188
+ // 缺 id 的 touched 工单:**它的日志整单拉不到**(CodeRabbit #61)。这不是「丢了日志
189
+ // 行」(行都没请求过),必须与 droppedLogs 分开计数并留痕——否则本轮 complete 而
190
+ // 这张工单的日志一行都没有。
191
+ if (isEmptyKey(r.id)) {
192
+ skippedTickets++;
193
+ continue;
194
+ }
195
+ touched.push(String(r.id));
159
196
  }
160
197
  // —— 逐单拉日志 ——
161
198
  const out = [];
199
+ let droppedLogs = 0;
162
200
  for (const tid of touched) {
163
201
  const res = await callPaced('ticket.log', { ticketId: Number(tid) }, ctx);
164
202
  // ticket.log 信封未实测(registry envelope=null)→ 宽松模式载荷;data 数组形态按实测 §10.3。
@@ -179,12 +217,20 @@ async function fetchTicketLogs(w, ctx) {
179
217
  }
180
218
  for (const r of rows) {
181
219
  const logId = r.id;
182
- if (isEmptyKey(logId))
183
- continue; // 键缺失/空串行:丢弃且不计入 fetched(C 低-7)
220
+ // 键缺失/空串行:丢弃、计数并留痕(审查 #5)——否则这一单的日志无声消失(C 低-7)。
221
+ if (isEmptyKey(logId)) {
222
+ droppedLogs++;
223
+ continue;
224
+ }
184
225
  out.push({ ticket_id: tid, log_id: String(logId), payload: JSON.stringify(r), synchronized_at: nowIso });
185
226
  }
186
227
  }
187
- return { rows: out, apiCount: out.length };
228
+ return {
229
+ rows: out, apiCount: out.length,
230
+ // 两种丢失合成一条缺口(引擎每窗只有一个 gapHint):缺 id 的日志行 + 因缺 id 而
231
+ // 整单没拉日志的 touched 工单。detail 分开点名,规模不可混为一谈。
232
+ ...droppedTicketHint('ticket.logs', droppedLogs, 'id', skippedTickets),
233
+ };
188
234
  }
189
235
  export const TICKET_TASKS = [
190
236
  {
@@ -208,6 +254,11 @@ export const TICKET_TASKS = [
208
254
  // 同路径任务共享冷却(B 中-6):touched 集合与逐单日志都经 ticket.search / ticket.log,
209
255
  // 闸门键取主要驱动路径 ticket.search(与 tickets.search 任务同键,交替调用照样被拦)。
210
256
  endpoint: 'ticket.search',
257
+ // ⚠️ 闸门必须覆盖 fetch 实际调用的**每个** endpoint(2026-11-02 实测修):逐单日志
258
+ // 的 `ticket.log` 被限流时 penalize 写的是 `__ratelimit__:ticket.log`,只声明
259
+ // `ticket.search` 会让引擎读不到那把冷却、下一窗照旧超发(实测:冷却行在库而
260
+ // acquire('ticket.search') 放行,随后又发 4 次 ticket.log)。
261
+ gateEndpoints: ['ticket.search', 'ticket.log'],
211
262
  windowStartFloorDays: 31,
212
263
  write: { kind: 'upsertRows' },
213
264
  fetch: fetchTicketLogs,
@@ -1 +1,60 @@
1
- export {};
1
+ /**
2
+ * `sync run` 每任务的 `status` 取值(闭集)。
3
+ *
4
+ * ⚠️ 运行时数组而不是裸联合类型:这是**输出数据里的机器值**,Agent 要按它分支
5
+ * (重跑 / 报告人类 / 放弃)。值域必须能在运行时导出,图例与测试才能双向核对。
6
+ *
7
+ * ⚠️⚠️ **`partial` 的字面语义是「部分成功」,但它同样覆盖「一行都没落」**:
8
+ * windowed 任务的引擎对「全部窗口都失败」也产出 `partial`(`succeeded: 0,
9
+ * failed: N`)——`failed` 只留给连窗口循环都进不去的异常路径(快照任务的限频闸门拦截)。
10
+ * 2026-10-27 实测:`tickets.search --since 1d` 全窗失败 → `status: "partial"`、
11
+ * `windows: {succeeded: 0, failed: 1}`、退出码 1。所以判「这次到底有没有拿到数据」
12
+ * 要看 `windows.succeeded` 或退出码,**不要**看 `status` 的字面。
13
+ */
14
+ export const RUN_STATUSES = ['complete', 'partial', 'failed'];
15
+ /**
16
+ * 任务层 `gapHint.reason` 的**全部取值**(业务提示类缺口)。
17
+ *
18
+ * ⚠️ 与引擎侧四个失败原因(`ENGINE_GAP_REASONS`,见 engine.ts)共同构成
19
+ * `sync_gaps.reason` / `sync status` 的 `gaps[].reason` / `sync run` 的 `gaps[].reason`
20
+ * 的完整值域 —— 消费方(Agent)按值分支,所以这里的每个值都必须在 README 图例里有
21
+ * 释义与动作(`tests/sync-enums.test.ts` 钉住两个方向:枚举 ⊆ 图例、图例 ⊆ 枚举)。
22
+ *
23
+ * 与失败类缺口的区别:这些是**成功窗上的提示** —— 窗口数据照常提交,`gaps` 非空
24
+ * 不等于同步失败。此前类型是 `string`、引擎用 `as WindowGapReason` 强转,把
25
+ * 「类型只声明四个」的谎报压了下去(2026-10-27 修)。
26
+ *
27
+ * ⚠️⚠️ 「提示」**不等于**「数据没缺」——这一族里有两档,消费方的动作不同,
28
+ * 合并成一句「数据未必缺」是误导(2026-11-02 审查):
29
+ * · **确实没落库**(`TASK_GAP_LOSSY_REASONS`):描述的行/成员**真的没进库**,
30
+ * `detail` 是丢失规模,必须核对上游形态;
31
+ * · **未必缺数据**(其余):可能只是筛选没命中、或空窗本来就空,按 `detail` 判断。
32
+ * 两档在 README 图例段有各自的一句话,`tests/sync-enums.test.ts` 双向核对
33
+ * (常量改了而 README 没改 → 红)。
34
+ */
35
+ export const TASK_GAP_REASONS = [
36
+ 'knowledge_row_malformed', // 快照映射时缺键列的行被丢弃(响应形态漂移)
37
+ 'staff_id_list_malformed', // staffIdList 非数组(整组)或成员 id 为空(该成员)→ 这些成员未落库
38
+ 'row_missing_key', // 窗口任务(报表/工单)映射时行缺主键列(缺键/空串)→ 该行被丢弃、未落库
39
+ 'filter_matched_no_staff', // 报表筛选条件未命中任何客服(本窗按 0 行记)
40
+ 'export_fixture_unreported', // 导出流未上报窗口声明行(空窗可能真空也可能被截断)
41
+ 'export_window_mismatch', // 导出声明的窗口宽于请求(重叠行幂等吸收)
42
+ ];
43
+ /**
44
+ * `TASK_GAP_REASONS` 里「**描述的行确实没落库**」的那一档(其余是「未必缺数据」的提示)。
45
+ *
46
+ * 判据是任务层对行的处理:`knowledge_row_malformed` 丢弃缺键列的行、
47
+ * `staff_id_list_malformed` 丢弃整组(非数组时)或空 id 成员、
48
+ * `row_missing_key` 丢弃窗口任务里缺主键列的行 —— 这些行不会以任何形式进库;
49
+ * 而 `filter_matched_no_staff`(上游本就没命中)、
50
+ * `export_window_mismatch`(重叠行被幂等 upsert 吸收,数据在库里)都不属于这一档,
51
+ * `export_fixture_unreported` 是「该不该有行」尚不可知,同样不在这一档。
52
+ *
53
+ * `tests/sync-enums.test.ts` 钉住它与 `TASK_GAP_REASONS` 的关系是**真划分**
54
+ * (非空、真子集),并核对 README 两档文案与它一致 —— 单一出处,不得在别处重抄一份。
55
+ */
56
+ export const TASK_GAP_LOSSY_REASONS = [
57
+ 'knowledge_row_malformed',
58
+ 'staff_id_list_malformed',
59
+ 'row_missing_key',
60
+ ];
@@ -32,25 +32,3 @@ export function sliceByMaxWindow(range, maxWindowDays, overlapDays) {
32
32
  }
33
33
  return windows;
34
34
  }
35
- /**
36
- * 合并相邻(start == 前者 end)与重叠的区间,保留缝隙。
37
- * 输入不要求有序,结果按 start 升序。
38
- */
39
- export function mergeRanges(rs) {
40
- if (rs.length === 0)
41
- return [];
42
- const sorted = [...rs].sort((a, b) => a.start - b.start);
43
- const merged = [{ ...sorted[0] }];
44
- for (let i = 1; i < sorted.length; i++) {
45
- const last = merged[merged.length - 1];
46
- const cur = sorted[i];
47
- if (cur.start <= last.end) {
48
- // 相邻或重叠:延伸右端(含完全包含的情形)
49
- last.end = Math.max(last.end, cur.end);
50
- }
51
- else {
52
- merged.push({ ...cur });
53
- }
54
- }
55
- return merged;
56
- }
@@ -0,0 +1,79 @@
1
+ import { TABLES } from '../store/schema.js';
2
+ /** 返回该任务写策略声明违反的契约(空数组 = 通过)。 */
3
+ export function writeContractViolations(task) {
4
+ const write = task.write;
5
+ if (write.kind !== 'deleteRangeInsert')
6
+ return [];
7
+ const out = [];
8
+ if ('instantColumn' in write) {
9
+ const table = TABLES.find((t) => t.name === task.table);
10
+ if (table === undefined) {
11
+ out.push(`${task.id}:instantColumn 指向的表 '${task.table}' 不在 TABLES 里`);
12
+ return out;
13
+ }
14
+ if (!table.columns.some((c) => c.name === write.instantColumn)) {
15
+ out.push(`${task.id}:instantColumn '${write.instantColumn}' 不是表 '${task.table}' 的列`);
16
+ }
17
+ else if (table.timeColumn?.name !== write.instantColumn
18
+ || table.timeColumn.kind !== 'iso-instant') {
19
+ out.push(`${task.id}:instantColumn '${write.instantColumn}' 必须是表 '${task.table}' 声明的`
20
+ + ` timeColumn 且 kind='iso-instant'(删除值与 new Date(ms).toISOString() 同形的前提)`);
21
+ }
22
+ }
23
+ else {
24
+ // 两条独立判据(CodeRabbit #59 三轮):漏声明 rangeAlign 不会落进「对齐」分支,
25
+ // 引擎于是拿 `toISOString()` 的瞬时串(…T00:00:00.000Z)去比日粒度列值(YYYY-MM-DD)——
26
+ // 字符串前缀关系让窗起点**那一整日**的行永远删不掉(陈旧行),窗口仍报 complete。
27
+ if (write.rangeAlign !== 'shanghaiDay') {
28
+ out.push(`${task.id}:按日粒度范围列(${write.rangeColumns.join(', ')})删旧必须声明`
29
+ + ` rangeAlign='shanghaiDay' —— 否则引擎用 ISO 瞬时串与日粒度列值比较,`
30
+ + `窗起点那一日的行永远删不掉(静默留陈旧行、窗口仍 complete);`
31
+ + `行内若有逐行时间列,改用 instantColumn`);
32
+ }
33
+ if (task.windowAlign !== 'shanghaiDay') {
34
+ out.push(`${task.id}:按日粒度范围列删旧只在窗起止都落上海日界时精确,`
35
+ + `但任务未声明 windowAlign='shanghaiDay' —— 边界日会被相邻窗整片删掉;`
36
+ + `让窗对齐到日界,或改用 instantColumn(行内有逐行时间列时)`);
37
+ }
38
+ }
39
+ return out;
40
+ }
41
+ /** 注册表加载期守卫:任一任务违反契约即抛错(fail-fast,绝不带着错误声明起跑)。 */
42
+ export function assertWriteContracts(tasks) {
43
+ const violations = tasks.flatMap((t) => writeContractViolations(t));
44
+ if (violations.length > 0) {
45
+ throw new Error(`同步任务写策略声明违反契约:\n- ${violations.join('\n- ')}`);
46
+ }
47
+ }
48
+ /**
49
+ * 闸门键声明的前提(加载期校验,2026-11-15,Sourcery PR#58 复核):
50
+ * `gateEndpoints` 一旦声明就必须**非空**且包含主端点。空数组/漏写会静默回退成
51
+ * `[endpoint ?? id]`,多端点任务的次要端点冷却就永远读不到(实测形态见
52
+ * `tests/sync/gate-keys.test.ts` 文件头)。
53
+ * 不声明 `gateEndpoints` 仍是合法的「单端点任务」形态(21 个里 18 个如此);
54
+ * 要挡住的是「声明了但声明不完整」——那是唯一一种「看起来配了、实际没配上」的写法。
55
+ */
56
+ export function gateContractViolations(tasks) {
57
+ const out = [];
58
+ for (const t of tasks) {
59
+ if (t.gateEndpoints === undefined)
60
+ continue; // 单端点任务:合法,回退到 [endpoint ?? id]
61
+ if (!Array.isArray(t.gateEndpoints) || t.gateEndpoints.length === 0) {
62
+ out.push(`${t.id}:gateEndpoints 声明为空 —— 会静默回退成单键,多端点任务的次要冷却读不到;`
63
+ + '不需要闸门多键时请删掉该字段');
64
+ continue;
65
+ }
66
+ const primary = t.endpoint ?? t.id;
67
+ if (!t.gateEndpoints.includes(primary)) {
68
+ out.push(`${t.id}:gateEndpoints 未包含主端点 ${primary}(声明:${t.gateEndpoints.join('、')})——`
69
+ + '主端点的冷却会被漏读');
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+ export function assertGateContracts(tasks) {
75
+ const violations = gateContractViolations(tasks);
76
+ if (violations.length > 0) {
77
+ throw new Error(`同步任务闸门键声明违反契约:\n- ${violations.join('\n- ')}`);
78
+ }
79
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qiyu-cli",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "网易七鱼开放 API 的命令行封装,主要用户是 AI Agent:默认输出机器可读 JSON,用退出码表达意图,危险操作有硬门禁",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -36,7 +36,7 @@
36
36
  "build": "tsc && node scripts/copy-assets.mjs",
37
37
  "check:pack": "node scripts/check-pack.mjs",
38
38
  "prepare": "npm run build",
39
- "postinstall": "node dist/postinstall.js || exit 0",
39
+ "postinstall": "node -e \"const f=require('node:fs'),c=require('node:child_process'),p='dist/postinstall.js';if(f.existsSync(p))try{c.execFileSync(process.execPath,[p],{stdio:'inherit'})}catch{}\" || exit 0",
40
40
  "test": "node scripts/test-shards.mjs",
41
41
  "test:single": "vitest run --maxWorkers=1 --no-file-parallelism",
42
42
  "typecheck": "tsc -p tsconfig.test.json"