@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
@@ -0,0 +1,480 @@
1
+ /**
2
+ * 把一篇论文的**全部资产**按新主名改名(D156)。
3
+ *
4
+ * 🔴 **为什么这不是「改一个文件名」**:本插件里 `pdfName` 同时是 9 个资产的主名
5
+ * (见 store-paths.js),所以改名 = 9 个文件搬家 **加** 三处记录同步
6
+ * (state.json 的文档记录、manifest 的 `pdfNameAtParse`、冷归档记录)。
7
+ * 少同步任何一处,下次读盘就会把名字"读回"旧值(portable.js 的 readDocumentManifest
8
+ * 会用 manifest 里的 `pdfNameAtParse` **覆盖**记录上的 pdfName)。
9
+ *
10
+ * 🔴 **只动 runtime 里的资产**(D127/D128):入库那一刻 PDF 已复制进 runtime,
11
+ * 用户论文目录一个字节都不动。
12
+ *
13
+ * 🔴 **热记录与冷归档记录都能改**(见 {@link recordOf}):文献库里列得出的论文不都躺在
14
+ * `state.documents` 里 —— `compact()` 会把长期没用的挪进 `archive/`。冷记录没有 state 里
15
+ * 的文档条目可提交,所以那条路只写 manifest 与冷记录(外加任务记录的路径同步)。
16
+ */
17
+ import { randomUUID } from 'node:crypto'
18
+ import { access, readFile, rename as renameFile, rm, writeFile } from 'node:fs/promises'
19
+ import { dirname, join } from 'node:path'
20
+ import { buildStem, cleanRenameMetadata, disambiguateStem, isSameStem, sanitizeStemInput, splitAuthors } from './rename.js'
21
+ import { storePathsOf } from './store-paths.js'
22
+ import { documentPaths, hydrateDocument } from './portable.js'
23
+ import { replaceStateFile } from './storage.js'
24
+
25
+ /** 主名派生出来的资产扩展名(与 storePathsOf 的成员一一对应)。 */
26
+ const STEM_SUFFIXES = ['.pdf', '.md', '.outline.md', '.content.json', '.dsh-paper.json', '.translation.json', '.reader.json', '.discussion.json', '.item.json']
27
+
28
+ /**
29
+ * 把一次改名**写进文档记录**(纯函数,不改文件系统)。
30
+ *
31
+ * 抽出来是为了让"哪些字段必须跟着主名走"只有一份:文档记录上任何从主名派生的字段
32
+ * 漏改一个,就有某个读取方会指向已不存在的旧文件。
33
+ *
34
+ * @param {object} record state.documents 里的记录
35
+ * @param {{nextName: string, nextPdfPath: string, toStem: string, force: boolean, metadata?: object, typedTitle?: string}} patch
36
+ */
37
+ function applyRenameToDocument(record, { nextName, nextPdfPath, toStem, force, metadata, typedTitle }) {
38
+ record.pdfName = nextName
39
+ record.pdfPath = nextPdfPath
40
+ /**
41
+ * 🔴 **键入的名字要用作显示名**(D181)。文献库列表与详情栏显示的是 `title` 而不是 `pdfName`
42
+ * (见 index.js 的 libraryItems),只改文件名不改 title 的话,用户点了确认、盘上也改了,
43
+ * 界面上却一个字都不动 —— 实测就是这条被当成"重命名失败"。
44
+ *
45
+ * 只覆盖 **typed** 这一路:自动改名(D156)改的是文件名,标题仍应以期刊/arXiv 登记的那份为准,
46
+ * 拿"作者 - 年份 - 标题"去覆盖 title 会把引用元数据一起弄脏。
47
+ * 空的键入值不会走到这里(上层已按 invalid-name 拒绝)。
48
+ */
49
+ if (typeof typedTitle === 'string' && typedTitle !== '') record.title = typedTitle
50
+ // 🔴 顺手把**这次用到的元数据**落进记录。改名的三级回退(目录 → PDF → 正文标题)
51
+ // 是唯一读过这些字段的地方,读到了却不留,下次还得重新 spawn 一次 uvx 去读 PDF,
52
+ // 而且冷归档时记录里的 title 会丢(sidecar 的 writeArchivedRecord 只留
53
+ // {id, pdfPath, artifact},title 只能靠 manifest 活下来)。
54
+ // 空值**不覆盖**已有值:某一级没拿到作者,不该把记录里原有的作者抹掉。
55
+ const merged = cleanRenameMetadata(metadata)
56
+ if (merged.title !== undefined) record.title = merged.title
57
+ if (merged.authors !== undefined) record.authors = merged.authors
58
+ if (merged.year !== undefined) record.year = merged.year
59
+ // 🔴 artifact 存的是**相对** pdfPath 所在目录的路径(D127),目录没变,只换主名。
60
+ // 少改任何一项,readerPathOf / translationPathOf 那些从 markdownPath 派生路径的函数
61
+ // 都会指向已经不存在的旧文件。
62
+ if (record.artifact?.kind === 'sidecar') {
63
+ record.artifact.markdownPath = toStem + '.md'
64
+ record.artifact.outlinePath = toStem + '.outline.md'
65
+ record.artifact.manifestPath = toStem + '.dsh-paper.json'
66
+ if (typeof record.artifact.contentPath === 'string' && record.artifact.contentPath !== '') {
67
+ record.artifact.contentPath = toStem + '.content.json'
68
+ }
69
+ }
70
+ record.renamedBy = force ? 'manual' : 'auto'
71
+ record.renamedAt = new Date().toISOString()
72
+ }
73
+
74
+ /** 文档 id 的形状:冷归档的路径按 64 位十六进制拼,别的形状根本没有冷记录可找。 */
75
+ const DOCUMENT_ID_SHAPE = /^[a-f0-9]{64}$/
76
+
77
+ /**
78
+ * 把一个文件的**原始字节**快照下来。`undefined` 表示原本没有这个文件。
79
+ *
80
+ * 🔴 快照必须是字节级的,不能"记住记录对象、失败时再重写一遍":重写走的是**合并**语义
81
+ * (`writePortableManifest` 会把本次新增的 `title` / `renamedBy` / `renamedAt` 合进旧 metadata),
82
+ * 于是"回滚"之后旧的留下来了、新的也留下来了 —— 实测复现:改名报失败,manifest 里却多了
83
+ * 一个 `renamedBy: 'manual'` 和新的时间戳,下一次解析的自动改名因此被当成"用户手动改过"。
84
+ */
85
+ async function snapshotBytes(path) {
86
+ try {
87
+ return await readFile(path)
88
+ } catch (error) {
89
+ if (error?.code === 'ENOENT') return undefined
90
+ throw error
91
+ }
92
+ }
93
+
94
+ /** 把快照原样写回(`undefined` = 原本没有 → 删掉,不留一个空壳文件)。 */
95
+ async function restoreBytes(path, bytes) {
96
+ if (bytes === undefined) {
97
+ await rm(path, { force: true })
98
+ return
99
+ }
100
+ const temporary = join(dirname(path), `.restore.${randomUUID()}.tmp`)
101
+ try {
102
+ await writeFile(temporary, bytes, { flag: 'wx', mode: 0o600 })
103
+ await replaceStateFile(temporary, path)
104
+ } catch (error) {
105
+ await rm(temporary, { force: true }).catch(() => {})
106
+ throw error
107
+ }
108
+ }
109
+
110
+ /**
111
+ * 改名会动两处**记录**,失败时都要能原样退回:
112
+ * - manifest(`<主名>.dsh-paper.json`)—— 它随主名搬家,所以快照必须取**搬之前**那份;
113
+ * - 冷归档记录(`archive/<id>.json`)—— 路径固定,冷归档论文唯一的定位入口。
114
+ *
115
+ * @returns {Promise<{manifest?: {path: string, bytes?: Buffer}, archive?: {path: string, bytes?: Buffer}}>}
116
+ * 缺某个键 = 这一处没有可恢复的对象(非 sidecar、或 id 不是哈希形状)。
117
+ */
118
+ async function snapshotRecords(repository, document) {
119
+ const snapshot = {}
120
+ // 🔴 这里**不许吞异常**。读不出来就意味着"失败时退不回原样",而改名一旦开始就会覆盖
121
+ // manifest 与冷记录 —— 此时唯一诚实的做法是**这次不改名**(见调用点的说明)。
122
+ // 只有两种情况是正常的、不需要快照:非 sidecar 记录(没有 manifest 可写)、
123
+ // 以及 id 不是哈希形状(根本没有冷归档文件)。
124
+ const manifestPath = documentPaths(document).manifestPath
125
+ if (typeof manifestPath === 'string' && manifestPath !== '') {
126
+ snapshot.manifest = { path: manifestPath, bytes: await snapshotBytes(manifestPath) }
127
+ }
128
+ if (DOCUMENT_ID_SHAPE.test(document.id)) {
129
+ const archivePath = repository.archivePath(document.id)
130
+ snapshot.archive = { path: archivePath, bytes: await snapshotBytes(archivePath) }
131
+ }
132
+ return snapshot
133
+ }
134
+
135
+ /** @returns {Promise<Error[]>} 没能恢复的项(调用方并进抛出的错误,不静默吞掉)。 */
136
+ async function restoreRecords(snapshot) {
137
+ const failures = []
138
+ for (const target of [snapshot?.manifest, snapshot?.archive]) {
139
+ if (!target) continue
140
+ try { await restoreBytes(target.path, target.bytes) } catch (error) { failures.push(error) }
141
+ }
142
+ return failures
143
+ }
144
+
145
+ /** 恢复失败时的附言:一句"没复原",比把失败藏起来强。 */
146
+ function restoreDetail(failures) {
147
+ if (failures.length === 0) return ''
148
+ return '(另有 ' + failures.length + ' 项记录未能恢复:' + failures.map(item => String(item?.message ?? item)).join(';') + ')'
149
+ }
150
+
151
+ /**
152
+ * 按 id 取一条记录:**热表优先,冷归档兜底**。
153
+ *
154
+ * 🔴 必须兜冷归档:`compact()` 会把长期没用的论文挪进 `archive/`,而文献库视图仍然列得出
155
+ * 它们(`archivedDocuments()` 会把冷记录拼回列表)。只查热表的话,对这样一篇改名会返回
156
+ * `not-found`,调用方顺势把它当成「文件名本来就对」—— 用户看到「已更新显示名」,盘上一个
157
+ * 字节都没变。冷记录里的标题等元数据在 manifest 上,`archivedDocument` 已经合回来了。
158
+ *
159
+ * @returns {Promise<{raw: object|undefined, cold: boolean}>} `cold` 表示记录来自冷归档 ——
160
+ * 于是没有「提交 state 里的文档记录」这一步可做,只写 manifest 与冷记录。
161
+ */
162
+ async function recordOf(repository, state, id) {
163
+ const hot = state.documents?.[id]
164
+ if (hot !== undefined) return { raw: hot, cold: false }
165
+ if (!DOCUMENT_ID_SHAPE.test(id)) return { raw: undefined, cold: true }
166
+ return { raw: await repository.archivedDocument(id), cold: true }
167
+ }
168
+
169
+ /** 文件存在吗(只判存在,不读内容)。 */
170
+ async function exists(path) {
171
+ try { await access(path); return true } catch { return false }
172
+ }
173
+
174
+ /**
175
+ * 列出「旧主名 → 新主名」需要搬的文件对,只包含**真实存在**的那些。
176
+ *
177
+ * 存在的才搬:一篇论文可能没有译文、没有划线、没有块列表 —— 给不存在的文件凑一条
178
+ * 搬移计划只会让搬迁在第一个 ENOENT 上失败。
179
+ *
180
+ * @param {string} dir 论文目录
181
+ * @param {string} fromStem 当前主名
182
+ * @param {string} toStem 目标主名
183
+ */
184
+ async function movePlan(dir, fromStem, toStem) {
185
+ const pairs = []
186
+ for (const suffix of STEM_SUFFIXES) {
187
+ const from = join(dir, fromStem + suffix)
188
+ const to = join(dir, toStem + suffix)
189
+ if (from === to) continue
190
+ if (await exists(from)) pairs.push({ from, to })
191
+ }
192
+ return pairs
193
+ }
194
+
195
+ /**
196
+ * 执行改名。顺序刻意是三段,每一段都为下一段兜底:
197
+ *
198
+ * 1. **搬文件**(9 个资产)—— 失败就把已搬的搬回去,此时记录还没动,完全复原;
199
+ * 2. **写 manifest 与冷归档** —— 失败同样只回滚文件,state 仍是旧名;
200
+ * 3. **原子提交 state**(文档记录 + 该篇的全部任务记录)—— 这是唯一一次"对外可见"的改名。
201
+ *
202
+ * 🔴 第 2 步必须在第 3 步**之前**:反过来会造出「state 已是新名、盘上还是旧名」的双真相
203
+ * (归档写失败时 catch 只回滚文件,不回滚已提交的 state)—— 实测复现过,现在有回归用例钉住。
204
+ *
205
+ * @param {{repository: object, documentId: string, metadata?: object, stem?: string, logger?: object, force?: boolean}} deps
206
+ * `stem` 是**用户直接键入**的主名(D181):给了它就跳过 `buildStem`,其余流程(搬家、回滚、
207
+ * manifest/归档、任务记录同步)原样复用。不给则维持「按元数据算名字」。
208
+ * @returns {Promise<{renamed: boolean, from: string, to: string, reason: string}>}
209
+ * `reason` 取值:`ok` / `manual` / `no-title` / `same` / `no-files` / `not-found` / `invalid-id` /
210
+ * `no-name`,以及键入路径专属的 `invalid-name` / `name-too-long` / `occupied`。
211
+ */
212
+ export async function renameDocument({ repository, documentId, metadata, stem: requestedStem, logger, force = false }) {
213
+ const id = typeof documentId === 'string' ? documentId : ''
214
+ if (id === '') return { renamed: false, from: '', to: '', reason: 'invalid-id' }
215
+ return repository.withDocumentWrite(id, () => renameDocumentLocked({ repository, id, metadata, requestedStem, logger, force }))
216
+ }
217
+
218
+ async function renameDocumentLocked({ repository, id, metadata, requestedStem, logger, force }) {
219
+ const state = await repository.snapshot()
220
+ const { raw, cold } = await recordOf(repository, state, id)
221
+ if (!raw) return { renamed: false, from: '', to: '', reason: 'not-found' }
222
+ const document = hydrateDocument(raw)
223
+ const currentName = typeof document.pdfName === 'string' ? document.pdfName : ''
224
+ if (currentName === '') return { renamed: false, from: '', to: '', reason: 'no-name' }
225
+ /**
226
+ * 两处**记录**的原始字节(manifest + 冷记录),失败时按它原样写回。
227
+ *
228
+ * 🔴 必须在任何一个字节落盘之前取:manifest 会随主名一起搬家,搬完就再也读不到旧那份;
229
+ * 而恢复必须是字节级的 —— 按记录对象重写走的是合并语义,删不掉本次新增的字段
230
+ * (`title` / `renamedBy` / `renamedAt` 会残留,下一次自动改名因此被当成「用户手动改过」)。
231
+ */
232
+ let before
233
+ try {
234
+ before = await snapshotRecords(repository, document)
235
+ } catch (error) {
236
+ // 🔴 读不出快照就**终止改名**,不能"带着半份快照继续"。
237
+ // 拿不到快照 = 失败时退不回原样,而改名一旦开始就要覆盖 manifest 与冷记录 —— 到那时
238
+ // 失败留下的就是「文件退回旧名、冷记录指向新名」这种收不了场的状态,而且回执里也没法
239
+ // 交代(恢复阶段根本不知道该恢复成什么)。宁可这次不改,也不做一件失败后还原不了的事。
240
+ // 正常的"原本就没有这个文件"由 snapshotBytes 折成 undefined,不会走到这里。
241
+ throw new Error('改名前的记录快照读取失败,已取消改名(本次未改动任何文件与记录):' + String(error?.message ?? error), { cause: error })
242
+ }
243
+
244
+ /**
245
+ * 两条入口在这里**第一次分叉**,而不是在调用方各写一遍:
246
+ * - 用户键入(D181):名字由人定,粘性不适用(这本身就是手动动作),也不静默加后缀;
247
+ * - 元数据(D156):沿用 Zotero 的粘性(手动改过就不再自动覆盖)与撞名兜底。
248
+ */
249
+ const typed = typeof requestedStem === 'string'
250
+ let stem
251
+ if (typed) {
252
+ const cleaned = sanitizeStemInput(requestedStem)
253
+ if (!cleaned.ok) {
254
+ return {
255
+ renamed: false,
256
+ from: currentName,
257
+ to: currentName,
258
+ reason: cleaned.reason === 'too-long' ? 'name-too-long' : 'invalid-name',
259
+ }
260
+ }
261
+ stem = cleaned.stem
262
+ } else {
263
+ // 粘性(抄 Zotero):用户手动改过名的,自动改名不再覆盖。
264
+ if (document.renamedBy === 'manual' && !force) return { renamed: false, from: currentName, to: currentName, reason: 'manual' }
265
+ stem = buildStem(metadata)
266
+ if (stem === '') return { renamed: false, from: currentName, to: currentName, reason: 'no-title' }
267
+ }
268
+ if (isSameStem(currentName, stem)) {
269
+ /**
270
+ * 🔴 文件已经叫这个名字,**不代表这次点什么都没发生**(D181 实测):
271
+ * 用户键入的名字可能正好等于现有文件名,但界面显示的是 title —— 那篇的 title 仍是
272
+ * 解析时算错的 `Broader Impacts`。这时文件名不该动,可**显示名必须改过来**,
273
+ * 否则用户点了确认,界面上一个字都不变,看起来像失败。
274
+ *
275
+ * 只有键入路径才落 title:自动改名的"同名"是真的无事可做。
276
+ */
277
+ if (typed && document.title !== stem) {
278
+ // 与搬家那条路同一个顺序:**先写 manifest,最后才提交 state** —— 归档写失败时
279
+ // state 还没动,不会留下"记录说改了、盘上没改"的双真相。
280
+ // 🔴 反过来也必须成立:state 写失败时,manifest 与冷记录要按**改名之前**的字节原样退回。
281
+ // 只回滚前两者、不管后一步会留下「manifest 说改了、热记录还是旧标题」的半边状态 ——
282
+ // 界面上看是失败,文件里却已经改了,下一次读取就按新标题走(实测复现)。
283
+ const nextRecord = structuredClone(raw)
284
+ nextRecord.title = stem
285
+ nextRecord.renamedBy = 'manual'
286
+ nextRecord.renamedAt = new Date().toISOString()
287
+ try {
288
+ await repository.writeArchivedDocument(hydrateDocument(nextRecord))
289
+ if (!cold) {
290
+ await repository.update(state => {
291
+ const record = state.documents[id]
292
+ if (!record) throw new Error('论文已从当前状态移除')
293
+ record.title = stem
294
+ record.renamedBy = 'manual'
295
+ record.renamedAt = new Date().toISOString()
296
+ return null
297
+ })
298
+ }
299
+ } catch (error) {
300
+ const restored = await restoreRecords(before)
301
+ throw new Error('论文显示名未能更新:' + String(error?.message ?? error) + restoreDetail(restored), { cause: error })
302
+ }
303
+ return { renamed: false, from: currentName, to: currentName, reason: 'same', titleUpdated: true }
304
+ }
305
+ return { renamed: false, from: currentName, to: currentName, reason: 'same' }
306
+ }
307
+ const paths = storePathsOf(repository.root, { id, pdfName: currentName })
308
+ const dir = paths.dir
309
+ const fromStem = paths.pdf.slice(dir.length + 1).replace(/\.pdf$/i, '')
310
+ let toStem = stem
311
+ // 目标主名已被占用(同目录里已有这个主名的文件)——
312
+ // 自动改名加短哈希兜底;用户键入则**拒绝**:磁盘上的名字必须与打进去的一致(D181)。
313
+ if (await exists(join(dir, toStem + '.pdf'))) {
314
+ if (typed) return { renamed: false, from: currentName, to: currentName, reason: 'occupied' }
315
+ toStem = disambiguateStem(stem, id)
316
+ }
317
+ const pairs = await movePlan(dir, fromStem, toStem)
318
+ if (pairs.length === 0) return { renamed: false, from: currentName, to: currentName, reason: 'no-files' }
319
+ const moved = []
320
+ for (const pair of pairs) {
321
+ try {
322
+ await renameFile(pair.from, pair.to)
323
+ moved.push(pair)
324
+ } catch (error) {
325
+ // 搬到一半失败:把已经搬的搬回去,回到调用前的形状。
326
+ for (const done of moved.reverse()) {
327
+ try { await renameFile(done.to, done.from) } catch {}
328
+ }
329
+ throw new Error('论文改名失败:' + String(error?.message ?? error), { cause: error })
330
+ }
331
+ }
332
+ const nextName = toStem + '.pdf'
333
+ const nextPdfPath = join(dir, nextName)
334
+
335
+ /**
336
+ * 把这次改名造成的**文件搬移**全部撤销,回到调用前的形状。
337
+ *
338
+ * 🔴 顺序与"先写记录后搬文件"直接相关:只要记录还没落盘,磁盘就该退回旧名,
339
+ * 这样任何一步失败都不会留下「状态说新名、盘上是旧名」的双真相。
340
+ */
341
+ const rollbackFiles = async () => {
342
+ for (const pair of [...moved].reverse()) {
343
+ try { await renameFile(pair.to, pair.from) } catch {}
344
+ }
345
+ }
346
+
347
+
348
+ // 🔴 **先写 manifest 与冷归档,最后才提交 state**。
349
+ //
350
+ // 反过来(先提交 state 再写归档)会造出一个我实测踩到过的错位:writeArchivedDocument 要读
351
+ // markdown 与 outline,读不到就抛;此时 state 已经是新名、盘上却还是旧名,而 catch 里的
352
+ // 回滚只搬文件、**不回滚已经提交的 state** —— 于是状态与磁盘永久不一致。
353
+ // 先写归档就没有这个窗口:它失败时 state 还没动,回滚文件即可完全复原。
354
+ //
355
+ // 这也是 writeArchivedDocument 的既有语义:它只读 **applyRenameToDocument 之后**的记录,
356
+ // 所以必须先算出新记录。
357
+ // 归一一次,两处写入共用(manifest 预写与 state 提交必须是同一份值)。
358
+ const persisted = cleanRenameMetadata(metadata)
359
+ try {
360
+ const snapshot = await repository.snapshot()
361
+ // 冷记录同样要在这里重新取一次:两次读之间可能刚被 compact 挪进 archive/。
362
+ // 🔴 这里只用它做**存在性**判断,造新记录用的是上面那份(搬文件之前读到的)。
363
+ const current = (await recordOf(repository, snapshot, id)).raw
364
+ if (!current) throw new Error('论文已从当前状态移除')
365
+ // 🔴 造"改名后"的记录必须用**搬文件之前**读到的那份完整记录。
366
+ // 主名一改,manifest 已经被 movePlan 搬到新主名下,这时再按旧主名去读它必然读不到 ——
367
+ // `archivedDocument` 于是只回 { id, pdfPath, artifact } 这个定位壳,标题/作者/源目录全没了。
368
+ // 用这份壳去写 manifest 时,`writePortableManifest` 会把「记录上没有 sourceDir」读成
369
+ // 「这一次要显式清空它」,于是 sourceDir / sourcePdfPath 被删除(实测复现:改名成功、关联消失)。
370
+ // 造一份"改名后"的记录视图用于写 manifest / 冷归档(不落 state)。
371
+ const nextRecord = structuredClone(raw)
372
+ // 键入改名同样算「手动」:它必须置上粘性标记,否则下一次解析的自动改名会把用户打的名字覆盖掉。
373
+ applyRenameToDocument(nextRecord, { nextName, nextPdfPath, toStem, force: force || typed, metadata: persisted, typedTitle: typed ? toStem : undefined })
374
+ await repository.writeArchivedDocument(hydrateDocument(nextRecord))
375
+
376
+ // 文件与 manifest 都就位了,最后原子地提交文档记录 + 任务记录。
377
+ await repository.update(state => {
378
+ const record = state.documents[id]
379
+ // 冷归档的论文只在 `archive/` 里有记录(manifest 与冷记录上面已经写过),这里没有文档
380
+ // 记录可提交;热记录在两次读之间被别的宿主删掉才是真错位,仍然要抛。
381
+ if (!record && !cold) throw new Error('论文已从当前状态移除')
382
+ if (record) {
383
+ applyRenameToDocument(record, { nextName, nextPdfPath, toStem, force: force || typed, metadata: persisted, typedTitle: typed ? toStem : undefined })
384
+ }
385
+ // 🔴 任务记录必须与文档记录在**同一次**状态写入里改:job 上也冻结着 pdfPath/pdfName,
386
+ // 而 job.pdfPath 是解析重试的**唯一**输入(resolver.retry → add(job.pdfPath))。
387
+ // 不同步的话,重试会拿一条指向已删文件的路径去 stat,报 ENOENT —— 实测复现过。
388
+ for (const job of Object.values(state.jobs ?? {})) {
389
+ if (job?.documentId !== id) continue
390
+ job.pdfPath = nextPdfPath
391
+ job.pdfName = nextName
392
+ }
393
+ })
394
+ } catch (error) {
395
+ // 反序复原:先把文件搬回旧名,再把两处记录写回改名前的字节。
396
+ await rollbackFiles()
397
+ const restored = await restoreRecords(before)
398
+ throw new Error('论文改名后记录未能更新:' + String(error?.message ?? error) + restoreDetail(restored), { cause: error })
399
+ }
400
+ logger?.info?.('dsh-paper rename: ' + currentName + ' → ' + nextName)
401
+ return { renamed: true, from: currentName, to: nextName, reason: 'ok', stem: toStem, files: moved.length }
402
+ }
403
+
404
+ /**
405
+ * 把两级元数据来源合成一份改名依据(缺哪段省略哪段)。
406
+ *
407
+ * 回退顺序**刻意是「目录元数据优先」**:
408
+ * 1. `catalog` —— arXiv / DOI 采集到的标题、作者、年份(最准,是出版方登记的那份);
409
+ * 2. `pdf` —— PDF 自己的 Info dict(Title / Author);
410
+ * 3. `heading` —— MinerU 解析出的正文首个 heading。
411
+ *
412
+ * 🔴 第 3 级是**实际用得上**的兜底,不是理论完备:实测某篇 Mem0 论文的 Info dict 里
413
+ * Title/Author **全空**,而正文首行就是 `# Mem0: Building Production-Ready AI Agents…`。
414
+ * 没有这一级,它就只能保留 `2504.19413v1.pdf` 这种原始文件名。
415
+ *
416
+ * 🔴 **实测结论决定了这个顺序**:arXiv 的 LaTeX 生成 PDF,Info dict 的 Title/Author **都是空的**
417
+ * (实测 1706.03762 与 ACL 2023 两篇,Title/Author 全空,只有 Creator/Producer),
418
+ * 而 CreationDate 是**编译时间**(2024),对一篇 2017 年的论文会写出错误的年份。
419
+ * PDF 那一路只补标题与作者;CreationDate 是文件生成时间,不能补出版年。
420
+ *
421
+ * @param {{catalog?: object, pdf?: object, heading?: string}} sources
422
+ * @returns {{title: string, authors: string[], year: string, source: string}}
423
+ */
424
+ export function composeRenameMetadata(sources = {}) {
425
+ const catalog = cleanRenameMetadata(sources?.catalog)
426
+ const pdfMeta = sources?.pdf ?? {}
427
+ const pdfTitle = typeof pdfMeta.title === 'string' ? pdfMeta.title.trim() : ''
428
+ // 🔴 必须过 splitAuthors:直接包成 [author] 会绕过分隔符拆分,五位作者全进文件名(实测踩过)。
429
+ const pdfAuthors = splitAuthors(pdfMeta.author)
430
+ // 第三级:MinerU 解析出的正文首个 heading。
431
+ const headingTitle = typeof sources?.heading === 'string' ? sources.heading.trim() : ''
432
+ const title = catalog.title ?? (pdfTitle !== '' ? pdfTitle : headingTitle)
433
+ const authors = catalog.authors ?? pdfAuthors
434
+ const year = catalog.year ?? ''
435
+ const source = catalog.title !== undefined
436
+ ? 'catalog'
437
+ : pdfTitle !== '' ? 'pdf' : (headingTitle !== '' ? 'heading' : 'none')
438
+ return { title, authors, year, source }
439
+ }
440
+
441
+ /**
442
+ * 解析一篇论文该用什么元数据改名,并**实际执行**改名(不满足条件时安静跳过)。
443
+ *
444
+ * 不满足就跳过、不报错:改名是解析的**副产物**,没有依据时保持原文件名是正确行为 ——
445
+ * 绝不能用 id 之类的占位符覆盖掉用户认得出的原名。
446
+ *
447
+ * @param {{repository: object, document: object, metadata?: object, readPdfMetadata?: Function, logger?: object, force?: boolean}} deps
448
+ * @returns {Promise<{renamed: boolean, reason: string, to?: string, source?: string}>}
449
+ */
450
+ export async function renameAfterParse({ repository, document, metadata, heading, readPdfMetadata, logger, force = false }) {
451
+ const pdfPath = typeof document?.pdfPath === 'string' ? document.pdfPath : ''
452
+ const catalog = { ...cleanRenameMetadata(document), ...cleanRenameMetadata(metadata) }
453
+ // 🔴 **目录元数据齐了就别起子进程**:读 PDF 元数据要 spawn 一次 uvx(实测几十到几百毫秒),
454
+ // 而它只在「目录没给标题」或「目录没给作者/年份」时才有补位价值。
455
+ // 出版年不能从 PDF 创建日期补齐;仅缺年份不需要读取 PDF。
456
+ let pdf = null
457
+ const needsPdfTier = catalog.title === undefined || catalog.authors === undefined
458
+ if (needsPdfTier && typeof readPdfMetadata === 'function' && pdfPath !== '') {
459
+ try {
460
+ // 读元数据失败一律降级成空(readPdfMetadata 自己兜住异常),这里再兜一层是防注入实现抛。
461
+ pdf = await readPdfMetadata(pdfPath)
462
+ } catch (error) {
463
+ logger?.warn?.('dsh-paper rename: PDF 元数据读取失败 ' + String(error?.message ?? error))
464
+ pdf = null
465
+ }
466
+ }
467
+ const composed = composeRenameMetadata({ catalog, pdf, heading })
468
+ if (composed.title === '') {
469
+ // 三级都没有标题 → 没有改名依据,保持原名(绝不用 id 覆盖用户认得出的原名)。
470
+ return { renamed: false, reason: 'no-title' }
471
+ }
472
+ const result = await renameDocument({
473
+ repository,
474
+ documentId: document.id,
475
+ metadata: { title: composed.title, authors: composed.authors, year: composed.year },
476
+ logger,
477
+ force,
478
+ })
479
+ return { ...result, source: composed.source }
480
+ }