Add stable-ID rule version diff

This commit is contained in:
gitea committed 2026-09-21 17:27:45 +08:00
1 parent c4428efd19
commit a8a28623df
9 files changed
+599 -158

No files matched your search

+23 -1
View File
@@ -112,6 +112,28 @@ export async function handleRulesCommand(
return;
}
if (action === "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>]");
}
await runTool(
"seal_approval_rule_version_diff",
client,
corp,
{
from,
to,
ruleId: stringOption(args.options.ruleId) ?? stringOption(args.options["rule-id"]),
includeUnchanged: booleanOption(args.options.includeUnchanged) ?? booleanOption(args.options["include-unchanged"]),
format: stringOption(args.options.format)
},
outputOptions(args.options)
);
return;
}
if (action === "get") {
await runTool(
"seal_approval_rule_get",
@@ -260,5 +282,5 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, linters, pull, push, map. Run 'seal-use help' for available commands.`);
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, diff, get, search, lint, linters, pull, push, map. Run 'seal-use help' for available commands.`);
}
+11
View File
@@ -243,6 +243,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
summary: "Inspect a specific rule version",
usage: ["seal-use rules version <versionId|versionNumber|latest> [--corp <corpId>]"]
},
{
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>]"],
options: [
{ flag: "--rule-id <id>", description: "Compare only one stable rule ID; never fall back to code or position" },
{ flag: "--include-unchanged", description: "Include unchanged rules in the structured changes list" },
{ 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."
},
{
name: "get",
summary: "Get single rule by code or record ID",
+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", "get", "search", "lint", "linters", "pull", "map"],
rules: ["count", "list", "versions", "version", "diff", "get", "search", "lint", "linters", "pull", "map"],
webhook: ["ready", "status", "list", "get", "resource-pack export", "resource-pack preview"],
"approval-runs": [
"summary",
+121
View File
@@ -0,0 +1,121 @@
import { describe, expect, test } from "bun:test";
import { diffRuleVersions } from "./rule-diff.js";
import { PublishedRuleSnapshotSchema, RuleSetVersionSchema, type RuleSetVersion } from "./types.js";
function version(versionNumber: number, rules: Array<Record<string, unknown>>): RuleSetVersion {
return {
id: `version-${versionNumber}`,
versionNumber,
versionName: `v${versionNumber}`,
rules
} as RuleSetVersion;
}
describe("published rule version diff", () => {
test("preserves unknown snapshot fields and matches reordered rules by stable ID", () => {
const from = version(1, [
{
id: "rule-a",
code: "#0001",
description: "Original travel policy",
scope: "travel",
strictness: "MUST_FOLLOW",
backendMetadata: { owner: "finance" }
},
{
id: "rule-b",
code: "#0002",
description: "Meal policy",
scope: "meal",
strictness: "SHOULD_FOLLOW"
}
]);
const to = version(2, [
{
id: "rule-b",
code: "#0001",
description: "Meal policy",
scope: "meal",
strictness: "SHOULD_FOLLOW"
},
{
id: "rule-a",
code: "#0002",
description: "Updated travel policy",
scope: "travel",
strictness: "MUST_FOLLOW",
backendMetadata: { owner: "finance" }
},
{
id: "rule-c",
code: "#0003",
description: "New invoice policy",
scope: "invoice",
strictness: "SUGGESTION"
}
]);
const result = diffRuleVersions(from, to);
expect(result.counts).toEqual({ added: 1, removed: 0, modified: 1, unchanged: 1 });
expect(result.changes.map((change) => [change.ruleId, change.status])).toEqual([
["rule-a", "modified"],
["rule-c", "added"]
]);
expect(result.changes[0]?.changedFields).toEqual(["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", () => {
const from = version(1, [{
code: "#0001",
description: "Policy",
scope: "travel",
strictness: "MUST_FOLLOW"
}]);
const to = version(2, [{
code: "#0001",
description: "Policy changed",
scope: "travel",
strictness: "MUST_FOLLOW"
}]);
expect(() => diffRuleVersions(from, to)).toThrow("refuses to match by code or position");
});
test("rejects duplicate stable IDs within one version", () => {
const rules = [
{ id: "rule-a", description: "A", scope: "travel", strictness: "MUST_FOLLOW" },
{ id: "rule-a", description: "B", scope: "meal", strictness: "SHOULD_FOLLOW" }
];
expect(() => diffRuleVersions(version(1, rules), version(2, []))).toThrow("duplicate stable rule ID: rule-a");
});
test("parses and retains backend fields omitted from the original snapshot model", () => {
const parsed = PublishedRuleSnapshotSchema.parse({
id: "rule-a",
code: "#0001",
description: "Policy",
scope: "travel",
strictness: "MUST_FOLLOW",
backendMetadata: { source: "published" }
});
expect(parsed).toMatchObject({
id: "rule-a",
backendMetadata: { source: "published" }
});
const versionWithExtraField = RuleSetVersionSchema.parse({
id: "version-1",
versionNumber: 1,
rules: [parsed],
backendVersionMetadata: { source: "published" }
});
expect(versionWithExtraField.backendVersionMetadata).toEqual({ source: "published" });
});
});
+214
View File
@@ -0,0 +1,214 @@
import type { RuleSetVersion } from "./types.js";
export type RuleDiffStatus = "added" | "removed" | "modified" | "unchanged";
export type RuleDiffChange = {
status: RuleDiffStatus;
ruleId: string;
before?: Record<string, unknown>;
after?: Record<string, unknown>;
changedFields?: string[];
diff?: string;
};
export type RuleVersionDiff = {
from: RuleVersionRef;
to: RuleVersionRef;
counts: Record<RuleDiffStatus, number>;
changes: RuleDiffChange[];
unifiedDiff: string;
};
export type RuleVersionRef = {
id: string;
versionNumber: number;
versionName?: string | null;
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([
...ID_FIELDS,
"code",
"ruleCode",
"tenantId",
"createdAt",
"updatedAt",
"versionId",
"versionNumber"
]);
function asRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: {};
}
export function stableRuleId(rule: unknown): string | undefined {
const object = asRecord(rule);
for (const field of ID_FIELDS) {
const value = object[field];
if (typeof value === "string" && value.trim()) return value.trim();
if (typeof value === "number" && Number.isFinite(value)) return String(value);
}
return undefined;
}
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)])
);
}
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 ruleLines(rule: Record<string, unknown> | undefined): string[] {
return rule ? JSON.stringify(comparableRule(rule), 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]!);
}
}
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;
}
}
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}`;
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} @@`,
...lineDiff(beforeLines, afterLines)
].join("\n");
}
function versionRef(version: RuleSetVersion): RuleVersionRef {
return {
id: version.id,
versionNumber: version.versionNumber,
versionName: version.versionName,
publishedAt: version.publishedAt
};
}
function indexRules(version: RuleSetVersion): 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);
}
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()])];
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) {
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";
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;
changes.push({
status,
ruleId,
...(beforeRule ? { before: beforeRule } : {}),
...(afterRule ? { after: afterRule } : {}),
...(changedFields?.length ? { changedFields } : {}),
...(status !== "unchanged" ? { diff: formatPatch(ruleId, from, to, beforeRule, afterRule) } : {})
});
}
const unifiedDiff = changes
.filter((change) => change.diff)
.map((change) => change.diff)
.join("\n");
return { from, to, counts, changes, unifiedDiff };
}
+62
View File
@@ -10,6 +10,7 @@ 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 { executeApprovalRunsReplay, resolveReplayCorpPair } from "./webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "./linter/index.js";
import {
@@ -560,6 +561,45 @@ export const sealTools = [
return version;
}
},
{
name: "seal_approval_rule_version_diff",
description: "按稳定规则 ID 对比两个已发布审批规则版本,返回新增、删除、修改和 Unified Diff",
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"),
includeUnchanged: z.boolean().optional().describe("是否返回未变化规则,默认 false"),
format: z.enum(["unified", "json"]).default("unified").describe("输出格式;unified 将 diff 文本放入 unifiedDiff 字段")
}),
handler: async (
client: KyInstance,
params: {
from: string;
to: string;
ruleId?: string;
includeUnchanged?: boolean;
format?: "unified" | "json";
}
) => {
const fromVersion = await resolveRuleVersionSelector(client, params.from);
const toVersion = await resolveRuleVersionSelector(client, params.to);
const result = diffRuleVersions(fromVersion, toVersion, {
includeUnchanged: params.includeUnchanged
});
if (!params.ruleId) return { ...result, format: params.format ?? "unified" };
const changes = result.changes.filter((change) => change.ruleId === params.ruleId);
const counts = { added: 0, removed: 0, modified: 0, unchanged: 0 };
for (const change of changes) counts[change.status] += 1;
return {
...result,
counts,
changes,
unifiedDiff: changes.map((change) => change.diff).filter(Boolean).join("\n"),
format: params.format ?? "unified"
};
}
},
{
name: "seal_approval_rule_version_publish",
description: "发布 Seal 草稿审批规则为新版本",
@@ -2732,6 +2772,7 @@ export const SEAL_READ_ONLY_TOOLS: ReadonlySet<string> = new Set([
"seal_approval_document_get",
"seal_approval_documents_list",
"seal_approval_rule_get",
"seal_approval_rule_version_diff",
"seal_approval_rule_version_get",
"seal_approval_rule_versions_list",
"seal_approval_rules_lint",
@@ -3842,6 +3883,27 @@ async function resolveRuleVersion(
return version;
}
async function resolveRuleVersionSelector(client: KyInstance, selector: string): Promise<RuleSetVersion> {
const normalized = selector.trim();
if (!normalized) throw new Error("Rule version selector cannot be empty");
if (normalized === "latest") {
const versions = await api.listApprovalRuleVersions(client);
const latest = versions[0];
if (!latest) throw new Error("No rule versions found");
return api.getApprovalRuleVersion(client, latest.id);
}
const versionNumber = Number(normalized);
if (Number.isInteger(versionNumber) && versionNumber > 0) {
const versions = await api.listApprovalRuleVersions(client);
const version = versions.find((item) => item.versionNumber === versionNumber);
if (!version) throw new Error(`Rule version not found: ${versionNumber}`);
return api.getApprovalRuleVersion(client, version.id);
}
return api.getApprovalRuleVersion(client, normalized);
}
function filterRuns(records: ApprovalRun[], query?: string): ApprovalRun[] {
const normalized = query?.trim().toLowerCase();
if (!normalized) return records;
+8 -3
View File
@@ -89,11 +89,16 @@ export const ApprovalRulesDataSchema = z.object({
});
export const PublishedRuleSnapshotSchema = z.object({
code: z.string().optional(),
id: z.union([z.string(), z.number()]).optional(),
ruleId: z.union([z.string(), z.number()]).optional(),
stableId: z.union([z.string(), z.number()]).optional(),
runtimeRuleId: z.union([z.string(), z.number()]).optional(),
runtimeId: z.union([z.string(), z.number()]).optional(),
code: z.union([z.string(), z.number()]).optional(),
description: z.string(),
scope: z.string(),
strictness: z.string()
});
}).passthrough();
export const RuleSetVersionSchema = z.object({
id: z.string(),
@@ -105,7 +110,7 @@ export const RuleSetVersionSchema = z.object({
rules: z.array(PublishedRuleSnapshotSchema).default([]),
publishedAt: z.number().optional(),
createdAt: z.number().optional()
});
}).passthrough();
export const PublishVersionDataSchema = z.object({
version: RuleSetVersionSchema,