import { nativeSessionId, sessionsByOpenCodeId } from "./sessions.js"; import { ERROR_CODES } from "./errors.js"; export const SESSION_ASSOCIATION_SPLIT_BRAIN = ERROR_CODES.SESSION_ASSOCIATION_SPLIT_BRAIN; const association = (session) => ({ workspace: session.workspace, stage: session.stage, stage_session_id: session.session_id, started_at: session.started_at, }); export function diagnoseSessionAssociations(events, opencodeSessionId = null) { const groups = new Map(); for (const session of sessionsByOpenCodeId(events, opencodeSessionId)) { const sessionId = nativeSessionId(session); if (!sessionId) continue; const grouped = groups.get(sessionId) || []; grouped.push(session); groups.set(sessionId, grouped); } const findings = [...groups.entries()].flatMap(([nativeSessionId, sessions]) => { const original = sessions[0]; const active = sessions.filter((session) => session.state === "active"); const activeAtAffinity = active.filter((session) => session.workspace === original.workspace && session.stage === original.stage); const conflicting = [ ...active.filter((session) => session.workspace !== original.workspace || session.stage !== original.stage), ...activeAtAffinity.slice(1), ]; if (!conflicting.length) return []; return [{ code: SESSION_ASSOCIATION_SPLIT_BRAIN, severity: "error", message: "One OpenCode session has an active association that conflicts with its immutable work-context stage affinity.", opencode_session_id: nativeSessionId, presumed_original_association: association(original), conflicting_associations: conflicting.map(association), recovery: { status: "manual_recovery_required", steps: [ "Treat the earliest historical association as the presumed original affinity until the session history is reviewed.", "Explicitly hand off or close only the incorrect later association.", "Do not force-close the presumed original association merely because a later association exists.", "Open a separate OpenCode session before resuming another stage.", ], }, }]; }); return { schema: 1, status: findings.length ? "conflict" : "ok", findings }; }