Files
seal-use/src/domains/seal/rule-diff.ts
T

210 lines
10 KiB
TypeScript

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[];
diff?: string;
};
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 = {
id: string;
versionNumber: number;
versionName?: string | null;
publishedAt?: number;
};
const ID_FIELDS = ["id", "ruleId", "stableId"] as const;
const BASE_IGNORED_FIELDS = new Set([
...ID_FIELDS,
"runtimeRuleId",
"runtimeId",
"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;
}
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)]));
}
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, 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]!);
}
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++]}`);
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, 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";
return [
`diff --git a/rules/${ruleId} b/rules/${ruleId}`,
`--- ${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 };
}
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 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;
}
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 keys) {
const beforeRule = before.get(ruleId);
const afterRule = after.get(ruleId);
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 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, identityMode) } : {})
});
}
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;
}
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." } };
}