Add test enterprise marking, binding, and staging sync commands

This commit is contained in:
gitea committed 2026-09-11 10:28:52 +08:00
1 parent f2595bb275
commit a56606af9c
16 files changed
+1080 -109

No files matched your search

+480
View File
@@ -0,0 +1,480 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { CorpConfig } from "../../core/config/types.js";
import { runCli } from "../runner.js";
const ORIGINAL_ENV = {
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
config: process.env.SEAL_USE_CONFIG_FILE,
tokenStore: process.env.SEAL_USE_TOKEN_STORE
};
const ORIGINAL_FETCH = globalThis.fetch;
const tempDirs: string[] = [];
afterEach(() => {
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
globalThis.fetch = ORIGINAL_FETCH;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
function setupTestEnv() {
const root = mkdtempSync(join(tmpdir(), "seal-use-bind-test-"));
const enterprises = join(root, "enterprises");
mkdirSync(enterprises, { recursive: true });
tempDirs.push(root);
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
const prodCorp: CorpConfig = {
id: "corp-prod",
name: "Acme Production",
environment: "production",
seal: {
url: "https://acme-prod.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "prod-token",
sealUrl: "https://acme-prod.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
auth: { refreshTtl: 300 }
};
const testCorp: CorpConfig = {
id: "corp-test",
name: "Acme Staging Test",
environment: "test",
seal: {
url: "https://acme-test.sealai.cc",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "test-token",
sealUrl: "https://acme-test.sealai.cc",
expiresIn: 3600,
staffId: "seal"
},
auth: { refreshTtl: 300 }
};
writeFileSync(join(enterprises, "corp-prod.json"), JSON.stringify(prodCorp, null, 2));
writeFileSync(join(enterprises, "corp-test.json"), JSON.stringify(testCorp, null, 2));
return { root, enterprises, prodCorp, testCorp };
}
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
describe("corps mark", () => {
test("requires confirmation and exit code 10 without --confirm", async () => {
setupTestEnv();
const result = await runCli(["corps", "mark", "corp-prod", "--env", "test"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(10);
expect(result.stderr).toContain("without --confirm");
expect(result.stderr).toContain("seal-use corps mark corp-prod --env test --confirm");
});
test("successfully updates environment with --confirm", async () => {
const { enterprises } = setupTestEnv();
const result = await runCli(["corps", "mark", "corp-prod", "--env", "test", "--confirm"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.id).toBe("corp-prod");
expect(parsed.environment).toBe("test");
const saved = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
expect(saved.environment).toBe("test");
});
});
describe("corps bind-test & unbind-test", () => {
test("rejects self-binding with exit code 2", async () => {
setupTestEnv();
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-prod", "--confirm"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Cannot bind enterprise 'corp-prod' to itself");
});
test("requires confirmation and exit code 10 without --confirm", async () => {
setupTestEnv();
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-test"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(10);
expect(result.stderr).toContain("without --confirm");
expect(result.stderr).toContain("seal-use corps bind-test corp-prod corp-test --confirm");
});
test("successfully binds 1-to-1 with --confirm and sets tags", async () => {
const { enterprises } = setupTestEnv();
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.success).toBe(true);
expect(parsed.productionEnterprise.id).toBe("corp-prod");
expect(parsed.productionEnterprise.testCorpId).toBe("corp-test");
expect(parsed.productionEnterprise.environment).toBe("production");
expect(parsed.testEnterprise.id).toBe("corp-test");
expect(parsed.testEnterprise.prodCorpId).toBe("corp-prod");
expect(parsed.testEnterprise.environment).toBe("test");
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
expect(savedProd.testCorpId).toBe("corp-test");
expect(savedProd.environment).toBe("production");
const savedTest = JSON.parse(readFileSync(join(enterprises, "corp-test.json"), "utf-8"));
expect(savedTest.prodCorpId).toBe("corp-prod");
expect(savedTest.environment).toBe("test");
});
test("prevents multi-tier chaining: test corp cannot be bound as prod parent", async () => {
const { enterprises } = setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const thirdCorp: CorpConfig = {
id: "corp-subtest",
name: "Acme Subtest",
environment: "test",
seal: { url: "https://sub.sealai.cc", endpoints: { approvalStylePreferences: "" } },
source: { type: "seal", token: "tok", sealUrl: "https://sub.sealai.cc", expiresIn: 3600, staffId: "seal" },
auth: { refreshTtl: 300 }
};
writeFileSync(join(enterprises, "corp-subtest.json"), JSON.stringify(thirdCorp, null, 2));
const result = await runCli(["corps", "bind-test", "corp-test", "corp-subtest", "--confirm"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("Multi-tier chaining is not permitted");
});
test("requires --force when re-binding an already bound corp", async () => {
const { enterprises } = setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const testCorp2: CorpConfig = {
id: "corp-test-2",
name: "Acme Staging 2",
environment: "test",
seal: { url: "https://test2.sealai.cc", endpoints: { approvalStylePreferences: "" } },
source: { type: "seal", token: "tok2", sealUrl: "https://test2.sealai.cc", expiresIn: 3600, staffId: "seal" },
auth: { refreshTtl: 300 }
};
writeFileSync(join(enterprises, "corp-test-2.json"), JSON.stringify(testCorp2, null, 2));
const conflictResult = await runCli(["corps", "bind-test", "corp-prod", "corp-test-2", "--confirm"]);
expect(conflictResult.isError).toBe(true);
expect(conflictResult.exitCode).toBe(10);
expect(conflictResult.stderr).toContain("requires --force");
const forceResult = await runCli(["corps", "bind-test", "corp-prod", "corp-test-2", "--confirm", "--force"]);
expect(forceResult.isError).toBe(false);
expect(forceResult.exitCode).toBe(0);
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
expect(savedProd.testCorpId).toBe("corp-test-2");
});
test("unbind-test requires confirmation then unlinks both sides", async () => {
const { enterprises } = setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const blockResult = await runCli(["corps", "unbind-test", "corp-prod"]);
expect(blockResult.isError).toBe(true);
expect(blockResult.exitCode).toBe(10);
expect(blockResult.stderr).toContain("without --confirm");
const successResult = await runCli(["corps", "unbind-test", "corp-prod", "--confirm"]);
expect(successResult.isError).toBe(false);
expect(successResult.exitCode).toBe(0);
const parsed = JSON.parse(successResult.stdout);
expect(parsed.success).toBe(true);
expect(parsed.unboundProduction).toBe("corp-prod");
expect(parsed.unboundTest).toBe("corp-test");
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
expect(savedProd.testCorpId).toBeUndefined();
const savedTest = JSON.parse(readFileSync(join(enterprises, "corp-test.json"), "utf-8"));
expect(savedTest.prodCorpId).toBeUndefined();
});
});
describe("corps sync-test", () => {
test("fails if production corp has no bound test corp", async () => {
setupTestEnv();
const result = await runCli(["corps", "sync-test", "corp-prod", "--dry-run"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("has no bound test enterprise");
});
test("dry-run produces preview diff without making network mutations", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const mockMutations: string[] = [];
mockSealSyncRequests({ onMutation: (method, path) => mockMutations.push(`${method} ${path}`) });
const result = await runCli(["corps", "sync-test", "corp-prod", "--dry-run"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.dryRun).toBe(true);
expect(parsed.source.id).toBe("corp-prod");
expect(parsed.target.id).toBe("corp-test");
expect(parsed.rulesPlan.sourceDraftRuleCount).toBe(2);
expect(parsed.rulesPlan.targetExistingDraftRuleCount).toBe(1);
expect(parsed.rulesPlan.toDeleteCount).toBe(1);
expect(parsed.rulesPlan.toCreateCount).toBe(2);
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
expect(mockMutations).toEqual([]);
});
test("sync-test requires --yes and blocks with exit code 10", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
mockSealSyncRequests();
const result = await runCli(["corps", "sync-test", "corp-prod"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(10);
expect(result.stderr).toContain("without --yes");
expect(result.stderr).toContain("seal-use corps sync-test corp-prod --yes");
});
test("sync-test --yes overwrites test preferences, syncs rules, publishes new test version, and guarantees prod draft safety", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const requests: { method: string; path: string; body?: unknown }[] = [];
mockSealSyncRequests({
onMutation: (method, path, body) => requests.push({ method, path, body })
});
const result = await runCli([
"corps",
"sync-test",
"corp-prod",
"--yes",
"--version-name",
"v1.5-staging"
]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.success).toBe(true);
expect(parsed.source.id).toBe("corp-prod");
expect(parsed.source.draftRulesCount).toBe(2);
expect(parsed.target.id).toBe("corp-test");
expect(parsed.target.deletedDraftRulesCount).toBe(1);
expect(parsed.target.createdDraftRulesCount).toBe(2);
expect(parsed.target.publishedVersion.versionName).toBe("v1.5-staging");
expect(parsed.target.publishedVersion.versionNumber).toBe(3);
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
const patchPref = requests.find((r) => r.method === "PATCH" && r.path.includes("config"));
expect(patchPref).toBeDefined();
expect((patchPref?.body as any).decisionPreferences?.explicitApprove).toBe("Prod approve note");
const deleteRule = requests.find((r) => r.method === "DELETE" && r.path === "/api/v1/rules/test-rule-old");
expect(deleteRule).toBeDefined();
const createdRules = requests.filter((r) => r.method === "POST" && r.path === "/api/v1/rules");
expect(createdRules.length).toBe(2);
expect((createdRules[0]?.body as any).description).toBe("Production Rule A");
expect((createdRules[1]?.body as any).description).toBe("Production Rule B");
const publishVersion = requests.find((r) => r.method === "POST" && r.path === "/api/v1/rule-set-versions/publish");
expect(publishVersion).toBeDefined();
expect((publishVersion?.body as any).versionName).toBe("v1.5-staging");
const allPublishCalls = requests.filter((r) => r.path === "/api/v1/rule-set-versions/publish");
expect(allPublishCalls.length).toBe(1);
});
});
describe("corps list & current", () => {
test("outputs environment, testCorpId, and prodCorpId", async () => {
setupTestEnv();
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
const listResult = await runCli(["corps", "list"]);
expect(listResult.isError).toBe(false);
const list = JSON.parse(listResult.stdout);
const prodItem = list.find((item: any) => item.id === "corp-prod");
const testItem = list.find((item: any) => item.id === "corp-test");
expect(prodItem.environment).toBe("production");
expect(prodItem.testCorpId).toBe("corp-test");
expect(testItem.environment).toBe("test");
expect(testItem.prodCorpId).toBe("corp-prod");
const currentResult = await runCli(["corps", "current", "--corp", "corp-prod"]);
expect(currentResult.isError).toBe(false);
const current = JSON.parse(currentResult.stdout);
expect(current.id).toBe("corp-prod");
expect(current.environment).toBe("production");
expect(current.testCorpId).toBe("corp-test");
});
});
function mockSealSyncRequests(options: {
onMutation?: (method: string, path: string, body?: unknown) => void;
} = {}) {
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const requestUrl = typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;
const url = new URL(requestUrl);
const method = (
init?.method ??
(typeof input === "object" && "method" in input ? (input as Request).method : "GET")
).toUpperCase();
const isProd = url.host.includes("prod");
let rawBody = typeof init?.body === "string" ? init.body : undefined;
if (!rawBody && typeof input === "object" && "text" in input) {
rawBody = await (input as Request).clone().text().catch(() => "{}");
}
if (url.pathname === "/api/v1/auth/me") {
return jsonResponse({
data: {
user: { id: "user-1", name: isProd ? "Prod User" : "Test User" },
tenant: { id: isProd ? "tenant-prod" : "tenant-test", tenantSlug: isProd ? "acme-prod" : "acme-test" }
}
});
}
if (url.pathname === "/api/v1/agent/ai-approval/config" && method === "GET") {
return jsonResponse({
data: {
id: isProd ? "pref-prod" : "pref-test",
tenantId: isProd ? "tenant-prod" : "tenant-test",
tone: isProd ? "formal" : "casual",
language: "zh-CN",
decisionPreferences: {
explicitApprove: isProd ? "Prod approve note" : "Test approve note",
explicitReject: "Reject invalid expenses",
exemptApprove: "",
review: ""
},
thinkingDepthPreference: {
defaultLevel: isProd ? "high" : "medium",
routingPolicies: []
},
integrations: [
{ type: "hosecloud", signKey: isProd ? "prod-sign" : "test-sign" }
]
}
});
}
if (url.pathname === "/api/v1/agent/ai-approval/config" && method === "PATCH") {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.("PATCH", url.pathname, body);
return jsonResponse({ data: body });
}
if (url.pathname === "/api/v1/rules" && method === "GET") {
if (isProd) {
return jsonResponse({
data: {
rules: [
{ id: "prod-rule-1", description: "Production Rule A", scope: "global", strictness: "strict" },
{ id: "prod-rule-2", description: "Production Rule B", scope: "invoice", strictness: "flexible" }
],
hasPendingDeletes: false
}
});
} else {
return jsonResponse({
data: {
rules: [
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
],
hasPendingDeletes: false
}
});
}
}
if (url.pathname.startsWith("/api/v1/rules/") && method === "DELETE") {
options.onMutation?.("DELETE", url.pathname);
return jsonResponse({ data: { success: true } });
}
if (url.pathname === "/api/v1/rules" && method === "POST") {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.("POST", url.pathname, body);
return jsonResponse({
data: {
id: `new-rule-${Date.now()}`,
...body
}
});
}
if (url.pathname === "/api/v1/rules/batch-recode" && method === "POST") {
options.onMutation?.("POST", url.pathname);
return jsonResponse({ data: { success: true } });
}
if (url.pathname === "/api/v1/rule-set-versions/publish" && method === "POST") {
const body = JSON.parse(rawBody || "{}");
options.onMutation?.("POST", url.pathname, body);
return jsonResponse({
data: {
version: {
id: "ver-3",
versionNumber: 3,
versionName: body.versionName ?? "v1.0",
rules: []
},
rulesCount: 2
}
});
}
return jsonResponse({ error: `Unexpected request: ${method} ${url.pathname}` }, 404);
}) as typeof fetch;
}
function jsonResponse(value: unknown, status = 200) {
return new Response(JSON.stringify(value), {
status,
headers: { "content-type": "application/json" }
});
}
+349 -4
View File
@@ -9,19 +9,22 @@ import {
probeHoseDomain
} from "../../core/auth/hose.js";
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
import { createSealClientForUrl } from "../../core/http/factory.js";
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import {
loadCorpConfigs,
loadGlobalConfig,
resolveWritableEnterprisesDir,
saveGlobalConfig
saveGlobalConfig,
updateCorpConfig
} from "../../core/config/loader.js";
import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/types.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { CorpConfig, CorpEnvironment } from "../../core/config/types.js";
import * as api from "../../domains/seal/api.js";
import { getMe } from "../../domains/seal/api.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
import { selectCorp } from "../helpers.js";
import { confirmationRequired, usageError } from "../errors.js";
import {
inferCorpIdFromStaffId,
booleanOption,
@@ -52,8 +55,11 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
printJson(corps.map((item) => ({
id: item.id,
name: item.name,
environment: item.environment ?? "production",
sourceType: item.source.type,
provider: (item.source as any).provider ?? item.source.type,
testCorpId: item.testCorpId,
prodCorpId: item.prodCorpId,
current: item.id === currentCorpId
})));
return;
@@ -64,8 +70,345 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
printJson({
id: corp.id,
name: corp.name,
environment: corp.environment ?? "production",
sourceType: corp.source.type,
provider: (corp.source as any).provider ?? corp.source.type
provider: (corp.source as any).provider ?? corp.source.type,
testCorpId: corp.testCorpId,
prodCorpId: corp.prodCorpId
});
return;
}
if (action === "mark" || action === "mark-test" || action === "mark-prod") {
const corpId = maybeName ?? stringOption(args.options.corp);
if (!corpId) {
throw usageError("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");
}
const corp = selectCorp(corpId);
const targetEnv = (
action === "mark-test"
? "test"
: action === "mark-prod"
? "production"
: (stringOption(args.options.env) ?? stringOption(args.options.environment))
) as CorpEnvironment | undefined;
if (targetEnv !== "production" && targetEnv !== "test") {
throw usageError("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");
}
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to change environment tag of enterprise '${corp.name}' (${corp.id}) to '${targetEnv}' without --confirm. Marking alters synchronization safety guards.`,
`seal-use corps mark ${corp.id} --env ${targetEnv} --confirm`
);
}
const updated = updateCorpConfig(corp.id, { environment: targetEnv });
printJson({
id: updated.id,
name: updated.name,
environment: updated.environment,
testCorpId: updated.testCorpId,
prodCorpId: updated.prodCorpId
});
return;
}
if (action === "bind-test") {
let prodId: string | undefined;
let testId: string | undefined;
if (maybeName && args.command[3]) {
prodId = maybeName;
testId = args.command[3];
} else if (maybeName) {
const corpOption = stringOption(args.options.corp);
const testCorpOption = stringOption(args.options["test-corp"]) ?? stringOption(args.options.testCorp);
if (corpOption) {
prodId = corpOption;
testId = maybeName;
} else if (testCorpOption) {
prodId = maybeName;
testId = testCorpOption;
}
}
if (!prodId || !testId) {
throw usageError(
"Usage: seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]\n" +
" or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"
);
}
const prodCorp = selectCorp(prodId);
const testCorp = selectCorp(testId);
if (prodCorp.id === testCorp.id) {
throw usageError(`Cannot bind enterprise '${prodCorp.id}' to itself.`);
}
if (prodCorp.prodCorpId && prodCorp.prodCorpId !== testCorp.id) {
throw usageError(
`Cannot use '${prodCorp.id}' as a production enterprise because it is already registered as a test enterprise for '${prodCorp.prodCorpId}'. Multi-tier chaining is not permitted.`
);
}
if (testCorp.testCorpId && testCorp.testCorpId !== prodCorp.id) {
throw usageError(
`Cannot bind '${testCorp.id}' as a test enterprise because it already has a bound test enterprise '${testCorp.testCorpId}'. Multi-tier chaining is not permitted.`
);
}
const force = booleanOption(args.options.force) === true;
if (
(prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) ||
(testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id)
) {
if (!force) {
throw confirmationRequired(
`Enterprise binding conflict: production enterprise '${prodCorp.id}' is bound to '${prodCorp.testCorpId ?? "none"}', and test enterprise '${testCorp.id}' is bound to '${testCorp.prodCorpId ?? "none"}'. Overwriting an existing binding requires --force and --confirm.`,
`seal-use corps bind-test ${prodCorp.id} ${testCorp.id} --confirm --force`
);
}
}
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
const forceFlag = force ? " --force" : "";
throw confirmationRequired(
`Refusing to bind test enterprise '${testCorp.name}' (${testCorp.id}) to production enterprise '${prodCorp.name}' (${prodCorp.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${testCorp.id}' as a test environment.`,
`seal-use corps bind-test ${prodCorp.id} ${testCorp.id} --confirm${forceFlag}`
);
}
if (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) {
try {
updateCorpConfig(prodCorp.testCorpId, { prodCorpId: undefined });
} catch {}
}
if (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) {
try {
updateCorpConfig(testCorp.prodCorpId, { testCorpId: undefined });
} catch {}
}
const updatedProd = updateCorpConfig(prodCorp.id, {
environment: "production",
testCorpId: testCorp.id
});
const updatedTest = updateCorpConfig(testCorp.id, {
environment: "test",
prodCorpId: prodCorp.id
});
printJson({
success: true,
productionEnterprise: {
id: updatedProd.id,
name: updatedProd.name,
environment: updatedProd.environment,
testCorpId: updatedProd.testCorpId
},
testEnterprise: {
id: updatedTest.id,
name: updatedTest.name,
environment: updatedTest.environment,
prodCorpId: updatedTest.prodCorpId
}
});
return;
}
if (action === "unbind-test") {
const targetId = maybeName ?? stringOption(args.options.corp);
const corp = selectCorp(targetId);
if (!corp.testCorpId && !corp.prodCorpId) {
printJson({
unbound: false,
message: `Enterprise '${corp.name}' (${corp.id}) does not have an active test enterprise binding.`
});
return;
}
const prodId = corp.testCorpId ? corp.id : corp.prodCorpId!;
const testId = corp.testCorpId ? corp.testCorpId : corp.id;
const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to unbind production enterprise '${prodId}' and test enterprise '${testId}' without --confirm.`,
`seal-use corps unbind-test ${corp.id} --confirm`
);
}
updateCorpConfig(prodId, { testCorpId: undefined });
try {
updateCorpConfig(testId, { prodCorpId: undefined });
} catch {}
printJson({
success: true,
unboundProduction: prodId,
unboundTest: testId
});
return;
}
if (action === "sync-test") {
const targetCorpId = maybeName ?? stringOption(args.options.corp);
const prodCorp = selectCorp(targetCorpId);
if (!prodCorp.testCorpId) {
throw usageError(
`Production enterprise '${prodCorp.name}' (${prodCorp.id}) has no bound test enterprise.\n` +
`Run 'seal-use corps bind-test ${prodCorp.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`
);
}
const testCorp = selectCorp(prodCorp.testCorpId);
if (testCorp.environment !== "test") {
throw new Error(
`Target enterprise '${testCorp.name}' (${testCorp.id}) is marked as '${testCorp.environment}', NOT 'test'. Aborting sync to protect non-test environments.`
);
}
const prodClient = await createSealClient(prodCorp);
const testClient = await createSealClient(testCorp);
const prodPref = (await api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences)) as any;
const testPref = (await api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences)) as any;
const prodRules = await api.listApprovalRules(prodClient);
const testRules = await api.listApprovalRules(testClient);
const updatedTestPref = {
...testPref,
tone: prodPref.tone,
language: prodPref.language,
detailLevel: prodPref.detailLevel,
outputFormat: prodPref.outputFormat,
examples: prodPref.examples ?? [],
prohibitedPhrases: prodPref.prohibitedPhrases ?? [],
customInstructions: prodPref.customInstructions,
decisionPreferences: prodPref.decisionPreferences,
thinkingDepthPreference: prodPref.thinkingDepthPreference
};
const customVersionName = stringOption(args.options["version-name"]) ?? stringOption(args.options.versionName);
const dateStr = new Date().toISOString().slice(0, 10);
const versionName = customVersionName ?? `Sync from ${prodCorp.name} (${dateStr})`;
const dryRun = booleanOption(args.options["dry-run"]) === true || booleanOption(args.options.dryRun) === true;
if (dryRun) {
printJson({
dryRun: true,
source: {
id: prodCorp.id,
name: prodCorp.name,
environment: prodCorp.environment
},
target: {
id: testCorp.id,
name: testCorp.name,
environment: testCorp.environment
},
preferencesDiff: {
decisionPreferences: {
before: testPref.decisionPreferences,
after: prodPref.decisionPreferences
},
thinkingDepthPreference: {
before: testPref.thinkingDepthPreference,
after: prodPref.thinkingDepthPreference
}
},
rulesPlan: {
sourceDraftRuleCount: prodRules.rules.length,
targetExistingDraftRuleCount: testRules.rules.length,
toDeleteCount: testRules.rules.length,
toCreateCount: prodRules.rules.length,
rulesToSync: prodRules.rules.map((r, idx) => ({
index: idx + 1,
description: r.description,
scope: r.scope,
strictness: r.strictness
}))
},
publishingPlan: {
targetCorpId: testCorp.id,
publishVersionName: versionName,
publishTarget: "test"
},
productionGuarantees: {
prodRulesStayDraft: true,
prodVersionPublished: false
}
});
return;
}
const confirmed = booleanOption(args.options.yes) === true || booleanOption(args.options.confirm) === true;
if (!confirmed) {
throw confirmationRequired(
`Refusing to overwrite test enterprise '${testCorp.name}' (${testCorp.id}) with preferences and ${prodRules.rules.length} draft rules from production enterprise '${prodCorp.name}' (${prodCorp.id}) without --yes. This will replace test draft rules and publish a new version on the test enterprise.`,
`seal-use corps sync-test ${prodCorp.id} --yes`
);
}
// 1. Update style & decision preferences in test enterprise
await api.updateApprovalStylePreferences(testClient, updatedTestPref, testCorp.seal.endpoints.approvalStylePreferences);
// 2. Clear old draft rules in test enterprise
for (const rule of testRules.rules) {
await api.deleteApprovalRule(testClient, rule.id);
}
// 3. Create new draft rules in test enterprise
const createdRules = [];
for (const rule of prodRules.rules) {
const created = await api.createApprovalRule(testClient, {
description: rule.description,
scope: rule.scope,
strictness: rule.strictness
});
createdRules.push(created);
}
// 4. Batch recode rules in test enterprise
await api.recodeApprovalRules(testClient).catch(() => undefined);
// 5. Publish new version in test enterprise
const published = await api.publishApprovalRuleVersion(testClient, versionName);
printJson({
success: true,
syncedAt: new Date().toISOString(),
source: {
id: prodCorp.id,
name: prodCorp.name,
environment: prodCorp.environment,
draftRulesCount: prodRules.rules.length
},
target: {
id: testCorp.id,
name: testCorp.name,
environment: testCorp.environment,
deletedDraftRulesCount: testRules.rules.length,
createdDraftRulesCount: createdRules.length,
publishedVersion: {
id: published.version.id,
versionNumber: published.version.versionNumber,
versionName: published.version.versionName,
rulesCount: published.rulesCount
}
},
productionGuarantees: {
prodRulesStayDraft: true,
prodVersionPublished: false
}
});
return;
}
@@ -326,6 +669,7 @@ async function addHoseCorp(input: Record<string, unknown>) {
const config: CorpConfig = {
id,
name,
environment: "production",
seal: {
url: sealUrl,
endpoints: {
@@ -460,6 +804,7 @@ function writeSealCorpConfig(
const config: CorpConfig = {
id,
name: optionalString(input, "name") ?? tenantName ?? id,
environment: "production",
seal: {
url: sealUrl,
tenantSlug,
+4
View File
@@ -99,6 +99,10 @@ Usage:
seal-use corps list [--corp <corpId>]
seal-use corps current [--corp <corpId>]
seal-use corps switch <corpId>
seal-use corps mark <corpId> --env <production|test> [--confirm]
seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]
seal-use corps unbind-test [<corpId>] [--confirm]
seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]
seal-use corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
seal-use corps add-seal --json '{"sealUrl":"https://tenant.sealai.cc","token":"seal-bearer-token"}'
seal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]
+2
View File
@@ -7,6 +7,7 @@ describe("getDirectSealSession", () => {
const corp: CorpConfig = {
id: "corp-direct-1",
name: "Direct Corp",
environment: "production",
seal: {
url: "https://seal.example.com",
tenantSlug: "direct-slug",
@@ -48,6 +49,7 @@ describe("getDirectSealSession", () => {
const corp: CorpConfig = {
id: "corp-native-1",
name: "Native Seal Corp",
environment: "production",
seal: {
url: "https://tenant.sealai.cc",
tenantSlug: "tenant-slug",
+3
View File
@@ -59,6 +59,7 @@ describe("hose auth helpers", () => {
const corpWithSealUrl: CorpConfig = {
id: "corp-1",
name: "Corp 1",
environment: "production",
seal: { url: "https://custom.sealai.cc", endpoints: { approvalStylePreferences: "" } },
source,
auth: { refreshTtl: 300 }
@@ -68,6 +69,7 @@ describe("hose auth helpers", () => {
const corpWithoutSealUrl: CorpConfig = {
id: "corp-1",
name: "Corp 1",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source,
auth: { refreshTtl: 300 }
@@ -91,6 +93,7 @@ describe("hose auth helpers", () => {
const corp: CorpConfig = {
id: "corp-cached",
name: "Corp Cached",
environment: "production",
seal: { endpoints: { approvalStylePreferences: "" } },
source: {
type: "hose",
+33 -1
View File
@@ -3,11 +3,13 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
findCorpConfigFile,
loadCorpConfigs,
loadGlobalConfig,
resolveEnterprisesDir,
resolveGlobalConfigFile,
saveGlobalConfig
saveGlobalConfig,
updateCorpConfig
} from "./loader.js";
const ORIGINAL_USE_ENV = process.env.SEAL_USE_ENTERPRISES_DIR;
@@ -153,6 +155,36 @@ describe("loadCorpConfigs", () => {
}
});
});
test("finds and updates an enterprise config file in-place", () => {
const dir = makeTempDir();
process.env.SEAL_USE_ENTERPRISES_DIR = dir;
writeCorpConfig(join(dir, "alpha.json"), "alpha", "Alpha Corp");
expect(findCorpConfigFile("alpha")).toBe(join(dir, "alpha.json"));
expect(findCorpConfigFile("nonexistent")).toBeUndefined();
const updated = updateCorpConfig("alpha", {
environment: "production",
testCorpId: "alpha-test"
});
expect(updated.id).toBe("alpha");
expect(updated.environment).toBe("production");
expect(updated.testCorpId).toBe("alpha-test");
// Check on-disk persistence
const reloaded = loadCorpConfigs().find((c) => c.id === "alpha");
expect(reloaded?.testCorpId).toBe("alpha-test");
// Unsetting / clearing testCorpId
const cleared = updateCorpConfig("alpha", {
testCorpId: undefined
});
expect(cleared.testCorpId).toBeUndefined();
const reloadedAfterClear = loadCorpConfigs().find((c) => c.id === "alpha");
expect(reloadedAfterClear?.testCorpId).toBeUndefined();
});
});
function makeTempDir(): string {
+39
View File
@@ -104,3 +104,42 @@ export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig {
writeFileSync(file, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
return normalized;
}
export function findCorpConfigFile(corpId: string): string | undefined {
const dirs = resolveEnterprisesDirs();
for (const dir of dirs) {
if (!existsSync(dir)) continue;
for (const file of readdirSync(dir)
.filter((item) => item.endsWith(".json"))
.filter((item) => !item.startsWith("example."))) {
const fullPath = join(dir, file);
try {
const content = readFileSync(fullPath, "utf-8");
const parsed = JSON.parse(content);
if (parsed && typeof parsed === "object" && parsed.id === corpId) {
return fullPath;
}
} catch {
// ignore malformed files
}
}
}
return undefined;
}
export function updateCorpConfig(corpId: string, patch: Partial<CorpConfig>): CorpConfig {
const filePath = findCorpConfigFile(corpId);
if (!filePath) {
throw new Error(`Enterprise config not found: ${corpId}`);
}
const raw = JSON.parse(readFileSync(filePath, "utf-8"));
const merged = { ...raw, ...patch };
for (const key of Object.keys(patch) as Array<keyof CorpConfig>) {
if (patch[key] === undefined) {
delete merged[key];
}
}
const validated = CorpConfigSchema.parse(merged);
writeFileSync(filePath, `${JSON.stringify(validated, null, 2)}\n`, "utf-8");
return validated;
}
+1
View File
@@ -6,6 +6,7 @@ function corp(id: string, name = id): CorpConfig {
return {
id,
name,
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
+33
View File
@@ -97,6 +97,39 @@ describe("CorpConfigSchema", () => {
expect(config.seal.headers).toBeUndefined();
expect(config.seal.cookies).toBeUndefined();
expect(config.environment).toBe("production");
expect(config.testCorpId).toBeUndefined();
expect(config.prodCorpId).toBeUndefined();
});
test("accepts environment, testCorpId, and prodCorpId", () => {
const prodConfig = CorpConfigSchema.parse({
id: "prod-corp",
name: "Prod Corp",
environment: "production",
testCorpId: "test-corp",
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://direct.sealai.cc"
}
});
expect(prodConfig.environment).toBe("production");
expect(prodConfig.testCorpId).toBe("test-corp");
const testConfig = CorpConfigSchema.parse({
id: "test-corp",
name: "Test Corp",
environment: "test",
prodCorpId: "prod-corp",
source: {
type: "direct",
token: "seal-token",
sealUrl: "https://direct.sealai.cc"
}
});
expect(testConfig.environment).toBe("test");
expect(testConfig.prodCorpId).toBe("prod-corp");
});
test("accepts custom headers and cookies on the Seal endpoint", () => {
+7 -1
View File
@@ -105,12 +105,17 @@ export const CorpAuthConfigSchema = z.object({
refreshTtl: z.number().int().positive().default(300)
}).default({ refreshTtl: 300 });
export const CorpEnvironmentSchema = z.enum(["production", "test"]).default("production");
export const CorpConfigSchema = z.object({
id: z.string(),
name: z.string(),
seal: SealEndpointSchema,
source: SealSourceSchema,
auth: CorpAuthConfigSchema
auth: CorpAuthConfigSchema,
environment: CorpEnvironmentSchema,
testCorpId: z.string().optional(),
prodCorpId: z.string().optional()
});
export const GlobalLintConfigSchema = z.object({
@@ -130,6 +135,7 @@ export const GlobalConfigSchema = z.object({
lint: GlobalLintConfigSchema
});
export type CorpEnvironment = z.infer<typeof CorpEnvironmentSchema>;
export type HoseSealSource = z.infer<typeof HoseSealSourceSchema>;
export type DirectSealSource = z.infer<typeof DirectSealSourceSchema>;
export type NativeSealSource = z.infer<typeof NativeSealSourceSchema>;
@@ -73,6 +73,7 @@ describe("exportApprovalRunsToExcel integration", () => {
const testCorp: CorpConfig = {
id: "test-corp",
name: "测试企业",
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
+1
View File
@@ -76,6 +76,7 @@ function fakeCorp(): CorpConfig {
return {
id: "corp-search-test",
name: "Search Test Corp",
environment: "production",
seal: {
url: "https://seal.test",
endpoints: {
+2
View File
@@ -1031,6 +1031,7 @@ function fakeContext(): { corp: CorpConfig } {
corp: {
id: "corp-a",
name: "Corp A",
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
@@ -1055,6 +1056,7 @@ function fakeHoseContext(): { corp: CorpConfig } {
corp: {
id: "corp-a",
name: "Corp A",
environment: "production",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"