kakaroto-config 1.0.0 → 1.0.2

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 (46) hide show
  1. package/README.md +122 -16
  2. package/bin/install.js +27 -5
  3. package/bin/release.js +255 -0
  4. package/config/ARCHITECTURE.md +3 -1
  5. package/config/CLAUDE.md +4 -0
  6. package/config/agents/memory-sync.md +87 -19
  7. package/config/agents/test-fixer.md +24 -0
  8. package/config/agents/visual-validator.md +17 -0
  9. package/config/commands/debug/01-reproduce.md +120 -0
  10. package/config/commands/debug/02-investigate.md +93 -0
  11. package/config/commands/debug/03-fix.md +110 -0
  12. package/config/commands/debug/04-verify.md +155 -0
  13. package/config/commands/debug/05-commit.md +106 -0
  14. package/config/commands/debug/06-evaluate.md +137 -0
  15. package/config/commands/debug/playbooks/api.md +21 -0
  16. package/config/commands/debug/playbooks/backend.md +19 -0
  17. package/config/commands/debug/playbooks/infra.md +130 -0
  18. package/config/commands/debug/playbooks/integration.md +16 -0
  19. package/config/commands/debug/playbooks/job.md +19 -0
  20. package/config/commands/debug/playbooks/test.md +14 -0
  21. package/config/commands/debug/playbooks/ui.md +24 -0
  22. package/config/commands/debug/self-healing.md +99 -0
  23. package/config/commands/debug/techniques/flow-tracing.md +75 -0
  24. package/config/commands/debug/techniques/hypothesis-generation.md +30 -0
  25. package/config/commands/debug/techniques/sequential-thinking-config.md +79 -0
  26. package/config/commands/debug/templates/diagnosis-script.md +72 -0
  27. package/config/commands/debug/templates/reproduction-doc.md +60 -0
  28. package/config/commands/debug/templates/root-cause-doc.md +46 -0
  29. package/config/commands/debug/validators/criticality-gate.md +40 -0
  30. package/config/commands/debug/validators/evidence-requirements.md +48 -0
  31. package/config/commands/debug/validators/fix-permanence.md +56 -0
  32. package/config/commands/debug/validators/root-cause-validation.md +50 -0
  33. package/config/commands/debug.md +3 -3
  34. package/config/commands/feature/01-interview.md +82 -90
  35. package/config/commands/feature/02-spec.md +22 -98
  36. package/config/commands/feature/03-planner.md +81 -4
  37. package/config/commands/feature/04-implement.md +15 -8
  38. package/config/commands/feature/05-quality.md +23 -5
  39. package/config/commands/feature/06-commit.md +91 -0
  40. package/config/commands/feature/07-evaluate.md +129 -0
  41. package/config/commands/feature.md +1 -7
  42. package/config/templates/spec-template.md +92 -0
  43. package/package.json +4 -1
  44. package/config/commands/debug/01-investigate.md +0 -119
  45. package/config/commands/debug/02-fix.md +0 -108
  46. package/config/commands/debug/03-verify.md +0 -66
package/README.md CHANGED
@@ -5,43 +5,149 @@ Claude Code configuration for autonomous development workflows.
5
5
  ## Quick Install
6
6
 
7
7
  ```bash
8
+ # Local installation (recommended - installs to ./.claude/)
8
9
  npx kakaroto-config
10
+
11
+ # Global installation (installs to ~/.claude/)
12
+ npx kakaroto-config --global
13
+ ```
14
+
15
+ **Local is recommended** because each project can have its own customizations while inheriting the global rules.
16
+
17
+ ## Updating
18
+
19
+ To update to the latest version, run the same command again:
20
+
21
+ ```bash
22
+ # Update local installation
23
+ npx kakaroto-config@latest
24
+
25
+ # Update global installation
26
+ npx kakaroto-config@latest --global
9
27
  ```
10
28
 
11
- This installs the configuration to `~/.claude/`.
29
+ The installer will detect the existing `.claude/` folder and ask if you want to overwrite.
12
30
 
13
- ## What's Included
31
+ > **Note:** If you previously installed globally (`~/.claude/`) and want to switch to local (`./.claude/`), just run `npx kakaroto-config@latest` in your project folder. Both can coexist - Claude Code will use local config when available.
14
32
 
15
- ### Skills (Commands)
33
+ ## What Gets Installed
16
34
 
17
- | Skill | Description |
18
- |-------|-------------|
19
- | `/feature` | Full feature development workflow (interview spec → plan → implement → quality) |
20
- | `/debug` | Bug resolution with 5 Whys methodology (investigate → fix → verify) |
21
- | `/gate` | Quality gate before PR (runs 7 validation agents) |
35
+ ```
36
+ .claude/
37
+ ├── CLAUDE.md # Global rules (autonomy, coding standards)
38
+ ├── ARCHITECTURE.md # Full documentation of the system
39
+ ├── commands/ # Skills (invoked via /skill)
40
+ │ ├── feature.md # /feature orchestrator
41
+ │ ├── feature/ # 5 phases: interview → spec → plan → implement → quality
42
+ │ ├── debug.md # /debug orchestrator
43
+ │ ├── debug/ # 5 phases: reproduce → investigate → fix → verify → commit
44
+ │ └── gate.md # /gate - quality gate before PR
45
+ └── agents/ # 7 specialized subagents
46
+ ├── test-fixer.md
47
+ ├── code-reviewer.md
48
+ ├── code-simplifier.md
49
+ ├── dry-enforcer.md
50
+ ├── visual-validator.md
51
+ ├── terraform-validator.md
52
+ └── memory-sync.md
53
+ ```
54
+
55
+ ## Skills (Commands)
56
+
57
+ | Skill | Trigger | Description |
58
+ |-------|---------|-------------|
59
+ | `/feature` | "adicionar", "implementar", "criar" | Full feature workflow with spec, planning, and quality gates |
60
+ | `/debug` | "bug", "erro", "problema" | Bug resolution with 5 Whys methodology |
61
+ | `/gate` | Manual | Run all 7 quality agents before PR |
22
62
 
23
- ### Agents (Subagents)
63
+ ## Agents (Subagents)
24
64
 
25
65
  | Agent | Purpose |
26
66
  |-------|---------|
27
67
  | `test-fixer` | Runs tests, fixes failures, creates missing tests |
28
68
  | `code-reviewer` | Reviews code quality, security, auto-fixes issues |
29
69
  | `code-simplifier` | Reduces complexity, improves readability |
30
- | `dry-enforcer` | Detects duplication, suggests reuse |
70
+ | `dry-enforcer` | Detects duplication, suggests code reuse |
31
71
  | `visual-validator` | Validates UI with Playwright |
32
72
  | `terraform-validator` | Validates env vars and Terraform consistency |
33
73
  | `memory-sync` | Syncs knowledge to MCP Memory |
34
74
 
35
75
  ## Philosophy
36
76
 
37
- - **FAZER, não perguntar** - Agents fix issues automatically
38
- - **BUSCAR, não pedir contexto** - Use MCP Memory and codebase exploration
39
- - **Código sem teste = PR rejeitado** - Tests are mandatory
40
- - **Erros: corrigir e continuar** - Don't stop on failures
77
+ The configuration enforces autonomous development:
78
+
79
+ | Principle | Meaning |
80
+ |-----------|---------|
81
+ | **FAZER, nao perguntar** | Agents fix issues automatically, don't ask for confirmation |
82
+ | **BUSCAR, nao pedir contexto** | Use MCP Memory and codebase exploration, don't ask user for context |
83
+ | **Codigo sem teste = PR rejeitado** | Tests are mandatory (blocking) |
84
+ | **Erros: corrigir e continuar** | Fix errors automatically, don't stop workflow |
85
+
86
+ ## After Installation
87
+
88
+ ### 1. Create Project CLAUDE.md (Optional but Recommended)
89
+
90
+ Create a `CLAUDE.md` in your project root with project-specific info:
91
+
92
+ ```markdown
93
+ # Project Name
94
+
95
+ ## Commands
96
+ - `npm run dev` - Start dev server
97
+ - `npm run build` - Build
98
+ - `npm run test` - Run tests
99
+
100
+ ## Structure
101
+ - `src/` - Source code
102
+ - `tests/` - Tests
103
+
104
+ ## MCP Memory Namespace
105
+ Prefix: `myproject:`
106
+ ```
107
+
108
+ ### 2. Add Custom Skills (Optional)
109
+
110
+ Create `.claude/commands/your-skill.md` for project-specific workflows.
111
+
112
+ ## Workflow Examples
113
+
114
+ ### Feature Development
115
+
116
+ ```
117
+ User: "adiciona filtro de data na listagem"
118
+
119
+ Claude automatically triggers /feature
120
+
121
+ 01-interview → Explores codebase, asks clarifying questions
122
+ 02-spec → Generates technical specification
123
+ 03-planner → Creates implementation plan (requires approval)
124
+ 04-implement → Writes code following spec and plan
125
+ 05-quality → Runs all 7 quality agents
126
+
127
+ Ready for PR
128
+ ```
129
+
130
+ ### Bug Resolution
131
+
132
+ ```
133
+ User: "erro ao salvar formulario"
134
+
135
+ Claude automatically triggers /debug
136
+
137
+ 01-reproduce → Reproduces the bug
138
+ 02-investigate → 5 Whys analysis with evidence
139
+ 03-fix → Minimal fix + mandatory test
140
+ 04-verify → Confirms fix works
141
+ 05-commit → Creates commit
142
+
143
+ Done
144
+ ```
41
145
 
42
- ## Documentation
146
+ ## Requirements
43
147
 
44
- After installation, read `~/.claude/ARCHITECTURE.md` for full documentation.
148
+ - Claude Code CLI
149
+ - MCP Memory server (optional, for knowledge persistence)
150
+ - Playwright MCP (optional, for visual validation)
45
151
 
46
152
  ## License
47
153
 
package/bin/install.js CHANGED
@@ -5,7 +5,26 @@ const path = require('path');
5
5
  const os = require('os');
6
6
  const readline = require('readline');
7
7
 
8
- const CLAUDE_DIR = path.join(os.homedir(), '.claude');
8
+ const args = process.argv.slice(2);
9
+ const isGlobal = args.includes('--global');
10
+ const showHelp = args.includes('--help') || args.includes('-h');
11
+
12
+ if (showHelp) {
13
+ console.log(`
14
+ Usage: npx kakaroto-config [options]
15
+
16
+ Options:
17
+ --global Install to ~/.claude/ (global, all projects)
18
+ --help, -h Show this help message
19
+
20
+ Default: Install to ./.claude/ (local, current project)
21
+ `);
22
+ process.exit(0);
23
+ }
24
+
25
+ const CLAUDE_DIR = isGlobal
26
+ ? path.join(os.homedir(), '.claude')
27
+ : path.join(process.cwd(), '.claude');
9
28
  const CONFIG_DIR = path.join(__dirname, '..', 'config');
10
29
 
11
30
  const rl = readline.createInterface({
@@ -52,9 +71,12 @@ function countFiles(dir) {
52
71
  }
53
72
 
54
73
  async function main() {
74
+ const targetPath = isGlobal ? '~/.claude/' : './.claude/ (local)';
75
+ const targetDisplay = isGlobal ? '~/.claude/' : '.claude/';
76
+
55
77
  console.log('\n🥋 kakaroto-config - Claude Code Configuration\n');
56
- console.log('This will install the following to ~/.claude/:');
57
- console.log(' - CLAUDE.md (global rules)');
78
+ console.log(`This will install the following to ${targetPath}:`);
79
+ console.log(' - CLAUDE.md (rules)');
58
80
  console.log(' - ARCHITECTURE.md (documentation)');
59
81
  console.log(' - commands/ (skills: /feature, /debug, /gate)');
60
82
  console.log(' - agents/ (7 specialized subagents)\n');
@@ -63,7 +85,7 @@ async function main() {
63
85
  console.log(`Total: ${fileCount} files\n`);
64
86
 
65
87
  if (fs.existsSync(CLAUDE_DIR)) {
66
- const answer = await question('~/.claude/ already exists. Overwrite? (y/N): ');
88
+ const answer = await question(`${targetDisplay} already exists. Overwrite? (y/N): `);
67
89
  if (answer.toLowerCase() !== 'y') {
68
90
  console.log('\nAborted. No changes made.');
69
91
  rl.close();
@@ -89,7 +111,7 @@ async function main() {
89
111
  console.log(' 2. Try /feature to create a new feature');
90
112
  console.log(' 3. Try /debug to fix a bug');
91
113
  console.log(' 4. Try /gate before creating a PR\n');
92
- console.log('Read ~/.claude/ARCHITECTURE.md for full documentation.\n');
114
+ console.log(`Read ${targetDisplay}ARCHITECTURE.md for full documentation.\n`);
93
115
  } catch (err) {
94
116
  console.error('Error during installation:', err.message);
95
117
  process.exit(1);
package/bin/release.js ADDED
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const os = require('os');
6
+ const readline = require('readline');
7
+ const { execFileSync } = require('child_process');
8
+
9
+ // Constants
10
+ const HOME_CLAUDE = path.join(os.homedir(), '.claude');
11
+ const PROJECT_ROOT = path.join(__dirname, '..');
12
+ const CONFIG_DIR = path.join(PROJECT_ROOT, 'config');
13
+ const PACKAGE_JSON = path.join(PROJECT_ROOT, 'package.json');
14
+
15
+ // Exclusions - personal files not to publish
16
+ const EXCLUDED_COMMANDS = ['audit-command', 'audit-command.md'];
17
+
18
+ // Semver validation regex
19
+ const SEMVER_REGEX = /^\d+\.\d+\.\d+$/;
20
+
21
+ // Readline interface
22
+ const rl = readline.createInterface({
23
+ input: process.stdin,
24
+ output: process.stdout
25
+ });
26
+
27
+ function question(prompt) {
28
+ return new Promise((resolve) => {
29
+ rl.question(prompt, resolve);
30
+ });
31
+ }
32
+
33
+ function cleanDir(dir) {
34
+ if (fs.existsSync(dir)) {
35
+ fs.rmSync(dir, { recursive: true, force: true });
36
+ }
37
+ }
38
+
39
+ function copyRecursive(src, dest, excludes = []) {
40
+ const stats = fs.statSync(src);
41
+
42
+ if (stats.isDirectory()) {
43
+ const baseName = path.basename(src);
44
+ if (excludes.includes(baseName)) {
45
+ return; // Skip excluded directories
46
+ }
47
+
48
+ if (!fs.existsSync(dest)) {
49
+ fs.mkdirSync(dest, { recursive: true });
50
+ }
51
+
52
+ const files = fs.readdirSync(src);
53
+ for (const file of files) {
54
+ if (excludes.includes(file)) {
55
+ continue; // Skip excluded files
56
+ }
57
+ copyRecursive(path.join(src, file), path.join(dest, file), excludes);
58
+ }
59
+ } else {
60
+ const baseName = path.basename(src);
61
+ if (excludes.includes(baseName)) {
62
+ return; // Skip excluded files
63
+ }
64
+ fs.copyFileSync(src, dest);
65
+ console.log(` + ${path.relative(CONFIG_DIR, dest)}`);
66
+ }
67
+ }
68
+
69
+ function bumpVersion(version) {
70
+ if (!SEMVER_REGEX.test(version)) {
71
+ throw new Error(`Invalid semver format: ${version}. Expected X.Y.Z`);
72
+ }
73
+ const parts = version.split('.');
74
+ parts[2] = String(parseInt(parts[2], 10) + 1);
75
+ return parts.join('.');
76
+ }
77
+
78
+ function execCommandSafe(executable, args, description) {
79
+ console.log(`\n${description}...`);
80
+ try {
81
+ execFileSync(executable, args, { cwd: PROJECT_ROOT, stdio: 'inherit' });
82
+ return true;
83
+ } catch (err) {
84
+ console.error(`Error: ${err.message}`);
85
+ return false;
86
+ }
87
+ }
88
+
89
+ function countFiles(dir, excludes = []) {
90
+ let count = 0;
91
+ if (!fs.existsSync(dir)) return 0;
92
+
93
+ const items = fs.readdirSync(dir);
94
+ for (const item of items) {
95
+ if (excludes.includes(item)) continue;
96
+
97
+ const fullPath = path.join(dir, item);
98
+ if (fs.statSync(fullPath).isDirectory()) {
99
+ count += countFiles(fullPath, excludes);
100
+ } else {
101
+ count++;
102
+ }
103
+ }
104
+ return count;
105
+ }
106
+
107
+ async function main() {
108
+ console.log('\n🥋 kakaroto-config - Release\n');
109
+
110
+ // Check ~/.claude exists
111
+ if (!fs.existsSync(HOME_CLAUDE)) {
112
+ console.error(`Error: ${HOME_CLAUDE} does not exist`);
113
+ rl.close();
114
+ process.exit(1);
115
+ }
116
+
117
+ // Read current version
118
+ let pkg;
119
+ try {
120
+ pkg = JSON.parse(fs.readFileSync(PACKAGE_JSON, 'utf8'));
121
+ } catch (err) {
122
+ console.error(`Error reading package.json: ${err.message}`);
123
+ rl.close();
124
+ process.exit(1);
125
+ }
126
+
127
+ const currentVersion = pkg.version;
128
+ let newVersion;
129
+ try {
130
+ newVersion = bumpVersion(currentVersion);
131
+ } catch (err) {
132
+ console.error(`Error: ${err.message}`);
133
+ rl.close();
134
+ process.exit(1);
135
+ }
136
+
137
+ // Count files to sync
138
+ const commandsCount = countFiles(path.join(HOME_CLAUDE, 'commands'), EXCLUDED_COMMANDS);
139
+ const agentsCount = countFiles(path.join(HOME_CLAUDE, 'agents'));
140
+ const templatesCount = countFiles(path.join(HOME_CLAUDE, 'templates'));
141
+ const totalFiles = commandsCount + agentsCount + templatesCount + 2; // +2 for CLAUDE.md and ARCHITECTURE.md
142
+
143
+ // Show preview
144
+ console.log('This will:');
145
+ console.log(` 1. Sync ${totalFiles} files from ~/.claude/ to config/`);
146
+ console.log(` - CLAUDE.md`);
147
+ console.log(` - ARCHITECTURE.md`);
148
+ console.log(` - commands/ (${commandsCount} files, excluding audit-command)`);
149
+ console.log(` - agents/ (${agentsCount} files)`);
150
+ console.log(` - templates/ (${templatesCount} files)`);
151
+ console.log(` 2. Bump version: ${currentVersion} → ${newVersion}`);
152
+ console.log(` 3. Git commit and push`);
153
+ console.log(` 4. Publish to npm\n`);
154
+
155
+ // Confirm
156
+ const answer = await question('Proceed with release? (Y/n): ');
157
+ if (answer.toLowerCase() === 'n') {
158
+ console.log('\nAborted. No changes made.');
159
+ rl.close();
160
+ process.exit(0);
161
+ }
162
+
163
+ console.log('\n--- Syncing files ---\n');
164
+
165
+ // Clean directories
166
+ cleanDir(path.join(CONFIG_DIR, 'commands'));
167
+ cleanDir(path.join(CONFIG_DIR, 'agents'));
168
+ cleanDir(path.join(CONFIG_DIR, 'templates'));
169
+
170
+ // Ensure config directory exists
171
+ if (!fs.existsSync(CONFIG_DIR)) {
172
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
173
+ }
174
+
175
+ // Copy files with existence check
176
+ const claudeMdPath = path.join(HOME_CLAUDE, 'CLAUDE.md');
177
+ if (fs.existsSync(claudeMdPath)) {
178
+ console.log('Copying CLAUDE.md...');
179
+ fs.copyFileSync(claudeMdPath, path.join(CONFIG_DIR, 'CLAUDE.md'));
180
+ console.log(' + CLAUDE.md');
181
+ } else {
182
+ console.warn('Warning: CLAUDE.md not found, skipping');
183
+ }
184
+
185
+ const archMdPath = path.join(HOME_CLAUDE, 'ARCHITECTURE.md');
186
+ if (fs.existsSync(archMdPath)) {
187
+ console.log('Copying ARCHITECTURE.md...');
188
+ fs.copyFileSync(archMdPath, path.join(CONFIG_DIR, 'ARCHITECTURE.md'));
189
+ console.log(' + ARCHITECTURE.md');
190
+ } else {
191
+ console.warn('Warning: ARCHITECTURE.md not found, skipping');
192
+ }
193
+
194
+ console.log('Copying commands/...');
195
+ copyRecursive(
196
+ path.join(HOME_CLAUDE, 'commands'),
197
+ path.join(CONFIG_DIR, 'commands'),
198
+ EXCLUDED_COMMANDS
199
+ );
200
+
201
+ console.log('Copying agents/...');
202
+ copyRecursive(
203
+ path.join(HOME_CLAUDE, 'agents'),
204
+ path.join(CONFIG_DIR, 'agents')
205
+ );
206
+
207
+ if (fs.existsSync(path.join(HOME_CLAUDE, 'templates'))) {
208
+ console.log('Copying templates/...');
209
+ copyRecursive(
210
+ path.join(HOME_CLAUDE, 'templates'),
211
+ path.join(CONFIG_DIR, 'templates')
212
+ );
213
+ }
214
+
215
+ // Update package.json
216
+ console.log('\n--- Updating version ---\n');
217
+ pkg.version = newVersion;
218
+ fs.writeFileSync(PACKAGE_JSON, JSON.stringify(pkg, null, 2) + '\n');
219
+ console.log(`Updated package.json: ${currentVersion} → ${newVersion}`);
220
+
221
+ // Git operations - use execCommandSafe for commands with user-derived values
222
+ if (!execCommandSafe('git', ['add', '.'], 'Staging changes')) {
223
+ rl.close();
224
+ process.exit(1);
225
+ }
226
+
227
+ // Use execCommandSafe to prevent command injection via newVersion
228
+ if (!execCommandSafe('git', ['commit', '-m', `release: v${newVersion}`], 'Creating commit')) {
229
+ rl.close();
230
+ process.exit(1);
231
+ }
232
+
233
+ if (!execCommandSafe('git', ['push'], 'Pushing to remote')) {
234
+ rl.close();
235
+ process.exit(1);
236
+ }
237
+
238
+ // npm publish
239
+ if (!execCommandSafe('npm', ['publish'], 'Publishing to npm')) {
240
+ rl.close();
241
+ process.exit(1);
242
+ }
243
+
244
+ console.log(`\n✅ Release complete! Published v${newVersion}\n`);
245
+ console.log('Users can update with:');
246
+ console.log(` npx kakaroto-config@${newVersion}\n`);
247
+
248
+ rl.close();
249
+ }
250
+
251
+ main().catch((err) => {
252
+ console.error(`Unexpected error: ${err.message}`);
253
+ rl.close();
254
+ process.exit(1);
255
+ });
@@ -132,7 +132,8 @@ projeto/.claude/
132
132
 
133
133
  ├── settings.json # Config do Claude Code
134
134
  ├── visual-validation.json # Routes para visual-validator (opcional)
135
- └── terraform-validation.json # Paths para terraform-validator (opcional)
135
+ ├── terraform-validation.json # Paths para terraform-validator (opcional)
136
+ └── debug-logs.json # Comandos para query de logs de producao (opcional)
136
137
  ```
137
138
 
138
139
  **Personalizacoes por projeto:**
@@ -142,6 +143,7 @@ projeto/.claude/
142
143
  | `commands/*.md` | Skills especificas (deploy, E2E, migrations) | Quando projeto tem workflows unicos |
143
144
  | `visual-validation.json` | Mapeia components → routes para teste | Projetos com UI complexa |
144
145
  | `terraform-validation.json` | Paths de env vars e terraform | Projetos com infra como codigo |
146
+ | `debug-logs.json` | Comandos para query de logs de producao | Projetos com logs em Cloud Logging, CloudWatch, etc. |
145
147
  | `settings.json` | Modelo default, permissoes, etc. | Config avancada |
146
148
 
147
149
  **CLAUDE.md do projeto deve conter:**
package/config/CLAUDE.md CHANGED
@@ -22,3 +22,7 @@ Exceções: config files, .d.ts, UI puro sem lógica.
22
22
  ## Memory
23
23
  Namespace: ver CLAUDE.md do projeto.
24
24
  Sincronizar via `memory-sync` ao final de workflows.
25
+
26
+ ## Auto-Avaliacao
27
+ Apos /feature e /debug: executar fase de avaliacao (07/06-evaluate).
28
+ Dual-loop sequential thinking: diagnostico → sintese → propor melhorias ao user.
@@ -15,14 +15,29 @@ Sincronizar conhecimento adquirido com MCP Memory apos desenvolvimento.
15
15
  2. `git diff --stat` para entender escopo das mudancas
16
16
  3. Identificar o prefixo do projeto via `mcp__memory__search_nodes({ query: "config" })`
17
17
 
18
- ## Fase 2: Verificar Entidades Existentes
18
+ ## Fase 2: Verificar Entidades Existentes + Garbage Collection
19
19
 
20
20
  1. `mcp__memory__read_graph()` para ver todas entidades do projeto
21
21
  2. Filtrar entidades pelo prefixo do projeto (ex: `sm:` para social-medias)
22
- 3. Para cada arquivo modificado/deletado:
22
+ 3. **CONTAR entidades do projeto atual**:
23
+ - Se > 50 entidades → executar Garbage Collection abaixo
24
+ - Se ≤ 50 → prosseguir normalmente
25
+
26
+ ### Garbage Collection (se > 50 entidades)
27
+
28
+ Identificar e REMOVER:
29
+
30
+ | Candidata | Critério | Ação |
31
+ |-----------|----------|------|
32
+ | Bugs | entityType === "bug" | DELETE todos |
33
+ | Outros projetos | nome não começa com prefixo atual | DELETE |
34
+ | Versões duplicadas | nome contém "-v2", "-v3" | MERGE em original, DELETE versão |
35
+ | Arquivos inexistentes | observation referencia arquivo deletado | DELETE se única referência |
36
+
37
+ 4. Para cada arquivo modificado/deletado:
23
38
  - Buscar entidades que o referenciam (grep no campo observations)
24
- - SE arquivo deletado -> marcar entidade para atualizacao
25
- - SE arquivo renomeado -> atualizar referencias
39
+ - SE arquivo deletado -> marcar entidade para atualização
40
+ - SE arquivo renomeado -> atualizar referências
26
41
  - SE comportamento mudou -> atualizar observations
27
42
 
28
43
  ## Fase 3: Atualizar Entidades Obsoletas
@@ -45,13 +60,15 @@ Avaliar o que foi desenvolvido e criar entidades conforme tabela:
45
60
 
46
61
  | Situacao | Namespace | Criar? |
47
62
  |----------|-----------|--------|
48
- | Padrao novo implementado | `{prefix}:pattern:{nome}` | SIM |
63
+ | Padrão novo implementado | `{prefix}:pattern:{nome}` | SIM |
49
64
  | Fluxo complexo entendido | `{prefix}:fluxo:{nome}` | SIM |
50
- | Bug nao-obvio resolvido | `{prefix}:bug:{nome}` | SIM |
51
- | Servico novo/modificado significativamente | `{prefix}:servico:{nome}` | SE significativo |
52
- | Tipo importante descoberto | `{prefix}:tipo:{nome}` | SE reutilizavel |
65
+ | Serviço novo/modificado significativamente | `{prefix}:servico:{nome}` | SE significativo |
66
+ | Tipo importante descoberto | `{prefix}:tipo:{nome}` | SE reutilizável |
53
67
  | Procedimento documentado | `{prefix}:procedimento:{nome}` | SIM |
54
- | Analise importante feita | `{prefix}:analise:{nome}` | SE referenciavel |
68
+ | Análise importante feita | `{prefix}:analise:{nome}` | SE referenciável |
69
+ | Config de projeto | `{prefix}:config:{nome}` | APENAS config:main |
70
+
71
+ **REMOVIDO**: `{prefix}:bug:{nome}` - bugs são efêmeros, fixes vão no código
55
72
 
56
73
  ### Criterio "Vale Salvar"
57
74
 
@@ -68,18 +85,34 @@ Avaliar o que foi desenvolvido e criar entidades conforme tabela:
68
85
  - Detalhes de implementacao que mudam frequentemente
69
86
  - Duplicatas de entidades existentes
70
87
 
88
+ ### Pre-Flight Check (OBRIGATÓRIO antes de criar)
89
+
90
+ Antes de `mcp__memory__create_entities`, verificar:
91
+
92
+ ```
93
+ [ ] Nome usa prefixo correto do projeto atual?
94
+ [ ] Nome está em kebab-case?
95
+ [ ] Não é um bug? (bugs não devem ser salvos)
96
+ [ ] Não existe entidade similar? (usar search_nodes)
97
+ [ ] Não é versão de entidade existente? (update, não create)
98
+ [ ] Máximo 10 observations?
99
+ [ ] Informação não é óbvia pelo código?
100
+ ```
101
+
102
+ Se QUALQUER check falhar → NÃO CRIAR
103
+
71
104
  ### Formato de Entidade
72
105
 
73
106
  ```javascript
74
107
  mcp__memory__create_entities({
75
108
  entities: [{
76
109
  name: "{prefix}:{tipo}:{nome-kebab-case}",
77
- entityType: "{tipo}", // pattern, bug, fluxo, servico, etc.
110
+ entityType: "{tipo}", // pattern, fluxo, servico, etc. (NUNCA bug)
78
111
  observations: [
79
- "Primeira linha: resumo do que e",
112
+ "Primeira linha: resumo do que é",
80
113
  "Segunda linha: arquivo principal: path/to/file.ts",
81
- "Demais linhas: detalhes relevantes",
82
- "Ultima linha: quando/por que foi criado"
114
+ "Demais linhas: detalhes relevantes (max 8 linhas adicionais)",
115
+ "Última linha: quando/por que foi criado"
83
116
  ]
84
117
  }]
85
118
  })
@@ -110,13 +143,48 @@ Ao final, reportar:
110
143
  - OU: Todas entidades ja estao atualizadas
111
144
  ```
112
145
 
113
- ## Regras
146
+ ## Regras OBRIGATÓRIAS
147
+
148
+ ### Namespace & Escopo
149
+
150
+ 1. **Prefixo obrigatório**: TODA entidade DEVE usar o prefixo do projeto atual
151
+ 2. **NUNCA criar entidades de outros projetos** (ex: `ga:`, `kk:` quando trabalhando em `sm:`)
152
+ 3. **Validar namespace**: Antes de criar, verificar se prefixo corresponde ao projeto
153
+
154
+ ### Controle de Tamanho
155
+
156
+ 4. **Max 10 observations por entidade**: Se precisar de mais, dividir em entidades relacionadas
157
+ 5. **Max 50 entidades por projeto**: Se ultrapassar, fazer garbage collection
158
+ 6. **Nomes kebab-case**: `sm:pattern:graceful-shutdown`, não `sm:pattern:GracefulShutdown`
159
+ 7. **Observations atômicas**: Uma informação por linha, fácil de deletar/atualizar
160
+
161
+ ### O que NÃO salvar
162
+
163
+ 8. **NUNCA salvar bugs como entidades** - bugs são efêmeros, fixes vão no código
164
+ - Exception: Bug recorrente que revela pattern arquitetural → salvar como `pattern:`
165
+ 9. **NUNCA criar versões** (v2, v3) - ATUALIZAR a entidade existente
166
+ 10. **NUNCA duplicar**: Buscar entidade similar antes de criar (`search_nodes`)
167
+ 11. **Minimalismo radical**: Na dúvida, NÃO salvar
168
+
169
+ ### Garbage Collection (executar se >50 entidades)
170
+
171
+ ```javascript
172
+ // Identificar candidatas a remoção:
173
+ // 1. Entidades que referenciam arquivos deletados
174
+ // 2. Entidades com >15 observations (muito verbosas)
175
+ // 3. Entidades com informação duplicada de outra
176
+ // 4. Bugs antigos (>30 dias)
177
+ ```
178
+
179
+ ### Anti-Patterns a EVITAR
114
180
 
115
- 1. **Prefixo obrigatorio**: Toda entidade deve usar o prefixo do projeto
116
- 2. **Nomes kebab-case**: `sm:bug:tiktok-media-id-vazio`, nao `sm:bug:TikTokMediaIdVazio`
117
- 3. **Observations atomicas**: Uma informacao por linha, facil de deletar/atualizar
118
- 4. **Nao duplicar**: Verificar se entidade similar ja existe antes de criar
119
- 5. **Minimalismo**: Na duvida, nao salvar. Menos entidades de qualidade > muitas entidades ruins
181
+ | Anti-Pattern | Exemplo | Correção |
182
+ |--------------|---------|----------|
183
+ | Bug como entidade | `sm:bug:login-error` | DELETE - fix está no código |
184
+ | Versões separadas | `sm:pattern:X-v2` | UPDATE `sm:pattern:X` |
185
+ | Cross-project | `ga:feature:Y` no sm: | DELETE - pertence a outro projeto |
186
+ | Observations demais | 17 observations | Condensar em 8-10 |
187
+ | Tipo duplicado | `pattern` + `padrao` | Usar apenas `pattern` |
120
188
 
121
189
  ---
122
190
 
@@ -58,6 +58,30 @@ npm run test
58
58
 
59
59
  ---
60
60
 
61
+ ## Step Extra: CRUD Smoke Test (SE nova entidade)
62
+
63
+ **Trigger:** Arquivo em `api/handlers/` com novo endpoint POST/PUT criado.
64
+
65
+ 1. Identificar endpoints novos:
66
+ ```bash
67
+ git diff --name-only HEAD~1 | grep 'api/handlers/'
68
+ ```
69
+
70
+ 2. Para cada arquivo de handler modificado:
71
+ - Buscar métodos POST/PUT/DELETE
72
+ - Construir payload de teste válido
73
+ - Executar request contra servidor local (se rodando)
74
+ - Verificar response 200/201
75
+
76
+ 3. Reportar:
77
+ - Endpoints testados
78
+ - Resultados (PASS/FAIL)
79
+ - Erros encontrados
80
+
81
+ **Nota:** Este step é condicional. Só executar se houver novos endpoints CRUD.
82
+
83
+ ---
84
+
61
85
  ## Test Creation Guidelines
62
86
 
63
87
  ### File Location