import { getRepository } from '@things-factory/shell' import { TwinReferenceReconciliation } from './twin-reference-reconciliation.js' import { reconcileReferenceSequence, type ReferenceRange } from './reference-reconciliation.js' /** backfill이 원본 범위를 실제로 읽은 뒤에만 최신 대사 상태를 갱신한다. */ export async function recordReferenceReconciliation(args: { domainId: string instanceId: string scope: string sourceRange?: ReferenceRange cursorSeq?: number firstSeqSeen?: number }): Promise { const { domainId, instanceId, scope, sourceRange, cursorSeq, firstSeqSeen } = args if (!sourceRange) return const verdict = reconcileReferenceSequence({ source: sourceRange, cursorSeq, firstSeqSeen }) const repo = getRepository(TwinReferenceReconciliation) const previous = await repo.findOne({ where: { domain: { id: domainId }, instanceId, scope } }) await repo.save( repo.create({ ...(previous ?? {}), domain: { id: domainId } as any, instanceId, scope, status: verdict.status, /* TypeORM은 undefined를 "갱신하지 않음"으로 읽는다. 현재 대사가 맞아진 뒤 옛 gap 수가 * 남지 않게 nullable 칸은 명시적으로 null로 지운다. */ sourceFirst: verdict.sourceFirst ?? null, sourceLast: verdict.sourceLast ?? null, cursorSeq: verdict.cursorSeq ?? null, firstSeqSeen: verdict.firstSeqSeen ?? null, headMissing: verdict.headMissing ?? null, behind: verdict.behind ?? null, reason: verdict.reason ?? null, checkedAt: new Date() }) ) }