refacil-sdd-ai 4.2.4 → 4.4.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 +189 -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 +447 -0
  14. package/lib/hooks.js +236 -236
  15. package/lib/installer.js +58 -2
  16. package/lib/methodology-migration-pending.js +101 -136
  17. package/package.json +4 -6
  18. package/skills/apply/SKILL.md +139 -120
  19. package/skills/archive/SKILL.md +105 -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 +73 -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 +103 -102
  31. package/skills/reply/SKILL.md +44 -44
  32. package/skills/review/SKILL.md +163 -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 +104 -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 +159 -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,136 +1,101 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
-
6
- /**
7
- * Motor compartido con `refacil-sdd-ai migration-pending`, hooks `check-update` / `notify-update`
8
- * y la skill `refacil:update`. Si ninguna condicion aplica, no hace falta migrar metodologia.
9
- */
10
- const REQUIRED_OPENSPEC_SKILLS = new Set([
11
- 'openspec-propose',
12
- 'openspec-explore',
13
- 'openspec-apply-change',
14
- 'openspec-archive-change',
15
- 'openspec-verify-change',
16
- ]);
17
-
18
- const REQUIRED_OPSX_CLAUDE = new Set([
19
- 'apply.md',
20
- 'archive.md',
21
- 'explore.md',
22
- 'propose.md',
23
- 'verify.md',
24
- ]);
25
-
26
- const REQUIRED_OPSX_CURSOR = new Set([
27
- 'opsx-apply.md',
28
- 'opsx-archive.md',
29
- 'opsx-explore.md',
30
- 'opsx-propose.md',
31
- 'opsx-verify.md',
32
- ]);
33
-
34
- function legacyIndexDoc(filePath) {
35
- if (!fs.existsSync(filePath)) return false;
36
- const content = fs.readFileSync(filePath, 'utf8');
37
- const lines = content.split(/\r?\n/).length;
38
- const pointsToAgents = /AGENTS\.md/i.test(content);
39
- return lines > 5 || !pointsToAgents;
40
- }
41
-
42
- function collectExtraOpenspecSkills(root) {
43
- const out = [];
44
- for (const rel of ['.claude/skills', '.cursor/skills']) {
45
- const full = path.join(root, rel);
46
- if (!fs.existsSync(full)) continue;
47
- let names;
48
- try {
49
- names = fs.readdirSync(full, { withFileTypes: true });
50
- } catch (_) {
51
- continue;
52
- }
53
- for (const d of names) {
54
- if (!d.isDirectory()) continue;
55
- const name = d.name;
56
- if (!name.startsWith('openspec-')) continue;
57
- if (REQUIRED_OPENSPEC_SKILLS.has(name)) continue;
58
- out.push(path.join(rel, name));
59
- }
60
- }
61
- return out;
62
- }
63
-
64
- function collectExtraOpsxClaude(root) {
65
- const dir = path.join(root, '.claude', 'commands', 'opsx');
66
- if (!fs.existsSync(dir)) return [];
67
- let names;
68
- try {
69
- names = fs.readdirSync(dir);
70
- } catch (_) {
71
- return [];
72
- }
73
- const extra = [];
74
- for (const name of names) {
75
- if (!name.endsWith('.md')) continue;
76
- if (REQUIRED_OPSX_CLAUDE.has(name)) continue;
77
- extra.push(path.join('.claude/commands/opsx', name));
78
- }
79
- return extra;
80
- }
81
-
82
- function collectExtraOpsxCursor(root) {
83
- const dir = path.join(root, '.cursor', 'commands');
84
- if (!fs.existsSync(dir)) return [];
85
- let names;
86
- try {
87
- names = fs.readdirSync(dir);
88
- } catch (_) {
89
- return [];
90
- }
91
- const extra = [];
92
- for (const name of names) {
93
- if (!name.startsWith('opsx-') || !name.endsWith('.md')) continue;
94
- if (REQUIRED_OPSX_CURSOR.has(name)) continue;
95
- extra.push(path.join('.cursor/commands', name));
96
- }
97
- return extra;
98
- }
99
-
100
- /**
101
- * @param {string} root - raíz del repo
102
- * @returns {{ pending: boolean, reasons: string[] }}
103
- */
104
- function methodologyMigrationPending(root) {
105
- const reasons = [];
106
-
107
- const agentsMd = path.join(root, 'AGENTS.md');
108
- const agentsDir = path.join(root, '.agents');
109
- if (fs.existsSync(agentsMd) && !fs.existsSync(agentsDir)) {
110
- reasons.push('AGENTS.md existe sin carpeta .agents/');
111
- }
112
-
113
- const claudeMd = path.join(root, 'CLAUDE.md');
114
- if (legacyIndexDoc(claudeMd)) {
115
- reasons.push('CLAUDE.md requiere normalización (índice mínimo → AGENTS.md)');
116
- }
117
-
118
- const cursorRules = path.join(root, '.cursorrules');
119
- if (legacyIndexDoc(cursorRules)) {
120
- reasons.push('.cursorrules requiere normalización (índice mínimo → AGENTS.md)');
121
- }
122
-
123
- const extraSkills = collectExtraOpenspecSkills(root);
124
- if (extraSkills.length) {
125
- reasons.push(`skills OpenSpec sobrantes: ${extraSkills.join(', ')}`);
126
- }
127
-
128
- const extraOpsx = [...collectExtraOpsxClaude(root), ...collectExtraOpsxCursor(root)];
129
- if (extraOpsx.length) {
130
- reasons.push(`commands opsx sobrantes: ${extraOpsx.join(', ')}`);
131
- }
132
-
133
- return { pending: reasons.length > 0, reasons };
134
- }
135
-
136
- module.exports = { methodologyMigrationPending };
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ /**
7
+ * Motor compartido con `refacil-sdd-ai migration-pending`, hooks `check-update` / `notify-update`
8
+ * y la skill `refacil:update`. Si ninguna condicion aplica, no hace falta migrar metodologia.
9
+ */
10
+ const REQUIRED_OPSX_CLAUDE = new Set([
11
+ 'apply.md',
12
+ 'archive.md',
13
+ 'explore.md',
14
+ 'propose.md',
15
+ 'verify.md',
16
+ ]);
17
+
18
+ const REQUIRED_OPSX_CURSOR = new Set([
19
+ 'opsx-apply.md',
20
+ 'opsx-archive.md',
21
+ 'opsx-explore.md',
22
+ 'opsx-propose.md',
23
+ 'opsx-verify.md',
24
+ ]);
25
+
26
+ function legacyIndexDoc(filePath) {
27
+ if (!fs.existsSync(filePath)) return false;
28
+ const content = fs.readFileSync(filePath, 'utf8');
29
+ const lines = content.split(/\r?\n/).length;
30
+ const pointsToAgents = /AGENTS\.md/i.test(content);
31
+ return lines > 5 || !pointsToAgents;
32
+ }
33
+
34
+ function collectExtraOpsxClaude(root) {
35
+ const dir = path.join(root, '.claude', 'commands', 'opsx');
36
+ if (!fs.existsSync(dir)) return [];
37
+ let names;
38
+ try {
39
+ names = fs.readdirSync(dir);
40
+ } catch (_) {
41
+ return [];
42
+ }
43
+ const extra = [];
44
+ for (const name of names) {
45
+ if (!name.endsWith('.md')) continue;
46
+ if (REQUIRED_OPSX_CLAUDE.has(name)) continue;
47
+ extra.push(path.join('.claude/commands/opsx', name));
48
+ }
49
+ return extra;
50
+ }
51
+
52
+ function collectExtraOpsxCursor(root) {
53
+ const dir = path.join(root, '.cursor', 'commands');
54
+ if (!fs.existsSync(dir)) return [];
55
+ let names;
56
+ try {
57
+ names = fs.readdirSync(dir);
58
+ } catch (_) {
59
+ return [];
60
+ }
61
+ const extra = [];
62
+ for (const name of names) {
63
+ if (!name.startsWith('opsx-') || !name.endsWith('.md')) continue;
64
+ if (REQUIRED_OPSX_CURSOR.has(name)) continue;
65
+ extra.push(path.join('.cursor/commands', name));
66
+ }
67
+ return extra;
68
+ }
69
+
70
+ /**
71
+ * @param {string} root - raíz del repo
72
+ * @returns {{ pending: boolean, reasons: string[] }}
73
+ */
74
+ function methodologyMigrationPending(root) {
75
+ const reasons = [];
76
+
77
+ const agentsMd = path.join(root, 'AGENTS.md');
78
+ const agentsDir = path.join(root, '.agents');
79
+ if (fs.existsSync(agentsMd) && !fs.existsSync(agentsDir)) {
80
+ reasons.push('AGENTS.md existe sin carpeta .agents/');
81
+ }
82
+
83
+ const claudeMd = path.join(root, 'CLAUDE.md');
84
+ if (legacyIndexDoc(claudeMd)) {
85
+ reasons.push('CLAUDE.md requiere normalización (índice mínimo → AGENTS.md)');
86
+ }
87
+
88
+ const cursorRules = path.join(root, '.cursorrules');
89
+ if (legacyIndexDoc(cursorRules)) {
90
+ reasons.push('.cursorrules requiere normalización (índice mínimo → AGENTS.md)');
91
+ }
92
+
93
+ const extraOpsx = [...collectExtraOpsxClaude(root), ...collectExtraOpsxCursor(root)];
94
+ if (extraOpsx.length) {
95
+ reasons.push(`commands opsx sobrantes: ${extraOpsx.join(', ')}`);
96
+ }
97
+
98
+ return { pending: reasons.length > 0, reasons };
99
+ }
100
+
101
+ module.exports = { methodologyMigrationPending };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "refacil-sdd-ai",
3
- "version": "4.2.4",
4
- "description": "SDD-AI: Specification-Driven Development with AI — metodologia de desarrollo con IA usando OpenSpec, Claude Code y Cursor",
3
+ "version": "4.4.0",
4
+ "description": "SDD-AI: Specification-Driven Development with AI — development methodology using AI with Claude Code and Cursor",
5
5
  "bin": {
6
6
  "refacil-sdd-ai": "./bin/cli.js"
7
7
  },
@@ -11,7 +11,6 @@
11
11
  "skills/",
12
12
  "agents/",
13
13
  "templates/",
14
- "config/",
15
14
  "README.md",
16
15
  "refacil-bus-diagrams.md"
17
16
  ],
@@ -19,7 +18,6 @@
19
18
  "ai",
20
19
  "development",
21
20
  "methodology",
22
- "openspec",
23
21
  "claude-code",
24
22
  "cursor",
25
23
  "sdd",
@@ -34,10 +32,10 @@
34
32
  "url": ""
35
33
  },
36
34
  "engines": {
37
- "node": ">=20.19.0"
35
+ "node": ">=20.0.0"
38
36
  },
39
37
  "scripts": {
40
- "test": "node --test test/hooks.test.js test/installer.test.js test/ignore-files.test.js test/methodology-migration-pending.test.js"
38
+ "test": "node --test test/hooks.test.js test/installer.test.js test/ignore-files.test.js test/methodology-migration-pending.test.js test/sdd.test.js test/refactor-integrar-openspec-nativo.test.js test/refactor-rutas-refacil-sdd.test.js test/refactor-agents-english.test.js test/remove-openspec-legacy.test.js"
41
39
  },
42
40
  "dependencies": {
43
41
  "ws": "^8.18.0"
@@ -1,120 +1,139 @@
1
- ---
2
- name: refacil:apply
3
- description: Implementar las tasks de un cambio propuestoverifica artefactos y rama de trabajo, construye un briefing estructurado y delega al sub-agente refacil-implementer para ejecutar la implementacion en contexto aislado
4
- user-invocable: true
5
- ---
6
-
7
- # refacil:apply — Entrypoint de Implementacion
8
-
9
- Este skill es un **wrapper** que verifica las precondiciones criticas (artefactos SDD y rama de trabajo), construye un **briefing estructurado** con el contexto clave ya extraido, y delega la implementacion al sub-agente `refacil-implementer`. El briefing evita que el sub-agente redescubra desde ceroarranca implementando, no explorando.
10
-
11
- **Prerequisitos**: perfil `openspec` de `refacil-prereqs/SKILL.md` + reglas de `METHODOLOGY-CONTRACT.md`.
12
-
13
- ## Flujo
14
-
15
- ### Paso 0: Verificar que existan artefactos SDD (bloqueante)
16
-
17
- Por cada carpeta bajo `openspec/changes/` (excluye `archive/` si aplica), comprueba:
18
-
19
- | Artefacto | Requisito |
20
- |-----------|-----------|
21
- | `proposal.md` | Obligatorio en la raiz del cambio |
22
- | `design.md` | Obligatorio en la raiz del cambio |
23
- | `tasks.md` | Obligatorio en la raiz del cambio |
24
- | **Especificacion** | **`specs.md` en la raiz** **O** al menos un `.md` bajo `specs/` del cambio (recursivo) |
25
-
26
- OpenSpec a veces solo genera el arbol `specs/**/*.md`; eso **cumple** la fila de especificacion. Ver `OPENSPEC-DELTAS.md` (seccion **Specs: archivo unico vs arbol**).
27
-
28
- - **Si `openspec/changes/` no existe o no hay cambios activos**: informa que ejecute `/refacil:propose` y **detente**.
29
-
30
- - **Si falta proposal, design o tasks**, o **no hay ni `specs.md` ni ningun `.md` bajo `specs/`**:
31
- ```
32
- El cambio en openspec/changes/[nombre]/ esta incompleto.
33
- Faltan: [lista]
34
- Ejecuta: /refacil:propose para completar los artefactos antes de implementar.
35
- ```
36
- **Detente.**
37
-
38
- - **Multiples cambios activos**: lista carpetas y pregunta cual implementar. No invoques al sub-agente con scope ambiguo.
39
-
40
- **IMPORTANTE**: Este comando NUNCA genera artefactos SDD. Si no existen, el usuario debe usar `/refacil:propose`.
41
-
42
- ### Paso 1: Validar rama de trabajo (bloqueante — antes de delegar)
43
-
44
- Ejecuta `git branch --show-current` para obtener la rama actual.
45
-
46
- Aplica la **Politica de ramas protegidas y creacion de rama** definida en `refacil-prereqs/METHODOLOGY-CONTRACT.md`.
47
-
48
- - **Si la rama actual es protegida**: ejecutar el protocolo completo de creacion de rama **antes de continuar**. No delegar al sub-agente hasta estar en una rama de trabajo.
49
- - Para `refacil:apply`, el prefijo sugerido de rama es `feature/`.
50
- - Si la rama actual ya es de trabajo (`feature/*`, `fix/*`, `hotfix/*`, `refactor/*`, etc.), continuar sin interrumpir.
51
- - Si el usuario no aprueba la creacion/cambio de rama, **detener**. No continuar con la implementacion.
52
-
53
- ### Paso 1.5: Construir briefing estructurado (reduce tool calls del sub-agente)
54
-
55
- Antes de invocar al sub-agente, extrae el contexto clave leyendo los artefactos. Esto evita que el sub-agente los redescubra desde cero.
56
-
57
- 1. **Objetivo** lee la primera seccion de `openspec/changes/<changeName>/proposal.md`. Extrae el objetivo en 1-2 oraciones.
58
- 2. **Scope de archivos** lee `openspec/changes/<changeName>/design.md`. Extrae:
59
- - Lista de archivos a **crear** (rutas completas)
60
- - Lista de archivos a **modificar** (rutas completas)
61
- 3. **Tasks** — lee `openspec/changes/<changeName>/tasks.md`. Extrae la lista numerada completa.
62
- 4. **Comando de test** lee `refacil-prereqs/METHODOLOGY-CONTRACT.md` §3. Extrae el comando exacto.
63
- 5. **Contexto de arquitectura** — lee `.agents/stack.md` si existe; si no, `.agents/architecture.md`; si no existe ninguno, lee solo las primeras 60 lineas de `AGENTS.md`. **No leas la carpeta completa `.agents/`**.
64
-
65
- Construye el bloque BRIEFING que incluiras literalmente en el prompt de delegacion:
66
-
67
- ```
68
- BRIEFING:
69
- changeName: <nombre>
70
- objective: <objetivo en 1-2 oraciones del proposal>
71
- scope:
72
- create: [ruta/archivo-nuevo-1.ts, ruta/archivo-nuevo-2.ts, ...]
73
- modify: [ruta/existente-1.ts, ruta/existente-2.ts, ...]
74
- doNotTouch: [openspec/, .claude/, .cursor/, AGENTS.md, package-lock.json]
75
- tasks:
76
- 1. <task 1>
77
- 2. <task 2>
78
- ...
79
- testCommand: <comando exacto>
80
- architectureContext: |
81
- <extracto de stack.md o primeras lineas de AGENTS.md>
82
- specsNote: <"specs.md" | "specs/**/*.md" | "ambos — reportar contradicciones en issues">
83
- ```
84
-
85
- ### Paso 2: Delegar al sub-agente refacil-implementer
86
-
87
- Invoca al sub-agente `refacil-implementer` pasandole el BRIEFING del paso anterior mas:
88
- - `changeName` (redundante con el briefing, pero lo necesita el guardrail)
89
- - Si el usuario pidio modo detallado, indicaselo. Default: conciso.
90
-
91
- El sub-agente usara el briefing como guia primaria y solo leera los archivos en `scope.modify` para entender interfaces existentes — no re-leera los artefactos ya extraidos.
92
-
93
- Retorna UN solo mensaje con el reporte + bloque JSON fenced como ` ```refacil-apply-result `.
94
-
95
- ### Paso 3: Presentar resultado y siguiente paso
96
-
97
- Muestra al usuario el **reporte** (todo lo anterior al bloque `refacil-apply-result`). No muestres el bloque JSON — es metadata interna.
98
-
99
- Despues del reporte agrega:
100
-
101
- ```
102
- El siguiente paso es generar/ajustar tests unitarios.
103
- Quieres que continue con /refacil:test?
104
- (Luego el flujo sigue con /refacil:verify)
105
- ```
106
-
107
- Si el sub-agente retorno `result: "PARCIAL"` o `"FALLO"`, presenta los `issues` al usuario y pide instrucciones antes de continuar.
108
-
109
- ## Reglas
110
-
111
- - NUNCA generar artefactos SDD desde este comando — eso es responsabilidad exclusiva de `/refacil:propose`.
112
- - Cumplir las precondiciones del Paso 0 (artefactos completos) y del Paso 1 (rama de trabajo valida) **antes de delegar**.
113
- - **Siempre construye el briefing (Paso 1.5) antes de delegar** — es la pieza clave que reduce el costo del sub-agente.
114
- - **Siempre delega la implementacion al sub-agente**. No repliques aqui la logica de implementacion ni de lectura de OpenSpec apply.
115
- - **No muestres el bloque JSON al usuario**. Es solo metadata interna.
116
- - **Continuidad del flujo**: si el usuario confirma afirmativamente ("si", "ok", "dale", "continua", etc.) la pregunta de continuidad del Paso 3, invocar inmediatamente el **Skill tool** con `skill: "refacil:test"`. No describirlo en texto ni esperar que el usuario escriba `/refacil:test`. (Ver `METHODOLOGY-CONTRACT.md §5`.)
117
-
118
- ## Ver tambien
119
-
120
- - Sub-agente: `.claude/agents/refacil-implementer.md` (fuente: `refacil-sdd-ai/agents/implementer.md`)
1
+ ---
2
+ name: refacil:apply
3
+ description: Implement the tasks of a proposed changeverifies artifacts and working branch, builds a structured briefing, and delegates to the refacil-implementer sub-agent to execute the implementation in isolated context
4
+ user-invocable: true
5
+ ---
6
+
7
+ # refacil:apply — Implementation Entrypoint
8
+
9
+ This skill is a **wrapper** that verifies the critical preconditions (SDD artifacts and working branch), builds a **structured briefing** with the key context already extracted, and delegates the implementation to the `refacil-implementer` sub-agent. The briefing prevents the sub-agent from rediscovering from scratch it starts implementing, not exploring.
10
+
11
+ **Prerequisites**: `sdd` profile from `refacil-prereqs/SKILL.md` + rules from `METHODOLOGY-CONTRACT.md`.
12
+
13
+ ## Flow
14
+
15
+ ### Step 0: Verify SDD artifacts exist (blocking)
16
+
17
+ Run `refacil-sdd-ai sdd list --json` to get the active changes.
18
+
19
+ - **If there are no active changes**: inform to run `/refacil:propose` and **stop**.
20
+ - **If there is a single active change**: use that `changeName`.
21
+ - **If there are multiple active changes**: list the names and ask which one to implement. Do not invoke the sub-agent with ambiguous scope.
22
+
23
+ With the selected `changeName`, run `refacil-sdd-ai sdd status <changeName> --json` and parse the JSON:
24
+
25
+ ```json
26
+ {
27
+ "name": "...",
28
+ "artifacts": { "proposal": bool, "design": bool, "tasks": bool, "specs": bool },
29
+ "tasks": { "total": N, "done": N, "pending": N },
30
+ "reviewPassed": bool,
31
+ "ready": { "forApply": bool, "forArchive": bool }
32
+ }
33
+ ```
34
+
35
+ Validations:
36
+ - If `artifacts.proposal` is `false` or `artifacts.tasks` is `false` or `artifacts.specs` is `false`:
37
+ ```
38
+ The change at refacil-sdd/changes/[name]/ is incomplete.
39
+ Missing: [list of artifacts with false]
40
+ Run: /refacil:propose to complete the artifacts before implementing.
41
+ ```
42
+ **Stop.**
43
+ - If `ready.forApply` is `false` for the same reason: same message above.
44
+
45
+ Note: `specs` is `true` if `specs.md` exists in the root **OR** at least one `.md` under the change's `specs/` folder.
46
+
47
+ **IMPORTANT**: This command NEVER generates SDD artifacts. If they do not exist, the user must use `/refacil:propose`.
48
+
49
+ ### Step 1: Validate working branch (blocking before delegating)
50
+
51
+ Run `git branch --show-current` to get the current branch.
52
+
53
+ Apply the **Protected branch policy and branch creation** defined in `refacil-prereqs/METHODOLOGY-CONTRACT.md`.
54
+
55
+ - **If the current branch is protected**: execute the full branch creation protocol **before continuing**. Do not delegate to the sub-agent until on a working branch.
56
+ - For `refacil:apply`, the suggested branch prefix is `feature/`.
57
+ - If the current branch is already a working branch (`feature/*`, `fix/*`, `hotfix/*`, `refactor/*`, etc.), continue without interruption.
58
+ - If the user does not approve the branch creation/change, **stop**. Do not continue with implementation.
59
+
60
+ ### Step 1.5: Build structured briefing (reduces sub-agent tool calls)
61
+
62
+ Before invoking the sub-agent, extract the key context by reading the artifacts. This prevents the sub-agent from rediscovering them from scratch.
63
+
64
+ 1. **Objective** — read the first section of `refacil-sdd/changes/<changeName>/proposal.md`. Extract the objective in 1-2 sentences.
65
+ 2. **File scope** read `refacil-sdd/changes/<changeName>/design.md`. Extract:
66
+ - List of files to **create** (full paths)
67
+ - List of files to **modify** (full paths)
68
+ 3. **Tasks** — read `refacil-sdd/changes/<changeName>/tasks.md`. Extract the full numbered list.
69
+ 4. **Test command** — read `refacil-prereqs/METHODOLOGY-CONTRACT.md` §3. Extract the exact command.
70
+ 5. **Architecture context** read `.agents/stack.md` if it exists; if not, `.agents/architecture.md`; if neither exists, read only the first 60 lines of `AGENTS.md`. **Do not read the entire `.agents/` folder**.
71
+
72
+ Build the BRIEFING block that you will include literally in the delegation prompt:
73
+
74
+ ```
75
+ BRIEFING:
76
+ changeName: <name>
77
+ objective: <objective in 1-2 sentences from the proposal>
78
+ scope:
79
+ create: [path/new-file-1.ts, path/new-file-2.ts, ...]
80
+ modify: [path/existing-1.ts, path/existing-2.ts, ...]
81
+ doNotTouch: [refacil-sdd/, .claude/, .cursor/, AGENTS.md, package-lock.json]
82
+ tasks:
83
+ 1. <task 1>
84
+ 2. <task 2>
85
+ ...
86
+ testCommand: <exact command>
87
+ architectureContext: |
88
+ <extract from stack.md or first lines of AGENTS.md>
89
+ specsNote: <"specs.md" | "specs/**/*.md" | "both report contradictions in issues">
90
+ ```
91
+
92
+ ### Step 2: Delegate to the refacil-implementer sub-agent
93
+
94
+ Invoke the `refacil-implementer` sub-agent passing it the BRIEFING from the previous step plus:
95
+ - `changeName` (redundant with the briefing, but the guardrail needs it)
96
+ - If the user requested detailed mode, indicate it. Default: concise.
97
+
98
+ The sub-agent will use the briefing as the primary guide and will only read the files in `scope.modify` to understand existing interfaces — it will not re-read the already-extracted artifacts.
99
+
100
+ Returns ONE single message with the report + JSON block fenced as ` ```refacil-apply-result `.
101
+
102
+ ### Step 2.5: Write memory.yaml (CA-16 — cross-skill state)
103
+
104
+ After parsing the `refacil-apply-result` block:
105
+ - Extract `touchedFiles` from the result (list of files actually created/modified by the implementer).
106
+ - Write or update `refacil-sdd/changes/<changeName>/memory.yaml` preserving any existing fields:
107
+
108
+ ```yaml
109
+ lastStep: apply
110
+ touchedFiles:
111
+ - path/file-1.ts
112
+ - path/file-2.ts
113
+ ```
114
+
115
+ If the file already exists, merge: update `lastStep` and `touchedFiles`; do not remove fields set by other steps (e.g. `commandsRun` from test).
116
+
117
+ If `result` is `"FAILED"`, skip the write and wait for user instructions.
118
+
119
+ ### Step 3: Present result and next step
120
+
121
+ Show the user the **report** (everything before the `refacil-apply-result` block). Do not show the JSON block — it is internal metadata.
122
+
123
+ After the report add:
124
+
125
+ ```
126
+ The next step is to generate/adjust unit tests.
127
+ Do you want me to continue with /refacil:test?
128
+ (The flow then continues with /refacil:verify)
129
+ ```
130
+
131
+ If the sub-agent returned `result: "PARTIAL"` or `"FAILED"`, present the `issues` to the user and ask for instructions before continuing.
132
+
133
+ ## Rules
134
+
135
+ - NEVER generate SDD artifacts from this command — that is exclusively `/refacil:propose`'s responsibility.
136
+ - Meet the preconditions of Step 0 (complete artifacts) and Step 1 (valid working branch) **before delegating**.
137
+ - **Always build the briefing (Step 1.5) before delegating** — it is the key piece that reduces the sub-agent cost.
138
+ - **Always delegate implementation to the sub-agent**. Do not replicate implementation logic or SDD artifact-apply logic here.
139
+ - **Flow continuity**: if the user confirms affirmatively ("yes", "ok", "go", "continue", etc.) the continuity question in Step 3, immediately invoke the **Skill tool** with `skill: "refacil:test"`. Do not describe it in text or wait for the user to type `/refacil:test`. (See `METHODOLOGY-CONTRACT.md §5`.)