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
@@ -57,7 +57,7 @@ seal-use corps list
|
||||
- User-facing Seal tenant assistance link (Seal 协助/Seal 授权/委托): resolve the named enterprise first, then run `seal-use delegation create --corp <corpId> --note '<enterprise>'`; verify the returned hostname is that tenant's Seal hostname. Always provide BOTH a code block (` ```text ... ``` `) AND a hyperlink.
|
||||
- Packaged customer feedback → approval-rule remediation: read `references/customer-feedback-rule-remediation.md`. Use this route for WeChat messages, screenshots, rejection notifications, document numbers, customer complaints, expected approval behavior, rule-only mitigation, exact diffs, or requests to update and publish a rule version.
|
||||
- 模拟测试发布闭环: `seal-use simulation create --mode hosecloud --flow-ids ... --no-wait --corp <corpId>` (合思指定单号) 或 `--mode material_pack --package-ids ... --schema-config file.json` (材料包导入), 支持多源系统 `--source-system <hosecloud|feishu|weaver|helios|maycur|material_pack>`, `simulation status <batchId>` 单次查询状态, `simulation wait <batchId>` 轮询等待完成, `simulation clean <batchId>` 清理数据, `simulation specifications` 列出单据模板, `simulation list`/`get`/`batch-records` 查看批次与记录。创建前确认目标环境为测试环境。
|
||||
- 测试企业标记、关联与配置规则同步: `seal-use corps mark <corpId> --env <production|test> --confirm` (严格标记环境), `seal-use corps bind-test <prodCorpId> <testCorpId> --confirm` (严格1对1下挂,禁止多层级串联), `seal-use corps unbind-test <corpId> --confirm`, `seal-use corps sync-test <prodCorpId> [--dry-run|--yes] [--version-name <name>]` (将正式企业的偏好和草稿规则覆盖同步到测试企业并直接发布成新版本,正式企业规则保持草稿态不发布)。
|
||||
- 测试企业标记、关联与配置规则同步: `seal-use corps mark <corpId> --env <production|test> --confirm` (严格标记环境), `seal-use corps bind-test <prodCorpId> <testCorpId> --confirm` (严格1对1下挂,禁止多层级串联), `seal-use corps unbind-test <corpId> --confirm`, `seal-use corps sync-test <prodCorpId> [--dry-run|--yes] [--version-name <name>]` (将正式企业的偏好和草稿规则覆盖同步到测试企业并自动发布语义版本 `[Prod vN · #M]`,输出并本地缓存 `ruleMapping`,正式企业规则保持草稿态不发布), `seal-use rules map [--corp <corpId>] [--version <v|latest>] [--code <code>]` (离线毫秒级速查测试与生产规则对照映射)。
|
||||
- Seal AI 智能审核发布到合思费控: `seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>`; read `references/hose-enterprise-deploy.md`.
|
||||
- 审核决策偏好与思考深度: `seal-use preference get --corp <corpId>`, `preference decision update --json '...' --corp <corpId>`, `preference thinking-depth set --default <medium|high> --corp <corpId>`, `preference thinking-depth policies <list|upsert|remove> --corp <corpId>`.
|
||||
- 审核大盘统计与去重分析: `seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|id] --corp <corpId>`, `seal-use approval-runs count --corp <corpId>`.
|
||||
|
||||
@@ -156,12 +156,15 @@ Test Enterprise Binding & Staging Synchronization:
|
||||
- **Production Safety Guarantee (`corps sync-test`)**:
|
||||
- In the **Production Enterprise**: Rules remain strictly in **draft state** without publishing any live version.
|
||||
- In the **Test Enterprise**: Style preferences (`decisionPreferences`, `thinkingDepthPreference`) are updated to match production, test draft rules are cleared and populated with production draft rules, recoded, and immediately **published as a new official version** in the test tenant (`--version-name <name>`).
|
||||
- `--dry-run` previews the full preference diff and rule sync plan without sending mutations. Execution requires `--yes`.
|
||||
- **Semantic Version Naming**: Defaults to `Sync from <ProdCorp> [Prod v<N> · #<Iteration>]` tracking production baseline version and test draft iteration without redundant date strings.
|
||||
- **Rule Mapping & Local Snapshot**: Returns `versionMapping` and `ruleMapping` in CLI stdout and saves persistent snapshot to `~/.config/seal-use/mappings/<testCorpId>-v<N>.json` and `<testCorpId>-latest.json`.
|
||||
- `--dry-run` previews the full preference diff, version mapping plan, and rule sync plan without sending mutations. Execution requires `--yes`.
|
||||
|
||||
Approval rule maintenance:
|
||||
|
||||
- `seal-use rules count [--corp <corpId>]`
|
||||
- `seal-use rules list --summary [--corp <corpId>]`
|
||||
- `seal-use rules map [--corp <corpId>] [--version <id|num|latest>] [--code <code>]` (reads local sync rule mapping snapshot)
|
||||
- `seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]`
|
||||
- `seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]`
|
||||
- `seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Run `--dry-run` first; a local file exported with `rules pull` is preferred.
|
||||
|
||||
@@ -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.`);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { existsSync, mkdirSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
computeNextSyncIteration,
|
||||
filterRuleMapping,
|
||||
formatSyncVersionName,
|
||||
getMappingsDir,
|
||||
loadRuleMappingSnapshot,
|
||||
RuleMappingSnapshot,
|
||||
saveRuleMappingSnapshot
|
||||
} from "./rule-mapping.js";
|
||||
|
||||
describe("rule-mapping", () => {
|
||||
let testDir: string;
|
||||
const originalEnv = process.env.SEAL_USE_MAPPINGS_DIR;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = join(tmpdir(), `seal-mappings-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
||||
mkdirSync(testDir, { recursive: true });
|
||||
process.env.SEAL_USE_MAPPINGS_DIR = testDir;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalEnv) {
|
||||
process.env.SEAL_USE_MAPPINGS_DIR = originalEnv;
|
||||
} else {
|
||||
delete process.env.SEAL_USE_MAPPINGS_DIR;
|
||||
}
|
||||
if (existsSync(testDir)) {
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("getMappingsDir respects custom environment variable", () => {
|
||||
expect(getMappingsDir()).toBe(testDir);
|
||||
});
|
||||
|
||||
test("saveRuleMappingSnapshot and loadRuleMappingSnapshot round-trip", () => {
|
||||
const snapshot: RuleMappingSnapshot = {
|
||||
syncedAt: new Date().toISOString(),
|
||||
source: {
|
||||
id: "prod-1",
|
||||
name: "Acme Corp",
|
||||
latestPublishedVersionNumber: 22,
|
||||
latestPublishedVersionName: "Version 22"
|
||||
},
|
||||
target: {
|
||||
id: "test-1",
|
||||
name: "Acme Test",
|
||||
publishedVersionNumber: 7,
|
||||
publishedVersionName: "Sync from Acme Corp [Prod v22 · #1]",
|
||||
rulesCount: 2
|
||||
},
|
||||
versionMapping: {
|
||||
sourceProdVersionNumber: 22,
|
||||
sourceProdVersionName: "Version 22",
|
||||
targetTestVersionNumber: 7,
|
||||
targetTestVersionName: "Sync from Acme Corp [Prod v22 · #1]"
|
||||
},
|
||||
ruleMapping: [
|
||||
{
|
||||
index: 1,
|
||||
sourceRuleId: "src-rule-1",
|
||||
sourceRuleCode: 10,
|
||||
targetRuleId: "tgt-rule-1",
|
||||
targetRuleCode: "rule-1",
|
||||
description: "No alcohol above 50%",
|
||||
scope: "all",
|
||||
strictness: "MUST_FOLLOW"
|
||||
},
|
||||
{
|
||||
index: 2,
|
||||
sourceRuleId: "src-rule-2",
|
||||
sourceRuleCode: 11,
|
||||
targetRuleId: "tgt-rule-2",
|
||||
targetRuleCode: "rule-2",
|
||||
description: "Private car mileage limit",
|
||||
scope: "travel",
|
||||
strictness: "MUST_FOLLOW"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const savedFile = saveRuleMappingSnapshot(snapshot);
|
||||
expect(existsSync(savedFile)).toBe(true);
|
||||
|
||||
const loadedByVersion = loadRuleMappingSnapshot("test-1", 7);
|
||||
expect(loadedByVersion).not.toBeNull();
|
||||
expect(loadedByVersion?.target.publishedVersionNumber).toBe(7);
|
||||
expect(loadedByVersion?.ruleMapping.length).toBe(2);
|
||||
expect(loadedByVersion?.ruleMapping[0]!.sourceRuleCode).toBe(10);
|
||||
expect(loadedByVersion?.ruleMapping[0]!.targetRuleCode).toBe("rule-1");
|
||||
|
||||
const loadedByVString = loadRuleMappingSnapshot("test-1", "v7");
|
||||
expect(loadedByVString?.target.publishedVersionNumber).toBe(7);
|
||||
|
||||
const loadedLatest = loadRuleMappingSnapshot("test-1", "latest");
|
||||
expect(loadedLatest?.target.publishedVersionNumber).toBe(7);
|
||||
|
||||
const missing = loadRuleMappingSnapshot("test-1", 999);
|
||||
expect(missing).toBeNull();
|
||||
});
|
||||
|
||||
test("filterRuleMapping filters by target code, source code, and IDs", () => {
|
||||
const items = [
|
||||
{
|
||||
index: 1,
|
||||
sourceRuleId: "src-uuid-1",
|
||||
sourceRuleCode: 14,
|
||||
targetRuleId: "tgt-uuid-1",
|
||||
targetRuleCode: "rule-14",
|
||||
description: "Rule 14 desc",
|
||||
scope: "scope 1",
|
||||
strictness: "MUST_FOLLOW"
|
||||
},
|
||||
{
|
||||
index: 2,
|
||||
sourceRuleId: "src-uuid-2",
|
||||
sourceRuleCode: 15,
|
||||
targetRuleId: "tgt-uuid-2",
|
||||
targetRuleCode: "rule-15",
|
||||
description: "Rule 15 desc",
|
||||
scope: "scope 2",
|
||||
strictness: "SUGGESTION"
|
||||
}
|
||||
];
|
||||
|
||||
expect(filterRuleMapping(items)).toHaveLength(2);
|
||||
expect(filterRuleMapping(items, "rule-14")).toHaveLength(1);
|
||||
expect(filterRuleMapping(items, "rule-14")[0]!.sourceRuleCode).toBe(14);
|
||||
expect(filterRuleMapping(items, "14")).toHaveLength(1);
|
||||
expect(filterRuleMapping(items, "#14")).toHaveLength(1);
|
||||
expect(filterRuleMapping(items, "#rule-15")).toHaveLength(1);
|
||||
expect(filterRuleMapping(items, "src-uuid-2")).toHaveLength(1);
|
||||
expect(filterRuleMapping(items, "non-existent")).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("computeNextSyncIteration calculates iteration sequence accurately", () => {
|
||||
// 1. Initial sync when test enterprise has no history
|
||||
expect(computeNextSyncIteration("Acme Corp", 22, [])).toBe(1);
|
||||
|
||||
// 2. Legacy un-numbered sync exists
|
||||
expect(
|
||||
computeNextSyncIteration("Acme Corp", 22, [
|
||||
{ versionName: "Sync from Acme Corp (2026-09-11)" }
|
||||
])
|
||||
).toBe(2);
|
||||
|
||||
// 3. Structured iterations exist for same prodVersion
|
||||
expect(
|
||||
computeNextSyncIteration("Acme Corp", 22, [
|
||||
{ versionName: "Sync from Acme Corp [Prod v22 · #1]" },
|
||||
{ versionName: "Sync from Acme Corp [Prod v22 · #2]" }
|
||||
])
|
||||
).toBe(3);
|
||||
|
||||
// 4. Production version bumped to 23 -> resets to 1
|
||||
expect(
|
||||
computeNextSyncIteration("Acme Corp", 23, [
|
||||
{ versionName: "Sync from Acme Corp [Prod v22 · #1]" },
|
||||
{ versionName: "Sync from Acme Corp [Prod v22 · #2]" }
|
||||
])
|
||||
).toBe(1);
|
||||
|
||||
// 5. Production has no published version (draft only)
|
||||
expect(
|
||||
computeNextSyncIteration("Acme Corp", undefined, [
|
||||
{ versionName: "Sync from Acme Corp [Prod draft · #1]" }
|
||||
])
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
test("formatSyncVersionName formats cleanly without redundant date", () => {
|
||||
expect(formatSyncVersionName("Acme Corp", 22, 1)).toBe(
|
||||
"Sync from Acme Corp [Prod v22 · #1]"
|
||||
);
|
||||
expect(formatSyncVersionName("Acme Corp", undefined, 1)).toBe(
|
||||
"Sync from Acme Corp [Prod draft · #1]"
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
export interface RuleMappingItem {
|
||||
index: number;
|
||||
sourceRuleId: string;
|
||||
sourceRuleCode: string | number;
|
||||
targetRuleId: string;
|
||||
targetRuleCode: string | number;
|
||||
description: string;
|
||||
scope: string;
|
||||
strictness: string;
|
||||
}
|
||||
|
||||
export interface RuleMappingSnapshot {
|
||||
syncedAt: string;
|
||||
source: {
|
||||
id: string;
|
||||
name: string;
|
||||
latestPublishedVersionNumber?: number | null;
|
||||
latestPublishedVersionName?: string | null;
|
||||
};
|
||||
target: {
|
||||
id: string;
|
||||
name: string;
|
||||
publishedVersionNumber: number;
|
||||
publishedVersionName?: string | null;
|
||||
rulesCount: number;
|
||||
};
|
||||
versionMapping: {
|
||||
sourceProdVersionNumber: number | null;
|
||||
sourceProdVersionName: string | null;
|
||||
targetTestVersionNumber: number;
|
||||
targetTestVersionName: string | null;
|
||||
};
|
||||
ruleMapping: RuleMappingItem[];
|
||||
}
|
||||
|
||||
export function getMappingsDir(): string {
|
||||
const custom = process.env.SEAL_USE_MAPPINGS_DIR?.trim();
|
||||
if (custom) return custom;
|
||||
return join(homedir(), ".config", "seal-use", "mappings");
|
||||
}
|
||||
|
||||
export function saveRuleMappingSnapshot(snapshot: RuleMappingSnapshot): string {
|
||||
const dir = getMappingsDir();
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
|
||||
const versionFile = join(dir, `${snapshot.target.id}-v${snapshot.target.publishedVersionNumber}.json`);
|
||||
const latestFile = join(dir, `${snapshot.target.id}-latest.json`);
|
||||
|
||||
const content = JSON.stringify(snapshot, null, 2);
|
||||
writeFileSync(versionFile, content, { encoding: "utf-8", mode: 0o600 });
|
||||
writeFileSync(latestFile, content, { encoding: "utf-8", mode: 0o600 });
|
||||
|
||||
return versionFile;
|
||||
}
|
||||
|
||||
export function loadRuleMappingSnapshot(
|
||||
targetCorpId: string,
|
||||
versionSelector?: string | number
|
||||
): RuleMappingSnapshot | null {
|
||||
const dir = getMappingsDir();
|
||||
let filename: string;
|
||||
if (!versionSelector || versionSelector === "latest") {
|
||||
filename = `${targetCorpId}-latest.json`;
|
||||
} else {
|
||||
const vStr = String(versionSelector).replace(/^v/i, "");
|
||||
filename = `${targetCorpId}-v${vStr}.json`;
|
||||
}
|
||||
|
||||
const filePath = join(dir, filename);
|
||||
if (!existsSync(filePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = readFileSync(filePath, "utf-8");
|
||||
return JSON.parse(raw) as RuleMappingSnapshot;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function filterRuleMapping(
|
||||
mapping: RuleMappingItem[],
|
||||
codeOrId?: string
|
||||
): RuleMappingItem[] {
|
||||
if (!codeOrId) return mapping;
|
||||
const target = codeOrId.trim().toLowerCase();
|
||||
return mapping.filter((item) => {
|
||||
return (
|
||||
String(item.sourceRuleCode).toLowerCase() === target ||
|
||||
String(item.targetRuleCode).toLowerCase() === target ||
|
||||
item.sourceRuleId.toLowerCase() === target ||
|
||||
item.targetRuleId.toLowerCase() === target ||
|
||||
`#${item.sourceRuleCode}`.toLowerCase() === target ||
|
||||
`#${item.targetRuleCode}`.toLowerCase() === target
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function computeNextSyncIteration(
|
||||
prodCorpName: string,
|
||||
prodVersionNumber: number | undefined,
|
||||
testVersions: Array<{ versionName?: string | null }>
|
||||
): number {
|
||||
let maxIteration = 0;
|
||||
const prefixRegex = prodVersionNumber !== undefined
|
||||
? new RegExp(`\\[Prod v${prodVersionNumber}\\s*·\\s*#(\\d+)\\]`)
|
||||
: /\[Prod draft\s*·\s*#(\d+)\]/;
|
||||
|
||||
for (const tv of testVersions) {
|
||||
if (!tv.versionName) continue;
|
||||
const match = tv.versionName.match(prefixRegex);
|
||||
if (match && match[1]) {
|
||||
const num = parseInt(match[1], 10);
|
||||
if (!isNaN(num) && num > maxIteration) {
|
||||
maxIteration = num;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (maxIteration > 0) {
|
||||
return maxIteration + 1;
|
||||
}
|
||||
|
||||
// If no structured tag exists at all, check legacy un-numbered sync versions
|
||||
const anyStructuredTag = testVersions.some(
|
||||
(tv) => tv.versionName && /\[Prod v\d+/.test(tv.versionName)
|
||||
);
|
||||
if (!anyStructuredTag) {
|
||||
const legacySyncCount = testVersions.filter(
|
||||
(tv) => tv.versionName && tv.versionName.includes(`Sync from ${prodCorpName}`)
|
||||
).length;
|
||||
if (legacySyncCount > 0) {
|
||||
return legacySyncCount + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
export function formatSyncVersionName(
|
||||
prodCorpName: string,
|
||||
prodVersionNumber: number | undefined,
|
||||
iteration: number
|
||||
): string {
|
||||
const prodLabel = prodVersionNumber !== undefined ? `Prod v${prodVersionNumber}` : "Prod draft";
|
||||
return `Sync from ${prodCorpName} [${prodLabel} · #${iteration}]`;
|
||||
}
|
||||
Reference in new issue
Block a user