diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index a94b206..a69ddfb 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -40,6 +40,7 @@ seal-use corps list - Parse JSON stdout. Do not scrape human text. - Do not hand-edit enterprise configs for normal setup. Use `seal-use corps ...`. - Before write operations on rules, documents, style preferences, or publishing, fetch current state and confirm the intended mutation with the user. For repeat test-environment rule resets, prefer `rules clear --dry-run` followed by `rules clear --yes`. +- Knowledge document creation is currently irreversible: the upstream API exposes no delete operation. Validate `contentType` and `scenarios` before creating, and use `enabled: false` when the document should be withdrawn. - For customer-feedback rule remediation, show an exact field-level diff and obtain explicit approval before updating. Default to changing only the narrowest necessary part of `description`; preserve `scope`, `strictness`, and unrelated clauses unless the user explicitly approves otherwise. - Resolve and lock the target enterprise `corpId` before diagnosis or mutation. Never assume the current tenant is the customer tenant. Re-fetch the target rule immediately before updating, then verify the draft and newly published version after writing. - For date questions, use explicit dates and `--timezone Asia/Shanghai`. @@ -55,7 +56,7 @@ seal-use corps list - First install / zero configuration / “how do I connect my enterprise?” / user supplies app credentials, an assistance link, or F12/Network cURL: read `references/enterprise-onboarding.md`. Ask what material the user already has in plain language, then discover all remaining identifiers automatically. - User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp --note ''`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink. - Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version. -- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --corp ` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system `, `simulation wait ` 轮询等待完成, `simulation clean ` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。 +- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp ` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system `, `simulation status ` 单次查询状态, `simulation wait ` 轮询等待完成, `simulation clean ` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。 - Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud --corp `; read `references/hose-enterprise-deploy.md`. - 审核决策偏好与思考深度: `seal-use preference get --corp `, `preference decision update --json '...' --corp `, `preference thinking-depth set --default --corp `, `preference thinking-depth policies --corp `. - 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp `, `seal-use approval-runs count --corp `. diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 431eaec..8f28033 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -102,9 +102,10 @@ seal-use approval-runs url --corp seal-use approval-runs url --sourceDocumentSN --corp seal-use approval-runs bridge --corp [--sourceDocumentSN ] seal-use simulation batch-records --corp -seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] --corp +seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] --corp seal-use simulation create --mode material_pack --package-ids [--template-id conference_reimbursement_v1] [--schema-config file.json] --corp seal-use simulation create --source-system weaver --request-ids "req-01,req-02" --corp +seal-use simulation status --corp seal-use simulation wait [--timeout 10m] [--poll-interval 2s] --corp seal-use simulation clean --corp seal-use simulation specifications [--integration ] --corp @@ -142,9 +143,16 @@ Approval rule maintenance: - `seal-use rules list --summary [--corp ]` - `seal-use rules pull [--corp ] [--version ] [--out ]` - `seal-use rules lint [--file ] [--corp ] [--linter ] [--version ] [--code ] [--min-score ] [--summary]` -- `seal-use rules push [--file ] [--corp ] [--publish] [--version-name ] [--dry-run|--yes]` +- `seal-use rules push [--file ] [--corp ] [--publish] [--version-name ] [--dry-run|--yes]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred. - `seal-use rules clear [--corp ] [--dry-run|--yes]` +Rule identity and versioning: + +- `rules list` and `rules pull` read the current **draft** rule set. Their `code` values belong to the draft code space. +- A published version has its own snapshot and code space. Publishing can recode rules, so a published `code` may differ from the draft `code`, and codes can shift again after later edits and publishes. +- Do not use a draft `#NN` as a cross-version identifier. For current draft work, prefer the stable rule `id`; for historical behavior, select the published `version` and locate the rule by its text/context or runtime rule ID from the approval run. +- `rules get --version ... --code ...` interprets `code` inside that selected published version, while `rules get --record-id ... --runtime-id ...` resolves the version recorded on the run. + Approval run lightweight queries: - `seal-use approval-runs get --corp --fields metadata` @@ -181,7 +189,8 @@ Approval runs, simulations, and Langfuse bridge: - `seal-use approval-runs search --corp [--query ] [--limit 20]` - `seal-use approval-runs summary --corp [--date YYYY-MM-DD] [--timezone Asia/Shanghai]` - `seal-use approval-runs bridge --corp [--sourceDocumentSN ]` -- `seal-use simulation create --mode hosecloud --flow-ids ... --corp ` +- `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp ` returns immediately with an `asyncTicket` (creation is non-blocking by default for compatibility). +- `seal-use simulation status --corp ` performs one non-blocking status check and returns `QUEUED`/`RUNNING`/`COMPLETED`/`FAILED`-style state plus counters. - `seal-use simulation wait --corp ` - `seal-use simulation clean --corp ` - `seal-use simulation list --corp ` @@ -311,13 +320,17 @@ Create a document: "title": "标题", "purpose": "用途", "content": "Markdown 内容", - "contentType": "text/markdown", - "status": "可选", - "scenarios": ["场景"], + "contentType": "policy", + "status": "published", + "scenarios": ["audit"], "tags": ["标签"] } ``` +`contentType` 必须是 `document`、`video`、`pdf`、`feishu_doc` 或 `policy` 之一;`scenarios` 必填且至少包含一个 `fill`(智能填单)或 `audit`(智能审核)。这里的 `scenarios` 是产品能力开关,不是费用类别或业务场景名。 + +知识文档创建后当前 API 没有删除接口,创建操作不可逆;请在写入前确认标题、正文、内容类型和能力场景。需要撤下内容时,优先使用更新操作并设置 `enabled: false`(如果上游支持该字段),不要通过试探性创建来验证参数。规则支持删除,但知识文档与规则的生命周期能力并不对称。 + Update a document: ```json diff --git a/skills/seal-use/references/customer-feedback-rule-remediation.md b/skills/seal-use/references/customer-feedback-rule-remediation.md index d76d823..d7630a3 100644 --- a/skills/seal-use/references/customer-feedback-rule-remediation.md +++ b/skills/seal-use/references/customer-feedback-rule-remediation.md @@ -133,6 +133,8 @@ seal-use tool seal_approval_rule_update --corp \ Do not send `scope` or `strictness` when they are unchanged. Fetch the draft again and verify the exact description, scope, strictness, and draft status before publishing. +For a complete local rule-set sync, `rules push` is incremental: it matches pulled rules by stable `id`, updates only changed fields, creates new entries, and removes entries omitted from the local file. It preserves matched rule IDs and does not recode the whole draft. Preview it with `rules push --dry-run` before applying. + ## 9. Publish and verify Publish only when explicitly authorized: diff --git a/skills/seal-use/references/rule-lightweight.md b/skills/seal-use/references/rule-lightweight.md index babf45a..0b42305 100644 --- a/skills/seal-use/references/rule-lightweight.md +++ b/skills/seal-use/references/rule-lightweight.md @@ -2,6 +2,12 @@ Use this reference when the user wants rule counts, compact rule lists, one rule from a historical version, or approval knowledge search without dumping hundreds of rule descriptions. +## Draft and Published Rule Codes + +`rules list` and `rules pull` operate on the current draft and therefore return draft `code` values. A published version stores a separate snapshot and may recode the same rules; publishing, deleting, or reordering rules can make those published codes differ or drift again. A code such as `#0038` is only meaningful together with its version context. + +Use the draft `id` for current edits and use the approval run's recorded version plus rule text or runtime rule ID for historical investigations. Do not copy a draft code into a report or command that will be interpreted against a published version. + ## Count Rules Use count when only scale or existence matters. diff --git a/src/cli/commands/simulation.ts b/src/cli/commands/simulation.ts index c553d07..beb6bd0 100644 --- a/src/cli/commands/simulation.ts +++ b/src/cli/commands/simulation.ts @@ -62,6 +62,7 @@ export async function handleSimulationCommand( stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]) ?? stringOption(args.options.integration); + const noWait = booleanOption(args.options.noWait) ?? booleanOption(args.options["no-wait"]); await runTool( "seal_simulation_batch_create", @@ -91,6 +92,7 @@ export async function handleSimulationCommand( endTime: numberOption(args.options.endTime) ?? numberOption(args.options["end-time"]), status: splitOption(args.options.status), limit: numberOption(args.options.limit), + noWait, rawParams: inputPayload }, outputOptions(args.options) @@ -115,6 +117,19 @@ export async function handleSimulationCommand( return; } + if (action === "status") { + const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]); + if (!batchId) throw new Error("Usage: seal-use simulation status "); + await runTool( + "seal_simulation_batch_status", + client, + corp, + { batchId }, + outputOptions(args.options) + ); + return; + } + if (action === "clean" || action === "delete") { const batchId = maybeName ?? stringOption(args.options.batchId) ?? stringOption(args.options["batch-id"]); if (!batchId) throw new Error("Usage: seal-use simulation clean "); diff --git a/src/cli/printer.ts b/src/cli/printer.ts index ac4716e..c23effc 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -169,9 +169,10 @@ Usage: seal-use approval-runs url --sourceDocumentSN B26022501 [--corp ] seal-use approval-runs bridge [--sourceDocumentSN B26001887] [--corp ] seal-use simulation batch-records [--corp ] - seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--corp ] + seal-use simulation create --mode hosecloud --flow-ids "B26017701,B26022501" [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--corp ] seal-use simulation create --mode material_pack --package-ids [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp ] seal-use simulation create --source-system weaver --request-ids "req-01,req-02" [--corp ] + seal-use simulation status [--corp ] seal-use simulation wait [--timeout 10m] [--poll-interval 2s] [--corp ] seal-use simulation clean [--corp ] seal-use simulation specifications [--integration ] [--corp ] diff --git a/src/core/http/factory.test.ts b/src/core/http/factory.test.ts new file mode 100644 index 0000000..6d0ff41 --- /dev/null +++ b/src/core/http/factory.test.ts @@ -0,0 +1,33 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { createSealClientForUrl } from "./factory.js"; + +const servers: Array> = []; + +afterEach(() => { + for (const server of servers.splice(0)) server.stop(true); +}); + +describe("Seal HTTP client errors", () => { + test("includes ky's parsed response body after the response stream is consumed", async () => { + const server = Bun.serve({ + port: 0, + fetch: () => new Response(JSON.stringify({ + error: { + code: "error:common:invalid-parameter", + message: "contentType 取值非法" + } + }), { + status: 400, + headers: { "content-type": "application/json" } + }) + }); + servers.push(server); + + await expect( + createSealClientForUrl(`http://127.0.0.1:${server.port}`, "dummy-token").get("/") + ).rejects.toThrow( + 'Request failed with status code 400 Bad Request: GET http://127.0.0.1:' + + `${server.port}/: {"error":{"code":"error:common:invalid-parameter","message":"contentType 取值非法"}}` + ); + }); +}); diff --git a/src/core/http/factory.ts b/src/core/http/factory.ts index a0d2889..10a9aa8 100644 --- a/src/core/http/factory.ts +++ b/src/core/http/factory.ts @@ -3,6 +3,32 @@ import { CorpConfig } from "../config/types.js"; import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js"; import { resolveSealCustomHeaders } from "./request-headers.js"; +function formatErrorData(data: unknown): string { + if (data === undefined || data === null || data === "") return ""; + if (typeof data === "string") return data; + try { + return JSON.stringify(data); + } catch { + return String(data); + } +} + +function withResponseBody(error: unknown): Error { + if (!(error instanceof HTTPError)) return error as Error; + const body = formatErrorData(error.data); + if (body) error.message = `${error.message}: ${body}`; + return error; +} + +function createBeforeErrorHook(corpId?: string) { + return async ({ error }: { error: unknown }) => { + if (corpId && error instanceof HTTPError && error.response.status === 401) { + clearSealToken(corpId); + } + return withResponseBody(error); + }; +} + export async function createSealClient(corp: CorpConfig): Promise { const session = await getSealSessionForCorp(corp); @@ -14,19 +40,7 @@ export async function createSealClient(corp: CorpConfig): Promise { Authorization: `Bearer ${session.token}` }, hooks: { - beforeError: [ - async ({ error }) => { - if (error instanceof HTTPError && error.response.status === 401) { - clearSealToken(corp.id); - } - const body = - error instanceof HTTPError - ? await error.response.text().catch(() => "") - : ""; - error.message = `${error.message}${body ? `: ${body}` : ""}`; - return error; - } - ] + beforeError: [createBeforeErrorHook(corp.id)] } }); } @@ -50,16 +64,7 @@ export function createSealClientForUrl( Authorization: `Bearer ${token}` }, hooks: { - beforeError: [ - async ({ error }) => { - const body = - error instanceof HTTPError - ? await error.response.text().catch(() => "") - : ""; - error.message = `${error.message}${body ? `: ${body}` : ""}`; - return error; - } - ] + beforeError: [createBeforeErrorHook()] } }); } diff --git a/src/domains/seal/simulation.test.ts b/src/domains/seal/simulation.test.ts index 893d93f..c09b648 100644 --- a/src/domains/seal/simulation.test.ts +++ b/src/domains/seal/simulation.test.ts @@ -501,7 +501,12 @@ describe("simulation tool handlers", () => { sourceSystem: "hosecloud" }); expect(postedBody).not.toHaveProperty("limit"); - expect(result).toMatchObject({ batchId: "batch-1", created: true }); + expect(result).toMatchObject({ + batchId: "batch-1", + created: true, + noWait: true, + asyncTicket: "batch-1" + }); }); test("create tool surface exposes mode, flowIds, and rawParams", () => { @@ -509,18 +514,44 @@ describe("simulation tool handlers", () => { const { z } = require("zod") as typeof import("zod"); const schema = z.toJSONSchema(tool!.parameters) as { properties?: Record }; expect(Object.keys(schema.properties ?? {})).toEqual( - expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds"]) + expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds", "noWait"]) ); }); test("includes the simulation management tool set", () => { expect(sealTools.find((item) => item.name === "seal_simulation_batches_list")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_batch_get")).toBeDefined(); + expect(sealTools.find((item) => item.name === "seal_simulation_batch_status")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_templates_get")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_integrations_get")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_batch_records_get")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_simulation_material_package_upload")).toBeDefined(); }); + + test("status tool performs one non-blocking check and exposes the next action", async () => { + const tool = sealTools.find((item) => item.name === "seal_simulation_batch_status"); + expect(tool).toBeDefined(); + + const client = { + get: (url: string) => { + expect(url).toBe("api/v1/simulation/batch/batch-1"); + return { json: async () => ({ data: { ...hosecloudBatchFixture, id: "batch-1" } }) }; + } + } as unknown as KyInstance; + + const handler = tool!.handler as ToolHandler; + const result = await handler(client, { batchId: "batch-1" }, fakeContext()) as Record; + + expect(result).toMatchObject({ + batchId: "batch-1", + status: "SYNCING", + terminal: false, + next: { + status: "seal-use simulation status batch-1", + wait: "seal-use simulation wait batch-1" + } + }); + }); }); describe("simulation response schemas", () => { diff --git a/src/domains/seal/tools.test.ts b/src/domains/seal/tools.test.ts index d5c4a0f..33a31e8 100644 --- a/src/domains/seal/tools.test.ts +++ b/src/domains/seal/tools.test.ts @@ -5,7 +5,7 @@ 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 { findSealTool, sealTools } from "./tools.js"; +import { buildRulePushPlan, findSealTool, sealTools } from "./tools.js"; type ToolHandler = ( client: KyInstance, @@ -223,6 +223,87 @@ describe("sealTools", () => { expect(await countFakeRules(client)).toBe(0); }); + test("plans incremental rule updates without rebuilding matched rules", () => { + const plan = buildRulePushPlan( + [ + { + id: "rule-1", + code: 1, + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }, + { + id: "rule-2", + code: 2, + description: "Keep attendee names", + scope: "meal", + strictness: "SHOULD_FOLLOW" + } + ], + [ + { + id: "rule-1", + description: "Keep complete receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }, + { + description: "Require cost center", + scope: "all", + strictness: "SUGGESTION" + } + ] + ); + + expect(plan.updated).toMatchObject([ + { id: "rule-1", changedFields: ["description"] } + ]); + expect(plan.created).toMatchObject([ + { description: "Require cost center" } + ]); + expect(plan.deleted).toMatchObject([{ id: "rule-2", code: 2 }]); + expect(plan.unchanged).toEqual([]); + }); + + test("matches legacy local rules by unique content when no id is present", () => { + const plan = buildRulePushPlan( + [{ + id: "rule-1", + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }], + [{ + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }] + ); + + expect(plan.created).toEqual([]); + expect(plan.updated).toEqual([]); + expect(plan.deleted).toEqual([]); + expect(plan.unchanged).toEqual([{ id: "rule-1" }]); + }); + + test("rejects local rule ids that are absent from the current draft", () => { + expect(() => buildRulePushPlan( + [{ + id: "rule-1", + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }], + [{ + id: "stale-rule", + description: "Keep receipts", + scope: "travel", + strictness: "MUST_FOLLOW" + }] + )).toThrow("stale-rule"); + }); + test("includes approval run Langfuse bridge tools", () => { expect(sealTools.find((item) => item.name === "seal_approval_runs_search")).toBeDefined(); expect(sealTools.find((item) => item.name === "seal_approval_runs_summary")).toBeDefined(); diff --git a/src/domains/seal/tools.ts b/src/domains/seal/tools.ts index c122efe..c7d17d2 100644 --- a/src/domains/seal/tools.ts +++ b/src/domains/seal/tools.ts @@ -209,7 +209,7 @@ export const sealTools = [ }, { name: "seal_approval_rules_list", - description: "列出 Seal 当前草稿审批规则;支持 countOnly、fields、limit 以避免返回规则正文", + description: "列出 Seal 当前草稿审批规则;返回的 code 属于草稿编号体系,发布版本可能重新编码;支持 countOnly、fields、limit 以避免返回规则正文", parameters: z.object({ countOnly: z.boolean().optional().describe("只返回规则数量,不返回规则列表"), fields: z.array(z.enum([ @@ -423,7 +423,7 @@ export const sealTools = [ }, { name: "seal_approval_rule_get", - description: "按版本号/code/runtime-id/record-id 定位单条规则,避免拉取整版规则快照", + description: "按版本号/code/runtime-id/record-id 定位单条规则;code 只在选定的版本编号体系内有效,避免拉取整版规则快照", parameters: z.object({ versionId: z.string().optional().describe("规则版本 ID"), versionNumber: z.number().int().positive().optional().describe("规则版本号"), @@ -625,7 +625,7 @@ export const sealTools = [ }, { name: "seal_approval_rules_push", - description: "将本地规则文件推送到远端草稿(本地调优通过后一键应用,支持直接发布为正式版本)", + description: "将本地规则文件增量同步到远端草稿;按规则 ID 更新/删除并保留未变更规则,支持直接发布为正式版本", parameters: z.object({ file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"), dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"), @@ -650,6 +650,7 @@ export const sealTools = [ const isDryRun = params.dryRun ?? !isConfirmed; const before = await api.listApprovalRules(client); + const plan = buildRulePushPlan(before.rules, local.rules); if (isDryRun) { return { @@ -658,39 +659,42 @@ export const sealTools = [ localFile: local.resolvedPath, localRulesCount: local.rules.length, remoteDraftCount: before.rules.length, + changes: plan, + impactCount: plan.created.length + plan.updated.length + plan.deleted.length, + preservedRuleIds: [ + ...plan.updated.map((change) => change.id), + ...plan.unchanged.map((rule) => rule.id) + ], + warning: "Incremental mode preserves matched rule IDs and does not recode the draft rule set.", willPublish: Boolean(params.publish), - message: "Preview mode. Use --yes or confirm=true to apply local rules to remote draft." + message: "Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft." }; } - // Step 1: Clear existing draft rules - let deleted = 0; - for (const rule of before.rules) { + for (const rule of plan.deleted) { await api.deleteApprovalRule(client, rule.id); - deleted += 1; } - // Step 2: Create new rules from local const created: Array<{ id: string; description: string; code?: number }> = []; - for (const rule of local.rules) { - const strictness = rule.strictness?.toUpperCase()?.includes("SHOULD") - ? "SHOULD_FOLLOW" - : rule.strictness?.toUpperCase()?.includes("SUGGEST") - ? "SUGGESTION" - : "MUST_FOLLOW"; - + for (const rule of plan.created) { const newRule = await api.createApprovalRule(client, { description: rule.description, scope: rule.scope ?? "ALL", - strictness + strictness: normalizeRuleStrictness(rule.strictness) }); created.push({ id: newRule.id, description: newRule.description, code: newRule.code }); } - // Step 3: Recode - await api.recodeApprovalRules(client); + const updated: string[] = []; + for (const change of plan.updated) { + await api.updateApprovalRule(client, change.id, { + description: change.rule.description, + scope: change.rule.scope ?? "ALL", + strictness: normalizeRuleStrictness(change.rule.strictness) + }); + updated.push(change.id); + } - // Step 4: Optional publish let publishedVersion: unknown = undefined; if (params.publish) { const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, ""); @@ -702,8 +706,15 @@ export const sealTools = [ corpId: context.corp.id, dryRun: false, localFile: local.resolvedPath, - clearedDraftRules: deleted, + deletedRules: plan.deleted.length, createdRules: created.length, + updatedRules: updated.length, + unchangedRules: plan.unchanged.length, + preservedRuleIds: [ + ...updated, + ...plan.unchanged.map((rule) => rule.id) + ], + recoded: false, published: publishedVersion ?? false }; } @@ -1423,6 +1434,7 @@ export const sealTools = [ packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"), templateId: z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"), schemaConfig: z.record(z.string(), z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"), + noWait: z.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"), rawParams: z.record(z.string(), z.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果") }), handler: async ( @@ -1439,6 +1451,7 @@ export const sealTools = [ packageIds?: string[]; templateId?: string; schemaConfig?: Record; + noWait?: boolean; rawParams?: Record; } ) => { @@ -1474,7 +1487,11 @@ export const sealTools = [ return { ...result, created: true, + noWait: params.noWait ?? true, + asyncTicket: result.batchId, next: { + status: `seal-use simulation status ${result.batchId}`, + wait: `seal-use simulation wait ${result.batchId}`, getBatch: "seal-home simulation get ", getRecords: "seal-home simulation batch-records ", listBatches: "seal-home simulation list" @@ -1516,6 +1533,32 @@ export const sealTools = [ }; } }, + { + name: "seal_simulation_batch_status", + description: "单次读取 Seal 模拟批次状态,不阻塞等待;适合根据异步票据轮询", + parameters: z.object({ + batchId: z.string().describe("simulation batch ID") + }), + handler: async (client: KyInstance, params: { batchId: string }) => { + const batch = await api.getSimulationBatch(client, params.batchId); + const status = String(batch.status ?? "UNKNOWN").toUpperCase(); + const terminal = ["COMPLETED", "FAILED", "CANCELLED", "CANCELED"].includes(status); + return { + batchId: params.batchId, + status, + terminal, + totalCount: batch.totalCount, + processedCount: batch.processedCount, + successCount: batch.successCount, + failedCount: batch.failedCount, + createdAt: batch.createdAt, + updatedAt: batch.updatedAt, + next: terminal + ? { getRecords: `seal-use simulation batch-records ${params.batchId}` } + : { status: `seal-use simulation status ${params.batchId}`, wait: `seal-use simulation wait ${params.batchId}` } + }; + } + }, { name: "seal_simulation_templates_get", description: "列出 Seal 模拟测试模板(我的模板,保存常用配置快速复用)", @@ -2184,6 +2227,90 @@ function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[]) { return output; } +type RulePushPlan = { + created: LocalRuleItem[]; + updated: Array<{ id: string; rule: LocalRuleItem; changedFields: string[] }>; + deleted: ApprovalRule[]; + unchanged: Array>; +}; + +export function buildRulePushPlan( + remoteRules: ApprovalRule[], + localRules: LocalRuleItem[] +): RulePushPlan { + const remoteById = new Map(remoteRules.map((rule) => [rule.id, rule])); + const usedRemoteIds = new Set(); + const created: LocalRuleItem[] = []; + const updated: RulePushPlan["updated"] = []; + const unchanged: RulePushPlan["unchanged"] = []; + + for (const localRule of localRules) { + let remoteRule: ApprovalRule | undefined; + if (localRule.id) { + remoteRule = remoteById.get(localRule.id); + if (!remoteRule) { + throw new Error( + `本地规则 ${localRule.id} 不存在于当前草稿。请先用 rules pull 获取当前草稿,再重新应用修改。` + ); + } + if (usedRemoteIds.has(localRule.id)) { + throw new Error(`本地规则文件包含重复的规则 ID:${localRule.id}`); + } + } else { + const matches = remoteRules.filter( + (candidate) => !usedRemoteIds.has(candidate.id) && rulesHaveSameContent(candidate, localRule) + ); + if (matches.length > 1) { + throw new Error( + `本地规则“${localRule.description}”无法唯一匹配远端草稿,请在规则文件中补充稳定的 id。` + ); + } + remoteRule = matches[0]; + } + + if (!remoteRule) { + created.push(localRule); + continue; + } + + usedRemoteIds.add(remoteRule.id); + const changedFields = ruleChangedFields(remoteRule, localRule); + if (changedFields.length) { + updated.push({ id: remoteRule.id, rule: localRule, changedFields }); + } else { + unchanged.push({ id: remoteRule.id }); + } + } + + return { + created, + updated, + deleted: remoteRules.filter((rule) => !usedRemoteIds.has(rule.id)), + unchanged + }; +} + +function rulesHaveSameContent(remoteRule: ApprovalRule, localRule: LocalRuleItem): boolean { + return remoteRule.description === localRule.description.trim() && + remoteRule.scope === (localRule.scope ?? "ALL") && + remoteRule.strictness === normalizeRuleStrictness(localRule.strictness); +} + +function ruleChangedFields(remoteRule: ApprovalRule, localRule: LocalRuleItem): string[] { + const changed: string[] = []; + if (remoteRule.description !== localRule.description.trim()) changed.push("description"); + if (remoteRule.scope !== (localRule.scope ?? "ALL")) changed.push("scope"); + if (remoteRule.strictness !== normalizeRuleStrictness(localRule.strictness)) changed.push("strictness"); + return changed; +} + +function normalizeRuleStrictness(value?: string): string { + const normalized = value?.toUpperCase() ?? "MUST_FOLLOW"; + if (normalized.includes("SHOULD")) return "SHOULD_FOLLOW"; + if (normalized.includes("SUGGEST")) return "SUGGESTION"; + return "MUST_FOLLOW"; +} + export type SimulationBatchCreateInput = { mode?: string; sourceSystem?: string;