import { describe, expect, test } from "bun:test"; import { builtinRuleLinter } from "./builtin.js"; import { loadRuleLinter } from "./loader.js"; import { lintRuleBatch, lintSingleRule } from "./service.js"; import { writeFileSync, unlinkSync, mkdirSync, existsSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; describe("Rule Linter", () => { test("builtinRuleLinter detects short text, vague words, and hanging exceptions", () => { // 1. 过短文本 const shortResult = builtinRuleLinter({ description: "测试" }); expect(shortResult.passed).toBe(false); expect(shortResult.issues.some((i) => i.code === "TOO_SHORT")).toBe(true); // 2. 主观模糊词 const vagueResult = builtinRuleLinter({ description: "原则上差旅住宿费尽量控制在500元以内" }); expect(vagueResult.passed).toBe(false); expect(vagueResult.issues.filter((i) => i.code === "VAGUE_WORD").length).toBe(2); expect(vagueResult.score).toBeLessThanOrEqual(50); // 3. 悬空例外条款(无证据说明) const exceptionResult = builtinRuleLinter({ description: "差旅住宿费单日不得超过500元,特殊情况除外" }); expect(exceptionResult.issues.some((i) => i.code === "HANGING_EXCEPTION")).toBe(true); // 4. 完美高质量规则 const cleanResult = builtinRuleLinter({ description: "差旅住宿费每日不可超过500元。若因特殊情况超标,必须在【单据备注】中说明原因并在【附件】中提供总监审批邮件截图。" }); expect(cleanResult.passed).toBe(true); expect(cleanResult.score).toBe(100); expect(cleanResult.issues.length).toBe(0); }); test("loadRuleLinter returns builtin linter for default or non-existent files safely", async () => { const builtinLoaded = await loadRuleLinter("builtin"); expect(builtinLoaded.type).toBe("builtin"); // 不存在的文件安全降级至 builtin,不抛错崩溃 const nonExistent = await loadRuleLinter("/tmp/non-existent-linter-xyz.ts"); expect(nonExistent.type).toBe("builtin"); const res = await nonExistent.linter({ description: "原则上不能超标" }); expect(res.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true); }); test("loadRuleLinter safely executes custom TS/JS linter and catches runtime exceptions", async () => { const testDir = join(tmpdir(), "seal-use-linter-test"); if (!existsSync(testDir)) mkdirSync(testDir, { recursive: true }); // 1. 有效的自定义校验器 const customTsPath = join(testDir, "custom-valid.ts"); writeFileSync( customTsPath, `export default function customLinter(rule) { if (rule.description.includes("商务舱")) { return { score: 40, passed: false, issues: [{ level: "error", code: "CUSTOM_FLIGHT", message: "禁止报销商务舱" }] }; } return { score: 100, passed: true, issues: [] }; }` ); const loadedCustom = await loadRuleLinter(customTsPath); expect(loadedCustom.type).toBe("custom"); const customRes = await loadedCustom.linter({ description: "报销商务舱机票一张" }); expect(customRes.passed).toBe(false); expect(customRes.issues[0]?.code).toBe("CUSTOM_FLIGHT"); // 2. 运行时崩溃的自定义校验器(安全捕获并降级) const crashingTsPath = join(testDir, "custom-crash.ts"); writeFileSync( customTsPath, `export default function crashLinter() { throw new Error("Intentional Crash"); }` ); const loadedCrash = await loadRuleLinter(crashingTsPath); const crashFallbackRes = await loadedCrash.linter({ description: "原则上不能超标" }); // 应当安全降级运行 builtin,返回模糊词拦截结果 expect(crashFallbackRes.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true); // 清理临时文件 try { unlinkSync(customTsPath); } catch {} }); test("lintRuleBatch computes overall summary, score average, and filters by level", async () => { const loaded = await loadRuleLinter("builtin"); const rules = [ { id: "1", code: "#0001", name: "清晰规则", description: "差旅住宿费每日不可超过500元,超标需在【单据备注】中说明并附【审批截图】。" }, { id: "2", code: "#0002", name: "模糊规则", description: "原则上差旅住宿费尽量控制在500元以内" }, { id: "3", code: "#0003", name: "悬空例外", description: "差旅住宿费单日不得超过500元,特殊情况除外" } ]; const batchRes = await lintRuleBatch(rules, loaded, undefined, { level: "all" }); expect(batchRes.totalRules).toBe(3); expect(batchRes.healthyCount).toBe(1); expect(batchRes.issueCount).toBe(2); expect(batchRes.overallScore).toBeLessThan(100); expect(batchRes.passed).toBe(false); // 摘要模式:只返回有问题的规则 const summaryRes = await lintRuleBatch(rules, loaded, undefined, { summary: true }); expect(summaryRes.issues.length).toBe(2); expect(summaryRes.issues.map((i) => i.ruleCode)).toEqual(["#0002", "#0003"]); }); test("strictRuleLinter enforces higher standards for quantitative constraints, approvers, and exceptions", async () => { const { strictRuleLinter } = await import("./strict.js"); // 1. 少于 10 字告警 const shortRes = strictRuleLinter({ description: "不能报销打车费" }); expect(shortRes.issues.some((i) => i.code === "SHORT_DESCRIPTION")).toBe(true); // 2. 严格主观模糊词 const vagueRes = strictRuleLinter({ description: "出差打车费用差不多就行,必要时可报销" }); expect(vagueRes.issues.some((i) => i.code === "VAGUE_WORD" && i.snippet === "差不多")).toBe(true); expect(vagueRes.issues.some((i) => i.code === "VAGUE_WORD" && i.snippet === "必要时")).toBe(true); // 3. 严格例外条款直接判定为 Error const exceptionRes = strictRuleLinter({ description: "差旅住宿单日不超过500元,特殊情况除外" }); const hanging = exceptionRes.issues.find((i) => i.code === "HANGING_EXCEPTION"); expect(hanging).toBeDefined(); expect(hanging?.level).toBe("error"); // 4. 缺少量化指标或刚性边界词 const noQuantRes = strictRuleLinter({ description: "出差应选择舒适快捷的交通工具前往" }); expect(noQuantRes.issues.some((i) => i.code === "LACKS_EXPLICIT_CONSTRAINT")).toBe(true); // 5. 模糊审批人角色 const vagueApproverRes = strictRuleLinter({ description: "差旅住宿单日不超过500元,经领导同意可上浮并在【单据备注】说明" }); expect(vagueApproverRes.issues.some((i) => i.code === "AMBIGUOUS_APPROVER")).toBe(true); // 6. 严格合格规则 (满分 100) const strictPassRes = strictRuleLinter({ description: "差旅住宿费每人每日上限不得超过500元。若遇旺季超标,需经【部门总监】审批邮件同意,并在【单据备注】中说明原因且在【附件】中上传截图。" }); expect(strictPassRes.passed).toBe(true); expect(strictPassRes.score).toBe(100); expect(strictPassRes.issues.length).toBe(0); }); test("syncOfficialLinters writes plaintext files, overwrites modifications, and prunes rogue files", async () => { const { syncOfficialLinters } = await import("./loader.js"); const { readFileSync } = await import("node:fs"); const testOfficialDir = join(tmpdir(), `seal-official-linter-test-${Date.now()}`); try { // 1. 首次同步:生成 builtin.ts 与 strict.ts 明文文件 const firstSync = syncOfficialLinters(testOfficialDir); expect(firstSync.synced.sort()).toEqual(["builtin.ts", "strict.ts"]); expect(existsSync(join(testOfficialDir, "builtin.ts"))).toBe(true); expect(existsSync(join(testOfficialDir, "strict.ts"))).toBe(true); const builtinPlaintext = readFileSync(join(testOfficialDir, "builtin.ts"), "utf8"); expect(builtinPlaintext).toContain("Seal 官方标准规则校验器"); expect(builtinPlaintext).toContain("export function lintRule"); const strictPlaintext = readFileSync(join(testOfficialDir, "strict.ts"), "utf8"); expect(strictPlaintext).toContain("Seal 官方严格风控规则校验器"); expect(strictPlaintext).toContain("STRICT_QUANTITATIVE_INDICATORS"); // 2. 模拟客户私自篡改 official/builtin.ts writeFileSync(join(testOfficialDir, "builtin.ts"), "// HACKED CONTENT", "utf8"); expect(readFileSync(join(testOfficialDir, "builtin.ts"), "utf8")).toBe("// HACKED CONTENT"); // 3. 模拟客户在 official/ 下私自创建了多余的文件和子目录 writeFileSync(join(testOfficialDir, "my-custom-rule.ts"), "// Should be deleted", "utf8"); writeFileSync(join(testOfficialDir, "random.txt"), "garbage", "utf8"); mkdirSync(join(testOfficialDir, "extra-subfolder"), { recursive: true }); // 4. 再次执行同步:篡改的内容必须被官方重写,多余文件和子目录必须全部被干掉 const secondSync = syncOfficialLinters(testOfficialDir); expect(secondSync.synced.sort()).toEqual(["builtin.ts", "strict.ts"]); expect(secondSync.pruned.sort()).toEqual(["extra-subfolder", "my-custom-rule.ts", "random.txt"]); // 验证官方文件已恢复明文 const restoredContent = readFileSync(join(testOfficialDir, "builtin.ts"), "utf8"); expect(restoredContent).toContain("Seal 官方标准规则校验器"); expect(restoredContent).not.toContain("// HACKED CONTENT"); // 验证多余文件已被清理干掉 expect(existsSync(join(testOfficialDir, "my-custom-rule.ts"))).toBe(false); expect(existsSync(join(testOfficialDir, "random.txt"))).toBe(false); expect(existsSync(join(testOfficialDir, "extra-subfolder"))).toBe(false); } finally { const { rmSync } = await import("node:fs"); rmSync(testOfficialDir, { recursive: true, force: true }); } }); test("loadRuleLinter loads strict linter and isolates official directory from custom linters", async () => { const loadedStrict = await loadRuleLinter("strict"); expect(loadedStrict.name).toBe("strict"); expect(loadedStrict.type).toBe("official"); const res = await loadedStrict.linter({ description: "原则上差旅住宿费尽量控制在500元以内" }); expect(res.passed).toBe(false); expect(res.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true); }); });