@li-canghai/dsh-paper 0.0.0-stage → 0.8.1

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 (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -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 +2762 -0
  19. package/lib/client-parts/02-author-year.js +95 -0
  20. package/lib/client.js +10381 -0
  21. package/lib/code-source.js +68 -0
  22. package/lib/concurrency-gate.js +91 -0
  23. package/lib/context.js +233 -0
  24. package/lib/csl/SOURCES.md +10 -0
  25. package/lib/csl/gb-t-7714.csl +441 -0
  26. package/lib/csl/ieee.csl +520 -0
  27. package/lib/csl/locales-zh-CN.xml +438 -0
  28. package/lib/csl/nature.csl +190 -0
  29. package/lib/discussion.js +400 -0
  30. package/lib/documents.js +67 -0
  31. package/lib/export.js +848 -0
  32. package/lib/file-lock.js +177 -0
  33. package/lib/gloss.js +181 -0
  34. package/lib/glossary.js +279 -0
  35. package/lib/index.js +3862 -0
  36. package/lib/inline-html.js +53 -0
  37. package/lib/install-dependency.js +120 -0
  38. package/lib/item-ops.js +83 -0
  39. package/lib/job-facade.js +58 -0
  40. package/lib/json-store.js +54 -0
  41. package/lib/library-model.js +132 -0
  42. package/lib/library-service.js +180 -0
  43. package/lib/library-tool.js +982 -0
  44. package/lib/library.js +814 -0
  45. package/lib/markdown-assets.js +138 -0
  46. package/lib/markdown-literals.js +93 -0
  47. package/lib/metadata-enrichment.js +516 -0
  48. package/lib/metadata-fetch.js +146 -0
  49. package/lib/metadata-node.js +158 -0
  50. package/lib/metadata-proxy.ps1 +35 -0
  51. package/lib/mineru-config.js +95 -0
  52. package/lib/mineru-sdk-helper.py +123 -0
  53. package/lib/mineru-sdk.js +182 -0
  54. package/lib/mineru.js +268 -0
  55. package/lib/mirror-export.js +240 -0
  56. package/lib/outline.js +296 -0
  57. package/lib/page-image-helper.py +308 -0
  58. package/lib/page-image.js +454 -0
  59. package/lib/paper-metadata.js +242 -0
  60. package/lib/parse-export.js +631 -0
  61. package/lib/pdf-analysis-tool.js +750 -0
  62. package/lib/pdf-metadata-helper.py +75 -0
  63. package/lib/pdf-metadata.js +141 -0
  64. package/lib/pdf-page.js +261 -0
  65. package/lib/pdf-scan.js +134 -0
  66. package/lib/pdf-text.js +68 -0
  67. package/lib/picker.js +305 -0
  68. package/lib/portable.js +379 -0
  69. package/lib/purge.js +170 -0
  70. package/lib/read-tool.js +660 -0
  71. package/lib/reader-store.js +497 -0
  72. package/lib/reading-order.js +207 -0
  73. package/lib/rename-document.js +480 -0
  74. package/lib/rename.js +372 -0
  75. package/lib/renderer-status.js +161 -0
  76. package/lib/resolver.js +1152 -0
  77. package/lib/result-archive.js +157 -0
  78. package/lib/revisions.js +330 -0
  79. package/lib/search-database.js +62 -0
  80. package/lib/search-index.js +601 -0
  81. package/lib/search-scan.js +185 -0
  82. package/lib/search-source.js +23 -0
  83. package/lib/search-terms.js +539 -0
  84. package/lib/section-audit.js +209 -0
  85. package/lib/selection-message.js +332 -0
  86. package/lib/serial-tail.js +21 -0
  87. package/lib/slicing.js +425 -0
  88. package/lib/source-resolver.js +581 -0
  89. package/lib/stem-repair.js +189 -0
  90. package/lib/storage.js +562 -0
  91. package/lib/store-paths.js +253 -0
  92. package/lib/table-gfm.js +236 -0
  93. package/lib/tasks.js +270 -0
  94. package/lib/tex-align.js +509 -0
  95. package/lib/tex-blocks.js +653 -0
  96. package/lib/tex-fetch.js +455 -0
  97. package/lib/tex-figures.js +140 -0
  98. package/lib/tex-inline.js +166 -0
  99. package/lib/tex-merge.js +279 -0
  100. package/lib/tex-pipeline.js +242 -0
  101. package/lib/tex-prepare.js +746 -0
  102. package/lib/tex-tables.js +210 -0
  103. package/lib/text-similarity.js +85 -0
  104. package/lib/tool-contract.js +86 -0
  105. package/lib/tool-host.js +1058 -0
  106. package/lib/tool-identity.js +214 -0
  107. package/lib/translatable-text.js +48 -0
  108. package/lib/translate-prompts.js +709 -0
  109. package/lib/translate-queue.js +418 -0
  110. package/lib/translate-task.js +158 -0
  111. package/lib/translate.js +909 -0
  112. package/lib/update-check.js +438 -0
  113. package/lib/update-contracts.js +75 -0
  114. package/lib/usage.js +282 -0
  115. package/package.json +55 -4
@@ -0,0 +1,1152 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { mkdir, readdir, readFile, rm, rmdir, writeFile } from 'node:fs/promises'
3
+ import { dirname, join, resolve } from 'node:path'
4
+ import { markBlocks, splitBlocks } from './blocks.js'
5
+ import { anchorsOf, reconcileBlocks } from './blocks-reconcile.js'
6
+ import { inspectPdf } from './documents.js'
7
+ import { planMarkdownImages, readMarkdownBundle } from './markdown-assets.js'
8
+ import { materializeMineruResult } from './mineru.js'
9
+ import { parseWithConfiguredMineruSdk } from './mineru-sdk.js'
10
+ import { isWithin } from './mirror-export.js'
11
+ import { buildOutline, outlineFileText } from './outline.js'
12
+ import { analysisPathsOf, hydrateDocument, portableDocument, readDocumentManifest, writeAnalysisBundle, writeAnalysisContent, writePortableManifest } from './portable.js'
13
+ import { cleanRenameMetadata } from './rename.js'
14
+ import { bibliographyOf } from './bibliography.js'
15
+ import { stampOutlineRevision } from './revisions.js'
16
+ import { repairDocumentStem } from './stem-repair.js'
17
+ import { jobKindOf } from './storage.js'
18
+ import { scratchJobDir, storePathsOf, storePdfCopy } from './store-paths.js'
19
+ import { extractPageLines, extractPdfLines } from './pdf-text.js'
20
+ import { arxivIdOf } from './arxiv-id.js'
21
+ import { buildTexContentList } from './tex-pipeline.js'
22
+ import { rewriteMarkdownBody } from './blocks-markdown.js'
23
+
24
+ // MinerU 官网"接口限流策略":提交任务接口 50 文件/分钟(单文件解析、批量上传、urls 批量共用
25
+ // 同一频控)、单用户 5000 文件/天;获取任务结果 1000 次/分钟。提交额度留约 10% 余量,边界抖动时
26
+ // 宁可慢一拍也别吃 429。轮询远在额度之内(SDK 侧 2s 起步、退避到 30s 封顶,拿满 1000 次/分都要
27
+ // 几十路并发才碰得到),不需要自己再设一层。
28
+ export const DEFAULT_SUBMISSIONS_PER_MINUTE = 45
29
+ export const SUBMISSION_WINDOW_MS = 60 * 1000
30
+ // 真吃了 429 之后的全局冷却:SDK(mineru-open-sdk)对 HTTP 429 **零重试**——`raise_for_status()`
31
+ // 直接抛,错误文本带着 "Too Many Requests" 或 `429`。此时滑动窗口多半还热着,四路并发里的
32
+ // 兜底 pipeline 重试会紧跟着再撞一次;让**所有**排队中的提交一起凉一拍,比逐个撞墙便宜。
33
+ export const RATE_LIMIT_COOLDOWN_MS = 30 * 1000
34
+ // e-print 下载超时:实测 export.arxiv.org 的响应在 83–235s 之间,30s 的默认值会把它们
35
+ // 全判成 network 降级。这个等待落在一次本来就以分钟计的 MinerU 解析里,不额外拉长
36
+ // 用户感知的完成时间;真拿不到时仍然按 network 退回 MinerU。
37
+ export const TEX_EPRINT_TIMEOUT_MS = 180 * 1000
38
+
39
+ /**
40
+ * 判定一次远端调用失败是不是限流(429)。
41
+ *
42
+ * SDK 的 HTTP 层用 `raise_for_status()`,429 会以 "Client error '429 Too Many Requests'"
43
+ * 形状出现在错误文本里;业务码限流(-60018/-60019)则落在 `QuotaExceededError` 的
44
+ * "[-60018] ..." 文本里,语义同样是"这一分钟/这一天不给提交",一并按限流收。
45
+ * 刻意只认窄特征:测试桩常见的"远端拒绝"/"远端 500"都不得命中。
46
+ */
47
+ export function isRateLimitError(error) {
48
+ const text = String(error?.message ?? error)
49
+ return /\b429\b|Too Many Requests|rate limit|过于频繁|\[-6001[89]\]/i.test(text)
50
+ }
51
+ // 宿主内同时解析的论文数。串行解析让一批 PDF 排成几小时;4 路并行足够,同时把结果 ZIP 下载与
52
+ // 图片恢复的内存/磁盘峰值控制在可接受范围。
53
+ export const DEFAULT_PARSE_CONCURRENCY = 4
54
+
55
+ /** Terminal job states {@link PaperResolver#retry} accepts, and `/retry-all` selects on. */
56
+ export const RETRYABLE_JOB_STATUSES = ['failed', 'interrupted']
57
+
58
+ /**
59
+ * 关闭时等解析池收尾的上限。
60
+ *
61
+ * 一次真实解析是"VLM 失败再退 pipeline",分钟级;关闭(HMR / 禁用插件)不能等那么久。
62
+ * 超时就丢弃在飞的结果并进入关闭状态({@link PaperResolver#stop}),已经付过的远端调用
63
+ * 不等于白花 —— 但下次启动会重新解析,这一点在日志里说清楚,不粉饰。
64
+ */
65
+ export const STOP_GRACE_MS = 10 * 1000
66
+
67
+ function positiveInt(value, fallback) {
68
+ return Number.isInteger(value) && value > 0 ? value : fallback
69
+ }
70
+
71
+ /**
72
+ * 提交额度闸门:滑动窗口内最多放行 limit 次提交。计数单位是"提交"而不是"任务"——VLM 失败后
73
+ * 自动重试 pipeline 是第二次提交,同样占额度,所以额度在每次远端调用前才取。
74
+ *
75
+ * 上面还叠了一层**限流冷却**({@link SubmissionLimiter#penalize}):任何一路真的吃了 429,
76
+ * 后续所有提交(文献库与解析 Tab 共用同一个实例)先等冷却走完再排窗口——冷却与窗口是两种
77
+ * 等待,冷却未过时窗口内明明有余额也不放行。
78
+ */
79
+ export class SubmissionLimiter {
80
+ constructor(limit = DEFAULT_SUBMISSIONS_PER_MINUTE, windowMs = SUBMISSION_WINDOW_MS) {
81
+ this.limit = positiveInt(limit, DEFAULT_SUBMISSIONS_PER_MINUTE)
82
+ this.windowMs = positiveInt(windowMs, SUBMISSION_WINDOW_MS)
83
+ this.stamps = []
84
+ /** 当前冷却的截止时刻(epoch ms);0 表示没有冷却。penalize 只会把它推得更远。 */
85
+ this.cooldownUntil = 0
86
+ }
87
+
88
+ /** 窗口内的提交上限(每分钟)。只读:面板据此显示"共用的一份额度有多大"。 */
89
+ get rate() { return this.limit }
90
+
91
+ /**
92
+ * 吃到限流后让**所有**提交一起凉一拍。重复命中时取"现在 + 冷却"与已有截止的较大者,
93
+ * 多路并发接连撞墙只会把冷却顺延,不会叠加成分钟级。
94
+ */
95
+ penalize(ms = RATE_LIMIT_COOLDOWN_MS) {
96
+ const until = Date.now() + Math.max(0, Number(ms) || 0)
97
+ if (until > this.cooldownUntil) this.cooldownUntil = until
98
+ }
99
+
100
+ /** 等到冷却走完且窗口内腾出额度再占用;返回时调用方已持有一次提交额度。 */
101
+ async acquire() {
102
+ for (;;) {
103
+ const now = Date.now()
104
+ if (now < this.cooldownUntil) {
105
+ await new Promise(resolve => setTimeout(resolve, this.cooldownUntil - now + 10))
106
+ continue
107
+ }
108
+ while (this.stamps.length > 0 && now - this.stamps[0] >= this.windowMs) this.stamps.shift()
109
+ if (this.stamps.length < this.limit) {
110
+ this.stamps.push(now)
111
+ return
112
+ }
113
+ await new Promise(resolve => setTimeout(resolve, this.windowMs - (now - this.stamps[0]) + 10))
114
+ }
115
+ }
116
+ }
117
+
118
+ async function hasMarkdownBundle(path) {
119
+ try { await readMarkdownBundle(path); return true } catch { return false }
120
+ }
121
+
122
+ async function isReadable(path) {
123
+ try { await readFile(path); return true } catch { return false }
124
+ }
125
+
126
+ /**
127
+ * 读目标目录里已有的块列表。读不到、不是数组、JSON 坏了都返回 undefined。
128
+ *
129
+ * 复用/重新发布场景(重新添加隐藏源、PDF 搬迁后按 analysis 恢复)走这条路:本次没有新解析
130
+ * 结果,但目录里可能已经躺着上一轮写下的 content.json。
131
+ */
132
+ async function readAnalysisContent(path) {
133
+ if (typeof path !== 'string' || path === '') return undefined
134
+ try {
135
+ const parsed = JSON.parse(await readFile(path, 'utf8'))
136
+ return Array.isArray(parsed) && parsed.length > 0 ? parsed : undefined
137
+ } catch { return undefined }
138
+ }
139
+
140
+ function errorText(error) {
141
+ return String(error?.message ?? error).slice(0, 500)
142
+ }
143
+
144
+ /**
145
+ * 把本次切出的块对齐到上一次发布留下的锚点,尽量保留旧 id。
146
+ *
147
+ * 为什么要有这一步:块 id 由「页码 + 页内同类型序号」派生(见 blocks.js)。重解析后只要某页
148
+ * 多出或少了一个同类型块,该块之后的同类块序号就整体平移 —— 实测一次插入会让 92% 的 id 变化
149
+ * (样本 329:274 块 → 275 块,253 个 id 变化)。笔记与划线锚在 id 上,不做事后对齐就等于
150
+ * 每次重解析都把笔记甩到别处。
151
+ *
152
+ * 旧 id 从**已发布的 Markdown** 反解(`<!-- b:id -->` 标记,见 blocks.js),不另存一份块列表:
153
+ * 标记里已经带了 id,而 id 自带页码与类型字母,于是 page + type + 文本三要素齐全。
154
+ *
155
+ * 读不出来(首次解析、文件被删、路径指向目录)一律当"没有旧锚点",**不报错** —— 那正是首次
156
+ * 解析该走的路径,结果退化成 splitBlocks 给的机械 id,与接对齐之前逐字节一致。
157
+ *
158
+ * 🔴 调用方必须在**写** analysis.markdown **之前**调用它。selfPublished 为真时 markdownPath
159
+ * 就是 analysis.markdown 本身:先写后读会读到刚打上新 id 的那一份,对齐变成自己对自己记账,
160
+ * 旧 id 一个也留不下。publishDocument 因此把它放在 buildOutline 之前、任何写盘动作之前。
161
+ *
162
+ * @param {Array<object>} blocks 本次 splitBlocks 的产物。
163
+ * @param {string} previousMarkdownPath 上一次发布的 Markdown 路径(可能并不存在)。
164
+ * @param {string} pdfName 只用于日志的论文名。
165
+ * @param {{warn: Function}} logger 日志口。
166
+ * @returns {Promise<Array<object>>} 对齐后的块序列。
167
+ */
168
+ async function alignToPublishedBlocks(blocks, previousMarkdownPath, pdfName, logger) {
169
+ let previous = ''
170
+ try { previous = await readFile(previousMarkdownPath, 'utf8') } catch { previous = '' }
171
+ const reconciled = reconcileBlocks(blocks, anchorsOf(previous))
172
+ const { kept, created, renamed, tombstones } = reconciled.stats
173
+ // 只在真有块让路改名或消失时出声:正常重解析(保留 + 新建)是常态,不必每次刷日志。
174
+ // 只报计数,不打印块正文 —— 日志里不该出现论文内容。
175
+ if (tombstones > 0 || renamed > 0) {
176
+ logger?.warn(`dsh-paper: 块对齐 ${pdfName}:保留 ${kept}、新建 ${created}、让路改名 ${renamed}、消失 ${tombstones}`)
177
+ }
178
+ return reconciled.blocks
179
+ }
180
+
181
+ export class PaperResolver {
182
+ constructor(repository, options = {}) {
183
+ this.repository = repository
184
+ this.logger = options.logger ?? { info() {}, warn() {}, error() {} }
185
+ /**
186
+ * 一篇论文发布成功后的回调(D67:解析完成即自动翻译)。
187
+ *
188
+ * 🔴 **调用方必须自己做 fire-and-forget**:这里是解析 worker 里的一环,await 翻译开头
189
+ * 会占住所剩无几的解析并发位。队列自己会按并发排队,不需要这里替它等。
190
+ * 🔴 回调抛错不得影响发布 —— 解析已经成功落地,翻译起不来是另一件事。
191
+ */
192
+ this.onPublished = typeof options.onPublished === 'function' ? options.onPublished : null
193
+ /**
194
+ * 发布成功后的改名钩子(D156)。
195
+ *
196
+ * 与 onPublished 分开是因为它**默认必须接上**:改名不是可选功能,自动翻译才是。
197
+ * 不注入时保持 null(测试与不需要改名的部署都走这条路,不会凭空改动文件名)。
198
+ */
199
+ this.onRenamed = typeof options.onRenamed === 'function' ? options.onRenamed : null
200
+ // 桥接配置的来源:一个「读回插件自存 MinerU Key 并解析成启动配置」的函数,由 index.js
201
+ // 注入。不注入时一律当作未配置 —— 测试与无 Key 的部署都走这条路,不会静默去起 uvx。
202
+ this.sdkConfig = options.sdkConfig ?? (() => null)
203
+ this.fetch = options.fetch ?? globalThis.fetch
204
+ this.sdkParse = options.sdkParse
205
+ this.maxConcurrent = positiveInt(options.maxConcurrent, DEFAULT_PARSE_CONCURRENCY)
206
+ this.limiter = options.limiter ?? new SubmissionLimiter(options.submissionsPerMinute)
207
+ this.pending = []
208
+ this.active = 0
209
+ this.draining = false
210
+ this.idleWaiters = []
211
+ /** 停止中:不再接受新任务({@link PaperResolver#stop})。 */
212
+ this.stopping = false
213
+ /** 已关闭:任何发布都不再写入 state(超时未收尾的旧任务靠它挡住)。 */
214
+ this.closed = false
215
+ /**
216
+ * 独立解析(右栏「解析」Tab)的并发位等待者。
217
+ *
218
+ * 🔴 它与 {@link PaperResolver#pending} 抢的是**同一本账** `active/maxConcurrent`:
219
+ * 用户裁定「解析并发本身要和文献库的解析共用」。两个队列各自去数自己的并发,等于
220
+ * 上限翻倍,那正是要避免的事。
221
+ */
222
+ this.slotWaiters = []
223
+ }
224
+
225
+ /**
226
+ * 解析池排空后才 resolve。测试与关闭流程用它等一批任务落地,不要用固定 sleep 猜时序:
227
+ * 池里还有等待或运行中的任务时返回一个新的 Promise,完全空闲时立刻 resolve。
228
+ */
229
+ get queue() {
230
+ if (this.pending.length === 0 && this.active === 0 && !this.draining) return Promise.resolve()
231
+ return new Promise(resolve => { this.idleWaiters.push(resolve) })
232
+ }
233
+
234
+ /**
235
+ * 关闭用:等池子排空,但**最多等 `timeoutMs`**(超时返回 false,不 reject)。
236
+ *
237
+ * 与 {@link PaperResolver#queue} 同一个等待队列,只是加了上限 —— 关闭流程不能因为一次
238
+ * 远端解析(最长 parseTimeoutMs = 15 分钟)把 HMR/禁用卡住。
239
+ */
240
+ idleWithin(timeoutMs) {
241
+ if (this.pending.length === 0 && this.active === 0 && !this.draining) return Promise.resolve(true)
242
+ return new Promise(resolve => {
243
+ const timer = setTimeout(() => resolve(false), timeoutMs)
244
+ timer.unref?.()
245
+ this.idleWaiters.push(() => { clearTimeout(timer); resolve(true) })
246
+ })
247
+ }
248
+
249
+ /**
250
+ * 停止解析池:**停新提交 → 等在飞的收尾 → 关闭**。
251
+ *
252
+ * 🔴 为什么必须显式接管(HMR / 禁用插件):过去 dispose 只结算翻译,解析池照旧跑 ——
253
+ * 实测 dispose 已经完成、任务仍是 running,等 SDK 边界放开后**已经被替换掉的旧实例**继续
254
+ * 发布并把它写成 ready,与新实例的启动恢复判断打架(后者看到 running 会判中断)。
255
+ *
256
+ * 语义:
257
+ * - 停止后不再接新任务(`enqueue` 直接丢弃):那些任务记录仍是 queued,下次启动按既有
258
+ * 恢复链续跑,不会丢;
259
+ * - 在飞的工作**等它收尾**(它们已经付过远端调用,把结果写完比丢掉更好),最多等
260
+ * `timeoutMs`;
261
+ * - `closed` 之后任何发布都拒绝写入 —— 超时未收尾的那几个结果就此丢弃,但"旧实例还在写"
262
+ * 这条被堵死了。
263
+ *
264
+ * @param {{timeoutMs?: number}} [options]
265
+ * @returns {Promise<{drained: boolean, active: number}>}
266
+ */
267
+ async stop({ timeoutMs = STOP_GRACE_MS } = {}) {
268
+ this.stopping = true
269
+ this.pending.length = 0
270
+ const drained = await this.idleWithin(timeoutMs)
271
+ this.closed = true
272
+ if (!drained && this.active > 0) {
273
+ this.logger.warn(`dsh-paper stop: 还有 ${this.active} 个解析任务在飞,已等待 ${timeoutMs}ms,现在关闭:这些结果不会再写入`)
274
+ }
275
+ return { drained, active: this.active }
276
+ }
277
+
278
+ /**
279
+ * MinerU 桥接的就绪状态:`configured` 表示插件自存的 Key 已解出一份可用的启动配置,
280
+ * 否则 `missing`。消费面只有三处(resolver 自己、index.js 的 `/state`、client.js 的侧栏
281
+ * 状态文案),都只读 `configured` 与 `status` 两个字段。
282
+ */
283
+ /**
284
+ * 复用一篇已有记录之前,先把"另一套主名"下的资产搬回来(D178)。
285
+ *
286
+ * 入库的主名一旦跟过源文件名,同一个 `library/<documentId>/` 目录里就会落下两套:记录指向的
287
+ * 那套缺块列表/译文/划线,另一套有。这里只搬文件、不碰记录 —— 调用方紧接着的 publishDocument
288
+ * 会拿搬回来的 `.content.json` 重新算出 `artifact.contentPath`。
289
+ *
290
+ * 整件事是**尽力而为**:对不上(多个候选主名、正文不一致)就原样返回,不让入库失败。
291
+ */
292
+ async repairStem(document) {
293
+ try {
294
+ return await repairDocumentStem({ runtimeRoot: this.repository.root, document })
295
+ } catch (error) {
296
+ this.logger?.warn?.(`dsh-paper stem repair: ${String(error?.message ?? error)}`)
297
+ return { changed: false, reason: 'error', files: [], swapped: [], contentPath: '' }
298
+ }
299
+ }
300
+
301
+ describeMineru() {
302
+ return this.sdkConfig() === null
303
+ ? { configured: false, status: 'missing' }
304
+ : { configured: true, status: 'configured' }
305
+ }
306
+
307
+ /**
308
+ * 发布一次解析结果:Markdown、目录与可选的块列表都落在 runtime 的
309
+ * `library/<documentId>/`(布局见 `store-paths.js`),并登记便携 manifest。
310
+ *
311
+ * 产物只落这一处:题录随 manifest 走,重装宿主或搬走整个 runtime 都还在。解析期的
312
+ * scratch(`documents/<hash>/<job>`、`outlines/<hash>`)在这里一并回收。
313
+ * 🔴 **不往用户目录写任何东西**(见本函数末尾的说明)。
314
+ */
315
+ /**
316
+ * 试着用作者源码包增强这一次解析结果。
317
+ *
318
+ * 🔴 整段包在 try/catch 里:源码侧是**增强**,它失败不该让一次已经成功的 MinerU 解析失败。
319
+ * 返回 null = 不做增强,调用方原样用 MinerU 的结果(这条路径与接入前逐字节一致)。
320
+ */
321
+ async applyTexSource({ job, contentList, pdf }) {
322
+ // 编号有三条来源,按可信度排:任务里带下来的来源地址 → 记录里的 archiveId → PDF 首页的自我标识。
323
+ // 前两条只在「导入时就带着 arXiv 链接」的条目上存在;库里的存量条目这两处**都是空的**
324
+ // (实测 74 篇全部为空),所以第三条不是兜底而是主路 —— arXiv 排版的首页自带那行水印。
325
+ const declared = typeof job?.sourceUrl === 'string' && job.sourceUrl !== ''
326
+ ? job.sourceUrl
327
+ : (job?.metadata?.archiveId ?? '')
328
+ try {
329
+ // 先用首页一页判定来源:出版版 PDF(ICLR / EMNLP 等)在这里就能退出,不必跑一遍全文档。
330
+ const arxivId = declared !== ''
331
+ ? declared
332
+ : arxivIdOf(await extractPageLines(job.pdfPath, 1))
333
+ if (arxivId === '') {
334
+ this.logger.info('dsh-paper tex: ' + pdf.name + ' 首页没有 arXiv 标识,保持 MinerU 结果')
335
+ return null
336
+ }
337
+ const lines = await extractPdfLines(job.pdfPath)
338
+ const analysis = analysisPathsOf(this.repository.root, pdf)
339
+ const result = await buildTexContentList({
340
+ mineruList: contentList,
341
+ arxivId,
342
+ pdfLines: lines,
343
+ cacheDir: join(this.repository.root, 'tex-cache'),
344
+ figureDir: analysis.dir,
345
+ logger: this.logger,
346
+ options: { fetchTimeoutMs: TEX_EPRINT_TIMEOUT_MS },
347
+ })
348
+ if (result.state !== 'ready') {
349
+ const detail = result.detail === undefined || result.detail === '' ? '' : ':' + result.detail
350
+ this.logger.warn('dsh-paper tex: ' + pdf.name + ' 未采用源码(' + (result.reason ?? result.state) + detail + ')')
351
+ return null
352
+ }
353
+ return { list: result.list, report: { ...result.report, idSource: declared === '' ? 'pdf' : 'meta' } }
354
+ } catch (error) {
355
+ this.logger.warn('dsh-paper tex: ' + pdf.name + ' 源码增强失败,已退回 MinerU:' + errorText(error))
356
+ return null
357
+ }
358
+ }
359
+
360
+ async publishDocument(pdf, markdownPath, options = {}) {
361
+ return this.repository.withDocumentWrite(pdf.hash, () => this.publishDocumentLocked(pdf, markdownPath, options))
362
+ }
363
+
364
+ // Read publication facts only after acquiring the same lock used by metadata edits and renames.
365
+ async publishDocumentLocked(pdf, markdownPath, options) {
366
+ const state = await this.repository.snapshot()
367
+ const markdown = await readFile(markdownPath, 'utf8')
368
+ if (markdown.trim() === '') throw new Error('Markdown 文件为空')
369
+ /**
370
+ * 这次发布**之前**那条记录(热优先、冷兜底),下面要继承它的标题/作者/年份/粘性与源目录。
371
+ *
372
+ * 🔴 必须在任何写盘动作**之前**读。发布链里 `writePortableManifest(pdf, paths)` 会先重写
373
+ * manifest,而它只按传进去的 document 合并元数据(见 portable.js 那段 `Object.hasOwn` 删除)——
374
+ * 传空对象等于把 sourceDir / sourcePdfPath 从 manifest 上抹掉。热记录有 state.documents
375
+ * 兜着看不出来,冷归档记录**只有** manifest 这一份元数据,晚读一步就继承不到任何东西
376
+ * (实测:重解析一篇冷归档论文,绑定直接消失)。
377
+ *
378
+ * 🔴 冷兜底同样必要:`compact()` 会把长期没用的论文挪进 `archive/`,那之后 state.documents
379
+ * 里就没有它了 —— 只看热表的话,重解析一次就把 title / 粘性 / sourceDir 一起抹掉,而
380
+ * sourceDir 是 D128 之后「这篇论文在用户工作区哪个文件夹」的唯一记录(reparse 不传它)。
381
+ */
382
+ let previous = state.documents[pdf.hash] ?? await this.repository.archivedDocument(pdf.hash)
383
+ if (previous) {
384
+ try { previous = await readDocumentManifest(previous, { validateArtifacts: false }) ?? previous }
385
+ catch (error) { if (error?.code !== 'ENOENT') throw error }
386
+ }
387
+ const inherited = {
388
+ ...cleanRenameMetadata(previous ? { title: previous.title, authors: previous.authors, year: previous.year } : null),
389
+ ...(typeof previous?.renamedBy === 'string' ? { renamedBy: previous.renamedBy } : {}),
390
+ ...(typeof previous?.renamedAt === 'string' ? { renamedAt: previous.renamedAt } : {}),
391
+ // 源目录同样必须继承:reparse / retry 都不带 sourceDir,不继承的话读一次正文就把
392
+ // 「这篇论文在用户工作区的哪个文件夹」抹掉 —— 而那是 D128 之后原件位置唯一的记录。
393
+ ...(typeof previous?.sourceDir === 'string' && previous.sourceDir !== '' ? { sourceDir: previous.sourceDir } : {}),
394
+ ...(typeof previous?.sourcePdfPath === 'string' && previous.sourcePdfPath !== '' ? { sourcePdfPath: previous.sourcePdfPath } : {}),
395
+ ...(previous?.bibliography ? { bibliography: previous.bibliography } : {}),
396
+ ...(previous?.clearedMetadata ? { clearedMetadata: previous.clearedMetadata } : {}),
397
+ ...(previous?.metadataSources ? { metadataSources: previous.metadataSources } : {}),
398
+ }
399
+ let finalMarkdownPath = markdownPath
400
+ let outlinePath
401
+ let manifestPath
402
+ let outline
403
+ let contentPath
404
+ let manifestPaths
405
+ // 这次发布有没有**用本次输入重写/重算**目录。只有这种情形才能在最后补输入身份:
406
+ // 目录是旧输入产出的、只是块列表换了,补新身份等于给过期目录盖章(见 stampOutlineRevision)。
407
+ let outlineWritten = false
408
+ const analysis = options.portable ?? analysisPathsOf(this.repository.root, pdf)
409
+ const selfPublished = resolve(markdownPath) === resolve(analysis.markdown)
410
+ // 重新添加隐藏源时 markdown 已在 analysis 目录:不改全文,仅在目录缺失时回填;
411
+ // saveDocument 随后更新 manifest 中的可移植元数据。
412
+ try {
413
+ // Refuse an unrelated or damaged manifest before replacing its parsed files.
414
+ try {
415
+ const manifest = JSON.parse(await readFile(analysis.manifest, 'utf8'))
416
+ if (manifest?.documentId !== pdf.hash || ![1, 2].includes(manifest?.schemaVersion)) throw new Error('manifest 身份或格式无效,拒绝覆盖')
417
+ } catch (error) { if (error?.code !== 'ENOENT') throw error }
418
+ // 块列表优先用本次解析拿到的原始数组;没有就用目标目录里已有的那份(复用/重新发布场景)。
419
+ // 都没有时 contentPath 保持 undefined,manifest 与 artifact 都不登记这个键。
420
+ let contentList = options.contentList
421
+ if (!(Array.isArray(contentList) && contentList.length > 0) && options.freshParse !== true) {
422
+ contentList = await readAnalysisContent(analysis.content)
423
+ }
424
+ if (options.freshParse === true && !(Array.isArray(contentList) && contentList.length > 0)
425
+ && await isReadable(analysis.content)) {
426
+ throw new Error('本次重解析缺少新的块列表,已保留原有解析结果;请重试解析')
427
+ }
428
+ if (selfPublished && Array.isArray(contentList) && contentList.length > 0) {
429
+ try { contentPath = await writeAnalysisContent(analysis, contentList) } catch (error) {
430
+ if (options.freshParse === true) throw error
431
+ contentPath = undefined
432
+ this.logger.warn(`dsh-paper: 块列表写入 ${analysis.dir} 失败,本次按无块列表处理:${errorText(error)}`)
433
+ }
434
+ }
435
+ // 块列表决定两件事:正文里插不插块标记、目录按不按块 id 区间渲染。读不出来就两样
436
+ // 都不做,回到只有 Markdown 的既有行为。
437
+ // 🔴 对齐只能发生在**写盘之前**:selfPublished 为真时 analysis.markdown 就是本次要
438
+ // 覆盖的那份文件,先写后读会读到刚打上新 id 的正文,旧 id 一个也留不下(见
439
+ // alignToPublishedBlocks 的说明)。这里正好是最后一个既拿到 blocks、又还没写过
440
+ // 任何文件的时刻,buildOutline 与 markBlocks 用的都是对齐后的 id。
441
+ //
442
+ // 没有块列表时**完全不进入**对齐:不读旧 Markdown、不记日志,行为与接对齐之前逐字节一致。
443
+ const blocks = Array.isArray(contentList) && contentList.length > 0
444
+ ? await alignToPublishedBlocks(splitBlocks(contentList), analysis.markdown, pdf.name, this.logger)
445
+ : undefined
446
+ const outlineBudgetBytes = state.settings.outlineBudgetBytes
447
+ outline = buildOutline(markdown, outlineBudgetBytes, blocks)
448
+ // 章节树文件带**版本头**:读端(revisions.documentView)据此判断盘上这份是不是
449
+ // 当前算法产出的,不是就按当前代码重建并覆盖 —— 否则改了层级规则也不会有一篇变样。
450
+ const outlineText = outlineFileText(outline, outlineBudgetBytes)
451
+ if (!selfPublished) {
452
+ await mkdir(analysis.dir, { recursive: true })
453
+ // 🔴 图片**不在这里落盘**,只算出「源 → 目标」的计划,交给 writeAnalysisBundle 与正文
454
+ // 一起提交 / 一起回滚。先直接覆盖图片再单独提交正文,正文一失败就留下「旧正文 +
455
+ // 新图片」的错位:同名文件被换掉,读者看到上一版的文字配这一版的图,而任何记录都
456
+ // 发现不了这件事(文件名、尺寸常常都一样)。
457
+ const materialized = await planMarkdownImages(markdown, markdownPath, analysis.markdown)
458
+ if (materialized.missingImages.length > 0) {
459
+ this.logger.warn(`dsh-paper: 解析结果引用的 ${materialized.missingImages.length} 张本地图片缺失(MinerU 服务端未落盘),已从发布副本剔除引用`)
460
+ }
461
+ // 正文回填(见 blocks-markdown.js):块的正文已经是源码,而 Markdown 里还是 MinerU
462
+ // 那一版。导出、注入会话给模型、检索索引读的都是这份 Markdown —— 不回填就会出现
463
+ // 「屏幕上源码、模型上下文里 OCR」两套文本。
464
+ const marked = markBlocks(materialized.markdown, blocks)
465
+ const rewritten = blocks === undefined
466
+ ? { markdown: marked.markdown, replaced: 0, skipped: 0, unknown: 0 }
467
+ : rewriteMarkdownBody(marked.markdown, blocks)
468
+ if (rewritten.replaced > 0) {
469
+ const kept = rewritten.skipped > 0 ? '(另有 ' + rewritten.skipped + ' 段含图表结构,按原样保留)' : ''
470
+ this.logger.info('dsh-paper: ' + pdf.name + ' 用源码正文回填 Markdown ' + rewritten.replaced + ' 段' + kept)
471
+ }
472
+ // 事务按 stage → commit 两段走:图片与正文都在 stage 里,任何一步失败都不会把
473
+ // 旧正文指到新图片上。
474
+ await writeAnalysisBundle(analysis, {
475
+ markdown: rewritten.markdown,
476
+ outline: outlineText, contentList,
477
+ }, { copies: materialized.copies })
478
+ outlineWritten = true
479
+ if (Array.isArray(contentList) && contentList.length > 0) contentPath = analysis.content
480
+ } else {
481
+ await readMarkdownBundle(analysis.markdown)
482
+ }
483
+ if (selfPublished && !await isReadable(analysis.outline)) {
484
+ await writeFile(analysis.outline, outlineText, 'utf8')
485
+ outlineWritten = true
486
+ }
487
+ finalMarkdownPath = analysis.markdown
488
+ outlinePath = analysis.outline
489
+ manifestPath = analysis.manifest
490
+ manifestPaths = { ...analysis, content: contentPath }
491
+ } catch (error) {
492
+ throw new Error(`无法把解析结果写入 ${analysis.dir}:${errorText(error)}`, { cause: error })
493
+ }
494
+ // 附带 `inherited`:这份 manifest 是冷归档记录**唯一**的元数据来源,写成空对象就等于把
495
+ // sourceDir / sourcePdfPath 抹掉(见上面 previous 的说明)。这里写全,后面的
496
+ // saveDocument 再写一遍也不会有第二个真相。
497
+ if (!selfPublished) {
498
+ await writePortableManifest(pdf, manifestPaths, inherited)
499
+ } else if (analysis.manifestReady !== true) {
500
+ try { await writePortableManifest(pdf, manifestPaths, inherited) } catch (error) {
501
+ this.logger.warn(`dsh-paper: 复用结果可读但无法写入便携 manifest:${errorText(error)}`)
502
+ }
503
+ }
504
+ // 🔴 目录头的输入身份只能在**所有输入都落定之后**补:身份取的是 Markdown 与块列表的
505
+ // mtime+size,而上面三步(正文 / 目录 / 块列表,以及 manifest)是依次提交的。
506
+ // 补不进去不算失败:下次读取发现身份不符会重建一次,结果一样。
507
+ if (outlineWritten) {
508
+ try {
509
+ await stampOutlineRevision({ markdownPath: finalMarkdownPath, outlinePath, contentPath })
510
+ } catch (error) {
511
+ this.logger.warn(`dsh-paper: 目录头的输入身份没能写入 ${outlinePath}:${errorText(error)}`)
512
+ }
513
+ }
514
+ const now = new Date().toISOString()
515
+ let document = {
516
+ ...options.portable?.metadata,
517
+ ...inherited,
518
+ // 目录元数据(arXiv/DOI 采集到的标题/作者/年份):入库时收下来,
519
+ // 供改名与引用导出使用。缺字段不挂,让「这条记录有哪些键」自己表达拿到了什么。
520
+ ...cleanRenameMetadata(options.metadata),
521
+ ...(options.metadata?.bibliography ? { bibliography: bibliographyOf(previous?.bibliography, options.metadata.bibliography) } : {}),
522
+ id: pdf.hash,
523
+ pdfName: pdf.name,
524
+ pdfPath: pdf.path,
525
+ pdfSize: pdf.size,
526
+ pdfMtimeMs: pdf.mtimeMs,
527
+ // 🔴 D128 之后 PDF 本体只在 runtime,原路径随即消失。用户工作区里那个文件夹是
528
+ // "配套 .md / Source/ / Thought.md 该放哪"的唯一答案,不记就再也推不出来。
529
+ //
530
+ // 只收 runtime 之外的目录:没显式来源时 add() 退回 dirname(pdfPath),而 retry 那条路
531
+ // 上那已经是 runtime 副本 —— 把它记下来等于凭空造一个"用户目录",比没有更糟。
532
+ // 判据与旁挂共用 isWithin,两处规则必须是同一个。
533
+ // 显式给了就覆盖继承的那个 —— 重新指一次文件夹等于重新绑定。
534
+ ...(typeof options.sourceDir === 'string' && options.sourceDir !== ''
535
+ && !isWithin(resolve(this.repository.root), resolve(options.sourceDir))
536
+ ? { sourceDir: options.sourceDir }
537
+ : {}),
538
+ ...(typeof options.sourcePdfPath === 'string' && options.sourcePdfPath !== ''
539
+ && !isWithin(resolve(this.repository.root), resolve(options.sourcePdfPath))
540
+ ? { sourcePdfPath: options.sourcePdfPath } : {}),
541
+ markdownPath: finalMarkdownPath,
542
+ outlinePath,
543
+ outlineTruncated: outline.truncated,
544
+ readyAt: now,
545
+ lastUsedAt: now,
546
+ hidden: false,
547
+ }
548
+ for (const key of previous?.clearedMetadata ?? []) {
549
+ if (['title', 'authors', 'year'].includes(key)) document[key] = key === 'authors' ? [] : ''
550
+ else if (document.bibliography && Object.hasOwn(document.bibliography, key)) document.bibliography[key] = ''
551
+ }
552
+ for (const [key, source] of Object.entries(previous?.metadataSources ?? {})) {
553
+ if (source?.provider !== 'manual') continue
554
+ if (['title', 'authors', 'year'].includes(key) && Object.hasOwn(previous, key)) document[key] = previous[key]
555
+ else if (previous.bibliography && Object.hasOwn(previous.bibliography, key)) {
556
+ document.bibliography ??= {}
557
+ document.bibliography[key] = previous.bibliography[key]
558
+ }
559
+ }
560
+ document = portableDocument(document, pdf, { markdownPath: finalMarkdownPath, outlinePath, manifestPath, contentPath })
561
+ const saved = await this.repository.saveDocument(document)
562
+ // 只回收**这次发布那个任务**的 scratch(见 cleanScratch 的说明);没有 jobId 的复用路径
563
+ // 只做「空了自己收掉」,绝不整层删。
564
+ await this.cleanScratch(pdf.hash, { outlines: true, jobId: options.jobId })
565
+ const hydrated = hydrateDocument(saved)
566
+ // 🔴 **入库不再往用户 PDF 目录写任何东西**(用户 2026-10-23 裁定)。
567
+ // 从前这里会旁挂一份同名 Markdown + 它引用的 images/,本意是"脱离插件也能读";
568
+ // 代价是每次入库都在用户自己的项目目录里留下派生文件,而这些文件的唯一正本
569
+ // 本来就躺在 `library/<documentId>/` 里。现在改为**手动**:文献库右键「存一份到论文文件夹」
570
+ // 走 /mirror 路由,点一次才写一次。
571
+ return hydrated
572
+ }
573
+
574
+ /**
575
+ * 回收这次发布用过的 scratch。
576
+ *
577
+ * 🔴 **只删属于自己的那一层**:`documents/<hash>/<job>/` 是每个任务自己的工作目录,而同 hash
578
+ * 的另一条通路(文献库解析 / 右栏独立解析)可能正在自己的 `<job>` 子目录里写 VLM 正文 ——
579
+ * 按整层 `documents/<hash>` 删会把对方正在写的输出端掉(实测:同 PDF 双入口并行时,
580
+ * 独立解析的 VLM 正文被删,恢复后不得不重跑,SDK 调用从 1 次变 2 次)。
581
+ *
582
+ * 所以规则是:给了 `jobId` 就只删那一个子目录;`documents/<hash>` 与 `outlines/<hash>`
583
+ * 这两层只在**自己已经空了**的时候才 `rmdir`(非空会失败,也就不删)。共同并发池不等于
584
+ * 可以删掉同 hash 别人的工作目录。
585
+ *
586
+ * @param {string} documentId 论文哈希。
587
+ * @param {{outlines?: boolean, jobId?: string}} [options]
588
+ */
589
+ async cleanScratch(documentId, { outlines = false, jobId } = {}) {
590
+ if (typeof jobId === 'string' && jobId !== '') await this.removeJobScratch(documentId, jobId)
591
+ const targets = [join(this.repository.root, 'documents', documentId)]
592
+ if (outlines) targets.push(join(this.repository.root, 'outlines', documentId))
593
+ for (const target of targets) {
594
+ try { await rmdir(target) } catch {}
595
+ }
596
+ }
597
+
598
+ /**
599
+ * One job's own scratch directory under `documents/<hash>/<job>/`.
600
+ *
601
+ * Both id parts come from `state.json`, which a user may have edited, so an unexpected
602
+ * shape yields `undefined` instead of a path — no removal, no traversal.
603
+ */
604
+ jobScratchDir(documentId, jobId) {
605
+ if (!/^[a-f0-9]{64}$/.test(String(documentId ?? ''))) return undefined
606
+ if (!/^job-[A-Za-z0-9._-]{1,80}$/.test(String(jobId ?? ''))) return undefined
607
+ return join(this.repository.root, 'documents', documentId, jobId)
608
+ }
609
+
610
+ /**
611
+ * Drop the scratch of one failed or abandoned job.
612
+ *
613
+ * Only `publishDocument`'s success path used to clean, so every task that failed (or was
614
+ * superseded by a retry) left its parse output on disk forever, under the plugin's
615
+ * runtime directory.
616
+ */
617
+ async removeJobScratch(documentId, jobId) {
618
+ const target = this.jobScratchDir(documentId, jobId)
619
+ if (target === undefined) return false
620
+ try {
621
+ await rm(target, { recursive: true, force: true })
622
+ return true
623
+ } catch (error) {
624
+ this.logger.warn(`dsh-paper job scratch cleanup: ${errorText(error)}`)
625
+ return false
626
+ }
627
+ }
628
+
629
+ /**
630
+ * Reclaim scratch directories no job record backs anymore, and return how many went.
631
+ *
632
+ * `compact()` trims terminal jobs to the most recent `MAX_TERMINAL_JOBS`, so a failed
633
+ * task older than that window loses the only record that named its scratch directory —
634
+ * nothing else could ever find it again. The job records still in state protect their
635
+ * directories, including the ones in flight (their record is written before parsing).
636
+ */
637
+ async pruneOrphanScratch() {
638
+ const state = await this.repository.snapshot()
639
+ const live = new Set(Object.values(state.jobs)
640
+ .filter(job => typeof job?.id === 'string' && typeof job?.documentId === 'string')
641
+ .map(job => `${job.documentId}/${job.id}`))
642
+ let removed = 0
643
+ let hashes
644
+ try {
645
+ hashes = await readdir(join(this.repository.root, 'documents'), { withFileTypes: true })
646
+ } catch (error) {
647
+ if (error?.code !== 'ENOENT') this.logger.warn(`dsh-paper scratch prune: ${errorText(error)}`)
648
+ return 0
649
+ }
650
+ for (const hash of hashes) {
651
+ if (!hash.isDirectory()) continue
652
+ for (const entry of await readdir(join(this.repository.root, 'documents', hash.name), { withFileTypes: true }).catch(() => [])) {
653
+ if (!entry.isDirectory()) continue
654
+ if (live.has(`${hash.name}/${entry.name}`)) continue
655
+ if (await this.removeJobScratch(hash.name, entry.name)) removed += 1
656
+ }
657
+ }
658
+ return removed
659
+ }
660
+
661
+ /**
662
+ * 记录一条已就绪任务。`deferCompaction` 给批量路径用:整目录扫描时逐篇 compact 会把整份
663
+ * state.json 重写 N 遍(并逐篇抢跨进程状态锁),改由调用方在批末统一整理一次。
664
+ */
665
+ async readyResult(pdf, document, sessionId, { deferCompaction = false } = {}) {
666
+ const job = {
667
+ id: `job-${randomUUID()}`,
668
+ documentId: pdf.hash,
669
+ pdfPath: pdf.path,
670
+ status: 'ready',
671
+ sessionId,
672
+ createdAt: new Date().toISOString(),
673
+ updatedAt: new Date().toISOString(),
674
+ }
675
+ await this.repository.update(state => { state.jobs[job.id] = job })
676
+ if (!deferCompaction) await this.repository.compact()
677
+ return { job, document }
678
+ }
679
+
680
+ async add(pdfPath, sessionId, { deferCompaction = false, metadata, sourceDir: inheritedSourceDir, sourcePdfPath: inheritedSourcePdfPath } = {}) {
681
+ // 🔴 **复制之前**取源目录:入库那一刻 PDF 就被复制进 runtime,此后记录里只剩副本路径,
682
+ // 谁也不记得用户当初把原件放在哪。旁挂导出(mirror-export)需要的正是这个目录,
683
+ // 而它只在"本次添加"这条链路上有意义 —— reparse 不传,所以重解析不写回(用户裁定)。
684
+ //
685
+ // 重试({@link PaperResolver#retry})**显式把它继承下来**:那条路的 pdfPath 已经是 runtime
686
+ // 副本,现算 dirname 只会得到一个"在 runtime 之内"的目录,被旁挂规则挡掉。
687
+ const sourceDir = typeof inheritedSourceDir === 'string' && inheritedSourceDir !== ''
688
+ ? inheritedSourceDir
689
+ : dirname(resolve(pdfPath))
690
+ const sourcePdfPath = isWithin(resolve(this.repository.root), resolve(pdfPath)) ? inheritedSourcePdfPath : resolve(pdfPath)
691
+ const batch = { deferCompaction, metadata, sourceDir, sourcePdfPath }
692
+ // D128:入库那一刻把 PDF 复制进 runtime,之后解析/重解析/页面图/导出一律用副本 ——
693
+ // 原文件被移走、改名、删除都不再影响这一篇。同哈希幂等,不重复拷贝(Q2-A)。
694
+ const inspected = await inspectPdf(pdfPath)
695
+ const state = await this.repository.snapshot()
696
+ // 复用链只剩一步本地探测(D127):runtime 里的文档记录。PDF 旁的 analysis/ 不再识别
697
+ // (旧位置不管 —— 不读、不迁、不删),都没命中才排队解析。
698
+ const existing = state.documents[inspected.hash] ?? await this.repository.archivedDocument(inspected.hash)
699
+ // 🔴 **主名跟着记录走,不跟着源文件名走**(D178)。一篇论文 9 个资产共用一个主名,
700
+ // 而记录里的 pdfName 是入库那一刻冻结的(reparse 也照抄它)。这里若用磁盘上的原名,
701
+ // 重复添加/重新扫描时一旦两者不同,就会把 PDF、Markdown、manifest 落到**另一套主名**下 ——
702
+ // 记录指向的那套于是缺块列表/译文/划线,症状是"这篇论文没有块列表,无法按块翻译"。
703
+ // 用户的 PDF 目录本身一个字节都不动,这里只是决定 runtime 副本叫什么。
704
+ const pdf = await storePdfCopy(this.repository.root, existing === undefined
705
+ ? inspected
706
+ : { ...inspected, name: existing.pdfName ?? inspected.name })
707
+ const resolvedExisting = hydrateDocument(existing)
708
+ if (resolvedExisting && await hasMarkdownBundle(resolvedExisting.markdownPath)) {
709
+ // D178:复用之前先把"另一套主名"下的资产搬回来。这一篇的资产可能在更早一次
710
+ // 跟着源文件名走的入库里劈开了(块列表/译文/划线落在另一个主名下),不搬回来的话
711
+ // publishDocument 找不到块列表,记录里就永远没有 contentPath —— 症状正是
712
+ // 「这篇论文没有块列表(旧产物或 MinerU 降级),无法按块翻译」。
713
+ // 只搬文件、不碰记录:紧接着的 publishDocument 会用这份记录重写 artifact。
714
+ await this.repairStem(resolvedExisting)
715
+ if (resolvedExisting && await hasMarkdownBundle(resolvedExisting.markdownPath)) {
716
+ const document = await this.publishDocument(pdf, resolvedExisting.markdownPath, { metadata, sourceDir, sourcePdfPath })
717
+ return this.readyResult(pdf, document, sessionId, batch)
718
+ }
719
+ }
720
+ const { job, document: concurrentDocument, created } = await this.createQueuedJob(pdf, sessionId, metadata, sourceDir, sourcePdfPath)
721
+ if (concurrentDocument) {
722
+ const document = await this.publishDocument(pdf, concurrentDocument.markdownPath, { metadata, sourceDir, sourcePdfPath })
723
+ return this.readyResult(pdf, document, sessionId, batch)
724
+ }
725
+ if (created) this.enqueue(job.id)
726
+ return { job }
727
+ }
728
+
729
+ // 旁挂的调用方只剩文献库的手动动作(index.js 的 /mirror 路由):入库不再写用户目录。
730
+ async createQueuedJob(pdf, sessionId, metadata, sourceDir, sourcePdfPath) {
731
+ const catalog = cleanRenameMetadata(metadata)
732
+ const bibliography = bibliographyOf(metadata?.bibliography, metadata)
733
+ if (Object.values(bibliography).some(Boolean)) catalog.bibliography = bibliography
734
+ return this.repository.update(async state => {
735
+ const document = hydrateDocument(state.documents[pdf.hash])
736
+ if (document && await hasMarkdownBundle(document.markdownPath)) return { document, created: false }
737
+ // 🔴 只认**解析**任务:解析与翻译共用 state.jobs,按 documentId 一抓就会抓到同篇的翻译任务,
738
+ // 于是 add() 以为「已经有解析在跑」、直接把它当解析任务返回 —— 用户拿到一条翻译任务的回执,
739
+ // 而解析队列里 pending=0,什么都没有真的开始(实测)。
740
+ const active = Object.values(state.jobs).find(job =>
741
+ job.documentId === pdf.hash && ['queued', 'running'].includes(job.status) && jobKindOf(job) === 'parse')
742
+ if (active) return { job: active, created: false }
743
+ const now = new Date().toISOString()
744
+ const job = {
745
+ id: `job-${randomUUID()}`,
746
+ documentId: pdf.hash,
747
+ pdfPath: pdf.path,
748
+ pdfName: pdf.name,
749
+ sessionId,
750
+ status: 'queued',
751
+ error: '',
752
+ createdAt: now,
753
+ updatedAt: now,
754
+ // 🔴 元数据**必须挂在任务记录上**:发布发生在 worker 里(job 是那时唯一还在的东西),
755
+ // add() 的局部变量到那时早就没了。空对象不挂,免得给每条任务记录平白加个空键。
756
+ ...(Object.keys(catalog).length > 0 ? { metadata: catalog } : {}),
757
+ // 同上:源目录也只有 add() 知道,发布时要用它决定"旁挂到哪"。空串不挂。
758
+ ...(typeof sourceDir === 'string' && sourceDir !== '' ? { sourceDir } : {}),
759
+ ...(typeof sourcePdfPath === 'string' && sourcePdfPath !== '' ? { sourcePdfPath } : {}),
760
+ }
761
+ state.jobs[job.id] = job
762
+ return { job, created: true }
763
+ })
764
+ }
765
+
766
+ async createJob(pdf, sessionId, status, error, { deferCompaction = false } = {}) {
767
+ const now = new Date().toISOString()
768
+ const job = {
769
+ id: `job-${randomUUID()}`,
770
+ documentId: pdf.hash,
771
+ pdfPath: pdf.path,
772
+ pdfName: pdf.name,
773
+ sessionId,
774
+ status,
775
+ error,
776
+ createdAt: now,
777
+ updatedAt: now,
778
+ }
779
+ await this.repository.update(state => { state.jobs[job.id] = job })
780
+ if (!deferCompaction) await this.repository.compact()
781
+ return job
782
+ }
783
+
784
+ async reparse(documentId, sessionId) {
785
+ const snapshot = await this.repository.snapshot()
786
+ const document = hydrateDocument(snapshot.documents[documentId] ?? await this.repository.archivedDocument(documentId))
787
+ if (!document) throw new Error('论文不存在')
788
+ // D128:重解析读 runtime 里那份副本。入库时复制过的话它已经在位;**D127 之前的旧记录**
789
+ // (pdfPath 还指用户论文目录、artifact 相对那个目录)没有副本,这里补一次入库拷贝 ——
790
+ // 少了这一步,发布阶段算 artifact 相对路径会以用户目录为基准,落在 runtime 的目标被判越界
791
+ // (「Markdown 不在论文目录内」),白跑一次 MinerU 才失败。补拷之后旧记录顺带迁到 runtime 布局。
792
+ // 主名用记录里冻结的原始文件名,副本文件名与它同源,这里显式取用免得多绕一层。
793
+ const inspected = await inspectPdf(document.pdfPath)
794
+ if (inspected.hash !== documentId) throw new Error('PDF 内容已变化,请作为新论文添加')
795
+ const pdf = await storePdfCopy(this.repository.root, { ...inspected, name: document.pdfName })
796
+ const result = await this.repository.update(state => {
797
+ // 同上:同篇的翻译任务不算「解析已经在跑」。
798
+ const active = Object.values(state.jobs).find(job =>
799
+ job.documentId === documentId && ['queued', 'running'].includes(job.status) && jobKindOf(job) === 'parse')
800
+ if (active) return { job: active, created: false }
801
+ const now = new Date().toISOString()
802
+ const job = {
803
+ id: `job-${randomUUID()}`,
804
+ documentId,
805
+ pdfPath: pdf.path,
806
+ pdfName: pdf.name,
807
+ sessionId,
808
+ status: 'queued',
809
+ error: '',
810
+ createdAt: now,
811
+ updatedAt: now,
812
+ // 🔴 **操作意图**必须留在任务记录上:重试那条路以前一律走 add(),而 add() 一看到
813
+ // 旧 Markdown 可读就按「已就绪」复用 —— 用户要求重做一次失败的重解析,拿到的却是
814
+ // 旧结果 + 一条成功回执。记录意图,重试才按原样再来一遍。
815
+ intent: 'reparse',
816
+ }
817
+ state.jobs[job.id] = job
818
+ return { job, created: true }
819
+ })
820
+ if (result.created) this.enqueue(result.job.id)
821
+ return { job: result.job }
822
+ }
823
+
824
+ enqueue(jobId) {
825
+ // 已经停止:不再接新任务。记录还留在 state 里(queued),下次启动的恢复链会接着跑。
826
+ if (this.stopping) return
827
+ this.pending.push(jobId)
828
+ this.drain()
829
+ }
830
+
831
+ /**
832
+ * 从队列里取出任务填满并发位。任务按入队顺序(FIFO)启动,单个任务失败不拖累其他任务。
833
+ * 提交额度不在这里取:额度是"每次远端提交"的资源,由 {@link PaperResolver#process} 在调用
834
+ * 远端之前逐个获取,否则一个任务算两次提交(VLM + pipeline)时会把限流算漏。
835
+ */
836
+ drain() {
837
+ if (this.stopping || this.draining) return
838
+ this.draining = true
839
+ try {
840
+ while (this.pending.length > 0 && this.active < this.maxConcurrent) {
841
+ const jobId = this.pending.shift()
842
+ this.active += 1
843
+ this.process(jobId).catch(error => {
844
+ this.logger.error(`dsh-paper queue: ${error?.stack ?? error}`)
845
+ }).finally(() => {
846
+ this.active -= 1
847
+ // 独立解析与解析任务抢同一个并发位:先喂**已经等了更久的**那个队列。少了这一拍,
848
+ // 只要任务队列一直有货,右栏「解析」Tab 那批就永远排不上。
849
+ this.pumpSlots()
850
+ this.drain()
851
+ this.settleIdle()
852
+ })
853
+ }
854
+ } finally {
855
+ this.draining = false
856
+ this.settleIdle()
857
+ }
858
+ }
859
+
860
+ settleIdle() {
861
+ if (this.draining || this.active > 0 || this.pending.length > 0 || this.slotWaiters.length > 0) return
862
+ const waiters = this.idleWaiters
863
+ this.idleWaiters = []
864
+ for (const resolve of waiters) resolve()
865
+ }
866
+
867
+ /**
868
+ * 取一个**解析并发位**并在它之下跑 `task`;独立解析(右栏「解析」Tab)用它。
869
+ *
870
+ * 🔴 与解析任务共用同一本账(`active` / `maxConcurrent`),不是另开一份计数:用户裁定
871
+ * 「解析并发本身要和文献库的解析共用」。所以两处同时在飞的篇数之和永远不超过上限。
872
+ * 额度({@link SubmissionLimiter})同理由调用方走 `this.limiter.acquire()` —— 那是
873
+ * "打给 MinerU 的提交频次",与并发位是两种资源,都要共用。
874
+ *
875
+ * 等待顺序是 FIFO:先到的先拿位,不插队。
876
+ *
877
+ * @template T
878
+ * @param {() => Promise<T>} task
879
+ * @returns {Promise<T>}
880
+ */
881
+ async runSlot(task) {
882
+ if (this.active < this.maxConcurrent) {
883
+ this.active += 1
884
+ } else {
885
+ await new Promise(resolve => this.slotWaiters.push(resolve))
886
+ // 被 pumpSlots 叫醒时它已经替我们占好了位(active 已加过),这里只负责还。
887
+ }
888
+ try {
889
+ return await task()
890
+ } finally {
891
+ this.active -= 1
892
+ this.pumpSlots()
893
+ this.drain()
894
+ this.settleIdle()
895
+ }
896
+ }
897
+
898
+ /**
899
+ * 把等待中的独立解析放行到并发位满为止。与 {@link PaperResolver#drain} 同形:
900
+ * 每放行一个就把 `active` 加一,等位的任务拿到 Promise 后直接开跑。
901
+ */
902
+ pumpSlots() {
903
+ while (this.slotWaiters.length > 0 && this.active < this.maxConcurrent) {
904
+ const resolve = this.slotWaiters.shift()
905
+ this.active += 1
906
+ resolve()
907
+ }
908
+ }
909
+
910
+ async process(jobId) {
911
+ // 已经关闭:连状态都不碰("旧实例还在写"正是关闭要堵的那件事)。
912
+ if (this.closed) return
913
+ /**
914
+ * 领取这条任务(`queued` → `running`),**领取成功才继续解析**。
915
+ *
916
+ * 🔴 判据必须是「这次调用把状态从 queued 改成了 running」,不能是「改完之后状态是不是
917
+ * running」。后者读的是自己刚写进去的值:两个宿主(runtime 与状态按 $DSH_HOME 共享)
918
+ * 抢同一条任务时,先到的那次把它置成 running,后到的那次在锁内看到「已经是 running」
919
+ * 就直接跳过状态更新 —— 但 `job` 拿的是状态对象**引用**,`job.status` 此刻同样是
920
+ * `'running'`,于是那个守卫判过,两边都去提交 MinerU。实测复现:同一条任务产生 4 次
921
+ * 提交调用(两边各跑 vlm + pipeline),重复计费且并发覆盖产物。
922
+ *
923
+ * 所以由锁内回调显式回一个「领到了」的布尔值,锁外只认它。
924
+ */
925
+ let job
926
+ let claimed = false
927
+ await this.repository.update(state => {
928
+ job = state.jobs[jobId]
929
+ if (!job || job.status !== 'queued') return
930
+ job.status = 'running'
931
+ job.error = ''
932
+ job.updatedAt = new Date().toISOString()
933
+ claimed = true
934
+ })
935
+ if (!claimed) return
936
+ // An attempt's outcome travels with the next state write instead of taking one of its
937
+ // own. A single task used to rewrite the whole `state.json` four times (running flip,
938
+ // attempt record, attempt outcome, terminal state), and on a batch import that is the
939
+ // dominant per-task cost. The attempt record itself is still written before the remote
940
+ // call, so "took a submission slot but never submitted" keeps its crash semantics.
941
+ let settledAttempt
942
+ const settlePrevious = active => {
943
+ if (settledAttempt === undefined) return
944
+ const previous = active.attempts?.at(-1)
945
+ if (previous) Object.assign(previous, settledAttempt)
946
+ settledAttempt = undefined
947
+ }
948
+ try {
949
+ const state = await this.repository.snapshot()
950
+ // 解析只有一条路:插件自存 Key 驱动的本地 SDK 桥接。Key 没录入时**不静默**、也不去
951
+ // 起一个注定失败的 uvx —— 直接失败并指向录入位置,任务记录里留得下这条原因。
952
+ const sdkConfig = this.sdkConfig()
953
+ if (sdkConfig === null) {
954
+ throw new Error('MinerU 未配置:请在「插件 → dsh-paper」详情页录入 MinerU API Key')
955
+ }
956
+ let markdownPath
957
+ let contentList
958
+ const requireContentList = await isReadable(analysisPathsOf(this.repository.root, { hash: job.documentId, name: job.pdfName }).content)
959
+ const failures = []
960
+ // vlm 优先、pipeline 兜底(顺序不动)。D134 实测过:两种模型的云端结果 ZIP **都带块列表**
961
+ // (`<任务UUID>_content_list.json`),所以顺序与能不能翻译无关;vlm 的 Markdown 更好看,留它在前。
962
+ const MODELS = ['vlm', 'pipeline']
963
+ for (const model of MODELS) {
964
+ const outputDir = scratchJobDir(this.repository.root, job.documentId, job.id, model)
965
+ await mkdir(outputDir, { recursive: true })
966
+ // 提交额度先取后记账:等待额度期间还没有提交给远端,此时宿主退出,该任务没有 attempt
967
+ // 记录,下次启动会按"从未开始"重新排队(见 recoverInterruptedJobs),不会重复计费。
968
+ await this.limiter.acquire()
969
+ await this.repository.update(current => {
970
+ const active = current.jobs[jobId]
971
+ if (!active) return
972
+ settlePrevious(active)
973
+ active.model = model
974
+ // 文案不带模型名(顺序会变):说清"上一个失败了,正在换这个"即可。
975
+ active.error = failures.length > 0 ? `解析失败,正在改试 ${model}:${failures[0]}`.slice(0, 500) : ''
976
+ active.attempts ??= []
977
+ active.attempts.push({ model, status: 'running', startedAt: new Date().toISOString() })
978
+ active.updatedAt = new Date().toISOString()
979
+ })
980
+ try {
981
+ contentList = undefined
982
+ const parse = this.sdkParse ?? parseWithConfiguredMineruSdk
983
+ const result = await parse({
984
+ pdfPath: job.pdfPath,
985
+ outputDir,
986
+ model,
987
+ timeoutMs: state.settings.parseTimeoutMs,
988
+ language: state.settings.parseLanguage,
989
+ ocr: state.settings.parseOcr,
990
+ }, { config: sdkConfig })
991
+ markdownPath = await materializeMineruResult(result, outputDir, {
992
+ logger: this.logger,
993
+ fetch: this.fetch,
994
+ onContentList: list => { contentList = list },
995
+ requireContentList,
996
+ })
997
+ settledAttempt = { status: 'ready', finishedAt: new Date().toISOString() }
998
+ break
999
+ } catch (error) {
1000
+ const text = String(error?.message ?? error)
1001
+ const message = (error?.code !== undefined && !text.includes(String(error.code)) ? `${text}(错误码 ${error.code})` : text).slice(0, 500)
1002
+ failures.push(message)
1003
+ // 真限流时别让兜底的那一枪紧跟着撞上同一堵墙:先全局冷却,后面的提交(含别的任务)
1004
+ // 在 acquire() 里等冷却走完。冷却后本任务继续试下一个模型,无需人工重试。
1005
+ if (isRateLimitError(error)) {
1006
+ this.limiter.penalize()
1007
+ this.logger.warn(`dsh-paper: MinerU 限流(429),全部提交冷却 ${RATE_LIMIT_COOLDOWN_MS / 1000}s:${message.slice(0, 200)}`)
1008
+ }
1009
+ settledAttempt = { status: 'failed', error: message, finishedAt: new Date().toISOString() }
1010
+ }
1011
+ }
1012
+ if (!markdownPath) {
1013
+ // 逐条报出**试过哪几个模型、各自报什么错**,顺序变了也不会说反。
1014
+ const detail = MODELS.map((model, index) => `${model} 失败:${failures[index] ?? '未知错误'}`).join(';')
1015
+ throw new Error(detail)
1016
+ }
1017
+ // 解析成功但**没有块列表**:翻译会一直失败(「这篇论文没有块列表」)。留一行日志,
1018
+
1019
+ const pdf = await inspectPdf(job.pdfPath)
1020
+ // sourceDir 随任务记录一起带下来(round-trip 里 `job.pdfPath` 已经是 runtime 副本,
1021
+ // 不顺着记录带下来,这篇就会永远失去「当初在用户工作区哪个文件夹」这条线索)。
1022
+ // 🔴 记下来 ≠ 写盘:publishDocument 只把这个值写进记录字段,一个字节都不写用户目录 ——
1023
+ // 往源文件夹放副本的只有文献库右键「存一份到论文文件夹」(/mirror)那一动作。
1024
+ // 🔴 收尾期间被关闭了:结果不写回(发布 = 往共享 state 写正文与记录,正是要挡的那一步)。
1025
+ if (this.closed) throw new Error('论文插件已停止,本次解析结果不再写入;下次启动会重新解析')
1026
+ // arXiv 源码优先(默认关):只在开关打开且本次拿到了块列表时尝试。
1027
+ // 任何一环不成立,applyTexSource 返回 null,这里就还是原来那一份 contentList。
1028
+ let finalContentList = contentList
1029
+ let texReport = null
1030
+ if (state.settings.texSourceEnabled === true && Array.isArray(contentList) && contentList.length > 0) {
1031
+ const enhanced = await this.applyTexSource({ job, contentList, pdf })
1032
+ if (enhanced !== null) {
1033
+ finalContentList = enhanced.list
1034
+ texReport = enhanced.report
1035
+ }
1036
+ }
1037
+ const document = await this.publishDocument(pdf, markdownPath, { contentList: finalContentList, freshParse: true, metadata: job.metadata, sourceDir: job.sourceDir, sourcePdfPath: job.sourcePdfPath, jobId: job.id })
1038
+ // 旁挂源码分析:不进 content.json,只在同目录留一份「这次为什么用/没用源码」。
1039
+ // 写失败不影响解析结果 —— 它只是给人看的凭据。
1040
+ if (texReport !== null) {
1041
+ try {
1042
+ const analysis = analysisPathsOf(this.repository.root, pdf)
1043
+ const reportPath = analysis.markdown.replace(/\.md$/, '.tex-analysis.json')
1044
+ await writeFile(reportPath, JSON.stringify({ analyzedAt: new Date().toISOString(), ...texReport }, null, 2), 'utf8')
1045
+ } catch (error) {
1046
+ this.logger.warn('dsh-paper tex: 写入源码分析旁挂失败:' + errorText(error))
1047
+ }
1048
+ }
1049
+ // D67:发布成功即触发自动翻译。fire-and-forget —— 上面构造里说过为什么不能在这里等。
1050
+ // 回调抛错只记一行:解析已经成功落地,翻译起不来不该把这篇论文报成解析失败。
1051
+ // D156:解析完成后按元数据改名。
1052
+ // 🔴 排在 onPublished **之外**:改名与自动翻译是两件独立的事,而自动翻译默认是关的
1053
+ // (config.autoTranslateOnParse 才开)。塞进 onPublished 会让"没开自动翻译"顺带把改名也关掉。
1054
+ // 回调抛错只记一行:解析已经成功落地,改名失败不该把这篇论文报成解析失败。
1055
+ if (this.onRenamed !== null) {
1056
+ try {
1057
+ await this.onRenamed({ document, pdf, sessionId: job.sessionId, job, metadata: job.metadata })
1058
+ } catch (error) {
1059
+ this.logger.warn(`dsh-paper rename: ${errorText(error)}`)
1060
+ }
1061
+ }
1062
+ if (this.onPublished !== null) {
1063
+ try {
1064
+ await this.onPublished({ document, pdf, sessionId: job.sessionId, job })
1065
+ } catch (error) {
1066
+ this.logger.warn(`dsh-paper auto-translate: ${errorText(error)}`)
1067
+ }
1068
+ }
1069
+ await this.repository.update(current => {
1070
+ const active = current.jobs[jobId]
1071
+ if (!active) return
1072
+ settlePrevious(active)
1073
+ // 成功就清掉 job.error:VLM 失败后 pipeline 成功的任务不该把失败文案留在
1074
+ // ready 记录上(逐次尝试的失败原因仍保留在 attempts 里)。
1075
+ Object.assign(active, { status: 'ready', documentId: document.id, error: '', updatedAt: new Date().toISOString() })
1076
+ })
1077
+ await this.repository.compact()
1078
+ } catch (error) {
1079
+ // 关闭之后连失败状态也不再写:那条记录留给下次启动的恢复链去判中断/重试。
1080
+ if (this.closed) {
1081
+ this.logger.warn(`dsh-paper stop: 任务 ${jobId} 在关闭后收尾,结果未写入(${errorText(error)})`)
1082
+ return
1083
+ }
1084
+ await this.repository.update(state => {
1085
+ const current = state.jobs[jobId]
1086
+ if (!current) return
1087
+ settlePrevious(current)
1088
+ current.status = 'failed'
1089
+ current.error = String(error?.message ?? error).slice(0, 500)
1090
+ current.updatedAt = new Date().toISOString()
1091
+ })
1092
+ // The success path is not the only one that needs cleaning: a task that ends failed
1093
+ // — or that nobody ever retries — used to leave its parse output under
1094
+ // `documents/<hash>/<job>/` forever.
1095
+ await this.removeJobScratch(job.documentId, job.id)
1096
+ await this.repository.compact()
1097
+ }
1098
+ }
1099
+
1100
+ async retry(jobId) {
1101
+ const state = await this.repository.snapshot()
1102
+ const job = state.jobs[jobId]
1103
+ // A job id the sidebar still shows may already have been trimmed out of the terminal
1104
+ // window by `compact()`; that is a 404 for the caller, not an unexpected 500 with a
1105
+ // stack in the host log (index.js only logs stacks for 5xx).
1106
+ if (!job) {
1107
+ const error = new Error('任务不存在或已超出任务记录保留窗口')
1108
+ error.status = 404
1109
+ throw error
1110
+ }
1111
+ if (!RETRYABLE_JOB_STATUSES.includes(job.status)) {
1112
+ const error = new Error('该任务当前不能重试')
1113
+ error.status = 409
1114
+ throw error
1115
+ }
1116
+ // 重试 = 当作从未解析过:清掉本任务自己的旧临时输出,重新走完整的 VLM → pipeline,
1117
+ // 不读取旧临时目录里的残留结果(只删本任务子目录,不影响同哈希其他进行中任务)。
1118
+ await this.removeJobScratch(job.documentId, job.id)
1119
+ // 🔴 **把源目录一起带下去**:job.sourceDir 记的是用户当初选的那个目录,而 job.pdfPath 早已
1120
+ // 是 runtime 副本 —— 照 `add(job.pdfPath)` 那样现算 dirname 只会得到 runtime 内部的路径,
1121
+ // 被 `isWithin` 判据挡掉,于是重试成功后这篇**永远失去源目录**(「存一份到论文文件夹」
1122
+ // 与源目录绑定都靠它)。老记录没有这个字段时留空,行为与加它之前逐字一致。
1123
+ const sourceDir = typeof job.sourceDir === 'string' && job.sourceDir !== '' ? job.sourceDir : undefined
1124
+ // 🔴 **按原意图重试**:这是一次强制重解析(reparse)留下的失败任务时,重试必须真的再解析
1125
+ // 一遍。走 add() 的话,只要旧正文还读得出来就会被判成「已就绪」直接复用 —— 用户点重试,
1126
+ // 拿到的是旧结果和一条成功回执(实测:SDK 调用数仍为 2,替代任务却立即 ready)。
1127
+ // 老记录没有 intent,一律按原来的 add() 走,行为与加这个字段之前逐字一致。
1128
+ const result = job.intent === 'reparse'
1129
+ ? await this.reparse(job.documentId, job.sessionId)
1130
+ : await this.add(job.pdfPath, job.sessionId, {
1131
+ ...(sourceDir === undefined ? {} : { sourceDir }),
1132
+ sourcePdfPath: job.sourcePdfPath,
1133
+ // 🔴 首次解析失败时,job.metadata 是**唯一**采集到的那份书目事实(题名/作者/年份/DOI):
1134
+ // 不继承它,重试成功后这篇只能退回文件名或正文猜测。只在库里**还没有这条记录**时继承 ——
1135
+ // 记录已经在(可能是人工改过的)就以记录 / manifest 为准,别让旧任务的事实盖掉人工值。
1136
+ ...(job.metadata !== undefined && job.metadata !== null
1137
+ && state.documents[job.documentId] === undefined
1138
+ && await this.repository.archivedDocument(job.documentId) === undefined
1139
+ ? { metadata: job.metadata }
1140
+ : {}),
1141
+ })
1142
+ await this.repository.update(current => {
1143
+ const retried = current.jobs[jobId]
1144
+ if (!retried || result.job.id === jobId) return
1145
+ retried.status = 'retried'
1146
+ retried.replacementJobId = result.job.id
1147
+ retried.updatedAt = new Date().toISOString()
1148
+ })
1149
+ await this.repository.compact()
1150
+ return result
1151
+ }
1152
+ }