From d7b649670a65902eb806bd78548dfb63743327bf Mon Sep 17 00:00:00 2001 From: UncleMoc Date: Wed, 25 Nov 2026 19:11:07 +0800 Subject: [PATCH 1/2] fix(factscribe): find Python on Windows, keep CRLF line endings on save Two fixes: one for Windows machines, one for manuscripts that use CRLF. 1. Windows interpreter discovery The candidate list had no Windows shape at all -- no "py" launcher, no versioned command, no common install directory -- and a failed probe was collapsed into "not installed". A user with Python 3.9 on the machine was told to "install Python >=3.10", with nothing to act on. - new miniapp/node/python_discovery.mjs: candidates are {command, args} and cover py, py -3, py -3.10 ... py -3.14, py.exe, versioned commands, python.exe and absolute paths under %LOCALAPPDATA%, %PROGRAMFILES% and C:\Python3xx -- 36 candidates on Windows. The macOS/Linux list is unchanged, word for word. - the probe classifies the outcome: version high enough / too low / command missing / present but the version cannot be read. The message therefore names the version it found and the executable it came from. - discovery and engine start share one "command + prefix arguments" pair, so "py -3" is used for both, not only for probing. - the settings page and the engine start failure share one message: not installed / too old (3.9 and below cannot run this engine) / installed but not on PATH (point FS_PYTHON at it) / Microsoft Store placeholder alias that cannot report its version. The requirement is unchanged: the engine needs Python >= 3.10. 2. Browser-layer CRLF preservation The engine reads sections with Python's universal-newline mode (CRLF becomes LF before the text ever reaches the page) and writes the file back byte for byte, so every save rewrote the whole file with LF endings -- a CRLF manuscript lost all its CR bytes on the first edit. - new miniapp/node/eol.mjs: split with the endings kept apart, recognise crlf / lf / mixed, put the original endings back. - the Node shell reads the real endings from disk before the save, hands the engine an LF-only body and restores the endings afterwards: lines the save did not touch keep their exact endings (a mixed file stays mixed), the edited lines take the file's dominant ending, and the text is never altered -- only the endings move. If the file changed underneath while the save ran, the endings are left alone. The vendored Python engine is untouched by both changes. Verified: - upstream checker: plugins/unclemoc/factscribe OK (0 errors, 0 warnings); npm run check exits 0 (92/92 checker self-tests). - package tests: node --test tests/*.test.mjs -- 19 cases, all green (16 unit cases for the line-ending module, plus 3 end-to-end cases that start the vendored Python engine and save into a copy of the sample paper). - measured on the vendored sample paper: a 678-byte section with 11 CRLF endings came back with all 11 endings and the same text; without the fix the engine's own save rewrote it as 667 bytes with 0 CRLF. Not verified: - Windows end to end. There is no Windows machine here. The 36 Windows candidates are generated from the platform string and covered by unit tests, but no run on a real Windows host has been done. - Linux hosts, as before. --- .../factscribe/.minimax-plugin/plugin.json | 2 +- plugins/unclemoc/factscribe/README.md | 49 +- plugins/unclemoc/factscribe/README.zh-CN.md | 38 +- .../unclemoc/factscribe/miniapp/node/eol.mjs | 163 +++++++ .../miniapp/node/python_discovery.mjs | 434 ++++++++++++++++++ .../factscribe/miniapp/node/server.mjs | 321 ++++++++++--- .../unclemoc/factscribe/tests/eol.test.mjs | 134 ++++++ .../factscribe/tests/save-eol.test.mjs | 190 ++++++++ 8 files changed, 1265 insertions(+), 66 deletions(-) create mode 100644 plugins/unclemoc/factscribe/miniapp/node/eol.mjs create mode 100644 plugins/unclemoc/factscribe/miniapp/node/python_discovery.mjs create mode 100644 plugins/unclemoc/factscribe/tests/eol.test.mjs create mode 100644 plugins/unclemoc/factscribe/tests/save-eol.test.mjs diff --git a/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json b/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json index 90168cf4..7444ccbc 100644 --- a/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json +++ b/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "name": "factscribe", "displayName": "FactScribe 论文工作台", - "version": "1.1.0", + "version": "1.2.0", "description": "A local workbench for writing papers: open your manuscript projects, read the check report, the fact ledger and the knowledge base, and let the assistant propose edits you approve before anything reaches the file. Numbers and citations stay pinned to the ledger; the AI proposes, you decide.", "author": "UncleMoc · BGISMALL", "icon": "icon.png", diff --git a/plugins/unclemoc/factscribe/README.md b/plugins/unclemoc/factscribe/README.md index 8902fac7..a868774f 100644 --- a/plugins/unclemoc/factscribe/README.md +++ b/plugins/unclemoc/factscribe/README.md @@ -48,6 +48,28 @@ Code and ask the Agent to "Open the FactScribe paper workbench". MiniMax Code 3.1.11 and later can also import the package straight from a Git repository: paste the repository URL, pick the package directory, and confirm the preview. +### Python interpreter (the machine needs ≥3.10) + +The engine is written in Python. Its source is vendored into the package, so there is nothing to `pip install`, but the machine still needs a **Python ≥3.10** interpreter. The Mini App looks for one in PATH and in the usual install locations, and the settings page states what it found, what is missing and whether the version is high enough. + +**Windows**: download the 3.10 or newer installer from and tick **Add python.exe to PATH**; open a fresh command prompt afterwards and run `py -3 --version` to confirm. A `py` launcher on its own is enough (the Mini App tries `py`, `py -3`, `py -3.14` down to `py -3.10`). An interpreter outside PATH is found too: `%LOCALAPPDATA%\Programs\Python\Python3xx\`, `%PROGRAMFILES%\Python3xx\` and `C:\Python3xx\` are all probed. If it still finds nothing, point the `FS_PYTHON` environment variable at the absolute path and restart MiniMax Code. + +**Why 3.9 does not work**: the engine needs ≥3.10 (on 3.10 it falls back to the TOML parser bundled with the package, on 3.11 and newer it uses the standard library `tomllib`), so Python 3.9 and older cannot run this engine. The Mini App therefore reports the highest version it found (3.9) and which executable it came from. An old version can stay installed next to 3.10 or newer. + +**macOS / Linux**: unchanged. The Mini App tries `python3`, `python`, `/usr/bin/python3`, `/opt/homebrew/bin/python3` and `/usr/local/bin/python3` in that order, and `FS_PYTHON` can point at an absolute path there too. + +### Line endings + +A save keeps the line endings your file already had. The engine reads sections with Python's +universal-newline mode (CRLF becomes LF before the text ever reaches the page) and writes the +file back byte for byte, so without a second step **every save rewrites the whole file with LF +endings** — a CRLF manuscript loses all its CR bytes on the first edit. The Node shell therefore +reads the real endings from the file on disk before the save, hands the engine an LF-only body, +and puts the original endings back afterwards: lines the save did not touch keep their exact +endings (a file with mixed endings stays mixed), the edited lines take the file's dominant +ending, and the text itself is never altered — only the endings move. If the file changed +underneath while the save was running, the endings are left alone instead of being overwritten. + On first use the page asks for your paper root directory: any directory that contains a `factscribe.toml` is treated as a paper project. It can be changed later from the settings page. @@ -55,13 +77,23 @@ On first use the page asks for your paper root directory: any directory that con - MiniMax Code 3.1.16 on macOS 26.6.2 (arm64). Installed from this directory, opened through the Agent, page rendered, and all 17 MCP tools called end to end over the Host's MCP runtime. -- Node 26.7 and Python 3.14 on the same machine. The Python engine is vendored inside the - package, so nothing has to be installed. +- Node 26.7 and Python 3.14 on the same machine. The Python engine source is vendored inside the + package, so nothing has to be `pip install`ed; the machine still needs a Python ≥3.10 + interpreter (see above). - Minimum client version: 3.1.2. The package declares `agentAccess: ["session.run"]`, which needs 3.1.2; no `engines` bound is declared, so clients from 3.1.2 on still install it and only lose the assistant model picker when their client does not expose the model catalogue. +- Node 26.7 with the package's own tests: `node --test tests/*.test.mjs` — 19 cases, all + green (16 unit cases for the line-ending module, plus 3 end-to-end cases that start the + vendored Python engine and save into a copy of the sample paper). +- The line-ending round trip was measured on the vendored sample paper: a 678-byte section with + 11 CRLF endings came back with all 11 endings and the same text. Without the fix the engine's + own save rewrote the same file as 667 bytes with 0 CRLF endings — every CR byte lost. - Not verified: Windows and Linux hosts. The package ships no platform-specific binary and the - Node entry uses only Node built-ins, but no run on those platforms has been done. + Node entry uses only Node built-ins, but no run on those platforms has been done. The Windows + interpreter discovery (`py` launcher, versioned commands, common install directories) is + covered by unit tests, but no end-to-end run on a real Windows machine has been done; the 36 + Windows candidates are generated from the platform string, not measured on Windows. ## Data & access @@ -72,13 +104,18 @@ On first use the page asks for your paper root directory: any directory that con `proposals/` (proposal records) and `custom-models.json` (an API key you typed yourself, mode 0600). Inside your paper directory, only where you click: `sections/*.tex` (atomic write plus a `.bak` copy, refused when the file changed underneath) and `facts/draft/` for imported drafts. - Opening a disk also records `last_opened` in that disk's `factscribe.toml`. + Opening a disk also records `last_opened` in that disk's `factscribe.toml`. Restoring the + original line endings after a save writes the same file again through a sibling temporary file + (`.eol-tmp-`) and renames it over the original, so no extra file is left behind; the + temporary file is removed if the write fails. - **Network hosts**: none by default. The Node service and the Python engine listen on loopback only (`127.0.0.1`). If you add a custom model in the panel, the Node shell sends the prompt to the OpenAI-compatible endpoint you typed; the host Agent turn is run by the Host on your MiniMax Code account and plan. -- **Processes spawned**: `python3 -B -m factscribe workbench --root --port 0 --json - --no-browser` (the engine; killed when the Mini App stops), `factscribe audit` (read-only +- **Processes spawned**: ` -B -m factscribe workbench --root --port 0 --json + --no-browser` (the engine; killed when the Mini App stops; the interpreter is the Python ≥3.10 + the Mini App found on this machine, possibly `python3`, `py -3` or the absolute path named by + `FS_PYTHON`), `factscribe audit` (read-only re-run of the check report), `tectonic` (only for the optional PDF render button) and macOS `open` (only for the "open folder" button). - **Agent turns**: the panel runs Host Agent turns through `agentAccess: ["session.run"]`. The diff --git a/plugins/unclemoc/factscribe/README.zh-CN.md b/plugins/unclemoc/factscribe/README.zh-CN.md index ca468c27..5cad1701 100644 --- a/plugins/unclemoc/factscribe/README.zh-CN.md +++ b/plugins/unclemoc/factscribe/README.zh-CN.md @@ -42,18 +42,43 @@ FactScribe 把它们变成可核对的读数: MiniMax Code 3.1.11 起也可以直接从 Git 仓库导入:贴仓库地址、选中包目录、核对预览即可。 +### Python 解释器(本机要有 ≥3.10) + +引擎是 Python 写的,源码随包 vendor,所以不用 `pip install` 任何东西;但**本机仍要有一个 Python ≥3.10 解释器**。Mini App 会自己在 PATH 与常见安装目录里找它,找到什么、缺什么、版本够不够,设置页都会写清楚。 + +**Windows**:到 下载 3.10 或更高版本的安装包,安装时勾上 **Add python.exe to PATH**;装完开一个新的命令行窗口跑 `py -3 --version` 确认。只装了 `py` 启动器也行(会依次试 `py`、`py -3`、`py -3.14` 到 `py -3.10`)。装在 PATH 之外也能找到:`%LOCALAPPDATA%\Programs\Python\Python3xx\`、`%PROGRAMFILES%\Python3xx\`、`C:\Python3xx\` 这些常见位置都会被探到;实在找不到就设环境变量 `FS_PYTHON` 指到解释器绝对路径,设完重启 MiniMax Code。 + +**为什么 3.9 不行**:引擎要求 ≥3.10(3.10 走随包的兜底 TOML 解析器,3.11 以上用标准库 `tomllib`),3.9 及以下跑不了这份引擎,所以 Mini App 会直接报出「探到的最高版本是 3.9」和它来自哪个可执行文件。旧版本可以和 3.10 以上并存,两个都装不冲突。 + +**macOS / Linux**:行为不变,按 `python3`、`python`、`/usr/bin/python3`、`/opt/homebrew/bin/python3`、`/usr/local/bin/python3` 的顺序找,`FS_PYTHON` 同样能指到绝对路径。 + +### 行尾保真 + +保存会保留文件原来的行尾。引擎读章节用 Python 的通用换行模式(CRLF 在到达页面前就变成 +LF 了),写文件又是逐字节写回,所以没有第二道工序的话,**每保存一次整篇就被改成 LF 行尾**—— +CRLF 的稿子一编辑就把 CR 全丢了。Node 薄壳因此在保存前先从磁盘读出原文件真正的行尾, +交给引擎的正文一律是 LF 形态,引擎写完再按原风格把行尾摆回去:这次保存没碰到的行连原来的 +行尾都原样留着(混合行尾的稿子保存后仍是混合的),被改动的那几行走该文件的主导行尾,正文 +一个字都不动——只有行尾在动。保存期间文件被别处改过,就不去动行尾,不覆盖别人的改动。 + 首次打开会让你填**论文根目录**:含 `factscribe.toml` 的目录会被当作论文项目,之后可在设置页改。 ## 测试环境 - MiniMax Code 3.1.16,macOS 26.6.2(arm64)。从本目录安装、经助手打开、页面渲染正常, 17 个 MCP 工具在宿主 MCP 运行时上逐个实调通过。 -- 同一台机器上的 Node 26.7 与 Python 3.14。Python 引擎已随包 vendor,不用装任何东西。 +- 同一台机器上的 Node 26.7 与 Python 3.14。Python 引擎源码已随包 vendor,不用 `pip install` 任何东西;但本机仍需一个 Python ≥3.10 解释器(见上)。 - 最低客户端版本:3.1.2。本包声明 `agentAccess: ["session.run"]`(该能力需要 3.1.2); 没有声明 `engines` 下限,所以 3.1.2 起的客户端都能装,只是客户端不提供模型目录时 面板里少一个模型下拉。 +- Node 26.7 与随包测试:`node --test tests/*.test.mjs` —— 19 例全绿(行尾模块 16 例 + 单测,加上 3 例真引擎端到端:拉起随包 Python 引擎,在样例盘副本上真存一次)。 +- 行尾往返在随包样例盘上实测过:678 字节、11 个 CRLF 的章节文件,保存后 11 个 CRLF 一个不少、 + 正文一字不差;不修的话,引擎自己那次保存会把它写成 667 字节、0 个 CRLF——CR 全丢。 - **未验证**:Windows 与 Linux 宿主。包内没有平台专属二进制、Node 入口只用内置模块, - 但没有在这两个平台上实跑过。 + 但没有在这两个平台上实跑过。Windows 上的解释器发现(`py` 启动器、版本化命令、 + 常见安装目录)有单元测试覆盖,但没有在 Windows 真机上端到端跑过;那 36 个 Windows + 候选是按平台字符串生成的,不是在 Windows 上量出来的。 ## 数据与访问 @@ -62,12 +87,15 @@ MiniMax Code 3.1.11 起也可以直接从 Git 仓库导入:贴仓库地址、 - **写入的文件**:插件私有 `dataDir`——`config.json`(论文根目录)、`proposals/`(提议单记录)、 `custom-models.json`(你自己填的 API Key,权限 0600)。你的论文目录里只有你点了才写: `sections/*.tex`(原子写+留 `.bak`,文件被别处改过就拒写)与 `facts/draft/`(草稿导入)。 - 另外「打开」一个稿盘会在该盘的 `factscribe.toml` 里记 `last_opened`。 + 另外「打开」一个稿盘会在该盘的 `factscribe.toml` 里记 `last_opened`。保存后把原行尾摆回去时, + 会先写同目录的临时文件(`<文件名>.eol-tmp-`)再改名盖回原文件,不会留下多余文件; + 写失败时临时文件会被清掉。 - **网络 host**:默认没有。Node 服务与 Python 引擎只绑回环(`127.0.0.1`)。若你在面板里 自加自定义模型,Node 薄壳会把你填的 OpenAI 兼容端点当作目标;面板里的助手回合由宿主代跑, 走你在 MiniMax Code 上的账号与额度。 -- **拉起的进程**:`python3 -B -m factscribe workbench --root <你的根目录> --port 0 --json - --no-browser`(引擎,MiniApp 停止时被杀)、`factscribe audit`(只读重跑检查报告)、 +- **拉起的进程**:`<解释器> -B -m factscribe workbench --root <你的根目录> --port 0 --json + --no-browser`(引擎,MiniApp 停止时被杀;解释器是本机探到的那个 ≥3.10 的 Python,可能是 + `python3`、`py -3`,也可能是 `FS_PYTHON` 指定的绝对路径)、`factscribe audit`(只读重跑检查报告)、 `tectonic`(只用于可选的 PDF 渲染按钮)、macOS `open`(只用于「打开目录」按钮)。 - **Agent 回合**:面板通过 `agentAccess: ["session.run"]` 跑宿主 Agent 回合,用的是 MiniMax Code 自己配的模型、宿主账号与额度;插件不读你的 API key、不读宿主配置。 diff --git a/plugins/unclemoc/factscribe/miniapp/node/eol.mjs b/plugins/unclemoc/factscribe/miniapp/node/eol.mjs new file mode 100644 index 00000000..159295aa --- /dev/null +++ b/plugins/unclemoc/factscribe/miniapp/node/eol.mjs @@ -0,0 +1,163 @@ +// 正文行尾保真:把引擎写盘时弄丢的行尾,按原文件的风格找回来。 +// +// 为什么需要这一层(为什么行尾会丢): +// +// 1. 引擎的读路径(factscribe/workbench/write.py 的 read_text)用 Python 文本 +// 模式读文件,做通用换行翻译:CRLF 在到达页面前就已经变成 LF 了—— +// 页面这一层拿不到磁盘上的真行尾。 +// 2. 引擎的写路径(write.py 的 atomic_write)用二进制模式写:它把读到的 +// LF 形态原样写回磁盘。于是**任何一次保存都会把整篇的行尾改成 LF**—— +// 一份 CRLF 的稿子存一次就没了(macOS / Linux 上同样发生,与 Windows 无关)。 +// +// 所以行尾的「真相」只在磁盘上的原文件里。这一模块只做两件事: +// +// * 读出原文件用哪种行尾(crlf / lf / mixed); +// * 把引擎写完的文件按那种风格摆回去。 +// +// 只碰行尾,不碰内容:段落文字、全角字符、emoji、\fact{}/\cite{} 标记、 +// 段内换行——一个字符都不动。 + +/** 换行只有两种:\r\n 与 \n。落单的 \r 当作正文里的普通字符,不当行尾。 */ +export const CRLF = '\r\n'; +export const LF = '\n'; + +/** + * 把文本切成 [{content, ending}]:行尾单独摘出来,行内容原样保留。 + * + * 刻意不用 String.prototype.split('\n'):那样会把 '\r' 留在行内容里, + * 重建时 \r\n 就会变成 '\r' + 换行,行尾就拼错了。 + */ +export function splitKeepEnds(text) { + const source = String(text ?? ''); + const out = []; + let index = 0; + while (index <= source.length) { + const nl = source.indexOf('\n', index); + if (nl === -1) { + if (index < source.length) out.push({ content: source.slice(index), ending: '' }); + break; + } + // '\r\n' 是一个行尾;落单的 '\r' 留在行内容里(当正文看)。 + const hasCr = nl > index && source[nl - 1] === '\r'; + const contentEnd = hasCr ? nl - 1 : nl; + out.push({ + content: source.slice(index, contentEnd), + ending: source.slice(contentEnd, nl + 1), + }); + index = nl + 1; + } + return out; +} + +/** 数一数文本里的行尾种类。 */ +export function detectEol(text) { + let crlf = 0; + let lf = 0; + for (const line of splitKeepEnds(text)) { + if (line.ending === CRLF) crlf += 1; + else if (line.ending === LF) lf += 1; + } + let style = 'none'; + if (crlf && lf) style = 'mixed'; + else if (crlf) style = 'crlf'; + else if (lf) style = 'lf'; + return { style, crlf, lf }; +} + +/** + * 原文件的主导行尾:CRLF 多就用 CRLF,LF 多就用 LF。 + * + * 计数相同时取 CRLF——与引擎侧 factscribe/textio.py::dominant_newline 同一口径。 + * 原文件一行都没有行尾时用 fallback(LF)。 + */ +export function dominantEnding(text, fallback = LF) { + const { crlf, lf } = detectEol(text); + if (crlf === 0 && lf === 0) return fallback; + return crlf >= lf ? CRLF : LF; +} + +/** + * 把正文里所有行尾换成 ending;行内容一个字不动。 + * + * 「末行有没有行尾」这个结构也原样保留:原文本末尾没有换行,换完还是没有。 + */ +export function applyEnding(text, ending) { + if (!ending) return String(text ?? ''); + return splitKeepEnds(text) + .map((line) => line.content + (line.ending ? ending : '')) + .join(''); +} + +/** + * 传给引擎的形态:一律 LF,不带 '\r'。 + * + * '\r' 绝不进引擎那一层:引擎写盘是二进制写,带 '\r' 会原样写进文件, + * 在已经是 CRLF 的稿子上就会写出 '\r\r\n' 这种坏掉的行尾。 + * 行尾由本模块在引擎写完之后按原风格校正。 + */ +export function toLfOnly(text) { + return String(text ?? '').replace(/\r\n/g, '\n'); +} + +/** 只要行内容(不要行尾):用来判断「内容有没有被别人改过」。 */ +export function lineContents(text) { + return splitKeepEnds(text).map((line) => line.content); +} + +/** 行内容序列一致=只差行尾;不一致=有人改过正文,不能覆盖。 */ +export function sameContent(a, b) { + const left = lineContents(a); + const right = lineContents(b); + if (left.length !== right.length) return false; + for (let i = 0; i < left.length; i += 1) { + if (left[i] !== right[i]) return false; + } + return true; +} + +/** + * 把引擎写完的正文按**原文件**的行尾风格摆回去。 + * + * 做法是按行对齐: + * - 头尾那些「内容没变」的行,原样留着原文件里的行尾(连混合行尾也留着); + * - 中间被这次保存改过的那一段,用原文件的主导行尾。 + * + * 只动行尾,不动内容:返回值的行内容序列与 after 一字不差—— + * 末尾再 assert 一次,对不上就返回 null(一个字也不动)。 + * + * @param {string} before 保存前的文件内容(带磁盘上的真行尾) + * @param {string} after 引擎写完的文件内容 + * @returns {string|null} 摆回行尾后的内容;对不上返回 null + */ +export function restoreOriginalEndings(before, after) { + const beforeItems = splitKeepEnds(String(before ?? '')); + const afterItems = splitKeepEnds(String(after ?? '')); + const limit = Math.min(beforeItems.length, afterItems.length); + + // 最长的共同前缀:内容相同的行数(头)。 + let head = 0; + while (head < limit && beforeItems[head].content === afterItems[head].content) head += 1; + // 最长的共同后缀:内容相同的行数(尾)。不与前缀重叠。 + let tail = 0; + while (tail < limit - head + && beforeItems[beforeItems.length - 1 - tail].content === afterItems[afterItems.length - 1 - tail].content) { + tail += 1; + } + + const ending = dominantEnding(before); + const out = []; + for (let i = 0; i < head; i += 1) { + out.push(beforeItems[i].content + beforeItems[i].ending); + } + const midEnd = afterItems.length - tail; + for (let i = head; i < midEnd; i += 1) { + out.push(afterItems[i].content + (afterItems[i].ending ? ending : '')); + } + for (let i = beforeItems.length - tail; i < beforeItems.length; i += 1) { + out.push(beforeItems[i].content + beforeItems[i].ending); + } + const restored = out.join(''); + // 安全网:内容必须与引擎写出来的一字不差(只差行尾)。对不上就一个字也不动。 + if (toLfOnly(restored) !== toLfOnly(String(after ?? ''))) return null; + return restored; +} diff --git a/plugins/unclemoc/factscribe/miniapp/node/python_discovery.mjs b/plugins/unclemoc/factscribe/miniapp/node/python_discovery.mjs new file mode 100644 index 00000000..6eb0ee06 --- /dev/null +++ b/plugins/unclemoc/factscribe/miniapp/node/python_discovery.mjs @@ -0,0 +1,434 @@ +// @ts-check +// FactScribe MiniApp —— Python 解释器发现:候选生成、探针分类、错误文案。 +// +// 为什么要单列一个文件(而不是继续塞在 server.mjs 里): +// ① Windows 上「明明装了 Python,却说没找到」——老候选表里根本没有 Windows 形态: +// 没有 py 启动器、没有 python3.12 这类版本化命令、没有 %LOCALAPPDATA% 下的安装路径。 +// 用户装了 3.10+ 但不在 PATH(或只有 py 启动器),一律判成「没找到」。 +// ② 探测失败一刀切:命令不存在(spawn ENOENT)与版本过低(读到的版本 < 3.10) +// 走同一条路,于是装了 3.9 的用户收到「装好 Python ≥3.10 再来」这种没法定位的话。 +// ③ py 启动器要带前缀参数(py -3),所以候选不能再是裸字符串: +// 统一成形如 {command, args},**探测与拉起引擎两处从同一份候选派生**,不会只改一处。 +// +// 边界:引擎要求 Python ≥3.10(3.10 走引擎仓内兜底 TOML 解析器,3.11+ 用标准库 tomllib)。 +// 这里只负责「找到它、说清楚为什么不行」,不放宽版本要求,也不改引擎本体。 +// +// 纯度约定:pythonCandidates() 与 pythonFailureMessage() 不碰文件系统与进程, +// 便于单元测试在任意平台上钉死 macOS 与 Windows 两套行为。 + +import { spawn } from 'node:child_process'; +import { existsSync } from 'node:fs'; + +/** 引擎要求的最低 Python 版本。 */ +export const MIN_PYTHON = [3, 10]; + +/** Windows 上值得一试的 3.x 版本(新的排前面:先挑最新的解释器)。 */ +export const WINDOWS_PYTHON_VERSIONS = ['3.14', '3.13', '3.12', '3.11', '3.10']; + +/** 探针超时(毫秒):超了就算这个候选不可用。 */ +export const PROBE_TIMEOUT_MS = 15000; + +/** + * 探针脚本:吐版本号 + 解释器真实路径。 + * 带 FSVER/FSEXE 标记是为了 stdout 混进别的东西(launcher 的广告语、Store 别名的提示)时 + * 仍能稳地切出来;切不到就当「读不出版本」,不猜。 + * FSEXE(sys.executable)很关键:候选叫 "py" 时,只有它能说清「这个 3.9 到底装在哪」。 + */ +const VERSION_SCRIPT = 'import sys; sys.stdout.write("FSVER:%d.%d\\nFSEXE:%s" % (sys.version_info[0], sys.version_info[1], sys.executable))'; + +/** 探针输出缓冲上限(防止解释器喷太多把内存吃满)。 */ +const PROBE_OUTPUT_CAP = 4000; + +/** + * 候选类型: + * env —— 用户显式指定的 FS_PYTHON; + * name —— 交给系统去 PATH 里找的命令名; + * path —— 拼出来的绝对路径(探测前先看它在不在)。 + * @typedef {{command: string, args: string[], kind: 'env'|'name'|'path'}} PythonCandidate + */ + +/** + * 发现结果:命令、前缀参数、探到的版本、读不出版本的命令、FS_PYTHON 是否失效。 + * 错误文案全靠它区分「没装」「装了但版本低」「装了但不在 PATH」。 + * @typedef {{ + * ok: boolean, + * command: string, + * args: string[], + * version: string|null, + * executable: string|null, + * candidate: PythonCandidate|null, + * found: Array<{command: string, args: string[], version: string, executable: string|null, kind: string}>, + * broken: Array<{command: string, args: string[], detail: string, stderr: string, kind: string}>, + * missingEnv: string|null, + * probedPaths: string[], + * }} PythonDiscovery + */ + +/** + * 从 env 里取一个键(Windows 上环境变量名大小写不敏感,这里做大小写无关查找)。 + * @param {Record} env + * @param {string} key + * @returns {string} + */ +function pickEnv(env, key) { + if (!env) return ''; + const direct = env[key]; + if (typeof direct === 'string' && direct) return direct; + const lower = key.toLowerCase(); + for (const name of Object.keys(env)) { + if (name.toLowerCase() === lower) { + const value = env[name]; + if (typeof value === 'string' && value) return value; + } + } + return ''; +} + +/** 去掉路径尾部的斜杠(拼绝对路径时避免出现双反斜杠)。 */ +function trimSeparators(value) { + return String(value || '').replace(/[\\/]+$/, ''); +} + +/** + * Windows 常见安装目录里的 python.exe 绝对路径。 + * 覆盖三种装法:每用户装(%LOCALAPPDATA%\Programs\Python\Python312)、 + * 全局装(%PROGRAMFILES%\Python312)、以及装在盘根的(C:\Python312)。 + * @param {Record} env + * @returns {string[]} + */ +export function windowsInstallPaths(env = {}) { + const local = trimSeparators(pickEnv(env, 'LOCALAPPDATA')); + const programFiles = trimSeparators(pickEnv(env, 'PROGRAMFILES')); + const systemDrive = trimSeparators(pickEnv(env, 'SystemDrive')) || 'C:'; + const out = []; + for (const version of WINDOWS_PYTHON_VERSIONS) { + const tag = version.replace('.', ''); // 3.12 → 312 + if (local) out.push(local + '\\Programs\\Python\\Python' + tag + '\\python.exe'); + if (programFiles) out.push(programFiles + '\\Python' + tag + '\\python.exe'); + out.push(systemDrive + '\\Python' + tag + '\\python.exe'); + } + return out; +} + +/** + * 候选表(纯函数:不碰文件系统、不起进程)。 + * + * macOS/Linux 的顺序与老实现完全一致(python3 → python → /usr/bin/python3 → + * /opt/homebrew/bin/python3 → /usr/local/bin/python3),不因为这次改动而变。 + * Windows 补上:FS_PYTHON → py(-3 与各版本号)→ py.exe → python3/python/python.exe → + * 版本化命令 python3.14…python3.10 → 常见安装目录里的绝对路径。 + * + * @param {string} platform process.platform + * @param {Record} env + * @returns {PythonCandidate[]} + */ +export function pythonCandidates(platform, env = {}) { + /** @type {PythonCandidate[]} */ + const list = []; + const add = (command, args, kind) => { + if (typeof command !== 'string') return; + const cmd = command.trim(); + if (!cmd) return; + list.push({ command: cmd, args: Array.isArray(args) ? args.slice() : [], kind: kind || 'name' }); + }; + // FS_PYTHON 用 pickEnv 取:Windows 上环境变量名大小写不敏感。 + const fsPython = pickEnv(env, 'FS_PYTHON'); + if (fsPython.trim()) add(fsPython, [], 'env'); + if (platform === 'win32') { + add('py'); + add('py', ['-3']); + for (const version of WINDOWS_PYTHON_VERSIONS) add('py', ['-' + version]); + add('py.exe'); + add('python3'); + add('python'); + add('python.exe'); + for (const version of WINDOWS_PYTHON_VERSIONS) add('python' + version); + for (const version of WINDOWS_PYTHON_VERSIONS) add('python' + version + '.exe'); + for (const full of windowsInstallPaths(env)) add(full, [], 'path'); + } else { + add('python3'); + add('python'); + add('/usr/bin/python3'); + add('/opt/homebrew/bin/python3'); + add('/usr/local/bin/python3'); + } + return list; +} + +/** + * 从探针输出里切版本号(认 FSVER 标记;切不到就返回 null,不猜)。 + * @param {string} text + * @returns {{major: number, minor: number, text: string}|null} + */ +export function parsePythonVersion(text) { + const matched = /FSVER:(\d+)\.(\d+)/.exec(String(text || '')); + if (!matched) return null; + const major = Number(matched[1]); + const minor = Number(matched[2]); + if (!Number.isFinite(major) || !Number.isFinite(minor)) return null; + return { major, minor, text: major + '.' + minor }; +} + +/** + * 从探针输出里切解释器真实路径(sys.executable);切不到返回 null。 + * @param {string} text + * @returns {string|null} + */ +export function parsePythonExecutable(text) { + const matched = /FSEXE:([^\r\n]*)/.exec(String(text || '')); + if (!matched) return null; + const value = matched[1].trim(); + return value ? value : null; +} + +/** + * 版本比较:a 比 b 新返回正数。 + * @param {{major: number, minor: number}} a + * @param {number[]} b + * @returns {number} + */ +export function compareVersion(a, b) { + const major = Number(a.major) - Number(b[0]); + if (major !== 0) return major; + return Number(a.minor) - Number(b[1]); +} + +/** + * 探一个候选:把「命令不存在」「命令在但读不出版本」「版本够」「版本低」四件事分开。 + * + * @param {PythonCandidate} candidate + * @param {{timeoutMs?: number, spawnFn?: Function, minVersion?: number[]}} [options] + * @returns {Promise<{status: 'ready'|'old'|'missing'|'broken', version?: string, executable?: string|null, detail?: string, stderr?: string}>} + */ +export function probePythonCandidate(candidate, options = {}) { + const timeoutMs = typeof options.timeoutMs === 'number' ? options.timeoutMs : PROBE_TIMEOUT_MS; + const spawnFn = options.spawnFn || spawn; + const minVersion = options.minVersion || MIN_PYTHON; + const args = (candidate.args || []).concat(['-c', VERSION_SCRIPT]); + return new Promise((resolve) => { + let out = ''; + let err = ''; + let settled = false; + /** @param {{status: string, version?: string, detail?: string}} result */ + const done = (result) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve({ ...result, stderr: err.slice(-PROBE_OUTPUT_CAP) }); + }; + /** @type {import('node:child_process').ChildProcess} */ + let child_; + try { + // stdout/stdin 绝不继承(归宿主);探测输出走管道,绝不进宿主 stdout/stderr。 + child_ = spawnFn(candidate.command, args, { stdio: ['ignore', 'pipe', 'pipe'] }); + } catch (error) { + done({ status: 'broken', detail: String((error && error.code) || error) }); + return; + } + const timer = setTimeout(() => { + try { child_.kill('SIGKILL'); } catch { /* 已退出 */ } + done({ status: 'broken', detail: 'probe_timeout' }); + }, timeoutMs); + if (child_.stdout) { + child_.stdout.setEncoding('utf8'); + child_.stdout.on('data', (chunk) => { + if (out.length < PROBE_OUTPUT_CAP) out += String(chunk); + }); + } + if (child_.stderr) { + child_.stderr.setEncoding('utf8'); + child_.stderr.on('data', (chunk) => { + if (err.length < PROBE_OUTPUT_CAP) err += String(chunk); + }); + } + child_.on('error', (error) => { + const code = String((error && error.code) || ''); + // ENOENT=这台机器上根本没有这个命令;其余错误=命令在,但跑不起来。 + done({ status: code === 'ENOENT' ? 'missing' : 'broken', detail: code || String((error && error.message) || error) }); + }); + child_.on('exit', (code) => { + const version = parsePythonVersion(out); + if (!version) { + done({ status: 'broken', detail: code === 0 ? 'no_version' : 'exit_' + code }); + return; + } + done({ + status: compareVersion(version, minVersion) >= 0 ? 'ready' : 'old', + version: version.text, + executable: parsePythonExecutable(out), + }); + }); + }); +} + +/** + * 逐个候选探过去,返回发现结果(纯逻辑:探针与存在性检查都可注入,便于单测)。 + * + * @param {{platform?: string, env?: Record, probe?: Function, exists?: Function, probeOptions?: object}} [options] + * @returns {Promise<{ + * ok: boolean, command: string, args: string[], version: string|null, + * found: Array<{command: string, args: string[], version: string, kind: string}>, + * broken: Array<{command: string, args: string[], detail: string, stderr: string, kind: string}>, + * missingEnv: string|null, probedPaths: string[], + * }>} + */ +export async function discoverPython(options = {}) { + const platform = options.platform || process.platform; + const env = options.env || process.env; + const probe = options.probe || probePythonCandidate; + const exists = options.exists || existsSync; + const probeOptions = options.probeOptions || {}; + const candidates = pythonCandidates(platform, env); + const state = { + ok: false, + command: '', + args: [], + version: null, + executable: null, + candidate: null, + found: [], + broken: [], + missingEnv: null, + probedPaths: [], + }; + for (const candidate of candidates) { + // 绝对路径候选:文件不在就跳过(省一次 spawn,也免得把 ENOENT 混进「装过」的证据里)。 + if (candidate.kind === 'path' && !exists(candidate.command)) { + state.probedPaths.push(candidate.command); + continue; + } + const result = await probe(candidate, probeOptions); + if (result.status === 'ready') { + state.ok = true; + state.command = candidate.command; + state.args = candidate.args.slice(); + state.version = result.version || null; + state.executable = result.executable || null; + state.candidate = candidate; + return state; + } + if (result.status === 'old') { + state.found.push({ command: candidate.command, args: candidate.args.slice(), version: result.version || '', executable: result.executable || null, kind: candidate.kind }); + continue; + } + if (result.status === 'broken') { + state.broken.push({ command: candidate.command, args: candidate.args.slice(), detail: result.detail || '', stderr: result.stderr || '', kind: candidate.kind }); + // FS_PYTHON 指错了也可能是「跑不起来」而不只是「文件不存在」——两种都要点名。 + if (candidate.kind === 'env') state.missingEnv = candidate.command; + continue; + } + // missing + if (candidate.kind === 'env') state.missingEnv = candidate.command; + else if (candidate.kind === 'path') state.probedPaths.push(candidate.command); + } + return state; +} + +/** + * 候选的可读写法(给人看的:「py -3」/「C:\Python39\python.exe」)。 + * @param {{command: string, args?: string[]}} candidate + * @returns {string} + */ +export function describeCandidate(candidate) { + const command = String((candidate && candidate.command) || ''); + const args = candidate && candidate.args && candidate.args.length ? ' ' + candidate.args.join(' ') : ''; + return command + args; +} + +/** + * 「这个版本来自哪个可执行文件」:候选名 + 解释器真实路径(sys.executable)。 + * 候选叫 py / python(从 PATH 里捡到的)时,只有真实路径能告诉用户东西装在哪。 + * @param {{command: string, args?: string[], executable?: string|null}} entry + * @returns {string} + */ +function describeSource(entry) { + const base = describeCandidate(entry); + const executable = entry && entry.executable ? String(entry.executable) : ''; + return executable ? base + ',实际解释器在 ' + executable : base; +} + +/** + * 安装说明:当前平台的排前面,另一个平台的也留着——换台机器照样用得上。 + * @param {string} platform + * @param {string} min 最低版本,形如 '3.10' + * @returns {string[]} + */ +function installHints(platform, min) { + const windows = '· 装一个 ≥' + min + ' 的解释器(Windows):到 https://www.python.org/downloads/windows/ 下载双击安装包,安装时勾上「Add python.exe to PATH」(新旧版本可以并存);装完在命令行跑 py -3 --version 确认——只装了 py 启动器也行,本机会自动找到它。'; + const unix = '· 装一个 ≥' + min + ' 的解释器(macOS / Debian / Ubuntu):macOS 用 brew install python@3.12;Debian/Ubuntu 用 sudo apt install python3.12 python3.12-venv'; + return platform === 'win32' ? [windows, unix] : [unix, windows]; +} + +/** + * 错误文案:把「没装」「装了但版本低」「装了但不在 PATH / 命令是假的」三种情况分开说。 + * 纯函数:同一份发现状态,引擎启动失败与设置页诊断共用它,两处口径不会漂。 + * + * @param {object} state discoverPython() 的返回值 + * @param {{platform?: string, minVersion?: number[]}} [options] + * @returns {string} + */ +export function pythonFailureMessage(state, options = {}) { + const minVersion = options.minVersion || MIN_PYTHON; + const platform = options.platform || process.platform; + const min = minVersion.join('.'); + const found = (state && state.found ? state.found : []).slice(); + const broken = (state && state.broken ? state.broken : []).slice(); + const probedPaths = (state && state.probedPaths ? state.probedPaths : []).slice(); + const lines = []; + + if (state && state.missingEnv) { + lines.push('环境变量 FS_PYTHON 指向的「' + state.missingEnv + '」跑不起来(文件不存在,或它不是 Python 解释器),请先检查这个路径。'); + } + + // 探到的最高版本(走这条分支说明它们全都低于下限)。 + found.sort((a, b) => { + const av = parsePythonVersion('FSVER:' + a.version) || { major: 0, minor: 0 }; + const bv = parsePythonVersion('FSVER:' + b.version) || { major: 0, minor: 0 }; + return bv.major - av.major || bv.minor - av.minor; + }); + const top = found[0]; + + if (top) { + lines.push('找到了 Python,但版本不够:最高只探到 ' + top.version + '(来自 ' + describeSource(top) + ')。'); + lines.push('FactScribe 的引擎需要 Python ≥' + min + '(3.10 走引擎随包的兜底 TOML 解析器,3.11+ 用标准库 tomllib)——Python ' + top.version + ' 及以下跑不了这份引擎。'); + for (const hint of installHints(platform, min)) lines.push(hint); + lines.push('· 或者指定现成的解释器:设环境变量 FS_PYTHON 指向一个 ≥' + min + ' 的解释器绝对路径,例如 FS_PYTHON=C:\\Users\\你\\AppData\\Local\\Programs\\Python\\Python312\\python.exe'); + } else if (broken.length) { + const first = broken.find((b) => b.kind !== 'env') || broken[0]; + lines.push('找到了「' + describeCandidate(first) + '」这个命令,但它不是一个可用的 Python 解释器(读不出版本号)。'); + lines.push('· Windows 上这命令常见的两种来路:Microsoft Store 的「python」占位别名会抢在前面(它把你引去商店,像是装了却不能用);或者只有 `py` 启动器、实际没装 Python。真装了 Python 的话,到「设置 → 应用 → 应用执行别名」把 python / python3 关掉。'); + lines.push('· 或者指定现成的解释器:设环境变量 FS_PYTHON 指向一个 ≥' + min + ' 的解释器绝对路径,例如 FS_PYTHON=C:\\Users\\你\\AppData\\Local\\Programs\\Python\\Python312\\python.exe'); + for (const hint of installHints(platform, min)) lines.push(hint); + const tail = String(first.stderr || '').trim().split('\n').filter(Boolean).slice(-3).join(' / '); + if (tail) lines.push('(它的原话:' + tail.slice(0, 300) + ')'); + } else { + lines.push('没找到可用的 Python 3:FactScribe 的引擎是 Python 写的,需要 Python ≥' + min + '。'); + for (const hint of installHints(platform, min)) lines.push(hint); + lines.push('· 已经装了 Python、只是它没进 PATH(或装在别处):设环境变量 FS_PYTHON 指向解释器的绝对路径,例如 FS_PYTHON=C:\\Users\\你\\AppData\\Local\\Programs\\Python\\Python312\\python.exe'); + if (probedPaths.length) { + const shown = probedPaths.slice(0, 4).join('、'); + const more = probedPaths.length > 4 ? '(共 ' + probedPaths.length + ' 处)' : ''; + lines.push('· 我们探过这些常见安装位置,都没有可用的解释器:' + shown + more); + } + } + return lines.join('\n'); +} + +/** + * 非致命的提醒:Python 找到了,但不是在 PATH 里找到的(靠绝对路径或 FS_PYTHON)。 + * 这时候引擎能用,但换台机器/换个 PATH 就可能找不到——值得说一声。 + * @param {object} state discoverPython() 的返回值 + * @returns {string} + */ +export function pythonAdvice(state) { + if (!state || !state.ok) return ''; + const candidate = state.candidate; + if (!candidate || candidate.kind === 'name') return ''; + const version = state.version ? ' ' + state.version : ''; + const where = describeCandidate(candidate); + if (candidate.kind === 'env') { + // 用户自己指的:告诉他现在用的是哪一个,别让他以为是自己装的默认 python。 + return 'Python' + version + ' 来自环境变量 FS_PYTHON 指定的解释器(' + where + ')。换台机器或换个人用时,记得把这个变量也带上。'; + } + return 'Python' + version + ' 是在 PATH 之外找到的(用的是 ' + where + ')。想让它每次都被稳定找到,设环境变量 FS_PYTHON 指向它。'; +} diff --git a/plugins/unclemoc/factscribe/miniapp/node/server.mjs b/plugins/unclemoc/factscribe/miniapp/node/server.mjs index 93ccca65..0e117bb1 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/server.mjs +++ b/plugins/unclemoc/factscribe/miniapp/node/server.mjs @@ -23,8 +23,15 @@ import { spawn } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { createReadStream, promises as fs } from 'node:fs'; import { createServer, request as httpRequest } from 'node:http'; -import { delimiter, join, resolve as resolvePath, sep } from 'node:path'; +import { delimiter, extname, join, resolve as resolvePath, sep } from 'node:path'; import { homedir } from 'node:os'; +// 解释器发现(候选表/探针/文案都在这个模块里,纯函数可单测): +// 候选带参数前缀(py -3 这类),探测与拉起引擎共用同一份候选。 +import { discoverPython, pythonFailureMessage, pythonAdvice } from './python_discovery.mjs'; +// 行尾保真(切分/识别/按原风格摆回,纯函数可单测): +// 引擎读文件用 Python 文本模式(通用换行翻译:CRLF→LF)、写文件用二进制写, +// 一次保存就会把 CRLF 的稿子整篇改成 LF;行尾的真相只在磁盘上的原文件里。 +import { detectEol, restoreOriginalEndings, toLfOnly } from './eol.mjs'; // ---------------------------------------------------------------- 常量 @@ -79,7 +86,6 @@ const STATIC_TYPES = { const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']); const MAX_BODY_BYTES = 1024 * 1024; const ENGINE_START_TIMEOUT_MS = 20000; -const PYTHON_PROBE_TIMEOUT_MS = 15000; // ---------------------------------------------------------------- 小件 @@ -554,50 +560,26 @@ function createEngine(env) { let failedAt = 0; let lastFailure = ''; let intentionalStop = false; - /** @type {Promise | null} */ + /** @type {Promise | null} */ let pythonProbe = null; - /** Python 命令发现:FS_PYTHON → python3 → python(全探版本 ≥3.10),缓存结果。 */ + /** + * Python 解释器发现:候选表、探针、失败分类都在 python_discovery.mjs 里。 + * + * 返回的是**发现状态**(不只是一个命令名):ok / 实际命令 / 前缀参数 / + * 探到的最高版本 / 读不出版本的命令 / FS_PYTHON 是否失效—— + * 错误文案要靠这些信息区分「没装」「装了但版本低」「装了但不在 PATH」。 + * 结果缓存;用户装完 Python 后由 restart() 清缓存重探。 + * + * @returns {Promise} + */ function findPython() { if (!pythonProbe) { - pythonProbe = (async () => { - const candidates = [ - process.env.FS_PYTHON, - 'python3', - 'python', // Windows 装机常常只有这个名字 - '/usr/bin/python3', - '/opt/homebrew/bin/python3', - '/usr/local/bin/python3', - ].filter((c) => typeof c === 'string' && c.length > 0); - for (const candidate of /** @type {string[]} */ (candidates)) { - try { - await runProbe(candidate); - return candidate; - } catch { - /* 试下一个 */ - } - } - return ''; - })(); + pythonProbe = discoverPython({ platform: process.platform, env: process.env }); } return pythonProbe; } - /** @param {string} command */ - function runProbe(command) { - return new Promise((resolve, reject) => { - // stdout/stdin 绝不继承(归宿主);探测输出两边都不要。 - const child_ = spawn(command, ['-c', 'import sys; raise SystemExit(0 if sys.version_info[:2] >= (3, 10) else 1)'], - { stdio: ['ignore', 'ignore', 'ignore'] }); - const timer = setTimeout(() => { - try { child_.kill('SIGKILL'); } catch { /* 已退出 */ } - reject(new Error('probe_timeout')); - }, PYTHON_PROBE_TIMEOUT_MS); - child_.on('error', (error) => { clearTimeout(timer); reject(error); }); - child_.on('exit', (code) => { clearTimeout(timer); (code === 0 ? resolve : reject)(undefined); }); - }); - } - /** * 读引擎 stdout 的首行 listening JSON 握手(cli.py --json),拿到真实端口。 * 超时或子进程先退 → 失败;其余 stdout 内容一律排掉(不归我们)。 @@ -650,13 +632,17 @@ function createEngine(env) { async function start(root) { intentionalStop = false; lastFailure = ''; - const python = await findPython(); - if (!python) { + const discovery = await findPython(); + if (!discovery.ok) { failedAt = Date.now(); - lastFailure = '本机没有找到可用的 Python 3(需要 ≥3.10)。装一个 python3,或设环境变量 FS_PYTHON 指到你的 Python。'; + // 文案区分三种情况(没装 / 装了但版本低 / 命令是假的),并报出实测版本与路径。 + lastFailure = pythonFailureMessage(discovery, { platform: process.platform }); throw new HttpError(503, 'python_missing', lastFailure); } - const c = spawn(python, ['-B', '-m', 'factscribe', 'workbench', '--root', root, '--port', '0', '--json', '--no-browser', '--state-dir', context.dataDir], { + // 与探测**同一套**「命令+前缀参数」:py -3 这类启动器参数不能只在探测时带。 + const python = discovery.command; + const pythonArgs = discovery.args; + const c = spawn(python, [...pythonArgs, '-B', '-m', 'factscribe', 'workbench', '--root', root, '--port', '0', '--json', '--no-browser', '--state-dir', context.dataDir], { stdio: ['ignore', 'pipe', 'pipe'], // stdout 管道取握手行;绝不继承宿主 stdout env: { ...process.env, @@ -759,7 +745,15 @@ function createEngine(env) { restart, stop, /** 设置页诊断用:本机探到可用 Python(≥3.10)了吗(带缓存,探过即记)。 */ - pythonAvailable: async () => Boolean(await findPython()), + pythonAvailable: async () => Boolean((await findPython()).ok), + /** + * 设置页诊断用:完整的发现状态(文案要靠它区分「没装」「版本低」「不在 PATH」)。 + * refresh=true 时丢掉缓存重探一次——用户刚装好 Python 的场景。 + */ + pythonDiscovery: async (options = {}) => { + if (options && options.refresh) pythonProbe = null; + return findPython(); + }, /** @returns {number} 引擎端口(0=没在跑) */ get port() { return port; }, /** @returns {string} 当前引擎的论文根 */ @@ -768,6 +762,119 @@ function createEngine(env) { }; } +// ---------------------------------------------------------------- 行尾保真(保存时把原行尾摆回去) +// +// 引擎读文件用 Python 文本模式(通用换行翻译:CRLF→LF),写文件用二进制模式: +// 一次保存就会把整篇的行尾改成 LF——CRLF 的稿子存一次就没了(macOS / Linux +// 上同样发生,与 Windows 无关)。所以 Node 这一层在保存前把原文件的真行尾 +// 读下来,引擎写完再按它摆回去:只换行尾,不换内容。 + +/** 正文文本文件:只有这些进行尾快照(其余是数据、产物或二进制)。 */ +const TEXT_FILE_EXTENSIONS = new Set([ + '.tex', '.bib', '.md', '.txt', '.toml', '.sty', '.cls', '.cfg', '.yaml', '.yml', +]); + +/** 单文件上限:超过就不进快照(读一遍太贵,也不该被行尾逻辑碰)。 */ +const SNAPSHOT_MAX_BYTES = 2 * 1024 * 1024; + +/** 快照最多收多少个文件:防病态目录。 */ +const SNAPSHOT_MAX_FILES = 500; + +/** decodeURIComponent 可能抛(坏百分号):解不开就原样返回。 */ +function safeDecode(value) { + const raw = String(value ?? ''); + try { + return decodeURIComponent(raw); + } catch { + return raw; + } +} + +/** + * 盘目录下的正文文本文件快照:绝对路径 → 原始内容。 + * + * Node 的 readFile(path, 'utf8') 不做换行翻译,所以这里拿得到磁盘上的真行尾。 + * + * @param {string} dir 盘的绝对目录 + * @returns {Promise>} + */ +async function snapshotTextFiles(dir) { + /** @type {Map} */ + const snap = new Map(); + const stack = [String(dir)]; + while (stack.length && snap.size < SNAPSHOT_MAX_FILES) { + const current = /** @type {string} */ (stack.pop()); + let entries; + try { + entries = await fs.readdir(current, { withFileTypes: true }); + } catch { + continue; + } + for (const entry of entries) { + if (snap.size >= SNAPSHOT_MAX_FILES) break; + if (entry.name.startsWith('.')) continue; + const absolute = join(current, entry.name); + if (entry.isDirectory()) { + stack.push(absolute); + continue; + } + if (!entry.isFile()) continue; + if (!TEXT_FILE_EXTENSIONS.has(extname(entry.name).toLowerCase())) continue; + try { + const info = await fs.stat(absolute); + if (!info.isFile() || info.size > SNAPSHOT_MAX_BYTES) continue; + snap.set(absolute, await fs.readFile(absolute, 'utf8')); + } catch { + /* 读不到就当没这个文件 */ + } + } + } + return snap; +} + +/** + * 引擎写完之后,把被这次保存改过的文件按**原文件的行尾**摆回去。 + * + * 引擎那一层拿到的是 LF 形态(不带 '\r'),它写出来的文件是 LF 的;这里按 + * 快照里的原行尾把它摆回去:内容一个字不动,没被这次保存碰到的行连原来的 + * 混合行尾都原样留着。摆不回去(内容对不上)就一个字也不动。 + * + * @param {Map} snapshot 保存前的快照 + */ +async function restoreSnapshotEndings(snapshot) { + /** @type {{file: string, style: string, repaired: boolean, note?: string}[]} */ + const report = []; + for (const [file, before] of snapshot) { + let after; + try { + after = await fs.readFile(file, 'utf8'); + } catch { + continue; + } + if (after === before) continue; // 这次保存没碰这个文件 + const restored = restoreOriginalEndings(before, after); + const style = detectEol(before).style; + if (!restored || restored === after) { + report.push({ file, style, repaired: false }); + continue; + } + // 原子写:同目录临时文件 → rename;保留原权限。 + const tmp = file + '.eol-tmp-' + process.pid; + try { + const info = await fs.stat(file); + await fs.writeFile(tmp, restored, 'utf8'); + await fs.chmod(tmp, info.mode & 0o7777); + await fs.rename(tmp, file); + } catch (err) { + await fs.rm(tmp, { force: true }).catch(() => {}); + report.push({ file, style, repaired: false, note: String(err?.message || err) }); + continue; + } + report.push({ file, style, repaired: true }); + } + return report; +} + // ---------------------------------------------------------------- 引擎 HTTP 客户端(MCP 工具用) /** @@ -1901,27 +2008,120 @@ export async function start(context) { ); const handleMcp = createMcpHandler(toolService, (message) => log.info(message)); - /** @type {Map} */ - const pageCache = new Map(); + /** + * 首启设置页:论文根目录 + Python 诊断。 + * + * 诊断每次现算,不吃页面缓存——用户刚装完 Python、刷新一下就该看到新结论, + * 而不是继续看上一轮那句「没找到 python3」。 + */ async function setupPage() { - const key = 'setup'; - if (pageCache.has(key)) return /** @type {string} */ (pageCache.get(key)); const configured = await readConfig(context.dataDir); /** @type {string[]} */ const warnings = []; if (configured) { warnings.push(`已保存的路径(${configured})在这台机器上不存在或不是文件夹,请改一个真实的目录。`); } - let pythonOk = false; + let discovery = null; try { - pythonOk = await engine.pythonAvailable(); + discovery = await engine.pythonDiscovery(); } catch { - pythonOk = false; + discovery = null; } - if (!pythonOk) warnings.push('没找到 python3:FactScribe 的引擎是 Python 写的,装好 Python ≥3.10 再来。'); - const html = setupPageHtml(configured, warnings); - pageCache.set(key, html); - return html; + if (discovery && !discovery.ok) { + // 失败态再探一次:上一轮探的时候还没装,用户可能刚装好。 + try { + discovery = await engine.pythonDiscovery({ refresh: true }); + } catch { + /* 探不动就沿用上一轮的结论 */ + } + } + if (!discovery || !discovery.ok) { + // 与引擎启动失败同源同口径:设置页不再说「没找到 python3」这种没法定位的话。 + warnings.push(discovery + ? pythonFailureMessage(discovery, { platform: process.platform }) + : '没找到可用的 Python 3:FactScribe 的引擎是 Python 写的,需要 Python ≥3.10。装好 Python ≥3.10(或设环境变量 FS_PYTHON 指向解释器绝对路径)再来。'); + } else { + const advice = pythonAdvice(discovery); + if (advice) warnings.push(advice); + } + return setupPageHtml(configured, warnings); + } + + /** 盘目录缓存:引擎的 /api/projects 给出每个盘的绝对路径(它自己扫出来的)。 */ + /** @type {Map} */ + const diskDirs = new Map(); + let diskDirsAt = 0; + + /** + * 盘目录(绝对路径):/ → 目录。 + * + * 引擎的 /api/projects 里带着每个盘的 path(引擎自己发现的,不靠猜)。 + * 问不到就按「没有盘目录」处理——那只是不保行尾,不影响保存本身。 + * + * @param {string} project + * @param {string} disk + * @returns {Promise} + */ + async function diskDirOf(project, disk) { + const now = Date.now(); + if (!diskDirs.size || now - diskDirsAt > 2000) { + diskDirsAt = now; + diskDirs.clear(); + try { + const data = await engineGet(engine.port, '/api/projects'); + for (const one of data?.projects || []) { + for (const item of one?.disks || []) { + if (one?.id && item?.id && typeof item.path === 'string') { + diskDirs.set(one.id + '\u0000' + item.id, item.path); + } + } + } + } catch { + /* 问不到就按「没有盘目录」处理 */ + } + } + for (const p of [project, safeDecode(project)]) { + for (const d of [disk, safeDecode(disk)]) { + const hit = diskDirs.get(p + '\u0000' + d); + if (hit) return hit; + } + } + return ''; + } + + /** + * 写盘的两条路(页面直写一段、采纳一张提议单):行尾保真在这一层做。 + * + * 引擎那一层拿到的是 LF 形态(不带 '\r'),它写出来的文件也是 LF 的—— + * CRLF 的稿子存一次就没了。这里在写之前把原文件的真行尾读下来,引擎写完 + * 再按原风格摆回去:内容一个字不动。 + * + * @param {import('node:http').IncomingMessage} request + * @param {import('node:http').ServerResponse} response + * @param {string} project + * @param {string} disk + */ + async function handleManuscriptWrite(request, response, project, disk) { + await engine.ensureReady(); + const body = await readJsonBody(request); + const dir = await diskDirOf(project, disk); + const snapshot = dir ? await snapshotTextFiles(dir) : new Map(); + // 传给引擎的一律 LF:引擎写盘是二进制写,带 '\r' 会原样写进文件。 + const payload = typeof body?.text === 'string' ? { ...body, text: toLfOnly(body.text) } : body; + const upstream = await enginePostRaw(engine.port, request.url || '', payload); + const status = upstream.status || 502; + const data = upstream.data; + if (status === 200 && data && data.ok !== false && snapshot.size) { + const report = await restoreSnapshotEndings(snapshot); + if (report.length) { + data.eol = { + files: report.length, + repaired: report.filter((item) => item.repaired).length, + style: report[0]?.style || 'none', + }; + } + } + return sendJson(response, status, data ?? { ok: false, error: '引擎没应答', code: 502 }); } /** @@ -2608,6 +2808,19 @@ export async function start(context) { return sendJson(response, 200, { ok: true, models: kept.map(publicCustomModel) }); } + // 写盘的两条路:行尾保真在这一层做(引擎读用文本模式、写用二进制写, + // 一次保存就会把 CRLF 的稿子整篇改成 LF)。 + const writeMatch = /^\/api\/disk\/([^/]+)\/([^/]+)\/(?:edit|proposal\/[^/]+\/confirm)$/.exec(path); + if (writeMatch && method === 'POST') { + try { + return await handleManuscriptWrite(request, response, writeMatch[1], writeMatch[2]); + } catch (error) { + const e = /** @type {HttpError} */ (error); + const status = typeof e?.status === 'number' ? e.status : 502; + return sendJson(response, status, { ok: false, error: e?.userMessage || '引擎暂不可用', code: status }); + } + } + // 业务请求:全部透传 Python 引擎(设置接口除外,上面已收)。 if (path === '/api' || path.startsWith('/api/')) { try { diff --git a/plugins/unclemoc/factscribe/tests/eol.test.mjs b/plugins/unclemoc/factscribe/tests/eol.test.mjs new file mode 100644 index 00000000..f9519d35 --- /dev/null +++ b/plugins/unclemoc/factscribe/tests/eol.test.mjs @@ -0,0 +1,134 @@ +// 行尾保真模块的单元测试(纯函数,不碰磁盘、不需要 Python)。 +// +// 跑法(包目录下): +// node --test tests/*.test.mjs +// +// 为什么行尾要单独管: +// 引擎读文件用 Python 文本模式(通用换行翻译:CRLF→LF),写文件用二进制写, +// 一次保存就会把 CRLF 的稿子整篇改成 LF。行尾的真相只在磁盘上的原文件里, +// 所以 Node 代理在保存时把原行尾读下来、写完再按它摆回去。 + +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { + applyEnding, detectEol, dominantEnding, lineContents, restoreOriginalEndings, + sameContent, splitKeepEnds, toLfOnly, +} from '../miniapp/node/eol.mjs'; + +// ---------------------------------------------------------------- 切分与识别 + +test('切分:行尾单独摘出来,行内容一字不动', () => { + const parts = splitKeepEnds('甲\r\n乙\n丙'); + assert.deepEqual(parts.map((p) => p.content), ['甲', '乙', '丙']); + assert.deepEqual(parts.map((p) => p.ending), ['\r\n', '\n', '']); +}); + +test('切分:落单的 \r 是正文里的字符,不当行尾', () => { + const parts = splitKeepEnds('甲\r乙\n丙'); + assert.deepEqual(parts.map((p) => p.content), ['甲\r乙', '丙']); + assert.deepEqual(parts.map((p) => p.ending), ['\n', '']); +}); + +test('切分:空文本与末尾无换行的文本', () => { + assert.deepEqual(splitKeepEnds(''), []); + assert.deepEqual(splitKeepEnds('单行'), [{ content: '单行', ending: '' }]); + assert.deepEqual(splitKeepEnds('a\n'), [ + { content: 'a', ending: '\n' }, + ]); +}); + +test('识别:认出 CRLF / LF / 混合三种文件', () => { + assert.equal(detectEol('a\r\nb\r\nc').style, 'crlf'); + assert.equal(detectEol('a\nb\nc').style, 'lf'); + assert.equal(detectEol('a\r\nb\nc').style, 'mixed'); + assert.equal(detectEol('单行没有换行').style, 'none'); + assert.equal(detectEol('').style, 'none'); +}); + +test('主导行尾:取多数,计数相同取 CRLF', () => { + assert.equal(dominantEnding('a\r\nb\r\nc\n'), '\r\n'); + assert.equal(dominantEnding('a\nb\nc\r\n'), '\n'); + assert.equal(dominantEnding('a\r\nb\n'), '\r\n'); + assert.equal(dominantEnding('没有换行'), '\n'); + assert.equal(dominantEnding('没有换行', '\r\n'), '\r\n'); +}); + +test('换行尾不动内容,末行有没有换行也照旧', () => { + const source = '第一段\n第二段\n第三段'; + const out = applyEnding(source, '\r\n'); + assert.equal(out, '第一段\r\n第二段\r\n第三段'); + assert.equal(out.endsWith('\r\n'), false, '原来末尾没换行,换完还是没有'); + assert.equal(applyEnding('a\n', '\r\n'), 'a\r\n', '原来末尾有换行,换完还是有'); +}); + +test('传给引擎的形态一律 LF,不带 \r', () => { + assert.equal(toLfOnly('a\r\nb\r\nc'), 'a\nb\nc'); + assert.equal(toLfOnly('a\r\nb\nc'), 'a\nb\nc'); +}); + +test('内容一致只看行内容,行尾不同不算内容不同', () => { + assert.equal(sameContent('a\r\nb', 'a\nb'), true); + assert.equal(sameContent('a\r\nb', 'a\nb\nc'), false); + assert.equal(sameContent('a\r\nb', 'a\nxb'), false); + assert.deepEqual(lineContents('a\r\nb\nc'), ['a', 'b', 'c']); +}); + +// ------------------------------------------------- 按原文件风格摆回行尾 + +test('摆回:CRLF 稿子存一次,CRLF 一个不少地回来', () => { + const before = '第一行\r\n第二行\r\n第三行\r\n'; + // 引擎写出来的样子:整篇被换成 LF,第二行被改过。 + const after = '第一行\n第二行改过\n第三行\n'; + const restored = restoreOriginalEndings(before, after); + assert.equal(restored, '第一行\r\n第二行改过\r\n第三行\r\n'); +}); + +test('摆回:LF 稿子不会被改成 CRLF', () => { + const before = '第一行\n第二行\n'; + const after = '第一行\n第二行改过\n'; + const restored = restoreOriginalEndings(before, after); + assert.equal(restored, '第一行\n第二行改过\n'); +}); + +test('摆回:混合行尾的稿子,没被碰到的行连原来的行尾都留着', () => { + const before = '甲\r\n乙\n丙\r\n'; + const after = '甲\n乙\n丙改过\n'; + const restored = restoreOriginalEndings(before, after); + assert.equal(restored, '甲\r\n乙\n丙改过\r\n'); +}); + +test('摆回:内容一个字都不动(只差行尾)', () => { + const before = '甲\r\n乙\r\n丙'; + const after = '甲\n乙\n丙'; + const restored = restoreOriginalEndings(before, after); + assert.equal(toLfOnly(String(restored)), toLfOnly(after)); + assert.equal(restored, '甲\r\n乙\r\n丙'); +}); + +test('摆回:末尾没有换行的文件,末尾还是没有', () => { + const before = '甲\r\n乙'; + const after = '甲\n乙'; + const restored = restoreOriginalEndings(before, after); + assert.equal(restored, '甲\r\n乙'); +}); + +test('摆回:新增的行用原文件的主导行尾', () => { + const before = '甲\r\n乙\r\n'; + const after = '甲\n新行\n乙\n'; + const restored = restoreOriginalEndings(before, after); + assert.equal(restored, '甲\r\n新行\r\n乙\r\n'); +}); + +test('摆回:内容被别处改过时,只还原本来的那几行,不覆盖别人的改动', () => { + const before = '甲\r\n乙\r\n丙\r\n'; + const after = '甲\n别人改的\n乙\n丙\n'; + const restored = restoreOriginalEndings(before, after); + assert.equal(toLfOnly(String(restored)), toLfOnly(after), '内容必须原样'); + assert.equal(restored, '甲\r\n别人改的\r\n乙\r\n丙\r\n'); +}); + +test('摆回:空文件与空内容不炸', () => { + assert.equal(restoreOriginalEndings('', ''), ''); + assert.equal(restoreOriginalEndings('', '新\n'), '新\n'); +}); diff --git a/plugins/unclemoc/factscribe/tests/save-eol.test.mjs b/plugins/unclemoc/factscribe/tests/save-eol.test.mjs new file mode 100644 index 00000000..e627620f --- /dev/null +++ b/plugins/unclemoc/factscribe/tests/save-eol.test.mjs @@ -0,0 +1,190 @@ +// 保存路径的行尾保真:真引擎端到端(CRLF / LF / 混合三种稿子)。 +// +// 跑法(包目录下): +// node --test tests/save-eol.test.mjs +// +// 这份测试要真的拉起随包的 Python 引擎(vendored 在 miniapp/node/engine/), +// 所以需要一台有 Python ≥3.10 的机器;没有就跳过(不假装通过)。 +// +// 它证明什么: +// * 引擎读文件用文本模式(CRLF→LF)、写文件用二进制写——不改这一层的话, +// 保存一次就把整篇的行尾变成 LF; +// * Node 代理这一层在保存前后按原文件的行尾摆回去,CRLF 稿子存一次, +// CRLF 一个不少地回来,内容一字不差。 +// +// 写操作一律落在 /tmp 的样例盘副本上,不碰任何真实稿盘。 + +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer as createNetServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; + +import { start } from '../miniapp/node/server.mjs'; + +const PACKAGE_ROOT = new URL('..', import.meta.url).pathname; +const SAMPLE = join(PACKAGE_ROOT, 'miniapp/node/engine/factscribe/samples/guide'); + +let available = false; +let workspace = ''; +let dataDir = ''; +let base = ''; +let dispose = null; + +/** 这台机器上有 Python ≥3.10 吗(没有就跳过这份端到端测试)。 */ +function pythonReady() { + return new Promise((resolve) => { + const candidates = ['python3', 'python']; + let index = 0; + const next = () => { + if (index >= candidates.length) { + resolve(false); + return; + } + const command = candidates[index]; + index += 1; + const child = spawn(command, ['-c', 'import sys; print(1 if sys.version_info >= (3, 10) else 0)'], { + stdio: ['ignore', 'pipe', 'ignore'], + }); + let out = ''; + child.stdout?.on('data', (chunk) => { out += String(chunk); }); + child.once('error', () => next()); + child.once('exit', () => { resolve(out.trim() === '1'); }); + }; + next(); + }); +} + +function freePort() { + return new Promise((resolve, reject) => { + const probe = createNetServer(); + probe.once('error', reject); + probe.listen(0, '127.0.0.1', () => { + const port = probe.address().port; + probe.close(() => resolve(port)); + }); + }); +} + +async function getJSON(path) { + const res = await fetch(base + path, { headers: { accept: 'application/json' } }); + assert.equal(res.status, 200, path + ' → HTTP ' + res.status); + return res.json(); +} + +before(async () => { + if (!(await pythonReady())) return; + workspace = mkdtempSync(join(tmpdir(), 'factscribe-eol-')); + const paper = join(workspace, 'guide'); + cpSync(SAMPLE, paper, { recursive: true }); + dataDir = join(workspace, 'data'); + mkdirSync(dataDir, { recursive: true }); + // 论文根 = workspace(引擎在它下面发现 guide 这个盘)。 + writeFileSync(join(dataDir, 'config.json'), JSON.stringify({ root: workspace }), 'utf8'); + const port = await freePort(); + const controller = new AbortController(); + const handle = await start({ + pluginRoot: PACKAGE_ROOT, + dataDir, + listen: { host: '127.0.0.1', port }, + logger: { info() {}, warn() {}, error() {} }, + signal: controller.signal, + }); + dispose = handle.dispose; + base = 'http://127.0.0.1:' + port; + available = true; +}); + +after(async () => { + if (dispose) await dispose(); + if (workspace) rmSync(workspace, { recursive: true, force: true }); +}); + +/** 把盘里第一个章节文件写成给定的行尾,返回 {绝对路径, 原始LF内容}。 */ +function rewriteSection(eol) { + const projects = getJSON('/api/projects'); + return projects.then((data) => { + const project = data.projects[0]; + const disk = project.disks[0]; + const file = join(workspace, 'guide', 'sections', '01-intro.tex'); + const lf = readFileSync(file, 'utf8').replace(/\r\n/g, '\n'); + const written = eol === 'crlf' ? lf.replace(/\n/g, '\r\n') : lf; + writeFileSync(file, written, 'utf8'); + return { project, disk, file, lf }; + }); +} + +async function saveFirstBlock(ctx) { + const sections = await getJSON('/api/disk/' + ctx.project.id + '/' + ctx.disk.id + '/sections'); + const block = (sections.blocks || [])[0]; + assert.ok(block, '样例盘里得有段'); + const model = await getJSON('/api/disk/' + ctx.project.id + '/' + ctx.disk.id + '/block/' + encodeURIComponent(block.id)); + const res = await fetch(base + '/api/disk/' + ctx.project.id + '/' + ctx.disk.id + '/edit', { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json' }, + body: JSON.stringify({ + file: model.file, + block: model.id, + text: model.plain, + expect_sha: model.sha, + }), + }); + assert.equal(res.status, 200, '保存应当成功'); + const data = await res.json(); + assert.equal(data.ok, true); + return data; +} + +test('CRLF 稿子保存一次,CRLF 一个不少地回来,内容一字不差', async (t) => { + if (!available) { + t.skip('这台机器上没有 Python ≥3.10,端到端跑不了'); + return; + } + const ctx = await rewriteSection('crlf'); + const before = readFileSync(ctx.file); + assert.ok(before.includes(Buffer.from('\r\n')), '前置条件:文件本来就是 CRLF'); + + await saveFirstBlock(ctx); + + const after = readFileSync(ctx.file); + assert.ok(after.includes(Buffer.from('\r\n')), '保存后仍然是 CRLF'); + assert.equal( + (after.toString('utf8').match(/\r\n/g) || []).length, + (ctx.lf.match(/\n/g) || []).length, + 'CRLF 的个数必须与原来一样多', + ); + assert.equal(after.toString('utf8').replace(/\r\n/g, '\n'), ctx.lf, '内容一字不差'); +}); + +test('LF 稿子保存一次,不会被改成 CRLF', async (t) => { + if (!available) { + t.skip('这台机器上没有 Python ≥3.10,端到端跑不了'); + return; + } + const ctx = await rewriteSection('lf'); + await saveFirstBlock(ctx); + const after = readFileSync(ctx.file, 'utf8'); + assert.equal(after.includes('\r\n'), false, 'LF 稿子不该出现 CRLF'); + assert.equal(after, ctx.lf, '内容一字不差'); +}); + +test('混合行尾的稿子,没被改到的行连原来的行尾都留着', async (t) => { + if (!available) { + t.skip('这台机器上没有 Python ≥3.10,端到端跑不了'); + return; + } + const ctx = await rewriteSection('lf'); + // 把第一行单独换成 CRLF,其余仍是 LF。 + const lines = ctx.lf.split('\n'); + const mixed = lines[0] + '\r\n' + lines.slice(1).join('\n'); + writeFileSync(ctx.file, mixed, 'utf8'); + + await saveFirstBlock(ctx); + + const after = readFileSync(ctx.file, 'utf8'); + assert.ok(after.startsWith(lines[0] + '\r\n'), '第一行的 CRLF 留着'); + assert.equal((after.match(/(? 0, true, '其余行仍是 LF'); + assert.equal(after.replace(/\r\n/g, '\n'), ctx.lf, '内容一字不差'); +}); From 908bdf920159cd85c7fc30ea549cee7b8da97ccc Mon Sep 17 00:00:00 2001 From: UncleMoc Date: Wed, 25 Nov 2026 19:35:10 +0800 Subject: [PATCH 2/2] fix(factscribe): vendor the newline-faithful Python engine into the package The vendored copy of the Python engine in this package predates the newline-fidelity work. It read user files in universal-newline mode, so a CRLF file was already LF by the time the text reached the page, and it wrote several user-owned files in platform default text mode, where a CRLF string is written as \r\r\n on Windows. The Node shell restored the endings after each save, but the engine itself still lost them, and the Node layer can only put a file back when its line contents still match. Re-vendor the engine from the FactScribe source tree, which now carries the newline-fidelity work: - new factscribe/textio.py: read_text_exact / write_text_exact / append_text_exact keep the file's own line endings, and to_lf gives the analysis layer an explicit normalisation point; - the read side uses read_text_exact, the write side write_text_exact; - machine-generated artefacts (JSON reports, audit matrices, manifests) keep using the platform default, so their format stays predictable. The vendored tree is produced by miniapp/build.sh and is byte-identical to the source tree apart from the excluded web/ directory. Measured on the vendored sample paper, saving through this package: a 678-byte section with 11 CRLF endings came back as 678 bytes with 11 CRLF endings and the same sha256; the LF file (667 bytes, 11 LF) and the mixed file (668 bytes, 1 CRLF + 10 LF) came back byte-identical. With the previous engine the Node layer had to repair the file after every CRLF and mixed save; with this engine the engine's own write is already faithful. Not verified: Windows end to end, and Linux. --- .../miniapp/node/engine/factscribe/audit.py | 15 +- .../miniapp/node/engine/factscribe/brief.py | 4 +- .../node/engine/factscribe/buildpdf.py | 10 +- .../miniapp/node/engine/factscribe/bundle.py | 10 +- .../miniapp/node/engine/factscribe/checks.py | 3 + .../node/engine/factscribe/citations.py | 3 +- .../node/engine/factscribe/citeedit.py | 15 +- .../node/engine/factscribe/citeview.py | 9 +- .../miniapp/node/engine/factscribe/cli.py | 3 +- .../miniapp/node/engine/factscribe/doctor.py | 7 +- .../node/engine/factscribe/projects.py | 91 ++++++++--- .../miniapp/node/engine/factscribe/protect.py | 5 +- .../node/engine/factscribe/reportapi.py | 5 +- .../node/engine/factscribe/scaffold.py | 3 +- .../miniapp/node/engine/factscribe/serve.py | 3 +- .../miniapp/node/engine/factscribe/style.py | 7 +- .../node/engine/factscribe/term_suggest.py | 18 ++- .../miniapp/node/engine/factscribe/terms.py | 4 +- .../miniapp/node/engine/factscribe/texscan.py | 5 +- .../miniapp/node/engine/factscribe/textio.py | 152 ++++++++++++++++++ .../node/engine/factscribe/textreuse.py | 3 +- .../miniapp/node/engine/factscribe/tide.py | 13 +- .../engine/factscribe/workbench/importer.py | 12 +- .../engine/factscribe/workbench/knowledge.py | 6 +- .../engine/factscribe/workbench/projects.py | 8 +- .../engine/factscribe/workbench/server.py | 3 +- .../node/engine/factscribe/workbench/venue.py | 8 +- .../node/engine/factscribe/workbench/write.py | 93 +++++++---- .../engine/factscribe/workbench_dataplayer.py | 7 +- 29 files changed, 408 insertions(+), 117 deletions(-) create mode 100644 plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textio.py diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/audit.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/audit.py index a567ad92..ff28c665 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/audit.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/audit.py @@ -25,6 +25,7 @@ from .texrules import (adjacency_hits, arith_hits, display_hits, fsignore_quant_hits, numeric_macro_hits, tabular_regions) +from .textio import read_text_exact, split_lines, to_lf from .texscan import (_balanced, _blank, _extract_numbers, _merge_number_units, has_auditable_content, scan_tex, sentence_index, sentence_spans, structural_whitelist) @@ -334,7 +335,7 @@ def _source_text_keys(text: str) -> set[str]: def _source_line(text: str, line: int) -> str: - lines = text.split("\n") + lines = split_lines(text) return lines[line - 1] if 1 <= line <= len(lines) else "" @@ -558,7 +559,7 @@ def verify_sources(cfg: Config, facts: list[Fact]) -> tuple[list[Issue], list[Is continue try: digest = sha256_file(full) - texts[src] = full.read_text(encoding="utf-8") + texts[src] = to_lf(read_text_exact(full)) except (OSError, UnicodeDecodeError) as exc: red.append(Issue("UNREADABLE_SOURCE", "fact %r 的 source 读不了:%s(%s)" % (f.id, src, exc), location=loc, token=f.id, params={"fact": repr(f.id), "src": str(src), "detail": str(exc)})) @@ -980,7 +981,7 @@ def _needs_scan(cfg: Config, rel: str) -> bool: 「未扫描」是噪声。读不了的文件照旧报(fail-closed)。 """ try: - text = _read_text(cfg.root / rel, cfg.root) + text = to_lf(_read_text(cfg.root / rel, cfg.root)) except ConfigError: return True return has_auditable_content(text) @@ -988,6 +989,9 @@ def _needs_scan(cfg: Config, rel: str) -> bool: def run_audit(cfg: Config, facts: list[Fact], sections: list[tuple[str, str]], resolve: bool = False): + # 分析入口归一行尾:读盘侧按原样读(CRLF 不丢),分析层按行做事; + # 归一的是内存副本,磁盘字节不动。 + sections = [(rel, to_lf(text)) for rel, text in sections] if not facts: raise ConfigError("facts 为空(%s 没匹配到任何 fact)——空账不算通过" % cfg.facts_glob) if not sections: @@ -1354,7 +1358,8 @@ def _line_bound_quant(line_no: int) -> list[Fact]: for key, line, col in scan.cites: used_keys[key] = used_keys.get(key, 0) + 1 entry = bib_by_key.get(key) - line_text = text.split("\n")[line - 1].strip() if line - 1 < len(text.split("\n")) else "" + _lines = split_lines(text) + line_text = _lines[line - 1].strip() if line - 1 < len(_lines) else "" if entry is None: red.append(Issue( "MISSING_CITE", "引用了 bib 里不存在的 key %r" % key, @@ -1510,7 +1515,7 @@ def _line_bound_quant(line_no: int) -> list[Fact]: struct_root = cfg.root_tex if not struct_root and (cfg.root / "main.tex").is_file(): struct_root = "main.tex" - shell = (cfg.root / "main.tex").read_text(encoding="utf-8") + shell = to_lf(read_text_exact(cfg.root / "main.tex")) if all(rel != "main.tex" for rel, _text in sections): struct_sections = list(sections) + [("main.tex", shell)] structural = structural_whitelist( diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/brief.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/brief.py index fadb77a0..edd07667 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/brief.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/brief.py @@ -27,6 +27,7 @@ from .evidence import suggest_evidence from .style import _headings # 复用既有标题抽取,不另写一套 from .terms import Term, load_glossary +from .textio import read_text_exact, to_lf from .texrules import strip_comments_and_verbatim from .texscan import scan_tex @@ -122,7 +123,7 @@ def _input_order(cfg: Config, known: set[str]) -> list[str]: if root_file is None or not root_file.is_file(): return [] try: - text = root_file.read_text(encoding="utf-8") + text = to_lf(read_text_exact(root_file)) except (OSError, UnicodeDecodeError): return [] body = strip_comments_and_verbatim(text) @@ -243,6 +244,7 @@ def build_brief(project: Path | str, section: str | None = None) -> Brief: "简报无从生成;请先补账。" % cfg.facts_glob) sections = load_sections(cfg) + sections = [(rel, to_lf(text)) for rel, text in sections] rows = build_sections(cfg, sections) if not rows: raise ConfigError( diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/buildpdf.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/buildpdf.py index 036af46b..f020acf5 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/buildpdf.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/buildpdf.py @@ -20,6 +20,7 @@ from . import fonts as fontcache from .constants import EXIT_CONFIG, EXIT_INTERNAL, EXIT_MISSING, EXIT_OK +from .textio import read_text_exact, write_text_exact TIMEOUT_SECONDS = 600 TAIL_LINES = 20 @@ -212,13 +213,13 @@ def auto_build(root: Path, output: str = "main.pdf", % (cjk_font, _tail(out))), info if font is not None: patched = rewrite_cjk_font( - target.read_text(encoding="utf-8"), font) + read_text_exact(target), font) info["font_source"] = "system" info["cjk_font"] = str(font) mode = "temp-cjk-font" elif fandol_dir is not None: patched = rewrite_cjk_font_fandol( - target.read_text(encoding="utf-8"), fandol_dir) + read_text_exact(target), fandol_dir) info["font_source"] = "fandol" info["font_dir"] = str(fandol_dir) mode = "temp-fandol-font" @@ -234,11 +235,12 @@ def auto_build(root: Path, output: str = "main.pdf", "(先跑 `python3 -m factscribe fonts --fetch`," "或试 --cjk-font <路径>)。\n%s" % _tail(out)), info patched = rewrite_cjk_font( - target.read_text(encoding="utf-8"), font) + read_text_exact(target), font) info["font_source"] = "system" info["cjk_font"] = str(font) mode = "temp-cjk-font" - target.write_text(patched, encoding="utf-8") + # newline="":临时副本与源文件逐字节对应(不引入 CRLF 翻译)。 + write_text_exact(target, patched) rc, out = _run_engine(exe, work, tex.name) info["attempts"].append({ "attempt": 2, "mode": mode, "returncode": rc, diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/bundle.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/bundle.py index 919f8ebc..31d6ec04 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/bundle.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/bundle.py @@ -36,6 +36,7 @@ from .checks import run_packages from .config import (Config, ConfigError, load_facts, load_sections) from .evidence import lock_check, read_lock, unfrozen_info +from .textio import read_text_exact, to_lf from .texscan import scan_tex BUNDLE_VERSION = "1" @@ -300,7 +301,7 @@ def collect_closure(cfg: Config) -> Closure: def _run_gate_audit(cfg: Config, closure: Closure) -> dict: """现跑一遍审计(闭包口径),返回退出码与全部判定条目。""" facts = load_facts(cfg) - sections = [(rel, (cfg.root / rel).read_text(encoding="utf-8")) + sections = [(rel, to_lf(read_text_exact(cfg.root / rel))) if (cfg.root / rel).is_file() else (rel, "") for rel in closure.files] if not sections: @@ -349,7 +350,7 @@ def _figure_item(cfg: Config, closure: Closure, audit: dict) -> GateItem: if not p.is_file(): continue try: - scan = scan_tex(p.read_text(encoding="utf-8")) + scan = scan_tex(to_lf(read_text_exact(p))) except (OSError, UnicodeDecodeError): continue figures.update(scan.figures) @@ -459,7 +460,7 @@ def _extra_item(index: int, check: ExtraCheck, root: Path) -> GateItem: return GateItem(code, check.name, STATUS_FAIL, "%s 不存在(正则无处可查)" % check.file, origin="config") try: - text = target.read_text(encoding="utf-8") + text = to_lf(read_text_exact(target)) except (OSError, UnicodeDecodeError) as exc: return GateItem(code, check.name, STATUS_FAIL, "%s 读不了:%s" % (check.file, exc), origin="config") @@ -675,7 +676,8 @@ def _artifact_bytes(root: Path, rel: str, source: Path, 写盘与**预览**共用这一条路——预览看到的字节/指纹/大小与真导出逐字一致。 """ try: - text = source.read_text(encoding="utf-8") + # 按原样读:工件是用户文件的副本,行尾不该在打包时被换掉。 + text = read_text_exact(source) except (OSError, UnicodeDecodeError): return source.read_bytes(), False new_text = _apply_exclusions(root, rel, text, patterns, excluded) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/checks.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/checks.py index 3b433510..b6314b78 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/checks.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/checks.py @@ -51,6 +51,7 @@ from .config import Config, ConfigError, _config_warn, load_toml from .constants import EXIT_RED, EXIT_YELLOW, SEV_INFO +from .textio import to_lf from .i18n import finding_key # -------------------------------------------------------------------------- @@ -520,6 +521,8 @@ def run_packages(cfg: Config, facts, sections, resolve: bool = False): 只发生在槽路径:每条发现多 `domain` 键(DomainIssue.as_dict), summary 末尾多 `by_domain` 计数(§3.2 只增键)。 """ + # 分析入口归一行尾(读盘侧按原样读,CRLF 不丢):归一的是内存副本。 + sections = [(rel, to_lf(text)) for rel, text in sections] packages = resolve_packages(cfg) red, yellow, hints = [], [], [] unresolved: list = [] diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citations.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citations.py index da06f444..333cda0d 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citations.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citations.py @@ -7,6 +7,7 @@ from pathlib import Path from .config import ConfigError +from .textio import read_text_exact from .texscan import _balanced # -------------------------------------------------------------------------- @@ -65,7 +66,7 @@ def stable_id(self): def parse_bib(path: Path, root: Path) -> list[BibEntry]: try: - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) except OSError as exc: raise ConfigError("读不了参考文献 %s:%s" % (path, exc)) rel = path.relative_to(root).as_posix() diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeedit.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeedit.py index 815f73a3..eed8dcaa 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeedit.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeedit.py @@ -23,6 +23,7 @@ from .citeview import _bib_paths, _tex_sources from .citations import parse_bib from .config import ConfigError, load_config +from .textio import read_text_exact, write_text_exact # BibTeX 的 key:字母数字,外加冒号、点、下划线、连字符。 KEY_RE = re.compile(r"^[A-Za-z0-9:._-]+$") @@ -72,12 +73,16 @@ def _bib_value(raw: str) -> str: def _write_atomic(path: Path, text: str) -> None: - """原子写:同目录临时文件 + rename。""" + """原子写:同目录临时文件 + rename。 + + `newline=""`:不翻译换行。bib 里原有的 '\r\n' 不会被写成 + '\r\r\n',新增的行也不会在 Windows 上被塞进 '\r\n'—— + 「保存必须逐字保留正文内容」对参考文献同样成立。 + """ path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name("%s.tmp-%d" % (path.name, os.getpid())) try: - with open(tmp, "w", encoding="utf-8") as fh: - fh.write(text) + write_text_exact(tmp, text) os.replace(str(tmp), str(path)) finally: if tmp.exists(): @@ -154,7 +159,7 @@ def citation_add_data(project: Path | str, body: dict, target = _project_bib(cfg) try: - old = target.read_text(encoding="utf-8") + old = read_text_exact(target) except (OSError, UnicodeDecodeError): old = "" fields = { @@ -210,7 +215,7 @@ def citation_delete_data(project: Path | str, body: dict, for hit in hits: path = hit["path"] try: - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("bib 读不了:%s" % hit["file"], code="CITATION_INVALID") lines = text.splitlines(keepends=True) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeview.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeview.py index c93f155f..8e3f7f93 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeview.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeview.py @@ -37,6 +37,7 @@ from .citations import parse_bib, valid_stable_id from .config import (ConfigError, _glob_paths, load_config, load_sections) +from .textio import read_text_exact from .texscan import scan_tex # 正文里点名的 bib:`\bibliography{a,b}`(逗号分隔,通常不带 .bib)。 @@ -52,9 +53,13 @@ def _read(path: Path) -> str: - """读文本;读不动就当空文件(只读页面不该因为一个坏文件整页报错)。""" + """读文本;读不动就当空文件(只读页面不该因为一个坏文件整页报错)。 + + 按原样读(不做通用换行翻译):正文里的 '\r\n' 原样保留,别在读盘 + 这一步就把用户的行尾换掉。 + """ try: - return path.read_text(encoding="utf-8") + return read_text_exact(path) except (OSError, UnicodeDecodeError): return "" diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py index 901794c2..02a9f914 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py @@ -63,6 +63,7 @@ suggest) from .tide import DEFAULT_SNAPSHOT_ROOT from .tide import render_human as render_tide +from .textio import read_text_exact, to_lf from .tide import render_restore as render_tide_restore from .tide import render_snapshot as render_tide_snapshot from .tide import restore_snapshot, run_tide, save_snapshot @@ -1746,7 +1747,7 @@ def _cmd_style_doc(args, paths: list[str]) -> int: path = Path(raw) if not path.is_file(): raise ConfigError("--doc 指向的 %s 不存在" % raw) - sections.append((raw, path.read_text(encoding="utf-8"))) + sections.append((raw, to_lf(read_text_exact(path)))) formats[raw] = mdscan.format_of(raw) rules_info = load_style_rules_info(root, args.rules) cfg = Config(root=root) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/doctor.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/doctor.py index 7b2a3244..bfeb7283 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/doctor.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/doctor.py @@ -26,6 +26,7 @@ load_facts, load_sections, load_toml) from .evidence import LOCK_REL, read_lock, unfrozen_info from .scaffold import INIT_FILES +from .textio import read_text_exact, to_lf LEVEL_OK = "ok" LEVEL_WARN = "warn" @@ -57,7 +58,7 @@ def _tool_version(exe: str) -> str: def _read_text(path: Path, limit: int = 400_000) -> str: try: - return path.read_text(encoding="utf-8", errors="ignore")[:limit] + return to_lf(read_text_exact(path, errors="ignore"))[:limit] except OSError: return "" @@ -69,7 +70,7 @@ def _uses_cjk(cfg: Config) -> bool: if main.is_file(): texts.append(_read_text(main)) try: - texts.extend(text for _, text in load_sections(cfg)) + texts.extend(to_lf(text) for _, text in load_sections(cfg)) except ConfigError: pass blob = "\n".join(texts) @@ -219,7 +220,7 @@ def _project_check(root: Path) -> tuple[dict, Config | None]: def _sections_check(cfg: Config) -> dict: try: - sections = load_sections(cfg) + sections = [(rel, to_lf(text)) for rel, text in load_sections(cfg)] except ConfigError as exc: return _check("sections", "章节", LEVEL_FAIL, str(exc), fix="检查 factscribe.toml 的 sections / root_tex") diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/projects.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/projects.py index 5bf05339..290d4e17 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/projects.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/projects.py @@ -17,6 +17,9 @@ from datetime import datetime, timezone from pathlib import Path +from .textio import (dominant_newline, read_text_exact, split_keepends, + write_text_exact) + REGISTRY_VERSION = 1 MAX_PROJECTS = 30 CONFIG_NAME = "factscribe.toml" @@ -195,17 +198,49 @@ def _toml_value(text: str) -> str: return '"%s"' % out +def _write_parts(path: Path, parts: list[tuple[str, str]], + fallback: str = "\n") -> None: + """把 `[(行内容, 行尾), ...]` 写回文件。 + + 与原来的 `"\n".join(lines).rstrip("\n") + "\n"` 意图一致(末尾不留 + 空行、末尾恰好一个换行),但**行尾用文件自己的那一种**:CRLF 的声明 + 文件不会被顺手改成 LF,Windows 上也不会被翻译成 CRLF。 + """ + rows = list(parts) + had_rows = bool(rows) + while rows and rows[-1][0] == "": + rows.pop() # 末尾的空行不留 + out: list[str] = [] + last = len(rows) - 1 + for index, (content, term) in enumerate(rows): + if index < last: + out.append(content + (term or fallback)) + else: + out.append(content) + text = "".join(out) + if text: + text += fallback + elif had_rows: + text = fallback + write_text_exact(path, text) + + def _rewrite_project_table(path: Path, values: dict) -> None: """改写项目声明(`factscribe.toml`)的 `[project]` 表:只替换/追加给定的键,别的原样保留。 骨架模板里已经有的键就地替换;没有的追加到 `[project]` 段末尾。 其它段(`[budget]`/`[evidence]` 之类)一个字都不动。 `values` 的值是**已经排版好的 TOML 字面量**(字符串带引号、数组带方括号)。 + + 行尾按原样保留:改一个键不牵动整份文件的换行。 """ - lines = path.read_text(encoding="utf-8").splitlines() + raw = read_text_exact(path) + parts = split_keepends(raw) + contents = [content for content, _ in parts] + nl = dominant_newline(raw) start = None - end = len(lines) - for index, line in enumerate(lines): + end = len(contents) + for index, line in enumerate(contents): stripped = line.strip() if not stripped.startswith("["): continue @@ -216,24 +251,25 @@ def _rewrite_project_table(path: Path, values: dict) -> None: end = index break if start is None: - lines.append("") - lines.append("[project]") + section: list[tuple[str, str]] = [("", nl), ("[project]", nl)] for key, value in values.items(): - lines.append("%s = %s" % (key, value)) + section.append(("%s = %s" % (key, value), nl)) + new_parts = parts + section else: pending = dict(values) section = [] - for line in lines[start:end]: - match = re.match(r"^\s*([A-Za-z0-9_-]+)\s*=", line) + for index in range(start, end): + content, term = parts[index] + match = re.match(r"^\s*([A-Za-z0-9_-]+)\s*=", content) key = match.group(1) if match else "" if key in pending: - section.append("%s = %s" % (key, pending.pop(key))) + section.append(("%s = %s" % (key, pending.pop(key)), term)) else: - section.append(line) + section.append((content, term)) for key, value in pending.items(): - section.append("%s = %s" % (key, value)) - lines[start:end] = section - path.write_text("\n".join(lines).rstrip("\n") + "\n", encoding="utf-8") + section.append(("%s = %s" % (key, value), nl)) + new_parts = parts[:start] + section + parts[end:] + _write_parts(path, new_parts, nl) def create_project(*, title: str, parent: str, slug: str, @@ -330,29 +366,32 @@ def _has_project_table(text: str) -> bool: def _rewrite_flat_keys(path: Path, values: dict) -> None: """改写扁平 schema(v3 形态 A)的顶层键:只替换/追加给定的键。 - 只动第一张表之前的那些行;表里的内容一个字都不改。 + 只动第一张表之前的那些行;表里的内容一个字都不改。行尾按原样保留。 """ if not values: return - lines = path.read_text(encoding="utf-8").splitlines() - end = len(lines) - for index, line in enumerate(lines): + raw = read_text_exact(path) + parts = split_keepends(raw) + contents = [content for content, _ in parts] + nl = dominant_newline(raw) + end = len(contents) + for index, line in enumerate(contents): if line.strip().startswith("["): end = index break pending = dict(values) - head = [] - for line in lines[:end]: - match = re.match(r"^\s*([A-Za-z0-9_-]+)\s*=", line) + head: list[tuple[str, str]] = [] + for index in range(end): + content, term = parts[index] + match = re.match(r"^\s*([A-Za-z0-9_-]+)\s*=", content) key = match.group(1) if match else "" if key in pending: - head.append("%s = %s" % (key, pending.pop(key))) + head.append(("%s = %s" % (key, pending.pop(key)), term)) else: - head.append(line) + head.append((content, term)) for key, value in pending.items(): - head.append("%s = %s" % (key, value)) - path.write_text("\n".join(head + lines[end:]).rstrip("\n") + "\n", - encoding="utf-8") + head.append(("%s = %s" % (key, value), nl)) + _write_parts(path, head + parts[end:], nl) def update_project(registry: dict, path: str, name: str = "", @@ -385,7 +424,7 @@ def update_project(registry: dict, path: str, name: str = "", new_desc = str(description or "").strip() cfg_file = config_file(Path(entry["path"])) if cfg_file.is_file(): - text = cfg_file.read_text(encoding="utf-8") + text = read_text_exact(cfg_file) values = {"description": _toml_value(new_desc)} if _has_project_table(text): # v1 与 v3 形态 B/C:名字在 [project].title。 diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/protect.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/protect.py index 36b72428..4692021d 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/protect.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/protect.py @@ -23,6 +23,7 @@ SEV_YELLOW) from .texscan import (_balanced, _blank, _extract_numbers, _line_of, _mask_envs_and_verb, scan_tex) +from .textio import read_text_exact, to_lf # -------------------------------------------------------------------------- @@ -573,8 +574,8 @@ def compare(before: Path | str, after: Path | str, for rel in sorted(set(bfiles) & set(afiles)): try: - btext = bfiles[rel].read_text(encoding="utf-8", errors="replace") - atext = afiles[rel].read_text(encoding="utf-8", errors="replace") + btext = to_lf(read_text_exact(bfiles[rel], errors="replace")) + atext = to_lf(read_text_exact(afiles[rel], errors="replace")) except OSError as exc: raise ConfigError("读不了 %s:%s" % (rel, exc)) from exc b = _surface(btext) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/reportapi.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/reportapi.py index f0059f1d..948ae9ad 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/reportapi.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/reportapi.py @@ -29,6 +29,7 @@ from .report import (ReportError, _artifact_path, _rel_posix, _resolve_in_ws, _ws_root, check_report, load_report, lock_report, report_card, sign_report, verify_signoff) +from .textio import write_text_exact # 报告扫描面:两个 glob,顺序即展示顺序。 REPORT_PATTERNS = ("experiments/*/reports/*.report.toml", @@ -311,8 +312,8 @@ def _write_atomic(path: Path, text: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name("%s.tmp-%d" % (path.name, os.getpid())) try: - with open(tmp, "w", encoding="utf-8") as fh: - fh.write(text) + # newline="":不翻译换行,报告模板里用户填的数字与注释逐字落盘。 + write_text_exact(tmp, text) os.replace(str(tmp), str(path)) finally: if tmp.exists(): diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/scaffold.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/scaffold.py index e6f39d25..07aea916 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/scaffold.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/scaffold.py @@ -21,6 +21,7 @@ from .config import Config, ConfigError, load_config, load_facts, load_toml from .constants import CONFIDENCE_OK from .facts import sha256_file +from .textio import read_text_exact, to_lf LANGS = ("zh", "en") DEFAULT_TITLE = {"zh": "未命名论文", "en": "Untitled Paper"} @@ -526,7 +527,7 @@ def check_value_in_source(root: Path, cfg: Config, source_rel: str, text = "" try: - text = Path(source_path).read_text(encoding="utf-8") + text = to_lf(read_text_exact(Path(source_path))) except UnicodeDecodeError: raise ConfigError( "产物 %s 不是 UTF-8 文本,没法核对 value——换一件文本产物," diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/serve.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/serve.py index ecb719be..a49bfe2b 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/serve.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/serve.py @@ -36,6 +36,7 @@ from .constants import EXIT_OK, VERSION from .report import ReportError, _payload, _severity_of from .reportapi import report_action_data, reports_data, report_template_data +from .textio import read_text_exact from .samples import SampleError, install_guide_sample, is_guide_path from .workbench import (SectionError, add_fact_data, audit_data, brief_data, create_section_data, delete_section_data, @@ -602,7 +603,7 @@ def _section_page(self) -> None: if not pdf.is_file(): raise ConfigError("还没有编译产物 %s,先编译一次" % out, code="PDF_MISSING") - title = section_title(tex.read_text(encoding="utf-8", errors="replace")) + title = section_title(read_text_exact(tex, errors="replace")) try: data = locate(pdf, title) except FileNotFoundError: diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/style.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/style.py index 80cf8555..007716c5 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/style.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/style.py @@ -40,6 +40,7 @@ from .segment import segment from .terms import Glossary, key_of, load_glossary from .texscan import sentence_spans +from .textio import read_text_exact, to_lf DISCLAIMER = ("本工具不评估、也不试图规避任何 AI 检测器;它检测的是可机械判定的" "公式化写作特征。黄牌只是改写提示,不阻断、不改正文;证据钢印" @@ -1498,7 +1499,7 @@ def _term_allowlist(rules: dict, project_root: Path, path = project_root / str(name) if not path.is_file(): continue - for line in path.read_text(encoding="utf-8").splitlines(): + for line in read_text_exact(path).splitlines(): line = line.strip() if not line or line.startswith("#"): continue @@ -3079,6 +3080,10 @@ def analyze(cfg: Config, sections: list[tuple[str, str]], rules: dict, stage: str = STAGE_DRAFT, rule_report: dict | None = None ) -> StyleResult: + # 分析入口归一行尾(读盘侧按原样读,CRLF 不丢):归一的是内存副本。 + sections = [(rel, to_lf(text)) for rel, text in sections] + if before is not None: + before = (before[0], [(rel, to_lf(text)) for rel, text in before[1]]) thresholds = _thresholds(rules) limits = _limits(rules) min_units = limits["min_paragraph_units"] diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/term_suggest.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/term_suggest.py index 8f89bd26..8e042d32 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/term_suggest.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/term_suggest.py @@ -21,6 +21,7 @@ from .config import ConfigError, load_config, load_sections from .style import _source_view +from .textio import dominant_newline, read_text_exact, to_lf, write_text_exact from .terms import (load_glossary, key_of, normalize_surface, parse_glossary) @@ -59,7 +60,7 @@ def _walk_sources(root: Path) -> list[tuple[str, str]]: for part in rel.parts[:-1]): continue out.append((rel.as_posix(), - path.read_text(encoding="utf-8", errors="replace"))) + to_lf(read_text_exact(path, errors="replace")))) return out @@ -72,7 +73,7 @@ def _project_sources(root: Path) -> list[tuple[str, str]] | None: return None if not sections: return None - return [(str(name), str(text)) for name, text in sections] + return [(str(name), to_lf(str(text))) for name, text in sections] def collect_sources(root: Path) -> list[tuple[str, str]]: @@ -546,16 +547,19 @@ def add_from_tsv(from_path, picks, glossary_path=None, "--pick 不在候选文件里:%s" % "、".join(repr(x) for x in missing)) if added: - text = targets.read_text(encoding="utf-8") - if text and not text.endswith("\n"): - text += "\n" + # 按原样读:词表是用户维护的,追加不能顺手把行尾换掉。 + text = read_text_exact(targets) + nl = dominant_newline(text) + if text and not text.endswith(("\n", "\r")): + text += nl stamp = today or date.today().isoformat() comment = "# terms add %s:来源 %s" % (stamp, source) body = [comment] body += ["%s\t\t\t待分类" % surface for surface in added] - targets.write_text(text + "\n".join(body) + "\n", encoding="utf-8") + # newline="":新增行用词表自己的行尾,不掺进混合行尾。 + write_text_exact(targets, text + nl.join(body) + nl) # 写完立刻重解析:词表坏了必须当场报错,不能留给 style 才发现。 - parsed = parse_glossary(targets.read_text(encoding="utf-8")) + parsed = parse_glossary(read_text_exact(targets)) for surface in added: if parsed.canonical_of(surface) is None: raise ConfigError("写入后词表无法解析新术语:%s" % surface) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/terms.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/terms.py index cb828304..38ce6e06 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/terms.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/terms.py @@ -29,6 +29,8 @@ from dataclasses import dataclass from pathlib import Path +from .textio import read_text_exact + DEFAULT_TERMS_DIR = Path(__file__).resolve().parent / "terms" DEFAULT_WORKSPACE_PATH = DEFAULT_TERMS_DIR / "workspace.tsv" DEFAULT_PAPER_PATH = DEFAULT_TERMS_DIR / "paper.tsv" @@ -296,7 +298,7 @@ def parse_glossary(text: str, source: str = "paper") -> Glossary: def _load_glossary_file(path: Path, source: str | None = None) -> Glossary: - return parse_glossary(path.read_text(encoding="utf-8"), + return parse_glossary(read_text_exact(path), source or _source_for_path(path)) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/texscan.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/texscan.py index be063245..8259bf25 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/texscan.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/texscan.py @@ -8,6 +8,7 @@ from .facts import THIN, _NUM_RE, canon_text, number_key from .texrules import strip_comments_and_verbatim +from .textio import split_lines # -------------------------------------------------------------------------- # LaTeX 扫描:注释、命令名、结构参数、\fact{} 绑定 @@ -616,10 +617,10 @@ def structural_whitelist(sections: list[tuple[str, str]], def _extract_numbers(masked: str, original: str) -> list[dict]: - orig_lines = original.split("\n") + orig_lines = split_lines(original) out = [] offset = 0 - for ln, line in enumerate(masked.split("\n"), 1): + for ln, line in enumerate(split_lines(masked), 1): toks: list[dict] = [] for m in _NUM_RE.finditer(line): raw, suffix, pct = m.group(1), m.group(2) or "", bool(m.group(3)) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textio.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textio.py new file mode 100644 index 00000000..d62c12a7 --- /dev/null +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textio.py @@ -0,0 +1,152 @@ +# -*- coding: utf-8 -*- +"""用户正文内容的换行保真读写。 + +事项约定:**保存必须逐字保留正文内容**——用户正文(论文正文 `.tex`、 +参考文献 `.bib`、事实账、项目声明、术语表)里的任何字符,**包括行尾**, +都不许被保存链路改写。 + +Windows 上默认文本模式两头都动手: + +* **写**:`newline=None`(默认)时,任何 `'\n'` 都被翻译成 `os.linesep` + (Windows 上是 `'\r\n'`);已经存在的 `'\r\n'` 会被写成 + `'\r\r\n'`——CR 被复制,是内容损坏。 +* **读**:`newline=None`(默认)时做通用换行翻译(universal newlines), + `'\r\n'` 被读成 `'\n'`。于是「读入 → 编辑 → 写回」跑一遍,正文的 + 行尾就被悄悄换掉了——这同样违反「逐字保留」。 + +这里统一收口: + +* **读**用 `newline=""`:不做任何换行翻译,`'\r\n'` 原样留在字符串里; +* **写**用 `newline=""`:不翻译,`'\n'` 就是 `'\n'`,`'\r\n'` 就是 + `'\r\n'`。 + +换行交还给人:文件里原本是什么行尾,写回还是什么行尾,一个字符不多、 +一个字符不少。 + +机器产物(JSON 报告、审计矩阵、证据锁、清单 manifest、日志……)**不用** +这一套——它们是工具自己生成、自己消费,格式由工具定,行尾统一成 `'\n'` +反而更可预期。哪些算「用户内容」、划分依据见 +`docs/design/SPEC-V3.0.md` 与本次修复的交付报告。 +""" +from __future__ import annotations + +from pathlib import Path + +__all__ = [ + "read_text_exact", + "write_text_exact", + "append_text_exact", + "split_keepends", + "split_lines", + "dominant_newline", + "to_lf", +] + + +def read_text_exact(path: Path | str, errors: str | None = None) -> str: + """按原样读文本:不做通用换行翻译,`'\r\n'` 原样保留。 + + 与 `Path.read_text()` 的差别只有一处——换行。其它行为一致: + 按 UTF-8 解码(非 UTF-8 抛 `UnicodeDecodeError`,读不动抛 + `OSError`),不剥离 BOM,不动末尾换行。 + + `errors` 透传给 `open()`:`"replace"` 时坏字节换成 U+FFFD, + 与 `Path.read_text(errors="replace")` 行为一致。 + """ + with open(path, "r", encoding="utf-8", newline="", errors=errors) as handle: + return handle.read() + + +def write_text_exact(path: Path | str, text: str) -> None: + """按原样写文本:`'\n'` 不翻译成 `'\r\n'`,`'\r\n'` 不变成 + `'\r\r\n'`。写出去的字节与传进来的字符串逐字节对应。""" + with open(path, "w", encoding="utf-8", newline="") as handle: + handle.write(text) + + +def append_text_exact(path: Path | str, text: str, + newline: str | None = None) -> None: + """按原样追加文本:不翻译换行。 + + `newline` 给定时用它当行尾(`'\r\n'` / `'\n'` / `'\r'`), + 追加进去的每一行都带这个行尾;不给时原样追加(调用方自己保证文本里 + 的行尾已经对)。 + + Windows 上默认文本模式(`newline=None`)会把追加的 `'\n'` 翻译成 + `'\r\n'`——一份 LF 账本会被追写成一半 LF 一半 CRLF 的混合行尾。 + """ + with open(path, "a", encoding="utf-8", newline="") as handle: + if newline is None: + handle.write(text) + else: + handle.write(text.replace("\r\n", "\n").replace("\r", "\n") + .replace("\n", newline)) + + +def to_lf(text: str) -> str: + """把 `'\r\n'` / `'\r'` 归一成 `'\n'`——**分析层**专用。 + + 为什么需要它:读盘侧一律按原样读(`read_text_exact`),正文里的 + `'\r\n'` 原样留在字符串里。可分析层(审计、闸门、文风、数号抽取) + 是**按行**做事的,它假设 `'\n'` 是行分隔符,正则里也用 `$` 锚行尾。 + 若把带 `'\r\n'` 的文本直接丢进去,行尾会多出一个 `'\r'`,`$` + 锚点会失配、发现条数会漂。 + + 所以边界要显式:`.textio` 只负责「读进来不丢字节」,**分析入口**调 + 这条把行尾归一——归一的是**内存里的副本**,磁盘上的字节一个不动。 + """ + return text.replace("\r\n", "\n").replace("\r", "\n") + + +def split_lines(text: str) -> list[str]: + """按行切开,行尾(CRLF/CR/LF)都不带进行内容。 + + 等价于「先 `to_lf` 再 `split('\n')`」,但只切 `'\r\n'`/`'\r'`/ + `'\n'` 三种行尾——不像 `str.splitlines()` 那样把 `'\x0b'`、 + `'\x0c'`、`'\u2028'` 也当行尾切。 + """ + return to_lf(text).split("\n") + + +def split_keepends(text: str) -> list[tuple[str, str]]: + """把文本切成 `[(行内容, 行尾), ...]`,行尾**原样保留**。 + + `str.splitlines()` 会把行尾吃掉——重建时行尾就丢了(CRLF 的文件会被 + 悄悄改成 LF)。这里把行尾单独摘出来,改哪一行都不影响其它行的行尾。 + """ + out: list[tuple[str, str]] = [] + index = 0 + size = len(text) + while index < size: + stop = index + while stop < size and text[stop] not in "\r\n": + stop += 1 + if stop >= size: + out.append((text[index:stop], "")) + break + if text[stop] == "\r" and stop + 1 < size and text[stop + 1] == "\n": + end = stop + 2 + else: + end = stop + 1 + out.append((text[index:stop], text[stop:end])) + index = end + return out + + +def dominant_newline(text: str, default: str = "\n") -> str: + """文本里占多数的行尾(`'\r\n'` / `'\n'` / `'\r'`)。 + + 追加内容时用它做新行的行尾:CRLF 的文件补进去的也是 CRLF,不会补出 + 一份混合行尾的文件。一行行尾都没有时用 `default`。 + """ + crlf = text.count("\r\n") + lf = text.count("\n") - crlf + cr = text.count("\r") - crlf + best = max(crlf, lf, cr) + if best <= 0: + return default + if crlf == best: + return "\r\n" + if lf == best: + return "\n" + return "\r" diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textreuse.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textreuse.py index a4f9915e..b136d5f7 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textreuse.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textreuse.py @@ -54,6 +54,7 @@ from pathlib import Path from .config import ConfigError +from .textio import read_text_exact, to_lf # -------------------------------------------------------------------------- # 常量(口径与预注册阈值) @@ -455,7 +456,7 @@ def _load_side(root: Path, exts: tuple, strip_comments: bool, sentences: bool): docs = [] for path in collect_files(root, exts): try: - text = path.read_text(encoding="utf-8", errors="replace") + text = to_lf(read_text_exact(path, errors="replace")) except OSError: continue if sentences: diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/tide.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/tide.py index b757bd64..f30ed509 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/tide.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/tide.py @@ -27,6 +27,7 @@ from .constants import EXIT_OK, EXIT_RED, SEV_RED from .protect import _code_view, _heading_items from .protect import compare as compare_protect +from .textio import dominant_newline, read_text_exact RISE = "rise" FALL = "fall" @@ -325,7 +326,7 @@ def _read_ledger(path: Path) -> list[dict]: if not path.exists(): return [] try: - raw = path.read_text(encoding="utf-8") + raw = read_text_exact(path) except OSError as exc: raise ConfigError("读不了账本 %s:%s" % (path, exc)) from exc events: list[dict] = [] @@ -356,7 +357,7 @@ def _append_ledger(path: Path, events: list[dict]) -> int: if path.exists(): try: existing = {line for line in - path.read_text(encoding="utf-8").splitlines() + read_text_exact(path).splitlines() if line.strip()} except OSError as exc: raise ConfigError("读不了账本 %s:%s" % (path, exc)) from exc @@ -364,9 +365,13 @@ def _append_ledger(path: Path, events: list[dict]) -> int: if not new: return 0 path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as fh: + # 行尾跟账本自身走:账本是 append-only 的机器产物,但它长在用户盘里—— + # 追写不能造出「一半 LF 一半 CRLF」的混合行尾(Windows 上默认文本模式 + # 会把追加的 '\n' 翻译成 '\r\n')。账本里占多数的行尾说了算。 + newline = dominant_newline(read_text_exact(path)) if path.exists() else "\n" + with path.open("a", encoding="utf-8", newline="") as fh: for line in new: - fh.write(line + "\n") + fh.write(line + newline) return len(new) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/importer.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/importer.py index 1d6f7527..d4949f67 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/importer.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/importer.py @@ -18,6 +18,8 @@ import time from pathlib import Path +from ..textio import read_text_exact, write_text_exact + #: 报告目录里认的扩展名。 REPORT_SUFFIXES = (".toml", ".json") @@ -225,7 +227,7 @@ def parse_report(path: str | Path) -> dict: if not target.is_file(): raise ImportError_("报告文件不在:%s" % target, "REPORT_FILE_MISSING") try: - text = target.read_text(encoding="utf-8", errors="replace") + text = read_text_exact(target, errors="replace") except OSError as exc: raise ImportError_("读不了报告文件:%s" % exc, "REPORT_READ_FAILED") from exc suffix = target.suffix.lower() @@ -360,7 +362,7 @@ def write_draft(disk_path: str | Path, report_name: str, rows: list[dict], written += 1 try: target.parent.mkdir(parents=True, exist_ok=True) - target.write_text("\n".join(lines), encoding="utf-8") + write_text_exact(target, "\n".join(lines)) except OSError as exc: raise ImportError_("写草稿失败:%s" % exc, "DRAFT_WRITE_FAILED") from exc return {"ok": True, "draft_path": str(target), "count": written, @@ -370,7 +372,7 @@ def write_draft(disk_path: str | Path, report_name: str, rows: list[dict], def _draft_fact_count(path: Path) -> int: """草稿里的条目数(`[[fact]]` 的个数)。""" try: - text = path.read_text(encoding="utf-8", errors="replace") + text = read_text_exact(path, errors="replace") except OSError: return 0 return text.count("[[fact]]") @@ -432,7 +434,7 @@ def read_draft(disk_path: str | Path, report_name: str) -> dict: if not target.is_file(): raise ImportError_("找不到这条导入记录:%s" % report_name, "DRAFT_NOT_FOUND") try: - text = target.read_text(encoding="utf-8", errors="replace") + text = read_text_exact(target, errors="replace") except OSError as exc: raise ImportError_("读不了草稿:%s" % exc, "DRAFT_READ_FAILED") from exc head: dict = {} @@ -489,7 +491,7 @@ def delete_draft(disk_path: str | Path, report_name: str) -> dict: raise ImportError_("没有这条导入记录:%s" % name, "DRAFT_MISSING") source = "" try: - text = target.read_text(encoding="utf-8", errors="replace") + text = read_text_exact(target, errors="replace") except OSError: text = "" for line in text.splitlines(): diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/knowledge.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/knowledge.py index 7d3bc962..adb96667 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/knowledge.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/knowledge.py @@ -21,6 +21,8 @@ import time from pathlib import Path, PurePosixPath +from ..textio import read_text_exact + #: 项目级工作台配置文件名(与 `ai.py` 同源:`[ai]` 节就在这个文件里)。 CONFIG_NAME = "workbench.toml" @@ -256,7 +258,7 @@ def preview(disk_path: str | Path, rel: str) -> dict: if suffix not in TEXT_SUFFIXES: raise KnowledgeError("这个后缀不认:%s" % suffix, "KNOWLEDGE_SUFFIX_INVALID") try: - text = target.read_text(encoding="utf-8", errors="replace") + text = read_text_exact(target, errors="replace") except OSError as exc: raise KnowledgeError("读不了这个文件:%s" % exc, "KNOWLEDGE_READ_FAILED") from exc truncated = len(text) > PREVIEW_CHARS @@ -345,7 +347,7 @@ def context_text(disk_path: str | Path, limit: int = CONTEXT_CHARS) -> str: continue try: target = _safe_project_file(disk, row["path"]) - text = target.read_text(encoding="utf-8", errors="replace") + text = read_text_exact(target, errors="replace") except (KnowledgeError, OSError): continue text = text.strip() diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/projects.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/projects.py index 98dcdc24..8c54a359 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/projects.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/projects.py @@ -18,6 +18,8 @@ from datetime import datetime, timezone from pathlib import Path +from ..textio import read_text_exact + CONFIG_NAME = "factscribe.toml" MAX_DEPTH = 3 @@ -147,7 +149,7 @@ def _title_command(target: Path) -> tuple[int, int, str] | None: (换下一个候选文件)。判定口径与读侧一字不差。 """ try: - text = target.read_text(encoding="utf-8", errors="replace") + text = read_text_exact(target, errors="replace") except OSError: return None match = _TITLE_CMD_RE.search(text) @@ -839,7 +841,7 @@ def _section_files(path: Path) -> list[tuple[str, str]]: for candidate in candidates: try: out.append((str(candidate.relative_to(path)), - candidate.read_text(encoding="utf-8", errors="replace"))) + read_text_exact(candidate, errors="replace"))) except (OSError, ValueError): continue return out @@ -1033,7 +1035,7 @@ def cover_abstract_block(path: str | Path) -> dict | None: if root_tex is None: return None try: - text = root_tex.read_text(encoding="utf-8") + text = read_text_exact(root_tex) except (OSError, UnicodeDecodeError): return None span = abstract_env_span(text) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/server.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/server.py index 1e199913..00d53420 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/server.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/server.py @@ -57,6 +57,7 @@ from urllib.parse import unquote, urlparse from ..config import ConfigError +from ..textio import read_text_exact from .projects import MAX_DEPTH, disk_meta, disk_sections, load_projects from .proposal import (ProposalError, create_proposal, list_proposals, read_proposal, resolve_proposal) @@ -713,7 +714,7 @@ def _rerender_block(self, disk: Path, rel: str, block_id: str) -> str: if not rel: return "" path = Path(disk) / rel - text = path.read_text(encoding="utf-8", errors="replace") + text = read_text_exact(path, errors="replace") for block in render_tex(text, stem=Path(rel).stem, disk_root=disk): if block.get("id") == block_id: return str(block.get("html") or "") diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/venue.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/venue.py index 043d2fbe..cfb57fef 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/venue.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/venue.py @@ -26,6 +26,8 @@ from datetime import date, datetime from pathlib import Path +from ..textio import write_text_exact + #: 项目级工作台配置文件名(与 `ai.py` / `knowledge.py` 同源)。 CONFIG_NAME = "workbench.toml" @@ -103,10 +105,10 @@ def _ensure_config(path: Path) -> None: return try: path.parent.mkdir(parents=True, exist_ok=True) - path.write_text( + write_text_exact( + path, "# FactScribe 工作台配置(项目级)。\n" - "# [ai] 放模型后端;[workbench] 放工作台自己的字段;[venue] 放目标刊物。\n", - encoding="utf-8") + "# [ai] 放模型后端;[workbench] 放工作台自己的字段;[venue] 放目标刊物。\n") except OSError as exc: raise VenueError("建不了 %s:%s" % (path, exc), "VENUE_CONFIG_FAILED") from exc diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/write.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/write.py index a2be60ec..058f4646 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/write.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/write.py @@ -35,6 +35,7 @@ from .. import i18n from ..config import ConfigError, load_config, load_facts +from ..textio import dominant_newline, read_text_exact, split_keepends from .projects import (ABSTRACT_BLOCK_ID as _ABSTRACT_BLOCK_ID, CONFIG_NAME, TOKEN_CLOSE, TOKEN_OPEN, TOKEN_RE, abstract_env_span as _abstract_env_span, @@ -883,7 +884,7 @@ def save_abstract(disk_root: Path, client_text: str, rel = block.file path = _writable_target(disk_root, rel) try: - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("读不到摘要所在文件:%s(%s)" % (rel, exc), code="SECTION_MISSING") @@ -907,7 +908,7 @@ def find_block(disk_root: Path, rel_file: str, block_id: str) -> Block: """按 id 找到一段:返回它所在文件、偏移与原文。""" path = _safe_section_file(disk_root, rel_file) try: - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("读不到章节文件:%s(%s)" % (rel_file, exc), code="SECTION_MISSING") @@ -1092,8 +1093,8 @@ def _block_shape_guard(block: Block, text: str, disk_root: Path, own_labels = set(_SHAPE_LABEL_RE.findall(block.raw)) if _SHAPE_LABEL_RE.search(text): try: - file_text = _writable_target(disk_root, block.file).read_text( - encoding="utf-8") + file_text = read_text_exact( + _writable_target(disk_root, block.file)) except (ConfigError, OSError, UnicodeDecodeError): file_text = "" file_labels = set(_SHAPE_LABEL_RE.findall(file_text)) @@ -1143,7 +1144,7 @@ def save_block(disk_root: Path, rel_file: str, block_id: str, _guard_surface_kept(segments, new_raw, bound_values, TOKEN_MISMATCH_CODE) path = _safe_section_file(disk_root, rel_file) try: - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("读不到章节文件:%s(%s)" % (rel_file, exc), code="SECTION_MISSING") @@ -1213,7 +1214,7 @@ def propose_ai_draft(disk_root: Path, rel_file: str, after_block_id: str, raise ConfigError("回复是空的,没什么可写进稿的。", code="DRAFT_EMPTY") path = _safe_section_file(disk_root, rel_file) try: - source_text = path.read_text(encoding="utf-8") + source_text = read_text_exact(path) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("读不到章节文件:%s(%s)" % (rel_file, exc), code="SECTION_MISSING") @@ -1357,7 +1358,7 @@ def insert_ai_draft(disk_root: Path, rel_file: str, after_block_id: str, _check_expect_sha(block, expect_sha) path = _safe_section_file(disk_root, rel_file) try: - source = path.read_text(encoding="utf-8") + source = read_text_exact(path) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("读不到章节文件:%s(%s)" % (rel_file, exc), code="SECTION_MISSING") @@ -1383,7 +1384,7 @@ def delete_ai_draft(disk_root: Path, rel_file: str, block_id: str) -> dict: code="DRAFT_NOT_AI") path = _safe_section_file(disk_root, rel_file) try: - source = path.read_text(encoding="utf-8") + source = read_text_exact(path) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("读不到章节文件:%s(%s)" % (rel_file, exc), code="SECTION_MISSING") @@ -1421,7 +1422,7 @@ def read_assembly(disk_root: Path, cfg=None) -> dict: if not path.is_file(): return {"file": "", "entries": []} try: - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) except (OSError, UnicodeDecodeError): return {"file": str(path), "entries": []} base = path.parent @@ -1447,7 +1448,7 @@ def read_assembly(disk_root: Path, cfg=None) -> dict: def _section_meta(path: Path) -> tuple[str, str]: """章节文件的(一级标题, 短指纹)——目录显示与条目 43 的 sha 同源。""" try: - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) except (OSError, UnicodeDecodeError): return "", "" for block in render_tex(text, stem=path.stem): @@ -1462,7 +1463,8 @@ def _rewrite_assembly(path: Path, entries: list[dict], text: str) -> str: 槽位=原来那些条目所在的行号(升序);第 i 个新条目写进第 i 个槽位, 这样调序只动装配行,不动文件里的其它内容。 """ - lines = text.splitlines() + rows = split_keepends(text) + lines = [content for content, _ in rows] slots = sorted(entry["line"] for entry in entries) for index, entry in enumerate(entries): if index >= len(slots): @@ -1473,7 +1475,12 @@ def _rewrite_assembly(path: Path, entries: list[dict], text: str) -> str: original = lines[number] cmd = "\\input" if "\\input" in original else "\\include" lines[number] = "%s{%s}" % (cmd, entry["target"]) - return "\n".join(lines) + ("\n" if text.endswith("\n") else "") + # 行尾跟装配文件自身走(CRLF 的装配不被顺手改成 LF)。 + out = [] + for index, content in enumerate(lines): + term = rows[index][1] if index < len(rows) else "" + out.append(content + term) + return "".join(out) def move_section(disk_root: Path, rel: str, direction: str) -> dict: @@ -1495,7 +1502,7 @@ def move_section(disk_root: Path, rel: str, direction: str) -> dict: if other < 0 or other >= len(entries): return {"ok": True, "moved": False, "order": [e["rel"] for e in entries]} entries[index], entries[other] = entries[other], entries[index] - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) new_text = _rewrite_assembly(path, entries, text) result = atomic_write(path, new_text, keep=BACKUP_KEEP) return {"ok": True, "moved": True, "order": [e["rel"] for e in entries], @@ -1525,11 +1532,15 @@ def delete_section(disk_root: Path, rel: str) -> dict: if source.is_file(): shutil.move(str(source), str(attic)) moved = True - lines = path.read_text(encoding="utf-8").splitlines() + raw = read_text_exact(path) + rows = split_keepends(raw) dropped = entries.pop(index) - if 0 <= dropped["line"] < len(lines): - lines.pop(dropped["line"]) - text = "\n".join(lines) + "\n" + if 0 <= dropped["line"] < len(rows): + rows.pop(dropped["line"]) + # 行尾跟装配文件自身走:CRLF 的装配文件不被顺手改成 LF。 + text = "".join(content + term for content, term in rows) + if not text.endswith(("\n", "\r")): + text += dominant_newline(raw) result = atomic_write(path, text, keep=BACKUP_KEEP) return {"ok": True, "removed": rel, "attic": str(attic), "moved": moved, "backup": result["backup"], @@ -1558,14 +1569,16 @@ def create_section(disk_root: Path, title: str, slug: str = "", target = sections_dir / name if target.exists(): raise ConfigError("这一节已经存在:%s" % name, code="SECTION_EXISTS") - content = "\\section{%s}\n\n" % clean_title + # 新建的一节用盘里占多数的行尾(CRLF 的盘不补出 LF 行)。 + nl = _disk_newline(*sorted(sections_dir.glob("*.tex"))) + content = "\\section{%s}%s%s" % (clean_title, nl, nl) atomic_write(target, content, backup=False) assembly = read_assembly(disk_root, cfg) path = Path(assembly["file"]) if assembly["file"] else None if path is None or not path.is_file(): return {"ok": True, "file": str(target), "rel": target.name, "assembled": False} - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) line = "\\input{%s}" % target.relative_to(disk_root).as_posix()[:-len(".tex")] entries = assembly["entries"] position = len(entries) @@ -1574,20 +1587,38 @@ def create_section(disk_root: Path, title: str, slug: str = "", if entry["rel"] == after: position = index + 1 break - lines = text.splitlines() + rows = split_keepends(text) + lines = [content for content, _ in rows] insert_at = None if entries and position > 0: insert_at = entries[position - 1]["line"] + 1 else: insert_at = _before_end_document(lines) - lines.insert(insert_at, line) - new_text = "\n".join(lines) + ("\n" if text.endswith("\n") else "") + # 新插入的一行用装配文件自己的行尾。 + rows.insert(insert_at, (line, dominant_newline(text))) + new_text = "".join(content + term for content, term in rows) result = atomic_write(path, new_text, keep=BACKUP_KEEP) return {"ok": True, "file": str(target), "rel": target.relative_to(disk_root).as_posix(), "assembled": True, "backup": result["backup"]} +def _disk_newline(*candidates) -> str: + """盘里占多数的行尾(找不到就用 LF)。 + + 新建的文件按盘里已有的行尾来写——CRLF 的盘里不补出 LF 行, + 免得同一盘里两种行尾混着。 + """ + for candidate in candidates: + try: + text = read_text_exact(candidate) + except (OSError, UnicodeDecodeError): + continue + if text: + return dominant_newline(text) + return "\n" + + def _before_end_document(lines: list[str]) -> int: for index in range(len(lines) - 1, -1, -1): if "\\end{document}" in lines[index]: @@ -1660,7 +1691,7 @@ def rename_section(disk_root: Path, rel_file: str, block_id: str, title: str, "after": new_raw, "sha": _short_sha(new_raw)} path = _safe_section_file(disk_root, rel_file) try: - source = path.read_text(encoding="utf-8") + source = read_text_exact(path) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("读不到章节文件:%s(%s)" % (rel_file, exc), code="SECTION_MISSING") @@ -1702,7 +1733,7 @@ def set_disk_title(disk_root: Path, title: str, subtitle: str = "", open_at = raw.index("{") new_raw = raw[:open_at + 1] + body + raw[raw.rindex("}"):] try: - source = target.read_text(encoding="utf-8") + source = read_text_exact(target) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("读不到入口文件:%s(%s)" % (target.name, exc), code="SECTION_MISSING") @@ -1829,7 +1860,7 @@ def insert_fact_binding(disk_root: Path, rel_file: str, block_id: str, new_raw = block.raw[:at] + insertion + block.raw[at:] path = _safe_section_file(disk_root, rel_file) try: - source = path.read_text(encoding="utf-8") + source = read_text_exact(path) except (OSError, UnicodeDecodeError) as exc: raise ConfigError("读不到章节文件:%s(%s)" % (rel_file, exc), code="SECTION_MISSING") @@ -1877,7 +1908,10 @@ def rewrite_table(path: Path, table: str, values: dict) -> None: `values` 的值是**排版好的 TOML 字面量**(字符串带引号)。 """ - lines = path.read_text(encoding="utf-8").splitlines() + raw = read_text_exact(path) + rows = split_keepends(raw) + lines = [content for content, _ in rows] + nl = dominant_newline(raw) start = None end = len(lines) for index, line in enumerate(lines): @@ -1909,7 +1943,12 @@ def rewrite_table(path: Path, table: str, values: dict) -> None: for key, value in pending.items(): section.append("%s = %s" % (key, value)) lines[start:end] = section - atomic_write(path, "\n".join(lines).rstrip("\n") + "\n") + # 拼回:原行保留自己的行尾,新追加的行用文件自己的行尾 + out = [] + for index, content in enumerate(lines): + term = rows[index][1] if index < len(rows) else "" + out.append(content + (term or nl)) + atomic_write(path, "".join(out).rstrip("\r\n") + nl) def workbench_config(disk_root: Path) -> dict: diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench_dataplayer.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench_dataplayer.py index 1491937c..041b4148 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench_dataplayer.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench_dataplayer.py @@ -13,6 +13,7 @@ from .audit import _aggregate_exit, run_audit, source_path from .brief import build_brief, payload as brief_payload from .config import (ConfigError, load_config, load_facts, load_sections) +from .textio import write_text_exact from .evidence import (freeze_evidence, lock_check, log_state, read_lock, unfreeze_evidence, unfrozen_info) from .i18n import issue_dict @@ -142,7 +143,9 @@ def write_section_data(project: Path | str, file: str, text: str, except ValueError: raise ConfigError("章节越出项目根:%s" % rel) tmp = target.with_name(target.name + ".tmp") - tmp.write_text(text, encoding="utf-8") + # newline="":不翻译换行。正文里的 '\r\n' 原样落盘—— + # Windows 上默认文本模式会把它写成 '\r\r\n'(内容损坏)。 + write_text_exact(tmp, text) os.replace(tmp, target) return {"file": rel, "bytes": len(text.encode("utf-8"))} @@ -296,7 +299,7 @@ def create_section_data(project: Path | str, file: str, text=None, raise SectionError("父目录不存在:%s(先建目录再建节)" % rel, code="SECTION_PARENT_MISSING") content = text if isinstance(text, str) else DEFAULT_SECTION_TEXT - target.write_text(content, encoding="utf-8") + write_text_exact(target, content) return {"file": rel, "bytes": len(content.encode("utf-8"))}