@@ -64,22 +64,97 @@ export async function handleRepoDetected(input: RepoDetectedInput): Promise<void
6464
6565 // 3. Vincular si hubo match (idempotente: tolera el unique sobre repo) y backfillear su historial
6666 // (solo métricas): los commits previos a la vinculación no llegaron por webhook. Idempotente.
67+ // Se sella el id numérico inmutable (meta.githubId) como ancla para sobrevivir renames futuros.
6768 if ( match ) {
68- await addProjectRepoIfAbsent ( match . id , repo ) ;
69+ await addProjectRepoIfAbsent ( match . id , repo , meta . githubId ) ;
6970 await enqueueRepoBackfill ( repo , match . id ) ;
7071 }
7172}
7273
7374/** Inserta el mapeo repo→proyecto tolerando el unique (23505) para reintentos seguros del outbox. */
74- async function addProjectRepoIfAbsent ( projectId : string , repo : string ) : Promise < void > {
75+ async function addProjectRepoIfAbsent ( projectId : string , repo : string , githubId ?: number | null ) : Promise < void > {
7576 try {
76- await addProjectRepo ( projectId , repo ) ;
77+ await addProjectRepo ( projectId , repo , githubId ) ;
7778 } catch ( err ) {
7879 if ( ( err as { code ?: string } ) ?. code === '23505' ) return ; // ya vinculado: no-op
7980 throw err ;
8081 }
8182}
8283
84+ export interface RepoRenamedInput {
85+ from : string ; // full_name viejo "owner/name" (puede venir vacío si solo tenemos el id)
86+ to : string ; // full_name nuevo "owner/name"
87+ githubId ?: number | null ; // id numérico inmutable del repo (ancla preferente para ubicar el vínculo)
88+ }
89+
90+ /**
91+ * Reconcilia el rename/transfer de un repo en GitHub (evento `repository` action renamed/transferred,
92+ * o auto-sanación desde resolveProjectByRepo). Mueve el vínculo repo→proyecto al nombre nuevo, sella
93+ * el id inmutable, y RE-ETIQUETA el historial (commits + work_items) al nombre nuevo para que las
94+ * dedup keys (`commit:repo:sha`, `pr:repo:number`) y el dashboard queden consistentes sin perder nada.
95+ * Idempotente: reprocesarlo no hace daño (los UPDATE por nombre viejo ya no encuentran filas).
96+ */
97+ export async function handleRepoRenamed ( input : RepoRenamedInput ) : Promise < void > {
98+ const supabase = db ( ) ;
99+ const from = input . from ?. toLowerCase ( ) ?? '' ;
100+ const to = input . to ?. toLowerCase ( ) ?? '' ;
101+ if ( ! to ) return ;
102+ const githubId = input . githubId ?? null ;
103+
104+ // 1. Localiza el vínculo: por id inmutable (sobrevive cualquier rename) y, si no lo tenemos, por
105+ // el nombre viejo. Si no existe, el repo no estaba trackeado: igual re-etiquetamos el historial
106+ // por si quedó trabajo bajo el nombre viejo, pero no creamos un vínculo nuevo aquí.
107+ type Link = { id : string ; project_id : string ; repo : string } ;
108+ let link : Link | null = null ;
109+ if ( githubId != null ) {
110+ const { data } = await supabase
111+ . from ( 'project_repo' )
112+ . select ( 'id, project_id, repo' )
113+ . eq ( 'github_repo_id' , githubId )
114+ . maybeSingle ( ) ;
115+ link = ( data as Link | null ) ?? null ;
116+ }
117+ if ( ! link && from ) {
118+ const { data } = await supabase
119+ . from ( 'project_repo' )
120+ . select ( 'id, project_id, repo' )
121+ . eq ( 'repo' , from )
122+ . maybeSingle ( ) ;
123+ link = ( data as Link | null ) ?? null ;
124+ }
125+
126+ if ( link && link . repo !== to ) {
127+ // 2. Si ya hay OTRA fila con el nombre nuevo (el repo se auto-onboardeó como "nuevo" tras el
128+ // rename, antes de esta corrección), elimínala: choca con el unique(repo) y el vínculo
129+ // histórico —con su id e historial— es el bueno.
130+ const { data : dup } = await supabase . from ( 'project_repo' ) . select ( 'id' ) . eq ( 'repo' , to ) . maybeSingle ( ) ;
131+ if ( dup && ( dup as { id : string } ) . id !== link . id ) {
132+ await supabase . from ( 'project_repo' ) . delete ( ) . eq ( 'id' , ( dup as { id : string } ) . id ) ;
133+ }
134+ }
135+
136+ // 3. Mueve el vínculo al nombre nuevo y sella el id inmutable (si lo conocemos).
137+ if ( link ) {
138+ const patch : Record < string , unknown > = { repo : to } ;
139+ if ( githubId != null ) patch . github_repo_id = githubId ;
140+ await supabase . from ( 'project_repo' ) . update ( patch ) . eq ( 'id' , link . id ) ;
141+ }
142+
143+ // 4. Re-etiqueta el historial al nombre nuevo (dedup keys + dashboard consistentes). El
144+ // unique(repo,sha) en commit solo chocaría si el mismo sha existiera bajo ambos nombres, lo
145+ // que no ocurre en operación normal (un push tras el rename trae shas nuevos, no los viejos).
146+ if ( from && from !== to ) {
147+ await supabase . from ( 'commit' ) . update ( { repo : to } ) . eq ( 'repo' , from ) ;
148+ await supabase . from ( 'work_item' ) . update ( { repo : to } ) . eq ( 'repo' , from ) ;
149+ }
150+
151+ // 5. Adopta los commits ya guardados bajo el nombre nuevo SIN proyecto: llegaron entre el rename y
152+ // esta corrección, cuando el nombre aún no resolvía (project_id quedó null). Best-effort.
153+ if ( link ?. project_id ) {
154+ await supabase . from ( 'commit' ) . update ( { project_id : link . project_id } ) . eq ( 'repo' , to ) . is ( 'project_id' , null ) ;
155+ }
156+ }
157+
83158/**
84159 * Intenta resolver a qué proyecto pertenece el repo. Primero por similitud de texto (barato,
85160 * determinista); si no hay match confiable, una pasada de Claude sobre la lista de proyectos.
0 commit comments