@li-canghai/dsh-paper 0.8.2 → 0.8.3

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.
@@ -148,6 +148,18 @@ function restoreDetail(failures) {
148
148
  return '(另有 ' + failures.length + ' 项记录未能恢复:' + failures.map(item => String(item?.message ?? item)).join(';') + ')'
149
149
  }
150
150
 
151
+ /**
152
+ * 文件没搬回去时的附言。
153
+ *
154
+ * 这条与 {@link restoreDetail} 是两件事:记录恢复失败是「状态与磁盘不一致」,
155
+ * 文件搬回失败是**磁盘上留着两套主名**(新旧各一份)。用户需要知道残局在哪,
156
+ * 所以把没搬回的那几个路径直接写出来。
157
+ */
158
+ function fileDetail(failures) {
159
+ if (!Array.isArray(failures) || failures.length === 0) return ''
160
+ return '(另有 ' + failures.length + ' 个文件未能搬回旧名,磁盘上可能两套主名并存:' + failures.map(item => String(item?.path ?? '') + ':' + String(item?.error ?? '')).join(';') + ')'
161
+ }
162
+
151
163
  /**
152
164
  * 按 id 取一条记录:**热表优先,冷归档兜底**。
153
165
  *
@@ -339,9 +351,17 @@ async function renameDocumentLocked({ repository, id, metadata, requestedStem, l
339
351
  * 这样任何一步失败都不会留下「状态说新名、盘上是旧名」的双真相。
340
352
  */
341
353
  const rollbackFiles = async () => {
354
+ // 🔴 回滚失败必须记下来、如实报给用户,不能 `catch {}` 吞掉。
355
+ // 吞掉的后果是:磁盘上留下两套主名并存(新旧各一份),而错误文本只说「记录未能更新」,
356
+ // 用户不知道要去哪个目录收拾残局。实测:改名报 `renamed: true`、state 已是新名,
357
+ // 盘上 `["Old Name.pdf", "New Name.pdf"]` 两份都在。
358
+ //
359
+ // 这不是「数据丢了」(文件都还在),而是「状态与磁盘不一致且没人告诉你」。
360
+ const failures = []
342
361
  for (const pair of [...moved].reverse()) {
343
- try { await renameFile(pair.to, pair.from) } catch {}
362
+ try { await renameFile(pair.to, pair.from) } catch (error) { failures.push({ path: pair.to, error: String(error?.message ?? error) }) }
344
363
  }
364
+ return failures
345
365
  }
346
366
 
347
367
 
@@ -393,9 +413,11 @@ async function renameDocumentLocked({ repository, id, metadata, requestedStem, l
393
413
  })
394
414
  } catch (error) {
395
415
  // 反序复原:先把文件搬回旧名,再把两处记录写回改名前的字节。
396
- await rollbackFiles()
416
+ // 两边都可能有失败项,**都要报出来**:文件没搬回意味着盘上留着两套主名,
417
+ // 记录没恢复意味着状态与磁盘不一致 —— 这两种残局用户得知道去哪收拾。
418
+ const fileFailures = await rollbackFiles()
397
419
  const restored = await restoreRecords(before)
398
- throw new Error('论文改名后记录未能更新:' + String(error?.message ?? error) + restoreDetail(restored), { cause: error })
420
+ throw new Error('论文改名后记录未能更新:' + String(error?.message ?? error) + restoreDetail(restored) + fileDetail(fileFailures), { cause: error })
399
421
  }
400
422
  logger?.info?.('dsh-paper rename: ' + currentName + ' → ' + nextName)
401
423
  return { renamed: true, from: currentName, to: nextName, reason: 'ok', stem: toStem, files: moved.length }
@@ -144,15 +144,6 @@ export async function writeDocumentPostings({ root, docNo, postings }) {
144
144
  })
145
145
  }
146
146
 
147
- export function withoutDocNo(flat, docNo) {
148
- if (!Array.isArray(flat)) return []
149
- const kept = []
150
- for (let index = 0; index < flat.length; index += 3) {
151
- if (flat[index] !== docNo) kept.push(flat[index], flat[index + 1], flat[index + 2])
152
- }
153
- return kept
154
- }
155
-
156
147
  export async function dropDocumentPostings({ root, docNo }) {
157
148
  return databaseWrite(root, (_db, prepare) => prepare('DELETE FROM postings WHERE doc_no=?').run(docNo))
158
149
  }
@@ -36,9 +36,8 @@ export const SELECTION_SECTION = 'dsh-paper-selection'
36
36
  /**
37
37
  * 整条消息文本的 UTF-8 字节上限。
38
38
  *
39
- * 🔴 与 discussion.js 的 DISCUSSION_MESSAGE_MAX_BYTES 同一口径(D96):超限按**保留优先级
40
- * 整段替换**,绝不截半句 —— 一条被拦腰砍断的选中原话会让模型对着半句话作答,比明说
41
- * "这段没带上"更糟。上限管的是**整条消息文本**,不含消息外层结构。
39
+ * 🔴 口径同 D96:超限按**保留优先级整段替换**,绝不截半句 —— 一条被拦腰砍断的选中原话
40
+ * 会让模型对着半句话作答,比明说"这段没带上"更糟。上限管的是**整条消息文本**,不含消息外层结构。
42
41
  *
43
42
  * 上限实际约束的是**可选段落**(章节树、术语表、所在段落):必留段落自身就超限时消息会
44
43
  * **越过上限**,而不是丢用户选中的内容 —— 一条没有选中内容的消息投递出去等于没投。
package/lib/storage.js CHANGED
@@ -83,6 +83,26 @@ function dropRetiredDocumentKeys(document) {
83
83
 
84
84
  const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
85
85
 
86
+ /**
87
+ * 同一进程内临时文件名的序号。
88
+ *
89
+ * 🔴 `pid + Date.now()` 不足以区分同一毫秒内的两次写:两次算出的临时名相同,
90
+ * 后一次覆盖前一次的内容、两次 rename 又把同一个(已是后一次内容的)文件搬走 ——
91
+ * 结果不是报错,而是**第一次的修改静默消失**。序号把这一毫秒内的事件强行排开。
92
+ * 跨进程由 pid 区分,同毫秒内的顺序由序号区分,两维都要有。
93
+ */
94
+ let stateTemporarySequence = 0
95
+
96
+ /**
97
+ * 取下一个临时文件序号。
98
+ *
99
+ * @returns {number} 从 1 起、进程内单调递增
100
+ */
101
+ function temporarySequence() {
102
+ stateTemporarySequence += 1
103
+ return stateTemporarySequence
104
+ }
105
+
86
106
  // Windows 上"写临时文件再 rename 覆盖"会被杀软扫描或并发读取短暂挡住,报 EPERM/EBUSY/EACCES
87
107
  // (POSIX 上不会)。这不是状态损坏,重试即可;不重试的话一次抖动就会让 update 抛错、任务卡住。
88
108
  const REPLACE_RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES'])
@@ -135,13 +155,58 @@ function interruptedByHostExit(job) {
135
155
  return typeof job?.error === 'string' && job.error.startsWith(hostExitMarkerOf(job))
136
156
  }
137
157
 
158
+ /**
159
+ * 当前 state.json 的 schema 版本。
160
+ *
161
+ * 🔴 这个数字**必须**有人读。此前它只是个写着玩的字段:readState 无条件把它覆盖成 3,
162
+ * 全仓没有一处读过原值 —— 于是「未来版本的 state.json」与「我们的 state.json」在代码眼里
163
+ * 没有区别,升级回退一次就是拿旧结构覆盖新结构。库文件那边(library.js 的 loadEnvelope)
164
+ * 早就有完整的迁移与拒写守卫,两个持久文件不该两套规范。
165
+ */
166
+ const STATE_SCHEMA_VERSION = 3
167
+
168
+ /** 从旧版本迁到当前版本的迁移函数表。此刻还没有需要迁移的结构,占位是为了下次加字段时不用改读侧。 */
169
+ const STATE_MIGRATIONS = Object.freeze({})
170
+
138
171
  function emptyState(initialSettings = {}) {
139
- return { version: 3, documents: {}, jobs: {}, selections: {}, settings: { ...DEFAULT_SETTINGS, ...initialSettings } }
172
+ return { version: STATE_SCHEMA_VERSION, documents: {}, jobs: {}, selections: {}, settings: { ...DEFAULT_SETTINGS, ...initialSettings } }
173
+ }
174
+
175
+ /**
176
+ * 读出状态文件的版本号并按需分派迁移。
177
+ *
178
+ * 🔴 三种情形分开处理,混在一起就必然出错:
179
+ * - **等于当前版本**:原样用;
180
+ * - **比当前旧**:有迁移函数就迁,没有就抛错停下写 —— 拿新结构写旧文件同样是覆盖用户数据;
181
+ * - **比当前新**(用户装过更新的版本又退回来):抛错停下写。读得懂不等于写得对,
182
+ * 我们认识的字段只是它的一部分,写回去会把它多出来的字段一起抹掉。
183
+ *
184
+ * 缺 version 的老文件按「还没有版本号的时代」处理:那是当前版本之前的形态,字段都还认得,
185
+ * 直接当作当前版本读 —— 这条兼容是必需的,用户的 state.json 里就可能留着这种历史数据。
186
+ *
187
+ * @param {unknown} raw 已解析的顶层对象
188
+ * @param {string} path 出错信息里要指出的文件
189
+ * @returns {number} 应当使用的版本号
190
+ */
191
+ function resolveStateVersion(raw, path) {
192
+ const version = raw?.version
193
+ if (version === undefined || version === null) return STATE_SCHEMA_VERSION
194
+ if (!Number.isInteger(version) || version < 1) {
195
+ throw new Error('dsh-paper 状态文件的 version 不是正整数(' + JSON.stringify(version) + '),已停止写入以保留原文件:' + path)
196
+ }
197
+ if (version === STATE_SCHEMA_VERSION) return STATE_SCHEMA_VERSION
198
+ if (version < STATE_SCHEMA_VERSION) {
199
+ const migrate = STATE_MIGRATIONS[version]
200
+ if (typeof migrate === 'function') return migrate(raw)
201
+ throw new Error('dsh-paper 状态文件的版本 ' + version + ' 没有迁移路径,已停止写入以保留原文件:' + path)
202
+ }
203
+ throw new Error('dsh-paper 状态文件的版本比本插件认识的更新(' + version + ' > ' + STATE_SCHEMA_VERSION + '),已停止写入以保留原文件:' + path)
140
204
  }
141
205
 
142
206
  async function readState(path, initialSettings) {
143
207
  try {
144
208
  const value = JSON.parse(await readFile(path, 'utf8'))
209
+ const version = resolveStateVersion(value, path)
145
210
  // 退役设置键在这里剔除:展开旧 settings 会把未知键原样带回,下一次写入就会把它再落盘。
146
211
  const settings = { ...DEFAULT_SETTINGS, ...initialSettings, ...(value.settings ?? {}) }
147
212
  for (const key of RETIRED_SETTINGS) delete settings[key]
@@ -150,7 +215,7 @@ async function readState(path, initialSettings) {
150
215
  return {
151
216
  ...emptyState(initialSettings),
152
217
  ...value,
153
- version: 3,
218
+ version,
154
219
  documents,
155
220
  jobs: value.jobs && typeof value.jobs === 'object' ? value.jobs : {},
156
221
  selections: value.selections && typeof value.selections === 'object' ? value.selections : {},
@@ -355,9 +420,24 @@ export class PaperRepository {
355
420
  ? { id: document.id, pdfPath: document.pdfPath, artifact: document.artifact }
356
421
  : metadata
357
422
  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)
423
+ // 🔴 序号不能省(与 `update()` 的 `temporarySequence` 同一条理由):`pid + Date.now()`
424
+ // 区分不了同一毫秒内的两次写,于是两次算出的临时名相同 —— 后一次覆盖前一次的内容、
425
+ // 两次 rename 又把同一个(已是后一次内容的)文件搬走。结果不是报错,而是**第一次的
426
+ // 修改静默消失**。实测:冻结时钟后连写两次都返回 ok,落盘只剩第一次的内容;
427
+ // 8 路并发 300 轮里 1094 次写被拒,其中 164 次 ENOENT —— 那正是临时文件已被对方的
428
+ // rename 搬走。`writeArchivedRecord` 被 compact / renameDocument / updateMetadata /
429
+ // purge 四条路径共用,同一篇上完全可能交错。
430
+ const temporary = join(dirname(path), `.${document.id}.${process.pid}.${Date.now()}.${temporarySequence()}.tmp`)
431
+ try {
432
+ await writeFile(temporary, `${JSON.stringify(archived, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
433
+ await rename(temporary, path)
434
+ } catch (error) {
435
+ // 写一半就失败(磁盘满、被占用)时把临时文件收走:`update()` 早就这么做,这里漏了。
436
+ // 漏掉的话每次失败都在 archive 里留一份 `.xxx.tmp`,而 `rawArchivedDocuments` 只认
437
+ // `.json` 后缀,它们不会被读到却也永远不会被清掉 —— 实测 5 次失败留 5 个。
438
+ await rm(temporary, { force: true }).catch(() => {})
439
+ throw error
440
+ }
361
441
  }
362
442
 
363
443
  async writeArchivedDocument(document) {
@@ -396,8 +476,26 @@ export class PaperRepository {
396
476
  for (const entry of await readdir(dir, { withFileTypes: true })) {
397
477
  if (!entry.isFile() || !entry.name.endsWith('.json')) continue
398
478
  if (excludeIds?.has(entry.name.slice(0, -5))) continue
479
+ // 一条坏记录不该炸掉整张列表。这里原来是一个裸 JSON.parse:任何一篇的冷记录
480
+ // 被截断(写盘中途断电、磁盘满、外部工具改坏)就让 archivedDocuments() 整个抛出
481
+ // 「Unterminated string」,其余几百篇好记录一条都列不出来 —— 表现为「文献库突然空了」。
482
+ //
483
+ // 冷记录是索引不是权威(权威是随 PDF 走的 analysis/*.json),所以读侧应当降级:
484
+ // 读不出来的那一条跳过并记一行警告,其余照常。这与 readState 对坏 state.json 的处理同一条口径。
485
+ // 写侧不受影响:assertReplaceableFile 仍然是「读不懂就拒绝替换」。
486
+ const filePath = join(dir, entry.name)
487
+ let raw
488
+ try {
489
+ raw = JSON.parse(await readFile(filePath, 'utf8'))
490
+ } catch (error) {
491
+ // 这里没有 logger:PaperRepository 不持有它(构造器只设 root/path/lockPath/…)。
492
+ // 静默跳过是刻意的——读侧降级的目标是「其余记录照常可用」,不是把每一条坏文件都播报出去;
493
+ // 真要追查,那个 .json 文件本身还在原处,而写侧的 assertReplaceableFile 会拒绝覆盖它。
494
+ void error
495
+ continue
496
+ }
399
497
  // 冷记录不经过 readState,退役字段要在这里同样剔掉(见 RETIRED_DOCUMENT_KEYS)。
400
- const document = dropRetiredDocumentKeys(JSON.parse(await readFile(join(dir, entry.name), 'utf8')))
498
+ const document = dropRetiredDocumentKeys(raw)
401
499
  if (document && typeof document.id === 'string') documents.push(document)
402
500
  }
403
501
  }
@@ -457,12 +555,19 @@ export class PaperRepository {
457
555
  .sort((left, right) => documentRecency(right) - documentRecency(left) || String(left.id).localeCompare(String(right.id)))
458
556
  for (const document of hidden) delete document.outlineText
459
557
  const evicted = hidden.slice(Math.max(0, hiddenLimit))
558
+ // 🔴 一条坏 id 不能让整次整理失败。`archivePath` 对非 `[a-f0-9]{64}` 的值会抛错,
559
+ // 而整理是启动链里的一环:一旦抛错,它后面的 outline 迁移、scratch 回收、续跑排队任务
560
+ // **全部不执行**(外层只记一行 warn),而已经驱逐的记录也不会回滚。
561
+ // 实测:一条 `legacy-document-1` 就让 204 条 hidden 记录一条都没驱逐。
562
+ // 这里逐个跳过并计数,让其余记录照常整理 —— 坏 id 本来也不可能有归档记录。
563
+ let skippedEvictions = 0
460
564
  for (const document of evicted) {
461
565
  // 🔴 整理只搬**定位索引**,不重写随 PDF 走的权威清单。
462
566
  //
463
567
  // 热记录可能是陈旧的:updateMetadata 先把新事实写进 manifest、再提交 state,
464
568
  // 提交那一步失败时热记录仍停在旧值。此时若用 writeArchivedDocument,就会拿那份陈旧
465
569
  // 记录把 manifest 重写回旧事实 —— 一次本可由权威记录恢复的索引写失败,被固化成事实回退。
570
+ if (!/^[a-f0-9]{64}$/.test(String(document.id))) { skippedEvictions += 1; continue }
466
571
  await this.writeArchivedRecord(document)
467
572
  delete state.documents[document.id]
468
573
  }
@@ -471,7 +576,7 @@ export class PaperRepository {
471
576
  .filter(job => TERMINAL_JOB_STATUSES.has(job?.status))
472
577
  .sort((left, right) => jobRecency(right) - jobRecency(left) || String(left.id).localeCompare(String(right.id)))
473
578
  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)) }
579
+ return { archivedDocuments: evicted.length - skippedEvictions, skippedEvictions, removedJobs: Math.max(0, terminalJobs.length - Math.max(0, terminalJobLimit)) }
475
580
  })
476
581
  }
477
582
 
@@ -491,9 +596,16 @@ export class PaperRepository {
491
596
  // 文档锁先查 —— 它比状态锁活得久,被判死时整段读改写都该作废。
492
597
  await documentLease.getStore()?.assertOwned()
493
598
  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)
599
+ const temporary = join(dirname(this.path), `.state.${process.pid}.${Date.now()}.${temporarySequence()}.tmp`)
600
+ try {
601
+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
602
+ await replaceStateFile(temporary, this.path)
603
+ } catch (error) {
604
+ // 🔴 写失败必须把临时文件收走:留着它既占空间,也会和下一次同毫秒的写撞同一个名字。
605
+ // 清理本身失败不再抛 —— 原始错误比「清理没成」更值得让调用方看见。
606
+ await rm(temporary, { force: true }).catch(() => {})
607
+ throw error
608
+ }
497
609
  return result
498
610
  } finally {
499
611
  await lease.release()
@@ -87,19 +87,6 @@ export function indexDocsDir(runtimeRoot) {
87
87
  return join(searchIndexRoot(runtimeRoot), 'docs')
88
88
  }
89
89
 
90
- /**
91
- * 一个词干分片的落点。`key` 是分片名(词干首字符,非字母数字归 `_`),
92
- * 由 `search-index.js` 的 `shardKeyOf` 决定 —— 那是索引结构,不该由路径模块来定。
93
- */
94
- export function indexTermShardPath(runtimeRoot, key) {
95
- return join(indexTermsDir(runtimeRoot), `${key}.json`)
96
- }
97
-
98
- /** 一篇论文的块长度表落点(`docNo` 是 manifest 分配的稳定小整数)。 */
99
- export function indexDocPath(runtimeRoot, docNo) {
100
- return join(indexDocsDir(runtimeRoot), `${docNo}.json`)
101
- }
102
-
103
90
  /**
104
91
  * 一个字符串能不能**原样**当一个路径段落(目录名或文件主名)拼进路径。
105
92
  *
package/lib/table-gfm.js CHANGED
@@ -29,7 +29,7 @@ const GFM_LINE_BREAK = /\s*\n\s*/g
29
29
 
30
30
  /** 单元格纯文本:剥标签、解实体、转义竖线、折空白。 */
31
31
  function tableCellText(cell) {
32
- return stringOf(cell)
32
+ return String(cell ?? '')
33
33
  .replace(/<br\s*\/?>/gi, '\n')
34
34
  .replace(/<[^>]*>/g, ' ')
35
35
  .replace(/&nbsp;/gi, ' ')
@@ -49,7 +49,7 @@ function tableCellText(cell) {
49
49
  /** 一个单元格的合并跨度。 */
50
50
  function tableSpans(attributes) {
51
51
  const spans = { rowspan: 1, colspan: 1 }
52
- for (const match of stringOf(attributes).matchAll(TABLE_SPAN)) {
52
+ for (const match of String(attributes ?? '').matchAll(TABLE_SPAN)) {
53
53
  const value = Number.parseInt(match[2] ?? match[3] ?? match[4] ?? '', 10)
54
54
  if (Number.isInteger(value) && value > 1 && value <= TABLE_SPAN_MAX) spans[match[1].toLowerCase()] = value
55
55
  }
@@ -59,7 +59,7 @@ function tableSpans(attributes) {
59
59
  /** 一行的 DOM 单元格(含合并跨度);空单元格照样占位。 */
60
60
  function tableRowCells(content) {
61
61
  const cells = []
62
- for (const match of stringOf(content).matchAll(TABLE_CELL)) {
62
+ for (const match of String(content ?? '').matchAll(TABLE_CELL)) {
63
63
  cells.push({ text: tableCellText(match[3]), ...tableSpans(match[2]) })
64
64
  }
65
65
  return cells
@@ -108,10 +108,9 @@ function tableGrid(rows) {
108
108
  * @returns {string}
109
109
  */
110
110
  export function tableToGfm(html) {
111
- const source = stringOf(html)
112
- if (source.trim() === '') return ''
111
+ if (typeof html !== 'string' || html.trim() === '') return ''
113
112
  const rows = []
114
- for (const match of source.matchAll(TABLE_ROW)) {
113
+ for (const match of html.matchAll(TABLE_ROW)) {
115
114
  const cells = tableRowCells(match[1])
116
115
  if (cells.length === 0) continue
117
116
  rows.push(cells)
@@ -120,6 +119,7 @@ export function tableToGfm(html) {
120
119
  const grid = tableGrid(rows)
121
120
  const width = grid[0].length
122
121
  if (width === 0) return ''
122
+ // 只有一行时不硬造一条空数据行:GFM 允许表体只有分隔行,凭空补一行的字比不补更难查。
123
123
  const lines = [`| ${grid[0].join(' | ')} |`, `| ${grid[0].map(() => '---').join(' | ')} |`]
124
124
  for (const row of grid.slice(1)) lines.push(`| ${row.join(' | ')} |`)
125
125
  return lines.join('\n')
@@ -147,12 +147,44 @@ function isDelimiterRow(cells) {
147
147
  return cells.length > 0 && cells.every(cell => /^:?-{1,}:?$/.test(cell.trim()))
148
148
  }
149
149
 
150
- /** 数字归一:`1,000` / `1 000` 与 `1000` 视为同一个值,`0.80` 与 `0.8` 也相同。 */
150
+ /**
151
+ * 数字归一:`1,000` / `1 000` 与 `1000` 视为同一个值,`0.80` 与 `0.8` 也相同。
152
+ *
153
+ * 排版减号(− – — -)先归一成 ASCII 连字符:它们是同一个负号的四种写法,
154
+ * 不归一就会在多重集比较里被当成不同的值(见 {@link NUMBER_TOKEN})。
155
+ */
151
156
  function normalizeNumber(token) {
152
- const value = Number(String(token).replace(/[,\s]/g, ''))
157
+ const ascii = String(token).replace(/[\u2212\u2013\u2014\uFF0D]/g, '-')
158
+ const value = Number(ascii.replace(/[,\s]/g, ''))
153
159
  return Number.isFinite(value) ? String(Number(value.toPrecision(12))) : String(token)
154
160
  }
155
161
 
162
+ /**
163
+ * 抽取单元格里的数字 token。
164
+ *
165
+ * 🔴 **负号只在一条数字的起点才算负号**。用 `/-?\d+…/` 全局扫会把 `2019-2020` 切成
166
+ * `2019` 与 `-2020`:原文记成 `-2020`,而模型把区间改写成 `2019 年至 2020 年` 后
167
+ * 记成 `2020` —— 两边对不上,一块本来正确的译文被拒收,重试两次后整块 skipped。
168
+ * 反过来更糟:原文 `-5` 被模型改写成 `1-5` 时,前者是 `-5`、后者是 `1` 与 `-5`,
169
+ * 多重集包含照样通过 —— **数值被改写了却判合格**,而守数值是这套校验存在的唯一理由。
170
+ *
171
+ * 所以判定改成「前面紧邻的是数字或小数点才算连字符」:连字符夹在两个数字之间是区间,
172
+ * 不是负号;真正的负数(行首、空格后、括号内、运算符后)照旧带号。
173
+ */
174
+ // 🔴 数字里的负号不止 U+002D 一种:论文与模型输出里常见 U+2212(数学减号 −)、
175
+ // U+2013(短破折号 –)、U+2014(长破折号 —)与全角 U+FF0D(-)。只认 ASCII 连字符时,
176
+ // 原文的 `−0.3` 与译文照抄的 `−0.3` 各自解析成两个不同的 token(`0.3` 与一段不是数字的东西),
177
+ // 多重集对不上,一块本来正确的译文被判「数值被改写」,重试两次后永久 skipped。
178
+ // 所以先把这几种写法归一成 ASCII 连字符再切分 —— 归一的是**符号写法**,不是数值。
179
+ const NUMBER_TOKEN = /(?<![\d.])[-\u2212\u2013\u2014\uFF0D]?\d+(?:[.,]\d+)*/g
180
+
181
+ /** 一段文本里所有数字 token 的归一化列表。 */
182
+ function numberTokensOf(text) {
183
+ const out = []
184
+ for (const match of stringOf(text).matchAll(NUMBER_TOKEN)) out.push(normalizeNumber(match[0]))
185
+ return out
186
+ }
187
+
156
188
  /**
157
189
  * 一张 GFM 表格的骨架:有几行、每行几格、出现过的数字(归一后)。
158
190
  *
@@ -174,9 +206,7 @@ export function tableShapeOf(text) {
174
206
  if (dataRows.length === 0) return null
175
207
  const numbers = []
176
208
  for (const cells of dataRows) {
177
- for (const cell of cells) {
178
- for (const match of cell.matchAll(/-?\d+(?:[.,]\d+)*/g)) numbers.push(normalizeNumber(match[0]))
179
- }
209
+ for (const cell of cells) numbers.push(...numberTokensOf(cell))
180
210
  }
181
211
  return { rows: dataRows.length, cells: dataRows.map(cells => cells.length), numbers: numbers.sort() }
182
212
  }
@@ -197,9 +227,7 @@ export function tableShapeOf(text) {
197
227
  */
198
228
  /** 任意文本里出现过的数字(归一后、升序):没有表格结构可比时用它守数值。 */
199
229
  function numbersIn(text) {
200
- const numbers = []
201
- for (const match of stringOf(text).matchAll(/-?\d+(?:[.,]\d+)*/g)) numbers.push(normalizeNumber(match[0]))
202
- return numbers.sort()
230
+ return numberTokensOf(text).sort()
203
231
  }
204
232
 
205
233
  /** 多重集包含:source 的每个数字都能在 reply 里找到对应的一份。 */
package/lib/tex-fetch.js CHANGED
@@ -452,4 +452,3 @@ async function touch(path) {
452
452
  }
453
453
 
454
454
  /** 导出上限常量,供测试与文档引用(避免测试里抄死字面量)。 */
455
- export const TEX_LIMITS = { MAX_FILE_BYTES, MAX_TOTAL_BYTES, MAX_FILES, DEFAULT_TIMEOUT_MS, DEFAULT_CACHE_BYTES }
package/lib/tex-merge.js CHANGED
@@ -276,4 +276,3 @@ export function mergeContentList(mineruList, texItems, options = {}) {
276
276
  }
277
277
 
278
278
  /** 导出阈值,供测试与调参引用。 */
279
- export const MERGE_LIMITS = { HIGH_SIMILARITY, MEDIUM_SIMILARITY, MATCH_WINDOW }
@@ -24,7 +24,21 @@ const MAX_INCLUDE_DEPTH = 16
24
24
  const MAX_EXPAND_ROUNDS = 12
25
25
  /** 宏展开的嵌套深度上限:防自引用炸栈。 */
26
26
  const MAX_EXPAND_DEPTH = 24
27
- /** 未知命令占比阈值:超过就判 macros。 */
27
+ /**
28
+ * 展开产物的大小上限。
29
+ *
30
+ * 🔴 轮数与深度限的是**层数**,限不住**宽度**。`\def\a{\a\a}` 在深度用尽后每层原地复制
31
+ * 两支,输出严格按 4·2^depth 增长:实测 maxDepth=22 时单趟就产出 16.7 MB,
32
+ * 默认参数(12 轮 / 24 深)直接 OOM(退出码 134,V8 "Ineffective mark-compacts")。
33
+ * 经 `prepareDocument` 的生产入口同样复现 —— 不是只有测试够得着。
34
+ *
35
+ * 所以判据不能只是"别递归太深",还要问"这一趟到底允许多大"。
36
+ * 4 MiB 的依据是**实测放大比**:正常论文(链式宏 + 带参宏)展开后 / 展开前 = 1.02,
37
+ * 即使正文 281 KB 也只有 287 KB。4 MiB 留了约 14 倍余量,而病态包在 depth=12 就已经
38
+ * 远超它 —— 余量与判据之间没有重叠区。上限再放大没有意义:越界判据只是为了**及时停下**,
39
+ * 32 MiB 时要跑 6.5 秒才停得下来,4 MiB 是毫秒级。
40
+ */
41
+ const MAX_EXPAND_BYTES = 4 * 1024 * 1024
28
42
  /**
29
43
  * 未知命令占比上限。
30
44
  *
@@ -528,19 +542,41 @@ function applyArguments(body, args) {
528
542
  *
529
543
  * 单趟而不是「每个宏做一次全文 replace」:实测 GPT-3 的包有 3713 条宏定义、正文 281KB,
530
544
  * 逐宏全量替换是 O(宏数 × 正文长度),几千万次字符扫描;单趟是 O(正文长度 × 嵌套深度)。
545
+ *
546
+ * 🔴 `budget` 是**跨所有递归层共享的一个计量器**(`{ used }`),不是每层各记各的:
547
+ * 宽度爆炸发生在同一趟里,分层各算各的预算等于没算 —— 每层都觉得自己还没超。
548
+ * 一旦越过上限就立刻返回 `overflow: true`,调用方不再继续递归,也不再往 `out` 里追加。
531
549
  */
532
- function expandOnce(text, macros, depth) {
550
+ function expandOnce(text, macros, depth, budget) {
551
+ if (budget.used > budget.limit) return { text: '', count: 0, unresolved: 0, overflow: true }
533
552
  let out = ''
534
553
  let index = 0
535
554
  let count = 0
536
555
  let unresolved = 0
537
556
  while (index < text.length) {
538
- if (text[index] !== BACKSLASH) { out += text[index]; index += 1; continue }
557
+ if (text[index] !== BACKSLASH) {
558
+ // 普通字符是绝大多数:整段切片而不是逐字符追加(逐字符在几十 MB 的中间产物上
559
+ // 会把一次展开拖到秒级),预算也按这一段的长度一次记清。
560
+ // 只要一个可判定的上界,不必精确到字节:Buffer.byteLength 会把 O(n) 扫描变成 O(n) 次编码。
561
+ const next = text.indexOf(BACKSLASH, index)
562
+ const end = next === -1 ? text.length : next
563
+ budget.used += end - index
564
+ out += text.slice(index, end)
565
+ index = end
566
+ continue
567
+ }
539
568
  const command = readCommandName(text, index)
540
- if (command === null) { out += text[index]; index += 1; continue }
569
+ if (command === null) {
570
+ budget.used += 1
571
+ out += text[index]
572
+ index += 1
573
+ continue
574
+ }
541
575
  const macro = macros.get(command.name)
542
576
  if (macro === undefined) {
543
- out += text.slice(index, command.end)
577
+ const piece = text.slice(index, command.end)
578
+ budget.used += piece.length
579
+ out += piece
544
580
  index = command.end
545
581
  continue
546
582
  }
@@ -557,16 +593,27 @@ function expandOnce(text, macros, depth) {
557
593
  if (!complete) {
558
594
  // 参数不齐:原样保留调用,计入 unresolved。宁可留着让人看见,也不要替换成半截内容。
559
595
  unresolved += 1
560
- out += text.slice(index, command.end)
596
+ const piece = text.slice(index, command.end)
597
+ budget.used += piece.length
598
+ out += piece
561
599
  index = command.end
562
600
  continue
563
601
  }
564
602
  const body = applyArguments(macro.body, args)
565
603
  count += 1
566
- out += depth > 0 ? expandOnce(body, macros, depth - 1).text : body
604
+ if (depth > 0) {
605
+ const nested = expandOnce(body, macros, depth - 1, budget)
606
+ // 内层已经越界:把结论原样往上传,本层不再继续扫。
607
+ if (nested.overflow) return { text: '', count, unresolved, overflow: true }
608
+ out += nested.text
609
+ } else {
610
+ // 深度用尽:直接取宏体 —— 宽度就是在这里放大的,所以这一笔也要记账。
611
+ budget.used += body.length
612
+ out += body
613
+ }
567
614
  index = cursor
568
615
  }
569
- return { text: out, count, unresolved }
616
+ return { text: out, count, unresolved, overflow: budget.used > budget.limit }
570
617
  }
571
618
 
572
619
  /**
@@ -575,20 +622,23 @@ function expandOnce(text, macros, depth) {
575
622
  * 多轮是必要的:\newcommand{\a}{\b} 与 \newcommand{\b}{x} 的收集顺序不定,
576
623
  * 一轮下来 \a 可能展开成 \b 而不是 x。
577
624
  */
578
- export function expandMacros(text, macros, { maxRounds = MAX_EXPAND_ROUNDS, maxDepth = MAX_EXPAND_DEPTH } = {}) {
625
+ export function expandMacros(text, macros, { maxRounds = MAX_EXPAND_ROUNDS, maxDepth = MAX_EXPAND_DEPTH, maxBytes = MAX_EXPAND_BYTES } = {}) {
579
626
  const source = typeof text === 'string' ? text : ''
580
- if (!(macros instanceof Map) || macros.size === 0) return { text: source, expanded: 0, unresolved: 0 }
627
+ if (!(macros instanceof Map) || macros.size === 0) return { text: source, expanded: 0, unresolved: 0, overflow: false }
581
628
  let current = source
582
629
  let expanded = 0
583
630
  let unresolved = 0
631
+ // 预算按**整次展开**计,不是每轮清零:12 轮各涨一点与一轮涨满,读者看到的是同一个结果。
632
+ const budget = { used: 0, limit: maxBytes }
584
633
  for (let round = 0; round < maxRounds; round += 1) {
585
- const result = expandOnce(current, macros, maxDepth)
634
+ const result = expandOnce(current, macros, maxDepth, budget)
586
635
  expanded += result.count
587
636
  unresolved = result.unresolved
637
+ if (result.overflow) return { text: current, expanded, unresolved, overflow: true }
588
638
  if (result.count === 0) { current = result.text; break }
589
639
  current = result.text
590
640
  }
591
- return { text: current, expanded, unresolved }
641
+ return { text: current, expanded, unresolved, overflow: budget.used > budget.limit }
592
642
  }
593
643
 
594
644
  /**
@@ -697,6 +747,18 @@ export function prepareDocument({ files } = {}) {
697
747
  const collected = collectMacros(uncommented)
698
748
  const withoutDefinitions = removeSpans(uncommented, collected.spans)
699
749
  const expanded = expandMacros(withoutDefinitions, collected.macros)
750
+ // 🔴 展开越界就整篇退回 OCR,不拿半截正文继续跑:
751
+ // 越界意味着这个包的宏体系不是线性展开的,继续下去只会产出被截断的正文,
752
+ // 而截断点可能落在 \begin{equation} 中间,下游块对齐会把它拼成畸形块。
753
+ if (expanded.overflow) {
754
+ return {
755
+ state: 'degraded',
756
+ reason: DEGRADE_REASON.MACROS,
757
+ detail: `宏展开超出 ${MAX_EXPAND_BYTES} 字节上限,这个包的宏体系无法安全展开`,
758
+ mainFile: main.name,
759
+ macros: collected.macros.size,
760
+ }
761
+ }
700
762
  const parts = extractBody(expanded.text)
701
763
  const stats = documentStats(parts.body)
702
764
  const documentClass = documentClassOf(parts.preamble)
@@ -743,4 +805,3 @@ export function prepareDocument({ files } = {}) {
743
805
  }
744
806
 
745
807
  /** 导出阈值,供测试与文档引用(避免测试里抄死字面量)。 */
746
- export const PREPARE_LIMITS = { MIN_BODY_CHARS, MAX_INCLUDES: MAX_INCLUDE_DEPTH, MAX_EXPAND_ROUNDS, MAX_UNKNOWN_RATIO }
@@ -74,12 +74,3 @@ export function coverage(left, right) {
74
74
  return shared / a.size
75
75
  }
76
76
 
77
- /**
78
- * 归一化后的可比较文本:折空白、去首尾空白。
79
- *
80
- * 对齐把 PDF 文本层的多行合成一段、把源码里的多行合回一段之后,两边仍会差在换行与
81
- * 制表符上;这里统一折成单空格,让「同一段话」在字符串层面也可比较(用于定位下标)。
82
- */
83
- export function normalizeForMatch(value) {
84
- return String(value ?? '').replace(/\s+/g, ' ').trim()
85
- }
package/lib/tool-host.js CHANGED
@@ -908,7 +908,10 @@ export function createToolHost(deps = {}) {
908
908
  const width = Number.isFinite(request.width) ? Math.floor(request.width) : 1200
909
909
  try {
910
910
  const rendered = await renderPages(
911
- { pdfPath: document.pdfPath, pages: [page], width: Math.min(Math.max(width, 200), 4096) },
911
+ // 🔴 `documentId` 必须传:不传时 `page-image.js` 会退回「把整份 PDF 读进来算 sha256」
912
+ // 当缓存键,而这里每一页都要算一次。实测 48 MiB 的 PDF:带 id 0.24 ms,不带 45.36 ms。
913
+ // 界面侧那两个调用点(index.js 的 /pdf-page 与 /page-image)本来都传了,只有工具这条漏了。
914
+ { documentId: request.documentId, pdfPath: document.pdfPath, pages: [page], width: Math.min(Math.max(width, 200), 4096) },
912
915
  // 🔴 这里必须用 deps 解构出来的 `mineruCommand`,不是 `config.mineruCommand` ——
913
916
  // 整个文件没有 `config` 这个名字(那只存在于 index.js 的 apply 作用域),
914
917
  // 写成 config.* 会抛 ReferenceError,被下面的 catch 收成