diff --git a/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json b/plugins/unclemoc/factscribe/.minimax-plugin/plugin.json index 7444ccbc..da165059 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.2.0", + "version": "1.3.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 a868774f..3d1c3455 100644 --- a/plugins/unclemoc/factscribe/README.md +++ b/plugins/unclemoc/factscribe/README.md @@ -60,15 +60,29 @@ The engine is written in Python. Its source is vendored into the package, so the ### 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. +A save keeps the line endings your file already had. + +The engine reads a section 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. Two independent steps prevent that: + +- The engine restores the endings itself. Every line it wrote keeps the ending of the line it + replaced; a line the user typed gets the file's dominant ending. The AI draft block inserted + into a manuscript is written with the file's dominant ending as well, so a CRLF manuscript gets + a CRLF draft block instead of a stray run of LF lines. +- The Node shell keeps a second, independent safety net: before a save it reads the real endings + from the text files on disk, 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 changed lines take the file's dominant ending. It moves endings only, + never a character of text, and if the file changed underneath while the save was running it + leaves the endings alone instead of overwriting somebody else's edit. + +The two steps were measured against each other on the same files (CRLF, LF and mixed-ending +manuscripts, each saved with and without a content change, plus an AI draft insertion): when the +engine restores the endings correctly the shell's pass produces byte-identical output in every +case but one, and in that one case it is the shell's result that keeps the untouched line's +original ending. 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. @@ -83,17 +97,21 @@ On first use the page asks for your paper root directory: any directory that con - 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. +- The package's own tests: `node --test tests/*.test.mjs` — 32 cases, all green: 16 unit cases + for the line-ending module, 8 cases for the status-code passthrough (the shell must not turn + the engine's 409/400/404 into a 502), and 8 end-to-end cases that start the vendored Python + engine and save into a copy of the sample paper. Run on Node 20.20.2, 22.23.5 and 26.7.0 — + 32/32 green on each, no case skipped. +- The line-ending round trip was measured on the vendored sample paper: a section of 678 bytes + with 11 CRLF endings came back with all 11 endings and the same text. The same section without + the CR bytes weighs 667 bytes with 0 CRLF endings — that is what a save would leave behind if + the endings were not restored. - 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. 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. + covered by unit tests, but no end-to-end run on a real Windows machine has been done; the + Windows candidate list is generated from the platform string (31 to 37 entries, depending on + which environment variables are set), not measured on Windows. ## Data & access @@ -104,10 +122,10 @@ 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`. 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. + Opening a disk also records `last_opened` in that disk's `factscribe.toml`. Putting the + original line endings back 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 diff --git a/plugins/unclemoc/factscribe/README.zh-CN.md b/plugins/unclemoc/factscribe/README.zh-CN.md index 5cad1701..a1c88320 100644 --- a/plugins/unclemoc/factscribe/README.zh-CN.md +++ b/plugins/unclemoc/factscribe/README.zh-CN.md @@ -54,12 +54,23 @@ MiniMax Code 3.1.11 起也可以直接从 Git 仓库导入:贴仓库地址、 ### 行尾保真 -保存会保留文件原来的行尾。引擎读章节用 Python 的通用换行模式(CRLF 在到达页面前就变成 -LF 了),写文件又是逐字节写回,所以没有第二道工序的话,**每保存一次整篇就被改成 LF 行尾**—— -CRLF 的稿子一编辑就把 CR 全丢了。Node 薄壳因此在保存前先从磁盘读出原文件真正的行尾, -交给引擎的正文一律是 LF 形态,引擎写完再按原风格把行尾摆回去:这次保存没碰到的行连原来的 -行尾都原样留着(混合行尾的稿子保存后仍是混合的),被改动的那几行走该文件的主导行尾,正文 -一个字都不动——只有行尾在动。保存期间文件被别处改过,就不去动行尾,不覆盖别人的改动。 +保存会保留文件原来的行尾。 + +引擎读章节用 Python 的通用换行模式(CRLF 在到达页面前就变成 LF 了),写文件又是逐字节写回, +所以没有第二道工序的话,**每保存一次整篇就被改成 LF 行尾**——CRLF 的稿子一编辑就把 CR 全丢了。 +这里有两道互相独立的工序挡着: + +- 引擎自己把行尾还原回去。它写出的每一行都沿用它替换掉的那一行的行尾;用户新输入的行按该文件的 + 主导行尾落。插进稿子里的 AI 草稿块同样按所在文件的主导行尾落——CRLF 的稿子插进去的草稿块 + 也是 CRLF,不会冒出一段 LF 行。 +- Node 薄壳还有第二道兜底:保存前先把磁盘上文本文件真正的行尾读下来,交给引擎的正文一律是 LF + 形态,引擎写完再按原风格把行尾摆回去——这次保存没碰到的行连原来的行尾都原样留着(混合行尾的 + 稿子保存后仍是混合的),被改动的那几行走该文件的主导行尾。它只动行尾,一个正文字符都不动; + 保存期间文件被别处改过,就不去动行尾,不覆盖别人的改动。 + +这两道工序在同样的文件上互相量过(CRLF/LF/混合三种稿子,各存一次与改完再存,外加插一次 AI +草稿):引擎自己把行尾还原对的时候,薄壳这一道在九组场景里有八组与它逐字节相同;剩下那一组里, +是薄壳的落盘保住了那句没被改动的行原来的行尾。 首次打开会让你填**论文根目录**:含 `factscribe.toml` 的目录会被当作论文项目,之后可在设置页改。 @@ -71,14 +82,15 @@ CRLF 的稿子一编辑就把 CR 全丢了。Node 薄壳因此在保存前先从 - 最低客户端版本: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 引擎,在样例盘副本上真存一次)。 +- 随包测试:`node --test tests/*.test.mjs` —— 32 例全绿:行尾模块 16 例单测、状态码透传 8 例 + (薄壳不能把引擎的 409/400/404 压成 502)、端到端 8 例(拉起随包 Python 引擎,在样例盘副本上 + 真存一次)。在 Node 20.20.2/22.23.5/26.7.0 上各跑一遍,均为 32/32 全绿、0 例跳过。 - 行尾往返在随包样例盘上实测过:678 字节、11 个 CRLF 的章节文件,保存后 11 个 CRLF 一个不少、 - 正文一字不差;不修的话,引擎自己那次保存会把它写成 667 字节、0 个 CRLF——CR 全丢。 + 正文一字不差;同一份文件去掉 CR 字节是 667 字节、0 个 CRLF——不还原行尾的话,保存完就是这个样子。 - **未验证**:Windows 与 Linux 宿主。包内没有平台专属二进制、Node 入口只用内置模块, 但没有在这两个平台上实跑过。Windows 上的解释器发现(`py` 启动器、版本化命令、 - 常见安装目录)有单元测试覆盖,但没有在 Windows 真机上端到端跑过;那 36 个 Windows - 候选是按平台字符串生成的,不是在 Windows 上量出来的。 + 常见安装目录)有单元测试覆盖,但没有在 Windows 真机上端到端跑过;那批 Windows 候选是按平台 + 字符串生成的(31 到 37 条,看设了哪些环境变量),不是在 Windows 上量出来的。 ## 数据与访问 diff --git a/plugins/unclemoc/factscribe/miniapp/client/app.css b/plugins/unclemoc/factscribe/miniapp/client/app.css index 0bed3fd0..495e3323 100644 --- a/plugins/unclemoc/factscribe/miniapp/client/app.css +++ b/plugins/unclemoc/factscribe/miniapp/client/app.css @@ -1599,3 +1599,41 @@ body.nav-collapsed .nav-splitter{display:none} .fi-src{flex:0 0 auto;max-width:22%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; font-size:11px;color:#9b9a96} + +/* ================================================================ + 第 ④ 步收口:引用(增/删)与图片(预览)——旧节级前端那两页搬过来的 + ================================================================ */ + +/* 项目列表页头部:装示例 与 新建 排一组 */ +.pv-head-btns .pv-new{margin-left:0} +.pv-sample{white-space:nowrap} + +/* 引用清单 */ +.cite-sum{font-size:11px;color:#6f6e69;margin:0 0 6px} +.cite-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px} +.cite-row{border:1px solid #ececeb;border-radius:7px;padding:7px 8px;background:#fff} +.cite-row.s-bad_id,.cite-row.s-duplicate{border-color:#e8c3c0;background:#fdf7f6} +.cite-line1{display:flex;align-items:center;gap:6px} +.cite-key{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11.5px;color:#2f2e2b; + overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:130px} +.cite-status{font-size:10px;color:#6f6e69;border:1px solid #e6e6e4;border-radius:999px;padding:1px 6px; + white-space:nowrap;flex:0 0 auto} +.cite-row.s-bad_id .cite-status,.cite-row.s-duplicate .cite-status{color:#8c2f22;border-color:#e8c3c0} +.cite-del{margin-left:auto;border:none;background:none;color:#9b9a96;font-size:12px;cursor:pointer;padding:0 2px; + line-height:1;flex:0 0 auto} +.cite-del:hover{color:#8c2f22} +.cite-title{font-size:12px;color:#37352f;margin-top:3px;line-height:1.45; + display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden} +.cite-meta{font-size:10.5px;color:#8f8d86;margin-top:2px} + +/* 图片清单 */ +.asset-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px} +.asset-cell{border:1px solid #ececeb;border-radius:7px;background:#fff;padding:4px;cursor:pointer; + display:flex;flex-direction:column;gap:3px;align-items:center;font-family:inherit} +.asset-cell:hover{border-color:#b8b5ac} +.asset-cell img{width:100%;height:52px;object-fit:cover;border-radius:4px;background:#f4f3f1;display:block} +.asset-name{font-size:10px;color:#6f6e69;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.asset-empty,.asset-more{font-size:11px;color:#8f8d86;margin:2px 0 0;grid-column:1/-1} +.asset-more{margin-top:4px} +.asset-view{display:flex;justify-content:center;align-items:center} +.asset-full{max-width:100%;max-height:62vh;border-radius:6px;background:#fff} diff --git a/plugins/unclemoc/factscribe/miniapp/client/app.js b/plugins/unclemoc/factscribe/miniapp/client/app.js index df736e5f..30063a68 100644 --- a/plugins/unclemoc/factscribe/miniapp/client/app.js +++ b/plugins/unclemoc/factscribe/miniapp/client/app.js @@ -281,6 +281,28 @@ const I18N = { 'confirm.ok': '确定', 'confirm.cancel': '取消', 'more.rpNote': '导入进来的都在待核对区;转正走闸,不在面板里', 'more.kbNote': '源文件只读;上传的资料才可删除', + /* 引用与图片:旧节级前端那两页搬过来的(第 ④ 步收口) */ + 'np.cite': '引用', 'np.citeAdd': '+ 加一条', 'np.assets': '图片', + 'more.citeNote': '删条目只动 bib;正文里的引用标记不跟着改', + 'more.assetNote': '盘里的图片文件;点开看大图', + 'cite.sum': '共 {total} 条:被引 {used},没被引 {unused}', + 'cite.st.ok': '可复核', 'cite.st.no_id': '缺标识', + 'cite.st.bad_id': '标识不合法', 'cite.st.unused': '没被引到', + 'cite.st.duplicate': 'key 重复', + 'cite.addT': '加一条引用', 'cite.key': '引用 key', + 'cite.title': '标题', 'cite.author': '作者', 'cite.year': '年份', + 'cite.doi': 'DOI', 'cite.arxiv': 'arXiv', 'cite.add': '加进去', + 'cite.needKey': 'key 必填', 'cite.addOk': '加好了:{key}', + 'cite.addErr': '加不上:{e}', + 'cite.delT': '删掉这条', 'cite.delTitle': '删掉这条引用?', + 'cite.delBody': '只删 bib 里的这一条;正文里的引用标记还留着。', + 'cite.delOk': '删掉了:{key}', 'cite.delErr': '删不掉:{e}', + 'cite.loadErr': '读引用清单失败:{e}', + 'asset.empty': '这个盘里没有图片文件。', + 'asset.more': '只列了前 {n} 个(盘里还有别的)。', + 'asset.loadErr': '读图片清单失败:{e}', + 'tb.sample': '装个示例', 'tb.sampleOk': '示例装好了:{p}', + 'tb.sampleErr': '装不上示例:{e}', 'vn.venue': '目标刊物 / 会议', 'vn.venuePh': '例如:ACL 2026', 'vn.deadline': '截稿日期', 'vn.save': '保存版式配置', 'vn.lockTag': '语言盘锁定', @@ -681,6 +703,28 @@ const I18N = { 'confirm.ok': 'OK', 'confirm.cancel': 'Cancel', 'more.rpNote': 'Imported reports sit in the pending-check zone; promoting them goes through the gate, not this panel.', 'more.kbNote': 'Source files are read-only; only uploaded material can be deleted.', + /* Citations and images: carried over from the old section-level front end */ + 'np.cite': 'Citations', 'np.citeAdd': '+ Add one', 'np.assets': 'Images', + 'more.citeNote': 'Deleting touches the bib only; citation marks in the text stay.', + 'more.assetNote': 'Image files in this disk; click to open.', + 'cite.sum': '{total} entries: {used} cited, {unused} uncited', + 'cite.st.ok': 'Verifiable', 'cite.st.no_id': 'No stable id', + 'cite.st.bad_id': 'Bad id', 'cite.st.unused': 'Not cited', + 'cite.st.duplicate': 'Duplicate key', + 'cite.addT': 'Add a citation', 'cite.key': 'Citation key', + 'cite.title': 'Title', 'cite.author': 'Author', 'cite.year': 'Year', + 'cite.doi': 'DOI', 'cite.arxiv': 'arXiv', 'cite.add': 'Add', + 'cite.needKey': 'The key is required', 'cite.addOk': 'Added: {key}', + 'cite.addErr': 'Could not add: {e}', + 'cite.delT': 'Delete this entry', 'cite.delTitle': 'Delete this citation?', + 'cite.delBody': 'Only this bib entry goes; citation marks in the text stay.', + 'cite.delOk': 'Deleted: {key}', 'cite.delErr': 'Could not delete: {e}', + 'cite.loadErr': 'Could not load the citation list: {e}', + 'asset.empty': 'No image files in this disk.', + 'asset.more': 'Only the first {n} are listed (there are more in the disk).', + 'asset.loadErr': 'Could not load the image list: {e}', + 'tb.sample': 'Install sample', 'tb.sampleOk': 'Sample installed: {p}', + 'tb.sampleErr': 'Could not install the sample: {e}', 'vn.venue': 'Target journal / conference', 'vn.venuePh': 'e.g. ACL 2026', 'vn.deadline': 'Deadline', 'vn.save': 'Save venue config', 'vn.lockTag': 'Language lock', @@ -837,6 +881,8 @@ const state = { reports: { list: [], loading: false, error: '', detail: null }, // 段四:实验报告 kb: { files: [], loading: false, error: '', current: '', detail: null }, // 段六:知识库 venue: { data: null, loading: false, error: '', msg: '' }, // 段六:版式 + cites: { data: null, loading: false, error: '' }, // 引用清单(旧节级前端那页搬过来的) + assets: { data: null, loading: false, error: '' }, // 盘里的图片清单(同上) wz: { step: 1, file: '', fileSize: 0, files: [], rows: [], failed: [], suggested: [], sha: '', busy: false, parseError: '' }, // 段四:导入向导 af: null, // 追加事实表单(两步:挑产物 → 说清这条数字 + 落哪本账) renameTarget: null, // 改章节名:正在改的那一节 {file, block, sha} @@ -975,6 +1021,9 @@ function applyI18n() { renderReports(); renderKb(); renderVenue(); + // 引用与图片的文案也跟语言走(面板里的字是 t() 现填的)。 + renderCitations(); + renderAssets(); // v4:模型下拉里的文案(来源标注、思考等级)也要跟着语言重画。 renderAiModelSelect(); // v5:「这一轮是谁答的」徽标也跟着语言重画。 @@ -1542,6 +1591,11 @@ async function loadDisk() { await loadAbstract(); // 段六:版式配置跟着当前盘走(截稿徽标立刻可显示)。 loadVenue(); + // 引用与图片也跟着当前盘走(旧节级前端那两页搬过来的)。 + state.cites.data = null; + state.assets.data = null; + loadCitations(); + loadAssets(); // 段三:检查报告与机器视图跟着当前盘走(进哪篇管哪篇)。 resetReportState(); state.rerun = null; @@ -4087,6 +4141,8 @@ function switchNavPane(name) { loadReports(); loadKb(); loadVenue(); + loadCitations(); + loadAssets(); } } @@ -4712,7 +4768,197 @@ function updateDeadlineBadge() { btn.classList.add('has-due'); } +/* ------------------------------------------------- 引用增删(旧节级前端那页搬过来的) */ + +/* 引用与图片都跟着当前盘走(进哪篇管哪篇)。 */ +function diskCitePath(suffix) { + const project = state.project; + const disk = currentDisk(); + if (!project || !disk) return null; + return `/api/disk/${encodeURIComponent(project.id)}/${encodeURIComponent(disk.id)}${suffix || ''}`; +} + +function renderCitations() { + const list = $('#citeList'); + const sum = $('#citeSum'); + if (!list) return; + const data = state.cites.data; + if (!data) { + list.innerHTML = ''; + if (sum) sum.textContent = state.cites.error || ''; + return; + } + if (sum) { + sum.textContent = t('cite.sum', { + total: data.total || 0, used: data.used || 0, unused: data.unused || 0, + }); + } + const entries = data.entries || []; + list.innerHTML = entries.map((row) => { + const status = String(row.status || 'ok'); + const meta = [row.author, row.year, row.doi || row.arxiv].filter(Boolean).join(' · '); + return `
  • +
    + ${esc(row.key || '')} + ${esc(t('cite.st.' + status))} + +
    +
    ${esc(row.title || '')}
    + ${meta ? `
    ${esc(meta)}
    ` : ''} +
  • `; + }).join(''); +} + +async function loadCitations() { + const url = diskCitePath('/citations'); + if (!url) { state.cites.data = null; renderCitations(); return; } + state.cites.loading = true; + try { + const data = await getJSON(url); + state.cites.data = data; + state.cites.error = ''; + } catch (err) { + state.cites.data = null; + state.cites.error = t('cite.loadErr', { e: (err && err.message) || String(err) }); + } finally { + state.cites.loading = false; + renderCitations(); + } +} + +function openCiteForm() { + const modal = $('#modalCite'); + if (!modal) return; + ['ctKey', 'ctTitle', 'ctAuthor', 'ctYear', 'ctDoi', 'ctArxiv'].forEach((id) => { + const el = $('#' + id); + if (el) el.value = ''; + }); + modal.hidden = false; +} + +function closeCiteForm() { + const modal = $('#modalCite'); + if (modal) modal.hidden = true; +} + +async function addCitation() { + const url = diskCitePath('/citations/add'); + if (!url) return; + const key = (($('#ctKey') || {}).value || '').trim(); + if (!key) { toast(t('cite.needKey')); return; } + const body = { + key: key, + title: (($('#ctTitle') || {}).value || '').trim(), + author: (($('#ctAuthor') || {}).value || '').trim(), + year: (($('#ctYear') || {}).value || '').trim(), + doi: (($('#ctDoi') || {}).value || '').trim(), + arxiv: (($('#ctArxiv') || {}).value || '').trim(), + }; + try { + await postJSON(url, body); + closeCiteForm(); + toast(t('cite.addOk', { key: key })); + await loadCitations(); + } catch (err) { + toast(t('cite.addErr', { e: (err && err.message) || String(err) })); + } +} + +async function deleteCitation(key) { + const url = diskCitePath('/citations/delete'); + if (!url || !key) return; + const ok = await askConfirm({ + title: t('cite.delTitle'), + body: t('cite.delBody'), + okLabel: t('confirm.ok'), + }); + if (!ok) return; + try { + await postJSON(url, { key: key }); + toast(t('cite.delOk', { key: key })); + await loadCitations(); + } catch (err) { + toast(t('cite.delErr', { e: (err && err.message) || String(err) })); + } +} + /* 首页预览:走现有的渲染 PDF 链路(真渲染,出预览)。 */ +/* ------------------------------------------------- 图片预览(旧节级前端那条只读通道搬过来的) */ + +function assetUrl(rel) { + const base = diskCitePath('/asset'); + if (!base) return ''; + return base + '?path=' + encodeURIComponent(String(rel || '')); +} + +function renderAssets() { + const grid = $('#assetGrid'); + if (!grid) return; + const data = state.assets.data; + if (!data) { + grid.innerHTML = ''; + return; + } + const items = data.assets || []; + if (!items.length) { + grid.innerHTML = '

    ' + esc(t('asset.empty')) + '

    '; + return; + } + const cells = items.map((item) => { + const rel = String(item.path || ''); + return ''; + }).join(''); + const more = data.truncated + ? '

    ' + esc(t('asset.more', { n: items.length })) + '

    ' + : ''; + grid.innerHTML = cells + more; +} + +async function loadAssets() { + const url = diskCitePath('/assets'); + if (!url) { state.assets.data = null; renderAssets(); return; } + state.assets.loading = true; + try { + const data = await getJSON(url); + state.assets.data = data; + state.assets.error = ''; + } catch (err) { + state.assets.data = null; + state.assets.error = t('asset.loadErr', { e: (err && err.message) || String(err) }); + } finally { + state.assets.loading = false; + renderAssets(); + } +} + +function openAsset(rel) { + const modal = $('#modalAsset'); + const body = $('#asBody'); + const title = $('#asTitle'); + if (!modal || !body) return; + if (title) title.textContent = String(rel || ''); + body.innerHTML = '' + esc(rel || '') + ''; + modal.hidden = false; +} + +/* ------------------------------------------------- 内置示例(装到工作根下面) */ + +async function installSample() { + const btn = $('#goSample'); + if (btn) btn.disabled = true; + try { + const data = await postJSON('/api/samples/guide', { reset: false }); + toast(t('tb.sampleOk', { p: data.path || '' })); + await loadProjects(); + } catch (err) { + toast(t('tb.sampleErr', { e: (err && err.message) || String(err) })); + } finally { + if (btn) btn.disabled = false; + } +} + /* ---------------------------------------------------------------- 段六:选刊指南 */ const VENUE_GUIDE_KEYS = [ @@ -5532,6 +5778,24 @@ function bind() { // 段六:知识库上传 $('#npKbUploadBtn').addEventListener('click', () => $('#npKbUpload').click()); $('#npKbUpload').addEventListener('change', uploadKbFile); + // 引用增删(旧节级前端那页搬过来的) + $('#npCiteAddBtn').addEventListener('click', openCiteForm); + $('#ctCancel').addEventListener('click', closeCiteForm); + $('#ctOk').addEventListener('click', addCitation); + $('#citeList').addEventListener('click', (ev) => { + const btn = ev.target.closest('button[data-key]'); + if (!btn) return; + deleteCitation(btn.dataset.key); + }); + // 图片预览 + $('#assetGrid').addEventListener('click', (ev) => { + const btn = ev.target.closest('button[data-path]'); + if (!btn) return; + openAsset(btn.dataset.path); + }); + $('#asClose').addEventListener('click', () => { $('#modalAsset').hidden = true; }); + // 内置示例:装到工作根下面 + $('#goSample').addEventListener('click', installSample); // 段六:版式(存配置 + 首页预览 + 选刊指南) $('#vnSave').addEventListener('click', saveVenueConfig); $('#npVenueGuideBtn').addEventListener('click', openVenueGuide); diff --git a/plugins/unclemoc/factscribe/miniapp/client/index.html b/plugins/unclemoc/factscribe/miniapp/client/index.html index 58d60193..4ab523f5 100644 --- a/plugins/unclemoc/factscribe/miniapp/client/index.html +++ b/plugins/unclemoc/factscribe/miniapp/client/index.html @@ -65,7 +65,11 @@

    论文项目

    打开一篇论文继续写,或新建一个项目。

    - +
    + + + +
    + + +
    +
    + 引用 + +
    +

    删条目只动 bib;正文里的引用标记不跟着改

    +
    +
      +
      + + +
      +
      + 图片 +
      +

      盘里的图片文件;点开看大图

      +
      +
      @@ -718,6 +742,40 @@

      —

      + + + + + + diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/audit.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/audit.py index ff28c665..0a549be8 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/audit.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/audit.py @@ -15,7 +15,8 @@ unused_bib_entries, valid_stable_id) from .checks import aggregate_exit from .config import (Config, ConfigError, _glob_paths, _read_text, - all_tex_files, facts_digest, git_commit, load_toml) + all_tex_files, facts_digest, git_commit, load_toml, + outside_closure_note, outside_facts_note) from .constants import (CONFIDENCE_OK, EXIT_INTEGRITY, KINDS_OK, SEV_INFO, SEV_RED, SEV_YELLOW, VERSION) from .evidence import CHANGED_CODE, UNFROZEN_CODE, lock_check, unfrozen_info @@ -29,6 +30,7 @@ from .texscan import (_balanced, _blank, _extract_numbers, _merge_number_units, has_auditable_content, scan_tex, sentence_index, sentence_spans, structural_whitelist) +from .textio import read_text_exact, split_lines, to_lf # -------------------------------------------------------------------------- # 问题单 @@ -522,8 +524,13 @@ def verify_sources(cfg: Config, facts: list[Fact]) -> tuple[list[Issue], list[Is continue bad = _source_rel_ok(src) if bad: - red.append(Issue(bad, "fact %r 的 source 必须是相对路径(不许 URL/绝对路径/%s):%s" - % (f.id, ".. 越界" if ".." in Path(src).parts else "绝对路径", src), + # 规则表里「不许 URL/绝对路径」已经说全了;只有 .. 越界这一种 + # 另外要点名,别把「绝对路径」说两遍。 + rules = "不许 URL/绝对路径" + if ".." in Path(src).parts: + rules += "/.. 越界" + red.append(Issue(bad, "fact %r 的 source 必须是相对路径(%s):%s" + % (f.id, rules, src), location=loc, token=f.id, message_key=finding_key(bad), params={"fact": repr(f.id), "src": src})) @@ -778,13 +785,48 @@ def _report_issues(cfg: Config, facts: list[Fact]) -> list[Issue]: return out +def _facts_outside_issues(cfg: Config) -> list[Issue]: + """事实账侧的两类信任根缺口(红,exit 5)。 + + - FACT_FILE_OUTSIDE_PROJECT:账文件的真实目标越出项目根。账本不收它, + 那些事实没进审计——审计拿不到项目外的数字当账,信任根被突破。 + - FACT_FILE_UNRESOLVED:账文件的软链成环或断链,真实目标不可解,内容 + 不可知。同样没进审计(覆盖缺口)。 + + 两条都不许静默:静默读入=fail-open,静默丢弃=把缺口盖住。 + """ + out: list[Issue] = [] + for rel, target in getattr(cfg, "outside_facts", []): + out.append(Issue( + "FACT_FILE_OUTSIDE_PROJECT", + "事实账文件 %r 是指向项目外的软链(真实目标 %s)——账本不收它," + "这些事实没进审计(信任根被突破)" % (rel, target), + location=rel, exit_code=EXIT_INTEGRITY, + params={"rel": repr(rel), "target": str(target)})) + for rel, why in getattr(cfg, "unresolved_facts", []): + out.append(Issue( + "FACT_FILE_UNRESOLVED", + "事实账文件 %r 的软链不可解(%s)——账本不收它," + "这些事实没进审计" % (rel, why), + location=rel, exit_code=EXIT_INTEGRITY, + params={"rel": repr(rel), "why": str(why)})) + return out + + + + def run_check(cfg: Config, facts: list[Fact]): issues: list[Issue] = [] warnings: list[Issue] = [] conflicts: list[dict] = [] - if not facts: + # 空账有两种:真没账(配置错,exit 2);或账文件是越界/不可解的软链、 + # 被账本拒收(红,exit 5,见 _facts_outside_issues)。后者不许在这里 + # 改写成「空账」——那是两回事,混成一个码就把信任根缺口盖住了。 + if not facts and not getattr(cfg, "outside_facts", []) \ + and not getattr(cfg, "unresolved_facts", []): raise ConfigError("facts 为空(%s 没匹配到任何 fact)——空账不算通过" % cfg.facts_glob) + issues += _facts_outside_issues(cfg) red_src, yellow_src = verify_sources(cfg, facts) issues += red_src @@ -989,12 +1031,20 @@ 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 不丢),分析层按行做事; - # 归一的是内存副本,磁盘字节不动。 + # 分析入口归一行尾:读盘侧按原样读(CRLF 不丢),分析层按行做事, + # 归一的是内存副本,磁盘字节不动。归一后与「通用换行翻译」的旧行为 + # 逐字节一致(发现条数、行号、正则命中都不漂)。 sections = [(rel, to_lf(text)) for rel, text in sections] - if not facts: + # 空账有两种:真没账(配置错,exit 2);或账文件是越界/不可解的软链、 + # 被账本拒收(红,exit 5,见 _facts_outside_issues)。后者不许在这里 + # 改写成「空账」——那是两回事,混成一个码就把信任根缺口盖住了。 + if not facts and not getattr(cfg, "outside_facts", []) \ + and not getattr(cfg, "unresolved_facts", []): raise ConfigError("facts 为空(%s 没匹配到任何 fact)——空账不算通过" % cfg.facts_glob) - if not sections: + # 空闭包有两种:真没正文(exit 2);或正文是越界软链、被记账挡在闭包外 + # (exit 5,INPUT_OUTSIDE_PROJECT)。后者由下面的越界记账判红,不许在这里 + # 改写成「没正文」——那是两回事,混成一个码就把覆盖缺口盖住了。 + if not sections and not outside_closure_note(cfg): raise ConfigError("sections 为空(%s 没匹配到任何 .tex)——没正文不算通过" % cfg.sections_glob) @@ -1002,6 +1052,9 @@ def run_audit(cfg: Config, facts: list[Fact], sections: list[tuple[str, str]], yellow: list[Issue] = [] hints: list[Issue] = [] + # R-04:账文件越出项目根/软链不可解——那些事实没进审计(红,exit 5)。 + red += _facts_outside_issues(cfg) + red_src, yellow_src = verify_sources(cfg, facts) red += red_src yellow += yellow_src @@ -1113,7 +1166,31 @@ def _ledger_add(rel: str, fid: str, unit: dict) -> None: "\\input 目标 %r 不存在(%s:%s)——闭包展开失败," "这一段可能整体没进审计(R-05)" % (ref, src_rel, line), location="%s:%s" % (src_rel, line), token=ref, - exit_code=EXIT_INTEGRITY, params={"ref": repr(ref), "src_rel": str(src_rel), "line": str(line)})) + exit_code=EXIT_INTEGRITY, + params={"ref": repr(ref), "src_rel": str(src_rel), + "line": str(line)})) + # R-05:目标存在但解析后越出项目根(\input{../shared/x.tex} 或绝对路径) + # ——闭包不收它,这一段同样没进审计。此前静默丢弃=fail-open(audit 判绿), + # 现在按 SPEC-V3.0 码表判红 INPUT_OUTSIDE_PROJECT(exit 5)。 + for src_rel, ref, line in getattr(cfg, "outside_inputs", []): + # line=0:不是 \input 声明越界,而是**闭包起点本身**越界(章节软链 + # 指向项目外)。两类判红同一个码,但文案要说清是哪一种。 + if line: + msg = ("\\input 目标 %r 越出项目根(%s:%s)——闭包不收它," + "这一段可能整体没进审计(R-05)" % (ref, src_rel, line)) + loc = "%s:%s" % (src_rel, line) + else: + msg = ("闭包起点 %s 是软链,越出项目根(目标 %r)——闭包不收它," + "这一段可能整体没进审计(R-05)" % (src_rel, ref)) + loc = str(src_rel) + red.append(Issue( + "INPUT_OUTSIDE_PROJECT", msg, + location=loc, token=ref, + exit_code=EXIT_INTEGRITY, + message_key=("finding.INPUT_OUTSIDE_PROJECT.start" if not line + else "finding.INPUT_OUTSIDE_PROJECT"), + params={"ref": repr(ref), "src_rel": str(src_rel), + "line": str(line)})) # R-05(v1.3):目标含宏/#/嵌套花括号或为空——静态审计无法确定它拉进 # 哪个文件;覆盖不了就判红,不许静默跳过(fail-closed)。 for src_rel, ref, line in getattr(cfg, "dynamic_inputs", []): diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/brief.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/brief.py index edd07667..9687ec05 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/brief.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/brief.py @@ -23,7 +23,8 @@ from pathlib import Path from .config import (Config, ConfigError, load_config, load_facts, - load_sections, section_budget, section_evidence) + load_sections, outside_closure_note, outside_facts_note, + section_budget, section_evidence) from .evidence import suggest_evidence from .style import _headings # 复用既有标题抽取,不另写一套 from .terms import Term, load_glossary @@ -239,14 +240,21 @@ def build_brief(project: Path | str, section: str | None = None) -> Brief: facts = load_facts(cfg) if not facts: + # 空账有两种:真没账(配置错,exit 2);或账文件是越界/不可解的软链、 + # 被账本拒收(信任根缺口,exit 5)。后者要说清是哪一种,不许混。 + note = outside_facts_note(cfg) + if note: + raise ConfigError(note) raise ConfigError( "facts 为空(%s 没匹配到任何 fact)——没有可用主张与数字," "简报无从生成;请先补账。" % cfg.facts_glob) - sections = load_sections(cfg) - sections = [(rel, to_lf(text)) for rel, text in sections] + sections = [(rel, to_lf(text)) for rel, text in load_sections(cfg)] rows = build_sections(cfg, sections) if not rows: + note = outside_closure_note(cfg) + if note: + raise ConfigError(note) raise ConfigError( "sections 为空(%s 没匹配到任何节文件)——没有可写的节,简报无从生成。" % cfg.sections_glob) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/buildpdf.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/buildpdf.py index f020acf5..432c07f7 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 .safepath import guard_project_write from .textio import read_text_exact, write_text_exact TIMEOUT_SECONDS = 600 @@ -160,6 +161,19 @@ def _is_font_error(output: str) -> bool: return any(marker in lowered for marker in FONT_ERROR_MARKERS) +def _write_font_patch(root: Path, root_tex: str, target: Path, + patched: str) -> None: + """把字体补丁写进构建副本:落点不许落在项目外。 + + 入口文件(`root_tex`)若是软链指到项目外,构建目录里的副本原样保留这条 + 软链(`copytree(symlinks=True)`),补丁就会跟着软链写到项目外去—— + 这种情况拒绝写,不落盘。 + """ + guard_project_write(root, root / root_tex, what="构建补丁", rel=root_tex) + # newline="":临时副本与源文件逐字节对应(不引入 CRLF 翻译)。 + write_text_exact(target, patched) + + def auto_build(root: Path, output: str = "main.pdf", engine: str = "tectonic", cjk_font: str | None = None, keep_temp: bool = False, @@ -239,8 +253,9 @@ def auto_build(root: Path, output: str = "main.pdf", info["font_source"] = "system" info["cjk_font"] = str(font) mode = "temp-cjk-font" - # newline="":临时副本与源文件逐字节对应(不引入 CRLF 翻译)。 - write_text_exact(target, patched) + # 写侧落点闸:入口文件若是软链指到项目外,构建目录里的副本原样 + # 保留这条软链,打字体补丁就写到项目外去了——不许(拒绝,不写)。 + _write_font_patch(root, root_tex, 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 31d6ec04..854916ba 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/bundle.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/bundle.py @@ -261,13 +261,15 @@ class Closure: files: list = field(default_factory=list) # 闭包内源文件(项目内相对路径) missing: list = field(default_factory=list) # 悬空 \input/\include dynamic: list = field(default_factory=list) # 无法静态解析的目标 + outside: list = field(default_factory=list) # 存在但越出项目根的目标(闭包不收) root_tex: str = "" cfg: Config = None # 闭包口径下的 cfg 副本 def as_dict(self) -> dict: return {"root_tex": self.root_tex, "files": list(self.files), "missing": [list(x) for x in self.missing], - "dynamic": [list(x) for x in self.dynamic]} + "dynamic": [list(x) for x in self.dynamic], + "outside": [list(x) for x in self.outside]} def collect_closure(cfg: Config) -> Closure: @@ -289,6 +291,7 @@ def collect_closure(cfg: Config) -> Closure: files=sorted(rel for rel, _ in sections), missing=[tuple(x) for x in getattr(scoped, "missing_inputs", [])], dynamic=[tuple(x) for x in getattr(scoped, "dynamic_inputs", [])], + outside=[tuple(x) for x in getattr(scoped, "outside_inputs", [])], root_tex=root_tex, cfg=scoped, ) @@ -334,6 +337,17 @@ def _closure_item(closure: Closure) -> GateItem: % (src, line, ref) for src, ref, line in closure.dynamic) return GateItem(GATE_CLOSURE, "闭包完整(无悬空 \\input/\\include)", STATUS_FAIL, detail) + if closure.outside: + def _outside_detail(src: str, ref: str, line) -> str: + # line=0:不是 \input 声明越界,而是闭包起点(章节软链)越界。 + if line: + return ("越出项目根的目标:%s:%s → %s(目标存在但闭包不收,覆盖缺口)" + % (src, line, ref)) + return ("闭包起点是软链,越出项目根:%s → %s(目标存在但闭包不收,覆盖缺口)" + % (src, ref)) + detail = ";".join(_outside_detail(*x) for x in closure.outside) + return GateItem(GATE_CLOSURE, "闭包完整(无悬空 \\input/\\include)", + STATUS_FAIL, detail) if not closure.files: return GateItem(GATE_CLOSURE, "闭包完整(无悬空 \\input/\\include)", STATUS_FAIL, "闭包为空:项目里没有 .tex 源文件") diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/checks.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/checks.py index b6314b78..f762dc96 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/checks.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/checks.py @@ -521,7 +521,8 @@ def run_packages(cfg: Config, facts, sections, resolve: bool = False): 只发生在槽路径:每条发现多 `domain` 键(DomainIssue.as_dict), summary 末尾多 `by_domain` 计数(§3.2 只增键)。 """ - # 分析入口归一行尾(读盘侧按原样读,CRLF 不丢):归一的是内存副本。 + # 分析入口归一行尾:读盘侧按原样读(CRLF 不丢),分析层按行做事; + # 归一的是内存副本,磁盘字节不动。 sections = [(rel, to_lf(text)) for rel, text in sections] packages = resolve_packages(cfg) red, yellow, hints = [], [], [] diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citations.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citations.py index 333cda0d..b124d137 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citations.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citations.py @@ -64,12 +64,50 @@ def stable_id(self): return None, "" +def _rel_under_root(path: Path, root: Path) -> str | None: + """`path` 在项目根下的相对路径;对不上就是 `None`。 + + 同一个项目根有两种拼法:解析软链前(`/var/...`、`/tmp/...`)与 + 解析软链后(`/private/var/...`)。调用方给的 `root` 与 `path` 落在 + 哪一边不一定一致——**同一个项目的两种拼法不该让相对路径算不出来**, + 所以两种拼法都试一遍。 + + 两种都对不上,才是真越出项目根。 + """ + bases = [Path(root)] + try: + bases.append(Path(root).resolve()) + except OSError: + pass + for base in bases: + try: + return path.relative_to(base).as_posix() + except ValueError: + continue + # path 自己可能带软链(真实位置在别处):再拿解析后的 path 比一次。 + try: + resolved = path.resolve() + except OSError: + return None + for base in bases: + try: + return resolved.relative_to(base).as_posix() + except ValueError: + continue + return None + + def parse_bib(path: Path, root: Path) -> list[BibEntry]: try: text = read_text_exact(path) except OSError as exc: raise ConfigError("读不了参考文献 %s:%s" % (path, exc)) - rel = path.relative_to(root).as_posix() + rel = _rel_under_root(path, root) + if rel is None: + # 不在项目根内:不再让 ValueError 裸崩穿透到调用方,按本模块 + # 既有的错误类型收成 ConfigError(调用方只需要判一种错)。 + raise ConfigError("参考文献不在项目根内:%s(项目根:%s)" + % (path, root)) macros = {} for sm in _STRING_RE.finditer(text): macros[sm.group(1).lower()] = " ".join((sm.group(2) or sm.group(3) or "").split()) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeedit.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeedit.py index eed8dcaa..a58d3bc2 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeedit.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeedit.py @@ -20,7 +20,7 @@ import re from pathlib import Path, PurePosixPath -from .citeview import _bib_paths, _tex_sources +from .citeview import _bib_paths, _tex_sources, inside_root, project_root from .citations import parse_bib from .config import ConfigError, load_config from .textio import read_text_exact, write_text_exact @@ -93,14 +93,20 @@ def _write_atomic(path: Path, text: str) -> None: def _project_bib(cfg) -> Path: - """项目自己的 bib 文件(配置里的 `bib`)。越出项目根一律拒。""" + """项目自己的 bib 文件(配置里的 `bib`)。越出项目根一律拒。 + + 口径与读侧 `citeview.inside_root()` 共用一份:写侧拒、读侧丢, + 但「在不在项目内」的判定规则只有一份,两侧不会各说各话。 + """ rel = str(getattr(cfg, "bib", "") or "refs.bib").strip() pure = PurePosixPath(rel.replace("\\", "/")) if pure.is_absolute() or any(part == ".." for part in pure.parts): raise ConfigError("配置里的 bib 必须是项目内的相对路径:%s" % rel, code="BIB_PATH_ESCAPE") - root = cfg.root.resolve() - target = root.joinpath(*[p for p in pure.parts if p not in ("", ".")]) + root = project_root(cfg) + target = inside_root(root, rel) + if target is None: + raise ConfigError("bib 越出项目根:%s" % rel, code="BIB_PATH_ESCAPE") try: target.resolve().relative_to(root) except ValueError: @@ -148,7 +154,7 @@ def citation_add_data(project: Path | str, body: dict, raise ConfigError("请求体必须是 JSON 对象", code="CITATION_INVALID") key = _clean_key(body.get("key")) cfg = load_config(Path(project)) - root = cfg.root.resolve() + root = project_root(cfg) # key 已存在 → 409。查的是整个 bib 集合:加到 refs.bib 里撞上 extra.bib # 的同名 key,一样是重复。 @@ -192,7 +198,7 @@ def citation_delete_data(project: Path | str, body: dict, raise ConfigError("请求体必须是 JSON 对象", code="CITATION_INVALID") key = _clean_key(body.get("key")) cfg = load_config(Path(project)) - root = cfg.root.resolve() + root = project_root(cfg) # 定位:parse_bib 给出每条的行范围(line..end)。 hits = [] diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeview.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeview.py index 8e3f7f93..7afe7c9f 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeview.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/citeview.py @@ -31,9 +31,8 @@ """ from __future__ import annotations -import os import re -from pathlib import Path +from pathlib import Path, PurePosixPath from .citations import parse_bib, valid_stable_id from .config import (ConfigError, _glob_paths, load_config, load_sections) @@ -95,13 +94,63 @@ def _tex_sources(cfg) -> dict: return out +def project_root(cfg) -> Path: + """项目根的**唯一口径**:`resolve()`(解析软链)。 + + 为什么必须是 resolve():同一个项目可能有两条路径——macOS 的 + `/tmp` → `/private/tmp`、Windows 的映射盘/短路径。写侧 + (`citeedit.py`)与产品路径(`serve.py` 建服时)都用 `resolve()`, + 读侧再用 `normpath()` 就会对不上:`Path.relative_to()` 直接抛 + `ValueError`,库层调用直接崩(不是 HTTP 路径,HTTP 那边被建服时的 + resolve() 挡住了,所以只在直接调库时炸)。 + + 口径统一到 resolve() 之后,读写两侧算出来的根是同一个,越界判定也 + 是同一套规则。 + """ + return Path(cfg.root).resolve() + + +def inside_root(root: Path, rel: str) -> Path | None: + """相对路径 → 项目根内的绝对路径;越出项目根 → `None`。 + + 判定规则(读侧 `_bib_paths` 与写侧 `_project_bib` 共用): + + * 绝对路径 → 越界; + * `..` 越过根 → 越界(`a/../b` 这种没越界的按词法折叠,不算越界); + * 其余按词法拼到根下。 + + 读侧遇到越界就丢掉这条 bib;写侧遇到越界就拒(`ConfigError`)。 + **规则是同一个**,所以两侧对「哪些路径在项目内」的看法一致。 + """ + raw = str(rel or "").strip().replace("\\", "/") + if not raw: + return None + pure = PurePosixPath(raw) + if pure.is_absolute(): + return None + parts: list[str] = [] + for part in pure.parts: + if part in ("", "."): + continue + if part == "..": + if not parts: + return None # 越出项目根 + parts.pop() + continue + parts.append(part) + if not parts: + return None + return root.joinpath(*parts) + + def _bib_paths(cfg, texs: dict) -> list: """bib 文件集合:配置里的 bib + 正文 `\\bibliography{}` 提到的。 - 路径一律按项目根解析;越界(`..`、绝对路径)与不存在的文件直接丢掉。 + 路径一律按**解析后的**项目根拼(口径见 `project_root()`);越界 + (`..`、绝对路径)与不存在的文件直接丢掉。 返回 [(相对路径, 绝对路径), …],按相对路径排序。 """ - root = Path(os.path.normpath(str(cfg.root))) + root = project_root(cfg) found: dict = {} def add(raw: str) -> None: @@ -110,13 +159,19 @@ def add(raw: str) -> None: return if not rel.lower().endswith(".bib"): rel += ".bib" - path = Path(os.path.normpath(str(root / rel))) + path = inside_root(root, rel) + if path is None: + return # 越出项目根:不许读 try: key = path.relative_to(root).as_posix() except ValueError: - return # 越出项目根:不许读 + return if not path.is_file(): return + try: + path.resolve().relative_to(root) + except (OSError, ValueError): + return # 软链指向项目外:不许读(与写侧 _project_bib 同一口径) found[key] = path add(str(getattr(cfg, "bib", "") or "")) @@ -207,7 +262,7 @@ def citations_data(project) -> dict: rows: list = [] by_key: dict = {} files: list = [] - root = Path(os.path.normpath(str(cfg.root))) + root = project_root(cfg) for rel, path in _bib_paths(cfg, texs): entries = parse_bib(path, root) keys = [] diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py index 28aaa23b..4952a023 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/cli.py @@ -28,6 +28,7 @@ from .config import (Config, ConfigError, load_config, load_facts, load_sections) from .console import safe_stdio +from .safepath import WriteRefused, guard_facts_write, guard_project_write from .constants import (EXIT_CONFIG, EXIT_INTERNAL, EXIT_OK, EXIT_RED, EXIT_YELLOW, VERSION) from .doctor import collect as collect_doctor @@ -55,6 +56,8 @@ from .review import payload as review_payload from .review import render_human as render_review from .review import run_review +from .safepath import (WriteRefused, guard_facts_write, + guard_project_write) from .scaffold import add_fact, init_project from .serve import LOOPBACK_HOSTS, create_server from .style import (DISCLAIMER, STAGE_DRAFT, STAGE_VALUES, analyze, @@ -187,11 +190,15 @@ def build_parser() -> argparse.ArgumentParser: sp.add_argument("--allow-build", dest="allow_build", action="store_true", help="允许 POST /api/build 编译 PDF;会执行 project.build") sp.add_argument("--ui", action="store_true", - help="同时在这个端口提供本地工作台页面(GET /)") + help="同时在这个端口提供页面(GET /):旧节级网页前端已按第 ④ 步" + "废弃,这条闸留给集成件自带的页面(如 legal 集成件);" + "产品前端是段落级工作台 factscribe workbench") sp.add_argument("--dev", action="store_true", help="开发模式:页面把 MiniApp 专属区(AI、启动)也显示出来,只做界面预览") sp.add_argument("--no-token", dest="no_token", action="store_true", - help="不要求 token(只允许本监听地址的同源请求;个人机器可用)") + help="不要求 token(只靠同源检查:带 Origin 的请求必须是本监听" + "地址,否则 403 CROSS_ORIGIN;不带 Origin 的请求一律放行" + "——命令行与 MiniApp 代理走这条;个人机器可用)") sp.add_argument("--no-open", dest="no_open", action="store_true", help="网页模式不自动打开浏览器") sp.add_argument("--json", action="store_true", @@ -252,34 +259,6 @@ def build_parser() -> argparse.ArgumentParser: sp.add_argument("--allow-write", dest="allow_write", action="store_true", help="开放 write_section / add_fact(默认只读)") - sp = sub.add_parser( - "web", - help="本地工作台页面:serve + 三栏编辑界面(只绑回环)", - description="等同 serve --ui:起本地 HTTP 服务,并在 GET / 提供" - "左章节 / 中正文 / 右证据与审计的页面。默认只读;" - "--allow-write 才开放改章节、追加事实与证据冻结。") - sp.add_argument("project", nargs="?", default=None, - help="项目目录(省略=只起服务,在页面里选论文项目)") - sp.add_argument("--host", default="127.0.0.1", - choices=sorted(LOOPBACK_HOSTS), - help="监听地址(只允许回环;默认 127.0.0.1)") - sp.add_argument("--port", type=int, default=0, - help="端口(默认 0=让系统分配)") - sp.add_argument("--token", default=None, - help="固定 token(默认每次随机生成)") - sp.add_argument("--allow-write", dest="allow_write", action="store_true", - help="打开写接口(章节/事实/证据)") - sp.add_argument("--allow-build", dest="allow_build", action="store_true", - help="允许编译 PDF(会执行 project.build)") - sp.add_argument("--dev", action="store_true", - help="开发模式:页面把 MiniApp 专属区(AI、启动)也显示出来") - sp.add_argument("--no-token", dest="no_token", action="store_true", - help="不要求 token(只允许本监听地址的同源请求)") - sp.add_argument("--no-open", dest="no_open", action="store_true", - help="不自动打开浏览器") - sp.add_argument("--json", action="store_true", - help="启动行只出 JSON(服务仍阻塞)") - for name, help_text in ( ("check", "校验事实账:id/sha256/人签清单/expr 算术/冲突"), ("audit", "核心:内联绑定 + 数字回账 + 引用落稳定标识 + 覆盖报告"), @@ -792,16 +771,20 @@ def cmd_serve(args) -> int: url = "http://%s:%d" % (host, port) dev = bool(getattr(args, "dev", False)) ui_url = "" + legal_url = "" if getattr(args, "ui", False): query = ("token=" + token if token else "") if dev: query = (query + "&" if query else "") + "dev=1" ui_url = url + "/" + ("?" + query if query else "") + # 法律侧工作台页面(法律集成件自带的前端;只读档案)。 + legal_url = url + "/legal" + ("?" + query if query else "") command = "web" if getattr(args, "web", False) else "serve" if args.json: print(json.dumps({ "event": "listening", "ok": True, "command": command, "url": url, "ui": ui_url or None, + "legal_ui": legal_url or None, "token": token, "token_required": not no_token, "project": str(server.project) if server.project else None, @@ -816,6 +799,11 @@ def cmd_serve(args) -> int: print("URL:%s" % url) if ui_url: print("页面:%s" % ui_url) + print(" (旧的节级网页前端已按第 ④ 步废弃;产品前端是段落级工作台:" + "factscribe workbench --root <目录>。--ui 这条闸留给集成件" + "自带的页面。)") + if legal_url: + print("法律侧页面:%s" % legal_url) if token: print("Token:%s" % token) mode = "可写(--allow-write)" if args.allow_write else "只读" @@ -843,13 +831,6 @@ def cmd_serve(args) -> int: return EXIT_OK -def cmd_web(args) -> int: - """本地工作台页面:serve + UI。""" - args.ui = True - args.web = True - return cmd_serve(args) - - def cmd_workbench(args) -> int: """工作台网页:发现项目 → 起本地服务 → 阻塞到 Ctrl+C。""" if getattr(args, "workbench_action", None) == "new": @@ -1263,6 +1244,18 @@ def cmd_fact_import(args) -> int: if target.parent.resolve() != facts_dir.resolve(): return _report_fail(args, command, EXIT_CONFIG, rel_report, "FACTS_PATH_INVALID", "只许写 facts/ 一级,不许写子目录") + # 写侧信任根闸:账本的真实目标越出项目根就拒写——不落盘、不留半截文件。 + # 与读侧同一对码(FACT_FILE_OUTSIDE_PROJECT / FACT_FILE_UNRESOLVED, + # red / exit 5),severity 与 exit 一律不动。 + try: + target_rel = target.relative_to(cfg.root).as_posix() + except ValueError: + target_rel = target.name + try: + guard_facts_write(cfg.root, target, rel=target_rel) + except WriteRefused as exc: + return _report_fail(args, command, exc.exit_code, rel_report, + exc.code, str(exc)) header = ("# managed by factscribe fact import; report=%s digest=%s" % (rel_report, semantic_digest(report))) body = [header, ""] @@ -1677,6 +1670,9 @@ def cmd_matrix(args) -> int: sections = load_sections(cfg) text, rows = render_matrix(cfg, facts, sections) out = Path(args.out) if getattr(args, "out", None) else cfg.root / "audit" / "matrix.md" + if not getattr(args, "out", None): + # 写侧落点闸:默认落点(项目内 audit/)必须留在项目根内。 + guard_project_write(cfg.root, out, what="矩阵产物", rel="audit/matrix.md") out.parent.mkdir(parents=True, exist_ok=True) out.write_text(text, encoding="utf-8") human = "== factscribe matrix ==\n写盘:%s\n行数:%d(每行一条 fact)\n%s" % ( @@ -1692,6 +1688,9 @@ def cmd_matrix(args) -> int: def cmd_preamble(args) -> int: cfg = load_config(Path(args.project)) out = Path(args.out) if getattr(args, "out", None) else cfg.root / "audit" / "preamble.tex" + if not getattr(args, "out", None): + # 写侧落点闸:默认落点(项目内 audit/)必须留在项目根内。 + guard_project_write(cfg.root, out, what="前言产物", rel="audit/preamble.tex") out.parent.mkdir(parents=True, exist_ok=True) out.write_text(PREAMBLE_TEXT, encoding="utf-8") human = "== factscribe preamble ==\n写盘:%s\n%s" % (out, PREAMBLE_TEXT) @@ -2282,7 +2281,6 @@ def main(argv=None) -> int: "doctor": cmd_doctor, "serve": cmd_serve, "workbench": cmd_workbench, - "web": cmd_web, "mcp": cmd_mcp, "report": cmd_report, "verify-pdf": cmd_verify_pdf, "style": cmd_style, @@ -2297,8 +2295,11 @@ def main(argv=None) -> int: return handlers[args.command](args) except ConfigError as exc: code = getattr(exc, "code", "CONFIG_INVALID") + # 写盘被拒的码自带退出码(事实账越界=信任链失败 exit 5); + # 其它配置/用法错仍是 exit 2。severity 与 exit 都按码走,不改既有码。 + exit_code = getattr(exc, "exit_code", EXIT_CONFIG) if getattr(args, "json", False): - payload = _payload(args.command, "error", EXIT_CONFIG, + payload = _payload(args.command, "error", exit_code, message=str(exc)) payload["code"] = code # §8:CONFIG 类码也必须出现在 findings/issues 里,判卷器不用 @@ -2308,8 +2309,10 @@ def main(argv=None) -> int: payload["issues"] = [finding] print(json.dumps(payload, ensure_ascii=False, indent=2)) else: - print("factscribe: 配置/用法错:%s" % exc, file=sys.stderr) - return EXIT_CONFIG + label = ("配置/用法错" if exit_code == EXIT_CONFIG + else "信任链失败") + print("factscribe: %s:%s" % (label, exc), file=sys.stderr) + return exit_code except Exception as exc: # noqa: BLE001 - 内部错误必须与「有违例」分开 if getattr(args, "json", False): print(json.dumps(_payload(args.command, "error", EXIT_INTERNAL, diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/config.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/config.py index 5a0f4409..2f566f4a 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/config.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/config.py @@ -2,14 +2,19 @@ """项目声明读取:factscribe.toml、迷你 TOML、facts/sections 装载。""" from __future__ import annotations +import datetime as _dt +import errno import hashlib +import os import re from dataclasses import dataclass, field from pathlib import Path from .facts import Fact, canon_text, fact_value_keys, latex_display from .constants import SEV_INFO +from .textio import read_text_exact, to_lf from .texrules import strip_comments_and_verbatim +from .textio import read_text_exact, to_lf # -------------------------------------------------------------------------- # TOML 读写(3.11+ 用 tomllib;3.10 用内置极简解析器兜底) @@ -41,161 +46,599 @@ def __init__(self, message: str, code: str | None = None, self.params = dict(params or {}) -def _strip_toml_comment(line: str) -> str: - out = [] - quote = None - i = 0 - while i < len(line): - c = line[i] - if quote: - out.append(c) - if c == "\\" and quote == '"' and i + 1 < len(line): - out.append(line[i + 1]) - i += 2 - continue - if c == quote: - quote = None - else: - if c in "\"'": - quote = c - out.append(c) - elif c == "#": - break - else: - out.append(c) - i += 1 - return "".join(out) - - -def _split_top_level(body: str) -> list[str]: - """按顶层逗号切:顾引号,也顾 {}/[] 嵌套——内联表不当劈开。""" - items: list[str] = [] - buf: list[str] = [] - quote: str | None = None - depth = 0 - for c in body: - if quote: - buf.append(c) - if c == quote: - quote = None - elif c in "\"'": - quote = c - buf.append(c) - elif c in "[{": - depth += 1 - buf.append(c) - elif c in "]}": - depth -= 1 - buf.append(c) - elif c == "," and depth == 0: - items.append("".join(buf)) - buf = [] - else: - buf.append(c) - if "".join(buf).strip(): - items.append("".join(buf)) - return items - - -def _mini_toml_inline_table(raw: str) -> dict: - """内联表 `{ key = 值, … }`(3.11+ tomllib 本就支持;此处补齐 3.10 同形)。""" - out: dict = {} - for part in _split_top_level(raw[1:-1]): - part = part.strip() - if not part: - continue - key, sep, value = part.partition("=") - if not sep: - raise ValueError("内联表缺 key=value:%r" % raw) - out[key.strip().strip("\"'")] = _mini_toml_value(value) - return out +# -------------------------------------------------------------------------- +# 3.10 兜底 TOML 解析器(严格档) +# -------------------------------------------------------------------------- +# +# 标准库 tomllib 只在 3.11+ 有;3.10 走这份自带解析器。 +# +# 铁律(CONTRIBUTING §1「fail closed」):坏 TOML 必须报错,经既有 +# ConfigError 通道变成 exit 2;不许把坏输入当合法内容收下。 +# +# 为什么必须是严格的:同一份坏文件,3.11+ 的 tomllib 报错(拒绝), +# 3.10 的兜底若宽松收下(放行),两道闸在两种解释器上结论相反 —— +# CI 矩阵里 3.10 一条腿红、别的腿绿,audit 输出也不再跨版本一致。 +# 旧兜底正是宽松的:坏表头 `[[ref]` 被当成表名 `[ref` 收下, +# 未闭合字符串 `id = "X1` 被当裸词吞下 —— 闸门 fail-open(放行)。 +# +# 覆盖面:factscribe 契约用得到的子集 = 表、表数组、点号表名、点号键、 +# 字符串(基本/字面/多行)、数组、内联表、整数、浮点、布尔、日期时间。 +# 判据照标准库 tomllib 来:同样的写法同样收、同样拒,读出的值也相同 —— +# 3.10 与 3.11+ 必须是同一个结论(audit 输出跨版本逐字节一致)。 + +_BARE_KEY_CHARS = frozenset( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") +_TOML_WS = " \t" +# 标准库 tomllib 的空白集只有 " \t" 与换行;裸 "\r" 不算空白(判非法语句)。 +_TOML_WS_AND_NEWLINE = " \t\n" +# 控制字符口径与标准库 tomllib 同源(ASCII 0-31 与 127): +# 单行字符串与注释里除制表符外都非法;多行字符串里除制表符与换行外都非法。 +_ASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127)) +_ILLEGAL_STR_CHARS = _ASCII_CTRL - frozenset("\t") +_ILLEGAL_MULTILINE_STR_CHARS = _ASCII_CTRL - frozenset("\t\n") +_BASIC_STR_ESCAPES = { + "b": "\b", "t": "\t", "n": "\n", "f": "\f", "r": "\r", + '"': '"', "\\": "\\", +} +# 数字与日期时间的词法(照 tomllib 的正则改写)。 +_RE_NUMBER = re.compile( + r"0(?:x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*" + r"|b[01](?:_?[01])*" + r"|o[0-7](?:_?[0-7])*)" + r"|[+-]?(?:0|[1-9](?:_?[0-9])*)" + r"(?P(?:\.[0-9](?:_?[0-9])*)?(?:[eE][+-]?[0-9](?:_?[0-9])*)?)") +_RE_LOCALTIME = re.compile( + r"(?P[01][0-9]|2[0-3]):(?P[0-5][0-9]):(?P[0-5][0-9])" + r"(?:\.(?P[0-9]{1,6})[0-9]*)?") +_RE_DATETIME = re.compile( + r"(?P[0-9]{4})-(?P0[1-9]|1[0-2])-(?P0[1-9]|[12][0-9]|3[01])" + r"(?:[Tt ]" + r"(?P[01][0-9]|2[0-3]):(?P[0-5][0-9]):(?P[0-5][0-9])" + r"(?:\.(?P[0-9]{1,6})[0-9]*)?" + r"(?:(?P[Zz])|(?P[+-])(?P[01][0-9]|2[0-3]):(?P[0-5][0-9]))?" + r")?") + + +class _MiniTomlError(ValueError): + """兜底解析器拒绝坏 TOML(与标准库 tomllib 同口径:坏输入必须报错)。""" + + +def _path_frozen(frozen: set, path: tuple) -> bool: + """路径(或其任一祖先)在 frozen 里 ⇒ 那块命名空间不可再改写。""" + for f in frozen: + if path[:len(f)] == f: + return True + return False + + +def _to_datetime(match): + """把日期/时间的正则匹配读成 date/datetime/time 对象(与 tomllib 同型)。""" + year = int(match.group("year")) + month = int(match.group("month")) + day = int(match.group("day")) + if match.group("hour") is None: + return _dt.date(year, month, day) + micros = int(match.group("micros").ljust(6, "0")) if match.group("micros") else 0 + tz = None + if match.group("osign"): + sign = 1 if match.group("osign") == "+" else -1 + tz = _dt.timezone(_dt.timedelta( + hours=sign * int(match.group("ohour")), + minutes=sign * int(match.group("ominute")))) + elif match.group("zulu"): + tz = _dt.timezone.utc + return _dt.datetime(year, month, day, int(match.group("hour")), + int(match.group("minute")), int(match.group("second")), + micros, tzinfo=tz) + + +class _MiniTomlParser: + """3.10 兜底 TOML 解析器:只吃合法 TOML,坏的一律报错。 + + 规则照标准库 tomllib(CPython 的 Lib/tomllib)来:同样收、同样拒, + 读出的值也相同 —— 3.10 与 3.11+ 的闸门结论必须一致。 + """ -def _mini_toml_value(raw: str): - raw = raw.strip() - if raw.startswith('"') and raw.endswith('"') and len(raw) >= 2: - return raw[1:-1].replace('\\"', '"').replace("\\n", "\n").replace("\\\\", "\\") - if raw.startswith("'") and raw.endswith("'") and len(raw) >= 2: - return raw[1:-1] - if raw in ("true", "false"): - return raw == "true" - if raw.startswith("[") and raw.endswith("]"): - return [_mini_toml_value(x) - for x in _split_top_level(raw[1:-1]) if x.strip()] - if raw.startswith("{") and raw.endswith("}"): - return _mini_toml_inline_table(raw) - try: - if any(ch in raw for ch in ".eE") and not raw.startswith("0x"): - return float(raw) - return int(raw) - except ValueError: - return raw # 裸词,容错 + def __init__(self, text: str): + self.text = text + self.n = len(text) + self.i = 0 + self.root: dict = {} + self.header: tuple = () + # 表头显式声明过的路径(不许再声明一次) + self.explicit: set = set() + # 点号键建出的中间表:挂起,等下一条表头才生效(与 tomllib 同口径) + self.pending: set = set() + # 内联表/内联数组的路径(不可再改写) + self.frozen: set = set() + + # ---- 报错 ---- + + def fail(self, msg: str): + """抛坏 TOML 错误(带行号列号,方便定位)。""" + line = self.text.count("\n", 0, self.i) + 1 + col = self.i - self.text.rfind("\n", 0, self.i) + raise _MiniTomlError("TOML 第 %d 行第 %d 列:%s" % (line, col, msg)) + + # ---- 空白与注释 ---- + + def skip_blank(self): + """跳过空白、换行与注释(语句之间用)。""" + while self.i < self.n: + c = self.text[self.i] + if c in _TOML_WS_AND_NEWLINE: + self.i += 1 + continue + if c == "#": + self.skip_comment() + continue + return + + def skip_comment(self): + """跳过行尾注释(注释里不许出现控制字符,与 tomllib 同口径)。""" + if self.i < self.n and self.text[self.i] == "#": + while self.i < self.n and self.text[self.i] != "\n": + c = self.text[self.i] + if c in _ILLEGAL_STR_CHARS: + self.fail("注释里有非法控制字符") + self.i += 1 + + def skip_spaces(self): + """只跳同行空白(表名/键名里的点号前后允许空格)。""" + while self.i < self.n and self.text[self.i] in _TOML_WS: + self.i += 1 + + def skip_array_ws(self): + """数组里可以换行、可以带注释。""" + while True: + before = self.i + while self.i < self.n and self.text[self.i] in _TOML_WS_AND_NEWLINE: + self.i += 1 + if self.i < self.n and self.text[self.i] == "#": + self.skip_comment() + continue + if self.i == before: + return + # ---- 文档 ---- -def _needs_more(value: str) -> bool: - depth = 0 - quote = None - for c in value: - if quote: - if c == quote: - quote = None - elif c in "\"'": - quote = c - elif c in "[{": - depth += 1 - elif c in "]}": - depth -= 1 - return depth > 0 + def parse(self) -> dict: + while True: + self.skip_blank() + if self.i >= self.n: + break + if self.text[self.i] == "[": + self.parse_header() + else: + self.parse_key_value() + # 一条语句之后只许行尾空白与注释,然后必须换行或到文件尾 + self.skip_spaces() + self.skip_comment() + if self.i < self.n and self.text[self.i] != "\n": + self.fail("这条语句后面还有多余内容") + return self.root + + # ---- 表头 ---- + + def parse_header(self): + # 表头之前先把点号键挂起的标记落定(与 tomllib 同口径) + self.explicit |= self.pending + self.pending.clear() + if self.text.startswith("[[", self.i): + self.i += 2 + path = self.parse_key_path() + self.expect("]]") + self.declare_array(path) + else: + self.i += 1 + path = self.parse_key_path() + self.expect("]") + self.declare_table(path) + + def expect(self, token: str): + self.skip_spaces() + if not self.text.startswith(token, self.i): + self.fail("这里应该是 %r" % token) + self.i += len(token) + + def declare_table(self, path): + """`[表]` —— 表已经声明过、或那儿已经是个值,就报错。""" + if path in self.explicit or _path_frozen(self.frozen, path): + self.fail("不能重复声明表 %r" % (path,)) + self.explicit.add(path) + try: + self.get_or_create_nest(path) + except KeyError: + self.fail("不能覆盖已有的值") + self.header = path + + def declare_array(self, path): + """`[[表数组]]` —— 表数组可以重复声明(每次追加一个元素)。""" + if _path_frozen(self.frozen, path): + self.fail("不能改写已冻结的命名空间 %r" % (path,)) + # 重新声明时,把上一轮挂在这个路径下的标记清掉 + self.unset_all(path) + self.explicit.add(path) + try: + parent = self.get_or_create_nest(path[:-1]) + except KeyError: + self.fail("不能覆盖已有的值") + leaf = path[-1] + if leaf in parent: + existing = parent[leaf] + if not isinstance(existing, list): + self.fail("不能覆盖已有的值") + item: dict = {} + existing.append(item) + else: + item = {} + parent[leaf] = [item] + self.header = path + + # ---- 键值 ---- + + def parse_key_value(self): + path = self.parse_key_path() + self.skip_spaces() + if self.i >= self.n or self.text[self.i] != "=": + self.fail("键名后面缺 '='") + self.i += 1 + self.skip_spaces() + self.set_key_value(path, self.scan_value()) + + def set_key_value(self, path, value): + """把 `键 = 值` 写进当前表(点号键会建出中间的表)。""" + header = self.header + # 点号键的中间层不许是已显式声明过的表(那是重新定义命名空间) + for i in range(1, len(path)): + cont = header + path[:i] + if cont in self.explicit: + self.fail("不能重新定义命名空间 %r" % (cont,)) + self.pending.add(cont) + parent = header + path[:-1] + if _path_frozen(self.frozen, parent): + self.fail("不能改写已冻结的命名空间 %r" % (parent,)) + try: + nest = self.get_or_create_nest(parent) + except KeyError: + self.fail("不能覆盖已有的值") + if path[-1] in nest: + self.fail("不能覆盖已有的值(%r)" % (path[-1],)) + nest[path[-1]] = value + if isinstance(value, (dict, list)): + self.frozen.add(header + path) + + # ---- 键名 ---- + + def parse_key_path(self) -> tuple: + self.skip_spaces() + parts = [self.parse_key_part()] + while True: + self.skip_spaces() + if self.i < self.n and self.text[self.i] == ".": + self.i += 1 + self.skip_spaces() + parts.append(self.parse_key_part()) + continue + return tuple(parts) + + def parse_key_part(self) -> str: + if self.i >= self.n: + self.fail("键名缺失") + c = self.text[self.i] + if c == '"': + return self.scan_basic_string() + if c == "'": + return self.scan_literal_string() + start = self.i + while self.i < self.n and self.text[self.i] in _BARE_KEY_CHARS: + self.i += 1 + if self.i == start: + self.fail("不是合法键名(%r)" % self.text[self.i:self.i + 12]) + return self.text[start:self.i] + + # ---- 值 ---- + + def scan_value(self): + if self.i >= self.n: + self.fail("值缺失") + c = self.text[self.i] + if c == '"': + if self.text.startswith('"""', self.i): + return self.scan_multiline_basic() + return self.scan_basic_string() + if c == "'": + if self.text.startswith("'''", self.i): + return self.scan_multiline_literal() + return self.scan_literal_string() + if c == "[": + return self.scan_array() + if c == "{": + return self.scan_inline_table() + if self.text.startswith("true", self.i): + self.i += 4 + return True + if self.text.startswith("false", self.i): + self.i += 5 + return False + return self.scan_number() + + def scan_array(self): + """`[…]` —— 元素之间用逗号,可以换行、可以带注释。""" + self.i += 1 # '[' + out: list = [] + self.skip_array_ws() + if self.i < self.n and self.text[self.i] == "]": + self.i += 1 + return out + while True: + out.append(self.scan_value()) + self.skip_array_ws() + if self.i < self.n and self.text[self.i] == "]": + self.i += 1 + return out + if self.i >= self.n or self.text[self.i] != ",": + self.fail("数组没闭合") + self.i += 1 + self.skip_array_ws() + if self.i < self.n and self.text[self.i] == "]": + self.i += 1 + return out + + def scan_inline_table(self): + """`{ 键 = 值, … }` —— 同行写完,不许换行、不许尾逗号。""" + self.i += 1 # '{' + out: dict = {} + frozen: set = set() + self.skip_spaces() + if self.i < self.n and self.text[self.i] == "}": + self.i += 1 + return out + while True: + path = self.parse_key_path() + self.skip_spaces() + if self.i >= self.n or self.text[self.i] != "=": + self.fail("内联表里键名后面缺 '='") + self.i += 1 + self.skip_spaces() + value = self.scan_value() + for i in range(1, len(path)): + if _path_frozen(frozen, path[:i]): + self.fail("内联表里不能改写已冻结的命名空间 %r" % (path[:i],)) + parent = path[:-1] + if _path_frozen(frozen, parent): + self.fail("内联表里不能改写已冻结的命名空间 %r" % (parent,)) + try: + nest = out + for k in parent: + if k not in nest: + nest[k] = {} + nest = nest[k] + if not isinstance(nest, dict): + raise KeyError(k) + except KeyError: + self.fail("内联表里不能覆盖已有的值") + if path[-1] in nest: + self.fail("内联表里有重复键 %r" % (path[-1],)) + nest[path[-1]] = value + if isinstance(value, (dict, list)): + frozen.add(path) + self.skip_spaces() + if self.i < self.n and self.text[self.i] == "}": + self.i += 1 + return out + if self.i >= self.n or self.text[self.i] != ",": + self.fail("内联表没闭合") + self.i += 1 + self.skip_spaces() + + def scan_number(self): + """整数、浮点、日期时间(布尔在上面已经收掉)。""" + text = self.text + pos = self.i + m = _RE_DATETIME.match(text, pos) + if m: + try: + value = _to_datetime(m) + except ValueError: + self.fail("日期/时间不合法") + self.i = m.end() + return value + m = _RE_LOCALTIME.match(text, pos) + if m: + micros = int(m.group("micros").ljust(6, "0")) if m.group("micros") else 0 + self.i = m.end() + return _dt.time(int(m.group("hour")), int(m.group("minute")), + int(m.group("second")), micros) + m = _RE_NUMBER.match(text, pos) + if m: + self.i = m.end() + raw = m.group() + if m.group("floatpart"): + return float(raw.replace("_", "")) + return int(raw.replace("_", ""), 0) + for token in ("inf", "nan"): + if text.startswith(token, pos): + self.i = pos + len(token) + return float(token) + for token in ("+inf", "-inf", "+nan", "-nan"): + if text.startswith(token, pos): + self.i = pos + len(token) + return float(token) + self.fail("不是合法的 TOML 值") + + # ---- 字符串 ---- + + def scan_basic_string(self) -> str: + """基本字符串 `"…"`(单行;转义照 tomllib 那套)。""" + self.i += 1 # 开引号 + out: list = [] + while True: + if self.i >= self.n: + self.fail("字符串没闭合") + c = self.text[self.i] + if c == '"': + self.i += 1 + return "".join(out) + if c in _ILLEGAL_STR_CHARS: + self.fail("基本字符串里有非法控制字符" + "(不能有换行,要换行请用三引号)") + if c == "\\": + self.i += 1 + out.append(self.scan_escape()) + continue + out.append(c) + self.i += 1 + + def scan_literal_string(self) -> str: + """字面字符串 `'…'`(单行,不解释转义)。""" + self.i += 1 # 开引号 + start = self.i + while self.i < self.n: + c = self.text[self.i] + if c == "'": + value = self.text[start:self.i] + self.i += 1 + return value + if c in _ILLEGAL_STR_CHARS: + self.fail("字面字符串里有非法控制字符(不能有换行)") + self.i += 1 + self.fail("字符串没闭合") + + def scan_escape(self) -> str: + """读一个转义序列(self.i 指着反斜杠之后那个字符)。""" + if self.i >= self.n: + self.fail("转义没写完") + e = self.text[self.i] + if e in _BASIC_STR_ESCAPES: + self.i += 1 + return _BASIC_STR_ESCAPES[e] + if e in ("u", "U"): + width = 4 if e == "u" else 8 + hexs = self.text[self.i + 1:self.i + 1 + width] + if len(hexs) != width or any(c not in "0123456789abcdefABCDEF" for c in hexs): + self.fail("坏的 \\%s 转义" % e) + code = int(hexs, 16) + if not (0 <= code <= 55295 or 57344 <= code <= 1114111): + self.fail("转义出来的不是合法 Unicode 码位") + self.i += 1 + width + return chr(code) + self.fail("不认识的转义 \\%s" % e) + + def scan_multiline_basic(self) -> str: + """多行基本字符串(三引号成对的那种)。""" + self.i += 3 # 开引号 + if self.i < self.n and self.text[self.i] == "\n": + self.i += 1 + out: list = [] + while True: + if self.i >= self.n: + self.fail("多行字符串没闭合") + c = self.text[self.i] + if c == '"': + if self.text.startswith('"""', self.i): + # 收尾:内容末尾最多带两个引号(写成 4 个或 5 个引号) + self.i += 3 + extra = 0 + if self.i < self.n and self.text[self.i] == '"': + extra = 1 + self.i += 1 + if self.i < self.n and self.text[self.i] == '"': + extra = 2 + self.i += 1 + return "".join(out) + '"' * extra + out.append('"') + self.i += 1 + continue + if c == "\\": + out.append(self.scan_escape_multiline()) + continue + if c in _ILLEGAL_MULTILINE_STR_CHARS: + self.fail("多行字符串里有非法控制字符") + out.append(c) + self.i += 1 + + def scan_multiline_literal(self) -> str: + """多行字面字符串 `'''…'''`。""" + self.i += 3 # 开引号 + if self.i < self.n and self.text[self.i] == "\n": + self.i += 1 + start = self.i + # 逐字扫:控制字符非法(与 tomllib 同口径),单独的引号算内容 + while True: + if self.i >= self.n: + self.fail("多行字符串没闭合") + c = self.text[self.i] + if c == "'": + if self.text.startswith("'''", self.i): + end = self.i + break + self.i += 1 + continue + if c in _ILLEGAL_MULTILINE_STR_CHARS: + self.fail("多行字面字符串里有非法控制字符") + self.i += 1 + pos = end + 3 + extra = 0 + if pos < self.n and self.text[pos] == "'": + extra = 1 + pos += 1 + if pos < self.n and self.text[pos] == "'": + extra = 2 + pos += 1 + self.i = pos + return self.text[start:end] + "'" * extra + + def scan_escape_multiline(self) -> str: + """多行字符串里的转义:行尾反斜杠吃掉换行与随后的空白。""" + j = self.i + 1 + k = j + while k < self.n and self.text[k] in " \t": + k += 1 + if (k < self.n and self.text[k] == "\n") or (j < self.n and self.text[j] == "\n"): + self.i = (k if k < self.n and self.text[k] == "\n" else j) + 1 + while self.i < self.n and self.text[self.i] in _TOML_WS_AND_NEWLINE: + self.i += 1 + return "" + self.i += 1 # 跳过反斜杠 + return self.scan_escape() + + # ---- 路径导航 ---- + + def get_or_create_nest(self, path) -> dict: + """按路径走到(或建出)那张表;中间撞上非表值就报错。""" + cont = self.root + for k in path: + if k not in cont: + cont[k] = {} + cont = cont[k] + if isinstance(cont, list): + cont = cont[-1] + if not isinstance(cont, dict): + raise KeyError(k) + return cont + + def unset_all(self, path): + """清掉挂在某路径下的标记(表数组重新声明时用)。""" + n = len(path) + self.explicit = {p for p in self.explicit if p[:n] != path} + self.frozen = {p for p in self.frozen if p[:n] != path} -def _table_for(root: dict, name: str): - """按点号分段建表:`[budget.sections]` → root["budget"]["sections"]。""" - table = root - for part in name.split("."): - part = part.strip().strip("\"'") - existing = table.setdefault(part, {}) - if not isinstance(existing, dict): - raise ValueError("表 %r 与同名非表值冲突" % name) - table = existing - return table +def _mini_toml(text: str) -> dict: + """3.10 兜底 TOML 解析器(严格档)。 + 坏 TOML 一律抛 _MiniTomlError(ValueError 子类),由 load_toml 转成 + ConfigError → 退出码 2(配置错),与 3.11+ 的 tomllib 同一口径。 -def _mini_toml(text: str) -> dict: - """只覆盖 factscribe 契约用得到的子集:表、表数组、字符串、数组、数字、布尔。""" - root: dict = {} - cur: dict = root - lines = text.splitlines() - i = 0 - while i < len(lines): - raw = lines[i] - i += 1 - s = _strip_toml_comment(raw).strip() - if not s: - continue - if s.startswith("[[") and s.endswith("]]"): - name = s[2:-2].strip() - parent, _, leaf = name.rpartition(".") - holder = _table_for(root, parent) if parent else root - arr = holder.setdefault(leaf.strip().strip("\"'"), []) - if not isinstance(arr, list): - raise ValueError("[[%s]] 与同名表冲突" % name) - cur = {} - arr.append(cur) - continue - if s.startswith("[") and s.endswith("]"): - name = s[1:-1].strip() - tbl = _table_for(root, name) - cur = tbl - continue - if "=" not in s: - raise ValueError("无法解析的 TOML 行:%r" % raw) - key, value = s.split("=", 1) - value = value.strip() - while _needs_more(value) and i < len(lines): - value += " " + _strip_toml_comment(lines[i]).strip() - i += 1 - cur[key.strip().strip("\"'")] = _mini_toml_value(value) - return root + 入口处先把 CRLF 归一成 LF —— 与标准库 tomllib.loads() 做的同一件事 + (它也在入口把整个文档里的 CRLF 换成 LF,连字符串字面量里也一起换)。 + 不这么做,Windows 写的 factscribe.toml 在 3.10 上会被判成坏 TOML, + 而 3.11+ 读得动 —— 同一份文件、两种解释器、两个结论。 + 归一之后仍剩下的裸 CR 不是合法 TOML(tomllib 判非法语句),照拒。 + """ + return _MiniTomlParser(text.replace("\r\n", "\n")).parse() def load_toml(path: Path) -> dict: @@ -258,6 +701,21 @@ class Config: # R-05(v1.3):无法静态解析的闭包目标(宏、#、嵌套花括号、空目标), # 元素同上。审计覆盖不了 ⇒ fail-closed 判红(INPUT_DYNAMIC)。 dynamic_inputs: list = field(default_factory=list) + # R-05:目标存在、但解析后越出项目根的闭包目标(\input{../shared/x.tex} + # 或绝对路径),元素同上。闭包不收它 ⇒ 这一段没进审计 ⇒ 覆盖缺口, + # 判红(INPUT_OUTSIDE_PROJECT,exit 5)。此前此处静默丢弃=fail-open。 + outside_inputs: list = field(default_factory=list) + # R-04:事实账文件(facts/*.toml)越出项目根——软链的真实目标在项目外, + # 或经软链目录绕出去。账本不收它 ⇒ 那些事实没进审计 ⇒ 信任根被突破, + # 判红(FACT_FILE_OUTSIDE_PROJECT,exit 5)。此前 `p.is_file()` 跟随软链 + # 直接读入=fail-open:审计拿信任根外的数字当账,且无任何码。 + # 元素为 (相对路径, 真实目标)。由 load_facts 填充,audit 判红。 + outside_facts: list = field(default_factory=list) + # R-04:事实账文件的软链不可解(成环或断链)——真实目标不可解,内容不可知, + # 账本同样不收它 ⇒ 那些事实没进审计,判红(FACT_FILE_UNRESOLVED,exit 5)。 + # 此前成环软链被 `is_file()` 静默跳过(既无码也无位置)。 + # 元素为 (相对路径, 原因)。由 load_facts 填充,audit 判红。 + unresolved_facts: list = field(default_factory=list) # 批 128:篇幅预算(`[budget]`,可选)。budget_defined=False 时判据不跑, # 行为与批 127 完全一致。键=节文件名去扩展名(sections/04_x.tex → 04_x)。 budget_defined: bool = False @@ -991,7 +1449,7 @@ def _normalise_display(raw, latex: bool = False) -> list[dict]: def _locate_id_line(path: Path, fid: str) -> int: pat = re.compile(r"""^\s*id\s*=\s*["']%s["']""" % re.escape(fid)) try: - for i, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + for i, line in enumerate(read_text_exact(path).splitlines(), 1): if pat.match(line): return i except OSError: @@ -1088,8 +1546,248 @@ def _fact_from_mapping(raw: dict, path: Path, cfg: Config) -> Fact: return f +# -------------------------------------------------------------------------- +# 软链信任根(读侧):事实账与章节闭包的越界/不可解闸 (迁自 main 正确性基线) +# -------------------------------------------------------------------------- + +# 逐跳走软链时的最大跳数(成环与跳数超限都归「内容不可知」)。 +_SYMLINK_MAX_HOPS = 64 + + +def _strip_ext_prefix(text: str) -> str: + r"""剥掉 Windows 扩展长度前缀(`\\?\` 与 `\\?\UNC\`)。 + + Windows 上 `os.readlink` 与 `os.path.realpath` 返回带 `\\?\` 的扩展 + 长度形态,而项目根多半是普通形态;两者直接比相对关系必然不相等——界内软链 + 会被误判成越界(闭包被丢、事实账被拒,还误报 INPUT_OUTSIDE_PROJECT)。 + + POSIX 上不存在这个前缀,本函数是恒等变换。 + """ + if text.startswith("\\\\?\\UNC\\"): + return "\\\\" + text[8:] + if text.startswith("\\\\?\\"): + return text[4:] + return text + + +def _norm_for_compare(path: Path | str) -> str: + """比较用的形态归一:剥扩展长度前缀 + normcase(Windows 忽略大小写)。""" + return os.path.normcase(os.path.normpath(_strip_ext_prefix(str(path)))) + + +def _is_inside_root(path: Path | str, root: Path | str) -> bool: + """path 是否在 root 之内(按归一形态比较;跨盘、形态不一致都算不在内)。""" + try: + Path(_norm_for_compare(path)).relative_to(Path(_norm_for_compare(root))) + return True + except ValueError: + return False + + +def _symlink_chain_end(path: Path) -> tuple[Path | None, bool]: + """逐跳解软链。返回 (最终路径, 是否不可解)。 + + - (最终路径, False):链走完了(最终路径也可能不存在=断链)。 + - (None, True):成环或跳数超限——内容不可知。 + """ + current = path + seen: set[str] = set() + for _ in range(_SYMLINK_MAX_HOPS): + try: + if not current.is_symlink(): + return current, False + except OSError: + return None, True + key = os.path.normpath(str(current)) + if key in seen: + return None, True # 同一跳第二次走到=成环 + seen.add(key) + try: + target = os.readlink(str(current)) + except OSError: + return None, True + # Windows 的 readlink 返回扩展长度形态(\\?\C:\...),剥掉再拼, + # 否则后面与项目根比相对关系时形态对不上(界内软链会被误判成越界)。 + target = _strip_ext_prefix(target) + current = Path(target) if os.path.isabs(target) else current.parent / target + return None, True # 跳数超限:链太深,当成不可解 + + + + +def _rel_to_root(path: Path, root: Path) -> str: + """path 相对 root 的 posix 路径;算不出来退回词法相对路径(绝不抛异常)。 + + 越界的软链已在闭包入口记账判红,这里只负责给「出处」一个能显示的路径—— + 不能因为算不出相对路径就把整个审计打成 traceback(exit 4)。 + """ + try: + return Path(_norm_for_compare(path.resolve())).relative_to( + Path(_norm_for_compare(root.resolve()))).as_posix() + except (ValueError, OSError, RuntimeError): + try: + return path.relative_to(root).as_posix() + except ValueError: + return path.as_posix() + + + + +def _filter_outside_symlinks(cfg: Config, found: dict[str, Path]) -> dict[str, Path]: + """闭包起点里的软链:指向项目外的记账判红,不进闭包。 + + 口径与 F1 已定的越界语义同一条:目标不在信任根内 ⇒ 闭包不收它 ⇒ 那一段 + 没进审计 ⇒ 覆盖缺口 ⇒ 判红 INPUT_OUTSIDE_PROJECT(exit 5)。此前这里直接 + `p.resolve().relative_to(...)` 抛裸 ValueError(exit 4、traceback)—— + 既不是红也不是绿。 + + 指向项目内的软链照旧收进闭包(内容照审);解析不出内容的(成环)也不收, + 但 `all_tex_files` 会把它算进 glob 命中集 ⇒ 覆盖报告报 UNSCANNED_TEX, + 不许静默跳过。 + """ + root = cfg.root.resolve() + kept: dict[str, Path] = {} + for rel, p in found.items(): + target, unresolved = _symlink_chain_end(p) + if unresolved or target is None: + continue + try: + resolved = target.resolve() + except (OSError, RuntimeError): + continue + if not _is_inside_root(resolved, root): + entry = (rel, _strip_ext_prefix(str(resolved)), 0) + if entry not in cfg.outside_inputs: + cfg.outside_inputs.append(entry) + continue + kept[rel] = p + return kept + + +_INPUT_CMD_RE = re.compile(r"\\(?:input|include|subfile|import)\b") +_DEF_RE = re.compile( + r"\\(?:newcommand|renewcommand|providecommand)\*?\s*\{\s*\\([A-Za-z@]+)\s*\}" + r"\s*(?:\[(\d)\])?\s*(?:\[[^\]]*\])?\s*\{") +_DEF_SIMPLE_RE = re.compile(r"\\def\s*\\[A-Za-z@]+(?:\s*#\d)*\s*") +_INPUT_WRAPPER_RE = re.compile(r"^\s*\\input\s*\{([^{}]*#(\d)[^{}]*)\}\s*$") +# 覆盖报告跳过的目录名(任一层命中即跳):attic=删节归档目录—— +# 挪进去的节已经不在审计闭包里了,别再报「未扫描」(口径 8 的删节归档)。 +_SKIP_DIRS = {".git", ".venv", "__pycache__", "audit", "node_modules", + ".pytest_cache", "attic"} + + + + +def _facts_link_kind(cfg: Config, path: Path) -> tuple[str, str]: + """给一个事实账候选文件定类:能不能进账本。 + + 返回 (kind, detail): + - ("ok", ""):普通文件,或软链的真实目标在项目根内 → 正常入账(行为不变)。 + - ("outside", 真实目标):真实目标越出项目根 → 不进账本(信任根被突破)。 + - ("unresolved", 原因):软链成环或断链,内容不可知 → 不进账本。 + + 为什么不用 `Path.resolve()`:软链成环时各版本行为不一致(3.10–3.12 抛 + RuntimeError,3.13+ 不抛),跨版本读数会漂。`os.path.realpath(strict=True)` + 在 3.10–3.14 行为一致:成环抛 ELOOP、断链抛 ENOENT、正常目标返回真实路径。 + 项目根也先 resolve 再比较——macOS 的 /private 前缀会让词法比较误判越界。 + """ + try: + resolved = os.path.realpath(str(path), strict=True) + except OSError as exc: + if exc.errno == errno.ELOOP: + return "unresolved", "软链成环(ELOOP)" + if exc.errno == errno.ENOENT: + return "unresolved", "软链断链(目标不存在)" + return "unresolved", "软链不可解(%s)" % (exc.strerror or exc) + if not _is_inside_root(resolved, cfg.root.resolve()): + return "outside", _strip_ext_prefix(resolved) + return "ok", "" + + + + +def _facts_rel(cfg: Config, path: Path) -> str: + """事实账候选文件的人读位置(相对项目根的 posix 路径)。 + + 取**链接本身**的词法相对路径,不取 resolve 后的目标——断链的 resolve 会 + 落到那个并不存在的目标名上,位置会指错文件。算不出就退回原样:这里只 + 负责给人定位,绝不因算不出相对路径就把整个审计打成 traceback(exit 4)。 + """ + try: + return path.relative_to(cfg.root).as_posix() + except ValueError: + pass + try: + return Path(_norm_for_compare(path.resolve())).relative_to( + Path(_norm_for_compare(cfg.root.resolve()))).as_posix() + except (ValueError, OSError, RuntimeError): + return path.as_posix() + + + + +def outside_facts_note(cfg: Config) -> str: + """事实账为空的原因说明(区分「没账」与「有账但越界/不可解没进审计」)。 + + 越界或不可解的事实账文件不进账本——那些事实没进审计,是信任根被突破 + (红,exit 5),不是「这个项目没有事实账」(配置错,exit 2)。两者混成 + 一个码就把缺口盖住了,所以空账时要说清是哪一种。 + """ + outside = getattr(cfg, "outside_facts", []) or [] + unresolved = getattr(cfg, "unresolved_facts", []) or [] + if outside: + return ("事实账没有可用事实(%s 没匹配到任何 fact)——%s 是指向项目外的" + "软链(真实目标 %s),账本不收它,这些事实没进审计" + % (cfg.facts_glob, outside[0][0], outside[0][1])) + if unresolved: + return ("事实账没有可用事实(%s 没匹配到任何 fact)——%s 的软链不可解" + "(%s),账本不收它,这些事实没进审计" + % (cfg.facts_glob, unresolved[0][0], unresolved[0][1])) + return "" + + + + +def outside_closure_note(cfg: Config) -> str: + """闭包空的原因说明(区分「没正文」与「有正文但越界没进审计」)。 + + 越界的闭包目标(章节软链指向项目外)不进闭包——那一段没进审计,是覆盖缺口 + (INPUT_OUTSIDE_PROJECT,exit 5),不是「这个项目没有正文」(exit 2)。两者 + 混成一个码就把缺口盖住了,所以空闭包时要说清是哪一种。 + """ + outside = getattr(cfg, "outside_inputs", []) or [] + if not outside: + return "" + return ("闭包没有正文——%s 是指向项目外的软链,那一段没进审计" + "(越界目标不进闭包);把它挪进项目内或改指向。" % outside[0][0]) + + + + def load_facts(cfg: Config) -> list[Fact]: - files = sorted(p for p in cfg.root.glob(cfg.facts_glob) if p.is_file()) + # 事实账的信任根=项目根。facts/*.toml 若是软链(或经软链目录绕出去), + # 真实目标必须在项目根内,否则这些事实就是从信任根外取数——此前 + # `p.is_file()` 跟随软链直接读入,静默无码(fail-open)。现在越界与不可解 + # (成环/断链)一律记账不读入,由 audit 判红(FACT_FILE_OUTSIDE_PROJECT / + # FACT_FILE_UNRESOLVED,exit 5)。指向项目内的软链照旧入账,行为一字不变。 + cfg.outside_facts = [] + cfg.unresolved_facts = [] + files: list[Path] = [] + for path in sorted(cfg.root.glob(cfg.facts_glob)): + kind, detail = _facts_link_kind(cfg, path) + if kind == "outside": + entry = (_facts_rel(cfg, path), detail) + if entry not in cfg.outside_facts: + cfg.outside_facts.append(entry) + continue + if kind == "unresolved": + entry = (_facts_rel(cfg, path), detail) + if entry not in cfg.unresolved_facts: + cfg.unresolved_facts.append(entry) + continue + if not path.is_file(): + continue + files.append(path) facts: list[Fact] = [] for path in files: data = load_toml(path) @@ -1160,15 +1858,6 @@ def _glob_paths(root: Path, pattern: str) -> dict[str, Path]: return found -_INPUT_CMD_RE = re.compile(r"\\(?:input|include|subfile|import)\b") -_DEF_RE = re.compile( - r"\\(?:newcommand|renewcommand|providecommand)\*?\s*\{\s*\\([A-Za-z@]+)\s*\}" - r"\s*(?:\[(\d)\])?\s*(?:\[[^\]]*\])?\s*\{") -_DEF_SIMPLE_RE = re.compile(r"\\def\s*\\[A-Za-z@]+(?:\s*#\d)*\s*") -_INPUT_WRAPPER_RE = re.compile(r"^\s*\\input\s*\{([^{}]*#(\d)[^{}]*)\}\s*$") -_SKIP_DIRS = {".git", ".venv", "__pycache__", "audit", "node_modules", ".pytest_cache"} - - def _balanced_braces(text: str, start: int) -> int: """text[start] == '{';返回配对 '}' 之后的位置。""" depth = 0 @@ -1303,9 +1992,13 @@ def load_sections(cfg: Config) -> list[tuple[str, str]]: 由 audit 判 ``INPUT_TARGET_MISSING``(R-05):不存在的目标不会静默放行。 目标含宏/`#`/嵌套花括号/为空时记进 ``cfg.dynamic_inputs``,由 audit 判 ``INPUT_DYNAMIC``:静态审计覆盖不了的目标一律 fail-closed,不许静默跳过。 + 目标存在但解析后越出项目根时记进 ``cfg.outside_inputs``,由 audit 判 + ``INPUT_OUTSIDE_PROJECT``:越界的目标闭包不收,它那一段同样没进审计, + 静默丢弃就是 fail-open,不许。 """ cfg.missing_inputs = [] cfg.dynamic_inputs = [] + cfg.outside_inputs = [] if cfg.section_files: # V3 形态 C:显式章节清单(不是 glob)。闭包仍从这些文件各自的 # `\input` 展开,但不会把目录里同名的无关 main.tex 也卷进来。 @@ -1327,6 +2020,9 @@ def load_sections(cfg: Config) -> list[tuple[str, str]]: found = {cfg.root_tex: root_file} else: found = _glob_paths(cfg.root, cfg.sections_glob) + # 软链越界:闭包起点若是指向项目外的软链 ⇒ 记账判红 + # (INPUT_OUTSIDE_PROJECT,exit 5),且不进闭包——那一段不在信任根内。 + found = _filter_outside_symlinks(cfg, found) seen: dict[str, Path] = dict(found) queue: list[Path] = list(found.values()) @@ -1341,7 +2037,26 @@ def add_ref(ref: str, bases: list[Path], src_rel: str, line: int) -> bool: try: rel = candidate.resolve().relative_to(cfg.root.resolve()).as_posix() except ValueError: + # 目标存在,但解析后越出项目根(\input{../shared/x.tex} 或 + # 绝对路径)。闭包不收它 ⇒ 这一段没进审计。此前在此静默 + # 丢弃(return False 且不记账),audit 仍判绿——fail-open。 + # 现在记进 cfg.outside_inputs,由 audit 判红 + # INPUT_OUTSIDE_PROJECT(exit 5),与 missing_inputs 同级可见。 + entry = (src_rel, ref, line) + if entry not in cfg.outside_inputs: + cfg.outside_inputs.append(entry) return False + except (OSError, RuntimeError): + # 解析不出来(软链成环等 OSError/ELOOP):绝不裸崩。 + # 按词法相对路径再判一次越界;判不出越界就照旧收进闭包 + # (内容读得到才审得到)。 + try: + rel = candidate.relative_to(cfg.root).as_posix() + except ValueError: + entry = (src_rel, ref, line) + if entry not in cfg.outside_inputs: + cfg.outside_inputs.append(entry) + return False if rel in seen: return False seen[rel] = candidate @@ -1367,22 +2082,22 @@ def add_raw_ref(raw: str, bases: list[Path], src_rel: str, line: int, # 普通 \input 闭包(注释/verbatim 里的 \input 不算引用,避免误判) while queue: p = queue.pop(0) - text = _read_text(p, cfg.root) + text = to_lf(_read_text(p, cfg.root)) body = _mask_macro_defs(strip_comments_and_verbatim(text)) - src_rel = p.resolve().relative_to(cfg.root.resolve()).as_posix() + src_rel = _rel_to_root(p, cfg.root) for ref, line, closed in _input_refs(body): add_raw_ref(ref, [p.parent, cfg.root], src_rel, line, closed=closed) # 包装宏:定义可能出现在后加载的文件里,故反复扫到稳定为止 wrappers: dict[str, tuple[str, str]] = {} for p in list(seen.values()): - wrappers.update(_input_wrappers(_read_text(p, cfg.root))) + wrappers.update(_input_wrappers(to_lf(_read_text(p, cfg.root)))) if not wrappers: break grew = False for p in list(seen.values()): - text = strip_comments_and_verbatim(_read_text(p, cfg.root)) - src_rel = p.resolve().relative_to(cfg.root.resolve()).as_posix() + text = strip_comments_and_verbatim(to_lf(_read_text(p, cfg.root))) + src_rel = _rel_to_root(p, cfg.root) for ref, line in _wrapper_calls(text, wrappers): if add_raw_ref(ref, [p.parent, cfg.root], src_rel, line): grew = True @@ -1396,8 +2111,17 @@ def add_raw_ref(raw: str, bases: list[Path], src_rel: str, line: int, def _read_text(path: Path, root: Path) -> str: + """按原样读项目里的文本文件(不做通用换行翻译)。 + + 读侧不翻译是「逐字保留」的第一环:通用换行翻译(universal newlines) + 把 CRLF 读成 LF,正文的行尾就此丢失——后面再写回磁盘,改掉的就是 + 用户自己的字节。 + + **分析层要按行看文本的**(正则里用 `$` 锚行尾),调用方自己用 + `textio.to_lf` 归一;归一的是内存里的副本,磁盘上的字节一个不动。 + """ try: - return path.read_text(encoding="utf-8") + return read_text_exact(path) except UnicodeDecodeError as exc: raise ConfigError("%s 不是合法 UTF-8:%s" % (path, exc)) except OSError as exc: @@ -1408,7 +2132,10 @@ def all_tex_files(cfg: Config) -> list[str]: """项目内全部 .tex(用于「闭包外文件是否从未被审计」的覆盖报告)。""" out = [] for p in cfg.root.glob("**/*.tex"): - if not p.is_file(): + # is_file() 跟随软链:断链/成环的软链是 False。它仍在 glob 命中集里 + # (文件名匹配上了),但内容读不出来 ⇒ 覆盖不了 ⇒ 照旧报 UNSCANNED_TEX + # (fail-closed)。此前这里直接 continue,那个文件就静默消失了。 + if not p.is_file() and not p.is_symlink(): continue parts = set(p.relative_to(cfg.root).parts) if parts & _SKIP_DIRS: @@ -1418,9 +2145,16 @@ def all_tex_files(cfg: Config) -> list[str]: def facts_digest(cfg: Config) -> str: - """账本输入指纹:所有 facts 文件按路径排序后串哈希(红队 D7)。""" + """账本输入指纹:所有 facts 文件按路径排序后串哈希(红队 D7)。 + + 口径与 load_facts 对齐:被账本拒收的文件(越界软链/不可解软链)不进 + 指纹——指纹只覆盖真正进了账本的输入。既有项目没有软链,指纹逐字节不变。 + """ h = hashlib.sha256() for name, path in sorted(_glob_paths(cfg.root, cfg.facts_glob).items()): + kind, _detail = _facts_link_kind(cfg, path) + if kind != "ok": + continue h.update(name.encode("utf-8")) h.update(path.read_bytes()) return h.hexdigest() diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/constants.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/constants.py index 549332ab..e3e265c3 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/constants.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/constants.py @@ -28,3 +28,185 @@ SEV_RED = "red" SEV_YELLOW = "yellow" SEV_INFO = "info" + +# --------------------------------------------------------------------------- +# 判定码闭集(2026-11-26:第 ② 步把段落级线并进 main 时入宪) +# +# 为什么入宪:退出码闭集早就是「全闭集入宪」的既有原则(见上 EXIT_* 那段 +# 注释)。判定码此前散落在各模块的 code= 里——第三方与上游社区包没法 +# 对照一份完整的码表。这里把**引擎会抛出的每一个判定码**登记成闭集: +# +# * 只加不改:既有码的名字与含义一个字不动;本次新增登记的是段落级线 +# 独有的 13 个(见 PARAGRAPH_ONLY_CODES);法律侧第 ② 步并进来时又补登了 +# 法律集成件自己的 3 个(PROPOSAL_STALE/PROPOSAL_INVALID/PROPOSAL_UNKNOWN)。 +# * 登记 ≠ 触发:这 13 个码全部落在**写侧**(提议单/段落写回/value 硬闸), +# 审计(audit --json)那条路上一个都不会抛——27 盘逐盘 cmp 27/27 与金样例 +# 逐字节未动,就是这件事的实测证据。 +# * 码表是**机械扫描**出来的(AST 扫 code= 关键字/常量/默认值), +# 增删码时重扫一次,别手抄;tests/test_code_closed_set.py 会核对。 +# --------------------------------------------------------------------------- + +#: 段落级线独有、本次(第 ② 步并入段落级线时)补登进闭集的 13 个判定码。 +#: 全部落在**写侧**(提议单/段落写回/value 硬闸),审计那条路一个都不抛。 +PARAGRAPH_ONLY_CODES = frozenset({ + 'BLOCK_STALE', + 'EDIT_TOKEN_MISMATCH', + 'EDIT_TOKEN_COUNT_MISMATCH', + 'EDIT_SHAPE_MISMATCH', + 'EDIT_UNBALANCED', + 'PROPOSAL_SHAPE_MISMATCH', + 'PROPOSAL_TOKEN_MISMATCH', + 'PROPOSAL_FAILED', + 'PROPOSAL_ID_INVALID', + 'PROPOSAL_NOT_FOUND', + 'PROPOSAL_UNREADABLE', + 'PROPOSAL_ALREADY_RESOLVED', + 'VALUE_SOURCE_NOT_TEXT', +}) + +#: 判定码权威闭集:引擎会抛出的每一个判定码(机械扫描生成,别手抄)。 +CODE_CLOSED_SET = frozenset({ + 'ABSTRACT_MISSING', + 'AI_UNAVAILABLE', + 'ASSEMBLY_MISSING', + 'ASSET_INVALID', + # 图片预览通道(factscribe/workbench/assets.py + serve.py 的 /api/asset) + # 抛的码。它在第 ④ 步之前就由 serve.py 抛了,只是那时闭集扫描器看不见 + # (扫描认的是 code= 关键字与异常默认值,不认 _error() 的位置参数); + # 第 ④ 步并进来的 assets.py 用了 code="ASSET_NOT_FOUND",闭集核对照实 + # 把它点出来了——补登即可,码的名字与含义一个字没改,运行行为零变化 + # (CODE_CLOSED_SET 是登记表,不是派发表)。 + 'ASSET_NOT_FOUND', + 'BAD_ENUM', + 'BAD_TOML', + 'BAD_VALUE', + 'BIB_PATH_ESCAPE', + 'BLOCK_MISSING', + 'BLOCK_STALE', + 'BUNDLE_CONFIG_INVALID', + 'BUNDLE_FAILED', + 'CHECK_FAILED', + 'CITATION_EXISTS', + 'CITATION_INVALID', + 'CITATION_MISSING', + 'DRAFT_EMPTY', + 'DRAFT_NOT_AI', + 'EDIT_SHAPE_MISMATCH', + 'EDIT_TOKEN_COUNT_MISMATCH', + 'EDIT_TOKEN_MISMATCH', + 'EDIT_UNBALANCED', + 'EVIDENCE_NOT_FROZEN', + 'EVIDENCE_REASON_REQUIRED', + 'FACT_ALREADY_BOUND', + 'FACT_BIND_NOT_PARA', + 'FACT_CONTAINER_INVALID', + 'FACT_ID_MISSING', + 'FACT_NOT_IN_LEDGER', + 'FACT_SCHEMA_INVALID', + 'FACT_VALUE_EMPTY', + 'FIG_SPEC_UNPLOTTABLE', + 'FILE_NOT_FOUND', + 'FILE_TOO_LARGE', + 'FLOAT_NOT_ALLOWED', + 'IMPORT_FAILED', + 'KNOWLEDGE_FAILED', + 'LEDGER_NOT_IN_GLOB_DIR', + 'LEDGER_OUTSIDE_GLOB', + 'LEDGER_PATH_INVALID', + 'LEDGER_PREFIX_TAKEN', + 'LEDGER_STYLE_MISMATCH', + 'LOCK_MISMATCH', + 'LOCK_MISSING', + 'MIRROR_BIB_INVALID', + 'MIRROR_BIB_MISSING', + 'MIRROR_CONFIG_INVALID', + 'MIRROR_DISK_INVALID', + 'MIRROR_DISK_MISSING', + 'MIRROR_FACTS_INVALID', + 'MIRROR_FACTS_MISSING', + 'MISSING_FIELD', + 'NO_PROJECT', + 'ORDER_INVALID', + 'PATH_ESCAPE', + 'PATH_NOT_FILE', + 'PDFTOTEXT_MISSING', + 'PDF_MISSING', + 'PDF_TEXT_FAILED', + 'POPPLER_MISSING', + 'PROBE_ERROR', + 'PROBE_MISMATCH', + 'PROBE_PARSE', + 'PROJECT_CREATE_FAILED', + 'PROJECT_DIR_NOT_EMPTY', + 'PROJECT_INVALID', + 'PROJECT_NOT_REGISTERED', + 'PROJECT_PARENT_INVALID', + 'PROJECT_PARENT_MISSING', + 'PROJECT_SLUG_INVALID', + 'PROJECT_TITLE_MISSING', + 'PROPOSAL_ALREADY_RESOLVED', + 'PROPOSAL_FACT_MISSING', + 'PROPOSAL_FAILED', + 'PROPOSAL_ID_INVALID', + 'PROPOSAL_INVALID', + 'PROPOSAL_KIND_INVALID', + 'PROPOSAL_NOT_FOUND', + 'PROPOSAL_SHAPE_MISMATCH', + # 法律侧待批提案通道的三个码(integrations/factscribe-legal/factscribe_legal/ + # proposals.py):PROPOSAL_STALE=指纹闸不过(before_sha 与现算的不符), + # PROPOSAL_INVALID=提议单本身不合形状,PROPOSAL_UNKNOWN=单号查无此单。 + # 法律侧第 ② 步并进 main 时补登——那个分支的基点早于闭集入宪那笔, + # 扫描器看不见这三个码。登记 ≠ 触发:三个码全落在**写侧**(建单/采纳), + # 审计那条路一个都不抛(27 盘逐盘 cmp 与金样例逐字节未动即是证据)。 + 'PROPOSAL_STALE', + 'PROPOSAL_TEXT_EMPTY', + 'PROPOSAL_TOKEN_MISMATCH', + 'PROPOSAL_UNKNOWN', + 'PROPOSAL_UNREADABLE', + 'PROTECT_FILE_SET_CHANGED', + 'PROTECT_HEADING_RENAMED', + 'PROTECT_MATH_CHANGED', + 'PROTECT_TABLE_CHANGED', + 'READ_ONLY', + 'REF_PICK_INVALID', + 'REF_SEARCH_BADPAYLOAD', + 'REF_SEARCH_HTTP', + 'REF_SEARCH_NETWORK', + 'REF_SEARCH_TIMEOUT', + 'REF_TODO_TABLE_INVALID', + 'REF_TODO_TABLE_MISSING', + 'REPORT_ERROR', + 'REPORT_EXISTS', + 'REPORT_ID_INVALID', + 'SAMPLE_COPY_FAILED', + 'SAMPLE_FAILED', + 'SAMPLE_MISSING', + 'SAMPLE_REMOVE_FAILED', + 'SECTIONS_DIR_MISSING', + 'SECTION_EXISTS', + 'SECTION_INVALID', + 'SECTION_MISSING', + 'SECTION_NOT_HEADING', + 'SECTION_NOT_INCLUDED', + 'SECTION_PARENT_MISSING', + 'SECTION_PATH_INVALID', + 'SECTION_READONLY', + 'SECTION_REFERENCED', + 'SECTION_TITLE_MISSING', + 'TITLE_MISSING', + 'TR_DIR_INVALID', + 'TR_DIR_MISSING', + 'TR_MIN_TOKENS_RANGE', + 'TR_NO_FILES', + 'TR_N_RANGE', + 'TR_SELF_COMPARE', + 'TR_SENTENCE_MIN_WORDS_RANGE', + 'TR_SENTENCE_THRESHOLD_RANGE', + 'USAGE', + 'VALUE_NOT_IN_SOURCE', + 'VALUE_SOURCE_NOT_TEXT', + 'VALUE_SOURCE_UNREADABLE', + 'VALUE_TEXT_NOT_IN_SOURCE', + 'VENUE_FAILED', + 'WORKSPACE_MISSING', +}) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/doctor.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/doctor.py index bfeb7283..d42d0ce2 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/doctor.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/doctor.py @@ -23,7 +23,8 @@ from .buildpdf import find_cjk_font, find_fandol_fonts from .config import (Config, ConfigError, find_config_file, load_config, - load_facts, load_sections, load_toml) + load_facts, load_sections, load_toml, + outside_closure_note, outside_facts_note) from .evidence import LOCK_REL, read_lock, unfrozen_info from .scaffold import INIT_FILES from .textio import read_text_exact, to_lf @@ -225,6 +226,10 @@ def _sections_check(cfg: Config) -> dict: return _check("sections", "章节", LEVEL_FAIL, str(exc), fix="检查 factscribe.toml 的 sections / root_tex") if not sections: + note = outside_closure_note(cfg) + if note: + return _check("sections", "章节", LEVEL_FAIL, note, + fix="把越界的软链挪进项目内或改指向") return _check("sections", "章节", LEVEL_WARN, "没有匹配到任何 .tex 章节,audit 会对着空正文跑", fix="把正文放进 sections/ 或改 sections 配置") @@ -238,6 +243,12 @@ def _facts_check(cfg: Config) -> tuple[dict, list]: return (_check("facts", "事实账", LEVEL_FAIL, str(exc), fix="按报错修 facts/ 下的 TOML"), []) if not facts: + # 空账有两种:真没账(空账警告,exit 2);或账文件是越界/不可解的 + # 软链、被账本拒收(信任根缺口,exit 5)——后者是失败,不是空账。 + note = outside_facts_note(cfg) + if note: + return (_check("facts", "事实账", LEVEL_FAIL, note, + fix="把越界或不可解的软链挪进项目内,或改指向"), []) return (_check( "facts", "事实账", LEVEL_WARN, "账里还没有事实:空账不能通过 check(exit 2)", diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/evidence.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/evidence.py index 149d0bb4..7ac734a3 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/evidence.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/evidence.py @@ -30,6 +30,7 @@ from pathlib import Path from .config import Config, ConfigError, load_facts, load_toml +from .safepath import guard_project_write from .texscan import scan_tex MISSING_CODE = "REQUIRED_EVIDENCE_MISSING" @@ -272,6 +273,8 @@ def write_lock(project_root: Path, evidence: dict) -> dict: for i in normal[key]) lines.append('"%s" = [%s]' % (key.replace('"', '\\"'), ids)) path = Path(project_root) / LOCK_REL + # 写侧落点闸:冻结件必须落在项目根内(软链绕出去就拒写,不落盘)。 + guard_project_write(Path(project_root), path, what="证据冻结件", rel=LOCK_REL) path.parent.mkdir(parents=True, exist_ok=True) path.write_text("\n".join(lines) + "\n", encoding="utf-8") return {"path": LOCK_REL, "sha256": digest, "entries": entries, diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/facts.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/facts.py index e4078254..5c138251 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/facts.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/facts.py @@ -19,7 +19,10 @@ # 数字照抽,单位只作噪声(不参与数值换算)。长单位排在短单位前,避免 # "ms" 被 "m"、"tokens" 被 "tok" 抢先;量级 [kKMB] 排在单位之后, # 所以 "5MB" 是单位、"5M" 仍是量级。 -# - 百分号允许中间有空格(\% 掩码后就是 " %"),也接受 percent/pct 英文词 +# - 百分号允许中间有空格(\% 掩码后就是 " %"),也接受 percent/pct 英文词; +# 全角 %(U+FF05)=半角 %:全角写法是同一种写法,不是另一种数。此前只认 +# ASCII 的 "%",于是 56.25% 被读成绝对值 56.25(而不是百分数 0.5625) +# ——会误判数字。与该文件对半角 % 的既有处理保持一致,不另立一套规则。 # - 科学计数法整体成 token(3e-4 / 1.2E+05),不拆成 3 和 4 # *** 匹配是 token 锚定的:不做子串匹配(红队 B1)*** _UNIT_RE = ( @@ -31,12 +34,24 @@ r"(? str: + """全角小数点 → ASCII 小数点(等长替换,位置不变)。""" + return str(text).replace(_FULLWIDTH_DOT, ".") + _FRACTION_RE = re.compile(r"(? str: def number_key(token: str, suffix: str | None = None, percent: bool = False) -> str: try: - d = Decimal(str(token).replace(",", "")) + d = Decimal(normalize_fullwidth_dot(str(token)).replace(",", "")) except InvalidOperation: return token if suffix: @@ -96,7 +111,7 @@ def number_key(token: str, suffix: str | None = None, percent: bool = False) -> def literal_tokens(value: str) -> list[tuple[str, str, bool]]: """value 里字面写出的数字 token:(raw, suffix, pct)。不做分数展开。""" out = [] - for m in _NUM_RE.finditer(str(value or "")): + for m in _NUM_RE.finditer(normalize_fullwidth_dot(str(value or ""))): out.append((m.group(1), m.group(2) or "", bool(m.group(3)))) return out @@ -122,7 +137,7 @@ def fact_value_keys(value: str, include_quotient: bool = True) -> set[str]: if pct: keys.add(number_key(raw, suffix, False)) if include_quotient: - for m in _FRACTION_RE.finditer(str(value or "")): + for m in _FRACTION_RE.finditer(normalize_fullwidth_dot(str(value or ""))): try: num, den = Decimal(m.group(1)), Decimal(m.group(2)) except InvalidOperation: @@ -140,7 +155,7 @@ def canon_text(text: str) -> str | None: 用于 `display` 严格等价判定(R-04):`10/16` 与 `62.5%` 都是 0.625; `0.91` 与 `0.9` 永不相等(不再有 round_to 容差)。 """ - s = str(text or "").strip() + s = normalize_fullwidth_dot(str(text or "").strip()) if not s: return None m = _FRACTION_RE.fullmatch(s) @@ -160,7 +175,7 @@ def canon_text(text: str) -> str | None: def decimal_places(text: str) -> int: """`text` 里数字的小数位数(用于 round_to 机械校验)。""" - m = _NUM_RE.search(str(text or "")) + m = _NUM_RE.search(normalize_fullwidth_dot(str(text or ""))) if not m: return 0 raw = m.group(1).replace(",", "") diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/figures.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/figures.py index dd38a4b7..f1d6ac25 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/figures.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/figures.py @@ -38,6 +38,7 @@ from .config import (Config, ConfigError, facts_digest, find_config_file, load_config, load_facts, load_toml) from .facts import canon_text, latex_display +from .safepath import guard_project_write from .scaffold import toml_string # -------------------------------------------------------------------------- @@ -889,6 +890,10 @@ def generate(root: Path) -> GenResult: artifacts.append(art) gen_dir = cfg.root / GEN_DIR + # 写侧落点闸:图表产物与绑定表必须落在项目根内(软链绕出去就拒写,不落盘)。 + guard_project_write(cfg.root, gen_dir, what="图表产物目录", rel=GEN_DIR) + guard_project_write(cfg.root, cfg.root / BIND_INDEX, what="图表绑定表", + rel=BIND_INDEX) for art in artifacts: spec = art.spec bind_path = gen_dir / ("%s.bind.toml" % spec.name) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/i18n.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/i18n.py index 717026ed..c7b95d7b 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/i18n.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/i18n.py @@ -442,6 +442,22 @@ def catalog_for(keys, langs=LANGS, catalog: dict | None = None) -> dict: "zh": "\\input/\\include 目标 {ref} 含宏、#、嵌套花括号或为空({src_rel}:{line})——无法静态解析,审计覆盖不了这一段(R-05)", "en": "\\input/\\include target {ref} contains macros, #, nested braces, or is empty ({src_rel}:{line}) — it cannot be resolved statically, so the audit cannot cover this part (R-05)", }, + "finding.FACT_FILE_OUTSIDE_PROJECT": { + "zh": "事实账文件 {rel} 是指向项目外的软链(真实目标 {target})——账本不收它,这些事实没进审计(信任根被突破)", + "en": "ledger file {rel} is a symlink pointing outside the project (real target {target}) — the ledger does not accept it, so those facts never entered the audit (the trust root is broken)", + }, + "finding.FACT_FILE_UNRESOLVED": { + "zh": "事实账文件 {rel} 的软链不可解({why})——账本不收它,这些事实没进审计", + "en": "the symlink of ledger file {rel} cannot be resolved ({why}) — the ledger does not accept it, so those facts never entered the audit", + }, + "finding.INPUT_OUTSIDE_PROJECT": { + "zh": "\\input 目标 {ref} 越出项目根({src_rel}:{line})——闭包不收它,这一段可能整体没进审计(R-05)", + "en": "\\input target {ref} is outside the project root ({src_rel}:{line}) — the closure does not accept it, so this part may not have entered the audit at all (R-05)", + }, + "finding.INPUT_OUTSIDE_PROJECT.start": { + "zh": "闭包起点 {src_rel} 是软链,越出项目根(目标 {ref})——闭包不收它,这一段可能整体没进审计(R-05)", + "en": "closure start {src_rel} is a symlink pointing outside the project root (target {ref}) — the closure does not accept it, so this part may not have entered the audit at all (R-05)", + }, "finding.INPUT_TARGET_MISSING": { "zh": "\\input 目标 {ref} 不存在({src_rel}:{line})——闭包展开失败,这一段可能整体没进审计(R-05)", "en": "\\input target {ref} does not exist ({src_rel}:{line}) — closure expansion failed, so this part may not have entered the audit at all (R-05)", diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/mcp.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/mcp.py index aa380674..f84494b0 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/mcp.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/mcp.py @@ -30,6 +30,12 @@ "file": {"type": "string", "description": "Project-relative .tex path, e.g. sections/03.tex"}, "text": {"type": "string", "description": "Full new file content"}, + "expect_sha": {"type": "string", + "description": "Optional fingerprint of the section " + "version this edit was based on " + "(sha256 hex, first 16 chars). If it " + "no longer matches the file on disk, " + "the write is refused (BLOCK_STALE)."}, }, "required": ["file", "text"], "additionalProperties": False, @@ -157,7 +163,8 @@ def _dispatch(project: Path, allow_write: bool, name: str, str(args.get("at") or ""), allow_write) if name == "factscribe_write_section": return write_section_data(project, str(args.get("file") or ""), - args.get("text"), allow_write) + args.get("text"), allow_write, + str(args.get("expect_sha") or "")) if name == "factscribe_add_fact": return add_fact_data(project, args, allow_write) raise KeyError(name) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/projects.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/projects.py index 290d4e17..f844661c 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/projects.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/projects.py @@ -17,6 +17,7 @@ from datetime import datetime, timezone from pathlib import Path +from .safepath import guard_project_write from .textio import (dominant_newline, read_text_exact, split_keepends, write_text_exact) @@ -234,6 +235,8 @@ def _rewrite_project_table(path: Path, values: dict) -> None: 行尾按原样保留:改一个键不牵动整份文件的换行。 """ + # 写侧落点闸:声明文件必须留在项目根内(软链绕出去就拒写,不落盘)。 + guard_project_write(path.parent, path, what="项目声明", rel=path.name) raw = read_text_exact(path) parts = split_keepends(raw) contents = [content for content, _ in parts] diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/refs.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/refs.py index bf69f6d9..b3d0e105 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/refs.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/refs.py @@ -49,6 +49,7 @@ from .citations import parse_bib from .config import ConfigError, load_config, load_toml from .constants import EXIT_OK, EXIT_RED, EXIT_YELLOW, VERSION +from .safepath import guard_project_write from .scaffold import toml_array, toml_string # -------------------------------------------------------------------------- @@ -876,6 +877,8 @@ def search(query: str, project=".", source: str = "crossref", stamp = _now_stamp() stem = "%s-%s-%s-%s" % (stamp, source, _slugify(query), digest[:8]) cdir = Path(cfg.root) / CANDIDATES_REL + # 写侧落点闸:候选落盘目录必须留在项目根内(软链绕出去就拒写,不落盘)。 + guard_project_write(cfg.root, cdir, what="候选落盘目录", rel=CANDIDATES_REL) suffix = ".raw.json" if source == "crossref" else ".raw.xml" raw_path = cdir / (stem + suffix) envelope_path = cdir / (stem + ".candidates.json") @@ -952,6 +955,8 @@ def _append_ref(root, fields: dict) -> Path: `root` 是项目根(不是 Config)——登记表固定在 `/refs/todo.toml`。 """ path = Path(root) / TODO_REL + # 写侧落点闸:登记表必须留在项目根内(软链绕出去就拒写,不落盘)。 + guard_project_write(Path(root), path, what="待补文献登记表", rel=TODO_REL) if path.is_file(): existing = path.read_bytes() else: diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/report.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/report.py index aea494bf..f68ebd02 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/report.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/report.py @@ -17,11 +17,12 @@ from pathlib import Path, PurePosixPath from .audit import Issue -from .config import Config, ConfigError, load_toml -from . import config as _config -from .constants import (EXIT_CONFIG, EXIT_INTERNAL, EXIT_OK, EXIT_RED, - EXIT_YELLOW, SCHEMA_VERSION, SEV_RED, SEV_YELLOW, - VERSION) +from .config import (Config, ConfigError, load_toml, outside_closure_note, + outside_facts_note) +from .constants import (EXIT_ATTACK_OPEN, EXIT_CONFIG, EXIT_INTEGRITY, + EXIT_INTERNAL, EXIT_MISSING, EXIT_OK, EXIT_PROOF, + EXIT_RED, EXIT_STALE, EXIT_YELLOW, SCHEMA_VERSION, + SEV_RED, SEV_YELLOW, VERSION) from .facts import Fact from .texscan import scan_tex @@ -35,8 +36,16 @@ def _cell(v) -> str: def render_matrix(cfg: Config, facts: list[Fact], sections: list[tuple[str, str]]): if not facts: + # 空账有两种:真没账(配置错,exit 2);或账文件是越界/不可解的软链、 + # 被账本拒收(信任根缺口,exit 5)。后者要说清是哪一种,不许混。 + note = outside_facts_note(cfg) + if note: + raise ConfigError(note) raise ConfigError("facts 为空(%s 没匹配到任何 fact)——矩阵无从生成" % cfg.facts_glob) if not sections: + note = outside_closure_note(cfg) + if note: + raise ConfigError(note) raise ConfigError("sections 为空(%s 没匹配到任何 .tex)" % cfg.sections_glob) used_sections: dict[str, list[str]] = {f.id: [] for f in facts} @@ -111,8 +120,17 @@ def _print_issue(i: Issue, idx: int) -> str: def _status_word(code: int) -> str: + """退出码 → 人读结论词。 + + 闭集里每个码都要有说法:原先只映射 0–4,5/6/7/8/9 一律落进默认的 + "?",于是「1 红 / 0 黄 → ?(退出码 5)」这种红闸结论行会印一个问号。 + 说法与 checks.EXIT_CODE_CLOSED_SET 的语义对齐。 + """ return {EXIT_OK: "绿", EXIT_RED: "红(有违例)", EXIT_YELLOW: "黄(未核验,不判死)", - EXIT_CONFIG: "配置/用法错", EXIT_INTERNAL: "工具内部错误"}.get(code, "?") + EXIT_CONFIG: "配置/用法错", EXIT_INTERNAL: "工具内部错误", + EXIT_INTEGRITY: "红(覆盖/信任链缺口)", EXIT_PROOF: "红(未达证明要求)", + EXIT_STALE: "红(过期/重放)", EXIT_MISSING: "工具缺失", + EXIT_ATTACK_OPEN: "红(攻击面未闭合)"}.get(code, "?") def _human_check(cfg, facts, issues, warnings, conflicts, summary, code) -> str: @@ -546,231 +564,22 @@ def evidence_digest(ws, report: dict) -> str: # TOML 读取 # -------------------------------------------------------------------------- -def _toml_scalar(text: str): - t = text.strip() - if t == "true": - return True - if t == "false": - return False - if re.fullmatch(r"[+-]?\d+", t): - return int(t) - if re.fullmatch(r"[+-]?(\d+\.\d*|\.\d+|\d+)([eE][+-]?\d+)?", t): - return float(t) - return t - - -class _MiniToml: - """3.10 兜底:认 inline table 与 inline table 数组的 TOML 子集解析器。 - - config.load_toml 在 3.10 走的是极简解析器,不认 `{ k = v }`, - 而报告格式必须用 inline table(sources 数组)。有 tomllib 时一律用 - config.load_toml;没有时才用这个。 - """ - - def __init__(self, text: str): - self.s = text - self.i = 0 - self.n = len(text) - - def _fail(self, msg: str): - raise ValueError(msg) - - def _ws(self, nl: bool = False): - while self.i < self.n: - c = self.s[self.i] - if c == "#": - while self.i < self.n and self.s[self.i] != "\n": - self.i += 1 - elif c in " \t\r": - self.i += 1 - elif c == "\n" and nl: - self.i += 1 - else: - break - - def parse(self) -> dict: - root: dict = {} - cur = root - while True: - self._ws(nl=True) - if self.i >= self.n: - return root - if self.s[self.i] == "[": - cur = self._header(root) - else: - key, value = self._keyval() - cur[key] = value - - def _header(self, root: dict) -> dict: - self.i += 1 - is_array = False - if self.i < self.n and self.s[self.i] == "[": - is_array = True - self.i += 1 - parts = self._dotted_key() - self._ws() - if self.i >= self.n or self.s[self.i] != "]": - self._fail("表头没有闭合 ]") - self.i += 1 - if is_array: - if self.i >= self.n or self.s[self.i] != "]": - self._fail("表数组头没有闭合 ]]") - self.i += 1 - holder = root - for part in parts[:-1]: - nxt = holder.setdefault(part, {}) - if isinstance(nxt, list): - nxt = nxt[-1] - if not isinstance(nxt, dict): - self._fail("表名 %r 与同名非表值冲突" % part) - holder = nxt - leaf = parts[-1] - if is_array: - arr = holder.setdefault(leaf, []) - if not isinstance(arr, list): - self._fail("[[%s]] 与同名表冲突" % leaf) - new = {} - arr.append(new) - return new - tbl = holder.setdefault(leaf, {}) - if not isinstance(tbl, dict): - self._fail("表 %r 与同名非表值冲突" % leaf) - return tbl - - def _dotted_key(self) -> list: - parts = [] - while True: - self._ws() - parts.append(self._key_token()) - self._ws() - if self.i < self.n and self.s[self.i] == ".": - self.i += 1 - continue - return parts - - def _key_token(self) -> str: - if self.i < self.n and self.s[self.i] in "\"'": - return self._string() - start = self.i - while self.i < self.n and self.s[self.i] not in "=. \t\r\n[]{}": - self.i += 1 - if start == self.i: - self._fail("键解析不了") - return self.s[start:self.i] - - def _keyval(self): - parts = self._dotted_key() - self._ws() - if self.i >= self.n or self.s[self.i] != "=": - self._fail("行里没有 =") - self.i += 1 - return ".".join(parts), self._value() - - def _value(self): - self._ws() - if self.i >= self.n: - self._fail("值缺失") - c = self.s[self.i] - if c in "\"'": - return self._string() - if c == "[": - return self._array() - if c == "{": - return self._inline_table() - start = self.i - while self.i < self.n and self.s[self.i] not in ",]}\n#": - self.i += 1 - return _toml_scalar(self.s[start:self.i]) - - def _string(self) -> str: - quote = self.s[self.i] - self.i += 1 - out = [] - while self.i < self.n: - c = self.s[self.i] - if quote == '"' and c == "\\": - self.i += 1 - if self.i >= self.n: - break - e = self.s[self.i] - mapping = {"n": "\n", "t": "\t", "r": "\r", "b": "\b", - "f": "\f", '"': '"', "\\": "\\"} - if e in mapping: - out.append(mapping[e]) - self.i += 1 - elif e == "u" and self.i + 4 < self.n: - out.append(chr(int(self.s[self.i + 1:self.i + 5], 16))) - self.i += 5 - else: - out.append(e) - self.i += 1 - continue - if c == quote: - self.i += 1 - return "".join(out) - out.append(c) - self.i += 1 - self._fail("字符串没有闭合引号") - - def _array(self) -> list: - self.i += 1 - out = [] - while True: - self._ws(nl=True) - if self.i >= self.n: - self._fail("数组没有闭合 ]") - if self.s[self.i] == "]": - self.i += 1 - return out - out.append(self._value()) - self._ws(nl=True) - if self.i < self.n and self.s[self.i] == ",": - self.i += 1 - continue - self._ws(nl=True) - if self.i < self.n and self.s[self.i] == "]": - self.i += 1 - return out - self._fail("数组里逗号或 ] 丢了") - - def _inline_table(self) -> dict: - self.i += 1 - out: dict = {} - while True: - self._ws(nl=True) - if self.i >= self.n: - self._fail("inline table 没有闭合 }") - if self.s[self.i] == "}": - self.i += 1 - return out - key, value = self._keyval() - out[key] = value - self._ws(nl=True) - if self.i < self.n and self.s[self.i] == ",": - self.i += 1 - continue - self._ws(nl=True) - if self.i < self.n and self.s[self.i] == "}": - self.i += 1 - return out - self._fail("inline table 里逗号或 } 丢了") +def _load_report_toml(path: Path) -> dict: + """读报告 TOML:统一走 config.load_toml。 + 3.11+ 走标准库 tomllib,3.10 走仓内那份严格兜底解析器 —— 两条路径 + 读出同一个结果、对坏文件给出同一个结论。 -def _load_report_toml(path: Path) -> dict: - """读报告 TOML:优先 factscribe.config.load_toml;3.10 才走兜底解析器。""" - if getattr(_config, "_tomllib", None) is not None: - try: - return load_toml(path) - except ConfigError as exc: - raise ReportError("报告 TOML 读不了:%s" % exc, code="BAD_TOML") - try: - text = path.read_text(encoding="utf-8") - except OSError as exc: - raise ReportError("报告读不了:%s" % exc, code="FILE_NOT_FOUND") + 为什么不再留一份 3.10 专用解析器:旧代码在 3.10 上另起炉灶写了一份 + 宽松解析器(只为认 inline table),那份是**宽松**的:坏表头当表名收下、 + 裸词当字符串收下、重复键默默覆盖 —— 同一份坏报告在 3.10 上"能读", + 在 3.11+ 上被拒,两种解释器两个结论。现在仓内兜底解析器既严格又认 + inline table,这层分叉没有存在理由了。 + """ try: - return _MiniToml(text).parse() - except ValueError as exc: - raise ReportError("报告 TOML 解析失败:%s" % exc, code="BAD_TOML") + return load_toml(path) + except ConfigError as exc: + raise ReportError("报告 TOML 读不了:%s" % exc, code="BAD_TOML") # -------------------------------------------------------------------------- diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/safepath.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/safepath.py new file mode 100644 index 00000000..42ae8ae4 --- /dev/null +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/safepath.py @@ -0,0 +1,219 @@ +# -*- coding: utf-8 -*- +"""写盘落点闸:写入目标经软链解析后越出项目根 → 拒写(不落盘、不留半截)。 + +为什么写侧也要有闸:读侧已经守住「事实账的真实目标不得越出项目根」 +(`FACT_FILE_OUTSIDE_PROJECT`,red / exit 5;读侧见 +`fix/facts-symlink-outside-20261125`),但写侧此前没有对应的闸—— +`fact add` 直接 `write_bytes`,账本文件是指向项目外的软链时, +写入就跟着软链落到项目外去了。本模块把同一条信任根规则用在写侧: +落点越界就拒写,错误可预期(不是 traceback,不是 exit 4),拒绝时 +不删、不覆盖、不留临时文件,也不留 .bak。 + +判定口径只有一份(写侧与读侧同一套 realpath 规则): + +* 落点存在(含软链、含断链)→ 解析它的真实目标; +* 落点还不存在 → 解析它爹目录的真实位置,再拼上文件名 + (目录本身是软链的话,新文件就落在软链那边); +* 真实目标**解不出来**(成环是最常见的那种)→ 落点不可解 + (`FACT_FILE_UNRESOLVED`),同样拒写。 + +「解不出来」的判据取**语义**,不拿某个 errno 常量当白名单——各平台写 +errno 的口径不一样(Windows 真机实测:成环抛的是 +`OSError(winerror=1921, errno=22 EINVAL)`,不是 POSIX 的 `ELOOP`; +Windows 的 `errno.ELOOP` 常量还是 10062,跟这里收到的 errno 不是一回事)。 +拿 errno 白名单判,Windows 上写侧成环就会漏判 → 退成 exit 4(工具内部 +错误),而不是 `FACT_FILE_UNRESOLVED` / exit 5。 + +用 `os.path.realpath` 而不是 `Path.resolve()`:后者在软链成环时 +3.10–3.12 抛 RuntimeError、3.13+ 不抛,跨版本读数会漂(读侧同因)。 + +两个入口,两个码(各有各的对象,不混): + +* `guard_facts_write`:事实账文件(`facts/*.toml`)——与读侧同一对象、 + 同一现象(真实目标越出项目根),**复用读侧已登记的码**, + severity / exit 一律不动(red / exit 5); +* `guard_project_write`:其它项目内写盘(图表、登记表、证据锁、声明文件…)—— + 不是事实账,是另一个对象,复用仓里既有的写侧越界码 `PATH_ESCAPE` + (章节写回、资产通道在用),exit 2(配置/用法层),不新增码。 +""" +from __future__ import annotations + +import errno +import os +from pathlib import Path + +from .config import ConfigError +from .constants import EXIT_INTEGRITY + +# 事实账写盘被拒时的两个码:与读侧同一对(红、exit 5),severity/exit 不动。 +CODE_FACTS_OUTSIDE = "FACT_FILE_OUTSIDE_PROJECT" +CODE_FACTS_UNRESOLVED = "FACT_FILE_UNRESOLVED" +# 其它项目内写盘:仓里既有的写侧越界码(章节写回 / 资产通道在用)。 +CODE_PATH_ESCAPE = "PATH_ESCAPE" + + +class WriteRefused(ConfigError): + """写盘被拒(落点越出项目根):拒写,不落盘,不留半截文件。 + + `exit_code` 让命令层按码分层退出:事实账是信任链失败(exit 5), + 不是配置错(exit 2),也不是工具内部错误(exit 4)。 + """ + + def __init__(self, message: str, code: str, + exit_code: int = EXIT_INTEGRITY): + super().__init__(message, code=code) + self.exit_code = exit_code + + +def _real(path: Path) -> 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 + + +# 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)。 +# 所以「成环」的判据不能写成 `exc.errno == errno.ELOOP`。 +_WINERROR_CANT_RESOLVE_FILENAME = 1921 + + +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, cycle_detail: str = "") -> str: + """落点不可解的一句人话(为什么算不出来)。 + + 判据是**语义**:「strict realpath 解不出来」就是不可解——成环只是其中 + 最常见的一种。各平台写 errno 的口径会变(见上面那段实测),拿 errno + 白名单判必然在某个平台上漏判 → 写侧成环退成 exit 4(工具内部错误), + 而不是 `FACT_FILE_UNRESOLVED` / exit 5。能判出是成环就直说成环, + 判不出就说「算不出来」,不编原因。 + + `cycle_detail` 是成环时补的那半句:两个入口的原话口径不同(事实账 + 那条原来写「是成环软链,真实落点算不出来」,别的项目内写盘那条原来 + 写「是成环软链」),补在参数里,两边的原话一个字节都不动。 + """ + if _is_cycle(exc): + return "是成环软链" + cycle_detail + detail = exc.strerror or str(exc) + return "真实落点算不出来(%s)" % detail + + +def landing_point(target: Path) -> 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 _parent_unresolved(path: Path) -> bool: + """落点的爹目录本身是断链软链——写不进去。 + + 这种落点 `mkdir(exist_ok=True)` 会抛 FileExistsError(命令层退成 exit 4 + 的内部错误),不是「明确拒写」。这里提前判成「落点不可解」。 + """ + parent = Path(path).parent + return parent.is_symlink() and not parent.is_dir() + + +def _root_real(root: Path) -> str: + """项目根的真实位置(项目根本身可以是软链,macOS 的 /tmp 就是)。""" + return os.path.realpath(str(root), strict=False) + + +def _outside(root_real: str, real: str) -> bool: + """落点是否越出项目根。""" + try: + Path(real).relative_to(Path(root_real)) + except ValueError: + return True + return False + + +def guard_facts_write(root: Path, target: Path, *, rel: str = "") -> None: + """事实账写盘闸:落点越出项目根 → 拒写。 + + 越界 → `FACT_FILE_OUTSIDE_PROJECT`(red,exit 5,与读侧同一码); + 软链成环 → `FACT_FILE_UNRESOLVED`(red,exit 5,与读侧同一码)。 + 两个码都是读侧已登记的,severity / exit 一律不动。 + """ + path = Path(target) + name = rel or path.name + try: + real = landing_point(path) + except OSError as exc: + # 落点解不出来(成环等)= 不可解:判红、拒写、exit 5。 + # 判据按语义(解不出来就是不可解),不按 errno 白名单—— + # Windows 上成环是 winerror=1921/errno=EINVAL,白名单判不到它, + # 漏判就退成 exit 4(工具内部错误),坏了退出码与判定码的契约。 + raise WriteRefused( + "事实账写入落点不可解:%s %s——" + "拒绝写入(没有落盘,也没有改原文件)" + % (name, _unresolved_reason(exc, ",真实落点算不出来")), + CODE_FACTS_UNRESOLVED) + if _parent_unresolved(path): + raise WriteRefused( + "事实账写入落点不可解:%s 所在的目录是断链软链——" + "拒绝写入(没有落盘,也没有改原文件)" % name, + CODE_FACTS_UNRESOLVED) + if _outside(_root_real(root), real): + raise WriteRefused( + "事实账写入落点越出项目根:%s → %s(真实目标在项目外)——" + "拒绝写入(没有落盘,也没有改原文件);" + "把软链指回项目内,或改项目声明里的 facts 路径" % (name, real), + CODE_FACTS_OUTSIDE) + + +def guard_project_write(root: Path, target: Path, *, what: str = "", + rel: str = "") -> None: + """其它项目内写盘闸:落点越出项目根 → 拒写(`PATH_ESCAPE`,exit 2)。 + + 与事实账不是同一个对象(不是 `facts/*.toml`),所以不套事实账的码: + 仓里既有的写侧越界码是 `PATH_ESCAPE`(章节写回、资产通道在用)。 + """ + path = Path(target) + name = rel or path.name + label = what or "写盘" + try: + real = landing_point(path) + except OSError as exc: + # 同一族:解不出来=不可解,按语义判(跨平台同一口径,见 + # `_unresolved_reason`)。不许让 OSError 裸崩成 exit 4。 + raise ConfigError( + "%s落点不可解:%s %s——拒绝写入(没有落盘)" + % (label, name, _unresolved_reason(exc)), code=CODE_PATH_ESCAPE) + if _parent_unresolved(path): + raise ConfigError( + "%s落点不可解:%s 所在的目录是断链软链——拒绝写入(没有落盘)" + % (label, name), code=CODE_PATH_ESCAPE) + if _outside(_root_real(root), real): + raise ConfigError( + "%s落点越出项目根:%s → %s——拒绝写入(没有落盘,也没有改原文件)" + % (label, name, real), code=CODE_PATH_ESCAPE) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/samples.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/samples.py index 95ad5dad..6bf6e09b 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/samples.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/samples.py @@ -62,14 +62,28 @@ def is_guide_path(path) -> bool: def install_guide_sample(reset: bool = False) -> dict: - """把示例装到 `~/.factscribe/samples/guide`。 + """把示例装到 `~/.factscribe/samples/guide`(旧宿主形态的落点)。 返回 `{"path": str, "created": bool, "reset": bool}`: `created` 表示「这一次调用真的写了目录」(新建或重置后重装), 已存在且没要求重置时为 False(什么都没动)。 """ + return install_guide_sample_into(guide_target(), reset=reset) + + +def install_guide_sample_into(target: Path | str, reset: bool = False) -> dict: + """把示例装到**指定目录**。 + + 与 :func:`install_guide_sample` 的差别只有落点:那个固定落在 + `~/.factscribe/samples/guide`(用户自己挑目录打开);这个落在调用方 + 给的目录——段落级工作台把它装进工作根下面,装完示例就在项目列表里, + 点开就能看。 + + 规矩不变:只写这一个目录,用户的论文一个字都不动;已存在且没要求 + reset 时原样返回,不覆盖用户在这份示例里改过的东西。 + """ source = guide_source() - target = guide_target() + target = Path(target) if not source.is_dir(): raise SampleError("内置示例不在包里:%s" % source, code="SAMPLE_MISSING", status=500) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/scaffold.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/scaffold.py index 07aea916..ad9e8677 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 .safepath import guard_facts_write, guard_project_write from .textio import read_text_exact, to_lf LANGS = ("zh", "en") @@ -404,6 +405,15 @@ def init_project(root: Path, *, title: str | None = None, files = _render(lang, clean_title, clean_author) overwritten = [name for name in files if (root / name).is_file()] + # 写侧落点闸:七个落点全查一遍再落盘——软链绕出去就拒写,不落盘,也不 + # 留下半副骨架。闸在 mkdir 之前:目录本身是软链时,mkdir 会把目录建在 + # 软链那边去;拒写时连目标目录都不必先建出来。 + for name in files: + dest = root / name + if name == FACTS_FILE: + guard_facts_write(root, dest, rel=name) + else: + guard_project_write(root, dest, what="项目骨架", rel=name) root.mkdir(parents=True, exist_ok=True) for name, text in files.items(): dest = root / name @@ -731,6 +741,15 @@ def prepare_fact(root: Path, *, fid: str, claim: str, value: str, "V3 的审批目标请按 SPEC-V3.0 写在 schema 声明里)") known = load_facts(cfg) ledger_path, ledger_explicit = resolve_ledger(root, cfg, ledger) + # 写侧信任根闸:账本的真实目标越出项目根就拒写——不落盘、不留半截文件。 + # 与读侧同一对码(FACT_FILE_OUTSIDE_PROJECT / FACT_FILE_UNRESOLVED, + # red / exit 5),severity 与 exit 一律不动。闸在其它内容校验之前: + # 落点越界是信任根缺口,先说它,别让内容校验盖住它。 + try: + ledger_rel = ledger_path.relative_to(root).as_posix() + except ValueError: + ledger_rel = ledger_path.name + guard_facts_write(root, ledger_path, rel=ledger_rel) if ledger_path.is_file(): load_toml(ledger_path) # 账坏了就别往上追加 @@ -787,7 +806,7 @@ def prepare_fact(root: Path, *, fid: str, claim: str, value: str, "derived_from": parents, "expr": expr, "note": str(note or "").strip(), - "ledger": ledger_path.relative_to(root).as_posix(), + "ledger": ledger_rel, "ledger_explicit": ledger_explicit, # source_path=产物在盘上的绝对路径(提案那侧要读它核对 value)。 # add_fact 会把它摘掉——CLI 的输出形状一个字不变。 diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/serve.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/serve.py index a49bfe2b..4ec25da5 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/serve.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/serve.py @@ -23,7 +23,7 @@ import tempfile from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from urllib.parse import parse_qs, urlparse +from urllib.parse import parse_qs, unquote, urlparse from .citeview import citations_data from .citeedit import citation_add_data, citation_delete_data @@ -38,11 +38,13 @@ 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, +from .workbench import (SectionError, add_fact_data, apply_section_proposal, + audit_data, brief_data, create_section_data, + create_section_proposal, delete_section_data, evidence_status_data, freeze_evidence_data, project_data, rename_section_data, status_data, unfreeze_evidence_data, write_section_data) +from .workbench.proposal import ProposalError LOOPBACK_HOSTS = {"127.0.0.1", "localhost"} WEB_DIR = Path(__file__).resolve().parent / "web" @@ -53,6 +55,22 @@ "/app.css": ("app.css", "text/css; charset=utf-8"), } +# 第 ④ 步:旧节级网页前端(factscribe/web/)已下线。GET / 这条闸**留着**—— +# 它是集成件自带页面的挂载点(legal 集成件在用)——但仓里自己的旧页面已经 +# 不在了,所以静态件读不到时不再抛 500(那是"服务端坏了"的读数,而页面是 +# 故意退场的),改成一句实话:页面没了,请去段落级工作台。 +UI_RETIRED_NOTE = ("旧网页前端已按第 ④ 步下线,请用 miniapp 段落级工作台 " + "/ legal 工作台。") +# 法律侧工作台页面(静态件;住在 legal 集成件自己的 web/ 目录里, +# 不在 factscribe/web/——那个节级前端按已定口径第 ④ 步要废弃) +_LEGAL_UI_TYPES = { + ".html": "text/html; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".json": "application/json; charset=utf-8", + ".svg": "image/svg+xml", +} + # 预览要能真的看见论文里的图:只放行这些扩展名,其余一律 ASSET_INVALID。 ASSET_CONTENT_TYPES = { ".png": "image/png", @@ -71,11 +89,13 @@ # REPORT_EXISTS 409 目标报告已存在 # CITATION_EXISTS 409 这个引用 key 已经有了 # CITATION_MISSING 404 找不到这条引用 +# BLOCK_STALE 409 指纹闸:这节在别处被改过,别覆盖(口径 3 补的闸) _STATUS_BY_CODE = { "READ_ONLY": 403, "REPORT_EXISTS": 409, "CITATION_EXISTS": 409, "CITATION_MISSING": 404, + "BLOCK_STALE": 409, } @@ -96,8 +116,9 @@ def _send(self, code: int, payload: dict) -> None: self.end_headers() self.wfile.write(body) - def _send_bytes(self, body: bytes, content_type: str) -> None: - self.send_response(200) + def _send_bytes(self, body: bytes, content_type: str, + status: int = 200) -> None: + self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") @@ -183,8 +204,23 @@ def do_GET(self) -> None: # noqa: N802 - stdlib signature try: self._send_bytes((WEB_DIR / name).read_bytes(), content_type) except OSError: - self._error(500, "INTERNAL", "UI 文件缺失:%s" % name) + # 旧页面是退场的,不是坏了:给一句实话(404),别抛 500。 + self._send_bytes(UI_RETIRED_NOTE.encode("utf-8"), + "text/plain; charset=utf-8", status=404) + return + if self.server.serve_ui and path in ("/legal", "/legal/"): # type: ignore[attr-defined] + self._legal_ui("index.html") return + if self.server.serve_ui and path.startswith("/legal/"): # type: ignore[attr-defined] + self._legal_ui(path[len("/legal/"):]) + return + # /legal(无尾斜杠)时,页面里的相对资源被 解析到根路径, + # 所以根上也托管一份同名静态件:/legal.css、/legal.js 两个 URL 都拿得到。 + if self.server.serve_ui and path.startswith("/legal."): # type: ignore[attr-defined] + tail = path[len("/legal."):] + if "." + tail in _LEGAL_UI_TYPES: + self._legal_ui("legal." + tail) + return if path == "/api/health": self._send(200, {"ok": True, "tool": "factscribe", "version": VERSION, "service": "workbench"}) @@ -241,6 +277,9 @@ def do_GET(self) -> None: # noqa: N802 - stdlib signature if path == "/api/asset": self._asset() return + if path.startswith("/api/legal/"): + self._legal_route(path[len("/api/legal/"):]) + return self._error(404, "NOT_FOUND", "没有这个接口:%s" % path) except ConfigError as exc: self._fail_config(exc) @@ -262,6 +301,14 @@ def do_POST(self) -> None: # noqa: N802 - stdlib signature "需要 Bearer token(Authorization 或 X-FactScribe-Token)") return try: + if path == "/api/legal/proposals": + # 待批提案:**只建单,不写盘**(法律闸没有写路径)。 + self._legal_proposal_create() + return + hit = re.match(r"^/api/legal/proposals/([^/]+)/adopt$", path) + if hit: + self._legal_proposal_adopt(unquote(hit.group(1))) + return if path == "/api/projects": self._projects_add() return @@ -284,6 +331,12 @@ def do_POST(self) -> None: # noqa: N802 - stdlib signature "/api/sections/delete"): self._sections_crud(path) return + if path == "/api/sections/propose": + self._propose_section() + return + if path == "/api/sections/propose/confirm": + self._confirm_section_proposal() + return if path == "/api/evidence/freeze": body = self._body() data = freeze_evidence_data( @@ -346,6 +399,9 @@ def do_POST(self) -> None: # noqa: N802 - stdlib signature except SampleError as exc: # 示例安装:500 = 包里没有示例 / 复制失败。 self._error(exc.status, exc.code, str(exc)) + except ProposalError as exc: + # 提议单:400/404/409/500 由提议单自己带(PROPOSAL_*)。 + self._error(exc.status, exc.code, str(exc)) except ConfigError as exc: self._fail_config(exc) except ReportError as exc: @@ -357,6 +413,14 @@ def do_POST(self) -> None: # noqa: N802 - stdlib signature def do_PUT(self) -> None: # noqa: N802 - stdlib signature path = urlparse(self.path).path + # 同源闸:四个 HTTP 方法里 do_PUT 原先独缺这一道(GET/POST/DELETE + # 都有)。PUT /api/sections 是唯一覆盖论文正文 .tex 的写接口, + # 缺这道闸=任意页面可跨源改写正文。语义与其它三处一致: + # 没有 Origin 头放行;带了 Origin 但不是本监听地址就拒。 + if not self._origin_ok(): + self._error(403, "CROSS_ORIGIN", + "跨源请求不接:只允许本监听地址(同源)") + return if not self._authorized(): self._error(401, "UNAUTHORIZED", "需要 Bearer token(Authorization 或 X-FactScribe-Token)") @@ -523,11 +587,37 @@ def _project_view(self) -> None: def _write_section(self) -> None: body = self._body() + # expect_sha:客户端所基于的那一版正文的指纹(口径 3 补的指纹闸)。 + # 带了就对不上拒写(409 BLOCK_STALE);不带就走老路(裸覆盖)。 data = write_section_data( self._project(), str(body.get("file") or ""), - body.get("text"), self.server.allow_write) # type: ignore[attr-defined] + body.get("text"), self.server.allow_write, # type: ignore[attr-defined] + str(body.get("expect_sha") or "")) self._send(200, self._base("write_section", **data)) + def _propose_section(self) -> None: + """建一张节级改稿提议单(**不碰正文**)——口径 7:AI 采纳走提议单。 + + 人确认(POST /api/sections/propose/confirm)之后才写回;提议之后 + 正文被别处改过,指纹对不上就拒写。 + """ + body = self._body() + record = create_section_proposal( + self._project(), str(body.get("file") or ""), + str(body.get("text") or ""), + str(body.get("expect_sha") or ""), + str(body.get("source") or ""), + str(body.get("rationale") or "")) + self._send(200, self._base("sections_propose", **record)) + + def _confirm_section_proposal(self) -> None: + """人点确认之后才写回(指纹闸在写回那一刻再核一遍)。""" + body = self._body() + pid = str(body.get("id") or body.get("proposal") or "") + data = apply_section_proposal(self._project(), pid, + self.server.allow_write) # type: ignore[attr-defined] + self._send(200, self._base("sections_propose_confirm", **data)) + def _add_fact(self) -> None: body = self._body() data = add_fact_data(self._project(), body, @@ -756,6 +846,158 @@ def _brief(self, section: str | None) -> None: data = brief_data(self._project(), section) self._send(200, self._base("brief", **data)) + # ------------------------------------------------------------------ legal + # 法律侧只读路由(factscribe-legal 接口层;legal 专属前缀,与论文侧路由 + # 不冲突)。全部**只读**:不写盘、不下判定(红黄码照抄各闸,退出码语义 + # 不因这一层改变)。集成件没装 ⇒ 501 说清原因,不给空壳假接口。 + + def _legal_api(self): + """载入 legal 接口层(integrations/factscribe-legal);装不上 → None。""" + try: + from factscribe import checks + checks.load_integration("legal") + except Exception: # noqa: BLE001 —— 集成件坏掉不该把服务带崩 + return None + try: + from factscribe_legal import api as legal_api + except ImportError: + return None + return legal_api + + def _legal_route(self, rest: str) -> None: + """legal 路由分发:七路通道 + 第 ② 步补的四条读侧视图。 + + 全部**只读**:不写盘、不下判定(红黄码照抄各闸,退出码语义不因 + 这一层改变)。没有这条路由就 404——不留空壳假接口。 + """ + api = self._legal_api() + if api is None: + self._error(501, "LEGAL_UNAVAILABLE", + "legal 集成件不可用(integrations/factscribe-legal 没装或" + "装不上)——法律侧接口不提供") + return + query = parse_qs(urlparse(self.path).query) + + def one(key): + return (query.get(key) or [None])[0] + + ctx = api.context_from_project(str(self._project())) + + # ---- 读侧视图(第 ② 步补的四条)---- + if rest.startswith("corpus/"): + item_id = unquote(rest[len("corpus/"):]) + data = api.build_view(ctx, "corpus_item", item_id=item_id, + domain=one("domain") or "") + if data is None: + self._error(404, "NOT_FOUND", "语料里没有这件:%s" % item_id) + return + self._send(200, self._base("legal.corpus_item", contract=data)) + return + if rest == "document": + data = api.build_view(ctx, "document") + self._send(200, self._base("legal.document", contract=data)) + return + if rest.startswith("provision/"): + hit = re.match(r"^provision/([^/]+)/facts$", rest) + if not hit: + self._error(404, "NOT_FOUND", "没有这个法律侧接口:%s" % rest) + return + data = api.build_view(ctx, "provision_facts", + num=unquote(hit.group(1))) + self._send(200, self._base("legal.provision_facts", contract=data)) + return + if rest == "cli": + data = api.build_view(ctx, "cli") + self._send(200, self._base("legal.cli", contract=data)) + return + + # ---- 七路通道(版本化契约)---- + channel = rest + if channel != "contract" and channel not in api.CHANNELS: + self._error(404, "NOT_FOUND", "没有这个法律侧接口:%s" % channel) + return + filters = {} + for key in ("country", "domain", "state", "kind", "severity"): + val = one(key) + if val: + filters[key] = val + line = one("line") + channels = None if channel == "contract" else [channel] + contract = api.build_contract(ctx, channels=channels, filters=filters, + line_ids=[line] if line else None) + self._send(200, self._base("legal.%s" % channel, contract=contract)) + + def _legal_ui(self, name: str) -> None: + """法律侧工作台页面(静态件;住在**段落级前端体系**的 + factscribe/workbench/static/legal/ 下——法律页是段落级工作台的一个 + 视图,不是独立的另一套界面)。""" + api = self._legal_api() + if api is None: + self._error(501, "LEGAL_UNAVAILABLE", + "legal 集成件不可用(integrations/factscribe-legal 没装或" + "装不上)——法律侧页面不提供") + return + root = (Path(__file__).resolve().parent / "workbench" / "static" + / "legal") + target = (root / name).resolve() + try: + target.relative_to(root) + except ValueError: + self._error(404, "NOT_FOUND", "没有这个法律侧页面文件") + return + if not target.is_file(): + self._error(404, "NOT_FOUND", "没有这个法律侧页面文件:%s" % name) + return + ctype = _LEGAL_UI_TYPES.get(target.suffix.lower(), + "application/octet-stream") + self._send_bytes(target.read_bytes(), ctype) + + def _legal_proposal_create(self) -> None: + """建一张待批提议单(**只建单,不写盘**)。""" + api = self._legal_api() + if api is None: + self._error(501, "LEGAL_UNAVAILABLE", + "legal 集成件不可用——法律侧提议单不提供") + return + body = self._body() + ctx = api.context_from_project(str(self._project())) + try: + record = api.create_proposal( + ctx, str(body.get("kind") or ""), body.get("target") or {}, + body.get("payload") or {}, str(body.get("before_sha") or "")) + except Exception as exc: # noqa: BLE001 —— proposals.ProposalError + code = getattr(exc, "code", "PROPOSAL_INVALID") + self._error(409 if code == "PROPOSAL_STALE" else 400, code, + str(exc)) + return + self._send(201, self._base( + "legal.proposal", + contract={"version": api.API_VERSION, "view": "proposal", + "proposal": record})) + + def _legal_proposal_adopt(self, pid: str) -> None: + """采纳一张提议单:过指纹闸才过;**不写任何文件**。""" + api = self._legal_api() + if api is None: + self._error(501, "LEGAL_UNAVAILABLE", + "legal 集成件不可用——法律侧提议单不提供") + return + ctx = api.context_from_project(str(self._project())) + try: + record = api.adopt_proposal(ctx, pid) + except Exception as exc: # noqa: BLE001 —— proposals.ProposalError + code = getattr(exc, "code", "PROPOSAL_INVALID") + self._error(409 if code == "PROPOSAL_STALE" else 400, code, + str(exc)) + return + if record is None: + self._error(404, "NOT_FOUND", "没有这张提议单:%s" % pid) + return + self._send(200, self._base( + "legal.proposal", + contract={"version": api.API_VERSION, "view": "proposal", + "proposal": record})) + def _audit(self) -> None: data = audit_data(self._project()) code = int(data.pop("exit")) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/style.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/style.py index 007716c5..08981b21 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/style.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/style.py @@ -3080,7 +3080,8 @@ def analyze(cfg: Config, sections: list[tuple[str, str]], rules: dict, stage: str = STAGE_DRAFT, rule_report: dict | None = None ) -> StyleResult: - # 分析入口归一行尾(读盘侧按原样读,CRLF 不丢):归一的是内存副本。 + # 分析入口归一行尾(见 checks.run_packages 同款口径):读盘侧按原样读, + # 分析层按行做事;归一的是内存副本,磁盘字节不动。 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]]) 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 8e042d32..b88564a1 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/term_suggest.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/term_suggest.py @@ -24,6 +24,7 @@ from .textio import dominant_newline, read_text_exact, to_lf, write_text_exact from .terms import (load_glossary, key_of, normalize_surface, parse_glossary) +from .textio import dominant_newline, read_text_exact, to_lf, write_text_exact # -------------------------------------------------------------------------- # 语料收集 @@ -485,7 +486,7 @@ def json_payload(rows, root, min_count: int, min_sections: int) -> dict: def _read_candidates(path: Path) -> list[dict]: if not path.is_file(): raise ConfigError("候选文件不存在:%s" % path) - lines = [line for line in path.read_text(encoding="utf-8").splitlines() + lines = [line for line in read_text_exact(path).splitlines() if line.strip() and not line.lstrip().startswith("#")] if not lines: raise ConfigError("候选文件为空:%s" % path) diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/texscan.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/texscan.py index 8259bf25..eb2cfa63 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/texscan.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/texscan.py @@ -6,7 +6,7 @@ import re from dataclasses import dataclass, field -from .facts import THIN, _NUM_RE, canon_text, number_key +from .facts import THIN, _NUM_RE, canon_text, normalize_fullwidth_dot, number_key from .texrules import strip_comments_and_verbatim from .textio import split_lines @@ -622,6 +622,9 @@ def _extract_numbers(masked: str, original: str) -> list[dict]: offset = 0 for ln, line in enumerate(split_lines(masked), 1): toks: list[dict] = [] + # 全角小数点归一成半角(等长:列号、绝对偏移都不动)。全角写法 + # =半角写法,一个数不许被切成两个。 + line = normalize_fullwidth_dot(line) for m in _NUM_RE.finditer(line): raw, suffix, pct = m.group(1), m.group(2) or "", bool(m.group(3)) item = { diff --git a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textio.py b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textio.py index 33237313..5c9a36ef 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textio.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/textio.py @@ -30,6 +30,7 @@ """ from __future__ import annotations +from difflib import SequenceMatcher from pathlib import Path __all__ = [ @@ -154,35 +155,65 @@ def dominant_newline(text: str, default: str = "\n") -> str: 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 行; - * 原文末尾没有行尾的,新文末尾也不补。 + fallback: str | None = None) -> str: + r"""把 `new_text` 的行尾还原成 `original` 里各行**原有**的行尾。 + + 为什么需要它:编辑器交回来的正文恒是 LF——浏览器按 HTML 规范把 + `' + + '
      ' + + '
      ' + + '
      ' + + '建单只登记提议,不写盘。
      ' + + ""; + if (S.proposalMsg) { + html += '
      ' + + (S.proposalMsg.ok ? "" : "" + esc(S.proposalMsg.code || "接口错误") + ":") + + esc(S.proposalMsg.text) + "
      "; + } + html += '
      提议单列表(GET /api/legal/proposals)
      '; + if (!p) { + html += (st.state === "err") ? errBox(st, "") : + emptyPane("提议单未取到", "GET /api/legal/proposals 没有返回。", "GET /api/legal/proposals"); + } else { + var items = p.items || []; + if (!items.length) { + html += emptyPane("没有提议单", p.note || "proposals 通道的 items 为空。", ""); + } else { + html += '
      ' + items.map(function (it) { + var fp = it.fingerprint || {}; + var dec = it.decision || {}; + var statusBadge = it.status === "rejected" ? "red" : (it.status === "adopted_pending" ? "green" : "grey"); + var rows = ""; + rows += '
      ' + esc(it.id) + "" + + '' + esc(it.kind || MISSING) + "" + + '' + esc(it.status || MISSING) + "" + + '' + + '
      '; + var target = it.target || {}; + rows += '
      target:' + esc(JSON.stringify(target)) + "
      "; + rows += '
      before_sha:' + esc(isEmpty(it.before_sha) ? MISSING : it.before_sha) + + ' after_sha:' + esc(isEmpty(it.after_sha) ? MISSING : it.after_sha) + '
      '; + rows += '
      fingerprint:source ' + esc(isEmpty(fp.source) ? MISSING : fp.source) + + ' · current ' + esc(isEmpty(fp.current) ? MISSING : fp.current) + + ' · matches ' + esc(fp.matches === undefined ? MISSING : String(fp.matches)) + '
      '; + if (!isEmpty(dec.action) || !isEmpty(dec.reason)) { + rows += '
      decision:action ' + esc(isEmpty(dec.action) ? MISSING : dec.action) + + ' · write_path ' + esc(isEmpty(dec.write_path) ? MISSING : String(dec.write_path)) + + (isEmpty(dec.reason) ? '' : ' · ' + esc(dec.reason)) + '
      '; + } + var afterText = (it.status === "adopted_pending") + ? "已登记采纳意图 · 未写盘" + : ((it.status === "rejected") ? "已拒写(指纹闸拦下)" : "待采纳 · 未写盘"); + rows += '
      ' + + '
      现状(before_sha)
      ' + + esc(isEmpty(it.before_sha) ? MISSING : it.before_sha) + "
      " + + '
      指纹来源
      ' + + esc(isEmpty(fp.source) ? MISSING : fp.source) + "
      " + + '
      采纳后(' + esc(it.status || MISSING) + ")
      " + + '
      ' + esc(afterText) + "
      " + + '
      write_path
      ' + + esc(dec.write_path === undefined ? MISSING : String(dec.write_path)) + "
      "; + return '
      ' + rows + "
      "; + }).join("") + "
      "; + if (!isEmpty(p.note)) html += '
      后端注记:' + esc(p.note) + "
      "; + } + } + host.innerHTML = html; + } + + /* -------------------- 页脚:CLI -------------------- */ + function renderCli() { + var host = $("#cli-list"); + if (!S.token) { host.innerHTML = tokenNeeded(); return; } + var cli = S.data.cli; + if (!cli) { + var st = statusOf("cli"); + host.innerHTML = (st.state === "err") ? errBox(st, "CLI 清单来自 GET /api/legal/cli。") : + emptyPane("CLI 清单未取到", "GET /api/legal/cli 没有返回。", "GET /api/legal/cli"); + return; + } + var items = cli.items || []; + if (!items.length) { + host.innerHTML = emptyPane("CLI 清单为空", "cli 通道的 items 为空。", ""); + return; + } + host.innerHTML = '' + + '' + + items.map(function (c) { + var args = (c.args || []).map(function (a) { + return '' + esc(a.name) + (a.required ? "(必填)" : "") + "" + + (isEmpty(a.help) ? "" : ":" + esc(a.help)); + }).join("、"); + return '" + + '" + + "" + + '"; + }).join("") + "
      namegrouphelpargs
      ' + esc(c.name) + "' + esc(isEmpty(c.group) ? MISSING : c.group) + "" + esc(isEmpty(c.help) ? MISSING : c.help) + "' + (args ? args : MISSING) + "
      "; + } + + /* -------------------- 写动作(只有两个) -------------------- */ + async function createProposal() { + var kind = $("#p-kind").value; + var scope = $("#p-scope").value; + var target = { scope: scope }; + var fact = $("#p-fact").value.trim(); + var item = $("#p-item").value.trim(); + var source = $("#p-source").value.trim(); + if (fact) target.fact_id = fact; + if (item) target.item_id = item; + if (source) target.source = source; + var raw = $("#p-payload").value.trim(); + var payload = {}; + if (raw) { + try { payload = JSON.parse(raw); } + catch (e) { payload = { summary: raw }; } + } + var body = { kind: kind, target: target, payload: payload }; + var beforeSha = $("#p-beforesha").value.trim(); + if (beforeSha) body.before_sha = beforeSha; + var r = await apiRequest("/api/legal/proposals", "POST", body); + if (r.ok) { + S.proposalMsg = { ok: true, text: "提议单已建(不写盘):" + + JSON.stringify((r.payload && r.payload.contract && r.payload.contract.proposal) || r.payload) }; + toast("提议单已建(不写盘)"); + } else { + S.proposalMsg = { ok: false, code: r.code, text: r.message }; + toast("建单失败:" + r.code); + } + var again = await apiRequest("/api/legal/proposals", "GET"); + if (again.ok) { + applyChannel("proposals", again.payload); + setStatus("proposals", "ok", "", ""); + } else { + setStatus("proposals", "err", again.message, again.code); + } + renderAll(); + } + async function adoptProposal(id) { + var r = await apiRequest("/api/legal/proposals/" + encodeURIComponent(id) + "/adopt", "POST", {}); + if (r.ok) { + S.proposalMsg = { ok: true, text: "已登记采纳意图(未写盘:法律闸无写路径,等第③步真写路径)" }; + toast("已登记采纳意图(未写盘)"); + } else { + S.proposalMsg = { ok: false, code: r.code, text: r.message }; + toast("采纳被闸挡住:" + r.code); + } + var again = await apiRequest("/api/legal/proposals", "GET"); + if (again.ok) { + applyChannel("proposals", again.payload); + setStatus("proposals", "ok", "", ""); + } else { + setStatus("proposals", "err", again.message, again.code); + } + renderAll(); + } + + /* -------------------- 总渲染 -------------------- */ + function renderAll() { + renderStatusStrip(); + renderLocks(); + renderPaperLock(); + renderFilters(); + renderCorpusList(); + renderTimelinessSummary(); + renderSidenote(); + renderDetail(); + renderReceipts(); + renderKpis(); + renderIssues(); + renderCodes(); + renderDocument(); + renderProvisionFacts(); + renderProposals(); + renderCli(); + } + + /* -------------------- 事件 -------------------- */ + function bindEvents() { + $("#btn-token").addEventListener("click", function () { + var v = $("#token-input").value.trim(); + if (!v) { toast("请先粘贴 token"); return; } + S.token = v; + S.tokenFrom = "顶栏粘贴"; + toast("token 已放在内存里,开始取数"); + loadAll(); + }); + $("#token-input").addEventListener("keydown", function (e) { + if (e.key === "Enter") $("#btn-token").click(); + }); + $("#btn-refresh").addEventListener("click", function () { + if (!S.token) { toast("需要令牌"); return; } + loadAll(); + }); + document.addEventListener("click", function (e) { + var target = e.target; + if (!target || !target.closest) return; + var chip = target.closest(".chip[data-group]"); + if (chip) { + S.filters[chip.getAttribute("data-group")] = chip.getAttribute("data-val"); + renderFilters(); + renderCorpusList(); + renderTimelinessSummary(); + renderSidenote(); + return; + } + var item = target.closest(".citem[data-item]"); + if (item) { + S.selectedId = item.getAttribute("data-item"); + S.selectedDomain = item.getAttribute("data-domain") || ""; + S.receiptId = ""; + S.receiptLine = ""; + renderCorpusList(); + if (S.token) loadDetail(S.selectedId, S.selectedDomain); + else renderAll(); + return; + } + var cand = target.closest("[data-cand-domain]"); + if (cand) { + S.selectedDomain = cand.getAttribute("data-cand-domain") || ""; + S.selectedId = cand.getAttribute("data-cand-id") || S.selectedId; + if (S.token) loadDetail(S.selectedId, S.selectedDomain); + return; + } + var row = target.closest("tr[data-rid]"); + if (row) { + var rid = row.getAttribute("data-rid"); + S.receiptId = (S.receiptId === rid) ? "" : rid; + renderReceipts(); + renderDocument(); + var again = document.querySelector("tr[data-rid]"); + if (again) { /* 重新渲染后位置不变,无需滚动 */ } + return; + } + var mark = target.closest(".mark[data-mk]"); + if (mark) { + var key = mark.getAttribute("data-mk"); + if (!key) return; + S.receiptId = (S.receiptId === key) ? "" : key; + renderReceipts(); + renderDocument(); + return; + } + var lineChip = target.closest(".chip[data-line]"); + if (lineChip) { + S.receiptLine = lineChip.getAttribute("data-line"); + S.receiptId = ""; + renderReceipts(); + return; + } + var pid = target.closest("[data-pid]"); + if (pid) { + if (!S.token) { toast("需要令牌"); return; } + adoptProposal(pid.getAttribute("data-pid")); + return; + } + if (target.closest("#btn-prov")) { + if (!S.token) { toast("需要令牌"); return; } + loadProvisionFacts(); + return; + } + if (target.closest("#btn-prov-fill")) { + var numInput = $("#prov-num"); + if (!S.selectedId) { toast("先在左栏选一件语料"); return; } + if (numInput) numInput.value = S.selectedId; + toast("已带入选中件的 id(可自行改)"); + return; + } + var propose = target.closest("#btn-propose"); + if (propose) { + if (!S.token) { toast("需要令牌"); return; } + createProposal(); + return; + } + var tab = target.closest(".tab[data-tab]"); + if (tab) { + var which = tab.getAttribute("data-tab"); + $$(".tab[data-tab]").forEach(function (x) { + x.setAttribute("aria-selected", x.getAttribute("data-tab") === which ? "true" : "false"); + }); + $("#issues").hidden = which !== "issues"; + $("#codes-right").hidden = which !== "codes"; + } + }); + $("#prov-num").addEventListener("keydown", function (e) { + if (e.key === "Enter") { + if (!S.token) { toast("需要令牌"); return; } + loadProvisionFacts(); + } + }); + window.addEventListener("error", function (e) { + toast("页面脚本出错:" + (e && e.message ? e.message : "未知错误")); + }); + } + + + /* -------------------- 界面语言(中/EN)-------------------- + 基准:miniapp app.js:5379(#langSeg 点击切语言)。 + 范围:只切**静态外壳**文案;接口返回的文案(码的中文短名、注记、 + 错误原文)保持后端原样——后端给什么就显示什么,不替它翻译。 */ + var LANG_KEY = "factscribe.legal.lang"; + var I18N = { + zh: { + "brand.sub": "法律侧工作台 · FR 判例样板页", + "tb.readonly": "法律闸暂无写路径", + "tb.connect": "连接", + "tb.refresh": "刷新读数", + "tb.rerun": "重新核验", + "lock.legal.tag": "法律域锁", + "lock.legal.desc": "域级证据锁 · 四键闭集", + "lock.paper.tag": "论文锁", + "lock.paper.desc": "论文侧证据锁 · 另一把锁(不是上面这把)", + "status.title": "接口状态", + "rail.country": "国家 / 法域", + "rail.domain": "域(对应闸)", + "rail.kind": "件型", + "rail.state": "时效状态", + "rail.corpus": "语料(依据)", + "rail.tl": "时效状态分布", + "main.detail": "件详情", + "main.receipts": "事实账 · 逐条收据", + "main.receipts.hint": "列=契约 fields 顺序:id|sha16|span|face|how;点行展开", + "right.issues": "问题区", + "right.issues.hint": "红牌 / 黄牌 · 码用 codes 通道的中文短名", + "tab.issues": "问题清单", + "tab.codes": "判定码表", + "right.doc": "文书段落区(落点)", + "right.doc.hint": "带引证标记的段落 · 点标记 ⇄ 点收据 双向高亮", + "right.prov": "条 → 事实反查", + "right.prov.hint": "GET /api/legal/provision/{num}/facts · 条号由你给,本页不预置", + "right.prov.go": "反查", + "right.prov.fill": "用选中件的 id", + "right.prop": "待批提案", + "right.prop.hint": "建单 · 采纳只登记意图,不写盘", + "foot.cli": "法律侧 CLI 子命令(来自 GET /api/legal/cli)", + "foot.unmounted": "未挂载的接口(页面不调、不假装有)", + "foot.consume": "本页怎么消费接口" + }, + en: { + "brand.sub": "Legal workbench · FR case sample", + "tb.readonly": "No write path in the legal gate", + "tb.connect": "Connect", + "tb.refresh": "Refresh", + "tb.rerun": "Re-verify", + "lock.legal.tag": "Legal lock", + "lock.legal.desc": "Domain evidence lock · 4-key closed set", + "lock.paper.tag": "Paper lock", + "lock.paper.desc": "Paper-side evidence lock · a different lock (not the one above)", + "status.title": "Endpoint status", + "rail.country": "Country / jurisdiction", + "rail.domain": "Domain (gate)", + "rail.kind": "Kind", + "rail.state": "Timeliness", + "rail.corpus": "Corpus (evidence)", + "rail.tl": "Timeliness distribution", + "main.detail": "Item detail", + "main.receipts": "Fact ledger · receipts", + "main.receipts.hint": "Columns = contract fields order: id|sha16|span|face|how; click a row to expand", + "right.issues": "Findings", + "right.issues.hint": "Red / yellow cards · code labels come from the codes channel (Chinese, as returned)", + "tab.issues": "Findings", + "tab.codes": "Code table", + "right.doc": "Document segments (landing)", + "right.doc.hint": "Segments with citation markers · click a marker ⇄ click a receipt", + "right.prov": "Provision → facts", + "right.prov.hint": "GET /api/legal/provision/{num}/facts · the number is yours to type; nothing is preset here", + "right.prov.go": "Look up", + "right.prov.fill": "Use selected item id", + "right.prop": "Pending proposals", + "right.prop.hint": "Create a ticket · adopt only registers intent, writes nothing", + "foot.cli": "Legal CLI subcommands (from GET /api/legal/cli)", + "foot.unmounted": "Unmounted endpoints (the page neither calls nor pretends to have)", + "foot.consume": "How this page consumes the API" + } + }; + var S_LANG = "zh"; + function t(key) { + var dict = I18N[S_LANG] || I18N.zh; + return dict[key] || (I18N.zh[key] || key); + } + function applyLang(lang) { + S_LANG = (lang === "en") ? "en" : "zh"; + var dict = I18N[S_LANG] || I18N.zh; + $$("[data-i18n]").forEach(function (el) { + var k = el.getAttribute("data-i18n"); + if (dict[k]) el.textContent = dict[k]; + }); + document.documentElement.setAttribute("lang", S_LANG === "en" ? "en" : "zh-CN"); + $$("#langSeg button").forEach(function (b) { + b.classList.toggle("on", b.getAttribute("data-lang") === S_LANG); + }); + try { localStorage.setItem(LANG_KEY, S_LANG); } catch (e) { /* 无痕模式:存不下就算了 */ } + } + function initLang() { + var saved = ""; + try { saved = localStorage.getItem(LANG_KEY) || ""; } catch (e) { saved = ""; } + applyLang(saved === "en" ? "en" : "zh"); + var seg = $("#langSeg"); + if (!seg) return; + seg.addEventListener("click", function (ev) { + var btn = ev.target && ev.target.closest ? ev.target.closest("button[data-lang]") : null; + if (!btn) return; + applyLang(btn.getAttribute("data-lang")); + }); + } + + /* -------------------- 右栏宽度拖拽 -------------------- + 基准:miniapp app.js:5757-5827(NAVW_KEY;拖动实时变、松手才记)。 + 宽度是**本机界面偏好**,记在 localStorage,与项目数据无关。 */ + var NAVW_KEY = "factscribe.legal.navw"; + var NAVW_MIN = 300, NAVW_MAX = 680, NAVW_DEFAULT = 392; + function navWidth(raw) { + var w = parseInt(raw, 10) || 0; + if (!w) w = NAVW_DEFAULT; + return Math.min(NAVW_MAX, Math.max(NAVW_MIN, w)); + } + function initSplitter() { + var el = $("#nav-splitter"); + if (!el) return; + var saved = 0; + try { saved = localStorage.getItem(NAVW_KEY) || ""; } catch (e) { saved = ""; } + document.documentElement.style.setProperty("--nav-w", navWidth(saved) + "px"); + var dragging = false; + el.addEventListener("mousedown", function (ev) { + dragging = true; + document.body.classList.add("nav-dragging"); + ev.preventDefault(); + }); + window.addEventListener("mousemove", function (ev) { + if (!dragging) return; + var w = window.innerWidth - ev.clientX; + document.documentElement.style.setProperty("--nav-w", navWidth(w) + "px"); + }); + window.addEventListener("mouseup", function () { + if (!dragging) return; + dragging = false; + document.body.classList.remove("nav-dragging"); + var now = getComputedStyle(document.documentElement).getPropertyValue("--nav-w"); + try { localStorage.setItem(NAVW_KEY, String(navWidth(now))); } catch (e) { /* 忽略 */ } + }); + } + + /* -------------------- 启动 -------------------- */ + function init() { + var q = new URLSearchParams(window.location.search || ""); + var token = q.get("token"); + if (token && token.trim()) { + S.token = token.trim(); + S.tokenFrom = "URL 查询参数"; + $("#token-input").value = S.token; + } + initLang(); + initSplitter(); + bindEvents(); + renderAll(); + if (S.token) loadAll(); + } + + init(); +})(); 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 bc194f2c..c5c2945d 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/write.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench/write.py @@ -1359,16 +1359,27 @@ def _draft_insertion(source: str, block: Block, body: str) -> tuple[str, str, in 提议单与真写回共用这一份计算——差异卡上看到的落盘结果, 与人点确认后真正写进文件的那一份,是同一条路算出来的。 + + **行尾按所在文件走**(与 save_block 的 restore_newlines 同一套口径): + CRLF 稿子里插进去的草稿块也是 CRLF,不补出 LF 行;LF 稿子也不会被 + 改成 CRLF。新插进去的行没有「原来的行尾」可依——按**文件的主导行尾** + 补(restore_newlines 的 fallback 口径,不另造一套)。 + + 草稿**正文**一个字不改:只改行尾,不动内容。 """ marker = _next_draft_id(source) - region = _draft_region(marker, body) + eol = dominant_newline(source) + # 草稿块内部:每一行的行尾按文件的主导行尾落。走 restore_newlines + # 这条(与 save_block 同一条):没有原文可依 → 全部用 fallback, + # fallback 就是文件的主导行尾。 + region = restore_newlines(_draft_region(marker, body), "", fallback=eol) newline = source.find("\n", block.end) if newline == -1: insert_at = len(source) - insertion = "\n\n" + region + "\n" + insertion = eol + eol + region + eol else: insert_at = newline + 1 - insertion = "\n" + region + "\n" + insertion = eol + region + eol return marker, insertion, insert_at 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 40a08507..dd40cf26 100644 --- a/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench_dataplayer.py +++ b/plugins/unclemoc/factscribe/miniapp/node/engine/factscribe/workbench_dataplayer.py @@ -8,18 +8,24 @@ import os import re +import shutil +import time from pathlib import Path, PurePosixPath 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 .textio import read_text_exact, restore_newlines, write_text_exact from .evidence import (freeze_evidence, lock_check, log_state, read_lock, unfreeze_evidence, unfrozen_info) from .i18n import issue_dict from .report import _config_block, _severity_of from .scaffold import add_fact +from .workbench.projects import short_sha +from .workbench.proposal import (STATUS_APPLIED, STATUS_STALE, ProposalError, + new_id, read_proposal, resolve_proposal, + write_proposal) def _config_bits(cfg) -> dict: @@ -64,14 +70,14 @@ def project_data(project: Path | str, allow_write: bool = False, base = source_path(cfg, "").resolve() path = source_path(cfg, src).resolve() path.relative_to(base) - text = path.read_text(encoding="utf-8") + text = read_text_exact(path) except (OSError, ValueError, UnicodeDecodeError): text = "" source_rows[src] = {"id": src, "name": src, "text": text, "sha256": fact.source_sha256} bib_path = cfg.root / cfg.bib try: - bib = bib_path.read_text(encoding="utf-8") + bib = read_text_exact(bib_path) except (OSError, UnicodeDecodeError): bib = "" return { @@ -79,7 +85,10 @@ def project_data(project: Path | str, allow_write: bool = False, "build_allowed": bool(allow_build), "project": cfg.name or cfg.title, "root": str(cfg.root), - "sections": [{"file": rel, "text": text} for rel, text in sections], + # sha:这一节的指纹(sha256 hex 前 16 位)——客户端保存时带回来当 + # expect_sha,指纹闸据此拒写「在别处被改过」的节。 + "sections": [{"file": rel, "text": text, "sha": short_sha(text)} + for rel, text in sections], "facts": [{ "id": f.id, "claim": f.claim, "value": f.value, "source": f.source, "sourceSha256": f.source_sha256, @@ -123,8 +132,21 @@ def audit_data(project: Path | str, lang: str = "zh") -> dict: } +#: 指纹闸:客户端所基于的那一版正文与服务端现算的不一致 → 拒写(HTTP 409)。 +#: 段落级那条闸的同一个码(见 factscribe/workbench/write.py 的 BLOCK_STALE)。 +BLOCK_STALE_CODE = "BLOCK_STALE" + + def write_section_data(project: Path | str, file: str, text: str, - allow_write: bool = False) -> dict: + allow_write: bool = False, + expect_sha: str = "") -> dict: + """写一节正文(节级兼容层的写入口)。 + + **指纹闸**(口径 3 补的那道):客户端带 `expect_sha`(它所基于的那一版 + 正文的指纹)来,服务端现算的指纹对不上就拒写(`BLOCK_STALE`)——这节 + 在别处(另一个窗口/外部编辑器)已被改过,照单写回会覆盖别人的字。 + 不带 `expect_sha` 就走老路(裸覆盖),与段落级同一条闸的语义。 + """ _require_write(allow_write) cfg = load_config(Path(project)) rel = str(file or "").strip() @@ -147,11 +169,28 @@ def write_section_data(project: Path | str, file: str, text: str, if not rel.endswith(".tex"): raise ConfigError("只允许写 .tex 章节:%s" % rel) tmp = target.with_name(target.name + ".tmp") + # 落盘原文:这一节当前在盘上的字节(行尾原样)。 + try: + original = read_text_exact(target) + except (OSError, UnicodeDecodeError): + original = "" + # 指纹闸:对不上就拒写(409),不许覆盖别人的字。 + expect = str(expect_sha or "").strip() + if expect and expect != short_sha(original): + raise ConfigError("这一节在别处已被改动,请重新编辑。", + code=BLOCK_STALE_CODE) + # 行尾还原:浏览器的