From b017e1fc487605757d145966e79c0d951d55bf7e Mon Sep 17 00:00:00 2001 From: yunyingk Date: Mon, 19 Oct 2026 17:02:16 +0800 Subject: [PATCH 1/2] Add safe knowledge document file editing --- skills/seal-use/SKILL.md | 3 +- skills/seal-use/references/cli.md | 10 +- skills/seal-use/references/documents.md | 65 +++++ src/cli.test.ts | 5 +- src/cli/commands/documents.test.ts | 165 +++++++++++++ src/cli/commands/documents.ts | 99 +++++--- src/cli/help.ts | 20 +- src/cli/parser.ts | 4 +- src/cli/read-only.test.ts | 3 + src/core/embedded-skill.generated.ts | 51 ++-- src/domains/seal/api.ts | 4 +- src/domains/seal/capabilities/rules.ts | 74 ++---- src/domains/seal/documents/files.ts | 148 ++++++++++++ src/domains/seal/documents/service.test.ts | 261 +++++++++++++++++++++ src/domains/seal/documents/service.ts | 132 +++++++++++ src/server.test.ts | 12 +- 16 files changed, 918 insertions(+), 138 deletions(-) create mode 100644 skills/seal-use/references/documents.md create mode 100644 src/cli/commands/documents.test.ts create mode 100644 src/domains/seal/documents/files.ts create mode 100644 src/domains/seal/documents/service.test.ts create mode 100644 src/domains/seal/documents/service.ts diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index 0661dec..36bc833 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -131,7 +131,8 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr | 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` | | CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 | | Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 | -| 规则数量、摘要列表、历史规则、编号重排、制度文档(`documents`)或知识搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` | +| 规则数量、摘要列表、历史规则、编号重排或规则搜索 | `references/rule-lightweight.md` | 需要质量评分/模糊表述检查时,改读 `rule-lint.md` | +| 制度/知识文档(`documents`)、正文文件导出编辑、文档更新/删除或本地快照 | `references/documents.md` | 只查命令参数时读 `cli.md` | | 规则质量评分、lint、发布前质检 | `references/rule-lint.md` | 不要把 lint 问题直接当成客诉根因 | | 客诉、截图/通知、预期业务行为,并要求诊断或修改规则 | `references/customer-feedback-rule-remediation.md` | 只有该流程明确要求附件追踪或测试发布时,才追加对应 reference | | Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` | diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 54d736d..e6e7296 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -203,12 +203,12 @@ seal-use analytics analyze [--corp ] seal-use analytics export [--downloads] [--out ] [--start-date ] [--end-date ] [--force] [--limit ] [--corp ] seal-use context [--ruleVersion ] [--documentLimit 50] [--corp ] seal-use source config [--corp ] -seal-use documents list [--scenarios ] [--limit 50] [--offset 0] [--corp ] -seal-use documents get [--corp ] +seal-use documents list [--summary] [--fields ] [--scenarios ] [--limit 50] [--offset 0] [--corp ] +seal-use documents get [--out ] [--content-format raw] [--overwrite] [--corp ] seal-use documents search [--maxResults 20] [--corp ] -seal-use documents create --title --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>] -seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>] -seal-use documents delete <documentId> --yes [--corp <corpId>] +seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>] +seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>] +seal-use documents delete <documentId> [--dry-run|--yes|--confirm] [--corp <corpId>] seal-use update [--check] [--force] [--version <v>] seal-use update check seal-use update changelog [--limit <n>] diff --git a/skills/seal-use/references/documents.md b/skills/seal-use/references/documents.md new file mode 100644 index 0000000..7d756fb --- /dev/null +++ b/skills/seal-use/references/documents.md @@ -0,0 +1,65 @@ +# 知识文档:文件编辑与安全更新 + +## 列表与读取 + +```bash +seal-use documents list --summary --corp <corpId> +seal-use documents list --fields id,title,purpose,updatedAt --corp <corpId> +seal-use documents get <documentId> --corp <corpId> +``` + +`list` 默认保留既有完整 JSON;`--summary` 返回 id、title、purpose、contentType、status、enabled、scenarios、tags、updatedAt,不返回 content。显式 `--fields` 覆盖摘要字段,非法字段报 exit 2。分页、过滤、total 不变;投影在客户端完成,不能据此声称减少了上游网络流量,也不会逐篇请求详情。 + +`get` 默认输出完整文档 JSON,正文位于 `content`。`--output-file <path>` 保存整份 JSON;`--out <path>` 单独导出正文,两者互斥。 + +## 导出 → 编辑 → 预览 → 更新 + +```bash +seal-use documents get <documentId> --out ./document.txt --corp <corpId> +# 编辑 document.txt;保留相邻的 document.txt.seal-use.json +seal-use documents update <documentId> --content-file ./document.txt --dry-run --corp <corpId> +seal-use documents update <documentId> --content-file ./document.txt --yes --corp <corpId> +``` + +导出产生三个本地文件:指定路径的 UTF-8 正文、相邻的 `.seal-use.json` 来源清单、配置目录 `document-history/` 下的原文快照。stdout 仍是 JSON 回执,包含路径、字节数、内容哈希和 snapshotId;文件权限为 0600,历史目录为 0700。正文不插入标题或 frontmatter,不 trim、不补末尾换行。扩展名可以是 `.md`,但不会改变编码行为。目标父目录须已存在;覆盖既有导出必须显式 `--overwrite`,目录和符号链接不可覆盖。 + +本期只支持 raw;`--content-format raw` 可显式指定。正文中的反斜杠、转义竖线、硬换行、代码与路径全部保持。Markdown 自动互转尚未开放,`--content-format markdown` 报 exit 2。不要批量替换 `\\` 或 `\|`:平台编码尚需真实脱敏样本证明可逆,JSON 显示转义也不能当作存储协议。 + +更新自动读取相邻来源清单,核对企业、Seal 服务地址与文档身份,并比较本次拟修改字段的导出基线哈希。远端变化返回 exit 1、`DOCUMENT_CONFLICT`,不会写入;`--yes` 不能绕过。重新导出并合并编辑后再预览。存在但损坏的清单报 exit 13,不会退化成无基线更新。 + +没有清单的旧 `--content-file` / `--content` 输入仍支持,但 preview、stderr 和回执明确 `baselineAvailable:false`,无法发现编辑期间发生的他人修改。不要为了绕过冲突删除清单。一次成功更新后,如需继续编辑,应重新导出新基线;保留本地修改前先自行留存,`--overwrite` 会覆盖正文。 + +仅传 `--content-file` 时,PATCH 只提交 content;title、purpose、status、enabled、scenarios、tags 保持。多个正文来源同时给出报 exit 2;非法 UTF-8、文件不可读或清单不可用报 exit 13。空或纯空白正文默认拒绝;明确要清空时加 `--allow-empty`。未变化的内容返回 `changed:false`,不写远端、不产生更新快照。 + +## 写入安全与兼容变化 + +所有 documents 创建、更新、删除正式执行均要求 `--yes` 或 `--confirm`,否则 exit 10。旧创建和更新脚本必须补确认标志。`--dry-run` 始终只读,即使同时提供确认标志也不写远端;预览不写历史快照。预览返回 `preview:true` 和结构化 `changesDiff`;内容过大时使用 `--output-file` 或有意选择 `--full`,仍遵守 exit 12 输出保护。 + +```bash +seal-use documents create --title <title> --purpose <purpose> --content-file ./document.txt --dry-run --corp <corpId> +seal-use documents create --title <title> --purpose <purpose> --content-file ./document.txt --yes --corp <corpId> +seal-use documents delete <documentId> --dry-run --corp <corpId> +seal-use documents delete <documentId> --yes --corp <corpId> +``` + +创建/更新成功回执改为紧凑执行结果,不再输出整篇文档;需要全文时重新 `get`。正式更新和删除前先保存实际将被覆盖的完整文档快照,备份失败则不写远端。创建和更新后回读,只有正文及预期保留字段核对通过才返回 `verified:true`。写请求禁用自动重试。 + +更新错误同时返回 JSON 状态和非零退出码: + +- `DOCUMENT_CONFLICT`:未执行写入,重新导出并审阅。 +- `DOCUMENT_WRITE_UNCERTAIN`:写入结果不确定,`executed:null`;先用返回的只读 next action 回读,不能盲目重跑。 +- `DOCUMENT_READBACK_FAILED`:已完成写请求,回读失败,`executed:true, verified:false`。 +- `DOCUMENT_VERIFICATION_FAILED`:回读和预期不符,保留 snapshotId / snapshotFile,核对当前状态后处理。 +- `DOCUMENT_AUTH_FAILED`:认证失败,exit 11;其他上述失败一般 exit 1。 + +创建请求失败时可能无法取得新文档 ID,应先查看列表,避免重复创建。删除成功表示服务端已接受删除;快照保留原对象,但重建不承诺保留原文档 ID。错误结果不会自动再次覆盖,也不会自动回滚。快照记录采集阶段,不能仅凭快照存在判断后续写入是否成功。 + +## 本地恢复、草稿和平台版本边界 + +历史默认位于当前配置文件所在目录的 `document-history/<来源哈希>/<snapshotId>.json`。包含正文和元数据,视为敏感业务数据,勿加入项目 Git。首期不自动清理快照,也没有快照浏览/一键恢复命令。 + +需要恢复时先回读当前文档,读取快照的 `document.content` 写成独立正文文件,再预览并确认更新;标题/状态等仅在明确需要时逐项传入。不要把整个快照当 PATCH 上传,不要覆盖作者、时间戳等系统字段。恢复本身是一次新更新,仍需备份与回读。 + +当前 CLI 有 `--status draft` 输入,但未验证其是否允许“旧发布版继续生效,同时编辑新草稿”。不要为了获得本地编辑稿而修改线上 status。文档更新可能立即影响生产;已发布版本与草稿并存、跨设备完整版本历史、原生回滚和原子条件写入属于待验证的平台能力。 + +客户端 GET→PATCH 之间仍有竞态窗口;哈希检查不能替代服务端 If-Match/修订号条件更新。本地快照只覆盖本机 CLI 留存过的内容,不能称为平台原生版本历史。 diff --git a/src/cli.test.ts b/src/cli.test.ts index 725f259..90287c3 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -107,12 +107,13 @@ describe("CLI version & help handling", () => { expect(result.stderr).toContain("Usage: seal-use documents get <documentId>"); }); - test("requires --yes confirmation on documents delete", () => { + test("requires explicit confirmation on documents delete", () => { const env = makeConfigEnv(); const result = runCli(["documents", "delete", "doc-123", "--corp", "corp-a"], env); expect(result.status).toBe(10); - expect(result.stderr).toContain("Refusing to delete document 'doc-123' without --yes."); + expect(result.stderr).toContain("documents delete requires --yes or --confirm"); + expect(result.stderr).toContain("--dry-run"); }); test("does not hijack --version option when passed to subcommands like rules", () => { diff --git a/src/cli/commands/documents.test.ts b/src/cli/commands/documents.test.ts new file mode 100644 index 0000000..60a6c3f --- /dev/null +++ b/src/cli/commands/documents.test.ts @@ -0,0 +1,165 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { runCli } from "../runner.js" + +const envKeys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE"] as const +const oldEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]])) +const oldFetch = globalThis.fetch +let dir: string +let document = { id: "doc-1", title: "Fixture policy", purpose: "Testing", content: "Line one\\\r\n| a \\| b |", status: "published", enabled: true, scenarios: ["audit"], tags: ["test"] } +let requests: Array<{ method: string; path: string; query: string; body?: Record<string, unknown> }> +let failReadback: boolean +const original = structuredClone(document) + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "seal-documents-cli-")) + const enterprises = join(dir, "enterprises") + mkdirSync(enterprises) + process.env.SEAL_USE_ENTERPRISES_DIR = enterprises + process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json") + process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json") + process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json") + writeFileSync(join(enterprises, "document-cli-test.json"), JSON.stringify({ + id: "document-cli-test", name: "Document Test", environment: "test", + seal: { url: "https://documents.example.test" }, + source: { type: "seal", token: "test-token", sealUrl: "https://documents.example.test", staffId: "fixture" } + })) + document = structuredClone(original) + requests = [] + failReadback = false + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init) + const url = new URL(request.url) + const method = request.method + const body = ["PATCH", "POST"].includes(method) ? JSON.parse(await request.text()) as Record<string, unknown> : undefined + requests.push({ method, path: url.pathname, query: url.searchParams.toString(), body }) + if (failReadback && method === "GET" && requests.some(item => item.method === "PATCH")) return Response.json({ error: "offline" }, { status: 400 }) + if (method === "PATCH") document = { ...document, ...(body?.attributes as object) } + if (method === "POST") document = { ...document, ...body } + return Response.json({ data: url.pathname.endsWith("/articles") && method === "GET" ? { articles: [document], total: 115 } : document }) + }) as typeof fetch +}) + +afterEach(() => { + for (const key of envKeys) { + if (oldEnv[key] === undefined) delete process.env[key] + else process.env[key] = oldEnv[key] + } + globalThis.fetch = oldFetch + rmSync(dir, { recursive: true, force: true }) +}) + +function cli(...argv: string[]) { return runCli(["documents", ...argv, "--corp", "document-cli-test"]) } +const writes = () => requests.filter(request => request.method !== "GET") + +describe("documents CLI", () => { + test("exports body plus baseline, previews edits, and updates only body with JSON receipts", async () => { + const out = join(dir, "body.txt") + const exported = await cli("get", "doc-1", "--out", out) + expect(exported.exitCode).toBe(0) + expect(JSON.parse(exported.stdout)).toMatchObject({ contentFile: out, contentFormat: "raw" }) + expect(readFileSync(out, "utf8")).toBe(original.content) + writeFileSync(out, "edited content") + const preview = await cli("update", "doc-1", "--content-file", out, "--dry-run", "--yes") + expect(preview.exitCode).toBe(0) + expect(JSON.parse(preview.stdout)).toMatchObject({ preview: true, executed: false, baselineAvailable: true, changedFields: ["content"] }) + expect(writes()).toHaveLength(0) + const result = await cli("update", "doc-1", "--content-file", out, "--yes") + expect(result.exitCode).toBe(0) + const payload = JSON.parse(result.stdout) + expect(payload).toMatchObject({ verified: true, executed: true, baselineAvailable: true }) + expect(JSON.parse(readFileSync(payload.snapshotFile, "utf8")).document.content).toBe(original.content) + expect(writes()).toHaveLength(1) + expect(writes()[0]?.body).toEqual({ attributes: { content: "edited content" } }) + expect(document.title).toBe(original.title) + expect(document.status).toBe("published") + }) + + test("plain get and output-file still produce whole document JSON", async () => { + expect(JSON.parse((await cli("get", "doc-1")).stdout)).toMatchObject(original) + const path = join(dir, "document.json") + const result = await cli("get", "doc-1", "--output-file", path) + expect(JSON.parse(result.stdout)).toMatchObject({ outputFile: path }) + expect(JSON.parse(readFileSync(path, "utf8"))).toMatchObject(original) + }) + + test("lightweight list and explicit fields do not request per-document details", async () => { + const summary = await cli("list", "--summary", "--limit", "2", "--offset", "1") + expect(summary.exitCode).toBe(0) + expect(JSON.parse(summary.stdout).articles[0]).not.toHaveProperty("content") + expect(new URLSearchParams(requests[0]?.query).get("limit")).toBe("2") + expect(new URLSearchParams(requests[0]?.query).get("offset")).toBe("1") + const fields = await cli("list", "--summary", "--fields", "id,title") + expect(JSON.parse(fields.stdout)).toEqual({ total: 115, articles: [{ id: "doc-1", title: original.title }] }) + expect(requests.every(request => request.path === "/api/v1/knowledge/articles")).toBe(true) + expect((await cli("list", "--fields", "typo")).exitCode).toBe(2) + }) + + test("all write commands require confirmation and all previews remain read-only", async () => { + const variants = [ + ["create", "--title", "new", "--purpose", "test", "--content", "new"], + ["update", "doc-1", "--content", "new"], + ["delete", "doc-1"] + ] + for (const argv of variants) { + expect((await cli(...argv)).exitCode).toBe(10) + for (const flag of ["--dry-run", "--dryRun"]) { + const result = await cli(...argv, flag, "--confirm") + expect(result.exitCode).toBe(0) + expect(JSON.parse(result.stdout)).toMatchObject({ preview: true, executed: false }) + } + } + expect(writes()).toHaveLength(0) + expect(existsSync(join(dir, "document-history"))).toBe(false) + }) + + test("conflicts and failed readback return JSON state with nonzero exit codes", async () => { + const path = join(dir, "body") + await cli("get", "doc-1", "--out", path) + writeFileSync(path, "my edit") + document.content = "remote edit" + const conflict = await cli("update", "doc-1", "--content-file", path, "--yes") + expect(conflict.exitCode).toBe(1) + expect(JSON.parse(conflict.stdout)).toMatchObject({ code: "DOCUMENT_CONFLICT", executed: false }) + expect(writes()).toHaveLength(0) + failReadback = true + const uncertain = await cli("update", "doc-1", "--content", "new", "--yes") + expect(uncertain.exitCode).toBe(1) + expect(JSON.parse(uncertain.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false }) + expect(uncertain.stderr).toContain("Next action:") + }) + + test("unsupported format and path/input conflicts fail before requests or file changes", async () => { + const path = join(dir, "body") + writeFileSync(path, "keep") + for (const argv of [ + ["get", "doc-1", "--out", path, "--content-format", "markdown"], + ["get", "doc-1", "--out", path, "--output-file", path], + ["update", "doc-1", "--content-file", path, "--content", "other", "--yes"], + ["update", "doc-1", "--content-file", path, "--output-file", path, "--yes"], + ["update", "doc-1", "--content-file", path, "--output-file", `${path}.seal-use.json`, "--yes"] + ]) expect((await cli(...argv)).exitCode).toBe(2) + expect(readFileSync(path, "utf8")).toBe("keep") + expect(requests).toHaveLength(0) + }) + + test("invalid UTF-8, missing file and damaged baseline fail with exit 13 and zero writes", async () => { + const path = join(dir, "body") + expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13) + writeFileSync(path, Buffer.from([0xff])) + expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13) + writeFileSync(path, "new") + writeFileSync(`${path}.seal-use.json`, "{}") + expect((await cli("update", "doc-1", "--content-file", path, "--yes")).exitCode).toBe(13) + expect(writes()).toHaveLength(0) + }) + + test("legacy raw input is supported and discloses absence of an editing baseline", async () => { + const result = await cli("update", "doc-1", "--content", "new", "--confirm") + expect(result.exitCode).toBe(0) + expect(JSON.parse(result.stdout)).toMatchObject({ verified: true, baselineAvailable: false }) + expect(result.stderr).toContain("baselineAvailable:false") + }) +}) diff --git a/src/cli/commands/documents.ts b/src/cli/commands/documents.ts index 5030bb9..93ebf27 100644 --- a/src/cli/commands/documents.ts +++ b/src/cli/commands/documents.ts @@ -1,8 +1,11 @@ -import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; -import { confirmationRequired, usageError } from "../../core/errors.js"; -import { runCapability } from "../helpers.js"; +import { usageError } from "../../core/errors.js"; +import { runCapability, runCapabilityResult } from "../helpers.js"; +import { exportDocument, readDocumentBaseline, readDocumentText } from "../../domains/seal/documents/files.js"; +import { DocumentMutationError } from "../../domains/seal/documents/service.js"; +import { ApprovalDocumentSchema } from "../../domains/seal/types.js"; import { booleanOption, jsonObject, @@ -10,17 +13,25 @@ import { splitOption, stringOption } from "../parser.js"; -import { outputOptions } from "../printer.js"; +import { outputOptions, printJson } from "../printer.js"; import type { ParsedArgs } from "../types.js"; -function readContentInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined { - const filePath = +function contentFilePath(args: ParsedArgs): string | undefined { + return ( stringOption(args.options.contentFile) ?? stringOption(args.options["content-file"]) ?? stringOption(args.options.file) ?? - stringOption(args.options.f); + stringOption(args.options.f) + ); +} + +function readContentInput(args: ParsedArgs, payload: Record<string, unknown>): string | undefined { + const filePath = contentFilePath(args); + const fileInputs = ["contentFile", "content-file", "file", "f"].filter(key => args.options[key] !== undefined).length; + const sources = fileInputs + Number(args.options.content !== undefined) + Number(payload.content !== undefined); + if (sources > 1) throw usageError("Specify exactly one document content source: --content-file, --content, or JSON content"); if (filePath) { - return readFileSync(filePath, "utf8"); + return readDocumentText(filePath); } const direct = stringOption(args.options.content); if (direct !== undefined) return direct; @@ -34,6 +45,33 @@ export async function handleDocumentsCommand( corp: CorpConfig, args: ParsedArgs ) { + const out = stringOption(args.options.out); + const format = stringOption(args.options["content-format"]) ?? stringOption(args.options.contentFormat); + if (format !== undefined && format !== "raw") throw usageError("--content-format supports raw only; Markdown conversion requires a verified platform codec"); + if (out && action !== "get") throw usageError("--out is supported only by documents get"); + if (format !== undefined && !["get", "create", "update"].includes(action ?? "")) throw usageError("--content-format is supported only by documents get/create/update"); + if (out && outputOptions(args.options).outputFile) throw usageError("--out (body) and --output-file (JSON) are mutually exclusive"); + if (booleanOption(args.options.overwrite) && !out) throw usageError("--overwrite requires documents get --out"); + const contentPath = contentFilePath(args); + const jsonOutput = outputOptions(args.options).outputFile; + if (contentPath && jsonOutput && [resolve(contentPath), `${resolve(contentPath)}.seal-use.json`].includes(resolve(jsonOutput))) { + throw usageError("--output-file must not overwrite the input body or its export baseline"); + } + + const safety = { + dryRun: booleanOption(args.options["dry-run"]) ?? booleanOption(args.options.dryRun), + confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true, + allowEmpty: booleanOption(args.options["allow-empty"]) ?? booleanOption(args.options.allowEmpty) + }; + const mutate = async (name: string, params: Record<string, unknown>) => { + try { + printJson(await runCapabilityResult(name, client, corp, params), outputOptions(args.options)); + } catch (error) { + if (error instanceof DocumentMutationError) printJson(error.payload, outputOptions(args.options)); + throw error; + } + }; + if (!action || action === "list") { const scenarios = splitOption(args.options.scenarios); const limit = numberOption(args.options.limit); @@ -42,7 +80,7 @@ export async function handleDocumentsCommand( "sealApprovalDocumentsList", client, corp, - { scenarios, limit, offset }, + { scenarios, limit, offset, summary: booleanOption(args.options.summary), fields: splitOption(args.options.fields) }, outputOptions(args.options) ); return; @@ -57,6 +95,11 @@ export async function handleDocumentsCommand( if (!documentId) { throw usageError("Usage: seal-use documents get <documentId> [--corp <corpId>]"); } + if (out) { + const document = ApprovalDocumentSchema.parse(await runCapabilityResult("sealApprovalDocumentGet", client, corp, { documentId })); + printJson(exportDocument(corp, document, out, booleanOption(args.options.overwrite))); + return; + } await runCapability( "sealApprovalDocumentGet", client, @@ -118,10 +161,8 @@ export async function handleDocumentsCommand( throw usageError("Usage: seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"); } - await runCapability( + await mutate( "sealApprovalDocumentCreate", - client, - corp, { title, purpose, @@ -130,9 +171,9 @@ export async function handleDocumentsCommand( status, enabled, scenarios, - tags - }, - outputOptions(args.options) + tags, + ...safety + } ); return; } @@ -180,10 +221,11 @@ export async function handleDocumentsCommand( throw usageError("Usage: seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]"); } - await runCapability( + const filePath = contentFilePath(args); + const baseline = filePath ? readDocumentBaseline(filePath) : undefined; + if (content !== undefined && !baseline) console.error("Document input has no export baseline; changes made by others during editing cannot be detected (baselineAvailable:false)."); + await mutate( "sealApprovalDocumentUpdate", - client, - corp, { documentId, title, @@ -193,9 +235,10 @@ export async function handleDocumentsCommand( status, enabled, scenarios, - tags - }, - outputOptions(args.options) + tags, + baseline, + ...safety + } ); return; } @@ -209,19 +252,9 @@ export async function handleDocumentsCommand( if (!documentId) { throw usageError("Usage: seal-use documents delete <documentId> --yes [--corp <corpId>]"); } - const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true; - if (!confirmed) { - throw confirmationRequired( - `Refusing to delete document '${documentId}' without --yes.`, - `seal-use documents delete ${documentId} --corp ${corp.id} --yes` - ); - } - await runCapability( + await mutate( "sealApprovalDeleteDocument", - client, - corp, - { documentId }, - outputOptions(args.options) + { documentId, dryRun: safety.dryRun, confirm: safety.confirm } ); return; } diff --git a/src/cli/help.ts b/src/cli/help.ts index 8ad75a7..e305e6f 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -1347,13 +1347,13 @@ export const HELP_REGISTRY: AreaHelp[] = [ commands: [ { name: "list", - summary: "List approval knowledge documents", - usage: ["seal-use documents list [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]"] + summary: "List knowledge documents; --summary omits body, --fields selects explicit fields", + usage: ["seal-use documents list [--summary] [--fields <id,title,purpose,updatedAt>] [--scenarios <audit,fill>] [--limit 50] [--offset 0] [--corp <corpId>]"] }, { name: "get", - summary: "Get approval knowledge document details by ID", - usage: ["seal-use documents get <documentId> [--corp <corpId>]"] + summary: "Get document JSON, or export exact UTF-8 body plus baseline with --out; --output-file saves JSON", + usage: ["seal-use documents get <documentId> [--out <path>] [--content-format raw] [--overwrite] [--corp <corpId>]"] }, { name: "search", @@ -1362,22 +1362,22 @@ export const HELP_REGISTRY: AreaHelp[] = [ }, { name: "create", - summary: "Create a new approval knowledge document", + summary: "Preview with --dry-run; --yes/--confirm creates and verifies a knowledge document", usage: [ - "seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]" + "seal-use documents create --title <title> --purpose <purpose> [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]" ] }, { name: "update", - summary: "Update an approval knowledge document by ID", + summary: "Preview changes; confirmed updates check export baseline, snapshot and verify readback", usage: [ - "seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--corp <corpId>]" + "seal-use documents update <documentId> [--title <title>] [--purpose <purpose>] [--content <text>|--content-file <path>] [--content-format raw] [--allow-empty] [--type <policy|document|video|pdf|feishu_doc>] [--enabled <true|false>] [--scenarios <audit,fill>] [--tags <tag1,tag2>] [--status <published|draft>] [--dry-run|--yes|--confirm] [--corp <corpId>]" ] }, { name: "delete", - summary: "Delete an approval knowledge document by ID", - usage: ["seal-use documents delete <documentId> --yes [--corp <corpId>]"] + summary: "Preview deletion; --yes/--confirm snapshots the document before deleting it", + usage: ["seal-use documents delete <documentId> [--dry-run|--yes|--confirm] [--corp <corpId>]"] } ] }, diff --git a/src/cli/parser.ts b/src/cli/parser.ts index e7cba4c..df8f0fb 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -23,7 +23,7 @@ import { usageError, validationError } from "../core/errors.js"; // Read with booleanOption(...) / Boolean(...) / presence check. export const BOOLEAN_FLAGS = new Set([ - "clear", "clear-max-file-size", "clearMaxFileSize", "latest", "show-secret", "showSecret", + "allow-empty", "allowEmpty", "clear", "clear-max-file-size", "clearMaxFileSize", "latest", "show-secret", "showSecret", "V", "add", "all", "allow-unreviewed", "allowUnreviewed", "as-hose", "attachments", "auto", "auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only", "completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache", @@ -47,7 +47,7 @@ export const VALUE_FLAGS = new Set([ "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity", "base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile", - "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", + "content-format", "contentFormat", "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", "dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc", "description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix", "docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type", diff --git a/src/cli/read-only.test.ts b/src/cli/read-only.test.ts index e10a40d..30be9e7 100644 --- a/src/cli/read-only.test.ts +++ b/src/cli/read-only.test.ts @@ -61,6 +61,8 @@ describe("CLI read-only classification", () => { ["expense", "--sn", "SN-FIXTURE", "--corp", "corp-a"], ["data", "expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"], ["documents", "get", "doc-1", "--corp", "corp-a"], + ["documents", "get", "doc-1", "--out", "./body.txt", "--corp", "corp-a"], + ["documents", "list", "--summary", "--fields", "id,title", "--corp", "corp-a"], ["documents", "search", "差旅", "--corp", "corp-a"], ["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"], ["approval-runs", "list", "--corp", "corp-a"], @@ -94,6 +96,7 @@ describe("CLI read-only classification", () => { ["rules", "clear"], ["documents", "create"], ["documents", "update", "doc-1"], + ["documents", "update", "doc-1", "--content-file", "body.txt", "--dry-run", "--yes"], ["documents", "delete", "doc-1"], ["simulation", "create", "--mode", "hosecloud"], ["deploy", "hosecloud", "sync", "sign-key"], diff --git a/src/core/embedded-skill.generated.ts b/src/core/embedded-skill.generated.ts index 4feeafe..c50a284 100644 --- a/src/core/embedded-skill.generated.ts +++ b/src/core/embedded-skill.generated.ts @@ -13,18 +13,19 @@ import file9 from "../../skills/seal-use/references/approval-bad-cases.md" with import file10 from "../../skills/seal-use/references/approval-run-lightweight.md" with { type: "text" }; import file11 from "../../skills/seal-use/references/cli.md" with { type: "text" }; import file12 from "../../skills/seal-use/references/customer-feedback-rule-remediation.md" with { type: "text" }; -import file13 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" }; -import file14 from "../../skills/seal-use/references/expense-data.md" with { type: "text" }; -import file15 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" }; -import file16 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" }; -import file17 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" }; -import file18 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" }; -import file19 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" }; -import file20 from "../../skills/seal-use/references/report-templates.md" with { type: "text" }; -import file21 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" }; -import file22 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" }; -import file23 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" }; -import file24 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" }; +import file13 from "../../skills/seal-use/references/documents.md" with { type: "text" }; +import file14 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" }; +import file15 from "../../skills/seal-use/references/expense-data.md" with { type: "text" }; +import file16 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" }; +import file17 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" }; +import file18 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" }; +import file19 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" }; +import file20 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" }; +import file21 from "../../skills/seal-use/references/report-templates.md" with { type: "text" }; +import file22 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" }; +import file23 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" }; +import file24 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" }; +import file25 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" }; export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = { "SKILL.md": file0, @@ -34,18 +35,19 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = { "references/approval-run-lightweight.md": file10, "references/cli.md": file11, "references/customer-feedback-rule-remediation.md": file12, - "references/enterprise-onboarding.md": file13, - "references/expense-data.md": file14, - "references/first-time-user.md": file15, - "references/hose-enterprise-auth.md": file16, - "references/hose-enterprise-deploy.md": file17, - "references/hose-enterprise-init.md": file18, - "references/langfuse-trace.md": file19, - "references/report-templates.md": file20, - "references/rule-lightweight.md": file21, - "references/rule-lint.md": file22, - "references/staging-simulation-workflow.md": file23, - "references/webhook-resource-pack.md": file24, + "references/documents.md": file13, + "references/enterprise-onboarding.md": file14, + "references/expense-data.md": file15, + "references/first-time-user.md": file16, + "references/hose-enterprise-auth.md": file17, + "references/hose-enterprise-deploy.md": file18, + "references/hose-enterprise-init.md": file19, + "references/langfuse-trace.md": file20, + "references/report-templates.md": file21, + "references/rule-lightweight.md": file22, + "references/rule-lint.md": file23, + "references/staging-simulation-workflow.md": file24, + "references/webhook-resource-pack.md": file25, }; export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = { @@ -71,6 +73,7 @@ export const EMBEDDED_SKILL_ALL_PATHS = [ "references/approval-run-lightweight.md", "references/cli.md", "references/customer-feedback-rule-remediation.md", + "references/documents.md", "references/enterprise-onboarding.md", "references/expense-data.md", "references/first-time-user.md", diff --git a/src/domains/seal/api.ts b/src/domains/seal/api.ts index b089acb..c1ca044 100644 --- a/src/domains/seal/api.ts +++ b/src/domains/seal/api.ts @@ -245,6 +245,7 @@ export async function createApprovalDocument( ) { return unwrap( await client.post("api/v1/knowledge/articles", { + retry: 0, json: { ...params, contentType: params.contentType ?? "policy", @@ -278,6 +279,7 @@ export async function updateApprovalDocument( return unwrap( await client.patch(`api/v1/knowledge/articles/${documentId}`, { + retry: 0, json: { attributes } }), ApprovalDocumentSchema @@ -288,7 +290,7 @@ export async function deleteApprovalDocument( client: KyInstance, documentId: string ): Promise<{ success: boolean; id: string }> { - await client.delete(`api/v1/knowledge/articles/${documentId}`); + await client.delete(`api/v1/knowledge/articles/${documentId}`, { retry: 0 }); return { success: true, id: documentId }; } diff --git a/src/domains/seal/capabilities/rules.ts b/src/domains/seal/capabilities/rules.ts index c951e50..af7eb29 100644 --- a/src/domains/seal/capabilities/rules.ts +++ b/src/domains/seal/capabilities/rules.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import type { KyInstance } from "ky"; import * as api from "../api.js"; +import { createDocument, deleteDocument, documentCreateSchema, documentDeleteSchema, documentListSchema, documentUpdateSchema, listDocuments, updateDocument } from "../documents/service.js"; import { recodeRules, type RecodeOptions } from "../rules/recode.js"; import { executeRulePush } from "../rules/push.js"; import { formatBeijingIso } from "../../../core/config/timestamps.js"; @@ -679,15 +680,11 @@ export const rulesCapabilities = [ { name: "sealApprovalDocumentsList", description: "列出 Seal 审批知识文档", - parameters: z.object({ - scenarios: z.array(z.string()).optional().describe("场景过滤"), - offset: z.number().int().nonnegative().optional(), - limit: z.number().int().positive().optional() - }), + parameters: documentListSchema, handler: async ( client: KyInstance, - params: { scenarios?: string[]; offset?: number; limit?: number } - ) => api.listApprovalDocuments(client, params) + params: z.infer<typeof documentListSchema> + ) => listDocuments(client, params) }, { name: "sealApprovalDocumentGet", @@ -701,70 +698,29 @@ export const rulesCapabilities = [ { name: "sealApprovalDocumentCreate", description: "新建 Seal 审批知识文档", - parameters: z.object({ - title: z.string(), - purpose: z.string(), - content: z.string().describe("正文,通常为 Markdown"), - contentType: z.string().optional(), - status: z.string().optional(), - enabled: z.boolean().optional(), - scenarios: z.array(z.string()).optional(), - tags: z.array(z.string()).optional() - }), + parameters: documentCreateSchema, handler: async ( client: KyInstance, - params: { - title: string; - purpose: string; - content: string; - contentType?: string; - status?: string; - enabled?: boolean; - scenarios?: string[]; - tags?: string[]; - } - ) => api.createApprovalDocument(client, params) + params: z.infer<typeof documentCreateSchema>, + context: CapabilityContext + ) => createDocument(client, context.corp, params) }, { name: "sealApprovalDocumentUpdate", description: "更新 Seal 审批知识文档", - parameters: z.object({ - documentId: z.string(), - title: z.string().optional(), - purpose: z.string().optional(), - content: z.string().optional(), - contentType: z.string().optional(), - status: z.string().optional(), - enabled: z.boolean().optional(), - scenarios: z.array(z.string()).optional(), - tags: z.array(z.string()).optional() - }), + parameters: documentUpdateSchema, handler: async ( client: KyInstance, - params: { - documentId: string; - title?: string; - purpose?: string; - content?: string; - contentType?: string; - status?: string; - enabled?: boolean; - scenarios?: string[]; - tags?: string[]; - } - ) => { - const { documentId, ...rest } = params; - return api.updateApprovalDocument(client, documentId, rest); - } + params: z.infer<typeof documentUpdateSchema>, + context: CapabilityContext + ) => updateDocument(client, context.corp, params) }, { name: "sealApprovalDeleteDocument", description: "删除 Seal 审批知识文档", - parameters: z.object({ - documentId: z.string().describe("知识文档 ID") - }), - handler: (client: KyInstance, params: { documentId: string }) => - api.deleteApprovalDocument(client, params.documentId) + parameters: documentDeleteSchema, + handler: (client: KyInstance, params: z.infer<typeof documentDeleteSchema>, context: CapabilityContext) => + deleteDocument(client, context.corp, params) }, { name: "sealApprovalSearch", diff --git a/src/domains/seal/documents/files.ts b/src/domains/seal/documents/files.ts new file mode 100644 index 0000000..71eec99 --- /dev/null +++ b/src/domains/seal/documents/files.ts @@ -0,0 +1,148 @@ +import { createHash, randomUUID } from "node:crypto" +import { chmodSync, closeSync, existsSync, fsyncSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs" +import { dirname, join, resolve } from "node:path" +import { z } from "zod" +import type { CorpConfig } from "../../../core/config/types.js" +import { resolveGlobalConfigFile } from "../../../core/config/loader.js" +import { formatBeijingIso } from "../../../core/config/timestamps.js" +import { validationError } from "../../../core/errors.js" +import type { ApprovalDocument } from "../types.js" + +export const DOCUMENT_EDITABLE_FIELDS = ["title", "purpose", "content", "contentType", "status", "enabled", "scenarios", "tags"] as const +export type DocumentField = typeof DOCUMENT_EDITABLE_FIELDS[number] +const hashSchema = z.string().regex(/^[a-f0-9]{64}$/) +const sourceSchema = z.object({ corpId: z.string(), sealUrl: z.string().url(), documentId: z.string() }) +export const documentBaselineSchema = z.object({ + schemaVersion: z.literal(1), + contentFormat: z.literal("raw"), + source: sourceSchema, + exportedAt: z.string(), + contentHash: hashSchema, + fieldHashes: z.record(z.enum(DOCUMENT_EDITABLE_FIELDS), hashSchema), + snapshotId: z.string() +}).refine(value => value.contentHash === value.fieldHashes.content, "Baseline content hash is inconsistent") +export type DocumentBaseline = z.infer<typeof documentBaselineSchema> + +export function documentHash(value: unknown): string { + return createHash("sha256").update(typeof value === "string" ? value : JSON.stringify(value)).digest("hex") +} + +export function documentSource(corp: CorpConfig, documentId: string) { + const sealUrl = corp.seal.url ?? corp.source.sealUrl + if (!sealUrl) throw validationError("Document operations require a Seal service URL") + const url = new URL(sealUrl) + url.username = "" + url.password = "" + url.search = "" + url.hash = "" + return { corpId: corp.id, sealUrl: url.toString().replace(/\/+$/, ""), documentId } +} + +export function documentFieldHashes(document: ApprovalDocument) { + return Object.fromEntries(DOCUMENT_EDITABLE_FIELDS.map(field => [field, documentHash(document[field])])) as Record<DocumentField, string> +} + +function localFileError(path: string, error: unknown): never { + const reason = error instanceof Error ? error.message : String(error) + throw validationError(`Cannot use document file ${path}: ${reason}`) +} + +export function readDocumentText(path: string): string { + try { + // ignoreBOM preserves a leading U+FEFF instead of silently stripping it. + return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(readFileSync(path)) + } catch (error) { + return localFileError(path, error) + } +} + +export function readDocumentBaseline(contentFile: string): DocumentBaseline | undefined { + const path = `${resolve(contentFile)}.seal-use.json` + // lstat also detects a dangling symlink, which must not silently disable protection. + try { + lstatSync(path) + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined + return localFileError(path, error) + } + try { + return documentBaselineSchema.parse(JSON.parse(readDocumentText(path))) + } catch (error) { + return localFileError(path, error) + } +} + +export function saveDocumentSnapshot(corp: CorpConfig, document: ApprovalDocument, operation: "export" | "update" | "delete") { + const source = documentSource(corp, document.id) + const history = join(dirname(resolveGlobalConfigFile()), "document-history") + const dir = join(history, documentHash(source)) + const snapshotId = randomUUID() + const snapshotFile = join(dir, `${snapshotId}.json`) + try { + mkdirSync(dir, { recursive: true, mode: 0o700 }) + chmodSync(history, 0o700) + chmodSync(dir, 0o700) + const fd = openSync(snapshotFile, "wx", 0o600) + try { + writeFileSync(fd, `${JSON.stringify({ schemaVersion: 1, snapshotId, source, capturedAt: formatBeijingIso(), operation, phase: "captured", document }, null, 2)}\n`) + fsyncSync(fd) + } finally { closeSync(fd) } + } catch (error) { + return localFileError(snapshotFile, error) + } + return { snapshotId, snapshotFile } +} + +export function exportDocument(corp: CorpConfig, document: ApprovalDocument, outputPath: string, overwrite = false) { + const contentFile = resolve(outputPath) + const manifestFile = `${contentFile}.seal-use.json` + const destinations = [contentFile, manifestFile] + let staging: string | undefined + const previous: Array<{ destination: string; backup: string }> = [] + const published: string[] = [] + let preserveStaging = false + try { + for (const path of destinations) { + let stat + try { stat = lstatSync(path) } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + } + if (stat && (!overwrite || !stat.isFile() || stat.isSymbolicLink())) { + throw new Error(`Refusing to replace ${path}; use --overwrite only for regular export files`) + } + } + staging = mkdtempSync(join(dirname(contentFile), ".seal-document-")) + const snapshot = saveDocumentSnapshot(corp, document, "export") + const baseline: DocumentBaseline = { + schemaVersion: 1, contentFormat: "raw", source: documentSource(corp, document.id), exportedAt: formatBeijingIso(), + contentHash: documentHash(document.content), fieldHashes: documentFieldHashes(document), snapshotId: snapshot.snapshotId + } + const contents = [document.content, `${JSON.stringify(baseline, null, 2)}\n`] + for (const [index, content] of contents.entries()) { + writeFileSync(join(staging, String(index)), content, { flag: "wx", mode: 0o600 }) + } + for (const [index, destination] of destinations.entries()) { + if (overwrite && existsSync(destination)) { + if (!lstatSync(destination).isFile() || lstatSync(destination).isSymbolicLink()) throw new Error(`Export destination changed during publication: ${destination}`) + const backup = join(staging, `before-${index}`) + renameSync(destination, backup) + previous.push({ destination, backup }) + } + // Exclusive publication: never truncate a destination created after preflight. + linkSync(join(staging, String(index)), destination) + published.push(destination) + } + return { contentFile, manifestFile, contentFormat: "raw", bytes: Buffer.byteLength(document.content, "utf8"), contentHash: baseline.contentHash, ...snapshot } + } catch (error) { + try { + for (const path of published.reverse()) rmSync(path) + for (const { destination, backup } of previous.reverse()) renameSync(backup, destination) + } catch { + preserveStaging = true + throw validationError(`Document export failed; original files retained for recovery in ${staging}`) + } + return localFileError(contentFile, error) + } finally { + if (staging && !preserveStaging) rmSync(staging, { recursive: true, force: true }) + } +} diff --git a/src/domains/seal/documents/service.test.ts b/src/domains/seal/documents/service.test.ts new file mode 100644 index 0000000..daf38a5 --- /dev/null +++ b/src/domains/seal/documents/service.test.ts @@ -0,0 +1,261 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test" +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import type { KyInstance } from "ky" +import type { CorpConfig } from "../../../core/config/types.js" +import { classifyCliError } from "../../../core/errors.js" +import { ApprovalDocumentSchema } from "../types.js" +import { documentFieldHashes, documentHash, documentSource, exportDocument, readDocumentBaseline, readDocumentText } from "./files.js" +import { createDocument, deleteDocument, DocumentMutationError, listDocuments, updateDocument } from "./service.js" + +const originalConfig = process.env.SEAL_USE_CONFIG_FILE +let dir: string +const corp = { id: "corp-fixture", seal: { url: "https://seal.example.test" }, source: { type: "seal" } } as CorpConfig +const initial = () => ApprovalDocumentSchema.parse({ id: "doc-1", title: "测试名单", purpose: "制度", content: "\uFEFF| 姓名 \\| 资格 |\\\r\n| --- | --- |\r\n\\path\\file \r\n末行", status: "published", enabled: true, tags: ["名单"], scenarios: ["audit"], updatedAt: 123 }) + +function fixture() { + let document = initial() + const requests: Array<{ method: string; path: string; options?: { json?: unknown; retry?: unknown } }> = [] + let reads = 0 + let failWrite = false + let failReadback = false + let corruptReadback = false + const client = { + get(path: string) { + requests.push({ method: "GET", path }) + return { json: async () => { + if (path === "api/v1/knowledge/articles") return { data: { articles: [document], total: 115 } } + reads++ + if (failReadback && reads > 1) throw new Error("readback unavailable") + return { data: structuredClone(corruptReadback && reads > 1 ? { ...document, status: "draft" } : document) } + } } + }, + patch(path: string, options: { json: { attributes: Record<string, unknown> }; retry: unknown }) { + requests.push({ method: "PATCH", path, options }) + document = ApprovalDocumentSchema.parse({ ...document, ...options.json.attributes }) + if (failWrite) throw new Error("timeout after sending request") + return { json: async () => ({ data: document }) } + }, + post(path: string, options: { json: Record<string, unknown>; retry: unknown }) { + requests.push({ method: "POST", path, options }) + document = ApprovalDocumentSchema.parse({ ...options.json, id: "created-1" }) + return { json: async () => ({ data: document }) } + }, + async delete(path: string, options: { retry: unknown }) { requests.push({ method: "DELETE", path, options }) } + } as unknown as KyInstance + return { + client, requests, get document() { return document }, + set document(value) { document = value }, + set failWrite(value: boolean) { failWrite = value }, + set failReadback(value: boolean) { failReadback = value }, + set corruptReadback(value: boolean) { corruptReadback = value }, + writes: () => requests.filter(request => request.method !== "GET") + } +} + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "seal-document-test-")) + process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json") +}) +afterEach(() => { + if (originalConfig === undefined) delete process.env.SEAL_USE_CONFIG_FILE + else process.env.SEAL_USE_CONFIG_FILE = originalConfig + rmSync(dir, { recursive: true, force: true }) +}) + +describe("document files", () => { + test("exports exact UTF-8 content, a source manifest, and private original snapshot", () => { + const document = initial() + const result = exportDocument(corp, document, join(dir, "名单.md")) + expect(readFileSync(result.contentFile)).toEqual(Buffer.from(document.content, "utf8")) + expect(readDocumentText(result.contentFile)).toBe(document.content) + expect(readDocumentBaseline(result.contentFile)).toMatchObject({ source: documentSource(corp, document.id), fieldHashes: documentFieldHashes(document), contentFormat: "raw" }) + const snapshot = JSON.parse(readFileSync(result.snapshotFile, "utf8")) + expect(snapshot.document).toEqual(document) + expect(snapshot.capturedAt).toMatch(/\+08:00$/) + for (const path of [result.contentFile, result.manifestFile, result.snapshotFile]) expect(statSync(path).mode & 0o777).toBe(0o600) + expect(statSync(join(dir, "document-history")).mode & 0o777).toBe(0o700) + }) + + test("existing exports require overwrite and both files are replaced together", () => { + const out = join(dir, "body.txt") + const result = exportDocument(corp, initial(), out) + writeFileSync(out, "local changes") + expect(() => exportDocument(corp, initial(), out)).toThrow("--overwrite") + expect(readFileSync(out, "utf8")).toBe("local changes") + exportDocument(corp, { ...initial(), content: "new" }, out, true) + expect(readDocumentText(out)).toBe("new") + expect(readDocumentBaseline(out)?.contentHash).toBe(documentHash("new")) + expect(JSON.parse(readFileSync(result.snapshotFile, "utf8")).document.content).toBe(initial().content) + }) + + test("invalid destinations and symlinks do not damage existing files", () => { + const out = join(dir, "body.txt") + writeFileSync(out, "keep") + mkdirSync(`${out}.seal-use.json`) + expect(() => exportDocument(corp, initial(), out, true)).toThrow() + expect(readFileSync(out, "utf8")).toBe("keep") + const link = join(dir, "link") + symlinkSync(out, link) + expect(() => exportDocument(corp, initial(), link, true)).toThrow() + expect(readFileSync(out, "utf8")).toBe("keep") + }) + + test("partial export publication rolls back only its own body and preserves a racing file", () => { + const out = join(dir, "body.txt") + const document = initial() + Object.defineProperty(document, "content", { enumerable: true, get() { + if (!existsSync(`${out}.seal-use.json`)) writeFileSync(`${out}.seal-use.json`, "another writer") + return initial().content + } }) + expect(() => exportDocument(corp, document, out)).toThrow() + expect(existsSync(out)).toBe(false) + expect(readFileSync(`${out}.seal-use.json`, "utf8")).toBe("another writer") + }) + + test("invalid UTF-8 and damaged or dangling manifests fail instead of losing baseline protection", () => { + const out = join(dir, "body") + writeFileSync(out, Buffer.from([0xff])) + expect(() => readDocumentText(out)).toThrow("Cannot use document file") + expect(readDocumentBaseline(out)).toBeUndefined() + writeFileSync(`${out}.seal-use.json`, "{}") + expect(() => readDocumentBaseline(out)).toThrow() + rmSync(`${out}.seal-use.json`) + symlinkSync(join(dir, "missing"), `${out}.seal-use.json`) + expect(() => readDocumentBaseline(out)).toThrow() + }) +}) + +describe("document mutations", () => { + for (const confirm of [true, false]) { + test(`all dry-runs avoid writes and history even with confirm=${confirm}`, async () => { + const f = fixture() + const create = await createDocument(f.client, corp, { title: "new", purpose: "policy", content: "body", dryRun: true, confirm }) + const update = await updateDocument(f.client, corp, { documentId: "doc-1", content: "changed", dryRun: true, confirm }) + const remove = await deleteDocument(f.client, corp, { documentId: "doc-1", dryRun: true, confirm }) + for (const result of [create, update, remove]) expect(result).toMatchObject({ preview: true, executed: false }) + expect(f.writes()).toHaveLength(0) + expect(existsSync(join(dir, "document-history"))).toBe(false) + }) + } + + test("all live mutations without confirmation fail with exit 10 before HTTP", async () => { + const f = fixture() + for (const operation of [ + () => createDocument(f.client, corp, { title: "new", purpose: "policy", content: "body" }), + () => updateDocument(f.client, corp, { documentId: "doc-1", content: "new" }), + () => deleteDocument(f.client, corp, { documentId: "doc-1" }) + ]) { + try { await operation(); throw new Error("expected rejection") } catch (error) { expect(classifyCliError(error).exitCode).toBe(10) } + } + expect(f.requests).toHaveLength(0) + }) + + test("updates only requested attributes, saves actual prior state, and verifies preserved metadata", async () => { + const f = fixture() + const out = join(dir, "body.txt") + exportDocument(corp, f.document, out) + const baseline = readDocumentBaseline(out) + const result = await updateDocument(f.client, corp, { documentId: "doc-1", content: "new content", baseline, confirm: true }) + expect(result).toMatchObject({ executed: true, verified: true, baselineAvailable: true, changedFields: ["content"] }) + expect(f.writes()).toEqual([{ method: "PATCH", path: "api/v1/knowledge/articles/doc-1", options: { json: { attributes: { content: "new content" } }, retry: 0 } }]) + expect(f.document.title).toBe(initial().title) + expect(f.document.status).toBe("published") + expect("snapshotFile" in result).toBe(true) + if ("snapshotFile" in result) expect(JSON.parse(readFileSync(result.snapshotFile!, "utf8")).document).toEqual(initial()) + }) + + test("unchanged upload is a no-op with no write or history", async () => { + const f = fixture() + expect(await updateDocument(f.client, corp, { documentId: "doc-1", content: f.document.content, confirm: true })).toMatchObject({ executed: false, changed: false, verified: true }) + expect(f.writes()).toHaveLength(0) + expect(existsSync(join(dir, "document-history"))).toBe(false) + }) + + test("remote changes conflict even with confirmation", async () => { + const f = fixture() + const out = join(dir, "body.txt") + exportDocument(corp, f.document, out) + f.document = { ...f.document, content: "someone else edited" } + try { + await updateDocument(f.client, corp, { documentId: "doc-1", content: "my edit", baseline: readDocumentBaseline(out), confirm: true }) + throw new Error("expected rejection") + } catch (error) { + expect(error).toBeInstanceOf(DocumentMutationError) + expect((error as DocumentMutationError).payload).toMatchObject({ code: "DOCUMENT_CONFLICT", executed: false, conflictingFields: ["content"] }) + } + expect(f.writes()).toHaveLength(0) + }) + + test("a baseline cannot be uploaded into another enterprise or service", async () => { + const f = fixture() + const out = join(dir, "body.txt") + exportDocument(corp, f.document, out) + for (const target of [{ ...corp, id: "other-corp" }, { ...corp, seal: { ...corp.seal, url: "https://other.test" } }]) { + await expect(updateDocument(f.client, target, { documentId: "doc-1", content: "my edit", baseline: readDocumentBaseline(out), confirm: true })).rejects.toThrow("different enterprise") + } + expect(f.requests).toHaveLength(0) + }) + + test("empty content requires an explicit allow-empty flag", async () => { + const f = fixture() + await expect(updateDocument(f.client, corp, { documentId: "doc-1", content: " ", confirm: true })).rejects.toThrow("--allow-empty") + expect(f.requests).toHaveLength(0) + expect(await updateDocument(f.client, corp, { documentId: "doc-1", content: "", confirm: true, allowEmpty: true })).toMatchObject({ verified: true }) + }) + + test("snapshot failure prevents PATCH and DELETE", async () => { + const f = fixture() + writeFileSync(join(dir, "document-history"), "not a directory") + await expect(updateDocument(f.client, corp, { documentId: "doc-1", content: "new", confirm: true })).rejects.toThrow("Cannot use document file") + await expect(deleteDocument(f.client, corp, { documentId: "doc-1", confirm: true })).rejects.toThrow("Cannot use document file") + expect(f.writes()).toHaveLength(0) + }) + + for (const mode of ["timeout", "readback", "mismatch"] as const) { + test(`reports ${mode} with recovery snapshot and no blind retry`, async () => { + const f = fixture() + f.failWrite = mode === "timeout" + f.failReadback = mode === "readback" + f.corruptReadback = mode === "mismatch" + try { + await updateDocument(f.client, corp, { documentId: "doc-1", content: "new", confirm: true }) + throw new Error("expected rejection") + } catch (error) { + expect(error).toBeInstanceOf(DocumentMutationError) + const payload = (error as DocumentMutationError).payload + expect(payload.code).toBe({ timeout: "DOCUMENT_WRITE_UNCERTAIN", readback: "DOCUMENT_READBACK_FAILED", mismatch: "DOCUMENT_VERIFICATION_FAILED" }[mode]) + expect(payload.executed).toBe(mode === "timeout" ? null : true) + expect(payload.verified).toBe(false) + expect(existsSync(String(payload.snapshotFile))).toBe(true) + } + expect(f.writes()).toHaveLength(1) + }) + } + + test("create and delete also disable transport retries", async () => { + const f = fixture() + expect(await createDocument(f.client, corp, { title: "new", purpose: "policy", content: "body", confirm: true })).toMatchObject({ verified: true }) + await deleteDocument(f.client, corp, { documentId: "created-1", confirm: true }) + expect(f.writes().map(request => [request.method, request.options?.retry])).toEqual([["POST", 0], ["DELETE", 0]]) + }) +}) + +describe("document lists", () => { + test("summary and explicit fields preserve totals while default retains content", async () => { + const f = fixture() + expect((await listDocuments(f.client, {})).articles[0]).toHaveProperty("content") + const summary = await listDocuments(f.client, { summary: true }) + expect(summary.total).toBe(115) + expect(summary.articles[0]).not.toHaveProperty("content") + expect((await listDocuments(f.client, { summary: true, fields: ["id", "title"] })).articles).toEqual([{ id: "doc-1", title: "测试名单" }]) + expect(f.requests.every(request => request.path === "api/v1/knowledge/articles")).toBe(true) + }) + + test("invalid projection fields fail before HTTP", async () => { + const f = fixture() + await expect(listDocuments(f.client, { fields: ["typo"] })).rejects.toThrow("Unknown document field") + expect(f.requests).toHaveLength(0) + }) +}) diff --git a/src/domains/seal/documents/service.ts b/src/domains/seal/documents/service.ts new file mode 100644 index 0000000..ad09075 --- /dev/null +++ b/src/domains/seal/documents/service.ts @@ -0,0 +1,132 @@ +import { z } from "zod" +import type { KyInstance } from "ky" +import type { CorpConfig } from "../../../core/config/types.js" +import { CliError, classifyCliError, confirmationRequired, usageError, validationError } from "../../../core/errors.js" +import * as api from "../api.js" +import { ApprovalDocumentSchema, type ApprovalDocument } from "../types.js" +import { DOCUMENT_EDITABLE_FIELDS, documentBaselineSchema, documentFieldHashes, documentHash, documentSource, saveDocumentSnapshot, type DocumentField } from "./files.js" + +export const DOCUMENT_SUMMARY_FIELDS = ["id", "title", "purpose", "contentType", "status", "enabled", "scenarios", "tags", "updatedAt"] +const documentFields = Object.keys(ApprovalDocumentSchema.shape) +export const documentListSchema = z.object({ + scenarios: z.array(z.string()).optional().describe("场景过滤"), offset: z.number().int().nonnegative().optional(), limit: z.number().int().positive().optional(), + summary: z.boolean().optional(), fields: z.array(z.string()).optional() +}) +const attributesSchema = z.object({ + title: z.string(), purpose: z.string(), content: z.string().describe("正文,通常为 Markdown;raw 原样传输"), contentType: z.string().optional(), status: z.string().optional(), + enabled: z.boolean().optional(), scenarios: z.array(z.string()).optional(), tags: z.array(z.string()).optional() +}) +const safetyShape = { dryRun: z.boolean().optional(), confirm: z.boolean().optional(), allowEmpty: z.boolean().optional() } +export const documentCreateSchema = attributesSchema.extend(safetyShape) +export const documentUpdateSchema = attributesSchema.partial().extend({ + documentId: z.string().describe("知识文档 ID"), ...safetyShape, baseline: documentBaselineSchema.optional() +}) +export const documentDeleteSchema = z.object({ documentId: z.string().describe("知识文档 ID"), dryRun: z.boolean().optional(), confirm: z.boolean().optional() }) +type DocumentAttributes = z.infer<typeof attributesSchema> + +export class DocumentMutationError extends CliError { + constructor(readonly payload: Record<string, unknown>, message: string, exitCode: 1 | 11 = 1, nextAction?: string) { + super(message, exitCode, nextAction) + this.name = "DocumentMutationError" + } +} + +export async function listDocuments(client: KyInstance, params: z.infer<typeof documentListSchema>) { + const fields = params.fields ?? (params.summary ? DOCUMENT_SUMMARY_FIELDS : undefined) + if (fields?.some(field => !documentFields.includes(field))) throw usageError(`Unknown document field; allowed: ${documentFields.join(", ")}`) + const result = await api.listApprovalDocuments(client, params) + return fields ? { ...result, articles: result.articles.map(document => Object.fromEntries(fields.map(field => [field, document[field as keyof ApprovalDocument]]))) } : result +} + +function quote(value: string) { return `'${value.replace(/'/g, "'\\''")}'` } +function nextRead(corp: CorpConfig, id: string) { return `seal-use documents get ${quote(id)} --corp ${quote(corp.id)}` } + +function requireConfirmation(action: string, params: { dryRun?: boolean; confirm?: boolean }) { + if (!params.dryRun && !params.confirm) { + throw confirmationRequired(`documents ${action} requires --yes or --confirm. Inspect --dry-run first.`, `seal-use help documents ${action}`) + } +} + +function validateContent(content: string | undefined, allowEmpty?: boolean) { + if (content !== undefined && !content.trim() && !allowEmpty) throw validationError("Empty document content requires --allow-empty") +} + +function changes(before: ApprovalDocument | undefined, patch: Partial<DocumentAttributes>) { + return DOCUMENT_EDITABLE_FIELDS.filter(field => patch[field] !== undefined && (!before || documentHash(before[field]) !== documentHash(patch[field]))) +} + +function preview(corp: CorpConfig, id: string, before: ApprovalDocument | undefined, patch: Partial<DocumentAttributes>, fields: DocumentField[], baselineAvailable = false) { + return { + source: documentSource(corp, id), preview: true, executed: false, changed: fields.length > 0, changedFields: fields, baselineAvailable, + changesDiff: Object.fromEntries(fields.map(field => [field, { before: before?.[field] ?? null, after: patch[field] }])), + contentStats: patch.content === undefined ? undefined : { + beforeBytes: Buffer.byteLength(before?.content ?? "", "utf8"), afterBytes: Buffer.byteLength(patch.content, "utf8"), + beforeLines: before?.content.split(/\r?\n/).length ?? 0, afterLines: patch.content.split(/\r?\n/).length + } + } +} + +function failedWrite(error: unknown, payload: Record<string, unknown>, nextAction?: string): never { + const auth = classifyCliError(error).exitCode === 11 + throw new DocumentMutationError({ ...payload, code: auth ? "DOCUMENT_AUTH_FAILED" : "DOCUMENT_WRITE_UNCERTAIN", executed: auth ? false : null, verified: false }, "Document write did not complete with a verified response; inspect current state before retrying.", auth ? 11 : 1, nextAction) +} + +export async function createDocument(client: KyInstance, corp: CorpConfig, params: z.infer<typeof documentCreateSchema>) { + validateContent(params.content, params.allowEmpty) + requireConfirmation("create", params) + const { dryRun, confirm: _confirm, allowEmpty: _allowEmpty, ...attributes } = params + const patch = { ...attributes, contentType: attributes.contentType ?? "policy", status: attributes.status ?? "published", enabled: attributes.enabled ?? true, scenarios: attributes.scenarios?.length ? attributes.scenarios : ["audit"], tags: attributes.tags ?? [] } + if (dryRun) return preview(corp, "(new)", undefined, patch, changes(undefined, patch)) + let created: ApprovalDocument + try { created = await api.createApprovalDocument(client, patch) } catch (error) { + return failedWrite(error, { source: { corpId: corp.id }, preview: false, operation: "create" }) + } + return verifyDocument(client, corp, created.id, patch, changes(undefined, patch), false) +} + +async function verifyDocument(client: KyInstance, corp: CorpConfig, id: string, expected: Partial<DocumentAttributes>, changedFields: DocumentField[], baselineAvailable: boolean, snapshot?: { snapshotId: string; snapshotFile: string }) { + const receipt = { source: documentSource(corp, id), preview: false, executed: true, changed: true, changedFields, baselineAvailable, ...snapshot } + let after: ApprovalDocument + try { after = await api.getApprovalDocument(client, id) } catch { + throw new DocumentMutationError({ ...receipt, code: "DOCUMENT_READBACK_FAILED", verified: false }, "Document was written, but readback failed.", 1, nextRead(corp, id)) + } + const mismatchedFields = changes(after, expected) + if (mismatchedFields.length) throw new DocumentMutationError({ ...receipt, code: "DOCUMENT_VERIFICATION_FAILED", verified: false, mismatchedFields }, "Document readback differs from the expected state.", 1, nextRead(corp, id)) + return { ...receipt, verified: true, contentHash: documentHash(after.content) } +} + +export async function updateDocument(client: KyInstance, corp: CorpConfig, params: z.infer<typeof documentUpdateSchema>) { + const { documentId, dryRun, confirm: _confirm, allowEmpty, baseline, ...rawPatch } = params + const patch = Object.fromEntries(Object.entries(rawPatch).filter(([, value]) => value !== undefined)) as Partial<DocumentAttributes> + if (!Object.keys(patch).length) throw usageError("documents update requires at least one changed field") + validateContent(patch.content, allowEmpty) + requireConfirmation("update", params) + const source = documentSource(corp, documentId) + if (baseline && JSON.stringify(baseline.source) !== JSON.stringify(source)) throw validationError("Document baseline belongs to a different enterprise, service, or document") + const before = await api.getApprovalDocument(client, documentId) + const changedFields = changes(before, patch) + if (baseline && changedFields.length) { + const hashes = documentFieldHashes(before) + const conflicts = DOCUMENT_EDITABLE_FIELDS.filter(field => patch[field] !== undefined && baseline.fieldHashes[field] !== hashes[field]) + if (conflicts.length) throw new DocumentMutationError({ source, code: "DOCUMENT_CONFLICT", preview: Boolean(dryRun), executed: false, verified: false, conflictingFields: conflicts }, "Document changed since export; export and review again.", 1, nextRead(corp, documentId)) + } + if (dryRun) return preview(corp, documentId, before, patch, changedFields, Boolean(baseline)) + if (!changedFields.length) return { source, preview: false, executed: false, changed: false, changedFields, verified: true, baselineAvailable: Boolean(baseline), contentHash: documentHash(before.content) } + const snapshot = saveDocumentSnapshot(corp, before, "update") + try { await api.updateApprovalDocument(client, documentId, patch) } catch (error) { + return failedWrite(error, { source, preview: false, operation: "update", baselineAvailable: Boolean(baseline), ...snapshot }, nextRead(corp, documentId)) + } + return verifyDocument(client, corp, documentId, { ...before, ...patch }, changedFields, Boolean(baseline), snapshot) +} + +export async function deleteDocument(client: KyInstance, corp: CorpConfig, params: z.infer<typeof documentDeleteSchema>) { + requireConfirmation("delete", params) + const before = await api.getApprovalDocument(client, params.documentId) + const source = documentSource(corp, params.documentId) + if (params.dryRun) return { source, preview: true, executed: false, changesDiff: { before, after: null } } + const snapshot = saveDocumentSnapshot(corp, before, "delete") + try { await api.deleteApprovalDocument(client, params.documentId) } catch (error) { + return failedWrite(error, { source, preview: false, operation: "delete", ...snapshot }, nextRead(corp, params.documentId)) + } + return { source, preview: false, executed: true, deleted: true, ...snapshot } +} diff --git a/src/server.test.ts b/src/server.test.ts index 25d38f6..a473e09 100644 --- a/src/server.test.ts +++ b/src/server.test.ts @@ -141,6 +141,8 @@ describe("seal-use MCP server", () => { "seal-use rules push", "seal-use rules create --description test --scope all", "seal-use documents create --title t --purpose p --content c", + "seal-use documents update doc-1 --content c --dry-run --yes", + "seal-use documents delete doc-1 --dry-run", "seal-use simulation create --mode hosecloud", "seal-use deploy hosecloud sync sign-key", "seal-use users reset-password corp-a:u1", @@ -156,7 +158,15 @@ describe("seal-use MCP server", () => { // Read-only commands must get past the policy; `version` is a top-level command with no // registry row, and `corp` is an area alias the CLI dispatches as `corps`. - for (const command of ["seal-use version", "seal-use corps list", "seal-use corp list", "seal-use documents list --corp corp-a", "seal-use expenses --sn SN-FIXTURE --corp missing-fixture-corp"]) { + for (const command of [ + "seal-use version", + "seal-use corps list", + "seal-use corp list", + "seal-use documents list --corp corp-a", + "seal-use documents list --summary --corp corp-a", + "seal-use documents get doc-1 --out ./body.txt --corp corp-a", + "seal-use expenses --sn SN-FIXTURE --corp missing-fixture-corp" + ]) { const allowed = await callRead(command); expect({ command, refusedByPolicy: allowed.text.includes("only runs read-only commands") }).toEqual({ command, From a2963c736c6287b5721644ff625dfca0cb159805 Mon Sep 17 00:00:00 2001 From: yunyingk <haoda2195176187@gmail.com> Date: Tue, 20 Oct 2026 17:40:06 +0800 Subject: [PATCH 2/2] Preserve auth exit codes when document readback fails --- src/cli/commands/documents.test.ts | 19 +++++++++++++++++-- src/domains/seal/documents/service.test.ts | 21 ++++++++++++++++++++- src/domains/seal/documents/service.ts | 5 +++-- 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/src/cli/commands/documents.test.ts b/src/cli/commands/documents.test.ts index 60a6c3f..f9f436b 100644 --- a/src/cli/commands/documents.test.ts +++ b/src/cli/commands/documents.test.ts @@ -11,6 +11,7 @@ let dir: string let document = { id: "doc-1", title: "Fixture policy", purpose: "Testing", content: "Line one\\\r\n| a \\| b |", status: "published", enabled: true, scenarios: ["audit"], tags: ["test"] } let requests: Array<{ method: string; path: string; query: string; body?: Record<string, unknown> }> let failReadback: boolean +let failReadbackStatus: number const original = structuredClone(document) beforeEach(() => { @@ -29,14 +30,23 @@ beforeEach(() => { document = structuredClone(original) requests = [] failReadback = false + failReadbackStatus = 400 + let writeCount = 0 + let readbackWrites = 0 globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const request = new Request(input, init) const url = new URL(request.url) const method = request.method const body = ["PATCH", "POST"].includes(method) ? JSON.parse(await request.text()) as Record<string, unknown> : undefined requests.push({ method, path: url.pathname, query: url.searchParams.toString(), body }) - if (failReadback && method === "GET" && requests.some(item => item.method === "PATCH")) return Response.json({ error: "offline" }, { status: 400 }) - if (method === "PATCH") document = { ...document, ...(body?.attributes as object) } + if (failReadback && method === "GET" && writeCount > readbackWrites) { + readbackWrites = writeCount + return Response.json({ error: "offline" }, { status: failReadbackStatus }) + } + if (method === "PATCH") { + writeCount++ + document = { ...document, ...(body?.attributes as object) } + } if (method === "POST") document = { ...document, ...body } return Response.json({ data: url.pathname.endsWith("/articles") && method === "GET" ? { articles: [document], total: 115 } : document }) }) as typeof fetch @@ -129,6 +139,11 @@ describe("documents CLI", () => { expect(uncertain.exitCode).toBe(1) expect(JSON.parse(uncertain.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false }) expect(uncertain.stderr).toContain("Next action:") + + failReadbackStatus = 401 + const authFailed = await cli("update", "doc-1", "--content", "newer", "--yes") + expect(authFailed.exitCode).toBe(11) + expect(JSON.parse(authFailed.stdout)).toMatchObject({ code: "DOCUMENT_READBACK_FAILED", executed: true, verified: false }) }) test("unsupported format and path/input conflicts fail before requests or file changes", async () => { diff --git a/src/domains/seal/documents/service.test.ts b/src/domains/seal/documents/service.test.ts index daf38a5..b805ff4 100644 --- a/src/domains/seal/documents/service.test.ts +++ b/src/domains/seal/documents/service.test.ts @@ -20,6 +20,7 @@ function fixture() { let reads = 0 let failWrite = false let failReadback = false + let readbackError: unknown = undefined let corruptReadback = false const client = { get(path: string) { @@ -27,7 +28,7 @@ function fixture() { return { json: async () => { if (path === "api/v1/knowledge/articles") return { data: { articles: [document], total: 115 } } reads++ - if (failReadback && reads > 1) throw new Error("readback unavailable") + if (failReadback && reads > 1) throw (readbackError ?? new Error("readback unavailable")) return { data: structuredClone(corruptReadback && reads > 1 ? { ...document, status: "draft" } : document) } } } }, @@ -49,6 +50,7 @@ function fixture() { set document(value) { document = value }, set failWrite(value: boolean) { failWrite = value }, set failReadback(value: boolean) { failReadback = value }, + set readbackError(value: unknown) { readbackError = value }, set corruptReadback(value: boolean) { corruptReadback = value }, writes: () => requests.filter(request => request.method !== "GET") } @@ -234,6 +236,23 @@ describe("document mutations", () => { }) } + test("readback authentication failure retains exit code 11", async () => { + const f = fixture() + f.failReadback = true + f.readbackError = Object.assign(new Error("unauthorized"), { response: { status: 401 } }) + try { + await updateDocument(f.client, corp, { documentId: "doc-1", content: "new", confirm: true }) + throw new Error("expected rejection") + } catch (error) { + expect(error).toBeInstanceOf(DocumentMutationError) + const err = error as DocumentMutationError + expect(err.exitCode).toBe(11) + expect(err.payload.code).toBe("DOCUMENT_READBACK_FAILED") + expect(err.payload.executed).toBe(true) + expect(err.payload.verified).toBe(false) + } + }) + test("create and delete also disable transport retries", async () => { const f = fixture() expect(await createDocument(f.client, corp, { title: "new", purpose: "policy", content: "body", confirm: true })).toMatchObject({ verified: true }) diff --git a/src/domains/seal/documents/service.ts b/src/domains/seal/documents/service.ts index ad09075..fffa821 100644 --- a/src/domains/seal/documents/service.ts +++ b/src/domains/seal/documents/service.ts @@ -87,8 +87,9 @@ export async function createDocument(client: KyInstance, corp: CorpConfig, param async function verifyDocument(client: KyInstance, corp: CorpConfig, id: string, expected: Partial<DocumentAttributes>, changedFields: DocumentField[], baselineAvailable: boolean, snapshot?: { snapshotId: string; snapshotFile: string }) { const receipt = { source: documentSource(corp, id), preview: false, executed: true, changed: true, changedFields, baselineAvailable, ...snapshot } let after: ApprovalDocument - try { after = await api.getApprovalDocument(client, id) } catch { - throw new DocumentMutationError({ ...receipt, code: "DOCUMENT_READBACK_FAILED", verified: false }, "Document was written, but readback failed.", 1, nextRead(corp, id)) + try { after = await api.getApprovalDocument(client, id) } catch (error) { + const auth = classifyCliError(error).exitCode === 11 + throw new DocumentMutationError({ ...receipt, code: "DOCUMENT_READBACK_FAILED", verified: false }, "Document was written, but readback failed.", auth ? 11 : 1, nextRead(corp, id)) } const mismatchedFields = changes(after, expected) if (mismatchedFields.length) throw new DocumentMutationError({ ...receipt, code: "DOCUMENT_VERIFICATION_FAILED", verified: false, mismatchedFields }, "Document readback differs from the expected state.", 1, nextRead(corp, id))