forjajs 1.2.0 → 1.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 (132) hide show
  1. package/.claude/settings.json +7 -7
  2. package/CHANGELOG.md +25 -0
  3. package/README.en.md +5 -0
  4. package/README.md +5 -0
  5. package/dist/bin/create-memory-nest-kit.d.ts +2 -0
  6. package/dist/bin/create-memory-nest-kit.js +110 -0
  7. package/dist/bin/forja.d.ts +13 -0
  8. package/dist/bin/forja.js +136 -0
  9. package/dist/bin/init-project.d.ts +2 -0
  10. package/dist/bin/init-project.js +516 -0
  11. package/dist/lib/audit.d.ts +67 -0
  12. package/dist/lib/audit.js +143 -0
  13. package/dist/lib/context-builder.d.ts +58 -0
  14. package/dist/lib/context-builder.js +233 -0
  15. package/dist/lib/core/checks.d.ts +91 -0
  16. package/dist/lib/core/checks.js +119 -0
  17. package/dist/lib/core/doc-graph.d.ts +60 -0
  18. package/dist/lib/core/doc-graph.js +235 -0
  19. package/dist/lib/core/health.d.ts +103 -0
  20. package/dist/lib/core/health.js +538 -0
  21. package/dist/lib/core/registry.d.ts +296 -0
  22. package/dist/lib/core/registry.js +317 -0
  23. package/dist/lib/core/release.d.ts +334 -0
  24. package/dist/lib/core/release.js +465 -0
  25. package/dist/lib/generators/memory-generator.d.ts +83 -0
  26. package/{lib → dist/lib}/generators/memory-generator.js +107 -178
  27. package/dist/lib/generators/nest-generator.d.ts +15 -0
  28. package/{lib → dist/lib}/generators/nest-generator.js +47 -71
  29. package/dist/lib/generators/readme-generator.d.ts +15 -0
  30. package/{lib → dist/lib}/generators/readme-generator.js +9 -14
  31. package/dist/lib/governance-report.d.ts +49 -0
  32. package/dist/lib/governance-report.js +170 -0
  33. package/dist/lib/templates/harness/code-intel.d.mts +2 -0
  34. package/dist/lib/templates/harness/code-intel.mjs +126 -0
  35. package/dist/lib/utils/file-helpers.d.ts +9 -0
  36. package/dist/lib/utils/file-helpers.js +34 -0
  37. package/dist/lib/validators/structure-validator.d.ts +48 -0
  38. package/dist/lib/validators/structure-validator.js +232 -0
  39. package/dist/lib/workspace.d.ts +40 -0
  40. package/dist/lib/workspace.js +174 -0
  41. package/dist/scripts/agent-harness.d.ts +2 -0
  42. package/dist/scripts/agent-harness.js +556 -0
  43. package/dist/scripts/agent-router.d.ts +30 -0
  44. package/dist/scripts/agent-router.js +208 -0
  45. package/dist/scripts/audit-query.d.ts +2 -0
  46. package/dist/scripts/audit-query.js +43 -0
  47. package/dist/scripts/audit-sync.d.ts +2 -0
  48. package/dist/scripts/audit-sync.js +19 -0
  49. package/dist/scripts/build-smart-context.d.ts +1 -0
  50. package/dist/scripts/build-smart-context.js +75 -0
  51. package/dist/scripts/check-standards.d.ts +1 -0
  52. package/dist/scripts/check-standards.js +87 -0
  53. package/dist/scripts/compress-memory.d.ts +16 -0
  54. package/dist/scripts/compress-memory.js +157 -0
  55. package/dist/scripts/compress-project-memory.d.ts +1 -0
  56. package/dist/scripts/compress-project-memory.js +48 -0
  57. package/dist/scripts/context-ops.d.ts +2 -0
  58. package/dist/scripts/context-ops.js +464 -0
  59. package/dist/scripts/dev.d.ts +96 -0
  60. package/dist/scripts/dev.js +312 -0
  61. package/dist/scripts/extract-global-knowledge.d.ts +1 -0
  62. package/dist/scripts/extract-global-knowledge.js +43 -0
  63. package/dist/scripts/generate-dashboard.d.ts +1 -0
  64. package/dist/scripts/generate-dashboard.js +48 -0
  65. package/dist/scripts/governance-dashboard.d.ts +2 -0
  66. package/dist/scripts/governance-dashboard.js +36 -0
  67. package/dist/scripts/hook-guard-paths.d.ts +17 -0
  68. package/dist/scripts/hook-guard-paths.js +68 -0
  69. package/dist/scripts/hook-post-edit.d.ts +20 -0
  70. package/dist/scripts/hook-post-edit.js +70 -0
  71. package/dist/scripts/hook-session-start.d.ts +17 -0
  72. package/dist/scripts/hook-session-start.js +108 -0
  73. package/dist/scripts/hook-user-prompt.d.ts +22 -0
  74. package/dist/scripts/hook-user-prompt.js +193 -0
  75. package/dist/scripts/memory-schema.d.ts +6 -0
  76. package/{scripts/memory-schema.mjs → dist/scripts/memory-schema.js} +27 -20
  77. package/dist/scripts/query-universal-memory.d.ts +1 -0
  78. package/dist/scripts/query-universal-memory.js +44 -0
  79. package/dist/scripts/release-check.d.ts +14 -0
  80. package/dist/scripts/release-check.js +48 -0
  81. package/dist/scripts/spec-cli.d.ts +29 -0
  82. package/dist/scripts/spec-cli.js +261 -0
  83. package/dist/scripts/sprint-manager.d.ts +1 -0
  84. package/dist/scripts/sprint-manager.js +187 -0
  85. package/dist/scripts/sync-universal-memory.d.ts +1 -0
  86. package/dist/scripts/sync-universal-memory.js +277 -0
  87. package/dist/scripts/token-benchmark.d.ts +20 -0
  88. package/dist/scripts/token-benchmark.js +181 -0
  89. package/dist/scripts/tools-doctor.d.ts +20 -0
  90. package/dist/scripts/tools-doctor.js +120 -0
  91. package/memory/90-decisions/0028-governanca-visivel.md +84 -0
  92. package/package.json +54 -56
  93. package/specs/governanca-visivel/plan.md +122 -0
  94. package/specs/governanca-visivel/spec.md +112 -0
  95. package/specs/governanca-visivel/tasks.md +60 -0
  96. package/specs/ts-migration/plan.md +24 -13
  97. package/bin/create-memory-nest-kit.js +0 -125
  98. package/bin/forja.mjs +0 -143
  99. package/bin/init-project.js +0 -612
  100. package/lib/context-builder.js +0 -257
  101. package/lib/core/checks.mjs +0 -155
  102. package/lib/core/doc-graph.mjs +0 -231
  103. package/lib/core/health.mjs +0 -577
  104. package/lib/core/registry.mjs +0 -312
  105. package/lib/core/release.mjs +0 -492
  106. package/lib/templates/harness/code-intel.mjs +0 -119
  107. package/lib/templates/harness/mcp.json +0 -10
  108. package/lib/utils/file-helpers.js +0 -40
  109. package/lib/validators/structure-validator.js +0 -253
  110. package/lib/workspace.mjs +0 -213
  111. package/scripts/agent-harness.mjs +0 -580
  112. package/scripts/agent-router.mjs +0 -189
  113. package/scripts/build-smart-context.js +0 -87
  114. package/scripts/check-standards.js +0 -98
  115. package/scripts/compress-memory.mjs +0 -198
  116. package/scripts/compress-project-memory.js +0 -58
  117. package/scripts/context-ops.mjs +0 -466
  118. package/scripts/dev.mjs +0 -349
  119. package/scripts/extract-global-knowledge.js +0 -52
  120. package/scripts/generate-dashboard.js +0 -59
  121. package/scripts/hook-guard-paths.mjs +0 -76
  122. package/scripts/hook-post-edit.mjs +0 -79
  123. package/scripts/hook-session-start.mjs +0 -104
  124. package/scripts/hook-user-prompt.mjs +0 -185
  125. package/scripts/pre-commit.sh +0 -102
  126. package/scripts/query-universal-memory.js +0 -50
  127. package/scripts/release-check.mjs +0 -56
  128. package/scripts/spec-cli.mjs +0 -261
  129. package/scripts/sprint-manager.js +0 -200
  130. package/scripts/sync-universal-memory.js +0 -286
  131. package/scripts/token-benchmark.mjs +0 -203
  132. package/scripts/tools-doctor.mjs +0 -132
@@ -1,189 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * agent-router — registra e consulta handoffs entre sub-agents.
4
- *
5
- * Schema (criado on-demand em universal.db):
6
- *
7
- * CREATE TABLE handoffs (
8
- * id INTEGER PRIMARY KEY AUTOINCREMENT,
9
- * created_at TEXT NOT NULL,
10
- * from_agent TEXT NOT NULL,
11
- * to_agent TEXT NOT NULL,
12
- * intent TEXT NOT NULL, -- implement|review|plan|research
13
- * context TEXT NOT NULL, -- paths, refs, links
14
- * acceptance TEXT NOT NULL, -- AC mensurável
15
- * constraints TEXT NOT NULL, -- limites
16
- * return_to TEXT NOT NULL, -- para onde devolver
17
- * spec_slug TEXT, -- specs/<slug> opcional
18
- * status TEXT DEFAULT 'open', -- open|in_progress|done|cancelled|archived
19
- * payload_json TEXT
20
- * );
21
- *
22
- * Uso:
23
- * agent-router append < handoff.json # lê JSON do stdin
24
- * agent-router append '{"from":"product",...}'
25
- * agent-router list [--open] [--to <agent>]
26
- * agent-router show <id>
27
- * agent-router done <id>
28
- * agent-router schema # imprime schema/migra
29
- */
30
-
31
- import fs from 'node:fs';
32
- import path from 'node:path';
33
- import process from 'node:process';
34
- import { fileURLToPath } from 'node:url';
35
- import Database from 'better-sqlite3';
36
- import { getDbPath, ensureSchema } from './memory-schema.mjs';
37
-
38
- const __filename = fileURLToPath(import.meta.url);
39
- const __dirname = path.dirname(__filename);
40
- const root = path.resolve(__dirname, '..');
41
- ensureSchema({ silent: true });
42
- const dbPath = getDbPath();
43
-
44
- const REQUIRED = ['from', 'to', 'intent', 'context', 'acceptance', 'constraints', 'return'];
45
- const VALID_AGENTS = ['orchestrator', 'context-engineer', 'sdd-architect', 'product', 'marketing', 'governance', 'worker', 'user'];
46
- const VALID_INTENTS = ['implement', 'review', 'plan', 'research', 'spec', 'route'];
47
- const BUSY_ATTEMPTS = 8;
48
- const BUSY_DELAY_MS = 150;
49
-
50
- function fail(msg, code = 1) {
51
- fs.writeSync(2, `[agent-router] ${msg}\n`);
52
- process.exit(code);
53
- }
54
-
55
- function openDb() {
56
- fs.mkdirSync(path.dirname(dbPath), { recursive: true });
57
- const db = new Database(dbPath, { timeout: 5000 });
58
- db.pragma('busy_timeout = 5000');
59
- db.pragma('journal_mode = WAL');
60
- withBusyRetry(() => db.exec(`
61
- CREATE TABLE IF NOT EXISTS handoffs (
62
- id INTEGER PRIMARY KEY AUTOINCREMENT,
63
- created_at TEXT NOT NULL,
64
- from_agent TEXT NOT NULL,
65
- to_agent TEXT NOT NULL,
66
- intent TEXT NOT NULL,
67
- context TEXT NOT NULL,
68
- acceptance TEXT NOT NULL,
69
- constraints TEXT NOT NULL,
70
- return_to TEXT NOT NULL,
71
- spec_slug TEXT,
72
- status TEXT DEFAULT 'open',
73
- payload_json TEXT
74
- );
75
- CREATE INDEX IF NOT EXISTS idx_handoffs_status ON handoffs(status);
76
- CREATE INDEX IF NOT EXISTS idx_handoffs_to ON handoffs(to_agent, status);
77
- `));
78
- return db;
79
- }
80
-
81
- function sleepSync(ms) {
82
- const buffer = new SharedArrayBuffer(4);
83
- const view = new Int32Array(buffer);
84
- Atomics.wait(view, 0, 0, ms);
85
- }
86
-
87
- function withBusyRetry(fn) {
88
- let lastError;
89
- for (let attempt = 1; attempt <= BUSY_ATTEMPTS; attempt++) {
90
- try { return fn(); }
91
- catch (err) {
92
- if (err?.code !== 'SQLITE_BUSY' && err?.code !== 'SQLITE_LOCKED') throw err;
93
- lastError = err;
94
- sleepSync(BUSY_DELAY_MS * attempt);
95
- }
96
- }
97
- throw lastError;
98
- }
99
-
100
- function readStdin() {
101
- return fs.readFileSync(0, 'utf8');
102
- }
103
-
104
- function parsePayload(raw) {
105
- let obj;
106
- try { obj = JSON.parse(raw); } catch (e) { fail(`JSON inválido: ${e.message}`); }
107
- for (const k of REQUIRED) {
108
- if (!obj[k] || typeof obj[k] !== 'string') fail(`campo obrigatório ausente ou inválido: ${k} (ADR-0005)`);
109
- }
110
- if (!VALID_AGENTS.includes(obj.from)) fail(`from inválido: ${obj.from}. Use um de: ${VALID_AGENTS.join(', ')}`);
111
- if (!VALID_AGENTS.includes(obj.to)) fail(`to inválido: ${obj.to}`);
112
- if (!VALID_INTENTS.includes(obj.intent)) fail(`intent inválido: ${obj.intent}. Use: ${VALID_INTENTS.join(', ')}`);
113
- return obj;
114
- }
115
-
116
- function cmdAppend(arg) {
117
- const raw = arg && arg !== '-' ? arg : readStdin();
118
- const h = parsePayload(raw);
119
- const db = openDb();
120
- const stmt = db.prepare(`
121
- INSERT INTO handoffs (created_at, from_agent, to_agent, intent, context, acceptance, constraints, return_to, spec_slug, payload_json)
122
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
123
- `);
124
- const result = withBusyRetry(() => stmt.run(
125
- new Date().toISOString(),
126
- h.from, h.to, h.intent,
127
- h.context, h.acceptance, h.constraints, h.return,
128
- h.spec_slug || null,
129
- JSON.stringify(h)
130
- ));
131
- console.log(JSON.stringify({ id: result.lastInsertRowid, status: 'open', from: h.from, to: h.to, intent: h.intent }));
132
- db.close();
133
- }
134
-
135
- function cmdList(args) {
136
- const db = openDb();
137
- const filters = [];
138
- const params = [];
139
- if (args.includes('--open')) filters.push("status = 'open'");
140
- const toIdx = args.indexOf('--to');
141
- if (toIdx >= 0 && args[toIdx + 1]) { filters.push('to_agent = ?'); params.push(args[toIdx + 1]); }
142
- const where = filters.length ? `WHERE ${filters.join(' AND ')}` : '';
143
- const rows = db.prepare(`SELECT id, created_at, from_agent, to_agent, intent, status, spec_slug FROM handoffs ${where} ORDER BY id DESC LIMIT 50`).all(...params);
144
- if (!rows.length) { console.log('(sem handoffs)'); db.close(); return; }
145
- for (const r of rows) {
146
- console.log(`#${r.id} [${r.status}] ${r.from_agent} → ${r.to_agent} (${r.intent}) ${r.spec_slug || ''} — ${r.created_at}`);
147
- }
148
- db.close();
149
- }
150
-
151
- function cmdShow(idArg) {
152
- const id = parseInt(idArg, 10);
153
- if (!id) fail('uso: agent-router show <id>');
154
- const db = openDb();
155
- const row = db.prepare('SELECT * FROM handoffs WHERE id = ?').get(id);
156
- if (!row) fail(`handoff ${id} não encontrado`);
157
- console.log(JSON.stringify(row, null, 2));
158
- db.close();
159
- }
160
-
161
- function cmdSetStatus(idArg, status) {
162
- const id = parseInt(idArg, 10);
163
- if (!id) fail(`uso: agent-router ${status} <id>`);
164
- const db = openDb();
165
- const r = withBusyRetry(() => db.prepare('UPDATE handoffs SET status = ? WHERE id = ?').run(status, id));
166
- if (!r.changes) fail(`handoff ${id} não encontrado`);
167
- fs.writeSync(1, `handoff #${id} → ${status}\n`);
168
- db.close();
169
- }
170
-
171
- function cmdSchema() {
172
- openDb().close();
173
- console.log(`✓ schema OK em ${dbPath}`);
174
- }
175
-
176
- const [, , subcmd, ...rest] = process.argv;
177
- switch (subcmd) {
178
- case 'append': cmdAppend(rest[0]); break;
179
- case 'list': cmdList(rest); break;
180
- case 'show': cmdShow(rest[0]); break;
181
- case 'done': cmdSetStatus(rest[0], 'done'); break;
182
- case 'in_progress': cmdSetStatus(rest[0], 'in_progress'); break;
183
- case 'cancel': cmdSetStatus(rest[0], 'cancelled'); break;
184
- case 'archive': cmdSetStatus(rest[0], 'archived'); break;
185
- case 'schema': cmdSchema(); break;
186
- default:
187
- console.log('Uso: agent-router <append|list|show|done|in_progress|cancel|archive|schema> [args]');
188
- process.exit(1);
189
- }
@@ -1,87 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import Database from 'better-sqlite3';
4
- import { getDbPath, ensureSchema } from './memory-schema.mjs';
5
- import { resolveProject, initWorkspace } from '../lib/workspace.mjs';
6
-
7
- initWorkspace();
8
- ensureSchema({ silent: true });
9
- const dbPath = getDbPath();
10
-
11
- const [project, taskKeyword = ''] = process.argv.slice(2);
12
-
13
- if (!project) {
14
- console.log('Uso: node scripts/build-smart-context.js <projeto> [keyword]');
15
- process.exit(0);
16
- }
17
-
18
- const db = new Database(dbPath, { readonly: true });
19
-
20
- function getSmartContext() {
21
- console.log(`🔍 Construindo contexto inteligente para: ${project} (Busca: ${taskKeyword || 'global'})...`);
22
-
23
- // 1. Pegar arquivos globais obrigatórios
24
- const globalNodes = db.prepare(`
25
- SELECT title, content, path FROM memory_nodes
26
- WHERE project_id IS NULL AND (path LIKE '%mission.md' OR path LIKE '%standards.md')
27
- `).all();
28
-
29
- // 2. Pegar arquivos do projeto por keyword ou gerais
30
- let projectNodes = [];
31
- if (taskKeyword) {
32
- projectNodes = db.prepare(`
33
- SELECT n.title, n.content, n.path
34
- FROM memory_nodes n
35
- JOIN projects p ON p.id = n.project_id
36
- JOIN search_idx s ON s.node_id = n.id
37
- WHERE p.name = ? AND search_idx MATCH ?
38
- LIMIT 10
39
- `).all(project, taskKeyword);
40
- }
41
-
42
- // 3. Pegar ADRs e Summaries recentes do projeto
43
- const metadata = db.prepare(`
44
- SELECT n.title, n.content, n.path
45
- FROM memory_nodes n
46
- JOIN projects p ON p.id = n.project_id
47
- WHERE p.name = ? AND (n.kind = 'adr' OR n.kind = 'summary' OR n.path LIKE '%vision.md')
48
- ORDER BY n.updated_at DESC LIMIT 5
49
- `).all(project);
50
-
51
- const designIndex = db.prepare(`
52
- SELECT n.title, n.content, n.path
53
- FROM memory_nodes n
54
- JOIN projects p ON p.id = n.project_id
55
- WHERE p.name = ? AND n.kind = 'design' AND n.path LIKE '%/design-md/INDEX.md'
56
- ORDER BY n.updated_at DESC LIMIT 1
57
- `).all(project);
58
-
59
- const allNodes = [...globalNodes, ...projectNodes, ...metadata, ...designIndex];
60
-
61
- let contextPack = `# SMART CONTEXT PACK: ${project.toUpperCase()}\n\n`;
62
- contextPack += `> Gerado em: ${new Date().toISOString()}\n`;
63
- contextPack += `> Keyword de Tarefa: ${taskKeyword || 'N/A'}\n\n`;
64
-
65
- const seen = new Set();
66
- for (const node of allNodes) {
67
- if (seen.has(node.path)) continue;
68
- seen.add(node.path);
69
- contextPack += `## FILE: ${node.path}\n\n${node.content}\n\n---\n\n`;
70
- }
71
-
72
- const outDir = path.join(resolveProject(project), '.context');
73
- if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
74
-
75
- const outFile = path.join(outDir, 'smart-context.md');
76
- fs.writeFileSync(outFile, contextPack, 'utf8');
77
-
78
- console.log(`✅ Contexto inteligente gerado: ${outFile} (${seen.size} arquivos incluídos).`);
79
- }
80
-
81
- try {
82
- getSmartContext();
83
- } catch (e) {
84
- console.error('Erro ao gerar contexto inteligente:', e.message);
85
- } finally {
86
- db.close();
87
- }
@@ -1,98 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import { resolveProject, getWorkspaceInfo, initWorkspace } from '../lib/workspace.mjs';
5
-
6
- const __filename = fileURLToPath(import.meta.url);
7
- const __dirname = path.dirname(__filename);
8
- const root = path.resolve(__dirname, '..');
9
-
10
- const [projectArg] = process.argv.slice(2);
11
-
12
- const project = projectArg || 'framework-root';
13
- let projectDir;
14
- if (projectArg) {
15
- initWorkspace();
16
- projectDir = resolveProject(projectArg);
17
- } else {
18
- projectDir = root;
19
- }
20
-
21
- const PROJECT_MANDATORY_FILES = [
22
- 'memory/00-global/mission.md',
23
- 'memory/10-product/vision.md',
24
- 'memory/20-architecture/scaling-patterns.md', // Criado pelo nosso init
25
- 'AGENTS.md',
26
- '.memoryrc.json'
27
- ];
28
-
29
- const ROOT_MANDATORY_FILES = [
30
- 'AGENTS.md',
31
- 'README.md',
32
- 'package.json',
33
- 'memory/00-global/mission.md',
34
- 'memory/40-delivery/backlog.md',
35
- 'memory/50-orchestration/gsd-harness.md',
36
- 'specs/README.md',
37
- ];
38
-
39
- function check() {
40
- if (!fs.existsSync(projectDir)) {
41
- console.error(`Projeto nao encontrado: ${projectArg}`);
42
- if (projectArg) {
43
- const info = getWorkspaceInfo();
44
- console.error(`Workspace ativo: ${info.root} (${info.source})`);
45
- console.error(`Diretorio esperado: ${resolveProject(projectArg)}`);
46
- }
47
- process.exit(1);
48
- }
49
-
50
- const mandatoryFiles = projectArg ? PROJECT_MANDATORY_FILES : ROOT_MANDATORY_FILES;
51
-
52
- console.log(`\nAnalisando aderencia aos padroes: ${project.toUpperCase()}...\n`);
53
- if (projectArg) {
54
- const info = getWorkspaceInfo();
55
- console.log(`Workspace: ${info.root} (${info.source})`);
56
- console.log(`Projeto: ${projectDir}\n`);
57
- }
58
-
59
- const results = [];
60
- let score = 0;
61
-
62
- for (const file of mandatoryFiles) {
63
- const exists = fs.existsSync(path.join(projectDir, file));
64
- if (exists) {
65
- const content = fs.readFileSync(path.join(projectDir, file), 'utf8');
66
- const isPlaceholder = content.length < 100 || content.includes('Descreva');
67
-
68
- results.push({
69
- file,
70
- status: isPlaceholder ? 'WARN Placeholder' : 'OK',
71
- weight: isPlaceholder ? 0.5 : 1
72
- });
73
- score += isPlaceholder ? 0.5 : 1;
74
- } else {
75
- results.push({ file, status: 'FAIL Faltando', weight: 0 });
76
- }
77
- }
78
-
79
- results.forEach(r => {
80
- console.log(`${r.status.padEnd(12)} | ${r.file}`);
81
- });
82
-
83
- const finalScore = (score / mandatoryFiles.length) * 100;
84
- console.log(`\nScore de Maturidade: ${finalScore.toFixed(0)}%`);
85
-
86
- if (finalScore < 70) {
87
- console.log('\nAlerta: o projeto precisa de mais documentacao de fundacao antes de escalar.');
88
- process.exit(1);
89
- } else {
90
- console.log('\nProjeto saudavel e pronto para execucao acelerada.');
91
- }
92
- }
93
-
94
- try {
95
- check();
96
- } catch (e) {
97
- console.error('Erro ao verificar padrões:', e.message);
98
- }
@@ -1,198 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Memory Vacuum - Comprime e limpa memória antiga do projeto
5
- *
6
- * Objetivo: Manter .memory/sqlite/ < 50MB removendo:
7
- * - Logs > 30 dias (moves para archive)
8
- * - Índices sem referência
9
- * - Cache expirado (TTL)
10
- *
11
- * Uso: npm run memory:vacuum
12
- */
13
-
14
- import fs from 'node:fs';
15
- import path from 'node:path';
16
- import Database from 'better-sqlite3';
17
- import { fileURLToPath } from 'node:url';
18
- import { getDbPath, ensureSchema } from './memory-schema.mjs';
19
-
20
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
21
- const root = path.resolve(__dirname, '..');
22
-
23
- // Configuração de defaults (pode ser sobrescrita por .memoryrc.json)
24
- const DEFAULT_CONFIG = {
25
- archiveAge: 30, // dias
26
- maxDbSize: 50, // MB
27
- cacheTtl: 7, // dias
28
- vacuumInterval: 86400000, // ms (1 dia)
29
- };
30
-
31
- function loadConfig() {
32
- const configPath = path.join(root, '.memoryrc.json');
33
- if (fs.existsSync(configPath)) {
34
- return JSON.parse(fs.readFileSync(configPath, 'utf8')).compression || {};
35
- }
36
- return {};
37
- }
38
-
39
- function getDbSize(dbPath) {
40
- if (!fs.existsSync(dbPath)) return 0;
41
- const stats = fs.statSync(dbPath);
42
- return stats.size / (1024 * 1024); // MB
43
- }
44
-
45
- function archiveOldLogs(dbPath, ageInDays) {
46
- console.log(`📦 Archiving logs older than ${ageInDays} days...`);
47
-
48
- const db = new Database(dbPath);
49
- const archiveDir = path.join(path.dirname(dbPath), 'archive');
50
-
51
- if (!fs.existsSync(archiveDir)) {
52
- fs.mkdirSync(archiveDir, { recursive: true });
53
- }
54
-
55
- try {
56
- // 1. Buscar runs antigos
57
- const cutoffDate = new Date();
58
- cutoffDate.setDate(cutoffDate.getDate() - ageInDays);
59
-
60
- const oldRuns = db
61
- .prepare(
62
- `
63
- SELECT id, project_id, completed_at, log_content
64
- FROM memory_runs
65
- WHERE completed_at < ?
66
- LIMIT 100
67
- `
68
- )
69
- .all(cutoffDate.toISOString());
70
-
71
- console.log(` Found ${oldRuns.length} old runs to archive`);
72
-
73
- // 2. Mover para arquivo
74
- let archived = 0;
75
- for (const run of oldRuns) {
76
- const filename = `run-${run.id}-${run.completed_at.split('T')[0]}.json`;
77
- const filepath = path.join(archiveDir, filename);
78
-
79
- fs.writeFileSync(filepath, JSON.stringify(run, null, 2), 'utf8');
80
-
81
- // 3. Deletar do DB
82
- db.prepare('DELETE FROM memory_runs WHERE id = ?').run(run.id);
83
- archived++;
84
- }
85
-
86
- console.log(` ✅ Archived ${archived} runs`);
87
-
88
- // 4. Cleanup de índices vazios
89
- const emptyNodes = db
90
- .prepare(
91
- `
92
- SELECT COUNT(*) as cnt FROM memory_nodes
93
- WHERE content IS NULL OR content = ''
94
- `
95
- )
96
- .get();
97
-
98
- if (emptyNodes.cnt > 0) {
99
- console.log(` 🗑️ Removing ${emptyNodes.cnt} empty nodes...`);
100
- db.prepare('DELETE FROM memory_nodes WHERE content IS NULL OR content = ""')
101
- .run();
102
- }
103
-
104
- db.exec('VACUUM;'); // Compactar DB
105
- console.log(` ✨ Database compacted`);
106
-
107
- db.close();
108
- } catch (e) {
109
- console.error(' ❌ Error archiving:', e.message);
110
- db.close();
111
- throw e;
112
- }
113
- }
114
-
115
- function cleanExpiredCache(cacheDir, ttlInDays) {
116
- console.log(`🧹 Cleaning expired cache (TTL: ${ttlInDays} days)...`);
117
-
118
- if (!fs.existsSync(cacheDir)) {
119
- console.log(' (No cache directory)');
120
- return 0;
121
- }
122
-
123
- const files = fs.readdirSync(cacheDir);
124
- const cutoffTime = Date.now() - ttlInDays * 86400000;
125
- let removed = 0;
126
-
127
- for (const file of files) {
128
- const filepath = path.join(cacheDir, file);
129
- const stats = fs.statSync(filepath);
130
-
131
- if (stats.mtimeMs < cutoffTime) {
132
- fs.unlinkSync(filepath);
133
- removed++;
134
- }
135
- }
136
-
137
- console.log(` ✅ Removed ${removed} expired cache files`);
138
- return removed;
139
- }
140
-
141
- function reportStats(dbPath, beforeSize) {
142
- const afterSize = getDbSize(dbPath);
143
- const saved = beforeSize - afterSize;
144
- const percent = ((saved / beforeSize) * 100).toFixed(1);
145
-
146
- console.log(`\n📊 Compression Report:`);
147
- console.log(` Before: ${beforeSize.toFixed(2)} MB`);
148
- console.log(` After: ${afterSize.toFixed(2)} MB`);
149
- console.log(` Saved: ${saved.toFixed(2)} MB (${percent}%)`);
150
-
151
- if (afterSize > DEFAULT_CONFIG.maxDbSize) {
152
- console.warn(
153
- ` ⚠️ Database still > ${DEFAULT_CONFIG.maxDbSize}MB. Consider manual cleanup.`
154
- );
155
- } else {
156
- console.log(` ✨ Database within limits (< ${DEFAULT_CONFIG.maxDbSize}MB)`);
157
- }
158
- }
159
-
160
- async function vacuum() {
161
- const config = { ...DEFAULT_CONFIG, ...loadConfig() };
162
- ensureSchema({ silent: true });
163
- const dbPath = getDbPath();
164
- const cacheDir = path.join(root, '.context', 'cache');
165
-
166
- console.log('🔧 Memory Vacuum - Compression & Cleanup');
167
- console.log(` Config: ${JSON.stringify(config)}\n`);
168
-
169
- if (!fs.existsSync(dbPath)) {
170
- console.log('⚠️ Database not found. Skipping.');
171
- return;
172
- }
173
-
174
- const beforeSize = getDbSize(dbPath);
175
-
176
- try {
177
- // 1. Archive old runs
178
- archiveOldLogs(dbPath, config.archiveAge);
179
-
180
- // 2. Clean cache
181
- cleanExpiredCache(cacheDir, config.cacheTtl);
182
-
183
- // 3. Report
184
- reportStats(dbPath, beforeSize);
185
-
186
- console.log('\n✅ Memory vacuum complete!');
187
- } catch (e) {
188
- console.error('❌ Vacuum failed:', e.message);
189
- process.exit(1);
190
- }
191
- }
192
-
193
- // Executar se chamado via CLI
194
- if (import.meta.url === `file://${process.argv[1]}`) {
195
- vacuum().catch(console.error);
196
- }
197
-
198
- export { vacuum, getDbSize, archiveOldLogs, cleanExpiredCache };
@@ -1,58 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import { resolveProject, initWorkspace } from '../lib/workspace.mjs';
5
-
6
- const __filename = fileURLToPath(import.meta.url);
7
- const __dirname = path.dirname(__filename);
8
-
9
- const [project] = process.argv.slice(2);
10
-
11
- if (!project) {
12
- console.log('Uso: node scripts/compress-project-memory.js <projeto>');
13
- process.exit(0);
14
- }
15
-
16
- initWorkspace();
17
- const projectDir = resolveProject(project);
18
- const handoffDir = path.join(projectDir, 'memory/50-orchestration/handoffs');
19
- const summaryFile = path.join(projectDir, 'memory/70-summaries/compressed-history.md');
20
-
21
- function compress() {
22
- if (!fs.existsSync(handoffDir)) return console.log('Sem handoffs para comprimir.');
23
-
24
- const files = fs.readdirSync(handoffDir).filter(f => f.endsWith('.md') && f !== 'README.md');
25
- if (files.length < 5) return console.log('Handoffs insuficientes para compressão significativa.');
26
-
27
- let compressedContent = `# Histórico Comprimido de Execução: ${project.toUpperCase()}\n\n`;
28
- compressedContent += `> Última compressão: ${new Date().toISOString()}\n\n`;
29
-
30
- for (const file of files) {
31
- const filePath = path.join(handoffDir, file);
32
- const content = fs.readFileSync(filePath, 'utf8');
33
-
34
- // Extrai apenas o Título e as Alterações para o resumo
35
- const titleMatch = content.match(/^## Titulo\n(.+)$/m) || content.match(/^# Handoff: (.+)$/m);
36
- const changesMatch = content.match(/## Alteracoes\n([\s\S]*?)(?=##|$)/);
37
-
38
- if (titleMatch) {
39
- compressedContent += `### ${titleMatch[1].trim()} (${file.split('_')[0]})\n`;
40
- if (changesMatch) {
41
- compressedContent += `${changesMatch[1].trim()}\n\n`;
42
- }
43
- }
44
-
45
- // Opcional: Arquivar ou deletar o handoff original após compressão
46
- // fs.unlinkSync(filePath);
47
- }
48
-
49
- fs.writeFileSync(summaryFile, compressedContent, 'utf8');
50
- console.log(`✅ Memória comprimida em: ${summaryFile}`);
51
- console.log(`📉 ${files.length} handoffs consolidados em um único arquivo de resumo.`);
52
- }
53
-
54
- try {
55
- compress();
56
- } catch (e) {
57
- console.error('Erro na compressão:', e.message);
58
- }