@li-canghai/dsh-paper 0.0.0-stage → 0.8.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 (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -2
  3. package/cordis.patch.yml +4 -0
  4. package/lib/annotate-tool.js +334 -0
  5. package/lib/arxiv-id.js +74 -0
  6. package/lib/asset-routes.js +210 -0
  7. package/lib/bibliography-formats.js +126 -0
  8. package/lib/bibliography-import.js +105 -0
  9. package/lib/bibliography-service.js +43 -0
  10. package/lib/bibliography.js +42 -0
  11. package/lib/block-authors.js +292 -0
  12. package/lib/block-cache.js +39 -0
  13. package/lib/blocks-markdown.js +157 -0
  14. package/lib/blocks-reconcile.js +218 -0
  15. package/lib/blocks.js +1344 -0
  16. package/lib/citation-metadata.js +260 -0
  17. package/lib/citation-styles.js +120 -0
  18. package/lib/client-parts/01-pure-helpers.js +2607 -0
  19. package/lib/client.js +9569 -0
  20. package/lib/code-source.js +68 -0
  21. package/lib/concurrency-gate.js +91 -0
  22. package/lib/context.js +233 -0
  23. package/lib/csl/SOURCES.md +10 -0
  24. package/lib/csl/gb-t-7714.csl +441 -0
  25. package/lib/csl/ieee.csl +520 -0
  26. package/lib/csl/locales-zh-CN.xml +438 -0
  27. package/lib/csl/nature.csl +190 -0
  28. package/lib/discussion.js +400 -0
  29. package/lib/documents.js +67 -0
  30. package/lib/export.js +848 -0
  31. package/lib/file-lock.js +177 -0
  32. package/lib/gloss.js +181 -0
  33. package/lib/glossary.js +279 -0
  34. package/lib/index.js +3862 -0
  35. package/lib/inline-html.js +53 -0
  36. package/lib/install-dependency.js +120 -0
  37. package/lib/item-ops.js +83 -0
  38. package/lib/job-facade.js +58 -0
  39. package/lib/json-store.js +54 -0
  40. package/lib/library-model.js +132 -0
  41. package/lib/library-service.js +180 -0
  42. package/lib/library-tool.js +982 -0
  43. package/lib/library.js +814 -0
  44. package/lib/markdown-assets.js +138 -0
  45. package/lib/markdown-literals.js +93 -0
  46. package/lib/metadata-enrichment.js +516 -0
  47. package/lib/metadata-fetch.js +146 -0
  48. package/lib/metadata-node.js +158 -0
  49. package/lib/metadata-proxy.ps1 +35 -0
  50. package/lib/mineru-config.js +95 -0
  51. package/lib/mineru-sdk-helper.py +123 -0
  52. package/lib/mineru-sdk.js +182 -0
  53. package/lib/mineru.js +268 -0
  54. package/lib/mirror-export.js +240 -0
  55. package/lib/outline.js +296 -0
  56. package/lib/page-image-helper.py +294 -0
  57. package/lib/page-image.js +454 -0
  58. package/lib/paper-metadata.js +242 -0
  59. package/lib/parse-export.js +631 -0
  60. package/lib/pdf-analysis-tool.js +750 -0
  61. package/lib/pdf-metadata-helper.py +75 -0
  62. package/lib/pdf-metadata.js +141 -0
  63. package/lib/pdf-page.js +183 -0
  64. package/lib/pdf-scan.js +134 -0
  65. package/lib/pdf-text.js +68 -0
  66. package/lib/picker.js +305 -0
  67. package/lib/portable.js +379 -0
  68. package/lib/purge.js +170 -0
  69. package/lib/read-tool.js +660 -0
  70. package/lib/reader-store.js +497 -0
  71. package/lib/reading-order.js +207 -0
  72. package/lib/rename-document.js +480 -0
  73. package/lib/rename.js +372 -0
  74. package/lib/renderer-status.js +161 -0
  75. package/lib/resolver.js +1152 -0
  76. package/lib/result-archive.js +157 -0
  77. package/lib/revisions.js +330 -0
  78. package/lib/search-database.js +62 -0
  79. package/lib/search-index.js +601 -0
  80. package/lib/search-scan.js +185 -0
  81. package/lib/search-source.js +23 -0
  82. package/lib/search-terms.js +539 -0
  83. package/lib/section-audit.js +209 -0
  84. package/lib/selection-message.js +332 -0
  85. package/lib/serial-tail.js +21 -0
  86. package/lib/slicing.js +425 -0
  87. package/lib/source-resolver.js +581 -0
  88. package/lib/stem-repair.js +189 -0
  89. package/lib/storage.js +562 -0
  90. package/lib/store-paths.js +253 -0
  91. package/lib/table-gfm.js +236 -0
  92. package/lib/tasks.js +270 -0
  93. package/lib/tex-align.js +509 -0
  94. package/lib/tex-blocks.js +653 -0
  95. package/lib/tex-fetch.js +455 -0
  96. package/lib/tex-figures.js +140 -0
  97. package/lib/tex-inline.js +166 -0
  98. package/lib/tex-merge.js +279 -0
  99. package/lib/tex-pipeline.js +242 -0
  100. package/lib/tex-prepare.js +746 -0
  101. package/lib/tex-tables.js +210 -0
  102. package/lib/text-similarity.js +85 -0
  103. package/lib/tool-contract.js +86 -0
  104. package/lib/tool-host.js +1058 -0
  105. package/lib/tool-identity.js +214 -0
  106. package/lib/translatable-text.js +48 -0
  107. package/lib/translate-prompts.js +709 -0
  108. package/lib/translate-queue.js +418 -0
  109. package/lib/translate-task.js +158 -0
  110. package/lib/translate.js +909 -0
  111. package/lib/update-check.js +438 -0
  112. package/lib/update-contracts.js +75 -0
  113. package/lib/usage.js +282 -0
  114. package/package.json +55 -4
package/lib/storage.js ADDED
@@ -0,0 +1,562 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { createHash } from 'node:crypto'
3
+ import { mkdir, readFile, readdir, rename, rm, rmdir, writeFile } from 'node:fs/promises'
4
+ import { dirname, join } from 'node:path'
5
+ import { acquireFileLock } from './file-lock.js'
6
+ import { readDocumentManifest, writeDocumentManifest } from './portable.js'
7
+ import { repairSplitStems } from './stem-repair.js'
8
+
9
+ export const MAX_HIDDEN_DOCUMENTS = 200
10
+ export const MAX_TERMINAL_JOBS = 200
11
+
12
+ const TERMINAL_JOB_STATUSES = new Set(['ready', 'failed', 'interrupted', 'retried'])
13
+
14
+ const DEFAULT_SETTINGS = Object.freeze({
15
+ // ---- arXiv 源码优先(默认关:关闭时解析路径与接入前逐字节一致)----
16
+ // 开启后,arXiv 来源会在 MinerU 之外再跑一遍作者源码包并按块择优;任何一环不成立就整篇退回 MinerU。
17
+ texSourceEnabled: false,
18
+ parseTimeoutMs: 15 * 60 * 1000,
19
+ parseLanguage: 'ch',
20
+ parseOcr: false,
21
+ outlineBudgetBytes: 32 * 1024,
22
+ // Byte cap for one injected message. A folder scan can attach hundreds of papers at
23
+ // once: however small each outline is, the count multiplies it into a library shipped
24
+ // inside a single request. Over the cap, papers degrade to path-only lines.
25
+ contextBudgetBytes: 96 * 1024,
26
+ // ---- 翻译(D67–D72)----
27
+ // 解析完成后是否自动开始翻译(D15:默认开)。
28
+ translationAuto: true,
29
+ readerMultipleTabs: true,
30
+ // all = 整篇;body = 只译正文(排除参考文献与附录);pages = 前 N 页。
31
+ // 🔴 没有全局固定的 pageFrom/pageTo —— 那个语义 per-paper 不成立(D68)。
32
+ translationScope: 'pages',
33
+ // 「前 N 页」的 N。20 覆盖摘要/引言/方法/结论通常所在的范围;monograph 主动改「整篇」。
34
+ translationPages: 20,
35
+ // 翻译用的模型路由;null = 跟随宿主默认 agent 模型(D42)。
36
+ translationModel: null,
37
+ // 并发翻译的批次上限(D136,用户裁定:默认 4,设置页可调 1–8)。
38
+ translateConcurrency: 4,
39
+ // 输出协议(D138 / D139):json = 通用模型要 JSON 数组;lines = 专用模型的逐行方言(批量);
40
+ // plain = 专用模型的纯文本(逐块,一次一块,插件的请求数 = 块数)。
41
+ translationProtocol: 'json',
42
+ // 目标语言(D140)。白名单在 translate-prompts.js 的 TRANSLATION_LANGUAGES。
43
+ translationLanguage: 'zh',
44
+ })
45
+
46
+ /** 翻译范围的合法取值。放进 storage 是因为 /settings 与插件详情页都要照它校验。 */
47
+ export const TRANSLATION_SCOPES = Object.freeze(['all', 'body', 'pages'])
48
+
49
+ /** 翻译输出协议的合法取值(D138 / D139)。与 translate-prompts.js 的 OUTPUT_PROTOCOLS 同集合,
50
+ * 放在 storage 是因为 /settings 与插件详情页都要照它校验。
51
+ */
52
+ export const TRANSLATION_PROTOCOLS = Object.freeze(['json', 'lines', 'plain'])
53
+
54
+ /**
55
+ * 已退役的设置键。读状态时显式剔除,不靠"下次写入自然消失":
56
+ * readState 用 `...(value.settings ?? {})` 展开旧文件,未知键会被原样带回,
57
+ * 于是退役的设置会永远留在 state.json 里。这里显式丢掉,下一次写入就不再落盘。
58
+ *
59
+ * - summaryCleanup:论文总结清理策略,连同它的自动删除路径一起退役
60
+ * - zoteroDataDir:Zotero 缓存复用的数据目录,随整个 Zotero 集成退役
61
+ *
62
+ * 🔴 退役一个设置键时**必须**同时把它加进这张表 —— 只是从 DEFAULT_SETTINGS 里删掉
63
+ * 不够:展开旧文件会把它原样带回,而它已经没有消费者了。
64
+ *
65
+ * 只删设置里的键,不碰 documents / jobs / selections 与任何文档记录。
66
+ */
67
+ const RETIRED_SETTINGS = ['summaryCleanup', 'zoteroDataDir']
68
+
69
+ /**
70
+ * 已退役的文档字段。与 RETIRED_SETTINGS 同因:readState 用 `...value` 展开旧文件,
71
+ * 未知键会被原样带回,于是 source(曾经记着解析结果从哪来)会永远留在 state.json 里。
72
+ *
73
+ * 冷记录走 rawArchivedDocuments() 直读 JSON,不经过 readState,所以两处都要剔。
74
+ * 只读时剔除,不主动重写用户的文件 —— 记录下次被写回时自然干净。
75
+ */
76
+ const RETIRED_DOCUMENT_KEYS = ['source']
77
+
78
+ function dropRetiredDocumentKeys(document) {
79
+ if (!document || typeof document !== 'object') return document
80
+ for (const key of RETIRED_DOCUMENT_KEYS) delete document[key]
81
+ return document
82
+ }
83
+
84
+ const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
85
+
86
+ // Windows 上"写临时文件再 rename 覆盖"会被杀软扫描或并发读取短暂挡住,报 EPERM/EBUSY/EACCES
87
+ // (POSIX 上不会)。这不是状态损坏,重试即可;不重试的话一次抖动就会让 update 抛错、任务卡住。
88
+ const REPLACE_RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES'])
89
+ const REPLACE_ATTEMPTS = 10
90
+
91
+ export async function replaceStateFile(temporary, path, renameFile = rename) {
92
+ for (let attempt = 0; ; attempt += 1) {
93
+ try {
94
+ await renameFile(temporary, path)
95
+ return
96
+ } catch (error) {
97
+ if (!REPLACE_RETRY_CODES.has(error?.code) || attempt >= REPLACE_ATTEMPTS - 1) throw error
98
+ await wait(20 * (attempt + 1))
99
+ }
100
+ }
101
+ }
102
+
103
+ /**
104
+ * 任务类别。解析与翻译共用 state.jobs,靠这一条分流。
105
+ *
106
+ * 🔴 用户磁盘上已有真实旧记录(写它们的时候还没有 kind 字段)。缺字段、给了 null、给了不认识
107
+ * 的值,一律读作 "parse" —— 不能当异常,也不能让翻译语义悄悄接管旧数据。
108
+ */
109
+ export function jobKindOf(job) {
110
+ return job?.kind === 'translate' ? 'translate' : 'parse'
111
+ }
112
+
113
+ /**
114
+ * 宿主退出标记按 kind 各记各的:解析沿用既有前缀(一字未改),翻译用自己的。
115
+ *
116
+ * 🔴 判定必须**同类才认**(见 {@link hostExitMarkerOf})。两个前缀互不为前缀,拿解析的前缀去判
117
+ * 翻译任务,会让"宿主在翻译中途退出"既不被自己认出来、又被当成解析中断自动重排;反过来同理。
118
+ */
119
+ export const HOST_EXIT_ERROR = '宿主在解析完成前退出'
120
+ export const HOST_EXIT_ERROR_TRANSLATE = '宿主在翻译完成前退出'
121
+
122
+ const HOST_EXIT_MARKER_BY_KIND = Object.freeze({ parse: HOST_EXIT_ERROR, translate: HOST_EXIT_ERROR_TRANSLATE })
123
+
124
+ /** 这一类任务自己的宿主退出前缀:写入方与判别方共用,免得两边各写一份字面量而悄悄分叉。 */
125
+ function hostExitMarkerOf(job) {
126
+ return HOST_EXIT_MARKER_BY_KIND[jobKindOf(job)]
127
+ }
128
+
129
+ /** Whether a job ever reached its first parse attempt (the attempt is recorded right before the remote call). */
130
+ function neverStarted(job) {
131
+ return !Array.isArray(job?.attempts) || job.attempts.length === 0
132
+ }
133
+
134
+ function interruptedByHostExit(job) {
135
+ return typeof job?.error === 'string' && job.error.startsWith(hostExitMarkerOf(job))
136
+ }
137
+
138
+ function emptyState(initialSettings = {}) {
139
+ return { version: 3, documents: {}, jobs: {}, selections: {}, settings: { ...DEFAULT_SETTINGS, ...initialSettings } }
140
+ }
141
+
142
+ async function readState(path, initialSettings) {
143
+ try {
144
+ const value = JSON.parse(await readFile(path, 'utf8'))
145
+ // 退役设置键在这里剔除:展开旧 settings 会把未知键原样带回,下一次写入就会把它再落盘。
146
+ const settings = { ...DEFAULT_SETTINGS, ...initialSettings, ...(value.settings ?? {}) }
147
+ for (const key of RETIRED_SETTINGS) delete settings[key]
148
+ const documents = value.documents && typeof value.documents === 'object' ? value.documents : {}
149
+ for (const document of Object.values(documents)) dropRetiredDocumentKeys(document)
150
+ return {
151
+ ...emptyState(initialSettings),
152
+ ...value,
153
+ version: 3,
154
+ documents,
155
+ jobs: value.jobs && typeof value.jobs === 'object' ? value.jobs : {},
156
+ selections: value.selections && typeof value.selections === 'object' ? value.selections : {},
157
+ settings,
158
+ }
159
+ } catch (error) {
160
+ if (error?.code === 'ENOENT') return emptyState(initialSettings)
161
+ if (error instanceof SyntaxError) throw new Error(`dsh-paper 状态文件损坏,已停止写入以保留原文件:${path}`, { cause: error })
162
+ throw error
163
+ }
164
+ }
165
+
166
+ export function sessionDocumentIds(state, sessionId) {
167
+ const entry = state.selections[sessionId]
168
+ if (Array.isArray(entry?.documentIds)) return [...new Set(entry.documentIds)]
169
+ if (!entry) return []
170
+ const inferred = new Set([
171
+ ...(entry.desired ?? []),
172
+ ...(entry.delivered ?? []),
173
+ ...(entry.deliveredUnavailable ?? []),
174
+ ])
175
+ for (const job of Object.values(state.jobs ?? {})) {
176
+ if (job?.sessionId === sessionId && typeof job.documentId === 'string') inferred.add(job.documentId)
177
+ }
178
+ return [...inferred]
179
+ }
180
+
181
+ export function documentIsAttached(state, documentId) {
182
+ return Object.keys(state.selections).some(sessionId => sessionDocumentIds(state, sessionId).includes(documentId))
183
+ }
184
+
185
+ /**
186
+ * 所有仍与会话关联的论文 id。compact 这类要逐个文档判断"是否还挂着"的场合必须先算一次:
187
+ * {@link documentIsAttached} 每次调用都要重扫 selections 并对每个会话展开 jobs,
188
+ * 批量导入留下几百条隐藏记录时整次 compact 会退化成 O(文档数 × 任务数)。
189
+ */
190
+ export function attachedDocumentIds(state) {
191
+ const attached = new Set()
192
+ for (const sessionId of Object.keys(state.selections ?? {})) {
193
+ for (const documentId of sessionDocumentIds(state, sessionId)) attached.add(documentId)
194
+ }
195
+ return attached
196
+ }
197
+
198
+ export function attachDocument(state, sessionId, documentId) {
199
+ const current = state.selections[sessionId] ?? { desired: [], delivered: [] }
200
+ const documentIds = new Set(sessionDocumentIds(state, sessionId))
201
+ documentIds.add(documentId)
202
+ state.selections[sessionId] = { ...current, documentIds: [...documentIds] }
203
+ if (state.documents[documentId]) state.documents[documentId].hidden = false
204
+ }
205
+
206
+ function errorText(error) {
207
+ return String(error?.message ?? error).slice(0, 500)
208
+ }
209
+
210
+ // sessionPersistence.stat(id) 返回 undefined 即会话已不存在;stat 报错时保守保留条目,绝不因校验失败丢数据。
211
+ export async function pruneStaleSelections(repository, persistence, logger) {
212
+ const state = await repository.snapshot()
213
+ const stale = []
214
+ for (const id of Object.keys(state.selections)) {
215
+ try {
216
+ if (await persistence.stat(id) === undefined) stale.push(id)
217
+ } catch (error) {
218
+ logger.warn(`dsh-paper selection sweep: 会话 ${id} 存在性校验失败,保留其选择条目:${errorText(error)}`)
219
+ }
220
+ }
221
+ if (stale.length === 0) return 0
222
+ await repository.update(current => {
223
+ const detached = new Set()
224
+ for (const id of stale) {
225
+ for (const documentId of sessionDocumentIds(current, id)) detached.add(documentId)
226
+ delete current.selections[id]
227
+ }
228
+ for (const documentId of detached) {
229
+ if (current.documents[documentId] && !documentIsAttached(current, documentId)) current.documents[documentId].hidden = true
230
+ }
231
+ })
232
+ await repository.compact()
233
+ logger.info(`dsh-paper selection sweep: 清理了 ${stale.length} 个已不存在会话的论文选择条目:${stale.slice(0, 8).join(', ')}${stale.length > 8 ? ' …' : ''}`)
234
+ return stale.length
235
+ }
236
+
237
+ function documentRecency(document) {
238
+ const timestamp = Date.parse(document?.lastUsedAt ?? document?.readyAt ?? '')
239
+ return Number.isFinite(timestamp) ? timestamp : 0
240
+ }
241
+
242
+ function jobRecency(job) {
243
+ const timestamp = Date.parse(job?.updatedAt ?? job?.createdAt ?? '')
244
+ return Number.isFinite(timestamp) ? timestamp : 0
245
+ }
246
+
247
+ function isPortableLocator(document) {
248
+ return document?.artifact?.kind === 'sidecar'
249
+ && Object.keys(document).every(key => ['id', 'pdfPath', 'artifact'].includes(key))
250
+ }
251
+
252
+ /**
253
+ * 当前调用栈持有的**文档锁**租约。{@link PaperRepository.update} 在写盘前要再自证一次:
254
+ * 文档锁被判死、被别的实例接管之后,旧持有者手里的读改写序列必须整段作废 ——
255
+ * 只校验状态锁是不够的,那把锁是它自己刚合法拿到的。
256
+ */
257
+ const documentLease = new AsyncLocalStorage()
258
+
259
+ export class PaperRepository {
260
+ constructor(runtimeRoot, initialSettings = {}) {
261
+ this.root = runtimeRoot
262
+ this.path = join(runtimeRoot, 'state.json')
263
+ this.lockPath = join(runtimeRoot, '.state.lock')
264
+ this.initialSettings = initialSettings
265
+ this.archiveRoot = join(runtimeRoot, 'archive')
266
+ this.tail = Promise.resolve()
267
+ }
268
+
269
+ archivePath(documentId) {
270
+ if (!/^[a-f0-9]{64}$/.test(documentId)) throw new Error(`论文 ID 无效:${documentId}`)
271
+ return join(this.archiveRoot, documentId.slice(0, 2), `${documentId}.json`)
272
+ }
273
+
274
+ /**
275
+ * Serialize a paper's publication, rename and metadata writes across instances and hosts.
276
+ * Acquire before reading records; retain through commit or rollback. Callers may
277
+ * acquire the state lock inside this operation, never the reverse.
278
+ */
279
+ async withDocumentWrite(documentId, operation) {
280
+ const key = createHash('sha256').update(documentId).digest('hex')
281
+ await mkdir(this.root, { recursive: true })
282
+ const lease = await acquireFileLock(join(this.root, `.document.${key}.lock`), {
283
+ message: '这篇论文正被另一个操作或另一个宿主占用,请稍后重试',
284
+ })
285
+ try {
286
+ await lease.assertOwned()
287
+ return await documentLease.run(lease, operation)
288
+ } finally {
289
+ await lease.release()
290
+ }
291
+ }
292
+
293
+ /**
294
+ * 按**名字**串行化一件全局的读改写(术语表、库偏好这类不归属于某一篇论文的东西)。
295
+ *
296
+ * 与 {@link withDocumentWrite} 是同一把锁、同一套租约,只有键的来路不同:这类东西没有
297
+ * documentId,硬拿一个哈希当目录名只会让排查时看不出它护着什么。
298
+ *
299
+ * 名字会进目录名,所以先收成「安全片段」再拼,避免 `../` 这类路径从调用方漏进来。
300
+ */
301
+ async withNamedWrite(name, operation) {
302
+ if (typeof name !== 'string' || name.trim() === '') throw new Error('dsh-paper 具名写锁需要一个非空名字')
303
+ await mkdir(this.root, { recursive: true })
304
+ const digest = createHash('sha256').update(name).digest('hex').slice(0, 12)
305
+ const slug = name.replace(/[^a-z0-9-]/gi, '').toLowerCase() || 'named'
306
+ const lease = await acquireFileLock(join(this.root, `.${slug}.${digest}.lock`), {
307
+ message: `dsh-paper 的「${name}」正被另一个操作或另一个宿主占用,请稍后重试`,
308
+ })
309
+ try {
310
+ await lease.assertOwned()
311
+ return await documentLease.run(lease, operation)
312
+ } finally {
313
+ await lease.release()
314
+ }
315
+ }
316
+
317
+ /**
318
+ * 删掉一篇的冷记录,并把**空掉的分片目录**一并收走。
319
+ *
320
+ * 🔴 只删文件会留下 `archive/11/`、`archive/f9/` 这种空壳 —— 分片目录本身是按
321
+ * 「哈希前两位」派的,永久删除之后它再无内容,却不会有人来清。`rmdir` 只对空目录成功,
322
+ * 所以同分片里还有别的论文时它自然失败,这里一律吞掉(非空 = 不该删)。
323
+ */
324
+ async removeArchivedDocument(documentId) {
325
+ const path = this.archivePath(documentId)
326
+ await rm(path, { force: true })
327
+ try {
328
+ await rmdir(dirname(path))
329
+ } catch {}
330
+ }
331
+
332
+ async rawArchivedDocument(documentId) {
333
+ try {
334
+ // 与 rawArchivedDocuments() 同因:单条冷记录也是直读 JSON,退役字段在这里一并剔掉。
335
+ const document = dropRetiredDocumentKeys(JSON.parse(await readFile(this.archivePath(documentId), 'utf8')))
336
+ if (document?.id !== documentId) throw new Error(`论文冷记录 ID 不匹配:${documentId}`)
337
+ return document
338
+ } catch (error) {
339
+ if (error?.code === 'ENOENT') return undefined
340
+ throw error
341
+ }
342
+ }
343
+
344
+ async archivedDocument(documentId) {
345
+ const document = await this.rawArchivedDocument(documentId)
346
+ if (!document) return undefined
347
+ try { return await readDocumentManifest(document) ?? document } catch { return document }
348
+ }
349
+
350
+ // 只写 runtime 归档冷记录,不碰随 PDF 走的 analysis/*.json 便携清单。
351
+ async writeArchivedRecord(document) {
352
+ const path = this.archivePath(document.id)
353
+ const { outlineText: _outlineText, ...metadata } = document
354
+ const archived = document?.artifact?.kind === 'sidecar'
355
+ ? { id: document.id, pdfPath: document.pdfPath, artifact: document.artifact }
356
+ : metadata
357
+ await mkdir(dirname(path), { recursive: true })
358
+ const temporary = join(dirname(path), `.${document.id}.${process.pid}.${Date.now()}.tmp`)
359
+ await writeFile(temporary, `${JSON.stringify(archived, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
360
+ await rename(temporary, path)
361
+ }
362
+
363
+ async writeArchivedDocument(document) {
364
+ await writeDocumentManifest(document)
365
+ await this.writeArchivedRecord(document)
366
+ }
367
+
368
+ async saveDocument(document) {
369
+ await this.update(async state => {
370
+ state.documents[document.id] = document
371
+ await this.writeArchivedDocument(document)
372
+ })
373
+ return document
374
+ }
375
+
376
+ async updateDocument(documentId, mutator) {
377
+ return this.update(async state => {
378
+ const document = state.documents[documentId]
379
+ if (!document) throw new Error('论文已从当前状态移除')
380
+ const result = await mutator(document)
381
+ await this.writeArchivedDocument(document)
382
+ return result
383
+ })
384
+ }
385
+
386
+ async rawArchivedDocuments({ excludeIds } = {}) {
387
+ let prefixes
388
+ try { prefixes = await readdir(this.archiveRoot, { withFileTypes: true }) } catch (error) {
389
+ if (error?.code === 'ENOENT') return []
390
+ throw error
391
+ }
392
+ const documents = []
393
+ for (const prefix of prefixes) {
394
+ if (!prefix.isDirectory()) continue
395
+ const dir = join(this.archiveRoot, prefix.name)
396
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
397
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue
398
+ if (excludeIds?.has(entry.name.slice(0, -5))) continue
399
+ // 冷记录不经过 readState,退役字段要在这里同样剔掉(见 RETIRED_DOCUMENT_KEYS)。
400
+ const document = dropRetiredDocumentKeys(JSON.parse(await readFile(join(dir, entry.name), 'utf8')))
401
+ if (document && typeof document.id === 'string') documents.push(document)
402
+ }
403
+ }
404
+ return documents
405
+ }
406
+
407
+ async archivedDocuments() {
408
+ const documents = []
409
+ for (const document of await this.rawArchivedDocuments()) {
410
+ try { documents.push(await readDocumentManifest(document) ?? document) } catch { documents.push(document) }
411
+ }
412
+ return documents
413
+ }
414
+
415
+ async migratePortableDocuments() {
416
+ let migrated = 0
417
+ const failures = []
418
+ await this.update(async state => {
419
+ const archived = new Map((await this.rawArchivedDocuments()).map(document => [document.id, document]))
420
+ const ids = new Set([
421
+ ...Object.values(state.documents).filter(document => document?.artifact?.kind === 'sidecar').map(document => document.id),
422
+ ...[...archived.values()].filter(document => document?.artifact?.kind === 'sidecar' && !isPortableLocator(document)).map(document => document.id),
423
+ ])
424
+ for (const id of ids) {
425
+ const hot = state.documents[id]
426
+ const cold = archived.get(id)
427
+ const base = hot ?? cold
428
+ if (!base) continue
429
+ try {
430
+ let sidecar
431
+ try { sidecar = await readDocumentManifest(base) } catch {}
432
+ const document = { ...(cold ?? {}), ...(hot ?? {}), ...(sidecar ?? {}) }
433
+ await this.writeArchivedDocument(document)
434
+ if (hot) state.documents[id] = document
435
+ migrated += 1
436
+ } catch (error) {
437
+ failures.push({ id, error: errorText(error) })
438
+ }
439
+ }
440
+ })
441
+ return { migrated, failures }
442
+ }
443
+
444
+ /**
445
+ * 对账"资产被劈成两套主名"的论文(D178)。逻辑全在 stem-repair.js,这里只把它接到
446
+ * repository 的读/写面上 —— 启动链与 migratePortableDocuments 并排调用,两者都不该抛。
447
+ */
448
+ async repairSplitStems(logger) {
449
+ return repairSplitStems(this, logger)
450
+ }
451
+
452
+ async compact({ hiddenLimit = MAX_HIDDEN_DOCUMENTS, terminalJobLimit = MAX_TERMINAL_JOBS } = {}) {
453
+ return this.update(async state => {
454
+ const attached = attachedDocumentIds(state)
455
+ const hidden = Object.values(state.documents)
456
+ .filter(document => document?.hidden === true && !attached.has(document.id))
457
+ .sort((left, right) => documentRecency(right) - documentRecency(left) || String(left.id).localeCompare(String(right.id)))
458
+ for (const document of hidden) delete document.outlineText
459
+ const evicted = hidden.slice(Math.max(0, hiddenLimit))
460
+ for (const document of evicted) {
461
+ // 🔴 整理只搬**定位索引**,不重写随 PDF 走的权威清单。
462
+ //
463
+ // 热记录可能是陈旧的:updateMetadata 先把新事实写进 manifest、再提交 state,
464
+ // 提交那一步失败时热记录仍停在旧值。此时若用 writeArchivedDocument,就会拿那份陈旧
465
+ // 记录把 manifest 重写回旧事实 —— 一次本可由权威记录恢复的索引写失败,被固化成事实回退。
466
+ await this.writeArchivedRecord(document)
467
+ delete state.documents[document.id]
468
+ }
469
+
470
+ const terminalJobs = Object.values(state.jobs)
471
+ .filter(job => TERMINAL_JOB_STATUSES.has(job?.status))
472
+ .sort((left, right) => jobRecency(right) - jobRecency(left) || String(left.id).localeCompare(String(right.id)))
473
+ for (const job of terminalJobs.slice(Math.max(0, terminalJobLimit))) delete state.jobs[job.id]
474
+ return { archivedDocuments: evicted.length, removedJobs: Math.max(0, terminalJobs.length - Math.max(0, terminalJobLimit)) }
475
+ })
476
+ }
477
+
478
+ async snapshot() {
479
+ await mkdir(this.root, { recursive: true })
480
+ return readState(this.path, this.initialSettings)
481
+ }
482
+
483
+ async update(mutator) {
484
+ const operation = this.tail.then(async () => {
485
+ await mkdir(this.root, { recursive: true })
486
+ const lease = await acquireFileLock(this.lockPath)
487
+ try {
488
+ const state = await readState(this.path, this.initialSettings)
489
+ const result = await mutator(state)
490
+ // 提交前自证:锁已经不是自己的时候一个字节都不写。
491
+ // 文档锁先查 —— 它比状态锁活得久,被判死时整段读改写都该作废。
492
+ await documentLease.getStore()?.assertOwned()
493
+ await lease.assertOwned()
494
+ const temporary = join(dirname(this.path), `.state.${process.pid}.${Date.now()}.tmp`)
495
+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
496
+ await replaceStateFile(temporary, this.path)
497
+ return result
498
+ } finally {
499
+ await lease.release()
500
+ }
501
+ })
502
+ this.tail = operation.catch(() => {})
503
+ return operation
504
+ }
505
+
506
+ /**
507
+ * Host-start reconciliation for jobs the previous process left behind.
508
+ *
509
+ * A `running` job may already have a parse submitted to MinerU, so it becomes
510
+ * `interrupted` and waits for an explicit retry. A `queued` job was never
511
+ * started, so nothing was submitted: it keeps its queue position and is
512
+ * returned as `resumable` for the caller to re-enqueue. Without that, every
513
+ * host restart in the middle of a batch destroys the whole remaining queue,
514
+ * which is what leaves dozens of identical "宿主在解析完成前退出" cards behind.
515
+ * A worker pool (4 in flight by default) plus the MinerU submission throttle
516
+ * both flip `queued` → `running` before any remote call, so a picked-up job
517
+ * that waits for a submission slot still has no attempt record and comes back
518
+ * as `resumable` through the host-exit branch below.
519
+ *
520
+ * Re-enqueueing is idempotent across hosts: {@link PaperRepository} serializes
521
+ * writes, but only the process that flips `queued` → `running` parses, and the
522
+ * other host's attempt for the same id returns without doing anything.
523
+ *
524
+ * 解析与翻译任务共用这张表,判定按 {@link jobKindOf} 分开走各自的宿主退出前缀:
525
+ * 两个前缀互不为前缀,所以跨类不会误判——拿解析的前缀去认翻译任务,只会让那条翻译
526
+ * 记录既不被自动重排、又带着"解析中断"的错误文本留在面板上。
527
+ *
528
+ * @returns {Promise<{resumable: string[]}>} queued job ids the caller re-enqueues,
529
+ * 解析与翻译混在一起——由调用方按 kind 各自接回自己的队列。
530
+ */
531
+ async recoverInterruptedJobs() {
532
+ return this.update(state => {
533
+ const resumable = []
534
+ const now = new Date().toISOString()
535
+ // 先结清上一次进程真正开始过的任务:它们可能已经把解析提交给 MinerU,
536
+ // 只能人工重试,不能自动重提。
537
+ for (const job of Object.values(state.jobs)) {
538
+ if (job.status !== 'running') continue
539
+ job.status = 'interrupted'
540
+ job.error = `${hostExitMarkerOf(job)},该任务已开始但未完成,请手动重试`
541
+ job.updatedAt = now
542
+ }
543
+ for (const job of Object.values(state.jobs)) {
544
+ if (job.status === 'queued') {
545
+ resumable.push(job.id)
546
+ continue
547
+ }
548
+ // 上次宿主退出时被标成中断、却一次都没开始的任务:同样没有提交给 MinerU,
549
+ // 直接接着排队——否则批量添加后一次重启就会留下几十张要逐条点重试的卡片。
550
+ // 带 attempts 的中断说明远端可能已受理,保持人工。
551
+ if (job.status !== 'interrupted' || !interruptedByHostExit(job) || !neverStarted(job)) continue
552
+ job.status = 'queued'
553
+ job.error = ''
554
+ job.updatedAt = now
555
+ resumable.push(job.id)
556
+ }
557
+ return { resumable }
558
+ })
559
+ }
560
+ }
561
+
562
+ export { DEFAULT_SETTINGS }