fix: reconcile unchanged document hits after API conflict

This commit is contained in:
muena
2026-10-19 11:02:18 +02:00
parent 031eaa978f
commit 4aad9886fc
3 changed files with 81 additions and 7 deletions

View File

@@ -64,6 +64,44 @@ export function spansBySegment<T extends { start: number; end: number }>(
}
export type GroupableHit = { id: string; type: string; original: string; placeholder: string };
export type DocumentReviewHit = { id: string; source: string; start: number; end: number;
type: string; original: string; context: string };
/** Rebind approved document hits only when the reviewed occurrence is unchanged. */
export function reconcileDocumentHitIds(
reviewed: DocumentReviewHit[], acceptedIds: readonly string[], refreshed: DocumentReviewHit[],
): string[] | null {
const key = (hit: DocumentReviewHit) => JSON.stringify([
hit.source, hit.start, hit.end, hit.type, hit.original, hit.context,
]);
const reviewedById = new Map(reviewed.map((hit) => [hit.id, hit]));
const reviewedByKey = new Map<string, DocumentReviewHit[]>();
const refreshedByKey = new Map<string, DocumentReviewHit[]>();
for (const hit of reviewed) (reviewedByKey.get(key(hit)) ??
(reviewedByKey.set(key(hit), []), reviewedByKey.get(key(hit))!)).push(hit);
for (const hit of refreshed) (refreshedByKey.get(key(hit)) ??
(refreshedByKey.set(key(hit), []), refreshedByKey.get(key(hit))!)).push(hit);
const acceptedByKey = new Map<string, Set<string>>();
for (const id of acceptedIds) {
const hit = reviewedById.get(id);
if (!hit) return null;
(acceptedByKey.get(key(hit)) ?? (acceptedByKey.set(key(hit), new Set()), acceptedByKey.get(key(hit))!)).add(id);
}
const resolved: string[] = [];
for (const [signature, selected] of acceptedByKey) {
const old = reviewedByKey.get(signature)!;
const fresh = refreshedByKey.get(signature);
if (!fresh || fresh.length !== old.length) return null;
if (selected.size === old.length) resolved.push(...fresh.map((hit) => hit.id));
else {
const matching = fresh.filter((hit) => selected.has(hit.id));
if (matching.length !== selected.size) return null;
resolved.push(...matching.map((hit) => hit.id));
}
}
return resolved;
}
export type ReviewGroup<T extends GroupableHit> = {
key: string; type: string; original: string; placeholder: string; hits: T[];
};