weflow-cli 1.6.3 → 1.7.0

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 (43) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/OPERATIONS.md +36 -1
  3. package/README.en.md +1 -1
  4. package/README.md +1 -1
  5. package/bin/weflow-cli.ts +312 -0
  6. package/dist/bin/weflow-cli.js +352 -0
  7. package/dist/bin/weflow-cli.js.map +1 -1
  8. package/dist/src/core/ntCore.d.ts +26 -0
  9. package/dist/src/core/ntCore.d.ts.map +1 -1
  10. package/dist/src/core/ntCore.js +21 -0
  11. package/dist/src/core/ntCore.js.map +1 -1
  12. package/dist/src/services/chatService.d.ts +13 -0
  13. package/dist/src/services/chatService.d.ts.map +1 -1
  14. package/dist/src/services/chatService.js +20 -0
  15. package/dist/src/services/chatService.js.map +1 -1
  16. package/dist/src/services/messageQuery.d.ts +35 -0
  17. package/dist/src/services/messageQuery.d.ts.map +1 -1
  18. package/dist/src/services/messageQuery.js +61 -0
  19. package/dist/src/services/messageQuery.js.map +1 -1
  20. package/dist/src/services/syncService.d.ts +121 -0
  21. package/dist/src/services/syncService.d.ts.map +1 -0
  22. package/dist/src/services/syncService.js +244 -0
  23. package/dist/src/services/syncService.js.map +1 -0
  24. package/dist/src/services/syncState.d.ts +113 -0
  25. package/dist/src/services/syncState.d.ts.map +1 -0
  26. package/dist/src/services/syncState.js +214 -0
  27. package/dist/src/services/syncState.js.map +1 -0
  28. package/docs/DECISIONS.md +60 -20
  29. package/docs/FUNCTIONAL-IMPROVEMENT-SPEC.md +338 -0
  30. package/docs/HEALTH-CHECK.md +6 -5
  31. package/docs/MCP.md +1 -1
  32. package/docs/NPM-PUBLISH.md +12 -4
  33. package/docs/PROJECT_STATE.md +8 -6
  34. package/docs/SETUP.md +1 -1
  35. package/docs/SYNC_CONTRACT.md +152 -0
  36. package/package.json +3 -3
  37. package/scripts/export_chat_html.py +242 -26
  38. package/scripts/nt_decrypt.py +123 -15
  39. package/src/core/ntCore.ts +42 -0
  40. package/src/services/chatService.ts +26 -0
  41. package/src/services/messageQuery.ts +97 -0
  42. package/src/services/syncService.ts +335 -0
  43. package/src/services/syncState.ts +275 -0
@@ -0,0 +1,335 @@
1
+ /**
2
+ * One sync pass: pick a window, read it, dedupe, decide coverage, record state.
3
+ *
4
+ * Deliberately not a general job runner - it is the single caller of the sync
5
+ * state contract for now (docs/SYNC_CONTRACT.md, D-029).
6
+ */
7
+ import type { Message } from '../types.js'
8
+ import type { ShardReport } from '../core/ntCore.js'
9
+ import {
10
+ DEFAULT_OVERLAP_SECONDS,
11
+ SYNC_SOURCE,
12
+ emptySyncState,
13
+ makeJobId,
14
+ syncStateStore,
15
+ type JobRecord,
16
+ type SyncCoverage,
17
+ type SyncState,
18
+ type SyncStateStore,
19
+ } from './syncState.js'
20
+
21
+ /** A window wider than this is worth warning about: the read is not bounded. */
22
+ export const WIDE_WINDOW_SECONDS = 90 * 24 * 3600
23
+
24
+ export class SyncRangeRequiredError extends Error {
25
+ readonly code = 'SYNC_RANGE_REQUIRED'
26
+ constructor() {
27
+ super('首次同步需要 --since <日期> 或 --full')
28
+ this.name = 'SyncRangeRequiredError'
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Stable identity for one message.
34
+ *
35
+ * `serverId` wins when nonzero; otherwise `localId` is paired with
36
+ * `createTime`. A bare `localId` is never an identity - it restarts in every
37
+ * shard, which is the whole reason D-014 exists.
38
+ *
39
+ * `shard` is intentionally absent: messages do not carry it, adding one would
40
+ * touch the fenced export contract, and overlap dedup does not need it (the
41
+ * same message read twice yields the same serverId or the same pair).
42
+ */
43
+ export function messageIdentity(source: string, talker: string, message: Message): string {
44
+ const serverId = String(message.serverId ?? '').trim()
45
+ if (serverId && serverId !== '0') return `${source}|${talker}|s:${serverId}`
46
+ return `${source}|${talker}|l:${message.localId}|t:${message.createTime}`
47
+ }
48
+
49
+ export interface WindowOptions {
50
+ since?: number
51
+ full?: boolean
52
+ overlapSeconds?: number
53
+ now?: number
54
+ }
55
+
56
+ export interface SyncWindow {
57
+ from: number | null
58
+ to: number
59
+ overlapSeconds: number
60
+ full: boolean
61
+ }
62
+
63
+ /**
64
+ * Work out what to read.
65
+ *
66
+ * Without a prior checkpoint there is nothing to resume from, so the caller
67
+ * must say how far back to go - guessing "everything" would silently turn a
68
+ * routine sync into a full-history read.
69
+ */
70
+ export function computeWindow(prior: SyncState | null, options: WindowOptions): SyncWindow {
71
+ const overlapSeconds = options.overlapSeconds ?? prior?.checkpoint.overlapSeconds
72
+ ?? DEFAULT_OVERLAP_SECONDS
73
+ const to = options.now ?? Math.floor(Date.now() / 1000)
74
+
75
+ if (options.full) {
76
+ return { from: null, to, overlapSeconds, full: true }
77
+ }
78
+ if (options.since !== undefined) {
79
+ return { from: options.since, to, overlapSeconds, full: false }
80
+ }
81
+ const newest = prior?.checkpoint.newestCreateTime
82
+ if (prior && typeof newest === 'number') {
83
+ // Back up by the overlap: a second-resolution timestamp is not a cursor,
84
+ // so the boundary messages have to be read again and deduplicated.
85
+ return { from: Math.max(0, newest - overlapSeconds), to, overlapSeconds, full: false }
86
+ }
87
+ throw new SyncRangeRequiredError()
88
+ }
89
+
90
+ /** Drop repeats the overlap window re-read. */
91
+ export function dedupeMessages(
92
+ messages: Message[], source: string, talker: string,
93
+ ): { unique: Message[]; duplicateCount: number } {
94
+ const seen = new Set<string>()
95
+ const unique: Message[] = []
96
+ for (const message of messages) {
97
+ const identity = messageIdentity(source, talker, message)
98
+ if (seen.has(identity)) continue
99
+ seen.add(identity)
100
+ unique.push(message)
101
+ }
102
+ return { unique, duplicateCount: messages.length - unique.length }
103
+ }
104
+
105
+ /**
106
+ * Decide how much of the read we can stand behind.
107
+ *
108
+ * `partial` is the only value that must not be reported as success.
109
+ *
110
+ * A short-page truncation cannot occur here because this pass reads in one
111
+ * call rather than paging; `collectMessagesInRangeDetailed` detects that case
112
+ * for the paged readers and is where a future revision of this should look.
113
+ */
114
+ export function deriveCoverage(input: {
115
+ shards?: ShardReport
116
+ mayHaveMore: boolean
117
+ }): SyncCoverage {
118
+ if (input.mayHaveMore) return 'partial'
119
+ // A shard that faulted *after* opening means its rows are only partly read.
120
+ const readFailed = input.shards?.items.some(item => item.reason === 'READ_FAILED')
121
+ if (readFailed) return 'partial'
122
+ if (!input.shards) return 'unverified'
123
+ // A shard that never opened is not knowable either way; say so rather than
124
+ // claiming completeness or declaring failure.
125
+ if (input.shards.failed > 0) return 'unverified'
126
+ return 'complete'
127
+ }
128
+
129
+ export function buildNextState(input: {
130
+ prior: SyncState | null
131
+ talker: string
132
+ scope: string
133
+ source: string
134
+ window: SyncWindow
135
+ recordsRead: number
136
+ recordsDeduplicated: number
137
+ recordsReturned: number
138
+ newestCreateTime: number | null
139
+ oldestCreateTime: number | null
140
+ shards?: ShardReport
141
+ coverage: SyncCoverage
142
+ mayHaveMore: boolean
143
+ warnings: string[]
144
+ now?: number
145
+ }): SyncState {
146
+ const state = input.prior ?? emptySyncState(input.talker, input.scope, input.source,
147
+ input.window.overlapSeconds)
148
+ // Same form as coveredFrom/coveredTo: an offset, not a bare Z. A file that
149
+ // mixes the two makes "which local day was this?" unanswerable.
150
+ const stamp = isoFromSeconds(input.now ?? Math.floor(Date.now() / 1000))
151
+
152
+ const priorFrom = state.coveredFrom
153
+ let coveredFrom: string | null = priorFrom
154
+ if (input.window.full) {
155
+ // The database's true minimum is not knowable without another query, so
156
+ // this is the oldest row we actually saw and says so in `warnings`.
157
+ coveredFrom = input.oldestCreateTime ? isoFromSeconds(input.oldestCreateTime) : priorFrom
158
+ } else if (input.window.from !== null) {
159
+ const candidate = isoFromSeconds(input.window.from)
160
+ coveredFrom = priorFrom && priorFrom < candidate ? priorFrom : candidate
161
+ }
162
+
163
+ return {
164
+ ...state,
165
+ scope: input.scope,
166
+ talker: input.talker,
167
+ source: input.source,
168
+ coveredFrom,
169
+ coveredTo: isoFromSeconds(input.window.to),
170
+ checkpoint: {
171
+ newestCreateTime: input.newestCreateTime ?? state.checkpoint.newestCreateTime,
172
+ overlapSeconds: input.window.overlapSeconds,
173
+ },
174
+ recordsRead: input.recordsRead,
175
+ recordsDeduplicated: input.recordsDeduplicated,
176
+ recordsReturned: input.recordsReturned,
177
+ shardsRead: input.shards?.opened ?? 0,
178
+ shardsFailed: input.shards?.failed ?? 0,
179
+ shards: input.shards
180
+ ? { scanned: input.shards.scanned, opened: input.shards.opened,
181
+ failed: input.shards.failed, items: input.shards.items }
182
+ : { scanned: 0, opened: 0, failed: 0, items: [] },
183
+ coverage: input.coverage,
184
+ mayHaveMore: input.mayHaveMore,
185
+ warnings: input.warnings,
186
+ // The attempt always advances; the success does not, so a partial run is
187
+ // never mistaken for a good one later.
188
+ lastAttempt: stamp,
189
+ lastSuccessfulRun: input.coverage === 'partial' ? state.lastSuccessfulRun : stamp,
190
+ updatedAt: stamp,
191
+ }
192
+ }
193
+
194
+ function isoFromSeconds(seconds: number): string {
195
+ const date = new Date(seconds * 1000)
196
+ const offsetMinutes = -date.getTimezoneOffset()
197
+ const sign = offsetMinutes >= 0 ? '+' : '-'
198
+ const pad = (value: number) => String(Math.floor(Math.abs(value))).padStart(2, '0')
199
+ const local = new Date(date.getTime() + offsetMinutes * 60_000)
200
+ const body = local.toISOString().slice(0, 19)
201
+ return `${body}${sign}${pad(offsetMinutes / 60)}:${pad(offsetMinutes % 60)}`
202
+ }
203
+
204
+ export interface SyncRunOptions extends WindowOptions {
205
+ source?: string
206
+ scope?: string
207
+ limit?: number
208
+ /** Injected for tests; the CLI wires this to chatService. */
209
+ read: (talker: string, limit: number) => Promise<{ messages: Message[]; shards?: ShardReport }>
210
+ write?: boolean
211
+ /** Defaults to the real store; tests pass one rooted in a temp directory. */
212
+ store?: SyncStateStore
213
+ }
214
+
215
+ export interface SyncRunResult {
216
+ success: boolean
217
+ code?: string
218
+ action: 'sync.messages'
219
+ scope: string
220
+ window: SyncWindow
221
+ recordsRead: number
222
+ recordsDeduplicated: number
223
+ recordsReturned: number
224
+ shards?: ShardReport
225
+ coverage: SyncCoverage
226
+ mayHaveMore: boolean
227
+ partial: boolean
228
+ warnings: string[]
229
+ jobId: string | null
230
+ state: SyncState | null
231
+ }
232
+
233
+ /**
234
+ * Run one pass. Writes state and a job record unless `write: false`.
235
+ *
236
+ * A partial run still writes (the spec forbids discarding usable results) but
237
+ * returns `success: false` with `code: 'SYNC_PARTIAL'` so nothing downstream
238
+ * treats it as complete.
239
+ */
240
+ export async function runSync(talker: string, options: SyncRunOptions): Promise<SyncRunResult> {
241
+ const source = options.source ?? SYNC_SOURCE
242
+ const scope = options.scope ?? talker
243
+ const store = options.store ?? syncStateStore
244
+ const prior = store.read(source, talker)
245
+ const window = computeWindow(prior, options)
246
+
247
+ const warnings: string[] = []
248
+ if (window.full) warnings.push('full-scan')
249
+ if (window.from !== null && window.to - window.from > WIDE_WINDOW_SECONDS) {
250
+ warnings.push('wide-window')
251
+ }
252
+
253
+ const limit = options.limit ?? 0
254
+ const read = await options.read(talker, limit)
255
+ const { unique, duplicateCount } = dedupeMessages(read.messages, source, talker)
256
+
257
+ // Without a native range pushdown the read is the whole conversation, so the
258
+ // window is applied here. This is why the sync is correct but not cheap yet.
259
+ const inWindow = window.from === null
260
+ ? unique
261
+ : unique.filter(m => Number(m.createTime) >= (window.from as number))
262
+
263
+ const newestCreateTime = inWindow.length
264
+ ? Math.max(...inWindow.map(m => Number(m.createTime) || 0))
265
+ : null
266
+ const oldestCreateTime = inWindow.length
267
+ ? Math.min(...inWindow.map(m => Number(m.createTime) || 0))
268
+ : null
269
+
270
+ const mayHaveMore = limit > 0 && read.messages.length >= limit
271
+ const coverage = deriveCoverage({ shards: read.shards, mayHaveMore })
272
+ if (!read.shards) warnings.push('shard-report-unavailable')
273
+ if (read.shards && read.shards.failed > 0) {
274
+ for (const item of read.shards.items) {
275
+ if (!item.opened) warnings.push(`shard-unverified:${item.name}`)
276
+ else if (item.reason === 'READ_FAILED') warnings.push(`shard-read-failed:${item.name}`)
277
+ }
278
+ }
279
+
280
+ const next = buildNextState({
281
+ prior, talker, scope, source, window,
282
+ recordsRead: read.messages.length,
283
+ recordsDeduplicated: duplicateCount,
284
+ recordsReturned: inWindow.length,
285
+ newestCreateTime, oldestCreateTime,
286
+ shards: read.shards, coverage, mayHaveMore, warnings,
287
+ // Same clock as the window: without this the recorded attempt would come
288
+ // from Date.now() while window.to came from the caller's `now`.
289
+ now: options.now,
290
+ })
291
+
292
+ const partial = coverage === 'partial'
293
+ let jobId: string | null = null
294
+ if (options.write !== false) {
295
+ jobId = makeJobId()
296
+ const job: JobRecord = {
297
+ schema: 'weflow-job/v1',
298
+ jobId,
299
+ kind: 'sync.messages',
300
+ state: partial ? 'partial' : 'completed',
301
+ createdAt: next.lastAttempt as string,
302
+ updatedAt: next.lastAttempt as string,
303
+ window: { from: window.from, to: window.to },
304
+ progress: { completed: inWindow.length, total: read.messages.length },
305
+ resumeable: partial,
306
+ result: {
307
+ records: inWindow.length,
308
+ recordsDeduplicated: duplicateCount,
309
+ shardsFailed: read.shards?.failed ?? 0,
310
+ coverage,
311
+ },
312
+ error: partial ? 'SYNC_PARTIAL' : null,
313
+ }
314
+ store.write(next)
315
+ store.writeJob(job)
316
+ }
317
+
318
+ return {
319
+ success: !partial,
320
+ code: partial ? 'SYNC_PARTIAL' : undefined,
321
+ action: 'sync.messages',
322
+ scope,
323
+ window,
324
+ recordsRead: read.messages.length,
325
+ recordsDeduplicated: duplicateCount,
326
+ recordsReturned: inWindow.length,
327
+ shards: read.shards,
328
+ coverage,
329
+ mayHaveMore,
330
+ partial,
331
+ warnings,
332
+ jobId,
333
+ state: next,
334
+ }
335
+ }
@@ -0,0 +1,275 @@
1
+ /**
2
+ * 同步检查点与任务记录的本地状态。
3
+ *
4
+ * 两个位置, 生命周期不同 (见 docs/SYNC_CONTRACT.md):
5
+ * ~/.weflow-cli/sync/<source>-<name>-<hash>.json 跨运行的检查点, 每会话一份
6
+ * ~/.weflow-cli/jobs/<jobId>.json 单次运行的记录
7
+ *
8
+ * 按会话分文件而不是一个全局文件: 全局文件要求跨会话读改写并合并, 分文件则每次
9
+ * 写入都是整文件原子替换 (沿用 assistantMemory.ts 的 tmp + rename 做法)。
10
+ *
11
+ * 两条本模块特有的规矩:
12
+ * - 遇到不认识的 schema 一律拒绝覆盖并报错, 不猜测字段含义;
13
+ * - 写盘前统一过一遍脱敏, 保证密钥/绝对路径不会进状态文件 (D-001 / D-002 / D-025)。
14
+ */
15
+ import { createHash } from 'crypto'
16
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'fs'
17
+ import { join } from 'path'
18
+ import os from 'os'
19
+
20
+ export const SYNC_SCHEMA = 'weflow-sync/v1'
21
+ export const JOB_SCHEMA = 'weflow-job/v1'
22
+ export const SYNC_SOURCE = 'wechat-nt'
23
+ export const DEFAULT_OVERLAP_SECONDS = 300
24
+
25
+ /** 单次运行的结局。partial 是本项目新增的一档——部分完成不算成功。 */
26
+ export type JobState = 'planned' | 'waiting_confirmation' | 'running' | 'paused'
27
+ | 'completed' | 'partial' | 'failed' | 'cancelled'
28
+
29
+ /**
30
+ * 覆盖可信度。这是对「有没有读全」的正面回答, 不是内部细节。
31
+ *
32
+ * - complete 扫到的分片全部打开、打开的全读成功, 且没有更多
33
+ * - unverified 有分片打不开, 但打开的都读成功——已读部分可信, 未打开的分片内容无法判断
34
+ * - partial 已打开的分片读失败, 或还有更多, 或分页提前结束
35
+ */
36
+ export type SyncCoverage = 'complete' | 'unverified' | 'partial'
37
+
38
+ export interface SyncShardItem {
39
+ /** 仅 basename——绝不落绝对路径 */
40
+ name: string
41
+ opened: boolean
42
+ hasTalkerTable: boolean | null
43
+ rowsForTalker: number | null
44
+ /** null | KEY_REJECTED | OPEN_FAILED | READ_FAILED */
45
+ reason: string | null
46
+ }
47
+
48
+ export interface SyncState {
49
+ schema: string
50
+ schemaVersion: number
51
+ source: string
52
+ scope: string
53
+ talker: string
54
+ lastSuccessfulRun: string | null
55
+ lastAttempt: string | null
56
+ coveredFrom: string | null
57
+ coveredTo: string | null
58
+ checkpoint: { newestCreateTime: number | null; overlapSeconds: number }
59
+ recordsRead: number
60
+ recordsDeduplicated: number
61
+ recordsReturned: number
62
+ shardsRead: number
63
+ shardsFailed: number
64
+ shards: { scanned: number; opened: number; failed: number; items: SyncShardItem[] }
65
+ coverage: SyncCoverage
66
+ mayHaveMore: boolean
67
+ warnings: string[]
68
+ updatedAt: string | null
69
+ }
70
+
71
+ export interface JobRecord {
72
+ schema: string
73
+ jobId: string
74
+ kind: string
75
+ state: JobState
76
+ createdAt: string
77
+ updatedAt: string
78
+ window: { from: number | null; to: number | null } | null
79
+ progress: { completed: number; total: number } | null
80
+ resumeable: boolean
81
+ result: Record<string, unknown> | null
82
+ error: string | null
83
+ }
84
+
85
+ /** 未知 schema 时不覆盖原文件, 交由调用方决定如何处理。 */
86
+ export class UnknownSchemaError extends Error {
87
+ constructor(public readonly path: string, public readonly found: unknown) {
88
+ super(`不认识的 schema: ${String(found)} (${path})`)
89
+ this.name = 'UnknownSchemaError'
90
+ }
91
+ }
92
+
93
+ const CONFIG_DIR = join(os.homedir(), '.weflow-cli')
94
+ const SYNC_DIR = join(CONFIG_DIR, 'sync')
95
+ const JOBS_DIR = join(CONFIG_DIR, 'jobs')
96
+
97
+ const FORBIDDEN_KEYS = /^(ntKey|ntSalt|decryptKey|favKey|favPassphrase|contactKey|snsKey|wechatOcToken|apiKey|password|auth)$/i
98
+ /** 密钥形状的十六进制串 (>=32 hex)。 */
99
+ const HEX_KEY = /\b[0-9a-f]{32,}\b/gi
100
+ /** Windows 盘符、UNC、以及 POSIX 绝对路径。三类都要, 早期只处理了第一类。 */
101
+ const ABS_PATH = /(?:[A-Za-z]:[\\/][^\s"']*|\\\\[^\s"']+|\/(?:Users|home|root|var|tmp|opt|mnt)\/[^\s"']*)/g
102
+
103
+ /**
104
+ * 递归剔除不该落盘的字段。
105
+ *
106
+ * 状态文件是本机产物, 但一旦被日志、issue 或截图带出去就是泄露, 所以在写入
107
+ * 这一层兜底, 而不是指望每个调用方都记得。
108
+ */
109
+ export function sanitizeForState(value: unknown): unknown {
110
+ if (typeof value === 'string') {
111
+ return value.replace(HEX_KEY, '<redacted>').replace(ABS_PATH, '<path>')
112
+ }
113
+ if (Array.isArray(value)) return value.map(sanitizeForState)
114
+ if (value && typeof value === 'object') {
115
+ const out: Record<string, unknown> = {}
116
+ for (const [key, item] of Object.entries(value)) {
117
+ if (FORBIDDEN_KEYS.test(key)) continue
118
+ out[key] = sanitizeForState(item)
119
+ }
120
+ return out
121
+ }
122
+ return value
123
+ }
124
+
125
+ /**
126
+ * 文件名里只放一个可读前缀和一个 hash。
127
+ *
128
+ * hash 后缀让 `wxid_a@chatroom` 与 `wxid_a_chatroom` 落到不同文件, 而显示名
129
+ * 不会出现在目录列表里。
130
+ */
131
+ export function talkerSlug(talker: string): string {
132
+ const readable = talker.replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 60)
133
+ const digest = createHash('sha256').update(talker).digest('hex').slice(0, 8)
134
+ return `${readable}-${digest}`
135
+ }
136
+
137
+ function writeAtomic(path: string, payload: unknown): void {
138
+ if (!existsSync(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true })
139
+ const tmp = `${path}.tmp`
140
+ writeFileSync(tmp, JSON.stringify(payload, null, 2), 'utf8')
141
+ renameSync(tmp, path)
142
+ }
143
+
144
+ function readJson(path: string): unknown {
145
+ try {
146
+ return JSON.parse(readFileSync(path, 'utf8'))
147
+ } catch {
148
+ return null
149
+ }
150
+ }
151
+
152
+ export function emptySyncState(
153
+ talker: string,
154
+ scope = talker,
155
+ source = SYNC_SOURCE,
156
+ overlapSeconds = DEFAULT_OVERLAP_SECONDS,
157
+ ): SyncState {
158
+ return {
159
+ schema: SYNC_SCHEMA,
160
+ schemaVersion: 1,
161
+ source,
162
+ scope,
163
+ talker,
164
+ lastSuccessfulRun: null,
165
+ lastAttempt: null,
166
+ coveredFrom: null,
167
+ coveredTo: null,
168
+ checkpoint: { newestCreateTime: null, overlapSeconds },
169
+ recordsRead: 0,
170
+ recordsDeduplicated: 0,
171
+ recordsReturned: 0,
172
+ shardsRead: 0,
173
+ shardsFailed: 0,
174
+ shards: { scanned: 0, opened: 0, failed: 0, items: [] },
175
+ coverage: 'unverified',
176
+ mayHaveMore: false,
177
+ warnings: [],
178
+ updatedAt: null,
179
+ }
180
+ }
181
+
182
+ export class SyncStateStore {
183
+ constructor(
184
+ private readonly syncDir: string = SYNC_DIR,
185
+ private readonly jobsDir: string = JOBS_DIR,
186
+ ) {}
187
+
188
+ statePath(source: string, talker: string): string {
189
+ return join(this.syncDir, `${source}-${talkerSlug(talker)}.json`)
190
+ }
191
+
192
+ /** 读取检查点。无记录返回 null; schema 不认识则抛错, 不猜测。 */
193
+ read(source: string, talker: string): SyncState | null {
194
+ const path = this.statePath(source, talker)
195
+ const raw = readJson(path)
196
+ if (raw === null) return null
197
+ const state = raw as SyncState
198
+ if (state.schema !== SYNC_SCHEMA) throw new UnknownSchemaError(path, state.schema)
199
+ return state
200
+ }
201
+
202
+ write(state: SyncState): void {
203
+ const path = this.statePath(state.source, state.talker)
204
+ if (!existsSync(this.syncDir)) mkdirSync(this.syncDir, { recursive: true })
205
+ writeAtomic(path, sanitizeForState({ ...state, schema: SYNC_SCHEMA }))
206
+ }
207
+
208
+ /** 所有会话的检查点, 最近尝试在前。目录缺失或单个文件损坏都不影响其余。 */
209
+ list(): SyncState[] {
210
+ try {
211
+ if (!existsSync(this.syncDir)) return []
212
+ const states: SyncState[] = []
213
+ for (const name of readdirSync(this.syncDir)) {
214
+ if (!name.endsWith('.json')) continue
215
+ const raw = readJson(join(this.syncDir, name))
216
+ if (!raw || (raw as SyncState).schema !== SYNC_SCHEMA) continue
217
+ states.push(raw as SyncState)
218
+ }
219
+ return states.sort((a, b) => String(b.lastAttempt ?? '').localeCompare(String(a.lastAttempt ?? '')))
220
+ } catch {
221
+ return []
222
+ }
223
+ }
224
+
225
+ jobPath(jobId: string): string {
226
+ return join(this.jobsDir, `${jobId}.json`)
227
+ }
228
+
229
+ writeJob(job: JobRecord): void {
230
+ if (!existsSync(this.jobsDir)) mkdirSync(this.jobsDir, { recursive: true })
231
+ writeAtomic(this.jobPath(job.jobId), sanitizeForState({ ...job, schema: JOB_SCHEMA }))
232
+ }
233
+
234
+ readJob(jobId: string): JobRecord | null {
235
+ const path = this.jobPath(jobId)
236
+ const raw = readJson(path)
237
+ if (raw === null) return null
238
+ const job = raw as JobRecord
239
+ if (job.schema !== JOB_SCHEMA) throw new UnknownSchemaError(path, job.schema)
240
+ return job
241
+ }
242
+
243
+ /** 最近的 job 记录, 最新在前。 */
244
+ recentJobs(limit = 10): JobRecord[] {
245
+ try {
246
+ if (!existsSync(this.jobsDir)) return []
247
+ const ids = readdirSync(this.jobsDir)
248
+ .filter(name => name.endsWith('.json'))
249
+ .map(name => name.slice(0, -'.json'.length))
250
+ .sort()
251
+ .reverse()
252
+ .slice(0, limit)
253
+ const jobs: JobRecord[] = []
254
+ for (const id of ids) {
255
+ const job = this.readJob(id)
256
+ if (job) jobs.push(job)
257
+ }
258
+ return jobs
259
+ } catch {
260
+ return []
261
+ }
262
+ }
263
+ }
264
+
265
+ export const syncStateStore = new SyncStateStore()
266
+
267
+ /** jobId 形如 job_20260919_0001。同日按时间戳后四位递增, 保证可排序。 */
268
+ export function makeJobId(now = new Date()): string {
269
+ const stamp = [
270
+ now.getFullYear(),
271
+ String(now.getMonth() + 1).padStart(2, '0'),
272
+ String(now.getDate()).padStart(2, '0'),
273
+ ].join('')
274
+ return `job_${stamp}_${String(now.getTime() % 10000).padStart(4, '0')}`
275
+ }