@li-canghai/dsh-paper 0.8.2 → 0.8.6

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.
package/README.md CHANGED
@@ -1,15 +1,12 @@
1
1
  # dsh-paper
2
2
 
3
+ 把 PDF 变成可检索、可引用、可对照阅读的本地语料。
4
+
3
5
  ## 概览
4
6
 
5
- 把 PDF 变成可检索、可引用、可对照阅读的本地语料。
7
+ 选文件或文件夹 → 解析(已有的直接复用)→ 连同结果收进插件存储,库自此自包含。
6
8
 
7
- 选文件或文件夹 → 解析(已有的直接复用)→ 连同结果收进插件存储,库自此自包含;
8
- 读的时候有章节目录、块级续读、划线、AI 边注、逐块中英对照、原页拖选提问,
9
- 引用标记悬停即见该条参考文献原文(`[41]` 与 `(Zhang et al., 2020)` 都认),
10
- 还能把同一篇并排开两格(左英文右译文、滚动联动);
11
- 写完有书目补全、BibTeX / RIS / CSL-JSON 互通与 GB/T 7714 等引用样式。
12
- 另有两条不进库的旁路:把结果存一份到论文文件夹,或直接把一篇 PDF 解成 md + `images`。
9
+ 读的时候有章节目录、块级续读、划线、AI 边注、逐块中英对照、原页拖选提问;引用标记悬停即见该条参考文献原文(`[41]` 与 `(Zhang et al., 2020)` 都认),同一篇还能并排开两格(左英文右译文、滚动联动)。写完有书目补全、BibTeX / RIS / CSL-JSON 互通与 GB/T 7714 等引用样式。另有两条不进库的旁路:把结果存一份到论文文件夹,或直接把一篇 PDF 解成 md + `images`。
13
10
 
14
11
  ## 目录
15
12
 
@@ -23,9 +20,7 @@
23
20
 
24
21
  ### 什么时候选它
25
22
 
26
- 想把一批 PDF 变成**可检索、可引用、可对照阅读**的语料时。它不做 Zotero 那样的多端同步与写作软件集成
27
- (差距见 [zotero-gaps.md](docs/zotero-gaps.md)),换来的是一条自包含的本地流水线:
28
- 入库即复制、解析可复用、引用能按 GB/T 7714 出。
23
+ 想把一批 PDF 变成**可检索、可引用、可对照阅读**的语料时。它不做 Zotero 那样的多端同步与写作软件集成(差距见 [zotero-gaps.md](docs/zotero-gaps.md)),换来的是一条自包含的本地流水线:入库即复制、解析可复用、引用能按 GB/T 7714 出。
29
24
 
30
25
  只要读一篇 PDF 的一段文字,用右栏「解析」Tab 就够 —— 那条路不建库、不写 `item.json`。
31
26
 
@@ -40,6 +35,16 @@
40
35
 
41
36
  完整配置项表见 [SPEC.md 的配置项](docs/SPEC.md#配置项)。
42
37
 
38
+ ### 三条主链
39
+
40
+ **入库** — 选 PDF 或文件夹(最多扫两层子目录)。解析结果按内容哈希复用,同一篇不会重复解析。
41
+
42
+ **阅读** — 三栏文献库选篇,右栏进阅读器:章节目录跳转、块级续读、划线笔记、逐块中英对照、原页拖选提问。原页可连续滚动,滚轮翻页,选字是字符级。
43
+
44
+ **引用** — 正文里的 `[41]` `(Zhang et al., 2020)` 悬停即出条目原文;书目可由 Crossref / arXiv 补全,导出支持 BibTeX、RIS、CSL-JSON 与多种引用样式。
45
+
46
+ 跨篇检索、上下文注入、笔记导出走工具栏与「`Paper_*`」这组模型工具,动作表见 [SPEC.md](docs/SPEC.md)。
47
+
43
48
  ### 部署
44
49
 
45
50
  ```bash
@@ -47,105 +52,49 @@ node deploy-plugin.mjs dsh-paper # 仓库根脚本,同步到 profile
47
52
  npm run deploy:check # 退出 0 才算副本齐、profile 注册完整
48
53
  ```
49
54
 
50
- 内容更新由 hmr 热换代;只有升级/删除已加载依赖或宿主升版才需要重启宿主。
51
- 从零安装与依赖清单见 [install.md](docs/install.md)。
55
+ 内容更新由 hmr 热换代;只有升级/删除已加载依赖或宿主升版才需要重启宿主。从零安装与依赖清单见 [install.md](docs/install.md)。
52
56
 
53
57
  ## 实现
54
58
 
55
- <details>
56
- <summary>四层分层、两条主链与关键不变量 — 点击展开</summary>
57
-
58
- 宿主半按四层分,依赖单向向下:**纯逻辑**(`tool-identity` / `slicing` / `reading-order` / `item-ops` /
59
- `library-model` / `blocks`,不碰 IO)→ **模型侧工具**(四个 `*-tool.js`,只做 schema 与整形)→
60
- **工具执行侧**(`tool-host.js` 的 `createToolHost(deps)`)→ **路由与装配**(`index.js`)。
61
- HTTP 分发只做三件事:`repositoryReady`、同源检查、按阶段转发;路由体按**阶段 × 领域**分组,
62
- 只读路由必须在解析请求体之前。同一件事只有一份实现:条目改写、切片、阅读顺序、导出各只有一个所有者。
59
+ 按四层组织,依赖单向向下:纯逻辑 → 模型侧工具 → 工具执行侧 → 路由与装配。同一件事只有一份实现。
63
60
 
64
- **解析链**:入库先把 PDF 复制进 runtime(同哈希幂等)→ 复用已有记录 → 才调 MinerU(VLM 优先,
65
- 失败补一次 pipeline)→ 整批提交(正文、目录、块列表、图片一起 stage 再逐个 `rename`,失败反序回滚)。
66
- 解析完成后按文章名自动改名,那是 **9 个文件搬家**而不是改一个文件。
61
+ 解析链是「入库即复制 → 复用已有记录 → 才调 MinerU → 整批提交」,翻译链的触发点是「打开一篇文献」而不是解析完成,两条链的并发都由全局闸门限住。
67
62
 
68
- **翻译链**:触发点是「打开一篇文献」而不是解析完成;范围三档、协议三种、并发由全局闸门限住
69
- (许可挂在**每一次模型请求**上,重试也算数)。「翻译」恒定增量,「整篇重译」才全量。
70
-
71
- **关键不变量**:🔴 路径只有一个所有者且主名用入库时冻结的 `pdfName` · 🔴 入库不写用户目录 ·
72
- 🔴 一个任务的执行权只有一个拥有者 · 🔴 「记录里没有这个键 = 显式清空」的写入必须用搬动前读到的那份记录 ·
73
- 🔴 回滚按字节不按记录对象重写 · 🔴 `section` 走阅读顺序、`blocks` 走块数组顺序 ·
74
- 🔴 注入默认关闭且单条消息区块整块保留或整块丢弃。
75
-
76
- 源码映射:
77
-
78
- | 关注点 | 入口 |
79
- | --- | --- |
80
- | 宿主装配、HTTP 分发 | `lib/index.js` |
81
- | 路径规则(唯一所有者)|`lib/store-paths.js` |
82
- | 解析队列与闸门 | `lib/resolver.js` · `lib/mineru-sdk.js` · `lib/result-archive.js` |
83
- | 阅读顺序与章节 | `lib/reading-order.js` · `lib/outline.js` · `lib/slicing.js` |
84
- | 翻译 | `lib/translate.js` · `lib/translate-prompts.js` · `lib/concurrency-gate.js` |
85
- | 跨篇检索 | `lib/search-index.js` · `lib/search-database.js` · `lib/search-terms.js` |
86
- | arXiv 源码层 | `lib/tex-*.js` · `lib/pdf-text.js` |
87
- | 客户端(源 / 产物)|`lib/client-parts/*.js` → `lib/client.js` |
88
-
89
- 完整机制见 [ARCHITECTURE.md](docs/ARCHITECTURE.md)。
90
-
91
- </details>
63
+ 代码分层、磁盘身份与写入边界、检索与注入、关键不变量,见 [ARCHITECTURE.md](docs/ARCHITECTURE.md)。
92
64
 
93
65
  ## 延伸阅读
94
66
 
95
- - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — 代码分层、磁盘身份与写入边界、解析与翻译两条主链、检索与注入、关键不变量
96
- - [docs/SPEC.md](docs/SPEC.md) — 四个工具的动作表、配置项、HTTP 路由、存储布局、状态码与退出码
97
- - [docs/PITFALLS.md](docs/PITFALLS.md) — 九十多条「现象 → 根因 → 规避」,含实测数字与反向验证过的回归
98
- - [docs/DECISIONS.md](docs/DECISIONS.md) — 45 条方向性选择,每条带背景、决定、后果与重审条件
99
- - [docs/install.md](docs/install.md) — 从零安装的依赖清单、步骤与验收清单
100
- - [docs/arXiv 源码计划](docs/arxiv-source-plan.md) — 源码优先层的判据与实测交付记录
101
- - [docs/阅读器设计](docs/reader-design.md) — 空块折叠、阅读位置、划线与中英对齐的实现判据
102
- - [docs/书目补全](docs/metadata-enrichment.md) — Crossref / arXiv 两路补全的判据与冲突处理
103
- - [docs/书目互通](docs/bibliography.md) — BibTeX / RIS / CSL-JSON 导入导出与引用样式
104
- - [docs/Zotero 差距](docs/zotero-gaps.md) — 排除多端同步后的其余能力差距
105
- - [docs/界面规划](docs/ui-plan.md) — 三栏文献库与右栏阅读器的界面规划稿(历史,非权威)
67
+ | 文档 | 讲什么 |
68
+ | --- | --- |
69
+ | [ARCHITECTURE.md](docs/ARCHITECTURE.md) | 代码分层、磁盘身份与写入边界、解析与翻译两条主链、检索与注入、关键不变量 |
70
+ | [SPEC.md](docs/SPEC.md) | 四个工具的动作表、配置项、HTTP 路由、存储布局、状态码与退出码 |
71
+ | [PITFALLS.md](docs/PITFALLS.md) | 现象 → 根因 → 规避,含实测数字与反向验证过的回归 |
72
+ | [DECISIONS.md](docs/DECISIONS.md) | 方向性选择,每条带背景、决定、后果与重审条件 |
73
+ | [install.md](docs/install.md) | 从零安装的依赖清单、步骤与验收清单 |
74
+ | [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) | 随包发布的三方组件许可声明 |
75
+ | [reader-design.md](docs/reader-design.md) | 空块折叠、阅读位置、划线与中英对齐的实现判据 |
76
+ | [metadata-enrichment.md](docs/metadata-enrichment.md) | Crossref / arXiv 两路补全的判据与冲突处理 |
77
+ | [bibliography.md](docs/bibliography.md) | BibTeX / RIS / CSL-JSON 导入导出与引用样式 |
78
+ | [arxiv-source-plan.md](docs/arxiv-source-plan.md) | 源码优先层的判据与交付记录 |
79
+ | [zotero-gaps.md](docs/zotero-gaps.md) | 排除多端同步后的其余能力差距 |
106
80
 
107
81
  ## 已知限制
108
82
 
109
- - **不自动补造空节正文**,也不跨章节搬移浮动图表;图内文字需通过原页核对。
110
- 正文与目录以现有解析产物为输入,漏字、错字和图片内文字由解析流程负责。
83
+ - **不自动补造空节正文**,也不跨章节搬移浮动图表;图内文字需通过原页核对。正文与目录以现有解析产物为输入,漏字、错字和图片内文字由解析流程负责。
111
84
  - **arXiv 源码增强默认关闭**(`texSourceEnabled`):打开后只对 arXiv 来源生效,任一环不成立就整篇退回 MinerU。
112
85
  - **书目补全依赖公开登记的覆盖**:未登记或不适用的卷期页码保持空白,版本冲突不自动合并。
113
86
  - **笔记导出的可选块 id 与源文件夹自动改名暂未提供**;源目录搬迁会影响用户既有分类工作流。
114
- - **两个系统窗口(选择 PDF / 选择文件夹)只支持 Windows**:非 win32 回 501,企业机被
115
- ConstrainedLanguage 策略挡住时同样只报错一行(此时路径粘贴与其余功能照常可用)。
87
+ - **两个系统窗口(选择 PDF / 选择文件夹)只支持 Windows**:非 win32 回 501,企业机被 ConstrainedLanguage 策略挡住时同样只报错一行(此时路径粘贴与其余功能照常可用)。
116
88
  - **模型工具面不提供永久删除**:`Paper_library` 只到回收站。
117
89
  - **检索未承诺恒定查询耗时**:首页仍需全库内容校验;中文按子串匹配、引号内按连续词组匹配。
118
90
 
119
91
  ## 开发笔记
120
92
 
121
- <details>
122
- <summary>维护者上下文 — 点击展开</summary>
123
-
124
- 非权威内容:工作假设与待排查方向,随时可能被推翻。
125
-
126
- - 新增设置项要同时改三处:默认值、白名单、校验。默认值只能存在一处。
127
- - 改 `lib/client-parts/` 之后必须跑 `node scripts/sync-client-parts.mjs`;`lib/client.js` 标记块之间是产物。
128
- `npm run check` 会跑 `--check`,源与产物不同步直接失败。
129
- - 只测闸门/渲染器这类「类本身」不够:实测摘掉 `index.js` 的 `gate: translationGate` 一行,
130
- 全仓 745 个测试一个都不红。新接线要有**穿透真实接线**的用例。
131
- - 断言要打在被观察的**那一层**:选区提问那个缺陷之所以溜过去,是因为用例断言了请求体里的字段,
132
- 而客户端本来就发对了 —— 要断言的是**投递出去的那条消息**。
133
- - 改 `sourceHashOf` 的口径时记得:哈希若仍按原串算,已经存下来的坏译文会被一直跳过、永远修不回来。
134
- - 部署面只剩 `desktop`;`npm audit` 必须显式给 `--registry=https://registry.npmjs.org`
135
- (本机默认镜像不实现审计端点);`package-lock.json` 只能在干净目录生成。
136
- - **测试 CI**:[`dsh-paper-ci.yml`](../../.github/workflows/dsh-paper-ci.yml) 随插件改动自动运行、也可手动触发。
137
- Windows 跑 `npm run check` 全量测试(额外安装与宿主镜像同版的测试工具包),Ubuntu 24.04 跑 PDF/选区跨平台回归,
138
- 并用真正的 PDFium + Chromium 逐字测坐标、逐像素检查**同一行蓝色选区不留白**、核对真实鼠标拖选;
139
- 截图作为 Actions artifact 保存 7 天。两者都跑 `npm run smoke`。测试 CI 不发布 npm 包。
140
- - **发版**见 [.agents/skills/dsh-paper-npm-release](../../.agents/skills/dsh-paper-npm-release/SKILL.md):
141
- **改 `package.json` 的 version 并推到 main 就发版**,其余提交不触发。
142
- `dsh-paper-release.yml` 盯着 `Plugins/dsh-paper/package.json` 这条路,先查 npm 判断该版本
143
- 是否已存在(幂等),过发布闸门,**自己打 tag `dsh-paper-v<版本>`**,再用 OIDC 发布 ——
144
- tag 是产物不是输入,所以它恒等于实际发出去的版本,也不存在「忘了打 tag 就静默不发」。
145
- 一键等效操作:`node scripts/release.mjs <版本号>`(过闸门 → 改版本号与 lockfile → 提交 → 推 HEAD)。
146
- 任何 npm 写操作都要显式 `--registry=https://registry.npmjs.org` —— 本机全局是镜像,
147
- 而 `npm publish`、`npm trust` 都**不读** scope 级 registry 配置。
148
- - 宿主接口一有变化,先看 [PITFALLS.md](docs/PITFALLS.md) 里有没有对应的旧坑,
149
- 再去改 [ARCHITECTURE.md](docs/ARCHITECTURE.md) 的不变量一节。
150
-
151
- </details>
93
+ 维护者上下文、待排查方向与踩过的坑都在 [docs/PITFALLS.md](docs/PITFALLS.md) 与 [docs/DECISIONS.md](docs/DECISIONS.md) 里,本节只留入口:
94
+
95
+ - **改客户端**:源在 `lib/client-parts/*.js`,`lib/client.js` 标记块之间是拼接产物。改完跑 `node scripts/sync-client-parts.mjs`,`npm run check` 会拦下不同步。
96
+ - **新增设置项**:默认值、白名单、校验三处要一起改,默认值只能存在一处。
97
+ - **写回归用例**:断言要打在被观察的那一层,只测类本身不足以覆盖真实接线。
98
+ - **宿主接口变化**:先翻 [PITFALLS.md](docs/PITFALLS.md) 有没有对应的旧坑,再改 [ARCHITECTURE.md](docs/ARCHITECTURE.md) 的不变量一节。
99
+
100
+ 部署同步、测试与各条检查命令的判据见 [SPEC.md](docs/SPEC.md)。
@@ -0,0 +1,69 @@
1
+ # Third-Party Notices
2
+
3
+ dsh-paper 以 [MIT](LICENSE) 发布。它依赖下列第三方软件,每个项目仍归各自的许可管辖。
4
+
5
+ 本文件列 **直接依赖** 与 **运行时传递闭包**。开发期工具(测试、构建、发布脚本)不进入 npm 产物,不在此表。完整的传递闭包与精确版本记录在 [`package-lock.json`](package-lock.json),可用 `npm ls --all` 复核。
6
+
7
+ 本插件自身代码、界面、文档与图形资产归 MIT;下表组件各有其许可,两者不因同处一个安装树而混同。
8
+
9
+ ## 直接运行时依赖
10
+
11
+ 插件在运行时直接 `import` 的包,随插件一起被安装。
12
+
13
+ | 包 | 版本 | 许可 | 上游 |
14
+ | --- | --- | --- | --- |
15
+ | `@citation-js/core` | 0.9.0 | MIT | [citation-js/citation-js](https://github.com/citation-js/citation-js) |
16
+ | `@citation-js/plugin-bibtex` | 0.9.0 | MIT | [citation-js/citation-js](https://github.com/citation-js/citation-js) |
17
+ | `@citation-js/plugin-csl` | 0.9.0 | MIT | [citation-js/citation-js](https://github.com/citation-js/citation-js) |
18
+ | `@citation-js/plugin-ris` | 0.9.0 | MIT | [citation-js/citation-js](https://github.com/citation-js/citation-js) |
19
+ | `@xmldom/xmldom` | 0.9.12 | MIT | [xmldom/xmldom](https://github.com/xmldom/xmldom) |
20
+ | `https-proxy-agent` | 9.1.0 | MIT | [TooTallNate/proxy-agents](https://github.com/TooTallNate/proxy-agents) |
21
+ | `katex` | 0.16.47 | MIT | [KaTeX/KaTeX](https://github.com/KaTeX/KaTeX) |
22
+ | `socks` | 2.8.10 | MIT | [JoshGlazebrook/socks](https://github.com/JoshGlazebrook/socks) |
23
+
24
+ ## 运行时传递依赖
25
+
26
+ 由上面那些包引入,同样随插件一起被安装。
27
+
28
+ | 包 | 版本 | 许可 | 上游 |
29
+ | --- | --- | --- | --- |
30
+ | `@citation-js/date` | 0.5.1 | MIT | [citation-js/date](https://github.com/citation-js/date) |
31
+ | `@citation-js/name` | 0.4.2 | MIT | [citation-js/name](https://github.com/citation-js/name) |
32
+ | `agent-base` | 9.0.0 | MIT | [TooTallNate/proxy-agents](https://github.com/TooTallNate/proxy-agents) |
33
+ | `citeproc` | 2.4.63 | CPAL-1.0 OR AGPL-1.0 | [juris-m/citeproc-js](https://github.com/juris-m/citeproc-js) |
34
+ | `commander` | 8.3.0 | MIT | [tj/commander.js](https://github.com/tj/commander.js) |
35
+ | `debug` | 4.4.3 | MIT | [debug-js/debug](https://github.com/debug-js/debug) |
36
+ | `ip-address` | 10.7.5 | MIT | [beaugunderson/ip-address](https://github.com/beaugunderson/ip-address) |
37
+ | `moo` | 0.5.3 | BSD-3-Clause | [tjvr/moo](https://github.com/tjvr/moo) |
38
+ | `ms` | 2.1.3 | MIT | [vercel/ms](https://github.com/vercel/ms) |
39
+ | `proxy-agent-negotiate` | 1.1.0 | MIT | [TooTallNate/proxy-agents](https://github.com/TooTallNate/proxy-agents) |
40
+ | `smart-buffer` | 4.2.0 | MIT | [JoshGlazebrook/smart-buffer](https://github.com/JoshGlazebrook/smart-buffer) |
41
+ | `sync-fetch-undici` | 0.7.1 | MIT | [larsgw/sync-fetch](https://github.com/larsgw/sync-fetch) |
42
+ | `whatwg-mimetype` | 5.0.0 | MIT | [jsdom/whatwg-mimetype](https://github.com/jsdom/whatwg-mimetype) |
43
+
44
+ ## 由宿主提供(不随本包安装)
45
+
46
+ 这些包由 DSH 宿主在运行时供给,本插件的 `package.json` 只在 `peerDependencies` 里声明版本区间,不把副本装进自己的安装树。
47
+
48
+ | 包 | 版本区间 | 许可 | 上游 |
49
+ | --- | --- | --- | --- |
50
+ | `@deepseek-ai/schemastery` | `^3.18.1` | MIT | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) |
51
+ | `@deepseek-ai/cosmokit` | 随 schemastery | MIT | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) |
52
+ | `@standard-schema/spec` | 随 schemastery | MIT | [standard-schema/standard-schema](https://github.com/standard-schema/standard-schema) |
53
+
54
+ ## 需要单独说明的许可
55
+
56
+ **`citeproc`(CPAL-1.0 OR AGPL-1.0,双许可)** 是唯一非宽松许可的运行时组件,经 `@citation-js/plugin-csl` 引入 CSL 引用渲染。本插件按 **CPAL-1.0** 一支使用:只在本地进程内调用它的渲染能力,不修改其源码,也不通过网络向用户提供其功能。若你分发本插件,需要一并满足 CPAL-1.0 对分发者的要求;`node_modules/citeproc/LICENSE` 随包提供原文。
57
+
58
+ **`moo`(BSD-3-Clause)** 是唯一非 MIT 的宽松许可,经 `@citation-js/plugin-bibtex` 引入。BSD-3-Clause 与 MIT 兼容,保留版权声明即可。
59
+
60
+ 其余全部为 MIT。
61
+
62
+ ## 复核方式
63
+
64
+ ```bash
65
+ npm ls --all # 运行时闭包与版本
66
+ npm query ":attr(license)" | jq -r '.[] | "\(.name) \(.version) \(.license)"' | sort # 逐包许可
67
+ ```
68
+
69
+ 改动依赖后请同步本表;`package-lock.json` 是版本的唯一真源,本表是许可的说明面。
@@ -117,6 +117,14 @@ export function planTargets(args, normalizeBlockId = trimId) {
117
117
  if (raw.length > 0) {
118
118
  if (raw.length > MAX_TARGETS) return { error: '一次最多写 ' + MAX_TARGETS + ' 段;再多请先合并。' }
119
119
  for (const [index, entry] of raw.entries()) {
120
+ // 🔴 targets 的子 schema 在宿主的输入侧**从未被执行**(宿主只对输出做递归校验),
121
+ // 所以拼错的键会被静默忽略:写 targets:[{blockID:'p1-p3', text:'…'}] 时 blockId 取不到,
122
+ // 落到 HEAD_ANCHOR —— 回执说成功,内容挂到了整篇上,用户找不到它写在哪。
123
+ // 这里按 TARGET_SCHEMA 的 additionalProperties:false 自己判一遍,并给出准确的可选键名。
124
+ const unknownKeys = Object.keys(entry ?? {}).filter(key => !(key in TARGET_SCHEMA.properties))
125
+ if (unknownKeys.length > 0) {
126
+ return { error: '第 ' + (index + 1) + ' 段不支持 ' + unknownKeys.join(' / ') + ';可用键:' + Object.keys(TARGET_SCHEMA.properties).join(' / ') + '。' }
127
+ }
120
128
  const text = textOf(entry?.text)
121
129
  const kind = textOf(entry?.kind).trim() || outerKind
122
130
  if (!ANNOTATION_KINDS.includes(kind)) return { error: '第 ' + (index + 1) + ' 段的 kind 只能是 answer 或 note。' }
@@ -124,6 +132,16 @@ export function planTargets(args, normalizeBlockId = trimId) {
124
132
  if (byteLength(text) > MAX_ANNOTATION_BYTES) {
125
133
  return { error: '第 ' + (index + 1) + ' 段太长了(' + byteLength(text) + ' 字节,上限 ' + MAX_ANNOTATION_BYTES + ')。请拆成几条。' }
126
134
  }
135
+ // `quote` 与 `question` 也进 sidecar,同样要限长:它们原来完全不过闸,
136
+ // 实测两个 400 KiB 的字段能原样落盘(单条 payload 819 KB),而 `text` 超 1 字节就被拒。
137
+ // 这两个字段的语义是「被引用的那一句」与「提问」,超出单段上限的多半不是这两件事。
138
+ const tooLong = [
139
+ ['quote', textOf(entry?.quote)],
140
+ ['question', textOf(entry?.question)],
141
+ ].find(([, value]) => byteLength(value) > MAX_ANNOTATION_BYTES)
142
+ if (tooLong !== undefined) {
143
+ return { error: '第 ' + (index + 1) + ' 段的 ' + tooLong[0] + ' 太长了(' + byteLength(tooLong[1]) + ' 字节,上限 ' + MAX_ANNOTATION_BYTES + ')。' }
144
+ }
127
145
  items.push({
128
146
  blockId: normalizeBlockId(entry?.blockId) || HEAD_ANCHOR,
129
147
  text,
@@ -140,6 +158,12 @@ export function planTargets(args, normalizeBlockId = trimId) {
140
158
  if (byteLength(text) > MAX_ANNOTATION_BYTES) {
141
159
  return { error: 'text 太长了(' + byteLength(text) + ' 字节,上限 ' + MAX_ANNOTATION_BYTES + ')。请分成几条写回。' }
142
160
  }
161
+ // 单条写回这条路径同样要挡(理由见 targets 那支)。
162
+ for (const [field, value] of [['quote', textOf(args?.quote)], ['question', textOf(args?.question)]]) {
163
+ if (byteLength(value) > MAX_ANNOTATION_BYTES) {
164
+ return { error: field + ' 太长了(' + byteLength(value) + ' 字节,上限 ' + MAX_ANNOTATION_BYTES + ')。' }
165
+ }
166
+ }
143
167
  return {
144
168
  items: [{
145
169
  blockId: normalizeBlockId(args?.blockId) || HEAD_ANCHOR,
@@ -161,8 +185,25 @@ export function planTargets(args, normalizeBlockId = trimId) {
161
185
  * @param {(path: string, payload: object) => Promise<void>} deps.writePayload 写边注文件
162
186
  * @param {(payload: object, input: object) => {payload: object, added: boolean, thread: object}} deps.appendThread
163
187
  * @param {(payload: object, input: object) => {payload: object, found: boolean, thread: object|null}} deps.answerThread
188
+ * @param {(documentId: string, operation: (fresh?: object) => Promise<object>) => Promise<object>} [deps.serialize]
189
+ * 在这篇论文的**文档写锁**里跑一次读改写。fresh 是锁内重新取的文档记录(拿不到时是 undefined)。
190
+ * 🔴 必须是跨进程的写锁,不能是进程内队列:边注与 Markdown 同目录同主名,改名会换路径,
191
+ * 第二个宿主或同进程的改名都会让锁外算出的 path 指向旧文件(见 pathOfFresh)。
164
192
  */
165
193
  export function createAnnotateTool(deps = {}) {
194
+ /**
195
+ * 锁内该写的边注路径。
196
+ *
197
+ * 🔴 deps.pathOf 用的是**锁外**那份记录:边注与 Markdown 同目录同主名,改名直接换主名,
198
+ * 于是锁外算出的路径会指向旧文件 —— 笔记写进去了,但阅读器按新主名读,面板上一条都没有。
199
+ * 序列化器在锁内重新给出记录时用它现算;拿不到记录(工具单测的替身、没有仓库的部署)
200
+ * 就退回锁外那份,那种场景下本来也不存在改名竞争。
201
+ */
202
+ function pathOfFresh(documentId, document, fresh) {
203
+ const current = fresh === undefined || fresh === null ? document : fresh
204
+ return textOf(deps.pathOf(current ?? document))
205
+ }
206
+
166
207
  return toolContract({
167
208
  name: 'Paper_annotate',
168
209
  description: TOOL_DESCRIPTION,
@@ -196,14 +237,18 @@ export function createAnnotateTool(deps = {}) {
196
237
  if (threadId === '') return { ok: false, code: 'THREAD_REQUIRED', notice: 'delete 需要 threadId。', documentId: '', blockId: HEAD_ANCHOR, kind: 'note' }
197
238
  const hit = await deps.findPaper(reference)
198
239
  if (!hit?.document) return { ok: false, code: hit?.code ?? 'PAPER_NOT_FOUND', notice: hit?.error ?? '找不到论文。', documentId: '', blockId: HEAD_ANCHOR, kind: 'note' }
240
+ const documentId = textOf(hit?.documentId)
199
241
  const path = deps.pathOf(hit.document)
200
- if (!path) return { ok: false, code: 'NO_CONTENT', notice: '这篇论文没有可写的边注位置。', documentId: hit.documentId, blockId: HEAD_ANCHOR, kind: 'note' }
201
- const remove = async () => {
202
- const result = deps.deleteThread(await deps.readPayload(path), threadId)
203
- if (result.found) await deps.writePayload(path, result.payload)
204
- return { ok: true, notice: result.found ? '已删除这条边注。' : '这条边注已不存在。', documentId: hit.documentId, blockId: HEAD_ANCHOR, kind: 'note', deletedId: threadId }
242
+ if (!path) return { ok: false, code: 'NO_CONTENT', notice: '这篇论文没有可写的边注位置。', documentId, blockId: HEAD_ANCHOR, kind: 'note' }
243
+ const remove = async fresh => {
244
+ // 锁内重新取记录再算路径:改名会换主名,沿用锁外算出的 path 会把删除写到旧文件上。
245
+ const target = pathOfFresh(documentId, hit.document, fresh)
246
+ if (target === '') return { ok: false, code: 'NO_CONTENT', notice: '这篇论文没有可写的边注位置。', documentId, blockId: HEAD_ANCHOR, kind: 'note' }
247
+ const result = deps.deleteThread(await deps.readPayload(target), threadId)
248
+ if (result.found) await deps.writePayload(target, result.payload)
249
+ return { ok: true, notice: result.found ? '已删除这条边注。' : '这条边注已不存在。', documentId, blockId: HEAD_ANCHOR, kind: 'note', deletedId: threadId }
205
250
  }
206
- return typeof deps.serialize === 'function' ? deps.serialize(remove) : remove()
251
+ return typeof deps.serialize === 'function' ? deps.serialize(documentId, remove) : remove(undefined)
207
252
  }
208
253
 
209
254
  const plan = planTargets(args, deps.normalizeBlockId)
@@ -290,9 +335,12 @@ export function createAnnotateTool(deps = {}) {
290
335
  }
291
336
  }
292
337
 
293
- const write = async () => {
338
+ const write = async fresh => {
294
339
  try {
295
- let payload = await deps.readPayload(path)
340
+ // 锁内重算路径:改名换主名之后,锁外算出的 path 指向旧文件(见 pathOfFresh)。
341
+ const target = pathOfFresh(documentId, document, fresh)
342
+ if (target === '') return { ok: false, code: 'NO_CONTENT', notice: '这篇论文没有可读的正文,无处写回。', documentId, blockId: plan.items[0].blockId, kind: plan.items[0].kind }
343
+ let payload = await deps.readPayload(target)
296
344
  const written = []
297
345
  for (const item of plan.items) {
298
346
  // kind=answer 且带 question 时走 appendThread 的幂等键(同一段同一问不重复建条),
@@ -310,7 +358,7 @@ export function createAnnotateTool(deps = {}) {
310
358
  written.push({ id: appended.thread.id, added: appended.added, blockId: item.blockId, kind: item.kind })
311
359
  }
312
360
  // 🔴 先落盘再返回成功:写回是这次调用的**全部意义**,磁盘没写上就不能说 ok。
313
- await deps.writePayload(path, payload)
361
+ await deps.writePayload(target, payload)
314
362
  const first = written[0]
315
363
  const where = written.length === 1 ? '第 ' + first.blockId + ' 段旁边' : written.length + ' 段旁边'
316
364
  const sourceDir = textOf(document?.sourceDir)
@@ -328,7 +376,7 @@ export function createAnnotateTool(deps = {}) {
328
376
  return { ok: false, notice: '写回失败:' + messageOf(error), documentId, blockId: plan.items[0].blockId, kind: plan.items[0].kind }
329
377
  }
330
378
  }
331
- return typeof deps.serialize === 'function' ? deps.serialize(write) : write()
379
+ return typeof deps.serialize === 'function' ? deps.serialize(documentId, write) : write(undefined)
332
380
  },
333
381
  })
334
382
  }
@@ -1,39 +1,58 @@
1
- import { readFile, stat } from 'node:fs/promises'
1
+ import { createHash } from 'node:crypto'
2
+ import { readFile } from 'node:fs/promises'
2
3
  import { splitBlocks } from './blocks.js'
3
4
 
4
- /** Bounded by bytes and document count. Only complete successful reads enter the cache. */
5
+ /**
6
+ * 块列表读取(带缓存)。只有完整成功的读取会进缓存。
7
+ *
8
+ * 🔴 **指纹必须来自内容,不能来自 stat。** 曾经用 `mtimeMs:ctimeMs:size` 判定「文件没变」,
9
+ * 而这个判据在真实使用里会失效:Windows 上 mtime/ctime 的时间粒度粗,两次快速写入可能落在
10
+ * 同一刻度;`ino` 在就地改写时根本不变(实测 100/100 不变);当前 Node 也没有 `mtimeNs`。
11
+ * 三者叠加的结果是——**同一篇论文重新解析、块数不变而内容变了时,阅读器继续显示旧正文**。
12
+ * 实测压测 200 次里 17 次返回旧内容;单测里 `before` 与 `after!` 恰好都是 6 字节,正好撞上。
13
+ *
14
+ * 代价:命中时仍要读一次文件(约 0.14ms / 263KB)并哈希(约 0.18ms),省下的是 JSON.parse
15
+ * 与 splitBlocks(合计约 0.57ms)。收益从「省掉整条链路」降到「省掉解析那半段」,但没有它
16
+ * 这个缓存就是在拿正确性换速度。
17
+ */
5
18
  export function createBlockReader({ maxBytes = 32 * 1024 * 1024, maxEntries = 64 } = {}) {
6
19
  const entries = new Map()
7
20
  let bytes = 0
8
21
  return async function readerBlocksOf(path) {
9
22
  if (typeof path !== 'string' || path === '') return { blocks: [], notice: '这篇论文没有块列表(解析结果里没有 content.json),暂时只能看原文。' }
23
+ let text
10
24
  try {
11
- const info = await stat(path)
12
- const fingerprint = `${info.mtimeMs}:${info.ctimeMs}:${info.size}`
13
- const cached = entries.get(path)
14
- if (cached?.fingerprint === fingerprint) {
15
- entries.delete(path)
16
- entries.set(path, cached)
17
- return cached.value
18
- }
19
- if (cached) { entries.delete(path); bytes -= cached.bytes }
20
- const parsed = JSON.parse(await readFile(path, 'utf8'))
21
- if (!Array.isArray(parsed)) return { blocks: [], notice: '这篇论文的块列表不是数组,已按无块列表处理,暂时只能看原文。' }
22
- const blocks = splitBlocks(parsed)
23
- const value = { blocks: Object.freeze(blocks.map(block => Object.freeze(block))), notice: '' }
24
- const size = Buffer.byteLength(JSON.stringify(blocks), 'utf8')
25
- if (size <= maxBytes) {
26
- while (entries.size > 0 && (entries.size >= maxEntries || bytes + size > maxBytes)) {
27
- const key = entries.keys().next().value
28
- bytes -= entries.get(key).bytes
29
- entries.delete(key)
30
- }
31
- entries.set(path, { value, fingerprint, bytes: size })
32
- bytes += size
33
- }
34
- return value
25
+ text = await readFile(path, 'utf8')
35
26
  } catch {
36
27
  return { blocks: [], notice: '这篇论文的块列表读不到或格式已损坏,已按无块列表处理,暂时只能看原文。' }
37
28
  }
29
+ const fingerprint = createHash('sha256').update(text).digest('base64')
30
+ const cached = entries.get(path)
31
+ if (cached !== undefined && cached.fingerprint === fingerprint) {
32
+ entries.delete(path)
33
+ entries.set(path, cached)
34
+ return cached.value
35
+ }
36
+ if (cached !== undefined) { entries.delete(path); bytes -= cached.bytes }
37
+ let parsed
38
+ try {
39
+ parsed = JSON.parse(text)
40
+ } catch {
41
+ return { blocks: [], notice: '这篇论文的块列表读不到或格式已损坏,已按无块列表处理,暂时只能看原文。' }
42
+ }
43
+ if (!Array.isArray(parsed)) return { blocks: [], notice: '这篇论文的块列表不是数组,已按无块列表处理,暂时只能看原文。' }
44
+ const blocks = splitBlocks(parsed)
45
+ const value = { blocks: Object.freeze(blocks.map(block => Object.freeze(block))), notice: '' }
46
+ const size = Buffer.byteLength(JSON.stringify(blocks), 'utf8')
47
+ if (size <= maxBytes) {
48
+ while (entries.size > 0 && (entries.size >= maxEntries || bytes + size > maxBytes)) {
49
+ const key = entries.keys().next().value
50
+ bytes -= entries.get(key).bytes
51
+ entries.delete(key)
52
+ }
53
+ entries.set(path, { value, fingerprint, bytes: size })
54
+ bytes += size
55
+ }
56
+ return value
38
57
  }
39
58
  }
@@ -26,12 +26,26 @@ const MARKER_LINE = /^<!-- b:(\S+) -->$/
26
26
  */
27
27
  const KIND_BY_LETTER = { h: 'heading', p: 'para', l: 'list', e: 'math', t: 'table', f: 'figure', c: 'code', r: 'references', n: 'note' }
28
28
 
29
- /** 相似度判定的最小归一化长度:太短的文本(作者名、页码)靠前缀匹配没有区分度。 */
29
+ /**
30
+ * 匹配判定的最小归一化长度:太短的文本(作者名、页码、`Fig. 3`、`Table 2`、`(a)`)
31
+ * 靠前缀没有区分度 —— 它们几乎是一切长文本的前缀。
32
+ */
30
33
  const MIN_SIMILARITY_TEXT = 24
31
34
 
35
+ /** 前缀匹配允许的长度倍差:`"1"` 与 `"1Introduction"` 差 13 倍,不是同一段。 */
36
+ const PREFIX_LENGTH_RATIO = 2
37
+
32
38
  /** 顺序约束下允许向前回看的窗口(块数)。重解析的漂移通常只影响局部。 */
33
39
  const LOOKBACK = 8
34
40
 
41
+ /**
42
+ * 页码差在匹配代价里的权重。
43
+ *
44
+ * 取得比任何可能的游标距离都大,于是「同页」永远压过「靠得近」:只有当同页确实没有
45
+ * 候选时(整篇页码平移),第二项才起作用,此时的语义是「选漂移最近的那份」。
46
+ */
47
+ const PAGE_DISTANCE_WEIGHT = 1e6
48
+
35
49
  /** Markdown 标题前缀(`#`/`##`…)。heading 块在 Markdown 里带它,而块的 sourceText 不带。 */
36
50
  const HEADING_PREFIX = /^#{1,6}\s+/
37
51
 
@@ -119,14 +133,28 @@ function freeIdNear(id, taken) {
119
133
  }
120
134
  }
121
135
 
122
- /** 相似度是否够格认作同一个块:要么前缀关系,要么足够长的公共前缀。 */
136
+ /**
137
+ * 相似度是否够格认作同一个块。
138
+ *
139
+ * 🔴 三种判定(精确 / 前缀 / 公共前缀比例)**都必须先过长度闸门**。守卫原本只挡第三种,
140
+ * 于是前缀分支成了后门:`"Fig. 3"` 是 `"Fig. 3 shows the ablation…"` 的前缀,
141
+ * `"1"` 是 `"1 Introduction"` 的前缀(归一化后连空格都没了),一个 5 字符的图注
142
+ * 就能认领整段正文的 id,挂在原段上的笔记与划线随之搬到不相干的位置。
143
+ *
144
+ * 长度闸门看**短边**:短的一方至少要 MIN_SIMILARITY_TEXT 个字符才有区分度 ——
145
+ * 判的是「短的那段够不够长到不像偶然前缀」,不是两段都要长。
146
+ *
147
+ * 精确相等不受闸门限制:正文一模一样就是同一个块,与长度无关。
148
+ */
123
149
  function isSameBlock(anchor, block) {
124
150
  const left = normalizeText(anchor.text)
125
151
  const right = normalizeText(block.sourceText)
126
152
  if (left === '' || right === '') return false
127
153
  if (left === right) return true
128
- if (left.startsWith(right) || right.startsWith(left)) return true
129
- if (Math.min(left.length, right.length) < MIN_SIMILARITY_TEXT) return false
154
+ const shorter = Math.min(left.length, right.length)
155
+ const longer = Math.max(left.length, right.length)
156
+ if (shorter < MIN_SIMILARITY_TEXT) return false
157
+ if (left.startsWith(right) || right.startsWith(left)) return longer <= shorter * PREFIX_LENGTH_RATIO
130
158
  return similarity(left, right) >= 0.6
131
159
  }
132
160
 
@@ -152,7 +180,6 @@ export function reconcileBlocks(blocks, anchors) {
152
180
  if (old.length === 0) return { blocks: list.map(block => ({ ...block })), tombstones: [], stats: emptyStats(0, list.length) }
153
181
 
154
182
  const claimed = new Set()
155
- const usedIds = new Set(list.map(block => block.id))
156
183
  const resolved = []
157
184
  let cursor = 0
158
185
 
@@ -161,20 +188,32 @@ export function reconcileBlocks(blocks, anchors) {
161
188
  const type = block.type
162
189
  let match = null
163
190
 
164
- // 1) 同页同类型的精确/前缀匹配:从游标起先向后找,找不到再在窗口内回看。
165
- for (let index = cursor; index < old.length; index += 1) {
191
+ // 🔴 `page` 是**提示**不是身份:它由解析器给(page_idx + 1),换解析器、换分页模型、
192
+ // 前面多一页,整篇都会平移一位 —— 而块文本一个字都没变。把它当硬过滤条件时,
193
+ // 实测页码一平移就是 kept:0 / tombstones:N,挂在这些块上的划线、边注、译文全部失锚,
194
+ // 用户看到的表现是「重新解析了一下,我标注的东西全没了」。
195
+ //
196
+ // 🔴 但也不能干脆不管页码:正文里逐字重复的句子是常态(节首提要、跨页续表、样板段),
197
+ // 一旦「跨页随便认领」,第 3 页那段就可能认领到第 1 页的同一个句子,笔记跟着搬走。
198
+ // 实测这是第一版两轮兜底引入的**回归**:样板段在第 3 页,笔记锚 `p3-p2` 被认到第 1 页那份。
199
+ //
200
+ // 所以改成**按代价择优**,而不是「先同页后跨页」:
201
+ // 代价 = 页码差 × `PAGE_DISTANCE_WEIGHT` + 与游标的距离
202
+ // 页码差主导,因此同页永远优先;只有同页确实没有候选(页码整体平移)时,
203
+ // 才由第二项决定选谁 —— 平移到最近的那份,而不是扫描顺序上的第一份。
204
+ // `type` 仍然硬性:段落与标题是不同的东西,文本碰巧相同也不该互相认领。
205
+ let bestScore = Number.POSITIVE_INFINITY
206
+ for (let index = Math.max(0, cursor - LOOKBACK); index < old.length; index += 1) {
166
207
  const anchor = old[index]
167
208
  if (claimed.has(anchor.id)) continue
168
- if (anchor.page !== page || anchor.type !== type) continue
169
- if (isSameBlock(anchor, block)) { match = anchor; break }
170
- }
171
- if (match === null) {
172
- for (let index = Math.max(0, cursor - LOOKBACK); index < cursor; index += 1) {
173
- const anchor = old[index]
174
- if (claimed.has(anchor.id)) continue
175
- if (anchor.page !== page || anchor.type !== type) continue
176
- if (isSameBlock(anchor, block)) { match = anchor; break }
177
- }
209
+ if (anchor.type !== type) continue
210
+ if (!isSameBlock(anchor, block)) continue
211
+ const pageDistance = Math.abs(Number(anchor.page ?? 0) - Number(page ?? 0))
212
+ const positionDistance = index >= cursor ? index - cursor : cursor - index
213
+ const score = pageDistance * PAGE_DISTANCE_WEIGHT + positionDistance
214
+ if (score >= bestScore) continue
215
+ bestScore = score
216
+ match = anchor
178
217
  }
179
218
 
180
219
  if (match !== null) {