Add semantic sync-test naming, rule mapping and rules map command
This commit is contained in:
1 parent
8db4b87385
commit
3d9e25fd06
7 files changed
+541
-11
No files matched your search
@@ -8,7 +8,8 @@ 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
|
||||
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
|
||||
mappings: process.env.SEAL_USE_MAPPINGS_DIR
|
||||
};
|
||||
const ORIGINAL_FETCH = globalThis.fetch;
|
||||
const tempDirs: string[] = [];
|
||||
@@ -17,6 +18,7 @@ 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);
|
||||
restoreEnv("SEAL_USE_MAPPINGS_DIR", ORIGINAL_ENV.mappings);
|
||||
globalThis.fetch = ORIGINAL_FETCH;
|
||||
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
@@ -27,12 +29,15 @@ afterEach(() => {
|
||||
function setupTestEnv() {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-bind-test-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
const mappings = join(root, "mappings");
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
mkdirSync(mappings, { 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");
|
||||
process.env.SEAL_USE_MAPPINGS_DIR = mappings;
|
||||
|
||||
const prodCorp: CorpConfig = {
|
||||
id: "corp-prod",
|
||||
@@ -302,6 +307,14 @@ describe("corps sync-test", () => {
|
||||
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
|
||||
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
|
||||
|
||||
expect(parsed.versionMapping).toBeDefined();
|
||||
expect(parsed.versionMapping.sourceProdVersionNumber).toBe(22);
|
||||
expect(parsed.versionMapping.targetTestVersionNumber).toBe(3);
|
||||
expect(parsed.ruleMapping).toHaveLength(2);
|
||||
expect(parsed.ruleMapping[0].sourceRuleId).toBe("prod-rule-1");
|
||||
expect(parsed.ruleMapping[0].targetRuleCode).toBe("rule-1");
|
||||
expect(parsed.mappingSavedTo).toBeDefined();
|
||||
|
||||
const postPref = requests.find((r) => (r.method === "POST" || r.method === "PATCH") && r.path.includes("config"));
|
||||
expect(postPref).toBeDefined();
|
||||
expect((postPref?.body as any).decisionPreferences?.explicitApprove).toBe("Prod approve note");
|
||||
@@ -321,6 +334,43 @@ describe("corps sync-test", () => {
|
||||
const allPublishCalls = requests.filter((r) => r.path === "/api/v1/rule-set-versions/publish");
|
||||
expect(allPublishCalls.length).toBe(1);
|
||||
});
|
||||
|
||||
test("sync-test formats semantic version name [Prod v22 · #1] and rules map inspects local snapshot", 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 syncResult = await runCli([
|
||||
"corps",
|
||||
"sync-test",
|
||||
"corp-prod",
|
||||
"--yes"
|
||||
]);
|
||||
|
||||
expect(syncResult.isError).toBe(false);
|
||||
const parsed = JSON.parse(syncResult.stdout);
|
||||
expect(parsed.target.publishedVersion.versionName).toBe("Sync from Acme Production [Prod v22 · #1]");
|
||||
expect(parsed.versionMapping.sourceProdVersionNumber).toBe(22);
|
||||
expect(parsed.ruleMapping).toHaveLength(2);
|
||||
|
||||
// Verify rules map command
|
||||
const mapResult = await runCli(["rules", "map", "--corp", "corp-test"]);
|
||||
expect(mapResult.isError).toBe(false);
|
||||
const mapParsed = JSON.parse(mapResult.stdout);
|
||||
expect(mapParsed.matchedRules).toBe(2);
|
||||
expect(mapParsed.versionMapping.sourceProdVersionNumber).toBe(22);
|
||||
|
||||
// Verify filtering rules map by targetCode
|
||||
const filteredResult = await runCli(["rules", "map", "--corp", "corp-test", "--code", "rule-1"]);
|
||||
expect(filteredResult.isError).toBe(false);
|
||||
const filteredParsed = JSON.parse(filteredResult.stdout);
|
||||
expect(filteredParsed.matchedRules).toBe(1);
|
||||
expect(filteredParsed.rules[0].targetRuleCode).toBe("rule-1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("corps list & current", () => {
|
||||
@@ -452,6 +502,38 @@ function mockSealSyncRequests(options: {
|
||||
return jsonResponse({ data: { success: true } });
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/rule-set-versions" && method === "GET") {
|
||||
if (isProd) {
|
||||
return jsonResponse({
|
||||
data: [
|
||||
{
|
||||
id: "ver-prod-22",
|
||||
versionNumber: 22,
|
||||
versionName: "审核规则 版本22",
|
||||
publishedByName: "周晚容",
|
||||
rules: [],
|
||||
publishedAt: 1786961644896,
|
||||
createdAt: 1786961644896
|
||||
}
|
||||
]
|
||||
});
|
||||
} else {
|
||||
return jsonResponse({
|
||||
data: [
|
||||
{
|
||||
id: "ver-test-2",
|
||||
versionNumber: 2,
|
||||
versionName: "v1.0-old",
|
||||
publishedByName: "管理员",
|
||||
rules: [],
|
||||
publishedAt: 1783495074421,
|
||||
createdAt: 1783495074421
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/rule-set-versions/publish" && method === "POST") {
|
||||
const body = JSON.parse(rawBody || "{}");
|
||||
options.onMutation?.("POST", url.pathname, body);
|
||||
@@ -461,7 +543,10 @@ function mockSealSyncRequests(options: {
|
||||
id: "ver-3",
|
||||
versionNumber: 3,
|
||||
versionName: body.versionName ?? "v1.0",
|
||||
rules: []
|
||||
rules: [
|
||||
{ code: "rule-1", description: "Production Rule A", scope: "global", strictness: "strict" },
|
||||
{ code: "rule-2", description: "Production Rule B", scope: "invoice", strictness: "flexible" }
|
||||
]
|
||||
},
|
||||
rulesCount: 2
|
||||
}
|
||||
|
||||
@@ -22,6 +22,11 @@ import { SealCookieMapSchema, SealHeaderMapSchema } from "../../core/config/type
|
||||
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 {
|
||||
computeNextSyncIteration,
|
||||
formatSyncVersionName,
|
||||
saveRuleMappingSnapshot
|
||||
} from "../../domains/seal/rule-mapping.js";
|
||||
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
|
||||
import { selectCorp } from "../helpers.js";
|
||||
import { confirmationRequired, usageError } from "../errors.js";
|
||||
@@ -284,6 +289,17 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
const prodRules = await api.listApprovalRules(prodClient);
|
||||
const testRules = await api.listApprovalRules(testClient);
|
||||
|
||||
const prodVersions = await api.listApprovalRuleVersions(prodClient).catch(() => []);
|
||||
const testVersions = await api.listApprovalRuleVersions(testClient).catch(() => []);
|
||||
|
||||
const sortedProdVersions = [...prodVersions].sort((a, b) => b.versionNumber - a.versionNumber);
|
||||
const latestProd = sortedProdVersions[0];
|
||||
const prodVersionNumber = latestProd?.versionNumber;
|
||||
|
||||
const nextIteration = computeNextSyncIteration(prodCorp.name, prodVersionNumber, testVersions);
|
||||
const customVersionName = stringOption(args.options["version-name"]) ?? stringOption(args.options.versionName);
|
||||
const versionName = customVersionName ?? formatSyncVersionName(prodCorp.name, prodVersionNumber, nextIteration);
|
||||
|
||||
const updatedTestPref = {
|
||||
...testPref,
|
||||
tone: prodPref.tone,
|
||||
@@ -297,10 +313,6 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
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({
|
||||
@@ -308,13 +320,24 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
source: {
|
||||
id: prodCorp.id,
|
||||
name: prodCorp.name,
|
||||
environment: prodCorp.environment
|
||||
environment: prodCorp.environment,
|
||||
latestPublishedVersion: latestProd ? {
|
||||
versionNumber: latestProd.versionNumber,
|
||||
versionName: latestProd.versionName
|
||||
} : null
|
||||
},
|
||||
target: {
|
||||
id: testCorp.id,
|
||||
name: testCorp.name,
|
||||
environment: testCorp.environment
|
||||
},
|
||||
versionMappingPlan: {
|
||||
sourceProdVersionNumber: prodVersionNumber ?? null,
|
||||
sourceProdVersionName: latestProd?.versionName ?? null,
|
||||
targetTestExpectedVersionNumber: (testVersions[0]?.versionNumber ?? 0) + 1,
|
||||
targetTestPublishVersionName: versionName,
|
||||
iteration: nextIteration
|
||||
},
|
||||
preferencesDiff: {
|
||||
decisionPreferences: {
|
||||
before: testPref.decisionPreferences,
|
||||
@@ -332,6 +355,9 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
toCreateCount: prodRules.rules.length,
|
||||
rulesToSync: prodRules.rules.map((r, idx) => ({
|
||||
index: idx + 1,
|
||||
sourceRuleId: r.id,
|
||||
sourceRuleCode: r.code ?? idx + 1,
|
||||
expectedTargetCode: `rule-${idx + 1}`,
|
||||
description: r.description,
|
||||
scope: r.scope,
|
||||
strictness: r.strictness
|
||||
@@ -367,7 +393,7 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
}
|
||||
|
||||
// 3. Create new draft rules in test enterprise
|
||||
const createdRules = [];
|
||||
const createdRules: any[] = [];
|
||||
for (const rule of prodRules.rules) {
|
||||
const created = await api.createApprovalRule(testClient, {
|
||||
description: rule.description,
|
||||
@@ -383,6 +409,51 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
// 5. Publish new version in test enterprise
|
||||
const published = await api.publishApprovalRuleVersion(testClient, versionName);
|
||||
|
||||
const publishedRules = published.version.rules ?? [];
|
||||
const ruleMapping = prodRules.rules.map((prodRule, idx) => {
|
||||
const testDraft = createdRules[idx];
|
||||
const publishedRule = publishedRules[idx];
|
||||
return {
|
||||
index: idx + 1,
|
||||
sourceRuleId: prodRule.id,
|
||||
sourceRuleCode: prodRule.code ?? idx + 1,
|
||||
targetRuleId: testDraft?.id ?? "",
|
||||
targetRuleCode: publishedRule?.code ?? `rule-${idx + 1}`,
|
||||
description: prodRule.description,
|
||||
scope: prodRule.scope,
|
||||
strictness: prodRule.strictness
|
||||
};
|
||||
});
|
||||
|
||||
const versionMapping = {
|
||||
sourceProdVersionNumber: prodVersionNumber ?? null,
|
||||
sourceProdVersionName: latestProd?.versionName ?? null,
|
||||
targetTestVersionNumber: published.version.versionNumber,
|
||||
targetTestVersionName: published.version.versionName ?? null
|
||||
};
|
||||
|
||||
let mappingSavedTo: string | undefined;
|
||||
try {
|
||||
mappingSavedTo = saveRuleMappingSnapshot({
|
||||
syncedAt: new Date().toISOString(),
|
||||
source: {
|
||||
id: prodCorp.id,
|
||||
name: prodCorp.name,
|
||||
latestPublishedVersionNumber: prodVersionNumber ?? null,
|
||||
latestPublishedVersionName: latestProd?.versionName ?? null
|
||||
},
|
||||
target: {
|
||||
id: testCorp.id,
|
||||
name: testCorp.name,
|
||||
publishedVersionNumber: published.version.versionNumber,
|
||||
publishedVersionName: published.version.versionName,
|
||||
rulesCount: published.rulesCount
|
||||
},
|
||||
versionMapping,
|
||||
ruleMapping
|
||||
});
|
||||
} catch {}
|
||||
|
||||
printJson({
|
||||
success: true,
|
||||
syncedAt: new Date().toISOString(),
|
||||
@@ -390,6 +461,10 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
id: prodCorp.id,
|
||||
name: prodCorp.name,
|
||||
environment: prodCorp.environment,
|
||||
latestPublishedVersion: latestProd ? {
|
||||
versionNumber: latestProd.versionNumber,
|
||||
versionName: latestProd.versionName
|
||||
} : null,
|
||||
draftRulesCount: prodRules.rules.length
|
||||
},
|
||||
target: {
|
||||
@@ -405,6 +480,9 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
rulesCount: published.rulesCount
|
||||
}
|
||||
},
|
||||
versionMapping,
|
||||
ruleMapping,
|
||||
...(mappingSavedTo ? { mappingSavedTo } : {}),
|
||||
productionGuarantees: {
|
||||
prodRulesStayDraft: true,
|
||||
prodVersionPublished: false
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { filterRuleMapping, loadRuleMappingSnapshot } from "../../domains/seal/rule-mapping.js";
|
||||
import { runTool, runToolResult } from "../helpers.js";
|
||||
import { confirmationRequired } from "../errors.js";
|
||||
import {
|
||||
@@ -214,5 +215,33 @@ export async function handleRulesCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, pull, push. Run 'seal-use help' for available commands.`);
|
||||
if (action === "map") {
|
||||
const versionSelector = stringOption(args.options.version) ?? maybeName;
|
||||
const code = stringOption(args.options.code) ?? stringOption(args.options.rule);
|
||||
const snapshot = loadRuleMappingSnapshot(corp.id, versionSelector);
|
||||
if (!snapshot) {
|
||||
const vText = versionSelector ? `version '${versionSelector}'` : "latest version";
|
||||
printJson({
|
||||
error: `No local rule mapping found for enterprise '${corp.name}' (${corp.id}) ${vText}. Run 'seal-use corps sync-test <prodCorp> --yes' to synchronize and generate mapping snapshots.`,
|
||||
corpId: corp.id,
|
||||
version: versionSelector ?? "latest"
|
||||
}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
const filtered = filterRuleMapping(snapshot.ruleMapping, code);
|
||||
printJson({
|
||||
corpId: corp.id,
|
||||
syncedAt: snapshot.syncedAt,
|
||||
source: snapshot.source,
|
||||
target: snapshot.target,
|
||||
versionMapping: snapshot.versionMapping,
|
||||
totalRules: snapshot.ruleMapping.length,
|
||||
matchedRules: filtered.length,
|
||||
rules: filtered
|
||||
}, outputOptions(args.options));
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, pull, push, map. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
Reference in new issue
Block a user