diff --git a/.crabcode-plugin/marketplace.json b/.crabcode-plugin/marketplace.json index 956b89c..cb2b5d1 100644 --- a/.crabcode-plugin/marketplace.json +++ b/.crabcode-plugin/marketplace.json @@ -4,7 +4,7 @@ "name": "CrabCode" }, "metadata": { - "version": "0.4.3", + "version": "0.4.4", "description": "Official CrabCode plugin marketplace hosted at acosmi/CrabCode-Plugin." }, "plugins": [ @@ -1576,10 +1576,10 @@ { "name": "crabcode-media-ops", "source": "./plugins/crabcode-media-ops", - "version": "0.4.3", + "version": "0.4.4", "displayName": "CrabCode 新媒体运营", - "shortDescription": "【连接暂停】参考隔离、联网可信来源、原创审校与精排白底 HTML 交付", - "longDescription": "面向媒体与自媒体团队的可审计工作流:第三方参考原文隔离、可核验联网研究、公众号独立观点、工具生成的原创与编辑复核、快速/完整/增量风格表单、多平台适配、精排白底 HTML 主交付、Markdown 备份,以及绑定内容/渲染/产物字节的人工审批与冻结发布包。 安全状态:本版本不发布可执行 MCP 配置;安装不会启动该服务或发起网络请求。 现有说明描述目标能力,不代表当前已连接或可执行。", + "shortDescription": "参考隔离、联网可信来源、原创审校与精排白底 HTML 交付", + "longDescription": "面向媒体与自媒体团队的可审计工作流:第三方参考原文隔离、可核验联网研究、公众号独立观点、工具生成的原创与编辑复核、快速/完整/增量风格表单、多平台适配、精排白底 HTML 主交付、Markdown 备份,以及绑定内容/渲染/产物字节的人工审批与冻结发布包。 安装后需在插件设置中填写本机编辑者 ID 与显示名(local-editorial 低保证身份),随后 mediaops 本地服务自动启动;正式多人审批仍需宿主注入不同主体。", "defaultPrompt": [ "参考这篇文章但不要洗稿,联网核验后独立创作", "把这篇内容适配成小红书风格并生成白底 HTML 预览", @@ -1588,7 +1588,7 @@ "brandColor": "#8957e5", "composerIcon": "./assets/icon.png", "logo": "./assets/icon.png", - "description": "Governed media operations with clean-room references, verifiable research, originality gates, refined white HTML delivery and artifact-bound approval. Executable MCP configuration is intentionally paused in this release.", + "description": "Governed media operations with clean-room references, verifiable research, originality gates, refined white HTML delivery and artifact-bound approval. After install, fill in the local editor ID and display name in plugin settings (local-editorial low-assurance identity); the mediaops local server then starts automatically. Multi-person approval still requires the host to inject distinct principals.", "category": "media-ops", "tags": [ "media-ops", diff --git a/docs/audit/evidence/2026-09-12-mcp-restore/restore-inventory.json b/docs/audit/evidence/2026-09-12-mcp-restore/restore-inventory.json new file mode 100644 index 0000000..7ff82e7 --- /dev/null +++ b/docs/audit/evidence/2026-09-12-mcp-restore/restore-inventory.json @@ -0,0 +1,61 @@ +{ + "schemaVersion": 1, + "baselineId": "mcp-safe-baseline-v2-first-party-local", + "decision": "D-0(c)", + "date": "2026-09-12", + "restored": [ + { + "pluginId": "crabcode-media-ops", + "serverName": "mediaops", + "transport": "stdio", + "configPath": "plugins/crabcode-media-ops/.mcp.json", + "configSha256": "65c5afbf0b309ce88dfdadc274c44e366ca932281c0d5945d54255bb8105179f", + "previousVersion": "0.4.3", + "restoredVersion": "0.4.4", + "identityInjection": "local-editorial via host user_config" + } + ], + "stillPaused": [ + "asana", + "clangd-lsp", + "context7", + "crabcode-example-plugin", + "crabwork-bio-research", + "crabwork-customer-support", + "crabwork-data", + "crabwork-design", + "crabwork-engineering", + "crabwork-enterprise-search", + "crabwork-hr", + "crabwork-marketing", + "crabwork-operations", + "crabwork-product-management", + "crabwork-productivity", + "crabwork-sales", + "crabwork-small-business", + "csharp-lsp", + "discord", + "fakechat", + "firebase", + "github", + "gitlab", + "gopls-lsp", + "greptile", + "imessage", + "jdtls-lsp", + "kotlin-lsp", + "laravel-boost", + "linear", + "lua-lsp", + "php-lsp", + "playwright", + "pyright-lsp", + "ruby-lsp", + "rust-analyzer-lsp", + "serena", + "swift-lsp", + "telegram", + "terraform", + "typescript-lsp" + ] +} diff --git a/plugins/crabcode-media-ops/.crabcode-plugin/plugin.json b/plugins/crabcode-media-ops/.crabcode-plugin/plugin.json index a9cb9a9..495e14e 100644 --- a/plugins/crabcode-media-ops/.crabcode-plugin/plugin.json +++ b/plugins/crabcode-media-ops/.crabcode-plugin/plugin.json @@ -1,12 +1,26 @@ { "name": "crabcode-media-ops", - "version": "0.4.3", - "description": "Governed media operations for CrabCode: clean-room references, verifiable research, originality review, refined white HTML delivery, hash-bound approval, and frozen local publish packages. Executable MCP configuration is intentionally paused in this release.", + "version": "0.4.4", + "description": "Governed media operations for CrabCode: clean-room references, verifiable research, originality review, refined white HTML delivery, hash-bound approval, and frozen local publish packages.", "author": { "name": "CrabCode" }, "license": "Apache-2.0", - "requiredMcpServers": [], + "requiredMcpServers": ["mediaops"], + "userConfig": { + "principal_id": { + "type": "string", + "title": "本机编辑者 ID", + "description": "本机低保证身份声明(local-editorial),不是登录、也不做强身份认证:宿主把它注入 mediaops 服务,作为全部写入操作的可信主体 ID。建议使用稳定的英文短标识(例如 editor-01)。规则:去掉首尾空白后不能为空、不超过 180 个字符、不能包含控制字符。同一个 ID 不能充当需要第二个真人的审批/复核门(原创复核、编辑复核、审批决定、profile 确认),这些门禁会保持 pending。", + "required": true + }, + "principal_name": { + "type": "string", + "title": "编辑者显示名", + "description": "审计记录与报告中展示的人名或角色名(例如 张三 / 主编)。与本机编辑者 ID 一样,只是宿主注入的本机身份声明,不是登录凭据;服务端在取不到显示名时回退显示 ID 本身。", + "required": true + } + }, "keywords": [ "media-ops", "publishing", diff --git a/plugins/crabcode-media-ops/.mcp.json b/plugins/crabcode-media-ops/.mcp.json new file mode 100644 index 0000000..099171d --- /dev/null +++ b/plugins/crabcode-media-ops/.mcp.json @@ -0,0 +1,16 @@ +{ + "mcpServers": { + "mediaops": { + "command": "bun", + "args": ["--no-env-file", "--cwd", "${CRABCODE_PLUGIN_ROOT}", "${CRABCODE_PLUGIN_ROOT}/dist/server.js"], + "env": { + "MEDIAOPS_DATA_DIR": "${CRABCODE_PLUGIN_DATA}", + "MEDIAOPS_IDENTITY_MODE": "local-editorial", + "MEDIAOPS_TRUSTED_PRINCIPAL_ISSUER": "crabcode-local-editorial", + "MEDIAOPS_TRUSTED_PRINCIPAL_ID": "${user_config.principal_id}", + "MEDIAOPS_TRUSTED_PRINCIPAL_NAME": "${user_config.principal_name}", + "MEDIAOPS_TRUSTED_PRINCIPAL_ROLES": "author,reference_curator,researcher,fact_checker,originality_scanner,renderer,delivery_reviewer,profile_editor,approval_requester,publisher" + } + } + } +} diff --git a/plugins/crabcode-media-ops/README.md b/plugins/crabcode-media-ops/README.md index 8234836..b13a47a 100644 --- a/plugins/crabcode-media-ops/README.md +++ b/plugins/crabcode-media-ops/README.md @@ -1,14 +1,21 @@ -# crabcode-media-ops 0.4.3 +# crabcode-media-ops 0.4.4 -> **MCP 安全暂停(2026-08-22)**:安全状态:本版本不发布可执行 MCP 配置;安装不会启动该服务或发起网络请求。 本文保留目标能力与后续接入资料,不代表当前版本已连接或可执行。 +> **本机执行配置状态(2026-09-12,三仓根因修复裁决 D-0(c))**:本版本随包发布 `.mcp.json`,`requiredMcpServers: ["mediaops"]`,宿主安装后自动激活本机 stdio sidecar。安装后需在插件设置里填写“本机编辑者 ID / 显示名”,宿主经 `user_config` 注入 `local-editorial` 低保证主体;未填写时宿主显示“需要配置”,写入工具仍以 `AUTHENTICATION_REQUIRED` 安全失败。 可审计的新媒体运营插件:参考材料防火墙、联网可信来源研究、独立原创风险复核、创作者风格管理、精排白底 HTML 交付、可信身份约束的审批,以及冻结发布包。 -## 0.4.3 变更(MCP 紧急安全暂停) +## 0.4.4 变更(本机执行配置恢复 + QA 等级不混用) -- **发布面 fail-closed**:当前版本不发布 `.mcp.json`,`requiredMcpServers` 为空;安装或升级不会启动 mediaops sidecar,也不会由插件配置发起网络请求。 +- **发布面恢复**:`.mcp.json` 直接执行入库的 `dist/server.js`(`bun --no-env-file`),`requiredMcpServers: ["mediaops"]`;服务为本机 stdio,不含任何远程端点。该配置随 `crabcode-html-video` 一起进入第一方本机允许表,其余 41 个连接器继续暂停。 +- **身份注入**:`.mcp.json` 固定 `MEDIAOPS_IDENTITY_MODE=local-editorial` 与 `MEDIAOPS_TRUSTED_PRINCIPAL_ISSUER=crabcode-local-editorial`,主体 ID 与显示名来自宿主 `user_config`(两项都是 `required: true` —— 宿主在缺值时替换会抛错,且不会把声明里的 `default` 写进去)。授予的角色是除“第二真人门”以外的全部治理角色;`originality.review`、`editorial.review`、`approval.decide`、`profile.confirm` 仍保持 pending,不伪造多人治理。host-principal 仍是宿主未来的接线项。 +- **业务失败不再伪装成功**:MCP 工具结果对 `error` / `blocked` 两种信封状态带 `isError: true`,宿主与模型看到的是失败,而不是“成功返回一段错误 JSON”。 +- **QA 等级不混用**:`MEDIAOPS_QA_MODE=static` 的证据记为 `status: 'static'` / `mode: 'static'`,未跑的 Chromium/Nu 检查记为 `skipped` 而不是 `passed`;Media Gate 只接受 `mode='full'` 的证据放行审批,static 证据只支持本地草稿链路。 +- **版本单一真源**:runtime/serverInfo 从 `package.json` 派生 `0.4.4`,manifest、marketplace、package、dist 与 CycloneDX SBOM 同步。 + +## 0.4.3 历史变更(MCP 紧急安全暂停,已由 0.4.4 恢复) + +- **发布面 fail-closed**:该版本不发布 `.mcp.json`,`requiredMcpServers` 为空;安装或升级不会启动 mediaops sidecar,也不会由插件配置发起网络请求。 - **能力边界**:sidecar 源码与确定性测试继续保留,供本机验证和后续宿主 principal 合同验收;依赖 `mediaops.*` 的治理步骤必须以 `MCP_INACTIVE` / `GATE_NOT_EXECUTED` 停止,不能把手工替代写成已治理结果。 -- **版本单一真源**:runtime/serverInfo 从 `package.json` 派生 `0.4.3`,manifest、marketplace、package、dist 与 CycloneDX SBOM 同步。 ## 0.4.2 变更(分发验证硬化) @@ -16,7 +23,7 @@ - **dist Linux 字节确定性确证**:经精确 CI 容器(digest 锁定)本地复现,`check:distribution` 重建的 `dist/server.js` 与入库产物字节一致,像素级黄金截图与全套测试(109 单测 + 全 QA)全绿;本版 `dist/server.js` 以 Linux 容器权威重建。 - **运行时功能与 0.4.1 等价**:仅 `VERSION` 串更新与 dist 平台权威重建,无工具/schema/存储变化(工具数 38,`SCHEMA_VERSION=2` 不变)。 -## 0.4.1 历史变更(MCP 可用性修复,已由 0.4.3 暂停) +## 0.4.1 历史变更(MCP 可用性修复,经 0.4.3 暂停后于 0.4.4 恢复) - **生命周期声明**:manifest 增加 `requiredMcpServers: ["mediaops"]`,CrabCode ≥1.0.16 安装后自动激活本地 sidecar;用户显式 disable 始终优先。旧宿主上退化为 inactive,不崩溃。 - **自包含发行物**:`.mcp.json` 直接执行入库的 `dist/server.js`(`bun --no-env-file`),启动不再执行任何安装步骤,离线冷启动实测亚秒到 2 秒完成 initialize/tools/list。Playwright/axe/vnu 为交付 QA 的惰性可选依赖,缺失时基础 MCP 全量可用、`delivery.verify` full 模式返回 `DEPENDENCY_NOT_READY`(static 模式始终可用)。`bun run check:distribution` 校验发行物新鲜度并做清洁目录冷启动 smoke。 @@ -79,7 +86,7 @@ reference.register 1. `mcp_oauth`:宿主在 MCP `authInfo` 中提供未过期的 subject、issuer,以及 scopes 或 roles。这是多用户部署的首选模式。 2. `host_principal`:受信宿主显式设置 `MEDIAOPS_IDENTITY_MODE=host-principal`、`MEDIAOPS_TRUSTED_PRINCIPAL_ID`、`MEDIAOPS_TRUSTED_PRINCIPAL_ISSUER` 和 `MEDIAOPS_TRUSTED_PRINCIPAL_ROLES`。这是宿主配置断言,不是插件自行完成的登录或强身份认证。 -0.4.1 历史 `.mcp.json` 只配置数据目录,不伪造 principal;0.4.3 当前安全基线已移除该执行配置。未来恢复时,没有宿主身份注入的变更操作仍必须安全失败。请求人与批准人、作者与独立核查人等隔离比较的是可信 `issuer:principalId`;一个 host principal 即使拥有多个角色,也不能充当需要不同人的两端。正式多人审批应使用能为每位用户注入不同 subject 的 MCP OAuth 或等价宿主认证。 +0.4.1 历史 `.mcp.json` 只配置数据目录,不伪造 principal;0.4.3 安全基线移除了该执行配置;0.4.4 以 `local-editorial` + 宿主 `user_config` 注入主体的形式恢复它——主体 ID 与显示名由用户在插件设置中填写,插件自身不做任何认证,缺少注入时变更操作仍以 `AUTHENTICATION_REQUIRED` 安全失败。host-principal 仍是宿主未来的接线项。请求人与批准人、作者与独立核查人等隔离比较的是可信 `issuer:principalId`;一个 host principal 即使拥有多个角色,也不能充当需要不同人的两端。正式多人审批应使用能为每位用户注入不同 subject 的 MCP OAuth 或等价宿主认证。 角色按职责最小授权:`author`、`reference_curator`、`researcher`、`fact_checker`、`originality_scanner`、`originality_reviewer`、`editorial_reviewer`、`renderer`、`delivery_reviewer`、`profile_editor`、`profile_approver`、`approval_requester`、`approver`、`publisher`。服务端也识别 `mediaops:`、`mediaops:*` 和 `*`,但多人生产环境不应以通配角色代替职责隔离。 diff --git a/plugins/crabcode-media-ops/dist/server.js b/plugins/crabcode-media-ops/dist/server.js index 3b5721c..c08e0ab 100644 --- a/plugins/crabcode-media-ops/dist/server.js +++ b/plugins/crabcode-media-ops/dist/server.js @@ -10577,7 +10577,7 @@ var package_default; var init_package = __esm(() => { package_default = { name: "crabcode-media-ops-mcp", - version: "0.4.3", + version: "0.4.4", license: "Apache-2.0", type: "module", bin: "./dist/server.js", @@ -11187,7 +11187,8 @@ var init_domain = __esm(() => { }); DeliveryQaEvidenceSchema = exports_external.object({ schemaVersion: exports_external.literal("mediaops-delivery-qa-evidence@1"), - status: exports_external.literal("passed"), + status: exports_external.enum(["passed", "static"]), + mode: exports_external.enum(["full", "static"]).optional(), htmlSha256: Sha256Schema, tools: exports_external.object({ java: exports_external.string().nullable(), @@ -11197,7 +11198,7 @@ var init_domain = __esm(() => { chromium: exports_external.string().nullable(), axe: exports_external.string().min(1) }).strict(), - checks: exports_external.array(exports_external.object({ id: exports_external.string().min(1), status: exports_external.literal("passed"), detail: exports_external.string().min(1) })).min(1), + checks: exports_external.array(exports_external.object({ id: exports_external.string().min(1), status: exports_external.enum(["passed", "skipped"]), detail: exports_external.string().min(1) })).min(1), artifacts: exports_external.array(DeliveryQaArtifactSchema).min(3), completedAt: exports_external.string().datetime() }); @@ -11223,7 +11224,7 @@ var init_domain = __esm(() => { semanticStatus: exports_external.enum(["passed", "failed"]), accessibilityStatus: exports_external.enum(["passed", "failed", "manual_required"]), visualReviewStatus: exports_external.enum(["pending", "passed", "failed"]), - checks: exports_external.array(exports_external.object({ id: exports_external.string().min(1), status: exports_external.enum(["passed", "failed"]), detail: exports_external.string().min(1) })), + checks: exports_external.array(exports_external.object({ id: exports_external.string().min(1), status: exports_external.enum(["passed", "failed", "skipped"]), detail: exports_external.string().min(1) })), qaEvidence: DeliveryQaEvidenceSchema.optional(), visualReview: exports_external.object({ reviewedBy: exports_external.string().trim().min(1).max(300), @@ -38585,7 +38586,8 @@ function err(code, message, warnings) { return env; } function toToolResult(envelope) { - return { content: [{ type: "text", text: JSON.stringify(envelope) }] }; + const content = [{ type: "text", text: JSON.stringify(envelope) }]; + return envelope.success === false ? { content, isError: true } : { content }; } // src/platforms/registry.ts @@ -50656,14 +50658,14 @@ async function writeStaticQaEvidence(args) { }; const browserReport = { schemaVersion: "mediaops-browser-qa@1", - status: "passed", + status: "skipped", mode: "static-skip", detail: "Browser QA skipped under MEDIAOPS_QA_MODE=static.", completedAt }; const summary = { schemaVersion: "mediaops-delivery-qa-summary@1", - status: "passed", + status: "static", mode: "static", generatedAt: completedAt, htmlSha256: args.htmlSha256, @@ -50676,7 +50678,7 @@ async function writeStaticQaEvidence(args) { axe: "4.12.1" }, checks: [ - { id: "static-qa-mode", status: "passed", detail: "Static verification mode: automated Chromium/Nu deferred to MEDIAOPS_QA_MODE=full." } + { id: "static-qa-mode", status: "skipped", detail: "Static verification mode: automated Chromium/Nu deferred to MEDIAOPS_QA_MODE=full." } ], errors: [] }; @@ -50700,7 +50702,8 @@ async function writeStaticQaEvidence(args) { ]; return { schemaVersion: "mediaops-delivery-qa-evidence@1", - status: "passed", + status: "static", + mode: "static", htmlSha256: args.htmlSha256, tools: { java: null, @@ -50711,7 +50714,7 @@ async function writeStaticQaEvidence(args) { axe: "4.12.1" }, checks: [ - { id: "static-qa-mode", status: "passed", detail: "Static verification mode: automated Chromium/Nu deferred to MEDIAOPS_QA_MODE=full." }, + { id: "static-qa-mode", status: "skipped", detail: "Static verification mode: automated Chromium/Nu deferred to MEDIAOPS_QA_MODE=full." }, { id: "static-html-binding", status: "passed", detail: `Evidence bound to primary HTML ${args.htmlSha256}.` } ], artifacts, @@ -50984,8 +50987,8 @@ async function verifyDeliveryBytes(manifest) { if (bytes.byteLength !== asset.byteSize || sha256(bytes) !== asset.sha256) throw new Error(`DELIVERY_ASSET_HASH_MISMATCH:${asset.assetId}`); } - if (manifest.visualReviewStatus === "passed" && (!manifest.qaEvidence || manifest.qaEvidence.status !== "passed")) { - throw new Error("DELIVERY_QA_EVIDENCE_MISSING: verified delivery has no passed Nu/axe/Playwright evidence"); + if (manifest.visualReviewStatus === "passed" && !manifest.qaEvidence) { + throw new Error("DELIVERY_QA_EVIDENCE_MISSING: verified delivery has no Nu/axe/Playwright evidence"); } if (manifest.qaEvidence) { if (manifest.qaEvidence.htmlSha256 !== manifest.primaryArtifact.artifactHash) @@ -51027,8 +51030,11 @@ async function verifyHandler(args) { if (!insideRoot2(root5, candidatesRoot)) return err("DELIVERY_PATH_INVALID", "Delivery root escapes the candidate directory."); const checks5 = []; + const recordCheck = (id, status, detail) => { + checks5.push({ id, status, detail }); + }; const check2 = (id, passed, detail) => { - checks5.push({ id, status: passed ? "passed" : "failed", detail }); + recordCheck(id, passed ? "passed" : "failed", detail); }; try { const primaryBytes = await readArtifact(root5, manifest.primaryArtifact.relativePath); @@ -51071,7 +51077,7 @@ async function verifyHandler(args) { try { qaEvidence = await writeStaticQaEvidence({ root: root5, htmlSha256: manifest.primaryArtifact.artifactHash }); for (const item of qaEvidence.checks) - check2(`automated-${item.id}`, true, item.detail); + recordCheck(`automated-${item.id}`, item.status, item.detail); check2("automated-qa-source-binding", true, "Static-mode evidence binds to the exact primary HTML artifact hash."); } catch (error2) { checks5.push({ id: "automated-delivery-qa", status: "failed", detail: error2 instanceof Error ? error2.message : String(error2) }); @@ -51097,6 +51103,7 @@ async function verifyHandler(args) { qaEvidence = { schemaVersion: "mediaops-delivery-qa-evidence@1", status: "passed", + mode: "full", htmlSha256: qa.html.sha256, tools: qa.tools, checks: qa.checks.map(({ id, status, detail }) => ({ id, status, detail })), @@ -51121,7 +51128,7 @@ async function verifyHandler(args) { const viewportCoverage = input.viewports.some((item) => item.width <= 375) && input.viewports.some((item) => item.width >= 768) && input.viewports.some((item) => item.width >= 1200); const visualPassed = reviewerIndependent && input.visualReviewStatus === "passed" && viewportCoverage && input.printChecked && input.viewports.every((item) => item.noHorizontalOverflow && item.whiteBackground && item.readable); check2("visual-evidence", visualPassed, "Visual review covers mobile, tablet/desktop, wide desktop, print, white background, readability and horizontal overflow."); - const staticPassed = checks5.filter((item) => item.id !== "visual-evidence").every((item) => item.status === "passed"); + const staticPassed = checks5.filter((item) => item.id !== "visual-evidence").every((item) => item.status !== "failed"); const verifiedAt = new Date().toISOString(); const { renderManifestHash: _previousManifestHash, ...baseManifest } = manifest; const updatedWithoutHash = { @@ -51674,6 +51681,13 @@ ${content3.bodyMarkdown}`; if (!delivery || delivery.contentHash !== content3.contentHash || delivery.articleDocHash !== content3.articleDocHash) { issues.push({ code: "DELIVERY_VERIFICATION_REQUIRED", severity: "error", message: "No verified white-background HTML-primary/Markdown-backup delivery manifest binds to this exact revision." }); } else { + if (delivery.qaEvidence?.mode !== "full") { + issues.push({ + code: "DELIVERY_QA_LEVEL_INSUFFICIENT", + severity: "error", + message: `Delivery QA evidence is ${delivery.qaEvidence?.mode ?? "legacy-unknown"}; the Media Gate requires MEDIAOPS_QA_MODE=full evidence bound to this revision before approval.` + }); + } try { await verifyDeliveryBytes(delivery); } catch (error2) { diff --git a/plugins/crabcode-media-ops/docs/0.4-migration.md b/plugins/crabcode-media-ops/docs/0.4-migration.md index 0d9e0ae..5421dbe 100644 --- a/plugins/crabcode-media-ops/docs/0.4-migration.md +++ b/plugins/crabcode-media-ops/docs/0.4-migration.md @@ -45,6 +45,8 @@ profile 的权威记录也迁入 SQLite,并与 `profile.version.confirmed` 审 宿主 principal 是部署者的信任声明,不是插件登录系统。一个进程中的同一 `issuer:principalId` 不能同时满足请求者/批准者或作者/独立核查者的跨人隔离;正式多人流程需要宿主为不同用户注入不同 subject。 +从 0.4.4 起,随包 `.mcp.json` 默认走单人本机模式,不需要手写 env:其中固定 `MEDIAOPS_IDENTITY_MODE=local-editorial`、`MEDIAOPS_TRUSTED_PRINCIPAL_ISSUER=crabcode-local-editorial` 与一份显式角色清单,主体 ID 与显示名来自安装后在插件设置里填写的“本机编辑者 ID / 显示名”(`user_config.principal_id` / `user_config.principal_name`,两项都必填——宿主在缺值时替换会抛错,也不会把声明里的 `default` 写进去)。这同样是宿主的配置断言而不是登录:同一个本机主体不能充当需要第二个真人的 `originality.review`、`editorial.review`、`approval.decide`、`profile.confirm`,这些门禁保持 pending。上面的 `host-principal` 形态留给未来由宿主为每位用户注入不同 subject 的部署。 + 按实际任务授予最小角色: | 工作 | 角色 | diff --git a/plugins/crabcode-media-ops/docs/legal/SBOM.cdx.json b/plugins/crabcode-media-ops/docs/legal/SBOM.cdx.json index 3f6a53b..7b34f00 100644 --- a/plugins/crabcode-media-ops/docs/legal/SBOM.cdx.json +++ b/plugins/crabcode-media-ops/docs/legal/SBOM.cdx.json @@ -6,9 +6,9 @@ "component": { "type": "application", "name": "crabcode-media-ops-mcp", - "version": "0.4.3", - "bom-ref": "pkg:npm/crabcode-media-ops-mcp@0.4.3", - "purl": "pkg:npm/crabcode-media-ops-mcp@0.4.3", + "version": "0.4.4", + "bom-ref": "pkg:npm/crabcode-media-ops-mcp@0.4.4", + "purl": "pkg:npm/crabcode-media-ops-mcp@0.4.4", "licenses": [ { "expression": "Apache-2.0" @@ -4706,7 +4706,7 @@ ], "dependencies": [ { - "ref": "pkg:npm/crabcode-media-ops-mcp@0.4.3", + "ref": "pkg:npm/crabcode-media-ops-mcp@0.4.4", "dependsOn": [ "pkg:npm/%40axe-core/playwright@4.12.1", "pkg:npm/%40hono/node-server@1.19.14", diff --git a/plugins/crabcode-media-ops/package.json b/plugins/crabcode-media-ops/package.json index 244c3a6..510fc6f 100644 --- a/plugins/crabcode-media-ops/package.json +++ b/plugins/crabcode-media-ops/package.json @@ -1,6 +1,6 @@ { "name": "crabcode-media-ops-mcp", - "version": "0.4.3", + "version": "0.4.4", "license": "Apache-2.0", "type": "module", "bin": "./dist/server.js", diff --git a/plugins/crabcode-media-ops/scripts/validate-media-plugin.ts b/plugins/crabcode-media-ops/scripts/validate-media-plugin.ts index d25a250..abc844f 100644 --- a/plugins/crabcode-media-ops/scripts/validate-media-plugin.ts +++ b/plugins/crabcode-media-ops/scripts/validate-media-plugin.ts @@ -120,11 +120,46 @@ if (!pkg.scripts?.start?.includes('dist/server.js')) errors.push('start script m if (pkg.bin !== './dist/server.js') errors.push('package bin must point at the prebuilt dist/server.js') if (!existsSync(join(pluginRoot, 'dist', 'server.js'))) errors.push('dist/server.js is missing; run `bun run build` (the distribution bundle ships in-repo)') -if (existsSync(join(pluginRoot, '.mcp.json'))) { - errors.push('.mcp.json must remain absent while mediaops principal-config-missing containment is active') +// 2026-09-12 decision D-0(c): the principal-config-missing containment is lifted +// because the host now injects the trusted local principal from user_config, so +// the executable configuration must be present and bound to that injection. +const mcpConfigPath = join(pluginRoot, '.mcp.json') +if (!existsSync(mcpConfigPath)) { + errors.push('.mcp.json is missing; the mediaops sidecar is a required local server since 0.4.4') +} else { + const mcpConfig = await json(mcpConfigPath) + const servers: Record = mcpConfig?.mcpServers ?? {} + const serverNames = Object.keys(servers) + if (serverNames.length !== 1 || serverNames[0] !== 'mediaops') { + errors.push(`.mcp.json must declare exactly one server named "mediaops", found [${serverNames.join(', ')}]`) + } + const mediaops = servers.mediaops + if (mediaops) { + if (mediaops.url !== undefined || mediaops.type === 'http' || mediaops.type === 'sse') { + errors.push('.mcp.json mediaops must stay a local stdio server; remote transport is not permitted') + } + const env: Record = mediaops.env ?? {} + if (env.MEDIAOPS_IDENTITY_MODE !== 'local-editorial') { + errors.push('.mcp.json must pin MEDIAOPS_IDENTITY_MODE=local-editorial; the sidecar never invents an identity mode') + } + // Every ${user_config.X} the host substitutes must be a required manifest + // field: substitution throws when the value is missing and the host never + // writes the declared default. + const declaredUserConfig: Record = manifest.userConfig ?? {} + for (const value of Object.values(env)) { + if (typeof value !== 'string') continue + for (const match of value.matchAll(/\$\{user_config\.([A-Za-z0-9_]+)\}/g)) { + if (declaredUserConfig[match[1]!]?.required !== true) { + errors.push(`.mcp.json references \${user_config.${match[1]}} but plugin.json userConfig.${match[1]} is not declared required: true`) + } + } + } + } } const requiredServers: unknown[] = Array.isArray(manifest.requiredMcpServers) ? manifest.requiredMcpServers : [] -if (requiredServers.length !== 0) errors.push('requiredMcpServers must stay empty while mediaops is contained') +if (requiredServers.length !== 1 || requiredServers[0] !== 'mediaops') { + errors.push('requiredMcpServers must be exactly ["mediaops"] so the host activates the bundled sidecar on install') +} if (pkg.overrides?.hono !== '4.12.25') errors.push('Hono security override must remain pinned at 4.12.25 until the SDK resolves above it') if (existsSync(join(pluginRoot, 'editorial', 'scripts', '__pycache__'))) errors.push('generated __pycache__ must not ship in the plugin') @@ -189,4 +224,4 @@ if (errors.length) { process.stderr.write(errors.map((error) => `ERROR ${error}`).join('\n') + '\n') process.exit(1) } -process.stdout.write(`validate-media-plugin: contained executable, ${skillNames.size} skills, ${declaredTools.size} tested tools, ${schemaNames.length} schemas, runtime/docs/manifest/marketplace/SBOM aligned at ${manifest.version}\n`) +process.stdout.write(`validate-media-plugin: bundled local stdio sidecar, ${skillNames.size} skills, ${declaredTools.size} tested tools, ${schemaNames.length} schemas, runtime/docs/manifest/marketplace/SBOM aligned at ${manifest.version}\n`) diff --git a/plugins/crabcode-media-ops/src/domain.ts b/plugins/crabcode-media-ops/src/domain.ts index f011509..bc8bbb7 100644 --- a/plugins/crabcode-media-ops/src/domain.ts +++ b/plugins/crabcode-media-ops/src/domain.ts @@ -630,9 +630,18 @@ const DeliveryQaArtifactSchema = z.object({ sha256: Sha256Schema, }) +/** + * QA evidence carries its own grade and never borrows another one. + * + * `status` says what the recorded run concluded; `mode` says how much of the + * pipeline actually ran. `mode` is optional only because records written before + * 0.4.4 have no such field — a missing `mode` is legacy-unknown and readers must + * never treat it as `full` (see readiness.ts::inspectContent). + */ const DeliveryQaEvidenceSchema = z.object({ schemaVersion: z.literal('mediaops-delivery-qa-evidence@1'), - status: z.literal('passed'), + status: z.enum(['passed', 'static']), + mode: z.enum(['full', 'static']).optional(), htmlSha256: Sha256Schema, tools: z.object({ java: z.string().nullable(), @@ -642,7 +651,7 @@ const DeliveryQaEvidenceSchema = z.object({ chromium: z.string().nullable(), axe: z.string().min(1), }).strict(), - checks: z.array(z.object({ id: z.string().min(1), status: z.literal('passed'), detail: z.string().min(1) })).min(1), + checks: z.array(z.object({ id: z.string().min(1), status: z.enum(['passed', 'skipped']), detail: z.string().min(1) })).min(1), artifacts: z.array(DeliveryQaArtifactSchema).min(3), completedAt: z.string().datetime(), }) @@ -669,7 +678,10 @@ export const DeliveryManifestSchema = z.object({ semanticStatus: z.enum(['passed', 'failed']), accessibilityStatus: z.enum(['passed', 'failed', 'manual_required']), visualReviewStatus: z.enum(['pending', 'passed', 'failed']), - checks: z.array(z.object({ id: z.string().min(1), status: z.enum(['passed', 'failed']), detail: z.string().min(1) })), + // 'skipped' records a check that was deliberately not executed (static QA + // mode); it is not a pass and must never be written as one, but it also does + // not block the static byte/security verdict. + checks: z.array(z.object({ id: z.string().min(1), status: z.enum(['passed', 'failed', 'skipped']), detail: z.string().min(1) })), qaEvidence: DeliveryQaEvidenceSchema.optional(), visualReview: z.object({ reviewedBy: z.string().trim().min(1).max(300), diff --git a/plugins/crabcode-media-ops/src/envelope.ts b/plugins/crabcode-media-ops/src/envelope.ts index 30fa5b9..8fca2a1 100644 --- a/plugins/crabcode-media-ops/src/envelope.ts +++ b/plugins/crabcode-media-ops/src/envelope.ts @@ -40,9 +40,19 @@ export function err(code: string, message: string, warnings?: string[]): Envelop return env } -/** Wrap an envelope into the MCP tool result shape. */ +/** + * Wrap an envelope into the MCP tool result shape. + * + * A business failure must arrive as a failure: `error` and `blocked` set + * `isError: true` so the host and the model see a failed tool call instead of a + * successful call whose text happens to describe a refusal. The JSON body is + * unchanged in every case — the host surfaces the first text block as the error + * detail, and the model still reads the full envelope. + */ export function toToolResult(envelope: Envelope): { content: { type: 'text'; text: string }[] + isError?: true } { - return { content: [{ type: 'text', text: JSON.stringify(envelope) }] } + const content = [{ type: 'text' as const, text: JSON.stringify(envelope) }] + return envelope.success === false ? { content, isError: true } : { content } } diff --git a/plugins/crabcode-media-ops/src/tools/delivery.ts b/plugins/crabcode-media-ops/src/tools/delivery.ts index d288928..90ccc47 100644 --- a/plugins/crabcode-media-ops/src/tools/delivery.ts +++ b/plugins/crabcode-media-ops/src/tools/delivery.ts @@ -43,14 +43,14 @@ async function writeStaticQaEvidence(args: { } const browserReport = { schemaVersion: 'mediaops-browser-qa@1', - status: 'passed', + status: 'skipped', mode: 'static-skip', detail: 'Browser QA skipped under MEDIAOPS_QA_MODE=static.', completedAt, } const summary = { schemaVersion: 'mediaops-delivery-qa-summary@1', - status: 'passed', + status: 'static', mode: 'static', generatedAt: completedAt, htmlSha256: args.htmlSha256, @@ -63,7 +63,7 @@ async function writeStaticQaEvidence(args: { axe: '4.12.1', }, checks: [ - { id: 'static-qa-mode', status: 'passed', detail: 'Static verification mode: automated Chromium/Nu deferred to MEDIAOPS_QA_MODE=full.' }, + { id: 'static-qa-mode', status: 'skipped', detail: 'Static verification mode: automated Chromium/Nu deferred to MEDIAOPS_QA_MODE=full.' }, ], errors: [], } @@ -86,7 +86,10 @@ async function writeStaticQaEvidence(args: { ] return { schemaVersion: 'mediaops-delivery-qa-evidence@1', - status: 'passed', + // Static evidence declares its own grade. It is not a pass of the full + // pipeline and must never be recorded as one: Chromium and Nu never ran. + status: 'static', + mode: 'static', htmlSha256: args.htmlSha256, tools: { java: null, @@ -97,7 +100,7 @@ async function writeStaticQaEvidence(args: { axe: '4.12.1', }, checks: [ - { id: 'static-qa-mode', status: 'passed', detail: 'Static verification mode: automated Chromium/Nu deferred to MEDIAOPS_QA_MODE=full.' }, + { id: 'static-qa-mode', status: 'skipped', detail: 'Static verification mode: automated Chromium/Nu deferred to MEDIAOPS_QA_MODE=full.' }, { id: 'static-html-binding', status: 'passed', detail: `Evidence bound to primary HTML ${args.htmlSha256}.` }, ], artifacts, @@ -136,7 +139,8 @@ function sha256(bytes: Uint8Array | string): string { return createHash('sha256').update(bytes).digest('hex') } -function deliveryHashPayload(manifest: Omit): unknown { +/** Single derivation of `renderManifestHash`; exported so nobody re-implements it. */ +export function deliveryHashPayload(manifest: Omit): unknown { return { ...manifest } } @@ -380,8 +384,13 @@ export async function verifyDeliveryBytes(manifest: DeliveryManifest): Promise): Promise if (!insideRoot(root, candidatesRoot)) return err('DELIVERY_PATH_INVALID', 'Delivery root escapes the candidate directory.') const checks: DeliveryManifest['checks'] = [] + const recordCheck = (id: string, status: DeliveryManifest['checks'][number]['status'], detail: string): void => { + checks.push({ id, status, detail }) + } const check = (id: string, passed: boolean, detail: string): void => { - checks.push({ id, status: passed ? 'passed' : 'failed', detail }) + recordCheck(id, passed ? 'passed' : 'failed', detail) } try { const primaryBytes = await readArtifact(root, manifest.primaryArtifact.relativePath) @@ -463,7 +475,9 @@ export async function verifyHandler(args: z.input): Promise } else if (qaMode === 'static') { try { qaEvidence = await writeStaticQaEvidence({ root, htmlSha256: manifest.primaryArtifact.artifactHash }) - for (const item of qaEvidence.checks) check(`automated-${item.id}`, true, item.detail) + // A skipped automated check is recorded as skipped. Writing it as passed + // is how static evidence used to masquerade as a full Nu/axe/Playwright run. + for (const item of qaEvidence.checks) recordCheck(`automated-${item.id}`, item.status, item.detail) check('automated-qa-source-binding', true, 'Static-mode evidence binds to the exact primary HTML artifact hash.') } catch (error) { checks.push({ id: 'automated-delivery-qa', status: 'failed', detail: error instanceof Error ? error.message : String(error) }) @@ -493,6 +507,7 @@ export async function verifyHandler(args: z.input): Promise qaEvidence = { schemaVersion: 'mediaops-delivery-qa-evidence@1', status: 'passed', + mode: 'full', htmlSha256: qa.html.sha256, tools: qa.tools, checks: qa.checks.map(({ id, status, detail }) => ({ id, status: status as 'passed', detail })), @@ -519,7 +534,9 @@ export async function verifyHandler(args: z.input): Promise const viewportCoverage = input.viewports.some((item) => item.width <= 375) && input.viewports.some((item) => item.width >= 768) && input.viewports.some((item) => item.width >= 1200) const visualPassed = reviewerIndependent && input.visualReviewStatus === 'passed' && viewportCoverage && input.printChecked && input.viewports.every((item) => item.noHorizontalOverflow && item.whiteBackground && item.readable) check('visual-evidence', visualPassed, 'Visual review covers mobile, tablet/desktop, wide desktop, print, white background, readability and horizontal overflow.') - const staticPassed = checks.filter((item) => item.id !== 'visual-evidence').every((item) => item.status === 'passed') + // A skipped check does not block the byte/security verdict; only a failure does. + // The full-vs-static level decision belongs to the Media Gate (readiness.ts). + const staticPassed = checks.filter((item) => item.id !== 'visual-evidence').every((item) => item.status !== 'failed') const verifiedAt = new Date().toISOString() const { renderManifestHash: _previousManifestHash, ...baseManifest } = manifest const updatedWithoutHash: Omit = { diff --git a/plugins/crabcode-media-ops/src/tools/readiness.ts b/plugins/crabcode-media-ops/src/tools/readiness.ts index cd52f22..96c9471 100644 --- a/plugins/crabcode-media-ops/src/tools/readiness.ts +++ b/plugins/crabcode-media-ops/src/tools/readiness.ts @@ -164,6 +164,16 @@ export async function inspectContent(content: ContentManifest, platform: Platfor if (!delivery || delivery.contentHash !== content.contentHash || delivery.articleDocHash !== content.articleDocHash) { issues.push({ code: 'DELIVERY_VERIFICATION_REQUIRED', severity: 'error', message: 'No verified white-background HTML-primary/Markdown-backup delivery manifest binds to this exact revision.' }) } else { + // Evidence grade is part of the gate, not a presentation detail. A static + // run never launched Chromium or Nu, and a pre-0.4.4 record does not say + // what it ran — neither may be read as a full pass. + if (delivery.qaEvidence?.mode !== 'full') { + issues.push({ + code: 'DELIVERY_QA_LEVEL_INSUFFICIENT', + severity: 'error', + message: `Delivery QA evidence is ${delivery.qaEvidence?.mode ?? 'legacy-unknown'}; the Media Gate requires MEDIAOPS_QA_MODE=full evidence bound to this revision before approval.`, + }) + } try { await verifyDeliveryBytes(delivery) } catch (error) { diff --git a/plugins/crabcode-media-ops/tests/delivery.test.ts b/plugins/crabcode-media-ops/tests/delivery.test.ts index 8a3482e..32dce23 100644 --- a/plugins/crabcode-media-ops/tests/delivery.test.ts +++ b/plugins/crabcode-media-ops/tests/delivery.test.ts @@ -51,6 +51,37 @@ describe('HTML-primary frozen delivery', () => { expect((second.data as any).backup.artifactHash).toBe(firstManifest!.backupArtifact.artifactHash) }) + // Static mode runs neither Chromium nor Nu. The evidence it writes must say + // so: a local draft stays reachable (the manifest still verifies) while the + // record keeps its own grade instead of borrowing the full run's. + test('static QA evidence declares its own grade and records skipped checks as skipped', async () => { + const previous = process.env.MEDIAOPS_QA_MODE + process.env.MEDIAOPS_QA_MODE = 'static' + try { + const fixture = await createReviewedContent({ dir, brandId: 'delivery-brand', profileVersion, deliveryMode: 'verified-static' }) + const { getDeliveryManifest } = await import('../src/tools/delivery.ts') + const manifest = await getDeliveryManifest(fixture.deliveryId) + expect(manifest!.visualReviewStatus).toBe('passed') + expect(manifest!.qaEvidence!.status).toBe('static') + expect(manifest!.qaEvidence!.mode).toBe('static') + const evidenceChecks = new Map(manifest!.qaEvidence!.checks.map((item) => [item.id, item.status])) + expect(evidenceChecks.get('static-qa-mode')).toBe('skipped') + // Positive control: the binding really was performed, so it stays passed. + expect(evidenceChecks.get('static-html-binding')).toBe('passed') + expect(manifest!.checks.find((item) => item.id === 'automated-static-qa-mode')?.status).toBe('skipped') + expect(manifest!.checks.some((item) => item.status === 'failed')).toBe(false) + + const browserReport = JSON.parse(await readFile(join(manifest!.artifactRoot, 'qa/browser-report.json'), 'utf8')) + expect(browserReport.status).toBe('skipped') + const summary = JSON.parse(await readFile(join(manifest!.artifactRoot, 'qa/summary.json'), 'utf8')) + expect(summary.status).toBe('static') + expect(summary.checks.find((item: any) => item.id === 'static-qa-mode').status).toBe('skipped') + } finally { + if (previous === undefined) delete process.env.MEDIAOPS_QA_MODE + else process.env.MEDIAOPS_QA_MODE = previous + } + }) + test('incomplete viewport/print evidence cannot mark a candidate verified', async () => { // Negative path: never launch full browser QA (MEDIAOPS_QA_MODE=off). const previous = process.env.MEDIAOPS_QA_MODE diff --git a/plugins/crabcode-media-ops/tests/envelope.test.ts b/plugins/crabcode-media-ops/tests/envelope.test.ts index 2f641d5..5ee6cdc 100644 --- a/plugins/crabcode-media-ops/tests/envelope.test.ts +++ b/plugins/crabcode-media-ops/tests/envelope.test.ts @@ -40,4 +40,24 @@ describe('envelope factories', () => { expect(result.content[0].type).toBe('text') expect(JSON.parse(result.content[0].text)).toEqual({ success: true, status: 'ok', data: { a: 2 } }) }) + + // A business failure has to arrive as a failed tool call. Returning + // `{content: [...]}` with no isError told the host "this call succeeded" and + // left the refusal buried in a JSON string the host never inspects. + test('toToolResult marks the two non-success statuses as tool errors', () => { + expect(toToolResult(err('AUTHENTICATION_REQUIRED', 'no principal')).isError).toBe(true) + expect(toToolResult(blocked({ reason: 'gate-b' })).isError).toBe(true) + }) + + test('toToolResult leaves the two success statuses unmarked', () => { + expect(toToolResult(ok({ a: 2 })).isError).toBeUndefined() + expect(toToolResult(actionRequired({ issues: [] })).isError).toBeUndefined() + }) + + test('the JSON body is identical whether or not the call is marked as an error', () => { + const envelope = err('NOT_FOUND', 'missing') + const result = toToolResult(envelope) + expect(result.content).toHaveLength(1) + expect(JSON.parse(result.content[0].text)).toEqual(envelope) + }) }) diff --git a/plugins/crabcode-media-ops/tests/helpers.ts b/plugins/crabcode-media-ops/tests/helpers.ts index 5d4cbba..54c4903 100644 --- a/plugins/crabcode-media-ops/tests/helpers.ts +++ b/plugins/crabcode-media-ops/tests/helpers.ts @@ -1,8 +1,8 @@ import { createHash, randomUUID } from 'node:crypto' import { setDefaultTimeout } from 'bun:test' -import { realpath, writeFile } from 'node:fs/promises' +import { realpath, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' -import { ResearchCaptureSchema, ResearchReviewSchema, stableHash } from '../src/domain.ts' +import { DeliveryManifestSchema, ResearchCaptureSchema, ResearchReviewSchema, stableHash } from '../src/domain.ts' import { extractVerifiableStatements, factualCompatibility } from '../src/factual-integrity.ts' import { bodyPlainText } from '../src/rendering/article-doc.ts' import { appendRecord } from '../src/storage.ts' @@ -11,7 +11,13 @@ import { getLatestContent, saveHandler as saveContent } from '../src/tools/conte import { getHandler as getResearch, handler as completeResearch } from '../src/tools/research.ts' import { scanHandler } from '../src/tools/originality.ts' import { handler as completeEditorialReview } from '../src/tools/editorial-review.ts' -import { renderHandler, verifyHandler } from '../src/tools/delivery.ts' +import { + deliveryHashPayload, + getDeliveryManifest, + renderHandler, + resolveMediaOpsQaMode, + verifyHandler, +} from '../src/tools/delivery.ts' import type { TrustedPrincipal } from '../src/identity.ts' export const DISCLOSURE = '本文包含 AI 辅助创作内容' @@ -73,11 +79,86 @@ export async function createProfile(brandId: string, bannedWords: string[] = []) type TestClaim = { id: string; claim: string; status?: 'verified' | 'doubtful' | 'unsourced'; core?: boolean } +/** + * Replace a candidate's QA evidence with full-grade fixture evidence. + * + * The Media Gate requires `qaEvidence.mode === 'full'` before approval, and full + * mode means a real Nu + Playwright/axe run — which this machine cannot do in the + * default suite (that is what `MEDIAOPS_QA_MODE=static` exists for). Suites about + * the *approval state machine* (approval/package/readiness/preview) still need a + * delivery that a real full run would have produced, so the fixture mints one + * here rather than letting static evidence quietly count as full — the exact + * confusion 0.4.4 removed from production. + * + * The written reports say plainly that they are fixtures; nothing in src/ can + * produce them. Under `MEDIAOPS_QA_MODE=full` this is a no-op and the real + * evidence stands (tests/delivery.qa.test.ts). + */ +export async function mintFullQaEvidenceFixture(deliveryId: string): Promise { + const manifest = await getDeliveryManifest(deliveryId) + if (!manifest) throw new Error(`qa fixture: no delivery ${deliveryId}`) + if (manifest.qaEvidence?.mode === 'full') return manifest.renderManifestHash + const root = await realpath(manifest.artifactRoot) + const htmlSha256 = manifest.primaryArtifact.artifactHash + const completedAt = new Date().toISOString() + const fixtureNote = 'TEST FIXTURE: stands in for a real Nu/Playwright/axe run; produced by tests/helpers.ts, never by src/.' + const checks = [ + { id: 'nu-html-validity', status: 'passed' as const, detail: `${fixtureNote} Nu reported no errors for ${htmlSha256}.` }, + { id: 'axe-accessibility', status: 'passed' as const, detail: `${fixtureNote} axe-core reported no violations.` }, + { id: 'viewport-matrix', status: 'passed' as const, detail: `${fixtureNote} light/dark, 320/768/1440 and print all clean.` }, + ] + const bodies: Array<[string, unknown]> = [ + ['qa/nu-report.json', { schemaVersion: 'mediaops-nu-qa@1', fixture: true, status: 'passed', htmlSha256, completedAt, detail: fixtureNote }], + ['qa/browser-report.json', { schemaVersion: 'mediaops-browser-qa@1', fixture: true, status: 'passed', mode: 'full', htmlSha256, completedAt, detail: fixtureNote }], + ['qa/summary.json', { schemaVersion: 'mediaops-delivery-qa-summary@1', fixture: true, status: 'passed', mode: 'full', htmlSha256, generatedAt: completedAt, checks, errors: [] }], + ] + await rm(join(root, 'qa', 'static-report.json'), { force: true }) + const artifacts = [] + for (const [relativePath, body] of bodies) { + const bytes = new TextEncoder().encode(JSON.stringify(body, null, 2) + '\n') + await writeFile(join(root, relativePath), bytes) + artifacts.push({ + relativePath, + mediaType: 'application/json', + byteSize: bytes.byteLength, + sha256: createHash('sha256').update(bytes).digest('hex'), + }) + } + const { renderManifestHash: _previous, ...withoutHash } = manifest + const promotedWithoutHash = { + ...withoutHash, + checks: [ + ...manifest.checks.filter((item) => !item.id.startsWith('automated-')), + ...checks.map((item) => ({ id: `automated-${item.id}`, status: item.status, detail: item.detail })), + { id: 'automated-qa-source-binding', status: 'passed' as const, detail: `${fixtureNote} Evidence binds to primary HTML ${htmlSha256}.` }, + ], + qaEvidence: { + schemaVersion: 'mediaops-delivery-qa-evidence@1' as const, + status: 'passed' as const, + mode: 'full' as const, + htmlSha256, + tools: manifest.qaEvidence?.tools ?? { java: null, vnuPackage: '26.7.15', vnuRuntime: null, playwright: '1.61.1', chromium: null, axe: '4.12.1' }, + checks, + artifacts, + completedAt, + }, + } + const renderManifestHash = stableHash(deliveryHashPayload(promotedWithoutHash)) + const promoted = DeliveryManifestSchema.parse({ ...promotedWithoutHash, renderManifestHash }) + await writeFile(join(root, 'delivery-manifest.json'), JSON.stringify(promoted, null, 2) + '\n', 'utf8') + await appendRecord('delivery-manifests', { id: randomUUID(), ...promoted }) + return renderManifestHash +} + /** * deliveryMode: * - none: stop after reviewed (no deliveryId) * - render-only (default): freeze/render delivery candidate without verify/QA - * - verified: call delivery.verify (honours MEDIAOPS_QA_MODE full|static|off) + * - verified: call delivery.verify, then mint full-grade QA evidence when the + * run was not MEDIAOPS_QA_MODE=full, so the Media Gate sees what a real full + * run would have produced (see mintFullQaEvidenceFixture) + * - verified-static: call delivery.verify and keep whatever grade it produced — + * for tests about the evidence grade itself */ export async function createReviewedContent(args: { dir: string @@ -93,7 +174,7 @@ export async function createReviewedContent(args: { lateReviewedSummary?: string lateReviewedCitationUrl?: string assetCaption?: string - deliveryMode?: 'none' | 'render-only' | 'verified' + deliveryMode?: 'none' | 'render-only' | 'verified' | 'verified-static' }): Promise<{ contentId: string; revisionId: string; contentHash: string; articleDocHash: string; assetPath: string; deliveryId: string; renderManifestHash: string }> { const deliveryMode = args.deliveryMode ?? 'render-only' const platform = args.platform ?? 'wechat' @@ -260,9 +341,9 @@ export async function createReviewedContent(args: { notes: ['测试夹具:静态与多视口视觉门禁通过'], }) if (verified.status !== 'ok') throw new Error(`delivery verify failed: ${JSON.stringify(verified)}`) - return { - ...base, - deliveryId, - renderManifestHash: (verified.data as any).renderManifestHash, + const verifiedManifestHash = (verified.data as any).renderManifestHash as string + if (deliveryMode === 'verified-static' || resolveMediaOpsQaMode() === 'full') { + return { ...base, deliveryId, renderManifestHash: verifiedManifestHash } } + return { ...base, deliveryId, renderManifestHash: await mintFullQaEvidenceFixture(deliveryId) } } diff --git a/plugins/crabcode-media-ops/tests/identity.test.ts b/plugins/crabcode-media-ops/tests/identity.test.ts index 662913e..20517ec 100644 --- a/plugins/crabcode-media-ops/tests/identity.test.ts +++ b/plugins/crabcode-media-ops/tests/identity.test.ts @@ -88,11 +88,15 @@ describe('trusted MCP/host identity binding', () => { delete baseEnv.MEDIAOPS_TRUSTED_PRINCIPAL_ROLES const anonymous = await stdioClient({ ...baseEnv, MEDIAOPS_DATA_DIR: dataDir }) try { - const rejected = parseToolResult(await anonymous.client.callTool({ + const rejectedResult = await anonymous.client.callTool({ name: 'mediaops.content.save', arguments: { kind: 'brief', brandId: 'identity-brand', profileVersion: 'v1', stage: 'intake', title: '身份测试', researchSubject: '身份测试', bodyMarkdown: '', savedBy: 'spoofed' }, - })) + }) + const rejected = parseToolResult(rejectedResult) expect(rejected.error.code).toBe('AUTHENTICATION_REQUIRED') + // The refusal must reach the host as a failed tool call, not as a + // successful call whose text happens to describe a refusal. + expect(rejectedResult.isError).toBe(true) } finally { await anonymous.client.close() } @@ -109,11 +113,14 @@ describe('trusted MCP/host identity binding', () => { const capability = parseToolResult(await authenticated.client.callTool({ name: 'mediaops.capabilities', arguments: {} })) expect(capability.data.governedCapabilities.authenticatedActorIdentity).toBe(true) expect(capability.data.governedCapabilities.actorPrincipalId).toBe('desktop-user') - const saved = parseToolResult(await authenticated.client.callTool({ + const savedResult = await authenticated.client.callTool({ name: 'mediaops.content.save', arguments: { kind: 'brief', brandId: 'identity-brand', profileVersion: 'v1', stage: 'intake', title: '身份测试', researchSubject: '身份测试', bodyMarkdown: '', savedBy: 'spoofed' }, - })) + }) + const saved = parseToolResult(savedResult) expect(saved.status).toBe('ok') + // Positive control: a real save must not be marked as an error. + expect(savedResult.isError).toBeUndefined() const content = parseToolResult(await authenticated.client.callTool({ name: 'mediaops.content.get', arguments: { contentId: saved.data.contentId } })) expect(content.data.savedBy).toBe('crabcode-host:desktop-user') } finally { diff --git a/plugins/crabcode-media-ops/tests/mcp-config-roles.test.ts b/plugins/crabcode-media-ops/tests/mcp-config-roles.test.ts new file mode 100644 index 0000000..993d670 --- /dev/null +++ b/plugins/crabcode-media-ops/tests/mcp-config-roles.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { isSecondHumanGate, toolRolePolicies } from '../src/identity.ts' + +/** + * The role list the host injects is a literal in `.mcp.json`, and identity.ts is + * where roles are actually defined. A literal that drifts from the definition + * fails in exactly the way that is hardest to see: a governed tool starts + * answering AUTHORIZATION_DENIED with no configuration having changed. + * + * So the expected list is derived here from the exported policy table rather + * than transcribed: every role some governed tool demands, minus the roles that + * only second-real-human gates demand. Those gates stay pending by design in + * local-editorial mode, and granting their roles to the single local principal + * would suggest a separation of duties that does not exist. + */ +const config = JSON.parse(readFileSync(join(import.meta.dir, '..', '.mcp.json'), 'utf8')) +const env: Record = config.mcpServers.mediaops.env + +function rolesInFirstAppearanceOrder(): string[] { + const order: string[] = [] + const onlyRequiredByGates = new Map() + for (const { tool, role } of toolRolePolicies()) { + if (!order.includes(role)) order.push(role) + const gate = isSecondHumanGate(tool) + onlyRequiredByGates.set(role, (onlyRequiredByGates.get(role) ?? true) && gate) + } + return order.filter((role) => onlyRequiredByGates.get(role) === false) +} + +describe('.mcp.json injected roles', () => { + test('the literal equals the roles derived from identity.ts', () => { + expect(env.MEDIAOPS_TRUSTED_PRINCIPAL_ROLES).toBe(rolesInFirstAppearanceOrder().join(',')) + }) + + test('second-human-gate-only roles are withheld and the ordinary pipeline roles are granted', () => { + const granted = new Set(env.MEDIAOPS_TRUSTED_PRINCIPAL_ROLES.split(',')) + // Positive control: the derivation is not vacuous — it drops exactly the + // roles no non-gate tool asks for, and keeps the ones the pipeline needs. + for (const role of ['originality_reviewer', 'editorial_reviewer', 'approver', 'profile_approver']) { + expect(granted.has(role), role).toBe(false) + } + for (const role of ['author', 'reference_curator', 'researcher', 'fact_checker', 'publisher']) { + expect(granted.has(role), role).toBe(true) + } + for (const { tool, role } of toolRolePolicies()) { + if (!isSecondHumanGate(tool)) expect(granted.has(role), `${tool} needs ${role}`).toBe(true) + } + }) + + test('the injected identity is local-editorial and never a wildcard grant', () => { + expect(env.MEDIAOPS_IDENTITY_MODE).toBe('local-editorial') + expect(env.MEDIAOPS_TRUSTED_PRINCIPAL_ISSUER).toBe('crabcode-local-editorial') + const granted = env.MEDIAOPS_TRUSTED_PRINCIPAL_ROLES.split(',') + expect(granted).not.toContain('*') + expect(granted).not.toContain('mediaops:*') + // The principal itself comes from host user_config, never from a literal. + expect(env.MEDIAOPS_TRUSTED_PRINCIPAL_ID).toBe('${user_config.principal_id}') + expect(env.MEDIAOPS_TRUSTED_PRINCIPAL_NAME).toBe('${user_config.principal_name}') + }) +}) diff --git a/plugins/crabcode-media-ops/tests/package.test.ts b/plugins/crabcode-media-ops/tests/package.test.ts index 1811e2d..7f26495 100644 --- a/plugins/crabcode-media-ops/tests/package.test.ts +++ b/plugins/crabcode-media-ops/tests/package.test.ts @@ -50,6 +50,8 @@ describe('hash-bound publish packaging', () => { expect(manifest.backupArtifact.format).toBe('markdown') expect(existsSync(join(path, manifest.assets[0].relativePath))).toBe(true) expect(manifest.qaEvidence.status).toBe('passed') + // Only full-grade evidence can reach an approved package (Media Gate, RC-24). + expect(manifest.qaEvidence.mode).toBe('full') expect(existsSync(join(path, 'qa/summary.json'))).toBe(true) // Full Chromium screenshots only exist under MEDIAOPS_QA_MODE=full; static mode still packages summary evidence. if ((process.env.MEDIAOPS_QA_MODE ?? 'full') === 'full') { diff --git a/plugins/crabcode-media-ops/tests/readiness.test.ts b/plugins/crabcode-media-ops/tests/readiness.test.ts index c9e59b8..8ffefb5 100644 --- a/plugins/crabcode-media-ops/tests/readiness.test.ts +++ b/plugins/crabcode-media-ops/tests/readiness.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test' -import { mkdtemp, rm } from 'node:fs/promises' +import { randomUUID } from 'node:crypto' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { saveHandler as saveContent, getLatestContent } from '../src/tools/content.ts' @@ -40,6 +41,53 @@ describe('complete Media Gate', () => { expect((await handler({ contentId: content.contentId })).status).toBe('ok') }) + // RC-24: a static run is a draft aid, not an approval-grade record. The gate + // decides on the evidence's own declared grade, never on the ambient QA mode. + test('static QA evidence cannot push a revision through the Media Gate', async () => { + const previous = process.env.MEDIAOPS_QA_MODE + process.env.MEDIAOPS_QA_MODE = 'static' + try { + const fixture = await createReviewedContent({ deliveryMode: 'verified-static', dir, brandId: 'tech-daily', profileVersion: version }) + const env = await handler({ contentId: fixture.contentId }) + expect(env.status).toBe('action_required') + expect((env.data as any).ready).toBe(false) + const issues = (env.data as any).issues as Array<{ code: string; severity: string; message: string }> + const blocker = issues.find((issue) => issue.code === 'DELIVERY_QA_LEVEL_INSUFFICIENT') + expect(blocker?.severity).toBe('error') + expect(blocker?.message).toContain('static') + // Positive control: nothing else is wrong with this revision, so the code + // cannot be appearing for some unrelated reason. + expect(issues.filter((issue) => issue.severity === 'error').map((issue) => issue.code)).toEqual(['DELIVERY_QA_LEVEL_INSUFFICIENT']) + } finally { + if (previous === undefined) delete process.env.MEDIAOPS_QA_MODE + else process.env.MEDIAOPS_QA_MODE = previous + } + }) + + // Records written before 0.4.4 carry no `mode`. "It does not say" is not + // "it was full": an absent grade must block exactly like a static one. + test('legacy evidence without a recorded mode is insufficient, not full', async () => { + const fixture = await createReviewedContent({ deliveryMode: 'verified', dir, brandId: 'tech-daily', profileVersion: version }) + // Positive control: this revision is ready before the grade is stripped. + expect((await handler({ contentId: fixture.contentId })).status).toBe('ok') + + const { getDeliveryManifest, deliveryHashPayload } = await import('../src/tools/delivery.ts') + const { DeliveryManifestSchema, stableHash } = await import('../src/domain.ts') + const { appendRecord } = await import('../src/storage.ts') + const manifest = await getDeliveryManifest(fixture.deliveryId) + const { renderManifestHash: _current, qaEvidence, ...rest } = manifest! + const { mode: _mode, ...legacyEvidence } = qaEvidence! + const withoutHash = { ...rest, qaEvidence: legacyEvidence } + const legacy = DeliveryManifestSchema.parse({ ...withoutHash, renderManifestHash: stableHash(deliveryHashPayload(withoutHash)) }) + await writeFile(join(legacy.artifactRoot, 'delivery-manifest.json'), JSON.stringify(legacy, null, 2) + '\n', 'utf8') + await appendRecord('delivery-manifests', { id: randomUUID(), ...legacy }) + + const issues = ((await handler({ contentId: fixture.contentId })).data as any).issues as Array<{ code: string; message: string }> + const blocker = issues.find((issue) => issue.code === 'DELIVERY_QA_LEVEL_INSUFFICIENT') + expect(blocker).toBeDefined() + expect(blocker?.message).toContain('legacy-unknown') + }) + test('stale platform rules are detected with an internal deterministic audit clock', async () => { const fixture = await createReviewedContent({ deliveryMode: 'verified', dir, brandId: 'tech-daily', profileVersion: version }) const content = await getLatestContent(fixture.contentId) diff --git a/plugins/crablaw-cn/legal-core/schemas/run-manifest.schema.json b/plugins/crablaw-cn/legal-core/schemas/run-manifest.schema.json index 74873a0..7bc32e2 100644 --- a/plugins/crablaw-cn/legal-core/schemas/run-manifest.schema.json +++ b/plugins/crablaw-cn/legal-core/schemas/run-manifest.schema.json @@ -24,6 +24,18 @@ "additionalProperties": false } }, + "sources": { + "type": "array", + "items": { + "type": "object", + "required": ["sourceId", "sha256"], + "properties": { + "sourceId": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]{1,120}$" }, + "sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" } + }, + "additionalProperties": false + } + }, "artifacts": { "type": "array", "items": { diff --git a/plugins/crablaw-cn/matter-core/PRACTICE.md b/plugins/crablaw-cn/matter-core/PRACTICE.md index edce50e..93f71df 100644 --- a/plugins/crablaw-cn/matter-core/PRACTICE.md +++ b/plugins/crablaw-cn/matter-core/PRACTICE.md @@ -45,7 +45,8 @@ Every substantive domain workflow must verify: - Active matter exists. - Matter is within the user's authorized scope. -- Conflict screening status is `no-hit` or `cleared-by-lawyer`; `pending` and `hit-review-required` block substantive work. +- Conflict screening status is `no-hit` or `cleared-by-lawyer`; `pending`, `hit-review-required` and `coverage-incomplete` block substantive work. +- The matter directory carries no `.pending` marker. A marker means a bootstrap was interrupted before it finished writing; the matter is not active and must be resolved by a human, never reused or overwritten. - Domain work fits the engagement scope. - Output destination is internal unless review status is approved. - Source records can be written for legal and factual references. @@ -72,7 +73,12 @@ For substantive legal analysis, also apply `legal-core/PRACTICE.md` and - Matter documents, facts/evidence, legal authorities, and model knowledge remain separate records. - `[已核验-来源]` requires a resolvable current source record; model knowledge cannot be upgraded by - confident wording. + confident wording. Concretely, the tag is satisfied only by a source record whose `sourceType` is + `official-law`, `official-guidance` or `case` **and** whose `status` is `verified` or + `lawyer-reviewed`. `verified` means the record was produced by a real retrieval action in this + session; `lawyer-reviewed` means a named reviewer confirmed it. Older records keep their + `unreviewed` status and stay readable, but `unreviewed`, `unknown`, `superseded` and + `source-needs-check` never satisfy the tag: not having been checked is not a check. - Findings that apply law to matter facts carry source-record IDs and fact/evidence IDs. - Outcome/practice-sensitive issues require a case comparison or a documented search limitation. - Engineering validation does not certify legal accuracy; the review queue remains mandatory. @@ -87,7 +93,41 @@ Deterministic tools live under `${CRABCODE_PLUGIN_ROOT}/matter-core/scripts/`. T - Use private permissions, atomic JSON replacement, and non-sensitive audit events. - Existing Matter records remain readable; missing fields block a new substantive run with a correction list rather than being guessed or silently migrated. -- A stale deep-analysis issue must be explicitly rerun before ready-for-review status. +- A stale deep-analysis issue must be explicitly rerun before ready-for-review status. A sync that + finds no new change is not evidence that a previous change was addressed, so `unchanged` keeps the + existing `staleIssueIds`; a mark is cleared only when the issue tree itself no longer says `stale`. +- Source records are hashed alongside documents. Editing `sources.jsonl` makes every issue and + artifact that relies on the edited record stale, exactly like editing a document would. +- Conflict screening reports its own coverage. A record that cannot be parsed, is not a JSON object, + or sits behind a symlink or Windows directory junction is counted in `conflict-check.json`'s + `coverage` block and forces status `coverage-incomplete` — an unreadable store is never reported as + "nothing found". +- Archived matters (`matters/_archived//parties.json`) are inside the screening scope. +- Matter creation is exclusive: the directory is created with an atomic exclusive `mkdir` under the + store lock, so two simultaneous writers cannot both create one matter id. +- A stale lock is reclaimed only when its recorded host matches this machine and its recorded process + is provably gone. Locks are never removed because they look old. + +## Runtime Environment + +The deterministic tools are plain Python 3 with no third-party packages, and every skill invokes them +as `python3`. + +- Windows without a `python3` alias: use `py -3` in place of `python3`, or create a `python3.exe` + copy/alias next to `python.exe` on `PATH`. Nothing else in the toolchain is platform-specific. +- Do not install packages for these scripts; a script that needs a dependency is a defect. + +`bootstrap_matter.py` exit codes: + +| Code | Meaning | +|---|---| +| 0 | Matter created and the local screen found nothing (`no-hit`) | +| 2 | Invalid arguments, unreadable store, or the store lock is held by a live writer | +| 3 | Refused: the matter id already exists, or it exists as an interrupted (`.pending`) bootstrap | +| 10 | Matter created but substantive work is blocked — `hit-review-required` or `coverage-incomplete` | + +`sync_run_manifest.py` and `validate_run.py` return 0 on success, 1 for validation failures +(`validate_run.py` only), and 2 for argument or IO errors. ## Currency Gate diff --git a/plugins/crablaw-cn/matter-core/schemas/conflict-check.schema.json b/plugins/crablaw-cn/matter-core/schemas/conflict-check.schema.json index 09e894b..7539532 100644 --- a/plugins/crablaw-cn/matter-core/schemas/conflict-check.schema.json +++ b/plugins/crablaw-cn/matter-core/schemas/conflict-check.schema.json @@ -6,7 +6,7 @@ "required": ["matterId", "status", "screenedAt", "queries", "hits"], "properties": { "matterId": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]{1,100}$" }, - "status": { "enum": ["pending", "no-hit", "hit-review-required", "cleared-by-lawyer", "declined"] }, + "status": { "enum": ["pending", "no-hit", "hit-review-required", "coverage-incomplete", "cleared-by-lawyer", "declined"] }, "screenedAt": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$", "format": "date" }, "screenedBy": { "type": "string", "minLength": 1 }, "queries": { "type": "array", "items": { "type": "string", "minLength": 1 }, "uniqueItems": true }, @@ -20,11 +20,30 @@ "matchedMatterId": { "type": "string", "pattern": "^[a-z0-9][a-z0-9._-]{1,100}$" }, "summary": { "type": "string", "minLength": 1 }, "risk": { "enum": ["low", "medium", "high", "unknown"] }, - "recommendedAction": { "type": "string", "minLength": 1 } + "recommendedAction": { "type": "string", "minLength": 1 }, + "matchedValue": { "type": "string", "minLength": 1 }, + "existingRole": { "type": "string", "minLength": 1 }, + "newRole": { "type": "string", "minLength": 1 }, + "relation": { + "enum": ["same-side-existing-client", "potential-adverse", "name-match-unclassified"] + } }, "additionalProperties": false } }, + "coverage": { + "type": "object", + "required": ["status", "scanned", "scopes"], + "properties": { + "status": { "enum": ["complete", "partial"] }, + "scanned": { "type": "integer", "minimum": 0 }, + "corrupt": { "type": "array", "items": { "type": "string", "minLength": 1 } }, + "refused": { "type": "array", "items": { "type": "string", "minLength": 1 } }, + "typeErrors": { "type": "array", "items": { "type": "string", "minLength": 1 } }, + "scopes": { "type": "array", "items": { "type": "string", "minLength": 1 } } + }, + "additionalProperties": false + }, "lawyerConfirmation": { "type": "object", "properties": { diff --git a/plugins/crablaw-cn/matter-core/schemas/source-record.schema.json b/plugins/crablaw-cn/matter-core/schemas/source-record.schema.json index 94618a0..6c7c64c 100644 --- a/plugins/crablaw-cn/matter-core/schemas/source-record.schema.json +++ b/plugins/crablaw-cn/matter-core/schemas/source-record.schema.json @@ -19,7 +19,7 @@ "contentHash": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, "confidentiality": { "enum": ["standard", "heightened", "clean-team"] }, "accessScope": { "type": "string", "minLength": 1 }, - "status": { "enum": ["unreviewed", "lawyer-reviewed", "source-needs-check", "superseded", "unknown"] }, + "status": { "enum": ["unreviewed", "verified", "lawyer-reviewed", "source-needs-check", "superseded", "unknown"] }, "reviewer": { "type": "string", "minLength": 1 } }, "allOf": [ @@ -37,6 +37,13 @@ }, "then": { "required": ["authority", "urlOrRecordId", "effectiveStatus"] } }, + { + "if": { + "properties": { "status": { "const": "verified" } }, + "required": ["status"] + }, + "then": { "required": ["urlOrRecordId", "effectiveStatus"] } + }, { "if": { "properties": { "status": { "const": "superseded" } }, diff --git a/plugins/crablaw-cn/matter-core/scripts/_matter_common.py b/plugins/crablaw-cn/matter-core/scripts/_matter_common.py index 6de78e9..1590620 100644 --- a/plugins/crablaw-cn/matter-core/scripts/_matter_common.py +++ b/plugins/crablaw-cn/matter-core/scripts/_matter_common.py @@ -9,6 +9,8 @@ import json import os import re +import socket +import stat as stat_module import tempfile import time from pathlib import Path @@ -16,6 +18,8 @@ ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{1,120}$") +PENDING_MARKER_NAME = ".pending" +PENDING_MATTER_MESSAGE = "matter is pending (incomplete bootstrap)" MATTER_TYPES = { "contract", "data-compliance", @@ -78,8 +82,49 @@ def resolve_root(raw: Optional[str], create: bool = True) -> Path: return root.resolve() +LINK_LIKE_REPARSE_TAGS = { + tag + for tag in ( + getattr(stat_module, "IO_REPARSE_TAG_SYMLINK", None), + getattr(stat_module, "IO_REPARSE_TAG_MOUNT_POINT", None), + getattr(stat_module, "IO_REPARSE_TAG_APPEXECLINK", None), + ) + if tag is not None +} + + +def is_link_like(path: Path) -> bool: + """True for anything that redirects to another location. + + POSIX symlinks are reported by ``S_ISLNK``. Windows directory junctions are + NOT: ``Path.is_symlink()`` and ``os.path.islink()`` both return False for a + junction on CPython 3.11 (``os.path.isjunction`` only exists from 3.12), and + the only signal available is the reparse tag on ``lstat``. A junction is a + redirection just like a symlink, so it must be refused the same way. + """ + + try: + info = path.lstat() + except (OSError, ValueError): + return False + if stat_module.S_ISLNK(info.st_mode): + return True + return getattr(info, "st_reparse_tag", 0) in LINK_LIKE_REPARSE_TAGS + + def safe_path(root: Path, *parts: str, must_exist: bool = False) -> Path: candidate = root.joinpath(*parts) + + try: + relative_parts = candidate.relative_to(root).parts + except ValueError as exc: + raise ValueError("managed path escapes the matter-store root") from exc + current = root + for part in relative_parts: + current = current / part + if is_link_like(current): + raise ValueError(f"managed path crosses a symbolic link: {current.relative_to(root)}") + resolved = candidate.resolve(strict=must_exist) try: common = Path(os.path.commonpath([str(root), str(resolved)])) @@ -87,12 +132,6 @@ def safe_path(root: Path, *parts: str, must_exist: bool = False) -> Path: raise ValueError("managed path escapes the matter-store root") from exc if common != root: raise ValueError("managed path escapes the matter-store root") - - current = root - for part in candidate.relative_to(root).parts: - current = current / part - if current.exists() and current.is_symlink(): - raise ValueError(f"managed path crosses a symbolic link: {current.relative_to(root)}") return resolved @@ -172,6 +211,107 @@ def append_jsonl(path: Path, payload: Any) -> None: os.fsync(handle.fileno()) +def lock_payload() -> str: + return f"pid={os.getpid()} host={socket.gethostname()} created={utc_now()}\n" + + +def parse_lock_metadata(content: str) -> dict[str, str]: + metadata: dict[str, str] = {} + for token in content.split(): + key, separator, value = token.partition("=") + if separator and key and value: + metadata.setdefault(key, value) + return metadata + + +def process_is_alive(pid: int) -> bool: + """Liveness probe that never disturbs the probed process. + + ``os.kill(pid, 0)`` must not be used on Windows: CPython implements + ``os.kill`` there as ``TerminateProcess(handle, sig)``, so signal 0 would + kill the holder instead of reporting on it. Windows therefore goes through + ``OpenProcess`` + ``GetExitCodeProcess``. Every undecidable answer is + resolved as "alive" so an ambiguous probe can never delete a live lock. + """ + + if pid <= 0: + return False + if os.name == "nt": + import ctypes + from ctypes import wintypes + + process_query_limited_information = 0x1000 + still_active = 259 + error_invalid_parameter = 87 + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + kernel32.OpenProcess.restype = wintypes.HANDLE + kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)] + kernel32.GetExitCodeProcess.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + handle = kernel32.OpenProcess(process_query_limited_information, False, pid) + if not handle: + # 87 is the only answer that means "no such process id"; every other + # failure (for example access denied) means the process exists. + return ctypes.get_last_error() != error_invalid_parameter + try: + exit_code = wintypes.DWORD() + if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)): + return True + return exit_code.value == still_active + finally: + kernel32.CloseHandle(handle) + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError: + return True + return True + + +def reclaim_stale_lock(path: Path) -> bool: + """Remove a lock whose owning process is provably gone. Never age-based. + + The lock is retired by renaming it to a private name first: on Windows that + rename fails while any process still holds the file open, and on every + platform only one racing reclaimer can win the rename, so a live lock cannot + be deleted by a slow read followed by a fast unlink. + """ + + try: + content = path.read_text(encoding="utf-8", errors="replace") + except FileNotFoundError: + return True + except OSError: + return False + metadata = parse_lock_metadata(content) + raw_pid = metadata.get("pid") + host = metadata.get("host") + if not raw_pid or not host: + return False + if host != socket.gethostname(): + return False + try: + pid = int(raw_pid) + except ValueError: + return False + if process_is_alive(pid): + return False + staged = path.with_name(f"{path.name}.stale-{os.getpid()}-{time.monotonic_ns()}") + try: + os.rename(path, staged) + except OSError: + return False + try: + os.unlink(staged) + except OSError: + pass + return True + + @contextlib.contextmanager def file_lock(path: Path, timeout_seconds: float = 0.0) -> Iterator[None]: ensure_private_dir(path.parent) @@ -180,8 +320,10 @@ def file_lock(path: Path, timeout_seconds: float = 0.0) -> Iterator[None]: while descriptor is None: try: descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) - os.write(descriptor, f"pid={os.getpid()} created={utc_now()}\n".encode("utf-8")) + os.write(descriptor, lock_payload().encode("utf-8")) except FileExistsError: + if reclaim_stale_lock(path): + continue if time.monotonic() >= deadline: raise ValueError(f"matter store is locked: {path}") time.sleep(0.05) @@ -196,6 +338,18 @@ def file_lock(path: Path, timeout_seconds: float = 0.0) -> Iterator[None]: pass +def pending_marker_path(matter_dir: Path) -> Path: + return matter_dir / PENDING_MARKER_NAME + + +def matter_is_pending(matter_dir: Path) -> bool: + return pending_marker_path(matter_dir).exists() + + +def sha256_text(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: diff --git a/plugins/crablaw-cn/matter-core/scripts/bootstrap_matter.py b/plugins/crablaw-cn/matter-core/scripts/bootstrap_matter.py index 9ac86cf..807a6e7 100644 --- a/plugins/crablaw-cn/matter-core/scripts/bootstrap_matter.py +++ b/plugins/crablaw-cn/matter-core/scripts/bootstrap_matter.py @@ -12,14 +12,17 @@ import os import re from pathlib import Path -from typing import Any +from typing import Any, Optional from _matter_common import ( + PENDING_MATTER_MESSAGE, append_jsonl, atomic_write_json, ensure_private_dir, file_lock, load_json, + matter_is_pending, + pending_marker_path, require_id, require_matter_type, resolve_root, @@ -29,6 +32,15 @@ ) +EXIT_OK = 0 +EXIT_USAGE_OR_IO = 2 +EXIT_CONFLICT = 3 +EXIT_REVIEW_REQUIRED = 10 + +CLIENT_SIDE_ROLES = {"client", "client-record"} +ADVERSE_ROLES = {"counterparty"} +SCAN_SCOPES = ("clients", "matters", "matters/_archived") + PARTY_ROLES = { "client", "counterparty", @@ -62,67 +74,213 @@ def parse_party(raw: str) -> dict[str, Any]: return {"role": role, "displayName": display_name, "normalizedNames": normalized_names} -def existing_name_records(root: Path, current_matter_id: str) -> list[tuple[str, str, str]]: - records: list[tuple[str, str, str]] = [] - for client_path in safe_path(root, "clients").glob("*/client.json"): - if client_path.is_symlink(): +class NameRecord: + """One searchable name taken from an existing client or party record.""" + + __slots__ = ("normalized", "value", "source", "role") + + def __init__(self, normalized: str, value: str, source: str, role: str) -> None: + self.normalized = normalized + self.value = value + self.source = source + self.role = role + + +def new_coverage() -> dict[str, Any]: + return { + "status": "complete", + "scanned": 0, + "corrupt": [], + "refused": [], + "typeErrors": [], + "scopes": list(SCAN_SCOPES), + } + + +def _relative_label(root: Path, *parts: str) -> str: + return "/".join(parts) + + +def _candidate_directories(root: Path, scope_parts: tuple[str, ...], coverage: dict[str, Any]) -> list[str]: + """List the child directory names of one scope without following redirections.""" + + try: + scope_dir = safe_path(root, *scope_parts) + except ValueError as exc: + coverage["refused"].append(f"{_relative_label(root, *scope_parts)}: {exc}") + return [] + if not scope_dir.is_dir(): + return [] + try: + return sorted(entry.name for entry in scope_dir.iterdir()) + except OSError as exc: + coverage["refused"].append(f"{_relative_label(root, *scope_parts)}: {exc}") + return [] + + +def _read_scanned_payload( + root: Path, + parts: tuple[str, ...], + coverage: dict[str, Any], +) -> Optional[dict[str, Any]]: + """Read one record file, accounting for every way it can fail to be scanned.""" + + label = _relative_label(root, *parts) + try: + managed = safe_path(root, *parts) + except ValueError as exc: + coverage["refused"].append(f"{label}: {exc}") + return None + if not managed.is_file(): + return None + try: + # Re-run the guard with strict resolution now that the file must exist. + managed = safe_path(root, *parts, must_exist=True) + except ValueError as exc: + coverage["refused"].append(f"{label}: {exc}") + return None + except OSError as exc: + coverage["refused"].append(f"{label}: {exc}") + return None + coverage["scanned"] += 1 + try: + payload = load_json(managed) + except ValueError as exc: + coverage["corrupt"].append(f"{label}: {exc}") + return None + except OSError as exc: + coverage["refused"].append(f"{label}: {exc}") + return None + if not isinstance(payload, dict): + coverage["typeErrors"].append( + f"{label}: expected a JSON object, got {type(payload).__name__}" + ) + return None + return payload + + +def _collect_party_names( + payload: dict[str, Any], + label: str, + records: list[NameRecord], + coverage: dict[str, Any], +) -> None: + parties = payload.get("parties", []) or [] + if not isinstance(parties, list): + coverage["typeErrors"].append(f"{label}: parties must be an array") + return + for position, party in enumerate(parties, 1): + if not isinstance(party, dict): + coverage["typeErrors"].append(f"{label}: parties[{position}] must be an object") continue - try: - payload = load_json(client_path) - except ValueError: + role = party.get("role") + role = str(role) if isinstance(role, str) and role else "unknown" + values = [party.get("displayName"), party.get("unifiedSocialCreditCode")] + aliases = party.get("normalizedNames", []) or [] + if isinstance(aliases, list): + values.extend(aliases) + else: + coverage["typeErrors"].append(f"{label}: parties[{position}].normalizedNames must be an array") + for value in values: + if value: + records.append(NameRecord(normalize_name(str(value)), str(value), label, role)) + + +def existing_name_records( + root: Path, current_matter_id: str +) -> tuple[list[NameRecord], dict[str, Any]]: + records: list[NameRecord] = [] + coverage = new_coverage() + + for client_id in _candidate_directories(root, ("clients",), coverage): + parts = ("clients", client_id, "client.json") + label = _relative_label(root, *parts) + payload = _read_scanned_payload(root, parts, coverage) + if payload is None: continue for key in ("displayName", "unifiedSocialCreditCode"): value = payload.get(key) if value: - records.append((normalize_name(str(value)), str(value), str(client_path.relative_to(root)))) + records.append(NameRecord(normalize_name(str(value)), str(value), label, "client-record")) for key in ("formerNames", "englishNames", "aliases", "affiliates"): - for value in payload.get(key, []) or []: - records.append((normalize_name(str(value)), str(value), str(client_path.relative_to(root)))) - - for parties_path in safe_path(root, "matters").glob("*/parties.json"): - if parties_path.parent.name == current_matter_id or parties_path.is_symlink(): - continue - try: - payload = load_json(parties_path) - except ValueError: - continue - for party in payload.get("parties", []) or []: - values = [party.get("displayName"), party.get("unifiedSocialCreditCode")] - values.extend(party.get("normalizedNames", []) or []) + values = payload.get(key, []) or [] + if not isinstance(values, list): + coverage["typeErrors"].append(f"{label}: {key} must be an array") + continue for value in values: if value: records.append( - (normalize_name(str(value)), str(value), str(parties_path.relative_to(root))) + NameRecord(normalize_name(str(value)), str(value), label, "client-record") ) - return records + for matter_id in _candidate_directories(root, ("matters",), coverage): + if matter_id == current_matter_id or matter_id == "_archived": + continue + parts = ("matters", matter_id, "parties.json") + payload = _read_scanned_payload(root, parts, coverage) + if payload is None: + continue + _collect_party_names(payload, _relative_label(root, *parts), records, coverage) + + for matter_id in _candidate_directories(root, ("matters", "_archived"), coverage): + if matter_id == current_matter_id: + continue + parts = ("matters", "_archived", matter_id, "parties.json") + payload = _read_scanned_payload(root, parts, coverage) + if payload is None: + continue + _collect_party_names(payload, _relative_label(root, *parts), records, coverage) -def conflict_hits(root: Path, matter_id: str, parties: list[dict[str, Any]]) -> list[dict[str, str]]: - existing = existing_name_records(root, matter_id) + if coverage["corrupt"] or coverage["refused"] or coverage["typeErrors"]: + coverage["status"] = "partial" + return records, coverage + + +def classify_relation(existing_role: str, new_role: str) -> str: + if existing_role in CLIENT_SIDE_ROLES and new_role in CLIENT_SIDE_ROLES: + return "same-side-existing-client" + if existing_role in CLIENT_SIDE_ROLES and new_role in ADVERSE_ROLES: + return "potential-adverse" + if existing_role in ADVERSE_ROLES and new_role in CLIENT_SIDE_ROLES: + return "potential-adverse" + return "name-match-unclassified" + + +def conflict_hits( + root: Path, matter_id: str, parties: list[dict[str, Any]] +) -> tuple[list[dict[str, str]], dict[str, Any]]: + existing, coverage = existing_name_records(root, matter_id) hits: list[dict[str, str]] = [] - seen: set[tuple[str, str]] = set() + seen: set[tuple[str, str, str, str]] = set() for party in parties: + new_role = str(party.get("role") or "unknown") values = [party.get("displayName"), *(party.get("normalizedNames", []) or [])] for value in values: if not value: continue normalized = normalize_name(str(value)) - for existing_normalized, existing_value, source in existing: - if not normalized or normalized != existing_normalized: + if not normalized: + continue + for record in existing: + if normalized != record.normalized: continue - key = (normalized, source) + key = (normalized, record.source, record.role, new_role) if key in seen: continue seen.add(key) hits.append( { - "source": source, - "summary": f"Local matter-store normalized-name match for {existing_value}", + "source": record.source, + "matchedValue": record.value, + "existingRole": record.role, + "newRole": new_role, + "relation": classify_relation(record.role, new_role), + "summary": f"Local matter-store normalized-name match for {record.value}", "risk": "unknown", "recommendedAction": "Stop substantive work until the responsible lawyer reviews the match.", } ) - return hits + return hits, coverage def main() -> int: @@ -153,8 +311,6 @@ def main() -> int: ensure_private_dir(safe_path(root, "clients")) ensure_private_dir(safe_path(root, "matters")) matter_dir = safe_path(root, "matters", matter_id) - if matter_dir.exists(): - raise ValueError(f"matter already exists; refusing to overwrite: {matter_id}") parties = [parse_party(raw) for raw in args.party] if not any(party["role"] == "client" for party in parties): @@ -168,9 +324,38 @@ def main() -> int: ) with file_lock(safe_path(root, ".matter-store.lock"), timeout_seconds=1.0): - hits = conflict_hits(root, matter_id, parties) - conflict_status = "hit-review-required" if hits else "no-hit" - matter_status = "pending-conflict-review" if hits else "active" + # Claim the matter id exclusively before anything else: the existence + # check and the creation must be the same filesystem operation, or two + # writers that both passed a separate check will both create. + try: + os.mkdir(matter_dir) + except FileExistsError: + reason = ( + PENDING_MATTER_MESSAGE + if matter_is_pending(matter_dir) + else "matter already exists; refusing to overwrite" + ) + print( + json.dumps( + {"status": "conflict", "matterId": matter_id, "error": f"{reason}: {matter_id}"}, + ensure_ascii=False, + ) + ) + return EXIT_CONFLICT + try: + matter_dir.chmod(0o700) + except OSError: + pass + touch_private(pending_marker_path(matter_dir)) + + hits, coverage = conflict_hits(root, matter_id, parties) + if coverage["status"] != "complete": + conflict_status = "coverage-incomplete" + elif hits: + conflict_status = "hit-review-required" + else: + conflict_status = "no-hit" + matter_status = "active" if conflict_status == "no-hit" else "pending-conflict-review" opened_at = today() client_dir = ensure_private_dir(safe_path(root, "clients", client_id)) @@ -190,7 +375,6 @@ def main() -> int: }, ) - ensure_private_dir(matter_dir) ensure_private_dir(safe_path(matter_dir, "outputs")) ensure_private_dir(safe_path(matter_dir, "runs")) @@ -228,6 +412,7 @@ def main() -> int: } ), "hits": hits, + "coverage": coverage, "lawyerConfirmation": { "status": "not-reviewed", "notes": "Preliminary local screen only; final conflict decision remains with the responsible lawyer.", @@ -247,10 +432,16 @@ def main() -> int: "matterId": matter_id, "createdAt": opened_at, "conflictStatus": conflict_status, + "coverageStatus": coverage["status"], "tool": "bootstrap_matter.py", }, ) + # Every file is written and readable back; only now is the matter complete. + for filename in ("matter.json", "parties.json", "permissions.json", "conflict-check.json"): + load_json(safe_path(matter_dir, filename, must_exist=True)) + pending_marker_path(matter_dir).unlink() + print( json.dumps( { @@ -258,14 +449,15 @@ def main() -> int: "matterId": matter_id, "conflictStatus": conflict_status, "substantiveWorkAllowed": conflict_status == "no-hit", + "coverage": coverage, }, ensure_ascii=False, ) ) - return 10 if hits else 0 + return EXIT_OK if conflict_status == "no-hit" else EXIT_REVIEW_REQUIRED except (OSError, ValueError) as exc: print(json.dumps({"status": "failed", "error": str(exc)}, ensure_ascii=False)) - return 2 + return EXIT_USAGE_OR_IO if __name__ == "__main__": diff --git a/plugins/crablaw-cn/matter-core/scripts/sync_run_manifest.py b/plugins/crablaw-cn/matter-core/scripts/sync_run_manifest.py index 0bb3dd5..4691112 100644 --- a/plugins/crablaw-cn/matter-core/scripts/sync_run_manifest.py +++ b/plugins/crablaw-cn/matter-core/scripts/sync_run_manifest.py @@ -17,14 +17,107 @@ atomic_write_json, file_lock, load_json, + load_jsonl, require_id, resolve_root, safe_path, sha256_file, + sha256_text, utc_now, ) +def source_digests(matter_dir: Path) -> list[dict[str, str]]: + """Hash every source record so a source edit is as detectable as a document edit.""" + + sources_path = safe_path(matter_dir, "sources.jsonl") + if not sources_path.exists(): + return [] + digests: dict[str, str] = {} + for row in load_jsonl(safe_path(matter_dir, "sources.jsonl", must_exist=True)): + if not isinstance(row, dict): + continue + source_id = row.get("sourceId") + if not isinstance(source_id, str) or not source_id: + continue + digests[source_id] = sha256_text(json.dumps(row, sort_keys=True)) + return [{"sourceId": key, "sha256": digests[key]} for key in sorted(digests)] + + +def issues_touching_sources( + changed_source_ids: set[str], + document_index: dict[str, Any], + issue_rows: list[dict[str, Any]], + run_dir: Path, +) -> set[str]: + """Map changed source records onto the issues that rely on them.""" + + if not changed_source_ids: + return set() + affected: set[str] = set() + + changed_document_ids = { + document.get("documentId") + for document in document_index.get("documents", []) + if document.get("sourceRecordId") in changed_source_ids and document.get("documentId") + } + if changed_document_ids: + for issue in issue_rows: + issue_id = issue.get("issueId") + if issue_id and changed_document_ids.intersection(issue.get("documentIds", []) or []): + affected.add(issue_id) + + claim_map_path = safe_path(run_dir, "claim-evidence-map.json") + if claim_map_path.exists(): + claim_map = load_json(claim_map_path) + claim_issue = { + claim.get("claimId"): claim.get("issueId") + for claim in claim_map.get("claims", []) + if isinstance(claim, dict) + } + for element in claim_map.get("elements", []): + if not isinstance(element, dict): + continue + if changed_source_ids.intersection(element.get("sourceRecordIds", []) or []): + issue_id = claim_issue.get(element.get("claimId")) + if issue_id: + affected.add(issue_id) + + findings_path = safe_path(run_dir, "analyzer-findings.json") + if findings_path.exists(): + findings = load_json(findings_path) + for finding in findings.get("findings", []): + if not isinstance(finding, dict): + continue + if changed_source_ids.intersection(finding.get("sourceRecordIds", []) or []): + issue_id = finding.get("issueId") + if issue_id: + affected.add(issue_id) + + return affected + + +def carried_stale_issue_ids( + manifest: dict[str, Any], issue_rows: list[dict[str, Any]] +) -> set[str]: + """Keep a prior stale mark until the issue tree itself says it was reanalyzed. + + A sync that finds no new change is not evidence that the previous change was + addressed, so `unchanged` must never clear the ledger. + """ + + status_by_issue = { + issue.get("issueId"): issue.get("status") + for issue in issue_rows + if isinstance(issue, dict) and issue.get("issueId") + } + return { + issue_id + for issue_id in manifest.get("staleIssueIds", []) or [] + if status_by_issue.get(issue_id) == "stale" + } + + def descendants_of_stale(issues: list[dict[str, Any]], initial: set[str]) -> set[str]: stale = set(initial) changed = True @@ -39,6 +132,117 @@ def descendants_of_stale(issues: list[dict[str, Any]], initial: set[str]) -> set return stale +def synchronize(matter_dir: Path, run_dir: Path, matter_id: str, run_id: str, apply: bool) -> dict[str, Any]: + document_index_path = safe_path(run_dir, "document-index.json", must_exist=True) + issue_tree_path = safe_path(run_dir, "issue-tree.json", must_exist=True) + manifest_path = safe_path(run_dir, "run-manifest.json") + document_index = load_json(document_index_path) + issue_tree = load_json(issue_tree_path) + + now = utc_now() + if manifest_path.exists(): + manifest = load_json(manifest_path) + previous = {item.get("documentId"): item.get("sha256") for item in manifest.get("documents", [])} + previous_sources = { + item.get("sourceId"): item.get("sha256") for item in manifest.get("sources", []) or [] + } + revision = int(manifest.get("revision", 0)) + 1 + else: + previous = {} + previous_sources = {} + revision = 1 + manifest = { + "schemaVersion": 1, + "runId": run_id, + "matterId": matter_id, + "revision": revision, + "status": "draft", + "startedAt": now, + "updatedAt": now, + "documents": [], + "sources": [], + "artifacts": [], + "staleIssueIds": [], + "completedStepIds": [], + "reviewState": "not-ready", + "externalRelease": "prohibited", + } + + issue_rows = issue_tree.get("issues", []) + carried_stale = carried_stale_issue_ids(manifest, issue_rows) + + current_documents: list[dict[str, str]] = [] + changed_document_ids: set[str] = set() + for document in document_index.get("documents", []): + document_id = document.get("documentId") + relative_path = document.get("path") + if not document_id or not relative_path: + raise ValueError("document-index entry requires documentId and path") + managed_path = safe_path(matter_dir, *Path(relative_path).parts, must_exist=True) + digest = sha256_file(managed_path) + if previous.get(document_id) != digest: + changed_document_ids.add(document_id) + document["sha256"] = digest + current_documents.append({"documentId": document_id, "sha256": digest}) + + removed_document_ids = set(previous) - {item["documentId"] for item in current_documents} + changed_document_ids.update(removed_document_ids) + + current_sources = source_digests(matter_dir) + changed_source_ids = { + item["sourceId"] for item in current_sources if previous_sources.get(item["sourceId"]) != item["sha256"] + } + changed_source_ids.update(set(previous_sources) - {item["sourceId"] for item in current_sources}) + + direct_stale = { + issue.get("issueId") + for issue in issue_rows + if issue.get("issueId") and changed_document_ids.intersection(issue.get("documentIds", []) or []) + } + direct_stale |= issues_touching_sources(changed_source_ids, document_index, issue_rows, run_dir) + stale_issue_ids = descendants_of_stale(issue_rows, direct_stale | carried_stale) + + for issue in issue_rows: + if issue.get("issueId") in stale_issue_ids: + issue["status"] = "stale" + for artifact in manifest.get("artifacts", []): + if changed_document_ids.intersection(artifact.get("dependsOnDocumentIds", [])) or stale_issue_ids.intersection( + artifact.get("dependsOnIssueIds", []) + ): + artifact["status"] = "stale" + + manifest["revision"] = revision + manifest["updatedAt"] = now + manifest["documents"] = sorted(current_documents, key=lambda item: item["documentId"]) + manifest["sources"] = current_sources + manifest["staleIssueIds"] = sorted(stale_issue_ids) + if changed_document_ids or changed_source_ids or stale_issue_ids: + manifest["status"] = "stale" + + result = { + "status": "apply-ready" if (changed_document_ids or changed_source_ids) else "unchanged", + "matterId": matter_id, + "runId": run_id, + "changedDocumentIds": sorted(changed_document_ids), + "changedSourceIds": sorted(changed_source_ids), + "staleIssueIds": sorted(stale_issue_ids), + "applied": apply, + } + if apply: + atomic_write_json(document_index_path, document_index) + atomic_write_json(issue_tree_path, issue_tree) + relative_document_index = str(document_index_path.relative_to(matter_dir)) + relative_issue_tree = str(issue_tree_path.relative_to(matter_dir)) + for artifact in manifest.get("artifacts", []): + if artifact.get("path") == relative_document_index: + artifact["sha256"] = sha256_file(document_index_path) + artifact["status"] = "validated" + if artifact.get("path") == relative_issue_tree: + artifact["sha256"] = sha256_file(issue_tree_path) + atomic_write_json(manifest_path, manifest) + return result + + def main() -> int: os.umask(0o077) parser = argparse.ArgumentParser(description=__doc__) @@ -54,97 +258,14 @@ def main() -> int: root = resolve_root(args.root, create=False) matter_dir = safe_path(root, "matters", matter_id, must_exist=True) run_dir = safe_path(matter_dir, "runs", run_id, must_exist=True) - document_index_path = safe_path(run_dir, "document-index.json", must_exist=True) - issue_tree_path = safe_path(run_dir, "issue-tree.json", must_exist=True) - manifest_path = safe_path(run_dir, "run-manifest.json") - document_index = load_json(document_index_path) - issue_tree = load_json(issue_tree_path) - - now = utc_now() - if manifest_path.exists(): - manifest = load_json(manifest_path) - previous = {item.get("documentId"): item.get("sha256") for item in manifest.get("documents", [])} - revision = int(manifest.get("revision", 0)) + 1 - else: - previous = {} - revision = 1 - manifest = { - "schemaVersion": 1, - "runId": run_id, - "matterId": matter_id, - "revision": revision, - "status": "draft", - "startedAt": now, - "updatedAt": now, - "documents": [], - "artifacts": [], - "staleIssueIds": [], - "completedStepIds": [], - "reviewState": "not-ready", - "externalRelease": "prohibited", - } - - current_documents: list[dict[str, str]] = [] - changed_document_ids: set[str] = set() - for document in document_index.get("documents", []): - document_id = document.get("documentId") - relative_path = document.get("path") - if not document_id or not relative_path: - raise ValueError("document-index entry requires documentId and path") - managed_path = safe_path(matter_dir, *Path(relative_path).parts, must_exist=True) - digest = sha256_file(managed_path) - if previous.get(document_id) != digest: - changed_document_ids.add(document_id) - document["sha256"] = digest - current_documents.append({"documentId": document_id, "sha256": digest}) - - removed_document_ids = set(previous) - {item["documentId"] for item in current_documents} - changed_document_ids.update(removed_document_ids) - direct_stale = { - issue.get("issueId") - for issue in issue_tree.get("issues", []) - if issue.get("issueId") - and changed_document_ids.intersection(issue.get("documentIds", [])) - } - stale_issue_ids = descendants_of_stale(issue_tree.get("issues", []), direct_stale) - for issue in issue_tree.get("issues", []): - if issue.get("issueId") in stale_issue_ids: - issue["status"] = "stale" - for artifact in manifest.get("artifacts", []): - if changed_document_ids.intersection(artifact.get("dependsOnDocumentIds", [])) or stale_issue_ids.intersection( - artifact.get("dependsOnIssueIds", []) - ): - artifact["status"] = "stale" - - manifest["revision"] = revision - manifest["updatedAt"] = now - manifest["documents"] = sorted(current_documents, key=lambda item: item["documentId"]) - manifest["staleIssueIds"] = sorted(stale_issue_ids) - if changed_document_ids: - manifest["status"] = "stale" - - result = { - "status": "apply-ready" if changed_document_ids else "unchanged", - "matterId": matter_id, - "runId": run_id, - "changedDocumentIds": sorted(changed_document_ids), - "staleIssueIds": sorted(stale_issue_ids), - "applied": args.apply, - } if args.apply: + # The whole read-modify-write runs under the writer lock; reading first + # and locking later would let a concurrent writer land between them. with file_lock(safe_path(matter_dir, ".writer.lock"), timeout_seconds=1.0): - atomic_write_json(document_index_path, document_index) - atomic_write_json(issue_tree_path, issue_tree) - relative_document_index = str(document_index_path.relative_to(matter_dir)) - relative_issue_tree = str(issue_tree_path.relative_to(matter_dir)) - for artifact in manifest.get("artifacts", []): - if artifact.get("path") == relative_document_index: - artifact["sha256"] = sha256_file(document_index_path) - artifact["status"] = "validated" - if artifact.get("path") == relative_issue_tree: - artifact["sha256"] = sha256_file(issue_tree_path) - atomic_write_json(manifest_path, manifest) + result = synchronize(matter_dir, run_dir, matter_id, run_id, apply=True) + else: + result = synchronize(matter_dir, run_dir, matter_id, run_id, apply=False) print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 except (OSError, ValueError, json.JSONDecodeError) as exc: diff --git a/plugins/crablaw-cn/matter-core/scripts/validate_run.py b/plugins/crablaw-cn/matter-core/scripts/validate_run.py index a7b2008..a900f1d 100644 --- a/plugins/crablaw-cn/matter-core/scripts/validate_run.py +++ b/plugins/crablaw-cn/matter-core/scripts/validate_run.py @@ -10,8 +10,10 @@ from typing import Any from _matter_common import ( + PENDING_MATTER_MESSAGE, load_json, load_jsonl, + matter_is_pending, require_id, resolve_root, safe_path, @@ -26,6 +28,12 @@ CORE_SCHEMAS = PLUGIN_ROOT / "legal-core" / "schemas" ALLOWED_CONFLICT = {"no-hit", "cleared-by-lawyer"} TERMINAL_SPECIALIST = {"integrated", "reviewed", "closed"} +# A `[已核验-来源]` claim means the record was actually retrieved this session or +# confirmed by a lawyer. Anything that only failed to be marked as needing a check +# (`unreviewed`), or that is positively doubtful (`unknown`, `superseded`), is not +# a verification and must not satisfy the tag. +VERIFIED_SOURCE_TYPES = {"official-law", "official-guidance", "case"} +VERIFIED_SOURCE_STATUSES = {"verified", "lawyer-reviewed"} def add_schema_errors( @@ -61,6 +69,8 @@ def require_refs(values: list[str], available: set[str], label: str, errors: lis def validate_base_store(root: Path, matter_id: str, errors: list[str]) -> dict[str, Any]: matter_dir = safe_path(root, "matters", matter_id, must_exist=True) + if matter_is_pending(matter_dir): + errors.append(f"{PENDING_MATTER_MESSAGE}: {matter_id}") files = { "matter": ("matter.json", "matter.schema.json"), "parties": ("parties.json", "parties.schema.json"), @@ -229,8 +239,8 @@ def validate_cross_references( verified = [ source for source in source_records - if source.get("sourceType") in {"official-law", "official-guidance", "case"} - and source.get("status") != "source-needs-check" + if source.get("sourceType") in VERIFIED_SOURCE_TYPES + and source.get("status") in VERIFIED_SOURCE_STATUSES ] if not verified: errors.append(f"finding {finding_id} marks verified but has no verified official/case source") diff --git a/plugins/crablaw-cn/matter-core/skills/conflict-check/SKILL.md b/plugins/crablaw-cn/matter-core/skills/conflict-check/SKILL.md index 545f2fe..603c975 100644 --- a/plugins/crablaw-cn/matter-core/skills/conflict-check/SKILL.md +++ b/plugins/crablaw-cn/matter-core/skills/conflict-check/SKILL.md @@ -19,15 +19,18 @@ Run an initial conflicts screening workflow. This is not a final conflicts concl - Counterparties, affiliates, third parties, actual controllers, beneficial owners, opposing counsel, and natural persons. - Transaction or dispute subject matter. - Former names, aliases, English names, and normalized variants. -3. Search only authorized matter indexes or user-provided conflict records. Do not read unrelated matter files unless cross-matter access is explicitly authorized in `permissions.json`. +3. Search only authorized matter indexes or user-provided conflict records, including archived matters under `matters/_archived/`. Do not read unrelated matter files unless cross-matter access is explicitly authorized in `permissions.json`. 4. Record hits in `conflict-check.json`: - matched source or matter id. - hit summary. - preliminary risk. - recommended lawyer action. -5. Set status: - - `no-hit` if no relevant hit was found. + - the matched value, the role it holds in the existing record, the role it holds in this matter, and the resulting relation (`same-side-existing-client`, `potential-adverse`, or `name-match-unclassified`). A relation is context for the reviewing lawyer, never a conclusion. +5. Record what the screen could not read in the `coverage` block: records that failed to parse, records that are not JSON objects, and records refused because they sit behind a symlink or Windows directory junction. +6. Set status: + - `no-hit` if coverage is complete and no relevant hit was found. - `hit-review-required` if any relevant hit exists. + - `coverage-incomplete` if any record could not be read. An incomplete screen is not a `no-hit`, and it blocks substantive work exactly like a hit does. - never set `cleared-by-lawyer` unless the reviewing lawyer explicitly confirms. ## Stop Conditions @@ -50,6 +53,7 @@ After this skill finishes, route based on the screening status: AI-governance, regulatory, product, legal-aid, or matter operations. A caller that already names a bounded leaf task may route directly to that canonical `crablaw-cn:` after the gate passes. - `hit-review-required`: stop substantive domain work; escalate to the responsible lawyer for `cleared-by-lawyer` confirmation or matter decline. +- `coverage-incomplete`: stop substantive domain work; report exactly which records could not be read, repair or remove them, and re-run the screen. Do not ask a lawyer to clear a screen that never completed. - `pending`: re-run after the responsible lawyer reviews; do not allow domain skills to proceed. ## Schemas diff --git a/plugins/crablaw-cn/matter-core/skills/new-matter/SKILL.md b/plugins/crablaw-cn/matter-core/skills/new-matter/SKILL.md index fd4ec76..c51367f 100644 --- a/plugins/crablaw-cn/matter-core/skills/new-matter/SKILL.md +++ b/plugins/crablaw-cn/matter-core/skills/new-matter/SKILL.md @@ -46,10 +46,16 @@ Create a matter workspace. This skill opens the matter record but does not autho - empty `matters//sources.jsonl` - empty `matters//audit-log.jsonl` - `matters//outputs/` -4. Inspect the returned preliminary conflict status. A local name match sets +4. Read the exit code, not just the text. `0` means created with no local match; `10` means created + but blocked (`hit-review-required` or `coverage-incomplete`); `3` means the command refused + because the matter id already exists or is an interrupted (`.pending`) bootstrap; `2` means bad + arguments, an unreadable store, or a store lock held by a live writer. On Windows without a + `python3` alias, invoke the same command with `py -3`. +5. Inspect the returned preliminary conflict status. A local name match sets `hit-review-required` and blocks substantive work; absence of a local match is not a final lawyer - conflict opinion. -5. Stop before substantive analysis and direct the user to `crablaw-cn:conflict-check` for the + conflict opinion. A `coverage-incomplete` status means the screen could not read part of the + store — report the `coverage` block verbatim and treat it as blocking, never as "nothing found". +6. Stop before substantive analysis and direct the user to `crablaw-cn:conflict-check` for the responsible lawyer's workflow. ## Output diff --git a/src/policy/mcpContractValidator.ts b/src/policy/mcpContractValidator.ts index d75511d..6b218e0 100644 --- a/src/policy/mcpContractValidator.ts +++ b/src/policy/mcpContractValidator.ts @@ -2,8 +2,7 @@ import { readdir, readFile, stat } from "node:fs/promises"; import { existsSync } from "node:fs"; import path from "node:path"; import { - MCP_ALLOWED_PLUGIN, - MCP_ALLOWED_SERVER, + MCP_ALLOWED_LOCAL_SERVERS, MCP_PAUSED_MARKETPLACE_MARKER, MCP_PAUSED_PLUGIN_SET, } from "./mcpSafeBaseline.ts"; @@ -11,9 +10,10 @@ import { /** * Repo-wide MCP executable contract checks. * - * The 2026-08-22 emergency baseline is deliberately small: generation-1 hosts - * execute `.mcp.json` directly, so only the fully bundled html-video local - * sidecar may ship until host-side connector profiles and release gates exist. + * The baseline is deliberately small: generation-1 hosts execute `.mcp.json` + * directly, so only the fully bundled first-party local sidecars in + * MCP_ALLOWED_LOCAL_SERVERS may ship until host-side connector profiles and + * release gates exist. */ export type McpContractIssue = { @@ -62,6 +62,29 @@ function serverArgStrings(definition: ServerDefinition): string[] { return parts; } +/** + * `${user_config.KEY}` references the host substitutes from the value the user + * supplied for `plugin.json.userConfig[KEY]`. Substitution throws when the value + * is missing and the host never writes the declared `default`, so an allowed + * plugin may only reference keys it declares as `required: true`. + */ +const USER_CONFIG_REFERENCE = /\$\{user_config\.([A-Za-z0-9_]+)\}/gu; + +function userConfigReferences(definition: ServerDefinition): string[] { + const env = definition.env; + if (!env || typeof env !== "object" || Array.isArray(env)) return []; + const keys = new Set(); + for (const value of Object.values(env as Record)) { + if (typeof value !== "string") continue; + for (const match of value.matchAll(USER_CONFIG_REFERENCE)) keys.add(match[1]!); + } + return [...keys]; +} + +function allowedPluginList(): string { + return [...MCP_ALLOWED_LOCAL_SERVERS.keys()].join(", "); +} + function hasFloatingVersion(parts: string[]): boolean { const joined = parts.join(" "); if (joined.includes("@latest")) return true; @@ -133,15 +156,16 @@ export async function validateMcpContract(root: string): Promise typeof name === "string") : []; - if (pluginName === MCP_ALLOWED_PLUGIN) { - if (required.length !== 1 || required[0] !== MCP_ALLOWED_SERVER) { - issues.push({ severity: "error", path: path.relative(root, manifestPath), message: `emergency MCP safe baseline requires requiredMcpServers=["${MCP_ALLOWED_SERVER}"]` }); + const allowedServer = MCP_ALLOWED_LOCAL_SERVERS.get(pluginName); + if (allowedServer !== undefined) { + if (required.length !== 1 || required[0] !== allowedServer) { + issues.push({ severity: "error", path: path.relative(root, manifestPath), message: `MCP safe baseline requires requiredMcpServers=["${allowedServer}"]` }); } if (!existsSync(path.join(pluginRoot, ".mcp.json"))) { - issues.push({ severity: "error", path: path.relative(root, manifestPath), message: "emergency MCP safe baseline requires the bundled html-video .mcp.json" }); + issues.push({ severity: "error", path: path.relative(root, manifestPath), message: `MCP safe baseline requires the bundled ${allowedServer} .mcp.json` }); } } else if (required.length > 0) { - issues.push({ severity: "error", path: path.relative(root, manifestPath), message: `requiredMcpServers is reserved for ${MCP_ALLOWED_PLUGIN} during the emergency MCP safe baseline` }); + issues.push({ severity: "error", path: path.relative(root, manifestPath), message: `requiredMcpServers is reserved for the first-party local servers (${allowedPluginList()}) during the MCP safe baseline` }); } if (MCP_PAUSED_PLUGIN_SET.has(pluginName)) { @@ -158,8 +182,9 @@ export async function validateMcpContract(root: string): Promise + : {}; + for (const definition of Object.values(servers)) { + for (const key of userConfigReferences(definition)) { + const field = declared[key]; + const isRequired = Boolean(field && typeof field === "object" && !Array.isArray(field) && (field as Record).required === true); + if (!isRequired) { + issues.push({ + severity: "error", + path: relativeMcp, + message: `env references \${user_config.${key}} but plugin.json userConfig.${key} is not declared with required: true; the host throws on substitution when the value is missing and never writes the declared default`, + }); + } + } + } } for (const name of required) { if (!servers[name]) { diff --git a/src/policy/mcpSafeBaseline.ts b/src/policy/mcpSafeBaseline.ts index 0a5dc06..94e8cf3 100644 --- a/src/policy/mcpSafeBaseline.ts +++ b/src/policy/mcpSafeBaseline.ts @@ -1,14 +1,39 @@ /** - * Emergency executable MCP baseline established by the 2026-08-22 health audit. + * First-party local MCP baseline. * - * Generation-1 hosts execute `.mcp.json` directly and do not understand a - * connector catalog or release leases. Until a host-side fail-closed loader is - * released, the official marketplace therefore publishes exactly one locally - * bundled MCP server and no remote/external-service connector configuration. + * v1 (2026-08-22 health audit) published exactly one locally bundled MCP server + * because generation-1 hosts execute `.mcp.json` directly and understood neither + * a connector catalog nor release leases. + * + * v2 (2026-09-12, three-repo root-cause remediation, decision D-0(c)) widens the + * allow list to the two *first-party* servers that ship their own prebuilt + * artifact inside the plugin and speak stdio to a sibling process: html-video + * and media-ops. Nothing else changes — the remaining 41 connectors stay paused, + * remote/SSE transport stays forbidden, and every allowed server must still be + * fully pinned, install nothing on launch and reference a committed artifact. + * + * media-ops additionally injects its trusted local principal from host + * `user_config`, so an allowed plugin's `.mcp.json` may only reference + * `${user_config.X}` keys the manifest declares as `required: true` (the host + * throws on substitution when a value is missing and never writes `default`). */ -export const MCP_SAFE_BASELINE_ID = "mcp-emergency-safe-baseline-v1"; +export const MCP_SAFE_BASELINE_ID = "mcp-safe-baseline-v2-first-party-local"; +/** pluginId → the single stdio server name that plugin may publish. */ +export const MCP_ALLOWED_LOCAL_SERVERS: ReadonlyMap = new Map([ + ["crabcode-html-video", "html-video"], + ["crabcode-media-ops", "mediaops"], +]); + +export const MCP_ALLOWED_PLUGIN_SET: ReadonlySet = new Set( + MCP_ALLOWED_LOCAL_SERVERS.keys(), +); + +/** + * v1 aliases, kept because scripts and tests still name the html-video sidecar + * through them. New code should read MCP_ALLOWED_LOCAL_SERVERS. + */ export const MCP_ALLOWED_PLUGIN = "crabcode-html-video"; export const MCP_ALLOWED_SERVER = "html-video"; @@ -18,14 +43,13 @@ export const MCP_PAUSED_MARKETPLACE_MARKER = /** * Every marketplace plugin that shipped `.mcp.json` immediately before the - * containment release, except the one allowed local sidecar. + * containment release and is still paused under v2. */ export const MCP_PAUSED_PLUGINS = [ "asana", "clangd-lsp", "context7", "crabcode-example-plugin", - "crabcode-media-ops", "crabwork-bio-research", "crabwork-customer-support", "crabwork-data", diff --git a/tests/crablaw-cn/matter-runtime.test.ts b/tests/crablaw-cn/matter-runtime.test.ts index c7c73b6..ce6fa18 100644 --- a/tests/crablaw-cn/matter-runtime.test.ts +++ b/tests/crablaw-cn/matter-runtime.test.ts @@ -1,333 +1,29 @@ import { describe, expect, test } from "bun:test"; -import { createHash } from "node:crypto"; -import { mkdir, mkdtemp, readFile, stat, writeFile } from "node:fs/promises"; -import os from "node:os"; +import { readFile, stat, writeFile } from "node:fs/promises"; import path from "node:path"; - -const repoRoot = path.resolve("."); -const scriptRoot = path.join(repoRoot, "plugins", "crablaw-cn", "matter-core", "scripts"); - -function runPython(script: string, args: string[]) { - const result = Bun.spawnSync(["python3", path.join(scriptRoot, script), ...args], { - cwd: repoRoot, - stdout: "pipe", - stderr: "pipe", - }); - return { - exitCode: result.exitCode, - stdout: new TextDecoder().decode(result.stdout), - stderr: new TextDecoder().decode(result.stderr), - }; -} - -async function writeJson(file: string, payload: unknown): Promise { - await mkdir(path.dirname(file), { recursive: true }); - await writeFile(file, `${JSON.stringify(payload, null, 2)}\n`); -} - -async function sha256(file: string): Promise { - return createHash("sha256").update(await readFile(file)).digest("hex"); -} - -async function bootstrap(root: string, matterId = "demo-matter", clientId = "demo-client", counterparty = "示例供应商") { - return runPython("bootstrap_matter.py", [ - "--root", root, - "--matter-id", matterId, - "--client-id", clientId, - "--client-name", clientId === "demo-client" ? "示例客户" : "第二客户", - "--title", "合成合同争议", - "--scope", "内部分析合同履行与证据问题", - "--matter-type", "litigation", - "--responsible-lawyer", "张律师", - "--review-owner", "王律师", - "--allowed-user", "test.user", - "--party", `client:${clientId === "demo-client" ? "示例客户" : "第二客户"}`, - "--party", `counterparty:${counterparty}`, - ]); -} - -async function makeValidRun() { - const root = await mkdtemp(path.join(os.tmpdir(), "crablaw-runtime-")); - const created = await bootstrap(root); - expect(created.exitCode).toBe(0); - const matterDir = path.join(root, "matters", "demo-matter"); - const runDir = path.join(matterDir, "runs", "run-001"); - const inputPath = path.join(matterDir, "inputs", "agreement.txt"); - await mkdir(path.dirname(inputPath), { recursive: true }); - await writeFile(inputPath, "用户提供:2026年8月1日双方签署合同,供应商应在8月10日前交付。\n"); - const inputHash = await sha256(inputPath); - - const sources = [ - { - sourceId: "src-document", - matterId: "demo-matter", - sourceType: "user-provided", - title: "合成合同材料", - urlOrRecordId: "inputs/agreement.txt", - retrievedAt: "2026-08-21", - effectiveStatus: "用户提供的合成测试材料", - documentId: "doc-agreement", - contentHash: inputHash, - confidentiality: "standard", - accessScope: "本事项内部", - status: "unreviewed", - }, - { - sourceId: "src-law", - matterId: "demo-matter", - sourceType: "official-law", - title: "合成测试用现行法律记录", - authority: "国家立法机关官方来源(合成记录)", - urlOrRecordId: "official-record:test-only", - retrievedAt: "2026-08-21", - effectiveStatus: "合成测试记录,不承载真实法律结论", - pinpoint: "测试条目", - status: "unreviewed", - }, - { - sourceId: "src-case", - matterId: "demo-matter", - sourceType: "case", - title: "合成类案记录", - authority: "人民法院官方案例来源(合成记录)", - urlOrRecordId: "official-case:test-only", - retrievedAt: "2026-08-21", - effectiveStatus: "合成测试记录,不承载真实裁判信息", - pinpoint: "测试裁判要旨", - status: "unreviewed", - }, - ]; - await writeFile(path.join(matterDir, "sources.jsonl"), `${sources.map((row) => JSON.stringify(row)).join("\n")}\n`); - await mkdir(runDir, { recursive: true }); - - const payloads: Record = { - "analysis-plan.json": { - schemaVersion: 1, - planId: "plan-001", - runId: "run-001", - matterId: "demo-matter", - status: "complete", - createdAt: "2026-08-21T10:00:00Z", - updatedAt: "2026-08-21T10:10:00Z", - documentIds: ["doc-agreement"], - issues: [{ - issueId: "issue-delivery", - title: "是否存在逾期交付风险", - priority: "high", - status: "complete", - documentIds: ["doc-agreement"], - requiredResearch: ["核验适用规范"], - targetDomains: ["contract", "litigation"], - }], - }, - "document-index.json": { - schemaVersion: 1, - runId: "run-001", - matterId: "demo-matter", - documents: [{ - documentId: "doc-agreement", - sourceRecordId: "src-document", - path: "inputs/agreement.txt", - sha256: inputHash, - status: "read-complete", - coverage: { scope: "全文", complete: true, ocrQuality: "not-applicable" }, - issueIds: ["issue-delivery"], - confidentiality: "standard", - }], - }, - "fact-chronology.json": { - schemaVersion: 1, - runId: "run-001", - matterId: "demo-matter", - facts: [{ - factId: "fact-deadline", - statement: "材料记载交付期限为2026年8月10日", - sourceDocumentIds: ["doc-agreement"], - evidenceIds: ["evidence-clause"], - occurredAt: "2026-08-10", - status: "document-stated", - confidenceBasis: "用户提供材料的明确文字", - missing: false, - }], - evidence: [{ - evidenceId: "evidence-clause", - documentId: "doc-agreement", - pinpoint: "第1行", - purpose: "证明材料记载的交付期限", - authenticity: "unreviewed", - legality: "unreviewed", - relevance: "supported", - weight: "medium", - }], - }, - "issue-tree.json": { - schemaVersion: 1, - runId: "run-001", - matterId: "demo-matter", - issues: [{ - issueId: "issue-delivery", - title: "是否存在逾期交付风险", - priority: "high", - status: "resolved-internal", - documentIds: ["doc-agreement"], - factIds: ["fact-deadline"], - evidenceIds: ["evidence-clause"], - requiredResearch: ["核验适用规范"], - targetDomains: ["contract", "litigation"], - specialistTaskIds: [], - }], - }, - "claim-evidence-map.json": { - schemaVersion: 1, - runId: "run-001", - matterId: "demo-matter", - claims: [{ - claimId: "claim-delivery", - issueId: "issue-delivery", - statement: "材料显示需要进一步核验逾期交付责任", - elementIds: ["element-deadline"], - counterarguments: ["尚未提供实际交付日期"], - confidence: "medium", - reviewRequired: true, - }], - elements: [{ - elementId: "element-deadline", - claimId: "claim-delivery", - statement: "合同记载明确交付期限", - factIds: ["fact-deadline"], - evidenceIds: ["evidence-clause"], - sourceRecordIds: ["src-law"], - status: "partially-supported", - missing: false, - }], - }, - "analyzer-findings.json": { - schemaVersion: 1, - matterId: "demo-matter", - runId: "run-001", - findings: [{ - findingId: "finding-delivery", - issueId: "issue-delivery", - category: "legal-conclusion", - statement: "现有材料支持进一步审查是否构成逾期交付,但实际交付日期仍缺失", - citationTag: "[已核验-来源]", - sourceRecordIds: ["src-law"], - factIds: ["fact-deadline"], - evidenceIds: ["evidence-clause"], - severity: "yellow", - confidenceBasis: "规范记录已登记,关键履行事实仍缺失", - reviewRequired: true, - producedBy: "diligence-analyzer", - recommendation: "补充实际交付记录并由律师复核", - caseComparisonRequired: true, - }], - }, - "specialist-findings.json": { - schemaVersion: 1, - matterId: "demo-matter", - runId: "run-001", - tasks: [], - }, - }; - for (const [filename, payload] of Object.entries(payloads)) { - await writeJson(path.join(runDir, filename), payload); - } - const comparisonPath = path.join(runDir, "case-comparison", "issue-delivery.json"); - await writeJson(comparisonPath, { - schemaVersion: 1, - matterId: "demo-matter", - runId: "run-001", - issueId: "issue-delivery", - searchDate: "2026-08-21", - sourcesSearched: ["人民法院官方案例来源(合成测试)"], - cases: [{ - sourceRecordId: "src-case", - caseTitle: "合成类案", - court: "合成法院", - caseDate: "2026-01-01", - factsMatch: "仅用于验证结构", - ruleOrHolding: "不承载真实裁判规则", - difference: "不用于实务依赖", - weight: "weak", - citationTag: "[已核验-来源]", - }], - caseSearchLimitations: "合成测试只有一条案例记录", - conclusion: "仅验证案例比较契约", - }); - - const memoPath = path.join(matterDir, "outputs", "run-001-memo.md"); - await mkdir(path.dirname(memoPath), { recursive: true }); - await writeFile(memoPath, "【AI 辅助草稿,需律师复核】\n\n合成测试备忘录。\n"); - const reviewItem = { - reviewItemId: "review-run-001", - matterId: "demo-matter", - sourcePlugin: "matter-core", - sourceSkill: "matter-deep-analysis", - sourceCapability: "crablaw-cn:matter-deep-analysis", - runId: "run-001", - issueIds: ["issue-delivery"], - outputPath: "outputs/run-001-memo.md", - status: "pending-review", - createdAt: "2026-08-21", - }; - await writeJson(path.join(runDir, "review-queue-item.json"), reviewItem); - - const artifactFiles: Array<[string, string, string]> = [ - ["analysis-plan", "analysis-plan", "analysis-plan.json"], - ["document-index", "document-index", "document-index.json"], - ["fact-chronology", "fact-chronology", "fact-chronology.json"], - ["issue-tree", "issue-tree", "issue-tree.json"], - ["claim-evidence-map", "claim-evidence-map", "claim-evidence-map.json"], - ["analysis-findings", "analysis-findings", "analyzer-findings.json"], - ["specialist-findings", "specialist-findings", "specialist-findings.json"], - ["case-comparison", "case-comparison", path.join("runs", "run-001", "case-comparison", "issue-delivery.json")], - ["memo", "memo", path.relative(matterDir, memoPath)], - ["review-item", "review-item", path.join("runs", "run-001", "review-queue-item.json")], - ]; - const artifacts = []; - for (const [artifactId, type, relative] of artifactFiles) { - const full = relative.startsWith("runs/") || relative.startsWith("outputs/") - ? path.join(matterDir, relative) - : path.join(runDir, relative); - const matterRelative = path.relative(matterDir, full); - artifacts.push({ - artifactId, - type, - path: matterRelative, - sha256: await sha256(full), - status: "validated", - dependsOnDocumentIds: ["doc-agreement"], - dependsOnIssueIds: ["issue-delivery"], - }); - } - await writeJson(path.join(runDir, "run-manifest.json"), { - schemaVersion: 1, - runId: "run-001", - matterId: "demo-matter", - revision: 1, - status: "ready-for-review", - startedAt: "2026-08-21T10:00:00Z", - updatedAt: "2026-08-21T10:20:00Z", - documents: [{ documentId: "doc-agreement", sha256: inputHash }], - artifacts, - staleIssueIds: [], - completedStepIds: ["plan", "read", "research", "analyze", "review"], - reviewState: "pending-lawyer-review", - externalRelease: "prohibited", - }); - - return { root, matterDir, runDir, inputPath }; -} +import { + bootstrap, + makeRoot, + makeValidRun, + repoRoot, + runPython, + writeJson, +} from "./matterFixture.ts"; describe("CrabLaw matter runtime", () => { test("bootstrap creates a private matter and blocks a later local conflict hit", async () => { - const root = await mkdtemp(path.join(os.tmpdir(), "crablaw-bootstrap-")); + const root = await makeRoot("crablaw-bootstrap-"); expect((await bootstrap(root)).exitCode).toBe(0); const matterPath = path.join(root, "matters", "demo-matter", "matter.json"); - expect((await stat(matterPath)).mode & 0o077).toBe(0); + if (process.platform !== "win32") { + // POSIX mode bits only carry meaning where the store enforces them; on + // Windows every file reports 0o666 regardless of what the tool did. + expect((await stat(matterPath)).mode & 0o077).toBe(0); + } const overwrite = await bootstrap(root); - expect(overwrite.exitCode).toBe(2); + expect(overwrite.exitCode).toBe(3); expect(overwrite.stdout).toContain("refusing to overwrite"); + expect(JSON.parse(overwrite.stdout).status).toBe("conflict"); const hit = await bootstrap(root, "second-matter", "second-client", "示例客户"); expect(hit.exitCode).toBe(10); const matter = JSON.parse(await readFile(path.join(root, "matters", "second-matter", "matter.json"), "utf8")); @@ -335,7 +31,7 @@ describe("CrabLaw matter runtime", () => { }); test("an existing store lock blocks a concurrent bootstrap writer", async () => { - const root = await mkdtemp(path.join(os.tmpdir(), "crablaw-lock-")); + const root = await makeRoot("crablaw-lock-"); await writeFile(path.join(root, ".matter-store.lock"), "held by test\n"); const result = await bootstrap(root); expect(result.exitCode).toBe(2); @@ -355,7 +51,7 @@ describe("CrabLaw matter runtime", () => { }); test("the dependency-free schema validator enforces the required client party", async () => { - const root = await mkdtemp(path.join(os.tmpdir(), "crablaw-schema-")); + const root = await makeRoot("crablaw-schema-"); const file = path.join(root, "parties.json"); await writeJson(file, { matterId: "demo-matter", diff --git a/tests/crablaw-cn/matter-store-integrity.test.ts b/tests/crablaw-cn/matter-store-integrity.test.ts new file mode 100644 index 0000000..66d3e46 --- /dev/null +++ b/tests/crablaw-cn/matter-store-integrity.test.ts @@ -0,0 +1,455 @@ +import { describe, expect, test } from "bun:test"; +import { symlinkSync } from "node:fs"; +import { mkdir, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + bootstrap, + bootstrapArgs, + collectPython, + makeRoot, + makeValidRun, + readJson, + readSources, + runPython, + scriptRoot, + spawnPython, + writeJson, + writeSources, + type RunFixture, +} from "./matterFixture.ts"; + +function pythonHostname(): string { + const result = Bun.spawnSync(["python3", "-c", "import socket; print(socket.gethostname())"], { + stdout: "pipe", + stderr: "pipe", + }); + return new TextDecoder().decode(result.stdout).trim(); +} + +function syncRun(fixture: RunFixture, apply = true) { + return runPython("sync_run_manifest.py", [ + "--root", fixture.root, + "--matter-id", "demo-matter", + "--run-id", "run-001", + ...(apply ? ["--apply"] : []), + ]); +} + +function validateRun(fixture: RunFixture, extra: string[] = []) { + return runPython("validate_run.py", [ + "--root", fixture.root, + "--matter-id", "demo-matter", + "--run-id", "run-001", + ...extra, + ]); +} + +async function conflictRecord(root: string, matterId: string) { + return readJson(path.join(root, "matters", matterId, "conflict-check.json")); +} + +describe("conflict screening coverage is reported, never silently skipped", () => { + test("R01: a corrupt client record turns the screen partial instead of passing as no-hit", async () => { + const root = await makeRoot("crablaw-corrupt-"); + expect((await bootstrap(root, "matter-one")).exitCode).toBe(0); + + const brokenPath = path.join(root, "clients", "broken-client", "client.json"); + await mkdir(path.dirname(brokenPath), { recursive: true }); + await writeFile(brokenPath, "{ this is not json"); + + const screened = await bootstrap(root, "matter-two", "second-client", "无关对手方"); + expect(screened.exitCode).toBe(10); + const payload = JSON.parse(screened.stdout); + expect(payload.conflictStatus).toBe("coverage-incomplete"); + expect(payload.substantiveWorkAllowed).toBe(false); + expect(payload.coverage.status).toBe("partial"); + expect(payload.coverage.corrupt.join("\n")).toContain("clients/broken-client/client.json"); + + const record = await conflictRecord(root, "matter-two"); + expect(record.status).toBe("coverage-incomplete"); + expect(record.coverage.corrupt.length).toBe(1); + const matter = await readJson(path.join(root, "matters", "matter-two", "matter.json")); + expect(matter.status).toBe("pending-conflict-review"); + + // Positive control: the very same scan reports complete once the record parses. + await writeJson(brokenPath, { + clientId: "broken-client", + displayName: "完好客户", + status: "active", + confidentiality: "standard", + }); + const repaired = runPython("bootstrap_matter.py", bootstrapArgs(root, { + matterId: "matter-three", + clientId: "third-client", + clientName: "第三客户", + counterparty: "另一无关对手方", + })); + expect(repaired.exitCode, repaired.stdout).toBe(0); + const repairedPayload = JSON.parse(repaired.stdout); + expect(repairedPayload.conflictStatus).toBe("no-hit"); + expect(repairedPayload.coverage.status).toBe("complete"); + expect(repairedPayload.coverage.corrupt).toEqual([]); + expect(repairedPayload.coverage.scanned).toBeGreaterThan(0); + }); + + test("X4: a client record that is valid JSON but not an object is a typed coverage gap, not a crash", async () => { + const root = await makeRoot("crablaw-typeerror-"); + expect((await bootstrap(root, "matter-one")).exitCode).toBe(0); + const arrayPath = path.join(root, "clients", "array-client", "client.json"); + await mkdir(path.dirname(arrayPath), { recursive: true }); + await writeFile(arrayPath, "[]\n"); + + const screened = await bootstrap(root, "matter-two", "second-client", "无关对手方"); + expect(screened.stderr).toBe(""); + expect(screened.exitCode).toBe(10); + const payload = JSON.parse(screened.stdout); + expect(payload.conflictStatus).toBe("coverage-incomplete"); + expect(payload.coverage.status).toBe("partial"); + expect(payload.coverage.typeErrors.join("\n")).toContain("clients/array-client/client.json"); + expect(payload.coverage.typeErrors.join("\n")).toContain("expected a JSON object, got list"); + expect(payload.coverage.corrupt).toEqual([]); + }); + + test("X1: archived matters are inside the screening scope and can produce a hit", async () => { + const root = await makeRoot("crablaw-archived-"); + expect((await bootstrap(root, "matter-one", "demo-client", "归档对手方")).exitCode).toBe(0); + + await mkdir(path.join(root, "matters", "_archived"), { recursive: true }); + await rename(path.join(root, "matters", "matter-one"), path.join(root, "matters", "_archived", "matter-one")); + + const screened = await bootstrap(root, "matter-two", "second-client", "归档对手方"); + expect(screened.exitCode).toBe(10); + const payload = JSON.parse(screened.stdout); + expect(payload.coverage.status).toBe("complete"); + expect(payload.coverage.scopes).toContain("matters/_archived"); + expect(payload.conflictStatus).toBe("hit-review-required"); + + const record = await conflictRecord(root, "matter-two"); + const archivedHits = record.hits.filter((hit: any) => + hit.source === "matters/_archived/matter-one/parties.json"); + expect(archivedHits.length).toBeGreaterThan(0); + expect(archivedHits[0].matchedValue).toBe("归档对手方"); + + // Positive control: an unrelated name is still a clean no-hit after archiving. + const clean = runPython("bootstrap_matter.py", bootstrapArgs(root, { + matterId: "matter-three", + clientId: "third-client", + clientName: "第三客户", + counterparty: "完全不相关的对手方", + })); + expect(clean.exitCode, clean.stdout).toBe(0); + expect(JSON.parse(clean.stdout).conflictStatus).toBe("no-hit"); + }); + + test("X2: a directory junction inside the store is refused and reported, not skipped", async () => { + const root = await makeRoot("crablaw-junction-"); + expect((await bootstrap(root, "matter-one")).exitCode).toBe(0); + + const outside = await makeRoot("crablaw-outside-"); + await writeJson(path.join(outside, "client.json"), { + clientId: "outside-client", + displayName: "根外客户", + status: "active", + confidentiality: "standard", + }); + // The leaf file is a real file; only the directory above it redirects. + symlinkSync(outside, path.join(root, "clients", "linked"), "junction"); + expect((await stat(path.join(root, "clients", "linked", "client.json"))).isFile()).toBe(true); + + const screened = await bootstrap(root, "matter-two", "second-client", "无关对手方"); + expect(screened.exitCode).toBe(10); + const payload = JSON.parse(screened.stdout); + expect(payload.conflictStatus).toBe("coverage-incomplete"); + expect(payload.coverage.status).toBe("partial"); + const refused = payload.coverage.refused.join("\n"); + expect(refused).toContain("clients/linked/client.json"); + expect(refused).toMatch(/symbolic link|escapes the matter-store root/); + expect(payload.coverage.corrupt).toEqual([]); + + // A junction whose target stays inside the root passes the containment test, + // so only the per-level link check can catch it. + await rm(path.join(root, "clients", "linked"), { recursive: true, force: true }); + const realClient = path.join(root, "clients", "real-client"); + await writeJson(path.join(realClient, "client.json"), { + clientId: "real-client", + displayName: "真实客户", + status: "active", + confidentiality: "standard", + }); + symlinkSync(realClient, path.join(root, "clients", "aliased"), "junction"); + const insideRoot = runPython("bootstrap_matter.py", bootstrapArgs(root, { + matterId: "matter-inside", + clientId: "inside-client", + clientName: "内部客户", + counterparty: "无关对手方二号", + })); + expect(insideRoot.exitCode).toBe(10); + const insidePayload = JSON.parse(insideRoot.stdout); + expect(insidePayload.conflictStatus).toBe("coverage-incomplete"); + expect(insidePayload.coverage.refused.join("\n")).toContain("clients/aliased/client.json"); + expect(insidePayload.coverage.refused.join("\n")).toContain("crosses a symbolic link"); + await rm(path.join(root, "clients", "aliased"), { recursive: true, force: true }); + await rm(realClient, { recursive: true, force: true }); + + // Positive control: without the redirection the same store scans completely. + const clean = runPython("bootstrap_matter.py", bootstrapArgs(root, { + matterId: "matter-three", + clientId: "third-client", + clientName: "第三客户", + counterparty: "另一无关对手方", + })); + expect(clean.exitCode, clean.stdout).toBe(0); + expect(JSON.parse(clean.stdout).coverage.status).toBe("complete"); + expect(JSON.parse(clean.stdout).coverage.refused).toEqual([]); + }); + + test("R02: a repeat client with a new counterparty carries roles, source and relation", async () => { + const root = await makeRoot("crablaw-relation-"); + expect((await bootstrap(root, "matter-one", "demo-client", "示例供应商")).exitCode).toBe(0); + + const second = runPython("bootstrap_matter.py", bootstrapArgs(root, { + matterId: "matter-two", + clientId: "demo-client", + clientName: "示例客户", + counterparty: "另一供应商", + })); + expect(second.exitCode).toBe(10); + expect(JSON.parse(second.stdout).conflictStatus).toBe("hit-review-required"); + + const record = await conflictRecord(root, "matter-two"); + expect(record.status).toBe("hit-review-required"); + // Not a final decision and not auto-cleared. + expect(record.lawyerConfirmation.status).toBe("not-reviewed"); + const sameSide = record.hits.filter((hit: any) => hit.relation === "same-side-existing-client"); + expect(sameSide.length).toBeGreaterThan(0); + for (const hit of record.hits) { + expect(typeof hit.matchedValue).toBe("string"); + expect(typeof hit.existingRole).toBe("string"); + expect(typeof hit.newRole).toBe("string"); + expect(["same-side-existing-client", "potential-adverse", "name-match-unclassified"]) + .toContain(hit.relation); + expect(hit.risk).toBe("unknown"); + } + expect(sameSide.some((hit: any) => hit.matchedValue === "示例客户" && hit.newRole === "client")).toBe(true); + expect(record.hits.some((hit: any) => hit.source === "clients/demo-client/client.json")).toBe(true); + expect(record.hits.some((hit: any) => hit.source === "matters/matter-one/parties.json")).toBe(true); + + // Positive control: the existing client showing up as the new counterparty is adverse. + const adverse = runPython("bootstrap_matter.py", bootstrapArgs(root, { + matterId: "matter-three", + clientId: "third-client", + clientName: "第三客户", + counterparty: "示例客户", + })); + expect(adverse.exitCode).toBe(10); + const adverseRecord = await conflictRecord(root, "matter-three"); + const adverseHits = adverseRecord.hits.filter((hit: any) => hit.relation === "potential-adverse"); + expect(adverseHits.length).toBeGreaterThan(0); + expect(adverseHits.every((hit: any) => hit.newRole === "counterparty")).toBe(true); + }); +}); + +describe("matter creation is exclusive and crash-visible", () => { + test("R03: two simultaneous bootstraps of one matter id create it exactly once", async () => { + const root = await makeRoot("crablaw-race-"); + const args = bootstrapArgs(root, { matterId: "raced-matter", title: "第一个写入者" }); + const [first, second] = await Promise.all([ + collectPython(spawnPython("bootstrap_matter.py", args)), + collectPython(spawnPython("bootstrap_matter.py", args)), + ]); + + const outcomes = [first, second].map((result) => ({ + code: result.exitCode, + status: JSON.parse(result.stdout).status, + raw: result.stdout, + })); + const created = outcomes.filter((item) => item.status === "created"); + const conflicted = outcomes.filter((item) => item.status === "conflict"); + expect(created.length, JSON.stringify(outcomes)).toBe(1); + expect(conflicted.length, JSON.stringify(outcomes)).toBe(1); + const winner = created[0]!; + const loser = conflicted[0]!; + expect(loser.code).toBe(3); + expect([0, 10]).toContain(winner.code); + expect(loser.raw).toContain("refusing to overwrite"); + + const matterPath = path.join(root, "matters", "raced-matter", "matter.json"); + const winnerBytes = await readFile(matterPath); + const matter = JSON.parse(winnerBytes.toString("utf8")); + expect(matter.matterId).toBe("raced-matter"); + expect(matter.title).toBe("第一个写入者"); + + // A later writer with different content still cannot touch the winner's bytes. + const late = runPython("bootstrap_matter.py", bootstrapArgs(root, { + matterId: "raced-matter", + title: "第二个写入者", + })); + expect(late.exitCode).toBe(3); + expect(Buffer.compare(await readFile(matterPath), winnerBytes)).toBe(0); + }); + + test("X3: a lock left behind by a killed process is reclaimed, and a live lock never is", async () => { + const root = await makeRoot("crablaw-stalelock-"); + const lockPath = path.join(root, ".matter-store.lock"); + const holder = Bun.spawnSync([ + "python3", + "-c", + [ + "import os, sys", + "from pathlib import Path", + "from _matter_common import file_lock", + "cm = file_lock(Path(sys.argv[1]))", + "cm.__enter__()", + "os._exit(19)", + ].join("\n"), + lockPath, + ], { cwd: scriptRoot, stdout: "pipe", stderr: "pipe" }); + expect(holder.exitCode, new TextDecoder().decode(holder.stderr)).toBe(19); + const leftover = await readFile(lockPath, "utf8"); + expect(leftover).toContain("pid="); + expect(leftover).toContain("host="); + + const recovered = await bootstrap(root, "after-crash"); + expect(recovered.exitCode, recovered.stdout).toBe(0); + expect(await Bun.file(lockPath).exists()).toBe(false); + + // Negative control 1: an old lock owned by a living process is not reclaimed, + // which is what separates "owner is gone" from "the file looks old". + const liveRoot = await makeRoot("crablaw-livelock-"); + const livePath = path.join(liveRoot, ".matter-store.lock"); + await writeFile(livePath, `pid=${process.pid} host=${pythonHostname()} created=2020-01-01T00:00:00Z\n`); + const anHourAgo = new Date(Date.now() - 3_600_000); + await utimes(livePath, anHourAgo, anHourAgo); + const blocked = await bootstrap(liveRoot, "blocked-matter"); + expect(blocked.exitCode).toBe(2); + expect(blocked.stdout).toContain("locked"); + expect(await Bun.file(livePath).exists()).toBe(true); + + // Negative control 2: a dead pid recorded on another host is not ours to judge. + const foreignRoot = await makeRoot("crablaw-foreignlock-"); + const foreignPath = path.join(foreignRoot, ".matter-store.lock"); + await writeFile(foreignPath, "pid=999999 host=some-other-host created=2020-01-01T00:00:00Z\n"); + const foreign = await bootstrap(foreignRoot, "foreign-matter"); + expect(foreign.exitCode).toBe(2); + expect(foreign.stdout).toContain("locked"); + expect(await Bun.file(foreignPath).exists()).toBe(true); + }); + + test("an interrupted bootstrap stays pending and blocks both reuse and validation", async () => { + const fixture = await makeValidRun(); + const pendingMarker = path.join(fixture.matterDir, ".pending"); + + const before = validateRun(fixture, ["--strict", "--require-verified-source"]); + expect(before.exitCode, before.stderr).toBe(0); + + await writeFile(pendingMarker, ""); + const blocked = validateRun(fixture, ["--strict", "--require-verified-source"]); + expect(blocked.exitCode).toBe(1); + expect(blocked.stderr).toContain("matter is pending (incomplete bootstrap)"); + + const rebootstrap = await bootstrap(fixture.root, "demo-matter"); + expect(rebootstrap.exitCode).toBe(3); + expect(rebootstrap.stdout).toContain("matter is pending (incomplete bootstrap)"); + + await rm(pendingMarker); + const after = validateRun(fixture, ["--strict", "--require-verified-source"]); + expect(after.exitCode, after.stderr).toBe(0); + }); +}); + +describe("staleness survives a second sync and follows source records", () => { + test("X5: a second apply with no new change keeps the stale ledger", async () => { + const fixture = await makeValidRun(); + await writeFile(fixture.inputPath, "changed bytes\n"); + + const first = syncRun(fixture); + expect(first.exitCode, first.stdout).toBe(0); + const firstResult = JSON.parse(first.stdout); + expect(firstResult.status).toBe("apply-ready"); + expect(firstResult.staleIssueIds).toContain("issue-delivery"); + + const second = syncRun(fixture); + expect(second.exitCode, second.stdout).toBe(0); + const secondResult = JSON.parse(second.stdout); + expect(secondResult.status).toBe("unchanged"); + expect(secondResult.changedDocumentIds).toEqual([]); + expect(secondResult.staleIssueIds).toContain("issue-delivery"); + const manifest = await readJson(path.join(fixture.runDir, "run-manifest.json")); + expect(manifest.staleIssueIds).toContain("issue-delivery"); + + // Positive control: once the issue tree records the rerun, the mark clears. + const issueTree = await readJson(path.join(fixture.runDir, "issue-tree.json")); + issueTree.issues[0].status = "resolved-internal"; + await writeJson(path.join(fixture.runDir, "issue-tree.json"), issueTree); + const third = syncRun(fixture); + expect(third.exitCode, third.stdout).toBe(0); + expect(JSON.parse(third.stdout).staleIssueIds).toEqual([]); + }); + + test("X7: editing only sources.jsonl makes the issues that rely on it stale", async () => { + const fixture = await makeValidRun(); + + // Control: the primed baseline reports nothing changed. + const baseline = syncRun(fixture); + expect(baseline.exitCode, baseline.stdout).toBe(0); + const baselineResult = JSON.parse(baseline.stdout); + expect(baselineResult.status).toBe("unchanged"); + expect(baselineResult.changedSourceIds).toEqual([]); + expect(baselineResult.staleIssueIds).toEqual([]); + + const rows = await readSources(fixture); + const law = rows.find((row) => row.sourceId === "src-law"); + expect(law).toBeDefined(); + law!.effectiveStatus = "合成测试记录已被后续修订取代"; + await writeSources(fixture, rows); + + const synced = syncRun(fixture); + expect(synced.exitCode, synced.stdout).toBe(0); + const result = JSON.parse(synced.stdout); + expect(result.status).toBe("apply-ready"); + expect(result.changedSourceIds).toEqual(["src-law"]); + expect(result.changedDocumentIds).toEqual([]); + expect(result.staleIssueIds).toContain("issue-delivery"); + + const manifest = await readJson(path.join(fixture.runDir, "run-manifest.json")); + expect(manifest.status).toBe("stale"); + expect(manifest.staleIssueIds).toContain("issue-delivery"); + const blocked = validateRun(fixture, ["--strict"]); + expect(blocked.exitCode).toBe(1); + expect(blocked.stderr).toContain("strict validation blocks stale"); + }); +}); + +describe("[已核验-来源] requires an actually verified source", () => { + async function withLawStatus(fixture: RunFixture, patch: Record) { + const rows = await readSources(fixture); + const law = rows.find((row) => row.sourceId === "src-law")!; + Object.assign(law, patch); + await writeSources(fixture, rows); + } + + for (const status of ["unreviewed", "unknown", "superseded"]) { + test(`P-L2-a: status ${status} does not satisfy the verified-source tag`, async () => { + const fixture = await makeValidRun(); + await withLawStatus(fixture, { status }); + const result = validateRun(fixture, ["--strict", "--require-verified-source"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("no verified official/case source"); + }); + } + + test("P-L2-a: a lawyer-reviewed official source still satisfies the tag", async () => { + const fixture = await makeValidRun(); + await withLawStatus(fixture, { status: "lawyer-reviewed", reviewer: "王律师" }); + const result = validateRun(fixture, ["--strict", "--require-verified-source"]); + expect(result.exitCode, result.stderr).toBe(0); + }); + + test("P-L2-a: source-needs-check still fails the tag", async () => { + const fixture = await makeValidRun(); + await withLawStatus(fixture, { status: "source-needs-check" }); + const result = validateRun(fixture, ["--strict", "--require-verified-source"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("no verified official/case source"); + }); +}); diff --git a/tests/crablaw-cn/matterFixture.ts b/tests/crablaw-cn/matterFixture.ts new file mode 100644 index 0000000..a893780 --- /dev/null +++ b/tests/crablaw-cn/matterFixture.ts @@ -0,0 +1,409 @@ +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +export const repoRoot = path.resolve("."); +export const scriptRoot = path.join(repoRoot, "plugins", "crablaw-cn", "matter-core", "scripts"); + +export interface PythonResult { + exitCode: number; + stdout: string; + stderr: string; +} + +export function runPython(script: string, args: string[]): PythonResult { + const result = Bun.spawnSync(["python3", path.join(scriptRoot, script), ...args], { + cwd: repoRoot, + stdout: "pipe", + stderr: "pipe", + }); + return { + exitCode: result.exitCode, + stdout: new TextDecoder().decode(result.stdout), + stderr: new TextDecoder().decode(result.stderr), + }; +} + +/** Start a script without waiting, so two writers can genuinely race. */ +export function spawnPython(script: string, args: string[]) { + return Bun.spawn(["python3", path.join(scriptRoot, script), ...args], { + cwd: repoRoot, + stdout: "pipe", + stderr: "pipe", + }); +} + +export async function collectPython(child: ReturnType): Promise { + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + return { exitCode, stdout, stderr }; +} + +export async function writeJson(file: string, payload: unknown): Promise { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, `${JSON.stringify(payload, null, 2)}\n`); +} + +export async function readJson(file: string): Promise { + return JSON.parse(await readFile(file, "utf8")) as T; +} + +export async function sha256(file: string): Promise { + return createHash("sha256").update(await readFile(file)).digest("hex"); +} + +export async function makeRoot(prefix: string): Promise { + return mkdtemp(path.join(os.tmpdir(), prefix)); +} + +export interface BootstrapOptions { + matterId?: string; + clientId?: string; + clientName?: string; + counterparty?: string; + title?: string; +} + +export function bootstrapArgs(root: string, options: BootstrapOptions = {}): string[] { + const clientId = options.clientId ?? "demo-client"; + const clientName = options.clientName ?? (clientId === "demo-client" ? "示例客户" : "第二客户"); + return [ + "--root", root, + "--matter-id", options.matterId ?? "demo-matter", + "--client-id", clientId, + "--client-name", clientName, + "--title", options.title ?? "合成合同争议", + "--scope", "内部分析合同履行与证据问题", + "--matter-type", "litigation", + "--responsible-lawyer", "张律师", + "--review-owner", "王律师", + "--allowed-user", "test.user", + "--party", `client:${clientName}`, + "--party", `counterparty:${options.counterparty ?? "示例供应商"}`, + ]; +} + +export async function bootstrap( + root: string, + matterId = "demo-matter", + clientId = "demo-client", + counterparty = "示例供应商", +): Promise { + return runPython("bootstrap_matter.py", bootstrapArgs(root, { matterId, clientId, counterparty })); +} + +export interface RunFixture { + root: string; + matterDir: string; + runDir: string; + inputPath: string; + sourcesPath: string; +} + +export async function makeValidRun(): Promise { + const root = await makeRoot("crablaw-runtime-"); + const created = await bootstrap(root); + if (created.exitCode !== 0) { + throw new Error(`fixture bootstrap failed (${created.exitCode}): ${created.stdout}${created.stderr}`); + } + const matterDir = path.join(root, "matters", "demo-matter"); + const runDir = path.join(matterDir, "runs", "run-001"); + const inputPath = path.join(matterDir, "inputs", "agreement.txt"); + await mkdir(path.dirname(inputPath), { recursive: true }); + await writeFile(inputPath, "用户提供:2026年8月1日双方签署合同,供应商应在8月10日前交付。\n"); + const inputHash = await sha256(inputPath); + + const sources = [ + { + sourceId: "src-document", + matterId: "demo-matter", + sourceType: "user-provided", + title: "合成合同材料", + urlOrRecordId: "inputs/agreement.txt", + retrievedAt: "2026-08-21", + effectiveStatus: "用户提供的合成测试材料", + documentId: "doc-agreement", + contentHash: inputHash, + confidentiality: "standard", + accessScope: "本事项内部", + status: "unreviewed", + }, + { + sourceId: "src-law", + matterId: "demo-matter", + sourceType: "official-law", + title: "合成测试用现行法律记录", + authority: "国家立法机关官方来源(合成记录)", + urlOrRecordId: "official-record:test-only", + retrievedAt: "2026-08-21", + effectiveStatus: "合成测试记录,不承载真实法律结论", + pinpoint: "测试条目", + status: "verified", + }, + { + sourceId: "src-case", + matterId: "demo-matter", + sourceType: "case", + title: "合成类案记录", + authority: "人民法院官方案例来源(合成记录)", + urlOrRecordId: "official-case:test-only", + retrievedAt: "2026-08-21", + effectiveStatus: "合成测试记录,不承载真实裁判信息", + pinpoint: "测试裁判要旨", + status: "verified", + }, + ]; + const sourcesPath = path.join(matterDir, "sources.jsonl"); + await writeFile(sourcesPath, `${sources.map((row) => JSON.stringify(row)).join("\n")}\n`); + await mkdir(runDir, { recursive: true }); + + const issueTree = { + schemaVersion: 1, + runId: "run-001", + matterId: "demo-matter", + issues: [{ + issueId: "issue-delivery", + title: "是否存在逾期交付风险", + priority: "high", + status: "resolved-internal", + documentIds: ["doc-agreement"], + factIds: ["fact-deadline"], + evidenceIds: ["evidence-clause"], + requiredResearch: ["核验适用规范"], + targetDomains: ["contract", "litigation"], + specialistTaskIds: [], + }], + }; + + const payloads: Record = { + "analysis-plan.json": { + schemaVersion: 1, + planId: "plan-001", + runId: "run-001", + matterId: "demo-matter", + status: "complete", + createdAt: "2026-08-21T10:00:00Z", + updatedAt: "2026-08-21T10:10:00Z", + documentIds: ["doc-agreement"], + issues: [{ + issueId: "issue-delivery", + title: "是否存在逾期交付风险", + priority: "high", + status: "complete", + documentIds: ["doc-agreement"], + requiredResearch: ["核验适用规范"], + targetDomains: ["contract", "litigation"], + }], + }, + "document-index.json": { + schemaVersion: 1, + runId: "run-001", + matterId: "demo-matter", + documents: [{ + documentId: "doc-agreement", + sourceRecordId: "src-document", + path: "inputs/agreement.txt", + sha256: inputHash, + status: "read-complete", + coverage: { scope: "全文", complete: true, ocrQuality: "not-applicable" }, + issueIds: ["issue-delivery"], + confidentiality: "standard", + }], + }, + "fact-chronology.json": { + schemaVersion: 1, + runId: "run-001", + matterId: "demo-matter", + facts: [{ + factId: "fact-deadline", + statement: "材料记载交付期限为2026年8月10日", + sourceDocumentIds: ["doc-agreement"], + evidenceIds: ["evidence-clause"], + occurredAt: "2026-08-10", + status: "document-stated", + confidenceBasis: "用户提供材料的明确文字", + missing: false, + }], + evidence: [{ + evidenceId: "evidence-clause", + documentId: "doc-agreement", + pinpoint: "第1行", + purpose: "证明材料记载的交付期限", + authenticity: "unreviewed", + legality: "unreviewed", + relevance: "supported", + weight: "medium", + }], + }, + "issue-tree.json": issueTree, + "claim-evidence-map.json": { + schemaVersion: 1, + runId: "run-001", + matterId: "demo-matter", + claims: [{ + claimId: "claim-delivery", + issueId: "issue-delivery", + statement: "材料显示需要进一步核验逾期交付责任", + elementIds: ["element-deadline"], + counterarguments: ["尚未提供实际交付日期"], + confidence: "medium", + reviewRequired: true, + }], + elements: [{ + elementId: "element-deadline", + claimId: "claim-delivery", + statement: "合同记载明确交付期限", + factIds: ["fact-deadline"], + evidenceIds: ["evidence-clause"], + sourceRecordIds: ["src-law"], + status: "partially-supported", + missing: false, + }], + }, + "analyzer-findings.json": { + schemaVersion: 1, + matterId: "demo-matter", + runId: "run-001", + findings: [{ + findingId: "finding-delivery", + issueId: "issue-delivery", + category: "legal-conclusion", + statement: "现有材料支持进一步审查是否构成逾期交付,但实际交付日期仍缺失", + citationTag: "[已核验-来源]", + sourceRecordIds: ["src-law"], + factIds: ["fact-deadline"], + evidenceIds: ["evidence-clause"], + severity: "yellow", + confidenceBasis: "规范记录已登记,关键履行事实仍缺失", + reviewRequired: true, + producedBy: "diligence-analyzer", + recommendation: "补充实际交付记录并由律师复核", + caseComparisonRequired: true, + }], + }, + "specialist-findings.json": { + schemaVersion: 1, + matterId: "demo-matter", + runId: "run-001", + tasks: [], + }, + }; + for (const [filename, payload] of Object.entries(payloads)) { + await writeJson(path.join(runDir, filename), payload); + } + const comparisonPath = path.join(runDir, "case-comparison", "issue-delivery.json"); + await writeJson(comparisonPath, { + schemaVersion: 1, + matterId: "demo-matter", + runId: "run-001", + issueId: "issue-delivery", + searchDate: "2026-08-21", + sourcesSearched: ["人民法院官方案例来源(合成测试)"], + cases: [{ + sourceRecordId: "src-case", + caseTitle: "合成类案", + court: "合成法院", + caseDate: "2026-01-01", + factsMatch: "仅用于验证结构", + ruleOrHolding: "不承载真实裁判规则", + difference: "不用于实务依赖", + weight: "weak", + citationTag: "[已核验-来源]", + }], + caseSearchLimitations: "合成测试只有一条案例记录", + conclusion: "仅验证案例比较契约", + }); + + const memoPath = path.join(matterDir, "outputs", "run-001-memo.md"); + await mkdir(path.dirname(memoPath), { recursive: true }); + await writeFile(memoPath, "【AI 辅助草稿,需律师复核】\n\n合成测试备忘录。\n"); + const reviewItem = { + reviewItemId: "review-run-001", + matterId: "demo-matter", + sourcePlugin: "matter-core", + sourceSkill: "matter-deep-analysis", + sourceCapability: "crablaw-cn:matter-deep-analysis", + runId: "run-001", + issueIds: ["issue-delivery"], + outputPath: "outputs/run-001-memo.md", + status: "pending-review", + createdAt: "2026-08-21", + }; + await writeJson(path.join(runDir, "review-queue-item.json"), reviewItem); + + // Establish the document/source baseline with the real sync tool rather than + // re-deriving Python's record digest in TypeScript, then restore the clean + // run state the fixture is supposed to represent. + const primed = runPython("sync_run_manifest.py", [ + "--root", root, + "--matter-id", "demo-matter", + "--run-id", "run-001", + "--apply", + ]); + if (primed.exitCode !== 0) { + throw new Error(`fixture source baseline failed: ${primed.stdout}${primed.stderr}`); + } + const primedManifest = await readJson(path.join(runDir, "run-manifest.json")); + await writeJson(path.join(runDir, "issue-tree.json"), issueTree); + + const artifactFiles: Array<[string, string, string]> = [ + ["analysis-plan", "analysis-plan", "analysis-plan.json"], + ["document-index", "document-index", "document-index.json"], + ["fact-chronology", "fact-chronology", "fact-chronology.json"], + ["issue-tree", "issue-tree", "issue-tree.json"], + ["claim-evidence-map", "claim-evidence-map", "claim-evidence-map.json"], + ["analysis-findings", "analysis-findings", "analyzer-findings.json"], + ["specialist-findings", "specialist-findings", "specialist-findings.json"], + ["case-comparison", "case-comparison", path.join("runs", "run-001", "case-comparison", "issue-delivery.json")], + ["memo", "memo", path.relative(matterDir, memoPath)], + ["review-item", "review-item", path.join("runs", "run-001", "review-queue-item.json")], + ]; + const artifacts = []; + for (const [artifactId, type, relative] of artifactFiles) { + const head = relative.split(path.sep)[0]; + const full = head === "runs" || head === "outputs" + ? path.join(matterDir, relative) + : path.join(runDir, relative); + const matterRelative = path.relative(matterDir, full); + artifacts.push({ + artifactId, + type, + path: matterRelative, + sha256: await sha256(full), + status: "validated", + dependsOnDocumentIds: ["doc-agreement"], + dependsOnIssueIds: ["issue-delivery"], + }); + } + await writeJson(path.join(runDir, "run-manifest.json"), { + schemaVersion: 1, + runId: "run-001", + matterId: "demo-matter", + revision: 1, + status: "ready-for-review", + startedAt: "2026-08-21T10:00:00Z", + updatedAt: "2026-08-21T10:20:00Z", + documents: [{ documentId: "doc-agreement", sha256: inputHash }], + sources: primedManifest.sources, + artifacts, + staleIssueIds: [], + completedStepIds: ["plan", "read", "research", "analyze", "review"], + reviewState: "pending-lawyer-review", + externalRelease: "prohibited", + }); + + return { root, matterDir, runDir, inputPath, sourcesPath }; +} + +export async function readSources(fixture: RunFixture): Promise[]> { + const raw = await readFile(fixture.sourcesPath, "utf8"); + return raw.split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line)); +} + +export async function writeSources(fixture: RunFixture, rows: Record[]): Promise { + await writeFile(fixture.sourcesPath, `${rows.map((row) => JSON.stringify(row)).join("\n")}\n`); +} diff --git a/tests/validators/mcp-contract.test.ts b/tests/validators/mcp-contract.test.ts index 860ee50..fca8da7 100644 --- a/tests/validators/mcp-contract.test.ts +++ b/tests/validators/mcp-contract.test.ts @@ -46,6 +46,81 @@ describe("mcp contract validator", () => { expect(await validateMcpContract(root)).toEqual([]); }); + test("accepts the media-ops sidecar with host-injected user_config principals", async () => { + const root = await makeTempRoot(); + await writeMarketplace(root, [{ name: "crabcode-media-ops", version: "0.4.4" }]); + await writePlugin(root, "crabcode-media-ops", { + ".crabcode-plugin/plugin.json": { + name: "crabcode-media-ops", + version: "0.4.4", + requiredMcpServers: ["mediaops"], + userConfig: { + principal_id: { type: "string", title: "id", required: true }, + principal_name: { type: "string", title: "name", required: true }, + }, + }, + "package.json": { name: "crabcode-media-ops-mcp", version: "0.4.4", scripts: { start: "bun --no-env-file dist/server.js" } }, + ".mcp.json": { + mcpServers: { + mediaops: { + command: "bun", + args: ["--no-env-file", "${CRABCODE_PLUGIN_ROOT}/dist/server.js"], + env: { + MEDIAOPS_IDENTITY_MODE: "local-editorial", + MEDIAOPS_TRUSTED_PRINCIPAL_ID: "${user_config.principal_id}", + MEDIAOPS_TRUSTED_PRINCIPAL_NAME: "${user_config.principal_name}", + }, + }, + }, + }, + "dist/server.js": "// bundled", + }); + expect(await validateMcpContract(root)).toEqual([]); + }); + + test("still rejects .mcp.json from a plugin outside the allow table", async () => { + const root = await makeTempRoot(); + await writePlugin(root, "crabwork-data", { + ".crabcode-plugin/plugin.json": { name: "crabwork-data", version: "0.1.1", requiredMcpServers: ["crabwork-data"] }, + ".mcp.json": { mcpServers: { "crabwork-data": { command: "bun", args: ["${CRABCODE_PLUGIN_ROOT}/dist/server.js"] } } }, + "dist/server.js": "// bundled", + }); + const messages = errorsOf(await validateMcpContract(root)).map((issue) => issue.message).join("\n"); + expect(messages).toContain("permits .mcp.json only"); + expect(messages).toContain("requiredMcpServers is reserved"); + }); + + // The host throws when a ${user_config.X} value is missing and never writes the + // declared default, so referencing an optional field turns a normal install + // into a server that cannot start. + test("rejects a user_config reference that is undeclared or merely optional", async () => { + const root = await makeTempRoot(); + await writePlugin(root, "crabcode-media-ops", { + ".crabcode-plugin/plugin.json": { + name: "crabcode-media-ops", + version: "0.4.4", + requiredMcpServers: ["mediaops"], + userConfig: { principal_name: { type: "string", default: "editor" } }, + }, + ".mcp.json": { + mcpServers: { + mediaops: { + command: "bun", + args: ["${CRABCODE_PLUGIN_ROOT}/dist/server.js"], + env: { + MEDIAOPS_TRUSTED_PRINCIPAL_ID: "${user_config.principal_id}", + MEDIAOPS_TRUSTED_PRINCIPAL_NAME: "${user_config.principal_name}", + }, + }, + }, + }, + "dist/server.js": "// bundled", + }); + const messages = errorsOf(await validateMcpContract(root)).map((issue) => issue.message).join("\n"); + expect(messages).toContain("${user_config.principal_id} but plugin.json userConfig.principal_id is not declared with required: true"); + expect(messages).toContain("${user_config.principal_name} but plugin.json userConfig.principal_name is not declared with required: true"); + }); + test("rejects required names without a server, installers, floating versions and missing artifacts", async () => { const root = await makeTempRoot(); await writeMarketplace(root, [{ name: "beta", version: "2.0.0" }]); diff --git a/tests/validators/mcp-safe-baseline.test.ts b/tests/validators/mcp-safe-baseline.test.ts index 83aad8f..cf0c7b1 100644 --- a/tests/validators/mcp-safe-baseline.test.ts +++ b/tests/validators/mcp-safe-baseline.test.ts @@ -3,7 +3,9 @@ import { createHash } from "node:crypto"; import { existsSync, readFileSync, readdirSync } from "node:fs"; import path from "node:path"; import { + MCP_ALLOWED_LOCAL_SERVERS, MCP_ALLOWED_PLUGIN, + MCP_ALLOWED_PLUGIN_SET, MCP_ALLOWED_SERVER, MCP_PAUSED_MARKETPLACE_MARKER, MCP_PAUSED_PLUGINS, @@ -22,44 +24,81 @@ function nextPatch(version: string): string { return `${match[1]}.${match[2]}.${Number(match[3]) + 1}`; } -describe("MCP emergency safe baseline", () => { - test("publishes exactly one bundled local server and no remote executable", () => { - const mcpFiles = readdirSync(path.join(root, "plugins"), { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => `plugins/${entry.name}/.mcp.json`) +function pluginDirectories(): string[] { + return readdirSync(path.join(root, "plugins"), { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name); +} + +type RestoredEntry = { + pluginId: string; + serverName: string; + transport: string; + configPath: string; + configSha256: string; + previousVersion: string; + restoredVersion: string; + identityInjection: string; +}; + +const allowedPlugins = [...MCP_ALLOWED_LOCAL_SERVERS.keys()].sort(); +const restore = json("docs/audit/evidence/2026-09-12-mcp-restore/restore-inventory.json") as { + baselineId: string; + decision: string; + restored: RestoredEntry[]; + stillPaused: string[]; +}; + +describe("MCP first-party local baseline", () => { + test("publishes exactly the allowed bundled local servers and no remote executable", () => { + const mcpFiles = pluginDirectories() + .map((name) => `plugins/${name}/.mcp.json`) .filter((relative) => existsSync(path.join(root, relative))) .sort(); - expect(mcpFiles).toEqual([`plugins/${MCP_ALLOWED_PLUGIN}/.mcp.json`]); - const config = json(mcpFiles[0]!); - expect(Object.keys(config.mcpServers ?? config)).toEqual([MCP_ALLOWED_SERVER]); - const server = (config.mcpServers ?? config)[MCP_ALLOWED_SERVER]; - expect(server.type ?? "stdio").toBe("stdio"); - expect(server.url).toBeUndefined(); + expect(mcpFiles).toEqual(allowedPlugins.map((plugin) => `plugins/${plugin}/.mcp.json`)); + for (const [plugin, serverName] of MCP_ALLOWED_LOCAL_SERVERS) { + const config = json(`plugins/${plugin}/.mcp.json`); + const servers = config.mcpServers ?? config; + expect(Object.keys(servers), plugin).toEqual([serverName]); + const server = servers[serverName]; + expect(server.type ?? "stdio", plugin).toBe("stdio"); + expect(server.url, plugin).toBeUndefined(); + } + }); - const nonEmptyRequired = readdirSync(path.join(root, "plugins"), { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => entry.name) + // Allowed and paused are the two halves of one partition. A plugin sitting in + // both would make every question about it answerable either way, depending on + // which list the caller happened to consult. + test("no plugin is both allowed and paused", () => { + expect([...MCP_ALLOWED_PLUGIN_SET].sort()).toEqual(allowedPlugins); + for (const plugin of MCP_PAUSED_PLUGINS) { + expect(MCP_ALLOWED_PLUGIN_SET.has(plugin), plugin).toBe(false); + } + }); + + test("requiredMcpServers is declared by exactly the allowed plugins", () => { + const nonEmptyRequired = pluginDirectories() .filter((plugin) => { const manifest = path.join(root, "plugins", plugin, ".crabcode-plugin", "plugin.json"); if (!existsSync(manifest)) return false; return (JSON.parse(readFileSync(manifest, "utf8")).requiredMcpServers?.length ?? 0) > 0; - }); - expect(nonEmptyRequired).toEqual([MCP_ALLOWED_PLUGIN]); + }) + .sort(); + expect(nonEmptyRequired).toEqual(allowedPlugins); + for (const [plugin, serverName] of MCP_ALLOWED_LOCAL_SERVERS) { + expect(json(`plugins/${plugin}/.crabcode-plugin/plugin.json`).requiredMcpServers, plugin).toEqual([serverName]); + } }); - test("binds every paused package, disclosure and one-step version bump to the evidence inventory", () => { + // The 2026-08-22 inventory is frozen history: it records what the containment + // release removed, and nothing about it changes when a plugin is later + // restored. Traceability is therefore an accounting identity — every plugin it + // removed is either still paused or named in a restore inventory. Without this + // a plugin could silently leave both lists. + test("every 2026-08-22 removal is still accounted for as paused or restored", () => { const evidence = json("docs/audit/evidence/2026-08-22-mcp-health/containment-inventory.json"); - const marketplace = json(".crabcode-plugin/marketplace.json"); - const entries = new Map( - marketplace.plugins.map((entry: any) => [entry.name, entry]), - ); - const removed = new Map( - evidence.removedConfigurations.map((entry: any) => [entry.pluginId, entry]), - ); - - expect(evidence.baselineId).toBe(MCP_SAFE_BASELINE_ID); - expect([...removed.keys()].sort()).toEqual([...MCP_PAUSED_PLUGINS].sort()); + expect(evidence.baselineId).toBe("mcp-emergency-safe-baseline-v1"); expect(evidence.expectedPostContainment).toEqual({ mcpConfigFiles: 1, totalServers: 1, @@ -67,9 +106,28 @@ describe("MCP emergency safe baseline", () => { sseServers: 0, stdioServers: 1, nonEmptyRequiredMcpPlugins: 1, - pausedMarketplaceDisclosures: MCP_PAUSED_PLUGINS.length, + pausedMarketplaceDisclosures: 42, }); + const removed = evidence.removedConfigurations.map((entry: any) => entry.pluginId).sort(); + const accounted = [ + ...MCP_PAUSED_PLUGINS, + ...restore.restored.map((entry) => entry.pluginId), + ].sort(); + expect(removed).toEqual(accounted); + expect(new Set(accounted).size).toBe(accounted.length); + }); + + test("binds every paused package, disclosure and one-step version bump to the evidence inventory", () => { + const evidence = json("docs/audit/evidence/2026-08-22-mcp-health/containment-inventory.json"); + const marketplace = json(".crabcode-plugin/marketplace.json"); + const entries = new Map( + marketplace.plugins.map((entry: any) => [entry.name, entry]), + ); + const removed = new Map( + evidence.removedConfigurations.map((entry: any) => [entry.pluginId, entry]), + ); + for (const plugin of MCP_PAUSED_PLUGINS) { const record: any = removed.get(plugin); const marketplaceEntry: any = entries.get(plugin); @@ -95,6 +153,7 @@ describe("MCP emergency safe baseline", () => { const allowedBytes = readFileSync(path.join(root, allowed.configPath)); expect(allowed.pluginId).toBe(MCP_ALLOWED_PLUGIN); expect(allowed.serverName).toBe(MCP_ALLOWED_SERVER); + expect(MCP_ALLOWED_LOCAL_SERVERS.get(allowed.pluginId)).toBe(allowed.serverName); expect(allowed.safeVersion).toBe(nextPatch(allowed.previousVersion)); expect(createHash("sha256").update(allowedBytes).digest("hex")).toBe( allowed.configSha256, @@ -104,4 +163,49 @@ describe("MCP emergency safe baseline", () => { ); expect(entries.get(MCP_ALLOWED_PLUGIN).version).toBe(allowed.safeVersion); }); + + // The restore inventory is the same kind of artefact as the containment one: + // it must name the exact bytes that were published and the exact version that + // carries them, or "restored" is an unverifiable claim. + test("the 2026-09-12 restore inventory binds to the published bytes and versions", () => { + expect(restore.baselineId).toBe(MCP_SAFE_BASELINE_ID); + expect(restore.decision).toBe("D-0(c)"); + expect(restore.stillPaused).toEqual([...MCP_PAUSED_PLUGINS]); + + const marketplace = json(".crabcode-plugin/marketplace.json"); + for (const entry of restore.restored) { + expect(MCP_ALLOWED_LOCAL_SERVERS.get(entry.pluginId), entry.pluginId).toBe(entry.serverName); + expect(entry.transport, entry.pluginId).toBe("stdio"); + expect(entry.configPath, entry.pluginId).toBe(`plugins/${entry.pluginId}/.mcp.json`); + const bytes = readFileSync(path.join(root, entry.configPath)); + expect(createHash("sha256").update(bytes).digest("hex"), entry.pluginId).toBe(entry.configSha256); + expect(entry.restoredVersion, entry.pluginId).toBe(nextPatch(entry.previousVersion)); + + expect(json(`plugins/${entry.pluginId}/.crabcode-plugin/plugin.json`).version, entry.pluginId).toBe(entry.restoredVersion); + expect(JSON.parse(readFileSync(path.join(root, "plugins", entry.pluginId, "package.json"), "utf8")).version, entry.pluginId).toBe(entry.restoredVersion); + const marketplaceEntry = marketplace.plugins.find((item: any) => item.name === entry.pluginId); + expect(marketplaceEntry.version, entry.pluginId).toBe(entry.restoredVersion); + } + }); + + // A restored plugin that keeps the pause disclosure tells every user the + // opposite of what the release does. + test("a restored marketplace entry carries no pause disclosure", () => { + const marketplace = json(".crabcode-plugin/marketplace.json"); + for (const entry of restore.restored) { + const marketplaceEntry = marketplace.plugins.find((item: any) => item.name === entry.pluginId); + const text = [ + marketplaceEntry.shortDescription, + marketplaceEntry.longDescription, + marketplaceEntry.description, + ].join("\n"); + expect(text.includes(MCP_PAUSED_MARKETPLACE_MARKER), entry.pluginId).toBe(false); + expect(text.includes("【连接暂停】"), entry.pluginId).toBe(false); + expect(text.includes("Executable MCP configuration is intentionally paused"), entry.pluginId).toBe(false); + // Positive control: the marker really is still carried by a paused entry, + // so this assertion cannot pass because the marker text stopped matching. + const paused = marketplace.plugins.find((item: any) => item.name === MCP_PAUSED_PLUGINS[0]); + expect(paused.longDescription.includes(MCP_PAUSED_MARKETPLACE_MARKER)).toBe(true); + } + }); }); diff --git a/tests/workflow-skill-presentation-completeness.test.ts b/tests/workflow-skill-presentation-completeness.test.ts index 924b29d..a297c8c 100644 --- a/tests/workflow-skill-presentation-completeness.test.ts +++ b/tests/workflow-skill-presentation-completeness.test.ts @@ -6,9 +6,10 @@ import { basename, join, resolve } from 'node:path' const root = resolve(import.meta.dir, '..') const EXPECTED_WORKFLOW_SKILLS = 316 const EXPECTED_INVOCATION_SET_SHA256 = '8fdfcd6fdd39d7fa952c6d0f554ed675429597869cac28f9239269588228ab33' -// Updated for the audited crabcopyright-cn v0.3.0 workflow-content migration; -// the 316 invocation identities remain unchanged and are pinned independently. -const EXPECTED_MODEL_CONTENT_SHA256 = '832c879eff1367a3b4ab2656e30c2dd81434e010bb17229cfef7d90c04ed122f' +// Updated 2026-09-12 for the crablaw-cn matter-core conflict-check / new-matter +// SKILL.md routing changes (coverage-incomplete, .pending, exit code 3); the 316 +// invocation identities remain unchanged and are pinned independently. +const EXPECTED_MODEL_CONTENT_SHA256 = '15a239a090ab580cded72a6f721b130be98c04dd9e6f9d24d225e5a21d5bc9ab' const HAN = /[\u3400-\u9fff]/u function sha256(value: string): string { @@ -79,7 +80,7 @@ describe('official workflow skill presentation completeness', () => { expect(new Set(invocationKeys).size).toBe(EXPECTED_WORKFLOW_SKILLS) expect(sha256(JSON.stringify(invocationKeys))).toBe(EXPECTED_INVOCATION_SET_SHA256) expect(sha256(JSON.stringify(modelContentHashes))).toBe(EXPECTED_MODEL_CONTENT_SHA256) - expect(marketplace.metadata.version).toBe('0.4.3') + expect(marketplace.metadata.version).toBe('0.4.4') const mediaEntry = workflows.find((entry) => entry.name === 'crabcode-media-ops') expect(mediaEntry).toBeDefined()