import type mongoose from "mongoose"; import { Schema } from "mongoose"; import { anonymizeIdentifier } from "@eval/anonymize"; import type { HandoffReason } from "@agent/types"; import type { SupervisorReviewResolution } from "@skills/supervisor/review-queue"; import { NoopEscalationHistoryService, type EscalationHistoryService, type UserEscalationHistory, type UserEscalationRecord, } from "./escalation-history.js"; export const ESCALATION_HISTORY_COLLECTION = "user_escalation_history"; interface EscalationHistoryRecord { _id: string; userId: string; chatroomId?: string | undefined; escalations: UserEscalationRecord[]; totalEscalations: number; lastEscalationAt: string; topReasons: Array<{ reason: HandoffReason; count: number }>; updatedAt: Date; } const EscalationHistorySchema = new Schema( { _id: { type: String, required: true }, userId: { type: String, required: true, index: true }, chatroomId: { type: String, index: true }, escalations: [ { queuedAt: String, reason: String, reviewId: String, target: String, resolution: { resolvedAt: String, action: String, note: String, }, packetSummary: String, sourceChain: [String], }, ], totalEscalations: { type: Number, default: 0 }, lastEscalationAt: String, topReasons: [{ reason: String, count: Number }], updatedAt: { type: Date, default: Date.now, index: true }, }, { versionKey: false }, ); function userKey(userId: string): string { return anonymizeIdentifier("user", userId) ?? "user_unknown"; } function computeTopReasons(records: UserEscalationRecord[]): Array<{ reason: HandoffReason; count: number }> { const counts = new Map(); for (const record of records) { counts.set(record.reason, (counts.get(record.reason) ?? 0) + 1); } return [...counts.entries()] .map(([reason, count]) => ({ reason, count })) .sort((left, right) => right.count - left.count || left.reason.localeCompare(right.reason)) .slice(0, 5); } export class MongoEscalationHistoryService implements EscalationHistoryService { private readonly model: mongoose.Model; constructor(connection: mongoose.Connection) { this.model = (connection.models["EscalationHistory"] as mongoose.Model | undefined) ?? connection.model( "EscalationHistory", EscalationHistorySchema, ESCALATION_HISTORY_COLLECTION, ); } async load(userId: string): Promise { const doc = await this.model.findById(userKey(userId)).lean().exec(); if (!doc) { return null; } return { userId: doc.userId, ...(doc.chatroomId ? { chatroomId: doc.chatroomId } : {}), escalations: doc.escalations.slice(-10), lastEscalationAt: doc.lastEscalationAt, topReasons: doc.topReasons, totalEscalations: doc.totalEscalations, }; } async recordEscalation(record: { userId: string; chatroomId?: string | undefined; queuedAt: string; reason: HandoffReason; reviewId: string; target: string; packetSummary: string; sourceChain: string[]; }): Promise { const id = userKey(record.userId); const item: UserEscalationRecord = { packetSummary: record.packetSummary, queuedAt: record.queuedAt, reason: record.reason, reviewId: record.reviewId, sourceChain: record.sourceChain, target: record.target, }; await this.model.updateOne( { _id: id }, { $inc: { totalEscalations: 1 }, $push: { escalations: { $each: [item], $slice: -50 } }, $set: { ...(record.chatroomId ? { chatroomId: record.chatroomId } : {}), lastEscalationAt: record.queuedAt, updatedAt: new Date(), userId: id, }, $setOnInsert: { _id: id }, }, { upsert: true }, ).exec(); await this.recomputeTopReasons(id); } async recordResolution(record: { userId: string; reviewId: string; resolution: SupervisorReviewResolution; }): Promise { const id = userKey(record.userId); await this.model.updateOne( { _id: id, "escalations.reviewId": record.reviewId }, { $set: { "escalations.$.resolution": { action: record.resolution.action, resolvedAt: record.resolution.resolvedAt, ...(record.resolution.note ? { note: record.resolution.note } : {}), }, updatedAt: new Date(), }, }, ).exec(); } private async recomputeTopReasons(id: string): Promise { const doc = await this.model.findById(id).lean().exec(); if (!doc) { return; } await this.model.updateOne( { _id: id }, { $set: { topReasons: computeTopReasons(doc.escalations) } }, ).exec(); } } export function createEscalationHistoryService( connection?: mongoose.Connection, ): EscalationHistoryService { return connection ? new MongoEscalationHistoryService(connection) : new NoopEscalationHistoryService(); }