weflow-cli 1.15.1 → 1.17.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 (100) hide show
  1. package/CHANGELOG.md +59 -1
  2. package/OPERATIONS.md +16 -1
  3. package/README.en.md +21 -2
  4. package/README.md +34 -6
  5. package/bin/weflow-cli.ts +389 -6
  6. package/dist/bin/weflow-cli.js +422 -8
  7. package/dist/bin/weflow-cli.js.map +1 -1
  8. package/dist/src/core/ntCore.d.ts +47 -0
  9. package/dist/src/core/ntCore.d.ts.map +1 -1
  10. package/dist/src/core/ntCore.js +24 -0
  11. package/dist/src/core/ntCore.js.map +1 -1
  12. package/dist/src/services/assistantService.d.ts +8 -1
  13. package/dist/src/services/assistantService.d.ts.map +1 -1
  14. package/dist/src/services/assistantService.js +47 -8
  15. package/dist/src/services/assistantService.js.map +1 -1
  16. package/dist/src/services/assistantTools.d.ts +8 -0
  17. package/dist/src/services/assistantTools.d.ts.map +1 -1
  18. package/dist/src/services/assistantTools.js +67 -11
  19. package/dist/src/services/assistantTools.js.map +1 -1
  20. package/dist/src/services/configService.d.ts.map +1 -1
  21. package/dist/src/services/configService.js +3 -2
  22. package/dist/src/services/configService.js.map +1 -1
  23. package/dist/src/services/cursorProbe.d.ts +44 -0
  24. package/dist/src/services/cursorProbe.d.ts.map +1 -0
  25. package/dist/src/services/cursorProbe.js +183 -0
  26. package/dist/src/services/cursorProbe.js.map +1 -0
  27. package/dist/src/services/qchatImport.d.ts +89 -0
  28. package/dist/src/services/qchatImport.d.ts.map +1 -0
  29. package/dist/src/services/qchatImport.js +273 -0
  30. package/dist/src/services/qchatImport.js.map +1 -0
  31. package/dist/src/services/setupVenv.d.ts +43 -0
  32. package/dist/src/services/setupVenv.d.ts.map +1 -0
  33. package/dist/src/services/setupVenv.js +198 -0
  34. package/dist/src/services/setupVenv.js.map +1 -0
  35. package/dist/src/utils/python.d.ts +10 -0
  36. package/dist/src/utils/python.d.ts.map +1 -1
  37. package/dist/src/utils/python.js +27 -4
  38. package/dist/src/utils/python.js.map +1 -1
  39. package/docs/DATA_CONTRACT.md +25 -0
  40. package/docs/DECISIONS.md +92 -30
  41. package/docs/FUNCTIONAL-IMPROVEMENT-SPEC.md +365 -365
  42. package/docs/HEALTH-CHECK.md +104 -104
  43. package/docs/JEV/345/272/224/347/224/250/346/226/275/345/267/245/346/226/207/346/241/243.md +310 -310
  44. package/docs/NEXT_ACTIONS.md +236 -236
  45. package/docs/NPM-PUBLISH.md +130 -130
  46. package/docs/POSITIONING.md +68 -68
  47. package/docs/PROJECT_STATE.md +6 -3
  48. package/docs/REPLAY.md +169 -0
  49. package/docs/SYNC_CONTRACT.md +197 -180
  50. package/package.json +89 -88
  51. package/requirements-3x.txt +4 -4
  52. package/requirements-voice.txt +15 -15
  53. package/resources/js/graph3d/NOTICE.txt +35 -35
  54. package/resources/js/graph3d/d3-binarytree.min.js +2 -2
  55. package/resources/js/graph3d/d3-dispatch.min.js +2 -2
  56. package/resources/js/graph3d/d3-force-3d.min.js +2 -2
  57. package/resources/js/graph3d/d3-octree.min.js +2 -2
  58. package/resources/js/graph3d/d3-quadtree.min.js +2 -2
  59. package/resources/js/graph3d/d3-timer.min.js +2 -2
  60. package/resources/js/graph3d/three.min.js +6 -6
  61. package/resources/js/graph3d/viewer2d.js +550 -448
  62. package/resources/panel/quick-menu.cjs +197 -197
  63. package/scripts/_utils.py +1338 -1338
  64. package/scripts/article_notes.py +423 -423
  65. package/scripts/bonds.py +11 -0
  66. package/scripts/chat_notes.py +86 -3
  67. package/scripts/check_readme_commands.py +427 -426
  68. package/scripts/contact_schema.py +339 -339
  69. package/scripts/create_reading_notes.py +11 -11
  70. package/scripts/daily_task.ps1 +213 -177
  71. package/scripts/fav_notes.py +321 -321
  72. package/scripts/graph_2d.py +156 -151
  73. package/scripts/graph_3d.py +672 -646
  74. package/scripts/health_check.py +473 -473
  75. package/scripts/imported_chats.py +68 -0
  76. package/scripts/install_tasks.ps1 +105 -91
  77. package/scripts/leads.py +179 -0
  78. package/scripts/network.py +206 -206
  79. package/scripts/nt_decrypt.py +135 -1
  80. package/scripts/on_this_day.py +178 -178
  81. package/scripts/opinion_timeline.py +138 -138
  82. package/scripts/promises.py +185 -185
  83. package/scripts/replay.py +803 -0
  84. package/scripts/run_hidden.vbs +25 -0
  85. package/scripts/semantic_search.py +73 -5
  86. package/scripts/user_notes.py +315 -315
  87. package/scripts/voice_transcribe.py +139 -139
  88. package/scripts/watch_issues.py +212 -212
  89. package/scripts/watch_mail.py +131 -131
  90. package/src/core/ntCore.ts +59 -0
  91. package/src/services/assistantService.ts +48 -8
  92. package/src/services/assistantTools.ts +73 -10
  93. package/src/services/configService.ts +3 -2
  94. package/src/services/cursorProbe.ts +222 -0
  95. package/src/services/qchatImport.ts +327 -0
  96. package/src/services/setupVenv.ts +238 -0
  97. package/src/services/syncService.ts +363 -363
  98. package/src/services/syncState.ts +275 -275
  99. package/src/services/wechatMedia.ts +166 -166
  100. package/src/utils/python.ts +33 -4
@@ -1,275 +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
- }
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
+ }