@louisultra/dsh-verymath 0.3.3 → 0.4.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,137 @@
3
3
  All notable changes to this project are documented in this file.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
+ ## [0.4.0] - 2026-11-11
7
+
8
+ Minor rather than patch: `verymath_glossary_upsert` changes what it does with a
9
+ request that omits `term_id` and supplies a different translation for an
10
+ existing English term (overwrite → additional alias row). The data-loss fix
11
+ below cannot be made without that change, and a patch number would understate
12
+ it.
13
+
14
+ ### Fixed
15
+
16
+ - **`verymath_glossary_upsert` destroyed translations of polysemous terms.** The
17
+ upstream contract stores a second translation of the same English term as a
18
+ separate alias row (`term_id` `<en>__N`), and the bundled
19
+ `glossary_build.py` produces exactly that. The tool never created alias rows:
20
+ it used the lowercased English term as the only identity, so upserting
21
+ `group / 分组` against a document holding `group / 群` plus `group__1 / 分组`
22
+ rewrote the primary row and left two rows carrying the same translation, with
23
+ 群 gone. Upserts now resolve identity as: an explicit `term_id` (correction of
24
+ one row), else the exact `(en, cn)` pair (idempotent re-add), else a new row
25
+ whose id continues the upstream sequence (`<en>`, `<en>__1`, `<en>__2`, …),
26
+ skipping ids other rows already use. See "Changed" for the intent split this
27
+ introduces.
28
+ - `verymath_paper_graph` returned an empty `topDownOrder` and reported
29
+ `supportsMainTheorem: false` for every entity whenever `extraPaths` merged
30
+ more than one batch artifact. Batch merging unions `entities` only, so the
31
+ `main_theorems` the reading directions are rooted at were dropped; the same
32
+ applied to `focus` when the target theorem appeared only in `main_theorems`.
33
+ Main theorems are now collected across all merged artifacts.
34
+ - `verymath_glossary_query` labelled an exact Chinese match as `matchedBy: 'en'`,
35
+ so a query for 流形 reported an English-field hit.
36
+ - `verymath_sage_check` spawned a bare `sage`. A conda-installed SageMath is not
37
+ on the `PATH` a desktop app inherits (a macOS app launched from Finder reads no
38
+ login shell profile), so the probe reported SageMath missing on machines that
39
+ have it. Resolution is now explicit and documented: `VERYMATH_SAGE` (an
40
+ absolute path) wins, then `PATH`, the TeX/conda base directories, and
41
+ `<conda root>/envs/<name>/bin` for the known roots — including this package's
42
+ own documented layout `~/.verymath/miniforge`, so the recommended
43
+ `conda create -n sage sage=10.9` environment is found. The search is
44
+ SageMath-only; it is not added to the generic executable path used by the TeX
45
+ probe.
46
+ - `verymath_glossary_upsert` read the document from the query cache. A glossary
47
+ edited by the user or by the bundled `glossary_web.py` could therefore be
48
+ overwritten from a stale snapshot; the write path now re-reads from disk, and
49
+ concurrent upserts on one document are serialized so the later write cannot
50
+ drop the earlier one. The lock is keyed on the document's canonical identity
51
+ (`fs.resolve` + `processPath`), not the model-supplied string, so a relative
52
+ path and an absolute path to the same file cannot run in parallel. Scope: this
53
+ runtime only — an external editor, a bundled Python script or another DSH
54
+ process does not take the lock.
55
+ - Only a genuine `ENOENT` is now treated as "this glossary does not exist yet".
56
+ Every read failure used to map to `VERYMATH_GLOSSARY_UNAVAILABLE`, which the
57
+ upsert tool interpreted as "start an empty glossary" — a permission or I/O
58
+ error could therefore replace a real document with only the terms in that one
59
+ request. Other failures surface as `VERYMATH_IO`, and cancellation propagates.
60
+ - `upsertTerms` built its id map before validating the input, so a document with
61
+ duplicate `term_id`s was silently collapsed and the closing invariant check
62
+ could no longer see the loss. Invariants are validated first.
63
+ - `verymath_paper_graph` rejected the upstream batch protocol. Each artifact was
64
+ validated on its own, so a later batch citing a label an earlier batch defined
65
+ failed with "depends on unknown label" before the merge could run. Artifacts
66
+ are now validated as a group against the merged label set: cross-batch edges
67
+ are accepted, genuinely dangling ones are still rejected.
68
+ - `verymath_paper_graph` rendered only the first artifact in Mermaid while the
69
+ counts described every merged batch. The render now uses the merged structure.
70
+ - `verymath_paper_graph` dropped a main theorem recorded only in `main_theorems`
71
+ (no matching entity) from the top-down order, contradicting `focus`, which
72
+ resolved the same theorem. Both directions now agree.
73
+ - `verymath_glossary_build` invalidated the query cache for the path it could
74
+ parse out of `--output`. That key was the raw argument, while queries cache the
75
+ resolved absolute path, so the invalidation never matched and a later query
76
+ could serve the document from before the build. Script runs now drop the whole
77
+ glossary cache.
78
+ - Probe timers are cleared when a probe settles; an uncleared timer kept the
79
+ event loop alive for the rest of the timeout after the answer was known.
80
+
81
+ ### Internal hardening (defects introduced and fixed within this release)
82
+
83
+ These were never present in a published version. They are listed so the review
84
+ history is honest, not because any user could have hit them.
85
+
86
+ - The `(en, cn)` lookup key joined the two strings with `\u0000`. JSON strings may
87
+ contain that character, so `en="a", cn="b\u0000c"` and `en="a\u0000b", cn="c"`
88
+ produced one key and the second request could overwrite a row belonging to a
89
+ different English term. The key is JSON-encoded now.
90
+ - Alias id allocation could hang the host. A `number` counter derived from
91
+ existing suffixes meant an id such as `group__9007199254740992` made
92
+ `occurrence + 1 === occurrence`, so the allocation loop never advanced —
93
+ synchronously, freezing the event loop instead of failing. The counter is a
94
+ `BigInt`, and the suffix bound is applied to both parsing and emitting so the
95
+ allocator never produces an id it would refuse to read back.
96
+ - Invalidation after an upsert covered only the paths that call knew about, so a
97
+ query issued earlier through a symlink alias could keep serving the pre-write
98
+ document. A successful upsert now clears the glossary cache.
99
+
100
+ ### Changed
101
+
102
+ - **Behavior change in `verymath_glossary_upsert`.** A request that omits
103
+ `term_id` and supplies a different translation for an existing English term
104
+ used to overwrite the existing translation in place; it now adds an alias row
105
+ and keeps the existing translation. To change a translation, query the term
106
+ and pass the returned `term_id`. Requests are rejected (no write) when:
107
+ `term_id` is blank or unknown, the `term_id` belongs to a different English
108
+ term, the `(en, cn)` pair is already held by another row, or an id-less
109
+ request matches several rows. `en` is never rewritten by this tool, so
110
+ renaming a term is not supported. Migration for a script that relied on the
111
+ overwrite: add `term_id: '<the id you meant>'` to the request.
112
+ - `TermUpsert` gained the optional `term_id` field; the model-facing
113
+ `verymath_glossary_upsert` schema, its description and the `math-glossary`
114
+ skill gained the matching "add alias vs correct a row" guidance. The tool
115
+ descriptions state that `en` must match the target row and is not renamed.
116
+ - `parsePaperStructure` takes an optional `deferDependencyCheck`; new exports
117
+ `parsePaperBatch` (validate artifacts as a group) and `collectMainTheorems` /
118
+ `mergeStructures` in the graph module.
119
+
120
+ ### Added
121
+
122
+ - Regression tests for the glossary write contract (alias creation, correction by
123
+ `term_id`, gap/skip id allocation, oversized suffixes, `(en, cn)` key encoding,
124
+ ambiguity, unknown/blank id, duplicate ids in the input, cache and lock
125
+ behaviour), for batch reading directions, and for SageMath resolution:
126
+ **107 → 146 specs**.
127
+ - The runtime probe now exercises the tool contract rather than only the core
128
+ functions: upsert alias creation and correction by `term_id`, an unknown
129
+ `term_id` rejected without writing, a batch whose later request is invalid
130
+ writing nothing, cache invalidation reaching a symlink alias, concurrent
131
+ writes through a path alias, batch paper-graph merging (cross-batch dependency
132
+ accepted, batched main theorem driving the top-down order, every merged entity
133
+ in the Mermaid render), a main theorem recorded only in `main_theorems`
134
+ resolving in both reading directions, and a dependency missing from every batch
135
+ still rejected: **8 → 16 probe checks**.
136
+
6
137
  ## [0.3.3] - 2026-11-08
7
138
 
8
139
  ### Fixed
package/README.md CHANGED
@@ -6,6 +6,32 @@
6
6
 
7
7
  `@louisultra/dsh-verymath` 把 [VeryMath](https://github.com/orgs/VeryMath/repositories) 的 AI4Math 技能与工具封装为 [DeepSeek Harness(DSH)](https://github.com/deepseek-ai/deepseek-harness)插件,适用于 [EduWork](https://github.com/ECNU/EduWork) 及其他 DSH 0.2.x 宿主。对应 [ECNU/EduWork#152](https://github.com/ECNU/EduWork/issues/152) 的首批场景。
8
8
 
9
+ ## 快速上手
10
+
11
+ 装好插件后,在 EduWork 或任意 DSH 0.2.x 宿主里直接说这两句,就能看到能力本身:
12
+
13
+ **① 把一份 CSV 变成可查询的双语术语库**(需要本机 `python3` + `PyYAML`。`verymath_python_check` 只确认 `python3` 可用;缺 `PyYAML` 时脚本会报 `No module named 'yaml'`,用 `pip install PyYAML` 补上)
14
+
15
+ ```text
16
+ 从 source.csv 构建一份中英数学术语表,输出 glossary/glossary.json;
17
+ 然后查「同调」对应的英文。
18
+ ```
19
+
20
+ 得到符合 math-glossary 合同的 `glossary/glossary.json`(条目有序、`term_id` 唯一、`idx` 连续)和 `同调 → homology` 的查询结果。
21
+ 输入样例:[`docs/examples/source.csv`](docs/examples/source.csv)。
22
+
23
+ **② 读一篇数学预印本,看主定理依赖哪些引理**(纯文件操作,不需要 Python、不需要联网)
24
+
25
+ ```text
26
+ 帮我读 papers/maynard/fulltext.txt(arXiv 1311.4600)的第 1 节,
27
+ 把里面的定义提取成结构 JSON 并用工具校验。
28
+ ```
29
+
30
+ 再追问「画出 Theorem 1.2 的依赖关系,标明每个节点对应的原文位置」,就得到定理依赖图。
31
+ 论文全文仓库不分发(第三方许可),按 [`docs/examples/README.md`](docs/examples/README.md) 里的命令自行下载并转成文本。
32
+
33
+ 其余 12 项能力(OCR 后校对、二次规划、混合整数规划、Lean、Sage 文档查询、MATLAB、Beamer 等)的「谁在什么情况下用、用户怎么说、需要什么输入、最后得到什么、运行条件与实测记录」逐项写在 [`docs/capability-examples.md`](docs/capability-examples.md)。
34
+
9
35
  ## 提供的能力
10
36
 
11
37
  **模型工具**(安装即用,Agent 自动调用):
@@ -14,7 +40,7 @@
14
40
  | --- | --- |
15
41
  | `verymath_glossary_query` | 查询双语(英中)数学术语库 JSON:精确、前缀、子串、term_id、子领域匹配;返回例句,支持按子领域过滤消歧。 |
16
42
  | `verymath_glossary_build` | 运行上游 `math-glossary` Python 脚本,从 CSV/TSV/JSON/YAML 构建或扩充术语库。 |
17
- | `verymath_glossary_upsert` | 读论文/翻译时顺手存词:自动维护 term_id、排序与连续 idx 等合同不变量,无需手改 JSON。 |
43
+ | `verymath_glossary_upsert` | 读论文/翻译时顺手存词:自动维护 term_id、排序与连续 idx 等合同不变量,无需手改 JSON。同一英文的另一种译法存为 `en__N` 别名行(不覆盖已有译名);带 `term_id` 则纠正指定那一行。 |
18
44
  | `verymath_python_check` | 检查本机 Python 3 可用性并给出安装提示。 |
19
45
  | `verymath_paper_validate` | 校验 `math-paper-reading` 产出的 `<slug>_structure.json`(实体类型、依赖完整性)。 |
20
46
  | `verymath_paper_graph` | 论文依赖图引擎:批次合并、`cited_by` 重建、`shared_node` 枢纽、环检测、双向阅读路径、`focus` 传递闭包、Mermaid 渲染(>40 实体自动降级)。 |
@@ -77,7 +103,7 @@ dsh plugin --profile <你的profile> add ./louisultra-dsh-verymath-<version>.tgz
77
103
  ### 依赖说明
78
104
 
79
105
  - **查询与论文校验**:无需任何外部依赖。
80
- - **术语库构建/导出**(`verymath_glossary_build`):需要本地 Python 3 与上游脚本依赖(`PyYAML`;Excel 导出另需 `openpyxl`,Web 管理界面另需 `Flask`)。缺失时先用 `verymath_python_check` 检查并按提示安装;插件不捆绑 Python。
106
+ - **术语库构建/导出**(`verymath_glossary_build`):需要本地 Python 3 与上游脚本依赖(`PyYAML`;Excel 导出另需 `openpyxl`,Web 管理界面另需 `Flask`)。`verymath_python_check` 只能确认 `python3` 可用;上游依赖缺失时由脚本报错(如 `No module named 'yaml'`),按需 `pip install PyYAML openpyxl Flask`。插件不捆绑 Python。
81
107
  - **平台**:仅在 macOS(Apple Silicon)验证过(DSH CLI 沙箱 + EduWork 0.4.3 桌面端实际装载)。**Windows 未测试**:代码依赖 Node 与 Python 的 PATH;外部二进制按 PATH 与 PATHEXT 解析(不再指向 macOS 固定路径),但未在 Windows 上实测,涉及 TeX、MATLAB、osqp 等外部环境的场景尤其如此。
82
108
 
83
109
  ## 持续集成
@@ -103,7 +129,7 @@ npm run test:upstream # 上游 math-glossary 离线测试(需把 VeryMath 的
103
129
  ## 相对上游 VeryMath 的差异
104
130
 
105
131
  - **论文依赖图工具化**:上游 `skill_base`/`skill_pathway_proof` 明文要求"严禁大模型手工遍历拼接 JSON",但上游仓库并未提供合并/拓扑脚本(模型每次现场生成)。本插件用 TypeScript 实现了确定性引擎(`verymath_paper_graph`),论文阅读关键路径不再依赖 Python。
106
- - **术语读写闭环**:`verymath_glossary_upsert` 自动维护上游合同的不变量(term_id 派生、排序、连续 idx),上游只能靠模型手改 JSON。
132
+ - **术语读写闭环**:`verymath_glossary_upsert` 自动维护上游合同的不变量(term_id 派生、`en__N` 别名行、排序、连续 idx),上游只能靠模型手改 JSON。同一英文的多个译名分开成行保留,改译名用 `term_id` 指定具体行。
107
133
  - **消歧支持**:查询返回例句、支持按子领域过滤,对应上游 usage-guide 的消歧策略(上游 DSH 化后原本无法执行)。
108
134
  - **验证边界**:本插件做结构层验证(依赖完整性、环检测、断链/孤立节点),不验证数学证明的正确性——这与上游 `skill_base` 的能力边界声明一致。
109
135
 
package/README_EN.md CHANGED
@@ -6,6 +6,32 @@
6
6
 
7
7
  `@louisultra/dsh-verymath` packages the VeryMath AI4Math skills and tools as a [DeepSeek Harness (DSH)](https://github.com/deepseek-ai/deepseek-harness) plugin for [EduWork](https://github.com/ECNU/EduWork) and other DSH 0.2.x hosts. It addresses the first-phase scenarios of [ECNU/EduWork#152](https://github.com/ECNU/EduWork/issues/152).
8
8
 
9
+ ## Quick start
10
+
11
+ Once installed, say either of these in EduWork or any DSH 0.2.x host to see the capabilities directly:
12
+
13
+ **1. Turn a CSV into a queryable bilingual glossary** (needs local `python3` + `PyYAML`. `verymath_python_check` only confirms that `python3` is available; without `PyYAML` the script fails with `No module named 'yaml'`, which `pip install PyYAML` fixes)
14
+
15
+ ```text
16
+ 从 source.csv 构建一份中英数学术语表,输出 glossary/glossary.json;
17
+ 然后查「同调」对应的英文。
18
+ ```
19
+
20
+ You get a contract-conforming `glossary/glossary.json` (sorted entries, unique `term_id`, contiguous `idx`) and the lookup `同调 → homology`.
21
+ Sample input: [`docs/examples/source.csv`](docs/examples/source.csv).
22
+
23
+ **2. Read a math preprint and see which lemmas the main theorem depends on** (pure file work — no Python, no network)
24
+
25
+ ```text
26
+ 帮我读 papers/maynard/fulltext.txt(arXiv 1311.4600)的第 1 节,
27
+ 把里面的定义提取成结构 JSON 并用工具校验。
28
+ ```
29
+
30
+ Then ask "draw the dependency graph of Theorem 1.2 and mark each node's source location" to get the theorem dependency graph.
31
+ The repo does not redistribute paper full texts (third-party license); follow [`docs/examples/README.md`](docs/examples/README.md) to download and convert one yourself.
32
+
33
+ Per-capability detail for the remaining 12 (OCR post-review, QP, MILP, Lean, Sage doc lookup, MATLAB, Beamer, ...) — who uses it, what to say, what input is needed, what you get, run conditions and recorded runs — is in [`docs/capability-examples.md`](docs/capability-examples.md).
34
+
9
35
  ## What it provides
10
36
 
11
37
  **Model-facing tools** (available right after install; the Agent calls them automatically):
@@ -14,7 +40,7 @@
14
40
  | --- | --- |
15
41
  | `verymath_glossary_query` | Query a bilingual (English-Chinese) math glossary JSON: exact, prefix, substring, term_id, and subfield matching; returns examples and supports subfield disambiguation. |
16
42
  | `verymath_glossary_build` | Run the upstream `math-glossary` Python scripts to build or extend a glossary from CSV/TSV/JSON/YAML. |
17
- | `verymath_glossary_upsert` | Save terms while reading/translating: maintains contract invariants (term_id, ordering, contiguous idx) automatically — no hand-editing of glossary.json. |
43
+ | `verymath_glossary_upsert` | Save terms while reading/translating: maintains contract invariants (term_id, ordering, contiguous idx) automatically — no hand-editing of glossary.json. A second translation of the same English term is stored as an `en__N` alias row (the existing translation is kept); pass `term_id` to correct one specific row. |
18
44
  | `verymath_python_check` | Check local Python 3 availability and surface installation hints. |
19
45
  | `verymath_paper_validate` | Validate `math-paper-reading` `<slug>_structure.json` artifacts (entity kinds, dependency integrity). |
20
46
  | `verymath_paper_graph` | Paper dependency-graph engine: batch merging, `cited_by` reconstruction, `shared_node` hubs, cycle detection, both reading directions, `focus` transitive closure, Mermaid rendering (auto-degrades above 40 entities). |
@@ -75,7 +101,7 @@ Then just ask in a session, e.g. "look up the Chinese term for manifold" or "rea
75
101
  ### Dependencies
76
102
 
77
103
  - **Query and paper validation**: no external dependencies.
78
- - **Glossary build/export** (`verymath_glossary_build`): requires a local Python 3 plus the upstream script dependencies (`PyYAML`; Excel export additionally needs `openpyxl`, the web UI needs `Flask`). Check availability with `verymath_python_check` first and install per its hints; the plugin does not bundle Python.
104
+ - **Glossary build/export** (`verymath_glossary_build`): requires a local Python 3 plus the upstream script dependencies (`PyYAML`; Excel export additionally needs `openpyxl`, the web UI needs `Flask`). `verymath_python_check` only confirms that `python3` is available; a missing upstream dependency surfaces as a script error (for example `No module named 'yaml'`), so install what you need with `pip install PyYAML openpyxl Flask`. The plugin does not bundle Python.
79
105
  - **Platforms**: verified on macOS (Apple Silicon) (DSH CLI sandbox + the EduWork 0.4.3 desktop app itself); Windows should work (Node and Python on PATH) but is not yet tested — external binaries are now resolved through PATH and PATHEXT rather than a macOS-only path, though that has not been exercised on Windows. Feedback welcome.
80
106
 
81
107
  ## Continuous integration
@@ -99,7 +125,7 @@ This package is MIT licensed (`LICENSE`). Skill content and Python scripts are a
99
125
  ## Differences from upstream VeryMath
100
126
 
101
127
  - **Paper dependency graph as a tool**: upstream `skill_base`/`skill_pathway_proof` explicitly forbid model-side manual graph traversal but ship no merge/topology scripts (the model regenerates one each time). This plugin implements a deterministic TypeScript engine (`verymath_paper_graph`); the paper-reading critical path no longer requires Python.
102
- - **Glossary read/write loop**: `verymath_glossary_upsert` maintains the upstream contract invariants (term_id derivation, ordering, contiguous idx) that upstream leaves to hand-edits.
128
+ - **Glossary read/write loop**: `verymath_glossary_upsert` maintains the upstream contract invariants (term_id derivation, `en__N` alias rows, ordering, contiguous idx) that upstream leaves to hand-edits. Multiple translations of one English term stay as separate rows; corrections name the row by `term_id`.
103
129
  - **Disambiguation**: queries return examples and support subfield filtering, implementing the upstream usage-guide strategies that could not execute in DSH before.
104
130
  - **Validation scope**: this plugin performs structural validation (dependency integrity, cycles, dangling/isolated nodes) and does not verify mathematical proof correctness — consistent with the upstream `skill_base` capability boundary.
105
131
 
package/UPSTREAM.json CHANGED
@@ -12,7 +12,7 @@
12
12
  "skills/math-glossary/tests/",
13
13
  "skills/matlab-runner/ (SKILL.md + references + examples, with DSH MCP setup notes)"
14
14
  ],
15
- "adaptationNotes": "SKILL.md routing and script-invocation text adapted for DSH tool names (verymath_glossary_*); Python scripts included verbatim; tests adapted to run from the skill directory. matlab-runner bundled after user installed MATLAB R2025b; MathWorks official MCP server v0.14.0 wired via dsh-mcp-client (5 tools match the skill capability list)."
15
+ "adaptationNotes": "SKILL.md routing and script-invocation text adapted for DSH tool names (verymath_glossary_*); Python scripts included verbatim, so alias-row ids (`en__N`) are produced by the same algorithm upstream uses; tests adapted to run from the skill directory. matlab-runner bundled after user installed MATLAB R2025b; MathWorks official MCP server v0.14.0 wired via dsh-mcp-client (5 tools match the skill capability list). One sentence added to SKILL.md rule 6 (added 0.4.0) explains the DSH tool contract that the bundled scripts do not cover: adding another translation omits term_id and creates an alias row, correcting a translation passes the term_id returned by a query."
16
16
  },
17
17
  {
18
18
  "repository": "https://github.com/VeryMath/AI4Math-Paper-Reading",
@@ -21,11 +21,11 @@
21
21
  因此本仓库只保存从 arXiv 下载的**方法**,不保存正文。复现时自行下载:
22
22
 
23
23
  ```sh
24
- mkdir -p papers && cd papers
25
- curl -sL -o maynard.pdf https://arxiv.org/pdf/1311.4600
26
- curl -sL -o treewidth.pdf https://arxiv.org/pdf/2012.11459
27
- pdftotext -layout maynard.pdf fulltext.txt
28
- pdftotext -layout treewidth.pdf paper-treewidth.txt
24
+ mkdir -p papers/maynard paper
25
+ curl -sL -o papers/maynard/maynard.pdf https://arxiv.org/pdf/1311.4600
26
+ pdftotext -layout papers/maynard/maynard.pdf papers/maynard/fulltext.txt
27
+ curl -sL -o paper/treewidth.pdf https://arxiv.org/pdf/2012.11459
28
+ pdftotext -layout paper/treewidth.pdf paper/paper-treewidth.txt
29
29
  ```
30
30
 
31
31
  `pdftotext` 来自 poppler(macOS: `brew install poppler`;Debian/Ubuntu: `apt install poppler-utils`)。
@@ -18,3 +18,10 @@ export declare class VeryMathError extends Error {
18
18
  }
19
19
  /** Whether a value looks like a {@link VeryMathError}, even from a duplicated package copy. */
20
20
  export declare function isVeryMathError(error: unknown): error is VeryMathError;
21
+ /**
22
+ * Whether an error carries a specific Node filesystem `code` such as `ENOENT`.
23
+ * Callers use this to tell "the document does not exist yet" apart from every
24
+ * other I/O failure (permissions, I/O, too many open files), which must not be
25
+ * mistaken for an empty starting document.
26
+ */
27
+ export declare function isErrnoCode(error: unknown, code: string): boolean;
package/lib/core/error.js CHANGED
@@ -23,3 +23,12 @@ export function isVeryMathError(error) {
23
23
  error.name === 'VeryMathError' &&
24
24
  typeof error.code === 'string');
25
25
  }
26
+ /**
27
+ * Whether an error carries a specific Node filesystem `code` such as `ENOENT`.
28
+ * Callers use this to tell "the document does not exist yet" apart from every
29
+ * other I/O failure (permissions, I/O, too many open files), which must not be
30
+ * mistaken for an empty starting document.
31
+ */
32
+ export function isErrnoCode(error, code) {
33
+ return typeof error === 'object' && error !== null && error.code === code;
34
+ }
@@ -67,6 +67,15 @@ export interface TermUpsert {
67
67
  readonly en: string;
68
68
  /** Chinese translation (or alias). */
69
69
  readonly cn: string;
70
+ /**
71
+ * Target row for a correction: when present, the row with this `term_id` is
72
+ * updated in place. Its Chinese translation and the optional fields given are
73
+ * rewritten; its `en` must already match the request's `en`
74
+ * (case-insensitively) and is never rewritten, because renaming a term is not
75
+ * supported here. When absent, the request matches an existing row by the
76
+ * exact `(en, cn)` pair and otherwise adds an alias row.
77
+ */
78
+ readonly term_id?: string;
70
79
  /** Optional part of speech in Chinese. */
71
80
  readonly pos?: string;
72
81
  /** Optional subfields. */
@@ -81,21 +90,46 @@ export interface TermUpsert {
81
90
  }
82
91
  /** Result of one upsert batch. */
83
92
  export interface UpsertResult {
84
- /** New terms that did not exist before (by term_id). */
93
+ /** term_ids created by this batch (primary rows and `en__N` alias rows). */
85
94
  readonly added: readonly string[];
86
- /** Existing terms whose cn/pos/field/source/examples were overwritten. */
95
+ /** term_ids whose cn/pos/field/source/examples were overwritten, in request order. */
87
96
  readonly updated: readonly string[];
88
97
  /** The complete re-sorted document ready to write (idx reassigned, today's dates on changed rows). */
89
98
  readonly document: GlossaryTerm[];
90
99
  }
91
100
  /**
92
- * Merge upsert requests into an existing glossary per the upstream contract:
93
- * term_id is the lowercased en for the primary translation and `en__N` for
94
- * additional alias rows of the same en; an existing term with the same
95
- * (term_id) is updated in place; the merged document is re-sorted by
96
- * (en, cn) with contiguous idx. The input document is never mutated.
101
+ * Merge upsert requests into an existing glossary per the upstream contract.
102
+ *
103
+ * Identity is resolved in this order, which is also what the tool description
104
+ * tells the model:
105
+ *
106
+ * 1. An explicit `term_id` selects that row (the correction path). It must
107
+ * exist, and its `en` must match the request's `en` case-insensitively:
108
+ * this function never renames a term or moves a row to another English term.
109
+ * 2. Otherwise the exact `(en case-insensitive, cn exact)` pair selects the row
110
+ * that already holds that translation, so re-adding a term is idempotent. If
111
+ * several rows hold that pair the request is rejected as ambiguous rather
112
+ * than silently picking one.
113
+ * 3. Otherwise a new row is created. Its id continues the upstream alias
114
+ * sequence for that English term (the lowercased `en`, then `en__1`, …) and
115
+ * skips ids any other row already uses. This is what keeps two translations
116
+ * of the same English term as two rows, as `glossary-schema.md` requires,
117
+ * instead of overwriting the existing translation.
118
+ *
119
+ * The merged document is re-sorted by `(en, cn)` with contiguous `idx`, and the
120
+ * input document is never mutated. Every request is validated by the same
121
+ * rules, so a batch either applies completely or throws.
122
+ *
123
+ * `en` comparison uses `toLowerCase()`, matching how ids are derived; upstream
124
+ * Python uses `casefold()`, so exotic multi-character foldings (e.g. `ß` → `ss`)
125
+ * are not treated as equal here. Glossaries are built from one or the other
126
+ * path, and within a single path the comparison is self-consistent.
127
+ *
97
128
  * @param terms - current glossary terms (any order).
98
- * @param upserts - terms to add or update.
99
- * @throws VeryMathError when the merged document breaks an invariant.
129
+ * @param upserts - terms to add or correct.
130
+ * @throws VeryMathError when the input document already breaks an invariant,
131
+ * when a request names an unknown or blank `term_id`, when the `term_id`
132
+ * belongs to a different English term, when an address is ambiguous, or when
133
+ * a correction would duplicate another row's `(en, cn)` pair.
100
134
  */
101
135
  export declare function upsertTerms(terms: readonly GlossaryTerm[], upserts: readonly TermUpsert[]): UpsertResult;