Add resilient rule version diff fallback

This commit is contained in:
gitea committed 2026-09-21 18:00:19 +08:00
1 parent c1aebc13b1
commit 3812625c30
11 files changed
+525 -303

No files matched your search

+4
View File
@@ -35,6 +35,7 @@ import {
formatSyncVersionName,
saveRuleMappingSnapshot
} from "../../domains/seal/rule-mapping.js";
import { savePublishedRuleVersionSnapshot } from "../../domains/seal/rule-version-snapshot.js";
import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../domains/seal/webhook-replay.js";
import { resolveLiveSealEnterpriseConfig } from "../../domains/seal/source.js";
import { selectCorp } from "../helpers.js";
@@ -733,6 +734,9 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
// 6. Publish new version in test enterprise
const published = await api.publishApprovalRuleVersion(testClient, versionName);
try {
savePublishedRuleVersionSnapshot(testCorp.id, published.version, createdRules);
} catch {}
const publishedRules = published.version.rules ?? [];
const ruleMapping = prodRules.rules.map((prodRule, idx) => {
+6 -3
View File
@@ -112,12 +112,13 @@ export async function handleRulesCommand(
return;
}
if (action === "diff") {
if (action === "diff" || action === "diff-one" || action === "rule-diff") {
const from = stringOption(args.options.from) ?? maybeName;
const to = stringOption(args.options.to) ?? args.command[3];
if (!from || !to) {
throw new Error("Usage: seal-use rules diff <fromVersion> <toVersion> [--rule-id <stableRuleId>]");
throw new Error("Usage: seal-use rules diff <fromVersion> <toVersion> [--rule-id <stableRuleId>|--code <code>] [--full]");
}
const singleSelector = args.command[4];
await runTool(
"seal_approval_rule_version_diff",
client,
@@ -125,8 +126,10 @@ export async function handleRulesCommand(
{
from,
to,
ruleId: stringOption(args.options.ruleId) ?? stringOption(args.options["rule-id"]),
ruleId: stringOption(args.options.ruleId) ?? stringOption(args.options["rule-id"]) ?? (action !== "diff" ? singleSelector : undefined),
code: stringOption(args.options.code),
includeUnchanged: booleanOption(args.options.includeUnchanged) ?? booleanOption(args.options["include-unchanged"]),
full: booleanOption(args.options.full),
format: stringOption(args.options.format)
},
outputOptions(args.options)
+12 -4
View File
@@ -245,14 +245,22 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "diff",
summary: "Compare two published rule versions by stable rule ID",
usage: ["seal-use rules diff <fromVersion> <toVersion> [--rule-id <stableRuleId>] [--include-unchanged] [--format unified|json] [--corp <corpId>]"],
summary: "Compare two published rule versions by persisted ID or code",
usage: ["seal-use rules diff <fromVersion> <toVersion> [--rule-id <stableRuleId>|--code <code>] [--include-unchanged] [--full] [--corp <corpId>]"],
options: [
{ flag: "--rule-id <id>", description: "Compare only one stable rule ID; never fall back to code or position" },
{ flag: "--rule-id <id>", description: "Compare only one stable rule ID" },
{ flag: "--code <code>", description: "Compare only one rule code when stable ID mapping is unavailable" },
{ flag: "--include-unchanged", description: "Include unchanged rules in the structured changes list" },
{ flag: "--full", description: "Expand an oversized diff; small diffs are returned in full by default" },
{ flag: "--format unified|json", description: "Return unified diff text together with structured metadata" }
],
description: "Compares published snapshots with stable rule IDs. The command refuses to guess when a snapshot lacks an ID, so code reordering cannot create a false match."
description: "Uses locally persisted draft IDs when available and otherwise falls back to code. Output is truncated only when the total diff exceeds the safety limit; use --full to expand it."
},
{
name: "diff-one",
summary: "Inspect one rule change",
usage: ["seal-use rules diff-one <fromVersion> <toVersion> <ruleId> [--full] [--corp <corpId>]"],
description: "Single-rule alias for rules diff; use --code when the published snapshots have no stable ID."
},
{
name: "get",
+1 -1
View File
@@ -28,7 +28,7 @@ const AREA_ALIASES: Record<string, string> = {
*/
const READ_ONLY_COMMANDS: Record<string, string[]> = {
corps: ["list", "search", "get", "current"],
rules: ["count", "list", "versions", "version", "diff", "get", "search", "lint", "linters", "pull", "map"],
rules: ["count", "list", "versions", "version", "diff", "diff-one", "get", "search", "lint", "linters", "pull", "map"],
webhook: ["ready", "status", "list", "get", "resource-pack export", "resource-pack preview"],
"approval-runs": [
"summary",
+28 -5
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { diffRuleVersions } from "./rule-diff.js";
import { diffRuleVersions, truncateRuleDiff } from "./rule-diff.js";
import { PublishedRuleSnapshotSchema, RuleSetVersionSchema, type RuleSetVersion } from "./types.js";
function version(versionNumber: number, rules: Array<Record<string, unknown>>): RuleSetVersion {
@@ -57,19 +57,20 @@ describe("published rule version diff", () => {
const result = diffRuleVersions(from, to);
expect(result.counts).toEqual({ added: 1, removed: 0, modified: 1, unchanged: 1 });
expect(result.counts).toEqual({ added: 1, removed: 0, modified: 2, unchanged: 0 });
expect(result.changes.map((change) => [change.ruleId, change.status])).toEqual([
["rule-a", "modified"],
["rule-b", "modified"],
["rule-c", "added"]
]);
expect(result.changes[0]?.changedFields).toEqual(["description"]);
expect(result.changes[0]?.changedFields).toEqual(["code", "description"]);
expect(result.changes[0]?.diff).toContain("diff --git a/rules/rule-a b/rules/rule-a");
expect(result.changes[0]?.diff).toContain("- \"description\": \"Original travel policy\"");
expect(result.changes[0]?.diff).toContain("+ \"description\": \"Updated travel policy\"");
expect(result.changes[0]?.before?.backendMetadata).toEqual({ owner: "finance" });
});
test("refuses to match snapshots without a stable ID", () => {
test("falls back to code when snapshots have no stable ID", () => {
const from = version(1, [{
code: "#0001",
description: "Policy",
@@ -83,7 +84,10 @@ describe("published rule version diff", () => {
strictness: "MUST_FOLLOW"
}]);
expect(() => diffRuleVersions(from, to)).toThrow("refuses to match by code or position");
const result = diffRuleVersions(from, to);
expect(result.identityMode).toBe("code");
expect(result.counts.modified).toBe(1);
expect(result.codeStats?.confidence).toBe("low");
});
test("rejects duplicate stable IDs within one version", () => {
@@ -95,6 +99,25 @@ describe("published rule version diff", () => {
expect(() => diffRuleVersions(version(1, rules), version(2, []))).toThrow("duplicate stable rule ID: rule-a");
});
test("reports code fallback confidence and truncates only oversized output", () => {
const from = version(1, Array.from({ length: 20 }, (_, index) => ({
code: `rule-${index + 1}`,
description: `Policy ${index + 1}`,
scope: "travel",
strictness: "MUST_FOLLOW"
})));
const to = version(2, from.rules.map((rule, index) => ({
...rule,
description: index >= 19 ? `${rule.description} changed` : rule.description
})));
const result = diffRuleVersions(from, to);
expect(result.identityMode).toBe("code");
expect(result.codeStats?.sameCodeUnchanged).toBe(19);
expect(result.codeStats?.confidence).toBe("high");
expect(truncateRuleDiff(result, 100).truncation?.truncated).toBe(true);
expect(truncateRuleDiff(result, 100, true).truncation?.truncated).toBe(false);
});
test("parses and retains backend fields omitted from the original snapshot model", () => {
const parsed = PublishedRuleSnapshotSchema.parse({
id: "rule-a",
+99 -104
View File
@@ -1,10 +1,12 @@
import type { RuleSetVersion } from "./types.js";
export type RuleDiffStatus = "added" | "removed" | "modified" | "unchanged";
export type RuleDiffIdentityMode = "stable-id" | "code";
export type RuleDiffChange = {
status: RuleDiffStatus;
ruleId: string;
identityMode: RuleDiffIdentityMode;
before?: Record<string, unknown>;
after?: Record<string, unknown>;
changedFields?: string[];
@@ -14,9 +16,20 @@ export type RuleDiffChange = {
export type RuleVersionDiff = {
from: RuleVersionRef;
to: RuleVersionRef;
identityMode: RuleDiffIdentityMode;
counts: Record<RuleDiffStatus, number>;
changes: RuleDiffChange[];
unifiedDiff: string;
codeStats?: {
oldCount: number;
newCount: number;
sameCodeCount: number;
sameCodeUnchanged: number;
sameBodyDifferentCode: number;
overlapRatio: number;
confidence: "high" | "ambiguous" | "low";
warning: string;
};
};
export type RuleVersionRef = {
@@ -26,13 +39,11 @@ export type RuleVersionRef = {
publishedAt?: number;
};
// Runtime IDs are version-local in this API and may be derived from the rule's position.
// They must never become an implicit cross-version identity.
const ID_FIELDS = ["id", "ruleId", "stableId"] as const;
const IGNORED_FIELDS = new Set([
const BASE_IGNORED_FIELDS = new Set([
...ID_FIELDS,
"code",
"ruleCode",
"runtimeRuleId",
"runtimeId",
"tenantId",
"createdAt",
"updatedAt",
@@ -41,9 +52,7 @@ const IGNORED_FIELDS = new Set([
]);
function asRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: {};
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
export function stableRuleId(rule: unknown): string | undefined {
@@ -56,159 +65,145 @@ export function stableRuleId(rule: unknown): string | undefined {
return undefined;
}
export function normalizedRuleCode(value: unknown): string | undefined {
if (value === undefined || value === null) return undefined;
const raw = String(value).trim().toLowerCase().replace(/^rule[-_:]?/, "").replace(/^#/, "");
if (!raw) return undefined;
return /^\d+$/.test(raw) ? String(Number(raw)) : raw;
}
function sortValue(value: unknown): unknown {
if (Array.isArray(value)) return value.map(sortValue);
if (!value || typeof value !== "object") return value;
return Object.fromEntries(
Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, item]) => [key, sortValue(item)])
);
return Object.fromEntries(Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, sortValue(item)]));
}
function comparableRule(rule: unknown): Record<string, unknown> {
const object = asRecord(rule);
return sortValue(
Object.fromEntries(
Object.entries(object).filter(([key]) => !IGNORED_FIELDS.has(key))
)
) as Record<string, unknown>;
function comparableRule(rule: unknown, identityMode: RuleDiffIdentityMode): Record<string, unknown> {
const ignored = new Set(BASE_IGNORED_FIELDS);
if (identityMode === "code") {
ignored.add("code");
ignored.add("ruleCode");
}
return sortValue(Object.fromEntries(Object.entries(asRecord(rule)).filter(([key]) => !ignored.has(key)))) as Record<string, unknown>;
}
function ruleLines(rule: Record<string, unknown> | undefined): string[] {
return rule ? JSON.stringify(comparableRule(rule), null, 2).split("\n") : [];
function ruleLines(rule: Record<string, unknown> | undefined, identityMode: RuleDiffIdentityMode): string[] {
return rule ? JSON.stringify(comparableRule(rule, identityMode), null, 2).split("\n") : [];
}
function lineDiff(before: string[], after: string[]): string[] {
const rows = Array.from({ length: before.length + 1 }, () => Array<number>(after.length + 1).fill(0));
for (let i = before.length - 1; i >= 0; i -= 1) {
for (let j = after.length - 1; j >= 0; j -= 1) {
rows[i]![j] = before[i] === after[j]
? rows[i + 1]![j + 1]! + 1
: Math.max(rows[i + 1]![j]!, rows[i]![j + 1]!);
}
for (let i = before.length - 1; i >= 0; i -= 1) for (let j = after.length - 1; j >= 0; j -= 1) {
rows[i]![j] = before[i] === after[j] ? rows[i + 1]![j + 1]! + 1 : Math.max(rows[i + 1]![j]!, rows[i]![j + 1]!);
}
const output: string[] = [];
let i = 0;
let j = 0;
while (i < before.length && j < after.length) {
if (before[i] === after[j]) {
output.push(` ${before[i]}`);
i += 1;
j += 1;
} else if (rows[i + 1]![j]! >= rows[i]![j + 1]!) {
output.push(`-${before[i]}`);
i += 1;
} else {
output.push(`+${after[j]}`);
j += 1;
}
if (before[i] === after[j]) { output.push(` ${before[i]}`); i += 1; j += 1; }
else if (rows[i + 1]![j]! >= rows[i]![j + 1]!) output.push(`-${before[i++]}`);
else output.push(`+${after[j++]}`);
}
while (i < before.length) output.push(`-${before[i++]}`);
while (j < after.length) output.push(`+${after[j++]}`);
return output;
}
function formatPatch(
ruleId: string,
from: RuleVersionRef,
to: RuleVersionRef,
before: Record<string, unknown> | undefined,
after: Record<string, unknown> | undefined
): string {
const beforeLines = ruleLines(before);
const afterLines = ruleLines(after);
const fromLabel = `v${from.versionNumber}`;
const toLabel = `v${to.versionNumber}`;
function formatPatch(ruleId: string, from: RuleVersionRef, to: RuleVersionRef, before: Record<string, unknown> | undefined, after: Record<string, unknown> | undefined, identityMode: RuleDiffIdentityMode): string {
const beforeLines = ruleLines(before, identityMode);
const afterLines = ruleLines(after, identityMode);
const oldPath = before ? `a/rules/${ruleId}` : "/dev/null";
const newPath = after ? `b/rules/${ruleId}` : "/dev/null";
const oldCount = beforeLines.length;
const newCount = afterLines.length;
const oldStart = oldCount ? 1 : 0;
const newStart = newCount ? 1 : 0;
return [
`diff --git a/rules/${ruleId} b/rules/${ruleId}`,
`--- ${oldPath}\t${fromLabel}`,
`+++ ${newPath}\t${toLabel}`,
`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`,
`--- ${oldPath}\tv${from.versionNumber}`,
`+++ ${newPath}\tv${to.versionNumber}`,
`@@ -${beforeLines.length ? 1 : 0},${beforeLines.length} +${afterLines.length ? 1 : 0},${afterLines.length} @@`,
...lineDiff(beforeLines, afterLines)
].join("\n");
}
function versionRef(version: RuleSetVersion): RuleVersionRef {
return {
id: version.id,
versionNumber: version.versionNumber,
versionName: version.versionName,
publishedAt: version.publishedAt
};
return { id: version.id, versionNumber: version.versionNumber, versionName: version.versionName, publishedAt: version.publishedAt };
}
function indexRules(version: RuleSetVersion): Map<string, Record<string, unknown>> {
function indexRules(version: RuleSetVersion, mode: RuleDiffIdentityMode): Map<string, Record<string, unknown>> {
const indexed = new Map<string, Record<string, unknown>>();
for (const rule of version.rules) {
const object = asRecord(rule);
const id = stableRuleId(object);
if (!id) {
throw new Error(
`Rule version ${version.versionNumber} contains a rule without a stable rule ID. ` +
"Cross-version diff refuses to match by code or position."
);
}
if (indexed.has(id)) throw new Error(`Rule version ${version.versionNumber} contains duplicate stable rule ID: ${id}`);
indexed.set(id, object);
const key = mode === "stable-id" ? stableRuleId(object) : normalizedRuleCode(object.code ?? object.ruleCode);
if (!key) throw new Error(`Rule version ${version.versionNumber} contains a rule without a ${mode === "stable-id" ? "stable rule ID" : "code"}.`);
if (indexed.has(key)) throw new Error(`Rule version ${version.versionNumber} contains duplicate ${mode === "stable-id" ? "stable rule ID" : "code"}: ${key}`);
indexed.set(key, object);
}
return indexed;
}
export function diffRuleVersions(
fromVersion: RuleSetVersion,
toVersion: RuleSetVersion,
options: { includeUnchanged?: boolean } = {}
): RuleVersionDiff {
const before = indexRules(fromVersion);
const after = indexRules(toVersion);
const ids = [...new Set([...before.keys(), ...after.keys()])];
function chooseIdentityMode(fromVersion: RuleSetVersion, toVersion: RuleSetVersion, requested: "auto" | RuleDiffIdentityMode): RuleDiffIdentityMode {
if (requested !== "auto") return requested;
const allHaveIds = [...fromVersion.rules, ...toVersion.rules].every((rule) => Boolean(stableRuleId(rule)));
if (allHaveIds) return "stable-id";
const allHaveCodes = [...fromVersion.rules, ...toVersion.rules].every((rule) => Boolean(normalizedRuleCode(asRecord(rule).code ?? asRecord(rule).ruleCode)));
if (allHaveCodes) return "code";
throw new Error("Rule snapshots have neither a complete stable-ID mapping nor a complete code mapping.");
}
export function diffRuleVersions(fromVersion: RuleSetVersion, toVersion: RuleSetVersion, options: { includeUnchanged?: boolean; identityMode?: "auto" | RuleDiffIdentityMode } = {}): RuleVersionDiff {
const identityMode = chooseIdentityMode(fromVersion, toVersion, options.identityMode ?? "auto");
const before = indexRules(fromVersion, identityMode);
const after = indexRules(toVersion, identityMode);
const keys = [...new Set([...before.keys(), ...after.keys()])];
const changes: RuleDiffChange[] = [];
const counts: Record<RuleDiffStatus, number> = { added: 0, removed: 0, modified: 0, unchanged: 0 };
const from = versionRef(fromVersion);
const to = versionRef(toVersion);
for (const ruleId of ids) {
for (const ruleId of keys) {
const beforeRule = before.get(ruleId);
const afterRule = after.get(ruleId);
let status: RuleDiffStatus;
if (!beforeRule) status = "added";
else if (!afterRule) status = "removed";
else if (JSON.stringify(comparableRule(beforeRule)) !== JSON.stringify(comparableRule(afterRule))) status = "modified";
else status = "unchanged";
const beforeComparable = beforeRule ? comparableRule(beforeRule, identityMode) : undefined;
const afterComparable = afterRule ? comparableRule(afterRule, identityMode) : undefined;
const status: RuleDiffStatus = !beforeRule ? "added" : !afterRule ? "removed" : JSON.stringify(beforeComparable) !== JSON.stringify(afterComparable) ? "modified" : "unchanged";
counts[status] += 1;
if (status === "unchanged" && !options.includeUnchanged) continue;
const beforeComparable = beforeRule ? comparableRule(beforeRule) : undefined;
const afterComparable = afterRule ? comparableRule(afterRule) : undefined;
const changedFields = status === "modified"
? [...new Set([...Object.keys(beforeComparable ?? {}), ...Object.keys(afterComparable ?? {})])]
.filter((key) => JSON.stringify(beforeComparable?.[key]) !== JSON.stringify(afterComparable?.[key]))
: undefined;
const changedFields = status === "modified" ? [...new Set([...Object.keys(beforeComparable ?? {}), ...Object.keys(afterComparable ?? {})])].filter((key) => JSON.stringify(beforeComparable?.[key]) !== JSON.stringify(afterComparable?.[key])) : undefined;
changes.push({
status,
ruleId,
identityMode,
...(beforeRule ? { before: beforeRule } : {}),
...(afterRule ? { after: afterRule } : {}),
...(changedFields?.length ? { changedFields } : {}),
...(status !== "unchanged" ? { diff: formatPatch(ruleId, from, to, beforeRule, afterRule) } : {})
...(status !== "unchanged" ? { diff: formatPatch(ruleId, from, to, beforeRule, afterRule, identityMode) } : {})
});
}
const unifiedDiff = changes
.filter((change) => change.diff)
.map((change) => change.diff)
.join("\n");
const result: RuleVersionDiff = { from, to, identityMode, counts, changes, unifiedDiff: changes.filter((change) => change.diff).map((change) => change.diff).join("\n") };
if (identityMode === "code") {
const sameCodeCount = keys.filter((key) => before.has(key) && after.has(key)).length;
const sameCodeUnchanged = keys.filter((key) => before.has(key) && after.has(key) && JSON.stringify(comparableRule(before.get(key), "code")) === JSON.stringify(comparableRule(after.get(key), "code"))).length;
const oldCount = before.size;
const newCount = after.size;
const overlapRatio = Math.min(oldCount, newCount) ? sameCodeCount / Math.min(oldCount, newCount) : 1;
const beforeBodies = new Map<string, string>();
for (const [code, rule] of before) beforeBodies.set(JSON.stringify(comparableRule(rule, "code")), code);
let sameBodyDifferentCode = 0;
for (const [code, rule] of after) {
const oldCode = beforeBodies.get(JSON.stringify(comparableRule(rule, "code")));
if (oldCode && oldCode !== code) sameBodyDifferentCode += 1;
}
const unchangedRatio = Math.min(oldCount, newCount) ? sameCodeUnchanged / Math.min(oldCount, newCount) : 1;
const confidence = unchangedRatio >= 0.5 ? "high" : sameCodeUnchanged > 0 || sameBodyDifferentCode > 0 ? "ambiguous" : "low";
result.codeStats = { oldCount, newCount, sameCodeCount, sameCodeUnchanged, sameBodyDifferentCode, overlapRatio, confidence, warning: "Published snapshots do not carry stable IDs; code matching can report reorderings as remove/add or modified rules." };
}
return result;
}
return { from, to, counts, changes, unifiedDiff };
export function truncateRuleDiff<T extends RuleVersionDiff>(result: T, maxChars = 20_000, full = false): T & { truncation?: { truncated: boolean; maxChars: number; omittedChars: number; hint: string } } {
if (full || result.unifiedDiff.length <= maxChars) return { ...result, truncation: { truncated: false, maxChars, omittedChars: 0, hint: "Use --full only when the complete diff is required." } };
const omittedChars = result.unifiedDiff.length - maxChars;
const marker = `\n... [diff truncated: ${omittedChars} characters omitted; rerun with --full for the complete diff]`;
const compactChanges = result.changes.map(({ before: _before, after: _after, diff, ...change }) => ({ ...change, ...(diff ? { diff: diff.length > maxChars ? `${diff.slice(0, maxChars)}${marker}` : diff } : {}) }));
return { ...result, changes: compactChanges as T["changes"], unifiedDiff: `${result.unifiedDiff.slice(0, maxChars)}${marker}`, truncation: { truncated: true, maxChars, omittedChars, hint: "Use --full for the complete diff." } };
}
@@ -0,0 +1,43 @@
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 {
hydrateRuleVersionStableIds,
loadPublishedRuleVersionSnapshot,
savePublishedRuleVersionSnapshot
} from "./rule-version-snapshot.js";
import type { RuleSetVersion } from "./types.js";
const originalDir = process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR;
let testDir = "";
afterEach(() => {
if (originalDir === undefined) delete process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR;
else process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR = originalDir;
if (testDir) rmSync(testDir, { recursive: true, force: true });
testDir = "";
});
describe("published rule version identity snapshots", () => {
test("persists draft IDs and hydrates API snapshots that only expose code", () => {
testDir = mkdtempSync(join(tmpdir(), "seal-use-rule-snapshot-"));
process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR = testDir;
const version = {
id: "published-1",
versionNumber: 1,
rules: [
{ code: "rule-0", description: "A", scope: "ALL", strictness: "MUST_FOLLOW" },
{ code: "rule-1", description: "B", scope: "ALL", strictness: "SHOULD_FOLLOW" }
]
} as RuleSetVersion;
savePublishedRuleVersionSnapshot("corp/a", version, [
{ id: "draft-a", code: 0, description: "A", scope: "ALL", strictness: "MUST_FOLLOW" },
{ id: "draft-b", code: 1, description: "B", scope: "ALL", strictness: "SHOULD_FOLLOW" }
]);
expect(loadPublishedRuleVersionSnapshot("corp/a", version)?.rules.map((rule) => rule.stableId)).toEqual(["draft-a", "draft-b"]);
const hydrated = hydrateRuleVersionStableIds("corp/a", version);
expect(hydrated.rules.map((rule) => rule.stableId)).toEqual(["draft-a", "draft-b"]);
});
});
+122
View File
@@ -0,0 +1,122 @@
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import type { ApprovalRule, RuleSetVersion } from "./types.js";
export type PersistedRuleIdentity = {
stableId: string;
code?: string | number;
description: string;
scope: string;
strictness: string;
};
export type PersistedRuleVersionSnapshot = {
corpId: string;
versionId: string;
versionNumber: number;
capturedAt: string;
rules: PersistedRuleIdentity[];
};
function normalizeCode(value: unknown): string | undefined {
if (value === undefined || value === null) return undefined;
const raw = String(value).trim().toLowerCase().replace(/^rule[-_:]?/, "").replace(/^#/, "");
if (!raw) return undefined;
return /^\d+$/.test(raw) ? String(Number(raw)) : raw;
}
function signature(rule: { description?: string; scope?: string; strictness?: string }): string {
return JSON.stringify([rule.description ?? "", rule.scope ?? "", rule.strictness ?? ""]);
}
export function getRuleVersionSnapshotsDir(): string {
return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim() ||
join(homedir(), ".config", "seal-use", "rule-version-snapshots");
}
function safeCorpId(corpId: string): string {
return corpId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
function snapshotPath(corpId: string, versionNumber: number): string {
return join(getRuleVersionSnapshotsDir(), `${safeCorpId(corpId)}-v${versionNumber}.json`);
}
export function savePublishedRuleVersionSnapshot(
corpId: string,
version: RuleSetVersion,
draftRules: ApprovalRule[]
): string {
const byCode = new Map<string, ApprovalRule[]>();
const bySignature = new Map<string, ApprovalRule[]>();
for (const draft of draftRules) {
const code = normalizeCode(draft.code);
if (code) byCode.set(code, [...(byCode.get(code) ?? []), draft]);
const key = signature(draft);
bySignature.set(key, [...(bySignature.get(key) ?? []), draft]);
}
const rules: PersistedRuleIdentity[] = [];
for (const published of version.rules ?? []) {
const code = normalizeCode(published.code);
const codeMatches = code ? byCode.get(code) ?? [] : [];
const signatureMatches = bySignature.get(signature(published)) ?? [];
const match = codeMatches.length === 1 ? codeMatches[0] : signatureMatches.length === 1 ? signatureMatches[0] : undefined;
if (!match) continue;
rules.push({
stableId: match.id,
...(published.code !== undefined ? { code: published.code } : {}),
description: published.description,
scope: published.scope,
strictness: published.strictness
});
}
const snapshot: PersistedRuleVersionSnapshot = {
corpId,
versionId: version.id,
versionNumber: version.versionNumber,
capturedAt: new Date().toISOString(),
rules
};
const dir = getRuleVersionSnapshotsDir();
mkdirSync(dir, { recursive: true, mode: 0o700 });
const path = snapshotPath(corpId, version.versionNumber);
const temp = `${path}.${process.pid}.tmp`;
writeFileSync(temp, `${JSON.stringify(snapshot, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
renameSync(temp, path);
return path;
}
export function loadPublishedRuleVersionSnapshot(
corpId: string,
version: Pick<RuleSetVersion, "versionNumber">
): PersistedRuleVersionSnapshot | null {
const path = snapshotPath(corpId, version.versionNumber);
if (!existsSync(path)) return null;
try {
return JSON.parse(readFileSync(path, "utf8")) as PersistedRuleVersionSnapshot;
} catch {
return null;
}
}
export function hydrateRuleVersionStableIds(corpId: string, version: RuleSetVersion): RuleSetVersion {
const snapshot = loadPublishedRuleVersionSnapshot(corpId, version);
if (!snapshot?.rules.length) return version;
const byCode = new Map(snapshot.rules.flatMap((rule) => {
const code = normalizeCode(rule.code);
return code ? [[code, rule] as const] : [];
}));
const bySignature = new Map(snapshot.rules.map((rule) => [signature(rule), rule]));
return {
...version,
rules: version.rules.map((rule) => {
if (rule.id !== undefined || rule.ruleId !== undefined || rule.stableId !== undefined) return rule;
const match = (normalizeCode(rule.code) ? byCode.get(normalizeCode(rule.code)!) : undefined) ?? bySignature.get(signature(rule));
return match ? { ...rule, stableId: match.stableId } : rule;
})
};
}
+33 -13
View File
@@ -10,7 +10,8 @@ import { resolveCorpConfig } from "../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import { searchApprovalContent } from "./search.js";
import { diffRuleVersions } from "./rule-diff.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "./rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "./rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "./webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "./linter/index.js";
import {
@@ -563,12 +564,14 @@ export const sealTools = [
},
{
name: "seal_approval_rule_version_diff",
description: "按稳定规则 ID 对比两个已发布审批规则版本,返回新增、删除、修改和 Unified Diff",
description: "对比两个已发布审批规则版本;优先使用本地持久化稳定 ID,没有时回退到 code",
parameters: z.object({
from: z.string().min(1).describe("起始规则版本号、版本 ID 或 latest"),
to: z.string().min(1).describe("目标规则版本号、版本 ID 或 latest"),
ruleId: z.string().optional().describe("只对比指定稳定规则 ID"),
code: z.string().optional().describe("只对比指定规则 code"),
includeUnchanged: z.boolean().optional().describe("是否返回未变化规则,默认 false"),
full: z.boolean().optional().describe("超过默认 diff 上限时返回完整内容"),
format: z.enum(["unified", "json"]).default("unified").describe("输出格式;unified 将 diff 文本放入 unifiedDiff 字段")
}),
handler: async (
@@ -577,27 +580,34 @@ export const sealTools = [
from: string;
to: string;
ruleId?: string;
code?: string;
includeUnchanged?: boolean;
full?: boolean;
format?: "unified" | "json";
}
},
context: ToolContext
) => {
const fromVersion = await resolveRuleVersionSelector(client, params.from);
const toVersion = await resolveRuleVersionSelector(client, params.to);
const result = diffRuleVersions(fromVersion, toVersion, {
const fromVersion = hydrateRuleVersionStableIds(context.corp.id, await resolveRuleVersionSelector(client, params.from));
const toVersion = hydrateRuleVersionStableIds(context.corp.id, await resolveRuleVersionSelector(client, params.to));
let result = diffRuleVersions(fromVersion, toVersion, {
includeUnchanged: params.includeUnchanged
});
if (!params.ruleId) return { ...result, format: params.format ?? "unified" };
if (!params.ruleId && !params.code) return { ...truncateRuleDiff(result, 20_000, params.full === true), format: params.format ?? "unified" };
const changes = result.changes.filter((change) => change.ruleId === params.ruleId);
const changes = result.changes.filter((change) => {
if (params.ruleId && change.ruleId === params.ruleId) return true;
if (!params.code) return false;
return normalizedRuleCode(params.code) === normalizedRuleCode(change.before?.code ?? change.before?.ruleCode ?? change.after?.code ?? change.after?.ruleCode ?? change.ruleId);
});
const counts = { added: 0, removed: 0, modified: 0, unchanged: 0 };
for (const change of changes) counts[change.status] += 1;
return {
result = {
...result,
counts,
changes,
unifiedDiff: changes.map((change) => change.diff).filter(Boolean).join("\n"),
format: params.format ?? "unified"
unifiedDiff: changes.map((change) => change.diff).filter(Boolean).join("\n")
};
return { ...truncateRuleDiff(result, 20_000, params.full === true), format: params.format ?? "unified" };
}
},
{
@@ -606,8 +616,14 @@ export const sealTools = [
parameters: z.object({
versionName: z.string().describe("版本名称")
}),
handler: async (client: KyInstance, params: { versionName: string }) =>
api.publishApprovalRuleVersion(client, params.versionName)
handler: async (client: KyInstance, params: { versionName: string }, context: ToolContext) => {
const draft = await api.listApprovalRules(client).catch(() => undefined);
const published = await api.publishApprovalRuleVersion(client, params.versionName);
if (draft) {
try { savePublishedRuleVersionSnapshot(context.corp.id, published.version, draft.rules); } catch {}
}
return published;
}
},
{
name: "seal_approval_rule_get",
@@ -899,6 +915,10 @@ export const sealTools = [
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
publishedVersion = await api.publishApprovalRuleVersion(client, name);
try {
const draft = await api.listApprovalRules(client);
savePublishedRuleVersionSnapshot(context.corp.id, (publishedVersion as { version: RuleSetVersion }).version, draft.rules);
} catch {}
}
return {