225 lines
10 KiB
TypeScript
225 lines
10 KiB
TypeScript
import { afterEach, describe, expect, test } from "bun:test"
|
|
import { mkdtempSync, rmSync } from "node:fs"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import type { KyInstance } from "ky"
|
|
import type { CorpConfig } from "../../../core/config/types.js"
|
|
import { classifyCliError } from "../../../core/errors.js"
|
|
import { recodeRules } from "./recode.js"
|
|
import { recodeApprovalRules } from "../api.js"
|
|
import type { ApprovalRulesData } from "../types.js"
|
|
import { runCapabilityResult } from "../../../cli/helpers.js"
|
|
import { handleRulesCommand } from "../../../cli/commands/rules.js"
|
|
import { parseArgs } from "../../../cli/parser.js"
|
|
|
|
const originalStore = process.env.SEAL_USE_RECODE_STORE
|
|
const dirs: string[] = []
|
|
afterEach(() => {
|
|
if (originalStore === undefined) delete process.env.SEAL_USE_RECODE_STORE
|
|
else process.env.SEAL_USE_RECODE_STORE = originalStore
|
|
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
|
|
})
|
|
|
|
function fixture() {
|
|
const dir = mkdtempSync(join(tmpdir(), "seal-rules-recode-"))
|
|
dirs.push(dir)
|
|
process.env.SEAL_USE_RECODE_STORE = join(dir, "tickets.sqlite")
|
|
const corp: CorpConfig = {
|
|
id: "recode-test", name: "Test Corp", environment: "test", auth: { refreshTtl: 300 },
|
|
source: { type: "seal", token: "test-token", sealUrl: "https://staging.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
|
seal: { url: "https://staging.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } }
|
|
}
|
|
const state: ApprovalRulesData = {
|
|
hasPendingDeletes: true,
|
|
rules: [
|
|
{ id: "a", tenantId: "tenant-a", code: 0, description: "Keep invoice", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE", updatedAt: 100 },
|
|
{ id: "b", tenantId: "tenant-a", code: 4, description: "Attach receipt", scope: "ALL", strictness: "SHOULD_FOLLOW", status: "DRAFT", updatedAt: 100 }
|
|
]
|
|
}
|
|
const calls: string[] = []
|
|
let tenantId = "tenant-a"
|
|
let origin = "https://staging.sealai.cc"
|
|
let failPost = false
|
|
let corruptReadback = false
|
|
let reorderOnServer = false
|
|
const client = {
|
|
get: async (url: string) => {
|
|
calls.push(`GET ${url}`)
|
|
const data = url === "api/v1/rules" ? structuredClone(state) : {
|
|
user: { id: "operator", tenantId, name: "Operator" }, tenant: { id: tenantId, name: "Tenant" }
|
|
}
|
|
const response = Response.json({ data })
|
|
Object.defineProperty(response, "url", { value: `${origin}/${url}` })
|
|
return response
|
|
},
|
|
post: async (url: string, options: { retry?: number }) => {
|
|
calls.push(`POST ${url}`)
|
|
expect(options.retry).toBe(0)
|
|
if (failPost) throw new Error("upstream timeout")
|
|
const order = [...state.rules].sort((a, b) => Number(a.code) - Number(b.code))
|
|
if (reorderOnServer) order.reverse()
|
|
order.forEach((rule, index) => { rule.code = index })
|
|
if (corruptReadback) state.rules[0]!.description = "concurrent edit"
|
|
return Response.json({ data: { activeRules: state.rules.length, pendingDeleteRules: 1, nextCode: state.rules.length } })
|
|
}
|
|
} as unknown as KyInstance
|
|
return {
|
|
client, corp, state, calls,
|
|
changeTenant: () => { tenantId = "tenant-b" },
|
|
changeOrigin: () => { origin = "https://production.sealai.cc" },
|
|
failPost: () => { failPost = true },
|
|
corruptReadback: () => { corruptReadback = true },
|
|
reorderOnServer: () => { reorderOnServer = true }
|
|
}
|
|
}
|
|
|
|
async function ticket(f: ReturnType<typeof fixture>) {
|
|
const result = await recodeRules(f.client, f.corp, {})
|
|
if (!("confirmCode" in result)) throw new Error("expected a confirmation ticket")
|
|
return result.confirmCode
|
|
}
|
|
|
|
describe("two-phase rules recode", () => {
|
|
test("dry-run never issues a ticket, and yes/confirm cannot bypass the shared capability", async () => {
|
|
const f = fixture()
|
|
const preview = await recodeRules(f.client, f.corp, { dryRun: true })
|
|
expect(preview).toMatchObject({ phase: "preview", executed: false, impactCount: 2, mappingAvailable: false })
|
|
expect(preview.changesDiff).toEqual({ before: ["0000", "0004"], after: ["0000", "0001"] })
|
|
expect(preview).not.toHaveProperty("confirmCode")
|
|
const first = await runCapabilityResult("sealApprovalRulesRecode", f.client, f.corp, { yes: true, confirm: true })
|
|
expect(first).toMatchObject({ executed: false, phase: "confirmation_required" })
|
|
expect(first).toHaveProperty("confirmCode")
|
|
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
|
|
})
|
|
|
|
test("an early second call is rejected; a later call preserves identities and content", async () => {
|
|
const f = fixture()
|
|
const code = await ticket(f)
|
|
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("尚未生效")
|
|
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
|
|
await Bun.sleep(510)
|
|
const result = await recodeRules(f.client, f.corp, { confirmCode: code })
|
|
expect(result).toMatchObject({ executed: true, phase: "executed", nextCode: 2 })
|
|
expect(result.changesDiff).toEqual({ before: ["0000", "0004"], after: ["0000", "0001"] })
|
|
expect(f.state.rules.map(rule => rule.id)).toEqual(["a", "b"])
|
|
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow()
|
|
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(1)
|
|
})
|
|
|
|
test("does not promise old-code order and reports a server-assigned permutation truthfully", async () => {
|
|
const f = fixture()
|
|
const code = await ticket(f)
|
|
f.reorderOnServer()
|
|
await Bun.sleep(510)
|
|
const result = await recodeRules(f.client, f.corp, { confirmCode: code })
|
|
expect(result).toMatchObject({ executed: true, impactCount: 2, mappingAvailable: true })
|
|
expect(result.changesDiff).toEqual({ before: ["0000", "0004"], after: ["0001", "0000"] })
|
|
if (!("changes" in result)) throw new Error("expected verified changes")
|
|
expect(result.changes).toEqual([{ beforeCode: "0000", afterCode: "0001" }, { beforeCode: "0004", afterCode: "0000" }])
|
|
})
|
|
|
|
test.each(["corp", "origin", "tenant", "content", "timestamp", "pendingDeletes"])("rejects a changed %s before any POST", async change => {
|
|
const f = fixture()
|
|
const code = await ticket(f)
|
|
if (change === "corp") f.corp.id = "another-corp"
|
|
if (change === "origin") f.changeOrigin()
|
|
if (change === "tenant") f.changeTenant()
|
|
if (change === "content") f.state.rules[0]!.description = "Changed"
|
|
if (change === "timestamp") f.state.rules[0]!.updatedAt = 101
|
|
if (change === "pendingDeletes") f.state.hasPendingDeletes = false
|
|
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow()
|
|
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
|
|
})
|
|
|
|
test("a failed POST spends the ticket and is not retried", async () => {
|
|
const f = fixture()
|
|
const code = await ticket(f)
|
|
await Bun.sleep(510)
|
|
f.failPost()
|
|
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("upstream timeout")
|
|
await expect(recodeRules(f.client, f.corp, { confirmCode: code })).rejects.toThrow("已使用")
|
|
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(1)
|
|
})
|
|
|
|
test("readback detects a concurrent content change after the POST and classifies as exit 1 (never 13)", async () => {
|
|
const f = fixture()
|
|
const code = await ticket(f)
|
|
await Bun.sleep(510)
|
|
f.corruptReadback()
|
|
try {
|
|
await recodeRules(f.client, f.corp, { confirmCode: code })
|
|
expect.unreachable()
|
|
} catch (error) {
|
|
expect((error as Error).message).toContain("回读规则与预览不一致")
|
|
expect(classifyCliError(error)).toEqual({
|
|
exitCode: 1,
|
|
nextAction: "seal-use rules list --corp 'recode-test' --summary"
|
|
})
|
|
}
|
|
})
|
|
|
|
test("backend contract: handles server placing newly created DRAFT rules ahead of older ACTIVE rules", async () => {
|
|
const f = fixture()
|
|
f.state.rules = [
|
|
{ id: "active-old", tenantId: "tenant-a", code: 2, description: "Existing active rule", scope: "ALL", strictness: "MUST_FOLLOW", status: "ACTIVE", updatedAt: 100 },
|
|
{ id: "draft-new", tenantId: "tenant-a", code: 9, description: "New draft rule placed first by server", scope: "ALL", strictness: "SHOULD_FOLLOW", status: "DRAFT", updatedAt: 200 }
|
|
]
|
|
const code = await ticket(f)
|
|
f.reorderOnServer()
|
|
await Bun.sleep(510)
|
|
const result = await recodeRules(f.client, f.corp, { confirmCode: code })
|
|
expect(result).toMatchObject({
|
|
executed: true,
|
|
phase: "executed",
|
|
mappingAvailable: true,
|
|
impactCount: 2,
|
|
changes: [
|
|
{ beforeCode: "0002", afterCode: "0001" },
|
|
{ beforeCode: "0009", afterCode: "0000" }
|
|
]
|
|
})
|
|
})
|
|
|
|
test("legacy auto-recode refuses a nonempty draft", async () => {
|
|
const f = fixture()
|
|
await expect(recodeApprovalRules(f.client)).rejects.toThrow("禁止隐式重排")
|
|
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
|
|
})
|
|
|
|
test("partial clear reports remaining rules without silently recoding them", async () => {
|
|
const f = fixture()
|
|
const client = {
|
|
get: f.client.get,
|
|
post: f.client.post,
|
|
delete: async (url: string) => {
|
|
if (url.endsWith("/a")) throw new Error("delete failed")
|
|
f.state.rules = f.state.rules.filter(rule => rule.id !== "b")
|
|
return Response.json({})
|
|
}
|
|
} as unknown as KyInstance
|
|
const result = await runCapabilityResult("sealApprovalRulesClear", client, f.corp, { dryRun: false })
|
|
expect(result).toMatchObject({ deleted: 1, afterCount: 1 })
|
|
expect((result as { warnings: string[] }).warnings[0]).toContain("跳过自动重排")
|
|
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
|
|
expect(f.state.rules[0]!.code).toBe(0)
|
|
})
|
|
|
|
test("CLI prints the JSON preview before returning confirmation-required exit 10", async () => {
|
|
const f = fixture()
|
|
const lines: string[] = []
|
|
const log = console.log
|
|
console.log = (...values: unknown[]) => { lines.push(values.map(String).join(" ")) }
|
|
try {
|
|
const args = parseArgs(["rules", "recode", "--corp", f.corp.id, "--yes"])
|
|
await expect(handleRulesCommand("recode", undefined, f.client, f.corp, args)).rejects.toMatchObject({ exitCode: 10 })
|
|
const preview = JSON.parse(lines.join("\n"))
|
|
expect(preview.executed).toBe(false)
|
|
expect(preview.nextCommand).toContain(`--confirm-code ${preview.confirmCode}`)
|
|
expect(preview).not.toHaveProperty("notBefore")
|
|
expect(f.calls.filter(call => call.startsWith("POST"))).toHaveLength(0)
|
|
} finally {
|
|
console.log = log
|
|
}
|
|
})
|
|
})
|