From f2738ee4a32e9e533492172c8f6ba0386920af80 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 11:49:50 +0800 Subject: [PATCH] Add one-shot run diagnosis and agent-feedback hardening --- skills/seal-use/SKILL.md | 10 + src/cli/commands/approval-runs.ts | 20 ++ src/cli/commands/corps/sync.ts | 9 +- src/cli/help.ts | 9 + src/cli/read-only.ts | 1 + src/core/config/loader.test.ts | 6 +- src/core/config/types.test.ts | 4 +- src/core/config/types.ts | 4 +- src/core/doctor/tenant-diagnose.test.ts | 72 ++++++++ src/domains/seal/doctor/tenant-diagnose.ts | 71 +++++-- src/domains/seal/tools.test.ts | 205 ++++++++++++++++++++- src/domains/seal/tools/approval-runs.ts | 99 +++++++++- src/domains/seal/tools/helpers.ts | 44 +++++ src/domains/seal/tools/index.ts | 1 + src/domains/seal/tools/rules.ts | 77 ++++++-- 15 files changed, 583 insertions(+), 49 deletions(-) diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index e718c8d..511c761 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -100,3 +100,13 @@ Hose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`appr | 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 | 冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。 + +## 客诉/单据诊断一步聚合 + +客诉定界、单据排查优先一次调用完成,不要串行敲 4~5 个命令: + +```bash +seal-use approval-runs diagnose --sn <单号> --corp +``` + +一次返回单据摘要、AI 判定结果、引用规则、判定当时的规则版本快照(含被引规则的快照内容)与 Langfuse trace 指针;需要完整 result 原文加 `--full`,需要按 recordId 定位则直接传 ``。只有诊断结果不够、需要更细颗粒时,再拆用 `pick` / `get --summary` / `cited-rules` / `rules version`。 diff --git a/src/cli/commands/approval-runs.ts b/src/cli/commands/approval-runs.ts index 42ea0b5..1d0b4bd 100644 --- a/src/cli/commands/approval-runs.ts +++ b/src/cli/commands/approval-runs.ts @@ -211,6 +211,26 @@ export async function handleApprovalRunsCommand( return; } + if (action === "diagnose") { + const recordId = args.command[2]; + const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]); + if (!recordId && !sn) { + throw new Error("Usage: seal-use approval-runs diagnose |--sn [--full] [--corp ]"); + } + await runTool( + "seal_approval_run_diagnose", + client, + corp, + { + recordId, + sn, + full: booleanOption(args.options.full) === true + }, + outputOptions(args.options) + ); + return; + } + if (action === "attachments") { const subAction = args.command[2]; if (subAction === "download") { diff --git a/src/cli/commands/corps/sync.ts b/src/cli/commands/corps/sync.ts index db65506..cb0a94c 100644 --- a/src/cli/commands/corps/sync.ts +++ b/src/cli/commands/corps/sync.ts @@ -39,11 +39,14 @@ export async function handleCorpSync( } if (!confirmed) { const preview = await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: false }) as { - rulesPlan: { sourceDraftRuleCount: number }; - documentsPlan: { sourceDocumentCount: number }; + rulesPlan: { sourceDraftRuleCount: number; targetExistingDraftRuleCount: number }; + documentsPlan: { sourceDocumentCount: number; toDeleteCount: number }; }; throw confirmationRequired( - `Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences, ${preview.rulesPlan.sourceDraftRuleCount} draft rules, and ${preview.documentsPlan.sourceDocumentCount} knowledge documents from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`, + `Refusing to sync into test enterprise '${testCorp.name}' (${testCorp.id}) without --yes. ` + + `This is DESTRUCTIVE for the test tenant: it will DELETE its ${preview.rulesPlan.targetExistingDraftRuleCount} existing draft rules and rebuild them from ${preview.rulesPlan.sourceDraftRuleCount} production draft rules, ` + + `DELETE ${preview.documentsPlan.toDeleteCount} existing knowledge documents and re-import ${preview.documentsPlan.sourceDocumentCount} documents from production, overwrite test preferences, and publish a new rules version. ` + + `Run with --dry-run first to review the exact documents that will be deleted.`, `seal-use corps sync-test ${prodCorp.id} --yes` ); } diff --git a/src/cli/help.ts b/src/cli/help.ts index 48dd1f7..4b9a211 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -521,6 +521,15 @@ export const HELP_REGISTRY: AreaHelp[] = [ summary: "Inspect rules cited by AI in an approval decision", usage: ["seal-use approval-runs cited-rules [--corp ]"] }, + { + name: "diagnose", + summary: "One-shot complaint/document diagnosis: document summary, AI decision, cited rules, rule version snapshot, and Langfuse trace pointer in a single call", + usage: ["seal-use approval-runs diagnose |--sn [--full] [--corp ]"], + options: [ + { flag: "--sn ", description: "Target the run by Hose document SN instead of record ID" }, + { flag: "--full", description: "Include the full raw AI result payload instead of the summary" } + ] + }, { name: "document-summary", summary: "Inspect parsed source document summary", diff --git a/src/cli/read-only.ts b/src/cli/read-only.ts index a5e17e9..0ba16ca 100644 --- a/src/cli/read-only.ts +++ b/src/cli/read-only.ts @@ -44,6 +44,7 @@ const READ_ONLY_COMMANDS: Record = { "bridge", "get", "cited-rules", + "diagnose", "document-summary", "attachments", "result", diff --git a/src/core/config/loader.test.ts b/src/core/config/loader.test.ts index b2d4f62..12267fc 100644 --- a/src/core/config/loader.test.ts +++ b/src/core/config/loader.test.ts @@ -124,7 +124,7 @@ describe("loadCorpConfigs", () => { expect(loadGlobalConfig()).toEqual({ stateful: false, lint: { - enabled: false, + enabled: true, activeLinter: "builtin", minScore: 0 } @@ -140,7 +140,7 @@ describe("loadCorpConfigs", () => { defaultCorpId: "corp-a", testEnterprisesDir: "/tmp/test-corps", lint: { - enabled: false, + enabled: true, activeLinter: "builtin", minScore: 0 } @@ -151,7 +151,7 @@ describe("loadCorpConfigs", () => { defaultCorpId: "corp-a", testEnterprisesDir: "/tmp/test-corps", lint: { - enabled: false, + enabled: true, activeLinter: "builtin", minScore: 0 } diff --git a/src/core/config/types.test.ts b/src/core/config/types.test.ts index 4f4769a..d1c6cb9 100644 --- a/src/core/config/types.test.ts +++ b/src/core/config/types.test.ts @@ -203,7 +203,7 @@ describe("GlobalConfigSchema", () => { expect(GlobalConfigSchema.parse({})).toEqual({ stateful: false, lint: { - enabled: false, + enabled: true, activeLinter: "builtin", minScore: 0 } @@ -218,7 +218,7 @@ describe("GlobalConfigSchema", () => { stateful: true, defaultCorpId: "corp-a", lint: { - enabled: false, + enabled: true, activeLinter: "builtin", minScore: 0 } diff --git a/src/core/config/types.ts b/src/core/config/types.ts index 98fcfdb..2f19dac 100644 --- a/src/core/config/types.ts +++ b/src/core/config/types.ts @@ -121,11 +121,11 @@ export const CorpConfigSchema = z.object({ }); export const GlobalLintConfigSchema = z.object({ - enabled: z.boolean().default(false), + enabled: z.boolean().default(true), activeLinter: z.string().default("builtin"), minScore: z.number().min(0).max(100).default(0) }).default({ - enabled: false, + enabled: true, activeLinter: "builtin", minScore: 0 }); diff --git a/src/core/doctor/tenant-diagnose.test.ts b/src/core/doctor/tenant-diagnose.test.ts index ffab0f0..d998952 100644 --- a/src/core/doctor/tenant-diagnose.test.ts +++ b/src/core/doctor/tenant-diagnose.test.ts @@ -96,12 +96,80 @@ describe("tenant-diagnose", () => { expect(result.rules.activeCount).toBe(1); expect(result.webhooks.hasReplayChannel).toBe(true); expect(result.summary.failedChecks).toBe(0); + expect(result.corp.boundCorpId).toBe("prod-corp"); + expect(result.corp.boundCorpRole).toBe("prodParent"); const dashboard = formatTenantDoctorDashboard(result); expect(dashboard).toContain("HEALTHY"); expect(dashboard).toContain("5000"); }); + test("reports an unknown quota instead of degrading after transient billing timeouts", async () => { + const base = createMockClient({}); + let billingCalls = 0; + const flakyClient = { + get: async (url: string) => { + if (url === "api/v1/billing/status") { + billingCalls += 1; + throw new Error("Request timed out after 15000ms"); + } + return base.get(url); + } + } as any; + + const testCorp: CorpConfig = { + id: "test-corp", + name: "园测企业", + environment: "test", + prodCorpId: "prod-corp", + source: { type: "seal" }, + seal: { url: "https://test.sealai.cc" } + } as any; + + const result = await diagnoseTenantContract(flakyClient, testCorp); + + expect(billingCalls).toBe(2); + expect(result.verdict).toBe("HEALTHY"); + expect(result.quota.status).toBe("unknown"); + expect(result.summary.unknownChecks).toBe(1); + const billingCheck = result.checks.find((check) => check.id === "billing_quota"); + expect(billingCheck?.status).toBe("unknown"); + + const dashboard = formatTenantDoctorDashboard(result); + expect(dashboard).toContain("未知"); + }); + + test("recovers a transient billing timeout via the built-in retry", async () => { + const base = createMockClient({}); + let billingCalls = 0; + const flakyClient = { + get: async (url: string) => { + if (url === "api/v1/billing/status") { + billingCalls += 1; + if (billingCalls === 1) { + throw new Error("fetch failed: socket hang up"); + } + } + return base.get(url); + } + } as any; + + const testCorp: CorpConfig = { + id: "test-corp", + name: "重试恢复企业", + environment: "test", + prodCorpId: "prod-corp", + source: { type: "seal" }, + seal: { url: "https://test.sealai.cc" } + } as any; + + const result = await diagnoseTenantContract(flakyClient, testCorp); + + expect(billingCalls).toBe(2); + expect(result.verdict).toBe("HEALTHY"); + expect(result.quota.status).toBe("sufficient"); + }); + test("flags warning for low quota and unbound prod corp", async () => { const mockClient = createMockClient({ billing: { @@ -128,6 +196,10 @@ describe("tenant-diagnose", () => { expect(result.quota.status).toBe("low"); expect(result.rules.totalCount).toBe(0); expect(result.summary.warningChecks).toBeGreaterThan(0); + // An unbound corp must not advertise a binding role. + expect(result.corp.boundCorpId).toBeUndefined(); + expect(result.corp.boundCorpRole).toBeUndefined(); + expect(result.corp.boundCorpRoleDescription).toBeUndefined(); }); test("flags fail when quota is exhausted or auth fails", async () => { diff --git a/src/domains/seal/doctor/tenant-diagnose.ts b/src/domains/seal/doctor/tenant-diagnose.ts index c217eac..552b557 100644 --- a/src/domains/seal/doctor/tenant-diagnose.ts +++ b/src/domains/seal/doctor/tenant-diagnose.ts @@ -6,7 +6,8 @@ import * as api from "../api.js"; export interface TenantHealthCheck { id: string; name: string; - status: "pass" | "warn" | "fail"; + /** "unknown" means a transient probe failure (e.g. one-off timeout after a retry) — it must not degrade the verdict. */ + status: "pass" | "warn" | "fail" | "unknown"; summary: string; details: Record; recommendation?: string; @@ -30,6 +31,7 @@ export interface TenantDoctorDiagnosis { passedChecks: number; warningChecks: number; failedChecks: number; + unknownChecks: number; }; checks: TenantHealthCheck[]; quota: { @@ -37,7 +39,7 @@ export interface TenantDoctorDiagnosis { balance: number; deductionAmount: number; estimatedRuns: number; - status: "sufficient" | "low" | "exhausted"; + status: "sufficient" | "low" | "exhausted" | "unknown"; }; rules: { totalCount: number; @@ -59,13 +61,34 @@ export async function diagnoseTenantContract( const checks: TenantHealthCheck[] = []; const environment = corp.environment === "test" ? "test" : "production"; const boundCorpId = environment === "test" ? corp.prodCorpId : corp.testCorpId; - const boundCorpRole = environment === "test" ? "prodParent" : "testTarget"; + // Role labels only make sense for an existing binding; emitting them for an unbound corp reads as a phantom binding. + const boundCorpRole = boundCorpId + ? environment === "test" + ? "prodParent" as const + : "testTarget" as const + : undefined; const boundCorpRoleDescription = boundCorpId ? environment === "test" ? "已绑定生产母企业 (上游配置与样本源)" : "已绑定测试靶场 (下游隔离演练环境)" : undefined; + // Transient network failures (timeouts, dropped sockets) get one retry before the check is + // reported; if the retry also fails the check reports "unknown" instead of degrading the verdict. + const isTransientNetworkError = (err: unknown): boolean => { + const text = `${err instanceof Error ? err.name : ""} ${err instanceof Error ? err.message : String(err)}`.toLowerCase(); + return /timeout|timed out|abort|fetch failed|network|econn|etimedout|eai_again|socket/.test(text); + }; + const probeWithRetry = async (probe: () => Promise): Promise => { + try { + return await probe(); + } catch (err) { + if (!isTransientNetworkError(err)) throw err; + await new Promise((resolve) => setTimeout(resolve, 400)); + return probe(); + } + }; + // 1. Auth & Admin Probe let userDetail: any = null; let tenantDetail: any = null; @@ -125,7 +148,7 @@ export async function diagnoseTenantContract( balance: 0, deductionAmount: 120, estimatedRuns: 0, - status: "exhausted" as "sufficient" | "low" | "exhausted" + status: "exhausted" as "sufficient" | "low" | "exhausted" | "unknown" }; let ruleQuota = { @@ -134,7 +157,7 @@ export async function diagnoseTenantContract( }; try { - const billing = await api.getBillingStatus(client); + const billing = await probeWithRetry(() => api.getBillingStatus(client)); const features = Array.isArray(billing.features) ? billing.features : []; // Find AI Approval feature @@ -197,12 +220,19 @@ export async function diagnoseTenantContract( ruleQuota.remaining = typeof ruleFeat.remaining === "number" ? ruleFeat.remaining : 0; } } catch (err) { + const transient = isTransientNetworkError(err); + if (transient) { + quotaInfo.status = "unknown"; + } checks.push({ id: "billing_quota", name: "AI 审批额度余量", - status: "warn", - summary: `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`, - details: { error: String(err) } + status: transient ? "unknown" : "warn", + summary: transient + ? "额度探测超时(已重试仍未达),额度未知——不判定为降级,其余检查不受影响" + : `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`, + details: { error: String(err), retried: transient }, + recommendation: transient ? `稍后重跑 seal-use doctor tenant --corp ${corp.id} 确认额度` : undefined }); } @@ -263,7 +293,7 @@ export async function diagnoseTenantContract( }; try { - const integrations = await api.listWebhookIntegrations(client); + const integrations = await probeWithRetry(() => api.listWebhookIntegrations(client)); webhooksSummary.integrationCount = integrations.length; const replayChannel = integrations.find( @@ -294,12 +324,16 @@ export async function diagnoseTenantContract( }); } } catch (err) { + const transient = isTransientNetworkError(err); checks.push({ id: "webhook_integrations", name: "单据推送 Webhook 通道", - status: "warn", - summary: `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`, - details: { error: String(err) } + status: transient ? "unknown" : "warn", + summary: transient + ? "检测 Webhook 通道超时(已重试仍未达),通道状态未知——不判定为降级" + : `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`, + details: { error: String(err), retried: transient }, + recommendation: transient ? `稍后重跑 seal-use doctor tenant --corp ${corp.id} 确认通道状态` : undefined }); } @@ -344,10 +378,11 @@ export async function diagnoseTenantContract( } } - // Compute overall verdict + // Compute overall verdict; "unknown" checks (transient probe failures after retry) never degrade it. const failedChecks = checks.filter((c) => c.status === "fail").length; const warningChecks = checks.filter((c) => c.status === "warn").length; const passedChecks = checks.filter((c) => c.status === "pass").length; + const unknownChecks = checks.filter((c) => c.status === "unknown").length; let verdict: "HEALTHY" | "DEGRADED" | "BLOCKED" = "HEALTHY"; if (failedChecks > 0) { @@ -373,7 +408,8 @@ export async function diagnoseTenantContract( totalChecks: checks.length, passedChecks, warningChecks, - failedChecks + failedChecks, + unknownChecks }, checks, quota: quotaInfo, @@ -400,8 +436,11 @@ export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): s ]; // Core metrics overview + const quotaLine = quota.status === "unknown" + ? ` AI 审批余量: 未知(探测超时,不判定降级)` + : ` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔)`; lines.push( - ` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔) | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}` + `${quotaLine} | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}` ); if (corp.boundCorpId) { lines.push(` 配对关系: ${corp.environment === "test" ? "来源生产母企业" : "绑定的测试靶场"} -> 「${corp.boundCorpId}」`); @@ -409,7 +448,7 @@ export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): s lines.push(" " + "─".repeat(60)); for (const check of checks) { - const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : "✗"; + const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : check.status === "unknown" ? "?" : "✗"; lines.push(` [${icon}] ${check.name}: ${check.summary}`); if (check.recommendation) { lines.push(` 👉 建议: ${check.recommendation}`); diff --git a/src/domains/seal/tools.test.ts b/src/domains/seal/tools.test.ts index 1218edc..ccc7fea 100644 --- a/src/domains/seal/tools.test.ts +++ b/src/domains/seal/tools.test.ts @@ -5,6 +5,8 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { CorpConfig } from "../../core/config/types.js"; +import { CliError } from "../../core/errors.js"; +import { saveRuleMappingSnapshot } from "./rule-mapping.js"; import { buildRulePushPlan, findSealTool, sealTools } from "./tools.js"; type ToolHandler = ( @@ -227,6 +229,115 @@ describe("sealTools", () => { }); }); + test("approval rule get attaches crossEnv mapping when a sync-test snapshot exists", async () => { + const mappingDir = mkdtempSync(join(tmpdir(), "seal-mapping-crossenv-")); + process.env.SEAL_USE_MAPPINGS_DIR = mappingDir; + try { + saveRuleMappingSnapshot({ + syncedAt: "2026-09-30T10:00:00+08:00", + source: { id: "prod-corp", name: "Prod Corp" }, + target: { id: "t-corp-1", name: "Test Corp", publishedVersionNumber: 3, rulesCount: 1 }, + versionMapping: { + sourceProdVersionNumber: 22, + sourceProdVersionName: "Prod v22 · #1", + targetTestVersionNumber: 3, + targetTestVersionName: "Test v3" + }, + ruleMapping: [{ + index: 0, + sourceRuleId: "rule-1", + sourceRuleCode: 29, + targetRuleId: "t-rule-1", + targetRuleCode: "0002", + description: "Must include full invoice detail", + scope: "travel", + strictness: "MUST_FOLLOW" + }] + }); + + const tool = sealTools.find((item) => item.name === "seal_approval_rule_get"); + expect(tool).toBeDefined(); + const handler = tool!.handler as ToolHandler; + const context = { corp: { ...fakeContext().corp, testCorpId: "t-corp-1" } }; + + const draft = await handler(fakeRulesClient(), { code: "29" }, context) as Record; + expect(draft.crossEnv).toMatchObject({ + environment: "test", + code: "0002", + direction: "prodToTest", + syncedAt: "2026-09-30T10:00:00+08:00" + }); + } finally { + delete process.env.SEAL_USE_MAPPINGS_DIR; + rmSync(mappingDir, { recursive: true, force: true }); + } + }); + + test("approval rule update without --if-unchanged leaves concurrency check absent", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_rule_update"); + expect(tool).toBeDefined(); + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeRuleUpdateClient(1780898164536), + { ruleId: "29", description: "当单据金额超过 5000 元时必须提供发票原件与行程证明。" }, + fakeContext() + ) as Record; + expect(result).toMatchObject({ id: "rule-1", code: "0029" }); + }); + + test("approval rule update --if-unchanged rejects when the draft moved on (exit 13)", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_rule_update"); + const handler = tool!.handler as ToolHandler; + try { + await handler( + fakeRuleUpdateClient(1780898164536), + { ruleId: "29", description: "更新后的规则内容", ifUnchanged: "2026-06-08T13:56:03+08:00" }, + fakeContext() + ); + expect.unreachable(); + } catch (err) { + expect((err as CliError).exitCode).toBe(13); + expect((err as Error).message).toContain("草稿并发冲突"); + } + }); + + test("approval rule update --if-unchanged proceeds when the draft is unchanged", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_rule_update"); + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeRuleUpdateClient(1780898164536), + { ruleId: "29", description: "当单据金额超过 5000 元时必须提供发票原件与行程证明。", ifUnchanged: "2026-06-08T13:56:04+08:00" }, + fakeContext() + ) as Record; + expect(result).toMatchObject({ id: "rule-1" }); + }); + + test("seal_approval_run_diagnose aggregates document, result, cited rules, and version snapshot", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_run_diagnose"); + expect(tool).toBeDefined(); + const handler = tool!.handler as ToolHandler; + + const byRecord = await handler(fakeDiagnoseClient(), { recordId: "run-1" }, fakeContext()) as Record; + expect(byRecord.recordId).toBe("run-1"); + expect(byRecord.documentSummary).toBeDefined(); + expect(byRecord.result).toMatchObject({ decision: "驳回" }); + expect(byRecord.citedRules.rules.length).toBeGreaterThan(0); + expect(byRecord.ruleVersion?.version).toMatchObject({ versionNumber: 16 }); + expect(byRecord.ruleVersion?.citedSnapshots).toEqual([{ + code: "rule-38", + description: "Rule 38 published snapshot", + scope: "travel", + strictness: "MUST_FOLLOW" + }]); + expect(byRecord.bridge).toBeDefined(); + expect(byRecord.next.url).toContain("approval-runs url run-1"); + + const bySn = await handler(fakeDiagnoseClient(), { sn: "B26001965" }, fakeContext()) as Record; + expect(bySn.recordId).toBe("run-1"); + + expect(handler(fakeDiagnoseClient(), {}, fakeContext())).rejects.toThrow("sn or recordId is required"); + }); + test("approval rules clear can dry run without deleting", async () => { const tool = sealTools.find((item) => item.name === "seal_approval_rules_clear"); expect(tool).toBeDefined(); @@ -1247,8 +1358,100 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance { } as unknown as KyInstance; } -function fakeRulesClient(): KyInstance { +function fakeRuleUpdateClient(draftUpdatedAt: number): KyInstance { + const draftRule = { + id: "rule-1", + tenantId: "tenant-1", + code: 29, + description: "当单据金额超过 5000 元时必须提供发票原件。", + scope: "travel", + strictness: "MUST_FOLLOW", + status: "active", + createdAt: draftUpdatedAt, + updatedAt: draftUpdatedAt + }; return { + get: (url: string) => ({ + json: async () => ({ + data: url === "api/v1/rules" + ? { hasPendingDeletes: false, rules: [draftRule] } + : draftRule + }) + }), + put: (_url: string, options?: { json?: { description?: string } }) => ({ + json: async () => ({ + data: { + ...draftRule, + description: options?.json?.description ?? draftRule.description, + updatedAt: draftUpdatedAt + 5000 + } + }) + }) + } as unknown as KyInstance; +} + +function fakeDiagnoseClient(): KyInstance { + const runDetail = { + id: "run-1", + status: "completed", + taskMode: "assisted", + sourceDocumentSN: "B26001965", + sourceDocumentId: "doc-source-1", + ruleSetVersionNumber: 16, + document: { + id: "normalized-doc-1", + title: "差旅报销单", + sourceDocumentSN: "B26001965", + fields: [{ label: "金额", value: "100.00" }] + }, + result: { + decision: "驳回", + summary: "费用存在风险", + matchedRules: [{ + runtimeRuleId: "rule-38", + ruleCode: "#0038", + versionNumber: 16, + scope: "travel", + strictness: "MUST_FOLLOW", + appliedAnalysis: "发票信息与报销说明不一致", + checkResult: "failed" + }] + }, + sourceExtendData: { _langfuseTraceId: "trace-1" }, + createdAt: 1780898164536 + }; + return { + get: (url: string) => ({ + json: async () => { + if (url === "api/v1/approvals/run-1") { + return { data: runDetail }; + } + if (url.startsWith("api/v1/approvals")) { + return { data: { total: 1, records: [{ id: "run-1", sourceDocumentSN: "B26001965" }] } }; + } + if (url === "api/v1/rule-set-versions") { + return { + data: [{ + id: "version-16", + versionNumber: 16, + versionName: "v16", + publishedByName: "Tester", + rules: [{ + code: "rule-38", + description: "Rule 38 published snapshot", + scope: "travel", + strictness: "MUST_FOLLOW" + }] + }] + }; + } + throw new Error(`Unhandled diagnose GET url: ${url}`); + } + }) + } as unknown as KyInstance; +} + +function fakeRulesClient(): KyInstance { return { get: (url: string) => ({ json: async () => ({ data: url === "api/v1/rule-set-versions" diff --git a/src/domains/seal/tools/approval-runs.ts b/src/domains/seal/tools/approval-runs.ts index 3ff0b0b..28eede4 100644 --- a/src/domains/seal/tools/approval-runs.ts +++ b/src/domains/seal/tools/approval-runs.ts @@ -40,7 +40,9 @@ const { approvalRunAliases, extractHumanResult, matchesRunLookup, - localDateKey + localDateKey, + resolveRuleVersion, + summarizeRuleVersion } = helpers; export const approvalRunsTools = [ @@ -545,7 +547,9 @@ export const approvalRunsTools = [ sourceDocumentId: record.sourceDocumentId, sourceSystem: record.sourceSystem, missing: { - hoseDocumentUrl: !hoseDocumentUrl ? "sourceExtendData.hosecloudViewUrl is absent from the approval run detail." : undefined + hoseDocumentUrl: !hoseDocumentUrl + ? `该审批运行未回写 hosecloudViewUrl,无法生成合思原单据直达链接;请到合思主系统以单据编号 ${record.sourceDocumentSN ?? record.sourceDocumentId ?? record.id} 检索原件,或检查该企业的 hosecloud 集成回写配置。` + : undefined } }; } @@ -614,6 +618,97 @@ export const approvalRunsTools = [ }; } }, + { + name: "seal_approval_run_diagnose", + description: "一键客诉/单据诊断:按单号 SN 或 recordId 一次聚合单据摘要、AI 判定结果、引用规则、当时的规则版本快照与 Langfuse trace 指针,替代串行调用 pick/get/cited-rules/rules version", + parameters: z.object({ + sn: z.string().optional().describe("合思/易快报单号 (sourceDocumentSN);与 recordId 二选一"), + recordId: z.string().optional().describe("Seal approval run record ID;与 sn 二选一"), + full: z.boolean().optional().describe("为 true 时附带完整 AI result 原文(默认只带摘要)") + }), + handler: async ( + client: KyInstance, + params: { sn?: string; recordId?: string; full?: boolean }, + context: ToolContext + ) => { + if (!params.sn && !params.recordId) { + throw new Error("sn or recordId is required for approval run diagnosis"); + } + let detail: ApprovalRun; + if (params.recordId) { + detail = await api.getApprovalRun(client, params.recordId); + } else { + const { records } = await api.listApprovalRuns(client, { + limit: 50, + search: params.sn, + sourceDocumentSN: params.sn + }); + const matched = records.find((record) => + matchesRunLookup(record, { sourceDocumentSN: params.sn }) + ); + if (!matched) { + throw new Error(`未找到单号为 ${params.sn} 的审批运行记录;可先用 seal-use approval-runs pick --sn ${params.sn} 确认单号`); + } + detail = await api.getApprovalRun(client, matched.id); + } + + const documentSummary = summarizeApprovalRunDocument(detail); + const resultSummary = summarizeApprovalRunResult(detail); + const citedRules = extractCitedRules(detail); + + let ruleVersion: { + version: ReturnType; + citedSnapshots: Array>; + } | undefined; + if (detail.ruleSetVersionNumber !== undefined) { + try { + const version = await resolveRuleVersion(client, { versionNumber: detail.ruleSetVersionNumber }); + const citedCodes = new Set( + (Array.isArray(citedRules?.rules) ? citedRules.rules : []) + .map((item) => item && typeof item === "object" ? item as Record : undefined) + .map((item) => item && helpers.parseRuleCodeNumber(item.ruleCode ?? item.code ?? item.runtimeRuleId)) + .filter((code): code is number => code !== undefined) + ); + const citedSnapshots = (version.rules ?? []) + .filter((snapshotRule) => { + const object = snapshotRule as Record; + const codeNum = helpers.parseRuleCodeNumber(object.code ?? object.ruleCode ?? object.runtimeRuleId); + return codeNum !== undefined && citedCodes.has(codeNum); + }) + .map((snapshotRule) => { + const object = snapshotRule as Record; + return { + code: object.code ?? object.ruleCode, + description: object.description, + scope: object.scope, + strictness: object.strictness + }; + }); + ruleVersion = { version: summarizeRuleVersion(version), citedSnapshots }; + } catch { + // 版本快照拉取失败不阻断诊断主流程 + } + } + + return { + recordId: detail.id, + sourceDocumentSN: detail.sourceDocumentSN, + sourceDocumentId: detail.sourceDocumentId, + status: detail.status, + ruleSetVersionNumber: detail.ruleSetVersionNumber, + documentSummary, + result: params.full === true ? detail.result : resultSummary, + citedRules, + ruleVersion, + bridge: summarizeRunBridge([detail]), + next: { + url: `seal-use approval-runs url ${detail.id} --corp ${context.corp.id}`, + hoseDocument: `seal-use approval-runs url ${detail.id} --type hose-document --corp ${context.corp.id}`, + replay: `seal-use approval-runs replay ${detail.id} --dry-run --corp ${context.corp.id}` + } + }; + } + }, { name: "seal_approval_run_langfuse_bridge_get", description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退", diff --git a/src/domains/seal/tools/helpers.ts b/src/domains/seal/tools/helpers.ts index 1f4a75c..76915c9 100644 --- a/src/domains/seal/tools/helpers.ts +++ b/src/domains/seal/tools/helpers.ts @@ -12,6 +12,7 @@ import type { } from "../types.js"; import { extractApprovalRunAttachments } from "../attachments.js"; import type { LocalRuleItem } from "../rules-local.js"; +import { loadRuleMappingSnapshot } from "../rule-mapping.js"; import { formatBeijingIso, normalizeBeijingIso } from "../../../core/config/timestamps.js"; export type ToolContext = { @@ -1041,6 +1042,49 @@ export function findRuleInVersion( }); } +/** + * Resolve the cross-environment rule code from the latest sync-test mapping snapshot, when one + * exists. Mapping snapshots are saved under the test (target) corp id, so a test corp reads its own + * snapshot directly while a production corp reads the snapshot of its bound test tenant. + */ +export function resolveCrossEnvRuleMapping( + corp: CorpConfig, + rule: { code?: unknown; id?: unknown } +): { + environment: "production" | "test"; + code: string; + direction: "prodToTest" | "testToProd"; + syncedAt: string; +} | undefined { + const codeNum = parseRuleCodeNumber(rule.code); + const ruleId = stringFromUnknown(rule.id); + if (codeNum === undefined && !ruleId) return undefined; + const direction = corp.environment === "test" ? "testToProd" : "prodToTest"; + const snapshot = corp.environment === "test" + ? loadRuleMappingSnapshot(corp.id) + : corp.testCorpId + ? loadRuleMappingSnapshot(corp.testCorpId) + : null; + if (!snapshot) return undefined; + const item = snapshot.ruleMapping.find((mapping) => { + if (direction === "prodToTest") { + return (codeNum !== undefined && parseRuleCodeNumber(mapping.sourceRuleCode) === codeNum) + || (ruleId !== undefined && mapping.sourceRuleId === ruleId); + } + return (codeNum !== undefined && parseRuleCodeNumber(mapping.targetRuleCode) === codeNum) + || (ruleId !== undefined && mapping.targetRuleId === ruleId); + }); + if (!item) return undefined; + const crossCode = direction === "prodToTest" ? item.targetRuleCode : item.sourceRuleCode; + const crossCodeNum = parseRuleCodeNumber(crossCode); + return { + environment: direction === "prodToTest" ? "test" : "production", + code: crossCodeNum !== undefined ? formatRuleCode(crossCodeNum) : String(crossCode), + direction, + syncedAt: snapshot.syncedAt + }; +} + export function parseRuleCodeNumber(value: unknown): number | undefined { if (typeof value === "number" && Number.isInteger(value) && value >= 0) { return value; diff --git a/src/domains/seal/tools/index.ts b/src/domains/seal/tools/index.ts index 5250e29..66b00d9 100644 --- a/src/domains/seal/tools/index.ts +++ b/src/domains/seal/tools/index.ts @@ -53,6 +53,7 @@ export const SEAL_READ_ONLY_TOOLS: ReadonlySet = new Set([ "seal_approval_rules_pull", "seal_approval_run_attachments_get", "seal_approval_run_cited_rules_get", + "seal_approval_run_diagnose", "seal_approval_run_document_summary_get", "seal_approval_run_flow_get", "seal_approval_run_get", diff --git a/src/domains/seal/tools/rules.ts b/src/domains/seal/tools/rules.ts index 4c29f92..b4bc331 100644 --- a/src/domains/seal/tools/rules.ts +++ b/src/domains/seal/tools/rules.ts @@ -3,6 +3,7 @@ import type { KyInstance } from "ky"; import * as api from "../api.js"; import { formatBeijingIso } from "../../../core/config/timestamps.js"; import { loadGlobalConfig } from "../../../core/config/loader.js"; +import { validationError } from "../../../core/errors.js"; import { redactSensitiveText } from "../../../core/redact.js"; import { searchApprovalContent } from "../search.js"; import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js"; @@ -37,9 +38,15 @@ const { normalizeRuleCode, formatRuleCode, resolveRuleVersion, - resolveRuleVersionSelector + resolveRuleVersionSelector, + resolveCrossEnvRuleMapping } = helpers; +function attachCrossEnvRule(context: ToolContext, rule: Record) { + const crossEnv = resolveCrossEnvRuleMapping(context.corp, rule); + return crossEnv ? { ...rule, crossEnv } : rule; +} + export const rulesTools = [ { name: "seal_approval_rules_list", @@ -183,47 +190,77 @@ export const rulesTools = [ }, { name: "seal_approval_rule_update", - description: "更新 Seal 草稿审批规则", + description: "更新 Seal 草稿审批规则;支持 --if-unchanged 乐观并发预检(草稿在基准后被他人修改则拒绝)", parameters: z.object({ ruleId: z.string().describe("规则 ID 或规则编号 code"), description: z.string().optional(), scope: z.string().optional(), - strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).optional() + strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).optional(), + ifUnchanged: z.union([z.string(), z.number()]).optional().describe("乐观并发预检基准:当前草稿的 updatedAt(rules get 输出的北京时间字符串或毫秒时间戳);服务端草稿在该基准后被修改则拒绝更新") }), handler: async ( client: KyInstance, - params: { ruleId: string; description?: string; scope?: string; strictness?: string } + params: { + ruleId: string; + description?: string; + scope?: string; + strictness?: string; + ifUnchanged?: string | number; + }, + context: ToolContext ) => { let resolvedRuleId = params.ruleId.trim(); const targetCodeNum = parseRuleCodeNumber(resolvedRuleId); - if (targetCodeNum !== undefined) { + let draftRule: ApprovalRule | undefined; + if (targetCodeNum !== undefined || params.ifUnchanged !== undefined) { const draftData = await api.listApprovalRules(client).catch(() => undefined); if (draftData?.rules) { const matched = draftData.rules.find( - (r) => r.id === resolvedRuleId || parseRuleCodeNumber(r.code) === targetCodeNum + (r) => r.id === resolvedRuleId || (targetCodeNum !== undefined && parseRuleCodeNumber(r.code) === targetCodeNum) ); if (!matched) { throw new Error(`未在当前草稿中找到编号为 ${params.ruleId} 的规则`); } resolvedRuleId = matched.id; + draftRule = matched; } } - const { ruleId: _ruleId, ...rest } = params; + if (params.ifUnchanged !== undefined) { + const expectedMs = typeof params.ifUnchanged === "number" + ? params.ifUnchanged + : Date.parse(params.ifUnchanged); + const serverMs = typeof draftRule?.updatedAt === "number" + ? draftRule.updatedAt + : draftRule?.updatedAt !== undefined + ? Date.parse(String(draftRule.updatedAt)) + : NaN; + const expectedSec = Number.isFinite(expectedMs) ? Math.floor(expectedMs / 1000) : undefined; + const serverSec = Number.isFinite(serverMs) ? Math.floor(serverMs / 1000) : undefined; + if (expectedSec === undefined || serverSec === undefined || expectedSec !== serverSec) { + throw validationError( + `草稿并发冲突:规则 ${params.ruleId} 的草稿在预检基准之后已被修改(服务端 updatedAt ${serverMs !== undefined && Number.isFinite(serverMs) ? formatBeijingIso(serverMs) : "未知"},预检基准 ${params.ifUnchanged})。`, + `seal-use rules get ${params.ruleId} --corp ${context.corp.id} 重新读取最新草稿并核对后重试` + ); + } + } + const { ruleId: _ruleId, ifUnchanged: _ifUnchanged, ...rest } = params; const result = await api.updateApprovalRule(client, resolvedRuleId, rest); - if (params.description) { + const finalDescription = result?.description ?? params.description; + if (finalDescription && loadGlobalConfig().lint?.enabled !== false) { try { const globalConfig = loadGlobalConfig(); - if (globalConfig.lint?.enabled) { - const loaded = await loadRuleLinter(globalConfig.lint.activeLinter); - const lintResult = await lintSingleRule({ id: resolvedRuleId, description: params.description }, loaded); - if (lintResult.issues.length > 0) { - console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${lintResult.score}/100 (发现 ${lintResult.issues.length} 处潜在风险):`); - for (const issue of lintResult.issues) { - console.error(` • [${issue.level.toUpperCase()}] ${issue.message}${issue.snippet ? ` ("${issue.snippet}")` : ""}`); - if (issue.suggestion) { - console.error(` 👉 建议: ${issue.suggestion}`); - } + const loaded = await loadRuleLinter(globalConfig.lint.activeLinter); + const lintResult = await lintSingleRule( + { id: resolvedRuleId, description: finalDescription, scope: result?.scope ?? params.scope }, + loaded + ); + if (lintResult.issues.length > 0) { + console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${lintResult.score}/100 (发现 ${lintResult.issues.length} 处潜在风险):`); + for (const issue of lintResult.issues) { + console.error(` • [${issue.level.toUpperCase()}] ${issue.message}${issue.snippet ? ` ("${issue.snippet}")` : ""}`); + if (issue.suggestion) { + console.error(` 👉 建议: ${issue.suggestion}`); } } } @@ -404,7 +441,7 @@ export const rulesTools = [ if (!explicitVersion && draftData?.rules) { const draftMatch = findRuleInDraft(draftData.rules, selector); if (draftMatch) { - return draftMatch; + return attachCrossEnvRule(context, draftMatch); } } @@ -425,7 +462,7 @@ export const rulesTools = [ : `Rule not found in current draft or version ${version.versionNumber}` ); } - return rule; + return attachCrossEnvRule(context, rule); } }, {