diff --git a/skills/seal-use/references/cli.md b/skills/seal-use/references/cli.md index 1f0483b..46344d3 100644 --- a/skills/seal-use/references/cli.md +++ b/skills/seal-use/references/cli.md @@ -151,8 +151,8 @@ seal-use deploy hosecloud requirements [--corp ] seal-use deploy hosecloud list [--corp ] seal-use deploy hosecloud get [--corp ] seal-use deploy hosecloud status [--corp ] -seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp ] -seal-use deploy hosecloud sync [] [--auto] [--corp ] +seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp ] +seal-use deploy hosecloud sync [] [--auto] [--dry-run] [--yes|--confirm] [--corp ] seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id --message-id [--sn ] [--rejection-num ] [--dry-run] [--yes|--confirm] [--corp ] seal-use preference get [--corp ] seal-use preference decision update --json '{"explicitApprove":"..."}' [--dry-run] [--corp ] diff --git a/skills/seal-use/references/hose-enterprise-deploy.md b/skills/seal-use/references/hose-enterprise-deploy.md index 4be5aeb..7ffe81b 100644 --- a/skills/seal-use/references/hose-enterprise-deploy.md +++ b/skills/seal-use/references/hose-enterprise-deploy.md @@ -50,7 +50,7 @@ seal-use deploy hosecloud list --corp seal-use deploy hosecloud requirements --corp # 3. 添加新配置(自动探测平台) -seal-use deploy hosecloud configure --corp --json '{ +seal-use deploy hosecloud configure --corp --yes --json '{ "apiKey": "your-app-key", "apiSecret": "your-app-secret", "outboundName": "SealAI 财务审批", @@ -58,7 +58,7 @@ seal-use deploy hosecloud configure --corp --json '{ }' # 4. 编辑已有配置(传入原 signKey) -seal-use deploy hosecloud configure --corp --json '{ +seal-use deploy hosecloud configure --corp --yes --json '{ "signKey": "<原 signKey>", "apiKey": "your-app-key", "apiSecret": "your-app-secret", @@ -67,11 +67,13 @@ seal-use deploy hosecloud configure --corp --json '{ }' # 5. 一键同步发布到合思审批流 -seal-use deploy hosecloud sync --corp +seal-use deploy hosecloud sync --dry-run --corp +seal-use deploy hosecloud sync --yes --corp # 5.1 单配置企业一键自动同步 (--auto) -# 若企业内仅存在 1 个合思配置卡片,可直接传入 --auto 自动锁定执行,免去查询复制 signKey: -seal-use deploy hosecloud sync --auto --corp +# 若企业内仅存在 1 个合思配置卡片,可传入 --auto 自动选择,免去查询复制 signKey;实际同步仍需确认: +seal-use deploy hosecloud sync --auto --dry-run --corp +seal-use deploy hosecloud sync --auto --yes --corp # 6. 查看单项配置详情(未传 signKey 时自动列出当前企业候选列表与查看命令) seal-use deploy hosecloud get [] --corp @@ -83,6 +85,9 @@ seal-use deploy hosecloud status --corp seal-use deploy hosecloud test-outbound [--sign-key ] --flow-id --message-id [--sn ] [--dry-run] [--yes|--confirm] --corp ``` +`configure` 保存 Seal 端集成配置,`sync` 在合思创建或更新出站消息及回调地址;两者实际写入都要求 `--yes` 或 `--confirm`。保存配置前可将示例中的 `--yes` 换成 `--dry-run` 查看脱敏后的前后差异。 +`sync --dry-run` 只列出待提交的名称、回调地址和模式;`remoteStateKnown: false` 表示未读取合思远端当前配置,不能把预览视为远端现状验证。 + 实际推送必须带 `--yes` 或 `--confirm`;`--dry-run` 可直接预览。自定义 `nodeId` 时,预览中的 `nodeId412Blocked` 不再声明默认标记的阻断保障。 出站响应未明确返回关联 `recordId` 时,结果为 `consumptionVerified: false`(推送已接受,消费尚未确认),不会用同单据的历史记录误报本次消费成功。 diff --git a/skills/seal-use/references/staging-simulation-workflow.md b/skills/seal-use/references/staging-simulation-workflow.md index 99dbfc7..1bcf539 100644 --- a/skills/seal-use/references/staging-simulation-workflow.md +++ b/skills/seal-use/references/staging-simulation-workflow.md @@ -207,6 +207,7 @@ flowchart TD # 底层直接推送出站调试消息(仅限 assisted 模式) seal-use deploy hosecloud test-outbound --flow-id --message-id --corp --yes ``` + 指定 `--rejection-num N` 时只接受第 N 轮出站日志,找不到则报错;按审核记录创建时间推测出站事件时,只接受相差小于 60 秒的记录,不会退回更旧的轮次或日志。 > **专属安全红线契约**: > 1. **双向绑定**:必须在已绑定的生产-测试企业对之间执行;严禁跨越非关联租户(未带 `--force` 时直接报 Exit 14 阻断)。 > 2. **锁死 assisted 模式**:目标测试环境的合思配置必须为 `assisted` 辅助模式,否则直接触发 Exit 14 安全阻断。 diff --git a/src/cli/commands/deploy.test.ts b/src/cli/commands/deploy.test.ts new file mode 100644 index 0000000..43cd6ea --- /dev/null +++ b/src/cli/commands/deploy.test.ts @@ -0,0 +1,170 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import type { KyInstance } from "ky"; +import { CorpConfigSchema } from "../../core/config/types.js"; +import { parseArgs } from "../parser.js"; +import { runCapabilityResult } from "../helpers.js"; +import { handleDeployCommand } from "./deploy.js"; + +const originalLog = console.log; +const originalError = console.error; +afterEach(() => { + console.log = originalLog; + console.error = originalError; +}); + +const corp = CorpConfigSchema.parse({ + id: "deploy-test", name: "Deployment test", environment: "test", + seal: { url: "https://seal.test", endpoints: { approvalStylePreferences: "api/custom/preferences" } }, + source: { type: "seal", sealUrl: "https://seal.test", token: "mock-token" } +}); + +const input = { + apiKey: "mock-key", apiSecret: "mock-secret", signKey: "sign-key", + apiOrigin: "custom", customApiUrl: "https://hose.test", mode: "assisted" +}; + +function fakeClient(signKeys = ["sign-key"]) { + const requests: Array<{ method: string; path: string; json?: unknown }> = []; + let config: Record = { + integrations: signKeys.map((signKey) => ({ + type: "hosecloud", signKey, outboundName: "AI review", mode: "assisted", + apiKey: "existing-key", apiSecret: "existing-secret" + })) + }; + const client = { + get: (path: string) => { + requests.push({ method: "GET", path }); + return { json: async () => ({ data: config }) }; + }, + post: (path: string, options: { json: Record }) => { + requests.push({ method: "POST", path, json: options.json }); + if (path === "api/hosecloud/corporation") { + return { json: async () => ({ data: { corporationId: "hose-corp" } }) }; + } + if (path === corp.seal.endpoints.approvalStylePreferences) { + config = options.json; + return { json: async () => ({ data: config }) }; + } + if (path === "api/hosecloud/outbound-config/sync") { + return { json: async () => ({ data: { outboundMessageId: "message" } }) }; + } + throw new Error(`Unexpected POST ${path}`); + } + } as unknown as KyInstance; + return { client, requests }; +} + +async function callDeploy(client: KyInstance, argv: string[]) { + const lines: string[] = []; + console.log = (line: string) => lines.push(line); + console.error = () => {}; + const args = parseArgs(argv); + await handleDeployCommand(args.command[1], args.command[2], args.command[3], client, corp, args); + return JSON.parse(lines.join("\n")) as Record; +} + +describe("Hose configure and sync confirmation", () => { + test("both execution handlers refuse unconfirmed writes before any network call", async () => { + for (const name of ["sealDeployHosecloudConfigure", "sealDeployHosecloudSync"]) { + for (const confirm of [undefined, false]) { + const fixture = fakeClient(); + await expect(runCapabilityResult(name, fixture.client, corp, { + ...(name.endsWith("Configure") ? input : { signKey: "sign-key" }), confirm + })).rejects.toMatchObject({ exitCode: 10 }); + expect(fixture.requests).toHaveLength(0); + } + } + }); + + test("configure previews a masked diff without persisting credentials or control flags", async () => { + const fixture = fakeClient(); + const preview = await callDeploy(fixture.client, [ + "deploy", "hosecloud", "configure", "--json", JSON.stringify(input), "--dry-run", "--yes" + ]); + expect(preview.preview).toBe(true); + expect(preview.targetUrl).toBe("https://seal.test/api/custom/preferences"); + expect(JSON.stringify(preview)).not.toContain("mock-secret"); + expect(JSON.stringify(preview)).not.toContain("existing-secret"); + expect(fixture.requests.filter((request) => request.method === "POST").map((request) => request.path)) + .toEqual(["api/hosecloud/corporation"]); + const after = (preview.changesDiff as { after: { integrations: Record[] } }).after; + expect(after.integrations[0]?.confirm).toBeUndefined(); + expect(after.integrations[0]?.dryRun).toBeUndefined(); + }); + + test("configure honors either CLI confirmation flag and keeps control flags out of saved configuration", async () => { + for (const flag of ["--yes", "--confirm"]) { + const fixture = fakeClient(); + await callDeploy(fixture.client, ["deploy", "hosecloud", "configure", "--json", JSON.stringify(input), flag]); + const saved = fixture.requests.find((request) => request.path === corp.seal.endpoints.approvalStylePreferences && request.method === "POST"); + expect(saved).toBeDefined(); + const integration = (saved!.json as { integrations: Record[] }).integrations[0]!; + expect(integration.apiSecret).toBe("mock-secret"); + expect(integration.confirm).toBeUndefined(); + expect(integration.dryRun).toBeUndefined(); + } + }); + + test("a JSON confirm field cannot replace an explicit CLI flag", async () => { + const fixture = fakeClient(); + await expect(callDeploy(fixture.client, [ + "deploy", "hosecloud", "configure", "--json", JSON.stringify({ ...input, confirm: true }) + ])).rejects.toMatchObject({ exitCode: 10 }); + expect(fixture.requests).toHaveLength(0); + }); + + test("legacy credential spellings are normalized and masked in previews", async () => { + const fixture = fakeClient(); + const { apiKey, apiSecret, ...settings } = input; + const preview = await callDeploy(fixture.client, [ + "deploy", "hosecloud", "configure", "--json", + JSON.stringify({ ...settings, appKey: apiKey, appSecurity: apiSecret }), "--dry-run" + ]); + expect(JSON.stringify(preview)).not.toContain("mock-secret"); + const after = (preview.changesDiff as { after: { integrations: Record[] } }).after; + expect(after.integrations[0]?.apiSecret).toBe("***"); + expect(after.integrations[0]?.appSecurity).toBeUndefined(); + }); + + test("sync preview matches the live request without calling the synchronization endpoint", async () => { + const fixture = fakeClient(); + const preview = await callDeploy(fixture.client, ["deploy", "hosecloud", "sync", "sign-key", "--dry-run"]); + expect(preview.preview).toBe(true); + expect(preview.remoteStateKnown).toBe(false); + expect(preview.targetUrl).toBe("https://seal.test/api/hosecloud/outbound-config/sync"); + expect((preview.changesDiff as { before: unknown }).before).toBeNull(); + expect(fixture.requests.every((request) => request.method === "GET")).toBe(true); + expect(fixture.requests[0]?.path).toBe(corp.seal.endpoints.approvalStylePreferences); + + for (const flag of ["--yes", "--confirm"]) { + const live = fakeClient(); + const result = await callDeploy(live.client, ["deploy", "hosecloud", "sync", "sign-key", flag]); + expect(result.synced).toBe(true); + expect(live.requests.find((request) => request.path === "api/hosecloud/outbound-config/sync")?.json) + .toEqual((preview.changesDiff as { after: unknown }).after); + } + }); + + test("auto only selects a singleton and never replaces confirmation", async () => { + const fixture = fakeClient(); + await expect(callDeploy(fixture.client, ["deploy", "hosecloud", "sync", "--auto"])) + .rejects.toMatchObject({ exitCode: 10 }); + expect(fixture.requests.every((request) => request.method === "GET")).toBe(true); + const preview = await callDeploy(fixture.client, ["deploy", "hosecloud", "sync", "--auto", "--dry-run"]); + expect(preview.preview).toBe(true); + const multiple = fakeClient(["first", "second"]); + await expect(callDeploy(multiple.client, ["deploy", "hosecloud", "sync", "--auto", "--yes"])) + .rejects.toMatchObject({ exitCode: 2 }); + expect(multiple.requests.every((request) => request.method === "GET")).toBe(true); + }); + + test("either confirmation flag supports singleton selection without a positional signKey", async () => { + for (const flag of ["--yes", "--confirm"]) { + const fixture = fakeClient(); + const result = await callDeploy(fixture.client, ["deploy", "hosecloud", "sync", flag]); + expect(result.synced).toBe(true); + expect(fixture.requests[0]?.path).toBe(corp.seal.endpoints.approvalStylePreferences); + expect(fixture.requests.filter((request) => request.path === "api/hosecloud/outbound-config/sync")).toHaveLength(1); + } + }); +}); diff --git a/src/cli/commands/deploy.ts b/src/cli/commands/deploy.ts index cfbfcf3..ed45782 100644 --- a/src/cli/commands/deploy.ts +++ b/src/cli/commands/deploy.ts @@ -112,17 +112,20 @@ export async function handleDeployCommand( } await runCapability("sealDeployHosecloudConfigure", client, corp, { ...payload, - dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) + dryRun: booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]), + confirm: booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true }, outputOptions(args.options)); return; } if (action === "sync") { const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]); - const autoOpt = booleanOption(args.options.auto) ?? booleanOption(args.options.yes); + const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]); + const confirm = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true; + const autoOpt = booleanOption(args.options.auto) ?? confirm; if (!signKey) { - const config = await api.getApprovalStylePreferences(client); + const config = await api.getApprovalStylePreferences(client, corp.seal.endpoints.approvalStylePreferences); const hoseConfigs = listHoseIntegrations(config); if (hoseConfigs.length === 0) { @@ -136,34 +139,34 @@ export async function handleDeployCommand( if (firstHose && hoseConfigs.length === 1 && autoOpt) { const singleKey = firstHose.signKey; console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${singleKey})`); - await runCapability("sealDeployHosecloudSync", client, corp, { signKey: singleKey }, outputOptions(args.options)); + await runCapability("sealDeployHosecloudSync", client, corp, { signKey: singleKey, dryRun, confirm }, outputOptions(args.options)); return; } - console.error(`Usage: seal-use deploy hosecloud sync [--corp ${corp.id}]\n`); + console.error(`Usage: seal-use deploy hosecloud sync [--dry-run] [--yes|--confirm] [--corp ${corp.id}]\n`); console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`); for (const item of hoseConfigs) { const name = item.outboundName ?? "SealAI 审批"; const key = item.signKey; const origin = item.apiOrigin ?? "production"; console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`); - console.error(` 👉 同步命令: seal-use deploy hosecloud sync ${key} --corp ${corp.id}\n`); + console.error(` 👉 同步预览: seal-use deploy hosecloud sync ${key} --dry-run --corp ${corp.id}\n`); } if (hoseConfigs.length === 1) { - console.error(`💡 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${corp.id}\n`); + console.error(`💡 提示:若希望自动选择单配置,可使用:seal-use deploy hosecloud sync --auto --dry-run --corp ${corp.id}\n`); } throw new CliError( "缺少必需参数 。请从上述候选列表中选择并指定 signKey 执行同步。", 2, hoseConfigs.length === 1 - ? `seal-use deploy hosecloud sync ${hoseConfigs[0]!.signKey} --corp ${corp.id}` + ? `seal-use deploy hosecloud sync ${hoseConfigs[0]!.signKey} --dry-run --corp ${corp.id}` : undefined ); } - await runCapability("sealDeployHosecloudSync", client, corp, { signKey }, outputOptions(args.options)); + await runCapability("sealDeployHosecloudSync", client, corp, { signKey, dryRun, confirm }, outputOptions(args.options)); return; } diff --git a/src/cli/help.ts b/src/cli/help.ts index f40df4f..04b6c82 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -748,13 +748,22 @@ export const HELP_REGISTRY: AreaHelp[] = [ }, { name: "hosecloud configure", - summary: "Configure HoseCloud deployment settings", - usage: ["seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--corp ]"] + summary: "Save Hose integration settings in Seal", + usage: ["seal-use deploy hosecloud configure --json '{...}' [--dry-run] [--yes|--confirm] [--corp ]"], + options: [ + { flag: "--dry-run", description: "Preview the configuration diff without saving" }, + { flag: "--yes, --confirm", description: "Required to save the integration configuration" } + ] }, { name: "hosecloud sync", - summary: "Synchronize HoseCloud rules and definitions", - usage: ["seal-use deploy hosecloud sync [--corp ]"] + summary: "Create or update Hose outbound messages and callback URLs", + usage: ["seal-use deploy hosecloud sync [] [--auto] [--dry-run] [--yes|--confirm] [--corp ]"], + options: [ + { flag: "--auto", description: "Select the sole Hose integration; does not confirm synchronization" }, + { flag: "--dry-run", description: "Preview the sync request without creating or updating messages" }, + { flag: "--yes, --confirm", description: "Required for live synchronization" } + ] }, { name: "hosecloud test-outbound", diff --git a/src/domains/seal/capabilities.test.ts b/src/domains/seal/capabilities.test.ts index 4d8cfd1..301e328 100644 --- a/src/domains/seal/capabilities.test.ts +++ b/src/domains/seal/capabilities.test.ts @@ -1198,7 +1198,8 @@ describe("sealCapabilities", () => { apiSecret: "test-sk", apiOrigin: "custom", customApiUrl: "https://dd2.hosecloud.com", - outboundName: "DingTalk AI Audit" + outboundName: "DingTalk AI Audit", + confirm: true }, fakeContext() ) as { integration: { corporationId: string; apiOrigin: string; customApiUrl: string; outboundName: string } }; diff --git a/src/domains/seal/capabilities/deploy.ts b/src/domains/seal/capabilities/deploy.ts index a484570..bfae415 100644 --- a/src/domains/seal/capabilities/deploy.ts +++ b/src/domains/seal/capabilities/deploy.ts @@ -3,7 +3,7 @@ import type { KyInstance } from "ky"; import { randomBytes } from "node:crypto"; import * as api from "../api.js"; import { probeHoseDomain } from "../../../core/auth/hose.js"; -import { validationError } from "../../../core/errors.js"; +import { confirmationRequired, validationError } from "../../../core/errors.js"; import { type HosecloudConfigInput } from "../types.js"; import { assertAssistedIntegration, @@ -115,12 +115,13 @@ export const deployCapabilities = [ autoApproveNodeNames: z.array(z.string()).optional(), apiOrigin: z.string().default("production"), customApiUrl: z.string().optional(), - dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入") + dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入"), + confirm: z.boolean().optional().describe("明确确认保存配置;CLI 使用 --yes 或 --confirm") }), handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: CapabilityContext) => { - const { dryRun, ...inputParams } = rawParams; - const apiKey = inputParams.apiKey ?? (inputParams as any).appKey; - const apiSecret = inputParams.apiSecret ?? (inputParams as any).appSecurity; + const { dryRun, confirm, appKey, appSecurity, ...inputParams } = rawParams; + const apiKey = inputParams.apiKey ?? (typeof appKey === "string" ? appKey : undefined); + const apiSecret = inputParams.apiSecret ?? (typeof appSecurity === "string" ? appSecurity : undefined); if (!apiKey || !apiSecret) { throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项"); } @@ -128,6 +129,16 @@ export const deployCapabilities = [ let effectiveApiOrigin = params.apiOrigin ?? "production"; let effectiveCustomApiUrl = params.customApiUrl; + if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) { + throw new Error("自定义合思环境必须提供 customApiUrl"); + } + if (!dryRun && confirm !== true) { + throw confirmationRequired( + "Refusing to save Hose integration configuration without --yes or --confirm. Use --dry-run to preview first.", + "seal-use help deploy hosecloud configure" + ); + } + // 自动平台/域名探测:当未提供 customApiUrl 时,并发探测合思 6 大标准公共 SaaS 平台域名 if (!effectiveCustomApiUrl && effectiveApiOrigin !== "custom") { try { @@ -146,17 +157,13 @@ export const deployCapabilities = [ } } - if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) { - throw new Error("自定义合思环境必须提供 customApiUrl"); - } - const corpResult = await api.getHosecloudCorporation(client, { apiKey: params.apiKey, apiSecret: params.apiSecret, apiOrigin: effectiveApiOrigin, customApiUrl: effectiveCustomApiUrl }); - const config = await api.getApprovalStylePreferences(client); + const config = await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences); const signKey = params.signKey ?? randomBytes(6).toString("hex"); const nextIntegration = { type: "hosecloud", @@ -187,7 +194,7 @@ export const deployCapabilities = [ await api.updateApprovalStylePreferences(client, nextConfig, context.corp.seal.endpoints.approvalStylePreferences); console.error(`✓ 配置已保存 (signKey: ${signKey})`); - console.error(`👉 Next action: seal-use deploy hosecloud sync ${signKey} --corp ${context.corp.id}`); + console.error(`👉 Next action: seal-use deploy hosecloud sync ${signKey} --dry-run --corp ${context.corp.id}`); return { integration: redactIntegrationSecrets(nextIntegration) @@ -198,10 +205,18 @@ export const deployCapabilities = [ name: "sealDeployHosecloudSync", description: "一键将 Seal AI 审核配置同步发布到合思费控审批流", parameters: z.object({ - signKey: z.string().describe("合思集成 sign-key") + signKey: z.string().describe("合思集成 sign-key"), + dryRun: z.boolean().optional().describe("只预览待同步的消息名称、回调地址和模式,不执行同步"), + confirm: z.boolean().optional().describe("明确确认同步到合思;CLI 使用 --yes 或 --confirm") }), - handler: async (client: KyInstance, params: { signKey: string }, context: CapabilityContext) => { - const config = await api.getApprovalStylePreferences(client); + handler: async (client: KyInstance, params: { signKey: string; dryRun?: boolean; confirm?: boolean }, context: CapabilityContext) => { + if (!params.dryRun && params.confirm !== true) { + throw confirmationRequired( + "Refusing to synchronize Hose outbound messages without --yes or --confirm. Use --dry-run to preview first.", + `seal-use deploy hosecloud sync ${params.signKey} --dry-run --corp ${context.corp.id}` + ); + } + const config = await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences); const integration = listHoseIntegrations(config).find( (item) => item.signKey === params.signKey ); @@ -210,13 +225,22 @@ export const deployCapabilities = [ } const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, ""); const messageName = integration.outboundName ?? "SealAI 审批"; - const result = await api.syncHosecloudOutbound(client, { + const payload = { signKey: params.signKey, webhookUrl: buildOutboundWebhookUrl(context.corp, params.signKey), completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`, messageName, mode: integration.mode ?? "assisted" - }); + }; + if (params.dryRun) { + return { + ...mutationPreview(context, "api/hosecloud/outbound-config/sync", null, payload, 1), + signKey: params.signKey, + remoteStateKnown: false, + note: "仅预览将同步的消息名称、回调地址和模式;合思远端当前配置尚未读取。" + }; + } + const result = await api.syncHosecloudOutbound(client, payload); console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`); console.error(`👉 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${messageName}"。`); diff --git a/src/domains/seal/hose-outbound-replay.test.ts b/src/domains/seal/hose-outbound-replay.test.ts index bb74c22..71a4295 100644 --- a/src/domains/seal/hose-outbound-replay.test.ts +++ b/src/domains/seal/hose-outbound-replay.test.ts @@ -140,6 +140,80 @@ describe("selectMatchingOutboundLog", () => { ]; expect(selectMatchingOutboundLog(emptyLogs)).toBeUndefined(); }); + + test("an unavailable iteration never falls back to another one", () => { + expect(selectMatchingOutboundLog(mockLogs, { rejectionNum: 99 })).toBeUndefined(); + expect(selectMatchingOutboundLog(mockLogs, { rejectionNum: 0 })).toBeUndefined(); + }); + + test("an explicit iteration also constrains message and callback matching", () => { + expect(selectMatchingOutboundLog(mockLogs, { + messageId: "ID01WahQ3gbhMP", rejectionNum: 3 + })).toBeUndefined(); + expect(selectMatchingOutboundLog(mockLogs, { + recordId: "01a08f69-ad6f-76b8-8c81-81190544150d", rejectionNum: 3 + })).toBeUndefined(); + }); + + test("timestamp matching has a strict 60-second window and preserves clock-skew tolerance", () => { + const time = mockLogs[1]!.createTime; + const invoking = [mockLogs[1]!]; + for (const delta of [0, 59_999, -1000]) { + expect(selectMatchingOutboundLog(invoking, { + recordId: "unknown-record", recordCreatedAt: time + delta + })?.id).toBe("log-invoking-3"); + } + for (const delta of [60_000, 864_000_000, -1001]) { + expect(selectMatchingOutboundLog(invoking, { + recordId: "unknown-record", recordCreatedAt: time + delta + })).toBeUndefined(); + } + expect(selectMatchingOutboundLog(invoking, { recordCreatedAt: NaN })).toBeUndefined(); + }); + + test("timestamp matching selects the nearest event within the requested iteration", () => { + const recordCreatedAt = 100_000; + const logs: HoseOutboundLogItem[] = [ + { ...mockLogs[1]!, id: "different-iteration", createTime: 99_999 }, + { ...mockLogs[3]!, id: "near", createTime: 95_000 }, + { ...mockLogs[3]!, id: "far", createTime: 70_000 } + ]; + expect(selectMatchingOutboundLog(logs, { + recordCreatedAt, rejectionNum: 2 + })?.id).toBe("near"); + }); + + test("a requested record without matching evidence is unresolved", () => { + expect(selectMatchingOutboundLog(mockLogs, { recordId: "unknown-record" })).toBeUndefined(); + }); + + test("latest selection does not depend on input order or mutate the log list", () => { + const reversed = [...mockLogs].reverse(); + const ids = reversed.map((item) => item.id); + expect(selectMatchingOutboundLog(reversed)?.id).toBe("log-invoking-3"); + expect(reversed.map((item) => item.id)).toEqual(ids); + }); + + test("callback lookup stays on the callback's document and node", () => { + const callback = mockLogs[2]!; + const unrelated = { + ...mockLogs[3]!, id: "other-node", createTime: callback.createTime - 1, + request: { ...mockLogs[3]!.request, nodeId: "FLOW:other-node" } + }; + expect(selectMatchingOutboundLog([unrelated, ...mockLogs], { + recordId: "01a08f69-ad6f-76b8-8c81-81190544150d" + })?.id).toBe("log-invoking-2"); + }); + + test("a callback for a different iteration cannot be paired with an older event on the same node", () => { + const recordId = "01a0a43c-521b-778c-b11b-238c8496dfec"; + const old = { + ...mockLogs[3]!, request: { ...mockLogs[3]!.request, nodeId: mockLogs[1]!.request!.nodeId } + }; + expect(selectMatchingOutboundLog([mockLogs[0]!, mockLogs[1]!, old], { + recordId, rejectionNum: 2 + })).toBeUndefined(); + }); }); describe("validateHoseOutboundReplaySafety", () => { diff --git a/src/domains/seal/hose-outbound-replay.ts b/src/domains/seal/hose-outbound-replay.ts index 6f3745c..cd5ec67 100644 --- a/src/domains/seal/hose-outbound-replay.ts +++ b/src/domains/seal/hose-outbound-replay.ts @@ -53,7 +53,13 @@ export function selectMatchingOutboundLog( rejectionNum?: number; } = {} ): HoseOutboundLogItem | undefined { - const invokingLogs = logs.filter((item) => item.type === "INVOKING"); + // An explicit iteration is a constraint on every matching strategy, including + // callback and timestamp lookups; it must never fall back to a different one. + const allInvokingLogs = logs.filter((item) => item.type === "INVOKING") + .sort((a, b) => b.createTime - a.createTime); + const invokingLogs = allInvokingLogs.filter((item) => + (options.rejectionNum === undefined || item.request?.rejectionNum === options.rejectionNum) + ); if (invokingLogs.length === 0) { return undefined; } @@ -73,29 +79,36 @@ export function selectMatchingOutboundLog( ); if (callbackWithRecordId) { // Find the invoking event right before this callback - const priorInvoking = invokingLogs.find( - (item) => item.createTime <= callbackWithRecordId.createTime + const priorInvoking = allInvokingLogs.find( + (item) => item.createTime <= callbackWithRecordId.createTime && + (!callbackWithRecordId.request?.flowId || + (item.request?.flowId ?? item.flowId?.id) === callbackWithRecordId.request.flowId) && + (!callbackWithRecordId.request?.nodeId || item.request?.nodeId === callbackWithRecordId.request.nodeId) ); - if (priorInvoking) { - return priorInvoking; - } - } - - // Fallback: match by timestamp delta (< 60s) - if (options.recordCreatedAt) { - const closestByTime = invokingLogs - .filter((item) => item.createTime <= options.recordCreatedAt! + 1000) - .sort( - (a, b) => - Math.abs(options.recordCreatedAt! - a.createTime) - - Math.abs(options.recordCreatedAt! - b.createTime) - )[0]; - if (closestByTime) { - return closestByTime; - } + return options.rejectionNum === undefined || priorInvoking?.request?.rejectionNum === options.rejectionNum + ? priorInvoking + : undefined; } } + // Fallback: match by timestamp delta (< 60s) + if (options.recordCreatedAt !== undefined) { + const recordCreatedAt = options.recordCreatedAt; + if (!Number.isFinite(recordCreatedAt)) return undefined; + const closestByTime = invokingLogs + .filter((item) => item.createTime <= recordCreatedAt + 1000 && + Math.abs(recordCreatedAt - item.createTime) < 60_000) + .sort( + (a, b) => + Math.abs(recordCreatedAt - a.createTime) - + Math.abs(recordCreatedAt - b.createTime) + )[0]; + return closestByTime; + } + + // A requested record with no callback or usable timestamp is unresolved. + if (options.recordId) return undefined; + // 3. Match by rejectionNum if provided if (options.rejectionNum !== undefined) { const matchRejection = invokingLogs.find( @@ -221,7 +234,7 @@ export async function executeHoseOutboundReplay(options: HoseOutboundReplayOptio if (!selectedLog || !selectedLog.request?.messageId) { throw validationError( - `在合思出站日志中未找到单据「${sn}」的有效出站记录 (type: INVOKING)。\n` + + `在合思出站日志中未找到单据「${sn}」${options.rejectionNum !== undefined ? `第 ${options.rejectionNum} 轮` : ""}的匹配出站记录 (type: INVOKING)。\n` + `请确认该单据在合思审批流中是否触发过出站消息(EBot节点),或显式提供 --message-id 参数。` ); } diff --git a/src/domains/seal/types.ts b/src/domains/seal/types.ts index ca70be5..ad26735 100644 --- a/src/domains/seal/types.ts +++ b/src/domains/seal/types.ts @@ -598,6 +598,7 @@ export const ThinkingDepthPreferenceSchema = z.object({ export const HosecloudConfigInputSchema = z.object({ dryRun: z.boolean().optional(), + confirm: z.boolean().optional(), signKey: z.string().min(1).optional(), outboundName: z.string().optional(), specificationId: z.string().optional(),