Skip to content

Commit cca0ea9

Browse files
committed
feat: manejar rename/transfer de repos sin romper el vinculo
Antes un repo renombrado o transferido en GitHub caia huerfano: el webhook repository/renamed|transferred se ignoraba, el trabajo nuevo no resolvia proyecto y el dashboard quedaba con el nombre viejo. - migracion 0013: project_repo.github_repo_id (id inmutable de GitHub) - webhook atiende renamed/transferred -> emite repo.renamed - handleRepoRenamed: mueve el vinculo y re-etiqueta historial (commit + work_item) al nombre nuevo, sin perder nada - resolveProjectByRepo auto-sana por github_repo_id si se pierde el webhook; los push/PR propagan el id y lo sellan oportunistamente
1 parent 5afeed7 commit cca0ea9

11 files changed

Lines changed: 255 additions & 27 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
-- 0013 — Ancla inmutable repo→proyecto por id numérico de GitHub. El full_name ("owner/name") cambia
2+
-- al renombrar o transferir un repo en GitHub; su id numérico NO. Guardarlo permite (a) reconciliar
3+
-- el rename sin perder el vínculo ni el historial y (b) auto-sanar el mapeo aunque el webhook de
4+
-- rename se pierda: el siguiente push trae el id y resolveProjectByRepo corrige el nombre solo.
5+
alter table roz.project_repo add column if not exists github_repo_id bigint;
6+
7+
-- Único cuando está presente (un id de GitHub ↔ una fila); las filas viejas sin id no chocan
8+
-- (un índice único parcial ignora los null, así que conviven las ya vinculadas sin id).
9+
create unique index if not exists idx_roz_project_repo_github_id
10+
on roz.project_repo(github_repo_id) where github_repo_id is not null;

‎src/adapters/github.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ export async function listRepoCommits(repo: string, sinceISO: string, page = 1):
181181
}
182182

183183
export interface RepoMeta {
184+
githubId: number; // id numérico INMUTABLE del repo (no cambia al renombrar/transferir)
184185
fullName: string; // "owner/name"
185186
name: string; // solo el nombre del repo (sin owner)
186187
description: string | null;
@@ -189,10 +190,10 @@ export interface RepoMeta {
189190

190191
/** Metadata del repo (para matching de proyecto y el correo de detección). */
191192
export async function getRepo(repo: string): Promise<RepoMeta> {
192-
const d = await gh<{ full_name: string; name: string; description: string | null; html_url: string }>(
193+
const d = await gh<{ id: number; full_name: string; name: string; description: string | null; html_url: string }>(
193194
`/repos/${encRepo(repo)}`,
194195
);
195-
return { fullName: d.full_name, name: d.name, description: d.description ?? null, url: d.html_url };
196+
return { githubId: d.id, fullName: d.full_name, name: d.name, description: d.description ?? null, url: d.html_url };
196197
}
197198

198199
/** Heurística barata: ¿el mensaje del commit referencia un issue de Linear (ABC-123)? */

‎src/dashboard/queries.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -159,11 +159,14 @@ export function normalizeRepo(input: string): string {
159159
return r.includes('/') ? r : `hyperlabs-ai/${r}`;
160160
}
161161

162-
/** Vincula un repo a un proyecto (idempotente por repo). Devuelve el repo normalizado para que el
163-
* caller pueda encolar su backfill de historial. */
164-
export async function addProjectRepo(projectId: string, repo: string): Promise<string> {
162+
/** Vincula un repo a un proyecto (idempotente por repo). Si se conoce el id numérico de GitHub se
163+
* sella como ancla inmutable (sobrevive renames/transfers). Devuelve el repo normalizado para que
164+
* el caller pueda encolar su backfill de historial. */
165+
export async function addProjectRepo(projectId: string, repo: string, githubId?: number | null): Promise<string> {
165166
const normalized = normalizeRepo(repo);
166-
const { error } = await db().from('project_repo').insert({ project_id: projectId, repo: normalized });
167+
const row: Record<string, unknown> = { project_id: projectId, repo: normalized };
168+
if (githubId != null) row.github_repo_id = githubId;
169+
const { error } = await db().from('project_repo').insert(row);
167170
if (error) throw error;
168171
return normalized;
169172
}

‎src/events/outbox.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { syncIssueFromWebhook, removeMirror } from '../sync/linear-issue.js';
88
import { reconcileCommit, backfillPushCommits } from '../reconcile/commits.js';
99
import { backfillRepoCommits } from '../reconcile/backfill.js';
1010
import { reconcilePullRequest } from '../reconcile/pull-request.js';
11-
import { handleRepoDetected } from '../reconcile/repos.js';
11+
import { handleRepoDetected, handleRepoRenamed } from '../reconcile/repos.js';
1212
import type { RepoMeta } from '../adapters/github.js';
1313
import { upsertLinearProject } from '../projects/resolve.js';
1414
import { documentCompletedWork } from '../brain/document.js';
@@ -26,6 +26,7 @@ export type OutboxEventType =
2626
| 'pr.merged'
2727
| 'change.documented'
2828
| 'repo.detected'
29+
| 'repo.renamed'
2930
| 'repo.notify'
3031
| 'notification.requested';
3132

@@ -205,6 +206,7 @@ async function dispatch(type: OutboxEventType, payload: Record<string, unknown>)
205206
await reconcileCommit({
206207
repo: String(payload.repo ?? ''),
207208
sha: String(payload.sha ?? ''),
209+
githubId: (payload.githubId as number | null) ?? null,
208210
});
209211
return;
210212
// Backfill de un push truncado (>20 commits): enumera el rango completo y encola cada commit.
@@ -213,6 +215,7 @@ async function dispatch(type: OutboxEventType, payload: Record<string, unknown>)
213215
repo: String(payload.repo ?? ''),
214216
before: String(payload.before ?? ''),
215217
after: String(payload.after ?? ''),
218+
githubId: (payload.githubId as number | null) ?? null,
216219
});
217220
return;
218221
// Backfill del historial de un repo recién vinculado (solo métricas, sin Claude/Linear). Se
@@ -237,6 +240,7 @@ async function dispatch(type: OutboxEventType, payload: Record<string, unknown>)
237240
await reconcilePullRequest({
238241
repo: String(payload.repo ?? ''),
239242
number: Number(payload.number ?? 0),
243+
githubId: (payload.githubId as number | null) ?? null,
240244
});
241245
return;
242246
// Resumen de cambios documentados (auto-creados desde commits). Agrupado por dev+ventana
@@ -255,6 +259,15 @@ async function dispatch(type: OutboxEventType, payload: Record<string, unknown>)
255259
meta: (payload.meta as RepoMeta | undefined) ?? undefined,
256260
});
257261
return;
262+
// Repo renombrado/transferido en GitHub: mover el vínculo y re-etiquetar el historial al nombre
263+
// nuevo (lo emite el webhook `repository/renamed|transferred` o la auto-sanación de resolve).
264+
case 'repo.renamed':
265+
await handleRepoRenamed({
266+
from: String(payload.from ?? ''),
267+
to: String(payload.to ?? ''),
268+
githubId: (payload.githubId as number | null) ?? null,
269+
});
270+
return;
258271
// Broadcast a todos los devs: se detectó/vinculó un repo.
259272
case 'repo.notify':
260273
await notifyRepoDetected(payload as { repo?: string; repoUrl?: string | null; projectName?: string | null; linked?: boolean });

‎src/projects/resolve.ts‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import { db, dbPublic } from '../db/supabase.js';
99
import { config } from '../config.js';
1010
import { enqueueRepoBackfill } from '../reconcile/backfill.js';
11+
import { emit } from '../events/outbox.js';
1112

1213
export interface RozProject {
1314
id: string;
@@ -21,23 +22,56 @@ export interface RozProject {
2122
const PROJECT_COLS = 'id, key, name, linear_team_id, linear_project_id, hyperops_project_id';
2223

2324
/** Resuelve el roz.project de un repo. Primero el mapeo directo en roz (cubre repos internos y
24-
* de cliente configurados explícitamente); como fallback, la tabla de repos de HyperOps. */
25-
export async function resolveProjectByRepo(fullName: string): Promise<RozProject | null> {
25+
* de cliente configurados explícitamente); como fallback, la tabla de repos de HyperOps.
26+
* `githubId` (id numérico inmutable del repo) habilita la auto-sanación de renames/transfers:
27+
* si el nombre ya no matchea pero el id sí, el vínculo se corrige solo (ver paso 1b). */
28+
export async function resolveProjectByRepo(fullName: string, githubId?: number | null): Promise<RozProject | null> {
2629
const supabase = db();
30+
const repoN = fullName.toLowerCase();
2731

2832
// 1. Mapeo directo roz.project_repo (interno o cliente). Los repos se guardan en minúsculas
2933
// (ver normalizeRepo); el webhook puede traer otro casing ("owner/Mind-playground"), así que
3034
// se compara contra la forma en minúsculas para no perder la vinculación.
3135
const { data: link } = await supabase
3236
.from('project_repo')
33-
.select('project_id')
34-
.eq('repo', fullName.toLowerCase())
37+
.select('project_id, github_repo_id')
38+
.eq('repo', repoN)
3539
.maybeSingle();
3640
if (link?.project_id) {
41+
// Sella el id inmutable de forma oportunista: si la fila aún no lo tiene y este evento sí lo
42+
// trae, lo guardamos. Así los repos ya vinculados (pre-migración) quedan anclados en su próximo
43+
// push, sin un backfill manual → la auto-sanación (paso 1b) funciona aunque se pierda un webhook.
44+
if (githubId != null && link.github_repo_id == null) {
45+
await supabase.from('project_repo').update({ github_repo_id: githubId }).eq('repo', repoN).is('github_repo_id', null).then(() => {}, () => {});
46+
}
3747
const { data: project } = await supabase.from('project').select(PROJECT_COLS).eq('id', link.project_id).maybeSingle();
3848
if (project) return project as RozProject;
3949
}
4050

51+
// 1b. Auto-sanación por id inmutable. El nombre no matcheó, pero si traemos el id de GitHub y hay
52+
// una fila con ese id bajo OTRO nombre, el repo se renombró/transfirió (y nos perdimos o aún
53+
// no procesamos el webhook `repository/renamed`). Encola la corrección del nombre + historial
54+
// (idempotente; la procesa handleRepoRenamed) y resuelve ya por el id para no perder este
55+
// evento. Misma idempotency key que el webhook → no se duplica el trabajo de rename.
56+
if (githubId != null) {
57+
const { data: byId } = await supabase
58+
.from('project_repo')
59+
.select('project_id, repo')
60+
.eq('github_repo_id', githubId)
61+
.maybeSingle();
62+
if (byId?.project_id) {
63+
if (byId.repo !== repoN) {
64+
await emit(
65+
'repo.renamed',
66+
{ from: byId.repo, to: repoN, githubId },
67+
{ idempotencyKey: `repo-renamed:${githubId}:${repoN}` },
68+
).catch(() => {});
69+
}
70+
const { data: project } = await supabase.from('project').select(PROJECT_COLS).eq('id', byId.project_id).maybeSingle();
71+
if (project) return project as RozProject;
72+
}
73+
}
74+
4175
// 2. Fallback opcional de HyperOps (solo si HYPEROPS_FALLBACK=true): repo → project_id en
4276
// public.github_repositories → roz.project por hyperops_project_id. Defensivo: si el schema
4377
// `public` no existe/expone en este deploy, no rompe la resolución.

‎src/reconcile/commits.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ import { resolveProjectByRepo } from '../projects/resolve.js';
1717
export interface ReconcileInput {
1818
repo: string; // "owner/name"
1919
sha: string;
20+
/** id numérico inmutable del repo (del payload del webhook): habilita la auto-sanación de renames. */
21+
githubId?: number | null;
2022
/** Para pruebas: si se pasa, no se consulta la API de GitHub. */
2123
commit?: CommitMeta;
2224
}
@@ -62,11 +64,11 @@ function extractJson(s: string): any | null {
6264
* webhook no se duplican). Cada commit se reconcilia luego por su propio camino (incluido el
6365
* descarte de merges), así que aquí solo se hace fan-out.
6466
*/
65-
export async function backfillPushCommits(input: { repo: string; before: string; after: string }): Promise<{ enqueued: number }> {
67+
export async function backfillPushCommits(input: { repo: string; before: string; after: string; githubId?: number | null }): Promise<{ enqueued: number }> {
6668
if (!input.repo || !input.before || !input.after) return { enqueued: 0 };
6769
const shas = await pushCommitShas(input.repo, input.before, input.after);
6870
for (const sha of shas) {
69-
await emit('commit.received', { repo: input.repo, sha }, { idempotencyKey: `commit:${input.repo}:${sha}` });
71+
await emit('commit.received', { repo: input.repo, sha, githubId: input.githubId ?? null }, { idempotencyKey: `commit:${input.repo}:${sha}` });
7072
}
7173
return { enqueued: shas.length };
7274
}
@@ -106,8 +108,9 @@ async function reconcileBody(
106108
}
107109

108110
// Resolver proyecto y dev autor una sola vez: se usan para persistir el commit (dashboard) y,
109-
// en el camino huérfano, para asignar el issue resultante.
110-
const project = await resolveProjectByRepo(input.repo);
111+
// en el camino huérfano, para asignar el issue resultante. Se pasa githubId para que un repo
112+
// renombrado (cuyo nombre ya no resuelve) se auto-sane por su id inmutable.
113+
const project = await resolveProjectByRepo(input.repo, input.githubId);
111114
const dev = await resolveDevByCommit(supabase, commit);
112115

113116
// Persistir el commit SIEMPRE (el dashboard cuenta TODO el trabajo, incluso el de ramas y PRs):

‎src/reconcile/pull-request.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ import { resolveProjectByRepo } from '../projects/resolve.js';
2424
export interface ReconcilePrInput {
2525
repo: string; // "owner/name"
2626
number: number;
27+
/** id numérico inmutable del repo (del payload del webhook): habilita la auto-sanación de renames. */
28+
githubId?: number | null;
2729
}
2830

2931
export interface ReconcilePrResult {
@@ -85,7 +87,8 @@ async function reconcileBody(
8587
const pr = await getPullRequest(input.repo, input.number);
8688
if (!pr.merged) return { action: 'not-merged', detail: `PR #${input.number} no está mergeada` };
8789

88-
const project = await resolveProjectByRepo(input.repo);
90+
// Se pasa githubId para auto-sanar un repo renombrado (cuyo nombre ya no resuelve) por su id.
91+
const project = await resolveProjectByRepo(input.repo, input.githubId);
8992

9093
// Atribución de la PR (autores reales de los commits + revisores + quién mergeó). Se necesita en
9194
// TODAS las ramas (linked / matched / documented) para alimentar la conexión-con-código del

‎src/reconcile/repos.ts‎

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -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.

‎src/routes/dashboard.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { z } from 'zod';
77
import type { RozContext } from '../types/hono.js';
88
import { requireDashboardAuth, requireAdmin } from '../auth/verify.js';
99
import { listUsers } from '../adapters/linear.js';
10-
import { getContributionCalendar } from '../adapters/github.js';
10+
import { getContributionCalendar, getRepo } from '../adapters/github.js';
1111
import { enqueueRepoBackfill } from '../reconcile/backfill.js';
1212
import {
1313
type Period,
@@ -24,6 +24,7 @@ import {
2424
updateProject,
2525
deleteProject,
2626
addProjectRepo,
27+
normalizeRepo,
2728
removeProjectRepo,
2829
listInfra,
2930
linkService,
@@ -271,7 +272,10 @@ dashboardRoutes.post('/projects/:id/repos', requireAdmin, async (c) => {
271272
if (!parsed.success) return c.json({ error: { code: 'VALIDATION_ERROR', message: parsed.error.message } }, 400);
272273
try {
273274
const projectId = c.req.param('id');
274-
const repo = await addProjectRepo(projectId, parsed.data.repo);
275+
// Sella el id numérico inmutable (best-effort): ancla el vínculo para sobrevivir renames. Si el
276+
// repo es privado/inaccesible para el PAT, se vincula sin id y se sellará en el primer push/rename.
277+
const githubId = await getRepo(normalizeRepo(parsed.data.repo)).then((m) => m.githubId).catch(() => null);
278+
const repo = await addProjectRepo(projectId, parsed.data.repo, githubId);
275279
// Vincular en vivo solo trackea hacia adelante; recupera el historial reciente (BACKFILL_DAYS).
276280
await enqueueRepoBackfill(repo, projectId).catch(() => {});
277281
return c.json({ ok: true });

0 commit comments

Comments
 (0)