Close the AGENTS.md "Safety Guardrail & Mutation Preview" coverage gap: every remote-mutating command now supports --dry-run returning structured JSON with preview: true, without executing the mutation. - Domain capabilities gain an optional dryRun param and preview handlers: sealUserCreate/ResetPassword/Delete/Activate/DelegationCreate, sealDelegationRevoke, sealApprovalRuleCreate/Update/Delete/ VersionPublish, sealSimulationBatchClean, sealInsightRecordAnalyze. Previews reuse the shared mutationPreview() diff shape; reads (GET) are allowed to build the before/after, writes never fire. - CLI wiring: users create/delegation/reset-password/delete, rules create/update/delete/publish, simulation delete, analytics analyze, auth link revoke pass dryRun; dry-run bypasses the --yes gate (webhook delete pattern); corps mark previews the local config tag change without writing it. - Shared dryRunOption() helper in parser.ts; help registry documents --dry-run on all covered commands; cli-protocol.md §3 example list updated; cli.md and embedded skill regenerated. - New src/cli/commands/dry-run-gates.test.ts pins the contract: preview JSON on stdout, zero mutating requests (GET-only where reads are needed), config untouched for local previews. Local user-config writes (corps switch/rename, config mode/test-dir/ lint) stay outside this contract: they are reversible local edits with no upstream effect.
1892 lines
66 KiB
TypeScript
1892 lines
66 KiB
TypeScript
import { afterEach, describe, expect, test } from "bun:test";
|
|
import { KyInstance } from "ky";
|
|
import { z } from "zod";
|
|
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 "../rules/mapping.js";
|
|
import { buildRulePushPlan, findSealCapability, sealCapabilities } from "../capabilities.js";
|
|
|
|
type CapabilityHandler = (
|
|
client: KyInstance,
|
|
params: Record<string, unknown>,
|
|
context: { corp: CorpConfig }
|
|
) => Promise<unknown>;
|
|
|
|
const ORIGINAL_TOKEN_STORE = process.env.SEAL_HOME_TOKEN_STORE;
|
|
const tempDirs: string[] = [];
|
|
|
|
afterEach(() => {
|
|
if (ORIGINAL_TOKEN_STORE === undefined) {
|
|
delete process.env.SEAL_HOME_TOKEN_STORE;
|
|
} else {
|
|
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_TOKEN_STORE;
|
|
}
|
|
|
|
for (const dir of tempDirs.splice(0)) {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
describe("sealCapabilities", () => {
|
|
test("exposes concrete JSON schemas for parameterized tools", () => {
|
|
const createRule = sealCapabilities.find((tool) => tool.name === "sealApprovalRuleCreate");
|
|
expect(createRule).toBeDefined();
|
|
|
|
const schema = z.toJSONSchema(createRule!.parameters) as {
|
|
properties?: Record<string, unknown>;
|
|
required?: string[];
|
|
};
|
|
|
|
expect(Object.keys(schema.properties ?? {})).toEqual([
|
|
"description",
|
|
"scope",
|
|
"strictness",
|
|
"dryRun"
|
|
]);
|
|
expect(schema.required).toEqual(["description", "scope", "strictness"]);
|
|
});
|
|
|
|
test("includes the approval context aggregation tool", () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalContextGet");
|
|
expect(tool).toBeDefined();
|
|
});
|
|
|
|
test("includes the session diagnostic tool", () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealSessionGet");
|
|
expect(tool).toBeDefined();
|
|
});
|
|
|
|
test("includes the delegation management tools", () => {
|
|
const listTool = sealCapabilities.find((item) => item.name === "sealDelegationList");
|
|
const createCapability = sealCapabilities.find((item) => item.name === "sealDelegationCreate");
|
|
const revokeTool = sealCapabilities.find((item) => item.name === "sealDelegationRevoke");
|
|
|
|
expect(listTool).toBeDefined();
|
|
expect(createCapability).toBeDefined();
|
|
expect(revokeTool).toBeDefined();
|
|
});
|
|
|
|
test("includes user management tools", () => {
|
|
const createCapability = sealCapabilities.find((item) => item.name === "sealUserCreate");
|
|
const resetTool = sealCapabilities.find((item) => item.name === "sealUserResetPassword");
|
|
const getTool = sealCapabilities.find((item) => item.name === "sealUserGet");
|
|
const searchTool = sealCapabilities.find((item) => item.name === "sealUserSearch");
|
|
const deleteTool = sealCapabilities.find((item) => item.name === "sealUserDelete");
|
|
const activateTool = sealCapabilities.find((item) => item.name === "sealUserActivate");
|
|
const userDelegationTool = sealCapabilities.find((item) => item.name === "sealUserDelegationCreate");
|
|
|
|
expect(createCapability).toBeDefined();
|
|
expect(resetTool).toBeDefined();
|
|
expect(getTool).toBeDefined();
|
|
expect(searchTool).toBeDefined();
|
|
expect(deleteTool).toBeDefined();
|
|
expect(activateTool).toBeDefined();
|
|
expect(userDelegationTool).toBeDefined();
|
|
});
|
|
|
|
test("includes read-only contacts directory tools", () => {
|
|
expect(sealCapabilities.find((item) => item.name === "sealContactsDepartmentsRootList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealContactsDepartmentGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealContactsDepartmentChildrenList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealContactsDepartmentUsersList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealContactsLastSyncTimeGet")).toBeDefined();
|
|
});
|
|
|
|
test("includes the read-only insight stats and analytics tools", () => {
|
|
expect(sealCapabilities.find((item) => item.name === "sealInsightStatsGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealInsightRisksByTagGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealInsightPerformanceGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealInsightRecordAnalyze")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealInsightExport")).toBeDefined();
|
|
});
|
|
|
|
test("includes read-only financial data tools", () => {
|
|
expect(sealCapabilities.find((item) => item.name === "sealExpensesList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealInvoicesList")).toBeDefined();
|
|
});
|
|
|
|
test("includes the Feishu simulation approval definition tool", () => {
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationFeishuApprovalDefinitionsList")).toBeDefined();
|
|
});
|
|
|
|
test("includes system configuration tools", () => {
|
|
expect(sealCapabilities.find((item) => item.name === "sealLlmConfigGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealLlmProvidersList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealPermissionsAvailableList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealPermissionsConfigsList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealBillingStatusGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealBillingPlansList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealBillingFeaturesList")).toBeDefined();
|
|
});
|
|
|
|
test("includes Webhook management tools", () => {
|
|
expect(sealCapabilities.find((item) => item.name === "sealWebhookList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealWebhookGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealWebhookAdd")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealWebhookUpdate")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealWebhookDelete")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealWebhookReplay")).toBeDefined();
|
|
});
|
|
|
|
test("includes deploy hosecloud tools", () => {
|
|
expect(sealCapabilities.find((item) => item.name === "sealDeployHosecloudRequirements")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealDeployHosecloudList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealDeployHosecloudGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealDeployHosecloudStatus")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealDeployHosecloudConfigure")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealDeployHosecloudSync")).toBeDefined();
|
|
});
|
|
|
|
test("includes preference and thinking-depth tools", () => {
|
|
expect(sealCapabilities.find((item) => item.name === "sealPreferenceGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealPreferenceDecisionUpdate")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealPreferenceThinkingDepthSet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealPreferenceThinkingDepthPoliciesList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealPreferenceThinkingDepthPoliciesUpsert")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealPreferenceThinkingDepthPoliciesRemove")).toBeDefined();
|
|
});
|
|
|
|
test("includes simulation wait, clean, specifications tools and approval run stats/count", () => {
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationBatchWait")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationBatchClean")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationSpecificationsList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealApprovalRunsStats")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealApprovalRunsCount")).toBeDefined();
|
|
});
|
|
|
|
test("includes the approval search tool", () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalSearch");
|
|
expect(tool).toBeDefined();
|
|
});
|
|
|
|
test("approval rules list can return count only", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRulesList");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(fakeRulesClient(), { countOnly: true }, fakeContext());
|
|
|
|
expect(result).toEqual({ count: 2 });
|
|
});
|
|
|
|
test("approval rules list treats limit zero as count only", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRulesList");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(fakeRulesClient(), { fields: ["id"], limit: 0 }, fakeContext());
|
|
|
|
expect(result).toEqual({ count: 2 });
|
|
});
|
|
|
|
test("approval rules list can project lightweight fields", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRulesList");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeRulesClient(),
|
|
{ fields: ["id", "code", "status", "strictness", "scope"], limit: 1 },
|
|
fakeContext()
|
|
) as { count: number; rules: Array<Record<string, unknown>> };
|
|
|
|
expect(result.count).toBe(2);
|
|
expect(result.rules).toEqual([
|
|
{
|
|
id: "rule-1",
|
|
code: "0029",
|
|
status: "active",
|
|
strictness: "MUST_FOLLOW",
|
|
scope: "travel"
|
|
}
|
|
]);
|
|
expect(result.rules[0]).not.toHaveProperty("description");
|
|
});
|
|
|
|
test("approval rules list renders timestamps in standard Beijing ISO format", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRulesList");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
|
|
const full = await handler(fakeRulesClient(), {}, fakeContext()) as {
|
|
rules: Array<Record<string, unknown>>;
|
|
};
|
|
expect(full.rules[0]?.createdAt).toBe("2026-06-08T13:56:04+08:00");
|
|
expect(full.rules[0]?.updatedAt).toBe("2026-06-08T13:56:04+08:00");
|
|
expect(full.rules[1]?.createdAt).toBe("2026-06-08T13:56:04+08:00");
|
|
|
|
const projected = await handler(
|
|
fakeRulesClient(),
|
|
{ fields: ["id", "createdAt"], limit: 1 },
|
|
fakeContext()
|
|
) as { rules: Array<Record<string, unknown>> };
|
|
expect(projected.rules[0]).toEqual({
|
|
id: "rule-1",
|
|
createdAt: "2026-06-08T13:56:04+08:00"
|
|
});
|
|
});
|
|
|
|
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 = sealCapabilities.find((item) => item.name === "sealApprovalRuleGet");
|
|
expect(tool).toBeDefined();
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const context = { corp: { ...fakeContext().corp, testCorpId: "t-corp-1" } };
|
|
|
|
const draft = await handler(fakeRulesClient(), { code: "29" }, context) as Record<string, unknown>;
|
|
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 = sealCapabilities.find((item) => item.name === "sealApprovalRuleUpdate");
|
|
expect(tool).toBeDefined();
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeRuleUpdateClient(1780898164536),
|
|
{ ruleId: "29", description: "当单据金额超过 5000 元时必须提供发票原件与行程证明。" },
|
|
fakeContext()
|
|
) as Record<string, unknown>;
|
|
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 = sealCapabilities.find((item) => item.name === "sealApprovalRuleUpdate");
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
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 = sealCapabilities.find((item) => item.name === "sealApprovalRuleUpdate");
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeRuleUpdateClient(1780898164536),
|
|
{ ruleId: "29", description: "当单据金额超过 5000 元时必须提供发票原件与行程证明。", ifUnchanged: "2026-06-08T13:56:04+08:00" },
|
|
fakeContext()
|
|
) as Record<string, unknown>;
|
|
expect(result).toMatchObject({ id: "rule-1" });
|
|
});
|
|
|
|
test("sealApprovalRunDiagnose aggregates document, result, cited rules, and version snapshot", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunDiagnose");
|
|
expect(tool).toBeDefined();
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
|
|
const byRecord = await handler(fakeDiagnoseClient(), { recordId: "run-1" }, fakeContext()) as Record<string, any>;
|
|
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<string, any>;
|
|
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 = sealCapabilities.find((item) => item.name === "sealApprovalRulesClear");
|
|
expect(tool).toBeDefined();
|
|
|
|
const client = fakeClearRulesClient();
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(client, { dryRun: true }, fakeContext()) as {
|
|
dryRun: boolean;
|
|
beforeCount: number;
|
|
deleted: number;
|
|
afterCount: number;
|
|
};
|
|
|
|
expect(result).toMatchObject({
|
|
dryRun: true,
|
|
beforeCount: 2,
|
|
deleted: 0,
|
|
afterCount: 2
|
|
});
|
|
expect(await countFakeRules(client)).toBe(2);
|
|
});
|
|
|
|
test("approval rules clear deletes all draft rules", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRulesClear");
|
|
expect(tool).toBeDefined();
|
|
|
|
const client = fakeClearRulesClient();
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(client, {}, fakeContext()) as {
|
|
dryRun: boolean;
|
|
beforeCount: number;
|
|
deleted: number;
|
|
afterCount: number;
|
|
failed: unknown[];
|
|
};
|
|
|
|
expect(result).toMatchObject({
|
|
dryRun: false,
|
|
beforeCount: 2,
|
|
deleted: 2,
|
|
afterCount: 0,
|
|
failed: []
|
|
});
|
|
expect(await countFakeRules(client)).toBe(0);
|
|
});
|
|
|
|
test("preference dry run reads config without patching it", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealPreferenceDecisionUpdate");
|
|
expect(tool).toBeDefined();
|
|
let patched = false;
|
|
const client = {
|
|
get: () => ({
|
|
json: async () => ({
|
|
data: {
|
|
decisionPreferences: {
|
|
explicitApprove: "old",
|
|
explicitReject: "reject",
|
|
exemptApprove: "exempt",
|
|
review: "review"
|
|
},
|
|
integrations: []
|
|
}
|
|
})
|
|
}),
|
|
patch: () => {
|
|
patched = true;
|
|
throw new Error("preview must not patch");
|
|
}
|
|
} as unknown as KyInstance;
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(client, { explicitApprove: "new", dryRun: true }, fakeContext()) as {
|
|
preview: boolean;
|
|
targetUrl: string;
|
|
changesDiff: { after: { decisionPreferences: { explicitApprove: string } } };
|
|
};
|
|
|
|
expect(result.preview).toBe(true);
|
|
expect(result.targetUrl).toBe("https://seal.test/api/v1/agent/ai-approval/config");
|
|
expect(result.changesDiff.after.decisionPreferences.explicitApprove).toBe("new");
|
|
expect(patched).toBe(false);
|
|
});
|
|
|
|
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(sealCapabilities.find((item) => item.name === "sealApprovalRunsSearch")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealApprovalRunsSummary")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationBatchRecordsGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealApprovalRunLangfuseBridgeGet")).toBeDefined();
|
|
});
|
|
|
|
test("can find tools by name in sealCapabilities", () => {
|
|
expect(findSealCapability("sealApprovalRuleCreate")).toBeDefined();
|
|
expect(findSealCapability("non_existent_tool")).toBeUndefined();
|
|
});
|
|
|
|
test("approval run search omits bridge unless requested", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunsSearch");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(fakeApprovalRunsClient(), { limit: 1 }, fakeContext());
|
|
|
|
expect(result).not.toHaveProperty("bridge");
|
|
expect(result).toHaveProperty("records");
|
|
});
|
|
|
|
test("approval run search can filter by extracted human result", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunsSearch");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ humanResult: "驳回", limit: 10 },
|
|
fakeContext()
|
|
) as {
|
|
records: Array<{
|
|
sourceDocumentSN?: string;
|
|
humanResult?: string;
|
|
humanResultPath?: string;
|
|
}>;
|
|
};
|
|
|
|
expect(result.records).toHaveLength(1);
|
|
expect(result.records[0]).toMatchObject({
|
|
sourceDocumentSN: "B26001965",
|
|
humanResult: "驳回",
|
|
humanResultPath: "result.manualApproval.result"
|
|
});
|
|
});
|
|
|
|
test("approval run search maps rejected human result to manual approval status", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunsSearch");
|
|
expect(tool).toBeDefined();
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
await handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{
|
|
humanResult: "驳回",
|
|
startDate: "1774972800000",
|
|
endDate: "1781020799999",
|
|
limit: 50
|
|
},
|
|
fakeContext()
|
|
);
|
|
|
|
expect(requests[0]).toContain("startDate=1774972800000");
|
|
expect(requests[0]).toContain("endDate=1781020799999");
|
|
expect(requests[0]).toContain("manualApprovalStatus%5B0%5D=TERMINATED");
|
|
});
|
|
|
|
test("approval run search forwards query as API search parameter", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunsSearch");
|
|
expect(tool).toBeDefined();
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
await handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{
|
|
query: "B26001965",
|
|
startDate: "1774972800000",
|
|
endDate: "1781020799999",
|
|
limit: 50
|
|
},
|
|
fakeContext()
|
|
);
|
|
|
|
expect(requests[0]).toContain("search=B26001965");
|
|
expect(requests[0]).toContain("startDate=1774972800000");
|
|
expect(requests[0]).toContain("endDate=1781020799999");
|
|
});
|
|
|
|
test("approval run get returns stable aliases for document concepts", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeContext()
|
|
) as {
|
|
aliases?: {
|
|
originalDocumentData?: { path?: string; frontendLabel?: string };
|
|
aiDocumentFields?: { path?: string; frontendLabel?: string };
|
|
aiDocument?: { path?: string; aliasOf?: string };
|
|
sourceDocument?: { path?: string };
|
|
aiResult?: { path?: string };
|
|
aiAuditLog?: { path?: string };
|
|
manualApproval?: { path?: string };
|
|
};
|
|
};
|
|
|
|
expect(result.aliases).toMatchObject({
|
|
originalDocumentData: { path: "document", frontendLabel: "单据原始数据" },
|
|
aiDocumentFields: { path: "document.fields", frontendLabel: "AI 看的单据" },
|
|
aiDocument: { path: "document.fields", aliasOf: "aiDocumentFields" },
|
|
sourceDocument: { path: "sourceExtendData.hosecloudViewUrl" },
|
|
aiResult: { path: "result" },
|
|
aiAuditLog: { path: "pipelineData.logs" },
|
|
manualApproval: { path: "manualApprovalRecord" }
|
|
});
|
|
});
|
|
|
|
test("approval run get can return selected fields only", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", fields: "metadata,document.fields,result.summary" },
|
|
fakeContext()
|
|
) as {
|
|
metadata?: { recordId?: string };
|
|
document?: { fields?: unknown[] };
|
|
result?: { summary?: string; manualApproval?: unknown };
|
|
pipelineData?: unknown;
|
|
};
|
|
|
|
expect(result.metadata?.recordId).toBe("run-1");
|
|
expect(result.document?.fields).toHaveLength(3);
|
|
expect(result.result?.summary).toBe("费用存在风险");
|
|
expect(result.result?.manualApproval).toBeUndefined();
|
|
expect(result.pipelineData).toBeUndefined();
|
|
});
|
|
|
|
test("approval run get can return summary preset", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", summary: true },
|
|
fakeContext()
|
|
) as { aiResult?: { decision?: string }; manualResult?: string; document?: { title?: string } };
|
|
|
|
expect(result.aiResult?.decision).toBe("驳回");
|
|
expect(result.manualResult).toBe("驳回");
|
|
expect(result.document?.title).toBe("差旅报销单");
|
|
});
|
|
|
|
test("approval run pick supports sn latest and compact candidate fields", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunPick");
|
|
expect(tool).toBeDefined();
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{ sn: "B26001965", latest: true },
|
|
fakeContext()
|
|
) as { matched: number; records: Array<{ recordId?: string; aiDecision?: string; aiSummary?: string }> };
|
|
|
|
expect(requests[0]).toContain("sourceDocumentSN=B26001965");
|
|
expect(result.matched).toBe(1);
|
|
expect(result.records[0]).toMatchObject({
|
|
recordId: "run-1",
|
|
aiDecision: "驳回",
|
|
aiSummary: "费用存在风险"
|
|
});
|
|
});
|
|
|
|
test("approval run attachments extracts compact attachment metadata", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunAttachmentsGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeContext()
|
|
) as { count: number; attachments: Array<Record<string, unknown>> };
|
|
|
|
expect(result.count).toBe(2);
|
|
expect(result.attachments).toContainEqual(expect.objectContaining({
|
|
kind: "attachment",
|
|
fileName: "receipt.pdf",
|
|
fileId: "file-1",
|
|
mimeType: "application/pdf",
|
|
ossPath: "oss://bucket/receipt.pdf"
|
|
}));
|
|
expect(result.attachments).toContainEqual(expect.objectContaining({
|
|
kind: "invoice",
|
|
fileName: "invoice.png",
|
|
url: "https://signed.example/invoice.png"
|
|
}));
|
|
});
|
|
|
|
test("approval run cited rules extracts rule application details", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunCitedRulesGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeContext()
|
|
) as { count: number; rules: Array<Record<string, unknown>> };
|
|
|
|
expect(result.count).toBe(1);
|
|
expect(result.rules[0]).toMatchObject({
|
|
code: "0038",
|
|
runtimeRuleId: "rule-38",
|
|
ruleCode: "0038",
|
|
versionNumber: 16,
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW",
|
|
checkResult: "failed"
|
|
});
|
|
});
|
|
|
|
test("approval run cited rules attaches mappedProdCode when test snapshot exists", async () => {
|
|
const mappingDir = mkdtempSync(join(tmpdir(), "seal-mapping-cited-"));
|
|
process.env.SEAL_USE_MAPPINGS_DIR = mappingDir;
|
|
try {
|
|
saveRuleMappingSnapshot({
|
|
syncedAt: "2026-10-10T10:00:00+08:00",
|
|
source: { id: "corp-prod", name: "Prod Corp" },
|
|
target: { id: "corp-test", name: "Test Corp", publishedVersionNumber: 16, rulesCount: 1 },
|
|
versionMapping: {
|
|
sourceProdVersionNumber: 22,
|
|
sourceProdVersionName: "Prod v22",
|
|
targetTestVersionNumber: 16,
|
|
targetTestVersionName: "Test v16"
|
|
},
|
|
ruleMapping: [{
|
|
index: 0,
|
|
sourceRuleId: "prod-rule-17",
|
|
sourceRuleCode: 17,
|
|
targetRuleId: "test-rule-38",
|
|
targetRuleCode: "0038",
|
|
description: "Prod rule 17",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
}]
|
|
});
|
|
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunCitedRulesGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const context = { corp: { ...fakeContext().corp, id: "corp-test", environment: "test" as const } };
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
context
|
|
) as { count: number; rules: Array<Record<string, unknown>> };
|
|
|
|
expect(result.rules[0]).toMatchObject({
|
|
code: "0038",
|
|
mappedProdCode: "0017",
|
|
mappedProdRuleId: "prod-rule-17"
|
|
});
|
|
} finally {
|
|
delete process.env.SEAL_USE_MAPPINGS_DIR;
|
|
}
|
|
});
|
|
|
|
test("approval run document summary returns key fields without raw payload", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunDocumentSummaryGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeContext()
|
|
) as { document?: { amount?: unknown; expenseType?: unknown }; invoices?: Array<Record<string, unknown>> };
|
|
|
|
expect(result.document?.amount).toBe("100.00");
|
|
expect(result.document?.expenseType).toBe("差旅费");
|
|
expect(result.invoices?.[0]).toMatchObject({
|
|
buyer: "甲方公司",
|
|
seller: "乙方公司",
|
|
amount: 100
|
|
});
|
|
});
|
|
|
|
test("approval run result can return summary only", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunResultGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", summary: true },
|
|
fakeContext()
|
|
) as {
|
|
decision?: string;
|
|
summary?: string;
|
|
riskPointCount?: number;
|
|
matchedRuleCount?: number;
|
|
traceId?: string;
|
|
};
|
|
|
|
expect(result).toMatchObject({
|
|
decision: "驳回",
|
|
summary: "费用存在风险",
|
|
riskPointCount: 2,
|
|
matchedRuleCount: 1,
|
|
traceId: "trace-1"
|
|
});
|
|
});
|
|
|
|
test("approval run url returns Seal result and Hose document links by recordId", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeHoseContext()
|
|
) as {
|
|
url?: string;
|
|
sealResultUrl?: string;
|
|
type?: string;
|
|
mode?: string;
|
|
hoseDomain?: string;
|
|
documentUrl?: string;
|
|
hoseDocumentUrl?: string;
|
|
recordId?: string;
|
|
sourceDocumentSN?: string;
|
|
enterpriseAssistUrl?: string;
|
|
enterpriseUrl?: string;
|
|
hoseEnterpriseUrl?: string;
|
|
};
|
|
|
|
expect(result).toMatchObject({
|
|
url: "https://hose-corp-a.sealai.cc/approval-result/run-1",
|
|
sealResultUrl: "https://hose-corp-a.sealai.cc/approval-result/run-1",
|
|
type: "seal_result",
|
|
mode: "direct",
|
|
hoseDomain: "https://app.ekuaibao.com",
|
|
documentUrl: "https://app.ekuaibao.com/web/thirdparty.html",
|
|
hoseDocumentUrl: "https://app.ekuaibao.com/web/thirdparty.html",
|
|
recordId: "run-1",
|
|
sourceDocumentSN: "B26001965"
|
|
});
|
|
expect(result.enterpriseAssistUrl).toBeUndefined();
|
|
expect(result.enterpriseUrl).toBeUndefined();
|
|
expect(result.hoseEnterpriseUrl).toBeUndefined();
|
|
});
|
|
|
|
test("approval run url supports type=hose-document", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", type: "hose-document" },
|
|
fakeHoseContext()
|
|
) as {
|
|
url?: string;
|
|
sealResultUrl?: string;
|
|
hoseDocumentUrl?: string;
|
|
type?: string;
|
|
mode?: string;
|
|
};
|
|
|
|
expect(result.type).toBe("hose_document");
|
|
expect(result.mode).toBe("direct");
|
|
expect(result.url).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
|
expect(result.hoseDocumentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
|
expect(result.sealResultUrl).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
|
|
});
|
|
|
|
test("approval run url synthesizes hoseDocumentUrl from source.domain and sourceDocumentId when hosecloudViewUrl is missing", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-2" },
|
|
fakeHoseContext()
|
|
) as {
|
|
hoseDocumentUrl?: string;
|
|
documentUrl?: string;
|
|
sealResultUrl?: string;
|
|
missing?: Record<string, string>;
|
|
};
|
|
|
|
const expectedHoseUrl = "https://app.ekuaibao.com/web/thirdparty.html?ekbCorpId=hose-corp-a&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=doc-source-2&backlogId=#/backlogDetail/false/doc-source-2";
|
|
expect(result.hoseDocumentUrl).toBe(expectedHoseUrl);
|
|
expect(result.documentUrl).toBe(expectedHoseUrl);
|
|
expect(result.missing?.hoseDocumentUrl).toBeUndefined();
|
|
});
|
|
|
|
test("approval run url supports auto-login for hose-document", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
|
expect(tool).toBeDefined();
|
|
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-2", type: "hose-document", autoLogin: true },
|
|
fakeHoseContext()
|
|
) as {
|
|
url?: string;
|
|
hoseSsoUrl?: string;
|
|
type?: string;
|
|
mode?: string;
|
|
};
|
|
|
|
const expectedSsoUrl = "https://app.ekuaibao.com/web/thirdparty.html?accessToken=close-token&ekbCorpId=hose-corp-a&pageType=form&overdueTokenRedirect=&noPathCache=true&flowId=doc-source-2&backlogId=#/backlogDetail/false/doc-source-2";
|
|
expect(result.type).toBe("hose_document");
|
|
expect(result.mode).toBe("auto_login");
|
|
expect(result.url).toBe(expectedSsoUrl);
|
|
expect(result.hoseSsoUrl).toBe(expectedSsoUrl);
|
|
});
|
|
|
|
test("approval run url throws error without a document lookup", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
await expect(
|
|
handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{},
|
|
fakeHoseContext()
|
|
)
|
|
).rejects.toThrow("recordId, sourceDocumentSN, or sourceDocumentId is required");
|
|
expect(requests).toEqual([]);
|
|
});
|
|
|
|
test("approval run url can resolve by sourceDocumentSN", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
|
expect(tool).toBeDefined();
|
|
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{ sourceDocumentSN: "B26001965" },
|
|
fakeHoseContext()
|
|
) as { documentUrl?: string; url?: string; type?: string; mode?: string };
|
|
|
|
expect(requests[0]).toContain("search=B26001965");
|
|
expect(requests[1]).toBe("api/v1/approvals/run-1");
|
|
expect(result.documentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
|
expect(result.type).toBe("seal_result");
|
|
expect(result.mode).toBe("direct");
|
|
expect(result.url).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
|
|
});
|
|
|
|
test("approval run url returns auto_login link with identity, expiration, and warning when autoLogin=true", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
|
expect(tool).toBeDefined();
|
|
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = (await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", autoLogin: true, expiresIn: 3600 },
|
|
fakeHoseContext()
|
|
)) as {
|
|
url?: string;
|
|
ssoUrl?: string;
|
|
type?: string;
|
|
mode?: string;
|
|
expiresIn?: number;
|
|
warning?: string;
|
|
identity?: { staffId?: string };
|
|
};
|
|
|
|
expect(result.type).toBe("seal_result");
|
|
expect(result.mode).toBe("auto_login");
|
|
expect(result.expiresIn).toBe(3600);
|
|
expect(result.url).toContain("/api/auth/oauth2/session/oem-hosecloud?token=close-token");
|
|
expect(result.url).toContain("path=%2Fapproval-result%2Frun-1");
|
|
expect(result.warning).toContain("安全警示");
|
|
expect(result.identity?.staffId).toBe("staff-a");
|
|
});
|
|
|
|
test("approval run url supports legacy hoseSso=true with explicit hose attribute naming", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
|
expect(tool).toBeDefined();
|
|
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = (await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", hoseSso: true },
|
|
fakeHoseContext()
|
|
)) as {
|
|
type?: string;
|
|
mode?: string;
|
|
url?: string;
|
|
hoseDocumentUrl?: string;
|
|
hoseEnterpriseUrl?: string;
|
|
};
|
|
|
|
expect(result.type).toBe("seal_result");
|
|
expect(result.mode).toBe("auto_login");
|
|
expect(result.url).toContain("/api/auth/oauth2/session/oem-hosecloud?token=close-token");
|
|
expect(result.hoseDocumentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
|
expect(result.hoseEnterpriseUrl).toBeUndefined();
|
|
});
|
|
|
|
test("approval run url throws clear error when sso=true is used on non-hose enterprise", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunUrlGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
await expect(
|
|
handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", sso: true },
|
|
fakeContext()
|
|
)
|
|
).rejects.toThrow("direct links currently support Hose-integrated enterprises");
|
|
});
|
|
|
|
test("approval run summary filters by local date and returns compact aggregates", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunsSummary");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ date: "2026-06-08", timezone: "Asia/Shanghai", limit: 100 },
|
|
fakeContext()
|
|
) as {
|
|
matched: number;
|
|
statusCounts: Record<string, number>;
|
|
taskModeCounts: Record<string, number>;
|
|
records: Array<{ sourceDocumentSN?: string; createdAt?: string }>;
|
|
};
|
|
|
|
expect(result.matched).toBe(2);
|
|
expect(result.statusCounts).toEqual({ completed: 1, failed: 1 });
|
|
expect(result.taskModeCounts).toEqual({ assisted: 1, simulation: 1 });
|
|
expect(result.records.map((record) => record.sourceDocumentSN)).toEqual([
|
|
"B26001965",
|
|
"B26001808"
|
|
]);
|
|
expect(result.records[0]?.createdAt).toBe("2026-06-08T13:56:04+08:00");
|
|
});
|
|
|
|
test("approval rule get resolves one rule by version and code", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRuleGet");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
fakeRulesClient(),
|
|
{ versionNumber: 16, code: "44" },
|
|
fakeContext()
|
|
) as { code?: number; ruleCode?: string; runtimeRuleId?: string; description?: string; versionNumber?: number; publishedAt?: string };
|
|
|
|
expect(result).toMatchObject({
|
|
code: "0044",
|
|
ruleCode: "0044",
|
|
runtimeRuleId: "rule-44",
|
|
description: "Second published rule",
|
|
versionNumber: 16,
|
|
publishedAt: "2026-06-08T13:56:04+08:00"
|
|
});
|
|
});
|
|
|
|
test("approval rule get defaults to current draft and handles 0-based codes without +1 offset", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRuleGet");
|
|
expect(tool).toBeDefined();
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const client = fakeZeroBasedRulesClient();
|
|
|
|
// Draft lookup for code 0
|
|
const draftZero = await handler(client, { code: "0" }, fakeContext()) as Record<string, unknown>;
|
|
expect(draftZero).toMatchObject({
|
|
id: "uuid-0",
|
|
code: "0000",
|
|
ruleCode: "0000",
|
|
runtimeRuleId: "rule-0",
|
|
description: "Draft rule zero",
|
|
status: "active",
|
|
createdAt: "2026-06-08T13:56:04+08:00",
|
|
updatedAt: "2026-06-08T13:56:04+08:00"
|
|
});
|
|
|
|
// Draft lookup for code 25 (sitting at array index 24 because code 12 was deleted)
|
|
const draft25 = await handler(client, { code: "25" }, fakeContext()) as Record<string, unknown>;
|
|
expect(draft25).toMatchObject({
|
|
id: "uuid-25",
|
|
code: "0025",
|
|
ruleCode: "0025",
|
|
runtimeRuleId: "rule-25",
|
|
description: "Draft rule twenty-five"
|
|
});
|
|
|
|
// Version lookup for code 0 and code 25 (never returns rule-24 when asking for 25)
|
|
const versionZero = await handler(client, { versionNumber: 9, code: "0000" }, fakeContext()) as Record<string, unknown>;
|
|
expect(versionZero).toMatchObject({
|
|
id: "uuid-0",
|
|
code: "0000",
|
|
ruleCode: "0000",
|
|
runtimeRuleId: "rule-0",
|
|
description: "Published rule zero",
|
|
versionNumber: 9
|
|
});
|
|
|
|
const version25 = await handler(client, { versionNumber: 9, code: "0025" }, fakeContext()) as Record<string, unknown>;
|
|
expect(version25).toMatchObject({
|
|
id: "uuid-25",
|
|
code: "0025",
|
|
ruleCode: "0025",
|
|
runtimeRuleId: "rule-25",
|
|
description: "Published rule twenty-five",
|
|
versionNumber: 9
|
|
});
|
|
});
|
|
|
|
test("approval run cited-rules extracts and merges result.rulesResult and result.hitRules", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunCitedRulesGet");
|
|
expect(tool).toBeDefined();
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
|
|
const mockClient = {
|
|
get: () => ({
|
|
json: async () => ({
|
|
data: {
|
|
id: "run-cited-1",
|
|
sourceDocumentSN: "BX20260928001",
|
|
ruleSetVersionNumber: 12,
|
|
result: {
|
|
hitRules: [
|
|
{
|
|
id: "rule-0",
|
|
description: "Rule zero description",
|
|
scope: "差旅报销单",
|
|
strictness: "MUST_FOLLOW"
|
|
},
|
|
{
|
|
id: "rule-25",
|
|
description: "Rule 25 description",
|
|
scope: "对公付款单",
|
|
strictness: "SHOULD_FOLLOW"
|
|
}
|
|
],
|
|
rulesResult: [
|
|
{
|
|
id: "rule-0",
|
|
ruleIntent: "Check hotel invoice",
|
|
appliedAnalysis: "Invoice matches",
|
|
checkResult: "PASS",
|
|
findings: []
|
|
},
|
|
{
|
|
id: "rule-25",
|
|
ruleIntent: "Check contract attachment",
|
|
appliedAnalysis: "Missing contract",
|
|
checkResult: "FAIL",
|
|
findings: ["未上传合同附件"]
|
|
}
|
|
]
|
|
}
|
|
}
|
|
})
|
|
})
|
|
} as unknown as KyInstance;
|
|
|
|
const res = await handler(mockClient, { recordId: "run-cited-1" }, fakeContext()) as {
|
|
count: number;
|
|
rules: Array<Record<string, unknown>>;
|
|
};
|
|
expect(res.count).toBe(2);
|
|
expect(res.rules[0]).toMatchObject({
|
|
code: "0000",
|
|
runtimeRuleId: "rule-0",
|
|
ruleCode: "0000",
|
|
description: "Rule zero description",
|
|
scope: "差旅报销单",
|
|
strictness: "MUST_FOLLOW",
|
|
checkResult: "PASS"
|
|
});
|
|
expect(res.rules[1]).toMatchObject({
|
|
code: "0025",
|
|
runtimeRuleId: "rule-25",
|
|
ruleCode: "0025",
|
|
description: "Rule 25 description",
|
|
scope: "对公付款单",
|
|
strictness: "SHOULD_FOLLOW",
|
|
checkResult: "FAIL",
|
|
findings: ["未上传合同附件"]
|
|
});
|
|
});
|
|
|
|
test("sealReportDataGet returns lightweight structured report data payload", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealReportDataGet");
|
|
expect(tool).toBeDefined();
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const mockClient = {
|
|
get: async () => ({
|
|
json: async () => ({
|
|
data: {
|
|
records: [
|
|
{
|
|
id: "run-rep-1",
|
|
sourceDocumentSN: "SN-001",
|
|
result: { decision: "REJECT", summary: "缺失发票", riskPoints: ["缺失发票"] },
|
|
pipelineData: { humanResult: "APPROVE" },
|
|
document: { fields: [{ key: "specificationId", value: "差旅报销" }] }
|
|
}
|
|
],
|
|
total: 1
|
|
}
|
|
})
|
|
}),
|
|
post: async () => ({
|
|
json: async () => ({
|
|
data: {
|
|
approvalCount: 1,
|
|
accuracy: 0,
|
|
automationRate: 0,
|
|
riskCount: 1,
|
|
avgDuration: 15
|
|
}
|
|
})
|
|
})
|
|
} as unknown as KyInstance;
|
|
|
|
const res = await handler(mockClient, { month: "2026-08" }, fakeContext()) as {
|
|
period: { month: string };
|
|
metrics: { approvalCount: number; aiAccuracy: number };
|
|
divergedRuns: Array<{ sn: string; triggeredConditions: string[] }>;
|
|
charts: { vennSvg: string };
|
|
};
|
|
|
|
expect(res.period.month).toBe("2026-08");
|
|
expect(res.metrics.approvalCount).toBe(1);
|
|
expect(res.divergedRuns).toHaveLength(1);
|
|
expect(res.divergedRuns[0]?.sn).toBe("SN-001");
|
|
expect(res.divergedRuns[0]?.triggeredConditions).toContain("缺失发票");
|
|
expect(res.charts.vennSvg).toContain("<svg");
|
|
|
|
const rangeRes = await handler(mockClient, {
|
|
startDate: "2026-08-12",
|
|
endDate: "2026-09-18",
|
|
templates: ["差旅报销"]
|
|
}, fakeContext()) as {
|
|
period: { start: string; end: string; label?: string };
|
|
templateGroups: Array<{ template: string }>;
|
|
};
|
|
expect(rangeRes.period.start).toBe("2026-08-12");
|
|
expect(rangeRes.period.end).toBe("2026-09-18");
|
|
expect(rangeRes.templateGroups[0]?.template).toBe("差旅报销");
|
|
|
|
// 验证 maxRuns 突破了原本的 500 限制,传入 2000 校验合法
|
|
expect(() => tool!.parameters.parse({ month: "2026-08", maxRuns: 2000 })).not.toThrow();
|
|
const monthlyTool = sealCapabilities.find((item) => item.name === "sealReportMonthlyGet");
|
|
expect(monthlyTool).toBeDefined();
|
|
expect(() => monthlyTool!.parameters.parse({ month: "2026-08", maxRuns: 2000 })).not.toThrow();
|
|
});
|
|
|
|
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealDeployHosecloudConfigure");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const client = fakeDeployClient();
|
|
|
|
// 1. Rejects custom environment without customApiUrl
|
|
await expect(
|
|
handler(
|
|
client,
|
|
{
|
|
apiKey: "test-ak",
|
|
apiSecret: "test-sk",
|
|
apiOrigin: "custom"
|
|
},
|
|
fakeContext()
|
|
)
|
|
).rejects.toThrow("自定义合思环境必须提供 customApiUrl");
|
|
|
|
// 2. Saves successfully with customApiUrl
|
|
const result = await handler(
|
|
client,
|
|
{
|
|
apiKey: "test-ak",
|
|
apiSecret: "test-sk",
|
|
apiOrigin: "custom",
|
|
customApiUrl: "https://dd2.hosecloud.com",
|
|
outboundName: "DingTalk AI Audit",
|
|
confirm: true
|
|
},
|
|
fakeContext()
|
|
) as { integration: { corporationId: string; apiOrigin: string; customApiUrl: string; outboundName: string } };
|
|
|
|
expect(result.integration).toMatchObject({
|
|
corporationId: "mock-hose-corp",
|
|
apiOrigin: "custom",
|
|
customApiUrl: "https://dd2.hosecloud.com",
|
|
outboundName: "DingTalk AI Audit"
|
|
});
|
|
});
|
|
|
|
test("deploy hosecloud status masks signKey alongside apiKey/apiSecret", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealDeployHosecloudStatus");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const client = {
|
|
get: (url: string) => {
|
|
if (url === "api/v1/simulation/integration-status") {
|
|
return { json: async () => ({ data: { hasHosecloud: true } }) };
|
|
}
|
|
if (url === "api/v1/agent/ai-approval/config") {
|
|
return {
|
|
json: async () => ({
|
|
data: {
|
|
integrations: [
|
|
{
|
|
type: "hosecloud",
|
|
signKey: "visible-sign-key-123",
|
|
apiKey: "ak-123",
|
|
apiSecret: "as-123",
|
|
apiOrigin: "production"
|
|
}
|
|
]
|
|
}
|
|
})
|
|
};
|
|
}
|
|
throw new Error(`unexpected url: ${url}`);
|
|
}
|
|
} as unknown as KyInstance;
|
|
|
|
const result = (await handler(client, {}, fakeContext())) as {
|
|
integrations: Array<Record<string, unknown>>;
|
|
};
|
|
|
|
// signKey rides in the outbound callback URL as config_id, so the
|
|
// diagnostic view must treat it like the other credentials.
|
|
expect(result.integrations[0]!.signKey).toBe("***");
|
|
expect(result.integrations[0]!.apiKey).toBe("***");
|
|
expect(result.integrations[0]!.apiSecret).toBe("***");
|
|
expect(JSON.stringify(result)).not.toContain("visible-sign-key-123");
|
|
});
|
|
|
|
test("sealApprovalRunsCount supports startDate and endDate and normalizes them", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunsCount");
|
|
expect(tool).toBeDefined();
|
|
|
|
const schema = z.toJSONSchema(tool!.parameters) as {
|
|
properties?: Record<string, unknown>;
|
|
};
|
|
expect(schema.properties).toHaveProperty("startDate");
|
|
expect(schema.properties).toHaveProperty("endDate");
|
|
expect(schema.properties).toHaveProperty("status");
|
|
|
|
const requests: string[] = [];
|
|
const client = fakeApprovalRunsClient(requests);
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
|
|
const res = await handler(
|
|
client,
|
|
{
|
|
status: "APPROVED",
|
|
startDate: "2026-08-07",
|
|
endDate: "2026-09-13"
|
|
},
|
|
fakeContext()
|
|
);
|
|
|
|
expect(res).toEqual({ total: 3 });
|
|
expect(requests).toHaveLength(1);
|
|
expect(requests[0]).toContain("api/v1/approvals?");
|
|
expect(requests[0]).toContain("startDate=1786032000000");
|
|
expect(requests[0]).toContain("endDate=1789315199999");
|
|
expect(requests[0]).toContain("APPROVED");
|
|
});
|
|
});
|
|
|
|
function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
|
|
return {
|
|
get: (url: string, options?: { searchParams?: URLSearchParams }) => ({
|
|
json: async () => ({
|
|
...(requests.push(`${url}${options?.searchParams ? `?${options.searchParams}` : ""}`) ? {} : {}),
|
|
data: url === "api/v1/approvals/run-1"
|
|
? {
|
|
id: "run-1",
|
|
status: "completed",
|
|
taskMode: "assisted",
|
|
sourceDocumentSN: "B26001965",
|
|
sourceDocumentId: "doc-source-1",
|
|
documentId: "normalized-doc-1",
|
|
ruleSetVersionNumber: 16,
|
|
document: {
|
|
id: "normalized-doc-1",
|
|
title: "差旅报销单",
|
|
templateName: "费用报销",
|
|
sourceDocumentSN: "B26001965",
|
|
sourceDocumentId: "doc-source-1",
|
|
fields: [
|
|
{ label: "金额", value: "100.00" },
|
|
{ label: "费用类型", value: "差旅费" },
|
|
{
|
|
label: "附件",
|
|
attachments: [
|
|
{
|
|
fileName: "receipt.pdf",
|
|
fileId: "file-1",
|
|
mimeType: "application/pdf",
|
|
ossPath: "oss://bucket/receipt.pdf"
|
|
}
|
|
]
|
|
}
|
|
]
|
|
},
|
|
result: {
|
|
decision: "驳回",
|
|
summary: "费用存在风险",
|
|
riskPoints: ["金额异常", "附件缺失"],
|
|
matchedRules: [{
|
|
runtimeRuleId: "rule-38",
|
|
ruleCode: "#0038",
|
|
versionNumber: 16,
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW",
|
|
appliedAnalysis: "发票信息与报销说明不一致",
|
|
checkResult: "failed",
|
|
findings: ["金额异常"]
|
|
}],
|
|
manualApproval: {
|
|
result: "驳回"
|
|
},
|
|
invoices: [
|
|
{
|
|
fileName: "invoice.png",
|
|
mimeType: "image/png",
|
|
signedUrl: "https://signed.example/invoice.png",
|
|
buyer: "甲方公司",
|
|
seller: "乙方公司",
|
|
amount: 100,
|
|
taxRate: "6%",
|
|
category: "增值税普通发票"
|
|
}
|
|
]
|
|
},
|
|
pipelineData: {
|
|
logs: "audit logs"
|
|
},
|
|
sourceExtendData: {
|
|
_langfuseTraceId: "trace-1",
|
|
original_document_id: "B26001965",
|
|
hosecloudViewUrl: "https://app.ekuaibao.com/web/thirdparty.html"
|
|
},
|
|
createdAt: 1780898164536
|
|
}
|
|
: url === "api/v1/approvals/run-2"
|
|
? {
|
|
id: "run-2",
|
|
status: "completed",
|
|
taskMode: "assisted",
|
|
sourceDocumentSN: "B26001808",
|
|
sourceDocumentId: "doc-source-2",
|
|
createdAt: 1780887698055
|
|
}
|
|
: {
|
|
total: 3,
|
|
records: [
|
|
{
|
|
id: "run-1",
|
|
status: "completed",
|
|
taskMode: "assisted",
|
|
sourceDocumentSN: "B26001965",
|
|
sourceDocumentId: "doc-source-1",
|
|
ruleSetVersionNumber: 16,
|
|
sourceExtendData: { _langfuseTraceId: "trace-1" },
|
|
createdAt: 1780898164536
|
|
},
|
|
{
|
|
id: "run-2",
|
|
status: "failed",
|
|
taskMode: "simulation",
|
|
sourceDocumentSN: "B26001808",
|
|
sourceDocumentId: "doc-source-2",
|
|
pipelineData: {
|
|
humanReview: {
|
|
decision: "通过"
|
|
}
|
|
},
|
|
createdAt: 1780887698055
|
|
},
|
|
{
|
|
id: "run-3",
|
|
status: "completed",
|
|
taskMode: "assisted",
|
|
sourceDocumentSN: "B26001762",
|
|
sourceDocumentId: "doc-source-3",
|
|
createdAt: 1780742324888
|
|
}
|
|
]
|
|
}
|
|
})
|
|
})
|
|
} as unknown as 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"
|
|
? [
|
|
{
|
|
id: "version-16",
|
|
versionNumber: 16,
|
|
versionName: "v16",
|
|
publishedByName: "Tester",
|
|
publishedAt: 1780898164536,
|
|
rules: [
|
|
{
|
|
code: "rule-29",
|
|
description: "First published rule",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
},
|
|
{
|
|
code: "rule-44",
|
|
description: "Second published rule",
|
|
scope: "meal",
|
|
strictness: "SHOULD_FOLLOW"
|
|
}
|
|
]
|
|
}
|
|
]
|
|
: {
|
|
hasPendingDeletes: false,
|
|
rules: [
|
|
{
|
|
id: "rule-1",
|
|
tenantId: "tenant-1",
|
|
code: 29,
|
|
description: "Must include full invoice detail",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW",
|
|
status: "active",
|
|
createdAt: 1780898164536,
|
|
updatedAt: 1780898164536
|
|
},
|
|
{
|
|
id: "rule-2",
|
|
tenantId: "tenant-1",
|
|
code: 44,
|
|
description: "Prefer matching attendee names",
|
|
scope: "meal",
|
|
strictness: "SHOULD_FOLLOW",
|
|
status: "draft",
|
|
createdAt: 1780898164537,
|
|
updatedAt: 1780898164537
|
|
}
|
|
]
|
|
}
|
|
})
|
|
})
|
|
} as unknown as KyInstance;
|
|
}
|
|
|
|
function fakeClearRulesClient(): KyInstance {
|
|
const rules = [
|
|
{
|
|
id: "rule-1",
|
|
tenantId: "tenant-1",
|
|
code: 29,
|
|
description: "Must include full invoice detail",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW",
|
|
status: "active"
|
|
},
|
|
{
|
|
id: "rule-2",
|
|
tenantId: "tenant-1",
|
|
code: 44,
|
|
description: "Prefer matching attendee names",
|
|
scope: "meal",
|
|
strictness: "SHOULD_FOLLOW",
|
|
status: "draft"
|
|
}
|
|
];
|
|
|
|
return {
|
|
get: () => ({
|
|
json: async () => ({
|
|
data: {
|
|
hasPendingDeletes: false,
|
|
rules: [...rules]
|
|
}
|
|
})
|
|
}),
|
|
delete: (url: string) => {
|
|
const ruleId = url.split("/").pop();
|
|
const index = rules.findIndex((rule) => rule.id === ruleId);
|
|
if (index >= 0) rules.splice(index, 1);
|
|
return Promise.resolve({});
|
|
},
|
|
post: () => Promise.resolve({
|
|
ok: true,
|
|
status: 200,
|
|
json: async () => ({ activeRules: rules.length, pendingDeleteRules: 0, nextCode: 1 })
|
|
})
|
|
} as unknown as KyInstance;
|
|
}
|
|
|
|
async function countFakeRules(client: KyInstance): Promise<number> {
|
|
const response = await client.get("api/v1/rules").json() as {
|
|
data: { rules: unknown[] };
|
|
};
|
|
return response.data.rules.length;
|
|
}
|
|
|
|
function fakeContext(): { corp: CorpConfig } {
|
|
return {
|
|
corp: {
|
|
id: "corp-a",
|
|
name: "Corp A",
|
|
environment: "production",
|
|
seal: {
|
|
endpoints: {
|
|
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
|
}
|
|
},
|
|
source: {
|
|
type: "seal",
|
|
token: "token",
|
|
sealUrl: "https://seal.test",
|
|
expiresIn: 3600,
|
|
staffId: "direct"
|
|
},
|
|
auth: {
|
|
refreshTtl: 300
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
function fakeHoseContext(): { corp: CorpConfig } {
|
|
return {
|
|
corp: {
|
|
id: "corp-a",
|
|
name: "Corp A",
|
|
environment: "production",
|
|
seal: {
|
|
endpoints: {
|
|
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
|
}
|
|
},
|
|
source: {
|
|
type: "hose",
|
|
domain: "https://app.ekuaibao.com/",
|
|
appKey: "app-key",
|
|
appSecurity: "app-secret",
|
|
staffId: "staff-a",
|
|
corpId: "hose-corp-a"
|
|
},
|
|
auth: {
|
|
refreshTtl: 300
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
function primeHoseEnterpriseUrl(corpId: string, url: string) {
|
|
const dir = mkdtempSync(join(tmpdir(), "seal-home-tools-"));
|
|
tempDirs.push(dir);
|
|
const storePath = join(dir, "tokens.json");
|
|
process.env.SEAL_HOME_TOKEN_STORE = storePath;
|
|
writeFileSync(storePath, JSON.stringify({
|
|
[corpId]: {
|
|
hose: {
|
|
closeapi: {
|
|
token: "close-token",
|
|
url,
|
|
expiresAt: Date.now() + 3600 * 1000
|
|
}
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
|
|
function fakeDeployClient(): KyInstance {
|
|
let config: Record<string, unknown> = {
|
|
integrationSystem: "hosecloud",
|
|
integrations: []
|
|
};
|
|
|
|
return {
|
|
get: (_url: string) => ({
|
|
json: async () => config
|
|
}),
|
|
patch: (url: string, options?: { json?: any }) => {
|
|
if (url === "api/v1/agent/ai-approval/config") {
|
|
config = options?.json ?? config;
|
|
return {
|
|
json: async () => config
|
|
};
|
|
}
|
|
return {
|
|
json: async () => ({})
|
|
};
|
|
},
|
|
post: (url: string, options?: { json?: any }) => {
|
|
if (url === "api/hosecloud/corporation") {
|
|
return {
|
|
json: async () => ({ corporationId: "mock-hose-corp" })
|
|
};
|
|
}
|
|
if (url === "api/v1/agent/ai-approval/config") {
|
|
config = options?.json ?? config;
|
|
return {
|
|
json: async () => config
|
|
};
|
|
}
|
|
return {
|
|
json: async () => ({})
|
|
};
|
|
}
|
|
} as unknown as KyInstance;
|
|
}
|
|
|
|
function fakeZeroBasedRulesClient(): KyInstance {
|
|
// Simulate 0-based rules with a deleted rule gap (code 12 missing, so code 25 is at array index 24)
|
|
const draftRules = Array.from({ length: 26 }, (_, i) => i)
|
|
.filter((code) => code !== 12)
|
|
.map((code) => ({
|
|
id: `uuid-${code}`,
|
|
tenantId: "tenant-1",
|
|
code,
|
|
description: code === 0 ? "Draft rule zero" : code === 25 ? "Draft rule twenty-five" : `Draft rule ${code}`,
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW",
|
|
status: "active",
|
|
createdAt: 1780898164536,
|
|
updatedAt: 1780898164536
|
|
}));
|
|
|
|
const versionRules = Array.from({ length: 26 }, (_, i) => i)
|
|
.filter((code) => code !== 12)
|
|
.map((code) => ({
|
|
code: `rule-${code}`,
|
|
description: code === 0 ? "Published rule zero" : code === 25 ? "Published rule twenty-five" : `Published rule ${code}`,
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
}));
|
|
|
|
return {
|
|
get: (url: string) => ({
|
|
json: async () => ({
|
|
data: url === "api/v1/rule-set-versions"
|
|
? [
|
|
{
|
|
id: "version-9",
|
|
versionNumber: 9,
|
|
versionName: "v9",
|
|
publishedByName: "Tester",
|
|
rules: versionRules
|
|
}
|
|
]
|
|
: {
|
|
hasPendingDeletes: false,
|
|
rules: draftRules
|
|
}
|
|
})
|
|
})
|
|
} as unknown as KyInstance;
|
|
}
|
|
|