dsh-selection-annotations 0.0.0-stage → 2.1.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 (46) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/LICENSE +21 -0
  3. package/README.md +161 -3
  4. package/README.zh-CN.md +161 -0
  5. package/client.js +11136 -0
  6. package/cordis.patch.yml +3 -0
  7. package/icon.svg +7 -0
  8. package/lib/annotations-db.js +1157 -0
  9. package/lib/index.js +1304 -0
  10. package/package.json +74 -6
  11. package/scripts/build.mjs +37 -0
  12. package/scripts/check-build.mjs +10 -0
  13. package/src/core/annotation-clipboard.js +93 -0
  14. package/src/core/annotation-utils.js +27 -0
  15. package/src/core/cards.js +502 -0
  16. package/src/core/config.js +91 -0
  17. package/src/core/constants.js +34 -0
  18. package/src/core/draft-codec.js +77 -0
  19. package/src/core/draft-store.js +85 -0
  20. package/src/core/hidden-payload.js +73 -0
  21. package/src/core/image-codec.js +111 -0
  22. package/src/core/jump-icon.js +25 -0
  23. package/src/core/locale.js +59 -0
  24. package/src/core/log.js +19 -0
  25. package/src/core/markdown.js +80 -0
  26. package/src/core/messages.js +311 -0
  27. package/src/core/note-tone.js +77 -0
  28. package/src/core/panel-render.js +315 -0
  29. package/src/core/payload.js +191 -0
  30. package/src/core/preview-bridge.js +216 -0
  31. package/src/core/remote-sync.js +206 -0
  32. package/src/core/scroll-trace.js +177 -0
  33. package/src/core/sent-store.js +148 -0
  34. package/src/core/session.js +60 -0
  35. package/src/core/settings.js +168 -0
  36. package/src/core/side-tab-state.js +30 -0
  37. package/src/core/source-capture.js +530 -0
  38. package/src/core/source-locate.js +220 -0
  39. package/src/core/source-resolve.js +89 -0
  40. package/src/core/styles.js +590 -0
  41. package/src/core/turn-anchor.js +54 -0
  42. package/src/core/util.js +55 -0
  43. package/src/core/uuid.js +23 -0
  44. package/src/core/web-picker.js +426 -0
  45. package/src/entry.js +22 -0
  46. package/src/plugin.js +8706 -0
@@ -0,0 +1,1157 @@
1
+ /**
2
+ * 批注台账的 SQLite 存储(宿主半边)。
3
+ *
4
+ * 替换原先「一个会话一个 JSON 文件、整份读改写」的落盘方式:
5
+ * 数据库固定在 `$DSH_HOME/selection-annotations/annotations.db`,与老台账目录
6
+ * (`selection-annotations/sessions/`)同级。老 JSON 文件不删,迁移后留作回退。
7
+ *
8
+ * 三个层次:
9
+ * sessions 每个会话一行,记最后更新时间、迁移来源、宿主写入的 rewind 标记;
10
+ * batches 与会话日志里的「已发送批注」一一对应,排序看 `batch_seq`(会话内单调递增);
11
+ * entries 批里的一条批注,答复(verdict/reason/next/replied_at)直接存在这一行上。
12
+ *
13
+ * 所有方法都是同步的:`node:sqlite` 的 DatabaseSync 不返回 Promise,Node 又是单线程,
14
+ * 所以同一进程内不存在并发读写;每个写操作各自包在一个事务里。
15
+ */
16
+ import { randomUUID } from 'node:crypto'
17
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
+ import { join } from 'node:path'
20
+ import { DatabaseSync } from 'node:sqlite'
21
+
22
+ /** 老接口的 `schemaVersion`:存储换了,对外形状不变。 */
23
+ const SNAPSHOT_SCHEMA_VERSION = 1
24
+
25
+ /** 与宿主旧实现一致:逐条答复最多保留 200 批(这里按 replied_at 分组)。 */
26
+ const MAX_REPLY_GROUPS = 200
27
+
28
+ /** 合法答复类型;工具与 HTTP 两条入口共用。 */
29
+ export const REPLY_VERDICTS = ['accepted', 'partial', 'rejected', 'needs_info']
30
+
31
+ const SCHEMA_SQL = `
32
+ CREATE TABLE IF NOT EXISTS sessions (
33
+ session_id TEXT PRIMARY KEY,
34
+ updated_at INTEGER NOT NULL,
35
+ migrated_from TEXT,
36
+ rewind_json TEXT
37
+ );
38
+ CREATE TABLE IF NOT EXISTS batches (
39
+ batch_uuid TEXT PRIMARY KEY,
40
+ session_id TEXT NOT NULL,
41
+ turn INTEGER,
42
+ batch_seq INTEGER NOT NULL,
43
+ batch_at INTEGER NOT NULL,
44
+ anchor_key TEXT,
45
+ value_anchor_key TEXT,
46
+ created_at INTEGER NOT NULL
47
+ );
48
+ CREATE TABLE IF NOT EXISTS entries (
49
+ uuid TEXT PRIMARY KEY,
50
+ batch_uuid TEXT NOT NULL,
51
+ session_id TEXT NOT NULL,
52
+ index_in_batch INTEGER NOT NULL,
53
+ quote TEXT,
54
+ note TEXT,
55
+ source_json TEXT,
56
+ images_json TEXT,
57
+ verdict TEXT,
58
+ reason TEXT,
59
+ next TEXT,
60
+ replied_at INTEGER,
61
+ replied_session_id TEXT
62
+ );
63
+ CREATE TABLE IF NOT EXISTS drafts (
64
+ session_id TEXT PRIMARY KEY,
65
+ draft_json TEXT NOT NULL,
66
+ updated_at INTEGER NOT NULL
67
+ );
68
+ CREATE INDEX IF NOT EXISTS idx_entries_session_batch ON entries (session_id, batch_uuid);
69
+ CREATE INDEX IF NOT EXISTS idx_entries_session_replied ON entries (session_id, replied_at);
70
+ CREATE INDEX IF NOT EXISTS idx_batches_session_seq ON batches (session_id, batch_seq);
71
+ CREATE INDEX IF NOT EXISTS idx_batches_uuid ON batches (batch_uuid);
72
+ `
73
+
74
+ /** 记录根目录:与 DSH 的会话目录平级,一个插件一个目录。 */
75
+ function annotationHome() {
76
+ const home = process.env.DSH_HOME
77
+ const base = typeof home === 'string' && home !== '' ? home : join(homedir(), '.dsh')
78
+ return join(base, 'selection-annotations')
79
+ }
80
+
81
+ /** 老 JSON 台账目录(只读:迁移时从这里导入)。 */
82
+ export function legacySessionsDir() {
83
+ return join(annotationHome(), 'sessions')
84
+ }
85
+
86
+ /** 默认数据库文件路径。 */
87
+ export function defaultDbFile() {
88
+ return join(annotationHome(), 'annotations.db')
89
+ }
90
+
91
+ /** 滚动追踪日志:人类事后直接读的明文文件。 */
92
+ export function scrollTraceFile() {
93
+ return join(annotationHome(), 'scroll-trace.log')
94
+ }
95
+
96
+ /**
97
+ * 建一个存储实例。默认位置取 `$DSH_HOME`;手工冒烟时传 `root` 指到临时目录即可。
98
+ */
99
+ export function createAnnotationsDb(options = {}) {
100
+ return new AnnotationsDb(options)
101
+ }
102
+
103
+ export class AnnotationsDb {
104
+ #db = null
105
+
106
+ constructor({ root, file, sessionsDir } = {}) {
107
+ const home = typeof root === 'string' && root !== '' ? root : annotationHome()
108
+ this.root = home
109
+ this.file = typeof file === 'string' && file !== '' ? file : join(home, 'annotations.db')
110
+ this.sessionsDir = typeof sessionsDir === 'string' && sessionsDir !== '' ? sessionsDir : join(home, 'sessions')
111
+ this.migrationErrors = new Map()
112
+ }
113
+
114
+ /** 懒开库:模块被 import 时不创建目录、不碰磁盘。 */
115
+ get db() {
116
+ if (this.#db !== null) return this.#db
117
+ mkdirSync(this.root, { recursive: true })
118
+ const db = new DatabaseSync(this.file)
119
+ // 先设 PRAGMA 再建表:WAL 让读写互不阻塞,busy_timeout 给其它进程留 3 秒。
120
+ db.prepare('PRAGMA journal_mode = WAL').get()
121
+ db.exec('PRAGMA busy_timeout = 3000')
122
+ db.exec(SCHEMA_SQL)
123
+ // 老库补列:entries.replied_session_id 记录「这条批注被哪个会话答复」。
124
+ // CREATE TABLE IF NOT EXISTS 不会给已存在的表加列,所以这里单独查一次再 ALTER。
125
+ const entryColumns = db.prepare('PRAGMA table_info(entries)').all()
126
+ if (!entryColumns.some((column) => column.name === 'replied_session_id')) {
127
+ db.exec('ALTER TABLE entries ADD COLUMN replied_session_id TEXT')
128
+ }
129
+ this.#db = db
130
+ return db
131
+ }
132
+
133
+ close() {
134
+ if (this.#db === null) return
135
+ try {
136
+ this.#db.close()
137
+ } finally {
138
+ this.#db = null
139
+ }
140
+ }
141
+
142
+ /* ------------------------------------------------------------ 对外读取 */
143
+
144
+ /**
145
+ * 按老 JSON 形状读一个会话。库里没有这个会话(且没有可迁移的老文件)时返回 undefined,
146
+ * 路由据此回 204 —— 与「文件不存在」时的旧行为一致。
147
+ */
148
+ readSession(sessionId) {
149
+ this.#ensureMigrated(sessionId)
150
+ const db = this.db
151
+ const session = db.prepare('SELECT updated_at, rewind_json FROM sessions WHERE session_id = ?').get(sessionId)
152
+ if (session === undefined) return undefined
153
+
154
+ const rewind = parseJsonText(session.rewind_json)
155
+ return {
156
+ schemaVersion: SNAPSHOT_SCHEMA_VERSION,
157
+ sessionId,
158
+ updatedAt: toIso(session.updated_at),
159
+ drafts: this.#readDrafts(sessionId),
160
+ sent: this.#readSent(sessionId),
161
+ replies: this.#readReplies(sessionId),
162
+ ...(isPlainObject(rewind) ? { rewind } : {}),
163
+ }
164
+ }
165
+
166
+ /** 宿主写入的 rewind 标记;没有就返回 undefined。 */
167
+ readRewind(sessionId) {
168
+ this.#ensureMigrated(sessionId)
169
+ const row = this.db.prepare('SELECT rewind_json FROM sessions WHERE session_id = ?').get(sessionId)
170
+ const rewind = parseJsonText(row?.rewind_json)
171
+ return isPlainObject(rewind) ? rewind : undefined
172
+ }
173
+
174
+ #readDrafts(sessionId) {
175
+ const row = this.db.prepare('SELECT draft_json FROM drafts WHERE session_id = ?').get(sessionId)
176
+ const drafts = parseJsonText(row?.draft_json)
177
+ return Array.isArray(drafts) ? drafts : []
178
+ }
179
+
180
+ #readSent(sessionId) {
181
+ const db = this.db
182
+ const batches = db
183
+ .prepare(
184
+ 'SELECT batch_uuid, batch_seq, batch_at, turn, anchor_key, value_anchor_key FROM batches WHERE session_id = ? ORDER BY batch_seq ASC',
185
+ )
186
+ .all(sessionId)
187
+ if (batches.length === 0) return {}
188
+
189
+ const entries = db
190
+ .prepare(
191
+ 'SELECT uuid, batch_uuid, index_in_batch, quote, note, source_json, images_json FROM entries WHERE session_id = ? ORDER BY batch_uuid ASC, index_in_batch ASC',
192
+ )
193
+ .all(sessionId)
194
+ const byBatch = new Map()
195
+ for (const entry of entries) {
196
+ let list = byBatch.get(entry.batch_uuid)
197
+ if (list === undefined) {
198
+ list = []
199
+ byBatch.set(entry.batch_uuid, list)
200
+ }
201
+ list.push(entry)
202
+ }
203
+
204
+ const sent = {}
205
+ for (const batch of batches) {
206
+ const items = []
207
+ for (const entry of byBatch.get(batch.batch_uuid) ?? []) {
208
+ items.push(entryToItem(entry))
209
+ }
210
+ const record = { savedAt: Number(batch.batch_at), items }
211
+ if (batch.turn !== null && Number.isFinite(Number(batch.turn))) record.turn = Number(batch.turn)
212
+ const anchorKey = batch.value_anchor_key ?? batch.anchor_key
213
+ if (typeof anchorKey === 'string' && anchorKey !== '') record.anchorKey = anchorKey
214
+ const key = typeof batch.anchor_key === 'string' && batch.anchor_key !== '' ? batch.anchor_key : `time:${batch.batch_at}`
215
+ sent[key] = record
216
+ }
217
+ return sent
218
+ }
219
+
220
+ #readReplies(sessionId) {
221
+ // 跨会话答复:条目属于别的会话、但在当前会话被答复过时,当前会话也要读得到,
222
+ // 否则页面换到答复所在的会话就看不到那张答复卡。
223
+ const rows = this.db
224
+ .prepare(
225
+ 'SELECT uuid, index_in_batch, quote, note, verdict, reason, next, replied_at FROM entries WHERE (session_id = ? OR replied_session_id = ?) AND replied_at IS NOT NULL ORDER BY replied_at ASC, index_in_batch ASC',
226
+ )
227
+ .all(sessionId, sessionId)
228
+ if (rows.length === 0) return []
229
+
230
+ const groups = new Map()
231
+ for (const row of rows) {
232
+ const at = Number(row.replied_at)
233
+ let group = groups.get(at)
234
+ if (group === undefined) {
235
+ group = { at, replies: [], accepted: 0, partial: 0, rejected: 0, needsInfo: 0 }
236
+ groups.set(at, group)
237
+ }
238
+ const reply = { uuid: row.uuid, index: Number(row.index_in_batch), verdict: row.verdict }
239
+ if (row.quote !== null) reply.quote = row.quote
240
+ if (row.note !== null) reply.note = row.note
241
+ if (row.reason !== null) reply.reason = row.reason
242
+ if (row.next !== null) reply.next = row.next
243
+ group.replies.push(reply)
244
+ if (row.verdict === 'accepted') group.accepted += 1
245
+ else if (row.verdict === 'partial') group.partial += 1
246
+ else if (row.verdict === 'rejected') group.rejected += 1
247
+ else if (row.verdict === 'needs_info') group.needsInfo += 1
248
+ }
249
+ const list = [...groups.values()]
250
+ return list.slice(Math.max(0, list.length - MAX_REPLY_GROUPS))
251
+ }
252
+
253
+ /* ------------------------------------------------------------ 写入:老快照 */
254
+
255
+ /**
256
+ * 老接口 `PUT /session/<id>` 的整份快照落库。
257
+ *
258
+ * 合并规则与旧文件实现一致:`sent` 只增不减,`replies` 按 `at` 去重后并入,`drafts` 以客户端为准,
259
+ * `rewind` 保留宿主那一份。
260
+ * 客户端曾在快照里附带 `sentRemoved`(回退时要删的台账键),这份清单现在一律忽略:
261
+ * 它由客户端的本地判据算出,一次误判就会让宿主按清单把整会话的批注连条目一起真删,
262
+ * 已经因此丢过四个会话的批注。快照通道只合并、不删除;删数据只能走 deleteEntry(单条、带显式确认)。
263
+ * 已存在的 batch 只更新真正变化的行,重复推送同一份快照不会重写整批。
264
+ */
265
+ saveSession(sessionId, parsed) {
266
+ this.#ensureMigrated(sessionId)
267
+ const db = this.db
268
+ return this.#tx(() => {
269
+ const now = Date.now()
270
+ const updatedAt = parseIsoMs(parsed.updatedAt) ?? now
271
+ const existing = db.prepare('SELECT updated_at FROM sessions WHERE session_id = ?').get(sessionId)
272
+ if (existing === undefined) {
273
+ db.prepare('INSERT INTO sessions (session_id, updated_at, migrated_from, rewind_json) VALUES (?, ?, NULL, NULL)').run(
274
+ sessionId,
275
+ updatedAt,
276
+ )
277
+ } else if (Number(existing.updated_at) !== updatedAt) {
278
+ db.prepare('UPDATE sessions SET updated_at = ? WHERE session_id = ?').run(updatedAt, sessionId)
279
+ }
280
+
281
+ if (Array.isArray(parsed.drafts)) this.#writeDrafts(sessionId, parsed.drafts, updatedAt)
282
+ if (isPlainObject(parsed.sent)) {
283
+ // 旧客户端还会照常推 sentRemoved:这里只留痕不执行,方便日后从日志认出仍在用删除通道的版本。
284
+ if (Array.isArray(parsed.sentRemoved) && parsed.sentRemoved.length > 0) {
285
+ console.warn(
286
+ `[selection-annotations] 忽略客户端推来的 sentRemoved(${parsed.sentRemoved.length} 项,会话 ${sessionId}):快照通道不再删除条目`,
287
+ )
288
+ }
289
+ this.#applySentSnapshot(sessionId, parsed.sent, updatedAt)
290
+ }
291
+ if (Array.isArray(parsed.replies)) this.#applyReplySnapshot(sessionId, parsed.replies)
292
+ })
293
+ }
294
+
295
+ #writeDrafts(sessionId, drafts, updatedAt) {
296
+ const text = safeStringify(drafts)
297
+ if (text === null) return
298
+ const row = this.db.prepare('SELECT draft_json FROM drafts WHERE session_id = ?').get(sessionId)
299
+ if (row === undefined) {
300
+ this.db
301
+ .prepare('INSERT INTO drafts (session_id, draft_json, updated_at) VALUES (?, ?, ?)')
302
+ .run(sessionId, text, updatedAt)
303
+ return
304
+ }
305
+ if (row.draft_json === text) return
306
+ this.db.prepare('UPDATE drafts SET draft_json = ?, updated_at = ? WHERE session_id = ?').run(text, updatedAt, sessionId)
307
+ }
308
+
309
+ #applySentSnapshot(sessionId, sent, fallbackAt) {
310
+ const db = this.db
311
+ const oldBatches = db.prepare('SELECT * FROM batches WHERE session_id = ? ORDER BY batch_seq ASC').all(sessionId)
312
+ const byKey = new Map()
313
+ let maxSeq = 0
314
+ for (const batch of oldBatches) {
315
+ // 没有 anchor_key 的批次在快照里以 `time:<batch_at>` 为键,这里用同一个派生键
316
+ // 对齐,避免整份快照重复插一批。
317
+ const key =
318
+ typeof batch.anchor_key === 'string' && batch.anchor_key !== ''
319
+ ? batch.anchor_key
320
+ : `time:${batch.batch_at}`
321
+ byKey.set(key, batch)
322
+ maxSeq = Math.max(maxSeq, Number(batch.batch_seq))
323
+ }
324
+
325
+ // 新键按 savedAt 升序编号;已存在的键只更新内容,不动 batch_seq。
326
+ const incomingKeys = Object.keys(sent).filter((key) => isPlainObject(sent[key]))
327
+ const freshKeys = incomingKeys
328
+ .filter((key) => !byKey.has(key))
329
+ .sort((a, b) => numberOr(sent[a]?.savedAt, 0) - numberOr(sent[b]?.savedAt, 0))
330
+
331
+ for (const key of incomingKeys) {
332
+ const value = sent[key]
333
+ const batchAt = numberOr(value.savedAt, fallbackAt)
334
+ const turn = Number.isSafeInteger(value.turn) ? Number(value.turn) : null
335
+ const valueAnchorKey = typeof value.anchorKey === 'string' && value.anchorKey !== '' ? value.anchorKey : null
336
+ const existing = byKey.get(key)
337
+ if (existing === undefined) continue
338
+
339
+ if (
340
+ Number(existing.batch_at) !== batchAt ||
341
+ (existing.turn === null ? null : Number(existing.turn)) !== turn ||
342
+ (existing.value_anchor_key ?? null) !== valueAnchorKey
343
+ ) {
344
+ db.prepare('UPDATE batches SET batch_at = ?, turn = ?, value_anchor_key = ? WHERE batch_uuid = ?').run(
345
+ batchAt,
346
+ turn,
347
+ valueAnchorKey,
348
+ existing.batch_uuid,
349
+ )
350
+ }
351
+ this.#syncItems(sessionId, existing.batch_uuid, Array.isArray(value.items) ? value.items : [])
352
+ }
353
+
354
+ for (const key of freshKeys) {
355
+ const value = sent[key]
356
+ const batchAt = numberOr(value.savedAt, fallbackAt)
357
+ const turn = Number.isSafeInteger(value.turn) ? Number(value.turn) : null
358
+ const valueAnchorKey = typeof value.anchorKey === 'string' && value.anchorKey !== '' ? value.anchorKey : null
359
+ maxSeq += 1
360
+ const batchUuid = randomUUID()
361
+ db.prepare(
362
+ 'INSERT INTO batches (batch_uuid, session_id, turn, batch_seq, batch_at, anchor_key, value_anchor_key, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
363
+ ).run(batchUuid, sessionId, turn, maxSeq, batchAt, key, valueAnchorKey, Date.now())
364
+ this.#insertItems(sessionId, batchUuid, Array.isArray(value.items) ? value.items : [])
365
+ }
366
+
367
+ // 这里原来按客户端的删除清单批量删 batch 与 entries(sentRemoved 通道)。
368
+ // 那条路径已经撤掉:客户端的回退判据一旦算错,宿主就会把整会话的批注真删,
369
+ // 属于不可恢复的数据丢失。回退现在只在客户端写标记;真删只保留 deleteEntry 这一条单条通道。
370
+ }
371
+
372
+ /**
373
+ * 老快照里同一批的条目按 index_in_batch 对齐:内容变了才写,缺的补,多的删。
374
+ * 已写进去的答复(verdict/reason/next/replied_at)不因客户端重推而丢失。
375
+ */
376
+ #syncItems(sessionId, batchUuid, items) {
377
+ const db = this.db
378
+ const existing = db.prepare('SELECT * FROM entries WHERE session_id = ? AND batch_uuid = ?').all(sessionId, batchUuid)
379
+ const byIndex = new Map()
380
+ for (const entry of existing) byIndex.set(Number(entry.index_in_batch), entry)
381
+
382
+ const seen = new Set()
383
+ items.forEach((item, position) => {
384
+ if (!isPlainObject(item)) return
385
+ const index = Number.isSafeInteger(item.index) ? Number(item.index) : position + 1
386
+ if (seen.has(index)) return
387
+ seen.add(index)
388
+ const fields = itemFields(item)
389
+ const current = byIndex.get(index)
390
+ if (current === undefined) {
391
+ // 快照可能先于 POST batch 到达:条目自带客户端 uuid 时用它,让随后的批次创建
392
+ // 按 uuid 认出同一条,避免重复插入。
393
+ const uuid = typeof item.uuid === 'string' && item.uuid !== '' ? item.uuid : undefined
394
+ this.#insertItem(sessionId, batchUuid, index, fields, uuid)
395
+ return
396
+ }
397
+ if (
398
+ current.quote !== fields.quote ||
399
+ current.note !== fields.note ||
400
+ current.source_json !== fields.sourceJson ||
401
+ current.images_json !== fields.imagesJson
402
+ ) {
403
+ db.prepare('UPDATE entries SET quote = ?, note = ?, source_json = ?, images_json = ? WHERE uuid = ?').run(
404
+ fields.quote,
405
+ fields.note,
406
+ fields.sourceJson,
407
+ fields.imagesJson,
408
+ current.uuid,
409
+ )
410
+ }
411
+ })
412
+
413
+ for (const [index, entry] of byIndex) {
414
+ if (seen.has(index)) continue
415
+ db.prepare('DELETE FROM entries WHERE uuid = ?').run(entry.uuid)
416
+ }
417
+ }
418
+
419
+ /**
420
+ * 老快照里的 `replies` 数组:每批 `at` 对应「该时刻之前最近的一个 batch」,
421
+ * 按 index_in_batch 写到对应条目上。匹配不到就跳过,不报错。
422
+ * 只往后写:客户端推回来的旧答复批次不会覆盖时间更晚的那次答复。
423
+ */
424
+ #applyReplySnapshot(sessionId, batches) {
425
+ const db = this.db
426
+ for (const batch of batches) {
427
+ if (!isPlainObject(batch)) continue
428
+ const at = Number(batch.at)
429
+ if (!Number.isFinite(at)) continue
430
+ const already = db
431
+ .prepare('SELECT 1 AS hit FROM entries WHERE session_id = ? AND replied_at = ? LIMIT 1')
432
+ .get(sessionId, at)
433
+ if (already !== undefined) continue
434
+ const target = db
435
+ .prepare(
436
+ 'SELECT batch_uuid FROM batches WHERE session_id = ? AND batch_at <= ? ORDER BY batch_seq DESC LIMIT 1',
437
+ )
438
+ .get(sessionId, at)
439
+ if (target === undefined) continue
440
+ const replies = Array.isArray(batch.replies) ? batch.replies : []
441
+ for (const reply of replies) {
442
+ if (!isPlainObject(reply)) continue
443
+ this.#applyLegacyReply(target.batch_uuid, reply, at)
444
+ }
445
+ }
446
+ }
447
+
448
+ /** 把一条老形状答复写到目标批的对应条目上;已有更晚的答复时不覆盖。 */
449
+ #applyLegacyReply(batchUuid, reply, at) {
450
+ const index = Number(reply.index)
451
+ if (!Number.isSafeInteger(index)) return false
452
+ const entry = this.db
453
+ .prepare('SELECT uuid, replied_at FROM entries WHERE batch_uuid = ? AND index_in_batch = ? LIMIT 1')
454
+ .get(batchUuid, index)
455
+ if (entry === undefined) return false
456
+ if (entry.replied_at !== null && Number(entry.replied_at) >= at) return false
457
+ this.db
458
+ .prepare('UPDATE entries SET verdict = ?, reason = ?, next = ?, replied_at = ? WHERE uuid = ?')
459
+ .run(stringOrNull(reply.verdict), stringOrNull(reply.reason), stringOrNull(reply.next), at, entry.uuid)
460
+ return true
461
+ }
462
+
463
+ /* ------------------------------------------------------------ 写入:按条 */
464
+
465
+ /**
466
+ * 新建一批批注(`POST /session/<id>/batch`)。
467
+ * `batch_seq` 取该会话当前最大值 +1;条目以客户端捕获时生成的 uuid 为主键。
468
+ * 客户端带了 `batchUuid`(发送时生成)时以它为准:同一 uuid 重复提交走
469
+ * `#mergeBatch` 的幂等路径,不新建批次、不动已写答复,只补缺的条目与空字段。
470
+ * 老客户端没带批次 uuid 时,整批都已落在同一批里仍直接返回原批,不再插空卡。
471
+ */
472
+ createBatch(sessionId, { turn, anchorKey, batchAt, items, batchUuid }) {
473
+ this.#ensureMigrated(sessionId)
474
+ const db = this.db
475
+ return this.#tx(() => {
476
+ const now = Date.now()
477
+ const updatedAt = Number.isFinite(batchAt) ? batchAt : now
478
+ this.#ensureSessionRow(sessionId, now)
479
+
480
+ // 先按请求顺序整理;同一次请求里出现重复 uuid 时只留第一条。
481
+ const requested = []
482
+ const seen = new Set()
483
+ for (const item of Array.isArray(items) ? items : []) {
484
+ if (!isPlainObject(item)) continue
485
+ const uuid = typeof item.uuid === 'string' && item.uuid !== '' ? item.uuid : undefined
486
+ if (uuid !== undefined) {
487
+ if (seen.has(uuid)) continue
488
+ seen.add(uuid)
489
+ }
490
+ requested.push({ item, uuid })
491
+ }
492
+
493
+ // 客户端发送时生成的批次 uuid 是这一批的权威键:同一批被重提时走幂等合并,
494
+ // 绝不能新建第二条 batches 行(答复会留在旧行上,界面上看着像被抹掉了)。
495
+ const clientBatchUuid = typeof batchUuid === 'string' && batchUuid !== '' ? batchUuid : undefined
496
+ if (clientBatchUuid !== undefined) {
497
+ const existingBatch = db
498
+ .prepare(
499
+ 'SELECT batch_uuid, batch_seq, session_id, turn, anchor_key, value_anchor_key FROM batches WHERE batch_uuid = ?',
500
+ )
501
+ .get(clientBatchUuid)
502
+ if (existingBatch !== undefined && existingBatch.session_id === sessionId) {
503
+ const merged = this.#mergeBatch(sessionId, existingBatch, { turn, anchorKey, items: requested })
504
+ if (merged.changed) {
505
+ db.prepare('UPDATE sessions SET updated_at = ? WHERE session_id = ?').run(now, sessionId)
506
+ }
507
+ return {
508
+ batch_uuid: existingBatch.batch_uuid,
509
+ batch_seq: Number(existingBatch.batch_seq),
510
+ items: merged.items,
511
+ }
512
+ }
513
+ // 同一个 uuid 已落在别的会话(正常不会发生):退回随机 uuid 新建,避免主键冲突。
514
+ }
515
+
516
+ const existing = requested
517
+ .filter((entry) => entry.uuid !== undefined)
518
+ .map((entry) => ({
519
+ uuid: entry.uuid,
520
+ row: db.prepare('SELECT batch_uuid, session_id FROM entries WHERE uuid = ?').get(entry.uuid),
521
+ }))
522
+ const existingRows = existing.filter((entry) => entry.row !== undefined)
523
+ if (
524
+ requested.length > 0 &&
525
+ existingRows.length === requested.length &&
526
+ existingRows.every((entry) => entry.row.batch_uuid === existingRows[0].row.batch_uuid) &&
527
+ existingRows[0].row.session_id === sessionId
528
+ ) {
529
+ const batch = db
530
+ .prepare('SELECT batch_uuid, batch_seq FROM batches WHERE batch_uuid = ?')
531
+ .get(existingRows[0].row.batch_uuid)
532
+ if (batch !== undefined) {
533
+ return {
534
+ batch_uuid: batch.batch_uuid,
535
+ batch_seq: Number(batch.batch_seq),
536
+ items: requested.map((entry) => ({ uuid: entry.uuid })),
537
+ reused: true,
538
+ }
539
+ }
540
+ }
541
+
542
+ const maxSeq = Number(
543
+ db.prepare('SELECT COALESCE(MAX(batch_seq), 0) AS seq FROM batches WHERE session_id = ?').get(sessionId).seq,
544
+ )
545
+ const batchSeq = maxSeq + 1
546
+ // 客户端给了批次 uuid 就直接拿它当主键;它已被别人占用时退回随机 uuid。
547
+ const newBatchUuid =
548
+ clientBatchUuid !== undefined &&
549
+ db.prepare('SELECT 1 AS ok FROM batches WHERE batch_uuid = ?').get(clientBatchUuid) === undefined
550
+ ? clientBatchUuid
551
+ : randomUUID()
552
+ const safeTurn = Number.isSafeInteger(turn) ? Number(turn) : null
553
+ const anchor = typeof anchorKey === 'string' && anchorKey !== '' ? anchorKey : null
554
+ // turn 与 anchor_key 允许留空,等消息真正入库后再走 patchBatch 回填。
555
+ db.prepare(
556
+ 'INSERT INTO batches (batch_uuid, session_id, turn, batch_seq, batch_at, anchor_key, value_anchor_key, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
557
+ ).run(newBatchUuid, sessionId, safeTurn, batchSeq, updatedAt, anchor, anchor, now)
558
+
559
+ const inserted = []
560
+ requested.forEach((entry, position) => {
561
+ const index = Number.isSafeInteger(entry.item.index) ? Number(entry.item.index) : position + 1
562
+ const uuid = this.#insertItem(sessionId, newBatchUuid, index, itemFields(entry.item), entry.uuid)
563
+ if (uuid !== undefined) inserted.push({ uuid })
564
+ })
565
+
566
+ db.prepare('UPDATE sessions SET updated_at = ? WHERE session_id = ?').run(now, sessionId)
567
+ return { batch_uuid: newBatchUuid, batch_seq: batchSeq, items: inserted }
568
+ })
569
+ }
570
+
571
+ /**
572
+ * 同一 `batch_uuid` 被重复提交时并入原批:不删行、不改 `batch_seq`、不碰任何条目的
573
+ * verdict / reason / next / replied_at。
574
+ *
575
+ * 幂等键:批次按 `batch_uuid`;条目先按客户端 `uuid` 认,uuid 对不上(客户端重建过、
576
+ * 或旧版宿主生成过另一套编号)就退回「同批内的 index_in_batch」。命中的行一律沿用
577
+ * 库里的 uuid,请求里的新编号不会写进去,所以同一条批注不会出现两个编号。
578
+ * 已存在的条目只把空的 quote / note / source_json / images_json 补上;
579
+ * `turn` 与 `anchor_key` 也只在原值为空(含 `time:` / `turn:` 派生占位键)时写入。
580
+ */
581
+ #mergeBatch(sessionId, batch, { turn, anchorKey, items }) {
582
+ const db = this.db
583
+ const existing = db.prepare('SELECT * FROM entries WHERE batch_uuid = ?').all(batch.batch_uuid)
584
+ const byUuid = new Map()
585
+ const byIndex = new Map()
586
+ for (const entry of existing) {
587
+ byUuid.set(entry.uuid, entry)
588
+ byIndex.set(Number(entry.index_in_batch), entry)
589
+ }
590
+
591
+ // 结果按请求顺序排:客户端靠这个顺序把宿主 uuid 对回本地卡片。
592
+ const resultItems = new Array(items.length)
593
+ const pending = []
594
+ let changed = false
595
+
596
+ items.forEach((entry, position) => {
597
+ const index = Number.isSafeInteger(entry.item.index) ? Number(entry.item.index) : position + 1
598
+ // 先按请求 uuid 认本批已有行;uuid 对不上(客户端重建过、或旧版宿主生成过另一套编号)
599
+ // 时退回同批的 index_in_batch。命中哪一行就沿用哪一行的 uuid,绝不把请求里的新编号写回去。
600
+ const current = (entry.uuid !== undefined ? byUuid.get(entry.uuid) : undefined) ?? byIndex.get(index)
601
+ if (current === undefined) {
602
+ pending.push({ item: entry.item, index, uuid: entry.uuid, position })
603
+ return
604
+ }
605
+ const fields = itemFields(entry.item)
606
+ // 这一批还没挂到任何消息上(turn 为空)时算「在途」:内容以最新一次提交为准,
607
+ // 否则发送前改过的批注正文会留在库里的是旧版本。挂上消息(turn 有值)之后只补空值。
608
+ const inflight = batch.turn === null || batch.turn === undefined
609
+ const pick = (current, incoming) =>
610
+ inflight && !isEmptyValue(incoming) ? incoming : isEmptyValue(current) ? incoming : current
611
+ const next = {
612
+ quote: pick(current.quote, fields.quote),
613
+ note: pick(current.note, fields.note),
614
+ sourceJson: pick(current.source_json, fields.sourceJson),
615
+ imagesJson: pick(current.images_json, fields.imagesJson),
616
+ }
617
+ if (
618
+ next.quote !== current.quote ||
619
+ next.note !== current.note ||
620
+ next.sourceJson !== current.source_json ||
621
+ next.imagesJson !== current.images_json
622
+ ) {
623
+ db.prepare('UPDATE entries SET quote = ?, note = ?, source_json = ?, images_json = ? WHERE uuid = ?').run(
624
+ next.quote,
625
+ next.note,
626
+ next.sourceJson,
627
+ next.imagesJson,
628
+ current.uuid,
629
+ )
630
+ changed = true
631
+ }
632
+ resultItems[position] = { uuid: current.uuid }
633
+ })
634
+
635
+ for (const entry of pending) {
636
+ const uuid = this.#insertItem(sessionId, batch.batch_uuid, entry.index, itemFields(entry.item), entry.uuid)
637
+ if (uuid === undefined) continue
638
+ resultItems[entry.position] = { uuid }
639
+ changed = true
640
+ }
641
+
642
+ const nextTurn = batch.turn === null ? (Number.isSafeInteger(turn) ? Number(turn) : null) : Number(batch.turn)
643
+ const anchor = typeof anchorKey === 'string' && anchorKey !== '' ? anchorKey : null
644
+ const anchorEmpty =
645
+ batch.anchor_key === null ||
646
+ batch.anchor_key === '' ||
647
+ String(batch.anchor_key).startsWith('time:') ||
648
+ String(batch.anchor_key).startsWith('turn:')
649
+ const nextAnchor = anchorEmpty && anchor !== null ? anchor : batch.anchor_key
650
+ // 与 patchBatch 一致:value_anchor_key 也只补空,已有真实锚点不覆盖。
651
+ const nextValueAnchor =
652
+ batch.value_anchor_key === null || batch.value_anchor_key === ''
653
+ ? anchor !== null
654
+ ? anchor
655
+ : null
656
+ : batch.value_anchor_key
657
+ if (nextTurn !== batch.turn || nextAnchor !== batch.anchor_key || nextValueAnchor !== batch.value_anchor_key) {
658
+ db.prepare('UPDATE batches SET turn = ?, anchor_key = ?, value_anchor_key = ? WHERE batch_uuid = ?').run(
659
+ nextTurn,
660
+ nextAnchor,
661
+ nextValueAnchor,
662
+ batch.batch_uuid,
663
+ )
664
+ changed = true
665
+ }
666
+
667
+ return { items: resultItems, changed }
668
+ }
669
+
670
+ /**
671
+ * 回填批次里「消息真正入库后」才确定的字段(`PATCH /batch/<batch_uuid>`)。
672
+ * turn 与 anchor_key 只补空值:重复调用不会改已写入的值(幂等,只写一次)。
673
+ */
674
+ patchBatch(batchUuid, { turn, anchorKey } = {}) {
675
+ const db = this.db
676
+ return this.#tx(() => {
677
+ const row = db
678
+ .prepare('SELECT turn, anchor_key, value_anchor_key FROM batches WHERE batch_uuid = ?')
679
+ .get(batchUuid)
680
+ if (row === undefined) return { status: 'not_found' }
681
+ const nextTurn = Number.isSafeInteger(turn) ? Number(turn) : null
682
+ const anchor = typeof anchorKey === 'string' && anchorKey !== '' ? anchorKey : null
683
+ const turnValue = row.turn === null ? nextTurn : Number(row.turn)
684
+ // 创建时可能只留下了 `time:<batch_at>` / `turn:<n>` 派生键;真实锚点到了就换掉。
685
+ const anchorEmpty =
686
+ row.anchor_key === null ||
687
+ row.anchor_key === '' ||
688
+ String(row.anchor_key).startsWith('time:') ||
689
+ String(row.anchor_key).startsWith('turn:')
690
+ const anchorValue = anchorEmpty && anchor !== null ? anchor : row.anchor_key
691
+ const valueAnchorValue =
692
+ row.value_anchor_key === null || row.value_anchor_key === ''
693
+ ? anchor !== null
694
+ ? anchor
695
+ : null
696
+ : row.value_anchor_key
697
+ if (turnValue !== row.turn || anchorValue !== row.anchor_key || valueAnchorValue !== row.value_anchor_key) {
698
+ db.prepare('UPDATE batches SET turn = ?, anchor_key = ?, value_anchor_key = ? WHERE batch_uuid = ?').run(
699
+ turnValue,
700
+ anchorValue,
701
+ valueAnchorValue,
702
+ batchUuid,
703
+ )
704
+ }
705
+ return { status: 'ok', batch_uuid: batchUuid, turn: turnValue, anchor_key: anchorValue }
706
+ })
707
+ }
708
+
709
+ /**
710
+ * 给一条批注写答复(`PATCH /entry/<uuid>`)。
711
+ * 不校验条目属于哪个会话:uuid 是全局唯一键,跨会话也能答复。
712
+ * `repliedSessionId` 记下「在哪个会话答复的」,供那个会话读回答复卡。
713
+ * 返回 { status: 'ok' | 'not_found' | 'conflict' },由路由映射成 200/404/409。
714
+ */
715
+ patchEntry(uuid, { verdict, reason, next, repliedSessionId }) {
716
+ const db = this.db
717
+ return this.#tx(() => {
718
+ const now = Date.now()
719
+ const row = db.prepare('SELECT session_id, replied_at FROM entries WHERE uuid = ?').get(uuid)
720
+ if (row === undefined) return { status: 'not_found' }
721
+ if (row.replied_at !== null) return { status: 'conflict' }
722
+ const replySession =
723
+ typeof repliedSessionId === 'string' && repliedSessionId !== '' ? repliedSessionId : null
724
+ db.prepare(
725
+ 'UPDATE entries SET verdict = ?, reason = ?, next = ?, replied_at = ?, replied_session_id = ? WHERE uuid = ?',
726
+ ).run(verdict, reason, stringOrNull(next), now, replySession, uuid)
727
+ db.prepare('UPDATE sessions SET updated_at = ? WHERE session_id = ?').run(now, row.session_id)
728
+ if (replySession !== null && replySession !== row.session_id) {
729
+ db.prepare('UPDATE sessions SET updated_at = ? WHERE session_id = ?').run(now, replySession)
730
+ }
731
+ return { status: 'ok', replied_at: now, replied_session_id: replySession }
732
+ })
733
+ }
734
+
735
+ /** 删一条批注(`DELETE /entry/<uuid>`);返回是否删到。 */
736
+ deleteEntry(uuid) {
737
+ const db = this.db
738
+ return this.#tx(() => {
739
+ const row = db.prepare('SELECT session_id FROM entries WHERE uuid = ?').get(uuid)
740
+ if (row === undefined) return false
741
+ db.prepare('DELETE FROM entries WHERE uuid = ?').run(uuid)
742
+ db.prepare('UPDATE sessions SET updated_at = ? WHERE session_id = ?').run(Date.now(), row.session_id)
743
+ return true
744
+ })
745
+ }
746
+
747
+ /* ------------------------------------------------------------ 写入:答复 */
748
+
749
+ /**
750
+ * 按条目 uuid 写答复。给「跨会话写入」预留的内部函数:它能写任意会话里的条目,
751
+ * 并记下答复发生在哪个会话。
752
+ */
753
+ writeReplyByUuid(uuid, { verdict, reason, next, repliedSessionId }) {
754
+ const db = this.db
755
+ return this.#tx(() => {
756
+ const now = Date.now()
757
+ const row = db.prepare('SELECT session_id FROM entries WHERE uuid = ?').get(uuid)
758
+ if (row === undefined) return false
759
+ const replySession =
760
+ typeof repliedSessionId === 'string' && repliedSessionId !== '' ? repliedSessionId : null
761
+ db.prepare(
762
+ 'UPDATE entries SET verdict = ?, reason = ?, next = ?, replied_at = ?, replied_session_id = ? WHERE uuid = ?',
763
+ ).run(verdict, reason, stringOrNull(next), now, replySession, uuid)
764
+ db.prepare('UPDATE sessions SET updated_at = ? WHERE session_id = ?').run(now, row.session_id)
765
+ return true
766
+ })
767
+ }
768
+
769
+ /**
770
+ * `annotation_replies` 工具的落库:逐条答复,uuid 是唯一定位依据。
771
+ *
772
+ * uuid 属于别的会话也照写(跨会话答复),并把答复会话记到 `replied_session_id`。
773
+ * 没有 uuid 时退回老行为:cardKey 命中某批的锚点就用那批,否则用会话里最近的一批,
774
+ * 再按 index 匹配批内条目。返回真实写入与跳过的明细,回执按它报数。
775
+ */
776
+ writeReplyBatch(sessionId, value) {
777
+ this.#ensureMigrated(sessionId)
778
+ const db = this.db
779
+ const replies = Array.isArray(value?.replies) ? value.replies : []
780
+ if (replies.length === 0) return { written: [], skipped: [], relocated: [] }
781
+ // 宿主在 pre-step 把数据块交给模型时记下的「uuid → 引文」。条目编号对不上库里的行时,
782
+ // 只有引文还能证明模型指的是哪一条;调用方不提供就退化为普通的编号不存在。
783
+ const quoteByUuid = isPlainObject(value?.quotes) ? value.quotes : undefined
784
+ return this.#tx(() => {
785
+ const now = Date.now()
786
+ // 替别的会话的批注写答复时,调用会话本身可能还没有台账行;先建一行,
787
+ // 这样它读回时能看到「在我这里答复过」的那些条目。
788
+ this.#ensureSessionRow(sessionId, now)
789
+ const written = []
790
+ const skipped = []
791
+ // 编号漂移后按引文写进库内另一条:回执要把「旧编号 → 库内编号」说清楚。
792
+ const relocated = []
793
+ const touched = new Set()
794
+
795
+ replies.forEach((reply, position) => {
796
+ const ordinal = position + 1
797
+ if (!isPlainObject(reply)) {
798
+ skipped.push({ position: ordinal, reason: 'invalid_reply' })
799
+ return
800
+ }
801
+ const verdict = stringOrNull(reply.verdict)
802
+ const reason = stringOrNull(reply.reason)
803
+ const next = stringOrNull(reply.next)
804
+ const uuid = typeof reply.uuid === 'string' && reply.uuid !== '' ? reply.uuid : undefined
805
+ if (typeof verdict !== 'string' || !REPLY_VERDICTS.includes(verdict)) {
806
+ skipped.push({ ...(uuid !== undefined ? { uuid } : {}), position: ordinal, reason: 'invalid_reply' })
807
+ return
808
+ }
809
+
810
+ if (uuid !== undefined) {
811
+ const row = db
812
+ .prepare('SELECT uuid, index_in_batch, session_id, replied_at FROM entries WHERE uuid = ?')
813
+ .get(uuid)
814
+ if (row === undefined) {
815
+ // 宽松匹配:同会话、引文完全相等、还没答复。命中一条就归位写入;
816
+ // 命中多条说明光凭引文定不了,宁可跳过也不能猜。
817
+ const quote = quoteByUuid !== undefined && typeof quoteByUuid[uuid] === 'string' ? quoteByUuid[uuid] : undefined
818
+ if (typeof quote === 'string' && quote !== '') {
819
+ const candidates = db
820
+ .prepare(
821
+ 'SELECT uuid, index_in_batch FROM entries WHERE session_id = ? AND quote = ? AND replied_at IS NULL',
822
+ )
823
+ .all(sessionId, quote)
824
+ if (candidates.length === 1) {
825
+ const target = candidates[0]
826
+ db.prepare(
827
+ 'UPDATE entries SET verdict = ?, reason = ?, next = ?, replied_at = ?, replied_session_id = ? WHERE uuid = ?',
828
+ ).run(verdict, reason, next, now, sessionId, target.uuid)
829
+ written.push({ uuid: target.uuid, index: Number(target.index_in_batch), verdict })
830
+ relocated.push({ from: uuid, to: target.uuid })
831
+ touched.add(sessionId)
832
+ return
833
+ }
834
+ if (candidates.length > 1) {
835
+ skipped.push({ uuid, position: ordinal, reason: 'quote_ambiguous', candidates: candidates.length })
836
+ return
837
+ }
838
+ // 引文唯一但已经答复过:报「已答复过」比报「编号不存在」更接近事实。
839
+ const answered = db
840
+ .prepare('SELECT uuid, index_in_batch, replied_at FROM entries WHERE session_id = ? AND quote = ?')
841
+ .all(sessionId, quote)
842
+ if (answered.length === 1 && answered[0].replied_at !== null) {
843
+ skipped.push({ uuid, position: ordinal, index: Number(answered[0].index_in_batch), reason: 'already_replied' })
844
+ return
845
+ }
846
+ }
847
+ skipped.push({ uuid, position: ordinal, reason: 'uuid_not_found' })
848
+ return
849
+ }
850
+ if (row.replied_at !== null) {
851
+ skipped.push({ uuid, position: ordinal, index: Number(row.index_in_batch), reason: 'already_replied' })
852
+ return
853
+ }
854
+ db.prepare(
855
+ 'UPDATE entries SET verdict = ?, reason = ?, next = ?, replied_at = ?, replied_session_id = ? WHERE uuid = ?',
856
+ ).run(verdict, reason, next, now, sessionId, uuid)
857
+ written.push({ uuid, index: Number(row.index_in_batch), verdict })
858
+ touched.add(String(row.session_id))
859
+ return
860
+ }
861
+
862
+ const index = Number(reply.index)
863
+ if (!Number.isSafeInteger(index)) {
864
+ skipped.push({ position: ordinal, reason: 'uuid_required' })
865
+ return
866
+ }
867
+ let target
868
+ if (typeof reply.cardKey === 'string' && reply.cardKey !== '') {
869
+ target = db
870
+ .prepare(
871
+ 'SELECT batch_uuid FROM batches WHERE session_id = ? AND (anchor_key = ? OR value_anchor_key = ?) ORDER BY batch_seq DESC LIMIT 1',
872
+ )
873
+ .get(sessionId, reply.cardKey, reply.cardKey)
874
+ }
875
+ if (target === undefined) {
876
+ target = db
877
+ .prepare('SELECT batch_uuid FROM batches WHERE session_id = ? ORDER BY batch_seq DESC LIMIT 1')
878
+ .get(sessionId)
879
+ }
880
+ if (target === undefined) {
881
+ skipped.push({ index, position: ordinal, reason: 'batch_not_found' })
882
+ return
883
+ }
884
+ const entry = db
885
+ .prepare('SELECT uuid, replied_at FROM entries WHERE batch_uuid = ? AND index_in_batch = ? LIMIT 1')
886
+ .get(target.batch_uuid, index)
887
+ if (entry === undefined) {
888
+ skipped.push({ index, position: ordinal, reason: 'index_not_found' })
889
+ return
890
+ }
891
+ if (entry.replied_at !== null) {
892
+ skipped.push({ uuid: entry.uuid, index, position: ordinal, reason: 'already_replied' })
893
+ return
894
+ }
895
+ db.prepare(
896
+ 'UPDATE entries SET verdict = ?, reason = ?, next = ?, replied_at = ?, replied_session_id = ? WHERE uuid = ?',
897
+ ).run(verdict, reason, next, now, sessionId, entry.uuid)
898
+ written.push({ uuid: entry.uuid, index, verdict })
899
+ touched.add(sessionId)
900
+ })
901
+ if (written.length > 0) {
902
+ const touch = db.prepare('UPDATE sessions SET updated_at = ? WHERE session_id = ?')
903
+ touch.run(now, sessionId)
904
+ for (const id of touched) touch.run(now, id)
905
+ }
906
+ return { written, skipped, relocated }
907
+ })
908
+ }
909
+
910
+ /**
911
+ * 记一次会话回退(dsh-rewind-plugin 触发的撤回)。标记读回时随老形状的 `rewind` 字段返回。
912
+ */
913
+ recordRewind(sessionId, turn) {
914
+ this.#ensureMigrated(sessionId)
915
+ const db = this.db
916
+ return this.#tx(() => {
917
+ const row = db.prepare('SELECT rewind_json FROM sessions WHERE session_id = ?').get(sessionId)
918
+ const previous = parseJsonText(row?.rewind_json)
919
+ const previousAt = Number.isFinite(previous?.at) ? Number(previous.at) : 0
920
+ const mark = { at: Math.max(Date.now(), previousAt + 1), turn: Number.isSafeInteger(turn) ? turn : null }
921
+ if (row === undefined) {
922
+ db.prepare('INSERT INTO sessions (session_id, updated_at, migrated_from, rewind_json) VALUES (?, ?, NULL, ?)').run(
923
+ sessionId,
924
+ Date.now(),
925
+ JSON.stringify(mark),
926
+ )
927
+ } else {
928
+ db.prepare('UPDATE sessions SET rewind_json = ? WHERE session_id = ?').run(JSON.stringify(mark), sessionId)
929
+ }
930
+ return mark
931
+ })
932
+ }
933
+
934
+ /* ------------------------------------------------------------ 迁移 */
935
+
936
+ /** 该会话在库里第一次出现时,把老 JSON 台账导进来;已有 sessions 行就跳过。 */
937
+ #ensureMigrated(sessionId) {
938
+ const db = this.db
939
+ const exists = db.prepare('SELECT 1 AS ok FROM sessions WHERE session_id = ?').get(sessionId)
940
+ if (exists !== undefined) return
941
+ const legacy = join(this.sessionsDir, `${sessionId}.json`)
942
+ if (!existsSync(legacy)) return
943
+
944
+ let parsed
945
+ try {
946
+ parsed = JSON.parse(readFileSync(legacy, 'utf8'))
947
+ } catch (error) {
948
+ // 坏文件不阻塞访问:记一次日志,下次访问再试(不建 sessions 行,保持「未迁移」状态)。
949
+ if (!this.migrationErrors.has(sessionId)) {
950
+ this.migrationErrors.set(sessionId, true)
951
+ console.error('[selection-annotations] 老台账解析失败,暂不迁移:', legacy, error)
952
+ }
953
+ return
954
+ }
955
+ if (!isPlainObject(parsed)) return
956
+ this.#migrate(sessionId, legacy, parsed)
957
+ }
958
+
959
+ #migrate(sessionId, legacyPath, parsed) {
960
+ const db = this.db
961
+ this.#tx(() => {
962
+ const updatedAt = parseIsoMs(parsed.updatedAt) ?? Date.now()
963
+ const rewind = isPlainObject(parsed.rewind) ? JSON.stringify(parsed.rewind) : null
964
+ db.prepare('INSERT INTO sessions (session_id, updated_at, migrated_from, rewind_json) VALUES (?, ?, ?, ?)').run(
965
+ sessionId,
966
+ updatedAt,
967
+ legacyPath,
968
+ rewind,
969
+ )
970
+
971
+ if (Array.isArray(parsed.drafts) && parsed.drafts.length > 0) {
972
+ const text = safeStringify(parsed.drafts)
973
+ if (text !== null) {
974
+ db.prepare('INSERT INTO drafts (session_id, draft_json, updated_at) VALUES (?, ?, ?)').run(
975
+ sessionId,
976
+ text,
977
+ updatedAt,
978
+ )
979
+ }
980
+ }
981
+
982
+ const sent = isPlainObject(parsed.sent) ? parsed.sent : {}
983
+ const keys = Object.keys(sent).filter((key) => isPlainObject(sent[key]))
984
+ // 按 savedAt 升序编号;同一个 savedAt 保持对象里原有顺序(Array.sort 是稳定的)。
985
+ keys.sort((a, b) => numberOr(sent[a].savedAt, 0) - numberOr(sent[b].savedAt, 0))
986
+
987
+ let seq = 0
988
+ for (const key of keys) {
989
+ const value = sent[key]
990
+ seq += 1
991
+ const batchUuid = randomUUID()
992
+ const batchAt = numberOr(value.savedAt, updatedAt)
993
+ const turn = Number.isSafeInteger(value.turn) ? Number(value.turn) : null
994
+ const valueAnchorKey = typeof value.anchorKey === 'string' && value.anchorKey !== '' ? value.anchorKey : null
995
+ db.prepare(
996
+ 'INSERT INTO batches (batch_uuid, session_id, turn, batch_seq, batch_at, anchor_key, value_anchor_key, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
997
+ ).run(batchUuid, sessionId, turn, seq, batchAt, key, valueAnchorKey, Date.now())
998
+ this.#insertItems(sessionId, batchUuid, Array.isArray(value.items) ? value.items : [])
999
+ }
1000
+
1001
+ // 顶层 replies:每批 at → 该时刻之前最近的一个 batch,按 index 落到条目上。
1002
+ const replyBatches = Array.isArray(parsed.replies) ? parsed.replies : []
1003
+ for (const batch of replyBatches) {
1004
+ if (!isPlainObject(batch)) continue
1005
+ const at = Number(batch.at)
1006
+ if (!Number.isFinite(at)) continue
1007
+ const target = db
1008
+ .prepare('SELECT batch_uuid FROM batches WHERE session_id = ? AND batch_at <= ? ORDER BY batch_seq DESC LIMIT 1')
1009
+ .get(sessionId, at)
1010
+ if (target === undefined) continue
1011
+ const replies = Array.isArray(batch.replies) ? batch.replies : []
1012
+ for (const reply of replies) {
1013
+ if (!isPlainObject(reply)) continue
1014
+ this.#applyLegacyReply(target.batch_uuid, reply, at)
1015
+ }
1016
+ }
1017
+ })
1018
+ }
1019
+
1020
+ /* ------------------------------------------------------------ 工具 */
1021
+
1022
+ #ensureSessionRow(sessionId, updatedAt) {
1023
+ const row = this.db.prepare('SELECT 1 AS ok FROM sessions WHERE session_id = ?').get(sessionId)
1024
+ if (row !== undefined) return
1025
+ this.db
1026
+ .prepare('INSERT INTO sessions (session_id, updated_at, migrated_from, rewind_json) VALUES (?, ?, NULL, NULL)')
1027
+ .run(sessionId, updatedAt)
1028
+ }
1029
+
1030
+ #insertItems(sessionId, batchUuid, items) {
1031
+ items.forEach((item, position) => {
1032
+ if (!isPlainObject(item)) return
1033
+ const index = Number.isSafeInteger(item.index) ? Number(item.index) : position + 1
1034
+ // 整份快照里带的条目 uuid 也要沿用:客户端可能先推快照、后补 POST batch,
1035
+ // 两条路必须落到同一个主键上,否则同一条批注会变成两行。
1036
+ const uuid = typeof item.uuid === 'string' && item.uuid !== '' ? item.uuid : undefined
1037
+ this.#insertItem(sessionId, batchUuid, index, itemFields(item), uuid)
1038
+ })
1039
+ }
1040
+
1041
+ #insertItem(sessionId, batchUuid, index, fields, uuid) {
1042
+ const id = typeof uuid === 'string' && uuid !== '' ? uuid : randomUUID()
1043
+ // 幂等:同 uuid 重复提交视为同一条,不重复插入,也不改它原来的批次归属。
1044
+ const exists = this.db.prepare('SELECT 1 AS ok FROM entries WHERE uuid = ?').get(id)
1045
+ if (exists !== undefined) return id
1046
+ this.db
1047
+ .prepare(
1048
+ 'INSERT INTO entries (uuid, batch_uuid, session_id, index_in_batch, quote, note, source_json, images_json, verdict, reason, next, replied_at, replied_session_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL)',
1049
+ )
1050
+ .run(id, batchUuid, sessionId, index, fields.quote, fields.note, fields.sourceJson, fields.imagesJson)
1051
+ return id
1052
+ }
1053
+
1054
+ /** 同步事务:BEGIN IMMEDIATE 立刻拿写锁,避免和其它进程的写互相等成死锁。 */
1055
+ #tx(fn) {
1056
+ const db = this.db
1057
+ db.exec('BEGIN IMMEDIATE')
1058
+ try {
1059
+ const result = fn()
1060
+ db.exec('COMMIT')
1061
+ return result
1062
+ } catch (error) {
1063
+ try {
1064
+ db.exec('ROLLBACK')
1065
+ } catch {
1066
+ /* 回滚失败时保留原始异常 */
1067
+ }
1068
+ throw error
1069
+ }
1070
+ }
1071
+ }
1072
+
1073
+ /* ------------------------------------------------------------ 形状转换 */
1074
+
1075
+ /** 一行 entry 还原成老 `sent[key].items` 里的条目;空 images 不写,避免凭空多出字段。 */
1076
+ function entryToItem(entry) {
1077
+ const item = { uuid: entry.uuid, index: Number(entry.index_in_batch) }
1078
+ if (entry.quote !== null) item.quote = entry.quote
1079
+ if (entry.note !== null) item.note = entry.note
1080
+ const source = parseJsonText(entry.source_json)
1081
+ if (source !== undefined) item.source = source
1082
+ const images = parseJsonText(entry.images_json)
1083
+ if (Array.isArray(images) && images.length > 0) {
1084
+ item.images = images
1085
+ const thumbs = thumbsOf(images)
1086
+ if (thumbs.length > 0) item.thumbs = thumbs
1087
+ }
1088
+ return item
1089
+ }
1090
+
1091
+ /** 与客户端 buildSentCard 的取图逻辑一致:images 里带 data URL 的才还原成缩略图。 */
1092
+ function thumbsOf(images) {
1093
+ const thumbs = []
1094
+ for (const image of images) {
1095
+ if (!isPlainObject(image)) continue
1096
+ if (typeof image.thumb !== 'string' || image.thumb === '') continue
1097
+ const name = typeof image.name === 'string' ? image.name : ''
1098
+ const preview = typeof image.preview === 'string' && image.preview !== '' ? image.preview : image.dataUrl
1099
+ thumbs.push({ name, dataUrl: image.thumb, ...(typeof preview === 'string' ? { preview } : {}) })
1100
+ }
1101
+ return thumbs
1102
+ }
1103
+
1104
+ function itemFields(item) {
1105
+ return {
1106
+ quote: stringOrNull(item.quote),
1107
+ note: stringOrNull(item.note),
1108
+ sourceJson: item.source === undefined ? null : safeStringify(item.source),
1109
+ imagesJson: item.images === undefined ? null : safeStringify(item.images),
1110
+ }
1111
+ }
1112
+
1113
+ function stringOrNull(value) {
1114
+ return typeof value === 'string' ? value : null
1115
+ }
1116
+
1117
+ /** 空值:NULL 或空字符串。重复建批时只回填这些格子,已有内容不动。 */
1118
+ function isEmptyValue(value) {
1119
+ return value === null || value === undefined || value === ''
1120
+ }
1121
+
1122
+ function numberOr(value, fallback) {
1123
+ const number = Number(value)
1124
+ return Number.isFinite(number) ? number : fallback
1125
+ }
1126
+
1127
+ function isPlainObject(value) {
1128
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
1129
+ }
1130
+
1131
+ function safeStringify(value) {
1132
+ try {
1133
+ return JSON.stringify(value)
1134
+ } catch {
1135
+ return null
1136
+ }
1137
+ }
1138
+
1139
+ function parseJsonText(text) {
1140
+ if (typeof text !== 'string' || text === '') return undefined
1141
+ try {
1142
+ return JSON.parse(text)
1143
+ } catch {
1144
+ return undefined
1145
+ }
1146
+ }
1147
+
1148
+ function parseIsoMs(text) {
1149
+ if (typeof text !== 'string' || text === '') return undefined
1150
+ const ms = Date.parse(text)
1151
+ return Number.isFinite(ms) ? ms : undefined
1152
+ }
1153
+
1154
+ function toIso(ms) {
1155
+ const value = Number(ms)
1156
+ return new Date(Number.isFinite(value) ? value : 0).toISOString()
1157
+ }