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/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..28aaa23b 100644
--- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py
+++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py
@@ -27,6 +27,7 @@
from .buildpdf import _is_font_error, auto_build
from .config import (Config, ConfigError, load_config, load_facts,
load_sections)
+from .console import safe_stdio
from .constants import (EXIT_CONFIG, EXIT_INTERNAL, EXIT_OK, EXIT_RED,
EXIT_YELLOW, VERSION)
from .doctor import collect as collect_doctor
@@ -63,6 +64,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 +1748,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)
@@ -2258,6 +2260,11 @@ def cmd_evidence(args) -> int:
def main(argv=None) -> int:
+ # 非 UTF-8 控制台(中文 Windows 的 cp936/gbk)上,人读输出里的装饰字符
+ # 编不出来 → UnicodeEncodeError → 命令退成 exit 4(工具内部错误)。
+ # 这里在入口把 stdout/stderr 装上「安全降级」的编码错误处理器:
+ # 编不出来的字符换同义 ASCII,命令照常跑完、退出码照旧。
+ safe_stdio()
try:
args = build_parser().parse_args(argv)
except SystemExit as exc:
diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/console.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/console.py
new file mode 100644
index 00000000..4c1ccc5d
--- /dev/null
+++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/console.py
@@ -0,0 +1,97 @@
+# -*- coding: utf-8 -*-
+"""控制台输出:非 UTF-8 控制台上,人读输出不许把命令自己搞崩。
+
+背景(Windows 真机实测,2026-11-25):中文 Windows 的本地编码是
+gbk/cp936(ACP=936,区域 zh-CN),**编不出**人读输出里的装饰字符
+(`✓` / `✗` / `↔` …)。
+`print()` 撞上就抛 `UnicodeEncodeError`,命令层把它当成
+「工具内部错误」→ 退成 **exit 4**,而不是这条命令本来的判定码与退出码。
+真机实测原话:
+
+ > python -m factscribe doctor examples/minimal
+ factscribe: 工具内部错误:UnicodeEncodeError: 'gbk' codec can't encode
+ character '\\u2713' in position 113: illegal multibyte sequence
+ (退出码 4)
+
+修法(口径):**降级的是字符,不是命令的判定**。
+
+* 人读输出编不出来时,换成**同义的 ASCII**(`✓`→`v`、`✗`→`x`、`↔`→`<->`…),
+ 语义不丢(通过仍是「通过」、失败仍是「失败」,不改成问号——问号
+ 分不清这两者),命令照常跑完、退出码照旧。
+* **编码不动**:流仍用它自己的编码(中文 Windows 上就是 cp936),
+ 所以重定向到文件的中文还是那个编码,外部读它的工具不用改。
+* 结构化输出(`--json`)不受影响:载荷里没有编不出来的字符时,
+ `--json` 的内容逐字节不变(仓内用例把这条锁住)。
+
+macOS / Linux 的流本来就是 UTF-8,装上这套处理器**不改变任何一个字节**
+(UTF-8 能编下所有字符,处理器根本不会被叫醒)。
+"""
+from __future__ import annotations
+
+import codecs
+import sys
+
+# 编码错误处理器的名字(进程内唯一)。
+ERROR_HANDLER = "factscribe.safe"
+
+# 编不出来的字符 → 同义 ASCII。表里的每一项都是仓里真在用的字符:
+# 扫 factscribe/ 全量,cp936 编不出来的装饰字符就这八个(另有几个
+# 生僻汉字与一个落单代理字符,只在分词测试样本里,不会进人读输出)。
+_ASCII_FALLBACK = {
+ "✓": "v", # U+2713 CHECK MARK —— 通过
+ "✗": "x", # U+2717 BALLOT X —— 失败
+ "↔": "<->", # U+2194 LEFT RIGHT ARROW
+ "⇒": "=>", # U+21D2 RIGHTWARDS DOUBLE ARROW
+ "⊆": "<=", # U+2286 SUBSET OF OR EQUAL TO
+ "«": "<<", # U+00AB
+ "»": ">>", # U+00BB
+ "²": "^2", # U+00B2
+}
+
+
+def _replace_handler(exc):
+ """编码错误处理器:编不出来的字符换同义 ASCII,其余照旧。
+
+ 只处理「编码」方向的错(UnicodeEncodeError);解码方向的错照旧抛
+ 出去(那是输入坏了,不该悄悄改)。
+ """
+ if not isinstance(exc, UnicodeEncodeError):
+ raise exc
+ chunk = exc.object[exc.start:exc.end]
+ out = "".join(_ASCII_FALLBACK.get(ch, "?") for ch in chunk)
+ return (out, exc.end)
+
+
+def _register_handler() -> None:
+ """注册处理器(进程内一次就够;重复注册同名会报错,所以先查)。"""
+ try:
+ codecs.lookup_error(ERROR_HANDLER)
+ except LookupError:
+ codecs.register_error(ERROR_HANDLER, _replace_handler)
+
+
+def safe_stream(stream) -> bool:
+ """给一个文本流装上「安全降级」的编码错误处理器。
+
+ 返回是否真的装了:流不是 `TextIOWrapper`(测试里常见的 StringIO、
+ 被换过的 stdout)或重配失败 → 返回 False,不抛。
+ """
+ reconfigure = getattr(stream, "reconfigure", None)
+ if reconfigure is None:
+ return False
+ _register_handler()
+ try:
+ reconfigure(errors=ERROR_HANDLER)
+ except (ValueError, OSError, LookupError):
+ return False
+ return True
+
+
+def safe_stdio() -> None:
+ """CLI 入口统一把 stdout/stderr 装上安全降级(幂等,可重复调用)。
+
+ 只换**错误处理器**,不换编码:流的编码是环境的事(中文 Windows 上
+ 就是 cp936),我们不替用户改;改的只是「编不出来时怎么办」。
+ """
+ for stream in (sys.stdout, sys.stderr):
+ safe_stream(stream)
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/landing.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/landing.py
new file mode 100644
index 00000000..b9aec235
--- /dev/null
+++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/landing.py
@@ -0,0 +1,117 @@
+# -*- coding: utf-8 -*-
+"""落点解析:写盘前把「真实写到哪儿」判清楚。
+
+**为什么有它**(D1,Windows 真机 2026-11-25 实测):
+
+写侧闸要回答两个问题:这个路径能不能解析(落点解不解得出来)?解析出来的
+落点还在盘根里面吗?答不上来的时候,引擎**不许裸崩**。
+
+本条 miniapp 线上的引擎没有主仓那套写侧落点闸(那是主仓 PR #56 才加的,
+本线还没有),所以这里只收口「落点解析」这一件事:
+
+* 落点**解不出来**(软链成环是最常见的一种)→ 判成不可解 → 拒写,带着
+ 调用点**自己已有的那个判定码**出去,不许裸崩成「工具内部错误」(exit 4);
+* 落点解出来了但**不在盘根里面** → 同样是拒写(各调用点的原话不动)。
+
+**判据取语义,不取 errno 白名单**:各平台写 errno 的口径不一样——
+Windows 真机实测,软链成环时 `os.path.realpath(strict=True)` 抛的是
+`OSError(winerror=1921 ERROR_CANT_RESOLVE_FILENAME, errno=22 EINVAL)`,
+不是 POSIX 的 `ELOOP`(Windows 的 `errno.ELOOP` 常量是 10062,跟这里收到的
+errno 不是一回事)。拿某个 errno 常量当白名单,必然在某个平台上漏判 →
+裸崩 → exit 4。所以这里按「解不出来就是解不出来」判。
+
+**为什么用 `os.path.realpath` 而不是 `pathlib.Path.resolve()`**:后者在软链
+成环时 3.10–3.12 抛 `RuntimeError`、3.13+ 干脆不抛(跨版本读数会漂)。
+`os.path.realpath(strict=True)` 各版本一个样:解不出来就抛错。
+"""
+from __future__ import annotations
+
+import errno
+import os
+from pathlib import Path
+
+from .config import ConfigError
+
+__all__ = ["landing_point", "resolve_landing", "unresolved_reason"]
+
+# Windows 真机实测(2026-11-25):软链成环时
+# `os.path.realpath(strict=True)` 抛的是
+# `OSError(winerror=1921 ERROR_CANT_RESOLVE_FILENAME, errno=22 EINVAL)`,
+# 不是 POSIX 的 `ELOOP`(Windows 的 `errno.ELOOP` 常量是 10062,跟这里收到的
+# errno 不是一回事)。断链则是 `errno=ENOENT`(winerror=2)。
+# 这个常量只用来判「文案上要不要直说是成环」,判定本身不依赖它。
+_WINERROR_CANT_RESOLVE_FILENAME = 1921
+
+
+def _real(path: Path | str) -> str:
+ """真实路径。
+
+ 存在(含软链)→ 解析后的真实目标;不存在(还没建、或是断链)→ 按
+ strict=False 尽力解析(断链给出「本来要写到哪」)。解不出来(成环等)→
+ 抛 OSError,由调用方判「不可解」。
+
+ errno 口径各平台不同(成环:POSIX 是 `ELOOP`,Windows 是
+ `winerror=1921` + `errno=EINVAL`),所以这里只负责把错误**抛出去**,
+ 「算不算不可解」由调用方按语义判(见 `unresolved_reason`)。
+ """
+ try:
+ return os.path.realpath(str(path), strict=True)
+ except OSError as exc:
+ if exc.errno == errno.ENOENT:
+ return os.path.realpath(str(path), strict=False)
+ raise
+
+
+def landing_point(target: Path | str) -> str:
+ """写入落点的真实位置(绝对路径字符串)。
+
+ 落点还不存在时看它爹目录的真实位置——目录是软链的话,新文件就落在
+ 软链那边(可能是项目外)。
+ """
+ path = Path(target)
+ if not os.path.lexists(str(path)):
+ parent = Path(path).parent
+ return os.path.join(_real(parent), path.name)
+ return _real(path)
+
+
+def _is_cycle(exc: OSError) -> bool:
+ """这次失败是不是「软链成环」(文案用;判定不依赖它)。"""
+ if getattr(exc, "winerror", None) == _WINERROR_CANT_RESOLVE_FILENAME:
+ return True
+ return exc.errno == errno.ELOOP
+
+
+def unresolved_reason(exc: OSError) -> str:
+ """落点不可解的一句人话(为什么算不出来)。
+
+ 判据是**语义**:「strict realpath 解不出来」就是不可解——成环只是其中
+ 最常见的一种。能判出是成环就直说成环,判不出就说「算不出来」,不编原因。
+ """
+ if _is_cycle(exc):
+ return "是成环软链,真实落点算不出来"
+ detail = exc.strerror or str(exc)
+ return "真实落点算不出来(%s)" % detail
+
+
+def resolve_landing(target: Path | str, *, what: str, name: str,
+ code: str) -> Path:
+ """解析落点(真实写到哪儿);解不出来 → 拒写,不许裸崩。
+
+ * `target`:要写的那个路径;
+ * `what`:文案里的主语(「章节文件」/「根文件」/「章节」);
+ * `name`:给人看的那份路径名(调用方的相对名,原话用它);
+ * `code`:判定码——调用点**沿用它自己已有的那个码**,不新开。
+
+ 返回解析后的真实路径。解不出来时抛 `ConfigError`(带 `code`)。
+ """
+ try:
+ return Path(landing_point(target))
+ except OSError as exc:
+ # 落点解不出来(成环等)= 不可解:判红、拒写。判据按语义
+ # (解不出来就是不可解),不按 errno 白名单——Windows 上成环是
+ # winerror=1921/errno=EINVAL,白名单判不到它,漏判就退成 exit 4
+ # (工具内部错误),坏了退出码与判定码的契约。
+ raise ConfigError("%s落点不可解:%s %s——拒绝写入(没有落盘)"
+ % (what, name, unresolved_reason(exc)),
+ code=code)
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..33237313
--- /dev/null
+++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textio.py
@@ -0,0 +1,188 @@
+# -*- 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",
+ "restore_newlines",
+]
+
+
+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"
+
+
+def restore_newlines(new_text: str, original: str,
+ fallback: str = "\n") -> str:
+ """把新正文的行尾还原成**原文**的行尾。
+
+ 浏览器交回来的正文恒是 LF——DOM 里没有 CRLF(contenteditable 的
+ textContent 一律给 LF)。若照单写回,CRLF 稿子存一次就变成 LF,或者
+ 变成一半 CRLF 一半 LF 的混合稿子,违反「保存必须逐字保留正文内容」。
+
+ 规则(**逐行**对齐,不是整篇一刀切):
+
+ * 新文的第 k 次断行 → 沿用原文第 k 次断行的行尾。原文是混合行尾时,
+ 哪一行原本是 CRLF,改完还是 CRLF,一行不差;
+ * 原文的断行数不够(新文多出了行)→ 多出来的断行用 fallback
+ (调用方给的是**文件**的主导行尾),免得在 CRLF 稿子里补出 LF 行;
+ * 原文末尾没有行尾的,新文末尾也不补。
+
+ original 是**这一块**的原文(不是整份文件):块的行尾归这一块自己
+ 管,块外的行尾一个都不碰。
+ """
+ orig_ends = [end for _, end in split_keepends(original)]
+ # 原文最后一段若没有行尾,它就不是一次「断行」,不算进断行表。
+ if orig_ends and orig_ends[-1] == "":
+ orig_ends = orig_ends[:-1]
+ extra = fallback or dominant_newline(original)
+ out: list[str] = []
+ for index, (line, end) in enumerate(split_keepends(to_lf(new_text))):
+ if end == "":
+ # 最后一段没有断行:原样留着(不补行尾)。
+ out.append(line)
+ continue
+ out.append(line + (orig_ends[index]
+ if index < len(orig_ends) else extra))
+ return "".join(out)
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..84443745 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)
@@ -806,6 +808,12 @@ def _section_files(path: Path) -> list[tuple[str, str]]:
走审计那套闭包(`load_sections`):配置写 `sections/*.tex` 时收章节,
写 `main.tex` 时收 `\input` 链。根文件(main.tex)的导言区不当作正文,
还有别的章节文件时把它剔掉。
+
+ **文本按落盘原样读**(`read_text_exact`):闭包里的文本走的是通用换行
+ 翻译,CRLF 会被读成 LF。块指纹(sha)是在文本上算的——显示路径(页面
+ 给出的那段指纹)与写回路径(保存时校验的那段指纹)必须看**同一份**文本;
+ 两边口径不一致时,CRLF 稿子的指纹必然对不上,保存直接 409
+ (BLOCK_STALE)。
"""
from ..config import ConfigError, load_config, load_sections
@@ -820,7 +828,8 @@ def _section_files(path: Path) -> list[tuple[str, str]]:
name, text = row
except (TypeError, ValueError):
continue
- rows.append((str(name), str(text)))
+ rows.append((str(name),
+ _read_section_exact(cfg, str(name), str(text))))
except Exception: # noqa: BLE001 - 坏文件不该让整页崩
rows = []
if rows:
@@ -839,12 +848,30 @@ 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
+def _read_section_exact(cfg, rel: str, fallback: str) -> str:
+ """按落盘原样读一个章节文件;读不动就退回闭包里那份。
+
+ 闭包(`load_sections`)给的相对名是相对**解析后**的项目根算的
+ (软链被解析过),而 `cfg.root` 可能还是调用方传进来的那条路径。
+ 两边拼出来的路径指向同一个文件;这里先按 `cfg.root` 拼,不在就按
+ 解析后的根再试一次。
+ """
+ for base in (cfg.root, cfg.root.resolve()):
+ try:
+ target = base / rel
+ if target.is_file():
+ return read_text_exact(target)
+ except (OSError, ValueError):
+ continue
+ return fallback
+
+
def _is_generated(rel: str) -> bool:
"""生成的工件(audit/ 下的宏定义等)不是正文。"""
parts = Path(rel).parts
@@ -1033,7 +1060,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..bc194f2c 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,9 @@
from .. import i18n
from ..config import ConfigError, load_config, load_facts
+from ..landing import resolve_landing
+from ..textio import (dominant_newline, read_text_exact, restore_newlines,
+ split_keepends, to_lf)
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,
@@ -749,9 +752,13 @@ def _safe_section_file(disk_root: Path, rel: str) -> Path:
code="SECTION_PATH_INVALID")
root = disk_root.resolve()
target = disk_root.joinpath(*[p for p in pure.parts if p not in ("", ".")])
+ # 落点先解析:解不出来(成环软链等)→ 判成不可解 → 拒写,不许裸崩成
+ # 「工具内部错误」(exit 4)。判据是语义,不是 errno 白名单(D1)。
+ resolved = resolve_landing(target, what="章节文件", name=rel,
+ code="SECTION_PATH_INVALID")
try:
- inside = target.resolve().relative_to(root)
- except (OSError, ValueError):
+ inside = resolved.relative_to(root)
+ except ValueError:
raise ConfigError("章节文件越出项目根:%s" % rel,
code="SECTION_PATH_INVALID")
if target.suffix.lower() != ".tex":
@@ -809,9 +816,13 @@ def _root_tex_file(disk_root: Path) -> tuple[str, Path]:
code="SECTION_PATH_INVALID")
root = Path(disk_root).resolve()
target = Path(disk_root).joinpath(*[p for p in pure.parts if p not in ("", ".")])
+ # 落点先解析:解不出来(成环软链等)→ 判成不可解 → 拒写,不许裸崩成
+ # 「工具内部错误」(exit 4)。判据是语义,不是 errno 白名单(D1)。
+ resolved = resolve_landing(target, what="根文件", name=rel,
+ code="SECTION_PATH_INVALID")
try:
- inside = target.resolve().relative_to(root)
- except (OSError, ValueError):
+ inside = resolved.relative_to(root)
+ except ValueError:
raise ConfigError("根文件越出项目根:%s" % rel,
code="SECTION_PATH_INVALID")
if target.suffix.lower() != ".tex":
@@ -871,9 +882,11 @@ def save_abstract(disk_root: Path, client_text: str,
"""
block = abstract_block(disk_root)
_check_expect_sha(block, expect_sha)
- prose = _abstract_prose(client_text)
+ # 分析层统一 LF 口径(与 save_block 同一条):客户端交回来的正文恒是
+ # LF,块原文可能是 CRLF。
+ prose = to_lf(_abstract_prose(client_text))
bound_values = _bound_values(disk_root)
- segments = scan(block.raw, bound_values)
+ segments = scan(to_lf(block.raw), bound_values)
_check_token_count(segments, expect_tokens)
new_raw, warnings = _rebuild(segments, prose, code=TOKEN_MISMATCH_CODE)
if not _balanced_ok(new_raw):
@@ -883,10 +896,13 @@ 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")
+ # 落盘层:摘要这一块原有的行尾还原回去(CRLF 稿子存一次仍是 CRLF)。
+ new_raw = restore_newlines(new_raw, block.raw,
+ fallback=dominant_newline(text))
# 重新定位:文件可能被人外部改过(绕过服务端),按当前结构再算一次——
# 写回落在**现在**的摘要块里,不会叠出第二层。
span = _abstract_span(text)
@@ -902,12 +918,24 @@ def save_abstract(disk_root: Path, client_text: str,
"backup": result["backup"], "warnings": _warn_texts(warnings)}
+def _file_newline(disk_root: Path, rel_file: str) -> str:
+ """这个文件的主导行尾(读不动就用 LF)。
+
+ 新写进去的行按**文件**的行尾走:CRLF 的稿子里不补出 LF 行,免得同一
+ 份稿子两种行尾混着。
+ """
+ try:
+ text = read_text_exact(_safe_section_file(disk_root, rel_file))
+ except (ConfigError, OSError, UnicodeDecodeError):
+ return "\n"
+ return dominant_newline(text)
+
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 +1120,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))
@@ -1129,12 +1157,16 @@ def save_block(disk_root: Path, rel_file: str, block_id: str,
"""
block = find_block(disk_root, rel_file, block_id)
_check_expect_sha(block, expect_sha)
- shape_warnings = _block_shape_guard(block, client_text, disk_root,
+ # 分析层统一 LF 口径:客户端(浏览器 contenteditable)交回来的正文恒是
+ # LF,块原文可能是 CRLF。两边都归一到 LF 再做结构活(切保护面、锚点
+ # 回插、保护面比对),落盘时再把这一块原有的行尾还原回去。
+ text_in = to_lf(str(client_text or ""))
+ shape_warnings = _block_shape_guard(block, text_in, disk_root,
code="EDIT_SHAPE_MISMATCH")
bound_values = _bound_values(disk_root)
- segments = scan(block.raw, bound_values)
+ segments = scan(to_lf(block.raw), bound_values)
_check_token_count(segments, expect_tokens)
- new_raw, warnings = _rebuild(segments, client_text,
+ new_raw, warnings = _rebuild(segments, text_in,
code=TOKEN_MISMATCH_CODE)
warnings = list(warnings) + shape_warnings
if not _balanced_ok(new_raw):
@@ -1143,10 +1175,14 @@ 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")
+ # 落盘层:把这一块**原有**的行尾还原到新正文上——CRLF 稿子存一次仍是
+ # CRLF,LF 稿子不会被改成 CRLF,混合稿子逐行照旧。
+ new_raw = restore_newlines(new_raw, block.raw,
+ fallback=dominant_newline(text))
new_text = text[:block.start] + new_raw + text[block.end:]
result = atomic_write(path, new_text, keep=BACKUP_KEEP)
return {"ok": True, "file": rel_file, "block": block_id,
@@ -1169,14 +1205,15 @@ def propose_block_edit(disk_root: Path, rel_file: str, block_id: str,
"""
block = find_block(disk_root, rel_file, block_id)
_check_expect_sha(block, expect_sha)
- text = client_text if isinstance(client_text, str) else ""
+ # 分析层统一 LF 口径(与 save_block 同一条)。
+ text = to_lf(client_text) if isinstance(client_text, str) else ""
if not text.strip():
raise ConfigError("提议内容是空的,没什么可改的。",
code="PROPOSAL_TEXT_EMPTY")
shape_warnings = _block_shape_guard(block, text, disk_root,
code=SHAPE_MISMATCH_CODE)
bound_values = _bound_values(disk_root)
- segments = scan(block.raw, bound_values)
+ segments = scan(to_lf(block.raw), bound_values)
new_raw, warnings = _rebuild(segments, text,
code="PROPOSAL_TOKEN_MISMATCH")
warnings = list(warnings) + shape_warnings
@@ -1185,6 +1222,10 @@ def propose_block_edit(disk_root: Path, rel_file: str, block_id: str,
code="EDIT_UNBALANCED")
_guard_surface_kept(segments, new_raw, bound_values,
"PROPOSAL_TOKEN_MISMATCH")
+ # 落盘层:与 save_block 同一套还原——差异卡上看到的落盘结果,就是
+ # 真写回时写进去的那一份(含行尾)。
+ new_raw = restore_newlines(new_raw, block.raw,
+ fallback=_file_newline(disk_root, rel_file))
return {"kind": "block_edit",
"file": rel_file,
"block": block_id,
@@ -1213,7 +1254,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 +1398,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 +1424,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 +1462,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 +1488,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 +1503,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 +1515,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 +1542,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 +1572,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 +1609,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 +1627,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 +1731,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 +1773,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 +1900,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 +1948,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 +1983,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..40a08507 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,8 @@
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 .landing import resolve_landing
+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
@@ -130,19 +132,24 @@ def write_section_data(project: Path | str, file: str, text: str,
raise ConfigError("file 必填:要写哪一节")
if not isinstance(text, str):
raise ConfigError("text 必须是字符串")
- sections = dict(load_sections(cfg))
- if rel not in sections:
- raise ConfigError("file 不在审计闭包内:%s" % rel)
- if not rel.endswith(".tex"):
- raise ConfigError("只允许写 .tex 章节:%s" % rel)
+ # 落点先解析:解不出来(成环软链等)→ 判成不可解 → 拒写,不许裸崩成
+ # 「工具内部错误」(exit 4)。判据是语义,不是 errno 白名单(D1)。
root = cfg.root.resolve()
- target = (cfg.root / rel).resolve()
+ target = resolve_landing(cfg.root / rel, what="章节", name=rel,
+ code="PATH_ESCAPE")
try:
target.relative_to(root)
except ValueError:
raise ConfigError("章节越出项目根:%s" % rel)
+ sections = dict(load_sections(cfg))
+ if rel not in sections:
+ raise ConfigError("file 不在审计闭包内:%s" % rel)
+ if not rel.endswith(".tex"):
+ raise ConfigError("只允许写 .tex 章节:%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 +303,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"))}
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