refacil-sdd-ai 4.2.4 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +239 -214
  2. package/agents/auditor.md +182 -184
  3. package/agents/debugger.md +201 -204
  4. package/agents/implementer.md +150 -149
  5. package/agents/investigator.md +80 -89
  6. package/agents/proposer.md +219 -124
  7. package/agents/tester.md +140 -144
  8. package/agents/validator.md +153 -145
  9. package/bin/cli.js +158 -116
  10. package/lib/bus/askFulfillment.js +17 -17
  11. package/lib/bus/broker.js +599 -599
  12. package/lib/bus/ui/app.js +318 -318
  13. package/lib/commands/sdd.js +433 -0
  14. package/lib/hooks.js +236 -236
  15. package/lib/installer.js +55 -1
  16. package/lib/methodology-migration-pending.js +101 -136
  17. package/package.json +4 -6
  18. package/skills/apply/SKILL.md +122 -120
  19. package/skills/archive/SKILL.md +101 -107
  20. package/skills/ask/SKILL.md +78 -78
  21. package/skills/attend/SKILL.md +70 -70
  22. package/skills/bug/SKILL.md +121 -128
  23. package/skills/explore/SKILL.md +61 -63
  24. package/skills/guide/SKILL.md +79 -79
  25. package/skills/inbox/SKILL.md +43 -43
  26. package/skills/join/SKILL.md +82 -82
  27. package/skills/prereqs/BUS-CROSS-REPO.md +55 -55
  28. package/skills/prereqs/METHODOLOGY-CONTRACT.md +122 -115
  29. package/skills/prereqs/SKILL.md +30 -37
  30. package/skills/propose/SKILL.md +91 -102
  31. package/skills/reply/SKILL.md +44 -44
  32. package/skills/review/SKILL.md +135 -126
  33. package/skills/review/checklist-back.md +92 -92
  34. package/skills/review/checklist-front.md +72 -72
  35. package/skills/review/checklist.md +114 -114
  36. package/skills/say/SKILL.md +38 -38
  37. package/skills/setup/SKILL.md +85 -141
  38. package/skills/setup/troubleshooting.md +38 -35
  39. package/skills/test/SKILL.md +86 -94
  40. package/skills/test/testing-patterns.md +63 -63
  41. package/skills/up-code/SKILL.md +108 -108
  42. package/skills/update/SKILL.md +109 -132
  43. package/skills/verify/SKILL.md +128 -132
  44. package/templates/compact-guidance.md +45 -45
  45. package/templates/methodology-guide.md +46 -42
  46. package/config/openspec-config.yaml +0 -8
  47. package/skills/prereqs/OPENSPEC-DELTAS.md +0 -51
@@ -1,44 +1,44 @@
1
- ---
2
- name: refacil:reply
3
- description: Responder la última pregunta dirigida a esta sesión en el bus. El broker autocompleta el correlationId.
4
- user-invocable: true
5
- ---
6
-
7
- # refacil:reply — Responder una pregunta del bus
8
-
9
- Envía una respuesta a la última pregunta dirigida a esta sesión. **$ARGUMENTS** = texto de la respuesta.
10
-
11
- ## Instrucciones
12
-
13
- ### Paso 1: Ejecutar reply
14
-
15
- Ejecuta vía `Bash`:
16
-
17
- ```bash
18
- refacil-sdd-ai bus reply --text "<respuesta>"
19
- ```
20
-
21
- El broker:
22
- - Busca automáticamente el último `ask` dirigido a esta sesión en la sala
23
- - Usa su `correlationId` para que el que preguntó (si está en `ask --wait`) reciba la respuesta directo
24
- - Broadcast a toda la sala como mensaje `kind=reply`
25
-
26
- ### Paso 2: Confirmar
27
-
28
- Reporta al usuario que la respuesta se envió.
29
-
30
- ## Cuándo usar `reply` vs `say`
31
-
32
- - **`reply`**: siempre que estés respondiendo algo que te preguntaron. Esto permite que el otro lado en `ask --wait` desbloquee automáticamente.
33
- - **`say`**: anuncio general sin relación con una pregunta previa.
34
-
35
- ## Reglas
36
-
37
- - Si acabas de **implementar** un cambio pedido por otro agente y este `reply` es el **cierre** (hecho / PR / bloqueo), incluye ese resumen en el texto; es el canal por defecto para contestar a quien hizo el `ask` original (mismo hilo).
38
- - Entrecomilla correctamente el texto.
39
- - Responde solo desde tu conocimiento de ESTE repo. Si la pregunta cae fuera de tu scope, dilo explícitamente: `"fuera de mi alcance, esto lo sabe el repo X"`.
40
- - Si no hay pregunta pendiente dirigida a ti y no quieres engancharla, usa `/refacil:say` en su lugar.
41
- - Si te hicieron múltiples preguntas y quieres responder una específica más vieja, pasa `--correlation <id>` explícito:
42
- ```bash
43
- refacil-sdd-ai bus reply --text "..." --correlation <id>
44
- ```
1
+ ---
2
+ name: refacil:reply
3
+ description: Reply to the last question directed to this session on the bus. The broker autocompletes the correlationId.
4
+ user-invocable: true
5
+ ---
6
+
7
+ # refacil:reply — Reply to a bus question
8
+
9
+ Sends a response to the last question directed to this session. **$ARGUMENTS** = response text.
10
+
11
+ ## Instructions
12
+
13
+ ### Step 1: Execute reply
14
+
15
+ Run via `Bash`:
16
+
17
+ ```bash
18
+ refacil-sdd-ai bus reply --text "<response>"
19
+ ```
20
+
21
+ The broker:
22
+ - Automatically finds the last `ask` directed to this session in the room
23
+ - Uses its `correlationId` so the asker (if in `ask --wait`) receives the response directly
24
+ - Broadcasts to the entire room as a `kind=reply` message
25
+
26
+ ### Step 2: Confirm
27
+
28
+ Report to the user that the response was sent.
29
+
30
+ ## When to use `reply` vs `say`
31
+
32
+ - **`reply`**: always when you are responding to something you were asked. This allows the other side in `ask --wait` to unblock automatically.
33
+ - **`say`**: general announcement unrelated to a previous question.
34
+
35
+ ## Rules
36
+
37
+ - If you just **implemented** a change requested by another agent and this `reply` is the **close** (done / PR / blocked), include that summary in the text; it is the default channel to respond to whoever made the original `ask` (same thread).
38
+ - Correctly quote the text.
39
+ - Respond only from your knowledge of THIS repo. If the question falls outside your scope, say it explicitly: `"out of my scope, repo X knows about this"`.
40
+ - If there is no pending question directed to you and you do not want to link it, use `/refacil:say` instead.
41
+ - If you were asked multiple questions and want to respond to a specific older one, pass `--correlation <id>` explicitly:
42
+ ```bash
43
+ refacil-sdd-ai bus reply --text "..." --correlation <id>
44
+ ```
@@ -1,126 +1,135 @@
1
- ---
2
- name: refacil:review
3
- description: Review de codigo con el checklist de calidad del equipo construye un briefing con archivos cambiados y tipo de proyecto, delega al sub-agente refacil-auditor y procesa el veredicto
4
- user-invocable: true
5
- ---
6
-
7
- # refacil:review — Entrypoint del Review
8
-
9
- Este skill es un **wrapper delgado** que delega el review pesado al sub-agente `refacil-auditor`. Antes de delegar, construye un **briefing estructurado** con los archivos cambiados y el tipo de proyecto ya detectados el sub-agente arranca evaluando, no descubriendo.
10
-
11
- **Prerequisitos**: perfil `agents` de `refacil-prereqs/SKILL.md` + modo de salida de `METHODOLOGY-CONTRACT.md`.
12
-
13
- ## Flujo
14
-
15
- ### Paso 0: Resolver alcance
16
-
17
- - Determina el alcance del review ANTES de invocar al sub-agente. Prioriza este orden:
18
- 1) Argumento del usuario (`$ARGUMENTS`)
19
- 2) Cambio activo en `openspec/changes/`
20
- 3) Cambios no commiteados (`git diff`)
21
- - Si hay multiples cambios activos en `openspec/changes/` y no hay `$ARGUMENTS`, **detente** y pide al usuario seleccionar explicitamente cual cambio revisar. **No invoques al sub-agente con scope ambiguo.**
22
-
23
- **Review ya aprobado**: Si el cambio objetivo ya tiene `.review-passed`, verifica si hay cambios posteriores al review (existencia del marcador: **`METHODOLOGY-CONTRACT.md` §8**):
24
- 1. Lee la `date` del `.review-passed`.
25
- 2. Compara con `git log --since="[date]" --oneline` y `git status --porcelain`.
26
- 3. **Si hay cambios nuevos**: elimina el `.review-passed` anterior y continua (construye briefing e invoca al sub-agente).
27
- 4. **Si NO hay cambios nuevos**: informa al usuario y termina sin invocar al sub-agente:
28
- ```
29
- El cambio [nombre] ya tiene review aprobado ([verdict] [date]) y no hay cambios posteriores.
30
- ```
31
-
32
- ### Paso 0.5: Construir briefing para el sub-agente (reduce tool calls del auditor)
33
-
34
- Antes de invocar al sub-agente, extrae el contexto que de otro modo el auditor calcularía por su cuenta:
35
-
36
- 1. **Archivos cambiados** — ejecuta `git diff --name-only HEAD` y `git status --porcelain`. La union es el scope bloqueante. (Si ya lo corriste en Paso 0 para verificar cambios post-review, reutiliza ese resultado.)
37
-
38
- 2. **Tipo de proyecto** — lee `package.json` (si existe) e inspecciona las dependencias:
39
- - Indicadores backend: `@nestjs/*`, `express`, `fastify`, `koa`, `typeorm`, `prisma`, `pg`, `mongoose`, `bullmq`, `amqplib`
40
- - Indicadores frontend: `react`, `vue`, `angular`, `next`, `nuxt`, `svelte`, `vite`, `@tanstack/*`
41
- - Si ambos `fullstack`; si solo backend `backend`; si solo frontend `frontend`; si no hay `package.json` o ninguno aplica → lee las primeras 20 lineas de `AGENTS.md` para inferir.
42
-
43
- 3. **Objetivo del cambio** (solo si hay cambio activo en `openspec/changes/`) lee la primera seccion de `proposal.md`. Extrae el objetivo en 1-2 oraciones. Si el scope es `git-diff` sin cambio activo → `null`.
44
-
45
- Construye el bloque BRIEFING:
46
-
47
- ```
48
- BRIEFING:
49
- scope: <changeName | "git-diff">
50
- changedFiles: [ruta/archivo-1.ts, ruta/archivo-2.ts, ...]
51
- projectType: backend | frontend | fullstack | library
52
- changeObjective: <objetivo en 1-2 oraciones, o null>
53
- mode: conciso | detailed
54
- ```
55
-
56
- ### Paso 1: Delegar al sub-agente refacil-auditor
57
-
58
- Invoca al sub-agente `refacil-auditor` pasandole el BRIEFING del paso anterior.
59
-
60
- El sub-agente:
61
- - Usa `changedFiles` del briefing como scope bloqueante (sin re-correr git diff).
62
- - Usa `projectType` para cargar directamente los checklists correctos (sin detection phase).
63
- - Usa `changeObjective` como contexto de intencion (sin releer proposal.md).
64
- - Lee los checklists y los archivos del scope bloqueante.
65
- - Evalua cada item con PASS/FAIL/N/A + severidad en cada FAIL.
66
- - Retorna UN solo mensaje con el reporte + bloque JSON fenced como ` ```refacil-review-result `.
67
-
68
- ### Paso 2: Procesar el reporte del sub-agente
69
-
70
- Muestra al usuario el **reporte conciso** (todo lo anterior al bloque `refacil-review-result`). No muestres el bloque JSON — es metadata interna.
71
-
72
- **Si el sub-agente retorno `SCOPE_ERROR: <razon>`**: propaga el error al usuario y pide clarificacion. No escribas marker.
73
-
74
- ### Paso 3: Crear marcador `.review-passed` (si aplica)
75
-
76
- Parsea el bloque ` ```refacil-review-result ` del sub-agente. Si `verdict` es **APROBADO** o **APROBADO CON OBSERVACIONES** y `changeName` no es null:
77
-
78
- **Ruta:** `openspec/changes/<changeName>/.review-passed`
79
-
80
- **Contenido (el JSON parseado del bloque, verbatim):**
81
- ```json
82
- {
83
- "verdict": "APROBADO|APROBADO CON OBSERVACIONES",
84
- "date": "<ISO>",
85
- "changeName": "<nombre-cambio>",
86
- "summary": "<resumen 1 linea>",
87
- "failCount": <int — solo FAILs en codigo nuevo>,
88
- "preexistingCount": <int FAILs preexistentes, no bloqueantes>,
89
- "blockers": false
90
- }
91
- ```
92
-
93
- **No crees el marker si:**
94
- - `verdict` es `REQUIERE CORRECCIONES`.
95
- - `changeName` es null.
96
- - El sub-agente retorno `SCOPE_ERROR`.
97
-
98
- ### Paso 4: Recomendar siguiente paso
99
-
100
- Segun el `verdict` parseado, agrega al final de tu respuesta:
101
-
102
- **Si APROBADO o APROBADO CON OBSERVACIONES:**
103
- ```
104
- El siguiente paso es archivar el cambio.
105
- Quieres que continue con /refacil:archive?
106
- ```
107
-
108
- **Si REQUIERE CORRECCIONES:**
109
- ```
110
- Una vez aplicadas las correcciones, el siguiente paso es re-verificar la implementacion.
111
- Quieres que continue con /refacil:verify?
112
- ```
113
-
114
- ## Reglas
115
-
116
- - **Siempre construye el briefing (Paso 0.5) antes de delegar** — es la pieza clave que reduce el costo del sub-agente.
117
- - **Siempre delega al sub-agente**. No repliques la logica de checklists ni de evaluacion aqui.
118
- - **El marker lo crea este skill, no el sub-agente**.
119
- - **No muestres el bloque JSON al usuario**.
120
- - Si el sub-agente retorno algo fuera de formato (sin bloque JSON parseable y no es `SCOPE_ERROR`), informa al usuario: "El reviewer retorno un reporte no estructurado — no se creo marker. Revisa el reporte manualmente."
121
- - **Continuidad del flujo**: si el usuario confirma afirmativamente ("si", "ok", "dale", "continua", etc.) la pregunta de continuidad, invocar inmediatamente el **Skill tool** correspondiente: `skill: "refacil:archive"` si el veredicto es APROBADO/APROBADO CON OBSERVACIONES, o `skill: "refacil:verify"` si es REQUIERE CORRECCIONES. (Ver `METHODOLOGY-CONTRACT.md §5`.)
122
-
123
- ## Ver tambien
124
-
125
- - Sub-agente: `.claude/agents/refacil-auditor.md` (fuente: `refacil-sdd-ai/agents/auditor.md`)
126
- - Checklists: `checklist.md`, `checklist-back.md`, `checklist-front.md` en este mismo directorio.
1
+ ---
2
+ name: refacil:review
3
+ description: Code review with the team quality checklist — builds a briefing with changed files and project type, delegates to the refacil-auditor sub-agent, and processes the verdict
4
+ user-invocable: true
5
+ ---
6
+
7
+ # refacil:review — Review Entrypoint
8
+
9
+ This skill is a **thin wrapper** that delegates the heavy review to the `refacil-auditor` sub-agent. Before delegating, it builds a **structured briefing** with the changed files and detected project typethe sub-agent starts evaluating, not discovering.
10
+
11
+ **Prerequisites**: `agents` profile from `refacil-prereqs/SKILL.md` + output mode from `METHODOLOGY-CONTRACT.md`.
12
+
13
+ ## Flow
14
+
15
+ ### Step 0: Resolve scope
16
+
17
+ - Determine the review scope BEFORE invoking the sub-agent. Prioritize in this order:
18
+ 1) User argument (`$ARGUMENTS`)
19
+ 2) Active change in `refacil-sdd/changes/`
20
+ 3) Uncommitted changes (`git diff`)
21
+ - If there are multiple active changes in `refacil-sdd/changes/` and no `$ARGUMENTS`, **stop** and ask the user to explicitly select which change to review. **Do not invoke the sub-agent with ambiguous scope.**
22
+
23
+ ### Step 0.3: Git working tree snapshot (run once)
24
+
25
+ After scope is unambiguous (you are **not** stopping for multiple active changes), collect git state **exactly once** for this skill invocation:
26
+
27
+ 1. Run `git diff --name-only HEAD` set `pathsFromDiff`.
28
+ 2. Run `git status --porcelain` → parse each line (strip the first two status columns) → set `pathsFromStatus`.
29
+ 3. **`changedFilesUnion`** = sorted unique union of `pathsFromDiff` and `pathsFromStatus` (drop empty entries).
30
+
31
+ **Rules:**
32
+ - Reuse **`changedFilesUnion`** and the **same** `git status --porcelain` interpretation everywhere below — **do not** run `git diff --name-only` or `git status --porcelain` again in this skill.
33
+ - If a later step needs “is the working tree non-empty?”, derive it from the snapshot (e.g. non-empty `changedFilesUnion` or any porcelain line) instead of re-running `git status`.
34
+
35
+ If you already have a `changeName`, run `refacil-sdd-ai sdd status <changeName> --json` to get the change status (artifacts, tasks, reviewPassed).
36
+
37
+ **Review already approved**: If `reviewPassed` is `true` in the status JSON (or if the target change already has `.review-passed`), verify if there are changes after the review (marker existence: **`METHODOLOGY-CONTRACT.md` §8**):
38
+ 1. Read the `date` from `.review-passed`.
39
+ 2. Compare with `git log --since="[date]" --oneline` and **reuse the Step 0.3 snapshot** for working-tree activity (do not run `git status` again).
40
+ 3. **If there are new changes** (commits since marker date and/or paths in `changedFilesUnion`): delete the previous `.review-passed` and continue (build briefing and invoke the sub-agent).
41
+ 4. **If there are NO new changes**: inform the user and finish without invoking the sub-agent:
42
+ ```
43
+ The change [name] already has an approved review ([verdict] [date]) and there are no subsequent changes.
44
+ ```
45
+
46
+ ### Step 0.5: Build briefing for the sub-agent (reduces auditor tool calls)
47
+
48
+ Before invoking the sub-agent, extract the context that the auditor would otherwise calculate on its own:
49
+
50
+ 1. **Changed files** — use **`changedFilesUnion` from Step 0.3** as the blocking scope. Do not run `git diff` or `git status` again.
51
+
52
+ 2. **Project type** read `package.json` (if it exists) and inspect the dependencies:
53
+ - Backend indicators: `@nestjs/*`, `express`, `fastify`, `koa`, `typeorm`, `prisma`, `pg`, `mongoose`, `bullmq`, `amqplib`
54
+ - Frontend indicators: `react`, `vue`, `angular`, `next`, `nuxt`, `svelte`, `vite`, `@tanstack/*`
55
+ - If both → `fullstack`; if only backend → `backend`; if only frontend → `frontend`; if no `package.json` or none applies → read the first 20 lines of `AGENTS.md` to infer.
56
+
57
+ 3. **Change objective** (only if there is an active change in `refacil-sdd/changes/`) — read the first section of `proposal.md`. Extract the objective in 1-2 sentences. If the scope is `git-diff` without an active change → `null`.
58
+
59
+ Build the BRIEFING block:
60
+
61
+ ```
62
+ BRIEFING:
63
+ scope: <changeName | "git-diff">
64
+ changedFiles: [path/file-1.ts, path/file-2.ts, ...]
65
+ projectType: backend | frontend | fullstack | library
66
+ changeObjective: <objective in 1-2 sentences, or null>
67
+ mode: concise | detailed
68
+ ```
69
+
70
+ ### Step 1: Delegate to the refacil-auditor sub-agent
71
+
72
+ Invoke the `refacil-auditor` sub-agent passing it the BRIEFING from the previous step.
73
+
74
+ The sub-agent:
75
+ - Uses `changedFiles` from the briefing as the blocking scope (without re-running git diff).
76
+ - Uses `projectType` to directly load the correct checklists (without a detection phase).
77
+ - Uses `changeObjective` as intent context (without re-reading proposal.md).
78
+ - Reads the checklists and the blocking scope files.
79
+ - Evaluates each item with PASS/FAIL/N/A + severity for each FAIL.
80
+ - Returns ONE single message with the report + JSON block fenced as ` ```refacil-review-result `.
81
+
82
+ ### Step 2: Process the sub-agent report
83
+
84
+ Show the user the **concise report** (everything before the `refacil-review-result` block). Do not show the JSON block — it is internal metadata.
85
+
86
+ **If the sub-agent returned `SCOPE_ERROR: <reason>`**: propagate the error to the user and ask for clarification. Do not write a marker.
87
+
88
+ ### Step 3: Create `.review-passed` marker (if applicable)
89
+
90
+ Parse the ` ```refacil-review-result ` block from the sub-agent. If `verdict` is **APROBADO** or **APROBADO CON OBSERVACIONES** and `changeName` is not null:
91
+
92
+ Run the following command to write the marker:
93
+
94
+ ```bash
95
+ refacil-sdd-ai sdd mark-reviewed <changeName> \
96
+ --verdict "<verdict>" \
97
+ --summary "<1-line summary>" \
98
+ --fail-count <failCount> \
99
+ --preexisting-count <preexistingCount>
100
+ ```
101
+
102
+ Where the values are extracted from the sub-agent's `refacil-review-result` block:
103
+ - `<verdict>`: the value of `verdict` (APROBADO, APROBADO CON OBSERVACIONES, etc.)
104
+ - `<summary>`: the value of `summary`
105
+ - `<failCount>`: FAILs in new code (default 0)
106
+ - `<preexistingCount>`: pre-existing non-blocking FAILs (default 0)
107
+
108
+ **Do NOT run the command if:**
109
+ - `verdict` is `REQUIERE CORRECCIONES`.
110
+ - `changeName` is null.
111
+ - The sub-agent returned `SCOPE_ERROR`.
112
+
113
+ ### Step 4: Recommend next step
114
+
115
+ According to the parsed `verdict`, add at the end of your response:
116
+
117
+ **If APROBADO or APROBADO CON OBSERVACIONES:**
118
+ ```
119
+ The next step is to archive the change.
120
+ Do you want me to continue with /refacil:archive?
121
+ ```
122
+
123
+ **If REQUIERE CORRECCIONES:**
124
+ ```
125
+ Once the corrections are applied, the next step is to re-verify the implementation.
126
+ Do you want me to continue with /refacil:verify?
127
+ ```
128
+
129
+ ## Rules
130
+
131
+ - **Always build the briefing (Step 0.5) before delegating** — it is the key piece that reduces the sub-agent cost.
132
+ - **Always delegate to the sub-agent**. Do not replicate checklist or evaluation logic here.
133
+ - **The marker is created by this skill, not the sub-agent**.
134
+ - If the sub-agent returned something out of format (no parseable JSON block and not `SCOPE_ERROR`), inform the user: "The reviewer returned an unstructured report — no marker was created. Review the report manually."
135
+ - **Flow continuity**: if the user confirms affirmatively ("yes", "ok", "go", "continue", etc.) the continuity question, immediately invoke the corresponding **Skill tool**: `skill: "refacil:archive"` if the verdict is APROBADO/APROBADO CON OBSERVACIONES, or `skill: "refacil:verify"` if REQUIERE CORRECCIONES. (See `METHODOLOGY-CONTRACT.md §5`.)
@@ -1,92 +1,92 @@
1
- # Checklist Backend Equipo Refacil
2
-
3
- > Complementa el [checklist general](checklist.md). Aplica a repositorios **backend** (APIs, microservicios, workers, colas).
4
- > Detectar tipo: si el proyecto tiene frameworks de servidor (HTTP, gRPC, mensajeria), estructura de microservicios, o acceso a base de datos, aplica este checklist.
5
- > Marcar N/A en secciones que no apliquen al cambio revisado (ej. colas si el cambio no toca mensajeria).
6
-
7
- ## B1. Validacion de entrada
8
- - Los DTOs/objetos de entrada de endpoints usan el mecanismo de validacion automatica del framework
9
- - Cada campo declara tipo y restricciones (obligatorio, formato, rango)
10
- - Endpoints nombrados en kebab-case (`get-user-info`, `create-payment`)
11
- - No se confian datos del cliente sin validar (query params, headers, body)
12
-
13
- ## B2. Contratos de API
14
- - Las respuestas usan una estructura consistente (no retornar formatos distintos segun el caso)
15
- - Los codigos HTTP son correctos y especificos (no todo es 200 o 500)
16
- - Los DTOs de respuesta no exponen campos internos (IDs de BD, campos de auditoria, relaciones internas)
17
- - Si el endpoint es consumido por otro servicio: verificar que no se introduzcan breaking changes en el contrato (campos renombrados, eliminados o con tipo diferente)
18
- - Los errores retornan un formato estandar con mensaje entendible para el consumidor
19
-
20
- ## B3. Manejo de errores (estandar Refacil)
21
- - No hay bloques try/catch anidados o multiples en un mismo hilo de peticion
22
- - Los errores se capturan, loggean y devuelven respuestas formateadas
23
- - Modulos/servicios nuevos usan el filtro o middleware global de excepciones del proyecto (si existe)
24
- - Se distingue entre errores del cliente (4xx) y errores del servidor (5xx)
25
- - Los errores de dependencias externas (APIs, BD, colas) se manejan con mensajes propios, no se propagan tal cual al consumidor
26
-
27
- ## B4. Arquitectura y patrones
28
- - **Responsabilidad por capas**: no hay logica de negocio en la capa de transporte (controllers/handlers) ni en la capa de infraestructura (repositorios/adaptadores)
29
- - Los DTOs estan en la capa correcta (entrada en transporte, salida en aplicacion)
30
- - Repository Pattern para acceso a datos (si el proyecto tiene un repositorio base, los nuevos lo extienden)
31
- - Si es un microservicio nuevo, sigue la estructura definida en AGENTS.md (hexagonal, clean architecture, etc.)
32
- - Las dependencias fluyen en la direccion correcta segun la arquitectura del proyecto
33
-
34
- ## B5. Concurrencia y atomicidad
35
- - Las operaciones que modifican multiples registros o tablas usan transacciones de BD (todo o nada)
36
- - Los endpoints de escritura criticos (pagos, transferencias, creacion de ordenes) son **idempotentes**: si se reintentan, no duplican el efecto
37
- ```
38
- // Patron: verificar si la operacion ya se ejecuto antes de procesarla
39
- SI existeOperacion(idempotencyKey) ENTONCES retornar resultado_existente
40
- SINO ejecutar operacion Y guardar resultado con idempotencyKey
41
- ```
42
- - Si multiples procesos pueden modificar el mismo recurso al mismo tiempo, se usan locks distribuidos o versionado optimista para evitar race conditions
43
- - Las operaciones de lectura-modificacion-escritura son atomicas (no leer, procesar en memoria y escribir sin proteccion)
44
-
45
- ## B6. Consultas a BD
46
- - No hay bucles para traer informacion de distintas fuentes de datos
47
- - Si se necesitan datos cruzados, crear una funcion que use JOINs o consultas optimizadas internamente
48
- - Las consultas usan indices apropiados
49
- - No hay queries N+1
50
- - No hay inyeccion SQL/NoSQL posible (queries parametrizadas con el ORM/driver del proyecto)
51
- - **Esquema (DDL)**: por defecto, no usar el sistema de migraciones de TypeORM ni `synchronize` para aplicar o versionar cambios de BD (ni `MigrationInterface`, ni depender de `migration:run` / `migration:generate` en el flujo de despliegue de la app). Los cambios de esquema se entregan como **scripts explícitos** (p. ej. `.sql` versionados bajo convención del repo) para que **quien opera el motor** los ejecute **manualmente y aparte** en cada entorno (Postgres, MySQL, etc.). **Excepción**: si `AGENTS.md` define **explicitamente** como regla de **ese** repositorio otro mecanismo (p. ej. migraciones TypeORM u otro pipeline acordado), marca esta viñeta como **N/A** y revisa solo que el cambio cumple lo documentado allí (sin exigir scripts manuales).
52
- - Si aplica la politica por defecto (scripts manuales): los scripts de esquema entregados documentan orden de ejecución, son reversibles o describen rollback, y no destruyen datos existentes sin plan explícito. Si aplica la excepción por `AGENTS.md`, marca **N/A** o evalua segun lo que ese archivo exija para migraciones.
53
-
54
- ## B7. Caching
55
- - Consultas repetitivas a BD usan cache **distribuido** (no cache local en memoria del proceso evitar reinicios por falta de RAM)
56
- - El patron es: verificar cache -> si no hay, consultar BD -> guardar en cache con TTL
57
- - Las claves de cache son especificas y predecibles (incluyen los parametros que hacen unica la consulta)
58
- - Se invalida el cache cuando los datos subyacentes cambian (si aplica)
59
- - El TTL es apropiado para el tipo de dato (configuracion: largo, datos transaccionales: corto o sin cache)
60
-
61
- ## B8. Resiliencia y conexiones
62
- - Todas las llamadas externas (HTTP, gRPC, BD, colas) tienen **timeout configurado** (no esperar indefinidamente)
63
- - Si una dependencia externa falla, la respuesta degrada de forma controlada (fallback, mensaje de error claro, reintento)
64
- - Connection pooling en BD y clientes HTTP (no abrir/cerrar conexion por cada peticion)
65
- - Las conexiones se liberan correctamente (en bloques finally o equivalente)
66
- - Si el proyecto usa circuit breaker, las llamadas a servicios inestables lo implementan
67
-
68
- ## B9. Colas y mensajeria (si aplica)
69
- - Los consumers son **idempotentes**: procesar el mismo mensaje dos veces no duplica el efecto
70
- - Se confirma el procesamiento (ack) **despues** de completar la operacion, no antes
71
- - Los mensajes que fallan repetidamente van a una dead letter queue (no se pierden ni bloquean la cola)
72
- - Los producers no pierden mensajes si la cola no esta disponible (retry o persistencia local)
73
- - Los payloads de mensajes contienen la informacion suficiente para procesarse sin consultas adicionales innecesarias
74
-
75
- ## B10. Performance
76
- - Las operaciones pesadas o de larga duracion son asincronas (colas, workers, background jobs)
77
- - No hay memory leaks obvios (subscriptions sin unsubscribe, listeners sin cleanup, conexiones sin cerrar, timers sin cancelar)
78
- - Los endpoints con respuesta pesada usan paginacion
79
- - No se cargan relaciones completas de BD si solo se necesitan campos puntuales (select especifico)
80
-
81
- ## B11. Logging (estandar Refacil)
82
- - Se usa el logger centralizado del proyecto (no prints directos a consola), si ya se tiene en el repositorio
83
- - Procesos criticos en la operacion (ventas, transacciones, pagos) tienen logs
84
- - Se loggean propiedades especificas y necesariasnunca objetos complejos ni entidades con relaciones completas
85
- - Los logs en catch contienen informacion suficiente para diagnosticar el error (que fallo, con que datos, en que contexto)
86
- - Los logs tienen nivel apropiado: error para fallos, warn para situaciones inesperadas recuperables, info para flujos criticos de negocio
87
-
88
- ## B12. Testing backend
89
- - Tests de integracion con BD real para repositorios y queries complejas (no solo mocks)
90
- - Tests de los contratos de API (request valido retorna estructura esperada, request invalido retorna error formateado)
91
- - Tests de casos de error (dependencia caida, timeout, datos invalidos)
92
- - Si hay concurrencia critica: tests que validen idempotencia o atomicidad
1
+ # Backend Checklist — Refacil Team
2
+
3
+ > Complements the [general checklist](checklist.md). Applies to **backend** repositories (APIs, microservices, workers, queues).
4
+ > Detection: if the project has server frameworks (HTTP, gRPC, messaging), microservice structure, or database access, apply this checklist.
5
+ > Mark N/A in sections that do not apply to the change being reviewed (e.g. queues if the change does not touch messaging).
6
+
7
+ ## B1. Input validation
8
+ - Endpoint DTOs/input objects use the framework's automatic validation mechanism
9
+ - Each field declares its type and constraints (required, format, range)
10
+ - Endpoints named in kebab-case (`get-user-info`, `create-payment`)
11
+ - Client data is not trusted without validation (query params, headers, body)
12
+
13
+ ## B2. API contracts
14
+ - Responses use a consistent structure (do not return different formats depending on the case)
15
+ - HTTP codes are correct and specific (not everything is 200 or 500)
16
+ - Response DTOs do not expose internal fields (DB IDs, audit fields, internal relationships)
17
+ - If the endpoint is consumed by another service: verify that no breaking changes are introduced in the contract (renamed, removed, or differently-typed fields)
18
+ - Errors return a standard format with a message understandable to the consumer
19
+
20
+ ## B3. Error handling (Refacil standard)
21
+ - No nested or multiple try/catch blocks in the same request thread
22
+ - Errors are captured, logged, and formatted responses are returned
23
+ - New modules/services use the project's global exception filter or middleware (if it exists)
24
+ - Client errors (4xx) are distinguished from server errors (5xx)
25
+ - External dependency errors (APIs, DB, queues) are handled with their own messages, not propagated as-is to the consumer
26
+
27
+ ## B4. Architecture and patterns
28
+ - **Layer responsibility**: no business logic in the transport layer (controllers/handlers) or in the infrastructure layer (repositories/adapters)
29
+ - DTOs are in the correct layer (input in transport, output in application)
30
+ - Repository Pattern for data access (if the project has a base repository, new ones extend it)
31
+ - If it is a new microservice, follows the structure defined in AGENTS.md (hexagonal, clean architecture, etc.)
32
+ - Dependencies flow in the correct direction according to the project architecture
33
+
34
+ ## B5. Concurrency and atomicity
35
+ - Operations that modify multiple records or tables use DB transactions (all or nothing)
36
+ - Critical write endpoints (payments, transfers, order creation) are **idempotent**: if retried, they do not duplicate the effect
37
+ ```
38
+ // Pattern: check if the operation was already executed before processing it
39
+ IF operationExists(idempotencyKey) THEN return existing_result
40
+ ELSE execute operation AND save result with idempotencyKey
41
+ ```
42
+ - If multiple processes can modify the same resource simultaneously, distributed locks or optimistic versioning are used to avoid race conditions
43
+ - Read-modify-write operations are atomic (not read, process in memory and write without protection)
44
+
45
+ ## B6. DB queries
46
+ - No loops to fetch information from different data sources
47
+ - If cross-data is needed, create a function that uses JOINs or internally optimized queries
48
+ - Queries use appropriate indexes
49
+ - No N+1 queries
50
+ - No SQL/NoSQL injection possible (parameterized queries with the project's ORM/driver)
51
+ - **Schema (DDL)**: by default, do not use TypeORM's migration system or `synchronize` to apply or version DB changes (neither `MigrationInterface`, nor relying on `migration:run` / `migration:generate` in the app deployment flow). Schema changes are delivered as **explicit scripts** (e.g. versioned `.sql` files under the repo convention) so **whoever operates the engine** executes them **manually and separately** in each environment (Postgres, MySQL, etc.). **Exception**: if `AGENTS.md` **explicitly** defines another mechanism as a rule for **that** repository (e.g. TypeORM migrations or another agreed pipeline), mark this bullet as **N/A** and only verify the change complies with what is documented there (without requiring manual scripts).
52
+ - If the default policy applies (manual scripts): the delivered schema scripts document execution order, are reversible or describe rollback, and do not destroy existing data without an explicit plan. If the exception applies via `AGENTS.md`, mark **N/A** or evaluate according to what that file requires for migrations.
53
+
54
+ ## B7. Caching
55
+ - Repetitive DB queries use **distributed** cache (not in-process memory cacheavoid restarts due to RAM exhaustion)
56
+ - The pattern is: check cache -> if not found, query DB -> save to cache with TTL
57
+ - Cache keys are specific and predictable (include the parameters that make the query unique)
58
+ - Cache is invalidated when underlying data changes (if applicable)
59
+ - TTL is appropriate for the data type (configuration: long, transactional data: short or no cache)
60
+
61
+ ## B8. Resilience and connections
62
+ - All external calls (HTTP, gRPC, DB, queues) have **configured timeout** (do not wait indefinitely)
63
+ - If an external dependency fails, the response degrades gracefully (fallback, clear error message, retry)
64
+ - Connection pooling in DB and HTTP clients (do not open/close a connection per request)
65
+ - Connections are properly released (in finally blocks or equivalent)
66
+ - If the project uses circuit breaker, calls to unstable services implement it
67
+
68
+ ## B9. Queues and messaging (if applicable)
69
+ - Consumers are **idempotent**: processing the same message twice does not duplicate the effect
70
+ - Processing is acknowledged (ack) **after** completing the operation, not before
71
+ - Messages that fail repeatedly go to a dead letter queue (they are not lost or stuck in the queue)
72
+ - Producers do not lose messages if the queue is unavailable (retry or local persistence)
73
+ - Message payloads contain enough information to be processed without unnecessary additional queries
74
+
75
+ ## B10. Performance
76
+ - Heavy or long-running operations are asynchronous (queues, workers, background jobs)
77
+ - No obvious memory leaks (subscriptions without unsubscribe, listeners without cleanup, unclosed connections, uncanceled timers)
78
+ - Endpoints with heavy responses use pagination
79
+ - Complete DB relationships are not loaded if only specific fields are needed (specific select)
80
+
81
+ ## B11. Logging (Refacil standard)
82
+ - The project's centralized logger is used (not direct console prints), if already present in the repository
83
+ - Critical business operations (sales, transactions, payments) have logs
84
+ - Specific and necessary properties are loggednever complex objects or entities with full relationships
85
+ - Catch logs contain enough information to diagnose the error (what failed, with what data, in what context)
86
+ - Logs have appropriate level: error for failures, warn for recoverable unexpected situations, info for critical business flows
87
+
88
+ ## B12. Backend testing
89
+ - Integration tests with a real DB for repositories and complex queries (not just mocks)
90
+ - API contract tests (valid request returns expected structure, invalid request returns formatted error)
91
+ - Error case tests (dependency down, timeout, invalid data)
92
+ - If there is critical concurrency: tests that validate idempotency or atomicity