qiyu-cli 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +345 -56
  2. package/dist/cli.js +48 -7
  3. package/dist/commands/api-notes.js +54 -0
  4. package/dist/commands/api.js +112 -38
  5. package/dist/commands/auth.js +150 -28
  6. package/dist/commands/credentials-source.js +30 -5
  7. package/dist/commands/db-notes.js +75 -0
  8. package/dist/commands/db.js +112 -113
  9. package/dist/commands/query-notes.js +58 -0
  10. package/dist/commands/query.js +427 -56
  11. package/dist/commands/skill.js +445 -51
  12. package/dist/commands/spec-types.js +101 -1
  13. package/dist/commands/stats.js +139 -30
  14. package/dist/commands/store-flags.js +18 -0
  15. package/dist/commands/store-notes.js +38 -0
  16. package/dist/commands/store-precheck.js +254 -0
  17. package/dist/commands/store.js +128 -75
  18. package/dist/commands/sync-notes.js +367 -0
  19. package/dist/commands/sync-run.js +155 -44
  20. package/dist/commands/sync.js +181 -120
  21. package/dist/core/config.js +274 -24
  22. package/dist/core/credentials.js +38 -4
  23. package/dist/core/edition.js +1 -1
  24. package/dist/core/envelope.js +73 -9
  25. package/dist/core/errors.js +73 -16
  26. package/dist/core/http.js +151 -52
  27. package/dist/core/ratelimit.js +5 -1
  28. package/dist/core/registry/index.js +26 -2
  29. package/dist/core/registry/params/export.session.check.json +17 -2
  30. package/dist/core/registry/params/export.session.json +24 -2
  31. package/dist/core/registry/params/export.session.one.json +10 -2
  32. package/dist/core/registry/params/export.session.one.message.json +17 -2
  33. package/dist/core/registry/specs.json +64 -42
  34. package/dist/core/shell.js +30 -0
  35. package/dist/core/time.js +1 -1
  36. package/dist/core/validate.js +21 -2
  37. package/dist/output.js +204 -28
  38. package/dist/postinstall.js +14 -5
  39. package/dist/query/errors.js +145 -45
  40. package/dist/query/mask.js +1277 -25
  41. package/dist/query/metric-catalog.js +11 -0
  42. package/dist/query/native-error.js +189 -0
  43. package/dist/query/sandbox.js +129 -24
  44. package/dist/query/table-query.js +36 -5
  45. package/dist/schedule/install.js +136 -13
  46. package/dist/skill/check.js +11 -6
  47. package/dist/skill/detect.js +89 -29
  48. package/dist/skill/install.js +233 -43
  49. package/dist/skill/paths.js +54 -0
  50. package/dist/skill/qiyu/SKILL.md +29 -5
  51. package/dist/skill/qiyu/errors.md +5 -4
  52. package/dist/skill/qiyu/protocols.md +57 -5
  53. package/dist/skill/qiyu/setup.md +6 -2
  54. package/dist/store/config.js +92 -16
  55. package/dist/store/duckdb.js +51 -5
  56. package/dist/store/retry.js +92 -4
  57. package/dist/store/schema.js +26 -3
  58. package/dist/sync/engine.js +257 -65
  59. package/dist/sync/registry.js +4 -0
  60. package/dist/sync/state.js +20 -0
  61. package/dist/sync/tasks/dim.js +23 -14
  62. package/dist/sync/tasks/knowledge.js +50 -8
  63. package/dist/sync/tasks/pipeline.js +29 -9
  64. package/dist/sync/tasks/reports.js +176 -49
  65. package/dist/sync/tasks/sessions.js +88 -21
  66. package/dist/sync/tasks/tickets.js +59 -8
  67. package/dist/sync/types.js +60 -1
  68. package/dist/sync/windowing.js +0 -22
  69. package/dist/sync/write-contract.js +47 -0
  70. package/package.json +1 -1
@@ -1,6 +1,8 @@
1
1
  // src/sync/tasks/dim.ts
2
- // D-T6:维度表快照任务(6 任务;tags 已在 v1 建表且其同步语义与维度表同构,
3
- // 归属 T12 汇总时一并声明)。全部 kind=snapshot:接口全量无分页(设计稿 §6.2
2
+ // D-T6:维度表快照任务(6 任务)。⚠️ `tags` 表在 V1 就建了,但**本仓库没有任何同步任务
3
+ // 声明它**(`tag.all` 只是可调接口,不是同步数据集 id)——`sync run` 不会填充它,
4
+ // `sync tasks` 的输出里也没有它;早前这里写「归属 T12 汇总时一并声明」,与实况不符。
5
+ // 全部 kind=snapshot:接口全量无分页(设计稿 §6.2
4
6
  // 实测),幂等来自「全删重插」。fetch 内部经 http.call + 信封归一化——sync 不绕过信封层。
5
7
  // 落库行按 TABLES 列集显式投影(缺列补 null)——响应多出的键不进库,缺的键不炸 upsert。
6
8
  //
@@ -26,16 +28,17 @@ const isEmptyKey = (v) => v === null || v === undefined || v === '';
26
28
  * `keyCols`(C 低-7):落库主键列 —— 值为空串的行**显式失败**,绝不因 `''` 写出一行
27
29
  * 能被反复覆盖的同键行(空串是合法的 VARCHAR 值,upsert 主键语义会把它们当成同一个键)。
28
30
  * 只有 cols 里出现的键列才在这里判定(如 template_id 由行外补齐,由调用方自行守卫)。
31
+ *
32
+ * ⚠️ 这里**没有** per-row 变换回调(审查 #5,2026-11-03):早前本函数带 `perRow`,
33
+ * 但它返回 null 时静默 `continue` 丢行,而**所有**调用点都传 `undefined`——一支永不执行、
34
+ * 一旦执行就静默丢行的死代码。删除它,丢行只保留「显式抛错(keyCols)」一种形态。
29
35
  */
30
- function project(rows, cols, nowIso, perRow, keyCols = []) {
36
+ function project(rows, cols, nowIso, keyCols = []) {
31
37
  const out = [];
32
38
  for (const raw of rows) {
33
- const mid = perRow ? perRow(raw) : raw;
34
- if (mid === null)
35
- continue;
36
39
  const row = {};
37
40
  for (const c of cols) {
38
- const v = mid[c];
41
+ const v = raw[c];
39
42
  if (isEmptyKey(v) && keyCols.includes(c)) {
40
43
  throw new Error(`响应出现空的主键列 ${c}(值为 ${JSON.stringify(v)})——` +
41
44
  '空串/缺键会写出一行能被反复覆盖的同键行,拒绝落库');
@@ -49,9 +52,9 @@ function project(rows, cols, nowIso, perRow, keyCols = []) {
49
52
  }
50
53
  /** 维度快照任务的通用 fetch:callPaced 调接口 → 行数组 → 投影直写(写侧引擎全删重插)。
51
54
  * ⚠️ 走 callPaced(B 高-1):本地令牌桶拒绝被吸收为等待重试,远端限频写持久化冷却行。 */
52
- async function fetchAll(endpointId, body, cols, ctx, nowIso, perRow, keyCols = []) {
55
+ async function fetchAll(endpointId, body, cols, ctx, nowIso, keyCols = []) {
53
56
  const res = await callPaced(endpointId, body, ctx);
54
- const rows = project(rowsOf(res, endpointId), cols, nowIso, perRow, keyCols);
57
+ const rows = project(rowsOf(res, endpointId), cols, nowIso, keyCols);
55
58
  return { rows, apiCount: rows.length };
56
59
  }
57
60
  // 列集常量(与 schema.ts TABLES 对齐;漂移由 schema drift 对拍测试拦)
@@ -71,7 +74,7 @@ export const DIM_TASKS = [
71
74
  write: { kind: 'upsertRows' },
72
75
  // role 文档标必填但实测 status/role 都省略时返回全部 330 行(§6.2)——不传,取全量。
73
76
  // groupInfo 列表 → JSON 字符串列(project 统一 JSON.stringify,非字符串值均适用)。
74
- fetch: (w, ctx) => fetchAll('staff.list.new', {}, STAFF_COLS, ctx, nowIsoOf(ctx), undefined, ['id']),
77
+ fetch: (w, ctx) => fetchAll('staff.list.new', {}, STAFF_COLS, ctx, nowIsoOf(ctx), ['id']),
75
78
  },
76
79
  {
77
80
  id: 'dim.staff_groups', table: 'staff_groups', kind: 'snapshot',
@@ -80,7 +83,7 @@ export const DIM_TASKS = [
80
83
  endpoint: 'staff.group.list.new',
81
84
  write: { kind: 'upsertRows' },
82
85
  // staff:true 取 staffIdList(成员关系单独落 staff_group_members,本表不存)。
83
- fetch: (w, ctx) => fetchAll('staff.group.list.new', { staff: true }, STAFF_GROUP_COLS, ctx, nowIsoOf(ctx), undefined, ['id']),
86
+ fetch: (w, ctx) => fetchAll('staff.group.list.new', { staff: true }, STAFF_GROUP_COLS, ctx, nowIsoOf(ctx), ['id']),
84
87
  },
85
88
  {
86
89
  id: 'dim.staff_group_members', table: 'staff_group_members', kind: 'snapshot',
@@ -121,6 +124,8 @@ export const DIM_TASKS = [
121
124
  out.push({ group_id: gid, staff_id: String(sid), synchronized_at: nowIso });
122
125
  }
123
126
  }
127
+ // ⚠️ `reason` 必须 `as const`:宽松下推成 `string` 后 `FetchResult.gapHint` 的类型守卫
128
+ // 会因此报错,而这里唯一可能的取值就是该枚举成员。
124
129
  const gapHint = (malformed.length > 0 || skippedMembers > 0)
125
130
  ? {
126
131
  reason: 'staff_id_list_malformed',
@@ -139,7 +144,7 @@ export const DIM_TASKS = [
139
144
  endpoint: 'category.list',
140
145
  write: { kind: 'upsertRows' },
141
146
  // 文档标 type 必填(2=工单分类);响应列名是 parentId,落库保持原名。
142
- fetch: (w, ctx) => fetchAll('category.list', { type: 2 }, CATEGORY_COLS, ctx, nowIsoOf(ctx), undefined, ['id']),
147
+ fetch: (w, ctx) => fetchAll('category.list', { type: 2 }, CATEGORY_COLS, ctx, nowIsoOf(ctx), ['id']),
143
148
  },
144
149
  {
145
150
  id: 'dim.ticket_templates', table: 'ticket_templates', kind: 'snapshot',
@@ -148,13 +153,17 @@ export const DIM_TASKS = [
148
153
  endpoint: 'ticket.template.list',
149
154
  write: { kind: 'upsertRows' },
150
155
  // 文档标 status 必填(-1=全部状态);响应 status 全为 1、不携带信息 → 不建列。
151
- fetch: (w, ctx) => fetchAll('ticket.template.list', { status: -1 }, TEMPLATE_COLS, ctx, nowIsoOf(ctx), undefined, ['id']),
156
+ fetch: (w, ctx) => fetchAll('ticket.template.list', { status: -1 }, TEMPLATE_COLS, ctx, nowIsoOf(ctx), ['id']),
152
157
  },
153
158
  {
154
159
  id: 'dim.ticket_template_fields', table: 'ticket_template_fields', kind: 'snapshot',
155
160
  watermark: { field: 'synchronized_at', initial: null },
156
161
  primaryKey: ['template_id', 'fieldId'],
157
162
  endpoint: 'ticket.template.fields',
163
+ // ⚠️ 闸门必须覆盖 fetch 实际调用的**每个** endpoint(2026-11-02 实测修):模板列表的
164
+ // `ticket.template.list` 被限流时 penalize 写的是它自己的冷却行,只声明
165
+ // `ticket.template.fields` 会让引擎读不到那把冷却、下一窗照旧超发。
166
+ gateEndpoints: ['ticket.template.list', 'ticket.template.fields'],
158
167
  write: { kind: 'upsertRows' },
159
168
  // 每模板一次调用(接口按 templateId 取字段);行补 template_id 列(主键 template_id+fieldId,fieldId 是响应键)。
160
169
  // 闸门键取 ticket.template.fields(该任务的主要调用路径);templates 列表的
@@ -172,7 +181,7 @@ export const DIM_TASKS = [
172
181
  }
173
182
  const fres = await callPaced('ticket.template.fields', { templateId: t.id }, ctx);
174
183
  // 主键列 fieldId 的空值在 project 内显式失败(C 低-7)
175
- const rows = project(rowsOf(fres, 'ticket.template.fields'), FIELD_COLS, nowIso, undefined, ['fieldId']);
184
+ const rows = project(rowsOf(fres, 'ticket.template.fields'), FIELD_COLS, nowIso, ['fieldId']);
176
185
  for (const row of rows)
177
186
  out.push({ ...row, template_id: String(t.id) });
178
187
  }
@@ -134,26 +134,55 @@ function projectRows(rows, keys, numericCols, nowIso) {
134
134
  }
135
135
  return { rows: out, dropped };
136
136
  }
137
- /** 类目树拍平(children 在叶子上为 null,实测形态——空数组/null 都没有子节点)。 */
137
+ /**
138
+ * 空串主键拒绝(C 低-7,与 dim/reports/tickets/sessions 同一判据):`''` 是合法的
139
+ * VARCHAR 值,落库后会被 upsert 主键语义当成同一个键反复覆盖。
140
+ */
141
+ const isEmptyKey = (v) => v === null || v === undefined || v === '';
142
+ /**
143
+ * 类目树拍平(children 在叶子上为 null,实测形态——空数组/null 都没有子节点)。
144
+ *
145
+ * 返回**被丢弃的节点数**(审查 #5,2026-11-03):缺 id 的脏节点此前静默 `continue`
146
+ * ——它的**整棵子树**也随之中断(不再递归),而 `apiCount` 取拍平后的行数让配对核对
147
+ * 恒等,快照全删重插下这些类目无声消失。计数把「丢了多少」留给调用方落 gap。
148
+ * 子树一并计入(它们同样没落库),所以丢的是一个子树时数字会大于 1。
149
+ */
138
150
  function flattenTree(robotId, nodes, level, parentId, out, nowIso) {
139
151
  if (!Array.isArray(nodes))
140
- return;
152
+ return 0;
153
+ let dropped = 0;
141
154
  for (const n of nodes) {
142
155
  const cid = n.id;
143
- if (cid === null || cid === undefined)
144
- continue; // 缺 id 的脏节点:丢弃
156
+ // 空串 id 与缺键同等对待(CodeRabbit #61):`''` 是合法的 VARCHAR 值,落库后会被
157
+ // 当成同一个主键反复覆盖 —— 与其余任务「空主键行绝不落库」的红线同口径。
158
+ if (isEmptyKey(cid)) {
159
+ dropped += 1 + countNodes(n.children);
160
+ continue;
161
+ }
145
162
  const sId = String(cid);
146
163
  out.push({ robot_id: robotId, category_id: sId, name: typeof n.name === 'string' ? n.name : null,
147
164
  parent_id: parentId, level, payload: JSON.stringify(n), synchronized_at: nowIso });
148
- flattenTree(robotId, n.children, level + 1, sId, out, nowIso);
165
+ dropped += flattenTree(robotId, n.children, level + 1, sId, out, nowIso);
166
+ }
167
+ return dropped;
168
+ }
169
+ /** 子树节点总数(缺 id 节点被丢弃时,它的后代同样没落库,规模要如实计入)。 */
170
+ function countNodes(nodes) {
171
+ if (!Array.isArray(nodes))
172
+ return 0;
173
+ let n = 0;
174
+ for (const node of nodes) {
175
+ n += 1 + countNodes(node?.children);
149
176
  }
177
+ return n;
150
178
  }
151
179
  /**
152
180
  * 类目树拍平的共享入口(T13 接线):从根(level=1)拍平一棵 getCategoryTree 响应。
153
181
  * 编排层的 robotId 注入路径消费同一实现——复制投影会让行形态在两处漂移。
182
+ * 返回被丢弃的节点数(缺 id 的脏节点及其子树),调用方据此决定是否记 gap。
154
183
  */
155
184
  export function flattenCategoryTree(robotId, payload, out, nowIso) {
156
- flattenTree(robotId, payload, 1, null, out, nowIso);
185
+ return flattenTree(robotId, payload, 1, null, out, nowIso);
157
186
  }
158
187
  /**
159
188
  * knowledge_items / knowledge_points 共用的游标快照 fetch。numericCols 是 INTEGER 列集(数字直通)。
@@ -235,14 +264,27 @@ export const KNOWLEDGE_TASKS = [
235
264
  '请先同步 knowledge.items 任务');
236
265
  }
237
266
  const out = [];
267
+ let dropped = 0;
238
268
  for (const rid of robotIds) {
239
269
  const res = await callPaced('ai.knowledge.getCategoryTree', { robotId: Number(rid) }, ctx);
240
270
  // 形状 A:data 直接是树数组;空树机器人整个丢 data 键(not_found)→ 0 行合法
241
271
  if (res.payload === undefined || res.payload === null)
242
272
  continue;
243
- flattenTree(rid, res.payload, 1, null, out, nowIso);
273
+ dropped += flattenTree(rid, res.payload, 1, null, out, nowIso);
244
274
  }
245
- return { rows: out, apiCount: out.length };
275
+ return {
276
+ rows: out, apiCount: out.length,
277
+ ...(dropped > 0
278
+ ? {
279
+ gapHint: {
280
+ reason: 'knowledge_row_malformed',
281
+ detail: `knowledge.categories: ${dropped} 个类目节点被丢弃(自身或祖先缺 id,`
282
+ + '连同其子树;快照全删重插下这些类目已消失)——接口 ai.knowledge.getCategoryTree 的'
283
+ + '响应形态漂移,请核对',
284
+ },
285
+ }
286
+ : {}),
287
+ };
246
288
  },
247
289
  },
248
290
  ];
@@ -15,17 +15,19 @@
15
15
  // 同参数重复创建返回不同 key 相同数据)——本函数只返回行,去重由 upsert(session_id) 幂等吸收。
16
16
  import { callPaced } from './pace.js';
17
17
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18
- /** 形状 A 载荷里的 message 字符串(create 的任务 key / check 的下载链接都走 message)。 */
18
+ /** 形状 M 的载荷(create 的任务 key / check 的下载链接都走 message 原文)。 */
19
19
  function messageOf(res, endpointId) {
20
- // 形状 A(envelope:'A'):信封层把 data 放进 payload、原文放 messageText。
20
+ // 形状 M(envelope:'M',2026-11-04 修正):信封层直接把 message 原文放进 payload。
21
21
  // 实测 create/check 的载荷就是 message 字符串本身(key/链接),不信任何 data 形态。
22
+ // ⚠️ 'OK' 是占位符(形态漂移的典型形态)——两个来源都要挡掉,否则会拿 'OK'
23
+ // 当下载链接去下载。
22
24
  const p = res.payload;
23
- if (typeof p === 'string' && p !== '')
25
+ if (typeof p === 'string' && p !== '' && p !== 'OK')
24
26
  return p;
25
27
  if (typeof res.messageText === 'string' && res.messageText !== '' && res.messageText !== 'OK') {
26
28
  return res.messageText;
27
29
  }
28
- throw new Error(`接口 ${endpointId} 未返回可用的 message 载荷(响应形态漂移?)`);
30
+ throw new Error(`接口 ${endpointId} 未返回可用的 message 载荷(响应形态漂移?—— 空串或 'OK' 占位)`);
29
31
  }
30
32
  /**
31
33
  * 解压密码 zip(ZipCrypto,密码 = appKey 前 12 字符,设计稿 §7.5 实测)并取出 session.txt。
@@ -95,8 +97,16 @@ function findEntry(zip) {
95
97
  };
96
98
  }
97
99
  /**
98
- * 中央目录里按名取条目:路径 EOCD(尾部 22 字节定长 + 可选注释,签名 0x06054b50)
99
- * → CD 起始偏移/条目数 → 逐条 CD 记录(46 字节定长 + 名 + 扩展 + 注释)按名匹配。
100
+ * 中央目录里取条目:路径 EOCD(尾部 22 字节定长 + 可选注释,签名 0x06054b50)
101
+ * → CD 起始偏移/条目数 → 逐条 CD 记录(46 字节定长 + 名 + 扩展 + 注释)匹配**基名**。
102
+ *
103
+ * ⚠️ 匹配的是**基名**(`name` 与末段相等),不是整段相等(2026-11-08 真实导出实测):
104
+ * 线上 zip 的条目名带导出 id 目录前缀(`5411798/session.txt`、`5411798/message.txt`),
105
+ * 精确匹配 `session.txt` 会**永远找不到** —— 每个窗口都抛「没有 session.txt 条目」、
106
+ * 整窗 fetch_failed。前缀是不可预知的导出 id,只能按基名匹配。
107
+ * 基名匹配必须**恰好一条**:同基名多条目(`a/session.txt` + `b/session.txt`)→ 显式抛错,
108
+ * 不猜(形态漂移,宁可失败也不在两条里任选一条把别人的数据落库)。
109
+ *
100
110
  * 返回 CD 里的 crc / csize / 本地头偏移(偏移 42)。找不到/结构不符 → 显式抛错:
101
111
  * 宁可失败,也绝不在「无校验字节可对」的状态下把错密码的乱码当数据吐出去。
102
112
  * 修复批 4 #5:本函数从「bit3 的兜底补查」升格为**唯一定位来源**(原逐条目本地头
@@ -119,6 +129,7 @@ function centralDirectoryEntry(zip, name) {
119
129
  const count = u16(eocd + 10);
120
130
  let o = u32(eocd + 16);
121
131
  const decoder = new TextDecoder();
132
+ let found;
122
133
  for (let i = 0; i < count; i++) {
123
134
  if (o + 46 > zip.length || u32(o) !== 0x02014b50) {
124
135
  throw new Error('zip central directory 结构不符——无法校验解压密码,拒绝落库');
@@ -127,12 +138,21 @@ function centralDirectoryEntry(zip, name) {
127
138
  const elen = u16(o + 30);
128
139
  const clen = u16(o + 32);
129
140
  const entryName = decoder.decode(zip.subarray(o + 46, o + 46 + nlen));
130
- if (entryName === name) {
131
- return { crc: u32(o + 16), csize: u32(o + 20), localOffset: u32(o + 42) };
141
+ // 基名匹配:`dir/session.txt` 与 `session.txt` 都算(前缀是导出 id,不可预知)。
142
+ const base = entryName.split('/').pop() ?? entryName;
143
+ if (base === name) {
144
+ if (found !== undefined) {
145
+ throw new Error(`zip 内有多个 ${name} 条目(${found.entryName}、${entryName})`
146
+ + '——形态漂移,无法确定用哪一个,拒绝落库');
147
+ }
148
+ found = { crc: u32(o + 16), csize: u32(o + 20), localOffset: u32(o + 42), entryName };
132
149
  }
133
150
  o = o + 46 + nlen + elen + clen;
134
151
  }
135
- throw new Error(`zip central directory 内没有 ${name} 条目——无法校验解压密码,拒绝落库`);
152
+ if (found === undefined) {
153
+ throw new Error(`zip central directory 内没有 ${name} 条目——无法校验解压密码,拒绝落库`);
154
+ }
155
+ return { crc: found.crc, csize: found.csize, localOffset: found.localOffset };
136
156
  }
137
157
  /**
138
158
  * ZipCrypto 解密:密钥由密码初始化,逐字节流式更新;校验字节匹配则剥掉 12 字节头。
@@ -98,6 +98,23 @@ export function reportBody(taskId, w) {
98
98
  * transfer_human 是形状 A、载荷在 data)。识别已知包装键(result/orders),
99
99
  * 其余对象形态视为「一行全局汇总」(overview 69 字段/summary 27 字段/transfer 恒 1 行)。
100
100
  */
101
+ /**
102
+ * 载荷 → 行数组(逐接口信封实测:C 族载荷是 message 解析物;robot_summary/
103
+ * transfer_human 是形状 A、载荷在 data)。识别已知包装键(result/orders),
104
+ * 其余对象形态视为「一行全局汇总」(overview 69 字段/summary 27 字段/transfer 恒 1 行)。
105
+ *
106
+ * ⚠️ **结构为空的载荷(`{}` / `[]`)一律拒绝**(HANDOFF 报表层 #6,2026-11-04 真实上游采样):
107
+ * 九个报表接口的**空窗**形状全部实测过,没有一个是空容器 ——
108
+ * · `overview` → 带 69 字段的**全零行**(`sessions:0` … 比例字段 `-1`);
109
+ * · `robot.summary` → 带字段的汇总行;`transferHuman` → **一行**数组
110
+ * `[{count:0, sessionRatio:-1, type:0}]`;`salaryDetail` → 带 account/date/id 的**一行**对象;
111
+ * · `staffworklod` / `satisfaction` / `staffAttendance` → `{result:[], total:0}`;
112
+ * `staffquality` → `{result:[], sum:{…34 字段}, total:0}`;
113
+ * `performance` → `{orders:[], sum:{…20 字段}, total:0}`。
114
+ * 所以 `{}` 落进下面的「一行全局汇总」兜底会把**一次形态漂移**写成一行全空行(覆盖真实
115
+ * 汇总的同键行),而 `[]` 会被当合法空窗 → `complete` 且零 gap:两种都是「静默吃掉一整窗」。
116
+ * 与 `api` 层 `not_found`(解包后 `{}`/`[]`)同一判据,这里只是把它变成**拒绝落库**。
117
+ */
101
118
  function payloadRows(taskId, payload) {
102
119
  // C 中-5:载荷为 null/undefined 是**形状漂移**(信封层丢 data 键、或上游改了形态),
103
120
  // 绝不能当合法空窗 —— 静默按空处理会把整段数据吞成 complete。与同文件 orders:null
@@ -105,9 +122,22 @@ function payloadRows(taskId, payload) {
105
122
  if (payload === null || payload === undefined) {
106
123
  throw new Error(`接口 ${endpointOf(taskId)} 未返回载荷(null/undefined)——响应形态漂移,拒绝按空窗处理`);
107
124
  }
108
- if (Array.isArray(payload))
125
+ if (Array.isArray(payload)) {
126
+ // 空数组:实测空窗从不是 `[]`(transferHuman 空窗是一行数组)→ 形态漂移。
127
+ if (payload.length === 0) {
128
+ throw new Error(`接口 ${endpointOf(taskId)} 返回空数组 [] —— 实测空窗形态是 `
129
+ + '{result:[],total:0}(result 族)或一行数组(transferHuman),空数组属响应形态漂移,拒绝按空窗处理');
130
+ }
109
131
  return { rows: payload, sum: null };
132
+ }
110
133
  const o = payload;
134
+ // 空对象:实测空窗从不是 `{}`(全局汇总表返回的是带字段的全零行;salaryDetail 返回带字段的一行)
135
+ // → 落进下面的「一行全局汇总」兜底会写出全空行,覆盖真实汇总。
136
+ if (Object.keys(o).length === 0) {
137
+ throw new Error(`接口 ${endpointOf(taskId)} 返回空对象 {} —— 实测空窗形态是带字段的全零行`
138
+ + '(overview/summary/salaryDetail)或 {result:[],total:0},空对象属响应形态漂移,'
139
+ + '拒绝当作「一行全局汇总」落库');
140
+ }
111
141
  // statistic.performance 的全 null 形态(orders:null/sum:null/total:null,code:200)
112
142
  // 是筛选失败(staffIdList 含租户不存在的 id),不是空窗口——fetch 层抛带 kind 的
113
143
  // 形态错误,引擎记 sync_gaps(reason=filter_matched_no_staff,T5 裁定透传)。
@@ -132,14 +162,69 @@ function staffRow(w, r, nowIso) {
132
162
  return null;
133
163
  return { ...baseRow(w, r, nowIso), staff_id: String(sid) };
134
164
  }
135
- /** 分页 + per-staff 投影(staffworklod / staff_satisfaction)。 */
136
- async function fetchPagedStaff(taskId, w, ctx) {
165
+ /**
166
+ * 分页 + per-staff 投影(staffworklod / staff_satisfaction;staffquality 传 withSum)。
167
+ * ⚠️ `withSum`(2026-11-03 实测修):staffquality 此前走 `fetchSimple` —— **不分页**,
168
+ * 上游 `total=1500` 只取回首页 1000 行仍 `complete`(C 中-3 的短读终检只存在于 `pagedRaw`,
169
+ * 实测只发了 1 个请求)。实测事实(设计稿 §6.2):`staffquality` **分页**(pageSize=5 时
170
+ * `result` 只有 5 行)且 `sum` 与分页无关、始终覆盖全集 → 分页拉满后照写 sum 全局行
171
+ * (staff_id='sum' 哨兵,主键含 stat_date,按天各自一行)。
172
+ */
173
+ async function fetchPagedStaff(taskId, w, ctx, withSum = false) {
137
174
  const nowIso = nowIsoOf(ctx);
138
- const { rows } = await pagedRaw(taskId, w, ctx);
139
- const mapped = rows
140
- .map((r) => staffRow(w, r, nowIso))
141
- .filter((r) => r !== null);
142
- return { rows: mapped, apiCount: mapped.length };
175
+ const { rows, sum } = await pagedRaw(taskId, w, ctx);
176
+ const mapped = [];
177
+ let dropped = 0;
178
+ for (const r of rows) {
179
+ const row = staffRow(w, r, nowIso);
180
+ if (row === null) {
181
+ dropped++;
182
+ continue;
183
+ } // 缺 staff_id 键的行:丢弃并计数(见下 gapHint)
184
+ mapped.push(row);
185
+ }
186
+ if (withSum && sum)
187
+ mapped.push({ ...baseRow(w, sum, nowIso), staff_id: 'sum' });
188
+ return { rows: mapped, apiCount: mapped.length, ...droppedHint(taskId, dropped, `缺 staffId(主键列,缺键或空串)`) };
189
+ }
190
+ /**
191
+ * 行被丢弃时的 task gapHint(`row_missing_key`)。
192
+ *
193
+ * ⚠️ 为什么必须记(审查 #5,2026-11-03):`apiCount` 取的是**过滤后**的行数,
194
+ * 配对核对(写库行数 vs apiCount)恒等,缺键行于是**静默消失** —— 窗口照样
195
+ * `status: complete`、`fetched == written`,Agent 无从知道上游有一批行没进库。
196
+ * 这类行是真的没落库(`TASK_GAP_LOSSY_REASONS` 档),必须留痕。
197
+ *
198
+ * `what` 是**丢弃成因的完整描述**(不是列名)—— 成因必须点名真正给坏值的那个东西
199
+ * (CodeRabbit #61:把「date 不是合法时间戳」写成「缺主键列」会把运维引向错的条件)。
200
+ */
201
+ function droppedHint(taskId, dropped, what) {
202
+ if (dropped === 0)
203
+ return {};
204
+ return {
205
+ gapHint: {
206
+ reason: 'row_missing_key',
207
+ detail: `${taskId}: ${dropped} 行${what}被丢弃、未落库`
208
+ + ' —— 上游响应形态漂移,请核对接口返回;本次按已落库的行覆盖窗口',
209
+ },
210
+ };
211
+ }
212
+ /**
213
+ * 一行被丢弃时的 gapHint:`dropped` 是按成因分好的几档(每档一个规模 + 一句说明)。
214
+ * 多个成因时合成一条(引擎每窗只有一个 gapHint),但**逐档点名**、不合并成一个数。
215
+ */
216
+ function droppedHintParts(taskId, parts) {
217
+ const nonZero = parts.filter(([n]) => n > 0);
218
+ if (nonZero.length === 0)
219
+ return {};
220
+ const detail = nonZero.map(([n, what]) => `${n} 行${what}`).join(';');
221
+ return {
222
+ gapHint: {
223
+ reason: 'row_missing_key',
224
+ detail: `${taskId}: ${detail}被丢弃、未落库`
225
+ + ' —— 上游响应形态漂移,请核对接口返回;本次按已落库的行覆盖窗口',
226
+ },
227
+ };
143
228
  }
144
229
  /**
145
230
  * stat_date + payload 的通用行投影(键列由各任务补齐)。
@@ -181,7 +266,14 @@ async function pagedRaw(taskId, w, ctx) {
181
266
  out.push(...rows);
182
267
  const total = res.payload?.total;
183
268
  if (typeof total !== 'number') {
184
- // total 缺省视为单页:拉满一页仍不声明 total 时不再翻(口径与 tickets.search 一致)
269
+ // ⚠️ 只有在**第一页**就缺 total 时才按「单页」处理(口径与 tickets.search 一致)。
270
+ // 已声明过 total 之后某页缺它 = 响应形态漂移,**不能**再把 declared 清空并 break ——
271
+ // 那会让下面的短读终检永远不执行,静默返回少于声明 total 的行且不留任何 gap
272
+ //(2026-11-07 审查实测:page1 total=5 + 2 行、page2 1 行无 total → 返回 3 行、不报错)。
273
+ if (declared !== null) {
274
+ throw new Error(`接口 ${endpointOf(taskId)} 第 ${page} 页缺少 total(首页声明 total=${declared}):` +
275
+ '响应形态漂移,拒绝落库——重跑即可');
276
+ }
185
277
  declared = null;
186
278
  break;
187
279
  }
@@ -217,35 +309,29 @@ function endpointOf(taskId) {
217
309
  default: throw new Error(`未知报表任务:${taskId}`);
218
310
  }
219
311
  }
220
- /** 普通报表 fetch(result/全局行形态):stat_date=窗口起点按上海天对齐;staffId 键取不到时用 'sum' 哨兵。 */
221
- function fetchSimple(taskId, perStaff) {
312
+ /**
313
+ * 全局汇总报表 fetch(overview / robot_summary / transfer_human):响应是**一行全局汇总**,
314
+ * 无 staffId,行形状按目标表列集投影(stat_date + payload)。
315
+ *
316
+ * ⚠️ 这里**没有** per-staff 分支(审查 #5,2026-11-03):早前本函数带 `perStaff` 参数,
317
+ * 但三个调用点全是全局表,`perStaff=true` 的分支连同它「缺 staffId 就 `continue` 丢弃」
318
+ * 的逻辑是**死代码**——声明了却永不执行的一支,正是契约诚实性要消灭的形态;per-staff 表
319
+ * (staffworklod / satisfaction / quality)早已改走 `fetchPagedStaff`(那里的丢弃有
320
+ * `row_missing_key` 缺口留痕)。因此本函数不做投影过滤,不存在静默丢行。
321
+ */
322
+ function fetchSimple(taskId) {
222
323
  return async (w, ctx) => {
223
324
  const nowIso = nowIsoOf(ctx);
224
325
  // B 高-1:走 callPaced(本地令牌桶拒绝被吸收为等待重试;远端限频写持久化冷却行)。
225
326
  // 裸 call 会让两种限频都直接冒泡成 fetch_failed gap,而空窗假空重试必然二次调用
226
327
  // 同一路径——这是最容易撞上本地限频的一条路径。
227
328
  const res = await callPaced(endpointOf(taskId), reportBody(taskId, w), ctx);
228
- const { rows, sum } = payloadRows(taskId, res.payload);
229
- const mapped = [];
230
- for (const r of rows) {
231
- // perStaff 表(staff_workload/quality/satisfaction)键是 (stat_date, staff_id);
232
- // 全局汇总表(overview/robot_summary/transfer_human)键只有 stat_date——
233
- // 响应没有 staffId,行形状按目标表列集投影。
234
- const base = baseRow(w, r, nowIso);
235
- if (perStaff) {
236
- const sid = r.staffId ?? r.staffid ?? r.staff_id;
237
- if (isEmptyKey(sid))
238
- continue; // 键缺失/空串行:计入 fetched 不写库
239
- mapped.push({ ...base, staff_id: String(sid) });
240
- }
241
- else {
242
- mapped.push(base);
243
- }
244
- }
245
- // staffquality 全局 sum 行(覆盖全集、与分页无关):sum 本就没有 staff_id,
246
- // 落 perStaff 表时用上游无语义的哨兵 'sum'(约定位置,见 task-7-report)。
247
- if (sum && perStaff)
248
- mapped.push({ ...baseRow(w, sum, nowIso), staff_id: 'sum' });
329
+ const { rows } = payloadRows(taskId, res.payload);
330
+ // ⚠️ 刻意**不写** sum 行:这三张全局表的主键只有 stat_date,而同窗口的 sum 行不带
331
+ // 任何区分列 —— 写进去会与那一行全局汇总同键互覆(`payloadRows` 对全局表本来也
332
+ // 返回 sum=null;这里显式不取,避免以后有人以为「漏了」而补上)。per-staff 表的
333
+ // sum 由 `fetchPagedStaff` 按 `staff_id='sum'` 哨兵处理(那里主键含 stat_date)。
334
+ const mapped = rows.map((r) => baseRow(w, r, nowIso));
249
335
  return { rows: mapped, apiCount: mapped.length };
250
336
  };
251
337
  }
@@ -256,8 +342,14 @@ async function staffIds(store) {
256
342
  .map((x) => (isEmptyKey(x.id) ? '' : String(x.id)))
257
343
  .filter((id) => id !== '');
258
344
  }
259
- /** 报表任务的通用写策略(A 中-2:删除边界与行内日期列同口径 = 上海天对齐)。 */
345
+ /**
346
+ * 报表任务的通用写策略(A 中-2:删除边界与行内日期列同口径 = 上海天对齐)。
347
+ * ⚠️ 只在「窗起止都落在日界」时精确 —— 声明者必须同时 `windowAlign: 'shanghaiDay'`
348
+ *(注册表加载期由 `write-contract.ts` 校验,见 `tests/sync/delete-boundary-contract.test.ts`)。
349
+ */
260
350
  const RANGE_INSERT = { kind: 'deleteRangeInsert', rangeColumns: ['stat_date'], rangeAlign: 'shanghaiDay' };
351
+ /** 行内自带逐小时时间戳 → 按窗精确删(`[start, end)`),不碰相邻窗的边界日。 */
352
+ const HOUR_INSERT = { kind: 'deleteRangeInsert', instantColumn: 'hour_ts' };
261
353
  export const REPORT_TASKS = [
262
354
  {
263
355
  id: 'reports.overview', table: 'daily_overview', kind: 'windowed',
@@ -268,7 +360,7 @@ export const REPORT_TASKS = [
268
360
  primaryKey: ['stat_date'], reportDayRotation: true,
269
361
  endpoint: 'statistic.overview',
270
362
  write: RANGE_INSERT,
271
- fetch: fetchSimple('reports.overview', false),
363
+ fetch: fetchSimple('reports.overview'),
272
364
  },
273
365
  {
274
366
  id: 'reports.staff_workload', table: 'staff_workload', kind: 'windowed',
@@ -287,7 +379,9 @@ export const REPORT_TASKS = [
287
379
  primaryKey: ['stat_date', 'staff_id'], reportDayRotation: true,
288
380
  endpoint: 'statistic.staffquality',
289
381
  write: RANGE_INSERT,
290
- fetch: fetchSimple('reports.staff_quality', true),
382
+ // ⚠️ 必须分页(2026-11-03 实测修):此前 fetchSimple 单次调用不读 total —— 租户
383
+ // 客服 > 1000 时被静默截断且仍 complete。sum 全局行经 withSum 保留。
384
+ fetch: (w, ctx) => fetchPagedStaff('reports.staff_quality', w, ctx, true),
291
385
  },
292
386
  {
293
387
  id: 'reports.staff_satisfaction', table: 'staff_satisfaction', kind: 'windowed',
@@ -303,6 +397,11 @@ export const REPORT_TASKS = [
303
397
  // 逐行可信时间戳(`date` 按小时对齐,落 hour_ts)→ 31 天窗口可行(≈1.7 万行/窗);
304
398
  // stat_date 由该行的 hour_ts 推导(不是窗口起点)——它跟随该行自己的业务日
305
399
  maxWindowDays: 31, overlapDays: 0,
400
+ // ⚠️ **刻意不声明 windowAlign**(2026-11-03 复核):31 天步长的日对齐网格 + 残段窗
401
+ // 跳过规则会让「水位+1ms 落在日中间」的首窗被整段跳过、再跳到 +31 天,中间 30 天直接
402
+ // 不抓(日对齐只在 maxWindowDays=1 的任务上安全)。窗不对齐日界就不能按 stat_date 的
403
+ // 自然日删 —— 改用 `instantColumn: 'hour_ts'`:删除范围跟随窗本身,窗内消失的小时
404
+ // 精确删、窗外相邻窗写好的小时一行不碰。
306
405
  watermark: { field: 'stat_date', initial: null },
307
406
  // hour_ts 是响应内唯一可信日期字段(小时对齐时间戳)
308
407
  primaryKey: ['staff_id', 'hour_ts'], reportDayRotation: true,
@@ -310,13 +409,16 @@ export const REPORT_TASKS = [
310
409
  // G 高-1:endTime 不得晚于今天 0:00(14501 endTime is invalid),
311
410
  // 且今天 0:00 这条边界不稳定 → 引擎把窗口 end 钳到昨天 0:00(留整日余量)。
312
411
  windowEndClamp: 'shanghaiYesterday',
313
- write: RANGE_INSERT,
412
+ // 逐行 hour_ts → 删除按 [start, end) 精确(31 天窗起止不在日界,见 types.ts instantColumn)
413
+ write: HOUR_INSERT,
314
414
  // ⚠️ 请求体恒含 startTime(reportBody 已保证)——省略会静默降级为天粒度、少抓 ~10 倍。
315
415
  // 分页 total 收敛拉满(单页 pageSize=1000,31d 实测 17765 行 → 两页),再抽 hour_ts。
316
416
  fetch: async (w, ctx) => {
317
417
  const nowIso = nowIsoOf(ctx);
318
418
  const { rows } = await pagedRaw('reports.staff_attendance', w, ctx);
319
419
  const mapped = [];
420
+ let badKey = 0;
421
+ let badTs = 0;
320
422
  for (const r of rows) {
321
423
  const sid = r.staffId ?? r.staffid;
322
424
  const ts = r.date; // 该小时按小时对齐的时间戳
@@ -330,16 +432,29 @@ export const REPORT_TASKS = [
330
432
  //(与读侧「一条脏值炸整条命令」同一失败模式)。上界取 `MAX_SHANGHAI_SAFE_MS`
331
433
  // 而不是 `MAX_DATE_MS`:两者都要「能回显成 +08:00 ISO」,差 8h 就会在
332
434
  // `shanghaiDayIso` 的偏移后一段重新抛。
435
+ // 丢弃的两类分开计数(CodeRabbit #61):缺 staff_id 是「缺主键列」,
436
+ // date 非数字/秒级/越界是「脏时间戳」—— 两者的动作不同,不能混成一句。
333
437
  const n = Number(ts);
334
- if (isEmptyKey(sid) || !Number.isFinite(n) || n <= 1e11 || n > MAX_SHANGHAI_SAFE_MS)
438
+ if (isEmptyKey(sid)) {
439
+ badKey++;
440
+ continue;
441
+ }
442
+ if (!Number.isFinite(n) || n <= 1e11 || n > MAX_SHANGHAI_SAFE_MS) {
443
+ badTs++;
335
444
  continue;
445
+ }
336
446
  // 修复批 4:stat_date 按**本行的 hour_ts** 推导上海日(不再用窗口起点)——
337
447
  // 31 天窗口里行跨多个自然日,用窗口起点会把它们全标成窗口首日。
338
- // 删除范围仍是 [dayOf(w.start), dayOf(w.end)](writeRows 的天对齐边界),
339
- // 覆盖窗内所有天 → 与本行的 stat_date 一致。
448
+ // 删除范围按 hour_ts ∈ [w.start, w.end)(write 的 instantColumn),与写入逐行同口径。
340
449
  mapped.push({ ...baseRow(w, r, nowIso, n), staff_id: String(sid), hour_ts: new Date(n).toISOString() });
341
450
  }
342
- return { rows: mapped, apiCount: mapped.length };
451
+ return {
452
+ rows: mapped, apiCount: mapped.length,
453
+ ...droppedHintParts('reports.staff_attendance', [
454
+ [badKey, '缺 staffId(主键列,缺键或空串)'],
455
+ [badTs, '的 date 不是合法毫秒时间戳(非数字/秒级/越界,无法作为 hour_ts)'],
456
+ ]),
457
+ };
343
458
  },
344
459
  },
345
460
  {
@@ -350,28 +465,40 @@ export const REPORT_TASKS = [
350
465
  watermark: { field: 'stat_date', initial: null },
351
466
  primaryKey: ['order_id'], reportDayRotation: true,
352
467
  endpoint: 'statistic.performance',
353
- // G 高-1:与 staff_attendance 同族的 endTime 对齐检查(14501 endTime is invalid)
468
+ // G 高-1:与 staff_attendance 同族的 endTime 上界检查(14501 endTime is invalid)
354
469
  windowEndClamp: 'shanghaiYesterday',
355
470
  write: RANGE_INSERT,
356
471
  // orders:null = 筛选失败、不是空窗口(staffIdList 含租户不存在的 id 时 code:200
357
472
  // 全 null)→ 显式 gapHint,引擎落 sync_gaps(T5 裁定:透传原始 reason)。
358
- // 行映射补主键列 order_id(响应键 orderId);缺 order_id 的订单行丢弃——
359
- // 计入 fetched 不写库(脏单行不致断流,与 per-staff 表同一取舍);
360
- // sum 全局行按 controller 裁定落同表哨兵 order_id='sum'(与 staff_quality 一致)。
473
+ // 行映射补主键列 order_id(响应键 orderId);缺 order_id 的订单行**丢弃且不计入
474
+ // fetched**(`continue` 在 push 之前 —— 此前注释写「计入 fetched」,与代码相反;
475
+ // 「丢了几行」目前对 Agent 不可见,见 HANDOFF 的 report_row_dropped 待办)。
476
+ // ⚠️ sum 行必须**按天**唯一(2026-11-03 实测修):本表主键只有 `order_id`,而
477
+ // staff_quality 的哨兵 `staff_id='sum'` 之所以按天各一行,是它的主键含 stat_date。
478
+ // 沿用裸 `'sum'` 时,回补前一天会 upsert 覆盖后一天的 sum(实测:先 day1 再 day0,
479
+ // day1 的汇总整体消失)—— 故哨兵随窗口日:`sum:<上海日>`。
361
480
  fetch: async (w, ctx) => {
362
481
  try {
363
482
  const nowIso = nowIsoOf(ctx);
364
483
  const { rows, sum } = await pagedRaw('reports.order_performance', w, ctx);
365
484
  const mapped = [];
485
+ let dropped = 0;
366
486
  for (const r of rows) {
367
487
  const oid = r.orderId ?? r.order_id;
368
- if (isEmptyKey(oid))
488
+ // 缺 order_id 的订单行:丢弃并计数(审查 #5,见 droppedHint);此前只丢弃、
489
+ // 不留痕,Agent 从 complete 的窗口上看不出上游有一批行没进库。
490
+ if (isEmptyKey(oid)) {
491
+ dropped++;
369
492
  continue;
493
+ }
370
494
  mapped.push({ ...baseRow(w, r, nowIso), order_id: String(oid) });
371
495
  }
372
496
  if (sum)
373
- mapped.push({ ...baseRow(w, sum, nowIso), order_id: 'sum' });
374
- return { rows: mapped, apiCount: mapped.length };
497
+ mapped.push({ ...baseRow(w, sum, nowIso), order_id: `sum:${shanghaiDayIso(w.start)}` });
498
+ return {
499
+ rows: mapped, apiCount: mapped.length,
500
+ ...droppedHint('reports.order_performance', dropped, '缺 orderId(主键列,缺键或空串)'),
501
+ };
375
502
  }
376
503
  catch (e) {
377
504
  if (e.kind === 'filter_matched_no_staff') {
@@ -425,7 +552,7 @@ export const REPORT_TASKS = [
425
552
  endpoint: 'robot.statistic.summary',
426
553
  write: RANGE_INSERT,
427
554
  // 形状 A;robotId 被服务端忽略 → body 不含(reportBody 保证)
428
- fetch: fetchSimple('reports.robot_summary', false),
555
+ fetch: fetchSimple('reports.robot_summary'),
429
556
  },
430
557
  {
431
558
  id: 'reports.transfer_human', table: 'transfer_human', kind: 'windowed',
@@ -439,7 +566,7 @@ export const REPORT_TASKS = [
439
566
  endpoint: 'ai.statistic.transferHuman',
440
567
  write: RANGE_INSERT,
441
568
  // 形状 A;type/robotId 被服务端忽略 → body 不含(reportBody 保证)
442
- fetch: fetchSimple('reports.transfer_human', false),
569
+ fetch: fetchSimple('reports.transfer_human'),
443
570
  },
444
571
  ];
445
572
  /** 按 id 取报表任务(T12 汇总与测试的取用形态)。 */